From e4da80a26c7df617a367c846519f8c42c9e0f00c Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 1 Nov 2019 13:42:41 +0700 Subject: [PATCH 001/267] adding tests for msc device --- test/project.yml | 1 + test/test/device/msc/test_msc_device.c | 247 +++++++++++++++++++++++++ test/test/device/usbd/test_usbd.c | 3 +- test/test/support/tusb_config.h | 10 +- 4 files changed, 255 insertions(+), 6 deletions(-) create mode 100644 test/test/device/msc/test_msc_device.c diff --git a/test/project.yml b/test/project.yml index 8ceaf63c..7350125a 100644 --- a/test/project.yml +++ b/test/project.yml @@ -7,6 +7,7 @@ :project: :use_exceptions: TRUE + :use_mocks: TRUE :use_test_preprocessor: TRUE :use_auxiliary_dependencies: TRUE :use_deep_dependencies: TRUE diff --git a/test/test/device/msc/test_msc_device.c b/test/test/device/msc/test_msc_device.c new file mode 100644 index 00000000..dd5e3fc9 --- /dev/null +++ b/test/test/device/msc/test_msc_device.c @@ -0,0 +1,247 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 hathach for Adafruit Industries + * + * 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 "unity.h" + +// Files to test +#include "tusb_fifo.h" +#include "tusb.h" +#include "usbd.h" +TEST_FILE("usbd_control.c") +TEST_FILE("msc_device.c") + +// Mock File +#include "mock_dcd.h" + +//--------------------------------------------------------------------+ +// MACRO TYPEDEF CONSTANT ENUM DECLARATION +//--------------------------------------------------------------------+ + +enum +{ + EDPT_CTRL_OUT = 0x00, + EDPT_CTRL_IN = 0x80, + + EDPT_MSC_OUT = 0x01, + EDPT_MSC_IN = 0x81, +}; + +uint8_t const rhport = 0; + +enum +{ + ITF_NUM_MSC, + ITF_NUM_TOTAL +}; + +uint8_t const data_desc_configuration[] = +{ + // Interface count, string index, total length, attribute, power in mA + TUD_CONFIG_DESCRIPTOR(ITF_NUM_TOTAL, 0, TUD_CONFIG_DESC_LEN, TUSB_DESC_CONFIG_ATT_REMOTE_WAKEUP, 100), + + // Interface number, string index, EP Out & EP In address, EP size + TUD_MSC_DESCRIPTOR(ITF_NUM_MSC, 0, EDPT_MSC_OUT, EDPT_MSC_IN, (CFG_TUSB_RHPORT0_MODE & OPT_MODE_HIGH_SPEED) ? 512 : 64), +}; + +tusb_control_request_t const request_set_configuration = +{ + .bmRequestType = 0x80, + .bRequest = TUSB_REQ_SET_CONFIGURATION, + .wValue = 0, + .wIndex = 0, + .wLength = 0 +}; + +uint8_t const* desc_configuration; + + +enum +{ + DISK_BLOCK_NUM = 16, // 8KB is the smallest size that windows allow to mount + DISK_BLOCK_SIZE = 512 +}; + +uint8_t msc_disk[DISK_BLOCK_NUM][DISK_BLOCK_SIZE]; + +// Invoked when received SCSI_CMD_INQUIRY +// Application fill vendor id, product id and revision with string up to 8, 16, 4 characters respectively +void tud_msc_inquiry_cb(uint8_t lun, uint8_t vendor_id[8], uint8_t product_id[16], uint8_t product_rev[4]) +{ + (void) lun; + + const char vid[] = "TinyUSB"; + const char pid[] = "Mass Storage"; + const char rev[] = "1.0"; + + memcpy(vendor_id , vid, strlen(vid)); + memcpy(product_id , pid, strlen(pid)); + memcpy(product_rev, rev, strlen(rev)); +} + +// Invoked when received Test Unit Ready command. +// return true allowing host to read/write this LUN e.g SD card inserted +bool tud_msc_test_unit_ready_cb(uint8_t lun) +{ + (void) lun; + + return true; // RAM disk is always ready +} + +// Invoked when received SCSI_CMD_READ_CAPACITY_10 and SCSI_CMD_READ_FORMAT_CAPACITY to determine the disk size +// Application update block count and block size +void tud_msc_capacity_cb(uint8_t lun, uint32_t* block_count, uint16_t* block_size) +{ + (void) lun; + + *block_count = DISK_BLOCK_NUM; + *block_size = DISK_BLOCK_SIZE; +} + +// Invoked when received Start Stop Unit command +// - Start = 0 : stopped power mode, if load_eject = 1 : unload disk storage +// - Start = 1 : active mode, if load_eject = 1 : load disk storage +bool tud_msc_start_stop_cb(uint8_t lun, uint8_t power_condition, bool start, bool load_eject) +{ + (void) lun; + (void) power_condition; + + return true; +} + +// Callback invoked when received READ10 command. +// Copy disk's data to buffer (up to bufsize) and return number of copied bytes. +int32_t tud_msc_read10_cb(uint8_t lun, uint32_t lba, uint32_t offset, void* buffer, uint32_t bufsize) +{ + (void) lun; + + uint8_t const* addr = msc_disk[lba] + offset; + memcpy(buffer, addr, bufsize); + + return bufsize; +} + +// Callback invoked when received WRITE10 command. +// Process data in buffer to disk's storage and return number of written bytes +int32_t tud_msc_write10_cb(uint8_t lun, uint32_t lba, uint32_t offset, uint8_t* buffer, uint32_t bufsize) +{ + (void) lun; + + uint8_t* addr = msc_disk[lba] + offset; + memcpy(addr, buffer, bufsize); + + return bufsize; +} + +// Callback invoked when received an SCSI command not in built-in list below +// - READ_CAPACITY10, READ_FORMAT_CAPACITY, INQUIRY, MODE_SENSE6, REQUEST_SENSE +// - READ10 and WRITE10 has their own callbacks +int32_t tud_msc_scsi_cb (uint8_t lun, uint8_t const scsi_cmd[16], void* buffer, uint16_t bufsize) +{ + // read10 & write10 has their own callback and MUST not be handled here + + void const* response = NULL; + uint16_t resplen = 0; + + // most scsi handled is input + bool in_xfer = true; + + switch (scsi_cmd[0]) + { + case SCSI_CMD_PREVENT_ALLOW_MEDIUM_REMOVAL: + // Host is about to read/write etc ... better not to disconnect disk + resplen = 0; + break; + + default: + // Set Sense = Invalid Command Operation + tud_msc_set_sense(lun, SCSI_SENSE_ILLEGAL_REQUEST, 0x20, 0x00); + + // negative means error -> tinyusb could stall and/or response with failed status + resplen = -1; + break; + } + + // return resplen must not larger than bufsize + if ( resplen > bufsize ) resplen = bufsize; + + if ( response && (resplen > 0) ) + { + if(in_xfer) + { + memcpy(buffer, response, resplen); + }else + { + // SCSI output + } + } + + return resplen; +} + +//--------------------------------------------------------------------+ +// +//--------------------------------------------------------------------+ +uint8_t const * tud_descriptor_device_cb(void) +{ + return NULL; +} + +uint8_t const * tud_descriptor_configuration_cb(uint8_t index) +{ + return desc_configuration; +} + +uint16_t const* tud_descriptor_string_cb(uint8_t index) +{ + return NULL; +} + +void setUp(void) +{ + dcd_int_disable_Ignore(); + dcd_int_enable_Ignore(); + + if ( !tusb_inited() ) + { + dcd_init_Expect(rhport); + tusb_init(); + } +} + +void tearDown(void) +{ +} + +//--------------------------------------------------------------------+ +// +//--------------------------------------------------------------------+ +void test_msc(void) +{ + desc_configuration = data_desc_configuration; + +// dcd_event_setup_received(rhport, (uint8_t*) &request_set_configuration, false); + + +// tud_task(); +} diff --git a/test/test/device/usbd/test_usbd.c b/test/test/device/usbd/test_usbd.c index d4b3f806..33021089 100644 --- a/test/test/device/usbd/test_usbd.c +++ b/test/test/device/usbd/test_usbd.c @@ -29,10 +29,10 @@ #include "tusb.h" #include "usbd.h" TEST_FILE("usbd_control.c") -//TEST_FILE("usb_descriptors.c") // Mock File #include "mock_dcd.h" +#include "mock_msc_device.h" //--------------------------------------------------------------------+ // MACRO TYPEDEF CONSTANT ENUM DECLARATION @@ -102,6 +102,7 @@ void setUp(void) if ( !tusb_inited() ) { + mscd_init_Expect(); dcd_init_Expect(rhport); tusb_init(); } diff --git a/test/test/support/tusb_config.h b/test/test/support/tusb_config.h index bfe5bf9e..b75b7667 100644 --- a/test/test/support/tusb_config.h +++ b/test/test/support/tusb_config.h @@ -73,11 +73,11 @@ #define CFG_TUD_ENDOINT0_SIZE 64 //------------- CLASS -------------// -#define CFG_TUD_CDC 0 -#define CFG_TUD_MSC 0 -#define CFG_TUD_HID 0 -#define CFG_TUD_MIDI 0 -#define CFG_TUD_VENDOR 0 +//#define CFG_TUD_CDC 0 +#define CFG_TUD_MSC 1 +//#define CFG_TUD_HID 0 +//#define CFG_TUD_MIDI 0 +//#define CFG_TUD_VENDOR 0 //------------- CDC -------------// From 774a9f63ab1c41b589fffa13b56e78bdfe121d96 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 1 Nov 2019 15:25:54 +0700 Subject: [PATCH 002/267] enable cmock ignore_arg --- test/project.yml | 1 + test/test/device/msc/test_msc_device.c | 62 ++++++++++---------------- 2 files changed, 25 insertions(+), 38 deletions(-) diff --git a/test/project.yml b/test/project.yml index 7350125a..a130569c 100644 --- a/test/project.yml +++ b/test/project.yml @@ -54,6 +54,7 @@ :enforce_strict_ordering: TRUE :plugins: - :ignore + - :ignore_arg - :callback - :array :treat_as: diff --git a/test/test/device/msc/test_msc_device.c b/test/test/device/msc/test_msc_device.c index dd5e3fc9..53febe96 100644 --- a/test/test/device/msc/test_msc_device.c +++ b/test/test/device/msc/test_msc_device.c @@ -55,10 +55,12 @@ enum ITF_NUM_TOTAL }; +#define CONFIG_TOTAL_LEN (TUD_CONFIG_DESC_LEN + TUD_MSC_DESC_LEN) + uint8_t const data_desc_configuration[] = { // Interface count, string index, total length, attribute, power in mA - TUD_CONFIG_DESCRIPTOR(ITF_NUM_TOTAL, 0, TUD_CONFIG_DESC_LEN, TUSB_DESC_CONFIG_ATT_REMOTE_WAKEUP, 100), + TUD_CONFIG_DESCRIPTOR(ITF_NUM_TOTAL, 0, CONFIG_TOTAL_LEN, TUSB_DESC_CONFIG_ATT_REMOTE_WAKEUP, 100), // Interface number, string index, EP Out & EP In address, EP size TUD_MSC_DESCRIPTOR(ITF_NUM_MSC, 0, EDPT_MSC_OUT, EDPT_MSC_IN, (CFG_TUSB_RHPORT0_MODE & OPT_MODE_HIGH_SPEED) ? 512 : 64), @@ -66,9 +68,9 @@ uint8_t const data_desc_configuration[] = tusb_control_request_t const request_set_configuration = { - .bmRequestType = 0x80, + .bmRequestType = 0x00, .bRequest = TUSB_REQ_SET_CONFIGURATION, - .wValue = 0, + .wValue = 1, .wIndex = 0, .wLength = 0 }; @@ -163,39 +165,6 @@ int32_t tud_msc_scsi_cb (uint8_t lun, uint8_t const scsi_cmd[16], void* buffer, void const* response = NULL; uint16_t resplen = 0; - // most scsi handled is input - bool in_xfer = true; - - switch (scsi_cmd[0]) - { - case SCSI_CMD_PREVENT_ALLOW_MEDIUM_REMOVAL: - // Host is about to read/write etc ... better not to disconnect disk - resplen = 0; - break; - - default: - // Set Sense = Invalid Command Operation - tud_msc_set_sense(lun, SCSI_SENSE_ILLEGAL_REQUEST, 0x20, 0x00); - - // negative means error -> tinyusb could stall and/or response with failed status - resplen = -1; - break; - } - - // return resplen must not larger than bufsize - if ( resplen > bufsize ) resplen = bufsize; - - if ( response && (resplen > 0) ) - { - if(in_xfer) - { - memcpy(buffer, response, resplen); - }else - { - // SCSI output - } - } - return resplen; } @@ -227,6 +196,9 @@ void setUp(void) dcd_init_Expect(rhport); tusb_init(); } + + dcd_event_bus_signal(rhport, DCD_EVENT_BUS_RESET, false); + tud_task(); } void tearDown(void) @@ -240,8 +212,22 @@ void test_msc(void) { desc_configuration = data_desc_configuration; -// dcd_event_setup_received(rhport, (uint8_t*) &request_set_configuration, false); + dcd_event_setup_received(rhport, (uint8_t*) &request_set_configuration, false); + dcd_set_config_Expect(rhport, 1); -// tud_task(); + uint8_t const* desc_ep = tu_desc_next(tu_desc_next(desc_configuration)); + + // open endpoints + dcd_edpt_open_ExpectAndReturn(rhport, desc_ep, true); + dcd_edpt_open_ExpectAndReturn(rhport, tu_desc_next(desc_ep), true); + + // queue endpoint out + dcd_edpt_xfer_ExpectAndReturn(rhport, EDPT_MSC_OUT, NULL, 31, true); + dcd_edpt_xfer_IgnoreArg_buffer(); // don't care buffer since it is msc device interal + + // control status + dcd_edpt_xfer_ExpectAndReturn(rhport, EDPT_CTRL_IN, NULL, 0, true); + + tud_task(); } From b25faa97c2881f6f759188a8e104f1d9f5c18999 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 1 Nov 2019 17:48:59 +0700 Subject: [PATCH 003/267] update ceedling to 0.29.0 --- test/vendor/ceedling/bin/ceedling | 133 +-- .../ceedling/lib/ceedling/cacheinator.rb | 11 +- .../lib/ceedling/cacheinator_helper.rb | 21 +- .../ceedling/lib/ceedling/configurator.rb | 9 +- .../lib/ceedling/configurator_builder.rb | 7 + .../vendor/ceedling/lib/ceedling/constants.rb | 2 +- .../ceedling/lib/ceedling/dependinator.rb | 23 +- .../vendor/ceedling/lib/ceedling/generator.rb | 9 +- .../lib/ceedling/generator_test_results.rb | 18 +- .../lib/ceedling/generator_test_runner.rb | 8 +- test/vendor/ceedling/lib/ceedling/objects.yml | 3 + .../ceedling/lib/ceedling/preprocessinator.rb | 3 +- .../preprocessinator_includes_handler.rb | 91 +- .../lib/ceedling/project_config_manager.rb | 13 +- .../ceedling/lib/ceedling/rules_tests.rake | 4 +- .../ceedling/lib/ceedling/stream_wrapper.rb | 10 +- .../ceedling/lib/ceedling/task_invoker.rb | 26 +- .../ceedling/lib/ceedling/tasks_base.rake | 1 - .../lib/ceedling/tasks_filesystem.rake | 5 +- .../ceedling/lib/ceedling/tasks_tests.rake | 7 +- .../ceedling/lib/ceedling/test_invoker.rb | 32 +- .../ceedling/lib/ceedling/tool_executor.rb | 10 +- test/vendor/ceedling/lib/ceedling/version.rb | 39 +- .../ceedling/plugins/command_hooks/README.md | 11 +- .../command_hooks/lib/command_hooks.rb | 27 +- test/vendor/ceedling/plugins/gcov/README.md | 75 +- .../ceedling/plugins/gcov/config/defaults.yml | 21 +- test/vendor/ceedling/plugins/gcov/gcov.rake | 66 +- test/vendor/ceedling/plugins/gcov/lib/gcov.rb | 13 +- .../plugins/gcov/lib/gcov_constants.rb | 3 +- .../lib/junit_tests_report.rb | 15 +- .../module_generator/lib/module_generator.rb | 25 +- .../module_generator/module_generator.rake | 18 +- .../xml_tests_report/lib/xml_tests_report.rb | 4 +- .../vendor/c_exception/lib/CException.h | 5 + .../ceedling/vendor/cmock/lib/cmock_config.rb | 10 +- .../vendor/cmock/lib/cmock_generator.rb | 18 +- .../lib/cmock_generator_plugin_callback.rb | 88 +- .../lib/cmock_generator_plugin_expect.rb | 7 +- .../cmock_generator_plugin_expect_any_args.rb | 47 +- .../lib/cmock_generator_plugin_ignore.rb | 2 +- .../cmock_generator_plugin_return_thru_ptr.rb | 8 +- .../vendor/cmock/lib/cmock_generator_utils.rb | 25 +- .../vendor/cmock/lib/cmock_header_parser.rb | 39 +- test/vendor/ceedling/vendor/cmock/src/cmock.c | 18 +- test/vendor/ceedling/vendor/cmock/src/cmock.h | 10 +- .../vendor/cmock/src/cmock_internals.h | 2 + .../vendor/unity/auto/colour_prompt.rb | 5 +- .../vendor/unity/auto/colour_reporter.rb | 2 +- .../vendor/unity/auto/generate_module.rb | 17 +- .../vendor/unity/auto/generate_test_runner.rb | 274 +++--- .../vendor/unity/auto/parse_output.rb | 61 +- .../vendor/unity/auto/stylize_as_junit.rb | 15 +- .../vendor/unity/auto/test_file_filter.rb | 4 +- .../vendor/unity/auto/unity_test_summary.py | 2 +- .../vendor/unity/auto/unity_test_summary.rb | 7 +- test/vendor/ceedling/vendor/unity/src/unity.c | 791 +++++++++++++++--- test/vendor/ceedling/vendor/unity/src/unity.h | 172 +++- .../vendor/unity/src/unity_internals.h | 306 ++++--- 59 files changed, 1962 insertions(+), 736 deletions(-) diff --git a/test/vendor/ceedling/bin/ceedling b/test/vendor/ceedling/bin/ceedling index 20943f66..fa099590 100644 --- a/test/vendor/ceedling/bin/ceedling +++ b/test/vendor/ceedling/bin/ceedling @@ -31,95 +31,111 @@ unless (project_found) include Thor::Actions desc "new PROJECT_NAME", "create a new ceedling project" - method_option :no_docs, :type => :boolean, :default => false, :desc => "No docs in vendor directory" - method_option :nodocs, :type => :boolean, :default => false - method_option :as_gem, :type => :boolean, :default => false, :desc => "Create the scaffold using Ceedling as a gem instead of filling in the vendor directory. Implies --no-docs." - method_option :asgem, :type => :boolean, :default => false - method_option :with_ignore, :type => :boolean, :default => false, :desc => "Create a gitignore file for ignoring ceedling generated files." - method_option :withignore, :type => :boolean, :default => false - method_option :no_configs, :type => :boolean, :default => false, :desc => "Don't install starter configuration files." + method_option :docs, :type => :boolean, :default => false, :desc => "Add docs in project vendor directory" + method_option :local, :type => :boolean, :default => false, :desc => "Create a copy of Ceedling in the project vendor directory" + method_option :gitignore, :type => :boolean, :default => false, :desc => "Create a gitignore file for ignoring ceedling generated files" + method_option :no_configs, :type => :boolean, :default => false, :desc => "Don't install starter configuration files" method_option :noconfigs, :type => :boolean, :default => false + + #deprecated: + method_option :no_docs, :type => :boolean, :default => false + method_option :nodocs, :type => :boolean, :default => false + method_option :as_gem, :type => :boolean, :default => false + method_option :asgem, :type => :boolean, :default => false + method_option :with_ignore, :type => :boolean, :default => false + method_option :withignore, :type => :boolean, :default => false def new(name, silent = false) copy_assets_and_create_structure(name, silent, false, options) end desc "upgrade PROJECT_NAME", "upgrade ceedling for a project (not req'd if gem used)" - method_option :no_docs, :type => :boolean, :default => false, :desc => "No docs in vendor directory" - method_option :nodocs, :type => :boolean, :default => false - method_option :no_configs, :type => :boolean, :default => true, :desc => "Don't install starter configuration files." + method_option :docs, :type => :boolean, :default => false, :desc => "Add docs in project vendor directory" + method_option :local, :type => :boolean, :default => false, :desc => "Create a copy of Ceedling in the project vendor directory" + method_option :no_configs, :type => :boolean, :default => false, :desc => "Don't install starter configuration files" method_option :noconfigs, :type => :boolean, :default => false + + #deprecated: + method_option :no_docs, :type => :boolean, :default => false + method_option :nodocs, :type => :boolean, :default => false def upgrade(name, silent = false) - copy_assets_and_create_structure(name, silent, true, options) + copy_assets_and_create_structure(name, silent, true, options || {:upgrade => true}) end no_commands do def copy_assets_and_create_structure(name, silent=false, force=false, options = {}) - no_docs = options[:no_docs] || options[:nodocs] || false - no_configs = options[:no_configs] || options[:noconfigs] || false - as_gem = options[:as_gem] || options[:asgem] || false - with_ignore = options[:with_ignore] || options[:withignore] || false + puts "WARNING: --no_docs deprecated. It is now the default. Specify -docs if you want docs installed." if (options[:no_docs] || options[:nodocs]) + puts "WARNING: --as_gem deprecated. It is now the default. Specify -local if you want ceedling installed to this project." if (options[:as_gem] || options[:asgem]) + puts "WARNING: --with_ignore deprecated. It is now called -gitignore" if (options[:with_ignore] || options[:with_ignore]) + + use_docs = options[:docs] || false + use_configs = !(options[:no_configs] || options[:noconfigs] || false) + use_gem = !(options[:local]) + use_ignore = options[:gitignore] || false + is_upgrade = options[:upgrade] || false ceedling_path = File.join(name, 'vendor', 'ceedling') source_path = File.join(name, 'src') test_path = File.join(name, 'test') test_support_path = File.join(name, 'test/support') - [source_path, test_path, test_support_path].each do |d| - FileUtils.mkdir_p d + # If it's not an upgrade, make sure we have the paths we expect + if (!is_upgrade) + [source_path, test_path, test_support_path].each do |d| + FileUtils.mkdir_p d + end end - unless as_gem + # Genarate gitkeep in test support path + FileUtils.touch(File.join(test_support_path, '.gitkeep')) + + # If documentation requested, create a place to dump them and do so + if use_docs + doc_path = File.join(ceedling_path, 'docs') + FileUtils.mkdir_p doc_path + + in_doc_path = lambda {|f| File.join(doc_path, f)} + + doc_files = [ + 'docs/CeedlingPacket.md', + 'vendor/c_exception/docs/CException.md', + 'vendor/cmock/docs/CMock_Summary.md', + 'vendor/unity/docs/UnityAssertionsCheatSheetSuitableforPrintingandPossiblyFraming.pdf', + 'vendor/unity/docs/UnityAssertionsReference.md', + 'vendor/unity/docs/UnityConfigurationGuide.md', + 'vendor/unity/docs/UnityGettingStartedGuide.md', + 'vendor/unity/docs/UnityHelperScriptsGuide.md', + 'vendor/unity/docs/ThrowTheSwitchCodingStandard.md', + ] + + doc_files.each do |f| + copy_file(f, in_doc_path.call(File.basename(f)), :force => force) + end + end + + # If installed locally to project, copy ceedling, unity, cmock, & supports to vendor + unless use_gem FileUtils.mkdir_p ceedling_path - unless no_docs - doc_path = File.join(ceedling_path, 'docs') - FileUtils.mkdir_p doc_path - - in_doc_path = lambda {|f| File.join(doc_path, f)} - - doc_files = [ - 'docs/CeedlingPacket.md', - 'vendor/c_exception/docs/CException.md', - 'vendor/cmock/docs/CMock_Summary.md', - 'vendor/unity/docs/UnityAssertionsCheatSheetSuitableforPrintingandPossiblyFraming.pdf', - 'vendor/unity/docs/UnityAssertionsReference.md', - 'vendor/unity/docs/UnityConfigurationGuide.md', - 'vendor/unity/docs/UnityGettingStartedGuide.md', - 'vendor/unity/docs/UnityHelperScriptsGuide.md', - 'vendor/unity/docs/ThrowTheSwitchCodingStandard.md', - ] - - doc_files.each do |f| - copy_file(f, in_doc_path.call(File.basename(f)), :force => force) - end - end - - folders = if as_gem - %w{plugins lib} - else - %w{plugins lib bin} - end - #copy full folders from ceedling gem into project - folders.map do |f| + %w{plugins lib bin}.map do |f| {:src => f, :dst => File.join(ceedling_path, f)} end.each do |f| directory(f[:src], f[:dst], :force => force) end + # mark ceedling as an executable + File.chmod(0755, File.join(ceedling_path, 'bin', 'ceedling')) unless is_windows? + #copy necessary subcomponents from ceedling gem into project sub_components = [ {:src => 'vendor/c_exception/lib/', :dst => 'vendor/c_exception/lib'}, - {:src => 'vendor/c_exception/release/', :dst => 'vendor/c_exception/release'}, {:src => 'vendor/cmock/config/', :dst => 'vendor/cmock/config'}, {:src => 'vendor/cmock/lib/', :dst => 'vendor/cmock/lib'}, - {:src => 'vendor/cmock/release/', :dst => 'vendor/cmock/release'}, {:src => 'vendor/cmock/src/', :dst => 'vendor/cmock/src'}, {:src => 'vendor/deep_merge/lib/', :dst => 'vendor/deep_merge/lib'}, {:src => 'vendor/diy/lib', :dst => 'vendor/diy/lib'}, {:src => 'vendor/unity/auto/', :dst => 'vendor/unity/auto'}, - {:src => 'vendor/unity/release/', :dst => 'vendor/unity/release'}, {:src => 'vendor/unity/src/', :dst => 'vendor/unity/src'}, ] @@ -128,8 +144,9 @@ unless (project_found) end end - unless (no_configs) - if as_gem + # We're copying in a configuration file if we haven't said not to + if (use_configs) + if use_gem copy_file(File.join('assets', 'project_as_gem.yml'), File.join(name, 'project.yml'), :force => force) else copy_file(File.join('assets', 'project_with_guts.yml'), File.join(name, 'project.yml'), :force => force) @@ -137,18 +154,20 @@ unless (project_found) copy_file(File.join('assets', 'ceedling.cmd'), File.join(name, 'ceedling.cmd'), :force => force) else copy_file(File.join('assets', 'ceedling'), File.join(name, 'ceedling'), :force => force) + File.chmod(0755, File.join(name, 'ceedling')) end end end - if (with_ignore) + # Copy the gitignore file if requested + if (use_ignore) copy_file(File.join('assets', 'default_gitignore'), File.join(name, '.gitignore'), :force => force) end unless silent puts "\n" puts "Project '#{name}' #{force ? "upgraded" : "created"}!" - puts " - Tool documentation is located in vendor/ceedling/docs" if (not no_docs) and (not as_gem) + puts " - Tool documentation is located in vendor/ceedling/docs" if use_docs puts " - Execute 'ceedling help' to view available test & build tasks" puts '' end @@ -167,7 +186,7 @@ unless (project_found) def example(proj_name, dest=nil) if dest.nil? then dest = proj_name end - invoke :new, [dest, true] + copy_assets_and_create_structure(dest, true, false, {:local=>true, :docs=>true}) dest_src = File.join(dest,'src') dest_test = File.join(dest,'test') @@ -266,6 +285,8 @@ else abort when /^help$/ options[:list_tasks] = true + when /^-T$/ + options[:list_tasks] = true when /^project:(\w+)/ ENV['CEEDLING_USER_PROJECT_FILE'] = "#{$1}.yml" else diff --git a/test/vendor/ceedling/lib/ceedling/cacheinator.rb b/test/vendor/ceedling/lib/ceedling/cacheinator.rb index 47953dd9..519a4aab 100644 --- a/test/vendor/ceedling/lib/ceedling/cacheinator.rb +++ b/test/vendor/ceedling/lib/ceedling/cacheinator.rb @@ -26,16 +26,21 @@ class Cacheinator return cached_filepath end - def diff_cached_test_config?(hash) cached_filepath = @file_path_utils.form_test_build_cache_path(INPUT_CONFIGURATION_CACHE_FILE) - + return @cacheinator_helper.diff_cached_config?( cached_filepath, hash ) end + def diff_cached_test_defines?(files) + cached_filepath = @file_path_utils.form_test_build_cache_path(DEFINES_DEPENDENCY_CACHE_FILE) + + return @cacheinator_helper.diff_cached_defines?( cached_filepath, files ) + end + def diff_cached_release_config?(hash) cached_filepath = @file_path_utils.form_release_build_cache_path(INPUT_CONFIGURATION_CACHE_FILE) - + return @cacheinator_helper.diff_cached_config?( cached_filepath, hash ) end diff --git a/test/vendor/ceedling/lib/ceedling/cacheinator_helper.rb b/test/vendor/ceedling/lib/ceedling/cacheinator_helper.rb index cb0ef781..2a161854 100644 --- a/test/vendor/ceedling/lib/ceedling/cacheinator_helper.rb +++ b/test/vendor/ceedling/lib/ceedling/cacheinator_helper.rb @@ -8,5 +8,24 @@ class CacheinatorHelper return true if ( (@file_wrapper.exist?(cached_filepath)) and (!(@yaml_wrapper.load(cached_filepath) == hash)) ) return false end - + + def diff_cached_defines?(cached_filepath, files) + current_defines = COLLECTION_DEFINES_TEST_AND_VENDOR.reject(&:empty?) + + current_dependency = Hash[files.collect { |source| [source, current_defines.dup] }] + if not @file_wrapper.exist?(cached_filepath) + @yaml_wrapper.dump(cached_filepath, current_dependency) + return false + end + + dependencies = @yaml_wrapper.load(cached_filepath) + if dependencies.values_at(*current_dependency.keys) != current_dependency.values + dependencies.merge!(current_dependency) + @yaml_wrapper.dump(cached_filepath, dependencies) + return true + end + + return false + end + end diff --git a/test/vendor/ceedling/lib/ceedling/configurator.rb b/test/vendor/ceedling/lib/ceedling/configurator.rb index 672609b3..b5ad8982 100644 --- a/test/vendor/ceedling/lib/ceedling/configurator.rb +++ b/test/vendor/ceedling/lib/ceedling/configurator.rb @@ -64,6 +64,8 @@ class Configurator end + # The default values defined in defaults.rb (eg. DEFAULT_TOOLS_TEST) are populated + # into @param config def populate_defaults(config) new_config = DEFAULT_CEEDLING_CONFIG.deep_clone new_config.deep_merge!(config) @@ -184,7 +186,8 @@ class Configurator plugin_defaults = @configurator_plugins.find_plugin_defaults(config, paths_hash) config_plugins.each do |plugin| - config.deep_merge!( @yaml_wrapper.load(plugin) ) + plugin_config = @yaml_wrapper.load(plugin) + config.deep_merge(plugin_config) end plugin_defaults.each do |defaults| @@ -346,6 +349,10 @@ class Configurator end def eval_path_list( paths ) + if paths.kind_of?(Array) + paths = Array.new(paths) + end + paths.flatten.each do |path| path.replace( @system_wrapper.module_eval( path ) ) if (path =~ RUBY_STRING_REPLACEMENT_PATTERN) end diff --git a/test/vendor/ceedling/lib/ceedling/configurator_builder.rb b/test/vendor/ceedling/lib/ceedling/configurator_builder.rb index cd7d3eb8..da8a816f 100644 --- a/test/vendor/ceedling/lib/ceedling/configurator_builder.rb +++ b/test/vendor/ceedling/lib/ceedling/configurator_builder.rb @@ -274,10 +274,17 @@ class ConfiguratorBuilder return {:collection_all_assembly => all_assembly} if ((not in_hash[:release_build_use_assembly]) && (not in_hash[:test_build_use_assembly])) + # Sprinkle in all assembly files we can find in the source folders in_hash[:collection_paths_source].each do |path| all_assembly.include( File.join(path, "*#{in_hash[:extension_assembly]}") ) end + # Also add all assembly files we can find in the support folders + in_hash[:collection_paths_support].each do |path| + all_assembly.include( File.join(path, "*#{in_hash[:extension_assembly]}") ) + end + + # Also add files that we are explicitly adding via :files:assembly: section @file_system_utils.revise_file_list( all_assembly, in_hash[:files_assembly] ) return {:collection_all_assembly => all_assembly} diff --git a/test/vendor/ceedling/lib/ceedling/constants.rb b/test/vendor/ceedling/lib/ceedling/constants.rb index 5df68368..993ce8db 100644 --- a/test/vendor/ceedling/lib/ceedling/constants.rb +++ b/test/vendor/ceedling/lib/ceedling/constants.rb @@ -63,7 +63,7 @@ DEFAULT_CEEDLING_MAIN_PROJECT_FILE = 'project.yml' unless defined?(DEFAULT_CEEDL DEFAULT_CEEDLING_USER_PROJECT_FILE = 'user.yml' unless defined?(DEFAULT_CEEDLING_USER_PROJECT_FILE) # supplemental user config file INPUT_CONFIGURATION_CACHE_FILE = 'input.yml' unless defined?(INPUT_CONFIGURATION_CACHE_FILE) # input configuration file dump - +DEFINES_DEPENDENCY_CACHE_FILE = 'defines_dependency.yml' unless defined?(DEFINES_DEPENDENCY_CACHE_FILE) # preprocessor definitions for files TEST_ROOT_NAME = 'test' unless defined?(TEST_ROOT_NAME) TEST_TASK_ROOT = TEST_ROOT_NAME + ':' unless defined?(TEST_TASK_ROOT) diff --git a/test/vendor/ceedling/lib/ceedling/dependinator.rb b/test/vendor/ceedling/lib/ceedling/dependinator.rb index dd6b9273..ebd12377 100644 --- a/test/vendor/ceedling/lib/ceedling/dependinator.rb +++ b/test/vendor/ceedling/lib/ceedling/dependinator.rb @@ -38,20 +38,23 @@ class Dependinator def enhance_runner_dependencies(runner_filepath) - @rake_wrapper[runner_filepath].enhance( [@configurator.project_test_force_rebuild_filepath] ) if (@project_config_manager.test_config_changed) + @rake_wrapper[runner_filepath].enhance( [@configurator.project_test_force_rebuild_filepath] ) if (@project_config_manager.test_config_changed || + @project_config_manager.test_defines_changed) end def enhance_shallow_include_lists_dependencies(include_lists) include_lists.each do |include_list_filepath| - @rake_wrapper[include_list_filepath].enhance( [@configurator.project_test_force_rebuild_filepath] ) if (@project_config_manager.test_config_changed) + @rake_wrapper[include_list_filepath].enhance( [@configurator.project_test_force_rebuild_filepath] ) if (@project_config_manager.test_config_changed || + @project_config_manager.test_defines_changed) end end def enhance_preprocesed_file_dependencies(files) files.each do |filepath| - @rake_wrapper[filepath].enhance( [@configurator.project_test_force_rebuild_filepath] ) if (@project_config_manager.test_config_changed) + @rake_wrapper[filepath].enhance( [@configurator.project_test_force_rebuild_filepath] ) if (@project_config_manager.test_config_changed || + @project_config_manager.test_defines_changed) end end @@ -59,7 +62,8 @@ class Dependinator def enhance_mock_dependencies(mocks_list) # if input configuration or ceedling changes, make sure these guys get rebuilt mocks_list.each do |mock_filepath| - @rake_wrapper[mock_filepath].enhance( [@configurator.project_test_force_rebuild_filepath] ) if (@project_config_manager.test_config_changed) + @rake_wrapper[mock_filepath].enhance( [@configurator.project_test_force_rebuild_filepath] ) if (@project_config_manager.test_config_changed || + @project_config_manager.test_defines_changed) @rake_wrapper[mock_filepath].enhance( @configurator.cmock_unity_helper ) if (@configurator.cmock_unity_helper) end end @@ -67,25 +71,28 @@ class Dependinator def enhance_dependencies_dependencies(dependencies) dependencies.each do |dependencies_filepath| - @rake_wrapper[dependencies_filepath].enhance( [@configurator.project_test_force_rebuild_filepath] ) if (@project_config_manager.test_config_changed) + @rake_wrapper[dependencies_filepath].enhance( [@configurator.project_test_force_rebuild_filepath] ) if (@project_config_manager.test_config_changed || + @project_config_manager.test_defines_changed) end end def enhance_test_build_object_dependencies(objects) objects.each do |object_filepath| - @rake_wrapper[object_filepath].enhance( [@configurator.project_test_force_rebuild_filepath] ) if (@project_config_manager.test_config_changed) + @rake_wrapper[object_filepath].enhance( [@configurator.project_test_force_rebuild_filepath] ) if (@project_config_manager.test_config_changed || + @project_config_manager.test_defines_changed) end end def enhance_results_dependencies(result_filepath) - @rake_wrapper[result_filepath].enhance( [@configurator.project_test_force_rebuild_filepath] ) if (@project_config_manager.test_config_changed) + @rake_wrapper[result_filepath].enhance( [@configurator.project_test_force_rebuild_filepath] ) if (@project_config_manager.test_config_changed || + @project_config_manager.test_defines_changed) end def setup_test_executable_dependencies(test, objects) - @rake_wrapper.create_file_task( @file_path_utils.form_test_executable_filepath(test), objects) + @rake_wrapper.create_file_task( @file_path_utils.form_test_executable_filepath(test), objects ) end end diff --git a/test/vendor/ceedling/lib/ceedling/generator.rb b/test/vendor/ceedling/lib/ceedling/generator.rb index a2c94ec5..828a0c02 100644 --- a/test/vendor/ceedling/lib/ceedling/generator.rb +++ b/test/vendor/ceedling/lib/ceedling/generator.rb @@ -19,6 +19,7 @@ class Generator def generate_shallow_includes_list(context, file) + @streaminator.stdout_puts("Generating include list for #{File.basename(file)}...", Verbosity::NORMAL) @preprocessinator.preprocess_shallow_includes(file) end @@ -92,6 +93,8 @@ class Generator arg_hash[:list], arg_hash[:dependencies]) + @streaminator.stdout_puts("Command: #{command}", Verbosity::DEBUG) + begin shell_result = @tool_executor.exec( command[:line], command[:options] ) rescue ShellExecutionException => ex @@ -124,6 +127,7 @@ class Generator arg_hash[:map], arg_hash[:libraries] ) + @streaminator.stdout_puts("Command: #{command}", Verbosity::DEBUG) begin shell_result = @tool_executor.exec( command[:line], command[:options] ) @@ -157,9 +161,12 @@ class Generator # Unity's exit code is equivalent to the number of failed tests, so we tell @tool_executor not to fail out if there are failures # so that we can run all tests and collect all results command = @tool_executor.build_command_line(arg_hash[:tool], [], arg_hash[:executable]) + @streaminator.stdout_puts("Command: #{command}", Verbosity::DEBUG) command[:options][:boom] = false shell_result = @tool_executor.exec( command[:line], command[:options] ) - shell_result[:exit_code] = 0 #Don't Let The Failure Count Make Us Believe Things Aren't Working + + #Don't Let The Failure Count Make Us Believe Things Aren't Working + shell_result[:exit_code] = 0 @generator_helper.test_results_error_handler(executable, shell_result) processed = @generator_test_results.process_and_write_results( shell_result, diff --git a/test/vendor/ceedling/lib/ceedling/generator_test_results.rb b/test/vendor/ceedling/lib/ceedling/generator_test_results.rb index 67bfce13..1d0c5201 100644 --- a/test/vendor/ceedling/lib/ceedling/generator_test_results.rb +++ b/test/vendor/ceedling/lib/ceedling/generator_test_results.rb @@ -7,7 +7,7 @@ class GeneratorTestResults constructor :configurator, :generator_test_results_sanity_checker, :yaml_wrapper def process_and_write_results(unity_shell_result, results_file, test_file) - output_file = results_file + output_file = results_file results = get_results_structure @@ -17,10 +17,10 @@ class GeneratorTestResults # process test statistics if (unity_shell_result[:output] =~ TEST_STDOUT_STATISTICS_PATTERN) - results[:counts][:total] = $1.to_i - results[:counts][:failed] = $2.to_i + results[:counts][:total] = $1.to_i + results[:counts][:failed] = $2.to_i results[:counts][:ignored] = $3.to_i - results[:counts][:passed] = (results[:counts][:total] - results[:counts][:failed] - results[:counts][:ignored]) + results[:counts][:passed] = (results[:counts][:total] - results[:counts][:failed] - results[:counts][:ignored]) end # remove test statistics lines @@ -31,16 +31,16 @@ class GeneratorTestResults case line when /(:IGNORE)/ elements = extract_line_elements(line, results[:source][:file]) - results[:ignores] << elements[0] - results[:stdout] << elements[1] if (!elements[1].nil?) + results[:ignores] << elements[0] + results[:stdout] << elements[1] if (!elements[1].nil?) when /(:PASS$)/ elements = extract_line_elements(line, results[:source][:file]) results[:successes] << elements[0] - results[:stdout] << elements[1] if (!elements[1].nil?) + results[:stdout] << elements[1] if (!elements[1].nil?) when /(:FAIL)/ elements = extract_line_elements(line, results[:source][:file]) - results[:failures] << elements[0] - results[:stdout] << elements[1] if (!elements[1].nil?) + results[:failures] << elements[0] + results[:stdout] << elements[1] if (!elements[1].nil?) else # collect up all other results[:stdout] << line.chomp end diff --git a/test/vendor/ceedling/lib/ceedling/generator_test_runner.rb b/test/vendor/ceedling/lib/ceedling/generator_test_runner.rb index d3f0a92b..6999faf9 100644 --- a/test/vendor/ceedling/lib/ceedling/generator_test_runner.rb +++ b/test/vendor/ceedling/lib/ceedling/generator_test_runner.rb @@ -15,7 +15,9 @@ class GeneratorTestRunner pre_test_file = @file_path_utils.form_preprocessed_file_filepath(test_file) #actually look for the tests using Unity's test runner generator - tests_and_line_numbers = @test_runner_generator.find_tests(@file_wrapper.read(pre_test_file)) + contents = @file_wrapper.read(pre_test_file) + tests_and_line_numbers = @test_runner_generator.find_tests(contents) + @test_runner_generator.find_setup_and_teardown(contents) #look up the line numbers in the original file source_lines = @file_wrapper.read(test_file).split("\n") @@ -31,7 +33,9 @@ class GeneratorTestRunner end else #Just look for the tests using Unity's test runner generator - tests_and_line_numbers = @test_runner_generator.find_tests(@file_wrapper.read(test_file)) + contents = @file_wrapper.read(test_file) + tests_and_line_numbers = @test_runner_generator.find_tests(contents) + @test_runner_generator.find_setup_and_teardown(contents) end return tests_and_line_numbers diff --git a/test/vendor/ceedling/lib/ceedling/objects.yml b/test/vendor/ceedling/lib/ceedling/objects.yml index a6f189b6..2e2e9b9d 100644 --- a/test/vendor/ceedling/lib/ceedling/objects.yml +++ b/test/vendor/ceedling/lib/ceedling/objects.yml @@ -41,7 +41,9 @@ project_file_loader: project_config_manager: compose: - cacheinator + - configurator - yaml_wrapper + - file_wrapper cacheinator: compose: @@ -172,6 +174,7 @@ task_invoker: - dependinator - rake_utils - rake_wrapper + - project_config_manager flaginator: compose: diff --git a/test/vendor/ceedling/lib/ceedling/preprocessinator.rb b/test/vendor/ceedling/lib/ceedling/preprocessinator.rb index e5c46c37..f07750dd 100644 --- a/test/vendor/ceedling/lib/ceedling/preprocessinator.rb +++ b/test/vendor/ceedling/lib/ceedling/preprocessinator.rb @@ -28,8 +28,7 @@ class Preprocessinator end def preprocess_shallow_includes(filepath) - dependencies_rule = @preprocessinator_includes_handler.form_shallow_dependencies_rule(filepath) - includes = @preprocessinator_includes_handler.extract_shallow_includes(dependencies_rule) + includes = @preprocessinator_includes_handler.extract_includes(filepath) @preprocessinator_includes_handler.write_shallow_includes_list( @file_path_utils.form_preprocessed_includes_list_filepath(filepath), includes) diff --git a/test/vendor/ceedling/lib/ceedling/preprocessinator_includes_handler.rb b/test/vendor/ceedling/lib/ceedling/preprocessinator_includes_handler.rb index 686add0e..703c84f3 100644 --- a/test/vendor/ceedling/lib/ceedling/preprocessinator_includes_handler.rb +++ b/test/vendor/ceedling/lib/ceedling/preprocessinator_includes_handler.rb @@ -3,6 +3,7 @@ class PreprocessinatorIncludesHandler constructor :configurator, :tool_executor, :task_invoker, :file_path_utils, :yaml_wrapper, :file_wrapper + @@makefile_cache = {} # shallow includes: only those headers a source file explicitly includes @@ -20,6 +21,9 @@ class PreprocessinatorIncludesHandler # === Return # _String_:: The text of the dependency rule generated by the preprocessor. def form_shallow_dependencies_rule(filepath) + if @@makefile_cache.has_key?(filepath) + return @@makefile_cache[filepath] + end # change filename (prefix of '_') to prevent preprocessor from finding # include files in temp directory containing file it's scanning temp_filepath = @file_path_utils.form_temp_path(filepath, '_') @@ -44,6 +48,7 @@ class PreprocessinatorIncludesHandler command = @tool_executor.build_command_line(@configurator.tools_test_includes_preprocessor, [], temp_filepath) shell_result = @tool_executor.exec(command[:line], command[:options]) + @@makefile_cache[filepath] = shell_result[:output] return shell_result[:output] end @@ -52,19 +57,52 @@ class PreprocessinatorIncludesHandler # provided, annotated Make dependency rule. # # === Arguments - # +make_rule+ _String_:: Annotated Make dependency rule. + # +filepath+ _String_:: C source or header file to extract includes for. # # === Return # _Array_ of _String_:: Array of the direct dependencies for the source file. - def extract_shallow_includes(make_rule) + def extract_includes(filepath) + to_process = [filepath] + ignore_list = [] + list = [] + + include_paths = @configurator.project_config_hash[:collection_paths_include] + include_paths = [] if include_paths.nil? + include_paths.map! {|path| File.expand_path(path)} + + while to_process.length > 0 + target = to_process.shift() + ignore_list << target + # puts "[HELL] Processing: \t\t#{target}" + new_deps, new_to_process = extract_includes_helper(target, include_paths, ignore_list) + list += new_deps + to_process += new_to_process + if (!@configurator.project_config_hash.has_key?(:project_auto_link_deep_dependencies) or + !@configurator.project_config_hash[:project_auto_link_deep_dependencies]) + break + else + list = list.uniq() + to_process = to_process.uniq() + end + end + + return list + end + + def extract_includes_helper(filepath, include_paths, ignore_list) # Extract the dependencies from the make rule hdr_ext = @configurator.extension_header + make_rule = self.form_shallow_dependencies_rule(filepath) dependencies = make_rule.split.find_all {|path| path.end_with?(hdr_ext) }.uniq dependencies.map! {|hdr| hdr.gsub('\\','/') } # Separate the real files form the annotated ones and remove the '@@@@' annotated_headers, real_headers = dependencies.partition {|hdr| hdr =~ /^@@@@/ } annotated_headers.map! {|hdr| hdr.gsub('@@@@','') } + # Matching annotated_headers values against real_headers to ensure that + # annotated_headers contain full path entries (as returned by make rule) + annotated_headers.map! {|hdr| real_headers.find {|real_hdr| !real_hdr.match(/(.*\/)?#{Regexp.escape(hdr)}/).nil? } } + annotated_headers = annotated_headers.compact # Find which of our annotated headers are "real" dependencies. This is # intended to weed out dependencies that have been removed due to build @@ -87,7 +125,54 @@ class PreprocessinatorIncludesHandler sdependencies.map! {|hdr| hdr.gsub('\\','/') } list += sdependencies - list + to_process = [] + + if @configurator.project_config_hash.has_key?(:project_auto_link_deep_dependencies) && @configurator.project_config_hash[:project_auto_link_deep_dependencies] + # Creating list of mocks + mocks = annotated_headers.find_all do |annotated_header| + File.basename(annotated_header) =~ /^#{@configurator.project_config_hash[:cmock_mock_prefix]}.*$/ + end.compact + + # Creating list of headers that should be recursively pre-processed + # Skipping mocks and unity.h + headers_to_deep_link = annotated_headers.select do |annotated_header| + !(mocks.include? annotated_header) and (annotated_header.match(/^(.*\/)?unity\.h$/).nil?) + end + headers_to_deep_link.map! {|hdr| File.expand_path(hdr)} + + mocks.each do |mock| + dirname = File.dirname(mock) + #basename = File.basename(mock).delete_prefix(@configurator.project_config_hash[:cmock_mock_prefix]) + basename = File.basename(mock).sub(@configurator.project_config_hash[:cmock_mock_prefix], '') + if dirname != "." + ignore_list << File.join(dirname, basename) + else + ignore_list << basename + end + end.compact + + # Filtering list of final includes to only include mocks and anything that is NOT in the ignore_list + list = list.select do |item| + mocks.include? item or !(ignore_list.any? { |ignore_item| !item.match(/^(.*\/)?#{Regexp.escape(ignore_item)}$/).nil? }) + end + + headers_to_deep_link.each do |hdr| + if (ignore_list.none? {|ignore_header| hdr.match(/^(.*\/)?#{Regexp.escape(ignore_header)}$/)} and + include_paths.none? {|include_path| hdr =~ /^#{include_path}\.*/}) + if File.exist?(hdr) + to_process << hdr + #source_file = hdr.delete_suffix(hdr_ext) + src_ext + source_file = hdr.chomp(hdr_ext) + src_ext + if source_file != hdr and File.exist?(source_file) + to_process << source_file + end + end + end + end + end + + return list, to_process + end def write_shallow_includes_list(filepath, list) diff --git a/test/vendor/ceedling/lib/ceedling/project_config_manager.rb b/test/vendor/ceedling/lib/ceedling/project_config_manager.rb index 801c206d..31f7e3a6 100644 --- a/test/vendor/ceedling/lib/ceedling/project_config_manager.rb +++ b/test/vendor/ceedling/lib/ceedling/project_config_manager.rb @@ -3,16 +3,17 @@ require 'ceedling/constants' class ProjectConfigManager - attr_reader :options_files, :release_config_changed, :test_config_changed + attr_reader :options_files, :release_config_changed, :test_config_changed, :test_defines_changed attr_accessor :config_hash - constructor :cacheinator, :yaml_wrapper + constructor :cacheinator, :configurator, :yaml_wrapper, :file_wrapper def setup @options_files = [] @release_config_changed = false @test_config_changed = false + @test_defines_changed = false end @@ -34,4 +35,12 @@ class ProjectConfigManager @test_config_changed = @cacheinator.diff_cached_test_config?( @config_hash ) end + def process_test_defines_change(files) + # has definitions changed since last test build + @test_defines_changed = @cacheinator.diff_cached_test_defines?( files ) + if @test_defines_changed + # update timestamp for rake task prerequisites + @file_wrapper.touch( @configurator.project_test_force_rebuild_filepath ) + end + end end diff --git a/test/vendor/ceedling/lib/ceedling/rules_tests.rake b/test/vendor/ceedling/lib/ceedling/rules_tests.rake index 67d8a500..2b8f7af5 100644 --- a/test/vendor/ceedling/lib/ceedling/rules_tests.rake +++ b/test/vendor/ceedling/lib/ceedling/rules_tests.rake @@ -35,8 +35,7 @@ end rule(/#{PROJECT_TEST_BUILD_OUTPUT_PATH}\/#{'.+\\'+EXTENSION_EXECUTABLE}$/) do |bin_file| - lib_args = ((defined? LIBRARIES_SYSTEM) ? LIBRARIES_SYSTEM : []) - lib_args.map! {|v| LIBRARIES_FLAG.gsub(/\$\{1\}/, v) } if (defined? LIBRARIES_FLAG) + lib_args = @ceedling[:test_invoker].convert_libraries_to_arguments() @ceedling[:generator].generate_executable_file( TOOLS_TEST_LINKER, @@ -67,6 +66,7 @@ namespace TEST_SYM do @ceedling[:file_finder].find_test_from_file_path(test) end ]) do |test| + @ceedling[:rake_wrapper][:directories].reenable if @ceedling[:task_invoker].first_run == false && @ceedling[:project_config_manager].test_defines_changed @ceedling[:rake_wrapper][:directories].invoke @ceedling[:test_invoker].setup_and_invoke([test.source]) end diff --git a/test/vendor/ceedling/lib/ceedling/stream_wrapper.rb b/test/vendor/ceedling/lib/ceedling/stream_wrapper.rb index 33d3c10b..7e160527 100644 --- a/test/vendor/ceedling/lib/ceedling/stream_wrapper.rb +++ b/test/vendor/ceedling/lib/ceedling/stream_wrapper.rb @@ -1,8 +1,16 @@ class StreamWrapper + def stdout_override(&fnc) + @stdout_overide_fnc = fnc + end + def stdout_puts(string) - $stdout.puts(string) + if @stdout_overide_fnc + @stdout_overide_fnc.call(string) + else + $stdout.puts(string) + end end def stdout_flush diff --git a/test/vendor/ceedling/lib/ceedling/task_invoker.rb b/test/vendor/ceedling/lib/ceedling/task_invoker.rb index 4e91b2ea..642695c4 100644 --- a/test/vendor/ceedling/lib/ceedling/task_invoker.rb +++ b/test/vendor/ceedling/lib/ceedling/task_invoker.rb @@ -2,11 +2,14 @@ require 'ceedling/par_map' class TaskInvoker - constructor :dependinator, :rake_utils, :rake_wrapper + attr_accessor :first_run + + constructor :dependinator, :rake_utils, :rake_wrapper, :project_config_manager def setup @test_regexs = [/^#{TEST_ROOT_NAME}:/] @release_regexs = [/^#{RELEASE_ROOT_NAME}(:|$)/] + @first_run = true end def add_test_task_regex(regex) @@ -46,17 +49,22 @@ class TaskInvoker def invoke_test_mocks(mocks) @dependinator.enhance_mock_dependencies( mocks ) - mocks.each { |mock| @rake_wrapper[mock].invoke } + mocks.each { |mock| + @rake_wrapper[mock].reenable if @first_run == false && @project_config_manager.test_defines_changed + @rake_wrapper[mock].invoke + } end def invoke_test_runner(runner) @dependinator.enhance_runner_dependencies( runner ) + @rake_wrapper[runner].reenable if @first_run == false && @project_config_manager.test_defines_changed @rake_wrapper[runner].invoke end def invoke_test_shallow_include_lists(files) @dependinator.enhance_shallow_include_lists_dependencies( files ) par_map(PROJECT_COMPILE_THREADS, files) do |file| + @rake_wrapper[file].reenable if @first_run == false && @project_config_manager.test_defines_changed @rake_wrapper[file].invoke end end @@ -64,6 +72,7 @@ class TaskInvoker def invoke_test_preprocessed_files(files) @dependinator.enhance_preprocesed_file_dependencies( files ) par_map(PROJECT_COMPILE_THREADS, files) do |file| + @rake_wrapper[file].reenable if @first_run == false && @project_config_manager.test_defines_changed @rake_wrapper[file].invoke end end @@ -71,30 +80,37 @@ class TaskInvoker def invoke_test_dependencies_files(files) @dependinator.enhance_dependencies_dependencies( files ) par_map(PROJECT_COMPILE_THREADS, files) do |file| + @rake_wrapper[file].reenable if @first_run == false && @project_config_manager.test_defines_changed @rake_wrapper[file].invoke end end def invoke_test_objects(objects) par_map(PROJECT_COMPILE_THREADS, objects) do |object| - @rake_wrapper[object].invoke + @rake_wrapper[object].reenable if @first_run == false && @project_config_manager.test_defines_changed + @rake_wrapper[object].invoke end end + def invoke_test_executable(file) + @rake_wrapper[file].invoke + end + def invoke_test_results(result) @dependinator.enhance_results_dependencies( result ) + @rake_wrapper[result].reenable if @first_run == false && @project_config_manager.test_defines_changed @rake_wrapper[result].invoke end def invoke_release_dependencies_files(files) par_map(PROJECT_COMPILE_THREADS, files) do |file| - @rake_wrapper[file].invoke + @rake_wrapper[file].invoke end end def invoke_release_objects(objects) par_map(PROJECT_COMPILE_THREADS, objects) do |object| - @rake_wrapper[object].invoke + @rake_wrapper[object].invoke end end diff --git a/test/vendor/ceedling/lib/ceedling/tasks_base.rake b/test/vendor/ceedling/lib/ceedling/tasks_base.rake index 29074534..8c825309 100644 --- a/test/vendor/ceedling/lib/ceedling/tasks_base.rake +++ b/test/vendor/ceedling/lib/ceedling/tasks_base.rake @@ -89,7 +89,6 @@ namespace :options do desc "Merge #{option} project options." task option.downcase.to_sym do - # @ceedling[:setupinator].reset_defaults( @ceedling[:setupinator].config_hash ) hash = @ceedling[:project_config_manager].merge_options( @ceedling[:setupinator].config_hash, option_path ) @ceedling[:setupinator].do_setup( hash ) if @ceedling[:configurator].project_release_build diff --git a/test/vendor/ceedling/lib/ceedling/tasks_filesystem.rake b/test/vendor/ceedling/lib/ceedling/tasks_filesystem.rake index 4c917297..58fa6511 100644 --- a/test/vendor/ceedling/lib/ceedling/tasks_filesystem.rake +++ b/test/vendor/ceedling/lib/ceedling/tasks_filesystem.rake @@ -81,7 +81,10 @@ namespace :files do ['source', COLLECTION_ALL_SOURCE], ['header', COLLECTION_ALL_HEADERS] ] - categories << ['assembly', COLLECTION_ALL_ASSEMBLY] if (RELEASE_BUILD_USE_ASSEMBLY) + + using_assembly = (defined?(TEST_BUILD_USE_ASSEMBLY) && TEST_BUILD_USE_ASSEMBLY) || + (defined?(RELEASE_BUILD_USE_ASSEMBLY) && RELEASE_BUILD_USE_ASSEMBLY) + categories << ['assembly', COLLECTION_ALL_ASSEMBLY] if using_assembly categories.each do |category| name = category[0] diff --git a/test/vendor/ceedling/lib/ceedling/tasks_tests.rake b/test/vendor/ceedling/lib/ceedling/tasks_tests.rake index 13e97133..5d09c1af 100644 --- a/test/vendor/ceedling/lib/ceedling/tasks_tests.rake +++ b/test/vendor/ceedling/lib/ceedling/tasks_tests.rake @@ -1,7 +1,7 @@ require 'ceedling/constants' task :test => [:directories] do - @ceedling[:test_invoker].setup_and_invoke(COLLECTION_ALL_TESTS) + Rake.application['test:all'].invoke end namespace TEST_SYM do @@ -25,6 +25,11 @@ namespace TEST_SYM do @ceedling[:test_invoker].setup_and_invoke(COLLECTION_ALL_TESTS, TEST_SYM, {:force_run => false}) end + desc "Just build tests without running." + task :build_only => [:directories] do + @ceedling[:test_invoker].setup_and_invoke(COLLECTION_ALL_TESTS, TEST_SYM, {:build_only => true}) + end + desc "Run tests by matching regular expression pattern." task :pattern, [:regex] => [:directories] do |t, args| matches = [] diff --git a/test/vendor/ceedling/lib/ceedling/test_invoker.rb b/test/vendor/ceedling/lib/ceedling/test_invoker.rb index 01287ef8..652cb318 100644 --- a/test/vendor/ceedling/lib/ceedling/test_invoker.rb +++ b/test/vendor/ceedling/lib/ceedling/test_invoker.rb @@ -54,7 +54,20 @@ class TestInvoker end end - def setup_and_invoke(tests, context=TEST_SYM, options={:force_run => true}) + # Convert libraries configuration form YAML configuration + # into a string that can be given to the compiler. + def convert_libraries_to_arguments() + if @configurator.project_config_hash.has_key?(:libraries_test) + lib_args = @configurator.project_config_hash[:libraries_test] + lib_args.flatten! + lib_flag = @configurator.project_config_hash[:libraries_flag] + lib_args.map! {|v| lib_flag.gsub(/\$\{1\}/, v) } if (defined? lib_flag) + return lib_args + end + end + + + def setup_and_invoke(tests, context=TEST_SYM, options={:force_run => true, :build_only => false}) @tests = tests @@ -68,7 +81,7 @@ class TestInvoker begin @plugin_manager.pre_test( test ) test_name ="#{File.basename(test)}".chomp('.c') - def_test_key="defines_#{test_name}" + def_test_key="defines_#{test_name.downcase}" # Re-define the project out path and pre-processor defines. if @configurator.project_config_hash.has_key?(def_test_key.to_sym) @@ -94,6 +107,8 @@ class TestInvoker results_pass = @file_path_utils.form_pass_results_filepath( test ) results_fail = @file_path_utils.form_fail_results_filepath( test ) + @project_config_manager.process_test_defines_change(sources) + # add the definition value in the build option for the unit test if @configurator.defines_use_test_definition add_test_definition(test) @@ -119,8 +134,15 @@ class TestInvoker # build test objects @task_invoker.invoke_test_objects( objects ) - # 3, 2, 1... launch - @task_invoker.invoke_test_results( results_pass ) + # if the option build_only has been specified, build only the executable + # but don't run the test + if (options[:build_only]) + executable = @file_path_utils.form_test_executable_filepath( test ) + @task_invoker.invoke_test_executable( executable ) + else + # 3, 2, 1... launch + @task_invoker.invoke_test_results( results_pass ) + end rescue => e @build_invoker_utils.process_exception( e, context ) ensure @@ -142,6 +164,8 @@ class TestInvoker # store away what's been processed @mocks.concat( mock_list ) @sources.concat( sources ) + + @task_invoker.first_run = false end # post-process collected mock list diff --git a/test/vendor/ceedling/lib/ceedling/tool_executor.rb b/test/vendor/ceedling/lib/ceedling/tool_executor.rb index a5b3f579..0ab5ddca 100644 --- a/test/vendor/ceedling/lib/ceedling/tool_executor.rb +++ b/test/vendor/ceedling/lib/ceedling/tool_executor.rb @@ -18,6 +18,8 @@ class ToolExecutor end # build up a command line from yaml provided config + + # @param extra_params is an array of parameters to append to executable def build_command_line(tool_config, extra_params, *args) @tool_name = tool_config[:name] @executable = tool_config[:executable] @@ -50,7 +52,6 @@ class ToolExecutor options[:boom] = true if (options[:boom].nil?) options[:stderr_redirect] = StdErrRedirect::NONE if (options[:stderr_redirect].nil?) options[:background_exec] = BackgroundExec::NONE if (options[:background_exec].nil?) - # build command line command_line = [ @tool_executor_helper.background_exec_cmdline_prepend( options ), @@ -60,6 +61,8 @@ class ToolExecutor @tool_executor_helper.background_exec_cmdline_append( options ), ].flatten.compact.join(' ') + @streaminator.stderr_puts("Verbose: #{__method__.to_s}(): #{command_line}", Verbosity::DEBUG) + shell_result = {} # depending on background exec option, we shell out differently @@ -73,7 +76,10 @@ class ToolExecutor shell_result[:time] = time #scrub the string for illegal output - shell_result[:output].scrub! unless (!("".respond_to? :scrub!) || (shell_result[:output].nil?)) + unless shell_result[:output].nil? + shell_result[:output] = shell_result[:output].scrub if "".respond_to?(:scrub) + shell_result[:output].gsub!(/\033\[\d\dm/,'') + end @tool_executor_helper.print_happy_results( command_line, shell_result, options[:boom] ) @tool_executor_helper.print_error_results( command_line, shell_result, options[:boom] ) diff --git a/test/vendor/ceedling/lib/ceedling/version.rb b/test/vendor/ceedling/lib/ceedling/version.rb index 3dfdf362..ba917df5 100644 --- a/test/vendor/ceedling/lib/ceedling/version.rb +++ b/test/vendor/ceedling/lib/ceedling/version.rb @@ -1,15 +1,36 @@ + # @private module Ceedling module Version - # @private - GEM = "0.28.3" - # @private + # Check for local or global version of vendor directory in order to look up versions + { + "CEXCEPTION" => File.join("vendor","c_exception","lib","CException.h"), + "CMOCK" => File.join("vendor","cmock","src","cmock.h"), + "UNITY" => File.join("vendor","unity","src","unity.h"), + }.each_pair do |name, path| + filename = if (File.exist?(File.join("..","..",path))) + File.join("..","..",path) + elsif (File.exist?(File.join(File.dirname(__FILE__),"..","..",path))) + File.join(File.dirname(__FILE__),"..","..",path) + else + eval "#{name} = 'unknown'" + continue + end + + # Actually look up the versions + a = [0,0,0] + File.readlines(filename) do |line| + ["VERSION_MAJOR", "VERSION_MINOR", "VERSION_BUILD"].each_with_index do |field, i| + m = line.match(/#{name}_#{field}\s+(\d+)/) + a[i] = m[1] unless (m.nil?) + end + end + + # Make a constant from each, so that we can use it elsewhere + eval "#{name} = '#{a.join(".")}'" + end + + GEM = "0.29.0" CEEDLING = GEM - # @private - CEXCEPTION = "1.3.1" - # @private - CMOCK = "2.4.5" - # @private - UNITY = "2.4.2" end end diff --git a/test/vendor/ceedling/plugins/command_hooks/README.md b/test/vendor/ceedling/plugins/command_hooks/README.md index 9fcbbba6..8ac64afc 100644 --- a/test/vendor/ceedling/plugins/command_hooks/README.md +++ b/test/vendor/ceedling/plugins/command_hooks/README.md @@ -15,7 +15,6 @@ Define any of these sections in :tools: to provide additional hooks to be called :pre_link_execute :post_link_execute :pre_test_fixture_execute - :pre_test_fixture_execute :pre_test :post_test :pre_release @@ -24,13 +23,13 @@ Define any of these sections in :tools: to provide additional hooks to be called :post_build ``` -Each of these tools can support an :executable string and an :args list, like so: +Each of these tools can support an :executable string and an :arguments list, like so: ``` :tools: :post_link_execute: :executable: objcopy.exe - :args: + :arguments: - ${1} #This is replaced with the executable name - output.srec - --strip-all @@ -42,11 +41,13 @@ You may also specify an array of executables to be called in a particular place, :tools: :post_test: - :executable: echo - :args: "${1} was glorious!" + :arguments: "${1} was glorious!" - :executable: echo - :args: + :arguments: - it kinda made me cry a little. - you? ``` +Please note that it varies which arguments are being parsed down to the +hooks. For now see `command_hooks.rb` to figure out which suits you best. Happy Tweaking! diff --git a/test/vendor/ceedling/plugins/command_hooks/lib/command_hooks.rb b/test/vendor/ceedling/plugins/command_hooks/lib/command_hooks.rb index d8525b03..4bf8b531 100644 --- a/test/vendor/ceedling/plugins/command_hooks/lib/command_hooks.rb +++ b/test/vendor/ceedling/plugins/command_hooks/lib/command_hooks.rb @@ -1,6 +1,5 @@ require 'ceedling/plugin' require 'ceedling/constants' - class CommandHooks < Plugin attr_reader :config @@ -23,7 +22,6 @@ class CommandHooks < Plugin :post_release => ((defined? TOOLS_POST_RELEASE) ? TOOLS_POST_RELEASE : nil ), :pre_build => ((defined? TOOLS_PRE_BUILD) ? TOOLS_PRE_BUILD : nil ), :post_build => ((defined? TOOLS_POST_BUILD) ? TOOLS_POST_BUILD : nil ), - :post_build => ((defined? TOOLS_POST_BUILD) ? TOOLS_POST_BUILD : nil ), :post_error => ((defined? TOOLS_POST_ERROR) ? TOOLS_POST_ERROR : nil ), } @plugin_root = File.expand_path(File.join(File.dirname(__FILE__), '..')) @@ -49,14 +47,33 @@ class CommandHooks < Plugin private + ## + # Run a hook if its available. + # + # :args: + # - hook: Name of the hook to run + # - name: Name of file (default: "") + # + # :return: + # shell_result. + # def run_hook_step(hook, name="") if (hook[:executable]) - args = ( (hook[:args].is_a? Array) ? hook[:args] : [] ) - cmd = @ceedling[:tool_executor].build_command_line( hook, args, name ) - shell_result = @ceedling[:tool_executor].exec( cmd[:line], cmd[:options] ) + # Handle argument replacemant ({$1}), and get commandline + cmd = @ceedling[:tool_executor].build_command_line( hook, [], name ) + shell_result = @ceedling[:tool_executor].exec(cmd[:line], cmd[:options]) end end + ## + # Run a hook if its available. + # + # If __which_hook__ is an array, run each of them sequentially. + # + # :args: + # - which_hook: Name of the hook to run + # - name: Name of file + # def run_hook(which_hook, name="") if (@config[which_hook]) @ceedling[:streaminator].stdout_puts("Running Hook #{which_hook}...", Verbosity::NORMAL) diff --git a/test/vendor/ceedling/plugins/gcov/README.md b/test/vendor/ceedling/plugins/gcov/README.md index 3ed992cb..096ffa10 100644 --- a/test/vendor/ceedling/plugins/gcov/README.md +++ b/test/vendor/ceedling/plugins/gcov/README.md @@ -1,13 +1,16 @@ ceedling-gcov ============= +# Plugin Overview + Plugin for integrating GNU GCov code coverage tool into Ceedling projects. Currently only designed for the gcov command (like LCOV for example). In the future we could configure this to work with other code coverage tools. +This plugin currently uses `gcovr` to generate HTML and/or XML reports as a +utility. The normal gcov plugin _must_ be run first for this report to generate. -This plugin currently uses `gcovr` to generate HTML reports as a utility. The -normal gcov plugin _must_ be run first for this report to generate. +## Installation Gcovr can be installed via pip like so: @@ -15,27 +18,83 @@ Gcovr can be installed via pip like so: pip install gcovr ``` +## Configuration + +The gcov plugin supports configuration options via your `project.yml` provided +by Ceedling. + +Generation of HTML reports may be enabled or disabled with the following +config. Set to `true` to enable or set to `false` to disable. + +``` +:gcov: + :html_report: true +``` + +Generation of XML reports may be enabled or disabled with the following +config. Set to `true` to enable or set to `false` to disable. + +``` +:gcov: + :xml_report: true +``` + There are two types of gcovr HTML reports that can be configured in your -`project.yml`. To create a basic HTML report with only the overall file -information use the following config. +`project.yml`. To create a basic HTML report, with only the overall file +information, use the following config. ``` :gcov: :html_report_type: basic ``` -To create a detailed HTML report with line by line breakdown of the coverage use -the following config. + +To create a detailed HTML report, with line by line breakdown of the +coverage, use the following config. ``` :gcov: :html_report_type: detailed ``` -These reports will be found in `build/artifacts/gcov`. +There are a number of options to control which files are considered part of +the coverage report. Most often, we only care about coverage on our source code, and not +on tests or automatically generated mocks, runners, etc. However, there are times +where this isn't true... or there are times where we've moved ceedling's directory +structure so that the project file isn't at the root of the project anymore. In these +cases, you may need to tweak the following: +``` +:gcov: + :report_root: "." + :report_exclude: "^build|^vendor|^test|^support" + :report_include: "^src" +``` +One important note about html_report_root: gcovr will only take a single root folder, unlike +Ceedling's ability to take as many as you like. So you will need to choose a folder which is +a superset of ALL the folders you want, and then use the include or exclude options to set up +patterns of files to pay attention to or ignore. It's not ideal, but it works. -# To-Do list +Finally, there are a number of settings which can be specified in order to adjust the +default behaviors of gcov: + +``` +:gcov: + :html_medium_threshold: 75 + :html_high_threshold: 90 + :fail_under_line: 30 + :fail_under_branch: 30 +``` + +These HTML and XML reports will be found in `build/artifacts/gcov`. + +## Example Usage + +``` +ceedling gcov:all utils:gcov +``` + +## To-Do list - Generate overall report (combined statistics from all files with coverage) - Generate coverage output files diff --git a/test/vendor/ceedling/plugins/gcov/config/defaults.yml b/test/vendor/ceedling/plugins/gcov/config/defaults.yml index cb11a7dd..13bac556 100644 --- a/test/vendor/ceedling/plugins/gcov/config/defaults.yml +++ b/test/vendor/ceedling/plugins/gcov/config/defaults.yml @@ -11,6 +11,7 @@ - -I"$": COLLECTION_PATHS_TEST_TOOLCHAIN_INCLUDE - -D$: COLLECTION_DEFINES_TEST_AND_VENDOR - -DGCOV_COMPILER + - -DCODE_COVERAGE - -c "${1}" - -o "${2}" :gcov_linker: @@ -20,6 +21,7 @@ - -ftest-coverage - ${1} - -o ${2} + - ${3} :gcov_fixture: :executable: ${1} :gcov_report: @@ -36,9 +38,8 @@ :arguments: - -p - -b - - -e "${1}" + - ${1} - --html - - -r . - -o GcovCoverageResults.html :gcov_post_report_basic: :executable: gcovr @@ -46,9 +47,8 @@ :arguments: - -p - -b - - -e "${1}" + - ${1} - --html - - -r . - -o "$": GCOV_ARTIFACTS_FILE :gcov_post_report_advanced: :executable: gcovr @@ -56,11 +56,18 @@ :arguments: - -p - -b - - -e "${1}" + - ${1} - --html - --html-details - - -r . - -o "$": GCOV_ARTIFACTS_FILE - + :gcov_post_report_xml: + :executable: gcovr + :optional: TRUE + :arguments: + - -p + - -b + - ${1} + - --xml + - -o "$": GCOV_ARTIFACTS_FILE_XML ... diff --git a/test/vendor/ceedling/plugins/gcov/gcov.rake b/test/vendor/ceedling/plugins/gcov/gcov.rake index 997a0cd9..3acab856 100644 --- a/test/vendor/ceedling/plugins/gcov/gcov.rake +++ b/test/vendor/ceedling/plugins/gcov/gcov.rake @@ -31,11 +31,14 @@ rule(/#{GCOV_BUILD_OUTPUT_PATH}\/#{'.+\\' + EXTENSION_OBJECT}$/ => [ end rule(/#{GCOV_BUILD_OUTPUT_PATH}\/#{'.+\\' + EXTENSION_EXECUTABLE}$/) do |bin_file| + lib_args = @ceedling[:test_invoker].convert_libraries_to_arguments() + @ceedling[:generator].generate_executable_file( TOOLS_GCOV_LINKER, GCOV_SYM, bin_file.prerequisites, bin_file.name, + lib_args, @ceedling[:file_path_utils].form_test_build_map_filepath(bin_file.name) ) end @@ -151,6 +154,17 @@ if PROJECT_USE_DEEP_DEPENDENCIES end namespace UTILS_SYM do + def gcov_args_builder(opts) + args = "" + args += "-r \"#{opts[:gcov_report_root] || '.'}\" " + args += "-f \"#{opts[:gcov_report_include]}\" " unless opts[:gcov_report_include].nil? + args += "-e \"#{opts[:gcov_report_exclude] || GCOV_FILTER_EXCLUDE}\" " + [ :gcov_fail_under_line, :gcov_fail_under_branch, :gcov_html_medium_threshold, :gcov_html_high_threshold].each do |opt| + args += "--#{opt.to_s.gsub('_','-').sub(/:?gcov-/,'')} #{opts[opt]} " unless opts[opt].nil? + end + return args + end + desc 'Create gcov code coverage html report (must run ceedling gcov first)' task GCOV_SYM do @@ -158,23 +172,49 @@ namespace UTILS_SYM do FileUtils.mkdir_p GCOV_ARTIFACTS_PATH end - filter = @ceedling[:configurator].project_config_hash[:gcov_html_report_filter] || GCOV_FILTER_EXPR + args = gcov_args_builder(@ceedling[:configurator].project_config_hash) - if @ceedling[:configurator].project_config_hash[:gcov_html_report_type] == 'basic' - puts "Creating a basic html report of gcov results in #{GCOV_ARTIFACTS_FILE}..." - command = @ceedling[:tool_executor].build_command_line(TOOLS_GCOV_POST_REPORT_BASIC, [], filter) - @ceedling[:tool_executor].exec(command[:line], command[:options]) - elsif @ceedling[:configurator].project_config_hash[:gcov_html_report_type] == 'detailed' - puts "Creating a detailed html report of gcov results in #{GCOV_ARTIFACTS_FILE}..." - command = @ceedling[:tool_executor].build_command_line(TOOLS_GCOV_POST_REPORT_ADVANCED, [], filter) - @ceedling[:tool_executor].exec(command[:line], command[:options]) + if @ceedling[:configurator].project_config_hash[:gcov_html_report].nil? + puts "In your project.yml, define: \n\n:gcov:\n :html_report:\n\n to true or false to refine this feature." + puts "For now, assumimg you want an html report generated." + html_enabled = true else - puts "In your project.yml, define: \n\n:gcov:\n :html_report_type:\n\n to basic or detailed to refine this feature." - puts "For now, just creating basic." - puts "Creating a basic html report of gcov results in #{GCOV_ARTIFACTS_FILE}..." - command = @ceedling[:tool_executor].build_command_line(TOOLS_GCOV_POST_REPORT_BASIC, [], filter) + html_enabled = @ceedling[:configurator].project_config_hash[:gcov_html_report] + end + + if @ceedling[:configurator].project_config_hash[:gcov_xml_report].nil? + puts "In your project.yml, define: \n\n:gcov:\n :xml_report:\n\n to true or false to refine this feature." + puts "For now, assumimg you do not want an xml report generated." + xml_enabled = false + else + xml_enabled = @ceedling[:configurator].project_config_hash[:gcov_xml_report] + end + + if html_enabled + if @ceedling[:configurator].project_config_hash[:gcov_html_report_type] == 'basic' + puts "Creating a basic html report of gcov results in #{GCOV_ARTIFACTS_FILE}..." + command = @ceedling[:tool_executor].build_command_line(TOOLS_GCOV_POST_REPORT_BASIC, [], args) + @ceedling[:tool_executor].exec(command[:line], command[:options]) + elsif @ceedling[:configurator].project_config_hash[:gcov_html_report_type] == 'detailed' + puts "Creating a detailed html report of gcov results in #{GCOV_ARTIFACTS_FILE}..." + command = @ceedling[:tool_executor].build_command_line(TOOLS_GCOV_POST_REPORT_ADVANCED, [], args) + @ceedling[:tool_executor].exec(command[:line], command[:options]) + + else + puts "In your project.yml, define: \n\n:gcov:\n :html_report_type:\n\n to basic or detailed to refine this feature." + puts "For now, just creating basic." + puts "Creating a basic html report of gcov results in #{GCOV_ARTIFACTS_FILE}..." + command = @ceedling[:tool_executor].build_command_line(TOOLS_GCOV_POST_REPORT_BASIC, [], args) + @ceedling[:tool_executor].exec(command[:line], command[:options]) + end + end + + if xml_enabled + puts "Creating an xml report of gcov results in #{GCOV_ARTIFACTS_FILE_XML}..." + command = @ceedling[:tool_executor].build_command_line(TOOLS_GCOV_POST_REPORT_XML, [], filter) @ceedling[:tool_executor].exec(command[:line], command[:options]) end + puts "Done." end end diff --git a/test/vendor/ceedling/plugins/gcov/lib/gcov.rb b/test/vendor/ceedling/plugins/gcov/lib/gcov.rb index 9a93d5bd..15a1b4cf 100644 --- a/test/vendor/ceedling/plugins/gcov/lib/gcov.rb +++ b/test/vendor/ceedling/plugins/gcov/lib/gcov.rb @@ -14,8 +14,7 @@ class Gcov < Plugin project_test_results_path: GCOV_RESULTS_PATH, project_test_dependencies_path: GCOV_DEPENDENCIES_PATH, defines_test: DEFINES_TEST + ['CODE_COVERAGE'], - collection_defines_test_and_vendor: COLLECTION_DEFINES_TEST_AND_VENDOR + ['CODE_COVERAGE'], - gcov_html_report_filter: GCOV_FILTER_EXPR + gcov_html_report_filter: GCOV_FILTER_EXCLUDE } @plugin_root = File.expand_path(File.join(File.dirname(__FILE__), '..')) @@ -23,13 +22,15 @@ class Gcov < Plugin end def generate_coverage_object_file(source, object) + lib_args = @ceedling[:test_invoker].convert_libraries_to_arguments() compile_command = @ceedling[:tool_executor].build_command_line( TOOLS_GCOV_COMPILER, @ceedling[:flaginator].flag_down(OPERATION_COMPILE_SYM, GCOV_SYM, source), source, object, - @ceedling[:file_path_utils].form_test_build_list_filepath(object) + @ceedling[:file_path_utils].form_test_build_list_filepath(object), + lib_args ) @ceedling[:streaminator].stdout_puts("Compiling #{File.basename(source)} with coverage...") @ceedling[:tool_executor].exec(compile_command[:line], compile_command[:options]) @@ -96,6 +97,12 @@ class Gcov < Plugin @ceedling[:streaminator].stdout_puts(report + "\n\n") end end + + COLLECTION_ALL_SOURCE.each do |source| + unless coverage_sources.include?(source) + @ceedling[:streaminator].stdout_puts("Could not find coverage results for " + source + "\n") + end + end end end diff --git a/test/vendor/ceedling/plugins/gcov/lib/gcov_constants.rb b/test/vendor/ceedling/plugins/gcov/lib/gcov_constants.rb index 84c91d3b..539d46f7 100644 --- a/test/vendor/ceedling/plugins/gcov/lib/gcov_constants.rb +++ b/test/vendor/ceedling/plugins/gcov/lib/gcov_constants.rb @@ -10,9 +10,10 @@ GCOV_DEPENDENCIES_PATH = File.join(GCOV_BUILD_PATH, "dependencies") GCOV_ARTIFACTS_PATH = File.join(PROJECT_BUILD_ARTIFACTS_ROOT, GCOV_ROOT_NAME) GCOV_ARTIFACTS_FILE = File.join(GCOV_ARTIFACTS_PATH, "GcovCoverageResults.html") +GCOV_ARTIFACTS_FILE_XML = File.join(GCOV_ARTIFACTS_PATH, "GcovCoverageResults.xml") GCOV_IGNORE_SOURCES = %w(unity cmock cexception).freeze -GCOV_FILTER_EXPR = '^vendor.*|^build.*|^test.*|^lib.*' +GCOV_FILTER_EXCLUDE = '^vendor.*|^build.*|^test.*|^lib.*' diff --git a/test/vendor/ceedling/plugins/junit_tests_report/lib/junit_tests_report.rb b/test/vendor/ceedling/plugins/junit_tests_report/lib/junit_tests_report.rb index 4612b220..a777d07d 100644 --- a/test/vendor/ceedling/plugins/junit_tests_report/lib/junit_tests_report.rb +++ b/test/vendor/ceedling/plugins/junit_tests_report/lib/junit_tests_report.rb @@ -22,7 +22,10 @@ class JunitTestsReport < Plugin def post_build @results_list.each_key do |context| results = @ceedling[:plugin_reportinator].assemble_test_results(@results_list[context]) - file_path = File.join( PROJECT_BUILD_ARTIFACTS_ROOT, context.to_s, 'report.xml' ) + + artifact_filename = @ceedling[:configurator].project_config_hash[:junit_tests_report_artifact_filename] || 'report.xml' + artifact_fullpath = @ceedling[:configurator].project_config_hash[:junit_tests_report_path] || File.join(PROJECT_BUILD_ARTIFACTS_ROOT, context.to_s) + file_path = File.join(artifact_fullpath, artifact_filename) @ceedling[:file_wrapper].open( file_path, 'w' ) do |f| @testsuite_counter = 0 @@ -90,7 +93,14 @@ class JunitTestsReport < Plugin unless suite[:stdout].empty? stream.puts(' ') - suite[:stdout].each{|line| stream.puts line } + suite[:stdout].each do |line| + line.gsub!(/&/, '&') + line.gsub!(//, '>') + line.gsub!(/"/, '"') + line.gsub!(/'/, ''') + stream.puts(line) + end stream.puts(' ') end @@ -98,6 +108,7 @@ class JunitTestsReport < Plugin end def write_test( test, stream ) + test[:test].gsub!('"', '"') case test[:result] when :success stream.puts(' ' % test) diff --git a/test/vendor/ceedling/plugins/module_generator/lib/module_generator.rb b/test/vendor/ceedling/plugins/module_generator/lib/module_generator.rb index ab0f0f10..b2fac006 100644 --- a/test/vendor/ceedling/plugins/module_generator/lib/module_generator.rb +++ b/test/vendor/ceedling/plugins/module_generator/lib/module_generator.rb @@ -39,10 +39,29 @@ class ModuleGenerator < Plugin :update_svn => ((defined? MODULE_GENERATOR_UPDATE_SVN ) ? MODULE_GENERATOR_UPDATE_SVN : false ), } + # Read Boilerplate template file. + if (defined? MODULE_GENERATOR_BOILERPLATE_FILES) + + bf = MODULE_GENERATOR_BOILERPLATE_FILES + + if !bf[:src].nil? && File.exists?(bf[:src]) + unity_generator_options[:boilerplates][:src] = File.read(bf[:src]) + end + + if !bf[:inc].nil? && File.exists?(bf[:inc]) + unity_generator_options[:boilerplates][:inc] = File.read(bf[:inc]) + end + + if !bf[:tst].nil? && File.exists?(bf[:tst]) + unity_generator_options[:boilerplates][:tst] = File.read(bf[:tst]) + end + end + + # If using "create[:]" option from command line. unless optz[:module_root_path].to_s.empty? - unity_generator_options[:path_src] = File.join(optz[:module_root_path], unity_generator_options[:path_src]) - unity_generator_options[:path_inc] = File.join(optz[:module_root_path], unity_generator_options[:path_inc]) - unity_generator_options[:path_tst] = File.join(optz[:module_root_path], unity_generator_options[:path_tst]) + unity_generator_options[:path_src] = File.join(optz[:module_root_path], unity_generator_options[:path_src]) + unity_generator_options[:path_inc] = File.join(optz[:module_root_path], unity_generator_options[:path_inc]) + unity_generator_options[:path_tst] = File.join(optz[:module_root_path], unity_generator_options[:path_tst]) end return unity_generator_options diff --git a/test/vendor/ceedling/plugins/module_generator/module_generator.rake b/test/vendor/ceedling/plugins/module_generator/module_generator.rake index 7a7a1a98..e88e346a 100644 --- a/test/vendor/ceedling/plugins/module_generator/module_generator.rake +++ b/test/vendor/ceedling/plugins/module_generator/module_generator.rake @@ -10,15 +10,20 @@ namespace :module do p = files.delete(pat) optz[:pattern] = p unless p.nil? end - files.each { - |v| + files.each do |v| module_root_path, module_name = v.split(module_root_separator, 2) if module_name optz[:module_root_path] = module_root_path v = module_name end - @ceedling[:module_generator].create(v, optz) - } + if (v =~ /^test_?/i) + # If the name of the file starts with test, automatically treat it as one + @ceedling[:module_generator].create(v.sub(/^test_?/i,''), optz.merge({:pattern => 'test'})) + else + # Otherwise, go through the normal procedure + @ceedling[:module_generator].create(v, optz) + end + end end desc "Destroy module (source, header and test files)" @@ -29,15 +34,14 @@ namespace :module do p = files.delete(pat) optz[:pattern] = p unless p.nil? end - files.each { - |v| + files.each do |v| module_root_path, module_name = v.split(module_root_separator, 2) if module_name optz[:module_root_path] = module_root_path v = module_name end @ceedling[:module_generator].create(v, optz) - } + end end end diff --git a/test/vendor/ceedling/plugins/xml_tests_report/lib/xml_tests_report.rb b/test/vendor/ceedling/plugins/xml_tests_report/lib/xml_tests_report.rb index abe52dd2..ed4e9960 100644 --- a/test/vendor/ceedling/plugins/xml_tests_report/lib/xml_tests_report.rb +++ b/test/vendor/ceedling/plugins/xml_tests_report/lib/xml_tests_report.rb @@ -19,7 +19,9 @@ class XmlTestsReport < Plugin @results_list.each_key do |context| results = @ceedling[:plugin_reportinator].assemble_test_results(@results_list[context]) - file_path = File.join(PROJECT_BUILD_ARTIFACTS_ROOT, context.to_s, 'report.xml') + artifact_filename = @ceedling[:configurator].project_config_hash[:xml_tests_report_artifact_filename] || 'report.xml' + artifact_fullpath = @ceedling[:configurator].project_config_hash[:xml_tests_report_path] || File.join(PROJECT_BUILD_ARTIFACTS_ROOT, context.to_s) + file_path = File.join(artifact_fullpath, artifact_filename) @ceedling[:file_wrapper].open(file_path, 'w') do |f| @test_counter = 1 diff --git a/test/vendor/ceedling/vendor/c_exception/lib/CException.h b/test/vendor/ceedling/vendor/c_exception/lib/CException.h index 06ecf525..78f2f940 100644 --- a/test/vendor/ceedling/vendor/c_exception/lib/CException.h +++ b/test/vendor/ceedling/vendor/c_exception/lib/CException.h @@ -9,6 +9,11 @@ extern "C" #endif +#define CEXCEPTION_VERSION_MAJOR 1 +#define CEXCEPTION_VERSION_MINOR 3 +#define CEXCEPTION_VERSION_BUILD 2 +#define CEXCEPTION_VERSION ((CEXCEPTION_VERSION_MAJOR << 16) | (CEXCEPTION_VERSION_MINOR << 8) | CEXCEPTION_VERSION_BUILD) + //To Use CException, you have a number of options: //1. Just include it and run with the defaults //2. Define any of the following symbols at the command line to override them diff --git a/test/vendor/ceedling/vendor/cmock/lib/cmock_config.rb b/test/vendor/ceedling/vendor/cmock/lib/cmock_config.rb index 398c582a..b21b61ed 100644 --- a/test/vendor/ceedling/vendor/cmock/lib/cmock_config.rb +++ b/test/vendor/ceedling/vendor/cmock/lib/cmock_config.rb @@ -22,6 +22,7 @@ class CMockConfig :fail_on_unexpected_calls => true, :unity_helper_path => false, :treat_as => {}, + :treat_as_array => {}, :treat_as_void => [], :memcmp_if_unknown => true, :when_no_prototypes => :warn, #the options being :ignore, :warn, or :error @@ -36,6 +37,8 @@ class CMockConfig :includes_c_pre_header => nil, :includes_c_post_header => nil, :orig_header_include_fmt => "#include \"%s\"", + :array_size_type => [], + :array_size_name => 'size|len', } def initialize(options=nil) @@ -61,6 +64,7 @@ class CMockConfig end options[:unity_helper_path] ||= options[:unity_helper] options[:unity_helper_path] = [options[:unity_helper_path]] if options[:unity_helper_path].is_a? String + options[:includes_c_post_header] = ((options[:includes_c_post_header] || []) + (options[:unity_helper_path] || [])).uniq options[:plugins].compact! options[:plugins].map! {|p| p.to_sym} @options = options @@ -69,7 +73,11 @@ class CMockConfig treat_as_map.merge!(@options[:treat_as]) @options[:treat_as] = treat_as_map - @options.each_key { |key| eval("def #{key.to_s}() return @options[:#{key.to_s}] end") } + @options.each_key do |key| + unless methods.include?(key) + eval("def #{key.to_s}() return @options[:#{key.to_s}] end") + end + end end def load_config_file_from_yaml yaml_filename diff --git a/test/vendor/ceedling/vendor/cmock/lib/cmock_generator.rb b/test/vendor/ceedling/vendor/cmock/lib/cmock_generator.rb index 8cfe07b1..42725a60 100644 --- a/test/vendor/ceedling/vendor/cmock/lib/cmock_generator.rb +++ b/test/vendor/ceedling/vendor/cmock/lib/cmock_generator.rb @@ -57,9 +57,7 @@ class CMockGenerator private if $ThisIsOnlyATest.nil? ############################## def create_mock_subdir() - if @subdir - @file_writer.create_subdir(@subdir) - end + @file_writer.create_subdir(@subdir) end def create_mock_header_file(parsed_stuff) @@ -95,6 +93,7 @@ class CMockGenerator file << "/* AUTOGENERATED FILE. DO NOT EDIT. */\n" file << "#ifndef _#{define_name}_H\n" file << "#define _#{define_name}_H\n\n" + file << "#include \"#{@framework}.h\"\n" @includes_h_pre_orig_header.each {|inc| file << "#include #{inc}\n"} file << @config.orig_header_include_fmt.gsub(/%s/, "#{orig_filename}") + "\n" @includes_h_post_orig_header.each {|inc| file << "#include #{inc}\n"} @@ -144,7 +143,6 @@ class CMockGenerator file << "#include \n" file << "#include \n" file << "#include \n" - file << "#include \"#{@framework}.h\"\n" file << "#include \"cmock.h\"\n" @includes_c_pre_header.each {|inc| file << "#include #{inc}\n"} file << "#include \"#{header_file}\"\n" @@ -190,9 +188,15 @@ class CMockGenerator def create_mock_verify_function(file, functions) file << "void #{@clean_mock_name}_Verify(void)\n{\n" - verifications = functions.collect {|function| @plugins.run(:mock_verify, function)}.join - file << " UNITY_LINE_TYPE cmock_line = TEST_LINE_NUM;\n" unless verifications.empty? - file << verifications + verifications = functions.collect do |function| + v = @plugins.run(:mock_verify, function) + v.empty? ? v : [" call_instance = Mock.#{function[:name]}_CallInstance;\n", v] + end.join + unless verifications.empty? + file << " UNITY_LINE_TYPE cmock_line = TEST_LINE_NUM;\n" + file << " CMOCK_MEM_INDEX_TYPE call_instance;\n" + file << verifications + end file << "}\n\n" end diff --git a/test/vendor/ceedling/vendor/cmock/lib/cmock_generator_plugin_callback.rb b/test/vendor/ceedling/vendor/cmock/lib/cmock_generator_plugin_callback.rb index da550859..564e0ac2 100644 --- a/test/vendor/ceedling/vendor/cmock/lib/cmock_generator_plugin_callback.rb +++ b/test/vendor/ceedling/vendor/cmock/lib/cmock_generator_plugin_callback.rb @@ -16,83 +16,73 @@ class CMockGeneratorPluginCallback @priority = 6 @include_count = @config.callback_include_count - if (@config.callback_after_arg_check) - alias :mock_implementation :mock_implementation_for_callbacks_after_arg_check - alias :mock_implementation_precheck :nothing - else - alias :mock_implementation_precheck :mock_implementation_for_callbacks_without_arg_check - alias :mock_implementation :nothing - end end def instance_structure(function) func_name = function[:name] - " CMOCK_#{func_name}_CALLBACK #{func_name}_CallbackFunctionPointer;\n" + + " int #{func_name}_CallbackBool;\n" \ + " CMOCK_#{func_name}_CALLBACK #{func_name}_CallbackFunctionPointer;\n" \ " int #{func_name}_CallbackCalls;\n" end def mock_function_declarations(function) func_name = function[:name] return_type = function[:return][:type] + action = @config.callback_after_arg_check ? 'AddCallback' : 'Stub' style = (@include_count ? 1 : 0) | (function[:args].empty? ? 0 : 2) styles = [ "void", "int cmock_num_calls", function[:args_string], "#{function[:args_string]}, int cmock_num_calls" ] - "typedef #{return_type} (* CMOCK_#{func_name}_CALLBACK)(#{styles[style]});\nvoid #{func_name}_StubWithCallback(CMOCK_#{func_name}_CALLBACK Callback);\n" + "typedef #{return_type} (* CMOCK_#{func_name}_CALLBACK)(#{styles[style]});\n" \ + "void #{func_name}_AddCallback(CMOCK_#{func_name}_CALLBACK Callback);\n" \ + "void #{func_name}_Stub(CMOCK_#{func_name}_CALLBACK Callback);\n" \ + "#define #{func_name}_StubWithCallback #{func_name}_#{action}\n" end - def mock_implementation_for_callbacks_after_arg_check(function) - func_name = function[:name] - style = (@include_count ? 1 : 0) | (function[:args].empty? ? 0 : 2) | (function[:return][:void?] ? 0 : 4) - " if (Mock.#{func_name}_CallbackFunctionPointer != NULL)\n {\n" + - case(style) - when 0 then " Mock.#{func_name}_CallbackFunctionPointer();\n }\n" - when 1 then " Mock.#{func_name}_CallbackFunctionPointer(Mock.#{func_name}_CallbackCalls++);\n }\n" - when 2 then " Mock.#{func_name}_CallbackFunctionPointer(#{function[:args].map{|m| m[:name]}.join(', ')});\n }\n" - when 3 then " Mock.#{func_name}_CallbackFunctionPointer(#{function[:args].map{|m| m[:name]}.join(', ')}, Mock.#{func_name}_CallbackCalls++);\n }\n" - when 4 then " cmock_call_instance->ReturnVal = Mock.#{func_name}_CallbackFunctionPointer();\n }\n" - when 5 then " cmock_call_instance->ReturnVal = Mock.#{func_name}_CallbackFunctionPointer(Mock.#{func_name}_CallbackCalls++);\n }\n" - when 6 then " cmock_call_instance->ReturnVal = Mock.#{func_name}_CallbackFunctionPointer(#{function[:args].map{|m| m[:name]}.join(', ')});\n }\n" - when 7 then " cmock_call_instance->ReturnVal = Mock.#{func_name}_CallbackFunctionPointer(#{function[:args].map{|m| m[:name]}.join(', ')}, Mock.#{func_name}_CallbackCalls++);\n }\n" - end + def generate_call(function) + args = function[:args].map { |m| m[:name] } + args << "Mock.#{function[:name]}_CallbackCalls++" if @include_count + "Mock.#{function[:name]}_CallbackFunctionPointer(#{args.join(', ')})" end - def mock_implementation_for_callbacks_without_arg_check(function) - func_name = function[:name] - style = (@include_count ? 1 : 0) | (function[:args].empty? ? 0 : 2) | (function[:return][:void?] ? 0 : 4) - " if (Mock.#{func_name}_CallbackFunctionPointer != NULL)\n {\n" + - case(style) - when 0 then " Mock.#{func_name}_CallbackFunctionPointer();\n return;\n }\n" - when 1 then " Mock.#{func_name}_CallbackFunctionPointer(Mock.#{func_name}_CallbackCalls++);\n return;\n }\n" - when 2 then " Mock.#{func_name}_CallbackFunctionPointer(#{function[:args].map{|m| m[:name]}.join(', ')});\n return;\n }\n" - when 3 then " Mock.#{func_name}_CallbackFunctionPointer(#{function[:args].map{|m| m[:name]}.join(', ')}, Mock.#{func_name}_CallbackCalls++);\n return;\n }\n" - when 4 then " return Mock.#{func_name}_CallbackFunctionPointer();\n }\n" - when 5 then " return Mock.#{func_name}_CallbackFunctionPointer(Mock.#{func_name}_CallbackCalls++);\n }\n" - when 6 then " return Mock.#{func_name}_CallbackFunctionPointer(#{function[:args].map{|m| m[:name]}.join(', ')});\n }\n" - when 7 then " return Mock.#{func_name}_CallbackFunctionPointer(#{function[:args].map{|m| m[:name]}.join(', ')}, Mock.#{func_name}_CallbackCalls++);\n }\n" - end + def mock_implementation(function) + " if (Mock.#{function[:name]}_CallbackFunctionPointer != NULL)\n {\n" + + if function[:return][:void?] + " #{generate_call(function)};\n }\n" + else + " cmock_call_instance->ReturnVal = #{generate_call(function)};\n }\n" + end end - def nothing(function) - return "" + def mock_implementation_precheck(function) + " if (!Mock.#{function[:name]}_CallbackBool &&\n" \ + " Mock.#{function[:name]}_CallbackFunctionPointer != NULL)\n {\n" + + if function[:return][:void?] + " #{generate_call(function)};\n" \ + " UNITY_CLR_DETAILS();\n" \ + " return;\n }\n" + else + " #{function[:return][:type]} ret = #{generate_call(function)};\n" \ + " UNITY_CLR_DETAILS();\n" \ + " return ret;\n }\n" + end end def mock_interfaces(function) func_name = function[:name] + has_ignore = @config.plugins.include? :ignore lines = "" - lines << "void #{func_name}_StubWithCallback(CMOCK_#{func_name}_CALLBACK Callback)\n{\n" - if @config.plugins.include? :ignore - lines << " Mock.#{func_name}_IgnoreBool = (int)0;\n" - end + lines << "void #{func_name}_AddCallback(CMOCK_#{func_name}_CALLBACK Callback)\n{\n" + lines << " Mock.#{func_name}_IgnoreBool = (int)0;\n" if has_ignore + lines << " Mock.#{func_name}_CallbackBool = (int)1;\n" + lines << " Mock.#{func_name}_CallbackFunctionPointer = Callback;\n}\n\n" + lines << "void #{func_name}_Stub(CMOCK_#{func_name}_CALLBACK Callback)\n{\n" + lines << " Mock.#{func_name}_IgnoreBool = (int)0;\n" if has_ignore + lines << " Mock.#{func_name}_CallbackBool = (int)0;\n" lines << " Mock.#{func_name}_CallbackFunctionPointer = Callback;\n}\n\n" - end - - def mock_destroy(function) - " Mock.#{function[:name]}_CallbackFunctionPointer = NULL;\n" + - " Mock.#{function[:name]}_CallbackCalls = 0;\n" end def mock_verify(function) func_name = function[:name] - " if (Mock.#{func_name}_CallbackFunctionPointer != NULL)\n Mock.#{func_name}_CallInstance = CMOCK_GUTS_NONE;\n" + " if (Mock.#{func_name}_CallbackFunctionPointer != NULL)\n call_instance = CMOCK_GUTS_NONE;\n" end end diff --git a/test/vendor/ceedling/vendor/cmock/lib/cmock_generator_plugin_expect.rb b/test/vendor/ceedling/vendor/cmock/lib/cmock_generator_plugin_expect.rb index 19fb41b6..dcf96f2e 100644 --- a/test/vendor/ceedling/vendor/cmock/lib/cmock_generator_plugin_expect.rb +++ b/test/vendor/ceedling/vendor/cmock/lib/cmock_generator_plugin_expect.rb @@ -64,7 +64,7 @@ class CMockGeneratorPluginExpect def mock_implementation_might_check_args(function) return "" if (function[:args].empty?) - lines = " if (cmock_call_instance->IgnoreMode != CMOCK_ARG_NONE)\n {\n" + lines = " if (!cmock_call_instance->ExpectAnyArgsBool)\n {\n" function[:args].each do |arg| lines << @utils.code_verify_an_arg_expectation(function, arg) end @@ -91,14 +91,13 @@ class CMockGeneratorPluginExpect lines << @utils.code_add_base_expectation(func_name) lines << @utils.code_call_argument_loader(function) lines << @utils.code_assign_argument_quickly("cmock_call_instance->ReturnVal", function[:return]) unless (function[:return][:void?]) - lines << " UNITY_CLR_DETAILS();\n" lines << "}\n\n" end def mock_verify(function) - func_name = function[:name] " UNITY_SET_DETAIL(CMockString_#{function[:name]});\n" + - " UNITY_TEST_ASSERT(CMOCK_GUTS_NONE == Mock.#{func_name}_CallInstance, cmock_line, CMockStringCalledLess);\n" + " UNITY_TEST_ASSERT(CMOCK_GUTS_NONE == call_instance, cmock_line, CMockStringCalledLess);\n" + + " UNITY_CLR_DETAILS();\n" end end diff --git a/test/vendor/ceedling/vendor/cmock/lib/cmock_generator_plugin_expect_any_args.rb b/test/vendor/ceedling/vendor/cmock/lib/cmock_generator_plugin_expect_any_args.rb index 0e80844b..0c1c74e9 100644 --- a/test/vendor/ceedling/vendor/cmock/lib/cmock_generator_plugin_expect_any_args.rb +++ b/test/vendor/ceedling/vendor/cmock/lib/cmock_generator_plugin_expect_any_args.rb @@ -15,40 +15,39 @@ class CMockGeneratorPluginExpectAnyArgs @priority = 3 end - def instance_structure(function) - if (function[:return][:void?]) || (@config.plugins.include? :ignore) - "" - else - " #{function[:return][:type]} #{function[:name]}_FinalReturn;\n" - end - end - def instance_typedefs(function) - " CMOCK_ARG_MODE IgnoreMode;\n" + " int ExpectAnyArgsBool;\n" end def mock_function_declarations(function) - if (function[:return][:void?]) - return "#define #{function[:name]}_ExpectAnyArgs() #{function[:name]}_CMockExpectAnyArgs(__LINE__)\n" + - "void #{function[:name]}_CMockExpectAnyArgs(UNITY_LINE_TYPE cmock_line);\n" + unless (function[:args].empty?) + if (function[:return][:void?]) + return "#define #{function[:name]}_ExpectAnyArgs() #{function[:name]}_CMockExpectAnyArgs(__LINE__)\n" + + "void #{function[:name]}_CMockExpectAnyArgs(UNITY_LINE_TYPE cmock_line);\n" + else + return "#define #{function[:name]}_ExpectAnyArgsAndReturn(cmock_retval) #{function[:name]}_CMockExpectAnyArgsAndReturn(__LINE__, cmock_retval)\n" + + "void #{function[:name]}_CMockExpectAnyArgsAndReturn(UNITY_LINE_TYPE cmock_line, #{function[:return][:str]});\n" + end else - return "#define #{function[:name]}_ExpectAnyArgsAndReturn(cmock_retval) #{function[:name]}_CMockExpectAnyArgsAndReturn(__LINE__, cmock_retval)\n" + - "void #{function[:name]}_CMockExpectAnyArgsAndReturn(UNITY_LINE_TYPE cmock_line, #{function[:return][:str]});\n" + "" end end def mock_interfaces(function) lines = "" - if (function[:return][:void?]) - lines << "void #{function[:name]}_CMockExpectAnyArgs(UNITY_LINE_TYPE cmock_line)\n{\n" - else - lines << "void #{function[:name]}_CMockExpectAnyArgsAndReturn(UNITY_LINE_TYPE cmock_line, #{function[:return][:str]})\n{\n" + unless (function[:args].empty?) + if (function[:return][:void?]) + lines << "void #{function[:name]}_CMockExpectAnyArgs(UNITY_LINE_TYPE cmock_line)\n{\n" + else + lines << "void #{function[:name]}_CMockExpectAnyArgsAndReturn(UNITY_LINE_TYPE cmock_line, #{function[:return][:str]})\n{\n" + end + lines << @utils.code_add_base_expectation(function[:name], true) + unless (function[:return][:void?]) + lines << " cmock_call_instance->ReturnVal = cmock_to_return;\n" + end + lines << " cmock_call_instance->ExpectAnyArgsBool = (int)1;\n" + lines << "}\n\n" end - lines << @utils.code_add_base_expectation(function[:name], true) - unless (function[:return][:void?]) - lines << " cmock_call_instance->ReturnVal = cmock_to_return;\n" - end - lines << " cmock_call_instance->IgnoreMode = CMOCK_ARG_NONE;\n" - lines << "}\n\n" + return lines end end diff --git a/test/vendor/ceedling/vendor/cmock/lib/cmock_generator_plugin_ignore.rb b/test/vendor/ceedling/vendor/cmock/lib/cmock_generator_plugin_ignore.rb index a291dd4c..8f31967a 100644 --- a/test/vendor/ceedling/vendor/cmock/lib/cmock_generator_plugin_ignore.rb +++ b/test/vendor/ceedling/vendor/cmock/lib/cmock_generator_plugin_ignore.rb @@ -70,6 +70,6 @@ class CMockGeneratorPluginIgnore def mock_verify(function) func_name = function[:name] - " if (Mock.#{func_name}_IgnoreBool)\n Mock.#{func_name}_CallInstance = CMOCK_GUTS_NONE;\n" + " if (Mock.#{func_name}_IgnoreBool)\n call_instance = CMOCK_GUTS_NONE;\n" end end diff --git a/test/vendor/ceedling/vendor/cmock/lib/cmock_generator_plugin_return_thru_ptr.rb b/test/vendor/ceedling/vendor/cmock/lib/cmock_generator_plugin_return_thru_ptr.rb index 5c3a9597..1c1af061 100644 --- a/test/vendor/ceedling/vendor/cmock/lib/cmock_generator_plugin_return_thru_ptr.rb +++ b/test/vendor/ceedling/vendor/cmock/lib/cmock_generator_plugin_return_thru_ptr.rb @@ -24,7 +24,13 @@ class CMockGeneratorPluginReturnThruPtr function[:args].each do |arg| if (@utils.ptr_or_str?(arg[:type]) and not arg[:const?]) lines << "#define #{function[:name]}_ReturnThruPtr_#{arg[:name]}(#{arg[:name]})" - lines << " #{function[:name]}_CMockReturnMemThruPtr_#{arg[:name]}(__LINE__, #{arg[:name]}, sizeof(*#{arg[:name]}))\n" + # If the pointer type actually contains an asterisk, we can do sizeof the type (super safe), otherwise + # we need to do a sizeof the dereferenced pointer (which could be a problem if give the wrong size + if (arg[:type][-1] == '*') + lines << " #{function[:name]}_CMockReturnMemThruPtr_#{arg[:name]}(__LINE__, #{arg[:name]}, sizeof(#{arg[:type][0..-2]}))\n" + else + lines << " #{function[:name]}_CMockReturnMemThruPtr_#{arg[:name]}(__LINE__, #{arg[:name]}, sizeof(*#{arg[:name]}))\n" + end lines << "#define #{function[:name]}_ReturnArrayThruPtr_#{arg[:name]}(#{arg[:name]}, cmock_len)" lines << " #{function[:name]}_CMockReturnMemThruPtr_#{arg[:name]}(__LINE__, #{arg[:name]}, (int)(cmock_len * (int)sizeof(*#{arg[:name]})))\n" lines << "#define #{function[:name]}_ReturnMemThruPtr_#{arg[:name]}(#{arg[:name]}, cmock_size)" diff --git a/test/vendor/ceedling/vendor/cmock/lib/cmock_generator_utils.rb b/test/vendor/ceedling/vendor/cmock/lib/cmock_generator_utils.rb index eb12e236..994e85c5 100644 --- a/test/vendor/ceedling/vendor/cmock/lib/cmock_generator_utils.rb +++ b/test/vendor/ceedling/vendor/cmock/lib/cmock_generator_utils.rb @@ -19,7 +19,7 @@ class CMockGeneratorUtils @ignore_arg = @config.plugins.include? :ignore_arg @ignore = @config.plugins.include? :ignore @treat_as = @config.treat_as - @helpers = helpers + @helpers = helpers end def self.arg_type_with_const(arg) @@ -57,7 +57,7 @@ class CMockGeneratorUtils lines << " cmock_call_instance->LineNumber = cmock_line;\n" lines << " cmock_call_instance->CallOrder = ++GlobalExpectCount;\n" if (@ordered and global_ordering_supported) lines << " cmock_call_instance->ExceptionToThrow = CEXCEPTION_NONE;\n" if (@cexception) - lines << " cmock_call_instance->IgnoreMode = CMOCK_ARG_ALL;\n" if (@expect_any) + lines << " cmock_call_instance->ExpectAnyArgsBool = (int)0;\n" if (@expect_any) lines end @@ -73,7 +73,10 @@ class CMockGeneratorUtils if (arg[:ptr?] or @treat_as.include?(arg[:type])) " #{dest} = #{arg[:name]};\n" else - " memcpy(&#{dest}, &#{arg[:name]}, sizeof(#{arg[:type]}));\n" + assert_expr = "sizeof(#{arg[:name]}) == sizeof(#{arg[:type]}) ? 1 : -1" + comment = "/* add #{arg[:type]} to :treat_as_array if this causes an error */" + " memcpy((void*)(&#{dest}), (void*)(&#{arg[:name]}),\n" + + " sizeof(#{arg[:type]}[#{assert_expr}])); #{comment}\n" end end @@ -84,10 +87,12 @@ class CMockGeneratorUtils type = arg_type_with_const(m) m[:ptr?] ? "#{type} #{m[:name]}, int #{m[:name]}_Depth" : "#{type} #{m[:name]}" end.join(', ') + "void CMockExpectParameters_#{function[:name]}(CMOCK_#{function[:name]}_CALL_INSTANCE* cmock_call_instance, #{args_string});\n" + "void CMockExpectParameters_#{function[:name]}(CMOCK_#{function[:name]}_CALL_INSTANCE* cmock_call_instance, #{args_string})\n{\n" + function[:args].inject("") { |all, arg| all + code_add_an_arg_expectation(arg, (arg[:ptr?] ? "#{arg[:name]}_Depth" : 1) ) } + "}\n\n" else + "void CMockExpectParameters_#{function[:name]}(CMOCK_#{function[:name]}_CALL_INSTANCE* cmock_call_instance, #{function[:args_string]});\n" + "void CMockExpectParameters_#{function[:name]}(CMOCK_#{function[:name]}_CALL_INSTANCE* cmock_call_instance, #{function[:args_string]})\n{\n" + function[:args].inject("") { |all, arg| all + code_add_an_arg_expectation(arg) } + "}\n\n" @@ -100,7 +105,13 @@ class CMockGeneratorUtils def code_call_argument_loader(function) if (function[:args_string] != "void") args = function[:args].map do |m| - (@arrays and m[:ptr?]) ? "#{m[:name]}, 1" : m[:name] + if (@arrays and m[:ptr?] and not m[:array_data?]) + "#{m[:name]}, 1" + elsif (@arrays and m[:array_size?]) + "#{m[:name]}, #{m[:name]}" + else + m[:name] + end end " CMockExpectParameters_#{function[:name]}(cmock_call_instance, #{args.join(', ')});\n" else @@ -170,6 +181,7 @@ class CMockGeneratorUtils lines << " if (!#{ignore})\n" if @ignore_arg lines << " {\n" lines << " UNITY_SET_DETAILS(CMockString_#{function[:name]},CMockString_#{arg_name});\n" + lines << " if (#{pre}#{expected} != #{pre}#{arg_name}) {\n" case(unity_func) when "UNITY_TEST_ASSERT_EQUAL_MEMORY" c_type_local = c_type.gsub(/\*$/,'') @@ -195,7 +207,7 @@ class CMockGeneratorUtils else lines << " #{unity_func}(#{pre}#{expected}, #{pre}#{arg_name}, cmock_line, CMockStringMismatch);\n" end - lines << " }\n" + lines << " }\n }\n" lines end @@ -206,6 +218,7 @@ class CMockGeneratorUtils lines << " if (!#{ignore})\n" if @ignore_arg lines << " {\n" lines << " UNITY_SET_DETAILS(CMockString_#{function[:name]},CMockString_#{arg_name});\n" + lines << " if (#{pre}#{expected} != #{pre}#{arg_name}) {\n" case(unity_func) when "UNITY_TEST_ASSERT_EQUAL_MEMORY" c_type_local = c_type.gsub(/\*$/,'') @@ -233,7 +246,7 @@ class CMockGeneratorUtils else lines << " #{unity_func}(#{pre}#{expected}, #{pre}#{arg_name}, cmock_line, CMockStringMismatch);\n" end - lines << " }\n" + lines << " }\n }\n" lines end diff --git a/test/vendor/ceedling/vendor/cmock/lib/cmock_header_parser.rb b/test/vendor/ceedling/vendor/cmock/lib/cmock_header_parser.rb index ee0fe6ab..0cf19478 100644 --- a/test/vendor/ceedling/vendor/cmock/lib/cmock_header_parser.rb +++ b/test/vendor/ceedling/vendor/cmock/lib/cmock_header_parser.rb @@ -14,9 +14,12 @@ class CMockHeaderParser @c_attr_noconst = cfg.attributes.uniq - ['const'] @c_attributes = ['const'] + c_attr_noconst @c_calling_conventions = cfg.c_calling_conventions.uniq + @treat_as_array = cfg.treat_as_array @treat_as_void = (['void'] + cfg.treat_as_void).uniq - @declaration_parse_matcher = /([\d\w\s\*\(\),\[\]]+??)\(([\d\w\s\*\(\),\.\[\]+-]*)\)$/m + @declaration_parse_matcher = /([\w\s\*\(\),\[\]]+??)\(([\w\s\*\(\),\.\[\]+-]*)\)$/m @standards = (['int','short','char','long','unsigned','signed'] + cfg.treat_as.keys).uniq + @array_size_name = cfg.array_size_name + @array_size_type = (['int', 'size_t'] + cfg.array_size_type).uniq @when_no_prototypes = cfg.when_no_prototypes @local_as_void = @treat_as_void @verbosity = cfg.verbosity @@ -54,7 +57,7 @@ class CMockHeaderParser # void must be void for cmock _ExpectAndReturn calls to process properly, not some weird typedef which equates to void # to a certain extent, this action assumes we're chewing on pre-processed header files, otherwise we'll most likely just get stuff from @treat_as_void @local_as_void = @treat_as_void - void_types = source.scan(/typedef\s+(?:\(\s*)?void(?:\s*\))?\s+([\w\d]+)\s*;/) + void_types = source.scan(/typedef\s+(?:\(\s*)?void(?:\s*\))?\s+([\w]+)\s*;/) if void_types @local_as_void += void_types.flatten.uniq.compact end @@ -63,9 +66,9 @@ class CMockHeaderParser source.gsub!(/\s*\\\s*/m, ' ') #remove comments (block and line, in three steps to ensure correct precedence) - source.gsub!(/\/\/(?:.+\/\*|\*(?:$|[^\/])).*$/, '') # remove line comments that comment out the start of blocks - source.gsub!(/\/\*.*?\*\//m, '') # remove block comments - source.gsub!(/\/\/.*$/, '') # remove line comments (all that remain) + source.gsub!(/(? * , <@array_size_type> <@array_size_name> + args.each_with_index {|val, index| + next_index = index + 1 + if (args.length > next_index) + if (val[:ptr?] == true and args[next_index][:name].match(@array_size_name) and @array_size_type.include?(args[next_index][:type])) + val[:array_data?] = true + args[next_index][:array_size?] = true + end + end + } + return args end @@ -220,7 +247,7 @@ class CMockHeaderParser return 'void' else c=0 - arg_list.gsub!(/(\w+)(?:\s*\[\s*\(*[\s\d\w+-]*\)*\s*\])+/,'*\1') # magically turn brackets into asterisks, also match for parentheses that come from macros + arg_list.gsub!(/(\w+)(?:\s*\[\s*\(*[\s\w+-]*\)*\s*\])+/,'*\1') # magically turn brackets into asterisks, also match for parentheses that come from macros arg_list.gsub!(/\s+\*/,'*') # remove space to place asterisks with type (where they belong) arg_list.gsub!(/\*(\w)/,'* \1') # pull asterisks away from arg to place asterisks with type (where they belong) diff --git a/test/vendor/ceedling/vendor/cmock/src/cmock.c b/test/vendor/ceedling/vendor/cmock/src/cmock.c index 318f4c7a..5e5cb6c7 100644 --- a/test/vendor/ceedling/vendor/cmock/src/cmock.c +++ b/test/vendor/ceedling/vendor/cmock/src/cmock.c @@ -4,13 +4,12 @@ [Released under MIT License. Please refer to license.txt for details] ========================================== */ -#include "unity.h" #include "cmock.h" //public constants to be used by mocks const char* CMockStringOutOfMemory = "CMock has run out of memory. Please allocate more."; const char* CMockStringCalledMore = "Called more times than expected."; -const char* CMockStringCalledLess = "Called less times than expected."; +const char* CMockStringCalledLess = "Called fewer times than expected."; const char* CMockStringCalledEarly = "Called earlier than expected."; const char* CMockStringCalledLate = "Called later than expected."; const char* CMockStringCallOrder = "Called out of order."; @@ -24,12 +23,11 @@ const char* CMockStringMismatch = "Function called with unexpected argument v #ifdef CMOCK_MEM_DYNAMIC static unsigned char* CMock_Guts_Buffer = NULL; static CMOCK_MEM_INDEX_TYPE CMock_Guts_BufferSize = CMOCK_MEM_ALIGN_SIZE; -static CMOCK_MEM_INDEX_TYPE CMock_Guts_FreePtr; +static CMOCK_MEM_INDEX_TYPE CMock_Guts_FreePtr = CMOCK_MEM_ALIGN_SIZE; #else -static CMOCK_MEM_INDEX_TYPE CMock_Guts_BufferArray[(CMOCK_MEM_SIZE + CMOCK_MEM_INDEX_SIZE - 1) / CMOCK_MEM_INDEX_SIZE]; -#define CMock_Guts_Buffer ((unsigned char*)CMock_Guts_BufferArray) +static unsigned char CMock_Guts_Buffer[CMOCK_MEM_SIZE + CMOCK_MEM_ALIGN_SIZE]; static CMOCK_MEM_INDEX_TYPE CMock_Guts_BufferSize = CMOCK_MEM_SIZE + CMOCK_MEM_ALIGN_SIZE; -static CMOCK_MEM_INDEX_TYPE CMock_Guts_FreePtr; +static CMOCK_MEM_INDEX_TYPE CMock_Guts_FreePtr = CMOCK_MEM_ALIGN_SIZE; #endif //------------------------------------------------------- @@ -169,6 +167,14 @@ void* CMock_Guts_GetAddressFor(CMOCK_MEM_INDEX_TYPE index) } } +//------------------------------------------------------- +// CMock_Guts_MemBytesCapacity +//------------------------------------------------------- +CMOCK_MEM_INDEX_TYPE CMock_Guts_MemBytesCapacity(void) +{ + return (sizeof(CMock_Guts_Buffer) - CMOCK_MEM_ALIGN_SIZE); +} + //------------------------------------------------------- // CMock_Guts_MemBytesFree //------------------------------------------------------- diff --git a/test/vendor/ceedling/vendor/cmock/src/cmock.h b/test/vendor/ceedling/vendor/cmock/src/cmock.h index a3134480..e96546da 100644 --- a/test/vendor/ceedling/vendor/cmock/src/cmock.h +++ b/test/vendor/ceedling/vendor/cmock/src/cmock.h @@ -9,6 +9,11 @@ #include "cmock_internals.h" +#define CMOCK_VERSION_MAJOR 2 +#define CMOCK_VERSION_MINOR 5 +#define CMOCK_VERSION_BUILD 0 +#define CMOCK_VERSION ((CMOCK_VERSION_MAJOR << 16) | (CMOCK_VERSION_MINOR << 8) | CMOCK_VERSION_BUILD) + //should be big enough to index full range of CMOCK_MEM_MAX #ifndef CMOCK_MEM_INDEX_TYPE #define CMOCK_MEM_INDEX_TYPE unsigned int @@ -16,10 +21,6 @@ #define CMOCK_GUTS_NONE (0) -#define CMOCK_ARG_MODE CMOCK_MEM_INDEX_TYPE -#define CMOCK_ARG_ALL 0 -#define CMOCK_ARG_NONE ((CMOCK_MEM_INDEX_TYPE)(~0U)) - //------------------------------------------------------- // Memory API //------------------------------------------------------- @@ -30,6 +31,7 @@ CMOCK_MEM_INDEX_TYPE CMock_Guts_MemEndOfChain(CMOCK_MEM_INDEX_TYPE root_index); void* CMock_Guts_GetAddressFor(CMOCK_MEM_INDEX_TYPE index); +CMOCK_MEM_INDEX_TYPE CMock_Guts_MemBytesCapacity(void); CMOCK_MEM_INDEX_TYPE CMock_Guts_MemBytesFree(void); CMOCK_MEM_INDEX_TYPE CMock_Guts_MemBytesUsed(void); void CMock_Guts_MemFreeAll(void); diff --git a/test/vendor/ceedling/vendor/cmock/src/cmock_internals.h b/test/vendor/ceedling/vendor/cmock/src/cmock_internals.h index 5c922adf..ae2e4962 100644 --- a/test/vendor/ceedling/vendor/cmock/src/cmock_internals.h +++ b/test/vendor/ceedling/vendor/cmock/src/cmock_internals.h @@ -7,6 +7,8 @@ #ifndef CMOCK_FRAMEWORK_INTERNALS_H #define CMOCK_FRAMEWORK_INTERNALS_H +#include "unity.h" + //These are constants that the generated mocks have access to extern const char* CMockStringOutOfMemory; extern const char* CMockStringCalledMore; diff --git a/test/vendor/ceedling/vendor/unity/auto/colour_prompt.rb b/test/vendor/ceedling/vendor/unity/auto/colour_prompt.rb index 0f1dc4e0..85cbfd80 100644 --- a/test/vendor/ceedling/vendor/unity/auto/colour_prompt.rb +++ b/test/vendor/ceedling/vendor/unity/auto/colour_prompt.rb @@ -22,9 +22,10 @@ end class ColourCommandLine def initialize return unless RUBY_PLATFORM =~ /(win|w)32$/ + get_std_handle = Win32API.new('kernel32', 'GetStdHandle', ['L'], 'L') @set_console_txt_attrb = - Win32API.new('kernel32', 'SetConsoleTextAttribute', %w(L N), 'I') + Win32API.new('kernel32', 'SetConsoleTextAttribute', %w[L N], 'I') @hout = get_std_handle.call(-11) end @@ -107,7 +108,7 @@ class ColourCommandLine $stdout.print("#{change_to(colour)}#{str}\033[0m") if mode == :print end end -end # ColourCommandLine +end def colour_puts(role, str) ColourCommandLine.new.out_c(:puts, role, str) diff --git a/test/vendor/ceedling/vendor/unity/auto/colour_reporter.rb b/test/vendor/ceedling/vendor/unity/auto/colour_reporter.rb index bb1fbfce..1c3bc216 100644 --- a/test/vendor/ceedling/vendor/unity/auto/colour_reporter.rb +++ b/test/vendor/ceedling/vendor/unity/auto/colour_reporter.rb @@ -4,7 +4,7 @@ # [Released under MIT License. Please refer to license.txt for details] # ========================================== -require "#{File.expand_path(File.dirname(__FILE__))}/colour_prompt" +require_relative 'colour_prompt' $colour_output = true diff --git a/test/vendor/ceedling/vendor/unity/auto/generate_module.rb b/test/vendor/ceedling/vendor/unity/auto/generate_module.rb index 13b4cc74..eb2cebd4 100644 --- a/test/vendor/ceedling/vendor/unity/auto/generate_module.rb +++ b/test/vendor/ceedling/vendor/unity/auto/generate_module.rb @@ -14,6 +14,7 @@ require 'pathname' # TEMPLATE_TST TEMPLATE_TST ||= '#include "unity.h" + %2$s#include "%1$s.h" void setUp(void) @@ -35,18 +36,16 @@ TEMPLATE_SRC ||= '%2$s#include "%1$s.h" '.freeze # TEMPLATE_INC -TEMPLATE_INC ||= '#ifndef _%3$s_H -#define _%3$s_H +TEMPLATE_INC ||= '#ifndef %3$s_H +#define %3$s_H %2$s -#endif // _%3$s_H +#endif // %3$s_H '.freeze class UnityModuleGenerator ############################ def initialize(options = nil) - here = File.expand_path(File.dirname(__FILE__)) + '/' - @options = UnityModuleGenerator.default_options case options when NilClass then @options @@ -56,9 +55,9 @@ class UnityModuleGenerator end # Create default file paths if none were provided - @options[:path_src] = here + '../src/' if @options[:path_src].nil? - @options[:path_inc] = @options[:path_src] if @options[:path_inc].nil? - @options[:path_tst] = here + '../test/' if @options[:path_tst].nil? + @options[:path_src] = "#{__dir__}/../src/" if @options[:path_src].nil? + @options[:path_inc] = @options[:path_src] if @options[:path_inc].nil? + @options[:path_tst] = "#{__dir__}/../test/" if @options[:path_tst].nil? @options[:path_src] += '/' unless @options[:path_src][-1] == 47 @options[:path_inc] += '/' unless @options[:path_inc][-1] == 47 @options[:path_tst] += '/' unless @options[:path_tst][-1] == 47 @@ -265,6 +264,7 @@ if $0 == __FILE__ when /^-y\"?(.+)\"?/ then options = UnityModuleGenerator.grab_config(Regexp.last_match(1)) when /^(\w+)/ raise "ERROR: You can't have more than one Module name specified!" unless module_name.nil? + module_name = arg when /^-(h|-help)/ ARGV = [].freeze @@ -299,6 +299,7 @@ if $0 == __FILE__ end raise 'ERROR: You must have a Module name specified! (use option -h for help)' if module_name.nil? + if destroy UnityModuleGenerator.new(options).destroy(module_name) else diff --git a/test/vendor/ceedling/vendor/unity/auto/generate_test_runner.rb b/test/vendor/ceedling/vendor/unity/auto/generate_test_runner.rb index 84daa42d..5053210d 100644 --- a/test/vendor/ceedling/vendor/unity/auto/generate_test_runner.rb +++ b/test/vendor/ceedling/vendor/unity/auto/generate_test_runner.rb @@ -4,18 +4,25 @@ # [Released under MIT License. Please refer to license.txt for details] # ========================================== -File.expand_path(File.join(File.dirname(__FILE__), 'colour_prompt')) - class UnityTestRunnerGenerator def initialize(options = nil) @options = UnityTestRunnerGenerator.default_options case options - when NilClass then @options - when String then @options.merge!(UnityTestRunnerGenerator.grab_config(options)) - when Hash then @options.merge!(options) - else raise 'If you specify arguments, it should be a filename or a hash of options' + when NilClass + @options + when String + @options.merge!(UnityTestRunnerGenerator.grab_config(options)) + when Hash + # Check if some of these have been specified + @options[:has_setup] = !options[:setup_name].nil? + @options[:has_teardown] = !options[:teardown_name].nil? + @options[:has_suite_setup] = !options[:suite_setup].nil? + @options[:has_suite_teardown] = !options[:suite_teardown].nil? + @options.merge!(options) + else + raise 'If you specify arguments, it should be a filename or a hash of options' end - require "#{File.expand_path(File.dirname(__FILE__))}/type_sanitizer" + require_relative 'type_sanitizer' end def self.default_options @@ -29,9 +36,12 @@ class UnityTestRunnerGenerator mock_suffix: '', setup_name: 'setUp', teardown_name: 'tearDown', + test_reset_name: 'resetTest', + test_verify_name: 'verifyTest', main_name: 'main', # set to :auto to automatically generate each time main_export_decl: '', cmdline_args: false, + omit_begin_end: false, use_param_tests: false } end @@ -53,12 +63,13 @@ class UnityTestRunnerGenerator # pull required data from source file source = File.read(input_file) source = source.force_encoding('ISO-8859-1').encode('utf-8', replace: nil) - tests = find_tests(source) - headers = find_includes(source) - testfile_includes = (headers[:local] + headers[:system]) - used_mocks = find_mocks(testfile_includes) - testfile_includes = (testfile_includes - used_mocks) + tests = find_tests(source) + headers = find_includes(source) + testfile_includes = (headers[:local] + headers[:system]) + used_mocks = find_mocks(testfile_includes) + testfile_includes = (testfile_includes - used_mocks) testfile_includes.delete_if { |inc| inc =~ /(unity|cmock)/ } + find_setup_and_teardown(source) # build runner file generate(input_file, output_file, tests, used_mocks, testfile_includes) @@ -76,9 +87,13 @@ class UnityTestRunnerGenerator create_header(output, used_mocks, testfile_includes) create_externs(output, tests, used_mocks) create_mock_management(output, used_mocks) + create_setup(output) + create_teardown(output) create_suite_setup(output) create_suite_teardown(output) - create_reset(output, used_mocks) + create_reset(output) + create_run_test(output) + create_args_wrappers(output, tests) create_main(output, input_file, tests, used_mocks) end @@ -92,27 +107,43 @@ class UnityTestRunnerGenerator def find_tests(source) tests_and_line_numbers = [] + # contains characters which will be substituted from within strings, doing + # this prevents these characters from interferring with scrubbers + # @ is not a valid C character, so there should be no clashes with files genuinely containing these markers + substring_subs = { '{' => '@co@', '}' => '@cc@', ';' => '@ss@', '/' => '@fs@' } + substring_re = Regexp.union(substring_subs.keys) + substring_unsubs = substring_subs.invert # the inverse map will be used to fix the strings afterwords + substring_unsubs['@quote@'] = '\\"' + substring_unsubs['@apos@'] = '\\\'' + substring_unre = Regexp.union(substring_unsubs.keys) source_scrubbed = source.clone - source_scrubbed = source_scrubbed.gsub(/"[^"\n]*"/, '') # remove things in strings - source_scrubbed = source_scrubbed.gsub(/\/\/.*$/, '') # remove line comments - source_scrubbed = source_scrubbed.gsub(/\/\*.*?\*\//m, '') # remove block comments - lines = source_scrubbed.split(/(^\s*\#.*$) # Treat preprocessor directives as a logical line - | (;|\{|\}) /x) # Match ;, {, and } as end of lines + source_scrubbed = source_scrubbed.gsub(/\\"/, '@quote@') # hide escaped quotes to allow capture of the full string/char + source_scrubbed = source_scrubbed.gsub(/\\'/, '@apos@') # hide escaped apostrophes to allow capture of the full string/char + source_scrubbed = source_scrubbed.gsub(/("[^"\n]*")|('[^'\n]*')/) { |s| s.gsub(substring_re, substring_subs) } # temporarily hide problematic characters within strings + source_scrubbed = source_scrubbed.gsub(/\/\/(?:.+\/\*|\*(?:$|[^\/])).*$/, '') # remove line comments that comment out the start of blocks + source_scrubbed = source_scrubbed.gsub(/\/\*.*?\*\//m, '') # remove block comments + source_scrubbed = source_scrubbed.gsub(/\/\/.*$/, '') # remove line comments (all that remain) + lines = source_scrubbed.split(/(^\s*\#.*$) | (;|\{|\}) /x) # Treat preprocessor directives as a logical line. Match ;, {, and } as end of lines + .map { |line| line.gsub(substring_unre, substring_unsubs) } # unhide the problematic characters previously removed lines.each_with_index do |line, _index| # find tests - next unless line =~ /^((?:\s*TEST_CASE\s*\(.*?\)\s*)*)\s*void\s+((?:#{@options[:test_prefix]}).*)\s*\(\s*(.*)\s*\)/ + next unless line =~ /^((?:\s*TEST_CASE\s*\(.*?\)\s*)*)\s*void\s+((?:#{@options[:test_prefix]}).*)\s*\(\s*(.*)\s*\)/m + arguments = Regexp.last_match(1) name = Regexp.last_match(2) call = Regexp.last_match(3) params = Regexp.last_match(4) args = nil + if @options[:use_param_tests] && !arguments.empty? args = [] arguments.scan(/\s*TEST_CASE\s*\((.*)\)\s*$/) { |a| args << a[0] } end + tests_and_line_numbers << { test: name, args: args, call: call, params: params, line_number: 0 } end + tests_and_line_numbers.uniq! { |v| v[:test] } # determine line numbers and create tests to run @@ -121,6 +152,7 @@ class UnityTestRunnerGenerator tests_and_line_numbers.size.times do |i| source_lines[source_index..-1].each_with_index do |line, index| next unless line =~ /\s+#{tests_and_line_numbers[i][:test]}(?:\s|\()/ + source_index += index tests_and_line_numbers[i][:line_number] = source_index + 1 break @@ -154,21 +186,20 @@ class UnityTestRunnerGenerator mock_headers end + def find_setup_and_teardown(source) + @options[:has_setup] = source =~ /void\s+#{@options[:setup_name]}\s*\(/ + @options[:has_teardown] = source =~ /void\s+#{@options[:teardown_name]}\s*\(/ + @options[:has_suite_setup] ||= (source =~ /void\s+suiteSetUp\s*\(/) + @options[:has_suite_teardown] ||= (source =~ /void\s+suiteTearDown\s*\(/) + end + def create_header(output, mocks, testfile_includes = []) output.puts('/* AUTOGENERATED FILE. DO NOT EDIT. */') - create_runtest(output, mocks) output.puts("\n/*=======Automagically Detected Files To Include=====*/") - output.puts('#ifdef __WIN32__') - output.puts('#define UNITY_INCLUDE_SETUP_STUBS') - output.puts('#endif') output.puts("#include \"#{@options[:framework]}.h\"") output.puts('#include "cmock.h"') unless mocks.empty? - output.puts('#ifndef UNITY_EXCLUDE_SETJMP_H') - output.puts('#include ') - output.puts("#endif") - output.puts('#include ') if @options[:defines] && !@options[:defines].empty? - @options[:defines].each { |d| output.puts("#define #{d}") } + @options[:defines].each { |d| output.puts("#ifndef #{d}\n#define #{d}\n#endif /* #{d} */") } end if @options[:header_file] && !@options[:header_file].empty? output.puts("#include \"#{File.basename(@options[:header_file])}\"") @@ -197,15 +228,15 @@ class UnityTestRunnerGenerator output.puts("\n/*=======External Functions This Runner Calls=====*/") output.puts("extern void #{@options[:setup_name]}(void);") output.puts("extern void #{@options[:teardown_name]}(void);") + output.puts("\n#ifdef __cplusplus\nextern \"C\"\n{\n#endif") if @options[:externc] tests.each do |test| output.puts("extern void #{test[:test]}(#{test[:call] || 'void'});") end + output.puts("#ifdef __cplusplus\n}\n#endif") if @options[:externc] output.puts('') end def create_mock_management(output, mock_headers) - return if mock_headers.empty? - output.puts("\n/*=======Mock Management=====*/") output.puts('static void CMock_Init(void)') output.puts('{') @@ -240,84 +271,78 @@ class UnityTestRunnerGenerator output.puts("}\n") end + def create_setup(output) + return if @options[:has_setup] + + output.puts("\n/*=======Setup (stub)=====*/") + output.puts("void #{@options[:setup_name]}(void) {}") + end + + def create_teardown(output) + return if @options[:has_teardown] + + output.puts("\n/*=======Teardown (stub)=====*/") + output.puts("void #{@options[:teardown_name]}(void) {}") + end + def create_suite_setup(output) + return if @options[:suite_setup].nil? + output.puts("\n/*=======Suite Setup=====*/") - output.puts('static void suite_setup(void)') + output.puts('void suiteSetUp(void)') output.puts('{') - if @options[:suite_setup].nil? - # New style, call suiteSetUp() if we can use weak symbols - output.puts('#if defined(UNITY_WEAK_ATTRIBUTE) || defined(UNITY_WEAK_PRAGMA)') - output.puts(' suiteSetUp();') - output.puts('#endif') - else - # Old style, C code embedded in the :suite_setup option - output.puts(@options[:suite_setup]) - end + output.puts(@options[:suite_setup]) output.puts('}') end def create_suite_teardown(output) + return if @options[:suite_teardown].nil? + output.puts("\n/*=======Suite Teardown=====*/") - output.puts('static int suite_teardown(int num_failures)') + output.puts('int suiteTearDown(int num_failures)') output.puts('{') - if @options[:suite_teardown].nil? - # New style, call suiteTearDown() if we can use weak symbols - output.puts('#if defined(UNITY_WEAK_ATTRIBUTE) || defined(UNITY_WEAK_PRAGMA)') - output.puts(' return suiteTearDown(num_failures);') - output.puts('#else') - output.puts(' return num_failures;') - output.puts('#endif') - else - # Old style, C code embedded in the :suite_teardown option - output.puts(@options[:suite_teardown]) - end + output.puts(@options[:suite_teardown]) output.puts('}') end - def create_runtest(output, used_mocks) - cexception = @options[:plugins].include? :cexception - va_args1 = @options[:use_param_tests] ? ', ...' : '' - va_args2 = @options[:use_param_tests] ? '__VA_ARGS__' : '' - output.puts("\n/*=======Test Runner Used To Run Each Test Below=====*/") - output.puts('#define RUN_TEST_NO_ARGS') if @options[:use_param_tests] - output.puts("#define RUN_TEST(TestFunc, TestLineNum#{va_args1}) \\") - output.puts('{ \\') - output.puts(" Unity.CurrentTestName = #TestFunc#{va_args2.empty? ? '' : " \"(\" ##{va_args2} \")\""}; \\") - output.puts(' Unity.CurrentTestLineNumber = TestLineNum; \\') - output.puts(' if (UnityTestMatches()) { \\') if @options[:cmdline_args] - output.puts(' Unity.NumberOfTests++; \\') - output.puts(' CMock_Init(); \\') unless used_mocks.empty? - output.puts(' UNITY_CLR_DETAILS(); \\') unless used_mocks.empty? - output.puts(' if (TEST_PROTECT()) \\') - output.puts(' { \\') - output.puts(' CEXCEPTION_T e; \\') if cexception - output.puts(' Try { \\') if cexception - output.puts(" #{@options[:setup_name]}(); \\") - output.puts(" TestFunc(#{va_args2}); \\") - output.puts(' } Catch(e) { TEST_ASSERT_EQUAL_HEX32_MESSAGE(CEXCEPTION_NONE, e, "Unhandled Exception!"); } \\') if cexception - output.puts(' } \\') - output.puts(' if (TEST_PROTECT()) \\') - output.puts(' { \\') - output.puts(" #{@options[:teardown_name]}(); \\") - output.puts(' CMock_Verify(); \\') unless used_mocks.empty? - output.puts(' } \\') - output.puts(' CMock_Destroy(); \\') unless used_mocks.empty? - output.puts(' UnityConcludeTest(); \\') - output.puts(' } \\') if @options[:cmdline_args] - output.puts("}\n") - end - - def create_reset(output, used_mocks) - output.puts("\n/*=======Test Reset Option=====*/") - output.puts('void resetTest(void);') - output.puts('void resetTest(void)') + def create_reset(output) + output.puts("\n/*=======Test Reset Options=====*/") + output.puts("void #{@options[:test_reset_name]}(void);") + output.puts("void #{@options[:test_reset_name]}(void)") output.puts('{') - output.puts(' CMock_Verify();') unless used_mocks.empty? - output.puts(' CMock_Destroy();') unless used_mocks.empty? output.puts(" #{@options[:teardown_name]}();") - output.puts(' CMock_Init();') unless used_mocks.empty? + output.puts(' CMock_Verify();') + output.puts(' CMock_Destroy();') + output.puts(' CMock_Init();') output.puts(" #{@options[:setup_name]}();") output.puts('}') + output.puts("void #{@options[:test_verify_name]}(void);") + output.puts("void #{@options[:test_verify_name]}(void)") + output.puts('{') + output.puts(' CMock_Verify();') + output.puts('}') + end + + def create_run_test(output) + require 'erb' + template = ERB.new(File.read(File.join(__dir__, 'run_test.erb'))) + output.puts(template.result(binding)) + end + + def create_args_wrappers(output, tests) + return unless @options[:use_param_tests] + + output.puts("\n/*=======Parameterized Test Wrappers=====*/") + tests.each do |test| + next if test[:args].nil? || test[:args].empty? + + test[:args].each.with_index(1) do |args, idx| + output.puts("static void runner_args#{idx}_#{test[:test]}(void)") + output.puts('{') + output.puts(" #{test[:test]}(#{args});") + output.puts("}\n") + end + end end def create_main(output, filename, tests, used_mocks) @@ -336,48 +361,57 @@ class UnityTestRunnerGenerator output.puts(' {') output.puts(" UnityPrint(\"#{filename.gsub('.c', '')}.\");") output.puts(' UNITY_PRINT_EOL();') - if @options[:use_param_tests] - tests.each do |test| - if test[:args].nil? || test[:args].empty? - output.puts(" UnityPrint(\" #{test[:test]}(RUN_TEST_NO_ARGS)\");") + tests.each do |test| + if (!@options[:use_param_tests]) || test[:args].nil? || test[:args].empty? + output.puts(" UnityPrint(\" #{test[:test]}\");") + output.puts(' UNITY_PRINT_EOL();') + else + test[:args].each do |args| + output.puts(" UnityPrint(\" #{test[:test]}(#{args})\");") output.puts(' UNITY_PRINT_EOL();') - else - test[:args].each do |args| - output.puts(" UnityPrint(\" #{test[:test]}(#{args})\");") - output.puts(' UNITY_PRINT_EOL();') - end end end - else - tests.each { |test| output.puts(" UnityPrint(\" #{test[:test]}\");\n UNITY_PRINT_EOL();") } end - output.puts(' return 0;') + output.puts(' return 0;') output.puts(' }') - output.puts(' return parse_status;') + output.puts(' return parse_status;') output.puts(' }') else + main_return = @options[:omit_begin_end] ? 'void' : 'int' if main_name != 'main' - output.puts("#{@options[:main_export_decl]} int #{main_name}(void);") + output.puts("#{@options[:main_export_decl]} #{main_return} #{main_name}(void);") end - output.puts("int #{main_name}(void)") + output.puts("#{main_return} #{main_name}(void)") output.puts('{') end - output.puts(' suite_setup();') - output.puts(" UnityBegin(\"#{filename.gsub(/\\/, '\\\\\\')}\");") - if @options[:use_param_tests] - tests.each do |test| - if test[:args].nil? || test[:args].empty? - output.puts(" RUN_TEST(#{test[:test]}, #{test[:line_number]}, RUN_TEST_NO_ARGS);") - else - test[:args].each { |args| output.puts(" RUN_TEST(#{test[:test]}, #{test[:line_number]}, #{args});") } + output.puts(' suiteSetUp();') if @options[:has_suite_setup] + if @options[:omit_begin_end] + output.puts(" UnitySetTestFile(\"#{filename.gsub(/\\/, '\\\\\\')}\");") + else + output.puts(" UnityBegin(\"#{filename.gsub(/\\/, '\\\\\\')}\");") + end + tests.each do |test| + if (!@options[:use_param_tests]) || test[:args].nil? || test[:args].empty? + output.puts(" run_test(#{test[:test]}, \"#{test[:test]}\", #{test[:line_number]});") + else + test[:args].each.with_index(1) do |args, idx| + wrapper = "runner_args#{idx}_#{test[:test]}" + testname = "#{test[:test]}(#{args})".dump + output.puts(" run_test(#{wrapper}, #{testname}, #{test[:line_number]});") end end - else - tests.each { |test| output.puts(" RUN_TEST(#{test[:test]}, #{test[:line_number]});") } end output.puts output.puts(' CMock_Guts_MemFreeFinal();') unless used_mocks.empty? - output.puts(" return suite_teardown(UnityEnd());") + if @options[:has_suite_teardown] + if @options[:omit_begin_end] + output.puts(' (void) suite_teardown(0);') + else + output.puts(' return suiteTearDown(UnityEnd());') + end + else + output.puts(' return UnityEnd();') if not @options[:omit_begin_end] + end output.puts('}') end @@ -439,13 +473,17 @@ if $0 == __FILE__ ' *.h - header files are added as #includes in runner', ' options:', ' -cexception - include cexception support', + ' -externc - add extern "C" for cpp support', ' --setup_name="" - redefine setUp func name to something else', ' --teardown_name="" - redefine tearDown func name to something else', ' --main_name="" - redefine main func name to something else', ' --test_prefix="" - redefine test prefix from default test|spec|should', + ' --test_reset_name="" - redefine resetTest func name to something else', + ' --test_verify_name="" - redefine verifyTest func name to something else', ' --suite_setup="" - code to execute for setup of entire suite', ' --suite_teardown="" - code to execute for teardown of entire suite', ' --use_param_tests=1 - enable parameterized tests (disabled by default)', + ' --omit_begin_end=1 - omit calls to UnityBegin and UnityEnd (disabled by default)', ' --header_file="" - path/name of test header file to generate too'].join("\n") exit 1 end diff --git a/test/vendor/ceedling/vendor/unity/auto/parse_output.rb b/test/vendor/ceedling/vendor/unity/auto/parse_output.rb index f04508fb..d72c6e8b 100644 --- a/test/vendor/ceedling/vendor/unity/auto/parse_output.rb +++ b/test/vendor/ceedling/vendor/unity/auto/parse_output.rb @@ -34,9 +34,9 @@ class ParseOutput # current suite name and statistics @test_suite = nil - @total_tests = 0 - @test_passed = 0 - @test_failed = 0 + @total_tests = 0 + @test_passed = 0 + @test_failed = 0 @test_ignored = 0 end @@ -210,7 +210,7 @@ class ParseOutput # Adjusts the os specific members according to the current path style # (Windows or Unix based) - def set_os_specifics(line) + def detect_os_specifics(line) if line.include? '\\' # Windows X:\Y\Z @class_name_idx = 1 @@ -254,43 +254,42 @@ class ParseOutput # TEST() PASS # # Note: Where path is different on Unix vs Windows devices (Windows leads with a drive letter)! - set_os_specifics(line) + detect_os_specifics(line) line_array = line.split(':') # If we were able to split the line then we can look to see if any of our target words # were found. Case is important. - if (line_array.size >= 4) || (line.start_with? 'TEST(') || (line.start_with? 'IGNORE_TEST(') + next unless (line_array.size >= 4) || (line.start_with? 'TEST(') || (line.start_with? 'IGNORE_TEST(') - # check if the output is fixture output (with verbose flag "-v") - if (line.start_with? 'TEST(') || (line.start_with? 'IGNORE_TEST(') - line_array = prepare_fixture_line(line) - if line.include? ' PASS' - test_passed_unity_fixture(line_array) - @test_passed += 1 - elsif line.include? 'FAIL' - test_failed_unity_fixture(line_array) - @test_failed += 1 - elsif line.include? 'IGNORE' - test_ignored_unity_fixture(line_array) - @test_ignored += 1 - end - # normal output / fixture output (without verbose "-v") - elsif line.include? ':PASS' - test_passed(line_array) + # check if the output is fixture output (with verbose flag "-v") + if (line.start_with? 'TEST(') || (line.start_with? 'IGNORE_TEST(') + line_array = prepare_fixture_line(line) + if line.include? ' PASS' + test_passed_unity_fixture(line_array) @test_passed += 1 - elsif line.include? ':FAIL' - test_failed(line_array) + elsif line.include? 'FAIL' + test_failed_unity_fixture(line_array) @test_failed += 1 - elsif line.include? ':IGNORE:' - test_ignored(line_array) - @test_ignored += 1 - elsif line.include? ':IGNORE' - line_array.push('No reason given') - test_ignored(line_array) + elsif line.include? 'IGNORE' + test_ignored_unity_fixture(line_array) @test_ignored += 1 end - @total_tests = @test_passed + @test_failed + @test_ignored + # normal output / fixture output (without verbose "-v") + elsif line.include? ':PASS' + test_passed(line_array) + @test_passed += 1 + elsif line.include? ':FAIL' + test_failed(line_array) + @test_failed += 1 + elsif line.include? ':IGNORE:' + test_ignored(line_array) + @test_ignored += 1 + elsif line.include? ':IGNORE' + line_array.push('No reason given') + test_ignored(line_array) + @test_ignored += 1 end + @total_tests = @test_passed + @test_failed + @test_ignored end puts '' puts '=================== SUMMARY =====================' diff --git a/test/vendor/ceedling/vendor/unity/auto/stylize_as_junit.rb b/test/vendor/ceedling/vendor/unity/auto/stylize_as_junit.rb index b3d8f409..e01f7912 100644 --- a/test/vendor/ceedling/vendor/unity/auto/stylize_as_junit.rb +++ b/test/vendor/ceedling/vendor/unity/auto/stylize_as_junit.rb @@ -61,8 +61,8 @@ class ArgvParser opts.parse!(args) options - end # parse() -end # class OptparseExample + end +end class UnityToJUnit include FileUtils::Verbose @@ -152,11 +152,8 @@ class UnityToJUnit def parse_test_summary(summary) raise "Couldn't parse test results: #{summary}" unless summary.find { |v| v =~ /(\d+) Tests (\d+) Failures (\d+) Ignored/ } - [Regexp.last_match(1).to_i, Regexp.last_match(2).to_i, Regexp.last_match(3).to_i] - end - def here - File.expand_path(File.dirname(__FILE__)) + [Regexp.last_match(1).to_i, Regexp.last_match(2).to_i, Regexp.last_match(3).to_i] end private @@ -221,9 +218,9 @@ class UnityToJUnit def write_suites_footer(stream) stream.puts '' end -end # UnityToJUnit +end -if __FILE__ == $0 +if $0 == __FILE__ # parse out the command options options = ArgvParser.parse(ARGV) @@ -234,7 +231,9 @@ if __FILE__ == $0 targets = "#{options.results_dir.tr('\\', '/')}**/*.test*" results = Dir[targets] + raise "No *.testpass, *.testfail, or *.testresults files found in '#{targets}'" if results.empty? + utj.targets = results # set the root path diff --git a/test/vendor/ceedling/vendor/unity/auto/test_file_filter.rb b/test/vendor/ceedling/vendor/unity/auto/test_file_filter.rb index aad28e38..5c3a79fc 100644 --- a/test/vendor/ceedling/vendor/unity/auto/test_file_filter.rb +++ b/test/vendor/ceedling/vendor/unity/auto/test_file_filter.rb @@ -11,8 +11,8 @@ module RakefileHelpers def initialize(all_files = false) @all_files = all_files - return false unless @all_files - return false unless File.exist?('test_file_filter.yml') + return unless @all_files + return unless File.exist?('test_file_filter.yml') filters = YAML.load_file('test_file_filter.yml') @all_files = filters[:all_files] diff --git a/test/vendor/ceedling/vendor/unity/auto/unity_test_summary.py b/test/vendor/ceedling/vendor/unity/auto/unity_test_summary.py index 4c20e528..00c0da8c 100644 --- a/test/vendor/ceedling/vendor/unity/auto/unity_test_summary.py +++ b/test/vendor/ceedling/vendor/unity/auto/unity_test_summary.py @@ -121,7 +121,7 @@ if __name__ == '__main__': targets_dir = sys.argv[1] else: targets_dir = './' - targets = list(map(lambda x: x.replace('\\', '/'), glob(targets_dir + '*.test*'))) + targets = list(map(lambda x: x.replace('\\', '/'), glob(targets_dir + '**/*.test*', recursive=True))) if len(targets) == 0: raise Exception("No *.testpass or *.testfail files found in '%s'" % targets_dir) uts.set_targets(targets) diff --git a/test/vendor/ceedling/vendor/unity/auto/unity_test_summary.rb b/test/vendor/ceedling/vendor/unity/auto/unity_test_summary.rb index b37dc5fa..b3fe8a69 100644 --- a/test/vendor/ceedling/vendor/unity/auto/unity_test_summary.rb +++ b/test/vendor/ceedling/vendor/unity/auto/unity_test_summary.rb @@ -99,11 +99,8 @@ class UnityTestSummary def parse_test_summary(summary) raise "Couldn't parse test results: #{summary}" unless summary.find { |v| v =~ /(\d+) Tests (\d+) Failures (\d+) Ignored/ } - [Regexp.last_match(1).to_i, Regexp.last_match(2).to_i, Regexp.last_match(3).to_i] - end - def here - File.expand_path(File.dirname(__FILE__)) + [Regexp.last_match(1).to_i, Regexp.last_match(2).to_i, Regexp.last_match(3).to_i] end end @@ -121,7 +118,9 @@ if $0 == __FILE__ args[0] ||= './' targets = "#{ARGV[0].tr('\\', '/')}**/*.test*" results = Dir[targets] + raise "No *.testpass, *.testfail, or *.testresults files found in '#{targets}'" if results.empty? + uts.targets = results # set the root path diff --git a/test/vendor/ceedling/vendor/unity/src/unity.c b/test/vendor/ceedling/vendor/unity/src/unity.c index 103bde21..c7be02cc 100644 --- a/test/vendor/ceedling/vendor/unity/src/unity.c +++ b/test/vendor/ceedling/vendor/unity/src/unity.c @@ -1,13 +1,18 @@ /* ========================================================================= Unity Project - A Test Framework for C - Copyright (c) 2007-14 Mike Karlesky, Mark VanderVoord, Greg Williams + Copyright (c) 2007-19 Mike Karlesky, Mark VanderVoord, Greg Williams [Released under MIT License. Please refer to license.txt for details] ============================================================================ */ -#define UNITY_INCLUDE_SETUP_STUBS #include "unity.h" #include +#ifdef AVR +#include +#else +#define PROGMEM +#endif + /* If omitted from header, declare overrideable prototypes here so they're ready for use */ #ifdef UNITY_OMIT_OUTPUT_CHAR_HEADER_DECLARATION void UNITY_OUTPUT_CHAR(int); @@ -21,52 +26,105 @@ void UNITY_OUTPUT_CHAR(int); struct UNITY_STORAGE_T Unity; #ifdef UNITY_OUTPUT_COLOR -static const char UnityStrOk[] = "\033[42mOK\033[00m"; -static const char UnityStrPass[] = "\033[42mPASS\033[00m"; -static const char UnityStrFail[] = "\033[41mFAIL\033[00m"; -static const char UnityStrIgnore[] = "\033[43mIGNORE\033[00m"; +const char PROGMEM UnityStrOk[] = "\033[42mOK\033[00m"; +const char PROGMEM UnityStrPass[] = "\033[42mPASS\033[00m"; +const char PROGMEM UnityStrFail[] = "\033[41mFAIL\033[00m"; +const char PROGMEM UnityStrIgnore[] = "\033[43mIGNORE\033[00m"; #else -static const char UnityStrOk[] = "OK"; -static const char UnityStrPass[] = "PASS"; -static const char UnityStrFail[] = "FAIL"; -static const char UnityStrIgnore[] = "IGNORE"; +const char PROGMEM UnityStrOk[] = "OK"; +const char PROGMEM UnityStrPass[] = "PASS"; +const char PROGMEM UnityStrFail[] = "FAIL"; +const char PROGMEM UnityStrIgnore[] = "IGNORE"; #endif -static const char UnityStrNull[] = "NULL"; -static const char UnityStrSpacer[] = ". "; -static const char UnityStrExpected[] = " Expected "; -static const char UnityStrWas[] = " Was "; -static const char UnityStrGt[] = " to be greater than "; -static const char UnityStrLt[] = " to be less than "; -static const char UnityStrOrEqual[] = "or equal to "; -static const char UnityStrElement[] = " Element "; -static const char UnityStrByte[] = " Byte "; -static const char UnityStrMemory[] = " Memory Mismatch."; -static const char UnityStrDelta[] = " Values Not Within Delta "; -static const char UnityStrPointless[] = " You Asked Me To Compare Nothing, Which Was Pointless."; -static const char UnityStrNullPointerForExpected[] = " Expected pointer to be NULL"; -static const char UnityStrNullPointerForActual[] = " Actual pointer was NULL"; +static const char PROGMEM UnityStrNull[] = "NULL"; +static const char PROGMEM UnityStrSpacer[] = ". "; +static const char PROGMEM UnityStrExpected[] = " Expected "; +static const char PROGMEM UnityStrWas[] = " Was "; +static const char PROGMEM UnityStrGt[] = " to be greater than "; +static const char PROGMEM UnityStrLt[] = " to be less than "; +static const char PROGMEM UnityStrOrEqual[] = "or equal to "; +static const char PROGMEM UnityStrElement[] = " Element "; +static const char PROGMEM UnityStrByte[] = " Byte "; +static const char PROGMEM UnityStrMemory[] = " Memory Mismatch."; +static const char PROGMEM UnityStrDelta[] = " Values Not Within Delta "; +static const char PROGMEM UnityStrPointless[] = " You Asked Me To Compare Nothing, Which Was Pointless."; +static const char PROGMEM UnityStrNullPointerForExpected[] = " Expected pointer to be NULL"; +static const char PROGMEM UnityStrNullPointerForActual[] = " Actual pointer was NULL"; #ifndef UNITY_EXCLUDE_FLOAT -static const char UnityStrNot[] = "Not "; -static const char UnityStrInf[] = "Infinity"; -static const char UnityStrNegInf[] = "Negative Infinity"; -static const char UnityStrNaN[] = "NaN"; -static const char UnityStrDet[] = "Determinate"; -static const char UnityStrInvalidFloatTrait[] = "Invalid Float Trait"; +static const char PROGMEM UnityStrNot[] = "Not "; +static const char PROGMEM UnityStrInf[] = "Infinity"; +static const char PROGMEM UnityStrNegInf[] = "Negative Infinity"; +static const char PROGMEM UnityStrNaN[] = "NaN"; +static const char PROGMEM UnityStrDet[] = "Determinate"; +static const char PROGMEM UnityStrInvalidFloatTrait[] = "Invalid Float Trait"; #endif -const char UnityStrErrFloat[] = "Unity Floating Point Disabled"; -const char UnityStrErrDouble[] = "Unity Double Precision Disabled"; -const char UnityStrErr64[] = "Unity 64-bit Support Disabled"; -static const char UnityStrBreaker[] = "-----------------------"; -static const char UnityStrResultsTests[] = " Tests "; -static const char UnityStrResultsFailures[] = " Failures "; -static const char UnityStrResultsIgnored[] = " Ignored "; -static const char UnityStrDetail1Name[] = UNITY_DETAIL1_NAME " "; -static const char UnityStrDetail2Name[] = " " UNITY_DETAIL2_NAME " "; +const char PROGMEM UnityStrErrShorthand[] = "Unity Shorthand Support Disabled"; +const char PROGMEM UnityStrErrFloat[] = "Unity Floating Point Disabled"; +const char PROGMEM UnityStrErrDouble[] = "Unity Double Precision Disabled"; +const char PROGMEM UnityStrErr64[] = "Unity 64-bit Support Disabled"; +static const char PROGMEM UnityStrBreaker[] = "-----------------------"; +static const char PROGMEM UnityStrResultsTests[] = " Tests "; +static const char PROGMEM UnityStrResultsFailures[] = " Failures "; +static const char PROGMEM UnityStrResultsIgnored[] = " Ignored "; +static const char PROGMEM UnityStrDetail1Name[] = UNITY_DETAIL1_NAME " "; +static const char PROGMEM UnityStrDetail2Name[] = " " UNITY_DETAIL2_NAME " "; /*----------------------------------------------- * Pretty Printers & Test Result Output Handlers *-----------------------------------------------*/ +/*-----------------------------------------------*/ +/* Local helper function to print characters. */ +static void UnityPrintChar(const char* pch) +{ + /* printable characters plus CR & LF are printed */ + if ((*pch <= 126) && (*pch >= 32)) + { + UNITY_OUTPUT_CHAR(*pch); + } + /* write escaped carriage returns */ + else if (*pch == 13) + { + UNITY_OUTPUT_CHAR('\\'); + UNITY_OUTPUT_CHAR('r'); + } + /* write escaped line feeds */ + else if (*pch == 10) + { + UNITY_OUTPUT_CHAR('\\'); + UNITY_OUTPUT_CHAR('n'); + } + /* unprintable characters are shown as codes */ + else + { + UNITY_OUTPUT_CHAR('\\'); + UNITY_OUTPUT_CHAR('x'); + UnityPrintNumberHex((UNITY_UINT)*pch, 2); + } +} + +/*-----------------------------------------------*/ +/* Local helper function to print ANSI escape strings e.g. "\033[42m". */ +#ifdef UNITY_OUTPUT_COLOR +static UNITY_UINT UnityPrintAnsiEscapeString(const char* string) +{ + const char* pch = string; + UNITY_UINT count = 0; + + while (*pch && (*pch != 'm')) + { + UNITY_OUTPUT_CHAR(*pch); + pch++; + count++; + } + UNITY_OUTPUT_CHAR('m'); + count++; + + return count; +} +#endif + +/*-----------------------------------------------*/ void UnityPrint(const char* string) { const char* pch = string; @@ -75,54 +133,142 @@ void UnityPrint(const char* string) { while (*pch) { - /* printable characters plus CR & LF are printed */ - if ((*pch <= 126) && (*pch >= 32)) - { - UNITY_OUTPUT_CHAR(*pch); - } - /* write escaped carriage returns */ - else if (*pch == 13) - { - UNITY_OUTPUT_CHAR('\\'); - UNITY_OUTPUT_CHAR('r'); - } - /* write escaped line feeds */ - else if (*pch == 10) - { - UNITY_OUTPUT_CHAR('\\'); - UNITY_OUTPUT_CHAR('n'); - } #ifdef UNITY_OUTPUT_COLOR /* print ANSI escape code */ - else if (*pch == 27 && *(pch + 1) == '[') + if ((*pch == 27) && (*(pch + 1) == '[')) { - while (*pch && *pch != 'm') - { - UNITY_OUTPUT_CHAR(*pch); - pch++; - } - UNITY_OUTPUT_CHAR('m'); + pch += UnityPrintAnsiEscapeString(pch); + continue; } #endif - /* unprintable characters are shown as codes */ - else - { - UNITY_OUTPUT_CHAR('\\'); - UNITY_OUTPUT_CHAR('x'); - UnityPrintNumberHex((UNITY_UINT)*pch, 2); - } + UnityPrintChar(pch); pch++; } } } +/*-----------------------------------------------*/ +#ifdef UNITY_INCLUDE_PRINT_FORMATTED +void UnityPrintFormatted(const char* format, ...) +{ + const char* pch = format; + va_list va; + va_start(va, format); + + if (pch != NULL) + { + while (*pch) + { + /* format identification character */ + if (*pch == '%') + { + pch++; + + if (pch != NULL) + { + switch (*pch) + { + case 'd': + case 'i': + { + const int number = va_arg(va, int); + UnityPrintNumber((UNITY_INT)number); + break; + } +#ifndef UNITY_EXCLUDE_FLOAT_PRINT + case 'f': + case 'g': + { + const double number = va_arg(va, double); + UnityPrintFloat((UNITY_DOUBLE)number); + break; + } +#endif + case 'u': + { + const unsigned int number = va_arg(va, unsigned int); + UnityPrintNumberUnsigned((UNITY_UINT)number); + break; + } + case 'b': + { + const unsigned int number = va_arg(va, unsigned int); + const UNITY_UINT mask = (UNITY_UINT)0 - (UNITY_UINT)1; + UNITY_OUTPUT_CHAR('0'); + UNITY_OUTPUT_CHAR('b'); + UnityPrintMask(mask, (UNITY_UINT)number); + break; + } + case 'x': + case 'X': + case 'p': + { + const unsigned int number = va_arg(va, unsigned int); + UNITY_OUTPUT_CHAR('0'); + UNITY_OUTPUT_CHAR('x'); + UnityPrintNumberHex((UNITY_UINT)number, 8); + break; + } + case 'c': + { + const int ch = va_arg(va, int); + UnityPrintChar((const char *)&ch); + break; + } + case 's': + { + const char * string = va_arg(va, const char *); + UnityPrint(string); + break; + } + case '%': + { + UnityPrintChar(pch); + break; + } + default: + { + /* print the unknown format character */ + UNITY_OUTPUT_CHAR('%'); + UnityPrintChar(pch); + break; + } + } + } + } +#ifdef UNITY_OUTPUT_COLOR + /* print ANSI escape code */ + else if ((*pch == 27) && (*(pch + 1) == '[')) + { + pch += UnityPrintAnsiEscapeString(pch); + continue; + } +#endif + else if (*pch == '\n') + { + UNITY_PRINT_EOL(); + } + else + { + UnityPrintChar(pch); + } + + pch++; + } + } + + va_end(va); +} +#endif /* ! UNITY_INCLUDE_PRINT_FORMATTED */ + +/*-----------------------------------------------*/ void UnityPrintLen(const char* string, const UNITY_UINT32 length) { const char* pch = string; if (pch != NULL) { - while (*pch && (UNITY_UINT32)(pch - string) < length) + while (*pch && ((UNITY_UINT32)(pch - string) < length)) { /* printable characters plus CR & LF are printed */ if ((*pch <= 126) && (*pch >= 32)) @@ -158,7 +304,39 @@ void UnityPrintNumberByStyle(const UNITY_INT number, const UNITY_DISPLAY_STYLE_T { if ((style & UNITY_DISPLAY_RANGE_INT) == UNITY_DISPLAY_RANGE_INT) { - UnityPrintNumber(number); + if (style == UNITY_DISPLAY_STYLE_CHAR) + { + /* printable characters plus CR & LF are printed */ + UNITY_OUTPUT_CHAR('\''); + if ((number <= 126) && (number >= 32)) + { + UNITY_OUTPUT_CHAR((int)number); + } + /* write escaped carriage returns */ + else if (number == 13) + { + UNITY_OUTPUT_CHAR('\\'); + UNITY_OUTPUT_CHAR('r'); + } + /* write escaped line feeds */ + else if (number == 10) + { + UNITY_OUTPUT_CHAR('\\'); + UNITY_OUTPUT_CHAR('n'); + } + /* unprintable characters are shown as codes */ + else + { + UNITY_OUTPUT_CHAR('\\'); + UNITY_OUTPUT_CHAR('x'); + UnityPrintNumberHex((UNITY_UINT)number, 2); + } + UNITY_OUTPUT_CHAR('\''); + } + else + { + UnityPrintNumber(number); + } } else if ((style & UNITY_DISPLAY_RANGE_UINT) == UNITY_DISPLAY_RANGE_UINT) { @@ -181,7 +359,7 @@ void UnityPrintNumber(const UNITY_INT number_to_print) { /* A negative number, including MIN negative */ UNITY_OUTPUT_CHAR('-'); - number = (UNITY_UINT)(-number_to_print); + number = (~number) + 1; } UnityPrintNumberUnsigned(number); } @@ -211,8 +389,11 @@ void UnityPrintNumberHex(const UNITY_UINT number, const char nibbles_to_print) { int nibble; char nibbles = nibbles_to_print; - if ((unsigned)nibbles > (2 * sizeof(number))) - nibbles = 2 * sizeof(number); + + if ((unsigned)nibbles > UNITY_MAX_NIBBLES) + { + nibbles = UNITY_MAX_NIBBLES; + } while (nibbles > 0) { @@ -258,53 +439,118 @@ void UnityPrintMask(const UNITY_UINT mask, const UNITY_UINT number) /*-----------------------------------------------*/ #ifndef UNITY_EXCLUDE_FLOAT_PRINT -/* This function prints a floating-point value in a format similar to - * printf("%.6g"). It can work with either single- or double-precision, - * but for simplicity, it prints only 6 significant digits in either case. - * Printing more than 6 digits accurately is hard (at least in the single- - * precision case) and isn't attempted here. */ +/* + * This function prints a floating-point value in a format similar to + * printf("%.7g") on a single-precision machine or printf("%.9g") on a + * double-precision machine. The 7th digit won't always be totally correct + * in single-precision operation (for that level of accuracy, a more + * complicated algorithm would be needed). + */ void UnityPrintFloat(const UNITY_DOUBLE input_number) { +#ifdef UNITY_INCLUDE_DOUBLE + static const int sig_digits = 9; + static const UNITY_INT32 min_scaled = 100000000; + static const UNITY_INT32 max_scaled = 1000000000; +#else + static const int sig_digits = 7; + static const UNITY_INT32 min_scaled = 1000000; + static const UNITY_INT32 max_scaled = 10000000; +#endif + UNITY_DOUBLE number = input_number; - /* print minus sign (including for negative zero) */ - if (number < 0.0f || (number == 0.0f && 1.0f / number < 0.0f)) + /* print minus sign (does not handle negative zero) */ + if (number < 0.0f) { UNITY_OUTPUT_CHAR('-'); number = -number; } /* handle zero, NaN, and +/- infinity */ - if (number == 0.0f) UnityPrint("0"); - else if (isnan(number)) UnityPrint("nan"); - else if (isinf(number)) UnityPrint("inf"); + if (number == 0.0f) + { + UnityPrint("0"); + } + else if (isnan(number)) + { + UnityPrint("nan"); + } + else if (isinf(number)) + { + UnityPrint("inf"); + } else { + UNITY_INT32 n_int = 0, n; int exponent = 0; int decimals, digits; - UNITY_INT32 n; - char buf[16]; + char buf[16] = {0}; - /* scale up or down by powers of 10 */ - while (number < 100000.0f / 1e6f) { number *= 1e6f; exponent -= 6; } - while (number < 100000.0f) { number *= 10.0f; exponent--; } - while (number > 1000000.0f * 1e6f) { number /= 1e6f; exponent += 6; } - while (number > 1000000.0f) { number /= 10.0f; exponent++; } + /* + * Scale up or down by powers of 10. To minimize rounding error, + * start with a factor/divisor of 10^10, which is the largest + * power of 10 that can be represented exactly. Finally, compute + * (exactly) the remaining power of 10 and perform one more + * multiplication or division. + */ + if (number < 1.0f) + { + UNITY_DOUBLE factor = 1.0f; + + while (number < (UNITY_DOUBLE)max_scaled / 1e10f) { number *= 1e10f; exponent -= 10; } + while (number * factor < (UNITY_DOUBLE)min_scaled) { factor *= 10.0f; exponent--; } + + number *= factor; + } + else if (number > (UNITY_DOUBLE)max_scaled) + { + UNITY_DOUBLE divisor = 1.0f; + + while (number > (UNITY_DOUBLE)min_scaled * 1e10f) { number /= 1e10f; exponent += 10; } + while (number / divisor > (UNITY_DOUBLE)max_scaled) { divisor *= 10.0f; exponent++; } + + number /= divisor; + } + else + { + /* + * In this range, we can split off the integer part before + * doing any multiplications. This reduces rounding error by + * freeing up significant bits in the fractional part. + */ + UNITY_DOUBLE factor = 1.0f; + n_int = (UNITY_INT32)number; + number -= (UNITY_DOUBLE)n_int; + + while (n_int < min_scaled) { n_int *= 10; factor *= 10.0f; exponent--; } + + number *= factor; + } /* round to nearest integer */ n = ((UNITY_INT32)(number + number) + 1) / 2; - if (n > 999999) + +#ifndef UNITY_ROUND_TIES_AWAY_FROM_ZERO + /* round to even if exactly between two integers */ + if ((n & 1) && (((UNITY_DOUBLE)n - number) == 0.5f)) + n--; +#endif + + n += n_int; + + if (n >= max_scaled) { - n = 100000; + n = min_scaled; exponent++; } /* determine where to place decimal point */ - decimals = (exponent <= 0 && exponent >= -9) ? -exponent : 5; + decimals = ((exponent <= 0) && (exponent >= -(sig_digits + 3))) ? (-exponent) : (sig_digits - 1); exponent += decimals; /* truncate trailing zeroes after decimal point */ - while (decimals > 0 && n % 10 == 0) + while ((decimals > 0) && ((n % 10) == 0)) { n /= 10; decimals--; @@ -312,14 +558,14 @@ void UnityPrintFloat(const UNITY_DOUBLE input_number) /* build up buffer in reverse order */ digits = 0; - while (n != 0 || digits < decimals + 1) + while ((n != 0) || (digits < (decimals + 1))) { buf[digits++] = (char)('0' + n % 10); n /= 10; } while (digits > 0) { - if(digits == decimals) UNITY_OUTPUT_CHAR('.'); + if (digits == decimals) { UNITY_OUTPUT_CHAR('.'); } UNITY_OUTPUT_CHAR(buf[--digits]); } @@ -328,7 +574,7 @@ void UnityPrintFloat(const UNITY_DOUBLE input_number) { UNITY_OUTPUT_CHAR('e'); - if(exponent < 0) + if (exponent < 0) { UNITY_OUTPUT_CHAR('-'); exponent = -exponent; @@ -339,7 +585,7 @@ void UnityPrintFloat(const UNITY_DOUBLE input_number) } digits = 0; - while (exponent != 0 || digits < 2) + while ((exponent != 0) || (digits < 2)) { buf[digits++] = (char)('0' + exponent % 10); exponent /= 10; @@ -356,12 +602,44 @@ void UnityPrintFloat(const UNITY_DOUBLE input_number) /*-----------------------------------------------*/ static void UnityTestResultsBegin(const char* file, const UNITY_LINE_TYPE line) { +#ifdef UNITY_OUTPUT_FOR_ECLIPSE + UNITY_OUTPUT_CHAR('('); + UnityPrint(file); + UNITY_OUTPUT_CHAR(':'); + UnityPrintNumber((UNITY_INT)line); + UNITY_OUTPUT_CHAR(')'); + UNITY_OUTPUT_CHAR(' '); + UnityPrint(Unity.CurrentTestName); + UNITY_OUTPUT_CHAR(':'); +#else +#ifdef UNITY_OUTPUT_FOR_IAR_WORKBENCH + UnityPrint("'); + UnityPrint(Unity.CurrentTestName); + UnityPrint(" "); +#else +#ifdef UNITY_OUTPUT_FOR_QT_CREATOR + UnityPrint("file://"); + UnityPrint(file); + UNITY_OUTPUT_CHAR(':'); + UnityPrintNumber((UNITY_INT)line); + UNITY_OUTPUT_CHAR(' '); + UnityPrint(Unity.CurrentTestName); + UNITY_OUTPUT_CHAR(':'); +#else UnityPrint(file); UNITY_OUTPUT_CHAR(':'); UnityPrintNumber((UNITY_INT)line); UNITY_OUTPUT_CHAR(':'); UnityPrint(Unity.CurrentTestName); UNITY_OUTPUT_CHAR(':'); +#endif +#endif +#endif } /*-----------------------------------------------*/ @@ -391,7 +669,7 @@ void UnityConcludeTest(void) Unity.CurrentTestFailed = 0; Unity.CurrentTestIgnored = 0; - UNITY_EXEC_TIME_RESET(); + UNITY_PRINT_EXEC_TIME(); UNITY_PRINT_EOL(); UNITY_FLUSH_CALL(); } @@ -479,12 +757,14 @@ static void UnityPrintExpectedAndActualStringsLen(const char* expected, * Assertion & Control Helpers *-----------------------------------------------*/ +/*-----------------------------------------------*/ static int UnityIsOneArrayNull(UNITY_INTERNAL_PTR expected, UNITY_INTERNAL_PTR actual, const UNITY_LINE_TYPE lineNumber, const char* msg) { - if (expected == actual) return 0; /* Both are NULL or same pointer */ + /* Both are NULL or same pointer */ + if (expected == actual) { return 0; } /* print and return true if just expected is NULL */ if (expected == NULL) @@ -511,6 +791,7 @@ static int UnityIsOneArrayNull(UNITY_INTERNAL_PTR expected, * Assertion Functions *-----------------------------------------------*/ +/*-----------------------------------------------*/ void UnityAssertBits(const UNITY_INT mask, const UNITY_INT expected, const UNITY_INT actual, @@ -563,18 +844,18 @@ void UnityAssertGreaterOrLessOrEqualNumber(const UNITY_INT threshold, int failed = 0; RETURN_IF_FAIL_OR_IGNORE; - if (threshold == actual && compare & UNITY_EQUAL_TO) return; - if (threshold == actual) failed = 1; + if ((threshold == actual) && (compare & UNITY_EQUAL_TO)) { return; } + if ((threshold == actual)) { failed = 1; } if ((style & UNITY_DISPLAY_RANGE_INT) == UNITY_DISPLAY_RANGE_INT) { - if (actual > threshold && compare & UNITY_SMALLER_THAN) failed = 1; - if (actual < threshold && compare & UNITY_GREATER_THAN) failed = 1; + if ((actual > threshold) && (compare & UNITY_SMALLER_THAN)) { failed = 1; } + if ((actual < threshold) && (compare & UNITY_GREATER_THAN)) { failed = 1; } } else /* UINT or HEX */ { - if ((UNITY_UINT)actual > (UNITY_UINT)threshold && compare & UNITY_SMALLER_THAN) failed = 1; - if ((UNITY_UINT)actual < (UNITY_UINT)threshold && compare & UNITY_GREATER_THAN) failed = 1; + if (((UNITY_UINT)actual > (UNITY_UINT)threshold) && (compare & UNITY_SMALLER_THAN)) { failed = 1; } + if (((UNITY_UINT)actual < (UNITY_UINT)threshold) && (compare & UNITY_GREATER_THAN)) { failed = 1; } } if (failed) @@ -582,9 +863,9 @@ void UnityAssertGreaterOrLessOrEqualNumber(const UNITY_INT threshold, UnityTestResultsFailBegin(lineNumber); UnityPrint(UnityStrExpected); UnityPrintNumberByStyle(actual, style); - if (compare & UNITY_GREATER_THAN) UnityPrint(UnityStrGt); - if (compare & UNITY_SMALLER_THAN) UnityPrint(UnityStrLt); - if (compare & UNITY_EQUAL_TO) UnityPrint(UnityStrOrEqual); + if (compare & UNITY_GREATER_THAN) { UnityPrint(UnityStrGt); } + if (compare & UNITY_SMALLER_THAN) { UnityPrint(UnityStrLt); } + if (compare & UNITY_EQUAL_TO) { UnityPrint(UnityStrOrEqual); } UnityPrintNumberByStyle(threshold, style); UnityAddMsgIfSpecified(msg); UNITY_FAIL_AND_BAIL; @@ -607,8 +888,9 @@ void UnityAssertEqualIntArray(UNITY_INTERNAL_PTR expected, const UNITY_DISPLAY_STYLE_T style, const UNITY_FLAGS_T flags) { - UNITY_UINT32 elements = num_elements; - unsigned int length = style & 0xF; + UNITY_UINT32 elements = num_elements; + unsigned int length = style & 0xF; + unsigned int increment = 0; RETURN_IF_FAIL_OR_IGNORE; @@ -617,40 +899,55 @@ void UnityAssertEqualIntArray(UNITY_INTERNAL_PTR expected, UnityPrintPointlessAndBail(); } - if (expected == actual) return; /* Both are NULL or same pointer */ - if (UnityIsOneArrayNull(expected, actual, lineNumber, msg)) - UNITY_FAIL_AND_BAIL; + if (expected == actual) + { + return; /* Both are NULL or same pointer */ + } - while ((elements > 0) && elements--) + if (UnityIsOneArrayNull(expected, actual, lineNumber, msg)) + { + UNITY_FAIL_AND_BAIL; + } + + while ((elements > 0) && (elements--)) { UNITY_INT expect_val; UNITY_INT actual_val; + switch (length) { case 1: expect_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT8*)expected; actual_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT8*)actual; + increment = sizeof(UNITY_INT8); break; + case 2: expect_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT16*)expected; actual_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT16*)actual; + increment = sizeof(UNITY_INT16); break; + #ifdef UNITY_SUPPORT_64 case 8: expect_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT64*)expected; actual_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT64*)actual; + increment = sizeof(UNITY_INT64); break; #endif - default: /* length 4 bytes */ + + default: /* default is length 4 bytes */ + case 4: expect_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT32*)expected; actual_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT32*)actual; + increment = sizeof(UNITY_INT32); length = 4; break; } if (expect_val != actual_val) { - if (style & UNITY_DISPLAY_RANGE_UINT && length < sizeof(expect_val)) + if ((style & UNITY_DISPLAY_RANGE_UINT) && (length < (UNITY_INT_WIDTH / 8))) { /* For UINT, remove sign extension (padding 1's) from signed type casts above */ UNITY_INT mask = 1; mask = (mask << 8 * length) - 1; @@ -667,11 +964,12 @@ void UnityAssertEqualIntArray(UNITY_INTERNAL_PTR expected, UnityAddMsgIfSpecified(msg); UNITY_FAIL_AND_BAIL; } + /* Walk through array by incrementing the pointers */ if (flags == UNITY_ARRAY_TO_ARRAY) { - expected = (UNITY_INTERNAL_PTR)(length + (const char*)expected); + expected = (UNITY_INTERNAL_PTR)((const char*)expected + increment); } - actual = (UNITY_INTERNAL_PTR)(length + (const char*)actual); + actual = (UNITY_INTERNAL_PTR)((const char*)actual + increment); } } @@ -704,12 +1002,14 @@ void UnityAssertEqualIntArray(UNITY_INTERNAL_PTR expected, UnityPrint(UnityStrDelta) #endif /* UNITY_EXCLUDE_FLOAT_PRINT */ +/*-----------------------------------------------*/ static int UnityFloatsWithin(UNITY_FLOAT delta, UNITY_FLOAT expected, UNITY_FLOAT actual) { UNITY_FLOAT diff; UNITY_FLOAT_OR_DOUBLE_WITHIN(delta, expected, actual, diff); } +/*-----------------------------------------------*/ void UnityAssertEqualFloatArray(UNITY_PTR_ATTRIBUTE const UNITY_FLOAT* expected, UNITY_PTR_ATTRIBUTE const UNITY_FLOAT* actual, const UNITY_UINT32 num_elements, @@ -728,9 +1028,15 @@ void UnityAssertEqualFloatArray(UNITY_PTR_ATTRIBUTE const UNITY_FLOAT* expected, UnityPrintPointlessAndBail(); } - if (expected == actual) return; /* Both are NULL or same pointer */ + if (expected == actual) + { + return; /* Both are NULL or same pointer */ + } + if (UnityIsOneArrayNull((UNITY_INTERNAL_PTR)expected, (UNITY_INTERNAL_PTR)actual, lineNumber, msg)) + { UNITY_FAIL_AND_BAIL; + } while (elements--) { @@ -815,14 +1121,18 @@ void UnityAssertFloatSpecial(const UNITY_FLOAT actual, UnityTestResultsFailBegin(lineNumber); UnityPrint(UnityStrExpected); if (!should_be_trait) + { UnityPrint(UnityStrNot); + } UnityPrint(trait_names[trait_index]); UnityPrint(UnityStrWas); #ifndef UNITY_EXCLUDE_FLOAT_PRINT UnityPrintFloat((UNITY_DOUBLE)actual); #else if (should_be_trait) + { UnityPrint(UnityStrNot); + } UnityPrint(trait_names[trait_index]); #endif UnityAddMsgIfSpecified(msg); @@ -840,6 +1150,7 @@ static int UnityDoublesWithin(UNITY_DOUBLE delta, UNITY_DOUBLE expected, UNITY_D UNITY_FLOAT_OR_DOUBLE_WITHIN(delta, expected, actual, diff); } +/*-----------------------------------------------*/ void UnityAssertEqualDoubleArray(UNITY_PTR_ATTRIBUTE const UNITY_DOUBLE* expected, UNITY_PTR_ATTRIBUTE const UNITY_DOUBLE* actual, const UNITY_UINT32 num_elements, @@ -858,9 +1169,15 @@ void UnityAssertEqualDoubleArray(UNITY_PTR_ATTRIBUTE const UNITY_DOUBLE* expecte UnityPrintPointlessAndBail(); } - if (expected == actual) return; /* Both are NULL or same pointer */ + if (expected == actual) + { + return; /* Both are NULL or same pointer */ + } + if (UnityIsOneArrayNull((UNITY_INTERNAL_PTR)expected, (UNITY_INTERNAL_PTR)actual, lineNumber, msg)) + { UNITY_FAIL_AND_BAIL; + } while (elements--) { @@ -900,7 +1217,6 @@ void UnityAssertDoublesWithin(const UNITY_DOUBLE delta, } /*-----------------------------------------------*/ - void UnityAssertDoubleSpecial(const UNITY_DOUBLE actual, const char* msg, const UNITY_LINE_TYPE lineNumber, @@ -945,14 +1261,18 @@ void UnityAssertDoubleSpecial(const UNITY_DOUBLE actual, UnityTestResultsFailBegin(lineNumber); UnityPrint(UnityStrExpected); if (!should_be_trait) + { UnityPrint(UnityStrNot); + } UnityPrint(trait_names[trait_index]); UnityPrint(UnityStrWas); #ifndef UNITY_EXCLUDE_FLOAT_PRINT UnityPrintFloat(actual); #else if (should_be_trait) + { UnityPrint(UnityStrNot); + } UnityPrint(trait_names[trait_index]); #endif UnityAddMsgIfSpecified(msg); @@ -975,16 +1295,24 @@ void UnityAssertNumbersWithin(const UNITY_UINT delta, if ((style & UNITY_DISPLAY_RANGE_INT) == UNITY_DISPLAY_RANGE_INT) { if (actual > expected) - Unity.CurrentTestFailed = (UNITY_UINT)((UNITY_UINT)(actual - expected) > delta); + { + Unity.CurrentTestFailed = (((UNITY_UINT)actual - (UNITY_UINT)expected) > delta); + } else - Unity.CurrentTestFailed = (UNITY_UINT)((UNITY_UINT)(expected - actual) > delta); + { + Unity.CurrentTestFailed = (((UNITY_UINT)expected - (UNITY_UINT)actual) > delta); + } } else { if ((UNITY_UINT)actual > (UNITY_UINT)expected) - Unity.CurrentTestFailed = (UNITY_UINT)((UNITY_UINT)(actual - expected) > delta); + { + Unity.CurrentTestFailed = (((UNITY_UINT)actual - (UNITY_UINT)expected) > delta); + } else - Unity.CurrentTestFailed = (UNITY_UINT)((UNITY_UINT)(expected - actual) > delta); + { + Unity.CurrentTestFailed = (((UNITY_UINT)expected - (UNITY_UINT)actual) > delta); + } } if (Unity.CurrentTestFailed) @@ -1001,6 +1329,126 @@ void UnityAssertNumbersWithin(const UNITY_UINT delta, } } +/*-----------------------------------------------*/ +void UnityAssertNumbersArrayWithin(const UNITY_UINT delta, + UNITY_INTERNAL_PTR expected, + UNITY_INTERNAL_PTR actual, + const UNITY_UINT32 num_elements, + const char* msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_DISPLAY_STYLE_T style, + const UNITY_FLAGS_T flags) +{ + UNITY_UINT32 elements = num_elements; + unsigned int length = style & 0xF; + unsigned int increment = 0; + + RETURN_IF_FAIL_OR_IGNORE; + + if (num_elements == 0) + { + UnityPrintPointlessAndBail(); + } + + if (expected == actual) + { + return; /* Both are NULL or same pointer */ + } + + if (UnityIsOneArrayNull(expected, actual, lineNumber, msg)) + { + UNITY_FAIL_AND_BAIL; + } + + while ((elements > 0) && (elements--)) + { + UNITY_INT expect_val; + UNITY_INT actual_val; + + switch (length) + { + case 1: + expect_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT8*)expected; + actual_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT8*)actual; + increment = sizeof(UNITY_INT8); + break; + + case 2: + expect_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT16*)expected; + actual_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT16*)actual; + increment = sizeof(UNITY_INT16); + break; + +#ifdef UNITY_SUPPORT_64 + case 8: + expect_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT64*)expected; + actual_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT64*)actual; + increment = sizeof(UNITY_INT64); + break; +#endif + + default: /* default is length 4 bytes */ + case 4: + expect_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT32*)expected; + actual_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT32*)actual; + increment = sizeof(UNITY_INT32); + length = 4; + break; + } + + if ((style & UNITY_DISPLAY_RANGE_INT) == UNITY_DISPLAY_RANGE_INT) + { + if (actual_val > expect_val) + { + Unity.CurrentTestFailed = (((UNITY_UINT)actual_val - (UNITY_UINT)expect_val) > delta); + } + else + { + Unity.CurrentTestFailed = (((UNITY_UINT)expect_val - (UNITY_UINT)actual_val) > delta); + } + } + else + { + if ((UNITY_UINT)actual_val > (UNITY_UINT)expect_val) + { + Unity.CurrentTestFailed = (((UNITY_UINT)actual_val - (UNITY_UINT)expect_val) > delta); + } + else + { + Unity.CurrentTestFailed = (((UNITY_UINT)expect_val - (UNITY_UINT)actual_val) > delta); + } + } + + if (Unity.CurrentTestFailed) + { + if ((style & UNITY_DISPLAY_RANGE_UINT) && (length < (UNITY_INT_WIDTH / 8))) + { /* For UINT, remove sign extension (padding 1's) from signed type casts above */ + UNITY_INT mask = 1; + mask = (mask << 8 * length) - 1; + expect_val &= mask; + actual_val &= mask; + } + UnityTestResultsFailBegin(lineNumber); + UnityPrint(UnityStrDelta); + UnityPrintNumberByStyle((UNITY_INT)delta, style); + UnityPrint(UnityStrElement); + UnityPrintNumberUnsigned(num_elements - elements - 1); + UnityPrint(UnityStrExpected); + UnityPrintNumberByStyle(expect_val, style); + UnityPrint(UnityStrWas); + UnityPrintNumberByStyle(actual_val, style); + UnityAddMsgIfSpecified(msg); + UNITY_FAIL_AND_BAIL; + } + /* Walk through array by incrementing the pointers */ + if (flags == UNITY_ARRAY_TO_ARRAY) + { + expected = (UNITY_INTERNAL_PTR)((const char*)expected + increment); + } + actual = (UNITY_INTERNAL_PTR)((const char*)actual + increment); + } +} + /*-----------------------------------------------*/ void UnityAssertEqualString(const char* expected, const char* actual, @@ -1180,9 +1628,15 @@ void UnityAssertEqualMemory(UNITY_INTERNAL_PTR expected, UnityPrintPointlessAndBail(); } - if (expected == actual) return; /* Both are NULL or same pointer */ + if (expected == actual) + { + return; /* Both are NULL or same pointer */ + } + if (UnityIsOneArrayNull(expected, actual, lineNumber, msg)) + { UNITY_FAIL_AND_BAIL; + } while (elements--) { @@ -1240,25 +1694,27 @@ UNITY_INTERNAL_PTR UnityNumToPtr(const UNITY_INT num, const UNITY_UINT8 size) switch(size) { case 1: - UnityQuickCompare.i8 = (UNITY_INT8)num; - return (UNITY_INTERNAL_PTR)(&UnityQuickCompare.i8); + UnityQuickCompare.i8 = (UNITY_INT8)num; + return (UNITY_INTERNAL_PTR)(&UnityQuickCompare.i8); case 2: - UnityQuickCompare.i16 = (UNITY_INT16)num; - return (UNITY_INTERNAL_PTR)(&UnityQuickCompare.i16); + UnityQuickCompare.i16 = (UNITY_INT16)num; + return (UNITY_INTERNAL_PTR)(&UnityQuickCompare.i16); #ifdef UNITY_SUPPORT_64 case 8: - UnityQuickCompare.i64 = (UNITY_INT64)num; - return (UNITY_INTERNAL_PTR)(&UnityQuickCompare.i64); + UnityQuickCompare.i64 = (UNITY_INT64)num; + return (UNITY_INTERNAL_PTR)(&UnityQuickCompare.i64); #endif + default: /* 4 bytes */ - UnityQuickCompare.i32 = (UNITY_INT32)num; - return (UNITY_INTERNAL_PTR)(&UnityQuickCompare.i32); + UnityQuickCompare.i32 = (UNITY_INT32)num; + return (UNITY_INTERNAL_PTR)(&UnityQuickCompare.i32); } } #ifndef UNITY_EXCLUDE_FLOAT +/*-----------------------------------------------*/ UNITY_INTERNAL_PTR UnityFloatToPtr(const float num) { UnityQuickCompare.f = num; @@ -1267,6 +1723,7 @@ UNITY_INTERNAL_PTR UnityFloatToPtr(const float num) #endif #ifndef UNITY_EXCLUDE_DOUBLE +/*-----------------------------------------------*/ UNITY_INTERNAL_PTR UnityDoubleToPtr(const double num) { UnityQuickCompare.d = num; @@ -1278,6 +1735,7 @@ UNITY_INTERNAL_PTR UnityDoubleToPtr(const double num) * Control Functions *-----------------------------------------------*/ +/*-----------------------------------------------*/ void UnityFail(const char* msg, const UNITY_LINE_TYPE line) { RETURN_IF_FAIL_OR_IGNORE; @@ -1327,6 +1785,20 @@ void UnityIgnore(const char* msg, const UNITY_LINE_TYPE line) UNITY_IGNORE_AND_BAIL; } +/*-----------------------------------------------*/ +void UnityMessage(const char* msg, const UNITY_LINE_TYPE line) +{ + UnityTestResultsBegin(Unity.TestFile, line); + UnityPrint("INFO"); + if (msg != NULL) + { + UNITY_OUTPUT_CHAR(':'); + UNITY_OUTPUT_CHAR(' '); + UnityPrint(msg); + } + UNITY_PRINT_EOL(); +} + /*-----------------------------------------------*/ void UnityDefaultTestRun(UnityTestFunction Func, const char* FuncName, const int FuncLineNum) { @@ -1334,6 +1806,7 @@ void UnityDefaultTestRun(UnityTestFunction Func, const char* FuncName, const int Unity.CurrentTestLineNumber = (UNITY_LINE_TYPE)FuncLineNum; Unity.NumberOfTests++; UNITY_CLR_DETAILS(); + UNITY_EXEC_TIME_START(); if (TEST_PROTECT()) { setUp(); @@ -1343,9 +1816,16 @@ void UnityDefaultTestRun(UnityTestFunction Func, const char* FuncName, const int { tearDown(); } + UNITY_EXEC_TIME_STOP(); UnityConcludeTest(); } +/*-----------------------------------------------*/ +void UnitySetTestFile(const char* filename) +{ + Unity.TestFile = filename; +} + /*-----------------------------------------------*/ void UnityBegin(const char* filename) { @@ -1357,7 +1837,6 @@ void UnityBegin(const char* filename) Unity.TestIgnores = 0; Unity.CurrentTestFailed = 0; Unity.CurrentTestIgnored = 0; - UNITY_EXEC_TIME_RESET(); UNITY_CLR_DETAILS(); UNITY_OUTPUT_START(); @@ -1402,12 +1881,14 @@ char* UnityOptionIncludeNamed = NULL; char* UnityOptionExcludeNamed = NULL; int UnityVerbosity = 1; +/*-----------------------------------------------*/ int UnityParseOptions(int argc, char** argv) { + int i; UnityOptionIncludeNamed = NULL; UnityOptionExcludeNamed = NULL; - for (int i = 1; i < argc; i++) + for (i = 1; i < argc; i++) { if (argv[i][0] == '-') { @@ -1418,9 +1899,13 @@ int UnityParseOptions(int argc, char** argv) case 'n': /* include tests with name including this string */ case 'f': /* an alias for -n */ if (argv[i][2] == '=') + { UnityOptionIncludeNamed = &argv[i][3]; + } else if (++i < argc) + { UnityOptionIncludeNamed = argv[i]; + } else { UnityPrint("ERROR: No Test String to Include Matches For"); @@ -1436,9 +1921,13 @@ int UnityParseOptions(int argc, char** argv) break; case 'x': /* exclude tests with name including this string */ if (argv[i][2] == '=') + { UnityOptionExcludeNamed = &argv[i][3]; + } else if (++i < argc) + { UnityOptionExcludeNamed = argv[i]; + } else { UnityPrint("ERROR: No Test String to Exclude Matches For"); @@ -1458,6 +1947,7 @@ int UnityParseOptions(int argc, char** argv) return 0; } +/*-----------------------------------------------*/ int IsStringInBiggerString(const char* longstring, const char* shortstring) { const char* lptr = longstring; @@ -1465,7 +1955,9 @@ int IsStringInBiggerString(const char* longstring, const char* shortstring) const char* lnext = lptr; if (*sptr == '*') + { return 1; + } while (*lptr) { @@ -1496,9 +1988,11 @@ int IsStringInBiggerString(const char* longstring, const char* shortstring) lptr = lnext; sptr = shortstring; } + return 0; } +/*-----------------------------------------------*/ int UnityStringArgumentMatches(const char* str) { int retval; @@ -1511,7 +2005,9 @@ int UnityStringArgumentMatches(const char* str) while (ptr1[0] != 0) { if ((ptr1[0] == '"') || (ptr1[0] == '\'')) + { ptr1++; + } /* look for the start of the next partial */ ptr2 = ptr1; @@ -1520,26 +2016,37 @@ int UnityStringArgumentMatches(const char* str) { ptr2++; if ((ptr2[0] == ':') && (ptr2[1] != 0) && (ptr2[0] != '\'') && (ptr2[0] != '"') && (ptr2[0] != ',')) + { ptrf = &ptr2[1]; + } } while ((ptr2[0] != 0) && (ptr2[0] != '\'') && (ptr2[0] != '"') && (ptr2[0] != ',')); + while ((ptr2[0] != 0) && ((ptr2[0] == ':') || (ptr2[0] == '\'') || (ptr2[0] == '"') || (ptr2[0] == ','))) + { ptr2++; + } /* done if complete filename match */ retval = IsStringInBiggerString(Unity.TestFile, ptr1); if (retval == 1) + { return retval; + } /* done if testname match after filename partial match */ if ((retval == 2) && (ptrf != 0)) { if (IsStringInBiggerString(Unity.CurrentTestName, ptrf)) + { return 1; + } } /* done if complete testname match */ if (IsStringInBiggerString(Unity.CurrentTestName, ptr1) == 1) + { return 1; + } ptr1 = ptr2; } @@ -1548,6 +2055,7 @@ int UnityStringArgumentMatches(const char* str) return 0; } +/*-----------------------------------------------*/ int UnityTestMatches(void) { /* Check if this test name matches the included test pattern */ @@ -1557,14 +2065,19 @@ int UnityTestMatches(void) retval = UnityStringArgumentMatches(UnityOptionIncludeNamed); } else + { retval = 1; + } /* Check if this test name matches the excluded test pattern */ if (UnityOptionExcludeNamed) { if (UnityStringArgumentMatches(UnityOptionExcludeNamed)) + { retval = 0; + } } + return retval; } diff --git a/test/vendor/ceedling/vendor/unity/src/unity.h b/test/vendor/ceedling/vendor/unity/src/unity.h index a0c301d2..34d7f93a 100644 --- a/test/vendor/ceedling/vendor/unity/src/unity.h +++ b/test/vendor/ceedling/vendor/unity/src/unity.h @@ -1,6 +1,6 @@ /* ========================================== Unity Project - A Test Framework for C - Copyright (c) 2007-14 Mike Karlesky, Mark VanderVoord, Greg Williams + Copyright (c) 2007-19 Mike Karlesky, Mark VanderVoord, Greg Williams [Released under MIT License. Please refer to license.txt for details] ========================================== */ @@ -8,6 +8,11 @@ #define UNITY_FRAMEWORK_H #define UNITY +#define UNITY_VERSION_MAJOR 2 +#define UNITY_VERSION_MINOR 5 +#define UNITY_VERSION_BUILD 0 +#define UNITY_VERSION ((UNITY_VERSION_MAJOR << 16) | (UNITY_VERSION_MINOR << 8) | UNITY_VERSION_BUILD) + #ifdef __cplusplus extern "C" { @@ -19,38 +24,33 @@ extern "C" * Test Setup / Teardown *-------------------------------------------------------*/ -/* These functions are intended to be called before and after each test. */ +/* These functions are intended to be called before and after each test. + * If using unity directly, these will need to be provided for each test + * executable built. If you are using the test runner generator and/or + * Ceedling, these are optional. */ void setUp(void); void tearDown(void); /* These functions are intended to be called at the beginning and end of an * entire test suite. suiteTearDown() is passed the number of tests that - * failed, and its return value becomes the exit code of main(). */ + * failed, and its return value becomes the exit code of main(). If using + * Unity directly, you're in charge of calling these if they are desired. + * If using Ceedling or the test runner generator, these will be called + * automatically if they exist. */ void suiteSetUp(void); int suiteTearDown(int num_failures); -/* If the compiler supports it, the following block provides stub - * implementations of the above functions as weak symbols. Note that on - * some platforms (MinGW for example), weak function implementations need - * to be in the same translation unit they are called from. This can be - * achieved by defining UNITY_INCLUDE_SETUP_STUBS before including unity.h. */ -#ifdef UNITY_INCLUDE_SETUP_STUBS - #ifdef UNITY_WEAK_ATTRIBUTE - UNITY_WEAK_ATTRIBUTE void setUp(void) { } - UNITY_WEAK_ATTRIBUTE void tearDown(void) { } - UNITY_WEAK_ATTRIBUTE void suiteSetUp(void) { } - UNITY_WEAK_ATTRIBUTE int suiteTearDown(int num_failures) { return num_failures; } - #elif defined(UNITY_WEAK_PRAGMA) - #pragma weak setUp - void setUp(void) { } - #pragma weak tearDown - void tearDown(void) { } - #pragma weak suiteSetUp - void suiteSetUp(void) { } - #pragma weak suiteTearDown - int suiteTearDown(int num_failures) { return num_failures; } - #endif -#endif +/*------------------------------------------------------- + * Test Reset and Verify + *-------------------------------------------------------*/ + +/* These functions are intended to be called before during tests in order + * to support complex test loops, etc. Both are NOT built into Unity. Instead + * the test runner generator will create them. resetTest will run teardown and + * setup again, verifying any end-of-test needs between. verifyTest will only + * run the verification. */ +void resetTest(void); +void verifyTest(void); /*------------------------------------------------------- * Configuration Options @@ -102,11 +102,13 @@ int suiteTearDown(int num_failures); #define TEST_FAIL() UNITY_TEST_FAIL(__LINE__, NULL) #define TEST_IGNORE_MESSAGE(message) UNITY_TEST_IGNORE(__LINE__, (message)) #define TEST_IGNORE() UNITY_TEST_IGNORE(__LINE__, NULL) +#define TEST_MESSAGE(message) UnityMessage((message), __LINE__) #define TEST_ONLY() /* It is not necessary for you to call PASS. A PASS condition is assumed if nothing fails. * This method allows you to abort a test immediately with a PASS state, ignoring the remainder of the test. */ #define TEST_PASS() TEST_ABORT() +#define TEST_PASS_MESSAGE(message) do { UnityMessage((message), __LINE__); TEST_ABORT(); } while(0) /* This macro does nothing, but it is useful for build tools (like Ceedling) to make use of this to figure out * which files should be linked to in order to perform a test. Use it like TEST_FILE("sandwiches.c") */ @@ -130,18 +132,18 @@ int suiteTearDown(int num_failures); #define TEST_ASSERT_EQUAL_INT16(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT16((expected), (actual), __LINE__, NULL) #define TEST_ASSERT_EQUAL_INT32(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT32((expected), (actual), __LINE__, NULL) #define TEST_ASSERT_EQUAL_INT64(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT64((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL(expected, actual) UNITY_TEST_ASSERT(((expected) != (actual)), __LINE__, " Expected Not-Equal") #define TEST_ASSERT_EQUAL_UINT(expected, actual) UNITY_TEST_ASSERT_EQUAL_UINT( (expected), (actual), __LINE__, NULL) #define TEST_ASSERT_EQUAL_UINT8(expected, actual) UNITY_TEST_ASSERT_EQUAL_UINT8( (expected), (actual), __LINE__, NULL) #define TEST_ASSERT_EQUAL_UINT16(expected, actual) UNITY_TEST_ASSERT_EQUAL_UINT16( (expected), (actual), __LINE__, NULL) #define TEST_ASSERT_EQUAL_UINT32(expected, actual) UNITY_TEST_ASSERT_EQUAL_UINT32( (expected), (actual), __LINE__, NULL) #define TEST_ASSERT_EQUAL_UINT64(expected, actual) UNITY_TEST_ASSERT_EQUAL_UINT64( (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_size_t(expected, actual) UNITY_TEST_ASSERT_EQUAL_UINT((expected), (actual), __LINE__, NULL) #define TEST_ASSERT_EQUAL_HEX(expected, actual) UNITY_TEST_ASSERT_EQUAL_HEX32((expected), (actual), __LINE__, NULL) #define TEST_ASSERT_EQUAL_HEX8(expected, actual) UNITY_TEST_ASSERT_EQUAL_HEX8( (expected), (actual), __LINE__, NULL) #define TEST_ASSERT_EQUAL_HEX16(expected, actual) UNITY_TEST_ASSERT_EQUAL_HEX16((expected), (actual), __LINE__, NULL) #define TEST_ASSERT_EQUAL_HEX32(expected, actual) UNITY_TEST_ASSERT_EQUAL_HEX32((expected), (actual), __LINE__, NULL) #define TEST_ASSERT_EQUAL_HEX64(expected, actual) UNITY_TEST_ASSERT_EQUAL_HEX64((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_CHAR(expected, actual) UNITY_TEST_ASSERT_EQUAL_CHAR((expected), (actual), __LINE__, NULL) #define TEST_ASSERT_BITS(mask, expected, actual) UNITY_TEST_ASSERT_BITS((mask), (expected), (actual), __LINE__, NULL) #define TEST_ASSERT_BITS_HIGH(mask, actual) UNITY_TEST_ASSERT_BITS((mask), (UNITY_UINT32)(-1), (actual), __LINE__, NULL) #define TEST_ASSERT_BITS_LOW(mask, actual) UNITY_TEST_ASSERT_BITS((mask), (UNITY_UINT32)(0), (actual), __LINE__, NULL) @@ -160,10 +162,12 @@ int suiteTearDown(int num_failures); #define TEST_ASSERT_GREATER_THAN_UINT16(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_UINT16((threshold), (actual), __LINE__, NULL) #define TEST_ASSERT_GREATER_THAN_UINT32(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_UINT32((threshold), (actual), __LINE__, NULL) #define TEST_ASSERT_GREATER_THAN_UINT64(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_UINT64((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_THAN_size_t(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_UINT((threshold), (actual), __LINE__, NULL) #define TEST_ASSERT_GREATER_THAN_HEX8(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_HEX8((threshold), (actual), __LINE__, NULL) #define TEST_ASSERT_GREATER_THAN_HEX16(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_HEX16((threshold), (actual), __LINE__, NULL) #define TEST_ASSERT_GREATER_THAN_HEX32(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_HEX32((threshold), (actual), __LINE__, NULL) #define TEST_ASSERT_GREATER_THAN_HEX64(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_HEX64((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_THAN_CHAR(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_CHAR((threshold), (actual), __LINE__, NULL) #define TEST_ASSERT_LESS_THAN(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_INT((threshold), (actual), __LINE__, NULL) #define TEST_ASSERT_LESS_THAN_INT(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_INT((threshold), (actual), __LINE__, NULL) @@ -176,10 +180,12 @@ int suiteTearDown(int num_failures); #define TEST_ASSERT_LESS_THAN_UINT16(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_UINT16((threshold), (actual), __LINE__, NULL) #define TEST_ASSERT_LESS_THAN_UINT32(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_UINT32((threshold), (actual), __LINE__, NULL) #define TEST_ASSERT_LESS_THAN_UINT64(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_UINT64((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_THAN_size_t(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_UINT((threshold), (actual), __LINE__, NULL) #define TEST_ASSERT_LESS_THAN_HEX8(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_HEX8((threshold), (actual), __LINE__, NULL) #define TEST_ASSERT_LESS_THAN_HEX16(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_HEX16((threshold), (actual), __LINE__, NULL) #define TEST_ASSERT_LESS_THAN_HEX32(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_HEX32((threshold), (actual), __LINE__, NULL) #define TEST_ASSERT_LESS_THAN_HEX64(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_HEX64((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_THAN_CHAR(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_CHAR((threshold), (actual), __LINE__, NULL) #define TEST_ASSERT_GREATER_OR_EQUAL(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT((threshold), (actual), __LINE__, NULL) #define TEST_ASSERT_GREATER_OR_EQUAL_INT(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT((threshold), (actual), __LINE__, NULL) @@ -192,10 +198,12 @@ int suiteTearDown(int num_failures); #define TEST_ASSERT_GREATER_OR_EQUAL_UINT16(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT16((threshold), (actual), __LINE__, NULL) #define TEST_ASSERT_GREATER_OR_EQUAL_UINT32(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT32((threshold), (actual), __LINE__, NULL) #define TEST_ASSERT_GREATER_OR_EQUAL_UINT64(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT64((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_OR_EQUAL_size_t(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT((threshold), (actual), __LINE__, NULL) #define TEST_ASSERT_GREATER_OR_EQUAL_HEX8(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX8((threshold), (actual), __LINE__, NULL) #define TEST_ASSERT_GREATER_OR_EQUAL_HEX16(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX16((threshold), (actual), __LINE__, NULL) #define TEST_ASSERT_GREATER_OR_EQUAL_HEX32(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX32((threshold), (actual), __LINE__, NULL) #define TEST_ASSERT_GREATER_OR_EQUAL_HEX64(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX64((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_GREATER_OR_EQUAL_CHAR(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_CHAR((threshold), (actual), __LINE__, NULL) #define TEST_ASSERT_LESS_OR_EQUAL(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT((threshold), (actual), __LINE__, NULL) #define TEST_ASSERT_LESS_OR_EQUAL_INT(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT((threshold), (actual), __LINE__, NULL) @@ -208,10 +216,12 @@ int suiteTearDown(int num_failures); #define TEST_ASSERT_LESS_OR_EQUAL_UINT16(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT16((threshold), (actual), __LINE__, NULL) #define TEST_ASSERT_LESS_OR_EQUAL_UINT32(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT32((threshold), (actual), __LINE__, NULL) #define TEST_ASSERT_LESS_OR_EQUAL_UINT64(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT64((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_OR_EQUAL_size_t(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT((threshold), (actual), __LINE__, NULL) #define TEST_ASSERT_LESS_OR_EQUAL_HEX8(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX8((threshold), (actual), __LINE__, NULL) #define TEST_ASSERT_LESS_OR_EQUAL_HEX16(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX16((threshold), (actual), __LINE__, NULL) #define TEST_ASSERT_LESS_OR_EQUAL_HEX32(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX32((threshold), (actual), __LINE__, NULL) #define TEST_ASSERT_LESS_OR_EQUAL_HEX64(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX64((threshold), (actual), __LINE__, NULL) +#define TEST_ASSERT_LESS_OR_EQUAL_CHAR(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_CHAR((threshold), (actual), __LINE__, NULL) /* Integer Ranges (of all sizes) */ #define TEST_ASSERT_INT_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_INT_WITHIN((delta), (expected), (actual), __LINE__, NULL) @@ -224,11 +234,33 @@ int suiteTearDown(int num_failures); #define TEST_ASSERT_UINT16_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_UINT16_WITHIN((delta), (expected), (actual), __LINE__, NULL) #define TEST_ASSERT_UINT32_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_UINT32_WITHIN((delta), (expected), (actual), __LINE__, NULL) #define TEST_ASSERT_UINT64_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_UINT64_WITHIN((delta), (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_size_t_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_UINT_WITHIN((delta), (expected), (actual), __LINE__, NULL) #define TEST_ASSERT_HEX_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_HEX32_WITHIN((delta), (expected), (actual), __LINE__, NULL) #define TEST_ASSERT_HEX8_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_HEX8_WITHIN((delta), (expected), (actual), __LINE__, NULL) #define TEST_ASSERT_HEX16_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_HEX16_WITHIN((delta), (expected), (actual), __LINE__, NULL) #define TEST_ASSERT_HEX32_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_HEX32_WITHIN((delta), (expected), (actual), __LINE__, NULL) #define TEST_ASSERT_HEX64_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_HEX64_WITHIN((delta), (expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_CHAR_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_CHAR_WITHIN((delta), (expected), (actual), __LINE__, NULL) + +/* Integer Array Ranges (of all sizes) */ +#define TEST_ASSERT_INT_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_INT_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) +#define TEST_ASSERT_INT8_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_INT8_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) +#define TEST_ASSERT_INT16_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_INT16_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) +#define TEST_ASSERT_INT32_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_INT32_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) +#define TEST_ASSERT_INT64_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_INT64_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) +#define TEST_ASSERT_UINT_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_UINT_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) +#define TEST_ASSERT_UINT8_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_UINT8_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) +#define TEST_ASSERT_UINT16_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_UINT16_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) +#define TEST_ASSERT_UINT32_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_UINT32_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) +#define TEST_ASSERT_UINT64_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_UINT64_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) +#define TEST_ASSERT_size_t_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_UINT_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) +#define TEST_ASSERT_HEX_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_HEX32_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) +#define TEST_ASSERT_HEX8_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_HEX8_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) +#define TEST_ASSERT_HEX16_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_HEX16_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) +#define TEST_ASSERT_HEX32_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_HEX32_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) +#define TEST_ASSERT_HEX64_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_HEX64_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) +#define TEST_ASSERT_CHAR_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_CHAR_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) + /* Structs and Strings */ #define TEST_ASSERT_EQUAL_PTR(expected, actual) UNITY_TEST_ASSERT_EQUAL_PTR((expected), (actual), __LINE__, NULL) @@ -247,6 +279,7 @@ int suiteTearDown(int num_failures); #define TEST_ASSERT_EQUAL_UINT16_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_UINT16_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) #define TEST_ASSERT_EQUAL_UINT32_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_UINT32_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) #define TEST_ASSERT_EQUAL_UINT64_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_UINT64_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_size_t_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_UINT_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) #define TEST_ASSERT_EQUAL_HEX_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_HEX32_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) #define TEST_ASSERT_EQUAL_HEX8_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_HEX8_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) #define TEST_ASSERT_EQUAL_HEX16_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_HEX16_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) @@ -255,6 +288,7 @@ int suiteTearDown(int num_failures); #define TEST_ASSERT_EQUAL_PTR_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_PTR_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) #define TEST_ASSERT_EQUAL_STRING_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_STRING_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) #define TEST_ASSERT_EQUAL_MEMORY_ARRAY(expected, actual, len, num_elements) UNITY_TEST_ASSERT_EQUAL_MEMORY_ARRAY((expected), (actual), (len), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EQUAL_CHAR_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_CHAR_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) /* Arrays Compared To Single Value */ #define TEST_ASSERT_EACH_EQUAL_INT(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_INT((expected), (actual), (num_elements), __LINE__, NULL) @@ -267,6 +301,7 @@ int suiteTearDown(int num_failures); #define TEST_ASSERT_EACH_EQUAL_UINT16(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_UINT16((expected), (actual), (num_elements), __LINE__, NULL) #define TEST_ASSERT_EACH_EQUAL_UINT32(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_UINT32((expected), (actual), (num_elements), __LINE__, NULL) #define TEST_ASSERT_EACH_EQUAL_UINT64(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_UINT64((expected), (actual), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_size_t(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_UINT((expected), (actual), (num_elements), __LINE__, NULL) #define TEST_ASSERT_EACH_EQUAL_HEX(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_HEX32((expected), (actual), (num_elements), __LINE__, NULL) #define TEST_ASSERT_EACH_EQUAL_HEX8(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_HEX8((expected), (actual), (num_elements), __LINE__, NULL) #define TEST_ASSERT_EACH_EQUAL_HEX16(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_HEX16((expected), (actual), (num_elements), __LINE__, NULL) @@ -275,6 +310,7 @@ int suiteTearDown(int num_failures); #define TEST_ASSERT_EACH_EQUAL_PTR(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_PTR((expected), (actual), (num_elements), __LINE__, NULL) #define TEST_ASSERT_EACH_EQUAL_STRING(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_STRING((expected), (actual), (num_elements), __LINE__, NULL) #define TEST_ASSERT_EACH_EQUAL_MEMORY(expected, actual, len, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_MEMORY((expected), (actual), (len), (num_elements), __LINE__, NULL) +#define TEST_ASSERT_EACH_EQUAL_CHAR(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_CHAR((expected), (actual), (num_elements), __LINE__, NULL) /* Floating Point (If Enabled) */ #define TEST_ASSERT_FLOAT_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_FLOAT_WITHIN((delta), (expected), (actual), __LINE__, NULL) @@ -304,6 +340,28 @@ int suiteTearDown(int num_failures); #define TEST_ASSERT_DOUBLE_IS_NOT_NAN(actual) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NAN((actual), __LINE__, NULL) #define TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE(actual) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE((actual), __LINE__, NULL) +/* Shorthand */ +#ifdef UNITY_SHORTHAND_AS_OLD +#define TEST_ASSERT_EQUAL(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_NOT_EQUAL(expected, actual) UNITY_TEST_ASSERT(((expected) != (actual)), __LINE__, " Expected Not-Equal") +#endif +#ifdef UNITY_SHORTHAND_AS_INT +#define TEST_ASSERT_EQUAL(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, NULL) +#define TEST_ASSERT_NOT_EQUAL(expected, actual) UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand) +#endif +#ifdef UNITY_SHORTHAND_AS_MEM +#define TEST_ASSERT_EQUAL(expected, actual) UNITY_TEST_ASSERT_EQUAL_MEMORY((&expected), (&actual), sizeof(expected), __LINE__, NULL) +#define TEST_ASSERT_NOT_EQUAL(expected, actual) UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand) +#endif +#ifdef UNITY_SHORTHAND_AS_RAW +#define TEST_ASSERT_EQUAL(expected, actual) UNITY_TEST_ASSERT(((expected) == (actual)), __LINE__, " Expected Equal") +#define TEST_ASSERT_NOT_EQUAL(expected, actual) UNITY_TEST_ASSERT(((expected) != (actual)), __LINE__, " Expected Not-Equal") +#endif +#ifdef UNITY_SHORTHAND_AS_NONE +#define TEST_ASSERT_EQUAL(expected, actual) UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand) +#define TEST_ASSERT_NOT_EQUAL(expected, actual) UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand) +#endif + /*------------------------------------------------------- * Test Asserts (with additional messages) *-------------------------------------------------------*/ @@ -322,13 +380,12 @@ int suiteTearDown(int num_failures); #define TEST_ASSERT_EQUAL_INT16_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT16((expected), (actual), __LINE__, (message)) #define TEST_ASSERT_EQUAL_INT32_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT32((expected), (actual), __LINE__, (message)) #define TEST_ASSERT_EQUAL_INT64_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT64((expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT(((expected) != (actual)), __LINE__, (message)) #define TEST_ASSERT_EQUAL_UINT_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_UINT( (expected), (actual), __LINE__, (message)) #define TEST_ASSERT_EQUAL_UINT8_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_UINT8( (expected), (actual), __LINE__, (message)) #define TEST_ASSERT_EQUAL_UINT16_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_UINT16( (expected), (actual), __LINE__, (message)) #define TEST_ASSERT_EQUAL_UINT32_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_UINT32( (expected), (actual), __LINE__, (message)) #define TEST_ASSERT_EQUAL_UINT64_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_UINT64( (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_size_t_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_UINT( (expected), (actual), __LINE__, (message)) #define TEST_ASSERT_EQUAL_HEX_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_HEX32((expected), (actual), __LINE__, (message)) #define TEST_ASSERT_EQUAL_HEX8_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_HEX8( (expected), (actual), __LINE__, (message)) #define TEST_ASSERT_EQUAL_HEX16_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_HEX16((expected), (actual), __LINE__, (message)) @@ -339,6 +396,7 @@ int suiteTearDown(int num_failures); #define TEST_ASSERT_BITS_LOW_MESSAGE(mask, actual, message) UNITY_TEST_ASSERT_BITS((mask), (UNITY_UINT32)(0), (actual), __LINE__, (message)) #define TEST_ASSERT_BIT_HIGH_MESSAGE(bit, actual, message) UNITY_TEST_ASSERT_BITS(((UNITY_UINT32)1 << (bit)), (UNITY_UINT32)(-1), (actual), __LINE__, (message)) #define TEST_ASSERT_BIT_LOW_MESSAGE(bit, actual, message) UNITY_TEST_ASSERT_BITS(((UNITY_UINT32)1 << (bit)), (UNITY_UINT32)(0), (actual), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_CHAR_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_CHAR((expected), (actual), __LINE__, (message)) /* Integer Greater Than/ Less Than (of all sizes) */ #define TEST_ASSERT_GREATER_THAN_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_INT((threshold), (actual), __LINE__, (message)) @@ -352,10 +410,12 @@ int suiteTearDown(int num_failures); #define TEST_ASSERT_GREATER_THAN_UINT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_UINT16((threshold), (actual), __LINE__, (message)) #define TEST_ASSERT_GREATER_THAN_UINT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_UINT32((threshold), (actual), __LINE__, (message)) #define TEST_ASSERT_GREATER_THAN_UINT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_UINT64((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_THAN_size_t_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_UINT((threshold), (actual), __LINE__, (message)) #define TEST_ASSERT_GREATER_THAN_HEX8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_HEX8((threshold), (actual), __LINE__, (message)) #define TEST_ASSERT_GREATER_THAN_HEX16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_HEX16((threshold), (actual), __LINE__, (message)) #define TEST_ASSERT_GREATER_THAN_HEX32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_HEX32((threshold), (actual), __LINE__, (message)) #define TEST_ASSERT_GREATER_THAN_HEX64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_HEX64((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_THAN_CHAR_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_CHAR((threshold), (actual), __LINE__, (message)) #define TEST_ASSERT_LESS_THAN_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_INT((threshold), (actual), __LINE__, (message)) #define TEST_ASSERT_LESS_THAN_INT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_INT((threshold), (actual), __LINE__, (message)) @@ -368,10 +428,12 @@ int suiteTearDown(int num_failures); #define TEST_ASSERT_LESS_THAN_UINT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_UINT16((threshold), (actual), __LINE__, (message)) #define TEST_ASSERT_LESS_THAN_UINT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_UINT32((threshold), (actual), __LINE__, (message)) #define TEST_ASSERT_LESS_THAN_UINT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_UINT64((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_THAN_size_t_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_UINT((threshold), (actual), __LINE__, (message)) #define TEST_ASSERT_LESS_THAN_HEX8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_HEX8((threshold), (actual), __LINE__, (message)) #define TEST_ASSERT_LESS_THAN_HEX16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_HEX16((threshold), (actual), __LINE__, (message)) #define TEST_ASSERT_LESS_THAN_HEX32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_HEX32((threshold), (actual), __LINE__, (message)) #define TEST_ASSERT_LESS_THAN_HEX64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_HEX64((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_THAN_CHAR_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_CHAR((threshold), (actual), __LINE__, (message)) #define TEST_ASSERT_GREATER_OR_EQUAL_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT((threshold), (actual), __LINE__, (message)) #define TEST_ASSERT_GREATER_OR_EQUAL_INT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT((threshold), (actual), __LINE__, (message)) @@ -384,10 +446,12 @@ int suiteTearDown(int num_failures); #define TEST_ASSERT_GREATER_OR_EQUAL_UINT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT16((threshold), (actual), __LINE__, (message)) #define TEST_ASSERT_GREATER_OR_EQUAL_UINT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT32((threshold), (actual), __LINE__, (message)) #define TEST_ASSERT_GREATER_OR_EQUAL_UINT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT64((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_OR_EQUAL_size_t_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT((threshold), (actual), __LINE__, (message)) #define TEST_ASSERT_GREATER_OR_EQUAL_HEX8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX8((threshold), (actual), __LINE__, (message)) #define TEST_ASSERT_GREATER_OR_EQUAL_HEX16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX16((threshold), (actual), __LINE__, (message)) #define TEST_ASSERT_GREATER_OR_EQUAL_HEX32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX32((threshold), (actual), __LINE__, (message)) #define TEST_ASSERT_GREATER_OR_EQUAL_HEX64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX64((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_GREATER_OR_EQUAL_CHAR_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_CHAR((threshold), (actual), __LINE__, (message)) #define TEST_ASSERT_LESS_OR_EQUAL_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT((threshold), (actual), __LINE__, (message)) #define TEST_ASSERT_LESS_OR_EQUAL_INT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT((threshold), (actual), __LINE__, (message)) @@ -400,10 +464,12 @@ int suiteTearDown(int num_failures); #define TEST_ASSERT_LESS_OR_EQUAL_UINT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT16((threshold), (actual), __LINE__, (message)) #define TEST_ASSERT_LESS_OR_EQUAL_UINT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT32((threshold), (actual), __LINE__, (message)) #define TEST_ASSERT_LESS_OR_EQUAL_UINT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT64((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_OR_EQUAL_size_t_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT((threshold), (actual), __LINE__, (message)) #define TEST_ASSERT_LESS_OR_EQUAL_HEX8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX8((threshold), (actual), __LINE__, (message)) #define TEST_ASSERT_LESS_OR_EQUAL_HEX16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX16((threshold), (actual), __LINE__, (message)) #define TEST_ASSERT_LESS_OR_EQUAL_HEX32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX32((threshold), (actual), __LINE__, (message)) #define TEST_ASSERT_LESS_OR_EQUAL_HEX64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX64((threshold), (actual), __LINE__, (message)) +#define TEST_ASSERT_LESS_OR_EQUAL_CHAR_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_CHAR((threshold), (actual), __LINE__, (message)) /* Integer Ranges (of all sizes) */ #define TEST_ASSERT_INT_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_INT_WITHIN((delta), (expected), (actual), __LINE__, (message)) @@ -416,11 +482,33 @@ int suiteTearDown(int num_failures); #define TEST_ASSERT_UINT16_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_UINT16_WITHIN((delta), (expected), (actual), __LINE__, (message)) #define TEST_ASSERT_UINT32_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_UINT32_WITHIN((delta), (expected), (actual), __LINE__, (message)) #define TEST_ASSERT_UINT64_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_UINT64_WITHIN((delta), (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_size_t_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_UINT_WITHIN((delta), (expected), (actual), __LINE__, (message)) #define TEST_ASSERT_HEX_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_HEX32_WITHIN((delta), (expected), (actual), __LINE__, (message)) #define TEST_ASSERT_HEX8_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_HEX8_WITHIN((delta), (expected), (actual), __LINE__, (message)) #define TEST_ASSERT_HEX16_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_HEX16_WITHIN((delta), (expected), (actual), __LINE__, (message)) #define TEST_ASSERT_HEX32_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_HEX32_WITHIN((delta), (expected), (actual), __LINE__, (message)) #define TEST_ASSERT_HEX64_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_HEX64_WITHIN((delta), (expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_CHAR_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_CHAR_WITHIN((delta), (expected), (actual), __LINE__, (message)) + +/* Integer Array Ranges (of all sizes) */ +#define TEST_ASSERT_INT_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_INT_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) +#define TEST_ASSERT_INT8_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_INT8_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) +#define TEST_ASSERT_INT16_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_INT16_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) +#define TEST_ASSERT_INT32_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_INT32_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) +#define TEST_ASSERT_INT64_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_INT64_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) +#define TEST_ASSERT_UINT_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_UINT_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) +#define TEST_ASSERT_UINT8_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_UINT8_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) +#define TEST_ASSERT_UINT16_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_UINT16_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) +#define TEST_ASSERT_UINT32_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_UINT32_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) +#define TEST_ASSERT_UINT64_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_UINT64_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) +#define TEST_ASSERT_size_t_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_UINT_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) +#define TEST_ASSERT_HEX_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_HEX32_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) +#define TEST_ASSERT_HEX8_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_HEX8_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) +#define TEST_ASSERT_HEX16_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_HEX16_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) +#define TEST_ASSERT_HEX32_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_HEX32_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) +#define TEST_ASSERT_HEX64_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_HEX64_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) +#define TEST_ASSERT_CHAR_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_CHAR_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) + /* Structs and Strings */ #define TEST_ASSERT_EQUAL_PTR_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_PTR((expected), (actual), __LINE__, (message)) @@ -439,6 +527,7 @@ int suiteTearDown(int num_failures); #define TEST_ASSERT_EQUAL_UINT16_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_UINT16_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) #define TEST_ASSERT_EQUAL_UINT32_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_UINT32_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) #define TEST_ASSERT_EQUAL_UINT64_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_UINT64_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_size_t_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_UINT_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) #define TEST_ASSERT_EQUAL_HEX_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_HEX32_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) #define TEST_ASSERT_EQUAL_HEX8_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_HEX8_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) #define TEST_ASSERT_EQUAL_HEX16_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_HEX16_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) @@ -447,6 +536,7 @@ int suiteTearDown(int num_failures); #define TEST_ASSERT_EQUAL_PTR_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_PTR_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) #define TEST_ASSERT_EQUAL_STRING_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_STRING_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) #define TEST_ASSERT_EQUAL_MEMORY_ARRAY_MESSAGE(expected, actual, len, num_elements, message) UNITY_TEST_ASSERT_EQUAL_MEMORY_ARRAY((expected), (actual), (len), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EQUAL_CHAR_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_CHAR_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) /* Arrays Compared To Single Value*/ #define TEST_ASSERT_EACH_EQUAL_INT_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_INT((expected), (actual), (num_elements), __LINE__, (message)) @@ -459,6 +549,7 @@ int suiteTearDown(int num_failures); #define TEST_ASSERT_EACH_EQUAL_UINT16_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_UINT16((expected), (actual), (num_elements), __LINE__, (message)) #define TEST_ASSERT_EACH_EQUAL_UINT32_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_UINT32((expected), (actual), (num_elements), __LINE__, (message)) #define TEST_ASSERT_EACH_EQUAL_UINT64_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_UINT64((expected), (actual), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_size_t_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_UINT((expected), (actual), (num_elements), __LINE__, (message)) #define TEST_ASSERT_EACH_EQUAL_HEX_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_HEX32((expected), (actual), (num_elements), __LINE__, (message)) #define TEST_ASSERT_EACH_EQUAL_HEX8_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_HEX8((expected), (actual), (num_elements), __LINE__, (message)) #define TEST_ASSERT_EACH_EQUAL_HEX16_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_HEX16((expected), (actual), (num_elements), __LINE__, (message)) @@ -467,6 +558,7 @@ int suiteTearDown(int num_failures); #define TEST_ASSERT_EACH_EQUAL_PTR_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_PTR((expected), (actual), (num_elements), __LINE__, (message)) #define TEST_ASSERT_EACH_EQUAL_STRING_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_STRING((expected), (actual), (num_elements), __LINE__, (message)) #define TEST_ASSERT_EACH_EQUAL_MEMORY_MESSAGE(expected, actual, len, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_MEMORY((expected), (actual), (len), (num_elements), __LINE__, (message)) +#define TEST_ASSERT_EACH_EQUAL_CHAR_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_CHAR((expected), (actual), (num_elements), __LINE__, (message)) /* Floating Point (If Enabled) */ #define TEST_ASSERT_FLOAT_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_FLOAT_WITHIN((delta), (expected), (actual), __LINE__, (message)) @@ -496,6 +588,28 @@ int suiteTearDown(int num_failures); #define TEST_ASSERT_DOUBLE_IS_NOT_NAN_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NAN((actual), __LINE__, (message)) #define TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE((actual), __LINE__, (message)) +/* Shorthand */ +#ifdef UNITY_SHORTHAND_AS_OLD +#define TEST_ASSERT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, (message)) +#define TEST_ASSERT_NOT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT(((expected) != (actual)), __LINE__, (message)) +#endif +#ifdef UNITY_SHORTHAND_AS_INT +#define TEST_ASSERT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, message) +#define TEST_ASSERT_NOT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand) +#endif +#ifdef UNITY_SHORTHAND_AS_MEM +#define TEST_ASSERT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_MEMORY((&expected), (&actual), sizeof(expected), __LINE__, message) +#define TEST_ASSERT_NOT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand) +#endif +#ifdef UNITY_SHORTHAND_AS_RAW +#define TEST_ASSERT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT(((expected) == (actual)), __LINE__, message) +#define TEST_ASSERT_NOT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT(((expected) != (actual)), __LINE__, message) +#endif +#ifdef UNITY_SHORTHAND_AS_NONE +#define TEST_ASSERT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand) +#define TEST_ASSERT_NOT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand) +#endif + /* end of UNITY_FRAMEWORK_H */ #ifdef __cplusplus } diff --git a/test/vendor/ceedling/vendor/unity/src/unity_internals.h b/test/vendor/ceedling/vendor/unity/src/unity_internals.h index 351d9fe6..a9a7ea23 100644 --- a/test/vendor/ceedling/vendor/unity/src/unity_internals.h +++ b/test/vendor/ceedling/vendor/unity/src/unity_internals.h @@ -1,6 +1,6 @@ /* ========================================== Unity Project - A Test Framework for C - Copyright (c) 2007-14 Mike Karlesky, Mark VanderVoord, Greg Williams + Copyright (c) 2007-19 Mike Karlesky, Mark VanderVoord, Greg Williams [Released under MIT License. Please refer to license.txt for details] ========================================== */ @@ -19,6 +19,14 @@ #include #endif +#ifndef UNITY_EXCLUDE_STDDEF_H +#include +#endif + +#ifdef UNITY_INCLUDE_PRINT_FORMATTED +#include +#endif + /* Unity Attempts to Auto-Detect Integer Types * Attempt 1: UINT_MAX, ULONG_MAX in , or default to 32 bits * Attempt 2: UINTPTR_MAX in , or default to same size as long @@ -32,10 +40,6 @@ #include #endif -#ifndef UNITY_EXCLUDE_TIME_H -#include -#endif - /*------------------------------------------------------- * Guess Widths If Not Specified *-------------------------------------------------------*/ @@ -43,6 +47,8 @@ /* Determine the size of an int, if not already specified. * We cannot use sizeof(int), because it is not yet defined * at this stage in the translation of the C program. + * Also sizeof(int) does return the size in addressable units on all platforms, + * which may not necessarily be the size in bytes. * Therefore, infer it from UINT_MAX if possible. */ #ifndef UNITY_INT_WIDTH #ifdef UINT_MAX @@ -114,19 +120,21 @@ * 64-bit Support *-------------------------------------------------------*/ +/* Auto-detect 64 Bit Support */ #ifndef UNITY_SUPPORT_64 #if UNITY_LONG_WIDTH == 64 || UNITY_POINTER_WIDTH == 64 #define UNITY_SUPPORT_64 #endif #endif +/* 64-Bit Support Dependent Configuration */ #ifndef UNITY_SUPPORT_64 /* No 64-bit Support */ typedef UNITY_UINT32 UNITY_UINT; - typedef UNITY_INT32 UNITY_INT; + typedef UNITY_INT32 UNITY_INT; + #define UNITY_MAX_NIBBLES (8) /* Maximum number of nibbles in a UNITY_(U)INT */ #else - - /* 64-bit Support */ + /* 64-bit Support */ #if (UNITY_LONG_WIDTH == 32) typedef unsigned long long UNITY_UINT64; typedef signed long long UNITY_INT64; @@ -137,8 +145,8 @@ #error Invalid UNITY_LONG_WIDTH specified! (32 or 64 are supported) #endif typedef UNITY_UINT64 UNITY_UINT; - typedef UNITY_INT64 UNITY_INT; - + typedef UNITY_INT64 UNITY_INT; + #define UNITY_MAX_NIBBLES (16) /* Maximum number of nibbles in a UNITY_(U)INT */ #endif /*------------------------------------------------------- @@ -146,24 +154,24 @@ *-------------------------------------------------------*/ #if (UNITY_POINTER_WIDTH == 32) -#define UNITY_PTR_TO_INT UNITY_INT32 -#define UNITY_DISPLAY_STYLE_POINTER UNITY_DISPLAY_STYLE_HEX32 + #define UNITY_PTR_TO_INT UNITY_INT32 + #define UNITY_DISPLAY_STYLE_POINTER UNITY_DISPLAY_STYLE_HEX32 #elif (UNITY_POINTER_WIDTH == 64) -#define UNITY_PTR_TO_INT UNITY_INT64 -#define UNITY_DISPLAY_STYLE_POINTER UNITY_DISPLAY_STYLE_HEX64 + #define UNITY_PTR_TO_INT UNITY_INT64 + #define UNITY_DISPLAY_STYLE_POINTER UNITY_DISPLAY_STYLE_HEX64 #elif (UNITY_POINTER_WIDTH == 16) -#define UNITY_PTR_TO_INT UNITY_INT16 -#define UNITY_DISPLAY_STYLE_POINTER UNITY_DISPLAY_STYLE_HEX16 + #define UNITY_PTR_TO_INT UNITY_INT16 + #define UNITY_DISPLAY_STYLE_POINTER UNITY_DISPLAY_STYLE_HEX16 #else - #error Invalid UNITY_POINTER_WIDTH specified! (16, 32 or 64 are supported) + #error Invalid UNITY_POINTER_WIDTH specified! (16, 32 or 64 are supported) #endif #ifndef UNITY_PTR_ATTRIBUTE -#define UNITY_PTR_ATTRIBUTE + #define UNITY_PTR_ATTRIBUTE #endif #ifndef UNITY_INTERNAL_PTR -#define UNITY_INTERNAL_PTR UNITY_PTR_ATTRIBUTE const void* + #define UNITY_INTERNAL_PTR UNITY_PTR_ATTRIBUTE const void* #endif /*------------------------------------------------------- @@ -289,42 +297,67 @@ typedef UNITY_FLOAT_TYPE UNITY_FLOAT; #define UNITY_OUTPUT_COMPLETE() #endif -#ifndef UNITY_EXEC_TIME_RESET #ifdef UNITY_INCLUDE_EXEC_TIME -#define UNITY_EXEC_TIME_RESET()\ - Unity.CurrentTestStartTime = 0;\ - Unity.CurrentTestStopTime = 0; -#else -#define UNITY_EXEC_TIME_RESET() -#endif + #if !defined(UNITY_EXEC_TIME_START) && \ + !defined(UNITY_EXEC_TIME_STOP) && \ + !defined(UNITY_PRINT_EXEC_TIME) && \ + !defined(UNITY_TIME_TYPE) + /* If none any of these macros are defined then try to provide a default implementation */ + + #if defined(UNITY_CLOCK_MS) + /* This is a simple way to get a default implementation on platforms that support getting a millisecond counter */ + #define UNITY_TIME_TYPE UNITY_UINT + #define UNITY_EXEC_TIME_START() Unity.CurrentTestStartTime = UNITY_CLOCK_MS() + #define UNITY_EXEC_TIME_STOP() Unity.CurrentTestStopTime = UNITY_CLOCK_MS() + #define UNITY_PRINT_EXEC_TIME() { \ + UNITY_UINT execTimeMs = (Unity.CurrentTestStopTime - Unity.CurrentTestStartTime); \ + UnityPrint(" ("); \ + UnityPrintNumberUnsigned(execTimeMs); \ + UnityPrint(" ms)"); \ + } + #elif defined(_WIN32) + #include + #define UNITY_TIME_TYPE clock_t + #define UNITY_GET_TIME(t) t = (clock_t)((clock() * 1000) / CLOCKS_PER_SEC) + #define UNITY_EXEC_TIME_START() UNITY_GET_TIME(Unity.CurrentTestStartTime) + #define UNITY_EXEC_TIME_STOP() UNITY_GET_TIME(Unity.CurrentTestStopTime) + #define UNITY_PRINT_EXEC_TIME() { \ + UNITY_UINT execTimeMs = (Unity.CurrentTestStopTime - Unity.CurrentTestStartTime); \ + UnityPrint(" ("); \ + UnityPrintNumberUnsigned(execTimeMs); \ + UnityPrint(" ms)"); \ + } + #elif defined(__unix__) + #include + #define UNITY_TIME_TYPE struct timespec + #define UNITY_GET_TIME(t) clock_gettime(CLOCK_MONOTONIC, &t) + #define UNITY_EXEC_TIME_START() UNITY_GET_TIME(Unity.CurrentTestStartTime) + #define UNITY_EXEC_TIME_STOP() UNITY_GET_TIME(Unity.CurrentTestStopTime) + #define UNITY_PRINT_EXEC_TIME() { \ + UNITY_UINT execTimeMs = ((Unity.CurrentTestStopTime.tv_sec - Unity.CurrentTestStartTime.tv_sec) * 1000L); \ + execTimeMs += ((Unity.CurrentTestStopTime.tv_nsec - Unity.CurrentTestStartTime.tv_nsec) / 1000000L); \ + UnityPrint(" ("); \ + UnityPrintNumberUnsigned(execTimeMs); \ + UnityPrint(" ms)"); \ + } + #endif + #endif #endif #ifndef UNITY_EXEC_TIME_START -#ifdef UNITY_INCLUDE_EXEC_TIME -#define UNITY_EXEC_TIME_START() Unity.CurrentTestStartTime = UNITY_CLOCK_MS(); -#else -#define UNITY_EXEC_TIME_START() -#endif +#define UNITY_EXEC_TIME_START() do{}while(0) #endif #ifndef UNITY_EXEC_TIME_STOP -#ifdef UNITY_INCLUDE_EXEC_TIME -#define UNITY_EXEC_TIME_STOP() Unity.CurrentTestStopTime = UNITY_CLOCK_MS(); -#else -#define UNITY_EXEC_TIME_STOP() +#define UNITY_EXEC_TIME_STOP() do{}while(0) #endif + +#ifndef UNITY_TIME_TYPE +#define UNITY_TIME_TYPE UNITY_UINT #endif #ifndef UNITY_PRINT_EXEC_TIME -#ifdef UNITY_INCLUDE_EXEC_TIME -#define UNITY_PRINT_EXEC_TIME() \ - UnityPrint(" (");\ - UNITY_COUNTER_TYPE execTimeMs = (Unity.CurrentTestStopTime - Unity.CurrentTestStartTime); - UnityPrintNumberUnsigned(execTimeMs);\ - UnityPrint(" ms)"); -#else -#define UNITY_PRINT_EXEC_TIME() -#endif +#define UNITY_PRINT_EXEC_TIME() do{}while(0) #endif /*------------------------------------------------------- @@ -339,23 +372,6 @@ typedef UNITY_FLOAT_TYPE UNITY_FLOAT; #define UNITY_COUNTER_TYPE UNITY_UINT #endif -/*------------------------------------------------------- - * Language Features Available - *-------------------------------------------------------*/ -#if !defined(UNITY_WEAK_ATTRIBUTE) && !defined(UNITY_WEAK_PRAGMA) -# if defined(__GNUC__) || defined(__ghs__) /* __GNUC__ includes clang */ -# if !(defined(__WIN32__) && defined(__clang__)) && !defined(__TMS470__) -# define UNITY_WEAK_ATTRIBUTE __attribute__((weak)) -# endif -# endif -#endif - -#ifdef UNITY_NO_WEAK -# undef UNITY_WEAK_ATTRIBUTE -# undef UNITY_WEAK_PRAGMA -#endif - - /*------------------------------------------------------- * Internal Structs Needed *-------------------------------------------------------*/ @@ -365,10 +381,11 @@ typedef void (*UnityTestFunction)(void); #define UNITY_DISPLAY_RANGE_INT (0x10) #define UNITY_DISPLAY_RANGE_UINT (0x20) #define UNITY_DISPLAY_RANGE_HEX (0x40) +#define UNITY_DISPLAY_RANGE_CHAR (0x80) typedef enum { -UNITY_DISPLAY_STYLE_INT = sizeof(int)+ UNITY_DISPLAY_RANGE_INT, + UNITY_DISPLAY_STYLE_INT = (UNITY_INT_WIDTH / 8) + UNITY_DISPLAY_RANGE_INT, UNITY_DISPLAY_STYLE_INT8 = 1 + UNITY_DISPLAY_RANGE_INT, UNITY_DISPLAY_STYLE_INT16 = 2 + UNITY_DISPLAY_RANGE_INT, UNITY_DISPLAY_STYLE_INT32 = 4 + UNITY_DISPLAY_RANGE_INT, @@ -376,7 +393,7 @@ UNITY_DISPLAY_STYLE_INT = sizeof(int)+ UNITY_DISPLAY_RANGE_INT, UNITY_DISPLAY_STYLE_INT64 = 8 + UNITY_DISPLAY_RANGE_INT, #endif -UNITY_DISPLAY_STYLE_UINT = sizeof(unsigned) + UNITY_DISPLAY_RANGE_UINT, + UNITY_DISPLAY_STYLE_UINT = (UNITY_INT_WIDTH / 8) + UNITY_DISPLAY_RANGE_UINT, UNITY_DISPLAY_STYLE_UINT8 = 1 + UNITY_DISPLAY_RANGE_UINT, UNITY_DISPLAY_STYLE_UINT16 = 2 + UNITY_DISPLAY_RANGE_UINT, UNITY_DISPLAY_STYLE_UINT32 = 4 + UNITY_DISPLAY_RANGE_UINT, @@ -391,16 +408,20 @@ UNITY_DISPLAY_STYLE_UINT = sizeof(unsigned) + UNITY_DISPLAY_RANGE_UINT, UNITY_DISPLAY_STYLE_HEX64 = 8 + UNITY_DISPLAY_RANGE_HEX, #endif + UNITY_DISPLAY_STYLE_CHAR = 1 + UNITY_DISPLAY_RANGE_CHAR + UNITY_DISPLAY_RANGE_INT, + UNITY_DISPLAY_STYLE_UNKNOWN } UNITY_DISPLAY_STYLE_T; typedef enum { - UNITY_EQUAL_TO = 1, - UNITY_GREATER_THAN = 2, - UNITY_GREATER_OR_EQUAL = 2 + UNITY_EQUAL_TO, - UNITY_SMALLER_THAN = 4, - UNITY_SMALLER_OR_EQUAL = 4 + UNITY_EQUAL_TO + UNITY_WITHIN = 0x0, + UNITY_EQUAL_TO = 0x1, + UNITY_GREATER_THAN = 0x2, + UNITY_GREATER_OR_EQUAL = 0x2 + UNITY_EQUAL_TO, + UNITY_SMALLER_THAN = 0x4, + UNITY_SMALLER_OR_EQUAL = 0x4 + UNITY_EQUAL_TO, + UNITY_UNKNOWN } UNITY_COMPARISON_T; #ifndef UNITY_EXCLUDE_FLOAT @@ -421,7 +442,8 @@ typedef enum UNITY_FLOAT_TRAIT typedef enum { UNITY_ARRAY_TO_VAL = 0, - UNITY_ARRAY_TO_ARRAY + UNITY_ARRAY_TO_ARRAY, + UNITY_ARRAY_UNKNOWN } UNITY_FLAGS_T; struct UNITY_STORAGE_T @@ -439,8 +461,8 @@ struct UNITY_STORAGE_T UNITY_COUNTER_TYPE CurrentTestFailed; UNITY_COUNTER_TYPE CurrentTestIgnored; #ifdef UNITY_INCLUDE_EXEC_TIME - UNITY_COUNTER_TYPE CurrentTestStartTime; - UNITY_COUNTER_TYPE CurrentTestStopTime; + UNITY_TIME_TYPE CurrentTestStartTime; + UNITY_TIME_TYPE CurrentTestStopTime; #endif #ifndef UNITY_EXCLUDE_SETJMP_H jmp_buf AbortFrame; @@ -455,6 +477,7 @@ extern struct UNITY_STORAGE_T Unity; void UnityBegin(const char* filename); int UnityEnd(void); +void UnitySetTestFile(const char* filename); void UnityConcludeTest(void); void UnityDefaultTestRun(UnityTestFunction Func, const char* FuncName, const int FuncLineNum); @@ -485,6 +508,11 @@ void UnityDefaultTestRun(UnityTestFunction Func, const char* FuncName, const int *-------------------------------------------------------*/ void UnityPrint(const char* string); + +#ifdef UNITY_INCLUDE_PRINT_FORMATTED +void UnityPrintFormatted(const char* format, ...); +#endif + void UnityPrintLen(const char* string, const UNITY_UINT32 length); void UnityPrintMask(const UNITY_UINT mask, const UNITY_UINT number); void UnityPrintNumberByStyle(const UNITY_INT number, const UNITY_DISPLAY_STYLE_T style); @@ -564,9 +592,18 @@ void UnityAssertNumbersWithin(const UNITY_UINT delta, const UNITY_LINE_TYPE lineNumber, const UNITY_DISPLAY_STYLE_T style); -void UnityFail(const char* msg, const UNITY_LINE_TYPE line); +void UnityAssertNumbersArrayWithin(const UNITY_UINT delta, + UNITY_INTERNAL_PTR expected, + UNITY_INTERNAL_PTR actual, + const UNITY_UINT32 num_elements, + const char* msg, + const UNITY_LINE_TYPE lineNumber, + const UNITY_DISPLAY_STYLE_T style, + const UNITY_FLAGS_T flags); -void UnityIgnore(const char* msg, const UNITY_LINE_TYPE line); +void UnityFail(const char* message, const UNITY_LINE_TYPE line); +void UnityIgnore(const char* message, const UNITY_LINE_TYPE line); +void UnityMessage(const char* message, const UNITY_LINE_TYPE line); #ifndef UNITY_EXCLUDE_FLOAT void UnityAssertFloatsWithin(const UNITY_FLOAT delta, @@ -624,9 +661,15 @@ UNITY_INTERNAL_PTR UnityDoubleToPtr(const double num); * Error Strings We Might Need *-------------------------------------------------------*/ +extern const char UnityStrOk[]; +extern const char UnityStrPass[]; +extern const char UnityStrFail[]; +extern const char UnityStrIgnore[]; + extern const char UnityStrErrFloat[]; extern const char UnityStrErrDouble[]; extern const char UnityStrErr64[]; +extern const char UnityStrErrShorthand[]; /*------------------------------------------------------- * Test Running Macros @@ -640,16 +683,14 @@ extern const char UnityStrErr64[]; #define TEST_ABORT() return #endif -#ifndef UNITY_EXCLUDE_TIME_H -#define UNITY_CLOCK_MS() (UNITY_COUNTER_TYPE)((clock() * 1000) / CLOCKS_PER_SEC) -#else -#define UNITY_CLOCK_MS() -#endif - /* This tricky series of macros gives us an optional line argument to treat it as RUN_TEST(func, num=__LINE__) */ #ifndef RUN_TEST #ifdef __STDC_VERSION__ #if __STDC_VERSION__ >= 199901L +#define UNITY_SUPPORT_VARIADIC_MACROS +#endif +#endif +#ifdef UNITY_SUPPORT_VARIADIC_MACROS #define RUN_TEST(...) UnityDefaultTestRun(RUN_TEST_FIRST(__VA_ARGS__), RUN_TEST_SECOND(__VA_ARGS__)) #define RUN_TEST_FIRST(...) RUN_TEST_FIRST_HELPER(__VA_ARGS__, throwaway) #define RUN_TEST_FIRST_HELPER(first, ...) (first), #first @@ -657,7 +698,6 @@ extern const char UnityStrErr64[]; #define RUN_TEST_SECOND_HELPER(first, second, ...) (second) #endif #endif -#endif /* If we can't do the tricky version, we'll just have to require them to always include the line number */ #ifndef RUN_TEST @@ -683,6 +723,16 @@ extern const char UnityStrErr64[]; #define UNITY_END() UnityEnd() #endif +#ifndef UNITY_SHORTHAND_AS_INT +#ifndef UNITY_SHORTHAND_AS_MEM +#ifndef UNITY_SHORTHAND_AS_NONE +#ifndef UNITY_SHORTHAND_AS_RAW +#define UNITY_SHORTHAND_AS_OLD +#endif +#endif +#endif +#endif + /*----------------------------------------------- * Command Line Argument Support *-----------------------------------------------*/ @@ -718,6 +768,7 @@ int UnityTestMatches(void); #define UNITY_TEST_ASSERT_EQUAL_HEX8(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT8 )(expected), (UNITY_INT)(UNITY_INT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) #define UNITY_TEST_ASSERT_EQUAL_HEX16(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT16)(expected), (UNITY_INT)(UNITY_INT16)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) #define UNITY_TEST_ASSERT_EQUAL_HEX32(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT32)(expected), (UNITY_INT)(UNITY_INT32)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) +#define UNITY_TEST_ASSERT_EQUAL_CHAR(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT8 )(expected), (UNITY_INT)(UNITY_INT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR) #define UNITY_TEST_ASSERT_BITS(mask, expected, actual, line, message) UnityAssertBits((UNITY_INT)(mask), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line)) #define UNITY_TEST_ASSERT_GREATER_THAN_INT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) @@ -731,6 +782,7 @@ int UnityTestMatches(void); #define UNITY_TEST_ASSERT_GREATER_THAN_HEX8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) #define UNITY_TEST_ASSERT_GREATER_THAN_HEX16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) #define UNITY_TEST_ASSERT_GREATER_THAN_HEX32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) +#define UNITY_TEST_ASSERT_GREATER_THAN_CHAR(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 )(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR) #define UNITY_TEST_ASSERT_SMALLER_THAN_INT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) #define UNITY_TEST_ASSERT_SMALLER_THAN_INT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 )(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) @@ -743,42 +795,60 @@ int UnityTestMatches(void); #define UNITY_TEST_ASSERT_SMALLER_THAN_HEX8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) #define UNITY_TEST_ASSERT_SMALLER_THAN_HEX16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) #define UNITY_TEST_ASSERT_SMALLER_THAN_HEX32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) +#define UNITY_TEST_ASSERT_SMALLER_THAN_CHAR(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 )(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 )(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT16)(threshold), (UNITY_INT)(UNITY_INT16)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT32)(threshold), (UNITY_INT)(UNITY_INT32)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT) (threshold), (UNITY_INT) (actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 ) (threshold), (UNITY_INT)(UNITY_INT8 ) (actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT16) (threshold), (UNITY_INT)(UNITY_INT16) (actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT32) (threshold), (UNITY_INT)(UNITY_INT32) (actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT) (threshold), (UNITY_INT) (actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) #define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) #define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) #define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) #define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) #define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) #define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) +#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_CHAR(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 ) (threshold), (UNITY_INT)(UNITY_INT8 ) (actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 )(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT16)(threshold), (UNITY_INT)(UNITY_INT16)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT32)(threshold), (UNITY_INT)(UNITY_INT32)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT) (threshold), (UNITY_INT) (actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 ) (actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT16)(threshold), (UNITY_INT)(UNITY_INT16) (actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT32)(threshold), (UNITY_INT)(UNITY_INT32) (actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT) (threshold), (UNITY_INT) (actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) #define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) #define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) #define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) #define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) #define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) #define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) +#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_CHAR(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 ) (actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR) -#define UNITY_TEST_ASSERT_INT_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((delta), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) -#define UNITY_TEST_ASSERT_INT8_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT8 )(delta), (UNITY_INT)(UNITY_INT8 )(expected), (UNITY_INT)(UNITY_INT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) -#define UNITY_TEST_ASSERT_INT16_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT16)(delta), (UNITY_INT)(UNITY_INT16)(expected), (UNITY_INT)(UNITY_INT16)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) -#define UNITY_TEST_ASSERT_INT32_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT32)(delta), (UNITY_INT)(UNITY_INT32)(expected), (UNITY_INT)(UNITY_INT32)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) -#define UNITY_TEST_ASSERT_UINT_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((delta), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) +#define UNITY_TEST_ASSERT_INT_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin( (delta), (UNITY_INT) (expected), (UNITY_INT) (actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) +#define UNITY_TEST_ASSERT_INT8_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT8 )(delta), (UNITY_INT)(UNITY_INT8 ) (expected), (UNITY_INT)(UNITY_INT8 ) (actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) +#define UNITY_TEST_ASSERT_INT16_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT16)(delta), (UNITY_INT)(UNITY_INT16) (expected), (UNITY_INT)(UNITY_INT16) (actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) +#define UNITY_TEST_ASSERT_INT32_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT32)(delta), (UNITY_INT)(UNITY_INT32) (expected), (UNITY_INT)(UNITY_INT32) (actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) +#define UNITY_TEST_ASSERT_UINT_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin( (delta), (UNITY_INT) (expected), (UNITY_INT) (actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) #define UNITY_TEST_ASSERT_UINT8_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT8 )(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT8 )(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) #define UNITY_TEST_ASSERT_UINT16_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT16)(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT16)(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT16)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) #define UNITY_TEST_ASSERT_UINT32_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT32)(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT32)(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT32)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) #define UNITY_TEST_ASSERT_HEX8_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT8 )(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT8 )(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) #define UNITY_TEST_ASSERT_HEX16_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT16)(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT16)(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT16)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) #define UNITY_TEST_ASSERT_HEX32_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT32)(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT32)(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT32)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) +#define UNITY_TEST_ASSERT_CHAR_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT8 )(delta), (UNITY_INT)(UNITY_INT8 ) (expected), (UNITY_INT)(UNITY_INT8 ) (actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR) + +#define UNITY_TEST_ASSERT_INT_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin( (delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_INT8_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT8 )(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_INT16_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT16)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_INT32_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT32)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_UINT_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin( (delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_UINT8_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin( (UNITY_UINT16)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_UINT16_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT16)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_UINT32_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT32)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_HEX8_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT8 )(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_HEX16_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT16)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_HEX32_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT32)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_CHAR_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT8 )(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR, UNITY_ARRAY_TO_ARRAY) + #define UNITY_TEST_ASSERT_EQUAL_PTR(expected, actual, line, message) UnityAssertEqualNumber((UNITY_PTR_TO_INT)(expected), (UNITY_PTR_TO_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_POINTER) #define UNITY_TEST_ASSERT_EQUAL_STRING(expected, actual, line, message) UnityAssertEqualString((const char*)(expected), (const char*)(actual), (message), (UNITY_LINE_TYPE)(line)) @@ -799,21 +869,23 @@ int UnityTestMatches(void); #define UNITY_TEST_ASSERT_EQUAL_PTR_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_POINTER, UNITY_ARRAY_TO_ARRAY) #define UNITY_TEST_ASSERT_EQUAL_STRING_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualStringArray((UNITY_INTERNAL_PTR)(expected), (const char**)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_ARRAY) #define UNITY_TEST_ASSERT_EQUAL_MEMORY_ARRAY(expected, actual, len, num_elements, line, message) UnityAssertEqualMemory((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(len), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EQUAL_CHAR_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EACH_EQUAL_INT(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT) (expected), sizeof(int)), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_INT8(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT8 )(expected), 1), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_INT16(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT16 )(expected), 2), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_INT32(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT32 )(expected), 4), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT) (expected), sizeof(unsigned int)), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT8(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_UINT8 )(expected), 1), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT16(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_UINT16)(expected), 2), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT32(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_UINT32)(expected), 4), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_HEX8(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT8 )(expected), 1), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_HEX16(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT16 )(expected), 2), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_HEX32(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT32 )(expected), 4), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_PTR(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_PTR_TO_INT) (expected), sizeof(int*)), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_POINTER, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_INT(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT) (expected), (UNITY_INT_WIDTH / 8)), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_INT8(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT8 )(expected), 1), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_INT16(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT16 )(expected), 2), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_INT32(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT32 )(expected), 4), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT) (expected), (UNITY_INT_WIDTH / 8)), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT8(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_UINT8 )(expected), 1), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT16(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_UINT16)(expected), 2), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT32(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_UINT32)(expected), 4), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_HEX8(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT8 )(expected), 1), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_HEX16(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT16 )(expected), 2), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_HEX32(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT32 )(expected), 4), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_PTR(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_PTR_TO_INT) (expected), (UNITY_POINTER_WIDTH / 8)), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_POINTER, UNITY_ARRAY_TO_VAL) #define UNITY_TEST_ASSERT_EACH_EQUAL_STRING(expected, actual, num_elements, line, message) UnityAssertEqualStringArray((UNITY_INTERNAL_PTR)(expected), (const char**)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_VAL) #define UNITY_TEST_ASSERT_EACH_EQUAL_MEMORY(expected, actual, len, num_elements, line, message) UnityAssertEqualMemory((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(len), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_CHAR(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT8 )(expected), 1), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR, UNITY_ARRAY_TO_VAL) #ifdef UNITY_SUPPORT_64 #define UNITY_TEST_ASSERT_EQUAL_INT64(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64) @@ -822,9 +894,9 @@ int UnityTestMatches(void); #define UNITY_TEST_ASSERT_EQUAL_INT64_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64, UNITY_ARRAY_TO_ARRAY) #define UNITY_TEST_ASSERT_EQUAL_UINT64_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64, UNITY_ARRAY_TO_ARRAY) #define UNITY_TEST_ASSERT_EQUAL_HEX64_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EACH_EQUAL_INT64(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT64)expected, 8), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT64(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_UINT64)expected, 8), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_HEX64(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT64)expected, 8), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_INT64(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT64)(expected), 8), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT64(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_UINT64)(expected), 8), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_EACH_EQUAL_HEX64(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT64)(expected), 8), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64, UNITY_ARRAY_TO_VAL) #define UNITY_TEST_ASSERT_INT64_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((delta), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64) #define UNITY_TEST_ASSERT_UINT64_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((delta), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64) #define UNITY_TEST_ASSERT_HEX64_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((delta), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64) @@ -840,6 +912,9 @@ int UnityTestMatches(void); #define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64) #define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64) #define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64) +#define UNITY_TEST_ASSERT_INT64_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT64)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_UINT64_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT64)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64, UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_HEX64_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT64)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64, UNITY_ARRAY_TO_ARRAY) #else #define UNITY_TEST_ASSERT_EQUAL_INT64(expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) #define UNITY_TEST_ASSERT_EQUAL_UINT64(expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) @@ -862,6 +937,9 @@ int UnityTestMatches(void); #define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) #define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) #define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_INT64_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_UINT64_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) +#define UNITY_TEST_ASSERT_HEX64_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) #endif #ifdef UNITY_EXCLUDE_FLOAT @@ -906,10 +984,10 @@ int UnityTestMatches(void); #define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NAN(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) #define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) #else -#define UNITY_TEST_ASSERT_DOUBLE_WITHIN(delta, expected, actual, line, message) UnityAssertDoublesWithin((UNITY_DOUBLE)(delta), (UNITY_DOUBLE)(expected), (UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)line) -#define UNITY_TEST_ASSERT_EQUAL_DOUBLE(expected, actual, line, message) UNITY_TEST_ASSERT_DOUBLE_WITHIN((UNITY_DOUBLE)(expected) * (UNITY_DOUBLE)UNITY_DOUBLE_PRECISION, (UNITY_DOUBLE)expected, (UNITY_DOUBLE)actual, (UNITY_LINE_TYPE)(line), message) -#define UNITY_TEST_ASSERT_EQUAL_DOUBLE_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualDoubleArray((UNITY_DOUBLE*)(expected), (UNITY_DOUBLE*)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)line, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EACH_EQUAL_DOUBLE(expected, actual, num_elements, line, message) UnityAssertEqualDoubleArray(UnityDoubleToPtr(expected), (UNITY_DOUBLE*)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)line, UNITY_ARRAY_TO_VAL) +#define UNITY_TEST_ASSERT_DOUBLE_WITHIN(delta, expected, actual, line, message) UnityAssertDoublesWithin((UNITY_DOUBLE)(delta), (UNITY_DOUBLE)(expected), (UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line)) +#define UNITY_TEST_ASSERT_EQUAL_DOUBLE(expected, actual, line, message) UNITY_TEST_ASSERT_DOUBLE_WITHIN((UNITY_DOUBLE)(expected) * (UNITY_DOUBLE)UNITY_DOUBLE_PRECISION, (UNITY_DOUBLE)(expected), (UNITY_DOUBLE)(actual), (UNITY_LINE_TYPE)(line), (message)) +#define UNITY_TEST_ASSERT_EQUAL_DOUBLE_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualDoubleArray((UNITY_DOUBLE*)(expected), (UNITY_DOUBLE*)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_ARRAY) +#define UNITY_TEST_ASSERT_EACH_EQUAL_DOUBLE(expected, actual, num_elements, line, message) UnityAssertEqualDoubleArray(UnityDoubleToPtr(expected), (UNITY_DOUBLE*)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_VAL) #define UNITY_TEST_ASSERT_DOUBLE_IS_INF(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_INF) #define UNITY_TEST_ASSERT_DOUBLE_IS_NEG_INF(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NEG_INF) #define UNITY_TEST_ASSERT_DOUBLE_IS_NAN(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NAN) From ab84731f2afeea4b9e56020a7657697cceac9bbf Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 1 Nov 2019 17:49:46 +0700 Subject: [PATCH 004/267] update test project yml --- test/project.yml | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/test/project.yml b/test/project.yml index a130569c..688423e1 100644 --- a/test/project.yml +++ b/test/project.yml @@ -18,6 +18,9 @@ :default_tasks: - test:all +#:test_build: +# :use_assembly: TRUE + #:release_build: # :output: MyApp.out # :use_assembly: FALSE @@ -40,13 +43,12 @@ # in order to add common defines: # 1) remove the trailing [] from the :common: section # 2) add entries to the :common: section (e.g. :test: has TEST defined) - :commmon: &common_defines [] + :common: &common_defines + - _UNITY_TEST_ :test: - *common_defines - - _TEST_ :test_preprocess: - *common_defines - - _TEST_ :cmock: :mock_prefix: mock_ @@ -64,8 +66,15 @@ int8: INT8 bool: UINT8 +# Add -gcov to the plugins list to make sure of the gcov plugin +# You will need to have gcov and gcovr both installed to make it work. +# For more information on these options, see docs in plugins/gcov :gcov: - :html_report_type: basic + :html_report: TRUE + :html_report_type: detailed + :html_medium_threshold: 75 + :html_high_threshold: 90 + :xml_report: FALSE #:tools: # Ceedling defaults to using gcc for compiling, linking, etc. @@ -92,4 +101,5 @@ - stdout_pretty_tests_report - module_generator - raw_output_report + - colour_report ... From 5b68cc91ad5059c595536016c19a914af6928296 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 1 Nov 2019 17:50:40 +0700 Subject: [PATCH 005/267] adding TEST_FAIL() for TU_ASSERT() --- src/common/tusb_verify.h | 14 +++++++++++--- test/test/support/tusb_config.h | 5 ++++- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/src/common/tusb_verify.h b/src/common/tusb_verify.h index e5948135..5ae3afc9 100644 --- a/src/common/tusb_verify.h +++ b/src/common/tusb_verify.h @@ -73,13 +73,21 @@ //--------------------------------------------------------------------+ // TU_VERIFY Helper //--------------------------------------------------------------------+ + +// Running unit tests +#ifdef _UNITY_TEST_ + #define _TEST_FAILED() TEST_FAIL(); +#else + #define _TEST_FAILED() +#endif + #if CFG_TUSB_DEBUG #include - #define _MESS_ERR(_err) printf("%s: %d: failed, error = %s\n", __func__, __LINE__, tusb_strerr[_err]) - #define _MESS_FAILED() printf("%s: %d: failed\n", __func__, __LINE__) + #define _MESS_ERR(_err) printf("%s %d: failed, error = %s\n", __func__, __LINE__, tusb_strerr[_err]) + #define _MESS_FAILED() do { printf("%s %d: assert failed\n", __func__, __LINE__); _TEST_FAILED() } while(0) #else #define _MESS_ERR(_err) - #define _MESS_FAILED() + #define _MESS_FAILED() _TEST_FAILED() #endif // Halt CPU (breakpoint) when hitting error, only apply for Cortex M3, M4, M7 diff --git a/test/test/support/tusb_config.h b/test/test/support/tusb_config.h index b75b7667..c745320d 100644 --- a/test/test/support/tusb_config.h +++ b/test/test/support/tusb_config.h @@ -26,6 +26,9 @@ #ifndef _TUSB_CONFIG_H_ #define _TUSB_CONFIG_H_ +// testing framework +#include "unity.h" + #ifdef __cplusplus extern "C" { #endif @@ -49,7 +52,7 @@ #define CFG_TUSB_OS OPT_OS_NONE // CFG_TUSB_DEBUG is defined by compiler in DEBUG build -// #define CFG_TUSB_DEBUG 0 + #define CFG_TUSB_DEBUG 0 /* USB DMA on some MCUs can only access a specific SRAM region with restriction on alignment. * Tinyusb use follows macros to declare transferring memory so that they can be put From 83cbe32097de748e84dd8a91fd71b6cc3667ebfa Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 1 Nov 2019 17:53:37 +0700 Subject: [PATCH 006/267] enable retrun_thru_ptr --- test/project.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/test/project.yml b/test/project.yml index 688423e1..dc4a9cb2 100644 --- a/test/project.yml +++ b/test/project.yml @@ -57,6 +57,7 @@ :plugins: - :ignore - :ignore_arg + - :return_thru_ptr - :callback - :array :treat_as: From d0d87d98f6d480ebf2b3b27d85a391780f0976f3 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 1 Nov 2019 18:03:43 +0700 Subject: [PATCH 007/267] add assert to prevent div by zero --- src/class/msc/msc_device.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/class/msc/msc_device.c b/src/class/msc/msc_device.c index a77282ed..115ca143 100644 --- a/src/class/msc/msc_device.c +++ b/src/class/msc/msc_device.c @@ -583,10 +583,14 @@ static void proc_read10_cmd(uint8_t rhport, mscd_interface_t* p_msc) msc_cbw_t const * p_cbw = &p_msc->cbw; msc_csw_t * p_csw = &p_msc->csw; - uint16_t const block_sz = p_cbw->total_bytes / rdwr10_get_blockcount(p_cbw->command); + uint16_t const block_cnt = rdwr10_get_blockcount(p_cbw->command); + TU_ASSERT(block_cnt, ); // prevent div by zero + + uint16_t const block_sz = p_cbw->total_bytes / block_cnt; + TU_ASSERT(block_sz, ); // prevent div by zero // Adjust lba with transferred bytes - uint32_t const lba = rdwr10_get_lba(p_cbw->command) + (p_msc->xferred_len / block_sz); + uint32_t lba = rdwr10_get_lba(p_cbw->command) + (p_msc->xferred_len / block_sz); // remaining bytes capped at class buffer int32_t nbytes = (int32_t) tu_min32(sizeof(_mscd_buf), p_cbw->total_bytes-p_msc->xferred_len); From c7d7ac42d85ab70821ecdb6cb7fcb0c46694cb75 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 1 Nov 2019 18:11:14 +0700 Subject: [PATCH 008/267] added first test for msc device --- test/test/device/msc/test_msc_device.c | 51 ++++++++++++++++++++++---- 1 file changed, 44 insertions(+), 7 deletions(-) diff --git a/test/test/device/msc/test_msc_device.c b/test/test/device/msc/test_msc_device.c index 53febe96..2eb58962 100644 --- a/test/test/device/msc/test_msc_device.c +++ b/test/test/device/msc/test_msc_device.c @@ -210,24 +210,61 @@ void tearDown(void) //--------------------------------------------------------------------+ void test_msc(void) { + // Read 1 LBA = 0, Block count = 1 + msc_cbw_t cbw_read10 = + { + .signature = MSC_CBW_SIGNATURE, + .tag = 0xCAFECAFE, + .total_bytes = 512, + .lun = 0, + .dir = TUSB_DIR_IN_MASK, + .cmd_len = sizeof(scsi_read10_t) + }; + + scsi_read10_t cmd_read10 = + { + .cmd_code = SCSI_CMD_READ_10, + .lba = tu_htonl(0), + .block_count = tu_htons(1) + }; + + memcpy(cbw_read10.command, &cmd_read10, cbw_read10.cmd_len); + desc_configuration = data_desc_configuration; + uint8_t const* desc_ep = tu_desc_next(tu_desc_next(desc_configuration)); dcd_event_setup_received(rhport, (uint8_t*) &request_set_configuration, false); dcd_set_config_Expect(rhport, 1); - uint8_t const* desc_ep = tu_desc_next(tu_desc_next(desc_configuration)); - // open endpoints - dcd_edpt_open_ExpectAndReturn(rhport, desc_ep, true); - dcd_edpt_open_ExpectAndReturn(rhport, tu_desc_next(desc_ep), true); + dcd_edpt_open_ExpectAndReturn(rhport, (tusb_desc_endpoint_t const *) desc_ep, true); + dcd_edpt_open_ExpectAndReturn(rhport, (tusb_desc_endpoint_t const *) tu_desc_next(desc_ep), true); - // queue endpoint out - dcd_edpt_xfer_ExpectAndReturn(rhport, EDPT_MSC_OUT, NULL, 31, true); - dcd_edpt_xfer_IgnoreArg_buffer(); // don't care buffer since it is msc device interal + // Prepare SCSI command + dcd_edpt_xfer_ExpectAndReturn(rhport, EDPT_MSC_OUT, NULL, sizeof(msc_cbw_t), true); + dcd_edpt_xfer_IgnoreArg_buffer(); + dcd_edpt_xfer_ReturnMemThruPtr_buffer( (uint8_t*) &cbw_read10, sizeof(msc_cbw_t)); + + // command received + dcd_event_xfer_complete(rhport, EDPT_MSC_OUT, sizeof(msc_cbw_t), 0, true); // control status dcd_edpt_xfer_ExpectAndReturn(rhport, EDPT_CTRL_IN, NULL, 0, true); + // SCSI Data transfer + dcd_edpt_xfer_ExpectAndReturn(rhport, EDPT_MSC_IN, NULL, 512, true); + dcd_edpt_xfer_IgnoreArg_buffer(); + dcd_event_xfer_complete(rhport, EDPT_MSC_IN, 512, 0, true); // complete + + // SCSI Status + dcd_edpt_xfer_ExpectAndReturn(rhport, EDPT_MSC_IN, NULL, 13, true); + dcd_edpt_xfer_IgnoreArg_buffer(); + dcd_event_xfer_complete(rhport, EDPT_MSC_IN, 13, 0, true); + + // Prepare for next command + dcd_edpt_xfer_ExpectAndReturn(rhport, EDPT_MSC_OUT, NULL, sizeof(msc_cbw_t), true); + dcd_edpt_xfer_IgnoreArg_buffer(); + tud_task(); } From 838173efc34ab3c55e925176a378a47f9ba65e7e Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 1 Nov 2019 18:27:15 +0700 Subject: [PATCH 009/267] remove TEST_FAIL() from TU_ASSERT, since it prevents we testing how stack response with failed assert --- src/common/tusb_verify.h | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/src/common/tusb_verify.h b/src/common/tusb_verify.h index 5ae3afc9..41364d05 100644 --- a/src/common/tusb_verify.h +++ b/src/common/tusb_verify.h @@ -74,20 +74,13 @@ // TU_VERIFY Helper //--------------------------------------------------------------------+ -// Running unit tests -#ifdef _UNITY_TEST_ - #define _TEST_FAILED() TEST_FAIL(); -#else - #define _TEST_FAILED() -#endif - #if CFG_TUSB_DEBUG #include #define _MESS_ERR(_err) printf("%s %d: failed, error = %s\n", __func__, __LINE__, tusb_strerr[_err]) - #define _MESS_FAILED() do { printf("%s %d: assert failed\n", __func__, __LINE__); _TEST_FAILED() } while(0) + #define _MESS_FAILED() printf("%s %d: assert failed\n", __func__, __LINE__) #else #define _MESS_ERR(_err) - #define _MESS_FAILED() _TEST_FAILED() + #define _MESS_FAILED() #endif // Halt CPU (breakpoint) when hitting error, only apply for Cortex M3, M4, M7 From 79fbc0b23c9b83b7f8fdbc8a06d9a4e5d3690066 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 1 Nov 2019 18:43:18 +0700 Subject: [PATCH 010/267] wait for scsi status complete before queueing for next scsi command fix #207 --- src/class/msc/msc_device.c | 45 +++++++++++++++++++++++--------------- 1 file changed, 27 insertions(+), 18 deletions(-) diff --git a/src/class/msc/msc_device.c b/src/class/msc/msc_device.c index 115ca143..88db1ffd 100644 --- a/src/class/msc/msc_device.c +++ b/src/class/msc/msc_device.c @@ -533,7 +533,18 @@ bool mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t } break; - case MSC_STAGE_STATUS: break; // processed immediately after this switch + case MSC_STAGE_STATUS: + // Wait for the command status wrapper complete event + if( (ep_addr == p_msc->ep_in) && (xferred_bytes == sizeof(msc_csw_t)) ) + { + // Move to default CMD stage + p_msc->stage = MSC_STAGE_CMD; + + // Queue for the next CBW + TU_ASSERT( usbd_edpt_xfer(rhport, p_msc->ep_out, (uint8_t*) &p_msc->cbw, sizeof(msc_cbw_t)) ); + } + break; + default : break; } @@ -543,32 +554,30 @@ bool mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t if ( usbd_edpt_stalled(rhport, p_msc->ep_in) || usbd_edpt_stalled(rhport, p_msc->ep_out) ) { // simulate an transfer complete with adjusted parameters --> this driver callback will fired again + // and response with status phase after halted endpoints are cleared. + // note: use ep_out to prevent confusing with STATUS complete dcd_event_xfer_complete(rhport, p_msc->ep_out, 0, XFER_RESULT_SUCCESS, false); } else { - // Move to default CMD stage when sending status - p_msc->stage = MSC_STAGE_CMD; - // Send SCSI Status - TU_ASSERT( usbd_edpt_xfer(rhport, p_msc->ep_in , (uint8_t*) &p_msc->csw, sizeof(msc_csw_t)) ); + TU_ASSERT(usbd_edpt_xfer(rhport, p_msc->ep_in , (uint8_t*) &p_msc->csw, sizeof(msc_csw_t))); // Invoke complete callback if defined - if ( SCSI_CMD_READ_10 == p_cbw->command[0]) + switch(p_cbw->command[0]) { - if ( tud_msc_read10_complete_cb ) tud_msc_read10_complete_cb(p_cbw->lun); - } - else if ( SCSI_CMD_WRITE_10 == p_cbw->command[0] ) - { - if ( tud_msc_write10_complete_cb ) tud_msc_write10_complete_cb(p_cbw->lun); - } - else - { - if ( tud_msc_scsi_complete_cb ) tud_msc_scsi_complete_cb(p_cbw->lun, p_cbw->command); - } + case SCSI_CMD_READ_10: + if ( tud_msc_read10_complete_cb ) tud_msc_read10_complete_cb(p_cbw->lun); + break; - // Queue for the next CBW - TU_ASSERT( usbd_edpt_xfer(rhport, p_msc->ep_out, (uint8_t*) &p_msc->cbw, sizeof(msc_cbw_t)) ); + case SCSI_CMD_WRITE_10: + if ( tud_msc_write10_complete_cb ) tud_msc_write10_complete_cb(p_cbw->lun); + break; + + default: + if ( tud_msc_scsi_complete_cb ) tud_msc_scsi_complete_cb(p_cbw->lun, p_cbw->command); + break; + } } } From b6ee180b66064504d743b3ef29f0127dbadd4cec Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 1 Nov 2019 19:26:33 +0700 Subject: [PATCH 011/267] add missing ceedling latest version files --- .../colour_report/lib/colour_report.rb | 16 +++++++++ .../plugins/junit_tests_report/README.md | 36 +++++++++++++++++++ .../plugins/xml_tests_report/README.md | 36 +++++++++++++++++++ .../ceedling/vendor/cmock/src/meson.build | 17 +++++++++ .../ceedling/vendor/unity/auto/run_test.erb | 36 +++++++++++++++++++ .../ceedling/vendor/unity/src/CMakeLists.txt | 22 ++++++++++++ .../ceedling/vendor/unity/src/meson.build | 16 +++++++++ 7 files changed, 179 insertions(+) create mode 100644 test/vendor/ceedling/plugins/colour_report/lib/colour_report.rb create mode 100644 test/vendor/ceedling/plugins/junit_tests_report/README.md create mode 100644 test/vendor/ceedling/plugins/xml_tests_report/README.md create mode 100644 test/vendor/ceedling/vendor/cmock/src/meson.build create mode 100644 test/vendor/ceedling/vendor/unity/auto/run_test.erb create mode 100644 test/vendor/ceedling/vendor/unity/src/CMakeLists.txt create mode 100644 test/vendor/ceedling/vendor/unity/src/meson.build diff --git a/test/vendor/ceedling/plugins/colour_report/lib/colour_report.rb b/test/vendor/ceedling/plugins/colour_report/lib/colour_report.rb new file mode 100644 index 00000000..1211eab4 --- /dev/null +++ b/test/vendor/ceedling/plugins/colour_report/lib/colour_report.rb @@ -0,0 +1,16 @@ +require 'ceedling/plugin' +require 'ceedling/streaminator' +require 'ceedling/constants' + +class ColourReport < Plugin + + def setup + @ceedling[:stream_wrapper].stdout_override(&ColourReport.method(:colour_stdout)) + end + + def self.colour_stdout(string) + require 'colour_reporter.rb' + report string + end + +end diff --git a/test/vendor/ceedling/plugins/junit_tests_report/README.md b/test/vendor/ceedling/plugins/junit_tests_report/README.md new file mode 100644 index 00000000..1259fd66 --- /dev/null +++ b/test/vendor/ceedling/plugins/junit_tests_report/README.md @@ -0,0 +1,36 @@ +junit_tests_report +==================== + +## Overview + +The junit_tests_report plugin creates an XML file of test results in JUnit +format, which is handy for Continuous Integration build servers or as input +into other reporting tools. The XML file is output to the appropriate +`/artifacts/` directory (e.g. `artifacts/test/` for test tasks, +`artifacts/gcov/` for gcov, or `artifacts/bullseye/` for bullseye runs). + +## Setup + +Enable the plugin in your project.yml by adding `junit_tests_report` +to the list of enabled plugins. + +``` YAML +:plugins: + :enabled: + - junit_tests_report +``` + +## Configuration + +Optionally configure the output / artifact filename in your project.yml with +the `artifact_filename` configuration option. The default filename is +`report.xml`. + +You can also configure the path that this artifact is stored. This can be done +by setting `path`. The default is that it will be placed in a subfolder under +the `build` directory. + +``` YAML +:junit_tests_report: + :artifact_filename: report_junit.xml +``` diff --git a/test/vendor/ceedling/plugins/xml_tests_report/README.md b/test/vendor/ceedling/plugins/xml_tests_report/README.md new file mode 100644 index 00000000..ce81eadf --- /dev/null +++ b/test/vendor/ceedling/plugins/xml_tests_report/README.md @@ -0,0 +1,36 @@ +xml_tests_report +==================== + +## Overview + +The xml_tests_report plugin creates an XML file of test results in xUnit +format, which is handy for Continuous Integration build servers or as input +into other reporting tools. The XML file is output to the appropriate +`/artifacts/` directory (e.g. `artifacts/test/` for test tasks, +`artifacts/gcov/` for gcov, or `artifacts/bullseye/` for bullseye runs). + +## Setup + +Enable the plugin in your project.yml by adding `xml_tests_report` to the list +of enabled plugins. + +``` YAML +:plugins: + :enabled: + - xml_tests_report +``` + +## Configuration + +Optionally configure the output / artifact filename in your project.yml with +the `artifact_filename` configuration option. The default filename is +`report.xml`. + +You can also configure the path that this artifact is stored. This can be done +by setting `path`. The default is that it will be placed in a subfolder under +the `build` directory. + +``` YAML +:xml_tests_report: + :artifact_filename: report_xunit.xml +``` diff --git a/test/vendor/ceedling/vendor/cmock/src/meson.build b/test/vendor/ceedling/vendor/cmock/src/meson.build new file mode 100644 index 00000000..e375e81a --- /dev/null +++ b/test/vendor/ceedling/vendor/cmock/src/meson.build @@ -0,0 +1,17 @@ +################################################################################### +# # +# NAME: meson.build # +# # +# AUTHOR: Mike Karlesky, Mark VanderVoord, Greg Williams. # +# WRITTEN BY: Michael Brockus. # +# # +# License: MIT # +# # +################################################################################### + +cmock_dir = include_directories('.') + +cmock_lib = static_library(meson.project_name(), + sources: ['cmock.c'], + dependencies: [unity_dep], + include_directories: cmock_dir) diff --git a/test/vendor/ceedling/vendor/unity/auto/run_test.erb b/test/vendor/ceedling/vendor/unity/auto/run_test.erb new file mode 100644 index 00000000..3d3b6d1e --- /dev/null +++ b/test/vendor/ceedling/vendor/unity/auto/run_test.erb @@ -0,0 +1,36 @@ +/*=======Test Runner Used To Run Each Test=====*/ +static void run_test(UnityTestFunction func, const char* name, int line_num) +{ + Unity.CurrentTestName = name; + Unity.CurrentTestLineNumber = line_num; +#ifdef UNITY_USE_COMMAND_LINE_ARGS + if (!UnityTestMatches()) + return; +#endif + Unity.NumberOfTests++; + UNITY_CLR_DETAILS(); + UNITY_EXEC_TIME_START(); + CMock_Init(); + if (TEST_PROTECT()) + { +<% if @options[:plugins].include?(:cexception) %> + CEXCEPTION_T e; + Try { +<% end %> + <%= @options[:setup_name] %>(); + func(); +<% if @options[:plugins].include?(:cexception) %> + } Catch(e) { + TEST_ASSERT_EQUAL_HEX32_MESSAGE(CEXCEPTION_NONE, e, "Unhandled Exception!"); + } +<% end %> + } + if (TEST_PROTECT()) + { + <%= @options[:teardown_name] %>(); + CMock_Verify(); + } + CMock_Destroy(); + UNITY_EXEC_TIME_STOP(); + UnityConcludeTest(); +} diff --git a/test/vendor/ceedling/vendor/unity/src/CMakeLists.txt b/test/vendor/ceedling/vendor/unity/src/CMakeLists.txt new file mode 100644 index 00000000..c747cb0a --- /dev/null +++ b/test/vendor/ceedling/vendor/unity/src/CMakeLists.txt @@ -0,0 +1,22 @@ +################################################################################### +# # +# NAME: CMakeLists.txt # +# # +# AUTHOR: Mike Karlesky, Mark VanderVoord, Greg Williams. # +# WRITTEN BY: Michael Brockus. # +# # +# License: MIT # +# # +################################################################################### +cmake_minimum_required(VERSION 3.0 FATAL_ERROR) + + +add_library(unity STATIC "unity.c") + +install(TARGETS unity EXPORT unityConfig + ARCHIVE DESTINATION "${CMAKE_CURRENT_SOURCE_DIR}/${CMAKE_INSTALL_LIBDIR}" + LIBRARY DESTINATION "${CMAKE_CURRENT_SOURCE_DIR}/${CMAKE_INSTALL_LIBDIR}" + RUNTIME DESTINATION "${CMAKE_CURRENT_SOURCE_DIR}/${CMAKE_INSTALL_BINDIR}" + INCLUDES DESTINATION "${CMAKE_INSTALL_LIBDIR}") + + diff --git a/test/vendor/ceedling/vendor/unity/src/meson.build b/test/vendor/ceedling/vendor/unity/src/meson.build new file mode 100644 index 00000000..f5e01465 --- /dev/null +++ b/test/vendor/ceedling/vendor/unity/src/meson.build @@ -0,0 +1,16 @@ +################################################################################### +# # +# NAME: meson.build # +# # +# AUTHOR: Mike Karlesky, Mark VanderVoord, Greg Williams. # +# WRITTEN BY: Michael Brockus. # +# # +# License: MIT # +# # +################################################################################### + +unity_dir = include_directories('.') + +unity_lib = static_library(meson.project_name(), + sources: ['unity.c'], + include_directories: unity_dir) From 66ce39368e0f4bba366956d3b0cd7a9ef87168b8 Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 4 Nov 2019 00:10:46 +0700 Subject: [PATCH 012/267] clean up --- test/test/device/msc/test_msc_device.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/test/test/device/msc/test_msc_device.c b/test/test/device/msc/test_msc_device.c index 2eb58962..5003ac83 100644 --- a/test/test/device/msc/test_msc_device.c +++ b/test/test/device/msc/test_msc_device.c @@ -1,7 +1,7 @@ /* * The MIT License (MIT) * - * Copyright (c) 2019 hathach for Adafruit Industries + * Copyright (c) 2019, hathach (tinyusb.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,8 +20,11 @@ * 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. + * + * This file is part of the TinyUSB stack. */ + #include "unity.h" // Files to test From e2b6f8c92bdf04036b4269d77f561869cf4da9fe Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 4 Nov 2019 00:10:03 +0700 Subject: [PATCH 013/267] clean up --- test/test/device/usbd/test_usbd.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/test/test/device/usbd/test_usbd.c b/test/test/device/usbd/test_usbd.c index d4b3f806..19717d87 100644 --- a/test/test/device/usbd/test_usbd.c +++ b/test/test/device/usbd/test_usbd.c @@ -1,7 +1,7 @@ /* * The MIT License (MIT) * - * Copyright (c) 2019 hathach for Adafruit Industries + * Copyright (c) 2019, hathach (tinyusb.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -20,8 +20,11 @@ * 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. + * + * This file is part of the TinyUSB stack. */ + #include "unity.h" // Files to test From 6baa79b3308d4637f7a22ad73a5ac26f9ef6b491 Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 4 Nov 2019 14:54:04 +0700 Subject: [PATCH 014/267] board test works --- hw/bsp/samg55xplained/board.mk | 50 +++++++++++ hw/bsp/samg55xplained/samg55xplained.c | 114 ++++++++++++++++++++++++ src/portable/template/dcd_template.c | 116 +++++++++++++++++++++++++ src/tusb_option.h | 2 + 4 files changed, 282 insertions(+) create mode 100644 hw/bsp/samg55xplained/board.mk create mode 100644 hw/bsp/samg55xplained/samg55xplained.c create mode 100644 src/portable/template/dcd_template.c diff --git a/hw/bsp/samg55xplained/board.mk b/hw/bsp/samg55xplained/board.mk new file mode 100644 index 00000000..a8d2b0fe --- /dev/null +++ b/hw/bsp/samg55xplained/board.mk @@ -0,0 +1,50 @@ +CFLAGS += \ + -D__SAMG55J19__ \ + -mthumb \ + -mabi=aapcs \ + -mcpu=cortex-m4 \ + -mfloat-abi=hard \ + -mfpu=fpv4-sp-d16 \ + -nostdlib -nostartfiles \ + -DCFG_TUSB_MCU=OPT_MCU_NONE + +#CFLAGS += -Wno-error=undef + +ASF_DIR = hw/mcu/microchip/samg + +# All source paths should be relative to the top level. +LD_FILE = $(ASF_DIR)/samg55/gcc/gcc/samg55j19_flash.ld + +SRC_C += \ + $(ASF_DIR)/samg55/gcc/gcc/startup_samg55j19.c \ + $(ASF_DIR)/samg55/gcc/system_samg55j19.c \ + $(ASF_DIR)/hpl/core/hpl_init.c \ + $(ASF_DIR)/hpl/pmc/hpl_pmc.c \ + $(ASF_DIR)/hal/src/hal_atomic.c + +INC += \ + $(TOP)/$(ASF_DIR) \ + $(TOP)/$(ASF_DIR)/config \ + $(TOP)/$(ASF_DIR)/samg55/include \ + $(TOP)/$(ASF_DIR)/hal/include \ + $(TOP)/$(ASF_DIR)/hal/utils/include \ + $(TOP)/$(ASF_DIR)/hpl/core \ + $(TOP)/$(ASF_DIR)/hpl/pio \ + $(TOP)/$(ASF_DIR)/hpl/pmc \ + $(TOP)/$(ASF_DIR)/hri \ + $(TOP)/$(ASF_DIR)/CMSIS/Core/Include + +# For TinyUSB port source +VENDOR = . +CHIP_FAMILY = template + +# For freeRTOS port source +FREERTOS_PORT = ARM_CM4F + +# For flash-jlink target +JLINK_DEVICE = ATSAMD51J19 +JLINK_IF = swd + +# flash using edbg from https://github.com/ataradov/edbg +flash: $(BUILD)/$(BOARD)-firmware.bin + edbg --verbose -t samg55 -pv -f $< diff --git a/hw/bsp/samg55xplained/samg55xplained.c b/hw/bsp/samg55xplained/samg55xplained.c new file mode 100644 index 00000000..e1bc9c4c --- /dev/null +++ b/hw/bsp/samg55xplained/samg55xplained.c @@ -0,0 +1,114 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019, hathach (tinyusb.org) + * + * 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 "sam.h" +#include "peripheral_clk_config.h" +#include "hal/include/hal_init.h" +#include "hpl/pmc/hpl_pmc.h" +#include "hal/include/hal_gpio.h" + +#include "bsp/board.h" + +//--------------------------------------------------------------------+ +// MACRO TYPEDEF CONSTANT ENUM DECLARATION +//--------------------------------------------------------------------+ + +#define LED_PIN GPIO(GPIO_PORTA, 6) + +#define BUTTON_PIN GPIO(GPIO_PORTA, 2) +#define BUTTON_STATE_ACTIVE 0 + +//------------- IMPLEMENTATION -------------// +void board_init(void) +{ + init_mcu(); + + _pmc_enable_periph_clock(ID_PIOA); + + /* Disable Watchdog */ + hri_wdt_set_MR_WDDIS_bit(WDT); + + // LED + gpio_set_pin_level(LED_PIN, false); + gpio_set_pin_direction(LED_PIN, GPIO_DIRECTION_OUT); + gpio_set_pin_function(LED_PIN, GPIO_PIN_FUNCTION_OFF); + + // Button + gpio_set_pin_direction(BUTTON_PIN, GPIO_DIRECTION_IN); + gpio_set_pin_pull_mode(BUTTON_PIN, GPIO_PULL_UP); + gpio_set_pin_function(BUTTON_PIN, GPIO_PIN_FUNCTION_OFF); + +#if CFG_TUSB_OS == OPT_OS_NONE + // 1ms tick timer (samd SystemCoreClock may not correct) + SysTick_Config(CONF_CPU_FREQUENCY / 1000); +#endif +} + +//--------------------------------------------------------------------+ +// Board porting API +//--------------------------------------------------------------------+ + +void board_led_write(bool state) +{ + gpio_set_pin_level(LED_PIN, state); +} + +uint32_t board_button_read(void) +{ + return BUTTON_STATE_ACTIVE == gpio_get_pin_level(BUTTON_PIN); +} + +int board_uart_read(uint8_t* buf, int len) +{ + (void) buf; (void) len; + return 0; +} + +int board_uart_write(void const * buf, int len) +{ + (void) buf; (void) len; + return 0; +} + +#if CFG_TUSB_OS == OPT_OS_NONE +volatile uint32_t system_ticks = 0; + +void SysTick_Handler (void) +{ + system_ticks++; +} + +uint32_t board_millis(void) +{ + return system_ticks; +} +#endif + +// Required by __libc_init_array in startup code if we are compiling using +// -nostdlib/-nostartfiles. +void _init(void) +{ + +} diff --git a/src/portable/template/dcd_template.c b/src/portable/template/dcd_template.c new file mode 100644 index 00000000..10291050 --- /dev/null +++ b/src/portable/template/dcd_template.c @@ -0,0 +1,116 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2018, hathach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#include "tusb_option.h" + +#if CFG_TUSB_MCU == OPT_MCU_NONE + +#include "device/dcd.h" + +//--------------------------------------------------------------------+ +// MACRO TYPEDEF CONSTANT ENUM DECLARATION +//--------------------------------------------------------------------+ + + +/*------------------------------------------------------------------*/ +/* Device API + *------------------------------------------------------------------*/ + +// Initialize controller to device mode +void dcd_init (uint8_t rhport) +{ + (void) rhport; +} + +// Enable device interrupt +void dcd_int_enable (uint8_t rhport) +{ + (void) rhport; +} + +// Disable device interrupt +void dcd_int_disable (uint8_t rhport) +{ + (void) rhport; +} + +// Receive Set Address request, mcu port must also include status IN response +void dcd_set_address (uint8_t rhport, uint8_t dev_addr) +{ + (void) rhport; + (void) dev_addr; +} + +// Receive Set Configure request +void dcd_set_config (uint8_t rhport, uint8_t config_num) +{ + (void) rhport; + (void) config_num; +} + +// Wake up host +void dcd_remote_wakeup (uint8_t rhport) +{ + (void) rhport; +} + +//--------------------------------------------------------------------+ +// Endpoint API +//--------------------------------------------------------------------+ + +// Configure endpoint's registers according to descriptor +bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * ep_desc) +{ + (void) rhport; + (void) ep_desc; + return false; +} + +// Submit a transfer, When complete dcd_event_xfer_complete() is invoked to notify the stack +bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t total_bytes) +{ + (void) rhport; + (void) ep_addr; + (void) buffer; + (void) total_bytes; + return false; +} + +// Stall endpoint +void dcd_edpt_stall (uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + (void) ep_addr; +} + +// clear stall, data toggle is also reset to DATA0 +void dcd_edpt_clear_stall (uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + (void) ep_addr; +} + +#endif diff --git a/src/tusb_option.h b/src/tusb_option.h index fc509ae7..5700bc8a 100644 --- a/src/tusb_option.h +++ b/src/tusb_option.h @@ -36,6 +36,8 @@ * \ref CFG_TUSB_MCU must be defined to one of these * @{ */ +#define OPT_MCU_NONE 0 + // LPC #define OPT_MCU_LPC11UXX 1 ///< NXP LPC11Uxx #define OPT_MCU_LPC13XX 2 ///< NXP LPC13xx From 42b55f6621a18179513c99d8013ef857b3d28b2f Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 4 Nov 2019 15:00:44 +0700 Subject: [PATCH 015/267] clean up --- hw/bsp/samg55xplained/board.mk | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hw/bsp/samg55xplained/board.mk b/hw/bsp/samg55xplained/board.mk index a8d2b0fe..78559450 100644 --- a/hw/bsp/samg55xplained/board.mk +++ b/hw/bsp/samg55xplained/board.mk @@ -10,7 +10,7 @@ CFLAGS += \ #CFLAGS += -Wno-error=undef -ASF_DIR = hw/mcu/microchip/samg +ASF_DIR = hw/mcu/microchip/samg55 # All source paths should be relative to the top level. LD_FILE = $(ASF_DIR)/samg55/gcc/gcc/samg55j19_flash.ld From 8cd19f88b9039657079a85d7bdb2cd3fffce585b Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 4 Nov 2019 22:03:31 +0700 Subject: [PATCH 016/267] clean up --- hw/bsp/samg55xplained/samg55xplained.c | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/hw/bsp/samg55xplained/samg55xplained.c b/hw/bsp/samg55xplained/samg55xplained.c index e1bc9c4c..b050d362 100644 --- a/hw/bsp/samg55xplained/samg55xplained.c +++ b/hw/bsp/samg55xplained/samg55xplained.c @@ -40,6 +40,7 @@ #define BUTTON_PIN GPIO(GPIO_PORTA, 2) #define BUTTON_STATE_ACTIVE 0 + //------------- IMPLEMENTATION -------------// void board_init(void) { @@ -64,6 +65,14 @@ void board_init(void) // 1ms tick timer (samd SystemCoreClock may not correct) SysTick_Config(CONF_CPU_FREQUENCY / 1000); #endif + + // USB + + /* Clear SYSIO 10 & 11 for USB DM & DP */ + hri_matrix_clear_CCFG_SYSIO_reg(MATRIX, CCFG_SYSIO_SYSIO10 | CCFG_SYSIO_SYSIO11); + + // Enble clock + _pmc_enable_periph_clock(ID_UDP); } //--------------------------------------------------------------------+ From fc86a308f6435752c9a6413e9a9d92f17783acf9 Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 5 Nov 2019 11:45:02 +0700 Subject: [PATCH 017/267] clean up --- src/class/msc/msc_device.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/class/msc/msc_device.c b/src/class/msc/msc_device.c index 88db1ffd..cec76b11 100644 --- a/src/class/msc/msc_device.c +++ b/src/class/msc/msc_device.c @@ -599,7 +599,7 @@ static void proc_read10_cmd(uint8_t rhport, mscd_interface_t* p_msc) TU_ASSERT(block_sz, ); // prevent div by zero // Adjust lba with transferred bytes - uint32_t lba = rdwr10_get_lba(p_cbw->command) + (p_msc->xferred_len / block_sz); + uint32_t const lba = rdwr10_get_lba(p_cbw->command) + (p_msc->xferred_len / block_sz); // remaining bytes capped at class buffer int32_t nbytes = (int32_t) tu_min32(sizeof(_mscd_buf), p_cbw->total_bytes-p_msc->xferred_len); From 943b7467d81889a7340e0d52d0ffe1cf1d9f7eec Mon Sep 17 00:00:00 2001 From: hathach Date: Sat, 9 Nov 2019 00:08:32 +0700 Subject: [PATCH 018/267] correct LED, button and uart for feather_stm32f405 --- hw/bsp/feather_stm32f405/board.mk | 7 ++-- hw/bsp/feather_stm32f405/feather_stm32f405.c | 39 +++++++++++++++---- hw/bsp/feather_stm32f405/stm32f4xx_hal_conf.h | 4 +- hw/bsp/stm32f072disco/stm32f072disco.c | 2 +- 4 files changed, 39 insertions(+), 13 deletions(-) diff --git a/hw/bsp/feather_stm32f405/board.mk b/hw/bsp/feather_stm32f405/board.mk index ef977797..14595e83 100644 --- a/hw/bsp/feather_stm32f405/board.mk +++ b/hw/bsp/feather_stm32f405/board.mk @@ -20,7 +20,8 @@ SRC_C += \ $(ST_HAL_DRIVER)/Src/stm32f4xx_hal.c \ $(ST_HAL_DRIVER)/Src/stm32f4xx_hal_cortex.c \ $(ST_HAL_DRIVER)/Src/stm32f4xx_hal_rcc.c \ - $(ST_HAL_DRIVER)/Src/stm32f4xx_hal_gpio.c + $(ST_HAL_DRIVER)/Src/stm32f4xx_hal_gpio.c \ + $(ST_HAL_DRIVER)/Src/stm32f4xx_hal_uart.c SRC_S += \ $(ST_CMSIS)/Source/Templates/gcc/startup_stm32f405xx.s @@ -46,5 +47,5 @@ JLINK_IF = swd STM32Prog = STM32_Programmer_CLI # flash target using on-board stlink -flash: $(BUILD)/$(BOARD)-firmware.elf - $(STM32Prog) --connect port=swd --write $< --go +flash: $(BUILD)/$(BOARD)-firmware.bin + dfu-util -R -a 0 --dfuse-address 0x08000000 -D $< diff --git a/hw/bsp/feather_stm32f405/feather_stm32f405.c b/hw/bsp/feather_stm32f405/feather_stm32f405.c index 0bc40ece..aec779ea 100644 --- a/hw/bsp/feather_stm32f405/feather_stm32f405.c +++ b/hw/bsp/feather_stm32f405/feather_stm32f405.c @@ -31,7 +31,7 @@ // Blue LED is chosen because the other LEDs are connected to ST-LINK lines. #define LED_PORT GPIOC -#define LED_PIN GPIO_PIN_4 +#define LED_PIN GPIO_PIN_1 #define LED_STATE_ON 1 // Pin D5 @@ -39,6 +39,24 @@ #define BUTTON_PIN GPIO_PIN_7 #define BUTTON_STATE_ACTIVE 0 +#define UARTx USART3 +#define UART_GPIO_PORT GPIOB +#define UART_GPIO_AF GPIO_AF7_USART3 +#define UART_TX_PIN GPIO_PIN_10 +#define UART_RX_PIN GPIO_PIN_11 + +UART_HandleTypeDef UartHandle; + + +// enable all LED, Button, Uart, USB clock +static void all_rcc_clk_enable(void) +{ + __HAL_RCC_GPIOA_CLK_ENABLE(); // USB D+, D- + __HAL_RCC_GPIOC_CLK_ENABLE(); // LED, Button + __HAL_RCC_GPIOB_CLK_ENABLE(); // Uart tx, rx + __HAL_RCC_USART3_CLK_ENABLE(); // Uart module +} + /** * @brief System Clock Configuration * The system Clock is configured as follow : @@ -104,14 +122,13 @@ void board_init(void) #endif SystemClock_Config(); - - // Notify runtime of frequency change. SystemCoreClockUpdate(); + all_rcc_clk_enable(); + GPIO_InitTypeDef GPIO_InitStruct; // LED - __HAL_RCC_GPIOC_CLK_ENABLE(); GPIO_InitStruct.Pin = LED_PIN; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_PULLUP; @@ -121,19 +138,25 @@ void board_init(void) board_led_write(false); // Button - //__HAL_RCC_GPIOC_CLK_ENABLE(); GPIO_InitStruct.Pin = BUTTON_PIN; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_PULLUP; GPIO_InitStruct.Speed = GPIO_SPEED_FAST; HAL_GPIO_Init(BUTTON_PORT, &GPIO_InitStruct); + // Uart + GPIO_InitStruct.Pin = UART_TX_PIN | UART_RX_PIN; + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Pull = GPIO_PULLUP; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; + GPIO_InitStruct.Alternate = UART_GPIO_AF; + HAL_GPIO_Init(UART_GPIO_PORT, &GPIO_InitStruct); + // Enable USB OTG clock __HAL_RCC_USB_OTG_FS_CLK_ENABLE(); // USB Pin Init // PA9- VUSB, PA10- ID, PA11- DM, PA12- DP - __HAL_RCC_GPIOA_CLK_ENABLE(); /* Configure DM DP Pins */ GPIO_InitStruct.Pin = GPIO_PIN_11 | GPIO_PIN_12; @@ -180,8 +203,8 @@ int board_uart_read(uint8_t* buf, int len) int board_uart_write(void const * buf, int len) { - (void) buf; (void) len; - return 0; + HAL_UART_Transmit(&UartHandle, (uint8_t*) buf, len, 0xffff); + return len; } #if CFG_TUSB_OS == OPT_OS_NONE diff --git a/hw/bsp/feather_stm32f405/stm32f4xx_hal_conf.h b/hw/bsp/feather_stm32f405/stm32f4xx_hal_conf.h index dbef20e0..b892df3b 100644 --- a/hw/bsp/feather_stm32f405/stm32f4xx_hal_conf.h +++ b/hw/bsp/feather_stm32f405/stm32f4xx_hal_conf.h @@ -75,7 +75,7 @@ /* #define HAL_MMC_MODULE_ENABLED */ /* #define HAL_SPI_MODULE_ENABLED */ /* #define HAL_TIM_MODULE_ENABLED */ -/* #define HAL_UART_MODULE_ENABLED */ +#define HAL_UART_MODULE_ENABLED /* #define HAL_USART_MODULE_ENABLED */ /* #define HAL_IRDA_MODULE_ENABLED */ /* #define HAL_SMARTCARD_MODULE_ENABLED */ @@ -199,6 +199,8 @@ #define USE_HAL_SPI_REGISTER_CALLBACKS 0U /* SPI register callback disabled */ #define USE_HAL_SWPMI_REGISTER_CALLBACKS 0U /* SWPMI register callback disabled */ #define USE_HAL_TIM_REGISTER_CALLBACKS 0U /* TIM register callback disabled */ +#define USE_HAL_UART_REGISTER_CALLBACKS 0U /* UART register callback disabled */ +#define USE_HAL_USART_REGISTER_CALLBACKS 0U /* USART register callback disabled */ #define USE_HAL_WWDG_REGISTER_CALLBACKS 0U /* WWDG register callback disabled */ /* ########################## Assert Selection ############################## */ diff --git a/hw/bsp/stm32f072disco/stm32f072disco.c b/hw/bsp/stm32f072disco/stm32f072disco.c index aac1c553..e26c5628 100644 --- a/hw/bsp/stm32f072disco/stm32f072disco.c +++ b/hw/bsp/stm32f072disco/stm32f072disco.c @@ -43,9 +43,9 @@ #define UART_TX_PIN GPIO_PIN_9 #define UART_RX_PIN GPIO_PIN_10 - UART_HandleTypeDef UartHandle; + // enable all LED, Button, Uart, USB clock static void all_rcc_clk_enable(void) { From a19db3bdd2071ceff3775a6ebb1a4d280423ac28 Mon Sep 17 00:00:00 2001 From: hathach Date: Sun, 10 Nov 2019 20:07:43 +0700 Subject: [PATCH 019/267] added board nrf52840 mdk dongle --- docs/boards.md | 3 +- hw/bsp/nrf52840_mdk_dongle/board.mk | 61 ++++++ .../nrf52840_mdk_dongle/nrf52840_mdk_dongle.c | 190 ++++++++++++++++++ .../nrf52840_mdk_dongle.ld | 13 ++ 4 files changed, 266 insertions(+), 1 deletion(-) create mode 100644 hw/bsp/nrf52840_mdk_dongle/board.mk create mode 100644 hw/bsp/nrf52840_mdk_dongle/nrf52840_mdk_dongle.c create mode 100644 hw/bsp/nrf52840_mdk_dongle/nrf52840_mdk_dongle.ld diff --git a/docs/boards.md b/docs/boards.md index 608cbf4e..9470ab2a 100644 --- a/docs/boards.md +++ b/docs/boards.md @@ -21,6 +21,7 @@ This code base already had supported for a handful of following boards - [Adafruit Feather nRF52840 Express](https://www.adafruit.com/product/4062) - [Adafruit Circuit Playground Bluefruit](https://www.adafruit.com/product/4333) +- [Maker Diary nRF52840 MDK Dongle](https://wiki.makerdiary.com/nrf52840-mdk-usb-dongle) - [Nordic nRF52840 Development Kit (aka pca10056)](https://www.nordicsemi.com/Software-and-Tools/Development-Kits/nRF52840-DK) - [Nordic nRF52840 Dongle (aka pca10059)](https://www.nordicsemi.com/Software-and-Tools/Development-Kits/nRF52840-Dongle) @@ -45,7 +46,7 @@ This code base already had supported for a handful of following boards ### ST STM32 -- Adafruit Feather STM32F405 +- [Adafruit Feather STM32F405](https://www.adafruit.com/product/4382) - [Micro Python PyBoard v1.1](https://store.micropython.org/product/PYBv1.1) - [STM32 L035c8 Discovery](https://www.st.com/en/evaluation-tools/32l0538discovery.html) - [STM32 F070rb Nucleo](https://www.st.com/en/evaluation-tools/nucleo-f070rb.html) diff --git a/hw/bsp/nrf52840_mdk_dongle/board.mk b/hw/bsp/nrf52840_mdk_dongle/board.mk new file mode 100644 index 00000000..df834f96 --- /dev/null +++ b/hw/bsp/nrf52840_mdk_dongle/board.mk @@ -0,0 +1,61 @@ +CFLAGS += \ + -mthumb \ + -mabi=aapcs \ + -mcpu=cortex-m4 \ + -mfloat-abi=hard \ + -mfpu=fpv4-sp-d16 \ + -DNRF52840_XXAA \ + -DCFG_TUSB_MCU=OPT_MCU_NRF5X + +# nrfx issue undef _ARMCC_VERSION usage https://github.com/NordicSemiconductor/nrfx/issues/49 +CFLAGS += -Wno-error=undef -Wno-error=unused-parameter + +# due to tusb_hal_nrf_power_event +GCCVERSION = $(firstword $(subst ., ,$(shell arm-none-eabi-gcc -dumpversion))) +ifeq ($(shell expr $(GCCVERSION) \>= 8), 1) +CFLAGS += -Wno-error=cast-function-type +endif + +# All source paths should be relative to the top level. +LD_FILE = hw/bsp/$(BOARD)/$(BOARD).ld + +LDFLAGS += -L$(TOP)/hw/mcu/nordic/nrfx/mdk + +SRC_C += \ + hw/mcu/nordic/nrfx/drivers/src/nrfx_power.c \ + hw/mcu/nordic/nrfx/mdk/system_nrf52840.c \ + +INC += \ + $(TOP)/hw/mcu/nordic/cmsis/Include \ + $(TOP)/hw/mcu/nordic \ + $(TOP)/hw/mcu/nordic/nrfx \ + $(TOP)/hw/mcu/nordic/nrfx/mdk \ + $(TOP)/hw/mcu/nordic/nrfx/hal \ + $(TOP)/hw/mcu/nordic/nrfx/drivers/include \ + $(TOP)/hw/mcu/nordic/nrfx/drivers/src \ + +SRC_S += hw/mcu/nordic/nrfx/mdk/gcc_startup_nrf52840.S + +ASFLAGS += -D__HEAP_SIZE=0 + +# For TinyUSB port source +VENDOR = nordic +CHIP_FAMILY = nrf5x + +# For freeRTOS port source +FREERTOS_PORT = ARM_CM4F + +# For flash-jlink target +JLINK_DEVICE = nRF52840_xxAA +JLINK_IF = swd + +# flash using Nordic nrfutil (pip2 install nrfutil) +# make BOARD=nrf52840_mdk_dongle SERIAL=/dev/ttyACM0 all flash +NRFUTIL = nrfutil + +$(BUILD)/$(BOARD)-firmware.zip: $(BUILD)/$(BOARD)-firmware.hex + $(NRFUTIL) pkg generate --hw-version 52 --sd-req 0x0000 --debug-mode --application $^ $@ + +flash: $(BUILD)/$(BOARD)-firmware.zip + @:$(call check_defined, SERIAL, example: SERIAL=/dev/ttyACM0) + $(NRFUTIL) dfu usb-serial --package $^ -p $(SERIAL) -b 115200 diff --git a/hw/bsp/nrf52840_mdk_dongle/nrf52840_mdk_dongle.c b/hw/bsp/nrf52840_mdk_dongle/nrf52840_mdk_dongle.c new file mode 100644 index 00000000..86f02d3e --- /dev/null +++ b/hw/bsp/nrf52840_mdk_dongle/nrf52840_mdk_dongle.c @@ -0,0 +1,190 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#include "bsp/board.h" + +#include "nrfx.h" +#include "nrfx/hal/nrf_gpio.h" +#include "nrfx/drivers/include/nrfx_power.h" + +#ifdef SOFTDEVICE_PRESENT +#include "nrf_sdm.h" +#include "nrf_soc.h" +#endif + +/*------------------------------------------------------------------*/ +/* MACRO TYPEDEF CONSTANT ENUM + *------------------------------------------------------------------*/ +#define LED_PIN 23 +#define LED_STATE_ON 0 + +// Button 1 +#define BUTTON_PIN 18 +#define BUTTON_STATE_ACTIVE 0 + +// tinyusb function that handles power event (detected, ready, removed) +// We must call it within SD's SOC event handler, or set it as power event handler if SD is not enabled. +extern void tusb_hal_nrf_power_event(uint32_t event); + +void board_init(void) +{ + // Config clock source: XTAL or RC in sdk_config.h + NRF_CLOCK->LFCLKSRC = (uint32_t)((CLOCK_LFCLKSRC_SRC_Xtal << CLOCK_LFCLKSRC_SRC_Pos) & CLOCK_LFCLKSRC_SRC_Msk); + NRF_CLOCK->TASKS_LFCLKSTART = 1UL; + + // LED + nrf_gpio_cfg_output(LED_PIN); + board_led_write(false); + + // Button + nrf_gpio_cfg_input(BUTTON_PIN, NRF_GPIO_PIN_PULLUP); + +#if CFG_TUSB_OS == OPT_OS_NONE + // 1ms tick timer + SysTick_Config(SystemCoreClock/1000); +#endif + +#if TUSB_OPT_DEVICE_ENABLED + // Priorities 0, 1, 4 (nRF52) are reserved for SoftDevice + // 2 is highest for application + NVIC_SetPriority(USBD_IRQn, 2); + + // USB power may already be ready at this time -> no event generated + // We need to invoke the handler based on the status initially + uint32_t usb_reg; + +#ifdef SOFTDEVICE_PRESENT + uint8_t sd_en = false; + sd_softdevice_is_enabled(&sd_en); + + if ( sd_en ) { + sd_power_usbdetected_enable(true); + sd_power_usbpwrrdy_enable(true); + sd_power_usbremoved_enable(true); + + sd_power_usbregstatus_get(&usb_reg); + }else +#endif + { + // Power module init + const nrfx_power_config_t pwr_cfg = { 0 }; + nrfx_power_init(&pwr_cfg); + + // Register tusb function as USB power handler + const nrfx_power_usbevt_config_t config = { .handler = (nrfx_power_usb_event_handler_t) tusb_hal_nrf_power_event }; + nrfx_power_usbevt_init(&config); + + nrfx_power_usbevt_enable(); + + usb_reg = NRF_POWER->USBREGSTATUS; + } + + if ( usb_reg & POWER_USBREGSTATUS_VBUSDETECT_Msk ) tusb_hal_nrf_power_event(NRFX_POWER_USB_EVT_DETECTED); + if ( usb_reg & POWER_USBREGSTATUS_OUTPUTRDY_Msk ) tusb_hal_nrf_power_event(NRFX_POWER_USB_EVT_READY); +#endif +} + +//--------------------------------------------------------------------+ +// Board porting API +//--------------------------------------------------------------------+ + +void board_led_write(bool state) +{ + nrf_gpio_pin_write(LED_PIN, state ? LED_STATE_ON : (1-LED_STATE_ON)); +} + +uint32_t board_button_read(void) +{ + return BUTTON_STATE_ACTIVE == nrf_gpio_pin_read(BUTTON_PIN); +} + +int board_uart_read(uint8_t* buf, int len) +{ + (void) buf; (void) len; + return 0; +} + +int board_uart_write(void const * buf, int len) +{ + (void) buf; (void) len; + return 0; +} + +#if CFG_TUSB_OS == OPT_OS_NONE +volatile uint32_t system_ticks = 0; +void SysTick_Handler (void) +{ + system_ticks++; +} + +uint32_t board_millis(void) +{ + return system_ticks; +} +#endif + +#ifdef SOFTDEVICE_PRESENT +// process SOC event from SD +uint32_t proc_soc(void) +{ + uint32_t soc_evt; + uint32_t err = sd_evt_get(&soc_evt); + + if (NRF_SUCCESS == err) + { + /*------------- usb power event handler -------------*/ + int32_t usbevt = (soc_evt == NRF_EVT_POWER_USB_DETECTED ) ? NRFX_POWER_USB_EVT_DETECTED: + (soc_evt == NRF_EVT_POWER_USB_POWER_READY) ? NRFX_POWER_USB_EVT_READY : + (soc_evt == NRF_EVT_POWER_USB_REMOVED ) ? NRFX_POWER_USB_EVT_REMOVED : -1; + + if ( usbevt >= 0) tusb_hal_nrf_power_event(usbevt); + } + + return err; +} + +uint32_t proc_ble(void) +{ + // do nothing with ble + return NRF_ERROR_NOT_FOUND; +} + +void SD_EVT_IRQHandler(void) +{ + // process BLE and SOC until there is no more events + while( (NRF_ERROR_NOT_FOUND != proc_ble()) || (NRF_ERROR_NOT_FOUND != proc_soc()) ) + { + + } +} + +void nrf_error_cb(uint32_t id, uint32_t pc, uint32_t info) +{ + (void) id; + (void) pc; + (void) info; +} +#endif diff --git a/hw/bsp/nrf52840_mdk_dongle/nrf52840_mdk_dongle.ld b/hw/bsp/nrf52840_mdk_dongle/nrf52840_mdk_dongle.ld new file mode 100644 index 00000000..78eddc9c --- /dev/null +++ b/hw/bsp/nrf52840_mdk_dongle/nrf52840_mdk_dongle.ld @@ -0,0 +1,13 @@ +/* Linker script to configure memory regions. */ + +SEARCH_DIR(.) +GROUP(-lgcc -lc -lnosys) + +MEMORY +{ + FLASH (rx) : ORIGIN = 0x1000, LENGTH = 0xE0000-0x1000 + RAM (rwx) : ORIGIN = 0x20000008, LENGTH = 0x3fff8 +} + + +INCLUDE "nrf_common.ld" From 2f19b9c100f4131d82e0e32ed78191188032a088 Mon Sep 17 00:00:00 2001 From: hathach Date: Sun, 10 Nov 2019 21:04:55 +0700 Subject: [PATCH 020/267] update submodule nrfx to 2.0.0 for nrf52833 support --- hw/mcu/nordic/nrfx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hw/mcu/nordic/nrfx b/hw/mcu/nordic/nrfx index 9d68726e..7a4c9d94 160000 --- a/hw/mcu/nordic/nrfx +++ b/hw/mcu/nordic/nrfx @@ -1 +1 @@ -Subproject commit 9d68726e41c321f1772c187bd12d82f5b13104f1 +Subproject commit 7a4c9d946cf1801771fc180acdbf7b878f270093 From 4008f0d1e66dff6bb42a0fb0c682bf4bfe8e6c4a Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 11 Nov 2019 00:01:12 +0700 Subject: [PATCH 021/267] update dcd nrf5x to be indepent from nrf_usbd.h fix build error with nrfx 2.0 --- hw/bsp/pca10056/pca10056.c | 8 +++--- hw/mcu/nordic/nrfx_config.h | 12 +++++++-- src/portable/nordic/nrf5x/dcd_nrf5x.c | 38 ++++++++++++++++----------- 3 files changed, 37 insertions(+), 21 deletions(-) diff --git a/hw/bsp/pca10056/pca10056.c b/hw/bsp/pca10056/pca10056.c index 31fd5e9b..b9cc9fc3 100644 --- a/hw/bsp/pca10056/pca10056.c +++ b/hw/bsp/pca10056/pca10056.c @@ -84,10 +84,12 @@ void board_init(void) .pselcts = NRF_UARTE_PSEL_DISCONNECTED, .pselrts = NRF_UARTE_PSEL_DISCONNECTED, .p_context = NULL, - .hwfc = NRF_UARTE_HWFC_DISABLED, - .parity = NRF_UARTE_PARITY_EXCLUDED, .baudrate = NRF_UARTE_BAUDRATE_115200, // CFG_BOARD_UART_BAUDRATE - .interrupt_priority = 7 + .interrupt_priority = 7, + .hal_cfg = { + .hwfc = NRF_UARTE_HWFC_DISABLED, + .parity = NRF_UARTE_PARITY_EXCLUDED, + } }; nrfx_uarte_init(&_uart_id, &uart_cfg, NULL); //uart_handler); diff --git a/hw/mcu/nordic/nrfx_config.h b/hw/mcu/nordic/nrfx_config.h index 8f9aeffe..6a974ba7 100644 --- a/hw/mcu/nordic/nrfx_config.h +++ b/hw/mcu/nordic/nrfx_config.h @@ -1,10 +1,18 @@ #ifndef NRFX_CONFIG_H__ #define NRFX_CONFIG_H__ -#define NRFX_POWER_ENABLED 1 -#define NRFX_POWER_CONFIG_IRQ_PRIORITY 7 +#define NRFX_POWER_ENABLED 1 +#define NRFX_POWER_DEFAULT_CONFIG_IRQ_PRIORITY 7 + +#define NRFX_CLOCK_ENABLED 0 #define NRFX_UARTE_ENABLED 1 #define NRFX_UARTE0_ENABLED 1 +#define NRFX_UARTE1_ENABLED 0 +#define NRFX_UARTE2_ENABLED 0 +#define NRFX_UARTE3_ENABLED 0 + +#define NRFX_PRS_ENABLED 0 + #endif // NRFX_CONFIG_H__ diff --git a/src/portable/nordic/nrf5x/dcd_nrf5x.c b/src/portable/nordic/nrf5x/dcd_nrf5x.c index 17140ee7..59c2f36a 100644 --- a/src/portable/nordic/nrf5x/dcd_nrf5x.c +++ b/src/portable/nordic/nrf5x/dcd_nrf5x.c @@ -31,7 +31,6 @@ #include "nrf.h" #include "nrf_clock.h" #include "nrf_power.h" -#include "nrf_usbd.h" #include "nrfx_usbd_errata.h" #ifdef SOFTDEVICE_PRESENT @@ -498,7 +497,8 @@ void USBD_IRQHandler(void) if ( int_status & (USBD_INTEN_EPDATA_Msk | USBD_INTEN_EP0DATADONE_Msk) ) { uint32_t data_status = NRF_USBD->EPDATASTATUS; - nrf_usbd_epdatastatus_clear(data_status); + NRF_USBD->EPDATASTATUS = data_status; + __ISB(); __DSB(); // EP0DATADONE is set with either Control Out on IN Data // Since EPDATASTATUS cannot be used to determine whether it is control OUT or IN. @@ -572,7 +572,7 @@ static bool hfclk_running(void) } #endif - return nrf_clock_hf_is_running(NRF_CLOCK_HFCLK_HIGH_ACCURACY); + return nrf_clock_hf_is_running(NRF_CLOCK, NRF_CLOCK_HFCLK_HIGH_ACCURACY); } static void hfclk_enable(void) @@ -588,8 +588,8 @@ static void hfclk_enable(void) } #endif - nrf_clock_event_clear(NRF_CLOCK_EVENT_HFCLKSTARTED); - nrf_clock_task_trigger(NRF_CLOCK_TASK_HFCLKSTART); + nrf_clock_event_clear(NRF_CLOCK, NRF_CLOCK_EVENT_HFCLKSTARTED); + nrf_clock_task_trigger(NRF_CLOCK, NRF_CLOCK_TASK_HFCLKSTART); } static void hfclk_disable(void) @@ -602,7 +602,7 @@ static void hfclk_disable(void) } #endif - nrf_clock_task_trigger(NRF_CLOCK_TASK_HFCLKSTOP); + nrf_clock_task_trigger(NRF_CLOCK, NRF_CLOCK_TASK_HFCLKSTOP); } // Power & Clock Peripheral on nRF5x to manage USB @@ -630,7 +630,8 @@ void tusb_hal_nrf_power_event (uint32_t event) if ( !NRF_USBD->ENABLE ) { /* Prepare for READY event receiving */ - nrf_usbd_eventcause_clear(NRF_USBD_EVENTCAUSE_READY_MASK); + NRF_USBD->EVENTCAUSE = USBD_EVENTCAUSE_READY_Msk; + __ISB(); __DSB(); // for sync /* Enable the peripheral */ // ERRATA 171, 187, 166 @@ -667,7 +668,8 @@ void tusb_hal_nrf_power_event (uint32_t event) // CRITICAL_REGION_EXIT(); } - nrf_usbd_enable(); + NRF_USBD->ENABLE = 1; + __ISB(); __DSB(); // for sync // Enable HFCLK hfclk_enable(); @@ -678,8 +680,8 @@ void tusb_hal_nrf_power_event (uint32_t event) /* Waiting for USBD peripheral enabled */ while ( !(USBD_EVENTCAUSE_READY_Msk & NRF_USBD->EVENTCAUSE) ) { } - nrf_usbd_eventcause_clear(USBD_EVENTCAUSE_READY_Msk); - nrf_usbd_event_clear(USBD_EVENTCAUSE_READY_Msk); + NRF_USBD->EVENTCAUSE = USBD_EVENTCAUSE_READY_Msk; + __ISB(); __DSB(); // for sync if ( nrfx_usbd_errata_171() ) { @@ -719,11 +721,11 @@ void tusb_hal_nrf_power_event (uint32_t event) *((volatile uint32_t *) (NRF_USBD_BASE + 0x800)) = 0x7E3; *((volatile uint32_t *) (NRF_USBD_BASE + 0x804)) = 0x40; - __ISB(); - __DSB(); + __ISB(); __DSB(); } - nrf_usbd_isosplit_set(USBD_ISOSPLIT_SPLIT_HalfIN); + // ISO buffer Lower half for IN, upper half for OUT + NRF_USBD->ISOSPLIT = USBD_ISOSPLIT_SPLIT_HalfIN; // Enable interrupt NRF_USBD->INTENSET = USBD_INTEN_USBRESET_Msk | USBD_INTEN_EPDATA_Msk | @@ -737,7 +739,8 @@ void tusb_hal_nrf_power_event (uint32_t event) while ( !hfclk_running() ) { } // Enable pull up - nrf_usbd_pullup_enable(); + NRF_USBD->USBPULLUP = 1; + __ISB(); __DSB(); // for sync break; case USB_EVT_REMOVED: @@ -746,7 +749,8 @@ void tusb_hal_nrf_power_event (uint32_t event) // Abort all transfers // Disable pull up - nrf_usbd_pullup_disable(); + NRF_USBD->USBPULLUP = 0; + __ISB(); __DSB(); // for sync // Disable Interrupt NVIC_DisableIRQ(USBD_IRQn); @@ -754,7 +758,9 @@ void tusb_hal_nrf_power_event (uint32_t event) // disable all interrupt NRF_USBD->INTENCLR = NRF_USBD->INTEN; - nrf_usbd_disable(); + NRF_USBD->ENABLE = 0; + __ISB(); __DSB(); // for sync + hfclk_disable(); dcd_event_bus_signal(0, DCD_EVENT_UNPLUGGED, true); From d65bc34bfeb3dab8fb79a94cec7b3b8f5a579525 Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 11 Nov 2019 00:11:49 +0700 Subject: [PATCH 022/267] added and tested nRF52833DK (pca10100) --- README.md | 2 +- docs/boards.md | 1 + examples/device/cdc_msc/src/main.c | 2 +- hw/bsp/pca10100/board.mk | 55 +++++++ hw/bsp/pca10100/pca10100.c | 223 +++++++++++++++++++++++++++++ 5 files changed, 281 insertions(+), 2 deletions(-) create mode 100644 hw/bsp/pca10100/board.mk create mode 100644 hw/bsp/pca10100/pca10100.c diff --git a/README.md b/README.md index 02fb8257..2e61c75e 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,7 @@ TinyUSB is an open-source cross-platform USB Host/Device stack for embedded syst The stack supports the following MCUs -- **Nordic:** nRF52840 +- **Nordic:** nRF52840, nRF52833 - **NXP:** LPC Series: 11Uxx, 13xx, 175x_6x, 177x_8x, 18xx, 40xx, 43xx, 51Uxx, 54xxx, 55xx - **MicroChip:** SAMD21, SAMD51 (device only) - **Sony:** CXD56 diff --git a/docs/boards.md b/docs/boards.md index 9470ab2a..3ca4d458 100644 --- a/docs/boards.md +++ b/docs/boards.md @@ -24,6 +24,7 @@ This code base already had supported for a handful of following boards - [Maker Diary nRF52840 MDK Dongle](https://wiki.makerdiary.com/nrf52840-mdk-usb-dongle) - [Nordic nRF52840 Development Kit (aka pca10056)](https://www.nordicsemi.com/Software-and-Tools/Development-Kits/nRF52840-DK) - [Nordic nRF52840 Dongle (aka pca10059)](https://www.nordicsemi.com/Software-and-Tools/Development-Kits/nRF52840-Dongle) +- [Nordic nRF52833 Development Kit (aka pca10100)](https://www.nordicsemi.com/Software-and-Tools/Development-Kits/nRF52833-DK) ### NXP LPC diff --git a/examples/device/cdc_msc/src/main.c b/examples/device/cdc_msc/src/main.c index e1b9ab11..a407e2dd 100644 --- a/examples/device/cdc_msc/src/main.c +++ b/examples/device/cdc_msc/src/main.c @@ -136,7 +136,7 @@ void tud_cdc_line_state_cb(uint8_t itf, bool dtr, bool rts) if ( dtr && rts ) { // print initial message when connected - tud_cdc_write_str("\r\nTinyUSB CDC MSC HID device example\r\n"); + tud_cdc_write_str("\r\nTinyUSB CDC MSC device example\r\n"); } } diff --git a/hw/bsp/pca10100/board.mk b/hw/bsp/pca10100/board.mk new file mode 100644 index 00000000..97d9aa42 --- /dev/null +++ b/hw/bsp/pca10100/board.mk @@ -0,0 +1,55 @@ +CFLAGS += \ + -mthumb \ + -mabi=aapcs \ + -mcpu=cortex-m4 \ + -mfloat-abi=hard \ + -mfpu=fpv4-sp-d16 \ + -DNRF52833_XXAA \ + -DCONFIG_GPIO_AS_PINRESET \ + -DCFG_TUSB_MCU=OPT_MCU_NRF5X + +# nrfx issue undef _ARMCC_VERSION usage https://github.com/NordicSemiconductor/nrfx/issues/49 +CFLAGS += -Wno-error=undef -Wno-error=unused-parameter + +# due to tusb_hal_nrf_power_event +GCCVERSION = $(firstword $(subst ., ,$(shell arm-none-eabi-gcc -dumpversion))) +ifeq ($(shell expr $(GCCVERSION) \>= 8), 1) +CFLAGS += -Wno-error=cast-function-type +endif + +# All source paths should be relative to the top level. +LD_FILE = hw/mcu/nordic/nrfx/mdk/nrf52833_xxaa.ld + +LDFLAGS += -L$(TOP)/hw/mcu/nordic/nrfx/mdk + +SRC_C += \ + hw/mcu/nordic/nrfx/drivers/src/nrfx_power.c \ + hw/mcu/nordic/nrfx/drivers/src/nrfx_uarte.c \ + hw/mcu/nordic/nrfx/mdk/system_nrf52833.c \ + +INC += \ + $(TOP)/hw/mcu/nordic/cmsis/Include \ + $(TOP)/hw/mcu/nordic \ + $(TOP)/hw/mcu/nordic/nrfx \ + $(TOP)/hw/mcu/nordic/nrfx/mdk \ + $(TOP)/hw/mcu/nordic/nrfx/hal \ + $(TOP)/hw/mcu/nordic/nrfx/drivers/include \ + $(TOP)/hw/mcu/nordic/nrfx/drivers/src \ + +SRC_S += hw/mcu/nordic/nrfx/mdk/gcc_startup_nrf52833.S + +ASFLAGS += -D__HEAP_SIZE=0 + +# For TinyUSB port source +VENDOR = nordic +CHIP_FAMILY = nrf5x + +# For freeRTOS port source +FREERTOS_PORT = ARM_CM4F + +# For flash-jlink target +JLINK_DEVICE = nRF52833_XXAA +JLINK_IF = swd + +# flash using jlink +flash: flash-jlink diff --git a/hw/bsp/pca10100/pca10100.c b/hw/bsp/pca10100/pca10100.c new file mode 100644 index 00000000..b9cc9fc3 --- /dev/null +++ b/hw/bsp/pca10100/pca10100.c @@ -0,0 +1,223 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#include "bsp/board.h" + +#include "nrfx.h" +#include "nrfx/hal/nrf_gpio.h" +#include "nrfx/drivers/include/nrfx_power.h" +#include "nrfx/drivers/include/nrfx_uarte.h" + +#ifdef SOFTDEVICE_PRESENT +#include "nrf_sdm.h" +#include "nrf_soc.h" +#endif + +/*------------------------------------------------------------------*/ +/* MACRO TYPEDEF CONSTANT ENUM + *------------------------------------------------------------------*/ +#define LED_PIN 13 +#define LED_STATE_ON 0 + +#define BUTTON_PIN 11 +#define BUTTON_STATE_ACTIVE 0 + +#define UART_RX_PIN 8 +#define UART_TX_PIN 6 + +static nrfx_uarte_t _uart_id = NRFX_UARTE_INSTANCE(0); +//static void uart_handler(nrfx_uart_event_t const * p_event, void* p_context); + +// tinyusb function that handles power event (detected, ready, removed) +// We must call it within SD's SOC event handler, or set it as power event handler if SD is not enabled. +extern void tusb_hal_nrf_power_event(uint32_t event); + +void board_init(void) +{ + // stop LF clock just in case we jump from application without reset + NRF_CLOCK->TASKS_LFCLKSTOP = 1UL; + + // Use Internal OSC to compatible with all boards + NRF_CLOCK->LFCLKSRC = CLOCK_LFCLKSRC_SRC_RC; + NRF_CLOCK->TASKS_LFCLKSTART = 1UL; + + // LED + nrf_gpio_cfg_output(LED_PIN); + board_led_write(false); + + // Button + nrf_gpio_cfg_input(BUTTON_PIN, NRF_GPIO_PIN_PULLUP); + +#if CFG_TUSB_OS == OPT_OS_NONE + // 1ms tick timer + SysTick_Config(SystemCoreClock/1000); +#endif + + // UART + nrfx_uarte_config_t uart_cfg = + { + .pseltxd = UART_TX_PIN, + .pselrxd = UART_RX_PIN, + .pselcts = NRF_UARTE_PSEL_DISCONNECTED, + .pselrts = NRF_UARTE_PSEL_DISCONNECTED, + .p_context = NULL, + .baudrate = NRF_UARTE_BAUDRATE_115200, // CFG_BOARD_UART_BAUDRATE + .interrupt_priority = 7, + .hal_cfg = { + .hwfc = NRF_UARTE_HWFC_DISABLED, + .parity = NRF_UARTE_PARITY_EXCLUDED, + } + }; + + nrfx_uarte_init(&_uart_id, &uart_cfg, NULL); //uart_handler); + +#if TUSB_OPT_DEVICE_ENABLED + // Priorities 0, 1, 4 (nRF52) are reserved for SoftDevice + // 2 is highest for application + NVIC_SetPriority(USBD_IRQn, 2); + + // USB power may already be ready at this time -> no event generated + // We need to invoke the handler based on the status initially + uint32_t usb_reg; + +#ifdef SOFTDEVICE_PRESENT + uint8_t sd_en = false; + sd_softdevice_is_enabled(&sd_en); + + if ( sd_en ) { + sd_power_usbdetected_enable(true); + sd_power_usbpwrrdy_enable(true); + sd_power_usbremoved_enable(true); + + sd_power_usbregstatus_get(&usb_reg); + }else +#endif + { + // Power module init + const nrfx_power_config_t pwr_cfg = { 0 }; + nrfx_power_init(&pwr_cfg); + + // Register tusb function as USB power handler + // cause cast-function-type warning + const nrfx_power_usbevt_config_t config = { .handler = ((nrfx_power_usb_event_handler_t) tusb_hal_nrf_power_event) }; + nrfx_power_usbevt_init(&config); + + nrfx_power_usbevt_enable(); + + usb_reg = NRF_POWER->USBREGSTATUS; + } + + if ( usb_reg & POWER_USBREGSTATUS_VBUSDETECT_Msk ) tusb_hal_nrf_power_event(NRFX_POWER_USB_EVT_DETECTED); + if ( usb_reg & POWER_USBREGSTATUS_OUTPUTRDY_Msk ) tusb_hal_nrf_power_event(NRFX_POWER_USB_EVT_READY); +#endif +} + +//--------------------------------------------------------------------+ +// Board porting API +//--------------------------------------------------------------------+ + +void board_led_write(bool state) +{ + nrf_gpio_pin_write(LED_PIN, state ? LED_STATE_ON : (1-LED_STATE_ON)); +} + +uint32_t board_button_read(void) +{ + return BUTTON_STATE_ACTIVE == nrf_gpio_pin_read(BUTTON_PIN); +} + +//static void uart_handler(nrfx_uart_event_t const * p_event, void* p_context) +//{ +// +//} + +int board_uart_read(uint8_t* buf, int len) +{ + (void) buf; (void) len; + return 0; +// return NRFX_SUCCESS == nrfx_uart_rx(&_uart_id, buf, (size_t) len) ? len : 0; +} + +int board_uart_write(void const * buf, int len) +{ + return (NRFX_SUCCESS == nrfx_uarte_tx(&_uart_id, (uint8_t const*) buf, (size_t) len)) ? len : 0; +} + +#if CFG_TUSB_OS == OPT_OS_NONE +volatile uint32_t system_ticks = 0; +void SysTick_Handler (void) +{ + system_ticks++; +} + +uint32_t board_millis(void) +{ + return system_ticks; +} +#endif + +#ifdef SOFTDEVICE_PRESENT +// process SOC event from SD +uint32_t proc_soc(void) +{ + uint32_t soc_evt; + uint32_t err = sd_evt_get(&soc_evt); + + if (NRF_SUCCESS == err) + { + /*------------- usb power event handler -------------*/ + int32_t usbevt = (soc_evt == NRF_EVT_POWER_USB_DETECTED ) ? NRFX_POWER_USB_EVT_DETECTED: + (soc_evt == NRF_EVT_POWER_USB_POWER_READY) ? NRFX_POWER_USB_EVT_READY : + (soc_evt == NRF_EVT_POWER_USB_REMOVED ) ? NRFX_POWER_USB_EVT_REMOVED : -1; + + if ( usbevt >= 0) tusb_hal_nrf_power_event(usbevt); + } + + return err; +} + +uint32_t proc_ble(void) +{ + // do nothing with ble + return NRF_ERROR_NOT_FOUND; +} + +void SD_EVT_IRQHandler(void) +{ + // process BLE and SOC until there is no more events + while( (NRF_ERROR_NOT_FOUND != proc_ble()) || (NRF_ERROR_NOT_FOUND != proc_soc()) ) + { + + } +} + +void nrf_error_cb(uint32_t id, uint32_t pc, uint32_t info) +{ + (void) id; + (void) pc; + (void) info; +} +#endif From 1684cb06b74b3a8ed645f3342edd504e6423f88c Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 11 Nov 2019 11:24:10 +0700 Subject: [PATCH 023/267] update makefile for lpc mcu --- hw/bsp/ea4088qs/board.mk | 2 +- hw/bsp/ea4357/board.mk | 2 +- hw/bsp/lpcxpresso11u37/board.mk | 2 +- hw/bsp/lpcxpresso11u68/board.mk | 2 +- hw/bsp/lpcxpresso1347/board.mk | 2 +- hw/bsp/lpcxpresso1549/board.mk | 2 +- hw/bsp/lpcxpresso1769/board.mk | 2 +- hw/bsp/lpcxpresso51u68/board.mk | 2 +- hw/bsp/lpcxpresso54114/board.mk | 2 +- hw/bsp/lpcxpresso55s69/board.mk | 2 +- hw/bsp/mbed1768/board.mk | 2 +- hw/bsp/mcb1800/board.mk | 2 +- hw/bsp/ngx4330/board.mk | 2 +- hw/mcu/nxp/lpc_driver | 2 +- 14 files changed, 14 insertions(+), 14 deletions(-) diff --git a/hw/bsp/ea4088qs/board.mk b/hw/bsp/ea4088qs/board.mk index 46625ca8..80cd4f65 100644 --- a/hw/bsp/ea4088qs/board.mk +++ b/hw/bsp/ea4088qs/board.mk @@ -11,7 +11,7 @@ CFLAGS += \ # mcu driver cause following warnings CFLAGS += -Wno-error=strict-prototypes -Wno-error=unused-parameter -MCU_DIR = hw/mcu/nxp/lpc_driver/lpc40xx/lpc_chip_40xx +MCU_DIR = hw/mcu/nxp/lpc_driver/lpcopen/lpc40xx/lpc_chip_40xx # All source paths should be relative to the top level. LD_FILE = hw/bsp/ea4088qs/lpc4088.ld diff --git a/hw/bsp/ea4357/board.mk b/hw/bsp/ea4357/board.mk index 823481ba..4e53cf4a 100644 --- a/hw/bsp/ea4357/board.mk +++ b/hw/bsp/ea4357/board.mk @@ -10,7 +10,7 @@ CFLAGS += \ # mcu driver cause following warnings CFLAGS += -Wno-error=unused-parameter -Wno-error=strict-prototypes -MCU_DIR = hw/mcu/nxp/lpc_driver/lpc43xx/lpc_chip_43xx +MCU_DIR = hw/mcu/nxp/lpc_driver/lpcopen/lpc43xx/lpc_chip_43xx # All source paths should be relative to the top level. LD_FILE = hw/bsp/ea4357/lpc4357.ld diff --git a/hw/bsp/lpcxpresso11u37/board.mk b/hw/bsp/lpcxpresso11u37/board.mk index ced7ceef..df7769f4 100644 --- a/hw/bsp/lpcxpresso11u37/board.mk +++ b/hw/bsp/lpcxpresso11u37/board.mk @@ -13,7 +13,7 @@ CFLAGS += \ # mcu driver cause following warnings CFLAGS += -Wno-error=nested-externs -Wno-error=strict-prototypes -Wno-error=unused-parameter -MCU_DIR = hw/mcu/nxp/lpc_driver/lpc11uxx/lpc_chip_11uxx +MCU_DIR = hw/mcu/nxp/lpc_driver/lpcopen/lpc11uxx/lpc_chip_11uxx # All source paths should be relative to the top level. LD_FILE = hw/bsp/lpcxpresso11u37/lpc11u37.ld diff --git a/hw/bsp/lpcxpresso11u68/board.mk b/hw/bsp/lpcxpresso11u68/board.mk index 9396a599..74ffef0c 100644 --- a/hw/bsp/lpcxpresso11u68/board.mk +++ b/hw/bsp/lpcxpresso11u68/board.mk @@ -10,7 +10,7 @@ CFLAGS += \ -DCFG_TUSB_MEM_SECTION='__attribute__((section(".data.$$RAM3")))' \ -DCFG_TUSB_MEM_ALIGN='__attribute__((aligned(64)))' -MCU_DIR = hw/mcu/nxp/lpc_driver/lpc11u6x/lpc_chip_11u6x +MCU_DIR = hw/mcu/nxp/lpc_driver/lpcopen/lpc11u6x/lpc_chip_11u6x # All source paths should be relative to the top level. LD_FILE = hw/bsp/lpcxpresso11u68/lpc11u68.ld diff --git a/hw/bsp/lpcxpresso1347/board.mk b/hw/bsp/lpcxpresso1347/board.mk index 0f9be1b5..05f42c4f 100644 --- a/hw/bsp/lpcxpresso1347/board.mk +++ b/hw/bsp/lpcxpresso1347/board.mk @@ -13,7 +13,7 @@ CFLAGS += \ # startup.c and lpc_types.h cause following errors CFLAGS += -Wno-error=nested-externs -Wno-error=strict-prototypes -MCU_DIR = hw/mcu/nxp/lpc_driver/lpc13xx/lpc_chip_13xx +MCU_DIR = hw/mcu/nxp/lpc_driver/lpcopen/lpc13xx/lpc_chip_13xx # All source paths should be relative to the top level. LD_FILE = hw/bsp/lpcxpresso1347/lpc1347.ld diff --git a/hw/bsp/lpcxpresso1549/board.mk b/hw/bsp/lpcxpresso1549/board.mk index 929c63a8..ddef463f 100644 --- a/hw/bsp/lpcxpresso1549/board.mk +++ b/hw/bsp/lpcxpresso1549/board.mk @@ -12,7 +12,7 @@ CFLAGS += \ # mcu driver cause following warnings CFLAGS += -Wno-error=strict-prototypes -Wno-error=unused-parameter -Wno-error=unused-variable -MCU_DIR = hw/mcu/nxp/lpc_driver/lpc15xx/lpc_chip_15xx +MCU_DIR = hw/mcu/nxp/lpc_driver/lpcopen/lpc15xx/lpc_chip_15xx # All source paths should be relative to the top level. LD_FILE = hw/bsp/$(BOARD)/lpc1549.ld diff --git a/hw/bsp/lpcxpresso1769/board.mk b/hw/bsp/lpcxpresso1769/board.mk index 8bbc8913..2fc70bb2 100644 --- a/hw/bsp/lpcxpresso1769/board.mk +++ b/hw/bsp/lpcxpresso1769/board.mk @@ -11,7 +11,7 @@ CFLAGS += \ # lpc_types.h cause following errors CFLAGS += -Wno-error=strict-prototypes -MCU_DIR = hw/mcu/nxp/lpc_driver/lpc175x_6x/lpc_chip_175x_6x +MCU_DIR = hw/mcu/nxp/lpc_driver/lpcopen/lpc175x_6x/lpc_chip_175x_6x # All source paths should be relative to the top level. LD_FILE = hw/bsp/lpcxpresso1769/lpc1769.ld diff --git a/hw/bsp/lpcxpresso51u68/board.mk b/hw/bsp/lpcxpresso51u68/board.mk index e5576c3c..fcda464c 100644 --- a/hw/bsp/lpcxpresso51u68/board.mk +++ b/hw/bsp/lpcxpresso51u68/board.mk @@ -10,7 +10,7 @@ CFLAGS += \ # mcu driver cause following warnings CFLAGS += -Wno-error=nested-externs -Wno-error=unused-parameter -MCU_DIR = hw/mcu/nxp/lpc_driver/lpc51u6x/devices/LPC51U68 +MCU_DIR = hw/mcu/nxp/lpc_driver/sdk/devices/LPC51U68 # All source paths should be relative to the top level. LD_FILE = $(MCU_DIR)/gcc/LPC51U68_flash.ld diff --git a/hw/bsp/lpcxpresso54114/board.mk b/hw/bsp/lpcxpresso54114/board.mk index 21c8dfd3..09592fab 100644 --- a/hw/bsp/lpcxpresso54114/board.mk +++ b/hw/bsp/lpcxpresso54114/board.mk @@ -12,7 +12,7 @@ CFLAGS += \ # mcu driver cause following warnings CFLAGS += -Wno-error=unused-parameter -MCU_DIR = hw/mcu/nxp/lpc_driver/lpc54xxx/devices/LPC54114 +MCU_DIR = hw/mcu/nxp/lpc_driver/sdk/devices/LPC54114 # All source paths should be relative to the top level. LD_FILE = $(MCU_DIR)/gcc/LPC54114J256_cm4_flash.ld diff --git a/hw/bsp/lpcxpresso55s69/board.mk b/hw/bsp/lpcxpresso55s69/board.mk index 6f1afaac..c51d527d 100644 --- a/hw/bsp/lpcxpresso55s69/board.mk +++ b/hw/bsp/lpcxpresso55s69/board.mk @@ -12,7 +12,7 @@ CFLAGS += \ # mcu driver cause following warnings CFLAGS += -Wno-error=unused-parameter -Wno-error=float-equal -Wno-error=nested-externs -MCU_DIR = hw/mcu/nxp/lpc_driver/lpc55xx/devices/LPC55S69 +MCU_DIR = hw/mcu/nxp/lpc_driver/sdk/devices/LPC55S69 # All source paths should be relative to the top level. LD_FILE = $(MCU_DIR)/gcc/LPC55S69_cm33_core0_flash.ld diff --git a/hw/bsp/mbed1768/board.mk b/hw/bsp/mbed1768/board.mk index 4e4cd1d8..dc5d11d9 100644 --- a/hw/bsp/mbed1768/board.mk +++ b/hw/bsp/mbed1768/board.mk @@ -11,7 +11,7 @@ CFLAGS += \ # startup.c and lpc_types.h cause following errors CFLAGS += -Wno-error=nested-externs -Wno-error=strict-prototypes -MCU_DIR = hw/mcu/nxp/lpc_driver/lpc175x_6x/lpc_chip_175x_6x +MCU_DIR = hw/mcu/nxp/lpc_driver/lpcopen/lpc175x_6x/lpc_chip_175x_6x # All source paths should be relative to the top level. LD_FILE = hw/bsp/mbed1768/lpc1768.ld diff --git a/hw/bsp/mcb1800/board.mk b/hw/bsp/mcb1800/board.mk index 3b8ee296..c4e39bef 100644 --- a/hw/bsp/mcb1800/board.mk +++ b/hw/bsp/mcb1800/board.mk @@ -10,7 +10,7 @@ CFLAGS += \ # mcu driver cause following warnings CFLAGS += -Wno-error=unused-parameter -Wno-error=strict-prototypes -MCU_DIR = hw/mcu/nxp/lpc_driver/lpc18xx/lpc_chip_18xx +MCU_DIR = hw/mcu/nxp/lpc_driver/lpcopen/lpc18xx/lpc_chip_18xx # All source paths should be relative to the top level. LD_FILE = hw/bsp/mcb1800/lpc1857.ld diff --git a/hw/bsp/ngx4330/board.mk b/hw/bsp/ngx4330/board.mk index b82ae9d5..f5de5f54 100644 --- a/hw/bsp/ngx4330/board.mk +++ b/hw/bsp/ngx4330/board.mk @@ -10,7 +10,7 @@ CFLAGS += \ # mcu driver cause following warnings CFLAGS += -Wno-error=strict-prototypes -Wno-error=unused-parameter -MCU_DIR = hw/mcu/nxp/lpc_driver/lpc43xx/lpc_chip_43xx +MCU_DIR = hw/mcu/nxp/lpc_driver/lpcopen/lpc43xx/lpc_chip_43xx # All source paths should be relative to the top level. LD_FILE = hw/bsp/$(BOARD)/ngx4330.ld diff --git a/hw/mcu/nxp/lpc_driver b/hw/mcu/nxp/lpc_driver index fa206508..0eef4984 160000 --- a/hw/mcu/nxp/lpc_driver +++ b/hw/mcu/nxp/lpc_driver @@ -1 +1 @@ -Subproject commit fa206508e9ea289ceeb9c35442dd8002002f9316 +Subproject commit 0eef4984c339b8c201812e3ed09cf70225a81b16 From 50cfc556d2f170b7e0c71cc2f25c36c43acf3732 Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 11 Nov 2019 11:33:50 +0700 Subject: [PATCH 024/267] remove submodule lpc_driver --- .gitmodules | 3 --- hw/mcu/nxp/lpc_driver | 1 - 2 files changed, 4 deletions(-) delete mode 160000 hw/mcu/nxp/lpc_driver diff --git a/.gitmodules b/.gitmodules index 9afa0d19..b932f64a 100644 --- a/.gitmodules +++ b/.gitmodules @@ -7,9 +7,6 @@ [submodule "tools/uf2"] path = tools/uf2 url = https://github.com/microsoft/uf2.git -[submodule "hw/mcu/nxp/lpc_driver"] - path = hw/mcu/nxp/lpc_driver - url = https://github.com/hathach/lpc_driver.git [submodule "hw/mcu/st/st_driver"] path = hw/mcu/st/st_driver url = https://github.com/hathach/st_driver.git diff --git a/hw/mcu/nxp/lpc_driver b/hw/mcu/nxp/lpc_driver deleted file mode 160000 index 0eef4984..00000000 --- a/hw/mcu/nxp/lpc_driver +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 0eef4984c339b8c201812e3ed09cf70225a81b16 From eca14a5ab34a432b49a06f083729e75af9e4db76 Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 11 Nov 2019 11:38:30 +0700 Subject: [PATCH 025/267] re-add submodule nxp_driver --- .gitmodules | 3 +++ hw/mcu/nxp | 1 + 2 files changed, 4 insertions(+) create mode 160000 hw/mcu/nxp diff --git a/.gitmodules b/.gitmodules index b932f64a..c7b39618 100644 --- a/.gitmodules +++ b/.gitmodules @@ -16,3 +16,6 @@ [submodule "hw/mcu/ti"] path = hw/mcu/ti url = https://github.com/hathach/ti_driver.git +[submodule "hw/mcu/nxp"] + path = hw/mcu/nxp + url = https://github.com/hathach/nxp_driver.git diff --git a/hw/mcu/nxp b/hw/mcu/nxp new file mode 160000 index 00000000..0eef4984 --- /dev/null +++ b/hw/mcu/nxp @@ -0,0 +1 @@ +Subproject commit 0eef4984c339b8c201812e3ed09cf70225a81b16 From cd96b3de863b49edad70fe06fc99fdf6c81c9575 Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 11 Nov 2019 11:51:51 +0700 Subject: [PATCH 026/267] update makefile for lpc boards --- hw/bsp/ea4088qs/board.mk | 2 +- hw/bsp/ea4357/board.mk | 2 +- hw/bsp/lpcxpresso11u37/board.mk | 2 +- hw/bsp/lpcxpresso11u68/board.mk | 2 +- hw/bsp/lpcxpresso1347/board.mk | 2 +- hw/bsp/lpcxpresso1549/board.mk | 2 +- hw/bsp/lpcxpresso1769/board.mk | 2 +- hw/bsp/lpcxpresso51u68/board.mk | 2 +- hw/bsp/lpcxpresso54114/board.mk | 2 +- hw/bsp/lpcxpresso55s69/board.mk | 2 +- hw/bsp/mbed1768/board.mk | 2 +- hw/bsp/mcb1800/board.mk | 2 +- hw/bsp/ngx4330/board.mk | 2 +- 13 files changed, 13 insertions(+), 13 deletions(-) diff --git a/hw/bsp/ea4088qs/board.mk b/hw/bsp/ea4088qs/board.mk index 80cd4f65..f621affb 100644 --- a/hw/bsp/ea4088qs/board.mk +++ b/hw/bsp/ea4088qs/board.mk @@ -11,7 +11,7 @@ CFLAGS += \ # mcu driver cause following warnings CFLAGS += -Wno-error=strict-prototypes -Wno-error=unused-parameter -MCU_DIR = hw/mcu/nxp/lpc_driver/lpcopen/lpc40xx/lpc_chip_40xx +MCU_DIR = hw/mcu/nxp/lpcopen/lpc40xx/lpc_chip_40xx # All source paths should be relative to the top level. LD_FILE = hw/bsp/ea4088qs/lpc4088.ld diff --git a/hw/bsp/ea4357/board.mk b/hw/bsp/ea4357/board.mk index 4e53cf4a..be6a307e 100644 --- a/hw/bsp/ea4357/board.mk +++ b/hw/bsp/ea4357/board.mk @@ -10,7 +10,7 @@ CFLAGS += \ # mcu driver cause following warnings CFLAGS += -Wno-error=unused-parameter -Wno-error=strict-prototypes -MCU_DIR = hw/mcu/nxp/lpc_driver/lpcopen/lpc43xx/lpc_chip_43xx +MCU_DIR = hw/mcu/nxp/lpcopen/lpc43xx/lpc_chip_43xx # All source paths should be relative to the top level. LD_FILE = hw/bsp/ea4357/lpc4357.ld diff --git a/hw/bsp/lpcxpresso11u37/board.mk b/hw/bsp/lpcxpresso11u37/board.mk index df7769f4..72c5ef0d 100644 --- a/hw/bsp/lpcxpresso11u37/board.mk +++ b/hw/bsp/lpcxpresso11u37/board.mk @@ -13,7 +13,7 @@ CFLAGS += \ # mcu driver cause following warnings CFLAGS += -Wno-error=nested-externs -Wno-error=strict-prototypes -Wno-error=unused-parameter -MCU_DIR = hw/mcu/nxp/lpc_driver/lpcopen/lpc11uxx/lpc_chip_11uxx +MCU_DIR = hw/mcu/nxp/lpcopen/lpc11uxx/lpc_chip_11uxx # All source paths should be relative to the top level. LD_FILE = hw/bsp/lpcxpresso11u37/lpc11u37.ld diff --git a/hw/bsp/lpcxpresso11u68/board.mk b/hw/bsp/lpcxpresso11u68/board.mk index 74ffef0c..c1718395 100644 --- a/hw/bsp/lpcxpresso11u68/board.mk +++ b/hw/bsp/lpcxpresso11u68/board.mk @@ -10,7 +10,7 @@ CFLAGS += \ -DCFG_TUSB_MEM_SECTION='__attribute__((section(".data.$$RAM3")))' \ -DCFG_TUSB_MEM_ALIGN='__attribute__((aligned(64)))' -MCU_DIR = hw/mcu/nxp/lpc_driver/lpcopen/lpc11u6x/lpc_chip_11u6x +MCU_DIR = hw/mcu/nxp/lpcopen/lpc11u6x/lpc_chip_11u6x # All source paths should be relative to the top level. LD_FILE = hw/bsp/lpcxpresso11u68/lpc11u68.ld diff --git a/hw/bsp/lpcxpresso1347/board.mk b/hw/bsp/lpcxpresso1347/board.mk index 05f42c4f..1900ca0a 100644 --- a/hw/bsp/lpcxpresso1347/board.mk +++ b/hw/bsp/lpcxpresso1347/board.mk @@ -13,7 +13,7 @@ CFLAGS += \ # startup.c and lpc_types.h cause following errors CFLAGS += -Wno-error=nested-externs -Wno-error=strict-prototypes -MCU_DIR = hw/mcu/nxp/lpc_driver/lpcopen/lpc13xx/lpc_chip_13xx +MCU_DIR = hw/mcu/nxp/lpcopen/lpc13xx/lpc_chip_13xx # All source paths should be relative to the top level. LD_FILE = hw/bsp/lpcxpresso1347/lpc1347.ld diff --git a/hw/bsp/lpcxpresso1549/board.mk b/hw/bsp/lpcxpresso1549/board.mk index ddef463f..66078f0f 100644 --- a/hw/bsp/lpcxpresso1549/board.mk +++ b/hw/bsp/lpcxpresso1549/board.mk @@ -12,7 +12,7 @@ CFLAGS += \ # mcu driver cause following warnings CFLAGS += -Wno-error=strict-prototypes -Wno-error=unused-parameter -Wno-error=unused-variable -MCU_DIR = hw/mcu/nxp/lpc_driver/lpcopen/lpc15xx/lpc_chip_15xx +MCU_DIR = hw/mcu/nxp/lpcopen/lpc15xx/lpc_chip_15xx # All source paths should be relative to the top level. LD_FILE = hw/bsp/$(BOARD)/lpc1549.ld diff --git a/hw/bsp/lpcxpresso1769/board.mk b/hw/bsp/lpcxpresso1769/board.mk index 2fc70bb2..412e0cd5 100644 --- a/hw/bsp/lpcxpresso1769/board.mk +++ b/hw/bsp/lpcxpresso1769/board.mk @@ -11,7 +11,7 @@ CFLAGS += \ # lpc_types.h cause following errors CFLAGS += -Wno-error=strict-prototypes -MCU_DIR = hw/mcu/nxp/lpc_driver/lpcopen/lpc175x_6x/lpc_chip_175x_6x +MCU_DIR = hw/mcu/nxp/lpcopen/lpc175x_6x/lpc_chip_175x_6x # All source paths should be relative to the top level. LD_FILE = hw/bsp/lpcxpresso1769/lpc1769.ld diff --git a/hw/bsp/lpcxpresso51u68/board.mk b/hw/bsp/lpcxpresso51u68/board.mk index fcda464c..f02dee03 100644 --- a/hw/bsp/lpcxpresso51u68/board.mk +++ b/hw/bsp/lpcxpresso51u68/board.mk @@ -10,7 +10,7 @@ CFLAGS += \ # mcu driver cause following warnings CFLAGS += -Wno-error=nested-externs -Wno-error=unused-parameter -MCU_DIR = hw/mcu/nxp/lpc_driver/sdk/devices/LPC51U68 +MCU_DIR = hw/mcu/nxp/sdk/devices/LPC51U68 # All source paths should be relative to the top level. LD_FILE = $(MCU_DIR)/gcc/LPC51U68_flash.ld diff --git a/hw/bsp/lpcxpresso54114/board.mk b/hw/bsp/lpcxpresso54114/board.mk index 09592fab..24de4a44 100644 --- a/hw/bsp/lpcxpresso54114/board.mk +++ b/hw/bsp/lpcxpresso54114/board.mk @@ -12,7 +12,7 @@ CFLAGS += \ # mcu driver cause following warnings CFLAGS += -Wno-error=unused-parameter -MCU_DIR = hw/mcu/nxp/lpc_driver/sdk/devices/LPC54114 +MCU_DIR = hw/mcu/nxp/sdk/devices/LPC54114 # All source paths should be relative to the top level. LD_FILE = $(MCU_DIR)/gcc/LPC54114J256_cm4_flash.ld diff --git a/hw/bsp/lpcxpresso55s69/board.mk b/hw/bsp/lpcxpresso55s69/board.mk index c51d527d..fada53dc 100644 --- a/hw/bsp/lpcxpresso55s69/board.mk +++ b/hw/bsp/lpcxpresso55s69/board.mk @@ -12,7 +12,7 @@ CFLAGS += \ # mcu driver cause following warnings CFLAGS += -Wno-error=unused-parameter -Wno-error=float-equal -Wno-error=nested-externs -MCU_DIR = hw/mcu/nxp/lpc_driver/sdk/devices/LPC55S69 +MCU_DIR = hw/mcu/nxp/sdk/devices/LPC55S69 # All source paths should be relative to the top level. LD_FILE = $(MCU_DIR)/gcc/LPC55S69_cm33_core0_flash.ld diff --git a/hw/bsp/mbed1768/board.mk b/hw/bsp/mbed1768/board.mk index dc5d11d9..9bb0a792 100644 --- a/hw/bsp/mbed1768/board.mk +++ b/hw/bsp/mbed1768/board.mk @@ -11,7 +11,7 @@ CFLAGS += \ # startup.c and lpc_types.h cause following errors CFLAGS += -Wno-error=nested-externs -Wno-error=strict-prototypes -MCU_DIR = hw/mcu/nxp/lpc_driver/lpcopen/lpc175x_6x/lpc_chip_175x_6x +MCU_DIR = hw/mcu/nxp/lpcopen/lpc175x_6x/lpc_chip_175x_6x # All source paths should be relative to the top level. LD_FILE = hw/bsp/mbed1768/lpc1768.ld diff --git a/hw/bsp/mcb1800/board.mk b/hw/bsp/mcb1800/board.mk index c4e39bef..b50e47a2 100644 --- a/hw/bsp/mcb1800/board.mk +++ b/hw/bsp/mcb1800/board.mk @@ -10,7 +10,7 @@ CFLAGS += \ # mcu driver cause following warnings CFLAGS += -Wno-error=unused-parameter -Wno-error=strict-prototypes -MCU_DIR = hw/mcu/nxp/lpc_driver/lpcopen/lpc18xx/lpc_chip_18xx +MCU_DIR = hw/mcu/nxp/lpcopen/lpc18xx/lpc_chip_18xx # All source paths should be relative to the top level. LD_FILE = hw/bsp/mcb1800/lpc1857.ld diff --git a/hw/bsp/ngx4330/board.mk b/hw/bsp/ngx4330/board.mk index f5de5f54..565532b4 100644 --- a/hw/bsp/ngx4330/board.mk +++ b/hw/bsp/ngx4330/board.mk @@ -10,7 +10,7 @@ CFLAGS += \ # mcu driver cause following warnings CFLAGS += -Wno-error=strict-prototypes -Wno-error=unused-parameter -MCU_DIR = hw/mcu/nxp/lpc_driver/lpcopen/lpc43xx/lpc_chip_43xx +MCU_DIR = hw/mcu/nxp/lpcopen/lpc43xx/lpc_chip_43xx # All source paths should be relative to the top level. LD_FILE = hw/bsp/$(BOARD)/ngx4330.ld From 23df777b301af128d3543e286cd865212214b44d Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 11 Nov 2019 12:14:54 +0700 Subject: [PATCH 027/267] update nxp_driver submodule for imx rt families --- hw/mcu/nxp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hw/mcu/nxp b/hw/mcu/nxp index 0eef4984..b618cb1d 160000 --- a/hw/mcu/nxp +++ b/hw/mcu/nxp @@ -1 +1 @@ -Subproject commit 0eef4984c339b8c201812e3ed09cf70225a81b16 +Subproject commit b618cb1d521cc9e133bdcd0fca154dee2d925dfe From f152bed4b4f7b470ebec2045dab6008ef7add856 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Sat, 12 Oct 2019 00:00:36 +0800 Subject: [PATCH 028/267] fomu: initial commit Signed-off-by: Sean Cross --- hw/bsp/fomu/board.mk | 29 ++ hw/bsp/fomu/bsp.c | 129 ++++++ hw/bsp/fomu/crt0-vexriscv.S | 91 ++++ hw/bsp/fomu/fomu.ld | 61 +++ hw/bsp/fomu/include/csr.h | 709 ++++++++++++++++++++++++++++++++ hw/bsp/fomu/include/hw/common.h | 33 ++ hw/bsp/fomu/include/irq.h | 71 ++++ hw/bsp/fomu/output_format.ld | 1 + hw/bsp/fomu/regions.ld | 6 + 9 files changed, 1130 insertions(+) create mode 100644 hw/bsp/fomu/board.mk create mode 100644 hw/bsp/fomu/bsp.c create mode 100644 hw/bsp/fomu/crt0-vexriscv.S create mode 100644 hw/bsp/fomu/fomu.ld create mode 100644 hw/bsp/fomu/include/csr.h create mode 100644 hw/bsp/fomu/include/hw/common.h create mode 100644 hw/bsp/fomu/include/irq.h create mode 100644 hw/bsp/fomu/output_format.ld create mode 100644 hw/bsp/fomu/regions.ld diff --git a/hw/bsp/fomu/board.mk b/hw/bsp/fomu/board.mk new file mode 100644 index 00000000..86f8df23 --- /dev/null +++ b/hw/bsp/fomu/board.mk @@ -0,0 +1,29 @@ +CFLAGS += \ + -march=rv32i \ + -mabi=ilp32 \ + -nostdlib \ + -DCFG_TUSB_MCU=OPT_MCU_FOMU_EPTRI + +MCU_DIR = hw/mcu/fomu +BSP_DIR = hw/bsp/fomu + +# All source paths should be relative to the top level. +LD_FILE = hw/bsp/fomu/fomu.ld + +# TODO remove later +SRC_C += src/portable/$(VENDOR)/$(CHIP_FAMILY)/hal_$(CHIP_FAMILY).c + +SRC_C += + +SRC_S += hw/bsp/fomu/crt0-vexriscv.S + +INC += \ + $(TOP)/$(BSP_DIR)/include + +# For TinyUSB port source +VENDOR = foosn +CHIP_FAMILY = fomu + +# flash using dfu-util +flash: $(BUILD)/$(BOARD)-firmware.dfu + dfu-util -D $^ diff --git a/hw/bsp/fomu/bsp.c b/hw/bsp/fomu/bsp.c new file mode 100644 index 00000000..861c223f --- /dev/null +++ b/hw/bsp/fomu/bsp.c @@ -0,0 +1,129 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#include +#include +#include "common/tusb_common.h" +#include "csr.h" +#include "irq.h" + +//--------------------------------------------------------------------+ +// Board porting API +//--------------------------------------------------------------------+ + +void hal_dcd_isr(uint8_t rhport); + +void mputs(const char *str) { + (void)str; + while (*str) { + if (! (messible_status_read() & CSR_MESSIBLE_STATUS_FULL_OFFSET)) + messible_in_write(*str); + str++; + } +} + +void mputln(const char *str) { + mputs(str); + mputs("\n"); +} + +void fomu_error(uint32_t line) +{ + (void)line; + TU_BREAKPOINT(); + while (1) {} +} + +volatile uint32_t system_ticks = 0; +static void timer_init(void) +{ + int t; + + timer0_en_write(0); + t = CONFIG_CLOCK_FREQUENCY / 1000; // 1000 kHz tick + timer0_reload_write(t); + timer0_load_write(t); + timer0_en_write(1); + timer0_ev_enable_write(1); + timer0_ev_pending_write(1); + irq_setmask(irq_getmask() | (1 << TIMER0_INTERRUPT)); +} + +void isr(void) +{ + unsigned int irqs; + + irqs = irq_pending() & irq_getmask(); + + if (irqs & (1 << USB_INTERRUPT)) { + hal_dcd_isr(0); + } + if (irqs & (1 << TIMER0_INTERRUPT)) { + system_ticks++; + timer0_ev_pending_write(1); + } +} + +void board_init(void) +{ + mputln("Fomu Initializing"); + irq_setmask(0); + irq_setie(1); + timer_init(); + return; +} + +void board_led_write(bool state) +{ + rgb_ctrl_write(0xff); + rgb_raw_write(state); +} + +uint32_t board_button_read(void) +{ + return 0; +} + +int board_uart_read(uint8_t* buf, int len) +{ + (void) buf; + (void) len; + return 0; +} + +int board_uart_write(void const * buf, int len) +{ + (void) buf; + (void) len; + return 0; +} + +#if CFG_TUSB_OS == OPT_OS_NONE +uint32_t board_millis(void) +{ + return system_ticks; +} +#endif \ No newline at end of file diff --git a/hw/bsp/fomu/crt0-vexriscv.S b/hw/bsp/fomu/crt0-vexriscv.S new file mode 100644 index 00000000..931d50a0 --- /dev/null +++ b/hw/bsp/fomu/crt0-vexriscv.S @@ -0,0 +1,91 @@ +.global main +.global isr + +.section .text.start +.global _start + +_start: + j crt_init + nop + nop + nop + nop + nop + nop + nop + +.section .text +.global trap_entry +trap_entry: + sw x1, - 1*4(sp) + sw x5, - 2*4(sp) + sw x6, - 3*4(sp) + sw x7, - 4*4(sp) + sw x10, - 5*4(sp) + sw x11, - 6*4(sp) + sw x12, - 7*4(sp) + sw x13, - 8*4(sp) + sw x14, - 9*4(sp) + sw x15, -10*4(sp) + sw x16, -11*4(sp) + sw x17, -12*4(sp) + sw x28, -13*4(sp) + sw x29, -14*4(sp) + sw x30, -15*4(sp) + sw x31, -16*4(sp) + addi sp,sp,-16*4 + call isr + lw x1 , 15*4(sp) + lw x5, 14*4(sp) + lw x6, 13*4(sp) + lw x7, 12*4(sp) + lw x10, 11*4(sp) + lw x11, 10*4(sp) + lw x12, 9*4(sp) + lw x13, 8*4(sp) + lw x14, 7*4(sp) + lw x15, 6*4(sp) + lw x16, 5*4(sp) + lw x17, 4*4(sp) + lw x28, 3*4(sp) + lw x29, 2*4(sp) + lw x30, 1*4(sp) + lw x31, 0*4(sp) + addi sp,sp,16*4 + mret + .text + + +crt_init: + la sp, _fstack + 4 + la a0, trap_entry + csrw mtvec, a0 + +bss_init: + la a0, _fbss + la a1, _ebss +bss_loop: + beq a0,a1,bss_done + sw zero,0(a0) + add a0,a0,4 + j bss_loop +bss_done: + + /* Load DATA */ + la t0, _erodata + la t1, _fdata + la t2, _edata +3: + lw t3, 0(t0) + sw t3, 0(t1) + /* _edata is aligned to 16 bytes. Use word-xfers. */ + addi t0, t0, 4 + addi t1, t1, 4 + bltu t1, t2, 3b + + li a0, 0x880 //880 enable timer + external interrupt sources (until mstatus.MIE is set, they will never trigger an interrupt) + csrw mie,a0 + + call main +infinit_loop: + j infinit_loop diff --git a/hw/bsp/fomu/fomu.ld b/hw/bsp/fomu/fomu.ld new file mode 100644 index 00000000..f39d62f3 --- /dev/null +++ b/hw/bsp/fomu/fomu.ld @@ -0,0 +1,61 @@ +OUTPUT_FORMAT("elf32-littleriscv") +ENTRY(_start) + +__DYNAMIC = 0; + +MEMORY { + csr : ORIGIN = 0x60000000, LENGTH = 0x01000000 + vexriscv_debug : ORIGIN = 0xf00f0000, LENGTH = 0x00000100 + sram : ORIGIN = 0x10000000, LENGTH = 0x00020000 + rom : ORIGIN = 0x2001a000, LENGTH = 0x00200000 - 0x1a000 +} + +SECTIONS +{ + .text : + { + _ftext = .; + *(.text.start) + *(.text .stub .text.* .gnu.linkonce.t.*) + _etext = .; + } > rom + + .rodata : + { + . = ALIGN(4); + _frodata = .; + *(.rodata .rodata.* .gnu.linkonce.r.*) + *(.rodata1) + *(.srodata) + _erodata = .; + } > rom + + .data : AT (ADDR(.rodata) + SIZEOF (.rodata)) + { + . = ALIGN(4); + _fdata = .; + *(.data .data.* .gnu.linkonce.d.*) + *(.data1) + _gp = ALIGN(16); + *(.sdata .sdata.* .gnu.linkonce.s.* .sdata2 .sdata2.*) + _edata = ALIGN(16); /* Make sure _edata is >= _gp. */ + } > sram + + .bss : + { + . = ALIGN(4); + _fbss = .; + *(.dynsbss) + *(.sbss .sbss.* .gnu.linkonce.sb.*) + *(.scommon) + *(.dynbss) + *(.bss .bss.* .gnu.linkonce.b.*) + *(COMMON) + . = ALIGN(4); + _ebss = .; + _end = .; + PROVIDE(end = .); + } > sram +} + +PROVIDE(_fstack = ORIGIN(sram) + LENGTH(sram) - 4); diff --git a/hw/bsp/fomu/include/csr.h b/hw/bsp/fomu/include/csr.h new file mode 100644 index 00000000..b9bffada --- /dev/null +++ b/hw/bsp/fomu/include/csr.h @@ -0,0 +1,709 @@ +//-------------------------------------------------------------------------------- +// Auto-generated by Migen (f4fcd10) & LiteX (1425a68d) on 2019-10-11 22:01:17 +//-------------------------------------------------------------------------------- +#ifndef __GENERATED_CSR_H +#define __GENERATED_CSR_H +#include +#ifdef CSR_ACCESSORS_DEFINED +extern void csr_writeb(uint8_t value, unsigned long addr); +extern uint8_t csr_readb(unsigned long addr); +extern void csr_writew(uint16_t value, unsigned long addr); +extern uint16_t csr_readw(unsigned long addr); +extern void csr_writel(uint32_t value, unsigned long addr); +extern uint32_t csr_readl(unsigned long addr); +#else /* ! CSR_ACCESSORS_DEFINED */ +#include +#endif /* ! CSR_ACCESSORS_DEFINED */ + +/* ctrl */ +#define CSR_CTRL_BASE 0xe0000000L +#define CSR_CTRL_RESET_ADDR 0xe0000000L +#define CSR_CTRL_RESET_SIZE 1 +static inline unsigned char ctrl_reset_read(void) { + unsigned char r = csr_readl(0xe0000000L); + return r; +} +static inline void ctrl_reset_write(unsigned char value) { + csr_writel(value, 0xe0000000L); +} +#define CSR_CTRL_SCRATCH_ADDR 0xe0000004L +#define CSR_CTRL_SCRATCH_SIZE 4 +static inline unsigned int ctrl_scratch_read(void) { + unsigned int r = csr_readl(0xe0000004L); + r <<= 8; + r |= csr_readl(0xe0000008L); + r <<= 8; + r |= csr_readl(0xe000000cL); + r <<= 8; + r |= csr_readl(0xe0000010L); + return r; +} +static inline void ctrl_scratch_write(unsigned int value) { + csr_writel(value >> 24, 0xe0000004L); + csr_writel(value >> 16, 0xe0000008L); + csr_writel(value >> 8, 0xe000000cL); + csr_writel(value, 0xe0000010L); +} +#define CSR_CTRL_BUS_ERRORS_ADDR 0xe0000014L +#define CSR_CTRL_BUS_ERRORS_SIZE 4 +static inline unsigned int ctrl_bus_errors_read(void) { + unsigned int r = csr_readl(0xe0000014L); + r <<= 8; + r |= csr_readl(0xe0000018L); + r <<= 8; + r |= csr_readl(0xe000001cL); + r <<= 8; + r |= csr_readl(0xe0000020L); + return r; +} + +/* lxspi */ +#define CSR_LXSPI_BASE 0xe0007800L +#define CSR_LXSPI_BITBANG_ADDR 0xe0007800L +#define CSR_LXSPI_BITBANG_SIZE 1 +static inline unsigned char lxspi_bitbang_read(void) { + unsigned char r = csr_readl(0xe0007800L); + return r; +} +static inline void lxspi_bitbang_write(unsigned char value) { + csr_writel(value, 0xe0007800L); +} +#define CSR_LXSPI_BITBANG_MOSI_OFFSET 0 +#define CSR_LXSPI_BITBANG_MOSI_SIZE 1 +#define CSR_LXSPI_BITBANG_CLK_OFFSET 1 +#define CSR_LXSPI_BITBANG_CLK_SIZE 1 +#define CSR_LXSPI_BITBANG_CS_N_OFFSET 2 +#define CSR_LXSPI_BITBANG_CS_N_SIZE 1 +#define CSR_LXSPI_BITBANG_DIR_OFFSET 3 +#define CSR_LXSPI_BITBANG_DIR_SIZE 1 +#define CSR_LXSPI_MISO_ADDR 0xe0007804L +#define CSR_LXSPI_MISO_SIZE 1 +static inline unsigned char lxspi_miso_read(void) { + unsigned char r = csr_readl(0xe0007804L); + return r; +} +#define CSR_LXSPI_BITBANG_EN_ADDR 0xe0007808L +#define CSR_LXSPI_BITBANG_EN_SIZE 1 +static inline unsigned char lxspi_bitbang_en_read(void) { + unsigned char r = csr_readl(0xe0007808L); + return r; +} +static inline void lxspi_bitbang_en_write(unsigned char value) { + csr_writel(value, 0xe0007808L); +} + +/* messible */ +#define CSR_MESSIBLE_BASE 0xe0008000L +#define CSR_MESSIBLE_IN_ADDR 0xe0008000L +#define CSR_MESSIBLE_IN_SIZE 1 +static inline unsigned char messible_in_read(void) { + unsigned char r = csr_readl(0xe0008000L); + return r; +} +static inline void messible_in_write(unsigned char value) { + csr_writel(value, 0xe0008000L); +} +#define CSR_MESSIBLE_OUT_ADDR 0xe0008004L +#define CSR_MESSIBLE_OUT_SIZE 1 +static inline unsigned char messible_out_read(void) { + unsigned char r = csr_readl(0xe0008004L); + return r; +} +#define CSR_MESSIBLE_STATUS_ADDR 0xe0008008L +#define CSR_MESSIBLE_STATUS_SIZE 1 +static inline unsigned char messible_status_read(void) { + unsigned char r = csr_readl(0xe0008008L); + return r; +} +#define CSR_MESSIBLE_STATUS_FULL_OFFSET 0 +#define CSR_MESSIBLE_STATUS_FULL_SIZE 1 +#define CSR_MESSIBLE_STATUS_HAVE_OFFSET 1 +#define CSR_MESSIBLE_STATUS_HAVE_SIZE 1 + +/* reboot */ +#define CSR_REBOOT_BASE 0xe0006000L +#define CSR_REBOOT_CTRL_ADDR 0xe0006000L +#define CSR_REBOOT_CTRL_SIZE 1 +static inline unsigned char reboot_ctrl_read(void) { + unsigned char r = csr_readl(0xe0006000L); + return r; +} +static inline void reboot_ctrl_write(unsigned char value) { + csr_writel(value, 0xe0006000L); +} +#define CSR_REBOOT_CTRL_IMAGE_OFFSET 0 +#define CSR_REBOOT_CTRL_IMAGE_SIZE 2 +#define CSR_REBOOT_CTRL_KEY_OFFSET 2 +#define CSR_REBOOT_CTRL_KEY_SIZE 6 +#define CSR_REBOOT_ADDR_ADDR 0xe0006004L +#define CSR_REBOOT_ADDR_SIZE 4 +static inline unsigned int reboot_addr_read(void) { + unsigned int r = csr_readl(0xe0006004L); + r <<= 8; + r |= csr_readl(0xe0006008L); + r <<= 8; + r |= csr_readl(0xe000600cL); + r <<= 8; + r |= csr_readl(0xe0006010L); + return r; +} +static inline void reboot_addr_write(unsigned int value) { + csr_writel(value >> 24, 0xe0006004L); + csr_writel(value >> 16, 0xe0006008L); + csr_writel(value >> 8, 0xe000600cL); + csr_writel(value, 0xe0006010L); +} + +/* rgb */ +#define CSR_RGB_BASE 0xe0006800L +#define CSR_RGB_DAT_ADDR 0xe0006800L +#define CSR_RGB_DAT_SIZE 1 +static inline unsigned char rgb_dat_read(void) { + unsigned char r = csr_readl(0xe0006800L); + return r; +} +static inline void rgb_dat_write(unsigned char value) { + csr_writel(value, 0xe0006800L); +} +#define CSR_RGB_ADDR_ADDR 0xe0006804L +#define CSR_RGB_ADDR_SIZE 1 +static inline unsigned char rgb_addr_read(void) { + unsigned char r = csr_readl(0xe0006804L); + return r; +} +static inline void rgb_addr_write(unsigned char value) { + csr_writel(value, 0xe0006804L); +} +#define CSR_RGB_CTRL_ADDR 0xe0006808L +#define CSR_RGB_CTRL_SIZE 1 +static inline unsigned char rgb_ctrl_read(void) { + unsigned char r = csr_readl(0xe0006808L); + return r; +} +static inline void rgb_ctrl_write(unsigned char value) { + csr_writel(value, 0xe0006808L); +} +#define CSR_RGB_CTRL_EXE_OFFSET 0 +#define CSR_RGB_CTRL_EXE_SIZE 1 +#define CSR_RGB_CTRL_CURREN_OFFSET 1 +#define CSR_RGB_CTRL_CURREN_SIZE 1 +#define CSR_RGB_CTRL_RGBLEDEN_OFFSET 2 +#define CSR_RGB_CTRL_RGBLEDEN_SIZE 1 +#define CSR_RGB_CTRL_RRAW_OFFSET 3 +#define CSR_RGB_CTRL_RRAW_SIZE 1 +#define CSR_RGB_CTRL_GRAW_OFFSET 4 +#define CSR_RGB_CTRL_GRAW_SIZE 1 +#define CSR_RGB_CTRL_BRAW_OFFSET 5 +#define CSR_RGB_CTRL_BRAW_SIZE 1 +#define CSR_RGB_RAW_ADDR 0xe000680cL +#define CSR_RGB_RAW_SIZE 1 +static inline unsigned char rgb_raw_read(void) { + unsigned char r = csr_readl(0xe000680cL); + return r; +} +static inline void rgb_raw_write(unsigned char value) { + csr_writel(value, 0xe000680cL); +} +#define CSR_RGB_RAW_R_OFFSET 0 +#define CSR_RGB_RAW_R_SIZE 1 +#define CSR_RGB_RAW_G_OFFSET 1 +#define CSR_RGB_RAW_G_SIZE 1 +#define CSR_RGB_RAW_B_OFFSET 2 +#define CSR_RGB_RAW_B_SIZE 1 + +/* timer0 */ +#define CSR_TIMER0_BASE 0xe0002800L +#define CSR_TIMER0_LOAD_ADDR 0xe0002800L +#define CSR_TIMER0_LOAD_SIZE 4 +static inline unsigned int timer0_load_read(void) { + unsigned int r = csr_readl(0xe0002800L); + r <<= 8; + r |= csr_readl(0xe0002804L); + r <<= 8; + r |= csr_readl(0xe0002808L); + r <<= 8; + r |= csr_readl(0xe000280cL); + return r; +} +static inline void timer0_load_write(unsigned int value) { + csr_writel(value >> 24, 0xe0002800L); + csr_writel(value >> 16, 0xe0002804L); + csr_writel(value >> 8, 0xe0002808L); + csr_writel(value, 0xe000280cL); +} +#define CSR_TIMER0_RELOAD_ADDR 0xe0002810L +#define CSR_TIMER0_RELOAD_SIZE 4 +static inline unsigned int timer0_reload_read(void) { + unsigned int r = csr_readl(0xe0002810L); + r <<= 8; + r |= csr_readl(0xe0002814L); + r <<= 8; + r |= csr_readl(0xe0002818L); + r <<= 8; + r |= csr_readl(0xe000281cL); + return r; +} +static inline void timer0_reload_write(unsigned int value) { + csr_writel(value >> 24, 0xe0002810L); + csr_writel(value >> 16, 0xe0002814L); + csr_writel(value >> 8, 0xe0002818L); + csr_writel(value, 0xe000281cL); +} +#define CSR_TIMER0_EN_ADDR 0xe0002820L +#define CSR_TIMER0_EN_SIZE 1 +static inline unsigned char timer0_en_read(void) { + unsigned char r = csr_readl(0xe0002820L); + return r; +} +static inline void timer0_en_write(unsigned char value) { + csr_writel(value, 0xe0002820L); +} +#define CSR_TIMER0_UPDATE_VALUE_ADDR 0xe0002824L +#define CSR_TIMER0_UPDATE_VALUE_SIZE 1 +static inline unsigned char timer0_update_value_read(void) { + unsigned char r = csr_readl(0xe0002824L); + return r; +} +static inline void timer0_update_value_write(unsigned char value) { + csr_writel(value, 0xe0002824L); +} +#define CSR_TIMER0_VALUE_ADDR 0xe0002828L +#define CSR_TIMER0_VALUE_SIZE 4 +static inline unsigned int timer0_value_read(void) { + unsigned int r = csr_readl(0xe0002828L); + r <<= 8; + r |= csr_readl(0xe000282cL); + r <<= 8; + r |= csr_readl(0xe0002830L); + r <<= 8; + r |= csr_readl(0xe0002834L); + return r; +} +#define CSR_TIMER0_EV_STATUS_ADDR 0xe0002838L +#define CSR_TIMER0_EV_STATUS_SIZE 1 +static inline unsigned char timer0_ev_status_read(void) { + unsigned char r = csr_readl(0xe0002838L); + return r; +} +static inline void timer0_ev_status_write(unsigned char value) { + csr_writel(value, 0xe0002838L); +} +#define CSR_TIMER0_EV_PENDING_ADDR 0xe000283cL +#define CSR_TIMER0_EV_PENDING_SIZE 1 +static inline unsigned char timer0_ev_pending_read(void) { + unsigned char r = csr_readl(0xe000283cL); + return r; +} +static inline void timer0_ev_pending_write(unsigned char value) { + csr_writel(value, 0xe000283cL); +} +#define CSR_TIMER0_EV_ENABLE_ADDR 0xe0002840L +#define CSR_TIMER0_EV_ENABLE_SIZE 1 +static inline unsigned char timer0_ev_enable_read(void) { + unsigned char r = csr_readl(0xe0002840L); + return r; +} +static inline void timer0_ev_enable_write(unsigned char value) { + csr_writel(value, 0xe0002840L); +} + +/* touch */ +#define CSR_TOUCH_BASE 0xe0005800L +#define CSR_TOUCH_O_ADDR 0xe0005800L +#define CSR_TOUCH_O_SIZE 1 +static inline unsigned char touch_o_read(void) { + unsigned char r = csr_readl(0xe0005800L); + return r; +} +static inline void touch_o_write(unsigned char value) { + csr_writel(value, 0xe0005800L); +} +#define CSR_TOUCH_O_O_OFFSET 0 +#define CSR_TOUCH_O_O_SIZE 4 +#define CSR_TOUCH_OE_ADDR 0xe0005804L +#define CSR_TOUCH_OE_SIZE 1 +static inline unsigned char touch_oe_read(void) { + unsigned char r = csr_readl(0xe0005804L); + return r; +} +static inline void touch_oe_write(unsigned char value) { + csr_writel(value, 0xe0005804L); +} +#define CSR_TOUCH_OE_OE_OFFSET 0 +#define CSR_TOUCH_OE_OE_SIZE 4 +#define CSR_TOUCH_I_ADDR 0xe0005808L +#define CSR_TOUCH_I_SIZE 1 +static inline unsigned char touch_i_read(void) { + unsigned char r = csr_readl(0xe0005808L); + return r; +} +#define CSR_TOUCH_I_I_OFFSET 0 +#define CSR_TOUCH_I_I_SIZE 4 + +/* usb */ +#define CSR_USB_BASE 0xe0004800L +#define CSR_USB_PULLUP_OUT_ADDR 0xe0004800L +#define CSR_USB_PULLUP_OUT_SIZE 1 +static inline unsigned char usb_pullup_out_read(void) { + unsigned char r = csr_readl(0xe0004800L); + return r; +} +static inline void usb_pullup_out_write(unsigned char value) { + csr_writel(value, 0xe0004800L); +} +#define CSR_USB_SETUP_DATA_ADDR 0xe0004804L +#define CSR_USB_SETUP_DATA_SIZE 1 +static inline unsigned char usb_setup_data_read(void) { + unsigned char r = csr_readl(0xe0004804L); + return r; +} +#define CSR_USB_SETUP_DATA_DATA_OFFSET 0 +#define CSR_USB_SETUP_DATA_DATA_SIZE 8 +#define CSR_USB_SETUP_CTRL_ADDR 0xe0004808L +#define CSR_USB_SETUP_CTRL_SIZE 1 +static inline unsigned char usb_setup_ctrl_read(void) { + unsigned char r = csr_readl(0xe0004808L); + return r; +} +static inline void usb_setup_ctrl_write(unsigned char value) { + csr_writel(value, 0xe0004808L); +} +#define CSR_USB_SETUP_CTRL_HANDLED_OFFSET 1 +#define CSR_USB_SETUP_CTRL_HANDLED_SIZE 1 +#define CSR_USB_SETUP_CTRL_RESET_OFFSET 2 +#define CSR_USB_SETUP_CTRL_RESET_SIZE 1 +#define CSR_USB_SETUP_STATUS_ADDR 0xe000480cL +#define CSR_USB_SETUP_STATUS_SIZE 1 +static inline unsigned char usb_setup_status_read(void) { + unsigned char r = csr_readl(0xe000480cL); + return r; +} +#define CSR_USB_SETUP_STATUS_HAVE_OFFSET 0 +#define CSR_USB_SETUP_STATUS_HAVE_SIZE 1 +#define CSR_USB_SETUP_STATUS_IS_IN_OFFSET 1 +#define CSR_USB_SETUP_STATUS_IS_IN_SIZE 1 +#define CSR_USB_SETUP_STATUS_EPNO_OFFSET 2 +#define CSR_USB_SETUP_STATUS_EPNO_SIZE 4 +#define CSR_USB_SETUP_STATUS_PEND_OFFSET 6 +#define CSR_USB_SETUP_STATUS_PEND_SIZE 1 +#define CSR_USB_SETUP_STATUS_DATA_OFFSET 7 +#define CSR_USB_SETUP_STATUS_DATA_SIZE 1 +#define CSR_USB_SETUP_EV_STATUS_ADDR 0xe0004810L +#define CSR_USB_SETUP_EV_STATUS_SIZE 1 +static inline unsigned char usb_setup_ev_status_read(void) { + unsigned char r = csr_readl(0xe0004810L); + return r; +} +static inline void usb_setup_ev_status_write(unsigned char value) { + csr_writel(value, 0xe0004810L); +} +#define CSR_USB_SETUP_EV_PENDING_ADDR 0xe0004814L +#define CSR_USB_SETUP_EV_PENDING_SIZE 1 +static inline unsigned char usb_setup_ev_pending_read(void) { + unsigned char r = csr_readl(0xe0004814L); + return r; +} +static inline void usb_setup_ev_pending_write(unsigned char value) { + csr_writel(value, 0xe0004814L); +} +#define CSR_USB_SETUP_EV_ENABLE_ADDR 0xe0004818L +#define CSR_USB_SETUP_EV_ENABLE_SIZE 1 +static inline unsigned char usb_setup_ev_enable_read(void) { + unsigned char r = csr_readl(0xe0004818L); + return r; +} +static inline void usb_setup_ev_enable_write(unsigned char value) { + csr_writel(value, 0xe0004818L); +} +#define CSR_USB_IN_DATA_ADDR 0xe000481cL +#define CSR_USB_IN_DATA_SIZE 1 +static inline unsigned char usb_in_data_read(void) { + unsigned char r = csr_readl(0xe000481cL); + return r; +} +static inline void usb_in_data_write(unsigned char value) { + csr_writel(value, 0xe000481cL); +} +#define CSR_USB_IN_DATA_DATA_OFFSET 0 +#define CSR_USB_IN_DATA_DATA_SIZE 8 +#define CSR_USB_IN_STATUS_ADDR 0xe0004820L +#define CSR_USB_IN_STATUS_SIZE 1 +static inline unsigned char usb_in_status_read(void) { + unsigned char r = csr_readl(0xe0004820L); + return r; +} +#define CSR_USB_IN_STATUS_HAVE_OFFSET 0 +#define CSR_USB_IN_STATUS_HAVE_SIZE 1 +#define CSR_USB_IN_STATUS_IDLE_OFFSET 1 +#define CSR_USB_IN_STATUS_IDLE_SIZE 1 +#define CSR_USB_IN_STATUS_PEND_OFFSET 6 +#define CSR_USB_IN_STATUS_PEND_SIZE 1 +#define CSR_USB_IN_CTRL_ADDR 0xe0004824L +#define CSR_USB_IN_CTRL_SIZE 1 +static inline unsigned char usb_in_ctrl_read(void) { + unsigned char r = csr_readl(0xe0004824L); + return r; +} +static inline void usb_in_ctrl_write(unsigned char value) { + csr_writel(value, 0xe0004824L); +} +#define CSR_USB_IN_CTRL_EP_OFFSET 0 +#define CSR_USB_IN_CTRL_EP_SIZE 4 +#define CSR_USB_IN_CTRL_STALL_OFFSET 4 +#define CSR_USB_IN_CTRL_STALL_SIZE 1 +#define CSR_USB_IN_CTRL_RESET_OFFSET 5 +#define CSR_USB_IN_CTRL_RESET_SIZE 1 +#define CSR_USB_IN_EV_STATUS_ADDR 0xe0004828L +#define CSR_USB_IN_EV_STATUS_SIZE 1 +static inline unsigned char usb_in_ev_status_read(void) { + unsigned char r = csr_readl(0xe0004828L); + return r; +} +static inline void usb_in_ev_status_write(unsigned char value) { + csr_writel(value, 0xe0004828L); +} +#define CSR_USB_IN_EV_PENDING_ADDR 0xe000482cL +#define CSR_USB_IN_EV_PENDING_SIZE 1 +static inline unsigned char usb_in_ev_pending_read(void) { + unsigned char r = csr_readl(0xe000482cL); + return r; +} +static inline void usb_in_ev_pending_write(unsigned char value) { + csr_writel(value, 0xe000482cL); +} +#define CSR_USB_IN_EV_ENABLE_ADDR 0xe0004830L +#define CSR_USB_IN_EV_ENABLE_SIZE 1 +static inline unsigned char usb_in_ev_enable_read(void) { + unsigned char r = csr_readl(0xe0004830L); + return r; +} +static inline void usb_in_ev_enable_write(unsigned char value) { + csr_writel(value, 0xe0004830L); +} +#define CSR_USB_OUT_DATA_ADDR 0xe0004834L +#define CSR_USB_OUT_DATA_SIZE 1 +static inline unsigned char usb_out_data_read(void) { + unsigned char r = csr_readl(0xe0004834L); + return r; +} +#define CSR_USB_OUT_DATA_DATA_OFFSET 0 +#define CSR_USB_OUT_DATA_DATA_SIZE 8 +#define CSR_USB_OUT_STATUS_ADDR 0xe0004838L +#define CSR_USB_OUT_STATUS_SIZE 1 +static inline unsigned char usb_out_status_read(void) { + unsigned char r = csr_readl(0xe0004838L); + return r; +} +#define CSR_USB_OUT_STATUS_HAVE_OFFSET 0 +#define CSR_USB_OUT_STATUS_HAVE_SIZE 1 +#define CSR_USB_OUT_STATUS_IDLE_OFFSET 1 +#define CSR_USB_OUT_STATUS_IDLE_SIZE 1 +#define CSR_USB_OUT_STATUS_EPNO_OFFSET 2 +#define CSR_USB_OUT_STATUS_EPNO_SIZE 4 +#define CSR_USB_OUT_STATUS_PEND_OFFSET 6 +#define CSR_USB_OUT_STATUS_PEND_SIZE 1 +#define CSR_USB_OUT_CTRL_ADDR 0xe000483cL +#define CSR_USB_OUT_CTRL_SIZE 1 +static inline unsigned char usb_out_ctrl_read(void) { + unsigned char r = csr_readl(0xe000483cL); + return r; +} +static inline void usb_out_ctrl_write(unsigned char value) { + csr_writel(value, 0xe000483cL); +} +#define CSR_USB_OUT_CTRL_ENABLE_OFFSET 1 +#define CSR_USB_OUT_CTRL_ENABLE_SIZE 1 +#define CSR_USB_OUT_CTRL_RESET_OFFSET 2 +#define CSR_USB_OUT_CTRL_RESET_SIZE 1 +#define CSR_USB_OUT_STALL_ADDR 0xe0004840L +#define CSR_USB_OUT_STALL_SIZE 1 +static inline unsigned char usb_out_stall_read(void) { + unsigned char r = csr_readl(0xe0004840L); + return r; +} +static inline void usb_out_stall_write(unsigned char value) { + csr_writel(value, 0xe0004840L); +} +#define CSR_USB_OUT_STALL_EPNO_OFFSET 0 +#define CSR_USB_OUT_STALL_EPNO_SIZE 4 +#define CSR_USB_OUT_STALL_STALL_OFFSET 4 +#define CSR_USB_OUT_STALL_STALL_SIZE 1 +#define CSR_USB_OUT_EV_STATUS_ADDR 0xe0004844L +#define CSR_USB_OUT_EV_STATUS_SIZE 1 +static inline unsigned char usb_out_ev_status_read(void) { + unsigned char r = csr_readl(0xe0004844L); + return r; +} +static inline void usb_out_ev_status_write(unsigned char value) { + csr_writel(value, 0xe0004844L); +} +#define CSR_USB_OUT_EV_PENDING_ADDR 0xe0004848L +#define CSR_USB_OUT_EV_PENDING_SIZE 1 +static inline unsigned char usb_out_ev_pending_read(void) { + unsigned char r = csr_readl(0xe0004848L); + return r; +} +static inline void usb_out_ev_pending_write(unsigned char value) { + csr_writel(value, 0xe0004848L); +} +#define CSR_USB_OUT_EV_ENABLE_ADDR 0xe000484cL +#define CSR_USB_OUT_EV_ENABLE_SIZE 1 +static inline unsigned char usb_out_ev_enable_read(void) { + unsigned char r = csr_readl(0xe000484cL); + return r; +} +static inline void usb_out_ev_enable_write(unsigned char value) { + csr_writel(value, 0xe000484cL); +} +#define CSR_USB_ADDRESS_ADDR 0xe0004850L +#define CSR_USB_ADDRESS_SIZE 1 +static inline unsigned char usb_address_read(void) { + unsigned char r = csr_readl(0xe0004850L); + return r; +} +static inline void usb_address_write(unsigned char value) { + csr_writel(value, 0xe0004850L); +} +#define CSR_USB_ADDRESS_ADDR_OFFSET 0 +#define CSR_USB_ADDRESS_ADDR_SIZE 7 +#define CSR_USB_STAGE_NUM_ADDR 0xe0004854L +#define CSR_USB_STAGE_NUM_SIZE 1 +static inline unsigned char usb_stage_num_read(void) { + unsigned char r = csr_readl(0xe0004854L); + return r; +} +#define CSR_USB_LAST_STAGE_NUM_ADDR 0xe0004858L +#define CSR_USB_LAST_STAGE_NUM_SIZE 1 +static inline unsigned char usb_last_stage_num_read(void) { + unsigned char r = csr_readl(0xe0004858L); + return r; +} + +/* version */ +#define CSR_VERSION_BASE 0xe0007000L +#define CSR_VERSION_MAJOR_ADDR 0xe0007000L +#define CSR_VERSION_MAJOR_SIZE 1 +static inline unsigned char version_major_read(void) { + unsigned char r = csr_readl(0xe0007000L); + return r; +} +#define CSR_VERSION_MINOR_ADDR 0xe0007004L +#define CSR_VERSION_MINOR_SIZE 1 +static inline unsigned char version_minor_read(void) { + unsigned char r = csr_readl(0xe0007004L); + return r; +} +#define CSR_VERSION_REVISION_ADDR 0xe0007008L +#define CSR_VERSION_REVISION_SIZE 1 +static inline unsigned char version_revision_read(void) { + unsigned char r = csr_readl(0xe0007008L); + return r; +} +#define CSR_VERSION_GITREV_ADDR 0xe000700cL +#define CSR_VERSION_GITREV_SIZE 4 +static inline unsigned int version_gitrev_read(void) { + unsigned int r = csr_readl(0xe000700cL); + r <<= 8; + r |= csr_readl(0xe0007010L); + r <<= 8; + r |= csr_readl(0xe0007014L); + r <<= 8; + r |= csr_readl(0xe0007018L); + return r; +} +#define CSR_VERSION_GITEXTRA_ADDR 0xe000701cL +#define CSR_VERSION_GITEXTRA_SIZE 2 +static inline unsigned short int version_gitextra_read(void) { + unsigned short int r = csr_readl(0xe000701cL); + r <<= 8; + r |= csr_readl(0xe0007020L); + return r; +} +#define CSR_VERSION_DIRTY_ADDR 0xe0007024L +#define CSR_VERSION_DIRTY_SIZE 1 +static inline unsigned char version_dirty_read(void) { + unsigned char r = csr_readl(0xe0007024L); + return r; +} +#define CSR_VERSION_DIRTY_DIRTY_OFFSET 0 +#define CSR_VERSION_DIRTY_DIRTY_SIZE 1 +#define CSR_VERSION_MODEL_ADDR 0xe0007028L +#define CSR_VERSION_MODEL_SIZE 1 +static inline unsigned char version_model_read(void) { + unsigned char r = csr_readl(0xe0007028L); + return r; +} +#define CSR_VERSION_MODEL_MODEL_OFFSET 0 +#define CSR_VERSION_MODEL_MODEL_SIZE 8 +#define CSR_VERSION_SEED_ADDR 0xe000702cL +#define CSR_VERSION_SEED_SIZE 4 +static inline unsigned int version_seed_read(void) { + unsigned int r = csr_readl(0xe000702cL); + r <<= 8; + r |= csr_readl(0xe0007030L); + r <<= 8; + r |= csr_readl(0xe0007034L); + r <<= 8; + r |= csr_readl(0xe0007038L); + return r; +} + +/* constants */ +#define TIMER0_INTERRUPT 2 +static inline int timer0_interrupt_read(void) { + return 2; +} +#define USB_INTERRUPT 3 +static inline int usb_interrupt_read(void) { + return 3; +} +#define SPI_BOOT 1 +static inline int spi_boot_read(void) { + return 1; +} +#define SPI_ENTRYPOINT 536977408 +static inline int spi_entrypoint_read(void) { + return 536977408; +} +#define CONFIG_BITSTREAM_SYNC_HEADER1 2123999870 +static inline int config_bitstream_sync_header1_read(void) { + return 2123999870; +} +#define CONFIG_BITSTREAM_SYNC_HEADER2 2125109630 +static inline int config_bitstream_sync_header2_read(void) { + return 2125109630; +} +#define CONFIG_CLOCK_FREQUENCY 12000000 +static inline int config_clock_frequency_read(void) { + return 12000000; +} +#define CONFIG_CPU_RESET_ADDR 0 +static inline int config_cpu_reset_addr_read(void) { + return 0; +} +#define CONFIG_CPU_TYPE "VEXRISCV" +static inline const char * config_cpu_type_read(void) { + return "VEXRISCV"; +} +#define CONFIG_CPU_TYPE_VEXRISCV 1 +static inline int config_cpu_type_vexriscv_read(void) { + return 1; +} +#define CONFIG_CPU_VARIANT "MIN" +static inline const char * config_cpu_variant_read(void) { + return "MIN"; +} +#define CONFIG_CPU_VARIANT_MIN 1 +static inline int config_cpu_variant_min_read(void) { + return 1; +} +#define CONFIG_CSR_ALIGNMENT 32 +static inline int config_csr_alignment_read(void) { + return 32; +} +#define CONFIG_CSR_DATA_WIDTH 8 +static inline int config_csr_data_width_read(void) { + return 8; +} + +#endif diff --git a/hw/bsp/fomu/include/hw/common.h b/hw/bsp/fomu/include/hw/common.h new file mode 100644 index 00000000..6a97ca2e --- /dev/null +++ b/hw/bsp/fomu/include/hw/common.h @@ -0,0 +1,33 @@ +#ifndef _HW_COMMON_H_ +#define _HW_COMMON_H_ +#include +static inline void csr_writeb(uint8_t value, uint32_t addr) +{ + *((volatile uint8_t *)addr) = value; +} + +static inline uint8_t csr_readb(uint32_t addr) +{ + return *(volatile uint8_t *)addr; +} + +static inline void csr_writew(uint16_t value, uint32_t addr) +{ + *((volatile uint16_t *)addr) = value; +} + +static inline uint16_t csr_readw(uint32_t addr) +{ + return *(volatile uint16_t *)addr; +} + +static inline void csr_writel(uint32_t value, uint32_t addr) +{ + *((volatile uint32_t *)addr) = value; +} + +static inline uint32_t csr_readl(uint32_t addr) +{ + return *(volatile uint32_t *)addr; +} +#endif /* _HW_COMMON_H_ */ \ No newline at end of file diff --git a/hw/bsp/fomu/include/irq.h b/hw/bsp/fomu/include/irq.h new file mode 100644 index 00000000..a8221890 --- /dev/null +++ b/hw/bsp/fomu/include/irq.h @@ -0,0 +1,71 @@ +#ifndef __IRQ_H +#define __IRQ_H + +#ifdef __cplusplus +extern "C" { +#endif + + +#define CSR_MSTATUS_MIE 0x8 + +#define CSR_IRQ_MASK 0xBC0 +#define CSR_IRQ_PENDING 0xFC0 + +#define CSR_DCACHE_INFO 0xCC0 + +#define csrr(reg) ({ unsigned long __tmp; \ + asm volatile ("csrr %0, " #reg : "=r"(__tmp)); \ + __tmp; }) + +#define csrw(reg, val) ({ \ + if (__builtin_constant_p(val) && (unsigned long)(val) < 32) \ + asm volatile ("csrw " #reg ", %0" :: "i"(val)); \ + else \ + asm volatile ("csrw " #reg ", %0" :: "r"(val)); }) + +#define csrs(reg, bit) ({ \ + if (__builtin_constant_p(bit) && (unsigned long)(bit) < 32) \ + asm volatile ("csrrs x0, " #reg ", %0" :: "i"(bit)); \ + else \ + asm volatile ("csrrs x0, " #reg ", %0" :: "r"(bit)); }) + +#define csrc(reg, bit) ({ \ + if (__builtin_constant_p(bit) && (unsigned long)(bit) < 32) \ + asm volatile ("csrrc x0, " #reg ", %0" :: "i"(bit)); \ + else \ + asm volatile ("csrrc x0, " #reg ", %0" :: "r"(bit)); }) + +static inline unsigned int irq_getie(void) +{ + return (csrr(mstatus) & CSR_MSTATUS_MIE) != 0; +} + +static inline void irq_setie(unsigned int ie) +{ + if(ie) csrs(mstatus,CSR_MSTATUS_MIE); else csrc(mstatus,CSR_MSTATUS_MIE); +} + +static inline unsigned int irq_getmask(void) +{ + unsigned int mask; + asm volatile ("csrr %0, %1" : "=r"(mask) : "i"(CSR_IRQ_MASK)); + return mask; +} + +static inline void irq_setmask(unsigned int mask) +{ + asm volatile ("csrw %0, %1" :: "i"(CSR_IRQ_MASK), "r"(mask)); +} + +static inline unsigned int irq_pending(void) +{ + unsigned int pending; + asm volatile ("csrr %0, %1" : "=r"(pending) : "i"(CSR_IRQ_PENDING)); + return pending; +} + +#ifdef __cplusplus +} +#endif + +#endif /* __IRQ_H */ \ No newline at end of file diff --git a/hw/bsp/fomu/output_format.ld b/hw/bsp/fomu/output_format.ld new file mode 100644 index 00000000..5e76f5f4 --- /dev/null +++ b/hw/bsp/fomu/output_format.ld @@ -0,0 +1 @@ +OUTPUT_FORMAT("elf32-littleriscv") diff --git a/hw/bsp/fomu/regions.ld b/hw/bsp/fomu/regions.ld new file mode 100644 index 00000000..51811f66 --- /dev/null +++ b/hw/bsp/fomu/regions.ld @@ -0,0 +1,6 @@ +MEMORY { + csr : ORIGIN = 0x60000000, LENGTH = 0x01000000 + vexriscv_debug : ORIGIN = 0xf00f0000, LENGTH = 0x00000100 + sram : ORIGIN = 0x10000000, LENGTH = 0x00020000 + rom : ORIGIN = 0x00000000, LENGTH = 0x00002000 +} From 36ede44885365faa230b63867e8392addd48e7b3 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Sat, 12 Oct 2019 10:25:10 +0800 Subject: [PATCH 029/267] fomu: wip support Signed-off-by: Sean Cross --- src/portable/foosn/fomu/dcd_fomu.c | 335 +++++++++++++++++++++++++++++ src/portable/foosn/fomu/dcd_fomu.h | 151 +++++++++++++ src/portable/foosn/fomu/hal_fomu.c | 33 +++ 3 files changed, 519 insertions(+) create mode 100644 src/portable/foosn/fomu/dcd_fomu.c create mode 100644 src/portable/foosn/fomu/dcd_fomu.h create mode 100644 src/portable/foosn/fomu/hal_fomu.c diff --git a/src/portable/foosn/fomu/dcd_fomu.c b/src/portable/foosn/fomu/dcd_fomu.c new file mode 100644 index 00000000..d7f9d3d1 --- /dev/null +++ b/src/portable/foosn/fomu/dcd_fomu.c @@ -0,0 +1,335 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#include "tusb_option.h" + +// #if TUSB_OPT_DEVICE_ENABLED && (CFG_TUSB_MCU == OPT_MCU_FOMU_EPTRI) +#if 1 + +#include "device/dcd.h" +#include "dcd_fomu.h" +#include "csr.h" +#include "irq.h" +void fomu_error(uint32_t line); +void mputs(const char *str); +void mputln(const char *str); + +//--------------------------------------------------------------------+ +// SIE Command +//--------------------------------------------------------------------+ + +static uint8_t volatile out_buffer_length[16]; +static uint8_t volatile * out_buffer[16]; +static uint8_t volatile out_buffer_max[16]; + +static volatile bool tx_in_progress; +static volatile uint8_t tx_ep; +static volatile uint16_t tx_len; + +//--------------------------------------------------------------------+ +// PIPE HELPER +//--------------------------------------------------------------------+ + +static void finish_tx(void) { + // // Don't allow requeueing -- only queue more data if the system is idle. + // if (!(usb_in_status_read() & 2)) { + // return; + // } + + // Don't send empty data + if (!tx_in_progress) { + return; + } + + tx_in_progress = 0; + dcd_event_xfer_complete(0, tx_ep, tx_len, XFER_RESULT_SUCCESS, true); + return; +} + +static void process_rx(bool in_isr) { + // If there isn't any data in the FIFO, don't do anything. + if (!(usb_out_status_read() & 1)) + return; + + uint8_t out_ep = (usb_out_status_read() >> 2) & 0xf; + uint32_t total_read = 0; + uint32_t current_offset = out_buffer_length[out_ep]; + while (usb_out_status_read() & 1) { + uint8_t c = usb_out_data_read(); + total_read++; + if (out_buffer_length[out_ep] < out_buffer_max[out_ep]) + out_buffer[out_ep][current_offset++] = c; + } + + // Strip off the CRC16 + total_read -= 2; + out_buffer_length[out_ep] += total_read; + if (out_buffer_length[out_ep] > out_buffer_max[out_ep]) + out_buffer_length[out_ep] = out_buffer_max[out_ep]; + + if (out_buffer_max[out_ep] == out_buffer_length[out_ep]) { + out_buffer[out_ep] = NULL; + dcd_event_xfer_complete(0, tu_edpt_addr(out_ep, TUSB_DIR_OUT), out_buffer_length[out_ep], XFER_RESULT_SUCCESS, in_isr); + } + + // Acknowledge having received the data + usb_out_ctrl_write(2); +} + +//--------------------------------------------------------------------+ +// CONTROLLER API +//--------------------------------------------------------------------+ + +// Initializes the USB peripheral for device mode and enables it. +void dcd_init(uint8_t rhport) +{ + (void) rhport; + + usb_pullup_out_write(0); + usb_address_write(0); + usb_out_ctrl_write(0); + + usb_setup_ev_enable_write(0); + usb_in_ev_enable_write(0); + usb_out_ev_enable_write(0); + + // Reset the IN handler + usb_in_ctrl_write(0x20); + + // Reset the SETUP handler + usb_setup_ctrl_write(0x04); + + // Reset the OUT handler + usb_out_ctrl_write(0x04); + + // Enable all event handlers and clear their contents + usb_setup_ev_pending_write(usb_setup_ev_pending_read()); + usb_in_ev_pending_write(usb_in_ev_pending_read()); + usb_out_ev_pending_write(usb_out_ev_pending_read()); + usb_setup_ev_enable_write(3); + usb_in_ev_enable_write(1); + usb_out_ev_enable_write(1); + + // Accept incoming data by default. + usb_out_ctrl_write(2); + + // Turn on the external pullup + usb_pullup_out_write(1); + + dcd_event_bus_signal(0, DCD_EVENT_BUS_RESET, false); +} + +// Enables or disables the USB device interrupt(s). May be used to +// prevent concurrency issues when mutating data structures shared +// between main code and the interrupt handler. +void dcd_int_enable(uint8_t rhport) +{ + (void) rhport; + irq_setmask(irq_getmask() | (1 << USB_INTERRUPT)); +} + +void dcd_int_disable(uint8_t rhport) +{ + (void) rhport; + irq_setmask(irq_getmask() & ~(1 << USB_INTERRUPT)); +} + +// Called when the device is given a new bus address. +void dcd_set_address(uint8_t rhport, uint8_t dev_addr) +{ + (void)rhport; + // Set address and then acknowledge the SETUP packet + usb_address_write(dev_addr); + + // ACK the transfer (sets the address) + usb_setup_ctrl_write(2); +} + +// Called when the device received SET_CONFIG request, you can leave this +// empty if your peripheral does not require any specific action. +void dcd_set_config(uint8_t rhport, uint8_t config_num) +{ + (void) rhport; + (void) config_num; +} + +// Called to remote wake up host when suspended (e.g hid keyboard) +void dcd_remote_wakeup(uint8_t rhport) +{ + (void) rhport; +} + +//--------------------------------------------------------------------+ +// DCD Endpoint Port +//--------------------------------------------------------------------+ +bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc) +{ + (void) rhport; + + if (p_endpoint_desc->bmAttributes.xfer == TUSB_XFER_ISOCHRONOUS) + return false; // Not supported + + return true; +} + +void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + if (tu_edpt_dir(ep_addr) == TUSB_DIR_OUT) + usb_out_stall_write((1 << CSR_USB_OUT_STALL_STALL_OFFSET) | tu_edpt_number(ep_addr)); + else { + usb_in_ctrl_write((1 << CSR_USB_IN_CTRL_STALL_OFFSET) | tu_edpt_number(ep_addr)); + } +} + +void dcd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + if (tu_edpt_dir(ep_addr) == TUSB_DIR_OUT) + usb_out_stall_write((0 << CSR_USB_OUT_STALL_STALL_OFFSET) | tu_edpt_number(ep_addr)); + // IN endpoints will get unstalled when more data is written. +} + +__attribute__((used)) +uint8_t *last_tx_buffer; +__attribute__((used)) +uint16_t last_tx_bytes; + +bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t* buffer, uint16_t total_bytes) +{ + (void)rhport; + + if (tu_edpt_dir(ep_addr) == TUSB_DIR_IN) { + // These sorts of transfers are handled in hardware + if ((tu_edpt_number(ep_addr) == 0) && (total_bytes == 0) && (buffer == 0)) { + dcd_event_xfer_complete(0, ep_addr, total_bytes, XFER_RESULT_SUCCESS, false); + return true; + } + uint32_t offset; + // Wait for the tx pipe to free up + while (tx_in_progress) + ; + tx_in_progress = 1; + tx_ep = ep_addr; + tx_len = total_bytes; + + for (offset = 0; offset < total_bytes; offset++) { + usb_in_data_write(buffer[offset]); + } + // Updating the epno queues the data + usb_in_ctrl_write(tu_edpt_number(ep_addr) & 0xf); + last_tx_buffer = buffer; + last_tx_bytes = total_bytes; + } + else if (tu_edpt_dir(ep_addr) == TUSB_DIR_OUT) { + + // Wait for the rx pipe to free up + while (out_buffer[tu_edpt_number(ep_addr)]) + ; + out_buffer_max[tu_edpt_number(ep_addr)] = total_bytes; + out_buffer[tu_edpt_number(ep_addr)] = buffer; + out_buffer_length[tu_edpt_number(ep_addr)] = 0; + process_rx(false); + } + return true; +} + +//--------------------------------------------------------------------+ +// ISR +//--------------------------------------------------------------------+ + +void hal_dcd_isr(uint8_t rhport) +{ + uint8_t setup_pending = usb_setup_ev_pending_read(); + uint8_t in_pending = usb_in_ev_pending_read(); + uint8_t out_pending = usb_out_ev_pending_read(); + usb_setup_ev_pending_write(setup_pending); + usb_in_ev_pending_write(in_pending); + usb_out_ev_pending_write(out_pending); + + // This event means a bus reset occurred. Reset everything, and + // abandon any further processing. + if (setup_pending & 2) { + usb_setup_ctrl_write(1 << CSR_USB_SETUP_CTRL_RESET_OFFSET); + usb_in_ctrl_write(1 << CSR_USB_IN_CTRL_RESET_OFFSET); + usb_out_ctrl_write(1 << CSR_USB_OUT_CTRL_RESET_OFFSET); + + dcd_event_bus_signal(0, DCD_EVENT_BUS_RESET, true); + return; + } + + // An "IN" transaction just completed. + // Note that due to the way tinyusb's callback system is implemented, + // we must handle IN and OUT packets before we handle SETUP packets. + // This ensures that any responses to SETUP packets aren't overwritten. + // For example, oftentimes a host will request part of a descriptor + // to begin with, then make a subsequent request. If we don't handle + // the IN packets first, then the second request will be truncated. + if (in_pending) { + finish_tx(); + } + + // An "OUT" transaction just completed so we have new data. + // (But only if we can accept the data) + if (out_pending) { + process_rx(true); + } + + // We got a SETUP packet. Copy it to the setup buffer and clear + // the "pending" bit. + if (setup_pending & 1) { + // Setup packets are always 8 bytes, plus two bytes + // of crc16 + uint8_t setup_packet[10]; + uint32_t setup_length = 0; + + if (!(usb_setup_status_read() & 1)) + fomu_error(__LINE__); + + while (usb_setup_status_read() & 1) { + uint8_t c = usb_setup_data_read(); + if (setup_length < sizeof(setup_packet)) + setup_packet[setup_length] = c; + setup_length++; + } + + // If we have 10 bytes, that's a full SETUP packet plus CRC16. + // Otherwise, it was an RX error. + if (setup_length == 10) { + dcd_event_setup_received(rhport, setup_packet, true); + // Acknowledge the packet, so long as it isn't a SET_ADDRESS + // packet. If it is, leave it unacknowledged and we'll do this + // in the `dcd_set_address` function instead. + if (!((setup_packet[0] == 0x00) && (setup_packet[1] == 0x05))) + usb_setup_ctrl_write(2); + } + else { + fomu_error(__LINE__); + } + } +} + +#endif diff --git a/src/portable/foosn/fomu/dcd_fomu.h b/src/portable/foosn/fomu/dcd_fomu.h new file mode 100644 index 00000000..60bc1240 --- /dev/null +++ b/src/portable/foosn/fomu/dcd_fomu.h @@ -0,0 +1,151 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#ifndef _TUSB_DCD_FOMU_H_ +#define _TUSB_DCD_FOMU_H_ + +#include "common/tusb_common.h" +#ifdef __cplusplus + extern "C" { +#endif + +// //--------------------------------------------------------------------+ +// // Register Interface +// //--------------------------------------------------------------------+ + +// //------------- USB Interrupt USBIntSt -------------// +// //enum { +// // DCD_USB_REQ_LOW_PRIO_MASK = TU_BIT(0), +// // DCD_USB_REQ_HIGH_PRIO_MASK = TU_BIT(1), +// // DCD_USB_REQ_DMA_MASK = TU_BIT(2), +// // DCD_USB_REQ_NEED_CLOCK_MASK = TU_BIT(8), +// // DCD_USB_REQ_ENABLE_MASK = TU_BIT(31) +// //}; + +// //------------- Device Interrupt USBDevInt -------------// +// enum { +// DEV_INT_FRAME_MASK = TU_BIT(0), +// DEV_INT_ENDPOINT_FAST_MASK = TU_BIT(1), +// DEV_INT_ENDPOINT_SLOW_MASK = TU_BIT(2), +// DEV_INT_DEVICE_STATUS_MASK = TU_BIT(3), +// DEV_INT_COMMAND_CODE_EMPTY_MASK = TU_BIT(4), +// DEV_INT_COMMAND_DATA_FULL_MASK = TU_BIT(5), +// DEV_INT_RX_ENDPOINT_PACKET_MASK = TU_BIT(6), +// DEV_INT_TX_ENDPOINT_PACKET_MASK = TU_BIT(7), +// DEV_INT_ENDPOINT_REALIZED_MASK = TU_BIT(8), +// DEV_INT_ERROR_MASK = TU_BIT(9) +// }; + +// //------------- DMA Interrupt USBDMAInt-------------// +// enum { +// DMA_INT_END_OF_XFER_MASK = TU_BIT(0), +// DMA_INT_NEW_DD_REQUEST_MASK = TU_BIT(1), +// DMA_INT_ERROR_MASK = TU_BIT(2) +// }; + +// //------------- USBCtrl -------------// +// enum { +// USBCTRL_READ_ENABLE_MASK = TU_BIT(0), +// USBCTRL_WRITE_ENABLE_MASK = TU_BIT(1), +// }; + +// //------------- USBRxPLen -------------// +// enum { +// USBRXPLEN_PACKET_LENGTH_MASK = (TU_BIT(10)-1), +// USBRXPLEN_DATA_VALID_MASK = TU_BIT(10), +// USBRXPLEN_PACKET_READY_MASK = TU_BIT(11), +// }; + +// //------------- SIE Command Code -------------// +// typedef enum +// { +// SIE_CMDPHASE_WRITE = 1, +// SIE_CMDPHASE_READ = 2, +// SIE_CMDPHASE_COMMAND = 5 +// } sie_cmdphase_t; + +// enum { +// // device commands +// SIE_CMDCODE_SET_ADDRESS = 0xd0, +// SIE_CMDCODE_CONFIGURE_DEVICE = 0xd8, +// SIE_CMDCODE_SET_MODE = 0xf3, +// SIE_CMDCODE_READ_FRAME_NUMBER = 0xf5, +// SIE_CMDCODE_READ_TEST_REGISTER = 0xfd, +// SIE_CMDCODE_DEVICE_STATUS = 0xfe, +// SIE_CMDCODE_GET_ERROR = 0xff, +// SIE_CMDCODE_READ_ERROR_STATUS = 0xfb, + +// // endpoint commands +// SIE_CMDCODE_ENDPOINT_SELECT = 0x00, // + endpoint index +// SIE_CMDCODE_ENDPOINT_SELECT_CLEAR_INTERRUPT = 0x40, // + endpoint index, should use USBEpIntClr instead +// SIE_CMDCODE_ENDPOINT_SET_STATUS = 0x40, // + endpoint index +// SIE_CMDCODE_BUFFER_CLEAR = 0xf2, +// SIE_CMDCODE_BUFFER_VALIDATE = 0xfa +// }; + +// //------------- SIE Device Status (get/set from SIE_CMDCODE_DEVICE_STATUS) -------------// +// enum { +// SIE_DEV_STATUS_CONNECT_STATUS_MASK = TU_BIT(0), +// SIE_DEV_STATUS_CONNECT_CHANGE_MASK = TU_BIT(1), +// SIE_DEV_STATUS_SUSPEND_MASK = TU_BIT(2), +// SIE_DEV_STATUS_SUSPEND_CHANGE_MASK = TU_BIT(3), +// SIE_DEV_STATUS_RESET_MASK = TU_BIT(4) +// }; + +// //------------- SIE Select Endpoint Command -------------// +// enum { +// SIE_SELECT_ENDPOINT_FULL_EMPTY_MASK = TU_BIT(0), // 0: empty, 1 full. IN endpoint checks empty, OUT endpoint check full +// SIE_SELECT_ENDPOINT_STALL_MASK = TU_BIT(1), +// SIE_SELECT_ENDPOINT_SETUP_RECEIVED_MASK = TU_BIT(2), // clear by SIE_CMDCODE_ENDPOINT_SELECT_CLEAR_INTERRUPT +// SIE_SELECT_ENDPOINT_PACKET_OVERWRITTEN_MASK = TU_BIT(3), // previous packet is overwritten by a SETUP packet +// SIE_SELECT_ENDPOINT_NAK_MASK = TU_BIT(4), // last packet response is NAK (auto clear by an ACK) +// SIE_SELECT_ENDPOINT_BUFFER1_FULL_MASK = TU_BIT(5), +// SIE_SELECT_ENDPOINT_BUFFER2_FULL_MASK = TU_BIT(6) +// }; + +// typedef enum +// { +// SIE_SET_ENDPOINT_STALLED_MASK = TU_BIT(0), +// SIE_SET_ENDPOINT_DISABLED_MASK = TU_BIT(5), +// SIE_SET_ENDPOINT_RATE_FEEDBACK_MASK = TU_BIT(6), +// SIE_SET_ENDPOINT_CONDITION_STALLED_MASK = TU_BIT(7), +// }sie_endpoint_set_status_mask_t; + +// //------------- DMA Descriptor Status -------------// +// enum { +// DD_STATUS_NOT_SERVICED = 0, +// DD_STATUS_BEING_SERVICED, +// DD_STATUS_NORMAL, +// DD_STATUS_DATA_UNDERUN, // short packet +// DD_STATUS_DATA_OVERRUN, +// DD_STATUS_SYSTEM_ERROR +// }; + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_DCD_FOMU_H_ */ diff --git a/src/portable/foosn/fomu/hal_fomu.c b/src/portable/foosn/fomu/hal_fomu.c new file mode 100644 index 00000000..ebc0a1d9 --- /dev/null +++ b/src/portable/foosn/fomu/hal_fomu.c @@ -0,0 +1,33 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#include "common/tusb_common.h" + +#if (CFG_TUSB_MCU == OPT_MCU_FOMU_EPTRI) + +// No HAL-specific stuff here! + +#endif From ba889eeb9e99500736a1aec38f38645a335bd5a1 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Sat, 12 Oct 2019 14:51:40 +0800 Subject: [PATCH 030/267] bsp: fomu: fix linker script overlap The end of the data section was overlapping the start of the bss. Signed-off-by: Sean Cross --- hw/bsp/fomu/fomu.ld | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/hw/bsp/fomu/fomu.ld b/hw/bsp/fomu/fomu.ld index f39d62f3..2a3f2376 100644 --- a/hw/bsp/fomu/fomu.ld +++ b/hw/bsp/fomu/fomu.ld @@ -27,6 +27,7 @@ SECTIONS *(.rodata .rodata.* .gnu.linkonce.r.*) *(.rodata1) *(.srodata) + . = ALIGN(4); _erodata = .; } > rom @@ -38,12 +39,12 @@ SECTIONS *(.data1) _gp = ALIGN(16); *(.sdata .sdata.* .gnu.linkonce.s.* .sdata2 .sdata2.*) - _edata = ALIGN(16); /* Make sure _edata is >= _gp. */ + . = ALIGN(16); + _edata = .; /* Make sure _edata is >= _gp. */ } > sram .bss : { - . = ALIGN(4); _fbss = .; *(.dynsbss) *(.sbss .sbss.* .gnu.linkonce.sb.*) From 32bb68409ea904af52f6044dd9448ed62226da25 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Sat, 12 Oct 2019 14:52:15 +0800 Subject: [PATCH 031/267] portable: fomu: get msc to enumerate Signed-off-by: Sean Cross --- src/portable/foosn/fomu/dcd_fomu.c | 158 +++++++++++++++++------------ 1 file changed, 94 insertions(+), 64 deletions(-) diff --git a/src/portable/foosn/fomu/dcd_fomu.c b/src/portable/foosn/fomu/dcd_fomu.c index d7f9d3d1..f49e9e50 100644 --- a/src/portable/foosn/fomu/dcd_fomu.c +++ b/src/portable/foosn/fomu/dcd_fomu.c @@ -41,105 +41,130 @@ void mputln(const char *str); // SIE Command //--------------------------------------------------------------------+ -static uint8_t volatile out_buffer_length[16]; -static uint8_t volatile * out_buffer[16]; -static uint8_t volatile out_buffer_max[16]; +#define EP_SIZE 64 + +static uint16_t volatile rx_buffer_length[16]; +static uint8_t volatile * rx_buffer[16]; +static uint16_t volatile rx_buffer_max[16]; static volatile bool tx_in_progress; static volatile uint8_t tx_ep; static volatile uint16_t tx_len; +static uint8_t volatile * tx_buffer; +static volatile uint16_t tx_offset; //--------------------------------------------------------------------+ // PIPE HELPER //--------------------------------------------------------------------+ static void finish_tx(void) { - // // Don't allow requeueing -- only queue more data if the system is idle. - // if (!(usb_in_status_read() & 2)) { - // return; - // } - - // Don't send empty data - if (!tx_in_progress) { - return; - } + // Don't send empty data + if (!tx_in_progress) { + return; + } + tx_offset += EP_SIZE; + if (tx_offset >= tx_len) { tx_in_progress = 0; + tx_buffer = NULL; dcd_event_xfer_complete(0, tx_ep, tx_len, XFER_RESULT_SUCCESS, true); return; + } + + // Send more data + uint8_t added_bytes; + for (added_bytes = 0; (added_bytes < EP_SIZE) && (added_bytes + tx_offset < tx_len); added_bytes++) { + usb_in_data_write(tx_buffer[added_bytes + tx_offset]); + } + + // Updating the epno queues the data + usb_in_ctrl_write(tu_edpt_number(tx_ep) & 0xf); + return; } static void process_rx(bool in_isr) { // If there isn't any data in the FIFO, don't do anything. - if (!(usb_out_status_read() & 1)) - return; + if (!(usb_out_status_read() & (1 << CSR_USB_OUT_STATUS_HAVE_OFFSET))) + return; + + uint8_t out_ep = (usb_out_status_read() >> CSR_USB_OUT_STATUS_EPNO_OFFSET) & 0xf; + + // If the destination buffer doesn't exist, don't drain the hardware + // fifo. Note that this can cause deadlocks if the host is waiting + // on some other endpoint's data! + if (rx_buffer[out_ep] == NULL) + return; - uint8_t out_ep = (usb_out_status_read() >> 2) & 0xf; uint32_t total_read = 0; - uint32_t current_offset = out_buffer_length[out_ep]; - while (usb_out_status_read() & 1) { + uint32_t current_offset = rx_buffer_length[out_ep]; + while (usb_out_status_read() & (1 << CSR_USB_OUT_STATUS_HAVE_OFFSET)) { uint8_t c = usb_out_data_read(); total_read++; - if (out_buffer_length[out_ep] < out_buffer_max[out_ep]) - out_buffer[out_ep][current_offset++] = c; + if (rx_buffer_length[out_ep] < rx_buffer_max[out_ep]) + rx_buffer[out_ep][current_offset++] = c; } // Strip off the CRC16 - total_read -= 2; - out_buffer_length[out_ep] += total_read; - if (out_buffer_length[out_ep] > out_buffer_max[out_ep]) - out_buffer_length[out_ep] = out_buffer_max[out_ep]; + rx_buffer_length[out_ep] += (total_read - 2); + if (rx_buffer_length[out_ep] > rx_buffer_max[out_ep]) + rx_buffer_length[out_ep] = rx_buffer_max[out_ep]; - if (out_buffer_max[out_ep] == out_buffer_length[out_ep]) { - out_buffer[out_ep] = NULL; - dcd_event_xfer_complete(0, tu_edpt_addr(out_ep, TUSB_DIR_OUT), out_buffer_length[out_ep], XFER_RESULT_SUCCESS, in_isr); + if (rx_buffer_max[out_ep] == rx_buffer_length[out_ep]) { + rx_buffer[out_ep] = NULL; + uint16_t len = rx_buffer_length[out_ep]; + dcd_event_xfer_complete(0, tu_edpt_addr(out_ep, TUSB_DIR_OUT), len, XFER_RESULT_SUCCESS, in_isr); } - // Acknowledge having received the data - usb_out_ctrl_write(2); + // Acknowledge having received the data, and re-enable data reception + usb_out_ctrl_write(1 << CSR_USB_OUT_CTRL_ENABLE_OFFSET); } //--------------------------------------------------------------------+ // CONTROLLER API //--------------------------------------------------------------------+ +static void dcd_reset(void) +{ + usb_address_write(0); + + // Reset all three FIFO handlers + usb_setup_ctrl_write(1 << CSR_USB_SETUP_CTRL_RESET_OFFSET); + usb_in_ctrl_write(1 << CSR_USB_IN_CTRL_RESET_OFFSET); + usb_out_ctrl_write(1 << CSR_USB_OUT_CTRL_RESET_OFFSET); + + // Accept incoming data by default. + usb_out_ctrl_write(CSR_USB_OUT_CTRL_ENABLE_OFFSET); + + memset(rx_buffer, 0, sizeof(rx_buffer)); + tx_in_progress = 0; + tx_len = 0; + tx_buffer = NULL; + tx_offset = 0; + + dcd_event_bus_signal(0, DCD_EVENT_BUS_RESET, true); +} + // Initializes the USB peripheral for device mode and enables it. void dcd_init(uint8_t rhport) { (void) rhport; usb_pullup_out_write(0); - usb_address_write(0); - usb_out_ctrl_write(0); usb_setup_ev_enable_write(0); usb_in_ev_enable_write(0); usb_out_ev_enable_write(0); - // Reset the IN handler - usb_in_ctrl_write(0x20); - - // Reset the SETUP handler - usb_setup_ctrl_write(0x04); - - // Reset the OUT handler - usb_out_ctrl_write(0x04); - // Enable all event handlers and clear their contents usb_setup_ev_pending_write(usb_setup_ev_pending_read()); usb_in_ev_pending_write(usb_in_ev_pending_read()); usb_out_ev_pending_write(usb_out_ev_pending_read()); - usb_setup_ev_enable_write(3); usb_in_ev_enable_write(1); usb_out_ev_enable_write(1); - - // Accept incoming data by default. - usb_out_ctrl_write(2); + usb_setup_ev_enable_write(3); // Turn on the external pullup usb_pullup_out_write(1); - - dcd_event_bus_signal(0, DCD_EVENT_BUS_RESET, false); } // Enables or disables the USB device interrupt(s). May be used to @@ -222,36 +247,45 @@ bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t* buffer, uint16_t t { (void)rhport; + // These sorts of transfers are handled in hardware + if ((tu_edpt_number(ep_addr) == 0) && (total_bytes == 0) && (buffer == NULL)) { + dcd_event_xfer_complete(0, ep_addr, total_bytes, XFER_RESULT_SUCCESS, false); + + // An IN packet is sent to acknowledge an OUT token. Re-enable OUT after this. + if (tu_edpt_dir(ep_addr) == TUSB_DIR_IN) + usb_out_ctrl_write(1 << CSR_USB_OUT_CTRL_ENABLE_OFFSET); + return true; + } + if (tu_edpt_dir(ep_addr) == TUSB_DIR_IN) { - // These sorts of transfers are handled in hardware - if ((tu_edpt_number(ep_addr) == 0) && (total_bytes == 0) && (buffer == 0)) { - dcd_event_xfer_complete(0, ep_addr, total_bytes, XFER_RESULT_SUCCESS, false); - return true; - } uint32_t offset; + // Wait for the tx pipe to free up while (tx_in_progress) ; tx_in_progress = 1; tx_ep = ep_addr; tx_len = total_bytes; + tx_buffer = buffer; + tx_offset = 0; - for (offset = 0; offset < total_bytes; offset++) { + for (offset = 0; (offset < EP_SIZE) && (offset < total_bytes); offset++) { usb_in_data_write(buffer[offset]); } // Updating the epno queues the data usb_in_ctrl_write(tu_edpt_number(ep_addr) & 0xf); - last_tx_buffer = buffer; - last_tx_bytes = total_bytes; } else if (tu_edpt_dir(ep_addr) == TUSB_DIR_OUT) { + TU_ASSERT(rx_buffer[tu_edpt_number(ep_addr)] == NULL); - // Wait for the rx pipe to free up - while (out_buffer[tu_edpt_number(ep_addr)]) - ; - out_buffer_max[tu_edpt_number(ep_addr)] = total_bytes; - out_buffer[tu_edpt_number(ep_addr)] = buffer; - out_buffer_length[tu_edpt_number(ep_addr)] = 0; + rx_buffer_length[tu_edpt_number(ep_addr)] = 0; + rx_buffer_max[tu_edpt_number(ep_addr)] = total_bytes; + rx_buffer[tu_edpt_number(ep_addr)] = buffer; + + // If there's data in the buffer already, we'll try draining it + // into the current fifo immediately. Note that since this + // bit is set, an interrupt won't fire again, so there is + // no need for a lock here. process_rx(false); } return true; @@ -273,11 +307,7 @@ void hal_dcd_isr(uint8_t rhport) // This event means a bus reset occurred. Reset everything, and // abandon any further processing. if (setup_pending & 2) { - usb_setup_ctrl_write(1 << CSR_USB_SETUP_CTRL_RESET_OFFSET); - usb_in_ctrl_write(1 << CSR_USB_IN_CTRL_RESET_OFFSET); - usb_out_ctrl_write(1 << CSR_USB_OUT_CTRL_RESET_OFFSET); - - dcd_event_bus_signal(0, DCD_EVENT_BUS_RESET, true); + dcd_reset(); return; } From 470d827f13e22dea083266b96c7bd724a08b0b65 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Mon, 14 Oct 2019 11:08:27 +0800 Subject: [PATCH 032/267] docs: porting: remove invalid information and fix typo It is no longer the case that boards need to be added to this file. Signed-off-by: Sean Cross --- docs/porting.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/docs/porting.md b/docs/porting.md index a38ff019..7ed21d75 100644 --- a/docs/porting.md +++ b/docs/porting.md @@ -25,8 +25,6 @@ Unless, you've read ahead, this will fail miserably. Now, lets get it to fail le One of the first things to change is the `-DCFG_TUSB_MCU` cflag in the `board.mk` file. This is used to tell TinyUSB what platform is being built. So, add an entry to `src/tusb_option.h` and update the CFLAG to match. -Also, add an entry for the board in `hw/bsp/board.h`. The CFLAG is auto-added. - Update `board.mk`'s VENDOR and CHIP_FAMILY values when creating the directory for the struct files. Duplicate one of the other sources from `src/portable` into `src/portable//` and delete all of the implementation internals. We'll cover what everything there does later. For now, get it compiling. ## Implementation @@ -104,7 +102,7 @@ Calls to this look like: dcd_event_setup_received(0, setup, true); -As before with `dcd_event_bus_signal` the first argument is the USB peripheral number and the third is true to signal its being called from an interrup handler. The middle argument is byte array of length 8 with the contents of the SETUP packet. It can be stack allocated because it is copied into the queue. +As before with `dcd_event_bus_signal` the first argument is the USB peripheral number and the third is true to signal its being called from an interrupt handler. The middle argument is byte array of length 8 with the contents of the SETUP packet. It can be stack allocated because it is copied into the queue. #### Endpoints From ef07427e06b1fa868ac7b96b18e77270f2231aed Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Mon, 14 Oct 2019 11:30:05 +0800 Subject: [PATCH 033/267] bsp: fomu: update Signed-off-by: Sean Cross --- hw/bsp/fomu/bsp.c | 8 ++- hw/bsp/fomu/crt0-vexriscv.S | 14 ++-- hw/bsp/fomu/fomu.ld | 130 ++++++++++++++++++++++++------------ 3 files changed, 98 insertions(+), 54 deletions(-) diff --git a/hw/bsp/fomu/bsp.c b/hw/bsp/fomu/bsp.c index 861c223f..2bba0ce2 100644 --- a/hw/bsp/fomu/bsp.c +++ b/hw/bsp/fomu/bsp.c @@ -116,9 +116,11 @@ int board_uart_read(uint8_t* buf, int len) int board_uart_write(void const * buf, int len) { - (void) buf; - (void) len; - return 0; + int32_t offset = 0; + for (offset = 0; offset < len; offset++) + if (! (messible_status_read() & CSR_MESSIBLE_STATUS_FULL_OFFSET)) + messible_in_write(((uint8_t *)buf)[offset]); + return len; } #if CFG_TUSB_OS == OPT_OS_NONE diff --git a/hw/bsp/fomu/crt0-vexriscv.S b/hw/bsp/fomu/crt0-vexriscv.S index 931d50a0..46dca557 100644 --- a/hw/bsp/fomu/crt0-vexriscv.S +++ b/hw/bsp/fomu/crt0-vexriscv.S @@ -57,13 +57,13 @@ trap_entry: crt_init: - la sp, _fstack + 4 + la sp, _estack - 4 la a0, trap_entry csrw mtvec, a0 bss_init: - la a0, _fbss - la a1, _ebss + la a0, _sbss + la a1, _ebss + 4 bss_loop: beq a0,a1,bss_done sw zero,0(a0) @@ -72,13 +72,13 @@ bss_loop: bss_done: /* Load DATA */ - la t0, _erodata - la t1, _fdata - la t2, _edata + la t0, _etext + la t1, _srelocate + la t2, _erelocate + 4 3: lw t3, 0(t0) sw t3, 0(t1) - /* _edata is aligned to 16 bytes. Use word-xfers. */ + /* _edata is aligned to 4 bytes. Use word-xfers. */ addi t0, t0, 4 addi t1, t1, 4 bltu t1, t2, 3b diff --git a/hw/bsp/fomu/fomu.ld b/hw/bsp/fomu/fomu.ld index 2a3f2376..abc91b8e 100644 --- a/hw/bsp/fomu/fomu.ld +++ b/hw/bsp/fomu/fomu.ld @@ -6,57 +6,99 @@ __DYNAMIC = 0; MEMORY { csr : ORIGIN = 0x60000000, LENGTH = 0x01000000 vexriscv_debug : ORIGIN = 0xf00f0000, LENGTH = 0x00000100 - sram : ORIGIN = 0x10000000, LENGTH = 0x00020000 + ram : ORIGIN = 0x10000000, LENGTH = 0x00020000 rom : ORIGIN = 0x2001a000, LENGTH = 0x00200000 - 0x1a000 } +/* The stack size used by the application. NOTE: you need to adjust according to your application. */ +STACK_SIZE = DEFINED(STACK_SIZE) ? STACK_SIZE : DEFINED(__stack_size__) ? __stack_size__ : 0x2000; + +/* Section Definitions */ SECTIONS { - .text : - { - _ftext = .; + .text : + { + . = ALIGN(4); + _ftext = .; *(.text.start) - *(.text .stub .text.* .gnu.linkonce.t.*) - _etext = .; - } > rom + *(.text .text.* .gnu.linkonce.t.*) + *(.glue_7t) *(.glue_7) + *(.rodata .rodata* .gnu.linkonce.r.*) - .rodata : - { - . = ALIGN(4); - _frodata = .; - *(.rodata .rodata.* .gnu.linkonce.r.*) - *(.rodata1) - *(.srodata) - . = ALIGN(4); - _erodata = .; - } > rom + /* Support C constructors, and C destructors in both user code + and the C library. This also provides support for C++ code. */ + . = ALIGN(4); + KEEP(*(.init)) + . = ALIGN(4); + __preinit_array_start = .; + KEEP (*(.preinit_array)) + __preinit_array_end = .; - .data : AT (ADDR(.rodata) + SIZEOF (.rodata)) - { - . = ALIGN(4); - _fdata = .; - *(.data .data.* .gnu.linkonce.d.*) - *(.data1) - _gp = ALIGN(16); - *(.sdata .sdata.* .gnu.linkonce.s.* .sdata2 .sdata2.*) - . = ALIGN(16); - _edata = .; /* Make sure _edata is >= _gp. */ - } > sram + . = ALIGN(4); + __init_array_start = .; + KEEP (*(SORT(.init_array.*))) + KEEP (*(.init_array)) + __init_array_end = .; - .bss : - { - _fbss = .; - *(.dynsbss) - *(.sbss .sbss.* .gnu.linkonce.sb.*) - *(.scommon) - *(.dynbss) - *(.bss .bss.* .gnu.linkonce.b.*) - *(COMMON) - . = ALIGN(4); - _ebss = .; - _end = .; - PROVIDE(end = .); - } > sram -} + . = ALIGN(4); + KEEP (*crtbegin.o(.ctors)) + KEEP (*(EXCLUDE_FILE (*crtend.o) .ctors)) + KEEP (*(SORT(.ctors.*))) + KEEP (*crtend.o(.ctors)) -PROVIDE(_fstack = ORIGIN(sram) + LENGTH(sram) - 4); + . = 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)) + } > rom + + . = ALIGN(4); + _etext = .; /* End of text section */ + + .relocate : AT (_etext) + { + . = ALIGN(4); + _srelocate = .; + *(.ramfunc .ramfunc.*); + *(.data .data.*); + . = ALIGN(4); + _erelocate = .; + } > ram + + /* .bss section which is used for uninitialized data */ + .bss (NOLOAD) : + { + . = ALIGN(4); + _sbss = . ; + _szero = .; + *(.bss .bss.*) + *(.sbss .sbss.*) + *(COMMON) + . = ALIGN(4); + _ebss = . ; + _ezero = .; + end = .; + } > ram + + /* stack section */ + .stack (NOLOAD): + { + . = ALIGN(8); + _sstack = .; + . = . + STACK_SIZE; + . = ALIGN(8); + _estack = .; + } > ram + + . = ALIGN(4); + _end = . ; +} \ No newline at end of file From 359189ea2d791ab895dc29cbfa4e3eba14caf65f Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Mon, 14 Oct 2019 11:58:17 +0800 Subject: [PATCH 034/267] tusb_verify: add riscv assert support This simply executes an "ebreak" instruction. Signed-off-by: Sean Cross --- src/common/tusb_verify.h | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/common/tusb_verify.h b/src/common/tusb_verify.h index e5948135..2b63ab94 100644 --- a/src/common/tusb_verify.h +++ b/src/common/tusb_verify.h @@ -89,9 +89,13 @@ volatile uint32_t* ARM_CM_DHCSR = ((volatile uint32_t*) 0xE000EDF0UL); /* Cortex M CoreDebug->DHCSR */ \ if ( (*ARM_CM_DHCSR) & 1UL ) __asm("BKPT #0\n"); /* Only halt mcu if debugger is attached */ \ } while(0) +#else +#if defined(__riscv) + #define TU_BREAKPOINT() do { __asm("ebreak\n"); } while(0) #else #define TU_BREAKPOINT() #endif +#endif /*------------------------------------------------------------------*/ /* Macro Generator From 0559fd13fb43aa991200c3bddc146c5828fc48b0 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Mon, 14 Oct 2019 11:59:17 +0800 Subject: [PATCH 035/267] fomu: fix some issues with dcd_fomu Signed-off-by: Sean Cross --- src/portable/foosn/fomu/dcd_fomu.c | 179 ++++++++++++++++++----------- 1 file changed, 109 insertions(+), 70 deletions(-) diff --git a/src/portable/foosn/fomu/dcd_fomu.c b/src/portable/foosn/fomu/dcd_fomu.c index f49e9e50..73cf018e 100644 --- a/src/portable/foosn/fomu/dcd_fomu.c +++ b/src/portable/foosn/fomu/dcd_fomu.c @@ -43,31 +43,34 @@ void mputln(const char *str); #define EP_SIZE 64 -static uint16_t volatile rx_buffer_length[16]; -static uint8_t volatile * rx_buffer[16]; -static uint16_t volatile rx_buffer_max[16]; +uint16_t volatile rx_buffer_offset[16]; +uint8_t volatile * rx_buffer[16]; +uint16_t volatile rx_buffer_max[16]; -static volatile bool tx_in_progress; -static volatile uint8_t tx_ep; -static volatile uint16_t tx_len; -static uint8_t volatile * tx_buffer; -static volatile uint16_t tx_offset; +volatile uint8_t tx_ep; +volatile uint16_t tx_len; +uint8_t volatile * tx_buffer; +volatile uint16_t tx_offset; +volatile uint8_t reset_count; //--------------------------------------------------------------------+ // PIPE HELPER //--------------------------------------------------------------------+ static void finish_tx(void) { - // Don't send empty data - if (!tx_in_progress) { + // Ignore "ACK" packets where there was no data to send. + if (!tx_buffer) { return; } + uint8_t in_status = usb_in_status_read(); + if (!(in_status & (1 << CSR_USB_IN_STATUS_IDLE_OFFSET))) + fomu_error(__LINE__); + tx_offset += EP_SIZE; if (tx_offset >= tx_len) { - tx_in_progress = 0; + dcd_event_xfer_complete(0, tu_edpt_addr(tx_ep, TUSB_DIR_IN), tx_len, XFER_RESULT_SUCCESS, true); tx_buffer = NULL; - dcd_event_xfer_complete(0, tx_ep, tx_len, XFER_RESULT_SUCCESS, true); return; } @@ -78,41 +81,49 @@ static void finish_tx(void) { } // Updating the epno queues the data - usb_in_ctrl_write(tu_edpt_number(tx_ep) & 0xf); + usb_in_ctrl_write(tx_ep & 0xf); return; } static void process_rx(bool in_isr) { - // If there isn't any data in the FIFO, don't do anything. - if (!(usb_out_status_read() & (1 << CSR_USB_OUT_STATUS_HAVE_OFFSET))) + // If the OUT handler is still waiting to send, don't do anything. + uint8_t out_status = usb_out_status_read(); + if (!(out_status & (1 << CSR_USB_OUT_STATUS_IDLE_OFFSET))) return; - uint8_t out_ep = (usb_out_status_read() >> CSR_USB_OUT_STATUS_EPNO_OFFSET) & 0xf; + uint8_t rx_ep = (out_status >> CSR_USB_OUT_STATUS_EPNO_OFFSET) & 0xf; + if ((rx_ep != 0) && (rx_ep != 2) && (rx_ep != 3)) + fomu_error(__LINE__); // If the destination buffer doesn't exist, don't drain the hardware // fifo. Note that this can cause deadlocks if the host is waiting // on some other endpoint's data! - if (rx_buffer[out_ep] == NULL) + if (rx_buffer[rx_ep] == NULL) return; uint32_t total_read = 0; - uint32_t current_offset = rx_buffer_length[out_ep]; + uint32_t current_offset = rx_buffer_offset[rx_ep]; + if (current_offset > rx_buffer_max[rx_ep]) + fomu_error(__LINE__); while (usb_out_status_read() & (1 << CSR_USB_OUT_STATUS_HAVE_OFFSET)) { uint8_t c = usb_out_data_read(); total_read++; - if (rx_buffer_length[out_ep] < rx_buffer_max[out_ep]) - rx_buffer[out_ep][current_offset++] = c; + if ((rx_buffer_offset[rx_ep] + current_offset) < rx_buffer_max[rx_ep]) + rx_buffer[rx_ep][current_offset++] = c; } // Strip off the CRC16 - rx_buffer_length[out_ep] += (total_read - 2); - if (rx_buffer_length[out_ep] > rx_buffer_max[out_ep]) - rx_buffer_length[out_ep] = rx_buffer_max[out_ep]; + rx_buffer_offset[rx_ep] += (total_read - 2); + if (rx_buffer_offset[rx_ep] > rx_buffer_max[rx_ep]) + rx_buffer_offset[rx_ep] = rx_buffer_max[rx_ep]; - if (rx_buffer_max[out_ep] == rx_buffer_length[out_ep]) { - rx_buffer[out_ep] = NULL; - uint16_t len = rx_buffer_length[out_ep]; - dcd_event_xfer_complete(0, tu_edpt_addr(out_ep, TUSB_DIR_OUT), len, XFER_RESULT_SUCCESS, in_isr); + if ((rx_ep == 3) && (rx_buffer[rx_ep][0] == 0x80) && (rx_buffer[rx_ep][1] == 0x25)) + fomu_error(__LINE__); + + if (rx_buffer_max[rx_ep] == rx_buffer_offset[rx_ep]) { + rx_buffer[rx_ep] = NULL; + uint16_t len = rx_buffer_offset[rx_ep]; + dcd_event_xfer_complete(0, tu_edpt_addr(rx_ep, TUSB_DIR_OUT), len, XFER_RESULT_SUCCESS, in_isr); } // Acknowledge having received the data, and re-enable data reception @@ -125,6 +136,11 @@ static void process_rx(bool in_isr) { static void dcd_reset(void) { + reset_count++; + usb_setup_ev_enable_write(0); + usb_in_ev_enable_write(0); + usb_out_ev_enable_write(0); + usb_address_write(0); // Reset all three FIFO handlers @@ -132,14 +148,24 @@ static void dcd_reset(void) usb_in_ctrl_write(1 << CSR_USB_IN_CTRL_RESET_OFFSET); usb_out_ctrl_write(1 << CSR_USB_OUT_CTRL_RESET_OFFSET); - // Accept incoming data by default. - usb_out_ctrl_write(CSR_USB_OUT_CTRL_ENABLE_OFFSET); - - memset(rx_buffer, 0, sizeof(rx_buffer)); - tx_in_progress = 0; + memset((void *)rx_buffer, 0, sizeof(rx_buffer)); + memset((void *)rx_buffer_max, 0, sizeof(rx_buffer_max)); + memset((void *)rx_buffer_offset, 0, sizeof(rx_buffer_offset)); tx_len = 0; tx_buffer = NULL; tx_offset = 0; + tx_ep = 0; + + // Accept incoming data by default. + usb_out_ctrl_write(1 << CSR_USB_OUT_CTRL_ENABLE_OFFSET); + + // Enable all event handlers and clear their contents + usb_setup_ev_pending_write(usb_setup_ev_pending_read()); + usb_in_ev_pending_write(usb_in_ev_pending_read()); + usb_out_ev_pending_write(usb_out_ev_pending_read()); + usb_in_ev_enable_write(1); + usb_out_ev_enable_write(1); + usb_setup_ev_enable_write(3); dcd_event_bus_signal(0, DCD_EVENT_BUS_RESET, true); } @@ -151,10 +177,6 @@ void dcd_init(uint8_t rhport) usb_pullup_out_write(0); - usb_setup_ev_enable_write(0); - usb_in_ev_enable_write(0); - usb_out_ev_enable_write(0); - // Enable all event handlers and clear their contents usb_setup_ev_pending_write(usb_setup_ev_pending_read()); usb_in_ev_pending_write(usb_in_ev_pending_read()); @@ -190,7 +212,7 @@ void dcd_set_address(uint8_t rhport, uint8_t dev_addr) usb_address_write(dev_addr); // ACK the transfer (sets the address) - usb_setup_ctrl_write(2); + usb_setup_ctrl_write(1 << CSR_USB_SETUP_CTRL_HANDLED_OFFSET); } // Called when the device received SET_CONFIG request, you can leave this @@ -213,10 +235,18 @@ void dcd_remote_wakeup(uint8_t rhport) bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc) { (void) rhport; + uint8_t ep_num = tu_edpt_number(p_endpoint_desc->bEndpointAddress); + uint8_t ep_dir = tu_edpt_dir(p_endpoint_desc->bEndpointAddress); if (p_endpoint_desc->bmAttributes.xfer == TUSB_XFER_ISOCHRONOUS) return false; // Not supported + if (ep_dir == TUSB_DIR_OUT) { + rx_buffer_offset[ep_num] = 0; + rx_buffer_max[ep_num] = 0; + rx_buffer[ep_num] = NULL; + } + return true; } @@ -238,55 +268,64 @@ void dcd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr) // IN endpoints will get unstalled when more data is written. } -__attribute__((used)) -uint8_t *last_tx_buffer; -__attribute__((used)) -uint16_t last_tx_bytes; - bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t* buffer, uint16_t total_bytes) { (void)rhport; + uint8_t ep_num = tu_edpt_number(ep_addr); + uint8_t ep_dir = tu_edpt_dir(ep_addr); - // These sorts of transfers are handled in hardware - if ((tu_edpt_number(ep_addr) == 0) && (total_bytes == 0) && (buffer == NULL)) { + // These sorts of transfers are handled in hardware automatically, so simply inform + // the core that the transfer was processed. + if ((ep_num == 0) && (total_bytes == 0) && (buffer == NULL)) { dcd_event_xfer_complete(0, ep_addr, total_bytes, XFER_RESULT_SUCCESS, false); // An IN packet is sent to acknowledge an OUT token. Re-enable OUT after this. - if (tu_edpt_dir(ep_addr) == TUSB_DIR_IN) - usb_out_ctrl_write(1 << CSR_USB_OUT_CTRL_ENABLE_OFFSET); + // if (ep_dir == TUSB_DIR_IN) { + // usb_out_ev_enable_write(0); + // process_rx(false); + // usb_out_ev_enable_write(1); + // } return true; } - if (tu_edpt_dir(ep_addr) == TUSB_DIR_IN) { + TU_ASSERT(((uint32_t)buffer) >= 0x10000000); + TU_ASSERT(((uint32_t)buffer) <= 0x10020000); + + if (ep_dir == TUSB_DIR_IN) { uint32_t offset; // Wait for the tx pipe to free up - while (tx_in_progress) + uint8_t previous_reset_count = reset_count; + while ((tx_buffer != NULL) || !(usb_in_status_read() & (1 << CSR_USB_IN_STATUS_IDLE_OFFSET))) ; - tx_in_progress = 1; - tx_ep = ep_addr; + // If a reset happens while we're waiting, abort the transfer + if (previous_reset_count != reset_count) + return true; + + tx_ep = ep_num; tx_len = total_bytes; - tx_buffer = buffer; tx_offset = 0; + tx_buffer = buffer; for (offset = 0; (offset < EP_SIZE) && (offset < total_bytes); offset++) { - usb_in_data_write(buffer[offset]); + usb_in_data_write(buffer[offset]); } // Updating the epno queues the data - usb_in_ctrl_write(tu_edpt_number(ep_addr) & 0xf); + usb_in_ctrl_write(ep_num & 0xf); } - else if (tu_edpt_dir(ep_addr) == TUSB_DIR_OUT) { - TU_ASSERT(rx_buffer[tu_edpt_number(ep_addr)] == NULL); + else if (ep_dir == TUSB_DIR_OUT) { + TU_ASSERT(rx_buffer[ep_num] == NULL); + TU_ASSERT((ep_num == 0) || (ep_num == 2) || (ep_num == 3)); - rx_buffer_length[tu_edpt_number(ep_addr)] = 0; - rx_buffer_max[tu_edpt_number(ep_addr)] = total_bytes; - rx_buffer[tu_edpt_number(ep_addr)] = buffer; + rx_buffer_offset[ep_num] = 0; + rx_buffer_max[ep_num] = total_bytes; + rx_buffer[ep_num] = buffer; // If there's data in the buffer already, we'll try draining it - // into the current fifo immediately. Note that since this - // bit is set, an interrupt won't fire again, so there is - // no need for a lock here. + // into the current fifo immediately. + usb_out_ev_enable_write(0); process_rx(false); + usb_out_ev_enable_write(1); } return true; } @@ -311,6 +350,13 @@ void hal_dcd_isr(uint8_t rhport) return; } + // An "OUT" transaction just completed so we have new data. + // (But only if we can accept the data) + // if (out_pending) { + if (usb_out_ev_enable_read() && out_pending) { + process_rx(true); + } + // An "IN" transaction just completed. // Note that due to the way tinyusb's callback system is implemented, // we must handle IN and OUT packets before we handle SETUP packets. @@ -322,17 +368,10 @@ void hal_dcd_isr(uint8_t rhport) finish_tx(); } - // An "OUT" transaction just completed so we have new data. - // (But only if we can accept the data) - if (out_pending) { - process_rx(true); - } - // We got a SETUP packet. Copy it to the setup buffer and clear // the "pending" bit. if (setup_pending & 1) { - // Setup packets are always 8 bytes, plus two bytes - // of crc16 + // Setup packets are always 8 bytes, plus two bytes of crc16. uint8_t setup_packet[10]; uint32_t setup_length = 0; @@ -354,7 +393,7 @@ void hal_dcd_isr(uint8_t rhport) // packet. If it is, leave it unacknowledged and we'll do this // in the `dcd_set_address` function instead. if (!((setup_packet[0] == 0x00) && (setup_packet[1] == 0x05))) - usb_setup_ctrl_write(2); + usb_setup_ctrl_write(1 << CSR_USB_SETUP_CTRL_HANDLED_OFFSET); } else { fomu_error(__LINE__); From 4a8475b8a7a2417b7b6dd27e071774d926130087 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Mon, 14 Oct 2019 11:59:40 +0800 Subject: [PATCH 036/267] src: add eptri to tusb Signed-off-by: Sean Cross --- src/tusb_option.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/tusb_option.h b/src/tusb_option.h index fc509ae7..d2a9ad80 100644 --- a/src/tusb_option.h +++ b/src/tusb_option.h @@ -70,6 +70,8 @@ #define OPT_MCU_CXD56 400 ///< SONY CXD56 +#define OPT_MCU_FOMU_EPTRI 600 ///< Fomu eptri config + /** @} */ /** \defgroup group_supported_os Supported RTOS From 22fd7bf85ecc4f1e58f8e6827431d0ae0b5700d1 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Mon, 14 Oct 2019 23:02:05 +0800 Subject: [PATCH 037/267] fomu: first fully-working release This is able to transfer lots of data back and forth across MSC. Signed-off-by: Sean Cross --- src/portable/foosn/fomu/dcd_fomu.c | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/src/portable/foosn/fomu/dcd_fomu.c b/src/portable/foosn/fomu/dcd_fomu.c index 73cf018e..96ac3a9f 100644 --- a/src/portable/foosn/fomu/dcd_fomu.c +++ b/src/portable/foosn/fomu/dcd_fomu.c @@ -63,6 +63,7 @@ static void finish_tx(void) { return; } + // If the system isn't idle, then something is very wrong. uint8_t in_status = usb_in_status_read(); if (!(in_status & (1 << CSR_USB_IN_STATUS_IDLE_OFFSET))) fomu_error(__LINE__); @@ -92,8 +93,6 @@ static void process_rx(bool in_isr) { return; uint8_t rx_ep = (out_status >> CSR_USB_OUT_STATUS_EPNO_OFFSET) & 0xf; - if ((rx_ep != 0) && (rx_ep != 2) && (rx_ep != 3)) - fomu_error(__LINE__); // If the destination buffer doesn't exist, don't drain the hardware // fifo. Note that this can cause deadlocks if the host is waiting @@ -117,9 +116,6 @@ static void process_rx(bool in_isr) { if (rx_buffer_offset[rx_ep] > rx_buffer_max[rx_ep]) rx_buffer_offset[rx_ep] = rx_buffer_max[rx_ep]; - if ((rx_ep == 3) && (rx_buffer[rx_ep][0] == 0x80) && (rx_buffer[rx_ep][1] == 0x25)) - fomu_error(__LINE__); - if (rx_buffer_max[rx_ep] == rx_buffer_offset[rx_ep]) { rx_buffer[rx_ep] = NULL; uint16_t len = rx_buffer_offset[rx_ep]; @@ -273,6 +269,7 @@ bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t* buffer, uint16_t t (void)rhport; uint8_t ep_num = tu_edpt_number(ep_addr); uint8_t ep_dir = tu_edpt_dir(ep_addr); + TU_ASSERT(tx_ep < 16); // These sorts of transfers are handled in hardware automatically, so simply inform // the core that the transfer was processed. @@ -296,7 +293,9 @@ bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t* buffer, uint16_t t // Wait for the tx pipe to free up uint8_t previous_reset_count = reset_count; - while ((tx_buffer != NULL) || !(usb_in_status_read() & (1 << CSR_USB_IN_STATUS_IDLE_OFFSET))) + while (!((tx_buffer == NULL) + && (usb_in_status_read() & (1 << CSR_USB_IN_STATUS_IDLE_OFFSET)) + && !(usb_in_status_read() & (1 << CSR_USB_IN_STATUS_HAVE_OFFSET)))) ; // If a reset happens while we're waiting, abort the transfer if (previous_reset_count != reset_count) @@ -315,7 +314,6 @@ bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t* buffer, uint16_t t } else if (ep_dir == TUSB_DIR_OUT) { TU_ASSERT(rx_buffer[ep_num] == NULL); - TU_ASSERT((ep_num == 0) || (ep_num == 2) || (ep_num == 3)); rx_buffer_offset[ep_num] = 0; rx_buffer_max[ep_num] = total_bytes; @@ -324,7 +322,8 @@ bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t* buffer, uint16_t t // If there's data in the buffer already, we'll try draining it // into the current fifo immediately. usb_out_ev_enable_write(0); - process_rx(false); + if (usb_out_status_read() & (1 << CSR_USB_OUT_STATUS_HAVE_OFFSET)) + process_rx(false); usb_out_ev_enable_write(1); } return true; From 843136d0e4467e1c554f246d1b69fed3172b6cc0 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Tue, 29 Oct 2019 21:35:03 +0800 Subject: [PATCH 038/267] fomu: commit latest version Signed-off-by: Sean Cross --- src/portable/foosn/fomu/dcd_fomu.c | 298 ++++++++++++++++++----------- 1 file changed, 181 insertions(+), 117 deletions(-) diff --git a/src/portable/foosn/fomu/dcd_fomu.c b/src/portable/foosn/fomu/dcd_fomu.c index 96ac3a9f..8b2212c1 100644 --- a/src/portable/foosn/fomu/dcd_fomu.c +++ b/src/portable/foosn/fomu/dcd_fomu.c @@ -48,19 +48,49 @@ uint8_t volatile * rx_buffer[16]; uint16_t volatile rx_buffer_max[16]; volatile uint8_t tx_ep; -volatile uint16_t tx_len; -uint8_t volatile * tx_buffer; -volatile uint16_t tx_offset; +volatile uint16_t tx_buffer_offset[16]; +uint8_t volatile * tx_buffer[16]; +volatile uint16_t tx_buffer_max[16]; volatile uint8_t reset_count; +__attribute__((used)) uint8_t volatile * last_tx_buffer; +__attribute__((used)) volatile uint8_t last_tx_ep; + +uint8_t setup_packet_bfr[10]; + //--------------------------------------------------------------------+ // PIPE HELPER //--------------------------------------------------------------------+ -static void finish_tx(void) { - // Ignore "ACK" packets where there was no data to send. - if (!tx_buffer) { - return; +static bool advance_tx_ep(void) { + // Move on to the next transmit buffer in a round-robin manner + uint8_t prev_tx_ep = tx_ep; + for (tx_ep = (tx_ep + 1) & 0xf; tx_ep != prev_tx_ep; tx_ep = ((tx_ep + 1) & 0xf)) { + if (tx_buffer[tx_ep]) + return true; + } + if (!tx_buffer[tx_ep]) + return false; + return true; +} + +static void tx_more_data(void) { + // Send more data + uint8_t added_bytes; + for (added_bytes = 0; (added_bytes < EP_SIZE) && (added_bytes + tx_buffer_offset[tx_ep] < tx_buffer_max[tx_ep]); added_bytes++) { + usb_in_data_write(tx_buffer[tx_ep][added_bytes + tx_buffer_offset[tx_ep]]); + } + + // Updating the epno queues the data + usb_in_ctrl_write(tx_ep & 0xf); +} + +static void process_tx(bool in_isr) { + // If the buffer is now empty, search for the next buffer to fill. + if (!tx_buffer[tx_ep]) { + if (advance_tx_ep()) + tx_more_data(); + return; } // If the system isn't idle, then something is very wrong. @@ -68,62 +98,78 @@ static void finish_tx(void) { if (!(in_status & (1 << CSR_USB_IN_STATUS_IDLE_OFFSET))) fomu_error(__LINE__); - tx_offset += EP_SIZE; - if (tx_offset >= tx_len) { - dcd_event_xfer_complete(0, tu_edpt_addr(tx_ep, TUSB_DIR_IN), tx_len, XFER_RESULT_SUCCESS, true); - tx_buffer = NULL; - return; + tx_buffer_offset[tx_ep] += EP_SIZE; + + if (tx_buffer_offset[tx_ep] >= tx_buffer_max[tx_ep]) { + last_tx_buffer = tx_buffer[tx_ep]; + last_tx_ep = tx_ep; + tx_buffer[tx_ep] = NULL; + + dcd_event_xfer_complete(0, tu_edpt_addr(tx_ep, TUSB_DIR_IN), tx_buffer_max[tx_ep], XFER_RESULT_SUCCESS, in_isr); + if (!advance_tx_ep()) + return; } - // Send more data - uint8_t added_bytes; - for (added_bytes = 0; (added_bytes < EP_SIZE) && (added_bytes + tx_offset < tx_len); added_bytes++) { - usb_in_data_write(tx_buffer[added_bytes + tx_offset]); - } - - // Updating the epno queues the data - usb_in_ctrl_write(tx_ep & 0xf); + tx_more_data(); return; } static void process_rx(bool in_isr) { - // If the OUT handler is still waiting to send, don't do anything. - uint8_t out_status = usb_out_status_read(); - if (!(out_status & (1 << CSR_USB_OUT_STATUS_IDLE_OFFSET))) - return; + // If the OUT handler is still waiting to send, don't do anything. + uint8_t out_status = usb_out_status_read(); + if (!(out_status & (1 << CSR_USB_OUT_STATUS_HAVE_OFFSET))) + fomu_error(__LINE__); + // return; - uint8_t rx_ep = (out_status >> CSR_USB_OUT_STATUS_EPNO_OFFSET) & 0xf; + uint8_t rx_ep = (out_status >> CSR_USB_OUT_STATUS_EPNO_OFFSET) & 0xf; - // If the destination buffer doesn't exist, don't drain the hardware - // fifo. Note that this can cause deadlocks if the host is waiting - // on some other endpoint's data! + // If the destination buffer doesn't exist, don't drain the hardware + // fifo. Note that this can cause deadlocks if the host is waiting + // on some other endpoint's data! + if (rx_buffer[rx_ep] == NULL) { + fomu_error(__LINE__); + return; + } + + uint32_t total_read = 0; + uint32_t current_offset = rx_buffer_offset[rx_ep]; + if (current_offset > rx_buffer_max[rx_ep]) + fomu_error(__LINE__); + while (usb_out_status_read() & (1 << CSR_USB_OUT_STATUS_HAVE_OFFSET)) { + uint8_t c = usb_out_data_read(); + total_read++; + if ((rx_buffer_offset[rx_ep] + current_offset) < rx_buffer_max[rx_ep]) + rx_buffer[rx_ep][current_offset++] = c; + } + if (total_read > 66) + fomu_error(__LINE__); + + // Strip off the CRC16 + rx_buffer_offset[rx_ep] += (total_read - 2); + if (rx_buffer_offset[rx_ep] > rx_buffer_max[rx_ep]) + rx_buffer_offset[rx_ep] = rx_buffer_max[rx_ep]; + + if (rx_buffer_max[rx_ep] == rx_buffer_offset[rx_ep]) { if (rx_buffer[rx_ep] == NULL) - return; - - uint32_t total_read = 0; - uint32_t current_offset = rx_buffer_offset[rx_ep]; - if (current_offset > rx_buffer_max[rx_ep]) fomu_error(__LINE__); - while (usb_out_status_read() & (1 << CSR_USB_OUT_STATUS_HAVE_OFFSET)) { - uint8_t c = usb_out_data_read(); - total_read++; - if ((rx_buffer_offset[rx_ep] + current_offset) < rx_buffer_max[rx_ep]) - rx_buffer[rx_ep][current_offset++] = c; - } - // Strip off the CRC16 - rx_buffer_offset[rx_ep] += (total_read - 2); - if (rx_buffer_offset[rx_ep] > rx_buffer_max[rx_ep]) - rx_buffer_offset[rx_ep] = rx_buffer_max[rx_ep]; + // Disable this endpoint (causing it to respond NAK) until we have + // a buffer to place the data into. + rx_buffer[rx_ep] = NULL; + uint16_t len = rx_buffer_offset[rx_ep]; - if (rx_buffer_max[rx_ep] == rx_buffer_offset[rx_ep]) { - rx_buffer[rx_ep] = NULL; - uint16_t len = rx_buffer_offset[rx_ep]; - dcd_event_xfer_complete(0, tu_edpt_addr(rx_ep, TUSB_DIR_OUT), len, XFER_RESULT_SUCCESS, in_isr); - } + // uint16_t ep_en_mask = usb_out_enable_status_read(); + // int i; + // for (i = 0; i < 16; i++) { + // if ((!!(ep_en_mask & (1 << i))) ^ (!!(rx_buffer[i]))) + // fomu_error(__LINE__); + // } + dcd_event_xfer_complete(0, tu_edpt_addr(rx_ep, TUSB_DIR_OUT), len, XFER_RESULT_SUCCESS, in_isr); + return; + } - // Acknowledge having received the data, and re-enable data reception - usb_out_ctrl_write(1 << CSR_USB_OUT_CTRL_ENABLE_OFFSET); + // If there's more data, re-enable data reception + usb_out_ctrl_write((1 << CSR_USB_OUT_CTRL_ENABLE_OFFSET) | rx_ep); } //--------------------------------------------------------------------+ @@ -147,18 +193,16 @@ static void dcd_reset(void) memset((void *)rx_buffer, 0, sizeof(rx_buffer)); memset((void *)rx_buffer_max, 0, sizeof(rx_buffer_max)); memset((void *)rx_buffer_offset, 0, sizeof(rx_buffer_offset)); - tx_len = 0; - tx_buffer = NULL; - tx_offset = 0; + + memset((void *)tx_buffer, 0, sizeof(tx_buffer)); + memset((void *)tx_buffer_max, 0, sizeof(tx_buffer_max)); + memset((void *)tx_buffer_offset, 0, sizeof(tx_buffer_offset)); tx_ep = 0; - // Accept incoming data by default. - usb_out_ctrl_write(1 << CSR_USB_OUT_CTRL_ENABLE_OFFSET); - // Enable all event handlers and clear their contents - usb_setup_ev_pending_write(usb_setup_ev_pending_read()); - usb_in_ev_pending_write(usb_in_ev_pending_read()); - usb_out_ev_pending_write(usb_out_ev_pending_read()); + usb_setup_ev_pending_write(-1); + usb_in_ev_pending_write(-1); + usb_out_ev_pending_write(-1); usb_in_ev_enable_write(1); usb_out_ev_enable_write(1); usb_setup_ev_enable_write(3); @@ -203,12 +247,15 @@ void dcd_int_disable(uint8_t rhport) // Called when the device is given a new bus address. void dcd_set_address(uint8_t rhport, uint8_t dev_addr) { - (void)rhport; - // Set address and then acknowledge the SETUP packet - usb_address_write(dev_addr); + // Respond with ACK status first before changing device address + dcd_edpt_xfer(rhport, tu_edpt_addr(0, TUSB_DIR_IN), NULL, 0); - // ACK the transfer (sets the address) - usb_setup_ctrl_write(1 << CSR_USB_SETUP_CTRL_HANDLED_OFFSET); + // Wait for the response packet to get sent + while (tx_buffer[0] != NULL) + ; + + // Activate the new address + usb_address_write(dev_addr); } // Called when the device received SET_CONFIG request, you can leave this @@ -243,24 +290,36 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc) rx_buffer[ep_num] = NULL; } + else if (ep_dir == TUSB_DIR_OUT) { + tx_buffer_offset[ep_num] = 0; + tx_buffer_max[ep_num] = 0; + tx_buffer[ep_num] = NULL; + } + return true; } void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr) { (void) rhport; + if (tu_edpt_number(ep_addr) == 2) + fomu_error(__LINE__); + if (tu_edpt_dir(ep_addr) == TUSB_DIR_OUT) - usb_out_stall_write((1 << CSR_USB_OUT_STALL_STALL_OFFSET) | tu_edpt_number(ep_addr)); - else { + usb_out_ctrl_write((1 << CSR_USB_OUT_CTRL_STALL_OFFSET) | (1 << CSR_USB_OUT_CTRL_ENABLE_OFFSET) | tu_edpt_number(ep_addr)); + else usb_in_ctrl_write((1 << CSR_USB_IN_CTRL_STALL_OFFSET) | tu_edpt_number(ep_addr)); - } } void dcd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr) { (void) rhport; - if (tu_edpt_dir(ep_addr) == TUSB_DIR_OUT) - usb_out_stall_write((0 << CSR_USB_OUT_STALL_STALL_OFFSET) | tu_edpt_number(ep_addr)); + if (tu_edpt_dir(ep_addr) == TUSB_DIR_OUT) { + uint8_t enable = 0; + if (rx_buffer[ep_addr]) + enable = 1; + usb_out_ctrl_write((0 << CSR_USB_OUT_CTRL_STALL_OFFSET) | (enable << CSR_USB_OUT_CTRL_ENABLE_OFFSET) | tu_edpt_number(ep_addr)); + } // IN endpoints will get unstalled when more data is written. } @@ -269,62 +328,64 @@ bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t* buffer, uint16_t t (void)rhport; uint8_t ep_num = tu_edpt_number(ep_addr); uint8_t ep_dir = tu_edpt_dir(ep_addr); - TU_ASSERT(tx_ep < 16); + TU_ASSERT(ep_num < 16); - // These sorts of transfers are handled in hardware automatically, so simply inform - // the core that the transfer was processed. - if ((ep_num == 0) && (total_bytes == 0) && (buffer == NULL)) { - dcd_event_xfer_complete(0, ep_addr, total_bytes, XFER_RESULT_SUCCESS, false); - - // An IN packet is sent to acknowledge an OUT token. Re-enable OUT after this. - // if (ep_dir == TUSB_DIR_IN) { - // usb_out_ev_enable_write(0); - // process_rx(false); - // usb_out_ev_enable_write(1); - // } - return true; + // Give a nonzero buffer when we transmit 0 bytes, so that the + // system doesn't think the endpoint is idle. + if ((buffer == NULL) && (total_bytes == 0)) { + buffer = (uint8_t *)0xffffffff; } - TU_ASSERT(((uint32_t)buffer) >= 0x10000000); - TU_ASSERT(((uint32_t)buffer) <= 0x10020000); + TU_ASSERT(buffer != NULL); if (ep_dir == TUSB_DIR_IN) { - uint32_t offset; - // Wait for the tx pipe to free up uint8_t previous_reset_count = reset_count; - while (!((tx_buffer == NULL) - && (usb_in_status_read() & (1 << CSR_USB_IN_STATUS_IDLE_OFFSET)) - && !(usb_in_status_read() & (1 << CSR_USB_IN_STATUS_HAVE_OFFSET)))) + // Continue until the buffer is empty, the system is idle, and the fifo is empty. + while (tx_buffer[ep_num] != NULL) ; + // If a reset happens while we're waiting, abort the transfer if (previous_reset_count != reset_count) return true; - tx_ep = ep_num; - tx_len = total_bytes; - tx_offset = 0; - tx_buffer = buffer; + dcd_int_disable(0); + TU_ASSERT(tx_buffer[ep_num] == NULL); + tx_buffer_offset[ep_num] = 0; + tx_buffer_max[ep_num] = total_bytes; + tx_buffer[ep_num] = buffer; - for (offset = 0; (offset < EP_SIZE) && (offset < total_bytes); offset++) { - usb_in_data_write(buffer[offset]); + // If the current buffer is NULL, then that means the tx logic is idle. + // Update the tx_ep to point to our endpoint number and queue the data. + // Otherwise, let it be and it'll get picked up after the next transfer + // finishes. + if ((tx_buffer[tx_ep] == NULL) || (tx_ep == ep_num)) { + tx_ep = ep_num; + tx_more_data(); } - // Updating the epno queues the data - usb_in_ctrl_write(ep_num & 0xf); + dcd_int_enable(0); } else if (ep_dir == TUSB_DIR_OUT) { - TU_ASSERT(rx_buffer[ep_num] == NULL); + while (rx_buffer[ep_num] != NULL) + ; rx_buffer_offset[ep_num] = 0; rx_buffer_max[ep_num] = total_bytes; - rx_buffer[ep_num] = buffer; - // If there's data in the buffer already, we'll try draining it - // into the current fifo immediately. - usb_out_ev_enable_write(0); - if (usb_out_status_read() & (1 << CSR_USB_OUT_STATUS_HAVE_OFFSET)) - process_rx(false); - usb_out_ev_enable_write(1); + dcd_int_disable(0); + rx_buffer[ep_num] = buffer; + usb_out_ctrl_write((1 << CSR_USB_OUT_CTRL_ENABLE_OFFSET) | ep_num); + + // uint16_t ep_en_mask = usb_out_enable_status_read(); + // int i; + // for (i = 0; i < 16; i++) { + // if ((!!(ep_en_mask & (1 << i))) ^ (!!(rx_buffer[i]))) { + // if (rx_buffer[i] && usb_out_ev_pending_read() && (usb_out_status_read() & 0xf) == i) + // continue; + // fomu_error(__LINE__); + // } + // } + dcd_int_enable(0); } return true; } @@ -339,8 +400,6 @@ void hal_dcd_isr(uint8_t rhport) uint8_t in_pending = usb_in_ev_pending_read(); uint8_t out_pending = usb_out_ev_pending_read(); usb_setup_ev_pending_write(setup_pending); - usb_in_ev_pending_write(in_pending); - usb_out_ev_pending_write(out_pending); // This event means a bus reset occurred. Reset everything, and // abandon any further processing. @@ -352,7 +411,10 @@ void hal_dcd_isr(uint8_t rhport) // An "OUT" transaction just completed so we have new data. // (But only if we can accept the data) // if (out_pending) { - if (usb_out_ev_enable_read() && out_pending) { + if (out_pending) { + if (!usb_out_ev_enable_read()) + fomu_error(__LINE__); + usb_out_ev_pending_write(out_pending); process_rx(true); } @@ -364,35 +426,37 @@ void hal_dcd_isr(uint8_t rhport) // to begin with, then make a subsequent request. If we don't handle // the IN packets first, then the second request will be truncated. if (in_pending) { - finish_tx(); + if (!usb_in_ev_enable_read()) + fomu_error(__LINE__); + usb_in_ev_pending_write(in_pending); + process_tx(true); } // We got a SETUP packet. Copy it to the setup buffer and clear // the "pending" bit. if (setup_pending & 1) { // Setup packets are always 8 bytes, plus two bytes of crc16. - uint8_t setup_packet[10]; uint32_t setup_length = 0; - if (!(usb_setup_status_read() & 1)) + if (!(usb_setup_status_read() & (1 << CSR_USB_SETUP_STATUS_HAVE_OFFSET))) fomu_error(__LINE__); - while (usb_setup_status_read() & 1) { + while (usb_setup_status_read() & (1 << CSR_USB_SETUP_STATUS_HAVE_OFFSET)) { uint8_t c = usb_setup_data_read(); - if (setup_length < sizeof(setup_packet)) - setup_packet[setup_length] = c; + if (setup_length < sizeof(setup_packet_bfr)) + setup_packet_bfr[setup_length] = c; setup_length++; } // If we have 10 bytes, that's a full SETUP packet plus CRC16. // Otherwise, it was an RX error. if (setup_length == 10) { - dcd_event_setup_received(rhport, setup_packet, true); + dcd_event_setup_received(rhport, setup_packet_bfr, true); // Acknowledge the packet, so long as it isn't a SET_ADDRESS // packet. If it is, leave it unacknowledged and we'll do this // in the `dcd_set_address` function instead. - if (!((setup_packet[0] == 0x00) && (setup_packet[1] == 0x05))) - usb_setup_ctrl_write(1 << CSR_USB_SETUP_CTRL_HANDLED_OFFSET); + // if (!((setup_packet_bfr[0] == 0x00) && (setup_packet_bfr[1] == 0x05))) + usb_setup_ctrl_write(1 << CSR_USB_SETUP_CTRL_ACK_OFFSET); } else { fomu_error(__LINE__); From 83bca4a74fce268082996ac098e998445a8a9987 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Thu, 31 Oct 2019 08:34:35 +0800 Subject: [PATCH 039/267] fomu: semi-working commit Signed-off-by: Sean Cross --- hw/bsp/fomu/bsp.c | 7 +- hw/bsp/fomu/include/csr.h | 227 ++++++++++++++++++-------------------- 2 files changed, 112 insertions(+), 122 deletions(-) diff --git a/hw/bsp/fomu/bsp.c b/hw/bsp/fomu/bsp.c index 2bba0ce2..3910cff4 100644 --- a/hw/bsp/fomu/bsp.c +++ b/hw/bsp/fomu/bsp.c @@ -39,8 +39,9 @@ void hal_dcd_isr(uint8_t rhport); void mputs(const char *str) { (void)str; while (*str) { - if (! (messible_status_read() & CSR_MESSIBLE_STATUS_FULL_OFFSET)) - messible_in_write(*str); + while ( (messible_status_read() & CSR_MESSIBLE_STATUS_FULL_OFFSET)) + ; + messible_in_write(*str); str++; } } @@ -54,7 +55,7 @@ void fomu_error(uint32_t line) { (void)line; TU_BREAKPOINT(); - while (1) {} + // while (1) {} } volatile uint32_t system_ticks = 0; diff --git a/hw/bsp/fomu/include/csr.h b/hw/bsp/fomu/include/csr.h index b9bffada..bcd48eb4 100644 --- a/hw/bsp/fomu/include/csr.h +++ b/hw/bsp/fomu/include/csr.h @@ -1,5 +1,5 @@ //-------------------------------------------------------------------------------- -// Auto-generated by Migen (f4fcd10) & LiteX (1425a68d) on 2019-10-11 22:01:17 +// Auto-generated by Migen (f4fcd10) & LiteX (1425a68d) on 2019-10-30 21:48:57 //-------------------------------------------------------------------------------- #ifndef __GENERATED_CSR_H #define __GENERATED_CSR_H @@ -351,93 +351,92 @@ static inline unsigned char usb_pullup_out_read(void) { static inline void usb_pullup_out_write(unsigned char value) { csr_writel(value, 0xe0004800L); } -#define CSR_USB_SETUP_DATA_ADDR 0xe0004804L +#define CSR_USB_ADDRESS_ADDR 0xe0004804L +#define CSR_USB_ADDRESS_SIZE 1 +static inline unsigned char usb_address_read(void) { + unsigned char r = csr_readl(0xe0004804L); + return r; +} +static inline void usb_address_write(unsigned char value) { + csr_writel(value, 0xe0004804L); +} +#define CSR_USB_ADDRESS_ADDR_OFFSET 0 +#define CSR_USB_ADDRESS_ADDR_SIZE 7 +#define CSR_USB_SETUP_DATA_ADDR 0xe0004808L #define CSR_USB_SETUP_DATA_SIZE 1 static inline unsigned char usb_setup_data_read(void) { - unsigned char r = csr_readl(0xe0004804L); + unsigned char r = csr_readl(0xe0004808L); return r; } #define CSR_USB_SETUP_DATA_DATA_OFFSET 0 #define CSR_USB_SETUP_DATA_DATA_SIZE 8 -#define CSR_USB_SETUP_CTRL_ADDR 0xe0004808L +#define CSR_USB_SETUP_CTRL_ADDR 0xe000480cL #define CSR_USB_SETUP_CTRL_SIZE 1 static inline unsigned char usb_setup_ctrl_read(void) { - unsigned char r = csr_readl(0xe0004808L); - return r; -} -static inline void usb_setup_ctrl_write(unsigned char value) { - csr_writel(value, 0xe0004808L); -} -#define CSR_USB_SETUP_CTRL_HANDLED_OFFSET 1 -#define CSR_USB_SETUP_CTRL_HANDLED_SIZE 1 -#define CSR_USB_SETUP_CTRL_RESET_OFFSET 2 -#define CSR_USB_SETUP_CTRL_RESET_SIZE 1 -#define CSR_USB_SETUP_STATUS_ADDR 0xe000480cL -#define CSR_USB_SETUP_STATUS_SIZE 1 -static inline unsigned char usb_setup_status_read(void) { unsigned char r = csr_readl(0xe000480cL); return r; } -#define CSR_USB_SETUP_STATUS_HAVE_OFFSET 0 -#define CSR_USB_SETUP_STATUS_HAVE_SIZE 1 -#define CSR_USB_SETUP_STATUS_IS_IN_OFFSET 1 -#define CSR_USB_SETUP_STATUS_IS_IN_SIZE 1 -#define CSR_USB_SETUP_STATUS_EPNO_OFFSET 2 -#define CSR_USB_SETUP_STATUS_EPNO_SIZE 4 -#define CSR_USB_SETUP_STATUS_PEND_OFFSET 6 -#define CSR_USB_SETUP_STATUS_PEND_SIZE 1 -#define CSR_USB_SETUP_STATUS_DATA_OFFSET 7 -#define CSR_USB_SETUP_STATUS_DATA_SIZE 1 -#define CSR_USB_SETUP_EV_STATUS_ADDR 0xe0004810L -#define CSR_USB_SETUP_EV_STATUS_SIZE 1 -static inline unsigned char usb_setup_ev_status_read(void) { +static inline void usb_setup_ctrl_write(unsigned char value) { + csr_writel(value, 0xe000480cL); +} +#define CSR_USB_SETUP_CTRL_ACK_OFFSET 1 +#define CSR_USB_SETUP_CTRL_ACK_SIZE 1 +#define CSR_USB_SETUP_CTRL_RESET_OFFSET 5 +#define CSR_USB_SETUP_CTRL_RESET_SIZE 1 +#define CSR_USB_SETUP_STATUS_ADDR 0xe0004810L +#define CSR_USB_SETUP_STATUS_SIZE 1 +static inline unsigned char usb_setup_status_read(void) { unsigned char r = csr_readl(0xe0004810L); return r; } -static inline void usb_setup_ev_status_write(unsigned char value) { - csr_writel(value, 0xe0004810L); -} -#define CSR_USB_SETUP_EV_PENDING_ADDR 0xe0004814L -#define CSR_USB_SETUP_EV_PENDING_SIZE 1 -static inline unsigned char usb_setup_ev_pending_read(void) { +#define CSR_USB_SETUP_STATUS_EPNO_OFFSET 0 +#define CSR_USB_SETUP_STATUS_EPNO_SIZE 4 +#define CSR_USB_SETUP_STATUS_HAVE_OFFSET 4 +#define CSR_USB_SETUP_STATUS_HAVE_SIZE 1 +#define CSR_USB_SETUP_STATUS_PEND_OFFSET 5 +#define CSR_USB_SETUP_STATUS_PEND_SIZE 1 +#define CSR_USB_SETUP_STATUS_IS_IN_OFFSET 6 +#define CSR_USB_SETUP_STATUS_IS_IN_SIZE 1 +#define CSR_USB_SETUP_STATUS_DATA_OFFSET 7 +#define CSR_USB_SETUP_STATUS_DATA_SIZE 1 +#define CSR_USB_SETUP_EV_STATUS_ADDR 0xe0004814L +#define CSR_USB_SETUP_EV_STATUS_SIZE 1 +static inline unsigned char usb_setup_ev_status_read(void) { unsigned char r = csr_readl(0xe0004814L); return r; } -static inline void usb_setup_ev_pending_write(unsigned char value) { +static inline void usb_setup_ev_status_write(unsigned char value) { csr_writel(value, 0xe0004814L); } -#define CSR_USB_SETUP_EV_ENABLE_ADDR 0xe0004818L -#define CSR_USB_SETUP_EV_ENABLE_SIZE 1 -static inline unsigned char usb_setup_ev_enable_read(void) { +#define CSR_USB_SETUP_EV_PENDING_ADDR 0xe0004818L +#define CSR_USB_SETUP_EV_PENDING_SIZE 1 +static inline unsigned char usb_setup_ev_pending_read(void) { unsigned char r = csr_readl(0xe0004818L); return r; } -static inline void usb_setup_ev_enable_write(unsigned char value) { +static inline void usb_setup_ev_pending_write(unsigned char value) { csr_writel(value, 0xe0004818L); } -#define CSR_USB_IN_DATA_ADDR 0xe000481cL -#define CSR_USB_IN_DATA_SIZE 1 -static inline unsigned char usb_in_data_read(void) { +#define CSR_USB_SETUP_EV_ENABLE_ADDR 0xe000481cL +#define CSR_USB_SETUP_EV_ENABLE_SIZE 1 +static inline unsigned char usb_setup_ev_enable_read(void) { unsigned char r = csr_readl(0xe000481cL); return r; } -static inline void usb_in_data_write(unsigned char value) { +static inline void usb_setup_ev_enable_write(unsigned char value) { csr_writel(value, 0xe000481cL); } -#define CSR_USB_IN_DATA_DATA_OFFSET 0 -#define CSR_USB_IN_DATA_DATA_SIZE 8 -#define CSR_USB_IN_STATUS_ADDR 0xe0004820L -#define CSR_USB_IN_STATUS_SIZE 1 -static inline unsigned char usb_in_status_read(void) { +#define CSR_USB_IN_DATA_ADDR 0xe0004820L +#define CSR_USB_IN_DATA_SIZE 1 +static inline unsigned char usb_in_data_read(void) { unsigned char r = csr_readl(0xe0004820L); return r; } -#define CSR_USB_IN_STATUS_HAVE_OFFSET 0 -#define CSR_USB_IN_STATUS_HAVE_SIZE 1 -#define CSR_USB_IN_STATUS_IDLE_OFFSET 1 -#define CSR_USB_IN_STATUS_IDLE_SIZE 1 -#define CSR_USB_IN_STATUS_PEND_OFFSET 6 -#define CSR_USB_IN_STATUS_PEND_SIZE 1 +static inline void usb_in_data_write(unsigned char value) { + csr_writel(value, 0xe0004820L); +} +#define CSR_USB_IN_DATA_DATA_OFFSET 0 +#define CSR_USB_IN_DATA_DATA_SIZE 8 #define CSR_USB_IN_CTRL_ADDR 0xe0004824L #define CSR_USB_IN_CTRL_SIZE 1 static inline unsigned char usb_in_ctrl_read(void) { @@ -447,61 +446,59 @@ static inline unsigned char usb_in_ctrl_read(void) { static inline void usb_in_ctrl_write(unsigned char value) { csr_writel(value, 0xe0004824L); } -#define CSR_USB_IN_CTRL_EP_OFFSET 0 -#define CSR_USB_IN_CTRL_EP_SIZE 4 -#define CSR_USB_IN_CTRL_STALL_OFFSET 4 -#define CSR_USB_IN_CTRL_STALL_SIZE 1 +#define CSR_USB_IN_CTRL_EPNO_OFFSET 0 +#define CSR_USB_IN_CTRL_EPNO_SIZE 4 #define CSR_USB_IN_CTRL_RESET_OFFSET 5 #define CSR_USB_IN_CTRL_RESET_SIZE 1 -#define CSR_USB_IN_EV_STATUS_ADDR 0xe0004828L -#define CSR_USB_IN_EV_STATUS_SIZE 1 -static inline unsigned char usb_in_ev_status_read(void) { +#define CSR_USB_IN_CTRL_STALL_OFFSET 6 +#define CSR_USB_IN_CTRL_STALL_SIZE 1 +#define CSR_USB_IN_STATUS_ADDR 0xe0004828L +#define CSR_USB_IN_STATUS_SIZE 1 +static inline unsigned char usb_in_status_read(void) { unsigned char r = csr_readl(0xe0004828L); return r; } -static inline void usb_in_ev_status_write(unsigned char value) { - csr_writel(value, 0xe0004828L); -} -#define CSR_USB_IN_EV_PENDING_ADDR 0xe000482cL -#define CSR_USB_IN_EV_PENDING_SIZE 1 -static inline unsigned char usb_in_ev_pending_read(void) { +#define CSR_USB_IN_STATUS_IDLE_OFFSET 0 +#define CSR_USB_IN_STATUS_IDLE_SIZE 1 +#define CSR_USB_IN_STATUS_HAVE_OFFSET 4 +#define CSR_USB_IN_STATUS_HAVE_SIZE 1 +#define CSR_USB_IN_STATUS_PEND_OFFSET 5 +#define CSR_USB_IN_STATUS_PEND_SIZE 1 +#define CSR_USB_IN_EV_STATUS_ADDR 0xe000482cL +#define CSR_USB_IN_EV_STATUS_SIZE 1 +static inline unsigned char usb_in_ev_status_read(void) { unsigned char r = csr_readl(0xe000482cL); return r; } -static inline void usb_in_ev_pending_write(unsigned char value) { +static inline void usb_in_ev_status_write(unsigned char value) { csr_writel(value, 0xe000482cL); } -#define CSR_USB_IN_EV_ENABLE_ADDR 0xe0004830L -#define CSR_USB_IN_EV_ENABLE_SIZE 1 -static inline unsigned char usb_in_ev_enable_read(void) { +#define CSR_USB_IN_EV_PENDING_ADDR 0xe0004830L +#define CSR_USB_IN_EV_PENDING_SIZE 1 +static inline unsigned char usb_in_ev_pending_read(void) { unsigned char r = csr_readl(0xe0004830L); return r; } -static inline void usb_in_ev_enable_write(unsigned char value) { +static inline void usb_in_ev_pending_write(unsigned char value) { csr_writel(value, 0xe0004830L); } -#define CSR_USB_OUT_DATA_ADDR 0xe0004834L +#define CSR_USB_IN_EV_ENABLE_ADDR 0xe0004834L +#define CSR_USB_IN_EV_ENABLE_SIZE 1 +static inline unsigned char usb_in_ev_enable_read(void) { + unsigned char r = csr_readl(0xe0004834L); + return r; +} +static inline void usb_in_ev_enable_write(unsigned char value) { + csr_writel(value, 0xe0004834L); +} +#define CSR_USB_OUT_DATA_ADDR 0xe0004838L #define CSR_USB_OUT_DATA_SIZE 1 static inline unsigned char usb_out_data_read(void) { - unsigned char r = csr_readl(0xe0004834L); + unsigned char r = csr_readl(0xe0004838L); return r; } #define CSR_USB_OUT_DATA_DATA_OFFSET 0 #define CSR_USB_OUT_DATA_DATA_SIZE 8 -#define CSR_USB_OUT_STATUS_ADDR 0xe0004838L -#define CSR_USB_OUT_STATUS_SIZE 1 -static inline unsigned char usb_out_status_read(void) { - unsigned char r = csr_readl(0xe0004838L); - return r; -} -#define CSR_USB_OUT_STATUS_HAVE_OFFSET 0 -#define CSR_USB_OUT_STATUS_HAVE_SIZE 1 -#define CSR_USB_OUT_STATUS_IDLE_OFFSET 1 -#define CSR_USB_OUT_STATUS_IDLE_SIZE 1 -#define CSR_USB_OUT_STATUS_EPNO_OFFSET 2 -#define CSR_USB_OUT_STATUS_EPNO_SIZE 4 -#define CSR_USB_OUT_STATUS_PEND_OFFSET 6 -#define CSR_USB_OUT_STATUS_PEND_SIZE 1 #define CSR_USB_OUT_CTRL_ADDR 0xe000483cL #define CSR_USB_OUT_CTRL_SIZE 1 static inline unsigned char usb_out_ctrl_read(void) { @@ -511,23 +508,26 @@ static inline unsigned char usb_out_ctrl_read(void) { static inline void usb_out_ctrl_write(unsigned char value) { csr_writel(value, 0xe000483cL); } -#define CSR_USB_OUT_CTRL_ENABLE_OFFSET 1 +#define CSR_USB_OUT_CTRL_EPNO_OFFSET 0 +#define CSR_USB_OUT_CTRL_EPNO_SIZE 4 +#define CSR_USB_OUT_CTRL_ENABLE_OFFSET 4 #define CSR_USB_OUT_CTRL_ENABLE_SIZE 1 -#define CSR_USB_OUT_CTRL_RESET_OFFSET 2 +#define CSR_USB_OUT_CTRL_RESET_OFFSET 5 #define CSR_USB_OUT_CTRL_RESET_SIZE 1 -#define CSR_USB_OUT_STALL_ADDR 0xe0004840L -#define CSR_USB_OUT_STALL_SIZE 1 -static inline unsigned char usb_out_stall_read(void) { +#define CSR_USB_OUT_CTRL_STALL_OFFSET 6 +#define CSR_USB_OUT_CTRL_STALL_SIZE 1 +#define CSR_USB_OUT_STATUS_ADDR 0xe0004840L +#define CSR_USB_OUT_STATUS_SIZE 1 +static inline unsigned char usb_out_status_read(void) { unsigned char r = csr_readl(0xe0004840L); return r; } -static inline void usb_out_stall_write(unsigned char value) { - csr_writel(value, 0xe0004840L); -} -#define CSR_USB_OUT_STALL_EPNO_OFFSET 0 -#define CSR_USB_OUT_STALL_EPNO_SIZE 4 -#define CSR_USB_OUT_STALL_STALL_OFFSET 4 -#define CSR_USB_OUT_STALL_STALL_SIZE 1 +#define CSR_USB_OUT_STATUS_EPNO_OFFSET 0 +#define CSR_USB_OUT_STATUS_EPNO_SIZE 4 +#define CSR_USB_OUT_STATUS_HAVE_OFFSET 4 +#define CSR_USB_OUT_STATUS_HAVE_SIZE 1 +#define CSR_USB_OUT_STATUS_PEND_OFFSET 5 +#define CSR_USB_OUT_STATUS_PEND_SIZE 1 #define CSR_USB_OUT_EV_STATUS_ADDR 0xe0004844L #define CSR_USB_OUT_EV_STATUS_SIZE 1 static inline unsigned char usb_out_ev_status_read(void) { @@ -555,29 +555,18 @@ static inline unsigned char usb_out_ev_enable_read(void) { static inline void usb_out_ev_enable_write(unsigned char value) { csr_writel(value, 0xe000484cL); } -#define CSR_USB_ADDRESS_ADDR 0xe0004850L -#define CSR_USB_ADDRESS_SIZE 1 -static inline unsigned char usb_address_read(void) { +#define CSR_USB_OUT_ENABLE_STATUS_ADDR 0xe0004850L +#define CSR_USB_OUT_ENABLE_STATUS_SIZE 1 +static inline unsigned char usb_out_enable_status_read(void) { unsigned char r = csr_readl(0xe0004850L); return r; } -static inline void usb_address_write(unsigned char value) { - csr_writel(value, 0xe0004850L); -} -#define CSR_USB_ADDRESS_ADDR_OFFSET 0 -#define CSR_USB_ADDRESS_ADDR_SIZE 7 -#define CSR_USB_STAGE_NUM_ADDR 0xe0004854L -#define CSR_USB_STAGE_NUM_SIZE 1 -static inline unsigned char usb_stage_num_read(void) { +#define CSR_USB_OUT_STALL_STATUS_ADDR 0xe0004854L +#define CSR_USB_OUT_STALL_STATUS_SIZE 1 +static inline unsigned char usb_out_stall_status_read(void) { unsigned char r = csr_readl(0xe0004854L); return r; } -#define CSR_USB_LAST_STAGE_NUM_ADDR 0xe0004858L -#define CSR_USB_LAST_STAGE_NUM_SIZE 1 -static inline unsigned char usb_last_stage_num_read(void) { - unsigned char r = csr_readl(0xe0004858L); - return r; -} /* version */ #define CSR_VERSION_BASE 0xe0007000L From 835a72c59599e83183e623972fe85e779ed01383 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Thu, 31 Oct 2019 08:35:04 +0800 Subject: [PATCH 040/267] fomu: semi-working dcd file Signed-off-by: Sean Cross --- src/portable/foosn/fomu/dcd_fomu.c | 133 ++++++++++++++++++++--------- 1 file changed, 93 insertions(+), 40 deletions(-) diff --git a/src/portable/foosn/fomu/dcd_fomu.c b/src/portable/foosn/fomu/dcd_fomu.c index 8b2212c1..07efcce7 100644 --- a/src/portable/foosn/fomu/dcd_fomu.c +++ b/src/portable/foosn/fomu/dcd_fomu.c @@ -26,6 +26,10 @@ #include "tusb_option.h" +#ifndef DEBUG +#define DEBUG 0 +#endif + // #if TUSB_OPT_DEVICE_ENABLED && (CFG_TUSB_MCU == OPT_MCU_FOMU_EPTRI) #if 1 @@ -48,16 +52,17 @@ uint8_t volatile * rx_buffer[16]; uint16_t volatile rx_buffer_max[16]; volatile uint8_t tx_ep; +volatile bool tx_active; volatile uint16_t tx_buffer_offset[16]; uint8_t volatile * tx_buffer[16]; volatile uint16_t tx_buffer_max[16]; volatile uint8_t reset_count; +#ifdef DEBUG __attribute__((used)) uint8_t volatile * last_tx_buffer; __attribute__((used)) volatile uint8_t last_tx_ep; - +#endif uint8_t setup_packet_bfr[10]; - //--------------------------------------------------------------------+ // PIPE HELPER //--------------------------------------------------------------------+ @@ -86,27 +91,35 @@ static void tx_more_data(void) { } static void process_tx(bool in_isr) { - // If the buffer is now empty, search for the next buffer to fill. - if (!tx_buffer[tx_ep]) { - if (advance_tx_ep()) - tx_more_data(); - return; - } - +#if DEBUG // If the system isn't idle, then something is very wrong. uint8_t in_status = usb_in_status_read(); if (!(in_status & (1 << CSR_USB_IN_STATUS_IDLE_OFFSET))) fomu_error(__LINE__); +#endif + + // If the buffer is now empty, search for the next buffer to fill. + if (!tx_buffer[tx_ep]) { + if (advance_tx_ep()) + tx_more_data(); + else + tx_active = false; + return; + } tx_buffer_offset[tx_ep] += EP_SIZE; if (tx_buffer_offset[tx_ep] >= tx_buffer_max[tx_ep]) { +#if DEBUG last_tx_buffer = tx_buffer[tx_ep]; last_tx_ep = tx_ep; +#endif tx_buffer[tx_ep] = NULL; - dcd_event_xfer_complete(0, tu_edpt_addr(tx_ep, TUSB_DIR_IN), tx_buffer_max[tx_ep], XFER_RESULT_SUCCESS, in_isr); if (!advance_tx_ep()) + tx_active = false; + dcd_event_xfer_complete(0, tu_edpt_addr(tx_ep, TUSB_DIR_IN), tx_buffer_max[tx_ep], XFER_RESULT_SUCCESS, in_isr); + if (!tx_active) return; } @@ -115,61 +128,85 @@ static void process_tx(bool in_isr) { } static void process_rx(bool in_isr) { - // If the OUT handler is still waiting to send, don't do anything. uint8_t out_status = usb_out_status_read(); +#if DEBUG + // If the OUT handler is still waiting to send, don't do anything. if (!(out_status & (1 << CSR_USB_OUT_STATUS_HAVE_OFFSET))) fomu_error(__LINE__); // return; - +#endif uint8_t rx_ep = (out_status >> CSR_USB_OUT_STATUS_EPNO_OFFSET) & 0xf; // If the destination buffer doesn't exist, don't drain the hardware // fifo. Note that this can cause deadlocks if the host is waiting // on some other endpoint's data! +#if DEBUG if (rx_buffer[rx_ep] == NULL) { fomu_error(__LINE__); return; } +#endif + // Drain the FIFO into the destination buffer uint32_t total_read = 0; uint32_t current_offset = rx_buffer_offset[rx_ep]; +#if DEBUG if (current_offset > rx_buffer_max[rx_ep]) fomu_error(__LINE__); +#endif while (usb_out_status_read() & (1 << CSR_USB_OUT_STATUS_HAVE_OFFSET)) { uint8_t c = usb_out_data_read(); total_read++; if ((rx_buffer_offset[rx_ep] + current_offset) < rx_buffer_max[rx_ep]) rx_buffer[rx_ep][current_offset++] = c; } +#if DEBUG if (total_read > 66) fomu_error(__LINE__); + if (total_read < 2) + fomu_error(__LINE__); +#endif // Strip off the CRC16 rx_buffer_offset[rx_ep] += (total_read - 2); if (rx_buffer_offset[rx_ep] > rx_buffer_max[rx_ep]) rx_buffer_offset[rx_ep] = rx_buffer_max[rx_ep]; + // If there's no more data, complete the transfer to tinyusb if (rx_buffer_max[rx_ep] == rx_buffer_offset[rx_ep]) { +#if DEBUG if (rx_buffer[rx_ep] == NULL) fomu_error(__LINE__); +#endif - // Disable this endpoint (causing it to respond NAK) until we have - // a buffer to place the data into. + // Free up this buffer. rx_buffer[rx_ep] = NULL; uint16_t len = rx_buffer_offset[rx_ep]; - // uint16_t ep_en_mask = usb_out_enable_status_read(); - // int i; - // for (i = 0; i < 16; i++) { - // if ((!!(ep_en_mask & (1 << i))) ^ (!!(rx_buffer[i]))) - // fomu_error(__LINE__); - // } +#if DEBUG + // Validate that all enabled endpoints have buffers, + // and no disabled endpoints have buffers. + uint16_t ep_en_mask = usb_out_enable_status_read(); + int i; + for (i = 0; i < 16; i++) { + if ((!!(ep_en_mask & (1 << i))) ^ (!!(rx_buffer[i]))) { + uint8_t new_status = usb_out_status_read(); + // Another IRQ came in while we were processing, so ignore this endpoint. + if ((new_status & 0x20) && ((new_status & 0xf) == i)) + continue; + fomu_error(__LINE__); + } + } +#endif dcd_event_xfer_complete(0, tu_edpt_addr(rx_ep, TUSB_DIR_OUT), len, XFER_RESULT_SUCCESS, in_isr); - return; + } + else { + // If there's more data, re-enable data reception on this endpoint + usb_out_ctrl_write((1 << CSR_USB_OUT_CTRL_ENABLE_OFFSET) | rx_ep); } - // If there's more data, re-enable data reception - usb_out_ctrl_write((1 << CSR_USB_OUT_CTRL_ENABLE_OFFSET) | rx_ep); + // Now that the buffer is drained, clear the pending IRQ. + usb_out_ev_pending_write(usb_out_ev_pending_read()); } //--------------------------------------------------------------------+ @@ -198,6 +235,7 @@ static void dcd_reset(void) memset((void *)tx_buffer_max, 0, sizeof(tx_buffer_max)); memset((void *)tx_buffer_offset, 0, sizeof(tx_buffer_offset)); tx_ep = 0; + tx_active = false; // Enable all event handlers and clear their contents usb_setup_ev_pending_write(-1); @@ -251,7 +289,7 @@ void dcd_set_address(uint8_t rhport, uint8_t dev_addr) dcd_edpt_xfer(rhport, tu_edpt_addr(0, TUSB_DIR_IN), NULL, 0); // Wait for the response packet to get sent - while (tx_buffer[0] != NULL) + while (tx_active) ; // Activate the new address @@ -305,8 +343,12 @@ void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr) if (tu_edpt_number(ep_addr) == 2) fomu_error(__LINE__); - if (tu_edpt_dir(ep_addr) == TUSB_DIR_OUT) - usb_out_ctrl_write((1 << CSR_USB_OUT_CTRL_STALL_OFFSET) | (1 << CSR_USB_OUT_CTRL_ENABLE_OFFSET) | tu_edpt_number(ep_addr)); + if (tu_edpt_dir(ep_addr) == TUSB_DIR_OUT) { + uint8_t enable = 0; + if (rx_buffer[ep_addr]) + enable = 1; + usb_out_ctrl_write((1 << CSR_USB_OUT_CTRL_STALL_OFFSET) | (enable << CSR_USB_OUT_CTRL_ENABLE_OFFSET) | tu_edpt_number(ep_addr)); + } else usb_in_ctrl_write((1 << CSR_USB_IN_CTRL_STALL_OFFSET) | tu_edpt_number(ep_addr)); } @@ -359,32 +401,36 @@ bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t* buffer, uint16_t t // Update the tx_ep to point to our endpoint number and queue the data. // Otherwise, let it be and it'll get picked up after the next transfer // finishes. - if ((tx_buffer[tx_ep] == NULL) || (tx_ep == ep_num)) { + if (!tx_active) { tx_ep = ep_num; + tx_active = true; tx_more_data(); } dcd_int_enable(0); } + else if (ep_dir == TUSB_DIR_OUT) { while (rx_buffer[ep_num] != NULL) ; + dcd_int_disable(0); + TU_ASSERT(rx_buffer[ep_num] == NULL); + rx_buffer[ep_num] = buffer; rx_buffer_offset[ep_num] = 0; rx_buffer_max[ep_num] = total_bytes; - dcd_int_disable(0); - rx_buffer[ep_num] = buffer; usb_out_ctrl_write((1 << CSR_USB_OUT_CTRL_ENABLE_OFFSET) | ep_num); - - // uint16_t ep_en_mask = usb_out_enable_status_read(); - // int i; - // for (i = 0; i < 16; i++) { - // if ((!!(ep_en_mask & (1 << i))) ^ (!!(rx_buffer[i]))) { - // if (rx_buffer[i] && usb_out_ev_pending_read() && (usb_out_status_read() & 0xf) == i) - // continue; - // fomu_error(__LINE__); - // } - // } +#if DEBUG + uint16_t ep_en_mask = usb_out_enable_status_read(); + int i; + for (i = 0; i < 16; i++) { + if ((!!(ep_en_mask & (1 << i))) ^ (!!(rx_buffer[i]))) { + if (rx_buffer[i] && usb_out_ev_pending_read() && (usb_out_status_read() & 0xf) == i) + continue; + fomu_error(__LINE__); + } + } +#endif dcd_int_enable(0); } return true; @@ -412,9 +458,10 @@ void hal_dcd_isr(uint8_t rhport) // (But only if we can accept the data) // if (out_pending) { if (out_pending) { +#if DEBUG if (!usb_out_ev_enable_read()) fomu_error(__LINE__); - usb_out_ev_pending_write(out_pending); +#endif process_rx(true); } @@ -426,8 +473,10 @@ void hal_dcd_isr(uint8_t rhport) // to begin with, then make a subsequent request. If we don't handle // the IN packets first, then the second request will be truncated. if (in_pending) { +#if DEBUG if (!usb_in_ev_enable_read()) fomu_error(__LINE__); +#endif usb_in_ev_pending_write(in_pending); process_tx(true); } @@ -438,8 +487,10 @@ void hal_dcd_isr(uint8_t rhport) // Setup packets are always 8 bytes, plus two bytes of crc16. uint32_t setup_length = 0; +#if DEBUG if (!(usb_setup_status_read() & (1 << CSR_USB_SETUP_STATUS_HAVE_OFFSET))) fomu_error(__LINE__); +#endif while (usb_setup_status_read() & (1 << CSR_USB_SETUP_STATUS_HAVE_OFFSET)) { uint8_t c = usb_setup_data_read(); @@ -458,9 +509,11 @@ void hal_dcd_isr(uint8_t rhport) // if (!((setup_packet_bfr[0] == 0x00) && (setup_packet_bfr[1] == 0x05))) usb_setup_ctrl_write(1 << CSR_USB_SETUP_CTRL_ACK_OFFSET); } +#if DEBUG else { fomu_error(__LINE__); } +#endif } } From 913032ae1d1d4a28e295d150bfa636f296be7bb9 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Thu, 31 Oct 2019 11:14:07 +0800 Subject: [PATCH 041/267] dcd_fomu: nearly there Signed-off-by: Sean Cross --- src/portable/foosn/fomu/dcd_fomu.c | 101 ++++++++++++++++------------- 1 file changed, 57 insertions(+), 44 deletions(-) diff --git a/src/portable/foosn/fomu/dcd_fomu.c b/src/portable/foosn/fomu/dcd_fomu.c index 07efcce7..12add4c8 100644 --- a/src/portable/foosn/fomu/dcd_fomu.c +++ b/src/portable/foosn/fomu/dcd_fomu.c @@ -24,11 +24,11 @@ * This file is part of the TinyUSB stack. */ +#ifndef DEBUG +#define DEBUG 1 +#endif #include "tusb_option.h" -#ifndef DEBUG -#define DEBUG 0 -#endif // #if TUSB_OPT_DEVICE_ENABLED && (CFG_TUSB_MCU == OPT_MCU_FOMU_EPTRI) #if 1 @@ -41,6 +41,8 @@ void fomu_error(uint32_t line); void mputs(const char *str); void mputln(const char *str); +static uint8_t last_address; + //--------------------------------------------------------------------+ // SIE Command //--------------------------------------------------------------------+ @@ -58,11 +60,11 @@ uint8_t volatile * tx_buffer[16]; volatile uint16_t tx_buffer_max[16]; volatile uint8_t reset_count; -#ifdef DEBUG +#if DEBUG __attribute__((used)) uint8_t volatile * last_tx_buffer; __attribute__((used)) volatile uint8_t last_tx_ep; -#endif uint8_t setup_packet_bfr[10]; +#endif //--------------------------------------------------------------------+ // PIPE HELPER //--------------------------------------------------------------------+ @@ -82,15 +84,15 @@ static bool advance_tx_ep(void) { static void tx_more_data(void) { // Send more data uint8_t added_bytes; - for (added_bytes = 0; (added_bytes < EP_SIZE) && (added_bytes + tx_buffer_offset[tx_ep] < tx_buffer_max[tx_ep]); added_bytes++) { - usb_in_data_write(tx_buffer[tx_ep][added_bytes + tx_buffer_offset[tx_ep]]); + for (added_bytes = 0; (added_bytes < EP_SIZE) && (tx_buffer_offset[tx_ep] < tx_buffer_max[tx_ep]); added_bytes++) { + usb_in_data_write(tx_buffer[tx_ep][tx_buffer_offset[tx_ep]++]); } // Updating the epno queues the data usb_in_ctrl_write(tx_ep & 0xf); } -static void process_tx(bool in_isr) { +static void process_tx(void) { #if DEBUG // If the system isn't idle, then something is very wrong. uint8_t in_status = usb_in_status_read(); @@ -107,18 +109,20 @@ static void process_tx(bool in_isr) { return; } - tx_buffer_offset[tx_ep] += EP_SIZE; - if (tx_buffer_offset[tx_ep] >= tx_buffer_max[tx_ep]) { #if DEBUG last_tx_buffer = tx_buffer[tx_ep]; last_tx_ep = tx_ep; #endif tx_buffer[tx_ep] = NULL; + uint16_t xferred_bytes = tx_buffer_max[tx_ep]; + uint8_t xferred_ep = tx_ep; if (!advance_tx_ep()) tx_active = false; - dcd_event_xfer_complete(0, tu_edpt_addr(tx_ep, TUSB_DIR_IN), tx_buffer_max[tx_ep], XFER_RESULT_SUCCESS, in_isr); + if ((xferred_bytes == 13) && (tx_buffer_max[tx_ep] == 512)) + fomu_error(__LINE__); + dcd_event_xfer_complete(0, tu_edpt_addr(xferred_ep, TUSB_DIR_IN), xferred_bytes, XFER_RESULT_SUCCESS, true); if (!tx_active) return; } @@ -127,7 +131,7 @@ static void process_tx(bool in_isr) { return; } -static void process_rx(bool in_isr) { +static void process_rx(void) { uint8_t out_status = usb_out_status_read(); #if DEBUG // If the OUT handler is still waiting to send, don't do anything. @@ -190,15 +194,15 @@ static void process_rx(bool in_isr) { int i; for (i = 0; i < 16; i++) { if ((!!(ep_en_mask & (1 << i))) ^ (!!(rx_buffer[i]))) { - uint8_t new_status = usb_out_status_read(); - // Another IRQ came in while we were processing, so ignore this endpoint. - if ((new_status & 0x20) && ((new_status & 0xf) == i)) - continue; + // uint8_t new_status = usb_out_status_read(); + // // Another IRQ came in while we were processing, so ignore this endpoint. + // if ((new_status & 0x20) && ((new_status & 0xf) == i)) + // continue; fomu_error(__LINE__); } } #endif - dcd_event_xfer_complete(0, tu_edpt_addr(rx_ep, TUSB_DIR_OUT), len, XFER_RESULT_SUCCESS, in_isr); + dcd_event_xfer_complete(0, tu_edpt_addr(rx_ep, TUSB_DIR_OUT), len, XFER_RESULT_SUCCESS, true); } else { // If there's more data, re-enable data reception on this endpoint @@ -220,6 +224,8 @@ static void dcd_reset(void) usb_in_ev_enable_write(0); usb_out_ev_enable_write(0); + if (last_address) + asm("ebreak"); usb_address_write(0); // Reset all three FIFO handlers @@ -294,6 +300,7 @@ void dcd_set_address(uint8_t rhport, uint8_t dev_addr) // Activate the new address usb_address_write(dev_addr); + last_address = dev_addr; } // Called when the device received SET_CONFIG request, you can leave this @@ -387,11 +394,13 @@ bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t* buffer, uint16_t t while (tx_buffer[ep_num] != NULL) ; + dcd_int_disable(0); + if (total_bytes == 499) + asm("ebreak"); // If a reset happens while we're waiting, abort the transfer if (previous_reset_count != reset_count) return true; - dcd_int_disable(0); TU_ASSERT(tx_buffer[ep_num] == NULL); tx_buffer_offset[ep_num] = 0; tx_buffer_max[ep_num] = total_bytes; @@ -419,18 +428,19 @@ bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t* buffer, uint16_t t rx_buffer_offset[ep_num] = 0; rx_buffer_max[ep_num] = total_bytes; + // Enable receiving on this particular endpoint usb_out_ctrl_write((1 << CSR_USB_OUT_CTRL_ENABLE_OFFSET) | ep_num); -#if DEBUG - uint16_t ep_en_mask = usb_out_enable_status_read(); - int i; - for (i = 0; i < 16; i++) { - if ((!!(ep_en_mask & (1 << i))) ^ (!!(rx_buffer[i]))) { - if (rx_buffer[i] && usb_out_ev_pending_read() && (usb_out_status_read() & 0xf) == i) - continue; - fomu_error(__LINE__); - } - } -#endif +// #if DEBUG +// uint16_t ep_en_mask = usb_out_enable_status_read(); +// int i; +// for (i = 0; i < 16; i++) { +// if ((!!(ep_en_mask & (1 << i))) ^ (!!(rx_buffer[i]))) { +// if (rx_buffer[i] && usb_out_ev_pending_read() && (usb_out_status_read() & 0xf) == i) +// continue; +// fomu_error(__LINE__); +// } +// } +// #endif dcd_int_enable(0); } return true; @@ -442,9 +452,12 @@ bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t* buffer, uint16_t t void hal_dcd_isr(uint8_t rhport) { - uint8_t setup_pending = usb_setup_ev_pending_read(); - uint8_t in_pending = usb_in_ev_pending_read(); - uint8_t out_pending = usb_out_ev_pending_read(); + uint8_t setup_pending = usb_setup_ev_pending_read() & usb_setup_ev_enable_read(); + uint8_t in_pending = usb_in_ev_pending_read() & usb_in_ev_enable_read(); + uint8_t out_pending = usb_out_ev_pending_read() & usb_out_ev_enable_read(); +#if !DEBUG + uint8_t setup_packet_bfr[10]; +#endif usb_setup_ev_pending_write(setup_pending); // This event means a bus reset occurred. Reset everything, and @@ -454,17 +467,6 @@ void hal_dcd_isr(uint8_t rhport) return; } - // An "OUT" transaction just completed so we have new data. - // (But only if we can accept the data) - // if (out_pending) { - if (out_pending) { -#if DEBUG - if (!usb_out_ev_enable_read()) - fomu_error(__LINE__); -#endif - process_rx(true); - } - // An "IN" transaction just completed. // Note that due to the way tinyusb's callback system is implemented, // we must handle IN and OUT packets before we handle SETUP packets. @@ -478,9 +480,20 @@ void hal_dcd_isr(uint8_t rhport) fomu_error(__LINE__); #endif usb_in_ev_pending_write(in_pending); - process_tx(true); + process_tx(); } + // An "OUT" transaction just completed so we have new data. + // (But only if we can accept the data) + // if (out_pending) { + if (out_pending) { +#if DEBUG + if (!usb_out_ev_enable_read()) + fomu_error(__LINE__); +#endif + process_rx(); + } + // We got a SETUP packet. Copy it to the setup buffer and clear // the "pending" bit. if (setup_pending & 1) { From 77cf0b5bfdba4aa97da4e75f0217048106bec151 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Fri, 1 Nov 2019 12:31:01 +0800 Subject: [PATCH 042/267] fomu: csr: add version with next_ev register The Fomu bitstream now includes a `USB_NEXT_EV` register to indicate which is the next logical event to process. Add this register to the CSR definition. Signed-off-by: Sean Cross --- hw/bsp/fomu/include/csr.h | 168 +++++++++++++++++++++----------------- 1 file changed, 91 insertions(+), 77 deletions(-) diff --git a/hw/bsp/fomu/include/csr.h b/hw/bsp/fomu/include/csr.h index bcd48eb4..01ef754b 100644 --- a/hw/bsp/fomu/include/csr.h +++ b/hw/bsp/fomu/include/csr.h @@ -1,5 +1,5 @@ //-------------------------------------------------------------------------------- -// Auto-generated by Migen (f4fcd10) & LiteX (1425a68d) on 2019-10-30 21:48:57 +// Auto-generated by Migen (f4fcd10) & LiteX (1425a68d) on 2019-11-01 12:04:21 //-------------------------------------------------------------------------------- #ifndef __GENERATED_CSR_H #define __GENERATED_CSR_H @@ -362,31 +362,45 @@ static inline void usb_address_write(unsigned char value) { } #define CSR_USB_ADDRESS_ADDR_OFFSET 0 #define CSR_USB_ADDRESS_ADDR_SIZE 7 -#define CSR_USB_SETUP_DATA_ADDR 0xe0004808L +#define CSR_USB_NEXT_EV_ADDR 0xe0004808L +#define CSR_USB_NEXT_EV_SIZE 1 +static inline unsigned char usb_next_ev_read(void) { + unsigned char r = csr_readl(0xe0004808L); + return r; +} +#define CSR_USB_NEXT_EV_IN_OFFSET 0 +#define CSR_USB_NEXT_EV_IN_SIZE 1 +#define CSR_USB_NEXT_EV_OUT_OFFSET 1 +#define CSR_USB_NEXT_EV_OUT_SIZE 1 +#define CSR_USB_NEXT_EV_SETUP_OFFSET 2 +#define CSR_USB_NEXT_EV_SETUP_SIZE 1 +#define CSR_USB_NEXT_EV_RESET_OFFSET 3 +#define CSR_USB_NEXT_EV_RESET_SIZE 1 +#define CSR_USB_SETUP_DATA_ADDR 0xe000480cL #define CSR_USB_SETUP_DATA_SIZE 1 static inline unsigned char usb_setup_data_read(void) { - unsigned char r = csr_readl(0xe0004808L); + unsigned char r = csr_readl(0xe000480cL); return r; } #define CSR_USB_SETUP_DATA_DATA_OFFSET 0 #define CSR_USB_SETUP_DATA_DATA_SIZE 8 -#define CSR_USB_SETUP_CTRL_ADDR 0xe000480cL +#define CSR_USB_SETUP_CTRL_ADDR 0xe0004810L #define CSR_USB_SETUP_CTRL_SIZE 1 static inline unsigned char usb_setup_ctrl_read(void) { - unsigned char r = csr_readl(0xe000480cL); + unsigned char r = csr_readl(0xe0004810L); return r; } static inline void usb_setup_ctrl_write(unsigned char value) { - csr_writel(value, 0xe000480cL); + csr_writel(value, 0xe0004810L); } #define CSR_USB_SETUP_CTRL_ACK_OFFSET 1 #define CSR_USB_SETUP_CTRL_ACK_SIZE 1 #define CSR_USB_SETUP_CTRL_RESET_OFFSET 5 #define CSR_USB_SETUP_CTRL_RESET_SIZE 1 -#define CSR_USB_SETUP_STATUS_ADDR 0xe0004810L +#define CSR_USB_SETUP_STATUS_ADDR 0xe0004814L #define CSR_USB_SETUP_STATUS_SIZE 1 static inline unsigned char usb_setup_status_read(void) { - unsigned char r = csr_readl(0xe0004810L); + unsigned char r = csr_readl(0xe0004814L); return r; } #define CSR_USB_SETUP_STATUS_EPNO_OFFSET 0 @@ -399,63 +413,63 @@ static inline unsigned char usb_setup_status_read(void) { #define CSR_USB_SETUP_STATUS_IS_IN_SIZE 1 #define CSR_USB_SETUP_STATUS_DATA_OFFSET 7 #define CSR_USB_SETUP_STATUS_DATA_SIZE 1 -#define CSR_USB_SETUP_EV_STATUS_ADDR 0xe0004814L +#define CSR_USB_SETUP_EV_STATUS_ADDR 0xe0004818L #define CSR_USB_SETUP_EV_STATUS_SIZE 1 static inline unsigned char usb_setup_ev_status_read(void) { - unsigned char r = csr_readl(0xe0004814L); - return r; -} -static inline void usb_setup_ev_status_write(unsigned char value) { - csr_writel(value, 0xe0004814L); -} -#define CSR_USB_SETUP_EV_PENDING_ADDR 0xe0004818L -#define CSR_USB_SETUP_EV_PENDING_SIZE 1 -static inline unsigned char usb_setup_ev_pending_read(void) { unsigned char r = csr_readl(0xe0004818L); return r; } -static inline void usb_setup_ev_pending_write(unsigned char value) { +static inline void usb_setup_ev_status_write(unsigned char value) { csr_writel(value, 0xe0004818L); } -#define CSR_USB_SETUP_EV_ENABLE_ADDR 0xe000481cL -#define CSR_USB_SETUP_EV_ENABLE_SIZE 1 -static inline unsigned char usb_setup_ev_enable_read(void) { +#define CSR_USB_SETUP_EV_PENDING_ADDR 0xe000481cL +#define CSR_USB_SETUP_EV_PENDING_SIZE 1 +static inline unsigned char usb_setup_ev_pending_read(void) { unsigned char r = csr_readl(0xe000481cL); return r; } -static inline void usb_setup_ev_enable_write(unsigned char value) { +static inline void usb_setup_ev_pending_write(unsigned char value) { csr_writel(value, 0xe000481cL); } -#define CSR_USB_IN_DATA_ADDR 0xe0004820L -#define CSR_USB_IN_DATA_SIZE 1 -static inline unsigned char usb_in_data_read(void) { +#define CSR_USB_SETUP_EV_ENABLE_ADDR 0xe0004820L +#define CSR_USB_SETUP_EV_ENABLE_SIZE 1 +static inline unsigned char usb_setup_ev_enable_read(void) { unsigned char r = csr_readl(0xe0004820L); return r; } -static inline void usb_in_data_write(unsigned char value) { +static inline void usb_setup_ev_enable_write(unsigned char value) { csr_writel(value, 0xe0004820L); } -#define CSR_USB_IN_DATA_DATA_OFFSET 0 -#define CSR_USB_IN_DATA_DATA_SIZE 8 -#define CSR_USB_IN_CTRL_ADDR 0xe0004824L -#define CSR_USB_IN_CTRL_SIZE 1 -static inline unsigned char usb_in_ctrl_read(void) { +#define CSR_USB_IN_DATA_ADDR 0xe0004824L +#define CSR_USB_IN_DATA_SIZE 1 +static inline unsigned char usb_in_data_read(void) { unsigned char r = csr_readl(0xe0004824L); return r; } -static inline void usb_in_ctrl_write(unsigned char value) { +static inline void usb_in_data_write(unsigned char value) { csr_writel(value, 0xe0004824L); } +#define CSR_USB_IN_DATA_DATA_OFFSET 0 +#define CSR_USB_IN_DATA_DATA_SIZE 8 +#define CSR_USB_IN_CTRL_ADDR 0xe0004828L +#define CSR_USB_IN_CTRL_SIZE 1 +static inline unsigned char usb_in_ctrl_read(void) { + unsigned char r = csr_readl(0xe0004828L); + return r; +} +static inline void usb_in_ctrl_write(unsigned char value) { + csr_writel(value, 0xe0004828L); +} #define CSR_USB_IN_CTRL_EPNO_OFFSET 0 #define CSR_USB_IN_CTRL_EPNO_SIZE 4 #define CSR_USB_IN_CTRL_RESET_OFFSET 5 #define CSR_USB_IN_CTRL_RESET_SIZE 1 #define CSR_USB_IN_CTRL_STALL_OFFSET 6 #define CSR_USB_IN_CTRL_STALL_SIZE 1 -#define CSR_USB_IN_STATUS_ADDR 0xe0004828L +#define CSR_USB_IN_STATUS_ADDR 0xe000482cL #define CSR_USB_IN_STATUS_SIZE 1 static inline unsigned char usb_in_status_read(void) { - unsigned char r = csr_readl(0xe0004828L); + unsigned char r = csr_readl(0xe000482cL); return r; } #define CSR_USB_IN_STATUS_IDLE_OFFSET 0 @@ -464,49 +478,49 @@ static inline unsigned char usb_in_status_read(void) { #define CSR_USB_IN_STATUS_HAVE_SIZE 1 #define CSR_USB_IN_STATUS_PEND_OFFSET 5 #define CSR_USB_IN_STATUS_PEND_SIZE 1 -#define CSR_USB_IN_EV_STATUS_ADDR 0xe000482cL +#define CSR_USB_IN_EV_STATUS_ADDR 0xe0004830L #define CSR_USB_IN_EV_STATUS_SIZE 1 static inline unsigned char usb_in_ev_status_read(void) { - unsigned char r = csr_readl(0xe000482cL); - return r; -} -static inline void usb_in_ev_status_write(unsigned char value) { - csr_writel(value, 0xe000482cL); -} -#define CSR_USB_IN_EV_PENDING_ADDR 0xe0004830L -#define CSR_USB_IN_EV_PENDING_SIZE 1 -static inline unsigned char usb_in_ev_pending_read(void) { unsigned char r = csr_readl(0xe0004830L); return r; } -static inline void usb_in_ev_pending_write(unsigned char value) { +static inline void usb_in_ev_status_write(unsigned char value) { csr_writel(value, 0xe0004830L); } -#define CSR_USB_IN_EV_ENABLE_ADDR 0xe0004834L -#define CSR_USB_IN_EV_ENABLE_SIZE 1 -static inline unsigned char usb_in_ev_enable_read(void) { +#define CSR_USB_IN_EV_PENDING_ADDR 0xe0004834L +#define CSR_USB_IN_EV_PENDING_SIZE 1 +static inline unsigned char usb_in_ev_pending_read(void) { unsigned char r = csr_readl(0xe0004834L); return r; } -static inline void usb_in_ev_enable_write(unsigned char value) { +static inline void usb_in_ev_pending_write(unsigned char value) { csr_writel(value, 0xe0004834L); } -#define CSR_USB_OUT_DATA_ADDR 0xe0004838L +#define CSR_USB_IN_EV_ENABLE_ADDR 0xe0004838L +#define CSR_USB_IN_EV_ENABLE_SIZE 1 +static inline unsigned char usb_in_ev_enable_read(void) { + unsigned char r = csr_readl(0xe0004838L); + return r; +} +static inline void usb_in_ev_enable_write(unsigned char value) { + csr_writel(value, 0xe0004838L); +} +#define CSR_USB_OUT_DATA_ADDR 0xe000483cL #define CSR_USB_OUT_DATA_SIZE 1 static inline unsigned char usb_out_data_read(void) { - unsigned char r = csr_readl(0xe0004838L); + unsigned char r = csr_readl(0xe000483cL); return r; } #define CSR_USB_OUT_DATA_DATA_OFFSET 0 #define CSR_USB_OUT_DATA_DATA_SIZE 8 -#define CSR_USB_OUT_CTRL_ADDR 0xe000483cL +#define CSR_USB_OUT_CTRL_ADDR 0xe0004840L #define CSR_USB_OUT_CTRL_SIZE 1 static inline unsigned char usb_out_ctrl_read(void) { - unsigned char r = csr_readl(0xe000483cL); + unsigned char r = csr_readl(0xe0004840L); return r; } static inline void usb_out_ctrl_write(unsigned char value) { - csr_writel(value, 0xe000483cL); + csr_writel(value, 0xe0004840L); } #define CSR_USB_OUT_CTRL_EPNO_OFFSET 0 #define CSR_USB_OUT_CTRL_EPNO_SIZE 4 @@ -516,10 +530,10 @@ static inline void usb_out_ctrl_write(unsigned char value) { #define CSR_USB_OUT_CTRL_RESET_SIZE 1 #define CSR_USB_OUT_CTRL_STALL_OFFSET 6 #define CSR_USB_OUT_CTRL_STALL_SIZE 1 -#define CSR_USB_OUT_STATUS_ADDR 0xe0004840L +#define CSR_USB_OUT_STATUS_ADDR 0xe0004844L #define CSR_USB_OUT_STATUS_SIZE 1 static inline unsigned char usb_out_status_read(void) { - unsigned char r = csr_readl(0xe0004840L); + unsigned char r = csr_readl(0xe0004844L); return r; } #define CSR_USB_OUT_STATUS_EPNO_OFFSET 0 @@ -528,43 +542,43 @@ static inline unsigned char usb_out_status_read(void) { #define CSR_USB_OUT_STATUS_HAVE_SIZE 1 #define CSR_USB_OUT_STATUS_PEND_OFFSET 5 #define CSR_USB_OUT_STATUS_PEND_SIZE 1 -#define CSR_USB_OUT_EV_STATUS_ADDR 0xe0004844L +#define CSR_USB_OUT_EV_STATUS_ADDR 0xe0004848L #define CSR_USB_OUT_EV_STATUS_SIZE 1 static inline unsigned char usb_out_ev_status_read(void) { - unsigned char r = csr_readl(0xe0004844L); - return r; -} -static inline void usb_out_ev_status_write(unsigned char value) { - csr_writel(value, 0xe0004844L); -} -#define CSR_USB_OUT_EV_PENDING_ADDR 0xe0004848L -#define CSR_USB_OUT_EV_PENDING_SIZE 1 -static inline unsigned char usb_out_ev_pending_read(void) { unsigned char r = csr_readl(0xe0004848L); return r; } -static inline void usb_out_ev_pending_write(unsigned char value) { +static inline void usb_out_ev_status_write(unsigned char value) { csr_writel(value, 0xe0004848L); } -#define CSR_USB_OUT_EV_ENABLE_ADDR 0xe000484cL -#define CSR_USB_OUT_EV_ENABLE_SIZE 1 -static inline unsigned char usb_out_ev_enable_read(void) { +#define CSR_USB_OUT_EV_PENDING_ADDR 0xe000484cL +#define CSR_USB_OUT_EV_PENDING_SIZE 1 +static inline unsigned char usb_out_ev_pending_read(void) { unsigned char r = csr_readl(0xe000484cL); return r; } -static inline void usb_out_ev_enable_write(unsigned char value) { +static inline void usb_out_ev_pending_write(unsigned char value) { csr_writel(value, 0xe000484cL); } -#define CSR_USB_OUT_ENABLE_STATUS_ADDR 0xe0004850L -#define CSR_USB_OUT_ENABLE_STATUS_SIZE 1 -static inline unsigned char usb_out_enable_status_read(void) { +#define CSR_USB_OUT_EV_ENABLE_ADDR 0xe0004850L +#define CSR_USB_OUT_EV_ENABLE_SIZE 1 +static inline unsigned char usb_out_ev_enable_read(void) { unsigned char r = csr_readl(0xe0004850L); return r; } -#define CSR_USB_OUT_STALL_STATUS_ADDR 0xe0004854L +static inline void usb_out_ev_enable_write(unsigned char value) { + csr_writel(value, 0xe0004850L); +} +#define CSR_USB_OUT_ENABLE_STATUS_ADDR 0xe0004854L +#define CSR_USB_OUT_ENABLE_STATUS_SIZE 1 +static inline unsigned char usb_out_enable_status_read(void) { + unsigned char r = csr_readl(0xe0004854L); + return r; +} +#define CSR_USB_OUT_STALL_STATUS_ADDR 0xe0004858L #define CSR_USB_OUT_STALL_STATUS_SIZE 1 static inline unsigned char usb_out_stall_status_read(void) { - unsigned char r = csr_readl(0xe0004854L); + unsigned char r = csr_readl(0xe0004858L); return r; } From 729c8d073ce9df2bdf5d1c94a5ff63b2ffc2f48b Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Fri, 1 Nov 2019 12:31:17 +0800 Subject: [PATCH 043/267] fomu: dcd_fomu: add next_ev support Now that we have the `USB_NEXT_EV` register, take advantage of it to work around issue #207. Signed-off-by: Sean Cross --- src/portable/foosn/fomu/dcd_fomu.c | 206 ++++++++++++++++++++--------- 1 file changed, 144 insertions(+), 62 deletions(-) diff --git a/src/portable/foosn/fomu/dcd_fomu.c b/src/portable/foosn/fomu/dcd_fomu.c index 12add4c8..29bd7d48 100644 --- a/src/portable/foosn/fomu/dcd_fomu.c +++ b/src/portable/foosn/fomu/dcd_fomu.c @@ -29,7 +29,6 @@ #endif #include "tusb_option.h" - // #if TUSB_OPT_DEVICE_ENABLED && (CFG_TUSB_MCU == OPT_MCU_FOMU_EPTRI) #if 1 @@ -41,6 +40,30 @@ void fomu_error(uint32_t line); void mputs(const char *str); void mputln(const char *str); +struct usb_log { + uint8_t ep_num; + uint8_t size; + uint8_t data[66]; +}; +__attribute__((used)) +struct usb_log usb_log[128]; +__attribute__((used)) +uint8_t usb_log_offset; + +struct xfer_log { + uint8_t ep_num; + uint16_t size; +}; +__attribute__((used)) +struct xfer_log xfer_log[64]; +__attribute__((used)) +uint8_t xfer_log_offset; + +__attribute__((used)) +struct xfer_log queue_log[64]; +__attribute__((used)) +uint8_t queue_log_offset; + static uint8_t last_address; //--------------------------------------------------------------------+ @@ -65,6 +88,7 @@ __attribute__((used)) uint8_t volatile * last_tx_buffer; __attribute__((used)) volatile uint8_t last_tx_ep; uint8_t setup_packet_bfr[10]; #endif + //--------------------------------------------------------------------+ // PIPE HELPER //--------------------------------------------------------------------+ @@ -81,13 +105,36 @@ static bool advance_tx_ep(void) { return true; } +void xfer_log_append(uint8_t ep_num, uint16_t sz) { + xfer_log[xfer_log_offset].ep_num = ep_num; + xfer_log[xfer_log_offset].size = sz; + xfer_log_offset++; + if (xfer_log_offset > sizeof(xfer_log)/sizeof(*xfer_log)) + xfer_log_offset = 0; +} + +void queue_log_append(uint8_t ep_num, uint16_t sz) { + queue_log[queue_log_offset].ep_num = ep_num; + queue_log[queue_log_offset].size = sz; + queue_log_offset++; + if (queue_log_offset > sizeof(queue_log)/sizeof(*queue_log)) + queue_log_offset = 0; +} + static void tx_more_data(void) { // Send more data uint8_t added_bytes; for (added_bytes = 0; (added_bytes < EP_SIZE) && (tx_buffer_offset[tx_ep] < tx_buffer_max[tx_ep]); added_bytes++) { + usb_log[usb_log_offset].data[added_bytes] = tx_buffer[tx_ep][tx_buffer_offset[tx_ep]]; usb_in_data_write(tx_buffer[tx_ep][tx_buffer_offset[tx_ep]++]); } + usb_log[usb_log_offset].ep_num = tu_edpt_addr(tx_ep, TUSB_DIR_IN); + usb_log[usb_log_offset].size = added_bytes; + usb_log_offset++; + if (usb_log_offset > sizeof(usb_log)/sizeof(*usb_log)) + usb_log_offset = 0; + // Updating the epno queues the data usb_in_ctrl_write(tx_ep & 0xf); } @@ -122,6 +169,7 @@ static void process_tx(void) { tx_active = false; if ((xferred_bytes == 13) && (tx_buffer_max[tx_ep] == 512)) fomu_error(__LINE__); + xfer_log_append(tu_edpt_addr(xferred_ep, TUSB_DIR_IN), xferred_bytes); dcd_event_xfer_complete(0, tu_edpt_addr(xferred_ep, TUSB_DIR_IN), xferred_bytes, XFER_RESULT_SUCCESS, true); if (!tx_active) return; @@ -158,12 +206,19 @@ static void process_rx(void) { if (current_offset > rx_buffer_max[rx_ep]) fomu_error(__LINE__); #endif + usb_log[usb_log_offset].ep_num = tu_edpt_addr(rx_ep, TUSB_DIR_OUT); + usb_log[usb_log_offset].size = 0; while (usb_out_status_read() & (1 << CSR_USB_OUT_STATUS_HAVE_OFFSET)) { uint8_t c = usb_out_data_read(); total_read++; - if ((rx_buffer_offset[rx_ep] + current_offset) < rx_buffer_max[rx_ep]) + if ((rx_buffer_offset[rx_ep] + current_offset) < rx_buffer_max[rx_ep]) { + usb_log[usb_log_offset].data[usb_log[usb_log_offset].size++] = c; rx_buffer[rx_ep][current_offset++] = c; + } } + usb_log_offset++; + if (usb_log_offset > sizeof(usb_log)/sizeof(*usb_log)) + usb_log_offset = 0; #if DEBUG if (total_read > 66) fomu_error(__LINE__); @@ -202,6 +257,7 @@ static void process_rx(void) { } } #endif + xfer_log_append(tu_edpt_addr(rx_ep, TUSB_DIR_OUT), len); dcd_event_xfer_complete(0, tu_edpt_addr(rx_ep, TUSB_DIR_OUT), len, XFER_RESULT_SUCCESS, true); } else { @@ -395,6 +451,7 @@ bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t* buffer, uint16_t t ; dcd_int_disable(0); + queue_log_append(ep_addr, total_bytes); if (total_bytes == 499) asm("ebreak"); // If a reset happens while we're waiting, abort the transfer @@ -422,8 +479,9 @@ bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t* buffer, uint16_t t while (rx_buffer[ep_num] != NULL) ; - dcd_int_disable(0); TU_ASSERT(rx_buffer[ep_num] == NULL); + dcd_int_disable(0); + queue_log_append(ep_addr, total_bytes); rx_buffer[ep_num] = buffer; rx_buffer_offset[ep_num] = 0; rx_buffer_max[ep_num] = total_bytes; @@ -450,83 +508,107 @@ bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t* buffer, uint16_t t // ISR //--------------------------------------------------------------------+ -void hal_dcd_isr(uint8_t rhport) +static void handle_out(void) +{ + // An "OUT" transaction just completed so we have new data. + // (But only if we can accept the data) +#if DEBUG + if (!usb_out_ev_pending_read()) + fomu_error(__LINE__); + if (!usb_out_ev_enable_read()) + fomu_error(__LINE__); +#endif + process_rx(); +} + +static void handle_in(void) +{ +#if DEBUG + if (!usb_in_ev_pending_read()) + fomu_error(__LINE__); + if (!usb_in_ev_enable_read()) + fomu_error(__LINE__); +#endif + usb_in_ev_pending_write(usb_in_ev_pending_read()); + process_tx(); +} + +static void handle_reset(void) { uint8_t setup_pending = usb_setup_ev_pending_read() & usb_setup_ev_enable_read(); - uint8_t in_pending = usb_in_ev_pending_read() & usb_in_ev_enable_read(); - uint8_t out_pending = usb_out_ev_pending_read() & usb_out_ev_enable_read(); -#if !DEBUG - uint8_t setup_packet_bfr[10]; -#endif - usb_setup_ev_pending_write(setup_pending); + if (!(setup_pending & 2)) + fomu_error(__LINE__); + usb_setup_ev_pending_write(2); // This event means a bus reset occurred. Reset everything, and // abandon any further processing. - if (setup_pending & 2) { - dcd_reset(); - return; - } + dcd_reset(); +} - // An "IN" transaction just completed. - // Note that due to the way tinyusb's callback system is implemented, - // we must handle IN and OUT packets before we handle SETUP packets. - // This ensures that any responses to SETUP packets aren't overwritten. - // For example, oftentimes a host will request part of a descriptor - // to begin with, then make a subsequent request. If we don't handle - // the IN packets first, then the second request will be truncated. - if (in_pending) { -#if DEBUG - if (!usb_in_ev_enable_read()) - fomu_error(__LINE__); +static void handle_setup(void) +{ +#if !DEBUG + uint8_t setup_packet_bfr[10]; #endif - usb_in_ev_pending_write(in_pending); - process_tx(); - } - // An "OUT" transaction just completed so we have new data. - // (But only if we can accept the data) - // if (out_pending) { - if (out_pending) { -#if DEBUG - if (!usb_out_ev_enable_read()) - fomu_error(__LINE__); -#endif - process_rx(); - } + uint8_t setup_pending = usb_setup_ev_pending_read() & usb_setup_ev_enable_read(); + if (!(setup_pending & 1)) + fomu_error(__LINE__); // We got a SETUP packet. Copy it to the setup buffer and clear // the "pending" bit. - if (setup_pending & 1) { - // Setup packets are always 8 bytes, plus two bytes of crc16. - uint32_t setup_length = 0; + // Setup packets are always 8 bytes, plus two bytes of crc16. + uint32_t setup_length = 0; #if DEBUG - if (!(usb_setup_status_read() & (1 << CSR_USB_SETUP_STATUS_HAVE_OFFSET))) - fomu_error(__LINE__); + if (!(usb_setup_status_read() & (1 << CSR_USB_SETUP_STATUS_HAVE_OFFSET))) + fomu_error(__LINE__); #endif - while (usb_setup_status_read() & (1 << CSR_USB_SETUP_STATUS_HAVE_OFFSET)) { - uint8_t c = usb_setup_data_read(); - if (setup_length < sizeof(setup_packet_bfr)) - setup_packet_bfr[setup_length] = c; - setup_length++; - } + while (usb_setup_status_read() & (1 << CSR_USB_SETUP_STATUS_HAVE_OFFSET)) { + uint8_t c = usb_setup_data_read(); + if (setup_length < sizeof(setup_packet_bfr)) + setup_packet_bfr[setup_length] = c; + setup_length++; + } - // If we have 10 bytes, that's a full SETUP packet plus CRC16. - // Otherwise, it was an RX error. - if (setup_length == 10) { - dcd_event_setup_received(rhport, setup_packet_bfr, true); - // Acknowledge the packet, so long as it isn't a SET_ADDRESS - // packet. If it is, leave it unacknowledged and we'll do this - // in the `dcd_set_address` function instead. - // if (!((setup_packet_bfr[0] == 0x00) && (setup_packet_bfr[1] == 0x05))) - usb_setup_ctrl_write(1 << CSR_USB_SETUP_CTRL_ACK_OFFSET); - } + // If we have 10 bytes, that's a full SETUP packet plus CRC16. + // Otherwise, it was an RX error. + if (setup_length == 10) { + dcd_event_setup_received(0, setup_packet_bfr, true); + // Acknowledge the packet, so long as it isn't a SET_ADDRESS + // packet. If it is, leave it unacknowledged and we'll do this + // in the `dcd_set_address` function instead. + // if (!((setup_packet_bfr[0] == 0x00) && (setup_packet_bfr[1] == 0x05))) + usb_setup_ctrl_write(1 << CSR_USB_SETUP_CTRL_ACK_OFFSET); + } #if DEBUG - else { - fomu_error(__LINE__); - } + else { + fomu_error(__LINE__); + } #endif + + usb_setup_ev_pending_write(1); +} +void hal_dcd_isr(uint8_t rhport) +{ + (void)rhport; + uint8_t next_ev; + while ((next_ev = usb_next_ev_read())) { + switch (next_ev) { + case 1 << CSR_USB_NEXT_EV_IN_OFFSET: + handle_in(); + break; + case 1 << CSR_USB_NEXT_EV_OUT_OFFSET: + handle_out(); + break; + case 1 << CSR_USB_NEXT_EV_SETUP_OFFSET: + handle_setup(); + break; + case 1 << CSR_USB_NEXT_EV_RESET_OFFSET: + handle_reset(); + break; + } } } From 1882a87212859e352502bddaccf973d2fd08ad09 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Fri, 1 Nov 2019 16:57:39 +0800 Subject: [PATCH 044/267] fomu: remove reference to SETUP_CTRL.ACK THis bit isn't used anymore, so remove it. Signed-off-by: Sean Cross --- src/portable/foosn/fomu/dcd_fomu.c | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/portable/foosn/fomu/dcd_fomu.c b/src/portable/foosn/fomu/dcd_fomu.c index 29bd7d48..a77f548c 100644 --- a/src/portable/foosn/fomu/dcd_fomu.c +++ b/src/portable/foosn/fomu/dcd_fomu.c @@ -576,11 +576,6 @@ static void handle_setup(void) // Otherwise, it was an RX error. if (setup_length == 10) { dcd_event_setup_received(0, setup_packet_bfr, true); - // Acknowledge the packet, so long as it isn't a SET_ADDRESS - // packet. If it is, leave it unacknowledged and we'll do this - // in the `dcd_set_address` function instead. - // if (!((setup_packet_bfr[0] == 0x00) && (setup_packet_bfr[1] == 0x05))) - usb_setup_ctrl_write(1 << CSR_USB_SETUP_CTRL_ACK_OFFSET); } #if DEBUG else { From f087cb1580d7167da54698a9c5d5d4d978084dac Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Tue, 12 Nov 2019 20:21:06 -0800 Subject: [PATCH 045/267] fomu: crt0: minor text refactor Signed-off-by: Sean Cross --- hw/bsp/fomu/crt0-vexriscv.S | 14 +++----------- 1 file changed, 3 insertions(+), 11 deletions(-) diff --git a/hw/bsp/fomu/crt0-vexriscv.S b/hw/bsp/fomu/crt0-vexriscv.S index 46dca557..d80a29e0 100644 --- a/hw/bsp/fomu/crt0-vexriscv.S +++ b/hw/bsp/fomu/crt0-vexriscv.S @@ -6,13 +6,6 @@ _start: j crt_init - nop - nop - nop - nop - nop - nop - nop .section .text .global trap_entry @@ -53,9 +46,8 @@ trap_entry: lw x31, 0*4(sp) addi sp,sp,16*4 mret - .text - +.text crt_init: la sp, _estack - 4 la a0, trap_entry @@ -87,5 +79,5 @@ bss_done: csrw mie,a0 call main -infinit_loop: - j infinit_loop +infinite_loop: + j infinite_loop From 25d5628063846d5e4601607afc72e7ef3cbbd1a9 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Tue, 12 Nov 2019 20:21:17 -0800 Subject: [PATCH 046/267] fomu: csr: sync csr Signed-off-by: Sean Cross --- hw/bsp/fomu/include/csr.h | 130 ++++++++++++++++++++++++-------------- 1 file changed, 84 insertions(+), 46 deletions(-) diff --git a/hw/bsp/fomu/include/csr.h b/hw/bsp/fomu/include/csr.h index 01ef754b..a2f60ecf 100644 --- a/hw/bsp/fomu/include/csr.h +++ b/hw/bsp/fomu/include/csr.h @@ -1,5 +1,5 @@ //-------------------------------------------------------------------------------- -// Auto-generated by Migen (f4fcd10) & LiteX (1425a68d) on 2019-11-01 12:04:21 +// Auto-generated by Migen (f4fcd10) & LiteX (1425a68d) on 2019-11-12 19:41:49 //-------------------------------------------------------------------------------- #ifndef __GENERATED_CSR_H #define __GENERATED_CSR_H @@ -57,41 +57,6 @@ static inline unsigned int ctrl_bus_errors_read(void) { return r; } -/* lxspi */ -#define CSR_LXSPI_BASE 0xe0007800L -#define CSR_LXSPI_BITBANG_ADDR 0xe0007800L -#define CSR_LXSPI_BITBANG_SIZE 1 -static inline unsigned char lxspi_bitbang_read(void) { - unsigned char r = csr_readl(0xe0007800L); - return r; -} -static inline void lxspi_bitbang_write(unsigned char value) { - csr_writel(value, 0xe0007800L); -} -#define CSR_LXSPI_BITBANG_MOSI_OFFSET 0 -#define CSR_LXSPI_BITBANG_MOSI_SIZE 1 -#define CSR_LXSPI_BITBANG_CLK_OFFSET 1 -#define CSR_LXSPI_BITBANG_CLK_SIZE 1 -#define CSR_LXSPI_BITBANG_CS_N_OFFSET 2 -#define CSR_LXSPI_BITBANG_CS_N_SIZE 1 -#define CSR_LXSPI_BITBANG_DIR_OFFSET 3 -#define CSR_LXSPI_BITBANG_DIR_SIZE 1 -#define CSR_LXSPI_MISO_ADDR 0xe0007804L -#define CSR_LXSPI_MISO_SIZE 1 -static inline unsigned char lxspi_miso_read(void) { - unsigned char r = csr_readl(0xe0007804L); - return r; -} -#define CSR_LXSPI_BITBANG_EN_ADDR 0xe0007808L -#define CSR_LXSPI_BITBANG_EN_SIZE 1 -static inline unsigned char lxspi_bitbang_en_read(void) { - unsigned char r = csr_readl(0xe0007808L); - return r; -} -static inline void lxspi_bitbang_en_write(unsigned char value) { - csr_writel(value, 0xe0007808L); -} - /* messible */ #define CSR_MESSIBLE_BASE 0xe0008000L #define CSR_MESSIBLE_IN_ADDR 0xe0008000L @@ -120,6 +85,89 @@ static inline unsigned char messible_status_read(void) { #define CSR_MESSIBLE_STATUS_HAVE_OFFSET 1 #define CSR_MESSIBLE_STATUS_HAVE_SIZE 1 +/* picorvspi */ +#define CSR_PICORVSPI_BASE 0xe0005000L +#define CSR_PICORVSPI_CFG1_ADDR 0xe0005000L +#define CSR_PICORVSPI_CFG1_SIZE 1 +static inline unsigned char picorvspi_cfg1_read(void) { + unsigned char r = csr_readl(0xe0005000L); + return r; +} +static inline void picorvspi_cfg1_write(unsigned char value) { + csr_writel(value, 0xe0005000L); +} +#define CSR_PICORVSPI_CFG1_BB_OUT_OFFSET 0 +#define CSR_PICORVSPI_CFG1_BB_OUT_SIZE 4 +#define CSR_PICORVSPI_CFG1_BB_CLK_OFFSET 4 +#define CSR_PICORVSPI_CFG1_BB_CLK_SIZE 1 +#define CSR_PICORVSPI_CFG1_BB_CS_OFFSET 5 +#define CSR_PICORVSPI_CFG1_BB_CS_SIZE 1 +#define CSR_PICORVSPI_CFG2_ADDR 0xe0005004L +#define CSR_PICORVSPI_CFG2_SIZE 1 +static inline unsigned char picorvspi_cfg2_read(void) { + unsigned char r = csr_readl(0xe0005004L); + return r; +} +static inline void picorvspi_cfg2_write(unsigned char value) { + csr_writel(value, 0xe0005004L); +} +#define CSR_PICORVSPI_CFG2_BB_OE_OFFSET 0 +#define CSR_PICORVSPI_CFG2_BB_OE_SIZE 4 +#define CSR_PICORVSPI_CFG3_ADDR 0xe0005008L +#define CSR_PICORVSPI_CFG3_SIZE 1 +static inline unsigned char picorvspi_cfg3_read(void) { + unsigned char r = csr_readl(0xe0005008L); + return r; +} +static inline void picorvspi_cfg3_write(unsigned char value) { + csr_writel(value, 0xe0005008L); +} +#define CSR_PICORVSPI_CFG3_RLAT_OFFSET 0 +#define CSR_PICORVSPI_CFG3_RLAT_SIZE 4 +#define CSR_PICORVSPI_CFG3_CRM_OFFSET 4 +#define CSR_PICORVSPI_CFG3_CRM_SIZE 1 +#define CSR_PICORVSPI_CFG3_QSPI_OFFSET 5 +#define CSR_PICORVSPI_CFG3_QSPI_SIZE 1 +#define CSR_PICORVSPI_CFG3_DDR_OFFSET 6 +#define CSR_PICORVSPI_CFG3_DDR_SIZE 1 +#define CSR_PICORVSPI_CFG4_ADDR 0xe000500cL +#define CSR_PICORVSPI_CFG4_SIZE 1 +static inline unsigned char picorvspi_cfg4_read(void) { + unsigned char r = csr_readl(0xe000500cL); + return r; +} +static inline void picorvspi_cfg4_write(unsigned char value) { + csr_writel(value, 0xe000500cL); +} +#define CSR_PICORVSPI_CFG4_MEMIO_OFFSET 7 +#define CSR_PICORVSPI_CFG4_MEMIO_SIZE 1 +#define CSR_PICORVSPI_STAT1_ADDR 0xe0005010L +#define CSR_PICORVSPI_STAT1_SIZE 1 +static inline unsigned char picorvspi_stat1_read(void) { + unsigned char r = csr_readl(0xe0005010L); + return r; +} +#define CSR_PICORVSPI_STAT1_BB_IN_OFFSET 0 +#define CSR_PICORVSPI_STAT1_BB_IN_SIZE 4 +#define CSR_PICORVSPI_STAT2_ADDR 0xe0005014L +#define CSR_PICORVSPI_STAT2_SIZE 1 +static inline unsigned char picorvspi_stat2_read(void) { + unsigned char r = csr_readl(0xe0005014L); + return r; +} +#define CSR_PICORVSPI_STAT3_ADDR 0xe0005018L +#define CSR_PICORVSPI_STAT3_SIZE 1 +static inline unsigned char picorvspi_stat3_read(void) { + unsigned char r = csr_readl(0xe0005018L); + return r; +} +#define CSR_PICORVSPI_STAT4_ADDR 0xe000501cL +#define CSR_PICORVSPI_STAT4_SIZE 1 +static inline unsigned char picorvspi_stat4_read(void) { + unsigned char r = csr_readl(0xe000501cL); + return r; +} + /* reboot */ #define CSR_REBOOT_BASE 0xe0006000L #define CSR_REBOOT_CTRL_ADDR 0xe0006000L @@ -393,8 +441,6 @@ static inline unsigned char usb_setup_ctrl_read(void) { static inline void usb_setup_ctrl_write(unsigned char value) { csr_writel(value, 0xe0004810L); } -#define CSR_USB_SETUP_CTRL_ACK_OFFSET 1 -#define CSR_USB_SETUP_CTRL_ACK_SIZE 1 #define CSR_USB_SETUP_CTRL_RESET_OFFSET 5 #define CSR_USB_SETUP_CTRL_RESET_SIZE 1 #define CSR_USB_SETUP_STATUS_ADDR 0xe0004814L @@ -660,14 +706,6 @@ static inline int timer0_interrupt_read(void) { static inline int usb_interrupt_read(void) { return 3; } -#define SPI_BOOT 1 -static inline int spi_boot_read(void) { - return 1; -} -#define SPI_ENTRYPOINT 536977408 -static inline int spi_entrypoint_read(void) { - return 536977408; -} #define CONFIG_BITSTREAM_SYNC_HEADER1 2123999870 static inline int config_bitstream_sync_header1_read(void) { return 2123999870; From 3292920933a35c98ecaf88062020cceb6a9bd5c2 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Tue, 12 Nov 2019 20:22:00 -0800 Subject: [PATCH 047/267] fomu: first stable working commit This appears to be stable, and works well. Signed-off-by: Sean Cross --- src/portable/foosn/fomu/dcd_fomu.c | 50 ++++++++++++++++-------------- 1 file changed, 27 insertions(+), 23 deletions(-) diff --git a/src/portable/foosn/fomu/dcd_fomu.c b/src/portable/foosn/fomu/dcd_fomu.c index a77f548c..49ad7d4b 100644 --- a/src/portable/foosn/fomu/dcd_fomu.c +++ b/src/portable/foosn/fomu/dcd_fomu.c @@ -109,7 +109,7 @@ void xfer_log_append(uint8_t ep_num, uint16_t sz) { xfer_log[xfer_log_offset].ep_num = ep_num; xfer_log[xfer_log_offset].size = sz; xfer_log_offset++; - if (xfer_log_offset > sizeof(xfer_log)/sizeof(*xfer_log)) + if (xfer_log_offset >= sizeof(xfer_log)/sizeof(*xfer_log)) xfer_log_offset = 0; } @@ -117,7 +117,7 @@ void queue_log_append(uint8_t ep_num, uint16_t sz) { queue_log[queue_log_offset].ep_num = ep_num; queue_log[queue_log_offset].size = sz; queue_log_offset++; - if (queue_log_offset > sizeof(queue_log)/sizeof(*queue_log)) + if (queue_log_offset >= sizeof(queue_log)/sizeof(*queue_log)) queue_log_offset = 0; } @@ -132,7 +132,7 @@ static void tx_more_data(void) { usb_log[usb_log_offset].ep_num = tu_edpt_addr(tx_ep, TUSB_DIR_IN); usb_log[usb_log_offset].size = added_bytes; usb_log_offset++; - if (usb_log_offset > sizeof(usb_log)/sizeof(*usb_log)) + if (usb_log_offset >= sizeof(usb_log)/sizeof(*usb_log)) usb_log_offset = 0; // Updating the epno queues the data @@ -167,8 +167,6 @@ static void process_tx(void) { if (!advance_tx_ep()) tx_active = false; - if ((xferred_bytes == 13) && (tx_buffer_max[tx_ep] == 512)) - fomu_error(__LINE__); xfer_log_append(tu_edpt_addr(xferred_ep, TUSB_DIR_IN), xferred_bytes); dcd_event_xfer_complete(0, tu_edpt_addr(xferred_ep, TUSB_DIR_IN), xferred_bytes, XFER_RESULT_SUCCESS, true); if (!tx_active) @@ -213,17 +211,19 @@ static void process_rx(void) { total_read++; if ((rx_buffer_offset[rx_ep] + current_offset) < rx_buffer_max[rx_ep]) { usb_log[usb_log_offset].data[usb_log[usb_log_offset].size++] = c; - rx_buffer[rx_ep][current_offset++] = c; + if (rx_buffer[rx_ep] != (volatile uint8_t *)0xffffffff) + rx_buffer[rx_ep][current_offset++] = c; } } usb_log_offset++; - if (usb_log_offset > sizeof(usb_log)/sizeof(*usb_log)) + if (usb_log_offset >= sizeof(usb_log)/sizeof(*usb_log)) usb_log_offset = 0; #if DEBUG if (total_read > 66) fomu_error(__LINE__); if (total_read < 2) - fomu_error(__LINE__); + total_read = 2; + // fomu_error(__LINE__); #endif // Strip off the CRC16 @@ -232,7 +232,11 @@ static void process_rx(void) { rx_buffer_offset[rx_ep] = rx_buffer_max[rx_ep]; // If there's no more data, complete the transfer to tinyusb - if (rx_buffer_max[rx_ep] == rx_buffer_offset[rx_ep]) { + if ((rx_buffer_max[rx_ep] == rx_buffer_offset[rx_ep]) + // ZLP with less than the total amount of data + || ((total_read == 2) && ((rx_buffer_offset[rx_ep] & 63) == 0)) + // Short read, but not a full packet + || (((rx_buffer_offset[rx_ep] & 63) != 0) && (total_read < 66))) { #if DEBUG if (rx_buffer[rx_ep] == NULL) fomu_error(__LINE__); @@ -249,10 +253,10 @@ static void process_rx(void) { int i; for (i = 0; i < 16; i++) { if ((!!(ep_en_mask & (1 << i))) ^ (!!(rx_buffer[i]))) { - // uint8_t new_status = usb_out_status_read(); - // // Another IRQ came in while we were processing, so ignore this endpoint. - // if ((new_status & 0x20) && ((new_status & 0xf) == i)) - // continue; + uint8_t new_status = usb_out_status_read(); + // Another IRQ came in while we were processing, so ignore this endpoint. + if ((new_status & 0x20) && ((new_status & 0xf) == i)) + continue; fomu_error(__LINE__); } } @@ -280,8 +284,8 @@ static void dcd_reset(void) usb_in_ev_enable_write(0); usb_out_ev_enable_write(0); - if (last_address) - asm("ebreak"); + // if (last_address) + // asm("ebreak"); usb_address_write(0); // Reset all three FIFO handlers @@ -300,9 +304,9 @@ static void dcd_reset(void) tx_active = false; // Enable all event handlers and clear their contents - usb_setup_ev_pending_write(-1); - usb_in_ev_pending_write(-1); - usb_out_ev_pending_write(-1); + usb_setup_ev_pending_write(0xff); + usb_in_ev_pending_write(0xff); + usb_out_ev_pending_write(0xff); usb_in_ev_enable_write(1); usb_out_ev_enable_write(1); usb_setup_ev_enable_write(3); @@ -535,9 +539,9 @@ static void handle_in(void) static void handle_reset(void) { - uint8_t setup_pending = usb_setup_ev_pending_read() & usb_setup_ev_enable_read(); - if (!(setup_pending & 2)) - fomu_error(__LINE__); + // uint8_t setup_pending = usb_setup_ev_pending_read() & usb_setup_ev_enable_read(); + // if (!(setup_pending & 2)) + // fomu_error(__LINE__); usb_setup_ev_pending_write(2); // This event means a bus reset occurred. Reset everything, and @@ -592,8 +596,8 @@ void hal_dcd_isr(uint8_t rhport) while ((next_ev = usb_next_ev_read())) { switch (next_ev) { case 1 << CSR_USB_NEXT_EV_IN_OFFSET: - handle_in(); - break; + handle_in(); + break; case 1 << CSR_USB_NEXT_EV_OUT_OFFSET: handle_out(); break; From e05e9801e46e19bc541c1ca7d6a2cc37902f6b2a Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Tue, 12 Nov 2019 20:55:48 -0800 Subject: [PATCH 048/267] fomu: gate debug/logging features This gates the majority of the debug and logging features behind testable macros. Signed-off-by: Sean Cross --- src/portable/foosn/fomu/dcd_fomu.c | 80 +++++++++++++++++++----------- 1 file changed, 52 insertions(+), 28 deletions(-) diff --git a/src/portable/foosn/fomu/dcd_fomu.c b/src/portable/foosn/fomu/dcd_fomu.c index 49ad7d4b..ee79366e 100644 --- a/src/portable/foosn/fomu/dcd_fomu.c +++ b/src/portable/foosn/fomu/dcd_fomu.c @@ -25,21 +25,24 @@ */ #ifndef DEBUG -#define DEBUG 1 +#define DEBUG 0 #endif + +#ifndef LOG_USB +#define LOG_USB 0 +#endif + #include "tusb_option.h" -// #if TUSB_OPT_DEVICE_ENABLED && (CFG_TUSB_MCU == OPT_MCU_FOMU_EPTRI) -#if 1 +#if TUSB_OPT_DEVICE_ENABLED && (CFG_TUSB_MCU == OPT_MCU_FOMU_EPTRI) #include "device/dcd.h" #include "dcd_fomu.h" #include "csr.h" #include "irq.h" void fomu_error(uint32_t line); -void mputs(const char *str); -void mputln(const char *str); +#if LOG_USB struct usb_log { uint8_t ep_num; uint8_t size; @@ -63,8 +66,7 @@ __attribute__((used)) struct xfer_log queue_log[64]; __attribute__((used)) uint8_t queue_log_offset; - -static uint8_t last_address; +#endif //--------------------------------------------------------------------+ // SIE Command @@ -105,6 +107,7 @@ static bool advance_tx_ep(void) { return true; } +#if LOG_USB void xfer_log_append(uint8_t ep_num, uint16_t sz) { xfer_log[xfer_log_offset].ep_num = ep_num; xfer_log[xfer_log_offset].size = sz; @@ -120,20 +123,25 @@ void queue_log_append(uint8_t ep_num, uint16_t sz) { if (queue_log_offset >= sizeof(queue_log)/sizeof(*queue_log)) queue_log_offset = 0; } +#endif static void tx_more_data(void) { // Send more data uint8_t added_bytes; for (added_bytes = 0; (added_bytes < EP_SIZE) && (tx_buffer_offset[tx_ep] < tx_buffer_max[tx_ep]); added_bytes++) { +#if LOG_USB usb_log[usb_log_offset].data[added_bytes] = tx_buffer[tx_ep][tx_buffer_offset[tx_ep]]; +#endif usb_in_data_write(tx_buffer[tx_ep][tx_buffer_offset[tx_ep]++]); } +#if LOG_USB usb_log[usb_log_offset].ep_num = tu_edpt_addr(tx_ep, TUSB_DIR_IN); usb_log[usb_log_offset].size = added_bytes; usb_log_offset++; if (usb_log_offset >= sizeof(usb_log)/sizeof(*usb_log)) usb_log_offset = 0; +#endif // Updating the epno queues the data usb_in_ctrl_write(tx_ep & 0xf); @@ -167,7 +175,9 @@ static void process_tx(void) { if (!advance_tx_ep()) tx_active = false; +#if LOG_USB xfer_log_append(tu_edpt_addr(xferred_ep, TUSB_DIR_IN), xferred_bytes); +#endif dcd_event_xfer_complete(0, tu_edpt_addr(xferred_ep, TUSB_DIR_IN), xferred_bytes, XFER_RESULT_SUCCESS, true); if (!tx_active) return; @@ -201,23 +211,34 @@ static void process_rx(void) { uint32_t total_read = 0; uint32_t current_offset = rx_buffer_offset[rx_ep]; #if DEBUG + uint8_t test_buffer[256]; + memset(test_buffer, 0, sizeof(test_buffer)); if (current_offset > rx_buffer_max[rx_ep]) fomu_error(__LINE__); #endif +#if LOG_USB usb_log[usb_log_offset].ep_num = tu_edpt_addr(rx_ep, TUSB_DIR_OUT); usb_log[usb_log_offset].size = 0; +#endif while (usb_out_status_read() & (1 << CSR_USB_OUT_STATUS_HAVE_OFFSET)) { uint8_t c = usb_out_data_read(); +#if DEBUG + test_buffer[total_read] = c; +#endif total_read++; if ((rx_buffer_offset[rx_ep] + current_offset) < rx_buffer_max[rx_ep]) { +#if LOG_USB usb_log[usb_log_offset].data[usb_log[usb_log_offset].size++] = c; +#endif if (rx_buffer[rx_ep] != (volatile uint8_t *)0xffffffff) rx_buffer[rx_ep][current_offset++] = c; } } +#if LOG_USB usb_log_offset++; if (usb_log_offset >= sizeof(usb_log)/sizeof(*usb_log)) usb_log_offset = 0; +#endif #if DEBUG if (total_read > 66) fomu_error(__LINE__); @@ -261,7 +282,9 @@ static void process_rx(void) { } } #endif +#if LOG_USB xfer_log_append(tu_edpt_addr(rx_ep, TUSB_DIR_OUT), len); +#endif dcd_event_xfer_complete(0, tu_edpt_addr(rx_ep, TUSB_DIR_OUT), len, XFER_RESULT_SUCCESS, true); } else { @@ -284,8 +307,6 @@ static void dcd_reset(void) usb_in_ev_enable_write(0); usb_out_ev_enable_write(0); - // if (last_address) - // asm("ebreak"); usb_address_write(0); // Reset all three FIFO handlers @@ -360,7 +381,6 @@ void dcd_set_address(uint8_t rhport, uint8_t dev_addr) // Activate the new address usb_address_write(dev_addr); - last_address = dev_addr; } // Called when the device received SET_CONFIG request, you can leave this @@ -407,8 +427,6 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc) void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr) { (void) rhport; - if (tu_edpt_number(ep_addr) == 2) - fomu_error(__LINE__); if (tu_edpt_dir(ep_addr) == TUSB_DIR_OUT) { uint8_t enable = 0; @@ -455,9 +473,9 @@ bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t* buffer, uint16_t t ; dcd_int_disable(0); +#if LOG_USB queue_log_append(ep_addr, total_bytes); - if (total_bytes == 499) - asm("ebreak"); +#endif // If a reset happens while we're waiting, abort the transfer if (previous_reset_count != reset_count) return true; @@ -485,24 +503,26 @@ bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t* buffer, uint16_t t TU_ASSERT(rx_buffer[ep_num] == NULL); dcd_int_disable(0); +#if LOG_USB queue_log_append(ep_addr, total_bytes); +#endif rx_buffer[ep_num] = buffer; rx_buffer_offset[ep_num] = 0; rx_buffer_max[ep_num] = total_bytes; // Enable receiving on this particular endpoint usb_out_ctrl_write((1 << CSR_USB_OUT_CTRL_ENABLE_OFFSET) | ep_num); -// #if DEBUG -// uint16_t ep_en_mask = usb_out_enable_status_read(); -// int i; -// for (i = 0; i < 16; i++) { -// if ((!!(ep_en_mask & (1 << i))) ^ (!!(rx_buffer[i]))) { -// if (rx_buffer[i] && usb_out_ev_pending_read() && (usb_out_status_read() & 0xf) == i) -// continue; -// fomu_error(__LINE__); -// } -// } -// #endif +#if DEBUG + uint16_t ep_en_mask = usb_out_enable_status_read(); + int i; + for (i = 0; i < 16; i++) { + if ((!!(ep_en_mask & (1 << i))) ^ (!!(rx_buffer[i]))) { + if (rx_buffer[i] && usb_out_ev_pending_read() && (usb_out_status_read() & 0xf) == i) + continue; + fomu_error(__LINE__); + } + } +#endif dcd_int_enable(0); } return true; @@ -539,9 +559,11 @@ static void handle_in(void) static void handle_reset(void) { - // uint8_t setup_pending = usb_setup_ev_pending_read() & usb_setup_ev_enable_read(); - // if (!(setup_pending & 2)) - // fomu_error(__LINE__); +#if DEBUG + uint8_t setup_pending = usb_setup_ev_pending_read() & usb_setup_ev_enable_read(); + if (!(setup_pending & 2)) + fomu_error(__LINE__); +#endif usb_setup_ev_pending_write(2); // This event means a bus reset occurred. Reset everything, and @@ -555,9 +577,11 @@ static void handle_setup(void) uint8_t setup_packet_bfr[10]; #endif +#if DEBUG uint8_t setup_pending = usb_setup_ev_pending_read() & usb_setup_ev_enable_read(); if (!(setup_pending & 1)) fomu_error(__LINE__); +#endif // We got a SETUP packet. Copy it to the setup buffer and clear // the "pending" bit. From 8c5f02960b7d41f663b0c6063a0cc268ef8d2270 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Tue, 12 Nov 2019 21:11:46 -0800 Subject: [PATCH 049/267] valentyusb: rename from `foosn` While Fomu is produced by Foosn, the actual name of the hardware block is `valentyusb`. Rename the module to match that. Signed-off-by: Sean Cross --- hw/bsp/fomu/board.mk | 6 +- src/portable/foosn/fomu/dcd_fomu.h | 151 ------------------ .../eptri/dcd_eptri.c} | 4 +- src/portable/valentyusb/eptri/dcd_eptri.h | 39 +++++ .../eptri/hal_eptri.c} | 2 +- 5 files changed, 45 insertions(+), 157 deletions(-) delete mode 100644 src/portable/foosn/fomu/dcd_fomu.h rename src/portable/{foosn/fomu/dcd_fomu.c => valentyusb/eptri/dcd_eptri.c} (99%) create mode 100644 src/portable/valentyusb/eptri/dcd_eptri.h rename src/portable/{foosn/fomu/hal_fomu.c => valentyusb/eptri/hal_eptri.c} (96%) diff --git a/hw/bsp/fomu/board.mk b/hw/bsp/fomu/board.mk index 86f8df23..cdcd63b2 100644 --- a/hw/bsp/fomu/board.mk +++ b/hw/bsp/fomu/board.mk @@ -2,7 +2,7 @@ CFLAGS += \ -march=rv32i \ -mabi=ilp32 \ -nostdlib \ - -DCFG_TUSB_MCU=OPT_MCU_FOMU_EPTRI + -DCFG_TUSB_MCU=OPT_MCU_VALENTYUSB_EPTRI MCU_DIR = hw/mcu/fomu BSP_DIR = hw/bsp/fomu @@ -21,8 +21,8 @@ INC += \ $(TOP)/$(BSP_DIR)/include # For TinyUSB port source -VENDOR = foosn -CHIP_FAMILY = fomu +VENDOR = valentyusb +CHIP_FAMILY = eptri # flash using dfu-util flash: $(BUILD)/$(BOARD)-firmware.dfu diff --git a/src/portable/foosn/fomu/dcd_fomu.h b/src/portable/foosn/fomu/dcd_fomu.h deleted file mode 100644 index 60bc1240..00000000 --- a/src/portable/foosn/fomu/dcd_fomu.h +++ /dev/null @@ -1,151 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2019 Ha Thach (tinyusb.org) - * - * 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. - * - * This file is part of the TinyUSB stack. - */ - -#ifndef _TUSB_DCD_FOMU_H_ -#define _TUSB_DCD_FOMU_H_ - -#include "common/tusb_common.h" -#ifdef __cplusplus - extern "C" { -#endif - -// //--------------------------------------------------------------------+ -// // Register Interface -// //--------------------------------------------------------------------+ - -// //------------- USB Interrupt USBIntSt -------------// -// //enum { -// // DCD_USB_REQ_LOW_PRIO_MASK = TU_BIT(0), -// // DCD_USB_REQ_HIGH_PRIO_MASK = TU_BIT(1), -// // DCD_USB_REQ_DMA_MASK = TU_BIT(2), -// // DCD_USB_REQ_NEED_CLOCK_MASK = TU_BIT(8), -// // DCD_USB_REQ_ENABLE_MASK = TU_BIT(31) -// //}; - -// //------------- Device Interrupt USBDevInt -------------// -// enum { -// DEV_INT_FRAME_MASK = TU_BIT(0), -// DEV_INT_ENDPOINT_FAST_MASK = TU_BIT(1), -// DEV_INT_ENDPOINT_SLOW_MASK = TU_BIT(2), -// DEV_INT_DEVICE_STATUS_MASK = TU_BIT(3), -// DEV_INT_COMMAND_CODE_EMPTY_MASK = TU_BIT(4), -// DEV_INT_COMMAND_DATA_FULL_MASK = TU_BIT(5), -// DEV_INT_RX_ENDPOINT_PACKET_MASK = TU_BIT(6), -// DEV_INT_TX_ENDPOINT_PACKET_MASK = TU_BIT(7), -// DEV_INT_ENDPOINT_REALIZED_MASK = TU_BIT(8), -// DEV_INT_ERROR_MASK = TU_BIT(9) -// }; - -// //------------- DMA Interrupt USBDMAInt-------------// -// enum { -// DMA_INT_END_OF_XFER_MASK = TU_BIT(0), -// DMA_INT_NEW_DD_REQUEST_MASK = TU_BIT(1), -// DMA_INT_ERROR_MASK = TU_BIT(2) -// }; - -// //------------- USBCtrl -------------// -// enum { -// USBCTRL_READ_ENABLE_MASK = TU_BIT(0), -// USBCTRL_WRITE_ENABLE_MASK = TU_BIT(1), -// }; - -// //------------- USBRxPLen -------------// -// enum { -// USBRXPLEN_PACKET_LENGTH_MASK = (TU_BIT(10)-1), -// USBRXPLEN_DATA_VALID_MASK = TU_BIT(10), -// USBRXPLEN_PACKET_READY_MASK = TU_BIT(11), -// }; - -// //------------- SIE Command Code -------------// -// typedef enum -// { -// SIE_CMDPHASE_WRITE = 1, -// SIE_CMDPHASE_READ = 2, -// SIE_CMDPHASE_COMMAND = 5 -// } sie_cmdphase_t; - -// enum { -// // device commands -// SIE_CMDCODE_SET_ADDRESS = 0xd0, -// SIE_CMDCODE_CONFIGURE_DEVICE = 0xd8, -// SIE_CMDCODE_SET_MODE = 0xf3, -// SIE_CMDCODE_READ_FRAME_NUMBER = 0xf5, -// SIE_CMDCODE_READ_TEST_REGISTER = 0xfd, -// SIE_CMDCODE_DEVICE_STATUS = 0xfe, -// SIE_CMDCODE_GET_ERROR = 0xff, -// SIE_CMDCODE_READ_ERROR_STATUS = 0xfb, - -// // endpoint commands -// SIE_CMDCODE_ENDPOINT_SELECT = 0x00, // + endpoint index -// SIE_CMDCODE_ENDPOINT_SELECT_CLEAR_INTERRUPT = 0x40, // + endpoint index, should use USBEpIntClr instead -// SIE_CMDCODE_ENDPOINT_SET_STATUS = 0x40, // + endpoint index -// SIE_CMDCODE_BUFFER_CLEAR = 0xf2, -// SIE_CMDCODE_BUFFER_VALIDATE = 0xfa -// }; - -// //------------- SIE Device Status (get/set from SIE_CMDCODE_DEVICE_STATUS) -------------// -// enum { -// SIE_DEV_STATUS_CONNECT_STATUS_MASK = TU_BIT(0), -// SIE_DEV_STATUS_CONNECT_CHANGE_MASK = TU_BIT(1), -// SIE_DEV_STATUS_SUSPEND_MASK = TU_BIT(2), -// SIE_DEV_STATUS_SUSPEND_CHANGE_MASK = TU_BIT(3), -// SIE_DEV_STATUS_RESET_MASK = TU_BIT(4) -// }; - -// //------------- SIE Select Endpoint Command -------------// -// enum { -// SIE_SELECT_ENDPOINT_FULL_EMPTY_MASK = TU_BIT(0), // 0: empty, 1 full. IN endpoint checks empty, OUT endpoint check full -// SIE_SELECT_ENDPOINT_STALL_MASK = TU_BIT(1), -// SIE_SELECT_ENDPOINT_SETUP_RECEIVED_MASK = TU_BIT(2), // clear by SIE_CMDCODE_ENDPOINT_SELECT_CLEAR_INTERRUPT -// SIE_SELECT_ENDPOINT_PACKET_OVERWRITTEN_MASK = TU_BIT(3), // previous packet is overwritten by a SETUP packet -// SIE_SELECT_ENDPOINT_NAK_MASK = TU_BIT(4), // last packet response is NAK (auto clear by an ACK) -// SIE_SELECT_ENDPOINT_BUFFER1_FULL_MASK = TU_BIT(5), -// SIE_SELECT_ENDPOINT_BUFFER2_FULL_MASK = TU_BIT(6) -// }; - -// typedef enum -// { -// SIE_SET_ENDPOINT_STALLED_MASK = TU_BIT(0), -// SIE_SET_ENDPOINT_DISABLED_MASK = TU_BIT(5), -// SIE_SET_ENDPOINT_RATE_FEEDBACK_MASK = TU_BIT(6), -// SIE_SET_ENDPOINT_CONDITION_STALLED_MASK = TU_BIT(7), -// }sie_endpoint_set_status_mask_t; - -// //------------- DMA Descriptor Status -------------// -// enum { -// DD_STATUS_NOT_SERVICED = 0, -// DD_STATUS_BEING_SERVICED, -// DD_STATUS_NORMAL, -// DD_STATUS_DATA_UNDERUN, // short packet -// DD_STATUS_DATA_OVERRUN, -// DD_STATUS_SYSTEM_ERROR -// }; - -#ifdef __cplusplus - } -#endif - -#endif /* _TUSB_DCD_FOMU_H_ */ diff --git a/src/portable/foosn/fomu/dcd_fomu.c b/src/portable/valentyusb/eptri/dcd_eptri.c similarity index 99% rename from src/portable/foosn/fomu/dcd_fomu.c rename to src/portable/valentyusb/eptri/dcd_eptri.c index ee79366e..d7e1b8a9 100644 --- a/src/portable/foosn/fomu/dcd_fomu.c +++ b/src/portable/valentyusb/eptri/dcd_eptri.c @@ -34,10 +34,10 @@ #include "tusb_option.h" -#if TUSB_OPT_DEVICE_ENABLED && (CFG_TUSB_MCU == OPT_MCU_FOMU_EPTRI) +#if TUSB_OPT_DEVICE_ENABLED && (CFG_TUSB_MCU == OPT_MCU_VALENTYUSB_EPTRI) #include "device/dcd.h" -#include "dcd_fomu.h" +#include "dcd_eptri.h" #include "csr.h" #include "irq.h" void fomu_error(uint32_t line); diff --git a/src/portable/valentyusb/eptri/dcd_eptri.h b/src/portable/valentyusb/eptri/dcd_eptri.h new file mode 100644 index 00000000..0fa6ecc6 --- /dev/null +++ b/src/portable/valentyusb/eptri/dcd_eptri.h @@ -0,0 +1,39 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#ifndef _TUSB_DCD_VALENTYUSB_EPTRI_H_ +#define _TUSB_DCD_VALENTYUSB_EPTRI_H_ + +#include "common/tusb_common.h" +#ifdef __cplusplus + extern "C" { +#endif + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_DCD_VALENTYUSB_EPTRI_H_ */ diff --git a/src/portable/foosn/fomu/hal_fomu.c b/src/portable/valentyusb/eptri/hal_eptri.c similarity index 96% rename from src/portable/foosn/fomu/hal_fomu.c rename to src/portable/valentyusb/eptri/hal_eptri.c index ebc0a1d9..72453aff 100644 --- a/src/portable/foosn/fomu/hal_fomu.c +++ b/src/portable/valentyusb/eptri/hal_eptri.c @@ -26,7 +26,7 @@ #include "common/tusb_common.h" -#if (CFG_TUSB_MCU == OPT_MCU_FOMU_EPTRI) +#if (CFG_TUSB_MCU == OPT_MCU_VALENTYUSB_EPTRI) // No HAL-specific stuff here! From cc73990530f3cae083c47d17716edeff2b58ffb3 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Tue, 12 Nov 2019 21:12:31 -0800 Subject: [PATCH 050/267] tusb: rename `foosn` to `valentyusb` Use the name `valentyusb` as the vendor for the `valentyusb` project, rather than the manufacturer name of the Fomu device. This is because the `valentyusb` core can be used across multiple vendors, much like how other cores can be used across chip vendors. Signed-off-by: Sean Cross --- src/tusb_option.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tusb_option.h b/src/tusb_option.h index d2a9ad80..53b837f6 100644 --- a/src/tusb_option.h +++ b/src/tusb_option.h @@ -70,7 +70,7 @@ #define OPT_MCU_CXD56 400 ///< SONY CXD56 -#define OPT_MCU_FOMU_EPTRI 600 ///< Fomu eptri config +#define OPT_MCU_VALENTYUSB_EPTRI 600 ///< Fomu eptri config /** @} */ From 737d437ab8d8159330cd4e08f639bd2cdac7d2f8 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Wed, 13 Nov 2019 09:22:18 -0800 Subject: [PATCH 051/267] travis: fetch xPack risc-v toolchain This toolchain seems popular in the embedded space, and is generally preferred over the upstream SiFive toolchain. It can produce both 32- and 64-bit binaries, so its prefix is riscv-none-embed-. Signed-off-by: Sean Cross --- .travis.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.travis.yml b/.travis.yml index 6dfc507f..2413e422 100644 --- a/.travis.yml +++ b/.travis.yml @@ -16,7 +16,11 @@ install: - gem install ceedling before_script: + - wget -O /tmp/riscv-toolchain.tgz https://github.com/xpack-dev-tools/riscv-none-embed-gcc-xpack/releases/download/v8.3.0-1.1/xpack-riscv-none-embed-gcc-8.3.0-1.1-linux-x64.tgz + - tar -xzf /tmp/riscv-toolchain.tgz + - export PATH=$PWD/xPacks/riscv-none-embed-gcc/8.3.0-1.1/bin:$PATH - arm-none-eabi-gcc --version + - riscv-none-embed-gcc --version script: # Build all examples From dce070ebe0ab95a8a87f5be2a0696ec58a749ab0 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Wed, 13 Nov 2019 09:26:00 -0800 Subject: [PATCH 052/267] examples: make: specify CROSS_COMPILE for fomu When BOARD=fomu, use the riscv cross-compiler. Otherwise, use the default arm compiler. This can be overridden by passing CROSS_COMIPLE on the command line. Note that there are now three common risc-v prefixes: - riscv32-unknown-elf- : Common for users who compile their own - riscv64-unknown-elf- : Upstream multiarch toolchain from SiFive - riscv-none-embed- : xPack embedded version of SiFive toolchain Here we assume users are using the `riscv-none-embed-` toolchain from xPack, because it appears to be growing more common. Additionally, there is much confusion surrounding `riscv64-unknown-elf-`, which actually includes both 32- and 64-bit runtimes and can generate software for both. Signed-off-by: Sean Cross --- examples/make.mk | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/examples/make.mk b/examples/make.mk index c2e0559f..5bb55687 100644 --- a/examples/make.mk +++ b/examples/make.mk @@ -2,8 +2,12 @@ # Common make definition for all examples # -# Compiler +# Compiler +ifeq ($(BOARD), fomu) +CROSS_COMPILE = riscv-none-embed- +else CROSS_COMPILE = arm-none-eabi- +endif CC = $(CROSS_COMPILE)gcc CXX = $(CROSS_COMPILE)g++ OBJCOPY = $(CROSS_COMPILE)objcopy From 67267a93997770a2f59d606b5eb2f2d96b3a1437 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Wed, 13 Nov 2019 11:08:56 -0800 Subject: [PATCH 053/267] fomu: bsp: remove unused messible functions These functions are unused in the current implementation. Signed-off-by: Sean Cross --- hw/bsp/fomu/{bsp.c => fomu.c} | 17 ----------------- 1 file changed, 17 deletions(-) rename hw/bsp/fomu/{bsp.c => fomu.c} (90%) diff --git a/hw/bsp/fomu/bsp.c b/hw/bsp/fomu/fomu.c similarity index 90% rename from hw/bsp/fomu/bsp.c rename to hw/bsp/fomu/fomu.c index 3910cff4..3303a082 100644 --- a/hw/bsp/fomu/bsp.c +++ b/hw/bsp/fomu/fomu.c @@ -36,26 +36,10 @@ void hal_dcd_isr(uint8_t rhport); -void mputs(const char *str) { - (void)str; - while (*str) { - while ( (messible_status_read() & CSR_MESSIBLE_STATUS_FULL_OFFSET)) - ; - messible_in_write(*str); - str++; - } -} - -void mputln(const char *str) { - mputs(str); - mputs("\n"); -} - void fomu_error(uint32_t line) { (void)line; TU_BREAKPOINT(); - // while (1) {} } volatile uint32_t system_ticks = 0; @@ -90,7 +74,6 @@ void isr(void) void board_init(void) { - mputln("Fomu Initializing"); irq_setmask(0); irq_setie(1); timer_init(); From 679821e9174f9410960f974eefd46a94e74cfeda Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Wed, 13 Nov 2019 11:10:37 -0800 Subject: [PATCH 054/267] fomu: bsp: don't call usb isr when usb is disabled When compiled without usb support, we don't want to call the USB ISR. Signed-off-by: Sean Cross --- hw/bsp/fomu/fomu.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/hw/bsp/fomu/fomu.c b/hw/bsp/fomu/fomu.c index 3303a082..519c6363 100644 --- a/hw/bsp/fomu/fomu.c +++ b/hw/bsp/fomu/fomu.c @@ -63,9 +63,11 @@ void isr(void) irqs = irq_pending() & irq_getmask(); +#if CFG_TUSB_RHPORT0_MODE == OPT_MODE_DEVICE if (irqs & (1 << USB_INTERRUPT)) { hal_dcd_isr(0); } +#endif if (irqs & (1 << TIMER0_INTERRUPT)) { system_ticks++; timer0_ev_pending_write(1); From 1aa3f085cb0dd2c147e0376f69e4b92f208a14c6 Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 20 Nov 2019 15:30:10 +0700 Subject: [PATCH 055/267] adding support for NXP rt1064 evk board, boad test led + sw8 work. LTO is temporary disabled --- examples/make.mk | 3 +- hw/bsp/mimxrt1064_evk/board.h | 34 +++ hw/bsp/mimxrt1064_evk/board.mk | 55 ++++ .../evkmimxrt1064_flexspi_nor_config.c | 49 ++++ .../evkmimxrt1064_flexspi_nor_config.h | 268 ++++++++++++++++++ hw/bsp/mimxrt1064_evk/mimxrt1064_evk.c | 185 ++++++++++++ src/tusb_option.h | 54 ++-- 7 files changed, 621 insertions(+), 27 deletions(-) create mode 100644 hw/bsp/mimxrt1064_evk/board.h create mode 100644 hw/bsp/mimxrt1064_evk/board.mk create mode 100644 hw/bsp/mimxrt1064_evk/evkmimxrt1064_flexspi_nor_config.c create mode 100644 hw/bsp/mimxrt1064_evk/evkmimxrt1064_flexspi_nor_config.h create mode 100644 hw/bsp/mimxrt1064_evk/mimxrt1064_evk.c diff --git a/examples/make.mk b/examples/make.mk index 5bb55687..edf5c1f5 100644 --- a/examples/make.mk +++ b/examples/make.mk @@ -86,7 +86,8 @@ ifeq ($(DEBUG), 1) CFLAGS += -Og -ggdb else ifneq ($(BOARD),spresense) - CFLAGS += -flto -Os + #CFLAGS += -flto -Os + CFLAGS += -Os else CFLAGS += -Os endif diff --git a/hw/bsp/mimxrt1064_evk/board.h b/hw/bsp/mimxrt1064_evk/board.h new file mode 100644 index 00000000..3157e7d5 --- /dev/null +++ b/hw/bsp/mimxrt1064_evk/board.h @@ -0,0 +1,34 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019, Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + + +#ifndef BOARD_H_ +#define BOARD_H_ + +// required since iMX RT10xx SDK include this file for board size +#define BOARD_FLASH_SIZE (0x400000U) + +#endif /* BOARD_H_ */ diff --git a/hw/bsp/mimxrt1064_evk/board.mk b/hw/bsp/mimxrt1064_evk/board.mk new file mode 100644 index 00000000..e88d58d6 --- /dev/null +++ b/hw/bsp/mimxrt1064_evk/board.mk @@ -0,0 +1,55 @@ +CFLAGS += \ + -mthumb \ + -mabi=aapcs \ + -mcpu=cortex-m7 \ + -mfloat-abi=hard \ + -mfpu=fpv5-d16 \ + -D__ARMVFP__=0 -D__ARMFPV5__=0\ + -DCPU_MIMXRT1064DVL6A \ + -DXIP_EXTERNAL_FLASH=1 \ + -DXIP_BOOT_HEADER_ENABLE=1 \ + -DCFG_TUSB_MCU=OPT_MCU_RT10XX \ + -DCFG_TUSB_MEM_SECTION='__attribute__((section(".data")))' \ + -DCFG_TUSB_MEM_ALIGN='__attribute__((aligned(64)))' + +# mcu driver cause following warnings +#CFLAGS += -Wno-error=float-equal -Wno-error=nested-externs +CFLAGS += -Wno-error=unused-parameter + +MCU_DIR = hw/mcu/nxp/sdk/devices/MIMXRT1064 + +# All source paths should be relative to the top level. +LD_FILE = $(MCU_DIR)/gcc/MIMXRT1064xxxxx_flexspi_nor.ld + +SRC_C += \ + $(MCU_DIR)/system_MIMXRT1064.c \ + $(MCU_DIR)/xip/fsl_flexspi_nor_boot.c \ + $(MCU_DIR)/project_template/clock_config.c \ + $(MCU_DIR)/drivers/fsl_clock.c \ + $(MCU_DIR)/drivers/fsl_gpio.c \ + $(MCU_DIR)/drivers/fsl_common.c \ + $(MCU_DIR)/drivers/fsl_lpuart.c + +INC += \ + $(TOP)/hw/bsp/$(BOARD) \ + $(TOP)/$(MCU_DIR)/../../CMSIS/Include \ + $(TOP)/$(MCU_DIR) \ + $(TOP)/$(MCU_DIR)/drivers \ + $(TOP)/$(MCU_DIR)/project_template \ + +SRC_S += $(MCU_DIR)/gcc/startup_MIMXRT1064.S + +# For TinyUSB port source +VENDOR = nxp +CHIP_FAMILY = lpc18_43 + +# For freeRTOS port source +FREERTOS_PORT = ARM_CM7 + +# For flash-jlink target +JLINK_DEVICE = MIMXRT1064xxx6A +JLINK_IF = swd + +# flash using pyocd +flash: $(BUILD)/$(BOARD)-firmware.hex + pyocd flash -t mimxrt1050_quadspi $< diff --git a/hw/bsp/mimxrt1064_evk/evkmimxrt1064_flexspi_nor_config.c b/hw/bsp/mimxrt1064_evk/evkmimxrt1064_flexspi_nor_config.c new file mode 100644 index 00000000..bfb1c2d5 --- /dev/null +++ b/hw/bsp/mimxrt1064_evk/evkmimxrt1064_flexspi_nor_config.c @@ -0,0 +1,49 @@ +/* + * Copyright 2018 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include "evkmimxrt1064_flexspi_nor_config.h" + +/* Component ID definition, used by tools. */ +#ifndef FSL_COMPONENT_ID +#define FSL_COMPONENT_ID "platform.drivers.xip_board" +#endif + +/******************************************************************************* + * Code + ******************************************************************************/ +#if defined(XIP_BOOT_HEADER_ENABLE) && (XIP_BOOT_HEADER_ENABLE == 1) +#if defined(__CC_ARM) || defined(__ARMCC_VERSION) || defined(__GNUC__) +__attribute__((section(".boot_hdr.conf"))) +#elif defined(__ICCARM__) +#pragma location = ".boot_hdr.conf" +#endif + +const flexspi_nor_config_t qspiflash_config = { + .memConfig = + { + .tag = FLEXSPI_CFG_BLK_TAG, + .version = FLEXSPI_CFG_BLK_VERSION, + .readSampleClkSrc = kFlexSPIReadSampleClk_LoopbackFromDqsPad, + .csHoldTime = 3u, + .csSetupTime = 3u, + // Enable DDR mode, Wordaddassable, Safe configuration, Differential clock + .sflashPadType = kSerialFlash_4Pads, + .serialClkFreq = kFlexSpiSerialClk_100MHz, + .sflashA1Size = 8u * 1024u * 1024u, + .lookupTable = + { + // Read LUTs + FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0xEB, RADDR_SDR, FLEXSPI_4PAD, 0x18), + FLEXSPI_LUT_SEQ(DUMMY_SDR, FLEXSPI_4PAD, 0x06, READ_SDR, FLEXSPI_4PAD, 0x04), + }, + }, + .pageSize = 256u, + .sectorSize = 4u * 1024u, + .blockSize = 256u * 1024u, + .isUniformBlockSize = false, +}; +#endif /* XIP_BOOT_HEADER_ENABLE */ diff --git a/hw/bsp/mimxrt1064_evk/evkmimxrt1064_flexspi_nor_config.h b/hw/bsp/mimxrt1064_evk/evkmimxrt1064_flexspi_nor_config.h new file mode 100644 index 00000000..efdfe583 --- /dev/null +++ b/hw/bsp/mimxrt1064_evk/evkmimxrt1064_flexspi_nor_config.h @@ -0,0 +1,268 @@ +/* + * Copyright 2018 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef __EVKMIMXRT1064_FLEXSPI_NOR_CONFIG__ +#define __EVKMIMXRT1064_FLEXSPI_NOR_CONFIG__ + +#include +#include +#include "fsl_common.h" + +/*! @name Driver version */ +/*@{*/ +/*! @brief XIP_BOARD driver version 2.0.0. */ +#define FSL_XIP_BOARD_DRIVER_VERSION (MAKE_VERSION(2, 0, 0)) +/*@}*/ + +/* FLEXSPI memory config block related defintions */ +#define FLEXSPI_CFG_BLK_TAG (0x42464346UL) // ascii "FCFB" Big Endian +#define FLEXSPI_CFG_BLK_VERSION (0x56010400UL) // V1.4.0 +#define FLEXSPI_CFG_BLK_SIZE (512) + +/* FLEXSPI Feature related definitions */ +#define FLEXSPI_FEATURE_HAS_PARALLEL_MODE 1 + +/* Lookup table related defintions */ +#define CMD_INDEX_READ 0 +#define CMD_INDEX_READSTATUS 1 +#define CMD_INDEX_WRITEENABLE 2 +#define CMD_INDEX_WRITE 4 + +#define CMD_LUT_SEQ_IDX_READ 0 +#define CMD_LUT_SEQ_IDX_READSTATUS 1 +#define CMD_LUT_SEQ_IDX_WRITEENABLE 3 +#define CMD_LUT_SEQ_IDX_WRITE 9 + +#define CMD_SDR 0x01 +#define CMD_DDR 0x21 +#define RADDR_SDR 0x02 +#define RADDR_DDR 0x22 +#define CADDR_SDR 0x03 +#define CADDR_DDR 0x23 +#define MODE1_SDR 0x04 +#define MODE1_DDR 0x24 +#define MODE2_SDR 0x05 +#define MODE2_DDR 0x25 +#define MODE4_SDR 0x06 +#define MODE4_DDR 0x26 +#define MODE8_SDR 0x07 +#define MODE8_DDR 0x27 +#define WRITE_SDR 0x08 +#define WRITE_DDR 0x28 +#define READ_SDR 0x09 +#define READ_DDR 0x29 +#define LEARN_SDR 0x0A +#define LEARN_DDR 0x2A +#define DATSZ_SDR 0x0B +#define DATSZ_DDR 0x2B +#define DUMMY_SDR 0x0C +#define DUMMY_DDR 0x2C +#define DUMMY_RWDS_SDR 0x0D +#define DUMMY_RWDS_DDR 0x2D +#define JMP_ON_CS 0x1F +#define STOP 0 + +#define FLEXSPI_1PAD 0 +#define FLEXSPI_2PAD 1 +#define FLEXSPI_4PAD 2 +#define FLEXSPI_8PAD 3 + +#define FLEXSPI_LUT_SEQ(cmd0, pad0, op0, cmd1, pad1, op1) \ + (FLEXSPI_LUT_OPERAND0(op0) | FLEXSPI_LUT_NUM_PADS0(pad0) | FLEXSPI_LUT_OPCODE0(cmd0) | FLEXSPI_LUT_OPERAND1(op1) | \ + FLEXSPI_LUT_NUM_PADS1(pad1) | FLEXSPI_LUT_OPCODE1(cmd1)) + +//!@brief Definitions for FlexSPI Serial Clock Frequency +typedef enum _FlexSpiSerialClockFreq +{ + kFlexSpiSerialClk_30MHz = 1, + kFlexSpiSerialClk_50MHz = 2, + kFlexSpiSerialClk_60MHz = 3, + kFlexSpiSerialClk_75MHz = 4, + kFlexSpiSerialClk_80MHz = 5, + kFlexSpiSerialClk_100MHz = 6, + kFlexSpiSerialClk_120MHz = 7, + kFlexSpiSerialClk_133MHz = 8, + kFlexSpiSerialClk_166MHz = 9, +} flexspi_serial_clk_freq_t; + +//!@brief FlexSPI clock configuration type +enum +{ + kFlexSpiClk_SDR, //!< Clock configure for SDR mode + kFlexSpiClk_DDR, //!< Clock configurat for DDR mode +}; + +//!@brief FlexSPI Read Sample Clock Source definition +typedef enum _FlashReadSampleClkSource +{ + kFlexSPIReadSampleClk_LoopbackInternally = 0, + kFlexSPIReadSampleClk_LoopbackFromDqsPad = 1, + kFlexSPIReadSampleClk_LoopbackFromSckPad = 2, + kFlexSPIReadSampleClk_ExternalInputFromDqsPad = 3, +} flexspi_read_sample_clk_t; + +//!@brief Misc feature bit definitions +enum +{ + kFlexSpiMiscOffset_DiffClkEnable = 0, //!< Bit for Differential clock enable + kFlexSpiMiscOffset_Ck2Enable = 1, //!< Bit for CK2 enable + kFlexSpiMiscOffset_ParallelEnable = 2, //!< Bit for Parallel mode enable + kFlexSpiMiscOffset_WordAddressableEnable = 3, //!< Bit for Word Addressable enable + kFlexSpiMiscOffset_SafeConfigFreqEnable = 4, //!< Bit for Safe Configuration Frequency enable + kFlexSpiMiscOffset_PadSettingOverrideEnable = 5, //!< Bit for Pad setting override enable + kFlexSpiMiscOffset_DdrModeEnable = 6, //!< Bit for DDR clock confiuration indication. +}; + +//!@brief Flash Type Definition +enum +{ + kFlexSpiDeviceType_SerialNOR = 1, //!< Flash devices are Serial NOR + kFlexSpiDeviceType_SerialNAND = 2, //!< Flash devices are Serial NAND + kFlexSpiDeviceType_SerialRAM = 3, //!< Flash devices are Serial RAM/HyperFLASH + kFlexSpiDeviceType_MCP_NOR_NAND = 0x12, //!< Flash device is MCP device, A1 is Serial NOR, A2 is Serial NAND + kFlexSpiDeviceType_MCP_NOR_RAM = 0x13, //!< Flash deivce is MCP device, A1 is Serial NOR, A2 is Serial RAMs +}; + +//!@brief Flash Pad Definitions +enum +{ + kSerialFlash_1Pad = 1, + kSerialFlash_2Pads = 2, + kSerialFlash_4Pads = 4, + kSerialFlash_8Pads = 8, +}; + +//!@brief FlexSPI LUT Sequence structure +typedef struct _lut_sequence +{ + uint8_t seqNum; //!< Sequence Number, valid number: 1-16 + uint8_t seqId; //!< Sequence Index, valid number: 0-15 + uint16_t reserved; +} flexspi_lut_seq_t; + +//!@brief Flash Configuration Command Type +enum +{ + kDeviceConfigCmdType_Generic, //!< Generic command, for example: configure dummy cycles, drive strength, etc + kDeviceConfigCmdType_QuadEnable, //!< Quad Enable command + kDeviceConfigCmdType_Spi2Xpi, //!< Switch from SPI to DPI/QPI/OPI mode + kDeviceConfigCmdType_Xpi2Spi, //!< Switch from DPI/QPI/OPI to SPI mode + kDeviceConfigCmdType_Spi2NoCmd, //!< Switch to 0-4-4/0-8-8 mode + kDeviceConfigCmdType_Reset, //!< Reset device command +}; + +//!@brief FlexSPI Memory Configuration Block +typedef struct _FlexSPIConfig +{ + uint32_t tag; //!< [0x000-0x003] Tag, fixed value 0x42464346UL + uint32_t version; //!< [0x004-0x007] Version,[31:24] -'V', [23:16] - Major, [15:8] - Minor, [7:0] - bugfix + uint32_t reserved0; //!< [0x008-0x00b] Reserved for future use + uint8_t readSampleClkSrc; //!< [0x00c-0x00c] Read Sample Clock Source, valid value: 0/1/3 + uint8_t csHoldTime; //!< [0x00d-0x00d] CS hold time, default value: 3 + uint8_t csSetupTime; //!< [0x00e-0x00e] CS setup time, default value: 3 + uint8_t columnAddressWidth; //!< [0x00f-0x00f] Column Address with, for HyperBus protocol, it is fixed to 3, For + //! Serial NAND, need to refer to datasheet + uint8_t deviceModeCfgEnable; //!< [0x010-0x010] Device Mode Configure enable flag, 1 - Enable, 0 - Disable + uint8_t deviceModeType; //!< [0x011-0x011] Specify the configuration command type:Quad Enable, DPI/QPI/OPI switch, + //! Generic configuration, etc. + uint16_t waitTimeCfgCommands; //!< [0x012-0x013] Wait time for all configuration commands, unit: 100us, Used for + //! DPI/QPI/OPI switch or reset command + flexspi_lut_seq_t deviceModeSeq; //!< [0x014-0x017] Device mode sequence info, [7:0] - LUT sequence id, [15:8] - LUt + //! sequence number, [31:16] Reserved + uint32_t deviceModeArg; //!< [0x018-0x01b] Argument/Parameter for device configuration + uint8_t configCmdEnable; //!< [0x01c-0x01c] Configure command Enable Flag, 1 - Enable, 0 - Disable + uint8_t configModeType[3]; //!< [0x01d-0x01f] Configure Mode Type, similar as deviceModeTpe + flexspi_lut_seq_t + configCmdSeqs[3]; //!< [0x020-0x02b] Sequence info for Device Configuration command, similar as deviceModeSeq + uint32_t reserved1; //!< [0x02c-0x02f] Reserved for future use + uint32_t configCmdArgs[3]; //!< [0x030-0x03b] Arguments/Parameters for device Configuration commands + uint32_t reserved2; //!< [0x03c-0x03f] Reserved for future use + uint32_t controllerMiscOption; //!< [0x040-0x043] Controller Misc Options, see Misc feature bit definitions for more + //! details + uint8_t deviceType; //!< [0x044-0x044] Device Type: See Flash Type Definition for more details + uint8_t sflashPadType; //!< [0x045-0x045] Serial Flash Pad Type: 1 - Single, 2 - Dual, 4 - Quad, 8 - Octal + uint8_t serialClkFreq; //!< [0x046-0x046] Serial Flash Frequencey, device specific definitions, See System Boot + //! Chapter for more details + uint8_t lutCustomSeqEnable; //!< [0x047-0x047] LUT customization Enable, it is required if the program/erase cannot + //! be done using 1 LUT sequence, currently, only applicable to HyperFLASH + uint32_t reserved3[2]; //!< [0x048-0x04f] Reserved for future use + uint32_t sflashA1Size; //!< [0x050-0x053] Size of Flash connected to A1 + uint32_t sflashA2Size; //!< [0x054-0x057] Size of Flash connected to A2 + uint32_t sflashB1Size; //!< [0x058-0x05b] Size of Flash connected to B1 + uint32_t sflashB2Size; //!< [0x05c-0x05f] Size of Flash connected to B2 + uint32_t csPadSettingOverride; //!< [0x060-0x063] CS pad setting override value + uint32_t sclkPadSettingOverride; //!< [0x064-0x067] SCK pad setting override value + uint32_t dataPadSettingOverride; //!< [0x068-0x06b] data pad setting override value + uint32_t dqsPadSettingOverride; //!< [0x06c-0x06f] DQS pad setting override value + uint32_t timeoutInMs; //!< [0x070-0x073] Timeout threshold for read status command + uint32_t commandInterval; //!< [0x074-0x077] CS deselect interval between two commands + uint16_t dataValidTime[2]; //!< [0x078-0x07b] CLK edge to data valid time for PORT A and PORT B, in terms of 0.1ns + uint16_t busyOffset; //!< [0x07c-0x07d] Busy offset, valid value: 0-31 + uint16_t busyBitPolarity; //!< [0x07e-0x07f] Busy flag polarity, 0 - busy flag is 1 when flash device is busy, 1 - + //! busy flag is 0 when flash device is busy + uint32_t lookupTable[64]; //!< [0x080-0x17f] Lookup table holds Flash command sequences + flexspi_lut_seq_t lutCustomSeq[12]; //!< [0x180-0x1af] Customizable LUT Sequences + uint32_t reserved4[4]; //!< [0x1b0-0x1bf] Reserved for future use +} flexspi_mem_config_t; + +/* */ +#define NOR_CMD_INDEX_READ CMD_INDEX_READ //!< 0 +#define NOR_CMD_INDEX_READSTATUS CMD_INDEX_READSTATUS //!< 1 +#define NOR_CMD_INDEX_WRITEENABLE CMD_INDEX_WRITEENABLE //!< 2 +#define NOR_CMD_INDEX_ERASESECTOR 3 //!< 3 +#define NOR_CMD_INDEX_PAGEPROGRAM CMD_INDEX_WRITE //!< 4 +#define NOR_CMD_INDEX_CHIPERASE 5 //!< 5 +#define NOR_CMD_INDEX_DUMMY 6 //!< 6 +#define NOR_CMD_INDEX_ERASEBLOCK 7 //!< 7 + +#define NOR_CMD_LUT_SEQ_IDX_READ CMD_LUT_SEQ_IDX_READ //!< 0 READ LUT sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_READSTATUS \ + CMD_LUT_SEQ_IDX_READSTATUS //!< 1 Read Status LUT sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_READSTATUS_XPI \ + 2 //!< 2 Read status DPI/QPI/OPI sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_WRITEENABLE \ + CMD_LUT_SEQ_IDX_WRITEENABLE //!< 3 Write Enable sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_WRITEENABLE_XPI \ + 4 //!< 4 Write Enable DPI/QPI/OPI sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_ERASESECTOR 5 //!< 5 Erase Sector sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_ERASEBLOCK 8 //!< 8 Erase Block sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_PAGEPROGRAM \ + CMD_LUT_SEQ_IDX_WRITE //!< 9 Program sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_CHIPERASE 11 //!< 11 Chip Erase sequence in lookupTable id stored in config block +#define NOR_CMD_LUT_SEQ_IDX_READ_SFDP 13 //!< 13 Read SFDP sequence in lookupTable id stored in config block +#define NOR_CMD_LUT_SEQ_IDX_RESTORE_NOCMD \ + 14 //!< 14 Restore 0-4-4/0-8-8 mode sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_EXIT_NOCMD \ + 15 //!< 15 Exit 0-4-4/0-8-8 mode sequence id in lookupTable stored in config blobk + +/* + * Serial NOR configuration block + */ +typedef struct _flexspi_nor_config +{ + flexspi_mem_config_t memConfig; //!< Common memory configuration info via FlexSPI + uint32_t pageSize; //!< Page size of Serial NOR + uint32_t sectorSize; //!< Sector size of Serial NOR + uint8_t ipcmdSerialClkFreq; //!< Clock frequency for IP command + uint8_t isUniformBlockSize; //!< Sector/Block size is the same + uint8_t reserved0[2]; //!< Reserved for future use + uint8_t serialNorType; //!< Serial NOR Flash type: 0/1/2/3 + uint8_t needExitNoCmdMode; //!< Need to exit NoCmd mode before other IP command + uint8_t halfClkForNonReadCmd; //!< Half the Serial Clock for non-read command: true/false + uint8_t needRestoreNoCmdMode; //!< Need to Restore NoCmd mode after IP commmand execution + uint32_t blockSize; //!< Block size + uint32_t reserve2[11]; //!< Reserved for future use +} flexspi_nor_config_t; + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef __cplusplus +} +#endif +#endif /* __EVKMIMXRT1064_FLEXSPI_NOR_CONFIG__ */ diff --git a/hw/bsp/mimxrt1064_evk/mimxrt1064_evk.c b/hw/bsp/mimxrt1064_evk/mimxrt1064_evk.c new file mode 100644 index 00000000..012c8ab5 --- /dev/null +++ b/hw/bsp/mimxrt1064_evk/mimxrt1064_evk.c @@ -0,0 +1,185 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2018, hathach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#include "../board.h" +#include "fsl_device_registers.h" +#include "fsl_gpio.h" +#include "fsl_iomuxc.h" +#include "fsl_clock.h" + +#include "clock_config.h" + +#define LED_PORT GPIO1 +#define LED_PIN 9 +#define LED_STATE_ON 0 + +// SW8 button +#define BUTTON_PORT GPIO5 +#define BUTTON_PIN 0 +#define BUTTON_STATE_ACTIVE 0 + +const uint8_t dcd_data[] = {0x00}; + +void board_init(void) +{ + // Init clock + BOARD_BootClockRUN(); + SystemCoreClockUpdate(); + + // Enable IOCON clock + CLOCK_EnableClock(kCLOCK_Iomuxc); +// CLOCK_EnableClock(kCLOCK_IomuxcSnvs); + + /* GPIO_AD_B0_09 is configured as GPIO1_IO09 */ + IOMUXC_SetPinMux( IOMUXC_GPIO_AD_B0_09_GPIO1_IO09, 0U); + + IOMUXC_GPR->GPR26 = ((IOMUXC_GPR->GPR26 & + (~(IOMUXC_GPR_GPR26_GPIO_MUX1_GPIO_SEL_MASK))) /* Mask bits to zero which are setting */ + | IOMUXC_GPR_GPR26_GPIO_MUX1_GPIO_SEL(0x00U) /* GPIO1 and GPIO6 share same IO MUX function, GPIO_MUX1 selects one GPIO function: 0x00U */ + ); + + /* GPIO_AD_B0_09 PAD functional properties : */ + /* Slew Rate Field: Slow Slew Rate + Drive Strength Field: R0/6 + Speed Field: medium(100MHz) + Open Drain Enable Field: Open Drain Disabled + Pull / Keep Enable Field: Pull/Keeper Enabled + Pull / Keep Select Field: Keeper + Pull Up / Down Config. Field: 100K Ohm Pull Down + Hyst. Enable Field: Hysteresis Disabled */ + IOMUXC_SetPinConfig( IOMUXC_GPIO_AD_B0_09_GPIO1_IO09, 0x10B0U); + + +// IOMUXC_SetPinMux( +// IOMUXC_SNVS_WAKEUP_GPIO5_IO00, /* WAKEUP is configured as GPIO5_IO00 */ +// 0U); /* Software Input On Field: Input Path is determined by functionality */ + +#if CFG_TUSB_OS == OPT_OS_NONE + // 1ms tick timer + SysTick_Config(SystemCoreClock / 1000); +#elif CFG_TUSB_OS == OPT_OS_FREERTOS + // If freeRTOS is used, IRQ priority is limit by max syscall ( smaller is higher ) + NVIC_SetPriority(USB0_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY ); +#endif + + // LED + gpio_pin_config_t led_config = { kGPIO_DigitalOutput, 0, kGPIO_NoIntmode }; + GPIO_PinInit(LED_PORT, LED_PIN, &led_config); + board_led_write(true); + + // Button +// gpio_pin_config_t button_config = { kGPIO_DigitalInput, 0, kGPIO_IntRisingEdge, }; +// GPIO_PinInit(BUTTON_PORT, BUTTON_PIN, &button_config); + +#if 0 + // USB VBUS + const uint32_t port0_pin22_config = ( + IOCON_PIO_FUNC7 | /* Pin is configured as USB0_VBUS */ + IOCON_PIO_MODE_INACT | /* No addition pin function */ + IOCON_PIO_SLEW_STANDARD | /* Standard mode, output slew rate control is enabled */ + IOCON_PIO_INV_DI | /* Input function is not inverted */ + IOCON_PIO_DIGITAL_EN | /* Enables digital function */ + IOCON_PIO_OPENDRAIN_DI /* Open drain is disabled */ + ); + /* PORT0 PIN22 (coords: 78) is configured as USB0_VBUS */ + IOCON_PinMuxSet(IOCON, 0U, 22U, port0_pin22_config); + + // USB Controller + POWER_DisablePD(kPDRUNCFG_PD_USB0_PHY); /*Turn on USB0 Phy */ + POWER_DisablePD(kPDRUNCFG_PD_USB1_PHY); /*< Turn on USB1 Phy */ + + /* reset the IP to make sure it's in reset state. */ + RESET_PeripheralReset(kUSB0D_RST_SHIFT_RSTn); + RESET_PeripheralReset(kUSB0HSL_RST_SHIFT_RSTn); + RESET_PeripheralReset(kUSB0HMR_RST_SHIFT_RSTn); + RESET_PeripheralReset(kUSB1H_RST_SHIFT_RSTn); + RESET_PeripheralReset(kUSB1D_RST_SHIFT_RSTn); + RESET_PeripheralReset(kUSB1_RST_SHIFT_RSTn); + RESET_PeripheralReset(kUSB1RAM_RST_SHIFT_RSTn); + +#if (defined USB_DEVICE_CONFIG_LPCIP3511HS) && (USB_DEVICE_CONFIG_LPCIP3511HS) + CLOCK_EnableClock(kCLOCK_Usbh1); + /* Put PHY powerdown under software control */ + *((uint32_t *)(USBHSH_BASE + 0x50)) = USBHSH_PORTMODE_SW_PDCOM_MASK; + /* According to reference mannual, device mode setting has to be set by access usb host register */ + *((uint32_t *)(USBHSH_BASE + 0x50)) |= USBHSH_PORTMODE_DEV_ENABLE_MASK; + /* enable usb1 host clock */ + CLOCK_DisableClock(kCLOCK_Usbh1); +#endif + +#if 1 || (defined USB_DEVICE_CONFIG_LPCIP3511FS) && (USB_DEVICE_CONFIG_LPCIP3511FS) + CLOCK_SetClkDiv(kCLOCK_DivUsb0Clk, 1, false); + CLOCK_AttachClk(kFRO_HF_to_USB0_CLK); + /* enable usb0 host clock */ + CLOCK_EnableClock(kCLOCK_Usbhsl0); + /*According to reference mannual, device mode setting has to be set by access usb host register */ + *((uint32_t *)(USBFSH_BASE + 0x5C)) |= USBFSH_PORTMODE_DEV_ENABLE_MASK; + /* disable usb0 host clock */ + CLOCK_DisableClock(kCLOCK_Usbhsl0); + CLOCK_EnableUsbfs0DeviceClock(kCLOCK_UsbfsSrcFro, CLOCK_GetFreq(kCLOCK_FroHf)); /* enable USB Device clock */ +#endif +#endif +} + +//--------------------------------------------------------------------+ +// Board porting API +//--------------------------------------------------------------------+ + +void board_led_write(bool state) +{ + GPIO_PinWrite(LED_PORT, LED_PIN, state ? LED_STATE_ON : (1-LED_STATE_ON)); +} + +uint32_t board_button_read(void) +{ + // active low + return BUTTON_STATE_ACTIVE == GPIO_PinRead(BUTTON_PORT, BUTTON_PIN); +} + +int board_uart_read(uint8_t* buf, int len) +{ + (void) buf; (void) len; + return 0; +} + +int board_uart_write(void const * buf, int len) +{ + (void) buf; (void) len; + return 0; +} + +#if CFG_TUSB_OS == OPT_OS_NONE +volatile uint32_t system_ticks = 0; +void SysTick_Handler(void) +{ + system_ticks++; +} + +uint32_t board_millis(void) +{ + return system_ticks; +} +#endif diff --git a/src/tusb_option.h b/src/tusb_option.h index 53b837f6..cc7b4675 100644 --- a/src/tusb_option.h +++ b/src/tusb_option.h @@ -37,40 +37,42 @@ * @{ */ // LPC -#define OPT_MCU_LPC11UXX 1 ///< NXP LPC11Uxx -#define OPT_MCU_LPC13XX 2 ///< NXP LPC13xx -#define OPT_MCU_LPC15XX 3 ///< NXP LPC15xx -#define OPT_MCU_LPC175X_6X 4 ///< NXP LPC175x, LPC176x -#define OPT_MCU_LPC177X_8X 5 ///< NXP LPC177x, LPC178x -#define OPT_MCU_LPC18XX 6 ///< NXP LPC18xx -#define OPT_MCU_LPC40XX 7 ///< NXP LPC40xx -#define OPT_MCU_LPC43XX 8 ///< NXP LPC43xx -#define OPT_MCU_LPC51UXX 9 ///< NXP LPC51U6x -#define OPT_MCU_LPC54XXX 10 ///< NXP LPC54xxx -#define OPT_MCU_LPC55XX 11 ///< NXP LPC55xx +#define OPT_MCU_LPC11UXX 1 ///< NXP LPC11Uxx +#define OPT_MCU_LPC13XX 2 ///< NXP LPC13xx +#define OPT_MCU_LPC15XX 3 ///< NXP LPC15xx +#define OPT_MCU_LPC175X_6X 4 ///< NXP LPC175x, LPC176x +#define OPT_MCU_LPC177X_8X 5 ///< NXP LPC177x, LPC178x +#define OPT_MCU_LPC18XX 6 ///< NXP LPC18xx +#define OPT_MCU_LPC40XX 7 ///< NXP LPC40xx +#define OPT_MCU_LPC43XX 8 ///< NXP LPC43xx +#define OPT_MCU_LPC51UXX 9 ///< NXP LPC51U6x +#define OPT_MCU_LPC54XXX 10 ///< NXP LPC54xxx +#define OPT_MCU_LPC55XX 11 ///< NXP LPC55xx // NRF -#define OPT_MCU_NRF5X 100 ///< Nordic nRF5x series +#define OPT_MCU_NRF5X 100 ///< Nordic nRF5x series // SAM -#define OPT_MCU_SAMD21 200 ///< MicroChip SAMD21 -#define OPT_MCU_SAMD51 201 ///< MicroChip SAMD51 +#define OPT_MCU_SAMD21 200 ///< MicroChip SAMD21 +#define OPT_MCU_SAMD51 201 ///< MicroChip SAMD51 // STM32 -#define OPT_MCU_STM32F0 300 ///< ST STM32F0 -#define OPT_MCU_STM32F1 301 ///< ST STM32F1 -#define OPT_MCU_STM32F2 302 ///< ST STM32F2 -#define OPT_MCU_STM32F3 303 ///< ST STM32F3 -#define OPT_MCU_STM32F4 304 ///< ST STM32F4 -#define OPT_MCU_STM32F7 305 ///< ST STM32F7 -#define OPT_MCU_STM32H7 306 ///< ST STM32H7 -#define OPT_MCU_STM32L0 307 ///< ST STM32L0 -#define OPT_MCU_STM32L1 308 ///< ST STM32L1 -#define OPT_MCU_STM32L4 309 ///< ST STM32L4 +#define OPT_MCU_STM32F0 300 ///< ST STM32F0 +#define OPT_MCU_STM32F1 301 ///< ST STM32F1 +#define OPT_MCU_STM32F2 302 ///< ST STM32F2 +#define OPT_MCU_STM32F3 303 ///< ST STM32F3 +#define OPT_MCU_STM32F4 304 ///< ST STM32F4 +#define OPT_MCU_STM32F7 305 ///< ST STM32F7 +#define OPT_MCU_STM32H7 306 ///< ST STM32H7 +#define OPT_MCU_STM32L0 307 ///< ST STM32L0 +#define OPT_MCU_STM32L1 308 ///< ST STM32L1 +#define OPT_MCU_STM32L4 309 ///< ST STM32L4 -#define OPT_MCU_CXD56 400 ///< SONY CXD56 +#define OPT_MCU_CXD56 400 ///< SONY CXD56 -#define OPT_MCU_VALENTYUSB_EPTRI 600 ///< Fomu eptri config +#define OPT_MCU_VALENTYUSB_EPTRI 600 ///< Fomu eptri config + +#define OPT_MCU_RT10XX 700 ///< NXP iMX RT10xx /** @} */ From f638594536643a69200ddca60fe5138447655fbb Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 20 Nov 2019 16:06:40 +0700 Subject: [PATCH 056/267] move -flto to board.mk current board that doesn work with flto is spresense and mimxrt10xx (due to xip image_vector_table is optimized out). --- examples/make.mk | 7 +--- hw/bsp/circuitplayground_bluefruit/board.mk | 33 ++++++++-------- hw/bsp/circuitplayground_express/board.mk | 30 +++++++------- hw/bsp/ea4088qs/board.mk | 1 + hw/bsp/ea4357/board.mk | 1 + hw/bsp/feather_m0_express/board.mk | 5 ++- hw/bsp/feather_m4_express/board.mk | 3 +- hw/bsp/feather_nrf52840_express/board.mk | 33 ++++++++-------- hw/bsp/feather_stm32f405/board.mk | 5 ++- hw/bsp/fomu/board.mk | 1 + hw/bsp/lpcxpresso11u37/board.mk | 1 + hw/bsp/lpcxpresso11u68/board.mk | 1 + hw/bsp/lpcxpresso1347/board.mk | 1 + hw/bsp/lpcxpresso1549/board.mk | 1 + hw/bsp/lpcxpresso1769/board.mk | 1 + hw/bsp/lpcxpresso51u68/board.mk | 1 + hw/bsp/lpcxpresso54114/board.mk | 1 + hw/bsp/lpcxpresso55s69/board.mk | 1 + hw/bsp/mbed1768/board.mk | 1 + hw/bsp/mcb1800/board.mk | 1 + hw/bsp/metro_m0_express/board.mk | 5 ++- hw/bsp/metro_m4_express/board.mk | 3 +- hw/bsp/mimxrt1064_evk/mimxrt1064_evk.c | 2 +- hw/bsp/ngx4330/board.mk | 1 + hw/bsp/nrf52840_mdk_dongle/board.mk | 1 + hw/bsp/pca10056/board.mk | 1 + hw/bsp/pca10059/board.mk | 1 + hw/bsp/pca10100/board.mk | 1 + hw/bsp/pyboardv11/board.mk | 5 ++- hw/bsp/spresense/board.mk | 18 ++++----- hw/bsp/stm32f070rbnucleo/board.mk | 43 +++++++++++---------- hw/bsp/stm32f072disco/board.mk | 43 +++++++++++---------- hw/bsp/stm32f103bluepill/board.mk | 39 ++++++++++--------- hw/bsp/stm32f207nucleo/board.mk | 39 ++++++++++--------- hw/bsp/stm32f303disco/board.mk | 41 ++++++++++---------- hw/bsp/stm32f407disco/board.mk | 5 ++- hw/bsp/stm32f411disco/board.mk | 5 ++- hw/bsp/stm32f412disco/board.mk | 5 ++- hw/bsp/stm32f767nucleo/board.mk | 5 ++- hw/bsp/stm32h743nucleo/board.mk | 5 ++- hw/bsp/stm32l0538disco/board.mk | 41 ++++++++++---------- hw/bsp/stm32l476disco/board.mk | 5 ++- 42 files changed, 238 insertions(+), 205 deletions(-) diff --git a/examples/make.mk b/examples/make.mk index edf5c1f5..12ce3fd0 100644 --- a/examples/make.mk +++ b/examples/make.mk @@ -85,12 +85,7 @@ CFLAGS += \ ifeq ($(DEBUG), 1) CFLAGS += -Og -ggdb else - ifneq ($(BOARD),spresense) - #CFLAGS += -flto -Os - CFLAGS += -Os - else - CFLAGS += -Os - endif + CFLAGS += -Os endif # TUSB Logging option diff --git a/hw/bsp/circuitplayground_bluefruit/board.mk b/hw/bsp/circuitplayground_bluefruit/board.mk index 72b9ddfb..bfeaa235 100644 --- a/hw/bsp/circuitplayground_bluefruit/board.mk +++ b/hw/bsp/circuitplayground_bluefruit/board.mk @@ -1,11 +1,12 @@ CFLAGS += \ - -mthumb \ - -mabi=aapcs \ - -mcpu=cortex-m4 \ - -mfloat-abi=hard \ - -mfpu=fpv4-sp-d16 \ - -DCFG_TUSB_MCU=OPT_MCU_NRF5X \ - -DNRF52840_XXAA \ + -flto \ + -mthumb \ + -mabi=aapcs \ + -mcpu=cortex-m4 \ + -mfloat-abi=hard \ + -mfpu=fpv4-sp-d16 \ + -DCFG_TUSB_MCU=OPT_MCU_NRF5X \ + -DNRF52840_XXAA \ -DCONFIG_GPIO_AS_PINRESET # nrfx issue undef _ARMCC_VERSION usage https://github.com/NordicSemiconductor/nrfx/issues/49 @@ -23,17 +24,17 @@ LD_FILE = hw/bsp/circuitplayground_bluefruit/nrf52840_s140_v6.ld LDFLAGS += -L$(TOP)/hw/mcu/nordic/nrfx/mdk SRC_C += \ - hw/mcu/nordic/nrfx/drivers/src/nrfx_power.c \ - hw/mcu/nordic/nrfx/mdk/system_nrf52840.c \ + hw/mcu/nordic/nrfx/drivers/src/nrfx_power.c \ + hw/mcu/nordic/nrfx/mdk/system_nrf52840.c \ INC += \ - $(TOP)/hw/mcu/nordic/cmsis/Include \ - $(TOP)/hw/mcu/nordic \ - $(TOP)/hw/mcu/nordic/nrfx \ - $(TOP)/hw/mcu/nordic/nrfx/mdk \ - $(TOP)/hw/mcu/nordic/nrfx/hal \ - $(TOP)/hw/mcu/nordic/nrfx/drivers/include \ - $(TOP)/hw/mcu/nordic/nrfx/drivers/src \ + $(TOP)/hw/mcu/nordic/cmsis/Include \ + $(TOP)/hw/mcu/nordic \ + $(TOP)/hw/mcu/nordic/nrfx \ + $(TOP)/hw/mcu/nordic/nrfx/mdk \ + $(TOP)/hw/mcu/nordic/nrfx/hal \ + $(TOP)/hw/mcu/nordic/nrfx/drivers/include \ + $(TOP)/hw/mcu/nordic/nrfx/drivers/src \ SRC_S += hw/mcu/nordic/nrfx/mdk/gcc_startup_nrf52840.S diff --git a/hw/bsp/circuitplayground_express/board.mk b/hw/bsp/circuitplayground_express/board.mk index 158f543b..115a8118 100644 --- a/hw/bsp/circuitplayground_express/board.mk +++ b/hw/bsp/circuitplayground_express/board.mk @@ -11,23 +11,23 @@ CFLAGS += \ LD_FILE = hw/bsp/circuitplayground_express/samd21g18a_flash.ld SRC_C += \ - hw/mcu/microchip/samd/asf4/samd21/gcc/gcc/startup_samd21.c \ - hw/mcu/microchip/samd/asf4/samd21/gcc/system_samd21.c \ - hw/mcu/microchip/samd/asf4/samd21/hpl/gclk/hpl_gclk.c \ - hw/mcu/microchip/samd/asf4/samd21/hpl/pm/hpl_pm.c \ - hw/mcu/microchip/samd/asf4/samd21/hpl/sysctrl/hpl_sysctrl.c \ - hw/mcu/microchip/samd/asf4/samd21/hal/src/hal_atomic.c + hw/mcu/microchip/samd/asf4/samd21/gcc/gcc/startup_samd21.c \ + hw/mcu/microchip/samd/asf4/samd21/gcc/system_samd21.c \ + hw/mcu/microchip/samd/asf4/samd21/hpl/gclk/hpl_gclk.c \ + hw/mcu/microchip/samd/asf4/samd21/hpl/pm/hpl_pm.c \ + hw/mcu/microchip/samd/asf4/samd21/hpl/sysctrl/hpl_sysctrl.c \ + hw/mcu/microchip/samd/asf4/samd21/hal/src/hal_atomic.c INC += \ - $(TOP)/hw/mcu/microchip/samd/asf4/samd21/ \ - $(TOP)/hw/mcu/microchip/samd/asf4/samd21/config \ - $(TOP)/hw/mcu/microchip/samd/asf4/samd21/include \ - $(TOP)/hw/mcu/microchip/samd/asf4/samd21/hal/include \ - $(TOP)/hw/mcu/microchip/samd/asf4/samd21/hal/utils/include \ - $(TOP)/hw/mcu/microchip/samd/asf4/samd51/hpl/pm/ \ - $(TOP)/hw/mcu/microchip/samd/asf4/samd21/hpl/port \ - $(TOP)/hw/mcu/microchip/samd/asf4/samd21/hri \ - $(TOP)/hw/mcu/microchip/samd/asf4/samd21/CMSIS/Include + $(TOP)/hw/mcu/microchip/samd/asf4/samd21/ \ + $(TOP)/hw/mcu/microchip/samd/asf4/samd21/config \ + $(TOP)/hw/mcu/microchip/samd/asf4/samd21/include \ + $(TOP)/hw/mcu/microchip/samd/asf4/samd21/hal/include \ + $(TOP)/hw/mcu/microchip/samd/asf4/samd21/hal/utils/include \ + $(TOP)/hw/mcu/microchip/samd/asf4/samd51/hpl/pm/ \ + $(TOP)/hw/mcu/microchip/samd/asf4/samd21/hpl/port \ + $(TOP)/hw/mcu/microchip/samd/asf4/samd21/hri \ + $(TOP)/hw/mcu/microchip/samd/asf4/samd21/CMSIS/Include # For TinyUSB port source VENDOR = microchip diff --git a/hw/bsp/ea4088qs/board.mk b/hw/bsp/ea4088qs/board.mk index f621affb..7869ea8d 100644 --- a/hw/bsp/ea4088qs/board.mk +++ b/hw/bsp/ea4088qs/board.mk @@ -1,4 +1,5 @@ CFLAGS += \ + -flto \ -mthumb \ -mabi=aapcs \ -mcpu=cortex-m4 \ diff --git a/hw/bsp/ea4357/board.mk b/hw/bsp/ea4357/board.mk index be6a307e..8e7367fa 100644 --- a/hw/bsp/ea4357/board.mk +++ b/hw/bsp/ea4357/board.mk @@ -1,4 +1,5 @@ CFLAGS += \ + -flto \ -mthumb \ -mabi=aapcs \ -mcpu=cortex-m4 \ diff --git a/hw/bsp/feather_m0_express/board.mk b/hw/bsp/feather_m0_express/board.mk index b7ba0b0e..fe191333 100644 --- a/hw/bsp/feather_m0_express/board.mk +++ b/hw/bsp/feather_m0_express/board.mk @@ -1,10 +1,11 @@ CFLAGS += \ - -DCONF_DFLL_OVERWRITE_CALIBRATION=0 \ - -D__SAMD21G18A__ \ + -flto \ -mthumb \ -mabi=aapcs-linux \ -mcpu=cortex-m0plus \ -nostdlib -nostartfiles \ + -D__SAMD21G18A__ \ + -DCONF_DFLL_OVERWRITE_CALIBRATION=0 \ -DCFG_TUSB_MCU=OPT_MCU_SAMD21 # All source paths should be relative to the top level. diff --git a/hw/bsp/feather_m4_express/board.mk b/hw/bsp/feather_m4_express/board.mk index c62d9bc3..010e4b86 100644 --- a/hw/bsp/feather_m4_express/board.mk +++ b/hw/bsp/feather_m4_express/board.mk @@ -1,11 +1,12 @@ CFLAGS += \ - -D__SAMD51J19A__ \ + -flto \ -mthumb \ -mabi=aapcs-linux \ -mcpu=cortex-m4 \ -mfloat-abi=hard \ -mfpu=fpv4-sp-d16 \ -nostdlib -nostartfiles \ + -D__SAMD51J19A__ \ -DCFG_TUSB_MCU=OPT_MCU_SAMD51 CFLAGS += -Wno-error=undef diff --git a/hw/bsp/feather_nrf52840_express/board.mk b/hw/bsp/feather_nrf52840_express/board.mk index 1e077bac..b4d6fbe9 100644 --- a/hw/bsp/feather_nrf52840_express/board.mk +++ b/hw/bsp/feather_nrf52840_express/board.mk @@ -1,11 +1,12 @@ CFLAGS += \ - -mthumb \ - -mabi=aapcs \ - -mcpu=cortex-m4 \ - -mfloat-abi=hard \ - -mfpu=fpv4-sp-d16 \ - -DCFG_TUSB_MCU=OPT_MCU_NRF5X \ - -DNRF52840_XXAA \ + -flto \ + -mthumb \ + -mabi=aapcs \ + -mcpu=cortex-m4 \ + -mfloat-abi=hard \ + -mfpu=fpv4-sp-d16 \ + -DCFG_TUSB_MCU=OPT_MCU_NRF5X \ + -DNRF52840_XXAA \ -DCONFIG_GPIO_AS_PINRESET # nrfx issue undef _ARMCC_VERSION usage https://github.com/NordicSemiconductor/nrfx/issues/49 @@ -23,17 +24,17 @@ LD_FILE = hw/bsp/feather_nrf52840_express/nrf52840_s140_v6.ld LDFLAGS += -L$(TOP)/hw/mcu/nordic/nrfx/mdk SRC_C += \ - hw/mcu/nordic/nrfx/drivers/src/nrfx_power.c \ - hw/mcu/nordic/nrfx/mdk/system_nrf52840.c \ + hw/mcu/nordic/nrfx/drivers/src/nrfx_power.c \ + hw/mcu/nordic/nrfx/mdk/system_nrf52840.c \ INC += \ - $(TOP)/hw/mcu/nordic/cmsis/Include \ - $(TOP)/hw/mcu/nordic \ - $(TOP)/hw/mcu/nordic/nrfx \ - $(TOP)/hw/mcu/nordic/nrfx/mdk \ - $(TOP)/hw/mcu/nordic/nrfx/hal \ - $(TOP)/hw/mcu/nordic/nrfx/drivers/include \ - $(TOP)/hw/mcu/nordic/nrfx/drivers/src \ + $(TOP)/hw/mcu/nordic/cmsis/Include \ + $(TOP)/hw/mcu/nordic \ + $(TOP)/hw/mcu/nordic/nrfx \ + $(TOP)/hw/mcu/nordic/nrfx/mdk \ + $(TOP)/hw/mcu/nordic/nrfx/hal \ + $(TOP)/hw/mcu/nordic/nrfx/drivers/include \ + $(TOP)/hw/mcu/nordic/nrfx/drivers/src \ SRC_S += hw/mcu/nordic/nrfx/mdk/gcc_startup_nrf52840.S diff --git a/hw/bsp/feather_stm32f405/board.mk b/hw/bsp/feather_stm32f405/board.mk index 14595e83..1e68737b 100644 --- a/hw/bsp/feather_stm32f405/board.mk +++ b/hw/bsp/feather_stm32f405/board.mk @@ -1,12 +1,13 @@ CFLAGS += \ - -DHSE_VALUE=12000000 \ - -DSTM32F405xx \ + -flto \ -mthumb \ -mabi=aapcs \ -mcpu=cortex-m4 \ -mfloat-abi=hard \ -mfpu=fpv4-sp-d16 \ -nostdlib -nostartfiles \ + -DSTM32F405xx \ + -DHSE_VALUE=12000000 \ -DCFG_TUSB_MCU=OPT_MCU_STM32F4 ST_HAL_DRIVER = hw/mcu/st/st_driver/STM32F4xx_HAL_Driver diff --git a/hw/bsp/fomu/board.mk b/hw/bsp/fomu/board.mk index cdcd63b2..4e8101b7 100644 --- a/hw/bsp/fomu/board.mk +++ b/hw/bsp/fomu/board.mk @@ -1,4 +1,5 @@ CFLAGS += \ + -flto \ -march=rv32i \ -mabi=ilp32 \ -nostdlib \ diff --git a/hw/bsp/lpcxpresso11u37/board.mk b/hw/bsp/lpcxpresso11u37/board.mk index 72c5ef0d..d3121ab9 100644 --- a/hw/bsp/lpcxpresso11u37/board.mk +++ b/hw/bsp/lpcxpresso11u37/board.mk @@ -1,4 +1,5 @@ CFLAGS += \ + -flto \ -mthumb \ -mabi=aapcs \ -mcpu=cortex-m0 \ diff --git a/hw/bsp/lpcxpresso11u68/board.mk b/hw/bsp/lpcxpresso11u68/board.mk index c1718395..ba84b7d9 100644 --- a/hw/bsp/lpcxpresso11u68/board.mk +++ b/hw/bsp/lpcxpresso11u68/board.mk @@ -1,4 +1,5 @@ CFLAGS += \ + -flto \ -mthumb \ -mabi=aapcs \ -mcpu=cortex-m0plus \ diff --git a/hw/bsp/lpcxpresso1347/board.mk b/hw/bsp/lpcxpresso1347/board.mk index 1900ca0a..54a83a3b 100644 --- a/hw/bsp/lpcxpresso1347/board.mk +++ b/hw/bsp/lpcxpresso1347/board.mk @@ -1,4 +1,5 @@ CFLAGS += \ + -flto \ -mthumb \ -mabi=aapcs \ -mcpu=cortex-m3 \ diff --git a/hw/bsp/lpcxpresso1549/board.mk b/hw/bsp/lpcxpresso1549/board.mk index 66078f0f..18325c5f 100644 --- a/hw/bsp/lpcxpresso1549/board.mk +++ b/hw/bsp/lpcxpresso1549/board.mk @@ -1,4 +1,5 @@ CFLAGS += \ + -flto \ -mthumb \ -mabi=aapcs \ -mcpu=cortex-m3 \ diff --git a/hw/bsp/lpcxpresso1769/board.mk b/hw/bsp/lpcxpresso1769/board.mk index 412e0cd5..8d1f14c4 100644 --- a/hw/bsp/lpcxpresso1769/board.mk +++ b/hw/bsp/lpcxpresso1769/board.mk @@ -1,4 +1,5 @@ CFLAGS += \ + -flto \ -mthumb \ -mabi=aapcs \ -mcpu=cortex-m3 \ diff --git a/hw/bsp/lpcxpresso51u68/board.mk b/hw/bsp/lpcxpresso51u68/board.mk index f02dee03..61fbc062 100644 --- a/hw/bsp/lpcxpresso51u68/board.mk +++ b/hw/bsp/lpcxpresso51u68/board.mk @@ -1,4 +1,5 @@ CFLAGS += \ + -flto \ -mthumb \ -mabi=aapcs \ -mcpu=cortex-m0plus \ diff --git a/hw/bsp/lpcxpresso54114/board.mk b/hw/bsp/lpcxpresso54114/board.mk index 24de4a44..474a1ac5 100644 --- a/hw/bsp/lpcxpresso54114/board.mk +++ b/hw/bsp/lpcxpresso54114/board.mk @@ -1,4 +1,5 @@ CFLAGS += \ + -flto \ -mthumb \ -mabi=aapcs \ -mcpu=cortex-m4 \ diff --git a/hw/bsp/lpcxpresso55s69/board.mk b/hw/bsp/lpcxpresso55s69/board.mk index fada53dc..5977ce9f 100644 --- a/hw/bsp/lpcxpresso55s69/board.mk +++ b/hw/bsp/lpcxpresso55s69/board.mk @@ -1,4 +1,5 @@ CFLAGS += \ + -flto \ -mthumb \ -mabi=aapcs \ -mcpu=cortex-m33 \ diff --git a/hw/bsp/mbed1768/board.mk b/hw/bsp/mbed1768/board.mk index 9bb0a792..03176b54 100644 --- a/hw/bsp/mbed1768/board.mk +++ b/hw/bsp/mbed1768/board.mk @@ -1,4 +1,5 @@ CFLAGS += \ + -flto \ -mthumb \ -mabi=aapcs \ -mcpu=cortex-m3 \ diff --git a/hw/bsp/mcb1800/board.mk b/hw/bsp/mcb1800/board.mk index b50e47a2..2a040130 100644 --- a/hw/bsp/mcb1800/board.mk +++ b/hw/bsp/mcb1800/board.mk @@ -1,4 +1,5 @@ CFLAGS += \ + -flto \ -mthumb \ -mabi=aapcs \ -mcpu=cortex-m3 \ diff --git a/hw/bsp/metro_m0_express/board.mk b/hw/bsp/metro_m0_express/board.mk index 3ea67280..2039219a 100644 --- a/hw/bsp/metro_m0_express/board.mk +++ b/hw/bsp/metro_m0_express/board.mk @@ -1,10 +1,11 @@ CFLAGS += \ - -DCONF_DFLL_OVERWRITE_CALIBRATION=0 \ - -D__SAMD21G18A__ \ + -flto \ -mthumb \ -mabi=aapcs-linux \ -mcpu=cortex-m0plus \ -nostdlib -nostartfiles \ + -D__SAMD21G18A__ \ + -DCONF_DFLL_OVERWRITE_CALIBRATION=0 \ -DCFG_TUSB_MCU=OPT_MCU_SAMD21 # All source paths should be relative to the top level. diff --git a/hw/bsp/metro_m4_express/board.mk b/hw/bsp/metro_m4_express/board.mk index c62d9bc3..010e4b86 100644 --- a/hw/bsp/metro_m4_express/board.mk +++ b/hw/bsp/metro_m4_express/board.mk @@ -1,11 +1,12 @@ CFLAGS += \ - -D__SAMD51J19A__ \ + -flto \ -mthumb \ -mabi=aapcs-linux \ -mcpu=cortex-m4 \ -mfloat-abi=hard \ -mfpu=fpv4-sp-d16 \ -nostdlib -nostartfiles \ + -D__SAMD51J19A__ \ -DCFG_TUSB_MCU=OPT_MCU_SAMD51 CFLAGS += -Wno-error=undef diff --git a/hw/bsp/mimxrt1064_evk/mimxrt1064_evk.c b/hw/bsp/mimxrt1064_evk/mimxrt1064_evk.c index 012c8ab5..be6aa9b6 100644 --- a/hw/bsp/mimxrt1064_evk/mimxrt1064_evk.c +++ b/hw/bsp/mimxrt1064_evk/mimxrt1064_evk.c @@ -41,7 +41,7 @@ #define BUTTON_PIN 0 #define BUTTON_STATE_ACTIVE 0 -const uint8_t dcd_data[] = {0x00}; +const uint8_t dcd_data[] = { 0x00 }; void board_init(void) { diff --git a/hw/bsp/ngx4330/board.mk b/hw/bsp/ngx4330/board.mk index 565532b4..4e6032fc 100644 --- a/hw/bsp/ngx4330/board.mk +++ b/hw/bsp/ngx4330/board.mk @@ -1,4 +1,5 @@ CFLAGS += \ + -flto \ -mthumb \ -mabi=aapcs \ -mcpu=cortex-m4 \ diff --git a/hw/bsp/nrf52840_mdk_dongle/board.mk b/hw/bsp/nrf52840_mdk_dongle/board.mk index df834f96..b9255600 100644 --- a/hw/bsp/nrf52840_mdk_dongle/board.mk +++ b/hw/bsp/nrf52840_mdk_dongle/board.mk @@ -1,4 +1,5 @@ CFLAGS += \ + -flto \ -mthumb \ -mabi=aapcs \ -mcpu=cortex-m4 \ diff --git a/hw/bsp/pca10056/board.mk b/hw/bsp/pca10056/board.mk index abe0d642..b4031844 100644 --- a/hw/bsp/pca10056/board.mk +++ b/hw/bsp/pca10056/board.mk @@ -1,4 +1,5 @@ CFLAGS += \ + -flto \ -mthumb \ -mabi=aapcs \ -mcpu=cortex-m4 \ diff --git a/hw/bsp/pca10059/board.mk b/hw/bsp/pca10059/board.mk index 15801054..19ec3eae 100644 --- a/hw/bsp/pca10059/board.mk +++ b/hw/bsp/pca10059/board.mk @@ -1,4 +1,5 @@ CFLAGS += \ + -flto \ -mthumb \ -mabi=aapcs \ -mcpu=cortex-m4 \ diff --git a/hw/bsp/pca10100/board.mk b/hw/bsp/pca10100/board.mk index 97d9aa42..d7ac7ec4 100644 --- a/hw/bsp/pca10100/board.mk +++ b/hw/bsp/pca10100/board.mk @@ -1,4 +1,5 @@ CFLAGS += \ + -flto \ -mthumb \ -mabi=aapcs \ -mcpu=cortex-m4 \ diff --git a/hw/bsp/pyboardv11/board.mk b/hw/bsp/pyboardv11/board.mk index ef977797..0118b54a 100644 --- a/hw/bsp/pyboardv11/board.mk +++ b/hw/bsp/pyboardv11/board.mk @@ -1,12 +1,13 @@ CFLAGS += \ - -DHSE_VALUE=12000000 \ - -DSTM32F405xx \ + -flto \ -mthumb \ -mabi=aapcs \ -mcpu=cortex-m4 \ -mfloat-abi=hard \ -mfpu=fpv4-sp-d16 \ -nostdlib -nostartfiles \ + -DSTM32F405xx \ + -DHSE_VALUE=12000000 \ -DCFG_TUSB_MCU=OPT_MCU_STM32F4 ST_HAL_DRIVER = hw/mcu/st/st_driver/STM32F4xx_HAL_Driver diff --git a/hw/bsp/spresense/board.mk b/hw/bsp/spresense/board.mk index 16421686..2e88cf99 100644 --- a/hw/bsp/spresense/board.mk +++ b/hw/bsp/spresense/board.mk @@ -1,12 +1,3 @@ -SPRESENSE_SDK = $(TOP)/hw/mcu/sony/cxd56/spresense-exported-sdk - -INC += \ - $(SPRESENSE_SDK)/nuttx/include \ - $(SPRESENSE_SDK)/nuttx/arch \ - $(SPRESENSE_SDK)/nuttx/arch/chip \ - $(SPRESENSE_SDK)/sdk/bsp/include \ - $(SPRESENSE_SDK)/sdk/bsp/include/sdk \ - CFLAGS += \ -DCONFIG_WCHAR_BUILTIN \ -DCONFIG_HAVE_DOUBLE \ @@ -23,6 +14,15 @@ CFLAGS += \ -fomit-frame-pointer \ -DCFG_TUSB_MCU=OPT_MCU_CXD56 \ +SPRESENSE_SDK = $(TOP)/hw/mcu/sony/cxd56/spresense-exported-sdk + +INC += \ + $(SPRESENSE_SDK)/nuttx/include \ + $(SPRESENSE_SDK)/nuttx/arch \ + $(SPRESENSE_SDK)/nuttx/arch/chip \ + $(SPRESENSE_SDK)/sdk/bsp/include \ + $(SPRESENSE_SDK)/sdk/bsp/include/sdk \ + LIBS += \ $(SPRESENSE_SDK)/sdk/libs/libapps.a \ $(SPRESENSE_SDK)/sdk/libs/libsdk.a \ diff --git a/hw/bsp/stm32f070rbnucleo/board.mk b/hw/bsp/stm32f070rbnucleo/board.mk index f930f6a8..6e52b814 100644 --- a/hw/bsp/stm32f070rbnucleo/board.mk +++ b/hw/bsp/stm32f070rbnucleo/board.mk @@ -1,13 +1,14 @@ CFLAGS += \ - -DHSE_VALUE=8000000 \ - -DSTM32F070xB \ - -mthumb \ - -mabi=aapcs-linux \ - -mcpu=cortex-m0 \ - -mfloat-abi=soft \ - -nostdlib -nostartfiles \ - -DCFG_EXAMPLE_MSC_READONLY \ - -DCFG_TUSB_MCU=OPT_MCU_STM32F0 + -flto \ + -mthumb \ + -mabi=aapcs-linux \ + -mcpu=cortex-m0 \ + -mfloat-abi=soft \ + -nostdlib -nostartfiles \ + -DHSE_VALUE=8000000 \ + -DSTM32F070xB \ + -DCFG_EXAMPLE_MSC_READONLY \ + -DCFG_TUSB_MCU=OPT_MCU_STM32F0 # mcu driver cause following warnings CFLAGS += -Wno-error=unused-parameter @@ -19,21 +20,21 @@ ST_CMSIS = hw/mcu/st/st_driver/CMSIS/Device/ST/STM32F0xx LD_FILE = hw/bsp/$(BOARD)/stm32F070rbtx_flash.ld SRC_C += \ - $(ST_CMSIS)/Source/Templates/system_stm32f0xx.c \ - $(ST_HAL_DRIVER)/Src/stm32f0xx_hal.c \ - $(ST_HAL_DRIVER)/Src/stm32f0xx_hal_cortex.c \ - $(ST_HAL_DRIVER)/Src/stm32f0xx_hal_rcc.c \ - $(ST_HAL_DRIVER)/Src/stm32f0xx_hal_rcc_ex.c \ - $(ST_HAL_DRIVER)/Src/stm32f0xx_hal_gpio.c \ - $(ST_HAL_DRIVER)/Src/stm32f0xx_hal_uart.c + $(ST_CMSIS)/Source/Templates/system_stm32f0xx.c \ + $(ST_HAL_DRIVER)/Src/stm32f0xx_hal.c \ + $(ST_HAL_DRIVER)/Src/stm32f0xx_hal_cortex.c \ + $(ST_HAL_DRIVER)/Src/stm32f0xx_hal_rcc.c \ + $(ST_HAL_DRIVER)/Src/stm32f0xx_hal_rcc_ex.c \ + $(ST_HAL_DRIVER)/Src/stm32f0xx_hal_gpio.c \ + $(ST_HAL_DRIVER)/Src/stm32f0xx_hal_uart.c SRC_S += \ - $(ST_CMSIS)/Source/Templates/gcc/startup_stm32f070xb.s + $(ST_CMSIS)/Source/Templates/gcc/startup_stm32f070xb.s INC += \ - $(TOP)/hw/mcu/st/st_driver/CMSIS/Include \ - $(TOP)/$(ST_CMSIS)/Include \ - $(TOP)/$(ST_HAL_DRIVER)/Inc \ - $(TOP)/hw/bsp/$(BOARD) + $(TOP)/hw/mcu/st/st_driver/CMSIS/Include \ + $(TOP)/$(ST_CMSIS)/Include \ + $(TOP)/$(ST_HAL_DRIVER)/Inc \ + $(TOP)/hw/bsp/$(BOARD) # For TinyUSB port source VENDOR = st diff --git a/hw/bsp/stm32f072disco/board.mk b/hw/bsp/stm32f072disco/board.mk index 39715e83..5ed87cfa 100644 --- a/hw/bsp/stm32f072disco/board.mk +++ b/hw/bsp/stm32f072disco/board.mk @@ -1,13 +1,14 @@ CFLAGS += \ - -DHSE_VALUE=8000000 \ - -DSTM32F072xB \ - -mthumb \ - -mabi=aapcs \ - -mcpu=cortex-m0 \ - -mfloat-abi=soft \ - -nostdlib -nostartfiles \ - -DCFG_EXAMPLE_MSC_READONLY \ - -DCFG_TUSB_MCU=OPT_MCU_STM32F0 + -flto \ + -mthumb \ + -mabi=aapcs \ + -mcpu=cortex-m0 \ + -mfloat-abi=soft \ + -nostdlib -nostartfiles \ + -DSTM32F072xB \ + -DHSE_VALUE=8000000 \ + -DCFG_EXAMPLE_MSC_READONLY \ + -DCFG_TUSB_MCU=OPT_MCU_STM32F0 # mcu driver cause following warnings CFLAGS += -Wno-error=unused-parameter @@ -19,22 +20,22 @@ ST_CMSIS = hw/mcu/st/st_driver/CMSIS/Device/ST/STM32F0xx LD_FILE = hw/bsp/$(BOARD)/STM32F072RBTx_FLASH.ld SRC_C += \ - $(ST_CMSIS)/Source/Templates/system_stm32f0xx.c \ - $(ST_HAL_DRIVER)/Src/stm32f0xx_hal.c \ - $(ST_HAL_DRIVER)/Src/stm32f0xx_hal_cortex.c \ - $(ST_HAL_DRIVER)/Src/stm32f0xx_hal_rcc.c \ - $(ST_HAL_DRIVER)/Src/stm32f0xx_hal_rcc_ex.c \ - $(ST_HAL_DRIVER)/Src/stm32f0xx_hal_gpio.c \ - $(ST_HAL_DRIVER)/Src/stm32f0xx_hal_uart.c + $(ST_CMSIS)/Source/Templates/system_stm32f0xx.c \ + $(ST_HAL_DRIVER)/Src/stm32f0xx_hal.c \ + $(ST_HAL_DRIVER)/Src/stm32f0xx_hal_cortex.c \ + $(ST_HAL_DRIVER)/Src/stm32f0xx_hal_rcc.c \ + $(ST_HAL_DRIVER)/Src/stm32f0xx_hal_rcc_ex.c \ + $(ST_HAL_DRIVER)/Src/stm32f0xx_hal_gpio.c \ + $(ST_HAL_DRIVER)/Src/stm32f0xx_hal_uart.c SRC_S += \ - $(ST_CMSIS)/Source/Templates/gcc/startup_stm32f072xb.s + $(ST_CMSIS)/Source/Templates/gcc/startup_stm32f072xb.s INC += \ - $(TOP)/hw/mcu/st/st_driver/CMSIS/Include \ - $(TOP)/$(ST_CMSIS)/Include \ - $(TOP)/$(ST_HAL_DRIVER)/Inc \ - $(TOP)/hw/bsp/$(BOARD) + $(TOP)/hw/mcu/st/st_driver/CMSIS/Include \ + $(TOP)/$(ST_CMSIS)/Include \ + $(TOP)/$(ST_HAL_DRIVER)/Inc \ + $(TOP)/hw/bsp/$(BOARD) # For TinyUSB port source VENDOR = st diff --git a/hw/bsp/stm32f103bluepill/board.mk b/hw/bsp/stm32f103bluepill/board.mk index 26ad07b7..f464fa29 100644 --- a/hw/bsp/stm32f103bluepill/board.mk +++ b/hw/bsp/stm32f103bluepill/board.mk @@ -1,12 +1,13 @@ CFLAGS += \ - -DHSE_VALUE=8000000 \ - -DSTM32F103xB \ - -mthumb \ - -mabi=aapcs \ - -mcpu=cortex-m3 \ - -mfloat-abi=soft \ - -nostdlib -nostartfiles \ - -DCFG_TUSB_MCU=OPT_MCU_STM32F1 + -flto \ + -mthumb \ + -mabi=aapcs \ + -mcpu=cortex-m3 \ + -mfloat-abi=soft \ + -nostdlib -nostartfiles \ + -DSTM32F103xB \ + -DHSE_VALUE=8000000 \ + -DCFG_TUSB_MCU=OPT_MCU_STM32F1 # mcu driver cause following warnings #CFLAGS += -Wno-error=unused-parameter @@ -18,21 +19,21 @@ ST_CMSIS = hw/mcu/st/st_driver/CMSIS/Device/ST/STM32F1xx LD_FILE = hw/bsp/$(BOARD)/STM32F103XB_FLASH.ld SRC_C += \ - $(ST_CMSIS)/Source/Templates/system_stm32f1xx.c \ - $(ST_HAL_DRIVER)/Src/stm32f1xx_hal.c \ - $(ST_HAL_DRIVER)/Src/stm32f1xx_hal_cortex.c \ - $(ST_HAL_DRIVER)/Src/stm32f1xx_hal_rcc.c \ - $(ST_HAL_DRIVER)/Src/stm32f1xx_hal_rcc_ex.c \ - $(ST_HAL_DRIVER)/Src/stm32f1xx_hal_gpio.c + $(ST_CMSIS)/Source/Templates/system_stm32f1xx.c \ + $(ST_HAL_DRIVER)/Src/stm32f1xx_hal.c \ + $(ST_HAL_DRIVER)/Src/stm32f1xx_hal_cortex.c \ + $(ST_HAL_DRIVER)/Src/stm32f1xx_hal_rcc.c \ + $(ST_HAL_DRIVER)/Src/stm32f1xx_hal_rcc_ex.c \ + $(ST_HAL_DRIVER)/Src/stm32f1xx_hal_gpio.c SRC_S += \ - $(ST_CMSIS)/Source/Templates/gcc/startup_stm32f103xb.s + $(ST_CMSIS)/Source/Templates/gcc/startup_stm32f103xb.s INC += \ - $(TOP)/hw/mcu/st/st_driver/CMSIS/Include \ - $(TOP)/$(ST_CMSIS)/Include \ - $(TOP)/$(ST_HAL_DRIVER)/Inc \ - $(TOP)/hw/bsp/$(BOARD) + $(TOP)/hw/mcu/st/st_driver/CMSIS/Include \ + $(TOP)/$(ST_CMSIS)/Include \ + $(TOP)/$(ST_HAL_DRIVER)/Inc \ + $(TOP)/hw/bsp/$(BOARD) # For TinyUSB port source VENDOR = st diff --git a/hw/bsp/stm32f207nucleo/board.mk b/hw/bsp/stm32f207nucleo/board.mk index cd2b2620..003a3dd4 100644 --- a/hw/bsp/stm32f207nucleo/board.mk +++ b/hw/bsp/stm32f207nucleo/board.mk @@ -1,12 +1,13 @@ CFLAGS += \ - -DHSE_VALUE=8000000 \ - -DSTM32F207xx \ - -mthumb \ - -mabi=aapcs \ - -mcpu=cortex-m3 \ - -mfloat-abi=soft \ - -nostdlib -nostartfiles \ - -DCFG_TUSB_MCU=OPT_MCU_STM32F2 + -flto \ + -mthumb \ + -mabi=aapcs \ + -mcpu=cortex-m3 \ + -mfloat-abi=soft \ + -nostdlib -nostartfiles \ + -DSTM32F207xx \ + -DHSE_VALUE=8000000 \ + -DCFG_TUSB_MCU=OPT_MCU_STM32F2 # mcu driver cause following warnings CFLAGS += -Wno-error=sign-compare @@ -18,21 +19,21 @@ ST_CMSIS = hw/mcu/st/st_driver/CMSIS/Device/ST/STM32F2xx LD_FILE = hw/bsp/$(BOARD)/STM32F207ZGTx_FLASH.ld SRC_C += \ - $(ST_CMSIS)/Source/Templates/system_stm32f2xx.c \ - $(ST_HAL_DRIVER)/Src/stm32f2xx_hal.c \ - $(ST_HAL_DRIVER)/Src/stm32f2xx_hal_cortex.c \ - $(ST_HAL_DRIVER)/Src/stm32f2xx_hal_rcc.c \ - $(ST_HAL_DRIVER)/Src/stm32f2xx_hal_rcc_ex.c \ - $(ST_HAL_DRIVER)/Src/stm32f2xx_hal_gpio.c + $(ST_CMSIS)/Source/Templates/system_stm32f2xx.c \ + $(ST_HAL_DRIVER)/Src/stm32f2xx_hal.c \ + $(ST_HAL_DRIVER)/Src/stm32f2xx_hal_cortex.c \ + $(ST_HAL_DRIVER)/Src/stm32f2xx_hal_rcc.c \ + $(ST_HAL_DRIVER)/Src/stm32f2xx_hal_rcc_ex.c \ + $(ST_HAL_DRIVER)/Src/stm32f2xx_hal_gpio.c SRC_S += \ - $(ST_CMSIS)/Source/Templates/gcc/startup_stm32f207xx.s + $(ST_CMSIS)/Source/Templates/gcc/startup_stm32f207xx.s INC += \ - $(TOP)/hw/mcu/st/st_driver/CMSIS/Include \ - $(TOP)/$(ST_CMSIS)/Include \ - $(TOP)/$(ST_HAL_DRIVER)/Inc \ - $(TOP)/hw/bsp/$(BOARD) + $(TOP)/hw/mcu/st/st_driver/CMSIS/Include \ + $(TOP)/$(ST_CMSIS)/Include \ + $(TOP)/$(ST_HAL_DRIVER)/Inc \ + $(TOP)/hw/bsp/$(BOARD) # For TinyUSB port source VENDOR = st diff --git a/hw/bsp/stm32f303disco/board.mk b/hw/bsp/stm32f303disco/board.mk index ab77c55c..fbe03414 100644 --- a/hw/bsp/stm32f303disco/board.mk +++ b/hw/bsp/stm32f303disco/board.mk @@ -1,13 +1,14 @@ CFLAGS += \ - -DHSE_VALUE=8000000 \ - -DSTM32F303xC \ - -mthumb \ - -mabi=aapcs \ - -mcpu=cortex-m4 \ - -mfloat-abi=hard \ - -mfpu=fpv4-sp-d16 \ - -nostdlib -nostartfiles \ - -DCFG_TUSB_MCU=OPT_MCU_STM32F3 + -flto \ + -mthumb \ + -mabi=aapcs \ + -mcpu=cortex-m4 \ + -mfloat-abi=hard \ + -mfpu=fpv4-sp-d16 \ + -nostdlib -nostartfiles \ + -DSTM32F303xC \ + -DHSE_VALUE=8000000 \ + -DCFG_TUSB_MCU=OPT_MCU_STM32F3 # mcu driver cause following warnings CFLAGS += -Wno-error=unused-parameter @@ -19,21 +20,21 @@ ST_CMSIS = hw/mcu/st/st_driver/CMSIS/Device/ST/STM32F3xx LD_FILE = hw/bsp/$(BOARD)/STM32F303VCTx_FLASH.ld SRC_C += \ - $(ST_CMSIS)/Source/Templates/system_stm32f3xx.c \ - $(ST_HAL_DRIVER)/Src/stm32f3xx_hal.c \ - $(ST_HAL_DRIVER)/Src/stm32f3xx_hal_cortex.c \ - $(ST_HAL_DRIVER)/Src/stm32f3xx_hal_rcc.c \ - $(ST_HAL_DRIVER)/Src/stm32f3xx_hal_rcc_ex.c \ - $(ST_HAL_DRIVER)/Src/stm32f3xx_hal_gpio.c + $(ST_CMSIS)/Source/Templates/system_stm32f3xx.c \ + $(ST_HAL_DRIVER)/Src/stm32f3xx_hal.c \ + $(ST_HAL_DRIVER)/Src/stm32f3xx_hal_cortex.c \ + $(ST_HAL_DRIVER)/Src/stm32f3xx_hal_rcc.c \ + $(ST_HAL_DRIVER)/Src/stm32f3xx_hal_rcc_ex.c \ + $(ST_HAL_DRIVER)/Src/stm32f3xx_hal_gpio.c SRC_S += \ - $(ST_CMSIS)/Source/Templates/gcc/startup_stm32f303xc.s + $(ST_CMSIS)/Source/Templates/gcc/startup_stm32f303xc.s INC += \ - $(TOP)/hw/mcu/st/st_driver/CMSIS/Include \ - $(TOP)/$(ST_CMSIS)/Include \ - $(TOP)/$(ST_HAL_DRIVER)/Inc \ - $(TOP)/hw/bsp/$(BOARD) + $(TOP)/hw/mcu/st/st_driver/CMSIS/Include \ + $(TOP)/$(ST_CMSIS)/Include \ + $(TOP)/$(ST_HAL_DRIVER)/Inc \ + $(TOP)/hw/bsp/$(BOARD) # For TinyUSB port source VENDOR = st diff --git a/hw/bsp/stm32f407disco/board.mk b/hw/bsp/stm32f407disco/board.mk index 4f4c1009..216b51bf 100644 --- a/hw/bsp/stm32f407disco/board.mk +++ b/hw/bsp/stm32f407disco/board.mk @@ -1,12 +1,13 @@ CFLAGS += \ - -DHSE_VALUE=8000000 \ - -DSTM32F407xx \ + -flto \ -mthumb \ -mabi=aapcs \ -mcpu=cortex-m4 \ -mfloat-abi=hard \ -mfpu=fpv4-sp-d16 \ -nostdlib -nostartfiles \ + -DSTM32F407xx \ + -DHSE_VALUE=8000000 \ -DCFG_TUSB_MCU=OPT_MCU_STM32F4 ST_HAL_DRIVER = hw/mcu/st/st_driver/STM32F4xx_HAL_Driver diff --git a/hw/bsp/stm32f411disco/board.mk b/hw/bsp/stm32f411disco/board.mk index dcfee33c..63aa7615 100644 --- a/hw/bsp/stm32f411disco/board.mk +++ b/hw/bsp/stm32f411disco/board.mk @@ -1,12 +1,13 @@ CFLAGS += \ - -DHSE_VALUE=8000000 \ - -DSTM32F411xE \ + -flto \ -mthumb \ -mabi=aapcs \ -mcpu=cortex-m4 \ -mfloat-abi=hard \ -mfpu=fpv4-sp-d16 \ -nostdlib -nostartfiles \ + -DSTM32F411xE \ + -DHSE_VALUE=8000000 \ -DCFG_TUSB_MCU=OPT_MCU_STM32F4 ST_HAL_DRIVER = hw/mcu/st/st_driver/STM32F4xx_HAL_Driver diff --git a/hw/bsp/stm32f412disco/board.mk b/hw/bsp/stm32f412disco/board.mk index e059c81d..ddb8402e 100644 --- a/hw/bsp/stm32f412disco/board.mk +++ b/hw/bsp/stm32f412disco/board.mk @@ -1,12 +1,13 @@ CFLAGS += \ - -DHSE_VALUE=8000000 \ - -DSTM32F412Zx \ + -flto \ -mthumb \ -mabi=aapcs \ -mcpu=cortex-m4 \ -mfloat-abi=hard \ -mfpu=fpv4-sp-d16 \ -nostdlib -nostartfiles \ + -DSTM32F412Zx \ + -DHSE_VALUE=8000000 \ -DCFG_TUSB_MCU=OPT_MCU_STM32F4 # mcu driver cause following warnings diff --git a/hw/bsp/stm32f767nucleo/board.mk b/hw/bsp/stm32f767nucleo/board.mk index 46023334..5d964537 100644 --- a/hw/bsp/stm32f767nucleo/board.mk +++ b/hw/bsp/stm32f767nucleo/board.mk @@ -1,12 +1,13 @@ CFLAGS += \ - -DHSE_VALUE=8000000 \ - -DSTM32F767xx \ + -flto \ -mthumb \ -mabi=aapcs \ -mcpu=cortex-m7 \ -mfloat-abi=hard \ -mfpu=fpv5-d16 \ -nostdlib -nostartfiles \ + -DSTM32F767xx \ + -DHSE_VALUE=8000000 \ -DCFG_TUSB_MCU=OPT_MCU_STM32F7 # mcu driver cause following warnings diff --git a/hw/bsp/stm32h743nucleo/board.mk b/hw/bsp/stm32h743nucleo/board.mk index 40b36413..cfea7f57 100644 --- a/hw/bsp/stm32h743nucleo/board.mk +++ b/hw/bsp/stm32h743nucleo/board.mk @@ -1,12 +1,13 @@ CFLAGS += \ - -DHSE_VALUE=8000000 \ - -DSTM32H743xx \ + -flto \ -mthumb \ -mabi=aapcs \ -mcpu=cortex-m7 \ -mfloat-abi=hard \ -mfpu=fpv5-d16 \ -nostdlib -nostartfiles \ + -DSTM32H743xx \ + -DHSE_VALUE=8000000 \ -DCFG_TUSB_MCU=OPT_MCU_STM32H7 # mcu driver cause following warnings diff --git a/hw/bsp/stm32l0538disco/board.mk b/hw/bsp/stm32l0538disco/board.mk index 7e11fa6c..d81b2d88 100644 --- a/hw/bsp/stm32l0538disco/board.mk +++ b/hw/bsp/stm32l0538disco/board.mk @@ -1,13 +1,14 @@ CFLAGS += \ - -DHSE_VALUE=8000000 \ - -DSTM32L053xx \ - -mthumb \ - -mabi=aapcs \ - -mcpu=cortex-m0plus \ - -mfloat-abi=soft \ - -nostdlib -nostartfiles \ - -DCFG_EXAMPLE_MSC_READONLY \ - -DCFG_TUSB_MCU=OPT_MCU_STM32L0 + -flto \ + -mthumb \ + -mabi=aapcs \ + -mcpu=cortex-m0plus \ + -mfloat-abi=soft \ + -nostdlib -nostartfiles \ + -DSTM32L053xx \ + -DHSE_VALUE=8000000 \ + -DCFG_EXAMPLE_MSC_READONLY \ + -DCFG_TUSB_MCU=OPT_MCU_STM32L0 # mcu driver cause following warnings CFLAGS += -Wno-error=unused-parameter -Wno-error=maybe-uninitialized @@ -19,21 +20,21 @@ ST_CMSIS = hw/mcu/st/st_driver/CMSIS/Device/ST/STM32L0xx LD_FILE = hw/bsp/$(BOARD)/STM32L053C8Tx_FLASH.ld SRC_C += \ - $(ST_CMSIS)/Source/Templates/system_stm32l0xx.c \ - $(ST_HAL_DRIVER)/Src/stm32l0xx_hal.c \ - $(ST_HAL_DRIVER)/Src/stm32l0xx_hal_cortex.c \ - $(ST_HAL_DRIVER)/Src/stm32l0xx_hal_rcc.c \ - $(ST_HAL_DRIVER)/Src/stm32l0xx_hal_rcc_ex.c \ - $(ST_HAL_DRIVER)/Src/stm32l0xx_hal_gpio.c + $(ST_CMSIS)/Source/Templates/system_stm32l0xx.c \ + $(ST_HAL_DRIVER)/Src/stm32l0xx_hal.c \ + $(ST_HAL_DRIVER)/Src/stm32l0xx_hal_cortex.c \ + $(ST_HAL_DRIVER)/Src/stm32l0xx_hal_rcc.c \ + $(ST_HAL_DRIVER)/Src/stm32l0xx_hal_rcc_ex.c \ + $(ST_HAL_DRIVER)/Src/stm32l0xx_hal_gpio.c SRC_S += \ - $(ST_CMSIS)/Source/Templates/gcc/startup_stm32l053xx.s + $(ST_CMSIS)/Source/Templates/gcc/startup_stm32l053xx.s INC += \ - $(TOP)/hw/mcu/st/st_driver/CMSIS/Include \ - $(TOP)/$(ST_CMSIS)/Include \ - $(TOP)/$(ST_HAL_DRIVER)/Inc \ - $(TOP)/hw/bsp/$(BOARD) + $(TOP)/hw/mcu/st/st_driver/CMSIS/Include \ + $(TOP)/$(ST_CMSIS)/Include \ + $(TOP)/$(ST_HAL_DRIVER)/Inc \ + $(TOP)/hw/bsp/$(BOARD) # For TinyUSB port source VENDOR = st diff --git a/hw/bsp/stm32l476disco/board.mk b/hw/bsp/stm32l476disco/board.mk index c987fea6..3432ac2e 100644 --- a/hw/bsp/stm32l476disco/board.mk +++ b/hw/bsp/stm32l476disco/board.mk @@ -1,12 +1,13 @@ CFLAGS += \ - -DHSE_VALUE=8000000 \ - -DSTM32L476xx \ + -flto \ -mthumb \ -mabi=aapcs \ -mcpu=cortex-m4 \ -mfloat-abi=hard \ -mfpu=fpv4-sp-d16 \ -nostdlib -nostartfiles \ + -DSTM32L476xx \ + -DHSE_VALUE=8000000 \ -DCFG_TUSB_MCU=OPT_MCU_STM32L4 ST_HAL_DRIVER = hw/mcu/st/st_driver/STM32L4xx_HAL_Driver From a9282eab51e7342cb464fcf995d8612ee606357c Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Wed, 20 Nov 2019 17:45:21 +0800 Subject: [PATCH 057/267] eptri: clear proper endpoint when opening IN port When opening a USB port, we ensure the buffer is NULL and has a length of 0. Due to a mistake in specifying the endpoint type, we never actually cleared the value when opening an IN endpoint. This patch fixes the comparison when opening an IN endpoint. This fixes issue #218. Signed-off-by: Sean Cross --- src/portable/valentyusb/eptri/dcd_eptri.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/portable/valentyusb/eptri/dcd_eptri.c b/src/portable/valentyusb/eptri/dcd_eptri.c index d7e1b8a9..e555fb0b 100644 --- a/src/portable/valentyusb/eptri/dcd_eptri.c +++ b/src/portable/valentyusb/eptri/dcd_eptri.c @@ -415,7 +415,7 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc) rx_buffer[ep_num] = NULL; } - else if (ep_dir == TUSB_DIR_OUT) { + else if (ep_dir == TUSB_DIR_IN) { tx_buffer_offset[ep_num] = 0; tx_buffer_max[ep_num] = 0; tx_buffer[ep_num] = NULL; From 54d597b72392fc7d7e4785eadd3eaecb073ed216 Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 20 Nov 2019 17:10:30 +0700 Subject: [PATCH 058/267] rt1064evk led, button, uart all work --- hw/bsp/mimxrt1064_evk/board.mk | 8 +++- hw/bsp/mimxrt1064_evk/mimxrt1064_evk.c | 64 +++++++++++++------------- 2 files changed, 38 insertions(+), 34 deletions(-) diff --git a/hw/bsp/mimxrt1064_evk/board.mk b/hw/bsp/mimxrt1064_evk/board.mk index e88d58d6..1163810e 100644 --- a/hw/bsp/mimxrt1064_evk/board.mk +++ b/hw/bsp/mimxrt1064_evk/board.mk @@ -51,5 +51,9 @@ JLINK_DEVICE = MIMXRT1064xxx6A JLINK_IF = swd # flash using pyocd -flash: $(BUILD)/$(BOARD)-firmware.hex - pyocd flash -t mimxrt1050_quadspi $< +#flash: $(BUILD)/$(BOARD)-firmware.hex +# pyocd flash -t mimxrt1050_quadspi $< + +flash: $(BUILD)/$(BOARD)-firmware.bin + cp $< /media/$(USER)/RT1064-EVK/ + diff --git a/hw/bsp/mimxrt1064_evk/mimxrt1064_evk.c b/hw/bsp/mimxrt1064_evk/mimxrt1064_evk.c index be6aa9b6..1673c01c 100644 --- a/hw/bsp/mimxrt1064_evk/mimxrt1064_evk.c +++ b/hw/bsp/mimxrt1064_evk/mimxrt1064_evk.c @@ -29,18 +29,26 @@ #include "fsl_gpio.h" #include "fsl_iomuxc.h" #include "fsl_clock.h" +#include "fsl_lpuart.h" #include "clock_config.h" +#define LED_PINMUX IOMUXC_GPIO_AD_B0_09_GPIO1_IO09 #define LED_PORT GPIO1 #define LED_PIN 9 #define LED_STATE_ON 0 // SW8 button +#define BUTTON_PINMUX IOMUXC_SNVS_WAKEUP_GPIO5_IO00 #define BUTTON_PORT GPIO5 #define BUTTON_PIN 0 #define BUTTON_STATE_ACTIVE 0 +// UART +#define UART_PORT LPUART1 +#define UART_RX_PINMUX IOMUXC_GPIO_AD_B0_13_LPUART1_RX +#define UART_TX_PINMUX IOMUXC_GPIO_AD_B0_12_LPUART1_TX + const uint8_t dcd_data[] = { 0x00 }; void board_init(void) @@ -51,48 +59,40 @@ void board_init(void) // Enable IOCON clock CLOCK_EnableClock(kCLOCK_Iomuxc); -// CLOCK_EnableClock(kCLOCK_IomuxcSnvs); - - /* GPIO_AD_B0_09 is configured as GPIO1_IO09 */ - IOMUXC_SetPinMux( IOMUXC_GPIO_AD_B0_09_GPIO1_IO09, 0U); - - IOMUXC_GPR->GPR26 = ((IOMUXC_GPR->GPR26 & - (~(IOMUXC_GPR_GPR26_GPIO_MUX1_GPIO_SEL_MASK))) /* Mask bits to zero which are setting */ - | IOMUXC_GPR_GPR26_GPIO_MUX1_GPIO_SEL(0x00U) /* GPIO1 and GPIO6 share same IO MUX function, GPIO_MUX1 selects one GPIO function: 0x00U */ - ); - - /* GPIO_AD_B0_09 PAD functional properties : */ - /* Slew Rate Field: Slow Slew Rate - Drive Strength Field: R0/6 - Speed Field: medium(100MHz) - Open Drain Enable Field: Open Drain Disabled - Pull / Keep Enable Field: Pull/Keeper Enabled - Pull / Keep Select Field: Keeper - Pull Up / Down Config. Field: 100K Ohm Pull Down - Hyst. Enable Field: Hysteresis Disabled */ - IOMUXC_SetPinConfig( IOMUXC_GPIO_AD_B0_09_GPIO1_IO09, 0x10B0U); - - -// IOMUXC_SetPinMux( -// IOMUXC_SNVS_WAKEUP_GPIO5_IO00, /* WAKEUP is configured as GPIO5_IO00 */ -// 0U); /* Software Input On Field: Input Path is determined by functionality */ #if CFG_TUSB_OS == OPT_OS_NONE // 1ms tick timer SysTick_Config(SystemCoreClock / 1000); #elif CFG_TUSB_OS == OPT_OS_FREERTOS // If freeRTOS is used, IRQ priority is limit by max syscall ( smaller is higher ) - NVIC_SetPriority(USB0_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY ); +// NVIC_SetPriority(USB0_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY ); #endif // LED + IOMUXC_SetPinMux( LED_PINMUX, 0U); + IOMUXC_SetPinConfig( LED_PINMUX, 0x10B0U); + gpio_pin_config_t led_config = { kGPIO_DigitalOutput, 0, kGPIO_NoIntmode }; GPIO_PinInit(LED_PORT, LED_PIN, &led_config); board_led_write(true); // Button -// gpio_pin_config_t button_config = { kGPIO_DigitalInput, 0, kGPIO_IntRisingEdge, }; -// GPIO_PinInit(BUTTON_PORT, BUTTON_PIN, &button_config); + IOMUXC_SetPinMux( BUTTON_PINMUX, 0U); + gpio_pin_config_t button_config = { kGPIO_DigitalInput, 0, kGPIO_IntRisingEdge, }; + GPIO_PinInit(BUTTON_PORT, BUTTON_PIN, &button_config); + + // UART + IOMUXC_SetPinMux( UART_TX_PINMUX, 0U); + IOMUXC_SetPinMux( UART_RX_PINMUX, 0U); + IOMUXC_SetPinConfig( UART_TX_PINMUX, 0x10B0u); + IOMUXC_SetPinConfig( UART_RX_PINMUX, 0x10B0u); + + lpuart_config_t uart_config; + LPUART_GetDefaultConfig(&uart_config); + uart_config.baudRate_Bps = CFG_BOARD_UART_BAUDRATE; + uart_config.enableTx = true; + uart_config.enableRx = true; + LPUART_Init(UART_PORT, &uart_config, (CLOCK_GetPllFreq(kCLOCK_PllUsb1) / 6U) / (CLOCK_GetDiv(kCLOCK_UartDiv) + 1U)); #if 0 // USB VBUS @@ -161,14 +161,14 @@ uint32_t board_button_read(void) int board_uart_read(uint8_t* buf, int len) { - (void) buf; (void) len; - return 0; + LPUART_ReadBlocking(UART_PORT, buf, len); + return len; } int board_uart_write(void const * buf, int len) { - (void) buf; (void) len; - return 0; + LPUART_WriteBlocking(UART_PORT, (uint8_t*)buf, len); + return len; } #if CFG_TUSB_OS == OPT_OS_NONE From 043697ab9589955f831f4f716bb37b5470ba11f6 Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 21 Nov 2019 16:08:08 +0700 Subject: [PATCH 059/267] rename lpc 17/18 irq to dcd_isr/hcd_isr --- hw/bsp/mimxrt1064_evk/mimxrt1064_evk.c | 62 +++++++----------------- src/host/ehci/ehci.c | 2 +- src/host/ohci/ohci.c | 2 +- src/portable/nxp/lpc17_40/dcd_lpc17_40.c | 2 +- src/portable/nxp/lpc17_40/hal_lpc17_40.c | 8 +-- src/portable/nxp/lpc18_43/dcd_lpc18_43.c | 10 ++-- src/portable/nxp/lpc18_43/hal_lpc18_43.c | 22 ++++++--- 7 files changed, 47 insertions(+), 61 deletions(-) diff --git a/hw/bsp/mimxrt1064_evk/mimxrt1064_evk.c b/hw/bsp/mimxrt1064_evk/mimxrt1064_evk.c index 1673c01c..62117e64 100644 --- a/hw/bsp/mimxrt1064_evk/mimxrt1064_evk.c +++ b/hw/bsp/mimxrt1064_evk/mimxrt1064_evk.c @@ -94,54 +94,28 @@ void board_init(void) uart_config.enableRx = true; LPUART_Init(UART_PORT, &uart_config, (CLOCK_GetPllFreq(kCLOCK_PllUsb1) / 6U) / (CLOCK_GetDiv(kCLOCK_UartDiv) + 1U)); -#if 0 - // USB VBUS - const uint32_t port0_pin22_config = ( - IOCON_PIO_FUNC7 | /* Pin is configured as USB0_VBUS */ - IOCON_PIO_MODE_INACT | /* No addition pin function */ - IOCON_PIO_SLEW_STANDARD | /* Standard mode, output slew rate control is enabled */ - IOCON_PIO_INV_DI | /* Input function is not inverted */ - IOCON_PIO_DIGITAL_EN | /* Enables digital function */ - IOCON_PIO_OPENDRAIN_DI /* Open drain is disabled */ - ); - /* PORT0 PIN22 (coords: 78) is configured as USB0_VBUS */ - IOCON_PinMuxSet(IOCON, 0U, 22U, port0_pin22_config); + //------------- USB0 -------------// + // Clock + CLOCK_EnableUsbhs0PhyPllClock(kCLOCK_Usbphy480M, 480000000U); + CLOCK_EnableUsbhs0Clock(kCLOCK_Usb480M, 480000000U); - // USB Controller - POWER_DisablePD(kPDRUNCFG_PD_USB0_PHY); /*Turn on USB0 Phy */ - POWER_DisablePD(kPDRUNCFG_PD_USB1_PHY); /*< Turn on USB1 Phy */ + USBPHY_Type* usb_phy = USBPHY1; - /* reset the IP to make sure it's in reset state. */ - RESET_PeripheralReset(kUSB0D_RST_SHIFT_RSTn); - RESET_PeripheralReset(kUSB0HSL_RST_SHIFT_RSTn); - RESET_PeripheralReset(kUSB0HMR_RST_SHIFT_RSTn); - RESET_PeripheralReset(kUSB1H_RST_SHIFT_RSTn); - RESET_PeripheralReset(kUSB1D_RST_SHIFT_RSTn); - RESET_PeripheralReset(kUSB1_RST_SHIFT_RSTn); - RESET_PeripheralReset(kUSB1RAM_RST_SHIFT_RSTn); + // Enable PHY support for Low speed device + LS via FS Hub + usb_phy->CTRL |= USBPHY_CTRL_SET_ENUTMILEVEL2_MASK | USBPHY_CTRL_SET_ENUTMILEVEL3_MASK; -#if (defined USB_DEVICE_CONFIG_LPCIP3511HS) && (USB_DEVICE_CONFIG_LPCIP3511HS) - CLOCK_EnableClock(kCLOCK_Usbh1); - /* Put PHY powerdown under software control */ - *((uint32_t *)(USBHSH_BASE + 0x50)) = USBHSH_PORTMODE_SW_PDCOM_MASK; - /* According to reference mannual, device mode setting has to be set by access usb host register */ - *((uint32_t *)(USBHSH_BASE + 0x50)) |= USBHSH_PORTMODE_DEV_ENABLE_MASK; - /* enable usb1 host clock */ - CLOCK_DisableClock(kCLOCK_Usbh1); -#endif + // Enable all power for normal operation + usb_phy->PWD = 0; -#if 1 || (defined USB_DEVICE_CONFIG_LPCIP3511FS) && (USB_DEVICE_CONFIG_LPCIP3511FS) - CLOCK_SetClkDiv(kCLOCK_DivUsb0Clk, 1, false); - CLOCK_AttachClk(kFRO_HF_to_USB0_CLK); - /* enable usb0 host clock */ - CLOCK_EnableClock(kCLOCK_Usbhsl0); - /*According to reference mannual, device mode setting has to be set by access usb host register */ - *((uint32_t *)(USBFSH_BASE + 0x5C)) |= USBFSH_PORTMODE_DEV_ENABLE_MASK; - /* disable usb0 host clock */ - CLOCK_DisableClock(kCLOCK_Usbhsl0); - CLOCK_EnableUsbfs0DeviceClock(kCLOCK_UsbfsSrcFro, CLOCK_GetFreq(kCLOCK_FroHf)); /* enable USB Device clock */ -#endif -#endif + // TX Timing + uint32_t phytx = usb_phy->TX; + phytx &= ~(USBPHY_TX_D_CAL_MASK | USBPHY_TX_TXCAL45DM_MASK | USBPHY_TX_TXCAL45DP_MASK); + phytx |= USBPHY_TX_D_CAL(0x0C) | USBPHY_TX_TXCAL45DP(0x06) | USBPHY_TX_TXCAL45DM(0x06); + usb_phy->TX = phytx; + + // USB1 +// CLOCK_EnableUsbhs1PhyPllClock(kCLOCK_Usbphy480M, 480000000U); +// CLOCK_EnableUsbhs1Clock(kCLOCK_Usb480M, 480000000U); } //--------------------------------------------------------------------+ diff --git a/src/host/ehci/ehci.c b/src/host/ehci/ehci.c index 63e87dd5..04ee5c5c 100644 --- a/src/host/ehci/ehci.c +++ b/src/host/ehci/ehci.c @@ -623,7 +623,7 @@ static void xfer_error_isr(uint8_t hostid) } //------------- Host Controller Driver's Interrupt Handler -------------// -void hal_hcd_isr(uint8_t rhport) +void hcd_isr(uint8_t rhport) { ehci_registers_t* regs = ehci_data.regs; diff --git a/src/host/ohci/ohci.c b/src/host/ohci/ohci.c index ea553baa..9fa861ac 100644 --- a/src/host/ohci/ohci.c +++ b/src/host/ohci/ohci.c @@ -599,7 +599,7 @@ static void done_queue_isr(uint8_t hostid) } } -void hal_hcd_isr(uint8_t hostid) +void hcd_isr(uint8_t hostid) { uint32_t const int_en = OHCI_REG->interrupt_enable; uint32_t const int_status = OHCI_REG->interrupt_status & int_en; diff --git a/src/portable/nxp/lpc17_40/dcd_lpc17_40.c b/src/portable/nxp/lpc17_40/dcd_lpc17_40.c index 8c439616..89a4ba3f 100644 --- a/src/portable/nxp/lpc17_40/dcd_lpc17_40.c +++ b/src/portable/nxp/lpc17_40/dcd_lpc17_40.c @@ -495,7 +495,7 @@ static void dd_complete_isr(uint8_t rhport, uint8_t ep_id) } // main USB IRQ handler -void hal_dcd_isr(uint8_t rhport) +void dcd_isr(uint8_t rhport) { uint32_t const dev_int_status = LPC_USB->DevIntSt & LPC_USB->DevIntEn; LPC_USB->DevIntClr = dev_int_status;// Acknowledge handled interrupt diff --git a/src/portable/nxp/lpc17_40/hal_lpc17_40.c b/src/portable/nxp/lpc17_40/hal_lpc17_40.c index e83e3e9a..bc2477a9 100644 --- a/src/portable/nxp/lpc17_40/hal_lpc17_40.c +++ b/src/portable/nxp/lpc17_40/hal_lpc17_40.c @@ -30,17 +30,17 @@ #include "chip.h" -extern void hal_hcd_isr(uint8_t hostid); -extern void hal_dcd_isr(uint8_t rhport); +extern void hcd_isr(uint8_t hostid); +extern void dcd_isr(uint8_t rhport); void USB_IRQHandler(void) { #if TUSB_OPT_HOST_ENABLED - hal_hcd_isr(0); + hcd_isr(0); #endif #if TUSB_OPT_DEVICE_ENABLED - hal_dcd_isr(0); + dcd_isr(0); #endif } diff --git a/src/portable/nxp/lpc18_43/dcd_lpc18_43.c b/src/portable/nxp/lpc18_43/dcd_lpc18_43.c index 3619a7c2..30cab820 100644 --- a/src/portable/nxp/lpc18_43/dcd_lpc18_43.c +++ b/src/portable/nxp/lpc18_43/dcd_lpc18_43.c @@ -26,7 +26,7 @@ #include "tusb_option.h" -#if TUSB_OPT_DEVICE_ENABLED && (CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_LPC43XX) +#if TUSB_OPT_DEVICE_ENABLED && (CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_RT10XX) //--------------------------------------------------------------------+ // INCLUDE @@ -35,7 +35,11 @@ #include "device/dcd.h" #include "dcd_lpc18_43.h" -#include "chip.h" +#if CFG_TUSB_MCU == OPT_MCU_RT10XX + #include "fsl_device_registers.h" +#else + #include "chip.h" +#endif //--------------------------------------------------------------------+ // MACRO CONSTANT TYPEDEF @@ -270,7 +274,7 @@ bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t t //--------------------------------------------------------------------+ // ISR //--------------------------------------------------------------------+ -void hal_dcd_isr(uint8_t rhport) +void dcd_isr(uint8_t rhport) { LPC_USBHS_T* const lpc_usb = LPC_USB[rhport]; diff --git a/src/portable/nxp/lpc18_43/hal_lpc18_43.c b/src/portable/nxp/lpc18_43/hal_lpc18_43.c index 3f4e9c23..5710b9ff 100644 --- a/src/portable/nxp/lpc18_43/hal_lpc18_43.c +++ b/src/portable/nxp/lpc18_43/hal_lpc18_43.c @@ -26,35 +26,43 @@ #include "tusb.h" -#if (CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_LPC43XX) +#if (CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_RT10XX) #include "chip.h" -extern void hal_dcd_isr(uint8_t rhport); -extern void hal_hcd_isr(uint8_t hostid); +extern void dcd_isr(uint8_t rhport); +extern void hcd_isr(uint8_t hostid); #if CFG_TUSB_RHPORT0_MODE +#if CFG_TUSB_MCU == OPT_MCU_RT10XX +void USB_OTG1_IRQHandler(void) +#else void USB0_IRQHandler(void) +#endif { #if TUSB_OPT_HOST_ENABLED - hal_hcd_isr(0); + hcd_isr(0); #endif #if TUSB_OPT_DEVICE_ENABLED - hal_dcd_isr(0); + dcd_isr(0); #endif } #endif #if CFG_TUSB_RHPORT1_MODE +#if CFG_TUSB_MCU == OPT_MCU_RT10XX +void USB_OTG2_IRQHandler(void) +#else void USB1_IRQHandler(void) +#endif { #if TUSB_OPT_HOST_ENABLED - hal_hcd_isr(1); + hcd_isr(1); #endif #if TUSB_OPT_DEVICE_ENABLED - hal_dcd_isr(1); + dcd_isr(1); #endif } #endif From 9fe34c2e622ed8b1333839aae7b823d87e78f0ea Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 21 Nov 2019 16:37:34 +0700 Subject: [PATCH 060/267] update build all script to build a specific --- tools/build_all.py | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/tools/build_all.py b/tools/build_all.py index b2078504..9f35aac6 100644 --- a/tools/build_all.py +++ b/tools/build_all.py @@ -15,12 +15,17 @@ exit_status = 0 total_time = time.monotonic() all_examples = [] -for entry in os.scandir("examples/device"): - if entry.is_dir(): - all_examples.append(entry.name) -# TODO update freeRTOS example to work with all boards (only nrf52840 now) -all_examples.remove("cdc_msc_hid_freertos") +# build all example if input not existed +if len(sys.argv) > 1: + all_examples.append(sys.argv[1]) +else: + for entry in os.scandir("examples/device"): + if entry.is_dir(): + all_examples.append(entry.name) + + # TODO update freeRTOS example to work with all boards (only nrf52840 now) + all_examples.remove("cdc_msc_hid_freertos") all_boards = [] for entry in os.scandir("hw/bsp"): @@ -31,7 +36,7 @@ for entry in os.scandir("hw/bsp"): def build_example(example, board): subprocess.run("make -C examples/device/{} BOARD={} clean".format(example, board), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) - return subprocess.run("make -j 4 -C examples/device/{} BOARD={} all".format(example, board), shell=True, + return subprocess.run("make -j 8 -C examples/device/{} BOARD={} all".format(example, board), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) From bbec47b647ab7b2e38644ffff60f45b54b791d42 Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 21 Nov 2019 22:20:30 +0700 Subject: [PATCH 061/267] adding tud_isr/tuh_isr with lpc18/43 --- hw/bsp/ea4357/board.mk | 3 --- hw/bsp/ea4357/ea4357.c | 25 +++++++++++++++++++++++++ hw/bsp/mcb1800/board.mk | 3 --- hw/bsp/mcb1800/mcb1800.c | 25 +++++++++++++++++++++++++ hw/bsp/ngx4330/board.mk | 3 --- hw/bsp/ngx4330/ngx4330.c | 25 +++++++++++++++++++++++++ src/device/usbd.h | 3 +++ src/host/usbh.h | 3 +++ 8 files changed, 81 insertions(+), 9 deletions(-) diff --git a/hw/bsp/ea4357/board.mk b/hw/bsp/ea4357/board.mk index 8e7367fa..8c3cfd82 100644 --- a/hw/bsp/ea4357/board.mk +++ b/hw/bsp/ea4357/board.mk @@ -16,9 +16,6 @@ MCU_DIR = hw/mcu/nxp/lpcopen/lpc43xx/lpc_chip_43xx # All source paths should be relative to the top level. LD_FILE = hw/bsp/ea4357/lpc4357.ld -# TODO remove later -SRC_C += src/portable/$(VENDOR)/$(CHIP_FAMILY)/hal_$(CHIP_FAMILY).c - SRC_C += \ $(MCU_DIR)/../gcc/cr_startup_lpc43xx.c \ $(MCU_DIR)/src/chip_18xx_43xx.c \ diff --git a/hw/bsp/ea4357/ea4357.c b/hw/bsp/ea4357/ea4357.c index c276f10d..e8252f21 100644 --- a/hw/bsp/ea4357/ea4357.c +++ b/hw/bsp/ea4357/ea4357.c @@ -230,6 +230,31 @@ void board_init(void) // TODO Remove R170, R171, solder a pair of 15K to USB1 D+/D- to test with USB1 Host } +//--------------------------------------------------------------------+ +// USB Interrupt Handler +//--------------------------------------------------------------------+ +void USB0_IRQHandler(void) +{ + #if TUSB_OPT_HOST_ENABLED + tuh_isr(0); + #endif + + #if TUSB_OPT_DEVICE_ENABLED + tud_isr(0); + #endif +} + +void USB1_IRQHandler(void) +{ + #if TUSB_OPT_HOST_ENABLED + tuh_isr(1); + #endif + + #if TUSB_OPT_DEVICE_ENABLED + tud_isr(1); + #endif +} + //--------------------------------------------------------------------+ // Board porting API //--------------------------------------------------------------------+ diff --git a/hw/bsp/mcb1800/board.mk b/hw/bsp/mcb1800/board.mk index 2a040130..953f5943 100644 --- a/hw/bsp/mcb1800/board.mk +++ b/hw/bsp/mcb1800/board.mk @@ -16,9 +16,6 @@ MCU_DIR = hw/mcu/nxp/lpcopen/lpc18xx/lpc_chip_18xx # All source paths should be relative to the top level. LD_FILE = hw/bsp/mcb1800/lpc1857.ld -# TODO remove later -SRC_C += src/portable/$(VENDOR)/$(CHIP_FAMILY)/hal_$(CHIP_FAMILY).c - SRC_C += \ $(MCU_DIR)/../gcc/cr_startup_lpc18xx.c \ $(MCU_DIR)/src/chip_18xx_43xx.c \ diff --git a/hw/bsp/mcb1800/mcb1800.c b/hw/bsp/mcb1800/mcb1800.c index deb17f11..4e75c10d 100644 --- a/hw/bsp/mcb1800/mcb1800.c +++ b/hw/bsp/mcb1800/mcb1800.c @@ -172,6 +172,31 @@ void board_init(void) #endif } +//--------------------------------------------------------------------+ +// USB Interrupt Handler +//--------------------------------------------------------------------+ +void USB0_IRQHandler(void) +{ + #if TUSB_OPT_HOST_ENABLED + tuh_isr(0); + #endif + + #if TUSB_OPT_DEVICE_ENABLED + tud_isr(0); + #endif +} + +void USB1_IRQHandler(void) +{ + #if TUSB_OPT_HOST_ENABLED + tuh_isr(1); + #endif + + #if TUSB_OPT_DEVICE_ENABLED + tud_isr(1); + #endif +} + //--------------------------------------------------------------------+ // Board porting API //--------------------------------------------------------------------+ diff --git a/hw/bsp/ngx4330/board.mk b/hw/bsp/ngx4330/board.mk index 4e6032fc..863a4966 100644 --- a/hw/bsp/ngx4330/board.mk +++ b/hw/bsp/ngx4330/board.mk @@ -16,9 +16,6 @@ MCU_DIR = hw/mcu/nxp/lpcopen/lpc43xx/lpc_chip_43xx # All source paths should be relative to the top level. LD_FILE = hw/bsp/$(BOARD)/ngx4330.ld -# TODO remove later -SRC_C += src/portable/$(VENDOR)/$(CHIP_FAMILY)/hal_$(CHIP_FAMILY).c - SRC_C += \ $(MCU_DIR)/../gcc/cr_startup_lpc43xx.c \ $(MCU_DIR)/src/chip_18xx_43xx.c \ diff --git a/hw/bsp/ngx4330/ngx4330.c b/hw/bsp/ngx4330/ngx4330.c index 66918002..e95f6b05 100644 --- a/hw/bsp/ngx4330/ngx4330.c +++ b/hw/bsp/ngx4330/ngx4330.c @@ -219,6 +219,31 @@ void board_init(void) #endif } +//--------------------------------------------------------------------+ +// USB Interrupt Handler +//--------------------------------------------------------------------+ +void USB0_IRQHandler(void) +{ + #if TUSB_OPT_HOST_ENABLED + tuh_isr(0); + #endif + + #if TUSB_OPT_DEVICE_ENABLED + tud_isr(0); + #endif +} + +void USB1_IRQHandler(void) +{ + #if TUSB_OPT_HOST_ENABLED + tuh_isr(1); + #endif + + #if TUSB_OPT_DEVICE_ENABLED + tud_isr(1); + #endif +} + //--------------------------------------------------------------------+ // Board porting API //--------------------------------------------------------------------+ diff --git a/src/device/usbd.h b/src/device/usbd.h index b3665d7f..9d39af13 100644 --- a/src/device/usbd.h +++ b/src/device/usbd.h @@ -47,6 +47,9 @@ bool tud_init (void); // Task function should be called in main/rtos loop void tud_task (void); +// Interrupt handler, name alias to DCD +#define tud_isr dcd_isr + // Check if device is connected and configured bool tud_mounted(void); diff --git a/src/host/usbh.h b/src/host/usbh.h index 311b2514..42a2bd09 100644 --- a/src/host/usbh.h +++ b/src/host/usbh.h @@ -68,6 +68,9 @@ typedef struct { //--------------------------------------------------------------------+ void tuh_task(void); +// Interrupt handler, name alias to HCD +#define tuh_isr hcd_isr + tusb_device_state_t tuh_device_get_state (uint8_t dev_addr); static inline bool tuh_device_is_configured(uint8_t dev_addr) { From f5d737aa7ec6abde5738d29510c8416d5e8b17e7 Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 21 Nov 2019 23:19:38 +0700 Subject: [PATCH 062/267] moving irq to bsp for lpc17/40 --- hw/bsp/ea4088qs/board.mk | 3 - hw/bsp/ea4088qs/ea4088qs.c | 15 ++++ hw/bsp/ea4357/ea4357.c | 8 +-- hw/bsp/lpcxpresso1769/board.mk | 3 - hw/bsp/lpcxpresso1769/lpcxpresso1769.c | 14 ++++ hw/bsp/mbed1768/board.mk | 9 ++- hw/bsp/mbed1768/mbed1768.c | 14 ++++ hw/bsp/mcb1800/mcb1800.c | 9 ++- hw/bsp/mimxrt1064_evk/mimxrt1064_evk.c | 25 +++++++ hw/bsp/ngx4330/ngx4330.c | 8 +-- src/device/dcd.h | 3 + .../{hal_lpc17_40.c => hcd_lpc17_40.c} | 21 +----- src/portable/nxp/lpc18_43/hal_lpc18_43.c | 70 ------------------- test/test/device/usbd/test_usbd.c | 2 +- 14 files changed, 91 insertions(+), 113 deletions(-) rename src/portable/nxp/lpc17_40/{hal_lpc17_40.c => hcd_lpc17_40.c} (82%) delete mode 100644 src/portable/nxp/lpc18_43/hal_lpc18_43.c diff --git a/hw/bsp/ea4088qs/board.mk b/hw/bsp/ea4088qs/board.mk index 7869ea8d..a88976d3 100644 --- a/hw/bsp/ea4088qs/board.mk +++ b/hw/bsp/ea4088qs/board.mk @@ -17,9 +17,6 @@ MCU_DIR = hw/mcu/nxp/lpcopen/lpc40xx/lpc_chip_40xx # All source paths should be relative to the top level. LD_FILE = hw/bsp/ea4088qs/lpc4088.ld -# TODO remove later -SRC_C += src/portable/$(VENDOR)/$(CHIP_FAMILY)/hal_$(CHIP_FAMILY).c - SRC_C += \ $(MCU_DIR)/../gcc/cr_startup_lpc40xx.c \ $(MCU_DIR)/src/chip_17xx_40xx.c \ diff --git a/hw/bsp/ea4088qs/ea4088qs.c b/hw/bsp/ea4088qs/ea4088qs.c index 8adb61fd..83b2d6b1 100644 --- a/hw/bsp/ea4088qs/ea4088qs.c +++ b/hw/bsp/ea4088qs/ea4088qs.c @@ -113,6 +113,21 @@ void board_init(void) LPC_USB->StCtrl = 0x3; } +//--------------------------------------------------------------------+ +// USB Interrupt Handler +//--------------------------------------------------------------------+ +void USB_IRQHandler(void) +{ + #if CFG_TUSB_RHPORT0_MODE & OPT_MODE_HOST + tuh_isr(0); + #endif + + #if CFG_TUSB_RHPORT0_MODE & OPT_MODE_DEVICE + tud_isr(0); + #endif +} + + //--------------------------------------------------------------------+ // Board porting API //--------------------------------------------------------------------+ diff --git a/hw/bsp/ea4357/ea4357.c b/hw/bsp/ea4357/ea4357.c index e8252f21..f21d3259 100644 --- a/hw/bsp/ea4357/ea4357.c +++ b/hw/bsp/ea4357/ea4357.c @@ -235,22 +235,22 @@ void board_init(void) //--------------------------------------------------------------------+ void USB0_IRQHandler(void) { - #if TUSB_OPT_HOST_ENABLED + #if CFG_TUSB_RHPORT0_MODE & OPT_MODE_HOST tuh_isr(0); #endif - #if TUSB_OPT_DEVICE_ENABLED + #if CFG_TUSB_RHPORT0_MODE & OPT_MODE_DEVICE tud_isr(0); #endif } void USB1_IRQHandler(void) { - #if TUSB_OPT_HOST_ENABLED + #if CFG_TUSB_RHPORT1_MODE & OPT_MODE_HOST tuh_isr(1); #endif - #if TUSB_OPT_DEVICE_ENABLED + #if CFG_TUSB_RHPORT1_MODE & OPT_MODE_DEVICE tud_isr(1); #endif } diff --git a/hw/bsp/lpcxpresso1769/board.mk b/hw/bsp/lpcxpresso1769/board.mk index 8d1f14c4..b87d6afc 100644 --- a/hw/bsp/lpcxpresso1769/board.mk +++ b/hw/bsp/lpcxpresso1769/board.mk @@ -17,9 +17,6 @@ MCU_DIR = hw/mcu/nxp/lpcopen/lpc175x_6x/lpc_chip_175x_6x # All source paths should be relative to the top level. LD_FILE = hw/bsp/lpcxpresso1769/lpc1769.ld -# TODO remove later -SRC_C += src/portable/$(VENDOR)/$(CHIP_FAMILY)/hal_$(CHIP_FAMILY).c - SRC_C += \ $(MCU_DIR)/../gcc/cr_startup_lpc175x_6x.c \ $(MCU_DIR)/src/chip_17xx_40xx.c \ diff --git a/hw/bsp/lpcxpresso1769/lpcxpresso1769.c b/hw/bsp/lpcxpresso1769/lpcxpresso1769.c index e2d5f6cf..76755e89 100644 --- a/hw/bsp/lpcxpresso1769/lpcxpresso1769.c +++ b/hw/bsp/lpcxpresso1769/lpcxpresso1769.c @@ -143,6 +143,20 @@ void board_init(void) #endif } +//--------------------------------------------------------------------+ +// USB Interrupt Handler +//--------------------------------------------------------------------+ +void USB_IRQHandler(void) +{ + #if CFG_TUSB_RHPORT0_MODE & OPT_MODE_HOST + tuh_isr(0); + #endif + + #if CFG_TUSB_RHPORT0_MODE & OPT_MODE_DEVICE + tud_isr(0); + #endif +} + //--------------------------------------------------------------------+ // Board porting API //--------------------------------------------------------------------+ diff --git a/hw/bsp/mbed1768/board.mk b/hw/bsp/mbed1768/board.mk index 03176b54..60428bcb 100644 --- a/hw/bsp/mbed1768/board.mk +++ b/hw/bsp/mbed1768/board.mk @@ -17,9 +17,6 @@ MCU_DIR = hw/mcu/nxp/lpcopen/lpc175x_6x/lpc_chip_175x_6x # All source paths should be relative to the top level. LD_FILE = hw/bsp/mbed1768/lpc1768.ld -# TODO remove later -SRC_C += src/portable/$(VENDOR)/$(CHIP_FAMILY)/hal_$(CHIP_FAMILY).c - SRC_C += \ $(MCU_DIR)/../gcc/cr_startup_lpc175x_6x.c \ $(MCU_DIR)/src/chip_17xx_40xx.c \ @@ -44,5 +41,7 @@ FREERTOS_PORT = ARM_CM3 JLINK_DEVICE = LPC1768 JLINK_IF = swd -# flash using jlink -flash: flash-jlink +# flash using pyocd +flash: $(BUILD)/$(BOARD)-firmware.hex + pyocd flash -t lpc1768 $< + diff --git a/hw/bsp/mbed1768/mbed1768.c b/hw/bsp/mbed1768/mbed1768.c index 9f1ed12e..66cf44a0 100644 --- a/hw/bsp/mbed1768/mbed1768.c +++ b/hw/bsp/mbed1768/mbed1768.c @@ -135,6 +135,20 @@ void board_init(void) #endif } +//--------------------------------------------------------------------+ +// USB Interrupt Handler +//--------------------------------------------------------------------+ +void USB_IRQHandler(void) +{ + #if CFG_TUSB_RHPORT0_MODE & OPT_MODE_HOST + tuh_isr(0); + #endif + + #if CFG_TUSB_RHPORT0_MODE & OPT_MODE_DEVICE + tud_isr(0); + #endif +} + //--------------------------------------------------------------------+ // Board porting API //--------------------------------------------------------------------+ diff --git a/hw/bsp/mcb1800/mcb1800.c b/hw/bsp/mcb1800/mcb1800.c index 4e75c10d..4fe87476 100644 --- a/hw/bsp/mcb1800/mcb1800.c +++ b/hw/bsp/mcb1800/mcb1800.c @@ -177,26 +177,25 @@ void board_init(void) //--------------------------------------------------------------------+ void USB0_IRQHandler(void) { - #if TUSB_OPT_HOST_ENABLED + #if CFG_TUSB_RHPORT0_MODE & OPT_MODE_HOST tuh_isr(0); #endif - #if TUSB_OPT_DEVICE_ENABLED + #if CFG_TUSB_RHPORT0_MODE & OPT_MODE_DEVICE tud_isr(0); #endif } void USB1_IRQHandler(void) { - #if TUSB_OPT_HOST_ENABLED + #if CFG_TUSB_RHPORT1_MODE & OPT_MODE_HOST tuh_isr(1); #endif - #if TUSB_OPT_DEVICE_ENABLED + #if CFG_TUSB_RHPORT1_MODE & OPT_MODE_DEVICE tud_isr(1); #endif } - //--------------------------------------------------------------------+ // Board porting API //--------------------------------------------------------------------+ diff --git a/hw/bsp/mimxrt1064_evk/mimxrt1064_evk.c b/hw/bsp/mimxrt1064_evk/mimxrt1064_evk.c index 62117e64..8793a759 100644 --- a/hw/bsp/mimxrt1064_evk/mimxrt1064_evk.c +++ b/hw/bsp/mimxrt1064_evk/mimxrt1064_evk.c @@ -118,6 +118,31 @@ void board_init(void) // CLOCK_EnableUsbhs1Clock(kCLOCK_Usb480M, 480000000U); } +//--------------------------------------------------------------------+ +// USB Interrupt Handler +//--------------------------------------------------------------------+ +void USB0_IRQHandler(void) +{ + #if CFG_TUSB_RHPORT0_MODE & OPT_MODE_HOST + tuh_isr(0); + #endif + + #if CFG_TUSB_RHPORT0_MODE & OPT_MODE_DEVICE + tud_isr(0); + #endif +} + +void USB1_IRQHandler(void) +{ + #if CFG_TUSB_RHPORT1_MODE & OPT_MODE_HOST + tuh_isr(1); + #endif + + #if CFG_TUSB_RHPORT1_MODE & OPT_MODE_DEVICE + tud_isr(1); + #endif +} + //--------------------------------------------------------------------+ // Board porting API //--------------------------------------------------------------------+ diff --git a/hw/bsp/ngx4330/ngx4330.c b/hw/bsp/ngx4330/ngx4330.c index e95f6b05..fd6f0119 100644 --- a/hw/bsp/ngx4330/ngx4330.c +++ b/hw/bsp/ngx4330/ngx4330.c @@ -224,22 +224,22 @@ void board_init(void) //--------------------------------------------------------------------+ void USB0_IRQHandler(void) { - #if TUSB_OPT_HOST_ENABLED + #if CFG_TUSB_RHPORT0_MODE & OPT_MODE_HOST tuh_isr(0); #endif - #if TUSB_OPT_DEVICE_ENABLED + #if CFG_TUSB_RHPORT0_MODE & OPT_MODE_DEVICE tud_isr(0); #endif } void USB1_IRQHandler(void) { - #if TUSB_OPT_HOST_ENABLED + #if CFG_TUSB_RHPORT1_MODE & OPT_MODE_HOST tuh_isr(1); #endif - #if TUSB_OPT_DEVICE_ENABLED + #if CFG_TUSB_RHPORT1_MODE & OPT_MODE_DEVICE tud_isr(1); #endif } diff --git a/src/device/dcd.h b/src/device/dcd.h index 6e43ab3e..dca289e7 100644 --- a/src/device/dcd.h +++ b/src/device/dcd.h @@ -88,6 +88,9 @@ typedef struct TU_ATTR_ALIGNED(4) // Initialize controller to device mode void dcd_init (uint8_t rhport); +// Interrupt Handler +void dcd_isr (uint8_t rhport); + // Enable device interrupt void dcd_int_enable (uint8_t rhport); diff --git a/src/portable/nxp/lpc17_40/hal_lpc17_40.c b/src/portable/nxp/lpc17_40/hcd_lpc17_40.c similarity index 82% rename from src/portable/nxp/lpc17_40/hal_lpc17_40.c rename to src/portable/nxp/lpc17_40/hcd_lpc17_40.c index bc2477a9..537b3dab 100644 --- a/src/portable/nxp/lpc17_40/hal_lpc17_40.c +++ b/src/portable/nxp/lpc17_40/hcd_lpc17_40.c @@ -1,7 +1,7 @@ /* * The MIT License (MIT) * - * Copyright (c) 2019 Ha Thach (tinyusb.org) + * Copyright (c) 2019, Ha Thach (tinyusb.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -24,27 +24,12 @@ * This file is part of the TinyUSB stack. */ -#include "common/tusb_common.h" +#include "tusb_option.h" #if (CFG_TUSB_MCU == OPT_MCU_LPC175X_6X || CFG_TUSB_MCU == OPT_MCU_LPC40XX) #include "chip.h" -extern void hcd_isr(uint8_t hostid); -extern void dcd_isr(uint8_t rhport); - -void USB_IRQHandler(void) -{ - #if TUSB_OPT_HOST_ENABLED - hcd_isr(0); - #endif - - #if TUSB_OPT_DEVICE_ENABLED - dcd_isr(0); - #endif -} - -//FIXME move later void hcd_int_enable(uint8_t rhport) { (void) rhport; @@ -57,5 +42,5 @@ void hcd_int_disable(uint8_t rhport) NVIC_DisableIRQ(USB_IRQn); } - #endif + diff --git a/src/portable/nxp/lpc18_43/hal_lpc18_43.c b/src/portable/nxp/lpc18_43/hal_lpc18_43.c deleted file mode 100644 index 5710b9ff..00000000 --- a/src/portable/nxp/lpc18_43/hal_lpc18_43.c +++ /dev/null @@ -1,70 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2019 Ha Thach (tinyusb.org) - * - * 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. - * - * This file is part of the TinyUSB stack. - */ - -#include "tusb.h" - -#if (CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_RT10XX) - -#include "chip.h" - -extern void dcd_isr(uint8_t rhport); -extern void hcd_isr(uint8_t hostid); - -#if CFG_TUSB_RHPORT0_MODE -#if CFG_TUSB_MCU == OPT_MCU_RT10XX -void USB_OTG1_IRQHandler(void) -#else -void USB0_IRQHandler(void) -#endif -{ - #if TUSB_OPT_HOST_ENABLED - hcd_isr(0); - #endif - - #if TUSB_OPT_DEVICE_ENABLED - dcd_isr(0); - #endif -} -#endif - -#if CFG_TUSB_RHPORT1_MODE -#if CFG_TUSB_MCU == OPT_MCU_RT10XX -void USB_OTG2_IRQHandler(void) -#else -void USB1_IRQHandler(void) -#endif -{ - #if TUSB_OPT_HOST_ENABLED - hcd_isr(1); - #endif - - #if TUSB_OPT_DEVICE_ENABLED - dcd_isr(1); - #endif -} -#endif - -#endif diff --git a/test/test/device/usbd/test_usbd.c b/test/test/device/usbd/test_usbd.c index fcd739b4..c59d94c2 100644 --- a/test/test/device/usbd/test_usbd.c +++ b/test/test/device/usbd/test_usbd.c @@ -1,7 +1,7 @@ /* * The MIT License (MIT) * - * Copyright (c) 2019 hathach for Adafruit Industries + * Copyright (c) 2019, Ha Thach (tinyusb.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal From 03deeea4655dc3cb39011397254f8dc6b5c9383f Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 22 Nov 2019 00:32:49 +0700 Subject: [PATCH 063/267] fix segger host example --- .../ses/lpc175x_6x/lpc175x_6x.emProject | 54 +++++------ .../cdc_msc_hid/ses/lpc18xx/lpc18xx.emProject | 73 ++++++++------- .../cdc_msc_hid/ses/lpc40xx/lpc40xx.emProject | 53 ++++++----- .../cdc_msc_hid/ses/lpc43xx/lpc43xx.emProject | 89 +++++++++---------- src/host/ehci/ehci.c | 2 +- src/host/hcd.h | 1 + src/host/usbh.c | 2 +- 7 files changed, 136 insertions(+), 138 deletions(-) diff --git a/examples/host/cdc_msc_hid/ses/lpc175x_6x/lpc175x_6x.emProject b/examples/host/cdc_msc_hid/ses/lpc175x_6x/lpc175x_6x.emProject index ecd2dc71..ba5a9cea 100644 --- a/examples/host/cdc_msc_hid/ses/lpc175x_6x/lpc175x_6x.emProject +++ b/examples/host/cdc_msc_hid/ses/lpc175x_6x/lpc175x_6x.emProject @@ -29,7 +29,7 @@ linker_memory_map_file="LPC1769_MemoryMap.xml" linker_section_placement_file="flash_placement.xml" linker_section_placements_segments="FLASH RX 0x00000000 0x00080000;RAM RWX 0x10000000 0x00008000" - macros="DeviceFamily=LPC1700;DeviceSubFamily=LPC176x;Target=LPC1769;Placement=Flash;rootDir=../../../../..;lpcDir=../../../../../hw/mcu/nxp/lpc_chip_175x_6x" + macros="DeviceFamily=LPC1700;DeviceSubFamily=LPC176x;Target=LPC1769;Placement=Flash;rootDir=../../../../..;lpcDir=../../../../../hw/mcu/nxp/lpcopen/lpc175x_6x/lpc_chip_175x_6x" project_directory="" project_type="Executable" target_reset_script="Reset();" @@ -46,40 +46,40 @@ - - + + - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + - - - - - - - + + + + + + + diff --git a/examples/host/cdc_msc_hid/ses/lpc18xx/lpc18xx.emProject b/examples/host/cdc_msc_hid/ses/lpc18xx/lpc18xx.emProject index 8e9123dc..2dd7de55 100644 --- a/examples/host/cdc_msc_hid/ses/lpc18xx/lpc18xx.emProject +++ b/examples/host/cdc_msc_hid/ses/lpc18xx/lpc18xx.emProject @@ -24,7 +24,7 @@ gcc_entry_point="Reset_Handler" linker_memory_map_file="$(ProjectDir)/LPC1857_MemoryMap.xml" linker_section_placement_file="$(ProjectDir)/flash_placement.xml" - macros="DeviceFamily=LPC1800;DeviceSubFamily=LPC185x;Target=LPC1857;Placement=Flash;rootDir=../../../../..;lpcDir=../../../../../hw/mcu/nxp/lpc_chip_18xx" + macros="DeviceFamily=LPC1800;DeviceSubFamily=LPC185x;Target=LPC1857;Placement=Flash;rootDir=../../../../..;lpcDir=../../../../../hw/mcu/nxp/lpcopen/lpc18xx/lpc_chip_18xx" package_dependencies="LPC1800" project_directory="" project_type="Executable" @@ -51,52 +51,51 @@ - - + - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + - - + + - - - - - + + + + + diff --git a/examples/host/cdc_msc_hid/ses/lpc40xx/lpc40xx.emProject b/examples/host/cdc_msc_hid/ses/lpc40xx/lpc40xx.emProject index 63cf7484..bfb7922a 100644 --- a/examples/host/cdc_msc_hid/ses/lpc40xx/lpc40xx.emProject +++ b/examples/host/cdc_msc_hid/ses/lpc40xx/lpc40xx.emProject @@ -26,7 +26,7 @@ gcc_entry_point="Reset_Handler" linker_memory_map_file="$(ProjectDir)/LPC4088FBD208_MemoryMap.xml" linker_section_placement_file="$(ProjectDir)/flash_placement.xml" - macros="DeviceFamily=LPC4000;DeviceSubFamily=LPC408x;Target=LPC4088FBD208;Placement=Flash;rootDir=../../../../..;lpcDir=../../../../../hw/mcu/nxp/lpc_chip_40xx" + macros="DeviceFamily=LPC4000;DeviceSubFamily=LPC408x;Target=LPC4088FBD208;Placement=Flash;rootDir=../../../../..;lpcDir=../../../../../hw/mcu/nxp/lpcopen/lpc40xx/lpc_chip_40xx" package_dependencies="LPC4000" project_directory="" project_type="Executable" @@ -53,40 +53,39 @@ - - + - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + - - - - - - - + + + + + + + diff --git a/examples/host/cdc_msc_hid/ses/lpc43xx/lpc43xx.emProject b/examples/host/cdc_msc_hid/ses/lpc43xx/lpc43xx.emProject index 425f42a5..3b93c623 100644 --- a/examples/host/cdc_msc_hid/ses/lpc43xx/lpc43xx.emProject +++ b/examples/host/cdc_msc_hid/ses/lpc43xx/lpc43xx.emProject @@ -29,7 +29,7 @@ linker_memory_map_file="LPC4357 Cortex-M4_MemoryMap.xml" linker_section_placement_file="flash_placement.xml" linker_section_placements_segments="FLASH RX 0x1a000000 0x00080000;RAM RWX 0x10000000 0x00008000" - macros="DeviceFamily=LPC4300;DeviceSubFamily=LPC435x;Target=LPC4357 Cortex-M4;Placement=Flash;rootDir=../../../../..;lpcDir=../../../../../hw/mcu/nxp/lpc_chip_43xx" + macros="DeviceFamily=LPC4300;DeviceSubFamily=LPC435x;Target=LPC4357 Cortex-M4;Placement=Flash;rootDir=../../../../..;lpcDir=../../../../../hw/mcu/nxp/lpcopen/lpc43xx/lpc_chip_43xx" project_directory="" project_type="Executable" target_reset_script="Reset();" @@ -46,8 +46,7 @@ - - + @@ -56,52 +55,52 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - + + - - - - - - - - + + + + + + + + diff --git a/src/host/ehci/ehci.c b/src/host/ehci/ehci.c index 04ee5c5c..18123a49 100644 --- a/src/host/ehci/ehci.c +++ b/src/host/ehci/ehci.c @@ -170,7 +170,7 @@ void hcd_device_close(uint8_t rhport, uint8_t dev_addr) list_remove_qhd_by_addr( (ehci_link_t*) qhd_async_head(rhport), dev_addr ); // Remove from all interval period list - for(uint8_t i = 0; i < TU_ARRAY_SZIE(ehci_data.period_head_arr); i++) + for(uint8_t i = 0; i < TU_ARRAY_SIZE(ehci_data.period_head_arr); i++) { list_remove_qhd_by_addr( (ehci_link_t*) &ehci_data.period_head_arr[i], dev_addr); } diff --git a/src/host/hcd.h b/src/host/hcd.h index 86e7d664..97dc3ebf 100644 --- a/src/host/hcd.h +++ b/src/host/hcd.h @@ -87,6 +87,7 @@ enum { // HCD API //--------------------------------------------------------------------+ bool hcd_init(void); +void hcd_isr(uint8_t hostid); void hcd_int_enable (uint8_t rhport); void hcd_int_disable(uint8_t rhport); diff --git a/src/host/usbh.c b/src/host/usbh.c index 42a99f3d..9e1861f8 100644 --- a/src/host/usbh.c +++ b/src/host/usbh.c @@ -95,7 +95,7 @@ static host_class_driver_t const usbh_class_drivers[] = #endif }; -enum { USBH_CLASS_DRIVER_COUNT = TU_ARRAY_SZIE(usbh_class_drivers) }; +enum { USBH_CLASS_DRIVER_COUNT = TU_ARRAY_SIZE(usbh_class_drivers) }; //--------------------------------------------------------------------+ // INTERNAL OBJECT & FUNCTION DECLARATION From 627d9a2b336e53d0dd2908a9c65e24f7097d67b9 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 22 Nov 2019 00:34:31 +0700 Subject: [PATCH 064/267] adding irq to rt1064evk --- hw/bsp/mimxrt1064_evk/mimxrt1064_evk.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/hw/bsp/mimxrt1064_evk/mimxrt1064_evk.c b/hw/bsp/mimxrt1064_evk/mimxrt1064_evk.c index 8793a759..a21dcdbf 100644 --- a/hw/bsp/mimxrt1064_evk/mimxrt1064_evk.c +++ b/hw/bsp/mimxrt1064_evk/mimxrt1064_evk.c @@ -121,7 +121,7 @@ void board_init(void) //--------------------------------------------------------------------+ // USB Interrupt Handler //--------------------------------------------------------------------+ -void USB0_IRQHandler(void) +void USB_OTG1_IRQHandler(void) { #if CFG_TUSB_RHPORT0_MODE & OPT_MODE_HOST tuh_isr(0); @@ -132,7 +132,7 @@ void USB0_IRQHandler(void) #endif } -void USB1_IRQHandler(void) +void USB_OTG2_IRQHandler(void) { #if CFG_TUSB_RHPORT1_MODE & OPT_MODE_HOST tuh_isr(1); From 1f52273d99a340128d535d8c3d146b8522cad0ec Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 22 Nov 2019 00:38:22 +0700 Subject: [PATCH 065/267] move dcd_lpc18_43.h into .c file --- src/portable/nxp/lpc18_43/dcd_lpc18_43.c | 98 ++++++++++++++- src/portable/nxp/lpc18_43/dcd_lpc18_43.h | 144 ----------------------- 2 files changed, 97 insertions(+), 145 deletions(-) delete mode 100644 src/portable/nxp/lpc18_43/dcd_lpc18_43.h diff --git a/src/portable/nxp/lpc18_43/dcd_lpc18_43.c b/src/portable/nxp/lpc18_43/dcd_lpc18_43.c index 30cab820..75f9c8d5 100644 --- a/src/portable/nxp/lpc18_43/dcd_lpc18_43.c +++ b/src/portable/nxp/lpc18_43/dcd_lpc18_43.c @@ -33,7 +33,6 @@ //--------------------------------------------------------------------+ #include "common/tusb_common.h" #include "device/dcd.h" -#include "dcd_lpc18_43.h" #if CFG_TUSB_MCU == OPT_MCU_RT10XX #include "fsl_device_registers.h" @@ -45,6 +44,103 @@ // MACRO CONSTANT TYPEDEF //--------------------------------------------------------------------+ +/*---------- ENDPTCTRL ----------*/ +enum { + ENDPTCTRL_MASK_STALL = TU_BIT(0), + ENDPTCTRL_MASK_TOGGLE_INHIBIT = TU_BIT(5), ///< used for test only + ENDPTCTRL_MASK_TOGGLE_RESET = TU_BIT(6), + ENDPTCTRL_MASK_ENABLE = TU_BIT(7) +}; + +/*---------- USBCMD ----------*/ +enum { + USBCMD_MASK_RUN_STOP = TU_BIT(0), + USBCMD_MASK_RESET = TU_BIT(1), + USBCMD_MASK_SETUP_TRIPWIRE = TU_BIT(13), + USBCMD_MASK_ADD_QTD_TRIPWIRE = TU_BIT(14) ///< This bit is used as a semaphore to ensure the to proper addition of a new dTD to an active (primed) endpoint’s linked list. This bit is set and cleared by software during the process of adding a new dTD +}; +// Interrupt Threshold bit 23:16 + +/*---------- USBSTS, USBINTR ----------*/ +enum { + INT_MASK_USB = TU_BIT(0), + INT_MASK_ERROR = TU_BIT(1), + INT_MASK_PORT_CHANGE = TU_BIT(2), + INT_MASK_RESET = TU_BIT(6), + INT_MASK_SOF = TU_BIT(7), + INT_MASK_SUSPEND = TU_BIT(8), + INT_MASK_NAK = TU_BIT(16) +}; + +//------------- PORTSC -------------// +enum { + PORTSC_CURRENT_CONNECT_STATUS_MASK = TU_BIT(0), + PORTSC_FORCE_PORT_RESUME_MASK = TU_BIT(6), + PORTSC_SUSPEND_MASK = TU_BIT(7) +}; + +typedef struct +{ + // Word 0: Next QTD Pointer + uint32_t next; ///< Next link pointer This field contains the physical memory address of the next dTD to be processed + + // Word 1: qTQ Token + uint32_t : 3 ; + volatile uint32_t xact_err : 1 ; + uint32_t : 1 ; + volatile uint32_t buffer_err : 1 ; + volatile uint32_t halted : 1 ; + volatile uint32_t active : 1 ; + uint32_t : 2 ; + uint32_t iso_mult_override : 2 ; ///< This field can be used for transmit ISOs to override the MULT field in the dQH. This field must be zero for all packet types that are not transmit-ISO. + uint32_t : 3 ; + uint32_t int_on_complete : 1 ; + volatile uint32_t total_bytes : 15 ; + uint32_t : 0 ; + + // Word 2-6: Buffer Page Pointer List, Each element in the list is a 4K page aligned, physical memory address. The lower 12 bits in each pointer are reserved (except for the first one) as each memory pointer must reference the start of a 4K page + uint32_t buffer[5]; ///< buffer1 has frame_n for TODO Isochronous + + //------------- DCD Area -------------// + uint16_t expected_bytes; + uint8_t reserved[2]; +} dcd_qtd_t; + +TU_VERIFY_STATIC( sizeof(dcd_qtd_t) == 32, "size is not correct"); + +typedef struct +{ + // Word 0: Capabilities and Characteristics + uint32_t : 15 ; ///< Number of packets executed per transaction descriptor 00 - Execute N transactions as demonstrated by the USB variable length protocol where N is computed using Max_packet_length and the Total_bytes field in the dTD. 01 - Execute one transaction 10 - Execute two transactions 11 - Execute three transactions Remark: Non-isochronous endpoints must set MULT = 00. Remark: Isochronous endpoints must set MULT = 01, 10, or 11 as needed. + uint32_t int_on_setup : 1 ; ///< Interrupt on setup This bit is used on control type endpoints to indicate if USBINT is set in response to a setup being received. + uint32_t max_package_size : 11 ; ///< This directly corresponds to the maximum packet size of the associated endpoint (wMaxPacketSize) + uint32_t : 2 ; + uint32_t zero_length_termination : 1 ; ///< This bit is used for non-isochronous endpoints to indicate when a zero-length packet is received to terminate transfers in case the total transfer length is “multiple”. 0 - Enable zero-length packet to terminate transfers equal to a multiple of Max_packet_length (default). 1 - Disable zero-length packet on transfers that are equal in length to a multiple Max_packet_length. + uint32_t iso_mult : 2 ; ///< + uint32_t : 0 ; + + // Word 1: Current qTD Pointer + volatile uint32_t qtd_addr; + + // Word 2-9: Transfer Overlay + volatile dcd_qtd_t qtd_overlay; + + // Word 10-11: Setup request (control OUT only) + volatile tusb_control_request_t setup_request; + + //--------------------------------------------------------------------+ + /// Due to the fact QHD is 64 bytes aligned but occupies only 48 bytes + /// thus there are 16 bytes padding free that we can make use of. + //--------------------------------------------------------------------+ + uint8_t reserved[16]; +} dcd_qhd_t; + +TU_VERIFY_STATIC( sizeof(dcd_qhd_t) == 64, "size is not correct"); + +//--------------------------------------------------------------------+ +// Variables +//--------------------------------------------------------------------+ + #define QHD_MAX 12 #define QTD_NEXT_INVALID 0x01 diff --git a/src/portable/nxp/lpc18_43/dcd_lpc18_43.h b/src/portable/nxp/lpc18_43/dcd_lpc18_43.h deleted file mode 100644 index 00f4854b..00000000 --- a/src/portable/nxp/lpc18_43/dcd_lpc18_43.h +++ /dev/null @@ -1,144 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2019 Ha Thach (tinyusb.org) - * - * 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. - * - * This file is part of the TinyUSB stack. - */ - -/** \ingroup group_dcd - * \defgroup group_dcd_lpc143xx LPC43xx - * @{ */ - -#ifndef _TUSB_DCD_LPC43XX_H_ -#define _TUSB_DCD_LPC43XX_H_ - -#include "common/tusb_common.h" - -#ifdef __cplusplus - extern "C" { -#endif - -//--------------------------------------------------------------------+ -// MACRO CONSTANT TYPEDEF -//--------------------------------------------------------------------+ - -/*---------- ENDPTCTRL ----------*/ -enum { - ENDPTCTRL_MASK_STALL = TU_BIT(0), - ENDPTCTRL_MASK_TOGGLE_INHIBIT = TU_BIT(5), ///< used for test only - ENDPTCTRL_MASK_TOGGLE_RESET = TU_BIT(6), - ENDPTCTRL_MASK_ENABLE = TU_BIT(7) -}; - -/*---------- USBCMD ----------*/ -enum { - USBCMD_MASK_RUN_STOP = TU_BIT(0), - USBCMD_MASK_RESET = TU_BIT(1), - USBCMD_MASK_SETUP_TRIPWIRE = TU_BIT(13), - USBCMD_MASK_ADD_QTD_TRIPWIRE = TU_BIT(14) ///< This bit is used as a semaphore to ensure the to proper addition of a new dTD to an active (primed) endpoint’s linked list. This bit is set and cleared by software during the process of adding a new dTD -}; -// Interrupt Threshold bit 23:16 - -/*---------- USBSTS, USBINTR ----------*/ -enum { - INT_MASK_USB = TU_BIT(0), - INT_MASK_ERROR = TU_BIT(1), - INT_MASK_PORT_CHANGE = TU_BIT(2), - INT_MASK_RESET = TU_BIT(6), - INT_MASK_SOF = TU_BIT(7), - INT_MASK_SUSPEND = TU_BIT(8), - INT_MASK_NAK = TU_BIT(16) -}; - -//------------- PORTSC -------------// -enum { - PORTSC_CURRENT_CONNECT_STATUS_MASK = TU_BIT(0), - PORTSC_FORCE_PORT_RESUME_MASK = TU_BIT(6), - PORTSC_SUSPEND_MASK = TU_BIT(7) -}; - -typedef struct -{ - // Word 0: Next QTD Pointer - uint32_t next; ///< Next link pointer This field contains the physical memory address of the next dTD to be processed - - // Word 1: qTQ Token - uint32_t : 3 ; - volatile uint32_t xact_err : 1 ; - uint32_t : 1 ; - volatile uint32_t buffer_err : 1 ; - volatile uint32_t halted : 1 ; - volatile uint32_t active : 1 ; - uint32_t : 2 ; - uint32_t iso_mult_override : 2 ; ///< This field can be used for transmit ISOs to override the MULT field in the dQH. This field must be zero for all packet types that are not transmit-ISO. - uint32_t : 3 ; - uint32_t int_on_complete : 1 ; - volatile uint32_t total_bytes : 15 ; - uint32_t : 0 ; - - // Word 2-6: Buffer Page Pointer List, Each element in the list is a 4K page aligned, physical memory address. The lower 12 bits in each pointer are reserved (except for the first one) as each memory pointer must reference the start of a 4K page - uint32_t buffer[5]; ///< buffer1 has frame_n for TODO Isochronous - - //------------- DCD Area -------------// - uint16_t expected_bytes; - uint8_t reserved[2]; -} dcd_qtd_t; - -TU_VERIFY_STATIC( sizeof(dcd_qtd_t) == 32, "size is not correct"); - -typedef struct -{ - // Word 0: Capabilities and Characteristics - uint32_t : 15 ; ///< Number of packets executed per transaction descriptor 00 - Execute N transactions as demonstrated by the USB variable length protocol where N is computed using Max_packet_length and the Total_bytes field in the dTD. 01 - Execute one transaction 10 - Execute two transactions 11 - Execute three transactions Remark: Non-isochronous endpoints must set MULT = 00. Remark: Isochronous endpoints must set MULT = 01, 10, or 11 as needed. - uint32_t int_on_setup : 1 ; ///< Interrupt on setup This bit is used on control type endpoints to indicate if USBINT is set in response to a setup being received. - uint32_t max_package_size : 11 ; ///< This directly corresponds to the maximum packet size of the associated endpoint (wMaxPacketSize) - uint32_t : 2 ; - uint32_t zero_length_termination : 1 ; ///< This bit is used for non-isochronous endpoints to indicate when a zero-length packet is received to terminate transfers in case the total transfer length is “multiple”. 0 - Enable zero-length packet to terminate transfers equal to a multiple of Max_packet_length (default). 1 - Disable zero-length packet on transfers that are equal in length to a multiple Max_packet_length. - uint32_t iso_mult : 2 ; ///< - uint32_t : 0 ; - - // Word 1: Current qTD Pointer - volatile uint32_t qtd_addr; - - // Word 2-9: Transfer Overlay - volatile dcd_qtd_t qtd_overlay; - - // Word 10-11: Setup request (control OUT only) - volatile tusb_control_request_t setup_request; - - //--------------------------------------------------------------------+ - /// Due to the fact QHD is 64 bytes aligned but occupies only 48 bytes - /// thus there are 16 bytes padding free that we can make use of. - //--------------------------------------------------------------------+ - uint8_t reserved[16]; -} dcd_qhd_t; - -TU_VERIFY_STATIC( sizeof(dcd_qhd_t) == 64, "size is not correct"); - - -#ifdef __cplusplus - } -#endif - -#endif /* _TUSB_DCD_LPC43XX_H_ */ - -/** @} */ From 623b16af2eb9ead9d4267464eb8f178a037ad5fc Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 22 Nov 2019 00:58:18 +0700 Subject: [PATCH 066/267] clean up dcd lpc18_43 drop supporting both device mode on both ports. --- src/portable/nxp/lpc18_43/dcd_lpc18_43.c | 56 +++++++----------------- 1 file changed, 16 insertions(+), 40 deletions(-) diff --git a/src/portable/nxp/lpc18_43/dcd_lpc18_43.c b/src/portable/nxp/lpc18_43/dcd_lpc18_43.c index 75f9c8d5..7613f671 100644 --- a/src/portable/nxp/lpc18_43/dcd_lpc18_43.c +++ b/src/portable/nxp/lpc18_43/dcd_lpc18_43.c @@ -26,7 +26,9 @@ #include "tusb_option.h" -#if TUSB_OPT_DEVICE_ENABLED && (CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_RT10XX) +#if TUSB_OPT_DEVICE_ENABLED && (CFG_TUSB_MCU == OPT_MCU_LPC18XX || \ + CFG_TUSB_MCU == OPT_MCU_LPC43XX || \ + CFG_TUSB_MCU == OPT_MCU_RT10XX) //--------------------------------------------------------------------+ // INCLUDE @@ -150,31 +152,9 @@ typedef struct { dcd_qtd_t qtd[QHD_MAX] TU_ATTR_ALIGNED(32); }dcd_data_t; -#if (CFG_TUSB_RHPORT0_MODE & OPT_MODE_DEVICE) -CFG_TUSB_MEM_SECTION TU_ATTR_ALIGNED(2048) static dcd_data_t dcd_data0; -#endif - -#if (CFG_TUSB_RHPORT1_MODE & OPT_MODE_DEVICE) -CFG_TUSB_MEM_SECTION TU_ATTR_ALIGNED(2048) static dcd_data_t dcd_data1; -#endif - +static dcd_data_t _dcd_data CFG_TUSB_MEM_SECTION TU_ATTR_ALIGNED(2048); static LPC_USBHS_T * const LPC_USB[2] = { LPC_USB0, LPC_USB1 }; -static dcd_data_t* const dcd_data_ptr[2] = -{ -#if (CFG_TUSB_RHPORT0_MODE & OPT_MODE_DEVICE) - &dcd_data0, -#else - NULL, -#endif - -#if (CFG_TUSB_RHPORT1_MODE & OPT_MODE_DEVICE) - &dcd_data1 -#else - NULL -#endif -}; - //--------------------------------------------------------------------+ // CONTROLLER API //--------------------------------------------------------------------+ @@ -210,25 +190,23 @@ static void bus_reset(uint8_t rhport) // read reset bit in portsc //------------- Queue Head & Queue TD -------------// - dcd_data_t* p_dcd = dcd_data_ptr[rhport]; - tu_memclr(p_dcd, sizeof(dcd_data_t)); + tu_memclr(&_dcd_data, sizeof(dcd_data_t)); //------------- Set up Control Endpoints (0 OUT, 1 IN) -------------// - p_dcd->qhd[0].zero_length_termination = p_dcd->qhd[1].zero_length_termination = 1; - p_dcd->qhd[0].max_package_size = p_dcd->qhd[1].max_package_size = CFG_TUD_ENDPOINT0_SIZE; - p_dcd->qhd[0].qtd_overlay.next = p_dcd->qhd[1].qtd_overlay.next = QTD_NEXT_INVALID; + _dcd_data.qhd[0].zero_length_termination = _dcd_data.qhd[1].zero_length_termination = 1; + _dcd_data.qhd[0].max_package_size = _dcd_data.qhd[1].max_package_size = CFG_TUD_ENDPOINT0_SIZE; + _dcd_data.qhd[0].qtd_overlay.next = _dcd_data.qhd[1].qtd_overlay.next = QTD_NEXT_INVALID; - p_dcd->qhd[0].int_on_setup = 1; // OUT only + _dcd_data.qhd[0].int_on_setup = 1; // OUT only } void dcd_init(uint8_t rhport) { LPC_USBHS_T* const lpc_usb = LPC_USB[rhport]; - dcd_data_t* p_dcd = dcd_data_ptr[rhport]; - tu_memclr(p_dcd, sizeof(dcd_data_t)); + tu_memclr(&_dcd_data, sizeof(dcd_data_t)); - lpc_usb->ENDPOINTLISTADDR = (uint32_t) p_dcd->qhd; // Endpoint List Address has to be 2K alignment + lpc_usb->ENDPOINTLISTADDR = (uint32_t) _dcd_data.qhd; // Endpoint List Address has to be 2K alignment lpc_usb->USBSTS_D = lpc_usb->USBSTS_D; lpc_usb->USBINTR_D = INT_MASK_USB | INT_MASK_ERROR | INT_MASK_PORT_CHANGE | INT_MASK_RESET | INT_MASK_SUSPEND | INT_MASK_SOF; @@ -327,7 +305,7 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc) TU_ASSERT( epnum <= (rhport ? 3 : 5) ); //------------- Prepare Queue Head -------------// - dcd_qhd_t * p_qhd = &dcd_data_ptr[rhport]->qhd[ep_idx]; + dcd_qhd_t * p_qhd = &_dcd_data.qhd[ep_idx]; tu_memclr(p_qhd, sizeof(dcd_qhd_t)); p_qhd->zero_length_termination = 1; @@ -353,8 +331,8 @@ bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t t while(LPC_USB[rhport]->ENDPTSETUPSTAT & TU_BIT(0)) {} } - dcd_qhd_t * p_qhd = &dcd_data_ptr[rhport]->qhd[ep_idx]; - dcd_qtd_t * p_qtd = &dcd_data_ptr[rhport]->qtd[ep_idx]; + dcd_qhd_t * p_qhd = &_dcd_data.qhd[ep_idx]; + dcd_qtd_t * p_qtd = &_dcd_data.qtd[ep_idx]; //------------- Prepare qtd -------------// qtd_init(p_qtd, buffer, total_bytes); @@ -414,15 +392,13 @@ void dcd_isr(uint8_t rhport) uint32_t const edpt_complete = lpc_usb->ENDPTCOMPLETE; lpc_usb->ENDPTCOMPLETE = edpt_complete; // acknowledge - dcd_data_t* const p_dcd = dcd_data_ptr[rhport]; - if (lpc_usb->ENDPTSETUPSTAT) { //------------- Set up Received -------------// // 23.10.10.2 Operational model for setup transfers lpc_usb->ENDPTSETUPSTAT = lpc_usb->ENDPTSETUPSTAT;// acknowledge - dcd_event_setup_received(rhport, (uint8_t*) &p_dcd->qhd[0].setup_request, true); + dcd_event_setup_received(rhport, (uint8_t*) &_dcd_data.qhd[0].setup_request, true); } if ( edpt_complete ) @@ -432,7 +408,7 @@ void dcd_isr(uint8_t rhport) if ( tu_bit_test(edpt_complete, ep_idx2bit(ep_idx)) ) { // 23.10.12.3 Failed QTD also get ENDPTCOMPLETE set - dcd_qtd_t * p_qtd = &dcd_data_ptr[rhport]->qtd[ep_idx]; + dcd_qtd_t * p_qtd = &_dcd_data.qtd[ep_idx]; uint8_t result = p_qtd->halted ? XFER_RESULT_STALLED : ( p_qtd->xact_err ||p_qtd->buffer_err ) ? XFER_RESULT_FAILED : XFER_RESULT_SUCCESS; From 8aacd1eacdc706e2fc54fa069b9ccf966aee6713 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 22 Nov 2019 12:11:13 +0700 Subject: [PATCH 067/267] refactor dcd_lpc18_43, making it capatible with rt10xx --- src/portable/nxp/lpc18_43/dcd_lpc18_43.c | 94 ++++++++++++++++++------ 1 file changed, 72 insertions(+), 22 deletions(-) diff --git a/src/portable/nxp/lpc18_43/dcd_lpc18_43.c b/src/portable/nxp/lpc18_43/dcd_lpc18_43.c index 7613f671..75dd7b85 100644 --- a/src/portable/nxp/lpc18_43/dcd_lpc18_43.c +++ b/src/portable/nxp/lpc18_43/dcd_lpc18_43.c @@ -40,12 +40,61 @@ #include "fsl_device_registers.h" #else #include "chip.h" + + // Register base to CAPLENGTH + #define DCD_REGS_BASE { (dcd_registers_t*) (LPC_USB0_BASE + 0x100), (dcd_registers_t*) (LPC_USB1_BASE + 0x100) } #endif //--------------------------------------------------------------------+ // MACRO CONSTANT TYPEDEF //--------------------------------------------------------------------+ +// Device Register starting with CAPLENGTH offset +typedef struct +{ + //------------- Capability Registers-------------// + __I uint8_t CAPLENGTH; ///< Capability Registers Length + __I uint8_t TU_RESERVED[1]; + __I uint16_t HCIVERSION; ///< Host Controller Interface Version + + __I uint32_t HCSPARAMS; ///< Host Controller Structural Parameters + __I uint32_t HCCPARAMS; ///< Host Controller Capability Parameters + __I uint32_t TU_RESERVED[5]; + + __I uint16_t DCIVERSION; ///< Device Controller Interface Version + __I uint8_t TU_RESERVED[2]; + + __I uint32_t DCCPARAMS; ///< Device Controller Capability Parameters + __I uint32_t TU_RESERVED[6]; + + //------------- Operational Registers -------------// + __IO uint32_t USBCMD; ///< USB Command Register + __IO uint32_t USBSTS; ///< USB Status Register + __IO uint32_t USBINTR; ///< Interrupt Enable Register + __IO uint32_t FRINDEX; ///< USB Frame Index + __I uint32_t TU_RESERVED; + __IO uint32_t DEVICEADDR; ///< Device Address + __IO uint32_t ENDPTLISTADDR; ///< Endpoint List Address + __I uint32_t TU_RESERVED; + __IO uint32_t BURSTSIZE; ///< Programmable Burst Size + __IO uint32_t TXFILLTUNING; ///< TX FIFO Fill Tuning + uint32_t TU_RESERVED[4]; + __IO uint32_t ENDPTNAK; ///< Endpoint NAK + __IO uint32_t ENDPTNAKEN; ///< Endpoint NAK Enable + __I uint32_t TU_RESERVED; + __IO uint32_t PORTSC1; ///< Port Status & Control + __I uint32_t TU_RESERVED[7]; + __IO uint32_t OTGSC; ///< On-The-Go Status & control + __IO uint32_t USBMODE; ///< USB Device Mode + __IO uint32_t ENDPTSETUPSTAT; ///< Endpoint Setup Status + __IO uint32_t ENDPTPRIME; ///< Endpoint Prime + __IO uint32_t ENDPTFLUSH; ///< Endpoint Flush + __I uint32_t ENDPTSTAT; ///< Endpoint Status + __IO uint32_t ENDPTCOMPLETE; ///< Endpoint Complete + __IO uint32_t ENDPTCTRL[8]; ///< Endpoint Control 0 - 7 +} dcd_registers_t; + + /*---------- ENDPTCTRL ----------*/ enum { ENDPTCTRL_MASK_STALL = TU_BIT(0), @@ -153,7 +202,8 @@ typedef struct { }dcd_data_t; static dcd_data_t _dcd_data CFG_TUSB_MEM_SECTION TU_ATTR_ALIGNED(2048); -static LPC_USBHS_T * const LPC_USB[2] = { LPC_USB0, LPC_USB1 }; +//static LPC_USBHS_T * const LPC_USB[2] = { LPC_USB0, LPC_USB1 }; +static dcd_registers_t* dcd_regs[] = DCD_REGS_BASE; //--------------------------------------------------------------------+ // CONTROLLER API @@ -162,7 +212,7 @@ static LPC_USBHS_T * const LPC_USB[2] = { LPC_USB0, LPC_USB1 }; /// follows LPC43xx User Manual 23.10.3 static void bus_reset(uint8_t rhport) { - LPC_USBHS_T* lpc_usb = LPC_USB[rhport]; + dcd_registers_t* lpc_usb = dcd_regs[rhport]; // The reset value for all endpoint types is the control endpoint. If one endpoint // direction is enabled and the paired endpoint of opposite direction is disabled, then the @@ -179,7 +229,7 @@ static void bus_reset(uint8_t rhport) //------------- Clear All Registers -------------// lpc_usb->ENDPTNAK = lpc_usb->ENDPTNAK; lpc_usb->ENDPTNAKEN = 0; - lpc_usb->USBSTS_D = lpc_usb->USBSTS_D; + lpc_usb->USBSTS = lpc_usb->USBSTS; lpc_usb->ENDPTSETUPSTAT = lpc_usb->ENDPTSETUPSTAT; lpc_usb->ENDPTCOMPLETE = lpc_usb->ENDPTCOMPLETE; @@ -202,16 +252,16 @@ static void bus_reset(uint8_t rhport) void dcd_init(uint8_t rhport) { - LPC_USBHS_T* const lpc_usb = LPC_USB[rhport]; + dcd_registers_t* const lpc_usb = dcd_regs[rhport]; tu_memclr(&_dcd_data, sizeof(dcd_data_t)); - lpc_usb->ENDPOINTLISTADDR = (uint32_t) _dcd_data.qhd; // Endpoint List Address has to be 2K alignment - lpc_usb->USBSTS_D = lpc_usb->USBSTS_D; - lpc_usb->USBINTR_D = INT_MASK_USB | INT_MASK_ERROR | INT_MASK_PORT_CHANGE | INT_MASK_RESET | INT_MASK_SUSPEND | INT_MASK_SOF; + lpc_usb->ENDPTLISTADDR = (uint32_t) _dcd_data.qhd; // Endpoint List Address has to be 2K alignment + lpc_usb->USBSTS = lpc_usb->USBSTS; + lpc_usb->USBINTR = INT_MASK_USB | INT_MASK_ERROR | INT_MASK_PORT_CHANGE | INT_MASK_RESET | INT_MASK_SUSPEND | INT_MASK_SOF; - lpc_usb->USBCMD_D &= ~0x00FF0000; // Interrupt Threshold Interval = 0 - lpc_usb->USBCMD_D |= TU_BIT(0); // connect + lpc_usb->USBCMD &= ~0x00FF0000; // Interrupt Threshold Interval = 0 + lpc_usb->USBCMD |= TU_BIT(0); // connect } void dcd_int_enable(uint8_t rhport) @@ -229,7 +279,7 @@ void dcd_set_address(uint8_t rhport, uint8_t dev_addr) // Response with status first before changing device address dcd_edpt_xfer(rhport, tu_edpt_addr(0, TUSB_DIR_IN), NULL, 0); - LPC_USB[rhport]->DEVICEADDR = (dev_addr << 25) | TU_BIT(24); + dcd_regs[rhport]->DEVICEADDR = (dev_addr << 25) | TU_BIT(24); } void dcd_set_config(uint8_t rhport, uint8_t config_num) @@ -279,7 +329,7 @@ void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr) uint8_t const epnum = tu_edpt_number(ep_addr); uint8_t const dir = tu_edpt_dir(ep_addr); - LPC_USB[rhport]->ENDPTCTRL[epnum] |= ENDPTCTRL_MASK_STALL << (dir ? 16 : 0); + dcd_regs[rhport]->ENDPTCTRL[epnum] |= ENDPTCTRL_MASK_STALL << (dir ? 16 : 0); } void dcd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr) @@ -288,8 +338,8 @@ void dcd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr) uint8_t const dir = tu_edpt_dir(ep_addr); // data toggle also need to be reset - LPC_USB[rhport]->ENDPTCTRL[epnum] |= ENDPTCTRL_MASK_TOGGLE_RESET << ( dir ? 16 : 0 ); - LPC_USB[rhport]->ENDPTCTRL[epnum] &= ~(ENDPTCTRL_MASK_STALL << ( dir ? 16 : 0)); + dcd_regs[rhport]->ENDPTCTRL[epnum] |= ENDPTCTRL_MASK_TOGGLE_RESET << ( dir ? 16 : 0 ); + dcd_regs[rhport]->ENDPTCTRL[epnum] &= ~(ENDPTCTRL_MASK_STALL << ( dir ? 16 : 0)); } bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc) @@ -313,7 +363,7 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc) p_qhd->qtd_overlay.next = QTD_NEXT_INVALID; // Enable EP Control - LPC_USB[rhport]->ENDPTCTRL[epnum] |= ((p_endpoint_desc->bmAttributes.xfer << 2) | ENDPTCTRL_MASK_ENABLE | ENDPTCTRL_MASK_TOGGLE_RESET) << (dir ? 16 : 0); + dcd_regs[rhport]->ENDPTCTRL[epnum] |= ((p_endpoint_desc->bmAttributes.xfer << 2) | ENDPTCTRL_MASK_ENABLE | ENDPTCTRL_MASK_TOGGLE_RESET) << (dir ? 16 : 0); return true; } @@ -328,7 +378,7 @@ bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t t { // follows UM 24.10.8.1.1 Setup packet handling using setup lockout mechanism // wait until ENDPTSETUPSTAT before priming data/status in response TODO add time out - while(LPC_USB[rhport]->ENDPTSETUPSTAT & TU_BIT(0)) {} + while(dcd_regs[rhport]->ENDPTSETUPSTAT & TU_BIT(0)) {} } dcd_qhd_t * p_qhd = &_dcd_data.qhd[ep_idx]; @@ -340,7 +390,7 @@ bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t t p_qhd->qtd_overlay.next = (uint32_t) p_qtd; // link qtd to qhd // start transfer - LPC_USB[rhport]->ENDPTPRIME = TU_BIT( ep_idx2bit(ep_idx) ) ; + dcd_regs[rhport]->ENDPTPRIME = TU_BIT( ep_idx2bit(ep_idx) ) ; return true; } @@ -350,11 +400,11 @@ bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t t //--------------------------------------------------------------------+ void dcd_isr(uint8_t rhport) { - LPC_USBHS_T* const lpc_usb = LPC_USB[rhport]; + dcd_registers_t* const lpc_usb = dcd_regs[rhport]; - uint32_t const int_enable = lpc_usb->USBINTR_D; - uint32_t const int_status = lpc_usb->USBSTS_D & int_enable; - lpc_usb->USBSTS_D = int_status; // Acknowledge handled interrupt + uint32_t const int_enable = lpc_usb->USBINTR; + uint32_t const int_status = lpc_usb->USBSTS & int_enable; + lpc_usb->USBSTS = int_status; // Acknowledge handled interrupt if (int_status == 0) return;// disabled interrupt sources @@ -367,7 +417,7 @@ void dcd_isr(uint8_t rhport) if (int_status & INT_MASK_SUSPEND) { - if (lpc_usb->PORTSC1_D & PORTSC_SUSPEND_MASK) + if (lpc_usb->PORTSC1 & PORTSC_SUSPEND_MASK) { // Note: Host may delay more than 3 ms before and/or after bus reset before doing enumeration. if ((lpc_usb->DEVICEADDR >> 25) & 0x0f) @@ -380,7 +430,7 @@ void dcd_isr(uint8_t rhport) // TODO disconnection does not generate interrupt !!!!!! // if (int_status & INT_MASK_PORT_CHANGE) // { -// if ( !(lpc_usb->PORTSC1_D & PORTSC_CURRENT_CONNECT_STATUS_MASK) ) +// if ( !(lpc_usb->PORTSC1 & PORTSC_CURRENT_CONNECT_STATUS_MASK) ) // { // dcd_event_t event = { .rhport = rhport, .event_id = DCD_EVENT_UNPLUGGED }; // dcd_event_handler(&event, true); From 7e16a9a1dbbb5ad87d351a7332adb361b1b6b2d3 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 22 Nov 2019 12:14:55 +0700 Subject: [PATCH 068/267] more constant rename clean up --- src/portable/nxp/lpc18_43/dcd_lpc18_43.c | 100 ++++++++++++----------- 1 file changed, 51 insertions(+), 49 deletions(-) diff --git a/src/portable/nxp/lpc18_43/dcd_lpc18_43.c b/src/portable/nxp/lpc18_43/dcd_lpc18_43.c index 75dd7b85..1e710c9c 100644 --- a/src/portable/nxp/lpc18_43/dcd_lpc18_43.c +++ b/src/portable/nxp/lpc18_43/dcd_lpc18_43.c @@ -49,6 +49,41 @@ // MACRO CONSTANT TYPEDEF //--------------------------------------------------------------------+ +// ENDPTCTRL +enum { + ENDPTCTRL_STALL = TU_BIT(0), + ENDPTCTRL_TOGGLE_INHIBIT = TU_BIT(5), ///< used for test only + ENDPTCTRL_TOGGLE_RESET = TU_BIT(6), + ENDPTCTRL_ENABLE = TU_BIT(7) +}; + +// USBCMD +enum { + USBCMD_RUN_STOP = TU_BIT(0), + USBCMD_RESET = TU_BIT(1), + USBCMD_SETUP_TRIPWIRE = TU_BIT(13), + USBCMD_ADD_QTD_TRIPWIRE = TU_BIT(14) ///< This bit is used as a semaphore to ensure the to proper addition of a new dTD to an active (primed) endpoint’s linked list. This bit is set and cleared by software during the process of adding a new dTD +}; +// Interrupt Threshold bit 23:16 + +// USBSTS, USBINTR +enum { + INTR_USB = TU_BIT(0), + INTR_ERROR = TU_BIT(1), + INTR_PORT_CHANGE = TU_BIT(2), + INTR_RESET = TU_BIT(6), + INTR_SOF = TU_BIT(7), + INTR_SUSPEND = TU_BIT(8), + INTR_NAK = TU_BIT(16) +}; + +// PORTSC +enum { + PORTSC_CURRENT_CONNECT_STATUS = TU_BIT(0), + PORTSC_FORCE_PORT_RESUME = TU_BIT(6), + PORTSC_SUSPEND = TU_BIT(7) +}; + // Device Register starting with CAPLENGTH offset typedef struct { @@ -95,41 +130,7 @@ typedef struct } dcd_registers_t; -/*---------- ENDPTCTRL ----------*/ -enum { - ENDPTCTRL_MASK_STALL = TU_BIT(0), - ENDPTCTRL_MASK_TOGGLE_INHIBIT = TU_BIT(5), ///< used for test only - ENDPTCTRL_MASK_TOGGLE_RESET = TU_BIT(6), - ENDPTCTRL_MASK_ENABLE = TU_BIT(7) -}; - -/*---------- USBCMD ----------*/ -enum { - USBCMD_MASK_RUN_STOP = TU_BIT(0), - USBCMD_MASK_RESET = TU_BIT(1), - USBCMD_MASK_SETUP_TRIPWIRE = TU_BIT(13), - USBCMD_MASK_ADD_QTD_TRIPWIRE = TU_BIT(14) ///< This bit is used as a semaphore to ensure the to proper addition of a new dTD to an active (primed) endpoint’s linked list. This bit is set and cleared by software during the process of adding a new dTD -}; -// Interrupt Threshold bit 23:16 - -/*---------- USBSTS, USBINTR ----------*/ -enum { - INT_MASK_USB = TU_BIT(0), - INT_MASK_ERROR = TU_BIT(1), - INT_MASK_PORT_CHANGE = TU_BIT(2), - INT_MASK_RESET = TU_BIT(6), - INT_MASK_SOF = TU_BIT(7), - INT_MASK_SUSPEND = TU_BIT(8), - INT_MASK_NAK = TU_BIT(16) -}; - -//------------- PORTSC -------------// -enum { - PORTSC_CURRENT_CONNECT_STATUS_MASK = TU_BIT(0), - PORTSC_FORCE_PORT_RESUME_MASK = TU_BIT(6), - PORTSC_SUSPEND_MASK = TU_BIT(7) -}; - +// Queue Transfer Descriptor typedef struct { // Word 0: Next QTD Pointer @@ -159,6 +160,7 @@ typedef struct TU_VERIFY_STATIC( sizeof(dcd_qtd_t) == 32, "size is not correct"); +// Queue Head typedef struct { // Word 0: Capabilities and Characteristics @@ -258,7 +260,7 @@ void dcd_init(uint8_t rhport) lpc_usb->ENDPTLISTADDR = (uint32_t) _dcd_data.qhd; // Endpoint List Address has to be 2K alignment lpc_usb->USBSTS = lpc_usb->USBSTS; - lpc_usb->USBINTR = INT_MASK_USB | INT_MASK_ERROR | INT_MASK_PORT_CHANGE | INT_MASK_RESET | INT_MASK_SUSPEND | INT_MASK_SOF; + lpc_usb->USBINTR = INTR_USB | INTR_ERROR | INTR_PORT_CHANGE | INTR_RESET | INTR_SUSPEND | INTR_SOF; lpc_usb->USBCMD &= ~0x00FF0000; // Interrupt Threshold Interval = 0 lpc_usb->USBCMD |= TU_BIT(0); // connect @@ -329,7 +331,7 @@ void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr) uint8_t const epnum = tu_edpt_number(ep_addr); uint8_t const dir = tu_edpt_dir(ep_addr); - dcd_regs[rhport]->ENDPTCTRL[epnum] |= ENDPTCTRL_MASK_STALL << (dir ? 16 : 0); + dcd_regs[rhport]->ENDPTCTRL[epnum] |= ENDPTCTRL_STALL << (dir ? 16 : 0); } void dcd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr) @@ -338,8 +340,8 @@ void dcd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr) uint8_t const dir = tu_edpt_dir(ep_addr); // data toggle also need to be reset - dcd_regs[rhport]->ENDPTCTRL[epnum] |= ENDPTCTRL_MASK_TOGGLE_RESET << ( dir ? 16 : 0 ); - dcd_regs[rhport]->ENDPTCTRL[epnum] &= ~(ENDPTCTRL_MASK_STALL << ( dir ? 16 : 0)); + dcd_regs[rhport]->ENDPTCTRL[epnum] |= ENDPTCTRL_TOGGLE_RESET << ( dir ? 16 : 0 ); + dcd_regs[rhport]->ENDPTCTRL[epnum] &= ~(ENDPTCTRL_STALL << ( dir ? 16 : 0)); } bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc) @@ -363,7 +365,7 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc) p_qhd->qtd_overlay.next = QTD_NEXT_INVALID; // Enable EP Control - dcd_regs[rhport]->ENDPTCTRL[epnum] |= ((p_endpoint_desc->bmAttributes.xfer << 2) | ENDPTCTRL_MASK_ENABLE | ENDPTCTRL_MASK_TOGGLE_RESET) << (dir ? 16 : 0); + dcd_regs[rhport]->ENDPTCTRL[epnum] |= ((p_endpoint_desc->bmAttributes.xfer << 2) | ENDPTCTRL_ENABLE | ENDPTCTRL_TOGGLE_RESET) << (dir ? 16 : 0); return true; } @@ -409,15 +411,15 @@ void dcd_isr(uint8_t rhport) if (int_status == 0) return;// disabled interrupt sources - if (int_status & INT_MASK_RESET) + if (int_status & INTR_RESET) { bus_reset(rhport); dcd_event_bus_signal(rhport, DCD_EVENT_BUS_RESET, true); } - if (int_status & INT_MASK_SUSPEND) + if (int_status & INTR_SUSPEND) { - if (lpc_usb->PORTSC1 & PORTSC_SUSPEND_MASK) + if (lpc_usb->PORTSC1 & PORTSC_SUSPEND) { // Note: Host may delay more than 3 ms before and/or after bus reset before doing enumeration. if ((lpc_usb->DEVICEADDR >> 25) & 0x0f) @@ -428,16 +430,16 @@ void dcd_isr(uint8_t rhport) } // TODO disconnection does not generate interrupt !!!!!! -// if (int_status & INT_MASK_PORT_CHANGE) +// if (int_status & INTR_PORT_CHANGE) // { -// if ( !(lpc_usb->PORTSC1 & PORTSC_CURRENT_CONNECT_STATUS_MASK) ) +// if ( !(lpc_usb->PORTSC1 & PORTSC_CURRENT_CONNECT_STATUS) ) // { // dcd_event_t event = { .rhport = rhport, .event_id = DCD_EVENT_UNPLUGGED }; // dcd_event_handler(&event, true); // } // } - if (int_status & INT_MASK_USB) + if (int_status & INTR_USB) { uint32_t const edpt_complete = lpc_usb->ENDPTCOMPLETE; lpc_usb->ENDPTCOMPLETE = edpt_complete; // acknowledge @@ -470,13 +472,13 @@ void dcd_isr(uint8_t rhport) } } - if (int_status & INT_MASK_SOF) + if (int_status & INTR_SOF) { dcd_event_bus_signal(rhport, DCD_EVENT_SOF, true); } - if (int_status & INT_MASK_NAK) {} - if (int_status & INT_MASK_ERROR) TU_ASSERT(false, ); + if (int_status & INTR_NAK) {} + if (int_status & INTR_ERROR) TU_ASSERT(false, ); } #endif From ccb09db3b782163e93f2208ff5612c789d465058 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 22 Nov 2019 12:16:47 +0700 Subject: [PATCH 069/267] more clean up --- src/portable/nxp/lpc18_43/dcd_lpc18_43.c | 74 ++++++++++++------------ 1 file changed, 37 insertions(+), 37 deletions(-) diff --git a/src/portable/nxp/lpc18_43/dcd_lpc18_43.c b/src/portable/nxp/lpc18_43/dcd_lpc18_43.c index 1e710c9c..2f3d8ab2 100644 --- a/src/portable/nxp/lpc18_43/dcd_lpc18_43.c +++ b/src/portable/nxp/lpc18_43/dcd_lpc18_43.c @@ -205,7 +205,7 @@ typedef struct { static dcd_data_t _dcd_data CFG_TUSB_MEM_SECTION TU_ATTR_ALIGNED(2048); //static LPC_USBHS_T * const LPC_USB[2] = { LPC_USB0, LPC_USB1 }; -static dcd_registers_t* dcd_regs[] = DCD_REGS_BASE; +static dcd_registers_t* DCD_REGS[] = DCD_REGS_BASE; //--------------------------------------------------------------------+ // CONTROLLER API @@ -214,7 +214,7 @@ static dcd_registers_t* dcd_regs[] = DCD_REGS_BASE; /// follows LPC43xx User Manual 23.10.3 static void bus_reset(uint8_t rhport) { - dcd_registers_t* lpc_usb = dcd_regs[rhport]; + dcd_registers_t* dcd_reg = DCD_REGS[rhport]; // The reset value for all endpoint types is the control endpoint. If one endpoint // direction is enabled and the paired endpoint of opposite direction is disabled, then the @@ -225,19 +225,19 @@ static void bus_reset(uint8_t rhport) // USB0 has 5 but USB1 only has 3 non-control endpoints for( int i=1; i < (rhport ? 6 : 4); i++) { - lpc_usb->ENDPTCTRL[i] = (TUSB_XFER_BULK << 2) | (TUSB_XFER_BULK << 18); + dcd_reg->ENDPTCTRL[i] = (TUSB_XFER_BULK << 2) | (TUSB_XFER_BULK << 18); } //------------- Clear All Registers -------------// - lpc_usb->ENDPTNAK = lpc_usb->ENDPTNAK; - lpc_usb->ENDPTNAKEN = 0; - lpc_usb->USBSTS = lpc_usb->USBSTS; - lpc_usb->ENDPTSETUPSTAT = lpc_usb->ENDPTSETUPSTAT; - lpc_usb->ENDPTCOMPLETE = lpc_usb->ENDPTCOMPLETE; + dcd_reg->ENDPTNAK = dcd_reg->ENDPTNAK; + dcd_reg->ENDPTNAKEN = 0; + dcd_reg->USBSTS = dcd_reg->USBSTS; + dcd_reg->ENDPTSETUPSTAT = dcd_reg->ENDPTSETUPSTAT; + dcd_reg->ENDPTCOMPLETE = dcd_reg->ENDPTCOMPLETE; - while (lpc_usb->ENDPTPRIME); - lpc_usb->ENDPTFLUSH = 0xFFFFFFFF; - while (lpc_usb->ENDPTFLUSH); + while (dcd_reg->ENDPTPRIME); + dcd_reg->ENDPTFLUSH = 0xFFFFFFFF; + while (dcd_reg->ENDPTFLUSH); // read reset bit in portsc @@ -254,16 +254,16 @@ static void bus_reset(uint8_t rhport) void dcd_init(uint8_t rhport) { - dcd_registers_t* const lpc_usb = dcd_regs[rhport]; + dcd_registers_t* const dcd_reg = DCD_REGS[rhport]; tu_memclr(&_dcd_data, sizeof(dcd_data_t)); - lpc_usb->ENDPTLISTADDR = (uint32_t) _dcd_data.qhd; // Endpoint List Address has to be 2K alignment - lpc_usb->USBSTS = lpc_usb->USBSTS; - lpc_usb->USBINTR = INTR_USB | INTR_ERROR | INTR_PORT_CHANGE | INTR_RESET | INTR_SUSPEND | INTR_SOF; + dcd_reg->ENDPTLISTADDR = (uint32_t) _dcd_data.qhd; // Endpoint List Address has to be 2K alignment + dcd_reg->USBSTS = dcd_reg->USBSTS; + dcd_reg->USBINTR = INTR_USB | INTR_ERROR | INTR_PORT_CHANGE | INTR_RESET | INTR_SUSPEND | INTR_SOF; - lpc_usb->USBCMD &= ~0x00FF0000; // Interrupt Threshold Interval = 0 - lpc_usb->USBCMD |= TU_BIT(0); // connect + dcd_reg->USBCMD &= ~0x00FF0000; // Interrupt Threshold Interval = 0 + dcd_reg->USBCMD |= TU_BIT(0); // connect } void dcd_int_enable(uint8_t rhport) @@ -281,7 +281,7 @@ void dcd_set_address(uint8_t rhport, uint8_t dev_addr) // Response with status first before changing device address dcd_edpt_xfer(rhport, tu_edpt_addr(0, TUSB_DIR_IN), NULL, 0); - dcd_regs[rhport]->DEVICEADDR = (dev_addr << 25) | TU_BIT(24); + DCD_REGS[rhport]->DEVICEADDR = (dev_addr << 25) | TU_BIT(24); } void dcd_set_config(uint8_t rhport, uint8_t config_num) @@ -331,7 +331,7 @@ void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr) uint8_t const epnum = tu_edpt_number(ep_addr); uint8_t const dir = tu_edpt_dir(ep_addr); - dcd_regs[rhport]->ENDPTCTRL[epnum] |= ENDPTCTRL_STALL << (dir ? 16 : 0); + DCD_REGS[rhport]->ENDPTCTRL[epnum] |= ENDPTCTRL_STALL << (dir ? 16 : 0); } void dcd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr) @@ -340,8 +340,8 @@ void dcd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr) uint8_t const dir = tu_edpt_dir(ep_addr); // data toggle also need to be reset - dcd_regs[rhport]->ENDPTCTRL[epnum] |= ENDPTCTRL_TOGGLE_RESET << ( dir ? 16 : 0 ); - dcd_regs[rhport]->ENDPTCTRL[epnum] &= ~(ENDPTCTRL_STALL << ( dir ? 16 : 0)); + DCD_REGS[rhport]->ENDPTCTRL[epnum] |= ENDPTCTRL_TOGGLE_RESET << ( dir ? 16 : 0 ); + DCD_REGS[rhport]->ENDPTCTRL[epnum] &= ~(ENDPTCTRL_STALL << ( dir ? 16 : 0)); } bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc) @@ -365,7 +365,7 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc) p_qhd->qtd_overlay.next = QTD_NEXT_INVALID; // Enable EP Control - dcd_regs[rhport]->ENDPTCTRL[epnum] |= ((p_endpoint_desc->bmAttributes.xfer << 2) | ENDPTCTRL_ENABLE | ENDPTCTRL_TOGGLE_RESET) << (dir ? 16 : 0); + DCD_REGS[rhport]->ENDPTCTRL[epnum] |= ((p_endpoint_desc->bmAttributes.xfer << 2) | ENDPTCTRL_ENABLE | ENDPTCTRL_TOGGLE_RESET) << (dir ? 16 : 0); return true; } @@ -380,7 +380,7 @@ bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t t { // follows UM 24.10.8.1.1 Setup packet handling using setup lockout mechanism // wait until ENDPTSETUPSTAT before priming data/status in response TODO add time out - while(dcd_regs[rhport]->ENDPTSETUPSTAT & TU_BIT(0)) {} + while(DCD_REGS[rhport]->ENDPTSETUPSTAT & TU_BIT(0)) {} } dcd_qhd_t * p_qhd = &_dcd_data.qhd[ep_idx]; @@ -392,7 +392,7 @@ bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t t p_qhd->qtd_overlay.next = (uint32_t) p_qtd; // link qtd to qhd // start transfer - dcd_regs[rhport]->ENDPTPRIME = TU_BIT( ep_idx2bit(ep_idx) ) ; + DCD_REGS[rhport]->ENDPTPRIME = TU_BIT( ep_idx2bit(ep_idx) ) ; return true; } @@ -402,14 +402,14 @@ bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t t //--------------------------------------------------------------------+ void dcd_isr(uint8_t rhport) { - dcd_registers_t* const lpc_usb = dcd_regs[rhport]; + dcd_registers_t* const dcd_reg = DCD_REGS[rhport]; - uint32_t const int_enable = lpc_usb->USBINTR; - uint32_t const int_status = lpc_usb->USBSTS & int_enable; - lpc_usb->USBSTS = int_status; // Acknowledge handled interrupt - - if (int_status == 0) return;// disabled interrupt sources + uint32_t const int_enable = dcd_reg->USBINTR; + uint32_t const int_status = dcd_reg->USBSTS & int_enable; + dcd_reg->USBSTS = int_status; // Acknowledge handled interrupt + // disabled interrupt sources + if (int_status == 0) return; if (int_status & INTR_RESET) { @@ -419,10 +419,10 @@ void dcd_isr(uint8_t rhport) if (int_status & INTR_SUSPEND) { - if (lpc_usb->PORTSC1 & PORTSC_SUSPEND) + if (dcd_reg->PORTSC1 & PORTSC_SUSPEND) { // Note: Host may delay more than 3 ms before and/or after bus reset before doing enumeration. - if ((lpc_usb->DEVICEADDR >> 25) & 0x0f) + if ((dcd_reg->DEVICEADDR >> 25) & 0x0f) { dcd_event_bus_signal(rhport, DCD_EVENT_SUSPEND, true); } @@ -432,7 +432,7 @@ void dcd_isr(uint8_t rhport) // TODO disconnection does not generate interrupt !!!!!! // if (int_status & INTR_PORT_CHANGE) // { -// if ( !(lpc_usb->PORTSC1 & PORTSC_CURRENT_CONNECT_STATUS) ) +// if ( !(dcd_reg->PORTSC1 & PORTSC_CURRENT_CONNECT_STATUS) ) // { // dcd_event_t event = { .rhport = rhport, .event_id = DCD_EVENT_UNPLUGGED }; // dcd_event_handler(&event, true); @@ -441,14 +441,14 @@ void dcd_isr(uint8_t rhport) if (int_status & INTR_USB) { - uint32_t const edpt_complete = lpc_usb->ENDPTCOMPLETE; - lpc_usb->ENDPTCOMPLETE = edpt_complete; // acknowledge + uint32_t const edpt_complete = dcd_reg->ENDPTCOMPLETE; + dcd_reg->ENDPTCOMPLETE = edpt_complete; // acknowledge - if (lpc_usb->ENDPTSETUPSTAT) + if (dcd_reg->ENDPTSETUPSTAT) { //------------- Set up Received -------------// // 23.10.10.2 Operational model for setup transfers - lpc_usb->ENDPTSETUPSTAT = lpc_usb->ENDPTSETUPSTAT;// acknowledge + dcd_reg->ENDPTSETUPSTAT = dcd_reg->ENDPTSETUPSTAT;// acknowledge dcd_event_setup_received(rhport, (uint8_t*) &_dcd_data.qhd[0].setup_request, true); } From 2ead26a12d8ec1a3c229d2afdb3f36fdde444162 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 22 Nov 2019 12:26:40 +0700 Subject: [PATCH 070/267] more clean up --- src/portable/nxp/lpc18_43/dcd_lpc18_43.c | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/portable/nxp/lpc18_43/dcd_lpc18_43.c b/src/portable/nxp/lpc18_43/dcd_lpc18_43.c index 2f3d8ab2..6e3e993d 100644 --- a/src/portable/nxp/lpc18_43/dcd_lpc18_43.c +++ b/src/portable/nxp/lpc18_43/dcd_lpc18_43.c @@ -38,11 +38,11 @@ #if CFG_TUSB_MCU == OPT_MCU_RT10XX #include "fsl_device_registers.h" + #define DCD_REGS_BASE { (dcd_registers_t*) USB1_BASE, (dcd_registers_t*) USB2_BASE } + #else #include "chip.h" - - // Register base to CAPLENGTH - #define DCD_REGS_BASE { (dcd_registers_t*) (LPC_USB0_BASE + 0x100), (dcd_registers_t*) (LPC_USB1_BASE + 0x100) } + #define DCD_REGS_BASE { (dcd_registers_t*) LPC_USB0_BASE, (dcd_registers_t*) LPC_USB1_BASE } #endif //--------------------------------------------------------------------+ @@ -84,9 +84,12 @@ enum { PORTSC_SUSPEND = TU_BIT(7) }; -// Device Register starting with CAPLENGTH offset +// Device Registers typedef struct { + //------------- ID + HW Parameter Registers-------------// + __I uint32_t TU_RESERVED[64]; ///< For iMX RT10xx, but not used by LPC18XX/LPC43XX + //------------- Capability Registers-------------// __I uint8_t CAPLENGTH; ///< Capability Registers Length __I uint8_t TU_RESERVED[1]; @@ -204,7 +207,6 @@ typedef struct { }dcd_data_t; static dcd_data_t _dcd_data CFG_TUSB_MEM_SECTION TU_ATTR_ALIGNED(2048); -//static LPC_USBHS_T * const LPC_USB[2] = { LPC_USB0, LPC_USB1 }; static dcd_registers_t* DCD_REGS[] = DCD_REGS_BASE; //--------------------------------------------------------------------+ From fca4653b95038d1ed1905d5a4731f758a1023eaa Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 22 Nov 2019 12:34:41 +0700 Subject: [PATCH 071/267] able to compile dcd 18/43 with rt1064 --- src/portable/nxp/lpc18_43/dcd_lpc18_43.c | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/portable/nxp/lpc18_43/dcd_lpc18_43.c b/src/portable/nxp/lpc18_43/dcd_lpc18_43.c index 6e3e993d..4972446b 100644 --- a/src/portable/nxp/lpc18_43/dcd_lpc18_43.c +++ b/src/portable/nxp/lpc18_43/dcd_lpc18_43.c @@ -38,11 +38,13 @@ #if CFG_TUSB_MCU == OPT_MCU_RT10XX #include "fsl_device_registers.h" - #define DCD_REGS_BASE { (dcd_registers_t*) USB1_BASE, (dcd_registers_t*) USB2_BASE } + #define DCD_REGS_BASE { (dcd_registers_t*) USB1_BASE, (dcd_registers_t*) USB2_BASE } + IRQn_Type DCD_IRQn[] = { USB_OTG1_IRQn, USB_OTG2_IRQn }; #else #include "chip.h" - #define DCD_REGS_BASE { (dcd_registers_t*) LPC_USB0_BASE, (dcd_registers_t*) LPC_USB1_BASE } + #define DCD_REGS_BASE { (dcd_registers_t*) LPC_USB0_BASE, (dcd_registers_t*) LPC_USB1_BASE } + IRQn_Type DCD_IRQn[] = { USB0_IRQn, USB1_IRQn }; #endif //--------------------------------------------------------------------+ @@ -270,12 +272,12 @@ void dcd_init(uint8_t rhport) void dcd_int_enable(uint8_t rhport) { - NVIC_EnableIRQ(rhport ? USB1_IRQn : USB0_IRQn); + NVIC_EnableIRQ(DCD_IRQn[rhport]); } void dcd_int_disable(uint8_t rhport) { - NVIC_DisableIRQ(rhport ? USB1_IRQn : USB0_IRQn); + NVIC_DisableIRQ(DCD_IRQn[rhport]); } void dcd_set_address(uint8_t rhport, uint8_t dev_addr) From 636c1475ba506b93a6a87f3acc96bb47922a900b Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 22 Nov 2019 12:38:24 +0700 Subject: [PATCH 072/267] clean up --- hw/bsp/mimxrt1064_evk/board.mk | 1 - 1 file changed, 1 deletion(-) diff --git a/hw/bsp/mimxrt1064_evk/board.mk b/hw/bsp/mimxrt1064_evk/board.mk index 1163810e..1490018c 100644 --- a/hw/bsp/mimxrt1064_evk/board.mk +++ b/hw/bsp/mimxrt1064_evk/board.mk @@ -56,4 +56,3 @@ JLINK_IF = swd flash: $(BUILD)/$(BOARD)-firmware.bin cp $< /media/$(USER)/RT1064-EVK/ - From f623dbc425b2e0dbee8409c81ba3d273407177ef Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 22 Nov 2019 12:41:47 +0700 Subject: [PATCH 073/267] config clean up --- examples/device/cdc_msc/src/tusb_config.h | 2 +- examples/device/cdc_msc_hid_freertos/src/tusb_config.h | 2 +- examples/device/dfu_rt/src/tusb_config.h | 2 +- examples/device/hid_composite/src/tusb_config.h | 2 +- examples/device/hid_generic_inout/src/tusb_config.h | 2 +- examples/device/midi_test/src/tusb_config.h | 2 +- examples/device/msc_dual_lun/src/tusb_config.h | 2 +- examples/device/usbtmc/src/tusb_config.h | 2 +- examples/device/webusb_serial/src/tusb_config.h | 2 +- examples/host/cdc_msc_hid/src/tusb_config.h | 2 +- test/test/support/tusb_config.h | 2 +- 11 files changed, 11 insertions(+), 11 deletions(-) diff --git a/examples/device/cdc_msc/src/tusb_config.h b/examples/device/cdc_msc/src/tusb_config.h index 4455f665..2b3002be 100644 --- a/examples/device/cdc_msc/src/tusb_config.h +++ b/examples/device/cdc_msc/src/tusb_config.h @@ -39,7 +39,7 @@ #error CFG_TUSB_MCU must be defined #endif -#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX +#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_RT10XX #define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED) #else #define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE diff --git a/examples/device/cdc_msc_hid_freertos/src/tusb_config.h b/examples/device/cdc_msc_hid_freertos/src/tusb_config.h index f84874ab..2b55faab 100644 --- a/examples/device/cdc_msc_hid_freertos/src/tusb_config.h +++ b/examples/device/cdc_msc_hid_freertos/src/tusb_config.h @@ -39,7 +39,7 @@ #error CFG_TUSB_MCU must be defined #endif -#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX +#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_RT10XX #define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED) #else #define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE diff --git a/examples/device/dfu_rt/src/tusb_config.h b/examples/device/dfu_rt/src/tusb_config.h index b4f7a556..4fab17f2 100644 --- a/examples/device/dfu_rt/src/tusb_config.h +++ b/examples/device/dfu_rt/src/tusb_config.h @@ -21,7 +21,7 @@ #error CFG_TUSB_MCU must be defined #endif -#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX +#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_RT10XX #define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED) #else #define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE diff --git a/examples/device/hid_composite/src/tusb_config.h b/examples/device/hid_composite/src/tusb_config.h index 8d29f10b..c1746539 100644 --- a/examples/device/hid_composite/src/tusb_config.h +++ b/examples/device/hid_composite/src/tusb_config.h @@ -39,7 +39,7 @@ #error CFG_TUSB_MCU must be defined #endif -#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX +#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_RT10XX #define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED) #else #define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE diff --git a/examples/device/hid_generic_inout/src/tusb_config.h b/examples/device/hid_generic_inout/src/tusb_config.h index a7ce7acf..bb292e78 100644 --- a/examples/device/hid_generic_inout/src/tusb_config.h +++ b/examples/device/hid_generic_inout/src/tusb_config.h @@ -39,7 +39,7 @@ #error CFG_TUSB_MCU must be defined #endif -#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX +#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_RT10XX #define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED) #else #define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE diff --git a/examples/device/midi_test/src/tusb_config.h b/examples/device/midi_test/src/tusb_config.h index fcd6b97c..62b4e88f 100644 --- a/examples/device/midi_test/src/tusb_config.h +++ b/examples/device/midi_test/src/tusb_config.h @@ -39,7 +39,7 @@ #error CFG_TUSB_MCU must be defined #endif -#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX +#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_RT10XX #define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED) #else #define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE diff --git a/examples/device/msc_dual_lun/src/tusb_config.h b/examples/device/msc_dual_lun/src/tusb_config.h index b45e9c4d..85de1279 100644 --- a/examples/device/msc_dual_lun/src/tusb_config.h +++ b/examples/device/msc_dual_lun/src/tusb_config.h @@ -39,7 +39,7 @@ #error CFG_TUSB_MCU must be defined #endif -#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX +#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_RT10XX #define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED) #else #define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE diff --git a/examples/device/usbtmc/src/tusb_config.h b/examples/device/usbtmc/src/tusb_config.h index 9141e6a5..4d2f77de 100644 --- a/examples/device/usbtmc/src/tusb_config.h +++ b/examples/device/usbtmc/src/tusb_config.h @@ -21,7 +21,7 @@ #error CFG_TUSB_MCU must be defined #endif -#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX +#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_RT10XX #define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED) #else #define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE diff --git a/examples/device/webusb_serial/src/tusb_config.h b/examples/device/webusb_serial/src/tusb_config.h index 8a73e835..f82ef2b2 100644 --- a/examples/device/webusb_serial/src/tusb_config.h +++ b/examples/device/webusb_serial/src/tusb_config.h @@ -39,7 +39,7 @@ #error CFG_TUSB_MCU must be defined #endif -#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX +#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_RT10XX #define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED) #else #define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE diff --git a/examples/host/cdc_msc_hid/src/tusb_config.h b/examples/host/cdc_msc_hid/src/tusb_config.h index 7a18c692..ef05da66 100644 --- a/examples/host/cdc_msc_hid/src/tusb_config.h +++ b/examples/host/cdc_msc_hid/src/tusb_config.h @@ -40,7 +40,7 @@ #error CFG_TUSB_MCU must be defined #endif -#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX +#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_RT10XX #define CFG_TUSB_RHPORT0_MODE (OPT_MODE_HOST | OPT_MODE_HIGH_SPEED) #else #define CFG_TUSB_RHPORT0_MODE OPT_MODE_HOST diff --git a/test/test/support/tusb_config.h b/test/test/support/tusb_config.h index f0a82d0b..888ac76a 100644 --- a/test/test/support/tusb_config.h +++ b/test/test/support/tusb_config.h @@ -43,7 +43,7 @@ #define CFG_TUSB_MCU OPT_MCU_NRF5X #endif -#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX +#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_RT10XX #define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED) #else #define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE From a0b2561a2df93cccbf48002348daf4220262f8d8 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 22 Nov 2019 14:20:10 +0700 Subject: [PATCH 074/267] move nxp dcd ehci controller reset and modde into dcd rt1064 work with cdc msc example --- hw/bsp/ea4357/ea4357.c | 52 +++++++++++----------- hw/bsp/mcb1800/mcb1800.c | 48 ++++++++++---------- hw/bsp/ngx4330/ngx4330.c | 52 +++++++++++----------- src/portable/nxp/lpc18_43/dcd_lpc18_43.c | 56 +++++++++++++++++++++--- 4 files changed, 125 insertions(+), 83 deletions(-) diff --git a/hw/bsp/ea4357/ea4357.c b/hw/bsp/ea4357/ea4357.c index f21d3259..f5d2a199 100644 --- a/hw/bsp/ea4357/ea4357.c +++ b/hw/bsp/ea4357/ea4357.c @@ -166,19 +166,19 @@ void board_init(void) #if CFG_TUSB_RHPORT0_MODE Chip_USB0_Init(); - // Reset controller - LPC_USB0->USBCMD_D |= 0x02; - while( LPC_USB0->USBCMD_D & 0x02 ) {} - - // Set mode - #if CFG_TUSB_RHPORT0_MODE & OPT_MODE_HOST - LPC_USB0->USBMODE_H = USBMODE_HOST | (USBMODE_VBUS_HIGH << 5); - - LPC_USB0->PORTSC1_D |= (1<<24); // FIXME force full speed for debugging - #else // TODO OTG - LPC_USB0->USBMODE_D = USBMODE_DEVICE; - LPC_USB0->OTGSC = (1<<3) | (1<<0) /*| (1<<16)| (1<<24)| (1<<25)| (1<<26)| (1<<27)| (1<<28)| (1<<29)| (1<<30)*/; - #endif +// // Reset controller +// LPC_USB0->USBCMD_D |= 0x02; +// while( LPC_USB0->USBCMD_D & 0x02 ) {} +// +// // Set mode +// #if CFG_TUSB_RHPORT0_MODE & OPT_MODE_HOST +// LPC_USB0->USBMODE_H = USBMODE_HOST | (USBMODE_VBUS_HIGH << 5); +// +// LPC_USB0->PORTSC1_D |= (1<<24); // FIXME force full speed for debugging +// #else // TODO OTG +// LPC_USB0->USBMODE_D = USBMODE_DEVICE; +// LPC_USB0->OTGSC = (1<<3) | (1<<0) /*| (1<<16)| (1<<24)| (1<<25)| (1<<26)| (1<<27)| (1<<28)| (1<<29)| (1<<30)*/; +// #endif #endif /* USB1 @@ -202,19 +202,19 @@ void board_init(void) #if CFG_TUSB_RHPORT1_MODE Chip_USB1_Init(); - // Reset controller - LPC_USB1->USBCMD_D |= 0x02; - while( LPC_USB1->USBCMD_D & 0x02 ) {} - - // Set mode - #if CFG_TUSB_RHPORT1_MODE & OPT_MODE_HOST - LPC_USB1->USBMODE_H = USBMODE_HOST | (USBMODE_VBUS_HIGH << 5); - #else // TODO OTG - LPC_USB1->USBMODE_D = USBMODE_DEVICE; - #endif - - // USB1 as fullspeed - LPC_USB1->PORTSC1_D |= (1<<24); +// // Reset controller +// LPC_USB1->USBCMD_D |= 0x02; +// while( LPC_USB1->USBCMD_D & 0x02 ) {} +// +// // Set mode +// #if CFG_TUSB_RHPORT1_MODE & OPT_MODE_HOST +// LPC_USB1->USBMODE_H = USBMODE_HOST | (USBMODE_VBUS_HIGH << 5); +// #else // TODO OTG +// LPC_USB1->USBMODE_D = USBMODE_DEVICE; +// #endif +// +// // USB1 as fullspeed +// LPC_USB1->PORTSC1_D |= (1<<24); #endif // USB0 Vbus Power: P2_3 on EA4357 channel B U20 GPIO26 active low (base board) diff --git a/hw/bsp/mcb1800/mcb1800.c b/hw/bsp/mcb1800/mcb1800.c index 4fe87476..6d528486 100644 --- a/hw/bsp/mcb1800/mcb1800.c +++ b/hw/bsp/mcb1800/mcb1800.c @@ -139,36 +139,36 @@ void board_init(void) #if CFG_TUSB_RHPORT0_MODE Chip_USB0_Init(); - // Reset controller - LPC_USB0->USBCMD_D |= 0x02; - while( LPC_USB0->USBCMD_D & 0x02 ) {} - - // Set mode - #if CFG_TUSB_RHPORT0_MODE & OPT_MODE_HOST - LPC_USB0->USBMODE_H = USBMODE_HOST | (USBMODE_VBUS_HIGH << 5); - #else // TODO OTG - LPC_USB0->USBMODE_D = USBMODE_DEVICE; - LPC_USB0->OTGSC = (1<<3) | (1<<0) /*| (1<<16)| (1<<24)| (1<<25)| (1<<26)| (1<<27)| (1<<28)| (1<<29)| (1<<30)*/; - #endif +// // Reset controller +// LPC_USB0->USBCMD_D |= 0x02; +// while( LPC_USB0->USBCMD_D & 0x02 ) {} +// +// // Set mode +// #if CFG_TUSB_RHPORT0_MODE & OPT_MODE_HOST +// LPC_USB0->USBMODE_H = USBMODE_HOST | (USBMODE_VBUS_HIGH << 5); +// #else // TODO OTG +// LPC_USB0->USBMODE_D = USBMODE_DEVICE; +// LPC_USB0->OTGSC = (1<<3) | (1<<0) /*| (1<<16)| (1<<24)| (1<<25)| (1<<26)| (1<<27)| (1<<28)| (1<<29)| (1<<30)*/; +// #endif #endif // USB1 #if CFG_TUSB_RHPORT1_MODE Chip_USB1_Init(); - // Reset controller - LPC_USB1->USBCMD_D |= 0x02; - while( LPC_USB1->USBCMD_D & 0x02 ) {} - - // Set mode - #if CFG_TUSB_RHPORT1_MODE & OPT_MODE_HOST - LPC_USB1->USBMODE_H = USBMODE_HOST | (USBMODE_VBUS_HIGH << 5); - #else // TODO OTG - LPC_USB1->USBMODE_D = USBMODE_DEVICE; - #endif - - // USB1 as fullspeed - LPC_USB1->PORTSC1_D |= (1<<24); +// // Reset controller +// LPC_USB1->USBCMD_D |= 0x02; +// while( LPC_USB1->USBCMD_D & 0x02 ) {} +// +// // Set mode +// #if CFG_TUSB_RHPORT1_MODE & OPT_MODE_HOST +// LPC_USB1->USBMODE_H = USBMODE_HOST | (USBMODE_VBUS_HIGH << 5); +// #else // TODO OTG +// LPC_USB1->USBMODE_D = USBMODE_DEVICE; +// #endif +// +// // USB1 as fullspeed +// LPC_USB1->PORTSC1_D |= (1<<24); #endif } diff --git a/hw/bsp/ngx4330/ngx4330.c b/hw/bsp/ngx4330/ngx4330.c index fd6f0119..e1bafff8 100644 --- a/hw/bsp/ngx4330/ngx4330.c +++ b/hw/bsp/ngx4330/ngx4330.c @@ -164,19 +164,19 @@ void board_init(void) #if CFG_TUSB_RHPORT0_MODE Chip_USB0_Init(); - // Reset controller - LPC_USB0->USBCMD_D |= 0x02; - while( LPC_USB0->USBCMD_D & 0x02 ) {} - - // Set mode - #if CFG_TUSB_RHPORT0_MODE & OPT_MODE_HOST - LPC_USB0->USBMODE_H = USBMODE_HOST | (USBMODE_VBUS_HIGH << 5); - - LPC_USB0->PORTSC1_D |= (1<<24); // FIXME force full speed for debugging - #else // TODO OTG - LPC_USB0->USBMODE_D = USBMODE_DEVICE; - LPC_USB0->OTGSC = (1<<3) | (1<<0) /*| (1<<16)| (1<<24)| (1<<25)| (1<<26)| (1<<27)| (1<<28)| (1<<29)| (1<<30)*/; - #endif +// // Reset controller +// LPC_USB0->USBCMD_D |= 0x02; +// while( LPC_USB0->USBCMD_D & 0x02 ) {} +// +// // Set mode +// #if CFG_TUSB_RHPORT0_MODE & OPT_MODE_HOST +// LPC_USB0->USBMODE_H = USBMODE_HOST | (USBMODE_VBUS_HIGH << 5); +// +// LPC_USB0->PORTSC1_D |= (1<<24); // FIXME force full speed for debugging +// #else // TODO OTG +// LPC_USB0->USBMODE_D = USBMODE_DEVICE; +// LPC_USB0->OTGSC = (1<<3) | (1<<0) /*| (1<<16)| (1<<24)| (1<<25)| (1<<26)| (1<<27)| (1<<28)| (1<<29)| (1<<30)*/; +// #endif #endif /* USB1 @@ -200,19 +200,19 @@ void board_init(void) #if CFG_TUSB_RHPORT1_MODE Chip_USB1_Init(); - // Reset controller - LPC_USB1->USBCMD_D |= 0x02; - while( LPC_USB1->USBCMD_D & 0x02 ) {} - - // Set mode - #if CFG_TUSB_RHPORT1_MODE & OPT_MODE_HOST - LPC_USB1->USBMODE_H = USBMODE_HOST | (USBMODE_VBUS_HIGH << 5); - #else // TODO OTG - LPC_USB1->USBMODE_D = USBMODE_DEVICE; - #endif - - // USB1 as fullspeed - LPC_USB1->PORTSC1_D |= (1<<24); +// // Reset controller +// LPC_USB1->USBCMD_D |= 0x02; +// while( LPC_USB1->USBCMD_D & 0x02 ) {} +// +// // Set mode +// #if CFG_TUSB_RHPORT1_MODE & OPT_MODE_HOST +// LPC_USB1->USBMODE_H = USBMODE_HOST | (USBMODE_VBUS_HIGH << 5); +// #else // TODO OTG +// LPC_USB1->USBMODE_D = USBMODE_DEVICE; +// #endif +// +// // USB1 as fullspeed +// LPC_USB1->PORTSC1_D |= (1<<24); // Chip_GPIO_SetPinDIROutput(LPC_GPIO_PORT, 5, 6); /* GPIO5[6] = USB1_PWR_EN */ // Chip_GPIO_SetPinState(LPC_GPIO_PORT, 5, 6, true); /* GPIO5[6] output high */ diff --git a/src/portable/nxp/lpc18_43/dcd_lpc18_43.c b/src/portable/nxp/lpc18_43/dcd_lpc18_43.c index 4972446b..b9527d65 100644 --- a/src/portable/nxp/lpc18_43/dcd_lpc18_43.c +++ b/src/portable/nxp/lpc18_43/dcd_lpc18_43.c @@ -79,11 +79,42 @@ enum { INTR_NAK = TU_BIT(16) }; -// PORTSC +// PORTSC1 enum { - PORTSC_CURRENT_CONNECT_STATUS = TU_BIT(0), - PORTSC_FORCE_PORT_RESUME = TU_BIT(6), - PORTSC_SUSPEND = TU_BIT(7) + PORTSC1_CURRENT_CONNECT_STATUS = TU_BIT(0), + PORTSC1_FORCE_PORT_RESUME = TU_BIT(6), + PORTSC1_SUSPEND = TU_BIT(7), + PORTSC1_FORCE_FULL_SPEED = TU_BIT(24), +}; + +// OTGSC +enum { + OTGSC_VBUS_DISCHARGE = TU_BIT(0), + OTGSC_VBUS_CHARGE = TU_BIT(1), +// OTGSC_HWASSIST_AUTORESET = TU_BIT(2), + OTGSC_OTG_TERMINATION = TU_BIT(3), ///< Must set to 1 when OTG go to device mode + OTGSC_DATA_PULSING = TU_BIT(4), + OTGSC_ID_PULLUP = TU_BIT(5), +// OTGSC_HWASSIT_DATA_PULSE = TU_BIT(6), +// OTGSC_HWASSIT_BDIS_ACONN = TU_BIT(7), + OTGSC_ID = TU_BIT(8), ///< 0 = A device, 1 = B Device + OTGSC_A_VBUS_VALID = TU_BIT(9), + OTGSC_A_SESSION_VALID = TU_BIT(10), + OTGSC_B_SESSION_VALID = TU_BIT(11), + OTGSC_B_SESSION_END = TU_BIT(12), + OTGSC_1MS_TOGGLE = TU_BIT(13), + OTGSC_DATA_BUS_PULSING_STATUS = TU_BIT(14), +}; + +// USBMode +enum { + USBMODE_CM_DEVICE = 2, + USBMODE_CM_HOST = 3, + + USBMODE_SLOM = TU_BIT(3), + USBMODE_SDIS = TU_BIT(4), + + USBMODE_VBUS_POWER_SELCT = TU_BIT(5), // Enable for LPC18XX/43XX in host most only }; // Device Registers @@ -258,9 +289,20 @@ static void bus_reset(uint8_t rhport) void dcd_init(uint8_t rhport) { + tu_memclr(&_dcd_data, sizeof(dcd_data_t)); + dcd_registers_t* const dcd_reg = DCD_REGS[rhport]; - tu_memclr(&_dcd_data, sizeof(dcd_data_t)); + // Reset controller + dcd_reg->USBCMD |= USBCMD_RESET; + while( dcd_reg->USBCMD & USBCMD_RESET ) {} + + // Set mode to device, must be set immediately after reset + dcd_reg->USBMODE = USBMODE_CM_DEVICE; + dcd_reg->OTGSC = OTGSC_VBUS_DISCHARGE | OTGSC_OTG_TERMINATION; + + // TODO Force fullspeed on non-highspeed port + // dcd_reg->PORTSC1 = PORTSC1_FORCE_FULL_SPEED; dcd_reg->ENDPTLISTADDR = (uint32_t) _dcd_data.qhd; // Endpoint List Address has to be 2K alignment dcd_reg->USBSTS = dcd_reg->USBSTS; @@ -423,7 +465,7 @@ void dcd_isr(uint8_t rhport) if (int_status & INTR_SUSPEND) { - if (dcd_reg->PORTSC1 & PORTSC_SUSPEND) + if (dcd_reg->PORTSC1 & PORTSC1_SUSPEND) { // Note: Host may delay more than 3 ms before and/or after bus reset before doing enumeration. if ((dcd_reg->DEVICEADDR >> 25) & 0x0f) @@ -436,7 +478,7 @@ void dcd_isr(uint8_t rhport) // TODO disconnection does not generate interrupt !!!!!! // if (int_status & INTR_PORT_CHANGE) // { -// if ( !(dcd_reg->PORTSC1 & PORTSC_CURRENT_CONNECT_STATUS) ) +// if ( !(dcd_reg->PORTSC1 & PORTSC1_CURRENT_CONNECT_STATUS) ) // { // dcd_event_t event = { .rhport = rhport, .event_id = DCD_EVENT_UNPLUGGED }; // dcd_event_handler(&event, true); From 6123b600fc9706cec73f1116eeaf0246773fccf9 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 22 Nov 2019 14:47:07 +0700 Subject: [PATCH 075/267] rename dcd_lpc18_43 to dcd_transdimension --- .../dcd_lpc18_43.c => transdimension/dcd_transdimension.c} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename src/portable/nxp/{lpc18_43/dcd_lpc18_43.c => transdimension/dcd_transdimension.c} (100%) diff --git a/src/portable/nxp/lpc18_43/dcd_lpc18_43.c b/src/portable/nxp/transdimension/dcd_transdimension.c similarity index 100% rename from src/portable/nxp/lpc18_43/dcd_lpc18_43.c rename to src/portable/nxp/transdimension/dcd_transdimension.c From a02e723d098c3e2735e84a229968947e485e1b68 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 22 Nov 2019 14:54:23 +0700 Subject: [PATCH 076/267] rename dcd lpc18_43 to transdimension --- hw/bsp/ea4357/board.mk | 2 +- hw/bsp/mcb1800/board.mk | 2 +- hw/bsp/mimxrt1064_evk/board.mk | 2 +- hw/bsp/ngx4330/board.mk | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/hw/bsp/ea4357/board.mk b/hw/bsp/ea4357/board.mk index 8c3cfd82..098fb4c9 100644 --- a/hw/bsp/ea4357/board.mk +++ b/hw/bsp/ea4357/board.mk @@ -32,7 +32,7 @@ INC += \ # For TinyUSB port source VENDOR = nxp -CHIP_FAMILY = lpc18_43 +CHIP_FAMILY = transdimension # For freeRTOS port source FREERTOS_PORT = ARM_CM4 diff --git a/hw/bsp/mcb1800/board.mk b/hw/bsp/mcb1800/board.mk index 953f5943..b05d4d71 100644 --- a/hw/bsp/mcb1800/board.mk +++ b/hw/bsp/mcb1800/board.mk @@ -30,7 +30,7 @@ INC += \ # For TinyUSB port source VENDOR = nxp -CHIP_FAMILY = lpc18_43 +CHIP_FAMILY = transdimension # For freeRTOS port source FREERTOS_PORT = ARM_CM3 diff --git a/hw/bsp/mimxrt1064_evk/board.mk b/hw/bsp/mimxrt1064_evk/board.mk index 1490018c..cd3c17ae 100644 --- a/hw/bsp/mimxrt1064_evk/board.mk +++ b/hw/bsp/mimxrt1064_evk/board.mk @@ -41,7 +41,7 @@ SRC_S += $(MCU_DIR)/gcc/startup_MIMXRT1064.S # For TinyUSB port source VENDOR = nxp -CHIP_FAMILY = lpc18_43 +CHIP_FAMILY = transdimension # For freeRTOS port source FREERTOS_PORT = ARM_CM7 diff --git a/hw/bsp/ngx4330/board.mk b/hw/bsp/ngx4330/board.mk index 863a4966..d95aaf05 100644 --- a/hw/bsp/ngx4330/board.mk +++ b/hw/bsp/ngx4330/board.mk @@ -30,7 +30,7 @@ INC += \ # For TinyUSB port source VENDOR = nxp -CHIP_FAMILY = lpc18_43 +CHIP_FAMILY = transdimension # For freeRTOS port source FREERTOS_PORT = ARM_CM4 From 00a571fc3837db8276b1ee0e80019545d39e5c36 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 22 Nov 2019 15:37:23 +0700 Subject: [PATCH 077/267] doc update --- README.md | 7 +++++-- docs/boards.md | 8 ++++++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 2e61c75e..588526ff 100644 --- a/README.md +++ b/README.md @@ -25,9 +25,12 @@ TinyUSB is an open-source cross-platform USB Host/Device stack for embedded syst The stack supports the following MCUs -- **Nordic:** nRF52840, nRF52833 -- **NXP:** LPC Series: 11Uxx, 13xx, 175x_6x, 177x_8x, 18xx, 40xx, 43xx, 51Uxx, 54xxx, 55xx +- **Tomu:** [valentyusb](https://github.com/im-tomu/valentyusb) (eptri) - **MicroChip:** SAMD21, SAMD51 (device only) +- **Nordic:** nRF52840, nRF52833 +- **NXP:** + - LPC Series: 11Uxx, 13xx, 175x_6x, 177x_8x, 18xx, 40xx, 43xx, 51Uxx, 54xxx, 55xx + - iMX RT Series: RT1064 - **Sony:** CXD56 - **ST:** STM32 series: L0, F0, F1, F2, F3, F4, F7, H7 (device only) diff --git a/docs/boards.md b/docs/boards.md index 3ca4d458..caf4ef6f 100644 --- a/docs/boards.md +++ b/docs/boards.md @@ -9,6 +9,10 @@ The board support code is only used for self-contained examples and testing. It This code base already had supported for a handful of following boards +## Tomu + +- [Fomu](https://www.crowdsupply.com/sutajio-kosagi/fomu) + ### MicroChip SAMD - [Adafruit Circuit Playground Express](https://www.adafruit.com/product/3333) @@ -26,6 +30,10 @@ This code base already had supported for a handful of following boards - [Nordic nRF52840 Dongle (aka pca10059)](https://www.nordicsemi.com/Software-and-Tools/Development-Kits/nRF52840-Dongle) - [Nordic nRF52833 Development Kit (aka pca10100)](https://www.nordicsemi.com/Software-and-Tools/Development-Kits/nRF52833-DK) +### NXP iMX RT + +- [iMX RT1064 Evaluation Kit](https://www.nxp.com/design/development-boards/i.mx-evaluation-and-development-boards/mimxrt1064-evk-i.mx-rt1064-evaluation-kit:MIMXRT1064-EVK) + ### NXP LPC - [LPCXpresso 11u37](https://www.nxp.com/design/microcontrollers-developer-resources/lpcxpresso-boards/lpcxpresso-board-for-lpc11u37h:OM13074) From 281e8cd9ecd4b324982a7ceaab14fdfa9ce27a1d Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 22 Nov 2019 15:42:46 +0700 Subject: [PATCH 078/267] rename OPT_MCU_RT10XX to OPT_MCU_IMXRT10XX --- examples/device/cdc_msc/src/tusb_config.h | 2 +- examples/device/cdc_msc_hid_freertos/src/tusb_config.h | 2 +- examples/device/dfu_rt/src/tusb_config.h | 2 +- examples/device/hid_composite/src/tusb_config.h | 2 +- examples/device/hid_generic_inout/src/tusb_config.h | 2 +- examples/device/midi_test/src/tusb_config.h | 2 +- examples/device/msc_dual_lun/src/tusb_config.h | 2 +- examples/device/usbtmc/src/tusb_config.h | 2 +- examples/device/webusb_serial/src/tusb_config.h | 2 +- examples/host/cdc_msc_hid/src/tusb_config.h | 2 +- hw/bsp/mimxrt1064_evk/board.mk | 2 +- src/portable/nxp/transdimension/dcd_transdimension.c | 4 ++-- src/tusb_option.h | 2 +- test/test/support/tusb_config.h | 2 +- 14 files changed, 15 insertions(+), 15 deletions(-) diff --git a/examples/device/cdc_msc/src/tusb_config.h b/examples/device/cdc_msc/src/tusb_config.h index 2b3002be..0210abda 100644 --- a/examples/device/cdc_msc/src/tusb_config.h +++ b/examples/device/cdc_msc/src/tusb_config.h @@ -39,7 +39,7 @@ #error CFG_TUSB_MCU must be defined #endif -#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_RT10XX +#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_IMXRT10XX #define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED) #else #define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE diff --git a/examples/device/cdc_msc_hid_freertos/src/tusb_config.h b/examples/device/cdc_msc_hid_freertos/src/tusb_config.h index 2b55faab..32c313f1 100644 --- a/examples/device/cdc_msc_hid_freertos/src/tusb_config.h +++ b/examples/device/cdc_msc_hid_freertos/src/tusb_config.h @@ -39,7 +39,7 @@ #error CFG_TUSB_MCU must be defined #endif -#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_RT10XX +#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_IMXRT10XX #define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED) #else #define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE diff --git a/examples/device/dfu_rt/src/tusb_config.h b/examples/device/dfu_rt/src/tusb_config.h index 4fab17f2..0ba90226 100644 --- a/examples/device/dfu_rt/src/tusb_config.h +++ b/examples/device/dfu_rt/src/tusb_config.h @@ -21,7 +21,7 @@ #error CFG_TUSB_MCU must be defined #endif -#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_RT10XX +#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_IMXRT10XX #define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED) #else #define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE diff --git a/examples/device/hid_composite/src/tusb_config.h b/examples/device/hid_composite/src/tusb_config.h index c1746539..91dee441 100644 --- a/examples/device/hid_composite/src/tusb_config.h +++ b/examples/device/hid_composite/src/tusb_config.h @@ -39,7 +39,7 @@ #error CFG_TUSB_MCU must be defined #endif -#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_RT10XX +#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_IMXRT10XX #define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED) #else #define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE diff --git a/examples/device/hid_generic_inout/src/tusb_config.h b/examples/device/hid_generic_inout/src/tusb_config.h index bb292e78..5950f1d9 100644 --- a/examples/device/hid_generic_inout/src/tusb_config.h +++ b/examples/device/hid_generic_inout/src/tusb_config.h @@ -39,7 +39,7 @@ #error CFG_TUSB_MCU must be defined #endif -#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_RT10XX +#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_IMXRT10XX #define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED) #else #define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE diff --git a/examples/device/midi_test/src/tusb_config.h b/examples/device/midi_test/src/tusb_config.h index 62b4e88f..1d90a948 100644 --- a/examples/device/midi_test/src/tusb_config.h +++ b/examples/device/midi_test/src/tusb_config.h @@ -39,7 +39,7 @@ #error CFG_TUSB_MCU must be defined #endif -#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_RT10XX +#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_IMXRT10XX #define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED) #else #define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE diff --git a/examples/device/msc_dual_lun/src/tusb_config.h b/examples/device/msc_dual_lun/src/tusb_config.h index 85de1279..1025fa46 100644 --- a/examples/device/msc_dual_lun/src/tusb_config.h +++ b/examples/device/msc_dual_lun/src/tusb_config.h @@ -39,7 +39,7 @@ #error CFG_TUSB_MCU must be defined #endif -#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_RT10XX +#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_IMXRT10XX #define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED) #else #define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE diff --git a/examples/device/usbtmc/src/tusb_config.h b/examples/device/usbtmc/src/tusb_config.h index 4d2f77de..a3c14d7d 100644 --- a/examples/device/usbtmc/src/tusb_config.h +++ b/examples/device/usbtmc/src/tusb_config.h @@ -21,7 +21,7 @@ #error CFG_TUSB_MCU must be defined #endif -#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_RT10XX +#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_IMXRT10XX #define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED) #else #define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE diff --git a/examples/device/webusb_serial/src/tusb_config.h b/examples/device/webusb_serial/src/tusb_config.h index f82ef2b2..92b97400 100644 --- a/examples/device/webusb_serial/src/tusb_config.h +++ b/examples/device/webusb_serial/src/tusb_config.h @@ -39,7 +39,7 @@ #error CFG_TUSB_MCU must be defined #endif -#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_RT10XX +#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_IMXRT10XX #define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED) #else #define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE diff --git a/examples/host/cdc_msc_hid/src/tusb_config.h b/examples/host/cdc_msc_hid/src/tusb_config.h index ef05da66..f8a6dc98 100644 --- a/examples/host/cdc_msc_hid/src/tusb_config.h +++ b/examples/host/cdc_msc_hid/src/tusb_config.h @@ -40,7 +40,7 @@ #error CFG_TUSB_MCU must be defined #endif -#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_RT10XX +#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_IMXRT10XX #define CFG_TUSB_RHPORT0_MODE (OPT_MODE_HOST | OPT_MODE_HIGH_SPEED) #else #define CFG_TUSB_RHPORT0_MODE OPT_MODE_HOST diff --git a/hw/bsp/mimxrt1064_evk/board.mk b/hw/bsp/mimxrt1064_evk/board.mk index cd3c17ae..94011ec8 100644 --- a/hw/bsp/mimxrt1064_evk/board.mk +++ b/hw/bsp/mimxrt1064_evk/board.mk @@ -8,7 +8,7 @@ CFLAGS += \ -DCPU_MIMXRT1064DVL6A \ -DXIP_EXTERNAL_FLASH=1 \ -DXIP_BOOT_HEADER_ENABLE=1 \ - -DCFG_TUSB_MCU=OPT_MCU_RT10XX \ + -DCFG_TUSB_MCU=OPT_MCU_IMXRT10XX \ -DCFG_TUSB_MEM_SECTION='__attribute__((section(".data")))' \ -DCFG_TUSB_MEM_ALIGN='__attribute__((aligned(64)))' diff --git a/src/portable/nxp/transdimension/dcd_transdimension.c b/src/portable/nxp/transdimension/dcd_transdimension.c index b9527d65..a17770ce 100644 --- a/src/portable/nxp/transdimension/dcd_transdimension.c +++ b/src/portable/nxp/transdimension/dcd_transdimension.c @@ -28,7 +28,7 @@ #if TUSB_OPT_DEVICE_ENABLED && (CFG_TUSB_MCU == OPT_MCU_LPC18XX || \ CFG_TUSB_MCU == OPT_MCU_LPC43XX || \ - CFG_TUSB_MCU == OPT_MCU_RT10XX) + CFG_TUSB_MCU == OPT_MCU_IMXRT10XX) //--------------------------------------------------------------------+ // INCLUDE @@ -36,7 +36,7 @@ #include "common/tusb_common.h" #include "device/dcd.h" -#if CFG_TUSB_MCU == OPT_MCU_RT10XX +#if CFG_TUSB_MCU == OPT_MCU_IMXRT10XX #include "fsl_device_registers.h" #define DCD_REGS_BASE { (dcd_registers_t*) USB1_BASE, (dcd_registers_t*) USB2_BASE } IRQn_Type DCD_IRQn[] = { USB_OTG1_IRQn, USB_OTG2_IRQn }; diff --git a/src/tusb_option.h b/src/tusb_option.h index cc7b4675..d7cbcb2d 100644 --- a/src/tusb_option.h +++ b/src/tusb_option.h @@ -72,7 +72,7 @@ #define OPT_MCU_VALENTYUSB_EPTRI 600 ///< Fomu eptri config -#define OPT_MCU_RT10XX 700 ///< NXP iMX RT10xx +#define OPT_MCU_IMXRT10XX 700 ///< NXP iMX RT10xx /** @} */ diff --git a/test/test/support/tusb_config.h b/test/test/support/tusb_config.h index 888ac76a..9ebd7e43 100644 --- a/test/test/support/tusb_config.h +++ b/test/test/support/tusb_config.h @@ -43,7 +43,7 @@ #define CFG_TUSB_MCU OPT_MCU_NRF5X #endif -#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_RT10XX +#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_IMXRT10XX #define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED) #else #define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE From d1d8ded43b7e91e1af305d8b3eb4ea15246c70c7 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 22 Nov 2019 17:36:04 +0700 Subject: [PATCH 079/267] added iMX RT1060 EVK board support board_text, cdc_msc, hid_composite all work --- hw/bsp/mimxrt1060_evk/board.h | 34 +++ hw/bsp/mimxrt1060_evk/board.mk | 58 ++++ .../evkmimxrt1060_flexspi_nor_config.c | 49 ++++ .../evkmimxrt1060_flexspi_nor_config.h | 268 ++++++++++++++++++ hw/bsp/mimxrt1060_evk/mimxrt1060_evk.c | 184 ++++++++++++ 5 files changed, 593 insertions(+) create mode 100644 hw/bsp/mimxrt1060_evk/board.h create mode 100644 hw/bsp/mimxrt1060_evk/board.mk create mode 100644 hw/bsp/mimxrt1060_evk/evkmimxrt1060_flexspi_nor_config.c create mode 100644 hw/bsp/mimxrt1060_evk/evkmimxrt1060_flexspi_nor_config.h create mode 100644 hw/bsp/mimxrt1060_evk/mimxrt1060_evk.c diff --git a/hw/bsp/mimxrt1060_evk/board.h b/hw/bsp/mimxrt1060_evk/board.h new file mode 100644 index 00000000..f1bd0636 --- /dev/null +++ b/hw/bsp/mimxrt1060_evk/board.h @@ -0,0 +1,34 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019, Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + + +#ifndef BOARD_H_ +#define BOARD_H_ + +// required since iMX RT10xx SDK include this file for board size +#define BOARD_FLASH_SIZE (0x800000U) + +#endif /* BOARD_H_ */ diff --git a/hw/bsp/mimxrt1060_evk/board.mk b/hw/bsp/mimxrt1060_evk/board.mk new file mode 100644 index 00000000..e81e41c1 --- /dev/null +++ b/hw/bsp/mimxrt1060_evk/board.mk @@ -0,0 +1,58 @@ +CFLAGS += \ + -mthumb \ + -mabi=aapcs \ + -mcpu=cortex-m7 \ + -mfloat-abi=hard \ + -mfpu=fpv5-d16 \ + -D__ARMVFP__=0 -D__ARMFPV5__=0\ + -DCPU_MIMXRT1062DVL6A \ + -DXIP_EXTERNAL_FLASH=1 \ + -DXIP_BOOT_HEADER_ENABLE=1 \ + -DCFG_TUSB_MCU=OPT_MCU_IMXRT10XX \ + -DCFG_TUSB_MEM_SECTION='__attribute__((section(".data")))' \ + -DCFG_TUSB_MEM_ALIGN='__attribute__((aligned(64)))' + +# mcu driver cause following warnings +#CFLAGS += -Wno-error=float-equal -Wno-error=nested-externs +CFLAGS += -Wno-error=unused-parameter + +MCU_DIR = hw/mcu/nxp/sdk/devices/MIMXRT1062 + +# All source paths should be relative to the top level. +LD_FILE = $(MCU_DIR)/gcc/MIMXRT1062xxxxx_flexspi_nor.ld + +SRC_C += \ + $(MCU_DIR)/system_MIMXRT1062.c \ + $(MCU_DIR)/xip/fsl_flexspi_nor_boot.c \ + $(MCU_DIR)/project_template/clock_config.c \ + $(MCU_DIR)/drivers/fsl_clock.c \ + $(MCU_DIR)/drivers/fsl_gpio.c \ + $(MCU_DIR)/drivers/fsl_common.c \ + $(MCU_DIR)/drivers/fsl_lpuart.c + +INC += \ + $(TOP)/hw/bsp/$(BOARD) \ + $(TOP)/$(MCU_DIR)/../../CMSIS/Include \ + $(TOP)/$(MCU_DIR) \ + $(TOP)/$(MCU_DIR)/drivers \ + $(TOP)/$(MCU_DIR)/project_template \ + +SRC_S += $(MCU_DIR)/gcc/startup_MIMXRT1062.S + +# For TinyUSB port source +VENDOR = nxp +CHIP_FAMILY = transdimension + +# For freeRTOS port source +FREERTOS_PORT = ARM_CM7 + +# For flash-jlink target +JLINK_DEVICE = MIMXRT1062xxx6A +JLINK_IF = swd + +# flash using pyocd +#flash: $(BUILD)/$(BOARD)-firmware.hex +# pyocd flash -t mimxrt1050_quadspi $< + +flash: $(BUILD)/$(BOARD)-firmware.bin + cp $< /media/$(USER)/RT1060-EVK/ diff --git a/hw/bsp/mimxrt1060_evk/evkmimxrt1060_flexspi_nor_config.c b/hw/bsp/mimxrt1060_evk/evkmimxrt1060_flexspi_nor_config.c new file mode 100644 index 00000000..5df2b7c1 --- /dev/null +++ b/hw/bsp/mimxrt1060_evk/evkmimxrt1060_flexspi_nor_config.c @@ -0,0 +1,49 @@ +/* + * Copyright 2018 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include "evkmimxrt1060_flexspi_nor_config.h" + +/* Component ID definition, used by tools. */ +#ifndef FSL_COMPONENT_ID +#define FSL_COMPONENT_ID "platform.drivers.xip_board" +#endif + +/******************************************************************************* + * Code + ******************************************************************************/ +#if defined(XIP_BOOT_HEADER_ENABLE) && (XIP_BOOT_HEADER_ENABLE == 1) +#if defined(__CC_ARM) || defined(__ARMCC_VERSION) || defined(__GNUC__) +__attribute__((section(".boot_hdr.conf"))) +#elif defined(__ICCARM__) +#pragma location = ".boot_hdr.conf" +#endif + +const flexspi_nor_config_t qspiflash_config = { + .memConfig = + { + .tag = FLEXSPI_CFG_BLK_TAG, + .version = FLEXSPI_CFG_BLK_VERSION, + .readSampleClkSrc = kFlexSPIReadSampleClk_LoopbackFromDqsPad, + .csHoldTime = 3u, + .csSetupTime = 3u, + // Enable DDR mode, Wordaddassable, Safe configuration, Differential clock + .sflashPadType = kSerialFlash_4Pads, + .serialClkFreq = kFlexSpiSerialClk_100MHz, + .sflashA1Size = 8u * 1024u * 1024u, + .lookupTable = + { + // Read LUTs + FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0xEB, RADDR_SDR, FLEXSPI_4PAD, 0x18), + FLEXSPI_LUT_SEQ(DUMMY_SDR, FLEXSPI_4PAD, 0x06, READ_SDR, FLEXSPI_4PAD, 0x04), + }, + }, + .pageSize = 256u, + .sectorSize = 4u * 1024u, + .blockSize = 256u * 1024u, + .isUniformBlockSize = false, +}; +#endif /* XIP_BOOT_HEADER_ENABLE */ diff --git a/hw/bsp/mimxrt1060_evk/evkmimxrt1060_flexspi_nor_config.h b/hw/bsp/mimxrt1060_evk/evkmimxrt1060_flexspi_nor_config.h new file mode 100644 index 00000000..28d7db57 --- /dev/null +++ b/hw/bsp/mimxrt1060_evk/evkmimxrt1060_flexspi_nor_config.h @@ -0,0 +1,268 @@ +/* + * Copyright 2018 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef __EVKMIMXRT1060_FLEXSPI_NOR_CONFIG__ +#define __EVKMIMXRT1060_FLEXSPI_NOR_CONFIG__ + +#include +#include +#include "fsl_common.h" + +/*! @name Driver version */ +/*@{*/ +/*! @brief XIP_BOARD driver version 2.0.0. */ +#define FSL_XIP_BOARD_DRIVER_VERSION (MAKE_VERSION(2, 0, 0)) +/*@}*/ + +/* FLEXSPI memory config block related defintions */ +#define FLEXSPI_CFG_BLK_TAG (0x42464346UL) // ascii "FCFB" Big Endian +#define FLEXSPI_CFG_BLK_VERSION (0x56010400UL) // V1.4.0 +#define FLEXSPI_CFG_BLK_SIZE (512) + +/* FLEXSPI Feature related definitions */ +#define FLEXSPI_FEATURE_HAS_PARALLEL_MODE 1 + +/* Lookup table related defintions */ +#define CMD_INDEX_READ 0 +#define CMD_INDEX_READSTATUS 1 +#define CMD_INDEX_WRITEENABLE 2 +#define CMD_INDEX_WRITE 4 + +#define CMD_LUT_SEQ_IDX_READ 0 +#define CMD_LUT_SEQ_IDX_READSTATUS 1 +#define CMD_LUT_SEQ_IDX_WRITEENABLE 3 +#define CMD_LUT_SEQ_IDX_WRITE 9 + +#define CMD_SDR 0x01 +#define CMD_DDR 0x21 +#define RADDR_SDR 0x02 +#define RADDR_DDR 0x22 +#define CADDR_SDR 0x03 +#define CADDR_DDR 0x23 +#define MODE1_SDR 0x04 +#define MODE1_DDR 0x24 +#define MODE2_SDR 0x05 +#define MODE2_DDR 0x25 +#define MODE4_SDR 0x06 +#define MODE4_DDR 0x26 +#define MODE8_SDR 0x07 +#define MODE8_DDR 0x27 +#define WRITE_SDR 0x08 +#define WRITE_DDR 0x28 +#define READ_SDR 0x09 +#define READ_DDR 0x29 +#define LEARN_SDR 0x0A +#define LEARN_DDR 0x2A +#define DATSZ_SDR 0x0B +#define DATSZ_DDR 0x2B +#define DUMMY_SDR 0x0C +#define DUMMY_DDR 0x2C +#define DUMMY_RWDS_SDR 0x0D +#define DUMMY_RWDS_DDR 0x2D +#define JMP_ON_CS 0x1F +#define STOP 0 + +#define FLEXSPI_1PAD 0 +#define FLEXSPI_2PAD 1 +#define FLEXSPI_4PAD 2 +#define FLEXSPI_8PAD 3 + +#define FLEXSPI_LUT_SEQ(cmd0, pad0, op0, cmd1, pad1, op1) \ + (FLEXSPI_LUT_OPERAND0(op0) | FLEXSPI_LUT_NUM_PADS0(pad0) | FLEXSPI_LUT_OPCODE0(cmd0) | FLEXSPI_LUT_OPERAND1(op1) | \ + FLEXSPI_LUT_NUM_PADS1(pad1) | FLEXSPI_LUT_OPCODE1(cmd1)) + +//!@brief Definitions for FlexSPI Serial Clock Frequency +typedef enum _FlexSpiSerialClockFreq +{ + kFlexSpiSerialClk_30MHz = 1, + kFlexSpiSerialClk_50MHz = 2, + kFlexSpiSerialClk_60MHz = 3, + kFlexSpiSerialClk_75MHz = 4, + kFlexSpiSerialClk_80MHz = 5, + kFlexSpiSerialClk_100MHz = 6, + kFlexSpiSerialClk_120MHz = 7, + kFlexSpiSerialClk_133MHz = 8, + kFlexSpiSerialClk_166MHz = 9, +} flexspi_serial_clk_freq_t; + +//!@brief FlexSPI clock configuration type +enum +{ + kFlexSpiClk_SDR, //!< Clock configure for SDR mode + kFlexSpiClk_DDR, //!< Clock configurat for DDR mode +}; + +//!@brief FlexSPI Read Sample Clock Source definition +typedef enum _FlashReadSampleClkSource +{ + kFlexSPIReadSampleClk_LoopbackInternally = 0, + kFlexSPIReadSampleClk_LoopbackFromDqsPad = 1, + kFlexSPIReadSampleClk_LoopbackFromSckPad = 2, + kFlexSPIReadSampleClk_ExternalInputFromDqsPad = 3, +} flexspi_read_sample_clk_t; + +//!@brief Misc feature bit definitions +enum +{ + kFlexSpiMiscOffset_DiffClkEnable = 0, //!< Bit for Differential clock enable + kFlexSpiMiscOffset_Ck2Enable = 1, //!< Bit for CK2 enable + kFlexSpiMiscOffset_ParallelEnable = 2, //!< Bit for Parallel mode enable + kFlexSpiMiscOffset_WordAddressableEnable = 3, //!< Bit for Word Addressable enable + kFlexSpiMiscOffset_SafeConfigFreqEnable = 4, //!< Bit for Safe Configuration Frequency enable + kFlexSpiMiscOffset_PadSettingOverrideEnable = 5, //!< Bit for Pad setting override enable + kFlexSpiMiscOffset_DdrModeEnable = 6, //!< Bit for DDR clock confiuration indication. +}; + +//!@brief Flash Type Definition +enum +{ + kFlexSpiDeviceType_SerialNOR = 1, //!< Flash devices are Serial NOR + kFlexSpiDeviceType_SerialNAND = 2, //!< Flash devices are Serial NAND + kFlexSpiDeviceType_SerialRAM = 3, //!< Flash devices are Serial RAM/HyperFLASH + kFlexSpiDeviceType_MCP_NOR_NAND = 0x12, //!< Flash device is MCP device, A1 is Serial NOR, A2 is Serial NAND + kFlexSpiDeviceType_MCP_NOR_RAM = 0x13, //!< Flash deivce is MCP device, A1 is Serial NOR, A2 is Serial RAMs +}; + +//!@brief Flash Pad Definitions +enum +{ + kSerialFlash_1Pad = 1, + kSerialFlash_2Pads = 2, + kSerialFlash_4Pads = 4, + kSerialFlash_8Pads = 8, +}; + +//!@brief FlexSPI LUT Sequence structure +typedef struct _lut_sequence +{ + uint8_t seqNum; //!< Sequence Number, valid number: 1-16 + uint8_t seqId; //!< Sequence Index, valid number: 0-15 + uint16_t reserved; +} flexspi_lut_seq_t; + +//!@brief Flash Configuration Command Type +enum +{ + kDeviceConfigCmdType_Generic, //!< Generic command, for example: configure dummy cycles, drive strength, etc + kDeviceConfigCmdType_QuadEnable, //!< Quad Enable command + kDeviceConfigCmdType_Spi2Xpi, //!< Switch from SPI to DPI/QPI/OPI mode + kDeviceConfigCmdType_Xpi2Spi, //!< Switch from DPI/QPI/OPI to SPI mode + kDeviceConfigCmdType_Spi2NoCmd, //!< Switch to 0-4-4/0-8-8 mode + kDeviceConfigCmdType_Reset, //!< Reset device command +}; + +//!@brief FlexSPI Memory Configuration Block +typedef struct _FlexSPIConfig +{ + uint32_t tag; //!< [0x000-0x003] Tag, fixed value 0x42464346UL + uint32_t version; //!< [0x004-0x007] Version,[31:24] -'V', [23:16] - Major, [15:8] - Minor, [7:0] - bugfix + uint32_t reserved0; //!< [0x008-0x00b] Reserved for future use + uint8_t readSampleClkSrc; //!< [0x00c-0x00c] Read Sample Clock Source, valid value: 0/1/3 + uint8_t csHoldTime; //!< [0x00d-0x00d] CS hold time, default value: 3 + uint8_t csSetupTime; //!< [0x00e-0x00e] CS setup time, default value: 3 + uint8_t columnAddressWidth; //!< [0x00f-0x00f] Column Address with, for HyperBus protocol, it is fixed to 3, For + //! Serial NAND, need to refer to datasheet + uint8_t deviceModeCfgEnable; //!< [0x010-0x010] Device Mode Configure enable flag, 1 - Enable, 0 - Disable + uint8_t deviceModeType; //!< [0x011-0x011] Specify the configuration command type:Quad Enable, DPI/QPI/OPI switch, + //! Generic configuration, etc. + uint16_t waitTimeCfgCommands; //!< [0x012-0x013] Wait time for all configuration commands, unit: 100us, Used for + //! DPI/QPI/OPI switch or reset command + flexspi_lut_seq_t deviceModeSeq; //!< [0x014-0x017] Device mode sequence info, [7:0] - LUT sequence id, [15:8] - LUt + //! sequence number, [31:16] Reserved + uint32_t deviceModeArg; //!< [0x018-0x01b] Argument/Parameter for device configuration + uint8_t configCmdEnable; //!< [0x01c-0x01c] Configure command Enable Flag, 1 - Enable, 0 - Disable + uint8_t configModeType[3]; //!< [0x01d-0x01f] Configure Mode Type, similar as deviceModeTpe + flexspi_lut_seq_t + configCmdSeqs[3]; //!< [0x020-0x02b] Sequence info for Device Configuration command, similar as deviceModeSeq + uint32_t reserved1; //!< [0x02c-0x02f] Reserved for future use + uint32_t configCmdArgs[3]; //!< [0x030-0x03b] Arguments/Parameters for device Configuration commands + uint32_t reserved2; //!< [0x03c-0x03f] Reserved for future use + uint32_t controllerMiscOption; //!< [0x040-0x043] Controller Misc Options, see Misc feature bit definitions for more + //! details + uint8_t deviceType; //!< [0x044-0x044] Device Type: See Flash Type Definition for more details + uint8_t sflashPadType; //!< [0x045-0x045] Serial Flash Pad Type: 1 - Single, 2 - Dual, 4 - Quad, 8 - Octal + uint8_t serialClkFreq; //!< [0x046-0x046] Serial Flash Frequencey, device specific definitions, See System Boot + //! Chapter for more details + uint8_t lutCustomSeqEnable; //!< [0x047-0x047] LUT customization Enable, it is required if the program/erase cannot + //! be done using 1 LUT sequence, currently, only applicable to HyperFLASH + uint32_t reserved3[2]; //!< [0x048-0x04f] Reserved for future use + uint32_t sflashA1Size; //!< [0x050-0x053] Size of Flash connected to A1 + uint32_t sflashA2Size; //!< [0x054-0x057] Size of Flash connected to A2 + uint32_t sflashB1Size; //!< [0x058-0x05b] Size of Flash connected to B1 + uint32_t sflashB2Size; //!< [0x05c-0x05f] Size of Flash connected to B2 + uint32_t csPadSettingOverride; //!< [0x060-0x063] CS pad setting override value + uint32_t sclkPadSettingOverride; //!< [0x064-0x067] SCK pad setting override value + uint32_t dataPadSettingOverride; //!< [0x068-0x06b] data pad setting override value + uint32_t dqsPadSettingOverride; //!< [0x06c-0x06f] DQS pad setting override value + uint32_t timeoutInMs; //!< [0x070-0x073] Timeout threshold for read status command + uint32_t commandInterval; //!< [0x074-0x077] CS deselect interval between two commands + uint16_t dataValidTime[2]; //!< [0x078-0x07b] CLK edge to data valid time for PORT A and PORT B, in terms of 0.1ns + uint16_t busyOffset; //!< [0x07c-0x07d] Busy offset, valid value: 0-31 + uint16_t busyBitPolarity; //!< [0x07e-0x07f] Busy flag polarity, 0 - busy flag is 1 when flash device is busy, 1 - + //! busy flag is 0 when flash device is busy + uint32_t lookupTable[64]; //!< [0x080-0x17f] Lookup table holds Flash command sequences + flexspi_lut_seq_t lutCustomSeq[12]; //!< [0x180-0x1af] Customizable LUT Sequences + uint32_t reserved4[4]; //!< [0x1b0-0x1bf] Reserved for future use +} flexspi_mem_config_t; + +/* */ +#define NOR_CMD_INDEX_READ CMD_INDEX_READ //!< 0 +#define NOR_CMD_INDEX_READSTATUS CMD_INDEX_READSTATUS //!< 1 +#define NOR_CMD_INDEX_WRITEENABLE CMD_INDEX_WRITEENABLE //!< 2 +#define NOR_CMD_INDEX_ERASESECTOR 3 //!< 3 +#define NOR_CMD_INDEX_PAGEPROGRAM CMD_INDEX_WRITE //!< 4 +#define NOR_CMD_INDEX_CHIPERASE 5 //!< 5 +#define NOR_CMD_INDEX_DUMMY 6 //!< 6 +#define NOR_CMD_INDEX_ERASEBLOCK 7 //!< 7 + +#define NOR_CMD_LUT_SEQ_IDX_READ CMD_LUT_SEQ_IDX_READ //!< 0 READ LUT sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_READSTATUS \ + CMD_LUT_SEQ_IDX_READSTATUS //!< 1 Read Status LUT sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_READSTATUS_XPI \ + 2 //!< 2 Read status DPI/QPI/OPI sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_WRITEENABLE \ + CMD_LUT_SEQ_IDX_WRITEENABLE //!< 3 Write Enable sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_WRITEENABLE_XPI \ + 4 //!< 4 Write Enable DPI/QPI/OPI sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_ERASESECTOR 5 //!< 5 Erase Sector sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_ERASEBLOCK 8 //!< 8 Erase Block sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_PAGEPROGRAM \ + CMD_LUT_SEQ_IDX_WRITE //!< 9 Program sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_CHIPERASE 11 //!< 11 Chip Erase sequence in lookupTable id stored in config block +#define NOR_CMD_LUT_SEQ_IDX_READ_SFDP 13 //!< 13 Read SFDP sequence in lookupTable id stored in config block +#define NOR_CMD_LUT_SEQ_IDX_RESTORE_NOCMD \ + 14 //!< 14 Restore 0-4-4/0-8-8 mode sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_EXIT_NOCMD \ + 15 //!< 15 Exit 0-4-4/0-8-8 mode sequence id in lookupTable stored in config blobk + +/* + * Serial NOR configuration block + */ +typedef struct _flexspi_nor_config +{ + flexspi_mem_config_t memConfig; //!< Common memory configuration info via FlexSPI + uint32_t pageSize; //!< Page size of Serial NOR + uint32_t sectorSize; //!< Sector size of Serial NOR + uint8_t ipcmdSerialClkFreq; //!< Clock frequency for IP command + uint8_t isUniformBlockSize; //!< Sector/Block size is the same + uint8_t reserved0[2]; //!< Reserved for future use + uint8_t serialNorType; //!< Serial NOR Flash type: 0/1/2/3 + uint8_t needExitNoCmdMode; //!< Need to exit NoCmd mode before other IP command + uint8_t halfClkForNonReadCmd; //!< Half the Serial Clock for non-read command: true/false + uint8_t needRestoreNoCmdMode; //!< Need to Restore NoCmd mode after IP commmand execution + uint32_t blockSize; //!< Block size + uint32_t reserve2[11]; //!< Reserved for future use +} flexspi_nor_config_t; + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef __cplusplus +} +#endif +#endif /* __EVKMIMXRT1060_FLEXSPI_NOR_CONFIG__ */ diff --git a/hw/bsp/mimxrt1060_evk/mimxrt1060_evk.c b/hw/bsp/mimxrt1060_evk/mimxrt1060_evk.c new file mode 100644 index 00000000..a21dcdbf --- /dev/null +++ b/hw/bsp/mimxrt1060_evk/mimxrt1060_evk.c @@ -0,0 +1,184 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2018, hathach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#include "../board.h" +#include "fsl_device_registers.h" +#include "fsl_gpio.h" +#include "fsl_iomuxc.h" +#include "fsl_clock.h" +#include "fsl_lpuart.h" + +#include "clock_config.h" + +#define LED_PINMUX IOMUXC_GPIO_AD_B0_09_GPIO1_IO09 +#define LED_PORT GPIO1 +#define LED_PIN 9 +#define LED_STATE_ON 0 + +// SW8 button +#define BUTTON_PINMUX IOMUXC_SNVS_WAKEUP_GPIO5_IO00 +#define BUTTON_PORT GPIO5 +#define BUTTON_PIN 0 +#define BUTTON_STATE_ACTIVE 0 + +// UART +#define UART_PORT LPUART1 +#define UART_RX_PINMUX IOMUXC_GPIO_AD_B0_13_LPUART1_RX +#define UART_TX_PINMUX IOMUXC_GPIO_AD_B0_12_LPUART1_TX + +const uint8_t dcd_data[] = { 0x00 }; + +void board_init(void) +{ + // Init clock + BOARD_BootClockRUN(); + SystemCoreClockUpdate(); + + // Enable IOCON clock + CLOCK_EnableClock(kCLOCK_Iomuxc); + +#if CFG_TUSB_OS == OPT_OS_NONE + // 1ms tick timer + SysTick_Config(SystemCoreClock / 1000); +#elif CFG_TUSB_OS == OPT_OS_FREERTOS + // If freeRTOS is used, IRQ priority is limit by max syscall ( smaller is higher ) +// NVIC_SetPriority(USB0_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY ); +#endif + + // LED + IOMUXC_SetPinMux( LED_PINMUX, 0U); + IOMUXC_SetPinConfig( LED_PINMUX, 0x10B0U); + + gpio_pin_config_t led_config = { kGPIO_DigitalOutput, 0, kGPIO_NoIntmode }; + GPIO_PinInit(LED_PORT, LED_PIN, &led_config); + board_led_write(true); + + // Button + IOMUXC_SetPinMux( BUTTON_PINMUX, 0U); + gpio_pin_config_t button_config = { kGPIO_DigitalInput, 0, kGPIO_IntRisingEdge, }; + GPIO_PinInit(BUTTON_PORT, BUTTON_PIN, &button_config); + + // UART + IOMUXC_SetPinMux( UART_TX_PINMUX, 0U); + IOMUXC_SetPinMux( UART_RX_PINMUX, 0U); + IOMUXC_SetPinConfig( UART_TX_PINMUX, 0x10B0u); + IOMUXC_SetPinConfig( UART_RX_PINMUX, 0x10B0u); + + lpuart_config_t uart_config; + LPUART_GetDefaultConfig(&uart_config); + uart_config.baudRate_Bps = CFG_BOARD_UART_BAUDRATE; + uart_config.enableTx = true; + uart_config.enableRx = true; + LPUART_Init(UART_PORT, &uart_config, (CLOCK_GetPllFreq(kCLOCK_PllUsb1) / 6U) / (CLOCK_GetDiv(kCLOCK_UartDiv) + 1U)); + + //------------- USB0 -------------// + // Clock + CLOCK_EnableUsbhs0PhyPllClock(kCLOCK_Usbphy480M, 480000000U); + CLOCK_EnableUsbhs0Clock(kCLOCK_Usb480M, 480000000U); + + USBPHY_Type* usb_phy = USBPHY1; + + // Enable PHY support for Low speed device + LS via FS Hub + usb_phy->CTRL |= USBPHY_CTRL_SET_ENUTMILEVEL2_MASK | USBPHY_CTRL_SET_ENUTMILEVEL3_MASK; + + // Enable all power for normal operation + usb_phy->PWD = 0; + + // TX Timing + uint32_t phytx = usb_phy->TX; + phytx &= ~(USBPHY_TX_D_CAL_MASK | USBPHY_TX_TXCAL45DM_MASK | USBPHY_TX_TXCAL45DP_MASK); + phytx |= USBPHY_TX_D_CAL(0x0C) | USBPHY_TX_TXCAL45DP(0x06) | USBPHY_TX_TXCAL45DM(0x06); + usb_phy->TX = phytx; + + // USB1 +// CLOCK_EnableUsbhs1PhyPllClock(kCLOCK_Usbphy480M, 480000000U); +// CLOCK_EnableUsbhs1Clock(kCLOCK_Usb480M, 480000000U); +} + +//--------------------------------------------------------------------+ +// USB Interrupt Handler +//--------------------------------------------------------------------+ +void USB_OTG1_IRQHandler(void) +{ + #if CFG_TUSB_RHPORT0_MODE & OPT_MODE_HOST + tuh_isr(0); + #endif + + #if CFG_TUSB_RHPORT0_MODE & OPT_MODE_DEVICE + tud_isr(0); + #endif +} + +void USB_OTG2_IRQHandler(void) +{ + #if CFG_TUSB_RHPORT1_MODE & OPT_MODE_HOST + tuh_isr(1); + #endif + + #if CFG_TUSB_RHPORT1_MODE & OPT_MODE_DEVICE + tud_isr(1); + #endif +} + +//--------------------------------------------------------------------+ +// Board porting API +//--------------------------------------------------------------------+ + +void board_led_write(bool state) +{ + GPIO_PinWrite(LED_PORT, LED_PIN, state ? LED_STATE_ON : (1-LED_STATE_ON)); +} + +uint32_t board_button_read(void) +{ + // active low + return BUTTON_STATE_ACTIVE == GPIO_PinRead(BUTTON_PORT, BUTTON_PIN); +} + +int board_uart_read(uint8_t* buf, int len) +{ + LPUART_ReadBlocking(UART_PORT, buf, len); + return len; +} + +int board_uart_write(void const * buf, int len) +{ + LPUART_WriteBlocking(UART_PORT, (uint8_t*)buf, len); + return len; +} + +#if CFG_TUSB_OS == OPT_OS_NONE +volatile uint32_t system_ticks = 0; +void SysTick_Handler(void) +{ + system_ticks++; +} + +uint32_t board_millis(void) +{ + return system_ticks; +} +#endif From 38b14725f736c12be1d661dcd32dbb9b2e625a08 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 22 Nov 2019 17:40:12 +0700 Subject: [PATCH 080/267] rename OPT_MCU_IMXRT10XX to OPT_MCU_MIMXRT10XX --- examples/device/cdc_msc/src/tusb_config.h | 2 +- examples/device/cdc_msc_hid_freertos/src/tusb_config.h | 2 +- examples/device/dfu_rt/src/tusb_config.h | 2 +- examples/device/hid_composite/src/tusb_config.h | 2 +- examples/device/hid_generic_inout/src/tusb_config.h | 2 +- examples/device/midi_test/src/tusb_config.h | 2 +- examples/device/msc_dual_lun/src/tusb_config.h | 2 +- examples/device/usbtmc/src/tusb_config.h | 2 +- examples/device/webusb_serial/src/tusb_config.h | 2 +- examples/host/cdc_msc_hid/src/tusb_config.h | 2 +- hw/bsp/mimxrt1060_evk/board.mk | 2 +- hw/bsp/mimxrt1064_evk/board.mk | 2 +- src/portable/nxp/transdimension/dcd_transdimension.c | 4 ++-- src/tusb_option.h | 2 +- test/test/support/tusb_config.h | 2 +- 15 files changed, 16 insertions(+), 16 deletions(-) diff --git a/examples/device/cdc_msc/src/tusb_config.h b/examples/device/cdc_msc/src/tusb_config.h index 0210abda..5b7a1671 100644 --- a/examples/device/cdc_msc/src/tusb_config.h +++ b/examples/device/cdc_msc/src/tusb_config.h @@ -39,7 +39,7 @@ #error CFG_TUSB_MCU must be defined #endif -#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_IMXRT10XX +#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX #define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED) #else #define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE diff --git a/examples/device/cdc_msc_hid_freertos/src/tusb_config.h b/examples/device/cdc_msc_hid_freertos/src/tusb_config.h index 32c313f1..6788a748 100644 --- a/examples/device/cdc_msc_hid_freertos/src/tusb_config.h +++ b/examples/device/cdc_msc_hid_freertos/src/tusb_config.h @@ -39,7 +39,7 @@ #error CFG_TUSB_MCU must be defined #endif -#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_IMXRT10XX +#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX #define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED) #else #define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE diff --git a/examples/device/dfu_rt/src/tusb_config.h b/examples/device/dfu_rt/src/tusb_config.h index 0ba90226..27afdb6b 100644 --- a/examples/device/dfu_rt/src/tusb_config.h +++ b/examples/device/dfu_rt/src/tusb_config.h @@ -21,7 +21,7 @@ #error CFG_TUSB_MCU must be defined #endif -#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_IMXRT10XX +#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX #define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED) #else #define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE diff --git a/examples/device/hid_composite/src/tusb_config.h b/examples/device/hid_composite/src/tusb_config.h index 91dee441..dd360741 100644 --- a/examples/device/hid_composite/src/tusb_config.h +++ b/examples/device/hid_composite/src/tusb_config.h @@ -39,7 +39,7 @@ #error CFG_TUSB_MCU must be defined #endif -#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_IMXRT10XX +#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX #define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED) #else #define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE diff --git a/examples/device/hid_generic_inout/src/tusb_config.h b/examples/device/hid_generic_inout/src/tusb_config.h index 5950f1d9..0053a7d0 100644 --- a/examples/device/hid_generic_inout/src/tusb_config.h +++ b/examples/device/hid_generic_inout/src/tusb_config.h @@ -39,7 +39,7 @@ #error CFG_TUSB_MCU must be defined #endif -#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_IMXRT10XX +#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX #define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED) #else #define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE diff --git a/examples/device/midi_test/src/tusb_config.h b/examples/device/midi_test/src/tusb_config.h index 1d90a948..5837db4e 100644 --- a/examples/device/midi_test/src/tusb_config.h +++ b/examples/device/midi_test/src/tusb_config.h @@ -39,7 +39,7 @@ #error CFG_TUSB_MCU must be defined #endif -#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_IMXRT10XX +#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX #define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED) #else #define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE diff --git a/examples/device/msc_dual_lun/src/tusb_config.h b/examples/device/msc_dual_lun/src/tusb_config.h index 1025fa46..baf857b7 100644 --- a/examples/device/msc_dual_lun/src/tusb_config.h +++ b/examples/device/msc_dual_lun/src/tusb_config.h @@ -39,7 +39,7 @@ #error CFG_TUSB_MCU must be defined #endif -#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_IMXRT10XX +#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX #define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED) #else #define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE diff --git a/examples/device/usbtmc/src/tusb_config.h b/examples/device/usbtmc/src/tusb_config.h index a3c14d7d..2932ea4d 100644 --- a/examples/device/usbtmc/src/tusb_config.h +++ b/examples/device/usbtmc/src/tusb_config.h @@ -21,7 +21,7 @@ #error CFG_TUSB_MCU must be defined #endif -#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_IMXRT10XX +#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX #define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED) #else #define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE diff --git a/examples/device/webusb_serial/src/tusb_config.h b/examples/device/webusb_serial/src/tusb_config.h index 92b97400..30acdacc 100644 --- a/examples/device/webusb_serial/src/tusb_config.h +++ b/examples/device/webusb_serial/src/tusb_config.h @@ -39,7 +39,7 @@ #error CFG_TUSB_MCU must be defined #endif -#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_IMXRT10XX +#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX #define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED) #else #define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE diff --git a/examples/host/cdc_msc_hid/src/tusb_config.h b/examples/host/cdc_msc_hid/src/tusb_config.h index f8a6dc98..7c181810 100644 --- a/examples/host/cdc_msc_hid/src/tusb_config.h +++ b/examples/host/cdc_msc_hid/src/tusb_config.h @@ -40,7 +40,7 @@ #error CFG_TUSB_MCU must be defined #endif -#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_IMXRT10XX +#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX #define CFG_TUSB_RHPORT0_MODE (OPT_MODE_HOST | OPT_MODE_HIGH_SPEED) #else #define CFG_TUSB_RHPORT0_MODE OPT_MODE_HOST diff --git a/hw/bsp/mimxrt1060_evk/board.mk b/hw/bsp/mimxrt1060_evk/board.mk index e81e41c1..89f5a0f3 100644 --- a/hw/bsp/mimxrt1060_evk/board.mk +++ b/hw/bsp/mimxrt1060_evk/board.mk @@ -8,7 +8,7 @@ CFLAGS += \ -DCPU_MIMXRT1062DVL6A \ -DXIP_EXTERNAL_FLASH=1 \ -DXIP_BOOT_HEADER_ENABLE=1 \ - -DCFG_TUSB_MCU=OPT_MCU_IMXRT10XX \ + -DCFG_TUSB_MCU=OPT_MCU_MIMXRT10XX \ -DCFG_TUSB_MEM_SECTION='__attribute__((section(".data")))' \ -DCFG_TUSB_MEM_ALIGN='__attribute__((aligned(64)))' diff --git a/hw/bsp/mimxrt1064_evk/board.mk b/hw/bsp/mimxrt1064_evk/board.mk index 94011ec8..d991168e 100644 --- a/hw/bsp/mimxrt1064_evk/board.mk +++ b/hw/bsp/mimxrt1064_evk/board.mk @@ -8,7 +8,7 @@ CFLAGS += \ -DCPU_MIMXRT1064DVL6A \ -DXIP_EXTERNAL_FLASH=1 \ -DXIP_BOOT_HEADER_ENABLE=1 \ - -DCFG_TUSB_MCU=OPT_MCU_IMXRT10XX \ + -DCFG_TUSB_MCU=OPT_MCU_MIMXRT10XX \ -DCFG_TUSB_MEM_SECTION='__attribute__((section(".data")))' \ -DCFG_TUSB_MEM_ALIGN='__attribute__((aligned(64)))' diff --git a/src/portable/nxp/transdimension/dcd_transdimension.c b/src/portable/nxp/transdimension/dcd_transdimension.c index a17770ce..cc85bb62 100644 --- a/src/portable/nxp/transdimension/dcd_transdimension.c +++ b/src/portable/nxp/transdimension/dcd_transdimension.c @@ -28,7 +28,7 @@ #if TUSB_OPT_DEVICE_ENABLED && (CFG_TUSB_MCU == OPT_MCU_LPC18XX || \ CFG_TUSB_MCU == OPT_MCU_LPC43XX || \ - CFG_TUSB_MCU == OPT_MCU_IMXRT10XX) + CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX) //--------------------------------------------------------------------+ // INCLUDE @@ -36,7 +36,7 @@ #include "common/tusb_common.h" #include "device/dcd.h" -#if CFG_TUSB_MCU == OPT_MCU_IMXRT10XX +#if CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX #include "fsl_device_registers.h" #define DCD_REGS_BASE { (dcd_registers_t*) USB1_BASE, (dcd_registers_t*) USB2_BASE } IRQn_Type DCD_IRQn[] = { USB_OTG1_IRQn, USB_OTG2_IRQn }; diff --git a/src/tusb_option.h b/src/tusb_option.h index d7cbcb2d..ae8c02ee 100644 --- a/src/tusb_option.h +++ b/src/tusb_option.h @@ -72,7 +72,7 @@ #define OPT_MCU_VALENTYUSB_EPTRI 600 ///< Fomu eptri config -#define OPT_MCU_IMXRT10XX 700 ///< NXP iMX RT10xx +#define OPT_MCU_MIMXRT10XX 700 ///< NXP iMX RT10xx /** @} */ diff --git a/test/test/support/tusb_config.h b/test/test/support/tusb_config.h index 9ebd7e43..5e7b70e0 100644 --- a/test/test/support/tusb_config.h +++ b/test/test/support/tusb_config.h @@ -43,7 +43,7 @@ #define CFG_TUSB_MCU OPT_MCU_NRF5X #endif -#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_IMXRT10XX +#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX #define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED) #else #define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE From cc9b6b93c84f62c86e5436b3feb69ae472668bb8 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 22 Nov 2019 17:42:52 +0700 Subject: [PATCH 081/267] update doc for RT1060 evk --- README.md | 2 +- docs/boards.md | 3 ++- docs/porting.md | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 588526ff..469cb566 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ The stack supports the following MCUs - **Nordic:** nRF52840, nRF52833 - **NXP:** - LPC Series: 11Uxx, 13xx, 175x_6x, 177x_8x, 18xx, 40xx, 43xx, 51Uxx, 54xxx, 55xx - - iMX RT Series: RT1064 + - iMX RT Series: RT1060, RT1064 - **Sony:** CXD56 - **ST:** STM32 series: L0, F0, F1, F2, F3, F4, F7, H7 (device only) diff --git a/docs/boards.md b/docs/boards.md index caf4ef6f..d310b1c2 100644 --- a/docs/boards.md +++ b/docs/boards.md @@ -32,7 +32,8 @@ This code base already had supported for a handful of following boards ### NXP iMX RT -- [iMX RT1064 Evaluation Kit](https://www.nxp.com/design/development-boards/i.mx-evaluation-and-development-boards/mimxrt1064-evk-i.mx-rt1064-evaluation-kit:MIMXRT1064-EVK) +- [MIMX RT1064 Evaluation Kit](https://www.nxp.com/design/development-boards/i.mx-evaluation-and-development-boards/mimxrt1064-evk-i.mx-rt1064-evaluation-kit:MIMXRT1064-EVK) +- [MIMX RT1060 Evaluation Kit](https://www.nxp.com/design/development-boards/i.mx-evaluation-and-development-boards/mimxrt1060-evk-i.mx-rt1060-evaluation-kit:MIMXRT1060-EVK) ### NXP LPC diff --git a/docs/porting.md b/docs/porting.md index 7ed21d75..deb1b9ef 100644 --- a/docs/porting.md +++ b/docs/porting.md @@ -1,6 +1,6 @@ # Porting -TinyUSB is designed to be a universal USB protocol stack for low-cost 32 bit microcontrollers. It +TinyUSB is designed to be a universal USB protocol stack for microcontrollers. It handles most of the high level USB protocol and relies on the microcontroller's USB peripheral for data transactions on different endpoints. Porting is the process of adding low-level support for the rest of the common stack. Once the low-level is implemented, it is very easy to add USB support From 4ecb07afc5012cbc93664cc1a57b15e2fe0aff20 Mon Sep 17 00:00:00 2001 From: hathach Date: Sat, 23 Nov 2019 00:19:53 +0700 Subject: [PATCH 082/267] added MIMX RT1052 Evaluation Kit --- README.md | 4 +- docs/boards.md | 11 +- hw/bsp/mimxrt1050_evkb/board.h | 34 +++ hw/bsp/mimxrt1050_evkb/board.mk | 55 ++++ .../evkbimxrt1050_flexspi_nor_config.c | 55 ++++ .../evkbimxrt1050_flexspi_nor_config.h | 269 ++++++++++++++++++ hw/bsp/mimxrt1050_evkb/mimxrt1050_evkb.c | 184 ++++++++++++ hw/bsp/mimxrt1060_evk/board.mk | 5 +- hw/bsp/mimxrt1064_evk/board.mk | 5 +- 9 files changed, 607 insertions(+), 15 deletions(-) create mode 100644 hw/bsp/mimxrt1050_evkb/board.h create mode 100644 hw/bsp/mimxrt1050_evkb/board.mk create mode 100644 hw/bsp/mimxrt1050_evkb/evkbimxrt1050_flexspi_nor_config.c create mode 100644 hw/bsp/mimxrt1050_evkb/evkbimxrt1050_flexspi_nor_config.h create mode 100644 hw/bsp/mimxrt1050_evkb/mimxrt1050_evkb.c diff --git a/README.md b/README.md index 469cb566..3401dc90 100644 --- a/README.md +++ b/README.md @@ -25,14 +25,14 @@ TinyUSB is an open-source cross-platform USB Host/Device stack for embedded syst The stack supports the following MCUs -- **Tomu:** [valentyusb](https://github.com/im-tomu/valentyusb) (eptri) - **MicroChip:** SAMD21, SAMD51 (device only) - **Nordic:** nRF52840, nRF52833 - **NXP:** - LPC Series: 11Uxx, 13xx, 175x_6x, 177x_8x, 18xx, 40xx, 43xx, 51Uxx, 54xxx, 55xx - - iMX RT Series: RT1060, RT1064 + - iMX RT Series: RT1052, RT1062, RT1064 - **Sony:** CXD56 - **ST:** STM32 series: L0, F0, F1, F2, F3, F4, F7, H7 (device only) +- **Tomu:** [valentyusb](https://github.com/im-tomu/valentyusb) (eptri) [Here is the list of supported Boards](docs/boards.md) that can be used with provided examples. diff --git a/docs/boards.md b/docs/boards.md index d310b1c2..de1e6bbd 100644 --- a/docs/boards.md +++ b/docs/boards.md @@ -9,10 +9,6 @@ The board support code is only used for self-contained examples and testing. It This code base already had supported for a handful of following boards -## Tomu - -- [Fomu](https://www.crowdsupply.com/sutajio-kosagi/fomu) - ### MicroChip SAMD - [Adafruit Circuit Playground Express](https://www.adafruit.com/product/3333) @@ -32,8 +28,9 @@ This code base already had supported for a handful of following boards ### NXP iMX RT -- [MIMX RT1064 Evaluation Kit](https://www.nxp.com/design/development-boards/i.mx-evaluation-and-development-boards/mimxrt1064-evk-i.mx-rt1064-evaluation-kit:MIMXRT1064-EVK) +- [MIMX RT1052 Evaluation Kit](https://www.nxp.com/design/development-boards/i.mx-evaluation-and-development-boards/i.mx-rt1050-evaluation-kit:MIMXRT1050-EVK) - [MIMX RT1060 Evaluation Kit](https://www.nxp.com/design/development-boards/i.mx-evaluation-and-development-boards/mimxrt1060-evk-i.mx-rt1060-evaluation-kit:MIMXRT1060-EVK) +- [MIMX RT1064 Evaluation Kit](https://www.nxp.com/design/development-boards/i.mx-evaluation-and-development-boards/mimxrt1064-evk-i.mx-rt1064-evaluation-kit:MIMXRT1064-EVK) ### NXP LPC @@ -70,6 +67,10 @@ This code base already had supported for a handful of following boards - [STM32 F767zi Nucleo](https://www.st.com/en/evaluation-tools/nucleo-f767zi.html) - [STM32 H743zi Nucleo](https://www.st.com/en/evaluation-tools/nucleo-h743zi.html) +### Tomu + +- [Fomu](https://www.crowdsupply.com/sutajio-kosagi/fomu) + ## Add your own board If you don't possess any of supported board above. Don't worry you can easily implemented your own one by following this guide as long as the mcu is supported. diff --git a/hw/bsp/mimxrt1050_evkb/board.h b/hw/bsp/mimxrt1050_evkb/board.h new file mode 100644 index 00000000..3f660ac7 --- /dev/null +++ b/hw/bsp/mimxrt1050_evkb/board.h @@ -0,0 +1,34 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019, Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + + +#ifndef BOARD_H_ +#define BOARD_H_ + +// required since iMX RT10xx SDK include this file for board size +#define BOARD_FLASH_SIZE (0x4000000U) + +#endif /* BOARD_H_ */ diff --git a/hw/bsp/mimxrt1050_evkb/board.mk b/hw/bsp/mimxrt1050_evkb/board.mk new file mode 100644 index 00000000..b455b060 --- /dev/null +++ b/hw/bsp/mimxrt1050_evkb/board.mk @@ -0,0 +1,55 @@ +CFLAGS += \ + -mthumb \ + -mabi=aapcs \ + -mcpu=cortex-m7 \ + -mfloat-abi=hard \ + -mfpu=fpv5-d16 \ + -D__ARMVFP__=0 -D__ARMFPV5__=0\ + -DCPU_MIMXRT1052DVL6B \ + -DXIP_EXTERNAL_FLASH=1 \ + -DXIP_BOOT_HEADER_ENABLE=1 \ + -DCFG_TUSB_MCU=OPT_MCU_MIMXRT10XX \ + -DCFG_TUSB_MEM_SECTION='__attribute__((section(".data")))' \ + -DCFG_TUSB_MEM_ALIGN='__attribute__((aligned(64)))' + +# mcu driver cause following warnings +#CFLAGS += -Wno-error=float-equal -Wno-error=nested-externs +CFLAGS += -Wno-error=unused-parameter + +MCU_DIR = hw/mcu/nxp/sdk/devices/MIMXRT1052 + +# All source paths should be relative to the top level. +LD_FILE = $(MCU_DIR)/gcc/MIMXRT1052xxxxx_flexspi_nor.ld + +SRC_C += \ + $(MCU_DIR)/system_MIMXRT1052.c \ + $(MCU_DIR)/xip/fsl_flexspi_nor_boot.c \ + $(MCU_DIR)/project_template/clock_config.c \ + $(MCU_DIR)/drivers/fsl_clock.c \ + $(MCU_DIR)/drivers/fsl_gpio.c \ + $(MCU_DIR)/drivers/fsl_common.c \ + $(MCU_DIR)/drivers/fsl_lpuart.c + +INC += \ + $(TOP)/hw/bsp/$(BOARD) \ + $(TOP)/$(MCU_DIR)/../../CMSIS/Include \ + $(TOP)/$(MCU_DIR) \ + $(TOP)/$(MCU_DIR)/drivers \ + $(TOP)/$(MCU_DIR)/project_template \ + +SRC_S += $(MCU_DIR)/gcc/startup_MIMXRT1052.S + +# For TinyUSB port source +VENDOR = nxp +CHIP_FAMILY = transdimension + +# For freeRTOS port source +FREERTOS_PORT = ARM_CM7 + +# For flash-jlink target +JLINK_DEVICE = MIMXRT1052xxx6B +JLINK_IF = swd + +# flash by copying bin file to DAP Mass Storage +flash: $(BUILD)/$(BOARD)-firmware.bin + cp $< /media/$(USER)/RT1050-EVK/ diff --git a/hw/bsp/mimxrt1050_evkb/evkbimxrt1050_flexspi_nor_config.c b/hw/bsp/mimxrt1050_evkb/evkbimxrt1050_flexspi_nor_config.c new file mode 100644 index 00000000..af6eabc8 --- /dev/null +++ b/hw/bsp/mimxrt1050_evkb/evkbimxrt1050_flexspi_nor_config.c @@ -0,0 +1,55 @@ +/* + * Copyright 2017 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include "evkbimxrt1050_flexspi_nor_config.h" + +/* Component ID definition, used by tools. */ +#ifndef FSL_COMPONENT_ID +#define FSL_COMPONENT_ID "platform.drivers.xip_board" +#endif + +/******************************************************************************* + * Code + ******************************************************************************/ +#if defined(XIP_BOOT_HEADER_ENABLE) && (XIP_BOOT_HEADER_ENABLE == 1) +#if defined(__CC_ARM) || defined(__ARMCC_VERSION) || defined(__GNUC__) +__attribute__((section(".boot_hdr.conf"))) +#elif defined(__ICCARM__) +#pragma location = ".boot_hdr.conf" +#endif + +const flexspi_nor_config_t hyperflash_config = { + .memConfig = + { + .tag = FLEXSPI_CFG_BLK_TAG, + .version = FLEXSPI_CFG_BLK_VERSION, + .readSampleClkSrc = kFlexSPIReadSampleClk_ExternalInputFromDqsPad, + .csHoldTime = 3u, + .csSetupTime = 3u, + .columnAddressWidth = 3u, + // Enable DDR mode, Wordaddassable, Safe configuration, Differential clock + .controllerMiscOption = + (1u << kFlexSpiMiscOffset_DdrModeEnable) | (1u << kFlexSpiMiscOffset_WordAddressableEnable) | + (1u << kFlexSpiMiscOffset_SafeConfigFreqEnable) | (1u << kFlexSpiMiscOffset_DiffClkEnable), + .sflashPadType = kSerialFlash_8Pads, + .serialClkFreq = kFlexSpiSerialClk_133MHz, + .sflashA1Size = 64u * 1024u * 1024u, + .dataValidTime = {16u, 16u}, + .lookupTable = + { + // Read LUTs + FLEXSPI_LUT_SEQ(CMD_DDR, FLEXSPI_8PAD, 0xA0, RADDR_DDR, FLEXSPI_8PAD, 0x18), + FLEXSPI_LUT_SEQ(CADDR_DDR, FLEXSPI_8PAD, 0x10, DUMMY_DDR, FLEXSPI_8PAD, 0x06), + FLEXSPI_LUT_SEQ(READ_DDR, FLEXSPI_8PAD, 0x04, STOP, FLEXSPI_1PAD, 0x0), + }, + }, + .pageSize = 512u, + .sectorSize = 256u * 1024u, + .blockSize = 256u * 1024u, + .isUniformBlockSize = true, +}; +#endif /* XIP_BOOT_HEADER_ENABLE */ diff --git a/hw/bsp/mimxrt1050_evkb/evkbimxrt1050_flexspi_nor_config.h b/hw/bsp/mimxrt1050_evkb/evkbimxrt1050_flexspi_nor_config.h new file mode 100644 index 00000000..fe40e7ed --- /dev/null +++ b/hw/bsp/mimxrt1050_evkb/evkbimxrt1050_flexspi_nor_config.h @@ -0,0 +1,269 @@ +/* + * Copyright (c) 2016, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef __EVKBIMXRT1050_FLEXSPI_NOR_CONFIG__ +#define __EVKBIMXRT1050_FLEXSPI_NOR_CONFIG__ + +#include +#include +#include "fsl_common.h" + +/*! @name Driver version */ +/*@{*/ +/*! @brief XIP_BOARD driver version 2.0.0. */ +#define FSL_XIP_BOARD_DRIVER_VERSION (MAKE_VERSION(2, 0, 0)) +/*@}*/ + +/* FLEXSPI memory config block related defintions */ +#define FLEXSPI_CFG_BLK_TAG (0x42464346UL) // ascii "FCFB" Big Endian +#define FLEXSPI_CFG_BLK_VERSION (0x56010400UL) // V1.4.0 +#define FLEXSPI_CFG_BLK_SIZE (512) + +/* FLEXSPI Feature related definitions */ +#define FLEXSPI_FEATURE_HAS_PARALLEL_MODE 1 + +/* Lookup table related defintions */ +#define CMD_INDEX_READ 0 +#define CMD_INDEX_READSTATUS 1 +#define CMD_INDEX_WRITEENABLE 2 +#define CMD_INDEX_WRITE 4 + +#define CMD_LUT_SEQ_IDX_READ 0 +#define CMD_LUT_SEQ_IDX_READSTATUS 1 +#define CMD_LUT_SEQ_IDX_WRITEENABLE 3 +#define CMD_LUT_SEQ_IDX_WRITE 9 + +#define CMD_SDR 0x01 +#define CMD_DDR 0x21 +#define RADDR_SDR 0x02 +#define RADDR_DDR 0x22 +#define CADDR_SDR 0x03 +#define CADDR_DDR 0x23 +#define MODE1_SDR 0x04 +#define MODE1_DDR 0x24 +#define MODE2_SDR 0x05 +#define MODE2_DDR 0x25 +#define MODE4_SDR 0x06 +#define MODE4_DDR 0x26 +#define MODE8_SDR 0x07 +#define MODE8_DDR 0x27 +#define WRITE_SDR 0x08 +#define WRITE_DDR 0x28 +#define READ_SDR 0x09 +#define READ_DDR 0x29 +#define LEARN_SDR 0x0A +#define LEARN_DDR 0x2A +#define DATSZ_SDR 0x0B +#define DATSZ_DDR 0x2B +#define DUMMY_SDR 0x0C +#define DUMMY_DDR 0x2C +#define DUMMY_RWDS_SDR 0x0D +#define DUMMY_RWDS_DDR 0x2D +#define JMP_ON_CS 0x1F +#define STOP 0 + +#define FLEXSPI_1PAD 0 +#define FLEXSPI_2PAD 1 +#define FLEXSPI_4PAD 2 +#define FLEXSPI_8PAD 3 + +#define FLEXSPI_LUT_SEQ(cmd0, pad0, op0, cmd1, pad1, op1) \ + (FLEXSPI_LUT_OPERAND0(op0) | FLEXSPI_LUT_NUM_PADS0(pad0) | FLEXSPI_LUT_OPCODE0(cmd0) | FLEXSPI_LUT_OPERAND1(op1) | \ + FLEXSPI_LUT_NUM_PADS1(pad1) | FLEXSPI_LUT_OPCODE1(cmd1)) + +//!@brief Definitions for FlexSPI Serial Clock Frequency +typedef enum _FlexSpiSerialClockFreq +{ + kFlexSpiSerialClk_30MHz = 1, + kFlexSpiSerialClk_50MHz = 2, + kFlexSpiSerialClk_60MHz = 3, + kFlexSpiSerialClk_75MHz = 4, + kFlexSpiSerialClk_80MHz = 5, + kFlexSpiSerialClk_100MHz = 6, + kFlexSpiSerialClk_133MHz = 7, + kFlexSpiSerialClk_166MHz = 8, + kFlexSpiSerialClk_200MHz = 9, +} flexspi_serial_clk_freq_t; + +//!@brief FlexSPI clock configuration type +enum +{ + kFlexSpiClk_SDR, //!< Clock configure for SDR mode + kFlexSpiClk_DDR, //!< Clock configurat for DDR mode +}; + +//!@brief FlexSPI Read Sample Clock Source definition +typedef enum _FlashReadSampleClkSource +{ + kFlexSPIReadSampleClk_LoopbackInternally = 0, + kFlexSPIReadSampleClk_LoopbackFromDqsPad = 1, + kFlexSPIReadSampleClk_LoopbackFromSckPad = 2, + kFlexSPIReadSampleClk_ExternalInputFromDqsPad = 3, +} flexspi_read_sample_clk_t; + +//!@brief Misc feature bit definitions +enum +{ + kFlexSpiMiscOffset_DiffClkEnable = 0, //!< Bit for Differential clock enable + kFlexSpiMiscOffset_Ck2Enable = 1, //!< Bit for CK2 enable + kFlexSpiMiscOffset_ParallelEnable = 2, //!< Bit for Parallel mode enable + kFlexSpiMiscOffset_WordAddressableEnable = 3, //!< Bit for Word Addressable enable + kFlexSpiMiscOffset_SafeConfigFreqEnable = 4, //!< Bit for Safe Configuration Frequency enable + kFlexSpiMiscOffset_PadSettingOverrideEnable = 5, //!< Bit for Pad setting override enable + kFlexSpiMiscOffset_DdrModeEnable = 6, //!< Bit for DDR clock confiuration indication. +}; + +//!@brief Flash Type Definition +enum +{ + kFlexSpiDeviceType_SerialNOR = 1, //!< Flash devices are Serial NOR + kFlexSpiDeviceType_SerialNAND = 2, //!< Flash devices are Serial NAND + kFlexSpiDeviceType_SerialRAM = 3, //!< Flash devices are Serial RAM/HyperFLASH + kFlexSpiDeviceType_MCP_NOR_NAND = 0x12, //!< Flash device is MCP device, A1 is Serial NOR, A2 is Serial NAND + kFlexSpiDeviceType_MCP_NOR_RAM = 0x13, //!< Flash deivce is MCP device, A1 is Serial NOR, A2 is Serial RAMs +}; + +//!@brief Flash Pad Definitions +enum +{ + kSerialFlash_1Pad = 1, + kSerialFlash_2Pads = 2, + kSerialFlash_4Pads = 4, + kSerialFlash_8Pads = 8, +}; + +//!@brief FlexSPI LUT Sequence structure +typedef struct _lut_sequence +{ + uint8_t seqNum; //!< Sequence Number, valid number: 1-16 + uint8_t seqId; //!< Sequence Index, valid number: 0-15 + uint16_t reserved; +} flexspi_lut_seq_t; + +//!@brief Flash Configuration Command Type +enum +{ + kDeviceConfigCmdType_Generic, //!< Generic command, for example: configure dummy cycles, drive strength, etc + kDeviceConfigCmdType_QuadEnable, //!< Quad Enable command + kDeviceConfigCmdType_Spi2Xpi, //!< Switch from SPI to DPI/QPI/OPI mode + kDeviceConfigCmdType_Xpi2Spi, //!< Switch from DPI/QPI/OPI to SPI mode + kDeviceConfigCmdType_Spi2NoCmd, //!< Switch to 0-4-4/0-8-8 mode + kDeviceConfigCmdType_Reset, //!< Reset device command +}; + +//!@brief FlexSPI Memory Configuration Block +typedef struct _FlexSPIConfig +{ + uint32_t tag; //!< [0x000-0x003] Tag, fixed value 0x42464346UL + uint32_t version; //!< [0x004-0x007] Version,[31:24] -'V', [23:16] - Major, [15:8] - Minor, [7:0] - bugfix + uint32_t reserved0; //!< [0x008-0x00b] Reserved for future use + uint8_t readSampleClkSrc; //!< [0x00c-0x00c] Read Sample Clock Source, valid value: 0/1/3 + uint8_t csHoldTime; //!< [0x00d-0x00d] CS hold time, default value: 3 + uint8_t csSetupTime; //!< [0x00e-0x00e] CS setup time, default value: 3 + uint8_t columnAddressWidth; //!< [0x00f-0x00f] Column Address with, for HyperBus protocol, it is fixed to 3, For + //! Serial NAND, need to refer to datasheet + uint8_t deviceModeCfgEnable; //!< [0x010-0x010] Device Mode Configure enable flag, 1 - Enable, 0 - Disable + uint8_t deviceModeType; //!< [0x011-0x011] Specify the configuration command type:Quad Enable, DPI/QPI/OPI switch, + //! Generic configuration, etc. + uint16_t waitTimeCfgCommands; //!< [0x012-0x013] Wait time for all configuration commands, unit: 100us, Used for + //! DPI/QPI/OPI switch or reset command + flexspi_lut_seq_t deviceModeSeq; //!< [0x014-0x017] Device mode sequence info, [7:0] - LUT sequence id, [15:8] - LUt + //! sequence number, [31:16] Reserved + uint32_t deviceModeArg; //!< [0x018-0x01b] Argument/Parameter for device configuration + uint8_t configCmdEnable; //!< [0x01c-0x01c] Configure command Enable Flag, 1 - Enable, 0 - Disable + uint8_t configModeType[3]; //!< [0x01d-0x01f] Configure Mode Type, similar as deviceModeTpe + flexspi_lut_seq_t + configCmdSeqs[3]; //!< [0x020-0x02b] Sequence info for Device Configuration command, similar as deviceModeSeq + uint32_t reserved1; //!< [0x02c-0x02f] Reserved for future use + uint32_t configCmdArgs[3]; //!< [0x030-0x03b] Arguments/Parameters for device Configuration commands + uint32_t reserved2; //!< [0x03c-0x03f] Reserved for future use + uint32_t controllerMiscOption; //!< [0x040-0x043] Controller Misc Options, see Misc feature bit definitions for more + //! details + uint8_t deviceType; //!< [0x044-0x044] Device Type: See Flash Type Definition for more details + uint8_t sflashPadType; //!< [0x045-0x045] Serial Flash Pad Type: 1 - Single, 2 - Dual, 4 - Quad, 8 - Octal + uint8_t serialClkFreq; //!< [0x046-0x046] Serial Flash Frequencey, device specific definitions, See System Boot + //! Chapter for more details + uint8_t lutCustomSeqEnable; //!< [0x047-0x047] LUT customization Enable, it is required if the program/erase cannot + //! be done using 1 LUT sequence, currently, only applicable to HyperFLASH + uint32_t reserved3[2]; //!< [0x048-0x04f] Reserved for future use + uint32_t sflashA1Size; //!< [0x050-0x053] Size of Flash connected to A1 + uint32_t sflashA2Size; //!< [0x054-0x057] Size of Flash connected to A2 + uint32_t sflashB1Size; //!< [0x058-0x05b] Size of Flash connected to B1 + uint32_t sflashB2Size; //!< [0x05c-0x05f] Size of Flash connected to B2 + uint32_t csPadSettingOverride; //!< [0x060-0x063] CS pad setting override value + uint32_t sclkPadSettingOverride; //!< [0x064-0x067] SCK pad setting override value + uint32_t dataPadSettingOverride; //!< [0x068-0x06b] data pad setting override value + uint32_t dqsPadSettingOverride; //!< [0x06c-0x06f] DQS pad setting override value + uint32_t timeoutInMs; //!< [0x070-0x073] Timeout threshold for read status command + uint32_t commandInterval; //!< [0x074-0x077] CS deselect interval between two commands + uint16_t dataValidTime[2]; //!< [0x078-0x07b] CLK edge to data valid time for PORT A and PORT B, in terms of 0.1ns + uint16_t busyOffset; //!< [0x07c-0x07d] Busy offset, valid value: 0-31 + uint16_t busyBitPolarity; //!< [0x07e-0x07f] Busy flag polarity, 0 - busy flag is 1 when flash device is busy, 1 - + //! busy flag is 0 when flash device is busy + uint32_t lookupTable[64]; //!< [0x080-0x17f] Lookup table holds Flash command sequences + flexspi_lut_seq_t lutCustomSeq[12]; //!< [0x180-0x1af] Customizable LUT Sequences + uint32_t reserved4[4]; //!< [0x1b0-0x1bf] Reserved for future use +} flexspi_mem_config_t; + +/* */ +#define NOR_CMD_INDEX_READ CMD_INDEX_READ //!< 0 +#define NOR_CMD_INDEX_READSTATUS CMD_INDEX_READSTATUS //!< 1 +#define NOR_CMD_INDEX_WRITEENABLE CMD_INDEX_WRITEENABLE //!< 2 +#define NOR_CMD_INDEX_ERASESECTOR 3 //!< 3 +#define NOR_CMD_INDEX_PAGEPROGRAM CMD_INDEX_WRITE //!< 4 +#define NOR_CMD_INDEX_CHIPERASE 5 //!< 5 +#define NOR_CMD_INDEX_DUMMY 6 //!< 6 +#define NOR_CMD_INDEX_ERASEBLOCK 7 //!< 7 + +#define NOR_CMD_LUT_SEQ_IDX_READ CMD_LUT_SEQ_IDX_READ //!< 0 READ LUT sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_READSTATUS \ + CMD_LUT_SEQ_IDX_READSTATUS //!< 1 Read Status LUT sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_READSTATUS_XPI \ + 2 //!< 2 Read status DPI/QPI/OPI sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_WRITEENABLE \ + CMD_LUT_SEQ_IDX_WRITEENABLE //!< 3 Write Enable sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_WRITEENABLE_XPI \ + 4 //!< 4 Write Enable DPI/QPI/OPI sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_ERASESECTOR 5 //!< 5 Erase Sector sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_ERASEBLOCK 8 //!< 8 Erase Block sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_PAGEPROGRAM \ + CMD_LUT_SEQ_IDX_WRITE //!< 9 Program sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_CHIPERASE 11 //!< 11 Chip Erase sequence in lookupTable id stored in config block +#define NOR_CMD_LUT_SEQ_IDX_READ_SFDP 13 //!< 13 Read SFDP sequence in lookupTable id stored in config block +#define NOR_CMD_LUT_SEQ_IDX_RESTORE_NOCMD \ + 14 //!< 14 Restore 0-4-4/0-8-8 mode sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_EXIT_NOCMD \ + 15 //!< 15 Exit 0-4-4/0-8-8 mode sequence id in lookupTable stored in config blobk + +/* + * Serial NOR configuration block + */ +typedef struct _flexspi_nor_config +{ + flexspi_mem_config_t memConfig; //!< Common memory configuration info via FlexSPI + uint32_t pageSize; //!< Page size of Serial NOR + uint32_t sectorSize; //!< Sector size of Serial NOR + uint8_t ipcmdSerialClkFreq; //!< Clock frequency for IP command + uint8_t isUniformBlockSize; //!< Sector/Block size is the same + uint8_t reserved0[2]; //!< Reserved for future use + uint8_t serialNorType; //!< Serial NOR Flash type: 0/1/2/3 + uint8_t needExitNoCmdMode; //!< Need to exit NoCmd mode before other IP command + uint8_t halfClkForNonReadCmd; //!< Half the Serial Clock for non-read command: true/false + uint8_t needRestoreNoCmdMode; //!< Need to Restore NoCmd mode after IP commmand execution + uint32_t blockSize; //!< Block size + uint32_t reserve2[11]; //!< Reserved for future use +} flexspi_nor_config_t; + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef __cplusplus +} +#endif +#endif /* __EVKBIMXRT1050_FLEXSPI_NOR_CONFIG__ */ diff --git a/hw/bsp/mimxrt1050_evkb/mimxrt1050_evkb.c b/hw/bsp/mimxrt1050_evkb/mimxrt1050_evkb.c new file mode 100644 index 00000000..a21dcdbf --- /dev/null +++ b/hw/bsp/mimxrt1050_evkb/mimxrt1050_evkb.c @@ -0,0 +1,184 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2018, hathach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#include "../board.h" +#include "fsl_device_registers.h" +#include "fsl_gpio.h" +#include "fsl_iomuxc.h" +#include "fsl_clock.h" +#include "fsl_lpuart.h" + +#include "clock_config.h" + +#define LED_PINMUX IOMUXC_GPIO_AD_B0_09_GPIO1_IO09 +#define LED_PORT GPIO1 +#define LED_PIN 9 +#define LED_STATE_ON 0 + +// SW8 button +#define BUTTON_PINMUX IOMUXC_SNVS_WAKEUP_GPIO5_IO00 +#define BUTTON_PORT GPIO5 +#define BUTTON_PIN 0 +#define BUTTON_STATE_ACTIVE 0 + +// UART +#define UART_PORT LPUART1 +#define UART_RX_PINMUX IOMUXC_GPIO_AD_B0_13_LPUART1_RX +#define UART_TX_PINMUX IOMUXC_GPIO_AD_B0_12_LPUART1_TX + +const uint8_t dcd_data[] = { 0x00 }; + +void board_init(void) +{ + // Init clock + BOARD_BootClockRUN(); + SystemCoreClockUpdate(); + + // Enable IOCON clock + CLOCK_EnableClock(kCLOCK_Iomuxc); + +#if CFG_TUSB_OS == OPT_OS_NONE + // 1ms tick timer + SysTick_Config(SystemCoreClock / 1000); +#elif CFG_TUSB_OS == OPT_OS_FREERTOS + // If freeRTOS is used, IRQ priority is limit by max syscall ( smaller is higher ) +// NVIC_SetPriority(USB0_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY ); +#endif + + // LED + IOMUXC_SetPinMux( LED_PINMUX, 0U); + IOMUXC_SetPinConfig( LED_PINMUX, 0x10B0U); + + gpio_pin_config_t led_config = { kGPIO_DigitalOutput, 0, kGPIO_NoIntmode }; + GPIO_PinInit(LED_PORT, LED_PIN, &led_config); + board_led_write(true); + + // Button + IOMUXC_SetPinMux( BUTTON_PINMUX, 0U); + gpio_pin_config_t button_config = { kGPIO_DigitalInput, 0, kGPIO_IntRisingEdge, }; + GPIO_PinInit(BUTTON_PORT, BUTTON_PIN, &button_config); + + // UART + IOMUXC_SetPinMux( UART_TX_PINMUX, 0U); + IOMUXC_SetPinMux( UART_RX_PINMUX, 0U); + IOMUXC_SetPinConfig( UART_TX_PINMUX, 0x10B0u); + IOMUXC_SetPinConfig( UART_RX_PINMUX, 0x10B0u); + + lpuart_config_t uart_config; + LPUART_GetDefaultConfig(&uart_config); + uart_config.baudRate_Bps = CFG_BOARD_UART_BAUDRATE; + uart_config.enableTx = true; + uart_config.enableRx = true; + LPUART_Init(UART_PORT, &uart_config, (CLOCK_GetPllFreq(kCLOCK_PllUsb1) / 6U) / (CLOCK_GetDiv(kCLOCK_UartDiv) + 1U)); + + //------------- USB0 -------------// + // Clock + CLOCK_EnableUsbhs0PhyPllClock(kCLOCK_Usbphy480M, 480000000U); + CLOCK_EnableUsbhs0Clock(kCLOCK_Usb480M, 480000000U); + + USBPHY_Type* usb_phy = USBPHY1; + + // Enable PHY support for Low speed device + LS via FS Hub + usb_phy->CTRL |= USBPHY_CTRL_SET_ENUTMILEVEL2_MASK | USBPHY_CTRL_SET_ENUTMILEVEL3_MASK; + + // Enable all power for normal operation + usb_phy->PWD = 0; + + // TX Timing + uint32_t phytx = usb_phy->TX; + phytx &= ~(USBPHY_TX_D_CAL_MASK | USBPHY_TX_TXCAL45DM_MASK | USBPHY_TX_TXCAL45DP_MASK); + phytx |= USBPHY_TX_D_CAL(0x0C) | USBPHY_TX_TXCAL45DP(0x06) | USBPHY_TX_TXCAL45DM(0x06); + usb_phy->TX = phytx; + + // USB1 +// CLOCK_EnableUsbhs1PhyPllClock(kCLOCK_Usbphy480M, 480000000U); +// CLOCK_EnableUsbhs1Clock(kCLOCK_Usb480M, 480000000U); +} + +//--------------------------------------------------------------------+ +// USB Interrupt Handler +//--------------------------------------------------------------------+ +void USB_OTG1_IRQHandler(void) +{ + #if CFG_TUSB_RHPORT0_MODE & OPT_MODE_HOST + tuh_isr(0); + #endif + + #if CFG_TUSB_RHPORT0_MODE & OPT_MODE_DEVICE + tud_isr(0); + #endif +} + +void USB_OTG2_IRQHandler(void) +{ + #if CFG_TUSB_RHPORT1_MODE & OPT_MODE_HOST + tuh_isr(1); + #endif + + #if CFG_TUSB_RHPORT1_MODE & OPT_MODE_DEVICE + tud_isr(1); + #endif +} + +//--------------------------------------------------------------------+ +// Board porting API +//--------------------------------------------------------------------+ + +void board_led_write(bool state) +{ + GPIO_PinWrite(LED_PORT, LED_PIN, state ? LED_STATE_ON : (1-LED_STATE_ON)); +} + +uint32_t board_button_read(void) +{ + // active low + return BUTTON_STATE_ACTIVE == GPIO_PinRead(BUTTON_PORT, BUTTON_PIN); +} + +int board_uart_read(uint8_t* buf, int len) +{ + LPUART_ReadBlocking(UART_PORT, buf, len); + return len; +} + +int board_uart_write(void const * buf, int len) +{ + LPUART_WriteBlocking(UART_PORT, (uint8_t*)buf, len); + return len; +} + +#if CFG_TUSB_OS == OPT_OS_NONE +volatile uint32_t system_ticks = 0; +void SysTick_Handler(void) +{ + system_ticks++; +} + +uint32_t board_millis(void) +{ + return system_ticks; +} +#endif diff --git a/hw/bsp/mimxrt1060_evk/board.mk b/hw/bsp/mimxrt1060_evk/board.mk index 89f5a0f3..d42da8cb 100644 --- a/hw/bsp/mimxrt1060_evk/board.mk +++ b/hw/bsp/mimxrt1060_evk/board.mk @@ -50,9 +50,6 @@ FREERTOS_PORT = ARM_CM7 JLINK_DEVICE = MIMXRT1062xxx6A JLINK_IF = swd -# flash using pyocd -#flash: $(BUILD)/$(BOARD)-firmware.hex -# pyocd flash -t mimxrt1050_quadspi $< - +# flash by copying bin file to DAP Mass Storage flash: $(BUILD)/$(BOARD)-firmware.bin cp $< /media/$(USER)/RT1060-EVK/ diff --git a/hw/bsp/mimxrt1064_evk/board.mk b/hw/bsp/mimxrt1064_evk/board.mk index d991168e..7bb0c637 100644 --- a/hw/bsp/mimxrt1064_evk/board.mk +++ b/hw/bsp/mimxrt1064_evk/board.mk @@ -50,9 +50,6 @@ FREERTOS_PORT = ARM_CM7 JLINK_DEVICE = MIMXRT1064xxx6A JLINK_IF = swd -# flash using pyocd -#flash: $(BUILD)/$(BOARD)-firmware.hex -# pyocd flash -t mimxrt1050_quadspi $< - +# flash by copying bin file to DAP Mass Storage flash: $(BUILD)/$(BOARD)-firmware.bin cp $< /media/$(USER)/RT1064-EVK/ From d991466a8e45d03a8c95da894b2992b1b8a7d0b0 Mon Sep 17 00:00:00 2001 From: hathach Date: Sat, 23 Nov 2019 00:48:56 +0700 Subject: [PATCH 083/267] fix rt1010 rt1020 only has 1 usb controller, rt1050 rt1060 has 2 --- hw/bsp/mimxrt1020_evk/board.h | 34 +++ hw/bsp/mimxrt1020_evk/board.mk | 55 ++++ .../evkmimxrt1020_flexspi_nor_config.c | 49 ++++ .../evkmimxrt1020_flexspi_nor_config.h | 268 ++++++++++++++++++ hw/bsp/mimxrt1020_evk/mimxrt1020_evk.c | 169 +++++++++++ .../nxp/transdimension/dcd_transdimension.c | 9 + 6 files changed, 584 insertions(+) create mode 100644 hw/bsp/mimxrt1020_evk/board.h create mode 100644 hw/bsp/mimxrt1020_evk/board.mk create mode 100644 hw/bsp/mimxrt1020_evk/evkmimxrt1020_flexspi_nor_config.c create mode 100644 hw/bsp/mimxrt1020_evk/evkmimxrt1020_flexspi_nor_config.h create mode 100644 hw/bsp/mimxrt1020_evk/mimxrt1020_evk.c diff --git a/hw/bsp/mimxrt1020_evk/board.h b/hw/bsp/mimxrt1020_evk/board.h new file mode 100644 index 00000000..f1bd0636 --- /dev/null +++ b/hw/bsp/mimxrt1020_evk/board.h @@ -0,0 +1,34 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019, Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + + +#ifndef BOARD_H_ +#define BOARD_H_ + +// required since iMX RT10xx SDK include this file for board size +#define BOARD_FLASH_SIZE (0x800000U) + +#endif /* BOARD_H_ */ diff --git a/hw/bsp/mimxrt1020_evk/board.mk b/hw/bsp/mimxrt1020_evk/board.mk new file mode 100644 index 00000000..538626e9 --- /dev/null +++ b/hw/bsp/mimxrt1020_evk/board.mk @@ -0,0 +1,55 @@ +CFLAGS += \ + -mthumb \ + -mabi=aapcs \ + -mcpu=cortex-m7 \ + -mfloat-abi=hard \ + -mfpu=fpv5-d16 \ + -D__ARMVFP__=0 -D__ARMFPV5__=0\ + -DCPU_MIMXRT1021DAG5A \ + -DXIP_EXTERNAL_FLASH=1 \ + -DXIP_BOOT_HEADER_ENABLE=1 \ + -DCFG_TUSB_MCU=OPT_MCU_MIMXRT10XX \ + -DCFG_TUSB_MEM_SECTION='__attribute__((section(".data")))' \ + -DCFG_TUSB_MEM_ALIGN='__attribute__((aligned(64)))' + +# mcu driver cause following warnings +#CFLAGS += -Wno-error=float-equal -Wno-error=nested-externs +CFLAGS += -Wno-error=unused-parameter + +MCU_DIR = hw/mcu/nxp/sdk/devices/MIMXRT1021 + +# All source paths should be relative to the top level. +LD_FILE = $(MCU_DIR)/gcc/MIMXRT1021xxxxx_flexspi_nor.ld + +SRC_C += \ + $(MCU_DIR)/system_MIMXRT1021.c \ + $(MCU_DIR)/xip/fsl_flexspi_nor_boot.c \ + $(MCU_DIR)/project_template/clock_config.c \ + $(MCU_DIR)/drivers/fsl_clock.c \ + $(MCU_DIR)/drivers/fsl_gpio.c \ + $(MCU_DIR)/drivers/fsl_common.c \ + $(MCU_DIR)/drivers/fsl_lpuart.c + +INC += \ + $(TOP)/hw/bsp/$(BOARD) \ + $(TOP)/$(MCU_DIR)/../../CMSIS/Include \ + $(TOP)/$(MCU_DIR) \ + $(TOP)/$(MCU_DIR)/drivers \ + $(TOP)/$(MCU_DIR)/project_template \ + +SRC_S += $(MCU_DIR)/gcc/startup_MIMXRT1021.S + +# For TinyUSB port source +VENDOR = nxp +CHIP_FAMILY = transdimension + +# For freeRTOS port source +FREERTOS_PORT = ARM_CM7 + +# For flash-jlink target +JLINK_DEVICE = CPU_MIMXRT1021DAG5A +JLINK_IF = swd + +# flash by copying bin file to DAP Mass Storage +flash: $(BUILD)/$(BOARD)-firmware.bin + cp $< /media/$(USER)/RT1020-EVK/ diff --git a/hw/bsp/mimxrt1020_evk/evkmimxrt1020_flexspi_nor_config.c b/hw/bsp/mimxrt1020_evk/evkmimxrt1020_flexspi_nor_config.c new file mode 100644 index 00000000..6bafe195 --- /dev/null +++ b/hw/bsp/mimxrt1020_evk/evkmimxrt1020_flexspi_nor_config.c @@ -0,0 +1,49 @@ +/* + * Copyright 2018 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include "evkmimxrt1020_flexspi_nor_config.h" + +/* Component ID definition, used by tools. */ +#ifndef FSL_COMPONENT_ID +#define FSL_COMPONENT_ID "platform.drivers.xip_board" +#endif + +/******************************************************************************* + * Code + ******************************************************************************/ +#if defined(XIP_BOOT_HEADER_ENABLE) && (XIP_BOOT_HEADER_ENABLE == 1) +#if defined(__CC_ARM) || defined(__ARMCC_VERSION) || defined(__GNUC__) +__attribute__((section(".boot_hdr.conf"))) +#elif defined(__ICCARM__) +#pragma location = ".boot_hdr.conf" +#endif + +const flexspi_nor_config_t qspiflash_config = { + .memConfig = + { + .tag = FLEXSPI_CFG_BLK_TAG, + .version = FLEXSPI_CFG_BLK_VERSION, + .readSampleClkSrc = kFlexSPIReadSampleClk_LoopbackFromDqsPad, + .csHoldTime = 3u, + .csSetupTime = 3u, + // Enable DDR mode, Wordaddassable, Safe configuration, Differential clock + .sflashPadType = kSerialFlash_4Pads, + .serialClkFreq = kFlexSpiSerialClk_100MHz, + .sflashA1Size = 8u * 1024u * 1024u, + .lookupTable = + { + // Read LUTs + FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0xEB, RADDR_SDR, FLEXSPI_4PAD, 0x18), + FLEXSPI_LUT_SEQ(DUMMY_SDR, FLEXSPI_4PAD, 0x06, READ_SDR, FLEXSPI_4PAD, 0x04), + }, + }, + .pageSize = 256u, + .sectorSize = 4u * 1024u, + .blockSize = 256u * 1024u, + .isUniformBlockSize = false, +}; +#endif /* XIP_BOOT_HEADER_ENABLE */ diff --git a/hw/bsp/mimxrt1020_evk/evkmimxrt1020_flexspi_nor_config.h b/hw/bsp/mimxrt1020_evk/evkmimxrt1020_flexspi_nor_config.h new file mode 100644 index 00000000..f5e1aca5 --- /dev/null +++ b/hw/bsp/mimxrt1020_evk/evkmimxrt1020_flexspi_nor_config.h @@ -0,0 +1,268 @@ +/* + * Copyright 2018 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef __EVKMIMXRT1020_FLEXSPI_NOR_CONFIG__ +#define __EVKMIMXRT1020_FLEXSPI_NOR_CONFIG__ + +#include +#include +#include "fsl_common.h" + +/*! @name Driver version */ +/*@{*/ +/*! @brief XIP_BOARD driver version 2.0.0. */ +#define FSL_XIP_BOARD_DRIVER_VERSION (MAKE_VERSION(2, 0, 0)) +/*@}*/ + +/* FLEXSPI memory config block related defintions */ +#define FLEXSPI_CFG_BLK_TAG (0x42464346UL) // ascii "FCFB" Big Endian +#define FLEXSPI_CFG_BLK_VERSION (0x56010400UL) // V1.4.0 +#define FLEXSPI_CFG_BLK_SIZE (512) + +/* FLEXSPI Feature related definitions */ +#define FLEXSPI_FEATURE_HAS_PARALLEL_MODE 1 + +/* Lookup table related defintions */ +#define CMD_INDEX_READ 0 +#define CMD_INDEX_READSTATUS 1 +#define CMD_INDEX_WRITEENABLE 2 +#define CMD_INDEX_WRITE 4 + +#define CMD_LUT_SEQ_IDX_READ 0 +#define CMD_LUT_SEQ_IDX_READSTATUS 1 +#define CMD_LUT_SEQ_IDX_WRITEENABLE 3 +#define CMD_LUT_SEQ_IDX_WRITE 9 + +#define CMD_SDR 0x01 +#define CMD_DDR 0x21 +#define RADDR_SDR 0x02 +#define RADDR_DDR 0x22 +#define CADDR_SDR 0x03 +#define CADDR_DDR 0x23 +#define MODE1_SDR 0x04 +#define MODE1_DDR 0x24 +#define MODE2_SDR 0x05 +#define MODE2_DDR 0x25 +#define MODE4_SDR 0x06 +#define MODE4_DDR 0x26 +#define MODE8_SDR 0x07 +#define MODE8_DDR 0x27 +#define WRITE_SDR 0x08 +#define WRITE_DDR 0x28 +#define READ_SDR 0x09 +#define READ_DDR 0x29 +#define LEARN_SDR 0x0A +#define LEARN_DDR 0x2A +#define DATSZ_SDR 0x0B +#define DATSZ_DDR 0x2B +#define DUMMY_SDR 0x0C +#define DUMMY_DDR 0x2C +#define DUMMY_RWDS_SDR 0x0D +#define DUMMY_RWDS_DDR 0x2D +#define JMP_ON_CS 0x1F +#define STOP 0 + +#define FLEXSPI_1PAD 0 +#define FLEXSPI_2PAD 1 +#define FLEXSPI_4PAD 2 +#define FLEXSPI_8PAD 3 + +#define FLEXSPI_LUT_SEQ(cmd0, pad0, op0, cmd1, pad1, op1) \ + (FLEXSPI_LUT_OPERAND0(op0) | FLEXSPI_LUT_NUM_PADS0(pad0) | FLEXSPI_LUT_OPCODE0(cmd0) | FLEXSPI_LUT_OPERAND1(op1) | \ + FLEXSPI_LUT_NUM_PADS1(pad1) | FLEXSPI_LUT_OPCODE1(cmd1)) + +//!@brief Definitions for FlexSPI Serial Clock Frequency +typedef enum _FlexSpiSerialClockFreq +{ + kFlexSpiSerialClk_30MHz = 1, + kFlexSpiSerialClk_50MHz = 2, + kFlexSpiSerialClk_60MHz = 3, + kFlexSpiSerialClk_75MHz = 4, + kFlexSpiSerialClk_80MHz = 5, + kFlexSpiSerialClk_100MHz = 6, + kFlexSpiSerialClk_133MHz = 7, + kFlexSpiSerialClk_166MHz = 8, + kFlexSpiSerialClk_200MHz = 9, +} flexspi_serial_clk_freq_t; + +//!@brief FlexSPI clock configuration type +enum +{ + kFlexSpiClk_SDR, //!< Clock configure for SDR mode + kFlexSpiClk_DDR, //!< Clock configurat for DDR mode +}; + +//!@brief FlexSPI Read Sample Clock Source definition +typedef enum _FlashReadSampleClkSource +{ + kFlexSPIReadSampleClk_LoopbackInternally = 0, + kFlexSPIReadSampleClk_LoopbackFromDqsPad = 1, + kFlexSPIReadSampleClk_LoopbackFromSckPad = 2, + kFlexSPIReadSampleClk_ExternalInputFromDqsPad = 3, +} flexspi_read_sample_clk_t; + +//!@brief Misc feature bit definitions +enum +{ + kFlexSpiMiscOffset_DiffClkEnable = 0, //!< Bit for Differential clock enable + kFlexSpiMiscOffset_Ck2Enable = 1, //!< Bit for CK2 enable + kFlexSpiMiscOffset_ParallelEnable = 2, //!< Bit for Parallel mode enable + kFlexSpiMiscOffset_WordAddressableEnable = 3, //!< Bit for Word Addressable enable + kFlexSpiMiscOffset_SafeConfigFreqEnable = 4, //!< Bit for Safe Configuration Frequency enable + kFlexSpiMiscOffset_PadSettingOverrideEnable = 5, //!< Bit for Pad setting override enable + kFlexSpiMiscOffset_DdrModeEnable = 6, //!< Bit for DDR clock confiuration indication. +}; + +//!@brief Flash Type Definition +enum +{ + kFlexSpiDeviceType_SerialNOR = 1, //!< Flash devices are Serial NOR + kFlexSpiDeviceType_SerialNAND = 2, //!< Flash devices are Serial NAND + kFlexSpiDeviceType_SerialRAM = 3, //!< Flash devices are Serial RAM/HyperFLASH + kFlexSpiDeviceType_MCP_NOR_NAND = 0x12, //!< Flash device is MCP device, A1 is Serial NOR, A2 is Serial NAND + kFlexSpiDeviceType_MCP_NOR_RAM = 0x13, //!< Flash deivce is MCP device, A1 is Serial NOR, A2 is Serial RAMs +}; + +//!@brief Flash Pad Definitions +enum +{ + kSerialFlash_1Pad = 1, + kSerialFlash_2Pads = 2, + kSerialFlash_4Pads = 4, + kSerialFlash_8Pads = 8, +}; + +//!@brief FlexSPI LUT Sequence structure +typedef struct _lut_sequence +{ + uint8_t seqNum; //!< Sequence Number, valid number: 1-16 + uint8_t seqId; //!< Sequence Index, valid number: 0-15 + uint16_t reserved; +} flexspi_lut_seq_t; + +//!@brief Flash Configuration Command Type +enum +{ + kDeviceConfigCmdType_Generic, //!< Generic command, for example: configure dummy cycles, drive strength, etc + kDeviceConfigCmdType_QuadEnable, //!< Quad Enable command + kDeviceConfigCmdType_Spi2Xpi, //!< Switch from SPI to DPI/QPI/OPI mode + kDeviceConfigCmdType_Xpi2Spi, //!< Switch from DPI/QPI/OPI to SPI mode + kDeviceConfigCmdType_Spi2NoCmd, //!< Switch to 0-4-4/0-8-8 mode + kDeviceConfigCmdType_Reset, //!< Reset device command +}; + +//!@brief FlexSPI Memory Configuration Block +typedef struct _FlexSPIConfig +{ + uint32_t tag; //!< [0x000-0x003] Tag, fixed value 0x42464346UL + uint32_t version; //!< [0x004-0x007] Version,[31:24] -'V', [23:16] - Major, [15:8] - Minor, [7:0] - bugfix + uint32_t reserved0; //!< [0x008-0x00b] Reserved for future use + uint8_t readSampleClkSrc; //!< [0x00c-0x00c] Read Sample Clock Source, valid value: 0/1/3 + uint8_t csHoldTime; //!< [0x00d-0x00d] CS hold time, default value: 3 + uint8_t csSetupTime; //!< [0x00e-0x00e] CS setup time, default value: 3 + uint8_t columnAddressWidth; //!< [0x00f-0x00f] Column Address with, for HyperBus protocol, it is fixed to 3, For + //! Serial NAND, need to refer to datasheet + uint8_t deviceModeCfgEnable; //!< [0x010-0x010] Device Mode Configure enable flag, 1 - Enable, 0 - Disable + uint8_t deviceModeType; //!< [0x011-0x011] Specify the configuration command type:Quad Enable, DPI/QPI/OPI switch, + //! Generic configuration, etc. + uint16_t waitTimeCfgCommands; //!< [0x012-0x013] Wait time for all configuration commands, unit: 100us, Used for + //! DPI/QPI/OPI switch or reset command + flexspi_lut_seq_t deviceModeSeq; //!< [0x014-0x017] Device mode sequence info, [7:0] - LUT sequence id, [15:8] - LUt + //! sequence number, [31:16] Reserved + uint32_t deviceModeArg; //!< [0x018-0x01b] Argument/Parameter for device configuration + uint8_t configCmdEnable; //!< [0x01c-0x01c] Configure command Enable Flag, 1 - Enable, 0 - Disable + uint8_t configModeType[3]; //!< [0x01d-0x01f] Configure Mode Type, similar as deviceModeTpe + flexspi_lut_seq_t + configCmdSeqs[3]; //!< [0x020-0x02b] Sequence info for Device Configuration command, similar as deviceModeSeq + uint32_t reserved1; //!< [0x02c-0x02f] Reserved for future use + uint32_t configCmdArgs[3]; //!< [0x030-0x03b] Arguments/Parameters for device Configuration commands + uint32_t reserved2; //!< [0x03c-0x03f] Reserved for future use + uint32_t controllerMiscOption; //!< [0x040-0x043] Controller Misc Options, see Misc feature bit definitions for more + //! details + uint8_t deviceType; //!< [0x044-0x044] Device Type: See Flash Type Definition for more details + uint8_t sflashPadType; //!< [0x045-0x045] Serial Flash Pad Type: 1 - Single, 2 - Dual, 4 - Quad, 8 - Octal + uint8_t serialClkFreq; //!< [0x046-0x046] Serial Flash Frequencey, device specific definitions, See System Boot + //! Chapter for more details + uint8_t lutCustomSeqEnable; //!< [0x047-0x047] LUT customization Enable, it is required if the program/erase cannot + //! be done using 1 LUT sequence, currently, only applicable to HyperFLASH + uint32_t reserved3[2]; //!< [0x048-0x04f] Reserved for future use + uint32_t sflashA1Size; //!< [0x050-0x053] Size of Flash connected to A1 + uint32_t sflashA2Size; //!< [0x054-0x057] Size of Flash connected to A2 + uint32_t sflashB1Size; //!< [0x058-0x05b] Size of Flash connected to B1 + uint32_t sflashB2Size; //!< [0x05c-0x05f] Size of Flash connected to B2 + uint32_t csPadSettingOverride; //!< [0x060-0x063] CS pad setting override value + uint32_t sclkPadSettingOverride; //!< [0x064-0x067] SCK pad setting override value + uint32_t dataPadSettingOverride; //!< [0x068-0x06b] data pad setting override value + uint32_t dqsPadSettingOverride; //!< [0x06c-0x06f] DQS pad setting override value + uint32_t timeoutInMs; //!< [0x070-0x073] Timeout threshold for read status command + uint32_t commandInterval; //!< [0x074-0x077] CS deselect interval between two commands + uint16_t dataValidTime[2]; //!< [0x078-0x07b] CLK edge to data valid time for PORT A and PORT B, in terms of 0.1ns + uint16_t busyOffset; //!< [0x07c-0x07d] Busy offset, valid value: 0-31 + uint16_t busyBitPolarity; //!< [0x07e-0x07f] Busy flag polarity, 0 - busy flag is 1 when flash device is busy, 1 - + //! busy flag is 0 when flash device is busy + uint32_t lookupTable[64]; //!< [0x080-0x17f] Lookup table holds Flash command sequences + flexspi_lut_seq_t lutCustomSeq[12]; //!< [0x180-0x1af] Customizable LUT Sequences + uint32_t reserved4[4]; //!< [0x1b0-0x1bf] Reserved for future use +} flexspi_mem_config_t; + +/* */ +#define NOR_CMD_INDEX_READ CMD_INDEX_READ //!< 0 +#define NOR_CMD_INDEX_READSTATUS CMD_INDEX_READSTATUS //!< 1 +#define NOR_CMD_INDEX_WRITEENABLE CMD_INDEX_WRITEENABLE //!< 2 +#define NOR_CMD_INDEX_ERASESECTOR 3 //!< 3 +#define NOR_CMD_INDEX_PAGEPROGRAM CMD_INDEX_WRITE //!< 4 +#define NOR_CMD_INDEX_CHIPERASE 5 //!< 5 +#define NOR_CMD_INDEX_DUMMY 6 //!< 6 +#define NOR_CMD_INDEX_ERASEBLOCK 7 //!< 7 + +#define NOR_CMD_LUT_SEQ_IDX_READ CMD_LUT_SEQ_IDX_READ //!< 0 READ LUT sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_READSTATUS \ + CMD_LUT_SEQ_IDX_READSTATUS //!< 1 Read Status LUT sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_READSTATUS_XPI \ + 2 //!< 2 Read status DPI/QPI/OPI sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_WRITEENABLE \ + CMD_LUT_SEQ_IDX_WRITEENABLE //!< 3 Write Enable sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_WRITEENABLE_XPI \ + 4 //!< 4 Write Enable DPI/QPI/OPI sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_ERASESECTOR 5 //!< 5 Erase Sector sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_ERASEBLOCK 8 //!< 8 Erase Block sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_PAGEPROGRAM \ + CMD_LUT_SEQ_IDX_WRITE //!< 9 Program sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_CHIPERASE 11 //!< 11 Chip Erase sequence in lookupTable id stored in config block +#define NOR_CMD_LUT_SEQ_IDX_READ_SFDP 13 //!< 13 Read SFDP sequence in lookupTable id stored in config block +#define NOR_CMD_LUT_SEQ_IDX_RESTORE_NOCMD \ + 14 //!< 14 Restore 0-4-4/0-8-8 mode sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_EXIT_NOCMD \ + 15 //!< 15 Exit 0-4-4/0-8-8 mode sequence id in lookupTable stored in config blobk + +/* + * Serial NOR configuration block + */ +typedef struct _flexspi_nor_config +{ + flexspi_mem_config_t memConfig; //!< Common memory configuration info via FlexSPI + uint32_t pageSize; //!< Page size of Serial NOR + uint32_t sectorSize; //!< Sector size of Serial NOR + uint8_t ipcmdSerialClkFreq; //!< Clock frequency for IP command + uint8_t isUniformBlockSize; //!< Sector/Block size is the same + uint8_t reserved0[2]; //!< Reserved for future use + uint8_t serialNorType; //!< Serial NOR Flash type: 0/1/2/3 + uint8_t needExitNoCmdMode; //!< Need to exit NoCmd mode before other IP command + uint8_t halfClkForNonReadCmd; //!< Half the Serial Clock for non-read command: true/false + uint8_t needRestoreNoCmdMode; //!< Need to Restore NoCmd mode after IP commmand execution + uint32_t blockSize; //!< Block size + uint32_t reserve2[11]; //!< Reserved for future use +} flexspi_nor_config_t; + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef __cplusplus +} +#endif +#endif /* __EVKMIMXRT1020_FLEXSPI_NOR_CONFIG__ */ diff --git a/hw/bsp/mimxrt1020_evk/mimxrt1020_evk.c b/hw/bsp/mimxrt1020_evk/mimxrt1020_evk.c new file mode 100644 index 00000000..708397f7 --- /dev/null +++ b/hw/bsp/mimxrt1020_evk/mimxrt1020_evk.c @@ -0,0 +1,169 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2018, hathach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#include "../board.h" +#include "fsl_device_registers.h" +#include "fsl_gpio.h" +#include "fsl_iomuxc.h" +#include "fsl_clock.h" +#include "fsl_lpuart.h" + +#include "clock_config.h" + +#define LED_PINMUX IOMUXC_GPIO_AD_B0_05_GPIO1_IO05 +#define LED_PORT GPIO1 +#define LED_PIN 5 +#define LED_STATE_ON 0 + +// SW8 button +#define BUTTON_PINMUX IOMUXC_SNVS_WAKEUP_GPIO5_IO00 +#define BUTTON_PORT GPIO5 +#define BUTTON_PIN 0 +#define BUTTON_STATE_ACTIVE 0 + +// UART +#define UART_PORT LPUART1 +#define UART_RX_PINMUX IOMUXC_GPIO_AD_B0_07_LPUART1_RX +#define UART_TX_PINMUX IOMUXC_GPIO_AD_B0_06_LPUART1_TX + +const uint8_t dcd_data[] = { 0x00 }; + +void board_init(void) +{ + // Init clock + BOARD_BootClockRUN(); + SystemCoreClockUpdate(); + + // Enable IOCON clock + CLOCK_EnableClock(kCLOCK_Iomuxc); + +#if CFG_TUSB_OS == OPT_OS_NONE + // 1ms tick timer + SysTick_Config(SystemCoreClock / 1000); +#elif CFG_TUSB_OS == OPT_OS_FREERTOS + // If freeRTOS is used, IRQ priority is limit by max syscall ( smaller is higher ) +// NVIC_SetPriority(USB0_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY ); +#endif + + // LED + IOMUXC_SetPinMux( LED_PINMUX, 0U); + IOMUXC_SetPinConfig( LED_PINMUX, 0x10B0U); + + gpio_pin_config_t led_config = { kGPIO_DigitalOutput, 0, kGPIO_NoIntmode }; + GPIO_PinInit(LED_PORT, LED_PIN, &led_config); + board_led_write(true); + + // Button + IOMUXC_SetPinMux( BUTTON_PINMUX, 0U); + gpio_pin_config_t button_config = { kGPIO_DigitalInput, 0, kGPIO_IntRisingEdge, }; + GPIO_PinInit(BUTTON_PORT, BUTTON_PIN, &button_config); + + // UART + IOMUXC_SetPinMux( UART_TX_PINMUX, 0U); + IOMUXC_SetPinMux( UART_RX_PINMUX, 0U); + IOMUXC_SetPinConfig( UART_TX_PINMUX, 0x10B0u); + IOMUXC_SetPinConfig( UART_RX_PINMUX, 0x10B0u); + + lpuart_config_t uart_config; + LPUART_GetDefaultConfig(&uart_config); + uart_config.baudRate_Bps = CFG_BOARD_UART_BAUDRATE; + uart_config.enableTx = true; + uart_config.enableRx = true; + LPUART_Init(UART_PORT, &uart_config, (CLOCK_GetPllFreq(kCLOCK_PllUsb1) / 6U) / (CLOCK_GetDiv(kCLOCK_UartDiv) + 1U)); + + //------------- USB0 -------------// + // Clock + CLOCK_EnableUsbhs0PhyPllClock(kCLOCK_Usbphy480M, 480000000U); + CLOCK_EnableUsbhs0Clock(kCLOCK_Usb480M, 480000000U); + + USBPHY_Type* usb_phy = USBPHY; + + // Enable PHY support for Low speed device + LS via FS Hub + usb_phy->CTRL |= USBPHY_CTRL_SET_ENUTMILEVEL2_MASK | USBPHY_CTRL_SET_ENUTMILEVEL3_MASK; + + // Enable all power for normal operation + usb_phy->PWD = 0; + + // TX Timing + uint32_t phytx = usb_phy->TX; + phytx &= ~(USBPHY_TX_D_CAL_MASK | USBPHY_TX_TXCAL45DM_MASK | USBPHY_TX_TXCAL45DP_MASK); + phytx |= USBPHY_TX_D_CAL(0x0C) | USBPHY_TX_TXCAL45DP(0x06) | USBPHY_TX_TXCAL45DM(0x06); + usb_phy->TX = phytx; +} + +//--------------------------------------------------------------------+ +// USB Interrupt Handler +//--------------------------------------------------------------------+ +void USB_OTG1_IRQHandler(void) +{ + #if CFG_TUSB_RHPORT0_MODE & OPT_MODE_HOST + tuh_isr(0); + #endif + + #if CFG_TUSB_RHPORT0_MODE & OPT_MODE_DEVICE + tud_isr(0); + #endif +} + +//--------------------------------------------------------------------+ +// Board porting API +//--------------------------------------------------------------------+ + +void board_led_write(bool state) +{ + GPIO_PinWrite(LED_PORT, LED_PIN, state ? LED_STATE_ON : (1-LED_STATE_ON)); +} + +uint32_t board_button_read(void) +{ + // active low + return BUTTON_STATE_ACTIVE == GPIO_PinRead(BUTTON_PORT, BUTTON_PIN); +} + +int board_uart_read(uint8_t* buf, int len) +{ + LPUART_ReadBlocking(UART_PORT, buf, len); + return len; +} + +int board_uart_write(void const * buf, int len) +{ + LPUART_WriteBlocking(UART_PORT, (uint8_t*)buf, len); + return len; +} + +#if CFG_TUSB_OS == OPT_OS_NONE +volatile uint32_t system_ticks = 0; +void SysTick_Handler(void) +{ + system_ticks++; +} + +uint32_t board_millis(void) +{ + return system_ticks; +} +#endif diff --git a/src/portable/nxp/transdimension/dcd_transdimension.c b/src/portable/nxp/transdimension/dcd_transdimension.c index cc85bb62..2ec7ae51 100644 --- a/src/portable/nxp/transdimension/dcd_transdimension.c +++ b/src/portable/nxp/transdimension/dcd_transdimension.c @@ -38,8 +38,17 @@ #if CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX #include "fsl_device_registers.h" + +// RT1010 and RT1020 only has 1 USB controller +#if FSL_FEATURE_SOC_USBHS_COUNT == 1 + #define DCD_REGS_BASE { (dcd_registers_t*) USB_BASE } + IRQn_Type DCD_IRQn[] = { USB_OTG1_IRQn }; + +// RT1050, RT1060 has 2 USB controllers +#else #define DCD_REGS_BASE { (dcd_registers_t*) USB1_BASE, (dcd_registers_t*) USB2_BASE } IRQn_Type DCD_IRQn[] = { USB_OTG1_IRQn, USB_OTG2_IRQn }; +#endif #else #include "chip.h" From d76eb8d6595860584640d26b1056bf47f31cb134 Mon Sep 17 00:00:00 2001 From: hathach Date: Sat, 23 Nov 2019 00:51:43 +0700 Subject: [PATCH 084/267] doc update --- README.md | 2 +- docs/boards.md | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 3401dc90..d983dadd 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ The stack supports the following MCUs - **Nordic:** nRF52840, nRF52833 - **NXP:** - LPC Series: 11Uxx, 13xx, 175x_6x, 177x_8x, 18xx, 40xx, 43xx, 51Uxx, 54xxx, 55xx - - iMX RT Series: RT1052, RT1062, RT1064 + - iMX RT Series: RT1021, RT1052, RT1062, RT1064 - **Sony:** CXD56 - **ST:** STM32 series: L0, F0, F1, F2, F3, F4, F7, H7 (device only) - **Tomu:** [valentyusb](https://github.com/im-tomu/valentyusb) (eptri) diff --git a/docs/boards.md b/docs/boards.md index de1e6bbd..305f06fe 100644 --- a/docs/boards.md +++ b/docs/boards.md @@ -28,7 +28,8 @@ This code base already had supported for a handful of following boards ### NXP iMX RT -- [MIMX RT1052 Evaluation Kit](https://www.nxp.com/design/development-boards/i.mx-evaluation-and-development-boards/i.mx-rt1050-evaluation-kit:MIMXRT1050-EVK) +- [MIMX RT1020 Evaluation Kit](https://www.nxp.com/design/development-boards/i.mx-evaluation-and-development-boards/i.mx-rt1020-evaluation-kit:MIMXRT1020-EVK) +- [MIMX RT1050 Evaluation Kit](https://www.nxp.com/design/development-boards/i.mx-evaluation-and-development-boards/i.mx-rt1050-evaluation-kit:MIMXRT1050-EVK) - [MIMX RT1060 Evaluation Kit](https://www.nxp.com/design/development-boards/i.mx-evaluation-and-development-boards/mimxrt1060-evk-i.mx-rt1060-evaluation-kit:MIMXRT1060-EVK) - [MIMX RT1064 Evaluation Kit](https://www.nxp.com/design/development-boards/i.mx-evaluation-and-development-boards/mimxrt1064-evk-i.mx-rt1064-evaluation-kit:MIMXRT1064-EVK) From a6b1289096864f4d8578006561e9de28742162f6 Mon Sep 17 00:00:00 2001 From: hathach Date: Sat, 23 Nov 2019 01:09:39 +0700 Subject: [PATCH 085/267] added rt1015 evk board --- hw/bsp/mimxrt1015_evk/board.h | 34 +++ hw/bsp/mimxrt1015_evk/board.mk | 52 ++++ .../evkmimxrt1015_flexspi_nor_config.c | 48 ++++ .../evkmimxrt1015_flexspi_nor_config.h | 268 ++++++++++++++++++ hw/bsp/mimxrt1015_evk/mimxrt1015_evk.c | 170 +++++++++++ hw/bsp/mimxrt1020_evk/board.mk | 6 +- hw/bsp/mimxrt1050_evkb/board.mk | 4 +- hw/bsp/mimxrt1060_evk/board.mk | 4 +- hw/bsp/mimxrt1064_evk/board.mk | 4 +- 9 files changed, 577 insertions(+), 13 deletions(-) create mode 100644 hw/bsp/mimxrt1015_evk/board.h create mode 100644 hw/bsp/mimxrt1015_evk/board.mk create mode 100644 hw/bsp/mimxrt1015_evk/evkmimxrt1015_flexspi_nor_config.c create mode 100644 hw/bsp/mimxrt1015_evk/evkmimxrt1015_flexspi_nor_config.h create mode 100644 hw/bsp/mimxrt1015_evk/mimxrt1015_evk.c diff --git a/hw/bsp/mimxrt1015_evk/board.h b/hw/bsp/mimxrt1015_evk/board.h new file mode 100644 index 00000000..5f3e3158 --- /dev/null +++ b/hw/bsp/mimxrt1015_evk/board.h @@ -0,0 +1,34 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019, Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + + +#ifndef BOARD_H_ +#define BOARD_H_ + +// required since iMX RT10xx SDK include this file for board size +#define BOARD_FLASH_SIZE (0x1000000U) + +#endif /* BOARD_H_ */ diff --git a/hw/bsp/mimxrt1015_evk/board.mk b/hw/bsp/mimxrt1015_evk/board.mk new file mode 100644 index 00000000..a538c7dc --- /dev/null +++ b/hw/bsp/mimxrt1015_evk/board.mk @@ -0,0 +1,52 @@ +CFLAGS += \ + -mthumb \ + -mabi=aapcs \ + -mcpu=cortex-m7 \ + -mfloat-abi=hard \ + -mfpu=fpv5-d16 \ + -D__ARMVFP__=0 -D__ARMFPV5__=0\ + -DCPU_MIMXRT1015DAF5A \ + -DXIP_EXTERNAL_FLASH=1 \ + -DXIP_BOOT_HEADER_ENABLE=1 \ + -DCFG_TUSB_MCU=OPT_MCU_MIMXRT10XX + +# mcu driver cause following warnings +CFLAGS += -Wno-error=unused-parameter -Wno-error=implicit-fallthrough= + +MCU_DIR = hw/mcu/nxp/sdk/devices/MIMXRT1015 + +# All source paths should be relative to the top level. +LD_FILE = $(MCU_DIR)/gcc/MIMXRT1015xxxxx_flexspi_nor.ld + +SRC_C += \ + $(MCU_DIR)/system_MIMXRT1015.c \ + $(MCU_DIR)/xip/fsl_flexspi_nor_boot.c \ + $(MCU_DIR)/project_template/clock_config.c \ + $(MCU_DIR)/drivers/fsl_clock.c \ + $(MCU_DIR)/drivers/fsl_gpio.c \ + $(MCU_DIR)/drivers/fsl_common.c \ + $(MCU_DIR)/drivers/fsl_lpuart.c + +INC += \ + $(TOP)/hw/bsp/$(BOARD) \ + $(TOP)/$(MCU_DIR)/../../CMSIS/Include \ + $(TOP)/$(MCU_DIR) \ + $(TOP)/$(MCU_DIR)/drivers \ + $(TOP)/$(MCU_DIR)/project_template \ + +SRC_S += $(MCU_DIR)/gcc/startup_MIMXRT1015.S + +# For TinyUSB port source +VENDOR = nxp +CHIP_FAMILY = transdimension + +# For freeRTOS port source +FREERTOS_PORT = ARM_CM7 + +# For flash-jlink target +JLINK_DEVICE = MIMXRT1015DAF5A +JLINK_IF = swd + +# flash by copying bin file to DAP Mass Storage +flash: $(BUILD)/$(BOARD)-firmware.bin + cp $< /media/$(USER)/RT1015-EVK/ diff --git a/hw/bsp/mimxrt1015_evk/evkmimxrt1015_flexspi_nor_config.c b/hw/bsp/mimxrt1015_evk/evkmimxrt1015_flexspi_nor_config.c new file mode 100644 index 00000000..a396fe60 --- /dev/null +++ b/hw/bsp/mimxrt1015_evk/evkmimxrt1015_flexspi_nor_config.c @@ -0,0 +1,48 @@ +/* + * Copyright 2018-2019 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include "evkmimxrt1015_flexspi_nor_config.h" + +/* Component ID definition, used by tools. */ +#ifndef FSL_COMPONENT_ID +#define FSL_COMPONENT_ID "platform.drivers.xip_board" +#endif + +/******************************************************************************* + * Code + ******************************************************************************/ +#if defined(XIP_BOOT_HEADER_ENABLE) && (XIP_BOOT_HEADER_ENABLE == 1) +#if defined(__CC_ARM) || defined(__ARMCC_VERSION) || defined(__GNUC__) +__attribute__((section(".boot_hdr.conf"))) +#elif defined(__ICCARM__) +#pragma location = ".boot_hdr.conf" +#endif + +const flexspi_nor_config_t qspiflash_config = { + .memConfig = + { + .tag = FLEXSPI_CFG_BLK_TAG, + .version = FLEXSPI_CFG_BLK_VERSION, + .readSampleClkSrc = kFlexSPIReadSampleClk_LoopbackFromDqsPad, + .csHoldTime = 3u, + .csSetupTime = 3u, + .sflashPadType = kSerialFlash_4Pads, + .serialClkFreq = kFlexSpiSerialClk_100MHz, + .sflashA1Size = 16u * 1024u * 1024u, + .lookupTable = + { + // Read LUTs + FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0xEB, RADDR_SDR, FLEXSPI_4PAD, 0x18), + FLEXSPI_LUT_SEQ(DUMMY_SDR, FLEXSPI_4PAD, 0x06, READ_SDR, FLEXSPI_4PAD, 0x04), + }, + }, + .pageSize = 256u, + .sectorSize = 4u * 1024u, + .blockSize = 256u * 1024u, + .isUniformBlockSize = false, +}; +#endif /* XIP_BOOT_HEADER_ENABLE */ diff --git a/hw/bsp/mimxrt1015_evk/evkmimxrt1015_flexspi_nor_config.h b/hw/bsp/mimxrt1015_evk/evkmimxrt1015_flexspi_nor_config.h new file mode 100644 index 00000000..94af5a11 --- /dev/null +++ b/hw/bsp/mimxrt1015_evk/evkmimxrt1015_flexspi_nor_config.h @@ -0,0 +1,268 @@ +/* + * Copyright 2018-2019 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef __EVKMIMXRT1015_FLEXSPI_NOR_CONFIG__ +#define __EVKMIMXRT1015_FLEXSPI_NOR_CONFIG__ + +#include +#include +#include "fsl_common.h" + +/*! @name Driver version */ +/*@{*/ +/*! @brief XIP_BOARD driver version 2.0.0. */ +#define FSL_XIP_BOARD_DRIVER_VERSION (MAKE_VERSION(2, 0, 0)) +/*@}*/ + +/* FLEXSPI memory config block related defintions */ +#define FLEXSPI_CFG_BLK_TAG (0x42464346UL) // ascii "FCFB" Big Endian +#define FLEXSPI_CFG_BLK_VERSION (0x56010400UL) // V1.4.0 +#define FLEXSPI_CFG_BLK_SIZE (512) + +/* FLEXSPI Feature related definitions */ +#define FLEXSPI_FEATURE_HAS_PARALLEL_MODE 1 + +/* Lookup table related defintions */ +#define CMD_INDEX_READ 0 +#define CMD_INDEX_READSTATUS 1 +#define CMD_INDEX_WRITEENABLE 2 +#define CMD_INDEX_WRITE 4 + +#define CMD_LUT_SEQ_IDX_READ 0 +#define CMD_LUT_SEQ_IDX_READSTATUS 1 +#define CMD_LUT_SEQ_IDX_WRITEENABLE 3 +#define CMD_LUT_SEQ_IDX_WRITE 9 + +#define CMD_SDR 0x01 +#define CMD_DDR 0x21 +#define RADDR_SDR 0x02 +#define RADDR_DDR 0x22 +#define CADDR_SDR 0x03 +#define CADDR_DDR 0x23 +#define MODE1_SDR 0x04 +#define MODE1_DDR 0x24 +#define MODE2_SDR 0x05 +#define MODE2_DDR 0x25 +#define MODE4_SDR 0x06 +#define MODE4_DDR 0x26 +#define MODE8_SDR 0x07 +#define MODE8_DDR 0x27 +#define WRITE_SDR 0x08 +#define WRITE_DDR 0x28 +#define READ_SDR 0x09 +#define READ_DDR 0x29 +#define LEARN_SDR 0x0A +#define LEARN_DDR 0x2A +#define DATSZ_SDR 0x0B +#define DATSZ_DDR 0x2B +#define DUMMY_SDR 0x0C +#define DUMMY_DDR 0x2C +#define DUMMY_RWDS_SDR 0x0D +#define DUMMY_RWDS_DDR 0x2D +#define JMP_ON_CS 0x1F +#define STOP 0 + +#define FLEXSPI_1PAD 0 +#define FLEXSPI_2PAD 1 +#define FLEXSPI_4PAD 2 +#define FLEXSPI_8PAD 3 + +#define FLEXSPI_LUT_SEQ(cmd0, pad0, op0, cmd1, pad1, op1) \ + (FLEXSPI_LUT_OPERAND0(op0) | FLEXSPI_LUT_NUM_PADS0(pad0) | FLEXSPI_LUT_OPCODE0(cmd0) | FLEXSPI_LUT_OPERAND1(op1) | \ + FLEXSPI_LUT_NUM_PADS1(pad1) | FLEXSPI_LUT_OPCODE1(cmd1)) + +//!@brief Definitions for FlexSPI Serial Clock Frequency +typedef enum _FlexSpiSerialClockFreq +{ + kFlexSpiSerialClk_30MHz = 1, + kFlexSpiSerialClk_50MHz = 2, + kFlexSpiSerialClk_60MHz = 3, + kFlexSpiSerialClk_75MHz = 4, + kFlexSpiSerialClk_80MHz = 5, + kFlexSpiSerialClk_100MHz = 6, + kFlexSpiSerialClk_133MHz = 7, + kFlexSpiSerialClk_166MHz = 8, + kFlexSpiSerialClk_200MHz = 9, +} flexspi_serial_clk_freq_t; + +//!@brief FlexSPI clock configuration type +enum +{ + kFlexSpiClk_SDR, //!< Clock configure for SDR mode + kFlexSpiClk_DDR, //!< Clock configurat for DDR mode +}; + +//!@brief FlexSPI Read Sample Clock Source definition +typedef enum _FlashReadSampleClkSource +{ + kFlexSPIReadSampleClk_LoopbackInternally = 0, + kFlexSPIReadSampleClk_LoopbackFromDqsPad = 1, + kFlexSPIReadSampleClk_LoopbackFromSckPad = 2, + kFlexSPIReadSampleClk_ExternalInputFromDqsPad = 3, +} flexspi_read_sample_clk_t; + +//!@brief Misc feature bit definitions +enum +{ + kFlexSpiMiscOffset_DiffClkEnable = 0, //!< Bit for Differential clock enable + kFlexSpiMiscOffset_Ck2Enable = 1, //!< Bit for CK2 enable + kFlexSpiMiscOffset_ParallelEnable = 2, //!< Bit for Parallel mode enable + kFlexSpiMiscOffset_WordAddressableEnable = 3, //!< Bit for Word Addressable enable + kFlexSpiMiscOffset_SafeConfigFreqEnable = 4, //!< Bit for Safe Configuration Frequency enable + kFlexSpiMiscOffset_PadSettingOverrideEnable = 5, //!< Bit for Pad setting override enable + kFlexSpiMiscOffset_DdrModeEnable = 6, //!< Bit for DDR clock confiuration indication. +}; + +//!@brief Flash Type Definition +enum +{ + kFlexSpiDeviceType_SerialNOR = 1, //!< Flash devices are Serial NOR + kFlexSpiDeviceType_SerialNAND = 2, //!< Flash devices are Serial NAND + kFlexSpiDeviceType_SerialRAM = 3, //!< Flash devices are Serial RAM/HyperFLASH + kFlexSpiDeviceType_MCP_NOR_NAND = 0x12, //!< Flash device is MCP device, A1 is Serial NOR, A2 is Serial NAND + kFlexSpiDeviceType_MCP_NOR_RAM = 0x13, //!< Flash deivce is MCP device, A1 is Serial NOR, A2 is Serial RAMs +}; + +//!@brief Flash Pad Definitions +enum +{ + kSerialFlash_1Pad = 1, + kSerialFlash_2Pads = 2, + kSerialFlash_4Pads = 4, + kSerialFlash_8Pads = 8, +}; + +//!@brief FlexSPI LUT Sequence structure +typedef struct _lut_sequence +{ + uint8_t seqNum; //!< Sequence Number, valid number: 1-16 + uint8_t seqId; //!< Sequence Index, valid number: 0-15 + uint16_t reserved; +} flexspi_lut_seq_t; + +//!@brief Flash Configuration Command Type +enum +{ + kDeviceConfigCmdType_Generic, //!< Generic command, for example: configure dummy cycles, drive strength, etc + kDeviceConfigCmdType_QuadEnable, //!< Quad Enable command + kDeviceConfigCmdType_Spi2Xpi, //!< Switch from SPI to DPI/QPI/OPI mode + kDeviceConfigCmdType_Xpi2Spi, //!< Switch from DPI/QPI/OPI to SPI mode + kDeviceConfigCmdType_Spi2NoCmd, //!< Switch to 0-4-4/0-8-8 mode + kDeviceConfigCmdType_Reset, //!< Reset device command +}; + +//!@brief FlexSPI Memory Configuration Block +typedef struct _FlexSPIConfig +{ + uint32_t tag; //!< [0x000-0x003] Tag, fixed value 0x42464346UL + uint32_t version; //!< [0x004-0x007] Version,[31:24] -'V', [23:16] - Major, [15:8] - Minor, [7:0] - bugfix + uint32_t reserved0; //!< [0x008-0x00b] Reserved for future use + uint8_t readSampleClkSrc; //!< [0x00c-0x00c] Read Sample Clock Source, valid value: 0/1/3 + uint8_t csHoldTime; //!< [0x00d-0x00d] CS hold time, default value: 3 + uint8_t csSetupTime; //!< [0x00e-0x00e] CS setup time, default value: 3 + uint8_t columnAddressWidth; //!< [0x00f-0x00f] Column Address with, for HyperBus protocol, it is fixed to 3, For + //! Serial NAND, need to refer to datasheet + uint8_t deviceModeCfgEnable; //!< [0x010-0x010] Device Mode Configure enable flag, 1 - Enable, 0 - Disable + uint8_t deviceModeType; //!< [0x011-0x011] Specify the configuration command type:Quad Enable, DPI/QPI/OPI switch, + //! Generic configuration, etc. + uint16_t waitTimeCfgCommands; //!< [0x012-0x013] Wait time for all configuration commands, unit: 100us, Used for + //! DPI/QPI/OPI switch or reset command + flexspi_lut_seq_t deviceModeSeq; //!< [0x014-0x017] Device mode sequence info, [7:0] - LUT sequence id, [15:8] - LUt + //! sequence number, [31:16] Reserved + uint32_t deviceModeArg; //!< [0x018-0x01b] Argument/Parameter for device configuration + uint8_t configCmdEnable; //!< [0x01c-0x01c] Configure command Enable Flag, 1 - Enable, 0 - Disable + uint8_t configModeType[3]; //!< [0x01d-0x01f] Configure Mode Type, similar as deviceModeTpe + flexspi_lut_seq_t + configCmdSeqs[3]; //!< [0x020-0x02b] Sequence info for Device Configuration command, similar as deviceModeSeq + uint32_t reserved1; //!< [0x02c-0x02f] Reserved for future use + uint32_t configCmdArgs[3]; //!< [0x030-0x03b] Arguments/Parameters for device Configuration commands + uint32_t reserved2; //!< [0x03c-0x03f] Reserved for future use + uint32_t controllerMiscOption; //!< [0x040-0x043] Controller Misc Options, see Misc feature bit definitions for more + //! details + uint8_t deviceType; //!< [0x044-0x044] Device Type: See Flash Type Definition for more details + uint8_t sflashPadType; //!< [0x045-0x045] Serial Flash Pad Type: 1 - Single, 2 - Dual, 4 - Quad, 8 - Octal + uint8_t serialClkFreq; //!< [0x046-0x046] Serial Flash Frequencey, device specific definitions, See System Boot + //! Chapter for more details + uint8_t lutCustomSeqEnable; //!< [0x047-0x047] LUT customization Enable, it is required if the program/erase cannot + //! be done using 1 LUT sequence, currently, only applicable to HyperFLASH + uint32_t reserved3[2]; //!< [0x048-0x04f] Reserved for future use + uint32_t sflashA1Size; //!< [0x050-0x053] Size of Flash connected to A1 + uint32_t sflashA2Size; //!< [0x054-0x057] Size of Flash connected to A2 + uint32_t sflashB1Size; //!< [0x058-0x05b] Size of Flash connected to B1 + uint32_t sflashB2Size; //!< [0x05c-0x05f] Size of Flash connected to B2 + uint32_t csPadSettingOverride; //!< [0x060-0x063] CS pad setting override value + uint32_t sclkPadSettingOverride; //!< [0x064-0x067] SCK pad setting override value + uint32_t dataPadSettingOverride; //!< [0x068-0x06b] data pad setting override value + uint32_t dqsPadSettingOverride; //!< [0x06c-0x06f] DQS pad setting override value + uint32_t timeoutInMs; //!< [0x070-0x073] Timeout threshold for read status command + uint32_t commandInterval; //!< [0x074-0x077] CS deselect interval between two commands + uint16_t dataValidTime[2]; //!< [0x078-0x07b] CLK edge to data valid time for PORT A and PORT B, in terms of 0.1ns + uint16_t busyOffset; //!< [0x07c-0x07d] Busy offset, valid value: 0-31 + uint16_t busyBitPolarity; //!< [0x07e-0x07f] Busy flag polarity, 0 - busy flag is 1 when flash device is busy, 1 - + //! busy flag is 0 when flash device is busy + uint32_t lookupTable[64]; //!< [0x080-0x17f] Lookup table holds Flash command sequences + flexspi_lut_seq_t lutCustomSeq[12]; //!< [0x180-0x1af] Customizable LUT Sequences + uint32_t reserved4[4]; //!< [0x1b0-0x1bf] Reserved for future use +} flexspi_mem_config_t; + +/* */ +#define NOR_CMD_INDEX_READ CMD_INDEX_READ //!< 0 +#define NOR_CMD_INDEX_READSTATUS CMD_INDEX_READSTATUS //!< 1 +#define NOR_CMD_INDEX_WRITEENABLE CMD_INDEX_WRITEENABLE //!< 2 +#define NOR_CMD_INDEX_ERASESECTOR 3 //!< 3 +#define NOR_CMD_INDEX_PAGEPROGRAM CMD_INDEX_WRITE //!< 4 +#define NOR_CMD_INDEX_CHIPERASE 5 //!< 5 +#define NOR_CMD_INDEX_DUMMY 6 //!< 6 +#define NOR_CMD_INDEX_ERASEBLOCK 7 //!< 7 + +#define NOR_CMD_LUT_SEQ_IDX_READ CMD_LUT_SEQ_IDX_READ //!< 0 READ LUT sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_READSTATUS \ + CMD_LUT_SEQ_IDX_READSTATUS //!< 1 Read Status LUT sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_READSTATUS_XPI \ + 2 //!< 2 Read status DPI/QPI/OPI sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_WRITEENABLE \ + CMD_LUT_SEQ_IDX_WRITEENABLE //!< 3 Write Enable sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_WRITEENABLE_XPI \ + 4 //!< 4 Write Enable DPI/QPI/OPI sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_ERASESECTOR 5 //!< 5 Erase Sector sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_ERASEBLOCK 8 //!< 8 Erase Block sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_PAGEPROGRAM \ + CMD_LUT_SEQ_IDX_WRITE //!< 9 Program sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_CHIPERASE 11 //!< 11 Chip Erase sequence in lookupTable id stored in config block +#define NOR_CMD_LUT_SEQ_IDX_READ_SFDP 13 //!< 13 Read SFDP sequence in lookupTable id stored in config block +#define NOR_CMD_LUT_SEQ_IDX_RESTORE_NOCMD \ + 14 //!< 14 Restore 0-4-4/0-8-8 mode sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_EXIT_NOCMD \ + 15 //!< 15 Exit 0-4-4/0-8-8 mode sequence id in lookupTable stored in config blobk + +/* + * Serial NOR configuration block + */ +typedef struct _flexspi_nor_config +{ + flexspi_mem_config_t memConfig; //!< Common memory configuration info via FlexSPI + uint32_t pageSize; //!< Page size of Serial NOR + uint32_t sectorSize; //!< Sector size of Serial NOR + uint8_t ipcmdSerialClkFreq; //!< Clock frequency for IP command + uint8_t isUniformBlockSize; //!< Sector/Block size is the same + uint8_t reserved0[2]; //!< Reserved for future use + uint8_t serialNorType; //!< Serial NOR Flash type: 0/1/2/3 + uint8_t needExitNoCmdMode; //!< Need to exit NoCmd mode before other IP command + uint8_t halfClkForNonReadCmd; //!< Half the Serial Clock for non-read command: true/false + uint8_t needRestoreNoCmdMode; //!< Need to Restore NoCmd mode after IP commmand execution + uint32_t blockSize; //!< Block size + uint32_t reserve2[11]; //!< Reserved for future use +} flexspi_nor_config_t; + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef __cplusplus +} +#endif +#endif /* __EVKMIMXRT1015_FLEXSPI_NOR_CONFIG__ */ diff --git a/hw/bsp/mimxrt1015_evk/mimxrt1015_evk.c b/hw/bsp/mimxrt1015_evk/mimxrt1015_evk.c new file mode 100644 index 00000000..95534488 --- /dev/null +++ b/hw/bsp/mimxrt1015_evk/mimxrt1015_evk.c @@ -0,0 +1,170 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2018, hathach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#include "../board.h" +#include "fsl_device_registers.h" +#include "fsl_gpio.h" +#include "fsl_iomuxc.h" +#include "fsl_clock.h" +#include "fsl_lpuart.h" + +#include "clock_config.h" + +#define LED_PINMUX IOMUXC_GPIO_SD_B1_01_GPIO3_IO21 +#define LED_PORT GPIO3 +#define LED_PIN 21 +#define LED_STATE_ON 0 + +// SW8 button +#define BUTTON_PINMUX IOMUXC_GPIO_EMC_09_GPIO2_IO09 +#define BUTTON_PORT GPIO2 +#define BUTTON_PIN 9 +#define BUTTON_STATE_ACTIVE 0 + +// UART +#define UART_PORT LPUART1 +#define UART_RX_PINMUX IOMUXC_GPIO_AD_B0_07_LPUART1_RX +#define UART_TX_PINMUX IOMUXC_GPIO_AD_B0_06_LPUART1_TX + +const uint8_t dcd_data[] = { 0x00 }; + +void board_init(void) +{ + // Init clock + BOARD_BootClockRUN(); + SystemCoreClockUpdate(); + + // Enable IOCON clock + CLOCK_EnableClock(kCLOCK_Iomuxc); + +#if CFG_TUSB_OS == OPT_OS_NONE + // 1ms tick timer + SysTick_Config(SystemCoreClock / 1000); +#elif CFG_TUSB_OS == OPT_OS_FREERTOS + // If freeRTOS is used, IRQ priority is limit by max syscall ( smaller is higher ) +// NVIC_SetPriority(USB0_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY ); +#endif + + // LED + IOMUXC_SetPinMux( LED_PINMUX, 0U); + IOMUXC_SetPinConfig( LED_PINMUX, 0x10B0U); + + gpio_pin_config_t led_config = { kGPIO_DigitalOutput, 0, kGPIO_NoIntmode }; + GPIO_PinInit(LED_PORT, LED_PIN, &led_config); + board_led_write(true); + + // Button + IOMUXC_SetPinMux( BUTTON_PINMUX, 0U); + IOMUXC_SetPinConfig(BUTTON_PINMUX, 0x01B0A0U); + gpio_pin_config_t button_config = { kGPIO_DigitalInput, 0, kGPIO_IntRisingEdge, }; + GPIO_PinInit(BUTTON_PORT, BUTTON_PIN, &button_config); + + // UART + IOMUXC_SetPinMux( UART_TX_PINMUX, 0U); + IOMUXC_SetPinMux( UART_RX_PINMUX, 0U); + IOMUXC_SetPinConfig( UART_TX_PINMUX, 0x10B0u); + IOMUXC_SetPinConfig( UART_RX_PINMUX, 0x10B0u); + + lpuart_config_t uart_config; + LPUART_GetDefaultConfig(&uart_config); + uart_config.baudRate_Bps = CFG_BOARD_UART_BAUDRATE; + uart_config.enableTx = true; + uart_config.enableRx = true; + LPUART_Init(UART_PORT, &uart_config, (CLOCK_GetPllFreq(kCLOCK_PllUsb1) / 6U) / (CLOCK_GetDiv(kCLOCK_UartDiv) + 1U)); + + //------------- USB0 -------------// + // Clock + CLOCK_EnableUsbhs0PhyPllClock(kCLOCK_Usbphy480M, 480000000U); + CLOCK_EnableUsbhs0Clock(kCLOCK_Usb480M, 480000000U); + + USBPHY_Type* usb_phy = USBPHY; + + // Enable PHY support for Low speed device + LS via FS Hub + usb_phy->CTRL |= USBPHY_CTRL_SET_ENUTMILEVEL2_MASK | USBPHY_CTRL_SET_ENUTMILEVEL3_MASK; + + // Enable all power for normal operation + usb_phy->PWD = 0; + + // TX Timing + uint32_t phytx = usb_phy->TX; + phytx &= ~(USBPHY_TX_D_CAL_MASK | USBPHY_TX_TXCAL45DM_MASK | USBPHY_TX_TXCAL45DP_MASK); + phytx |= USBPHY_TX_D_CAL(0x0C) | USBPHY_TX_TXCAL45DP(0x06) | USBPHY_TX_TXCAL45DM(0x06); + usb_phy->TX = phytx; +} + +//--------------------------------------------------------------------+ +// USB Interrupt Handler +//--------------------------------------------------------------------+ +void USB_OTG1_IRQHandler(void) +{ + #if CFG_TUSB_RHPORT0_MODE & OPT_MODE_HOST + tuh_isr(0); + #endif + + #if CFG_TUSB_RHPORT0_MODE & OPT_MODE_DEVICE + tud_isr(0); + #endif +} + +//--------------------------------------------------------------------+ +// Board porting API +//--------------------------------------------------------------------+ + +void board_led_write(bool state) +{ + GPIO_PinWrite(LED_PORT, LED_PIN, state ? LED_STATE_ON : (1-LED_STATE_ON)); +} + +uint32_t board_button_read(void) +{ + // active low + return BUTTON_STATE_ACTIVE == GPIO_PinRead(BUTTON_PORT, BUTTON_PIN); +} + +int board_uart_read(uint8_t* buf, int len) +{ + LPUART_ReadBlocking(UART_PORT, buf, len); + return len; +} + +int board_uart_write(void const * buf, int len) +{ + LPUART_WriteBlocking(UART_PORT, (uint8_t*)buf, len); + return len; +} + +#if CFG_TUSB_OS == OPT_OS_NONE +volatile uint32_t system_ticks = 0; +void SysTick_Handler(void) +{ + system_ticks++; +} + +uint32_t board_millis(void) +{ + return system_ticks; +} +#endif diff --git a/hw/bsp/mimxrt1020_evk/board.mk b/hw/bsp/mimxrt1020_evk/board.mk index 538626e9..83a57085 100644 --- a/hw/bsp/mimxrt1020_evk/board.mk +++ b/hw/bsp/mimxrt1020_evk/board.mk @@ -8,9 +8,7 @@ CFLAGS += \ -DCPU_MIMXRT1021DAG5A \ -DXIP_EXTERNAL_FLASH=1 \ -DXIP_BOOT_HEADER_ENABLE=1 \ - -DCFG_TUSB_MCU=OPT_MCU_MIMXRT10XX \ - -DCFG_TUSB_MEM_SECTION='__attribute__((section(".data")))' \ - -DCFG_TUSB_MEM_ALIGN='__attribute__((aligned(64)))' + -DCFG_TUSB_MCU=OPT_MCU_MIMXRT10XX # mcu driver cause following warnings #CFLAGS += -Wno-error=float-equal -Wno-error=nested-externs @@ -47,7 +45,7 @@ CHIP_FAMILY = transdimension FREERTOS_PORT = ARM_CM7 # For flash-jlink target -JLINK_DEVICE = CPU_MIMXRT1021DAG5A +JLINK_DEVICE = MIMXRT1021DAG5A JLINK_IF = swd # flash by copying bin file to DAP Mass Storage diff --git a/hw/bsp/mimxrt1050_evkb/board.mk b/hw/bsp/mimxrt1050_evkb/board.mk index b455b060..2303df11 100644 --- a/hw/bsp/mimxrt1050_evkb/board.mk +++ b/hw/bsp/mimxrt1050_evkb/board.mk @@ -8,9 +8,7 @@ CFLAGS += \ -DCPU_MIMXRT1052DVL6B \ -DXIP_EXTERNAL_FLASH=1 \ -DXIP_BOOT_HEADER_ENABLE=1 \ - -DCFG_TUSB_MCU=OPT_MCU_MIMXRT10XX \ - -DCFG_TUSB_MEM_SECTION='__attribute__((section(".data")))' \ - -DCFG_TUSB_MEM_ALIGN='__attribute__((aligned(64)))' + -DCFG_TUSB_MCU=OPT_MCU_MIMXRT10XX # mcu driver cause following warnings #CFLAGS += -Wno-error=float-equal -Wno-error=nested-externs diff --git a/hw/bsp/mimxrt1060_evk/board.mk b/hw/bsp/mimxrt1060_evk/board.mk index d42da8cb..4bfc48bb 100644 --- a/hw/bsp/mimxrt1060_evk/board.mk +++ b/hw/bsp/mimxrt1060_evk/board.mk @@ -8,9 +8,7 @@ CFLAGS += \ -DCPU_MIMXRT1062DVL6A \ -DXIP_EXTERNAL_FLASH=1 \ -DXIP_BOOT_HEADER_ENABLE=1 \ - -DCFG_TUSB_MCU=OPT_MCU_MIMXRT10XX \ - -DCFG_TUSB_MEM_SECTION='__attribute__((section(".data")))' \ - -DCFG_TUSB_MEM_ALIGN='__attribute__((aligned(64)))' + -DCFG_TUSB_MCU=OPT_MCU_MIMXRT10XX # mcu driver cause following warnings #CFLAGS += -Wno-error=float-equal -Wno-error=nested-externs diff --git a/hw/bsp/mimxrt1064_evk/board.mk b/hw/bsp/mimxrt1064_evk/board.mk index 7bb0c637..7b992da3 100644 --- a/hw/bsp/mimxrt1064_evk/board.mk +++ b/hw/bsp/mimxrt1064_evk/board.mk @@ -8,9 +8,7 @@ CFLAGS += \ -DCPU_MIMXRT1064DVL6A \ -DXIP_EXTERNAL_FLASH=1 \ -DXIP_BOOT_HEADER_ENABLE=1 \ - -DCFG_TUSB_MCU=OPT_MCU_MIMXRT10XX \ - -DCFG_TUSB_MEM_SECTION='__attribute__((section(".data")))' \ - -DCFG_TUSB_MEM_ALIGN='__attribute__((aligned(64)))' + -DCFG_TUSB_MCU=OPT_MCU_MIMXRT10XX # mcu driver cause following warnings #CFLAGS += -Wno-error=float-equal -Wno-error=nested-externs From 9758f3e461f031b88d630dfb89757d2cbea809d5 Mon Sep 17 00:00:00 2001 From: hathach Date: Sat, 23 Nov 2019 01:11:37 +0700 Subject: [PATCH 086/267] doc update --- README.md | 2 +- docs/boards.md | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index d983dadd..8226ead5 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ The stack supports the following MCUs - **Nordic:** nRF52840, nRF52833 - **NXP:** - LPC Series: 11Uxx, 13xx, 175x_6x, 177x_8x, 18xx, 40xx, 43xx, 51Uxx, 54xxx, 55xx - - iMX RT Series: RT1021, RT1052, RT1062, RT1064 + - iMX RT Series: RT1015, RT1021, RT1052, RT1062, RT1064 - **Sony:** CXD56 - **ST:** STM32 series: L0, F0, F1, F2, F3, F4, F7, H7 (device only) - **Tomu:** [valentyusb](https://github.com/im-tomu/valentyusb) (eptri) diff --git a/docs/boards.md b/docs/boards.md index 305f06fe..391d40a8 100644 --- a/docs/boards.md +++ b/docs/boards.md @@ -28,6 +28,7 @@ This code base already had supported for a handful of following boards ### NXP iMX RT +- [MIMX RT1015 Evaluation Kit](https://www.nxp.com/design/development-boards/i.mx-evaluation-and-development-boards/i.mx-rt1015-evaluation-kit:MIMXRT1015-EVK) - [MIMX RT1020 Evaluation Kit](https://www.nxp.com/design/development-boards/i.mx-evaluation-and-development-boards/i.mx-rt1020-evaluation-kit:MIMXRT1020-EVK) - [MIMX RT1050 Evaluation Kit](https://www.nxp.com/design/development-boards/i.mx-evaluation-and-development-boards/i.mx-rt1050-evaluation-kit:MIMXRT1050-EVK) - [MIMX RT1060 Evaluation Kit](https://www.nxp.com/design/development-boards/i.mx-evaluation-and-development-boards/mimxrt1060-evk-i.mx-rt1060-evaluation-kit:MIMXRT1060-EVK) From 778cff19c121cddf88b05d92eecdf97ff1c4bbbd Mon Sep 17 00:00:00 2001 From: hathach Date: Sat, 23 Nov 2019 21:18:40 +0700 Subject: [PATCH 087/267] added rt1010 board support not tested on the actual hardware board though. --- hw/bsp/mimxrt1010_evk/board.h | 36 +++ hw/bsp/mimxrt1010_evk/board.mk | 52 ++++ .../evkmimxrt1010_flexspi_nor_config.c | 48 ++++ .../evkmimxrt1010_flexspi_nor_config.h | 267 ++++++++++++++++++ hw/bsp/mimxrt1010_evk/mimxrt1010_evk.c | 170 +++++++++++ 5 files changed, 573 insertions(+) create mode 100644 hw/bsp/mimxrt1010_evk/board.h create mode 100644 hw/bsp/mimxrt1010_evk/board.mk create mode 100644 hw/bsp/mimxrt1010_evk/evkmimxrt1010_flexspi_nor_config.c create mode 100644 hw/bsp/mimxrt1010_evk/evkmimxrt1010_flexspi_nor_config.h create mode 100644 hw/bsp/mimxrt1010_evk/mimxrt1010_evk.c diff --git a/hw/bsp/mimxrt1010_evk/board.h b/hw/bsp/mimxrt1010_evk/board.h new file mode 100644 index 00000000..7e4b5729 --- /dev/null +++ b/hw/bsp/mimxrt1010_evk/board.h @@ -0,0 +1,36 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019, Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + + +#ifndef BOARD_H_ +#define BOARD_H_ + +#include "fsl_device_registers.h" + +// required since iMX RT10xx SDK include this file for board size +#define BOARD_FLASH_SIZE (0x1000000U) + +#endif /* BOARD_H_ */ diff --git a/hw/bsp/mimxrt1010_evk/board.mk b/hw/bsp/mimxrt1010_evk/board.mk new file mode 100644 index 00000000..24a3dbdc --- /dev/null +++ b/hw/bsp/mimxrt1010_evk/board.mk @@ -0,0 +1,52 @@ +CFLAGS += \ + -mthumb \ + -mabi=aapcs \ + -mcpu=cortex-m7 \ + -mfloat-abi=hard \ + -mfpu=fpv5-d16 \ + -D__ARMVFP__=0 -D__ARMFPV5__=0\ + -DCPU_MIMXRT1011DAE5A \ + -DXIP_EXTERNAL_FLASH=1 \ + -DXIP_BOOT_HEADER_ENABLE=1 \ + -DCFG_TUSB_MCU=OPT_MCU_MIMXRT10XX + +# mcu driver cause following warnings +CFLAGS += -Wno-error=unused-parameter -Wno-error=implicit-fallthrough= + +MCU_DIR = hw/mcu/nxp/sdk/devices/MIMXRT1011 + +# All source paths should be relative to the top level. +LD_FILE = $(MCU_DIR)/gcc/MIMXRT1011xxxxx_flexspi_nor.ld + +SRC_C += \ + $(MCU_DIR)/system_MIMXRT1011.c \ + $(MCU_DIR)/xip/fsl_flexspi_nor_boot.c \ + $(MCU_DIR)/project_template/clock_config.c \ + $(MCU_DIR)/drivers/fsl_clock.c \ + $(MCU_DIR)/drivers/fsl_gpio.c \ + $(MCU_DIR)/drivers/fsl_common.c \ + $(MCU_DIR)/drivers/fsl_lpuart.c + +INC += \ + $(TOP)/hw/bsp/$(BOARD) \ + $(TOP)/$(MCU_DIR)/../../CMSIS/Include \ + $(TOP)/$(MCU_DIR) \ + $(TOP)/$(MCU_DIR)/drivers \ + $(TOP)/$(MCU_DIR)/project_template \ + +SRC_S += $(MCU_DIR)/gcc/startup_MIMXRT1011.S + +# For TinyUSB port source +VENDOR = nxp +CHIP_FAMILY = transdimension + +# For freeRTOS port source +FREERTOS_PORT = ARM_CM7 + +# For flash-jlink target +JLINK_DEVICE = MIMXRT1011DAE5A +JLINK_IF = swd + +# flash by copying bin file to DAP Mass Storage +flash: $(BUILD)/$(BOARD)-firmware.bin + cp $< /media/$(USER)/RT1010-EVK/ diff --git a/hw/bsp/mimxrt1010_evk/evkmimxrt1010_flexspi_nor_config.c b/hw/bsp/mimxrt1010_evk/evkmimxrt1010_flexspi_nor_config.c new file mode 100644 index 00000000..cd50a93d --- /dev/null +++ b/hw/bsp/mimxrt1010_evk/evkmimxrt1010_flexspi_nor_config.c @@ -0,0 +1,48 @@ +/* + * Copyright 2019 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include "evkmimxrt1010_flexspi_nor_config.h" + +/* Component ID definition, used by tools. */ +#ifndef FSL_COMPONENT_ID +#define FSL_COMPONENT_ID "platform.drivers.xip_board" +#endif + +/******************************************************************************* + * Code + ******************************************************************************/ +#if defined(XIP_BOOT_HEADER_ENABLE) && (XIP_BOOT_HEADER_ENABLE == 1) +#if defined(__CC_ARM) || defined(__ARMCC_VERSION) || defined(__GNUC__) +__attribute__((section(".boot_hdr.conf"))) +#elif defined(__ICCARM__) +#pragma location = ".boot_hdr.conf" +#endif + +const flexspi_nor_config_t qspiflash_config = { + .memConfig = + { + .tag = FLEXSPI_CFG_BLK_TAG, + .version = FLEXSPI_CFG_BLK_VERSION, + .readSampleClkSrc = kFlexSPIReadSampleClk_LoopbackFromDqsPad, + .csHoldTime = 3u, + .csSetupTime = 3u, + .sflashPadType = kSerialFlash_4Pads, + .serialClkFreq = kFlexSpiSerialClk_100MHz, + .sflashA1Size = 16u * 1024u * 1024u, + .lookupTable = + { + // Read LUTs + FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0xEB, RADDR_SDR, FLEXSPI_4PAD, 0x18), + FLEXSPI_LUT_SEQ(DUMMY_SDR, FLEXSPI_4PAD, 0x06, READ_SDR, FLEXSPI_4PAD, 0x04), + }, + }, + .pageSize = 256u, + .sectorSize = 4u * 1024u, + .blockSize = 256u * 1024u, + .isUniformBlockSize = false, +}; +#endif /* XIP_BOOT_HEADER_ENABLE */ diff --git a/hw/bsp/mimxrt1010_evk/evkmimxrt1010_flexspi_nor_config.h b/hw/bsp/mimxrt1010_evk/evkmimxrt1010_flexspi_nor_config.h new file mode 100644 index 00000000..4be2760b --- /dev/null +++ b/hw/bsp/mimxrt1010_evk/evkmimxrt1010_flexspi_nor_config.h @@ -0,0 +1,267 @@ +/* + * Copyright 2019 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef __EVKMIMXRT1011_FLEXSPI_NOR_CONFIG__ +#define __EVKMIMXRT1011_FLEXSPI_NOR_CONFIG__ + +#include +#include +#include "fsl_common.h" + +/*! @name Driver version */ +/*@{*/ +/*! @brief XIP_BOARD driver version 2.0.0. */ +#define FSL_XIP_BOARD_DRIVER_VERSION (MAKE_VERSION(2, 0, 0)) +/*@}*/ + +/* FLEXSPI memory config block related defintions */ +#define FLEXSPI_CFG_BLK_TAG (0x42464346UL) // ascii "FCFB" Big Endian +#define FLEXSPI_CFG_BLK_VERSION (0x56010400UL) // V1.4.0 +#define FLEXSPI_CFG_BLK_SIZE (512) + +/* FLEXSPI Feature related definitions */ +#define FLEXSPI_FEATURE_HAS_PARALLEL_MODE 1 + +/* Lookup table related defintions */ +#define CMD_INDEX_READ 0 +#define CMD_INDEX_READSTATUS 1 +#define CMD_INDEX_WRITEENABLE 2 +#define CMD_INDEX_WRITE 4 + +#define CMD_LUT_SEQ_IDX_READ 0 +#define CMD_LUT_SEQ_IDX_READSTATUS 1 +#define CMD_LUT_SEQ_IDX_WRITEENABLE 3 +#define CMD_LUT_SEQ_IDX_WRITE 9 + +#define CMD_SDR 0x01 +#define CMD_DDR 0x21 +#define RADDR_SDR 0x02 +#define RADDR_DDR 0x22 +#define CADDR_SDR 0x03 +#define CADDR_DDR 0x23 +#define MODE1_SDR 0x04 +#define MODE1_DDR 0x24 +#define MODE2_SDR 0x05 +#define MODE2_DDR 0x25 +#define MODE4_SDR 0x06 +#define MODE4_DDR 0x26 +#define MODE8_SDR 0x07 +#define MODE8_DDR 0x27 +#define WRITE_SDR 0x08 +#define WRITE_DDR 0x28 +#define READ_SDR 0x09 +#define READ_DDR 0x29 +#define LEARN_SDR 0x0A +#define LEARN_DDR 0x2A +#define DATSZ_SDR 0x0B +#define DATSZ_DDR 0x2B +#define DUMMY_SDR 0x0C +#define DUMMY_DDR 0x2C +#define DUMMY_RWDS_SDR 0x0D +#define DUMMY_RWDS_DDR 0x2D +#define JMP_ON_CS 0x1F +#define STOP 0 + +#define FLEXSPI_1PAD 0 +#define FLEXSPI_2PAD 1 +#define FLEXSPI_4PAD 2 +#define FLEXSPI_8PAD 3 + +#define FLEXSPI_LUT_SEQ(cmd0, pad0, op0, cmd1, pad1, op1) \ + (FLEXSPI_LUT_OPERAND0(op0) | FLEXSPI_LUT_NUM_PADS0(pad0) | FLEXSPI_LUT_OPCODE0(cmd0) | FLEXSPI_LUT_OPERAND1(op1) | \ + FLEXSPI_LUT_NUM_PADS1(pad1) | FLEXSPI_LUT_OPCODE1(cmd1)) + +//!@brief Definitions for FlexSPI Serial Clock Frequency +typedef enum _FlexSpiSerialClockFreq +{ + kFlexSpiSerialClk_30MHz = 1, + kFlexSpiSerialClk_50MHz = 2, + kFlexSpiSerialClk_60MHz = 3, + kFlexSpiSerialClk_75MHz = 4, + kFlexSpiSerialClk_80MHz = 5, + kFlexSpiSerialClk_100MHz = 6, + kFlexSpiSerialClk_120MHz = 7, + kFlexSpiSerialClk_133MHz = 8, +} flexspi_serial_clk_freq_t; + +//!@brief FlexSPI clock configuration type +enum +{ + kFlexSpiClk_SDR, //!< Clock configure for SDR mode + kFlexSpiClk_DDR, //!< Clock configurat for DDR mode +}; + +//!@brief FlexSPI Read Sample Clock Source definition +typedef enum _FlashReadSampleClkSource +{ + kFlexSPIReadSampleClk_LoopbackInternally = 0, + kFlexSPIReadSampleClk_LoopbackFromDqsPad = 1, + kFlexSPIReadSampleClk_LoopbackFromSckPad = 2, + kFlexSPIReadSampleClk_ExternalInputFromDqsPad = 3, +} flexspi_read_sample_clk_t; + +//!@brief Misc feature bit definitions +enum +{ + kFlexSpiMiscOffset_DiffClkEnable = 0, //!< Bit for Differential clock enable + kFlexSpiMiscOffset_Ck2Enable = 1, //!< Bit for CK2 enable + kFlexSpiMiscOffset_ParallelEnable = 2, //!< Bit for Parallel mode enable + kFlexSpiMiscOffset_WordAddressableEnable = 3, //!< Bit for Word Addressable enable + kFlexSpiMiscOffset_SafeConfigFreqEnable = 4, //!< Bit for Safe Configuration Frequency enable + kFlexSpiMiscOffset_PadSettingOverrideEnable = 5, //!< Bit for Pad setting override enable + kFlexSpiMiscOffset_DdrModeEnable = 6, //!< Bit for DDR clock confiuration indication. +}; + +//!@brief Flash Type Definition +enum +{ + kFlexSpiDeviceType_SerialNOR = 1, //!< Flash devices are Serial NOR + kFlexSpiDeviceType_SerialNAND = 2, //!< Flash devices are Serial NAND + kFlexSpiDeviceType_SerialRAM = 3, //!< Flash devices are Serial RAM/HyperFLASH + kFlexSpiDeviceType_MCP_NOR_NAND = 0x12, //!< Flash device is MCP device, A1 is Serial NOR, A2 is Serial NAND + kFlexSpiDeviceType_MCP_NOR_RAM = 0x13, //!< Flash deivce is MCP device, A1 is Serial NOR, A2 is Serial RAMs +}; + +//!@brief Flash Pad Definitions +enum +{ + kSerialFlash_1Pad = 1, + kSerialFlash_2Pads = 2, + kSerialFlash_4Pads = 4, + kSerialFlash_8Pads = 8, +}; + +//!@brief FlexSPI LUT Sequence structure +typedef struct _lut_sequence +{ + uint8_t seqNum; //!< Sequence Number, valid number: 1-16 + uint8_t seqId; //!< Sequence Index, valid number: 0-15 + uint16_t reserved; +} flexspi_lut_seq_t; + +//!@brief Flash Configuration Command Type +enum +{ + kDeviceConfigCmdType_Generic, //!< Generic command, for example: configure dummy cycles, drive strength, etc + kDeviceConfigCmdType_QuadEnable, //!< Quad Enable command + kDeviceConfigCmdType_Spi2Xpi, //!< Switch from SPI to DPI/QPI/OPI mode + kDeviceConfigCmdType_Xpi2Spi, //!< Switch from DPI/QPI/OPI to SPI mode + kDeviceConfigCmdType_Spi2NoCmd, //!< Switch to 0-4-4/0-8-8 mode + kDeviceConfigCmdType_Reset, //!< Reset device command +}; + +//!@brief FlexSPI Memory Configuration Block +typedef struct _FlexSPIConfig +{ + uint32_t tag; //!< [0x000-0x003] Tag, fixed value 0x42464346UL + uint32_t version; //!< [0x004-0x007] Version,[31:24] -'V', [23:16] - Major, [15:8] - Minor, [7:0] - bugfix + uint32_t reserved0; //!< [0x008-0x00b] Reserved for future use + uint8_t readSampleClkSrc; //!< [0x00c-0x00c] Read Sample Clock Source, valid value: 0/1/3 + uint8_t csHoldTime; //!< [0x00d-0x00d] CS hold time, default value: 3 + uint8_t csSetupTime; //!< [0x00e-0x00e] CS setup time, default value: 3 + uint8_t columnAddressWidth; //!< [0x00f-0x00f] Column Address with, for HyperBus protocol, it is fixed to 3, For + //! Serial NAND, need to refer to datasheet + uint8_t deviceModeCfgEnable; //!< [0x010-0x010] Device Mode Configure enable flag, 1 - Enable, 0 - Disable + uint8_t deviceModeType; //!< [0x011-0x011] Specify the configuration command type:Quad Enable, DPI/QPI/OPI switch, + //! Generic configuration, etc. + uint16_t waitTimeCfgCommands; //!< [0x012-0x013] Wait time for all configuration commands, unit: 100us, Used for + //! DPI/QPI/OPI switch or reset command + flexspi_lut_seq_t deviceModeSeq; //!< [0x014-0x017] Device mode sequence info, [7:0] - LUT sequence id, [15:8] - LUt + //! sequence number, [31:16] Reserved + uint32_t deviceModeArg; //!< [0x018-0x01b] Argument/Parameter for device configuration + uint8_t configCmdEnable; //!< [0x01c-0x01c] Configure command Enable Flag, 1 - Enable, 0 - Disable + uint8_t configModeType[3]; //!< [0x01d-0x01f] Configure Mode Type, similar as deviceModeTpe + flexspi_lut_seq_t + configCmdSeqs[3]; //!< [0x020-0x02b] Sequence info for Device Configuration command, similar as deviceModeSeq + uint32_t reserved1; //!< [0x02c-0x02f] Reserved for future use + uint32_t configCmdArgs[3]; //!< [0x030-0x03b] Arguments/Parameters for device Configuration commands + uint32_t reserved2; //!< [0x03c-0x03f] Reserved for future use + uint32_t controllerMiscOption; //!< [0x040-0x043] Controller Misc Options, see Misc feature bit definitions for more + //! details + uint8_t deviceType; //!< [0x044-0x044] Device Type: See Flash Type Definition for more details + uint8_t sflashPadType; //!< [0x045-0x045] Serial Flash Pad Type: 1 - Single, 2 - Dual, 4 - Quad, 8 - Octal + uint8_t serialClkFreq; //!< [0x046-0x046] Serial Flash Frequencey, device specific definitions, See System Boot + //! Chapter for more details + uint8_t lutCustomSeqEnable; //!< [0x047-0x047] LUT customization Enable, it is required if the program/erase cannot + //! be done using 1 LUT sequence, currently, only applicable to HyperFLASH + uint32_t reserved3[2]; //!< [0x048-0x04f] Reserved for future use + uint32_t sflashA1Size; //!< [0x050-0x053] Size of Flash connected to A1 + uint32_t sflashA2Size; //!< [0x054-0x057] Size of Flash connected to A2 + uint32_t sflashB1Size; //!< [0x058-0x05b] Size of Flash connected to B1 + uint32_t sflashB2Size; //!< [0x05c-0x05f] Size of Flash connected to B2 + uint32_t csPadSettingOverride; //!< [0x060-0x063] CS pad setting override value + uint32_t sclkPadSettingOverride; //!< [0x064-0x067] SCK pad setting override value + uint32_t dataPadSettingOverride; //!< [0x068-0x06b] data pad setting override value + uint32_t dqsPadSettingOverride; //!< [0x06c-0x06f] DQS pad setting override value + uint32_t timeoutInMs; //!< [0x070-0x073] Timeout threshold for read status command + uint32_t commandInterval; //!< [0x074-0x077] CS deselect interval between two commands + uint16_t dataValidTime[2]; //!< [0x078-0x07b] CLK edge to data valid time for PORT A and PORT B, in terms of 0.1ns + uint16_t busyOffset; //!< [0x07c-0x07d] Busy offset, valid value: 0-31 + uint16_t busyBitPolarity; //!< [0x07e-0x07f] Busy flag polarity, 0 - busy flag is 1 when flash device is busy, 1 - + //! busy flag is 0 when flash device is busy + uint32_t lookupTable[64]; //!< [0x080-0x17f] Lookup table holds Flash command sequences + flexspi_lut_seq_t lutCustomSeq[12]; //!< [0x180-0x1af] Customizable LUT Sequences + uint32_t reserved4[4]; //!< [0x1b0-0x1bf] Reserved for future use +} flexspi_mem_config_t; + +/* */ +#define NOR_CMD_INDEX_READ CMD_INDEX_READ //!< 0 +#define NOR_CMD_INDEX_READSTATUS CMD_INDEX_READSTATUS //!< 1 +#define NOR_CMD_INDEX_WRITEENABLE CMD_INDEX_WRITEENABLE //!< 2 +#define NOR_CMD_INDEX_ERASESECTOR 3 //!< 3 +#define NOR_CMD_INDEX_PAGEPROGRAM CMD_INDEX_WRITE //!< 4 +#define NOR_CMD_INDEX_CHIPERASE 5 //!< 5 +#define NOR_CMD_INDEX_DUMMY 6 //!< 6 +#define NOR_CMD_INDEX_ERASEBLOCK 7 //!< 7 + +#define NOR_CMD_LUT_SEQ_IDX_READ CMD_LUT_SEQ_IDX_READ //!< 0 READ LUT sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_READSTATUS \ + CMD_LUT_SEQ_IDX_READSTATUS //!< 1 Read Status LUT sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_READSTATUS_XPI \ + 2 //!< 2 Read status DPI/QPI/OPI sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_WRITEENABLE \ + CMD_LUT_SEQ_IDX_WRITEENABLE //!< 3 Write Enable sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_WRITEENABLE_XPI \ + 4 //!< 4 Write Enable DPI/QPI/OPI sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_ERASESECTOR 5 //!< 5 Erase Sector sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_ERASEBLOCK 8 //!< 8 Erase Block sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_PAGEPROGRAM \ + CMD_LUT_SEQ_IDX_WRITE //!< 9 Program sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_CHIPERASE 11 //!< 11 Chip Erase sequence in lookupTable id stored in config block +#define NOR_CMD_LUT_SEQ_IDX_READ_SFDP 13 //!< 13 Read SFDP sequence in lookupTable id stored in config block +#define NOR_CMD_LUT_SEQ_IDX_RESTORE_NOCMD \ + 14 //!< 14 Restore 0-4-4/0-8-8 mode sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_EXIT_NOCMD \ + 15 //!< 15 Exit 0-4-4/0-8-8 mode sequence id in lookupTable stored in config blobk + +/* + * Serial NOR configuration block + */ +typedef struct _flexspi_nor_config +{ + flexspi_mem_config_t memConfig; //!< Common memory configuration info via FlexSPI + uint32_t pageSize; //!< Page size of Serial NOR + uint32_t sectorSize; //!< Sector size of Serial NOR + uint8_t ipcmdSerialClkFreq; //!< Clock frequency for IP command + uint8_t isUniformBlockSize; //!< Sector/Block size is the same + uint8_t reserved0[2]; //!< Reserved for future use + uint8_t serialNorType; //!< Serial NOR Flash type: 0/1/2/3 + uint8_t needExitNoCmdMode; //!< Need to exit NoCmd mode before other IP command + uint8_t halfClkForNonReadCmd; //!< Half the Serial Clock for non-read command: true/false + uint8_t needRestoreNoCmdMode; //!< Need to Restore NoCmd mode after IP commmand execution + uint32_t blockSize; //!< Block size + uint32_t reserve2[11]; //!< Reserved for future use +} flexspi_nor_config_t; + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef __cplusplus +} +#endif +#endif /* __EVKMIMXRT1011_FLEXSPI_NOR_CONFIG__ */ diff --git a/hw/bsp/mimxrt1010_evk/mimxrt1010_evk.c b/hw/bsp/mimxrt1010_evk/mimxrt1010_evk.c new file mode 100644 index 00000000..a76e2d9b --- /dev/null +++ b/hw/bsp/mimxrt1010_evk/mimxrt1010_evk.c @@ -0,0 +1,170 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2018, hathach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#include "../board.h" +#include "fsl_device_registers.h" +#include "fsl_gpio.h" +#include "fsl_iomuxc.h" +#include "fsl_clock.h" +#include "fsl_lpuart.h" + +#include "clock_config.h" + +#define LED_PINMUX IOMUXC_GPIO_11_GPIOMUX_IO11 +#define LED_PORT GPIO1 +#define LED_PIN 11 +#define LED_STATE_ON 0 + +// SW8 button +#define BUTTON_PINMUX IOMUXC_GPIO_SD_05_GPIO2_IO05 +#define BUTTON_PORT GPIO2 +#define BUTTON_PIN 5 +#define BUTTON_STATE_ACTIVE 0 + +// UART +#define UART_PORT LPUART1 +#define UART_RX_PINMUX IOMUXC_GPIO_09_LPUART1_RXD +#define UART_TX_PINMUX IOMUXC_GPIO_10_LPUART1_TXD + +const uint8_t dcd_data[] = { 0x00 }; + +void board_init(void) +{ + // Init clock + BOARD_BootClockRUN(); + SystemCoreClockUpdate(); + + // Enable IOCON clock + CLOCK_EnableClock(kCLOCK_Iomuxc); + +#if CFG_TUSB_OS == OPT_OS_NONE + // 1ms tick timer + SysTick_Config(SystemCoreClock / 1000); +#elif CFG_TUSB_OS == OPT_OS_FREERTOS + // If freeRTOS is used, IRQ priority is limit by max syscall ( smaller is higher ) +// NVIC_SetPriority(USB0_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY ); +#endif + + // LED + IOMUXC_SetPinMux( LED_PINMUX, 0U); + IOMUXC_SetPinConfig( LED_PINMUX, 0x10B0U); + + gpio_pin_config_t led_config = { kGPIO_DigitalOutput, 0, kGPIO_NoIntmode }; + GPIO_PinInit(LED_PORT, LED_PIN, &led_config); + board_led_write(true); + + // Button + IOMUXC_SetPinMux( BUTTON_PINMUX, 0U); + IOMUXC_SetPinConfig(BUTTON_PINMUX, 0x01B0A0U); + gpio_pin_config_t button_config = { kGPIO_DigitalInput, 0, kGPIO_IntRisingEdge, }; + GPIO_PinInit(BUTTON_PORT, BUTTON_PIN, &button_config); + + // UART + IOMUXC_SetPinMux( UART_TX_PINMUX, 0U); + IOMUXC_SetPinMux( UART_RX_PINMUX, 0U); + IOMUXC_SetPinConfig( UART_TX_PINMUX, 0x10B0u); + IOMUXC_SetPinConfig( UART_RX_PINMUX, 0x10B0u); + + lpuart_config_t uart_config; + LPUART_GetDefaultConfig(&uart_config); + uart_config.baudRate_Bps = CFG_BOARD_UART_BAUDRATE; + uart_config.enableTx = true; + uart_config.enableRx = true; + LPUART_Init(UART_PORT, &uart_config, (CLOCK_GetPllFreq(kCLOCK_PllUsb1) / 6U) / (CLOCK_GetDiv(kCLOCK_UartDiv) + 1U)); + + //------------- USB0 -------------// + // Clock + CLOCK_EnableUsbhs0PhyPllClock(kCLOCK_Usbphy480M, 480000000U); + CLOCK_EnableUsbhs0Clock(kCLOCK_Usb480M, 480000000U); + + USBPHY_Type* usb_phy = USBPHY; + + // Enable PHY support for Low speed device + LS via FS Hub + usb_phy->CTRL |= USBPHY_CTRL_SET_ENUTMILEVEL2_MASK | USBPHY_CTRL_SET_ENUTMILEVEL3_MASK; + + // Enable all power for normal operation + usb_phy->PWD = 0; + + // TX Timing + uint32_t phytx = usb_phy->TX; + phytx &= ~(USBPHY_TX_D_CAL_MASK | USBPHY_TX_TXCAL45DM_MASK | USBPHY_TX_TXCAL45DP_MASK); + phytx |= USBPHY_TX_D_CAL(0x0C) | USBPHY_TX_TXCAL45DP(0x06) | USBPHY_TX_TXCAL45DM(0x06); + usb_phy->TX = phytx; +} + +//--------------------------------------------------------------------+ +// USB Interrupt Handler +//--------------------------------------------------------------------+ +void USB_OTG1_IRQHandler(void) +{ + #if CFG_TUSB_RHPORT0_MODE & OPT_MODE_HOST + tuh_isr(0); + #endif + + #if CFG_TUSB_RHPORT0_MODE & OPT_MODE_DEVICE + tud_isr(0); + #endif +} + +//--------------------------------------------------------------------+ +// Board porting API +//--------------------------------------------------------------------+ + +void board_led_write(bool state) +{ + GPIO_PinWrite(LED_PORT, LED_PIN, state ? LED_STATE_ON : (1-LED_STATE_ON)); +} + +uint32_t board_button_read(void) +{ + // active low + return BUTTON_STATE_ACTIVE == GPIO_PinRead(BUTTON_PORT, BUTTON_PIN); +} + +int board_uart_read(uint8_t* buf, int len) +{ + LPUART_ReadBlocking(UART_PORT, buf, len); + return len; +} + +int board_uart_write(void const * buf, int len) +{ + LPUART_WriteBlocking(UART_PORT, (uint8_t*)buf, len); + return len; +} + +#if CFG_TUSB_OS == OPT_OS_NONE +volatile uint32_t system_ticks = 0; +void SysTick_Handler(void) +{ + system_ticks++; +} + +uint32_t board_millis(void) +{ + return system_ticks; +} +#endif From 2379ce8d6576f32cfd44b92b59e08c0dd24303ff Mon Sep 17 00:00:00 2001 From: hathach Date: Sat, 23 Nov 2019 21:59:28 +0700 Subject: [PATCH 088/267] update doc, RT1011 verified to work, thanks to @arturo182 --- README.md | 2 +- docs/boards.md | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 8226ead5..1700be44 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ The stack supports the following MCUs - **Nordic:** nRF52840, nRF52833 - **NXP:** - LPC Series: 11Uxx, 13xx, 175x_6x, 177x_8x, 18xx, 40xx, 43xx, 51Uxx, 54xxx, 55xx - - iMX RT Series: RT1015, RT1021, RT1052, RT1062, RT1064 + - iMX RT Series: RT1011, RT1015, RT1021, RT1052, RT1062, RT1064 - **Sony:** CXD56 - **ST:** STM32 series: L0, F0, F1, F2, F3, F4, F7, H7 (device only) - **Tomu:** [valentyusb](https://github.com/im-tomu/valentyusb) (eptri) diff --git a/docs/boards.md b/docs/boards.md index 391d40a8..7006aae5 100644 --- a/docs/boards.md +++ b/docs/boards.md @@ -28,6 +28,7 @@ This code base already had supported for a handful of following boards ### NXP iMX RT +- [MIMX RT1010 Evaluation Kit](https://www.nxp.com/design/development-boards/i.mx-evaluation-and-development-boards/i.mx-rt1010-evaluation-kit:MIMXRT1010-EVK) - [MIMX RT1015 Evaluation Kit](https://www.nxp.com/design/development-boards/i.mx-evaluation-and-development-boards/i.mx-rt1015-evaluation-kit:MIMXRT1015-EVK) - [MIMX RT1020 Evaluation Kit](https://www.nxp.com/design/development-boards/i.mx-evaluation-and-development-boards/i.mx-rt1020-evaluation-kit:MIMXRT1020-EVK) - [MIMX RT1050 Evaluation Kit](https://www.nxp.com/design/development-boards/i.mx-evaluation-and-development-boards/i.mx-rt1050-evaluation-kit:MIMXRT1050-EVK) From a3ed87972df853ee4c2025265d65da996edf48ae Mon Sep 17 00:00:00 2001 From: hathach Date: Sun, 24 Nov 2019 00:52:34 +0700 Subject: [PATCH 089/267] more doc --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1700be44..162b707d 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ The stack supports the following MCUs - iMX RT Series: RT1011, RT1015, RT1021, RT1052, RT1062, RT1064 - **Sony:** CXD56 - **ST:** STM32 series: L0, F0, F1, F2, F3, F4, F7, H7 (device only) -- **Tomu:** [valentyusb](https://github.com/im-tomu/valentyusb) (eptri) +- **[valentyusb](https://github.com/im-tomu/valentyusb)** eptri [Here is the list of supported Boards](docs/boards.md) that can be used with provided examples. From a106c5114b3774283b45fc69f53af02c7253da7b Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Sun, 24 Nov 2019 01:15:31 +0000 Subject: [PATCH 090/267] bsp: fomu: fix rom address for example programs During development, the ROM address was at offset 0x2001a000 (due to the fact that the test program was located immediately following the bitstream). In normal Fomus, the ROM address is at offset 0x20040000, in order to take into account additional bitstreams and bootloaders. Correct the address to the offset in order to get examples working with existing Fomus. Signed-off-by: Sean Cross --- hw/bsp/fomu/fomu.ld | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/hw/bsp/fomu/fomu.ld b/hw/bsp/fomu/fomu.ld index abc91b8e..13278d2a 100644 --- a/hw/bsp/fomu/fomu.ld +++ b/hw/bsp/fomu/fomu.ld @@ -7,7 +7,7 @@ MEMORY { csr : ORIGIN = 0x60000000, LENGTH = 0x01000000 vexriscv_debug : ORIGIN = 0xf00f0000, LENGTH = 0x00000100 ram : ORIGIN = 0x10000000, LENGTH = 0x00020000 - rom : ORIGIN = 0x2001a000, LENGTH = 0x00200000 - 0x1a000 + rom : ORIGIN = 0x20040000, LENGTH = 0x00200000 - 0x40000 } /* The stack size used by the application. NOTE: you need to adjust according to your application. */ @@ -101,4 +101,4 @@ SECTIONS . = ALIGN(4); _end = . ; -} \ No newline at end of file +} From 58e8265964ef8260851465b56c1a3d48445ec04d Mon Sep 17 00:00:00 2001 From: hathach Date: Sun, 24 Nov 2019 23:46:28 +0700 Subject: [PATCH 091/267] usb hw init OK --- hw/bsp/samg55xplained/board.mk | 6 +- hw/bsp/samg55xplained/samg55xplained.c | 8 ++ src/portable/microchip/samg/dcd_samg.c | 116 +++++++++++++++++++++++++ src/tusb_option.h | 1 + 4 files changed, 128 insertions(+), 3 deletions(-) create mode 100644 src/portable/microchip/samg/dcd_samg.c diff --git a/hw/bsp/samg55xplained/board.mk b/hw/bsp/samg55xplained/board.mk index 78559450..eff773e0 100644 --- a/hw/bsp/samg55xplained/board.mk +++ b/hw/bsp/samg55xplained/board.mk @@ -6,7 +6,7 @@ CFLAGS += \ -mfloat-abi=hard \ -mfpu=fpv4-sp-d16 \ -nostdlib -nostartfiles \ - -DCFG_TUSB_MCU=OPT_MCU_NONE + -DCFG_TUSB_MCU=OPT_MCU_SAMG #CFLAGS += -Wno-error=undef @@ -35,8 +35,8 @@ INC += \ $(TOP)/$(ASF_DIR)/CMSIS/Core/Include # For TinyUSB port source -VENDOR = . -CHIP_FAMILY = template +VENDOR = microchip +CHIP_FAMILY = samg # For freeRTOS port source FREERTOS_PORT = ARM_CM4F diff --git a/hw/bsp/samg55xplained/samg55xplained.c b/hw/bsp/samg55xplained/samg55xplained.c index b050d362..79f10250 100644 --- a/hw/bsp/samg55xplained/samg55xplained.c +++ b/hw/bsp/samg55xplained/samg55xplained.c @@ -73,6 +73,14 @@ void board_init(void) // Enble clock _pmc_enable_periph_clock(ID_UDP); + + /* USB Device mode & Transceiver active */ + hri_matrix_write_CCFG_USBMR_reg(MATRIX, CCFG_USBMR_USBMODE); + +// NVIC_EnableIRQ(UDP_IRQn); + + // Attach + hri_udp_write_TXVC_reg(UDP, UDP_TXVC_PUON); } //--------------------------------------------------------------------+ diff --git a/src/portable/microchip/samg/dcd_samg.c b/src/portable/microchip/samg/dcd_samg.c new file mode 100644 index 00000000..793892fe --- /dev/null +++ b/src/portable/microchip/samg/dcd_samg.c @@ -0,0 +1,116 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2018, hathach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#include "tusb_option.h" + +#if CFG_TUSB_MCU == OPT_MCU_SAMG + +#include "device/dcd.h" + +//--------------------------------------------------------------------+ +// MACRO TYPEDEF CONSTANT ENUM DECLARATION +//--------------------------------------------------------------------+ + + +/*------------------------------------------------------------------*/ +/* Device API + *------------------------------------------------------------------*/ + +// Initialize controller to device mode +void dcd_init (uint8_t rhport) +{ + (void) rhport; +} + +// Enable device interrupt +void dcd_int_enable (uint8_t rhport) +{ + (void) rhport; +} + +// Disable device interrupt +void dcd_int_disable (uint8_t rhport) +{ + (void) rhport; +} + +// Receive Set Address request, mcu port must also include status IN response +void dcd_set_address (uint8_t rhport, uint8_t dev_addr) +{ + (void) rhport; + (void) dev_addr; +} + +// Receive Set Configure request +void dcd_set_config (uint8_t rhport, uint8_t config_num) +{ + (void) rhport; + (void) config_num; +} + +// Wake up host +void dcd_remote_wakeup (uint8_t rhport) +{ + (void) rhport; +} + +//--------------------------------------------------------------------+ +// Endpoint API +//--------------------------------------------------------------------+ + +// Configure endpoint's registers according to descriptor +bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * ep_desc) +{ + (void) rhport; + (void) ep_desc; + return false; +} + +// Submit a transfer, When complete dcd_event_xfer_complete() is invoked to notify the stack +bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t total_bytes) +{ + (void) rhport; + (void) ep_addr; + (void) buffer; + (void) total_bytes; + return false; +} + +// Stall endpoint +void dcd_edpt_stall (uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + (void) ep_addr; +} + +// clear stall, data toggle is also reset to DATA0 +void dcd_edpt_clear_stall (uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + (void) ep_addr; +} + +#endif diff --git a/src/tusb_option.h b/src/tusb_option.h index 281d4402..6766da07 100644 --- a/src/tusb_option.h +++ b/src/tusb_option.h @@ -57,6 +57,7 @@ // SAM #define OPT_MCU_SAMD21 200 ///< MicroChip SAMD21 #define OPT_MCU_SAMD51 201 ///< MicroChip SAMD51 +#define OPT_MCU_SAMG 202 ///< MicroChip SAMDG series // STM32 #define OPT_MCU_STM32F0 300 ///< ST STM32F0 From c691dc4cb2dd37998e529d7f3f71de9e947aa80d Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 25 Nov 2019 10:42:32 +0700 Subject: [PATCH 092/267] update --- hw/bsp/samg55xplained/samg55xplained.c | 4 +--- src/portable/microchip/samg/dcd_samg.c | 3 +++ 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/hw/bsp/samg55xplained/samg55xplained.c b/hw/bsp/samg55xplained/samg55xplained.c index 79f10250..67d1ae94 100644 --- a/hw/bsp/samg55xplained/samg55xplained.c +++ b/hw/bsp/samg55xplained/samg55xplained.c @@ -66,7 +66,7 @@ void board_init(void) SysTick_Config(CONF_CPU_FREQUENCY / 1000); #endif - // USB + // USB Pin, Clock init /* Clear SYSIO 10 & 11 for USB DM & DP */ hri_matrix_clear_CCFG_SYSIO_reg(MATRIX, CCFG_SYSIO_SYSIO10 | CCFG_SYSIO_SYSIO11); @@ -77,8 +77,6 @@ void board_init(void) /* USB Device mode & Transceiver active */ hri_matrix_write_CCFG_USBMR_reg(MATRIX, CCFG_USBMR_USBMODE); -// NVIC_EnableIRQ(UDP_IRQn); - // Attach hri_udp_write_TXVC_reg(UDP, UDP_TXVC_PUON); } diff --git a/src/portable/microchip/samg/dcd_samg.c b/src/portable/microchip/samg/dcd_samg.c index 793892fe..d3028e60 100644 --- a/src/portable/microchip/samg/dcd_samg.c +++ b/src/portable/microchip/samg/dcd_samg.c @@ -29,6 +29,7 @@ #if CFG_TUSB_MCU == OPT_MCU_SAMG #include "device/dcd.h" +#include "sam.h" //--------------------------------------------------------------------+ // MACRO TYPEDEF CONSTANT ENUM DECLARATION @@ -49,12 +50,14 @@ void dcd_init (uint8_t rhport) void dcd_int_enable (uint8_t rhport) { (void) rhport; + NVIC_EnableIRQ(UDP_IRQn); } // Disable device interrupt void dcd_int_disable (uint8_t rhport) { (void) rhport; + NVIC_DisableIRQ(UDP_IRQn); } // Receive Set Address request, mcu port must also include status IN response From a91ac72dbdc033fd1cc26651ca2d66d0705b08aa Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 25 Nov 2019 13:29:42 +0700 Subject: [PATCH 093/267] add the most important file of the project: CONTRIBUTORS.md --- CONTRIBUTORS.md | 50 +++++++++++++++++++++++++++++++++++++++++++++++++ README.md | 7 ++++++- 2 files changed, 56 insertions(+), 1 deletion(-) create mode 100644 CONTRIBUTORS.md diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md new file mode 100644 index 00000000..11c947c2 --- /dev/null +++ b/CONTRIBUTORS.md @@ -0,0 +1,50 @@ +# TinyUSB contributors (sorted alphabetically) + +* **[Arturo182](https://github.com/arturo182)** + * Board support for MiMX RT1010 evaluation kit + +* **[Ha Thach](https://github.com/hathach)** + * Author and maintainer + * Most features develpopment + +* **[Jeff Epler](https://github.com/jepler)** + * Improvement to MIDI device driver + +* **[Kamil Tomaszewski](https://github.com/kamtom480)** + * Sony CXD56 device driver port for spresnese board + +* **[Nathan Conrad](https://github.com/pigrew)** + * STM32 fsdev Fullspeed device driver port for STM32 L0, F0, F1, F3 etc ... + * USB device class driver support + * USBTMC class driver support with example + * Improvement to Zero-length packet for control transfer + * Board support for STM32F070RB Nucleo, STM32F303 Discovery + +* **[Scott Shawcroft](https://github.com/tannewt)** + * SAMD21 and SAMD51 device driver port + * MIDI device class driver support + * Improvement to USBD control transfer, MSC, CDC class driver + * Board support for Metro M0 & M4 express + * Write the execellent porting.md documentation + * Introduce inital Makefile + +* **[Sean Cross](https://github.com/xobs)** + * ValentyUSB eptri device driver port + * Board support for fomu + +* **[Sylvain "tnt" Munaut](https://github.com/smunaut)** + * DFU runtime support with example + +* **[Timon Skerutsch](https://github.com/PTS93)** + * hid_test.js script and extensive test for bi-directional raw HID + +* **[Tod E. Kurt](https://github.com/todbot)** + * hid_test.js script and extensive test for bi-directional raw HID + +* **[William D. Jones](https://github.com/cr1901)** + * Synopsys DesignWare device driver port for STM32 L4, F2, F4, F7, H7 etc ... + * MSP430 device driver port (WIP) + * Board support for STM32F407 Discovery, STM32H743 Nucleo, pyboard v1.1 + + +**[Full contributors list](https://github.com/hathach/tinyusb/contributors).** diff --git a/README.md b/README.md index 162b707d..2e503e39 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,11 @@ TinyUSB is an open-source cross-platform USB Host/Device stack for embedded syst └── tools # Files used internally ``` +## Contributors + +Special thanks for all the people who had spent their precious time and effort to helped this project so far. +[CONTRIBUTORS.md](CONTRIBUTORS.md) file contains list of contributors and their awesome work. + ## Supported MCUs The stack supports the following MCUs @@ -32,7 +37,7 @@ The stack supports the following MCUs - iMX RT Series: RT1011, RT1015, RT1021, RT1052, RT1062, RT1064 - **Sony:** CXD56 - **ST:** STM32 series: L0, F0, F1, F2, F3, F4, F7, H7 (device only) -- **[valentyusb](https://github.com/im-tomu/valentyusb)** eptri +- **[ValentyUSB](https://github.com/im-tomu/valentyusb)** eptri [Here is the list of supported Boards](docs/boards.md) that can be used with provided examples. From 168f0cb4711056e452fa335e71ee4a10341a9821 Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 25 Nov 2019 13:33:50 +0700 Subject: [PATCH 094/267] update readme --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 2e503e39..3f7556cf 100644 --- a/README.md +++ b/README.md @@ -23,8 +23,8 @@ TinyUSB is an open-source cross-platform USB Host/Device stack for embedded syst ## Contributors -Special thanks for all the people who had spent their precious time and effort to helped this project so far. -[CONTRIBUTORS.md](CONTRIBUTORS.md) file contains list of contributors and their awesome work. +Special thanks for all the people who had spent their precious time and effort to helped this project so far. Check out +[CONTRIBUTORS.md](CONTRIBUTORS.md) file for the list of all contributors and their awesome work for the stack. ## Supported MCUs From 0fccfc647fc5538481b8f673e9680ac6a9990e83 Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 25 Nov 2019 13:37:55 +0700 Subject: [PATCH 095/267] update --- CONTRIBUTORS.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 11c947c2..0eb6974d 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -15,9 +15,8 @@ * **[Nathan Conrad](https://github.com/pigrew)** * STM32 fsdev Fullspeed device driver port for STM32 L0, F0, F1, F3 etc ... - * USB device class driver support * USBTMC class driver support with example - * Improvement to Zero-length packet for control transfer + * Various improvement e.g Zero-length packet, Lint setup * Board support for STM32F070RB Nucleo, STM32F303 Discovery * **[Scott Shawcroft](https://github.com/tannewt)** From 7c606563edfd5207c506566e0c49c25fb5a7e23c Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 25 Nov 2019 20:52:27 +0700 Subject: [PATCH 096/267] lower case for arturo --- CONTRIBUTORS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 0eb6974d..1c8bbe37 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -1,6 +1,6 @@ # TinyUSB contributors (sorted alphabetically) -* **[Arturo182](https://github.com/arturo182)** +* **[arturo182](https://github.com/arturo182)** * Board support for MiMX RT1010 evaluation kit * **[Ha Thach](https://github.com/hathach)** From 13f42235176ef6dd49c7798dd83214a0963ee69f Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 25 Nov 2019 21:10:08 +0700 Subject: [PATCH 097/267] add the most important contributor --- CONTRIBUTORS.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 1c8bbe37..f938c332 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -1,5 +1,9 @@ # TinyUSB contributors (sorted alphabetically) +* **[Adafruit Team](https://github.com/adafruit)** + * Main supporter and sponsor for hardware boards and kits + * Discussion and suggestion for feature and improvement + * **[arturo182](https://github.com/arturo182)** * Board support for MiMX RT1010 evaluation kit From 3a2d63613bf710e706176f968e2ce1c1337adf26 Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 25 Nov 2019 22:56:37 +0700 Subject: [PATCH 098/267] logo design --- CONTRIBUTORS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index f938c332..20f4d9e2 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -3,6 +3,7 @@ * **[Adafruit Team](https://github.com/adafruit)** * Main supporter and sponsor for hardware boards and kits * Discussion and suggestion for feature and improvement + * Design the project logo * **[arturo182](https://github.com/arturo182)** * Board support for MiMX RT1010 evaluation kit From 387384c0d9b8a98fb4baab2bda16372876b86d6f Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 26 Nov 2019 17:39:51 +0700 Subject: [PATCH 099/267] fix samg55 with newlib missing end symbol --- hw/bsp/samg55xplained/board.mk | 5 +- hw/bsp/samg55xplained/samg55j19_flash.ld | 158 +++++++++++++++++++++++ hw/bsp/samg55xplained/samg55xplained.c | 5 +- 3 files changed, 162 insertions(+), 6 deletions(-) create mode 100644 hw/bsp/samg55xplained/samg55j19_flash.ld diff --git a/hw/bsp/samg55xplained/board.mk b/hw/bsp/samg55xplained/board.mk index eff773e0..8d4d11df 100644 --- a/hw/bsp/samg55xplained/board.mk +++ b/hw/bsp/samg55xplained/board.mk @@ -1,11 +1,12 @@ CFLAGS += \ - -D__SAMG55J19__ \ + -flto \ -mthumb \ -mabi=aapcs \ -mcpu=cortex-m4 \ -mfloat-abi=hard \ -mfpu=fpv4-sp-d16 \ -nostdlib -nostartfiles \ + -D__SAMG55J19__ \ -DCFG_TUSB_MCU=OPT_MCU_SAMG #CFLAGS += -Wno-error=undef @@ -13,7 +14,7 @@ CFLAGS += \ ASF_DIR = hw/mcu/microchip/samg55 # All source paths should be relative to the top level. -LD_FILE = $(ASF_DIR)/samg55/gcc/gcc/samg55j19_flash.ld +LD_FILE = hw/bsp/$(BOARD)/samg55j19_flash.ld SRC_C += \ $(ASF_DIR)/samg55/gcc/gcc/startup_samg55j19.c \ diff --git a/hw/bsp/samg55xplained/samg55j19_flash.ld b/hw/bsp/samg55xplained/samg55j19_flash.ld new file mode 100644 index 00000000..21c0b5bc --- /dev/null +++ b/hw/bsp/samg55xplained/samg55j19_flash.ld @@ -0,0 +1,158 @@ +/** + * \file + * + * \brief GCC linker script (flash) for ATSAMG55J19 + * + * Copyright (c) 2017 Atmel Corporation, a wholly owned subsidiary of Microchip Technology Inc. + * + * \license_start + * + * \page License + * + * 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. + * + * \license_stop + * + */ + +/*------------------------------------------------------------------------------ + * Linker script for running in internal FLASH on the ATSAMG55J19 + *----------------------------------------------------------------------------*/ + +OUTPUT_FORMAT("elf32-littlearm", "elf32-littlearm", "elf32-littlearm") +OUTPUT_ARCH(arm) + +/* Memory Spaces Definitions */ +MEMORY +{ + rom (rx) : ORIGIN = 0x00400000, LENGTH = 0x00080000 /* rom, 524288K */ + ram (rwx) : ORIGIN = 0x20000000, LENGTH = 0x00028000 /* ram, 163840K */ +} + +/* The stack size used by the application. NOTE: you need to adjust according to your application. */ +STACK_SIZE = DEFINED(STACK_SIZE) ? STACK_SIZE : DEFINED(__stack_size__) ? __stack_size__ : 0x0400; + +/* The heapsize used by the application. NOTE: you need to adjust according to your application. */ +HEAP_SIZE = DEFINED(HEAP_SIZE) ? HEAP_SIZE : DEFINED(__heap_size__) ? __heap_size__ : 0x0200; + +/* Section Definitions */ +SECTIONS +{ + .text : + { + . = ALIGN(4); + _sfixed = .; + KEEP(*(.vectors .vectors.*)) + *(.text .text.* .gnu.linkonce.t.*) + *(.glue_7t) *(.glue_7) + *(.rodata .rodata* .gnu.linkonce.r.*) + *(.ARM.extab* .gnu.linkonce.armextab.*) + + /* Support C constructors, and C destructors in both user code + and the C library. This also provides support for C++ code. */ + . = 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(0x4); + 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)) + + . = ALIGN(4); + _efixed = .; /* End of text section */ + } > rom + + /* .ARM.exidx is sorted, so has to go in its own output section. */ + PROVIDE_HIDDEN (__exidx_start = .); + .ARM.exidx : + { + *(.ARM.exidx* .gnu.linkonce.armexidx.*) + } > rom + PROVIDE_HIDDEN (__exidx_end = .); + + . = ALIGN(4); + _etext = .; + + .relocate : AT (_etext) + { + . = ALIGN(4); + _srelocate = .; + *(.ramfunc .ramfunc.*); + *(.data .data.*); + . = ALIGN(4); + _erelocate = .; + } > ram + + /* .bss section which is used for uninitialized data */ + .bss (NOLOAD) : + { + . = ALIGN(4); + _sbss = . ; + _szero = .; + *(.bss .bss.*) + *(COMMON) + . = ALIGN(4); + _ebss = . ; + _ezero = .; + end = .; + } > ram + + /* heap section */ + .heap (NOLOAD): + { + . = ALIGN(8); + _sheap = .; + . = . + HEAP_SIZE; + . = ALIGN(8); + _eheap = .; + } > ram + + /* stack section */ + .stack (NOLOAD): + { + . = ALIGN(8); + _sstack = .; + . = . + STACK_SIZE; + . = ALIGN(8); + _estack = .; + } > ram + + . = ALIGN(4); + _end = . ; + _ram_end_ = ORIGIN(ram) + LENGTH(ram) - 1 ; +} diff --git a/hw/bsp/samg55xplained/samg55xplained.c b/hw/bsp/samg55xplained/samg55xplained.c index 67d1ae94..8377424f 100644 --- a/hw/bsp/samg55xplained/samg55xplained.c +++ b/hw/bsp/samg55xplained/samg55xplained.c @@ -71,14 +71,11 @@ void board_init(void) /* Clear SYSIO 10 & 11 for USB DM & DP */ hri_matrix_clear_CCFG_SYSIO_reg(MATRIX, CCFG_SYSIO_SYSIO10 | CCFG_SYSIO_SYSIO11); - // Enble clock + // Enable clock _pmc_enable_periph_clock(ID_UDP); /* USB Device mode & Transceiver active */ hri_matrix_write_CCFG_USBMR_reg(MATRIX, CCFG_USBMR_USBMODE); - - // Attach - hri_udp_write_TXVC_reg(UDP, UDP_TXVC_PUON); } //--------------------------------------------------------------------+ From 4c9c13c767bb41b3cb3cb36810f5898fb966caae Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 26 Nov 2019 18:21:46 +0700 Subject: [PATCH 100/267] add uart sync support --- hw/bsp/samg55xplained/board.mk | 2 ++ hw/bsp/samg55xplained/samg55xplained.c | 30 ++++++++++++++++++++++++-- 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/hw/bsp/samg55xplained/board.mk b/hw/bsp/samg55xplained/board.mk index 8d4d11df..1fd13746 100644 --- a/hw/bsp/samg55xplained/board.mk +++ b/hw/bsp/samg55xplained/board.mk @@ -20,10 +20,12 @@ SRC_C += \ $(ASF_DIR)/samg55/gcc/gcc/startup_samg55j19.c \ $(ASF_DIR)/samg55/gcc/system_samg55j19.c \ $(ASF_DIR)/hpl/core/hpl_init.c \ + $(ASF_DIR)/hpl/usart/hpl_usart.c \ $(ASF_DIR)/hpl/pmc/hpl_pmc.c \ $(ASF_DIR)/hal/src/hal_atomic.c INC += \ + $(TOP)/hw/bsp/$(BOARD) \ $(TOP)/$(ASF_DIR) \ $(TOP)/$(ASF_DIR)/config \ $(TOP)/$(ASF_DIR)/samg55/include \ diff --git a/hw/bsp/samg55xplained/samg55xplained.c b/hw/bsp/samg55xplained/samg55xplained.c index 8377424f..b66b906a 100644 --- a/hw/bsp/samg55xplained/samg55xplained.c +++ b/hw/bsp/samg55xplained/samg55xplained.c @@ -26,6 +26,7 @@ #include "sam.h" #include "peripheral_clk_config.h" #include "hal/include/hal_init.h" +#include "hal/include/hpl_usart_sync.h" #include "hpl/pmc/hpl_pmc.h" #include "hal/include/hal_gpio.h" @@ -41,6 +42,15 @@ #define BUTTON_STATE_ACTIVE 0 +#define UART_TX_PIN GPIO(GPIO_PORTA, 28) +#define UART_RX_PIN GPIO(GPIO_PORTA, 27) + +//struct usart_async_descriptor _edbg_com; +//static uint8_t _edbg_com_buf[64]; + +struct _usart_sync_device _edbg_com; + + //------------- IMPLEMENTATION -------------// void board_init(void) { @@ -61,6 +71,17 @@ void board_init(void) gpio_set_pin_pull_mode(BUTTON_PIN, GPIO_PULL_UP); gpio_set_pin_function(BUTTON_PIN, GPIO_PIN_FUNCTION_OFF); + // Uart via EDBG Com + _pmc_enable_periph_clock(ID_FLEXCOM7); + gpio_set_pin_function(UART_RX_PIN, MUX_PA27B_FLEXCOM7_RXD); + gpio_set_pin_function(UART_TX_PIN, MUX_PA28B_FLEXCOM7_TXD); +// _usart_sync_init(&_edbg_com, FLEXCOM7, _edbg_com_buf, sizeof(_edbg_com_buf), _usart_get_usart_async()); + _usart_sync_init(&_edbg_com, FLEXCOM7); + _usart_sync_set_baud_rate(&_edbg_com, CFG_BOARD_UART_BAUDRATE); + _usart_sync_set_mode(&_edbg_com, USART_MODE_ASYNCHRONOUS); + _usart_sync_enable(&_edbg_com); + + #if CFG_TUSB_OS == OPT_OS_NONE // 1ms tick timer (samd SystemCoreClock may not correct) SysTick_Config(CONF_CPU_FREQUENCY / 1000); @@ -100,8 +121,13 @@ int board_uart_read(uint8_t* buf, int len) int board_uart_write(void const * buf, int len) { - (void) buf; (void) len; - return 0; + uint8_t const * buf8 = (uint8_t const *) buf; + for(int i=0; i Date: Tue, 26 Nov 2019 13:51:16 +0100 Subject: [PATCH 101/267] missing source file for cdc_msc to compile --- examples/device/cdc_msc/ses/nrf5x/nrf5x.emProject | 1 + 1 file changed, 1 insertion(+) diff --git a/examples/device/cdc_msc/ses/nrf5x/nrf5x.emProject b/examples/device/cdc_msc/ses/nrf5x/nrf5x.emProject index 55c5a4ec..fa553463 100644 --- a/examples/device/cdc_msc/ses/nrf5x/nrf5x.emProject +++ b/examples/device/cdc_msc/ses/nrf5x/nrf5x.emProject @@ -60,6 +60,7 @@ + From 745f0b4521a43c8f764b0bcac2d000b17f9aa1ac Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 27 Nov 2019 11:02:24 +0700 Subject: [PATCH 102/267] clean up --- hw/bsp/samg55xplained/samg55xplained.c | 12 +++++++++++- src/portable/microchip/samg/dcd_samg.c | 24 +++++++++++++++++++++++- 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/hw/bsp/samg55xplained/samg55xplained.c b/hw/bsp/samg55xplained/samg55xplained.c index b66b906a..67e7f925 100644 --- a/hw/bsp/samg55xplained/samg55xplained.c +++ b/hw/bsp/samg55xplained/samg55xplained.c @@ -75,7 +75,7 @@ void board_init(void) _pmc_enable_periph_clock(ID_FLEXCOM7); gpio_set_pin_function(UART_RX_PIN, MUX_PA27B_FLEXCOM7_RXD); gpio_set_pin_function(UART_TX_PIN, MUX_PA28B_FLEXCOM7_TXD); -// _usart_sync_init(&_edbg_com, FLEXCOM7, _edbg_com_buf, sizeof(_edbg_com_buf), _usart_get_usart_async()); + _usart_sync_init(&_edbg_com, FLEXCOM7); _usart_sync_set_baud_rate(&_edbg_com, CFG_BOARD_UART_BAUDRATE); _usart_sync_set_mode(&_edbg_com, USART_MODE_ASYNCHRONOUS); @@ -99,6 +99,16 @@ void board_init(void) hri_matrix_write_CCFG_USBMR_reg(MATRIX, CCFG_USBMR_USBMODE); } +//--------------------------------------------------------------------+ +// USB Interrupt Handler +//--------------------------------------------------------------------+ +void UDP_Handler(void) +{ + #if CFG_TUSB_RHPORT0_MODE & OPT_MODE_DEVICE + tud_isr(0); + #endif +} + //--------------------------------------------------------------------+ // Board porting API //--------------------------------------------------------------------+ diff --git a/src/portable/microchip/samg/dcd_samg.c b/src/portable/microchip/samg/dcd_samg.c index d3028e60..9b9ebad7 100644 --- a/src/portable/microchip/samg/dcd_samg.c +++ b/src/portable/microchip/samg/dcd_samg.c @@ -28,8 +28,8 @@ #if CFG_TUSB_MCU == OPT_MCU_SAMG -#include "device/dcd.h" #include "sam.h" +#include "device/dcd.h" //--------------------------------------------------------------------+ // MACRO TYPEDEF CONSTANT ENUM DECLARATION @@ -40,10 +40,22 @@ /* Device API *------------------------------------------------------------------*/ +// Set up endpoint 0, clear all other endpoints +//static void bus_reset(void) +//{ +// +//} + // Initialize controller to device mode void dcd_init (uint8_t rhport) { (void) rhport; + + + + + // Pull-up & Transceiver enable + UDP->UDP_TXVC = UDP_TXVC_PUON; } // Enable device interrupt @@ -116,4 +128,14 @@ void dcd_edpt_clear_stall (uint8_t rhport, uint8_t ep_addr) (void) ep_addr; } +//--------------------------------------------------------------------+ +// ISR +//--------------------------------------------------------------------+ +void dcd_isr(uint8_t rhport) +{ + (void) rhport; + + +} + #endif From 8a1b6327ba22940e42424e7ff208a81a4eb93e53 Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 27 Nov 2019 12:12:52 +0700 Subject: [PATCH 103/267] extract code to invoke_class_control() - also rename usbd_class_drivers to _usbd_driver --- src/device/usbd.c | 75 +++++++++++++++++++-------------------- src/device/usbd_control.c | 4 ++- 2 files changed, 40 insertions(+), 39 deletions(-) diff --git a/src/device/usbd.c b/src/device/usbd.c index 7d12e398..1797dfaf 100644 --- a/src/device/usbd.c +++ b/src/device/usbd.c @@ -84,7 +84,7 @@ typedef struct { void (* sof ) (uint8_t rhport); } usbd_class_driver_t; -static usbd_class_driver_t const usbd_class_drivers[] = +static usbd_class_driver_t const _usbd_driver[] = { #if CFG_TUD_CDC { @@ -183,7 +183,7 @@ static usbd_class_driver_t const usbd_class_drivers[] = #endif }; -enum { USBD_CLASS_DRIVER_COUNT = TU_ARRAY_SIZE(usbd_class_drivers) }; +enum { USBD_CLASS_DRIVER_COUNT = TU_ARRAY_SIZE(_usbd_driver) }; //--------------------------------------------------------------------+ // DCD Event @@ -304,7 +304,7 @@ bool tud_init (void) for (uint8_t i = 0; i < USBD_CLASS_DRIVER_COUNT; i++) { TU_LOG2("%s init\r\n", _usbd_driver_str[i]); - usbd_class_drivers[i].init(); + _usbd_driver[i].init(); } // Init device controller driver @@ -325,7 +325,7 @@ static void usbd_reset(uint8_t rhport) for (uint8_t i = 0; i < USBD_CLASS_DRIVER_COUNT; i++) { - if ( usbd_class_drivers[i].reset ) usbd_class_drivers[i].reset( rhport ); + if ( _usbd_driver[i].reset ) _usbd_driver[i].reset( rhport ); } } @@ -414,7 +414,7 @@ void tud_task (void) TU_ASSERT(drv_id < USBD_CLASS_DRIVER_COUNT,); TU_LOG2(" %s xfer callback\r\n", _usbd_driver_str[drv_id]); - usbd_class_drivers[drv_id].xfer_cb(event.rhport, ep_addr, event.xfer_complete.result, event.xfer_complete.len); + _usbd_driver[drv_id].xfer_cb(event.rhport, ep_addr, event.xfer_complete.result, event.xfer_complete.len); } } break; @@ -430,9 +430,9 @@ void tud_task (void) case DCD_EVENT_SOF: for ( uint8_t i = 0; i < USBD_CLASS_DRIVER_COUNT; i++ ) { - if ( usbd_class_drivers[i].sof ) + if ( _usbd_driver[i].sof ) { - usbd_class_drivers[i].sof(event.rhport); + _usbd_driver[i].sof(event.rhport); } } break; @@ -452,6 +452,16 @@ void tud_task (void) // Control Request Parser & Handling //--------------------------------------------------------------------+ +// Helper to invoke class driver control request handler +static bool invoke_class_control(uint8_t rhport, uint8_t drvid, tusb_control_request_t const * request) +{ + TU_ASSERT(_usbd_driver[drvid].control_request); + + usbd_control_set_complete_callback(_usbd_driver[drvid].control_complete); + TU_LOG2(" %s control request\r\n", _usbd_driver_str[drvid]); + return _usbd_driver[drvid].control_request(rhport, request); +} + // This handles the actual request and its response. // return false will cause its caller to stall control endpoint static bool process_control_request(uint8_t rhport, tusb_control_request_t const * p_request) @@ -586,21 +596,13 @@ static bool process_control_request(uint8_t rhport, tusb_control_request_t const default: // forward to class driver: "STD request to Interface" // GET HID REPORT DESCRIPTOR falls into this case - // stall control endpoint if driver return false - usbd_control_set_complete_callback(usbd_class_drivers[drvid].control_complete); - TU_LOG2(" %s control request\r\n", _usbd_driver_str[drvid]); - TU_VERIFY(usbd_class_drivers[drvid].control_request != NULL && - usbd_class_drivers[drvid].control_request(rhport, p_request)); + TU_VERIFY(invoke_class_control(rhport, drvid, p_request)); break; } }else { // forward to class driver: "non-STD request to Interface" - // stall control endpoint if driver return false - usbd_control_set_complete_callback(usbd_class_drivers[drvid].control_complete); - TU_LOG2(" %s control request\r\n", _usbd_driver_str[drvid]); - TU_VERIFY(usbd_class_drivers[drvid].control_request != NULL && - usbd_class_drivers[drvid].control_request(rhport, p_request)); + TU_VERIFY(invoke_class_control(rhport, drvid, p_request)); } } break; @@ -614,18 +616,12 @@ static bool process_control_request(uint8_t rhport, tusb_control_request_t const TU_ASSERT(ep_num < TU_ARRAY_SIZE(_usbd_dev.ep2drv) ); - uint8_t const drv_id = _usbd_dev.ep2drv[ep_num][ep_dir]; - TU_ASSERT(drv_id < USBD_CLASS_DRIVER_COUNT); + uint8_t const drvid = _usbd_dev.ep2drv[ep_num][ep_dir]; + TU_ASSERT(drvid < USBD_CLASS_DRIVER_COUNT); bool ret = false; - if ( TUSB_REQ_TYPE_STANDARD != p_request->bmRequestType_bit.type ) - { - // complete callback is also capable of stalling/acking the request - usbd_control_set_complete_callback(usbd_class_drivers[drv_id].control_complete); - } - - // Then handle if it is standard request + // Handle STD request to endpoint if ( TUSB_REQ_TYPE_STANDARD == p_request->bmRequestType_bit.type ) { // force return true for standard request @@ -660,18 +656,21 @@ static bool process_control_request(uint8_t rhport, tusb_control_request_t const default: TU_BREAKPOINT(); return false; } } - // Some classes such as TMC needs to clear/re-init its buffer when receiving CLEAR_FEATURE request - // We will forward all request targeted endpoint to its class driver - // For class-type requests: must (call tud_control_status(); return true) or (return false) - // For std-type requests: non-std request codes are already discarded. - // must not call tud_control_status(), and return value will have no effect - // class driver is invoked last, so that EP already has EP stall cleared (in event of clear feature EP halt) - TU_LOG2(" %s control request\r\n", _usbd_driver_str[drv_id]); - if ( usbd_class_drivers[drv_id].control_request && - usbd_class_drivers[drv_id].control_request(rhport, p_request)) + + // Some classes such as USBTMC needs to clear/re-init its buffer when receiving CLEAR_FEATURE request + // We will forward all request targeted endpoint to class drivers after + // - For class-type requests: driver is fully responsible to reply to host + // - For std-type requests : driver init/re-init internal variable/buffer only, and + // must not call tud_control_status(), driver's return value will have no effect. + // EP state has already affected (stalled/cleared) + if ( invoke_class_control(rhport, drvid, p_request) ) ret = true; + + if ( TUSB_REQ_TYPE_STANDARD == p_request->bmRequestType_bit.type ) { - ret = true; + // Set complete callback = NULL since it can also stall the request. + usbd_control_set_complete_callback(NULL); } + return ret; } break; @@ -714,7 +713,7 @@ static bool process_set_config(uint8_t rhport, uint8_t cfg_num) uint8_t drv_id; for (drv_id = 0; drv_id < USBD_CLASS_DRIVER_COUNT; drv_id++) { - if ( usbd_class_drivers[drv_id].class_code == desc_itf->bInterfaceClass ) break; + if ( _usbd_driver[drv_id].class_code == desc_itf->bInterfaceClass ) break; } TU_ASSERT( drv_id < USBD_CLASS_DRIVER_COUNT ); @@ -724,7 +723,7 @@ static bool process_set_config(uint8_t rhport, uint8_t cfg_num) uint16_t itf_len=0; TU_LOG2(" %s open\r\n", _usbd_driver_str[drv_id]); - TU_ASSERT( usbd_class_drivers[drv_id].open(rhport, desc_itf, &itf_len) ); + TU_ASSERT( _usbd_driver[drv_id].open(rhport, desc_itf, &itf_len) ); TU_ASSERT( itf_len >= sizeof(tusb_desc_interface_t) ); mark_interface_endpoint(_usbd_dev.ep2drv, p_desc, itf_len, drv_id); diff --git a/src/device/usbd_control.c b/src/device/usbd_control.c index 96786413..7f6cf5a4 100644 --- a/src/device/usbd_control.c +++ b/src/device/usbd_control.c @@ -130,7 +130,9 @@ void usbd_control_set_complete_callback( bool (*fp) (uint8_t, tusb_control_reque _ctrl_xfer.complete_cb = fp; } -// callback when a transaction complete on DATA stage of control endpoint +// callback when a transaction complete on +// - DATA stage of control endpoint or +// - Status stage bool usbd_control_xfer_cb (uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes) { (void) result; From fe1eadf177ec42914ce156704c6d2a6d85371945 Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 27 Nov 2019 12:34:30 +0700 Subject: [PATCH 104/267] fix #229 --- src/class/cdc/cdc_device.c | 4 +-- src/class/dfu/dfu_rt_device.c | 14 ++++------ src/class/hid/hid_device.c | 52 +++++++++++++++++------------------ src/class/midi/midi_device.c | 5 ++-- src/class/msc/msc_device.c | 3 +- 5 files changed, 36 insertions(+), 42 deletions(-) diff --git a/src/class/cdc/cdc_device.c b/src/class/cdc/cdc_device.c index 6da9157b..b124b473 100644 --- a/src/class/cdc/cdc_device.c +++ b/src/class/cdc/cdc_device.c @@ -311,8 +311,8 @@ bool cdcd_control_complete(uint8_t rhport, tusb_control_request_t const * reques // return false to stall control endpoint (e.g unsupported request) bool cdcd_control_request(uint8_t rhport, tusb_control_request_t const * request) { - //------------- Class Specific Request -------------// - TU_ASSERT(request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS); + // Handle class request only + TU_VERIFY(request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS); // TODO Support multiple interfaces uint8_t const itf = 0; diff --git a/src/class/dfu/dfu_rt_device.c b/src/class/dfu/dfu_rt_device.c index 59adae7e..ad1871da 100644 --- a/src/class/dfu/dfu_rt_device.c +++ b/src/class/dfu/dfu_rt_device.c @@ -79,21 +79,17 @@ bool dfu_rtd_open(uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16 bool dfu_rtd_control_complete(uint8_t rhport, tusb_control_request_t const * request) { (void) rhport; + (void) request; - //------------- Class Specific Request -------------// - TU_VERIFY(request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS); - TU_VERIFY(request->bmRequestType_bit.recipient == TUSB_REQ_RCPT_INTERFACE); - + // nothing to do return true; } bool dfu_rtd_control_request(uint8_t rhport, tusb_control_request_t const * request) { - (void) rhport; - - //------------- Class Specific Request -------------// - TU_ASSERT(request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS); - TU_ASSERT(request->bmRequestType_bit.recipient == TUSB_REQ_RCPT_INTERFACE); + // Handle class request only + TU_VERIFY(request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS); + TU_VERIFY(request->bmRequestType_bit.recipient == TUSB_REQ_RCPT_INTERFACE); switch ( request->bRequest ) { diff --git a/src/class/hid/hid_device.c b/src/class/hid/hid_device.c index 1d35e63f..8527fa5d 100644 --- a/src/class/hid/hid_device.c +++ b/src/class/hid/hid_device.c @@ -191,89 +191,87 @@ bool hidd_open(uint8_t rhport, tusb_desc_interface_t const * desc_itf, uint16_t // Handle class control request // return false to stall control endpoint (e.g unsupported request) -bool hidd_control_request(uint8_t rhport, tusb_control_request_t const * p_request) +bool hidd_control_request(uint8_t rhport, tusb_control_request_t const * request) { - if (p_request->bmRequestType_bit.recipient != TUSB_REQ_RCPT_INTERFACE) - { - return false; - } - hidd_interface_t* p_hid = get_interface_by_itfnum( (uint8_t) p_request->wIndex ); + TU_VERIFY(request->bmRequestType_bit.recipient == TUSB_REQ_RCPT_INTERFACE); + + hidd_interface_t* p_hid = get_interface_by_itfnum( (uint8_t) request->wIndex ); TU_ASSERT(p_hid); - if (p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_STANDARD) + if (request->bmRequestType_bit.type == TUSB_REQ_TYPE_STANDARD) { //------------- STD Request -------------// - uint8_t const desc_type = tu_u16_high(p_request->wValue); - uint8_t const desc_index = tu_u16_low (p_request->wValue); + uint8_t const desc_type = tu_u16_high(request->wValue); + uint8_t const desc_index = tu_u16_low (request->wValue); (void) desc_index; - if (p_request->bRequest == TUSB_REQ_GET_DESCRIPTOR && desc_type == HID_DESC_TYPE_HID) + if (request->bRequest == TUSB_REQ_GET_DESCRIPTOR && desc_type == HID_DESC_TYPE_HID) { TU_VERIFY(p_hid->hid_descriptor != NULL); - TU_VERIFY(tud_control_xfer(rhport, p_request, (void*) p_hid->hid_descriptor, p_hid->hid_descriptor->bLength)); + TU_VERIFY(tud_control_xfer(rhport, request, (void*) p_hid->hid_descriptor, p_hid->hid_descriptor->bLength)); } - else if (p_request->bRequest == TUSB_REQ_GET_DESCRIPTOR && desc_type == HID_DESC_TYPE_REPORT) + else if (request->bRequest == TUSB_REQ_GET_DESCRIPTOR && desc_type == HID_DESC_TYPE_REPORT) { uint8_t const * desc_report = tud_hid_descriptor_report_cb(); - tud_control_xfer(rhport, p_request, (void*) desc_report, p_hid->report_desc_len); + tud_control_xfer(rhport, request, (void*) desc_report, p_hid->report_desc_len); } else { return false; // stall unsupported request } } - else if (p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS) + else if (request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS) { //------------- Class Specific Request -------------// - switch( p_request->bRequest ) + switch( request->bRequest ) { case HID_REQ_CONTROL_GET_REPORT: { // wValue = Report Type | Report ID - uint8_t const report_type = tu_u16_high(p_request->wValue); - uint8_t const report_id = tu_u16_low(p_request->wValue); + uint8_t const report_type = tu_u16_high(request->wValue); + uint8_t const report_id = tu_u16_low(request->wValue); - uint16_t xferlen = tud_hid_get_report_cb(report_id, (hid_report_type_t) report_type, p_hid->epin_buf, p_request->wLength); + uint16_t xferlen = tud_hid_get_report_cb(report_id, (hid_report_type_t) report_type, p_hid->epin_buf, request->wLength); TU_ASSERT( xferlen > 0 ); - tud_control_xfer(rhport, p_request, p_hid->epin_buf, xferlen); + tud_control_xfer(rhport, request, p_hid->epin_buf, xferlen); } break; case HID_REQ_CONTROL_SET_REPORT: - TU_VERIFY(p_request->wLength <= sizeof(p_hid->epout_buf)); - tud_control_xfer(rhport, p_request, p_hid->epout_buf, p_request->wLength); + TU_VERIFY(request->wLength <= sizeof(p_hid->epout_buf)); + tud_control_xfer(rhport, request, p_hid->epout_buf, request->wLength); break; case HID_REQ_CONTROL_SET_IDLE: - p_hid->idle_rate = tu_u16_high(p_request->wValue); + p_hid->idle_rate = tu_u16_high(request->wValue); if ( tud_hid_set_idle_cb ) { // stall request if callback return false if ( !tud_hid_set_idle_cb(p_hid->idle_rate) ) return false; } - tud_control_status(rhport, p_request); + tud_control_status(rhport, request); break; case HID_REQ_CONTROL_GET_IDLE: // TODO idle rate of report - tud_control_xfer(rhport, p_request, &p_hid->idle_rate, 1); + tud_control_xfer(rhport, request, &p_hid->idle_rate, 1); break; case HID_REQ_CONTROL_GET_PROTOCOL: { uint8_t protocol = (uint8_t)(1-p_hid->boot_mode); // 0 is Boot, 1 is Report protocol - tud_control_xfer(rhport, p_request, &protocol, 1); + tud_control_xfer(rhport, request, &protocol, 1); } break; case HID_REQ_CONTROL_SET_PROTOCOL: - p_hid->boot_mode = 1 - p_request->wValue; // 0 is Boot, 1 is Report protocol + p_hid->boot_mode = 1 - request->wValue; // 0 is Boot, 1 is Report protocol if (tud_hid_boot_mode_cb) tud_hid_boot_mode_cb(p_hid->boot_mode); - tud_control_status(rhport, p_request); + tud_control_status(rhport, request); break; default: return false; // stall unsupported request diff --git a/src/class/midi/midi_device.c b/src/class/midi/midi_device.c index 11fe06e3..b278039b 100644 --- a/src/class/midi/midi_device.c +++ b/src/class/midi/midi_device.c @@ -322,10 +322,9 @@ bool midid_control_complete(uint8_t rhport, tusb_control_request_t const * p_req bool midid_control_request(uint8_t rhport, tusb_control_request_t const * p_request) { (void) rhport; + (void) p_request; - //------------- Class Specific Request -------------// - if (p_request->bmRequestType_bit.type != TUSB_REQ_TYPE_CLASS) return false; - + // driver doesn't support any request yet return false; } diff --git a/src/class/msc/msc_device.c b/src/class/msc/msc_device.c index cec76b11..bf2b5bb8 100644 --- a/src/class/msc/msc_device.c +++ b/src/class/msc/msc_device.c @@ -149,7 +149,8 @@ bool mscd_open(uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t // return false to stall control endpoint (e.g unsupported request) bool mscd_control_request(uint8_t rhport, tusb_control_request_t const * p_request) { - TU_ASSERT(p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS); + // Handle class request only + TU_VERIFY(p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS); switch ( p_request->bRequest ) { From bc21714c7ee7767c0aae6d782b6b72b954dddcdf Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 27 Nov 2019 14:49:19 +0700 Subject: [PATCH 105/267] detect bus reset --- hw/bsp/samg55xplained/samg55xplained.c | 5 ----- src/portable/microchip/samg/dcd_samg.c | 19 ++++++++++++++----- 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/hw/bsp/samg55xplained/samg55xplained.c b/hw/bsp/samg55xplained/samg55xplained.c index 67e7f925..a5e14573 100644 --- a/hw/bsp/samg55xplained/samg55xplained.c +++ b/hw/bsp/samg55xplained/samg55xplained.c @@ -45,12 +45,8 @@ #define UART_TX_PIN GPIO(GPIO_PORTA, 28) #define UART_RX_PIN GPIO(GPIO_PORTA, 27) -//struct usart_async_descriptor _edbg_com; -//static uint8_t _edbg_com_buf[64]; - struct _usart_sync_device _edbg_com; - //------------- IMPLEMENTATION -------------// void board_init(void) { @@ -81,7 +77,6 @@ void board_init(void) _usart_sync_set_mode(&_edbg_com, USART_MODE_ASYNCHRONOUS); _usart_sync_enable(&_edbg_com); - #if CFG_TUSB_OS == OPT_OS_NONE // 1ms tick timer (samd SystemCoreClock may not correct) SysTick_Config(CONF_CPU_FREQUENCY / 1000); diff --git a/src/portable/microchip/samg/dcd_samg.c b/src/portable/microchip/samg/dcd_samg.c index 9b9ebad7..3eb64eb1 100644 --- a/src/portable/microchip/samg/dcd_samg.c +++ b/src/portable/microchip/samg/dcd_samg.c @@ -41,10 +41,10 @@ *------------------------------------------------------------------*/ // Set up endpoint 0, clear all other endpoints -//static void bus_reset(void) -//{ -// -//} +static void bus_reset(void) +{ + +} // Initialize controller to device mode void dcd_init (uint8_t rhport) @@ -133,9 +133,18 @@ void dcd_edpt_clear_stall (uint8_t rhport, uint8_t ep_addr) //--------------------------------------------------------------------+ void dcd_isr(uint8_t rhport) { - (void) rhport; + uint32_t const intr_mask = UDP->UDP_IMR; + uint32_t const intr_status = UDP->UDP_ISR & intr_mask; + // clear interrupt + UDP->UDP_ICR = intr_status; + // Bus reset + if (intr_status & UDP_ISR_ENDBUSRES) + { + bus_reset(); + dcd_event_bus_signal(rhport, DCD_EVENT_BUS_RESET, true); + } } #endif From 6225d5bcfdf3b416d2dd109e88b67bc4fcefe249 Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 27 Nov 2019 16:01:25 +0700 Subject: [PATCH 106/267] able to handle setup packet --- src/portable/microchip/samg/dcd_samg.c | 47 ++++++++++++++++++++++++-- 1 file changed, 44 insertions(+), 3 deletions(-) diff --git a/src/portable/microchip/samg/dcd_samg.c b/src/portable/microchip/samg/dcd_samg.c index 3eb64eb1..899d054c 100644 --- a/src/portable/microchip/samg/dcd_samg.c +++ b/src/portable/microchip/samg/dcd_samg.c @@ -43,7 +43,14 @@ // Set up endpoint 0, clear all other endpoints static void bus_reset(void) { + // Enable EP0 control + UDP->UDP_CSR[0] = UDP_CSR_EPEDS_Msk; + // Enable interrupt : EP0, Suspend, Resume, Wakeup + UDP->UDP_IER = UDP_IER_EP0INT_Msk | UDP_IER_RXSUSP_Msk | UDP_IER_RXRSM_Msk | UDP_IER_WAKEUP_Msk; + + // Enable transceiver + UDP->UDP_TXVC &= ~UDP_TXVC_TXVDIS_Msk; } // Initialize controller to device mode @@ -54,8 +61,8 @@ void dcd_init (uint8_t rhport) - // Pull-up & Transceiver enable - UDP->UDP_TXVC = UDP_TXVC_PUON; + // Enable pull-up, disable transceiver + UDP->UDP_TXVC = UDP_TXVC_PUON | UDP_TXVC_TXVDIS_Msk; } // Enable device interrupt @@ -140,11 +147,45 @@ void dcd_isr(uint8_t rhport) UDP->UDP_ICR = intr_status; // Bus reset - if (intr_status & UDP_ISR_ENDBUSRES) + if (intr_status & UDP_ISR_ENDBUSRES_Msk) { bus_reset(); dcd_event_bus_signal(rhport, DCD_EVENT_BUS_RESET, true); } + + // SOF + if (intr_status & UDP_ISR_SOFINT_Msk) dcd_event_bus_signal(rhport, DCD_EVENT_SOF, true); + + // Suspend + if (intr_status & UDP_ISR_RXSUSP_Msk) dcd_event_bus_signal(rhport, DCD_EVENT_SUSPEND, true); + + // Resume + if (intr_status & UDP_ISR_RXRSM_Msk) dcd_event_bus_signal(rhport, DCD_EVENT_RESUME, true); + + // Wakeup +// if (intr_status & UDP_ISR_WAKEUP_Msk) dcd_event_bus_signal(rhport, DCD_EVENT_RESUME, true); + + //------------- Endpoints -------------// + + if ( intr_status & TU_BIT(0) ) + { + // setup packet + if (UDP->UDP_CSR[0] & UDP_CSR_RXSETUP) + { + // get setup from FIFO + uint8_t setup[8]; + for(uint8_t i=0; iUDP_FDR[0]; + } + + // clear setup bit + UDP->UDP_CSR[0] &= ~UDP_CSR_RXSETUP_Msk; + + // notify usbd + dcd_event_setup_received(rhport, setup, true); + } + } } #endif From 40b454cf28e5a86dac8d261f1276ace108446ffe Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 27 Nov 2019 23:20:48 +0700 Subject: [PATCH 107/267] get passed first get device descriptor --- src/common/tusb_common.h | 6 +- src/device/usbd.c | 25 +---- src/portable/microchip/samg/dcd_samg.c | 122 ++++++++++++++++++++++--- 3 files changed, 119 insertions(+), 34 deletions(-) diff --git a/src/common/tusb_common.h b/src/common/tusb_common.h index 59e1fe7f..d162e4e8 100644 --- a/src/common/tusb_common.h +++ b/src/common/tusb_common.h @@ -139,9 +139,9 @@ static inline uint8_t tu_log2(uint32_t value) } // Bit -static inline uint32_t tu_bit_set (uint32_t value, uint8_t n) { return value | TU_BIT(n); } -static inline uint32_t tu_bit_clear(uint32_t value, uint8_t n) { return value & (~TU_BIT(n)); } -static inline bool tu_bit_test (uint32_t value, uint8_t n) { return (value & TU_BIT(n)) ? true : false; } +static inline uint32_t tu_bit_set (uint32_t value, uint8_t pos) { return value | TU_BIT(pos); } +static inline uint32_t tu_bit_clear(uint32_t value, uint8_t pos) { return value & (~TU_BIT(pos)); } +static inline bool tu_bit_test (uint32_t value, uint8_t pos) { return (value & TU_BIT(pos)) ? true : false; } /*------------------------------------------------------------------*/ /* Count number of arguments of __VA_ARGS__ diff --git a/src/device/usbd.c b/src/device/usbd.c index 1797dfaf..530eb09d 100644 --- a/src/device/usbd.c +++ b/src/device/usbd.c @@ -830,19 +830,15 @@ void dcd_event_handler(dcd_event_t const * event, bool in_isr) { switch (event->event_id) { - case DCD_EVENT_BUS_RESET: - osal_queue_send(_usbd_q, event, in_isr); - break; - case DCD_EVENT_UNPLUGGED: - _usbd_dev.connected = 0; + _usbd_dev.connected = 0; _usbd_dev.configured = 0; - _usbd_dev.suspended = 0; + _usbd_dev.suspended = 0; osal_queue_send(_usbd_q, event, in_isr); break; case DCD_EVENT_SOF: - // nothing to do now + return; // skip SOF event for now break; case DCD_EVENT_SUSPEND: @@ -857,6 +853,7 @@ void dcd_event_handler(dcd_event_t const * event, bool in_isr) break; case DCD_EVENT_RESUME: + // skip event if not connected (especially required for SAMD) if ( _usbd_dev.connected ) { _usbd_dev.suspended = 0; @@ -864,21 +861,9 @@ void dcd_event_handler(dcd_event_t const * event, bool in_isr) } break; - case DCD_EVENT_SETUP_RECEIVED: + default: osal_queue_send(_usbd_q, event, in_isr); break; - - case DCD_EVENT_XFER_COMPLETE: - osal_queue_send(_usbd_q, event, in_isr); - TU_ASSERT(event->xfer_complete.result == XFER_RESULT_SUCCESS,); - break; - - // Not an DCD event, just a convenient way to defer ISR function should we need to - case USBD_EVENT_FUNC_CALL: - osal_queue_send(_usbd_q, event, in_isr); - break; - - default: break; } } diff --git a/src/portable/microchip/samg/dcd_samg.c b/src/portable/microchip/samg/dcd_samg.c index 899d054c..27fd35de 100644 --- a/src/portable/microchip/samg/dcd_samg.c +++ b/src/portable/microchip/samg/dcd_samg.c @@ -35,6 +35,38 @@ // MACRO TYPEDEF CONSTANT ENUM DECLARATION //--------------------------------------------------------------------+ +// Transfer descriptor +typedef struct +{ + uint8_t* buffer; + uint16_t total_len; + volatile uint16_t actual_len; + uint16_t epsize; +} xfer_desc_t; + +// Endpoint 0-5 with OUT & IN +xfer_desc_t _dcd_xfer[6][2]; + +void xfer_begin(xfer_desc_t* xfer, uint8_t * buffer, uint16_t total_bytes) +{ + xfer->buffer = buffer; + xfer->total_len = total_bytes; + xfer->actual_len = 0; +} + +uint16_t xfer_packet_len(xfer_desc_t* xfer) +{ + // also cover zero-length packet + return tu_min16(xfer->total_len - xfer->actual_len, xfer->epsize); +} + +void xfer_packet_done(xfer_desc_t* xfer) +{ + uint16_t const xact_len = xfer_packet_len(xfer); + + xfer->buffer += xact_len; + xfer->actual_len += xact_len; +} /*------------------------------------------------------------------*/ /* Device API @@ -43,6 +75,10 @@ // Set up endpoint 0, clear all other endpoints static void bus_reset(void) { + tu_memclr(_dcd_xfer, sizeof(_dcd_xfer)); + + _dcd_xfer[0][0].epsize = _dcd_xfer[0][1].epsize = CFG_TUD_ENDPOINT0_SIZE; + // Enable EP0 control UDP->UDP_CSR[0] = UDP_CSR_EPEDS_Msk; @@ -58,8 +94,7 @@ void dcd_init (uint8_t rhport) { (void) rhport; - - + tu_memclr(_dcd_xfer, sizeof(_dcd_xfer)); // Enable pull-up, disable transceiver UDP->UDP_TXVC = UDP_TXVC_PUON | UDP_TXVC_TXVDIS_Msk; @@ -115,10 +150,46 @@ bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * ep_desc) bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t total_bytes) { (void) rhport; - (void) ep_addr; - (void) buffer; - (void) total_bytes; - return false; + + uint8_t const epnum = tu_edpt_number(ep_addr); + uint8_t const dir = tu_edpt_dir(ep_addr); + + xfer_desc_t* xfer = &_dcd_xfer[epnum][dir]; + xfer_begin(xfer, buffer, total_bytes); + + uint16_t const xact_len = xfer_packet_len(xfer); + + // control endpoint + if ( epnum == 0 ) + { + // opposite to DIR bit --> status phase + // switch the DIR bit +// if ( dir != tu_bit_test(UDP->UDP_CSR[0], UDP_CSR_DIR_Pos) ) +// { +// +// } + + if (dir == TUSB_DIR_OUT) + { + UDP->UDP_CSR[0] &= ~UDP_CSR_DIR_Msk; + // + }else + { + UDP->UDP_CSR[0] |= UDP_CSR_DIR_Msk; + + // Write data to fifo + for(uint16_t i=0; iUDP_FDR[0] = (uint32_t) buffer[i]; + + // TX ready for transfer + UDP->UDP_CSR[0] |= UDP_CSR_TXPKTRDY_Msk; + } + + }else + { + return false; + } + + return true; } // Stall endpoint @@ -154,13 +225,13 @@ void dcd_isr(uint8_t rhport) } // SOF - if (intr_status & UDP_ISR_SOFINT_Msk) dcd_event_bus_signal(rhport, DCD_EVENT_SOF, true); +// if (intr_status & UDP_ISR_SOFINT_Msk) dcd_event_bus_signal(rhport, DCD_EVENT_SOF, true); // Suspend - if (intr_status & UDP_ISR_RXSUSP_Msk) dcd_event_bus_signal(rhport, DCD_EVENT_SUSPEND, true); +// if (intr_status & UDP_ISR_RXSUSP_Msk) dcd_event_bus_signal(rhport, DCD_EVENT_SUSPEND, true); // Resume - if (intr_status & UDP_ISR_RXRSM_Msk) dcd_event_bus_signal(rhport, DCD_EVENT_RESUME, true); +// if (intr_status & UDP_ISR_RXRSM_Msk) dcd_event_bus_signal(rhport, DCD_EVENT_RESUME, true); // Wakeup // if (intr_status & UDP_ISR_WAKEUP_Msk) dcd_event_bus_signal(rhport, DCD_EVENT_RESUME, true); @@ -179,11 +250,40 @@ void dcd_isr(uint8_t rhport) setup[i] = (uint8_t) UDP->UDP_FDR[0]; } - // clear setup bit - UDP->UDP_CSR[0] &= ~UDP_CSR_RXSETUP_Msk; + // Set EP0 Dir bit & Clear setup bit +// uint32_t csr = UDP->UDP_CSR[0]; +// csr &= ~(UDP_CSR_RXSETUP_Msk | UDP_CSR_DIR_Msk); +// if ( setup[0] & TUSB_DIR_IN_MASK ) csr |= UDP_CSR_DIR_Msk; +// +// UDP->UDP_CSR[0] = csr; // notify usbd dcd_event_setup_received(rhport, setup, true); + + // Clear Setup bit + UDP->UDP_CSR[0] &= ~UDP_CSR_RXSETUP_Msk; + } + } + + for(uint8_t epnum = 0; epnum < 6; epnum++) + { + // Endpoint IN + if (UDP->UDP_CSR[epnum] & UDP_CSR_TXCOMP_Msk) + { + xfer_desc_t* xfer = &_dcd_xfer[epnum][1]; + uint16_t xact_len = xfer_packet_len(xfer); + xfer_packet_done(xfer); + + dcd_event_xfer_complete(rhport, epnum | TUSB_DIR_IN_MASK, xact_len, XFER_RESULT_SUCCESS, true); + + // Clear TX Complete bit + UDP->UDP_CSR[0] &= ~UDP_CSR_TXCOMP_Msk; + } + + // Endpoint OUT + if (UDP->UDP_CSR[epnum] & UDP_CSR_RX_DATA_BK0_Msk) + { + dcd_event_bus_signal(rhport, DCD_EVENT_INVALID, true); } } } From 6bc245cb36cd18543916516a91def1f1e3a04e66 Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 28 Nov 2019 11:46:36 +0700 Subject: [PATCH 108/267] add dcd_edpt0_status_complete() which is useful for several mcu port --- src/common/tusb_common.h | 12 +++++++----- src/device/dcd.h | 4 ++++ src/device/usbd_control.c | 2 ++ src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c | 2 ++ 4 files changed, 15 insertions(+), 5 deletions(-) diff --git a/src/common/tusb_common.h b/src/common/tusb_common.h index d162e4e8..a2c40e66 100644 --- a/src/common/tusb_common.h +++ b/src/common/tusb_common.h @@ -216,17 +216,19 @@ static inline bool tu_bit_test (uint32_t value, uint8_t pos) { return (value void tu_print_mem(void const *buf, uint8_t size, uint16_t count); #ifndef tu_printf - #define tu_printf printf + #define tu_printf printf #endif // Log with debug level 1 -#define TU_LOG1 tu_printf -#define TU_LOG1_MEM tu_print_mem +#define TU_LOG1 tu_printf +#define TU_LOG1_MEM tu_print_mem +#define TU_LOG1_LOCATION() tu_printf("%s: %d:\n", __PRETTY_FUNCTION__, __LINE__) // Log with debug level 2 #if CFG_TUSB_DEBUG > 1 - #define TU_LOG2 TU_LOG1 - #define TU_LOG2_MEM TU_LOG1_MEM + #define TU_LOG2 TU_LOG1 + #define TU_LOG2_MEM TU_LOG1_MEM + #define TU_LOG2_LOCATION() TU_LOG1_LOCATION() #endif #endif // CFG_TUSB_DEBUG diff --git a/src/device/dcd.h b/src/device/dcd.h index dca289e7..8ae232fa 100644 --- a/src/device/dcd.h +++ b/src/device/dcd.h @@ -110,6 +110,10 @@ void dcd_remote_wakeup(uint8_t rhport); // Endpoint API //--------------------------------------------------------------------+ +// Invoked when a control transfer's status stage is complete. +// May help DCD to prepare for next control transfer, this API is optional. +void dcd_edpt0_status_complete(uint8_t rhport, tusb_control_request_t const * request) TU_ATTR_WEAK; + // Configure endpoint's registers according to descriptor bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc); diff --git a/src/device/usbd_control.c b/src/device/usbd_control.c index 7f6cf5a4..8b9b8f1c 100644 --- a/src/device/usbd_control.c +++ b/src/device/usbd_control.c @@ -64,6 +64,7 @@ static inline bool _status_stage_xact(uint8_t rhport, tusb_control_request_t con return dcd_edpt_xfer(rhport, request->bmRequestType_bit.direction ? EDPT_CTRL_OUT : EDPT_CTRL_IN, NULL, 0); } +// Status phase bool tud_control_status(uint8_t rhport, tusb_control_request_t const * request) { _ctrl_xfer.request = (*request); @@ -141,6 +142,7 @@ bool usbd_control_xfer_cb (uint8_t rhport, uint8_t ep_addr, xfer_result_t result if ( tu_edpt_dir(ep_addr) != _ctrl_xfer.request.bmRequestType_bit.direction ) { TU_ASSERT(0 == xferred_bytes); + if (dcd_edpt0_status_complete) dcd_edpt0_status_complete(rhport, &_ctrl_xfer.request); return true; } diff --git a/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c b/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c index ec182960..7ba9481b 100644 --- a/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c +++ b/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c @@ -296,6 +296,8 @@ void dcd_int_disable(uint8_t rhport) void dcd_set_address(uint8_t rhport, uint8_t dev_addr) { (void)rhport; + + // FIXME use dcd_edpt0_status_complete() // We cannot immediatly change it; it must be queued to change after the STATUS packet is sent. // (CTR handler will actually change the address once it sees that the transmission is complete) newDADDR = dev_addr; From 5dc04887e28314c1d74409939af66445ce9626ae Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 28 Nov 2019 11:48:08 +0700 Subject: [PATCH 109/267] get passed set address --- src/device/usbd.c | 7 +++- src/portable/microchip/samg/dcd_samg.c | 49 +++++++++++++++++--------- 2 files changed, 39 insertions(+), 17 deletions(-) diff --git a/src/device/usbd.c b/src/device/usbd.c index 530eb09d..01ec0e5f 100644 --- a/src/device/usbd.c +++ b/src/device/usbd.c @@ -405,7 +405,6 @@ void tud_task (void) if ( 0 == epnum ) { - TU_LOG1(" EP Addr = 0x%02X, len = %ld\r\n", ep_addr, event.xfer_complete.len); usbd_control_xfer_cb(event.rhport, ep_addr, event.xfer_complete.result, event.xfer_complete.len); } else @@ -503,7 +502,13 @@ static bool process_control_request(uint8_t rhport, tusb_control_request_t const // Depending on mcu, status phase could be sent either before or after changing device address // Therefore DCD must include zero-length status response dcd_set_address(rhport, (uint8_t) p_request->wValue); + +// FIXME remove STATUS response from dcd_set_address(), +#if CFG_TUSB_MCU == OPT_MCU_SAMG // skip status for nrf5x mcu + tud_control_status(rhport, p_request); +#else return true; // skip status +#endif break; case TUSB_REQ_GET_CONFIGURATION: diff --git a/src/portable/microchip/samg/dcd_samg.c b/src/portable/microchip/samg/dcd_samg.c index 27fd35de..bf842eab 100644 --- a/src/portable/microchip/samg/dcd_samg.c +++ b/src/portable/microchip/samg/dcd_samg.c @@ -119,6 +119,9 @@ void dcd_set_address (uint8_t rhport, uint8_t dev_addr) { (void) rhport; (void) dev_addr; + + // SAMG can only set address after status for this request is complete + // do it at dcd_edpt0_status_complete() } // Receive Set Configure request @@ -138,6 +141,27 @@ void dcd_remote_wakeup (uint8_t rhport) // Endpoint API //--------------------------------------------------------------------+ +// Invoked when a control transfer's status stage is complete. +// May help DCD to prepare for next control transfer, this API is optional. +void dcd_edpt0_status_complete(uint8_t rhport, tusb_control_request_t const * request) +{ + (void) rhport; + + if (request->bRequest == TUSB_REQ_SET_ADDRESS) + { + uint8_t const dev_addr = (uint8_t) request->wValue; + TU_LOG2("dev address = %d", dev_addr); + + // Enable addressed state + UDP->UDP_GLB_STAT |= UDP_GLB_STAT_FADDEN_Msk; + + // Set new address & Function enable bit + UDP->UDP_FADDR |= UDP_FADDR_FADD(dev_addr); + + UDP->UDP_FADDR |= UDP_FADDR_FEN_Msk; + } +} + // Configure endpoint's registers according to descriptor bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * ep_desc) { @@ -162,19 +186,14 @@ bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t // control endpoint if ( epnum == 0 ) { - // opposite to DIR bit --> status phase - // switch the DIR bit -// if ( dir != tu_bit_test(UDP->UDP_CSR[0], UDP_CSR_DIR_Pos) ) -// { -// -// } - if (dir == TUSB_DIR_OUT) { + // Clear DIR bit UDP->UDP_CSR[0] &= ~UDP_CSR_DIR_Msk; - // + }else { + // Set DIR bit if needed UDP->UDP_CSR[0] |= UDP_CSR_DIR_Msk; // Write data to fifo @@ -250,13 +269,6 @@ void dcd_isr(uint8_t rhport) setup[i] = (uint8_t) UDP->UDP_FDR[0]; } - // Set EP0 Dir bit & Clear setup bit -// uint32_t csr = UDP->UDP_CSR[0]; -// csr &= ~(UDP_CSR_RXSETUP_Msk | UDP_CSR_DIR_Msk); -// if ( setup[0] & TUSB_DIR_IN_MASK ) csr |= UDP_CSR_DIR_Msk; -// -// UDP->UDP_CSR[0] = csr; - // notify usbd dcd_event_setup_received(rhport, setup, true); @@ -283,7 +295,12 @@ void dcd_isr(uint8_t rhport) // Endpoint OUT if (UDP->UDP_CSR[epnum] & UDP_CSR_RX_DATA_BK0_Msk) { - dcd_event_bus_signal(rhport, DCD_EVENT_INVALID, true); + uint16_t const xact_len = (uint16_t) ((UDP->UDP_CSR[0] & UDP_CSR_RXBYTECNT_Msk) >> UDP_CSR_RXBYTECNT_Pos); + + dcd_event_xfer_complete(rhport, epnum, xact_len, XFER_RESULT_SUCCESS, true); + + // Clear DATA Bank0 bit + UDP->UDP_CSR[0] &= ~UDP_CSR_RX_DATA_BK0_Msk; } } } From 552cc3ef33aee21eba3ea60ad07c461181eeaa58 Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 28 Nov 2019 11:56:35 +0700 Subject: [PATCH 110/267] implement dcd_edpt_stall --- src/portable/microchip/samg/dcd_samg.c | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/portable/microchip/samg/dcd_samg.c b/src/portable/microchip/samg/dcd_samg.c index bf842eab..1d2e150d 100644 --- a/src/portable/microchip/samg/dcd_samg.c +++ b/src/portable/microchip/samg/dcd_samg.c @@ -215,7 +215,12 @@ bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t void dcd_edpt_stall (uint8_t rhport, uint8_t ep_addr) { (void) rhport; - (void) ep_addr; + + uint8_t const epnum = tu_edpt_number(ep_addr); +// uint8_t const dir = tu_edpt_dir(ep_addr); + + // Set force stall bit + UDP->UDP_CSR[epnum] |= UDP_CSR_FORCESTALL_Msk; } // clear stall, data toggle is also reset to DATA0 @@ -302,6 +307,12 @@ void dcd_isr(uint8_t rhport) // Clear DATA Bank0 bit UDP->UDP_CSR[0] &= ~UDP_CSR_RX_DATA_BK0_Msk; } + + // Stall sent to host + if (UDP->UDP_CSR[epnum] & UDP_CSR_STALLSENT_Msk) + { + UDP->UDP_CSR[0] &= ~UDP_CSR_STALLSENT_Msk; + } } } From ac701c398b4e9a43eefe0ee0be38579ca17535df Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 28 Nov 2019 12:18:56 +0700 Subject: [PATCH 111/267] clean up --- src/portable/microchip/samg/dcd_samg.c | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/portable/microchip/samg/dcd_samg.c b/src/portable/microchip/samg/dcd_samg.c index 1d2e150d..c38621e0 100644 --- a/src/portable/microchip/samg/dcd_samg.c +++ b/src/portable/microchip/samg/dcd_samg.c @@ -150,15 +150,12 @@ void dcd_edpt0_status_complete(uint8_t rhport, tusb_control_request_t const * re if (request->bRequest == TUSB_REQ_SET_ADDRESS) { uint8_t const dev_addr = (uint8_t) request->wValue; - TU_LOG2("dev address = %d", dev_addr); // Enable addressed state UDP->UDP_GLB_STAT |= UDP_GLB_STAT_FADDEN_Msk; // Set new address & Function enable bit - UDP->UDP_FADDR |= UDP_FADDR_FADD(dev_addr); - - UDP->UDP_FADDR |= UDP_FADDR_FEN_Msk; + UDP->UDP_FADDR = UDP_FADDR_FEN_Msk | UDP_FADDR_FADD(dev_addr); } } From d7558e8a0f12c685f2690c985e5f75df0777065b Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 28 Nov 2019 13:39:29 +0700 Subject: [PATCH 112/267] use dcd_edpt0_status_complete() to set address without blocking for samd21/samd51/stm32_fsdev --- src/device/usbd.c | 25 ++++++-------- src/device/usbd_control.c | 12 +++++-- src/portable/microchip/samd21/dcd_samd21.c | 25 ++++++++++---- src/portable/microchip/samd51/dcd_samd51.c | 23 ++++++++++--- src/portable/microchip/samg/dcd_samg.c | 5 ++- src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c | 34 +++++++++++-------- src/portable/st/synopsys/dcd_synopsys.c | 1 - 7 files changed, 82 insertions(+), 43 deletions(-) diff --git a/src/device/usbd.c b/src/device/usbd.c index 01ec0e5f..497281c2 100644 --- a/src/device/usbd.c +++ b/src/device/usbd.c @@ -202,9 +202,10 @@ static bool process_control_request(uint8_t rhport, tusb_control_request_t const static bool process_set_config(uint8_t rhport, uint8_t cfg_num); static bool process_get_descriptor(uint8_t rhport, tusb_control_request_t const * p_request); -void usbd_control_reset (uint8_t rhport); -bool usbd_control_xfer_cb (uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes); +void usbd_control_reset(void); +void usbd_control_set_request(tusb_control_request_t const *request); void usbd_control_set_complete_callback( bool (*fp) (uint8_t, tusb_control_request_t const * ) ); +bool usbd_control_xfer_cb (uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes); //--------------------------------------------------------------------+ @@ -321,7 +322,7 @@ static void usbd_reset(uint8_t rhport) memset(_usbd_dev.itf2drv, DRVID_INVALID, sizeof(_usbd_dev.itf2drv)); // invalid mapping memset(_usbd_dev.ep2drv , DRVID_INVALID, sizeof(_usbd_dev.ep2drv )); // invalid mapping - usbd_control_reset(rhport); + usbd_control_reset(); for (uint8_t i = 0; i < USBD_CLASS_DRIVER_COUNT; i++) { @@ -376,7 +377,7 @@ void tud_task (void) case DCD_EVENT_SETUP_RECEIVED: TU_LOG2(" "); - TU_LOG1_MEM(&event.setup_received, 1, 8); + TU_LOG2_MEM(&event.setup_received, 1, 8); // Mark as connected after receiving 1st setup packet. // But it is easier to set it every time instead of wasting time to check then set @@ -385,7 +386,7 @@ void tud_task (void) // Process control request if ( !process_control_request(event.rhport, &event.setup_received) ) { - TU_LOG1(" Stall EP0\r\n"); + TU_LOG2(" Stall EP0\r\n"); // Failed -> stall both control endpoint IN and OUT dcd_edpt_stall(event.rhport, 0); dcd_edpt_stall(event.rhport, 0 | TUSB_DIR_IN_MASK); @@ -499,16 +500,12 @@ static bool process_control_request(uint8_t rhport, tusb_control_request_t const switch ( p_request->bRequest ) { case TUSB_REQ_SET_ADDRESS: - // Depending on mcu, status phase could be sent either before or after changing device address - // Therefore DCD must include zero-length status response + // Depending on mcu, status phase could be sent either before or after changing device address, + // or even require stack to not response with status at all + // Therefore DCD must take full responsibility to response and include zlp status packet if needed. + usbd_control_set_request(p_request); // set request since DCD has no access to tud_control_status() API dcd_set_address(rhport, (uint8_t) p_request->wValue); - -// FIXME remove STATUS response from dcd_set_address(), -#if CFG_TUSB_MCU == OPT_MCU_SAMG // skip status for nrf5x mcu - tud_control_status(rhport, p_request); -#else - return true; // skip status -#endif + // skip tud_control_status() break; case TUSB_REQ_GET_CONFIGURATION: diff --git a/src/device/usbd_control.c b/src/device/usbd_control.c index 8b9b8f1c..e6d1caf4 100644 --- a/src/device/usbd_control.c +++ b/src/device/usbd_control.c @@ -119,9 +119,8 @@ bool tud_control_xfer(uint8_t rhport, tusb_control_request_t const * request, vo // USBD API //--------------------------------------------------------------------+ -void usbd_control_reset (uint8_t rhport) +void usbd_control_reset(void) { - (void) rhport; tu_varclr(&_ctrl_xfer); } @@ -131,6 +130,15 @@ void usbd_control_set_complete_callback( bool (*fp) (uint8_t, tusb_control_reque _ctrl_xfer.complete_cb = fp; } +// useful for dcd_set_address where DCD is responsible for status response +void usbd_control_set_request(tusb_control_request_t const *request) +{ + _ctrl_xfer.request = (*request); + _ctrl_xfer.buffer = NULL; + _ctrl_xfer.total_xferred = 0; + _ctrl_xfer.data_len = 0; +} + // callback when a transaction complete on // - DATA stage of control endpoint or // - Status stage diff --git a/src/portable/microchip/samd21/dcd_samd21.c b/src/portable/microchip/samd21/dcd_samd21.c index 231abc7d..3ffaabf0 100644 --- a/src/portable/microchip/samd21/dcd_samd21.c +++ b/src/portable/microchip/samd21/dcd_samd21.c @@ -98,13 +98,13 @@ void dcd_int_disable(uint8_t rhport) void dcd_set_address (uint8_t rhport, uint8_t dev_addr) { - // Response with status first before changing device address - dcd_edpt_xfer(rhport, tu_edpt_addr(0, TUSB_DIR_IN), NULL, 0); + (void) dev_addr; - // Wait for EP0 to finish before switching the address. - while (USB->DEVICE.DeviceEndpoint[0].EPSTATUS.bit.BK1RDY == 1) {} + // Response with zlp status + dcd_edpt_xfer(rhport, 0x80, NULL, 0); - USB->DEVICE.DADD.reg = USB_DEVICE_DADD_DADD(dev_addr) | USB_DEVICE_DADD_ADDEN; + // DCD can only set address after status for this request is complete + // do it at dcd_edpt0_status_complete() // Enable SUSPEND interrupt since the bus signal D+/D- are stable now. USB->DEVICE.INTFLAG.reg = USB_DEVICE_INTENCLR_SUSPEND; // clear pending @@ -116,7 +116,6 @@ void dcd_set_config (uint8_t rhport, uint8_t config_num) (void) rhport; (void) config_num; // Nothing to do - } void dcd_remote_wakeup(uint8_t rhport) @@ -130,6 +129,20 @@ void dcd_remote_wakeup(uint8_t rhport) /* DCD Endpoint port *------------------------------------------------------------------*/ +// Invoked when a control transfer's status stage is complete. +// May help DCD to prepare for next control transfer, this API is optional. +void dcd_edpt0_status_complete(uint8_t rhport, tusb_control_request_t const * request) +{ + (void) rhport; + + if (request->bRequest == TUSB_REQ_SET_ADDRESS) + { + uint8_t const dev_addr = (uint8_t) request->wValue; + USB->DEVICE.DADD.reg = USB_DEVICE_DADD_DADD(dev_addr) | USB_DEVICE_DADD_ADDEN; + } +} + + bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * desc_edpt) { (void) rhport; diff --git a/src/portable/microchip/samd51/dcd_samd51.c b/src/portable/microchip/samd51/dcd_samd51.c index f58e7cbc..1af24770 100644 --- a/src/portable/microchip/samd51/dcd_samd51.c +++ b/src/portable/microchip/samd51/dcd_samd51.c @@ -104,13 +104,13 @@ void dcd_int_disable(uint8_t rhport) void dcd_set_address (uint8_t rhport, uint8_t dev_addr) { - // Response with status first before changing device address - dcd_edpt_xfer(rhport, tu_edpt_addr(0, TUSB_DIR_IN), NULL, 0); + (void) dev_addr; - // Wait for EP0 to finish before switching the address. - while (USB->DEVICE.DeviceEndpoint[0].EPSTATUS.bit.BK1RDY == 1) {} + // Response with zlp status + dcd_edpt_xfer(rhport, 0x80, NULL, 0); - USB->DEVICE.DADD.reg = USB_DEVICE_DADD_DADD(dev_addr) | USB_DEVICE_DADD_ADDEN; + // DCD can only set address after status for this request is complete + // do it at dcd_edpt0_status_complete() // Enable SUSPEND interrupt since the bus signal D+/D- are stable now. USB->DEVICE.INTFLAG.reg = USB_DEVICE_INTENCLR_SUSPEND; // clear pending @@ -135,6 +135,19 @@ void dcd_remote_wakeup(uint8_t rhport) /* DCD Endpoint port *------------------------------------------------------------------*/ +// Invoked when a control transfer's status stage is complete. +// May help DCD to prepare for next control transfer, this API is optional. +void dcd_edpt0_status_complete(uint8_t rhport, tusb_control_request_t const * request) +{ + (void) rhport; + + if (request->bRequest == TUSB_REQ_SET_ADDRESS) + { + uint8_t const dev_addr = (uint8_t) request->wValue; + USB->DEVICE.DADD.reg = USB_DEVICE_DADD_DADD(dev_addr) | USB_DEVICE_DADD_ADDEN; + } +} + bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * desc_edpt) { (void) rhport; diff --git a/src/portable/microchip/samg/dcd_samg.c b/src/portable/microchip/samg/dcd_samg.c index c38621e0..122dc04b 100644 --- a/src/portable/microchip/samg/dcd_samg.c +++ b/src/portable/microchip/samg/dcd_samg.c @@ -120,7 +120,10 @@ void dcd_set_address (uint8_t rhport, uint8_t dev_addr) (void) rhport; (void) dev_addr; - // SAMG can only set address after status for this request is complete + // Response with zlp status + dcd_edpt_xfer(rhport, 0x80, NULL, 0); + + // DCD can only set address after status for this request is complete. // do it at dcd_edpt0_status_complete() } diff --git a/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c b/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c index 7ba9481b..f52e113b 100644 --- a/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c +++ b/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c @@ -172,7 +172,6 @@ static inline xfer_ctl_t* xfer_ctl_ptr(uint32_t epnum, uint32_t dir) static TU_ATTR_ALIGNED(4) uint32_t _setup_packet[6]; -static uint8_t newDADDR; // Used to set the new device address during the CTR IRQ handler static uint8_t remoteWakeCountdown; // When wake is requested // EP Buffers assigned from end of memory location, to minimize their chance of crashing @@ -297,14 +296,11 @@ void dcd_set_address(uint8_t rhport, uint8_t dev_addr) { (void)rhport; - // FIXME use dcd_edpt0_status_complete() - // We cannot immediatly change it; it must be queued to change after the STATUS packet is sent. - // (CTR handler will actually change the address once it sees that the transmission is complete) - newDADDR = dev_addr; - // Respond with status dcd_edpt_xfer(rhport, tu_edpt_addr(0, TUSB_DIR_IN), NULL, 0); + // DCD can only set address after status for this request is complete. + // do it at dcd_edpt0_status_complete() } // Receive Set Config request @@ -361,7 +357,7 @@ static void dcd_handle_bus_reset(void) ep_buf_ptr = DCD_STM32_BTABLE_BASE + 8*MAX_EP_COUNT; // 8 bytes per endpoint (two TX and two RX words, each) dcd_edpt_open (0, &ep0OUT_desc); dcd_edpt_open (0, &ep0IN_desc); - newDADDR = 0u; + USB->DADDR = USB_DADDR_EF; // Set enable flag, and leaving the device address as zero. } @@ -397,13 +393,7 @@ static uint16_t dcd_ep_ctr_handler(void) if((xfer->total_len == xfer->queued_len)) { dcd_event_xfer_complete(0u, (uint8_t)(0x80 + EPindex), xfer->total_len, XFER_RESULT_SUCCESS, true); - if((newDADDR != 0) && ( xfer->total_len == 0U)) - { - // Delayed setting of the DADDR after the 0-len DATA packet acking the request is sent. - reg16_clear_bits(&USB->DADDR, USB_DADDR_ADD); - USB->DADDR = (uint16_t)(USB->DADDR | newDADDR); // leave the enable bit set - newDADDR = 0; - } + if(xfer->total_len == 0) // Probably a status message? { pcd_clear_rx_dtog(USB,EPindex); @@ -601,6 +591,22 @@ static void dcd_fs_irqHandler(void) { // Endpoint API //--------------------------------------------------------------------+ +// Invoked when a control transfer's status stage is complete. +// May help DCD to prepare for next control transfer, this API is optional. +void dcd_edpt0_status_complete(uint8_t rhport, tusb_control_request_t const * request) +{ + (void) rhport; + + if (request->bRequest == TUSB_REQ_SET_ADDRESS) + { + uint8_t const dev_addr = (uint8_t) request->wValue; + + // Setting new address after the whole request is complete + reg16_clear_bits(&USB->DADDR, USB_DADDR_ADD); + USB->DADDR = (uint16_t)(USB->DADDR | dev_addr); // leave the enable bit set + } +} + // The STM32F0 doesn't seem to like |= or &= to manipulate the EP#R registers, // so I'm using the #define from HAL here, instead. diff --git a/src/portable/st/synopsys/dcd_synopsys.c b/src/portable/st/synopsys/dcd_synopsys.c index 7929b691..e02580e4 100644 --- a/src/portable/st/synopsys/dcd_synopsys.c +++ b/src/portable/st/synopsys/dcd_synopsys.c @@ -236,7 +236,6 @@ void dcd_set_address (uint8_t rhport, uint8_t dev_addr) (void) rhport; USB_OTG_DeviceTypeDef * dev = DEVICE_BASE; - dev->DCFG |= (dev_addr << USB_OTG_DCFG_DAD_Pos) & USB_OTG_DCFG_DAD_Msk; // Response with status after changing device address From e9725dcdbe8dcb56f7eeedd5671bf0f4c3fe72a2 Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 28 Nov 2019 13:48:55 +0700 Subject: [PATCH 113/267] use dcd_edpt0_status_complete() to prepare for setup packet for samd21/samd51 --- src/portable/microchip/samd21/dcd_samd21.c | 11 +++-------- src/portable/microchip/samd51/dcd_samd51.c | 8 +++----- 2 files changed, 6 insertions(+), 13 deletions(-) diff --git a/src/portable/microchip/samd21/dcd_samd21.c b/src/portable/microchip/samd21/dcd_samd21.c index 3ffaabf0..828b4701 100644 --- a/src/portable/microchip/samd21/dcd_samd21.c +++ b/src/portable/microchip/samd21/dcd_samd21.c @@ -133,13 +133,14 @@ void dcd_remote_wakeup(uint8_t rhport) // May help DCD to prepare for next control transfer, this API is optional. void dcd_edpt0_status_complete(uint8_t rhport, tusb_control_request_t const * request) { - (void) rhport; - if (request->bRequest == TUSB_REQ_SET_ADDRESS) { uint8_t const dev_addr = (uint8_t) request->wValue; USB->DEVICE.DADD.reg = USB_DEVICE_DADD_DADD(dev_addr) | USB_DEVICE_DADD_ADDEN; } + + // Just finished status stage, prepare for next setup packet + dcd_edpt_xfer(rhport, 0x00, _setup_packet, sizeof(_setup_packet)); } @@ -295,12 +296,6 @@ void maybe_transfer_complete(void) { uint8_t ep_addr = epnum; dcd_event_xfer_complete(0, ep_addr, total_transfer_size, XFER_RESULT_SUCCESS, true); } - - // Just finished status stage (total size = 0), prepare for next setup packet - // TODO could cause issue with actual zero length data used by class such as DFU - if (epnum == 0 && total_transfer_size == 0) { - dcd_edpt_xfer(0, 0, _setup_packet, sizeof(_setup_packet)); - } } } diff --git a/src/portable/microchip/samd51/dcd_samd51.c b/src/portable/microchip/samd51/dcd_samd51.c index 1af24770..abf89c32 100644 --- a/src/portable/microchip/samd51/dcd_samd51.c +++ b/src/portable/microchip/samd51/dcd_samd51.c @@ -146,6 +146,9 @@ void dcd_edpt0_status_complete(uint8_t rhport, tusb_control_request_t const * re uint8_t const dev_addr = (uint8_t) request->wValue; USB->DEVICE.DADD.reg = USB_DEVICE_DADD_DADD(dev_addr) | USB_DEVICE_DADD_ADDEN; } + + // Just finished status stage, prepare for next setup packet + dcd_edpt_xfer(rhport, 0x00, _setup_packet, sizeof(_setup_packet)); } bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * desc_edpt) @@ -347,11 +350,6 @@ void transfer_complete(uint8_t direction) { } dcd_event_xfer_complete(0, ep_addr, total_transfer_size, XFER_RESULT_SUCCESS, true); - // just finished status stage (total size = 0), prepare for next setup packet - if (epnum == 0 && total_transfer_size == 0) { - dcd_edpt_xfer(0, 0, _setup_packet, sizeof(_setup_packet)); - } - if (direction == TUSB_DIR_IN) { ep->EPINTFLAG.reg = USB_DEVICE_EPINTFLAG_TRCPT1; } else { From 26dcc19b186a85f6ee8d1d94bb672e34865f56e9 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Fri, 29 Nov 2019 18:14:23 +0800 Subject: [PATCH 114/267] valentyusb: eptri: don't double-advance read buffer Due to an error, we were double-advancing the FIFO buffer. The end result was that the second half of most reads were getting ignored. This wasn't found during earlier testing because only 64-byte buffers were tested. This corrects this error by avoiding double-advancing the buffer. Signed-off-by: Sean Cross --- src/portable/valentyusb/eptri/dcd_eptri.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/portable/valentyusb/eptri/dcd_eptri.c b/src/portable/valentyusb/eptri/dcd_eptri.c index e555fb0b..67e0c59a 100644 --- a/src/portable/valentyusb/eptri/dcd_eptri.c +++ b/src/portable/valentyusb/eptri/dcd_eptri.c @@ -226,7 +226,7 @@ static void process_rx(void) { test_buffer[total_read] = c; #endif total_read++; - if ((rx_buffer_offset[rx_ep] + current_offset) < rx_buffer_max[rx_ep]) { + if (current_offset < rx_buffer_max[rx_ep]) { #if LOG_USB usb_log[usb_log_offset].data[usb_log[usb_log_offset].size++] = c; #endif From 4a1f7d024315a8a280cf2ab1c5ba0c0d0c80fb7d Mon Sep 17 00:00:00 2001 From: Jerzy Kasenberg Date: Fri, 29 Nov 2019 16:25:08 +0100 Subject: [PATCH 115/267] Fix mynewt osal queue definition Queue table has pointers instead of data os_event structs. This resulted in crashes when elements were put to queue and overwritten variables that were just after mpool desiged for queue. --- src/osal/osal_mynewt.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/osal/osal_mynewt.h b/src/osal/osal_mynewt.h index da7977d3..e47e140c 100644 --- a/src/osal/osal_mynewt.h +++ b/src/osal/osal_mynewt.h @@ -98,7 +98,7 @@ static inline bool osal_mutex_unlock(osal_mutex_t mutex_hdl) // role device/host is used by OS NONE for mutex (disable usb isr) only #define OSAL_QUEUE_DEF(_role, _name, _depth, _type) \ static _type _name##_##buf[_depth];\ - static struct os_event* _name##_##evbuf[_depth];\ + static struct os_event _name##_##evbuf[_depth];\ osal_queue_def_t _name = { .depth = _depth, .item_sz = sizeof(_type), .buf = _name##_##buf, .evbuf = _name##_##evbuf};\ typedef struct From 69a801c0275500f392b21d77acd690a5c1977de7 Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 9 Dec 2019 17:59:30 +0700 Subject: [PATCH 116/267] change the samd submodule --- .gitmodules | 3 --- hw/mcu/microchip/samd/asf4 | 1 - 2 files changed, 4 deletions(-) delete mode 160000 hw/mcu/microchip/samd/asf4 diff --git a/.gitmodules b/.gitmodules index c7b39618..b5a2feac 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,9 +1,6 @@ [submodule "hw/mcu/nordic/nrfx"] path = hw/mcu/nordic/nrfx url = https://github.com/NordicSemiconductor/nrfx.git -[submodule "hw/mcu/microchip/samd/asf4"] - path = hw/mcu/microchip/samd/asf4 - url = https://github.com/adafruit/asf4.git [submodule "tools/uf2"] path = tools/uf2 url = https://github.com/microsoft/uf2.git diff --git a/hw/mcu/microchip/samd/asf4 b/hw/mcu/microchip/samd/asf4 deleted file mode 160000 index 82fe3aa0..00000000 --- a/hw/mcu/microchip/samd/asf4 +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 82fe3aa05bc3b9f4956ee775c748a3885443f66b From 9a8e6ed93b0713506c729c12243561ef23a2c619 Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 9 Dec 2019 18:18:01 +0700 Subject: [PATCH 117/267] added microchip submodule --- .gitmodules | 3 +++ hw/mcu/microchip | 1 + 2 files changed, 4 insertions(+) create mode 160000 hw/mcu/microchip diff --git a/.gitmodules b/.gitmodules index b5a2feac..83db9dff 100644 --- a/.gitmodules +++ b/.gitmodules @@ -16,3 +16,6 @@ [submodule "hw/mcu/nxp"] path = hw/mcu/nxp url = https://github.com/hathach/nxp_driver.git +[submodule "hw/mcu/microchip"] + path = hw/mcu/microchip + url = https://github.com/hathach/microchip_driver.git diff --git a/hw/mcu/microchip b/hw/mcu/microchip new file mode 160000 index 00000000..005624a6 --- /dev/null +++ b/hw/mcu/microchip @@ -0,0 +1 @@ +Subproject commit 005624a65dc6598b10eb1287edc92316d8ae3c1d From 208a77678cabd3dbd270a9f93f4ec110b25908ff Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 9 Dec 2019 18:37:20 +0700 Subject: [PATCH 118/267] clean up, switch and update submodule samd to circuitpython branch --- hw/bsp/circuitplayground_express/circuitplayground_express.c | 2 +- hw/bsp/feather_m0_express/feather_m0_express.c | 2 +- hw/bsp/feather_m4_express/feather_m4_express.c | 2 +- hw/bsp/metro_m0_express/metro_m0_express.c | 2 +- hw/bsp/metro_m4_express/metro_m4_express.c | 2 +- hw/mcu/microchip | 2 +- src/portable/microchip/samd21/dcd_samd21.c | 2 +- src/portable/microchip/samd51/dcd_samd51.c | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/hw/bsp/circuitplayground_express/circuitplayground_express.c b/hw/bsp/circuitplayground_express/circuitplayground_express.c index 6ca584eb..c48d1446 100644 --- a/hw/bsp/circuitplayground_express/circuitplayground_express.c +++ b/hw/bsp/circuitplayground_express/circuitplayground_express.c @@ -24,9 +24,9 @@ * This file is part of the TinyUSB stack. */ +#include "sam.h" #include "bsp/board.h" -#include "sam.h" #include "hal/include/hal_gpio.h" #include "hal/include/hal_init.h" #include "hri/hri_nvmctrl_d21.h" diff --git a/hw/bsp/feather_m0_express/feather_m0_express.c b/hw/bsp/feather_m0_express/feather_m0_express.c index 35505add..6fb14b5a 100644 --- a/hw/bsp/feather_m0_express/feather_m0_express.c +++ b/hw/bsp/feather_m0_express/feather_m0_express.c @@ -24,9 +24,9 @@ * This file is part of the TinyUSB stack. */ +#include "sam.h" #include "bsp/board.h" -#include "sam.h" #include "hal/include/hal_gpio.h" #include "hal/include/hal_init.h" #include "hri/hri_nvmctrl_d21.h" diff --git a/hw/bsp/feather_m4_express/feather_m4_express.c b/hw/bsp/feather_m4_express/feather_m4_express.c index fccd0d3a..1e20c846 100644 --- a/hw/bsp/feather_m4_express/feather_m4_express.c +++ b/hw/bsp/feather_m4_express/feather_m4_express.c @@ -24,9 +24,9 @@ * This file is part of the TinyUSB stack. */ +#include "sam.h" #include "bsp/board.h" -#include "sam.h" #include "hal/include/hal_gpio.h" #include "hal/include/hal_init.h" #include "hpl/gclk/hpl_gclk_base.h" diff --git a/hw/bsp/metro_m0_express/metro_m0_express.c b/hw/bsp/metro_m0_express/metro_m0_express.c index 35505add..6fb14b5a 100644 --- a/hw/bsp/metro_m0_express/metro_m0_express.c +++ b/hw/bsp/metro_m0_express/metro_m0_express.c @@ -24,9 +24,9 @@ * This file is part of the TinyUSB stack. */ +#include "sam.h" #include "bsp/board.h" -#include "sam.h" #include "hal/include/hal_gpio.h" #include "hal/include/hal_init.h" #include "hri/hri_nvmctrl_d21.h" diff --git a/hw/bsp/metro_m4_express/metro_m4_express.c b/hw/bsp/metro_m4_express/metro_m4_express.c index 08559e57..c3c0468a 100644 --- a/hw/bsp/metro_m4_express/metro_m4_express.c +++ b/hw/bsp/metro_m4_express/metro_m4_express.c @@ -24,9 +24,9 @@ * This file is part of the TinyUSB stack. */ +#include "sam.h" #include "bsp/board.h" -#include "sam.h" #include "hal/include/hal_gpio.h" #include "hal/include/hal_init.h" #include "hpl/gclk/hpl_gclk_base.h" diff --git a/hw/mcu/microchip b/hw/mcu/microchip index 005624a6..66b5a119 160000 --- a/hw/mcu/microchip +++ b/hw/mcu/microchip @@ -1 +1 @@ -Subproject commit 005624a65dc6598b10eb1287edc92316d8ae3c1d +Subproject commit 66b5a11995025426224e0ba6f377322e6e8893b6 diff --git a/src/portable/microchip/samd21/dcd_samd21.c b/src/portable/microchip/samd21/dcd_samd21.c index 828b4701..9f04ac06 100644 --- a/src/portable/microchip/samd21/dcd_samd21.c +++ b/src/portable/microchip/samd21/dcd_samd21.c @@ -28,8 +28,8 @@ #if TUSB_OPT_DEVICE_ENABLED && CFG_TUSB_MCU == OPT_MCU_SAMD21 -#include "device/dcd.h" #include "sam.h" +#include "device/dcd.h" /*------------------------------------------------------------------*/ /* MACRO TYPEDEF CONSTANT ENUM diff --git a/src/portable/microchip/samd51/dcd_samd51.c b/src/portable/microchip/samd51/dcd_samd51.c index abf89c32..6ece35ac 100644 --- a/src/portable/microchip/samd51/dcd_samd51.c +++ b/src/portable/microchip/samd51/dcd_samd51.c @@ -28,8 +28,8 @@ #if TUSB_OPT_DEVICE_ENABLED && CFG_TUSB_MCU == OPT_MCU_SAMD51 -#include "device/dcd.h" #include "sam.h" +#include "device/dcd.h" /*------------------------------------------------------------------*/ /* MACRO TYPEDEF CONSTANT ENUM From 988edce74530a585a4ffa40a7d955d0208892539 Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 9 Dec 2019 18:49:38 +0700 Subject: [PATCH 119/267] fix build --- src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c | 3 ++- tools/build_all.py | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c b/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c index f52e113b..a93a282e 100644 --- a/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c +++ b/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c @@ -294,7 +294,8 @@ void dcd_int_disable(uint8_t rhport) // Receive Set Address request, mcu port must also include status IN response void dcd_set_address(uint8_t rhport, uint8_t dev_addr) { - (void)rhport; + (void) rhport; + (void) dev_addr; // Respond with status dcd_edpt_xfer(rhport, tu_edpt_addr(0, TUSB_DIR_IN), NULL, 0); diff --git a/tools/build_all.py b/tools/build_all.py index 9f35aac6..2ea898f4 100644 --- a/tools/build_all.py +++ b/tools/build_all.py @@ -36,7 +36,7 @@ for entry in os.scandir("hw/bsp"): def build_example(example, board): subprocess.run("make -C examples/device/{} BOARD={} clean".format(example, board), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) - return subprocess.run("make -j 8 -C examples/device/{} BOARD={} all".format(example, board), shell=True, + return subprocess.run("make -j 4 -C examples/device/{} BOARD={} all".format(example, board), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) From 759fa7628093fd1f92ae188db8d1a98b22d548f0 Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 9 Dec 2019 21:36:15 +0700 Subject: [PATCH 120/267] implementing dcd_edpt_open --- hw/bsp/samg55xplained/hpl_usart_config.h | 215 ++++++++++++++++++ hw/bsp/samg55xplained/peripheral_clk_config.h | 85 +++++++ src/portable/microchip/samg/dcd_samg.c | 44 +++- 3 files changed, 334 insertions(+), 10 deletions(-) create mode 100644 hw/bsp/samg55xplained/hpl_usart_config.h create mode 100644 hw/bsp/samg55xplained/peripheral_clk_config.h diff --git a/hw/bsp/samg55xplained/hpl_usart_config.h b/hw/bsp/samg55xplained/hpl_usart_config.h new file mode 100644 index 00000000..4f2837d2 --- /dev/null +++ b/hw/bsp/samg55xplained/hpl_usart_config.h @@ -0,0 +1,215 @@ +/* Auto-generated config file hpl_usart_config.h */ +#ifndef HPL_USART_CONFIG_H +#define HPL_USART_CONFIG_H + +// <<< Use Configuration Wizard in Context Menu >>> + +#include + +#ifndef CONF_USART_7_ENABLE +#define CONF_USART_7_ENABLE 1 +#endif + +// Basic Configuration + +// Frame parity +// <0x0=>Even parity +// <0x1=>Odd parity +// <0x2=>Parity forced to 0 +// <0x3=>Parity forced to 1 +// <0x4=>No parity +// Parity bit mode for USART frame +// usart_parity +#ifndef CONF_USART_7_PARITY +#define CONF_USART_7_PARITY 0x4 +#endif + +// Character Size +// <0x0=>5 bits +// <0x1=>6 bits +// <0x2=>7 bits +// <0x3=>8 bits +// Data character size in USART frame +// usart_character_size +#ifndef CONF_USART_7_CHSIZE +#define CONF_USART_7_CHSIZE 0x3 +#endif + +// Stop Bit +// <0=>1 stop bit +// <1=>1.5 stop bits +// <2=>2 stop bits +// Number of stop bits in USART frame +// usart_stop_bit +#ifndef CONF_USART_7_SBMODE +#define CONF_USART_7_SBMODE 0 +#endif + +// Clock Output Select +// <0=>The USART does not drive the SCK pin +// <1=>The USART drives the SCK pin if USCLKS does not select the external clock SCK +// Clock Output Select in USART sck, if in usrt master mode, please drive SCK. +// usart_clock_output_select +#ifndef CONF_USART_7_CLKO +#define CONF_USART_7_CLKO 0 +#endif + +// Baud rate <1-3000000> +// USART baud rate setting +// usart_baud_rate +#ifndef CONF_USART_7_BAUD +#define CONF_USART_7_BAUD 9600 +#endif + +// + +// Advanced configuration +// usart_advanced +#ifndef CONF_USART_7_ADVANCED_CONFIG +#define CONF_USART_7_ADVANCED_CONFIG 0 +#endif + +// Channel Mode +// <0=>Normal Mode +// <1=>Automatic Echo +// <2=>Local Loopback +// <3=>Remote Loopback +// Channel mode in USART frame +// usart_channel_mode +#ifndef CONF_USART_7_CHMODE +#define CONF_USART_7_CHMODE 0 +#endif + +// 9 bits character enable +// Enable 9 bits character, this has high priority than 5/6/7/8 bits. +// usart_9bits_enable +#ifndef CONF_USART_7_MODE9 +#define CONF_USART_7_MODE9 0 +#endif + +// Variable Sync +// <0=>User defined configuration +// <1=>sync field is updated when a character is written into US_THR +// Variable Synchronization of Command/Data Sync Start Frarm Delimiter +// variable_sync +#ifndef CONF_USART_7_VAR_SYNC +#define CONF_USART_7_VAR_SYNC 0 +#endif + +// Oversampling Mode +// <0=>16 Oversampling +// <1=>8 Oversampling +// Oversampling Mode in UART mode +// usart__oversampling_mode +#ifndef CONF_USART_7_OVER +#define CONF_USART_7_OVER 0 +#endif + +// Inhibit Non Ack +// <0=>The NACK is generated +// <1=>The NACK is not generated +// Inhibit Non Acknowledge +// usart__inack +#ifndef CONF_USART_7_INACK +#define CONF_USART_7_INACK 1 +#endif + +// Disable Successive NACK +// <0=>NACK is sent on the ISO line as soon as a parity error occurs +// <1=>Many parity errors generate a NACK on the ISO line +// Disable Successive NACK +// usart_dsnack +#ifndef CONF_USART_7_DSNACK +#define CONF_USART_7_DSNACK 0 +#endif + +// Inverted Data +// <0=>Data isn't inverted, nomal mode +// <1=>Data is inverted +// Inverted Data +// usart_invdata +#ifndef CONF_USART_7_INVDATA +#define CONF_USART_7_INVDATA 0 +#endif + +// Maximum Number of Automatic Iteration <0-7> +// Defines the maximum number of iterations in mode ISO7816, protocol T = 0. +// usart_max_iteration +#ifndef CONF_USART_7_MAX_ITERATION +#define CONF_USART_7_MAX_ITERATION 0 +#endif + +// Receive Line Filter enable +// whether the USART filters the receive line using a three-sample filter +// usart_receive_filter_enable +#ifndef CONF_USART_7_FILTER +#define CONF_USART_7_FILTER 0 +#endif + +// Manchester Encoder/Decoder Enable +// whether the USART Manchester Encoder/Decoder +// usart_manchester_filter_enable +#ifndef CONF_USART_7_MAN +#define CONF_USART_7_MAN 0 +#endif + +// Manchester Synchronization Mode +// <0=>The Manchester start bit is a 0 to 1 transition +// <1=>The Manchester start bit is a 1 to 0 transition +// Manchester Synchronization Mode +// usart_manchester_synchronization_mode +#ifndef CONF_USART_7_MODSYNC +#define CONF_USART_7_MODSYNC 0 +#endif + +// Start Frame Delimiter Selector +// <0=>Start frame delimiter is COMMAND or DATA SYNC +// <1=>Start frame delimiter is one bit +// Start Frame Delimiter Selector +// usart_start_frame_delimiter +#ifndef CONF_USART_7_ONEBIT +#define CONF_USART_7_ONEBIT 0 +#endif + +// Fractional Part <0-7> +// Fractional part of the baud rate if baud rate generator is in fractional mode +// usart_arch_fractional +#ifndef CONF_USART_7_FRACTIONAL +#define CONF_USART_7_FRACTIONAL 0x0 +#endif + +// Data Order +// <0=>LSB is transmitted first +// <1=>MSB is transmitted first +// Data order of the data bits in the frame +// usart_arch_msbf +#ifndef CONF_USART_7_MSBF +#define CONF_USART_7_MSBF 0 +#endif + +// + +#define CONF_USART_7_MODE 0x0 + +// Calculate BAUD register value in UART mode +#if CONF_FLEXCOM7_CK_SRC < 3 +#ifndef CONF_USART_7_BAUD_CD +#define CONF_USART_7_BAUD_CD ((CONF_FLEXCOM7_FREQUENCY) / CONF_USART_7_BAUD / 8 / (2 - CONF_USART_7_OVER)) +#endif +#ifndef CONF_USART_7_BAUD_FP +#define CONF_USART_7_BAUD_FP \ + ((CONF_FLEXCOM7_FREQUENCY) / CONF_USART_7_BAUD / (2 - CONF_USART_7_OVER) - 8 * CONF_USART_7_BAUD_CD) +#endif +#elif CONF_FLEXCOM7_CK_SRC == 3 +// No division is active. The value written in US_BRGR has no effect. +#ifndef CONF_USART_7_BAUD_CD +#define CONF_USART_7_BAUD_CD 1 +#endif +#ifndef CONF_USART_7_BAUD_FP +#define CONF_USART_7_BAUD_FP 1 +#endif +#endif + +// <<< end of configuration section >>> + +#endif // HPL_USART_CONFIG_H diff --git a/hw/bsp/samg55xplained/peripheral_clk_config.h b/hw/bsp/samg55xplained/peripheral_clk_config.h new file mode 100644 index 00000000..6d390f38 --- /dev/null +++ b/hw/bsp/samg55xplained/peripheral_clk_config.h @@ -0,0 +1,85 @@ +/* Auto-generated config file peripheral_clk_config.h */ +#ifndef PERIPHERAL_CLK_CONFIG_H +#define PERIPHERAL_CLK_CONFIG_H + +// <<< Use Configuration Wizard in Context Menu >>> + +/** + * \def CONF_HCLK_FREQUENCY + * \brief HCLK's Clock frequency + */ +#ifndef CONF_HCLK_FREQUENCY +#define CONF_HCLK_FREQUENCY 8000000 +#endif + +/** + * \def CONF_FCLK_FREQUENCY + * \brief FCLK's Clock frequency + */ +#ifndef CONF_FCLK_FREQUENCY +#define CONF_FCLK_FREQUENCY 8000000 +#endif + +/** + * \def CONF_CPU_FREQUENCY + * \brief CPU's Clock frequency + */ +#ifndef CONF_CPU_FREQUENCY +#define CONF_CPU_FREQUENCY 8000000 +#endif + +/** + * \def CONF_SLCK_FREQUENCY + * \brief Slow Clock frequency + */ +#define CONF_SLCK_FREQUENCY 32768 + +/** + * \def CONF_MCK_FREQUENCY + * \brief Master Clock frequency + */ +#define CONF_MCK_FREQUENCY 8000000 + +// USB Clock Source +// <0=> USB Clock Controller (USB_48M) +// usb_clock_source +// Select the clock source for USB. +#ifndef CONF_UDP_SRC +#define CONF_UDP_SRC 0 +#endif + +/** + * \def CONF_UDP_FREQUENCY + * \brief UDP's Clock frequency + */ +#ifndef CONF_UDP_FREQUENCY +#define CONF_UDP_FREQUENCY 48005120 +#endif + +// FLEXCOM Clock Settings +// FLEXCOM Clock source +// <0=> Master Clock (MCK) +// <1=> MCK / 8 +// <2=> Programmable Clock Controller 6 (PMC_PCK6) +// <2=> Programmable Clock Controller 7 (PMC_PCK7) +// <3=> External Clock +// This defines the clock source for the FLEXCOM, PCK6 is used for FLEXCOM0/1/2/3 and PCK7 is used for FLEXCOM4/5/6/7 +// flexcom_clock_source +#ifndef CONF_FLEXCOM7_CK_SRC +#define CONF_FLEXCOM7_CK_SRC 0 +#endif + +// FLEXCOM External Clock Input on SCK <1-4294967295> +// Inputs the external clock frequency on SCK +// flexcom_clock_freq +#ifndef CONF_FLEXCOM7_SCK_FREQ +#define CONF_FLEXCOM7_SCK_FREQ 10000000 +#endif + +#ifndef CONF_FLEXCOM7_FREQUENCY +#define CONF_FLEXCOM7_FREQUENCY 8000000 +#endif + +// <<< end of configuration section >>> + +#endif // PERIPHERAL_CLK_CONFIG_H diff --git a/src/portable/microchip/samg/dcd_samg.c b/src/portable/microchip/samg/dcd_samg.c index 122dc04b..f29c5d79 100644 --- a/src/portable/microchip/samg/dcd_samg.c +++ b/src/portable/microchip/samg/dcd_samg.c @@ -35,6 +35,8 @@ // MACRO TYPEDEF CONSTANT ENUM DECLARATION //--------------------------------------------------------------------+ +#define EP_COUNT 6 + // Transfer descriptor typedef struct { @@ -44,8 +46,8 @@ typedef struct uint16_t epsize; } xfer_desc_t; -// Endpoint 0-5 with OUT & IN -xfer_desc_t _dcd_xfer[6][2]; +// Endpoint 0-5, each can only be either OUT or In +xfer_desc_t _dcd_xfer[EP_COUNT]; void xfer_begin(xfer_desc_t* xfer, uint8_t * buffer, uint16_t total_bytes) { @@ -77,7 +79,7 @@ static void bus_reset(void) { tu_memclr(_dcd_xfer, sizeof(_dcd_xfer)); - _dcd_xfer[0][0].epsize = _dcd_xfer[0][1].epsize = CFG_TUD_ENDPOINT0_SIZE; + _dcd_xfer[0].epsize = CFG_TUD_ENDPOINT0_SIZE; // Enable EP0 control UDP->UDP_CSR[0] = UDP_CSR_EPEDS_Msk; @@ -163,11 +165,29 @@ void dcd_edpt0_status_complete(uint8_t rhport, tusb_control_request_t const * re } // Configure endpoint's registers according to descriptor +// SAMG doesnt support using a same endpoint with IN and OUT +// e.g EP1 OUT & EP1 IN cannot exist together bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * ep_desc) { (void) rhport; - (void) ep_desc; - return false; + + uint8_t const epnum = tu_edpt_number(ep_desc->bEndpointAddress); + uint8_t const dir = tu_edpt_dir(ep_desc->bEndpointAddress); + + // TODO Isochronous is not supported yet + TU_VERIFY(ep_desc->bmAttributes.xfer != TUSB_XFER_ISOCHRONOUS); + TU_VERIFY(epnum < EP_COUNT); + + // Must not already enabled + TU_ASSERT((UDP->UDP_CSR[epnum] & UDP_CSR_EPEDS_Msk) == 0); + + // Configure type and eanble EP + UDP->UDP_CSR[epnum] = UDP_CSR_EPEDS_Msk | UDP_CSR_EPTYPE(ep_desc->bmAttributes.xfer + 4*dir); + + // Enable EP Interrupt + UDP->UDP_IER |= (1 << epnum); + + return true; } // Submit a transfer, When complete dcd_event_xfer_complete() is invoked to notify the stack @@ -178,7 +198,7 @@ bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t uint8_t const epnum = tu_edpt_number(ep_addr); uint8_t const dir = tu_edpt_dir(ep_addr); - xfer_desc_t* xfer = &_dcd_xfer[epnum][dir]; + xfer_desc_t* xfer = &_dcd_xfer[epnum]; xfer_begin(xfer, buffer, total_bytes); uint16_t const xact_len = xfer_packet_len(xfer); @@ -217,7 +237,6 @@ void dcd_edpt_stall (uint8_t rhport, uint8_t ep_addr) (void) rhport; uint8_t const epnum = tu_edpt_number(ep_addr); -// uint8_t const dir = tu_edpt_dir(ep_addr); // Set force stall bit UDP->UDP_CSR[epnum] |= UDP_CSR_FORCESTALL_Msk; @@ -227,7 +246,11 @@ void dcd_edpt_stall (uint8_t rhport, uint8_t ep_addr) void dcd_edpt_clear_stall (uint8_t rhport, uint8_t ep_addr) { (void) rhport; - (void) ep_addr; + + uint8_t const epnum = tu_edpt_number(ep_addr); + + // clear stall, must also clear data toggle + UDP->UDP_CSR[epnum] &= ~UDP_CSR_FORCESTALL_Msk; } //--------------------------------------------------------------------+ @@ -282,12 +305,13 @@ void dcd_isr(uint8_t rhport) } } - for(uint8_t epnum = 0; epnum < 6; epnum++) + for(uint8_t epnum = 0; epnum < EP_COUNT; epnum++) { + xfer_desc_t* xfer = &_dcd_xfer[epnum]; + // Endpoint IN if (UDP->UDP_CSR[epnum] & UDP_CSR_TXCOMP_Msk) { - xfer_desc_t* xfer = &_dcd_xfer[epnum][1]; uint16_t xact_len = xfer_packet_len(xfer); xfer_packet_done(xfer); From 0316e0ecd4ba10324f53c341480949fe025b8869 Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 9 Dec 2019 22:48:35 +0700 Subject: [PATCH 121/267] update descriptor, enhance ep in transfer --- examples/device/cdc_msc/src/usb_descriptors.c | 34 +++++++++++--- src/portable/microchip/samg/dcd_samg.c | 45 ++++++++++++------- 2 files changed, 56 insertions(+), 23 deletions(-) diff --git a/examples/device/cdc_msc/src/usb_descriptors.c b/examples/device/cdc_msc/src/usb_descriptors.c index 11d07e9b..e8527df0 100644 --- a/examples/device/cdc_msc/src/usb_descriptors.c +++ b/examples/device/cdc_msc/src/usb_descriptors.c @@ -86,12 +86,32 @@ enum #if CFG_TUSB_MCU == OPT_MCU_LPC175X_6X || CFG_TUSB_MCU == OPT_MCU_LPC177X_8X || CFG_TUSB_MCU == OPT_MCU_LPC40XX // LPC 17xx and 40xx endpoint type (bulk/interrupt/iso) are fixed by its number - // 0 control, 1 In, 2 Bulk, 3 Iso, 4 In etc ... - // Note: since CDC EP ( 1 & 2), HID (4) are spot-on, thus we only need to force - // endpoint number for MSC to 5 - #define EPNUM_MSC 0x05 + // 0 control, 1 In, 2 Bulk, 3 Iso, 4 In, 5 Bulk etc ... + #define EPNUM_CDC_NOTIF 0x81 + #define EPNUM_CDC_OUT 0x02 + #define EPNUM_CDC_IN 0x82 + + #define EPNUM_MSC_OUT 0x05 + #define EPNUM_MSC_IN 0x85 + +#elif CFG_TUSB_MCU == OPT_MCU_SAMG + // SAMG doesn't support a same endpoint number with IN and OUT + // e.g EP1 OUT & EP1 IN cannot exist together + #define EPNUM_CDC_NOTIF 0x81 + #define EPNUM_CDC_OUT 0x02 + #define EPNUM_CDC_IN 0x83 + + #define EPNUM_MSC_OUT 0x04 + #define EPNUM_MSC_IN 0x85 + #else - #define EPNUM_MSC 0x03 + #define EPNUM_CDC_NOTIF 0x81 + #define EPNUM_CDC_OUT 0x02 + #define EPNUM_CDC_IN 0x82 + + #define EPNUM_MSC_OUT 0x03 + #define EPNUM_MSC_IN 0x83 + #endif uint8_t const desc_configuration[] = @@ -100,10 +120,10 @@ uint8_t const desc_configuration[] = TUD_CONFIG_DESCRIPTOR(ITF_NUM_TOTAL, 0, CONFIG_TOTAL_LEN, TUSB_DESC_CONFIG_ATT_REMOTE_WAKEUP, 100), // Interface number, string index, EP notification address and size, EP data address (out, in) and size. - TUD_CDC_DESCRIPTOR(ITF_NUM_CDC, 4, 0x81, 8, 0x02, 0x82, 64), + TUD_CDC_DESCRIPTOR(ITF_NUM_CDC, 4, EPNUM_CDC_NOTIF, 8, EPNUM_CDC_OUT, EPNUM_CDC_IN, 64), // Interface number, string index, EP Out & EP In address, EP size - TUD_MSC_DESCRIPTOR(ITF_NUM_MSC, 5, EPNUM_MSC, 0x80 | EPNUM_MSC, (CFG_TUSB_RHPORT0_MODE & OPT_MODE_HIGH_SPEED) ? 512 : 64), + TUD_MSC_DESCRIPTOR(ITF_NUM_MSC, 5, EPNUM_MSC_OUT, EPNUM_MSC_IN, (CFG_TUSB_RHPORT0_MODE & OPT_MODE_HIGH_SPEED) ? 512 : 64), }; diff --git a/src/portable/microchip/samg/dcd_samg.c b/src/portable/microchip/samg/dcd_samg.c index f29c5d79..06e9902d 100644 --- a/src/portable/microchip/samg/dcd_samg.c +++ b/src/portable/microchip/samg/dcd_samg.c @@ -70,6 +70,17 @@ void xfer_packet_done(xfer_desc_t* xfer) xfer->actual_len += xact_len; } +//------------- Transaction helpers -------------// +static uint16_t xact_in(uint8_t epnum, xfer_desc_t* xfer) +{ + uint16_t const xact_len = xfer_packet_len(xfer); + + // Write data to fifo + for(uint16_t i=0; iUDP_FDR[epnum] = (uint32_t) xfer->buffer[i]; + + return xact_len; +} + /*------------------------------------------------------------------*/ /* Device API *------------------------------------------------------------------*/ @@ -165,7 +176,7 @@ void dcd_edpt0_status_complete(uint8_t rhport, tusb_control_request_t const * re } // Configure endpoint's registers according to descriptor -// SAMG doesnt support using a same endpoint with IN and OUT +// SAMG doesn't support a same endpoint number with IN and OUT // e.g EP1 OUT & EP1 IN cannot exist together bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * ep_desc) { @@ -201,31 +212,26 @@ bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t xfer_desc_t* xfer = &_dcd_xfer[epnum]; xfer_begin(xfer, buffer, total_bytes); - uint16_t const xact_len = xfer_packet_len(xfer); - - // control endpoint + // Configure DIR bit for control endpoint if ( epnum == 0 ) { if (dir == TUSB_DIR_OUT) { // Clear DIR bit UDP->UDP_CSR[0] &= ~UDP_CSR_DIR_Msk; - }else { - // Set DIR bit if needed + // Set DIR bit UDP->UDP_CSR[0] |= UDP_CSR_DIR_Msk; - - // Write data to fifo - for(uint16_t i=0; iUDP_FDR[0] = (uint32_t) buffer[i]; - - // TX ready for transfer - UDP->UDP_CSR[0] |= UDP_CSR_TXPKTRDY_Msk; } + } - }else + if (dir == TUSB_DIR_IN) { - return false; + xact_in(epnum, xfer); + + // TX ready for transfer + UDP->UDP_CSR[epnum] |= UDP_CSR_TXPKTRDY_Msk; } return true; @@ -312,10 +318,17 @@ void dcd_isr(uint8_t rhport) // Endpoint IN if (UDP->UDP_CSR[epnum] & UDP_CSR_TXCOMP_Msk) { - uint16_t xact_len = xfer_packet_len(xfer); xfer_packet_done(xfer); - dcd_event_xfer_complete(rhport, epnum | TUSB_DIR_IN_MASK, xact_len, XFER_RESULT_SUCCESS, true); + if ( xact_in(epnum, xfer) ) + { + // TX ready for transfer + UDP->UDP_CSR[epnum] |= UDP_CSR_TXPKTRDY_Msk; + }else + { + // xfer is complete + dcd_event_xfer_complete(rhport, epnum | TUSB_DIR_IN_MASK, xfer->actual_len, XFER_RESULT_SUCCESS, true); + } // Clear TX Complete bit UDP->UDP_CSR[0] &= ~UDP_CSR_TXCOMP_Msk; From 75a2157715ba9977bd9b193b76f1d4182e24d760 Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 9 Dec 2019 23:20:21 +0700 Subject: [PATCH 122/267] fix samd using TUSB_REQ_SET_ADDRESS in dcd_edpt0_status_complete --- src/portable/microchip/samd21/dcd_samd21.c | 4 +++- src/portable/microchip/samd51/dcd_samd51.c | 6 +++--- src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c | 4 +++- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/src/portable/microchip/samd21/dcd_samd21.c b/src/portable/microchip/samd21/dcd_samd21.c index 9f04ac06..5e44dc38 100644 --- a/src/portable/microchip/samd21/dcd_samd21.c +++ b/src/portable/microchip/samd21/dcd_samd21.c @@ -133,7 +133,9 @@ void dcd_remote_wakeup(uint8_t rhport) // May help DCD to prepare for next control transfer, this API is optional. void dcd_edpt0_status_complete(uint8_t rhport, tusb_control_request_t const * request) { - if (request->bRequest == TUSB_REQ_SET_ADDRESS) + if (request->bmRequestType_bit.recipient == TUSB_REQ_RCPT_DEVICE && + request->bmRequestType_bit.type == TUSB_REQ_TYPE_STANDARD && + request->bRequest == TUSB_REQ_SET_ADDRESS ) { uint8_t const dev_addr = (uint8_t) request->wValue; USB->DEVICE.DADD.reg = USB_DEVICE_DADD_DADD(dev_addr) | USB_DEVICE_DADD_ADDEN; diff --git a/src/portable/microchip/samd51/dcd_samd51.c b/src/portable/microchip/samd51/dcd_samd51.c index 6ece35ac..c298acc5 100644 --- a/src/portable/microchip/samd51/dcd_samd51.c +++ b/src/portable/microchip/samd51/dcd_samd51.c @@ -139,9 +139,9 @@ void dcd_remote_wakeup(uint8_t rhport) // May help DCD to prepare for next control transfer, this API is optional. void dcd_edpt0_status_complete(uint8_t rhport, tusb_control_request_t const * request) { - (void) rhport; - - if (request->bRequest == TUSB_REQ_SET_ADDRESS) + if (request->bmRequestType_bit.recipient == TUSB_REQ_RCPT_DEVICE && + request->bmRequestType_bit.type == TUSB_REQ_TYPE_STANDARD && + request->bRequest == TUSB_REQ_SET_ADDRESS ) { uint8_t const dev_addr = (uint8_t) request->wValue; USB->DEVICE.DADD.reg = USB_DEVICE_DADD_DADD(dev_addr) | USB_DEVICE_DADD_ADDEN; diff --git a/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c b/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c index a93a282e..341aa5f5 100644 --- a/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c +++ b/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c @@ -598,7 +598,9 @@ void dcd_edpt0_status_complete(uint8_t rhport, tusb_control_request_t const * re { (void) rhport; - if (request->bRequest == TUSB_REQ_SET_ADDRESS) + if (request->bmRequestType_bit.recipient == TUSB_REQ_RCPT_DEVICE && + request->bmRequestType_bit.type == TUSB_REQ_TYPE_STANDARD && + request->bRequest == TUSB_REQ_SET_ADDRESS ) { uint8_t const dev_addr = (uint8_t) request->wValue; From fa9607888204b2028f0f53340232a5d4cc47640d Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 9 Dec 2019 23:21:06 +0700 Subject: [PATCH 123/267] clear data toggle in clear stall, also set config bit --- src/portable/microchip/samg/dcd_samg.c | 29 +++++++++++++++++++------- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/src/portable/microchip/samg/dcd_samg.c b/src/portable/microchip/samg/dcd_samg.c index 06e9902d..f3efdeed 100644 --- a/src/portable/microchip/samg/dcd_samg.c +++ b/src/portable/microchip/samg/dcd_samg.c @@ -145,6 +145,9 @@ void dcd_set_config (uint8_t rhport, uint8_t config_num) { (void) rhport; (void) config_num; + + // Configured State +// UDP->UDP_GLB_STAT |= UDP_GLB_STAT_CONFG_Msk; } // Wake up host @@ -163,15 +166,23 @@ void dcd_edpt0_status_complete(uint8_t rhport, tusb_control_request_t const * re { (void) rhport; - if (request->bRequest == TUSB_REQ_SET_ADDRESS) + if (request->bmRequestType_bit.recipient == TUSB_REQ_RCPT_DEVICE && + request->bmRequestType_bit.type == TUSB_REQ_TYPE_STANDARD ) { - uint8_t const dev_addr = (uint8_t) request->wValue; + if (request->bRequest == TUSB_REQ_SET_ADDRESS) + { + uint8_t const dev_addr = (uint8_t) request->wValue; - // Enable addressed state - UDP->UDP_GLB_STAT |= UDP_GLB_STAT_FADDEN_Msk; + // Enable addressed state + UDP->UDP_GLB_STAT |= UDP_GLB_STAT_FADDEN_Msk; - // Set new address & Function enable bit - UDP->UDP_FADDR = UDP_FADDR_FEN_Msk | UDP_FADDR_FADD(dev_addr); + // Set new address & Function enable bit + UDP->UDP_FADDR = UDP_FADDR_FEN_Msk | UDP_FADDR_FADD(dev_addr); + }else if (request->bRequest == TUSB_REQ_SET_CONFIGURATION) + { + // Configured State + UDP->UDP_GLB_STAT |= UDP_GLB_STAT_CONFG_Msk; + } } } @@ -255,8 +266,12 @@ void dcd_edpt_clear_stall (uint8_t rhport, uint8_t ep_addr) uint8_t const epnum = tu_edpt_number(ep_addr); - // clear stall, must also clear data toggle + // clear stall UDP->UDP_CSR[epnum] &= ~UDP_CSR_FORCESTALL_Msk; + + // must also reset EP to clear data toggle + UDP->UDP_RST_EP = tu_bit_set(UDP->UDP_RST_EP, epnum); + UDP->UDP_RST_EP = tu_bit_clear(UDP->UDP_RST_EP, epnum); } //--------------------------------------------------------------------+ From 752aea7d723f5301f90a48a0888507fb333e86f8 Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 9 Dec 2019 23:58:13 +0700 Subject: [PATCH 124/267] enhance samg --- src/portable/microchip/samg/dcd_samg.c | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/portable/microchip/samg/dcd_samg.c b/src/portable/microchip/samg/dcd_samg.c index f3efdeed..f05763e3 100644 --- a/src/portable/microchip/samg/dcd_samg.c +++ b/src/portable/microchip/samg/dcd_samg.c @@ -31,6 +31,8 @@ #include "sam.h" #include "device/dcd.h" +// TODO should support (SAM3S || SAM4S || SAM4E || SAMG55) + //--------------------------------------------------------------------+ // MACRO TYPEDEF CONSTANT ENUM DECLARATION //--------------------------------------------------------------------+ @@ -346,24 +348,24 @@ void dcd_isr(uint8_t rhport) } // Clear TX Complete bit - UDP->UDP_CSR[0] &= ~UDP_CSR_TXCOMP_Msk; + UDP->UDP_CSR[epnum] &= ~UDP_CSR_TXCOMP_Msk; } // Endpoint OUT if (UDP->UDP_CSR[epnum] & UDP_CSR_RX_DATA_BK0_Msk) { - uint16_t const xact_len = (uint16_t) ((UDP->UDP_CSR[0] & UDP_CSR_RXBYTECNT_Msk) >> UDP_CSR_RXBYTECNT_Pos); + uint16_t const xact_len = (uint16_t) ((UDP->UDP_CSR[epnum] & UDP_CSR_RXBYTECNT_Msk) >> UDP_CSR_RXBYTECNT_Pos); dcd_event_xfer_complete(rhport, epnum, xact_len, XFER_RESULT_SUCCESS, true); // Clear DATA Bank0 bit - UDP->UDP_CSR[0] &= ~UDP_CSR_RX_DATA_BK0_Msk; + UDP->UDP_CSR[epnum] &= ~UDP_CSR_RX_DATA_BK0_Msk; } // Stall sent to host if (UDP->UDP_CSR[epnum] & UDP_CSR_STALLSENT_Msk) { - UDP->UDP_CSR[0] &= ~UDP_CSR_STALLSENT_Msk; + UDP->UDP_CSR[epnum] &= ~UDP_CSR_STALLSENT_Msk; } } } From 24009cb689e97a288cc79bae4f974aab7674f292 Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 10 Dec 2019 08:16:11 +0700 Subject: [PATCH 125/267] fixed unit test with dcd_edpt0_status_complete --- test/test/device/usbd/test_usbd.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/test/test/device/usbd/test_usbd.c b/test/test/device/usbd/test_usbd.c index c59d94c2..24535310 100644 --- a/test/test/device/usbd/test_usbd.c +++ b/test/test/device/usbd/test_usbd.c @@ -149,6 +149,8 @@ void test_usbd_get_device_descriptor(void) // status dcd_edpt_xfer_ExpectAndReturn(rhport, EDPT_CTRL_OUT, NULL, 0, true); + dcd_event_xfer_complete(rhport, EDPT_CTRL_OUT, 0, 0, false); + dcd_edpt0_status_complete_ExpectWithArray(rhport, &req_get_desc_device, 1); tud_task(); } @@ -180,6 +182,8 @@ void test_usbd_get_configuration_descriptor(void) // status dcd_edpt_xfer_ExpectAndReturn(rhport, EDPT_CTRL_OUT, NULL, 0, true); + dcd_event_xfer_complete(rhport, EDPT_CTRL_OUT, 0, 0, false); + dcd_edpt0_status_complete_ExpectWithArray(rhport, &req_get_desc_configuration, 1); tud_task(); } @@ -231,6 +235,7 @@ void test_usbd_control_in_zlp(void) // Status dcd_edpt_xfer_ExpectAndReturn(rhport, EDPT_CTRL_OUT, NULL, 0, true); dcd_event_xfer_complete(rhport, EDPT_CTRL_OUT, 0, 0, false); + dcd_edpt0_status_complete_ExpectWithArray(rhport, &req_get_desc_configuration, 1); tud_task(); } From 96a9eca6a041c8a7e9e86792f06abd0ef5a187a3 Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 11 Dec 2019 14:03:36 +0700 Subject: [PATCH 126/267] move VBUS sense out of dcd_synosys to bsp --- hw/bsp/feather_stm32f405/feather_stm32f405.c | 10 +++- hw/bsp/pyboardv11/pyboardv11.c | 24 +++++--- hw/bsp/stm32f207nucleo/stm32f207nucleo.c | 24 ++++++-- hw/bsp/stm32f407disco/stm32f407disco.c | 18 ++++-- hw/bsp/stm32f411disco/stm32f411disco.c | 23 +++++--- hw/bsp/stm32f412disco/stm32f412disco.c | 17 ++++-- hw/bsp/stm32f767nucleo/stm32f767nucleo.c | 3 + hw/bsp/stm32h743nucleo/stm32h743nucleo.c | 58 ++++++++++++-------- hw/bsp/stm32l476disco/stm32l476disco.c | 22 +++++--- src/portable/st/synopsys/dcd_synopsys.c | 8 +-- 10 files changed, 136 insertions(+), 71 deletions(-) diff --git a/hw/bsp/feather_stm32f405/feather_stm32f405.c b/hw/bsp/feather_stm32f405/feather_stm32f405.c index aec779ea..e8b15b51 100644 --- a/hw/bsp/feather_stm32f405/feather_stm32f405.c +++ b/hw/bsp/feather_stm32f405/feather_stm32f405.c @@ -152,9 +152,6 @@ void board_init(void) GPIO_InitStruct.Alternate = UART_GPIO_AF; HAL_GPIO_Init(UART_GPIO_PORT, &GPIO_InitStruct); - // Enable USB OTG clock - __HAL_RCC_USB_OTG_FS_CLK_ENABLE(); - // USB Pin Init // PA9- VUSB, PA10- ID, PA11- DM, PA12- DP @@ -179,6 +176,13 @@ void board_init(void) GPIO_InitStruct.Speed = GPIO_SPEED_HIGH; GPIO_InitStruct.Alternate = GPIO_AF10_OTG_FS; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); + + // Enable USB OTG clock + __HAL_RCC_USB_OTG_FS_CLK_ENABLE(); + + // Enable VBUS sense (B device) via pin PA9 + USB_OTG_FS->GCCFG &= ~USB_OTG_GCCFG_NOVBUSSENS; + USB_OTG_FS->GCCFG |= USB_OTG_GCCFG_VBUSBSEN; } //--------------------------------------------------------------------+ diff --git a/hw/bsp/pyboardv11/pyboardv11.c b/hw/bsp/pyboardv11/pyboardv11.c index 2d4c732c..7452eef7 100644 --- a/hw/bsp/pyboardv11/pyboardv11.c +++ b/hw/bsp/pyboardv11/pyboardv11.c @@ -38,6 +38,14 @@ #define BUTTON_PIN GPIO_PIN_3 #define BUTTON_STATE_ACTIVE 1 + +// enable all LED, Button, Uart, USB clock +static void all_rcc_clk_enable(void) +{ + __HAL_RCC_GPIOA_CLK_ENABLE(); // USB D+, D- + __HAL_RCC_GPIOB_CLK_ENABLE(); // LED, Button +} + /** * @brief System Clock Configuration * The system Clock is configured as follow : @@ -107,14 +115,11 @@ void board_init(void) // Notify runtime of frequency change. SystemCoreClockUpdate(); - __HAL_RCC_GPIOA_CLK_ENABLE(); // USB D+/D- - __HAL_RCC_GPIOB_CLK_ENABLE(); // button, LED + all_rcc_clk_enable(); GPIO_InitTypeDef GPIO_InitStruct; // LED - __HAL_RCC_GPIOD_CLK_ENABLE(); - GPIO_InitStruct.Pin = LED_PIN; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_PULLUP; @@ -130,12 +135,8 @@ void board_init(void) GPIO_InitStruct.Speed = GPIO_SPEED_FAST; HAL_GPIO_Init(BUTTON_PORT, &GPIO_InitStruct); - // Enable USB OTG clock - __HAL_RCC_USB_OTG_FS_CLK_ENABLE(); - // USB Pin Init // PA9- VUSB, PA10- ID, PA11- DM, PA12- DP - __HAL_RCC_GPIOA_CLK_ENABLE(); /* Configure DM DP Pins */ GPIO_InitStruct.Pin = GPIO_PIN_11 | GPIO_PIN_12; @@ -158,6 +159,13 @@ void board_init(void) GPIO_InitStruct.Speed = GPIO_SPEED_HIGH; GPIO_InitStruct.Alternate = GPIO_AF10_OTG_FS; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); + + // Enable USB OTG clock + __HAL_RCC_USB_OTG_FS_CLK_ENABLE(); + + // Enable VBUS sense (B device) via pin PA9 + USB_OTG_FS->GCCFG &= ~USB_OTG_GCCFG_NOVBUSSENS; + USB_OTG_FS->GCCFG |= USB_OTG_GCCFG_VBUSBSEN; } //--------------------------------------------------------------------+ diff --git a/hw/bsp/stm32f207nucleo/stm32f207nucleo.c b/hw/bsp/stm32f207nucleo/stm32f207nucleo.c index de0b4753..a09f26cf 100644 --- a/hw/bsp/stm32f207nucleo/stm32f207nucleo.c +++ b/hw/bsp/stm32f207nucleo/stm32f207nucleo.c @@ -38,6 +38,14 @@ #define BUTTON_STATE_ACTIVE 1 +// enable all LED, Button, Uart, USB clock +static void all_rcc_clk_enable(void) +{ + __HAL_RCC_GPIOA_CLK_ENABLE(); // USB D+, D- + __HAL_RCC_GPIOB_CLK_ENABLE(); // LED + __HAL_RCC_GPIOC_CLK_ENABLE(); // Button +} + /** * @brief System Clock Configuration * The system Clock is configured as follow : @@ -91,21 +99,22 @@ void board_init(void) #endif SystemClock_Config(); - - // Notify runtime of frequency change. SystemCoreClockUpdate(); - // LED - __HAL_RCC_GPIOB_CLK_ENABLE(); + all_rcc_clk_enable(); + GPIO_InitTypeDef GPIO_InitStruct; + + // LED GPIO_InitStruct.Pin = LED_PIN; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_PULLUP; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; HAL_GPIO_Init(LED_PORT, &GPIO_InitStruct); + board_led_write(false); + // Button - __HAL_RCC_GPIOC_CLK_ENABLE(); GPIO_InitStruct.Pin = BUTTON_PIN; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_PULLDOWN; @@ -113,7 +122,6 @@ void board_init(void) HAL_GPIO_Init(BUTTON_PORT, &GPIO_InitStruct); /* Configure DM DP Pins */ - __HAL_RCC_GPIOA_CLK_ENABLE(); GPIO_InitStruct.Pin = (GPIO_PIN_11 | GPIO_PIN_12); GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; @@ -136,6 +144,10 @@ void board_init(void) /* Enable USB FS Clocks */ __HAL_RCC_USB_OTG_FS_CLK_ENABLE(); + + // Enable VBUS sense (B device) via pin PA9 + USB_OTG_FS->GCCFG &= ~USB_OTG_GCCFG_NOVBUSSENS; + USB_OTG_FS->GCCFG |= USB_OTG_GCCFG_VBUSBSEN; } //--------------------------------------------------------------------+ diff --git a/hw/bsp/stm32f407disco/stm32f407disco.c b/hw/bsp/stm32f407disco/stm32f407disco.c index b80c5c1b..42cb613c 100644 --- a/hw/bsp/stm32f407disco/stm32f407disco.c +++ b/hw/bsp/stm32f407disco/stm32f407disco.c @@ -37,6 +37,14 @@ #define BUTTON_PIN GPIO_PIN_0 #define BUTTON_STATE_ACTIVE 1 + +// enable all LED, Button, Uart, USB clock +static void all_rcc_clk_enable(void) +{ + __HAL_RCC_GPIOA_CLK_ENABLE(); // USB D+, D-, Button + __HAL_RCC_GPIOD_CLK_ENABLE(); // LED +} + /** * @brief System Clock Configuration * The system Clock is configured as follow : @@ -102,14 +110,12 @@ void board_init(void) #endif SystemClock_Config(); - - // Notify runtime of frequency change. SystemCoreClockUpdate(); + all_rcc_clk_enable(); GPIO_InitTypeDef GPIO_InitStruct; // LED - __HAL_RCC_GPIOD_CLK_ENABLE(); GPIO_InitStruct.Pin = LED_PIN; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_PULLUP; @@ -119,7 +125,6 @@ void board_init(void) board_led_write(false); // Button - __HAL_RCC_GPIOA_CLK_ENABLE(); GPIO_InitStruct.Pin = BUTTON_PIN; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_PULLDOWN; @@ -129,7 +134,6 @@ void board_init(void) // USB Pin Init // PA9- VUSB, PA10- ID, PA11- DM, PA12- DP /* Configure DM DP Pins */ - __HAL_RCC_GPIOA_CLK_ENABLE(); GPIO_InitStruct.Pin = GPIO_PIN_11 | GPIO_PIN_12; GPIO_InitStruct.Speed = GPIO_SPEED_HIGH; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; @@ -153,6 +157,10 @@ void board_init(void) // Enable USB OTG clock __HAL_RCC_USB_OTG_FS_CLK_ENABLE(); + + // Enable VBUS sense (B device) via pin PA9 + USB_OTG_FS->GCCFG &= ~USB_OTG_GCCFG_NOVBUSSENS; + USB_OTG_FS->GCCFG |= USB_OTG_GCCFG_VBUSBSEN; } //--------------------------------------------------------------------+ diff --git a/hw/bsp/stm32f411disco/stm32f411disco.c b/hw/bsp/stm32f411disco/stm32f411disco.c index d8d79d2f..9d9c3071 100644 --- a/hw/bsp/stm32f411disco/stm32f411disco.c +++ b/hw/bsp/stm32f411disco/stm32f411disco.c @@ -37,6 +37,13 @@ #define BUTTON_PIN GPIO_PIN_0 #define BUTTON_STATE_ACTIVE 1 +// enable all LED, Button, Uart, USB clock +static void all_rcc_clk_enable(void) +{ + __HAL_RCC_GPIOA_CLK_ENABLE(); // USB D+, D-, Button + __HAL_RCC_GPIOD_CLK_ENABLE(); // LED +} + /** * @brief System Clock Configuration * The system Clock is configured as follow : @@ -102,14 +109,12 @@ void board_init(void) #endif SystemClock_Config(); - - // Notify runtime of frequency change. SystemCoreClockUpdate(); + all_rcc_clk_enable(); GPIO_InitTypeDef GPIO_InitStruct; // LED - __HAL_RCC_GPIOD_CLK_ENABLE(); GPIO_InitStruct.Pin = LED_PIN; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_PULLUP; @@ -119,19 +124,14 @@ void board_init(void) board_led_write(false); // Button - __HAL_RCC_GPIOA_CLK_ENABLE(); GPIO_InitStruct.Pin = BUTTON_PIN; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_PULLDOWN; GPIO_InitStruct.Speed = GPIO_SPEED_FAST; HAL_GPIO_Init(BUTTON_PORT, &GPIO_InitStruct); - // Enable USB OTG clock - __HAL_RCC_USB_OTG_FS_CLK_ENABLE(); - /* Configure USB FS GPIOs */ /* Configure USB D+ D- Pins */ - __HAL_RCC_GPIOA_CLK_ENABLE(); GPIO_InitStruct.Pin = GPIO_PIN_11 | GPIO_PIN_12; GPIO_InitStruct.Speed = GPIO_SPEED_HIGH; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; @@ -152,6 +152,13 @@ void board_init(void) GPIO_InitStruct.Speed = GPIO_SPEED_HIGH; GPIO_InitStruct.Alternate = GPIO_AF10_OTG_FS; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); + + // Enable USB OTG clock + __HAL_RCC_USB_OTG_FS_CLK_ENABLE(); + + // Enable VBUS sense (B device) via pin PA9 + USB_OTG_FS->GCCFG &= ~USB_OTG_GCCFG_NOVBUSSENS; + USB_OTG_FS->GCCFG |= USB_OTG_GCCFG_VBUSBSEN; } //--------------------------------------------------------------------+ diff --git a/hw/bsp/stm32f412disco/stm32f412disco.c b/hw/bsp/stm32f412disco/stm32f412disco.c index 8d93013c..10778bcf 100644 --- a/hw/bsp/stm32f412disco/stm32f412disco.c +++ b/hw/bsp/stm32f412disco/stm32f412disco.c @@ -38,6 +38,14 @@ #define BUTTON_PIN GPIO_PIN_0 #define BUTTON_STATE_ACTIVE 1 + +// enable all LED, Button, Uart, USB clock +static void all_rcc_clk_enable(void) +{ + __HAL_RCC_GPIOA_CLK_ENABLE(); // USB D+, D-, Button + __HAL_RCC_GPIOE_CLK_ENABLE(); // LED +} + /** * @brief System Clock Configuration * The system Clock is configured as follow : @@ -114,9 +122,8 @@ static void SystemClock_Config(void) void board_init(void) { SystemClock_Config(); - - // Notify runtime of frequency change. SystemCoreClockUpdate(); + all_rcc_clk_enable(); #if CFG_TUSB_OS == OPT_OS_NONE // 1ms tick timer @@ -129,7 +136,6 @@ void board_init(void) GPIO_InitTypeDef GPIO_InitStruct; // LED - __HAL_RCC_GPIOE_CLK_ENABLE(); GPIO_InitStruct.Pin = LED_PIN; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_PULLUP; @@ -139,7 +145,6 @@ void board_init(void) board_led_write(false); // Button - __HAL_RCC_GPIOA_CLK_ENABLE(); GPIO_InitStruct.Pin = BUTTON_PIN; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_PULLDOWN; @@ -148,7 +153,6 @@ void board_init(void) /* Configure USB FS GPIOs */ /* Configure USB D+ D- Pins */ - __HAL_RCC_GPIOA_CLK_ENABLE(); GPIO_InitStruct.Pin = GPIO_PIN_11 | GPIO_PIN_12; GPIO_InitStruct.Speed = GPIO_SPEED_HIGH; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; @@ -179,6 +183,9 @@ void board_init(void) // Enable USB OTG clock __HAL_RCC_USB_OTG_FS_CLK_ENABLE(); + + // Enable VBUS sense (B device) via pin PA9 + USB_OTG_FS->GCCFG |= USB_OTG_GCCFG_VBDEN; } //--------------------------------------------------------------------+ diff --git a/hw/bsp/stm32f767nucleo/stm32f767nucleo.c b/hw/bsp/stm32f767nucleo/stm32f767nucleo.c index 13966438..7367c56b 100644 --- a/hw/bsp/stm32f767nucleo/stm32f767nucleo.c +++ b/hw/bsp/stm32f767nucleo/stm32f767nucleo.c @@ -189,6 +189,9 @@ void board_init(void) /* Enable USB FS Clocks */ __HAL_RCC_USB_OTG_FS_CLK_ENABLE(); + + // Enable VBUS sense (B device) via pin PA9 + USB_OTG_FS->GCCFG |= USB_OTG_GCCFG_VBDEN; } //--------------------------------------------------------------------+ diff --git a/hw/bsp/stm32h743nucleo/stm32h743nucleo.c b/hw/bsp/stm32h743nucleo/stm32h743nucleo.c index f7e46a15..b7071ed6 100644 --- a/hw/bsp/stm32h743nucleo/stm32h743nucleo.c +++ b/hw/bsp/stm32h743nucleo/stm32h743nucleo.c @@ -30,10 +30,23 @@ #include "stm32h7xx.h" #include "stm32h7xx_hal_conf.h" -#define LED_PORT GPIOB -#define LED_PIN GPIO_PIN_0 -#define BUTTON_PORT GPIOC -#define BUTTON_PIN GPIO_PIN_13 +#define LED_PORT GPIOB +#define LED_PIN GPIO_PIN_0 +#define LED_STATE_ON 1 + +#define BUTTON_PORT GPIOC +#define BUTTON_PIN GPIO_PIN_13 +#define BUTTON_STATE_ACTIVE 1 + +// enable all LED, Button, Uart, USB clock +static void all_rcc_clk_enable(void) +{ + __HAL_RCC_GPIOA_CLK_ENABLE(); // USB D+, D- + __HAL_RCC_GPIOB_CLK_ENABLE(); // LED + __HAL_RCC_GPIOC_CLK_ENABLE(); // Button +// __HAL_RCC_GPIOD_CLK_ENABLE(); // Uart tx, rx +// __HAL_RCC_USART3_CLK_ENABLE(); // Uart module +} /* PWR, RCC, GPIO (All): AHB4 (D3 domain) USB{1,2} OTG_{H,F}S: AHB1 (D2 domain) @@ -127,14 +140,27 @@ void board_init(void) #endif SystemClock_Config(); - SystemCoreClockUpdate(); + all_rcc_clk_enable(); GPIO_InitTypeDef GPIO_InitStruct; + // LED + GPIO_InitStruct.Pin = LED_PIN; + GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; + GPIO_InitStruct.Pull = GPIO_PULLUP; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; + HAL_GPIO_Init(LED_PORT, &GPIO_InitStruct); + + // Button + GPIO_InitStruct.Pin = BUTTON_PIN; + GPIO_InitStruct.Mode = GPIO_MODE_INPUT; + GPIO_InitStruct.Pull = GPIO_NOPULL; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; + HAL_GPIO_Init(BUTTON_PORT, &GPIO_InitStruct); + // USB Pin Init // PA9- VUSB, PA10- ID, PA11- DM, PA12- DP - __HAL_RCC_GPIOA_CLK_ENABLE(); /* Configure DM DP Pins */ GPIO_InitStruct.Pin = GPIO_PIN_11 | GPIO_PIN_12; @@ -158,27 +184,13 @@ void board_init(void) GPIO_InitStruct.Alternate = GPIO_AF10_OTG2_HS; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); - // LED - __HAL_RCC_GPIOB_CLK_ENABLE(); - - GPIO_InitStruct.Pin = LED_PIN; - GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; - GPIO_InitStruct.Pull = GPIO_PULLUP; - GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; - HAL_GPIO_Init(LED_PORT, &GPIO_InitStruct); - - // Button - __HAL_RCC_GPIOC_CLK_ENABLE(); - GPIO_InitStruct.Pin = BUTTON_PIN; - GPIO_InitStruct.Mode = GPIO_MODE_INPUT; - GPIO_InitStruct.Pull = GPIO_NOPULL; - GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; - HAL_GPIO_Init(BUTTON_PORT, &GPIO_InitStruct); - // https://community.st.com/s/question/0D50X00009XkYZLSA3/stm32h7-nucleo-usb-fs-cdc // TODO: Board init actually works fine without this line. HAL_PWREx_EnableUSBVoltageDetector(); __HAL_RCC_USB2_OTG_FS_CLK_ENABLE(); + + // Enable VBUS sense (B device) via pin PA9 + USB_OTG_FS->GCCFG |= USB_OTG_GCCFG_VBDEN; } //--------------------------------------------------------------------+ diff --git a/hw/bsp/stm32l476disco/stm32l476disco.c b/hw/bsp/stm32l476disco/stm32l476disco.c index a4cad68b..ac4ef365 100644 --- a/hw/bsp/stm32l476disco/stm32l476disco.c +++ b/hw/bsp/stm32l476disco/stm32l476disco.c @@ -38,6 +38,16 @@ #define BUTTON_PIN GPIO_PIN_0 #define BUTTON_STATE_ACTIVE 1 + +// enable all LED, Button, Uart, USB clock +static void all_rcc_clk_enable(void) +{ + __HAL_RCC_GPIOA_CLK_ENABLE(); // USB D+, D-, Button + __HAL_RCC_GPIOB_CLK_ENABLE(); // LED + __HAL_RCC_GPIOC_CLK_ENABLE(); // VBUS pin +} + + /** * @brief System Clock Configuration * The system Clock is configured as follow : @@ -117,6 +127,8 @@ void board_init(void) #endif SystemClock_Config(); + SystemCoreClockUpdate(); + all_rcc_clk_enable(); /* Enable Power Clock*/ __HAL_RCC_PWR_CLK_ENABLE(); @@ -124,13 +136,9 @@ void board_init(void) /* Enable USB power on Pwrctrl CR2 register */ HAL_PWREx_EnableVddUSB(); - // Notify runtime of frequency change. - SystemCoreClockUpdate(); - GPIO_InitTypeDef GPIO_InitStruct; // LED - __HAL_RCC_GPIOB_CLK_ENABLE(); GPIO_InitStruct.Pin = LED_PIN; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_PULLUP; @@ -140,7 +148,6 @@ void board_init(void) board_led_write(false); // Button - __HAL_RCC_GPIOA_CLK_ENABLE(); GPIO_InitStruct.Pin = BUTTON_PIN; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_PULLDOWN; @@ -149,7 +156,6 @@ void board_init(void) // USB /* Configure DM DP Pins */ - __HAL_RCC_GPIOA_CLK_ENABLE(); GPIO_InitStruct.Pin = (GPIO_PIN_11 | GPIO_PIN_12); GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; @@ -158,7 +164,6 @@ void board_init(void) HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); /* Configure VBUS Pin */ - __HAL_RCC_GPIOC_CLK_ENABLE(); GPIO_InitStruct.Pin = GPIO_PIN_11; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_NOPULL; @@ -166,6 +171,9 @@ void board_init(void) /* Enable USB FS Clock */ __HAL_RCC_USB_OTG_FS_CLK_ENABLE(); + + // Enable VBUS sense (B device) via pin PA9 + USB_OTG_FS->GCCFG |= USB_OTG_GCCFG_VBDEN; } //--------------------------------------------------------------------+ diff --git a/src/portable/st/synopsys/dcd_synopsys.c b/src/portable/st/synopsys/dcd_synopsys.c index 7929b691..b25cfcca 100644 --- a/src/portable/st/synopsys/dcd_synopsys.c +++ b/src/portable/st/synopsys/dcd_synopsys.c @@ -207,12 +207,8 @@ void dcd_init (uint8_t rhport) USB_OTG_GINTMSK_SOFM | USB_OTG_GINTMSK_RXFLVLM /* SB_OTG_GINTMSK_ESUSPM | \ USB_OTG_GINTMSK_USBSUSPM */; - // Enable VBUS hardware sensing, enable pullup, enable peripheral. -#ifdef USB_OTG_GCCFG_VBDEN - USB_OTG_FS->GCCFG |= USB_OTG_GCCFG_VBDEN | USB_OTG_GCCFG_PWRDWN; -#else - USB_OTG_FS->GCCFG |= USB_OTG_GCCFG_VBUSBSEN | USB_OTG_GCCFG_PWRDWN; -#endif + // Enable USB transceiver. + USB_OTG_FS->GCCFG |= USB_OTG_GCCFG_PWRDWN; // Soft Connect -> Enable pullup on D+/D-. // This step does not appear to be specified in the programmer's model. From 88bdb12ee506a143e2fa1033c258a0540c0768bd Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 11 Dec 2019 15:19:51 +0700 Subject: [PATCH 127/267] close #204 define HSE_VALUE in _hal_conf instead of board.mk --- hw/bsp/feather_stm32f405/board.mk | 1 - hw/bsp/pyboardv11/board.mk | 1 - hw/bsp/stm32f070rbnucleo/board.mk | 1 - hw/bsp/stm32f072disco/board.mk | 1 - hw/bsp/stm32f103bluepill/board.mk | 1 - hw/bsp/stm32f207nucleo/board.mk | 1 - hw/bsp/stm32f303disco/board.mk | 1 - hw/bsp/stm32f407disco/board.mk | 1 - hw/bsp/stm32f411disco/board.mk | 1 - hw/bsp/stm32f412disco/board.mk | 1 - hw/bsp/stm32f767nucleo/board.mk | 1 - hw/bsp/stm32h743nucleo/board.mk | 1 - hw/bsp/stm32h743nucleo/stm32h7xx_hal_conf.h | 2 +- hw/bsp/stm32l0538disco/board.mk | 1 - hw/bsp/stm32l476disco/board.mk | 1 - 15 files changed, 1 insertion(+), 15 deletions(-) diff --git a/hw/bsp/feather_stm32f405/board.mk b/hw/bsp/feather_stm32f405/board.mk index 1e68737b..ba84dd3a 100644 --- a/hw/bsp/feather_stm32f405/board.mk +++ b/hw/bsp/feather_stm32f405/board.mk @@ -7,7 +7,6 @@ CFLAGS += \ -mfpu=fpv4-sp-d16 \ -nostdlib -nostartfiles \ -DSTM32F405xx \ - -DHSE_VALUE=12000000 \ -DCFG_TUSB_MCU=OPT_MCU_STM32F4 ST_HAL_DRIVER = hw/mcu/st/st_driver/STM32F4xx_HAL_Driver diff --git a/hw/bsp/pyboardv11/board.mk b/hw/bsp/pyboardv11/board.mk index 0118b54a..f57f662f 100644 --- a/hw/bsp/pyboardv11/board.mk +++ b/hw/bsp/pyboardv11/board.mk @@ -7,7 +7,6 @@ CFLAGS += \ -mfpu=fpv4-sp-d16 \ -nostdlib -nostartfiles \ -DSTM32F405xx \ - -DHSE_VALUE=12000000 \ -DCFG_TUSB_MCU=OPT_MCU_STM32F4 ST_HAL_DRIVER = hw/mcu/st/st_driver/STM32F4xx_HAL_Driver diff --git a/hw/bsp/stm32f070rbnucleo/board.mk b/hw/bsp/stm32f070rbnucleo/board.mk index 6e52b814..07d885dc 100644 --- a/hw/bsp/stm32f070rbnucleo/board.mk +++ b/hw/bsp/stm32f070rbnucleo/board.mk @@ -5,7 +5,6 @@ CFLAGS += \ -mcpu=cortex-m0 \ -mfloat-abi=soft \ -nostdlib -nostartfiles \ - -DHSE_VALUE=8000000 \ -DSTM32F070xB \ -DCFG_EXAMPLE_MSC_READONLY \ -DCFG_TUSB_MCU=OPT_MCU_STM32F0 diff --git a/hw/bsp/stm32f072disco/board.mk b/hw/bsp/stm32f072disco/board.mk index 5ed87cfa..cae3b562 100644 --- a/hw/bsp/stm32f072disco/board.mk +++ b/hw/bsp/stm32f072disco/board.mk @@ -6,7 +6,6 @@ CFLAGS += \ -mfloat-abi=soft \ -nostdlib -nostartfiles \ -DSTM32F072xB \ - -DHSE_VALUE=8000000 \ -DCFG_EXAMPLE_MSC_READONLY \ -DCFG_TUSB_MCU=OPT_MCU_STM32F0 diff --git a/hw/bsp/stm32f103bluepill/board.mk b/hw/bsp/stm32f103bluepill/board.mk index f464fa29..7c1a7b37 100644 --- a/hw/bsp/stm32f103bluepill/board.mk +++ b/hw/bsp/stm32f103bluepill/board.mk @@ -6,7 +6,6 @@ CFLAGS += \ -mfloat-abi=soft \ -nostdlib -nostartfiles \ -DSTM32F103xB \ - -DHSE_VALUE=8000000 \ -DCFG_TUSB_MCU=OPT_MCU_STM32F1 # mcu driver cause following warnings diff --git a/hw/bsp/stm32f207nucleo/board.mk b/hw/bsp/stm32f207nucleo/board.mk index 003a3dd4..2eb92f17 100644 --- a/hw/bsp/stm32f207nucleo/board.mk +++ b/hw/bsp/stm32f207nucleo/board.mk @@ -6,7 +6,6 @@ CFLAGS += \ -mfloat-abi=soft \ -nostdlib -nostartfiles \ -DSTM32F207xx \ - -DHSE_VALUE=8000000 \ -DCFG_TUSB_MCU=OPT_MCU_STM32F2 # mcu driver cause following warnings diff --git a/hw/bsp/stm32f303disco/board.mk b/hw/bsp/stm32f303disco/board.mk index fbe03414..61c85103 100644 --- a/hw/bsp/stm32f303disco/board.mk +++ b/hw/bsp/stm32f303disco/board.mk @@ -7,7 +7,6 @@ CFLAGS += \ -mfpu=fpv4-sp-d16 \ -nostdlib -nostartfiles \ -DSTM32F303xC \ - -DHSE_VALUE=8000000 \ -DCFG_TUSB_MCU=OPT_MCU_STM32F3 # mcu driver cause following warnings diff --git a/hw/bsp/stm32f407disco/board.mk b/hw/bsp/stm32f407disco/board.mk index 216b51bf..e80e84bc 100644 --- a/hw/bsp/stm32f407disco/board.mk +++ b/hw/bsp/stm32f407disco/board.mk @@ -7,7 +7,6 @@ CFLAGS += \ -mfpu=fpv4-sp-d16 \ -nostdlib -nostartfiles \ -DSTM32F407xx \ - -DHSE_VALUE=8000000 \ -DCFG_TUSB_MCU=OPT_MCU_STM32F4 ST_HAL_DRIVER = hw/mcu/st/st_driver/STM32F4xx_HAL_Driver diff --git a/hw/bsp/stm32f411disco/board.mk b/hw/bsp/stm32f411disco/board.mk index 63aa7615..5cbe0524 100644 --- a/hw/bsp/stm32f411disco/board.mk +++ b/hw/bsp/stm32f411disco/board.mk @@ -7,7 +7,6 @@ CFLAGS += \ -mfpu=fpv4-sp-d16 \ -nostdlib -nostartfiles \ -DSTM32F411xE \ - -DHSE_VALUE=8000000 \ -DCFG_TUSB_MCU=OPT_MCU_STM32F4 ST_HAL_DRIVER = hw/mcu/st/st_driver/STM32F4xx_HAL_Driver diff --git a/hw/bsp/stm32f412disco/board.mk b/hw/bsp/stm32f412disco/board.mk index ddb8402e..9b54ab55 100644 --- a/hw/bsp/stm32f412disco/board.mk +++ b/hw/bsp/stm32f412disco/board.mk @@ -7,7 +7,6 @@ CFLAGS += \ -mfpu=fpv4-sp-d16 \ -nostdlib -nostartfiles \ -DSTM32F412Zx \ - -DHSE_VALUE=8000000 \ -DCFG_TUSB_MCU=OPT_MCU_STM32F4 # mcu driver cause following warnings diff --git a/hw/bsp/stm32f767nucleo/board.mk b/hw/bsp/stm32f767nucleo/board.mk index 5d964537..152e0bdb 100644 --- a/hw/bsp/stm32f767nucleo/board.mk +++ b/hw/bsp/stm32f767nucleo/board.mk @@ -7,7 +7,6 @@ CFLAGS += \ -mfpu=fpv5-d16 \ -nostdlib -nostartfiles \ -DSTM32F767xx \ - -DHSE_VALUE=8000000 \ -DCFG_TUSB_MCU=OPT_MCU_STM32F7 # mcu driver cause following warnings diff --git a/hw/bsp/stm32h743nucleo/board.mk b/hw/bsp/stm32h743nucleo/board.mk index cfea7f57..928ad9a8 100644 --- a/hw/bsp/stm32h743nucleo/board.mk +++ b/hw/bsp/stm32h743nucleo/board.mk @@ -7,7 +7,6 @@ CFLAGS += \ -mfpu=fpv5-d16 \ -nostdlib -nostartfiles \ -DSTM32H743xx \ - -DHSE_VALUE=8000000 \ -DCFG_TUSB_MCU=OPT_MCU_STM32H7 # mcu driver cause following warnings diff --git a/hw/bsp/stm32h743nucleo/stm32h7xx_hal_conf.h b/hw/bsp/stm32h743nucleo/stm32h7xx_hal_conf.h index 2a9eb37a..c58fdf75 100644 --- a/hw/bsp/stm32h743nucleo/stm32h7xx_hal_conf.h +++ b/hw/bsp/stm32h743nucleo/stm32h7xx_hal_conf.h @@ -111,7 +111,7 @@ * (when HSE is used as system clock source, directly or through the PLL). */ #if !defined (HSE_VALUE) -#define HSE_VALUE ((uint32_t)25000000) /*!< Value of the External oscillator in Hz */ +#define HSE_VALUE ((uint32_t)8000000) /*!< Value of the External oscillator in Hz */ #endif /* HSE_VALUE */ #if !defined (HSE_STARTUP_TIMEOUT) diff --git a/hw/bsp/stm32l0538disco/board.mk b/hw/bsp/stm32l0538disco/board.mk index d81b2d88..241ad5d2 100644 --- a/hw/bsp/stm32l0538disco/board.mk +++ b/hw/bsp/stm32l0538disco/board.mk @@ -6,7 +6,6 @@ CFLAGS += \ -mfloat-abi=soft \ -nostdlib -nostartfiles \ -DSTM32L053xx \ - -DHSE_VALUE=8000000 \ -DCFG_EXAMPLE_MSC_READONLY \ -DCFG_TUSB_MCU=OPT_MCU_STM32L0 diff --git a/hw/bsp/stm32l476disco/board.mk b/hw/bsp/stm32l476disco/board.mk index 3432ac2e..dc6b886d 100644 --- a/hw/bsp/stm32l476disco/board.mk +++ b/hw/bsp/stm32l476disco/board.mk @@ -7,7 +7,6 @@ CFLAGS += \ -mfpu=fpv4-sp-d16 \ -nostdlib -nostartfiles \ -DSTM32L476xx \ - -DHSE_VALUE=8000000 \ -DCFG_TUSB_MCU=OPT_MCU_STM32L4 ST_HAL_DRIVER = hw/mcu/st/st_driver/STM32L4xx_HAL_Driver From 9d96b6d66eab8a8dea44db1a2c346f667d22ce21 Mon Sep 17 00:00:00 2001 From: Jeremy Herbert Date: Thu, 12 Dec 2019 09:40:06 +1000 Subject: [PATCH 128/267] Update dcd_stm32_fsdev.c Add a note about pin remapping for the STM32F042Fx --- src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c b/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c index ec182960..9e99ea1d 100644 --- a/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c +++ b/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c @@ -30,7 +30,7 @@ /********************************************** * This driver has been tested with the following MCUs: - * - F070, F072, L053 + * - F070, F072, L053, F042F6 * * It also should work with minimal changes for any ST MCU with an "USB A"/"PCD"/"HCD" peripheral. This * covers: @@ -44,6 +44,9 @@ * L4x2, L4x3 1024 byte buffer * * To use this driver, you must: + * - If you are using a device with crystal-less USB, set up the clock recovery system (CRS) + * - Remap pins to be D+/D- on devices that they are shared (for example: F042Fx) + * - This is different to the normal "alternate function" GPIO interface, needs to go through SYSCFG->CFGRx register * - Enable USB clock; Perhaps use __HAL_RCC_USB_CLK_ENABLE(); * - (Optionally configure GPIO HAL to tell it the USB driver is using the USB pins) * - call tusb_init(); From fdce63b268579f4b847980172d113577de28900e Mon Sep 17 00:00:00 2001 From: samveen Date: Mon, 16 Dec 2019 23:01:26 +0530 Subject: [PATCH 129/267] [tusb]fix typo in comment --- src/class/hid/hid.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/class/hid/hid.h b/src/class/hid/hid.h index a3a9ffc8..cb5e6047 100644 --- a/src/class/hid/hid.h +++ b/src/class/hid/hid.h @@ -180,7 +180,7 @@ typedef enum /// Standard HID Boot Protocol Keyboard Report. typedef struct TU_ATTR_PACKED { - uint8_t modifier; /**< Keyboard modifier (KEYBOARD_MODIFER_* masks). */ + uint8_t modifier; /**< Keyboard modifier (KEYBOARD_MODIFIER_* masks). */ uint8_t reserved; /**< Reserved for OEM use, always set to 0. */ uint8_t keycode[6]; /**< Key codes of the currently pressed keys. */ } hid_keyboard_report_t; From ba8a2329700059a52594efdfe8d0f98018e02fc7 Mon Sep 17 00:00:00 2001 From: samveen Date: Tue, 17 Dec 2019 12:47:05 +0530 Subject: [PATCH 130/267] add "`" and "~" to keycode -> ASCII table --- src/class/hid/hid.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/class/hid/hid.h b/src/class/hid/hid.h index cb5e6047..7fa4aa8a 100644 --- a/src/class/hid/hid.h +++ b/src/class/hid/hid.h @@ -812,7 +812,7 @@ enum {'#' , '~' }, /* 0x32 */ \ {';' , ':' }, /* 0x33 */ \ {'\'' , '\"' }, /* 0x34 */ \ - {0 , 0 }, /* 0x35 */ \ + {'`' , '~' }, /* 0x35 */ \ {',' , '<' }, /* 0x36 */ \ {'.' , '>' }, /* 0x37 */ \ {'/' , '?' }, /* 0x38 */ \ From 65711de870ba4ef178d08f9f02fb76c69306aa67 Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 18 Dec 2019 15:18:05 +0700 Subject: [PATCH 131/267] added coverity badge --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3f7556cf..3f7e7ecd 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ ![tinyUSB_240x100](https://user-images.githubusercontent.com/249515/62646655-f9393200-b978-11e9-9c53-484862f15503.png) -[![Build Status](https://travis-ci.org/hathach/tinyusb.svg?branch=master)](https://travis-ci.org/hathach/tinyusb) [![License](https://img.shields.io/badge/license-MIT-brightgreen.svg)](https://opensource.org/licenses/MIT) +[![Build Status](https://travis-ci.org/hathach/tinyusb.svg?branch=master)](https://travis-ci.org/hathach/tinyusb) [![License](https://img.shields.io/badge/license-MIT-brightgreen.svg)](https://opensource.org/licenses/MIT)[![Coverity](https://img.shields.io/coverity/scan/458.svg)](https://scan.coverity.com/projects/tinyusb) TinyUSB is an open-source cross-platform USB Host/Device stack for embedded system, designed to be memory-safe with no dynamic allocation and thread-safe with all interrupt events are deferred then handled in the non-ISR task function. From a1e55e57a4b012742e0f571723e86d1bcdc91186 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 20 Dec 2019 17:09:42 +0700 Subject: [PATCH 132/267] clean warnings --- src/device/usbd.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/device/usbd.h b/src/device/usbd.h index 9d39af13..e685686a 100644 --- a/src/device/usbd.h +++ b/src/device/usbd.h @@ -212,7 +212,7 @@ TU_ATTR_WEAK bool tud_vendor_control_complete_cb(uint8_t rhport, tusb_control_re // Interface number, string index, protocol, report descriptor len, EP In address, size & polling interval #define TUD_HID_DESCRIPTOR(_itfnum, _stridx, _boot_protocol, _report_desc_len, _epin, _epsize, _ep_interval) \ /* Interface */\ - 9, TUSB_DESC_INTERFACE, _itfnum, 0, 1, TUSB_CLASS_HID, (_boot_protocol) ? HID_SUBCLASS_BOOT : 0, _boot_protocol, _stridx,\ + 9, TUSB_DESC_INTERFACE, _itfnum, 0, 1, TUSB_CLASS_HID, (uint8_t)((_boot_protocol) ? HID_SUBCLASS_BOOT : 0), _boot_protocol, _stridx,\ /* HID descriptor */\ 9, HID_DESC_TYPE_HID, U16_TO_U8S_LE(0x0111), 0, 1, HID_DESC_TYPE_REPORT, U16_TO_U8S_LE(_report_desc_len),\ /* Endpoint In */\ @@ -225,7 +225,7 @@ TU_ATTR_WEAK bool tud_vendor_control_complete_cb(uint8_t rhport, tusb_control_re // Interface number, string index, protocol, report descriptor len, EP OUT & IN address, size & polling interval #define TUD_HID_INOUT_DESCRIPTOR(_itfnum, _stridx, _boot_protocol, _report_desc_len, _epout, _epin, _epsize, _ep_interval) \ /* Interface */\ - 9, TUSB_DESC_INTERFACE, _itfnum, 0, 2, TUSB_CLASS_HID, (_boot_protocol) ? HID_SUBCLASS_BOOT : 0, _boot_protocol, _stridx,\ + 9, TUSB_DESC_INTERFACE, _itfnum, 0, 2, TUSB_CLASS_HID, (uint8_t)((_boot_protocol) ? HID_SUBCLASS_BOOT : 0), _boot_protocol, _stridx,\ /* HID descriptor */\ 9, HID_DESC_TYPE_HID, U16_TO_U8S_LE(0x0111), 0, 1, HID_DESC_TYPE_REPORT, U16_TO_U8S_LE(_report_desc_len),\ /* Endpoint Out */\ From 050fa2fd394912775994d4171774adb475eaf531 Mon Sep 17 00:00:00 2001 From: hathach Date: Sat, 21 Dec 2019 19:33:41 +0700 Subject: [PATCH 133/267] able to response to scsi inquiry, but failed to response to test unit ready --- src/class/msc/msc_device.c | 9 ++ src/common/tusb_common.h | 2 +- src/device/usbd.c | 5 +- src/portable/microchip/samg/dcd_samg.c | 158 +++++++++++++++++-------- src/tusb.c | 6 +- 5 files changed, 125 insertions(+), 55 deletions(-) diff --git a/src/class/msc/msc_device.c b/src/class/msc/msc_device.c index bf2b5bb8..19025226 100644 --- a/src/class/msc/msc_device.c +++ b/src/class/msc/msc_device.c @@ -378,6 +378,9 @@ bool mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t TU_ASSERT( event == XFER_RESULT_SUCCESS && xferred_bytes == sizeof(msc_cbw_t) && p_cbw->signature == MSC_CBW_SIGNATURE ); + TU_LOG2(" Command Block Wrapper\n"); + TU_LOG2_MEM(p_cbw, xferred_bytes, 2); + p_csw->signature = MSC_CSW_SIGNATURE; p_csw->tag = p_cbw->tag; p_csw->data_residue = 0; @@ -448,6 +451,9 @@ bool mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t break; case MSC_STAGE_DATA: + //TU_LOG2(" SCSI Data\n"); + //TU_LOG2_MEM(_mscd_buf, xferred_bytes, 2); + // OUT transfer, invoke callback if needed if ( !tu_bit_test(p_cbw->dir, 7) ) { @@ -538,6 +544,9 @@ bool mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t // Wait for the command status wrapper complete event if( (ep_addr == p_msc->ep_in) && (xferred_bytes == sizeof(msc_csw_t)) ) { + TU_LOG2(" Command Status Wrapper\n"); + TU_LOG2_MEM(p_csw, xferred_bytes, 2); + // Move to default CMD stage p_msc->stage = MSC_STAGE_CMD; diff --git a/src/common/tusb_common.h b/src/common/tusb_common.h index a2c40e66..f76abca8 100644 --- a/src/common/tusb_common.h +++ b/src/common/tusb_common.h @@ -213,7 +213,7 @@ static inline bool tu_bit_test (uint32_t value, uint8_t pos) { return (value // 2 : print out log #if CFG_TUSB_DEBUG -void tu_print_mem(void const *buf, uint8_t size, uint16_t count); +void tu_print_mem(void const *buf, uint16_t count, uint8_t indent); #ifndef tu_printf #define tu_printf printf diff --git a/src/device/usbd.c b/src/device/usbd.c index 497281c2..5832f235 100644 --- a/src/device/usbd.c +++ b/src/device/usbd.c @@ -376,8 +376,7 @@ void tud_task (void) break; case DCD_EVENT_SETUP_RECEIVED: - TU_LOG2(" "); - TU_LOG2_MEM(&event.setup_received, 1, 8); + TU_LOG2_MEM(&event.setup_received, 8, 2); // Mark as connected after receiving 1st setup packet. // But it is easier to set it every time instead of wasting time to check then set @@ -949,6 +948,8 @@ bool usbd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t TU_VERIFY( dcd_edpt_xfer(rhport, ep_addr, buffer, total_bytes) ); _usbd_dev.ep_status[epnum][dir].busy = true; + TU_LOG2(" XFER Endpoint: 0x%02X, Bytes: %d\r\n", ep_addr, total_bytes); + return true; } diff --git a/src/portable/microchip/samg/dcd_samg.c b/src/portable/microchip/samg/dcd_samg.c index f05763e3..96cd775c 100644 --- a/src/portable/microchip/samg/dcd_samg.c +++ b/src/portable/microchip/samg/dcd_samg.c @@ -51,6 +51,11 @@ typedef struct // Endpoint 0-5, each can only be either OUT or In xfer_desc_t _dcd_xfer[EP_COUNT]; +void xfer_epsize_set(xfer_desc_t* xfer, uint16_t epsize) +{ + xfer->epsize = epsize; +} + void xfer_begin(xfer_desc_t* xfer, uint8_t * buffer, uint16_t total_bytes) { xfer->buffer = buffer; @@ -73,14 +78,23 @@ void xfer_packet_done(xfer_desc_t* xfer) } //------------- Transaction helpers -------------// -static uint16_t xact_in(uint8_t epnum, xfer_desc_t* xfer) + +// Write data to EP FIFO, return number of written bytes +static void xact_ep_write(uint8_t epnum, uint8_t* buffer, uint16_t xact_len) { - uint16_t const xact_len = xfer_packet_len(xfer); + for(uint16_t i=0; iUDP_FDR[epnum] = (uint32_t) buffer[i]; + } +} - // Write data to fifo - for(uint16_t i=0; iUDP_FDR[epnum] = (uint32_t) xfer->buffer[i]; - - return xact_len; +// Read data from EP FIFO +static void xact_ep_read(uint8_t epnum, uint8_t* buffer, uint16_t xact_len) +{ + for(uint16_t i=0; iUDP_FDR[epnum]; + } } /*------------------------------------------------------------------*/ @@ -92,7 +106,7 @@ static void bus_reset(void) { tu_memclr(_dcd_xfer, sizeof(_dcd_xfer)); - _dcd_xfer[0].epsize = CFG_TUD_ENDPOINT0_SIZE; + xfer_epsize_set(&_dcd_xfer[0], CFG_TUD_ENDPOINT0_SIZE); // Enable EP0 control UDP->UDP_CSR[0] = UDP_CSR_EPEDS_Msk; @@ -205,11 +219,13 @@ bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * ep_desc) // Must not already enabled TU_ASSERT((UDP->UDP_CSR[epnum] & UDP_CSR_EPEDS_Msk) == 0); + xfer_epsize_set(&_dcd_xfer[epnum], ep_desc->wMaxPacketSize.size); + // Configure type and eanble EP UDP->UDP_CSR[epnum] = UDP_CSR_EPEDS_Msk | UDP_CSR_EPTYPE(ep_desc->bmAttributes.xfer + 4*dir); - // Enable EP Interrupt - UDP->UDP_IER |= (1 << epnum); + // Enable EP Interrupt for IN + if (dir == TUSB_DIR_IN) UDP->UDP_IER |= (1 << epnum); return true; } @@ -225,27 +241,47 @@ bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t xfer_desc_t* xfer = &_dcd_xfer[epnum]; xfer_begin(xfer, buffer, total_bytes); - // Configure DIR bit for control endpoint - if ( epnum == 0 ) - { - if (dir == TUSB_DIR_OUT) - { - // Clear DIR bit - UDP->UDP_CSR[0] &= ~UDP_CSR_DIR_Msk; - }else - { - // Set DIR bit - UDP->UDP_CSR[0] |= UDP_CSR_DIR_Msk; - } - } - if (dir == TUSB_DIR_IN) { - xact_in(epnum, xfer); + // Set DIR bit for EP0 + if ( epnum == 0 ) UDP->UDP_CSR[epnum] |= UDP_CSR_DIR_Msk; + + xact_ep_write(epnum, xfer->buffer, xfer_packet_len(xfer)); // TX ready for transfer UDP->UDP_CSR[epnum] |= UDP_CSR_TXPKTRDY_Msk; } + else + { + // Clear DIR bit for EP0 + if ( epnum == 0 ) UDP->UDP_CSR[epnum] &= ~UDP_CSR_DIR_Msk; + + // OUT Data may already received and acked by hardware + // Read it as 1st packet then continue with transfer if needed +// uint16_t const xact_len = (uint16_t) ((UDP->UDP_CSR[epnum] & UDP_CSR_RXBYTECNT_Msk) >> UDP_CSR_RXBYTECNT_Pos); +// +// if ( xact_len ) +// { +// // Read from EP fifo +// xact_ep_read(epnum, xfer->buffer, xact_len); +// xfer_packet_done(xfer); +// +// // Clear DATA Bank0 bit +// UDP->UDP_CSR[epnum] &= ~UDP_CSR_RX_DATA_BK0_Msk; +// +// if ( 0 == xfer_packet_len(xfer) ) +// { +// // Disable OUT EP interrupt when transfer is complete +// UDP->UDP_IER &= ~(1 << epnum); +// +// dcd_event_xfer_complete(rhport, epnum, xact_len, XFER_RESULT_SUCCESS, false); +// return true; // complete +// } +// } + + // Enable interrupt when starting OUT transfer + UDP->UDP_IER |= (1 << epnum); + } return true; } @@ -325,47 +361,67 @@ void dcd_isr(uint8_t rhport) // Clear Setup bit UDP->UDP_CSR[0] &= ~UDP_CSR_RXSETUP_Msk; + + return; } } for(uint8_t epnum = 0; epnum < EP_COUNT; epnum++) { - xfer_desc_t* xfer = &_dcd_xfer[epnum]; - - // Endpoint IN - if (UDP->UDP_CSR[epnum] & UDP_CSR_TXCOMP_Msk) + if ( intr_status & TU_BIT(epnum) ) { - xfer_packet_done(xfer); + xfer_desc_t* xfer = &_dcd_xfer[epnum]; - if ( xact_in(epnum, xfer) ) + // Endpoint IN + if (UDP->UDP_CSR[epnum] & UDP_CSR_TXCOMP_Msk) { - // TX ready for transfer - UDP->UDP_CSR[epnum] |= UDP_CSR_TXPKTRDY_Msk; - }else - { - // xfer is complete - dcd_event_xfer_complete(rhport, epnum | TUSB_DIR_IN_MASK, xfer->actual_len, XFER_RESULT_SUCCESS, true); + xfer_packet_done(xfer); + + uint16_t const xact_len = xfer_packet_len(xfer); + + if (xact_len) + { + // write to EP fifo + xact_ep_write(epnum, xfer->buffer, xact_len); + + // TX ready for transfer + UDP->UDP_CSR[epnum] |= UDP_CSR_TXPKTRDY_Msk; + }else + { + // xfer is complete + dcd_event_xfer_complete(rhport, epnum | TUSB_DIR_IN_MASK, xfer->actual_len, XFER_RESULT_SUCCESS, true); + } + + // Clear TX Complete bit + UDP->UDP_CSR[epnum] &= ~UDP_CSR_TXCOMP_Msk; } - // Clear TX Complete bit - UDP->UDP_CSR[epnum] &= ~UDP_CSR_TXCOMP_Msk; - } + // Endpoint OUT + if (UDP->UDP_CSR[epnum] & UDP_CSR_RX_DATA_BK0_Msk) + { + uint16_t const xact_len = (uint16_t) ((UDP->UDP_CSR[epnum] & UDP_CSR_RXBYTECNT_Msk) >> UDP_CSR_RXBYTECNT_Pos); - // Endpoint OUT - if (UDP->UDP_CSR[epnum] & UDP_CSR_RX_DATA_BK0_Msk) - { - uint16_t const xact_len = (uint16_t) ((UDP->UDP_CSR[epnum] & UDP_CSR_RXBYTECNT_Msk) >> UDP_CSR_RXBYTECNT_Pos); + // Read from EP fifo + xact_ep_read(epnum, xfer->buffer, xact_len); + xfer_packet_done(xfer); - dcd_event_xfer_complete(rhport, epnum, xact_len, XFER_RESULT_SUCCESS, true); + if ( 0 == xfer_packet_len(xfer) ) + { + // Disable OUT EP interrupt when transfer is complete + UDP->UDP_IER &= ~(1 << epnum); - // Clear DATA Bank0 bit - UDP->UDP_CSR[epnum] &= ~UDP_CSR_RX_DATA_BK0_Msk; - } + dcd_event_xfer_complete(rhport, epnum, xact_len, XFER_RESULT_SUCCESS, true); + } - // Stall sent to host - if (UDP->UDP_CSR[epnum] & UDP_CSR_STALLSENT_Msk) - { - UDP->UDP_CSR[epnum] &= ~UDP_CSR_STALLSENT_Msk; + // Clear DATA Bank0 bit + UDP->UDP_CSR[epnum] &= ~UDP_CSR_RX_DATA_BK0_Msk; + } + + // Stall sent to host + if (UDP->UDP_CSR[epnum] & UDP_CSR_STALLSENT_Msk) + { + UDP->UDP_CSR[epnum] &= ~UDP_CSR_STALLSENT_Msk; + } } } } diff --git a/src/tusb.c b/src/tusb.c index 7a1e73ec..f6838745 100644 --- a/src/tusb.c +++ b/src/tusb.c @@ -81,8 +81,10 @@ static void dump_str_line(uint8_t const* buf, uint16_t count) // size : item size in bytes // count : number of item // print offet or not (handfy for dumping large memory) -void tu_print_mem(void const *buf, uint8_t size, uint16_t count) +void tu_print_mem(void const *buf, uint16_t count, uint8_t indent) { + uint8_t const size = 1; // fixed 1 byte for now + if ( !buf || !count ) { tu_printf("NULL\r\n"); @@ -110,6 +112,8 @@ void tu_print_mem(void const *buf, uint8_t size, uint16_t count) tu_printf("\r\n"); } + for(uint8_t s=0; s < indent; s++) tu_printf(" "); + // print offset or absolute address tu_printf("%03lX: ", 16*i/item_per_line); } From 421221baa5b8509b705f76def43fd684c5fe06df Mon Sep 17 00:00:00 2001 From: hathach Date: Sat, 21 Dec 2019 23:51:57 +0700 Subject: [PATCH 134/267] making more progress, but failed with WRITE10 incorrect queue 448 bytes instead of 512 --- src/class/msc/msc_device.c | 6 ++--- src/portable/microchip/samg/dcd_samg.c | 31 ++++++++++++++++++-------- 2 files changed, 25 insertions(+), 12 deletions(-) diff --git a/src/class/msc/msc_device.c b/src/class/msc/msc_device.c index 19025226..84fe5a19 100644 --- a/src/class/msc/msc_device.c +++ b/src/class/msc/msc_device.c @@ -379,7 +379,7 @@ bool mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes == sizeof(msc_cbw_t) && p_cbw->signature == MSC_CBW_SIGNATURE ); TU_LOG2(" Command Block Wrapper\n"); - TU_LOG2_MEM(p_cbw, xferred_bytes, 2); + // TU_LOG2_MEM(p_cbw, xferred_bytes, 2); p_csw->signature = MSC_CSW_SIGNATURE; p_csw->tag = p_cbw->tag; @@ -451,7 +451,7 @@ bool mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t break; case MSC_STAGE_DATA: - //TU_LOG2(" SCSI Data\n"); + TU_LOG2(" SCSI Data\n"); //TU_LOG2_MEM(_mscd_buf, xferred_bytes, 2); // OUT transfer, invoke callback if needed @@ -545,7 +545,7 @@ bool mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t if( (ep_addr == p_msc->ep_in) && (xferred_bytes == sizeof(msc_csw_t)) ) { TU_LOG2(" Command Status Wrapper\n"); - TU_LOG2_MEM(p_csw, xferred_bytes, 2); + // TU_LOG2_MEM(p_csw, xferred_bytes, 2); // Move to default CMD stage p_msc->stage = MSC_STAGE_CMD; diff --git a/src/portable/microchip/samg/dcd_samg.c b/src/portable/microchip/samg/dcd_samg.c index 96cd775c..fd50237d 100644 --- a/src/portable/microchip/samg/dcd_samg.c +++ b/src/portable/microchip/samg/dcd_samg.c @@ -63,6 +63,13 @@ void xfer_begin(xfer_desc_t* xfer, uint8_t * buffer, uint16_t total_bytes) xfer->actual_len = 0; } +void xfer_end(xfer_desc_t* xfer) +{ + xfer->buffer = NULL; + xfer->total_len = 0; + xfer->actual_len = 0; +} + uint16_t xfer_packet_len(xfer_desc_t* xfer) { // also cover zero-length packet @@ -258,10 +265,12 @@ bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t // OUT Data may already received and acked by hardware // Read it as 1st packet then continue with transfer if needed -// uint16_t const xact_len = (uint16_t) ((UDP->UDP_CSR[epnum] & UDP_CSR_RXBYTECNT_Msk) >> UDP_CSR_RXBYTECNT_Pos); -// -// if ( xact_len ) -// { + if ( UDP->UDP_CSR[epnum] & (UDP_CSR_RX_DATA_BK0_Msk | UDP_CSR_RX_DATA_BK1_Msk) ) + { + uint16_t const xact_len = (uint16_t) ((UDP->UDP_CSR[epnum] & UDP_CSR_RXBYTECNT_Msk) >> UDP_CSR_RXBYTECNT_Pos); + + TU_LOG2("xact_len = %d\r", xact_len); + // // Read from EP fifo // xact_ep_read(epnum, xfer->buffer, xact_len); // xfer_packet_done(xfer); @@ -277,10 +286,10 @@ bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t // dcd_event_xfer_complete(rhport, epnum, xact_len, XFER_RESULT_SUCCESS, false); // return true; // complete // } -// } + } // Enable interrupt when starting OUT transfer - UDP->UDP_IER |= (1 << epnum); + if (epnum != 0) UDP->UDP_IER |= (1 << epnum); } return true; @@ -397,10 +406,13 @@ void dcd_isr(uint8_t rhport) } // Endpoint OUT - if (UDP->UDP_CSR[epnum] & UDP_CSR_RX_DATA_BK0_Msk) + // When both Bank0 and Bank1 are both set, there is not way to know which one comes first + if (UDP->UDP_CSR[epnum] & (UDP_CSR_RX_DATA_BK0_Msk | UDP_CSR_RX_DATA_BK1_Msk)) { uint16_t const xact_len = (uint16_t) ((UDP->UDP_CSR[epnum] & UDP_CSR_RXBYTECNT_Msk) >> UDP_CSR_RXBYTECNT_Pos); + //if (epnum != 0) TU_LOG2("xact_len = %d\r", xact_len); + // Read from EP fifo xact_ep_read(epnum, xfer->buffer, xact_len); xfer_packet_done(xfer); @@ -408,13 +420,14 @@ void dcd_isr(uint8_t rhport) if ( 0 == xfer_packet_len(xfer) ) { // Disable OUT EP interrupt when transfer is complete - UDP->UDP_IER &= ~(1 << epnum); + if (epnum != 0) UDP->UDP_IDR |= (1 << epnum); dcd_event_xfer_complete(rhport, epnum, xact_len, XFER_RESULT_SUCCESS, true); +// xfer_end(xfer); } // Clear DATA Bank0 bit - UDP->UDP_CSR[epnum] &= ~UDP_CSR_RX_DATA_BK0_Msk; + UDP->UDP_CSR[epnum] &= ~(UDP_CSR_RX_DATA_BK0_Msk | UDP_CSR_RX_DATA_BK1_Msk); } // Stall sent to host From bbada1d3e6dba5b339c7cd4129e5df7b3203c11b Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 23 Dec 2019 18:54:06 +0700 Subject: [PATCH 135/267] adding lookup table for debugging add msc scsi command list --- src/class/msc/msc_device.c | 32 ++++++++++++++++++++++++-- src/common/tusb_common.h | 23 ++++++++++++++++++ src/device/usbd.c | 2 +- src/portable/microchip/samg/dcd_samg.c | 5 ++-- 4 files changed, 57 insertions(+), 5 deletions(-) diff --git a/src/class/msc/msc_device.c b/src/class/msc/msc_device.c index 84fe5a19..93167bc6 100644 --- a/src/class/msc/msc_device.c +++ b/src/class/msc/msc_device.c @@ -97,6 +97,34 @@ static inline uint16_t rdwr10_get_blockcount(uint8_t const command[]) return tu_ntohs(block_count); } +//--------------------------------------------------------------------+ +// Debug +//--------------------------------------------------------------------+ +#if CFG_TUSB_DEBUG >= 2 + +static lookup_entry_t const _msc_scsi_cmd_lookup[] = +{ + { .key = SCSI_CMD_TEST_UNIT_READY , .data = "Test Unit Ready" }, + { .key = SCSI_CMD_INQUIRY , .data = "Inquiry" }, + { .key = SCSI_CMD_MODE_SELECT_6 , .data = "Mode_Select 6" }, + { .key = SCSI_CMD_MODE_SENSE_6 , .data = "Mode_Sense 6" }, + { .key = SCSI_CMD_START_STOP_UNIT , .data = "Start Stop Unit" }, + { .key = SCSI_CMD_PREVENT_ALLOW_MEDIUM_REMOVAL , .data = "Prevent Allow Medium Removal" }, + { .key = SCSI_CMD_READ_CAPACITY_10 , .data = "Read Capacity10" }, + { .key = SCSI_CMD_REQUEST_SENSE , .data = "Request Sense" }, + { .key = SCSI_CMD_READ_FORMAT_CAPACITY , .data = "Read Format Capacity" }, + { .key = SCSI_CMD_READ_10 , .data = "Read10" }, + { .key = SCSI_CMD_WRITE_10 , .data = "Write10" } +}; + +static lookup_table_t const _msc_scsi_cmd_table = +{ + .count = TU_ARRAY_SIZE(_msc_scsi_cmd_lookup), + .items = _msc_scsi_cmd_lookup +}; + +#endif + //--------------------------------------------------------------------+ // APPLICATION API //--------------------------------------------------------------------+ @@ -378,7 +406,7 @@ bool mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t TU_ASSERT( event == XFER_RESULT_SUCCESS && xferred_bytes == sizeof(msc_cbw_t) && p_cbw->signature == MSC_CBW_SIGNATURE ); - TU_LOG2(" Command Block Wrapper\n"); + TU_LOG2(" SCSI Command: %s\n", lookup_find(&_msc_scsi_cmd_table, p_cbw->command[0])); // TU_LOG2_MEM(p_cbw, xferred_bytes, 2); p_csw->signature = MSC_CSW_SIGNATURE; @@ -544,7 +572,7 @@ bool mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t // Wait for the command status wrapper complete event if( (ep_addr == p_msc->ep_in) && (xferred_bytes == sizeof(msc_csw_t)) ) { - TU_LOG2(" Command Status Wrapper\n"); + TU_LOG2(" SCSI Status: %u\n", p_csw->status); // TU_LOG2_MEM(p_csw, xferred_bytes, 2); // Move to default CMD stage diff --git a/src/common/tusb_common.h b/src/common/tusb_common.h index f76abca8..5700c128 100644 --- a/src/common/tusb_common.h +++ b/src/common/tusb_common.h @@ -231,6 +231,29 @@ void tu_print_mem(void const *buf, uint16_t count, uint8_t indent); #define TU_LOG2_LOCATION() TU_LOG1_LOCATION() #endif + +typedef struct +{ + uint32_t key; + char const * data; +}lookup_entry_t; + +typedef struct +{ + uint16_t count; + lookup_entry_t const* items; +} lookup_table_t; + +static inline char const* lookup_find(lookup_table_t const* p_table, uint32_t key) +{ + for(uint16_t i=0; icount; i++) + { + if (p_table->items[i].key == key) return p_table->items[i].data; + } + + return NULL; +} + #endif // CFG_TUSB_DEBUG #ifndef TU_LOG1 diff --git a/src/device/usbd.c b/src/device/usbd.c index 5832f235..949e1409 100644 --- a/src/device/usbd.c +++ b/src/device/usbd.c @@ -211,7 +211,7 @@ bool usbd_control_xfer_cb (uint8_t rhport, uint8_t ep_addr, xfer_result_t event, //--------------------------------------------------------------------+ // Debugging //--------------------------------------------------------------------+ -#if CFG_TUSB_DEBUG > 1 +#if CFG_TUSB_DEBUG >= 2 static char const* const _usbd_event_str[DCD_EVENT_COUNT] = { "INVALID" , diff --git a/src/portable/microchip/samg/dcd_samg.c b/src/portable/microchip/samg/dcd_samg.c index fd50237d..a93b26ca 100644 --- a/src/portable/microchip/samg/dcd_samg.c +++ b/src/portable/microchip/samg/dcd_samg.c @@ -267,9 +267,9 @@ bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t // Read it as 1st packet then continue with transfer if needed if ( UDP->UDP_CSR[epnum] & (UDP_CSR_RX_DATA_BK0_Msk | UDP_CSR_RX_DATA_BK1_Msk) ) { - uint16_t const xact_len = (uint16_t) ((UDP->UDP_CSR[epnum] & UDP_CSR_RXBYTECNT_Msk) >> UDP_CSR_RXBYTECNT_Pos); +// uint16_t const xact_len = (uint16_t) ((UDP->UDP_CSR[epnum] & UDP_CSR_RXBYTECNT_Msk) >> UDP_CSR_RXBYTECNT_Pos); - TU_LOG2("xact_len = %d\r", xact_len); +// TU_LOG2("xact_len = %d\r", xact_len); // // Read from EP fifo // xact_ep_read(epnum, xfer->buffer, xact_len); @@ -406,6 +406,7 @@ void dcd_isr(uint8_t rhport) } // Endpoint OUT + // Ping-Pong is a must for Bulk/Iso // When both Bank0 and Bank1 are both set, there is not way to know which one comes first if (UDP->UDP_CSR[epnum] & (UDP_CSR_RX_DATA_BK0_Msk | UDP_CSR_RX_DATA_BK1_Msk)) { From a1c94067f778dc6f055c132ca18c870a107910be Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 23 Dec 2019 19:48:52 +0700 Subject: [PATCH 136/267] add driver 99-tinyusb.rules for ubuntu, rename window usbser inf --- tools/usb_drivers/99-tinyusb.rules | 18 ++++++++++++++++++ .../tinyusb_win_usbser.inf} | 0 2 files changed, 18 insertions(+) create mode 100644 tools/usb_drivers/99-tinyusb.rules rename tools/{windows_cdc_driver/tusb_usbser.inf => usb_drivers/tinyusb_win_usbser.inf} (100%) diff --git a/tools/usb_drivers/99-tinyusb.rules b/tools/usb_drivers/99-tinyusb.rules new file mode 100644 index 00000000..334159f9 --- /dev/null +++ b/tools/usb_drivers/99-tinyusb.rules @@ -0,0 +1,18 @@ +# Copy this file to the location of your distribution's udev rules, for example on Ubuntu: +# sudo cp 99-tinyusb.rules /etc/udev/rules.d/ +# Then reload udev configuration by executing: +# sudo udevadm control --reload-rules +# sudo udevadm trigger + +# Check SUBSYSTEM +SUBSYSTEMS=="hidraw", KERNEL=="hidraw*", MODE="0666", GROUP="dialout" + +# Rule applies to all TinyUSB example +ATTRS{idVendor}=="cafe", MODE="0666", GROUP="dialout" + +# Rule to blacklist TinyUSB example from being manipulated by ModemManager. +SUBSYSTEMS=="usb", ATTRS{idVendor}=="cafe", ENV{ID_MM_DEVICE_IGNORE}="1" + +# Xplained Pro SamG55 Device +SUBSYSTEMS=="usb", ATTRS{idVendor}=="03eb", ATTRS{idProduct}=="2111", MODE="0666", GROUP="users", ENV{ID_MM_DEVICE_IGNORE}="1" +SUBSYSTEMS=="tty", ATTRS{idVendor}=="03eb", ATTRS{idProduct}=="2111", MODE="0666", GROUP="users", ENV{ID_MM_DEVICE_IGNORE}="1" diff --git a/tools/windows_cdc_driver/tusb_usbser.inf b/tools/usb_drivers/tinyusb_win_usbser.inf similarity index 100% rename from tools/windows_cdc_driver/tusb_usbser.inf rename to tools/usb_drivers/tinyusb_win_usbser.inf From 605129eb6600ffb50ea2d239e0ad78a9636df8e1 Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 24 Dec 2019 21:24:43 +0700 Subject: [PATCH 137/267] invoke scsi complete callback before queue for csw status there is racing issue with samd + qspi flash testing with arduino otherwise. --- src/class/msc/msc_device.c | 18 +++++++++++++----- src/tusb_option.h | 2 +- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/src/class/msc/msc_device.c b/src/class/msc/msc_device.c index 93167bc6..bef5d599 100644 --- a/src/class/msc/msc_device.c +++ b/src/class/msc/msc_device.c @@ -39,7 +39,8 @@ enum { MSC_STAGE_CMD = 0, MSC_STAGE_DATA, - MSC_STAGE_STATUS + MSC_STAGE_STATUS, + MSC_STAGE_STATUS_SENT }; typedef struct @@ -569,7 +570,11 @@ bool mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t break; case MSC_STAGE_STATUS: - // Wait for the command status wrapper complete event + // processed immediately after this switch, supposedly to be empty + break; + + case MSC_STAGE_STATUS_SENT: + // Wait for the Status phase to complete if( (ep_addr == p_msc->ep_in) && (xferred_bytes == sizeof(msc_csw_t)) ) { TU_LOG2(" SCSI Status: %u\n", p_csw->status); @@ -598,9 +603,6 @@ bool mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t } else { - // Send SCSI Status - TU_ASSERT(usbd_edpt_xfer(rhport, p_msc->ep_in , (uint8_t*) &p_msc->csw, sizeof(msc_csw_t))); - // Invoke complete callback if defined switch(p_cbw->command[0]) { @@ -616,6 +618,12 @@ bool mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t if ( tud_msc_scsi_complete_cb ) tud_msc_scsi_complete_cb(p_cbw->lun, p_cbw->command); break; } + + // Move to Status Sent stage + p_msc->stage = MSC_STAGE_STATUS_SENT; + + // Send SCSI Status + TU_ASSERT(usbd_edpt_xfer(rhport, p_msc->ep_in , (uint8_t*) &p_msc->csw, sizeof(msc_csw_t))); } } diff --git a/src/tusb_option.h b/src/tusb_option.h index 6766da07..266687ff 100644 --- a/src/tusb_option.h +++ b/src/tusb_option.h @@ -36,7 +36,7 @@ * \ref CFG_TUSB_MCU must be defined to one of these * @{ */ -#define OPT_MCU_NONE 0 +#define OPT_MCU_NONE 0 // LPC #define OPT_MCU_LPC11UXX 1 ///< NXP LPC11Uxx From 5690e7b304d9179dd1b8e35b3f61e016b7822c31 Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 25 Dec 2019 23:47:47 +0700 Subject: [PATCH 138/267] fix samd51 setup packet handling issue occur due to race condition https://github.com/adafruit/Adafruit_TinyUSB_Arduino/issues/37 --- README.md | 2 +- src/portable/microchip/samd21/dcd_samd21.c | 2 +- src/portable/microchip/samd51/dcd_samd51.c | 13 +++++-------- 3 files changed, 7 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 3f7e7ecd..798c10a5 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ ![tinyUSB_240x100](https://user-images.githubusercontent.com/249515/62646655-f9393200-b978-11e9-9c53-484862f15503.png) -[![Build Status](https://travis-ci.org/hathach/tinyusb.svg?branch=master)](https://travis-ci.org/hathach/tinyusb) [![License](https://img.shields.io/badge/license-MIT-brightgreen.svg)](https://opensource.org/licenses/MIT)[![Coverity](https://img.shields.io/coverity/scan/458.svg)](https://scan.coverity.com/projects/tinyusb) +[![Build Status](https://travis-ci.org/hathach/tinyusb.svg?branch=master)](https://travis-ci.org/hathach/tinyusb) [![License](https://img.shields.io/badge/license-MIT-brightgreen.svg)](https://opensource.org/licenses/MIT) [![Coverity](https://img.shields.io/coverity/scan/458.svg)](https://scan.coverity.com/projects/tinyusb) TinyUSB is an open-source cross-platform USB Host/Device stack for embedded system, designed to be memory-safe with no dynamic allocation and thread-safe with all interrupt events are deferred then handled in the non-ISR task function. diff --git a/src/portable/microchip/samd21/dcd_samd21.c b/src/portable/microchip/samd21/dcd_samd21.c index 5e44dc38..c96c87f8 100644 --- a/src/portable/microchip/samd21/dcd_samd21.c +++ b/src/portable/microchip/samd21/dcd_samd21.c @@ -253,7 +253,7 @@ static bool maybe_handle_setup_packet(void) { USB->DEVICE.DeviceEndpoint[0].EPINTFLAG.reg = USB_DEVICE_EPINTFLAG_RXSTP; // This copies the data elsewhere so we can reuse the buffer. - dcd_event_setup_received(0, (uint8_t*) sram_registers[0][0].ADDR.reg, true); + dcd_event_setup_received(0, _setup_packet, true); return true; } return false; diff --git a/src/portable/microchip/samd51/dcd_samd51.c b/src/portable/microchip/samd51/dcd_samd51.c index c298acc5..598ab7bb 100644 --- a/src/portable/microchip/samd51/dcd_samd51.c +++ b/src/portable/microchip/samd51/dcd_samd51.c @@ -34,7 +34,7 @@ /*------------------------------------------------------------------*/ /* MACRO TYPEDEF CONSTANT ENUM *------------------------------------------------------------------*/ -static UsbDeviceDescBank sram_registers[8][2]; +static TU_ATTR_ALIGNED(4) UsbDeviceDescBank sram_registers[8][2]; static TU_ATTR_ALIGNED(4) uint8_t _setup_packet[8]; // Setup the control endpoint 0. @@ -69,7 +69,7 @@ void dcd_init (uint8_t rhport) USB->DEVICE.PADCAL.bit.TRANSP = (*((uint32_t*) USB_FUSES_TRANSP_ADDR) & USB_FUSES_TRANSP_Msk) >> USB_FUSES_TRANSP_Pos; USB->DEVICE.PADCAL.bit.TRANSN = (*((uint32_t*) USB_FUSES_TRANSN_ADDR) & USB_FUSES_TRANSN_Msk) >> USB_FUSES_TRANSN_Pos; - USB->DEVICE.PADCAL.bit.TRIM = (*((uint32_t*) USB_FUSES_TRIM_ADDR) & USB_FUSES_TRIM_Msk) >> USB_FUSES_TRIM_Pos; + USB->DEVICE.PADCAL.bit.TRIM = (*((uint32_t*) USB_FUSES_TRIM_ADDR) & USB_FUSES_TRIM_Msk) >> USB_FUSES_TRIM_Pos; USB->DEVICE.QOSCTRL.bit.CQOS = 3; USB->DEVICE.QOSCTRL.bit.DQOS = 3; @@ -81,7 +81,7 @@ void dcd_init (uint8_t rhport) while (USB->DEVICE.SYNCBUSY.bit.ENABLE == 1) {} USB->DEVICE.INTFLAG.reg |= USB->DEVICE.INTFLAG.reg; // clear pending - USB->DEVICE.INTENSET.reg = USB_DEVICE_INTENSET_SOF | USB_DEVICE_INTENSET_EORST; + USB->DEVICE.INTENSET.reg = /* USB_DEVICE_INTENSET_SOF | */ USB_DEVICE_INTENSET_EORST; } void dcd_int_enable(uint8_t rhport) @@ -257,7 +257,8 @@ static bool maybe_handle_setup_packet(void) { USB->DEVICE.DeviceEndpoint[0].EPINTFLAG.reg = USB_DEVICE_EPINTFLAG_RXSTP; // This copies the data elsewhere so we can reuse the buffer. - dcd_event_setup_received(0, (uint8_t*) sram_registers[0][0].ADDR.reg, true); + dcd_event_setup_received(0, _setup_packet, true); + return true; } return false; @@ -336,11 +337,7 @@ void transfer_complete(uint8_t direction) { continue; } - if (direction == TUSB_DIR_OUT && maybe_handle_setup_packet()) { - continue; - } UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum]; - UsbDeviceDescBank* bank = &sram_registers[epnum][direction]; uint16_t total_transfer_size = bank->PCKSIZE.bit.BYTE_COUNT; From 49b316143ad4e1bd6130b3032b8418be7e0bc2c3 Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 26 Dec 2019 17:11:24 +0700 Subject: [PATCH 139/267] improve samd, fix missing setup packet occasionally --- src/portable/microchip/samd51/dcd_samd51.c | 32 ++++++++++++++-------- 1 file changed, 21 insertions(+), 11 deletions(-) diff --git a/src/portable/microchip/samd51/dcd_samd51.c b/src/portable/microchip/samd51/dcd_samd51.c index 598ab7bb..4bb214cb 100644 --- a/src/portable/microchip/samd51/dcd_samd51.c +++ b/src/portable/microchip/samd51/dcd_samd51.c @@ -37,6 +37,15 @@ static TU_ATTR_ALIGNED(4) UsbDeviceDescBank sram_registers[8][2]; static TU_ATTR_ALIGNED(4) uint8_t _setup_packet[8]; + +// ready for receiving SETUP packet +static inline void prepare_setup(void) +{ + // Only make sure the EP0 OUT buffer is ready + // SETUP token doesn't check any other parameters + sram_registers[0][0].ADDR.reg = (uint32_t) _setup_packet; +} + // Setup the control endpoint 0. static void bus_reset(void) { @@ -51,10 +60,9 @@ static void bus_reset(void) ep->EPINTENSET.reg = USB_DEVICE_EPINTENSET_TRCPT0 | USB_DEVICE_EPINTENSET_TRCPT1 | USB_DEVICE_EPINTENSET_RXSTP; // Prepare for setup packet - dcd_edpt_xfer(0, 0, _setup_packet, sizeof(_setup_packet)); + prepare_setup(); } - /*------------------------------------------------------------------*/ /* Controller API *------------------------------------------------------------------*/ @@ -148,7 +156,9 @@ void dcd_edpt0_status_complete(uint8_t rhport, tusb_control_request_t const * re } // Just finished status stage, prepare for next setup packet - dcd_edpt_xfer(rhport, 0x00, _setup_packet, sizeof(_setup_packet)); + // Note: we may already prepare setup when the last EP0 OUT complete. + // but it has no harm to do it again here + prepare_setup(); } bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * desc_edpt) @@ -197,12 +207,6 @@ bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t UsbDeviceDescBank* bank = &sram_registers[epnum][dir]; UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum]; - // A setup token can occur immediately after an OUT STATUS packet so make sure we have a valid - // buffer for the control endpoint. - if (epnum == 0 && dir == 0 && buffer == NULL) { - buffer = _setup_packet; - } - bank->ADDR.reg = (uint32_t) buffer; if ( dir == TUSB_DIR_OUT ) { @@ -254,11 +258,11 @@ void dcd_edpt_clear_stall (uint8_t rhport, uint8_t ep_addr) static bool maybe_handle_setup_packet(void) { if (USB->DEVICE.DeviceEndpoint[0].EPINTFLAG.bit.RXSTP) { - USB->DEVICE.DeviceEndpoint[0].EPINTFLAG.reg = USB_DEVICE_EPINTFLAG_RXSTP; - // This copies the data elsewhere so we can reuse the buffer. dcd_event_setup_received(0, _setup_packet, true); + USB->DEVICE.DeviceEndpoint[0].EPINTFLAG.reg = USB_DEVICE_EPINTFLAG_RXSTP; + return true; } return false; @@ -337,6 +341,12 @@ void transfer_complete(uint8_t direction) { continue; } + // A SETUP token can occur immediately after an OUT packet + // so make sure we have a valid buffer for the control endpoint. + if (epnum == 0 && direction == TUSB_DIR_OUT ) { + prepare_setup(); + } + UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum]; UsbDeviceDescBank* bank = &sram_registers[epnum][direction]; uint16_t total_transfer_size = bank->PCKSIZE.bit.BYTE_COUNT; From b5684c5c102dbe54988357d1ea0fd457f6cbfc5c Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 26 Dec 2019 21:46:59 +0700 Subject: [PATCH 140/267] merge dcd_samd51 & dcd_samd21 into dcd_samd --- hw/bsp/circuitplayground_express/board.mk | 2 +- hw/bsp/feather_m0_express/board.mk | 2 +- hw/bsp/feather_m4_express/board.mk | 2 +- hw/bsp/metro_m0_express/board.mk | 2 +- hw/bsp/metro_m4_express/board.mk | 2 +- .../{samd51/dcd_samd51.c => samd/dcd_samd.c} | 177 +++++---- src/portable/microchip/samd21/dcd_samd21.c | 353 ------------------ 7 files changed, 116 insertions(+), 424 deletions(-) rename src/portable/microchip/{samd51/dcd_samd51.c => samd/dcd_samd.c} (84%) delete mode 100644 src/portable/microchip/samd21/dcd_samd21.c diff --git a/hw/bsp/circuitplayground_express/board.mk b/hw/bsp/circuitplayground_express/board.mk index 115a8118..7ea90e8e 100644 --- a/hw/bsp/circuitplayground_express/board.mk +++ b/hw/bsp/circuitplayground_express/board.mk @@ -31,7 +31,7 @@ INC += \ # For TinyUSB port source VENDOR = microchip -CHIP_FAMILY = samd21 +CHIP_FAMILY = samd # For freeRTOS port source FREERTOS_PORT = ARM_CM0 diff --git a/hw/bsp/feather_m0_express/board.mk b/hw/bsp/feather_m0_express/board.mk index fe191333..d4530a47 100644 --- a/hw/bsp/feather_m0_express/board.mk +++ b/hw/bsp/feather_m0_express/board.mk @@ -32,7 +32,7 @@ INC += \ # For TinyUSB port source VENDOR = microchip -CHIP_FAMILY = samd21 +CHIP_FAMILY = samd # For freeRTOS port source FREERTOS_PORT = ARM_CM0 diff --git a/hw/bsp/feather_m4_express/board.mk b/hw/bsp/feather_m4_express/board.mk index 010e4b86..f42aa770 100644 --- a/hw/bsp/feather_m4_express/board.mk +++ b/hw/bsp/feather_m4_express/board.mk @@ -35,7 +35,7 @@ INC += \ # For TinyUSB port source VENDOR = microchip -CHIP_FAMILY = samd51 +CHIP_FAMILY = samd # For freeRTOS port source FREERTOS_PORT = ARM_CM4F diff --git a/hw/bsp/metro_m0_express/board.mk b/hw/bsp/metro_m0_express/board.mk index 2039219a..668d9a5b 100644 --- a/hw/bsp/metro_m0_express/board.mk +++ b/hw/bsp/metro_m0_express/board.mk @@ -32,7 +32,7 @@ INC += \ # For TinyUSB port source VENDOR = microchip -CHIP_FAMILY = samd21 +CHIP_FAMILY = samd # For freeRTOS port source FREERTOS_PORT = ARM_CM0 diff --git a/hw/bsp/metro_m4_express/board.mk b/hw/bsp/metro_m4_express/board.mk index 010e4b86..f42aa770 100644 --- a/hw/bsp/metro_m4_express/board.mk +++ b/hw/bsp/metro_m4_express/board.mk @@ -35,7 +35,7 @@ INC += \ # For TinyUSB port source VENDOR = microchip -CHIP_FAMILY = samd51 +CHIP_FAMILY = samd # For freeRTOS port source FREERTOS_PORT = ARM_CM4F diff --git a/src/portable/microchip/samd51/dcd_samd51.c b/src/portable/microchip/samd/dcd_samd.c similarity index 84% rename from src/portable/microchip/samd51/dcd_samd51.c rename to src/portable/microchip/samd/dcd_samd.c index 4bb214cb..eccc9c09 100644 --- a/src/portable/microchip/samd51/dcd_samd51.c +++ b/src/portable/microchip/samd/dcd_samd.c @@ -26,7 +26,7 @@ #include "tusb_option.h" -#if TUSB_OPT_DEVICE_ENABLED && CFG_TUSB_MCU == OPT_MCU_SAMD51 +#if TUSB_OPT_DEVICE_ENABLED && (CFG_TUSB_MCU == OPT_MCU_SAMD51 || CFG_TUSB_MCU == OPT_MCU_SAMD21) #include "sam.h" #include "device/dcd.h" @@ -63,6 +63,7 @@ static void bus_reset(void) prepare_setup(); } + /*------------------------------------------------------------------*/ /* Controller API *------------------------------------------------------------------*/ @@ -79,8 +80,8 @@ void dcd_init (uint8_t rhport) USB->DEVICE.PADCAL.bit.TRANSN = (*((uint32_t*) USB_FUSES_TRANSN_ADDR) & USB_FUSES_TRANSN_Msk) >> USB_FUSES_TRANSN_Pos; USB->DEVICE.PADCAL.bit.TRIM = (*((uint32_t*) USB_FUSES_TRIM_ADDR) & USB_FUSES_TRIM_Msk) >> USB_FUSES_TRIM_Pos; - USB->DEVICE.QOSCTRL.bit.CQOS = 3; - USB->DEVICE.QOSCTRL.bit.DQOS = 3; + USB->DEVICE.QOSCTRL.bit.CQOS = 3; // High Quality + USB->DEVICE.QOSCTRL.bit.DQOS = 3; // High Quality // Configure registers USB->DEVICE.DESCADD.reg = (uint32_t) &sram_registers; @@ -95,19 +96,29 @@ void dcd_init (uint8_t rhport) void dcd_int_enable(uint8_t rhport) { (void) rhport; + +#if CFG_TUSB_MCU == OPT_MCU_SAMD51 NVIC_EnableIRQ(USB_0_IRQn); NVIC_EnableIRQ(USB_1_IRQn); NVIC_EnableIRQ(USB_2_IRQn); NVIC_EnableIRQ(USB_3_IRQn); +#elif CFG_TUSB_MCU == OPT_MCU_SAMD21 + NVIC_EnableIRQ(USB_IRQn); +#endif } void dcd_int_disable(uint8_t rhport) { (void) rhport; + +#if CFG_TUSB_MCU == OPT_MCU_SAMD51 NVIC_DisableIRQ(USB_3_IRQn); NVIC_DisableIRQ(USB_2_IRQn); NVIC_DisableIRQ(USB_1_IRQn); NVIC_DisableIRQ(USB_0_IRQn); +#elif CFG_TUSB_MCU == OPT_MCU_SAMD21 + NVIC_DisableIRQ(USB_IRQn); +#endif } void dcd_set_address (uint8_t rhport, uint8_t dev_addr) @@ -147,6 +158,8 @@ void dcd_remote_wakeup(uint8_t rhport) // May help DCD to prepare for next control transfer, this API is optional. void dcd_edpt0_status_complete(uint8_t rhport, tusb_control_request_t const * request) { + (void) rhport; + if (request->bmRequestType_bit.recipient == TUSB_REQ_RCPT_DEVICE && request->bmRequestType_bit.type == TUSB_REQ_TYPE_STANDARD && request->bRequest == TUSB_REQ_SET_ADDRESS ) @@ -253,40 +266,65 @@ void dcd_edpt_clear_stall (uint8_t rhport, uint8_t ep_addr) } } -/*------------------------------------------------------------------*/ +//--------------------------------------------------------------------+ +// Interrupt Handler +//--------------------------------------------------------------------+ +void maybe_transfer_complete(void) { + uint32_t epints = USB->DEVICE.EPINTSMRY.reg; -static bool maybe_handle_setup_packet(void) { - if (USB->DEVICE.DeviceEndpoint[0].EPINTFLAG.bit.RXSTP) - { - // This copies the data elsewhere so we can reuse the buffer. - dcd_event_setup_received(0, _setup_packet, true); + for (uint8_t epnum = 0; epnum < USB_EPT_NUM; epnum++) { + if ((epints & (1 << epnum)) == 0) { + continue; + } - USB->DEVICE.DeviceEndpoint[0].EPINTFLAG.reg = USB_DEVICE_EPINTFLAG_RXSTP; + UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum]; + uint32_t epintflag = ep->EPINTFLAG.reg; - return true; + // Handle IN completions + if ((epintflag & USB_DEVICE_EPINTFLAG_TRCPT1) != 0) { + UsbDeviceDescBank* bank = &sram_registers[epnum][TUSB_DIR_IN]; + uint16_t total_transfer_size = bank->PCKSIZE.bit.BYTE_COUNT; + + uint8_t ep_addr = epnum | TUSB_DIR_IN_MASK; + dcd_event_xfer_complete(0, ep_addr, total_transfer_size, XFER_RESULT_SUCCESS, true); + + ep->EPINTFLAG.reg = USB_DEVICE_EPINTFLAG_TRCPT1; + } + + // Handle OUT completions + if ((epintflag & USB_DEVICE_EPINTFLAG_TRCPT0) != 0) { + + // A SETUP token can occur immediately after an OUT packet + // so make sure we have a valid buffer for the control endpoint. + if (epnum == 0) { + prepare_setup(); + } + + UsbDeviceDescBank* bank = &sram_registers[epnum][TUSB_DIR_OUT]; + uint16_t total_transfer_size = bank->PCKSIZE.bit.BYTE_COUNT; + + uint8_t ep_addr = epnum; + dcd_event_xfer_complete(0, ep_addr, total_transfer_size, XFER_RESULT_SUCCESS, true); + + ep->EPINTFLAG.reg = USB_DEVICE_EPINTFLAG_TRCPT0; + } } - return false; } -/* - *------------------------------------------------------------------*/ -/* USB_EORSM_DNRSM, USB_EORST_RST, USB_LPMSUSP_DDISC, USB_LPM_DCONN, -USB_MSOF, USB_RAMACER, USB_RXSTP_TXSTP_0, USB_RXSTP_TXSTP_1, -USB_RXSTP_TXSTP_2, USB_RXSTP_TXSTP_3, USB_RXSTP_TXSTP_4, -USB_RXSTP_TXSTP_5, USB_RXSTP_TXSTP_6, USB_RXSTP_TXSTP_7, -USB_STALL0_STALL_0, USB_STALL0_STALL_1, USB_STALL0_STALL_2, -USB_STALL0_STALL_3, USB_STALL0_STALL_4, USB_STALL0_STALL_5, -USB_STALL0_STALL_6, USB_STALL0_STALL_7, USB_STALL1_0, USB_STALL1_1, -USB_STALL1_2, USB_STALL1_3, USB_STALL1_4, USB_STALL1_5, USB_STALL1_6, -USB_STALL1_7, USB_SUSPEND, USB_TRFAIL0_TRFAIL_0, USB_TRFAIL0_TRFAIL_1, -USB_TRFAIL0_TRFAIL_2, USB_TRFAIL0_TRFAIL_3, USB_TRFAIL0_TRFAIL_4, -USB_TRFAIL0_TRFAIL_5, USB_TRFAIL0_TRFAIL_6, USB_TRFAIL0_TRFAIL_7, -USB_TRFAIL1_PERR_0, USB_TRFAIL1_PERR_1, USB_TRFAIL1_PERR_2, -USB_TRFAIL1_PERR_3, USB_TRFAIL1_PERR_4, USB_TRFAIL1_PERR_5, -USB_TRFAIL1_PERR_6, USB_TRFAIL1_PERR_7, USB_UPRSM, USB_WAKEUP */ -void USB_0_Handler(void) { + + +void dcd_isr (uint8_t rhport) +{ + (void) rhport; + uint32_t int_status = USB->DEVICE.INTFLAG.reg & USB->DEVICE.INTENSET.reg; /*------------- Interrupt Processing -------------*/ + if ( int_status & USB_DEVICE_INTFLAG_SOF ) + { + USB->DEVICE.INTFLAG.reg = USB_DEVICE_INTFLAG_SOF; + dcd_event_bus_signal(0, DCD_EVENT_SOF, true); + } + // SAMD doesn't distinguish between Suspend and Disconnect state. // Both condition will cause SUSPEND interrupt triggered. // To prevent being triggered when D+/D- are not stable, SUSPEND interrupt is only @@ -324,45 +362,44 @@ void USB_0_Handler(void) { dcd_event_bus_signal(0, DCD_EVENT_BUS_RESET, true); } - // Setup packet received. - maybe_handle_setup_packet(); + // Handle SETUP packet + if (USB->DEVICE.DeviceEndpoint[0].EPINTFLAG.bit.RXSTP) + { + // This copies the data elsewhere so we can reuse the buffer. + dcd_event_setup_received(0, _setup_packet, true); + + USB->DEVICE.DeviceEndpoint[0].EPINTFLAG.reg = USB_DEVICE_EPINTFLAG_RXSTP; + } + + // Handle complete transfer + maybe_transfer_complete(); +} + +#if CFG_TUSB_MCU == OPT_MCU_SAMD51 + +/* + *------------------------------------------------------------------*/ +/* USB_EORSM_DNRSM, USB_EORST_RST, USB_LPMSUSP_DDISC, USB_LPM_DCONN, +USB_MSOF, USB_RAMACER, USB_RXSTP_TXSTP_0, USB_RXSTP_TXSTP_1, +USB_RXSTP_TXSTP_2, USB_RXSTP_TXSTP_3, USB_RXSTP_TXSTP_4, +USB_RXSTP_TXSTP_5, USB_RXSTP_TXSTP_6, USB_RXSTP_TXSTP_7, +USB_STALL0_STALL_0, USB_STALL0_STALL_1, USB_STALL0_STALL_2, +USB_STALL0_STALL_3, USB_STALL0_STALL_4, USB_STALL0_STALL_5, +USB_STALL0_STALL_6, USB_STALL0_STALL_7, USB_STALL1_0, USB_STALL1_1, +USB_STALL1_2, USB_STALL1_3, USB_STALL1_4, USB_STALL1_5, USB_STALL1_6, +USB_STALL1_7, USB_SUSPEND, USB_TRFAIL0_TRFAIL_0, USB_TRFAIL0_TRFAIL_1, +USB_TRFAIL0_TRFAIL_2, USB_TRFAIL0_TRFAIL_3, USB_TRFAIL0_TRFAIL_4, +USB_TRFAIL0_TRFAIL_5, USB_TRFAIL0_TRFAIL_6, USB_TRFAIL0_TRFAIL_7, +USB_TRFAIL1_PERR_0, USB_TRFAIL1_PERR_1, USB_TRFAIL1_PERR_2, +USB_TRFAIL1_PERR_3, USB_TRFAIL1_PERR_4, USB_TRFAIL1_PERR_5, +USB_TRFAIL1_PERR_6, USB_TRFAIL1_PERR_7, USB_UPRSM, USB_WAKEUP */ +void USB_0_Handler(void) { + dcd_isr(0); } /* USB_SOF_HSOF */ void USB_1_Handler(void) { - USB->DEVICE.INTFLAG.reg = USB_DEVICE_INTFLAG_SOF; - dcd_event_bus_signal(0, DCD_EVENT_SOF, true); -} - -void transfer_complete(uint8_t direction) { - uint32_t epints = USB->DEVICE.EPINTSMRY.reg; - for (uint8_t epnum = 0; epnum < USB_EPT_NUM; epnum++) { - if ((epints & (1 << epnum)) == 0) { - continue; - } - - // A SETUP token can occur immediately after an OUT packet - // so make sure we have a valid buffer for the control endpoint. - if (epnum == 0 && direction == TUSB_DIR_OUT ) { - prepare_setup(); - } - - UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum]; - UsbDeviceDescBank* bank = &sram_registers[epnum][direction]; - uint16_t total_transfer_size = bank->PCKSIZE.bit.BYTE_COUNT; - - uint8_t ep_addr = epnum; - if (direction == TUSB_DIR_IN) { - ep_addr |= TUSB_DIR_IN_MASK; - } - dcd_event_xfer_complete(0, ep_addr, total_transfer_size, XFER_RESULT_SUCCESS, true); - - if (direction == TUSB_DIR_IN) { - ep->EPINTFLAG.reg = USB_DEVICE_EPINTFLAG_TRCPT1; - } else { - ep->EPINTFLAG.reg = USB_DEVICE_EPINTFLAG_TRCPT0; - } - } + dcd_isr(0); } // Bank zero is for OUT and SETUP transactions. @@ -370,7 +407,7 @@ void transfer_complete(uint8_t direction) { USB_TRCPT0_3, USB_TRCPT0_4, USB_TRCPT0_5, USB_TRCPT0_6, USB_TRCPT0_7 */ void USB_2_Handler(void) { - transfer_complete(TUSB_DIR_OUT); + dcd_isr(0); } // Bank one is used for IN transactions. @@ -378,7 +415,15 @@ void USB_2_Handler(void) { USB_TRCPT1_3, USB_TRCPT1_4, USB_TRCPT1_5, USB_TRCPT1_6, USB_TRCPT1_7 */ void USB_3_Handler(void) { - transfer_complete(TUSB_DIR_IN); + dcd_isr(0); +} + +#elif CFG_TUSB_MCU == OPT_MCU_SAMD21 + +void USB_Handler(void) { + dcd_isr(0); } #endif + +#endif diff --git a/src/portable/microchip/samd21/dcd_samd21.c b/src/portable/microchip/samd21/dcd_samd21.c deleted file mode 100644 index c96c87f8..00000000 --- a/src/portable/microchip/samd21/dcd_samd21.c +++ /dev/null @@ -1,353 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2018 Scott Shawcroft for Adafruit Industries - * - * 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. - * - * This file is part of the TinyUSB stack. - */ - -#include "tusb_option.h" - -#if TUSB_OPT_DEVICE_ENABLED && CFG_TUSB_MCU == OPT_MCU_SAMD21 - -#include "sam.h" -#include "device/dcd.h" - -/*------------------------------------------------------------------*/ -/* MACRO TYPEDEF CONSTANT ENUM - *------------------------------------------------------------------*/ -static TU_ATTR_ALIGNED(4) UsbDeviceDescBank sram_registers[8][2]; -static TU_ATTR_ALIGNED(4) uint8_t _setup_packet[8]; - -// Setup the control endpoint 0. -static void bus_reset(void) -{ - // Max size of packets is 64 bytes. - UsbDeviceDescBank* bank_out = &sram_registers[0][TUSB_DIR_OUT]; - bank_out->PCKSIZE.bit.SIZE = 0x3; - UsbDeviceDescBank* bank_in = &sram_registers[0][TUSB_DIR_IN]; - bank_in->PCKSIZE.bit.SIZE = 0x3; - - UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[0]; - ep->EPCFG.reg = USB_DEVICE_EPCFG_EPTYPE0(0x1) | USB_DEVICE_EPCFG_EPTYPE1(0x1); - ep->EPINTENSET.reg = USB_DEVICE_EPINTENSET_TRCPT0 | USB_DEVICE_EPINTENSET_TRCPT1 | USB_DEVICE_EPINTENSET_RXSTP; - - // Prepare for setup packet - dcd_edpt_xfer(0, 0, _setup_packet, sizeof(_setup_packet)); -} - - -/*------------------------------------------------------------------*/ -/* Controller API - *------------------------------------------------------------------*/ -void dcd_init (uint8_t rhport) -{ - (void) rhport; - - // Reset to get in a clean state. - USB->DEVICE.CTRLA.bit.SWRST = true; - while (USB->DEVICE.SYNCBUSY.bit.SWRST == 0) {} - while (USB->DEVICE.SYNCBUSY.bit.SWRST == 1) {} - - USB->DEVICE.PADCAL.bit.TRANSP = (*((uint32_t*) USB_FUSES_TRANSP_ADDR) & USB_FUSES_TRANSP_Msk) >> USB_FUSES_TRANSP_Pos; - USB->DEVICE.PADCAL.bit.TRANSN = (*((uint32_t*) USB_FUSES_TRANSN_ADDR) & USB_FUSES_TRANSN_Msk) >> USB_FUSES_TRANSN_Pos; - USB->DEVICE.PADCAL.bit.TRIM = (*((uint32_t*) USB_FUSES_TRIM_ADDR) & USB_FUSES_TRIM_Msk) >> USB_FUSES_TRIM_Pos; - - USB->DEVICE.QOSCTRL.bit.CQOS = USB_QOSCTRL_CQOS_HIGH_Val; - USB->DEVICE.QOSCTRL.bit.DQOS = USB_QOSCTRL_DQOS_HIGH_Val; - - // Configure registers - USB->DEVICE.DESCADD.reg = (uint32_t) &sram_registers; - USB->DEVICE.CTRLB.reg = USB_DEVICE_CTRLB_SPDCONF_FS; - USB->DEVICE.CTRLA.reg = USB_CTRLA_MODE_DEVICE | USB_CTRLA_ENABLE | USB_CTRLA_RUNSTDBY; - while (USB->DEVICE.SYNCBUSY.bit.ENABLE == 1) {} - - USB->DEVICE.INTFLAG.reg |= USB->DEVICE.INTFLAG.reg; // clear pending - USB->DEVICE.INTENSET.reg = USB_DEVICE_INTENSET_SOF | USB_DEVICE_INTENSET_EORST; -} - -void dcd_int_enable(uint8_t rhport) -{ - (void) rhport; - NVIC_EnableIRQ(USB_IRQn); -} - -void dcd_int_disable(uint8_t rhport) -{ - (void) rhport; - NVIC_DisableIRQ(USB_IRQn); -} - -void dcd_set_address (uint8_t rhport, uint8_t dev_addr) -{ - (void) dev_addr; - - // Response with zlp status - dcd_edpt_xfer(rhport, 0x80, NULL, 0); - - // DCD can only set address after status for this request is complete - // do it at dcd_edpt0_status_complete() - - // Enable SUSPEND interrupt since the bus signal D+/D- are stable now. - USB->DEVICE.INTFLAG.reg = USB_DEVICE_INTENCLR_SUSPEND; // clear pending - USB->DEVICE.INTENSET.reg = USB_DEVICE_INTENSET_SUSPEND; -} - -void dcd_set_config (uint8_t rhport, uint8_t config_num) -{ - (void) rhport; - (void) config_num; - // Nothing to do -} - -void dcd_remote_wakeup(uint8_t rhport) -{ - (void) rhport; - - USB->DEVICE.CTRLB.bit.UPRSM = 1; -} - -/*------------------------------------------------------------------*/ -/* DCD Endpoint port - *------------------------------------------------------------------*/ - -// Invoked when a control transfer's status stage is complete. -// May help DCD to prepare for next control transfer, this API is optional. -void dcd_edpt0_status_complete(uint8_t rhport, tusb_control_request_t const * request) -{ - if (request->bmRequestType_bit.recipient == TUSB_REQ_RCPT_DEVICE && - request->bmRequestType_bit.type == TUSB_REQ_TYPE_STANDARD && - request->bRequest == TUSB_REQ_SET_ADDRESS ) - { - uint8_t const dev_addr = (uint8_t) request->wValue; - USB->DEVICE.DADD.reg = USB_DEVICE_DADD_DADD(dev_addr) | USB_DEVICE_DADD_ADDEN; - } - - // Just finished status stage, prepare for next setup packet - dcd_edpt_xfer(rhport, 0x00, _setup_packet, sizeof(_setup_packet)); -} - - -bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * desc_edpt) -{ - (void) rhport; - - uint8_t const epnum = tu_edpt_number(desc_edpt->bEndpointAddress); - uint8_t const dir = tu_edpt_dir(desc_edpt->bEndpointAddress); - - UsbDeviceDescBank* bank = &sram_registers[epnum][dir]; - uint32_t size_value = 0; - while (size_value < 7) { - if (1 << (size_value + 3) == desc_edpt->wMaxPacketSize.size) { - break; - } - size_value++; - } - - // unsupported endpoint size - if ( size_value == 7 && desc_edpt->wMaxPacketSize.size != 1023 ) return false; - - bank->PCKSIZE.bit.SIZE = size_value; - - UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum]; - - if ( dir == TUSB_DIR_OUT ) - { - ep->EPCFG.bit.EPTYPE0 = desc_edpt->bmAttributes.xfer + 1; - ep->EPINTENSET.bit.TRCPT0 = true; - }else - { - ep->EPCFG.bit.EPTYPE1 = desc_edpt->bmAttributes.xfer + 1; - ep->EPINTENSET.bit.TRCPT1 = true; - } - - return true; -} - -bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t total_bytes) -{ - (void) rhport; - - uint8_t const epnum = tu_edpt_number(ep_addr); - uint8_t const dir = tu_edpt_dir(ep_addr); - - UsbDeviceDescBank* bank = &sram_registers[epnum][dir]; - UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum]; - - // A setup token can occur immediately after an OUT STATUS packet so make sure we have a valid - // buffer for the control endpoint. - if (epnum == 0 && dir == 0 && buffer == NULL) { - buffer = _setup_packet; - } - - bank->ADDR.reg = (uint32_t) buffer; - if ( dir == TUSB_DIR_OUT ) - { - bank->PCKSIZE.bit.MULTI_PACKET_SIZE = total_bytes; - bank->PCKSIZE.bit.BYTE_COUNT = 0; - ep->EPSTATUSCLR.reg |= USB_DEVICE_EPSTATUSCLR_BK0RDY; - ep->EPINTFLAG.reg |= USB_DEVICE_EPINTFLAG_TRFAIL0; - } else - { - bank->PCKSIZE.bit.MULTI_PACKET_SIZE = 0; - bank->PCKSIZE.bit.BYTE_COUNT = total_bytes; - // bank->PCKSIZE.bit.AUTO_ZLP = 1; - ep->EPSTATUSSET.reg |= USB_DEVICE_EPSTATUSSET_BK1RDY; - ep->EPINTFLAG.reg |= USB_DEVICE_EPINTFLAG_TRFAIL1; - } - - return true; -} - -void dcd_edpt_stall (uint8_t rhport, uint8_t ep_addr) -{ - (void) rhport; - - uint8_t const epnum = tu_edpt_number(ep_addr); - UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum]; - - if (tu_edpt_dir(ep_addr) == TUSB_DIR_IN) { - ep->EPSTATUSSET.reg = USB_DEVICE_EPSTATUSSET_STALLRQ1; - } else { - ep->EPSTATUSSET.reg = USB_DEVICE_EPSTATUSSET_STALLRQ0; - } -} - -void dcd_edpt_clear_stall (uint8_t rhport, uint8_t ep_addr) -{ - (void) rhport; - - uint8_t const epnum = tu_edpt_number(ep_addr); - UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum]; - - if (tu_edpt_dir(ep_addr) == TUSB_DIR_IN) { - ep->EPSTATUSCLR.reg = USB_DEVICE_EPSTATUSCLR_STALLRQ1 | USB_DEVICE_EPSTATUSCLR_DTGLIN; - } else { - ep->EPSTATUSCLR.reg = USB_DEVICE_EPSTATUSCLR_STALLRQ0 | USB_DEVICE_EPSTATUSCLR_DTGLOUT; - } -} - -/*------------------------------------------------------------------*/ - -static bool maybe_handle_setup_packet(void) { - if (USB->DEVICE.DeviceEndpoint[0].EPINTFLAG.bit.RXSTP) - { - USB->DEVICE.DeviceEndpoint[0].EPINTFLAG.reg = USB_DEVICE_EPINTFLAG_RXSTP; - - // This copies the data elsewhere so we can reuse the buffer. - dcd_event_setup_received(0, _setup_packet, true); - return true; - } - return false; -} - -void maybe_transfer_complete(void) { - uint32_t epints = USB->DEVICE.EPINTSMRY.reg; - - for (uint8_t epnum = 0; epnum < USB_EPT_NUM; epnum++) { - if ((epints & (1 << epnum)) == 0) { - continue; - } - - if (maybe_handle_setup_packet()) { - continue; - } - - UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum]; - - uint32_t epintflag = ep->EPINTFLAG.reg; - - uint16_t total_transfer_size = 0; - - // Handle IN completions - if ((epintflag & USB_DEVICE_EPINTFLAG_TRCPT1) != 0) { - ep->EPINTFLAG.reg = USB_DEVICE_EPINTFLAG_TRCPT1; - - UsbDeviceDescBank* bank = &sram_registers[epnum][TUSB_DIR_IN]; - total_transfer_size = bank->PCKSIZE.bit.BYTE_COUNT; - - uint8_t ep_addr = epnum | TUSB_DIR_IN_MASK; - dcd_event_xfer_complete(0, ep_addr, total_transfer_size, XFER_RESULT_SUCCESS, true); - } - - // Handle OUT completions - if ((epintflag & USB_DEVICE_EPINTFLAG_TRCPT0) != 0) { - ep->EPINTFLAG.reg = USB_DEVICE_EPINTFLAG_TRCPT0; - - UsbDeviceDescBank* bank = &sram_registers[epnum][TUSB_DIR_OUT]; - total_transfer_size = bank->PCKSIZE.bit.BYTE_COUNT; - - uint8_t ep_addr = epnum; - dcd_event_xfer_complete(0, ep_addr, total_transfer_size, XFER_RESULT_SUCCESS, true); - } - } -} - -void USB_Handler(void) -{ - uint32_t int_status = USB->DEVICE.INTFLAG.reg & USB->DEVICE.INTENSET.reg; - USB->DEVICE.INTFLAG.reg = int_status; // clear interrupt - - /*------------- Interrupt Processing -------------*/ - if ( int_status & USB_DEVICE_INTFLAG_SOF ) - { - dcd_event_bus_signal(0, DCD_EVENT_SOF, true); - } - - // SAMD doesn't distinguish between Suspend and Disconnect state. - // Both condition will cause SUSPEND interrupt triggered. - // To prevent being triggered when D+/D- are not stable, SUSPEND interrupt is only - // enabled when we received SET_ADDRESS request and cleared on Bus Reset - if ( int_status & USB_DEVICE_INTFLAG_SUSPEND ) - { - // Enable wakeup interrupt - USB->DEVICE.INTFLAG.reg = USB_DEVICE_INTFLAG_WAKEUP; // clear pending - USB->DEVICE.INTENSET.reg = USB_DEVICE_INTFLAG_WAKEUP; - - dcd_event_bus_signal(0, DCD_EVENT_SUSPEND, true); - } - - // Wakeup interrupt is only enabled when we got suspended. - // Wakeup interrupt will disable itself - if ( int_status & USB_DEVICE_INTFLAG_WAKEUP ) - { - // disable wakeup interrupt itself - USB->DEVICE.INTENCLR.reg = USB_DEVICE_INTFLAG_WAKEUP; - dcd_event_bus_signal(0, DCD_EVENT_RESUME, true); - } - - if ( int_status & USB_DEVICE_INTFLAG_EORST ) - { - // Disable both suspend and wakeup interrupt - USB->DEVICE.INTENCLR.reg = USB_DEVICE_INTFLAG_WAKEUP | USB_DEVICE_INTFLAG_SUSPEND; - - bus_reset(); - dcd_event_bus_signal(0, DCD_EVENT_BUS_RESET, true); - } - - // Setup packet received. - maybe_handle_setup_packet(); - - // Handle complete transfer - maybe_transfer_complete(); -} - -#endif From 0da45c2e78598dc311bfe08fa845e8276e299418 Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 26 Dec 2019 22:31:29 +0700 Subject: [PATCH 141/267] clean up --- src/portable/microchip/samd/dcd_samd.c | 27 ++++++++++++++++---------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/src/portable/microchip/samd/dcd_samd.c b/src/portable/microchip/samd/dcd_samd.c index eccc9c09..5f904b31 100644 --- a/src/portable/microchip/samd/dcd_samd.c +++ b/src/portable/microchip/samd/dcd_samd.c @@ -93,34 +93,41 @@ void dcd_init (uint8_t rhport) USB->DEVICE.INTENSET.reg = /* USB_DEVICE_INTENSET_SOF | */ USB_DEVICE_INTENSET_EORST; } +#if CFG_TUSB_MCU == OPT_MCU_SAMD51 + void dcd_int_enable(uint8_t rhport) { (void) rhport; - -#if CFG_TUSB_MCU == OPT_MCU_SAMD51 NVIC_EnableIRQ(USB_0_IRQn); NVIC_EnableIRQ(USB_1_IRQn); NVIC_EnableIRQ(USB_2_IRQn); NVIC_EnableIRQ(USB_3_IRQn); -#elif CFG_TUSB_MCU == OPT_MCU_SAMD21 - NVIC_EnableIRQ(USB_IRQn); -#endif } void dcd_int_disable(uint8_t rhport) { (void) rhport; - -#if CFG_TUSB_MCU == OPT_MCU_SAMD51 NVIC_DisableIRQ(USB_3_IRQn); NVIC_DisableIRQ(USB_2_IRQn); NVIC_DisableIRQ(USB_1_IRQn); NVIC_DisableIRQ(USB_0_IRQn); -#elif CFG_TUSB_MCU == OPT_MCU_SAMD21 - NVIC_DisableIRQ(USB_IRQn); -#endif } +#elif CFG_TUSB_MCU == OPT_MCU_SAMD21 + +void dcd_int_enable(uint8_t rhport) +{ + (void) rhport; + NVIC_EnableIRQ(USB_IRQn); +} + +void dcd_int_disable(uint8_t rhport) +{ + (void) rhport; + NVIC_DisableIRQ(USB_IRQn); +} +#endif + void dcd_set_address (uint8_t rhport, uint8_t dev_addr) { (void) dev_addr; From 89f3ad59da093823cd48e6ca1ae2e09bb3e9309a Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 27 Dec 2019 09:42:57 +0700 Subject: [PATCH 142/267] fix #247 --- src/portable/microchip/samd/dcd_samd.c | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/src/portable/microchip/samd/dcd_samd.c b/src/portable/microchip/samd/dcd_samd.c index 5f904b31..14899552 100644 --- a/src/portable/microchip/samd/dcd_samd.c +++ b/src/portable/microchip/samd/dcd_samd.c @@ -42,8 +42,9 @@ static TU_ATTR_ALIGNED(4) uint8_t _setup_packet[8]; static inline void prepare_setup(void) { // Only make sure the EP0 OUT buffer is ready - // SETUP token doesn't check any other parameters sram_registers[0][0].ADDR.reg = (uint32_t) _setup_packet; + sram_registers[0][0].PCKSIZE.bit.MULTI_PACKET_SIZE = sizeof(_setup_packet); + sram_registers[0][0].PCKSIZE.bit.BYTE_COUNT = 0; } // Setup the control endpoint 0. @@ -292,8 +293,7 @@ void maybe_transfer_complete(void) { UsbDeviceDescBank* bank = &sram_registers[epnum][TUSB_DIR_IN]; uint16_t total_transfer_size = bank->PCKSIZE.bit.BYTE_COUNT; - uint8_t ep_addr = epnum | TUSB_DIR_IN_MASK; - dcd_event_xfer_complete(0, ep_addr, total_transfer_size, XFER_RESULT_SUCCESS, true); + dcd_event_xfer_complete(0, epnum | TUSB_DIR_IN_MASK, total_transfer_size, XFER_RESULT_SUCCESS, true); ep->EPINTFLAG.reg = USB_DEVICE_EPINTFLAG_TRCPT1; } @@ -301,17 +301,16 @@ void maybe_transfer_complete(void) { // Handle OUT completions if ((epintflag & USB_DEVICE_EPINTFLAG_TRCPT0) != 0) { + UsbDeviceDescBank* bank = &sram_registers[epnum][TUSB_DIR_OUT]; + uint16_t total_transfer_size = bank->PCKSIZE.bit.BYTE_COUNT; + // A SETUP token can occur immediately after an OUT packet // so make sure we have a valid buffer for the control endpoint. if (epnum == 0) { prepare_setup(); } - UsbDeviceDescBank* bank = &sram_registers[epnum][TUSB_DIR_OUT]; - uint16_t total_transfer_size = bank->PCKSIZE.bit.BYTE_COUNT; - - uint8_t ep_addr = epnum; - dcd_event_xfer_complete(0, ep_addr, total_transfer_size, XFER_RESULT_SUCCESS, true); + dcd_event_xfer_complete(0, epnum, total_transfer_size, XFER_RESULT_SUCCESS, true); ep->EPINTFLAG.reg = USB_DEVICE_EPINTFLAG_TRCPT0; } From 9ed7ca39ea1620fe772bc07208a792649083e82a Mon Sep 17 00:00:00 2001 From: Ha Thach Date: Fri, 27 Dec 2019 16:34:25 +0700 Subject: [PATCH 143/267] try action --- .github/workflows/build.yml | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 .github/workflows/build.yml diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 00000000..2a643a87 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,12 @@ +name: TinyUSB CI + +on: [pull_request, push] + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v2 + with: + submodules: true From ae6e7fa9284519c9ee3d0b52faab5be532ea1709 Mon Sep 17 00:00:00 2001 From: Ha Thach Date: Fri, 27 Dec 2019 16:39:23 +0700 Subject: [PATCH 144/267] Update build.yml --- .github/workflows/build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 2a643a87..912a13ae 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -7,6 +7,6 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v1 with: submodules: true From 8e2cc9731923e55793715bb9eb3dd2ea2db72fbf Mon Sep 17 00:00:00 2001 From: Ha Thach Date: Fri, 27 Dec 2019 16:55:13 +0700 Subject: [PATCH 145/267] Update build.yml --- .github/workflows/build.yml | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 912a13ae..debba866 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -7,6 +7,25 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v1 + - name: Python + uses: actions/setup-python@v1 + with: + python-version: 3.5 + - name: Toolchains + run: | + sudo apt-get install -y gettext + pip install requests sh click setuptools awscli + wget https://adafruit-circuit-python.s3.amazonaws.com/gcc-arm-none-eabi-9-2019-q4-major-x86_64-linux.tar.bz2 + sudo tar -C /usr --strip-components=1 -xaf gcc-arm-none-eabi-9-2019-q4-major-x86_64-linux.tar.bz2 + wget -O /tmp/riscv-toolchain.tgz https://github.com/xpack-dev-tools/riscv-none-embed-gcc-xpack/releases/download/v8.3.0-1.1/xpack-riscv-none-embed-gcc-8.3.0-1.1-linux-x64.tgz + tar -xzf /tmp/riscv-toolchain.tgz + export PATH=$PWD/xPacks/riscv-none-embed-gcc/8.3.0-1.1/bin:$PATH + - name: Versions + run: | + arm-none-eabi-gcc --version + riscv-none-embed-gcc --version + - name: Git clone + uses: actions/checkout@v1 with: submodules: true + - name: From 73906cb4958ad2f2dcb291636f05d39ed6d090d5 Mon Sep 17 00:00:00 2001 From: Ha Thach Date: Fri, 27 Dec 2019 16:56:46 +0700 Subject: [PATCH 146/267] Update build.yml --- .github/workflows/build.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index debba866..2676415c 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -28,4 +28,3 @@ jobs: uses: actions/checkout@v1 with: submodules: true - - name: From e5a5d146e1707bf00cadabd86bc0c9a832ee3b6b Mon Sep 17 00:00:00 2001 From: Ha Thach Date: Fri, 27 Dec 2019 17:05:57 +0700 Subject: [PATCH 147/267] Update build.yml --- .github/workflows/build.yml | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 2676415c..1c053482 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -11,15 +11,17 @@ jobs: uses: actions/setup-python@v1 with: python-version: 3.5 + - name: Node.js + uses: actions/setup-node@v1.1.0 - name: Toolchains run: | + # Install XPM + npm install --global xpm + xpm install --global @xpack-dev-tools/riscv-none-embed-gcc@latest sudo apt-get install -y gettext pip install requests sh click setuptools awscli wget https://adafruit-circuit-python.s3.amazonaws.com/gcc-arm-none-eabi-9-2019-q4-major-x86_64-linux.tar.bz2 sudo tar -C /usr --strip-components=1 -xaf gcc-arm-none-eabi-9-2019-q4-major-x86_64-linux.tar.bz2 - wget -O /tmp/riscv-toolchain.tgz https://github.com/xpack-dev-tools/riscv-none-embed-gcc-xpack/releases/download/v8.3.0-1.1/xpack-riscv-none-embed-gcc-8.3.0-1.1-linux-x64.tgz - tar -xzf /tmp/riscv-toolchain.tgz - export PATH=$PWD/xPacks/riscv-none-embed-gcc/8.3.0-1.1/bin:$PATH - name: Versions run: | arm-none-eabi-gcc --version From a005a74e3dbb6aa99ef06b1baac800eb76ebb49a Mon Sep 17 00:00:00 2001 From: Ha Thach Date: Fri, 27 Dec 2019 17:24:37 +0700 Subject: [PATCH 148/267] Update build.yml --- .github/workflows/build.yml | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 1c053482..7a34228d 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -18,13 +18,14 @@ jobs: # Install XPM npm install --global xpm xpm install --global @xpack-dev-tools/riscv-none-embed-gcc@latest - sudo apt-get install -y gettext - pip install requests sh click setuptools awscli - wget https://adafruit-circuit-python.s3.amazonaws.com/gcc-arm-none-eabi-9-2019-q4-major-x86_64-linux.tar.bz2 - sudo tar -C /usr --strip-components=1 -xaf gcc-arm-none-eabi-9-2019-q4-major-x86_64-linux.tar.bz2 + export PATH=$PATH:`$HOME/opt/xPacks/@xpack-dev-tools/riscv-none-embed-gcc/*/.content/bin` + # sudo apt-get install -y gettext + # pip install requests sh click setuptools awscli + # wget https://adafruit-circuit-python.s3.amazonaws.com/gcc-arm-none-eabi-9-2019-q4-major-x86_64-linux.tar.bz2 + # sudo tar -C /usr --strip-components=1 -xaf gcc-arm-none-eabi-9-2019-q4-major-x86_64-linux.tar.bz2 - name: Versions run: | - arm-none-eabi-gcc --version + #arm-none-eabi-gcc --version riscv-none-embed-gcc --version - name: Git clone uses: actions/checkout@v1 From 56f717bca1aa32ec33f855a69c5b1d80ec1c1fc5 Mon Sep 17 00:00:00 2001 From: Ha Thach Date: Fri, 27 Dec 2019 18:01:14 +0700 Subject: [PATCH 149/267] Update build.yml --- .github/workflows/build.yml | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 7a34228d..d0dbf3b6 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -17,15 +17,15 @@ jobs: run: | # Install XPM npm install --global xpm + # Install ARM GCC + xpm install --global @xpack-dev-tools/arm-none-eabi-gcc@latest + export PATH=$PATH:`echo $HOME/opt/xPacks/@xpack-dev-tools/arm-none-embed-gcc/*/.content/bin` + # Install RISCV GCC xpm install --global @xpack-dev-tools/riscv-none-embed-gcc@latest - export PATH=$PATH:`$HOME/opt/xPacks/@xpack-dev-tools/riscv-none-embed-gcc/*/.content/bin` - # sudo apt-get install -y gettext - # pip install requests sh click setuptools awscli - # wget https://adafruit-circuit-python.s3.amazonaws.com/gcc-arm-none-eabi-9-2019-q4-major-x86_64-linux.tar.bz2 - # sudo tar -C /usr --strip-components=1 -xaf gcc-arm-none-eabi-9-2019-q4-major-x86_64-linux.tar.bz2 + export PATH=$PATH:`echo $HOME/opt/xPacks/@xpack-dev-tools/riscv-none-embed-gcc/*/.content/bin` - name: Versions run: | - #arm-none-eabi-gcc --version + arm-none-eabi-gcc --version riscv-none-embed-gcc --version - name: Git clone uses: actions/checkout@v1 From ee3e2bcc91149171c4585b7e592e2e791e92e85d Mon Sep 17 00:00:00 2001 From: Ha Thach Date: Fri, 27 Dec 2019 20:07:22 +0700 Subject: [PATCH 150/267] Update build.yml --- .github/workflows/build.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index d0dbf3b6..9c2d329c 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -23,6 +23,8 @@ jobs: # Install RISCV GCC xpm install --global @xpack-dev-tools/riscv-none-embed-gcc@latest export PATH=$PATH:`echo $HOME/opt/xPacks/@xpack-dev-tools/riscv-none-embed-gcc/*/.content/bin` + arm-none-eabi-gcc --version + riscv-none-embed-gcc --version - name: Versions run: | arm-none-eabi-gcc --version From 22ec72cd4b295f733931d5d23d032e904d4b14b3 Mon Sep 17 00:00:00 2001 From: Ha Thach Date: Fri, 27 Dec 2019 20:09:18 +0700 Subject: [PATCH 151/267] Update build.yml --- .github/workflows/build.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 9c2d329c..627d7256 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -23,6 +23,7 @@ jobs: # Install RISCV GCC xpm install --global @xpack-dev-tools/riscv-none-embed-gcc@latest export PATH=$PATH:`echo $HOME/opt/xPacks/@xpack-dev-tools/riscv-none-embed-gcc/*/.content/bin` + echo $PATH arm-none-eabi-gcc --version riscv-none-embed-gcc --version - name: Versions From 81592feca53d5c0d2ea191eddc07ac758627e547 Mon Sep 17 00:00:00 2001 From: Ha Thach Date: Fri, 27 Dec 2019 20:11:43 +0700 Subject: [PATCH 152/267] Update build.yml --- .github/workflows/build.yml | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 627d7256..cb1930e8 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -19,15 +19,10 @@ jobs: npm install --global xpm # Install ARM GCC xpm install --global @xpack-dev-tools/arm-none-eabi-gcc@latest - export PATH=$PATH:`echo $HOME/opt/xPacks/@xpack-dev-tools/arm-none-embed-gcc/*/.content/bin` + export PATH=$PATH:`echo $HOME/opt/xPacks/@xpack-dev-tools/arm-none-eabi-gcc/*/.content/bin` # Install RISCV GCC xpm install --global @xpack-dev-tools/riscv-none-embed-gcc@latest export PATH=$PATH:`echo $HOME/opt/xPacks/@xpack-dev-tools/riscv-none-embed-gcc/*/.content/bin` - echo $PATH - arm-none-eabi-gcc --version - riscv-none-embed-gcc --version - - name: Versions - run: | arm-none-eabi-gcc --version riscv-none-embed-gcc --version - name: Git clone From a4be3a3227861d40c9179cde209e16b52ea2c456 Mon Sep 17 00:00:00 2001 From: Ha Thach Date: Fri, 27 Dec 2019 20:29:25 +0700 Subject: [PATCH 153/267] Update build.yml --- .github/workflows/build.yml | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index cb1930e8..ccb39f7d 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -7,13 +7,15 @@ jobs: runs-on: ubuntu-latest steps: - - name: Python + - name: Setup Python uses: actions/setup-python@v1 with: python-version: 3.5 - - name: Node.js + - name: Setup Node.js uses: actions/setup-node@v1.1.0 - - name: Toolchains + - name: Setup Ruby + uses: actions/setup-ruby@v1.0.0 + - name: Install Toolchains run: | # Install XPM npm install --global xpm @@ -29,3 +31,10 @@ jobs: uses: actions/checkout@v1 with: submodules: true + - name: Unit Tests + run: | + # Install Ceedling + gem install ceedling + cd test + ceedling test:all + From 7590266ad71aacf46fc567d30dfab0079a5e03be Mon Sep 17 00:00:00 2001 From: Ha Thach Date: Fri, 27 Dec 2019 20:33:09 +0700 Subject: [PATCH 154/267] Update build.yml --- .github/workflows/build.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index ccb39f7d..fbb4dd85 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -37,4 +37,7 @@ jobs: gem install ceedling cd test ceedling test:all - + cd .. + - name: Build + run: | + python3 tools/build_all.py board_test From ce5ceea3c4dde6a9590d43ca80d18dad2a8b2554 Mon Sep 17 00:00:00 2001 From: Ha Thach Date: Fri, 27 Dec 2019 20:38:39 +0700 Subject: [PATCH 155/267] Update build.yml --- .github/workflows/build.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index fbb4dd85..24506c16 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -40,4 +40,6 @@ jobs: cd .. - name: Build run: | + arm-none-eabi-gcc --version + riscv-none-embed-gcc --version python3 tools/build_all.py board_test From 424063afd14dadf52cf3019da7c695830d72a557 Mon Sep 17 00:00:00 2001 From: Ha Thach Date: Fri, 27 Dec 2019 20:41:51 +0700 Subject: [PATCH 156/267] Update build.yml --- .github/workflows/build.yml | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 24506c16..d8b3e56e 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -17,16 +17,9 @@ jobs: uses: actions/setup-ruby@v1.0.0 - name: Install Toolchains run: | - # Install XPM npm install --global xpm - # Install ARM GCC xpm install --global @xpack-dev-tools/arm-none-eabi-gcc@latest - export PATH=$PATH:`echo $HOME/opt/xPacks/@xpack-dev-tools/arm-none-eabi-gcc/*/.content/bin` - # Install RISCV GCC xpm install --global @xpack-dev-tools/riscv-none-embed-gcc@latest - export PATH=$PATH:`echo $HOME/opt/xPacks/@xpack-dev-tools/riscv-none-embed-gcc/*/.content/bin` - arm-none-eabi-gcc --version - riscv-none-embed-gcc --version - name: Git clone uses: actions/checkout@v1 with: @@ -40,6 +33,7 @@ jobs: cd .. - name: Build run: | + export PATH=$PATH:`echo $HOME/opt/xPacks/@xpack-dev-tools/arm-none-eabi-gcc/*/.content/bin`:`echo $HOME/opt/xPacks/@xpack-dev-tools/riscv-none-embed-gcc/*/.content/bin` arm-none-eabi-gcc --version riscv-none-embed-gcc --version python3 tools/build_all.py board_test From 6e4df81998399e86f18bb2db47e94b013f394846 Mon Sep 17 00:00:00 2001 From: Ha Thach Date: Fri, 27 Dec 2019 20:49:54 +0700 Subject: [PATCH 157/267] Update build.yml --- .github/workflows/build.yml | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index d8b3e56e..ff86e72c 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -21,9 +21,13 @@ jobs: xpm install --global @xpack-dev-tools/arm-none-eabi-gcc@latest xpm install --global @xpack-dev-tools/riscv-none-embed-gcc@latest - name: Git clone - uses: actions/checkout@v1 - with: - submodules: true + uses: actions/checkout@v2 + - name: Checkout submodules + shell: bash + run: | + auth_header="$(git config --local --get http.https://github.com/.extraheader)" + git submodule sync --recursive + git -c "http.extraheader=$auth_header" -c protocol.version=2 submodule update --init --force --recursive - name: Unit Tests run: | # Install Ceedling From e74dd33945d66f8d685f416eb927a3dac86a510c Mon Sep 17 00:00:00 2001 From: Ha Thach Date: Fri, 27 Dec 2019 20:53:55 +0700 Subject: [PATCH 158/267] Update build.yml --- .github/workflows/build.yml | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index ff86e72c..6f491808 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -11,23 +11,29 @@ jobs: uses: actions/setup-python@v1 with: python-version: 3.5 + - name: Setup Node.js uses: actions/setup-node@v1.1.0 + - name: Setup Ruby uses: actions/setup-ruby@v1.0.0 + - name: Install Toolchains run: | npm install --global xpm xpm install --global @xpack-dev-tools/arm-none-eabi-gcc@latest xpm install --global @xpack-dev-tools/riscv-none-embed-gcc@latest - - name: Git clone + + - name: Checkout TinyUSB uses: actions/checkout@v2 + - name: Checkout submodules shell: bash run: | auth_header="$(git config --local --get http.https://github.com/.extraheader)" git submodule sync --recursive git -c "http.extraheader=$auth_header" -c protocol.version=2 submodule update --init --force --recursive + - name: Unit Tests run: | # Install Ceedling @@ -35,6 +41,7 @@ jobs: cd test ceedling test:all cd .. + - name: Build run: | export PATH=$PATH:`echo $HOME/opt/xPacks/@xpack-dev-tools/arm-none-eabi-gcc/*/.content/bin`:`echo $HOME/opt/xPacks/@xpack-dev-tools/riscv-none-embed-gcc/*/.content/bin` From 72af007a1927d91a95b41aa86e28838ef9b57c21 Mon Sep 17 00:00:00 2001 From: Ha Thach Date: Fri, 27 Dec 2019 20:58:37 +0700 Subject: [PATCH 159/267] Update build.yml --- .github/workflows/build.yml | 35 ++++++++++++++++++++--------------- 1 file changed, 20 insertions(+), 15 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 6f491808..2d4fdec3 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -3,21 +3,34 @@ name: TinyUSB CI on: [pull_request, push] jobs: + unit-test: + runs-on: ubuntu-latest + steps: + - name: Setup Ruby + uses: actions/setup-ruby@v1.0.0 + + - name: Checkout TinyUSB + uses: actions/checkout@v2 + + - name: Unit Tests + run: | + # Install Ceedling + gem install ceedling + cd test + ceedling test:all + cd .. + build: - runs-on: ubuntu-latest - + runs-on: ubuntu-latest steps: - name: Setup Python uses: actions/setup-python@v1 with: python-version: 3.5 - + - name: Setup Node.js uses: actions/setup-node@v1.1.0 - - - name: Setup Ruby - uses: actions/setup-ruby@v1.0.0 - + - name: Install Toolchains run: | npm install --global xpm @@ -34,14 +47,6 @@ jobs: git submodule sync --recursive git -c "http.extraheader=$auth_header" -c protocol.version=2 submodule update --init --force --recursive - - name: Unit Tests - run: | - # Install Ceedling - gem install ceedling - cd test - ceedling test:all - cd .. - - name: Build run: | export PATH=$PATH:`echo $HOME/opt/xPacks/@xpack-dev-tools/arm-none-eabi-gcc/*/.content/bin`:`echo $HOME/opt/xPacks/@xpack-dev-tools/riscv-none-embed-gcc/*/.content/bin` From e14698028c86226e03e024a7d998e0a63e43516d Mon Sep 17 00:00:00 2001 From: Ha Thach Date: Fri, 27 Dec 2019 21:03:40 +0700 Subject: [PATCH 160/267] Update build.yml --- .github/workflows/build.yml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 2d4fdec3..9dc8d999 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -21,7 +21,11 @@ jobs: cd .. build: - runs-on: ubuntu-latest + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + example: ['board_test', 'cdc_msc', 'dfu_rt', 'hid_composite', 'hid_generic_inout', 'midi_test', 'msc_dual_lun', 'usbtmc', 'webusb_serial'] steps: - name: Setup Python uses: actions/setup-python@v1 From e4a0af5e5ec54e217674bb4c74d87868f401b642 Mon Sep 17 00:00:00 2001 From: Ha Thach Date: Fri, 27 Dec 2019 21:08:16 +0700 Subject: [PATCH 161/267] Update build.yml --- .github/workflows/build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 9dc8d999..75cd57d1 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -56,4 +56,4 @@ jobs: export PATH=$PATH:`echo $HOME/opt/xPacks/@xpack-dev-tools/arm-none-eabi-gcc/*/.content/bin`:`echo $HOME/opt/xPacks/@xpack-dev-tools/riscv-none-embed-gcc/*/.content/bin` arm-none-eabi-gcc --version riscv-none-embed-gcc --version - python3 tools/build_all.py board_test + python3 tools/build_all.py ${{ matrix.example }} From 2b6b856d7c0ba51cb1b3c1467c33c7527fb8c47e Mon Sep 17 00:00:00 2001 From: Ha Thach Date: Fri, 27 Dec 2019 21:12:53 +0700 Subject: [PATCH 162/267] wrap up actions --- .github/workflows/build.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 75cd57d1..e0fdb93d 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -18,7 +18,6 @@ jobs: gem install ceedling cd test ceedling test:all - cd .. build: runs-on: ubuntu-latest @@ -40,6 +39,9 @@ jobs: npm install --global xpm xpm install --global @xpack-dev-tools/arm-none-eabi-gcc@latest xpm install --global @xpack-dev-tools/riscv-none-embed-gcc@latest + export PATH=$PATH:`echo $HOME/opt/xPacks/@xpack-dev-tools/arm-none-eabi-gcc/*/.content/bin`:`echo $HOME/opt/xPacks/@xpack-dev-tools/riscv-none-embed-gcc/*/.content/bin` + arm-none-eabi-gcc --version + riscv-none-embed-gcc --version - name: Checkout TinyUSB uses: actions/checkout@v2 @@ -54,6 +56,4 @@ jobs: - name: Build run: | export PATH=$PATH:`echo $HOME/opt/xPacks/@xpack-dev-tools/arm-none-eabi-gcc/*/.content/bin`:`echo $HOME/opt/xPacks/@xpack-dev-tools/riscv-none-embed-gcc/*/.content/bin` - arm-none-eabi-gcc --version - riscv-none-embed-gcc --version python3 tools/build_all.py ${{ matrix.example }} From 70abfe7f45358af324613fb14c0746ae38ecf67e Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 27 Dec 2019 21:39:44 +0700 Subject: [PATCH 163/267] use github actions for build badge --- .github/workflows/build.yml | 2 +- README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index e0fdb93d..82e9d573 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1,4 +1,4 @@ -name: TinyUSB CI +name: Build on: [pull_request, push] diff --git a/README.md b/README.md index 798c10a5..eccb7627 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ ![tinyUSB_240x100](https://user-images.githubusercontent.com/249515/62646655-f9393200-b978-11e9-9c53-484862f15503.png) -[![Build Status](https://travis-ci.org/hathach/tinyusb.svg?branch=master)](https://travis-ci.org/hathach/tinyusb) [![License](https://img.shields.io/badge/license-MIT-brightgreen.svg)](https://opensource.org/licenses/MIT) [![Coverity](https://img.shields.io/coverity/scan/458.svg)](https://scan.coverity.com/projects/tinyusb) +[![Build Status](https://github.com/hathach/tinyusb/workflows/Build/badge.svg)](https://travis-ci.org/hathach/tinyusb) [![License](https://img.shields.io/badge/license-MIT-brightgreen.svg)](https://opensource.org/licenses/MIT) [![Coverity](https://img.shields.io/coverity/scan/458.svg)](https://scan.coverity.com/projects/tinyusb) TinyUSB is an open-source cross-platform USB Host/Device stack for embedded system, designed to be memory-safe with no dynamic allocation and thread-safe with all interrupt events are deferred then handled in the non-ISR task function. From 947e7b803a05365065e67f92a3b90898138577b0 Mon Sep 17 00:00:00 2001 From: hathach Date: Sat, 28 Dec 2019 15:03:25 +0700 Subject: [PATCH 164/267] more ci --- .github/workflows/build.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 82e9d573..6f0b9df9 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -39,7 +39,9 @@ jobs: npm install --global xpm xpm install --global @xpack-dev-tools/arm-none-eabi-gcc@latest xpm install --global @xpack-dev-tools/riscv-none-embed-gcc@latest - export PATH=$PATH:`echo $HOME/opt/xPacks/@xpack-dev-tools/arm-none-eabi-gcc/*/.content/bin`:`echo $HOME/opt/xPacks/@xpack-dev-tools/riscv-none-embed-gcc/*/.content/bin` + echo "::add-path::$HOME/opt/xPacks/@xpack-dev-tools/arm-none-eabi-gcc/*/.content/bin" + echo "::add-path::$HOME/opt/xPacks/@xpack-dev-tools/riscv-none-embed-gcc/*/.content/bin" + #export PATH=$PATH:`echo $HOME/opt/xPacks/@xpack-dev-tools/arm-none-eabi-gcc/*/.content/bin`:`echo $HOME/opt/xPacks/@xpack-dev-tools/riscv-none-embed-gcc/*/.content/bin` arm-none-eabi-gcc --version riscv-none-embed-gcc --version @@ -54,6 +56,4 @@ jobs: git -c "http.extraheader=$auth_header" -c protocol.version=2 submodule update --init --force --recursive - name: Build - run: | - export PATH=$PATH:`echo $HOME/opt/xPacks/@xpack-dev-tools/arm-none-eabi-gcc/*/.content/bin`:`echo $HOME/opt/xPacks/@xpack-dev-tools/riscv-none-embed-gcc/*/.content/bin` - python3 tools/build_all.py ${{ matrix.example }} + run: python3 tools/build_all.py ${{ matrix.example }} From ac78f420329130231b42245dcc6c73e40ac100b0 Mon Sep 17 00:00:00 2001 From: hathach Date: Sat, 28 Dec 2019 15:05:33 +0700 Subject: [PATCH 165/267] ci --- .github/workflows/build.yml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 6f0b9df9..66f58830 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -39,8 +39,9 @@ jobs: npm install --global xpm xpm install --global @xpack-dev-tools/arm-none-eabi-gcc@latest xpm install --global @xpack-dev-tools/riscv-none-embed-gcc@latest - echo "::add-path::$HOME/opt/xPacks/@xpack-dev-tools/arm-none-eabi-gcc/*/.content/bin" - echo "::add-path::$HOME/opt/xPacks/@xpack-dev-tools/riscv-none-embed-gcc/*/.content/bin" + echo "::add-path::`echo $HOME/opt/xPacks/@xpack-dev-tools/arm-none-eabi-gcc/*/.content/bin`" + echo "::add-path::`echo $HOME/opt/xPacks/@xpack-dev-tools/riscv-none-embed-gcc/*/.content/bin`" + echo $PATH #export PATH=$PATH:`echo $HOME/opt/xPacks/@xpack-dev-tools/arm-none-eabi-gcc/*/.content/bin`:`echo $HOME/opt/xPacks/@xpack-dev-tools/riscv-none-embed-gcc/*/.content/bin` arm-none-eabi-gcc --version riscv-none-embed-gcc --version From 1b8626025eebbb1f5919caabee684d9e7473aee6 Mon Sep 17 00:00:00 2001 From: hathach Date: Sat, 28 Dec 2019 15:35:12 +0700 Subject: [PATCH 166/267] ci --- .github/workflows/build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 66f58830..ab9de729 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -39,7 +39,7 @@ jobs: npm install --global xpm xpm install --global @xpack-dev-tools/arm-none-eabi-gcc@latest xpm install --global @xpack-dev-tools/riscv-none-embed-gcc@latest - echo "::add-path::`echo $HOME/opt/xPacks/@xpack-dev-tools/arm-none-eabi-gcc/*/.content/bin`" + echo "::add-path::$HOME/opt/xPacks/@xpack-dev-tools/arm-none-eabi-gcc/*/.content/bin" echo "::add-path::`echo $HOME/opt/xPacks/@xpack-dev-tools/riscv-none-embed-gcc/*/.content/bin`" echo $PATH #export PATH=$PATH:`echo $HOME/opt/xPacks/@xpack-dev-tools/arm-none-eabi-gcc/*/.content/bin`:`echo $HOME/opt/xPacks/@xpack-dev-tools/riscv-none-embed-gcc/*/.content/bin` From dc8a68c7c0176e6ba160f7bb26553ae9804c286b Mon Sep 17 00:00:00 2001 From: hathach Date: Sat, 28 Dec 2019 15:36:25 +0700 Subject: [PATCH 167/267] ci --- .github/workflows/build.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index ab9de729..947f8ad0 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -41,6 +41,7 @@ jobs: xpm install --global @xpack-dev-tools/riscv-none-embed-gcc@latest echo "::add-path::$HOME/opt/xPacks/@xpack-dev-tools/arm-none-eabi-gcc/*/.content/bin" echo "::add-path::`echo $HOME/opt/xPacks/@xpack-dev-tools/riscv-none-embed-gcc/*/.content/bin`" + echo "::set-env PATH=`echo $HOME/opt/xPacks/@xpack-dev-tools/riscv-none-embed-gcc/*/.content/bin`" echo $PATH #export PATH=$PATH:`echo $HOME/opt/xPacks/@xpack-dev-tools/arm-none-eabi-gcc/*/.content/bin`:`echo $HOME/opt/xPacks/@xpack-dev-tools/riscv-none-embed-gcc/*/.content/bin` arm-none-eabi-gcc --version From ccbae7538ddf7961af310b71f30a99f30db2fd52 Mon Sep 17 00:00:00 2001 From: hathach Date: Sat, 28 Dec 2019 15:41:44 +0700 Subject: [PATCH 168/267] ci test --- .github/workflows/build.yml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 947f8ad0..1c58f58e 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -39,9 +39,13 @@ jobs: npm install --global xpm xpm install --global @xpack-dev-tools/arm-none-eabi-gcc@latest xpm install --global @xpack-dev-tools/riscv-none-embed-gcc@latest + echo $PATH echo "::add-path::$HOME/opt/xPacks/@xpack-dev-tools/arm-none-eabi-gcc/*/.content/bin" echo "::add-path::`echo $HOME/opt/xPacks/@xpack-dev-tools/riscv-none-embed-gcc/*/.content/bin`" - echo "::set-env PATH=`echo $HOME/opt/xPacks/@xpack-dev-tools/riscv-none-embed-gcc/*/.content/bin`" + + echo "::add-path::/thach_tinyusb/" + + echo "::set-env name=PATH::$PATH:`echo $HOME/opt/xPacks/@xpack-dev-tools/riscv-none-embed-gcc/*/.content/bin`" echo $PATH #export PATH=$PATH:`echo $HOME/opt/xPacks/@xpack-dev-tools/arm-none-eabi-gcc/*/.content/bin`:`echo $HOME/opt/xPacks/@xpack-dev-tools/riscv-none-embed-gcc/*/.content/bin` arm-none-eabi-gcc --version From 274488ec65b0e46e0bc773d52929665be5438dd7 Mon Sep 17 00:00:00 2001 From: hathach Date: Sat, 28 Dec 2019 15:45:44 +0700 Subject: [PATCH 169/267] more ci test --- .github/workflows/build.yml | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 1c58f58e..fbd4f6bb 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -40,10 +40,14 @@ jobs: xpm install --global @xpack-dev-tools/arm-none-eabi-gcc@latest xpm install --global @xpack-dev-tools/riscv-none-embed-gcc@latest echo $PATH - echo "::add-path::$HOME/opt/xPacks/@xpack-dev-tools/arm-none-eabi-gcc/*/.content/bin" - echo "::add-path::`echo $HOME/opt/xPacks/@xpack-dev-tools/riscv-none-embed-gcc/*/.content/bin`" - echo "::add-path::/thach_tinyusb/" + echo $PATH + echo "::add-path::`echo $HOME/opt/xPacks/@xpack-dev-tools/arm-none-eabi-gcc/*/.content/bin`" + echo $PATH + echo "::add-path::$HOME/opt/xPacks/@xpack-dev-tools/arm-none-eabi-gcc/*/.content/bin" + echo $PATH + echo "::add-path::`echo $HOME/opt/xPacks/@xpack-dev-tools/riscv-none-embed-gcc/*/.content/bin`" + echo $PATH echo "::set-env name=PATH::$PATH:`echo $HOME/opt/xPacks/@xpack-dev-tools/riscv-none-embed-gcc/*/.content/bin`" echo $PATH From f5cc48017a5c751ed66ff5d74c7f78ee81f9686a Mon Sep 17 00:00:00 2001 From: hathach Date: Sat, 28 Dec 2019 15:49:38 +0700 Subject: [PATCH 170/267] more ci --- .github/workflows/build.yml | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index fbd4f6bb..1b0865c0 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -42,19 +42,21 @@ jobs: echo $PATH echo "::add-path::/thach_tinyusb/" echo $PATH - echo "::add-path::`echo $HOME/opt/xPacks/@xpack-dev-tools/arm-none-eabi-gcc/*/.content/bin`" - echo $PATH - echo "::add-path::$HOME/opt/xPacks/@xpack-dev-tools/arm-none-eabi-gcc/*/.content/bin" - echo $PATH - echo "::add-path::`echo $HOME/opt/xPacks/@xpack-dev-tools/riscv-none-embed-gcc/*/.content/bin`" - echo $PATH + #echo "::add-path::`echo $HOME/opt/xPacks/@xpack-dev-tools/arm-none-eabi-gcc/*/.content/bin`" + #echo $PATH + #echo "::add-path::$HOME/opt/xPacks/@xpack-dev-tools/arm-none-eabi-gcc/*/.content/bin" + #echo $PATH + #echo "::add-path::`echo $HOME/opt/xPacks/@xpack-dev-tools/riscv-none-embed-gcc/*/.content/bin`" + #echo $PATH - echo "::set-env name=PATH::$PATH:`echo $HOME/opt/xPacks/@xpack-dev-tools/riscv-none-embed-gcc/*/.content/bin`" - echo $PATH + #echo "::set-env name=PATH::$PATH:`echo $HOME/opt/xPacks/@xpack-dev-tools/riscv-none-embed-gcc/*/.content/bin`" + #echo $PATH #export PATH=$PATH:`echo $HOME/opt/xPacks/@xpack-dev-tools/arm-none-eabi-gcc/*/.content/bin`:`echo $HOME/opt/xPacks/@xpack-dev-tools/riscv-none-embed-gcc/*/.content/bin` - arm-none-eabi-gcc --version - riscv-none-embed-gcc --version - + #arm-none-eabi-gcc --version + #riscv-none-embed-gcc --version + - nane: test PATH + run: echo $PATH + - name: Checkout TinyUSB uses: actions/checkout@v2 From 4406e378ce81d3c817e6f3679c6ff4a8dd9f1531 Mon Sep 17 00:00:00 2001 From: hathach Date: Sat, 28 Dec 2019 15:52:15 +0700 Subject: [PATCH 171/267] ci typo --- .github/workflows/build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 1b0865c0..4e563ed1 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -54,7 +54,7 @@ jobs: #export PATH=$PATH:`echo $HOME/opt/xPacks/@xpack-dev-tools/arm-none-eabi-gcc/*/.content/bin`:`echo $HOME/opt/xPacks/@xpack-dev-tools/riscv-none-embed-gcc/*/.content/bin` #arm-none-eabi-gcc --version #riscv-none-embed-gcc --version - - nane: test PATH + - name: test PATH run: echo $PATH - name: Checkout TinyUSB From bfdc9a94f9a89922ede1f64eea96e4d63d3bd87a Mon Sep 17 00:00:00 2001 From: hathach Date: Sat, 28 Dec 2019 15:55:18 +0700 Subject: [PATCH 172/267] test ci --- .github/workflows/build.yml | 15 ++------------- 1 file changed, 2 insertions(+), 13 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 4e563ed1..10961837 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -39,21 +39,10 @@ jobs: npm install --global xpm xpm install --global @xpack-dev-tools/arm-none-eabi-gcc@latest xpm install --global @xpack-dev-tools/riscv-none-embed-gcc@latest - echo $PATH echo "::add-path::/thach_tinyusb/" - echo $PATH - #echo "::add-path::`echo $HOME/opt/xPacks/@xpack-dev-tools/arm-none-eabi-gcc/*/.content/bin`" - #echo $PATH - #echo "::add-path::$HOME/opt/xPacks/@xpack-dev-tools/arm-none-eabi-gcc/*/.content/bin" - #echo $PATH + echo "::add-path::`echo $HOME/opt/xPacks/@xpack-dev-tools/arm-none-eabi-gcc/*/.content/bin`" + echo "::add-path::$HOME/opt/xPacks/@xpack-dev-tools/arm-none-eabi-gcc/*/.content/bin" #echo "::add-path::`echo $HOME/opt/xPacks/@xpack-dev-tools/riscv-none-embed-gcc/*/.content/bin`" - #echo $PATH - - #echo "::set-env name=PATH::$PATH:`echo $HOME/opt/xPacks/@xpack-dev-tools/riscv-none-embed-gcc/*/.content/bin`" - #echo $PATH - #export PATH=$PATH:`echo $HOME/opt/xPacks/@xpack-dev-tools/arm-none-eabi-gcc/*/.content/bin`:`echo $HOME/opt/xPacks/@xpack-dev-tools/riscv-none-embed-gcc/*/.content/bin` - #arm-none-eabi-gcc --version - #riscv-none-embed-gcc --version - name: test PATH run: echo $PATH From 1bcf1217857fe5228669c01f8e78e5d411ee06a0 Mon Sep 17 00:00:00 2001 From: hathach Date: Sat, 28 Dec 2019 16:11:10 +0700 Subject: [PATCH 173/267] ci use github ::add-path:: --- .github/workflows/build.yml | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 10961837..6e71351a 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -28,8 +28,6 @@ jobs: steps: - name: Setup Python uses: actions/setup-python@v1 - with: - python-version: 3.5 - name: Setup Node.js uses: actions/setup-node@v1.1.0 @@ -39,12 +37,8 @@ jobs: npm install --global xpm xpm install --global @xpack-dev-tools/arm-none-eabi-gcc@latest xpm install --global @xpack-dev-tools/riscv-none-embed-gcc@latest - echo "::add-path::/thach_tinyusb/" echo "::add-path::`echo $HOME/opt/xPacks/@xpack-dev-tools/arm-none-eabi-gcc/*/.content/bin`" - echo "::add-path::$HOME/opt/xPacks/@xpack-dev-tools/arm-none-eabi-gcc/*/.content/bin" - #echo "::add-path::`echo $HOME/opt/xPacks/@xpack-dev-tools/riscv-none-embed-gcc/*/.content/bin`" - - name: test PATH - run: echo $PATH + echo "::add-path::`echo $HOME/opt/xPacks/@xpack-dev-tools/riscv-none-embed-gcc/*/.content/bin`" - name: Checkout TinyUSB uses: actions/checkout@v2 From 8e04eafb8a71ac214cfcb8b5a19c2b9aa00c492b Mon Sep 17 00:00:00 2001 From: Ha Thach Date: Sat, 28 Dec 2019 16:24:32 +0700 Subject: [PATCH 174/267] more ci (#253) * more ci * ci * ci * ci * ci test * more ci test * more ci * ci typo * test ci * ci use github ::add-path:: --- .github/workflows/build.yml | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 82e9d573..6e71351a 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -28,8 +28,6 @@ jobs: steps: - name: Setup Python uses: actions/setup-python@v1 - with: - python-version: 3.5 - name: Setup Node.js uses: actions/setup-node@v1.1.0 @@ -39,10 +37,9 @@ jobs: npm install --global xpm xpm install --global @xpack-dev-tools/arm-none-eabi-gcc@latest xpm install --global @xpack-dev-tools/riscv-none-embed-gcc@latest - export PATH=$PATH:`echo $HOME/opt/xPacks/@xpack-dev-tools/arm-none-eabi-gcc/*/.content/bin`:`echo $HOME/opt/xPacks/@xpack-dev-tools/riscv-none-embed-gcc/*/.content/bin` - arm-none-eabi-gcc --version - riscv-none-embed-gcc --version - + echo "::add-path::`echo $HOME/opt/xPacks/@xpack-dev-tools/arm-none-eabi-gcc/*/.content/bin`" + echo "::add-path::`echo $HOME/opt/xPacks/@xpack-dev-tools/riscv-none-embed-gcc/*/.content/bin`" + - name: Checkout TinyUSB uses: actions/checkout@v2 @@ -54,6 +51,4 @@ jobs: git -c "http.extraheader=$auth_header" -c protocol.version=2 submodule update --init --force --recursive - name: Build - run: | - export PATH=$PATH:`echo $HOME/opt/xPacks/@xpack-dev-tools/arm-none-eabi-gcc/*/.content/bin`:`echo $HOME/opt/xPacks/@xpack-dev-tools/riscv-none-embed-gcc/*/.content/bin` - python3 tools/build_all.py ${{ matrix.example }} + run: python3 tools/build_all.py ${{ matrix.example }} From ff0e7d2bed64592c16e73e83cead8d76eda66f36 Mon Sep 17 00:00:00 2001 From: Peter Lawrence <12226419+majbthrd@users.noreply.github.com> Date: Sun, 22 Dec 2019 18:18:54 -0600 Subject: [PATCH 175/267] implement multiple interfaces support --- examples/device/cdc_dual_ports/Makefile | 12 ++ examples/device/cdc_dual_ports/src/main.c | 98 +++++++++++ .../device/cdc_dual_ports/src/tusb_config.h | 92 ++++++++++ .../cdc_dual_ports/src/usb_descriptors.c | 166 ++++++++++++++++++ .../cdc_dual_ports/src/usb_descriptors.h | 28 +++ src/class/cdc/cdc_device.c | 39 +++- src/class/hid/hid_device.c | 27 ++- src/class/midi/midi_device.c | 12 +- src/class/vendor/vendor_device.c | 12 +- 9 files changed, 465 insertions(+), 21 deletions(-) create mode 100644 examples/device/cdc_dual_ports/Makefile create mode 100644 examples/device/cdc_dual_ports/src/main.c create mode 100644 examples/device/cdc_dual_ports/src/tusb_config.h create mode 100644 examples/device/cdc_dual_ports/src/usb_descriptors.c create mode 100644 examples/device/cdc_dual_ports/src/usb_descriptors.h diff --git a/examples/device/cdc_dual_ports/Makefile b/examples/device/cdc_dual_ports/Makefile new file mode 100644 index 00000000..5a455078 --- /dev/null +++ b/examples/device/cdc_dual_ports/Makefile @@ -0,0 +1,12 @@ +include ../../../tools/top.mk +include ../../make.mk + +INC += \ + src \ + $(TOP)/hw \ + +# Example source +EXAMPLE_SOURCE += $(wildcard src/*.c) +SRC_C += $(addprefix $(CURRENT_PATH)/, $(EXAMPLE_SOURCE)) + +include ../../rules.mk diff --git a/examples/device/cdc_dual_ports/src/main.c b/examples/device/cdc_dual_ports/src/main.c new file mode 100644 index 00000000..e612dc83 --- /dev/null +++ b/examples/device/cdc_dual_ports/src/main.c @@ -0,0 +1,98 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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 +#include +#include +#include + +#include "bsp/board.h" +#include "tusb.h" +#include "usb_descriptors.h" + +//------------- prototypes -------------// +static void cdc_task(void); + +/*------------- MAIN -------------*/ +int main(void) +{ + board_init(); + + tusb_init(); + + while (1) + { + tud_task(); // tinyusb device task + cdc_task(); + } + + return 0; +} + +static void echo_all(uint8_t itf, uint8_t buf[], uint32_t count) +{ + for(uint32_t i=0; i 1) + ITF_NUM_CDC2, + ITF_NUM_CDC_DATA2, +#endif + ITF_NUM_TOTAL +}; + +#define CONFIG_TOTAL_LEN (TUD_CONFIG_DESC_LEN + CFG_TUD_CDC * TUD_CDC_DESC_LEN) + +#if CFG_TUSB_MCU == OPT_MCU_LPC175X_6X || CFG_TUSB_MCU == OPT_MCU_LPC177X_8X || CFG_TUSB_MCU == OPT_MCU_LPC40XX + // LPC 17xx and 40xx endpoint type (bulk/interrupt/iso) are fixed by its number + // 0 control, 1 In, 2 Bulk, 3 Iso, 4 In etc ... + #define EPNUM_CDC 2 +#else + #define EPNUM_CDC 2 +#endif + +uint8_t const desc_configuration[] = +{ + // Interface count, string index, total length, attribute, power in mA + TUD_CONFIG_DESCRIPTOR(ITF_NUM_TOTAL, 0, CONFIG_TOTAL_LEN, TUSB_DESC_CONFIG_ATT_REMOTE_WAKEUP, 100), + + // Interface number, string index, EP notification address and size, EP data address (out, in) and size. + TUD_CDC_DESCRIPTOR(ITF_NUM_CDC1, 4, 0x81, 8, EPNUM_CDC, 0x80 | EPNUM_CDC, 64), +#if (CFG_TUD_CDC > 1) + TUD_CDC_DESCRIPTOR(ITF_NUM_CDC2, 4, 0x83, 8, EPNUM_CDC + 2, 0x80 | (EPNUM_CDC + 2), 64), +#endif +}; + +// Invoked when received GET CONFIGURATION DESCRIPTOR +// Application return pointer to descriptor +// Descriptor contents must exist long enough for transfer to complete +uint8_t const * tud_descriptor_configuration_cb(uint8_t index) +{ + (void) index; // for multiple configurations + return desc_configuration; +} + +//--------------------------------------------------------------------+ +// String Descriptors +//--------------------------------------------------------------------+ + +// array of pointer to string descriptors +char const* string_desc_arr [] = +{ + (const char[]) { 0x09, 0x04 }, // 0: is supported language is English (0x0409) + "TinyUSB", // 1: Manufacturer + "TinyUSB Device", // 2: Product + "123456", // 3: Serials, should use chip ID + "TinyUSB CDC", // 4: CDC Interface +}; + +static uint16_t _desc_str[32]; + +// Invoked when received GET STRING DESCRIPTOR request +// Application return pointer to descriptor, whose contents must exist long enough for transfer to complete +uint16_t const* tud_descriptor_string_cb(uint8_t index) +{ + uint8_t chr_count; + + if ( index == 0) + { + memcpy(&_desc_str[1], string_desc_arr[0], 2); + chr_count = 1; + }else + { + // Convert ASCII string into UTF-16 + + if ( !(index < sizeof(string_desc_arr)/sizeof(string_desc_arr[0])) ) return NULL; + + const char* str = string_desc_arr[index]; + + // Cap at max char + chr_count = strlen(str); + if ( chr_count > 31 ) chr_count = 31; + + for(uint8_t i=0; ibmRequestType_bit.type == TUSB_REQ_TYPE_CLASS); - // TODO Support multiple interfaces - uint8_t const itf = 0; - cdcd_interface_t* p_cdc = &_cdcd_itf[itf]; + uint8_t itf = 0; + cdcd_interface_t* p_cdc = _cdcd_itf; + + // Identify which interface to use + for ( ; ; itf++, p_cdc++) + { + if (itf >= TU_ARRAY_SIZE(_cdcd_itf)) return false; + + if ( p_cdc->itf_num == request->wIndex ) break; + } // Invoke callback if ( CDC_REQUEST_SET_LINE_CODING == request->bRequest ) @@ -314,9 +321,16 @@ bool cdcd_control_request(uint8_t rhport, tusb_control_request_t const * request // Handle class request only TU_VERIFY(request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS); - // TODO Support multiple interfaces - uint8_t const itf = 0; - cdcd_interface_t* p_cdc = &_cdcd_itf[itf]; + uint8_t itf = 0; + cdcd_interface_t* p_cdc = _cdcd_itf; + + // Identify which interface to use + for ( ; ; itf++, p_cdc++) + { + if (itf >= TU_ARRAY_SIZE(_cdcd_itf)) return false; + + if ( p_cdc->itf_num == request->wIndex ) break; + } switch ( request->bRequest ) { @@ -353,9 +367,16 @@ bool cdcd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_ (void) rhport; (void) result; - // TODO Support multiple interfaces - uint8_t const itf = 0; - cdcd_interface_t* p_cdc = &_cdcd_itf[itf]; + uint8_t itf = 0; + cdcd_interface_t* p_cdc = _cdcd_itf; + + // Identify which interface to use + for ( ; ; itf++, p_cdc++) + { + if (itf >= TU_ARRAY_SIZE(_cdcd_itf)) return false; + + if ( ( ep_addr == p_cdc->ep_out ) || ( ep_addr == p_cdc->ep_in ) ) break; + } // Received new data if ( ep_addr == p_cdc->ep_out ) diff --git a/src/class/hid/hid_device.c b/src/class/hid/hid_device.c index 8527fa5d..7cb35f1c 100644 --- a/src/class/hid/hid_device.c +++ b/src/class/hid/hid_device.c @@ -162,9 +162,18 @@ bool hidd_open(uint8_t rhport, tusb_desc_interface_t const * desc_itf, uint16_t { uint8_t const *p_desc = (uint8_t const *) desc_itf; - // TODO support multiple HID interface - uint8_t const itf = 0; - hidd_interface_t * p_hid = &_hidd_itf[itf]; + // Find available interface + hidd_interface_t * p_hid = NULL; + uint8_t hid_id; + for(hid_id=0; hid_id= TU_ARRAY_SIZE(_hidd_itf)) return false; + + if ( ep_addr == p_hid->ep_out ) break; + } if (ep_addr == p_hid->ep_out) { diff --git a/src/class/midi/midi_device.c b/src/class/midi/midi_device.c index b278039b..0c68f8e7 100644 --- a/src/class/midi/midi_device.c +++ b/src/class/midi/midi_device.c @@ -332,9 +332,15 @@ bool midid_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32 { (void) result; - // TODO Support multiple interfaces - uint8_t const itf = 0; - midid_interface_t* p_midi = &_midid_itf[itf]; + uint8_t itf = 0; + midid_interface_t* p_midi = _midid_itf; + + for ( ; ; itf++, p_midi++) + { + if (itf >= TU_ARRAY_SIZE(_midid_itf)) return false; + + if ( ep_addr == p_midi->ep_out ) break; + } // receive new data if ( ep_addr == p_midi->ep_out ) diff --git a/src/class/vendor/vendor_device.c b/src/class/vendor/vendor_device.c index a0025747..8db5005f 100644 --- a/src/class/vendor/vendor_device.c +++ b/src/class/vendor/vendor_device.c @@ -197,9 +197,15 @@ bool vendord_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint (void) rhport; (void) result; - // TODO Support multiple interfaces - uint8_t const itf = 0; - vendord_interface_t* p_itf = &_vendord_itf[itf]; + uint8_t itf = 0; + vendord_interface_t* p_itf = _vendord_itf; + + for ( ; ; itf++, p_itf++) + { + if (itf >= TU_ARRAY_SIZE(_vendord_itf)) return false; + + if ( ( ep_addr == p_itf->ep_out ) || ( ep_addr == p_itf->ep_in ) ) break; + } if ( ep_addr == p_itf->ep_out ) { From e7bf66b29e00e725d80ea3bab5a747a2e7b23bfa Mon Sep 17 00:00:00 2001 From: Peter Lawrence <12226419+majbthrd@users.noreply.github.com> Date: Sat, 28 Dec 2019 16:49:52 -0600 Subject: [PATCH 176/267] gracefully handle multiple SET_CONFIGURATION requests --- src/device/usbd.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/device/usbd.c b/src/device/usbd.c index 1797dfaf..84f38301 100644 --- a/src/device/usbd.c +++ b/src/device/usbd.c @@ -518,9 +518,11 @@ static bool process_control_request(uint8_t rhport, tusb_control_request_t const uint8_t const cfg_num = (uint8_t) p_request->wValue; dcd_set_config(rhport, cfg_num); + + if ( !_usbd_dev.configured && cfg_num ) TU_ASSERT( process_set_config(rhport, cfg_num) ); + _usbd_dev.configured = cfg_num ? 1 : 0; - if ( cfg_num ) TU_ASSERT( process_set_config(rhport, cfg_num) ); tud_control_status(rhport, p_request); } break; From db24b2f3728cc29af5b2688f9cd7ab0b4b3f22b5 Mon Sep 17 00:00:00 2001 From: Jeremy Herbert Date: Mon, 30 Dec 2019 13:58:06 +1000 Subject: [PATCH 177/267] Let device respond to endpoint requests on EP0 (#251) Since endpoint 0 is used for control requests, it doesn't have a class driver attached to it. As such, the corresponding `_usbd_dev.ep2drv` entry points to driver `0xFF`, which is invalid and this makes the `TU_ASSERT(drvid < USBD_CLASS_DRIVER_COUNT);` line fail, and eventually causes an endpoint stall. So as-is the stack cannot respond to any endpoint requests on endpoint 0. However, standard requests on endpoint 0 do not need a class driver to produce a valid response. This commit changes the order of execution so that the assert is only checked if the endpoint is not 0. --- src/device/usbd.c | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/src/device/usbd.c b/src/device/usbd.c index 949e1409..b63d4202 100644 --- a/src/device/usbd.c +++ b/src/device/usbd.c @@ -618,7 +618,6 @@ static bool process_control_request(uint8_t rhport, tusb_control_request_t const TU_ASSERT(ep_num < TU_ARRAY_SIZE(_usbd_dev.ep2drv) ); uint8_t const drvid = _usbd_dev.ep2drv[ep_num][ep_dir]; - TU_ASSERT(drvid < USBD_CLASS_DRIVER_COUNT); bool ret = false; @@ -658,13 +657,17 @@ static bool process_control_request(uint8_t rhport, tusb_control_request_t const } } - // Some classes such as USBTMC needs to clear/re-init its buffer when receiving CLEAR_FEATURE request - // We will forward all request targeted endpoint to class drivers after - // - For class-type requests: driver is fully responsible to reply to host - // - For std-type requests : driver init/re-init internal variable/buffer only, and - // must not call tud_control_status(), driver's return value will have no effect. - // EP state has already affected (stalled/cleared) - if ( invoke_class_control(rhport, drvid, p_request) ) ret = true; + if (drvid < 0xFF) { + TU_ASSERT(drvid < USBD_CLASS_DRIVER_COUNT); + + // Some classes such as USBTMC needs to clear/re-init its buffer when receiving CLEAR_FEATURE request + // We will forward all request targeted endpoint to class drivers after + // - For class-type requests: driver is fully responsible to reply to host + // - For std-type requests : driver init/re-init internal variable/buffer only, and + // must not call tud_control_status(), driver's return value will have no effect. + // EP state has already affected (stalled/cleared) + if ( invoke_class_control(rhport, drvid, p_request) ) ret = true; + } if ( TUSB_REQ_TYPE_STANDARD == p_request->bmRequestType_bit.type ) { From 6b3eb5f17386d21b2b9f0bad2d1c06b73f07cb5f Mon Sep 17 00:00:00 2001 From: majbthrd Date: Mon, 30 Dec 2019 10:12:18 -0600 Subject: [PATCH 178/267] fix missing parentheses in TU_MIN and TU_MAX macros (#256) --- src/common/tusb_common.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/common/tusb_common.h b/src/common/tusb_common.h index 5700c128..839989c9 100644 --- a/src/common/tusb_common.h +++ b/src/common/tusb_common.h @@ -39,8 +39,8 @@ // Macros Helper //--------------------------------------------------------------------+ #define TU_ARRAY_SIZE(_arr) ( sizeof(_arr) / sizeof(_arr[0]) ) -#define TU_MIN(_x, _y) ( (_x) < (_y) ) ? (_x) : (_y) ) -#define TU_MAX(_x, _y) ( (_x) > (_y) ) ? (_x) : (_y) ) +#define TU_MIN(_x, _y) ( ( (_x) < (_y) ) ? (_x) : (_y) ) +#define TU_MAX(_x, _y) ( ( (_x) > (_y) ) ? (_x) : (_y) ) #define TU_U16_HIGH(u16) ((uint8_t) (((u16) >> 8) & 0x00ff)) #define TU_U16_LOW(u16) ((uint8_t) ((u16) & 0x00ff)) From e06f4a3ffef4a55db1e583f24483d1ce6daa5ec8 Mon Sep 17 00:00:00 2001 From: Greg Steiert Date: Mon, 30 Dec 2019 09:11:52 -0800 Subject: [PATCH 179/267] fixed build issue with i.MXRT1010-EVK, corrected typo in examples/readme --- examples/readme.md | 2 +- hw/bsp/mimxrt1010_evk/board.mk | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/examples/readme.md b/examples/readme.md index dc4c563d..897931b0 100644 --- a/examples/readme.md +++ b/examples/readme.md @@ -12,7 +12,7 @@ $ cd tinyusb TinyUSB examples includes external repos aka submodules to provide low-level MCU peripheral's driver to compile with. Therefore we will firstly fetch those mcu driver repo by running this command in the top folder repo ``` -$ git submodule update --init --rescursive +$ git submodule update --init --recursive ``` It will takes a bit of time due to the number of supported MCUs, luckily we only need to do this once. diff --git a/hw/bsp/mimxrt1010_evk/board.mk b/hw/bsp/mimxrt1010_evk/board.mk index 24a3dbdc..7b61cb24 100644 --- a/hw/bsp/mimxrt1010_evk/board.mk +++ b/hw/bsp/mimxrt1010_evk/board.mk @@ -11,7 +11,8 @@ CFLAGS += \ -DCFG_TUSB_MCU=OPT_MCU_MIMXRT10XX # mcu driver cause following warnings -CFLAGS += -Wno-error=unused-parameter -Wno-error=implicit-fallthrough= +# CFLAGS += -Wno-error=unused-parameter -Wno-error=implicit-fallthrough= +CFLAGS += -Wno-error=unused-parameter MCU_DIR = hw/mcu/nxp/sdk/devices/MIMXRT1011 From 019d1b09c5fcaa601af6e0a2aba882031bcbd3c7 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 3 Jan 2020 17:11:22 +0700 Subject: [PATCH 180/267] try to trigger mynewt example --- .github/workflows/build.yml | 8 ++++++++ README.md | 2 +- tools/build_all.py | 10 ---------- 3 files changed, 9 insertions(+), 11 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 6e71351a..fbbea9e1 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -52,3 +52,11 @@ jobs: - name: Build run: python3 tools/build_all.py ${{ matrix.example }} + + trigger-mynewt: + runs-on: ubuntu-latest + needs: build + steps: + - name: Trigger mynewt-tinyusb-example + - run: curl -XPOST -u "hathach:${{secrets.MYNEWT_EXAMPLE_TOKEN}}" -H "Accept: application/vnd.github.everest-preview+json" -H "Content-Type: application/json" https://api.github.com/repos/hathach/mynewt-tinyusb-example/dispatches --data '{"event_type": "build_application"}' + diff --git a/README.md b/README.md index eccb7627..75d35400 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ ![tinyUSB_240x100](https://user-images.githubusercontent.com/249515/62646655-f9393200-b978-11e9-9c53-484862f15503.png) -[![Build Status](https://github.com/hathach/tinyusb/workflows/Build/badge.svg)](https://travis-ci.org/hathach/tinyusb) [![License](https://img.shields.io/badge/license-MIT-brightgreen.svg)](https://opensource.org/licenses/MIT) [![Coverity](https://img.shields.io/coverity/scan/458.svg)](https://scan.coverity.com/projects/tinyusb) +[![Build Status](https://github.com/hathach/tinyusb/workflows/Build/badge.svg)](https://github.com/hathach/tinyusb/actions) [![License](https://img.shields.io/badge/license-MIT-brightgreen.svg)](https://opensource.org/licenses/MIT) [![Coverity](https://img.shields.io/coverity/scan/458.svg)](https://scan.coverity.com/projects/tinyusb) TinyUSB is an open-source cross-platform USB Host/Device stack for embedded system, designed to be memory-safe with no dynamic allocation and thread-safe with all interrupt events are deferred then handled in the non-ISR task function. diff --git a/tools/build_all.py b/tools/build_all.py index 2ea898f4..97294a9a 100644 --- a/tools/build_all.py +++ b/tools/build_all.py @@ -4,10 +4,6 @@ import sys import subprocess import time -travis = False -if "TRAVIS" in os.environ and os.environ["TRAVIS"] == "true": - travis = True - success_count = 0 fail_count = 0 exit_status = 0 @@ -59,16 +55,10 @@ for example in all_examples: success = "\033[31mfailed\033[0m " fail_count += 1 - if travis: - print('travis_fold:start:build-{}-{}\\r'.format(example, board)) - print((build_format + '| {:.2f}s |').format(example, board, success, build_duration)) if build_result.returncode != 0: print(build_result.stdout.decode("utf-8")) - if travis: - print('travis_fold:end:build-{}-{}\\r'.format(example, board)) - # FreeRTOS example # example = 'cdc_msc_hid_freertos' # board = 'pca10056' From 2cbd0cdf5046201428b255c942ce760ac859d172 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 3 Jan 2020 17:19:23 +0700 Subject: [PATCH 181/267] change to token --- .github/workflows/build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index fbbea9e1..f7dddfc8 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -58,5 +58,5 @@ jobs: needs: build steps: - name: Trigger mynewt-tinyusb-example - - run: curl -XPOST -u "hathach:${{secrets.MYNEWT_EXAMPLE_TOKEN}}" -H "Accept: application/vnd.github.everest-preview+json" -H "Content-Type: application/json" https://api.github.com/repos/hathach/mynewt-tinyusb-example/dispatches --data '{"event_type": "build_application"}' + - run: curl -X POST -H "Authorization: token ${{ secrets.MYNEWT_EXAMPLE_TOKEN }}" -H "Accept: application/vnd.github.everest-preview+json" -H "Content-Type: application/json" https://api.github.com/repos/hathach/mynewt-tinyusb-example/dispatches --data '{"event_type": "build_application"}' From 4282a0d96aef028f0557de18aa022ea84829d155 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 3 Jan 2020 17:37:10 +0700 Subject: [PATCH 182/267] curl again --- .github/workflows/build.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index f7dddfc8..d27896f7 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -58,5 +58,5 @@ jobs: needs: build steps: - name: Trigger mynewt-tinyusb-example - - run: curl -X POST -H "Authorization: token ${{ secrets.MYNEWT_EXAMPLE_TOKEN }}" -H "Accept: application/vnd.github.everest-preview+json" -H "Content-Type: application/json" https://api.github.com/repos/hathach/mynewt-tinyusb-example/dispatches --data '{"event_type": "build_application"}' - + shell: bash + run: curl -X POST -H "Authorization: token ${{ secrets.MYNEWT_EXAMPLE_TOKEN }}" -H "Accept: application/vnd.github.everest-preview+json" -H "Content-Type: application/json" --data '{"event_type": "rebuild"}' https://api.github.com/repos/hathach/mynewt-tinyusb-example/dispatches From 6f03617ff56a4c057bbf846500f2c33cbe1d6d1d Mon Sep 17 00:00:00 2001 From: hathach Date: Sat, 4 Jan 2020 00:12:03 +0700 Subject: [PATCH 183/267] curl --- .github/workflows/build.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index d27896f7..1e41d600 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -59,4 +59,5 @@ jobs: steps: - name: Trigger mynewt-tinyusb-example shell: bash - run: curl -X POST -H "Authorization: token ${{ secrets.MYNEWT_EXAMPLE_TOKEN }}" -H "Accept: application/vnd.github.everest-preview+json" -H "Content-Type: application/json" --data '{"event_type": "rebuild"}' https://api.github.com/repos/hathach/mynewt-tinyusb-example/dispatches + run: | + curl -X POST -H "Authorization: token ${{ secrets.MYNEWT_EXAMPLE_TOKEN }}" -H "Accept: application/vnd.github.everest-preview+json" -H "Content-Type: application/json" --data '{"event_type": "rebuild"}' https://api.github.com/repos/hathach/mynewt-tinyusb-example/dispatches From 3362a4b09dac481cc47ae54446026fa211c4d914 Mon Sep 17 00:00:00 2001 From: hathach Date: Sat, 4 Jan 2020 14:24:21 +0700 Subject: [PATCH 184/267] change token name --- .github/workflows/build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 1e41d600..2ac5b2ba 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -60,4 +60,4 @@ jobs: - name: Trigger mynewt-tinyusb-example shell: bash run: | - curl -X POST -H "Authorization: token ${{ secrets.MYNEWT_EXAMPLE_TOKEN }}" -H "Accept: application/vnd.github.everest-preview+json" -H "Content-Type: application/json" --data '{"event_type": "rebuild"}' https://api.github.com/repos/hathach/mynewt-tinyusb-example/dispatches + curl -X POST -H "Authorization: token ${{ secrets.GH_REPO_TOKEN }}" -H "Accept: application/vnd.github.everest-preview+json" -H "Content-Type: application/json" --data '{"event_type": "rebuild"}' https://api.github.com/repos/hathach/mynewt-tinyusb-example/dispatches From f4371e79b10f85b0f8f6112c8e81b92072bacea0 Mon Sep 17 00:00:00 2001 From: Peter Lawrence <12226419+majbthrd@users.noreply.github.com> Date: Sat, 4 Jan 2020 10:31:55 -0600 Subject: [PATCH 185/267] add Nuvoton NUC121/NUC125/NUC126 --- .gitmodules | 3 + README.md | 1 + hw/bsp/nutiny_nuc121s/board.mk | 54 +++ hw/bsp/nutiny_nuc121s/nuc121_flash.ld | 195 ++++++++++ hw/bsp/nutiny_nuc121s/nutiny_nuc121.c | 102 ++++++ hw/bsp/nutiny_nuc125s/board.mk | 37 ++ hw/bsp/nutiny_nuc125s/nuc125_flash.ld | 195 ++++++++++ hw/bsp/nutiny_nuc125s/nutiny_nuc125.c | 102 ++++++ hw/bsp/nutiny_nuc126v/board.mk | 61 ++++ hw/bsp/nutiny_nuc126v/nuc126_flash.ld | 195 ++++++++++ hw/bsp/nutiny_nuc126v/nutiny_nuc126.c | 133 +++++++ hw/mcu/nuvoton | 1 + src/portable/nuvoton/nuc121/dcd_nuc121.c | 434 +++++++++++++++++++++++ src/tusb_option.h | 3 + 14 files changed, 1516 insertions(+) create mode 100644 hw/bsp/nutiny_nuc121s/board.mk create mode 100644 hw/bsp/nutiny_nuc121s/nuc121_flash.ld create mode 100644 hw/bsp/nutiny_nuc121s/nutiny_nuc121.c create mode 100644 hw/bsp/nutiny_nuc125s/board.mk create mode 100644 hw/bsp/nutiny_nuc125s/nuc125_flash.ld create mode 100644 hw/bsp/nutiny_nuc125s/nutiny_nuc125.c create mode 100644 hw/bsp/nutiny_nuc126v/board.mk create mode 100644 hw/bsp/nutiny_nuc126v/nuc126_flash.ld create mode 100644 hw/bsp/nutiny_nuc126v/nutiny_nuc126.c create mode 160000 hw/mcu/nuvoton create mode 100644 src/portable/nuvoton/nuc121/dcd_nuc121.c diff --git a/.gitmodules b/.gitmodules index c7b39618..7565f199 100644 --- a/.gitmodules +++ b/.gitmodules @@ -19,3 +19,6 @@ [submodule "hw/mcu/nxp"] path = hw/mcu/nxp url = https://github.com/hathach/nxp_driver.git +[submodule "hw/mcu/nuvoton"] + path = hw/mcu/nuvoton + url = https://github.com/majbthrd/nuc_driver.git diff --git a/README.md b/README.md index 3f7556cf..f06b5c41 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,7 @@ The stack supports the following MCUs - **Sony:** CXD56 - **ST:** STM32 series: L0, F0, F1, F2, F3, F4, F7, H7 (device only) - **[ValentyUSB](https://github.com/im-tomu/valentyusb)** eptri +- **Nuvoton:** NUC121/NUC125, NUC126 [Here is the list of supported Boards](docs/boards.md) that can be used with provided examples. diff --git a/hw/bsp/nutiny_nuc121s/board.mk b/hw/bsp/nutiny_nuc121s/board.mk new file mode 100644 index 00000000..dfd0e80c --- /dev/null +++ b/hw/bsp/nutiny_nuc121s/board.mk @@ -0,0 +1,54 @@ +CFLAGS += \ + -flto \ + -mthumb \ + -mabi=aapcs-linux \ + -mcpu=cortex-m0 \ + -D__ARM_FEATURE_DSP=0 \ + -DUSE_ASSERT=0 \ + -DCFG_TUSB_MCU=OPT_MCU_NUC121 + +# All source paths should be relative to the top level. +LD_FILE = hw/bsp/nutiny_nuc121s/nuc121_flash.ld + +SRC_C += \ + hw/mcu/nuvoton/nuc121_125/Device/Nuvoton/NUC121/Source/system_NUC121.c \ + hw/mcu/nuvoton/nuc121_125/StdDriver/src/adc.c \ + hw/mcu/nuvoton/nuc121_125/StdDriver/src/bpwm.c \ + hw/mcu/nuvoton/nuc121_125/StdDriver/src/clk.c \ + hw/mcu/nuvoton/nuc121_125/StdDriver/src/fmc.c \ + hw/mcu/nuvoton/nuc121_125/StdDriver/src/gpio.c \ + hw/mcu/nuvoton/nuc121_125/StdDriver/src/i2c.c \ + hw/mcu/nuvoton/nuc121_125/StdDriver/src/pdma.c \ + hw/mcu/nuvoton/nuc121_125/StdDriver/src/pwm.c \ + hw/mcu/nuvoton/nuc121_125/StdDriver/src/spi_i2s.c \ + hw/mcu/nuvoton/nuc121_125/StdDriver/src/sys.c \ + hw/mcu/nuvoton/nuc121_125/StdDriver/src/timer.c \ + hw/mcu/nuvoton/nuc121_125/StdDriver/src/uart.c \ + hw/mcu/nuvoton/nuc121_125/StdDriver/src/usbd.c \ + hw/mcu/nuvoton/nuc121_125/StdDriver/src/usci_i2c.c \ + hw/mcu/nuvoton/nuc121_125/StdDriver/src/usci_spi.c \ + hw/mcu/nuvoton/nuc121_125/StdDriver/src/usci_uart.c \ + hw/mcu/nuvoton/nuc121_125/StdDriver/src/wdt.c \ + hw/mcu/nuvoton/nuc121_125/StdDriver/src/wwdt.c + +SRC_S += \ + hw/mcu/nuvoton/nuc121_125/Device/Nuvoton/NUC121/Source/GCC/startup_NUC121.S + +INC += \ + $(TOP)/hw/mcu/nuvoton/nuc121_125/Device/Nuvoton/NUC121/Include \ + $(TOP)/hw/mcu/nuvoton/nuc121_125/StdDriver/inc \ + $(TOP)/hw/mcu/nuvoton/nuc121_125/CMSIS/Include + +# For TinyUSB port source +VENDOR = nuvoton +CHIP_FAMILY = nuc121 + +# For freeRTOS port source +FREERTOS_PORT = ARM_CM0 + +# For flash-jlink target +JLINK_DEVICE = NUC121SC2AE +JLINK_IF = swd + +# flash using jlink +flash: flash-jlink diff --git a/hw/bsp/nutiny_nuc121s/nuc121_flash.ld b/hw/bsp/nutiny_nuc121s/nuc121_flash.ld new file mode 100644 index 00000000..3966b276 --- /dev/null +++ b/hw/bsp/nutiny_nuc121s/nuc121_flash.ld @@ -0,0 +1,195 @@ +/* Linker script to configure memory regions. */ +MEMORY +{ + FLASH (rx) : ORIGIN = 0x00000000, LENGTH = 0x8000 /* 32k */ + RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 0x2000 /* 8k */ +} + +/* Library configurations */ +GROUP(libgcc.a libc.a libm.a libnosys.a) + +/* 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 + * __copy_table_start__ + * __copy_table_end__ + * __zero_table_start__ + * __zero_table_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 + * __Vectors_End + * __Vectors_Size + */ +ENTRY(Reset_Handler) + +SECTIONS +{ + .text : + { + KEEP(*(.vectors)) + __Vectors_End = .; + __Vectors_Size = __Vectors_End - __Vectors; + __end__ = .; + + *(.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 = .; + + /* To copy multiple ROM to RAM sections, + * uncomment .copy.table section and, + * define __STARTUP_COPY_MULTIPLE in startup_ARMCMx.S */ + /* + .copy.table : + { + . = ALIGN(4); + __copy_table_start__ = .; + LONG (__etext) + LONG (__data_start__) + LONG (__data_end__ - __data_start__) + LONG (__etext2) + LONG (__data2_start__) + LONG (__data2_end__ - __data2_start__) + __copy_table_end__ = .; + } > FLASH + */ + + /* To clear multiple BSS sections, + * uncomment .zero.table section and, + * define __STARTUP_CLEAR_BSS_MULTIPLE in startup_ARMCMx.S */ + /* + .zero.table : + { + . = ALIGN(4); + __zero_table_start__ = .; + LONG (__bss_start__) + LONG (__bss_end__ - __bss_start__) + LONG (__bss2_start__) + LONG (__bss2_end__ - __bss2_start__) + __zero_table_end__ = .; + } > FLASH + */ + + __etext = .; + + .data : AT (__etext) + { + __data_start__ = .; + *(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__ = .; + + } > RAM + + .bss : + { + . = ALIGN(4); + __bss_start__ = .; + *(.bss*) + *(COMMON) + . = ALIGN(4); + __bss_end__ = .; + } > RAM + + .heap (COPY): + { + __HeapBase = .; + __end__ = .; + end = __end__; + KEEP(*(.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): + { + KEEP(*(.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); + __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/hw/bsp/nutiny_nuc121s/nutiny_nuc121.c b/hw/bsp/nutiny_nuc121s/nutiny_nuc121.c new file mode 100644 index 00000000..51ca28a8 --- /dev/null +++ b/hw/bsp/nutiny_nuc121s/nutiny_nuc121.c @@ -0,0 +1,102 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#include "bsp/board.h" +#include "NuMicro.h" +#include "clk.h" +#include "sys.h" + +void board_init(void) +{ + /* Unlock protected registers */ + SYS_UnlockReg(); + + /*---------------------------------------------------------------------------------------------------------*/ + /* Init System Clock */ + /*---------------------------------------------------------------------------------------------------------*/ + + /* Enable Internal HIRC 48 MHz clock */ + CLK_EnableXtalRC(CLK_PWRCTL_HIRCEN); + + /* Waiting for Internal RC clock ready */ + CLK_WaitClockReady(CLK_STATUS_HIRCSTB_Msk); + + /* Switch HCLK clock source to Internal HIRC and HCLK source divide 1 */ + CLK_SetHCLK(CLK_CLKSEL0_HCLKSEL_HIRC, CLK_CLKDIV0_HCLK(1)); + + /* Enable module clock */ + CLK_EnableModuleClock(USBD_MODULE); + + /* Select module clock source */ + CLK_SetModuleClock(USBD_MODULE, CLK_CLKSEL3_USBDSEL_HIRC, CLK_CLKDIV0_USB(1)); + + /* Enable module clock */ + CLK_EnableModuleClock(USBD_MODULE); + +#if CFG_TUSB_OS == OPT_OS_NONE + // 1ms tick timer + SysTick_Config(48000000 / 1000); +#endif +} + +#if CFG_TUSB_OS == OPT_OS_NONE +volatile uint32_t system_ticks = 0; +void SysTick_Handler (void) +{ + system_ticks++; +} + +uint32_t board_millis(void) +{ + return system_ticks; +} +#endif + +//--------------------------------------------------------------------+ +// Board porting API +//--------------------------------------------------------------------+ + +void board_led_write(bool state) +{ + (void)(state); +} + +uint32_t board_button_read(void) +{ + return 0; +} + +int board_uart_read(uint8_t* buf, int len) +{ + (void) buf; (void) len; + return 0; +} + +int board_uart_write(void const * buf, int len) +{ + (void) buf; (void) len; + return 0; +} diff --git a/hw/bsp/nutiny_nuc125s/board.mk b/hw/bsp/nutiny_nuc125s/board.mk new file mode 100644 index 00000000..8e4d78ce --- /dev/null +++ b/hw/bsp/nutiny_nuc125s/board.mk @@ -0,0 +1,37 @@ +CFLAGS += \ + -flto \ + -mthumb \ + -mabi=aapcs-linux \ + -mcpu=cortex-m0 \ + -D__ARM_FEATURE_DSP=0 \ + -DUSE_ASSERT=0 \ + -DCFG_TUSB_MCU=OPT_MCU_NUC121 + +# All source paths should be relative to the top level. +LD_FILE = hw/bsp/nutiny_nuc125s/nuc125_flash.ld + +SRC_C += \ + hw/mcu/nuvoton/nuc121_125/Device/Nuvoton/NUC121/Source/system_NUC121.c \ + hw/mcu/nuvoton/nuc121_125/StdDriver/src/clk.c + +SRC_S += \ + hw/mcu/nuvoton/nuc121_125/Device/Nuvoton/NUC121/Source/GCC/startup_NUC121.S + +INC += \ + $(TOP)/hw/mcu/nuvoton/nuc121_125/Device/Nuvoton/NUC121/Include \ + $(TOP)/hw/mcu/nuvoton/nuc121_125/StdDriver/inc \ + $(TOP)/hw/mcu/nuvoton/nuc121_125/CMSIS/Include + +# For TinyUSB port source +VENDOR = nuvoton +CHIP_FAMILY = nuc121 + +# For freeRTOS port source +FREERTOS_PORT = ARM_CM0 + +# For flash-jlink target +JLINK_DEVICE = NUC125SC2AE +JLINK_IF = swd + +# flash using jlink +flash: flash-jlink diff --git a/hw/bsp/nutiny_nuc125s/nuc125_flash.ld b/hw/bsp/nutiny_nuc125s/nuc125_flash.ld new file mode 100644 index 00000000..3966b276 --- /dev/null +++ b/hw/bsp/nutiny_nuc125s/nuc125_flash.ld @@ -0,0 +1,195 @@ +/* Linker script to configure memory regions. */ +MEMORY +{ + FLASH (rx) : ORIGIN = 0x00000000, LENGTH = 0x8000 /* 32k */ + RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 0x2000 /* 8k */ +} + +/* Library configurations */ +GROUP(libgcc.a libc.a libm.a libnosys.a) + +/* 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 + * __copy_table_start__ + * __copy_table_end__ + * __zero_table_start__ + * __zero_table_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 + * __Vectors_End + * __Vectors_Size + */ +ENTRY(Reset_Handler) + +SECTIONS +{ + .text : + { + KEEP(*(.vectors)) + __Vectors_End = .; + __Vectors_Size = __Vectors_End - __Vectors; + __end__ = .; + + *(.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 = .; + + /* To copy multiple ROM to RAM sections, + * uncomment .copy.table section and, + * define __STARTUP_COPY_MULTIPLE in startup_ARMCMx.S */ + /* + .copy.table : + { + . = ALIGN(4); + __copy_table_start__ = .; + LONG (__etext) + LONG (__data_start__) + LONG (__data_end__ - __data_start__) + LONG (__etext2) + LONG (__data2_start__) + LONG (__data2_end__ - __data2_start__) + __copy_table_end__ = .; + } > FLASH + */ + + /* To clear multiple BSS sections, + * uncomment .zero.table section and, + * define __STARTUP_CLEAR_BSS_MULTIPLE in startup_ARMCMx.S */ + /* + .zero.table : + { + . = ALIGN(4); + __zero_table_start__ = .; + LONG (__bss_start__) + LONG (__bss_end__ - __bss_start__) + LONG (__bss2_start__) + LONG (__bss2_end__ - __bss2_start__) + __zero_table_end__ = .; + } > FLASH + */ + + __etext = .; + + .data : AT (__etext) + { + __data_start__ = .; + *(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__ = .; + + } > RAM + + .bss : + { + . = ALIGN(4); + __bss_start__ = .; + *(.bss*) + *(COMMON) + . = ALIGN(4); + __bss_end__ = .; + } > RAM + + .heap (COPY): + { + __HeapBase = .; + __end__ = .; + end = __end__; + KEEP(*(.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): + { + KEEP(*(.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); + __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/hw/bsp/nutiny_nuc125s/nutiny_nuc125.c b/hw/bsp/nutiny_nuc125s/nutiny_nuc125.c new file mode 100644 index 00000000..51ca28a8 --- /dev/null +++ b/hw/bsp/nutiny_nuc125s/nutiny_nuc125.c @@ -0,0 +1,102 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#include "bsp/board.h" +#include "NuMicro.h" +#include "clk.h" +#include "sys.h" + +void board_init(void) +{ + /* Unlock protected registers */ + SYS_UnlockReg(); + + /*---------------------------------------------------------------------------------------------------------*/ + /* Init System Clock */ + /*---------------------------------------------------------------------------------------------------------*/ + + /* Enable Internal HIRC 48 MHz clock */ + CLK_EnableXtalRC(CLK_PWRCTL_HIRCEN); + + /* Waiting for Internal RC clock ready */ + CLK_WaitClockReady(CLK_STATUS_HIRCSTB_Msk); + + /* Switch HCLK clock source to Internal HIRC and HCLK source divide 1 */ + CLK_SetHCLK(CLK_CLKSEL0_HCLKSEL_HIRC, CLK_CLKDIV0_HCLK(1)); + + /* Enable module clock */ + CLK_EnableModuleClock(USBD_MODULE); + + /* Select module clock source */ + CLK_SetModuleClock(USBD_MODULE, CLK_CLKSEL3_USBDSEL_HIRC, CLK_CLKDIV0_USB(1)); + + /* Enable module clock */ + CLK_EnableModuleClock(USBD_MODULE); + +#if CFG_TUSB_OS == OPT_OS_NONE + // 1ms tick timer + SysTick_Config(48000000 / 1000); +#endif +} + +#if CFG_TUSB_OS == OPT_OS_NONE +volatile uint32_t system_ticks = 0; +void SysTick_Handler (void) +{ + system_ticks++; +} + +uint32_t board_millis(void) +{ + return system_ticks; +} +#endif + +//--------------------------------------------------------------------+ +// Board porting API +//--------------------------------------------------------------------+ + +void board_led_write(bool state) +{ + (void)(state); +} + +uint32_t board_button_read(void) +{ + return 0; +} + +int board_uart_read(uint8_t* buf, int len) +{ + (void) buf; (void) len; + return 0; +} + +int board_uart_write(void const * buf, int len) +{ + (void) buf; (void) len; + return 0; +} diff --git a/hw/bsp/nutiny_nuc126v/board.mk b/hw/bsp/nutiny_nuc126v/board.mk new file mode 100644 index 00000000..6d87c9d9 --- /dev/null +++ b/hw/bsp/nutiny_nuc126v/board.mk @@ -0,0 +1,61 @@ +CFLAGS += \ + -flto \ + -mthumb \ + -mabi=aapcs-linux \ + -mcpu=cortex-m0 \ + -D__ARM_FEATURE_DSP=0 \ + -DUSE_ASSERT=0 \ + -D__CORTEX_SC=0 \ + -DCFG_TUSB_MCU=OPT_MCU_NUC126 + +# All source paths should be relative to the top level. +LD_FILE = hw/bsp/nutiny_nuc126v/nuc126_flash.ld + +SRC_C += \ + hw/mcu/nuvoton/nuc126/Device/Nuvoton/NUC126/Source/system_NUC126.c \ + hw/mcu/nuvoton/nuc126/StdDriver/src/acmp.c \ + hw/mcu/nuvoton/nuc126/StdDriver/src/adc.c \ + hw/mcu/nuvoton/nuc126/StdDriver/src/clk.c \ + hw/mcu/nuvoton/nuc126/StdDriver/src/crc.c \ + hw/mcu/nuvoton/nuc126/StdDriver/src/ebi.c \ + hw/mcu/nuvoton/nuc126/StdDriver/src/fmc.c \ + hw/mcu/nuvoton/nuc126/StdDriver/src/gpio.c \ + hw/mcu/nuvoton/nuc126/StdDriver/src/i2c.c \ + hw/mcu/nuvoton/nuc126/StdDriver/src/pdma.c \ + hw/mcu/nuvoton/nuc126/StdDriver/src/pwm.c \ + hw/mcu/nuvoton/nuc126/StdDriver/src/rtc.c \ + hw/mcu/nuvoton/nuc126/StdDriver/src/sc.c \ + hw/mcu/nuvoton/nuc126/StdDriver/src/scuart.c \ + hw/mcu/nuvoton/nuc126/StdDriver/src/spi.c \ + hw/mcu/nuvoton/nuc126/StdDriver/src/sys.c \ + hw/mcu/nuvoton/nuc126/StdDriver/src/timer.c \ + hw/mcu/nuvoton/nuc126/StdDriver/src/timer_pwm.c \ + hw/mcu/nuvoton/nuc126/StdDriver/src/uart.c \ + hw/mcu/nuvoton/nuc126/StdDriver/src/usbd.c \ + hw/mcu/nuvoton/nuc126/StdDriver/src/usci_i2c.c \ + hw/mcu/nuvoton/nuc126/StdDriver/src/usci_spi.c \ + hw/mcu/nuvoton/nuc126/StdDriver/src/usci_uart.c \ + hw/mcu/nuvoton/nuc126/StdDriver/src/wdt.c \ + hw/mcu/nuvoton/nuc126/StdDriver/src/wwdt.c + +SRC_S += \ + hw/mcu/nuvoton/nuc126/Device/Nuvoton/NUC126/Source/GCC/startup_NUC126.S + +INC += \ + $(TOP)/hw/mcu/nuvoton/nuc126/Device/Nuvoton/NUC126/Include \ + $(TOP)/hw/mcu/nuvoton/nuc126/StdDriver/inc \ + $(TOP)/hw/mcu/nuvoton/nuc126/CMSIS/Include + +# For TinyUSB port source +VENDOR = nuvoton +CHIP_FAMILY = nuc121 + +# For freeRTOS port source +FREERTOS_PORT = ARM_CM0 + +# For flash-jlink target +JLINK_DEVICE = NUC126VG4AE +JLINK_IF = swd + +# flash using jlink +flash: flash-jlink diff --git a/hw/bsp/nutiny_nuc126v/nuc126_flash.ld b/hw/bsp/nutiny_nuc126v/nuc126_flash.ld new file mode 100644 index 00000000..b23890b4 --- /dev/null +++ b/hw/bsp/nutiny_nuc126v/nuc126_flash.ld @@ -0,0 +1,195 @@ +/* Linker script to configure memory regions. */ +MEMORY +{ + FLASH (rx) : ORIGIN = 0x00000000, LENGTH = 0x40000 /* 256k */ + RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 0x5000 /* 20k */ +} + +/* Library configurations */ +GROUP(libgcc.a libc.a libm.a libnosys.a) + +/* 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 + * __copy_table_start__ + * __copy_table_end__ + * __zero_table_start__ + * __zero_table_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 + * __Vectors_End + * __Vectors_Size + */ +ENTRY(Reset_Handler) + +SECTIONS +{ + .text : + { + KEEP(*(.vectors)) + __Vectors_End = .; + __Vectors_Size = __Vectors_End - __Vectors; + __end__ = .; + + *(.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 = .; + + /* To copy multiple ROM to RAM sections, + * uncomment .copy.table section and, + * define __STARTUP_COPY_MULTIPLE in startup_ARMCMx.S */ + /* + .copy.table : + { + . = ALIGN(4); + __copy_table_start__ = .; + LONG (__etext) + LONG (__data_start__) + LONG (__data_end__ - __data_start__) + LONG (__etext2) + LONG (__data2_start__) + LONG (__data2_end__ - __data2_start__) + __copy_table_end__ = .; + } > FLASH + */ + + /* To clear multiple BSS sections, + * uncomment .zero.table section and, + * define __STARTUP_CLEAR_BSS_MULTIPLE in startup_ARMCMx.S */ + /* + .zero.table : + { + . = ALIGN(4); + __zero_table_start__ = .; + LONG (__bss_start__) + LONG (__bss_end__ - __bss_start__) + LONG (__bss2_start__) + LONG (__bss2_end__ - __bss2_start__) + __zero_table_end__ = .; + } > FLASH + */ + + __etext = .; + + .data : AT (__etext) + { + __data_start__ = .; + *(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__ = .; + + } > RAM + + .bss : + { + . = ALIGN(4); + __bss_start__ = .; + *(.bss*) + *(COMMON) + . = ALIGN(4); + __bss_end__ = .; + } > RAM + + .heap (COPY): + { + __HeapBase = .; + __end__ = .; + end = __end__; + KEEP(*(.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): + { + KEEP(*(.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); + __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/hw/bsp/nutiny_nuc126v/nutiny_nuc126.c b/hw/bsp/nutiny_nuc126v/nutiny_nuc126.c new file mode 100644 index 00000000..0ce787d3 --- /dev/null +++ b/hw/bsp/nutiny_nuc126v/nutiny_nuc126.c @@ -0,0 +1,133 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#include "bsp/board.h" +#include "NuMicro.h" +#include "clk.h" +#include "sys.h" + +#define CRYSTAL_LESS /* system will be 48MHz when defined, otherwise, system is 72MHz */ +#define HIRC48_AUTO_TRIM SYS_IRCTCTL1_REFCKSEL_Msk | (1UL << SYS_IRCTCTL1_LOOPSEL_Pos) | (2UL << SYS_IRCTCTL1_FREQSEL_Pos) +#define TRIM_INIT (SYS_BASE+0x118) + +void board_init(void) +{ + /* Unlock protected registers */ + SYS_UnlockReg(); + + /*---------------------------------------------------------------------------------------------------------*/ + /* Init System Clock */ + /*---------------------------------------------------------------------------------------------------------*/ + + /* Enable Internal RC 22.1184 MHz clock */ + CLK_EnableXtalRC(CLK_PWRCTL_HIRCEN_Msk); + + /* Waiting for Internal RC clock ready */ + CLK_WaitClockReady(CLK_STATUS_HIRCSTB_Msk); + + /* Switch HCLK clock source to Internal RC and HCLK source divide 1 */ + CLK_SetHCLK(CLK_CLKSEL0_HCLKSEL_HIRC, CLK_CLKDIV0_HCLK(1)); + +#ifndef CRYSTAL_LESS + /* Enable external XTAL 12 MHz clock */ + CLK_EnableXtalRC(CLK_PWRCTL_HXTEN_Msk); + + /* Waiting for external XTAL clock ready */ + CLK_WaitClockReady(CLK_STATUS_HXTSTB_Msk); + + /* Set core clock */ + CLK_SetCoreClock(72000000); + + /* Use HIRC as UART clock source */ + CLK_SetModuleClock(UART0_MODULE, CLK_CLKSEL1_UARTSEL_HIRC, CLK_CLKDIV0_UART(1)); + + /* Use PLL as USB clock source */ + CLK_SetModuleClock(USBD_MODULE, CLK_CLKSEL3_USBDSEL_PLL, CLK_CLKDIV0_USB(3)); + +#else + /* Enable Internal RC 48MHz clock */ + CLK_EnableXtalRC(CLK_PWRCTL_HIRC48EN_Msk); + + /* Waiting for Internal RC clock ready */ + CLK_WaitClockReady(CLK_STATUS_HIRC48STB_Msk); + + /* Switch HCLK clock source to Internal RC and HCLK source divide 1 */ + CLK_SetHCLK(CLK_CLKSEL0_HCLKSEL_HIRC48, CLK_CLKDIV0_HCLK(1)); + + /* Use HIRC as UART clock source */ + CLK_SetModuleClock(UART0_MODULE, CLK_CLKSEL1_UARTSEL_HIRC, CLK_CLKDIV0_UART(1)); + + /* Use HIRC48 as USB clock source */ + CLK_SetModuleClock(USBD_MODULE, CLK_CLKSEL3_USBDSEL_HIRC48, CLK_CLKDIV0_USB(1)); +#endif + + /* Enable module clock */ + CLK_EnableModuleClock(USBD_MODULE); + +#if CFG_TUSB_OS == OPT_OS_NONE + // 1ms tick timer + SysTick_Config(48000000 / 1000); +#endif +} + +#if CFG_TUSB_OS == OPT_OS_NONE +volatile uint32_t system_ticks = 0; +void SysTick_Handler (void) +{ + system_ticks++; +} + +uint32_t board_millis(void) +{ + return system_ticks; +} +#endif + +//--------------------------------------------------------------------+ +// Board porting API +//--------------------------------------------------------------------+ + +void board_led_write(bool state) +{ + (void)(state); +} + +uint32_t board_button_read(void) +{ + return 0; +} + +int board_uart_read(uint8_t* buf, int len) +{ + (void) buf; (void) len; + return 0; +} + +int board_uart_write(void const * buf, int len) +{ + (void) buf; (void) len; + return 0; +} diff --git a/hw/mcu/nuvoton b/hw/mcu/nuvoton new file mode 160000 index 00000000..dc96fff7 --- /dev/null +++ b/hw/mcu/nuvoton @@ -0,0 +1 @@ +Subproject commit dc96fff794d14818c93ea1d4d760d51a014d70c5 diff --git a/src/portable/nuvoton/nuc121/dcd_nuc121.c b/src/portable/nuvoton/nuc121/dcd_nuc121.c new file mode 100644 index 00000000..57db5231 --- /dev/null +++ b/src/portable/nuvoton/nuc121/dcd_nuc121.c @@ -0,0 +1,434 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Peter Lawrence + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +/* + Theory of operation: + + The NUC121/NUC125/NUC126 USBD peripheral has eight "EP"s, but each is simplex, + so two collectively (peripheral nomenclature of "EP0" and "EP1") are needed to + implement USB EP0. PERIPH_EP0 and PERIPH_EP1 are used by this driver for + EP0_IN and EP0_OUT respectively. This leaves up to six for user usage. +*/ + +#include "tusb_option.h" + +#if TUSB_OPT_DEVICE_ENABLED && ( (CFG_TUSB_MCU == OPT_MCU_NUC121) || (CFG_TUSB_MCU == OPT_MCU_NUC126) ) + +#include "device/dcd.h" +#include "NuMicro.h" + +/* allocation of USBD RAM for Setup, EP0_IN, and and EP_OUT */ +#define PERIPH_SETUP_BUF_BASE 0 +#define PERIPH_SETUP_BUF_LEN 8 +#define PERIPH_EP0_BUF_BASE (PERIPH_SETUP_BUF_BASE + PERIPH_SETUP_BUF_LEN) +#define PERIPH_EP0_BUF_LEN CFG_TUD_ENDPOINT0_SIZE +#define PERIPH_EP1_BUF_BASE (PERIPH_EP0_BUF_BASE + PERIPH_EP0_BUF_LEN) +#define PERIPH_EP1_BUF_LEN CFG_TUD_ENDPOINT0_SIZE +#define PERIPH_EP2_BUF_BASE (PERIPH_EP1_BUF_BASE + PERIPH_EP1_BUF_LEN) + +/* rather important info unfortunately not provided by device include files: how much there is */ +#define USBD_BUF_SIZE ((CFG_TUSB_MCU == OPT_MCU_NUC121) ? 768 : 512) + +enum ep_enum +{ + PERIPH_EP0 = 0, + PERIPH_EP1 = 1, + PERIPH_EP2 = 2, + PERIPH_EP3 = 3, + PERIPH_EP4 = 4, + PERIPH_EP5 = 5, + PERIPH_EP6 = 6, + PERIPH_EP7 = 7, + PERIPH_MAX_EP, +}; + +/* set by dcd_set_address() */ +static volatile uint8_t assigned_address; + +/* reset by dcd_init(), this is used by dcd_edpt_open() to assign USBD peripheral buffer addresses */ +static uint32_t bufseg_addr; + +/* used by dcd_edpt_xfer() and the ISR to reset the data sync (DATA0/DATA1) in an EP0_IN transfer */ +static bool active_ep0_xfer; + +/* RAM table needed to track ongoing transfers performed by dcd_edpt_xfer(), dcd_in_xfer(), and the ISR */ +static struct xfer_ctl_t +{ + uint8_t *data_ptr; /* collectively, data_ptr and remaining_bytes track progress of endpoint transfers */ + uint16_t remaining_bytes; + uint16_t max_packet_size; /* needed since device driver only finds out this at runtime */ + uint16_t total_bytes; /* quantity needed to pass as argument to dcd_event_xfer_complete() (for IN endpoints) */ +} xfer_table[PERIPH_MAX_EP]; + +/* + local helper functions +*/ + +static void usb_attach(void) +{ + USBD->SE0 &= ~USBD_SE0_SE0_Msk; +} + +static void usb_detach(void) +{ + USBD->SE0 |= USBD_SE0_SE0_Msk; +} + +static void usb_control_send_zlp(void) +{ + USBD->EP[PERIPH_EP0].CFG |= USBD_CFG_DSQSYNC_Msk; + USBD->EP[PERIPH_EP0].MXPLD = 0; +} + +/* reconstruct ep_addr from particular USB Configuration Register */ +static uint8_t decode_ep_addr(USBD_EP_T *ep) +{ + uint8_t ep_addr = ep->CFG & USBD_CFG_EPNUM_Msk; + if ( USBD_CFG_EPMODE_IN == (ep->CFG & USBD_CFG_STATE_Msk) ) + ep_addr |= TUSB_DIR_IN_MASK; + return ep_addr; +} + +/* map 8-bit ep_addr into peripheral endpoint index (PERIPH_EP0...) */ +static USBD_EP_T *ep_entry(uint8_t ep_addr, bool add) +{ + USBD_EP_T *ep; + enum ep_enum ep_index; + + for (ep_index = PERIPH_EP0, ep = USBD->EP; ep_index < PERIPH_MAX_EP; ep_index++, ep++) + { + if (add) + { + /* take first peripheral endpoint that is unused */ + if (0 == (ep->CFG & USBD_CFG_STATE_Msk)) return ep; + } + else + { + /* find a peripheral endpoint that matches ep_addr */ + uint8_t candidate_ep_addr = decode_ep_addr(ep); + if (candidate_ep_addr == ep_addr) return ep; + } + } + + return NULL; +} + +/* perform an IN endpoint transfer; this is called by dcd_edpt_xfer() and the ISR */ +static void dcd_in_xfer(struct xfer_ctl_t *xfer, USBD_EP_T *ep) +{ + uint16_t bytes_now = tu_min16(xfer->remaining_bytes, xfer->max_packet_size); + + memcpy((uint8_t *)(USBD_BUF_BASE + ep->BUFSEG), xfer->data_ptr, bytes_now); + ep->MXPLD = bytes_now; +} + +/* centralized location for USBD interrupt enable bit mask */ +static const uint32_t enabled_irqs = USBD_INTSTS_VBDETIF_Msk | USBD_INTSTS_BUSIF_Msk | USBD_INTSTS_SETUP_Msk | USBD_INTSTS_USBIF_Msk | USBD_INTSTS_SOFIF_Msk; + +/* + NUC121/NUC125/NUC126 TinyUSB API driver implementation +*/ + +void dcd_init(uint8_t rhport) +{ + (void) rhport; + +#ifdef SUPPORT_LPM + USBD->ATTR = 0x7D0 | USBD_LPMACK; +#else + USBD->ATTR = 0x7D0; +#endif + + usb_detach(); + + USBD->STBUFSEG = PERIPH_SETUP_BUF_BASE; + + for (enum ep_enum ep_index = PERIPH_EP0; ep_index < PERIPH_MAX_EP; ep_index++) + { + USBD->EP[ep_index].CFGP &= ~USBD_CFG_STATE_Msk; + } + + /* allocate the default EP0 endpoints */ + + USBD->EP[PERIPH_EP0].CFG = USBD_CFG_CSTALL_Msk | USBD_CFG_EPMODE_IN; + USBD->EP[PERIPH_EP0].BUFSEG = PERIPH_EP0_BUF_BASE; + xfer_table[PERIPH_EP0].max_packet_size = PERIPH_EP0_BUF_LEN; + + USBD->EP[PERIPH_EP1].CFG = USBD_CFG_CSTALL_Msk | USBD_CFG_EPMODE_OUT; + USBD->EP[PERIPH_EP1].BUFSEG = PERIPH_EP1_BUF_BASE; + xfer_table[PERIPH_EP1].max_packet_size = PERIPH_EP1_BUF_LEN; + + /* USB RAM beyond what we've allocated above is available to the user */ + bufseg_addr = PERIPH_EP2_BUF_BASE; + + usb_attach(); + + USBD->INTSTS = enabled_irqs; + USBD->INTEN = enabled_irqs; +} + +void dcd_int_enable(uint8_t rhport) +{ + (void) rhport; + NVIC_EnableIRQ(USBD_IRQn); +} + +void dcd_int_disable(uint8_t rhport) +{ + (void) rhport; + NVIC_DisableIRQ(USBD_IRQn); +} + +void dcd_set_address(uint8_t rhport, uint8_t dev_addr) +{ + (void) rhport; + usb_control_send_zlp(); /* SET_ADDRESS is the one exception where TinyUSB doesn't use dcd_edpt_xfer() to generate a ZLP */ + assigned_address = dev_addr; +} + +void dcd_set_config(uint8_t rhport, uint8_t config_num) +{ + (void) rhport; + (void) config_num; +} + +void dcd_remote_wakeup(uint8_t rhport) +{ + (void) rhport; + USBD->ATTR = USBD_ATTR_RWAKEUP_Msk; +} + +bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc) +{ + (void) rhport; + + USBD_EP_T *ep = ep_entry(p_endpoint_desc->bEndpointAddress, true); + TU_ASSERT(ep); + + /* mine the data for the information we need */ + int const dir = tu_edpt_dir(p_endpoint_desc->bEndpointAddress); + int const size = p_endpoint_desc->wMaxPacketSize.size; + tusb_xfer_type_t const type = p_endpoint_desc->bmAttributes.xfer; + struct xfer_ctl_t *xfer = &xfer_table[ep - USBD->EP]; + + /* allocate buffer from USB RAM */ + ep->BUFSEG = bufseg_addr; + bufseg_addr += size; + TU_ASSERT(bufseg_addr <= USBD_BUF_SIZE); + + /* construct USB Configuration Register value and then write it */ + uint32_t cfg = tu_edpt_number(p_endpoint_desc->bEndpointAddress); + cfg |= (TUSB_DIR_IN == dir) ? USBD_CFG_EPMODE_IN : USBD_CFG_EPMODE_OUT; + if (TUSB_XFER_ISOCHRONOUS == type) + cfg |= USBD_CFG_TYPE_ISO; + ep->CFG = cfg; + + /* make a note of the endpoint size */ + xfer->max_packet_size = size; + + return true; +} + +bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t *buffer, uint16_t total_bytes) +{ + (void) rhport; + + /* mine the data for the information we need */ + tusb_dir_t dir = tu_edpt_dir(ep_addr); + USBD_EP_T *ep = ep_entry(ep_addr, false); + struct xfer_ctl_t *xfer = &xfer_table[ep - USBD->EP]; + + /* store away the information we'll needing now and later */ + xfer->data_ptr = buffer; + xfer->remaining_bytes = total_bytes; + xfer->total_bytes = total_bytes; + + /* for the first of one or more EP0_IN packets in a message, the first must be DATA1 */ + if ( (0x80 == ep_addr) && !active_ep0_xfer ) ep->CFG |= USBD_CFG_DSQSYNC_Msk; + + if (TUSB_DIR_IN == dir) + dcd_in_xfer(xfer, ep); + else + ep->MXPLD = xfer->max_packet_size; + + return true; +} + +void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + USBD_EP_T *ep = ep_entry(ep_addr, false); + ep->CFGP |= USBD_CFGP_SSTALL_Msk; +} + +void dcd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + USBD_EP_T *ep = ep_entry(ep_addr, false); + ep->CFG |= USBD_CFG_CSTALL_Msk; +} + +void USBD_IRQHandler(void) +{ + uint32_t status = USBD->INTSTS; +#ifdef SUPPORT_LPM + uint32_t state = USBD->ATTR & 0x300f; +#else + uint32_t state = USBD->ATTR & 0xf; +#endif + + if(status & USBD_INTSTS_VBDETIF_Msk) + { + if(USBD->VBUSDET & USBD_VBUSDET_VBUSDET_Msk) + { + /* USB connect */ + USBD->ATTR |= USBD_ATTR_USBEN_Msk | USBD_ATTR_PHYEN_Msk; + } + else + { + /* USB disconnect */ + USBD->ATTR &= ~USBD_ATTR_USBEN_Msk; + } + } + + if(status & USBD_INTSTS_BUSIF_Msk) + { + if(state & USBD_ATTR_USBRST_Msk) + { + /* USB bus reset */ + USBD->ATTR |= USBD_ATTR_USBEN_Msk | USBD_ATTR_PHYEN_Msk; + + /* Reset all endpoints to DATA0 */ + for(enum ep_enum ep_index = PERIPH_EP0; ep_index < PERIPH_MAX_EP; ep_index++) + USBD->EP[ep_index].CFG &= ~USBD_CFG_DSQSYNC_Msk; + + /* Reset USB device address */ + USBD->FADDR = 0; + + /* reset EP0_IN flag */ + active_ep0_xfer = false; + + dcd_event_bus_signal(0, DCD_EVENT_BUS_RESET, true); + } + + if(state & USBD_ATTR_SUSPEND_Msk) + { + /* Enable USB but disable PHY */ + USBD->ATTR &= ~USBD_ATTR_PHYEN_Msk; + dcd_event_bus_signal(0, DCD_EVENT_SUSPEND, true); + } + + if(state & USBD_ATTR_RESUME_Msk) + { + /* Enable USB and enable PHY */ + USBD->ATTR |= USBD_ATTR_USBEN_Msk | USBD_ATTR_PHYEN_Msk; + dcd_event_bus_signal(0, DCD_EVENT_RESUME, true); + } + } + + if(status & USBD_INTSTS_SETUP_Msk) + { + /* clear the data ready flag of control endpoints */ + USBD->EP[PERIPH_EP0].CFGP |= USBD_CFGP_CLRRDY_Msk; + USBD->EP[PERIPH_EP1].CFGP |= USBD_CFGP_CLRRDY_Msk; + + /* get SETUP packet from USB buffer */ + dcd_event_setup_received(0, (uint8_t *)USBD_BUF_BASE, true); + } + + if(status & USBD_INTSTS_USBIF_Msk) + { + if (status & USBD_INTSTS_EPEVT0_Msk) /* PERIPH_EP0 (EP0_IN) event: this is treated separately from the rest */ + { + /* given ACK from host has happened, we can now set the address (if not already done) */ + if((USBD->FADDR != assigned_address) && (USBD->FADDR == 0)) USBD->FADDR = assigned_address; + + uint16_t const available_bytes = USBD->EP[PERIPH_EP0].MXPLD; + + active_ep0_xfer = (available_bytes == xfer_table[PERIPH_EP0].max_packet_size); + + dcd_event_xfer_complete(0, 0x80, available_bytes, XFER_RESULT_SUCCESS, true); + } + + /* service PERIPH_EP1 through PERIPH_EP7 */ + enum ep_enum ep_index; + uint32_t mask; + struct xfer_ctl_t *xfer; + USBD_EP_T *ep; + for (ep_index = PERIPH_EP1, mask = USBD_INTSTS_EPEVT1_Msk, xfer = &xfer_table[PERIPH_EP1], ep = &USBD->EP[PERIPH_EP1]; ep_index <= PERIPH_EP7; ep_index++, mask <<= 1, xfer++, ep++) + { + if(status & mask) + { + USBD->INTSTS = mask; + + uint16_t const available_bytes = ep->MXPLD; + uint8_t const ep_addr = decode_ep_addr(ep); + bool const out_ep = !(ep_addr & TUSB_DIR_IN_MASK); + + if (out_ep) + { + /* copy the data from the PC to the previously provided buffer */ + memcpy(xfer->data_ptr, (uint8_t *)(USBD_BUF_BASE + ep->BUFSEG), available_bytes); + xfer->remaining_bytes -= available_bytes; + xfer->data_ptr += available_bytes; + + /* when the transfer is finished, alert TinyUSB */ + if ( (0 == xfer->remaining_bytes) || (available_bytes < xfer->max_packet_size) ) + dcd_event_xfer_complete(0, ep_addr, available_bytes, XFER_RESULT_SUCCESS, true); + } + else if (xfer->remaining_bytes) + { + /* update the bookkeeping to reflect the data that has now been sent to the PC */ + xfer->remaining_bytes -= available_bytes; + xfer->data_ptr += available_bytes; + + /* if more data to send, send it; otherwise, alert TinyUSB that we've finished */ + if (xfer->remaining_bytes) + dcd_in_xfer(xfer, ep); + else + dcd_event_xfer_complete(0, ep_addr, xfer->total_bytes, XFER_RESULT_SUCCESS, true); + } + } + } + } + + if(status & USBD_INTSTS_SOFIF_Msk) + { + /* Start-Of-Frame event */ + dcd_event_bus_signal(0, DCD_EVENT_SOF, true); + } + + /* acknowledge all interrupts */ + USBD->INTSTS = status & enabled_irqs; +} + +void dcd_isr(uint8_t rhport) +{ + (void) rhport; + USBD_IRQHandler(); +} + +#endif diff --git a/src/tusb_option.h b/src/tusb_option.h index ae8c02ee..12b499c0 100644 --- a/src/tusb_option.h +++ b/src/tusb_option.h @@ -74,6 +74,9 @@ #define OPT_MCU_MIMXRT10XX 700 ///< NXP iMX RT10xx +#define OPT_MCU_NUC121 800 +#define OPT_MCU_NUC126 801 + /** @} */ /** \defgroup group_supported_os Supported RTOS From 5c5f876461e81ff7c2937978e4e6855e0208ebfb Mon Sep 17 00:00:00 2001 From: Peter Lawrence <12226419+majbthrd@users.noreply.github.com> Date: Sat, 4 Jan 2020 13:36:26 -0600 Subject: [PATCH 186/267] dcd_nuc121: allow user ZLP transfers to get a callback --- src/portable/nuvoton/nuc121/dcd_nuc121.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/portable/nuvoton/nuc121/dcd_nuc121.c b/src/portable/nuvoton/nuc121/dcd_nuc121.c index 57db5231..afe2cf00 100644 --- a/src/portable/nuvoton/nuc121/dcd_nuc121.c +++ b/src/portable/nuvoton/nuc121/dcd_nuc121.c @@ -399,7 +399,7 @@ void USBD_IRQHandler(void) if ( (0 == xfer->remaining_bytes) || (available_bytes < xfer->max_packet_size) ) dcd_event_xfer_complete(0, ep_addr, available_bytes, XFER_RESULT_SUCCESS, true); } - else if (xfer->remaining_bytes) + else { /* update the bookkeeping to reflect the data that has now been sent to the PC */ xfer->remaining_bytes -= available_bytes; From 0268f24227c19145d7fe1fefda91673bc7a0514b Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 7 Jan 2020 16:29:11 +0700 Subject: [PATCH 187/267] skip travis build --- .travis.yml => .travis.yml.bck | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename .travis.yml => .travis.yml.bck (100%) diff --git a/.travis.yml b/.travis.yml.bck similarity index 100% rename from .travis.yml rename to .travis.yml.bck From 8aef8d4b85535a2112bddd8b22f68fa6cdc09dca Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 7 Jan 2020 16:57:18 +0700 Subject: [PATCH 188/267] fix ci build - nuc 121/125: add CFG_EXAMPLE_MSC_READONLY since it is not enough SRAM to hold MSC disk - nuc 126: drop i2c source files in compile list due to SDK driver issue. --- hw/bsp/nutiny_nuc121s/board.mk | 1 + hw/bsp/nutiny_nuc125s/board.mk | 1 + hw/bsp/nutiny_nuc126v/board.mk | 2 -- 3 files changed, 2 insertions(+), 2 deletions(-) diff --git a/hw/bsp/nutiny_nuc121s/board.mk b/hw/bsp/nutiny_nuc121s/board.mk index dfd0e80c..ec4966cb 100644 --- a/hw/bsp/nutiny_nuc121s/board.mk +++ b/hw/bsp/nutiny_nuc121s/board.mk @@ -5,6 +5,7 @@ CFLAGS += \ -mcpu=cortex-m0 \ -D__ARM_FEATURE_DSP=0 \ -DUSE_ASSERT=0 \ + -DCFG_EXAMPLE_MSC_READONLY \ -DCFG_TUSB_MCU=OPT_MCU_NUC121 # All source paths should be relative to the top level. diff --git a/hw/bsp/nutiny_nuc125s/board.mk b/hw/bsp/nutiny_nuc125s/board.mk index 8e4d78ce..6329ca7c 100644 --- a/hw/bsp/nutiny_nuc125s/board.mk +++ b/hw/bsp/nutiny_nuc125s/board.mk @@ -5,6 +5,7 @@ CFLAGS += \ -mcpu=cortex-m0 \ -D__ARM_FEATURE_DSP=0 \ -DUSE_ASSERT=0 \ + -DCFG_EXAMPLE_MSC_READONLY \ -DCFG_TUSB_MCU=OPT_MCU_NUC121 # All source paths should be relative to the top level. diff --git a/hw/bsp/nutiny_nuc126v/board.mk b/hw/bsp/nutiny_nuc126v/board.mk index 6d87c9d9..d38e6c4d 100644 --- a/hw/bsp/nutiny_nuc126v/board.mk +++ b/hw/bsp/nutiny_nuc126v/board.mk @@ -20,7 +20,6 @@ SRC_C += \ hw/mcu/nuvoton/nuc126/StdDriver/src/ebi.c \ hw/mcu/nuvoton/nuc126/StdDriver/src/fmc.c \ hw/mcu/nuvoton/nuc126/StdDriver/src/gpio.c \ - hw/mcu/nuvoton/nuc126/StdDriver/src/i2c.c \ hw/mcu/nuvoton/nuc126/StdDriver/src/pdma.c \ hw/mcu/nuvoton/nuc126/StdDriver/src/pwm.c \ hw/mcu/nuvoton/nuc126/StdDriver/src/rtc.c \ @@ -32,7 +31,6 @@ SRC_C += \ hw/mcu/nuvoton/nuc126/StdDriver/src/timer_pwm.c \ hw/mcu/nuvoton/nuc126/StdDriver/src/uart.c \ hw/mcu/nuvoton/nuc126/StdDriver/src/usbd.c \ - hw/mcu/nuvoton/nuc126/StdDriver/src/usci_i2c.c \ hw/mcu/nuvoton/nuc126/StdDriver/src/usci_spi.c \ hw/mcu/nuvoton/nuc126/StdDriver/src/usci_uart.c \ hw/mcu/nuvoton/nuc126/StdDriver/src/wdt.c \ From e85a481db1393f15a2c879b529569fb8d11bc112 Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 7 Jan 2020 17:04:15 +0700 Subject: [PATCH 189/267] added Peter into contributors doc --- CONTRIBUTORS.md | 4 ++++ docs/boards.md | 8 +++++++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 20f4d9e2..0b52c4c5 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -23,6 +23,10 @@ * USBTMC class driver support with example * Various improvement e.g Zero-length packet, Lint setup * Board support for STM32F070RB Nucleo, STM32F303 Discovery + +* **[Peter Lawrence](https://github.com/majbthrd)** + * Nuvoton NUC 121, 125, 126 device driver port + * Board support for NuTiny NUC121s, NUC125s, NUC126V * **[Scott Shawcroft](https://github.com/tannewt)** * SAMD21 and SAMD51 device driver port diff --git a/docs/boards.md b/docs/boards.md index 7006aae5..399278e5 100644 --- a/docs/boards.md +++ b/docs/boards.md @@ -7,7 +7,7 @@ The board support code is only used for self-contained examples and testing. It ## Supported Boards -This code base already had supported for a handful of following boards +This code base already had supported for a handful of following boards (sorted alphabetically) ### MicroChip SAMD @@ -26,6 +26,12 @@ This code base already had supported for a handful of following boards - [Nordic nRF52840 Dongle (aka pca10059)](https://www.nordicsemi.com/Software-and-Tools/Development-Kits/nRF52840-Dongle) - [Nordic nRF52833 Development Kit (aka pca10100)](https://www.nordicsemi.com/Software-and-Tools/Development-Kits/nRF52833-DK) +### Nuvoton + +- [NuTiny NUC121S](https://direct.nuvoton.com/en/nutiny-nuc121s) +- [NuTiny NUC125S](https://direct.nuvoton.com/en/nutiny-nuc125s) +- [NuTiny NUC126V](https://direct.nuvoton.com/en/nutiny-nuc126v) + ### NXP iMX RT - [MIMX RT1010 Evaluation Kit](https://www.nxp.com/design/development-boards/i.mx-evaluation-and-development-boards/i.mx-rt1010-evaluation-kit:MIMXRT1010-EVK) From 8ead416865b99cf623ce0a152c88764bbaf70926 Mon Sep 17 00:00:00 2001 From: Lady Ada Date: Thu, 9 Jan 2020 00:59:48 -0500 Subject: [PATCH 190/267] add a rough bsp. UART on D0/D1, LED on D13, button on D12 --- hw/bsp/teensy_40/board.h | 36 +++ hw/bsp/teensy_40/board.mk | 53 ++++ hw/bsp/teensy_40/teensy40.c | 184 ++++++++++++ .../teensy_40/teensy40_flexspi_nor_config.c | 49 ++++ .../teensy_40/teensy40_flexspi_nor_config.h | 268 ++++++++++++++++++ 5 files changed, 590 insertions(+) create mode 100644 hw/bsp/teensy_40/board.h create mode 100644 hw/bsp/teensy_40/board.mk create mode 100644 hw/bsp/teensy_40/teensy40.c create mode 100644 hw/bsp/teensy_40/teensy40_flexspi_nor_config.c create mode 100644 hw/bsp/teensy_40/teensy40_flexspi_nor_config.h diff --git a/hw/bsp/teensy_40/board.h b/hw/bsp/teensy_40/board.h new file mode 100644 index 00000000..c5338e27 --- /dev/null +++ b/hw/bsp/teensy_40/board.h @@ -0,0 +1,36 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019, Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + + +#ifndef BOARD_H_ +#define BOARD_H_ + + +// required since iMX RT10xx SDK include this file for board size +#define BOARD_FLASH_SIZE (2 * 1024 * 1024) + + +#endif /* BOARD_H_ */ diff --git a/hw/bsp/teensy_40/board.mk b/hw/bsp/teensy_40/board.mk new file mode 100644 index 00000000..4bfc48bb --- /dev/null +++ b/hw/bsp/teensy_40/board.mk @@ -0,0 +1,53 @@ +CFLAGS += \ + -mthumb \ + -mabi=aapcs \ + -mcpu=cortex-m7 \ + -mfloat-abi=hard \ + -mfpu=fpv5-d16 \ + -D__ARMVFP__=0 -D__ARMFPV5__=0\ + -DCPU_MIMXRT1062DVL6A \ + -DXIP_EXTERNAL_FLASH=1 \ + -DXIP_BOOT_HEADER_ENABLE=1 \ + -DCFG_TUSB_MCU=OPT_MCU_MIMXRT10XX + +# mcu driver cause following warnings +#CFLAGS += -Wno-error=float-equal -Wno-error=nested-externs +CFLAGS += -Wno-error=unused-parameter + +MCU_DIR = hw/mcu/nxp/sdk/devices/MIMXRT1062 + +# All source paths should be relative to the top level. +LD_FILE = $(MCU_DIR)/gcc/MIMXRT1062xxxxx_flexspi_nor.ld + +SRC_C += \ + $(MCU_DIR)/system_MIMXRT1062.c \ + $(MCU_DIR)/xip/fsl_flexspi_nor_boot.c \ + $(MCU_DIR)/project_template/clock_config.c \ + $(MCU_DIR)/drivers/fsl_clock.c \ + $(MCU_DIR)/drivers/fsl_gpio.c \ + $(MCU_DIR)/drivers/fsl_common.c \ + $(MCU_DIR)/drivers/fsl_lpuart.c + +INC += \ + $(TOP)/hw/bsp/$(BOARD) \ + $(TOP)/$(MCU_DIR)/../../CMSIS/Include \ + $(TOP)/$(MCU_DIR) \ + $(TOP)/$(MCU_DIR)/drivers \ + $(TOP)/$(MCU_DIR)/project_template \ + +SRC_S += $(MCU_DIR)/gcc/startup_MIMXRT1062.S + +# For TinyUSB port source +VENDOR = nxp +CHIP_FAMILY = transdimension + +# For freeRTOS port source +FREERTOS_PORT = ARM_CM7 + +# For flash-jlink target +JLINK_DEVICE = MIMXRT1062xxx6A +JLINK_IF = swd + +# flash by copying bin file to DAP Mass Storage +flash: $(BUILD)/$(BOARD)-firmware.bin + cp $< /media/$(USER)/RT1060-EVK/ diff --git a/hw/bsp/teensy_40/teensy40.c b/hw/bsp/teensy_40/teensy40.c new file mode 100644 index 00000000..9c905dbb --- /dev/null +++ b/hw/bsp/teensy_40/teensy40.c @@ -0,0 +1,184 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2018, hathach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#include "../board.h" +#include "fsl_device_registers.h" +#include "fsl_gpio.h" +#include "fsl_iomuxc.h" +#include "fsl_clock.h" +#include "fsl_lpuart.h" + +#include "clock_config.h" + +#define LED_PINMUX IOMUXC_GPIO_B0_03_GPIO2_IO03 // D13 +#define LED_PORT GPIO2 +#define LED_PIN 3 +#define LED_STATE_ON 0 + +// no button +#define BUTTON_PINMUX IOMUXC_GPIO_B0_01_GPIO2_IO01 // D12 +#define BUTTON_PORT GPIO2 +#define BUTTON_PIN 1 +#define BUTTON_STATE_ACTIVE 0 + +// UART +#define UART_PORT LPUART6 +#define UART_RX_PINMUX IOMUXC_GPIO_AD_B0_03_LPUART6_RX // D0 +#define UART_TX_PINMUX IOMUXC_GPIO_AD_B0_02_LPUART6_TX // D1 + +const uint8_t dcd_data[] = { 0x00 }; + +void board_init(void) +{ + // Init clock + BOARD_BootClockRUN(); + SystemCoreClockUpdate(); + + // Enable IOCON clock + CLOCK_EnableClock(kCLOCK_Iomuxc); + +#if CFG_TUSB_OS == OPT_OS_NONE + // 1ms tick timer + SysTick_Config(SystemCoreClock / 1000); +#elif CFG_TUSB_OS == OPT_OS_FREERTOS + // If freeRTOS is used, IRQ priority is limit by max syscall ( smaller is higher ) +// NVIC_SetPriority(USB0_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY ); +#endif + + // LED + IOMUXC_SetPinMux( LED_PINMUX, 0U); + IOMUXC_SetPinConfig( LED_PINMUX, 0x10B0U); + + gpio_pin_config_t led_config = { kGPIO_DigitalOutput, 0, kGPIO_NoIntmode }; + GPIO_PinInit(LED_PORT, LED_PIN, &led_config); + board_led_write(true); + + // Button + IOMUXC_SetPinMux( BUTTON_PINMUX, 0U); + gpio_pin_config_t button_config = { kGPIO_DigitalInput, 0, kGPIO_IntRisingEdge, }; + GPIO_PinInit(BUTTON_PORT, BUTTON_PIN, &button_config); + + // UART + IOMUXC_SetPinMux( UART_TX_PINMUX, 0U); + IOMUXC_SetPinMux( UART_RX_PINMUX, 0U); + IOMUXC_SetPinConfig( UART_TX_PINMUX, 0x10B0u); + IOMUXC_SetPinConfig( UART_RX_PINMUX, 0x10B0u); + + lpuart_config_t uart_config; + LPUART_GetDefaultConfig(&uart_config); + uart_config.baudRate_Bps = CFG_BOARD_UART_BAUDRATE; + uart_config.enableTx = true; + uart_config.enableRx = true; + LPUART_Init(UART_PORT, &uart_config, (CLOCK_GetPllFreq(kCLOCK_PllUsb1) / 6U) / (CLOCK_GetDiv(kCLOCK_UartDiv) + 1U)); + + //------------- USB0 -------------// + // Clock + CLOCK_EnableUsbhs0PhyPllClock(kCLOCK_Usbphy480M, 480000000U); + CLOCK_EnableUsbhs0Clock(kCLOCK_Usb480M, 480000000U); + + USBPHY_Type* usb_phy = USBPHY1; + + // Enable PHY support for Low speed device + LS via FS Hub + usb_phy->CTRL |= USBPHY_CTRL_SET_ENUTMILEVEL2_MASK | USBPHY_CTRL_SET_ENUTMILEVEL3_MASK; + + // Enable all power for normal operation + usb_phy->PWD = 0; + + // TX Timing + uint32_t phytx = usb_phy->TX; + phytx &= ~(USBPHY_TX_D_CAL_MASK | USBPHY_TX_TXCAL45DM_MASK | USBPHY_TX_TXCAL45DP_MASK); + phytx |= USBPHY_TX_D_CAL(0x0C) | USBPHY_TX_TXCAL45DP(0x06) | USBPHY_TX_TXCAL45DM(0x06); + usb_phy->TX = phytx; + + // USB1 +// CLOCK_EnableUsbhs1PhyPllClock(kCLOCK_Usbphy480M, 480000000U); +// CLOCK_EnableUsbhs1Clock(kCLOCK_Usb480M, 480000000U); +} + +//--------------------------------------------------------------------+ +// USB Interrupt Handler +//--------------------------------------------------------------------+ +void USB_OTG1_IRQHandler(void) +{ + #if CFG_TUSB_RHPORT0_MODE & OPT_MODE_HOST + tuh_isr(0); + #endif + + #if CFG_TUSB_RHPORT0_MODE & OPT_MODE_DEVICE + tud_isr(0); + #endif +} + +void USB_OTG2_IRQHandler(void) +{ + #if CFG_TUSB_RHPORT1_MODE & OPT_MODE_HOST + tuh_isr(1); + #endif + + #if CFG_TUSB_RHPORT1_MODE & OPT_MODE_DEVICE + tud_isr(1); + #endif +} + +//--------------------------------------------------------------------+ +// Board porting API +//--------------------------------------------------------------------+ + +void board_led_write(bool state) +{ + GPIO_PinWrite(LED_PORT, LED_PIN, state ? LED_STATE_ON : (1-LED_STATE_ON)); +} + +uint32_t board_button_read(void) +{ + // active low + return BUTTON_STATE_ACTIVE == GPIO_PinRead(BUTTON_PORT, BUTTON_PIN); +} + +int board_uart_read(uint8_t* buf, int len) +{ + LPUART_ReadBlocking(UART_PORT, buf, len); + return len; +} + +int board_uart_write(void const * buf, int len) +{ + LPUART_WriteBlocking(UART_PORT, (uint8_t*)buf, len); + return len; +} + +#if CFG_TUSB_OS == OPT_OS_NONE +volatile uint32_t system_ticks = 0; +void SysTick_Handler(void) +{ + system_ticks++; +} + +uint32_t board_millis(void) +{ + return system_ticks; +} +#endif diff --git a/hw/bsp/teensy_40/teensy40_flexspi_nor_config.c b/hw/bsp/teensy_40/teensy40_flexspi_nor_config.c new file mode 100644 index 00000000..dbedc90a --- /dev/null +++ b/hw/bsp/teensy_40/teensy40_flexspi_nor_config.c @@ -0,0 +1,49 @@ +/* + * Copyright 2018 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include "teensy40_flexspi_nor_config.h" + +/* Component ID definition, used by tools. */ +#ifndef FSL_COMPONENT_ID +#define FSL_COMPONENT_ID "platform.drivers.xip_board" +#endif + +/******************************************************************************* + * Code + ******************************************************************************/ +#if defined(XIP_BOOT_HEADER_ENABLE) && (XIP_BOOT_HEADER_ENABLE == 1) +#if defined(__CC_ARM) || defined(__ARMCC_VERSION) || defined(__GNUC__) +__attribute__((section(".boot_hdr.conf"))) +#elif defined(__ICCARM__) +#pragma location = ".boot_hdr.conf" +#endif + +const flexspi_nor_config_t qspiflash_config = { + .memConfig = + { + .tag = FLEXSPI_CFG_BLK_TAG, + .version = FLEXSPI_CFG_BLK_VERSION, + .readSampleClkSrc = kFlexSPIReadSampleClk_LoopbackFromDqsPad, + .csHoldTime = 3u, + .csSetupTime = 3u, + // Enable DDR mode, Wordaddassable, Safe configuration, Differential clock + .sflashPadType = kSerialFlash_4Pads, + .serialClkFreq = kFlexSpiSerialClk_100MHz, + .sflashA1Size = 2u * 1024u * 1024u, + .lookupTable = + { + // Read LUTs + FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0xEB, RADDR_SDR, FLEXSPI_4PAD, 0x18), + FLEXSPI_LUT_SEQ(DUMMY_SDR, FLEXSPI_4PAD, 0x06, READ_SDR, FLEXSPI_4PAD, 0x04), + }, + }, + .pageSize = 256u, + .sectorSize = 4u * 1024u, + .blockSize = 256u * 1024u, + .isUniformBlockSize = false, +}; +#endif /* XIP_BOOT_HEADER_ENABLE */ diff --git a/hw/bsp/teensy_40/teensy40_flexspi_nor_config.h b/hw/bsp/teensy_40/teensy40_flexspi_nor_config.h new file mode 100644 index 00000000..56068ec6 --- /dev/null +++ b/hw/bsp/teensy_40/teensy40_flexspi_nor_config.h @@ -0,0 +1,268 @@ +/* + * Copyright 2018 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef __TEENSY40_FLEXSPI_NOR_CONFIG__ +#define __TEENSY40_FLEXSPI_NOR_CONFIG__ + +#include +#include +#include "fsl_common.h" + +/*! @name Driver version */ +/*@{*/ +/*! @brief XIP_BOARD driver version 2.0.0. */ +#define FSL_XIP_BOARD_DRIVER_VERSION (MAKE_VERSION(2, 0, 0)) +/*@}*/ + +/* FLEXSPI memory config block related defintions */ +#define FLEXSPI_CFG_BLK_TAG (0x42464346UL) // ascii "FCFB" Big Endian +#define FLEXSPI_CFG_BLK_VERSION (0x56010400UL) // V1.4.0 +#define FLEXSPI_CFG_BLK_SIZE (512) + +/* FLEXSPI Feature related definitions */ +#define FLEXSPI_FEATURE_HAS_PARALLEL_MODE 1 + +/* Lookup table related defintions */ +#define CMD_INDEX_READ 0 +#define CMD_INDEX_READSTATUS 1 +#define CMD_INDEX_WRITEENABLE 2 +#define CMD_INDEX_WRITE 4 + +#define CMD_LUT_SEQ_IDX_READ 0 +#define CMD_LUT_SEQ_IDX_READSTATUS 1 +#define CMD_LUT_SEQ_IDX_WRITEENABLE 3 +#define CMD_LUT_SEQ_IDX_WRITE 9 + +#define CMD_SDR 0x01 +#define CMD_DDR 0x21 +#define RADDR_SDR 0x02 +#define RADDR_DDR 0x22 +#define CADDR_SDR 0x03 +#define CADDR_DDR 0x23 +#define MODE1_SDR 0x04 +#define MODE1_DDR 0x24 +#define MODE2_SDR 0x05 +#define MODE2_DDR 0x25 +#define MODE4_SDR 0x06 +#define MODE4_DDR 0x26 +#define MODE8_SDR 0x07 +#define MODE8_DDR 0x27 +#define WRITE_SDR 0x08 +#define WRITE_DDR 0x28 +#define READ_SDR 0x09 +#define READ_DDR 0x29 +#define LEARN_SDR 0x0A +#define LEARN_DDR 0x2A +#define DATSZ_SDR 0x0B +#define DATSZ_DDR 0x2B +#define DUMMY_SDR 0x0C +#define DUMMY_DDR 0x2C +#define DUMMY_RWDS_SDR 0x0D +#define DUMMY_RWDS_DDR 0x2D +#define JMP_ON_CS 0x1F +#define STOP 0 + +#define FLEXSPI_1PAD 0 +#define FLEXSPI_2PAD 1 +#define FLEXSPI_4PAD 2 +#define FLEXSPI_8PAD 3 + +#define FLEXSPI_LUT_SEQ(cmd0, pad0, op0, cmd1, pad1, op1) \ + (FLEXSPI_LUT_OPERAND0(op0) | FLEXSPI_LUT_NUM_PADS0(pad0) | FLEXSPI_LUT_OPCODE0(cmd0) | FLEXSPI_LUT_OPERAND1(op1) | \ + FLEXSPI_LUT_NUM_PADS1(pad1) | FLEXSPI_LUT_OPCODE1(cmd1)) + +//!@brief Definitions for FlexSPI Serial Clock Frequency +typedef enum _FlexSpiSerialClockFreq +{ + kFlexSpiSerialClk_30MHz = 1, + kFlexSpiSerialClk_50MHz = 2, + kFlexSpiSerialClk_60MHz = 3, + kFlexSpiSerialClk_75MHz = 4, + kFlexSpiSerialClk_80MHz = 5, + kFlexSpiSerialClk_100MHz = 6, + kFlexSpiSerialClk_120MHz = 7, + kFlexSpiSerialClk_133MHz = 8, + kFlexSpiSerialClk_166MHz = 9, +} flexspi_serial_clk_freq_t; + +//!@brief FlexSPI clock configuration type +enum +{ + kFlexSpiClk_SDR, //!< Clock configure for SDR mode + kFlexSpiClk_DDR, //!< Clock configurat for DDR mode +}; + +//!@brief FlexSPI Read Sample Clock Source definition +typedef enum _FlashReadSampleClkSource +{ + kFlexSPIReadSampleClk_LoopbackInternally = 0, + kFlexSPIReadSampleClk_LoopbackFromDqsPad = 1, + kFlexSPIReadSampleClk_LoopbackFromSckPad = 2, + kFlexSPIReadSampleClk_ExternalInputFromDqsPad = 3, +} flexspi_read_sample_clk_t; + +//!@brief Misc feature bit definitions +enum +{ + kFlexSpiMiscOffset_DiffClkEnable = 0, //!< Bit for Differential clock enable + kFlexSpiMiscOffset_Ck2Enable = 1, //!< Bit for CK2 enable + kFlexSpiMiscOffset_ParallelEnable = 2, //!< Bit for Parallel mode enable + kFlexSpiMiscOffset_WordAddressableEnable = 3, //!< Bit for Word Addressable enable + kFlexSpiMiscOffset_SafeConfigFreqEnable = 4, //!< Bit for Safe Configuration Frequency enable + kFlexSpiMiscOffset_PadSettingOverrideEnable = 5, //!< Bit for Pad setting override enable + kFlexSpiMiscOffset_DdrModeEnable = 6, //!< Bit for DDR clock confiuration indication. +}; + +//!@brief Flash Type Definition +enum +{ + kFlexSpiDeviceType_SerialNOR = 1, //!< Flash devices are Serial NOR + kFlexSpiDeviceType_SerialNAND = 2, //!< Flash devices are Serial NAND + kFlexSpiDeviceType_SerialRAM = 3, //!< Flash devices are Serial RAM/HyperFLASH + kFlexSpiDeviceType_MCP_NOR_NAND = 0x12, //!< Flash device is MCP device, A1 is Serial NOR, A2 is Serial NAND + kFlexSpiDeviceType_MCP_NOR_RAM = 0x13, //!< Flash deivce is MCP device, A1 is Serial NOR, A2 is Serial RAMs +}; + +//!@brief Flash Pad Definitions +enum +{ + kSerialFlash_1Pad = 1, + kSerialFlash_2Pads = 2, + kSerialFlash_4Pads = 4, + kSerialFlash_8Pads = 8, +}; + +//!@brief FlexSPI LUT Sequence structure +typedef struct _lut_sequence +{ + uint8_t seqNum; //!< Sequence Number, valid number: 1-16 + uint8_t seqId; //!< Sequence Index, valid number: 0-15 + uint16_t reserved; +} flexspi_lut_seq_t; + +//!@brief Flash Configuration Command Type +enum +{ + kDeviceConfigCmdType_Generic, //!< Generic command, for example: configure dummy cycles, drive strength, etc + kDeviceConfigCmdType_QuadEnable, //!< Quad Enable command + kDeviceConfigCmdType_Spi2Xpi, //!< Switch from SPI to DPI/QPI/OPI mode + kDeviceConfigCmdType_Xpi2Spi, //!< Switch from DPI/QPI/OPI to SPI mode + kDeviceConfigCmdType_Spi2NoCmd, //!< Switch to 0-4-4/0-8-8 mode + kDeviceConfigCmdType_Reset, //!< Reset device command +}; + +//!@brief FlexSPI Memory Configuration Block +typedef struct _FlexSPIConfig +{ + uint32_t tag; //!< [0x000-0x003] Tag, fixed value 0x42464346UL + uint32_t version; //!< [0x004-0x007] Version,[31:24] -'V', [23:16] - Major, [15:8] - Minor, [7:0] - bugfix + uint32_t reserved0; //!< [0x008-0x00b] Reserved for future use + uint8_t readSampleClkSrc; //!< [0x00c-0x00c] Read Sample Clock Source, valid value: 0/1/3 + uint8_t csHoldTime; //!< [0x00d-0x00d] CS hold time, default value: 3 + uint8_t csSetupTime; //!< [0x00e-0x00e] CS setup time, default value: 3 + uint8_t columnAddressWidth; //!< [0x00f-0x00f] Column Address with, for HyperBus protocol, it is fixed to 3, For + //! Serial NAND, need to refer to datasheet + uint8_t deviceModeCfgEnable; //!< [0x010-0x010] Device Mode Configure enable flag, 1 - Enable, 0 - Disable + uint8_t deviceModeType; //!< [0x011-0x011] Specify the configuration command type:Quad Enable, DPI/QPI/OPI switch, + //! Generic configuration, etc. + uint16_t waitTimeCfgCommands; //!< [0x012-0x013] Wait time for all configuration commands, unit: 100us, Used for + //! DPI/QPI/OPI switch or reset command + flexspi_lut_seq_t deviceModeSeq; //!< [0x014-0x017] Device mode sequence info, [7:0] - LUT sequence id, [15:8] - LUt + //! sequence number, [31:16] Reserved + uint32_t deviceModeArg; //!< [0x018-0x01b] Argument/Parameter for device configuration + uint8_t configCmdEnable; //!< [0x01c-0x01c] Configure command Enable Flag, 1 - Enable, 0 - Disable + uint8_t configModeType[3]; //!< [0x01d-0x01f] Configure Mode Type, similar as deviceModeTpe + flexspi_lut_seq_t + configCmdSeqs[3]; //!< [0x020-0x02b] Sequence info for Device Configuration command, similar as deviceModeSeq + uint32_t reserved1; //!< [0x02c-0x02f] Reserved for future use + uint32_t configCmdArgs[3]; //!< [0x030-0x03b] Arguments/Parameters for device Configuration commands + uint32_t reserved2; //!< [0x03c-0x03f] Reserved for future use + uint32_t controllerMiscOption; //!< [0x040-0x043] Controller Misc Options, see Misc feature bit definitions for more + //! details + uint8_t deviceType; //!< [0x044-0x044] Device Type: See Flash Type Definition for more details + uint8_t sflashPadType; //!< [0x045-0x045] Serial Flash Pad Type: 1 - Single, 2 - Dual, 4 - Quad, 8 - Octal + uint8_t serialClkFreq; //!< [0x046-0x046] Serial Flash Frequencey, device specific definitions, See System Boot + //! Chapter for more details + uint8_t lutCustomSeqEnable; //!< [0x047-0x047] LUT customization Enable, it is required if the program/erase cannot + //! be done using 1 LUT sequence, currently, only applicable to HyperFLASH + uint32_t reserved3[2]; //!< [0x048-0x04f] Reserved for future use + uint32_t sflashA1Size; //!< [0x050-0x053] Size of Flash connected to A1 + uint32_t sflashA2Size; //!< [0x054-0x057] Size of Flash connected to A2 + uint32_t sflashB1Size; //!< [0x058-0x05b] Size of Flash connected to B1 + uint32_t sflashB2Size; //!< [0x05c-0x05f] Size of Flash connected to B2 + uint32_t csPadSettingOverride; //!< [0x060-0x063] CS pad setting override value + uint32_t sclkPadSettingOverride; //!< [0x064-0x067] SCK pad setting override value + uint32_t dataPadSettingOverride; //!< [0x068-0x06b] data pad setting override value + uint32_t dqsPadSettingOverride; //!< [0x06c-0x06f] DQS pad setting override value + uint32_t timeoutInMs; //!< [0x070-0x073] Timeout threshold for read status command + uint32_t commandInterval; //!< [0x074-0x077] CS deselect interval between two commands + uint16_t dataValidTime[2]; //!< [0x078-0x07b] CLK edge to data valid time for PORT A and PORT B, in terms of 0.1ns + uint16_t busyOffset; //!< [0x07c-0x07d] Busy offset, valid value: 0-31 + uint16_t busyBitPolarity; //!< [0x07e-0x07f] Busy flag polarity, 0 - busy flag is 1 when flash device is busy, 1 - + //! busy flag is 0 when flash device is busy + uint32_t lookupTable[64]; //!< [0x080-0x17f] Lookup table holds Flash command sequences + flexspi_lut_seq_t lutCustomSeq[12]; //!< [0x180-0x1af] Customizable LUT Sequences + uint32_t reserved4[4]; //!< [0x1b0-0x1bf] Reserved for future use +} flexspi_mem_config_t; + +/* */ +#define NOR_CMD_INDEX_READ CMD_INDEX_READ //!< 0 +#define NOR_CMD_INDEX_READSTATUS CMD_INDEX_READSTATUS //!< 1 +#define NOR_CMD_INDEX_WRITEENABLE CMD_INDEX_WRITEENABLE //!< 2 +#define NOR_CMD_INDEX_ERASESECTOR 3 //!< 3 +#define NOR_CMD_INDEX_PAGEPROGRAM CMD_INDEX_WRITE //!< 4 +#define NOR_CMD_INDEX_CHIPERASE 5 //!< 5 +#define NOR_CMD_INDEX_DUMMY 6 //!< 6 +#define NOR_CMD_INDEX_ERASEBLOCK 7 //!< 7 + +#define NOR_CMD_LUT_SEQ_IDX_READ CMD_LUT_SEQ_IDX_READ //!< 0 READ LUT sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_READSTATUS \ + CMD_LUT_SEQ_IDX_READSTATUS //!< 1 Read Status LUT sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_READSTATUS_XPI \ + 2 //!< 2 Read status DPI/QPI/OPI sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_WRITEENABLE \ + CMD_LUT_SEQ_IDX_WRITEENABLE //!< 3 Write Enable sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_WRITEENABLE_XPI \ + 4 //!< 4 Write Enable DPI/QPI/OPI sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_ERASESECTOR 5 //!< 5 Erase Sector sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_ERASEBLOCK 8 //!< 8 Erase Block sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_PAGEPROGRAM \ + CMD_LUT_SEQ_IDX_WRITE //!< 9 Program sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_CHIPERASE 11 //!< 11 Chip Erase sequence in lookupTable id stored in config block +#define NOR_CMD_LUT_SEQ_IDX_READ_SFDP 13 //!< 13 Read SFDP sequence in lookupTable id stored in config block +#define NOR_CMD_LUT_SEQ_IDX_RESTORE_NOCMD \ + 14 //!< 14 Restore 0-4-4/0-8-8 mode sequence id in lookupTable stored in config block +#define NOR_CMD_LUT_SEQ_IDX_EXIT_NOCMD \ + 15 //!< 15 Exit 0-4-4/0-8-8 mode sequence id in lookupTable stored in config blobk + +/* + * Serial NOR configuration block + */ +typedef struct _flexspi_nor_config +{ + flexspi_mem_config_t memConfig; //!< Common memory configuration info via FlexSPI + uint32_t pageSize; //!< Page size of Serial NOR + uint32_t sectorSize; //!< Sector size of Serial NOR + uint8_t ipcmdSerialClkFreq; //!< Clock frequency for IP command + uint8_t isUniformBlockSize; //!< Sector/Block size is the same + uint8_t reserved0[2]; //!< Reserved for future use + uint8_t serialNorType; //!< Serial NOR Flash type: 0/1/2/3 + uint8_t needExitNoCmdMode; //!< Need to exit NoCmd mode before other IP command + uint8_t halfClkForNonReadCmd; //!< Half the Serial Clock for non-read command: true/false + uint8_t needRestoreNoCmdMode; //!< Need to Restore NoCmd mode after IP commmand execution + uint32_t blockSize; //!< Block size + uint32_t reserve2[11]; //!< Reserved for future use +} flexspi_nor_config_t; + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef __cplusplus +} +#endif +#endif /* __EVKMIMXRT1060_FLEXSPI_NOR_CONFIG__ */ From 03d14f4d832efc8a015c2b13e09cab7f4fa48079 Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 9 Jan 2020 21:31:10 +0700 Subject: [PATCH 191/267] add trigger.yml --- .github/workflows/trigger.yml | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 .github/workflows/trigger.yml diff --git a/.github/workflows/trigger.yml b/.github/workflows/trigger.yml new file mode 100644 index 00000000..a7ef1341 --- /dev/null +++ b/.github/workflows/trigger.yml @@ -0,0 +1,14 @@ +name: Trigger Repos + +on: + push: + branches: master + +jobs: + trigger: + runs-on: ubuntu-latest + steps: + - name: mynewt-tinyusb-example + shell: bash + run: | + curl -X POST -H "Authorization: token ${{ secrets.GH_REPO_TOKEN }}" -H "Accept: application/vnd.github.everest-preview+json" -H "Content-Type: application/json" --data '{"event_type": "rebuild"}' https://api.github.com/repos/hathach/mynewt-tinyusb-example/dispatches From 84bbe54e171c92efb669ccb9a4960e406c8afa17 Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 9 Jan 2020 22:04:11 +0700 Subject: [PATCH 192/267] follow up to #261 - fix button pullup - flash using teensy_loader_cli - update boards.md --- docs/boards.md | 1 + hw/bsp/teensy_40/board.mk | 7 ++++--- hw/bsp/teensy_40/teensy40.c | 3 ++- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/docs/boards.md b/docs/boards.md index 399278e5..c052552b 100644 --- a/docs/boards.md +++ b/docs/boards.md @@ -40,6 +40,7 @@ This code base already had supported for a handful of following boards (sorted a - [MIMX RT1050 Evaluation Kit](https://www.nxp.com/design/development-boards/i.mx-evaluation-and-development-boards/i.mx-rt1050-evaluation-kit:MIMXRT1050-EVK) - [MIMX RT1060 Evaluation Kit](https://www.nxp.com/design/development-boards/i.mx-evaluation-and-development-boards/mimxrt1060-evk-i.mx-rt1060-evaluation-kit:MIMXRT1060-EVK) - [MIMX RT1064 Evaluation Kit](https://www.nxp.com/design/development-boards/i.mx-evaluation-and-development-boards/mimxrt1064-evk-i.mx-rt1064-evaluation-kit:MIMXRT1064-EVK) +- [Teensy 4.0 Development Board](https://www.pjrc.com/store/teensy40.html) ### NXP LPC diff --git a/hw/bsp/teensy_40/board.mk b/hw/bsp/teensy_40/board.mk index 4bfc48bb..955603e3 100644 --- a/hw/bsp/teensy_40/board.mk +++ b/hw/bsp/teensy_40/board.mk @@ -48,6 +48,7 @@ FREERTOS_PORT = ARM_CM7 JLINK_DEVICE = MIMXRT1062xxx6A JLINK_IF = swd -# flash by copying bin file to DAP Mass Storage -flash: $(BUILD)/$(BOARD)-firmware.bin - cp $< /media/$(USER)/RT1060-EVK/ +# flash by using teensy_loader_cli https://github.com/PaulStoffregen/teensy_loader_cli +# Make sure it is in your PATH +flash: $(BUILD)/$(BOARD)-firmware.hex + teensy_loader_cli --mcu=imxrt1062 -v -w $< diff --git a/hw/bsp/teensy_40/teensy40.c b/hw/bsp/teensy_40/teensy40.c index 9c905dbb..7c2bee53 100644 --- a/hw/bsp/teensy_40/teensy40.c +++ b/hw/bsp/teensy_40/teensy40.c @@ -78,7 +78,8 @@ void board_init(void) // Button IOMUXC_SetPinMux( BUTTON_PINMUX, 0U); - gpio_pin_config_t button_config = { kGPIO_DigitalInput, 0, kGPIO_IntRisingEdge, }; + IOMUXC_SetPinConfig(BUTTON_PINMUX, 0x01B0A0U); + gpio_pin_config_t button_config = { kGPIO_DigitalInput, 0, kGPIO_NoIntmode }; GPIO_PinInit(BUTTON_PORT, BUTTON_PIN, &button_config); // UART From dd6313a6ca13cb51288d205696d58ff74a434dfa Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 10 Jan 2020 00:28:46 +0700 Subject: [PATCH 193/267] added stm32f411 blackpill --- hw/bsp/feather_stm32f405/board.mk | 2 +- .../stm32f411blackpill/STM32F411CEUx_FLASH.ld | 169 ++++++++ hw/bsp/stm32f411blackpill/board.mk | 47 +++ .../stm32f411blackpill/stm32f411blackpill.c | 215 ++++++++++ .../stm32f411blackpill/stm32f4xx_hal_conf.h | 394 ++++++++++++++++++ hw/bsp/stm32f411disco/board.mk | 2 +- 6 files changed, 827 insertions(+), 2 deletions(-) create mode 100644 hw/bsp/stm32f411blackpill/STM32F411CEUx_FLASH.ld create mode 100644 hw/bsp/stm32f411blackpill/board.mk create mode 100644 hw/bsp/stm32f411blackpill/stm32f411blackpill.c create mode 100644 hw/bsp/stm32f411blackpill/stm32f4xx_hal_conf.h diff --git a/hw/bsp/feather_stm32f405/board.mk b/hw/bsp/feather_stm32f405/board.mk index ba84dd3a..5a007cad 100644 --- a/hw/bsp/feather_stm32f405/board.mk +++ b/hw/bsp/feather_stm32f405/board.mk @@ -46,6 +46,6 @@ JLINK_IF = swd # Path to STM32 Cube Programmer CLI, should be added into system path STM32Prog = STM32_Programmer_CLI -# flash target using on-board stlink +# flash target ROM bootloader flash: $(BUILD)/$(BOARD)-firmware.bin dfu-util -R -a 0 --dfuse-address 0x08000000 -D $< diff --git a/hw/bsp/stm32f411blackpill/STM32F411CEUx_FLASH.ld b/hw/bsp/stm32f411blackpill/STM32F411CEUx_FLASH.ld new file mode 100644 index 00000000..efea1e06 --- /dev/null +++ b/hw/bsp/stm32f411blackpill/STM32F411CEUx_FLASH.ld @@ -0,0 +1,169 @@ +/* +***************************************************************************** +** + +** File : LinkerScript.ld +** +** Abstract : Linker script for STM32F411CEUx Device with +** 512KByte FLASH, 128KByte RAM +** +** Set heap size, stack size and stack location according +** to application requirements. +** +** Set memory bank area and size if external memory is used. +** +** Target : STMicroelectronics STM32 +** +** +** Distribution: The file is distributed as is, without any warranty +** of any kind. +** +** (c)Copyright Ac6. +** You may use this file as-is or modify it according to the needs of your +** project. Distribution of this file (unmodified or modified) is not +** permitted. Ac6 permit registered System Workbench for MCU users the +** rights to distribute the assembled, compiled & linked contents of this +** file as part of an application binary file, provided that it is built +** using the System Workbench for MCU toolchain. +** +***************************************************************************** +*/ + +/* Entry Point */ +ENTRY(Reset_Handler) + +/* Highest address of the user mode stack */ +_estack = 0x20020000; /* end of RAM */ +/* Generate a link error if heap and stack don't fit into RAM */ +_Min_Heap_Size = 0x200;; /* required amount of heap */ +_Min_Stack_Size = 0x400;; /* required amount of stack */ + +/* Specify the memory areas */ +MEMORY +{ +FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 512K +RAM (xrw) : ORIGIN = 0x20000000, LENGTH = 128K +} + +/* Define output sections */ +SECTIONS +{ + /* The startup code goes first into FLASH */ + .isr_vector : + { + . = ALIGN(4); + KEEP(*(.isr_vector)) /* Startup code */ + . = ALIGN(4); + } >FLASH + + /* The program code and other data goes into FLASH */ + .text : + { + . = ALIGN(4); + *(.text) /* .text sections (code) */ + *(.text*) /* .text* sections (code) */ + *(.glue_7) /* glue arm to thumb code */ + *(.glue_7t) /* glue thumb to arm code */ + *(.eh_frame) + + KEEP (*(.init)) + KEEP (*(.fini)) + + . = ALIGN(4); + _etext = .; /* define a global symbols at end of code */ + } >FLASH + + /* Constant data goes into FLASH */ + .rodata : + { + . = ALIGN(4); + *(.rodata) /* .rodata sections (constants, strings, etc.) */ + *(.rodata*) /* .rodata* sections (constants, strings, etc.) */ + . = ALIGN(4); + } >FLASH + + .ARM.extab : { *(.ARM.extab* .gnu.linkonce.armextab.*) } >FLASH + .ARM : { + __exidx_start = .; + *(.ARM.exidx*) + __exidx_end = .; + } >FLASH + + .preinit_array : + { + PROVIDE_HIDDEN (__preinit_array_start = .); + KEEP (*(.preinit_array*)) + PROVIDE_HIDDEN (__preinit_array_end = .); + } >FLASH + .init_array : + { + PROVIDE_HIDDEN (__init_array_start = .); + KEEP (*(SORT(.init_array.*))) + KEEP (*(.init_array*)) + PROVIDE_HIDDEN (__init_array_end = .); + } >FLASH + .fini_array : + { + PROVIDE_HIDDEN (__fini_array_start = .); + KEEP (*(SORT(.fini_array.*))) + KEEP (*(.fini_array*)) + PROVIDE_HIDDEN (__fini_array_end = .); + } >FLASH + + /* used by the startup to initialize data */ + _sidata = LOADADDR(.data); + + /* Initialized data sections goes into RAM, load LMA copy after code */ + .data : + { + . = ALIGN(4); + _sdata = .; /* create a global symbol at data start */ + *(.data) /* .data sections */ + *(.data*) /* .data* sections */ + + . = ALIGN(4); + _edata = .; /* define a global symbol at data end */ + } >RAM AT> FLASH + + + /* Uninitialized data section */ + . = ALIGN(4); + .bss : + { + /* This is used by the startup in order to initialize the .bss secion */ + _sbss = .; /* define a global symbol at bss start */ + __bss_start__ = _sbss; + *(.bss) + *(.bss*) + *(COMMON) + + . = ALIGN(4); + _ebss = .; /* define a global symbol at bss end */ + __bss_end__ = _ebss; + } >RAM + + /* User_heap_stack section, used to check that there is enough RAM left */ + ._user_heap_stack : + { + . = ALIGN(4); + PROVIDE ( end = . ); + PROVIDE ( _end = . ); + . = . + _Min_Heap_Size; + . = . + _Min_Stack_Size; + . = ALIGN(4); + } >RAM + + + + /* Remove information from the standard libraries */ + /DISCARD/ : + { + libc.a ( * ) + libm.a ( * ) + libgcc.a ( * ) + } + + .ARM.attributes 0 : { *(.ARM.attributes) } +} + + diff --git a/hw/bsp/stm32f411blackpill/board.mk b/hw/bsp/stm32f411blackpill/board.mk new file mode 100644 index 00000000..36897607 --- /dev/null +++ b/hw/bsp/stm32f411blackpill/board.mk @@ -0,0 +1,47 @@ +CFLAGS += \ + -flto \ + -mthumb \ + -mabi=aapcs \ + -mcpu=cortex-m4 \ + -mfloat-abi=hard \ + -mfpu=fpv4-sp-d16 \ + -nostdlib -nostartfiles \ + -DSTM32F411xE \ + -DCFG_TUSB_MCU=OPT_MCU_STM32F4 + +ST_HAL_DRIVER = hw/mcu/st/st_driver/STM32F4xx_HAL_Driver +ST_CMSIS = hw/mcu/st/st_driver/CMSIS/Device/ST/STM32F4xx + +# All source paths should be relative to the top level. +LD_FILE = hw/bsp/$(BOARD)/STM32F411CEUx_FLASH.ld + +SRC_C += \ + $(ST_CMSIS)/Source/Templates/system_stm32f4xx.c \ + $(ST_HAL_DRIVER)/Src/stm32f4xx_hal.c \ + $(ST_HAL_DRIVER)/Src/stm32f4xx_hal_cortex.c \ + $(ST_HAL_DRIVER)/Src/stm32f4xx_hal_rcc.c \ + $(ST_HAL_DRIVER)/Src/stm32f4xx_hal_gpio.c + +SRC_S += \ + $(ST_CMSIS)/Source/Templates/gcc/startup_stm32f411xe.s + +INC += \ + $(TOP)/hw/mcu/st/st_driver/CMSIS/Include \ + $(TOP)/$(ST_CMSIS)/Include \ + $(TOP)/$(ST_HAL_DRIVER)/Inc \ + $(TOP)/hw/bsp/$(BOARD) + +# For TinyUSB port source +VENDOR = st +CHIP_FAMILY = synopsys + +# For freeRTOS port source +FREERTOS_PORT = ARM_CM4F + +# For flash-jlink target +JLINK_DEVICE = stm32f411ce +JLINK_IF = swd + +# flash target ROM bootloader +flash: $(BUILD)/$(BOARD)-firmware.bin + dfu-util -R -a 0 --dfuse-address 0x08000000 -D $< diff --git a/hw/bsp/stm32f411blackpill/stm32f411blackpill.c b/hw/bsp/stm32f411blackpill/stm32f411blackpill.c new file mode 100644 index 00000000..63a7b4c7 --- /dev/null +++ b/hw/bsp/stm32f411blackpill/stm32f411blackpill.c @@ -0,0 +1,215 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#include "../board.h" + +#include "stm32f4xx.h" +#include "stm32f4xx_hal_conf.h" + +#define LED_PORT GPIOC +#define LED_PIN GPIO_PIN_13 +#define LED_STATE_ON 1 + +#define BUTTON_PORT GPIOA +#define BUTTON_PIN GPIO_PIN_0 +#define BUTTON_STATE_ACTIVE 0 + +// enable all LED, Button, Uart, USB clock +static void all_rcc_clk_enable(void) +{ + __HAL_RCC_GPIOA_CLK_ENABLE(); // USB D+, D-, Button + __HAL_RCC_GPIOC_CLK_ENABLE(); // LED +} + +/** + * @brief System Clock Configuration + * The system Clock is configured as follow : + * System Clock source = PLL (HSE) + * SYSCLK(Hz) = 84000000 + * HCLK(Hz) = 84000000 + * AHB Prescaler = 1 + * APB1 Prescaler = 2 + * APB2 Prescaler = 1 + * HSE Frequency(Hz) = 8000000 + * PLL_M = 8 + * PLL_N = 336 + * PLL_P = 4 + * PLL_Q = 7 + * VDD(V) = 3.3 + * Main regulator output voltage = Scale2 mode + * Flash Latency(WS) = 2 + * @param None + * @retval None + */ +static void SystemClock_Config(void) +{ + RCC_ClkInitTypeDef RCC_ClkInitStruct; + RCC_OscInitTypeDef RCC_OscInitStruct; + + /* Enable Power Control clock */ + __HAL_RCC_PWR_CLK_ENABLE(); + + /* 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. */ + __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE2); + + /* Enable HSE Oscillator and activate PLL with HSE as source */ + 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; + RCC_OscInitStruct.PLL.PLLM = HSE_VALUE/1000000; + RCC_OscInitStruct.PLL.PLLN = 336; + RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV4; + RCC_OscInitStruct.PLL.PLLQ = 7; + HAL_RCC_OscConfig(&RCC_OscInitStruct); + + /* 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; + 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); +} + +void board_init(void) +{ +#if CFG_TUSB_OS == OPT_OS_NONE + // 1ms tick timer + SysTick_Config(SystemCoreClock / 1000); +#elif CFG_TUSB_OS == OPT_OS_FREERTOS + // If freeRTOS is used, IRQ priority is limit by max syscall ( smaller is higher ) + //NVIC_SetPriority(USB0_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY ); +#endif + + SystemClock_Config(); + SystemCoreClockUpdate(); + all_rcc_clk_enable(); + + GPIO_InitTypeDef GPIO_InitStruct; + + // LED + GPIO_InitStruct.Pin = LED_PIN; + GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; + GPIO_InitStruct.Pull = GPIO_PULLUP; + GPIO_InitStruct.Speed = GPIO_SPEED_FAST; + HAL_GPIO_Init(LED_PORT, &GPIO_InitStruct); + + board_led_write(false); + + // Button + GPIO_InitStruct.Pin = BUTTON_PIN; + GPIO_InitStruct.Mode = GPIO_MODE_INPUT; + GPIO_InitStruct.Pull = BUTTON_STATE_ACTIVE ? GPIO_PULLDOWN : GPIO_PULLUP; + GPIO_InitStruct.Speed = GPIO_SPEED_FAST; + HAL_GPIO_Init(BUTTON_PORT, &GPIO_InitStruct); + + /* Configure USB FS GPIOs */ + /* Configure USB D+ D- Pins */ + GPIO_InitStruct.Pin = GPIO_PIN_11 | GPIO_PIN_12; + GPIO_InitStruct.Speed = GPIO_SPEED_HIGH; + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Pull = GPIO_NOPULL; + GPIO_InitStruct.Alternate = GPIO_AF10_OTG_FS; + HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); + + /* Configure VBUS Pin */ + GPIO_InitStruct.Pin = GPIO_PIN_9; + GPIO_InitStruct.Mode = GPIO_MODE_INPUT; + GPIO_InitStruct.Pull = GPIO_NOPULL; + HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); + + /* This for ID line debug */ + GPIO_InitStruct.Pin = GPIO_PIN_10; + GPIO_InitStruct.Mode = GPIO_MODE_AF_OD; + GPIO_InitStruct.Pull = GPIO_PULLUP; + GPIO_InitStruct.Speed = GPIO_SPEED_HIGH; + GPIO_InitStruct.Alternate = GPIO_AF10_OTG_FS; + HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); + + // Enable USB OTG clock + __HAL_RCC_USB_OTG_FS_CLK_ENABLE(); + + // Blackpill doens't use VBUS sense (B device) + // explicitly disable it + USB_OTG_FS->GCCFG |= USB_OTG_GCCFG_NOVBUSSENS; + USB_OTG_FS->GCCFG &= ~USB_OTG_GCCFG_VBUSBSEN; + USB_OTG_FS->GCCFG &= ~USB_OTG_GCCFG_VBUSASEN; +} + +//--------------------------------------------------------------------+ +// Board porting API +//--------------------------------------------------------------------+ + +void board_led_write(bool state) +{ + HAL_GPIO_WritePin(LED_PORT, LED_PIN, state ? LED_STATE_ON : (1-LED_STATE_ON)); +} + +uint32_t board_button_read(void) +{ + return BUTTON_STATE_ACTIVE == HAL_GPIO_ReadPin(BUTTON_PORT, BUTTON_PIN); +} + +int board_uart_read(uint8_t* buf, int len) +{ + (void) buf; (void) len; + return 0; +} + +int board_uart_write(void const * buf, int len) +{ + (void) buf; (void) len; + return 0; +} + +#if CFG_TUSB_OS == OPT_OS_NONE +volatile uint32_t system_ticks = 0; +void SysTick_Handler (void) +{ + system_ticks++; +} + +uint32_t board_millis(void) +{ + return system_ticks; +} +#endif + +void HardFault_Handler (void) +{ + asm("bkpt"); +} + +// Required by __libc_init_array in startup code if we are compiling using +// -nostdlib/-nostartfiles. +void _init(void) +{ + +} diff --git a/hw/bsp/stm32f411blackpill/stm32f4xx_hal_conf.h b/hw/bsp/stm32f411blackpill/stm32f4xx_hal_conf.h new file mode 100644 index 00000000..bc6f34c5 --- /dev/null +++ b/hw/bsp/stm32f411blackpill/stm32f4xx_hal_conf.h @@ -0,0 +1,394 @@ +/** + ****************************************************************************** + * @file GPIO/GPIO_EXTI/Inc/stm32f4xx_hal_conf.h + * @author MCD Application Team + * @brief HAL configuration file + ****************************************************************************** + * @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 __STM32F4xx_HAL_CONF_H +#define __STM32F4xx_HAL_CONF_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ + +/* ########################## Module Selection ############################## */ +/** + * @brief This is the list of modules to be used in the HAL driver + */ +#define HAL_MODULE_ENABLED +/* #define HAL_ADC_MODULE_ENABLED */ +/* #define HAL_CAN_MODULE_ENABLED */ +/* #define HAL_CAN_LEGACY_MODULE_ENABLED */ +/* #define HAL_CRC_MODULE_ENABLED */ +/* #define HAL_CRYP_MODULE_ENABLED */ +/* #define HAL_DAC_MODULE_ENABLED */ +/* #define HAL_DCMI_MODULE_ENABLED */ +#define HAL_DMA_MODULE_ENABLED +/* #define HAL_DMA2D_MODULE_ENABLED */ +/* #define HAL_ETH_MODULE_ENABLED */ +#define HAL_FLASH_MODULE_ENABLED +/* #define HAL_NAND_MODULE_ENABLED */ +/* #define HAL_NOR_MODULE_ENABLED */ +/* #define HAL_PCCARD_MODULE_ENABLED */ +/* #define HAL_SRAM_MODULE_ENABLED */ +/* #define HAL_SDRAM_MODULE_ENABLED */ +/* #define HAL_HASH_MODULE_ENABLED */ +#define HAL_GPIO_MODULE_ENABLED +// #define HAL_I2C_MODULE_ENABLED +/* #define HAL_I2S_MODULE_ENABLED */ +/* #define HAL_IWDG_MODULE_ENABLED */ +/* #define HAL_LTDC_MODULE_ENABLED */ +#define HAL_PWR_MODULE_ENABLED +#define HAL_RCC_MODULE_ENABLED +/* #define HAL_RNG_MODULE_ENABLED */ +/* #define HAL_RTC_MODULE_ENABLED */ +/* #define HAL_SAI_MODULE_ENABLED */ +/* #define HAL_SD_MODULE_ENABLED */ +// #define HAL_SPI_MODULE_ENABLED +/* #define HAL_TIM_MODULE_ENABLED */ +/* #define HAL_UART_MODULE_ENABLED */ +/* #define HAL_USART_MODULE_ENABLED */ +/* #define HAL_IRDA_MODULE_ENABLED */ +/* #define HAL_SMARTCARD_MODULE_ENABLED */ +/* #define HAL_WWDG_MODULE_ENABLED */ +#define HAL_CORTEX_MODULE_ENABLED +/* #define HAL_PCD_MODULE_ENABLED */ +/* #define HAL_HCD_MODULE_ENABLED */ + + +/* ########################## HSE/HSI Values adaptation ##################### */ +/** + * @brief Adjust the value of External High Speed oscillator (HSE) used in your application. + * This value is used by the RCC HAL module to compute the system frequency + * (when HSE is used as system clock source, directly or through the PLL). + */ +#if !defined (HSE_VALUE) + #define HSE_VALUE (25000000U) /*!< Value of the External oscillator in Hz */ +#endif /* HSE_VALUE */ + +#if !defined (HSE_STARTUP_TIMEOUT) + #define HSE_STARTUP_TIMEOUT (100U) /*!< Time out for HSE start up, in ms */ +#endif /* HSE_STARTUP_TIMEOUT */ + +/** + * @brief Internal High Speed oscillator (HSI) value. + * This value is used by the RCC HAL module to compute the system frequency + * (when HSI is used as system clock source, directly or through the PLL). + */ +#if !defined (HSI_VALUE) + #define HSI_VALUE (16000000U) /*!< Value of the Internal oscillator in Hz*/ +#endif /* HSI_VALUE */ + +/** + * @brief Internal Low Speed oscillator (LSI) value. + */ +#if !defined (LSI_VALUE) + #define LSI_VALUE (32000U) +#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. + */ +#if !defined (LSE_VALUE) + #define LSE_VALUE (32768U) /*!< Value of the External Low Speed 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 */ + +/** + * @brief External clock source for I2S peripheral + * This value is used by the I2S HAL module to compute the I2S clock source + * frequency, this source is inserted directly through I2S_CKIN pad. + */ +#if !defined (EXTERNAL_CLOCK_VALUE) + #define EXTERNAL_CLOCK_VALUE (12288000U) /*!< Value of the External oscillator in Hz*/ +#endif /* EXTERNAL_CLOCK_VALUE */ + +/* 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. */ + +/* ########################### System Configuration ######################### */ +/** + * @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 INSTRUCTION_CACHE_ENABLE 1U +#define DATA_CACHE_ENABLE 1U + +#define USE_HAL_ADC_REGISTER_CALLBACKS 0U /* ADC register callback disabled */ +#define USE_HAL_CAN_REGISTER_CALLBACKS 0U /* CAN register callback disabled */ +#define USE_HAL_CEC_REGISTER_CALLBACKS 0U /* CEC register callback disabled */ +#define USE_HAL_CRYP_REGISTER_CALLBACKS 0U /* CRYP register callback disabled */ +#define USE_HAL_DAC_REGISTER_CALLBACKS 0U /* DAC register callback disabled */ +#define USE_HAL_DCMI_REGISTER_CALLBACKS 0U /* DCMI register callback disabled */ +#define USE_HAL_DFSDM_REGISTER_CALLBACKS 0U /* DFSDM register callback disabled */ +#define USE_HAL_DMA2D_REGISTER_CALLBACKS 0U /* DMA2D register callback disabled */ +#define USE_HAL_DSI_REGISTER_CALLBACKS 0U /* DSI register callback disabled */ +#define USE_HAL_ETH_REGISTER_CALLBACKS 0U /* ETH register callback disabled */ +#define USE_HAL_HASH_REGISTER_CALLBACKS 0U /* HASH register callback disabled */ +#define USE_HAL_HCD_REGISTER_CALLBACKS 0U /* HCD register callback disabled */ +#define USE_HAL_I2C_REGISTER_CALLBACKS 0U /* I2C register callback disabled */ +#define USE_HAL_FMPI2C_REGISTER_CALLBACKS 0U /* FMPI2C register callback disabled */ +#define USE_HAL_I2S_REGISTER_CALLBACKS 0U /* I2S register callback disabled */ +#define USE_HAL_IRDA_REGISTER_CALLBACKS 0U /* IRDA register callback disabled */ +#define USE_HAL_LPTIM_REGISTER_CALLBACKS 0U /* LPTIM register callback disabled */ +#define USE_HAL_LTDC_REGISTER_CALLBACKS 0U /* LTDC register callback disabled */ +#define USE_HAL_MMC_REGISTER_CALLBACKS 0U /* MMC register callback disabled */ +#define USE_HAL_NAND_REGISTER_CALLBACKS 0U /* NAND register callback disabled */ +#define USE_HAL_NOR_REGISTER_CALLBACKS 0U /* NOR register callback disabled */ +#define USE_HAL_PCCARD_REGISTER_CALLBACKS 0U /* PCCARD register callback disabled */ +#define USE_HAL_PCD_REGISTER_CALLBACKS 0U /* PCD register callback disabled */ +#define USE_HAL_QSPI_REGISTER_CALLBACKS 0U /* QSPI register callback disabled */ +#define USE_HAL_RNG_REGISTER_CALLBACKS 0U /* RNG register callback disabled */ +#define USE_HAL_RTC_REGISTER_CALLBACKS 0U /* RTC register callback disabled */ +#define USE_HAL_SAI_REGISTER_CALLBACKS 0U /* SAI register callback disabled */ +#define USE_HAL_SD_REGISTER_CALLBACKS 0U /* SD register callback disabled */ +#define USE_HAL_SMARTCARD_REGISTER_CALLBACKS 0U /* SMARTCARD register callback disabled */ +#define USE_HAL_SDRAM_REGISTER_CALLBACKS 0U /* SDRAM register callback disabled */ +#define USE_HAL_SRAM_REGISTER_CALLBACKS 0U /* SRAM register callback disabled */ +#define USE_HAL_SPDIFRX_REGISTER_CALLBACKS 0U /* SPDIFRX register callback disabled */ +#define USE_HAL_SMBUS_REGISTER_CALLBACKS 0U /* SMBUS register callback disabled */ +#define USE_HAL_SPI_REGISTER_CALLBACKS 0U /* SPI register callback disabled */ +#define USE_HAL_TIM_REGISTER_CALLBACKS 0U /* TIM register callback disabled */ +#define USE_HAL_UART_REGISTER_CALLBACKS 0U /* UART register callback disabled */ +#define USE_HAL_USART_REGISTER_CALLBACKS 0U /* USART register callback disabled */ +#define USE_HAL_WWDG_REGISTER_CALLBACKS 0U /* WWDG register callback disabled */ + +/* ########################## Assert Selection ############################## */ +/** + * @brief Uncomment the line below to expanse the "assert_param" macro in the + * HAL drivers code + */ +/* #define USE_FULL_ASSERT 1U */ + +/* ################## 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 ------------------------------------------------------------------*/ +/** + * @brief Include module's header file + */ + +#ifdef HAL_RCC_MODULE_ENABLED + #include "stm32f4xx_hal_rcc.h" +#endif /* HAL_RCC_MODULE_ENABLED */ + +#ifdef HAL_GPIO_MODULE_ENABLED + #include "stm32f4xx_hal_gpio.h" +#endif /* HAL_GPIO_MODULE_ENABLED */ + +#ifdef HAL_DMA_MODULE_ENABLED + #include "stm32f4xx_hal_dma.h" +#endif /* HAL_DMA_MODULE_ENABLED */ + +#ifdef HAL_CORTEX_MODULE_ENABLED + #include "stm32f4xx_hal_cortex.h" +#endif /* HAL_CORTEX_MODULE_ENABLED */ + +#ifdef HAL_ADC_MODULE_ENABLED + #include "stm32f4xx_hal_adc.h" +#endif /* HAL_ADC_MODULE_ENABLED */ + +#ifdef HAL_CAN_MODULE_ENABLED + #include "stm32f4xx_hal_can.h" +#endif /* HAL_CAN_MODULE_ENABLED */ + +#ifdef HAL_CAN_LEGACY_MODULE_ENABLED + #include "stm32f4xx_hal_can_legacy.h" +#endif /* HAL_CAN_LEGACY_MODULE_ENABLED */ + +#ifdef HAL_CRC_MODULE_ENABLED + #include "stm32f4xx_hal_crc.h" +#endif /* HAL_CRC_MODULE_ENABLED */ + +#ifdef HAL_CRYP_MODULE_ENABLED + #include "stm32f4xx_hal_cryp.h" +#endif /* HAL_CRYP_MODULE_ENABLED */ + +#ifdef HAL_DMA2D_MODULE_ENABLED + #include "stm32f4xx_hal_dma2d.h" +#endif /* HAL_DMA2D_MODULE_ENABLED */ + +#ifdef HAL_DAC_MODULE_ENABLED + #include "stm32f4xx_hal_dac.h" +#endif /* HAL_DAC_MODULE_ENABLED */ + +#ifdef HAL_DCMI_MODULE_ENABLED + #include "stm32f4xx_hal_dcmi.h" +#endif /* HAL_DCMI_MODULE_ENABLED */ + +#ifdef HAL_ETH_MODULE_ENABLED + #include "stm32f4xx_hal_eth.h" +#endif /* HAL_ETH_MODULE_ENABLED */ + +#ifdef HAL_FLASH_MODULE_ENABLED + #include "stm32f4xx_hal_flash.h" +#endif /* HAL_FLASH_MODULE_ENABLED */ + +#ifdef HAL_SRAM_MODULE_ENABLED + #include "stm32f4xx_hal_sram.h" +#endif /* HAL_SRAM_MODULE_ENABLED */ + +#ifdef HAL_NOR_MODULE_ENABLED + #include "stm32f4xx_hal_nor.h" +#endif /* HAL_NOR_MODULE_ENABLED */ + +#ifdef HAL_NAND_MODULE_ENABLED + #include "stm32f4xx_hal_nand.h" +#endif /* HAL_NAND_MODULE_ENABLED */ + +#ifdef HAL_PCCARD_MODULE_ENABLED + #include "stm32f4xx_hal_pccard.h" +#endif /* HAL_PCCARD_MODULE_ENABLED */ + +#ifdef HAL_SDRAM_MODULE_ENABLED + #include "stm32f4xx_hal_sdram.h" +#endif /* HAL_SDRAM_MODULE_ENABLED */ + +#ifdef HAL_HASH_MODULE_ENABLED + #include "stm32f4xx_hal_hash.h" +#endif /* HAL_HASH_MODULE_ENABLED */ + +#ifdef HAL_I2C_MODULE_ENABLED + #include "stm32f4xx_hal_i2c.h" +#endif /* HAL_I2C_MODULE_ENABLED */ + +#ifdef HAL_I2S_MODULE_ENABLED + #include "stm32f4xx_hal_i2s.h" +#endif /* HAL_I2S_MODULE_ENABLED */ + +#ifdef HAL_IWDG_MODULE_ENABLED + #include "stm32f4xx_hal_iwdg.h" +#endif /* HAL_IWDG_MODULE_ENABLED */ + +#ifdef HAL_LTDC_MODULE_ENABLED + #include "stm32f4xx_hal_ltdc.h" +#endif /* HAL_LTDC_MODULE_ENABLED */ + +#ifdef HAL_PWR_MODULE_ENABLED + #include "stm32f4xx_hal_pwr.h" +#endif /* HAL_PWR_MODULE_ENABLED */ + +#ifdef HAL_RNG_MODULE_ENABLED + #include "stm32f4xx_hal_rng.h" +#endif /* HAL_RNG_MODULE_ENABLED */ + +#ifdef HAL_RTC_MODULE_ENABLED + #include "stm32f4xx_hal_rtc.h" +#endif /* HAL_RTC_MODULE_ENABLED */ + +#ifdef HAL_SAI_MODULE_ENABLED + #include "stm32f4xx_hal_sai.h" +#endif /* HAL_SAI_MODULE_ENABLED */ + +#ifdef HAL_SD_MODULE_ENABLED + #include "stm32f4xx_hal_sd.h" +#endif /* HAL_SD_MODULE_ENABLED */ + +#ifdef HAL_SPI_MODULE_ENABLED + #include "stm32f4xx_hal_spi.h" +#endif /* HAL_SPI_MODULE_ENABLED */ + +#ifdef HAL_TIM_MODULE_ENABLED + #include "stm32f4xx_hal_tim.h" +#endif /* HAL_TIM_MODULE_ENABLED */ + +#ifdef HAL_UART_MODULE_ENABLED + #include "stm32f4xx_hal_uart.h" +#endif /* HAL_UART_MODULE_ENABLED */ + +#ifdef HAL_USART_MODULE_ENABLED + #include "stm32f4xx_hal_usart.h" +#endif /* HAL_USART_MODULE_ENABLED */ + +#ifdef HAL_IRDA_MODULE_ENABLED + #include "stm32f4xx_hal_irda.h" +#endif /* HAL_IRDA_MODULE_ENABLED */ + +#ifdef HAL_SMARTCARD_MODULE_ENABLED + #include "stm32f4xx_hal_smartcard.h" +#endif /* HAL_SMARTCARD_MODULE_ENABLED */ + +#ifdef HAL_WWDG_MODULE_ENABLED + #include "stm32f4xx_hal_wwdg.h" +#endif /* HAL_WWDG_MODULE_ENABLED */ + +#ifdef HAL_PCD_MODULE_ENABLED + #include "stm32f4xx_hal_pcd.h" +#endif /* HAL_PCD_MODULE_ENABLED */ + +#ifdef HAL_HCD_MODULE_ENABLED + #include "stm32f4xx_hal_hcd.h" +#endif /* HAL_HCD_MODULE_ENABLED */ + +/* Exported macro ------------------------------------------------------------*/ +#ifdef USE_FULL_ASSERT +/** + * @brief The assert_param macro is used for function's parameters check. + * @param expr: If expr is false, it calls assert_failed function + * which reports the name of the source file and the source + * line number of the call that failed. + * If expr is true, it returns no value. + * @retval None + */ + #define assert_param(expr) ((expr) ? (void)0U : assert_failed((uint8_t *)__FILE__, __LINE__)) +/* Exported functions ------------------------------------------------------- */ + void assert_failed(uint8_t* file, uint32_t line); +#else + #define assert_param(expr) ((void)0U) +#endif /* USE_FULL_ASSERT */ + + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32F4xx_HAL_CONF_H */ + + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/hw/bsp/stm32f411disco/board.mk b/hw/bsp/stm32f411disco/board.mk index 5cbe0524..eb571474 100644 --- a/hw/bsp/stm32f411disco/board.mk +++ b/hw/bsp/stm32f411disco/board.mk @@ -39,7 +39,7 @@ CHIP_FAMILY = synopsys FREERTOS_PORT = ARM_CM4F # For flash-jlink target -JLINK_DEVICE = stm32f41ve +JLINK_DEVICE = stm32f411ve JLINK_IF = swd # Path to STM32 Cube Programmer CLI, should be added into system path From 33723157a46685e678177058a9c0695ae8f571e1 Mon Sep 17 00:00:00 2001 From: arturo182 Date: Fri, 10 Jan 2020 00:34:12 +0100 Subject: [PATCH 194/267] Fix some style issues in the README --- README.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index eabf924b..29052d01 100644 --- a/README.md +++ b/README.md @@ -23,12 +23,12 @@ TinyUSB is an open-source cross-platform USB Host/Device stack for embedded syst ## Contributors -Special thanks for all the people who had spent their precious time and effort to helped this project so far. Check out +Special thanks to all the people who spent their precious time and effort to help this project so far. Check out the [CONTRIBUTORS.md](CONTRIBUTORS.md) file for the list of all contributors and their awesome work for the stack. ## Supported MCUs -The stack supports the following MCUs +The stack supports the following MCUs: - **MicroChip:** SAMD21, SAMD51 (device only) - **Nordic:** nRF52840, nRF52833 @@ -44,7 +44,7 @@ The stack supports the following MCUs ## Device Stack -Support multiple device configurations by dynamically changing usb descriptors. Low power functions such as suspend, resume and remote wakeup. Following device classes are supported: +Supports multiple device configurations by dynamically changing usb descriptors. Low power functions such like suspend, resume, and remote wakeup. Following device classes are supported: - Communication Class (CDC) - Human Interface Device (HID): Generic (In & Out), Keyboard, Mouse, Gamepad etc ... @@ -59,11 +59,11 @@ Support multiple device configurations by dynamically changing usb descriptors. - Human Interface Device (HID): Keyboard, Mouse, Generic - Mass Storage Class (MSC) -- Hub currently only support 1 level of hub (due to my laziness) +- Hub currently only supports 1 level of hub (due to my laziness) -## OS Abtraction layer +## OS Abstraction layer -TinyUSB is completely thread-safe by pushing all ISR events into a central queue, then process it later in the non-ISR context task function. It also uses semphore/mutex to access shared resource such as CDC FIFO. Therefore the stack needs to use some of OS's basic APIs. Following OSes are already supported out of the box. +TinyUSB is completely thread-safe by pushing all ISR events into a central queue, then process it later in the non-ISR context task function. It also uses semaphore/mutex to access shared resources such as CDC FIFO. Therefore the stack needs to use some of OS's basic APIs. Following OSes are already supported out of the box. - **No OS** : Disabling USB IRQ is used as way to provide mutex - **FreeRTOS** @@ -71,11 +71,11 @@ TinyUSB is completely thread-safe by pushing all ISR events into a central queue ## Compiler & IDE -The stack is developed with GCC compiler, and should be compilable with others. Folder `examples` provide Makefile and Segger Embedded Studio build support. [Here is instruction to build example](examples/readme.md). +The stack is developed with GCC compiler and should be compilable with others. The `examples` folder provides Makefile and Segger Embedded Studio build support. [Here are example build instructions](examples/readme.md). ## Getting Started -[Here is the details for getting started](docs/getting_started.md) with the stack. +[Here are the details for getting started](docs/getting_started.md) with the stack. ## Porting @@ -83,7 +83,7 @@ Want to help add TinyUSB support for a new MCU? Read [here](docs/porting.md) for ## License -MIT license for all TinyUSB sources `src` folder, [Full license is here](LICENSE). However each file is individually licensed especially those in `lib` and `hw/mcu` folder. Please make sure you understand all the license term for files you use in your project. +MIT license for all TinyUSB sources `src` folder, [Full license is here](LICENSE). However, each file is individually licensed especially those in `lib` and `hw/mcu` folder. Please make sure you understand all the license term for files you use in your project. ## Uses @@ -96,4 +96,4 @@ TinyUSB is currently used by these other projects: * [MicroPython](https://github.com/micropython/micropython) * [TinyUSB Arduino Library](https://github.com/adafruit/Adafruit_TinyUSB_Arduino) -Let's me know if your project also uses TinyUSB and want to share. +Let me know if your project also uses TinyUSB and want to share. From 67d88a83488bee3bef2ab186e5bd1f02403a48ab Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 10 Jan 2020 15:00:46 +0700 Subject: [PATCH 195/267] add generic flash-stlink --- examples/rules.mk | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/examples/rules.mk b/examples/rules.mk index 8f0e415a..2969a66f 100644 --- a/examples/rules.mk +++ b/examples/rules.mk @@ -109,7 +109,7 @@ size: $(BUILD)/$(BOARD)-firmware.elf clean: rm -rf $(BUILD) - + # Flash binary using Jlink ifeq ($(OS),Windows_NT) JLINKEXE = JLink.exe @@ -125,3 +125,7 @@ flash-jlink: $(BUILD)/$(BOARD)-firmware.hex @echo go >> $(BUILD)/$(BOARD).jlink @echo exit >> $(BUILD)/$(BOARD).jlink $(JLINKEXE) -device $(JLINK_DEVICE) -if $(JLINK_IF) -JTAGConf -1,-1 -speed auto -CommandFile $(BUILD)/$(BOARD).jlink + +# flash STM32 MCU using stlink with STM32 Cube Programmer CLI +flash-stlink: $(BUILD)/$(BOARD)-firmware.elf + STM32_Programmer_CLI --connect port=swd --write $< --go From 04cf337b792a0777b92c63725323898b66f6fbd2 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 10 Jan 2020 15:09:59 +0700 Subject: [PATCH 196/267] clean up flash-stlink --- hw/bsp/pyboardv11/board.mk | 6 +----- hw/bsp/stm32f070rbnucleo/board.mk | 6 +----- hw/bsp/stm32f072disco/board.mk | 6 +----- hw/bsp/stm32f207nucleo/board.mk | 6 +----- hw/bsp/stm32f303disco/board.mk | 6 +----- hw/bsp/stm32f407disco/board.mk | 6 +----- hw/bsp/stm32f411disco/board.mk | 6 +----- hw/bsp/stm32f412disco/board.mk | 6 +----- hw/bsp/stm32f767nucleo/board.mk | 6 +----- hw/bsp/stm32h743nucleo/board.mk | 6 +----- 10 files changed, 10 insertions(+), 50 deletions(-) diff --git a/hw/bsp/pyboardv11/board.mk b/hw/bsp/pyboardv11/board.mk index f57f662f..a0b07f26 100644 --- a/hw/bsp/pyboardv11/board.mk +++ b/hw/bsp/pyboardv11/board.mk @@ -42,9 +42,5 @@ FREERTOS_PORT = ARM_CM4F JLINK_DEVICE = stm32f405rg JLINK_IF = swd -# Path to STM32 Cube Programmer CLI, should be added into system path -STM32Prog = STM32_Programmer_CLI - # flash target using on-board stlink -flash: $(BUILD)/$(BOARD)-firmware.elf - $(STM32Prog) --connect port=swd --write $< --go +flash: flash-stlink diff --git a/hw/bsp/stm32f070rbnucleo/board.mk b/hw/bsp/stm32f070rbnucleo/board.mk index 07d885dc..8a073d52 100644 --- a/hw/bsp/stm32f070rbnucleo/board.mk +++ b/hw/bsp/stm32f070rbnucleo/board.mk @@ -46,9 +46,5 @@ FREERTOS_PORT = ARM_CM0 JLINK_DEVICE = stm32f070rb JLINK_IF = swd -# Path to STM32 Cube Programmer CLI, should be added into system path -STM32Prog = STM32_Programmer_CLI - # flash target using on-board stlink -flash: $(BUILD)/$(BOARD)-firmware.elf - $(STM32Prog) --connect port=swd --write $< --go +flash: flash-stlink diff --git a/hw/bsp/stm32f072disco/board.mk b/hw/bsp/stm32f072disco/board.mk index cae3b562..522459d6 100644 --- a/hw/bsp/stm32f072disco/board.mk +++ b/hw/bsp/stm32f072disco/board.mk @@ -47,9 +47,5 @@ FREERTOS_PORT = ARM_CM0 JLINK_DEVICE = stm32f072rb JLINK_IF = swd -# Path to STM32 Cube Programmer CLI, should be added into system path -STM32Prog = STM32_Programmer_CLI - # flash target using on-board stlink -flash: $(BUILD)/$(BOARD)-firmware.elf - $(STM32Prog) --connect port=swd --write $< --go +flash: flash-stlink diff --git a/hw/bsp/stm32f207nucleo/board.mk b/hw/bsp/stm32f207nucleo/board.mk index 2eb92f17..9eaff854 100644 --- a/hw/bsp/stm32f207nucleo/board.mk +++ b/hw/bsp/stm32f207nucleo/board.mk @@ -45,9 +45,5 @@ FREERTOS_PORT = ARM_CM3 JLINK_DEVICE = stm32f207zg JLINK_IF = swd -# Path to STM32 Cube Programmer CLI, should be added into system path -STM32Prog = STM32_Programmer_CLI - # flash target using on-board stlink -flash: $(BUILD)/$(BOARD)-firmware.elf - $(STM32Prog) --connect port=swd --write $< --go +flash: flash-stlink diff --git a/hw/bsp/stm32f303disco/board.mk b/hw/bsp/stm32f303disco/board.mk index 61c85103..07312ac8 100644 --- a/hw/bsp/stm32f303disco/board.mk +++ b/hw/bsp/stm32f303disco/board.mk @@ -46,9 +46,5 @@ FREERTOS_PORT = ARM_CM4F JLINK_DEVICE = stm32f303vc JLINK_IF = swd -# Path to STM32 Cube Programmer CLI, should be added into system path -STM32Prog = STM32_Programmer_CLI - # flash target using on-board stlink -flash: $(BUILD)/$(BOARD)-firmware.elf - $(STM32Prog) --connect port=swd --write $< --go +flash: flash-stlink diff --git a/hw/bsp/stm32f407disco/board.mk b/hw/bsp/stm32f407disco/board.mk index e80e84bc..9800b9cb 100644 --- a/hw/bsp/stm32f407disco/board.mk +++ b/hw/bsp/stm32f407disco/board.mk @@ -42,9 +42,5 @@ FREERTOS_PORT = ARM_CM4F JLINK_DEVICE = stm32f407vg JLINK_IF = swd -# Path to STM32 Cube Programmer CLI, should be added into system path -STM32Prog = STM32_Programmer_CLI - # flash target using on-board stlink -flash: $(BUILD)/$(BOARD)-firmware.elf - $(STM32Prog) --connect port=swd --write $< --go +flash: flash-stlink diff --git a/hw/bsp/stm32f411disco/board.mk b/hw/bsp/stm32f411disco/board.mk index eb571474..16d90e08 100644 --- a/hw/bsp/stm32f411disco/board.mk +++ b/hw/bsp/stm32f411disco/board.mk @@ -42,9 +42,5 @@ FREERTOS_PORT = ARM_CM4F JLINK_DEVICE = stm32f411ve JLINK_IF = swd -# Path to STM32 Cube Programmer CLI, should be added into system path -STM32Prog = STM32_Programmer_CLI - # flash target using on-board stlink -flash: $(BUILD)/$(BOARD)-firmware.elf - $(STM32Prog) --connect port=swd --write $< --go +flash: flash-stlink diff --git a/hw/bsp/stm32f412disco/board.mk b/hw/bsp/stm32f412disco/board.mk index 9b54ab55..2976464f 100644 --- a/hw/bsp/stm32f412disco/board.mk +++ b/hw/bsp/stm32f412disco/board.mk @@ -46,9 +46,5 @@ FREERTOS_PORT = ARM_CM4F JLINK_DEVICE = stm32f41zx JLINK_IF = swd -# Path to STM32 Cube Programmer CLI, should be added into system path -STM32Prog = STM32_Programmer_CLI - # flash target using on-board stlink -flash: $(BUILD)/$(BOARD)-firmware.elf - $(STM32Prog) --connect port=swd --write $< --go +flash: flash-stlink diff --git a/hw/bsp/stm32f767nucleo/board.mk b/hw/bsp/stm32f767nucleo/board.mk index 152e0bdb..8d733b9b 100644 --- a/hw/bsp/stm32f767nucleo/board.mk +++ b/hw/bsp/stm32f767nucleo/board.mk @@ -41,9 +41,5 @@ INC += \ VENDOR = st CHIP_FAMILY = synopsys -# Path to STM32 Cube Programmer CLI, should be added into system path -STM32Prog = STM32_Programmer_CLI - # flash target using on-board stlink -flash: $(BUILD)/$(BOARD)-firmware.elf - $(STM32Prog) --connect port=swd --write $< --go +flash: flash-stlink diff --git a/hw/bsp/stm32h743nucleo/board.mk b/hw/bsp/stm32h743nucleo/board.mk index 928ad9a8..a45c667d 100644 --- a/hw/bsp/stm32h743nucleo/board.mk +++ b/hw/bsp/stm32h743nucleo/board.mk @@ -40,9 +40,5 @@ INC += \ VENDOR = st CHIP_FAMILY = synopsys -# Path to STM32 Cube Programmer CLI, should be added into system path -STM32Prog = STM32_Programmer_CLI - # flash target using on-board stlink -flash: $(BUILD)/$(BOARD)-firmware.elf - $(STM32Prog) --connect port=swd --write $< --go +flash: flash-stlink From 4494720dbc6444f31f29000c0c39c49180d591b6 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 10 Jan 2020 15:10:16 +0700 Subject: [PATCH 197/267] clean up HSE_VALUE for stm32 --- hw/bsp/feather_stm32f405/feather_stm32f405.c | 4 ++-- hw/bsp/pyboardv11/pyboardv11.c | 4 ++-- hw/bsp/stm32f207nucleo/stm32f207nucleo.c | 4 ++-- hw/bsp/stm32f407disco/stm32f407disco.c | 4 ++-- hw/bsp/stm32f411blackpill/stm32f411blackpill.c | 4 ++-- hw/bsp/stm32f411disco/stm32f411disco.c | 4 ++-- hw/bsp/stm32f412disco/stm32f412disco.c | 4 ++-- hw/bsp/stm32f767nucleo/stm32f767nucleo.c | 4 ++-- hw/bsp/stm32h743nucleo/stm32h743nucleo.c | 2 +- 9 files changed, 17 insertions(+), 17 deletions(-) diff --git a/hw/bsp/feather_stm32f405/feather_stm32f405.c b/hw/bsp/feather_stm32f405/feather_stm32f405.c index e8b15b51..16036750 100644 --- a/hw/bsp/feather_stm32f405/feather_stm32f405.c +++ b/hw/bsp/feather_stm32f405/feather_stm32f405.c @@ -67,7 +67,7 @@ static void all_rcc_clk_enable(void) * APB1 Prescaler = 4 * APB2 Prescaler = 2 * HSE Frequency(Hz) = 12000000 - * PLL_M = 12 + * PLL_M = HSE_VALUE/1000000 * PLL_N = 336 * PLL_P = 2 * PLL_Q = 7 @@ -95,7 +95,7 @@ static void SystemClock_Config(void) RCC_OscInitStruct.HSEState = RCC_HSE_ON; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; - RCC_OscInitStruct.PLL.PLLM = 12; + RCC_OscInitStruct.PLL.PLLM = HSE_VALUE/1000000; RCC_OscInitStruct.PLL.PLLN = 336; RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2; RCC_OscInitStruct.PLL.PLLQ = 7; diff --git a/hw/bsp/pyboardv11/pyboardv11.c b/hw/bsp/pyboardv11/pyboardv11.c index 7452eef7..aa8301b4 100644 --- a/hw/bsp/pyboardv11/pyboardv11.c +++ b/hw/bsp/pyboardv11/pyboardv11.c @@ -56,7 +56,7 @@ static void all_rcc_clk_enable(void) * APB1 Prescaler = 4 * APB2 Prescaler = 2 * HSE Frequency(Hz) = 12000000 - * PLL_M = 12 + * PLL_M = HSE_VALUE/1000000 * PLL_N = 336 * PLL_P = 2 * PLL_Q = 7 @@ -84,7 +84,7 @@ static void SystemClock_Config(void) RCC_OscInitStruct.HSEState = RCC_HSE_ON; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; - RCC_OscInitStruct.PLL.PLLM = 12; + RCC_OscInitStruct.PLL.PLLM = HSE_VALUE/1000000; RCC_OscInitStruct.PLL.PLLN = 336; RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2; RCC_OscInitStruct.PLL.PLLQ = 7; diff --git a/hw/bsp/stm32f207nucleo/stm32f207nucleo.c b/hw/bsp/stm32f207nucleo/stm32f207nucleo.c index a09f26cf..178c0e8c 100644 --- a/hw/bsp/stm32f207nucleo/stm32f207nucleo.c +++ b/hw/bsp/stm32f207nucleo/stm32f207nucleo.c @@ -56,7 +56,7 @@ static void all_rcc_clk_enable(void) * APB1 Prescaler = 4 * APB2 Prescaler = 2 * HSE Frequency(Hz) = 8000000 - * PLL_M = 8 + * PLL_M = HSE_VALUE/1000000 * PLL_N = 240 * PLL_P = 2 * PLL_Q = 5 @@ -75,7 +75,7 @@ void SystemClock_Config(void) RCC_OscInitStruct.HSEState = RCC_HSE_BYPASS; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; - RCC_OscInitStruct.PLL.PLLM = 8; + RCC_OscInitStruct.PLL.PLLM = HSE_VALUE/1000000; RCC_OscInitStruct.PLL.PLLN = 240; RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2; RCC_OscInitStruct.PLL.PLLQ = 5; diff --git a/hw/bsp/stm32f407disco/stm32f407disco.c b/hw/bsp/stm32f407disco/stm32f407disco.c index 42cb613c..88d50efd 100644 --- a/hw/bsp/stm32f407disco/stm32f407disco.c +++ b/hw/bsp/stm32f407disco/stm32f407disco.c @@ -55,7 +55,7 @@ static void all_rcc_clk_enable(void) * APB1 Prescaler = 4 * APB2 Prescaler = 2 * HSE Frequency(Hz) = 8000000 - * PLL_M = 8 + * PLL_M = HSE_VALUE/1000000 * PLL_N = 336 * PLL_P = 2 * PLL_Q = 7 @@ -83,7 +83,7 @@ static void SystemClock_Config(void) RCC_OscInitStruct.HSEState = RCC_HSE_ON; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; - RCC_OscInitStruct.PLL.PLLM = 8; + RCC_OscInitStruct.PLL.PLLM = HSE_VALUE/1000000; RCC_OscInitStruct.PLL.PLLN = 336; RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2; RCC_OscInitStruct.PLL.PLLQ = 7; diff --git a/hw/bsp/stm32f411blackpill/stm32f411blackpill.c b/hw/bsp/stm32f411blackpill/stm32f411blackpill.c index 63a7b4c7..1fc5bb56 100644 --- a/hw/bsp/stm32f411blackpill/stm32f411blackpill.c +++ b/hw/bsp/stm32f411blackpill/stm32f411blackpill.c @@ -53,8 +53,8 @@ static void all_rcc_clk_enable(void) * AHB Prescaler = 1 * APB1 Prescaler = 2 * APB2 Prescaler = 1 - * HSE Frequency(Hz) = 8000000 - * PLL_M = 8 + * HSE Frequency(Hz) = 25000000 + * PLL_M = HSE_VALUE/1000000 * PLL_N = 336 * PLL_P = 4 * PLL_Q = 7 diff --git a/hw/bsp/stm32f411disco/stm32f411disco.c b/hw/bsp/stm32f411disco/stm32f411disco.c index 9d9c3071..04e211f2 100644 --- a/hw/bsp/stm32f411disco/stm32f411disco.c +++ b/hw/bsp/stm32f411disco/stm32f411disco.c @@ -54,7 +54,7 @@ static void all_rcc_clk_enable(void) * APB1 Prescaler = 2 * APB2 Prescaler = 1 * HSE Frequency(Hz) = 8000000 - * PLL_M = 8 + * PLL_M = HSE_VALUE/1000000 * PLL_N = 336 * PLL_P = 4 * PLL_Q = 7 @@ -82,7 +82,7 @@ static void SystemClock_Config(void) RCC_OscInitStruct.HSEState = RCC_HSE_ON; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; - RCC_OscInitStruct.PLL.PLLM = 8; + RCC_OscInitStruct.PLL.PLLM = HSE_VALUE/1000000; RCC_OscInitStruct.PLL.PLLN = 336; RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV4; RCC_OscInitStruct.PLL.PLLQ = 7; diff --git a/hw/bsp/stm32f412disco/stm32f412disco.c b/hw/bsp/stm32f412disco/stm32f412disco.c index 10778bcf..97291d8b 100644 --- a/hw/bsp/stm32f412disco/stm32f412disco.c +++ b/hw/bsp/stm32f412disco/stm32f412disco.c @@ -56,7 +56,7 @@ static void all_rcc_clk_enable(void) * APB1 Prescaler = 2 * APB2 Prescaler = 1 * HSE Frequency(Hz) = 8000000 - * PLL_M = 8 + * PLL_M = HSE_VALUE/1000000 * PLL_N = 200 * PLL_P = 2 * PLL_Q = 7 @@ -91,7 +91,7 @@ static void SystemClock_Config(void) RCC_OscInitStruct.HSEState = RCC_HSE_ON; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; - RCC_OscInitStruct.PLL.PLLM = 8; + RCC_OscInitStruct.PLL.PLLM = HSE_VALUE/1000000; RCC_OscInitStruct.PLL.PLLN = 200; RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2; RCC_OscInitStruct.PLL.PLLQ = 7; diff --git a/hw/bsp/stm32f767nucleo/stm32f767nucleo.c b/hw/bsp/stm32f767nucleo/stm32f767nucleo.c index 7367c56b..228fd6e5 100644 --- a/hw/bsp/stm32f767nucleo/stm32f767nucleo.c +++ b/hw/bsp/stm32f767nucleo/stm32f767nucleo.c @@ -66,7 +66,7 @@ static void all_rcc_clk_enable(void) * APB1 Prescaler = 4 * APB2 Prescaler = 2 * HSE Frequency(Hz) = 8000000 - * PLL_M = 8 + * PLL_M = HSE_VALUE/1000000 * PLL_N = 432 * PLL_P = 2 * PLL_Q = 9 @@ -99,7 +99,7 @@ void SystemClock_Config(void) RCC_OscInitStruct.HSEState = RCC_HSE_ON; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; - RCC_OscInitStruct.PLL.PLLM = 8; + RCC_OscInitStruct.PLL.PLLM = HSE_VALUE/1000000; RCC_OscInitStruct.PLL.PLLN = 432; RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2; RCC_OscInitStruct.PLL.PLLQ = 9; diff --git a/hw/bsp/stm32h743nucleo/stm32h743nucleo.c b/hw/bsp/stm32h743nucleo/stm32h743nucleo.c index b7071ed6..022827f5 100644 --- a/hw/bsp/stm32h743nucleo/stm32h743nucleo.c +++ b/hw/bsp/stm32h743nucleo/stm32h743nucleo.c @@ -94,7 +94,7 @@ static void SystemClock_Config(void) RCC_OscInitStruct.CSIState = RCC_CSI_OFF; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; - RCC_OscInitStruct.PLL.PLLM = 8; + RCC_OscInitStruct.PLL.PLLM = HSE_VALUE/1000000; RCC_OscInitStruct.PLL.PLLN = 336; RCC_OscInitStruct.PLL.PLLP = 2; RCC_OscInitStruct.PLL.PLLQ = 7; From 287d45155d0fdc45819dd49b991ebe548d014814 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 10 Jan 2020 15:19:33 +0700 Subject: [PATCH 198/267] added stm32f401 blackpill --- docs/boards.md | 2 + .../stm32f401blackpill/STM32F401VCTx_FLASH.ld | 169 ++++++++ hw/bsp/stm32f401blackpill/board.mk | 47 +++ .../stm32f401blackpill/stm32f401blackpill.c | 215 ++++++++++ .../stm32f401blackpill/stm32f4xx_hal_conf.h | 394 ++++++++++++++++++ 5 files changed, 827 insertions(+) create mode 100644 hw/bsp/stm32f401blackpill/STM32F401VCTx_FLASH.ld create mode 100644 hw/bsp/stm32f401blackpill/board.mk create mode 100644 hw/bsp/stm32f401blackpill/stm32f401blackpill.c create mode 100644 hw/bsp/stm32f401blackpill/stm32f4xx_hal_conf.h diff --git a/docs/boards.md b/docs/boards.md index c052552b..99c90c5a 100644 --- a/docs/boards.md +++ b/docs/boards.md @@ -71,7 +71,9 @@ This code base already had supported for a handful of following boards (sorted a - STM32 F103c Blue Pill - [STM32 F207zg Nucleo](https://www.st.com/en/evaluation-tools/nucleo-f207zg.html) - [STM32 F303vc Discovery](https://www.st.com/en/evaluation-tools/stm32f3discovery.html) +- STM32 F401cc Black Pill - [STM32 F407vg Discovery](https://www.st.com/en/evaluation-tools/stm32f4discovery.html) +- STM32 F411ce Black Pill - [STM32 F411ve Discovery](https://www.st.com/en/evaluation-tools/32f411ediscovery.html) - [STM32 F412zg Discovery](https://www.st.com/en/evaluation-tools/32f412gdiscovery.html) - [STM32 F767zi Nucleo](https://www.st.com/en/evaluation-tools/nucleo-f767zi.html) diff --git a/hw/bsp/stm32f401blackpill/STM32F401VCTx_FLASH.ld b/hw/bsp/stm32f401blackpill/STM32F401VCTx_FLASH.ld new file mode 100644 index 00000000..f51f1ab4 --- /dev/null +++ b/hw/bsp/stm32f401blackpill/STM32F401VCTx_FLASH.ld @@ -0,0 +1,169 @@ +/* +***************************************************************************** +** + +** File : LinkerScript.ld +** +** Abstract : Linker script for STM32F401VCTx Device with +** 256KByte FLASH, 64KByte RAM +** +** Set heap size, stack size and stack location according +** to application requirements. +** +** Set memory bank area and size if external memory is used. +** +** Target : STMicroelectronics STM32 +** +** +** Distribution: The file is distributed as is, without any warranty +** of any kind. +** +** (c)Copyright Ac6. +** You may use this file as-is or modify it according to the needs of your +** project. Distribution of this file (unmodified or modified) is not +** permitted. Ac6 permit registered System Workbench for MCU users the +** rights to distribute the assembled, compiled & linked contents of this +** file as part of an application binary file, provided that it is built +** using the System Workbench for MCU toolchain. +** +***************************************************************************** +*/ + +/* Entry Point */ +ENTRY(Reset_Handler) + +/* Highest address of the user mode stack */ +_estack = 0x20010000; /* end of RAM */ +/* Generate a link error if heap and stack don't fit into RAM */ +_Min_Heap_Size = 0x200;; /* required amount of heap */ +_Min_Stack_Size = 0x400;; /* required amount of stack */ + +/* Specify the memory areas */ +MEMORY +{ +FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 256K +RAM (xrw) : ORIGIN = 0x20000000, LENGTH = 64K +} + +/* Define output sections */ +SECTIONS +{ + /* The startup code goes first into FLASH */ + .isr_vector : + { + . = ALIGN(4); + KEEP(*(.isr_vector)) /* Startup code */ + . = ALIGN(4); + } >FLASH + + /* The program code and other data goes into FLASH */ + .text : + { + . = ALIGN(4); + *(.text) /* .text sections (code) */ + *(.text*) /* .text* sections (code) */ + *(.glue_7) /* glue arm to thumb code */ + *(.glue_7t) /* glue thumb to arm code */ + *(.eh_frame) + + KEEP (*(.init)) + KEEP (*(.fini)) + + . = ALIGN(4); + _etext = .; /* define a global symbols at end of code */ + } >FLASH + + /* Constant data goes into FLASH */ + .rodata : + { + . = ALIGN(4); + *(.rodata) /* .rodata sections (constants, strings, etc.) */ + *(.rodata*) /* .rodata* sections (constants, strings, etc.) */ + . = ALIGN(4); + } >FLASH + + .ARM.extab : { *(.ARM.extab* .gnu.linkonce.armextab.*) } >FLASH + .ARM : { + __exidx_start = .; + *(.ARM.exidx*) + __exidx_end = .; + } >FLASH + + .preinit_array : + { + PROVIDE_HIDDEN (__preinit_array_start = .); + KEEP (*(.preinit_array*)) + PROVIDE_HIDDEN (__preinit_array_end = .); + } >FLASH + .init_array : + { + PROVIDE_HIDDEN (__init_array_start = .); + KEEP (*(SORT(.init_array.*))) + KEEP (*(.init_array*)) + PROVIDE_HIDDEN (__init_array_end = .); + } >FLASH + .fini_array : + { + PROVIDE_HIDDEN (__fini_array_start = .); + KEEP (*(SORT(.fini_array.*))) + KEEP (*(.fini_array*)) + PROVIDE_HIDDEN (__fini_array_end = .); + } >FLASH + + /* used by the startup to initialize data */ + _sidata = LOADADDR(.data); + + /* Initialized data sections goes into RAM, load LMA copy after code */ + .data : + { + . = ALIGN(4); + _sdata = .; /* create a global symbol at data start */ + *(.data) /* .data sections */ + *(.data*) /* .data* sections */ + + . = ALIGN(4); + _edata = .; /* define a global symbol at data end */ + } >RAM AT> FLASH + + + /* Uninitialized data section */ + . = ALIGN(4); + .bss : + { + /* This is used by the startup in order to initialize the .bss secion */ + _sbss = .; /* define a global symbol at bss start */ + __bss_start__ = _sbss; + *(.bss) + *(.bss*) + *(COMMON) + + . = ALIGN(4); + _ebss = .; /* define a global symbol at bss end */ + __bss_end__ = _ebss; + } >RAM + + /* User_heap_stack section, used to check that there is enough RAM left */ + ._user_heap_stack : + { + . = ALIGN(8); + PROVIDE ( end = . ); + PROVIDE ( _end = . ); + . = . + _Min_Heap_Size; + . = . + _Min_Stack_Size; + . = ALIGN(8); + } >RAM + + + + /* Remove information from the standard libraries */ + /DISCARD/ : + { + libc.a ( * ) + libm.a ( * ) + libgcc.a ( * ) + } + + .ARM.attributes 0 : { *(.ARM.attributes) } +} + + diff --git a/hw/bsp/stm32f401blackpill/board.mk b/hw/bsp/stm32f401blackpill/board.mk new file mode 100644 index 00000000..38cabcc5 --- /dev/null +++ b/hw/bsp/stm32f401blackpill/board.mk @@ -0,0 +1,47 @@ +CFLAGS += \ + -flto \ + -mthumb \ + -mabi=aapcs \ + -mcpu=cortex-m4 \ + -mfloat-abi=hard \ + -mfpu=fpv4-sp-d16 \ + -nostdlib -nostartfiles \ + -DSTM32F401xC \ + -DCFG_TUSB_MCU=OPT_MCU_STM32F4 + +ST_HAL_DRIVER = hw/mcu/st/st_driver/STM32F4xx_HAL_Driver +ST_CMSIS = hw/mcu/st/st_driver/CMSIS/Device/ST/STM32F4xx + +# All source paths should be relative to the top level. +LD_FILE = hw/bsp/$(BOARD)/STM32F401VCTx_FLASH.ld + +SRC_C += \ + $(ST_CMSIS)/Source/Templates/system_stm32f4xx.c \ + $(ST_HAL_DRIVER)/Src/stm32f4xx_hal.c \ + $(ST_HAL_DRIVER)/Src/stm32f4xx_hal_cortex.c \ + $(ST_HAL_DRIVER)/Src/stm32f4xx_hal_rcc.c \ + $(ST_HAL_DRIVER)/Src/stm32f4xx_hal_gpio.c + +SRC_S += \ + $(ST_CMSIS)/Source/Templates/gcc/startup_stm32f401xc.s + +INC += \ + $(TOP)/hw/mcu/st/st_driver/CMSIS/Include \ + $(TOP)/$(ST_CMSIS)/Include \ + $(TOP)/$(ST_HAL_DRIVER)/Inc \ + $(TOP)/hw/bsp/$(BOARD) + +# For TinyUSB port source +VENDOR = st +CHIP_FAMILY = synopsys + +# For freeRTOS port source +FREERTOS_PORT = ARM_CM4F + +# For flash-jlink target +JLINK_DEVICE = stm32f401cc +JLINK_IF = swd + +# flash target ROM bootloader +flash: $(BUILD)/$(BOARD)-firmware.bin + dfu-util -R -a 0 --dfuse-address 0x08000000 -D $< diff --git a/hw/bsp/stm32f401blackpill/stm32f401blackpill.c b/hw/bsp/stm32f401blackpill/stm32f401blackpill.c new file mode 100644 index 00000000..1fc5bb56 --- /dev/null +++ b/hw/bsp/stm32f401blackpill/stm32f401blackpill.c @@ -0,0 +1,215 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#include "../board.h" + +#include "stm32f4xx.h" +#include "stm32f4xx_hal_conf.h" + +#define LED_PORT GPIOC +#define LED_PIN GPIO_PIN_13 +#define LED_STATE_ON 1 + +#define BUTTON_PORT GPIOA +#define BUTTON_PIN GPIO_PIN_0 +#define BUTTON_STATE_ACTIVE 0 + +// enable all LED, Button, Uart, USB clock +static void all_rcc_clk_enable(void) +{ + __HAL_RCC_GPIOA_CLK_ENABLE(); // USB D+, D-, Button + __HAL_RCC_GPIOC_CLK_ENABLE(); // LED +} + +/** + * @brief System Clock Configuration + * The system Clock is configured as follow : + * System Clock source = PLL (HSE) + * SYSCLK(Hz) = 84000000 + * HCLK(Hz) = 84000000 + * AHB Prescaler = 1 + * APB1 Prescaler = 2 + * APB2 Prescaler = 1 + * HSE Frequency(Hz) = 25000000 + * PLL_M = HSE_VALUE/1000000 + * PLL_N = 336 + * PLL_P = 4 + * PLL_Q = 7 + * VDD(V) = 3.3 + * Main regulator output voltage = Scale2 mode + * Flash Latency(WS) = 2 + * @param None + * @retval None + */ +static void SystemClock_Config(void) +{ + RCC_ClkInitTypeDef RCC_ClkInitStruct; + RCC_OscInitTypeDef RCC_OscInitStruct; + + /* Enable Power Control clock */ + __HAL_RCC_PWR_CLK_ENABLE(); + + /* 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. */ + __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE2); + + /* Enable HSE Oscillator and activate PLL with HSE as source */ + 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; + RCC_OscInitStruct.PLL.PLLM = HSE_VALUE/1000000; + RCC_OscInitStruct.PLL.PLLN = 336; + RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV4; + RCC_OscInitStruct.PLL.PLLQ = 7; + HAL_RCC_OscConfig(&RCC_OscInitStruct); + + /* 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; + 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); +} + +void board_init(void) +{ +#if CFG_TUSB_OS == OPT_OS_NONE + // 1ms tick timer + SysTick_Config(SystemCoreClock / 1000); +#elif CFG_TUSB_OS == OPT_OS_FREERTOS + // If freeRTOS is used, IRQ priority is limit by max syscall ( smaller is higher ) + //NVIC_SetPriority(USB0_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY ); +#endif + + SystemClock_Config(); + SystemCoreClockUpdate(); + all_rcc_clk_enable(); + + GPIO_InitTypeDef GPIO_InitStruct; + + // LED + GPIO_InitStruct.Pin = LED_PIN; + GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; + GPIO_InitStruct.Pull = GPIO_PULLUP; + GPIO_InitStruct.Speed = GPIO_SPEED_FAST; + HAL_GPIO_Init(LED_PORT, &GPIO_InitStruct); + + board_led_write(false); + + // Button + GPIO_InitStruct.Pin = BUTTON_PIN; + GPIO_InitStruct.Mode = GPIO_MODE_INPUT; + GPIO_InitStruct.Pull = BUTTON_STATE_ACTIVE ? GPIO_PULLDOWN : GPIO_PULLUP; + GPIO_InitStruct.Speed = GPIO_SPEED_FAST; + HAL_GPIO_Init(BUTTON_PORT, &GPIO_InitStruct); + + /* Configure USB FS GPIOs */ + /* Configure USB D+ D- Pins */ + GPIO_InitStruct.Pin = GPIO_PIN_11 | GPIO_PIN_12; + GPIO_InitStruct.Speed = GPIO_SPEED_HIGH; + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Pull = GPIO_NOPULL; + GPIO_InitStruct.Alternate = GPIO_AF10_OTG_FS; + HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); + + /* Configure VBUS Pin */ + GPIO_InitStruct.Pin = GPIO_PIN_9; + GPIO_InitStruct.Mode = GPIO_MODE_INPUT; + GPIO_InitStruct.Pull = GPIO_NOPULL; + HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); + + /* This for ID line debug */ + GPIO_InitStruct.Pin = GPIO_PIN_10; + GPIO_InitStruct.Mode = GPIO_MODE_AF_OD; + GPIO_InitStruct.Pull = GPIO_PULLUP; + GPIO_InitStruct.Speed = GPIO_SPEED_HIGH; + GPIO_InitStruct.Alternate = GPIO_AF10_OTG_FS; + HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); + + // Enable USB OTG clock + __HAL_RCC_USB_OTG_FS_CLK_ENABLE(); + + // Blackpill doens't use VBUS sense (B device) + // explicitly disable it + USB_OTG_FS->GCCFG |= USB_OTG_GCCFG_NOVBUSSENS; + USB_OTG_FS->GCCFG &= ~USB_OTG_GCCFG_VBUSBSEN; + USB_OTG_FS->GCCFG &= ~USB_OTG_GCCFG_VBUSASEN; +} + +//--------------------------------------------------------------------+ +// Board porting API +//--------------------------------------------------------------------+ + +void board_led_write(bool state) +{ + HAL_GPIO_WritePin(LED_PORT, LED_PIN, state ? LED_STATE_ON : (1-LED_STATE_ON)); +} + +uint32_t board_button_read(void) +{ + return BUTTON_STATE_ACTIVE == HAL_GPIO_ReadPin(BUTTON_PORT, BUTTON_PIN); +} + +int board_uart_read(uint8_t* buf, int len) +{ + (void) buf; (void) len; + return 0; +} + +int board_uart_write(void const * buf, int len) +{ + (void) buf; (void) len; + return 0; +} + +#if CFG_TUSB_OS == OPT_OS_NONE +volatile uint32_t system_ticks = 0; +void SysTick_Handler (void) +{ + system_ticks++; +} + +uint32_t board_millis(void) +{ + return system_ticks; +} +#endif + +void HardFault_Handler (void) +{ + asm("bkpt"); +} + +// Required by __libc_init_array in startup code if we are compiling using +// -nostdlib/-nostartfiles. +void _init(void) +{ + +} diff --git a/hw/bsp/stm32f401blackpill/stm32f4xx_hal_conf.h b/hw/bsp/stm32f401blackpill/stm32f4xx_hal_conf.h new file mode 100644 index 00000000..bc6f34c5 --- /dev/null +++ b/hw/bsp/stm32f401blackpill/stm32f4xx_hal_conf.h @@ -0,0 +1,394 @@ +/** + ****************************************************************************** + * @file GPIO/GPIO_EXTI/Inc/stm32f4xx_hal_conf.h + * @author MCD Application Team + * @brief HAL configuration file + ****************************************************************************** + * @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 __STM32F4xx_HAL_CONF_H +#define __STM32F4xx_HAL_CONF_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ + +/* ########################## Module Selection ############################## */ +/** + * @brief This is the list of modules to be used in the HAL driver + */ +#define HAL_MODULE_ENABLED +/* #define HAL_ADC_MODULE_ENABLED */ +/* #define HAL_CAN_MODULE_ENABLED */ +/* #define HAL_CAN_LEGACY_MODULE_ENABLED */ +/* #define HAL_CRC_MODULE_ENABLED */ +/* #define HAL_CRYP_MODULE_ENABLED */ +/* #define HAL_DAC_MODULE_ENABLED */ +/* #define HAL_DCMI_MODULE_ENABLED */ +#define HAL_DMA_MODULE_ENABLED +/* #define HAL_DMA2D_MODULE_ENABLED */ +/* #define HAL_ETH_MODULE_ENABLED */ +#define HAL_FLASH_MODULE_ENABLED +/* #define HAL_NAND_MODULE_ENABLED */ +/* #define HAL_NOR_MODULE_ENABLED */ +/* #define HAL_PCCARD_MODULE_ENABLED */ +/* #define HAL_SRAM_MODULE_ENABLED */ +/* #define HAL_SDRAM_MODULE_ENABLED */ +/* #define HAL_HASH_MODULE_ENABLED */ +#define HAL_GPIO_MODULE_ENABLED +// #define HAL_I2C_MODULE_ENABLED +/* #define HAL_I2S_MODULE_ENABLED */ +/* #define HAL_IWDG_MODULE_ENABLED */ +/* #define HAL_LTDC_MODULE_ENABLED */ +#define HAL_PWR_MODULE_ENABLED +#define HAL_RCC_MODULE_ENABLED +/* #define HAL_RNG_MODULE_ENABLED */ +/* #define HAL_RTC_MODULE_ENABLED */ +/* #define HAL_SAI_MODULE_ENABLED */ +/* #define HAL_SD_MODULE_ENABLED */ +// #define HAL_SPI_MODULE_ENABLED +/* #define HAL_TIM_MODULE_ENABLED */ +/* #define HAL_UART_MODULE_ENABLED */ +/* #define HAL_USART_MODULE_ENABLED */ +/* #define HAL_IRDA_MODULE_ENABLED */ +/* #define HAL_SMARTCARD_MODULE_ENABLED */ +/* #define HAL_WWDG_MODULE_ENABLED */ +#define HAL_CORTEX_MODULE_ENABLED +/* #define HAL_PCD_MODULE_ENABLED */ +/* #define HAL_HCD_MODULE_ENABLED */ + + +/* ########################## HSE/HSI Values adaptation ##################### */ +/** + * @brief Adjust the value of External High Speed oscillator (HSE) used in your application. + * This value is used by the RCC HAL module to compute the system frequency + * (when HSE is used as system clock source, directly or through the PLL). + */ +#if !defined (HSE_VALUE) + #define HSE_VALUE (25000000U) /*!< Value of the External oscillator in Hz */ +#endif /* HSE_VALUE */ + +#if !defined (HSE_STARTUP_TIMEOUT) + #define HSE_STARTUP_TIMEOUT (100U) /*!< Time out for HSE start up, in ms */ +#endif /* HSE_STARTUP_TIMEOUT */ + +/** + * @brief Internal High Speed oscillator (HSI) value. + * This value is used by the RCC HAL module to compute the system frequency + * (when HSI is used as system clock source, directly or through the PLL). + */ +#if !defined (HSI_VALUE) + #define HSI_VALUE (16000000U) /*!< Value of the Internal oscillator in Hz*/ +#endif /* HSI_VALUE */ + +/** + * @brief Internal Low Speed oscillator (LSI) value. + */ +#if !defined (LSI_VALUE) + #define LSI_VALUE (32000U) +#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. + */ +#if !defined (LSE_VALUE) + #define LSE_VALUE (32768U) /*!< Value of the External Low Speed 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 */ + +/** + * @brief External clock source for I2S peripheral + * This value is used by the I2S HAL module to compute the I2S clock source + * frequency, this source is inserted directly through I2S_CKIN pad. + */ +#if !defined (EXTERNAL_CLOCK_VALUE) + #define EXTERNAL_CLOCK_VALUE (12288000U) /*!< Value of the External oscillator in Hz*/ +#endif /* EXTERNAL_CLOCK_VALUE */ + +/* 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. */ + +/* ########################### System Configuration ######################### */ +/** + * @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 INSTRUCTION_CACHE_ENABLE 1U +#define DATA_CACHE_ENABLE 1U + +#define USE_HAL_ADC_REGISTER_CALLBACKS 0U /* ADC register callback disabled */ +#define USE_HAL_CAN_REGISTER_CALLBACKS 0U /* CAN register callback disabled */ +#define USE_HAL_CEC_REGISTER_CALLBACKS 0U /* CEC register callback disabled */ +#define USE_HAL_CRYP_REGISTER_CALLBACKS 0U /* CRYP register callback disabled */ +#define USE_HAL_DAC_REGISTER_CALLBACKS 0U /* DAC register callback disabled */ +#define USE_HAL_DCMI_REGISTER_CALLBACKS 0U /* DCMI register callback disabled */ +#define USE_HAL_DFSDM_REGISTER_CALLBACKS 0U /* DFSDM register callback disabled */ +#define USE_HAL_DMA2D_REGISTER_CALLBACKS 0U /* DMA2D register callback disabled */ +#define USE_HAL_DSI_REGISTER_CALLBACKS 0U /* DSI register callback disabled */ +#define USE_HAL_ETH_REGISTER_CALLBACKS 0U /* ETH register callback disabled */ +#define USE_HAL_HASH_REGISTER_CALLBACKS 0U /* HASH register callback disabled */ +#define USE_HAL_HCD_REGISTER_CALLBACKS 0U /* HCD register callback disabled */ +#define USE_HAL_I2C_REGISTER_CALLBACKS 0U /* I2C register callback disabled */ +#define USE_HAL_FMPI2C_REGISTER_CALLBACKS 0U /* FMPI2C register callback disabled */ +#define USE_HAL_I2S_REGISTER_CALLBACKS 0U /* I2S register callback disabled */ +#define USE_HAL_IRDA_REGISTER_CALLBACKS 0U /* IRDA register callback disabled */ +#define USE_HAL_LPTIM_REGISTER_CALLBACKS 0U /* LPTIM register callback disabled */ +#define USE_HAL_LTDC_REGISTER_CALLBACKS 0U /* LTDC register callback disabled */ +#define USE_HAL_MMC_REGISTER_CALLBACKS 0U /* MMC register callback disabled */ +#define USE_HAL_NAND_REGISTER_CALLBACKS 0U /* NAND register callback disabled */ +#define USE_HAL_NOR_REGISTER_CALLBACKS 0U /* NOR register callback disabled */ +#define USE_HAL_PCCARD_REGISTER_CALLBACKS 0U /* PCCARD register callback disabled */ +#define USE_HAL_PCD_REGISTER_CALLBACKS 0U /* PCD register callback disabled */ +#define USE_HAL_QSPI_REGISTER_CALLBACKS 0U /* QSPI register callback disabled */ +#define USE_HAL_RNG_REGISTER_CALLBACKS 0U /* RNG register callback disabled */ +#define USE_HAL_RTC_REGISTER_CALLBACKS 0U /* RTC register callback disabled */ +#define USE_HAL_SAI_REGISTER_CALLBACKS 0U /* SAI register callback disabled */ +#define USE_HAL_SD_REGISTER_CALLBACKS 0U /* SD register callback disabled */ +#define USE_HAL_SMARTCARD_REGISTER_CALLBACKS 0U /* SMARTCARD register callback disabled */ +#define USE_HAL_SDRAM_REGISTER_CALLBACKS 0U /* SDRAM register callback disabled */ +#define USE_HAL_SRAM_REGISTER_CALLBACKS 0U /* SRAM register callback disabled */ +#define USE_HAL_SPDIFRX_REGISTER_CALLBACKS 0U /* SPDIFRX register callback disabled */ +#define USE_HAL_SMBUS_REGISTER_CALLBACKS 0U /* SMBUS register callback disabled */ +#define USE_HAL_SPI_REGISTER_CALLBACKS 0U /* SPI register callback disabled */ +#define USE_HAL_TIM_REGISTER_CALLBACKS 0U /* TIM register callback disabled */ +#define USE_HAL_UART_REGISTER_CALLBACKS 0U /* UART register callback disabled */ +#define USE_HAL_USART_REGISTER_CALLBACKS 0U /* USART register callback disabled */ +#define USE_HAL_WWDG_REGISTER_CALLBACKS 0U /* WWDG register callback disabled */ + +/* ########################## Assert Selection ############################## */ +/** + * @brief Uncomment the line below to expanse the "assert_param" macro in the + * HAL drivers code + */ +/* #define USE_FULL_ASSERT 1U */ + +/* ################## 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 ------------------------------------------------------------------*/ +/** + * @brief Include module's header file + */ + +#ifdef HAL_RCC_MODULE_ENABLED + #include "stm32f4xx_hal_rcc.h" +#endif /* HAL_RCC_MODULE_ENABLED */ + +#ifdef HAL_GPIO_MODULE_ENABLED + #include "stm32f4xx_hal_gpio.h" +#endif /* HAL_GPIO_MODULE_ENABLED */ + +#ifdef HAL_DMA_MODULE_ENABLED + #include "stm32f4xx_hal_dma.h" +#endif /* HAL_DMA_MODULE_ENABLED */ + +#ifdef HAL_CORTEX_MODULE_ENABLED + #include "stm32f4xx_hal_cortex.h" +#endif /* HAL_CORTEX_MODULE_ENABLED */ + +#ifdef HAL_ADC_MODULE_ENABLED + #include "stm32f4xx_hal_adc.h" +#endif /* HAL_ADC_MODULE_ENABLED */ + +#ifdef HAL_CAN_MODULE_ENABLED + #include "stm32f4xx_hal_can.h" +#endif /* HAL_CAN_MODULE_ENABLED */ + +#ifdef HAL_CAN_LEGACY_MODULE_ENABLED + #include "stm32f4xx_hal_can_legacy.h" +#endif /* HAL_CAN_LEGACY_MODULE_ENABLED */ + +#ifdef HAL_CRC_MODULE_ENABLED + #include "stm32f4xx_hal_crc.h" +#endif /* HAL_CRC_MODULE_ENABLED */ + +#ifdef HAL_CRYP_MODULE_ENABLED + #include "stm32f4xx_hal_cryp.h" +#endif /* HAL_CRYP_MODULE_ENABLED */ + +#ifdef HAL_DMA2D_MODULE_ENABLED + #include "stm32f4xx_hal_dma2d.h" +#endif /* HAL_DMA2D_MODULE_ENABLED */ + +#ifdef HAL_DAC_MODULE_ENABLED + #include "stm32f4xx_hal_dac.h" +#endif /* HAL_DAC_MODULE_ENABLED */ + +#ifdef HAL_DCMI_MODULE_ENABLED + #include "stm32f4xx_hal_dcmi.h" +#endif /* HAL_DCMI_MODULE_ENABLED */ + +#ifdef HAL_ETH_MODULE_ENABLED + #include "stm32f4xx_hal_eth.h" +#endif /* HAL_ETH_MODULE_ENABLED */ + +#ifdef HAL_FLASH_MODULE_ENABLED + #include "stm32f4xx_hal_flash.h" +#endif /* HAL_FLASH_MODULE_ENABLED */ + +#ifdef HAL_SRAM_MODULE_ENABLED + #include "stm32f4xx_hal_sram.h" +#endif /* HAL_SRAM_MODULE_ENABLED */ + +#ifdef HAL_NOR_MODULE_ENABLED + #include "stm32f4xx_hal_nor.h" +#endif /* HAL_NOR_MODULE_ENABLED */ + +#ifdef HAL_NAND_MODULE_ENABLED + #include "stm32f4xx_hal_nand.h" +#endif /* HAL_NAND_MODULE_ENABLED */ + +#ifdef HAL_PCCARD_MODULE_ENABLED + #include "stm32f4xx_hal_pccard.h" +#endif /* HAL_PCCARD_MODULE_ENABLED */ + +#ifdef HAL_SDRAM_MODULE_ENABLED + #include "stm32f4xx_hal_sdram.h" +#endif /* HAL_SDRAM_MODULE_ENABLED */ + +#ifdef HAL_HASH_MODULE_ENABLED + #include "stm32f4xx_hal_hash.h" +#endif /* HAL_HASH_MODULE_ENABLED */ + +#ifdef HAL_I2C_MODULE_ENABLED + #include "stm32f4xx_hal_i2c.h" +#endif /* HAL_I2C_MODULE_ENABLED */ + +#ifdef HAL_I2S_MODULE_ENABLED + #include "stm32f4xx_hal_i2s.h" +#endif /* HAL_I2S_MODULE_ENABLED */ + +#ifdef HAL_IWDG_MODULE_ENABLED + #include "stm32f4xx_hal_iwdg.h" +#endif /* HAL_IWDG_MODULE_ENABLED */ + +#ifdef HAL_LTDC_MODULE_ENABLED + #include "stm32f4xx_hal_ltdc.h" +#endif /* HAL_LTDC_MODULE_ENABLED */ + +#ifdef HAL_PWR_MODULE_ENABLED + #include "stm32f4xx_hal_pwr.h" +#endif /* HAL_PWR_MODULE_ENABLED */ + +#ifdef HAL_RNG_MODULE_ENABLED + #include "stm32f4xx_hal_rng.h" +#endif /* HAL_RNG_MODULE_ENABLED */ + +#ifdef HAL_RTC_MODULE_ENABLED + #include "stm32f4xx_hal_rtc.h" +#endif /* HAL_RTC_MODULE_ENABLED */ + +#ifdef HAL_SAI_MODULE_ENABLED + #include "stm32f4xx_hal_sai.h" +#endif /* HAL_SAI_MODULE_ENABLED */ + +#ifdef HAL_SD_MODULE_ENABLED + #include "stm32f4xx_hal_sd.h" +#endif /* HAL_SD_MODULE_ENABLED */ + +#ifdef HAL_SPI_MODULE_ENABLED + #include "stm32f4xx_hal_spi.h" +#endif /* HAL_SPI_MODULE_ENABLED */ + +#ifdef HAL_TIM_MODULE_ENABLED + #include "stm32f4xx_hal_tim.h" +#endif /* HAL_TIM_MODULE_ENABLED */ + +#ifdef HAL_UART_MODULE_ENABLED + #include "stm32f4xx_hal_uart.h" +#endif /* HAL_UART_MODULE_ENABLED */ + +#ifdef HAL_USART_MODULE_ENABLED + #include "stm32f4xx_hal_usart.h" +#endif /* HAL_USART_MODULE_ENABLED */ + +#ifdef HAL_IRDA_MODULE_ENABLED + #include "stm32f4xx_hal_irda.h" +#endif /* HAL_IRDA_MODULE_ENABLED */ + +#ifdef HAL_SMARTCARD_MODULE_ENABLED + #include "stm32f4xx_hal_smartcard.h" +#endif /* HAL_SMARTCARD_MODULE_ENABLED */ + +#ifdef HAL_WWDG_MODULE_ENABLED + #include "stm32f4xx_hal_wwdg.h" +#endif /* HAL_WWDG_MODULE_ENABLED */ + +#ifdef HAL_PCD_MODULE_ENABLED + #include "stm32f4xx_hal_pcd.h" +#endif /* HAL_PCD_MODULE_ENABLED */ + +#ifdef HAL_HCD_MODULE_ENABLED + #include "stm32f4xx_hal_hcd.h" +#endif /* HAL_HCD_MODULE_ENABLED */ + +/* Exported macro ------------------------------------------------------------*/ +#ifdef USE_FULL_ASSERT +/** + * @brief The assert_param macro is used for function's parameters check. + * @param expr: If expr is false, it calls assert_failed function + * which reports the name of the source file and the source + * line number of the call that failed. + * If expr is true, it returns no value. + * @retval None + */ + #define assert_param(expr) ((expr) ? (void)0U : assert_failed((uint8_t *)__FILE__, __LINE__)) +/* Exported functions ------------------------------------------------------- */ + void assert_failed(uint8_t* file, uint32_t line); +#else + #define assert_param(expr) ((void)0U) +#endif /* USE_FULL_ASSERT */ + + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32F4xx_HAL_CONF_H */ + + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ From 82c2674b192c0f4ef01632ee5538846b524c8893 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 10 Jan 2020 15:22:45 +0700 Subject: [PATCH 199/267] clean up --- hw/bsp/stm32f103bluepill/board.mk | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/hw/bsp/stm32f103bluepill/board.mk b/hw/bsp/stm32f103bluepill/board.mk index 7c1a7b37..028c567b 100644 --- a/hw/bsp/stm32f103bluepill/board.mk +++ b/hw/bsp/stm32f103bluepill/board.mk @@ -42,12 +42,9 @@ CHIP_FAMILY = stm32_fsdev FREERTOS_PORT = ARM_CM3 # For flash-jlink target -JLINK_DEVICE = stm32f303vc +JLINK_DEVICE = stm32f103c8 JLINK_IF = swd -# Path to STM32 Cube Programmer CLI, should be added into system path -STM32Prog = STM32_Programmer_CLI - -# flash target using on-board stlink -flash: $(BUILD)/$(BOARD)-firmware.elf - $(STM32Prog) --connect port=swd --write $< --go +# flash target ROM bootloader +flash: $(BUILD)/$(BOARD)-firmware.bin + dfu-util -R -a 0 --dfuse-address 0x08000000 -D $< From 43eff66d40632b26e8e985ff913017b724697c72 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 10 Jan 2020 16:51:24 +0700 Subject: [PATCH 200/267] add raytac mdbt50q rx dongle --- docs/boards.md | 1 + hw/bsp/raytac_mdbt50q_rx/board.mk | 54 ++++++ hw/bsp/raytac_mdbt50q_rx/raytac_mdbt50q_rx.c | 190 +++++++++++++++++++ 3 files changed, 245 insertions(+) create mode 100644 hw/bsp/raytac_mdbt50q_rx/board.mk create mode 100644 hw/bsp/raytac_mdbt50q_rx/raytac_mdbt50q_rx.c diff --git a/docs/boards.md b/docs/boards.md index 99c90c5a..cf5defb5 100644 --- a/docs/boards.md +++ b/docs/boards.md @@ -25,6 +25,7 @@ This code base already had supported for a handful of following boards (sorted a - [Nordic nRF52840 Development Kit (aka pca10056)](https://www.nordicsemi.com/Software-and-Tools/Development-Kits/nRF52840-DK) - [Nordic nRF52840 Dongle (aka pca10059)](https://www.nordicsemi.com/Software-and-Tools/Development-Kits/nRF52840-Dongle) - [Nordic nRF52833 Development Kit (aka pca10100)](https://www.nordicsemi.com/Software-and-Tools/Development-Kits/nRF52833-DK) +- [Raytac MDBT50Q-RX Dongle](https://www.raytac.com/product/ins.php?index_id=89) ### Nuvoton diff --git a/hw/bsp/raytac_mdbt50q_rx/board.mk b/hw/bsp/raytac_mdbt50q_rx/board.mk new file mode 100644 index 00000000..d446d3de --- /dev/null +++ b/hw/bsp/raytac_mdbt50q_rx/board.mk @@ -0,0 +1,54 @@ +CFLAGS += \ + -flto \ + -mthumb \ + -mabi=aapcs \ + -mcpu=cortex-m4 \ + -mfloat-abi=hard \ + -mfpu=fpv4-sp-d16 \ + -DNRF52840_XXAA \ + -DCFG_TUSB_MCU=OPT_MCU_NRF5X + +# nrfx issue undef _ARMCC_VERSION usage https://github.com/NordicSemiconductor/nrfx/issues/49 +CFLAGS += -Wno-error=undef -Wno-error=unused-parameter + +# due to tusb_hal_nrf_power_event +GCCVERSION = $(firstword $(subst ., ,$(shell arm-none-eabi-gcc -dumpversion))) +ifeq ($(shell expr $(GCCVERSION) \>= 8), 1) +CFLAGS += -Wno-error=cast-function-type +endif + +# All source paths should be relative to the top level. +LD_FILE = hw/mcu/nordic/nrfx/mdk/nrf52840_xxaa.ld + +LDFLAGS += -L$(TOP)/hw/mcu/nordic/nrfx/mdk + +SRC_C += \ + hw/mcu/nordic/nrfx/drivers/src/nrfx_power.c \ + hw/mcu/nordic/nrfx/mdk/system_nrf52840.c \ + +INC += \ + $(TOP)/hw/mcu/nordic/cmsis/Include \ + $(TOP)/hw/mcu/nordic \ + $(TOP)/hw/mcu/nordic/nrfx \ + $(TOP)/hw/mcu/nordic/nrfx/mdk \ + $(TOP)/hw/mcu/nordic/nrfx/hal \ + $(TOP)/hw/mcu/nordic/nrfx/drivers/include \ + $(TOP)/hw/mcu/nordic/nrfx/drivers/src \ + +SRC_S += hw/mcu/nordic/nrfx/mdk/gcc_startup_nrf52840.S + +ASFLAGS += -D__HEAP_SIZE=0 + +# For TinyUSB port source +VENDOR = nordic +CHIP_FAMILY = nrf5x + +# For freeRTOS port source +FREERTOS_PORT = ARM_CM4F + +# For flash-jlink target +JLINK_DEVICE = nRF52840_xxAA +JLINK_IF = swd + +# flash using jlink +flash: flash-jlink diff --git a/hw/bsp/raytac_mdbt50q_rx/raytac_mdbt50q_rx.c b/hw/bsp/raytac_mdbt50q_rx/raytac_mdbt50q_rx.c new file mode 100644 index 00000000..8bb5a173 --- /dev/null +++ b/hw/bsp/raytac_mdbt50q_rx/raytac_mdbt50q_rx.c @@ -0,0 +1,190 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#include "bsp/board.h" + +#include "nrfx.h" +#include "nrfx/hal/nrf_gpio.h" +#include "nrfx/drivers/include/nrfx_power.h" + +#ifdef SOFTDEVICE_PRESENT +#include "nrf_sdm.h" +#include "nrf_soc.h" +#endif + +/*------------------------------------------------------------------*/ +/* MACRO TYPEDEF CONSTANT ENUM + *------------------------------------------------------------------*/ +#define LED_PIN (32+13) // P1.13 +#define LED_STATE_ON 0 + +// Button 1 +#define BUTTON_PIN 15 // P0.15 +#define BUTTON_STATE_ACTIVE 0 + +// tinyusb function that handles power event (detected, ready, removed) +// We must call it within SD's SOC event handler, or set it as power event handler if SD is not enabled. +extern void tusb_hal_nrf_power_event(uint32_t event); + +void board_init(void) +{ + // Config clock source: XTAL or RC in sdk_config.h + NRF_CLOCK->LFCLKSRC = (uint32_t)((CLOCK_LFCLKSRC_SRC_Xtal << CLOCK_LFCLKSRC_SRC_Pos) & CLOCK_LFCLKSRC_SRC_Msk); + NRF_CLOCK->TASKS_LFCLKSTART = 1UL; + + // LED + nrf_gpio_cfg_output(LED_PIN); + board_led_write(false); + + // Button + nrf_gpio_cfg_input(BUTTON_PIN, NRF_GPIO_PIN_PULLUP); + +#if CFG_TUSB_OS == OPT_OS_NONE + // 1ms tick timer + SysTick_Config(SystemCoreClock/1000); +#endif + +#if TUSB_OPT_DEVICE_ENABLED + // Priorities 0, 1, 4 (nRF52) are reserved for SoftDevice + // 2 is highest for application + NVIC_SetPriority(USBD_IRQn, 2); + + // USB power may already be ready at this time -> no event generated + // We need to invoke the handler based on the status initially + uint32_t usb_reg; + +#ifdef SOFTDEVICE_PRESENT + uint8_t sd_en = false; + sd_softdevice_is_enabled(&sd_en); + + if ( sd_en ) { + sd_power_usbdetected_enable(true); + sd_power_usbpwrrdy_enable(true); + sd_power_usbremoved_enable(true); + + sd_power_usbregstatus_get(&usb_reg); + }else +#endif + { + // Power module init + const nrfx_power_config_t pwr_cfg = { 0 }; + nrfx_power_init(&pwr_cfg); + + // Register tusb function as USB power handler + const nrfx_power_usbevt_config_t config = { .handler = (nrfx_power_usb_event_handler_t) tusb_hal_nrf_power_event }; + nrfx_power_usbevt_init(&config); + + nrfx_power_usbevt_enable(); + + usb_reg = NRF_POWER->USBREGSTATUS; + } + + if ( usb_reg & POWER_USBREGSTATUS_VBUSDETECT_Msk ) tusb_hal_nrf_power_event(NRFX_POWER_USB_EVT_DETECTED); + if ( usb_reg & POWER_USBREGSTATUS_OUTPUTRDY_Msk ) tusb_hal_nrf_power_event(NRFX_POWER_USB_EVT_READY); +#endif +} + +//--------------------------------------------------------------------+ +// Board porting API +//--------------------------------------------------------------------+ + +void board_led_write(bool state) +{ + nrf_gpio_pin_write(LED_PIN, state ? LED_STATE_ON : (1-LED_STATE_ON)); +} + +uint32_t board_button_read(void) +{ + return BUTTON_STATE_ACTIVE == nrf_gpio_pin_read(BUTTON_PIN); +} + +int board_uart_read(uint8_t* buf, int len) +{ + (void) buf; (void) len; + return 0; +} + +int board_uart_write(void const * buf, int len) +{ + (void) buf; (void) len; + return 0; +} + +#if CFG_TUSB_OS == OPT_OS_NONE +volatile uint32_t system_ticks = 0; +void SysTick_Handler (void) +{ + system_ticks++; +} + +uint32_t board_millis(void) +{ + return system_ticks; +} +#endif + +#ifdef SOFTDEVICE_PRESENT +// process SOC event from SD +uint32_t proc_soc(void) +{ + uint32_t soc_evt; + uint32_t err = sd_evt_get(&soc_evt); + + if (NRF_SUCCESS == err) + { + /*------------- usb power event handler -------------*/ + int32_t usbevt = (soc_evt == NRF_EVT_POWER_USB_DETECTED ) ? NRFX_POWER_USB_EVT_DETECTED: + (soc_evt == NRF_EVT_POWER_USB_POWER_READY) ? NRFX_POWER_USB_EVT_READY : + (soc_evt == NRF_EVT_POWER_USB_REMOVED ) ? NRFX_POWER_USB_EVT_REMOVED : -1; + + if ( usbevt >= 0) tusb_hal_nrf_power_event(usbevt); + } + + return err; +} + +uint32_t proc_ble(void) +{ + // do nothing with ble + return NRF_ERROR_NOT_FOUND; +} + +void SD_EVT_IRQHandler(void) +{ + // process BLE and SOC until there is no more events + while( (NRF_ERROR_NOT_FOUND != proc_ble()) || (NRF_ERROR_NOT_FOUND != proc_soc()) ) + { + + } +} + +void nrf_error_cb(uint32_t id, uint32_t pc, uint32_t info) +{ + (void) id; + (void) pc; + (void) info; +} +#endif From 242a2b6126f00cb3d8ffe6bf6245f801709910ed Mon Sep 17 00:00:00 2001 From: hathach Date: Sat, 11 Jan 2020 12:35:51 +0700 Subject: [PATCH 201/267] clean example --- CONTRIBUTORS.md | 1 + examples/device/cdc_dual_ports/src/main.c | 1 - .../cdc_dual_ports/src/usb_descriptors.c | 9 ++---- .../cdc_dual_ports/src/usb_descriptors.h | 28 ------------------- 4 files changed, 4 insertions(+), 35 deletions(-) delete mode 100644 examples/device/cdc_dual_ports/src/usb_descriptors.h diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 0b52c4c5..e1d5db69 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -27,6 +27,7 @@ * **[Peter Lawrence](https://github.com/majbthrd)** * Nuvoton NUC 121, 125, 126 device driver port * Board support for NuTiny NUC121s, NUC125s, NUC126V + * Complete multiple class interfaces & add cdc_dual_ports example * **[Scott Shawcroft](https://github.com/tannewt)** * SAMD21 and SAMD51 device driver port diff --git a/examples/device/cdc_dual_ports/src/main.c b/examples/device/cdc_dual_ports/src/main.c index e612dc83..87e66b95 100644 --- a/examples/device/cdc_dual_ports/src/main.c +++ b/examples/device/cdc_dual_ports/src/main.c @@ -30,7 +30,6 @@ #include "bsp/board.h" #include "tusb.h" -#include "usb_descriptors.h" //------------- prototypes -------------// static void cdc_task(void); diff --git a/examples/device/cdc_dual_ports/src/usb_descriptors.c b/examples/device/cdc_dual_ports/src/usb_descriptors.c index 63885347..1e24a0f1 100644 --- a/examples/device/cdc_dual_ports/src/usb_descriptors.c +++ b/examples/device/cdc_dual_ports/src/usb_descriptors.c @@ -24,7 +24,6 @@ */ #include "tusb.h" -#include "usb_descriptors.h" /* A combination of interfaces must have a unique product id, since PC will save device driver after the first plug. * Same VID/PID with different interface e.g MSC (first), then CDC (later) will possibly cause system error on PC. @@ -77,10 +76,8 @@ enum { ITF_NUM_CDC1 = 0, ITF_NUM_CDC_DATA1, -#if (CFG_TUD_CDC > 1) ITF_NUM_CDC2, ITF_NUM_CDC_DATA2, -#endif ITF_NUM_TOTAL }; @@ -99,11 +96,11 @@ uint8_t const desc_configuration[] = // Interface count, string index, total length, attribute, power in mA TUD_CONFIG_DESCRIPTOR(ITF_NUM_TOTAL, 0, CONFIG_TOTAL_LEN, TUSB_DESC_CONFIG_ATT_REMOTE_WAKEUP, 100), - // Interface number, string index, EP notification address and size, EP data address (out, in) and size. + // 1st CDC: Interface number, string index, EP notification address and size, EP data address (out, in) and size. TUD_CDC_DESCRIPTOR(ITF_NUM_CDC1, 4, 0x81, 8, EPNUM_CDC, 0x80 | EPNUM_CDC, 64), -#if (CFG_TUD_CDC > 1) + + // 2nd CDC: Interface number, string index, EP notification address and size, EP data address (out, in) and size. TUD_CDC_DESCRIPTOR(ITF_NUM_CDC2, 4, 0x83, 8, EPNUM_CDC + 2, 0x80 | (EPNUM_CDC + 2), 64), -#endif }; // Invoked when received GET CONFIGURATION DESCRIPTOR diff --git a/examples/device/cdc_dual_ports/src/usb_descriptors.h b/examples/device/cdc_dual_ports/src/usb_descriptors.h deleted file mode 100644 index 28057083..00000000 --- a/examples/device/cdc_dual_ports/src/usb_descriptors.h +++ /dev/null @@ -1,28 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2019 Ha Thach (tinyusb.org) - * - * 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 USB_DESCRIPTORS_H_ -#define USB_DESCRIPTORS_H_ - -#endif /* USB_DESCRIPTORS_H_ */ From 08da3e80b7d93c31ee0b679bcb9d05722abfe182 Mon Sep 17 00:00:00 2001 From: hathach Date: Sat, 11 Jan 2020 12:59:02 +0700 Subject: [PATCH 202/267] echo to both serial at once --- examples/device/cdc_dual_ports/src/main.c | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/examples/device/cdc_dual_ports/src/main.c b/examples/device/cdc_dual_ports/src/main.c index 87e66b95..d6e38df8 100644 --- a/examples/device/cdc_dual_ports/src/main.c +++ b/examples/device/cdc_dual_ports/src/main.c @@ -50,7 +50,9 @@ int main(void) return 0; } -static void echo_all(uint8_t itf, uint8_t buf[], uint32_t count) +// echo to either Serial0 or Serial1 +// with Serial0 as all lower case, Serial1 as all upper case +static void echo_serial_port(uint8_t itf, uint8_t buf[], uint32_t count) { for(uint32_t i=0; i Date: Sat, 11 Jan 2020 13:02:10 +0700 Subject: [PATCH 203/267] add cdc_dual_ports example to actionci --- .github/workflows/build.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 4fc11f3d..72922251 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -24,7 +24,8 @@ jobs: strategy: fail-fast: false matrix: - example: ['board_test', 'cdc_msc', 'dfu_rt', 'hid_composite', 'hid_generic_inout', 'midi_test', 'msc_dual_lun', 'usbtmc', 'webusb_serial'] + example: ['board_test', 'cdc_dual_ports', 'cdc_msc', 'dfu_rt', 'hid_composite', + 'hid_generic_inout', 'midi_test', 'msc_dual_lun', 'usbtmc', 'webusb_serial'] steps: - name: Setup Python uses: actions/setup-python@v1 From 64b435cf6e6401699086b3c1d62794c7d9aafab9 Mon Sep 17 00:00:00 2001 From: Peter Lawrence <12226419+majbthrd@users.noreply.github.com> Date: Sat, 11 Jan 2020 18:25:38 -0600 Subject: [PATCH 204/267] correct apparent Adafruit typo in SAMD21 board.mk --- hw/bsp/feather_m0_express/board.mk | 2 +- hw/bsp/metro_m0_express/board.mk | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/hw/bsp/feather_m0_express/board.mk b/hw/bsp/feather_m0_express/board.mk index d4530a47..a147cf82 100644 --- a/hw/bsp/feather_m0_express/board.mk +++ b/hw/bsp/feather_m0_express/board.mk @@ -25,7 +25,7 @@ INC += \ $(TOP)/hw/mcu/microchip/samd/asf4/samd21/include \ $(TOP)/hw/mcu/microchip/samd/asf4/samd21/hal/include \ $(TOP)/hw/mcu/microchip/samd/asf4/samd21/hal/utils/include \ - $(TOP)/hw/mcu/microchip/samd/asf4/samd51/hpl/pm/ \ + $(TOP)/hw/mcu/microchip/samd/asf4/samd21/hpl/pm/ \ $(TOP)/hw/mcu/microchip/samd/asf4/samd21/hpl/port \ $(TOP)/hw/mcu/microchip/samd/asf4/samd21/hri \ $(TOP)/hw/mcu/microchip/samd/asf4/samd21/CMSIS/Include diff --git a/hw/bsp/metro_m0_express/board.mk b/hw/bsp/metro_m0_express/board.mk index 668d9a5b..4d6dedcf 100644 --- a/hw/bsp/metro_m0_express/board.mk +++ b/hw/bsp/metro_m0_express/board.mk @@ -25,7 +25,7 @@ INC += \ $(TOP)/hw/mcu/microchip/samd/asf4/samd21/include \ $(TOP)/hw/mcu/microchip/samd/asf4/samd21/hal/include \ $(TOP)/hw/mcu/microchip/samd/asf4/samd21/hal/utils/include \ - $(TOP)/hw/mcu/microchip/samd/asf4/samd51/hpl/pm/ \ + $(TOP)/hw/mcu/microchip/samd/asf4/samd21/hpl/pm/ \ $(TOP)/hw/mcu/microchip/samd/asf4/samd21/hpl/port \ $(TOP)/hw/mcu/microchip/samd/asf4/samd21/hri \ $(TOP)/hw/mcu/microchip/samd/asf4/samd21/CMSIS/Include From 4de9439fb11a412630c758217779920a11487cd2 Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 14 Jan 2020 18:13:42 +0700 Subject: [PATCH 205/267] more nuvoton support - add LED for nutiny nuc 121, 125s, 126v - flash target to use nuvoton's openocd fork --- hw/bsp/nutiny_nuc121s/board.mk | 7 +++++-- hw/bsp/nutiny_nuc121s/nutiny_nuc121.c | 10 +++++++++- hw/bsp/nutiny_nuc125s/board.mk | 9 ++++++--- hw/bsp/nutiny_nuc125s/nutiny_nuc125.c | 10 +++++++++- hw/bsp/nutiny_nuc126v/board.mk | 6 ++++-- hw/bsp/nutiny_nuc126v/nutiny_nuc126.c | 10 +++++++++- 6 files changed, 42 insertions(+), 10 deletions(-) diff --git a/hw/bsp/nutiny_nuc121s/board.mk b/hw/bsp/nutiny_nuc121s/board.mk index ec4966cb..7e01de2b 100644 --- a/hw/bsp/nutiny_nuc121s/board.mk +++ b/hw/bsp/nutiny_nuc121s/board.mk @@ -51,5 +51,8 @@ FREERTOS_PORT = ARM_CM0 JLINK_DEVICE = NUC121SC2AE JLINK_IF = swd -# flash using jlink -flash: flash-jlink + +# Flash using Nuvoton's openocd fork at https://github.com/OpenNuvoton/OpenOCD-Nuvoton +# Please compile and install it from github source +flash: $(BUILD)/$(BOARD)-firmware.elf + openocd -f interface/nulink.cfg -f target/numicroM0.cfg -c "program $< verify reset exit" diff --git a/hw/bsp/nutiny_nuc121s/nutiny_nuc121.c b/hw/bsp/nutiny_nuc121s/nutiny_nuc121.c index 51ca28a8..dfa67206 100644 --- a/hw/bsp/nutiny_nuc121s/nutiny_nuc121.c +++ b/hw/bsp/nutiny_nuc121s/nutiny_nuc121.c @@ -29,6 +29,11 @@ #include "clk.h" #include "sys.h" +#define LED_PORT PB +#define LED_PIN 4 +#define LED_PIN_IO PB4 +#define LED_STATE_ON 0 + void board_init(void) { /* Unlock protected registers */ @@ -60,6 +65,9 @@ void board_init(void) // 1ms tick timer SysTick_Config(48000000 / 1000); #endif + + // LED + GPIO_SetMode(LED_PORT, 1 << LED_PIN, GPIO_MODE_OUTPUT); } #if CFG_TUSB_OS == OPT_OS_NONE @@ -81,7 +89,7 @@ uint32_t board_millis(void) void board_led_write(bool state) { - (void)(state); + LED_PIN_IO = (state ? LED_STATE_ON : (1-LED_STATE_ON)); } uint32_t board_button_read(void) diff --git a/hw/bsp/nutiny_nuc125s/board.mk b/hw/bsp/nutiny_nuc125s/board.mk index 6329ca7c..d563db5e 100644 --- a/hw/bsp/nutiny_nuc125s/board.mk +++ b/hw/bsp/nutiny_nuc125s/board.mk @@ -13,7 +13,8 @@ LD_FILE = hw/bsp/nutiny_nuc125s/nuc125_flash.ld SRC_C += \ hw/mcu/nuvoton/nuc121_125/Device/Nuvoton/NUC121/Source/system_NUC121.c \ - hw/mcu/nuvoton/nuc121_125/StdDriver/src/clk.c + hw/mcu/nuvoton/nuc121_125/StdDriver/src/clk.c \ + hw/mcu/nuvoton/nuc121_125/StdDriver/src/gpio.c SRC_S += \ hw/mcu/nuvoton/nuc121_125/Device/Nuvoton/NUC121/Source/GCC/startup_NUC121.S @@ -34,5 +35,7 @@ FREERTOS_PORT = ARM_CM0 JLINK_DEVICE = NUC125SC2AE JLINK_IF = swd -# flash using jlink -flash: flash-jlink +# Flash using Nuvoton's openocd fork at https://github.com/OpenNuvoton/OpenOCD-Nuvoton +# Please compile and install it from github source +flash: $(BUILD)/$(BOARD)-firmware.elf + openocd -f interface/nulink.cfg -f target/numicroM0.cfg -c "program $< verify reset exit" diff --git a/hw/bsp/nutiny_nuc125s/nutiny_nuc125.c b/hw/bsp/nutiny_nuc125s/nutiny_nuc125.c index 51ca28a8..dfa67206 100644 --- a/hw/bsp/nutiny_nuc125s/nutiny_nuc125.c +++ b/hw/bsp/nutiny_nuc125s/nutiny_nuc125.c @@ -29,6 +29,11 @@ #include "clk.h" #include "sys.h" +#define LED_PORT PB +#define LED_PIN 4 +#define LED_PIN_IO PB4 +#define LED_STATE_ON 0 + void board_init(void) { /* Unlock protected registers */ @@ -60,6 +65,9 @@ void board_init(void) // 1ms tick timer SysTick_Config(48000000 / 1000); #endif + + // LED + GPIO_SetMode(LED_PORT, 1 << LED_PIN, GPIO_MODE_OUTPUT); } #if CFG_TUSB_OS == OPT_OS_NONE @@ -81,7 +89,7 @@ uint32_t board_millis(void) void board_led_write(bool state) { - (void)(state); + LED_PIN_IO = (state ? LED_STATE_ON : (1-LED_STATE_ON)); } uint32_t board_button_read(void) diff --git a/hw/bsp/nutiny_nuc126v/board.mk b/hw/bsp/nutiny_nuc126v/board.mk index d38e6c4d..1edf4a63 100644 --- a/hw/bsp/nutiny_nuc126v/board.mk +++ b/hw/bsp/nutiny_nuc126v/board.mk @@ -55,5 +55,7 @@ FREERTOS_PORT = ARM_CM0 JLINK_DEVICE = NUC126VG4AE JLINK_IF = swd -# flash using jlink -flash: flash-jlink +# Flash using Nuvoton's openocd fork at https://github.com/OpenNuvoton/OpenOCD-Nuvoton +# Please compile and install it from github source +flash: $(BUILD)/$(BOARD)-firmware.elf + openocd -f interface/nulink.cfg -f target/numicroM0.cfg -c "program $< verify reset exit" diff --git a/hw/bsp/nutiny_nuc126v/nutiny_nuc126.c b/hw/bsp/nutiny_nuc126v/nutiny_nuc126.c index 0ce787d3..bdc15455 100644 --- a/hw/bsp/nutiny_nuc126v/nutiny_nuc126.c +++ b/hw/bsp/nutiny_nuc126v/nutiny_nuc126.c @@ -29,6 +29,11 @@ #include "clk.h" #include "sys.h" +#define LED_PORT PC +#define LED_PIN 9 +#define LED_PIN_IO PC9 +#define LED_STATE_ON 0 + #define CRYSTAL_LESS /* system will be 48MHz when defined, otherwise, system is 72MHz */ #define HIRC48_AUTO_TRIM SYS_IRCTCTL1_REFCKSEL_Msk | (1UL << SYS_IRCTCTL1_LOOPSEL_Pos) | (2UL << SYS_IRCTCTL1_FREQSEL_Pos) #define TRIM_INIT (SYS_BASE+0x118) @@ -91,6 +96,9 @@ void board_init(void) // 1ms tick timer SysTick_Config(48000000 / 1000); #endif + + // LED + GPIO_SetMode(LED_PORT, 1 << LED_PIN, GPIO_MODE_OUTPUT); } #if CFG_TUSB_OS == OPT_OS_NONE @@ -112,7 +120,7 @@ uint32_t board_millis(void) void board_led_write(bool state) { - (void)(state); + LED_PIN_IO = (state ? LED_STATE_ON : (1-LED_STATE_ON)); } uint32_t board_button_read(void) From 0c1fff735d2db0971515330394479912624da6f7 Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 14 Jan 2020 18:19:33 +0700 Subject: [PATCH 206/267] skip nuc flash verify --- hw/bsp/nutiny_nuc121s/board.mk | 3 +-- hw/bsp/nutiny_nuc125s/board.mk | 2 +- hw/bsp/nutiny_nuc126v/board.mk | 2 +- 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/hw/bsp/nutiny_nuc121s/board.mk b/hw/bsp/nutiny_nuc121s/board.mk index 7e01de2b..893c8500 100644 --- a/hw/bsp/nutiny_nuc121s/board.mk +++ b/hw/bsp/nutiny_nuc121s/board.mk @@ -51,8 +51,7 @@ FREERTOS_PORT = ARM_CM0 JLINK_DEVICE = NUC121SC2AE JLINK_IF = swd - # Flash using Nuvoton's openocd fork at https://github.com/OpenNuvoton/OpenOCD-Nuvoton # Please compile and install it from github source flash: $(BUILD)/$(BOARD)-firmware.elf - openocd -f interface/nulink.cfg -f target/numicroM0.cfg -c "program $< verify reset exit" + openocd -f interface/nulink.cfg -f target/numicroM0.cfg -c "program $< reset exit" diff --git a/hw/bsp/nutiny_nuc125s/board.mk b/hw/bsp/nutiny_nuc125s/board.mk index d563db5e..e2eecff1 100644 --- a/hw/bsp/nutiny_nuc125s/board.mk +++ b/hw/bsp/nutiny_nuc125s/board.mk @@ -38,4 +38,4 @@ JLINK_IF = swd # Flash using Nuvoton's openocd fork at https://github.com/OpenNuvoton/OpenOCD-Nuvoton # Please compile and install it from github source flash: $(BUILD)/$(BOARD)-firmware.elf - openocd -f interface/nulink.cfg -f target/numicroM0.cfg -c "program $< verify reset exit" + openocd -f interface/nulink.cfg -f target/numicroM0.cfg -c "program $< reset exit" diff --git a/hw/bsp/nutiny_nuc126v/board.mk b/hw/bsp/nutiny_nuc126v/board.mk index 1edf4a63..cc88b552 100644 --- a/hw/bsp/nutiny_nuc126v/board.mk +++ b/hw/bsp/nutiny_nuc126v/board.mk @@ -58,4 +58,4 @@ JLINK_IF = swd # Flash using Nuvoton's openocd fork at https://github.com/OpenNuvoton/OpenOCD-Nuvoton # Please compile and install it from github source flash: $(BUILD)/$(BOARD)-firmware.elf - openocd -f interface/nulink.cfg -f target/numicroM0.cfg -c "program $< verify reset exit" + openocd -f interface/nulink.cfg -f target/numicroM0.cfg -c "program $< reset exit" From c1781e5e7c47e716a558f388beb96454d4bf8627 Mon Sep 17 00:00:00 2001 From: Mateusz Holenko Date: Tue, 14 Jan 2020 13:37:45 +0100 Subject: [PATCH 207/267] dcd_eptri: Fix rx_buffer/tx_buffer volatile annotation This makes `rx_buffer` and `tx_buffer` *pointers* volatile in order to avoid caching them in a register. The original notation meant "a pointer to a volatile value" (equivalent of `volatile uint8_t *`). This resulted in `while(rx_buffer[ep_num] != NULL) ;` loop to get stuck forever, even though the IRQ handler set the `rx_buffer[ep_num] = NULL`. --- src/portable/valentyusb/eptri/dcd_eptri.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/portable/valentyusb/eptri/dcd_eptri.c b/src/portable/valentyusb/eptri/dcd_eptri.c index d7e1b8a9..0d388c37 100644 --- a/src/portable/valentyusb/eptri/dcd_eptri.c +++ b/src/portable/valentyusb/eptri/dcd_eptri.c @@ -75,13 +75,13 @@ uint8_t queue_log_offset; #define EP_SIZE 64 uint16_t volatile rx_buffer_offset[16]; -uint8_t volatile * rx_buffer[16]; +uint8_t* volatile rx_buffer[16]; uint16_t volatile rx_buffer_max[16]; volatile uint8_t tx_ep; volatile bool tx_active; volatile uint16_t tx_buffer_offset[16]; -uint8_t volatile * tx_buffer[16]; +uint8_t* volatile tx_buffer[16]; volatile uint16_t tx_buffer_max[16]; volatile uint8_t reset_count; From f2a5335417004cdc9398e3beac1f4861a5e29e0a Mon Sep 17 00:00:00 2001 From: Peter Lawrence <12226419+majbthrd@users.noreply.github.com> Date: Tue, 14 Jan 2020 22:07:38 -0600 Subject: [PATCH 208/267] nuc121: fix handling of OUT transfers larger than max packet size --- src/portable/nuvoton/nuc121/dcd_nuc121.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/portable/nuvoton/nuc121/dcd_nuc121.c b/src/portable/nuvoton/nuc121/dcd_nuc121.c index afe2cf00..892a20aa 100644 --- a/src/portable/nuvoton/nuc121/dcd_nuc121.c +++ b/src/portable/nuvoton/nuc121/dcd_nuc121.c @@ -395,9 +395,11 @@ void USBD_IRQHandler(void) xfer->remaining_bytes -= available_bytes; xfer->data_ptr += available_bytes; - /* when the transfer is finished, alert TinyUSB */ + /* when the transfer is finished, alert TinyUSB; otherwise, accept more data */ if ( (0 == xfer->remaining_bytes) || (available_bytes < xfer->max_packet_size) ) dcd_event_xfer_complete(0, ep_addr, available_bytes, XFER_RESULT_SUCCESS, true); + else if (xfer->remaining_bytes) + ep->MXPLD = xfer->max_packet_size; } else { From 7f2db321bf8e1f97d4759cf2efef0f684a461916 Mon Sep 17 00:00:00 2001 From: Peter Lawrence <12226419+majbthrd@users.noreply.github.com> Date: Wed, 15 Jan 2020 10:23:23 -0600 Subject: [PATCH 209/267] nuc121: better fix for handling large OUT transfers --- src/portable/nuvoton/nuc121/dcd_nuc121.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/portable/nuvoton/nuc121/dcd_nuc121.c b/src/portable/nuvoton/nuc121/dcd_nuc121.c index 892a20aa..237a5fd9 100644 --- a/src/portable/nuvoton/nuc121/dcd_nuc121.c +++ b/src/portable/nuvoton/nuc121/dcd_nuc121.c @@ -397,7 +397,7 @@ void USBD_IRQHandler(void) /* when the transfer is finished, alert TinyUSB; otherwise, accept more data */ if ( (0 == xfer->remaining_bytes) || (available_bytes < xfer->max_packet_size) ) - dcd_event_xfer_complete(0, ep_addr, available_bytes, XFER_RESULT_SUCCESS, true); + dcd_event_xfer_complete(0, ep_addr, xfer->total_bytes, XFER_RESULT_SUCCESS, true); else if (xfer->remaining_bytes) ep->MXPLD = xfer->max_packet_size; } From 5b9b36be14920bfdce4922cd77f2e973cd93a96b Mon Sep 17 00:00:00 2001 From: Nathan Conrad Date: Tue, 14 Jan 2020 23:27:21 -0500 Subject: [PATCH 210/267] Add gitattributes --- .gitattributes | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 .gitattributes diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..2342decc --- /dev/null +++ b/.gitattributes @@ -0,0 +1,25 @@ +# Set the default behavior, in case people don't have core.autocrlf set. +* text=auto + +*.c text +*.cpp text +*.h text +*.icf text +*.js text +*.json text +*.ld text +*.md text +*.mk text +*.py text +*.rst text +*.s text +*.txt text +*.xml text +*.yml text + +Makefile text + +# Windows-only Visual Studio things + +*.sln text eol=crlf +*.csproj text eol=crlf From 25c1bea782e69e8d365e8b61e12d888611d2f6f7 Mon Sep 17 00:00:00 2001 From: Nathan Conrad Date: Tue, 14 Jan 2020 23:30:39 -0500 Subject: [PATCH 211/267] Normalize line endings --- src/class/audio/audio.h | 200 +-- src/class/cdc/cdc.h | 810 ++++----- src/class/cdc/cdc_device.c | 830 ++++----- src/class/cdc/cdc_device.h | 426 ++--- src/class/cdc/cdc_host.c | 450 ++--- src/class/cdc/cdc_host.h | 246 +-- src/class/hid/hid.h | 1746 +++++++++---------- src/class/hid/hid_device.h | 630 +++---- src/class/hid/hid_host.c | 578 +++---- src/class/hid/hid_host.h | 430 ++--- src/class/midi/midi.h | 334 ++-- src/class/midi/midi_device.c | 722 ++++---- src/class/midi/midi_device.h | 276 +-- src/class/msc/msc.h | 784 ++++----- src/class/msc/msc_device.c | 1400 +++++++-------- src/class/msc/msc_device.h | 330 ++-- src/class/msc/msc_host.c | 826 ++++----- src/class/msc/msc_host.h | 412 ++--- src/common/tusb_common.h | 550 +++--- src/common/tusb_compiler.h | 280 +-- src/common/tusb_error.h | 148 +- src/common/tusb_fifo.c | 576 +++---- src/common/tusb_fifo.h | 262 +-- src/common/tusb_timeout.h | 160 +- src/common/tusb_types.h | 962 +++++------ src/device/dcd.h | 302 ++-- src/device/usbd.c | 2002 +++++++++++----------- src/device/usbd.h | 670 ++++---- src/host/ehci/ehci.c | 1712 +++++++++--------- src/host/hcd.h | 294 ++-- src/host/hub.c | 500 +++--- src/host/hub.h | 388 ++--- src/host/ohci/ohci.c | 1302 +++++++------- src/host/ohci/ohci.h | 582 +++---- src/host/usbh.c | 1352 +++++++-------- src/osal/osal.h | 196 +-- src/osal/osal_none.h | 420 ++--- src/portable/nuvoton/nuc121/dcd_nuc121.c | 872 +++++----- src/tusb.c | 296 ++-- src/tusb.h | 236 +-- src/tusb_option.h | 480 +++--- 41 files changed, 12986 insertions(+), 12986 deletions(-) diff --git a/src/class/audio/audio.h b/src/class/audio/audio.h index 83b8906d..5bec14d8 100644 --- a/src/class/audio/audio.h +++ b/src/class/audio/audio.h @@ -1,100 +1,100 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2019 Ha Thach (tinyusb.org) - * - * 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. - * - * This file is part of the TinyUSB stack. - */ - -/** \ingroup group_class - * \defgroup ClassDriver_Audio Audio - * Currently only MIDI subclass is supported - * @{ */ - -#ifndef _TUSB_AUDIO_H__ -#define _TUSB_AUDIO_H__ - -#include "common/tusb_common.h" - -#ifdef __cplusplus - extern "C" { -#endif - -/// Audio Interface Subclass Codes -typedef enum -{ - AUDIO_SUBCLASS_CONTROL = 0x01 , ///< Audio Control - AUDIO_SUBCLASS_STREAMING , ///< Audio Streaming - AUDIO_SUBCLASS_MIDI_STREAMING , ///< MIDI Streaming -} audio_subclass_type_t; - -/// Audio Protocol Codes -typedef enum -{ - AUDIO_PROTOCOL_V1 = 0x00, ///< Version 1.0 - AUDIO_PROTOCOL_V2 = 0x20, ///< Version 2.0 - AUDIO_PROTOCOL_V3 = 0x30, ///< Version 3.0 -} audio_protocol_type_t; - -/// Audio Function Category Codes -typedef enum -{ - AUDIO_FUNC_DESKTOP_SPEAKER = 0x01, - AUDIO_FUNC_HOME_THEATER = 0x02, - AUDIO_FUNC_MICROPHONE = 0x03, - AUDIO_FUNC_HEADSET = 0x04, - AUDIO_FUNC_TELEPHONE = 0x05, - AUDIO_FUNC_CONVERTER = 0x06, - AUDIO_FUNC_SOUND_RECODER = 0x07, - AUDIO_FUNC_IO_BOX = 0x08, - AUDIO_FUNC_MUSICAL_INSTRUMENT = 0x09, - AUDIO_FUNC_PRO_AUDIO = 0x0A, - AUDIO_FUNC_AUDIO_VIDEO = 0x0B, - AUDIO_FUNC_CONTROL_PANEL = 0x0C -} audio_function_t; - -/// Audio Class-Specific AC Interface Descriptor Subtypes -typedef enum -{ - AUDIO_CS_INTERFACE_HEADER = 0x01, - AUDIO_CS_INTERFACE_INPUT_TERMINAL = 0x02, - AUDIO_CS_INTERFACE_OUTPUT_TERMINAL = 0x03, - AUDIO_CS_INTERFACE_MIXER_UNIT = 0x04, - AUDIO_CS_INTERFACE_SELECTOR_UNIT = 0x05, - AUDIO_CS_INTERFACE_FEATURE_UNIT = 0x06, - AUDIO_CS_INTERFACE_EFFECT_UNIT = 0x07, - AUDIO_CS_INTERFACE_PROCESSING_UNIT = 0x08, - AUDIO_CS_INTERFACE_EXTENSION_UNIT = 0x09, - AUDIO_CS_INTERFACE_CLOCK_SOURCE = 0x0A, - AUDIO_CS_INTERFACE_CLOCK_SELECTOR = 0x0B, - AUDIO_CS_INTERFACE_CLOCK_MULTIPLIER = 0x0C, - AUDIO_CS_INTERFACE_SAMPLE_RATE_CONVERTER = 0x0D, -} audio_cs_interface_subtype_t; - -/** @} */ - -#ifdef __cplusplus - } -#endif - -#endif - -/** @} */ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +/** \ingroup group_class + * \defgroup ClassDriver_Audio Audio + * Currently only MIDI subclass is supported + * @{ */ + +#ifndef _TUSB_AUDIO_H__ +#define _TUSB_AUDIO_H__ + +#include "common/tusb_common.h" + +#ifdef __cplusplus + extern "C" { +#endif + +/// Audio Interface Subclass Codes +typedef enum +{ + AUDIO_SUBCLASS_CONTROL = 0x01 , ///< Audio Control + AUDIO_SUBCLASS_STREAMING , ///< Audio Streaming + AUDIO_SUBCLASS_MIDI_STREAMING , ///< MIDI Streaming +} audio_subclass_type_t; + +/// Audio Protocol Codes +typedef enum +{ + AUDIO_PROTOCOL_V1 = 0x00, ///< Version 1.0 + AUDIO_PROTOCOL_V2 = 0x20, ///< Version 2.0 + AUDIO_PROTOCOL_V3 = 0x30, ///< Version 3.0 +} audio_protocol_type_t; + +/// Audio Function Category Codes +typedef enum +{ + AUDIO_FUNC_DESKTOP_SPEAKER = 0x01, + AUDIO_FUNC_HOME_THEATER = 0x02, + AUDIO_FUNC_MICROPHONE = 0x03, + AUDIO_FUNC_HEADSET = 0x04, + AUDIO_FUNC_TELEPHONE = 0x05, + AUDIO_FUNC_CONVERTER = 0x06, + AUDIO_FUNC_SOUND_RECODER = 0x07, + AUDIO_FUNC_IO_BOX = 0x08, + AUDIO_FUNC_MUSICAL_INSTRUMENT = 0x09, + AUDIO_FUNC_PRO_AUDIO = 0x0A, + AUDIO_FUNC_AUDIO_VIDEO = 0x0B, + AUDIO_FUNC_CONTROL_PANEL = 0x0C +} audio_function_t; + +/// Audio Class-Specific AC Interface Descriptor Subtypes +typedef enum +{ + AUDIO_CS_INTERFACE_HEADER = 0x01, + AUDIO_CS_INTERFACE_INPUT_TERMINAL = 0x02, + AUDIO_CS_INTERFACE_OUTPUT_TERMINAL = 0x03, + AUDIO_CS_INTERFACE_MIXER_UNIT = 0x04, + AUDIO_CS_INTERFACE_SELECTOR_UNIT = 0x05, + AUDIO_CS_INTERFACE_FEATURE_UNIT = 0x06, + AUDIO_CS_INTERFACE_EFFECT_UNIT = 0x07, + AUDIO_CS_INTERFACE_PROCESSING_UNIT = 0x08, + AUDIO_CS_INTERFACE_EXTENSION_UNIT = 0x09, + AUDIO_CS_INTERFACE_CLOCK_SOURCE = 0x0A, + AUDIO_CS_INTERFACE_CLOCK_SELECTOR = 0x0B, + AUDIO_CS_INTERFACE_CLOCK_MULTIPLIER = 0x0C, + AUDIO_CS_INTERFACE_SAMPLE_RATE_CONVERTER = 0x0D, +} audio_cs_interface_subtype_t; + +/** @} */ + +#ifdef __cplusplus + } +#endif + +#endif + +/** @} */ diff --git a/src/class/cdc/cdc.h b/src/class/cdc/cdc.h index 9cc8b82e..f0488acb 100644 --- a/src/class/cdc/cdc.h +++ b/src/class/cdc/cdc.h @@ -1,405 +1,405 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2019 Ha Thach (tinyusb.org) - * - * 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. - * - * This file is part of the TinyUSB stack. - */ - -/** \ingroup group_class - * \defgroup ClassDriver_CDC Communication Device Class (CDC) - * Currently only Abstract Control Model subclass is supported - * @{ */ - -#ifndef _TUSB_CDC_H__ -#define _TUSB_CDC_H__ - -#include "common/tusb_common.h" - -#ifdef __cplusplus - extern "C" { -#endif - -/** \defgroup ClassDriver_CDC_Common Common Definitions - * @{ */ - -// TODO remove -/// CDC Pipe ID, used to indicate which pipe the API is addressing to (Notification, Out, In) -typedef enum -{ - CDC_PIPE_NOTIFICATION , ///< Notification pipe - CDC_PIPE_DATA_IN , ///< Data in pipe - CDC_PIPE_DATA_OUT , ///< Data out pipe - CDC_PIPE_ERROR , ///< Invalid Pipe ID -}cdc_pipeid_t; - -//--------------------------------------------------------------------+ -// CDC Communication Interface Class -//--------------------------------------------------------------------+ - -/// Communication Interface Subclass Codes -typedef enum -{ - CDC_COMM_SUBCLASS_DIRECT_LINE_CONTROL_MODEL = 0x01 , ///< Direct Line Control Model [USBPSTN1.2] - CDC_COMM_SUBCLASS_ABSTRACT_CONTROL_MODEL , ///< Abstract Control Model [USBPSTN1.2] - CDC_COMM_SUBCLASS_TELEPHONE_CONTROL_MODEL , ///< Telephone Control Model [USBPSTN1.2] - CDC_COMM_SUBCLASS_MULTICHANNEL_CONTROL_MODEL , ///< Multi-Channel Control Model [USBISDN1.2] - CDC_COMM_SUBCLASS_CAPI_CONTROL_MODEL , ///< CAPI Control Model [USBISDN1.2] - CDC_COMM_SUBCLASS_ETHERNET_NETWORKING_CONTROL_MODEL , ///< Ethernet Networking Control Model [USBECM1.2] - CDC_COMM_SUBCLASS_ATM_NETWORKING_CONTROL_MODEL , ///< ATM Networking Control Model [USBATM1.2] - CDC_COMM_SUBCLASS_WIRELESS_HANDSET_CONTROL_MODEL , ///< Wireless Handset Control Model [USBWMC1.1] - CDC_COMM_SUBCLASS_DEVICE_MANAGEMENT , ///< Device Management [USBWMC1.1] - CDC_COMM_SUBCLASS_MOBILE_DIRECT_LINE_MODEL , ///< Mobile Direct Line Model [USBWMC1.1] - CDC_COMM_SUBCLASS_OBEX , ///< OBEX [USBWMC1.1] - CDC_COMM_SUBCLASS_ETHERNET_EMULATION_MODEL ///< Ethernet Emulation Model [USBEEM1.0] -} cdc_comm_sublcass_type_t; - -/// Communication Interface Protocol Codes -typedef enum -{ - CDC_COMM_PROTOCOL_NONE = 0x00 , ///< No specific protocol - CDC_COMM_PROTOCOL_ATCOMMAND , ///< AT Commands: V.250 etc - CDC_COMM_PROTOCOL_ATCOMMAND_PCCA_101 , ///< AT Commands defined by PCCA-101 - CDC_COMM_PROTOCOL_ATCOMMAND_PCCA_101_AND_ANNEXO , ///< AT Commands defined by PCCA-101 & Annex O - CDC_COMM_PROTOCOL_ATCOMMAND_GSM_707 , ///< AT Commands defined by GSM 07.07 - CDC_COMM_PROTOCOL_ATCOMMAND_3GPP_27007 , ///< AT Commands defined by 3GPP 27.007 - CDC_COMM_PROTOCOL_ATCOMMAND_CDMA , ///< AT Commands defined by TIA for CDMA - CDC_COMM_PROTOCOL_ETHERNET_EMULATION_MODEL ///< Ethernet Emulation Model -} cdc_comm_protocol_type_t; - -//------------- SubType Descriptor in COMM Functional Descriptor -------------// -/// Communication Interface SubType Descriptor -typedef enum -{ - CDC_FUNC_DESC_HEADER = 0x00 , ///< Header Functional Descriptor, which marks the beginning of the concatenated set of functional descriptors for the interface. - CDC_FUNC_DESC_CALL_MANAGEMENT = 0x01 , ///< Call Management Functional Descriptor. - CDC_FUNC_DESC_ABSTRACT_CONTROL_MANAGEMENT = 0x02 , ///< Abstract Control Management Functional Descriptor. - CDC_FUNC_DESC_DIRECT_LINE_MANAGEMENT = 0x03 , ///< Direct Line Management Functional Descriptor. - CDC_FUNC_DESC_TELEPHONE_RINGER = 0x04 , ///< Telephone Ringer Functional Descriptor. - CDC_FUNC_DESC_TELEPHONE_CALL_AND_LINE_STATE_REPORTING_CAPACITY = 0x05 , ///< Telephone Call and Line State Reporting Capabilities Functional Descriptor. - CDC_FUNC_DESC_UNION = 0x06 , ///< Union Functional Descriptor - CDC_FUNC_DESC_COUNTRY_SELECTION = 0x07 , ///< Country Selection Functional Descriptor - CDC_FUNC_DESC_TELEPHONE_OPERATIONAL_MODES = 0x08 , ///< Telephone Operational ModesFunctional Descriptor - CDC_FUNC_DESC_USB_TERMINAL = 0x09 , ///< USB Terminal Functional Descriptor - CDC_FUNC_DESC_NETWORK_CHANNEL_TERMINAL = 0x0A , ///< Network Channel Terminal Descriptor - CDC_FUNC_DESC_PROTOCOL_UNIT = 0x0B , ///< Protocol Unit Functional Descriptor - CDC_FUNC_DESC_EXTENSION_UNIT = 0x0C , ///< Extension Unit Functional Descriptor - CDC_FUNC_DESC_MULTICHANEL_MANAGEMENT = 0x0D , ///< Multi-Channel Management Functional Descriptor - CDC_FUNC_DESC_CAPI_CONTROL_MANAGEMENT = 0x0E , ///< CAPI Control Management Functional Descriptor - CDC_FUNC_DESC_ETHERNET_NETWORKING = 0x0F , ///< Ethernet Networking Functional Descriptor - CDC_FUNC_DESC_ATM_NETWORKING = 0x10 , ///< ATM Networking Functional Descriptor - CDC_FUNC_DESC_WIRELESS_HANDSET_CONTROL_MODEL = 0x11 , ///< Wireless Handset Control Model Functional Descriptor - CDC_FUNC_DESC_MOBILE_DIRECT_LINE_MODEL = 0x12 , ///< Mobile Direct Line Model Functional Descriptor - CDC_FUNC_DESC_MOBILE_DIRECT_LINE_MODEL_DETAIL = 0x13 , ///< MDLM Detail Functional Descriptor - CDC_FUNC_DESC_DEVICE_MANAGEMENT_MODEL = 0x14 , ///< Device Management Model Functional Descriptor - CDC_FUNC_DESC_OBEX = 0x15 , ///< OBEX Functional Descriptor - CDC_FUNC_DESC_COMMAND_SET = 0x16 , ///< Command Set Functional Descriptor - CDC_FUNC_DESC_COMMAND_SET_DETAIL = 0x17 , ///< Command Set Detail Functional Descriptor - CDC_FUNC_DESC_TELEPHONE_CONTROL_MODEL = 0x18 , ///< Telephone Control Model Functional Descriptor - CDC_FUNC_DESC_OBEX_SERVICE_IDENTIFIER = 0x19 ///< OBEX Service Identifier Functional Descriptor -}cdc_func_desc_type_t; - -//--------------------------------------------------------------------+ -// CDC Data Interface Class -//--------------------------------------------------------------------+ - -// SUBCLASS code of Data Interface is not used and should/must be zero -/// Data Interface Protocol Codes -typedef enum{ - CDC_DATA_PROTOCOL_ISDN_BRI = 0x30, ///< Physical interface protocol for ISDN BRI - CDC_DATA_PROTOCOL_HDLC = 0x31, ///< HDLC - CDC_DATA_PROTOCOL_TRANSPARENT = 0x32, ///< Transparent - CDC_DATA_PROTOCOL_Q921_MANAGEMENT = 0x50, ///< Management protocol for Q.921 data link protocol - CDC_DATA_PROTOCOL_Q921_DATA_LINK = 0x51, ///< Data link protocol for Q.931 - CDC_DATA_PROTOCOL_Q921_TEI_MULTIPLEXOR = 0x52, ///< TEI-multiplexor for Q.921 data link protocol - CDC_DATA_PROTOCOL_V42BIS_DATA_COMPRESSION = 0x90, ///< Data compression procedures - CDC_DATA_PROTOCOL_EURO_ISDN = 0x91, ///< Euro-ISDN protocol control - CDC_DATA_PROTOCOL_V24_RATE_ADAPTION_TO_ISDN = 0x92, ///< V.24 rate adaptation to ISDN - CDC_DATA_PROTOCOL_CAPI_COMMAND = 0x93, ///< CAPI Commands - CDC_DATA_PROTOCOL_HOST_BASED_DRIVER = 0xFD, ///< Host based driver. Note: This protocol code should only be used in messages between host and device to identify the host driver portion of a protocol stack. - CDC_DATA_PROTOCOL_IN_PROTOCOL_UNIT_FUNCTIONAL_DESCRIPTOR = 0xFE ///< The protocol(s) are described using a ProtocolUnit Functional Descriptors on Communications Class Interface -}cdc_data_protocol_type_t; - -//--------------------------------------------------------------------+ -// Management Element Request (Control Endpoint) -//--------------------------------------------------------------------+ - -/// Communication Interface Management Element Request Codes -typedef enum -{ - CDC_REQUEST_SEND_ENCAPSULATED_COMMAND = 0x00, ///< is used to issue a command in the format of the supported control protocol of the Communications Class interface - CDC_REQUEST_GET_ENCAPSULATED_RESPONSE = 0x01, ///< is used to request a response in the format of the supported control protocol of the Communications Class interface. - - CDC_REQUEST_SET_COMM_FEATURE = 0x02, - CDC_REQUEST_GET_COMM_FEATURE = 0x03, - CDC_REQUEST_CLEAR_COMM_FEATURE = 0x04, - - CDC_REQUEST_SET_AUX_LINE_STATE = 0x10, - CDC_REQUEST_SET_HOOK_STATE = 0x11, - CDC_REQUEST_PULSE_SETUP = 0x12, - CDC_REQUEST_SEND_PULSE = 0x13, - CDC_REQUEST_SET_PULSE_TIME = 0x14, - CDC_REQUEST_RING_AUX_JACK = 0x15, - - CDC_REQUEST_SET_LINE_CODING = 0x20, - CDC_REQUEST_GET_LINE_CODING = 0x21, - CDC_REQUEST_SET_CONTROL_LINE_STATE = 0x22, - CDC_REQUEST_SEND_BREAK = 0x23, - - CDC_REQUEST_SET_RINGER_PARMS = 0x30, - CDC_REQUEST_GET_RINGER_PARMS = 0x31, - CDC_REQUEST_SET_OPERATION_PARMS = 0x32, - CDC_REQUEST_GET_OPERATION_PARMS = 0x33, - CDC_REQUEST_SET_LINE_PARMS = 0x34, - CDC_REQUEST_GET_LINE_PARMS = 0x35, - CDC_REQUEST_DIAL_DIGITS = 0x36, - CDC_REQUEST_SET_UNIT_PARAMETER = 0x37, - CDC_REQUEST_GET_UNIT_PARAMETER = 0x38, - CDC_REQUEST_CLEAR_UNIT_PARAMETER = 0x39, - CDC_REQUEST_GET_PROFILE = 0x3A, - - CDC_REQUEST_SET_ETHERNET_MULTICAST_FILTERS = 0x40, - CDC_REQUEST_SET_ETHERNET_POWER_MANAGEMENT_PATTERN_FILTER = 0x41, - CDC_REQUEST_GET_ETHERNET_POWER_MANAGEMENT_PATTERN_FILTER = 0x42, - CDC_REQUEST_SET_ETHERNET_PACKET_FILTER = 0x43, - CDC_REQUEST_GET_ETHERNET_STATISTIC = 0x44, - - CDC_REQUEST_SET_ATM_DATA_FORMAT = 0x50, - CDC_REQUEST_GET_ATM_DEVICE_STATISTICS = 0x51, - CDC_REQUEST_SET_ATM_DEFAULT_VC = 0x52, - CDC_REQUEST_GET_ATM_VC_STATISTICS = 0x53, - - CDC_REQUEST_MDLM_SEMANTIC_MODEL = 0x60, -}cdc_management_request_t; - -//--------------------------------------------------------------------+ -// Management Elemenent Notification (Notification Endpoint) -//--------------------------------------------------------------------+ - -/// Communication Interface Management Element Notification Codes -typedef enum -{ - NETWORK_CONNECTION = 0x00, ///< This notification allows the device to notify the host about network connection status. - RESPONSE_AVAILABLE = 0x01, ///< This notification allows the device to notify the hostthat a response is available. This response can be retrieved with a subsequent \ref CDC_REQUEST_GET_ENCAPSULATED_RESPONSE request. - - AUX_JACK_HOOK_STATE = 0x08, - RING_DETECT = 0x09, - - SERIAL_STATE = 0x20, - - CALL_STATE_CHANGE = 0x28, - LINE_STATE_CHANGE = 0x29, - CONNECTION_SPEED_CHANGE = 0x2A, ///< This notification allows the device to inform the host-networking driver that a change in either the upstream or the downstream bit rate of the connection has occurred - MDLM_SEMANTIC_MODEL_NOTIFICATION = 0x40, -}cdc_notification_request_t; - -//--------------------------------------------------------------------+ -// Class Specific Functional Descriptor (Communication Interface) -//--------------------------------------------------------------------+ - -/// Header Functional Descriptor (Communication Interface) -typedef struct TU_ATTR_PACKED -{ - uint8_t bLength ; ///< Size of this descriptor in bytes. - uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific - uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above CDC_FUNC_DESC_ - uint16_t bcdCDC ; ///< CDC release number in Binary-Coded Decimal -}cdc_desc_func_header_t; - -/// Union Functional Descriptor (Communication Interface) -typedef struct TU_ATTR_PACKED -{ - uint8_t bLength ; ///< Size of this descriptor in bytes. - uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific - uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above CDC_FUCN_DESC_ - uint8_t bControlInterface ; ///< Interface number of Communication Interface - uint8_t bSubordinateInterface ; ///< Array of Interface number of Data Interface -}cdc_desc_func_union_t; - -#define cdc_desc_func_union_n_t(no_slave)\ - struct TU_ATTR_PACKED { \ - uint8_t bLength ;\ - uint8_t bDescriptorType ;\ - uint8_t bDescriptorSubType ;\ - uint8_t bControlInterface ;\ - uint8_t bSubordinateInterface[no_slave] ;\ -} - -/// Country Selection Functional Descriptor (Communication Interface) -typedef struct TU_ATTR_PACKED -{ - uint8_t bLength ; ///< Size of this descriptor in bytes. - uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific - uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above CDC_FUCN_DESC_ - uint8_t iCountryCodeRelDate ; ///< Index of a string giving the release date for the implemented ISO 3166 Country Codes. - uint16_t wCountryCode ; ///< Country code in the format as defined in [ISO3166], release date as specified inoffset 3 for the first supported country. -}cdc_desc_func_country_selection_t; - -#define cdc_desc_func_country_selection_n_t(no_country) \ - struct TU_ATTR_PACKED {\ - uint8_t bLength ;\ - uint8_t bDescriptorType ;\ - uint8_t bDescriptorSubType ;\ - uint8_t iCountryCodeRelDate ;\ - uint16_t wCountryCode[no_country] ;\ -} - -//--------------------------------------------------------------------+ -// PUBLIC SWITCHED TELEPHONE NETWORK (PSTN) SUBCLASS -//--------------------------------------------------------------------+ - -/// \brief Call Management Functional Descriptor -/// \details This functional descriptor describes the processing of calls for the Communications Class interface. -typedef struct TU_ATTR_PACKED -{ - uint8_t bLength ; ///< Size of this descriptor in bytes. - uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific - uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above CDC_FUCN_DESC_ - - struct { - uint8_t handle_call : 1; ///< 0 - Device sends/receives call management information only over the Communications Class interface. 1 - Device can send/receive call management information over a Data Class interface. - uint8_t send_recv_call : 1; ///< 0 - Device does not handle call management itself. 1 - Device handles call management itself. - uint8_t : 0; - } bmCapabilities; - - uint8_t bDataInterface; -}cdc_desc_func_call_management_t; - - -typedef struct TU_ATTR_PACKED -{ - uint8_t support_comm_request : 1; ///< Device supports the request combination of Set_Comm_Feature, Clear_Comm_Feature, and Get_Comm_Feature. - uint8_t support_line_request : 1; ///< Device supports the request combination of Set_Line_Coding, Set_Control_Line_State, Get_Line_Coding, and the notification Serial_State. - uint8_t support_send_break : 1; ///< Device supports the request Send_Break - uint8_t support_notification_network_connection : 1; ///< Device supports the notification Network_Connection. - uint8_t : 0; -}cdc_acm_capability_t; - -TU_VERIFY_STATIC(sizeof(cdc_acm_capability_t) == 1, "mostly problem with compiler"); - -/// \brief Abstract Control Management Functional Descriptor -/// \details This functional descriptor describes the commands supported by by the Communications Class interface with SubClass code of \ref CDC_COMM_SUBCLASS_ABSTRACT_CONTROL_MODEL -typedef struct TU_ATTR_PACKED -{ - uint8_t bLength ; ///< Size of this descriptor in bytes. - uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific - uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above CDC_FUCN_DESC_ - cdc_acm_capability_t bmCapabilities ; -}cdc_desc_func_acm_t; - -/// \brief Direct Line Management Functional Descriptor -/// \details This functional descriptor describes the commands supported by the Communications Class interface with SubClass code of \ref CDC_FUNC_DESC_DIRECT_LINE_MANAGEMENT -typedef struct TU_ATTR_PACKED -{ - uint8_t bLength ; ///< Size of this descriptor in bytes. - uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific - uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above CDC_FUCN_DESC_ - struct { - uint8_t require_pulse_setup : 1; ///< Device requires extra Pulse_Setup request during pulse dialing sequence to disengage holding circuit. - uint8_t support_aux_request : 1; ///< Device supports the request combination of Set_Aux_Line_State, Ring_Aux_Jack, and notification Aux_Jack_Hook_State. - uint8_t support_pulse_request : 1; ///< Device supports the request combination of Pulse_Setup, Send_Pulse, and Set_Pulse_Time. - uint8_t : 0; - } bmCapabilities; -}cdc_desc_func_direct_line_management_t; - -/// \brief Telephone Ringer Functional Descriptor -/// \details The Telephone Ringer functional descriptor describes the ringer capabilities supported by the Communications Class interface, -/// with the SubClass code of \ref CDC_COMM_SUBCLASS_TELEPHONE_CONTROL_MODEL -typedef struct TU_ATTR_PACKED -{ - uint8_t bLength ; ///< Size of this descriptor in bytes. - uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific - uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above CDC_FUCN_DESC_ - uint8_t bRingerVolSteps ; - uint8_t bNumRingerPatterns ; -}cdc_desc_func_telephone_ringer_t; - -/// \brief Telephone Operational Modes Functional Descriptor -/// \details The Telephone Operational Modes functional descriptor describes the operational modes supported by -/// the Communications Class interface, with the SubClass code of \ref CDC_COMM_SUBCLASS_TELEPHONE_CONTROL_MODEL -typedef struct TU_ATTR_PACKED -{ - uint8_t bLength ; ///< Size of this descriptor in bytes. - uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific - uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above CDC_FUCN_DESC_ - struct { - uint8_t simple_mode : 1; - uint8_t standalone_mode : 1; - uint8_t computer_centric_mode : 1; - uint8_t : 0; - } bmCapabilities; -}cdc_desc_func_telephone_operational_modes_t; - -/// \brief Telephone Call and Line State Reporting Capabilities Descriptor -/// \details The Telephone Call and Line State Reporting Capabilities functional descriptor describes the abilities of a -/// telephone device to report optional call and line states. -typedef struct TU_ATTR_PACKED -{ - uint8_t bLength ; ///< Size of this descriptor in bytes. - uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific - uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above CDC_FUCN_DESC_ - struct { - uint32_t interrupted_dialtone : 1; ///< 0 : Reports only dialtone (does not differentiate between normal and interrupted dialtone). 1 : Reports interrupted dialtone in addition to normal dialtone - uint32_t ringback_busy_fastbusy : 1; ///< 0 : Reports only dialing state. 1 : Reports ringback, busy, and fast busy states. - uint32_t caller_id : 1; ///< 0 : Does not report caller ID. 1 : Reports caller ID information. - uint32_t incoming_distinctive : 1; ///< 0 : Reports only incoming ringing. 1 : Reports incoming distinctive ringing patterns. - uint32_t dual_tone_multi_freq : 1; ///< 0 : Cannot report dual tone multi-frequency (DTMF) digits input remotely over the telephone line. 1 : Can report DTMF digits input remotely over the telephone line. - uint32_t line_state_change : 1; ///< 0 : Does not support line state change notification. 1 : Does support line state change notification - uint32_t : 0; - } bmCapabilities; -}cdc_desc_func_telephone_call_state_reporting_capabilities_t; - -static inline uint8_t cdc_functional_desc_typeof(uint8_t const * p_desc) -{ - return p_desc[2]; -} - -//--------------------------------------------------------------------+ -// Requests -//--------------------------------------------------------------------+ -typedef struct TU_ATTR_PACKED -{ - uint32_t bit_rate; - uint8_t stop_bits; ///< 0: 1 stop bit - 1: 1.5 stop bits - 2: 2 stop bits - uint8_t parity; ///< 0: None - 1: Odd - 2: Even - 3: Mark - 4: Space - uint8_t data_bits; ///< can be 5, 6, 7, 8 or 16 -} cdc_line_coding_t; - -TU_VERIFY_STATIC(sizeof(cdc_line_coding_t) == 7, "size is not correct"); - -typedef struct TU_ATTR_PACKED -{ - uint16_t dte_is_present : 1; ///< Indicates to DCE if DTE is presentor not. This signal corresponds to V.24 signal 108/2 and RS-232 signal DTR. - uint16_t half_duplex_carrier_control : 1; - uint16_t : 14; -} cdc_line_control_state_t; - -TU_VERIFY_STATIC(sizeof(cdc_line_control_state_t) == 2, "size is not correct"); - -/** @} */ - -#ifdef __cplusplus - } -#endif - -#endif - -/** @} */ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +/** \ingroup group_class + * \defgroup ClassDriver_CDC Communication Device Class (CDC) + * Currently only Abstract Control Model subclass is supported + * @{ */ + +#ifndef _TUSB_CDC_H__ +#define _TUSB_CDC_H__ + +#include "common/tusb_common.h" + +#ifdef __cplusplus + extern "C" { +#endif + +/** \defgroup ClassDriver_CDC_Common Common Definitions + * @{ */ + +// TODO remove +/// CDC Pipe ID, used to indicate which pipe the API is addressing to (Notification, Out, In) +typedef enum +{ + CDC_PIPE_NOTIFICATION , ///< Notification pipe + CDC_PIPE_DATA_IN , ///< Data in pipe + CDC_PIPE_DATA_OUT , ///< Data out pipe + CDC_PIPE_ERROR , ///< Invalid Pipe ID +}cdc_pipeid_t; + +//--------------------------------------------------------------------+ +// CDC Communication Interface Class +//--------------------------------------------------------------------+ + +/// Communication Interface Subclass Codes +typedef enum +{ + CDC_COMM_SUBCLASS_DIRECT_LINE_CONTROL_MODEL = 0x01 , ///< Direct Line Control Model [USBPSTN1.2] + CDC_COMM_SUBCLASS_ABSTRACT_CONTROL_MODEL , ///< Abstract Control Model [USBPSTN1.2] + CDC_COMM_SUBCLASS_TELEPHONE_CONTROL_MODEL , ///< Telephone Control Model [USBPSTN1.2] + CDC_COMM_SUBCLASS_MULTICHANNEL_CONTROL_MODEL , ///< Multi-Channel Control Model [USBISDN1.2] + CDC_COMM_SUBCLASS_CAPI_CONTROL_MODEL , ///< CAPI Control Model [USBISDN1.2] + CDC_COMM_SUBCLASS_ETHERNET_NETWORKING_CONTROL_MODEL , ///< Ethernet Networking Control Model [USBECM1.2] + CDC_COMM_SUBCLASS_ATM_NETWORKING_CONTROL_MODEL , ///< ATM Networking Control Model [USBATM1.2] + CDC_COMM_SUBCLASS_WIRELESS_HANDSET_CONTROL_MODEL , ///< Wireless Handset Control Model [USBWMC1.1] + CDC_COMM_SUBCLASS_DEVICE_MANAGEMENT , ///< Device Management [USBWMC1.1] + CDC_COMM_SUBCLASS_MOBILE_DIRECT_LINE_MODEL , ///< Mobile Direct Line Model [USBWMC1.1] + CDC_COMM_SUBCLASS_OBEX , ///< OBEX [USBWMC1.1] + CDC_COMM_SUBCLASS_ETHERNET_EMULATION_MODEL ///< Ethernet Emulation Model [USBEEM1.0] +} cdc_comm_sublcass_type_t; + +/// Communication Interface Protocol Codes +typedef enum +{ + CDC_COMM_PROTOCOL_NONE = 0x00 , ///< No specific protocol + CDC_COMM_PROTOCOL_ATCOMMAND , ///< AT Commands: V.250 etc + CDC_COMM_PROTOCOL_ATCOMMAND_PCCA_101 , ///< AT Commands defined by PCCA-101 + CDC_COMM_PROTOCOL_ATCOMMAND_PCCA_101_AND_ANNEXO , ///< AT Commands defined by PCCA-101 & Annex O + CDC_COMM_PROTOCOL_ATCOMMAND_GSM_707 , ///< AT Commands defined by GSM 07.07 + CDC_COMM_PROTOCOL_ATCOMMAND_3GPP_27007 , ///< AT Commands defined by 3GPP 27.007 + CDC_COMM_PROTOCOL_ATCOMMAND_CDMA , ///< AT Commands defined by TIA for CDMA + CDC_COMM_PROTOCOL_ETHERNET_EMULATION_MODEL ///< Ethernet Emulation Model +} cdc_comm_protocol_type_t; + +//------------- SubType Descriptor in COMM Functional Descriptor -------------// +/// Communication Interface SubType Descriptor +typedef enum +{ + CDC_FUNC_DESC_HEADER = 0x00 , ///< Header Functional Descriptor, which marks the beginning of the concatenated set of functional descriptors for the interface. + CDC_FUNC_DESC_CALL_MANAGEMENT = 0x01 , ///< Call Management Functional Descriptor. + CDC_FUNC_DESC_ABSTRACT_CONTROL_MANAGEMENT = 0x02 , ///< Abstract Control Management Functional Descriptor. + CDC_FUNC_DESC_DIRECT_LINE_MANAGEMENT = 0x03 , ///< Direct Line Management Functional Descriptor. + CDC_FUNC_DESC_TELEPHONE_RINGER = 0x04 , ///< Telephone Ringer Functional Descriptor. + CDC_FUNC_DESC_TELEPHONE_CALL_AND_LINE_STATE_REPORTING_CAPACITY = 0x05 , ///< Telephone Call and Line State Reporting Capabilities Functional Descriptor. + CDC_FUNC_DESC_UNION = 0x06 , ///< Union Functional Descriptor + CDC_FUNC_DESC_COUNTRY_SELECTION = 0x07 , ///< Country Selection Functional Descriptor + CDC_FUNC_DESC_TELEPHONE_OPERATIONAL_MODES = 0x08 , ///< Telephone Operational ModesFunctional Descriptor + CDC_FUNC_DESC_USB_TERMINAL = 0x09 , ///< USB Terminal Functional Descriptor + CDC_FUNC_DESC_NETWORK_CHANNEL_TERMINAL = 0x0A , ///< Network Channel Terminal Descriptor + CDC_FUNC_DESC_PROTOCOL_UNIT = 0x0B , ///< Protocol Unit Functional Descriptor + CDC_FUNC_DESC_EXTENSION_UNIT = 0x0C , ///< Extension Unit Functional Descriptor + CDC_FUNC_DESC_MULTICHANEL_MANAGEMENT = 0x0D , ///< Multi-Channel Management Functional Descriptor + CDC_FUNC_DESC_CAPI_CONTROL_MANAGEMENT = 0x0E , ///< CAPI Control Management Functional Descriptor + CDC_FUNC_DESC_ETHERNET_NETWORKING = 0x0F , ///< Ethernet Networking Functional Descriptor + CDC_FUNC_DESC_ATM_NETWORKING = 0x10 , ///< ATM Networking Functional Descriptor + CDC_FUNC_DESC_WIRELESS_HANDSET_CONTROL_MODEL = 0x11 , ///< Wireless Handset Control Model Functional Descriptor + CDC_FUNC_DESC_MOBILE_DIRECT_LINE_MODEL = 0x12 , ///< Mobile Direct Line Model Functional Descriptor + CDC_FUNC_DESC_MOBILE_DIRECT_LINE_MODEL_DETAIL = 0x13 , ///< MDLM Detail Functional Descriptor + CDC_FUNC_DESC_DEVICE_MANAGEMENT_MODEL = 0x14 , ///< Device Management Model Functional Descriptor + CDC_FUNC_DESC_OBEX = 0x15 , ///< OBEX Functional Descriptor + CDC_FUNC_DESC_COMMAND_SET = 0x16 , ///< Command Set Functional Descriptor + CDC_FUNC_DESC_COMMAND_SET_DETAIL = 0x17 , ///< Command Set Detail Functional Descriptor + CDC_FUNC_DESC_TELEPHONE_CONTROL_MODEL = 0x18 , ///< Telephone Control Model Functional Descriptor + CDC_FUNC_DESC_OBEX_SERVICE_IDENTIFIER = 0x19 ///< OBEX Service Identifier Functional Descriptor +}cdc_func_desc_type_t; + +//--------------------------------------------------------------------+ +// CDC Data Interface Class +//--------------------------------------------------------------------+ + +// SUBCLASS code of Data Interface is not used and should/must be zero +/// Data Interface Protocol Codes +typedef enum{ + CDC_DATA_PROTOCOL_ISDN_BRI = 0x30, ///< Physical interface protocol for ISDN BRI + CDC_DATA_PROTOCOL_HDLC = 0x31, ///< HDLC + CDC_DATA_PROTOCOL_TRANSPARENT = 0x32, ///< Transparent + CDC_DATA_PROTOCOL_Q921_MANAGEMENT = 0x50, ///< Management protocol for Q.921 data link protocol + CDC_DATA_PROTOCOL_Q921_DATA_LINK = 0x51, ///< Data link protocol for Q.931 + CDC_DATA_PROTOCOL_Q921_TEI_MULTIPLEXOR = 0x52, ///< TEI-multiplexor for Q.921 data link protocol + CDC_DATA_PROTOCOL_V42BIS_DATA_COMPRESSION = 0x90, ///< Data compression procedures + CDC_DATA_PROTOCOL_EURO_ISDN = 0x91, ///< Euro-ISDN protocol control + CDC_DATA_PROTOCOL_V24_RATE_ADAPTION_TO_ISDN = 0x92, ///< V.24 rate adaptation to ISDN + CDC_DATA_PROTOCOL_CAPI_COMMAND = 0x93, ///< CAPI Commands + CDC_DATA_PROTOCOL_HOST_BASED_DRIVER = 0xFD, ///< Host based driver. Note: This protocol code should only be used in messages between host and device to identify the host driver portion of a protocol stack. + CDC_DATA_PROTOCOL_IN_PROTOCOL_UNIT_FUNCTIONAL_DESCRIPTOR = 0xFE ///< The protocol(s) are described using a ProtocolUnit Functional Descriptors on Communications Class Interface +}cdc_data_protocol_type_t; + +//--------------------------------------------------------------------+ +// Management Element Request (Control Endpoint) +//--------------------------------------------------------------------+ + +/// Communication Interface Management Element Request Codes +typedef enum +{ + CDC_REQUEST_SEND_ENCAPSULATED_COMMAND = 0x00, ///< is used to issue a command in the format of the supported control protocol of the Communications Class interface + CDC_REQUEST_GET_ENCAPSULATED_RESPONSE = 0x01, ///< is used to request a response in the format of the supported control protocol of the Communications Class interface. + + CDC_REQUEST_SET_COMM_FEATURE = 0x02, + CDC_REQUEST_GET_COMM_FEATURE = 0x03, + CDC_REQUEST_CLEAR_COMM_FEATURE = 0x04, + + CDC_REQUEST_SET_AUX_LINE_STATE = 0x10, + CDC_REQUEST_SET_HOOK_STATE = 0x11, + CDC_REQUEST_PULSE_SETUP = 0x12, + CDC_REQUEST_SEND_PULSE = 0x13, + CDC_REQUEST_SET_PULSE_TIME = 0x14, + CDC_REQUEST_RING_AUX_JACK = 0x15, + + CDC_REQUEST_SET_LINE_CODING = 0x20, + CDC_REQUEST_GET_LINE_CODING = 0x21, + CDC_REQUEST_SET_CONTROL_LINE_STATE = 0x22, + CDC_REQUEST_SEND_BREAK = 0x23, + + CDC_REQUEST_SET_RINGER_PARMS = 0x30, + CDC_REQUEST_GET_RINGER_PARMS = 0x31, + CDC_REQUEST_SET_OPERATION_PARMS = 0x32, + CDC_REQUEST_GET_OPERATION_PARMS = 0x33, + CDC_REQUEST_SET_LINE_PARMS = 0x34, + CDC_REQUEST_GET_LINE_PARMS = 0x35, + CDC_REQUEST_DIAL_DIGITS = 0x36, + CDC_REQUEST_SET_UNIT_PARAMETER = 0x37, + CDC_REQUEST_GET_UNIT_PARAMETER = 0x38, + CDC_REQUEST_CLEAR_UNIT_PARAMETER = 0x39, + CDC_REQUEST_GET_PROFILE = 0x3A, + + CDC_REQUEST_SET_ETHERNET_MULTICAST_FILTERS = 0x40, + CDC_REQUEST_SET_ETHERNET_POWER_MANAGEMENT_PATTERN_FILTER = 0x41, + CDC_REQUEST_GET_ETHERNET_POWER_MANAGEMENT_PATTERN_FILTER = 0x42, + CDC_REQUEST_SET_ETHERNET_PACKET_FILTER = 0x43, + CDC_REQUEST_GET_ETHERNET_STATISTIC = 0x44, + + CDC_REQUEST_SET_ATM_DATA_FORMAT = 0x50, + CDC_REQUEST_GET_ATM_DEVICE_STATISTICS = 0x51, + CDC_REQUEST_SET_ATM_DEFAULT_VC = 0x52, + CDC_REQUEST_GET_ATM_VC_STATISTICS = 0x53, + + CDC_REQUEST_MDLM_SEMANTIC_MODEL = 0x60, +}cdc_management_request_t; + +//--------------------------------------------------------------------+ +// Management Elemenent Notification (Notification Endpoint) +//--------------------------------------------------------------------+ + +/// Communication Interface Management Element Notification Codes +typedef enum +{ + NETWORK_CONNECTION = 0x00, ///< This notification allows the device to notify the host about network connection status. + RESPONSE_AVAILABLE = 0x01, ///< This notification allows the device to notify the hostthat a response is available. This response can be retrieved with a subsequent \ref CDC_REQUEST_GET_ENCAPSULATED_RESPONSE request. + + AUX_JACK_HOOK_STATE = 0x08, + RING_DETECT = 0x09, + + SERIAL_STATE = 0x20, + + CALL_STATE_CHANGE = 0x28, + LINE_STATE_CHANGE = 0x29, + CONNECTION_SPEED_CHANGE = 0x2A, ///< This notification allows the device to inform the host-networking driver that a change in either the upstream or the downstream bit rate of the connection has occurred + MDLM_SEMANTIC_MODEL_NOTIFICATION = 0x40, +}cdc_notification_request_t; + +//--------------------------------------------------------------------+ +// Class Specific Functional Descriptor (Communication Interface) +//--------------------------------------------------------------------+ + +/// Header Functional Descriptor (Communication Interface) +typedef struct TU_ATTR_PACKED +{ + uint8_t bLength ; ///< Size of this descriptor in bytes. + uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific + uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above CDC_FUNC_DESC_ + uint16_t bcdCDC ; ///< CDC release number in Binary-Coded Decimal +}cdc_desc_func_header_t; + +/// Union Functional Descriptor (Communication Interface) +typedef struct TU_ATTR_PACKED +{ + uint8_t bLength ; ///< Size of this descriptor in bytes. + uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific + uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above CDC_FUCN_DESC_ + uint8_t bControlInterface ; ///< Interface number of Communication Interface + uint8_t bSubordinateInterface ; ///< Array of Interface number of Data Interface +}cdc_desc_func_union_t; + +#define cdc_desc_func_union_n_t(no_slave)\ + struct TU_ATTR_PACKED { \ + uint8_t bLength ;\ + uint8_t bDescriptorType ;\ + uint8_t bDescriptorSubType ;\ + uint8_t bControlInterface ;\ + uint8_t bSubordinateInterface[no_slave] ;\ +} + +/// Country Selection Functional Descriptor (Communication Interface) +typedef struct TU_ATTR_PACKED +{ + uint8_t bLength ; ///< Size of this descriptor in bytes. + uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific + uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above CDC_FUCN_DESC_ + uint8_t iCountryCodeRelDate ; ///< Index of a string giving the release date for the implemented ISO 3166 Country Codes. + uint16_t wCountryCode ; ///< Country code in the format as defined in [ISO3166], release date as specified inoffset 3 for the first supported country. +}cdc_desc_func_country_selection_t; + +#define cdc_desc_func_country_selection_n_t(no_country) \ + struct TU_ATTR_PACKED {\ + uint8_t bLength ;\ + uint8_t bDescriptorType ;\ + uint8_t bDescriptorSubType ;\ + uint8_t iCountryCodeRelDate ;\ + uint16_t wCountryCode[no_country] ;\ +} + +//--------------------------------------------------------------------+ +// PUBLIC SWITCHED TELEPHONE NETWORK (PSTN) SUBCLASS +//--------------------------------------------------------------------+ + +/// \brief Call Management Functional Descriptor +/// \details This functional descriptor describes the processing of calls for the Communications Class interface. +typedef struct TU_ATTR_PACKED +{ + uint8_t bLength ; ///< Size of this descriptor in bytes. + uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific + uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above CDC_FUCN_DESC_ + + struct { + uint8_t handle_call : 1; ///< 0 - Device sends/receives call management information only over the Communications Class interface. 1 - Device can send/receive call management information over a Data Class interface. + uint8_t send_recv_call : 1; ///< 0 - Device does not handle call management itself. 1 - Device handles call management itself. + uint8_t : 0; + } bmCapabilities; + + uint8_t bDataInterface; +}cdc_desc_func_call_management_t; + + +typedef struct TU_ATTR_PACKED +{ + uint8_t support_comm_request : 1; ///< Device supports the request combination of Set_Comm_Feature, Clear_Comm_Feature, and Get_Comm_Feature. + uint8_t support_line_request : 1; ///< Device supports the request combination of Set_Line_Coding, Set_Control_Line_State, Get_Line_Coding, and the notification Serial_State. + uint8_t support_send_break : 1; ///< Device supports the request Send_Break + uint8_t support_notification_network_connection : 1; ///< Device supports the notification Network_Connection. + uint8_t : 0; +}cdc_acm_capability_t; + +TU_VERIFY_STATIC(sizeof(cdc_acm_capability_t) == 1, "mostly problem with compiler"); + +/// \brief Abstract Control Management Functional Descriptor +/// \details This functional descriptor describes the commands supported by by the Communications Class interface with SubClass code of \ref CDC_COMM_SUBCLASS_ABSTRACT_CONTROL_MODEL +typedef struct TU_ATTR_PACKED +{ + uint8_t bLength ; ///< Size of this descriptor in bytes. + uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific + uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above CDC_FUCN_DESC_ + cdc_acm_capability_t bmCapabilities ; +}cdc_desc_func_acm_t; + +/// \brief Direct Line Management Functional Descriptor +/// \details This functional descriptor describes the commands supported by the Communications Class interface with SubClass code of \ref CDC_FUNC_DESC_DIRECT_LINE_MANAGEMENT +typedef struct TU_ATTR_PACKED +{ + uint8_t bLength ; ///< Size of this descriptor in bytes. + uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific + uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above CDC_FUCN_DESC_ + struct { + uint8_t require_pulse_setup : 1; ///< Device requires extra Pulse_Setup request during pulse dialing sequence to disengage holding circuit. + uint8_t support_aux_request : 1; ///< Device supports the request combination of Set_Aux_Line_State, Ring_Aux_Jack, and notification Aux_Jack_Hook_State. + uint8_t support_pulse_request : 1; ///< Device supports the request combination of Pulse_Setup, Send_Pulse, and Set_Pulse_Time. + uint8_t : 0; + } bmCapabilities; +}cdc_desc_func_direct_line_management_t; + +/// \brief Telephone Ringer Functional Descriptor +/// \details The Telephone Ringer functional descriptor describes the ringer capabilities supported by the Communications Class interface, +/// with the SubClass code of \ref CDC_COMM_SUBCLASS_TELEPHONE_CONTROL_MODEL +typedef struct TU_ATTR_PACKED +{ + uint8_t bLength ; ///< Size of this descriptor in bytes. + uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific + uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above CDC_FUCN_DESC_ + uint8_t bRingerVolSteps ; + uint8_t bNumRingerPatterns ; +}cdc_desc_func_telephone_ringer_t; + +/// \brief Telephone Operational Modes Functional Descriptor +/// \details The Telephone Operational Modes functional descriptor describes the operational modes supported by +/// the Communications Class interface, with the SubClass code of \ref CDC_COMM_SUBCLASS_TELEPHONE_CONTROL_MODEL +typedef struct TU_ATTR_PACKED +{ + uint8_t bLength ; ///< Size of this descriptor in bytes. + uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific + uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above CDC_FUCN_DESC_ + struct { + uint8_t simple_mode : 1; + uint8_t standalone_mode : 1; + uint8_t computer_centric_mode : 1; + uint8_t : 0; + } bmCapabilities; +}cdc_desc_func_telephone_operational_modes_t; + +/// \brief Telephone Call and Line State Reporting Capabilities Descriptor +/// \details The Telephone Call and Line State Reporting Capabilities functional descriptor describes the abilities of a +/// telephone device to report optional call and line states. +typedef struct TU_ATTR_PACKED +{ + uint8_t bLength ; ///< Size of this descriptor in bytes. + uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific + uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above CDC_FUCN_DESC_ + struct { + uint32_t interrupted_dialtone : 1; ///< 0 : Reports only dialtone (does not differentiate between normal and interrupted dialtone). 1 : Reports interrupted dialtone in addition to normal dialtone + uint32_t ringback_busy_fastbusy : 1; ///< 0 : Reports only dialing state. 1 : Reports ringback, busy, and fast busy states. + uint32_t caller_id : 1; ///< 0 : Does not report caller ID. 1 : Reports caller ID information. + uint32_t incoming_distinctive : 1; ///< 0 : Reports only incoming ringing. 1 : Reports incoming distinctive ringing patterns. + uint32_t dual_tone_multi_freq : 1; ///< 0 : Cannot report dual tone multi-frequency (DTMF) digits input remotely over the telephone line. 1 : Can report DTMF digits input remotely over the telephone line. + uint32_t line_state_change : 1; ///< 0 : Does not support line state change notification. 1 : Does support line state change notification + uint32_t : 0; + } bmCapabilities; +}cdc_desc_func_telephone_call_state_reporting_capabilities_t; + +static inline uint8_t cdc_functional_desc_typeof(uint8_t const * p_desc) +{ + return p_desc[2]; +} + +//--------------------------------------------------------------------+ +// Requests +//--------------------------------------------------------------------+ +typedef struct TU_ATTR_PACKED +{ + uint32_t bit_rate; + uint8_t stop_bits; ///< 0: 1 stop bit - 1: 1.5 stop bits - 2: 2 stop bits + uint8_t parity; ///< 0: None - 1: Odd - 2: Even - 3: Mark - 4: Space + uint8_t data_bits; ///< can be 5, 6, 7, 8 or 16 +} cdc_line_coding_t; + +TU_VERIFY_STATIC(sizeof(cdc_line_coding_t) == 7, "size is not correct"); + +typedef struct TU_ATTR_PACKED +{ + uint16_t dte_is_present : 1; ///< Indicates to DCE if DTE is presentor not. This signal corresponds to V.24 signal 108/2 and RS-232 signal DTR. + uint16_t half_duplex_carrier_control : 1; + uint16_t : 14; +} cdc_line_control_state_t; + +TU_VERIFY_STATIC(sizeof(cdc_line_control_state_t) == 2, "size is not correct"); + +/** @} */ + +#ifdef __cplusplus + } +#endif + +#endif + +/** @} */ diff --git a/src/class/cdc/cdc_device.c b/src/class/cdc/cdc_device.c index 3ff72b00..c0de0cad 100644 --- a/src/class/cdc/cdc_device.c +++ b/src/class/cdc/cdc_device.c @@ -1,415 +1,415 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2019 Ha Thach (tinyusb.org) - * - * 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. - * - * This file is part of the TinyUSB stack. - */ - -#include "tusb_option.h" - -#if (TUSB_OPT_DEVICE_ENABLED && CFG_TUD_CDC) - -#include "cdc_device.h" -#include "device/usbd_pvt.h" - -//--------------------------------------------------------------------+ -// MACRO CONSTANT TYPEDEF -//--------------------------------------------------------------------+ -typedef struct -{ - uint8_t itf_num; - uint8_t ep_notif; - uint8_t ep_in; - uint8_t ep_out; - - // Bit 0: DTR (Data Terminal Ready), Bit 1: RTS (Request to Send) - uint8_t line_state; - - /*------------- From this point, data is not cleared by bus reset -------------*/ - char wanted_char; - cdc_line_coding_t line_coding; - - // FIFO - tu_fifo_t rx_ff; - tu_fifo_t tx_ff; - - uint8_t rx_ff_buf[CFG_TUD_CDC_RX_BUFSIZE]; - uint8_t tx_ff_buf[CFG_TUD_CDC_TX_BUFSIZE]; - -#if CFG_FIFO_MUTEX - osal_mutex_def_t rx_ff_mutex; - osal_mutex_def_t tx_ff_mutex; -#endif - - // Endpoint Transfer buffer - CFG_TUSB_MEM_ALIGN uint8_t epout_buf[CFG_TUD_CDC_EPSIZE]; - CFG_TUSB_MEM_ALIGN uint8_t epin_buf[CFG_TUD_CDC_EPSIZE]; - -}cdcd_interface_t; - -#define ITF_MEM_RESET_SIZE offsetof(cdcd_interface_t, wanted_char) - -//--------------------------------------------------------------------+ -// INTERNAL OBJECT & FUNCTION DECLARATION -//--------------------------------------------------------------------+ -CFG_TUSB_MEM_SECTION static cdcd_interface_t _cdcd_itf[CFG_TUD_CDC]; - -static void _prep_out_transaction (uint8_t itf) -{ - cdcd_interface_t* p_cdc = &_cdcd_itf[itf]; - - // skip if previous transfer not complete - if ( usbd_edpt_busy(TUD_OPT_RHPORT, p_cdc->ep_out) ) return; - - // Prepare for incoming data but only allow what we can store in the ring buffer. - uint16_t max_read = tu_fifo_remaining(&p_cdc->rx_ff); - if ( max_read >= CFG_TUD_CDC_EPSIZE ) - { - usbd_edpt_xfer(TUD_OPT_RHPORT, p_cdc->ep_out, p_cdc->epout_buf, CFG_TUD_CDC_EPSIZE); - } -} - -//--------------------------------------------------------------------+ -// APPLICATION API -//--------------------------------------------------------------------+ -bool tud_cdc_n_connected(uint8_t itf) -{ - // DTR (bit 0) active is considered as connected - return tud_ready() && tu_bit_test(_cdcd_itf[itf].line_state, 0); -} - -uint8_t tud_cdc_n_get_line_state (uint8_t itf) -{ - return _cdcd_itf[itf].line_state; -} - -void tud_cdc_n_get_line_coding (uint8_t itf, cdc_line_coding_t* coding) -{ - (*coding) = _cdcd_itf[itf].line_coding; -} - -void tud_cdc_n_set_wanted_char (uint8_t itf, char wanted) -{ - _cdcd_itf[itf].wanted_char = wanted; -} - - -//--------------------------------------------------------------------+ -// READ API -//--------------------------------------------------------------------+ -uint32_t tud_cdc_n_available(uint8_t itf) -{ - return tu_fifo_count(&_cdcd_itf[itf].rx_ff); -} - -uint32_t tud_cdc_n_read(uint8_t itf, void* buffer, uint32_t bufsize) -{ - uint32_t num_read = tu_fifo_read_n(&_cdcd_itf[itf].rx_ff, buffer, bufsize); - _prep_out_transaction(itf); - return num_read; -} - -bool tud_cdc_n_peek(uint8_t itf, int pos, uint8_t* chr) -{ - return tu_fifo_peek_at(&_cdcd_itf[itf].rx_ff, pos, chr); -} - -void tud_cdc_n_read_flush (uint8_t itf) -{ - tu_fifo_clear(&_cdcd_itf[itf].rx_ff); - _prep_out_transaction(itf); -} - -//--------------------------------------------------------------------+ -// WRITE API -//--------------------------------------------------------------------+ -uint32_t tud_cdc_n_write(uint8_t itf, void const* buffer, uint32_t bufsize) -{ - uint16_t ret = tu_fifo_write_n(&_cdcd_itf[itf].tx_ff, buffer, bufsize); - -#if 0 // TODO issue with circuitpython's REPL - // flush if queue more than endpoint size - if ( tu_fifo_count(&_cdcd_itf[itf].tx_ff) >= CFG_TUD_CDC_EPSIZE ) - { - tud_cdc_n_write_flush(itf); - } -#endif - - return ret; -} - -bool tud_cdc_n_write_flush (uint8_t itf) -{ - cdcd_interface_t* p_cdc = &_cdcd_itf[itf]; - TU_VERIFY( !usbd_edpt_busy(TUD_OPT_RHPORT, p_cdc->ep_in) ); // skip if previous transfer not complete - - uint16_t count = tu_fifo_read_n(&_cdcd_itf[itf].tx_ff, p_cdc->epin_buf, CFG_TUD_CDC_EPSIZE); - if ( count ) - { - TU_VERIFY( tud_cdc_n_connected(itf) ); // fifo is empty if not connected - TU_ASSERT( usbd_edpt_xfer(TUD_OPT_RHPORT, p_cdc->ep_in, p_cdc->epin_buf, count) ); - } - - return true; -} - -uint32_t tud_cdc_n_write_available (uint8_t itf) -{ - return tu_fifo_remaining(&_cdcd_itf[itf].tx_ff); -} - - -//--------------------------------------------------------------------+ -// USBD Driver API -//--------------------------------------------------------------------+ -void cdcd_init(void) -{ - tu_memclr(_cdcd_itf, sizeof(_cdcd_itf)); - - for(uint8_t i=0; iwanted_char = -1; - - // default line coding is : stop bit = 1, parity = none, data bits = 8 - p_cdc->line_coding.bit_rate = 115200; - p_cdc->line_coding.stop_bits = 0; - p_cdc->line_coding.parity = 0; - p_cdc->line_coding.data_bits = 8; - - // config fifo - tu_fifo_config(&p_cdc->rx_ff, p_cdc->rx_ff_buf, CFG_TUD_CDC_RX_BUFSIZE, 1, false); - tu_fifo_config(&p_cdc->tx_ff, p_cdc->tx_ff_buf, CFG_TUD_CDC_TX_BUFSIZE, 1, false); - -#if CFG_FIFO_MUTEX - tu_fifo_config_mutex(&p_cdc->rx_ff, osal_mutex_create(&p_cdc->rx_ff_mutex)); - tu_fifo_config_mutex(&p_cdc->tx_ff, osal_mutex_create(&p_cdc->tx_ff_mutex)); -#endif - } -} - -void cdcd_reset(uint8_t rhport) -{ - (void) rhport; - - for(uint8_t i=0; ibInterfaceSubClass); - - // Only support AT commands, no protocol and vendor specific commands. - TU_ASSERT(tu_within(CDC_COMM_PROTOCOL_NONE, itf_desc->bInterfaceProtocol, CDC_COMM_PROTOCOL_ATCOMMAND_CDMA) || - itf_desc->bInterfaceProtocol == 0xff); - - // Find available interface - cdcd_interface_t * p_cdc = NULL; - uint8_t cdc_id; - for(cdc_id=0; cdc_iditf_num = itf_desc->bInterfaceNumber; - - uint8_t const * p_desc = tu_desc_next( itf_desc ); - (*p_length) = sizeof(tusb_desc_interface_t); - - // Communication Functional Descriptors - while ( TUSB_DESC_CS_INTERFACE == tu_desc_type(p_desc) ) - { - (*p_length) += tu_desc_len(p_desc); - p_desc = tu_desc_next(p_desc); - } - - if ( TUSB_DESC_ENDPOINT == tu_desc_type(p_desc) ) - { - // notification endpoint if any - TU_ASSERT( dcd_edpt_open(rhport, (tusb_desc_endpoint_t const *) p_desc) ); - - p_cdc->ep_notif = ((tusb_desc_endpoint_t const *) p_desc)->bEndpointAddress; - - (*p_length) += p_desc[DESC_OFFSET_LEN]; - p_desc = tu_desc_next(p_desc); - } - - //------------- Data Interface (if any) -------------// - if ( (TUSB_DESC_INTERFACE == p_desc[DESC_OFFSET_TYPE]) && - (TUSB_CLASS_CDC_DATA == ((tusb_desc_interface_t const *) p_desc)->bInterfaceClass) ) - { - // next to endpoint descriptor - p_desc = tu_desc_next(p_desc); - - // Open endpoint pair - TU_ASSERT( usbd_open_edpt_pair(rhport, p_desc, 2, TUSB_XFER_BULK, &p_cdc->ep_out, &p_cdc->ep_in) ); - - (*p_length) += sizeof(tusb_desc_interface_t) + 2*sizeof(tusb_desc_endpoint_t); - } - - // Prepare for incoming data - _prep_out_transaction(cdc_id); - - return true; -} - -// Invoked when class request DATA stage is finished. -// return false to stall control endpoint (e.g Host send non-sense DATA) -bool cdcd_control_complete(uint8_t rhport, tusb_control_request_t const * request) -{ - (void) rhport; - - //------------- Class Specific Request -------------// - TU_VERIFY (request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS); - - uint8_t itf = 0; - cdcd_interface_t* p_cdc = _cdcd_itf; - - // Identify which interface to use - for ( ; ; itf++, p_cdc++) - { - if (itf >= TU_ARRAY_SIZE(_cdcd_itf)) return false; - - if ( p_cdc->itf_num == request->wIndex ) break; - } - - // Invoke callback - if ( CDC_REQUEST_SET_LINE_CODING == request->bRequest ) - { - if ( tud_cdc_line_coding_cb ) tud_cdc_line_coding_cb(itf, &p_cdc->line_coding); - } - - return true; -} - -// Handle class control request -// return false to stall control endpoint (e.g unsupported request) -bool cdcd_control_request(uint8_t rhport, tusb_control_request_t const * request) -{ - // Handle class request only - TU_VERIFY(request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS); - - uint8_t itf = 0; - cdcd_interface_t* p_cdc = _cdcd_itf; - - // Identify which interface to use - for ( ; ; itf++, p_cdc++) - { - if (itf >= TU_ARRAY_SIZE(_cdcd_itf)) return false; - - if ( p_cdc->itf_num == request->wIndex ) break; - } - - switch ( request->bRequest ) - { - case CDC_REQUEST_SET_LINE_CODING: - tud_control_xfer(rhport, request, &p_cdc->line_coding, sizeof(cdc_line_coding_t)); - break; - - case CDC_REQUEST_GET_LINE_CODING: - tud_control_xfer(rhport, request, &p_cdc->line_coding, sizeof(cdc_line_coding_t)); - break; - - case CDC_REQUEST_SET_CONTROL_LINE_STATE: - // CDC PSTN v1.2 section 6.3.12 - // Bit 0: Indicates if DTE is present or not. - // This signal corresponds to V.24 signal 108/2 and RS-232 signal DTR (Data Terminal Ready) - // Bit 1: Carrier control for half-duplex modems. - // This signal corresponds to V.24 signal 105 and RS-232 signal RTS (Request to Send) - p_cdc->line_state = (uint8_t) request->wValue; - - tud_control_status(rhport, request); - - // Invoke callback - if ( tud_cdc_line_state_cb) tud_cdc_line_state_cb(itf, tu_bit_test(request->wValue, 0), tu_bit_test(request->wValue, 1)); - break; - - default: return false; // stall unsupported request - } - - return true; -} - -bool cdcd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes) -{ - (void) rhport; - (void) result; - - uint8_t itf = 0; - cdcd_interface_t* p_cdc = _cdcd_itf; - - // Identify which interface to use - for ( ; ; itf++, p_cdc++) - { - if (itf >= TU_ARRAY_SIZE(_cdcd_itf)) return false; - - if ( ( ep_addr == p_cdc->ep_out ) || ( ep_addr == p_cdc->ep_in ) ) break; - } - - // Received new data - if ( ep_addr == p_cdc->ep_out ) - { - for(uint32_t i=0; irx_ff, &p_cdc->epout_buf[i]); - - // Check for wanted char and invoke callback if needed - if ( tud_cdc_rx_wanted_cb && ( ((signed char) p_cdc->wanted_char) != -1 ) && ( p_cdc->wanted_char == p_cdc->epout_buf[i] ) ) - { - tud_cdc_rx_wanted_cb(itf, p_cdc->wanted_char); - } - } - - // invoke receive callback (if there is still data) - if (tud_cdc_rx_cb && tu_fifo_count(&p_cdc->rx_ff) ) tud_cdc_rx_cb(itf); - - // prepare for OUT transaction - _prep_out_transaction(itf); - } - - // Data sent to host, we could continue to fetch data tx fifo to send. - // But it will cause incorrect baudrate set in line coding. - // Though maybe the baudrate is not really important !!! -// if ( ep_addr == p_cdc->ep_in ) -// { -// -// } - - // nothing to do with notif endpoint for now - - return true; -} - -#endif +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#include "tusb_option.h" + +#if (TUSB_OPT_DEVICE_ENABLED && CFG_TUD_CDC) + +#include "cdc_device.h" +#include "device/usbd_pvt.h" + +//--------------------------------------------------------------------+ +// MACRO CONSTANT TYPEDEF +//--------------------------------------------------------------------+ +typedef struct +{ + uint8_t itf_num; + uint8_t ep_notif; + uint8_t ep_in; + uint8_t ep_out; + + // Bit 0: DTR (Data Terminal Ready), Bit 1: RTS (Request to Send) + uint8_t line_state; + + /*------------- From this point, data is not cleared by bus reset -------------*/ + char wanted_char; + cdc_line_coding_t line_coding; + + // FIFO + tu_fifo_t rx_ff; + tu_fifo_t tx_ff; + + uint8_t rx_ff_buf[CFG_TUD_CDC_RX_BUFSIZE]; + uint8_t tx_ff_buf[CFG_TUD_CDC_TX_BUFSIZE]; + +#if CFG_FIFO_MUTEX + osal_mutex_def_t rx_ff_mutex; + osal_mutex_def_t tx_ff_mutex; +#endif + + // Endpoint Transfer buffer + CFG_TUSB_MEM_ALIGN uint8_t epout_buf[CFG_TUD_CDC_EPSIZE]; + CFG_TUSB_MEM_ALIGN uint8_t epin_buf[CFG_TUD_CDC_EPSIZE]; + +}cdcd_interface_t; + +#define ITF_MEM_RESET_SIZE offsetof(cdcd_interface_t, wanted_char) + +//--------------------------------------------------------------------+ +// INTERNAL OBJECT & FUNCTION DECLARATION +//--------------------------------------------------------------------+ +CFG_TUSB_MEM_SECTION static cdcd_interface_t _cdcd_itf[CFG_TUD_CDC]; + +static void _prep_out_transaction (uint8_t itf) +{ + cdcd_interface_t* p_cdc = &_cdcd_itf[itf]; + + // skip if previous transfer not complete + if ( usbd_edpt_busy(TUD_OPT_RHPORT, p_cdc->ep_out) ) return; + + // Prepare for incoming data but only allow what we can store in the ring buffer. + uint16_t max_read = tu_fifo_remaining(&p_cdc->rx_ff); + if ( max_read >= CFG_TUD_CDC_EPSIZE ) + { + usbd_edpt_xfer(TUD_OPT_RHPORT, p_cdc->ep_out, p_cdc->epout_buf, CFG_TUD_CDC_EPSIZE); + } +} + +//--------------------------------------------------------------------+ +// APPLICATION API +//--------------------------------------------------------------------+ +bool tud_cdc_n_connected(uint8_t itf) +{ + // DTR (bit 0) active is considered as connected + return tud_ready() && tu_bit_test(_cdcd_itf[itf].line_state, 0); +} + +uint8_t tud_cdc_n_get_line_state (uint8_t itf) +{ + return _cdcd_itf[itf].line_state; +} + +void tud_cdc_n_get_line_coding (uint8_t itf, cdc_line_coding_t* coding) +{ + (*coding) = _cdcd_itf[itf].line_coding; +} + +void tud_cdc_n_set_wanted_char (uint8_t itf, char wanted) +{ + _cdcd_itf[itf].wanted_char = wanted; +} + + +//--------------------------------------------------------------------+ +// READ API +//--------------------------------------------------------------------+ +uint32_t tud_cdc_n_available(uint8_t itf) +{ + return tu_fifo_count(&_cdcd_itf[itf].rx_ff); +} + +uint32_t tud_cdc_n_read(uint8_t itf, void* buffer, uint32_t bufsize) +{ + uint32_t num_read = tu_fifo_read_n(&_cdcd_itf[itf].rx_ff, buffer, bufsize); + _prep_out_transaction(itf); + return num_read; +} + +bool tud_cdc_n_peek(uint8_t itf, int pos, uint8_t* chr) +{ + return tu_fifo_peek_at(&_cdcd_itf[itf].rx_ff, pos, chr); +} + +void tud_cdc_n_read_flush (uint8_t itf) +{ + tu_fifo_clear(&_cdcd_itf[itf].rx_ff); + _prep_out_transaction(itf); +} + +//--------------------------------------------------------------------+ +// WRITE API +//--------------------------------------------------------------------+ +uint32_t tud_cdc_n_write(uint8_t itf, void const* buffer, uint32_t bufsize) +{ + uint16_t ret = tu_fifo_write_n(&_cdcd_itf[itf].tx_ff, buffer, bufsize); + +#if 0 // TODO issue with circuitpython's REPL + // flush if queue more than endpoint size + if ( tu_fifo_count(&_cdcd_itf[itf].tx_ff) >= CFG_TUD_CDC_EPSIZE ) + { + tud_cdc_n_write_flush(itf); + } +#endif + + return ret; +} + +bool tud_cdc_n_write_flush (uint8_t itf) +{ + cdcd_interface_t* p_cdc = &_cdcd_itf[itf]; + TU_VERIFY( !usbd_edpt_busy(TUD_OPT_RHPORT, p_cdc->ep_in) ); // skip if previous transfer not complete + + uint16_t count = tu_fifo_read_n(&_cdcd_itf[itf].tx_ff, p_cdc->epin_buf, CFG_TUD_CDC_EPSIZE); + if ( count ) + { + TU_VERIFY( tud_cdc_n_connected(itf) ); // fifo is empty if not connected + TU_ASSERT( usbd_edpt_xfer(TUD_OPT_RHPORT, p_cdc->ep_in, p_cdc->epin_buf, count) ); + } + + return true; +} + +uint32_t tud_cdc_n_write_available (uint8_t itf) +{ + return tu_fifo_remaining(&_cdcd_itf[itf].tx_ff); +} + + +//--------------------------------------------------------------------+ +// USBD Driver API +//--------------------------------------------------------------------+ +void cdcd_init(void) +{ + tu_memclr(_cdcd_itf, sizeof(_cdcd_itf)); + + for(uint8_t i=0; iwanted_char = -1; + + // default line coding is : stop bit = 1, parity = none, data bits = 8 + p_cdc->line_coding.bit_rate = 115200; + p_cdc->line_coding.stop_bits = 0; + p_cdc->line_coding.parity = 0; + p_cdc->line_coding.data_bits = 8; + + // config fifo + tu_fifo_config(&p_cdc->rx_ff, p_cdc->rx_ff_buf, CFG_TUD_CDC_RX_BUFSIZE, 1, false); + tu_fifo_config(&p_cdc->tx_ff, p_cdc->tx_ff_buf, CFG_TUD_CDC_TX_BUFSIZE, 1, false); + +#if CFG_FIFO_MUTEX + tu_fifo_config_mutex(&p_cdc->rx_ff, osal_mutex_create(&p_cdc->rx_ff_mutex)); + tu_fifo_config_mutex(&p_cdc->tx_ff, osal_mutex_create(&p_cdc->tx_ff_mutex)); +#endif + } +} + +void cdcd_reset(uint8_t rhport) +{ + (void) rhport; + + for(uint8_t i=0; ibInterfaceSubClass); + + // Only support AT commands, no protocol and vendor specific commands. + TU_ASSERT(tu_within(CDC_COMM_PROTOCOL_NONE, itf_desc->bInterfaceProtocol, CDC_COMM_PROTOCOL_ATCOMMAND_CDMA) || + itf_desc->bInterfaceProtocol == 0xff); + + // Find available interface + cdcd_interface_t * p_cdc = NULL; + uint8_t cdc_id; + for(cdc_id=0; cdc_iditf_num = itf_desc->bInterfaceNumber; + + uint8_t const * p_desc = tu_desc_next( itf_desc ); + (*p_length) = sizeof(tusb_desc_interface_t); + + // Communication Functional Descriptors + while ( TUSB_DESC_CS_INTERFACE == tu_desc_type(p_desc) ) + { + (*p_length) += tu_desc_len(p_desc); + p_desc = tu_desc_next(p_desc); + } + + if ( TUSB_DESC_ENDPOINT == tu_desc_type(p_desc) ) + { + // notification endpoint if any + TU_ASSERT( dcd_edpt_open(rhport, (tusb_desc_endpoint_t const *) p_desc) ); + + p_cdc->ep_notif = ((tusb_desc_endpoint_t const *) p_desc)->bEndpointAddress; + + (*p_length) += p_desc[DESC_OFFSET_LEN]; + p_desc = tu_desc_next(p_desc); + } + + //------------- Data Interface (if any) -------------// + if ( (TUSB_DESC_INTERFACE == p_desc[DESC_OFFSET_TYPE]) && + (TUSB_CLASS_CDC_DATA == ((tusb_desc_interface_t const *) p_desc)->bInterfaceClass) ) + { + // next to endpoint descriptor + p_desc = tu_desc_next(p_desc); + + // Open endpoint pair + TU_ASSERT( usbd_open_edpt_pair(rhport, p_desc, 2, TUSB_XFER_BULK, &p_cdc->ep_out, &p_cdc->ep_in) ); + + (*p_length) += sizeof(tusb_desc_interface_t) + 2*sizeof(tusb_desc_endpoint_t); + } + + // Prepare for incoming data + _prep_out_transaction(cdc_id); + + return true; +} + +// Invoked when class request DATA stage is finished. +// return false to stall control endpoint (e.g Host send non-sense DATA) +bool cdcd_control_complete(uint8_t rhport, tusb_control_request_t const * request) +{ + (void) rhport; + + //------------- Class Specific Request -------------// + TU_VERIFY (request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS); + + uint8_t itf = 0; + cdcd_interface_t* p_cdc = _cdcd_itf; + + // Identify which interface to use + for ( ; ; itf++, p_cdc++) + { + if (itf >= TU_ARRAY_SIZE(_cdcd_itf)) return false; + + if ( p_cdc->itf_num == request->wIndex ) break; + } + + // Invoke callback + if ( CDC_REQUEST_SET_LINE_CODING == request->bRequest ) + { + if ( tud_cdc_line_coding_cb ) tud_cdc_line_coding_cb(itf, &p_cdc->line_coding); + } + + return true; +} + +// Handle class control request +// return false to stall control endpoint (e.g unsupported request) +bool cdcd_control_request(uint8_t rhport, tusb_control_request_t const * request) +{ + // Handle class request only + TU_VERIFY(request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS); + + uint8_t itf = 0; + cdcd_interface_t* p_cdc = _cdcd_itf; + + // Identify which interface to use + for ( ; ; itf++, p_cdc++) + { + if (itf >= TU_ARRAY_SIZE(_cdcd_itf)) return false; + + if ( p_cdc->itf_num == request->wIndex ) break; + } + + switch ( request->bRequest ) + { + case CDC_REQUEST_SET_LINE_CODING: + tud_control_xfer(rhport, request, &p_cdc->line_coding, sizeof(cdc_line_coding_t)); + break; + + case CDC_REQUEST_GET_LINE_CODING: + tud_control_xfer(rhport, request, &p_cdc->line_coding, sizeof(cdc_line_coding_t)); + break; + + case CDC_REQUEST_SET_CONTROL_LINE_STATE: + // CDC PSTN v1.2 section 6.3.12 + // Bit 0: Indicates if DTE is present or not. + // This signal corresponds to V.24 signal 108/2 and RS-232 signal DTR (Data Terminal Ready) + // Bit 1: Carrier control for half-duplex modems. + // This signal corresponds to V.24 signal 105 and RS-232 signal RTS (Request to Send) + p_cdc->line_state = (uint8_t) request->wValue; + + tud_control_status(rhport, request); + + // Invoke callback + if ( tud_cdc_line_state_cb) tud_cdc_line_state_cb(itf, tu_bit_test(request->wValue, 0), tu_bit_test(request->wValue, 1)); + break; + + default: return false; // stall unsupported request + } + + return true; +} + +bool cdcd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes) +{ + (void) rhport; + (void) result; + + uint8_t itf = 0; + cdcd_interface_t* p_cdc = _cdcd_itf; + + // Identify which interface to use + for ( ; ; itf++, p_cdc++) + { + if (itf >= TU_ARRAY_SIZE(_cdcd_itf)) return false; + + if ( ( ep_addr == p_cdc->ep_out ) || ( ep_addr == p_cdc->ep_in ) ) break; + } + + // Received new data + if ( ep_addr == p_cdc->ep_out ) + { + for(uint32_t i=0; irx_ff, &p_cdc->epout_buf[i]); + + // Check for wanted char and invoke callback if needed + if ( tud_cdc_rx_wanted_cb && ( ((signed char) p_cdc->wanted_char) != -1 ) && ( p_cdc->wanted_char == p_cdc->epout_buf[i] ) ) + { + tud_cdc_rx_wanted_cb(itf, p_cdc->wanted_char); + } + } + + // invoke receive callback (if there is still data) + if (tud_cdc_rx_cb && tu_fifo_count(&p_cdc->rx_ff) ) tud_cdc_rx_cb(itf); + + // prepare for OUT transaction + _prep_out_transaction(itf); + } + + // Data sent to host, we could continue to fetch data tx fifo to send. + // But it will cause incorrect baudrate set in line coding. + // Though maybe the baudrate is not really important !!! +// if ( ep_addr == p_cdc->ep_in ) +// { +// +// } + + // nothing to do with notif endpoint for now + + return true; +} + +#endif diff --git a/src/class/cdc/cdc_device.h b/src/class/cdc/cdc_device.h index b8b3c864..969ec7f9 100644 --- a/src/class/cdc/cdc_device.h +++ b/src/class/cdc/cdc_device.h @@ -1,213 +1,213 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2019 Ha Thach (tinyusb.org) - * - * 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. - * - * This file is part of the TinyUSB stack. - */ - -#ifndef _TUSB_CDC_DEVICE_H_ -#define _TUSB_CDC_DEVICE_H_ - -#include "common/tusb_common.h" -#include "device/usbd.h" -#include "cdc.h" - -//--------------------------------------------------------------------+ -// Class Driver Configuration -//--------------------------------------------------------------------+ -#ifndef CFG_TUD_CDC_EPSIZE -#define CFG_TUD_CDC_EPSIZE 64 -#endif - -#ifdef __cplusplus - extern "C" { -#endif - -/** \addtogroup CDC_Serial Serial - * @{ - * \defgroup CDC_Serial_Device Device - * @{ */ - -//--------------------------------------------------------------------+ -// Application API (Multiple Interfaces) -// CFG_TUD_CDC > 1 -//--------------------------------------------------------------------+ -bool tud_cdc_n_connected (uint8_t itf); -uint8_t tud_cdc_n_get_line_state (uint8_t itf); -void tud_cdc_n_get_line_coding (uint8_t itf, cdc_line_coding_t* coding); -void tud_cdc_n_set_wanted_char (uint8_t itf, char wanted); - -uint32_t tud_cdc_n_available (uint8_t itf); -uint32_t tud_cdc_n_read (uint8_t itf, void* buffer, uint32_t bufsize); -void tud_cdc_n_read_flush (uint8_t itf); -bool tud_cdc_n_peek (uint8_t itf, int pos, uint8_t* u8); -static inline int32_t tud_cdc_n_read_char (uint8_t itf); - -uint32_t tud_cdc_n_write (uint8_t itf, void const* buffer, uint32_t bufsize); -bool tud_cdc_n_write_flush (uint8_t itf); -uint32_t tud_cdc_n_write_available (uint8_t itf); -static inline uint32_t tud_cdc_n_write_char (uint8_t itf, char ch); -static inline uint32_t tud_cdc_n_write_str (uint8_t itf, char const* str); - -//--------------------------------------------------------------------+ -// Application API (Interface0) -//--------------------------------------------------------------------+ -static inline bool tud_cdc_connected (void); -static inline uint8_t tud_cdc_get_line_state (void); -static inline void tud_cdc_get_line_coding (cdc_line_coding_t* coding); -static inline void tud_cdc_set_wanted_char (char wanted); - -static inline uint32_t tud_cdc_available (void); -static inline int32_t tud_cdc_read_char (void); -static inline uint32_t tud_cdc_read (void* buffer, uint32_t bufsize); -static inline void tud_cdc_read_flush (void); -static inline bool tud_cdc_peek (int pos, uint8_t* u8); - -static inline uint32_t tud_cdc_write_char (char ch); -static inline uint32_t tud_cdc_write (void const* buffer, uint32_t bufsize); -static inline uint32_t tud_cdc_write_str (char const* str); -static inline bool tud_cdc_write_flush (void); -static inline uint32_t tud_cdc_write_available (void); - -//--------------------------------------------------------------------+ -// Application Callback API (weak is optional) -//--------------------------------------------------------------------+ - -// Invoked when received new data -TU_ATTR_WEAK void tud_cdc_rx_cb(uint8_t itf); - -// Invoked when received `wanted_char` -TU_ATTR_WEAK void tud_cdc_rx_wanted_cb(uint8_t itf, char wanted_char); - -// Invoked when line state DTR & RTS are changed via SET_CONTROL_LINE_STATE -TU_ATTR_WEAK void tud_cdc_line_state_cb(uint8_t itf, bool dtr, bool rts); - -// Invoked when line coding is change via SET_LINE_CODING -TU_ATTR_WEAK void tud_cdc_line_coding_cb(uint8_t itf, cdc_line_coding_t const* p_line_coding); - -//--------------------------------------------------------------------+ -// Inline Functions -//--------------------------------------------------------------------+ -static inline int32_t tud_cdc_n_read_char (uint8_t itf) -{ - uint8_t ch; - return tud_cdc_n_read(itf, &ch, 1) ? (int32_t) ch : -1; -} - -static inline uint32_t tud_cdc_n_write_char(uint8_t itf, char ch) -{ - return tud_cdc_n_write(itf, &ch, 1); -} - -static inline uint32_t tud_cdc_n_write_str (uint8_t itf, char const* str) -{ - return tud_cdc_n_write(itf, str, strlen(str)); -} - -static inline bool tud_cdc_connected (void) -{ - return tud_cdc_n_connected(0); -} - -static inline uint8_t tud_cdc_get_line_state (void) -{ - return tud_cdc_n_get_line_state(0); -} - -static inline void tud_cdc_get_line_coding (cdc_line_coding_t* coding) -{ - tud_cdc_n_get_line_coding(0, coding); -} - -static inline void tud_cdc_set_wanted_char (char wanted) -{ - tud_cdc_n_set_wanted_char(0, wanted); -} - -static inline uint32_t tud_cdc_available (void) -{ - return tud_cdc_n_available(0); -} - -static inline int32_t tud_cdc_read_char (void) -{ - return tud_cdc_n_read_char(0); -} - -static inline uint32_t tud_cdc_read (void* buffer, uint32_t bufsize) -{ - return tud_cdc_n_read(0, buffer, bufsize); -} - -static inline void tud_cdc_read_flush (void) -{ - tud_cdc_n_read_flush(0); -} - -static inline bool tud_cdc_peek (int pos, uint8_t* u8) -{ - return tud_cdc_n_peek(0, pos, u8); -} - -static inline uint32_t tud_cdc_write_char (char ch) -{ - return tud_cdc_n_write_char(0, ch); -} - -static inline uint32_t tud_cdc_write (void const* buffer, uint32_t bufsize) -{ - return tud_cdc_n_write(0, buffer, bufsize); -} - -static inline uint32_t tud_cdc_write_str (char const* str) -{ - return tud_cdc_n_write_str(0, str); -} - -static inline bool tud_cdc_write_flush (void) -{ - return tud_cdc_n_write_flush(0); -} - -static inline uint32_t tud_cdc_write_available(void) -{ - return tud_cdc_n_write_available(0); -} - -/** @} */ -/** @} */ - -//--------------------------------------------------------------------+ -// INTERNAL USBD-CLASS DRIVER API -//--------------------------------------------------------------------+ -void cdcd_init (void); -void cdcd_reset (uint8_t rhport); -bool cdcd_open (uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t *p_length); -bool cdcd_control_request (uint8_t rhport, tusb_control_request_t const * request); -bool cdcd_control_complete (uint8_t rhport, tusb_control_request_t const * request); -bool cdcd_xfer_cb (uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes); - -#ifdef __cplusplus - } -#endif - -#endif /* _TUSB_CDC_DEVICE_H_ */ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#ifndef _TUSB_CDC_DEVICE_H_ +#define _TUSB_CDC_DEVICE_H_ + +#include "common/tusb_common.h" +#include "device/usbd.h" +#include "cdc.h" + +//--------------------------------------------------------------------+ +// Class Driver Configuration +//--------------------------------------------------------------------+ +#ifndef CFG_TUD_CDC_EPSIZE +#define CFG_TUD_CDC_EPSIZE 64 +#endif + +#ifdef __cplusplus + extern "C" { +#endif + +/** \addtogroup CDC_Serial Serial + * @{ + * \defgroup CDC_Serial_Device Device + * @{ */ + +//--------------------------------------------------------------------+ +// Application API (Multiple Interfaces) +// CFG_TUD_CDC > 1 +//--------------------------------------------------------------------+ +bool tud_cdc_n_connected (uint8_t itf); +uint8_t tud_cdc_n_get_line_state (uint8_t itf); +void tud_cdc_n_get_line_coding (uint8_t itf, cdc_line_coding_t* coding); +void tud_cdc_n_set_wanted_char (uint8_t itf, char wanted); + +uint32_t tud_cdc_n_available (uint8_t itf); +uint32_t tud_cdc_n_read (uint8_t itf, void* buffer, uint32_t bufsize); +void tud_cdc_n_read_flush (uint8_t itf); +bool tud_cdc_n_peek (uint8_t itf, int pos, uint8_t* u8); +static inline int32_t tud_cdc_n_read_char (uint8_t itf); + +uint32_t tud_cdc_n_write (uint8_t itf, void const* buffer, uint32_t bufsize); +bool tud_cdc_n_write_flush (uint8_t itf); +uint32_t tud_cdc_n_write_available (uint8_t itf); +static inline uint32_t tud_cdc_n_write_char (uint8_t itf, char ch); +static inline uint32_t tud_cdc_n_write_str (uint8_t itf, char const* str); + +//--------------------------------------------------------------------+ +// Application API (Interface0) +//--------------------------------------------------------------------+ +static inline bool tud_cdc_connected (void); +static inline uint8_t tud_cdc_get_line_state (void); +static inline void tud_cdc_get_line_coding (cdc_line_coding_t* coding); +static inline void tud_cdc_set_wanted_char (char wanted); + +static inline uint32_t tud_cdc_available (void); +static inline int32_t tud_cdc_read_char (void); +static inline uint32_t tud_cdc_read (void* buffer, uint32_t bufsize); +static inline void tud_cdc_read_flush (void); +static inline bool tud_cdc_peek (int pos, uint8_t* u8); + +static inline uint32_t tud_cdc_write_char (char ch); +static inline uint32_t tud_cdc_write (void const* buffer, uint32_t bufsize); +static inline uint32_t tud_cdc_write_str (char const* str); +static inline bool tud_cdc_write_flush (void); +static inline uint32_t tud_cdc_write_available (void); + +//--------------------------------------------------------------------+ +// Application Callback API (weak is optional) +//--------------------------------------------------------------------+ + +// Invoked when received new data +TU_ATTR_WEAK void tud_cdc_rx_cb(uint8_t itf); + +// Invoked when received `wanted_char` +TU_ATTR_WEAK void tud_cdc_rx_wanted_cb(uint8_t itf, char wanted_char); + +// Invoked when line state DTR & RTS are changed via SET_CONTROL_LINE_STATE +TU_ATTR_WEAK void tud_cdc_line_state_cb(uint8_t itf, bool dtr, bool rts); + +// Invoked when line coding is change via SET_LINE_CODING +TU_ATTR_WEAK void tud_cdc_line_coding_cb(uint8_t itf, cdc_line_coding_t const* p_line_coding); + +//--------------------------------------------------------------------+ +// Inline Functions +//--------------------------------------------------------------------+ +static inline int32_t tud_cdc_n_read_char (uint8_t itf) +{ + uint8_t ch; + return tud_cdc_n_read(itf, &ch, 1) ? (int32_t) ch : -1; +} + +static inline uint32_t tud_cdc_n_write_char(uint8_t itf, char ch) +{ + return tud_cdc_n_write(itf, &ch, 1); +} + +static inline uint32_t tud_cdc_n_write_str (uint8_t itf, char const* str) +{ + return tud_cdc_n_write(itf, str, strlen(str)); +} + +static inline bool tud_cdc_connected (void) +{ + return tud_cdc_n_connected(0); +} + +static inline uint8_t tud_cdc_get_line_state (void) +{ + return tud_cdc_n_get_line_state(0); +} + +static inline void tud_cdc_get_line_coding (cdc_line_coding_t* coding) +{ + tud_cdc_n_get_line_coding(0, coding); +} + +static inline void tud_cdc_set_wanted_char (char wanted) +{ + tud_cdc_n_set_wanted_char(0, wanted); +} + +static inline uint32_t tud_cdc_available (void) +{ + return tud_cdc_n_available(0); +} + +static inline int32_t tud_cdc_read_char (void) +{ + return tud_cdc_n_read_char(0); +} + +static inline uint32_t tud_cdc_read (void* buffer, uint32_t bufsize) +{ + return tud_cdc_n_read(0, buffer, bufsize); +} + +static inline void tud_cdc_read_flush (void) +{ + tud_cdc_n_read_flush(0); +} + +static inline bool tud_cdc_peek (int pos, uint8_t* u8) +{ + return tud_cdc_n_peek(0, pos, u8); +} + +static inline uint32_t tud_cdc_write_char (char ch) +{ + return tud_cdc_n_write_char(0, ch); +} + +static inline uint32_t tud_cdc_write (void const* buffer, uint32_t bufsize) +{ + return tud_cdc_n_write(0, buffer, bufsize); +} + +static inline uint32_t tud_cdc_write_str (char const* str) +{ + return tud_cdc_n_write_str(0, str); +} + +static inline bool tud_cdc_write_flush (void) +{ + return tud_cdc_n_write_flush(0); +} + +static inline uint32_t tud_cdc_write_available(void) +{ + return tud_cdc_n_write_available(0); +} + +/** @} */ +/** @} */ + +//--------------------------------------------------------------------+ +// INTERNAL USBD-CLASS DRIVER API +//--------------------------------------------------------------------+ +void cdcd_init (void); +void cdcd_reset (uint8_t rhport); +bool cdcd_open (uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t *p_length); +bool cdcd_control_request (uint8_t rhport, tusb_control_request_t const * request); +bool cdcd_control_complete (uint8_t rhport, tusb_control_request_t const * request); +bool cdcd_xfer_cb (uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes); + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_CDC_DEVICE_H_ */ diff --git a/src/class/cdc/cdc_host.c b/src/class/cdc/cdc_host.c index 6a6f508b..595e7fd6 100644 --- a/src/class/cdc/cdc_host.c +++ b/src/class/cdc/cdc_host.c @@ -1,225 +1,225 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2019 Ha Thach (tinyusb.org) - * - * 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. - * - * This file is part of the TinyUSB stack. - */ - -#include "tusb_option.h" - -#if (TUSB_OPT_HOST_ENABLED && CFG_TUH_CDC) - -#include "common/tusb_common.h" -#include "cdc_host.h" - -//--------------------------------------------------------------------+ -// MACRO CONSTANT TYPEDEF -//--------------------------------------------------------------------+ -typedef struct { - uint8_t itf_num; - uint8_t itf_protocol; - - uint8_t ep_notif; - uint8_t ep_in; - uint8_t ep_out; - - cdc_acm_capability_t acm_capability; - -} cdch_data_t; - -//--------------------------------------------------------------------+ -// INTERNAL OBJECT & FUNCTION DECLARATION -//--------------------------------------------------------------------+ -static cdch_data_t cdch_data[CFG_TUSB_HOST_DEVICE_MAX]; - -bool tuh_cdc_mounted(uint8_t dev_addr) -{ - cdch_data_t* cdc = &cdch_data[dev_addr-1]; - return cdc->ep_in && cdc->ep_out; -} - -bool tuh_cdc_is_busy(uint8_t dev_addr, cdc_pipeid_t pipeid) -{ - if ( !tuh_cdc_mounted(dev_addr) ) return false; - - cdch_data_t const * p_cdc = &cdch_data[dev_addr-1]; - - switch (pipeid) - { - case CDC_PIPE_NOTIFICATION: - return hcd_edpt_busy(dev_addr, p_cdc->ep_notif ); - - case CDC_PIPE_DATA_IN: - return hcd_edpt_busy(dev_addr, p_cdc->ep_in ); - - case CDC_PIPE_DATA_OUT: - return hcd_edpt_busy(dev_addr, p_cdc->ep_out ); - - default: - return false; - } -} - -//--------------------------------------------------------------------+ -// APPLICATION API (parameter validation needed) -//--------------------------------------------------------------------+ -bool tuh_cdc_serial_is_mounted(uint8_t dev_addr) -{ - // TODO consider all AT Command as serial candidate - return tuh_cdc_mounted(dev_addr) && - (CDC_COMM_PROTOCOL_ATCOMMAND <= cdch_data[dev_addr-1].itf_protocol) && - (cdch_data[dev_addr-1].itf_protocol <= CDC_COMM_PROTOCOL_ATCOMMAND_CDMA); -} - -bool tuh_cdc_send(uint8_t dev_addr, void const * p_data, uint32_t length, bool is_notify) -{ - TU_VERIFY( tuh_cdc_mounted(dev_addr) ); - TU_VERIFY( p_data != NULL && length, TUSB_ERROR_INVALID_PARA); - - uint8_t const ep_out = cdch_data[dev_addr-1].ep_out; - if ( hcd_edpt_busy(dev_addr, ep_out) ) return false; - - return hcd_pipe_xfer(dev_addr, ep_out, (void *) p_data, length, is_notify); -} - -bool tuh_cdc_receive(uint8_t dev_addr, void * p_buffer, uint32_t length, bool is_notify) -{ - TU_VERIFY( tuh_cdc_mounted(dev_addr) ); - TU_VERIFY( p_buffer != NULL && length, TUSB_ERROR_INVALID_PARA); - - uint8_t const ep_in = cdch_data[dev_addr-1].ep_in; - if ( hcd_edpt_busy(dev_addr, ep_in) ) return false; - - return hcd_pipe_xfer(dev_addr, ep_in, p_buffer, length, is_notify); -} - -//--------------------------------------------------------------------+ -// USBH-CLASS DRIVER API -//--------------------------------------------------------------------+ -void cdch_init(void) -{ - tu_memclr(cdch_data, sizeof(cdch_data_t)*CFG_TUSB_HOST_DEVICE_MAX); -} - -bool cdch_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const *itf_desc, uint16_t *p_length) -{ - // Only support ACM - TU_VERIFY( CDC_COMM_SUBCLASS_ABSTRACT_CONTROL_MODEL == itf_desc->bInterfaceSubClass); - - // Only support AT commands, no protocol and vendor specific commands. - TU_VERIFY(tu_within(CDC_COMM_PROTOCOL_NONE, itf_desc->bInterfaceProtocol, CDC_COMM_PROTOCOL_ATCOMMAND_CDMA) || - 0xff == itf_desc->bInterfaceProtocol); - - uint8_t const * p_desc; - cdch_data_t * p_cdc; - - p_desc = tu_desc_next(itf_desc); - p_cdc = &cdch_data[dev_addr-1]; - - p_cdc->itf_num = itf_desc->bInterfaceNumber; - p_cdc->itf_protocol = itf_desc->bInterfaceProtocol; // TODO 0xff is consider as rndis candidate, other is virtual Com - - //------------- Communication Interface -------------// - (*p_length) = sizeof(tusb_desc_interface_t); - - // Communication Functional Descriptors - while( TUSB_DESC_CS_INTERFACE == p_desc[DESC_OFFSET_TYPE] ) - { - if ( CDC_FUNC_DESC_ABSTRACT_CONTROL_MANAGEMENT == cdc_functional_desc_typeof(p_desc) ) - { - // save ACM bmCapabilities - p_cdc->acm_capability = ((cdc_desc_func_acm_t const *) p_desc)->bmCapabilities; - } - - (*p_length) += p_desc[DESC_OFFSET_LEN]; - p_desc = tu_desc_next(p_desc); - } - - if ( TUSB_DESC_ENDPOINT == p_desc[DESC_OFFSET_TYPE]) - { - // notification endpoint - tusb_desc_endpoint_t const * ep_desc = (tusb_desc_endpoint_t const *) p_desc; - - TU_ASSERT( hcd_edpt_open(rhport, dev_addr, ep_desc) ); - p_cdc->ep_notif = ep_desc->bEndpointAddress; - - (*p_length) += p_desc[DESC_OFFSET_LEN]; - p_desc = tu_desc_next(p_desc); - } - - //------------- Data Interface (if any) -------------// - if ( (TUSB_DESC_INTERFACE == p_desc[DESC_OFFSET_TYPE]) && - (TUSB_CLASS_CDC_DATA == ((tusb_desc_interface_t const *) p_desc)->bInterfaceClass) ) - { - (*p_length) += p_desc[DESC_OFFSET_LEN]; - p_desc = tu_desc_next(p_desc); - - // data endpoints expected to be in pairs - for(uint32_t i=0; i<2; i++) - { - tusb_desc_endpoint_t const *ep_desc = (tusb_desc_endpoint_t const *) p_desc; - TU_ASSERT(TUSB_DESC_ENDPOINT == ep_desc->bDescriptorType); - TU_ASSERT(TUSB_XFER_BULK == ep_desc->bmAttributes.xfer); - - TU_ASSERT(hcd_edpt_open(rhport, dev_addr, ep_desc)); - - if ( tu_edpt_dir(ep_desc->bEndpointAddress) == TUSB_DIR_IN ) - { - p_cdc->ep_in = ep_desc->bEndpointAddress; - }else - { - p_cdc->ep_out = ep_desc->bEndpointAddress; - } - - (*p_length) += p_desc[DESC_OFFSET_LEN]; - p_desc = tu_desc_next( p_desc ); - } - } - - // FIXME move to seperate API : connect - tusb_control_request_t request = - { - .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_INTERFACE, .type = TUSB_REQ_TYPE_CLASS, .direction = TUSB_DIR_OUT }, - .bRequest = CDC_REQUEST_SET_CONTROL_LINE_STATE, - .wValue = 0x03, // dtr on, cst on - .wIndex = p_cdc->itf_num, - .wLength = 0 - }; - - TU_ASSERT( usbh_control_xfer(dev_addr, &request, NULL) ); - - return true; -} - -void cdch_isr(uint8_t dev_addr, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes) -{ - (void) ep_addr; - tuh_cdc_xfer_isr( dev_addr, event, 0, xferred_bytes ); -} - -void cdch_close(uint8_t dev_addr) -{ - cdch_data_t * p_cdc = &cdch_data[dev_addr-1]; - tu_memclr(p_cdc, sizeof(cdch_data_t)); -} - -#endif +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#include "tusb_option.h" + +#if (TUSB_OPT_HOST_ENABLED && CFG_TUH_CDC) + +#include "common/tusb_common.h" +#include "cdc_host.h" + +//--------------------------------------------------------------------+ +// MACRO CONSTANT TYPEDEF +//--------------------------------------------------------------------+ +typedef struct { + uint8_t itf_num; + uint8_t itf_protocol; + + uint8_t ep_notif; + uint8_t ep_in; + uint8_t ep_out; + + cdc_acm_capability_t acm_capability; + +} cdch_data_t; + +//--------------------------------------------------------------------+ +// INTERNAL OBJECT & FUNCTION DECLARATION +//--------------------------------------------------------------------+ +static cdch_data_t cdch_data[CFG_TUSB_HOST_DEVICE_MAX]; + +bool tuh_cdc_mounted(uint8_t dev_addr) +{ + cdch_data_t* cdc = &cdch_data[dev_addr-1]; + return cdc->ep_in && cdc->ep_out; +} + +bool tuh_cdc_is_busy(uint8_t dev_addr, cdc_pipeid_t pipeid) +{ + if ( !tuh_cdc_mounted(dev_addr) ) return false; + + cdch_data_t const * p_cdc = &cdch_data[dev_addr-1]; + + switch (pipeid) + { + case CDC_PIPE_NOTIFICATION: + return hcd_edpt_busy(dev_addr, p_cdc->ep_notif ); + + case CDC_PIPE_DATA_IN: + return hcd_edpt_busy(dev_addr, p_cdc->ep_in ); + + case CDC_PIPE_DATA_OUT: + return hcd_edpt_busy(dev_addr, p_cdc->ep_out ); + + default: + return false; + } +} + +//--------------------------------------------------------------------+ +// APPLICATION API (parameter validation needed) +//--------------------------------------------------------------------+ +bool tuh_cdc_serial_is_mounted(uint8_t dev_addr) +{ + // TODO consider all AT Command as serial candidate + return tuh_cdc_mounted(dev_addr) && + (CDC_COMM_PROTOCOL_ATCOMMAND <= cdch_data[dev_addr-1].itf_protocol) && + (cdch_data[dev_addr-1].itf_protocol <= CDC_COMM_PROTOCOL_ATCOMMAND_CDMA); +} + +bool tuh_cdc_send(uint8_t dev_addr, void const * p_data, uint32_t length, bool is_notify) +{ + TU_VERIFY( tuh_cdc_mounted(dev_addr) ); + TU_VERIFY( p_data != NULL && length, TUSB_ERROR_INVALID_PARA); + + uint8_t const ep_out = cdch_data[dev_addr-1].ep_out; + if ( hcd_edpt_busy(dev_addr, ep_out) ) return false; + + return hcd_pipe_xfer(dev_addr, ep_out, (void *) p_data, length, is_notify); +} + +bool tuh_cdc_receive(uint8_t dev_addr, void * p_buffer, uint32_t length, bool is_notify) +{ + TU_VERIFY( tuh_cdc_mounted(dev_addr) ); + TU_VERIFY( p_buffer != NULL && length, TUSB_ERROR_INVALID_PARA); + + uint8_t const ep_in = cdch_data[dev_addr-1].ep_in; + if ( hcd_edpt_busy(dev_addr, ep_in) ) return false; + + return hcd_pipe_xfer(dev_addr, ep_in, p_buffer, length, is_notify); +} + +//--------------------------------------------------------------------+ +// USBH-CLASS DRIVER API +//--------------------------------------------------------------------+ +void cdch_init(void) +{ + tu_memclr(cdch_data, sizeof(cdch_data_t)*CFG_TUSB_HOST_DEVICE_MAX); +} + +bool cdch_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const *itf_desc, uint16_t *p_length) +{ + // Only support ACM + TU_VERIFY( CDC_COMM_SUBCLASS_ABSTRACT_CONTROL_MODEL == itf_desc->bInterfaceSubClass); + + // Only support AT commands, no protocol and vendor specific commands. + TU_VERIFY(tu_within(CDC_COMM_PROTOCOL_NONE, itf_desc->bInterfaceProtocol, CDC_COMM_PROTOCOL_ATCOMMAND_CDMA) || + 0xff == itf_desc->bInterfaceProtocol); + + uint8_t const * p_desc; + cdch_data_t * p_cdc; + + p_desc = tu_desc_next(itf_desc); + p_cdc = &cdch_data[dev_addr-1]; + + p_cdc->itf_num = itf_desc->bInterfaceNumber; + p_cdc->itf_protocol = itf_desc->bInterfaceProtocol; // TODO 0xff is consider as rndis candidate, other is virtual Com + + //------------- Communication Interface -------------// + (*p_length) = sizeof(tusb_desc_interface_t); + + // Communication Functional Descriptors + while( TUSB_DESC_CS_INTERFACE == p_desc[DESC_OFFSET_TYPE] ) + { + if ( CDC_FUNC_DESC_ABSTRACT_CONTROL_MANAGEMENT == cdc_functional_desc_typeof(p_desc) ) + { + // save ACM bmCapabilities + p_cdc->acm_capability = ((cdc_desc_func_acm_t const *) p_desc)->bmCapabilities; + } + + (*p_length) += p_desc[DESC_OFFSET_LEN]; + p_desc = tu_desc_next(p_desc); + } + + if ( TUSB_DESC_ENDPOINT == p_desc[DESC_OFFSET_TYPE]) + { + // notification endpoint + tusb_desc_endpoint_t const * ep_desc = (tusb_desc_endpoint_t const *) p_desc; + + TU_ASSERT( hcd_edpt_open(rhport, dev_addr, ep_desc) ); + p_cdc->ep_notif = ep_desc->bEndpointAddress; + + (*p_length) += p_desc[DESC_OFFSET_LEN]; + p_desc = tu_desc_next(p_desc); + } + + //------------- Data Interface (if any) -------------// + if ( (TUSB_DESC_INTERFACE == p_desc[DESC_OFFSET_TYPE]) && + (TUSB_CLASS_CDC_DATA == ((tusb_desc_interface_t const *) p_desc)->bInterfaceClass) ) + { + (*p_length) += p_desc[DESC_OFFSET_LEN]; + p_desc = tu_desc_next(p_desc); + + // data endpoints expected to be in pairs + for(uint32_t i=0; i<2; i++) + { + tusb_desc_endpoint_t const *ep_desc = (tusb_desc_endpoint_t const *) p_desc; + TU_ASSERT(TUSB_DESC_ENDPOINT == ep_desc->bDescriptorType); + TU_ASSERT(TUSB_XFER_BULK == ep_desc->bmAttributes.xfer); + + TU_ASSERT(hcd_edpt_open(rhport, dev_addr, ep_desc)); + + if ( tu_edpt_dir(ep_desc->bEndpointAddress) == TUSB_DIR_IN ) + { + p_cdc->ep_in = ep_desc->bEndpointAddress; + }else + { + p_cdc->ep_out = ep_desc->bEndpointAddress; + } + + (*p_length) += p_desc[DESC_OFFSET_LEN]; + p_desc = tu_desc_next( p_desc ); + } + } + + // FIXME move to seperate API : connect + tusb_control_request_t request = + { + .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_INTERFACE, .type = TUSB_REQ_TYPE_CLASS, .direction = TUSB_DIR_OUT }, + .bRequest = CDC_REQUEST_SET_CONTROL_LINE_STATE, + .wValue = 0x03, // dtr on, cst on + .wIndex = p_cdc->itf_num, + .wLength = 0 + }; + + TU_ASSERT( usbh_control_xfer(dev_addr, &request, NULL) ); + + return true; +} + +void cdch_isr(uint8_t dev_addr, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes) +{ + (void) ep_addr; + tuh_cdc_xfer_isr( dev_addr, event, 0, xferred_bytes ); +} + +void cdch_close(uint8_t dev_addr) +{ + cdch_data_t * p_cdc = &cdch_data[dev_addr-1]; + tu_memclr(p_cdc, sizeof(cdch_data_t)); +} + +#endif diff --git a/src/class/cdc/cdc_host.h b/src/class/cdc/cdc_host.h index 59ad2bfa..306420ce 100644 --- a/src/class/cdc/cdc_host.h +++ b/src/class/cdc/cdc_host.h @@ -1,123 +1,123 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2019 Ha Thach (tinyusb.org) - * - * 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. - * - * This file is part of the TinyUSB stack. - */ - -#ifndef _TUSB_CDC_HOST_H_ -#define _TUSB_CDC_HOST_H_ - -#include "common/tusb_common.h" -#include "host/usbh.h" -#include "cdc.h" - -#ifdef __cplusplus - extern "C" { -#endif - -//--------------------------------------------------------------------+ -// CDC APPLICATION PUBLIC API -//--------------------------------------------------------------------+ -/** \ingroup ClassDriver_CDC Communication Device Class (CDC) - * \addtogroup CDC_Serial Serial - * @{ - * \defgroup CDC_Serial_Host Host - * @{ */ - -/** \brief Check if device support CDC Serial interface or not - * \param[in] dev_addr device address - * \retval true if device supports - * \retval false if device does not support or is not mounted - */ -bool tuh_cdc_serial_is_mounted(uint8_t dev_addr); - -/** \brief Check if the interface is currently busy or not - * \param[in] dev_addr device address - * \param[in] pipeid value from \ref cdc_pipeid_t to indicate target pipe. - * \retval true if the interface is busy, meaning the stack is still transferring/waiting data from/to device - * \retval false if the interface is not busy, meaning the stack successfully transferred data from/to device - * \note This function is used to check if previous transfer is complete (success or error), so that the next transfer - * can be scheduled. User needs to make sure the corresponding interface is mounted - * (by \ref tuh_cdc_serial_is_mounted) before calling this function. - */ -bool tuh_cdc_is_busy(uint8_t dev_addr, cdc_pipeid_t pipeid); - -/** \brief Perform USB OUT transfer to device - * \param[in] dev_addr device address - * \param[in] p_data Buffer containing data. Must be accessible by USB controller (see \ref CFG_TUSB_MEM_SECTION) - * \param[in] length Number of bytes to be transferred via USB bus - * \retval TUSB_ERROR_NONE on success - * \retval TUSB_ERROR_INTERFACE_IS_BUSY if the interface is already transferring data with device - * \retval TUSB_ERROR_DEVICE_NOT_READY if device is not yet configured (by SET CONFIGURED request) - * \retval TUSB_ERROR_INVALID_PARA if input parameters are not correct - * \note This function is non-blocking and returns immediately. The result of USB transfer will be reported by the - * interface's callback function. \a p_data must be declared with \ref CFG_TUSB_MEM_SECTION. - */ -bool tuh_cdc_send(uint8_t dev_addr, void const * p_data, uint32_t length, bool is_notify); - -/** \brief Perform USB IN transfer to get data from device - * \param[in] dev_addr device address - * \param[in] p_buffer Buffer containing received data. Must be accessible by USB controller (see \ref CFG_TUSB_MEM_SECTION) - * \param[in] length Number of bytes to be transferred via USB bus - * \retval TUSB_ERROR_NONE on success - * \retval TUSB_ERROR_INTERFACE_IS_BUSY if the interface is already transferring data with device - * \retval TUSB_ERROR_DEVICE_NOT_READY if device is not yet configured (by SET CONFIGURED request) - * \retval TUSB_ERROR_INVALID_PARA if input parameters are not correct - * \note This function is non-blocking and returns immediately. The result of USB transfer will be reported by the - * interface's callback function. \a p_data must be declared with \ref CFG_TUSB_MEM_SECTION. - */ -bool tuh_cdc_receive(uint8_t dev_addr, void * p_buffer, uint32_t length, bool is_notify); - -//--------------------------------------------------------------------+ -// CDC APPLICATION CALLBACKS -//--------------------------------------------------------------------+ - -/** \brief Callback function that is invoked when an transferring event occurred - * \param[in] dev_addr Address of device - * \param[in] event an value from \ref xfer_result_t - * \param[in] pipe_id value from \ref cdc_pipeid_t indicate the pipe - * \param[in] xferred_bytes Number of bytes transferred via USB bus - * \note event can be one of following - * - XFER_RESULT_SUCCESS : previously scheduled transfer completes successfully. - * - XFER_RESULT_FAILED : previously scheduled transfer encountered a transaction error. - * - XFER_RESULT_STALLED : previously scheduled transfer is stalled by device. - * \note - */ -void tuh_cdc_xfer_isr(uint8_t dev_addr, xfer_result_t event, cdc_pipeid_t pipe_id, uint32_t xferred_bytes); - -/// @} // group CDC_Serial_Host -/// @} - -//--------------------------------------------------------------------+ -// Internal Class Driver API -//--------------------------------------------------------------------+ -void cdch_init(void); -bool cdch_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const *itf_desc, uint16_t *p_length); -void cdch_isr(uint8_t dev_addr, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes); -void cdch_close(uint8_t dev_addr); - -#ifdef __cplusplus - } -#endif - -#endif /* _TUSB_CDC_HOST_H_ */ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#ifndef _TUSB_CDC_HOST_H_ +#define _TUSB_CDC_HOST_H_ + +#include "common/tusb_common.h" +#include "host/usbh.h" +#include "cdc.h" + +#ifdef __cplusplus + extern "C" { +#endif + +//--------------------------------------------------------------------+ +// CDC APPLICATION PUBLIC API +//--------------------------------------------------------------------+ +/** \ingroup ClassDriver_CDC Communication Device Class (CDC) + * \addtogroup CDC_Serial Serial + * @{ + * \defgroup CDC_Serial_Host Host + * @{ */ + +/** \brief Check if device support CDC Serial interface or not + * \param[in] dev_addr device address + * \retval true if device supports + * \retval false if device does not support or is not mounted + */ +bool tuh_cdc_serial_is_mounted(uint8_t dev_addr); + +/** \brief Check if the interface is currently busy or not + * \param[in] dev_addr device address + * \param[in] pipeid value from \ref cdc_pipeid_t to indicate target pipe. + * \retval true if the interface is busy, meaning the stack is still transferring/waiting data from/to device + * \retval false if the interface is not busy, meaning the stack successfully transferred data from/to device + * \note This function is used to check if previous transfer is complete (success or error), so that the next transfer + * can be scheduled. User needs to make sure the corresponding interface is mounted + * (by \ref tuh_cdc_serial_is_mounted) before calling this function. + */ +bool tuh_cdc_is_busy(uint8_t dev_addr, cdc_pipeid_t pipeid); + +/** \brief Perform USB OUT transfer to device + * \param[in] dev_addr device address + * \param[in] p_data Buffer containing data. Must be accessible by USB controller (see \ref CFG_TUSB_MEM_SECTION) + * \param[in] length Number of bytes to be transferred via USB bus + * \retval TUSB_ERROR_NONE on success + * \retval TUSB_ERROR_INTERFACE_IS_BUSY if the interface is already transferring data with device + * \retval TUSB_ERROR_DEVICE_NOT_READY if device is not yet configured (by SET CONFIGURED request) + * \retval TUSB_ERROR_INVALID_PARA if input parameters are not correct + * \note This function is non-blocking and returns immediately. The result of USB transfer will be reported by the + * interface's callback function. \a p_data must be declared with \ref CFG_TUSB_MEM_SECTION. + */ +bool tuh_cdc_send(uint8_t dev_addr, void const * p_data, uint32_t length, bool is_notify); + +/** \brief Perform USB IN transfer to get data from device + * \param[in] dev_addr device address + * \param[in] p_buffer Buffer containing received data. Must be accessible by USB controller (see \ref CFG_TUSB_MEM_SECTION) + * \param[in] length Number of bytes to be transferred via USB bus + * \retval TUSB_ERROR_NONE on success + * \retval TUSB_ERROR_INTERFACE_IS_BUSY if the interface is already transferring data with device + * \retval TUSB_ERROR_DEVICE_NOT_READY if device is not yet configured (by SET CONFIGURED request) + * \retval TUSB_ERROR_INVALID_PARA if input parameters are not correct + * \note This function is non-blocking and returns immediately. The result of USB transfer will be reported by the + * interface's callback function. \a p_data must be declared with \ref CFG_TUSB_MEM_SECTION. + */ +bool tuh_cdc_receive(uint8_t dev_addr, void * p_buffer, uint32_t length, bool is_notify); + +//--------------------------------------------------------------------+ +// CDC APPLICATION CALLBACKS +//--------------------------------------------------------------------+ + +/** \brief Callback function that is invoked when an transferring event occurred + * \param[in] dev_addr Address of device + * \param[in] event an value from \ref xfer_result_t + * \param[in] pipe_id value from \ref cdc_pipeid_t indicate the pipe + * \param[in] xferred_bytes Number of bytes transferred via USB bus + * \note event can be one of following + * - XFER_RESULT_SUCCESS : previously scheduled transfer completes successfully. + * - XFER_RESULT_FAILED : previously scheduled transfer encountered a transaction error. + * - XFER_RESULT_STALLED : previously scheduled transfer is stalled by device. + * \note + */ +void tuh_cdc_xfer_isr(uint8_t dev_addr, xfer_result_t event, cdc_pipeid_t pipe_id, uint32_t xferred_bytes); + +/// @} // group CDC_Serial_Host +/// @} + +//--------------------------------------------------------------------+ +// Internal Class Driver API +//--------------------------------------------------------------------+ +void cdch_init(void); +bool cdch_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const *itf_desc, uint16_t *p_length); +void cdch_isr(uint8_t dev_addr, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes); +void cdch_close(uint8_t dev_addr); + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_CDC_HOST_H_ */ diff --git a/src/class/hid/hid.h b/src/class/hid/hid.h index 7fa4aa8a..84827403 100644 --- a/src/class/hid/hid.h +++ b/src/class/hid/hid.h @@ -1,873 +1,873 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2019 Ha Thach (tinyusb.org) - * - * 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. - * - * This file is part of the TinyUSB stack. - */ - -/** \ingroup group_class - * \defgroup ClassDriver_HID Human Interface Device (HID) - * @{ */ - -#ifndef _TUSB_HID_H_ -#define _TUSB_HID_H_ - -#include "common/tusb_common.h" - -#ifdef __cplusplus - extern "C" { -#endif - -//--------------------------------------------------------------------+ -// Common Definitions -//--------------------------------------------------------------------+ -/** \defgroup ClassDriver_HID_Common Common Definitions - * @{ */ - - /// USB HID Descriptor -typedef struct TU_ATTR_PACKED -{ - uint8_t bLength; /**< Numeric expression that is the total size of the HID descriptor */ - uint8_t bDescriptorType; /**< Constant name specifying type of HID descriptor. */ - - uint16_t bcdHID; /**< Numeric expression identifying the HID Class Specification release */ - uint8_t bCountryCode; /**< Numeric expression identifying country code of the localized hardware. */ - uint8_t bNumDescriptors; /**< Numeric expression specifying the number of class descriptors */ - - uint8_t bReportType; /**< Type of HID class report. */ - uint16_t wReportLength; /**< the total size of the Report descriptor. */ -} tusb_hid_descriptor_hid_t; - -/// HID Subclass -typedef enum -{ - HID_SUBCLASS_NONE = 0, ///< No Subclass - HID_SUBCLASS_BOOT = 1 ///< Boot Interface Subclass -}hid_subclass_type_t; - -/// HID Protocol -typedef enum -{ - HID_PROTOCOL_NONE = 0, ///< None - HID_PROTOCOL_KEYBOARD = 1, ///< Keyboard - HID_PROTOCOL_MOUSE = 2 ///< Mouse -}hid_protocol_type_t; - -/// HID Descriptor Type -typedef enum -{ - HID_DESC_TYPE_HID = 0x21, ///< HID Descriptor - HID_DESC_TYPE_REPORT = 0x22, ///< Report Descriptor - HID_DESC_TYPE_PHYSICAL = 0x23 ///< Physical Descriptor -}hid_descriptor_type_t; - -/// HID Request Report Type -typedef enum -{ - HID_REPORT_TYPE_INVALID = 0, - HID_REPORT_TYPE_INPUT, ///< Input - HID_REPORT_TYPE_OUTPUT, ///< Output - HID_REPORT_TYPE_FEATURE ///< Feature -}hid_report_type_t; - -/// HID Class Specific Control Request -typedef enum -{ - HID_REQ_CONTROL_GET_REPORT = 0x01, ///< Get Report - HID_REQ_CONTROL_GET_IDLE = 0x02, ///< Get Idle - HID_REQ_CONTROL_GET_PROTOCOL = 0x03, ///< Get Protocol - HID_REQ_CONTROL_SET_REPORT = 0x09, ///< Set Report - HID_REQ_CONTROL_SET_IDLE = 0x0a, ///< Set Idle - HID_REQ_CONTROL_SET_PROTOCOL = 0x0b ///< Set Protocol -}hid_request_type_t; - -/// HID Country Code -typedef enum -{ - HID_LOCAL_NotSupported = 0 , ///< NotSupported - HID_LOCAL_Arabic , ///< Arabic - HID_LOCAL_Belgian , ///< Belgian - HID_LOCAL_Canadian_Bilingual , ///< Canadian_Bilingual - HID_LOCAL_Canadian_French , ///< Canadian_French - HID_LOCAL_Czech_Republic , ///< Czech_Republic - HID_LOCAL_Danish , ///< Danish - HID_LOCAL_Finnish , ///< Finnish - HID_LOCAL_French , ///< French - HID_LOCAL_German , ///< German - HID_LOCAL_Greek , ///< Greek - HID_LOCAL_Hebrew , ///< Hebrew - HID_LOCAL_Hungary , ///< Hungary - HID_LOCAL_International , ///< International - HID_LOCAL_Italian , ///< Italian - HID_LOCAL_Japan_Katakana , ///< Japan_Katakana - HID_LOCAL_Korean , ///< Korean - HID_LOCAL_Latin_American , ///< Latin_American - HID_LOCAL_Netherlands_Dutch , ///< Netherlands/Dutch - HID_LOCAL_Norwegian , ///< Norwegian - HID_LOCAL_Persian_Farsi , ///< Persian (Farsi) - HID_LOCAL_Poland , ///< Poland - HID_LOCAL_Portuguese , ///< Portuguese - HID_LOCAL_Russia , ///< Russia - HID_LOCAL_Slovakia , ///< Slovakia - HID_LOCAL_Spanish , ///< Spanish - HID_LOCAL_Swedish , ///< Swedish - HID_LOCAL_Swiss_French , ///< Swiss/French - HID_LOCAL_Swiss_German , ///< Swiss/German - HID_LOCAL_Switzerland , ///< Switzerland - HID_LOCAL_Taiwan , ///< Taiwan - HID_LOCAL_Turkish_Q , ///< Turkish-Q - HID_LOCAL_UK , ///< UK - HID_LOCAL_US , ///< US - HID_LOCAL_Yugoslavia , ///< Yugoslavia - HID_LOCAL_Turkish_F ///< Turkish-F -} hid_country_code_t; - -/** @} */ - -//--------------------------------------------------------------------+ -// MOUSE -//--------------------------------------------------------------------+ -/** \addtogroup ClassDriver_HID_Mouse Mouse - * @{ */ - -/// Standard HID Boot Protocol Mouse Report. -typedef struct TU_ATTR_PACKED -{ - uint8_t buttons; /**< buttons mask for currently pressed buttons in the mouse. */ - int8_t x; /**< Current delta x movement of the mouse. */ - int8_t y; /**< Current delta y movement on the mouse. */ - int8_t wheel; /**< Current delta wheel movement on the mouse. */ - int8_t pan; // using AC Pan -} hid_mouse_report_t; - -/// Standard Mouse Buttons Bitmap -typedef enum -{ - MOUSE_BUTTON_LEFT = TU_BIT(0), ///< Left button - MOUSE_BUTTON_RIGHT = TU_BIT(1), ///< Right button - MOUSE_BUTTON_MIDDLE = TU_BIT(2), ///< Middle button - MOUSE_BUTTON_BACKWARD = TU_BIT(3), ///< Backward button, - MOUSE_BUTTON_FORWARD = TU_BIT(4), ///< Forward button, -}hid_mouse_button_bm_t; - -/// @} - -//--------------------------------------------------------------------+ -// Keyboard -//--------------------------------------------------------------------+ -/** \addtogroup ClassDriver_HID_Keyboard Keyboard - * @{ */ - -/// Standard HID Boot Protocol Keyboard Report. -typedef struct TU_ATTR_PACKED -{ - uint8_t modifier; /**< Keyboard modifier (KEYBOARD_MODIFIER_* masks). */ - uint8_t reserved; /**< Reserved for OEM use, always set to 0. */ - uint8_t keycode[6]; /**< Key codes of the currently pressed keys. */ -} hid_keyboard_report_t; - -/// Keyboard modifier codes bitmap -typedef enum -{ - KEYBOARD_MODIFIER_LEFTCTRL = TU_BIT(0), ///< Left Control - KEYBOARD_MODIFIER_LEFTSHIFT = TU_BIT(1), ///< Left Shift - KEYBOARD_MODIFIER_LEFTALT = TU_BIT(2), ///< Left Alt - KEYBOARD_MODIFIER_LEFTGUI = TU_BIT(3), ///< Left Window - KEYBOARD_MODIFIER_RIGHTCTRL = TU_BIT(4), ///< Right Control - KEYBOARD_MODIFIER_RIGHTSHIFT = TU_BIT(5), ///< Right Shift - KEYBOARD_MODIFIER_RIGHTALT = TU_BIT(6), ///< Right Alt - KEYBOARD_MODIFIER_RIGHTGUI = TU_BIT(7) ///< Right Window -}hid_keyboard_modifier_bm_t; - -typedef enum -{ - KEYBOARD_LED_NUMLOCK = TU_BIT(0), ///< Num Lock LED - KEYBOARD_LED_CAPSLOCK = TU_BIT(1), ///< Caps Lock LED - KEYBOARD_LED_SCROLLLOCK = TU_BIT(2), ///< Scroll Lock LED - KEYBOARD_LED_COMPOSE = TU_BIT(3), ///< Composition Mode - KEYBOARD_LED_KANA = TU_BIT(4) ///< Kana mode -}hid_keyboard_led_bm_t; - -/// @} - -//--------------------------------------------------------------------+ -// HID KEYCODE -//--------------------------------------------------------------------+ -#define HID_KEY_NONE 0x00 -#define HID_KEY_A 0x04 -#define HID_KEY_B 0x05 -#define HID_KEY_C 0x06 -#define HID_KEY_D 0x07 -#define HID_KEY_E 0x08 -#define HID_KEY_F 0x09 -#define HID_KEY_G 0x0A -#define HID_KEY_H 0x0B -#define HID_KEY_I 0x0C -#define HID_KEY_J 0x0D -#define HID_KEY_K 0x0E -#define HID_KEY_L 0x0F -#define HID_KEY_M 0x10 -#define HID_KEY_N 0x11 -#define HID_KEY_O 0x12 -#define HID_KEY_P 0x13 -#define HID_KEY_Q 0x14 -#define HID_KEY_R 0x15 -#define HID_KEY_S 0x16 -#define HID_KEY_T 0x17 -#define HID_KEY_U 0x18 -#define HID_KEY_V 0x19 -#define HID_KEY_W 0x1A -#define HID_KEY_X 0x1B -#define HID_KEY_Y 0x1C -#define HID_KEY_Z 0x1D -#define HID_KEY_1 0x1E -#define HID_KEY_2 0x1F -#define HID_KEY_3 0x20 -#define HID_KEY_4 0x21 -#define HID_KEY_5 0x22 -#define HID_KEY_6 0x23 -#define HID_KEY_7 0x24 -#define HID_KEY_8 0x25 -#define HID_KEY_9 0x26 -#define HID_KEY_0 0x27 -#define HID_KEY_RETURN 0x28 -#define HID_KEY_ESCAPE 0x29 -#define HID_KEY_BACKSPACE 0x2A -#define HID_KEY_TAB 0x2B -#define HID_KEY_SPACE 0x2C -#define HID_KEY_MINUS 0x2D -#define HID_KEY_EQUAL 0x2E -#define HID_KEY_BRACKET_LEFT 0x2F -#define HID_KEY_BRACKET_RIGHT 0x30 -#define HID_KEY_BACKSLASH 0x31 -#define HID_KEY_EUROPE_1 0x32 -#define HID_KEY_SEMICOLON 0x33 -#define HID_KEY_APOSTROPHE 0x34 -#define HID_KEY_GRAVE 0x35 -#define HID_KEY_COMMA 0x36 -#define HID_KEY_PERIOD 0x37 -#define HID_KEY_SLASH 0x38 -#define HID_KEY_CAPS_LOCK 0x39 -#define HID_KEY_F1 0x3A -#define HID_KEY_F2 0x3B -#define HID_KEY_F3 0x3C -#define HID_KEY_F4 0x3D -#define HID_KEY_F5 0x3E -#define HID_KEY_F6 0x3F -#define HID_KEY_F7 0x40 -#define HID_KEY_F8 0x41 -#define HID_KEY_F9 0x42 -#define HID_KEY_F10 0x43 -#define HID_KEY_F11 0x44 -#define HID_KEY_F12 0x45 -#define HID_KEY_PRINT_SCREEN 0x46 -#define HID_KEY_SCROLL_LOCK 0x47 -#define HID_KEY_PAUSE 0x48 -#define HID_KEY_INSERT 0x49 -#define HID_KEY_HOME 0x4A -#define HID_KEY_PAGE_UP 0x4B -#define HID_KEY_DELETE 0x4C -#define HID_KEY_END 0x4D -#define HID_KEY_PAGE_DOWN 0x4E -#define HID_KEY_ARROW_RIGHT 0x4F -#define HID_KEY_ARROW_LEFT 0x50 -#define HID_KEY_ARROW_DOWN 0x51 -#define HID_KEY_ARROW_UP 0x52 -#define HID_KEY_NUM_LOCK 0x53 -#define HID_KEY_KEYPAD_DIVIDE 0x54 -#define HID_KEY_KEYPAD_MULTIPLY 0x55 -#define HID_KEY_KEYPAD_SUBTRACT 0x56 -#define HID_KEY_KEYPAD_ADD 0x57 -#define HID_KEY_KEYPAD_ENTER 0x58 -#define HID_KEY_KEYPAD_1 0x59 -#define HID_KEY_KEYPAD_2 0x5A -#define HID_KEY_KEYPAD_3 0x5B -#define HID_KEY_KEYPAD_4 0x5C -#define HID_KEY_KEYPAD_5 0x5D -#define HID_KEY_KEYPAD_6 0x5E -#define HID_KEY_KEYPAD_7 0x5F -#define HID_KEY_KEYPAD_8 0x60 -#define HID_KEY_KEYPAD_9 0x61 -#define HID_KEY_KEYPAD_0 0x62 -#define HID_KEY_KEYPAD_DECIMAL 0x63 -#define HID_KEY_EUROPE_2 0x64 -#define HID_KEY_APPLICATION 0x65 -#define HID_KEY_POWER 0x66 -#define HID_KEY_KEYPAD_EQUAL 0x67 -#define HID_KEY_F13 0x68 -#define HID_KEY_F14 0x69 -#define HID_KEY_F15 0x6A -#define HID_KEY_CONTROL_LEFT 0xE0 -#define HID_KEY_SHIFT_LEFT 0xE1 -#define HID_KEY_ALT_LEFT 0xE2 -#define HID_KEY_GUI_LEFT 0xE3 -#define HID_KEY_CONTROL_RIGHT 0xE4 -#define HID_KEY_SHIFT_RIGHT 0xE5 -#define HID_KEY_ALT_RIGHT 0xE6 -#define HID_KEY_GUI_RIGHT 0xE7 - - -//--------------------------------------------------------------------+ -// REPORT DESCRIPTOR -//--------------------------------------------------------------------+ -//------------- ITEM & TAG -------------// -#define HID_REPORT_DATA_0(data) -#define HID_REPORT_DATA_1(data) , data -#define HID_REPORT_DATA_2(data) , U16_TO_U8S_LE(data) -#define HID_REPORT_DATA_3(data) , U32_TO_U8S_LE(data) - -#define HID_REPORT_ITEM(data, tag, type, size) \ - (((tag) << 4) | ((type) << 2) | (size)) HID_REPORT_DATA_##size(data) - -#define RI_TYPE_MAIN 0 -#define RI_TYPE_GLOBAL 1 -#define RI_TYPE_LOCAL 2 - -//------------- MAIN ITEMS 6.2.2.4 -------------// -#define HID_INPUT(x) HID_REPORT_ITEM(x, 8, RI_TYPE_MAIN, 1) -#define HID_OUTPUT(x) HID_REPORT_ITEM(x, 9, RI_TYPE_MAIN, 1) -#define HID_COLLECTION(x) HID_REPORT_ITEM(x, 10, RI_TYPE_MAIN, 1) -#define HID_FEATURE(x) HID_REPORT_ITEM(x, 11, RI_TYPE_MAIN, 1) -#define HID_COLLECTION_END HID_REPORT_ITEM(x, 12, RI_TYPE_MAIN, 0) - -//------------- INPUT, OUTPUT, FEATURE 6.2.2.5 -------------// -#define HID_DATA (0<<0) -#define HID_CONSTANT (1<<0) - -#define HID_ARRAY (0<<1) -#define HID_VARIABLE (1<<1) - -#define HID_ABSOLUTE (0<<2) -#define HID_RELATIVE (1<<2) - -#define HID_WRAP_NO (0<<3) -#define HID_WRAP (1<<3) - -#define HID_LINEAR (0<<4) -#define HID_NONLINEAR (1<<4) - -#define HID_PREFERRED_STATE (0<<5) -#define HID_PREFERRED_NO (1<<5) - -#define HID_NO_NULL_POSITION (0<<6) -#define HID_NULL_STATE (1<<6) - -#define HID_NON_VOLATILE (0<<7) -#define HID_VOLATILE (1<<7) - -#define HID_BITFIELD (0<<8) -#define HID_BUFFERED_BYTES (1<<8) - -//------------- COLLECTION ITEM 6.2.2.6 -------------// -enum { - HID_COLLECTION_PHYSICAL = 0, - HID_COLLECTION_APPLICATION, - HID_COLLECTION_LOGICAL, - HID_COLLECTION_REPORT, - HID_COLLECTION_NAMED_ARRAY, - HID_COLLECTION_USAGE_SWITCH, - HID_COLLECTION_USAGE_MODIFIER -}; - -//------------- GLOBAL ITEMS 6.2.2.7 -------------// -#define HID_USAGE_PAGE(x) HID_REPORT_ITEM(x, 0, RI_TYPE_GLOBAL, 1) -#define HID_USAGE_PAGE_N(x, n) HID_REPORT_ITEM(x, 0, RI_TYPE_GLOBAL, n) - -#define HID_LOGICAL_MIN(x) HID_REPORT_ITEM(x, 1, RI_TYPE_GLOBAL, 1) -#define HID_LOGICAL_MIN_N(x, n) HID_REPORT_ITEM(x, 1, RI_TYPE_GLOBAL, n) - -#define HID_LOGICAL_MAX(x) HID_REPORT_ITEM(x, 2, RI_TYPE_GLOBAL, 1) -#define HID_LOGICAL_MAX_N(x, n) HID_REPORT_ITEM(x, 2, RI_TYPE_GLOBAL, n) - -#define HID_PHYSICAL_MIN(x) HID_REPORT_ITEM(x, 3, RI_TYPE_GLOBAL, 1) -#define HID_PHYSICAL_MIN_N(x, n) HID_REPORT_ITEM(x, 3, RI_TYPE_GLOBAL, n) - -#define HID_PHYSICAL_MAX(x) HID_REPORT_ITEM(x, 4, RI_TYPE_GLOBAL, 1) -#define HID_PHYSICAL_MAX_N(x, n) HID_REPORT_ITEM(x, 4, RI_TYPE_GLOBAL, n) - -#define HID_UNIT_EXPONENT(x) HID_REPORT_ITEM(x, 5, RI_TYPE_GLOBAL, 1) -#define HID_UNIT_EXPONENT_N(x, n) HID_REPORT_ITEM(x, 5, RI_TYPE_GLOBAL, n) - -#define HID_UNIT(x) HID_REPORT_ITEM(x, 6, RI_TYPE_GLOBAL, 1) -#define HID_UNIT_N(x, n) HID_REPORT_ITEM(x, 6, RI_TYPE_GLOBAL, n) - -#define HID_REPORT_SIZE(x) HID_REPORT_ITEM(x, 7, RI_TYPE_GLOBAL, 1) -#define HID_REPORT_SIZE_N(x, n) HID_REPORT_ITEM(x, 7, RI_TYPE_GLOBAL, n) - -#define HID_REPORT_ID(x) HID_REPORT_ITEM(x, 8, RI_TYPE_GLOBAL, 1) -#define HID_REPORT_ID_N(x) HID_REPORT_ITEM(x, 8, RI_TYPE_GLOBAL, n) - -#define HID_REPORT_COUNT(x) HID_REPORT_ITEM(x, 9, RI_TYPE_GLOBAL, 1) -#define HID_REPORT_COUNT_N(x, n) HID_REPORT_ITEM(x, 9, RI_TYPE_GLOBAL, n) - -#define HID_PUSH HID_REPORT_ITEM(x, 10, RI_TYPE_GLOBAL, 0) -#define HID_POP HID_REPORT_ITEM(x, 11, RI_TYPE_GLOBAL, 0) - -//------------- LOCAL ITEMS 6.2.2.8 -------------// -#define HID_USAGE(x) HID_REPORT_ITEM(x, 0, RI_TYPE_LOCAL, 1) -#define HID_USAGE_N(x, n) HID_REPORT_ITEM(x, 0, RI_TYPE_LOCAL, n) - -#define HID_USAGE_MIN(x) HID_REPORT_ITEM(x, 1, RI_TYPE_LOCAL, 1) -#define HID_USAGE_MIN_N(x, n) HID_REPORT_ITEM(x, 1, RI_TYPE_LOCAL, n) - -#define HID_USAGE_MAX(x) HID_REPORT_ITEM(x, 2, RI_TYPE_LOCAL, 1) -#define HID_USAGE_MAX_N(x, n) HID_REPORT_ITEM(x, 2, RI_TYPE_LOCAL, n) - -//--------------------------------------------------------------------+ -// Usage Table -//--------------------------------------------------------------------+ - -/// HID Usage Table - Table 1: Usage Page Summary -enum { - HID_USAGE_PAGE_DESKTOP = 0x01, - HID_USAGE_PAGE_SIMULATE = 0x02, - HID_USAGE_PAGE_VIRTUAL_REALITY = 0x03, - HID_USAGE_PAGE_SPORT = 0x04, - HID_USAGE_PAGE_GAME = 0x05, - HID_USAGE_PAGE_GENERIC_DEVICE = 0x06, - HID_USAGE_PAGE_KEYBOARD = 0x07, - HID_USAGE_PAGE_LED = 0x08, - HID_USAGE_PAGE_BUTTON = 0x09, - HID_USAGE_PAGE_ORDINAL = 0x0a, - HID_USAGE_PAGE_TELEPHONY = 0x0b, - HID_USAGE_PAGE_CONSUMER = 0x0c, - HID_USAGE_PAGE_DIGITIZER = 0x0d, - HID_USAGE_PAGE_PID = 0x0f, - HID_USAGE_PAGE_UNICODE = 0x10, - HID_USAGE_PAGE_ALPHA_DISPLAY = 0x14, - HID_USAGE_PAGE_MEDICAL = 0x40, - HID_USAGE_PAGE_MONITOR = 0x80, //0x80 - 0x83 - HID_USAGE_PAGE_POWER = 0x84, // 0x084 - 0x87 - HID_USAGE_PAGE_BARCODE_SCANNER = 0x8c, - HID_USAGE_PAGE_SCALE = 0x8d, - HID_USAGE_PAGE_MSR = 0x8e, - HID_USAGE_PAGE_CAMERA = 0x90, - HID_USAGE_PAGE_ARCADE = 0x91, - HID_USAGE_PAGE_VENDOR = 0xFF00 // 0xFF00 - 0xFFFF -}; - -/// HID Usage Table - Table 6: Generic Desktop Page -enum { - HID_USAGE_DESKTOP_POINTER = 0x01, - HID_USAGE_DESKTOP_MOUSE = 0x02, - HID_USAGE_DESKTOP_JOYSTICK = 0x04, - HID_USAGE_DESKTOP_GAMEPAD = 0x05, - HID_USAGE_DESKTOP_KEYBOARD = 0x06, - HID_USAGE_DESKTOP_KEYPAD = 0x07, - HID_USAGE_DESKTOP_MULTI_AXIS_CONTROLLER = 0x08, - HID_USAGE_DESKTOP_TABLET_PC_SYSTEM = 0x09, - HID_USAGE_DESKTOP_X = 0x30, - HID_USAGE_DESKTOP_Y = 0x31, - HID_USAGE_DESKTOP_Z = 0x32, - HID_USAGE_DESKTOP_RX = 0x33, - HID_USAGE_DESKTOP_RY = 0x34, - HID_USAGE_DESKTOP_RZ = 0x35, - HID_USAGE_DESKTOP_SLIDER = 0x36, - HID_USAGE_DESKTOP_DIAL = 0x37, - HID_USAGE_DESKTOP_WHEEL = 0x38, - HID_USAGE_DESKTOP_HAT_SWITCH = 0x39, - HID_USAGE_DESKTOP_COUNTED_BUFFER = 0x3a, - HID_USAGE_DESKTOP_BYTE_COUNT = 0x3b, - HID_USAGE_DESKTOP_MOTION_WAKEUP = 0x3c, - HID_USAGE_DESKTOP_START = 0x3d, - HID_USAGE_DESKTOP_SELECT = 0x3e, - HID_USAGE_DESKTOP_VX = 0x40, - HID_USAGE_DESKTOP_VY = 0x41, - HID_USAGE_DESKTOP_VZ = 0x42, - HID_USAGE_DESKTOP_VBRX = 0x43, - HID_USAGE_DESKTOP_VBRY = 0x44, - HID_USAGE_DESKTOP_VBRZ = 0x45, - HID_USAGE_DESKTOP_VNO = 0x46, - HID_USAGE_DESKTOP_FEATURE_NOTIFICATION = 0x47, - HID_USAGE_DESKTOP_RESOLUTION_MULTIPLIER = 0x48, - HID_USAGE_DESKTOP_SYSTEM_CONTROL = 0x80, - HID_USAGE_DESKTOP_SYSTEM_POWER_DOWN = 0x81, - HID_USAGE_DESKTOP_SYSTEM_SLEEP = 0x82, - HID_USAGE_DESKTOP_SYSTEM_WAKE_UP = 0x83, - HID_USAGE_DESKTOP_SYSTEM_CONTEXT_MENU = 0x84, - HID_USAGE_DESKTOP_SYSTEM_MAIN_MENU = 0x85, - HID_USAGE_DESKTOP_SYSTEM_APP_MENU = 0x86, - HID_USAGE_DESKTOP_SYSTEM_MENU_HELP = 0x87, - HID_USAGE_DESKTOP_SYSTEM_MENU_EXIT = 0x88, - HID_USAGE_DESKTOP_SYSTEM_MENU_SELECT = 0x89, - HID_USAGE_DESKTOP_SYSTEM_MENU_RIGHT = 0x8A, - HID_USAGE_DESKTOP_SYSTEM_MENU_LEFT = 0x8B, - HID_USAGE_DESKTOP_SYSTEM_MENU_UP = 0x8C, - HID_USAGE_DESKTOP_SYSTEM_MENU_DOWN = 0x8D, - HID_USAGE_DESKTOP_SYSTEM_COLD_RESTART = 0x8E, - HID_USAGE_DESKTOP_SYSTEM_WARM_RESTART = 0x8F, - HID_USAGE_DESKTOP_DPAD_UP = 0x90, - HID_USAGE_DESKTOP_DPAD_DOWN = 0x91, - HID_USAGE_DESKTOP_DPAD_RIGHT = 0x92, - HID_USAGE_DESKTOP_DPAD_LEFT = 0x93, - HID_USAGE_DESKTOP_SYSTEM_DOCK = 0xA0, - HID_USAGE_DESKTOP_SYSTEM_UNDOCK = 0xA1, - HID_USAGE_DESKTOP_SYSTEM_SETUP = 0xA2, - HID_USAGE_DESKTOP_SYSTEM_BREAK = 0xA3, - HID_USAGE_DESKTOP_SYSTEM_DEBUGGER_BREAK = 0xA4, - HID_USAGE_DESKTOP_APPLICATION_BREAK = 0xA5, - HID_USAGE_DESKTOP_APPLICATION_DEBUGGER_BREAK = 0xA6, - HID_USAGE_DESKTOP_SYSTEM_SPEAKER_MUTE = 0xA7, - HID_USAGE_DESKTOP_SYSTEM_HIBERNATE = 0xA8, - HID_USAGE_DESKTOP_SYSTEM_DISPLAY_INVERT = 0xB0, - HID_USAGE_DESKTOP_SYSTEM_DISPLAY_INTERNAL = 0xB1, - HID_USAGE_DESKTOP_SYSTEM_DISPLAY_EXTERNAL = 0xB2, - HID_USAGE_DESKTOP_SYSTEM_DISPLAY_BOTH = 0xB3, - HID_USAGE_DESKTOP_SYSTEM_DISPLAY_DUAL = 0xB4, - HID_USAGE_DESKTOP_SYSTEM_DISPLAY_TOGGLE_INT_EXT = 0xB5, - HID_USAGE_DESKTOP_SYSTEM_DISPLAY_SWAP_PRIMARY_SECONDARY = 0xB6, - HID_USAGE_DESKTOP_SYSTEM_DISPLAY_LCD_AUTOSCALE = 0xB7 -}; - - -/// HID Usage Table: Consumer Page (0x0C) -/// Only contains controls that supported by Windows (whole list is too long) -enum -{ - // Generic Control - HID_USAGE_CONSUMER_CONTROL = 0x0001, - - // Power Control - HID_USAGE_CONSUMER_POWER = 0x0030, - HID_USAGE_CONSUMER_RESET = 0x0031, - HID_USAGE_CONSUMER_SLEEP = 0x0032, - - // Screen Brightness - HID_USAGE_CONSUMER_BRIGHTNESS_INCREMENT = 0x006F, - HID_USAGE_CONSUMER_BRIGHTNESS_DECREMENT = 0x0070, - - // These HID usages operate only on mobile systems (battery powered) and - // require Windows 8 (build 8302 or greater). - HID_USAGE_CONSUMER_WIRELESS_RADIO_CONTROLS = 0x000C, - HID_USAGE_CONSUMER_WIRELESS_RADIO_BUTTONS = 0x00C6, - HID_USAGE_CONSUMER_WIRELESS_RADIO_LED = 0x00C7, - HID_USAGE_CONSUMER_WIRELESS_RADIO_SLIDER_SWITCH = 0x00C8, - - // Media Control - HID_USAGE_CONSUMER_PLAY_PAUSE = 0x00CD, - HID_USAGE_CONSUMER_SCAN_NEXT = 0x00B5, - HID_USAGE_CONSUMER_SCAN_PREVIOUS = 0x00B6, - HID_USAGE_CONSUMER_STOP = 0x00B7, - HID_USAGE_CONSUMER_VOLUME = 0x00E0, - HID_USAGE_CONSUMER_MUTE = 0x00E2, - HID_USAGE_CONSUMER_BASS = 0x00E3, - HID_USAGE_CONSUMER_TREBLE = 0x00E4, - HID_USAGE_CONSUMER_BASS_BOOST = 0x00E5, - HID_USAGE_CONSUMER_VOLUME_INCREMENT = 0x00E9, - HID_USAGE_CONSUMER_VOLUME_DECREMENT = 0x00EA, - HID_USAGE_CONSUMER_BASS_INCREMENT = 0x0152, - HID_USAGE_CONSUMER_BASS_DECREMENT = 0x0153, - HID_USAGE_CONSUMER_TREBLE_INCREMENT = 0x0154, - HID_USAGE_CONSUMER_TREBLE_DECREMENT = 0x0155, - - // Application Launcher - HID_USAGE_CONSUMER_AL_CONSUMER_CONTROL_CONFIGURATION = 0x0183, - HID_USAGE_CONSUMER_AL_EMAIL_READER = 0x018A, - HID_USAGE_CONSUMER_AL_CALCULATOR = 0x0192, - HID_USAGE_CONSUMER_AL_LOCAL_BROWSER = 0x0194, - - // Browser/Explorer Specific - HID_USAGE_CONSUMER_AC_SEARCH = 0x0221, - HID_USAGE_CONSUMER_AC_HOME = 0x0223, - HID_USAGE_CONSUMER_AC_BACK = 0x0224, - HID_USAGE_CONSUMER_AC_FORWARD = 0x0225, - HID_USAGE_CONSUMER_AC_STOP = 0x0226, - HID_USAGE_CONSUMER_AC_REFRESH = 0x0227, - HID_USAGE_CONSUMER_AC_BOOKMARKS = 0x022A, - - // Mouse Horizontal scroll - HID_USAGE_CONSUMER_AC_PAN = 0x0238, -}; - -/*-------------------------------------------------------------------- - * ASCII to KEYCODE Conversion - * Expand to array of [128][2] (shift, keycode) - * - * Usage: example to convert input chr into keyboard report (modifier + keycode) - * - * uint8_t const conv_table[128][2] = { HID_ASCII_TO_KEYCODE }; - * - * uint8_t keycode[6] = { 0 }; - * uint8_t modifier = 0; - * - * if ( conv_table[chr][0] ) modifier = KEYBOARD_MODIFIER_LEFTSHIFT; - * keycode[0] = conv_table[chr][1]; - * tud_hid_keyboard_report(report_id, modifier, keycode); - * - *--------------------------------------------------------------------*/ -#define HID_ASCII_TO_KEYCODE \ - {0, 0 }, /* 0x00 Null */ \ - {0, 0 }, /* 0x01 */ \ - {0, 0 }, /* 0x02 */ \ - {0, 0 }, /* 0x03 */ \ - {0, 0 }, /* 0x04 */ \ - {0, 0 }, /* 0x05 */ \ - {0, 0 }, /* 0x06 */ \ - {0, 0 }, /* 0x07 */ \ - {0, HID_KEY_BACKSPACE }, /* 0x08 Backspace */ \ - {0, HID_KEY_TAB }, /* 0x09 Tab */ \ - {0, HID_KEY_RETURN }, /* 0x0A Line Feed */ \ - {0, 0 }, /* 0x0B */ \ - {0, 0 }, /* 0x0C */ \ - {0, HID_KEY_RETURN }, /* 0x0D CR */ \ - {0, 0 }, /* 0x0E */ \ - {0, 0 }, /* 0x0F */ \ - {0, 0 }, /* 0x10 */ \ - {0, 0 }, /* 0x11 */ \ - {0, 0 }, /* 0x12 */ \ - {0, 0 }, /* 0x13 */ \ - {0, 0 }, /* 0x14 */ \ - {0, 0 }, /* 0x15 */ \ - {0, 0 }, /* 0x16 */ \ - {0, 0 }, /* 0x17 */ \ - {0, 0 }, /* 0x18 */ \ - {0, 0 }, /* 0x19 */ \ - {0, 0 }, /* 0x1A */ \ - {0, HID_KEY_ESCAPE }, /* 0x1B Escape */ \ - {0, 0 }, /* 0x1C */ \ - {0, 0 }, /* 0x1D */ \ - {0, 0 }, /* 0x1E */ \ - {0, 0 }, /* 0x1F */ \ - \ - {0, HID_KEY_SPACE }, /* 0x20 */ \ - {1, HID_KEY_1 }, /* 0x21 ! */ \ - {1, HID_KEY_APOSTROPHE }, /* 0x22 " */ \ - {1, HID_KEY_3 }, /* 0x23 # */ \ - {1, HID_KEY_4 }, /* 0x24 $ */ \ - {1, HID_KEY_5 }, /* 0x25 % */ \ - {1, HID_KEY_7 }, /* 0x26 & */ \ - {0, HID_KEY_APOSTROPHE }, /* 0x27 ' */ \ - {1, HID_KEY_9 }, /* 0x28 ( */ \ - {1, HID_KEY_0 }, /* 0x29 ) */ \ - {1, HID_KEY_8 }, /* 0x2A * */ \ - {1, HID_KEY_EQUAL }, /* 0x2B + */ \ - {0, HID_KEY_COMMA }, /* 0x2C , */ \ - {0, HID_KEY_MINUS }, /* 0x2D - */ \ - {0, HID_KEY_PERIOD }, /* 0x2E . */ \ - {0, HID_KEY_SLASH }, /* 0x2F / */ \ - {0, HID_KEY_0 }, /* 0x30 0 */ \ - {0, HID_KEY_1 }, /* 0x31 1 */ \ - {0, HID_KEY_2 }, /* 0x32 2 */ \ - {0, HID_KEY_3 }, /* 0x33 3 */ \ - {0, HID_KEY_4 }, /* 0x34 4 */ \ - {0, HID_KEY_5 }, /* 0x35 5 */ \ - {0, HID_KEY_6 }, /* 0x36 6 */ \ - {0, HID_KEY_7 }, /* 0x37 7 */ \ - {0, HID_KEY_8 }, /* 0x38 8 */ \ - {0, HID_KEY_9 }, /* 0x39 9 */ \ - {1, HID_KEY_SEMICOLON }, /* 0x3A : */ \ - {0, HID_KEY_SEMICOLON }, /* 0x3B ; */ \ - {1, HID_KEY_COMMA }, /* 0x3C < */ \ - {0, HID_KEY_EQUAL }, /* 0x3D = */ \ - {1, HID_KEY_PERIOD }, /* 0x3E > */ \ - {1, HID_KEY_SLASH }, /* 0x3F ? */ \ - \ - {1, HID_KEY_2 }, /* 0x40 @ */ \ - {1, HID_KEY_A }, /* 0x41 A */ \ - {1, HID_KEY_B }, /* 0x42 B */ \ - {1, HID_KEY_C }, /* 0x43 C */ \ - {1, HID_KEY_D }, /* 0x44 D */ \ - {1, HID_KEY_E }, /* 0x45 E */ \ - {1, HID_KEY_F }, /* 0x46 F */ \ - {1, HID_KEY_G }, /* 0x47 G */ \ - {1, HID_KEY_H }, /* 0x48 H */ \ - {1, HID_KEY_I }, /* 0x49 I */ \ - {1, HID_KEY_J }, /* 0x4A J */ \ - {1, HID_KEY_K }, /* 0x4B K */ \ - {1, HID_KEY_L }, /* 0x4C L */ \ - {1, HID_KEY_M }, /* 0x4D M */ \ - {1, HID_KEY_N }, /* 0x4E N */ \ - {1, HID_KEY_O }, /* 0x4F O */ \ - {1, HID_KEY_P }, /* 0x50 P */ \ - {1, HID_KEY_Q }, /* 0x51 Q */ \ - {1, HID_KEY_R }, /* 0x52 R */ \ - {1, HID_KEY_S }, /* 0x53 S */ \ - {1, HID_KEY_T }, /* 0x55 T */ \ - {1, HID_KEY_U }, /* 0x55 U */ \ - {1, HID_KEY_V }, /* 0x56 V */ \ - {1, HID_KEY_W }, /* 0x57 W */ \ - {1, HID_KEY_X }, /* 0x58 X */ \ - {1, HID_KEY_Y }, /* 0x59 Y */ \ - {1, HID_KEY_Z }, /* 0x5A Z */ \ - {0, HID_KEY_BRACKET_LEFT }, /* 0x5B [ */ \ - {0, HID_KEY_BACKSLASH }, /* 0x5C '\' */ \ - {0, HID_KEY_BRACKET_RIGHT }, /* 0x5D ] */ \ - {1, HID_KEY_6 }, /* 0x5E ^ */ \ - {1, HID_KEY_MINUS }, /* 0x5F _ */ \ - \ - {0, HID_KEY_GRAVE }, /* 0x60 ` */ \ - {0, HID_KEY_A }, /* 0x61 a */ \ - {0, HID_KEY_B }, /* 0x62 b */ \ - {0, HID_KEY_C }, /* 0x63 c */ \ - {0, HID_KEY_D }, /* 0x66 d */ \ - {0, HID_KEY_E }, /* 0x65 e */ \ - {0, HID_KEY_F }, /* 0x66 f */ \ - {0, HID_KEY_G }, /* 0x67 g */ \ - {0, HID_KEY_H }, /* 0x68 h */ \ - {0, HID_KEY_I }, /* 0x69 i */ \ - {0, HID_KEY_J }, /* 0x6A j */ \ - {0, HID_KEY_K }, /* 0x6B k */ \ - {0, HID_KEY_L }, /* 0x6C l */ \ - {0, HID_KEY_M }, /* 0x6D m */ \ - {0, HID_KEY_N }, /* 0x6E n */ \ - {0, HID_KEY_O }, /* 0x6F o */ \ - {0, HID_KEY_P }, /* 0x70 p */ \ - {0, HID_KEY_Q }, /* 0x71 q */ \ - {0, HID_KEY_R }, /* 0x72 r */ \ - {0, HID_KEY_S }, /* 0x73 s */ \ - {0, HID_KEY_T }, /* 0x75 t */ \ - {0, HID_KEY_U }, /* 0x75 u */ \ - {0, HID_KEY_V }, /* 0x76 v */ \ - {0, HID_KEY_W }, /* 0x77 w */ \ - {0, HID_KEY_X }, /* 0x78 x */ \ - {0, HID_KEY_Y }, /* 0x79 y */ \ - {0, HID_KEY_Z }, /* 0x7A z */ \ - {1, HID_KEY_BRACKET_LEFT }, /* 0x7B { */ \ - {1, HID_KEY_BACKSLASH }, /* 0x7C | */ \ - {1, HID_KEY_BRACKET_RIGHT }, /* 0x7D } */ \ - {1, HID_KEY_GRAVE }, /* 0x7E ~ */ \ - {0, HID_KEY_DELETE } /* 0x7F Delete */ \ - -/*-------------------------------------------------------------------- - * KEYCODE to Ascii Conversion - * Expand to array of [128][2] (ascii without shift, ascii with shift) - * - * Usage: example to convert ascii from keycode (key) and shift modifier (shift). - * Here we assume key < 128 ( printable ) - * - * uint8_t const conv_table[128][2] = { HID_KEYCODE_TO_ASCII }; - * char ch = shift ? conv_table[chr][1] : conv_table[chr][0]; - * - *--------------------------------------------------------------------*/ -#define HID_KEYCODE_TO_ASCII \ - {0 , 0 }, /* 0x00 */ \ - {0 , 0 }, /* 0x01 */ \ - {0 , 0 }, /* 0x02 */ \ - {0 , 0 }, /* 0x03 */ \ - {'a' , 'A' }, /* 0x04 */ \ - {'b' , 'B' }, /* 0x05 */ \ - {'c' , 'C' }, /* 0x06 */ \ - {'d' , 'D' }, /* 0x07 */ \ - {'e' , 'E' }, /* 0x08 */ \ - {'f' , 'F' }, /* 0x09 */ \ - {'g' , 'G' }, /* 0x0a */ \ - {'h' , 'H' }, /* 0x0b */ \ - {'i' , 'I' }, /* 0x0c */ \ - {'j' , 'J' }, /* 0x0d */ \ - {'k' , 'K' }, /* 0x0e */ \ - {'l' , 'L' }, /* 0x0f */ \ - {'m' , 'M' }, /* 0x10 */ \ - {'n' , 'N' }, /* 0x11 */ \ - {'o' , 'O' }, /* 0x12 */ \ - {'p' , 'P' }, /* 0x13 */ \ - {'q' , 'Q' }, /* 0x14 */ \ - {'r' , 'R' }, /* 0x15 */ \ - {'s' , 'S' }, /* 0x16 */ \ - {'t' , 'T' }, /* 0x17 */ \ - {'u' , 'U' }, /* 0x18 */ \ - {'v' , 'V' }, /* 0x19 */ \ - {'w' , 'W' }, /* 0x1a */ \ - {'x' , 'X' }, /* 0x1b */ \ - {'y' , 'Y' }, /* 0x1c */ \ - {'z' , 'Z' }, /* 0x1d */ \ - {'1' , '!' }, /* 0x1e */ \ - {'2' , '@' }, /* 0x1f */ \ - {'3' , '#' }, /* 0x20 */ \ - {'4' , '$' }, /* 0x21 */ \ - {'5' , '%' }, /* 0x22 */ \ - {'6' , '^' }, /* 0x23 */ \ - {'7' , '&' }, /* 0x24 */ \ - {'8' , '*' }, /* 0x25 */ \ - {'9' , '(' }, /* 0x26 */ \ - {'0' , ')' }, /* 0x27 */ \ - {'\r' , '\r' }, /* 0x28 */ \ - {'\x1b', '\x1b' }, /* 0x29 */ \ - {'\b' , '\b' }, /* 0x2a */ \ - {'\t' , '\t' }, /* 0x2b */ \ - {' ' , ' ' }, /* 0x2c */ \ - {'-' , '_' }, /* 0x2d */ \ - {'=' , '+' }, /* 0x2e */ \ - {'[' , '{' }, /* 0x2f */ \ - {']' , '}' }, /* 0x30 */ \ - {'\\' , '|' }, /* 0x31 */ \ - {'#' , '~' }, /* 0x32 */ \ - {';' , ':' }, /* 0x33 */ \ - {'\'' , '\"' }, /* 0x34 */ \ - {'`' , '~' }, /* 0x35 */ \ - {',' , '<' }, /* 0x36 */ \ - {'.' , '>' }, /* 0x37 */ \ - {'/' , '?' }, /* 0x38 */ \ - \ - {0 , 0 }, /* 0x39 */ \ - {0 , 0 }, /* 0x3a */ \ - {0 , 0 }, /* 0x3b */ \ - {0 , 0 }, /* 0x3c */ \ - {0 , 0 }, /* 0x3d */ \ - {0 , 0 }, /* 0x3e */ \ - {0 , 0 }, /* 0x3f */ \ - {0 , 0 }, /* 0x40 */ \ - {0 , 0 }, /* 0x41 */ \ - {0 , 0 }, /* 0x42 */ \ - {0 , 0 }, /* 0x43 */ \ - {0 , 0 }, /* 0x44 */ \ - {0 , 0 }, /* 0x45 */ \ - {0 , 0 }, /* 0x46 */ \ - {0 , 0 }, /* 0x47 */ \ - {0 , 0 }, /* 0x48 */ \ - {0 , 0 }, /* 0x49 */ \ - {0 , 0 }, /* 0x4a */ \ - {0 , 0 }, /* 0x4b */ \ - {0 , 0 }, /* 0x4c */ \ - {0 , 0 }, /* 0x4d */ \ - {0 , 0 }, /* 0x4e */ \ - {0 , 0 }, /* 0x4f */ \ - {0 , 0 }, /* 0x50 */ \ - {0 , 0 }, /* 0x51 */ \ - {0 , 0 }, /* 0x52 */ \ - {0 , 0 }, /* 0x53 */ \ - \ - {'/' , '/' }, /* 0x54 */ \ - {'*' , '*' }, /* 0x55 */ \ - {'-' , '-' }, /* 0x56 */ \ - {'+' , '+' }, /* 0x57 */ \ - {'\r' , '\r' }, /* 0x58 */ \ - {'1' , 0 }, /* 0x59 */ \ - {'2' , 0 }, /* 0x5a */ \ - {'3' , 0 }, /* 0x5b */ \ - {'4' , 0 }, /* 0x5c */ \ - {'5' , '5' }, /* 0x5d */ \ - {'6' , 0 }, /* 0x5e */ \ - {'7' , 0 }, /* 0x5f */ \ - {'8' , 0 }, /* 0x60 */ \ - {'9' , 0 }, /* 0x61 */ \ - {'0' , 0 }, /* 0x62 */ \ - {'0' , 0 }, /* 0x63 */ \ - {'=' , '=' }, /* 0x67 */ \ - - -#ifdef __cplusplus - } -#endif - -#endif /* _TUSB_HID_H__ */ - -/// @} +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +/** \ingroup group_class + * \defgroup ClassDriver_HID Human Interface Device (HID) + * @{ */ + +#ifndef _TUSB_HID_H_ +#define _TUSB_HID_H_ + +#include "common/tusb_common.h" + +#ifdef __cplusplus + extern "C" { +#endif + +//--------------------------------------------------------------------+ +// Common Definitions +//--------------------------------------------------------------------+ +/** \defgroup ClassDriver_HID_Common Common Definitions + * @{ */ + + /// USB HID Descriptor +typedef struct TU_ATTR_PACKED +{ + uint8_t bLength; /**< Numeric expression that is the total size of the HID descriptor */ + uint8_t bDescriptorType; /**< Constant name specifying type of HID descriptor. */ + + uint16_t bcdHID; /**< Numeric expression identifying the HID Class Specification release */ + uint8_t bCountryCode; /**< Numeric expression identifying country code of the localized hardware. */ + uint8_t bNumDescriptors; /**< Numeric expression specifying the number of class descriptors */ + + uint8_t bReportType; /**< Type of HID class report. */ + uint16_t wReportLength; /**< the total size of the Report descriptor. */ +} tusb_hid_descriptor_hid_t; + +/// HID Subclass +typedef enum +{ + HID_SUBCLASS_NONE = 0, ///< No Subclass + HID_SUBCLASS_BOOT = 1 ///< Boot Interface Subclass +}hid_subclass_type_t; + +/// HID Protocol +typedef enum +{ + HID_PROTOCOL_NONE = 0, ///< None + HID_PROTOCOL_KEYBOARD = 1, ///< Keyboard + HID_PROTOCOL_MOUSE = 2 ///< Mouse +}hid_protocol_type_t; + +/// HID Descriptor Type +typedef enum +{ + HID_DESC_TYPE_HID = 0x21, ///< HID Descriptor + HID_DESC_TYPE_REPORT = 0x22, ///< Report Descriptor + HID_DESC_TYPE_PHYSICAL = 0x23 ///< Physical Descriptor +}hid_descriptor_type_t; + +/// HID Request Report Type +typedef enum +{ + HID_REPORT_TYPE_INVALID = 0, + HID_REPORT_TYPE_INPUT, ///< Input + HID_REPORT_TYPE_OUTPUT, ///< Output + HID_REPORT_TYPE_FEATURE ///< Feature +}hid_report_type_t; + +/// HID Class Specific Control Request +typedef enum +{ + HID_REQ_CONTROL_GET_REPORT = 0x01, ///< Get Report + HID_REQ_CONTROL_GET_IDLE = 0x02, ///< Get Idle + HID_REQ_CONTROL_GET_PROTOCOL = 0x03, ///< Get Protocol + HID_REQ_CONTROL_SET_REPORT = 0x09, ///< Set Report + HID_REQ_CONTROL_SET_IDLE = 0x0a, ///< Set Idle + HID_REQ_CONTROL_SET_PROTOCOL = 0x0b ///< Set Protocol +}hid_request_type_t; + +/// HID Country Code +typedef enum +{ + HID_LOCAL_NotSupported = 0 , ///< NotSupported + HID_LOCAL_Arabic , ///< Arabic + HID_LOCAL_Belgian , ///< Belgian + HID_LOCAL_Canadian_Bilingual , ///< Canadian_Bilingual + HID_LOCAL_Canadian_French , ///< Canadian_French + HID_LOCAL_Czech_Republic , ///< Czech_Republic + HID_LOCAL_Danish , ///< Danish + HID_LOCAL_Finnish , ///< Finnish + HID_LOCAL_French , ///< French + HID_LOCAL_German , ///< German + HID_LOCAL_Greek , ///< Greek + HID_LOCAL_Hebrew , ///< Hebrew + HID_LOCAL_Hungary , ///< Hungary + HID_LOCAL_International , ///< International + HID_LOCAL_Italian , ///< Italian + HID_LOCAL_Japan_Katakana , ///< Japan_Katakana + HID_LOCAL_Korean , ///< Korean + HID_LOCAL_Latin_American , ///< Latin_American + HID_LOCAL_Netherlands_Dutch , ///< Netherlands/Dutch + HID_LOCAL_Norwegian , ///< Norwegian + HID_LOCAL_Persian_Farsi , ///< Persian (Farsi) + HID_LOCAL_Poland , ///< Poland + HID_LOCAL_Portuguese , ///< Portuguese + HID_LOCAL_Russia , ///< Russia + HID_LOCAL_Slovakia , ///< Slovakia + HID_LOCAL_Spanish , ///< Spanish + HID_LOCAL_Swedish , ///< Swedish + HID_LOCAL_Swiss_French , ///< Swiss/French + HID_LOCAL_Swiss_German , ///< Swiss/German + HID_LOCAL_Switzerland , ///< Switzerland + HID_LOCAL_Taiwan , ///< Taiwan + HID_LOCAL_Turkish_Q , ///< Turkish-Q + HID_LOCAL_UK , ///< UK + HID_LOCAL_US , ///< US + HID_LOCAL_Yugoslavia , ///< Yugoslavia + HID_LOCAL_Turkish_F ///< Turkish-F +} hid_country_code_t; + +/** @} */ + +//--------------------------------------------------------------------+ +// MOUSE +//--------------------------------------------------------------------+ +/** \addtogroup ClassDriver_HID_Mouse Mouse + * @{ */ + +/// Standard HID Boot Protocol Mouse Report. +typedef struct TU_ATTR_PACKED +{ + uint8_t buttons; /**< buttons mask for currently pressed buttons in the mouse. */ + int8_t x; /**< Current delta x movement of the mouse. */ + int8_t y; /**< Current delta y movement on the mouse. */ + int8_t wheel; /**< Current delta wheel movement on the mouse. */ + int8_t pan; // using AC Pan +} hid_mouse_report_t; + +/// Standard Mouse Buttons Bitmap +typedef enum +{ + MOUSE_BUTTON_LEFT = TU_BIT(0), ///< Left button + MOUSE_BUTTON_RIGHT = TU_BIT(1), ///< Right button + MOUSE_BUTTON_MIDDLE = TU_BIT(2), ///< Middle button + MOUSE_BUTTON_BACKWARD = TU_BIT(3), ///< Backward button, + MOUSE_BUTTON_FORWARD = TU_BIT(4), ///< Forward button, +}hid_mouse_button_bm_t; + +/// @} + +//--------------------------------------------------------------------+ +// Keyboard +//--------------------------------------------------------------------+ +/** \addtogroup ClassDriver_HID_Keyboard Keyboard + * @{ */ + +/// Standard HID Boot Protocol Keyboard Report. +typedef struct TU_ATTR_PACKED +{ + uint8_t modifier; /**< Keyboard modifier (KEYBOARD_MODIFIER_* masks). */ + uint8_t reserved; /**< Reserved for OEM use, always set to 0. */ + uint8_t keycode[6]; /**< Key codes of the currently pressed keys. */ +} hid_keyboard_report_t; + +/// Keyboard modifier codes bitmap +typedef enum +{ + KEYBOARD_MODIFIER_LEFTCTRL = TU_BIT(0), ///< Left Control + KEYBOARD_MODIFIER_LEFTSHIFT = TU_BIT(1), ///< Left Shift + KEYBOARD_MODIFIER_LEFTALT = TU_BIT(2), ///< Left Alt + KEYBOARD_MODIFIER_LEFTGUI = TU_BIT(3), ///< Left Window + KEYBOARD_MODIFIER_RIGHTCTRL = TU_BIT(4), ///< Right Control + KEYBOARD_MODIFIER_RIGHTSHIFT = TU_BIT(5), ///< Right Shift + KEYBOARD_MODIFIER_RIGHTALT = TU_BIT(6), ///< Right Alt + KEYBOARD_MODIFIER_RIGHTGUI = TU_BIT(7) ///< Right Window +}hid_keyboard_modifier_bm_t; + +typedef enum +{ + KEYBOARD_LED_NUMLOCK = TU_BIT(0), ///< Num Lock LED + KEYBOARD_LED_CAPSLOCK = TU_BIT(1), ///< Caps Lock LED + KEYBOARD_LED_SCROLLLOCK = TU_BIT(2), ///< Scroll Lock LED + KEYBOARD_LED_COMPOSE = TU_BIT(3), ///< Composition Mode + KEYBOARD_LED_KANA = TU_BIT(4) ///< Kana mode +}hid_keyboard_led_bm_t; + +/// @} + +//--------------------------------------------------------------------+ +// HID KEYCODE +//--------------------------------------------------------------------+ +#define HID_KEY_NONE 0x00 +#define HID_KEY_A 0x04 +#define HID_KEY_B 0x05 +#define HID_KEY_C 0x06 +#define HID_KEY_D 0x07 +#define HID_KEY_E 0x08 +#define HID_KEY_F 0x09 +#define HID_KEY_G 0x0A +#define HID_KEY_H 0x0B +#define HID_KEY_I 0x0C +#define HID_KEY_J 0x0D +#define HID_KEY_K 0x0E +#define HID_KEY_L 0x0F +#define HID_KEY_M 0x10 +#define HID_KEY_N 0x11 +#define HID_KEY_O 0x12 +#define HID_KEY_P 0x13 +#define HID_KEY_Q 0x14 +#define HID_KEY_R 0x15 +#define HID_KEY_S 0x16 +#define HID_KEY_T 0x17 +#define HID_KEY_U 0x18 +#define HID_KEY_V 0x19 +#define HID_KEY_W 0x1A +#define HID_KEY_X 0x1B +#define HID_KEY_Y 0x1C +#define HID_KEY_Z 0x1D +#define HID_KEY_1 0x1E +#define HID_KEY_2 0x1F +#define HID_KEY_3 0x20 +#define HID_KEY_4 0x21 +#define HID_KEY_5 0x22 +#define HID_KEY_6 0x23 +#define HID_KEY_7 0x24 +#define HID_KEY_8 0x25 +#define HID_KEY_9 0x26 +#define HID_KEY_0 0x27 +#define HID_KEY_RETURN 0x28 +#define HID_KEY_ESCAPE 0x29 +#define HID_KEY_BACKSPACE 0x2A +#define HID_KEY_TAB 0x2B +#define HID_KEY_SPACE 0x2C +#define HID_KEY_MINUS 0x2D +#define HID_KEY_EQUAL 0x2E +#define HID_KEY_BRACKET_LEFT 0x2F +#define HID_KEY_BRACKET_RIGHT 0x30 +#define HID_KEY_BACKSLASH 0x31 +#define HID_KEY_EUROPE_1 0x32 +#define HID_KEY_SEMICOLON 0x33 +#define HID_KEY_APOSTROPHE 0x34 +#define HID_KEY_GRAVE 0x35 +#define HID_KEY_COMMA 0x36 +#define HID_KEY_PERIOD 0x37 +#define HID_KEY_SLASH 0x38 +#define HID_KEY_CAPS_LOCK 0x39 +#define HID_KEY_F1 0x3A +#define HID_KEY_F2 0x3B +#define HID_KEY_F3 0x3C +#define HID_KEY_F4 0x3D +#define HID_KEY_F5 0x3E +#define HID_KEY_F6 0x3F +#define HID_KEY_F7 0x40 +#define HID_KEY_F8 0x41 +#define HID_KEY_F9 0x42 +#define HID_KEY_F10 0x43 +#define HID_KEY_F11 0x44 +#define HID_KEY_F12 0x45 +#define HID_KEY_PRINT_SCREEN 0x46 +#define HID_KEY_SCROLL_LOCK 0x47 +#define HID_KEY_PAUSE 0x48 +#define HID_KEY_INSERT 0x49 +#define HID_KEY_HOME 0x4A +#define HID_KEY_PAGE_UP 0x4B +#define HID_KEY_DELETE 0x4C +#define HID_KEY_END 0x4D +#define HID_KEY_PAGE_DOWN 0x4E +#define HID_KEY_ARROW_RIGHT 0x4F +#define HID_KEY_ARROW_LEFT 0x50 +#define HID_KEY_ARROW_DOWN 0x51 +#define HID_KEY_ARROW_UP 0x52 +#define HID_KEY_NUM_LOCK 0x53 +#define HID_KEY_KEYPAD_DIVIDE 0x54 +#define HID_KEY_KEYPAD_MULTIPLY 0x55 +#define HID_KEY_KEYPAD_SUBTRACT 0x56 +#define HID_KEY_KEYPAD_ADD 0x57 +#define HID_KEY_KEYPAD_ENTER 0x58 +#define HID_KEY_KEYPAD_1 0x59 +#define HID_KEY_KEYPAD_2 0x5A +#define HID_KEY_KEYPAD_3 0x5B +#define HID_KEY_KEYPAD_4 0x5C +#define HID_KEY_KEYPAD_5 0x5D +#define HID_KEY_KEYPAD_6 0x5E +#define HID_KEY_KEYPAD_7 0x5F +#define HID_KEY_KEYPAD_8 0x60 +#define HID_KEY_KEYPAD_9 0x61 +#define HID_KEY_KEYPAD_0 0x62 +#define HID_KEY_KEYPAD_DECIMAL 0x63 +#define HID_KEY_EUROPE_2 0x64 +#define HID_KEY_APPLICATION 0x65 +#define HID_KEY_POWER 0x66 +#define HID_KEY_KEYPAD_EQUAL 0x67 +#define HID_KEY_F13 0x68 +#define HID_KEY_F14 0x69 +#define HID_KEY_F15 0x6A +#define HID_KEY_CONTROL_LEFT 0xE0 +#define HID_KEY_SHIFT_LEFT 0xE1 +#define HID_KEY_ALT_LEFT 0xE2 +#define HID_KEY_GUI_LEFT 0xE3 +#define HID_KEY_CONTROL_RIGHT 0xE4 +#define HID_KEY_SHIFT_RIGHT 0xE5 +#define HID_KEY_ALT_RIGHT 0xE6 +#define HID_KEY_GUI_RIGHT 0xE7 + + +//--------------------------------------------------------------------+ +// REPORT DESCRIPTOR +//--------------------------------------------------------------------+ +//------------- ITEM & TAG -------------// +#define HID_REPORT_DATA_0(data) +#define HID_REPORT_DATA_1(data) , data +#define HID_REPORT_DATA_2(data) , U16_TO_U8S_LE(data) +#define HID_REPORT_DATA_3(data) , U32_TO_U8S_LE(data) + +#define HID_REPORT_ITEM(data, tag, type, size) \ + (((tag) << 4) | ((type) << 2) | (size)) HID_REPORT_DATA_##size(data) + +#define RI_TYPE_MAIN 0 +#define RI_TYPE_GLOBAL 1 +#define RI_TYPE_LOCAL 2 + +//------------- MAIN ITEMS 6.2.2.4 -------------// +#define HID_INPUT(x) HID_REPORT_ITEM(x, 8, RI_TYPE_MAIN, 1) +#define HID_OUTPUT(x) HID_REPORT_ITEM(x, 9, RI_TYPE_MAIN, 1) +#define HID_COLLECTION(x) HID_REPORT_ITEM(x, 10, RI_TYPE_MAIN, 1) +#define HID_FEATURE(x) HID_REPORT_ITEM(x, 11, RI_TYPE_MAIN, 1) +#define HID_COLLECTION_END HID_REPORT_ITEM(x, 12, RI_TYPE_MAIN, 0) + +//------------- INPUT, OUTPUT, FEATURE 6.2.2.5 -------------// +#define HID_DATA (0<<0) +#define HID_CONSTANT (1<<0) + +#define HID_ARRAY (0<<1) +#define HID_VARIABLE (1<<1) + +#define HID_ABSOLUTE (0<<2) +#define HID_RELATIVE (1<<2) + +#define HID_WRAP_NO (0<<3) +#define HID_WRAP (1<<3) + +#define HID_LINEAR (0<<4) +#define HID_NONLINEAR (1<<4) + +#define HID_PREFERRED_STATE (0<<5) +#define HID_PREFERRED_NO (1<<5) + +#define HID_NO_NULL_POSITION (0<<6) +#define HID_NULL_STATE (1<<6) + +#define HID_NON_VOLATILE (0<<7) +#define HID_VOLATILE (1<<7) + +#define HID_BITFIELD (0<<8) +#define HID_BUFFERED_BYTES (1<<8) + +//------------- COLLECTION ITEM 6.2.2.6 -------------// +enum { + HID_COLLECTION_PHYSICAL = 0, + HID_COLLECTION_APPLICATION, + HID_COLLECTION_LOGICAL, + HID_COLLECTION_REPORT, + HID_COLLECTION_NAMED_ARRAY, + HID_COLLECTION_USAGE_SWITCH, + HID_COLLECTION_USAGE_MODIFIER +}; + +//------------- GLOBAL ITEMS 6.2.2.7 -------------// +#define HID_USAGE_PAGE(x) HID_REPORT_ITEM(x, 0, RI_TYPE_GLOBAL, 1) +#define HID_USAGE_PAGE_N(x, n) HID_REPORT_ITEM(x, 0, RI_TYPE_GLOBAL, n) + +#define HID_LOGICAL_MIN(x) HID_REPORT_ITEM(x, 1, RI_TYPE_GLOBAL, 1) +#define HID_LOGICAL_MIN_N(x, n) HID_REPORT_ITEM(x, 1, RI_TYPE_GLOBAL, n) + +#define HID_LOGICAL_MAX(x) HID_REPORT_ITEM(x, 2, RI_TYPE_GLOBAL, 1) +#define HID_LOGICAL_MAX_N(x, n) HID_REPORT_ITEM(x, 2, RI_TYPE_GLOBAL, n) + +#define HID_PHYSICAL_MIN(x) HID_REPORT_ITEM(x, 3, RI_TYPE_GLOBAL, 1) +#define HID_PHYSICAL_MIN_N(x, n) HID_REPORT_ITEM(x, 3, RI_TYPE_GLOBAL, n) + +#define HID_PHYSICAL_MAX(x) HID_REPORT_ITEM(x, 4, RI_TYPE_GLOBAL, 1) +#define HID_PHYSICAL_MAX_N(x, n) HID_REPORT_ITEM(x, 4, RI_TYPE_GLOBAL, n) + +#define HID_UNIT_EXPONENT(x) HID_REPORT_ITEM(x, 5, RI_TYPE_GLOBAL, 1) +#define HID_UNIT_EXPONENT_N(x, n) HID_REPORT_ITEM(x, 5, RI_TYPE_GLOBAL, n) + +#define HID_UNIT(x) HID_REPORT_ITEM(x, 6, RI_TYPE_GLOBAL, 1) +#define HID_UNIT_N(x, n) HID_REPORT_ITEM(x, 6, RI_TYPE_GLOBAL, n) + +#define HID_REPORT_SIZE(x) HID_REPORT_ITEM(x, 7, RI_TYPE_GLOBAL, 1) +#define HID_REPORT_SIZE_N(x, n) HID_REPORT_ITEM(x, 7, RI_TYPE_GLOBAL, n) + +#define HID_REPORT_ID(x) HID_REPORT_ITEM(x, 8, RI_TYPE_GLOBAL, 1) +#define HID_REPORT_ID_N(x) HID_REPORT_ITEM(x, 8, RI_TYPE_GLOBAL, n) + +#define HID_REPORT_COUNT(x) HID_REPORT_ITEM(x, 9, RI_TYPE_GLOBAL, 1) +#define HID_REPORT_COUNT_N(x, n) HID_REPORT_ITEM(x, 9, RI_TYPE_GLOBAL, n) + +#define HID_PUSH HID_REPORT_ITEM(x, 10, RI_TYPE_GLOBAL, 0) +#define HID_POP HID_REPORT_ITEM(x, 11, RI_TYPE_GLOBAL, 0) + +//------------- LOCAL ITEMS 6.2.2.8 -------------// +#define HID_USAGE(x) HID_REPORT_ITEM(x, 0, RI_TYPE_LOCAL, 1) +#define HID_USAGE_N(x, n) HID_REPORT_ITEM(x, 0, RI_TYPE_LOCAL, n) + +#define HID_USAGE_MIN(x) HID_REPORT_ITEM(x, 1, RI_TYPE_LOCAL, 1) +#define HID_USAGE_MIN_N(x, n) HID_REPORT_ITEM(x, 1, RI_TYPE_LOCAL, n) + +#define HID_USAGE_MAX(x) HID_REPORT_ITEM(x, 2, RI_TYPE_LOCAL, 1) +#define HID_USAGE_MAX_N(x, n) HID_REPORT_ITEM(x, 2, RI_TYPE_LOCAL, n) + +//--------------------------------------------------------------------+ +// Usage Table +//--------------------------------------------------------------------+ + +/// HID Usage Table - Table 1: Usage Page Summary +enum { + HID_USAGE_PAGE_DESKTOP = 0x01, + HID_USAGE_PAGE_SIMULATE = 0x02, + HID_USAGE_PAGE_VIRTUAL_REALITY = 0x03, + HID_USAGE_PAGE_SPORT = 0x04, + HID_USAGE_PAGE_GAME = 0x05, + HID_USAGE_PAGE_GENERIC_DEVICE = 0x06, + HID_USAGE_PAGE_KEYBOARD = 0x07, + HID_USAGE_PAGE_LED = 0x08, + HID_USAGE_PAGE_BUTTON = 0x09, + HID_USAGE_PAGE_ORDINAL = 0x0a, + HID_USAGE_PAGE_TELEPHONY = 0x0b, + HID_USAGE_PAGE_CONSUMER = 0x0c, + HID_USAGE_PAGE_DIGITIZER = 0x0d, + HID_USAGE_PAGE_PID = 0x0f, + HID_USAGE_PAGE_UNICODE = 0x10, + HID_USAGE_PAGE_ALPHA_DISPLAY = 0x14, + HID_USAGE_PAGE_MEDICAL = 0x40, + HID_USAGE_PAGE_MONITOR = 0x80, //0x80 - 0x83 + HID_USAGE_PAGE_POWER = 0x84, // 0x084 - 0x87 + HID_USAGE_PAGE_BARCODE_SCANNER = 0x8c, + HID_USAGE_PAGE_SCALE = 0x8d, + HID_USAGE_PAGE_MSR = 0x8e, + HID_USAGE_PAGE_CAMERA = 0x90, + HID_USAGE_PAGE_ARCADE = 0x91, + HID_USAGE_PAGE_VENDOR = 0xFF00 // 0xFF00 - 0xFFFF +}; + +/// HID Usage Table - Table 6: Generic Desktop Page +enum { + HID_USAGE_DESKTOP_POINTER = 0x01, + HID_USAGE_DESKTOP_MOUSE = 0x02, + HID_USAGE_DESKTOP_JOYSTICK = 0x04, + HID_USAGE_DESKTOP_GAMEPAD = 0x05, + HID_USAGE_DESKTOP_KEYBOARD = 0x06, + HID_USAGE_DESKTOP_KEYPAD = 0x07, + HID_USAGE_DESKTOP_MULTI_AXIS_CONTROLLER = 0x08, + HID_USAGE_DESKTOP_TABLET_PC_SYSTEM = 0x09, + HID_USAGE_DESKTOP_X = 0x30, + HID_USAGE_DESKTOP_Y = 0x31, + HID_USAGE_DESKTOP_Z = 0x32, + HID_USAGE_DESKTOP_RX = 0x33, + HID_USAGE_DESKTOP_RY = 0x34, + HID_USAGE_DESKTOP_RZ = 0x35, + HID_USAGE_DESKTOP_SLIDER = 0x36, + HID_USAGE_DESKTOP_DIAL = 0x37, + HID_USAGE_DESKTOP_WHEEL = 0x38, + HID_USAGE_DESKTOP_HAT_SWITCH = 0x39, + HID_USAGE_DESKTOP_COUNTED_BUFFER = 0x3a, + HID_USAGE_DESKTOP_BYTE_COUNT = 0x3b, + HID_USAGE_DESKTOP_MOTION_WAKEUP = 0x3c, + HID_USAGE_DESKTOP_START = 0x3d, + HID_USAGE_DESKTOP_SELECT = 0x3e, + HID_USAGE_DESKTOP_VX = 0x40, + HID_USAGE_DESKTOP_VY = 0x41, + HID_USAGE_DESKTOP_VZ = 0x42, + HID_USAGE_DESKTOP_VBRX = 0x43, + HID_USAGE_DESKTOP_VBRY = 0x44, + HID_USAGE_DESKTOP_VBRZ = 0x45, + HID_USAGE_DESKTOP_VNO = 0x46, + HID_USAGE_DESKTOP_FEATURE_NOTIFICATION = 0x47, + HID_USAGE_DESKTOP_RESOLUTION_MULTIPLIER = 0x48, + HID_USAGE_DESKTOP_SYSTEM_CONTROL = 0x80, + HID_USAGE_DESKTOP_SYSTEM_POWER_DOWN = 0x81, + HID_USAGE_DESKTOP_SYSTEM_SLEEP = 0x82, + HID_USAGE_DESKTOP_SYSTEM_WAKE_UP = 0x83, + HID_USAGE_DESKTOP_SYSTEM_CONTEXT_MENU = 0x84, + HID_USAGE_DESKTOP_SYSTEM_MAIN_MENU = 0x85, + HID_USAGE_DESKTOP_SYSTEM_APP_MENU = 0x86, + HID_USAGE_DESKTOP_SYSTEM_MENU_HELP = 0x87, + HID_USAGE_DESKTOP_SYSTEM_MENU_EXIT = 0x88, + HID_USAGE_DESKTOP_SYSTEM_MENU_SELECT = 0x89, + HID_USAGE_DESKTOP_SYSTEM_MENU_RIGHT = 0x8A, + HID_USAGE_DESKTOP_SYSTEM_MENU_LEFT = 0x8B, + HID_USAGE_DESKTOP_SYSTEM_MENU_UP = 0x8C, + HID_USAGE_DESKTOP_SYSTEM_MENU_DOWN = 0x8D, + HID_USAGE_DESKTOP_SYSTEM_COLD_RESTART = 0x8E, + HID_USAGE_DESKTOP_SYSTEM_WARM_RESTART = 0x8F, + HID_USAGE_DESKTOP_DPAD_UP = 0x90, + HID_USAGE_DESKTOP_DPAD_DOWN = 0x91, + HID_USAGE_DESKTOP_DPAD_RIGHT = 0x92, + HID_USAGE_DESKTOP_DPAD_LEFT = 0x93, + HID_USAGE_DESKTOP_SYSTEM_DOCK = 0xA0, + HID_USAGE_DESKTOP_SYSTEM_UNDOCK = 0xA1, + HID_USAGE_DESKTOP_SYSTEM_SETUP = 0xA2, + HID_USAGE_DESKTOP_SYSTEM_BREAK = 0xA3, + HID_USAGE_DESKTOP_SYSTEM_DEBUGGER_BREAK = 0xA4, + HID_USAGE_DESKTOP_APPLICATION_BREAK = 0xA5, + HID_USAGE_DESKTOP_APPLICATION_DEBUGGER_BREAK = 0xA6, + HID_USAGE_DESKTOP_SYSTEM_SPEAKER_MUTE = 0xA7, + HID_USAGE_DESKTOP_SYSTEM_HIBERNATE = 0xA8, + HID_USAGE_DESKTOP_SYSTEM_DISPLAY_INVERT = 0xB0, + HID_USAGE_DESKTOP_SYSTEM_DISPLAY_INTERNAL = 0xB1, + HID_USAGE_DESKTOP_SYSTEM_DISPLAY_EXTERNAL = 0xB2, + HID_USAGE_DESKTOP_SYSTEM_DISPLAY_BOTH = 0xB3, + HID_USAGE_DESKTOP_SYSTEM_DISPLAY_DUAL = 0xB4, + HID_USAGE_DESKTOP_SYSTEM_DISPLAY_TOGGLE_INT_EXT = 0xB5, + HID_USAGE_DESKTOP_SYSTEM_DISPLAY_SWAP_PRIMARY_SECONDARY = 0xB6, + HID_USAGE_DESKTOP_SYSTEM_DISPLAY_LCD_AUTOSCALE = 0xB7 +}; + + +/// HID Usage Table: Consumer Page (0x0C) +/// Only contains controls that supported by Windows (whole list is too long) +enum +{ + // Generic Control + HID_USAGE_CONSUMER_CONTROL = 0x0001, + + // Power Control + HID_USAGE_CONSUMER_POWER = 0x0030, + HID_USAGE_CONSUMER_RESET = 0x0031, + HID_USAGE_CONSUMER_SLEEP = 0x0032, + + // Screen Brightness + HID_USAGE_CONSUMER_BRIGHTNESS_INCREMENT = 0x006F, + HID_USAGE_CONSUMER_BRIGHTNESS_DECREMENT = 0x0070, + + // These HID usages operate only on mobile systems (battery powered) and + // require Windows 8 (build 8302 or greater). + HID_USAGE_CONSUMER_WIRELESS_RADIO_CONTROLS = 0x000C, + HID_USAGE_CONSUMER_WIRELESS_RADIO_BUTTONS = 0x00C6, + HID_USAGE_CONSUMER_WIRELESS_RADIO_LED = 0x00C7, + HID_USAGE_CONSUMER_WIRELESS_RADIO_SLIDER_SWITCH = 0x00C8, + + // Media Control + HID_USAGE_CONSUMER_PLAY_PAUSE = 0x00CD, + HID_USAGE_CONSUMER_SCAN_NEXT = 0x00B5, + HID_USAGE_CONSUMER_SCAN_PREVIOUS = 0x00B6, + HID_USAGE_CONSUMER_STOP = 0x00B7, + HID_USAGE_CONSUMER_VOLUME = 0x00E0, + HID_USAGE_CONSUMER_MUTE = 0x00E2, + HID_USAGE_CONSUMER_BASS = 0x00E3, + HID_USAGE_CONSUMER_TREBLE = 0x00E4, + HID_USAGE_CONSUMER_BASS_BOOST = 0x00E5, + HID_USAGE_CONSUMER_VOLUME_INCREMENT = 0x00E9, + HID_USAGE_CONSUMER_VOLUME_DECREMENT = 0x00EA, + HID_USAGE_CONSUMER_BASS_INCREMENT = 0x0152, + HID_USAGE_CONSUMER_BASS_DECREMENT = 0x0153, + HID_USAGE_CONSUMER_TREBLE_INCREMENT = 0x0154, + HID_USAGE_CONSUMER_TREBLE_DECREMENT = 0x0155, + + // Application Launcher + HID_USAGE_CONSUMER_AL_CONSUMER_CONTROL_CONFIGURATION = 0x0183, + HID_USAGE_CONSUMER_AL_EMAIL_READER = 0x018A, + HID_USAGE_CONSUMER_AL_CALCULATOR = 0x0192, + HID_USAGE_CONSUMER_AL_LOCAL_BROWSER = 0x0194, + + // Browser/Explorer Specific + HID_USAGE_CONSUMER_AC_SEARCH = 0x0221, + HID_USAGE_CONSUMER_AC_HOME = 0x0223, + HID_USAGE_CONSUMER_AC_BACK = 0x0224, + HID_USAGE_CONSUMER_AC_FORWARD = 0x0225, + HID_USAGE_CONSUMER_AC_STOP = 0x0226, + HID_USAGE_CONSUMER_AC_REFRESH = 0x0227, + HID_USAGE_CONSUMER_AC_BOOKMARKS = 0x022A, + + // Mouse Horizontal scroll + HID_USAGE_CONSUMER_AC_PAN = 0x0238, +}; + +/*-------------------------------------------------------------------- + * ASCII to KEYCODE Conversion + * Expand to array of [128][2] (shift, keycode) + * + * Usage: example to convert input chr into keyboard report (modifier + keycode) + * + * uint8_t const conv_table[128][2] = { HID_ASCII_TO_KEYCODE }; + * + * uint8_t keycode[6] = { 0 }; + * uint8_t modifier = 0; + * + * if ( conv_table[chr][0] ) modifier = KEYBOARD_MODIFIER_LEFTSHIFT; + * keycode[0] = conv_table[chr][1]; + * tud_hid_keyboard_report(report_id, modifier, keycode); + * + *--------------------------------------------------------------------*/ +#define HID_ASCII_TO_KEYCODE \ + {0, 0 }, /* 0x00 Null */ \ + {0, 0 }, /* 0x01 */ \ + {0, 0 }, /* 0x02 */ \ + {0, 0 }, /* 0x03 */ \ + {0, 0 }, /* 0x04 */ \ + {0, 0 }, /* 0x05 */ \ + {0, 0 }, /* 0x06 */ \ + {0, 0 }, /* 0x07 */ \ + {0, HID_KEY_BACKSPACE }, /* 0x08 Backspace */ \ + {0, HID_KEY_TAB }, /* 0x09 Tab */ \ + {0, HID_KEY_RETURN }, /* 0x0A Line Feed */ \ + {0, 0 }, /* 0x0B */ \ + {0, 0 }, /* 0x0C */ \ + {0, HID_KEY_RETURN }, /* 0x0D CR */ \ + {0, 0 }, /* 0x0E */ \ + {0, 0 }, /* 0x0F */ \ + {0, 0 }, /* 0x10 */ \ + {0, 0 }, /* 0x11 */ \ + {0, 0 }, /* 0x12 */ \ + {0, 0 }, /* 0x13 */ \ + {0, 0 }, /* 0x14 */ \ + {0, 0 }, /* 0x15 */ \ + {0, 0 }, /* 0x16 */ \ + {0, 0 }, /* 0x17 */ \ + {0, 0 }, /* 0x18 */ \ + {0, 0 }, /* 0x19 */ \ + {0, 0 }, /* 0x1A */ \ + {0, HID_KEY_ESCAPE }, /* 0x1B Escape */ \ + {0, 0 }, /* 0x1C */ \ + {0, 0 }, /* 0x1D */ \ + {0, 0 }, /* 0x1E */ \ + {0, 0 }, /* 0x1F */ \ + \ + {0, HID_KEY_SPACE }, /* 0x20 */ \ + {1, HID_KEY_1 }, /* 0x21 ! */ \ + {1, HID_KEY_APOSTROPHE }, /* 0x22 " */ \ + {1, HID_KEY_3 }, /* 0x23 # */ \ + {1, HID_KEY_4 }, /* 0x24 $ */ \ + {1, HID_KEY_5 }, /* 0x25 % */ \ + {1, HID_KEY_7 }, /* 0x26 & */ \ + {0, HID_KEY_APOSTROPHE }, /* 0x27 ' */ \ + {1, HID_KEY_9 }, /* 0x28 ( */ \ + {1, HID_KEY_0 }, /* 0x29 ) */ \ + {1, HID_KEY_8 }, /* 0x2A * */ \ + {1, HID_KEY_EQUAL }, /* 0x2B + */ \ + {0, HID_KEY_COMMA }, /* 0x2C , */ \ + {0, HID_KEY_MINUS }, /* 0x2D - */ \ + {0, HID_KEY_PERIOD }, /* 0x2E . */ \ + {0, HID_KEY_SLASH }, /* 0x2F / */ \ + {0, HID_KEY_0 }, /* 0x30 0 */ \ + {0, HID_KEY_1 }, /* 0x31 1 */ \ + {0, HID_KEY_2 }, /* 0x32 2 */ \ + {0, HID_KEY_3 }, /* 0x33 3 */ \ + {0, HID_KEY_4 }, /* 0x34 4 */ \ + {0, HID_KEY_5 }, /* 0x35 5 */ \ + {0, HID_KEY_6 }, /* 0x36 6 */ \ + {0, HID_KEY_7 }, /* 0x37 7 */ \ + {0, HID_KEY_8 }, /* 0x38 8 */ \ + {0, HID_KEY_9 }, /* 0x39 9 */ \ + {1, HID_KEY_SEMICOLON }, /* 0x3A : */ \ + {0, HID_KEY_SEMICOLON }, /* 0x3B ; */ \ + {1, HID_KEY_COMMA }, /* 0x3C < */ \ + {0, HID_KEY_EQUAL }, /* 0x3D = */ \ + {1, HID_KEY_PERIOD }, /* 0x3E > */ \ + {1, HID_KEY_SLASH }, /* 0x3F ? */ \ + \ + {1, HID_KEY_2 }, /* 0x40 @ */ \ + {1, HID_KEY_A }, /* 0x41 A */ \ + {1, HID_KEY_B }, /* 0x42 B */ \ + {1, HID_KEY_C }, /* 0x43 C */ \ + {1, HID_KEY_D }, /* 0x44 D */ \ + {1, HID_KEY_E }, /* 0x45 E */ \ + {1, HID_KEY_F }, /* 0x46 F */ \ + {1, HID_KEY_G }, /* 0x47 G */ \ + {1, HID_KEY_H }, /* 0x48 H */ \ + {1, HID_KEY_I }, /* 0x49 I */ \ + {1, HID_KEY_J }, /* 0x4A J */ \ + {1, HID_KEY_K }, /* 0x4B K */ \ + {1, HID_KEY_L }, /* 0x4C L */ \ + {1, HID_KEY_M }, /* 0x4D M */ \ + {1, HID_KEY_N }, /* 0x4E N */ \ + {1, HID_KEY_O }, /* 0x4F O */ \ + {1, HID_KEY_P }, /* 0x50 P */ \ + {1, HID_KEY_Q }, /* 0x51 Q */ \ + {1, HID_KEY_R }, /* 0x52 R */ \ + {1, HID_KEY_S }, /* 0x53 S */ \ + {1, HID_KEY_T }, /* 0x55 T */ \ + {1, HID_KEY_U }, /* 0x55 U */ \ + {1, HID_KEY_V }, /* 0x56 V */ \ + {1, HID_KEY_W }, /* 0x57 W */ \ + {1, HID_KEY_X }, /* 0x58 X */ \ + {1, HID_KEY_Y }, /* 0x59 Y */ \ + {1, HID_KEY_Z }, /* 0x5A Z */ \ + {0, HID_KEY_BRACKET_LEFT }, /* 0x5B [ */ \ + {0, HID_KEY_BACKSLASH }, /* 0x5C '\' */ \ + {0, HID_KEY_BRACKET_RIGHT }, /* 0x5D ] */ \ + {1, HID_KEY_6 }, /* 0x5E ^ */ \ + {1, HID_KEY_MINUS }, /* 0x5F _ */ \ + \ + {0, HID_KEY_GRAVE }, /* 0x60 ` */ \ + {0, HID_KEY_A }, /* 0x61 a */ \ + {0, HID_KEY_B }, /* 0x62 b */ \ + {0, HID_KEY_C }, /* 0x63 c */ \ + {0, HID_KEY_D }, /* 0x66 d */ \ + {0, HID_KEY_E }, /* 0x65 e */ \ + {0, HID_KEY_F }, /* 0x66 f */ \ + {0, HID_KEY_G }, /* 0x67 g */ \ + {0, HID_KEY_H }, /* 0x68 h */ \ + {0, HID_KEY_I }, /* 0x69 i */ \ + {0, HID_KEY_J }, /* 0x6A j */ \ + {0, HID_KEY_K }, /* 0x6B k */ \ + {0, HID_KEY_L }, /* 0x6C l */ \ + {0, HID_KEY_M }, /* 0x6D m */ \ + {0, HID_KEY_N }, /* 0x6E n */ \ + {0, HID_KEY_O }, /* 0x6F o */ \ + {0, HID_KEY_P }, /* 0x70 p */ \ + {0, HID_KEY_Q }, /* 0x71 q */ \ + {0, HID_KEY_R }, /* 0x72 r */ \ + {0, HID_KEY_S }, /* 0x73 s */ \ + {0, HID_KEY_T }, /* 0x75 t */ \ + {0, HID_KEY_U }, /* 0x75 u */ \ + {0, HID_KEY_V }, /* 0x76 v */ \ + {0, HID_KEY_W }, /* 0x77 w */ \ + {0, HID_KEY_X }, /* 0x78 x */ \ + {0, HID_KEY_Y }, /* 0x79 y */ \ + {0, HID_KEY_Z }, /* 0x7A z */ \ + {1, HID_KEY_BRACKET_LEFT }, /* 0x7B { */ \ + {1, HID_KEY_BACKSLASH }, /* 0x7C | */ \ + {1, HID_KEY_BRACKET_RIGHT }, /* 0x7D } */ \ + {1, HID_KEY_GRAVE }, /* 0x7E ~ */ \ + {0, HID_KEY_DELETE } /* 0x7F Delete */ \ + +/*-------------------------------------------------------------------- + * KEYCODE to Ascii Conversion + * Expand to array of [128][2] (ascii without shift, ascii with shift) + * + * Usage: example to convert ascii from keycode (key) and shift modifier (shift). + * Here we assume key < 128 ( printable ) + * + * uint8_t const conv_table[128][2] = { HID_KEYCODE_TO_ASCII }; + * char ch = shift ? conv_table[chr][1] : conv_table[chr][0]; + * + *--------------------------------------------------------------------*/ +#define HID_KEYCODE_TO_ASCII \ + {0 , 0 }, /* 0x00 */ \ + {0 , 0 }, /* 0x01 */ \ + {0 , 0 }, /* 0x02 */ \ + {0 , 0 }, /* 0x03 */ \ + {'a' , 'A' }, /* 0x04 */ \ + {'b' , 'B' }, /* 0x05 */ \ + {'c' , 'C' }, /* 0x06 */ \ + {'d' , 'D' }, /* 0x07 */ \ + {'e' , 'E' }, /* 0x08 */ \ + {'f' , 'F' }, /* 0x09 */ \ + {'g' , 'G' }, /* 0x0a */ \ + {'h' , 'H' }, /* 0x0b */ \ + {'i' , 'I' }, /* 0x0c */ \ + {'j' , 'J' }, /* 0x0d */ \ + {'k' , 'K' }, /* 0x0e */ \ + {'l' , 'L' }, /* 0x0f */ \ + {'m' , 'M' }, /* 0x10 */ \ + {'n' , 'N' }, /* 0x11 */ \ + {'o' , 'O' }, /* 0x12 */ \ + {'p' , 'P' }, /* 0x13 */ \ + {'q' , 'Q' }, /* 0x14 */ \ + {'r' , 'R' }, /* 0x15 */ \ + {'s' , 'S' }, /* 0x16 */ \ + {'t' , 'T' }, /* 0x17 */ \ + {'u' , 'U' }, /* 0x18 */ \ + {'v' , 'V' }, /* 0x19 */ \ + {'w' , 'W' }, /* 0x1a */ \ + {'x' , 'X' }, /* 0x1b */ \ + {'y' , 'Y' }, /* 0x1c */ \ + {'z' , 'Z' }, /* 0x1d */ \ + {'1' , '!' }, /* 0x1e */ \ + {'2' , '@' }, /* 0x1f */ \ + {'3' , '#' }, /* 0x20 */ \ + {'4' , '$' }, /* 0x21 */ \ + {'5' , '%' }, /* 0x22 */ \ + {'6' , '^' }, /* 0x23 */ \ + {'7' , '&' }, /* 0x24 */ \ + {'8' , '*' }, /* 0x25 */ \ + {'9' , '(' }, /* 0x26 */ \ + {'0' , ')' }, /* 0x27 */ \ + {'\r' , '\r' }, /* 0x28 */ \ + {'\x1b', '\x1b' }, /* 0x29 */ \ + {'\b' , '\b' }, /* 0x2a */ \ + {'\t' , '\t' }, /* 0x2b */ \ + {' ' , ' ' }, /* 0x2c */ \ + {'-' , '_' }, /* 0x2d */ \ + {'=' , '+' }, /* 0x2e */ \ + {'[' , '{' }, /* 0x2f */ \ + {']' , '}' }, /* 0x30 */ \ + {'\\' , '|' }, /* 0x31 */ \ + {'#' , '~' }, /* 0x32 */ \ + {';' , ':' }, /* 0x33 */ \ + {'\'' , '\"' }, /* 0x34 */ \ + {'`' , '~' }, /* 0x35 */ \ + {',' , '<' }, /* 0x36 */ \ + {'.' , '>' }, /* 0x37 */ \ + {'/' , '?' }, /* 0x38 */ \ + \ + {0 , 0 }, /* 0x39 */ \ + {0 , 0 }, /* 0x3a */ \ + {0 , 0 }, /* 0x3b */ \ + {0 , 0 }, /* 0x3c */ \ + {0 , 0 }, /* 0x3d */ \ + {0 , 0 }, /* 0x3e */ \ + {0 , 0 }, /* 0x3f */ \ + {0 , 0 }, /* 0x40 */ \ + {0 , 0 }, /* 0x41 */ \ + {0 , 0 }, /* 0x42 */ \ + {0 , 0 }, /* 0x43 */ \ + {0 , 0 }, /* 0x44 */ \ + {0 , 0 }, /* 0x45 */ \ + {0 , 0 }, /* 0x46 */ \ + {0 , 0 }, /* 0x47 */ \ + {0 , 0 }, /* 0x48 */ \ + {0 , 0 }, /* 0x49 */ \ + {0 , 0 }, /* 0x4a */ \ + {0 , 0 }, /* 0x4b */ \ + {0 , 0 }, /* 0x4c */ \ + {0 , 0 }, /* 0x4d */ \ + {0 , 0 }, /* 0x4e */ \ + {0 , 0 }, /* 0x4f */ \ + {0 , 0 }, /* 0x50 */ \ + {0 , 0 }, /* 0x51 */ \ + {0 , 0 }, /* 0x52 */ \ + {0 , 0 }, /* 0x53 */ \ + \ + {'/' , '/' }, /* 0x54 */ \ + {'*' , '*' }, /* 0x55 */ \ + {'-' , '-' }, /* 0x56 */ \ + {'+' , '+' }, /* 0x57 */ \ + {'\r' , '\r' }, /* 0x58 */ \ + {'1' , 0 }, /* 0x59 */ \ + {'2' , 0 }, /* 0x5a */ \ + {'3' , 0 }, /* 0x5b */ \ + {'4' , 0 }, /* 0x5c */ \ + {'5' , '5' }, /* 0x5d */ \ + {'6' , 0 }, /* 0x5e */ \ + {'7' , 0 }, /* 0x5f */ \ + {'8' , 0 }, /* 0x60 */ \ + {'9' , 0 }, /* 0x61 */ \ + {'0' , 0 }, /* 0x62 */ \ + {'0' , 0 }, /* 0x63 */ \ + {'=' , '=' }, /* 0x67 */ \ + + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_HID_H__ */ + +/// @} diff --git a/src/class/hid/hid_device.h b/src/class/hid/hid_device.h index 577b9ca8..f5e29d8a 100644 --- a/src/class/hid/hid_device.h +++ b/src/class/hid/hid_device.h @@ -1,315 +1,315 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2019 Ha Thach (tinyusb.org) - * - * 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. - * - * This file is part of the TinyUSB stack. - */ - -#ifndef _TUSB_HID_DEVICE_H_ -#define _TUSB_HID_DEVICE_H_ - -#include "common/tusb_common.h" -#include "device/usbd.h" -#include "hid.h" - -#ifdef __cplusplus - extern "C" { -#endif - -//--------------------------------------------------------------------+ -// Class Driver Default Configure & Validation -//--------------------------------------------------------------------+ - -#ifndef CFG_TUD_HID_BUFSIZE -#define CFG_TUD_HID_BUFSIZE 16 -#endif - -//--------------------------------------------------------------------+ -// Application API -//--------------------------------------------------------------------+ - -// Check if the interface is ready to use -bool tud_hid_ready(void); - -// Check if current mode is Boot (true) or Report (false) -bool tud_hid_boot_mode(void); - -// Send report to host -bool tud_hid_report(uint8_t report_id, void const* report, uint8_t len); - -// KEYBOARD: convenient helper to send keyboard report if application -// use template layout report as defined by hid_keyboard_report_t -bool tud_hid_keyboard_report(uint8_t report_id, uint8_t modifier, uint8_t keycode[6]); - -// MOUSE: convenient helper to send mouse report if application -// use template layout report as defined by hid_mouse_report_t -bool tud_hid_mouse_report(uint8_t report_id, uint8_t buttons, int8_t x, int8_t y, int8_t vertical, int8_t horizontal); - -//--------------------------------------------------------------------+ -// Callbacks (Weak is optional) -//--------------------------------------------------------------------+ - -// Invoked when received GET HID REPORT DESCRIPTOR request -// Application return pointer to descriptor, whose contents must exist long enough for transfer to complete -uint8_t const * tud_hid_descriptor_report_cb(void); - -// Invoked when received GET_REPORT control request -// Application must fill buffer report's content and return its length. -// Return zero will cause the stack to STALL request -uint16_t tud_hid_get_report_cb(uint8_t report_id, hid_report_type_t report_type, uint8_t* buffer, uint16_t reqlen); - -// Invoked when received SET_REPORT control request or -// received data on OUT endpoint ( Report ID = 0, Type = 0 ) -void tud_hid_set_report_cb(uint8_t report_id, hid_report_type_t report_type, uint8_t const* buffer, uint16_t bufsize); - -// Invoked when received SET_PROTOCOL request ( mode switch Boot <-> Report ) -TU_ATTR_WEAK void tud_hid_boot_mode_cb(uint8_t boot_mode); - -// Invoked when received SET_IDLE request. return false will stall the request -// - Idle Rate = 0 : only send report if there is changes, i.e skip duplication -// - Idle Rate > 0 : skip duplication, but send at least 1 report every idle rate (in unit of 4 ms). -TU_ATTR_WEAK bool tud_hid_set_idle_cb(uint8_t idle_rate); - -/* --------------------------------------------------------------------+ - * HID Report Descriptor Template - * - * Convenient for declaring popular HID device (keyboard, mouse, consumer, - * gamepad etc...). Templates take "HID_REPORT_ID(n)," as input, leave - * empty if multiple reports is not used - * - * - Only 1 report: no parameter - * uint8_t const report_desc[] = { TUD_HID_REPORT_DESC_KEYBOARD() }; - * - * - Multiple Reports: "HID_REPORT_ID(ID)," must be passed to template - * uint8_t const report_desc[] = - * { - * TUD_HID_REPORT_DESC_KEYBOARD( HID_REPORT_ID(1), ) , - * TUD_HID_REPORT_DESC_MOUSE ( HID_REPORT_ID(2), ) - * }; - *--------------------------------------------------------------------*/ - -// Keyboard Report Descriptor Template -#define TUD_HID_REPORT_DESC_KEYBOARD(...) \ - HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\ - HID_USAGE ( HID_USAGE_DESKTOP_KEYBOARD ) ,\ - HID_COLLECTION ( HID_COLLECTION_APPLICATION ) ,\ - /* Report ID if any */\ - __VA_ARGS__ \ - /* 8 bits Modifier Keys (Shfit, Control, Alt) */ \ - HID_USAGE_PAGE ( HID_USAGE_PAGE_KEYBOARD ) ,\ - HID_USAGE_MIN ( 224 ) ,\ - HID_USAGE_MAX ( 231 ) ,\ - HID_LOGICAL_MIN ( 0 ) ,\ - HID_LOGICAL_MAX ( 1 ) ,\ - HID_REPORT_COUNT ( 8 ) ,\ - HID_REPORT_SIZE ( 1 ) ,\ - HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\ - /* 8 bit reserved */ \ - HID_REPORT_COUNT ( 1 ) ,\ - HID_REPORT_SIZE ( 8 ) ,\ - HID_INPUT ( HID_CONSTANT ) ,\ - /* 6-byte Keycodes */ \ - HID_USAGE_PAGE ( HID_USAGE_PAGE_KEYBOARD ) ,\ - HID_USAGE_MIN ( 0 ) ,\ - HID_USAGE_MAX ( 255 ) ,\ - HID_LOGICAL_MIN ( 0 ) ,\ - HID_LOGICAL_MAX ( 255 ) ,\ - HID_REPORT_COUNT ( 6 ) ,\ - HID_REPORT_SIZE ( 8 ) ,\ - HID_INPUT ( HID_DATA | HID_ARRAY | HID_ABSOLUTE ) ,\ - /* 5-bit LED Indicator Kana | Compose | ScrollLock | CapsLock | NumLock */ \ - HID_USAGE_PAGE ( HID_USAGE_PAGE_LED ) ,\ - HID_USAGE_MIN ( 1 ) ,\ - HID_USAGE_MAX ( 5 ) ,\ - HID_REPORT_COUNT ( 5 ) ,\ - HID_REPORT_SIZE ( 1 ) ,\ - HID_OUTPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\ - /* led padding */ \ - HID_REPORT_COUNT ( 1 ) ,\ - HID_REPORT_SIZE ( 3 ) ,\ - HID_OUTPUT ( HID_CONSTANT ) ,\ - HID_COLLECTION_END \ - -// Mouse Report Descriptor Template -#define TUD_HID_REPORT_DESC_MOUSE(...) \ - HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\ - HID_USAGE ( HID_USAGE_DESKTOP_MOUSE ) ,\ - HID_COLLECTION ( HID_COLLECTION_APPLICATION ) ,\ - /* Report ID if any */\ - __VA_ARGS__ \ - HID_USAGE ( HID_USAGE_DESKTOP_POINTER ) ,\ - HID_COLLECTION ( HID_COLLECTION_PHYSICAL ) ,\ - HID_USAGE_PAGE ( HID_USAGE_PAGE_BUTTON ) ,\ - HID_USAGE_MIN ( 1 ) ,\ - HID_USAGE_MAX ( 5 ) ,\ - HID_LOGICAL_MIN ( 0 ) ,\ - HID_LOGICAL_MAX ( 1 ) ,\ - /* Left, Right, Middle, Backward, Forward buttons */ \ - HID_REPORT_COUNT( 5 ) ,\ - HID_REPORT_SIZE ( 1 ) ,\ - HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\ - /* 3 bit padding */ \ - HID_REPORT_COUNT( 1 ) ,\ - HID_REPORT_SIZE ( 3 ) ,\ - HID_INPUT ( HID_CONSTANT ) ,\ - HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\ - /* X, Y position [-127, 127] */ \ - HID_USAGE ( HID_USAGE_DESKTOP_X ) ,\ - HID_USAGE ( HID_USAGE_DESKTOP_Y ) ,\ - HID_LOGICAL_MIN ( 0x81 ) ,\ - HID_LOGICAL_MAX ( 0x7f ) ,\ - HID_REPORT_COUNT( 2 ) ,\ - HID_REPORT_SIZE ( 8 ) ,\ - HID_INPUT ( HID_DATA | HID_VARIABLE | HID_RELATIVE ) ,\ - /* Verital wheel scroll [-127, 127] */ \ - HID_USAGE ( HID_USAGE_DESKTOP_WHEEL ) ,\ - HID_LOGICAL_MIN ( 0x81 ) ,\ - HID_LOGICAL_MAX ( 0x7f ) ,\ - HID_REPORT_COUNT( 1 ) ,\ - HID_REPORT_SIZE ( 8 ) ,\ - HID_INPUT ( HID_DATA | HID_VARIABLE | HID_RELATIVE ) ,\ - HID_USAGE_PAGE ( HID_USAGE_PAGE_CONSUMER ), \ - /* Horizontal wheel scroll [-127, 127] */ \ - HID_USAGE_N ( HID_USAGE_CONSUMER_AC_PAN, 2 ), \ - HID_LOGICAL_MIN ( 0x81 ), \ - HID_LOGICAL_MAX ( 0x7f ), \ - HID_REPORT_COUNT( 1 ), \ - HID_REPORT_SIZE ( 8 ), \ - HID_INPUT ( HID_DATA | HID_VARIABLE | HID_RELATIVE ), \ - HID_COLLECTION_END , \ - HID_COLLECTION_END \ - -// Consumer Control Report Descriptor Template -#define TUD_HID_REPORT_DESC_CONSUMER(...) \ - HID_USAGE_PAGE ( HID_USAGE_PAGE_CONSUMER ) ,\ - HID_USAGE ( HID_USAGE_CONSUMER_CONTROL ) ,\ - HID_COLLECTION ( HID_COLLECTION_APPLICATION ) ,\ - /* Report ID if any */\ - __VA_ARGS__ \ - HID_LOGICAL_MIN ( 0x00 ) ,\ - HID_LOGICAL_MAX_N( 0x03FF, 2 ) ,\ - HID_USAGE_MIN ( 0x00 ) ,\ - HID_USAGE_MAX_N ( 0x03FF, 2 ) ,\ - HID_REPORT_COUNT ( 1 ) ,\ - HID_REPORT_SIZE ( 16 ) ,\ - HID_INPUT ( HID_DATA | HID_ARRAY | HID_ABSOLUTE ) ,\ - HID_COLLECTION_END \ - -/* System Control Report Descriptor Template - * 0x00 - do nothing - * 0x01 - Power Off - * 0x02 - Standby - * 0x04 - Wake Host - */ -#define TUD_HID_REPORT_DESC_SYSTEM_CONTROL(...) \ - HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\ - HID_USAGE ( HID_USAGE_DESKTOP_SYSTEM_CONTROL ) ,\ - HID_COLLECTION ( HID_COLLECTION_APPLICATION ) ,\ - /* Report ID if any */\ - __VA_ARGS__ \ - /* 2 bit system power control */ \ - HID_LOGICAL_MIN ( 1 ) ,\ - HID_LOGICAL_MAX ( 3 ) ,\ - HID_REPORT_COUNT ( 1 ) ,\ - HID_REPORT_SIZE ( 2 ) ,\ - HID_USAGE ( HID_USAGE_DESKTOP_SYSTEM_SLEEP ) ,\ - HID_USAGE ( HID_USAGE_DESKTOP_SYSTEM_POWER_DOWN ) ,\ - HID_USAGE ( HID_USAGE_DESKTOP_SYSTEM_WAKE_UP ) ,\ - HID_INPUT ( HID_DATA | HID_ARRAY | HID_ABSOLUTE ) ,\ - /* 6 bit padding */ \ - HID_REPORT_COUNT ( 1 ) ,\ - HID_REPORT_SIZE ( 6 ) ,\ - HID_INPUT ( HID_CONSTANT ) ,\ - HID_COLLECTION_END \ - -// Gamepad Report Descriptor Template -// with 16 buttons and 2 joysticks with following layout -// | Button Map (2 bytes) | X | Y | Z | Rz -#define TUD_HID_REPORT_DESC_GAMEPAD(...) \ - HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\ - HID_USAGE ( HID_USAGE_DESKTOP_GAMEPAD ) ,\ - HID_COLLECTION ( HID_COLLECTION_APPLICATION ) ,\ - /* Report ID if any */\ - __VA_ARGS__ \ - /* 16 bit Button Map */ \ - HID_USAGE_PAGE ( HID_USAGE_PAGE_BUTTON ) ,\ - HID_USAGE_MIN ( 1 ) ,\ - HID_USAGE_MAX ( 16 ) ,\ - HID_LOGICAL_MIN ( 0 ) ,\ - HID_LOGICAL_MAX ( 1 ) ,\ - HID_REPORT_COUNT ( 16 ) ,\ - HID_REPORT_SIZE ( 1 ) ,\ - HID_INPUT ( HID_DATA | HID_ARRAY | HID_ABSOLUTE ) ,\ - /* X, Y, Z, Rz (min -127, max 127 ) */ \ - HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\ - HID_LOGICAL_MIN ( 0x81 ) ,\ - HID_LOGICAL_MAX ( 0x7f ) ,\ - HID_USAGE ( HID_USAGE_DESKTOP_X ) ,\ - HID_USAGE ( HID_USAGE_DESKTOP_Y ) ,\ - HID_USAGE ( HID_USAGE_DESKTOP_Z ) ,\ - HID_USAGE ( HID_USAGE_DESKTOP_RZ ) ,\ - HID_REPORT_COUNT ( 4 ) ,\ - HID_REPORT_SIZE ( 8 ) ,\ - HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\ - HID_COLLECTION_END \ - -// HID Generic Input & Output -// - 1st parameter is report size (mandatory) -// - 2nd parameter is report id HID_REPORT_ID(n) (optional) -#define TUD_HID_REPORT_DESC_GENERIC_INOUT(report_size, ...) \ - HID_USAGE_PAGE_N ( HID_USAGE_PAGE_VENDOR, 2 ),\ - HID_USAGE ( 0x01 ),\ - HID_COLLECTION ( HID_COLLECTION_APPLICATION ),\ - /* Report ID if any */\ - __VA_ARGS__ \ - /* Input */ \ - HID_USAGE ( 0x02 ),\ - HID_LOGICAL_MIN ( 0x00 ),\ - HID_LOGICAL_MAX ( 0xff ),\ - HID_REPORT_SIZE ( 8 ),\ - HID_REPORT_COUNT( report_size ),\ - HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ),\ - /* Output */ \ - HID_USAGE ( 0x03 ),\ - HID_LOGICAL_MIN ( 0x00 ),\ - HID_LOGICAL_MAX ( 0xff ),\ - HID_REPORT_SIZE ( 8 ),\ - HID_REPORT_COUNT( report_size ),\ - HID_OUTPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ),\ - HID_COLLECTION_END \ - -//--------------------------------------------------------------------+ -// Internal Class Driver API -//--------------------------------------------------------------------+ -void hidd_init (void); -void hidd_reset (uint8_t rhport); -bool hidd_open (uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t *p_length); -bool hidd_control_request (uint8_t rhport, tusb_control_request_t const * request); -bool hidd_control_complete (uint8_t rhport, tusb_control_request_t const * request); -bool hidd_xfer_cb (uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes); - -#ifdef __cplusplus - } -#endif - -#endif /* _TUSB_HID_DEVICE_H_ */ - +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#ifndef _TUSB_HID_DEVICE_H_ +#define _TUSB_HID_DEVICE_H_ + +#include "common/tusb_common.h" +#include "device/usbd.h" +#include "hid.h" + +#ifdef __cplusplus + extern "C" { +#endif + +//--------------------------------------------------------------------+ +// Class Driver Default Configure & Validation +//--------------------------------------------------------------------+ + +#ifndef CFG_TUD_HID_BUFSIZE +#define CFG_TUD_HID_BUFSIZE 16 +#endif + +//--------------------------------------------------------------------+ +// Application API +//--------------------------------------------------------------------+ + +// Check if the interface is ready to use +bool tud_hid_ready(void); + +// Check if current mode is Boot (true) or Report (false) +bool tud_hid_boot_mode(void); + +// Send report to host +bool tud_hid_report(uint8_t report_id, void const* report, uint8_t len); + +// KEYBOARD: convenient helper to send keyboard report if application +// use template layout report as defined by hid_keyboard_report_t +bool tud_hid_keyboard_report(uint8_t report_id, uint8_t modifier, uint8_t keycode[6]); + +// MOUSE: convenient helper to send mouse report if application +// use template layout report as defined by hid_mouse_report_t +bool tud_hid_mouse_report(uint8_t report_id, uint8_t buttons, int8_t x, int8_t y, int8_t vertical, int8_t horizontal); + +//--------------------------------------------------------------------+ +// Callbacks (Weak is optional) +//--------------------------------------------------------------------+ + +// Invoked when received GET HID REPORT DESCRIPTOR request +// Application return pointer to descriptor, whose contents must exist long enough for transfer to complete +uint8_t const * tud_hid_descriptor_report_cb(void); + +// Invoked when received GET_REPORT control request +// Application must fill buffer report's content and return its length. +// Return zero will cause the stack to STALL request +uint16_t tud_hid_get_report_cb(uint8_t report_id, hid_report_type_t report_type, uint8_t* buffer, uint16_t reqlen); + +// Invoked when received SET_REPORT control request or +// received data on OUT endpoint ( Report ID = 0, Type = 0 ) +void tud_hid_set_report_cb(uint8_t report_id, hid_report_type_t report_type, uint8_t const* buffer, uint16_t bufsize); + +// Invoked when received SET_PROTOCOL request ( mode switch Boot <-> Report ) +TU_ATTR_WEAK void tud_hid_boot_mode_cb(uint8_t boot_mode); + +// Invoked when received SET_IDLE request. return false will stall the request +// - Idle Rate = 0 : only send report if there is changes, i.e skip duplication +// - Idle Rate > 0 : skip duplication, but send at least 1 report every idle rate (in unit of 4 ms). +TU_ATTR_WEAK bool tud_hid_set_idle_cb(uint8_t idle_rate); + +/* --------------------------------------------------------------------+ + * HID Report Descriptor Template + * + * Convenient for declaring popular HID device (keyboard, mouse, consumer, + * gamepad etc...). Templates take "HID_REPORT_ID(n)," as input, leave + * empty if multiple reports is not used + * + * - Only 1 report: no parameter + * uint8_t const report_desc[] = { TUD_HID_REPORT_DESC_KEYBOARD() }; + * + * - Multiple Reports: "HID_REPORT_ID(ID)," must be passed to template + * uint8_t const report_desc[] = + * { + * TUD_HID_REPORT_DESC_KEYBOARD( HID_REPORT_ID(1), ) , + * TUD_HID_REPORT_DESC_MOUSE ( HID_REPORT_ID(2), ) + * }; + *--------------------------------------------------------------------*/ + +// Keyboard Report Descriptor Template +#define TUD_HID_REPORT_DESC_KEYBOARD(...) \ + HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\ + HID_USAGE ( HID_USAGE_DESKTOP_KEYBOARD ) ,\ + HID_COLLECTION ( HID_COLLECTION_APPLICATION ) ,\ + /* Report ID if any */\ + __VA_ARGS__ \ + /* 8 bits Modifier Keys (Shfit, Control, Alt) */ \ + HID_USAGE_PAGE ( HID_USAGE_PAGE_KEYBOARD ) ,\ + HID_USAGE_MIN ( 224 ) ,\ + HID_USAGE_MAX ( 231 ) ,\ + HID_LOGICAL_MIN ( 0 ) ,\ + HID_LOGICAL_MAX ( 1 ) ,\ + HID_REPORT_COUNT ( 8 ) ,\ + HID_REPORT_SIZE ( 1 ) ,\ + HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\ + /* 8 bit reserved */ \ + HID_REPORT_COUNT ( 1 ) ,\ + HID_REPORT_SIZE ( 8 ) ,\ + HID_INPUT ( HID_CONSTANT ) ,\ + /* 6-byte Keycodes */ \ + HID_USAGE_PAGE ( HID_USAGE_PAGE_KEYBOARD ) ,\ + HID_USAGE_MIN ( 0 ) ,\ + HID_USAGE_MAX ( 255 ) ,\ + HID_LOGICAL_MIN ( 0 ) ,\ + HID_LOGICAL_MAX ( 255 ) ,\ + HID_REPORT_COUNT ( 6 ) ,\ + HID_REPORT_SIZE ( 8 ) ,\ + HID_INPUT ( HID_DATA | HID_ARRAY | HID_ABSOLUTE ) ,\ + /* 5-bit LED Indicator Kana | Compose | ScrollLock | CapsLock | NumLock */ \ + HID_USAGE_PAGE ( HID_USAGE_PAGE_LED ) ,\ + HID_USAGE_MIN ( 1 ) ,\ + HID_USAGE_MAX ( 5 ) ,\ + HID_REPORT_COUNT ( 5 ) ,\ + HID_REPORT_SIZE ( 1 ) ,\ + HID_OUTPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\ + /* led padding */ \ + HID_REPORT_COUNT ( 1 ) ,\ + HID_REPORT_SIZE ( 3 ) ,\ + HID_OUTPUT ( HID_CONSTANT ) ,\ + HID_COLLECTION_END \ + +// Mouse Report Descriptor Template +#define TUD_HID_REPORT_DESC_MOUSE(...) \ + HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\ + HID_USAGE ( HID_USAGE_DESKTOP_MOUSE ) ,\ + HID_COLLECTION ( HID_COLLECTION_APPLICATION ) ,\ + /* Report ID if any */\ + __VA_ARGS__ \ + HID_USAGE ( HID_USAGE_DESKTOP_POINTER ) ,\ + HID_COLLECTION ( HID_COLLECTION_PHYSICAL ) ,\ + HID_USAGE_PAGE ( HID_USAGE_PAGE_BUTTON ) ,\ + HID_USAGE_MIN ( 1 ) ,\ + HID_USAGE_MAX ( 5 ) ,\ + HID_LOGICAL_MIN ( 0 ) ,\ + HID_LOGICAL_MAX ( 1 ) ,\ + /* Left, Right, Middle, Backward, Forward buttons */ \ + HID_REPORT_COUNT( 5 ) ,\ + HID_REPORT_SIZE ( 1 ) ,\ + HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\ + /* 3 bit padding */ \ + HID_REPORT_COUNT( 1 ) ,\ + HID_REPORT_SIZE ( 3 ) ,\ + HID_INPUT ( HID_CONSTANT ) ,\ + HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\ + /* X, Y position [-127, 127] */ \ + HID_USAGE ( HID_USAGE_DESKTOP_X ) ,\ + HID_USAGE ( HID_USAGE_DESKTOP_Y ) ,\ + HID_LOGICAL_MIN ( 0x81 ) ,\ + HID_LOGICAL_MAX ( 0x7f ) ,\ + HID_REPORT_COUNT( 2 ) ,\ + HID_REPORT_SIZE ( 8 ) ,\ + HID_INPUT ( HID_DATA | HID_VARIABLE | HID_RELATIVE ) ,\ + /* Verital wheel scroll [-127, 127] */ \ + HID_USAGE ( HID_USAGE_DESKTOP_WHEEL ) ,\ + HID_LOGICAL_MIN ( 0x81 ) ,\ + HID_LOGICAL_MAX ( 0x7f ) ,\ + HID_REPORT_COUNT( 1 ) ,\ + HID_REPORT_SIZE ( 8 ) ,\ + HID_INPUT ( HID_DATA | HID_VARIABLE | HID_RELATIVE ) ,\ + HID_USAGE_PAGE ( HID_USAGE_PAGE_CONSUMER ), \ + /* Horizontal wheel scroll [-127, 127] */ \ + HID_USAGE_N ( HID_USAGE_CONSUMER_AC_PAN, 2 ), \ + HID_LOGICAL_MIN ( 0x81 ), \ + HID_LOGICAL_MAX ( 0x7f ), \ + HID_REPORT_COUNT( 1 ), \ + HID_REPORT_SIZE ( 8 ), \ + HID_INPUT ( HID_DATA | HID_VARIABLE | HID_RELATIVE ), \ + HID_COLLECTION_END , \ + HID_COLLECTION_END \ + +// Consumer Control Report Descriptor Template +#define TUD_HID_REPORT_DESC_CONSUMER(...) \ + HID_USAGE_PAGE ( HID_USAGE_PAGE_CONSUMER ) ,\ + HID_USAGE ( HID_USAGE_CONSUMER_CONTROL ) ,\ + HID_COLLECTION ( HID_COLLECTION_APPLICATION ) ,\ + /* Report ID if any */\ + __VA_ARGS__ \ + HID_LOGICAL_MIN ( 0x00 ) ,\ + HID_LOGICAL_MAX_N( 0x03FF, 2 ) ,\ + HID_USAGE_MIN ( 0x00 ) ,\ + HID_USAGE_MAX_N ( 0x03FF, 2 ) ,\ + HID_REPORT_COUNT ( 1 ) ,\ + HID_REPORT_SIZE ( 16 ) ,\ + HID_INPUT ( HID_DATA | HID_ARRAY | HID_ABSOLUTE ) ,\ + HID_COLLECTION_END \ + +/* System Control Report Descriptor Template + * 0x00 - do nothing + * 0x01 - Power Off + * 0x02 - Standby + * 0x04 - Wake Host + */ +#define TUD_HID_REPORT_DESC_SYSTEM_CONTROL(...) \ + HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\ + HID_USAGE ( HID_USAGE_DESKTOP_SYSTEM_CONTROL ) ,\ + HID_COLLECTION ( HID_COLLECTION_APPLICATION ) ,\ + /* Report ID if any */\ + __VA_ARGS__ \ + /* 2 bit system power control */ \ + HID_LOGICAL_MIN ( 1 ) ,\ + HID_LOGICAL_MAX ( 3 ) ,\ + HID_REPORT_COUNT ( 1 ) ,\ + HID_REPORT_SIZE ( 2 ) ,\ + HID_USAGE ( HID_USAGE_DESKTOP_SYSTEM_SLEEP ) ,\ + HID_USAGE ( HID_USAGE_DESKTOP_SYSTEM_POWER_DOWN ) ,\ + HID_USAGE ( HID_USAGE_DESKTOP_SYSTEM_WAKE_UP ) ,\ + HID_INPUT ( HID_DATA | HID_ARRAY | HID_ABSOLUTE ) ,\ + /* 6 bit padding */ \ + HID_REPORT_COUNT ( 1 ) ,\ + HID_REPORT_SIZE ( 6 ) ,\ + HID_INPUT ( HID_CONSTANT ) ,\ + HID_COLLECTION_END \ + +// Gamepad Report Descriptor Template +// with 16 buttons and 2 joysticks with following layout +// | Button Map (2 bytes) | X | Y | Z | Rz +#define TUD_HID_REPORT_DESC_GAMEPAD(...) \ + HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\ + HID_USAGE ( HID_USAGE_DESKTOP_GAMEPAD ) ,\ + HID_COLLECTION ( HID_COLLECTION_APPLICATION ) ,\ + /* Report ID if any */\ + __VA_ARGS__ \ + /* 16 bit Button Map */ \ + HID_USAGE_PAGE ( HID_USAGE_PAGE_BUTTON ) ,\ + HID_USAGE_MIN ( 1 ) ,\ + HID_USAGE_MAX ( 16 ) ,\ + HID_LOGICAL_MIN ( 0 ) ,\ + HID_LOGICAL_MAX ( 1 ) ,\ + HID_REPORT_COUNT ( 16 ) ,\ + HID_REPORT_SIZE ( 1 ) ,\ + HID_INPUT ( HID_DATA | HID_ARRAY | HID_ABSOLUTE ) ,\ + /* X, Y, Z, Rz (min -127, max 127 ) */ \ + HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\ + HID_LOGICAL_MIN ( 0x81 ) ,\ + HID_LOGICAL_MAX ( 0x7f ) ,\ + HID_USAGE ( HID_USAGE_DESKTOP_X ) ,\ + HID_USAGE ( HID_USAGE_DESKTOP_Y ) ,\ + HID_USAGE ( HID_USAGE_DESKTOP_Z ) ,\ + HID_USAGE ( HID_USAGE_DESKTOP_RZ ) ,\ + HID_REPORT_COUNT ( 4 ) ,\ + HID_REPORT_SIZE ( 8 ) ,\ + HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\ + HID_COLLECTION_END \ + +// HID Generic Input & Output +// - 1st parameter is report size (mandatory) +// - 2nd parameter is report id HID_REPORT_ID(n) (optional) +#define TUD_HID_REPORT_DESC_GENERIC_INOUT(report_size, ...) \ + HID_USAGE_PAGE_N ( HID_USAGE_PAGE_VENDOR, 2 ),\ + HID_USAGE ( 0x01 ),\ + HID_COLLECTION ( HID_COLLECTION_APPLICATION ),\ + /* Report ID if any */\ + __VA_ARGS__ \ + /* Input */ \ + HID_USAGE ( 0x02 ),\ + HID_LOGICAL_MIN ( 0x00 ),\ + HID_LOGICAL_MAX ( 0xff ),\ + HID_REPORT_SIZE ( 8 ),\ + HID_REPORT_COUNT( report_size ),\ + HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ),\ + /* Output */ \ + HID_USAGE ( 0x03 ),\ + HID_LOGICAL_MIN ( 0x00 ),\ + HID_LOGICAL_MAX ( 0xff ),\ + HID_REPORT_SIZE ( 8 ),\ + HID_REPORT_COUNT( report_size ),\ + HID_OUTPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ),\ + HID_COLLECTION_END \ + +//--------------------------------------------------------------------+ +// Internal Class Driver API +//--------------------------------------------------------------------+ +void hidd_init (void); +void hidd_reset (uint8_t rhport); +bool hidd_open (uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t *p_length); +bool hidd_control_request (uint8_t rhport, tusb_control_request_t const * request); +bool hidd_control_complete (uint8_t rhport, tusb_control_request_t const * request); +bool hidd_xfer_cb (uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes); + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_HID_DEVICE_H_ */ + diff --git a/src/class/hid/hid_host.c b/src/class/hid/hid_host.c index 91a441af..69c49b01 100644 --- a/src/class/hid/hid_host.c +++ b/src/class/hid/hid_host.c @@ -1,289 +1,289 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2019 Ha Thach (tinyusb.org) - * - * 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. - * - * This file is part of the TinyUSB stack. - */ - -#include "tusb_option.h" - -#if (TUSB_OPT_HOST_ENABLED && HOST_CLASS_HID) - -#include "common/tusb_common.h" -#include "hid_host.h" - -//--------------------------------------------------------------------+ -// MACRO CONSTANT TYPEDEF -//--------------------------------------------------------------------+ - -//--------------------------------------------------------------------+ -// HID Interface common functions -//--------------------------------------------------------------------+ -static inline bool hidh_interface_open(uint8_t dev_addr, uint8_t interface_number, tusb_desc_endpoint_t const *p_endpoint_desc, hidh_interface_info_t *p_hid) -{ - p_hid->pipe_hdl = hcd_edpt_open(dev_addr, p_endpoint_desc, TUSB_CLASS_HID); - p_hid->report_size = p_endpoint_desc->wMaxPacketSize.size; // TODO get size from report descriptor - p_hid->interface_number = interface_number; - - TU_ASSERT (pipehandle_is_valid(p_hid->pipe_hdl)); - - return true; -} - -static inline void hidh_interface_close(hidh_interface_info_t *p_hid) -{ - tu_memclr(p_hid, sizeof(hidh_interface_info_t)); -} - -// called from public API need to validate parameters -tusb_error_t hidh_interface_get_report(uint8_t dev_addr, void * report, hidh_interface_info_t *p_hid) -{ - //------------- parameters validation -------------// - // TODO change to use is configured function - TU_ASSERT (TUSB_DEVICE_STATE_CONFIGURED == tuh_device_get_state(dev_addr), TUSB_ERROR_DEVICE_NOT_READY); - TU_VERIFY (report, TUSB_ERROR_INVALID_PARA); - TU_ASSERT (!hcd_edpt_busy(p_hid->pipe_hdl), TUSB_ERROR_INTERFACE_IS_BUSY); - - TU_ASSERT_ERR( hcd_pipe_xfer(p_hid->pipe_hdl, report, p_hid->report_size, true) ) ; - - return TUSB_ERROR_NONE; -} - -//--------------------------------------------------------------------+ -// KEYBOARD -//--------------------------------------------------------------------+ -#if CFG_TUH_HID_KEYBOARD - -#if 0 -#define EXPAND_KEYCODE_TO_ASCII(keycode, ascii, shift_modified) \ - [0][keycode] = ascii,\ - [1][keycode] = shift_modified,\ - -// TODO size of table should be a macro for application to check boundary -uint8_t const hid_keycode_to_ascii_tbl[2][128] = -{ - HID_KEYCODE_TABLE(EXPAND_KEYCODE_TO_ASCII) -}; -#endif - -static hidh_interface_info_t keyboardh_data[CFG_TUSB_HOST_DEVICE_MAX]; // does not have addr0, index = dev_address-1 - -//------------- KEYBOARD PUBLIC API (parameter validation required) -------------// -bool tuh_hid_keyboard_is_mounted(uint8_t dev_addr) -{ - return tuh_device_is_configured(dev_addr) && pipehandle_is_valid(keyboardh_data[dev_addr-1].pipe_hdl); -} - -tusb_error_t tuh_hid_keyboard_get_report(uint8_t dev_addr, void* p_report) -{ - return hidh_interface_get_report(dev_addr, p_report, &keyboardh_data[dev_addr-1]); -} - -bool tuh_hid_keyboard_is_busy(uint8_t dev_addr) -{ - return tuh_hid_keyboard_is_mounted(dev_addr) && - hcd_edpt_busy( keyboardh_data[dev_addr-1].pipe_hdl ); -} - -#endif - -//--------------------------------------------------------------------+ -// MOUSE -//--------------------------------------------------------------------+ -#if CFG_TUH_HID_MOUSE - -static hidh_interface_info_t mouseh_data[CFG_TUSB_HOST_DEVICE_MAX]; // does not have addr0, index = dev_address-1 - -//------------- Public API -------------// -bool tuh_hid_mouse_is_mounted(uint8_t dev_addr) -{ - return tuh_device_is_configured(dev_addr) && pipehandle_is_valid(mouseh_data[dev_addr-1].pipe_hdl); -} - -bool tuh_hid_mouse_is_busy(uint8_t dev_addr) -{ - return tuh_hid_mouse_is_mounted(dev_addr) && - hcd_edpt_busy( mouseh_data[dev_addr-1].pipe_hdl ); -} - -tusb_error_t tuh_hid_mouse_get_report(uint8_t dev_addr, void * report) -{ - return hidh_interface_get_report(dev_addr, report, &mouseh_data[dev_addr-1]); -} - -#endif - -//--------------------------------------------------------------------+ -// GENERIC -//--------------------------------------------------------------------+ -#if CFG_TUSB_HOST_HID_GENERIC - -//STATIC_ struct { -// hidh_interface_info_t -//} generic_data[CFG_TUSB_HOST_DEVICE_MAX]; - -#endif - -//--------------------------------------------------------------------+ -// CLASS-USBH API (don't require to verify parameters) -//--------------------------------------------------------------------+ -void hidh_init(void) -{ -#if CFG_TUH_HID_KEYBOARD - tu_memclr(&keyboardh_data, sizeof(hidh_interface_info_t)*CFG_TUSB_HOST_DEVICE_MAX); -#endif - -#if CFG_TUH_HID_MOUSE - tu_memclr(&mouseh_data, sizeof(hidh_interface_info_t)*CFG_TUSB_HOST_DEVICE_MAX); -#endif - -#if CFG_TUSB_HOST_HID_GENERIC - hidh_generic_init(); -#endif -} - -#if 0 -CFG_TUSB_MEM_SECTION uint8_t report_descriptor[256]; -#endif - -bool hidh_open_subtask(uint8_t dev_addr, tusb_desc_interface_t const *p_interface_desc, uint16_t *p_length) -{ - uint8_t const *p_desc = (uint8_t const *) p_interface_desc; - - //------------- HID descriptor -------------// - p_desc += p_desc[DESC_OFFSET_LEN]; - tusb_hid_descriptor_hid_t const *p_desc_hid = (tusb_hid_descriptor_hid_t const *) p_desc; - TU_ASSERT(HID_DESC_TYPE_HID == p_desc_hid->bDescriptorType, TUSB_ERROR_INVALID_PARA); - - //------------- Endpoint Descriptor -------------// - p_desc += p_desc[DESC_OFFSET_LEN]; - tusb_desc_endpoint_t const * p_endpoint_desc = (tusb_desc_endpoint_t const *) p_desc; - TU_ASSERT(TUSB_DESC_ENDPOINT == p_endpoint_desc->bDescriptorType, TUSB_ERROR_INVALID_PARA); - - //------------- SET IDLE (0) request -------------// - tusb_control_request_t request = { - .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_INTERFACE, .type = TUSB_REQ_TYPE_CLASS, .direction = TUSB_DIR_OUT }, - .bRequest = HID_REQ_CONTROL_SET_IDLE, - .wValue = 0, // idle_rate = 0 - .wIndex = p_interface_desc->bInterfaceNumber, - .wLength = 0 - }; - TU_ASSERT( usbh_control_xfer( dev_addr, &request, NULL ) ); - -#if 0 - //------------- Get Report Descriptor TODO HID parser -------------// - if ( p_desc_hid->bNumDescriptors ) - { - STASK_INVOKE( - usbh_control_xfer_subtask( dev_addr, bm_request_type(TUSB_DIR_IN, TUSB_REQ_TYPE_STANDARD, TUSB_REQ_RCPT_INTERFACE), - TUSB_REQ_GET_DESCRIPTOR, (p_desc_hid->bReportType << 8), 0, - p_desc_hid->wReportLength, report_descriptor ), - error - ); - (void) error; // if error in getting report descriptor --> treating like there is none - } -#endif - - if ( HID_SUBCLASS_BOOT == p_interface_desc->bInterfaceSubClass ) - { - #if CFG_TUH_HID_KEYBOARD - if ( HID_PROTOCOL_KEYBOARD == p_interface_desc->bInterfaceProtocol) - { - TU_ASSERT( hidh_interface_open(dev_addr, p_interface_desc->bInterfaceNumber, p_endpoint_desc, &keyboardh_data[dev_addr-1]) ); - tuh_hid_keyboard_mounted_cb(dev_addr); - } else - #endif - - #if CFG_TUH_HID_MOUSE - if ( HID_PROTOCOL_MOUSE == p_interface_desc->bInterfaceProtocol) - { - TU_ASSERT ( hidh_interface_open(dev_addr, p_interface_desc->bInterfaceNumber, p_endpoint_desc, &mouseh_data[dev_addr-1]) ); - tuh_hid_mouse_mounted_cb(dev_addr); - } else - #endif - - { - // Not supported protocol - return false; - } - }else - { - // Not supported subclass - return false; - } - - *p_length = sizeof(tusb_desc_interface_t) + sizeof(tusb_hid_descriptor_hid_t) + sizeof(tusb_desc_endpoint_t); - - return true; -} - -void hidh_isr(pipe_handle_t pipe_hdl, xfer_result_t event, uint32_t xferred_bytes) -{ - (void) xferred_bytes; // TODO may need to use this para later - -#if CFG_TUH_HID_KEYBOARD - if ( pipehandle_is_equal(pipe_hdl, keyboardh_data[pipe_hdl.dev_addr-1].pipe_hdl) ) - { - tuh_hid_keyboard_isr(pipe_hdl.dev_addr, event); - return; - } -#endif - -#if CFG_TUH_HID_MOUSE - if ( pipehandle_is_equal(pipe_hdl, mouseh_data[pipe_hdl.dev_addr-1].pipe_hdl) ) - { - tuh_hid_mouse_isr(pipe_hdl.dev_addr, event); - return; - } -#endif - -#if CFG_TUSB_HOST_HID_GENERIC - -#endif -} - -void hidh_close(uint8_t dev_addr) -{ -#if CFG_TUH_HID_KEYBOARD - if ( pipehandle_is_valid( keyboardh_data[dev_addr-1].pipe_hdl ) ) - { - hidh_interface_close(&keyboardh_data[dev_addr-1]); - tuh_hid_keyboard_unmounted_cb(dev_addr); - } -#endif - -#if CFG_TUH_HID_MOUSE - if( pipehandle_is_valid( mouseh_data[dev_addr-1].pipe_hdl ) ) - { - hidh_interface_close(&mouseh_data[dev_addr-1]); - tuh_hid_mouse_unmounted_cb( dev_addr ); - } -#endif - -#if CFG_TUSB_HOST_HID_GENERIC - hidh_generic_close(dev_addr); -#endif -} - - - -#endif +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#include "tusb_option.h" + +#if (TUSB_OPT_HOST_ENABLED && HOST_CLASS_HID) + +#include "common/tusb_common.h" +#include "hid_host.h" + +//--------------------------------------------------------------------+ +// MACRO CONSTANT TYPEDEF +//--------------------------------------------------------------------+ + +//--------------------------------------------------------------------+ +// HID Interface common functions +//--------------------------------------------------------------------+ +static inline bool hidh_interface_open(uint8_t dev_addr, uint8_t interface_number, tusb_desc_endpoint_t const *p_endpoint_desc, hidh_interface_info_t *p_hid) +{ + p_hid->pipe_hdl = hcd_edpt_open(dev_addr, p_endpoint_desc, TUSB_CLASS_HID); + p_hid->report_size = p_endpoint_desc->wMaxPacketSize.size; // TODO get size from report descriptor + p_hid->interface_number = interface_number; + + TU_ASSERT (pipehandle_is_valid(p_hid->pipe_hdl)); + + return true; +} + +static inline void hidh_interface_close(hidh_interface_info_t *p_hid) +{ + tu_memclr(p_hid, sizeof(hidh_interface_info_t)); +} + +// called from public API need to validate parameters +tusb_error_t hidh_interface_get_report(uint8_t dev_addr, void * report, hidh_interface_info_t *p_hid) +{ + //------------- parameters validation -------------// + // TODO change to use is configured function + TU_ASSERT (TUSB_DEVICE_STATE_CONFIGURED == tuh_device_get_state(dev_addr), TUSB_ERROR_DEVICE_NOT_READY); + TU_VERIFY (report, TUSB_ERROR_INVALID_PARA); + TU_ASSERT (!hcd_edpt_busy(p_hid->pipe_hdl), TUSB_ERROR_INTERFACE_IS_BUSY); + + TU_ASSERT_ERR( hcd_pipe_xfer(p_hid->pipe_hdl, report, p_hid->report_size, true) ) ; + + return TUSB_ERROR_NONE; +} + +//--------------------------------------------------------------------+ +// KEYBOARD +//--------------------------------------------------------------------+ +#if CFG_TUH_HID_KEYBOARD + +#if 0 +#define EXPAND_KEYCODE_TO_ASCII(keycode, ascii, shift_modified) \ + [0][keycode] = ascii,\ + [1][keycode] = shift_modified,\ + +// TODO size of table should be a macro for application to check boundary +uint8_t const hid_keycode_to_ascii_tbl[2][128] = +{ + HID_KEYCODE_TABLE(EXPAND_KEYCODE_TO_ASCII) +}; +#endif + +static hidh_interface_info_t keyboardh_data[CFG_TUSB_HOST_DEVICE_MAX]; // does not have addr0, index = dev_address-1 + +//------------- KEYBOARD PUBLIC API (parameter validation required) -------------// +bool tuh_hid_keyboard_is_mounted(uint8_t dev_addr) +{ + return tuh_device_is_configured(dev_addr) && pipehandle_is_valid(keyboardh_data[dev_addr-1].pipe_hdl); +} + +tusb_error_t tuh_hid_keyboard_get_report(uint8_t dev_addr, void* p_report) +{ + return hidh_interface_get_report(dev_addr, p_report, &keyboardh_data[dev_addr-1]); +} + +bool tuh_hid_keyboard_is_busy(uint8_t dev_addr) +{ + return tuh_hid_keyboard_is_mounted(dev_addr) && + hcd_edpt_busy( keyboardh_data[dev_addr-1].pipe_hdl ); +} + +#endif + +//--------------------------------------------------------------------+ +// MOUSE +//--------------------------------------------------------------------+ +#if CFG_TUH_HID_MOUSE + +static hidh_interface_info_t mouseh_data[CFG_TUSB_HOST_DEVICE_MAX]; // does not have addr0, index = dev_address-1 + +//------------- Public API -------------// +bool tuh_hid_mouse_is_mounted(uint8_t dev_addr) +{ + return tuh_device_is_configured(dev_addr) && pipehandle_is_valid(mouseh_data[dev_addr-1].pipe_hdl); +} + +bool tuh_hid_mouse_is_busy(uint8_t dev_addr) +{ + return tuh_hid_mouse_is_mounted(dev_addr) && + hcd_edpt_busy( mouseh_data[dev_addr-1].pipe_hdl ); +} + +tusb_error_t tuh_hid_mouse_get_report(uint8_t dev_addr, void * report) +{ + return hidh_interface_get_report(dev_addr, report, &mouseh_data[dev_addr-1]); +} + +#endif + +//--------------------------------------------------------------------+ +// GENERIC +//--------------------------------------------------------------------+ +#if CFG_TUSB_HOST_HID_GENERIC + +//STATIC_ struct { +// hidh_interface_info_t +//} generic_data[CFG_TUSB_HOST_DEVICE_MAX]; + +#endif + +//--------------------------------------------------------------------+ +// CLASS-USBH API (don't require to verify parameters) +//--------------------------------------------------------------------+ +void hidh_init(void) +{ +#if CFG_TUH_HID_KEYBOARD + tu_memclr(&keyboardh_data, sizeof(hidh_interface_info_t)*CFG_TUSB_HOST_DEVICE_MAX); +#endif + +#if CFG_TUH_HID_MOUSE + tu_memclr(&mouseh_data, sizeof(hidh_interface_info_t)*CFG_TUSB_HOST_DEVICE_MAX); +#endif + +#if CFG_TUSB_HOST_HID_GENERIC + hidh_generic_init(); +#endif +} + +#if 0 +CFG_TUSB_MEM_SECTION uint8_t report_descriptor[256]; +#endif + +bool hidh_open_subtask(uint8_t dev_addr, tusb_desc_interface_t const *p_interface_desc, uint16_t *p_length) +{ + uint8_t const *p_desc = (uint8_t const *) p_interface_desc; + + //------------- HID descriptor -------------// + p_desc += p_desc[DESC_OFFSET_LEN]; + tusb_hid_descriptor_hid_t const *p_desc_hid = (tusb_hid_descriptor_hid_t const *) p_desc; + TU_ASSERT(HID_DESC_TYPE_HID == p_desc_hid->bDescriptorType, TUSB_ERROR_INVALID_PARA); + + //------------- Endpoint Descriptor -------------// + p_desc += p_desc[DESC_OFFSET_LEN]; + tusb_desc_endpoint_t const * p_endpoint_desc = (tusb_desc_endpoint_t const *) p_desc; + TU_ASSERT(TUSB_DESC_ENDPOINT == p_endpoint_desc->bDescriptorType, TUSB_ERROR_INVALID_PARA); + + //------------- SET IDLE (0) request -------------// + tusb_control_request_t request = { + .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_INTERFACE, .type = TUSB_REQ_TYPE_CLASS, .direction = TUSB_DIR_OUT }, + .bRequest = HID_REQ_CONTROL_SET_IDLE, + .wValue = 0, // idle_rate = 0 + .wIndex = p_interface_desc->bInterfaceNumber, + .wLength = 0 + }; + TU_ASSERT( usbh_control_xfer( dev_addr, &request, NULL ) ); + +#if 0 + //------------- Get Report Descriptor TODO HID parser -------------// + if ( p_desc_hid->bNumDescriptors ) + { + STASK_INVOKE( + usbh_control_xfer_subtask( dev_addr, bm_request_type(TUSB_DIR_IN, TUSB_REQ_TYPE_STANDARD, TUSB_REQ_RCPT_INTERFACE), + TUSB_REQ_GET_DESCRIPTOR, (p_desc_hid->bReportType << 8), 0, + p_desc_hid->wReportLength, report_descriptor ), + error + ); + (void) error; // if error in getting report descriptor --> treating like there is none + } +#endif + + if ( HID_SUBCLASS_BOOT == p_interface_desc->bInterfaceSubClass ) + { + #if CFG_TUH_HID_KEYBOARD + if ( HID_PROTOCOL_KEYBOARD == p_interface_desc->bInterfaceProtocol) + { + TU_ASSERT( hidh_interface_open(dev_addr, p_interface_desc->bInterfaceNumber, p_endpoint_desc, &keyboardh_data[dev_addr-1]) ); + tuh_hid_keyboard_mounted_cb(dev_addr); + } else + #endif + + #if CFG_TUH_HID_MOUSE + if ( HID_PROTOCOL_MOUSE == p_interface_desc->bInterfaceProtocol) + { + TU_ASSERT ( hidh_interface_open(dev_addr, p_interface_desc->bInterfaceNumber, p_endpoint_desc, &mouseh_data[dev_addr-1]) ); + tuh_hid_mouse_mounted_cb(dev_addr); + } else + #endif + + { + // Not supported protocol + return false; + } + }else + { + // Not supported subclass + return false; + } + + *p_length = sizeof(tusb_desc_interface_t) + sizeof(tusb_hid_descriptor_hid_t) + sizeof(tusb_desc_endpoint_t); + + return true; +} + +void hidh_isr(pipe_handle_t pipe_hdl, xfer_result_t event, uint32_t xferred_bytes) +{ + (void) xferred_bytes; // TODO may need to use this para later + +#if CFG_TUH_HID_KEYBOARD + if ( pipehandle_is_equal(pipe_hdl, keyboardh_data[pipe_hdl.dev_addr-1].pipe_hdl) ) + { + tuh_hid_keyboard_isr(pipe_hdl.dev_addr, event); + return; + } +#endif + +#if CFG_TUH_HID_MOUSE + if ( pipehandle_is_equal(pipe_hdl, mouseh_data[pipe_hdl.dev_addr-1].pipe_hdl) ) + { + tuh_hid_mouse_isr(pipe_hdl.dev_addr, event); + return; + } +#endif + +#if CFG_TUSB_HOST_HID_GENERIC + +#endif +} + +void hidh_close(uint8_t dev_addr) +{ +#if CFG_TUH_HID_KEYBOARD + if ( pipehandle_is_valid( keyboardh_data[dev_addr-1].pipe_hdl ) ) + { + hidh_interface_close(&keyboardh_data[dev_addr-1]); + tuh_hid_keyboard_unmounted_cb(dev_addr); + } +#endif + +#if CFG_TUH_HID_MOUSE + if( pipehandle_is_valid( mouseh_data[dev_addr-1].pipe_hdl ) ) + { + hidh_interface_close(&mouseh_data[dev_addr-1]); + tuh_hid_mouse_unmounted_cb( dev_addr ); + } +#endif + +#if CFG_TUSB_HOST_HID_GENERIC + hidh_generic_close(dev_addr); +#endif +} + + + +#endif diff --git a/src/class/hid/hid_host.h b/src/class/hid/hid_host.h index 1c619c57..a3b614cd 100644 --- a/src/class/hid/hid_host.h +++ b/src/class/hid/hid_host.h @@ -1,215 +1,215 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2019 Ha Thach (tinyusb.org) - * - * 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. - * - * This file is part of the TinyUSB stack. - */ - -/** \addtogroup ClassDriver_HID - * @{ */ - -#ifndef _TUSB_HID_HOST_H_ -#define _TUSB_HID_HOST_H_ - -#include "common/tusb_common.h" -#include "host/usbh.h" -#include "hid.h" - -#ifdef __cplusplus - extern "C" { -#endif - -//--------------------------------------------------------------------+ -// KEYBOARD Application API -//--------------------------------------------------------------------+ -/** \addtogroup ClassDriver_HID_Keyboard Keyboard - * @{ */ - -/** \defgroup Keyboard_Host Host - * The interface API includes status checking function, data transferring function and callback functions - * @{ */ - -extern uint8_t const hid_keycode_to_ascii_tbl[2][128]; // TODO used weak attr if build failed without KEYBOARD enabled - -/** \brief Check if device supports Keyboard interface or not - * \param[in] dev_addr device address - * \retval true if device supports Keyboard interface - * \retval false if device does not support Keyboard interface or is not mounted - */ -bool tuh_hid_keyboard_is_mounted(uint8_t dev_addr); - -/** \brief Check if the interface is currently busy or not - * \param[in] dev_addr device address - * \retval true if the interface is busy meaning the stack is still transferring/waiting data from/to device - * \retval false if the interface is not busy meaning the stack successfully transferred data from/to device - * \note This function is primarily used for polling/waiting result after \ref tuh_hid_keyboard_get_report. - * Alternatively, asynchronous event API can be used - */ -bool tuh_hid_keyboard_is_busy(uint8_t dev_addr); - -/** \brief Perform a get report from Keyboard interface - * \param[in] dev_addr device address - * \param[in,out] p_report address that is used to store data from device. Must be accessible by usb controller (see \ref CFG_TUSB_MEM_SECTION) - * \returns \ref tusb_error_t type to indicate success or error condition. - * \retval TUSB_ERROR_NONE on success - * \retval TUSB_ERROR_INTERFACE_IS_BUSY if the interface is already transferring data with device - * \retval TUSB_ERROR_DEVICE_NOT_READY if device is not yet configured (by SET CONFIGURED request) - * \retval TUSB_ERROR_INVALID_PARA if input parameters are not correct - * \note This function is non-blocking and returns immediately. The result of usb transfer will be reported by the interface's callback function - */ -tusb_error_t tuh_hid_keyboard_get_report(uint8_t dev_addr, void * p_report); - -//------------- Application Callback -------------// -/** \brief Callback function that is invoked when an transferring event occurred - * \param[in] dev_addr Address of device - * \param[in] event an value from \ref xfer_result_t - * \note event can be one of following - * - XFER_RESULT_SUCCESS : previously scheduled transfer completes successfully. - * - XFER_RESULT_FAILED : previously scheduled transfer encountered a transaction error. - * - XFER_RESULT_STALLED : previously scheduled transfer is stalled by device. - * \note Application should schedule the next report by calling \ref tuh_hid_keyboard_get_report within this callback - */ -void tuh_hid_keyboard_isr(uint8_t dev_addr, xfer_result_t event); - -/** \brief Callback function that will be invoked when a device with Keyboard interface is mounted - * \param[in] dev_addr Address of newly mounted device - * \note This callback should be used by Application to set-up interface-related data - */ -void tuh_hid_keyboard_mounted_cb(uint8_t dev_addr); - -/** \brief Callback function that will be invoked when a device with Keyboard interface is unmounted - * \param[in] dev_addr Address of newly unmounted device - * \note This callback should be used by Application to tear-down interface-related data - */ -void tuh_hid_keyboard_unmounted_cb(uint8_t dev_addr); - -/** @} */ // Keyboard_Host -/** @} */ // ClassDriver_HID_Keyboard - -//--------------------------------------------------------------------+ -// MOUSE Application API -//--------------------------------------------------------------------+ -/** \addtogroup ClassDriver_HID_Mouse Mouse - * @{ */ - -/** \defgroup Mouse_Host Host - * The interface API includes status checking function, data transferring function and callback functions - * @{ */ - -/** \brief Check if device supports Mouse interface or not - * \param[in] dev_addr device address - * \retval true if device supports Mouse interface - * \retval false if device does not support Mouse interface or is not mounted - */ -bool tuh_hid_mouse_is_mounted(uint8_t dev_addr); - -/** \brief Check if the interface is currently busy or not - * \param[in] dev_addr device address - * \retval true if the interface is busy meaning the stack is still transferring/waiting data from/to device - * \retval false if the interface is not busy meaning the stack successfully transferred data from/to device - * \note This function is primarily used for polling/waiting result after \ref tuh_hid_mouse_get_report. - * Alternatively, asynchronous event API can be used - */ -bool tuh_hid_mouse_is_busy(uint8_t dev_addr); - -/** \brief Perform a get report from Mouse interface - * \param[in] dev_addr device address - * \param[in,out] p_report address that is used to store data from device. Must be accessible by usb controller (see \ref CFG_TUSB_MEM_SECTION) - * \returns \ref tusb_error_t type to indicate success or error condition. - * \retval TUSB_ERROR_NONE on success - * \retval TUSB_ERROR_INTERFACE_IS_BUSY if the interface is already transferring data with device - * \retval TUSB_ERROR_DEVICE_NOT_READY if device is not yet configured (by SET CONFIGURED request) - * \retval TUSB_ERROR_INVALID_PARA if input parameters are not correct - * \note This function is non-blocking and returns immediately. The result of usb transfer will be reported by the interface's callback function - */ -tusb_error_t tuh_hid_mouse_get_report(uint8_t dev_addr, void* p_report); - -//------------- Application Callback -------------// -/** \brief Callback function that is invoked when an transferring event occurred - * \param[in] dev_addr Address of device - * \param[in] event an value from \ref xfer_result_t - * \note event can be one of following - * - XFER_RESULT_SUCCESS : previously scheduled transfer completes successfully. - * - XFER_RESULT_FAILED : previously scheduled transfer encountered a transaction error. - * - XFER_RESULT_STALLED : previously scheduled transfer is stalled by device. - * \note Application should schedule the next report by calling \ref tuh_hid_mouse_get_report within this callback - */ -void tuh_hid_mouse_isr(uint8_t dev_addr, xfer_result_t event); - -/** \brief Callback function that will be invoked when a device with Mouse interface is mounted - * \param[in] dev_addr Address of newly mounted device - * \note This callback should be used by Application to set-up interface-related data - */ -void tuh_hid_mouse_mounted_cb(uint8_t dev_addr); - -/** \brief Callback function that will be invoked when a device with Mouse interface is unmounted - * \param[in] dev_addr Address of newly unmounted device - * \note This callback should be used by Application to tear-down interface-related data - */ -void tuh_hid_mouse_unmounted_cb(uint8_t dev_addr); - -/** @} */ // Mouse_Host -/** @} */ // ClassDriver_HID_Mouse - -//--------------------------------------------------------------------+ -// GENERIC Application API -//--------------------------------------------------------------------+ -/** \addtogroup ClassDriver_HID_Generic Generic (not supported yet) - * @{ */ - -/** \defgroup Generic_Host Host - * The interface API includes status checking function, data transferring function and callback functions - * @{ */ - -bool tuh_hid_generic_is_mounted(uint8_t dev_addr); -tusb_error_t tuh_hid_generic_get_report(uint8_t dev_addr, void* p_report, bool int_on_complete); -tusb_error_t tuh_hid_generic_set_report(uint8_t dev_addr, void* p_report, bool int_on_complete); -tusb_interface_status_t tuh_hid_generic_get_status(uint8_t dev_addr); -tusb_interface_status_t tuh_hid_generic_set_status(uint8_t dev_addr); - -//------------- Application Callback -------------// -void tuh_hid_generic_isr(uint8_t dev_addr, xfer_result_t event); - -/** @} */ // Generic_Host -/** @} */ // ClassDriver_HID_Generic - -//--------------------------------------------------------------------+ -// Internal Class Driver API -//--------------------------------------------------------------------+ -typedef struct { - pipe_handle_t pipe_hdl; - uint16_t report_size; - uint8_t interface_number; -}hidh_interface_info_t; - -void hidh_init(void); -bool hidh_open_subtask(uint8_t dev_addr, tusb_desc_interface_t const *p_interface_desc, uint16_t *p_length); -void hidh_isr(pipe_handle_t pipe_hdl, xfer_result_t event, uint32_t xferred_bytes); -void hidh_close(uint8_t dev_addr); - -#ifdef __cplusplus -} -#endif - -#endif /* _TUSB_HID_HOST_H_ */ - -/** @} */ // ClassDriver_HID +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +/** \addtogroup ClassDriver_HID + * @{ */ + +#ifndef _TUSB_HID_HOST_H_ +#define _TUSB_HID_HOST_H_ + +#include "common/tusb_common.h" +#include "host/usbh.h" +#include "hid.h" + +#ifdef __cplusplus + extern "C" { +#endif + +//--------------------------------------------------------------------+ +// KEYBOARD Application API +//--------------------------------------------------------------------+ +/** \addtogroup ClassDriver_HID_Keyboard Keyboard + * @{ */ + +/** \defgroup Keyboard_Host Host + * The interface API includes status checking function, data transferring function and callback functions + * @{ */ + +extern uint8_t const hid_keycode_to_ascii_tbl[2][128]; // TODO used weak attr if build failed without KEYBOARD enabled + +/** \brief Check if device supports Keyboard interface or not + * \param[in] dev_addr device address + * \retval true if device supports Keyboard interface + * \retval false if device does not support Keyboard interface or is not mounted + */ +bool tuh_hid_keyboard_is_mounted(uint8_t dev_addr); + +/** \brief Check if the interface is currently busy or not + * \param[in] dev_addr device address + * \retval true if the interface is busy meaning the stack is still transferring/waiting data from/to device + * \retval false if the interface is not busy meaning the stack successfully transferred data from/to device + * \note This function is primarily used for polling/waiting result after \ref tuh_hid_keyboard_get_report. + * Alternatively, asynchronous event API can be used + */ +bool tuh_hid_keyboard_is_busy(uint8_t dev_addr); + +/** \brief Perform a get report from Keyboard interface + * \param[in] dev_addr device address + * \param[in,out] p_report address that is used to store data from device. Must be accessible by usb controller (see \ref CFG_TUSB_MEM_SECTION) + * \returns \ref tusb_error_t type to indicate success or error condition. + * \retval TUSB_ERROR_NONE on success + * \retval TUSB_ERROR_INTERFACE_IS_BUSY if the interface is already transferring data with device + * \retval TUSB_ERROR_DEVICE_NOT_READY if device is not yet configured (by SET CONFIGURED request) + * \retval TUSB_ERROR_INVALID_PARA if input parameters are not correct + * \note This function is non-blocking and returns immediately. The result of usb transfer will be reported by the interface's callback function + */ +tusb_error_t tuh_hid_keyboard_get_report(uint8_t dev_addr, void * p_report); + +//------------- Application Callback -------------// +/** \brief Callback function that is invoked when an transferring event occurred + * \param[in] dev_addr Address of device + * \param[in] event an value from \ref xfer_result_t + * \note event can be one of following + * - XFER_RESULT_SUCCESS : previously scheduled transfer completes successfully. + * - XFER_RESULT_FAILED : previously scheduled transfer encountered a transaction error. + * - XFER_RESULT_STALLED : previously scheduled transfer is stalled by device. + * \note Application should schedule the next report by calling \ref tuh_hid_keyboard_get_report within this callback + */ +void tuh_hid_keyboard_isr(uint8_t dev_addr, xfer_result_t event); + +/** \brief Callback function that will be invoked when a device with Keyboard interface is mounted + * \param[in] dev_addr Address of newly mounted device + * \note This callback should be used by Application to set-up interface-related data + */ +void tuh_hid_keyboard_mounted_cb(uint8_t dev_addr); + +/** \brief Callback function that will be invoked when a device with Keyboard interface is unmounted + * \param[in] dev_addr Address of newly unmounted device + * \note This callback should be used by Application to tear-down interface-related data + */ +void tuh_hid_keyboard_unmounted_cb(uint8_t dev_addr); + +/** @} */ // Keyboard_Host +/** @} */ // ClassDriver_HID_Keyboard + +//--------------------------------------------------------------------+ +// MOUSE Application API +//--------------------------------------------------------------------+ +/** \addtogroup ClassDriver_HID_Mouse Mouse + * @{ */ + +/** \defgroup Mouse_Host Host + * The interface API includes status checking function, data transferring function and callback functions + * @{ */ + +/** \brief Check if device supports Mouse interface or not + * \param[in] dev_addr device address + * \retval true if device supports Mouse interface + * \retval false if device does not support Mouse interface or is not mounted + */ +bool tuh_hid_mouse_is_mounted(uint8_t dev_addr); + +/** \brief Check if the interface is currently busy or not + * \param[in] dev_addr device address + * \retval true if the interface is busy meaning the stack is still transferring/waiting data from/to device + * \retval false if the interface is not busy meaning the stack successfully transferred data from/to device + * \note This function is primarily used for polling/waiting result after \ref tuh_hid_mouse_get_report. + * Alternatively, asynchronous event API can be used + */ +bool tuh_hid_mouse_is_busy(uint8_t dev_addr); + +/** \brief Perform a get report from Mouse interface + * \param[in] dev_addr device address + * \param[in,out] p_report address that is used to store data from device. Must be accessible by usb controller (see \ref CFG_TUSB_MEM_SECTION) + * \returns \ref tusb_error_t type to indicate success or error condition. + * \retval TUSB_ERROR_NONE on success + * \retval TUSB_ERROR_INTERFACE_IS_BUSY if the interface is already transferring data with device + * \retval TUSB_ERROR_DEVICE_NOT_READY if device is not yet configured (by SET CONFIGURED request) + * \retval TUSB_ERROR_INVALID_PARA if input parameters are not correct + * \note This function is non-blocking and returns immediately. The result of usb transfer will be reported by the interface's callback function + */ +tusb_error_t tuh_hid_mouse_get_report(uint8_t dev_addr, void* p_report); + +//------------- Application Callback -------------// +/** \brief Callback function that is invoked when an transferring event occurred + * \param[in] dev_addr Address of device + * \param[in] event an value from \ref xfer_result_t + * \note event can be one of following + * - XFER_RESULT_SUCCESS : previously scheduled transfer completes successfully. + * - XFER_RESULT_FAILED : previously scheduled transfer encountered a transaction error. + * - XFER_RESULT_STALLED : previously scheduled transfer is stalled by device. + * \note Application should schedule the next report by calling \ref tuh_hid_mouse_get_report within this callback + */ +void tuh_hid_mouse_isr(uint8_t dev_addr, xfer_result_t event); + +/** \brief Callback function that will be invoked when a device with Mouse interface is mounted + * \param[in] dev_addr Address of newly mounted device + * \note This callback should be used by Application to set-up interface-related data + */ +void tuh_hid_mouse_mounted_cb(uint8_t dev_addr); + +/** \brief Callback function that will be invoked when a device with Mouse interface is unmounted + * \param[in] dev_addr Address of newly unmounted device + * \note This callback should be used by Application to tear-down interface-related data + */ +void tuh_hid_mouse_unmounted_cb(uint8_t dev_addr); + +/** @} */ // Mouse_Host +/** @} */ // ClassDriver_HID_Mouse + +//--------------------------------------------------------------------+ +// GENERIC Application API +//--------------------------------------------------------------------+ +/** \addtogroup ClassDriver_HID_Generic Generic (not supported yet) + * @{ */ + +/** \defgroup Generic_Host Host + * The interface API includes status checking function, data transferring function and callback functions + * @{ */ + +bool tuh_hid_generic_is_mounted(uint8_t dev_addr); +tusb_error_t tuh_hid_generic_get_report(uint8_t dev_addr, void* p_report, bool int_on_complete); +tusb_error_t tuh_hid_generic_set_report(uint8_t dev_addr, void* p_report, bool int_on_complete); +tusb_interface_status_t tuh_hid_generic_get_status(uint8_t dev_addr); +tusb_interface_status_t tuh_hid_generic_set_status(uint8_t dev_addr); + +//------------- Application Callback -------------// +void tuh_hid_generic_isr(uint8_t dev_addr, xfer_result_t event); + +/** @} */ // Generic_Host +/** @} */ // ClassDriver_HID_Generic + +//--------------------------------------------------------------------+ +// Internal Class Driver API +//--------------------------------------------------------------------+ +typedef struct { + pipe_handle_t pipe_hdl; + uint16_t report_size; + uint8_t interface_number; +}hidh_interface_info_t; + +void hidh_init(void); +bool hidh_open_subtask(uint8_t dev_addr, tusb_desc_interface_t const *p_interface_desc, uint16_t *p_length); +void hidh_isr(pipe_handle_t pipe_hdl, xfer_result_t event, uint32_t xferred_bytes); +void hidh_close(uint8_t dev_addr); + +#ifdef __cplusplus +} +#endif + +#endif /* _TUSB_HID_HOST_H_ */ + +/** @} */ // ClassDriver_HID diff --git a/src/class/midi/midi.h b/src/class/midi/midi.h index b3cc17af..f758b6e1 100644 --- a/src/class/midi/midi.h +++ b/src/class/midi/midi.h @@ -1,167 +1,167 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2019 Ha Thach (tinyusb.org) - * - * 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. - * - * This file is part of the TinyUSB stack. - */ - -/** \ingroup group_class - * \defgroup ClassDriver_CDC Communication Device Class (CDC) - * Currently only Abstract Control Model subclass is supported - * @{ */ - -#ifndef _TUSB_MIDI_H__ -#define _TUSB_MIDI_H__ - -#include "common/tusb_common.h" - -#ifdef __cplusplus - extern "C" { -#endif - -//--------------------------------------------------------------------+ -// Class Specific Descriptor -//--------------------------------------------------------------------+ - -typedef enum -{ - MIDI_CS_INTERFACE_HEADER = 0x01, - MIDI_CS_INTERFACE_IN_JACK = 0x02, - MIDI_CS_INTERFACE_OUT_JACK = 0x03, - MIDI_CS_INTERFACE_ELEMENT = 0x04, -} midi_cs_interface_subtype_t; - -typedef enum -{ - MIDI_CS_ENDPOINT_GENERAL = 0x01 -} midi_cs_endpoint_subtype_t; - -typedef enum -{ - MIDI_JACK_EMBEDDED = 0x01, - MIDI_JACK_EXTERNAL = 0x02 -} midi_jack_type_t; - -/// MIDI Interface Header Descriptor -typedef struct TU_ATTR_PACKED -{ - uint8_t bLength ; ///< Size of this descriptor in bytes. - uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific - uint8_t bDescriptorSubType ; ///< Descriptor SubType - uint16_t bcdMSC ; ///< MidiStreaming SubClass release number in Binary-Coded Decimal - uint16_t wTotalLength ; -} midi_desc_header_t; - -/// MIDI In Jack Descriptor -typedef struct TU_ATTR_PACKED -{ - uint8_t bLength ; ///< Size of this descriptor in bytes. - uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific - uint8_t bDescriptorSubType ; ///< Descriptor SubType - uint8_t bJackType ; ///< Embedded or External - uint8_t bJackID ; ///< Unique ID for MIDI IN Jack - uint8_t iJack ; ///< string descriptor -} midi_desc_in_jack_t; - - -/// MIDI Out Jack Descriptor with single pin -typedef struct TU_ATTR_PACKED -{ - uint8_t bLength ; ///< Size of this descriptor in bytes. - uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific - uint8_t bDescriptorSubType ; ///< Descriptor SubType - uint8_t bJackType ; ///< Embedded or External - uint8_t bJackID ; ///< Unique ID for MIDI IN Jack - uint8_t bNrInputPins; - - uint8_t baSourceID; - uint8_t baSourcePin; - - uint8_t iJack ; ///< string descriptor -} midi_desc_out_jack_t ; - -/// MIDI Out Jack Descriptor with multiple pins -#define midi_desc_out_jack_n_t(input_num) \ - struct TU_ATTR_PACKED { \ - uint8_t bLength ; \ - uint8_t bDescriptorType ; \ - uint8_t bDescriptorSubType ; \ - uint8_t bJackType ; \ - uint8_t bJackID ; \ - uint8_t bNrInputPins ; \ - struct TU_ATTR_PACKED { \ - uint8_t baSourceID; \ - uint8_t baSourcePin; \ - } pins[input_num]; \ - uint8_t iJack ; \ - } - -/// MIDI Element Descriptor -typedef struct TU_ATTR_PACKED -{ - uint8_t bLength ; ///< Size of this descriptor in bytes. - uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific - uint8_t bDescriptorSubType ; ///< Descriptor SubType - uint8_t bElementID; - - uint8_t bNrInputPins; - uint8_t baSourceID; - uint8_t baSourcePin; - - uint8_t bNrOutputPins; - uint8_t bInTerminalLink; - uint8_t bOutTerminalLink; - uint8_t bElCapsSize; - - uint16_t bmElementCaps; - uint8_t iElement; -} midi_desc_element_t; - -/// MIDI Element Descriptor with multiple pins -#define midi_desc_element_n_t(input_num) \ - struct TU_ATTR_PACKED { \ - uint8_t bLength; \ - uint8_t bDescriptorType; \ - uint8_t bDescriptorSubType; \ - uint8_t bElementID; \ - uint8_t bNrInputPins; \ - struct TU_ATTR_PACKED { \ - uint8_t baSourceID; \ - uint8_t baSourcePin; \ - } pins[input_num]; \ - uint8_t bNrOutputPins; \ - uint8_t bInTerminalLink; \ - uint8_t bOutTerminalLink; \ - uint8_t bElCapsSize; \ - uint16_t bmElementCaps; \ - uint8_t iElement; \ - } - -/** @} */ - -#ifdef __cplusplus - } -#endif - -#endif - -/** @} */ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +/** \ingroup group_class + * \defgroup ClassDriver_CDC Communication Device Class (CDC) + * Currently only Abstract Control Model subclass is supported + * @{ */ + +#ifndef _TUSB_MIDI_H__ +#define _TUSB_MIDI_H__ + +#include "common/tusb_common.h" + +#ifdef __cplusplus + extern "C" { +#endif + +//--------------------------------------------------------------------+ +// Class Specific Descriptor +//--------------------------------------------------------------------+ + +typedef enum +{ + MIDI_CS_INTERFACE_HEADER = 0x01, + MIDI_CS_INTERFACE_IN_JACK = 0x02, + MIDI_CS_INTERFACE_OUT_JACK = 0x03, + MIDI_CS_INTERFACE_ELEMENT = 0x04, +} midi_cs_interface_subtype_t; + +typedef enum +{ + MIDI_CS_ENDPOINT_GENERAL = 0x01 +} midi_cs_endpoint_subtype_t; + +typedef enum +{ + MIDI_JACK_EMBEDDED = 0x01, + MIDI_JACK_EXTERNAL = 0x02 +} midi_jack_type_t; + +/// MIDI Interface Header Descriptor +typedef struct TU_ATTR_PACKED +{ + uint8_t bLength ; ///< Size of this descriptor in bytes. + uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific + uint8_t bDescriptorSubType ; ///< Descriptor SubType + uint16_t bcdMSC ; ///< MidiStreaming SubClass release number in Binary-Coded Decimal + uint16_t wTotalLength ; +} midi_desc_header_t; + +/// MIDI In Jack Descriptor +typedef struct TU_ATTR_PACKED +{ + uint8_t bLength ; ///< Size of this descriptor in bytes. + uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific + uint8_t bDescriptorSubType ; ///< Descriptor SubType + uint8_t bJackType ; ///< Embedded or External + uint8_t bJackID ; ///< Unique ID for MIDI IN Jack + uint8_t iJack ; ///< string descriptor +} midi_desc_in_jack_t; + + +/// MIDI Out Jack Descriptor with single pin +typedef struct TU_ATTR_PACKED +{ + uint8_t bLength ; ///< Size of this descriptor in bytes. + uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific + uint8_t bDescriptorSubType ; ///< Descriptor SubType + uint8_t bJackType ; ///< Embedded or External + uint8_t bJackID ; ///< Unique ID for MIDI IN Jack + uint8_t bNrInputPins; + + uint8_t baSourceID; + uint8_t baSourcePin; + + uint8_t iJack ; ///< string descriptor +} midi_desc_out_jack_t ; + +/// MIDI Out Jack Descriptor with multiple pins +#define midi_desc_out_jack_n_t(input_num) \ + struct TU_ATTR_PACKED { \ + uint8_t bLength ; \ + uint8_t bDescriptorType ; \ + uint8_t bDescriptorSubType ; \ + uint8_t bJackType ; \ + uint8_t bJackID ; \ + uint8_t bNrInputPins ; \ + struct TU_ATTR_PACKED { \ + uint8_t baSourceID; \ + uint8_t baSourcePin; \ + } pins[input_num]; \ + uint8_t iJack ; \ + } + +/// MIDI Element Descriptor +typedef struct TU_ATTR_PACKED +{ + uint8_t bLength ; ///< Size of this descriptor in bytes. + uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific + uint8_t bDescriptorSubType ; ///< Descriptor SubType + uint8_t bElementID; + + uint8_t bNrInputPins; + uint8_t baSourceID; + uint8_t baSourcePin; + + uint8_t bNrOutputPins; + uint8_t bInTerminalLink; + uint8_t bOutTerminalLink; + uint8_t bElCapsSize; + + uint16_t bmElementCaps; + uint8_t iElement; +} midi_desc_element_t; + +/// MIDI Element Descriptor with multiple pins +#define midi_desc_element_n_t(input_num) \ + struct TU_ATTR_PACKED { \ + uint8_t bLength; \ + uint8_t bDescriptorType; \ + uint8_t bDescriptorSubType; \ + uint8_t bElementID; \ + uint8_t bNrInputPins; \ + struct TU_ATTR_PACKED { \ + uint8_t baSourceID; \ + uint8_t baSourcePin; \ + } pins[input_num]; \ + uint8_t bNrOutputPins; \ + uint8_t bInTerminalLink; \ + uint8_t bOutTerminalLink; \ + uint8_t bElCapsSize; \ + uint16_t bmElementCaps; \ + uint8_t iElement; \ + } + +/** @} */ + +#ifdef __cplusplus + } +#endif + +#endif + +/** @} */ diff --git a/src/class/midi/midi_device.c b/src/class/midi/midi_device.c index 0c68f8e7..31240562 100644 --- a/src/class/midi/midi_device.c +++ b/src/class/midi/midi_device.c @@ -1,361 +1,361 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2019 Ha Thach (tinyusb.org) - * - * 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. - * - * This file is part of the TinyUSB stack. - */ - -#include "tusb_option.h" - -#if (TUSB_OPT_DEVICE_ENABLED && CFG_TUD_MIDI) - -//--------------------------------------------------------------------+ -// INCLUDE -//--------------------------------------------------------------------+ -#include "midi_device.h" -#include "class/audio/audio.h" -#include "device/usbd_pvt.h" - -//--------------------------------------------------------------------+ -// MACRO CONSTANT TYPEDEF -//--------------------------------------------------------------------+ -typedef struct -{ - uint8_t itf_num; - uint8_t ep_in; - uint8_t ep_out; - - /*------------- From this point, data is not cleared by bus reset -------------*/ - // FIFO - tu_fifo_t rx_ff; - tu_fifo_t tx_ff; - uint8_t rx_ff_buf[CFG_TUD_MIDI_RX_BUFSIZE]; - uint8_t tx_ff_buf[CFG_TUD_MIDI_TX_BUFSIZE]; - - #if CFG_FIFO_MUTEX - osal_mutex_def_t rx_ff_mutex; - osal_mutex_def_t tx_ff_mutex; - #endif - - // We need to pack messages into words before queueing their transmission so buffer across write - // calls. - uint8_t message_buffer[4]; - uint8_t message_buffer_length; - uint8_t message_target_length; - - // Endpoint Transfer buffer - CFG_TUSB_MEM_ALIGN uint8_t epout_buf[CFG_TUD_MIDI_EPSIZE]; - CFG_TUSB_MEM_ALIGN uint8_t epin_buf[CFG_TUD_MIDI_EPSIZE]; - -} midid_interface_t; - -#define ITF_MEM_RESET_SIZE offsetof(midid_interface_t, rx_ff) - -//--------------------------------------------------------------------+ -// INTERNAL OBJECT & FUNCTION DECLARATION -//--------------------------------------------------------------------+ -CFG_TUSB_MEM_SECTION midid_interface_t _midid_itf[CFG_TUD_MIDI]; - -bool tud_midi_n_mounted (uint8_t itf) -{ - midid_interface_t* midi = &_midid_itf[itf]; - return midi->ep_in && midi->ep_out; -} - -//--------------------------------------------------------------------+ -// READ API -//--------------------------------------------------------------------+ -uint32_t tud_midi_n_available(uint8_t itf, uint8_t jack_id) -{ - (void) jack_id; - return tu_fifo_count(&_midid_itf[itf].rx_ff); -} - -uint32_t tud_midi_n_read(uint8_t itf, uint8_t jack_id, void* buffer, uint32_t bufsize) -{ - (void) jack_id; - return tu_fifo_read_n(&_midid_itf[itf].rx_ff, buffer, bufsize); -} - -void tud_midi_n_read_flush (uint8_t itf, uint8_t jack_id) -{ - (void) jack_id; - tu_fifo_clear(&_midid_itf[itf].rx_ff); -} - -void midi_rx_done_cb(midid_interface_t* midi, uint8_t const* buffer, uint32_t bufsize) { - if (bufsize % 4 != 0) { - return; - } - - for(uint32_t i=0; i> 4; - uint8_t code_index = header & 0x0f; - // We always copy over the first byte. - uint8_t count = 1; - // Ignore subsequent bytes based on the code. - if (code_index != 0x5 && code_index != 0xf) { - count = 2; - if (code_index != 0x2 && code_index != 0x6 && code_index != 0xc && code_index != 0xd) { - count = 3; - } - } - tu_fifo_write_n(&midi->rx_ff, &buffer[i + 1], count); - } -} - - -//--------------------------------------------------------------------+ -// WRITE API -//--------------------------------------------------------------------+ - -static bool maybe_transmit(midid_interface_t* midi, uint8_t itf_index) -{ - (void) itf_index; - - // skip if previous transfer not complete - TU_VERIFY( !usbd_edpt_busy(TUD_OPT_RHPORT, midi->ep_in) ); - - uint16_t count = tu_fifo_read_n(&midi->tx_ff, midi->epin_buf, CFG_TUD_MIDI_EPSIZE); - if (count > 0) - { - TU_ASSERT( usbd_edpt_xfer(TUD_OPT_RHPORT, midi->ep_in, midi->epin_buf, count) ); - } - return true; -} - -uint32_t tud_midi_n_write(uint8_t itf, uint8_t jack_id, uint8_t const* buffer, uint32_t bufsize) -{ - midid_interface_t* midi = &_midid_itf[itf]; - if (midi->itf_num == 0) { - return 0; - } - - uint32_t i = 0; - while (i < bufsize) { - uint8_t data = buffer[i]; - if (midi->message_buffer_length == 0) { - uint8_t msg = data >> 4; - midi->message_buffer[1] = data; - midi->message_buffer_length = 2; - // Check to see if we're still in a SysEx transmit. - if (midi->message_buffer[0] == 0x4) { - if (data == 0xf7) { - midi->message_buffer[0] = 0x5; - } else { - midi->message_buffer_length = 4; - } - } else if ((msg >= 0x8 && msg <= 0xB) || msg == 0xE) { - midi->message_buffer[0] = jack_id << 4 | msg; - midi->message_target_length = 4; - } else if (msg == 0xC || msg == 0xD) { - midi->message_buffer[0] = jack_id << 4 | msg; - midi->message_target_length = 3; - } else if (msg == 0xf) { - if (data == 0xf0) { - midi->message_buffer[0] = 0x4; - midi->message_target_length = 4; - } else if (data == 0xf1 || data == 0xf3) { - midi->message_buffer[0] = 0x2; - midi->message_target_length = 3; - } else if (data == 0xf2) { - midi->message_buffer[0] = 0x3; - midi->message_target_length = 4; - } else { - midi->message_buffer[0] = 0x5; - midi->message_target_length = 2; - } - } else { - // Pack individual bytes if we don't support packing them into words. - midi->message_buffer[0] = jack_id << 4 | 0xf; - midi->message_buffer[2] = 0; - midi->message_buffer[3] = 0; - midi->message_buffer_length = 2; - midi->message_target_length = 2; - } - } else { - midi->message_buffer[midi->message_buffer_length] = data; - midi->message_buffer_length += 1; - // See if this byte ends a SysEx. - if (midi->message_buffer[0] == 0x4 && data == 0xf7) { - midi->message_buffer[0] = 0x4 + (midi->message_buffer_length - 1); - midi->message_target_length = midi->message_buffer_length; - } - } - - if (midi->message_buffer_length == midi->message_target_length) { - uint16_t written = tu_fifo_write_n(&midi->tx_ff, midi->message_buffer, 4); - if (written < 4) { - TU_ASSERT( written == 0 ); - break; - } - midi->message_buffer_length = 0; - } - i++; - } - maybe_transmit(midi, itf); - - return i; -} - -//--------------------------------------------------------------------+ -// USBD Driver API -//--------------------------------------------------------------------+ -void midid_init(void) -{ - tu_memclr(_midid_itf, sizeof(_midid_itf)); - - for(uint8_t i=0; irx_ff, midi->rx_ff_buf, CFG_TUD_MIDI_RX_BUFSIZE, 1, true); - tu_fifo_config(&midi->tx_ff, midi->tx_ff_buf, CFG_TUD_MIDI_TX_BUFSIZE, 1, true); - - #if CFG_FIFO_MUTEX - tu_fifo_config_mutex(&midi->rx_ff, osal_mutex_create(&midi->rx_ff_mutex)); - tu_fifo_config_mutex(&midi->tx_ff, osal_mutex_create(&midi->tx_ff_mutex)); - #endif - } -} - -void midid_reset(uint8_t rhport) -{ - (void) rhport; - - for(uint8_t i=0; irx_ff); - tu_fifo_clear(&midi->tx_ff); - } -} - -bool midid_open(uint8_t rhport, tusb_desc_interface_t const * p_interface_desc, uint16_t *p_length) -{ - // For now handle the audio control interface as well. - if ( AUDIO_SUBCLASS_CONTROL == p_interface_desc->bInterfaceSubClass) { - uint8_t const * p_desc = tu_desc_next ( (uint8_t const *) p_interface_desc ); - (*p_length) = sizeof(tusb_desc_interface_t); - - // Skip over the class specific descriptor. - (*p_length) += tu_desc_len(p_desc); - p_desc = tu_desc_next(p_desc); - return true; - } - - TU_VERIFY(AUDIO_SUBCLASS_MIDI_STREAMING == p_interface_desc->bInterfaceSubClass && - AUDIO_PROTOCOL_V1 == p_interface_desc->bInterfaceProtocol ); - - // Find available interface - midid_interface_t * p_midi = NULL; - for(uint8_t i=0; iitf_num = p_interface_desc->bInterfaceNumber; - - uint8_t const * p_desc = tu_desc_next( (uint8_t const *) p_interface_desc ); - (*p_length) = sizeof(tusb_desc_interface_t); - - uint8_t found_endpoints = 0; - while (found_endpoints < p_interface_desc->bNumEndpoints) - { - if ( TUSB_DESC_ENDPOINT == p_desc[DESC_OFFSET_TYPE]) - { - TU_ASSERT( dcd_edpt_open(rhport, (tusb_desc_endpoint_t const *) p_desc), false); - uint8_t ep_addr = ((tusb_desc_endpoint_t const *) p_desc)->bEndpointAddress; - if (tu_edpt_dir(ep_addr) == TUSB_DIR_IN) { - p_midi->ep_in = ep_addr; - } else { - p_midi->ep_out = ep_addr; - } - - (*p_length) += p_desc[DESC_OFFSET_LEN]; - p_desc = tu_desc_next(p_desc); - found_endpoints += 1; - } - (*p_length) += p_desc[DESC_OFFSET_LEN]; - p_desc = tu_desc_next(p_desc); - } - - // Prepare for incoming data - TU_ASSERT( usbd_edpt_xfer(rhport, p_midi->ep_out, p_midi->epout_buf, CFG_TUD_MIDI_EPSIZE), false); - - return true; -} - -bool midid_control_complete(uint8_t rhport, tusb_control_request_t const * p_request) -{ - (void) rhport; - (void) p_request; - return true; -} - -bool midid_control_request(uint8_t rhport, tusb_control_request_t const * p_request) -{ - (void) rhport; - (void) p_request; - - // driver doesn't support any request yet - return false; -} - -bool midid_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes) -{ - (void) result; - - uint8_t itf = 0; - midid_interface_t* p_midi = _midid_itf; - - for ( ; ; itf++, p_midi++) - { - if (itf >= TU_ARRAY_SIZE(_midid_itf)) return false; - - if ( ep_addr == p_midi->ep_out ) break; - } - - // receive new data - if ( ep_addr == p_midi->ep_out ) - { - midi_rx_done_cb(p_midi, p_midi->epout_buf, xferred_bytes); - - // prepare for next - TU_ASSERT( usbd_edpt_xfer(rhport, p_midi->ep_out, p_midi->epout_buf, CFG_TUD_MIDI_EPSIZE), false ); - } else if ( ep_addr == p_midi->ep_in ) { - maybe_transmit(p_midi, itf); - } - - // nothing to do with in and notif endpoint - - return TUSB_ERROR_NONE; -} - -#endif +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#include "tusb_option.h" + +#if (TUSB_OPT_DEVICE_ENABLED && CFG_TUD_MIDI) + +//--------------------------------------------------------------------+ +// INCLUDE +//--------------------------------------------------------------------+ +#include "midi_device.h" +#include "class/audio/audio.h" +#include "device/usbd_pvt.h" + +//--------------------------------------------------------------------+ +// MACRO CONSTANT TYPEDEF +//--------------------------------------------------------------------+ +typedef struct +{ + uint8_t itf_num; + uint8_t ep_in; + uint8_t ep_out; + + /*------------- From this point, data is not cleared by bus reset -------------*/ + // FIFO + tu_fifo_t rx_ff; + tu_fifo_t tx_ff; + uint8_t rx_ff_buf[CFG_TUD_MIDI_RX_BUFSIZE]; + uint8_t tx_ff_buf[CFG_TUD_MIDI_TX_BUFSIZE]; + + #if CFG_FIFO_MUTEX + osal_mutex_def_t rx_ff_mutex; + osal_mutex_def_t tx_ff_mutex; + #endif + + // We need to pack messages into words before queueing their transmission so buffer across write + // calls. + uint8_t message_buffer[4]; + uint8_t message_buffer_length; + uint8_t message_target_length; + + // Endpoint Transfer buffer + CFG_TUSB_MEM_ALIGN uint8_t epout_buf[CFG_TUD_MIDI_EPSIZE]; + CFG_TUSB_MEM_ALIGN uint8_t epin_buf[CFG_TUD_MIDI_EPSIZE]; + +} midid_interface_t; + +#define ITF_MEM_RESET_SIZE offsetof(midid_interface_t, rx_ff) + +//--------------------------------------------------------------------+ +// INTERNAL OBJECT & FUNCTION DECLARATION +//--------------------------------------------------------------------+ +CFG_TUSB_MEM_SECTION midid_interface_t _midid_itf[CFG_TUD_MIDI]; + +bool tud_midi_n_mounted (uint8_t itf) +{ + midid_interface_t* midi = &_midid_itf[itf]; + return midi->ep_in && midi->ep_out; +} + +//--------------------------------------------------------------------+ +// READ API +//--------------------------------------------------------------------+ +uint32_t tud_midi_n_available(uint8_t itf, uint8_t jack_id) +{ + (void) jack_id; + return tu_fifo_count(&_midid_itf[itf].rx_ff); +} + +uint32_t tud_midi_n_read(uint8_t itf, uint8_t jack_id, void* buffer, uint32_t bufsize) +{ + (void) jack_id; + return tu_fifo_read_n(&_midid_itf[itf].rx_ff, buffer, bufsize); +} + +void tud_midi_n_read_flush (uint8_t itf, uint8_t jack_id) +{ + (void) jack_id; + tu_fifo_clear(&_midid_itf[itf].rx_ff); +} + +void midi_rx_done_cb(midid_interface_t* midi, uint8_t const* buffer, uint32_t bufsize) { + if (bufsize % 4 != 0) { + return; + } + + for(uint32_t i=0; i> 4; + uint8_t code_index = header & 0x0f; + // We always copy over the first byte. + uint8_t count = 1; + // Ignore subsequent bytes based on the code. + if (code_index != 0x5 && code_index != 0xf) { + count = 2; + if (code_index != 0x2 && code_index != 0x6 && code_index != 0xc && code_index != 0xd) { + count = 3; + } + } + tu_fifo_write_n(&midi->rx_ff, &buffer[i + 1], count); + } +} + + +//--------------------------------------------------------------------+ +// WRITE API +//--------------------------------------------------------------------+ + +static bool maybe_transmit(midid_interface_t* midi, uint8_t itf_index) +{ + (void) itf_index; + + // skip if previous transfer not complete + TU_VERIFY( !usbd_edpt_busy(TUD_OPT_RHPORT, midi->ep_in) ); + + uint16_t count = tu_fifo_read_n(&midi->tx_ff, midi->epin_buf, CFG_TUD_MIDI_EPSIZE); + if (count > 0) + { + TU_ASSERT( usbd_edpt_xfer(TUD_OPT_RHPORT, midi->ep_in, midi->epin_buf, count) ); + } + return true; +} + +uint32_t tud_midi_n_write(uint8_t itf, uint8_t jack_id, uint8_t const* buffer, uint32_t bufsize) +{ + midid_interface_t* midi = &_midid_itf[itf]; + if (midi->itf_num == 0) { + return 0; + } + + uint32_t i = 0; + while (i < bufsize) { + uint8_t data = buffer[i]; + if (midi->message_buffer_length == 0) { + uint8_t msg = data >> 4; + midi->message_buffer[1] = data; + midi->message_buffer_length = 2; + // Check to see if we're still in a SysEx transmit. + if (midi->message_buffer[0] == 0x4) { + if (data == 0xf7) { + midi->message_buffer[0] = 0x5; + } else { + midi->message_buffer_length = 4; + } + } else if ((msg >= 0x8 && msg <= 0xB) || msg == 0xE) { + midi->message_buffer[0] = jack_id << 4 | msg; + midi->message_target_length = 4; + } else if (msg == 0xC || msg == 0xD) { + midi->message_buffer[0] = jack_id << 4 | msg; + midi->message_target_length = 3; + } else if (msg == 0xf) { + if (data == 0xf0) { + midi->message_buffer[0] = 0x4; + midi->message_target_length = 4; + } else if (data == 0xf1 || data == 0xf3) { + midi->message_buffer[0] = 0x2; + midi->message_target_length = 3; + } else if (data == 0xf2) { + midi->message_buffer[0] = 0x3; + midi->message_target_length = 4; + } else { + midi->message_buffer[0] = 0x5; + midi->message_target_length = 2; + } + } else { + // Pack individual bytes if we don't support packing them into words. + midi->message_buffer[0] = jack_id << 4 | 0xf; + midi->message_buffer[2] = 0; + midi->message_buffer[3] = 0; + midi->message_buffer_length = 2; + midi->message_target_length = 2; + } + } else { + midi->message_buffer[midi->message_buffer_length] = data; + midi->message_buffer_length += 1; + // See if this byte ends a SysEx. + if (midi->message_buffer[0] == 0x4 && data == 0xf7) { + midi->message_buffer[0] = 0x4 + (midi->message_buffer_length - 1); + midi->message_target_length = midi->message_buffer_length; + } + } + + if (midi->message_buffer_length == midi->message_target_length) { + uint16_t written = tu_fifo_write_n(&midi->tx_ff, midi->message_buffer, 4); + if (written < 4) { + TU_ASSERT( written == 0 ); + break; + } + midi->message_buffer_length = 0; + } + i++; + } + maybe_transmit(midi, itf); + + return i; +} + +//--------------------------------------------------------------------+ +// USBD Driver API +//--------------------------------------------------------------------+ +void midid_init(void) +{ + tu_memclr(_midid_itf, sizeof(_midid_itf)); + + for(uint8_t i=0; irx_ff, midi->rx_ff_buf, CFG_TUD_MIDI_RX_BUFSIZE, 1, true); + tu_fifo_config(&midi->tx_ff, midi->tx_ff_buf, CFG_TUD_MIDI_TX_BUFSIZE, 1, true); + + #if CFG_FIFO_MUTEX + tu_fifo_config_mutex(&midi->rx_ff, osal_mutex_create(&midi->rx_ff_mutex)); + tu_fifo_config_mutex(&midi->tx_ff, osal_mutex_create(&midi->tx_ff_mutex)); + #endif + } +} + +void midid_reset(uint8_t rhport) +{ + (void) rhport; + + for(uint8_t i=0; irx_ff); + tu_fifo_clear(&midi->tx_ff); + } +} + +bool midid_open(uint8_t rhport, tusb_desc_interface_t const * p_interface_desc, uint16_t *p_length) +{ + // For now handle the audio control interface as well. + if ( AUDIO_SUBCLASS_CONTROL == p_interface_desc->bInterfaceSubClass) { + uint8_t const * p_desc = tu_desc_next ( (uint8_t const *) p_interface_desc ); + (*p_length) = sizeof(tusb_desc_interface_t); + + // Skip over the class specific descriptor. + (*p_length) += tu_desc_len(p_desc); + p_desc = tu_desc_next(p_desc); + return true; + } + + TU_VERIFY(AUDIO_SUBCLASS_MIDI_STREAMING == p_interface_desc->bInterfaceSubClass && + AUDIO_PROTOCOL_V1 == p_interface_desc->bInterfaceProtocol ); + + // Find available interface + midid_interface_t * p_midi = NULL; + for(uint8_t i=0; iitf_num = p_interface_desc->bInterfaceNumber; + + uint8_t const * p_desc = tu_desc_next( (uint8_t const *) p_interface_desc ); + (*p_length) = sizeof(tusb_desc_interface_t); + + uint8_t found_endpoints = 0; + while (found_endpoints < p_interface_desc->bNumEndpoints) + { + if ( TUSB_DESC_ENDPOINT == p_desc[DESC_OFFSET_TYPE]) + { + TU_ASSERT( dcd_edpt_open(rhport, (tusb_desc_endpoint_t const *) p_desc), false); + uint8_t ep_addr = ((tusb_desc_endpoint_t const *) p_desc)->bEndpointAddress; + if (tu_edpt_dir(ep_addr) == TUSB_DIR_IN) { + p_midi->ep_in = ep_addr; + } else { + p_midi->ep_out = ep_addr; + } + + (*p_length) += p_desc[DESC_OFFSET_LEN]; + p_desc = tu_desc_next(p_desc); + found_endpoints += 1; + } + (*p_length) += p_desc[DESC_OFFSET_LEN]; + p_desc = tu_desc_next(p_desc); + } + + // Prepare for incoming data + TU_ASSERT( usbd_edpt_xfer(rhport, p_midi->ep_out, p_midi->epout_buf, CFG_TUD_MIDI_EPSIZE), false); + + return true; +} + +bool midid_control_complete(uint8_t rhport, tusb_control_request_t const * p_request) +{ + (void) rhport; + (void) p_request; + return true; +} + +bool midid_control_request(uint8_t rhport, tusb_control_request_t const * p_request) +{ + (void) rhport; + (void) p_request; + + // driver doesn't support any request yet + return false; +} + +bool midid_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes) +{ + (void) result; + + uint8_t itf = 0; + midid_interface_t* p_midi = _midid_itf; + + for ( ; ; itf++, p_midi++) + { + if (itf >= TU_ARRAY_SIZE(_midid_itf)) return false; + + if ( ep_addr == p_midi->ep_out ) break; + } + + // receive new data + if ( ep_addr == p_midi->ep_out ) + { + midi_rx_done_cb(p_midi, p_midi->epout_buf, xferred_bytes); + + // prepare for next + TU_ASSERT( usbd_edpt_xfer(rhport, p_midi->ep_out, p_midi->epout_buf, CFG_TUD_MIDI_EPSIZE), false ); + } else if ( ep_addr == p_midi->ep_in ) { + maybe_transmit(p_midi, itf); + } + + // nothing to do with in and notif endpoint + + return TUSB_ERROR_NONE; +} + +#endif diff --git a/src/class/midi/midi_device.h b/src/class/midi/midi_device.h index 6d9b292a..fbf4bce0 100644 --- a/src/class/midi/midi_device.h +++ b/src/class/midi/midi_device.h @@ -1,138 +1,138 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2019 Ha Thach (tinyusb.org) - * - * 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. - * - * This file is part of the TinyUSB stack. - */ - -#ifndef _TUSB_MIDI_DEVICE_H_ -#define _TUSB_MIDI_DEVICE_H_ - -#include "common/tusb_common.h" -#include "device/usbd.h" - -#include "class/audio/audio.h" -#include "midi.h" - -//--------------------------------------------------------------------+ -// Class Driver Configuration -//--------------------------------------------------------------------+ -#ifndef CFG_TUD_MIDI_EPSIZE -#define CFG_TUD_MIDI_EPSIZE 64 -#endif - -#ifdef __cplusplus - extern "C" { -#endif - -/** \addtogroup MIDI_Serial Serial - * @{ - * \defgroup MIDI_Serial_Device Device - * @{ */ - -//--------------------------------------------------------------------+ -// Application API (Multiple Interfaces) -// CFG_TUD_MIDI > 1 -//--------------------------------------------------------------------+ -bool tud_midi_n_mounted (uint8_t itf); -uint32_t tud_midi_n_available (uint8_t itf, uint8_t jack_id); -uint32_t tud_midi_n_read (uint8_t itf, uint8_t jack_id, void* buffer, uint32_t bufsize); -void tud_midi_n_read_flush (uint8_t itf, uint8_t jack_id); -uint32_t tud_midi_n_write (uint8_t itf, uint8_t jack_id, uint8_t const* buffer, uint32_t bufsize); - -static inline -uint32_t tud_midi_n_write24 (uint8_t itf, uint8_t jack_id, uint8_t b1, uint8_t b2, uint8_t b3); - -//--------------------------------------------------------------------+ -// Application API (Interface0) -//--------------------------------------------------------------------+ -static inline bool tud_midi_mounted (void); -static inline uint32_t tud_midi_available (void); -static inline uint32_t tud_midi_read (void* buffer, uint32_t bufsize); -static inline void tud_midi_read_flush (void); -static inline uint32_t tud_midi_write (uint8_t jack_id, uint8_t const* buffer, uint32_t bufsize); -static inline uint32_t tudi_midi_write24 (uint8_t jack_id, uint8_t b1, uint8_t b2, uint8_t b3); - -//--------------------------------------------------------------------+ -// Application Callback API (weak is optional) -//--------------------------------------------------------------------+ -TU_ATTR_WEAK void tud_midi_rx_cb(uint8_t itf); - -//--------------------------------------------------------------------+ -// Inline Functions -//--------------------------------------------------------------------+ - -static inline uint32_t tud_midi_n_write24 (uint8_t itf, uint8_t jack_id, uint8_t b1, uint8_t b2, uint8_t b3) -{ - uint8_t msg[3] = { b1, b2, b3 }; - return tud_midi_n_write(itf, jack_id, msg, 3); -} - -static inline bool tud_midi_mounted (void) -{ - return tud_midi_n_mounted(0); -} - -static inline uint32_t tud_midi_available (void) -{ - return tud_midi_n_available(0, 0); -} - -static inline uint32_t tud_midi_read (void* buffer, uint32_t bufsize) -{ - return tud_midi_n_read(0, 0, buffer, bufsize); -} - -static inline void tud_midi_read_flush (void) -{ - tud_midi_n_read_flush(0, 0); -} - -static inline uint32_t tud_midi_write (uint8_t jack_id, uint8_t const* buffer, uint32_t bufsize) -{ - return tud_midi_n_write(0, jack_id, buffer, bufsize); -} - -static inline uint32_t tudi_midi_write24 (uint8_t jack_id, uint8_t b1, uint8_t b2, uint8_t b3) -{ - uint8_t msg[3] = { b1, b2, b3 }; - return tud_midi_write(jack_id, msg, 3); -} - -//--------------------------------------------------------------------+ -// Internal Class Driver API -//--------------------------------------------------------------------+ -void midid_init (void); -void midid_reset (uint8_t rhport); -bool midid_open (uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t *p_length); -bool midid_control_request (uint8_t rhport, tusb_control_request_t const * request); -bool midid_control_complete (uint8_t rhport, tusb_control_request_t const * request); -bool midid_xfer_cb (uint8_t rhport, uint8_t edpt_addr, xfer_result_t result, uint32_t xferred_bytes); - -#ifdef __cplusplus - } -#endif - -#endif /* _TUSB_MIDI_DEVICE_H_ */ - -/** @} */ -/** @} */ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#ifndef _TUSB_MIDI_DEVICE_H_ +#define _TUSB_MIDI_DEVICE_H_ + +#include "common/tusb_common.h" +#include "device/usbd.h" + +#include "class/audio/audio.h" +#include "midi.h" + +//--------------------------------------------------------------------+ +// Class Driver Configuration +//--------------------------------------------------------------------+ +#ifndef CFG_TUD_MIDI_EPSIZE +#define CFG_TUD_MIDI_EPSIZE 64 +#endif + +#ifdef __cplusplus + extern "C" { +#endif + +/** \addtogroup MIDI_Serial Serial + * @{ + * \defgroup MIDI_Serial_Device Device + * @{ */ + +//--------------------------------------------------------------------+ +// Application API (Multiple Interfaces) +// CFG_TUD_MIDI > 1 +//--------------------------------------------------------------------+ +bool tud_midi_n_mounted (uint8_t itf); +uint32_t tud_midi_n_available (uint8_t itf, uint8_t jack_id); +uint32_t tud_midi_n_read (uint8_t itf, uint8_t jack_id, void* buffer, uint32_t bufsize); +void tud_midi_n_read_flush (uint8_t itf, uint8_t jack_id); +uint32_t tud_midi_n_write (uint8_t itf, uint8_t jack_id, uint8_t const* buffer, uint32_t bufsize); + +static inline +uint32_t tud_midi_n_write24 (uint8_t itf, uint8_t jack_id, uint8_t b1, uint8_t b2, uint8_t b3); + +//--------------------------------------------------------------------+ +// Application API (Interface0) +//--------------------------------------------------------------------+ +static inline bool tud_midi_mounted (void); +static inline uint32_t tud_midi_available (void); +static inline uint32_t tud_midi_read (void* buffer, uint32_t bufsize); +static inline void tud_midi_read_flush (void); +static inline uint32_t tud_midi_write (uint8_t jack_id, uint8_t const* buffer, uint32_t bufsize); +static inline uint32_t tudi_midi_write24 (uint8_t jack_id, uint8_t b1, uint8_t b2, uint8_t b3); + +//--------------------------------------------------------------------+ +// Application Callback API (weak is optional) +//--------------------------------------------------------------------+ +TU_ATTR_WEAK void tud_midi_rx_cb(uint8_t itf); + +//--------------------------------------------------------------------+ +// Inline Functions +//--------------------------------------------------------------------+ + +static inline uint32_t tud_midi_n_write24 (uint8_t itf, uint8_t jack_id, uint8_t b1, uint8_t b2, uint8_t b3) +{ + uint8_t msg[3] = { b1, b2, b3 }; + return tud_midi_n_write(itf, jack_id, msg, 3); +} + +static inline bool tud_midi_mounted (void) +{ + return tud_midi_n_mounted(0); +} + +static inline uint32_t tud_midi_available (void) +{ + return tud_midi_n_available(0, 0); +} + +static inline uint32_t tud_midi_read (void* buffer, uint32_t bufsize) +{ + return tud_midi_n_read(0, 0, buffer, bufsize); +} + +static inline void tud_midi_read_flush (void) +{ + tud_midi_n_read_flush(0, 0); +} + +static inline uint32_t tud_midi_write (uint8_t jack_id, uint8_t const* buffer, uint32_t bufsize) +{ + return tud_midi_n_write(0, jack_id, buffer, bufsize); +} + +static inline uint32_t tudi_midi_write24 (uint8_t jack_id, uint8_t b1, uint8_t b2, uint8_t b3) +{ + uint8_t msg[3] = { b1, b2, b3 }; + return tud_midi_write(jack_id, msg, 3); +} + +//--------------------------------------------------------------------+ +// Internal Class Driver API +//--------------------------------------------------------------------+ +void midid_init (void); +void midid_reset (uint8_t rhport); +bool midid_open (uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t *p_length); +bool midid_control_request (uint8_t rhport, tusb_control_request_t const * request); +bool midid_control_complete (uint8_t rhport, tusb_control_request_t const * request); +bool midid_xfer_cb (uint8_t rhport, uint8_t edpt_addr, xfer_result_t result, uint32_t xferred_bytes); + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_MIDI_DEVICE_H_ */ + +/** @} */ +/** @} */ diff --git a/src/class/msc/msc.h b/src/class/msc/msc.h index d461513f..cba8066b 100644 --- a/src/class/msc/msc.h +++ b/src/class/msc/msc.h @@ -1,392 +1,392 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2019 Ha Thach (tinyusb.org) - * - * 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. - * - * This file is part of the TinyUSB stack. - */ - -/** \ingroup group_class - * \defgroup ClassDriver_MSC MassStorage (MSC) - * @{ */ - -/** \defgroup ClassDriver_MSC_Common Common Definitions - * @{ */ - -#ifndef _TUSB_MSC_H_ -#define _TUSB_MSC_H_ - -#include "common/tusb_common.h" - -#ifdef __cplusplus - extern "C" { -#endif - -//--------------------------------------------------------------------+ -// Mass Storage Class Constant -//--------------------------------------------------------------------+ -/// MassStorage Subclass -typedef enum -{ - MSC_SUBCLASS_RBC = 1 , ///< Reduced Block Commands (RBC) T10 Project 1240-D - MSC_SUBCLASS_SFF_MMC , ///< SFF-8020i, MMC-2 (ATAPI). Typically used by a CD/DVD device - MSC_SUBCLASS_QIC , ///< QIC-157. Typically used by a tape device - MSC_SUBCLASS_UFI , ///< UFI. Typically used by Floppy Disk Drive (FDD) device - MSC_SUBCLASS_SFF , ///< SFF-8070i. Can be used by Floppy Disk Drive (FDD) device - MSC_SUBCLASS_SCSI ///< SCSI transparent command set -}msc_subclass_type_t; - -enum { - MSC_CBW_SIGNATURE = 0x43425355, ///< Constant value of 43425355h (little endian) - MSC_CSW_SIGNATURE = 0x53425355 ///< Constant value of 53425355h (little endian) -}; - -/// \brief MassStorage Protocol. -/// \details CBI only approved to use with full-speed floopy disk & should not used with highspeed or device other than floopy -typedef enum -{ - MSC_PROTOCOL_CBI = 0 , ///< Control/Bulk/Interrupt protocol (with command completion interrupt) - MSC_PROTOCOL_CBI_NO_INTERRUPT = 1 , ///< Control/Bulk/Interrupt protocol (without command completion interrupt) - MSC_PROTOCOL_BOT = 0x50 ///< Bulk-Only Transport -}msc_protocol_type_t; - -/// MassStorage Class-Specific Control Request -typedef enum -{ - MSC_REQ_GET_MAX_LUN = 254, ///< The Get Max LUN device request is used to determine the number of logical units supported by the device. Logical Unit Numbers on the device shall be numbered contiguously starting from LUN 0 to a maximum LUN of 15 - MSC_REQ_RESET = 255 ///< This request is used to reset the mass storage device and its associated interface. This class-specific request shall ready the device for the next CBW from the host. -}msc_request_type_t; - -/// \brief Command Block Status Values -/// \details Indicates the success or failure of the command. The device shall set this byte to zero if the command completed -/// successfully. A non-zero value shall indicate a failure during command execution according to the following -typedef enum -{ - MSC_CSW_STATUS_PASSED = 0 , ///< MSC_CSW_STATUS_PASSED - MSC_CSW_STATUS_FAILED , ///< MSC_CSW_STATUS_FAILED - MSC_CSW_STATUS_PHASE_ERROR ///< MSC_CSW_STATUS_PHASE_ERROR -}msc_csw_status_t; - -/// Command Block Wrapper -typedef struct TU_ATTR_PACKED -{ - uint32_t signature; ///< Signature that helps identify this data packet as a CBW. The signature field shall contain the value 43425355h (little endian), indicating a CBW. - uint32_t tag; ///< Tag sent by the host. The device shall echo the contents of this field back to the host in the dCSWTagfield of the associated CSW. The dCSWTagpositively associates a CSW with the corresponding CBW. - uint32_t total_bytes; ///< The number of bytes of data that the host expects to transfer on the Bulk-In or Bulk-Out endpoint (as indicated by the Direction bit) during the execution of this command. If this field is zero, the device and the host shall transfer no data between the CBW and the associated CSW, and the device shall ignore the value of the Direction bit in bmCBWFlags. - uint8_t dir; ///< Bit 7 of this field define transfer direction \n - 0 : Data-Out from host to the device. \n - 1 : Data-In from the device to the host. - uint8_t lun; ///< The device Logical Unit Number (LUN) to which the command block is being sent. For devices that support multiple LUNs, the host shall place into this field the LUN to which this command block is addressed. Otherwise, the host shall set this field to zero. - uint8_t cmd_len; ///< The valid length of the CBWCBin bytes. This defines the valid length of the command block. The only legal values are 1 through 16 - uint8_t command[16]; ///< The command block to be executed by the device. The device shall interpret the first cmd_len bytes in this field as a command block -}msc_cbw_t; - -TU_VERIFY_STATIC(sizeof(msc_cbw_t) == 31, "size is not correct"); - -/// Command Status Wrapper -typedef struct TU_ATTR_PACKED -{ - uint32_t signature ; ///< Signature that helps identify this data packet as a CSW. The signature field shall contain the value 53425355h (little endian), indicating CSW. - uint32_t tag ; ///< The device shall set this field to the value received in the dCBWTag of the associated CBW. - uint32_t data_residue ; ///< For Data-Out the device shall report in the dCSWDataResiduethe difference between the amount of data expected as stated in the dCBWDataTransferLength, and the actual amount of data processed by the device. For Data-In the device shall report in the dCSWDataResiduethe difference between the amount of data expected as stated in the dCBWDataTransferLengthand the actual amount of relevant data sent by the device - uint8_t status ; ///< indicates the success or failure of the command. Values from \ref msc_csw_status_t -}msc_csw_t; - -TU_VERIFY_STATIC(sizeof(msc_csw_t) == 13, "size is not correct"); - -//--------------------------------------------------------------------+ -// SCSI Constant -//--------------------------------------------------------------------+ - -/// SCSI Command Operation Code -typedef enum -{ - SCSI_CMD_TEST_UNIT_READY = 0x00, ///< The SCSI Test Unit Ready command is used to determine if a device is ready to transfer data (read/write), i.e. if a disk has spun up, if a tape is loaded and ready etc. The device does not perform a self-test operation. - SCSI_CMD_INQUIRY = 0x12, ///< The SCSI Inquiry command is used to obtain basic information from a target device. - SCSI_CMD_MODE_SELECT_6 = 0x15, ///< provides a means for the application client to specify medium, logical unit, or peripheral device parameters to the device server. Device servers that implement the MODE SELECT(6) command shall also implement the MODE SENSE(6) command. Application clients should issue MODE SENSE(6) prior to each MODE SELECT(6) to determine supported mode pages, page lengths, and other parameters. - SCSI_CMD_MODE_SENSE_6 = 0x1A, ///< provides a means for a device server to report parameters to an application client. It is a complementary command to the MODE SELECT(6) command. Device servers that implement the MODE SENSE(6) command shall also implement the MODE SELECT(6) command. - SCSI_CMD_START_STOP_UNIT = 0x1B, - SCSI_CMD_PREVENT_ALLOW_MEDIUM_REMOVAL = 0x1E, - SCSI_CMD_READ_CAPACITY_10 = 0x25, ///< The SCSI Read Capacity command is used to obtain data capacity information from a target device. - SCSI_CMD_REQUEST_SENSE = 0x03, ///< The SCSI Request Sense command is part of the SCSI computer protocol standard. This command is used to obtain sense data -- status/error information -- from a target device. - SCSI_CMD_READ_FORMAT_CAPACITY = 0x23, ///< The command allows the Host to request a list of the possible format capacities for an installed writable media. This command also has the capability to report the writable capacity for a media when it is installed - SCSI_CMD_READ_10 = 0x28, ///< The READ (10) command requests that the device server read the specified logical block(s) and transfer them to the data-in buffer. - SCSI_CMD_WRITE_10 = 0x2A, ///< The WRITE (10) command requests thatthe device server transfer the specified logical block(s) from the data-out buffer and write them. -}scsi_cmd_type_t; - -/// SCSI Sense Key -typedef enum -{ - SCSI_SENSE_NONE = 0x00, ///< no specific Sense Key. This would be the case for a successful command - SCSI_SENSE_RECOVERED_ERROR = 0x01, ///< ndicates the last command completed successfully with some recovery action performed by the disc drive. - SCSI_SENSE_NOT_READY = 0x02, ///< Indicates the logical unit addressed cannot be accessed. - SCSI_SENSE_MEDIUM_ERROR = 0x03, ///< Indicates the command terminated with a non-recovered error condition. - SCSI_SENSE_HARDWARE_ERROR = 0x04, ///< Indicates the disc drive detected a nonrecoverable hardware failure while performing the command or during a self test. - SCSI_SENSE_ILLEGAL_REQUEST = 0x05, ///< Indicates an illegal parameter in the command descriptor block or in the additional parameters - SCSI_SENSE_UNIT_ATTENTION = 0x06, ///< Indicates the disc drive may have been reset. - SCSI_SENSE_DATA_PROTECT = 0x07, ///< Indicates that a command that reads or writes the medium was attempted on a block that is protected from this operation. The read or write operation is not performed. - SCSI_SENSE_FIRMWARE_ERROR = 0x08, ///< Vendor specific sense key. - SCSI_SENSE_ABORTED_COMMAND = 0x0b, ///< Indicates the disc drive aborted the command. - SCSI_SENSE_EQUAL = 0x0c, ///< Indicates a SEARCH DATA command has satisfied an equal comparison. - SCSI_SENSE_VOLUME_OVERFLOW = 0x0d, ///< Indicates a buffered peripheral device has reached the end of medium partition and data remains in the buffer that has not been written to the medium. - SCSI_SENSE_MISCOMPARE = 0x0e ///< ndicates that the source data did not match the data read from the medium. -}scsi_sense_key_type_t; - -//--------------------------------------------------------------------+ -// SCSI Primary Command (SPC-4) -//--------------------------------------------------------------------+ - -/// SCSI Test Unit Ready Command -typedef struct TU_ATTR_PACKED -{ - uint8_t cmd_code ; ///< SCSI OpCode for \ref SCSI_CMD_TEST_UNIT_READY - uint8_t lun ; ///< Logical Unit - uint8_t reserved[3] ; - uint8_t control ; -} scsi_test_unit_ready_t; - -TU_VERIFY_STATIC(sizeof(scsi_test_unit_ready_t) == 6, "size is not correct"); - -/// SCSI Inquiry Command -typedef struct TU_ATTR_PACKED -{ - uint8_t cmd_code ; ///< SCSI OpCode for \ref SCSI_CMD_INQUIRY - uint8_t reserved1 ; - uint8_t page_code ; - uint8_t reserved2 ; - uint8_t alloc_length ; ///< specifies the maximum number of bytes that USB host has allocated in the Data-In Buffer. An allocation length of zero specifies that no data shall be transferred. - uint8_t control ; -} scsi_inquiry_t, scsi_request_sense_t; - -TU_VERIFY_STATIC(sizeof(scsi_inquiry_t) == 6, "size is not correct"); - -/// SCSI Inquiry Response Data -typedef struct TU_ATTR_PACKED -{ - uint8_t peripheral_device_type : 5; - uint8_t peripheral_qualifier : 3; - - uint8_t : 7; - uint8_t is_removable : 1; - - uint8_t version; - - uint8_t response_data_format : 4; - uint8_t hierarchical_support : 1; - uint8_t normal_aca : 1; - uint8_t : 2; - - uint8_t additional_length; - - uint8_t protect : 1; - uint8_t : 2; - uint8_t third_party_copy : 1; - uint8_t target_port_group_support : 2; - uint8_t access_control_coordinator : 1; - uint8_t scc_support : 1; - - uint8_t addr16 : 1; - uint8_t : 3; - uint8_t multi_port : 1; - uint8_t : 1; // vendor specific - uint8_t enclosure_service : 1; - uint8_t : 1; - - uint8_t : 1; // vendor specific - uint8_t cmd_que : 1; - uint8_t : 2; - uint8_t sync : 1; - uint8_t wbus16 : 1; - uint8_t : 2; - - uint8_t vendor_id[8] ; ///< 8 bytes of ASCII data identifying the vendor of the product. - uint8_t product_id[16]; ///< 16 bytes of ASCII data defined by the vendor. - uint8_t product_rev[4]; ///< 4 bytes of ASCII data defined by the vendor. -} scsi_inquiry_resp_t; - -TU_VERIFY_STATIC(sizeof(scsi_inquiry_resp_t) == 36, "size is not correct"); - - -typedef struct TU_ATTR_PACKED -{ - uint8_t response_code : 7; ///< 70h - current errors, Fixed Format 71h - deferred errors, Fixed Format - uint8_t valid : 1; - - uint8_t reserved; - - uint8_t sense_key : 4; - uint8_t : 1; - uint8_t ili : 1; ///< Incorrect length indicator - uint8_t end_of_medium : 1; - uint8_t filemark : 1; - - uint32_t information; - uint8_t add_sense_len; - uint32_t command_specific_info; - uint8_t add_sense_code; - uint8_t add_sense_qualifier; - uint8_t field_replaceable_unit_code; - - uint8_t sense_key_specific[3]; ///< sense key specific valid bit is bit 7 of key[0], aka MSB in Big Endian layout - -} scsi_sense_fixed_resp_t; - -TU_VERIFY_STATIC(sizeof(scsi_sense_fixed_resp_t) == 18, "size is not correct"); - -typedef struct TU_ATTR_PACKED -{ - uint8_t cmd_code ; ///< SCSI OpCode for \ref SCSI_CMD_MODE_SENSE_6 - - uint8_t : 3; - uint8_t disable_block_descriptor : 1; - uint8_t : 0; - - uint8_t page_code : 6; - uint8_t page_control : 2; - - uint8_t subpage_code; - uint8_t alloc_length; - uint8_t control; -} scsi_mode_sense6_t; - -TU_VERIFY_STATIC( sizeof(scsi_mode_sense6_t) == 6, "size is not correct"); - -// This is only a Mode parameter header(6). -typedef struct TU_ATTR_PACKED -{ - uint8_t data_len; - uint8_t medium_type; - - uint8_t reserved : 7; - bool write_protected : 1; - - uint8_t block_descriptor_len; -} scsi_mode_sense6_resp_t; - -TU_VERIFY_STATIC( sizeof(scsi_mode_sense6_resp_t) == 4, "size is not correct"); - -typedef struct TU_ATTR_PACKED -{ - uint8_t cmd_code; ///< SCSI OpCode for \ref SCSI_CMD_PREVENT_ALLOW_MEDIUM_REMOVAL - uint8_t reserved[3]; - uint8_t prohibit_removal; - uint8_t control; -} scsi_prevent_allow_medium_removal_t; - -TU_VERIFY_STATIC( sizeof(scsi_prevent_allow_medium_removal_t) == 6, "size is not correct"); - -typedef struct TU_ATTR_PACKED -{ - uint8_t cmd_code; - - uint8_t immded : 1; - uint8_t : 7; - - uint8_t TU_RESERVED; - - uint8_t power_condition_mod : 4; - uint8_t : 4; - - uint8_t start : 1; - uint8_t load_eject : 1; - uint8_t no_flush : 1; - uint8_t : 1; - uint8_t power_condition : 4; - - uint8_t control; -} scsi_start_stop_unit_t; - -TU_VERIFY_STATIC( sizeof(scsi_start_stop_unit_t) == 6, "size is not correct"); - -//--------------------------------------------------------------------+ -// SCSI MMC -//--------------------------------------------------------------------+ -/// SCSI Read Format Capacity: Write Capacity -typedef struct TU_ATTR_PACKED -{ - uint8_t cmd_code; - uint8_t reserved[6]; - uint16_t alloc_length; - uint8_t control; -} scsi_read_format_capacity_t; - -TU_VERIFY_STATIC( sizeof(scsi_read_format_capacity_t) == 10, "size is not correct"); - -typedef struct TU_ATTR_PACKED{ - uint8_t reserved[3]; - uint8_t list_length; /// must be 8*n, length in bytes of formattable capacity descriptor followed it. - - uint32_t block_num; /// Number of Logical Blocks - uint8_t descriptor_type; // 00: reserved, 01 unformatted media , 10 Formatted media, 11 No media present - - uint8_t reserved2; - uint16_t block_size_u16; - -} scsi_read_format_capacity_data_t; - -TU_VERIFY_STATIC( sizeof(scsi_read_format_capacity_data_t) == 12, "size is not correct"); - -//--------------------------------------------------------------------+ -// SCSI Block Command (SBC-3) -// NOTE: All data in SCSI command are in Big Endian -//--------------------------------------------------------------------+ - -/// SCSI Read Capacity 10 Command: Read Capacity -typedef struct TU_ATTR_PACKED -{ - uint8_t cmd_code ; ///< SCSI OpCode for \ref SCSI_CMD_READ_CAPACITY_10 - uint8_t reserved1 ; - uint32_t lba ; ///< The first Logical Block Address (LBA) accessed by this command - uint16_t reserved2 ; - uint8_t partial_medium_indicator ; - uint8_t control ; -} scsi_read_capacity10_t; - -TU_VERIFY_STATIC(sizeof(scsi_read_capacity10_t) == 10, "size is not correct"); - -/// SCSI Read Capacity 10 Response Data -typedef struct { - uint32_t last_lba ; ///< The last Logical Block Address of the device - uint32_t block_size ; ///< Block size in bytes -} scsi_read_capacity10_resp_t; - -TU_VERIFY_STATIC(sizeof(scsi_read_capacity10_resp_t) == 8, "size is not correct"); - -/// SCSI Read 10 Command -typedef struct TU_ATTR_PACKED -{ - uint8_t cmd_code ; ///< SCSI OpCode - uint8_t reserved ; // has LUN according to wiki - uint32_t lba ; ///< The first Logical Block Address (LBA) accessed by this command - uint8_t reserved2 ; - uint16_t block_count ; ///< Number of Blocks used by this command - uint8_t control ; -} scsi_read10_t, scsi_write10_t; - -TU_VERIFY_STATIC(sizeof(scsi_read10_t) == 10, "size is not correct"); -TU_VERIFY_STATIC(sizeof(scsi_write10_t) == 10, "size is not correct"); - -#ifdef __cplusplus - } -#endif - -#endif /* _TUSB_MSC_H_ */ - -/// @} -/// @} +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +/** \ingroup group_class + * \defgroup ClassDriver_MSC MassStorage (MSC) + * @{ */ + +/** \defgroup ClassDriver_MSC_Common Common Definitions + * @{ */ + +#ifndef _TUSB_MSC_H_ +#define _TUSB_MSC_H_ + +#include "common/tusb_common.h" + +#ifdef __cplusplus + extern "C" { +#endif + +//--------------------------------------------------------------------+ +// Mass Storage Class Constant +//--------------------------------------------------------------------+ +/// MassStorage Subclass +typedef enum +{ + MSC_SUBCLASS_RBC = 1 , ///< Reduced Block Commands (RBC) T10 Project 1240-D + MSC_SUBCLASS_SFF_MMC , ///< SFF-8020i, MMC-2 (ATAPI). Typically used by a CD/DVD device + MSC_SUBCLASS_QIC , ///< QIC-157. Typically used by a tape device + MSC_SUBCLASS_UFI , ///< UFI. Typically used by Floppy Disk Drive (FDD) device + MSC_SUBCLASS_SFF , ///< SFF-8070i. Can be used by Floppy Disk Drive (FDD) device + MSC_SUBCLASS_SCSI ///< SCSI transparent command set +}msc_subclass_type_t; + +enum { + MSC_CBW_SIGNATURE = 0x43425355, ///< Constant value of 43425355h (little endian) + MSC_CSW_SIGNATURE = 0x53425355 ///< Constant value of 53425355h (little endian) +}; + +/// \brief MassStorage Protocol. +/// \details CBI only approved to use with full-speed floopy disk & should not used with highspeed or device other than floopy +typedef enum +{ + MSC_PROTOCOL_CBI = 0 , ///< Control/Bulk/Interrupt protocol (with command completion interrupt) + MSC_PROTOCOL_CBI_NO_INTERRUPT = 1 , ///< Control/Bulk/Interrupt protocol (without command completion interrupt) + MSC_PROTOCOL_BOT = 0x50 ///< Bulk-Only Transport +}msc_protocol_type_t; + +/// MassStorage Class-Specific Control Request +typedef enum +{ + MSC_REQ_GET_MAX_LUN = 254, ///< The Get Max LUN device request is used to determine the number of logical units supported by the device. Logical Unit Numbers on the device shall be numbered contiguously starting from LUN 0 to a maximum LUN of 15 + MSC_REQ_RESET = 255 ///< This request is used to reset the mass storage device and its associated interface. This class-specific request shall ready the device for the next CBW from the host. +}msc_request_type_t; + +/// \brief Command Block Status Values +/// \details Indicates the success or failure of the command. The device shall set this byte to zero if the command completed +/// successfully. A non-zero value shall indicate a failure during command execution according to the following +typedef enum +{ + MSC_CSW_STATUS_PASSED = 0 , ///< MSC_CSW_STATUS_PASSED + MSC_CSW_STATUS_FAILED , ///< MSC_CSW_STATUS_FAILED + MSC_CSW_STATUS_PHASE_ERROR ///< MSC_CSW_STATUS_PHASE_ERROR +}msc_csw_status_t; + +/// Command Block Wrapper +typedef struct TU_ATTR_PACKED +{ + uint32_t signature; ///< Signature that helps identify this data packet as a CBW. The signature field shall contain the value 43425355h (little endian), indicating a CBW. + uint32_t tag; ///< Tag sent by the host. The device shall echo the contents of this field back to the host in the dCSWTagfield of the associated CSW. The dCSWTagpositively associates a CSW with the corresponding CBW. + uint32_t total_bytes; ///< The number of bytes of data that the host expects to transfer on the Bulk-In or Bulk-Out endpoint (as indicated by the Direction bit) during the execution of this command. If this field is zero, the device and the host shall transfer no data between the CBW and the associated CSW, and the device shall ignore the value of the Direction bit in bmCBWFlags. + uint8_t dir; ///< Bit 7 of this field define transfer direction \n - 0 : Data-Out from host to the device. \n - 1 : Data-In from the device to the host. + uint8_t lun; ///< The device Logical Unit Number (LUN) to which the command block is being sent. For devices that support multiple LUNs, the host shall place into this field the LUN to which this command block is addressed. Otherwise, the host shall set this field to zero. + uint8_t cmd_len; ///< The valid length of the CBWCBin bytes. This defines the valid length of the command block. The only legal values are 1 through 16 + uint8_t command[16]; ///< The command block to be executed by the device. The device shall interpret the first cmd_len bytes in this field as a command block +}msc_cbw_t; + +TU_VERIFY_STATIC(sizeof(msc_cbw_t) == 31, "size is not correct"); + +/// Command Status Wrapper +typedef struct TU_ATTR_PACKED +{ + uint32_t signature ; ///< Signature that helps identify this data packet as a CSW. The signature field shall contain the value 53425355h (little endian), indicating CSW. + uint32_t tag ; ///< The device shall set this field to the value received in the dCBWTag of the associated CBW. + uint32_t data_residue ; ///< For Data-Out the device shall report in the dCSWDataResiduethe difference between the amount of data expected as stated in the dCBWDataTransferLength, and the actual amount of data processed by the device. For Data-In the device shall report in the dCSWDataResiduethe difference between the amount of data expected as stated in the dCBWDataTransferLengthand the actual amount of relevant data sent by the device + uint8_t status ; ///< indicates the success or failure of the command. Values from \ref msc_csw_status_t +}msc_csw_t; + +TU_VERIFY_STATIC(sizeof(msc_csw_t) == 13, "size is not correct"); + +//--------------------------------------------------------------------+ +// SCSI Constant +//--------------------------------------------------------------------+ + +/// SCSI Command Operation Code +typedef enum +{ + SCSI_CMD_TEST_UNIT_READY = 0x00, ///< The SCSI Test Unit Ready command is used to determine if a device is ready to transfer data (read/write), i.e. if a disk has spun up, if a tape is loaded and ready etc. The device does not perform a self-test operation. + SCSI_CMD_INQUIRY = 0x12, ///< The SCSI Inquiry command is used to obtain basic information from a target device. + SCSI_CMD_MODE_SELECT_6 = 0x15, ///< provides a means for the application client to specify medium, logical unit, or peripheral device parameters to the device server. Device servers that implement the MODE SELECT(6) command shall also implement the MODE SENSE(6) command. Application clients should issue MODE SENSE(6) prior to each MODE SELECT(6) to determine supported mode pages, page lengths, and other parameters. + SCSI_CMD_MODE_SENSE_6 = 0x1A, ///< provides a means for a device server to report parameters to an application client. It is a complementary command to the MODE SELECT(6) command. Device servers that implement the MODE SENSE(6) command shall also implement the MODE SELECT(6) command. + SCSI_CMD_START_STOP_UNIT = 0x1B, + SCSI_CMD_PREVENT_ALLOW_MEDIUM_REMOVAL = 0x1E, + SCSI_CMD_READ_CAPACITY_10 = 0x25, ///< The SCSI Read Capacity command is used to obtain data capacity information from a target device. + SCSI_CMD_REQUEST_SENSE = 0x03, ///< The SCSI Request Sense command is part of the SCSI computer protocol standard. This command is used to obtain sense data -- status/error information -- from a target device. + SCSI_CMD_READ_FORMAT_CAPACITY = 0x23, ///< The command allows the Host to request a list of the possible format capacities for an installed writable media. This command also has the capability to report the writable capacity for a media when it is installed + SCSI_CMD_READ_10 = 0x28, ///< The READ (10) command requests that the device server read the specified logical block(s) and transfer them to the data-in buffer. + SCSI_CMD_WRITE_10 = 0x2A, ///< The WRITE (10) command requests thatthe device server transfer the specified logical block(s) from the data-out buffer and write them. +}scsi_cmd_type_t; + +/// SCSI Sense Key +typedef enum +{ + SCSI_SENSE_NONE = 0x00, ///< no specific Sense Key. This would be the case for a successful command + SCSI_SENSE_RECOVERED_ERROR = 0x01, ///< ndicates the last command completed successfully with some recovery action performed by the disc drive. + SCSI_SENSE_NOT_READY = 0x02, ///< Indicates the logical unit addressed cannot be accessed. + SCSI_SENSE_MEDIUM_ERROR = 0x03, ///< Indicates the command terminated with a non-recovered error condition. + SCSI_SENSE_HARDWARE_ERROR = 0x04, ///< Indicates the disc drive detected a nonrecoverable hardware failure while performing the command or during a self test. + SCSI_SENSE_ILLEGAL_REQUEST = 0x05, ///< Indicates an illegal parameter in the command descriptor block or in the additional parameters + SCSI_SENSE_UNIT_ATTENTION = 0x06, ///< Indicates the disc drive may have been reset. + SCSI_SENSE_DATA_PROTECT = 0x07, ///< Indicates that a command that reads or writes the medium was attempted on a block that is protected from this operation. The read or write operation is not performed. + SCSI_SENSE_FIRMWARE_ERROR = 0x08, ///< Vendor specific sense key. + SCSI_SENSE_ABORTED_COMMAND = 0x0b, ///< Indicates the disc drive aborted the command. + SCSI_SENSE_EQUAL = 0x0c, ///< Indicates a SEARCH DATA command has satisfied an equal comparison. + SCSI_SENSE_VOLUME_OVERFLOW = 0x0d, ///< Indicates a buffered peripheral device has reached the end of medium partition and data remains in the buffer that has not been written to the medium. + SCSI_SENSE_MISCOMPARE = 0x0e ///< ndicates that the source data did not match the data read from the medium. +}scsi_sense_key_type_t; + +//--------------------------------------------------------------------+ +// SCSI Primary Command (SPC-4) +//--------------------------------------------------------------------+ + +/// SCSI Test Unit Ready Command +typedef struct TU_ATTR_PACKED +{ + uint8_t cmd_code ; ///< SCSI OpCode for \ref SCSI_CMD_TEST_UNIT_READY + uint8_t lun ; ///< Logical Unit + uint8_t reserved[3] ; + uint8_t control ; +} scsi_test_unit_ready_t; + +TU_VERIFY_STATIC(sizeof(scsi_test_unit_ready_t) == 6, "size is not correct"); + +/// SCSI Inquiry Command +typedef struct TU_ATTR_PACKED +{ + uint8_t cmd_code ; ///< SCSI OpCode for \ref SCSI_CMD_INQUIRY + uint8_t reserved1 ; + uint8_t page_code ; + uint8_t reserved2 ; + uint8_t alloc_length ; ///< specifies the maximum number of bytes that USB host has allocated in the Data-In Buffer. An allocation length of zero specifies that no data shall be transferred. + uint8_t control ; +} scsi_inquiry_t, scsi_request_sense_t; + +TU_VERIFY_STATIC(sizeof(scsi_inquiry_t) == 6, "size is not correct"); + +/// SCSI Inquiry Response Data +typedef struct TU_ATTR_PACKED +{ + uint8_t peripheral_device_type : 5; + uint8_t peripheral_qualifier : 3; + + uint8_t : 7; + uint8_t is_removable : 1; + + uint8_t version; + + uint8_t response_data_format : 4; + uint8_t hierarchical_support : 1; + uint8_t normal_aca : 1; + uint8_t : 2; + + uint8_t additional_length; + + uint8_t protect : 1; + uint8_t : 2; + uint8_t third_party_copy : 1; + uint8_t target_port_group_support : 2; + uint8_t access_control_coordinator : 1; + uint8_t scc_support : 1; + + uint8_t addr16 : 1; + uint8_t : 3; + uint8_t multi_port : 1; + uint8_t : 1; // vendor specific + uint8_t enclosure_service : 1; + uint8_t : 1; + + uint8_t : 1; // vendor specific + uint8_t cmd_que : 1; + uint8_t : 2; + uint8_t sync : 1; + uint8_t wbus16 : 1; + uint8_t : 2; + + uint8_t vendor_id[8] ; ///< 8 bytes of ASCII data identifying the vendor of the product. + uint8_t product_id[16]; ///< 16 bytes of ASCII data defined by the vendor. + uint8_t product_rev[4]; ///< 4 bytes of ASCII data defined by the vendor. +} scsi_inquiry_resp_t; + +TU_VERIFY_STATIC(sizeof(scsi_inquiry_resp_t) == 36, "size is not correct"); + + +typedef struct TU_ATTR_PACKED +{ + uint8_t response_code : 7; ///< 70h - current errors, Fixed Format 71h - deferred errors, Fixed Format + uint8_t valid : 1; + + uint8_t reserved; + + uint8_t sense_key : 4; + uint8_t : 1; + uint8_t ili : 1; ///< Incorrect length indicator + uint8_t end_of_medium : 1; + uint8_t filemark : 1; + + uint32_t information; + uint8_t add_sense_len; + uint32_t command_specific_info; + uint8_t add_sense_code; + uint8_t add_sense_qualifier; + uint8_t field_replaceable_unit_code; + + uint8_t sense_key_specific[3]; ///< sense key specific valid bit is bit 7 of key[0], aka MSB in Big Endian layout + +} scsi_sense_fixed_resp_t; + +TU_VERIFY_STATIC(sizeof(scsi_sense_fixed_resp_t) == 18, "size is not correct"); + +typedef struct TU_ATTR_PACKED +{ + uint8_t cmd_code ; ///< SCSI OpCode for \ref SCSI_CMD_MODE_SENSE_6 + + uint8_t : 3; + uint8_t disable_block_descriptor : 1; + uint8_t : 0; + + uint8_t page_code : 6; + uint8_t page_control : 2; + + uint8_t subpage_code; + uint8_t alloc_length; + uint8_t control; +} scsi_mode_sense6_t; + +TU_VERIFY_STATIC( sizeof(scsi_mode_sense6_t) == 6, "size is not correct"); + +// This is only a Mode parameter header(6). +typedef struct TU_ATTR_PACKED +{ + uint8_t data_len; + uint8_t medium_type; + + uint8_t reserved : 7; + bool write_protected : 1; + + uint8_t block_descriptor_len; +} scsi_mode_sense6_resp_t; + +TU_VERIFY_STATIC( sizeof(scsi_mode_sense6_resp_t) == 4, "size is not correct"); + +typedef struct TU_ATTR_PACKED +{ + uint8_t cmd_code; ///< SCSI OpCode for \ref SCSI_CMD_PREVENT_ALLOW_MEDIUM_REMOVAL + uint8_t reserved[3]; + uint8_t prohibit_removal; + uint8_t control; +} scsi_prevent_allow_medium_removal_t; + +TU_VERIFY_STATIC( sizeof(scsi_prevent_allow_medium_removal_t) == 6, "size is not correct"); + +typedef struct TU_ATTR_PACKED +{ + uint8_t cmd_code; + + uint8_t immded : 1; + uint8_t : 7; + + uint8_t TU_RESERVED; + + uint8_t power_condition_mod : 4; + uint8_t : 4; + + uint8_t start : 1; + uint8_t load_eject : 1; + uint8_t no_flush : 1; + uint8_t : 1; + uint8_t power_condition : 4; + + uint8_t control; +} scsi_start_stop_unit_t; + +TU_VERIFY_STATIC( sizeof(scsi_start_stop_unit_t) == 6, "size is not correct"); + +//--------------------------------------------------------------------+ +// SCSI MMC +//--------------------------------------------------------------------+ +/// SCSI Read Format Capacity: Write Capacity +typedef struct TU_ATTR_PACKED +{ + uint8_t cmd_code; + uint8_t reserved[6]; + uint16_t alloc_length; + uint8_t control; +} scsi_read_format_capacity_t; + +TU_VERIFY_STATIC( sizeof(scsi_read_format_capacity_t) == 10, "size is not correct"); + +typedef struct TU_ATTR_PACKED{ + uint8_t reserved[3]; + uint8_t list_length; /// must be 8*n, length in bytes of formattable capacity descriptor followed it. + + uint32_t block_num; /// Number of Logical Blocks + uint8_t descriptor_type; // 00: reserved, 01 unformatted media , 10 Formatted media, 11 No media present + + uint8_t reserved2; + uint16_t block_size_u16; + +} scsi_read_format_capacity_data_t; + +TU_VERIFY_STATIC( sizeof(scsi_read_format_capacity_data_t) == 12, "size is not correct"); + +//--------------------------------------------------------------------+ +// SCSI Block Command (SBC-3) +// NOTE: All data in SCSI command are in Big Endian +//--------------------------------------------------------------------+ + +/// SCSI Read Capacity 10 Command: Read Capacity +typedef struct TU_ATTR_PACKED +{ + uint8_t cmd_code ; ///< SCSI OpCode for \ref SCSI_CMD_READ_CAPACITY_10 + uint8_t reserved1 ; + uint32_t lba ; ///< The first Logical Block Address (LBA) accessed by this command + uint16_t reserved2 ; + uint8_t partial_medium_indicator ; + uint8_t control ; +} scsi_read_capacity10_t; + +TU_VERIFY_STATIC(sizeof(scsi_read_capacity10_t) == 10, "size is not correct"); + +/// SCSI Read Capacity 10 Response Data +typedef struct { + uint32_t last_lba ; ///< The last Logical Block Address of the device + uint32_t block_size ; ///< Block size in bytes +} scsi_read_capacity10_resp_t; + +TU_VERIFY_STATIC(sizeof(scsi_read_capacity10_resp_t) == 8, "size is not correct"); + +/// SCSI Read 10 Command +typedef struct TU_ATTR_PACKED +{ + uint8_t cmd_code ; ///< SCSI OpCode + uint8_t reserved ; // has LUN according to wiki + uint32_t lba ; ///< The first Logical Block Address (LBA) accessed by this command + uint8_t reserved2 ; + uint16_t block_count ; ///< Number of Blocks used by this command + uint8_t control ; +} scsi_read10_t, scsi_write10_t; + +TU_VERIFY_STATIC(sizeof(scsi_read10_t) == 10, "size is not correct"); +TU_VERIFY_STATIC(sizeof(scsi_write10_t) == 10, "size is not correct"); + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_MSC_H_ */ + +/// @} +/// @} diff --git a/src/class/msc/msc_device.c b/src/class/msc/msc_device.c index bef5d599..3ff0eba9 100644 --- a/src/class/msc/msc_device.c +++ b/src/class/msc/msc_device.c @@ -1,700 +1,700 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2019 Ha Thach (tinyusb.org) - * - * 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. - * - * This file is part of the TinyUSB stack. - */ - -#include "tusb_option.h" - -#if (TUSB_OPT_DEVICE_ENABLED && CFG_TUD_MSC) - -#include "common/tusb_common.h" -#include "msc_device.h" -#include "device/usbd_pvt.h" - -//--------------------------------------------------------------------+ -// MACRO CONSTANT TYPEDEF -//--------------------------------------------------------------------+ -enum -{ - MSC_STAGE_CMD = 0, - MSC_STAGE_DATA, - MSC_STAGE_STATUS, - MSC_STAGE_STATUS_SENT -}; - -typedef struct -{ - // TODO optimize alignment - CFG_TUSB_MEM_ALIGN msc_cbw_t cbw; - CFG_TUSB_MEM_ALIGN msc_csw_t csw; - - uint8_t itf_num; - uint8_t ep_in; - uint8_t ep_out; - - // Bulk Only Transfer (BOT) Protocol - uint8_t stage; - uint32_t total_len; - uint32_t xferred_len; // numbered of bytes transferred so far in the Data Stage - - // Sense Response Data - uint8_t sense_key; - uint8_t add_sense_code; - uint8_t add_sense_qualifier; -}mscd_interface_t; - -CFG_TUSB_MEM_SECTION CFG_TUSB_MEM_ALIGN static mscd_interface_t _mscd_itf; -CFG_TUSB_MEM_SECTION CFG_TUSB_MEM_ALIGN static uint8_t _mscd_buf[CFG_TUD_MSC_BUFSIZE]; - -//--------------------------------------------------------------------+ -// INTERNAL OBJECT & FUNCTION DECLARATION -//--------------------------------------------------------------------+ -static void proc_read10_cmd(uint8_t rhport, mscd_interface_t* p_msc); -static void proc_write10_cmd(uint8_t rhport, mscd_interface_t* p_msc); - -static inline uint32_t rdwr10_get_lba(uint8_t const command[]) -{ - // read10 & write10 has the same format - scsi_write10_t* p_rdwr10 = (scsi_write10_t*) command; - - // copy first to prevent mis-aligned access - uint32_t lba; - memcpy(&lba, &p_rdwr10->lba, 4); - - // lba is in Big Endian format - return tu_ntohl(lba); -} - -static inline uint16_t rdwr10_get_blockcount(uint8_t const command[]) -{ - // read10 & write10 has the same format - scsi_write10_t* p_rdwr10 = (scsi_write10_t*) command; - - // copy first to prevent mis-aligned access - uint16_t block_count; - memcpy(&block_count, &p_rdwr10->block_count, 2); - - return tu_ntohs(block_count); -} - -//--------------------------------------------------------------------+ -// Debug -//--------------------------------------------------------------------+ -#if CFG_TUSB_DEBUG >= 2 - -static lookup_entry_t const _msc_scsi_cmd_lookup[] = -{ - { .key = SCSI_CMD_TEST_UNIT_READY , .data = "Test Unit Ready" }, - { .key = SCSI_CMD_INQUIRY , .data = "Inquiry" }, - { .key = SCSI_CMD_MODE_SELECT_6 , .data = "Mode_Select 6" }, - { .key = SCSI_CMD_MODE_SENSE_6 , .data = "Mode_Sense 6" }, - { .key = SCSI_CMD_START_STOP_UNIT , .data = "Start Stop Unit" }, - { .key = SCSI_CMD_PREVENT_ALLOW_MEDIUM_REMOVAL , .data = "Prevent Allow Medium Removal" }, - { .key = SCSI_CMD_READ_CAPACITY_10 , .data = "Read Capacity10" }, - { .key = SCSI_CMD_REQUEST_SENSE , .data = "Request Sense" }, - { .key = SCSI_CMD_READ_FORMAT_CAPACITY , .data = "Read Format Capacity" }, - { .key = SCSI_CMD_READ_10 , .data = "Read10" }, - { .key = SCSI_CMD_WRITE_10 , .data = "Write10" } -}; - -static lookup_table_t const _msc_scsi_cmd_table = -{ - .count = TU_ARRAY_SIZE(_msc_scsi_cmd_lookup), - .items = _msc_scsi_cmd_lookup -}; - -#endif - -//--------------------------------------------------------------------+ -// APPLICATION API -//--------------------------------------------------------------------+ -bool tud_msc_set_sense(uint8_t lun, uint8_t sense_key, uint8_t add_sense_code, uint8_t add_sense_qualifier) -{ - (void) lun; - - _mscd_itf.sense_key = sense_key; - _mscd_itf.add_sense_code = add_sense_code; - _mscd_itf.add_sense_qualifier = add_sense_qualifier; - - return true; -} - -//--------------------------------------------------------------------+ -// USBD Driver API -//--------------------------------------------------------------------+ -void mscd_init(void) -{ - tu_memclr(&_mscd_itf, sizeof(mscd_interface_t)); -} - -void mscd_reset(uint8_t rhport) -{ - (void) rhport; - tu_memclr(&_mscd_itf, sizeof(mscd_interface_t)); -} - -bool mscd_open(uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t *p_len) -{ - // only support SCSI's BOT protocol - TU_ASSERT(MSC_SUBCLASS_SCSI == itf_desc->bInterfaceSubClass && - MSC_PROTOCOL_BOT == itf_desc->bInterfaceProtocol); - - mscd_interface_t * p_msc = &_mscd_itf; - - // Open endpoint pair - TU_ASSERT( usbd_open_edpt_pair(rhport, tu_desc_next(itf_desc), 2, TUSB_XFER_BULK, &p_msc->ep_out, &p_msc->ep_in) ); - - p_msc->itf_num = itf_desc->bInterfaceNumber; - (*p_len) = sizeof(tusb_desc_interface_t) + 2*sizeof(tusb_desc_endpoint_t); - - // Prepare for Command Block Wrapper - TU_ASSERT( usbd_edpt_xfer(rhport, p_msc->ep_out, (uint8_t*) &p_msc->cbw, sizeof(msc_cbw_t)) ); - - return true; -} - -// Handle class control request -// return false to stall control endpoint (e.g unsupported request) -bool mscd_control_request(uint8_t rhport, tusb_control_request_t const * p_request) -{ - // Handle class request only - TU_VERIFY(p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS); - - switch ( p_request->bRequest ) - { - case MSC_REQ_RESET: - // TODO: Actually reset interface. - tud_control_status(rhport, p_request); - break; - - case MSC_REQ_GET_MAX_LUN: - { - uint8_t maxlun = 1; - if (tud_msc_get_maxlun_cb) maxlun = tud_msc_get_maxlun_cb(); - TU_VERIFY(maxlun); - - // MAX LUN is minus 1 by specs - maxlun--; - - tud_control_xfer(rhport, p_request, &maxlun, 1); - } - break; - - default: return false; // stall unsupported request - } - - return true; -} - -// Invoked when class request DATA stage is finished. -// return false to stall control endpoint (e.g Host send non-sense DATA) -bool mscd_control_complete(uint8_t rhport, tusb_control_request_t const * request) -{ - (void) rhport; - (void) request; - - // nothing to do - return true; -} - -// return response's length (copied to buffer). Negative if it is not an built-in command or indicate Failed status (CSW) -// In case of a failed status, sense key must be set for reason of failure -int32_t proc_builtin_scsi(uint8_t lun, uint8_t const scsi_cmd[16], uint8_t* buffer, uint32_t bufsize) -{ - (void) bufsize; // TODO refractor later - int32_t resplen; - - switch ( scsi_cmd[0] ) - { - case SCSI_CMD_TEST_UNIT_READY: - resplen = 0; - if ( !tud_msc_test_unit_ready_cb(lun) ) - { - // Failed status response - resplen = - 1; - - // If sense key is not set by callback, default to Logical Unit Not Ready, Cause Not Reportable - if ( _mscd_itf.sense_key == 0 ) tud_msc_set_sense(lun, SCSI_SENSE_NOT_READY, 0x04, 0x00); - } - break; - - case SCSI_CMD_START_STOP_UNIT: - resplen = 0; - - if (tud_msc_start_stop_cb) - { - scsi_start_stop_unit_t const * start_stop = (scsi_start_stop_unit_t const *) scsi_cmd; - if ( !tud_msc_start_stop_cb(lun, start_stop->power_condition, start_stop->start, start_stop->load_eject) ) - { - // Failed status response - resplen = - 1; - - // If sense key is not set by callback, default to Logical Unit Not Ready, Cause Not Reportable - if ( _mscd_itf.sense_key == 0 ) tud_msc_set_sense(lun, SCSI_SENSE_NOT_READY, 0x04, 0x00); - } - } - break; - - case SCSI_CMD_READ_CAPACITY_10: - { - uint32_t block_count; - uint32_t block_size; - uint16_t block_size_u16; - - tud_msc_capacity_cb(lun, &block_count, &block_size_u16); - block_size = (uint32_t) block_size_u16; - - // Invalid block size/count from callback, possibly unit is not ready - // stall this request, set sense key to NOT READY - if (block_count == 0 || block_size == 0) - { - resplen = -1; - - // If sense key is not set by callback, default to Logical Unit Not Ready, Cause Not Reportable - if ( _mscd_itf.sense_key == 0 ) tud_msc_set_sense(lun, SCSI_SENSE_NOT_READY, 0x04, 0x00); - }else - { - scsi_read_capacity10_resp_t read_capa10; - - read_capa10.last_lba = tu_htonl(block_count-1); - read_capa10.block_size = tu_htonl(block_size); - - resplen = sizeof(read_capa10); - memcpy(buffer, &read_capa10, resplen); - } - } - break; - - case SCSI_CMD_READ_FORMAT_CAPACITY: - { - scsi_read_format_capacity_data_t read_fmt_capa = - { - .list_length = 8, - .block_num = 0, - .descriptor_type = 2, // formatted media - .block_size_u16 = 0 - }; - - uint32_t block_count; - uint16_t block_size; - - tud_msc_capacity_cb(lun, &block_count, &block_size); - - // Invalid block size/count from callback, possibly unit is not ready - // stall this request, set sense key to NOT READY - if (block_count == 0 || block_size == 0) - { - resplen = -1; - - // If sense key is not set by callback, default to Logical Unit Not Ready, Cause Not Reportable - if ( _mscd_itf.sense_key == 0 ) tud_msc_set_sense(lun, SCSI_SENSE_NOT_READY, 0x04, 0x00); - }else - { - read_fmt_capa.block_num = tu_htonl(block_count); - read_fmt_capa.block_size_u16 = tu_htons(block_size); - - resplen = sizeof(read_fmt_capa); - memcpy(buffer, &read_fmt_capa, resplen); - } - } - break; - - case SCSI_CMD_INQUIRY: - { - scsi_inquiry_resp_t inquiry_rsp = - { - .is_removable = 1, - .version = 2, - .response_data_format = 2, - }; - - // vendor_id, product_id, product_rev is space padded string - memset(inquiry_rsp.vendor_id , ' ', sizeof(inquiry_rsp.vendor_id)); - memset(inquiry_rsp.product_id , ' ', sizeof(inquiry_rsp.product_id)); - memset(inquiry_rsp.product_rev, ' ', sizeof(inquiry_rsp.product_rev)); - - tud_msc_inquiry_cb(lun, inquiry_rsp.vendor_id, inquiry_rsp.product_id, inquiry_rsp.product_rev); - - resplen = sizeof(inquiry_rsp); - memcpy(buffer, &inquiry_rsp, resplen); - } - break; - - case SCSI_CMD_MODE_SENSE_6: - { - scsi_mode_sense6_resp_t mode_resp = - { - .data_len = 3, - .medium_type = 0, - .write_protected = false, - .reserved = 0, - .block_descriptor_len = 0 // no block descriptor are included - }; - - bool writable = true; - if (tud_msc_is_writable_cb) { - writable = tud_msc_is_writable_cb(lun); - } - mode_resp.write_protected = !writable; - - resplen = sizeof(mode_resp); - memcpy(buffer, &mode_resp, resplen); - } - break; - - case SCSI_CMD_REQUEST_SENSE: - { - scsi_sense_fixed_resp_t sense_rsp = - { - .response_code = 0x70, - .valid = 1 - }; - - sense_rsp.add_sense_len = sizeof(scsi_sense_fixed_resp_t) - 8; - - sense_rsp.sense_key = _mscd_itf.sense_key; - sense_rsp.add_sense_code = _mscd_itf.add_sense_code; - sense_rsp.add_sense_qualifier = _mscd_itf.add_sense_qualifier; - - resplen = sizeof(sense_rsp); - memcpy(buffer, &sense_rsp, resplen); - - // Clear sense data after copy - tud_msc_set_sense(lun, 0, 0, 0); - } - break; - - default: resplen = -1; break; - } - - return resplen; -} - -bool mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes) -{ - mscd_interface_t* p_msc = &_mscd_itf; - msc_cbw_t const * p_cbw = &p_msc->cbw; - msc_csw_t * p_csw = &p_msc->csw; - - switch (p_msc->stage) - { - case MSC_STAGE_CMD: - //------------- new CBW received -------------// - // Complete IN while waiting for CMD is usually Status of previous SCSI op, ignore it - if(ep_addr != p_msc->ep_out) return true; - - TU_ASSERT( event == XFER_RESULT_SUCCESS && - xferred_bytes == sizeof(msc_cbw_t) && p_cbw->signature == MSC_CBW_SIGNATURE ); - - TU_LOG2(" SCSI Command: %s\n", lookup_find(&_msc_scsi_cmd_table, p_cbw->command[0])); - // TU_LOG2_MEM(p_cbw, xferred_bytes, 2); - - p_csw->signature = MSC_CSW_SIGNATURE; - p_csw->tag = p_cbw->tag; - p_csw->data_residue = 0; - - /*------------- Parse command and prepare DATA -------------*/ - p_msc->stage = MSC_STAGE_DATA; - p_msc->total_len = p_cbw->total_bytes; - p_msc->xferred_len = 0; - - if (SCSI_CMD_READ_10 == p_cbw->command[0]) - { - proc_read10_cmd(rhport, p_msc); - } - else if (SCSI_CMD_WRITE_10 == p_cbw->command[0]) - { - proc_write10_cmd(rhport, p_msc); - } - else - { - // For other SCSI commands - // 1. OUT : queue transfer (invoke app callback after done) - // 2. IN & Zero: Process if is built-in, else Invoke app callback. Skip DATA if zero length - if ( (p_cbw->total_bytes > 0 ) && !tu_bit_test(p_cbw->dir, 7) ) - { - // queue transfer - TU_ASSERT( usbd_edpt_xfer(rhport, p_msc->ep_out, _mscd_buf, p_msc->total_len) ); - }else - { - int32_t resplen; - - // First process if it is a built-in commands - resplen = proc_builtin_scsi(p_cbw->lun, p_cbw->command, _mscd_buf, sizeof(_mscd_buf)); - - // Not built-in, invoke user callback - if ( (resplen < 0) && (p_msc->sense_key == 0) ) - { - resplen = tud_msc_scsi_cb(p_cbw->lun, p_cbw->command, _mscd_buf, p_msc->total_len); - } - - if ( resplen < 0 ) - { - p_msc->total_len = 0; - p_csw->status = MSC_CSW_STATUS_FAILED; - p_msc->stage = MSC_STAGE_STATUS; - - // failed but senskey is not set: default to Illegal Request - if ( p_msc->sense_key == 0 ) tud_msc_set_sense(p_cbw->lun, SCSI_SENSE_ILLEGAL_REQUEST, 0x20, 0x00); - - // Stall bulk In if needed - if (p_cbw->total_bytes) usbd_edpt_stall(rhport, p_msc->ep_in); - } - else - { - p_msc->total_len = (uint32_t) resplen; - p_csw->status = MSC_CSW_STATUS_PASSED; - - if (p_msc->total_len) - { - TU_ASSERT( p_cbw->total_bytes >= p_msc->total_len ); // cannot return more than host expect - TU_ASSERT( usbd_edpt_xfer(rhport, p_msc->ep_in, _mscd_buf, p_msc->total_len) ); - }else - { - p_msc->stage = MSC_STAGE_STATUS; - } - } - } - } - break; - - case MSC_STAGE_DATA: - TU_LOG2(" SCSI Data\n"); - //TU_LOG2_MEM(_mscd_buf, xferred_bytes, 2); - - // OUT transfer, invoke callback if needed - if ( !tu_bit_test(p_cbw->dir, 7) ) - { - if ( SCSI_CMD_WRITE_10 != p_cbw->command[0] ) - { - int32_t cb_result = tud_msc_scsi_cb(p_cbw->lun, p_cbw->command, _mscd_buf, p_msc->total_len); - - if ( cb_result < 0 ) - { - p_csw->status = MSC_CSW_STATUS_FAILED; - tud_msc_set_sense(p_cbw->lun, SCSI_SENSE_ILLEGAL_REQUEST, 0x20, 0x00); // Sense = Invalid Command Operation - }else - { - p_csw->status = MSC_CSW_STATUS_PASSED; - } - } - else - { - uint16_t const block_sz = p_cbw->total_bytes / rdwr10_get_blockcount(p_cbw->command); - - // Adjust lba with transferred bytes - uint32_t const lba = rdwr10_get_lba(p_cbw->command) + (p_msc->xferred_len / block_sz); - - // Application can consume smaller bytes - int32_t nbytes = tud_msc_write10_cb(p_cbw->lun, lba, p_msc->xferred_len % block_sz, _mscd_buf, xferred_bytes); - - if ( nbytes < 0 ) - { - // negative means error -> skip to status phase, status in CSW set to failed - p_csw->data_residue = p_cbw->total_bytes - p_msc->xferred_len; - p_csw->status = MSC_CSW_STATUS_FAILED; - p_msc->stage = MSC_STAGE_STATUS; - - tud_msc_set_sense(p_cbw->lun, SCSI_SENSE_ILLEGAL_REQUEST, 0x20, 0x00); // Sense = Invalid Command Operation - break; - }else - { - // Application consume less than what we got (including zero) - if ( nbytes < (int32_t) xferred_bytes ) - { - if ( nbytes > 0 ) - { - p_msc->xferred_len += nbytes; - memmove(_mscd_buf, _mscd_buf+nbytes, xferred_bytes-nbytes); - } - - // simulate an transfer complete with adjusted parameters --> this driver callback will fired again - dcd_event_xfer_complete(rhport, p_msc->ep_out, xferred_bytes-nbytes, XFER_RESULT_SUCCESS, false); - - return true; // skip the rest - } - else - { - // Application consume all bytes in our buffer. Nothing to do, process with normal flow - } - } - } - } - - // Accumulate data so far - p_msc->xferred_len += xferred_bytes; - - if ( p_msc->xferred_len >= p_msc->total_len ) - { - // Data Stage is complete - p_msc->stage = MSC_STAGE_STATUS; - } - else - { - // READ10 & WRITE10 Can be executed with large bulk of data e.g write 8K bytes (several flash write) - // We break it into multiple smaller command whose data size is up to CFG_TUD_MSC_BUFSIZE - if (SCSI_CMD_READ_10 == p_cbw->command[0]) - { - proc_read10_cmd(rhport, p_msc); - } - else if (SCSI_CMD_WRITE_10 == p_cbw->command[0]) - { - proc_write10_cmd(rhport, p_msc); - }else - { - // No other command take more than one transfer yet -> unlikely error - TU_BREAKPOINT(); - } - } - break; - - case MSC_STAGE_STATUS: - // processed immediately after this switch, supposedly to be empty - break; - - case MSC_STAGE_STATUS_SENT: - // Wait for the Status phase to complete - if( (ep_addr == p_msc->ep_in) && (xferred_bytes == sizeof(msc_csw_t)) ) - { - TU_LOG2(" SCSI Status: %u\n", p_csw->status); - // TU_LOG2_MEM(p_csw, xferred_bytes, 2); - - // Move to default CMD stage - p_msc->stage = MSC_STAGE_CMD; - - // Queue for the next CBW - TU_ASSERT( usbd_edpt_xfer(rhport, p_msc->ep_out, (uint8_t*) &p_msc->cbw, sizeof(msc_cbw_t)) ); - } - break; - - default : break; - } - - if ( p_msc->stage == MSC_STAGE_STATUS ) - { - // Either endpoints is stalled, need to wait until it is cleared by host - if ( usbd_edpt_stalled(rhport, p_msc->ep_in) || usbd_edpt_stalled(rhport, p_msc->ep_out) ) - { - // simulate an transfer complete with adjusted parameters --> this driver callback will fired again - // and response with status phase after halted endpoints are cleared. - // note: use ep_out to prevent confusing with STATUS complete - dcd_event_xfer_complete(rhport, p_msc->ep_out, 0, XFER_RESULT_SUCCESS, false); - } - else - { - // Invoke complete callback if defined - switch(p_cbw->command[0]) - { - case SCSI_CMD_READ_10: - if ( tud_msc_read10_complete_cb ) tud_msc_read10_complete_cb(p_cbw->lun); - break; - - case SCSI_CMD_WRITE_10: - if ( tud_msc_write10_complete_cb ) tud_msc_write10_complete_cb(p_cbw->lun); - break; - - default: - if ( tud_msc_scsi_complete_cb ) tud_msc_scsi_complete_cb(p_cbw->lun, p_cbw->command); - break; - } - - // Move to Status Sent stage - p_msc->stage = MSC_STAGE_STATUS_SENT; - - // Send SCSI Status - TU_ASSERT(usbd_edpt_xfer(rhport, p_msc->ep_in , (uint8_t*) &p_msc->csw, sizeof(msc_csw_t))); - } - } - - return true; -} - -/*------------------------------------------------------------------*/ -/* SCSI Command Process - *------------------------------------------------------------------*/ -static void proc_read10_cmd(uint8_t rhport, mscd_interface_t* p_msc) -{ - msc_cbw_t const * p_cbw = &p_msc->cbw; - msc_csw_t * p_csw = &p_msc->csw; - - uint16_t const block_cnt = rdwr10_get_blockcount(p_cbw->command); - TU_ASSERT(block_cnt, ); // prevent div by zero - - uint16_t const block_sz = p_cbw->total_bytes / block_cnt; - TU_ASSERT(block_sz, ); // prevent div by zero - - // Adjust lba with transferred bytes - uint32_t const lba = rdwr10_get_lba(p_cbw->command) + (p_msc->xferred_len / block_sz); - - // remaining bytes capped at class buffer - int32_t nbytes = (int32_t) tu_min32(sizeof(_mscd_buf), p_cbw->total_bytes-p_msc->xferred_len); - - // Application can consume smaller bytes - nbytes = tud_msc_read10_cb(p_cbw->lun, lba, p_msc->xferred_len % block_sz, _mscd_buf, (uint32_t) nbytes); - - if ( nbytes < 0 ) - { - // negative means error -> pipe is stalled & status in CSW set to failed - p_csw->data_residue = p_cbw->total_bytes - p_msc->xferred_len; - p_csw->status = MSC_CSW_STATUS_FAILED; - - tud_msc_set_sense(p_cbw->lun, SCSI_SENSE_ILLEGAL_REQUEST, 0x20, 0x00); // Sense = Invalid Command Operation - usbd_edpt_stall(rhport, p_msc->ep_in); - } - else if ( nbytes == 0 ) - { - // zero means not ready -> simulate an transfer complete so that this driver callback will fired again - dcd_event_xfer_complete(rhport, p_msc->ep_in, 0, XFER_RESULT_SUCCESS, false); - } - else - { - TU_ASSERT( usbd_edpt_xfer(rhport, p_msc->ep_in, _mscd_buf, nbytes), ); - } -} - -static void proc_write10_cmd(uint8_t rhport, mscd_interface_t* p_msc) -{ - msc_cbw_t const * p_cbw = &p_msc->cbw; - bool writable = true; - if (tud_msc_is_writable_cb) { - writable = tud_msc_is_writable_cb(p_cbw->lun); - } - if (!writable) { - msc_csw_t* p_csw = &p_msc->csw; - p_csw->data_residue = p_cbw->total_bytes; - p_csw->status = MSC_CSW_STATUS_FAILED; - - tud_msc_set_sense(p_cbw->lun, SCSI_SENSE_DATA_PROTECT, 0x27, 0x00); // Sense = Write protected - usbd_edpt_stall(rhport, p_msc->ep_out); - return; - } - - // remaining bytes capped at class buffer - int32_t nbytes = (int32_t) tu_min32(sizeof(_mscd_buf), p_cbw->total_bytes-p_msc->xferred_len); - - // Write10 callback will be called later when usb transfer complete - TU_ASSERT( usbd_edpt_xfer(rhport, p_msc->ep_out, _mscd_buf, nbytes), ); -} - -#endif +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#include "tusb_option.h" + +#if (TUSB_OPT_DEVICE_ENABLED && CFG_TUD_MSC) + +#include "common/tusb_common.h" +#include "msc_device.h" +#include "device/usbd_pvt.h" + +//--------------------------------------------------------------------+ +// MACRO CONSTANT TYPEDEF +//--------------------------------------------------------------------+ +enum +{ + MSC_STAGE_CMD = 0, + MSC_STAGE_DATA, + MSC_STAGE_STATUS, + MSC_STAGE_STATUS_SENT +}; + +typedef struct +{ + // TODO optimize alignment + CFG_TUSB_MEM_ALIGN msc_cbw_t cbw; + CFG_TUSB_MEM_ALIGN msc_csw_t csw; + + uint8_t itf_num; + uint8_t ep_in; + uint8_t ep_out; + + // Bulk Only Transfer (BOT) Protocol + uint8_t stage; + uint32_t total_len; + uint32_t xferred_len; // numbered of bytes transferred so far in the Data Stage + + // Sense Response Data + uint8_t sense_key; + uint8_t add_sense_code; + uint8_t add_sense_qualifier; +}mscd_interface_t; + +CFG_TUSB_MEM_SECTION CFG_TUSB_MEM_ALIGN static mscd_interface_t _mscd_itf; +CFG_TUSB_MEM_SECTION CFG_TUSB_MEM_ALIGN static uint8_t _mscd_buf[CFG_TUD_MSC_BUFSIZE]; + +//--------------------------------------------------------------------+ +// INTERNAL OBJECT & FUNCTION DECLARATION +//--------------------------------------------------------------------+ +static void proc_read10_cmd(uint8_t rhport, mscd_interface_t* p_msc); +static void proc_write10_cmd(uint8_t rhport, mscd_interface_t* p_msc); + +static inline uint32_t rdwr10_get_lba(uint8_t const command[]) +{ + // read10 & write10 has the same format + scsi_write10_t* p_rdwr10 = (scsi_write10_t*) command; + + // copy first to prevent mis-aligned access + uint32_t lba; + memcpy(&lba, &p_rdwr10->lba, 4); + + // lba is in Big Endian format + return tu_ntohl(lba); +} + +static inline uint16_t rdwr10_get_blockcount(uint8_t const command[]) +{ + // read10 & write10 has the same format + scsi_write10_t* p_rdwr10 = (scsi_write10_t*) command; + + // copy first to prevent mis-aligned access + uint16_t block_count; + memcpy(&block_count, &p_rdwr10->block_count, 2); + + return tu_ntohs(block_count); +} + +//--------------------------------------------------------------------+ +// Debug +//--------------------------------------------------------------------+ +#if CFG_TUSB_DEBUG >= 2 + +static lookup_entry_t const _msc_scsi_cmd_lookup[] = +{ + { .key = SCSI_CMD_TEST_UNIT_READY , .data = "Test Unit Ready" }, + { .key = SCSI_CMD_INQUIRY , .data = "Inquiry" }, + { .key = SCSI_CMD_MODE_SELECT_6 , .data = "Mode_Select 6" }, + { .key = SCSI_CMD_MODE_SENSE_6 , .data = "Mode_Sense 6" }, + { .key = SCSI_CMD_START_STOP_UNIT , .data = "Start Stop Unit" }, + { .key = SCSI_CMD_PREVENT_ALLOW_MEDIUM_REMOVAL , .data = "Prevent Allow Medium Removal" }, + { .key = SCSI_CMD_READ_CAPACITY_10 , .data = "Read Capacity10" }, + { .key = SCSI_CMD_REQUEST_SENSE , .data = "Request Sense" }, + { .key = SCSI_CMD_READ_FORMAT_CAPACITY , .data = "Read Format Capacity" }, + { .key = SCSI_CMD_READ_10 , .data = "Read10" }, + { .key = SCSI_CMD_WRITE_10 , .data = "Write10" } +}; + +static lookup_table_t const _msc_scsi_cmd_table = +{ + .count = TU_ARRAY_SIZE(_msc_scsi_cmd_lookup), + .items = _msc_scsi_cmd_lookup +}; + +#endif + +//--------------------------------------------------------------------+ +// APPLICATION API +//--------------------------------------------------------------------+ +bool tud_msc_set_sense(uint8_t lun, uint8_t sense_key, uint8_t add_sense_code, uint8_t add_sense_qualifier) +{ + (void) lun; + + _mscd_itf.sense_key = sense_key; + _mscd_itf.add_sense_code = add_sense_code; + _mscd_itf.add_sense_qualifier = add_sense_qualifier; + + return true; +} + +//--------------------------------------------------------------------+ +// USBD Driver API +//--------------------------------------------------------------------+ +void mscd_init(void) +{ + tu_memclr(&_mscd_itf, sizeof(mscd_interface_t)); +} + +void mscd_reset(uint8_t rhport) +{ + (void) rhport; + tu_memclr(&_mscd_itf, sizeof(mscd_interface_t)); +} + +bool mscd_open(uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t *p_len) +{ + // only support SCSI's BOT protocol + TU_ASSERT(MSC_SUBCLASS_SCSI == itf_desc->bInterfaceSubClass && + MSC_PROTOCOL_BOT == itf_desc->bInterfaceProtocol); + + mscd_interface_t * p_msc = &_mscd_itf; + + // Open endpoint pair + TU_ASSERT( usbd_open_edpt_pair(rhport, tu_desc_next(itf_desc), 2, TUSB_XFER_BULK, &p_msc->ep_out, &p_msc->ep_in) ); + + p_msc->itf_num = itf_desc->bInterfaceNumber; + (*p_len) = sizeof(tusb_desc_interface_t) + 2*sizeof(tusb_desc_endpoint_t); + + // Prepare for Command Block Wrapper + TU_ASSERT( usbd_edpt_xfer(rhport, p_msc->ep_out, (uint8_t*) &p_msc->cbw, sizeof(msc_cbw_t)) ); + + return true; +} + +// Handle class control request +// return false to stall control endpoint (e.g unsupported request) +bool mscd_control_request(uint8_t rhport, tusb_control_request_t const * p_request) +{ + // Handle class request only + TU_VERIFY(p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS); + + switch ( p_request->bRequest ) + { + case MSC_REQ_RESET: + // TODO: Actually reset interface. + tud_control_status(rhport, p_request); + break; + + case MSC_REQ_GET_MAX_LUN: + { + uint8_t maxlun = 1; + if (tud_msc_get_maxlun_cb) maxlun = tud_msc_get_maxlun_cb(); + TU_VERIFY(maxlun); + + // MAX LUN is minus 1 by specs + maxlun--; + + tud_control_xfer(rhport, p_request, &maxlun, 1); + } + break; + + default: return false; // stall unsupported request + } + + return true; +} + +// Invoked when class request DATA stage is finished. +// return false to stall control endpoint (e.g Host send non-sense DATA) +bool mscd_control_complete(uint8_t rhport, tusb_control_request_t const * request) +{ + (void) rhport; + (void) request; + + // nothing to do + return true; +} + +// return response's length (copied to buffer). Negative if it is not an built-in command or indicate Failed status (CSW) +// In case of a failed status, sense key must be set for reason of failure +int32_t proc_builtin_scsi(uint8_t lun, uint8_t const scsi_cmd[16], uint8_t* buffer, uint32_t bufsize) +{ + (void) bufsize; // TODO refractor later + int32_t resplen; + + switch ( scsi_cmd[0] ) + { + case SCSI_CMD_TEST_UNIT_READY: + resplen = 0; + if ( !tud_msc_test_unit_ready_cb(lun) ) + { + // Failed status response + resplen = - 1; + + // If sense key is not set by callback, default to Logical Unit Not Ready, Cause Not Reportable + if ( _mscd_itf.sense_key == 0 ) tud_msc_set_sense(lun, SCSI_SENSE_NOT_READY, 0x04, 0x00); + } + break; + + case SCSI_CMD_START_STOP_UNIT: + resplen = 0; + + if (tud_msc_start_stop_cb) + { + scsi_start_stop_unit_t const * start_stop = (scsi_start_stop_unit_t const *) scsi_cmd; + if ( !tud_msc_start_stop_cb(lun, start_stop->power_condition, start_stop->start, start_stop->load_eject) ) + { + // Failed status response + resplen = - 1; + + // If sense key is not set by callback, default to Logical Unit Not Ready, Cause Not Reportable + if ( _mscd_itf.sense_key == 0 ) tud_msc_set_sense(lun, SCSI_SENSE_NOT_READY, 0x04, 0x00); + } + } + break; + + case SCSI_CMD_READ_CAPACITY_10: + { + uint32_t block_count; + uint32_t block_size; + uint16_t block_size_u16; + + tud_msc_capacity_cb(lun, &block_count, &block_size_u16); + block_size = (uint32_t) block_size_u16; + + // Invalid block size/count from callback, possibly unit is not ready + // stall this request, set sense key to NOT READY + if (block_count == 0 || block_size == 0) + { + resplen = -1; + + // If sense key is not set by callback, default to Logical Unit Not Ready, Cause Not Reportable + if ( _mscd_itf.sense_key == 0 ) tud_msc_set_sense(lun, SCSI_SENSE_NOT_READY, 0x04, 0x00); + }else + { + scsi_read_capacity10_resp_t read_capa10; + + read_capa10.last_lba = tu_htonl(block_count-1); + read_capa10.block_size = tu_htonl(block_size); + + resplen = sizeof(read_capa10); + memcpy(buffer, &read_capa10, resplen); + } + } + break; + + case SCSI_CMD_READ_FORMAT_CAPACITY: + { + scsi_read_format_capacity_data_t read_fmt_capa = + { + .list_length = 8, + .block_num = 0, + .descriptor_type = 2, // formatted media + .block_size_u16 = 0 + }; + + uint32_t block_count; + uint16_t block_size; + + tud_msc_capacity_cb(lun, &block_count, &block_size); + + // Invalid block size/count from callback, possibly unit is not ready + // stall this request, set sense key to NOT READY + if (block_count == 0 || block_size == 0) + { + resplen = -1; + + // If sense key is not set by callback, default to Logical Unit Not Ready, Cause Not Reportable + if ( _mscd_itf.sense_key == 0 ) tud_msc_set_sense(lun, SCSI_SENSE_NOT_READY, 0x04, 0x00); + }else + { + read_fmt_capa.block_num = tu_htonl(block_count); + read_fmt_capa.block_size_u16 = tu_htons(block_size); + + resplen = sizeof(read_fmt_capa); + memcpy(buffer, &read_fmt_capa, resplen); + } + } + break; + + case SCSI_CMD_INQUIRY: + { + scsi_inquiry_resp_t inquiry_rsp = + { + .is_removable = 1, + .version = 2, + .response_data_format = 2, + }; + + // vendor_id, product_id, product_rev is space padded string + memset(inquiry_rsp.vendor_id , ' ', sizeof(inquiry_rsp.vendor_id)); + memset(inquiry_rsp.product_id , ' ', sizeof(inquiry_rsp.product_id)); + memset(inquiry_rsp.product_rev, ' ', sizeof(inquiry_rsp.product_rev)); + + tud_msc_inquiry_cb(lun, inquiry_rsp.vendor_id, inquiry_rsp.product_id, inquiry_rsp.product_rev); + + resplen = sizeof(inquiry_rsp); + memcpy(buffer, &inquiry_rsp, resplen); + } + break; + + case SCSI_CMD_MODE_SENSE_6: + { + scsi_mode_sense6_resp_t mode_resp = + { + .data_len = 3, + .medium_type = 0, + .write_protected = false, + .reserved = 0, + .block_descriptor_len = 0 // no block descriptor are included + }; + + bool writable = true; + if (tud_msc_is_writable_cb) { + writable = tud_msc_is_writable_cb(lun); + } + mode_resp.write_protected = !writable; + + resplen = sizeof(mode_resp); + memcpy(buffer, &mode_resp, resplen); + } + break; + + case SCSI_CMD_REQUEST_SENSE: + { + scsi_sense_fixed_resp_t sense_rsp = + { + .response_code = 0x70, + .valid = 1 + }; + + sense_rsp.add_sense_len = sizeof(scsi_sense_fixed_resp_t) - 8; + + sense_rsp.sense_key = _mscd_itf.sense_key; + sense_rsp.add_sense_code = _mscd_itf.add_sense_code; + sense_rsp.add_sense_qualifier = _mscd_itf.add_sense_qualifier; + + resplen = sizeof(sense_rsp); + memcpy(buffer, &sense_rsp, resplen); + + // Clear sense data after copy + tud_msc_set_sense(lun, 0, 0, 0); + } + break; + + default: resplen = -1; break; + } + + return resplen; +} + +bool mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes) +{ + mscd_interface_t* p_msc = &_mscd_itf; + msc_cbw_t const * p_cbw = &p_msc->cbw; + msc_csw_t * p_csw = &p_msc->csw; + + switch (p_msc->stage) + { + case MSC_STAGE_CMD: + //------------- new CBW received -------------// + // Complete IN while waiting for CMD is usually Status of previous SCSI op, ignore it + if(ep_addr != p_msc->ep_out) return true; + + TU_ASSERT( event == XFER_RESULT_SUCCESS && + xferred_bytes == sizeof(msc_cbw_t) && p_cbw->signature == MSC_CBW_SIGNATURE ); + + TU_LOG2(" SCSI Command: %s\n", lookup_find(&_msc_scsi_cmd_table, p_cbw->command[0])); + // TU_LOG2_MEM(p_cbw, xferred_bytes, 2); + + p_csw->signature = MSC_CSW_SIGNATURE; + p_csw->tag = p_cbw->tag; + p_csw->data_residue = 0; + + /*------------- Parse command and prepare DATA -------------*/ + p_msc->stage = MSC_STAGE_DATA; + p_msc->total_len = p_cbw->total_bytes; + p_msc->xferred_len = 0; + + if (SCSI_CMD_READ_10 == p_cbw->command[0]) + { + proc_read10_cmd(rhport, p_msc); + } + else if (SCSI_CMD_WRITE_10 == p_cbw->command[0]) + { + proc_write10_cmd(rhport, p_msc); + } + else + { + // For other SCSI commands + // 1. OUT : queue transfer (invoke app callback after done) + // 2. IN & Zero: Process if is built-in, else Invoke app callback. Skip DATA if zero length + if ( (p_cbw->total_bytes > 0 ) && !tu_bit_test(p_cbw->dir, 7) ) + { + // queue transfer + TU_ASSERT( usbd_edpt_xfer(rhport, p_msc->ep_out, _mscd_buf, p_msc->total_len) ); + }else + { + int32_t resplen; + + // First process if it is a built-in commands + resplen = proc_builtin_scsi(p_cbw->lun, p_cbw->command, _mscd_buf, sizeof(_mscd_buf)); + + // Not built-in, invoke user callback + if ( (resplen < 0) && (p_msc->sense_key == 0) ) + { + resplen = tud_msc_scsi_cb(p_cbw->lun, p_cbw->command, _mscd_buf, p_msc->total_len); + } + + if ( resplen < 0 ) + { + p_msc->total_len = 0; + p_csw->status = MSC_CSW_STATUS_FAILED; + p_msc->stage = MSC_STAGE_STATUS; + + // failed but senskey is not set: default to Illegal Request + if ( p_msc->sense_key == 0 ) tud_msc_set_sense(p_cbw->lun, SCSI_SENSE_ILLEGAL_REQUEST, 0x20, 0x00); + + // Stall bulk In if needed + if (p_cbw->total_bytes) usbd_edpt_stall(rhport, p_msc->ep_in); + } + else + { + p_msc->total_len = (uint32_t) resplen; + p_csw->status = MSC_CSW_STATUS_PASSED; + + if (p_msc->total_len) + { + TU_ASSERT( p_cbw->total_bytes >= p_msc->total_len ); // cannot return more than host expect + TU_ASSERT( usbd_edpt_xfer(rhport, p_msc->ep_in, _mscd_buf, p_msc->total_len) ); + }else + { + p_msc->stage = MSC_STAGE_STATUS; + } + } + } + } + break; + + case MSC_STAGE_DATA: + TU_LOG2(" SCSI Data\n"); + //TU_LOG2_MEM(_mscd_buf, xferred_bytes, 2); + + // OUT transfer, invoke callback if needed + if ( !tu_bit_test(p_cbw->dir, 7) ) + { + if ( SCSI_CMD_WRITE_10 != p_cbw->command[0] ) + { + int32_t cb_result = tud_msc_scsi_cb(p_cbw->lun, p_cbw->command, _mscd_buf, p_msc->total_len); + + if ( cb_result < 0 ) + { + p_csw->status = MSC_CSW_STATUS_FAILED; + tud_msc_set_sense(p_cbw->lun, SCSI_SENSE_ILLEGAL_REQUEST, 0x20, 0x00); // Sense = Invalid Command Operation + }else + { + p_csw->status = MSC_CSW_STATUS_PASSED; + } + } + else + { + uint16_t const block_sz = p_cbw->total_bytes / rdwr10_get_blockcount(p_cbw->command); + + // Adjust lba with transferred bytes + uint32_t const lba = rdwr10_get_lba(p_cbw->command) + (p_msc->xferred_len / block_sz); + + // Application can consume smaller bytes + int32_t nbytes = tud_msc_write10_cb(p_cbw->lun, lba, p_msc->xferred_len % block_sz, _mscd_buf, xferred_bytes); + + if ( nbytes < 0 ) + { + // negative means error -> skip to status phase, status in CSW set to failed + p_csw->data_residue = p_cbw->total_bytes - p_msc->xferred_len; + p_csw->status = MSC_CSW_STATUS_FAILED; + p_msc->stage = MSC_STAGE_STATUS; + + tud_msc_set_sense(p_cbw->lun, SCSI_SENSE_ILLEGAL_REQUEST, 0x20, 0x00); // Sense = Invalid Command Operation + break; + }else + { + // Application consume less than what we got (including zero) + if ( nbytes < (int32_t) xferred_bytes ) + { + if ( nbytes > 0 ) + { + p_msc->xferred_len += nbytes; + memmove(_mscd_buf, _mscd_buf+nbytes, xferred_bytes-nbytes); + } + + // simulate an transfer complete with adjusted parameters --> this driver callback will fired again + dcd_event_xfer_complete(rhport, p_msc->ep_out, xferred_bytes-nbytes, XFER_RESULT_SUCCESS, false); + + return true; // skip the rest + } + else + { + // Application consume all bytes in our buffer. Nothing to do, process with normal flow + } + } + } + } + + // Accumulate data so far + p_msc->xferred_len += xferred_bytes; + + if ( p_msc->xferred_len >= p_msc->total_len ) + { + // Data Stage is complete + p_msc->stage = MSC_STAGE_STATUS; + } + else + { + // READ10 & WRITE10 Can be executed with large bulk of data e.g write 8K bytes (several flash write) + // We break it into multiple smaller command whose data size is up to CFG_TUD_MSC_BUFSIZE + if (SCSI_CMD_READ_10 == p_cbw->command[0]) + { + proc_read10_cmd(rhport, p_msc); + } + else if (SCSI_CMD_WRITE_10 == p_cbw->command[0]) + { + proc_write10_cmd(rhport, p_msc); + }else + { + // No other command take more than one transfer yet -> unlikely error + TU_BREAKPOINT(); + } + } + break; + + case MSC_STAGE_STATUS: + // processed immediately after this switch, supposedly to be empty + break; + + case MSC_STAGE_STATUS_SENT: + // Wait for the Status phase to complete + if( (ep_addr == p_msc->ep_in) && (xferred_bytes == sizeof(msc_csw_t)) ) + { + TU_LOG2(" SCSI Status: %u\n", p_csw->status); + // TU_LOG2_MEM(p_csw, xferred_bytes, 2); + + // Move to default CMD stage + p_msc->stage = MSC_STAGE_CMD; + + // Queue for the next CBW + TU_ASSERT( usbd_edpt_xfer(rhport, p_msc->ep_out, (uint8_t*) &p_msc->cbw, sizeof(msc_cbw_t)) ); + } + break; + + default : break; + } + + if ( p_msc->stage == MSC_STAGE_STATUS ) + { + // Either endpoints is stalled, need to wait until it is cleared by host + if ( usbd_edpt_stalled(rhport, p_msc->ep_in) || usbd_edpt_stalled(rhport, p_msc->ep_out) ) + { + // simulate an transfer complete with adjusted parameters --> this driver callback will fired again + // and response with status phase after halted endpoints are cleared. + // note: use ep_out to prevent confusing with STATUS complete + dcd_event_xfer_complete(rhport, p_msc->ep_out, 0, XFER_RESULT_SUCCESS, false); + } + else + { + // Invoke complete callback if defined + switch(p_cbw->command[0]) + { + case SCSI_CMD_READ_10: + if ( tud_msc_read10_complete_cb ) tud_msc_read10_complete_cb(p_cbw->lun); + break; + + case SCSI_CMD_WRITE_10: + if ( tud_msc_write10_complete_cb ) tud_msc_write10_complete_cb(p_cbw->lun); + break; + + default: + if ( tud_msc_scsi_complete_cb ) tud_msc_scsi_complete_cb(p_cbw->lun, p_cbw->command); + break; + } + + // Move to Status Sent stage + p_msc->stage = MSC_STAGE_STATUS_SENT; + + // Send SCSI Status + TU_ASSERT(usbd_edpt_xfer(rhport, p_msc->ep_in , (uint8_t*) &p_msc->csw, sizeof(msc_csw_t))); + } + } + + return true; +} + +/*------------------------------------------------------------------*/ +/* SCSI Command Process + *------------------------------------------------------------------*/ +static void proc_read10_cmd(uint8_t rhport, mscd_interface_t* p_msc) +{ + msc_cbw_t const * p_cbw = &p_msc->cbw; + msc_csw_t * p_csw = &p_msc->csw; + + uint16_t const block_cnt = rdwr10_get_blockcount(p_cbw->command); + TU_ASSERT(block_cnt, ); // prevent div by zero + + uint16_t const block_sz = p_cbw->total_bytes / block_cnt; + TU_ASSERT(block_sz, ); // prevent div by zero + + // Adjust lba with transferred bytes + uint32_t const lba = rdwr10_get_lba(p_cbw->command) + (p_msc->xferred_len / block_sz); + + // remaining bytes capped at class buffer + int32_t nbytes = (int32_t) tu_min32(sizeof(_mscd_buf), p_cbw->total_bytes-p_msc->xferred_len); + + // Application can consume smaller bytes + nbytes = tud_msc_read10_cb(p_cbw->lun, lba, p_msc->xferred_len % block_sz, _mscd_buf, (uint32_t) nbytes); + + if ( nbytes < 0 ) + { + // negative means error -> pipe is stalled & status in CSW set to failed + p_csw->data_residue = p_cbw->total_bytes - p_msc->xferred_len; + p_csw->status = MSC_CSW_STATUS_FAILED; + + tud_msc_set_sense(p_cbw->lun, SCSI_SENSE_ILLEGAL_REQUEST, 0x20, 0x00); // Sense = Invalid Command Operation + usbd_edpt_stall(rhport, p_msc->ep_in); + } + else if ( nbytes == 0 ) + { + // zero means not ready -> simulate an transfer complete so that this driver callback will fired again + dcd_event_xfer_complete(rhport, p_msc->ep_in, 0, XFER_RESULT_SUCCESS, false); + } + else + { + TU_ASSERT( usbd_edpt_xfer(rhport, p_msc->ep_in, _mscd_buf, nbytes), ); + } +} + +static void proc_write10_cmd(uint8_t rhport, mscd_interface_t* p_msc) +{ + msc_cbw_t const * p_cbw = &p_msc->cbw; + bool writable = true; + if (tud_msc_is_writable_cb) { + writable = tud_msc_is_writable_cb(p_cbw->lun); + } + if (!writable) { + msc_csw_t* p_csw = &p_msc->csw; + p_csw->data_residue = p_cbw->total_bytes; + p_csw->status = MSC_CSW_STATUS_FAILED; + + tud_msc_set_sense(p_cbw->lun, SCSI_SENSE_DATA_PROTECT, 0x27, 0x00); // Sense = Write protected + usbd_edpt_stall(rhport, p_msc->ep_out); + return; + } + + // remaining bytes capped at class buffer + int32_t nbytes = (int32_t) tu_min32(sizeof(_mscd_buf), p_cbw->total_bytes-p_msc->xferred_len); + + // Write10 callback will be called later when usb transfer complete + TU_ASSERT( usbd_edpt_xfer(rhport, p_msc->ep_out, _mscd_buf, nbytes), ); +} + +#endif diff --git a/src/class/msc/msc_device.h b/src/class/msc/msc_device.h index 8da9cfaa..66180777 100644 --- a/src/class/msc/msc_device.h +++ b/src/class/msc/msc_device.h @@ -1,165 +1,165 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2019 Ha Thach (tinyusb.org) - * - * 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. - * - * This file is part of the TinyUSB stack. - */ - -#ifndef _TUSB_MSC_DEVICE_H_ -#define _TUSB_MSC_DEVICE_H_ - -#include "common/tusb_common.h" -#include "device/usbd.h" -#include "msc.h" - -#ifdef __cplusplus - extern "C" { -#endif - -//--------------------------------------------------------------------+ -// Class Driver Configuration -//--------------------------------------------------------------------+ -TU_VERIFY_STATIC(CFG_TUD_MSC_BUFSIZE < UINT16_MAX, "Size is not correct"); - -#ifndef CFG_TUD_MSC_BUFSIZE - #error CFG_TUD_MSC_BUFSIZE must be defined, value of a block size should work well, the more the better -#endif - -/** \addtogroup ClassDriver_MSC - * @{ - * \defgroup MSC_Device Device - * @{ */ - -bool tud_msc_set_sense(uint8_t lun, uint8_t sense_key, uint8_t add_sense_code, uint8_t add_sense_qualifier); - -//--------------------------------------------------------------------+ -// Application Callbacks (WEAK is optional) -//--------------------------------------------------------------------+ - -/** - * Invoked when received \ref SCSI_CMD_READ_10 command - * \param[in] lun Logical unit number - * \param[in] lba Logical Block Address to be read - * \param[in] offset Byte offset from LBA - * \param[out] buffer Buffer which application need to update with the response data. - * \param[in] bufsize Requested bytes - * - * \return Number of byte read, if it is less than requested bytes by \a \b bufsize. Tinyusb will transfer - * this amount first and invoked this again for remaining data. - * - * \retval zero Indicate application is not ready yet to response e.g disk I/O is not complete. - * tinyusb will invoke this callback with the same parameters again some time later. - * - * \retval negative Indicate error e.g reading disk I/O. tinyusb will \b STALL the corresponding - * endpoint and return failed status in command status wrapper phase. - */ -int32_t tud_msc_read10_cb (uint8_t lun, uint32_t lba, uint32_t offset, void* buffer, uint32_t bufsize); - -/** - * Invoked when received \ref SCSI_CMD_WRITE_10 command - * \param[in] lun Logical unit number - * \param[in] lba Logical Block Address to be write - * \param[in] offset Byte offset from LBA - * \param[out] buffer Buffer which holds written data. - * \param[in] bufsize Requested bytes - * - * \return Number of byte written, if it is less than requested bytes by \a \b bufsize. Tinyusb will proceed with - * other work and invoked this again with adjusted parameters. - * - * \retval zero Indicate application is not ready yet e.g disk I/O is not complete. - * Tinyusb will invoke this callback with the same parameters again some time later. - * - * \retval negative Indicate error writing disk I/O. Tinyusb will \b STALL the corresponding - * endpoint and return failed status in command status wrapper phase. - */ -int32_t tud_msc_write10_cb (uint8_t lun, uint32_t lba, uint32_t offset, uint8_t* buffer, uint32_t bufsize); - -// Invoked when received SCSI_CMD_INQUIRY -// Application fill vendor id, product id and revision with string up to 8, 16, 4 characters respectively -void tud_msc_inquiry_cb(uint8_t lun, uint8_t vendor_id[8], uint8_t product_id[16], uint8_t product_rev[4]); - -// Invoked when received Test Unit Ready command. -// return true allowing host to read/write this LUN e.g SD card inserted -bool tud_msc_test_unit_ready_cb(uint8_t lun); - -// Invoked when received SCSI_CMD_READ_CAPACITY_10 and SCSI_CMD_READ_FORMAT_CAPACITY to determine the disk size -// Application update block count and block size -void tud_msc_capacity_cb(uint8_t lun, uint32_t* block_count, uint16_t* block_size); - -/** - * Invoked when received an SCSI command not in built-in list below. - * - READ_CAPACITY10, READ_FORMAT_CAPACITY, INQUIRY, TEST_UNIT_READY, START_STOP_UNIT, MODE_SENSE6, REQUEST_SENSE - * - READ10 and WRITE10 has their own callbacks - * - * \param[in] lun Logical unit number - * \param[in] scsi_cmd SCSI command contents which application must examine to response accordingly - * \param[out] buffer Buffer for SCSI Data Stage. - * - For INPUT: application must fill this with response. - * - For OUTPUT it holds the Data from host - * \param[in] bufsize Buffer's length. - * - * \return Actual bytes processed, can be zero for no-data command. - * \retval negative Indicate error e.g unsupported command, tinyusb will \b STALL the corresponding - * endpoint and return failed status in command status wrapper phase. - */ -int32_t tud_msc_scsi_cb (uint8_t lun, uint8_t const scsi_cmd[16], void* buffer, uint16_t bufsize); - -/*------------- Optional callbacks -------------*/ - -// Invoked when received GET_MAX_LUN request, required for multiple LUNs implementation -TU_ATTR_WEAK uint8_t tud_msc_get_maxlun_cb(void); - -// Invoked when received Start Stop Unit command -// - Start = 0 : stopped power mode, if load_eject = 1 : unload disk storage -// - Start = 1 : active mode, if load_eject = 1 : load disk storage -TU_ATTR_WEAK bool tud_msc_start_stop_cb(uint8_t lun, uint8_t power_condition, bool start, bool load_eject); - -// Invoked when Read10 command is complete -TU_ATTR_WEAK void tud_msc_read10_complete_cb(uint8_t lun); - -// Invoke when Write10 command is complete, can be used to flush flash caching -TU_ATTR_WEAK void tud_msc_write10_complete_cb(uint8_t lun); - -// Invoked when command in tud_msc_scsi_cb is complete -TU_ATTR_WEAK void tud_msc_scsi_complete_cb(uint8_t lun, uint8_t const scsi_cmd[16]); - -// Hook to make a mass storage device read-only. TODO remove -TU_ATTR_WEAK bool tud_msc_is_writable_cb(uint8_t lun); - -/** @} */ -/** @} */ - -//--------------------------------------------------------------------+ -// Internal Class Driver API -//--------------------------------------------------------------------+ -void mscd_init (void); -void mscd_reset (uint8_t rhport); -bool mscd_open (uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t *p_length); -bool mscd_control_request (uint8_t rhport, tusb_control_request_t const * p_request); -bool mscd_control_complete (uint8_t rhport, tusb_control_request_t const * p_request); -bool mscd_xfer_cb (uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes); - -#ifdef __cplusplus - } -#endif - -#endif /* _TUSB_MSC_DEVICE_H_ */ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#ifndef _TUSB_MSC_DEVICE_H_ +#define _TUSB_MSC_DEVICE_H_ + +#include "common/tusb_common.h" +#include "device/usbd.h" +#include "msc.h" + +#ifdef __cplusplus + extern "C" { +#endif + +//--------------------------------------------------------------------+ +// Class Driver Configuration +//--------------------------------------------------------------------+ +TU_VERIFY_STATIC(CFG_TUD_MSC_BUFSIZE < UINT16_MAX, "Size is not correct"); + +#ifndef CFG_TUD_MSC_BUFSIZE + #error CFG_TUD_MSC_BUFSIZE must be defined, value of a block size should work well, the more the better +#endif + +/** \addtogroup ClassDriver_MSC + * @{ + * \defgroup MSC_Device Device + * @{ */ + +bool tud_msc_set_sense(uint8_t lun, uint8_t sense_key, uint8_t add_sense_code, uint8_t add_sense_qualifier); + +//--------------------------------------------------------------------+ +// Application Callbacks (WEAK is optional) +//--------------------------------------------------------------------+ + +/** + * Invoked when received \ref SCSI_CMD_READ_10 command + * \param[in] lun Logical unit number + * \param[in] lba Logical Block Address to be read + * \param[in] offset Byte offset from LBA + * \param[out] buffer Buffer which application need to update with the response data. + * \param[in] bufsize Requested bytes + * + * \return Number of byte read, if it is less than requested bytes by \a \b bufsize. Tinyusb will transfer + * this amount first and invoked this again for remaining data. + * + * \retval zero Indicate application is not ready yet to response e.g disk I/O is not complete. + * tinyusb will invoke this callback with the same parameters again some time later. + * + * \retval negative Indicate error e.g reading disk I/O. tinyusb will \b STALL the corresponding + * endpoint and return failed status in command status wrapper phase. + */ +int32_t tud_msc_read10_cb (uint8_t lun, uint32_t lba, uint32_t offset, void* buffer, uint32_t bufsize); + +/** + * Invoked when received \ref SCSI_CMD_WRITE_10 command + * \param[in] lun Logical unit number + * \param[in] lba Logical Block Address to be write + * \param[in] offset Byte offset from LBA + * \param[out] buffer Buffer which holds written data. + * \param[in] bufsize Requested bytes + * + * \return Number of byte written, if it is less than requested bytes by \a \b bufsize. Tinyusb will proceed with + * other work and invoked this again with adjusted parameters. + * + * \retval zero Indicate application is not ready yet e.g disk I/O is not complete. + * Tinyusb will invoke this callback with the same parameters again some time later. + * + * \retval negative Indicate error writing disk I/O. Tinyusb will \b STALL the corresponding + * endpoint and return failed status in command status wrapper phase. + */ +int32_t tud_msc_write10_cb (uint8_t lun, uint32_t lba, uint32_t offset, uint8_t* buffer, uint32_t bufsize); + +// Invoked when received SCSI_CMD_INQUIRY +// Application fill vendor id, product id and revision with string up to 8, 16, 4 characters respectively +void tud_msc_inquiry_cb(uint8_t lun, uint8_t vendor_id[8], uint8_t product_id[16], uint8_t product_rev[4]); + +// Invoked when received Test Unit Ready command. +// return true allowing host to read/write this LUN e.g SD card inserted +bool tud_msc_test_unit_ready_cb(uint8_t lun); + +// Invoked when received SCSI_CMD_READ_CAPACITY_10 and SCSI_CMD_READ_FORMAT_CAPACITY to determine the disk size +// Application update block count and block size +void tud_msc_capacity_cb(uint8_t lun, uint32_t* block_count, uint16_t* block_size); + +/** + * Invoked when received an SCSI command not in built-in list below. + * - READ_CAPACITY10, READ_FORMAT_CAPACITY, INQUIRY, TEST_UNIT_READY, START_STOP_UNIT, MODE_SENSE6, REQUEST_SENSE + * - READ10 and WRITE10 has their own callbacks + * + * \param[in] lun Logical unit number + * \param[in] scsi_cmd SCSI command contents which application must examine to response accordingly + * \param[out] buffer Buffer for SCSI Data Stage. + * - For INPUT: application must fill this with response. + * - For OUTPUT it holds the Data from host + * \param[in] bufsize Buffer's length. + * + * \return Actual bytes processed, can be zero for no-data command. + * \retval negative Indicate error e.g unsupported command, tinyusb will \b STALL the corresponding + * endpoint and return failed status in command status wrapper phase. + */ +int32_t tud_msc_scsi_cb (uint8_t lun, uint8_t const scsi_cmd[16], void* buffer, uint16_t bufsize); + +/*------------- Optional callbacks -------------*/ + +// Invoked when received GET_MAX_LUN request, required for multiple LUNs implementation +TU_ATTR_WEAK uint8_t tud_msc_get_maxlun_cb(void); + +// Invoked when received Start Stop Unit command +// - Start = 0 : stopped power mode, if load_eject = 1 : unload disk storage +// - Start = 1 : active mode, if load_eject = 1 : load disk storage +TU_ATTR_WEAK bool tud_msc_start_stop_cb(uint8_t lun, uint8_t power_condition, bool start, bool load_eject); + +// Invoked when Read10 command is complete +TU_ATTR_WEAK void tud_msc_read10_complete_cb(uint8_t lun); + +// Invoke when Write10 command is complete, can be used to flush flash caching +TU_ATTR_WEAK void tud_msc_write10_complete_cb(uint8_t lun); + +// Invoked when command in tud_msc_scsi_cb is complete +TU_ATTR_WEAK void tud_msc_scsi_complete_cb(uint8_t lun, uint8_t const scsi_cmd[16]); + +// Hook to make a mass storage device read-only. TODO remove +TU_ATTR_WEAK bool tud_msc_is_writable_cb(uint8_t lun); + +/** @} */ +/** @} */ + +//--------------------------------------------------------------------+ +// Internal Class Driver API +//--------------------------------------------------------------------+ +void mscd_init (void); +void mscd_reset (uint8_t rhport); +bool mscd_open (uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t *p_length); +bool mscd_control_request (uint8_t rhport, tusb_control_request_t const * p_request); +bool mscd_control_complete (uint8_t rhport, tusb_control_request_t const * p_request); +bool mscd_xfer_cb (uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes); + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_MSC_DEVICE_H_ */ diff --git a/src/class/msc/msc_host.c b/src/class/msc/msc_host.c index 0507c5f6..e20969f5 100644 --- a/src/class/msc/msc_host.c +++ b/src/class/msc/msc_host.c @@ -1,413 +1,413 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2019 Ha Thach (tinyusb.org) - * - * 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. - * - * This file is part of the TinyUSB stack. - */ - -#include "tusb_option.h" - -#if TUSB_OPT_HOST_ENABLED & CFG_TUH_MSC - -//--------------------------------------------------------------------+ -// INCLUDE -//--------------------------------------------------------------------+ -#include "common/tusb_common.h" -#include "msc_host.h" - -//--------------------------------------------------------------------+ -// MACRO CONSTANT TYPEDEF -//--------------------------------------------------------------------+ -CFG_TUSB_MEM_SECTION static msch_interface_t msch_data[CFG_TUSB_HOST_DEVICE_MAX]; - -//------------- Initalization Data -------------// -static osal_semaphore_def_t msch_sem_def; -static osal_semaphore_t msch_sem_hdl; - -// buffer used to read scsi information when mounted, largest response data currently is inquiry -CFG_TUSB_MEM_SECTION TU_ATTR_ALIGNED(4) static uint8_t msch_buffer[sizeof(scsi_inquiry_resp_t)]; - -//--------------------------------------------------------------------+ -// INTERNAL OBJECT & FUNCTION DECLARATION -//--------------------------------------------------------------------+ - -//--------------------------------------------------------------------+ -// PUBLIC API -//--------------------------------------------------------------------+ -bool tuh_msc_is_mounted(uint8_t dev_addr) -{ - return tuh_device_is_configured(dev_addr) && // is configured can be omitted - msch_data[dev_addr-1].is_initialized; -} - -bool tuh_msc_is_busy(uint8_t dev_addr) -{ - return msch_data[dev_addr-1].is_initialized && - hcd_edpt_busy(dev_addr, msch_data[dev_addr-1].ep_in); -} - -uint8_t const* tuh_msc_get_vendor_name(uint8_t dev_addr) -{ - return msch_data[dev_addr-1].is_initialized ? msch_data[dev_addr-1].vendor_id : NULL; -} - -uint8_t const* tuh_msc_get_product_name(uint8_t dev_addr) -{ - return msch_data[dev_addr-1].is_initialized ? msch_data[dev_addr-1].product_id : NULL; -} - -tusb_error_t tuh_msc_get_capacity(uint8_t dev_addr, uint32_t* p_last_lba, uint32_t* p_block_size) -{ - if ( !msch_data[dev_addr-1].is_initialized ) return TUSB_ERROR_MSCH_DEVICE_NOT_MOUNTED; - TU_ASSERT(p_last_lba != NULL && p_block_size != NULL, TUSB_ERROR_INVALID_PARA); - - (*p_last_lba) = msch_data[dev_addr-1].last_lba; - (*p_block_size) = (uint32_t) msch_data[dev_addr-1].block_size; - - return TUSB_ERROR_NONE; -} - -//--------------------------------------------------------------------+ -// PUBLIC API: SCSI COMMAND -//--------------------------------------------------------------------+ -static inline void msc_cbw_add_signature(msc_cbw_t *p_cbw, uint8_t lun) -{ - p_cbw->signature = MSC_CBW_SIGNATURE; - p_cbw->tag = 0xCAFECAFE; - p_cbw->lun = lun; -} - -static tusb_error_t msch_command_xfer(uint8_t dev_addr, msch_interface_t * p_msch, void* p_buffer) -{ - if ( NULL != p_buffer) - { // there is data phase - if (p_msch->cbw.dir & TUSB_DIR_IN_MASK) - { - TU_ASSERT( hcd_pipe_xfer(dev_addr, p_msch->ep_out, (uint8_t*) &p_msch->cbw, sizeof(msc_cbw_t), false), TUSB_ERROR_FAILED ); - TU_ASSERT( hcd_pipe_queue_xfer(dev_addr, p_msch->ep_in , p_buffer, p_msch->cbw.total_bytes), TUSB_ERROR_FAILED ); - }else - { - TU_ASSERT( hcd_pipe_queue_xfer(dev_addr, p_msch->ep_out, (uint8_t*) &p_msch->cbw, sizeof(msc_cbw_t)), TUSB_ERROR_FAILED ); - TU_ASSERT( hcd_pipe_xfer(dev_addr, p_msch->ep_out , p_buffer, p_msch->cbw.total_bytes, false), TUSB_ERROR_FAILED ); - } - } - - TU_ASSERT( hcd_pipe_xfer(dev_addr, p_msch->ep_in , (uint8_t*) &p_msch->csw, sizeof(msc_csw_t), true), TUSB_ERROR_FAILED); - - return TUSB_ERROR_NONE; -} - -tusb_error_t tusbh_msc_inquiry(uint8_t dev_addr, uint8_t lun, uint8_t *p_data) -{ - msch_interface_t* p_msch = &msch_data[dev_addr-1]; - - //------------- Command Block Wrapper -------------// - msc_cbw_add_signature(&p_msch->cbw, lun); - p_msch->cbw.total_bytes = sizeof(scsi_inquiry_resp_t); - p_msch->cbw.dir = TUSB_DIR_IN_MASK; - p_msch->cbw.cmd_len = sizeof(scsi_inquiry_t); - - //------------- SCSI command -------------// - scsi_inquiry_t cmd_inquiry = - { - .cmd_code = SCSI_CMD_INQUIRY, - .alloc_length = sizeof(scsi_inquiry_resp_t) - }; - - memcpy(p_msch->cbw.command, &cmd_inquiry, p_msch->cbw.cmd_len); - - TU_ASSERT_ERR ( msch_command_xfer(dev_addr, p_msch, p_data) ); - - return TUSB_ERROR_NONE; -} - -tusb_error_t tusbh_msc_read_capacity10(uint8_t dev_addr, uint8_t lun, uint8_t *p_data) -{ - msch_interface_t* p_msch = &msch_data[dev_addr-1]; - - //------------- Command Block Wrapper -------------// - msc_cbw_add_signature(&p_msch->cbw, lun); - p_msch->cbw.total_bytes = sizeof(scsi_read_capacity10_resp_t); - p_msch->cbw.dir = TUSB_DIR_IN_MASK; - p_msch->cbw.cmd_len = sizeof(scsi_read_capacity10_t); - - //------------- SCSI command -------------// - scsi_read_capacity10_t cmd_read_capacity10 = - { - .cmd_code = SCSI_CMD_READ_CAPACITY_10, - .lba = 0, - .partial_medium_indicator = 0 - }; - - memcpy(p_msch->cbw.command, &cmd_read_capacity10, p_msch->cbw.cmd_len); - - TU_ASSERT_ERR ( msch_command_xfer(dev_addr, p_msch, p_data) ); - - return TUSB_ERROR_NONE; -} - -tusb_error_t tuh_msc_request_sense(uint8_t dev_addr, uint8_t lun, uint8_t *p_data) -{ - (void) lun; // TODO [MSCH] multiple lun support - - msch_interface_t* p_msch = &msch_data[dev_addr-1]; - - //------------- Command Block Wrapper -------------// - p_msch->cbw.total_bytes = 18; - p_msch->cbw.dir = TUSB_DIR_IN_MASK; - p_msch->cbw.cmd_len = sizeof(scsi_request_sense_t); - - //------------- SCSI command -------------// - scsi_request_sense_t cmd_request_sense = - { - .cmd_code = SCSI_CMD_REQUEST_SENSE, - .alloc_length = 18 - }; - - memcpy(p_msch->cbw.command, &cmd_request_sense, p_msch->cbw.cmd_len); - - TU_ASSERT_ERR ( msch_command_xfer(dev_addr, p_msch, p_data) ); - - return TUSB_ERROR_NONE; -} - -tusb_error_t tuh_msc_test_unit_ready(uint8_t dev_addr, uint8_t lun, msc_csw_t * p_csw) -{ - msch_interface_t* p_msch = &msch_data[dev_addr-1]; - - //------------- Command Block Wrapper -------------// - msc_cbw_add_signature(&p_msch->cbw, lun); - - p_msch->cbw.total_bytes = 0; // Number of bytes - p_msch->cbw.dir = TUSB_DIR_OUT; - p_msch->cbw.cmd_len = sizeof(scsi_test_unit_ready_t); - - //------------- SCSI command -------------// - scsi_test_unit_ready_t cmd_test_unit_ready = - { - .cmd_code = SCSI_CMD_TEST_UNIT_READY, - .lun = lun // according to wiki - }; - - memcpy(p_msch->cbw.command, &cmd_test_unit_ready, p_msch->cbw.cmd_len); - - // TODO MSCH refractor test uinit ready - TU_ASSERT( hcd_pipe_xfer(dev_addr, p_msch->ep_out, (uint8_t*) &p_msch->cbw, sizeof(msc_cbw_t), false), TUSB_ERROR_FAILED ); - TU_ASSERT( hcd_pipe_xfer(dev_addr, p_msch->ep_in , (uint8_t*) p_csw, sizeof(msc_csw_t), true), TUSB_ERROR_FAILED ); - - return TUSB_ERROR_NONE; -} - -tusb_error_t tuh_msc_read10(uint8_t dev_addr, uint8_t lun, void * p_buffer, uint32_t lba, uint16_t block_count) -{ - msch_interface_t* p_msch = &msch_data[dev_addr-1]; - - //------------- Command Block Wrapper -------------// - msc_cbw_add_signature(&p_msch->cbw, lun); - - p_msch->cbw.total_bytes = p_msch->block_size*block_count; // Number of bytes - p_msch->cbw.dir = TUSB_DIR_IN_MASK; - p_msch->cbw.cmd_len = sizeof(scsi_read10_t); - - //------------- SCSI command -------------// - scsi_read10_t cmd_read10 = - { - .cmd_code = SCSI_CMD_READ_10, - .lba = tu_htonl(lba), - .block_count = tu_htons(block_count) - }; - - memcpy(p_msch->cbw.command, &cmd_read10, p_msch->cbw.cmd_len); - - TU_ASSERT_ERR ( msch_command_xfer(dev_addr, p_msch, p_buffer)); - - return TUSB_ERROR_NONE; -} - -tusb_error_t tuh_msc_write10(uint8_t dev_addr, uint8_t lun, void const * p_buffer, uint32_t lba, uint16_t block_count) -{ - msch_interface_t* p_msch = &msch_data[dev_addr-1]; - - //------------- Command Block Wrapper -------------// - msc_cbw_add_signature(&p_msch->cbw, lun); - - p_msch->cbw.total_bytes = p_msch->block_size*block_count; // Number of bytes - p_msch->cbw.dir = TUSB_DIR_OUT; - p_msch->cbw.cmd_len = sizeof(scsi_write10_t); - - //------------- SCSI command -------------// - scsi_write10_t cmd_write10 = - { - .cmd_code = SCSI_CMD_WRITE_10, - .lba = tu_htonl(lba), - .block_count = tu_htons(block_count) - }; - - memcpy(p_msch->cbw.command, &cmd_write10, p_msch->cbw.cmd_len); - - TU_ASSERT_ERR ( msch_command_xfer(dev_addr, p_msch, (void*) p_buffer)); - - return TUSB_ERROR_NONE; -} - -//--------------------------------------------------------------------+ -// CLASS-USBH API (don't require to verify parameters) -//--------------------------------------------------------------------+ -void msch_init(void) -{ - tu_memclr(msch_data, sizeof(msch_interface_t)*CFG_TUSB_HOST_DEVICE_MAX); - msch_sem_hdl = osal_semaphore_create(&msch_sem_def); -} - -bool msch_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const *itf_desc, uint16_t *p_length) -{ - TU_VERIFY (MSC_SUBCLASS_SCSI == itf_desc->bInterfaceSubClass && - MSC_PROTOCOL_BOT == itf_desc->bInterfaceProtocol); - - msch_interface_t* p_msc = &msch_data[dev_addr-1]; - - //------------- Open Data Pipe -------------// - tusb_desc_endpoint_t const * ep_desc = (tusb_desc_endpoint_t const *) tu_desc_next(itf_desc); - - for(uint32_t i=0; i<2; i++) - { - TU_ASSERT(TUSB_DESC_ENDPOINT == ep_desc->bDescriptorType); - TU_ASSERT(TUSB_XFER_BULK == ep_desc->bmAttributes.xfer); - - TU_ASSERT(hcd_edpt_open(rhport, dev_addr, ep_desc)); - - if ( tu_edpt_dir(ep_desc->bEndpointAddress) == TUSB_DIR_IN ) - { - p_msc->ep_in = ep_desc->bEndpointAddress; - }else - { - p_msc->ep_out = ep_desc->bEndpointAddress; - } - - ep_desc = (tusb_desc_endpoint_t const *) tu_desc_next(ep_desc); - } - - p_msc->itf_numr = itf_desc->bInterfaceNumber; - (*p_length) += sizeof(tusb_desc_interface_t) + 2*sizeof(tusb_desc_endpoint_t); - - //------------- Get Max Lun -------------// - tusb_control_request_t request = { - .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_INTERFACE, .type = TUSB_REQ_TYPE_CLASS, .direction = TUSB_DIR_IN }, - .bRequest = MSC_REQ_GET_MAX_LUN, - .wValue = 0, - .wIndex = p_msc->itf_numr, - .wLength = 1 - }; - // TODO STALL means zero - TU_ASSERT( usbh_control_xfer( dev_addr, &request, msch_buffer ) ); - p_msc->max_lun = msch_buffer[0]; - -#if 0 - //------------- Reset -------------// - request = (tusb_control_request_t) { - .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_INTERFACE, .type = TUSB_REQ_TYPE_CLASS, .direction = TUSB_DIR_OUT }, - .bRequest = MSC_REQ_RESET, - .wValue = 0, - .wIndex = p_msc->itf_numr, - .wLength = 0 - }; - TU_ASSERT( usbh_control_xfer( dev_addr, &request, NULL ) ); -#endif - - enum { SCSI_XFER_TIMEOUT = 2000 }; - //------------- SCSI Inquiry -------------// - tusbh_msc_inquiry(dev_addr, 0, msch_buffer); - TU_ASSERT( osal_semaphore_wait(msch_sem_hdl, SCSI_XFER_TIMEOUT) ); - - memcpy(p_msc->vendor_id , ((scsi_inquiry_resp_t*) msch_buffer)->vendor_id , 8); - memcpy(p_msc->product_id, ((scsi_inquiry_resp_t*) msch_buffer)->product_id, 16); - - //------------- SCSI Read Capacity 10 -------------// - tusbh_msc_read_capacity10(dev_addr, 0, msch_buffer); - TU_ASSERT( osal_semaphore_wait(msch_sem_hdl, SCSI_XFER_TIMEOUT)); - - // NOTE: my toshiba thumb-drive stall the first Read Capacity and require the sequence - // Read Capacity --> Stalled --> Clear Stall --> Request Sense --> Read Capacity (2) to work - if ( hcd_edpt_stalled(dev_addr, p_msc->ep_in) ) - { - // clear stall TODO abstract clear stall function - request = (tusb_control_request_t) { - .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_ENDPOINT, .type = TUSB_REQ_TYPE_STANDARD, .direction = TUSB_DIR_OUT }, - .bRequest = TUSB_REQ_CLEAR_FEATURE, - .wValue = 0, - .wIndex = p_msc->ep_in, - .wLength = 0 - }; - - TU_ASSERT(usbh_control_xfer( dev_addr, &request, NULL )); - - hcd_edpt_clear_stall(dev_addr, p_msc->ep_in); - TU_ASSERT( osal_semaphore_wait(msch_sem_hdl, SCSI_XFER_TIMEOUT) ); // wait for SCSI status - - //------------- SCSI Request Sense -------------// - (void) tuh_msc_request_sense(dev_addr, 0, msch_buffer); - TU_ASSERT(osal_semaphore_wait(msch_sem_hdl, SCSI_XFER_TIMEOUT)); - - //------------- Re-read SCSI Read Capactity -------------// - tusbh_msc_read_capacity10(dev_addr, 0, msch_buffer); - TU_ASSERT(osal_semaphore_wait(msch_sem_hdl, SCSI_XFER_TIMEOUT)); - } - - p_msc->last_lba = tu_ntohl( ((scsi_read_capacity10_resp_t*)msch_buffer)->last_lba ); - p_msc->block_size = (uint16_t) tu_ntohl( ((scsi_read_capacity10_resp_t*)msch_buffer)->block_size ); - - p_msc->is_initialized = true; - - tuh_msc_mounted_cb(dev_addr); - - return true; -} - -void msch_isr(uint8_t dev_addr, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes) -{ - msch_interface_t* p_msc = &msch_data[dev_addr-1]; - if ( ep_addr == p_msc->ep_in ) - { - if (p_msc->is_initialized) - { - tuh_msc_isr(dev_addr, event, xferred_bytes); - }else - { // still initializing under open subtask - osal_semaphore_post(msch_sem_hdl, true); - } - } -} - -void msch_close(uint8_t dev_addr) -{ - tu_memclr(&msch_data[dev_addr-1], sizeof(msch_interface_t)); - osal_semaphore_reset(msch_sem_hdl); - - tuh_msc_unmounted_cb(dev_addr); // invoke Application Callback -} - -//--------------------------------------------------------------------+ -// INTERNAL & HELPER -//--------------------------------------------------------------------+ - - -#endif +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#include "tusb_option.h" + +#if TUSB_OPT_HOST_ENABLED & CFG_TUH_MSC + +//--------------------------------------------------------------------+ +// INCLUDE +//--------------------------------------------------------------------+ +#include "common/tusb_common.h" +#include "msc_host.h" + +//--------------------------------------------------------------------+ +// MACRO CONSTANT TYPEDEF +//--------------------------------------------------------------------+ +CFG_TUSB_MEM_SECTION static msch_interface_t msch_data[CFG_TUSB_HOST_DEVICE_MAX]; + +//------------- Initalization Data -------------// +static osal_semaphore_def_t msch_sem_def; +static osal_semaphore_t msch_sem_hdl; + +// buffer used to read scsi information when mounted, largest response data currently is inquiry +CFG_TUSB_MEM_SECTION TU_ATTR_ALIGNED(4) static uint8_t msch_buffer[sizeof(scsi_inquiry_resp_t)]; + +//--------------------------------------------------------------------+ +// INTERNAL OBJECT & FUNCTION DECLARATION +//--------------------------------------------------------------------+ + +//--------------------------------------------------------------------+ +// PUBLIC API +//--------------------------------------------------------------------+ +bool tuh_msc_is_mounted(uint8_t dev_addr) +{ + return tuh_device_is_configured(dev_addr) && // is configured can be omitted + msch_data[dev_addr-1].is_initialized; +} + +bool tuh_msc_is_busy(uint8_t dev_addr) +{ + return msch_data[dev_addr-1].is_initialized && + hcd_edpt_busy(dev_addr, msch_data[dev_addr-1].ep_in); +} + +uint8_t const* tuh_msc_get_vendor_name(uint8_t dev_addr) +{ + return msch_data[dev_addr-1].is_initialized ? msch_data[dev_addr-1].vendor_id : NULL; +} + +uint8_t const* tuh_msc_get_product_name(uint8_t dev_addr) +{ + return msch_data[dev_addr-1].is_initialized ? msch_data[dev_addr-1].product_id : NULL; +} + +tusb_error_t tuh_msc_get_capacity(uint8_t dev_addr, uint32_t* p_last_lba, uint32_t* p_block_size) +{ + if ( !msch_data[dev_addr-1].is_initialized ) return TUSB_ERROR_MSCH_DEVICE_NOT_MOUNTED; + TU_ASSERT(p_last_lba != NULL && p_block_size != NULL, TUSB_ERROR_INVALID_PARA); + + (*p_last_lba) = msch_data[dev_addr-1].last_lba; + (*p_block_size) = (uint32_t) msch_data[dev_addr-1].block_size; + + return TUSB_ERROR_NONE; +} + +//--------------------------------------------------------------------+ +// PUBLIC API: SCSI COMMAND +//--------------------------------------------------------------------+ +static inline void msc_cbw_add_signature(msc_cbw_t *p_cbw, uint8_t lun) +{ + p_cbw->signature = MSC_CBW_SIGNATURE; + p_cbw->tag = 0xCAFECAFE; + p_cbw->lun = lun; +} + +static tusb_error_t msch_command_xfer(uint8_t dev_addr, msch_interface_t * p_msch, void* p_buffer) +{ + if ( NULL != p_buffer) + { // there is data phase + if (p_msch->cbw.dir & TUSB_DIR_IN_MASK) + { + TU_ASSERT( hcd_pipe_xfer(dev_addr, p_msch->ep_out, (uint8_t*) &p_msch->cbw, sizeof(msc_cbw_t), false), TUSB_ERROR_FAILED ); + TU_ASSERT( hcd_pipe_queue_xfer(dev_addr, p_msch->ep_in , p_buffer, p_msch->cbw.total_bytes), TUSB_ERROR_FAILED ); + }else + { + TU_ASSERT( hcd_pipe_queue_xfer(dev_addr, p_msch->ep_out, (uint8_t*) &p_msch->cbw, sizeof(msc_cbw_t)), TUSB_ERROR_FAILED ); + TU_ASSERT( hcd_pipe_xfer(dev_addr, p_msch->ep_out , p_buffer, p_msch->cbw.total_bytes, false), TUSB_ERROR_FAILED ); + } + } + + TU_ASSERT( hcd_pipe_xfer(dev_addr, p_msch->ep_in , (uint8_t*) &p_msch->csw, sizeof(msc_csw_t), true), TUSB_ERROR_FAILED); + + return TUSB_ERROR_NONE; +} + +tusb_error_t tusbh_msc_inquiry(uint8_t dev_addr, uint8_t lun, uint8_t *p_data) +{ + msch_interface_t* p_msch = &msch_data[dev_addr-1]; + + //------------- Command Block Wrapper -------------// + msc_cbw_add_signature(&p_msch->cbw, lun); + p_msch->cbw.total_bytes = sizeof(scsi_inquiry_resp_t); + p_msch->cbw.dir = TUSB_DIR_IN_MASK; + p_msch->cbw.cmd_len = sizeof(scsi_inquiry_t); + + //------------- SCSI command -------------// + scsi_inquiry_t cmd_inquiry = + { + .cmd_code = SCSI_CMD_INQUIRY, + .alloc_length = sizeof(scsi_inquiry_resp_t) + }; + + memcpy(p_msch->cbw.command, &cmd_inquiry, p_msch->cbw.cmd_len); + + TU_ASSERT_ERR ( msch_command_xfer(dev_addr, p_msch, p_data) ); + + return TUSB_ERROR_NONE; +} + +tusb_error_t tusbh_msc_read_capacity10(uint8_t dev_addr, uint8_t lun, uint8_t *p_data) +{ + msch_interface_t* p_msch = &msch_data[dev_addr-1]; + + //------------- Command Block Wrapper -------------// + msc_cbw_add_signature(&p_msch->cbw, lun); + p_msch->cbw.total_bytes = sizeof(scsi_read_capacity10_resp_t); + p_msch->cbw.dir = TUSB_DIR_IN_MASK; + p_msch->cbw.cmd_len = sizeof(scsi_read_capacity10_t); + + //------------- SCSI command -------------// + scsi_read_capacity10_t cmd_read_capacity10 = + { + .cmd_code = SCSI_CMD_READ_CAPACITY_10, + .lba = 0, + .partial_medium_indicator = 0 + }; + + memcpy(p_msch->cbw.command, &cmd_read_capacity10, p_msch->cbw.cmd_len); + + TU_ASSERT_ERR ( msch_command_xfer(dev_addr, p_msch, p_data) ); + + return TUSB_ERROR_NONE; +} + +tusb_error_t tuh_msc_request_sense(uint8_t dev_addr, uint8_t lun, uint8_t *p_data) +{ + (void) lun; // TODO [MSCH] multiple lun support + + msch_interface_t* p_msch = &msch_data[dev_addr-1]; + + //------------- Command Block Wrapper -------------// + p_msch->cbw.total_bytes = 18; + p_msch->cbw.dir = TUSB_DIR_IN_MASK; + p_msch->cbw.cmd_len = sizeof(scsi_request_sense_t); + + //------------- SCSI command -------------// + scsi_request_sense_t cmd_request_sense = + { + .cmd_code = SCSI_CMD_REQUEST_SENSE, + .alloc_length = 18 + }; + + memcpy(p_msch->cbw.command, &cmd_request_sense, p_msch->cbw.cmd_len); + + TU_ASSERT_ERR ( msch_command_xfer(dev_addr, p_msch, p_data) ); + + return TUSB_ERROR_NONE; +} + +tusb_error_t tuh_msc_test_unit_ready(uint8_t dev_addr, uint8_t lun, msc_csw_t * p_csw) +{ + msch_interface_t* p_msch = &msch_data[dev_addr-1]; + + //------------- Command Block Wrapper -------------// + msc_cbw_add_signature(&p_msch->cbw, lun); + + p_msch->cbw.total_bytes = 0; // Number of bytes + p_msch->cbw.dir = TUSB_DIR_OUT; + p_msch->cbw.cmd_len = sizeof(scsi_test_unit_ready_t); + + //------------- SCSI command -------------// + scsi_test_unit_ready_t cmd_test_unit_ready = + { + .cmd_code = SCSI_CMD_TEST_UNIT_READY, + .lun = lun // according to wiki + }; + + memcpy(p_msch->cbw.command, &cmd_test_unit_ready, p_msch->cbw.cmd_len); + + // TODO MSCH refractor test uinit ready + TU_ASSERT( hcd_pipe_xfer(dev_addr, p_msch->ep_out, (uint8_t*) &p_msch->cbw, sizeof(msc_cbw_t), false), TUSB_ERROR_FAILED ); + TU_ASSERT( hcd_pipe_xfer(dev_addr, p_msch->ep_in , (uint8_t*) p_csw, sizeof(msc_csw_t), true), TUSB_ERROR_FAILED ); + + return TUSB_ERROR_NONE; +} + +tusb_error_t tuh_msc_read10(uint8_t dev_addr, uint8_t lun, void * p_buffer, uint32_t lba, uint16_t block_count) +{ + msch_interface_t* p_msch = &msch_data[dev_addr-1]; + + //------------- Command Block Wrapper -------------// + msc_cbw_add_signature(&p_msch->cbw, lun); + + p_msch->cbw.total_bytes = p_msch->block_size*block_count; // Number of bytes + p_msch->cbw.dir = TUSB_DIR_IN_MASK; + p_msch->cbw.cmd_len = sizeof(scsi_read10_t); + + //------------- SCSI command -------------// + scsi_read10_t cmd_read10 = + { + .cmd_code = SCSI_CMD_READ_10, + .lba = tu_htonl(lba), + .block_count = tu_htons(block_count) + }; + + memcpy(p_msch->cbw.command, &cmd_read10, p_msch->cbw.cmd_len); + + TU_ASSERT_ERR ( msch_command_xfer(dev_addr, p_msch, p_buffer)); + + return TUSB_ERROR_NONE; +} + +tusb_error_t tuh_msc_write10(uint8_t dev_addr, uint8_t lun, void const * p_buffer, uint32_t lba, uint16_t block_count) +{ + msch_interface_t* p_msch = &msch_data[dev_addr-1]; + + //------------- Command Block Wrapper -------------// + msc_cbw_add_signature(&p_msch->cbw, lun); + + p_msch->cbw.total_bytes = p_msch->block_size*block_count; // Number of bytes + p_msch->cbw.dir = TUSB_DIR_OUT; + p_msch->cbw.cmd_len = sizeof(scsi_write10_t); + + //------------- SCSI command -------------// + scsi_write10_t cmd_write10 = + { + .cmd_code = SCSI_CMD_WRITE_10, + .lba = tu_htonl(lba), + .block_count = tu_htons(block_count) + }; + + memcpy(p_msch->cbw.command, &cmd_write10, p_msch->cbw.cmd_len); + + TU_ASSERT_ERR ( msch_command_xfer(dev_addr, p_msch, (void*) p_buffer)); + + return TUSB_ERROR_NONE; +} + +//--------------------------------------------------------------------+ +// CLASS-USBH API (don't require to verify parameters) +//--------------------------------------------------------------------+ +void msch_init(void) +{ + tu_memclr(msch_data, sizeof(msch_interface_t)*CFG_TUSB_HOST_DEVICE_MAX); + msch_sem_hdl = osal_semaphore_create(&msch_sem_def); +} + +bool msch_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const *itf_desc, uint16_t *p_length) +{ + TU_VERIFY (MSC_SUBCLASS_SCSI == itf_desc->bInterfaceSubClass && + MSC_PROTOCOL_BOT == itf_desc->bInterfaceProtocol); + + msch_interface_t* p_msc = &msch_data[dev_addr-1]; + + //------------- Open Data Pipe -------------// + tusb_desc_endpoint_t const * ep_desc = (tusb_desc_endpoint_t const *) tu_desc_next(itf_desc); + + for(uint32_t i=0; i<2; i++) + { + TU_ASSERT(TUSB_DESC_ENDPOINT == ep_desc->bDescriptorType); + TU_ASSERT(TUSB_XFER_BULK == ep_desc->bmAttributes.xfer); + + TU_ASSERT(hcd_edpt_open(rhport, dev_addr, ep_desc)); + + if ( tu_edpt_dir(ep_desc->bEndpointAddress) == TUSB_DIR_IN ) + { + p_msc->ep_in = ep_desc->bEndpointAddress; + }else + { + p_msc->ep_out = ep_desc->bEndpointAddress; + } + + ep_desc = (tusb_desc_endpoint_t const *) tu_desc_next(ep_desc); + } + + p_msc->itf_numr = itf_desc->bInterfaceNumber; + (*p_length) += sizeof(tusb_desc_interface_t) + 2*sizeof(tusb_desc_endpoint_t); + + //------------- Get Max Lun -------------// + tusb_control_request_t request = { + .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_INTERFACE, .type = TUSB_REQ_TYPE_CLASS, .direction = TUSB_DIR_IN }, + .bRequest = MSC_REQ_GET_MAX_LUN, + .wValue = 0, + .wIndex = p_msc->itf_numr, + .wLength = 1 + }; + // TODO STALL means zero + TU_ASSERT( usbh_control_xfer( dev_addr, &request, msch_buffer ) ); + p_msc->max_lun = msch_buffer[0]; + +#if 0 + //------------- Reset -------------// + request = (tusb_control_request_t) { + .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_INTERFACE, .type = TUSB_REQ_TYPE_CLASS, .direction = TUSB_DIR_OUT }, + .bRequest = MSC_REQ_RESET, + .wValue = 0, + .wIndex = p_msc->itf_numr, + .wLength = 0 + }; + TU_ASSERT( usbh_control_xfer( dev_addr, &request, NULL ) ); +#endif + + enum { SCSI_XFER_TIMEOUT = 2000 }; + //------------- SCSI Inquiry -------------// + tusbh_msc_inquiry(dev_addr, 0, msch_buffer); + TU_ASSERT( osal_semaphore_wait(msch_sem_hdl, SCSI_XFER_TIMEOUT) ); + + memcpy(p_msc->vendor_id , ((scsi_inquiry_resp_t*) msch_buffer)->vendor_id , 8); + memcpy(p_msc->product_id, ((scsi_inquiry_resp_t*) msch_buffer)->product_id, 16); + + //------------- SCSI Read Capacity 10 -------------// + tusbh_msc_read_capacity10(dev_addr, 0, msch_buffer); + TU_ASSERT( osal_semaphore_wait(msch_sem_hdl, SCSI_XFER_TIMEOUT)); + + // NOTE: my toshiba thumb-drive stall the first Read Capacity and require the sequence + // Read Capacity --> Stalled --> Clear Stall --> Request Sense --> Read Capacity (2) to work + if ( hcd_edpt_stalled(dev_addr, p_msc->ep_in) ) + { + // clear stall TODO abstract clear stall function + request = (tusb_control_request_t) { + .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_ENDPOINT, .type = TUSB_REQ_TYPE_STANDARD, .direction = TUSB_DIR_OUT }, + .bRequest = TUSB_REQ_CLEAR_FEATURE, + .wValue = 0, + .wIndex = p_msc->ep_in, + .wLength = 0 + }; + + TU_ASSERT(usbh_control_xfer( dev_addr, &request, NULL )); + + hcd_edpt_clear_stall(dev_addr, p_msc->ep_in); + TU_ASSERT( osal_semaphore_wait(msch_sem_hdl, SCSI_XFER_TIMEOUT) ); // wait for SCSI status + + //------------- SCSI Request Sense -------------// + (void) tuh_msc_request_sense(dev_addr, 0, msch_buffer); + TU_ASSERT(osal_semaphore_wait(msch_sem_hdl, SCSI_XFER_TIMEOUT)); + + //------------- Re-read SCSI Read Capactity -------------// + tusbh_msc_read_capacity10(dev_addr, 0, msch_buffer); + TU_ASSERT(osal_semaphore_wait(msch_sem_hdl, SCSI_XFER_TIMEOUT)); + } + + p_msc->last_lba = tu_ntohl( ((scsi_read_capacity10_resp_t*)msch_buffer)->last_lba ); + p_msc->block_size = (uint16_t) tu_ntohl( ((scsi_read_capacity10_resp_t*)msch_buffer)->block_size ); + + p_msc->is_initialized = true; + + tuh_msc_mounted_cb(dev_addr); + + return true; +} + +void msch_isr(uint8_t dev_addr, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes) +{ + msch_interface_t* p_msc = &msch_data[dev_addr-1]; + if ( ep_addr == p_msc->ep_in ) + { + if (p_msc->is_initialized) + { + tuh_msc_isr(dev_addr, event, xferred_bytes); + }else + { // still initializing under open subtask + osal_semaphore_post(msch_sem_hdl, true); + } + } +} + +void msch_close(uint8_t dev_addr) +{ + tu_memclr(&msch_data[dev_addr-1], sizeof(msch_interface_t)); + osal_semaphore_reset(msch_sem_hdl); + + tuh_msc_unmounted_cb(dev_addr); // invoke Application Callback +} + +//--------------------------------------------------------------------+ +// INTERNAL & HELPER +//--------------------------------------------------------------------+ + + +#endif diff --git a/src/class/msc/msc_host.h b/src/class/msc/msc_host.h index da817fbe..76cf8685 100644 --- a/src/class/msc/msc_host.h +++ b/src/class/msc/msc_host.h @@ -1,206 +1,206 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2019 Ha Thach (tinyusb.org) - * - * 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. - * - * This file is part of the TinyUSB stack. - */ - -#ifndef _TUSB_MSC_HOST_H_ -#define _TUSB_MSC_HOST_H_ - -#include "common/tusb_common.h" -#include "host/usbh.h" -#include "msc.h" - -#ifdef __cplusplus - extern "C" { -#endif - -/** \addtogroup ClassDriver_MSC - * @{ - * \defgroup MSC_Host Host - * The interface API includes status checking function, data transferring function and callback functions - * @{ */ -//--------------------------------------------------------------------+ -// MASS STORAGE Application API -//--------------------------------------------------------------------+ -/** \brief Check if device supports MassStorage interface or not - * \param[in] dev_addr device address - * \retval true if device supports - * \retval false if device does not support or is not mounted - */ -bool tuh_msc_is_mounted(uint8_t dev_addr); - -/** \brief Check if the interface is currently busy or not - * \param[in] dev_addr device address - * \retval true if the interface is busy meaning the stack is still transferring/waiting data from/to device - * \retval false if the interface is not busy meaning the stack successfully transferred data from/to device - * \note This function is used to check if previous transfer is complete (success or error), so that the next transfer - * can be scheduled. User needs to make sure the corresponding interface is mounted (by \ref tuh_msc_is_mounted) - * before calling this function - */ -bool tuh_msc_is_busy(uint8_t dev_addr); - -/** \brief Get SCSI vendor's name of MassStorage device - * \param[in] dev_addr device address - * \return pointer to vendor's name or NULL if specified device does not support MassStorage - * \note SCSI vendor's name is 8-byte length field in \ref scsi_inquiry_data_t. During enumeration, the stack has already - * retrieved (via SCSI INQUIRY) and store this information internally. There is no need for application to re-send SCSI INQUIRY - * command or allocate buffer for this. - */ -uint8_t const* tuh_msc_get_vendor_name(uint8_t dev_addr); - -/** \brief Get SCSI product's name of MassStorage device - * \param[in] dev_addr device address - * \return pointer to product's name or NULL if specified device does not support MassStorage - * \note SCSI product's name is 16-byte length field in \ref scsi_inquiry_data_t. During enumeration, the stack has already - * retrieved (via SCSI INQUIRY) and store this information internally. There is no need for application to re-send SCSI INQUIRY - * command or allocate buffer for this. - */ -uint8_t const* tuh_msc_get_product_name(uint8_t dev_addr); - -/** \brief Get SCSI Capacity of MassStorage device - * \param[in] dev_addr device address - * \param[out] p_last_lba Last Logical Block Address of device - * \param[out] p_block_size Block Size of device in bytes - * \retval pointer to product's name or NULL if specified device does not support MassStorage - * \note MassStorage's capacity can be computed by last LBA x block size (in bytes). During enumeration, the stack has already - * retrieved (via SCSI READ CAPACITY 10) and store this information internally. There is no need for application - * to re-send SCSI READ CAPACITY 10 command - */ -tusb_error_t tuh_msc_get_capacity(uint8_t dev_addr, uint32_t* p_last_lba, uint32_t* p_block_size); - -/** \brief Perform SCSI READ 10 command to read data from MassStorage device - * \param[in] dev_addr device address - * \param[in] lun Targeted Logical Unit - * \param[out] p_buffer Buffer used to store data read from device. Must be accessible by USB controller (see \ref CFG_TUSB_MEM_SECTION) - * \param[in] lba Starting Logical Block Address to be read - * \param[in] block_count Number of Block to be read - * \retval TUSB_ERROR_NONE on success - * \retval TUSB_ERROR_INTERFACE_IS_BUSY if the interface is already transferring data with device - * \retval TUSB_ERROR_DEVICE_NOT_READY if device is not yet configured (by SET CONFIGURED request) - * \retval TUSB_ERROR_INVALID_PARA if input parameters are not correct - * \note This function is non-blocking and returns immediately. The result of USB transfer will be reported by the interface's callback function - */ -tusb_error_t tuh_msc_read10 (uint8_t dev_addr, uint8_t lun, void * p_buffer, uint32_t lba, uint16_t block_count); - -/** \brief Perform SCSI WRITE 10 command to write data to MassStorage device - * \param[in] dev_addr device address - * \param[in] lun Targeted Logical Unit - * \param[in] p_buffer Buffer containing data. Must be accessible by USB controller (see \ref CFG_TUSB_MEM_SECTION) - * \param[in] lba Starting Logical Block Address to be written - * \param[in] block_count Number of Block to be written - * \retval TUSB_ERROR_NONE on success - * \retval TUSB_ERROR_INTERFACE_IS_BUSY if the interface is already transferring data with device - * \retval TUSB_ERROR_DEVICE_NOT_READY if device is not yet configured (by SET CONFIGURED request) - * \retval TUSB_ERROR_INVALID_PARA if input parameters are not correct - * \note This function is non-blocking and returns immediately. The result of USB transfer will be reported by the interface's callback function - */ -tusb_error_t tuh_msc_write10(uint8_t dev_addr, uint8_t lun, void const * p_buffer, uint32_t lba, uint16_t block_count); - -/** \brief Perform SCSI REQUEST SENSE command, used to retrieve sense data from MassStorage device - * \param[in] dev_addr device address - * \param[in] lun Targeted Logical Unit - * \param[in] p_data Buffer to store response's data from device. Must be accessible by USB controller (see \ref CFG_TUSB_MEM_SECTION) - * \retval TUSB_ERROR_NONE on success - * \retval TUSB_ERROR_INTERFACE_IS_BUSY if the interface is already transferring data with device - * \retval TUSB_ERROR_DEVICE_NOT_READY if device is not yet configured (by SET CONFIGURED request) - * \retval TUSB_ERROR_INVALID_PARA if input parameters are not correct - * \note This function is non-blocking and returns immediately. The result of USB transfer will be reported by the interface's callback function - */ -tusb_error_t tuh_msc_request_sense(uint8_t dev_addr, uint8_t lun, uint8_t *p_data); - -/** \brief Perform SCSI TEST UNIT READY command to test if MassStorage device is ready - * \param[in] dev_addr device address - * \param[in] lun Targeted Logical Unit - * \retval TUSB_ERROR_NONE on success - * \retval TUSB_ERROR_INTERFACE_IS_BUSY if the interface is already transferring data with device - * \retval TUSB_ERROR_DEVICE_NOT_READY if device is not yet configured (by SET CONFIGURED request) - * \retval TUSB_ERROR_INVALID_PARA if input parameters are not correct - * \note This function is non-blocking and returns immediately. The result of USB transfer will be reported by the interface's callback function - */ -tusb_error_t tuh_msc_test_unit_ready(uint8_t dev_addr, uint8_t lun, msc_csw_t * p_csw); // TODO to be refractor - -//tusb_error_t tusbh_msc_scsi_send(uint8_t dev_addr, uint8_t lun, bool is_direction_in, -// uint8_t const * p_command, uint8_t cmd_len, -// uint8_t * p_response, uint32_t resp_len); - -//------------- Application Callback -------------// -/** \brief Callback function that will be invoked when a device with MassStorage interface is mounted - * \param[in] dev_addr Address of newly mounted device - * \note This callback should be used by Application to set-up interface-related data - */ -void tuh_msc_mounted_cb(uint8_t dev_addr); - -/** \brief Callback function that will be invoked when a device with MassStorage interface is unmounted - * \param[in] dev_addr Address of newly unmounted device - * \note This callback should be used by Application to tear-down interface-related data - */ -void tuh_msc_unmounted_cb(uint8_t dev_addr); - -/** \brief Callback function that is invoked when an transferring event occurred - * \param[in] dev_addr Address of device - * \param[in] event an value from \ref xfer_result_t - * \param[in] xferred_bytes Number of bytes transferred via USB bus - * \note event can be one of following - * - XFER_RESULT_SUCCESS : previously scheduled transfer completes successfully. - * - XFER_RESULT_FAILED : previously scheduled transfer encountered a transaction error. - * - XFER_RESULT_STALLED : previously scheduled transfer is stalled by device. - * \note - */ -void tuh_msc_isr(uint8_t dev_addr, xfer_result_t event, uint32_t xferred_bytes); - - -//--------------------------------------------------------------------+ -// Internal Class Driver API -//--------------------------------------------------------------------+ -typedef struct -{ - uint8_t itf_numr; - uint8_t ep_in; - uint8_t ep_out; - - uint8_t max_lun; - uint16_t block_size; - uint32_t last_lba; // last logical block address - - volatile bool is_initialized; - uint8_t vendor_id[8]; - uint8_t product_id[16]; - - msc_cbw_t cbw; - msc_csw_t csw; -}msch_interface_t; - -void msch_init(void); -bool msch_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const *itf_desc, uint16_t *p_length); -void msch_isr(uint8_t dev_addr, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes); -void msch_close(uint8_t dev_addr); - -#ifdef __cplusplus - } -#endif - -#endif /* _TUSB_MSC_HOST_H_ */ - -/// @} -/// @} +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#ifndef _TUSB_MSC_HOST_H_ +#define _TUSB_MSC_HOST_H_ + +#include "common/tusb_common.h" +#include "host/usbh.h" +#include "msc.h" + +#ifdef __cplusplus + extern "C" { +#endif + +/** \addtogroup ClassDriver_MSC + * @{ + * \defgroup MSC_Host Host + * The interface API includes status checking function, data transferring function and callback functions + * @{ */ +//--------------------------------------------------------------------+ +// MASS STORAGE Application API +//--------------------------------------------------------------------+ +/** \brief Check if device supports MassStorage interface or not + * \param[in] dev_addr device address + * \retval true if device supports + * \retval false if device does not support or is not mounted + */ +bool tuh_msc_is_mounted(uint8_t dev_addr); + +/** \brief Check if the interface is currently busy or not + * \param[in] dev_addr device address + * \retval true if the interface is busy meaning the stack is still transferring/waiting data from/to device + * \retval false if the interface is not busy meaning the stack successfully transferred data from/to device + * \note This function is used to check if previous transfer is complete (success or error), so that the next transfer + * can be scheduled. User needs to make sure the corresponding interface is mounted (by \ref tuh_msc_is_mounted) + * before calling this function + */ +bool tuh_msc_is_busy(uint8_t dev_addr); + +/** \brief Get SCSI vendor's name of MassStorage device + * \param[in] dev_addr device address + * \return pointer to vendor's name or NULL if specified device does not support MassStorage + * \note SCSI vendor's name is 8-byte length field in \ref scsi_inquiry_data_t. During enumeration, the stack has already + * retrieved (via SCSI INQUIRY) and store this information internally. There is no need for application to re-send SCSI INQUIRY + * command or allocate buffer for this. + */ +uint8_t const* tuh_msc_get_vendor_name(uint8_t dev_addr); + +/** \brief Get SCSI product's name of MassStorage device + * \param[in] dev_addr device address + * \return pointer to product's name or NULL if specified device does not support MassStorage + * \note SCSI product's name is 16-byte length field in \ref scsi_inquiry_data_t. During enumeration, the stack has already + * retrieved (via SCSI INQUIRY) and store this information internally. There is no need for application to re-send SCSI INQUIRY + * command or allocate buffer for this. + */ +uint8_t const* tuh_msc_get_product_name(uint8_t dev_addr); + +/** \brief Get SCSI Capacity of MassStorage device + * \param[in] dev_addr device address + * \param[out] p_last_lba Last Logical Block Address of device + * \param[out] p_block_size Block Size of device in bytes + * \retval pointer to product's name or NULL if specified device does not support MassStorage + * \note MassStorage's capacity can be computed by last LBA x block size (in bytes). During enumeration, the stack has already + * retrieved (via SCSI READ CAPACITY 10) and store this information internally. There is no need for application + * to re-send SCSI READ CAPACITY 10 command + */ +tusb_error_t tuh_msc_get_capacity(uint8_t dev_addr, uint32_t* p_last_lba, uint32_t* p_block_size); + +/** \brief Perform SCSI READ 10 command to read data from MassStorage device + * \param[in] dev_addr device address + * \param[in] lun Targeted Logical Unit + * \param[out] p_buffer Buffer used to store data read from device. Must be accessible by USB controller (see \ref CFG_TUSB_MEM_SECTION) + * \param[in] lba Starting Logical Block Address to be read + * \param[in] block_count Number of Block to be read + * \retval TUSB_ERROR_NONE on success + * \retval TUSB_ERROR_INTERFACE_IS_BUSY if the interface is already transferring data with device + * \retval TUSB_ERROR_DEVICE_NOT_READY if device is not yet configured (by SET CONFIGURED request) + * \retval TUSB_ERROR_INVALID_PARA if input parameters are not correct + * \note This function is non-blocking and returns immediately. The result of USB transfer will be reported by the interface's callback function + */ +tusb_error_t tuh_msc_read10 (uint8_t dev_addr, uint8_t lun, void * p_buffer, uint32_t lba, uint16_t block_count); + +/** \brief Perform SCSI WRITE 10 command to write data to MassStorage device + * \param[in] dev_addr device address + * \param[in] lun Targeted Logical Unit + * \param[in] p_buffer Buffer containing data. Must be accessible by USB controller (see \ref CFG_TUSB_MEM_SECTION) + * \param[in] lba Starting Logical Block Address to be written + * \param[in] block_count Number of Block to be written + * \retval TUSB_ERROR_NONE on success + * \retval TUSB_ERROR_INTERFACE_IS_BUSY if the interface is already transferring data with device + * \retval TUSB_ERROR_DEVICE_NOT_READY if device is not yet configured (by SET CONFIGURED request) + * \retval TUSB_ERROR_INVALID_PARA if input parameters are not correct + * \note This function is non-blocking and returns immediately. The result of USB transfer will be reported by the interface's callback function + */ +tusb_error_t tuh_msc_write10(uint8_t dev_addr, uint8_t lun, void const * p_buffer, uint32_t lba, uint16_t block_count); + +/** \brief Perform SCSI REQUEST SENSE command, used to retrieve sense data from MassStorage device + * \param[in] dev_addr device address + * \param[in] lun Targeted Logical Unit + * \param[in] p_data Buffer to store response's data from device. Must be accessible by USB controller (see \ref CFG_TUSB_MEM_SECTION) + * \retval TUSB_ERROR_NONE on success + * \retval TUSB_ERROR_INTERFACE_IS_BUSY if the interface is already transferring data with device + * \retval TUSB_ERROR_DEVICE_NOT_READY if device is not yet configured (by SET CONFIGURED request) + * \retval TUSB_ERROR_INVALID_PARA if input parameters are not correct + * \note This function is non-blocking and returns immediately. The result of USB transfer will be reported by the interface's callback function + */ +tusb_error_t tuh_msc_request_sense(uint8_t dev_addr, uint8_t lun, uint8_t *p_data); + +/** \brief Perform SCSI TEST UNIT READY command to test if MassStorage device is ready + * \param[in] dev_addr device address + * \param[in] lun Targeted Logical Unit + * \retval TUSB_ERROR_NONE on success + * \retval TUSB_ERROR_INTERFACE_IS_BUSY if the interface is already transferring data with device + * \retval TUSB_ERROR_DEVICE_NOT_READY if device is not yet configured (by SET CONFIGURED request) + * \retval TUSB_ERROR_INVALID_PARA if input parameters are not correct + * \note This function is non-blocking and returns immediately. The result of USB transfer will be reported by the interface's callback function + */ +tusb_error_t tuh_msc_test_unit_ready(uint8_t dev_addr, uint8_t lun, msc_csw_t * p_csw); // TODO to be refractor + +//tusb_error_t tusbh_msc_scsi_send(uint8_t dev_addr, uint8_t lun, bool is_direction_in, +// uint8_t const * p_command, uint8_t cmd_len, +// uint8_t * p_response, uint32_t resp_len); + +//------------- Application Callback -------------// +/** \brief Callback function that will be invoked when a device with MassStorage interface is mounted + * \param[in] dev_addr Address of newly mounted device + * \note This callback should be used by Application to set-up interface-related data + */ +void tuh_msc_mounted_cb(uint8_t dev_addr); + +/** \brief Callback function that will be invoked when a device with MassStorage interface is unmounted + * \param[in] dev_addr Address of newly unmounted device + * \note This callback should be used by Application to tear-down interface-related data + */ +void tuh_msc_unmounted_cb(uint8_t dev_addr); + +/** \brief Callback function that is invoked when an transferring event occurred + * \param[in] dev_addr Address of device + * \param[in] event an value from \ref xfer_result_t + * \param[in] xferred_bytes Number of bytes transferred via USB bus + * \note event can be one of following + * - XFER_RESULT_SUCCESS : previously scheduled transfer completes successfully. + * - XFER_RESULT_FAILED : previously scheduled transfer encountered a transaction error. + * - XFER_RESULT_STALLED : previously scheduled transfer is stalled by device. + * \note + */ +void tuh_msc_isr(uint8_t dev_addr, xfer_result_t event, uint32_t xferred_bytes); + + +//--------------------------------------------------------------------+ +// Internal Class Driver API +//--------------------------------------------------------------------+ +typedef struct +{ + uint8_t itf_numr; + uint8_t ep_in; + uint8_t ep_out; + + uint8_t max_lun; + uint16_t block_size; + uint32_t last_lba; // last logical block address + + volatile bool is_initialized; + uint8_t vendor_id[8]; + uint8_t product_id[16]; + + msc_cbw_t cbw; + msc_csw_t csw; +}msch_interface_t; + +void msch_init(void); +bool msch_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const *itf_desc, uint16_t *p_length); +void msch_isr(uint8_t dev_addr, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes); +void msch_close(uint8_t dev_addr); + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_MSC_HOST_H_ */ + +/// @} +/// @} diff --git a/src/common/tusb_common.h b/src/common/tusb_common.h index 839989c9..5e6a8bb1 100644 --- a/src/common/tusb_common.h +++ b/src/common/tusb_common.h @@ -1,275 +1,275 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2019 Ha Thach (tinyusb.org) - * - * 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. - * - * This file is part of the TinyUSB stack. - */ - -/** \ingroup Group_Common - * \defgroup Group_CommonH common.h - * @{ */ - -#ifndef _TUSB_COMMON_H_ -#define _TUSB_COMMON_H_ - -#ifdef __cplusplus - extern "C" { -#endif - -//--------------------------------------------------------------------+ -// Macros Helper -//--------------------------------------------------------------------+ -#define TU_ARRAY_SIZE(_arr) ( sizeof(_arr) / sizeof(_arr[0]) ) -#define TU_MIN(_x, _y) ( ( (_x) < (_y) ) ? (_x) : (_y) ) -#define TU_MAX(_x, _y) ( ( (_x) > (_y) ) ? (_x) : (_y) ) - -#define TU_U16_HIGH(u16) ((uint8_t) (((u16) >> 8) & 0x00ff)) -#define TU_U16_LOW(u16) ((uint8_t) ((u16) & 0x00ff)) -#define U16_TO_U8S_BE(u16) TU_U16_HIGH(u16), TU_U16_LOW(u16) -#define U16_TO_U8S_LE(u16) TU_U16_LOW(u16), TU_U16_HIGH(u16) - -#define U32_B1_U8(u32) ((uint8_t) (((u32) >> 24) & 0x000000ff)) // MSB -#define U32_B2_U8(u32) ((uint8_t) (((u32) >> 16) & 0x000000ff)) -#define U32_B3_U8(u32) ((uint8_t) (((u32) >> 8) & 0x000000ff)) -#define U32_B4_U8(u32) ((uint8_t) ((u32) & 0x000000ff)) // LSB - -#define U32_TO_U8S_BE(u32) U32_B1_U8(u32), U32_B2_U8(u32), U32_B3_U8(u32), U32_B4_U8(u32) -#define U32_TO_U8S_LE(u32) U32_B4_U8(u32), U32_B3_U8(u32), U32_B2_U8(u32), U32_B1_U8(u32) - -#define TU_BIT(n) (1U << (n)) - -//--------------------------------------------------------------------+ -// Includes -//--------------------------------------------------------------------+ - -// Standard Headers -#include -#include -#include -#include -#include - -// Tinyusb Common Headers -#include "tusb_option.h" -#include "tusb_compiler.h" -#include "tusb_verify.h" -#include "tusb_error.h" // TODO remove -#include "tusb_timeout.h" -#include "tusb_types.h" - -//--------------------------------------------------------------------+ -// Inline Functions -//--------------------------------------------------------------------+ -#define tu_memclr(buffer, size) memset((buffer), 0, (size)) -#define tu_varclr(_var) tu_memclr(_var, sizeof(*(_var))) - -static inline uint32_t tu_u32(uint8_t b1, uint8_t b2, uint8_t b3, uint8_t b4) -{ - return ( ((uint32_t) b1) << 24) + ( ((uint32_t) b2) << 16) + ( ((uint32_t) b3) << 8) + b4; -} - -static inline uint16_t tu_u16(uint8_t high, uint8_t low) -{ - return (uint16_t)((((uint16_t) high) << 8) + low); -} - -static inline uint8_t tu_u16_high(uint16_t u16) { return (uint8_t) (((uint16_t) (u16 >> 8)) & 0x00ff); } -static inline uint8_t tu_u16_low (uint16_t u16) { return (uint8_t) (u16 & 0x00ff); } - -// Min -static inline uint8_t tu_min8 (uint8_t x, uint8_t y ) { return (x < y) ? x : y; } -static inline uint16_t tu_min16 (uint16_t x, uint16_t y) { return (x < y) ? x : y; } -static inline uint32_t tu_min32 (uint32_t x, uint32_t y) { return (x < y) ? x : y; } - -// Max -static inline uint8_t tu_max8 (uint8_t x, uint8_t y ) { return (x > y) ? x : y; } -static inline uint16_t tu_max16 (uint16_t x, uint16_t y) { return (x > y) ? x : y; } -static inline uint32_t tu_max32 (uint32_t x, uint32_t y) { return (x > y) ? x : y; } - -// Align -static inline uint32_t tu_align_n(uint32_t value, uint32_t alignment) -{ - return value & ((uint32_t) ~(alignment-1)); -} - -static inline uint32_t tu_align32 (uint32_t value) { return (value & 0xFFFFFFE0UL); } -static inline uint32_t tu_align16 (uint32_t value) { return (value & 0xFFFFFFF0UL); } -static inline uint32_t tu_align4k (uint32_t value) { return (value & 0xFFFFF000UL); } -static inline uint32_t tu_offset4k(uint32_t value) { return (value & 0xFFFUL); } - -//------------- Mathematics -------------// -static inline uint32_t tu_abs(int32_t value) { return (uint32_t)((value < 0) ? (-value) : value); } - -/// inclusive range checking -static inline bool tu_within(uint32_t lower, uint32_t value, uint32_t upper) -{ - return (lower <= value) && (value <= upper); -} - -// log2 of a value is its MSB's position -// TODO use clz TODO remove -static inline uint8_t tu_log2(uint32_t value) -{ - uint8_t result = 0; - - while (value >>= 1) - { - result++; - } - return result; -} - -// Bit -static inline uint32_t tu_bit_set (uint32_t value, uint8_t pos) { return value | TU_BIT(pos); } -static inline uint32_t tu_bit_clear(uint32_t value, uint8_t pos) { return value & (~TU_BIT(pos)); } -static inline bool tu_bit_test (uint32_t value, uint8_t pos) { return (value & TU_BIT(pos)) ? true : false; } - -/*------------------------------------------------------------------*/ -/* Count number of arguments of __VA_ARGS__ - * - reference https://groups.google.com/forum/#!topic/comp.std.c/d-6Mj5Lko_s - * - _GET_NTH_ARG() takes args >= N (64) but only expand to Nth one (64th) - * - _RSEQ_N() is reverse sequential to N to add padding to have - * Nth position is the same as the number of arguments - * - ##__VA_ARGS__ is used to deal with 0 paramerter (swallows comma) - *------------------------------------------------------------------*/ -#ifndef TU_ARGS_NUM - -#define TU_ARGS_NUM(...) NARG_(_0, ##__VA_ARGS__,_RSEQ_N()) - -#define NARG_(...) _GET_NTH_ARG(__VA_ARGS__) -#define _GET_NTH_ARG( \ - _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,_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,_52,_53,_54,_55,_56,_57,_58,_59,_60, \ - _61,_62,_63,N,...) N -#define _RSEQ_N() \ - 62,61,60, \ - 59,58,57,56,55,54,53,52,51,50, \ - 49,48,47,46,45,44,43,42,41,40, \ - 39,38,37,36,35,34,33,32,31,30, \ - 29,28,27,26,25,24,23,22,21,20, \ - 19,18,17,16,15,14,13,12,11,10, \ - 9,8,7,6,5,4,3,2,1,0 -#endif - -// To be removed -//------------- Binary constant -------------// -#if defined(__GNUC__) && !defined(__CC_ARM) - -#define TU_BIN8(x) ((uint8_t) (0b##x)) -#define TU_BIN16(b1, b2) ((uint16_t) (0b##b1##b2)) -#define TU_BIN32(b1, b2, b3, b4) ((uint32_t) (0b##b1##b2##b3##b4)) - -#else - -// internal macro of B8, B16, B32 -#define _B8__(x) (((x&0x0000000FUL)?1:0) \ - +((x&0x000000F0UL)?2:0) \ - +((x&0x00000F00UL)?4:0) \ - +((x&0x0000F000UL)?8:0) \ - +((x&0x000F0000UL)?16:0) \ - +((x&0x00F00000UL)?32:0) \ - +((x&0x0F000000UL)?64:0) \ - +((x&0xF0000000UL)?128:0)) - -#define TU_BIN8(d) ((uint8_t) _B8__(0x##d##UL)) -#define TU_BIN16(dmsb,dlsb) (((uint16_t)TU_BIN8(dmsb)<<8) + TU_BIN8(dlsb)) -#define TU_BIN32(dmsb,db2,db3,dlsb) \ - (((uint32_t)TU_BIN8(dmsb)<<24) \ - + ((uint32_t)TU_BIN8(db2)<<16) \ - + ((uint32_t)TU_BIN8(db3)<<8) \ - + TU_BIN8(dlsb)) -#endif - -//--------------------------------------------------------------------+ -// Debug Function -//--------------------------------------------------------------------+ - -// CFG_TUSB_DEBUG for debugging -// 0 : no debug -// 1 : print when there is error -// 2 : print out log -#if CFG_TUSB_DEBUG - -void tu_print_mem(void const *buf, uint16_t count, uint8_t indent); - -#ifndef tu_printf - #define tu_printf printf -#endif - -// Log with debug level 1 -#define TU_LOG1 tu_printf -#define TU_LOG1_MEM tu_print_mem -#define TU_LOG1_LOCATION() tu_printf("%s: %d:\n", __PRETTY_FUNCTION__, __LINE__) - -// Log with debug level 2 -#if CFG_TUSB_DEBUG > 1 - #define TU_LOG2 TU_LOG1 - #define TU_LOG2_MEM TU_LOG1_MEM - #define TU_LOG2_LOCATION() TU_LOG1_LOCATION() -#endif - - -typedef struct -{ - uint32_t key; - char const * data; -}lookup_entry_t; - -typedef struct -{ - uint16_t count; - lookup_entry_t const* items; -} lookup_table_t; - -static inline char const* lookup_find(lookup_table_t const* p_table, uint32_t key) -{ - for(uint16_t i=0; icount; i++) - { - if (p_table->items[i].key == key) return p_table->items[i].data; - } - - return NULL; -} - -#endif // CFG_TUSB_DEBUG - -#ifndef TU_LOG1 - #define TU_LOG1(...) - #define TU_LOG1_MEM(...) -#endif - -#ifndef TU_LOG2 - #define TU_LOG2(...) - #define TU_LOG2_MEM(...) -#endif - -#ifdef __cplusplus - } -#endif - -#endif /* _TUSB_COMMON_H_ */ - -/** @} */ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +/** \ingroup Group_Common + * \defgroup Group_CommonH common.h + * @{ */ + +#ifndef _TUSB_COMMON_H_ +#define _TUSB_COMMON_H_ + +#ifdef __cplusplus + extern "C" { +#endif + +//--------------------------------------------------------------------+ +// Macros Helper +//--------------------------------------------------------------------+ +#define TU_ARRAY_SIZE(_arr) ( sizeof(_arr) / sizeof(_arr[0]) ) +#define TU_MIN(_x, _y) ( ( (_x) < (_y) ) ? (_x) : (_y) ) +#define TU_MAX(_x, _y) ( ( (_x) > (_y) ) ? (_x) : (_y) ) + +#define TU_U16_HIGH(u16) ((uint8_t) (((u16) >> 8) & 0x00ff)) +#define TU_U16_LOW(u16) ((uint8_t) ((u16) & 0x00ff)) +#define U16_TO_U8S_BE(u16) TU_U16_HIGH(u16), TU_U16_LOW(u16) +#define U16_TO_U8S_LE(u16) TU_U16_LOW(u16), TU_U16_HIGH(u16) + +#define U32_B1_U8(u32) ((uint8_t) (((u32) >> 24) & 0x000000ff)) // MSB +#define U32_B2_U8(u32) ((uint8_t) (((u32) >> 16) & 0x000000ff)) +#define U32_B3_U8(u32) ((uint8_t) (((u32) >> 8) & 0x000000ff)) +#define U32_B4_U8(u32) ((uint8_t) ((u32) & 0x000000ff)) // LSB + +#define U32_TO_U8S_BE(u32) U32_B1_U8(u32), U32_B2_U8(u32), U32_B3_U8(u32), U32_B4_U8(u32) +#define U32_TO_U8S_LE(u32) U32_B4_U8(u32), U32_B3_U8(u32), U32_B2_U8(u32), U32_B1_U8(u32) + +#define TU_BIT(n) (1U << (n)) + +//--------------------------------------------------------------------+ +// Includes +//--------------------------------------------------------------------+ + +// Standard Headers +#include +#include +#include +#include +#include + +// Tinyusb Common Headers +#include "tusb_option.h" +#include "tusb_compiler.h" +#include "tusb_verify.h" +#include "tusb_error.h" // TODO remove +#include "tusb_timeout.h" +#include "tusb_types.h" + +//--------------------------------------------------------------------+ +// Inline Functions +//--------------------------------------------------------------------+ +#define tu_memclr(buffer, size) memset((buffer), 0, (size)) +#define tu_varclr(_var) tu_memclr(_var, sizeof(*(_var))) + +static inline uint32_t tu_u32(uint8_t b1, uint8_t b2, uint8_t b3, uint8_t b4) +{ + return ( ((uint32_t) b1) << 24) + ( ((uint32_t) b2) << 16) + ( ((uint32_t) b3) << 8) + b4; +} + +static inline uint16_t tu_u16(uint8_t high, uint8_t low) +{ + return (uint16_t)((((uint16_t) high) << 8) + low); +} + +static inline uint8_t tu_u16_high(uint16_t u16) { return (uint8_t) (((uint16_t) (u16 >> 8)) & 0x00ff); } +static inline uint8_t tu_u16_low (uint16_t u16) { return (uint8_t) (u16 & 0x00ff); } + +// Min +static inline uint8_t tu_min8 (uint8_t x, uint8_t y ) { return (x < y) ? x : y; } +static inline uint16_t tu_min16 (uint16_t x, uint16_t y) { return (x < y) ? x : y; } +static inline uint32_t tu_min32 (uint32_t x, uint32_t y) { return (x < y) ? x : y; } + +// Max +static inline uint8_t tu_max8 (uint8_t x, uint8_t y ) { return (x > y) ? x : y; } +static inline uint16_t tu_max16 (uint16_t x, uint16_t y) { return (x > y) ? x : y; } +static inline uint32_t tu_max32 (uint32_t x, uint32_t y) { return (x > y) ? x : y; } + +// Align +static inline uint32_t tu_align_n(uint32_t value, uint32_t alignment) +{ + return value & ((uint32_t) ~(alignment-1)); +} + +static inline uint32_t tu_align32 (uint32_t value) { return (value & 0xFFFFFFE0UL); } +static inline uint32_t tu_align16 (uint32_t value) { return (value & 0xFFFFFFF0UL); } +static inline uint32_t tu_align4k (uint32_t value) { return (value & 0xFFFFF000UL); } +static inline uint32_t tu_offset4k(uint32_t value) { return (value & 0xFFFUL); } + +//------------- Mathematics -------------// +static inline uint32_t tu_abs(int32_t value) { return (uint32_t)((value < 0) ? (-value) : value); } + +/// inclusive range checking +static inline bool tu_within(uint32_t lower, uint32_t value, uint32_t upper) +{ + return (lower <= value) && (value <= upper); +} + +// log2 of a value is its MSB's position +// TODO use clz TODO remove +static inline uint8_t tu_log2(uint32_t value) +{ + uint8_t result = 0; + + while (value >>= 1) + { + result++; + } + return result; +} + +// Bit +static inline uint32_t tu_bit_set (uint32_t value, uint8_t pos) { return value | TU_BIT(pos); } +static inline uint32_t tu_bit_clear(uint32_t value, uint8_t pos) { return value & (~TU_BIT(pos)); } +static inline bool tu_bit_test (uint32_t value, uint8_t pos) { return (value & TU_BIT(pos)) ? true : false; } + +/*------------------------------------------------------------------*/ +/* Count number of arguments of __VA_ARGS__ + * - reference https://groups.google.com/forum/#!topic/comp.std.c/d-6Mj5Lko_s + * - _GET_NTH_ARG() takes args >= N (64) but only expand to Nth one (64th) + * - _RSEQ_N() is reverse sequential to N to add padding to have + * Nth position is the same as the number of arguments + * - ##__VA_ARGS__ is used to deal with 0 paramerter (swallows comma) + *------------------------------------------------------------------*/ +#ifndef TU_ARGS_NUM + +#define TU_ARGS_NUM(...) NARG_(_0, ##__VA_ARGS__,_RSEQ_N()) + +#define NARG_(...) _GET_NTH_ARG(__VA_ARGS__) +#define _GET_NTH_ARG( \ + _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,_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,_52,_53,_54,_55,_56,_57,_58,_59,_60, \ + _61,_62,_63,N,...) N +#define _RSEQ_N() \ + 62,61,60, \ + 59,58,57,56,55,54,53,52,51,50, \ + 49,48,47,46,45,44,43,42,41,40, \ + 39,38,37,36,35,34,33,32,31,30, \ + 29,28,27,26,25,24,23,22,21,20, \ + 19,18,17,16,15,14,13,12,11,10, \ + 9,8,7,6,5,4,3,2,1,0 +#endif + +// To be removed +//------------- Binary constant -------------// +#if defined(__GNUC__) && !defined(__CC_ARM) + +#define TU_BIN8(x) ((uint8_t) (0b##x)) +#define TU_BIN16(b1, b2) ((uint16_t) (0b##b1##b2)) +#define TU_BIN32(b1, b2, b3, b4) ((uint32_t) (0b##b1##b2##b3##b4)) + +#else + +// internal macro of B8, B16, B32 +#define _B8__(x) (((x&0x0000000FUL)?1:0) \ + +((x&0x000000F0UL)?2:0) \ + +((x&0x00000F00UL)?4:0) \ + +((x&0x0000F000UL)?8:0) \ + +((x&0x000F0000UL)?16:0) \ + +((x&0x00F00000UL)?32:0) \ + +((x&0x0F000000UL)?64:0) \ + +((x&0xF0000000UL)?128:0)) + +#define TU_BIN8(d) ((uint8_t) _B8__(0x##d##UL)) +#define TU_BIN16(dmsb,dlsb) (((uint16_t)TU_BIN8(dmsb)<<8) + TU_BIN8(dlsb)) +#define TU_BIN32(dmsb,db2,db3,dlsb) \ + (((uint32_t)TU_BIN8(dmsb)<<24) \ + + ((uint32_t)TU_BIN8(db2)<<16) \ + + ((uint32_t)TU_BIN8(db3)<<8) \ + + TU_BIN8(dlsb)) +#endif + +//--------------------------------------------------------------------+ +// Debug Function +//--------------------------------------------------------------------+ + +// CFG_TUSB_DEBUG for debugging +// 0 : no debug +// 1 : print when there is error +// 2 : print out log +#if CFG_TUSB_DEBUG + +void tu_print_mem(void const *buf, uint16_t count, uint8_t indent); + +#ifndef tu_printf + #define tu_printf printf +#endif + +// Log with debug level 1 +#define TU_LOG1 tu_printf +#define TU_LOG1_MEM tu_print_mem +#define TU_LOG1_LOCATION() tu_printf("%s: %d:\n", __PRETTY_FUNCTION__, __LINE__) + +// Log with debug level 2 +#if CFG_TUSB_DEBUG > 1 + #define TU_LOG2 TU_LOG1 + #define TU_LOG2_MEM TU_LOG1_MEM + #define TU_LOG2_LOCATION() TU_LOG1_LOCATION() +#endif + + +typedef struct +{ + uint32_t key; + char const * data; +}lookup_entry_t; + +typedef struct +{ + uint16_t count; + lookup_entry_t const* items; +} lookup_table_t; + +static inline char const* lookup_find(lookup_table_t const* p_table, uint32_t key) +{ + for(uint16_t i=0; icount; i++) + { + if (p_table->items[i].key == key) return p_table->items[i].data; + } + + return NULL; +} + +#endif // CFG_TUSB_DEBUG + +#ifndef TU_LOG1 + #define TU_LOG1(...) + #define TU_LOG1_MEM(...) +#endif + +#ifndef TU_LOG2 + #define TU_LOG2(...) + #define TU_LOG2_MEM(...) +#endif + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_COMMON_H_ */ + +/** @} */ diff --git a/src/common/tusb_compiler.h b/src/common/tusb_compiler.h index 0bac3eae..e403c749 100644 --- a/src/common/tusb_compiler.h +++ b/src/common/tusb_compiler.h @@ -1,140 +1,140 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2019 Ha Thach (tinyusb.org) - * - * 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. - * - * This file is part of the TinyUSB stack. - */ - -/** \ingroup Group_Common - * \defgroup Group_Compiler Compiler - * \brief Group_Compiler brief - * @{ */ - -#ifndef _TUSB_COMPILER_H_ -#define _TUSB_COMPILER_H_ - -#define TU_STRING(x) #x ///< stringify without expand -#define TU_XSTRING(x) TU_STRING(x) ///< expand then stringify -#define TU_STRCAT(a, b) a##b ///< concat without expand -#define TU_XSTRCAT(a, b) TU_STRCAT(a, b) ///< expand then concat - -#if defined __COUNTER__ && __COUNTER__ != __COUNTER__ - #define _TU_COUNTER_ __COUNTER__ -#else - #define _TU_COUNTER_ __LINE__ -#endif - -// Compile-time Assert -#if __STDC_VERSION__ >= 201112L - #define TU_VERIFY_STATIC _Static_assert -#else - #define TU_VERIFY_STATIC(const_expr, _mess) enum { TU_XSTRCAT(_verify_static_, _TU_COUNTER_) = 1/(!!(const_expr)) } -#endif - -// for declaration of reserved field, make use of _TU_COUNTER_ -#define TU_RESERVED TU_XSTRCAT(reserved, _TU_COUNTER_) - -#define TU_LITTLE_ENDIAN (0x12u) -#define TU_BIG_ENDIAN (0x21u) - -//--------------------------------------------------------------------+ -// Compiler porting with Attribute and Endian -//--------------------------------------------------------------------+ -#if defined(__GNUC__) - #define TU_ATTR_ALIGNED(Bytes) __attribute__ ((aligned(Bytes))) - #define TU_ATTR_SECTION(sec_name) __attribute__ ((section(#sec_name))) - #define TU_ATTR_PACKED __attribute__ ((packed)) - #define TU_ATTR_PREPACKED - #define TU_ATTR_WEAK __attribute__ ((weak)) - #define TU_ATTR_DEPRECATED(mess) __attribute__ ((deprecated(mess))) // warn if function with this attribute is used - #define TU_ATTR_UNUSED __attribute__ ((unused)) // Function/Variable is meant to be possibly unused - #define TU_ATTR_USED __attribute__ ((used)) // Function/Variable is meant to be used - - // Endian conversion use well-known host to network (big endian) naming - #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ - #define TU_BYTE_ORDER TU_LITTLE_ENDIAN - #else - #define TU_BYTE_ORDER TU_BIG_ENDIAN - #endif - - #define TU_BSWAP16(u16) (__builtin_bswap16(u16)) - #define TU_BSWAP32(u32) (__builtin_bswap32(u32)) - -#elif defined(__TI_COMPILER_VERSION__) - #define TU_ATTR_ALIGNED(Bytes) __attribute__ ((aligned(Bytes))) - #define TU_ATTR_SECTION(sec_name) __attribute__ ((section(#sec_name))) - #define TU_ATTR_PACKED __attribute__ ((packed)) - #define TU_ATTR_PREPACKED - #define TU_ATTR_WEAK __attribute__ ((weak)) - #define TU_ATTR_DEPRECATED(mess) __attribute__ ((deprecated(mess))) // warn if function with this attribute is used - #define TU_ATTR_UNUSED __attribute__ ((unused)) // Function/Variable is meant to be possibly unused - #define TU_ATTR_USED __attribute__ ((used)) - - // __BYTE_ORDER is defined in the TI ARM compiler, but not MSP430 (which is little endian) - #if ((__BYTE_ORDER__) == (__ORDER_LITTLE_ENDIAN__)) || defined(__MSP430__) - #define TU_BYTE_ORDER TU_LITTLE_ENDIAN - #else - #define TU_BYTE_ORDER TU_BIG_ENDIAN - #endif - - #define TU_BSWAP16(u16) (__builtin_bswap16(u16)) - #define TU_BSWAP32(u32) (__builtin_bswap32(u32)) - -#else - #error "Compiler attribute porting is required" -#endif - -#if (TU_BYTE_ORDER == TU_LITTLE_ENDIAN) - - #define tu_htons(u16) (TU_BSWAP16(u16)) - #define tu_ntohs(u16) (TU_BSWAP16(u16)) - - #define tu_htonl(u32) (TU_BSWAP32(u32)) - #define tu_ntohl(u32) (TU_BSWAP32(u32)) - - #define tu_htole16(u16) (u16) - #define tu_le16toh(u16) (u16) - - #define tu_htole32(u32) (u32) - #define tu_le32toh(u32) (u32) - -#elif (TU_BYTE_ORDER == TU_BIG_ENDIAN) - - #define tu_htons(u16) (u16) - #define tu_ntohs(u16) (u16) - - #define tu_htonl(u32) (u32) - #define tu_ntohl(u32) (u32) - - #define tu_htole16(u16) (tu_bswap16(u16)) - #define tu_le16toh(u16) (tu_bswap16(u16)) - - #define tu_htole32(u32) (tu_bswap32(u32)) - #define tu_le32toh(u32) (tu_bswap32(u32)) - -#else - #error Byte order is undefined -#endif - -#endif /* _TUSB_COMPILER_H_ */ - -/// @} +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +/** \ingroup Group_Common + * \defgroup Group_Compiler Compiler + * \brief Group_Compiler brief + * @{ */ + +#ifndef _TUSB_COMPILER_H_ +#define _TUSB_COMPILER_H_ + +#define TU_STRING(x) #x ///< stringify without expand +#define TU_XSTRING(x) TU_STRING(x) ///< expand then stringify +#define TU_STRCAT(a, b) a##b ///< concat without expand +#define TU_XSTRCAT(a, b) TU_STRCAT(a, b) ///< expand then concat + +#if defined __COUNTER__ && __COUNTER__ != __COUNTER__ + #define _TU_COUNTER_ __COUNTER__ +#else + #define _TU_COUNTER_ __LINE__ +#endif + +// Compile-time Assert +#if __STDC_VERSION__ >= 201112L + #define TU_VERIFY_STATIC _Static_assert +#else + #define TU_VERIFY_STATIC(const_expr, _mess) enum { TU_XSTRCAT(_verify_static_, _TU_COUNTER_) = 1/(!!(const_expr)) } +#endif + +// for declaration of reserved field, make use of _TU_COUNTER_ +#define TU_RESERVED TU_XSTRCAT(reserved, _TU_COUNTER_) + +#define TU_LITTLE_ENDIAN (0x12u) +#define TU_BIG_ENDIAN (0x21u) + +//--------------------------------------------------------------------+ +// Compiler porting with Attribute and Endian +//--------------------------------------------------------------------+ +#if defined(__GNUC__) + #define TU_ATTR_ALIGNED(Bytes) __attribute__ ((aligned(Bytes))) + #define TU_ATTR_SECTION(sec_name) __attribute__ ((section(#sec_name))) + #define TU_ATTR_PACKED __attribute__ ((packed)) + #define TU_ATTR_PREPACKED + #define TU_ATTR_WEAK __attribute__ ((weak)) + #define TU_ATTR_DEPRECATED(mess) __attribute__ ((deprecated(mess))) // warn if function with this attribute is used + #define TU_ATTR_UNUSED __attribute__ ((unused)) // Function/Variable is meant to be possibly unused + #define TU_ATTR_USED __attribute__ ((used)) // Function/Variable is meant to be used + + // Endian conversion use well-known host to network (big endian) naming + #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ + #define TU_BYTE_ORDER TU_LITTLE_ENDIAN + #else + #define TU_BYTE_ORDER TU_BIG_ENDIAN + #endif + + #define TU_BSWAP16(u16) (__builtin_bswap16(u16)) + #define TU_BSWAP32(u32) (__builtin_bswap32(u32)) + +#elif defined(__TI_COMPILER_VERSION__) + #define TU_ATTR_ALIGNED(Bytes) __attribute__ ((aligned(Bytes))) + #define TU_ATTR_SECTION(sec_name) __attribute__ ((section(#sec_name))) + #define TU_ATTR_PACKED __attribute__ ((packed)) + #define TU_ATTR_PREPACKED + #define TU_ATTR_WEAK __attribute__ ((weak)) + #define TU_ATTR_DEPRECATED(mess) __attribute__ ((deprecated(mess))) // warn if function with this attribute is used + #define TU_ATTR_UNUSED __attribute__ ((unused)) // Function/Variable is meant to be possibly unused + #define TU_ATTR_USED __attribute__ ((used)) + + // __BYTE_ORDER is defined in the TI ARM compiler, but not MSP430 (which is little endian) + #if ((__BYTE_ORDER__) == (__ORDER_LITTLE_ENDIAN__)) || defined(__MSP430__) + #define TU_BYTE_ORDER TU_LITTLE_ENDIAN + #else + #define TU_BYTE_ORDER TU_BIG_ENDIAN + #endif + + #define TU_BSWAP16(u16) (__builtin_bswap16(u16)) + #define TU_BSWAP32(u32) (__builtin_bswap32(u32)) + +#else + #error "Compiler attribute porting is required" +#endif + +#if (TU_BYTE_ORDER == TU_LITTLE_ENDIAN) + + #define tu_htons(u16) (TU_BSWAP16(u16)) + #define tu_ntohs(u16) (TU_BSWAP16(u16)) + + #define tu_htonl(u32) (TU_BSWAP32(u32)) + #define tu_ntohl(u32) (TU_BSWAP32(u32)) + + #define tu_htole16(u16) (u16) + #define tu_le16toh(u16) (u16) + + #define tu_htole32(u32) (u32) + #define tu_le32toh(u32) (u32) + +#elif (TU_BYTE_ORDER == TU_BIG_ENDIAN) + + #define tu_htons(u16) (u16) + #define tu_ntohs(u16) (u16) + + #define tu_htonl(u32) (u32) + #define tu_ntohl(u32) (u32) + + #define tu_htole16(u16) (tu_bswap16(u16)) + #define tu_le16toh(u16) (tu_bswap16(u16)) + + #define tu_htole32(u32) (tu_bswap32(u32)) + #define tu_le32toh(u32) (tu_bswap32(u32)) + +#else + #error Byte order is undefined +#endif + +#endif /* _TUSB_COMPILER_H_ */ + +/// @} diff --git a/src/common/tusb_error.h b/src/common/tusb_error.h index e6313f7a..f600c4ae 100644 --- a/src/common/tusb_error.h +++ b/src/common/tusb_error.h @@ -1,74 +1,74 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2019 Ha Thach (tinyusb.org) - * - * 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. - * - * This file is part of the TinyUSB stack. - */ - -/** \ingroup Group_Common - * \defgroup Group_Error Error Codes - * @{ */ - -#ifndef _TUSB_ERRORS_H_ -#define _TUSB_ERRORS_H_ - -#include "tusb_option.h" - -#ifdef __cplusplus - extern "C" { -#endif - -#define ERROR_ENUM(x) x, -#define ERROR_STRING(x) #x, - -#define ERROR_TABLE(ENTRY) \ - ENTRY(TUSB_ERROR_NONE )\ - ENTRY(TUSB_ERROR_INVALID_PARA )\ - ENTRY(TUSB_ERROR_DEVICE_NOT_READY )\ - ENTRY(TUSB_ERROR_INTERFACE_IS_BUSY )\ - ENTRY(TUSB_ERROR_HCD_OPEN_PIPE_FAILED )\ - ENTRY(TUSB_ERROR_OSAL_TIMEOUT )\ - ENTRY(TUSB_ERROR_CDCH_DEVICE_NOT_MOUNTED )\ - ENTRY(TUSB_ERROR_MSCH_DEVICE_NOT_MOUNTED )\ - ENTRY(TUSB_ERROR_NOT_SUPPORTED )\ - ENTRY(TUSB_ERROR_NOT_ENOUGH_MEMORY )\ - ENTRY(TUSB_ERROR_FAILED )\ - -/// \brief Error Code returned -typedef enum -{ - ERROR_TABLE(ERROR_ENUM) - TUSB_ERROR_COUNT -}tusb_error_t; - -#if CFG_TUSB_DEBUG -/// Enum to String for debugging purposes. Only available if \ref CFG_TUSB_DEBUG > 0 -extern char const* const tusb_strerr[TUSB_ERROR_COUNT]; -#endif - -#ifdef __cplusplus - } -#endif - -#endif /* _TUSB_ERRORS_H_ */ - -/** @} */ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +/** \ingroup Group_Common + * \defgroup Group_Error Error Codes + * @{ */ + +#ifndef _TUSB_ERRORS_H_ +#define _TUSB_ERRORS_H_ + +#include "tusb_option.h" + +#ifdef __cplusplus + extern "C" { +#endif + +#define ERROR_ENUM(x) x, +#define ERROR_STRING(x) #x, + +#define ERROR_TABLE(ENTRY) \ + ENTRY(TUSB_ERROR_NONE )\ + ENTRY(TUSB_ERROR_INVALID_PARA )\ + ENTRY(TUSB_ERROR_DEVICE_NOT_READY )\ + ENTRY(TUSB_ERROR_INTERFACE_IS_BUSY )\ + ENTRY(TUSB_ERROR_HCD_OPEN_PIPE_FAILED )\ + ENTRY(TUSB_ERROR_OSAL_TIMEOUT )\ + ENTRY(TUSB_ERROR_CDCH_DEVICE_NOT_MOUNTED )\ + ENTRY(TUSB_ERROR_MSCH_DEVICE_NOT_MOUNTED )\ + ENTRY(TUSB_ERROR_NOT_SUPPORTED )\ + ENTRY(TUSB_ERROR_NOT_ENOUGH_MEMORY )\ + ENTRY(TUSB_ERROR_FAILED )\ + +/// \brief Error Code returned +typedef enum +{ + ERROR_TABLE(ERROR_ENUM) + TUSB_ERROR_COUNT +}tusb_error_t; + +#if CFG_TUSB_DEBUG +/// Enum to String for debugging purposes. Only available if \ref CFG_TUSB_DEBUG > 0 +extern char const* const tusb_strerr[TUSB_ERROR_COUNT]; +#endif + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_ERRORS_H_ */ + +/** @} */ diff --git a/src/common/tusb_fifo.c b/src/common/tusb_fifo.c index 455b1ad3..01e99031 100644 --- a/src/common/tusb_fifo.c +++ b/src/common/tusb_fifo.c @@ -1,288 +1,288 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2019 Ha Thach (tinyusb.org) - * - * 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. - * - * This file is part of the TinyUSB stack. - */ - -#include - -#include "osal/osal.h" -#include "tusb_fifo.h" - -// implement mutex lock and unlock -#if CFG_FIFO_MUTEX - -static void tu_fifo_lock(tu_fifo_t *f) -{ - if (f->mutex) - { - osal_mutex_lock(f->mutex, OSAL_TIMEOUT_WAIT_FOREVER); - } -} - -static void tu_fifo_unlock(tu_fifo_t *f) -{ - if (f->mutex) - { - osal_mutex_unlock(f->mutex); - } -} - -#else - -#define tu_fifo_lock(_ff) -#define tu_fifo_unlock(_ff) - -#endif - -bool tu_fifo_config(tu_fifo_t *f, void* buffer, uint16_t depth, uint16_t item_size, bool overwritable) -{ - tu_fifo_lock(f); - - f->buffer = (uint8_t*) buffer; - f->depth = depth; - f->item_size = item_size; - f->overwritable = overwritable; - - f->rd_idx = f->wr_idx = f->count = 0; - - tu_fifo_unlock(f); - - return true; -} - -// retrieve data from fifo -static void _tu_ff_pull(tu_fifo_t* f, void * buffer) -{ - memcpy(buffer, - f->buffer + (f->rd_idx * f->item_size), - f->item_size); - - f->rd_idx = (f->rd_idx + 1) % f->depth; - f->count--; -} - -// send data to fifo -static void _tu_ff_push(tu_fifo_t* f, void const * data) -{ - memcpy( f->buffer + (f->wr_idx * f->item_size), - data, - f->item_size); - - f->wr_idx = (f->wr_idx + 1) % f->depth; - - if (tu_fifo_full(f)) - { - f->rd_idx = f->wr_idx; // keep the full state (rd == wr && len = size) - } - else - { - f->count++; - } -} - -/******************************************************************************/ -/*! - @brief Read one byte out of the RX buffer. - - This function will return the byte located at the array index of the - read pointer, and then increment the read pointer index. If the read - pointer exceeds the maximum buffer size, it will roll over to zero. - - @param[in] f - Pointer to the FIFO buffer to manipulate - @param[in] buffer - Pointer to the place holder for data read from the buffer - - @returns TRUE if the queue is not empty -*/ -/******************************************************************************/ -bool tu_fifo_read(tu_fifo_t* f, void * buffer) -{ - if( tu_fifo_empty(f) ) return false; - - tu_fifo_lock(f); - - _tu_ff_pull(f, buffer); - - tu_fifo_unlock(f); - - return true; -} - -/******************************************************************************/ -/*! - @brief This function will read n elements into the array index specified by - the write pointer and increment the write index. If the write index - exceeds the max buffer size, then it will roll over to zero. - - @param[in] f - Pointer to the FIFO buffer to manipulate - @param[in] buffer - The pointer to data location - @param[in] count - Number of element that buffer can afford - - @returns number of items read from the FIFO -*/ -/******************************************************************************/ -uint16_t tu_fifo_read_n (tu_fifo_t* f, void * buffer, uint16_t count) -{ - if( tu_fifo_empty(f) ) return 0; - - tu_fifo_lock(f); - - /* Limit up to fifo's count */ - if ( count > f->count ) count = f->count; - - uint8_t* buf8 = (uint8_t*) buffer; - uint16_t len = 0; - - while (len < count) - { - _tu_ff_pull(f, buf8); - - len++; - buf8 += f->item_size; - } - - tu_fifo_unlock(f); - - return len; -} - -/******************************************************************************/ -/*! - @brief Reads one item without removing it from the FIFO - - @param[in] f - Pointer to the FIFO buffer to manipulate - @param[in] pos - Position to read from in the FIFO buffer - @param[in] p_buffer - Pointer to the place holder for data read from the buffer - - @returns TRUE if the queue is not empty -*/ -/******************************************************************************/ -bool tu_fifo_peek_at(tu_fifo_t* f, uint16_t pos, void * p_buffer) -{ - if ( pos >= f->count ) return false; - - // rd_idx is pos=0 - uint16_t index = (f->rd_idx + pos) % f->depth; - memcpy(p_buffer, - f->buffer + (index * f->item_size), - f->item_size); - - return true; -} - -/******************************************************************************/ -/*! - @brief Write one element into the RX buffer. - - This function will write one element into the array index specified by - the write pointer and increment the write index. If the write index - exceeds the max buffer size, then it will roll over to zero. - - @param[in] f - Pointer to the FIFO buffer to manipulate - @param[in] data - The byte to add to the FIFO - - @returns TRUE if the data was written to the FIFO (overwrittable - FIFO will always return TRUE) -*/ -/******************************************************************************/ -bool tu_fifo_write (tu_fifo_t* f, const void * data) -{ - if ( tu_fifo_full(f) && !f->overwritable ) return false; - - tu_fifo_lock(f); - - _tu_ff_push(f, data); - - tu_fifo_unlock(f); - - return true; -} - -/******************************************************************************/ -/*! - @brief This function will write n elements into the array index specified by - the write pointer and increment the write index. If the write index - exceeds the max buffer size, then it will roll over to zero. - - @param[in] f - Pointer to the FIFO buffer to manipulate - @param[in] data - The pointer to data to add to the FIFO - @param[in] count - Number of element - @return Number of written elements -*/ -/******************************************************************************/ -uint16_t tu_fifo_write_n (tu_fifo_t* f, const void * data, uint16_t count) -{ - if ( count == 0 ) return 0; - - tu_fifo_lock(f); - - // Not overwritable limit up to full - if (!f->overwritable) count = tu_min16(count, tu_fifo_remaining(f)); - - uint8_t const* buf8 = (uint8_t const*) data; - uint16_t len = 0; - - while (len < count) - { - _tu_ff_push(f, buf8); - - len++; - buf8 += f->item_size; - } - - tu_fifo_unlock(f); - - return len; -} - -/******************************************************************************/ -/*! - @brief Clear the fifo read and write pointers and set length to zero - - @param[in] f - Pointer to the FIFO buffer to manipulate -*/ -/******************************************************************************/ -bool tu_fifo_clear(tu_fifo_t *f) -{ - tu_fifo_lock(f); - - f->rd_idx = f->wr_idx = f->count = 0; - - tu_fifo_unlock(f); - - return true; -} +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#include + +#include "osal/osal.h" +#include "tusb_fifo.h" + +// implement mutex lock and unlock +#if CFG_FIFO_MUTEX + +static void tu_fifo_lock(tu_fifo_t *f) +{ + if (f->mutex) + { + osal_mutex_lock(f->mutex, OSAL_TIMEOUT_WAIT_FOREVER); + } +} + +static void tu_fifo_unlock(tu_fifo_t *f) +{ + if (f->mutex) + { + osal_mutex_unlock(f->mutex); + } +} + +#else + +#define tu_fifo_lock(_ff) +#define tu_fifo_unlock(_ff) + +#endif + +bool tu_fifo_config(tu_fifo_t *f, void* buffer, uint16_t depth, uint16_t item_size, bool overwritable) +{ + tu_fifo_lock(f); + + f->buffer = (uint8_t*) buffer; + f->depth = depth; + f->item_size = item_size; + f->overwritable = overwritable; + + f->rd_idx = f->wr_idx = f->count = 0; + + tu_fifo_unlock(f); + + return true; +} + +// retrieve data from fifo +static void _tu_ff_pull(tu_fifo_t* f, void * buffer) +{ + memcpy(buffer, + f->buffer + (f->rd_idx * f->item_size), + f->item_size); + + f->rd_idx = (f->rd_idx + 1) % f->depth; + f->count--; +} + +// send data to fifo +static void _tu_ff_push(tu_fifo_t* f, void const * data) +{ + memcpy( f->buffer + (f->wr_idx * f->item_size), + data, + f->item_size); + + f->wr_idx = (f->wr_idx + 1) % f->depth; + + if (tu_fifo_full(f)) + { + f->rd_idx = f->wr_idx; // keep the full state (rd == wr && len = size) + } + else + { + f->count++; + } +} + +/******************************************************************************/ +/*! + @brief Read one byte out of the RX buffer. + + This function will return the byte located at the array index of the + read pointer, and then increment the read pointer index. If the read + pointer exceeds the maximum buffer size, it will roll over to zero. + + @param[in] f + Pointer to the FIFO buffer to manipulate + @param[in] buffer + Pointer to the place holder for data read from the buffer + + @returns TRUE if the queue is not empty +*/ +/******************************************************************************/ +bool tu_fifo_read(tu_fifo_t* f, void * buffer) +{ + if( tu_fifo_empty(f) ) return false; + + tu_fifo_lock(f); + + _tu_ff_pull(f, buffer); + + tu_fifo_unlock(f); + + return true; +} + +/******************************************************************************/ +/*! + @brief This function will read n elements into the array index specified by + the write pointer and increment the write index. If the write index + exceeds the max buffer size, then it will roll over to zero. + + @param[in] f + Pointer to the FIFO buffer to manipulate + @param[in] buffer + The pointer to data location + @param[in] count + Number of element that buffer can afford + + @returns number of items read from the FIFO +*/ +/******************************************************************************/ +uint16_t tu_fifo_read_n (tu_fifo_t* f, void * buffer, uint16_t count) +{ + if( tu_fifo_empty(f) ) return 0; + + tu_fifo_lock(f); + + /* Limit up to fifo's count */ + if ( count > f->count ) count = f->count; + + uint8_t* buf8 = (uint8_t*) buffer; + uint16_t len = 0; + + while (len < count) + { + _tu_ff_pull(f, buf8); + + len++; + buf8 += f->item_size; + } + + tu_fifo_unlock(f); + + return len; +} + +/******************************************************************************/ +/*! + @brief Reads one item without removing it from the FIFO + + @param[in] f + Pointer to the FIFO buffer to manipulate + @param[in] pos + Position to read from in the FIFO buffer + @param[in] p_buffer + Pointer to the place holder for data read from the buffer + + @returns TRUE if the queue is not empty +*/ +/******************************************************************************/ +bool tu_fifo_peek_at(tu_fifo_t* f, uint16_t pos, void * p_buffer) +{ + if ( pos >= f->count ) return false; + + // rd_idx is pos=0 + uint16_t index = (f->rd_idx + pos) % f->depth; + memcpy(p_buffer, + f->buffer + (index * f->item_size), + f->item_size); + + return true; +} + +/******************************************************************************/ +/*! + @brief Write one element into the RX buffer. + + This function will write one element into the array index specified by + the write pointer and increment the write index. If the write index + exceeds the max buffer size, then it will roll over to zero. + + @param[in] f + Pointer to the FIFO buffer to manipulate + @param[in] data + The byte to add to the FIFO + + @returns TRUE if the data was written to the FIFO (overwrittable + FIFO will always return TRUE) +*/ +/******************************************************************************/ +bool tu_fifo_write (tu_fifo_t* f, const void * data) +{ + if ( tu_fifo_full(f) && !f->overwritable ) return false; + + tu_fifo_lock(f); + + _tu_ff_push(f, data); + + tu_fifo_unlock(f); + + return true; +} + +/******************************************************************************/ +/*! + @brief This function will write n elements into the array index specified by + the write pointer and increment the write index. If the write index + exceeds the max buffer size, then it will roll over to zero. + + @param[in] f + Pointer to the FIFO buffer to manipulate + @param[in] data + The pointer to data to add to the FIFO + @param[in] count + Number of element + @return Number of written elements +*/ +/******************************************************************************/ +uint16_t tu_fifo_write_n (tu_fifo_t* f, const void * data, uint16_t count) +{ + if ( count == 0 ) return 0; + + tu_fifo_lock(f); + + // Not overwritable limit up to full + if (!f->overwritable) count = tu_min16(count, tu_fifo_remaining(f)); + + uint8_t const* buf8 = (uint8_t const*) data; + uint16_t len = 0; + + while (len < count) + { + _tu_ff_push(f, buf8); + + len++; + buf8 += f->item_size; + } + + tu_fifo_unlock(f); + + return len; +} + +/******************************************************************************/ +/*! + @brief Clear the fifo read and write pointers and set length to zero + + @param[in] f + Pointer to the FIFO buffer to manipulate +*/ +/******************************************************************************/ +bool tu_fifo_clear(tu_fifo_t *f) +{ + tu_fifo_lock(f); + + f->rd_idx = f->wr_idx = f->count = 0; + + tu_fifo_unlock(f); + + return true; +} diff --git a/src/common/tusb_fifo.h b/src/common/tusb_fifo.h index 1b64f1db..fb0c896f 100644 --- a/src/common/tusb_fifo.h +++ b/src/common/tusb_fifo.h @@ -1,131 +1,131 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2019 Ha Thach (tinyusb.org) - * - * 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. - * - * This file is part of the TinyUSB stack. - */ - -/** \ingroup Group_Common - * \defgroup group_fifo fifo - * @{ */ - -#ifndef _TUSB_FIFO_H_ -#define _TUSB_FIFO_H_ - -// mutex is only needed for RTOS -// for OS None, we don't get preempted -#define CFG_FIFO_MUTEX (CFG_TUSB_OS != OPT_OS_NONE) - -#include -#include - -#ifdef __cplusplus - extern "C" { -#endif - -#if CFG_FIFO_MUTEX -#define tu_fifo_mutex_t osal_mutex_t -#endif - - -/** \struct tu_fifo_t - * \brief Simple Circular FIFO - */ -typedef struct -{ - uint8_t* buffer ; ///< buffer pointer - uint16_t depth ; ///< max items - uint16_t item_size ; ///< size of each item - bool overwritable ; - - volatile uint16_t count ; ///< number of items in queue - volatile uint16_t wr_idx ; ///< write pointer - volatile uint16_t rd_idx ; ///< read pointer - -#if CFG_FIFO_MUTEX - tu_fifo_mutex_t mutex; -#endif - -} tu_fifo_t; - -#define TU_FIFO_DEF(_name, _depth, _type, _overwritable) \ - uint8_t _name##_buf[_depth*sizeof(_type)]; \ - tu_fifo_t _name = { \ - .buffer = _name##_buf, \ - .depth = _depth, \ - .item_size = sizeof(_type), \ - .overwritable = _overwritable, \ - } - -bool tu_fifo_clear(tu_fifo_t *f); -bool tu_fifo_config(tu_fifo_t *f, void* buffer, uint16_t depth, uint16_t item_size, bool overwritable); - -#if CFG_FIFO_MUTEX -static inline void tu_fifo_config_mutex(tu_fifo_t *f, tu_fifo_mutex_t mutex_hdl) -{ - f->mutex = mutex_hdl; -} -#endif - -bool tu_fifo_write (tu_fifo_t* f, void const * p_data); -uint16_t tu_fifo_write_n (tu_fifo_t* f, void const * p_data, uint16_t count); - -bool tu_fifo_read (tu_fifo_t* f, void * p_buffer); -uint16_t tu_fifo_read_n (tu_fifo_t* f, void * p_buffer, uint16_t count); - -bool tu_fifo_peek_at (tu_fifo_t* f, uint16_t pos, void * p_buffer); - -static inline bool tu_fifo_peek(tu_fifo_t* f, void * p_buffer) -{ - return tu_fifo_peek_at(f, 0, p_buffer); -} - -static inline bool tu_fifo_empty(tu_fifo_t* f) -{ - return (f->count == 0); -} - -static inline bool tu_fifo_full(tu_fifo_t* f) -{ - return (f->count == f->depth); -} - -static inline uint16_t tu_fifo_count(tu_fifo_t* f) -{ - return f->count; -} - -static inline uint16_t tu_fifo_remaining(tu_fifo_t* f) -{ - return f->depth - f->count; -} - -static inline uint16_t tu_fifo_depth(tu_fifo_t* f) -{ - return f->depth; -} - -#ifdef __cplusplus - } -#endif - -#endif /* _TUSB_FIFO_H_ */ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +/** \ingroup Group_Common + * \defgroup group_fifo fifo + * @{ */ + +#ifndef _TUSB_FIFO_H_ +#define _TUSB_FIFO_H_ + +// mutex is only needed for RTOS +// for OS None, we don't get preempted +#define CFG_FIFO_MUTEX (CFG_TUSB_OS != OPT_OS_NONE) + +#include +#include + +#ifdef __cplusplus + extern "C" { +#endif + +#if CFG_FIFO_MUTEX +#define tu_fifo_mutex_t osal_mutex_t +#endif + + +/** \struct tu_fifo_t + * \brief Simple Circular FIFO + */ +typedef struct +{ + uint8_t* buffer ; ///< buffer pointer + uint16_t depth ; ///< max items + uint16_t item_size ; ///< size of each item + bool overwritable ; + + volatile uint16_t count ; ///< number of items in queue + volatile uint16_t wr_idx ; ///< write pointer + volatile uint16_t rd_idx ; ///< read pointer + +#if CFG_FIFO_MUTEX + tu_fifo_mutex_t mutex; +#endif + +} tu_fifo_t; + +#define TU_FIFO_DEF(_name, _depth, _type, _overwritable) \ + uint8_t _name##_buf[_depth*sizeof(_type)]; \ + tu_fifo_t _name = { \ + .buffer = _name##_buf, \ + .depth = _depth, \ + .item_size = sizeof(_type), \ + .overwritable = _overwritable, \ + } + +bool tu_fifo_clear(tu_fifo_t *f); +bool tu_fifo_config(tu_fifo_t *f, void* buffer, uint16_t depth, uint16_t item_size, bool overwritable); + +#if CFG_FIFO_MUTEX +static inline void tu_fifo_config_mutex(tu_fifo_t *f, tu_fifo_mutex_t mutex_hdl) +{ + f->mutex = mutex_hdl; +} +#endif + +bool tu_fifo_write (tu_fifo_t* f, void const * p_data); +uint16_t tu_fifo_write_n (tu_fifo_t* f, void const * p_data, uint16_t count); + +bool tu_fifo_read (tu_fifo_t* f, void * p_buffer); +uint16_t tu_fifo_read_n (tu_fifo_t* f, void * p_buffer, uint16_t count); + +bool tu_fifo_peek_at (tu_fifo_t* f, uint16_t pos, void * p_buffer); + +static inline bool tu_fifo_peek(tu_fifo_t* f, void * p_buffer) +{ + return tu_fifo_peek_at(f, 0, p_buffer); +} + +static inline bool tu_fifo_empty(tu_fifo_t* f) +{ + return (f->count == 0); +} + +static inline bool tu_fifo_full(tu_fifo_t* f) +{ + return (f->count == f->depth); +} + +static inline uint16_t tu_fifo_count(tu_fifo_t* f) +{ + return f->count; +} + +static inline uint16_t tu_fifo_remaining(tu_fifo_t* f) +{ + return f->depth - f->count; +} + +static inline uint16_t tu_fifo_depth(tu_fifo_t* f) +{ + return f->depth; +} + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_FIFO_H_ */ diff --git a/src/common/tusb_timeout.h b/src/common/tusb_timeout.h index 558742ff..ce53955f 100644 --- a/src/common/tusb_timeout.h +++ b/src/common/tusb_timeout.h @@ -1,80 +1,80 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2019 Ha Thach (tinyusb.org) - * - * 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. - * - * This file is part of the TinyUSB stack. - */ - -/** \ingroup Group_Common Common Files - * \defgroup Group_TimeoutTimer timeout timer - * @{ */ - -#ifndef _TUSB_TIMEOUT_H_ -#define _TUSB_TIMEOUT_H_ - -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct { - uint32_t start; - uint32_t interval; -}tu_timeout_t; - -#if 0 - -extern uint32_t tusb_hal_millis(void); - -static inline void tu_timeout_set(tu_timeout_t* tt, uint32_t msec) -{ - tt->interval = msec; - tt->start = tusb_hal_millis(); -} - -static inline bool tu_timeout_expired(tu_timeout_t* tt) -{ - return ( tusb_hal_millis() - tt->start ) >= tt->interval; -} - -// For used with periodic event to prevent drift -static inline void tu_timeout_reset(tu_timeout_t* tt) -{ - tt->start += tt->interval; -} - -static inline void tu_timeout_restart(tu_timeout_t* tt) -{ - tt->start = tusb_hal_millis(); -} - -#endif - -#ifdef __cplusplus - } -#endif - -#endif /* _TUSB_TIMEOUT_H_ */ - -/** @} */ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +/** \ingroup Group_Common Common Files + * \defgroup Group_TimeoutTimer timeout timer + * @{ */ + +#ifndef _TUSB_TIMEOUT_H_ +#define _TUSB_TIMEOUT_H_ + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct { + uint32_t start; + uint32_t interval; +}tu_timeout_t; + +#if 0 + +extern uint32_t tusb_hal_millis(void); + +static inline void tu_timeout_set(tu_timeout_t* tt, uint32_t msec) +{ + tt->interval = msec; + tt->start = tusb_hal_millis(); +} + +static inline bool tu_timeout_expired(tu_timeout_t* tt) +{ + return ( tusb_hal_millis() - tt->start ) >= tt->interval; +} + +// For used with periodic event to prevent drift +static inline void tu_timeout_reset(tu_timeout_t* tt) +{ + tt->start += tt->interval; +} + +static inline void tu_timeout_restart(tu_timeout_t* tt) +{ + tt->start = tusb_hal_millis(); +} + +#endif + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_TIMEOUT_H_ */ + +/** @} */ diff --git a/src/common/tusb_types.h b/src/common/tusb_types.h index 737b17f7..c37c19ba 100644 --- a/src/common/tusb_types.h +++ b/src/common/tusb_types.h @@ -1,481 +1,481 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2019 Ha Thach (tinyusb.org) - * - * 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. - * - * This file is part of the TinyUSB stack. - */ - -/** \ingroup group_usb_definitions - * \defgroup USBDef_Type USB Types - * @{ */ - -#ifndef _TUSB_TYPES_H_ -#define _TUSB_TYPES_H_ - -#include -#include -#include "tusb_compiler.h" - -#ifdef __cplusplus - extern "C" { -#endif - -/*------------------------------------------------------------------*/ -/* CONSTANTS - *------------------------------------------------------------------*/ - -/// defined base on EHCI specs value for Endpoint Speed -typedef enum -{ - TUSB_SPEED_FULL = 0, - TUSB_SPEED_LOW , - TUSB_SPEED_HIGH -}tusb_speed_t; - -/// defined base on USB Specs Endpoint's bmAttributes -typedef enum -{ - TUSB_XFER_CONTROL = 0 , - TUSB_XFER_ISOCHRONOUS , - TUSB_XFER_BULK , - TUSB_XFER_INTERRUPT -}tusb_xfer_type_t; - -typedef enum -{ - TUSB_DIR_OUT = 0, - TUSB_DIR_IN = 1, - - TUSB_DIR_IN_MASK = 0x80 -}tusb_dir_t; - -/// USB Descriptor Types -typedef enum -{ - TUSB_DESC_DEVICE = 0x01, - TUSB_DESC_CONFIGURATION = 0x02, - TUSB_DESC_STRING = 0x03, - TUSB_DESC_INTERFACE = 0x04, - TUSB_DESC_ENDPOINT = 0x05, - TUSB_DESC_DEVICE_QUALIFIER = 0x06, - TUSB_DESC_OTHER_SPEED_CONFIG = 0x07, - TUSB_DESC_INTERFACE_POWER = 0x08, - TUSB_DESC_OTG = 0x09, - TUSB_DESC_DEBUG = 0x0A, - TUSB_DESC_INTERFACE_ASSOCIATION = 0x0B, - - TUSB_DESC_BOS = 0x0F, - TUSB_DESC_DEVICE_CAPABILITY = 0x10, - - TUSB_DESC_FUNCTIONAL = 0x21, - - // Class Specific Descriptor - TUSB_DESC_CS_DEVICE = 0x21, - TUSB_DESC_CS_CONFIGURATION = 0x22, - TUSB_DESC_CS_STRING = 0x23, - TUSB_DESC_CS_INTERFACE = 0x24, - TUSB_DESC_CS_ENDPOINT = 0x25, - - TUSB_DESC_SUPERSPEED_ENDPOINT_COMPANION = 0x30, - TUSB_DESC_SUPERSPEED_ISO_ENDPOINT_COMPANION = 0x31 -}tusb_desc_type_t; - -typedef enum -{ - TUSB_REQ_GET_STATUS = 0 , - TUSB_REQ_CLEAR_FEATURE = 1 , - TUSB_REQ_RESERVED = 2 , - TUSB_REQ_SET_FEATURE = 3 , - TUSB_REQ_RESERVED2 = 4 , - TUSB_REQ_SET_ADDRESS = 5 , - TUSB_REQ_GET_DESCRIPTOR = 6 , - TUSB_REQ_SET_DESCRIPTOR = 7 , - TUSB_REQ_GET_CONFIGURATION = 8 , - TUSB_REQ_SET_CONFIGURATION = 9 , - TUSB_REQ_GET_INTERFACE = 10 , - TUSB_REQ_SET_INTERFACE = 11 , - TUSB_REQ_SYNCH_FRAME = 12 -}tusb_request_code_t; - -typedef enum -{ - TUSB_REQ_FEATURE_EDPT_HALT = 0, - TUSB_REQ_FEATURE_REMOTE_WAKEUP = 1, - TUSB_REQ_FEATURE_TEST_MODE = 2 -}tusb_request_feature_selector_t; - -typedef enum -{ - TUSB_REQ_TYPE_STANDARD = 0, - TUSB_REQ_TYPE_CLASS, - TUSB_REQ_TYPE_VENDOR, - TUSB_REQ_TYPE_INVALID -} tusb_request_type_t; - -typedef enum -{ - TUSB_REQ_RCPT_DEVICE =0, - TUSB_REQ_RCPT_INTERFACE, - TUSB_REQ_RCPT_ENDPOINT, - TUSB_REQ_RCPT_OTHER -} tusb_request_recipient_t; - -typedef enum -{ - TUSB_CLASS_UNSPECIFIED = 0 , - TUSB_CLASS_AUDIO = 1 , - TUSB_CLASS_CDC = 2 , - TUSB_CLASS_HID = 3 , - TUSB_CLASS_RESERVED_4 = 4 , - TUSB_CLASS_PHYSICAL = 5 , - TUSB_CLASS_IMAGE = 6 , - TUSB_CLASS_PRINTER = 7 , - TUSB_CLASS_MSC = 8 , - TUSB_CLASS_HUB = 9 , - TUSB_CLASS_CDC_DATA = 10 , - TUSB_CLASS_SMART_CARD = 11 , - TUSB_CLASS_RESERVED_12 = 12 , - TUSB_CLASS_CONTENT_SECURITY = 13 , - TUSB_CLASS_VIDEO = 14 , - TUSB_CLASS_PERSONAL_HEALTHCARE = 15 , - TUSB_CLASS_AUDIO_VIDEO = 16 , - - TUSB_CLASS_DIAGNOSTIC = 0xDC , - TUSB_CLASS_WIRELESS_CONTROLLER = 0xE0 , - TUSB_CLASS_MISC = 0xEF , - TUSB_CLASS_APPLICATION_SPECIFIC = 0xFE , - TUSB_CLASS_VENDOR_SPECIFIC = 0xFF -}tusb_class_code_t; - -typedef enum -{ - MISC_SUBCLASS_COMMON = 2 -}misc_subclass_type_t; - -typedef enum -{ - MISC_PROTOCOL_IAD = 1 -}misc_protocol_type_t; - -typedef enum -{ - DEVICE_CAPABILITY_WIRELESS_USB = 0x01, - DEVICE_CAPABILITY_USB20_EXTENSION = 0x02, - DEVICE_CAPABILITY_SUPERSPEED_USB = 0x03, - DEVICE_CAPABILITY_CONTAINER_id = 0x04, - DEVICE_CAPABILITY_PLATFORM = 0x05, - DEVICE_CAPABILITY_POWER_DELIVERY = 0x06, - DEVICE_CAPABILITY_BATTERY_INFO = 0x07, - DEVICE_CAPABILITY_PD_CONSUMER_PORT = 0x08, - DEVICE_CAPABILITY_PD_PROVIDER_PORT = 0x09, - DEVICE_CAPABILITY_SUPERSPEED_PLUS = 0x0A, - DEVICE_CAPABILITY_PRECESION_TIME_MEASUREMENT = 0x0B, - DEVICE_CAPABILITY_WIRELESS_USB_EXT = 0x0C, - DEVICE_CAPABILITY_BILLBOARD = 0x0D, - DEVICE_CAPABILITY_AUTHENTICATION = 0x0E, - DEVICE_CAPABILITY_BILLBOARD_EX = 0x0F, - DEVICE_CAPABILITY_CONFIGURATION_SUMMARY = 0x10 -}device_capability_type_t; - -enum { - TUSB_DESC_CONFIG_ATT_REMOTE_WAKEUP = TU_BIT(5), - TUSB_DESC_CONFIG_ATT_SELF_POWERED = TU_BIT(6), -}; - -#define TUSB_DESC_CONFIG_POWER_MA(x) ((x)/2) - -/// Device State TODO remove -typedef enum -{ - TUSB_DEVICE_STATE_UNPLUG = 0 , - TUSB_DEVICE_STATE_CONFIGURED , - TUSB_DEVICE_STATE_SUSPENDED , -}tusb_device_state_t; - -typedef enum -{ - XFER_RESULT_SUCCESS, - XFER_RESULT_FAILED, - XFER_RESULT_STALLED, -}xfer_result_t; - -enum // TODO remove -{ - DESC_OFFSET_LEN = 0, - DESC_OFFSET_TYPE = 1 -}; - -enum -{ - INTERFACE_INVALID_NUMBER = 0xff -}; - - -typedef enum -{ - MS_OS_20_SET_HEADER_DESCRIPTOR = 0x00, - MS_OS_20_SUBSET_HEADER_CONFIGURATION = 0x01, - MS_OS_20_SUBSET_HEADER_FUNCTION = 0x02, - MS_OS_20_FEATURE_COMPATBLE_ID = 0x03, - MS_OS_20_FEATURE_REG_PROPERTY = 0x04, - MS_OS_20_FEATURE_MIN_RESUME_TIME = 0x05, - MS_OS_20_FEATURE_MODEL_ID = 0x06, - MS_OS_20_FEATURE_CCGP_DEVICE = 0x07, - MS_OS_20_FEATURE_VENDOR_REVISION = 0x08 -} microsoft_os_20_type_t; - -//--------------------------------------------------------------------+ -// USB Descriptors -//--------------------------------------------------------------------+ - -/// USB Device Descriptor -typedef struct TU_ATTR_PACKED -{ - uint8_t bLength ; ///< Size of this descriptor in bytes. - uint8_t bDescriptorType ; ///< DEVICE Descriptor Type. - uint16_t bcdUSB ; ///< BUSB Specification Release Number in Binary-Coded Decimal (i.e., 2.10 is 210H). This field identifies the release of the USB Specification with which the device and its descriptors are compliant. - - uint8_t bDeviceClass ; ///< Class code (assigned by the USB-IF). \li If this field is reset to zero, each interface within a configuration specifies its own class information and the various interfaces operate independently. \li If this field is set to a value between 1 and FEH, the device supports different class specifications on different interfaces and the interfaces may not operate independently. This value identifies the class definition used for the aggregate interfaces. \li If this field is set to FFH, the device class is vendor-specific. - uint8_t bDeviceSubClass ; ///< Subclass code (assigned by the USB-IF). These codes are qualified by the value of the bDeviceClass field. \li If the bDeviceClass field is reset to zero, this field must also be reset to zero. \li If the bDeviceClass field is not set to FFH, all values are reserved for assignment by the USB-IF. - uint8_t bDeviceProtocol ; ///< Protocol code (assigned by the USB-IF). These codes are qualified by the value of the bDeviceClass and the bDeviceSubClass fields. If a device supports class-specific protocols on a device basis as opposed to an interface basis, this code identifies the protocols that the device uses as defined by the specification of the device class. \li If this field is reset to zero, the device does not use class-specific protocols on a device basis. However, it may use classspecific protocols on an interface basis. \li If this field is set to FFH, the device uses a vendor-specific protocol on a device basis. - uint8_t bMaxPacketSize0 ; ///< Maximum packet size for endpoint zero (only 8, 16, 32, or 64 are valid). For HS devices is fixed to 64. - - uint16_t idVendor ; ///< Vendor ID (assigned by the USB-IF). - uint16_t idProduct ; ///< Product ID (assigned by the manufacturer). - uint16_t bcdDevice ; ///< Device release number in binary-coded decimal. - uint8_t iManufacturer ; ///< Index of string descriptor describing manufacturer. - uint8_t iProduct ; ///< Index of string descriptor describing product. - uint8_t iSerialNumber ; ///< Index of string descriptor describing the device's serial number. - - uint8_t bNumConfigurations ; ///< Number of possible configurations. -} tusb_desc_device_t; - -// USB Binary Device Object Store (BOS) Descriptor -typedef struct TU_ATTR_PACKED -{ - uint8_t bLength ; ///< Size of this descriptor in bytes - uint8_t bDescriptorType ; ///< CONFIGURATION Descriptor Type - uint16_t wTotalLength ; ///< Total length of data returned for this descriptor - uint8_t bNumDeviceCaps ; ///< Number of device capability descriptors in the BOS -} tusb_desc_bos_t; - -/// USB Configuration Descriptor -typedef struct TU_ATTR_PACKED -{ - uint8_t bLength ; ///< Size of this descriptor in bytes - uint8_t bDescriptorType ; ///< CONFIGURATION Descriptor Type - uint16_t wTotalLength ; ///< Total length of data returned for this configuration. Includes the combined length of all descriptors (configuration, interface, endpoint, and class- or vendor-specific) returned for this configuration. - - uint8_t bNumInterfaces ; ///< Number of interfaces supported by this configuration - uint8_t bConfigurationValue ; ///< Value to use as an argument to the SetConfiguration() request to select this configuration. - uint8_t iConfiguration ; ///< Index of string descriptor describing this configuration - uint8_t bmAttributes ; ///< Configuration characteristics \n D7: Reserved (set to one)\n D6: Self-powered \n D5: Remote Wakeup \n D4...0: Reserved (reset to zero) \n D7 is reserved and must be set to one for historical reasons. \n A device configuration that uses power from the bus and a local source reports a non-zero value in bMaxPower to indicate the amount of bus power required and sets D6. The actual power source at runtime may be determined using the GetStatus(DEVICE) request (see USB 2.0 spec Section 9.4.5). \n If a device configuration supports remote wakeup, D5 is set to one. - uint8_t bMaxPower ; ///< Maximum power consumption of the USB device from the bus in this specific configuration when the device is fully operational. Expressed in 2 mA units (i.e., 50 = 100 mA). -} tusb_desc_configuration_t; - -/// USB Interface Descriptor -typedef struct TU_ATTR_PACKED -{ - uint8_t bLength ; ///< Size of this descriptor in bytes - uint8_t bDescriptorType ; ///< INTERFACE Descriptor Type - - uint8_t bInterfaceNumber ; ///< Number of this interface. Zero-based value identifying the index in the array of concurrent interfaces supported by this configuration. - uint8_t bAlternateSetting ; ///< Value used to select this alternate setting for the interface identified in the prior field - uint8_t bNumEndpoints ; ///< Number of endpoints used by this interface (excluding endpoint zero). If this value is zero, this interface only uses the Default Control Pipe. - uint8_t bInterfaceClass ; ///< Class code (assigned by the USB-IF). \li A value of zero is reserved for future standardization. \li If this field is set to FFH, the interface class is vendor-specific. \li All other values are reserved for assignment by the USB-IF. - uint8_t bInterfaceSubClass ; ///< Subclass code (assigned by the USB-IF). \n These codes are qualified by the value of the bInterfaceClass field. \li If the bInterfaceClass field is reset to zero, this field must also be reset to zero. \li If the bInterfaceClass field is not set to FFH, all values are reserved for assignment by the USB-IF. - uint8_t bInterfaceProtocol ; ///< Protocol code (assigned by the USB). \n These codes are qualified by the value of the bInterfaceClass and the bInterfaceSubClass fields. If an interface supports class-specific requests, this code identifies the protocols that the device uses as defined by the specification of the device class. \li If this field is reset to zero, the device does not use a class-specific protocol on this interface. \li If this field is set to FFH, the device uses a vendor-specific protocol for this interface. - uint8_t iInterface ; ///< Index of string descriptor describing this interface -} tusb_desc_interface_t; - -/// USB Endpoint Descriptor -typedef struct TU_ATTR_PACKED -{ - uint8_t bLength ; ///< Size of this descriptor in bytes - uint8_t bDescriptorType ; ///< ENDPOINT Descriptor Type - - uint8_t bEndpointAddress ; ///< The address of the endpoint on the USB device described by this descriptor. The address is encoded as follows: \n Bit 3...0: The endpoint number \n Bit 6...4: Reserved, reset to zero \n Bit 7: Direction, ignored for control endpoints 0 = OUT endpoint 1 = IN endpoint. - - struct TU_ATTR_PACKED { - uint8_t xfer : 2; - uint8_t sync : 2; - uint8_t usage : 2; - uint8_t : 2; - } bmAttributes ; ///< This field describes the endpoint's attributes when it is configured using the bConfigurationValue. \n Bits 1..0: Transfer Type \n- 00 = Control \n- 01 = Isochronous \n- 10 = Bulk \n- 11 = Interrupt \n If not an isochronous endpoint, bits 5..2 are reserved and must be set to zero. If isochronous, they are defined as follows: \n Bits 3..2: Synchronization Type \n- 00 = No Synchronization \n- 01 = Asynchronous \n- 10 = Adaptive \n- 11 = Synchronous \n Bits 5..4: Usage Type \n- 00 = Data endpoint \n- 01 = Feedback endpoint \n- 10 = Implicit feedback Data endpoint \n- 11 = Reserved \n Refer to Chapter 5 of USB 2.0 specification for more information. \n All other bits are reserved and must be reset to zero. Reserved bits must be ignored by the host. - - struct TU_ATTR_PACKED { - uint16_t size : 11; ///< Maximum packet size this endpoint is capable of sending or receiving when this configuration is selected. \n For isochronous endpoints, this value is used to reserve the bus time in the schedule, required for the per-(micro)frame data payloads. The pipe may, on an ongoing basis, actually use less bandwidth than that reserved. The device reports, if necessary, the actual bandwidth used via its normal, non-USB defined mechanisms. \n For all endpoints, bits 10..0 specify the maximum packet size (in bytes). \n For high-speed isochronous and interrupt endpoints: \n Bits 12..11 specify the number of additional transaction opportunities per microframe: \n- 00 = None (1 transaction per microframe) \n- 01 = 1 additional (2 per microframe) \n- 10 = 2 additional (3 per microframe) \n- 11 = Reserved \n Bits 15..13 are reserved and must be set to zero. - uint16_t hs_period_mult : 2; - uint16_t : 0; - }wMaxPacketSize; - - uint8_t bInterval ; ///< Interval for polling endpoint for data transfers. Expressed in frames or microframes depending on the device operating speed (i.e., either 1 millisecond or 125 us units). \n- For full-/high-speed isochronous endpoints, this value must be in the range from 1 to 16. The bInterval value is used as the exponent for a \f$ 2^(bInterval-1) \f$ value; e.g., a bInterval of 4 means a period of 8 (\f$ 2^(4-1) \f$). \n- For full-/low-speed interrupt endpoints, the value of this field may be from 1 to 255. \n- For high-speed interrupt endpoints, the bInterval value is used as the exponent for a \f$ 2^(bInterval-1) \f$ value; e.g., a bInterval of 4 means a period of 8 (\f$ 2^(4-1) \f$) . This value must be from 1 to 16. \n- For high-speed bulk/control OUT endpoints, the bInterval must specify the maximum NAK rate of the endpoint. A value of 0 indicates the endpoint never NAKs. Other values indicate at most 1 NAK each bInterval number of microframes. This value must be in the range from 0 to 255. \n Refer to Chapter 5 of USB 2.0 specification for more information. -} tusb_desc_endpoint_t; - -/// USB Other Speed Configuration Descriptor -typedef struct TU_ATTR_PACKED -{ - uint8_t bLength ; ///< Size of descriptor - uint8_t bDescriptorType ; ///< Other_speed_Configuration Type - uint16_t wTotalLength ; ///< Total length of data returned - - uint8_t bNumInterfaces ; ///< Number of interfaces supported by this speed configuration - uint8_t bConfigurationValue ; ///< Value to use to select configuration - uint8_t IConfiguration ; ///< Index of string descriptor - uint8_t bmAttributes ; ///< Same as Configuration descriptor - uint8_t bMaxPower ; ///< Same as Configuration descriptor -} tusb_desc_other_speed_t; - -/// USB Device Qualifier Descriptor -typedef struct TU_ATTR_PACKED -{ - uint8_t bLength ; ///< Size of descriptor - uint8_t bDescriptorType ; ///< Device Qualifier Type - uint16_t bcdUSB ; ///< USB specification version number (e.g., 0200H for V2.00) - - uint8_t bDeviceClass ; ///< Class Code - uint8_t bDeviceSubClass ; ///< SubClass Code - uint8_t bDeviceProtocol ; ///< Protocol Code - uint8_t bMaxPacketSize0 ; ///< Maximum packet size for other speed - uint8_t bNumConfigurations ; ///< Number of Other-speed Configurations - uint8_t bReserved ; ///< Reserved for future use, must be zero -} tusb_desc_device_qualifier_t; - -/// USB Interface Association Descriptor (IAD ECN) -typedef struct TU_ATTR_PACKED -{ - uint8_t bLength ; ///< Size of descriptor - uint8_t bDescriptorType ; ///< Other_speed_Configuration Type - - uint8_t bFirstInterface ; ///< Index of the first associated interface. - uint8_t bInterfaceCount ; ///< Total number of associated interfaces. - - uint8_t bFunctionClass ; ///< Interface class ID. - uint8_t bFunctionSubClass ; ///< Interface subclass ID. - uint8_t bFunctionProtocol ; ///< Interface protocol ID. - - uint8_t iFunction ; ///< Index of the string descriptor describing the interface association. -} tusb_desc_interface_assoc_t; - -// USB String Descriptor -typedef struct TU_ATTR_PACKED -{ - uint8_t bLength ; ///< Size of this descriptor in bytes - uint8_t bDescriptorType ; ///< Descriptor Type - uint16_t unicode_string[]; -} tusb_desc_string_t; - -// USB Binary Device Object Store (BOS) -typedef struct TU_ATTR_PACKED -{ - uint8_t bLength; - uint8_t bDescriptorType ; - uint8_t bDevCapabilityType; - uint8_t bReserved; - uint8_t PlatformCapabilityUUID[16]; - uint8_t CapabilityData[]; -} tusb_desc_bos_platform_t; - -// USB WebuSB URL Descriptor -typedef struct TU_ATTR_PACKED -{ - uint8_t bLength; - uint8_t bDescriptorType; - uint8_t bScheme; - char url[]; -} tusb_desc_webusb_url_t; - -/*------------------------------------------------------------------*/ -/* Types - *------------------------------------------------------------------*/ -typedef struct TU_ATTR_PACKED{ - union { - struct TU_ATTR_PACKED { - uint8_t recipient : 5; ///< Recipient type tusb_request_recipient_t. - uint8_t type : 2; ///< Request type tusb_request_type_t. - uint8_t direction : 1; ///< Direction type. tusb_dir_t - } bmRequestType_bit; - - uint8_t bmRequestType; - }; - - uint8_t bRequest; - uint16_t wValue; - uint16_t wIndex; - uint16_t wLength; -} tusb_control_request_t; - -TU_VERIFY_STATIC( sizeof(tusb_control_request_t) == 8, "mostly compiler option issue"); - -// TODO move to somewhere suitable -static inline uint8_t bm_request_type(uint8_t direction, uint8_t type, uint8_t recipient) -{ - return ((uint8_t) (direction << 7)) | ((uint8_t) (type << 5)) | (recipient); -} - -//--------------------------------------------------------------------+ -// Endpoint helper -//--------------------------------------------------------------------+ - -// Get direction from Endpoint address -static inline tusb_dir_t tu_edpt_dir(uint8_t addr) -{ - return (addr & TUSB_DIR_IN_MASK) ? TUSB_DIR_IN : TUSB_DIR_OUT; -} - -// Get Endpoint number from address -static inline uint8_t tu_edpt_number(uint8_t addr) -{ - return (uint8_t)(addr & (~TUSB_DIR_IN_MASK)); -} - -static inline uint8_t tu_edpt_addr(uint8_t num, uint8_t dir) -{ - return (uint8_t)(num | (dir ? TUSB_DIR_IN_MASK : 0)); -} - -//--------------------------------------------------------------------+ -// Descriptor helper -//--------------------------------------------------------------------+ -static inline uint8_t const * tu_desc_next(void const* desc) -{ - uint8_t const* desc8 = (uint8_t const*) desc; - return desc8 + desc8[DESC_OFFSET_LEN]; -} - -static inline uint8_t tu_desc_type(void const* desc) -{ - return ((uint8_t const*) desc)[DESC_OFFSET_TYPE]; -} - -static inline uint8_t tu_desc_len(void const* desc) -{ - return ((uint8_t const*) desc)[DESC_OFFSET_LEN]; -} - -#ifdef __cplusplus - } -#endif - -#endif /* _TUSB_TYPES_H_ */ - -/** @} */ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +/** \ingroup group_usb_definitions + * \defgroup USBDef_Type USB Types + * @{ */ + +#ifndef _TUSB_TYPES_H_ +#define _TUSB_TYPES_H_ + +#include +#include +#include "tusb_compiler.h" + +#ifdef __cplusplus + extern "C" { +#endif + +/*------------------------------------------------------------------*/ +/* CONSTANTS + *------------------------------------------------------------------*/ + +/// defined base on EHCI specs value for Endpoint Speed +typedef enum +{ + TUSB_SPEED_FULL = 0, + TUSB_SPEED_LOW , + TUSB_SPEED_HIGH +}tusb_speed_t; + +/// defined base on USB Specs Endpoint's bmAttributes +typedef enum +{ + TUSB_XFER_CONTROL = 0 , + TUSB_XFER_ISOCHRONOUS , + TUSB_XFER_BULK , + TUSB_XFER_INTERRUPT +}tusb_xfer_type_t; + +typedef enum +{ + TUSB_DIR_OUT = 0, + TUSB_DIR_IN = 1, + + TUSB_DIR_IN_MASK = 0x80 +}tusb_dir_t; + +/// USB Descriptor Types +typedef enum +{ + TUSB_DESC_DEVICE = 0x01, + TUSB_DESC_CONFIGURATION = 0x02, + TUSB_DESC_STRING = 0x03, + TUSB_DESC_INTERFACE = 0x04, + TUSB_DESC_ENDPOINT = 0x05, + TUSB_DESC_DEVICE_QUALIFIER = 0x06, + TUSB_DESC_OTHER_SPEED_CONFIG = 0x07, + TUSB_DESC_INTERFACE_POWER = 0x08, + TUSB_DESC_OTG = 0x09, + TUSB_DESC_DEBUG = 0x0A, + TUSB_DESC_INTERFACE_ASSOCIATION = 0x0B, + + TUSB_DESC_BOS = 0x0F, + TUSB_DESC_DEVICE_CAPABILITY = 0x10, + + TUSB_DESC_FUNCTIONAL = 0x21, + + // Class Specific Descriptor + TUSB_DESC_CS_DEVICE = 0x21, + TUSB_DESC_CS_CONFIGURATION = 0x22, + TUSB_DESC_CS_STRING = 0x23, + TUSB_DESC_CS_INTERFACE = 0x24, + TUSB_DESC_CS_ENDPOINT = 0x25, + + TUSB_DESC_SUPERSPEED_ENDPOINT_COMPANION = 0x30, + TUSB_DESC_SUPERSPEED_ISO_ENDPOINT_COMPANION = 0x31 +}tusb_desc_type_t; + +typedef enum +{ + TUSB_REQ_GET_STATUS = 0 , + TUSB_REQ_CLEAR_FEATURE = 1 , + TUSB_REQ_RESERVED = 2 , + TUSB_REQ_SET_FEATURE = 3 , + TUSB_REQ_RESERVED2 = 4 , + TUSB_REQ_SET_ADDRESS = 5 , + TUSB_REQ_GET_DESCRIPTOR = 6 , + TUSB_REQ_SET_DESCRIPTOR = 7 , + TUSB_REQ_GET_CONFIGURATION = 8 , + TUSB_REQ_SET_CONFIGURATION = 9 , + TUSB_REQ_GET_INTERFACE = 10 , + TUSB_REQ_SET_INTERFACE = 11 , + TUSB_REQ_SYNCH_FRAME = 12 +}tusb_request_code_t; + +typedef enum +{ + TUSB_REQ_FEATURE_EDPT_HALT = 0, + TUSB_REQ_FEATURE_REMOTE_WAKEUP = 1, + TUSB_REQ_FEATURE_TEST_MODE = 2 +}tusb_request_feature_selector_t; + +typedef enum +{ + TUSB_REQ_TYPE_STANDARD = 0, + TUSB_REQ_TYPE_CLASS, + TUSB_REQ_TYPE_VENDOR, + TUSB_REQ_TYPE_INVALID +} tusb_request_type_t; + +typedef enum +{ + TUSB_REQ_RCPT_DEVICE =0, + TUSB_REQ_RCPT_INTERFACE, + TUSB_REQ_RCPT_ENDPOINT, + TUSB_REQ_RCPT_OTHER +} tusb_request_recipient_t; + +typedef enum +{ + TUSB_CLASS_UNSPECIFIED = 0 , + TUSB_CLASS_AUDIO = 1 , + TUSB_CLASS_CDC = 2 , + TUSB_CLASS_HID = 3 , + TUSB_CLASS_RESERVED_4 = 4 , + TUSB_CLASS_PHYSICAL = 5 , + TUSB_CLASS_IMAGE = 6 , + TUSB_CLASS_PRINTER = 7 , + TUSB_CLASS_MSC = 8 , + TUSB_CLASS_HUB = 9 , + TUSB_CLASS_CDC_DATA = 10 , + TUSB_CLASS_SMART_CARD = 11 , + TUSB_CLASS_RESERVED_12 = 12 , + TUSB_CLASS_CONTENT_SECURITY = 13 , + TUSB_CLASS_VIDEO = 14 , + TUSB_CLASS_PERSONAL_HEALTHCARE = 15 , + TUSB_CLASS_AUDIO_VIDEO = 16 , + + TUSB_CLASS_DIAGNOSTIC = 0xDC , + TUSB_CLASS_WIRELESS_CONTROLLER = 0xE0 , + TUSB_CLASS_MISC = 0xEF , + TUSB_CLASS_APPLICATION_SPECIFIC = 0xFE , + TUSB_CLASS_VENDOR_SPECIFIC = 0xFF +}tusb_class_code_t; + +typedef enum +{ + MISC_SUBCLASS_COMMON = 2 +}misc_subclass_type_t; + +typedef enum +{ + MISC_PROTOCOL_IAD = 1 +}misc_protocol_type_t; + +typedef enum +{ + DEVICE_CAPABILITY_WIRELESS_USB = 0x01, + DEVICE_CAPABILITY_USB20_EXTENSION = 0x02, + DEVICE_CAPABILITY_SUPERSPEED_USB = 0x03, + DEVICE_CAPABILITY_CONTAINER_id = 0x04, + DEVICE_CAPABILITY_PLATFORM = 0x05, + DEVICE_CAPABILITY_POWER_DELIVERY = 0x06, + DEVICE_CAPABILITY_BATTERY_INFO = 0x07, + DEVICE_CAPABILITY_PD_CONSUMER_PORT = 0x08, + DEVICE_CAPABILITY_PD_PROVIDER_PORT = 0x09, + DEVICE_CAPABILITY_SUPERSPEED_PLUS = 0x0A, + DEVICE_CAPABILITY_PRECESION_TIME_MEASUREMENT = 0x0B, + DEVICE_CAPABILITY_WIRELESS_USB_EXT = 0x0C, + DEVICE_CAPABILITY_BILLBOARD = 0x0D, + DEVICE_CAPABILITY_AUTHENTICATION = 0x0E, + DEVICE_CAPABILITY_BILLBOARD_EX = 0x0F, + DEVICE_CAPABILITY_CONFIGURATION_SUMMARY = 0x10 +}device_capability_type_t; + +enum { + TUSB_DESC_CONFIG_ATT_REMOTE_WAKEUP = TU_BIT(5), + TUSB_DESC_CONFIG_ATT_SELF_POWERED = TU_BIT(6), +}; + +#define TUSB_DESC_CONFIG_POWER_MA(x) ((x)/2) + +/// Device State TODO remove +typedef enum +{ + TUSB_DEVICE_STATE_UNPLUG = 0 , + TUSB_DEVICE_STATE_CONFIGURED , + TUSB_DEVICE_STATE_SUSPENDED , +}tusb_device_state_t; + +typedef enum +{ + XFER_RESULT_SUCCESS, + XFER_RESULT_FAILED, + XFER_RESULT_STALLED, +}xfer_result_t; + +enum // TODO remove +{ + DESC_OFFSET_LEN = 0, + DESC_OFFSET_TYPE = 1 +}; + +enum +{ + INTERFACE_INVALID_NUMBER = 0xff +}; + + +typedef enum +{ + MS_OS_20_SET_HEADER_DESCRIPTOR = 0x00, + MS_OS_20_SUBSET_HEADER_CONFIGURATION = 0x01, + MS_OS_20_SUBSET_HEADER_FUNCTION = 0x02, + MS_OS_20_FEATURE_COMPATBLE_ID = 0x03, + MS_OS_20_FEATURE_REG_PROPERTY = 0x04, + MS_OS_20_FEATURE_MIN_RESUME_TIME = 0x05, + MS_OS_20_FEATURE_MODEL_ID = 0x06, + MS_OS_20_FEATURE_CCGP_DEVICE = 0x07, + MS_OS_20_FEATURE_VENDOR_REVISION = 0x08 +} microsoft_os_20_type_t; + +//--------------------------------------------------------------------+ +// USB Descriptors +//--------------------------------------------------------------------+ + +/// USB Device Descriptor +typedef struct TU_ATTR_PACKED +{ + uint8_t bLength ; ///< Size of this descriptor in bytes. + uint8_t bDescriptorType ; ///< DEVICE Descriptor Type. + uint16_t bcdUSB ; ///< BUSB Specification Release Number in Binary-Coded Decimal (i.e., 2.10 is 210H). This field identifies the release of the USB Specification with which the device and its descriptors are compliant. + + uint8_t bDeviceClass ; ///< Class code (assigned by the USB-IF). \li If this field is reset to zero, each interface within a configuration specifies its own class information and the various interfaces operate independently. \li If this field is set to a value between 1 and FEH, the device supports different class specifications on different interfaces and the interfaces may not operate independently. This value identifies the class definition used for the aggregate interfaces. \li If this field is set to FFH, the device class is vendor-specific. + uint8_t bDeviceSubClass ; ///< Subclass code (assigned by the USB-IF). These codes are qualified by the value of the bDeviceClass field. \li If the bDeviceClass field is reset to zero, this field must also be reset to zero. \li If the bDeviceClass field is not set to FFH, all values are reserved for assignment by the USB-IF. + uint8_t bDeviceProtocol ; ///< Protocol code (assigned by the USB-IF). These codes are qualified by the value of the bDeviceClass and the bDeviceSubClass fields. If a device supports class-specific protocols on a device basis as opposed to an interface basis, this code identifies the protocols that the device uses as defined by the specification of the device class. \li If this field is reset to zero, the device does not use class-specific protocols on a device basis. However, it may use classspecific protocols on an interface basis. \li If this field is set to FFH, the device uses a vendor-specific protocol on a device basis. + uint8_t bMaxPacketSize0 ; ///< Maximum packet size for endpoint zero (only 8, 16, 32, or 64 are valid). For HS devices is fixed to 64. + + uint16_t idVendor ; ///< Vendor ID (assigned by the USB-IF). + uint16_t idProduct ; ///< Product ID (assigned by the manufacturer). + uint16_t bcdDevice ; ///< Device release number in binary-coded decimal. + uint8_t iManufacturer ; ///< Index of string descriptor describing manufacturer. + uint8_t iProduct ; ///< Index of string descriptor describing product. + uint8_t iSerialNumber ; ///< Index of string descriptor describing the device's serial number. + + uint8_t bNumConfigurations ; ///< Number of possible configurations. +} tusb_desc_device_t; + +// USB Binary Device Object Store (BOS) Descriptor +typedef struct TU_ATTR_PACKED +{ + uint8_t bLength ; ///< Size of this descriptor in bytes + uint8_t bDescriptorType ; ///< CONFIGURATION Descriptor Type + uint16_t wTotalLength ; ///< Total length of data returned for this descriptor + uint8_t bNumDeviceCaps ; ///< Number of device capability descriptors in the BOS +} tusb_desc_bos_t; + +/// USB Configuration Descriptor +typedef struct TU_ATTR_PACKED +{ + uint8_t bLength ; ///< Size of this descriptor in bytes + uint8_t bDescriptorType ; ///< CONFIGURATION Descriptor Type + uint16_t wTotalLength ; ///< Total length of data returned for this configuration. Includes the combined length of all descriptors (configuration, interface, endpoint, and class- or vendor-specific) returned for this configuration. + + uint8_t bNumInterfaces ; ///< Number of interfaces supported by this configuration + uint8_t bConfigurationValue ; ///< Value to use as an argument to the SetConfiguration() request to select this configuration. + uint8_t iConfiguration ; ///< Index of string descriptor describing this configuration + uint8_t bmAttributes ; ///< Configuration characteristics \n D7: Reserved (set to one)\n D6: Self-powered \n D5: Remote Wakeup \n D4...0: Reserved (reset to zero) \n D7 is reserved and must be set to one for historical reasons. \n A device configuration that uses power from the bus and a local source reports a non-zero value in bMaxPower to indicate the amount of bus power required and sets D6. The actual power source at runtime may be determined using the GetStatus(DEVICE) request (see USB 2.0 spec Section 9.4.5). \n If a device configuration supports remote wakeup, D5 is set to one. + uint8_t bMaxPower ; ///< Maximum power consumption of the USB device from the bus in this specific configuration when the device is fully operational. Expressed in 2 mA units (i.e., 50 = 100 mA). +} tusb_desc_configuration_t; + +/// USB Interface Descriptor +typedef struct TU_ATTR_PACKED +{ + uint8_t bLength ; ///< Size of this descriptor in bytes + uint8_t bDescriptorType ; ///< INTERFACE Descriptor Type + + uint8_t bInterfaceNumber ; ///< Number of this interface. Zero-based value identifying the index in the array of concurrent interfaces supported by this configuration. + uint8_t bAlternateSetting ; ///< Value used to select this alternate setting for the interface identified in the prior field + uint8_t bNumEndpoints ; ///< Number of endpoints used by this interface (excluding endpoint zero). If this value is zero, this interface only uses the Default Control Pipe. + uint8_t bInterfaceClass ; ///< Class code (assigned by the USB-IF). \li A value of zero is reserved for future standardization. \li If this field is set to FFH, the interface class is vendor-specific. \li All other values are reserved for assignment by the USB-IF. + uint8_t bInterfaceSubClass ; ///< Subclass code (assigned by the USB-IF). \n These codes are qualified by the value of the bInterfaceClass field. \li If the bInterfaceClass field is reset to zero, this field must also be reset to zero. \li If the bInterfaceClass field is not set to FFH, all values are reserved for assignment by the USB-IF. + uint8_t bInterfaceProtocol ; ///< Protocol code (assigned by the USB). \n These codes are qualified by the value of the bInterfaceClass and the bInterfaceSubClass fields. If an interface supports class-specific requests, this code identifies the protocols that the device uses as defined by the specification of the device class. \li If this field is reset to zero, the device does not use a class-specific protocol on this interface. \li If this field is set to FFH, the device uses a vendor-specific protocol for this interface. + uint8_t iInterface ; ///< Index of string descriptor describing this interface +} tusb_desc_interface_t; + +/// USB Endpoint Descriptor +typedef struct TU_ATTR_PACKED +{ + uint8_t bLength ; ///< Size of this descriptor in bytes + uint8_t bDescriptorType ; ///< ENDPOINT Descriptor Type + + uint8_t bEndpointAddress ; ///< The address of the endpoint on the USB device described by this descriptor. The address is encoded as follows: \n Bit 3...0: The endpoint number \n Bit 6...4: Reserved, reset to zero \n Bit 7: Direction, ignored for control endpoints 0 = OUT endpoint 1 = IN endpoint. + + struct TU_ATTR_PACKED { + uint8_t xfer : 2; + uint8_t sync : 2; + uint8_t usage : 2; + uint8_t : 2; + } bmAttributes ; ///< This field describes the endpoint's attributes when it is configured using the bConfigurationValue. \n Bits 1..0: Transfer Type \n- 00 = Control \n- 01 = Isochronous \n- 10 = Bulk \n- 11 = Interrupt \n If not an isochronous endpoint, bits 5..2 are reserved and must be set to zero. If isochronous, they are defined as follows: \n Bits 3..2: Synchronization Type \n- 00 = No Synchronization \n- 01 = Asynchronous \n- 10 = Adaptive \n- 11 = Synchronous \n Bits 5..4: Usage Type \n- 00 = Data endpoint \n- 01 = Feedback endpoint \n- 10 = Implicit feedback Data endpoint \n- 11 = Reserved \n Refer to Chapter 5 of USB 2.0 specification for more information. \n All other bits are reserved and must be reset to zero. Reserved bits must be ignored by the host. + + struct TU_ATTR_PACKED { + uint16_t size : 11; ///< Maximum packet size this endpoint is capable of sending or receiving when this configuration is selected. \n For isochronous endpoints, this value is used to reserve the bus time in the schedule, required for the per-(micro)frame data payloads. The pipe may, on an ongoing basis, actually use less bandwidth than that reserved. The device reports, if necessary, the actual bandwidth used via its normal, non-USB defined mechanisms. \n For all endpoints, bits 10..0 specify the maximum packet size (in bytes). \n For high-speed isochronous and interrupt endpoints: \n Bits 12..11 specify the number of additional transaction opportunities per microframe: \n- 00 = None (1 transaction per microframe) \n- 01 = 1 additional (2 per microframe) \n- 10 = 2 additional (3 per microframe) \n- 11 = Reserved \n Bits 15..13 are reserved and must be set to zero. + uint16_t hs_period_mult : 2; + uint16_t : 0; + }wMaxPacketSize; + + uint8_t bInterval ; ///< Interval for polling endpoint for data transfers. Expressed in frames or microframes depending on the device operating speed (i.e., either 1 millisecond or 125 us units). \n- For full-/high-speed isochronous endpoints, this value must be in the range from 1 to 16. The bInterval value is used as the exponent for a \f$ 2^(bInterval-1) \f$ value; e.g., a bInterval of 4 means a period of 8 (\f$ 2^(4-1) \f$). \n- For full-/low-speed interrupt endpoints, the value of this field may be from 1 to 255. \n- For high-speed interrupt endpoints, the bInterval value is used as the exponent for a \f$ 2^(bInterval-1) \f$ value; e.g., a bInterval of 4 means a period of 8 (\f$ 2^(4-1) \f$) . This value must be from 1 to 16. \n- For high-speed bulk/control OUT endpoints, the bInterval must specify the maximum NAK rate of the endpoint. A value of 0 indicates the endpoint never NAKs. Other values indicate at most 1 NAK each bInterval number of microframes. This value must be in the range from 0 to 255. \n Refer to Chapter 5 of USB 2.0 specification for more information. +} tusb_desc_endpoint_t; + +/// USB Other Speed Configuration Descriptor +typedef struct TU_ATTR_PACKED +{ + uint8_t bLength ; ///< Size of descriptor + uint8_t bDescriptorType ; ///< Other_speed_Configuration Type + uint16_t wTotalLength ; ///< Total length of data returned + + uint8_t bNumInterfaces ; ///< Number of interfaces supported by this speed configuration + uint8_t bConfigurationValue ; ///< Value to use to select configuration + uint8_t IConfiguration ; ///< Index of string descriptor + uint8_t bmAttributes ; ///< Same as Configuration descriptor + uint8_t bMaxPower ; ///< Same as Configuration descriptor +} tusb_desc_other_speed_t; + +/// USB Device Qualifier Descriptor +typedef struct TU_ATTR_PACKED +{ + uint8_t bLength ; ///< Size of descriptor + uint8_t bDescriptorType ; ///< Device Qualifier Type + uint16_t bcdUSB ; ///< USB specification version number (e.g., 0200H for V2.00) + + uint8_t bDeviceClass ; ///< Class Code + uint8_t bDeviceSubClass ; ///< SubClass Code + uint8_t bDeviceProtocol ; ///< Protocol Code + uint8_t bMaxPacketSize0 ; ///< Maximum packet size for other speed + uint8_t bNumConfigurations ; ///< Number of Other-speed Configurations + uint8_t bReserved ; ///< Reserved for future use, must be zero +} tusb_desc_device_qualifier_t; + +/// USB Interface Association Descriptor (IAD ECN) +typedef struct TU_ATTR_PACKED +{ + uint8_t bLength ; ///< Size of descriptor + uint8_t bDescriptorType ; ///< Other_speed_Configuration Type + + uint8_t bFirstInterface ; ///< Index of the first associated interface. + uint8_t bInterfaceCount ; ///< Total number of associated interfaces. + + uint8_t bFunctionClass ; ///< Interface class ID. + uint8_t bFunctionSubClass ; ///< Interface subclass ID. + uint8_t bFunctionProtocol ; ///< Interface protocol ID. + + uint8_t iFunction ; ///< Index of the string descriptor describing the interface association. +} tusb_desc_interface_assoc_t; + +// USB String Descriptor +typedef struct TU_ATTR_PACKED +{ + uint8_t bLength ; ///< Size of this descriptor in bytes + uint8_t bDescriptorType ; ///< Descriptor Type + uint16_t unicode_string[]; +} tusb_desc_string_t; + +// USB Binary Device Object Store (BOS) +typedef struct TU_ATTR_PACKED +{ + uint8_t bLength; + uint8_t bDescriptorType ; + uint8_t bDevCapabilityType; + uint8_t bReserved; + uint8_t PlatformCapabilityUUID[16]; + uint8_t CapabilityData[]; +} tusb_desc_bos_platform_t; + +// USB WebuSB URL Descriptor +typedef struct TU_ATTR_PACKED +{ + uint8_t bLength; + uint8_t bDescriptorType; + uint8_t bScheme; + char url[]; +} tusb_desc_webusb_url_t; + +/*------------------------------------------------------------------*/ +/* Types + *------------------------------------------------------------------*/ +typedef struct TU_ATTR_PACKED{ + union { + struct TU_ATTR_PACKED { + uint8_t recipient : 5; ///< Recipient type tusb_request_recipient_t. + uint8_t type : 2; ///< Request type tusb_request_type_t. + uint8_t direction : 1; ///< Direction type. tusb_dir_t + } bmRequestType_bit; + + uint8_t bmRequestType; + }; + + uint8_t bRequest; + uint16_t wValue; + uint16_t wIndex; + uint16_t wLength; +} tusb_control_request_t; + +TU_VERIFY_STATIC( sizeof(tusb_control_request_t) == 8, "mostly compiler option issue"); + +// TODO move to somewhere suitable +static inline uint8_t bm_request_type(uint8_t direction, uint8_t type, uint8_t recipient) +{ + return ((uint8_t) (direction << 7)) | ((uint8_t) (type << 5)) | (recipient); +} + +//--------------------------------------------------------------------+ +// Endpoint helper +//--------------------------------------------------------------------+ + +// Get direction from Endpoint address +static inline tusb_dir_t tu_edpt_dir(uint8_t addr) +{ + return (addr & TUSB_DIR_IN_MASK) ? TUSB_DIR_IN : TUSB_DIR_OUT; +} + +// Get Endpoint number from address +static inline uint8_t tu_edpt_number(uint8_t addr) +{ + return (uint8_t)(addr & (~TUSB_DIR_IN_MASK)); +} + +static inline uint8_t tu_edpt_addr(uint8_t num, uint8_t dir) +{ + return (uint8_t)(num | (dir ? TUSB_DIR_IN_MASK : 0)); +} + +//--------------------------------------------------------------------+ +// Descriptor helper +//--------------------------------------------------------------------+ +static inline uint8_t const * tu_desc_next(void const* desc) +{ + uint8_t const* desc8 = (uint8_t const*) desc; + return desc8 + desc8[DESC_OFFSET_LEN]; +} + +static inline uint8_t tu_desc_type(void const* desc) +{ + return ((uint8_t const*) desc)[DESC_OFFSET_TYPE]; +} + +static inline uint8_t tu_desc_len(void const* desc) +{ + return ((uint8_t const*) desc)[DESC_OFFSET_LEN]; +} + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_TYPES_H_ */ + +/** @} */ diff --git a/src/device/dcd.h b/src/device/dcd.h index 8ae232fa..143a2de3 100644 --- a/src/device/dcd.h +++ b/src/device/dcd.h @@ -1,151 +1,151 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2019 Ha Thach (tinyusb.org) - * - * 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. - * - * This file is part of the TinyUSB stack. - */ - -/** \ingroup group_usbd - * \defgroup group_dcd Device Controller Driver (DCD) - * @{ */ - -#ifndef _TUSB_DCD_H_ -#define _TUSB_DCD_H_ - -#include "common/tusb_common.h" - -#ifdef __cplusplus - extern "C" { -#endif - -typedef enum -{ - DCD_EVENT_INVALID = 0, - DCD_EVENT_BUS_RESET, - DCD_EVENT_UNPLUGGED, - DCD_EVENT_SOF, - DCD_EVENT_SUSPEND, // TODO LPM Sleep L1 support - DCD_EVENT_RESUME, - - DCD_EVENT_SETUP_RECEIVED, - DCD_EVENT_XFER_COMPLETE, - - // Not an DCD event, just a convenient way to defer ISR function - USBD_EVENT_FUNC_CALL, - - DCD_EVENT_COUNT -} dcd_eventid_t; - -typedef struct TU_ATTR_ALIGNED(4) -{ - uint8_t rhport; - uint8_t event_id; - - union { - // USBD_EVT_SETUP_RECEIVED - tusb_control_request_t setup_received; - - // USBD_EVT_XFER_COMPLETE - struct { - uint8_t ep_addr; - uint8_t result; - uint32_t len; - }xfer_complete; - - // USBD_EVENT_FUNC_CALL - struct { - void (*func) (void*); - void* param; - }func_call; - }; -} dcd_event_t; - -//TU_VERIFY_STATIC(sizeof(dcd_event_t) <= 12, "size is not correct"); - -/*------------------------------------------------------------------*/ -/* Device API - *------------------------------------------------------------------*/ - -// Initialize controller to device mode -void dcd_init (uint8_t rhport); - -// Interrupt Handler -void dcd_isr (uint8_t rhport); - -// Enable device interrupt -void dcd_int_enable (uint8_t rhport); - -// Disable device interrupt -void dcd_int_disable(uint8_t rhport); - -// Receive Set Address request, mcu port must also include status IN response -void dcd_set_address(uint8_t rhport, uint8_t dev_addr); - -// Receive Set Configure request -void dcd_set_config (uint8_t rhport, uint8_t config_num); - -// Wake up host -void dcd_remote_wakeup(uint8_t rhport); - -//--------------------------------------------------------------------+ -// Endpoint API -//--------------------------------------------------------------------+ - -// Invoked when a control transfer's status stage is complete. -// May help DCD to prepare for next control transfer, this API is optional. -void dcd_edpt0_status_complete(uint8_t rhport, tusb_control_request_t const * request) TU_ATTR_WEAK; - -// Configure endpoint's registers according to descriptor -bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc); - -// Submit a transfer, When complete dcd_event_xfer_complete() is invoked to notify the stack -bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t total_bytes); - -// Stall endpoint -void dcd_edpt_stall (uint8_t rhport, uint8_t ep_addr); - -// clear stall, data toggle is also reset to DATA0 -void dcd_edpt_clear_stall (uint8_t rhport, uint8_t ep_addr); - -//--------------------------------------------------------------------+ -// Event API (Implemented by device stack) -//--------------------------------------------------------------------+ - -// Called by DCD to notify device stack -extern void dcd_event_handler(dcd_event_t const * event, bool in_isr); - -// helper to send bus signal event -extern void dcd_event_bus_signal (uint8_t rhport, dcd_eventid_t eid, bool in_isr); - -// helper to send setup received -extern void dcd_event_setup_received(uint8_t rhport, uint8_t const * setup, bool in_isr); - -// helper to send transfer complete event -extern void dcd_event_xfer_complete (uint8_t rhport, uint8_t ep_addr, uint32_t xferred_bytes, uint8_t result, bool in_isr); - -#ifdef __cplusplus - } -#endif - -#endif /* _TUSB_DCD_H_ */ - -/// @} +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +/** \ingroup group_usbd + * \defgroup group_dcd Device Controller Driver (DCD) + * @{ */ + +#ifndef _TUSB_DCD_H_ +#define _TUSB_DCD_H_ + +#include "common/tusb_common.h" + +#ifdef __cplusplus + extern "C" { +#endif + +typedef enum +{ + DCD_EVENT_INVALID = 0, + DCD_EVENT_BUS_RESET, + DCD_EVENT_UNPLUGGED, + DCD_EVENT_SOF, + DCD_EVENT_SUSPEND, // TODO LPM Sleep L1 support + DCD_EVENT_RESUME, + + DCD_EVENT_SETUP_RECEIVED, + DCD_EVENT_XFER_COMPLETE, + + // Not an DCD event, just a convenient way to defer ISR function + USBD_EVENT_FUNC_CALL, + + DCD_EVENT_COUNT +} dcd_eventid_t; + +typedef struct TU_ATTR_ALIGNED(4) +{ + uint8_t rhport; + uint8_t event_id; + + union { + // USBD_EVT_SETUP_RECEIVED + tusb_control_request_t setup_received; + + // USBD_EVT_XFER_COMPLETE + struct { + uint8_t ep_addr; + uint8_t result; + uint32_t len; + }xfer_complete; + + // USBD_EVENT_FUNC_CALL + struct { + void (*func) (void*); + void* param; + }func_call; + }; +} dcd_event_t; + +//TU_VERIFY_STATIC(sizeof(dcd_event_t) <= 12, "size is not correct"); + +/*------------------------------------------------------------------*/ +/* Device API + *------------------------------------------------------------------*/ + +// Initialize controller to device mode +void dcd_init (uint8_t rhport); + +// Interrupt Handler +void dcd_isr (uint8_t rhport); + +// Enable device interrupt +void dcd_int_enable (uint8_t rhport); + +// Disable device interrupt +void dcd_int_disable(uint8_t rhport); + +// Receive Set Address request, mcu port must also include status IN response +void dcd_set_address(uint8_t rhport, uint8_t dev_addr); + +// Receive Set Configure request +void dcd_set_config (uint8_t rhport, uint8_t config_num); + +// Wake up host +void dcd_remote_wakeup(uint8_t rhport); + +//--------------------------------------------------------------------+ +// Endpoint API +//--------------------------------------------------------------------+ + +// Invoked when a control transfer's status stage is complete. +// May help DCD to prepare for next control transfer, this API is optional. +void dcd_edpt0_status_complete(uint8_t rhport, tusb_control_request_t const * request) TU_ATTR_WEAK; + +// Configure endpoint's registers according to descriptor +bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc); + +// Submit a transfer, When complete dcd_event_xfer_complete() is invoked to notify the stack +bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t total_bytes); + +// Stall endpoint +void dcd_edpt_stall (uint8_t rhport, uint8_t ep_addr); + +// clear stall, data toggle is also reset to DATA0 +void dcd_edpt_clear_stall (uint8_t rhport, uint8_t ep_addr); + +//--------------------------------------------------------------------+ +// Event API (Implemented by device stack) +//--------------------------------------------------------------------+ + +// Called by DCD to notify device stack +extern void dcd_event_handler(dcd_event_t const * event, bool in_isr); + +// helper to send bus signal event +extern void dcd_event_bus_signal (uint8_t rhport, dcd_eventid_t eid, bool in_isr); + +// helper to send setup received +extern void dcd_event_setup_received(uint8_t rhport, uint8_t const * setup, bool in_isr); + +// helper to send transfer complete event +extern void dcd_event_xfer_complete (uint8_t rhport, uint8_t ep_addr, uint32_t xferred_bytes, uint8_t result, bool in_isr); + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_DCD_H_ */ + +/// @} diff --git a/src/device/usbd.c b/src/device/usbd.c index fcc623d3..16670b94 100644 --- a/src/device/usbd.c +++ b/src/device/usbd.c @@ -1,1001 +1,1001 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2019 Ha Thach (tinyusb.org) - * - * 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. - * - * This file is part of the TinyUSB stack. - */ - -#include "tusb_option.h" - -#if TUSB_OPT_DEVICE_ENABLED - -#include "tusb.h" -#include "usbd.h" -#include "device/usbd_pvt.h" -#include "dcd.h" - -#ifndef CFG_TUD_TASK_QUEUE_SZ -#define CFG_TUD_TASK_QUEUE_SZ 16 -#endif - -//--------------------------------------------------------------------+ -// Device Data -//--------------------------------------------------------------------+ -typedef struct { - struct TU_ATTR_PACKED - { - volatile uint8_t connected : 1; - volatile uint8_t configured : 1; - volatile uint8_t suspended : 1; - - uint8_t remote_wakeup_en : 1; // enable/disable by host - uint8_t remote_wakeup_support : 1; // configuration descriptor's attribute - uint8_t self_powered : 1; // configuration descriptor's attribute - }; - - uint8_t itf2drv[16]; // map interface number to driver (0xff is invalid) - uint8_t ep2drv[8][2]; // map endpoint to driver ( 0xff is invalid ) - - struct TU_ATTR_PACKED - { - volatile bool busy : 1; - volatile bool stalled : 1; - - // TODO merge ep2drv here, 4-bit should be sufficient - }ep_status[8][2]; -}usbd_device_t; - -static usbd_device_t _usbd_dev; - -// Invalid driver ID in itf2drv[] ep2drv[][] mapping -enum { DRVID_INVALID = 0xFFu }; - -//--------------------------------------------------------------------+ -// Class Driver -//--------------------------------------------------------------------+ -typedef struct { - uint8_t class_code; - - void (* init ) (void); - void (* reset ) (uint8_t rhport); - bool (* open ) (uint8_t rhport, tusb_desc_interface_t const * desc_intf, uint16_t* p_length); - bool (* control_request ) (uint8_t rhport, tusb_control_request_t const * request); - bool (* control_complete ) (uint8_t rhport, tusb_control_request_t const * request); - bool (* xfer_cb ) (uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes); - void (* sof ) (uint8_t rhport); -} usbd_class_driver_t; - -static usbd_class_driver_t const _usbd_driver[] = -{ - #if CFG_TUD_CDC - { - .class_code = TUSB_CLASS_CDC, - .init = cdcd_init, - .reset = cdcd_reset, - .open = cdcd_open, - .control_request = cdcd_control_request, - .control_complete = cdcd_control_complete, - .xfer_cb = cdcd_xfer_cb, - .sof = NULL - }, - #endif - - #if CFG_TUD_MSC - { - .class_code = TUSB_CLASS_MSC, - .init = mscd_init, - .reset = mscd_reset, - .open = mscd_open, - .control_request = mscd_control_request, - .control_complete = mscd_control_complete, - .xfer_cb = mscd_xfer_cb, - .sof = NULL - }, - #endif - - #if CFG_TUD_HID - { - .class_code = TUSB_CLASS_HID, - .init = hidd_init, - .reset = hidd_reset, - .open = hidd_open, - .control_request = hidd_control_request, - .control_complete = hidd_control_complete, - .xfer_cb = hidd_xfer_cb, - .sof = NULL - }, - #endif - - #if CFG_TUD_MIDI - { - .class_code = TUSB_CLASS_AUDIO, - .init = midid_init, - .open = midid_open, - .reset = midid_reset, - .control_request = midid_control_request, - .control_complete = midid_control_complete, - .xfer_cb = midid_xfer_cb, - .sof = NULL - }, - #endif - - #if CFG_TUD_VENDOR - { - .class_code = TUSB_CLASS_VENDOR_SPECIFIC, - .init = vendord_init, - .reset = vendord_reset, - .open = vendord_open, - .control_request = tud_vendor_control_request_cb, - .control_complete = tud_vendor_control_complete_cb, - .xfer_cb = vendord_xfer_cb, - .sof = NULL - }, - #endif - - #if CFG_TUD_USBTMC - // Presently USBTMC is the only defined class with the APP_SPECIFIC class code. - // We maybe need to add subclass codes here, or a callback to ask if a driver can - // handle a particular interface. - { - .class_code = TUD_USBTMC_APP_CLASS, - //.subclass_code = TUD_USBTMC_APP_SUBCLASS - .init = usbtmcd_init_cb, - .reset = usbtmcd_reset_cb, - .open = usbtmcd_open_cb, - .control_request = usbtmcd_control_request_cb, - .control_complete = usbtmcd_control_complete_cb, - .xfer_cb = usbtmcd_xfer_cb, - .sof = NULL - }, - #endif - - #if CFG_TUD_DFU_RT - { - .class_code = TUD_DFU_APP_CLASS, - //.subclass_code = TUD_DFU_APP_SUBCLASS - .init = dfu_rtd_init, - .reset = dfu_rtd_reset, - .open = dfu_rtd_open, - .control_request = dfu_rtd_control_request, - .control_complete = dfu_rtd_control_complete, - .xfer_cb = dfu_rtd_xfer_cb, - .sof = NULL - }, - #endif -}; - -enum { USBD_CLASS_DRIVER_COUNT = TU_ARRAY_SIZE(_usbd_driver) }; - -//--------------------------------------------------------------------+ -// DCD Event -//--------------------------------------------------------------------+ - -// Event queue -// OPT_MODE_DEVICE is used by OS NONE for mutex (disable usb isr) -OSAL_QUEUE_DEF(OPT_MODE_DEVICE, _usbd_qdef, CFG_TUD_TASK_QUEUE_SZ, dcd_event_t); -static osal_queue_t _usbd_q; - -//--------------------------------------------------------------------+ -// Prototypes -//--------------------------------------------------------------------+ -static void mark_interface_endpoint(uint8_t ep2drv[8][2], uint8_t const* p_desc, uint16_t desc_len, uint8_t driver_id); -static bool process_control_request(uint8_t rhport, tusb_control_request_t const * p_request); -static bool process_set_config(uint8_t rhport, uint8_t cfg_num); -static bool process_get_descriptor(uint8_t rhport, tusb_control_request_t const * p_request); - -void usbd_control_reset(void); -void usbd_control_set_request(tusb_control_request_t const *request); -void usbd_control_set_complete_callback( bool (*fp) (uint8_t, tusb_control_request_t const * ) ); -bool usbd_control_xfer_cb (uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes); - - -//--------------------------------------------------------------------+ -// Debugging -//--------------------------------------------------------------------+ -#if CFG_TUSB_DEBUG >= 2 -static char const* const _usbd_event_str[DCD_EVENT_COUNT] = -{ - "INVALID" , - "BUS_RESET" , - "UNPLUGGED" , - "SOF" , - "SUSPEND" , - "RESUME" , - "SETUP_RECEIVED" , - "XFER_COMPLETE" , - "FUNC_CALL" -}; - -// must be same driver order as usbd_class_drivers[] -static char const* const _usbd_driver_str[USBD_CLASS_DRIVER_COUNT] = -{ - #if CFG_TUD_CDC - "CDC", - #endif - #if CFG_TUD_MSC - "MSC", - #endif - #if CFG_TUD_HID - "HID", - #endif - #if CFG_TUD_MIDI - "MIDI", - #endif - #if CFG_TUD_VENDOR - "Vendor", - #endif - #if CFG_TUD_USBTMC - "USBTMC" - #endif -}; - -static char const* const _tusb_std_request_str[] = -{ - "Get Status" , - "Clear Feature" , - "Reserved" , - "Set Feature" , - "Reserved" , - "Set Address" , - "Get Descriptor" , - "Set Descriptor" , - "Get Configuration" , - "Set Configuration" , - "Get Interface" , - "Set Interface" , - "Synch Frame" -}; - -#endif - -//--------------------------------------------------------------------+ -// Application API -//--------------------------------------------------------------------+ -bool tud_mounted(void) -{ - return _usbd_dev.configured; -} - -bool tud_suspended(void) -{ - return _usbd_dev.suspended; -} - -bool tud_remote_wakeup(void) -{ - // only wake up host if this feature is supported and enabled and we are suspended - TU_VERIFY (_usbd_dev.suspended && _usbd_dev.remote_wakeup_support && _usbd_dev.remote_wakeup_en ); - dcd_remote_wakeup(TUD_OPT_RHPORT); - return true; -} - -//--------------------------------------------------------------------+ -// USBD Task -//--------------------------------------------------------------------+ -bool tud_init (void) -{ - TU_LOG2("USBD init\r\n"); - - tu_varclr(&_usbd_dev); - - // Init device queue & task - _usbd_q = osal_queue_create(&_usbd_qdef); - TU_ASSERT(_usbd_q != NULL); - - // Init class drivers - for (uint8_t i = 0; i < USBD_CLASS_DRIVER_COUNT; i++) - { - TU_LOG2("%s init\r\n", _usbd_driver_str[i]); - _usbd_driver[i].init(); - } - - // Init device controller driver - dcd_init(TUD_OPT_RHPORT); - dcd_int_enable(TUD_OPT_RHPORT); - - return true; -} - -static void usbd_reset(uint8_t rhport) -{ - tu_varclr(&_usbd_dev); - - memset(_usbd_dev.itf2drv, DRVID_INVALID, sizeof(_usbd_dev.itf2drv)); // invalid mapping - memset(_usbd_dev.ep2drv , DRVID_INVALID, sizeof(_usbd_dev.ep2drv )); // invalid mapping - - usbd_control_reset(); - - for (uint8_t i = 0; i < USBD_CLASS_DRIVER_COUNT; i++) - { - if ( _usbd_driver[i].reset ) _usbd_driver[i].reset( rhport ); - } -} - -/* USB Device Driver task - * This top level thread manages all device controller event and delegates events to class-specific drivers. - * This should be called periodically within the mainloop or rtos thread. - * - @code - int main(void) - { - application_init(); - tusb_init(); - - while(1) // the mainloop - { - application_code(); - tud_task(); // tinyusb device task - } - } - @endcode - */ -void tud_task (void) -{ - // Skip if stack is not initialized - if ( !tusb_inited() ) return; - - // Loop until there is no more events in the queue - while (1) - { - dcd_event_t event; - - if ( !osal_queue_receive(_usbd_q, &event) ) return; - - TU_LOG2("USBD: event %s\r\n", event.event_id < DCD_EVENT_COUNT ? _usbd_event_str[event.event_id] : "CORRUPTED"); - - switch ( event.event_id ) - { - case DCD_EVENT_BUS_RESET: - usbd_reset(event.rhport); - break; - - case DCD_EVENT_UNPLUGGED: - usbd_reset(event.rhport); - - // invoke callback - if (tud_umount_cb) tud_umount_cb(); - break; - - case DCD_EVENT_SETUP_RECEIVED: - TU_LOG2_MEM(&event.setup_received, 8, 2); - - // Mark as connected after receiving 1st setup packet. - // But it is easier to set it every time instead of wasting time to check then set - _usbd_dev.connected = 1; - - // Process control request - if ( !process_control_request(event.rhport, &event.setup_received) ) - { - TU_LOG2(" Stall EP0\r\n"); - // Failed -> stall both control endpoint IN and OUT - dcd_edpt_stall(event.rhport, 0); - dcd_edpt_stall(event.rhport, 0 | TUSB_DIR_IN_MASK); - } - break; - - case DCD_EVENT_XFER_COMPLETE: - { - // Invoke the class callback associated with the endpoint address - uint8_t const ep_addr = event.xfer_complete.ep_addr; - uint8_t const epnum = tu_edpt_number(ep_addr); - uint8_t const ep_dir = tu_edpt_dir(ep_addr); - - TU_LOG2(" Endpoint: 0x%02X, Bytes: %ld\r\n", ep_addr, event.xfer_complete.len); - - _usbd_dev.ep_status[epnum][ep_dir].busy = false; - - if ( 0 == epnum ) - { - usbd_control_xfer_cb(event.rhport, ep_addr, event.xfer_complete.result, event.xfer_complete.len); - } - else - { - uint8_t const drv_id = _usbd_dev.ep2drv[epnum][ep_dir]; - TU_ASSERT(drv_id < USBD_CLASS_DRIVER_COUNT,); - - TU_LOG2(" %s xfer callback\r\n", _usbd_driver_str[drv_id]); - _usbd_driver[drv_id].xfer_cb(event.rhport, ep_addr, event.xfer_complete.result, event.xfer_complete.len); - } - } - break; - - case DCD_EVENT_SUSPEND: - if (tud_suspend_cb) tud_suspend_cb(_usbd_dev.remote_wakeup_en); - break; - - case DCD_EVENT_RESUME: - if (tud_resume_cb) tud_resume_cb(); - break; - - case DCD_EVENT_SOF: - for ( uint8_t i = 0; i < USBD_CLASS_DRIVER_COUNT; i++ ) - { - if ( _usbd_driver[i].sof ) - { - _usbd_driver[i].sof(event.rhport); - } - } - break; - - case USBD_EVENT_FUNC_CALL: - if ( event.func_call.func ) event.func_call.func(event.func_call.param); - break; - - default: - TU_BREAKPOINT(); - break; - } - } -} - -//--------------------------------------------------------------------+ -// Control Request Parser & Handling -//--------------------------------------------------------------------+ - -// Helper to invoke class driver control request handler -static bool invoke_class_control(uint8_t rhport, uint8_t drvid, tusb_control_request_t const * request) -{ - TU_ASSERT(_usbd_driver[drvid].control_request); - - usbd_control_set_complete_callback(_usbd_driver[drvid].control_complete); - TU_LOG2(" %s control request\r\n", _usbd_driver_str[drvid]); - return _usbd_driver[drvid].control_request(rhport, request); -} - -// This handles the actual request and its response. -// return false will cause its caller to stall control endpoint -static bool process_control_request(uint8_t rhport, tusb_control_request_t const * p_request) -{ - usbd_control_set_complete_callback(NULL); - - TU_ASSERT(p_request->bmRequestType_bit.type < TUSB_REQ_TYPE_INVALID); - - // Vendor request - if ( p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_VENDOR ) - { - TU_VERIFY(tud_vendor_control_request_cb); - - if (tud_vendor_control_complete_cb) usbd_control_set_complete_callback(tud_vendor_control_complete_cb); - return tud_vendor_control_request_cb(rhport, p_request); - } - -#if CFG_TUSB_DEBUG > 1 - if (TUSB_REQ_TYPE_STANDARD == p_request->bmRequestType_bit.type && p_request->bRequest <= TUSB_REQ_SYNCH_FRAME) - { - TU_LOG2(" %s\r\n", _tusb_std_request_str[p_request->bRequest]); - } -#endif - - switch ( p_request->bmRequestType_bit.recipient ) - { - //------------- Device Requests e.g in enumeration -------------// - case TUSB_REQ_RCPT_DEVICE: - if ( TUSB_REQ_TYPE_STANDARD != p_request->bmRequestType_bit.type ) - { - // Non standard request is not supported - TU_BREAKPOINT(); - return false; - } - - switch ( p_request->bRequest ) - { - case TUSB_REQ_SET_ADDRESS: - // Depending on mcu, status phase could be sent either before or after changing device address, - // or even require stack to not response with status at all - // Therefore DCD must take full responsibility to response and include zlp status packet if needed. - usbd_control_set_request(p_request); // set request since DCD has no access to tud_control_status() API - dcd_set_address(rhport, (uint8_t) p_request->wValue); - // skip tud_control_status() - break; - - case TUSB_REQ_GET_CONFIGURATION: - { - uint8_t cfgnum = _usbd_dev.configured ? 1 : 0; - tud_control_xfer(rhport, p_request, &cfgnum, 1); - } - break; - - case TUSB_REQ_SET_CONFIGURATION: - { - uint8_t const cfg_num = (uint8_t) p_request->wValue; - - dcd_set_config(rhport, cfg_num); - - if ( !_usbd_dev.configured && cfg_num ) TU_ASSERT( process_set_config(rhport, cfg_num) ); - - _usbd_dev.configured = cfg_num ? 1 : 0; - - tud_control_status(rhport, p_request); - } - break; - - case TUSB_REQ_GET_DESCRIPTOR: - TU_VERIFY( process_get_descriptor(rhport, p_request) ); - break; - - case TUSB_REQ_SET_FEATURE: - // Only support remote wakeup for device feature - TU_VERIFY(TUSB_REQ_FEATURE_REMOTE_WAKEUP == p_request->wValue); - - // Host may enable remote wake up before suspending especially HID device - _usbd_dev.remote_wakeup_en = true; - tud_control_status(rhport, p_request); - break; - - case TUSB_REQ_CLEAR_FEATURE: - // Only support remote wakeup for device feature - TU_VERIFY(TUSB_REQ_FEATURE_REMOTE_WAKEUP == p_request->wValue); - - // Host may disable remote wake up after resuming - _usbd_dev.remote_wakeup_en = false; - tud_control_status(rhport, p_request); - break; - - case TUSB_REQ_GET_STATUS: - { - // Device status bit mask - // - Bit 0: Self Powered - // - Bit 1: Remote Wakeup enabled - uint16_t status = (_usbd_dev.self_powered ? 1 : 0) | (_usbd_dev.remote_wakeup_en ? 2 : 0); - tud_control_xfer(rhport, p_request, &status, 2); - } - break; - - // Unknown/Unsupported request - default: TU_BREAKPOINT(); return false; - } - break; - - //------------- Class/Interface Specific Request -------------// - case TUSB_REQ_RCPT_INTERFACE: - { - uint8_t const itf = tu_u16_low(p_request->wIndex); - TU_VERIFY(itf < TU_ARRAY_SIZE(_usbd_dev.itf2drv)); - - uint8_t const drvid = _usbd_dev.itf2drv[itf]; - TU_VERIFY(drvid < USBD_CLASS_DRIVER_COUNT); - - if (p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_STANDARD) - { - switch ( p_request->bRequest ) - { - case TUSB_REQ_GET_INTERFACE: - { - // TODO not support alternate interface yet - uint8_t alternate = 0; - tud_control_xfer(rhport, p_request, &alternate, 1); - } - break; - - case TUSB_REQ_SET_INTERFACE: - { - uint8_t const alternate = (uint8_t) p_request->wValue; - - // TODO not support alternate interface yet - TU_ASSERT(alternate == 0); - tud_control_status(rhport, p_request); - } - break; - - default: - // forward to class driver: "STD request to Interface" - // GET HID REPORT DESCRIPTOR falls into this case - TU_VERIFY(invoke_class_control(rhport, drvid, p_request)); - break; - } - }else - { - // forward to class driver: "non-STD request to Interface" - TU_VERIFY(invoke_class_control(rhport, drvid, p_request)); - } - } - break; - - //------------- Endpoint Request -------------// - case TUSB_REQ_RCPT_ENDPOINT: - { - uint8_t const ep_addr = tu_u16_low(p_request->wIndex); - uint8_t const ep_num = tu_edpt_number(ep_addr); - uint8_t const ep_dir = tu_edpt_dir(ep_addr); - - TU_ASSERT(ep_num < TU_ARRAY_SIZE(_usbd_dev.ep2drv) ); - - uint8_t const drvid = _usbd_dev.ep2drv[ep_num][ep_dir]; - - bool ret = false; - - // Handle STD request to endpoint - if ( TUSB_REQ_TYPE_STANDARD == p_request->bmRequestType_bit.type ) - { - // force return true for standard request - ret = true; - - switch ( p_request->bRequest ) - { - case TUSB_REQ_GET_STATUS: - { - uint16_t status = usbd_edpt_stalled(rhport, ep_addr) ? 0x0001 : 0x0000; - tud_control_xfer(rhport, p_request, &status, 2); - } - break; - - case TUSB_REQ_CLEAR_FEATURE: - if ( TUSB_REQ_FEATURE_EDPT_HALT == p_request->wValue ) - { - usbd_edpt_clear_stall(rhport, ep_addr); - } - tud_control_status(rhport, p_request); - break; - - case TUSB_REQ_SET_FEATURE: - if ( TUSB_REQ_FEATURE_EDPT_HALT == p_request->wValue ) - { - usbd_edpt_stall(rhport, ep_addr); - } - tud_control_status(rhport, p_request); - break; - - // Unknown/Unsupported request - default: TU_BREAKPOINT(); return false; - } - } - - if (drvid < 0xFF) { - TU_ASSERT(drvid < USBD_CLASS_DRIVER_COUNT); - - // Some classes such as USBTMC needs to clear/re-init its buffer when receiving CLEAR_FEATURE request - // We will forward all request targeted endpoint to class drivers after - // - For class-type requests: driver is fully responsible to reply to host - // - For std-type requests : driver init/re-init internal variable/buffer only, and - // must not call tud_control_status(), driver's return value will have no effect. - // EP state has already affected (stalled/cleared) - if ( invoke_class_control(rhport, drvid, p_request) ) ret = true; - } - - if ( TUSB_REQ_TYPE_STANDARD == p_request->bmRequestType_bit.type ) - { - // Set complete callback = NULL since it can also stall the request. - usbd_control_set_complete_callback(NULL); - } - - return ret; - } - break; - - // Unknown recipient - default: TU_BREAKPOINT(); return false; - } - - return true; -} - -// Process Set Configure Request -// This function parse configuration descriptor & open drivers accordingly -static bool process_set_config(uint8_t rhport, uint8_t cfg_num) -{ - tusb_desc_configuration_t const * desc_cfg = (tusb_desc_configuration_t const *) tud_descriptor_configuration_cb(cfg_num-1); // index is cfg_num-1 - TU_ASSERT(desc_cfg != NULL && desc_cfg->bDescriptorType == TUSB_DESC_CONFIGURATION); - - // Parse configuration descriptor - _usbd_dev.remote_wakeup_support = (desc_cfg->bmAttributes & TUSB_DESC_CONFIG_ATT_REMOTE_WAKEUP) ? 1 : 0; - _usbd_dev.self_powered = (desc_cfg->bmAttributes & TUSB_DESC_CONFIG_ATT_SELF_POWERED) ? 1 : 0; - - // Parse interface descriptor - uint8_t const * p_desc = ((uint8_t const*) desc_cfg) + sizeof(tusb_desc_configuration_t); - uint8_t const * desc_end = ((uint8_t const*) desc_cfg) + desc_cfg->wTotalLength; - - while( p_desc < desc_end ) - { - // Each interface always starts with Interface or Association descriptor - if ( TUSB_DESC_INTERFACE_ASSOCIATION == tu_desc_type(p_desc) ) - { - p_desc = tu_desc_next(p_desc); // ignore Interface Association - }else - { - TU_ASSERT( TUSB_DESC_INTERFACE == tu_desc_type(p_desc) ); - - tusb_desc_interface_t* desc_itf = (tusb_desc_interface_t*) p_desc; - - // Check if class is supported - uint8_t drv_id; - for (drv_id = 0; drv_id < USBD_CLASS_DRIVER_COUNT; drv_id++) - { - if ( _usbd_driver[drv_id].class_code == desc_itf->bInterfaceClass ) break; - } - TU_ASSERT( drv_id < USBD_CLASS_DRIVER_COUNT ); - - // Interface number must not be used already TODO alternate interface - TU_ASSERT( DRVID_INVALID == _usbd_dev.itf2drv[desc_itf->bInterfaceNumber] ); - _usbd_dev.itf2drv[desc_itf->bInterfaceNumber] = drv_id; - - uint16_t itf_len=0; - TU_LOG2(" %s open\r\n", _usbd_driver_str[drv_id]); - TU_ASSERT( _usbd_driver[drv_id].open(rhport, desc_itf, &itf_len) ); - TU_ASSERT( itf_len >= sizeof(tusb_desc_interface_t) ); - - mark_interface_endpoint(_usbd_dev.ep2drv, p_desc, itf_len, drv_id); - - p_desc += itf_len; // next interface - } - } - - // invoke callback - if (tud_mount_cb) tud_mount_cb(); - - return true; -} - -// Helper marking endpoint of interface belongs to class driver -static void mark_interface_endpoint(uint8_t ep2drv[8][2], uint8_t const* p_desc, uint16_t desc_len, uint8_t driver_id) -{ - uint16_t len = 0; - - while( len < desc_len ) - { - if ( TUSB_DESC_ENDPOINT == tu_desc_type(p_desc) ) - { - uint8_t const ep_addr = ((tusb_desc_endpoint_t const*) p_desc)->bEndpointAddress; - - ep2drv[tu_edpt_number(ep_addr)][tu_edpt_dir(ep_addr)] = driver_id; - } - - len = (uint16_t)(len + tu_desc_len(p_desc)); - p_desc = tu_desc_next(p_desc); - } -} - -// return descriptor's buffer and update desc_len -static bool process_get_descriptor(uint8_t rhport, tusb_control_request_t const * p_request) -{ - tusb_desc_type_t const desc_type = (tusb_desc_type_t) tu_u16_high(p_request->wValue); - uint8_t const desc_index = tu_u16_low( p_request->wValue ); - - switch(desc_type) - { - case TUSB_DESC_DEVICE: - return tud_control_xfer(rhport, p_request, (void*) tud_descriptor_device_cb(), sizeof(tusb_desc_device_t)); - break; - - case TUSB_DESC_BOS: - { - // requested by host if USB > 2.0 ( i.e 2.1 or 3.x ) - if (!tud_descriptor_bos_cb) return false; - - tusb_desc_bos_t const* desc_bos = (tusb_desc_bos_t const*) tud_descriptor_bos_cb(); - uint16_t total_len; - memcpy(&total_len, &desc_bos->wTotalLength, 2); // possibly mis-aligned memory - - return tud_control_xfer(rhport, p_request, (void*) desc_bos, total_len); - } - break; - - case TUSB_DESC_CONFIGURATION: - { - tusb_desc_configuration_t const* desc_config = (tusb_desc_configuration_t const*) tud_descriptor_configuration_cb(desc_index); - TU_ASSERT(desc_config); - - uint16_t total_len; - memcpy(&total_len, &desc_config->wTotalLength, 2); // possibly mis-aligned memory - - return tud_control_xfer(rhport, p_request, (void*) desc_config, total_len); - } - break; - - case TUSB_DESC_STRING: - // String Descriptor always uses the desc set from user - if ( desc_index == 0xEE ) - { - // The 0xEE index string is a Microsoft OS Descriptors. - // https://docs.microsoft.com/en-us/windows-hardware/drivers/usbcon/microsoft-defined-usb-descriptors - return false; - }else - { - uint8_t const* desc_str = (uint8_t const*) tud_descriptor_string_cb(desc_index); - TU_ASSERT(desc_str); - - // first byte of descriptor is its size - return tud_control_xfer(rhport, p_request, (void*) desc_str, desc_str[0]); - } - break; - - case TUSB_DESC_DEVICE_QUALIFIER: - // TODO If not highspeed capable stall this request otherwise - // return the descriptor that could work in highspeed - return false; - break; - - default: return false; - } - - return true; -} - -//--------------------------------------------------------------------+ -// DCD Event Handler -//--------------------------------------------------------------------+ -void dcd_event_handler(dcd_event_t const * event, bool in_isr) -{ - switch (event->event_id) - { - case DCD_EVENT_UNPLUGGED: - _usbd_dev.connected = 0; - _usbd_dev.configured = 0; - _usbd_dev.suspended = 0; - osal_queue_send(_usbd_q, event, in_isr); - break; - - case DCD_EVENT_SOF: - return; // skip SOF event for now - break; - - case DCD_EVENT_SUSPEND: - // NOTE: When plugging/unplugging device, the D+/D- state are unstable and can accidentally meet the - // SUSPEND condition ( Idle for 3ms ). Some MCUs such as SAMD doesn't distinguish suspend vs disconnect as well. - // We will skip handling SUSPEND/RESUME event if not currently connected - if ( _usbd_dev.connected ) - { - _usbd_dev.suspended = 1; - osal_queue_send(_usbd_q, event, in_isr); - } - break; - - case DCD_EVENT_RESUME: - // skip event if not connected (especially required for SAMD) - if ( _usbd_dev.connected ) - { - _usbd_dev.suspended = 0; - osal_queue_send(_usbd_q, event, in_isr); - } - break; - - default: - osal_queue_send(_usbd_q, event, in_isr); - break; - } -} - -void dcd_event_bus_signal (uint8_t rhport, dcd_eventid_t eid, bool in_isr) -{ - dcd_event_t event = { .rhport = rhport, .event_id = eid, }; - dcd_event_handler(&event, in_isr); -} - -void dcd_event_setup_received(uint8_t rhport, uint8_t const * setup, bool in_isr) -{ - dcd_event_t event = { .rhport = rhport, .event_id = DCD_EVENT_SETUP_RECEIVED }; - memcpy(&event.setup_received, setup, 8); - - dcd_event_handler(&event, in_isr); -} - -void dcd_event_xfer_complete (uint8_t rhport, uint8_t ep_addr, uint32_t xferred_bytes, uint8_t result, bool in_isr) -{ - dcd_event_t event = { .rhport = rhport, .event_id = DCD_EVENT_XFER_COMPLETE }; - - event.xfer_complete.ep_addr = ep_addr; - event.xfer_complete.len = xferred_bytes; - event.xfer_complete.result = result; - - dcd_event_handler(&event, in_isr); -} - -//--------------------------------------------------------------------+ -// Helper -//--------------------------------------------------------------------+ - -// Parse consecutive endpoint descriptors (IN & OUT) -bool usbd_open_edpt_pair(uint8_t rhport, uint8_t const* p_desc, uint8_t ep_count, uint8_t xfer_type, uint8_t* ep_out, uint8_t* ep_in) -{ - for(int i=0; ibDescriptorType && xfer_type == desc_ep->bmAttributes.xfer); - TU_ASSERT(dcd_edpt_open(rhport, desc_ep)); - - if ( tu_edpt_dir(desc_ep->bEndpointAddress) == TUSB_DIR_IN ) - { - (*ep_in) = desc_ep->bEndpointAddress; - }else - { - (*ep_out) = desc_ep->bEndpointAddress; - } - - p_desc = tu_desc_next(p_desc); - } - - return true; -} - -// Helper to defer an isr function -void usbd_defer_func(osal_task_func_t func, void* param, bool in_isr) -{ - dcd_event_t event = - { - .rhport = 0, - .event_id = USBD_EVENT_FUNC_CALL, - }; - - event.func_call.func = func; - event.func_call.param = param; - - dcd_event_handler(&event, in_isr); -} - -//--------------------------------------------------------------------+ -// USBD Endpoint API -//--------------------------------------------------------------------+ - -bool usbd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t total_bytes) -{ - uint8_t const epnum = tu_edpt_number(ep_addr); - uint8_t const dir = tu_edpt_dir(ep_addr); - - TU_VERIFY( dcd_edpt_xfer(rhport, ep_addr, buffer, total_bytes) ); - _usbd_dev.ep_status[epnum][dir].busy = true; - - TU_LOG2(" XFER Endpoint: 0x%02X, Bytes: %d\r\n", ep_addr, total_bytes); - - return true; -} - -bool usbd_edpt_busy(uint8_t rhport, uint8_t ep_addr) -{ - (void) rhport; - - uint8_t const epnum = tu_edpt_number(ep_addr); - uint8_t const dir = tu_edpt_dir(ep_addr); - - return _usbd_dev.ep_status[epnum][dir].busy; -} - -void usbd_edpt_stall(uint8_t rhport, uint8_t ep_addr) -{ - uint8_t const epnum = tu_edpt_number(ep_addr); - uint8_t const dir = tu_edpt_dir(ep_addr); - - dcd_edpt_stall(rhport, ep_addr); - _usbd_dev.ep_status[epnum][dir].stalled = true; - _usbd_dev.ep_status[epnum][dir].busy = true; -} - -void usbd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr) -{ - uint8_t const epnum = tu_edpt_number(ep_addr); - uint8_t const dir = tu_edpt_dir(ep_addr); - - dcd_edpt_clear_stall(rhport, ep_addr); - _usbd_dev.ep_status[epnum][dir].stalled = false; - _usbd_dev.ep_status[epnum][dir].busy = false; -} - -bool usbd_edpt_stalled(uint8_t rhport, uint8_t ep_addr) -{ - (void) rhport; - - uint8_t const epnum = tu_edpt_number(ep_addr); - uint8_t const dir = tu_edpt_dir(ep_addr); - - return _usbd_dev.ep_status[epnum][dir].stalled; -} - -#endif +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#include "tusb_option.h" + +#if TUSB_OPT_DEVICE_ENABLED + +#include "tusb.h" +#include "usbd.h" +#include "device/usbd_pvt.h" +#include "dcd.h" + +#ifndef CFG_TUD_TASK_QUEUE_SZ +#define CFG_TUD_TASK_QUEUE_SZ 16 +#endif + +//--------------------------------------------------------------------+ +// Device Data +//--------------------------------------------------------------------+ +typedef struct { + struct TU_ATTR_PACKED + { + volatile uint8_t connected : 1; + volatile uint8_t configured : 1; + volatile uint8_t suspended : 1; + + uint8_t remote_wakeup_en : 1; // enable/disable by host + uint8_t remote_wakeup_support : 1; // configuration descriptor's attribute + uint8_t self_powered : 1; // configuration descriptor's attribute + }; + + uint8_t itf2drv[16]; // map interface number to driver (0xff is invalid) + uint8_t ep2drv[8][2]; // map endpoint to driver ( 0xff is invalid ) + + struct TU_ATTR_PACKED + { + volatile bool busy : 1; + volatile bool stalled : 1; + + // TODO merge ep2drv here, 4-bit should be sufficient + }ep_status[8][2]; +}usbd_device_t; + +static usbd_device_t _usbd_dev; + +// Invalid driver ID in itf2drv[] ep2drv[][] mapping +enum { DRVID_INVALID = 0xFFu }; + +//--------------------------------------------------------------------+ +// Class Driver +//--------------------------------------------------------------------+ +typedef struct { + uint8_t class_code; + + void (* init ) (void); + void (* reset ) (uint8_t rhport); + bool (* open ) (uint8_t rhport, tusb_desc_interface_t const * desc_intf, uint16_t* p_length); + bool (* control_request ) (uint8_t rhport, tusb_control_request_t const * request); + bool (* control_complete ) (uint8_t rhport, tusb_control_request_t const * request); + bool (* xfer_cb ) (uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes); + void (* sof ) (uint8_t rhport); +} usbd_class_driver_t; + +static usbd_class_driver_t const _usbd_driver[] = +{ + #if CFG_TUD_CDC + { + .class_code = TUSB_CLASS_CDC, + .init = cdcd_init, + .reset = cdcd_reset, + .open = cdcd_open, + .control_request = cdcd_control_request, + .control_complete = cdcd_control_complete, + .xfer_cb = cdcd_xfer_cb, + .sof = NULL + }, + #endif + + #if CFG_TUD_MSC + { + .class_code = TUSB_CLASS_MSC, + .init = mscd_init, + .reset = mscd_reset, + .open = mscd_open, + .control_request = mscd_control_request, + .control_complete = mscd_control_complete, + .xfer_cb = mscd_xfer_cb, + .sof = NULL + }, + #endif + + #if CFG_TUD_HID + { + .class_code = TUSB_CLASS_HID, + .init = hidd_init, + .reset = hidd_reset, + .open = hidd_open, + .control_request = hidd_control_request, + .control_complete = hidd_control_complete, + .xfer_cb = hidd_xfer_cb, + .sof = NULL + }, + #endif + + #if CFG_TUD_MIDI + { + .class_code = TUSB_CLASS_AUDIO, + .init = midid_init, + .open = midid_open, + .reset = midid_reset, + .control_request = midid_control_request, + .control_complete = midid_control_complete, + .xfer_cb = midid_xfer_cb, + .sof = NULL + }, + #endif + + #if CFG_TUD_VENDOR + { + .class_code = TUSB_CLASS_VENDOR_SPECIFIC, + .init = vendord_init, + .reset = vendord_reset, + .open = vendord_open, + .control_request = tud_vendor_control_request_cb, + .control_complete = tud_vendor_control_complete_cb, + .xfer_cb = vendord_xfer_cb, + .sof = NULL + }, + #endif + + #if CFG_TUD_USBTMC + // Presently USBTMC is the only defined class with the APP_SPECIFIC class code. + // We maybe need to add subclass codes here, or a callback to ask if a driver can + // handle a particular interface. + { + .class_code = TUD_USBTMC_APP_CLASS, + //.subclass_code = TUD_USBTMC_APP_SUBCLASS + .init = usbtmcd_init_cb, + .reset = usbtmcd_reset_cb, + .open = usbtmcd_open_cb, + .control_request = usbtmcd_control_request_cb, + .control_complete = usbtmcd_control_complete_cb, + .xfer_cb = usbtmcd_xfer_cb, + .sof = NULL + }, + #endif + + #if CFG_TUD_DFU_RT + { + .class_code = TUD_DFU_APP_CLASS, + //.subclass_code = TUD_DFU_APP_SUBCLASS + .init = dfu_rtd_init, + .reset = dfu_rtd_reset, + .open = dfu_rtd_open, + .control_request = dfu_rtd_control_request, + .control_complete = dfu_rtd_control_complete, + .xfer_cb = dfu_rtd_xfer_cb, + .sof = NULL + }, + #endif +}; + +enum { USBD_CLASS_DRIVER_COUNT = TU_ARRAY_SIZE(_usbd_driver) }; + +//--------------------------------------------------------------------+ +// DCD Event +//--------------------------------------------------------------------+ + +// Event queue +// OPT_MODE_DEVICE is used by OS NONE for mutex (disable usb isr) +OSAL_QUEUE_DEF(OPT_MODE_DEVICE, _usbd_qdef, CFG_TUD_TASK_QUEUE_SZ, dcd_event_t); +static osal_queue_t _usbd_q; + +//--------------------------------------------------------------------+ +// Prototypes +//--------------------------------------------------------------------+ +static void mark_interface_endpoint(uint8_t ep2drv[8][2], uint8_t const* p_desc, uint16_t desc_len, uint8_t driver_id); +static bool process_control_request(uint8_t rhport, tusb_control_request_t const * p_request); +static bool process_set_config(uint8_t rhport, uint8_t cfg_num); +static bool process_get_descriptor(uint8_t rhport, tusb_control_request_t const * p_request); + +void usbd_control_reset(void); +void usbd_control_set_request(tusb_control_request_t const *request); +void usbd_control_set_complete_callback( bool (*fp) (uint8_t, tusb_control_request_t const * ) ); +bool usbd_control_xfer_cb (uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes); + + +//--------------------------------------------------------------------+ +// Debugging +//--------------------------------------------------------------------+ +#if CFG_TUSB_DEBUG >= 2 +static char const* const _usbd_event_str[DCD_EVENT_COUNT] = +{ + "INVALID" , + "BUS_RESET" , + "UNPLUGGED" , + "SOF" , + "SUSPEND" , + "RESUME" , + "SETUP_RECEIVED" , + "XFER_COMPLETE" , + "FUNC_CALL" +}; + +// must be same driver order as usbd_class_drivers[] +static char const* const _usbd_driver_str[USBD_CLASS_DRIVER_COUNT] = +{ + #if CFG_TUD_CDC + "CDC", + #endif + #if CFG_TUD_MSC + "MSC", + #endif + #if CFG_TUD_HID + "HID", + #endif + #if CFG_TUD_MIDI + "MIDI", + #endif + #if CFG_TUD_VENDOR + "Vendor", + #endif + #if CFG_TUD_USBTMC + "USBTMC" + #endif +}; + +static char const* const _tusb_std_request_str[] = +{ + "Get Status" , + "Clear Feature" , + "Reserved" , + "Set Feature" , + "Reserved" , + "Set Address" , + "Get Descriptor" , + "Set Descriptor" , + "Get Configuration" , + "Set Configuration" , + "Get Interface" , + "Set Interface" , + "Synch Frame" +}; + +#endif + +//--------------------------------------------------------------------+ +// Application API +//--------------------------------------------------------------------+ +bool tud_mounted(void) +{ + return _usbd_dev.configured; +} + +bool tud_suspended(void) +{ + return _usbd_dev.suspended; +} + +bool tud_remote_wakeup(void) +{ + // only wake up host if this feature is supported and enabled and we are suspended + TU_VERIFY (_usbd_dev.suspended && _usbd_dev.remote_wakeup_support && _usbd_dev.remote_wakeup_en ); + dcd_remote_wakeup(TUD_OPT_RHPORT); + return true; +} + +//--------------------------------------------------------------------+ +// USBD Task +//--------------------------------------------------------------------+ +bool tud_init (void) +{ + TU_LOG2("USBD init\r\n"); + + tu_varclr(&_usbd_dev); + + // Init device queue & task + _usbd_q = osal_queue_create(&_usbd_qdef); + TU_ASSERT(_usbd_q != NULL); + + // Init class drivers + for (uint8_t i = 0; i < USBD_CLASS_DRIVER_COUNT; i++) + { + TU_LOG2("%s init\r\n", _usbd_driver_str[i]); + _usbd_driver[i].init(); + } + + // Init device controller driver + dcd_init(TUD_OPT_RHPORT); + dcd_int_enable(TUD_OPT_RHPORT); + + return true; +} + +static void usbd_reset(uint8_t rhport) +{ + tu_varclr(&_usbd_dev); + + memset(_usbd_dev.itf2drv, DRVID_INVALID, sizeof(_usbd_dev.itf2drv)); // invalid mapping + memset(_usbd_dev.ep2drv , DRVID_INVALID, sizeof(_usbd_dev.ep2drv )); // invalid mapping + + usbd_control_reset(); + + for (uint8_t i = 0; i < USBD_CLASS_DRIVER_COUNT; i++) + { + if ( _usbd_driver[i].reset ) _usbd_driver[i].reset( rhport ); + } +} + +/* USB Device Driver task + * This top level thread manages all device controller event and delegates events to class-specific drivers. + * This should be called periodically within the mainloop or rtos thread. + * + @code + int main(void) + { + application_init(); + tusb_init(); + + while(1) // the mainloop + { + application_code(); + tud_task(); // tinyusb device task + } + } + @endcode + */ +void tud_task (void) +{ + // Skip if stack is not initialized + if ( !tusb_inited() ) return; + + // Loop until there is no more events in the queue + while (1) + { + dcd_event_t event; + + if ( !osal_queue_receive(_usbd_q, &event) ) return; + + TU_LOG2("USBD: event %s\r\n", event.event_id < DCD_EVENT_COUNT ? _usbd_event_str[event.event_id] : "CORRUPTED"); + + switch ( event.event_id ) + { + case DCD_EVENT_BUS_RESET: + usbd_reset(event.rhport); + break; + + case DCD_EVENT_UNPLUGGED: + usbd_reset(event.rhport); + + // invoke callback + if (tud_umount_cb) tud_umount_cb(); + break; + + case DCD_EVENT_SETUP_RECEIVED: + TU_LOG2_MEM(&event.setup_received, 8, 2); + + // Mark as connected after receiving 1st setup packet. + // But it is easier to set it every time instead of wasting time to check then set + _usbd_dev.connected = 1; + + // Process control request + if ( !process_control_request(event.rhport, &event.setup_received) ) + { + TU_LOG2(" Stall EP0\r\n"); + // Failed -> stall both control endpoint IN and OUT + dcd_edpt_stall(event.rhport, 0); + dcd_edpt_stall(event.rhport, 0 | TUSB_DIR_IN_MASK); + } + break; + + case DCD_EVENT_XFER_COMPLETE: + { + // Invoke the class callback associated with the endpoint address + uint8_t const ep_addr = event.xfer_complete.ep_addr; + uint8_t const epnum = tu_edpt_number(ep_addr); + uint8_t const ep_dir = tu_edpt_dir(ep_addr); + + TU_LOG2(" Endpoint: 0x%02X, Bytes: %ld\r\n", ep_addr, event.xfer_complete.len); + + _usbd_dev.ep_status[epnum][ep_dir].busy = false; + + if ( 0 == epnum ) + { + usbd_control_xfer_cb(event.rhport, ep_addr, event.xfer_complete.result, event.xfer_complete.len); + } + else + { + uint8_t const drv_id = _usbd_dev.ep2drv[epnum][ep_dir]; + TU_ASSERT(drv_id < USBD_CLASS_DRIVER_COUNT,); + + TU_LOG2(" %s xfer callback\r\n", _usbd_driver_str[drv_id]); + _usbd_driver[drv_id].xfer_cb(event.rhport, ep_addr, event.xfer_complete.result, event.xfer_complete.len); + } + } + break; + + case DCD_EVENT_SUSPEND: + if (tud_suspend_cb) tud_suspend_cb(_usbd_dev.remote_wakeup_en); + break; + + case DCD_EVENT_RESUME: + if (tud_resume_cb) tud_resume_cb(); + break; + + case DCD_EVENT_SOF: + for ( uint8_t i = 0; i < USBD_CLASS_DRIVER_COUNT; i++ ) + { + if ( _usbd_driver[i].sof ) + { + _usbd_driver[i].sof(event.rhport); + } + } + break; + + case USBD_EVENT_FUNC_CALL: + if ( event.func_call.func ) event.func_call.func(event.func_call.param); + break; + + default: + TU_BREAKPOINT(); + break; + } + } +} + +//--------------------------------------------------------------------+ +// Control Request Parser & Handling +//--------------------------------------------------------------------+ + +// Helper to invoke class driver control request handler +static bool invoke_class_control(uint8_t rhport, uint8_t drvid, tusb_control_request_t const * request) +{ + TU_ASSERT(_usbd_driver[drvid].control_request); + + usbd_control_set_complete_callback(_usbd_driver[drvid].control_complete); + TU_LOG2(" %s control request\r\n", _usbd_driver_str[drvid]); + return _usbd_driver[drvid].control_request(rhport, request); +} + +// This handles the actual request and its response. +// return false will cause its caller to stall control endpoint +static bool process_control_request(uint8_t rhport, tusb_control_request_t const * p_request) +{ + usbd_control_set_complete_callback(NULL); + + TU_ASSERT(p_request->bmRequestType_bit.type < TUSB_REQ_TYPE_INVALID); + + // Vendor request + if ( p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_VENDOR ) + { + TU_VERIFY(tud_vendor_control_request_cb); + + if (tud_vendor_control_complete_cb) usbd_control_set_complete_callback(tud_vendor_control_complete_cb); + return tud_vendor_control_request_cb(rhport, p_request); + } + +#if CFG_TUSB_DEBUG > 1 + if (TUSB_REQ_TYPE_STANDARD == p_request->bmRequestType_bit.type && p_request->bRequest <= TUSB_REQ_SYNCH_FRAME) + { + TU_LOG2(" %s\r\n", _tusb_std_request_str[p_request->bRequest]); + } +#endif + + switch ( p_request->bmRequestType_bit.recipient ) + { + //------------- Device Requests e.g in enumeration -------------// + case TUSB_REQ_RCPT_DEVICE: + if ( TUSB_REQ_TYPE_STANDARD != p_request->bmRequestType_bit.type ) + { + // Non standard request is not supported + TU_BREAKPOINT(); + return false; + } + + switch ( p_request->bRequest ) + { + case TUSB_REQ_SET_ADDRESS: + // Depending on mcu, status phase could be sent either before or after changing device address, + // or even require stack to not response with status at all + // Therefore DCD must take full responsibility to response and include zlp status packet if needed. + usbd_control_set_request(p_request); // set request since DCD has no access to tud_control_status() API + dcd_set_address(rhport, (uint8_t) p_request->wValue); + // skip tud_control_status() + break; + + case TUSB_REQ_GET_CONFIGURATION: + { + uint8_t cfgnum = _usbd_dev.configured ? 1 : 0; + tud_control_xfer(rhport, p_request, &cfgnum, 1); + } + break; + + case TUSB_REQ_SET_CONFIGURATION: + { + uint8_t const cfg_num = (uint8_t) p_request->wValue; + + dcd_set_config(rhport, cfg_num); + + if ( !_usbd_dev.configured && cfg_num ) TU_ASSERT( process_set_config(rhport, cfg_num) ); + + _usbd_dev.configured = cfg_num ? 1 : 0; + + tud_control_status(rhport, p_request); + } + break; + + case TUSB_REQ_GET_DESCRIPTOR: + TU_VERIFY( process_get_descriptor(rhport, p_request) ); + break; + + case TUSB_REQ_SET_FEATURE: + // Only support remote wakeup for device feature + TU_VERIFY(TUSB_REQ_FEATURE_REMOTE_WAKEUP == p_request->wValue); + + // Host may enable remote wake up before suspending especially HID device + _usbd_dev.remote_wakeup_en = true; + tud_control_status(rhport, p_request); + break; + + case TUSB_REQ_CLEAR_FEATURE: + // Only support remote wakeup for device feature + TU_VERIFY(TUSB_REQ_FEATURE_REMOTE_WAKEUP == p_request->wValue); + + // Host may disable remote wake up after resuming + _usbd_dev.remote_wakeup_en = false; + tud_control_status(rhport, p_request); + break; + + case TUSB_REQ_GET_STATUS: + { + // Device status bit mask + // - Bit 0: Self Powered + // - Bit 1: Remote Wakeup enabled + uint16_t status = (_usbd_dev.self_powered ? 1 : 0) | (_usbd_dev.remote_wakeup_en ? 2 : 0); + tud_control_xfer(rhport, p_request, &status, 2); + } + break; + + // Unknown/Unsupported request + default: TU_BREAKPOINT(); return false; + } + break; + + //------------- Class/Interface Specific Request -------------// + case TUSB_REQ_RCPT_INTERFACE: + { + uint8_t const itf = tu_u16_low(p_request->wIndex); + TU_VERIFY(itf < TU_ARRAY_SIZE(_usbd_dev.itf2drv)); + + uint8_t const drvid = _usbd_dev.itf2drv[itf]; + TU_VERIFY(drvid < USBD_CLASS_DRIVER_COUNT); + + if (p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_STANDARD) + { + switch ( p_request->bRequest ) + { + case TUSB_REQ_GET_INTERFACE: + { + // TODO not support alternate interface yet + uint8_t alternate = 0; + tud_control_xfer(rhport, p_request, &alternate, 1); + } + break; + + case TUSB_REQ_SET_INTERFACE: + { + uint8_t const alternate = (uint8_t) p_request->wValue; + + // TODO not support alternate interface yet + TU_ASSERT(alternate == 0); + tud_control_status(rhport, p_request); + } + break; + + default: + // forward to class driver: "STD request to Interface" + // GET HID REPORT DESCRIPTOR falls into this case + TU_VERIFY(invoke_class_control(rhport, drvid, p_request)); + break; + } + }else + { + // forward to class driver: "non-STD request to Interface" + TU_VERIFY(invoke_class_control(rhport, drvid, p_request)); + } + } + break; + + //------------- Endpoint Request -------------// + case TUSB_REQ_RCPT_ENDPOINT: + { + uint8_t const ep_addr = tu_u16_low(p_request->wIndex); + uint8_t const ep_num = tu_edpt_number(ep_addr); + uint8_t const ep_dir = tu_edpt_dir(ep_addr); + + TU_ASSERT(ep_num < TU_ARRAY_SIZE(_usbd_dev.ep2drv) ); + + uint8_t const drvid = _usbd_dev.ep2drv[ep_num][ep_dir]; + + bool ret = false; + + // Handle STD request to endpoint + if ( TUSB_REQ_TYPE_STANDARD == p_request->bmRequestType_bit.type ) + { + // force return true for standard request + ret = true; + + switch ( p_request->bRequest ) + { + case TUSB_REQ_GET_STATUS: + { + uint16_t status = usbd_edpt_stalled(rhport, ep_addr) ? 0x0001 : 0x0000; + tud_control_xfer(rhport, p_request, &status, 2); + } + break; + + case TUSB_REQ_CLEAR_FEATURE: + if ( TUSB_REQ_FEATURE_EDPT_HALT == p_request->wValue ) + { + usbd_edpt_clear_stall(rhport, ep_addr); + } + tud_control_status(rhport, p_request); + break; + + case TUSB_REQ_SET_FEATURE: + if ( TUSB_REQ_FEATURE_EDPT_HALT == p_request->wValue ) + { + usbd_edpt_stall(rhport, ep_addr); + } + tud_control_status(rhport, p_request); + break; + + // Unknown/Unsupported request + default: TU_BREAKPOINT(); return false; + } + } + + if (drvid < 0xFF) { + TU_ASSERT(drvid < USBD_CLASS_DRIVER_COUNT); + + // Some classes such as USBTMC needs to clear/re-init its buffer when receiving CLEAR_FEATURE request + // We will forward all request targeted endpoint to class drivers after + // - For class-type requests: driver is fully responsible to reply to host + // - For std-type requests : driver init/re-init internal variable/buffer only, and + // must not call tud_control_status(), driver's return value will have no effect. + // EP state has already affected (stalled/cleared) + if ( invoke_class_control(rhport, drvid, p_request) ) ret = true; + } + + if ( TUSB_REQ_TYPE_STANDARD == p_request->bmRequestType_bit.type ) + { + // Set complete callback = NULL since it can also stall the request. + usbd_control_set_complete_callback(NULL); + } + + return ret; + } + break; + + // Unknown recipient + default: TU_BREAKPOINT(); return false; + } + + return true; +} + +// Process Set Configure Request +// This function parse configuration descriptor & open drivers accordingly +static bool process_set_config(uint8_t rhport, uint8_t cfg_num) +{ + tusb_desc_configuration_t const * desc_cfg = (tusb_desc_configuration_t const *) tud_descriptor_configuration_cb(cfg_num-1); // index is cfg_num-1 + TU_ASSERT(desc_cfg != NULL && desc_cfg->bDescriptorType == TUSB_DESC_CONFIGURATION); + + // Parse configuration descriptor + _usbd_dev.remote_wakeup_support = (desc_cfg->bmAttributes & TUSB_DESC_CONFIG_ATT_REMOTE_WAKEUP) ? 1 : 0; + _usbd_dev.self_powered = (desc_cfg->bmAttributes & TUSB_DESC_CONFIG_ATT_SELF_POWERED) ? 1 : 0; + + // Parse interface descriptor + uint8_t const * p_desc = ((uint8_t const*) desc_cfg) + sizeof(tusb_desc_configuration_t); + uint8_t const * desc_end = ((uint8_t const*) desc_cfg) + desc_cfg->wTotalLength; + + while( p_desc < desc_end ) + { + // Each interface always starts with Interface or Association descriptor + if ( TUSB_DESC_INTERFACE_ASSOCIATION == tu_desc_type(p_desc) ) + { + p_desc = tu_desc_next(p_desc); // ignore Interface Association + }else + { + TU_ASSERT( TUSB_DESC_INTERFACE == tu_desc_type(p_desc) ); + + tusb_desc_interface_t* desc_itf = (tusb_desc_interface_t*) p_desc; + + // Check if class is supported + uint8_t drv_id; + for (drv_id = 0; drv_id < USBD_CLASS_DRIVER_COUNT; drv_id++) + { + if ( _usbd_driver[drv_id].class_code == desc_itf->bInterfaceClass ) break; + } + TU_ASSERT( drv_id < USBD_CLASS_DRIVER_COUNT ); + + // Interface number must not be used already TODO alternate interface + TU_ASSERT( DRVID_INVALID == _usbd_dev.itf2drv[desc_itf->bInterfaceNumber] ); + _usbd_dev.itf2drv[desc_itf->bInterfaceNumber] = drv_id; + + uint16_t itf_len=0; + TU_LOG2(" %s open\r\n", _usbd_driver_str[drv_id]); + TU_ASSERT( _usbd_driver[drv_id].open(rhport, desc_itf, &itf_len) ); + TU_ASSERT( itf_len >= sizeof(tusb_desc_interface_t) ); + + mark_interface_endpoint(_usbd_dev.ep2drv, p_desc, itf_len, drv_id); + + p_desc += itf_len; // next interface + } + } + + // invoke callback + if (tud_mount_cb) tud_mount_cb(); + + return true; +} + +// Helper marking endpoint of interface belongs to class driver +static void mark_interface_endpoint(uint8_t ep2drv[8][2], uint8_t const* p_desc, uint16_t desc_len, uint8_t driver_id) +{ + uint16_t len = 0; + + while( len < desc_len ) + { + if ( TUSB_DESC_ENDPOINT == tu_desc_type(p_desc) ) + { + uint8_t const ep_addr = ((tusb_desc_endpoint_t const*) p_desc)->bEndpointAddress; + + ep2drv[tu_edpt_number(ep_addr)][tu_edpt_dir(ep_addr)] = driver_id; + } + + len = (uint16_t)(len + tu_desc_len(p_desc)); + p_desc = tu_desc_next(p_desc); + } +} + +// return descriptor's buffer and update desc_len +static bool process_get_descriptor(uint8_t rhport, tusb_control_request_t const * p_request) +{ + tusb_desc_type_t const desc_type = (tusb_desc_type_t) tu_u16_high(p_request->wValue); + uint8_t const desc_index = tu_u16_low( p_request->wValue ); + + switch(desc_type) + { + case TUSB_DESC_DEVICE: + return tud_control_xfer(rhport, p_request, (void*) tud_descriptor_device_cb(), sizeof(tusb_desc_device_t)); + break; + + case TUSB_DESC_BOS: + { + // requested by host if USB > 2.0 ( i.e 2.1 or 3.x ) + if (!tud_descriptor_bos_cb) return false; + + tusb_desc_bos_t const* desc_bos = (tusb_desc_bos_t const*) tud_descriptor_bos_cb(); + uint16_t total_len; + memcpy(&total_len, &desc_bos->wTotalLength, 2); // possibly mis-aligned memory + + return tud_control_xfer(rhport, p_request, (void*) desc_bos, total_len); + } + break; + + case TUSB_DESC_CONFIGURATION: + { + tusb_desc_configuration_t const* desc_config = (tusb_desc_configuration_t const*) tud_descriptor_configuration_cb(desc_index); + TU_ASSERT(desc_config); + + uint16_t total_len; + memcpy(&total_len, &desc_config->wTotalLength, 2); // possibly mis-aligned memory + + return tud_control_xfer(rhport, p_request, (void*) desc_config, total_len); + } + break; + + case TUSB_DESC_STRING: + // String Descriptor always uses the desc set from user + if ( desc_index == 0xEE ) + { + // The 0xEE index string is a Microsoft OS Descriptors. + // https://docs.microsoft.com/en-us/windows-hardware/drivers/usbcon/microsoft-defined-usb-descriptors + return false; + }else + { + uint8_t const* desc_str = (uint8_t const*) tud_descriptor_string_cb(desc_index); + TU_ASSERT(desc_str); + + // first byte of descriptor is its size + return tud_control_xfer(rhport, p_request, (void*) desc_str, desc_str[0]); + } + break; + + case TUSB_DESC_DEVICE_QUALIFIER: + // TODO If not highspeed capable stall this request otherwise + // return the descriptor that could work in highspeed + return false; + break; + + default: return false; + } + + return true; +} + +//--------------------------------------------------------------------+ +// DCD Event Handler +//--------------------------------------------------------------------+ +void dcd_event_handler(dcd_event_t const * event, bool in_isr) +{ + switch (event->event_id) + { + case DCD_EVENT_UNPLUGGED: + _usbd_dev.connected = 0; + _usbd_dev.configured = 0; + _usbd_dev.suspended = 0; + osal_queue_send(_usbd_q, event, in_isr); + break; + + case DCD_EVENT_SOF: + return; // skip SOF event for now + break; + + case DCD_EVENT_SUSPEND: + // NOTE: When plugging/unplugging device, the D+/D- state are unstable and can accidentally meet the + // SUSPEND condition ( Idle for 3ms ). Some MCUs such as SAMD doesn't distinguish suspend vs disconnect as well. + // We will skip handling SUSPEND/RESUME event if not currently connected + if ( _usbd_dev.connected ) + { + _usbd_dev.suspended = 1; + osal_queue_send(_usbd_q, event, in_isr); + } + break; + + case DCD_EVENT_RESUME: + // skip event if not connected (especially required for SAMD) + if ( _usbd_dev.connected ) + { + _usbd_dev.suspended = 0; + osal_queue_send(_usbd_q, event, in_isr); + } + break; + + default: + osal_queue_send(_usbd_q, event, in_isr); + break; + } +} + +void dcd_event_bus_signal (uint8_t rhport, dcd_eventid_t eid, bool in_isr) +{ + dcd_event_t event = { .rhport = rhport, .event_id = eid, }; + dcd_event_handler(&event, in_isr); +} + +void dcd_event_setup_received(uint8_t rhport, uint8_t const * setup, bool in_isr) +{ + dcd_event_t event = { .rhport = rhport, .event_id = DCD_EVENT_SETUP_RECEIVED }; + memcpy(&event.setup_received, setup, 8); + + dcd_event_handler(&event, in_isr); +} + +void dcd_event_xfer_complete (uint8_t rhport, uint8_t ep_addr, uint32_t xferred_bytes, uint8_t result, bool in_isr) +{ + dcd_event_t event = { .rhport = rhport, .event_id = DCD_EVENT_XFER_COMPLETE }; + + event.xfer_complete.ep_addr = ep_addr; + event.xfer_complete.len = xferred_bytes; + event.xfer_complete.result = result; + + dcd_event_handler(&event, in_isr); +} + +//--------------------------------------------------------------------+ +// Helper +//--------------------------------------------------------------------+ + +// Parse consecutive endpoint descriptors (IN & OUT) +bool usbd_open_edpt_pair(uint8_t rhport, uint8_t const* p_desc, uint8_t ep_count, uint8_t xfer_type, uint8_t* ep_out, uint8_t* ep_in) +{ + for(int i=0; ibDescriptorType && xfer_type == desc_ep->bmAttributes.xfer); + TU_ASSERT(dcd_edpt_open(rhport, desc_ep)); + + if ( tu_edpt_dir(desc_ep->bEndpointAddress) == TUSB_DIR_IN ) + { + (*ep_in) = desc_ep->bEndpointAddress; + }else + { + (*ep_out) = desc_ep->bEndpointAddress; + } + + p_desc = tu_desc_next(p_desc); + } + + return true; +} + +// Helper to defer an isr function +void usbd_defer_func(osal_task_func_t func, void* param, bool in_isr) +{ + dcd_event_t event = + { + .rhport = 0, + .event_id = USBD_EVENT_FUNC_CALL, + }; + + event.func_call.func = func; + event.func_call.param = param; + + dcd_event_handler(&event, in_isr); +} + +//--------------------------------------------------------------------+ +// USBD Endpoint API +//--------------------------------------------------------------------+ + +bool usbd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t total_bytes) +{ + uint8_t const epnum = tu_edpt_number(ep_addr); + uint8_t const dir = tu_edpt_dir(ep_addr); + + TU_VERIFY( dcd_edpt_xfer(rhport, ep_addr, buffer, total_bytes) ); + _usbd_dev.ep_status[epnum][dir].busy = true; + + TU_LOG2(" XFER Endpoint: 0x%02X, Bytes: %d\r\n", ep_addr, total_bytes); + + return true; +} + +bool usbd_edpt_busy(uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + + uint8_t const epnum = tu_edpt_number(ep_addr); + uint8_t const dir = tu_edpt_dir(ep_addr); + + return _usbd_dev.ep_status[epnum][dir].busy; +} + +void usbd_edpt_stall(uint8_t rhport, uint8_t ep_addr) +{ + uint8_t const epnum = tu_edpt_number(ep_addr); + uint8_t const dir = tu_edpt_dir(ep_addr); + + dcd_edpt_stall(rhport, ep_addr); + _usbd_dev.ep_status[epnum][dir].stalled = true; + _usbd_dev.ep_status[epnum][dir].busy = true; +} + +void usbd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr) +{ + uint8_t const epnum = tu_edpt_number(ep_addr); + uint8_t const dir = tu_edpt_dir(ep_addr); + + dcd_edpt_clear_stall(rhport, ep_addr); + _usbd_dev.ep_status[epnum][dir].stalled = false; + _usbd_dev.ep_status[epnum][dir].busy = false; +} + +bool usbd_edpt_stalled(uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + + uint8_t const epnum = tu_edpt_number(ep_addr); + uint8_t const dir = tu_edpt_dir(ep_addr); + + return _usbd_dev.ep_status[epnum][dir].stalled; +} + +#endif diff --git a/src/device/usbd.h b/src/device/usbd.h index e685686a..847251ca 100644 --- a/src/device/usbd.h +++ b/src/device/usbd.h @@ -1,335 +1,335 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2019 Ha Thach (tinyusb.org) - * - * 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. - * - * This file is part of the TinyUSB stack. - */ - -/** \ingroup group_usbd - * @{ */ - -#ifndef _TUSB_USBD_H_ -#define _TUSB_USBD_H_ - -#ifdef __cplusplus - extern "C" { -#endif - -#include "common/tusb_common.h" -#include "dcd.h" - -//--------------------------------------------------------------------+ -// Application API -//--------------------------------------------------------------------+ - -// Init device stack -bool tud_init (void); - -// Task function should be called in main/rtos loop -void tud_task (void); - -// Interrupt handler, name alias to DCD -#define tud_isr dcd_isr - -// Check if device is connected and configured -bool tud_mounted(void); - -// Check if device is suspended -bool tud_suspended(void); - -// Check if device is ready to transfer -static inline bool tud_ready(void) -{ - return tud_mounted() && !tud_suspended(); -} - -// Remote wake up host, only if suspended and enabled by host -bool tud_remote_wakeup(void); - -// Carry out Data and Status stage of control transfer -// - If len = 0, it is equivalent to sending status only -// - If len > wLength : it will be truncated -bool tud_control_xfer(uint8_t rhport, tusb_control_request_t const * request, void* buffer, uint16_t len); - -// Send STATUS (zero length) packet -bool tud_control_status(uint8_t rhport, tusb_control_request_t const * request); - -//--------------------------------------------------------------------+ -// Application Callbacks (WEAK is optional) -//--------------------------------------------------------------------+ - -// Invoked when received GET DEVICE DESCRIPTOR request -// Application return pointer to descriptor -uint8_t const * tud_descriptor_device_cb(void); - -// Invoked when received GET BOS DESCRIPTOR request -// Application return pointer to descriptor -TU_ATTR_WEAK uint8_t const * tud_descriptor_bos_cb(void); - -// Invoked when received GET CONFIGURATION DESCRIPTOR request -// Application return pointer to descriptor, whose contents must exist long enough for transfer to complete -uint8_t const * tud_descriptor_configuration_cb(uint8_t index); - -// Invoked when received GET STRING DESCRIPTOR request -// Application return pointer to descriptor, whose contents must exist long enough for transfer to complete -uint16_t const* tud_descriptor_string_cb(uint8_t index); - -// Invoked when device is mounted (configured) -TU_ATTR_WEAK void tud_mount_cb(void); - -// Invoked when device is unmounted -TU_ATTR_WEAK void tud_umount_cb(void); - -// Invoked when usb bus is suspended -// Within 7ms, device must draw an average of current less than 2.5 mA from bus -TU_ATTR_WEAK void tud_suspend_cb(bool remote_wakeup_en); - -// Invoked when usb bus is resumed -TU_ATTR_WEAK void tud_resume_cb(void); - -// Invoked when received control request with VENDOR TYPE -TU_ATTR_WEAK bool tud_vendor_control_request_cb(uint8_t rhport, tusb_control_request_t const * request); -TU_ATTR_WEAK bool tud_vendor_control_complete_cb(uint8_t rhport, tusb_control_request_t const * request); - - -//--------------------------------------------------------------------+ -// Binary Device Object Store (BOS) Descriptor Templates -//--------------------------------------------------------------------+ - -#define TUD_BOS_DESC_LEN 5 - -// total length, number of device caps -#define TUD_BOS_DESCRIPTOR(_total_len, _caps_num) \ - 5, TUSB_DESC_BOS, U16_TO_U8S_LE(_total_len), _caps_num - -// Device Capability Platform 128-bit UUID + Data -#define TUD_BOS_PLATFORM_DESCRIPTOR(...) \ - 4+TU_ARGS_NUM(__VA_ARGS__), TUSB_DESC_DEVICE_CAPABILITY, DEVICE_CAPABILITY_PLATFORM, 0x00, __VA_ARGS__ - -//------------- WebUSB BOS Platform -------------// - -// Descriptor Length -#define TUD_BOS_WEBUSB_DESC_LEN 24 - -// Vendor Code, iLandingPage -#define TUD_BOS_WEBUSB_DESCRIPTOR(_vendor_code, _ipage) \ - TUD_BOS_PLATFORM_DESCRIPTOR(TUD_BOS_WEBUSB_UUID, U16_TO_U8S_LE(0x0100), _vendor_code, _ipage) - -#define TUD_BOS_WEBUSB_UUID \ - 0x38, 0xB6, 0x08, 0x34, 0xA9, 0x09, 0xA0, 0x47, \ - 0x8B, 0xFD, 0xA0, 0x76, 0x88, 0x15, 0xB6, 0x65 - -//------------- Microsoft OS 2.0 Platform -------------// -#define TUD_BOS_MICROSOFT_OS_DESC_LEN 28 - -// Total Length of descriptor set, vendor code -#define TUD_BOS_MS_OS_20_DESCRIPTOR(_desc_set_len, _vendor_code) \ - TUD_BOS_PLATFORM_DESCRIPTOR(TUD_BOS_MS_OS_20_UUID, U32_TO_U8S_LE(0x06030000), U16_TO_U8S_LE(_desc_set_len), _vendor_code, 0) - -#define TUD_BOS_MS_OS_20_UUID \ - 0xDF, 0x60, 0xDD, 0xD8, 0x89, 0x45, 0xC7, 0x4C, \ - 0x9C, 0xD2, 0x65, 0x9D, 0x9E, 0x64, 0x8A, 0x9F - -//--------------------------------------------------------------------+ -// Configuration & Interface Descriptor Templates -//--------------------------------------------------------------------+ - -//------------- Configuration -------------// -#define TUD_CONFIG_DESC_LEN (9) - -// Interface count, string index, total length, attribute, power in mA -#define TUD_CONFIG_DESCRIPTOR(_itfcount, _stridx, _total_len, _attribute, _power_ma) \ - 9, TUSB_DESC_CONFIGURATION, U16_TO_U8S_LE(_total_len), _itfcount, 1, _stridx, TU_BIT(7) | _attribute, (_power_ma)/2 - -//------------- CDC -------------// - -// Length of template descriptor: 66 bytes -#define TUD_CDC_DESC_LEN (8+9+5+5+4+5+7+9+7+7) - -// CDC Descriptor Template -// Interface number, string index, EP notification address and size, EP data address (out, in) and size. -#define TUD_CDC_DESCRIPTOR(_itfnum, _stridx, _ep_notif, _ep_notif_size, _epout, _epin, _epsize) \ - /* Interface Associate */\ - 8, TUSB_DESC_INTERFACE_ASSOCIATION, _itfnum, 2, TUSB_CLASS_CDC, CDC_COMM_SUBCLASS_ABSTRACT_CONTROL_MODEL, CDC_COMM_PROTOCOL_ATCOMMAND, 0,\ - /* CDC Control Interface */\ - 9, TUSB_DESC_INTERFACE, _itfnum, 0, 1, TUSB_CLASS_CDC, CDC_COMM_SUBCLASS_ABSTRACT_CONTROL_MODEL, CDC_COMM_PROTOCOL_ATCOMMAND, _stridx,\ - /* CDC Header */\ - 5, TUSB_DESC_CS_INTERFACE, CDC_FUNC_DESC_HEADER, U16_TO_U8S_LE(0x0120),\ - /* CDC Call */\ - 5, TUSB_DESC_CS_INTERFACE, CDC_FUNC_DESC_CALL_MANAGEMENT, 0, (uint8_t)((_itfnum) + 1),\ - /* CDC ACM: support line request */\ - 4, TUSB_DESC_CS_INTERFACE, CDC_FUNC_DESC_ABSTRACT_CONTROL_MANAGEMENT, 2,\ - /* CDC Union */\ - 5, TUSB_DESC_CS_INTERFACE, CDC_FUNC_DESC_UNION, _itfnum, (uint8_t)((_itfnum) + 1),\ - /* Endpoint Notification */\ - 7, TUSB_DESC_ENDPOINT, _ep_notif, TUSB_XFER_INTERRUPT, U16_TO_U8S_LE(_ep_notif_size), 16,\ - /* CDC Data Interface */\ - 9, TUSB_DESC_INTERFACE, (uint8_t)((_itfnum)+1), 0, 2, TUSB_CLASS_CDC_DATA, 0, 0, 0,\ - /* Endpoint Out */\ - 7, TUSB_DESC_ENDPOINT, _epout, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0,\ - /* Endpoint In */\ - 7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0 - -//------------- MSC -------------// - -// Length of template descriptor: 23 bytes -#define TUD_MSC_DESC_LEN (9 + 7 + 7) - -// Interface number, string index, EP Out & EP In address, EP size -#define TUD_MSC_DESCRIPTOR(_itfnum, _stridx, _epout, _epin, _epsize) \ - /* Interface */\ - 9, TUSB_DESC_INTERFACE, _itfnum, 0, 2, TUSB_CLASS_MSC, MSC_SUBCLASS_SCSI, MSC_PROTOCOL_BOT, _stridx,\ - /* Endpoint Out */\ - 7, TUSB_DESC_ENDPOINT, _epout, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0,\ - /* Endpoint In */\ - 7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0 - -//------------- HID -------------// - -// Length of template descriptor: 25 bytes -#define TUD_HID_DESC_LEN (9 + 9 + 7) - -// HID Input only descriptor -// Interface number, string index, protocol, report descriptor len, EP In address, size & polling interval -#define TUD_HID_DESCRIPTOR(_itfnum, _stridx, _boot_protocol, _report_desc_len, _epin, _epsize, _ep_interval) \ - /* Interface */\ - 9, TUSB_DESC_INTERFACE, _itfnum, 0, 1, TUSB_CLASS_HID, (uint8_t)((_boot_protocol) ? HID_SUBCLASS_BOOT : 0), _boot_protocol, _stridx,\ - /* HID descriptor */\ - 9, HID_DESC_TYPE_HID, U16_TO_U8S_LE(0x0111), 0, 1, HID_DESC_TYPE_REPORT, U16_TO_U8S_LE(_report_desc_len),\ - /* Endpoint In */\ - 7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_INTERRUPT, U16_TO_U8S_LE(_epsize), _ep_interval - -// Length of template descriptor: 32 bytes -#define TUD_HID_INOUT_DESC_LEN (9 + 9 + 7 + 7) - -// HID Input & Output descriptor -// Interface number, string index, protocol, report descriptor len, EP OUT & IN address, size & polling interval -#define TUD_HID_INOUT_DESCRIPTOR(_itfnum, _stridx, _boot_protocol, _report_desc_len, _epout, _epin, _epsize, _ep_interval) \ - /* Interface */\ - 9, TUSB_DESC_INTERFACE, _itfnum, 0, 2, TUSB_CLASS_HID, (uint8_t)((_boot_protocol) ? HID_SUBCLASS_BOOT : 0), _boot_protocol, _stridx,\ - /* HID descriptor */\ - 9, HID_DESC_TYPE_HID, U16_TO_U8S_LE(0x0111), 0, 1, HID_DESC_TYPE_REPORT, U16_TO_U8S_LE(_report_desc_len),\ - /* Endpoint Out */\ - 7, TUSB_DESC_ENDPOINT, _epout, TUSB_XFER_INTERRUPT, U16_TO_U8S_LE(_epsize), _ep_interval, \ - /* Endpoint In */\ - 7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_INTERRUPT, U16_TO_U8S_LE(_epsize), _ep_interval - -//------------- MIDI -------------// - -// Length of template descriptor (96 bytes) -#define TUD_MIDI_DESC_LEN (9 + 9 + 9 + 7 + 6 + 6 + 9 + 9 + 7 + 5 + 7 + 5) - -// MIDI simple descriptor -// - 1 Embedded Jack In connected to 1 External Jack Out -// - 1 Embedded Jack out connected to 1 External Jack In -#define TUD_MIDI_DESCRIPTOR(_itfnum, _stridx, _epout, _epin, _epsize) \ - /* Audio Control (AC) Interface */\ - 9, TUSB_DESC_INTERFACE, _itfnum, 0, 0, TUSB_CLASS_AUDIO, AUDIO_SUBCLASS_CONTROL, AUDIO_PROTOCOL_V1, _stridx,\ - /* AC Header */\ - 9, TUSB_DESC_CS_INTERFACE, AUDIO_CS_INTERFACE_HEADER, U16_TO_U8S_LE(0x0100), U16_TO_U8S_LE(0x0009), 1, (uint8_t)((_itfnum)+1),\ - /* MIDI Streaming (MS) Interface */\ - 9, TUSB_DESC_INTERFACE, (uint8_t)((_itfnum)+1), 0, 2, TUSB_CLASS_AUDIO, AUDIO_SUBCLASS_MIDI_STREAMING, AUDIO_PROTOCOL_V1, 0,\ - /* MS Header */\ - 7, TUSB_DESC_CS_INTERFACE, MIDI_CS_INTERFACE_HEADER, U16_TO_U8S_LE(0x0100), U16_TO_U8S_LE(0x0025),\ - /* MS In Jack (Embedded) */\ - 6, TUSB_DESC_CS_INTERFACE, MIDI_CS_INTERFACE_IN_JACK, MIDI_JACK_EMBEDDED, 1, 0,\ - /* MS In Jack (External) */\ - 6, TUSB_DESC_CS_INTERFACE, MIDI_CS_INTERFACE_IN_JACK, MIDI_JACK_EXTERNAL, 2, 0,\ - /* MS Out Jack (Embedded), connected to In Jack External */\ - 9, TUSB_DESC_CS_INTERFACE, MIDI_CS_INTERFACE_OUT_JACK, MIDI_JACK_EMBEDDED, 3, 1, 2, 1, 0,\ - /* MS Out Jack (External), connected to In Jack Embedded */\ - 9, TUSB_DESC_CS_INTERFACE, MIDI_CS_INTERFACE_OUT_JACK, MIDI_JACK_EXTERNAL, 4, 1, 1, 1, 0,\ - /* Endpoint Out */\ - 7, TUSB_DESC_ENDPOINT, _epout, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0,\ - /* MS Endpoint (connected to embedded jack in) */\ - 5, TUSB_DESC_CS_ENDPOINT, MIDI_CS_ENDPOINT_GENERAL, 1, 1,\ - /* Endpoint In */\ - 7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0,\ - /* MS Endpoint (connected to embedded jack out) */\ - 5, TUSB_DESC_CS_ENDPOINT, MIDI_CS_ENDPOINT_GENERAL, 1, 3 - -//------------- TUD_USBTMC/USB488 -------------// -#define TUD_USBTMC_APP_CLASS (TUSB_CLASS_APPLICATION_SPECIFIC) -#define TUD_USBTMC_APP_SUBCLASS 0x03u - -#define TUD_USBTMC_PROTOCOL_STD 0x00u -#define TUD_USBTMC_PROTOCOL_USB488 0x01u - -// Interface number, number of endpoints, EP string index, USB_TMC_PROTOCOL*, bulk-out endpoint ID, -// bulk-in endpoint ID -#define TUD_USBTMC_IF_DESCRIPTOR(_itfnum, _bNumEndpoints, _stridx, _itfProtocol) \ -/* Interface */ \ - 0x09, TUSB_DESC_INTERFACE, _itfnum, 0x00, _bNumEndpoints, TUD_USBTMC_APP_CLASS, TUD_USBTMC_APP_SUBCLASS, _itfProtocol, _stridx - -#define TUD_USBTMC_IF_DESCRIPTOR_LEN 9u - -#define TUD_USBTMC_BULK_DESCRIPTORS(_epout, _epin, _bulk_epsize) \ -/* Endpoint Out */ \ -7, TUSB_DESC_ENDPOINT, _epout, TUSB_XFER_BULK, U16_TO_U8S_LE(_bulk_epsize), 0u, \ -/* Endpoint In */ \ -7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_BULK, U16_TO_U8S_LE(_bulk_epsize), 0u - -#define TUD_USBTMC_BULK_DESCRIPTORS_LEN (7u+7u) - -/* optional interrupt endpoint */ \ -// _int_pollingInterval : for LS/FS, expressed in frames (1ms each). 16 may be a good number? -#define TUD_USBTMC_INT_DESCRIPTOR(_ep_interrupt, _ep_interrupt_size, _int_pollingInterval ) \ -7, TUSB_DESC_ENDPOINT, _ep_interrupt, TUSB_XFER_INTERRUPT, U16_TO_U8S_LE(_ep_interrupt_size), 0x16 - -#define TUD_USBTMC_INT_DESCRIPTOR_LEN (7u) - - -//------------- Vendor -------------// -#define TUD_VENDOR_DESC_LEN (9+7+7) - -// Interface number, string index, EP Out & IN address, EP size -#define TUD_VENDOR_DESCRIPTOR(_itfnum, _stridx, _epout, _epin, _epsize) \ - /* Interface */\ - 9, TUSB_DESC_INTERFACE, _itfnum, 0, 2, TUSB_CLASS_VENDOR_SPECIFIC, 0x00, 0x00, _stridx,\ - /* Endpoint Out */\ - 7, TUSB_DESC_ENDPOINT, _epout, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0,\ - /* Endpoint In */\ - 7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0 - -//------------- DFU Runtime -------------// -#define TUD_DFU_APP_CLASS (TUSB_CLASS_APPLICATION_SPECIFIC) -#define TUD_DFU_APP_SUBCLASS 0x01u - -// Length of template descriptr: 18 bytes -#define TUD_DFU_RT_DESC_LEN (9 + 9) - -// DFU runtime descriptor -// Interface number, string index, attributes, detach timeout, transfer size -#define TUD_DFU_RT_DESCRIPTOR(_itfnum, _stridx, _attr, _timeout, _xfer_size) \ - /* Interface */ \ - 9, TUSB_DESC_INTERFACE, _itfnum, 0, 0, TUD_DFU_APP_CLASS, TUD_DFU_APP_SUBCLASS, DFU_PROTOCOL_RT, _stridx, \ - /* Function */ \ - 9, DFU_DESC_FUNCTIONAL, _attr, U16_TO_U8S_LE(_timeout), U16_TO_U8S_LE(_xfer_size), U16_TO_U8S_LE(0x0101) - - -#ifdef __cplusplus - } -#endif - -#endif /* _TUSB_USBD_H_ */ - -/** @} */ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +/** \ingroup group_usbd + * @{ */ + +#ifndef _TUSB_USBD_H_ +#define _TUSB_USBD_H_ + +#ifdef __cplusplus + extern "C" { +#endif + +#include "common/tusb_common.h" +#include "dcd.h" + +//--------------------------------------------------------------------+ +// Application API +//--------------------------------------------------------------------+ + +// Init device stack +bool tud_init (void); + +// Task function should be called in main/rtos loop +void tud_task (void); + +// Interrupt handler, name alias to DCD +#define tud_isr dcd_isr + +// Check if device is connected and configured +bool tud_mounted(void); + +// Check if device is suspended +bool tud_suspended(void); + +// Check if device is ready to transfer +static inline bool tud_ready(void) +{ + return tud_mounted() && !tud_suspended(); +} + +// Remote wake up host, only if suspended and enabled by host +bool tud_remote_wakeup(void); + +// Carry out Data and Status stage of control transfer +// - If len = 0, it is equivalent to sending status only +// - If len > wLength : it will be truncated +bool tud_control_xfer(uint8_t rhport, tusb_control_request_t const * request, void* buffer, uint16_t len); + +// Send STATUS (zero length) packet +bool tud_control_status(uint8_t rhport, tusb_control_request_t const * request); + +//--------------------------------------------------------------------+ +// Application Callbacks (WEAK is optional) +//--------------------------------------------------------------------+ + +// Invoked when received GET DEVICE DESCRIPTOR request +// Application return pointer to descriptor +uint8_t const * tud_descriptor_device_cb(void); + +// Invoked when received GET BOS DESCRIPTOR request +// Application return pointer to descriptor +TU_ATTR_WEAK uint8_t const * tud_descriptor_bos_cb(void); + +// Invoked when received GET CONFIGURATION DESCRIPTOR request +// Application return pointer to descriptor, whose contents must exist long enough for transfer to complete +uint8_t const * tud_descriptor_configuration_cb(uint8_t index); + +// Invoked when received GET STRING DESCRIPTOR request +// Application return pointer to descriptor, whose contents must exist long enough for transfer to complete +uint16_t const* tud_descriptor_string_cb(uint8_t index); + +// Invoked when device is mounted (configured) +TU_ATTR_WEAK void tud_mount_cb(void); + +// Invoked when device is unmounted +TU_ATTR_WEAK void tud_umount_cb(void); + +// Invoked when usb bus is suspended +// Within 7ms, device must draw an average of current less than 2.5 mA from bus +TU_ATTR_WEAK void tud_suspend_cb(bool remote_wakeup_en); + +// Invoked when usb bus is resumed +TU_ATTR_WEAK void tud_resume_cb(void); + +// Invoked when received control request with VENDOR TYPE +TU_ATTR_WEAK bool tud_vendor_control_request_cb(uint8_t rhport, tusb_control_request_t const * request); +TU_ATTR_WEAK bool tud_vendor_control_complete_cb(uint8_t rhport, tusb_control_request_t const * request); + + +//--------------------------------------------------------------------+ +// Binary Device Object Store (BOS) Descriptor Templates +//--------------------------------------------------------------------+ + +#define TUD_BOS_DESC_LEN 5 + +// total length, number of device caps +#define TUD_BOS_DESCRIPTOR(_total_len, _caps_num) \ + 5, TUSB_DESC_BOS, U16_TO_U8S_LE(_total_len), _caps_num + +// Device Capability Platform 128-bit UUID + Data +#define TUD_BOS_PLATFORM_DESCRIPTOR(...) \ + 4+TU_ARGS_NUM(__VA_ARGS__), TUSB_DESC_DEVICE_CAPABILITY, DEVICE_CAPABILITY_PLATFORM, 0x00, __VA_ARGS__ + +//------------- WebUSB BOS Platform -------------// + +// Descriptor Length +#define TUD_BOS_WEBUSB_DESC_LEN 24 + +// Vendor Code, iLandingPage +#define TUD_BOS_WEBUSB_DESCRIPTOR(_vendor_code, _ipage) \ + TUD_BOS_PLATFORM_DESCRIPTOR(TUD_BOS_WEBUSB_UUID, U16_TO_U8S_LE(0x0100), _vendor_code, _ipage) + +#define TUD_BOS_WEBUSB_UUID \ + 0x38, 0xB6, 0x08, 0x34, 0xA9, 0x09, 0xA0, 0x47, \ + 0x8B, 0xFD, 0xA0, 0x76, 0x88, 0x15, 0xB6, 0x65 + +//------------- Microsoft OS 2.0 Platform -------------// +#define TUD_BOS_MICROSOFT_OS_DESC_LEN 28 + +// Total Length of descriptor set, vendor code +#define TUD_BOS_MS_OS_20_DESCRIPTOR(_desc_set_len, _vendor_code) \ + TUD_BOS_PLATFORM_DESCRIPTOR(TUD_BOS_MS_OS_20_UUID, U32_TO_U8S_LE(0x06030000), U16_TO_U8S_LE(_desc_set_len), _vendor_code, 0) + +#define TUD_BOS_MS_OS_20_UUID \ + 0xDF, 0x60, 0xDD, 0xD8, 0x89, 0x45, 0xC7, 0x4C, \ + 0x9C, 0xD2, 0x65, 0x9D, 0x9E, 0x64, 0x8A, 0x9F + +//--------------------------------------------------------------------+ +// Configuration & Interface Descriptor Templates +//--------------------------------------------------------------------+ + +//------------- Configuration -------------// +#define TUD_CONFIG_DESC_LEN (9) + +// Interface count, string index, total length, attribute, power in mA +#define TUD_CONFIG_DESCRIPTOR(_itfcount, _stridx, _total_len, _attribute, _power_ma) \ + 9, TUSB_DESC_CONFIGURATION, U16_TO_U8S_LE(_total_len), _itfcount, 1, _stridx, TU_BIT(7) | _attribute, (_power_ma)/2 + +//------------- CDC -------------// + +// Length of template descriptor: 66 bytes +#define TUD_CDC_DESC_LEN (8+9+5+5+4+5+7+9+7+7) + +// CDC Descriptor Template +// Interface number, string index, EP notification address and size, EP data address (out, in) and size. +#define TUD_CDC_DESCRIPTOR(_itfnum, _stridx, _ep_notif, _ep_notif_size, _epout, _epin, _epsize) \ + /* Interface Associate */\ + 8, TUSB_DESC_INTERFACE_ASSOCIATION, _itfnum, 2, TUSB_CLASS_CDC, CDC_COMM_SUBCLASS_ABSTRACT_CONTROL_MODEL, CDC_COMM_PROTOCOL_ATCOMMAND, 0,\ + /* CDC Control Interface */\ + 9, TUSB_DESC_INTERFACE, _itfnum, 0, 1, TUSB_CLASS_CDC, CDC_COMM_SUBCLASS_ABSTRACT_CONTROL_MODEL, CDC_COMM_PROTOCOL_ATCOMMAND, _stridx,\ + /* CDC Header */\ + 5, TUSB_DESC_CS_INTERFACE, CDC_FUNC_DESC_HEADER, U16_TO_U8S_LE(0x0120),\ + /* CDC Call */\ + 5, TUSB_DESC_CS_INTERFACE, CDC_FUNC_DESC_CALL_MANAGEMENT, 0, (uint8_t)((_itfnum) + 1),\ + /* CDC ACM: support line request */\ + 4, TUSB_DESC_CS_INTERFACE, CDC_FUNC_DESC_ABSTRACT_CONTROL_MANAGEMENT, 2,\ + /* CDC Union */\ + 5, TUSB_DESC_CS_INTERFACE, CDC_FUNC_DESC_UNION, _itfnum, (uint8_t)((_itfnum) + 1),\ + /* Endpoint Notification */\ + 7, TUSB_DESC_ENDPOINT, _ep_notif, TUSB_XFER_INTERRUPT, U16_TO_U8S_LE(_ep_notif_size), 16,\ + /* CDC Data Interface */\ + 9, TUSB_DESC_INTERFACE, (uint8_t)((_itfnum)+1), 0, 2, TUSB_CLASS_CDC_DATA, 0, 0, 0,\ + /* Endpoint Out */\ + 7, TUSB_DESC_ENDPOINT, _epout, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0,\ + /* Endpoint In */\ + 7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0 + +//------------- MSC -------------// + +// Length of template descriptor: 23 bytes +#define TUD_MSC_DESC_LEN (9 + 7 + 7) + +// Interface number, string index, EP Out & EP In address, EP size +#define TUD_MSC_DESCRIPTOR(_itfnum, _stridx, _epout, _epin, _epsize) \ + /* Interface */\ + 9, TUSB_DESC_INTERFACE, _itfnum, 0, 2, TUSB_CLASS_MSC, MSC_SUBCLASS_SCSI, MSC_PROTOCOL_BOT, _stridx,\ + /* Endpoint Out */\ + 7, TUSB_DESC_ENDPOINT, _epout, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0,\ + /* Endpoint In */\ + 7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0 + +//------------- HID -------------// + +// Length of template descriptor: 25 bytes +#define TUD_HID_DESC_LEN (9 + 9 + 7) + +// HID Input only descriptor +// Interface number, string index, protocol, report descriptor len, EP In address, size & polling interval +#define TUD_HID_DESCRIPTOR(_itfnum, _stridx, _boot_protocol, _report_desc_len, _epin, _epsize, _ep_interval) \ + /* Interface */\ + 9, TUSB_DESC_INTERFACE, _itfnum, 0, 1, TUSB_CLASS_HID, (uint8_t)((_boot_protocol) ? HID_SUBCLASS_BOOT : 0), _boot_protocol, _stridx,\ + /* HID descriptor */\ + 9, HID_DESC_TYPE_HID, U16_TO_U8S_LE(0x0111), 0, 1, HID_DESC_TYPE_REPORT, U16_TO_U8S_LE(_report_desc_len),\ + /* Endpoint In */\ + 7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_INTERRUPT, U16_TO_U8S_LE(_epsize), _ep_interval + +// Length of template descriptor: 32 bytes +#define TUD_HID_INOUT_DESC_LEN (9 + 9 + 7 + 7) + +// HID Input & Output descriptor +// Interface number, string index, protocol, report descriptor len, EP OUT & IN address, size & polling interval +#define TUD_HID_INOUT_DESCRIPTOR(_itfnum, _stridx, _boot_protocol, _report_desc_len, _epout, _epin, _epsize, _ep_interval) \ + /* Interface */\ + 9, TUSB_DESC_INTERFACE, _itfnum, 0, 2, TUSB_CLASS_HID, (uint8_t)((_boot_protocol) ? HID_SUBCLASS_BOOT : 0), _boot_protocol, _stridx,\ + /* HID descriptor */\ + 9, HID_DESC_TYPE_HID, U16_TO_U8S_LE(0x0111), 0, 1, HID_DESC_TYPE_REPORT, U16_TO_U8S_LE(_report_desc_len),\ + /* Endpoint Out */\ + 7, TUSB_DESC_ENDPOINT, _epout, TUSB_XFER_INTERRUPT, U16_TO_U8S_LE(_epsize), _ep_interval, \ + /* Endpoint In */\ + 7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_INTERRUPT, U16_TO_U8S_LE(_epsize), _ep_interval + +//------------- MIDI -------------// + +// Length of template descriptor (96 bytes) +#define TUD_MIDI_DESC_LEN (9 + 9 + 9 + 7 + 6 + 6 + 9 + 9 + 7 + 5 + 7 + 5) + +// MIDI simple descriptor +// - 1 Embedded Jack In connected to 1 External Jack Out +// - 1 Embedded Jack out connected to 1 External Jack In +#define TUD_MIDI_DESCRIPTOR(_itfnum, _stridx, _epout, _epin, _epsize) \ + /* Audio Control (AC) Interface */\ + 9, TUSB_DESC_INTERFACE, _itfnum, 0, 0, TUSB_CLASS_AUDIO, AUDIO_SUBCLASS_CONTROL, AUDIO_PROTOCOL_V1, _stridx,\ + /* AC Header */\ + 9, TUSB_DESC_CS_INTERFACE, AUDIO_CS_INTERFACE_HEADER, U16_TO_U8S_LE(0x0100), U16_TO_U8S_LE(0x0009), 1, (uint8_t)((_itfnum)+1),\ + /* MIDI Streaming (MS) Interface */\ + 9, TUSB_DESC_INTERFACE, (uint8_t)((_itfnum)+1), 0, 2, TUSB_CLASS_AUDIO, AUDIO_SUBCLASS_MIDI_STREAMING, AUDIO_PROTOCOL_V1, 0,\ + /* MS Header */\ + 7, TUSB_DESC_CS_INTERFACE, MIDI_CS_INTERFACE_HEADER, U16_TO_U8S_LE(0x0100), U16_TO_U8S_LE(0x0025),\ + /* MS In Jack (Embedded) */\ + 6, TUSB_DESC_CS_INTERFACE, MIDI_CS_INTERFACE_IN_JACK, MIDI_JACK_EMBEDDED, 1, 0,\ + /* MS In Jack (External) */\ + 6, TUSB_DESC_CS_INTERFACE, MIDI_CS_INTERFACE_IN_JACK, MIDI_JACK_EXTERNAL, 2, 0,\ + /* MS Out Jack (Embedded), connected to In Jack External */\ + 9, TUSB_DESC_CS_INTERFACE, MIDI_CS_INTERFACE_OUT_JACK, MIDI_JACK_EMBEDDED, 3, 1, 2, 1, 0,\ + /* MS Out Jack (External), connected to In Jack Embedded */\ + 9, TUSB_DESC_CS_INTERFACE, MIDI_CS_INTERFACE_OUT_JACK, MIDI_JACK_EXTERNAL, 4, 1, 1, 1, 0,\ + /* Endpoint Out */\ + 7, TUSB_DESC_ENDPOINT, _epout, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0,\ + /* MS Endpoint (connected to embedded jack in) */\ + 5, TUSB_DESC_CS_ENDPOINT, MIDI_CS_ENDPOINT_GENERAL, 1, 1,\ + /* Endpoint In */\ + 7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0,\ + /* MS Endpoint (connected to embedded jack out) */\ + 5, TUSB_DESC_CS_ENDPOINT, MIDI_CS_ENDPOINT_GENERAL, 1, 3 + +//------------- TUD_USBTMC/USB488 -------------// +#define TUD_USBTMC_APP_CLASS (TUSB_CLASS_APPLICATION_SPECIFIC) +#define TUD_USBTMC_APP_SUBCLASS 0x03u + +#define TUD_USBTMC_PROTOCOL_STD 0x00u +#define TUD_USBTMC_PROTOCOL_USB488 0x01u + +// Interface number, number of endpoints, EP string index, USB_TMC_PROTOCOL*, bulk-out endpoint ID, +// bulk-in endpoint ID +#define TUD_USBTMC_IF_DESCRIPTOR(_itfnum, _bNumEndpoints, _stridx, _itfProtocol) \ +/* Interface */ \ + 0x09, TUSB_DESC_INTERFACE, _itfnum, 0x00, _bNumEndpoints, TUD_USBTMC_APP_CLASS, TUD_USBTMC_APP_SUBCLASS, _itfProtocol, _stridx + +#define TUD_USBTMC_IF_DESCRIPTOR_LEN 9u + +#define TUD_USBTMC_BULK_DESCRIPTORS(_epout, _epin, _bulk_epsize) \ +/* Endpoint Out */ \ +7, TUSB_DESC_ENDPOINT, _epout, TUSB_XFER_BULK, U16_TO_U8S_LE(_bulk_epsize), 0u, \ +/* Endpoint In */ \ +7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_BULK, U16_TO_U8S_LE(_bulk_epsize), 0u + +#define TUD_USBTMC_BULK_DESCRIPTORS_LEN (7u+7u) + +/* optional interrupt endpoint */ \ +// _int_pollingInterval : for LS/FS, expressed in frames (1ms each). 16 may be a good number? +#define TUD_USBTMC_INT_DESCRIPTOR(_ep_interrupt, _ep_interrupt_size, _int_pollingInterval ) \ +7, TUSB_DESC_ENDPOINT, _ep_interrupt, TUSB_XFER_INTERRUPT, U16_TO_U8S_LE(_ep_interrupt_size), 0x16 + +#define TUD_USBTMC_INT_DESCRIPTOR_LEN (7u) + + +//------------- Vendor -------------// +#define TUD_VENDOR_DESC_LEN (9+7+7) + +// Interface number, string index, EP Out & IN address, EP size +#define TUD_VENDOR_DESCRIPTOR(_itfnum, _stridx, _epout, _epin, _epsize) \ + /* Interface */\ + 9, TUSB_DESC_INTERFACE, _itfnum, 0, 2, TUSB_CLASS_VENDOR_SPECIFIC, 0x00, 0x00, _stridx,\ + /* Endpoint Out */\ + 7, TUSB_DESC_ENDPOINT, _epout, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0,\ + /* Endpoint In */\ + 7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0 + +//------------- DFU Runtime -------------// +#define TUD_DFU_APP_CLASS (TUSB_CLASS_APPLICATION_SPECIFIC) +#define TUD_DFU_APP_SUBCLASS 0x01u + +// Length of template descriptr: 18 bytes +#define TUD_DFU_RT_DESC_LEN (9 + 9) + +// DFU runtime descriptor +// Interface number, string index, attributes, detach timeout, transfer size +#define TUD_DFU_RT_DESCRIPTOR(_itfnum, _stridx, _attr, _timeout, _xfer_size) \ + /* Interface */ \ + 9, TUSB_DESC_INTERFACE, _itfnum, 0, 0, TUD_DFU_APP_CLASS, TUD_DFU_APP_SUBCLASS, DFU_PROTOCOL_RT, _stridx, \ + /* Function */ \ + 9, DFU_DESC_FUNCTIONAL, _attr, U16_TO_U8S_LE(_timeout), U16_TO_U8S_LE(_xfer_size), U16_TO_U8S_LE(0x0101) + + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_USBD_H_ */ + +/** @} */ diff --git a/src/host/ehci/ehci.c b/src/host/ehci/ehci.c index 18123a49..9ddffaf2 100644 --- a/src/host/ehci/ehci.c +++ b/src/host/ehci/ehci.c @@ -1,856 +1,856 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2019 Ha Thach (tinyusb.org) - * - * 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. - * - * This file is part of the TinyUSB stack. - */ - -#include "common/tusb_common.h" - -#if TUSB_OPT_HOST_ENABLED && (CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX) -//--------------------------------------------------------------------+ -// INCLUDE -//--------------------------------------------------------------------+ -#include "osal/osal.h" - -#include "../hcd.h" -#include "../usbh_hcd.h" -#include "ehci.h" - -//--------------------------------------------------------------------+ -// MACRO CONSTANT TYPEDEF -//--------------------------------------------------------------------+ - -//--------------------------------------------------------------------+ -// INTERNAL OBJECT & FUNCTION DECLARATION -//--------------------------------------------------------------------+ -// Periodic frame list must be 4K alignment -CFG_TUSB_MEM_SECTION TU_ATTR_ALIGNED(4096) static ehci_data_t ehci_data; - -// EHCI portable -uint32_t hcd_ehci_register_addr(uint8_t rhport); - -//--------------------------------------------------------------------+ -// PROTOTYPE -//--------------------------------------------------------------------+ -static inline ehci_link_t* get_period_head(uint8_t rhport, uint8_t interval_ms) -{ - (void) rhport; - return (ehci_link_t*) &ehci_data.period_head_arr[ tu_log2( tu_min8(EHCI_FRAMELIST_SIZE, interval_ms) ) ]; -} - -static inline ehci_qhd_t* qhd_control(uint8_t dev_addr) -{ - return &ehci_data.control[dev_addr].qhd; -} - -static inline ehci_qhd_t* qhd_async_head(uint8_t rhport) -{ - (void) rhport; - return qhd_control(0); // control qhd of dev0 is used as async head -} - -static inline ehci_qtd_t* qtd_control(uint8_t dev_addr) -{ - return &ehci_data.control[dev_addr].qtd; -} - - -static inline ehci_qhd_t* qhd_next (ehci_qhd_t const * p_qhd); -static inline ehci_qhd_t* qhd_find_free (void); -static inline ehci_qhd_t* qhd_get_from_addr (uint8_t dev_addr, uint8_t ep_addr); - -// determine if a queue head has bus-related error -static inline bool qhd_has_xact_error (ehci_qhd_t * p_qhd) -{ - return (p_qhd->qtd_overlay.buffer_err || p_qhd->qtd_overlay.babble_err || p_qhd->qtd_overlay.xact_err); - //p_qhd->qtd_overlay.non_hs_period_missed_uframe || p_qhd->qtd_overlay.pingstate_err TODO split transaction error -} - -static void qhd_init (ehci_qhd_t *p_qhd, uint8_t dev_addr, tusb_desc_endpoint_t const * ep_desc); - -static inline ehci_qtd_t* qtd_find_free (void); -static inline ehci_qtd_t* qtd_next (ehci_qtd_t const * p_qtd); -static inline void qtd_insert_to_qhd (ehci_qhd_t *p_qhd, ehci_qtd_t *p_qtd_new); -static inline void qtd_remove_1st_from_qhd (ehci_qhd_t *p_qhd); -static void qtd_init (ehci_qtd_t* p_qtd, void* buffer, uint16_t total_bytes); - -static inline void list_insert (ehci_link_t *current, ehci_link_t *new, uint8_t new_type); -static inline ehci_link_t* list_next (ehci_link_t *p_link_pointer); - -static bool ehci_init (uint8_t rhport); - -//--------------------------------------------------------------------+ -// HCD API -//--------------------------------------------------------------------+ -bool hcd_init(void) -{ - tu_memclr(&ehci_data, sizeof(ehci_data_t)); - return ehci_init(TUH_OPT_RHPORT); -} - -void hcd_port_reset(uint8_t rhport) -{ - (void) rhport; - - ehci_registers_t* regs = ehci_data.regs; - - regs->portsc_bm.port_enabled = 0; // disable port before reset - regs->portsc_bm.port_reset = 1; -} - -bool hcd_port_connect_status(uint8_t rhport) -{ - (void) rhport; - return ehci_data.regs->portsc_bm.current_connect_status; -} - -tusb_speed_t hcd_port_speed_get(uint8_t rhport) -{ - (void) rhport; - return (tusb_speed_t) ehci_data.regs->portsc_bm.nxp_port_speed; // NXP specific port speed -} - -static void list_remove_qhd_by_addr(ehci_link_t* list_head, uint8_t dev_addr) -{ - for(ehci_link_t* prev = list_head; - !prev->terminate && (tu_align32(prev->address) != (uint32_t) list_head); - prev = list_next(prev) ) - { - // TODO check type for ISO iTD and siTD - ehci_qhd_t* qhd = (ehci_qhd_t*) list_next(prev); - if ( qhd->dev_addr == dev_addr ) - { - // TODO deactive all TD, wait for QHD to inactive before removal - prev->address = qhd->next.address; - - // EHCI 4.8.2 link the removed qhd to async head (which always reachable by Host Controller) - qhd->next.address = ((uint32_t) list_head) | (EHCI_QTYPE_QHD << 1); - - if ( qhd->int_smask ) - { - // period list queue element is guarantee to be free in the next frame (1 ms) - qhd->used = 0; - }else - { - // async list use async advance handshake - // mark as removing, will completely re-usable when async advance isr occurs - qhd->removing = 1; - } - } - } -} - -// Close all opened endpoint belong to this device -void hcd_device_close(uint8_t rhport, uint8_t dev_addr) -{ - // skip dev0 - if (dev_addr == 0) return; - - // Remove from async list - list_remove_qhd_by_addr( (ehci_link_t*) qhd_async_head(rhport), dev_addr ); - - // Remove from all interval period list - for(uint8_t i = 0; i < TU_ARRAY_SIZE(ehci_data.period_head_arr); i++) - { - list_remove_qhd_by_addr( (ehci_link_t*) &ehci_data.period_head_arr[i], dev_addr); - } - - // Async doorbell (EHCI 4.8.2 for operational details) - ehci_data.regs->command_bm.async_adv_doorbell = 1; -} - -// EHCI controller init -static bool ehci_init(uint8_t rhport) -{ - ehci_data.regs = (ehci_registers_t* ) hcd_ehci_register_addr(rhport); - - ehci_registers_t* regs = ehci_data.regs; - - //------------- CTRLDSSEGMENT Register (skip) -------------// - //------------- USB INT Register -------------// - regs->inten = 0; // 1. disable all the interrupt - regs->status = EHCI_INT_MASK_ALL; // 2. clear all status - - regs->inten = EHCI_INT_MASK_ERROR | EHCI_INT_MASK_PORT_CHANGE | EHCI_INT_MASK_ASYNC_ADVANCE | - EHCI_INT_MASK_NXP_PERIODIC | EHCI_INT_MASK_NXP_ASYNC ; - - //------------- Asynchronous List -------------// - ehci_qhd_t * const async_head = qhd_async_head(rhport); - tu_memclr(async_head, sizeof(ehci_qhd_t)); - - async_head->next.address = (uint32_t) async_head; // circular list, next is itself - async_head->next.type = EHCI_QTYPE_QHD; - async_head->head_list_flag = 1; - async_head->qtd_overlay.halted = 1; // inactive most of time - async_head->qtd_overlay.next.terminate = 1; // TODO removed if verified - - regs->async_list_addr = (uint32_t) async_head; - - //------------- Periodic List -------------// - // Build the polling interval tree with 1 ms, 2 ms, 4 ms and 8 ms (framesize) only - for(uint32_t i=0; i<4; i++) - { - ehci_data.period_head_arr[i].int_smask = 1; // queue head in period list must have smask non-zero - ehci_data.period_head_arr[i].qtd_overlay.halted = 1; // dummy node, always inactive - } - - ehci_link_t * const framelist = ehci_data.period_framelist; - ehci_link_t * const period_1ms = get_period_head(rhport, 1); - // all links --> period_head_arr[0] (1ms) - // 0, 2, 4, 6 etc --> period_head_arr[1] (2ms) - // 1, 5 --> period_head_arr[2] (4ms) - // 3 --> period_head_arr[3] (8ms) - - // TODO EHCI_FRAMELIST_SIZE with other size than 8 - for(uint32_t i=0; iterminate = 1; - - regs->periodic_list_base = (uint32_t) framelist; - - //------------- TT Control (NXP only) -------------// - regs->nxp_tt_control = 0; - - //------------- USB CMD Register -------------// - regs->command |= TU_BIT(EHCI_USBCMD_POS_RUN_STOP) | TU_BIT(EHCI_USBCMD_POS_ASYNC_ENABLE) - | TU_BIT(EHCI_USBCMD_POS_PERIOD_ENABLE) // TODO enable period list only there is int/iso endpoint - | ((EHCI_CFG_FRAMELIST_SIZE_BITS & TU_BIN8(011)) << EHCI_USBCMD_POS_FRAMELIST_SZIE) - | ((EHCI_CFG_FRAMELIST_SIZE_BITS >> 2) << EHCI_USBCMD_POS_NXP_FRAMELIST_SIZE_MSB); - - //------------- ConfigFlag Register (skip) -------------// - regs->portsc_bm.port_power = 1; // enable port power - - return true; -} - -#if 0 -static void ehci_stop(uint8_t rhport) -{ - (void) rhport; - - ehci_registers_t* regs = ehci_data.regs; - - regs->command_bm.run_stop = 0; - - // USB Spec: controller has to stop within 16 uframe = 2 frames - while( regs->status_bm.hc_halted == 0 ) {} -} -#endif - -//--------------------------------------------------------------------+ -// CONTROL PIPE API -//--------------------------------------------------------------------+ -bool hcd_edpt_xfer(uint8_t rhport, uint8_t dev_addr, uint8_t ep_addr, uint8_t * buffer, uint16_t buflen) -{ - (void) rhport; - - uint8_t const epnum = tu_edpt_number(ep_addr); - uint8_t const dir = tu_edpt_dir(ep_addr); - - // FIXME control only for now - if ( epnum == 0 ) - { - ehci_qhd_t* qhd = qhd_control(dev_addr); - ehci_qtd_t* qtd = qtd_control(dev_addr); - - qtd_init(qtd, buffer, buflen); - - // first first data toggle is always 1 (data & setup stage) - qtd->data_toggle = 1; - qtd->pid = dir ? EHCI_PID_IN : EHCI_PID_OUT; - qtd->int_on_complete = 1; - qtd->next.terminate = 1; - - // sw region - qhd->p_qtd_list_head = qtd; - qhd->p_qtd_list_tail = qtd; - - // attach TD - qhd->qtd_overlay.next.address = (uint32_t) qtd; - } - - return true; -} - -bool hcd_setup_send(uint8_t rhport, uint8_t dev_addr, uint8_t const setup_packet[8]) -{ - (void) rhport; - - ehci_qhd_t* qhd = &ehci_data.control[dev_addr].qhd; - ehci_qtd_t* td = &ehci_data.control[dev_addr].qtd; - - qtd_init(td, (void*) setup_packet, 8); - td->pid = EHCI_PID_SETUP; - td->int_on_complete = 1; - td->next.terminate = 1; - - // sw region - qhd->p_qtd_list_head = td; - qhd->p_qtd_list_tail = td; - - // attach TD - qhd->qtd_overlay.next.address = (uint32_t) td; - - return true; -} - -//--------------------------------------------------------------------+ -// BULK/INT/ISO PIPE API -//--------------------------------------------------------------------+ -bool hcd_edpt_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_endpoint_t const * ep_desc) -{ - (void) rhport; - - // TODO not support ISO yet - TU_ASSERT (ep_desc->bmAttributes.xfer != TUSB_XFER_ISOCHRONOUS); - - //------------- Prepare Queue Head -------------// - ehci_qhd_t * p_qhd; - - if ( ep_desc->bEndpointAddress == 0 ) - { - p_qhd = qhd_control(dev_addr); - }else - { - p_qhd = qhd_find_free(); - } - TU_ASSERT(p_qhd); - - qhd_init(p_qhd, dev_addr, ep_desc); - - // control of dev0 is always present as async head - if ( dev_addr == 0 ) return true; - - // Insert to list - ehci_link_t * list_head; - - switch (ep_desc->bmAttributes.xfer) - { - case TUSB_XFER_CONTROL: - case TUSB_XFER_BULK: - list_head = (ehci_link_t*) qhd_async_head(rhport); - break; - - case TUSB_XFER_INTERRUPT: - list_head = get_period_head(rhport, p_qhd->interval_ms); - break; - - case TUSB_XFER_ISOCHRONOUS: - // TODO iso is not supported - break; - - default: break; - } - - // TODO might need to disable async/period list - list_insert( list_head, (ehci_link_t*) p_qhd, EHCI_QTYPE_QHD); - - return true; -} - -bool hcd_pipe_queue_xfer(uint8_t dev_addr, uint8_t ep_addr, uint8_t buffer[], uint16_t total_bytes) -{ - //------------- set up QTD -------------// - ehci_qhd_t *p_qhd = qhd_get_from_addr(dev_addr, ep_addr); - ehci_qtd_t *p_qtd = qtd_find_free(); - - TU_ASSERT(p_qtd); - - qtd_init(p_qtd, buffer, total_bytes); - p_qtd->pid = p_qhd->pid; - - //------------- insert TD to TD list -------------// - qtd_insert_to_qhd(p_qhd, p_qtd); - - return true; -} - -bool hcd_pipe_xfer(uint8_t dev_addr, uint8_t ep_addr, uint8_t buffer[], uint16_t total_bytes, bool int_on_complete) -{ - TU_ASSERT ( hcd_pipe_queue_xfer(dev_addr, ep_addr, buffer, total_bytes) ); - - ehci_qhd_t *p_qhd = qhd_get_from_addr(dev_addr, ep_addr); - - if ( int_on_complete ) - { // the just added qtd is pointed by list_tail - p_qhd->p_qtd_list_tail->int_on_complete = 1; - } - p_qhd->qtd_overlay.next.address = (uint32_t) p_qhd->p_qtd_list_head; // attach head QTD to QHD start transferring - - return true; -} - -bool hcd_edpt_busy(uint8_t dev_addr, uint8_t ep_addr) -{ - ehci_qhd_t *p_qhd = qhd_get_from_addr(dev_addr, ep_addr); - return !p_qhd->qtd_overlay.halted && (p_qhd->p_qtd_list_head != NULL); -} - -bool hcd_edpt_stalled(uint8_t dev_addr, uint8_t ep_addr) -{ - ehci_qhd_t *p_qhd = qhd_get_from_addr(dev_addr, ep_addr); - return p_qhd->qtd_overlay.halted && !qhd_has_xact_error(p_qhd); -} - -bool hcd_edpt_clear_stall(uint8_t dev_addr, uint8_t ep_addr) -{ - ehci_qhd_t *p_qhd = qhd_get_from_addr(dev_addr, ep_addr); - p_qhd->qtd_overlay.halted = 0; - // TODO reset data toggle ? - return true; -} - -//--------------------------------------------------------------------+ -// EHCI Interrupt Handler -//--------------------------------------------------------------------+ - -// async_advance is handshake between usb stack & ehci controller. -// This isr mean it is safe to modify previously removed queue head from async list. -// In tinyusb, queue head is only removed when device is unplugged. -static void async_advance_isr(uint8_t rhport) -{ - (void) rhport; - - ehci_qhd_t* qhd_pool = ehci_data.qhd_pool; - for(uint32_t i = 0; i < HCD_MAX_ENDPOINT; i++) - { - if ( qhd_pool[i].removing ) - { - qhd_pool[i].removing = 0; - qhd_pool[i].used = 0; - } - } -} - -static void port_connect_status_change_isr(uint8_t hostid) -{ - // NOTE There is an sequence plug->unplug->…..-> plug if device is powering with pre-plugged device - if (ehci_data.regs->portsc_bm.current_connect_status) - { - hcd_port_reset(hostid); - hcd_event_device_attach(hostid); - }else // device unplugged - { - hcd_event_device_remove(hostid); - } -} - -static void qhd_xfer_complete_isr(ehci_qhd_t * p_qhd) -{ - // free all TDs from the head td to the first active TD - while(p_qhd->p_qtd_list_head != NULL && !p_qhd->p_qtd_list_head->active) - { - // TD need to be freed and removed from qhd, before invoking callback - bool is_ioc = (p_qhd->p_qtd_list_head->int_on_complete != 0); - p_qhd->total_xferred_bytes += p_qhd->p_qtd_list_head->expected_bytes - p_qhd->p_qtd_list_head->total_bytes; - - p_qhd->p_qtd_list_head->used = 0; // free QTD - qtd_remove_1st_from_qhd(p_qhd); - - if (is_ioc) - { - // end of request - // call USBH callback - hcd_event_xfer_complete(p_qhd->dev_addr, tu_edpt_addr(p_qhd->ep_number, p_qhd->pid == EHCI_PID_IN ? 1 : 0), XFER_RESULT_SUCCESS, p_qhd->total_xferred_bytes); - p_qhd->total_xferred_bytes = 0; - } - } -} - -static void async_list_xfer_complete_isr(ehci_qhd_t * const async_head) -{ - ehci_qhd_t *p_qhd = async_head; - do - { - if ( !p_qhd->qtd_overlay.halted ) // halted or error is processed in error isr - { - qhd_xfer_complete_isr(p_qhd); - } - p_qhd = qhd_next(p_qhd); - }while(p_qhd != async_head); // async list traversal, stop if loop around -} - -static void period_list_xfer_complete_isr(uint8_t hostid, uint8_t interval_ms) -{ - uint8_t max_loop = 0; - uint32_t const period_1ms_addr = (uint32_t) get_period_head(hostid, 1); - ehci_link_t next_item = * get_period_head(hostid, interval_ms); - - // TODO abstract max loop guard for period - while( !next_item.terminate && - !(interval_ms > 1 && period_1ms_addr == tu_align32(next_item.address)) && - max_loop < (HCD_MAX_ENDPOINT + EHCI_MAX_ITD + EHCI_MAX_SITD)*CFG_TUSB_HOST_DEVICE_MAX) - { - switch ( next_item.type ) - { - case EHCI_QTYPE_QHD: - { - ehci_qhd_t *p_qhd_int = (ehci_qhd_t *) tu_align32(next_item.address); - if ( !p_qhd_int->qtd_overlay.halted ) - { - qhd_xfer_complete_isr(p_qhd_int); - } - } - break; - - case EHCI_QTYPE_ITD: // TODO support hs/fs ISO - case EHCI_QTYPE_SITD: - case EHCI_QTYPE_FSTN: - - default: break; - } - - next_item = *list_next(&next_item); - max_loop++; - } -} - -static void qhd_xfer_error_isr(ehci_qhd_t * p_qhd) -{ - if ( (p_qhd->dev_addr != 0 && p_qhd->qtd_overlay.halted) || // addr0 cannot be protocol STALL - qhd_has_xact_error(p_qhd) ) - { - // current qhd has error in transaction - xfer_result_t error_event; - - // no error bits are set, endpoint is halted due to STALL - error_event = qhd_has_xact_error(p_qhd) ? XFER_RESULT_FAILED : XFER_RESULT_STALLED; - - p_qhd->total_xferred_bytes += p_qhd->p_qtd_list_head->expected_bytes - p_qhd->p_qtd_list_head->total_bytes; - -// if ( XFER_RESULT_FAILED == error_event ) TU_BREAKPOINT(); // TODO skip unplugged device - - p_qhd->p_qtd_list_head->used = 0; // free QTD - qtd_remove_1st_from_qhd(p_qhd); - - if ( 0 == p_qhd->ep_number ) - { - // control cannot be halted --> clear all qtd list - p_qhd->p_qtd_list_head = NULL; - p_qhd->p_qtd_list_tail = NULL; - - p_qhd->qtd_overlay.next.terminate = 1; - p_qhd->qtd_overlay.alternate.terminate = 1; - p_qhd->qtd_overlay.halted = 0; - - ehci_qtd_t *p_setup = qtd_control(p_qhd->dev_addr); - p_setup->used = 0; - } - - // call USBH callback - hcd_event_xfer_complete(p_qhd->dev_addr, tu_edpt_addr(p_qhd->ep_number, p_qhd->pid == EHCI_PID_IN ? 1 : 0), error_event, p_qhd->total_xferred_bytes); - - p_qhd->total_xferred_bytes = 0; - } -} - -static void xfer_error_isr(uint8_t hostid) -{ - //------------- async list -------------// - ehci_qhd_t * const async_head = qhd_async_head(hostid); - ehci_qhd_t *p_qhd = async_head; - do - { - qhd_xfer_error_isr( p_qhd ); - p_qhd = qhd_next(p_qhd); - }while(p_qhd != async_head); // async list traversal, stop if loop around - - //------------- TODO refractor period list -------------// - uint32_t const period_1ms_addr = (uint32_t) get_period_head(hostid, 1); - for (uint8_t interval_ms=1; interval_ms <= EHCI_FRAMELIST_SIZE; interval_ms *= 2) - { - ehci_link_t next_item = * get_period_head(hostid, interval_ms); - - // TODO abstract max loop guard for period - while( !next_item.terminate && - !(interval_ms > 1 && period_1ms_addr == tu_align32(next_item.address)) ) - { - switch ( next_item.type ) - { - case EHCI_QTYPE_QHD: - { - ehci_qhd_t *p_qhd_int = (ehci_qhd_t *) tu_align32(next_item.address); - qhd_xfer_error_isr(p_qhd_int); - } - break; - - // TODO support hs/fs ISO - case EHCI_QTYPE_ITD: - case EHCI_QTYPE_SITD: - case EHCI_QTYPE_FSTN: - default: break; - } - - next_item = *list_next(&next_item); - } - } -} - -//------------- Host Controller Driver's Interrupt Handler -------------// -void hcd_isr(uint8_t rhport) -{ - ehci_registers_t* regs = ehci_data.regs; - - uint32_t int_status = regs->status; - int_status &= regs->inten; - - regs->status |= int_status; // Acknowledge handled interrupt - - if (int_status == 0) return; - - if (int_status & EHCI_INT_MASK_PORT_CHANGE) - { - uint32_t port_status = regs->portsc & EHCI_PORTSC_MASK_ALL; - - if (regs->portsc_bm.connect_status_change) - { - port_connect_status_change_isr(rhport); - } - - regs->portsc |= port_status; // Acknowledge change bits in portsc - } - - if (int_status & EHCI_INT_MASK_ERROR) - { - xfer_error_isr(rhport); - } - - //------------- some QTD/SITD/ITD with IOC set is completed -------------// - if (int_status & EHCI_INT_MASK_NXP_ASYNC) - { - async_list_xfer_complete_isr( qhd_async_head(rhport) ); - } - - if (int_status & EHCI_INT_MASK_NXP_PERIODIC) - { - for (uint8_t i=1; i <= EHCI_FRAMELIST_SIZE; i *= 2) - { - period_list_xfer_complete_isr( rhport, i ); - } - } - - //------------- There is some removed async previously -------------// - if (int_status & EHCI_INT_MASK_ASYNC_ADVANCE) // need to place after EHCI_INT_MASK_NXP_ASYNC - { - async_advance_isr(rhport); - } -} - -//--------------------------------------------------------------------+ -// HELPER -//--------------------------------------------------------------------+ - - -//------------- queue head helper -------------// -static inline ehci_qhd_t* qhd_find_free (void) -{ - for (uint32_t i=0; inext.address); -} - -static inline ehci_qhd_t* qhd_get_from_addr(uint8_t dev_addr, uint8_t ep_addr) -{ - ehci_qhd_t* qhd_pool = ehci_data.qhd_pool; - - for(uint32_t i=0; inext.address); -} - -static inline void qtd_remove_1st_from_qhd(ehci_qhd_t *p_qhd) -{ - if (p_qhd->p_qtd_list_head == p_qhd->p_qtd_list_tail) // last TD --> make it NULL - { - p_qhd->p_qtd_list_head = p_qhd->p_qtd_list_tail = NULL; - }else - { - p_qhd->p_qtd_list_head = qtd_next( p_qhd->p_qtd_list_head ); - } -} - -static inline void qtd_insert_to_qhd(ehci_qhd_t *p_qhd, ehci_qtd_t *p_qtd_new) -{ - if (p_qhd->p_qtd_list_head == NULL) // empty list - { - p_qhd->p_qtd_list_head = p_qhd->p_qtd_list_tail = p_qtd_new; - }else - { - p_qhd->p_qtd_list_tail->next.address = (uint32_t) p_qtd_new; - p_qhd->p_qtd_list_tail = p_qtd_new; - } -} - -static void qhd_init(ehci_qhd_t *p_qhd, uint8_t dev_addr, tusb_desc_endpoint_t const * ep_desc) -{ - // address 0 is used as async head, which always on the list --> cannot be cleared (ehci halted otherwise) - if (dev_addr != 0) - { - tu_memclr(p_qhd, sizeof(ehci_qhd_t)); - } - - uint8_t const xfer_type = ep_desc->bmAttributes.xfer; - uint8_t const interval = ep_desc->bInterval; - - p_qhd->dev_addr = dev_addr; - p_qhd->fl_inactive_next_xact = 0; - p_qhd->ep_number = tu_edpt_number(ep_desc->bEndpointAddress); - p_qhd->ep_speed = _usbh_devices[dev_addr].speed; - p_qhd->data_toggle_control= (xfer_type == TUSB_XFER_CONTROL) ? 1 : 0; - p_qhd->head_list_flag = (dev_addr == 0) ? 1 : 0; // addr0's endpoint is the static asyn list head - p_qhd->max_packet_size = ep_desc->wMaxPacketSize.size; - p_qhd->fl_ctrl_ep_flag = ((xfer_type == TUSB_XFER_CONTROL) && (p_qhd->ep_speed != TUSB_SPEED_HIGH)) ? 1 : 0; - p_qhd->nak_reload = 0; - - // Bulk/Control -> smask = cmask = 0 - // TODO Isochronous - if (TUSB_XFER_INTERRUPT == xfer_type) - { - if (TUSB_SPEED_HIGH == p_qhd->ep_speed) - { - TU_ASSERT( interval <= 16, ); - if ( interval < 4) // sub milisecond interval - { - p_qhd->interval_ms = 0; - p_qhd->int_smask = (interval == 1) ? TU_BIN8(11111111) : - (interval == 2) ? TU_BIN8(10101010) : TU_BIN8(01000100); - }else - { - p_qhd->interval_ms = (uint8_t) tu_min16( 1 << (interval-4), 255 ); - p_qhd->int_smask = TU_BIT(interval % 8); - } - }else - { - TU_ASSERT( 0 != interval, ); - // Full/Low: 4.12.2.1 (EHCI) case 1 schedule start split at 1 us & complete split at 2,3,4 uframes - p_qhd->int_smask = 0x01; - p_qhd->fl_int_cmask = TU_BIN8(11100); - p_qhd->interval_ms = interval; - } - }else - { - p_qhd->int_smask = p_qhd->fl_int_cmask = 0; - } - - p_qhd->fl_hub_addr = _usbh_devices[dev_addr].hub_addr; - p_qhd->fl_hub_port = _usbh_devices[dev_addr].hub_port; - p_qhd->mult = 1; // TODO not use high bandwidth/park mode yet - - //------------- HCD Management Data -------------// - p_qhd->used = 1; - p_qhd->removing = 0; - p_qhd->p_qtd_list_head = NULL; - p_qhd->p_qtd_list_tail = NULL; - p_qhd->pid = tu_edpt_dir(ep_desc->bEndpointAddress) ? EHCI_PID_IN : EHCI_PID_OUT; // PID for TD under this endpoint - - //------------- active, but no TD list -------------// - p_qhd->qtd_overlay.halted = 0; - p_qhd->qtd_overlay.next.terminate = 1; - p_qhd->qtd_overlay.alternate.terminate = 1; - if (TUSB_XFER_BULK == xfer_type && p_qhd->ep_speed == TUSB_SPEED_HIGH && p_qhd->pid == EHCI_PID_OUT) - { - p_qhd->qtd_overlay.ping_err = 1; // do PING for Highspeed Bulk OUT, EHCI section 4.11 - } -} - -static void qtd_init(ehci_qtd_t* p_qtd, void* buffer, uint16_t total_bytes) -{ - tu_memclr(p_qtd, sizeof(ehci_qtd_t)); - - p_qtd->used = 1; - - p_qtd->next.terminate = 1; // init to null - p_qtd->alternate.terminate = 1; // not used, always set to terminated - p_qtd->active = 1; - p_qtd->err_count = 3; // TODO 3 consecutive errors tolerance - p_qtd->data_toggle = 0; - p_qtd->total_bytes = total_bytes; - p_qtd->expected_bytes = total_bytes; - - p_qtd->buffer[0] = (uint32_t) buffer; - for(uint8_t i=1; i<5; i++) - { - p_qtd->buffer[i] |= tu_align4k( p_qtd->buffer[i-1] ) + 4096; - } -} - -//------------- List Managing Helper -------------// -static inline void list_insert(ehci_link_t *current, ehci_link_t *new, uint8_t new_type) -{ - new->address = current->address; - current->address = ((uint32_t) new) | (new_type << 1); -} - -static inline ehci_link_t* list_next(ehci_link_t *p_link_pointer) -{ - return (ehci_link_t*) tu_align32(p_link_pointer->address); -} - -#endif +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#include "common/tusb_common.h" + +#if TUSB_OPT_HOST_ENABLED && (CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX) +//--------------------------------------------------------------------+ +// INCLUDE +//--------------------------------------------------------------------+ +#include "osal/osal.h" + +#include "../hcd.h" +#include "../usbh_hcd.h" +#include "ehci.h" + +//--------------------------------------------------------------------+ +// MACRO CONSTANT TYPEDEF +//--------------------------------------------------------------------+ + +//--------------------------------------------------------------------+ +// INTERNAL OBJECT & FUNCTION DECLARATION +//--------------------------------------------------------------------+ +// Periodic frame list must be 4K alignment +CFG_TUSB_MEM_SECTION TU_ATTR_ALIGNED(4096) static ehci_data_t ehci_data; + +// EHCI portable +uint32_t hcd_ehci_register_addr(uint8_t rhport); + +//--------------------------------------------------------------------+ +// PROTOTYPE +//--------------------------------------------------------------------+ +static inline ehci_link_t* get_period_head(uint8_t rhport, uint8_t interval_ms) +{ + (void) rhport; + return (ehci_link_t*) &ehci_data.period_head_arr[ tu_log2( tu_min8(EHCI_FRAMELIST_SIZE, interval_ms) ) ]; +} + +static inline ehci_qhd_t* qhd_control(uint8_t dev_addr) +{ + return &ehci_data.control[dev_addr].qhd; +} + +static inline ehci_qhd_t* qhd_async_head(uint8_t rhport) +{ + (void) rhport; + return qhd_control(0); // control qhd of dev0 is used as async head +} + +static inline ehci_qtd_t* qtd_control(uint8_t dev_addr) +{ + return &ehci_data.control[dev_addr].qtd; +} + + +static inline ehci_qhd_t* qhd_next (ehci_qhd_t const * p_qhd); +static inline ehci_qhd_t* qhd_find_free (void); +static inline ehci_qhd_t* qhd_get_from_addr (uint8_t dev_addr, uint8_t ep_addr); + +// determine if a queue head has bus-related error +static inline bool qhd_has_xact_error (ehci_qhd_t * p_qhd) +{ + return (p_qhd->qtd_overlay.buffer_err || p_qhd->qtd_overlay.babble_err || p_qhd->qtd_overlay.xact_err); + //p_qhd->qtd_overlay.non_hs_period_missed_uframe || p_qhd->qtd_overlay.pingstate_err TODO split transaction error +} + +static void qhd_init (ehci_qhd_t *p_qhd, uint8_t dev_addr, tusb_desc_endpoint_t const * ep_desc); + +static inline ehci_qtd_t* qtd_find_free (void); +static inline ehci_qtd_t* qtd_next (ehci_qtd_t const * p_qtd); +static inline void qtd_insert_to_qhd (ehci_qhd_t *p_qhd, ehci_qtd_t *p_qtd_new); +static inline void qtd_remove_1st_from_qhd (ehci_qhd_t *p_qhd); +static void qtd_init (ehci_qtd_t* p_qtd, void* buffer, uint16_t total_bytes); + +static inline void list_insert (ehci_link_t *current, ehci_link_t *new, uint8_t new_type); +static inline ehci_link_t* list_next (ehci_link_t *p_link_pointer); + +static bool ehci_init (uint8_t rhport); + +//--------------------------------------------------------------------+ +// HCD API +//--------------------------------------------------------------------+ +bool hcd_init(void) +{ + tu_memclr(&ehci_data, sizeof(ehci_data_t)); + return ehci_init(TUH_OPT_RHPORT); +} + +void hcd_port_reset(uint8_t rhport) +{ + (void) rhport; + + ehci_registers_t* regs = ehci_data.regs; + + regs->portsc_bm.port_enabled = 0; // disable port before reset + regs->portsc_bm.port_reset = 1; +} + +bool hcd_port_connect_status(uint8_t rhport) +{ + (void) rhport; + return ehci_data.regs->portsc_bm.current_connect_status; +} + +tusb_speed_t hcd_port_speed_get(uint8_t rhport) +{ + (void) rhport; + return (tusb_speed_t) ehci_data.regs->portsc_bm.nxp_port_speed; // NXP specific port speed +} + +static void list_remove_qhd_by_addr(ehci_link_t* list_head, uint8_t dev_addr) +{ + for(ehci_link_t* prev = list_head; + !prev->terminate && (tu_align32(prev->address) != (uint32_t) list_head); + prev = list_next(prev) ) + { + // TODO check type for ISO iTD and siTD + ehci_qhd_t* qhd = (ehci_qhd_t*) list_next(prev); + if ( qhd->dev_addr == dev_addr ) + { + // TODO deactive all TD, wait for QHD to inactive before removal + prev->address = qhd->next.address; + + // EHCI 4.8.2 link the removed qhd to async head (which always reachable by Host Controller) + qhd->next.address = ((uint32_t) list_head) | (EHCI_QTYPE_QHD << 1); + + if ( qhd->int_smask ) + { + // period list queue element is guarantee to be free in the next frame (1 ms) + qhd->used = 0; + }else + { + // async list use async advance handshake + // mark as removing, will completely re-usable when async advance isr occurs + qhd->removing = 1; + } + } + } +} + +// Close all opened endpoint belong to this device +void hcd_device_close(uint8_t rhport, uint8_t dev_addr) +{ + // skip dev0 + if (dev_addr == 0) return; + + // Remove from async list + list_remove_qhd_by_addr( (ehci_link_t*) qhd_async_head(rhport), dev_addr ); + + // Remove from all interval period list + for(uint8_t i = 0; i < TU_ARRAY_SIZE(ehci_data.period_head_arr); i++) + { + list_remove_qhd_by_addr( (ehci_link_t*) &ehci_data.period_head_arr[i], dev_addr); + } + + // Async doorbell (EHCI 4.8.2 for operational details) + ehci_data.regs->command_bm.async_adv_doorbell = 1; +} + +// EHCI controller init +static bool ehci_init(uint8_t rhport) +{ + ehci_data.regs = (ehci_registers_t* ) hcd_ehci_register_addr(rhport); + + ehci_registers_t* regs = ehci_data.regs; + + //------------- CTRLDSSEGMENT Register (skip) -------------// + //------------- USB INT Register -------------// + regs->inten = 0; // 1. disable all the interrupt + regs->status = EHCI_INT_MASK_ALL; // 2. clear all status + + regs->inten = EHCI_INT_MASK_ERROR | EHCI_INT_MASK_PORT_CHANGE | EHCI_INT_MASK_ASYNC_ADVANCE | + EHCI_INT_MASK_NXP_PERIODIC | EHCI_INT_MASK_NXP_ASYNC ; + + //------------- Asynchronous List -------------// + ehci_qhd_t * const async_head = qhd_async_head(rhport); + tu_memclr(async_head, sizeof(ehci_qhd_t)); + + async_head->next.address = (uint32_t) async_head; // circular list, next is itself + async_head->next.type = EHCI_QTYPE_QHD; + async_head->head_list_flag = 1; + async_head->qtd_overlay.halted = 1; // inactive most of time + async_head->qtd_overlay.next.terminate = 1; // TODO removed if verified + + regs->async_list_addr = (uint32_t) async_head; + + //------------- Periodic List -------------// + // Build the polling interval tree with 1 ms, 2 ms, 4 ms and 8 ms (framesize) only + for(uint32_t i=0; i<4; i++) + { + ehci_data.period_head_arr[i].int_smask = 1; // queue head in period list must have smask non-zero + ehci_data.period_head_arr[i].qtd_overlay.halted = 1; // dummy node, always inactive + } + + ehci_link_t * const framelist = ehci_data.period_framelist; + ehci_link_t * const period_1ms = get_period_head(rhport, 1); + // all links --> period_head_arr[0] (1ms) + // 0, 2, 4, 6 etc --> period_head_arr[1] (2ms) + // 1, 5 --> period_head_arr[2] (4ms) + // 3 --> period_head_arr[3] (8ms) + + // TODO EHCI_FRAMELIST_SIZE with other size than 8 + for(uint32_t i=0; iterminate = 1; + + regs->periodic_list_base = (uint32_t) framelist; + + //------------- TT Control (NXP only) -------------// + regs->nxp_tt_control = 0; + + //------------- USB CMD Register -------------// + regs->command |= TU_BIT(EHCI_USBCMD_POS_RUN_STOP) | TU_BIT(EHCI_USBCMD_POS_ASYNC_ENABLE) + | TU_BIT(EHCI_USBCMD_POS_PERIOD_ENABLE) // TODO enable period list only there is int/iso endpoint + | ((EHCI_CFG_FRAMELIST_SIZE_BITS & TU_BIN8(011)) << EHCI_USBCMD_POS_FRAMELIST_SZIE) + | ((EHCI_CFG_FRAMELIST_SIZE_BITS >> 2) << EHCI_USBCMD_POS_NXP_FRAMELIST_SIZE_MSB); + + //------------- ConfigFlag Register (skip) -------------// + regs->portsc_bm.port_power = 1; // enable port power + + return true; +} + +#if 0 +static void ehci_stop(uint8_t rhport) +{ + (void) rhport; + + ehci_registers_t* regs = ehci_data.regs; + + regs->command_bm.run_stop = 0; + + // USB Spec: controller has to stop within 16 uframe = 2 frames + while( regs->status_bm.hc_halted == 0 ) {} +} +#endif + +//--------------------------------------------------------------------+ +// CONTROL PIPE API +//--------------------------------------------------------------------+ +bool hcd_edpt_xfer(uint8_t rhport, uint8_t dev_addr, uint8_t ep_addr, uint8_t * buffer, uint16_t buflen) +{ + (void) rhport; + + uint8_t const epnum = tu_edpt_number(ep_addr); + uint8_t const dir = tu_edpt_dir(ep_addr); + + // FIXME control only for now + if ( epnum == 0 ) + { + ehci_qhd_t* qhd = qhd_control(dev_addr); + ehci_qtd_t* qtd = qtd_control(dev_addr); + + qtd_init(qtd, buffer, buflen); + + // first first data toggle is always 1 (data & setup stage) + qtd->data_toggle = 1; + qtd->pid = dir ? EHCI_PID_IN : EHCI_PID_OUT; + qtd->int_on_complete = 1; + qtd->next.terminate = 1; + + // sw region + qhd->p_qtd_list_head = qtd; + qhd->p_qtd_list_tail = qtd; + + // attach TD + qhd->qtd_overlay.next.address = (uint32_t) qtd; + } + + return true; +} + +bool hcd_setup_send(uint8_t rhport, uint8_t dev_addr, uint8_t const setup_packet[8]) +{ + (void) rhport; + + ehci_qhd_t* qhd = &ehci_data.control[dev_addr].qhd; + ehci_qtd_t* td = &ehci_data.control[dev_addr].qtd; + + qtd_init(td, (void*) setup_packet, 8); + td->pid = EHCI_PID_SETUP; + td->int_on_complete = 1; + td->next.terminate = 1; + + // sw region + qhd->p_qtd_list_head = td; + qhd->p_qtd_list_tail = td; + + // attach TD + qhd->qtd_overlay.next.address = (uint32_t) td; + + return true; +} + +//--------------------------------------------------------------------+ +// BULK/INT/ISO PIPE API +//--------------------------------------------------------------------+ +bool hcd_edpt_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_endpoint_t const * ep_desc) +{ + (void) rhport; + + // TODO not support ISO yet + TU_ASSERT (ep_desc->bmAttributes.xfer != TUSB_XFER_ISOCHRONOUS); + + //------------- Prepare Queue Head -------------// + ehci_qhd_t * p_qhd; + + if ( ep_desc->bEndpointAddress == 0 ) + { + p_qhd = qhd_control(dev_addr); + }else + { + p_qhd = qhd_find_free(); + } + TU_ASSERT(p_qhd); + + qhd_init(p_qhd, dev_addr, ep_desc); + + // control of dev0 is always present as async head + if ( dev_addr == 0 ) return true; + + // Insert to list + ehci_link_t * list_head; + + switch (ep_desc->bmAttributes.xfer) + { + case TUSB_XFER_CONTROL: + case TUSB_XFER_BULK: + list_head = (ehci_link_t*) qhd_async_head(rhport); + break; + + case TUSB_XFER_INTERRUPT: + list_head = get_period_head(rhport, p_qhd->interval_ms); + break; + + case TUSB_XFER_ISOCHRONOUS: + // TODO iso is not supported + break; + + default: break; + } + + // TODO might need to disable async/period list + list_insert( list_head, (ehci_link_t*) p_qhd, EHCI_QTYPE_QHD); + + return true; +} + +bool hcd_pipe_queue_xfer(uint8_t dev_addr, uint8_t ep_addr, uint8_t buffer[], uint16_t total_bytes) +{ + //------------- set up QTD -------------// + ehci_qhd_t *p_qhd = qhd_get_from_addr(dev_addr, ep_addr); + ehci_qtd_t *p_qtd = qtd_find_free(); + + TU_ASSERT(p_qtd); + + qtd_init(p_qtd, buffer, total_bytes); + p_qtd->pid = p_qhd->pid; + + //------------- insert TD to TD list -------------// + qtd_insert_to_qhd(p_qhd, p_qtd); + + return true; +} + +bool hcd_pipe_xfer(uint8_t dev_addr, uint8_t ep_addr, uint8_t buffer[], uint16_t total_bytes, bool int_on_complete) +{ + TU_ASSERT ( hcd_pipe_queue_xfer(dev_addr, ep_addr, buffer, total_bytes) ); + + ehci_qhd_t *p_qhd = qhd_get_from_addr(dev_addr, ep_addr); + + if ( int_on_complete ) + { // the just added qtd is pointed by list_tail + p_qhd->p_qtd_list_tail->int_on_complete = 1; + } + p_qhd->qtd_overlay.next.address = (uint32_t) p_qhd->p_qtd_list_head; // attach head QTD to QHD start transferring + + return true; +} + +bool hcd_edpt_busy(uint8_t dev_addr, uint8_t ep_addr) +{ + ehci_qhd_t *p_qhd = qhd_get_from_addr(dev_addr, ep_addr); + return !p_qhd->qtd_overlay.halted && (p_qhd->p_qtd_list_head != NULL); +} + +bool hcd_edpt_stalled(uint8_t dev_addr, uint8_t ep_addr) +{ + ehci_qhd_t *p_qhd = qhd_get_from_addr(dev_addr, ep_addr); + return p_qhd->qtd_overlay.halted && !qhd_has_xact_error(p_qhd); +} + +bool hcd_edpt_clear_stall(uint8_t dev_addr, uint8_t ep_addr) +{ + ehci_qhd_t *p_qhd = qhd_get_from_addr(dev_addr, ep_addr); + p_qhd->qtd_overlay.halted = 0; + // TODO reset data toggle ? + return true; +} + +//--------------------------------------------------------------------+ +// EHCI Interrupt Handler +//--------------------------------------------------------------------+ + +// async_advance is handshake between usb stack & ehci controller. +// This isr mean it is safe to modify previously removed queue head from async list. +// In tinyusb, queue head is only removed when device is unplugged. +static void async_advance_isr(uint8_t rhport) +{ + (void) rhport; + + ehci_qhd_t* qhd_pool = ehci_data.qhd_pool; + for(uint32_t i = 0; i < HCD_MAX_ENDPOINT; i++) + { + if ( qhd_pool[i].removing ) + { + qhd_pool[i].removing = 0; + qhd_pool[i].used = 0; + } + } +} + +static void port_connect_status_change_isr(uint8_t hostid) +{ + // NOTE There is an sequence plug->unplug->…..-> plug if device is powering with pre-plugged device + if (ehci_data.regs->portsc_bm.current_connect_status) + { + hcd_port_reset(hostid); + hcd_event_device_attach(hostid); + }else // device unplugged + { + hcd_event_device_remove(hostid); + } +} + +static void qhd_xfer_complete_isr(ehci_qhd_t * p_qhd) +{ + // free all TDs from the head td to the first active TD + while(p_qhd->p_qtd_list_head != NULL && !p_qhd->p_qtd_list_head->active) + { + // TD need to be freed and removed from qhd, before invoking callback + bool is_ioc = (p_qhd->p_qtd_list_head->int_on_complete != 0); + p_qhd->total_xferred_bytes += p_qhd->p_qtd_list_head->expected_bytes - p_qhd->p_qtd_list_head->total_bytes; + + p_qhd->p_qtd_list_head->used = 0; // free QTD + qtd_remove_1st_from_qhd(p_qhd); + + if (is_ioc) + { + // end of request + // call USBH callback + hcd_event_xfer_complete(p_qhd->dev_addr, tu_edpt_addr(p_qhd->ep_number, p_qhd->pid == EHCI_PID_IN ? 1 : 0), XFER_RESULT_SUCCESS, p_qhd->total_xferred_bytes); + p_qhd->total_xferred_bytes = 0; + } + } +} + +static void async_list_xfer_complete_isr(ehci_qhd_t * const async_head) +{ + ehci_qhd_t *p_qhd = async_head; + do + { + if ( !p_qhd->qtd_overlay.halted ) // halted or error is processed in error isr + { + qhd_xfer_complete_isr(p_qhd); + } + p_qhd = qhd_next(p_qhd); + }while(p_qhd != async_head); // async list traversal, stop if loop around +} + +static void period_list_xfer_complete_isr(uint8_t hostid, uint8_t interval_ms) +{ + uint8_t max_loop = 0; + uint32_t const period_1ms_addr = (uint32_t) get_period_head(hostid, 1); + ehci_link_t next_item = * get_period_head(hostid, interval_ms); + + // TODO abstract max loop guard for period + while( !next_item.terminate && + !(interval_ms > 1 && period_1ms_addr == tu_align32(next_item.address)) && + max_loop < (HCD_MAX_ENDPOINT + EHCI_MAX_ITD + EHCI_MAX_SITD)*CFG_TUSB_HOST_DEVICE_MAX) + { + switch ( next_item.type ) + { + case EHCI_QTYPE_QHD: + { + ehci_qhd_t *p_qhd_int = (ehci_qhd_t *) tu_align32(next_item.address); + if ( !p_qhd_int->qtd_overlay.halted ) + { + qhd_xfer_complete_isr(p_qhd_int); + } + } + break; + + case EHCI_QTYPE_ITD: // TODO support hs/fs ISO + case EHCI_QTYPE_SITD: + case EHCI_QTYPE_FSTN: + + default: break; + } + + next_item = *list_next(&next_item); + max_loop++; + } +} + +static void qhd_xfer_error_isr(ehci_qhd_t * p_qhd) +{ + if ( (p_qhd->dev_addr != 0 && p_qhd->qtd_overlay.halted) || // addr0 cannot be protocol STALL + qhd_has_xact_error(p_qhd) ) + { + // current qhd has error in transaction + xfer_result_t error_event; + + // no error bits are set, endpoint is halted due to STALL + error_event = qhd_has_xact_error(p_qhd) ? XFER_RESULT_FAILED : XFER_RESULT_STALLED; + + p_qhd->total_xferred_bytes += p_qhd->p_qtd_list_head->expected_bytes - p_qhd->p_qtd_list_head->total_bytes; + +// if ( XFER_RESULT_FAILED == error_event ) TU_BREAKPOINT(); // TODO skip unplugged device + + p_qhd->p_qtd_list_head->used = 0; // free QTD + qtd_remove_1st_from_qhd(p_qhd); + + if ( 0 == p_qhd->ep_number ) + { + // control cannot be halted --> clear all qtd list + p_qhd->p_qtd_list_head = NULL; + p_qhd->p_qtd_list_tail = NULL; + + p_qhd->qtd_overlay.next.terminate = 1; + p_qhd->qtd_overlay.alternate.terminate = 1; + p_qhd->qtd_overlay.halted = 0; + + ehci_qtd_t *p_setup = qtd_control(p_qhd->dev_addr); + p_setup->used = 0; + } + + // call USBH callback + hcd_event_xfer_complete(p_qhd->dev_addr, tu_edpt_addr(p_qhd->ep_number, p_qhd->pid == EHCI_PID_IN ? 1 : 0), error_event, p_qhd->total_xferred_bytes); + + p_qhd->total_xferred_bytes = 0; + } +} + +static void xfer_error_isr(uint8_t hostid) +{ + //------------- async list -------------// + ehci_qhd_t * const async_head = qhd_async_head(hostid); + ehci_qhd_t *p_qhd = async_head; + do + { + qhd_xfer_error_isr( p_qhd ); + p_qhd = qhd_next(p_qhd); + }while(p_qhd != async_head); // async list traversal, stop if loop around + + //------------- TODO refractor period list -------------// + uint32_t const period_1ms_addr = (uint32_t) get_period_head(hostid, 1); + for (uint8_t interval_ms=1; interval_ms <= EHCI_FRAMELIST_SIZE; interval_ms *= 2) + { + ehci_link_t next_item = * get_period_head(hostid, interval_ms); + + // TODO abstract max loop guard for period + while( !next_item.terminate && + !(interval_ms > 1 && period_1ms_addr == tu_align32(next_item.address)) ) + { + switch ( next_item.type ) + { + case EHCI_QTYPE_QHD: + { + ehci_qhd_t *p_qhd_int = (ehci_qhd_t *) tu_align32(next_item.address); + qhd_xfer_error_isr(p_qhd_int); + } + break; + + // TODO support hs/fs ISO + case EHCI_QTYPE_ITD: + case EHCI_QTYPE_SITD: + case EHCI_QTYPE_FSTN: + default: break; + } + + next_item = *list_next(&next_item); + } + } +} + +//------------- Host Controller Driver's Interrupt Handler -------------// +void hcd_isr(uint8_t rhport) +{ + ehci_registers_t* regs = ehci_data.regs; + + uint32_t int_status = regs->status; + int_status &= regs->inten; + + regs->status |= int_status; // Acknowledge handled interrupt + + if (int_status == 0) return; + + if (int_status & EHCI_INT_MASK_PORT_CHANGE) + { + uint32_t port_status = regs->portsc & EHCI_PORTSC_MASK_ALL; + + if (regs->portsc_bm.connect_status_change) + { + port_connect_status_change_isr(rhport); + } + + regs->portsc |= port_status; // Acknowledge change bits in portsc + } + + if (int_status & EHCI_INT_MASK_ERROR) + { + xfer_error_isr(rhport); + } + + //------------- some QTD/SITD/ITD with IOC set is completed -------------// + if (int_status & EHCI_INT_MASK_NXP_ASYNC) + { + async_list_xfer_complete_isr( qhd_async_head(rhport) ); + } + + if (int_status & EHCI_INT_MASK_NXP_PERIODIC) + { + for (uint8_t i=1; i <= EHCI_FRAMELIST_SIZE; i *= 2) + { + period_list_xfer_complete_isr( rhport, i ); + } + } + + //------------- There is some removed async previously -------------// + if (int_status & EHCI_INT_MASK_ASYNC_ADVANCE) // need to place after EHCI_INT_MASK_NXP_ASYNC + { + async_advance_isr(rhport); + } +} + +//--------------------------------------------------------------------+ +// HELPER +//--------------------------------------------------------------------+ + + +//------------- queue head helper -------------// +static inline ehci_qhd_t* qhd_find_free (void) +{ + for (uint32_t i=0; inext.address); +} + +static inline ehci_qhd_t* qhd_get_from_addr(uint8_t dev_addr, uint8_t ep_addr) +{ + ehci_qhd_t* qhd_pool = ehci_data.qhd_pool; + + for(uint32_t i=0; inext.address); +} + +static inline void qtd_remove_1st_from_qhd(ehci_qhd_t *p_qhd) +{ + if (p_qhd->p_qtd_list_head == p_qhd->p_qtd_list_tail) // last TD --> make it NULL + { + p_qhd->p_qtd_list_head = p_qhd->p_qtd_list_tail = NULL; + }else + { + p_qhd->p_qtd_list_head = qtd_next( p_qhd->p_qtd_list_head ); + } +} + +static inline void qtd_insert_to_qhd(ehci_qhd_t *p_qhd, ehci_qtd_t *p_qtd_new) +{ + if (p_qhd->p_qtd_list_head == NULL) // empty list + { + p_qhd->p_qtd_list_head = p_qhd->p_qtd_list_tail = p_qtd_new; + }else + { + p_qhd->p_qtd_list_tail->next.address = (uint32_t) p_qtd_new; + p_qhd->p_qtd_list_tail = p_qtd_new; + } +} + +static void qhd_init(ehci_qhd_t *p_qhd, uint8_t dev_addr, tusb_desc_endpoint_t const * ep_desc) +{ + // address 0 is used as async head, which always on the list --> cannot be cleared (ehci halted otherwise) + if (dev_addr != 0) + { + tu_memclr(p_qhd, sizeof(ehci_qhd_t)); + } + + uint8_t const xfer_type = ep_desc->bmAttributes.xfer; + uint8_t const interval = ep_desc->bInterval; + + p_qhd->dev_addr = dev_addr; + p_qhd->fl_inactive_next_xact = 0; + p_qhd->ep_number = tu_edpt_number(ep_desc->bEndpointAddress); + p_qhd->ep_speed = _usbh_devices[dev_addr].speed; + p_qhd->data_toggle_control= (xfer_type == TUSB_XFER_CONTROL) ? 1 : 0; + p_qhd->head_list_flag = (dev_addr == 0) ? 1 : 0; // addr0's endpoint is the static asyn list head + p_qhd->max_packet_size = ep_desc->wMaxPacketSize.size; + p_qhd->fl_ctrl_ep_flag = ((xfer_type == TUSB_XFER_CONTROL) && (p_qhd->ep_speed != TUSB_SPEED_HIGH)) ? 1 : 0; + p_qhd->nak_reload = 0; + + // Bulk/Control -> smask = cmask = 0 + // TODO Isochronous + if (TUSB_XFER_INTERRUPT == xfer_type) + { + if (TUSB_SPEED_HIGH == p_qhd->ep_speed) + { + TU_ASSERT( interval <= 16, ); + if ( interval < 4) // sub milisecond interval + { + p_qhd->interval_ms = 0; + p_qhd->int_smask = (interval == 1) ? TU_BIN8(11111111) : + (interval == 2) ? TU_BIN8(10101010) : TU_BIN8(01000100); + }else + { + p_qhd->interval_ms = (uint8_t) tu_min16( 1 << (interval-4), 255 ); + p_qhd->int_smask = TU_BIT(interval % 8); + } + }else + { + TU_ASSERT( 0 != interval, ); + // Full/Low: 4.12.2.1 (EHCI) case 1 schedule start split at 1 us & complete split at 2,3,4 uframes + p_qhd->int_smask = 0x01; + p_qhd->fl_int_cmask = TU_BIN8(11100); + p_qhd->interval_ms = interval; + } + }else + { + p_qhd->int_smask = p_qhd->fl_int_cmask = 0; + } + + p_qhd->fl_hub_addr = _usbh_devices[dev_addr].hub_addr; + p_qhd->fl_hub_port = _usbh_devices[dev_addr].hub_port; + p_qhd->mult = 1; // TODO not use high bandwidth/park mode yet + + //------------- HCD Management Data -------------// + p_qhd->used = 1; + p_qhd->removing = 0; + p_qhd->p_qtd_list_head = NULL; + p_qhd->p_qtd_list_tail = NULL; + p_qhd->pid = tu_edpt_dir(ep_desc->bEndpointAddress) ? EHCI_PID_IN : EHCI_PID_OUT; // PID for TD under this endpoint + + //------------- active, but no TD list -------------// + p_qhd->qtd_overlay.halted = 0; + p_qhd->qtd_overlay.next.terminate = 1; + p_qhd->qtd_overlay.alternate.terminate = 1; + if (TUSB_XFER_BULK == xfer_type && p_qhd->ep_speed == TUSB_SPEED_HIGH && p_qhd->pid == EHCI_PID_OUT) + { + p_qhd->qtd_overlay.ping_err = 1; // do PING for Highspeed Bulk OUT, EHCI section 4.11 + } +} + +static void qtd_init(ehci_qtd_t* p_qtd, void* buffer, uint16_t total_bytes) +{ + tu_memclr(p_qtd, sizeof(ehci_qtd_t)); + + p_qtd->used = 1; + + p_qtd->next.terminate = 1; // init to null + p_qtd->alternate.terminate = 1; // not used, always set to terminated + p_qtd->active = 1; + p_qtd->err_count = 3; // TODO 3 consecutive errors tolerance + p_qtd->data_toggle = 0; + p_qtd->total_bytes = total_bytes; + p_qtd->expected_bytes = total_bytes; + + p_qtd->buffer[0] = (uint32_t) buffer; + for(uint8_t i=1; i<5; i++) + { + p_qtd->buffer[i] |= tu_align4k( p_qtd->buffer[i-1] ) + 4096; + } +} + +//------------- List Managing Helper -------------// +static inline void list_insert(ehci_link_t *current, ehci_link_t *new, uint8_t new_type) +{ + new->address = current->address; + current->address = ((uint32_t) new) | (new_type << 1); +} + +static inline ehci_link_t* list_next(ehci_link_t *p_link_pointer) +{ + return (ehci_link_t*) tu_align32(p_link_pointer->address); +} + +#endif diff --git a/src/host/hcd.h b/src/host/hcd.h index 97dc3ebf..a39e7fe1 100644 --- a/src/host/hcd.h +++ b/src/host/hcd.h @@ -1,147 +1,147 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2019 Ha Thach (tinyusb.org) - * - * 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. - * - * This file is part of the TinyUSB stack. - */ - -/** \ingroup group_usbh - * \defgroup Group_HCD Host Controller Driver (HCD) - * @{ */ - -#ifndef _TUSB_HCD_H_ -#define _TUSB_HCD_H_ - -#include - -#ifdef __cplusplus - extern "C" { -#endif - - //--------------------------------------------------------------------+ -// MACRO CONSTANT TYPEDEF -//--------------------------------------------------------------------+ -typedef enum -{ - HCD_EVENT_DEVICE_ATTACH, - HCD_EVENT_DEVICE_REMOVE, - HCD_EVENT_XFER_COMPLETE, -} hcd_eventid_t; - -typedef struct -{ - uint8_t rhport; - uint8_t event_id; - - union - { - struct - { - uint8_t hub_addr; - uint8_t hub_port; - } attach, remove; - - struct - { - uint8_t ep_addr; - uint8_t result; - uint32_t len; - } xfer_complete; - }; - -} hcd_event_t; - -#if TUSB_OPT_HOST_ENABLED -// Max number of endpoints per device -enum { - HCD_MAX_ENDPOINT = CFG_TUSB_HOST_DEVICE_MAX*(CFG_TUH_HUB + CFG_TUH_HID_KEYBOARD + CFG_TUH_HID_MOUSE + CFG_TUSB_HOST_HID_GENERIC + - CFG_TUH_MSC*2 + CFG_TUH_CDC*3), - - HCD_MAX_XFER = HCD_MAX_ENDPOINT*2, -}; - -//#define HCD_MAX_ENDPOINT 16 -//#define HCD_MAX_XFER 16 -#endif - -//--------------------------------------------------------------------+ -// HCD API -//--------------------------------------------------------------------+ -bool hcd_init(void); -void hcd_isr(uint8_t hostid); -void hcd_int_enable (uint8_t rhport); -void hcd_int_disable(uint8_t rhport); - -// PORT API -/// return the current connect status of roothub port -bool hcd_port_connect_status(uint8_t hostid); -void hcd_port_reset(uint8_t hostid); -tusb_speed_t hcd_port_speed_get(uint8_t hostid); - -// HCD closes all opened endpoints belong to this device -void hcd_device_close(uint8_t rhport, uint8_t dev_addr); - -//--------------------------------------------------------------------+ -// Event function -//--------------------------------------------------------------------+ -void hcd_event_handler(hcd_event_t const* event, bool in_isr); - -// Helper to send device attach event -void hcd_event_device_attach(uint8_t rhport); - -// Helper to send device removal event -void hcd_event_device_remove(uint8_t rhport); - -// Helper to send USB transfer event -void hcd_event_xfer_complete(uint8_t dev_addr, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes); - -//--------------------------------------------------------------------+ -// Endpoints API -//--------------------------------------------------------------------+ -bool hcd_setup_send(uint8_t rhport, uint8_t dev_addr, uint8_t const setup_packet[8]); -bool hcd_edpt_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_endpoint_t const * ep_desc); - -bool hcd_edpt_busy(uint8_t dev_addr, uint8_t ep_addr); -bool hcd_edpt_stalled(uint8_t dev_addr, uint8_t ep_addr); -bool hcd_edpt_clear_stall(uint8_t dev_addr, uint8_t ep_addr); - -// TODO merge with pipe_xfer -bool hcd_edpt_xfer(uint8_t rhport, uint8_t dev_addr, uint8_t ep_addr, uint8_t * buffer, uint16_t buflen); - -//--------------------------------------------------------------------+ -// PIPE API -//--------------------------------------------------------------------+ -// TODO control xfer should be used via usbh layer -bool hcd_pipe_queue_xfer(uint8_t dev_addr, uint8_t ep_addr, uint8_t buffer[], uint16_t total_bytes); // only queue, not transferring yet -bool hcd_pipe_xfer(uint8_t dev_addr, uint8_t ep_addr, uint8_t buffer[], uint16_t total_bytes, bool int_on_complete); - -#if 0 -tusb_error_t hcd_pipe_cancel(); -#endif - -#ifdef __cplusplus - } -#endif - -#endif /* _TUSB_HCD_H_ */ - -/// @} +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +/** \ingroup group_usbh + * \defgroup Group_HCD Host Controller Driver (HCD) + * @{ */ + +#ifndef _TUSB_HCD_H_ +#define _TUSB_HCD_H_ + +#include + +#ifdef __cplusplus + extern "C" { +#endif + + //--------------------------------------------------------------------+ +// MACRO CONSTANT TYPEDEF +//--------------------------------------------------------------------+ +typedef enum +{ + HCD_EVENT_DEVICE_ATTACH, + HCD_EVENT_DEVICE_REMOVE, + HCD_EVENT_XFER_COMPLETE, +} hcd_eventid_t; + +typedef struct +{ + uint8_t rhport; + uint8_t event_id; + + union + { + struct + { + uint8_t hub_addr; + uint8_t hub_port; + } attach, remove; + + struct + { + uint8_t ep_addr; + uint8_t result; + uint32_t len; + } xfer_complete; + }; + +} hcd_event_t; + +#if TUSB_OPT_HOST_ENABLED +// Max number of endpoints per device +enum { + HCD_MAX_ENDPOINT = CFG_TUSB_HOST_DEVICE_MAX*(CFG_TUH_HUB + CFG_TUH_HID_KEYBOARD + CFG_TUH_HID_MOUSE + CFG_TUSB_HOST_HID_GENERIC + + CFG_TUH_MSC*2 + CFG_TUH_CDC*3), + + HCD_MAX_XFER = HCD_MAX_ENDPOINT*2, +}; + +//#define HCD_MAX_ENDPOINT 16 +//#define HCD_MAX_XFER 16 +#endif + +//--------------------------------------------------------------------+ +// HCD API +//--------------------------------------------------------------------+ +bool hcd_init(void); +void hcd_isr(uint8_t hostid); +void hcd_int_enable (uint8_t rhport); +void hcd_int_disable(uint8_t rhport); + +// PORT API +/// return the current connect status of roothub port +bool hcd_port_connect_status(uint8_t hostid); +void hcd_port_reset(uint8_t hostid); +tusb_speed_t hcd_port_speed_get(uint8_t hostid); + +// HCD closes all opened endpoints belong to this device +void hcd_device_close(uint8_t rhport, uint8_t dev_addr); + +//--------------------------------------------------------------------+ +// Event function +//--------------------------------------------------------------------+ +void hcd_event_handler(hcd_event_t const* event, bool in_isr); + +// Helper to send device attach event +void hcd_event_device_attach(uint8_t rhport); + +// Helper to send device removal event +void hcd_event_device_remove(uint8_t rhport); + +// Helper to send USB transfer event +void hcd_event_xfer_complete(uint8_t dev_addr, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes); + +//--------------------------------------------------------------------+ +// Endpoints API +//--------------------------------------------------------------------+ +bool hcd_setup_send(uint8_t rhport, uint8_t dev_addr, uint8_t const setup_packet[8]); +bool hcd_edpt_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_endpoint_t const * ep_desc); + +bool hcd_edpt_busy(uint8_t dev_addr, uint8_t ep_addr); +bool hcd_edpt_stalled(uint8_t dev_addr, uint8_t ep_addr); +bool hcd_edpt_clear_stall(uint8_t dev_addr, uint8_t ep_addr); + +// TODO merge with pipe_xfer +bool hcd_edpt_xfer(uint8_t rhport, uint8_t dev_addr, uint8_t ep_addr, uint8_t * buffer, uint16_t buflen); + +//--------------------------------------------------------------------+ +// PIPE API +//--------------------------------------------------------------------+ +// TODO control xfer should be used via usbh layer +bool hcd_pipe_queue_xfer(uint8_t dev_addr, uint8_t ep_addr, uint8_t buffer[], uint16_t total_bytes); // only queue, not transferring yet +bool hcd_pipe_xfer(uint8_t dev_addr, uint8_t ep_addr, uint8_t buffer[], uint16_t total_bytes, bool int_on_complete); + +#if 0 +tusb_error_t hcd_pipe_cancel(); +#endif + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_HCD_H_ */ + +/// @} diff --git a/src/host/hub.c b/src/host/hub.c index a2d4e842..00450b70 100644 --- a/src/host/hub.c +++ b/src/host/hub.c @@ -1,250 +1,250 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2019 Ha Thach (tinyusb.org) - * - * 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. - * - * This file is part of the TinyUSB stack. - */ - -#include "tusb_option.h" - -#if (TUSB_OPT_HOST_ENABLED && CFG_TUH_HUB) - -//--------------------------------------------------------------------+ -// INCLUDE -//--------------------------------------------------------------------+ -#include "hub.h" - -//--------------------------------------------------------------------+ -// MACRO CONSTANT TYPEDEF -//--------------------------------------------------------------------+ -typedef struct -{ - uint8_t itf_num; - uint8_t ep_status; - uint8_t port_number; - uint8_t status_change; // data from status change interrupt endpoint -}usbh_hub_t; - -CFG_TUSB_MEM_SECTION static usbh_hub_t hub_data[CFG_TUSB_HOST_DEVICE_MAX]; -TU_ATTR_ALIGNED(4) CFG_TUSB_MEM_SECTION static uint8_t hub_enum_buffer[sizeof(descriptor_hub_desc_t)]; - -//OSAL_SEM_DEF(hub_enum_semaphore); -//static osal_semaphore_handle_t hub_enum_sem_hdl; - -//--------------------------------------------------------------------+ -// HUB -//--------------------------------------------------------------------+ -bool hub_port_clear_feature_subtask(uint8_t hub_addr, uint8_t hub_port, uint8_t feature) -{ - TU_ASSERT(HUB_FEATURE_PORT_CONNECTION_CHANGE <= feature && feature <= HUB_FEATURE_PORT_RESET_CHANGE); - - tusb_control_request_t request = { - .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_OTHER, .type = TUSB_REQ_TYPE_CLASS, .direction = TUSB_DIR_OUT }, - .bRequest = HUB_REQUEST_CLEAR_FEATURE, - .wValue = feature, - .wIndex = hub_port, - .wLength = 0 - }; - - //------------- Clear Port Feature request -------------// - TU_ASSERT( usbh_control_xfer( hub_addr, &request, NULL ) ); - - //------------- Get Port Status to check if feature is cleared -------------// - request = (tusb_control_request_t ) { - .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_OTHER, .type = TUSB_REQ_TYPE_CLASS, .direction = TUSB_DIR_IN }, - .bRequest = HUB_REQUEST_GET_STATUS, - .wValue = 0, - .wIndex = hub_port, - .wLength = 4 - }; - - TU_ASSERT( usbh_control_xfer( hub_addr, &request, hub_enum_buffer ) ); - - //------------- Check if feature is cleared -------------// - hub_port_status_response_t * p_port_status; - p_port_status = (hub_port_status_response_t *) hub_enum_buffer; - - TU_ASSERT( !tu_bit_test(p_port_status->status_change.value, feature-16) ); - - return true; -} - -bool hub_port_reset_subtask(uint8_t hub_addr, uint8_t hub_port) -{ - enum { RESET_DELAY = 200 }; // USB specs say only 50ms but many devices require much longer - - //------------- Set Port Reset -------------// - tusb_control_request_t request = { - .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_OTHER, .type = TUSB_REQ_TYPE_CLASS, .direction = TUSB_DIR_OUT }, - .bRequest = HUB_REQUEST_SET_FEATURE, - .wValue = HUB_FEATURE_PORT_RESET, - .wIndex = hub_port, - .wLength = 0 - }; - - TU_ASSERT( usbh_control_xfer( hub_addr, &request, NULL ) ); - - osal_task_delay(RESET_DELAY); // TODO Hub wait for Status Endpoint on Reset Change - - //------------- Get Port Status to check if port is enabled, powered and reset_change -------------// - request = (tusb_control_request_t ) { - .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_OTHER, .type = TUSB_REQ_TYPE_CLASS, .direction = TUSB_DIR_IN }, - .bRequest = HUB_REQUEST_GET_STATUS, - .wValue = 0, - .wIndex = hub_port, - .wLength = 4 - }; - - TU_ASSERT( usbh_control_xfer( hub_addr, &request, hub_enum_buffer ) ); - - hub_port_status_response_t * p_port_status; - p_port_status = (hub_port_status_response_t *) hub_enum_buffer; - - TU_ASSERT ( p_port_status->status_change.reset && p_port_status->status_current.connect_status && - p_port_status->status_current.port_power && p_port_status->status_current.port_enable); - - return true; -} - -// can only get the speed RIGHT AFTER hub_port_reset_subtask call -tusb_speed_t hub_port_get_speed(void) -{ - hub_port_status_response_t * p_port_status = (hub_port_status_response_t *) hub_enum_buffer; - return (p_port_status->status_current.high_speed_device_attached) ? TUSB_SPEED_HIGH : - (p_port_status->status_current.low_speed_device_attached ) ? TUSB_SPEED_LOW : TUSB_SPEED_FULL; -} - -//--------------------------------------------------------------------+ -// CLASS-USBH API (don't require to verify parameters) -//--------------------------------------------------------------------+ -void hub_init(void) -{ - tu_memclr(hub_data, CFG_TUSB_HOST_DEVICE_MAX*sizeof(usbh_hub_t)); -// hub_enum_sem_hdl = osal_semaphore_create( OSAL_SEM_REF(hub_enum_semaphore) ); -} - -bool hub_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const *itf_desc, uint16_t *p_length) -{ - // not support multiple TT yet - if ( itf_desc->bInterfaceProtocol > 1 ) return false; - - //------------- Open Interrupt Status Pipe -------------// - tusb_desc_endpoint_t const *ep_desc; - ep_desc = (tusb_desc_endpoint_t const *) tu_desc_next(itf_desc); - - TU_ASSERT(TUSB_DESC_ENDPOINT == ep_desc->bDescriptorType); - TU_ASSERT(TUSB_XFER_INTERRUPT == ep_desc->bmAttributes.xfer); - - TU_ASSERT(hcd_edpt_open(rhport, dev_addr, ep_desc)); - - hub_data[dev_addr-1].itf_num = itf_desc->bInterfaceNumber; - hub_data[dev_addr-1].ep_status = ep_desc->bEndpointAddress; - - (*p_length) = sizeof(tusb_desc_interface_t) + sizeof(tusb_desc_endpoint_t); - - //------------- Get Hub Descriptor -------------// - tusb_control_request_t request = { - .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_DEVICE, .type = TUSB_REQ_TYPE_CLASS, .direction = TUSB_DIR_IN }, - .bRequest = HUB_REQUEST_GET_DESCRIPTOR, - .wValue = 0, - .wIndex = 0, - .wLength = sizeof(descriptor_hub_desc_t) - }; - - TU_ASSERT( usbh_control_xfer( dev_addr, &request, hub_enum_buffer ) ); - - // only care about this field in hub descriptor - hub_data[dev_addr-1].port_number = ((descriptor_hub_desc_t*) hub_enum_buffer)->bNbrPorts; - - //------------- Set Port_Power on all ports -------------// - // TODO may only power port with attached - request = (tusb_control_request_t ) { - .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_OTHER, .type = TUSB_REQ_TYPE_CLASS, .direction = TUSB_DIR_OUT }, - .bRequest = HUB_REQUEST_SET_FEATURE, - .wValue = HUB_FEATURE_PORT_POWER, - .wIndex = 0, - .wLength = 0 - }; - - for(uint8_t i=1; i <= hub_data[dev_addr-1].port_number; i++) - { - request.wIndex = i; - TU_ASSERT( usbh_control_xfer( dev_addr, &request, NULL ) ); - } - - //------------- Queue the initial Status endpoint transfer -------------// - TU_ASSERT( hcd_pipe_xfer(dev_addr, hub_data[dev_addr-1].ep_status, &hub_data[dev_addr-1].status_change, 1, true) ); - - return true; -} - -// is the response of interrupt endpoint polling -#include "usbh_hcd.h" // FIXME remove -void hub_isr(uint8_t dev_addr, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes) -{ - (void) xferred_bytes; // TODO can be more than 1 for hub with lots of ports - (void) ep_addr; - - usbh_hub_t * p_hub = &hub_data[dev_addr-1]; - - if ( event == XFER_RESULT_SUCCESS ) - { - for (uint8_t port=1; port <= p_hub->port_number; port++) - { - // TODO HUB ignore bit0 hub_status_change - if ( tu_bit_test(p_hub->status_change, port) ) - { - hcd_event_t event = - { - .rhport = _usbh_devices[dev_addr].rhport, - .event_id = HCD_EVENT_DEVICE_ATTACH - }; - - event.attach.hub_addr = dev_addr; - event.attach.hub_port = port; - - hcd_event_handler(&event, true); - break; // handle one port at a time, next port if any will be handled in the next cycle - } - } - // NOTE: next status transfer is queued by usbh.c after handling this request - } - else - { - // TODO [HUB] check if hub is still plugged before polling status endpoint since failed usually mean hub unplugged -// TU_ASSERT ( hub_status_pipe_queue(dev_addr) ); - } -} - -void hub_close(uint8_t dev_addr) -{ - tu_memclr(&hub_data[dev_addr-1], sizeof(usbh_hub_t)); -// osal_semaphore_reset(hub_enum_sem_hdl); -} - -bool hub_status_pipe_queue(uint8_t dev_addr) -{ - return hcd_pipe_xfer(dev_addr, hub_data[dev_addr-1].ep_status, &hub_data[dev_addr-1].status_change, 1, true); -} - - -#endif +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#include "tusb_option.h" + +#if (TUSB_OPT_HOST_ENABLED && CFG_TUH_HUB) + +//--------------------------------------------------------------------+ +// INCLUDE +//--------------------------------------------------------------------+ +#include "hub.h" + +//--------------------------------------------------------------------+ +// MACRO CONSTANT TYPEDEF +//--------------------------------------------------------------------+ +typedef struct +{ + uint8_t itf_num; + uint8_t ep_status; + uint8_t port_number; + uint8_t status_change; // data from status change interrupt endpoint +}usbh_hub_t; + +CFG_TUSB_MEM_SECTION static usbh_hub_t hub_data[CFG_TUSB_HOST_DEVICE_MAX]; +TU_ATTR_ALIGNED(4) CFG_TUSB_MEM_SECTION static uint8_t hub_enum_buffer[sizeof(descriptor_hub_desc_t)]; + +//OSAL_SEM_DEF(hub_enum_semaphore); +//static osal_semaphore_handle_t hub_enum_sem_hdl; + +//--------------------------------------------------------------------+ +// HUB +//--------------------------------------------------------------------+ +bool hub_port_clear_feature_subtask(uint8_t hub_addr, uint8_t hub_port, uint8_t feature) +{ + TU_ASSERT(HUB_FEATURE_PORT_CONNECTION_CHANGE <= feature && feature <= HUB_FEATURE_PORT_RESET_CHANGE); + + tusb_control_request_t request = { + .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_OTHER, .type = TUSB_REQ_TYPE_CLASS, .direction = TUSB_DIR_OUT }, + .bRequest = HUB_REQUEST_CLEAR_FEATURE, + .wValue = feature, + .wIndex = hub_port, + .wLength = 0 + }; + + //------------- Clear Port Feature request -------------// + TU_ASSERT( usbh_control_xfer( hub_addr, &request, NULL ) ); + + //------------- Get Port Status to check if feature is cleared -------------// + request = (tusb_control_request_t ) { + .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_OTHER, .type = TUSB_REQ_TYPE_CLASS, .direction = TUSB_DIR_IN }, + .bRequest = HUB_REQUEST_GET_STATUS, + .wValue = 0, + .wIndex = hub_port, + .wLength = 4 + }; + + TU_ASSERT( usbh_control_xfer( hub_addr, &request, hub_enum_buffer ) ); + + //------------- Check if feature is cleared -------------// + hub_port_status_response_t * p_port_status; + p_port_status = (hub_port_status_response_t *) hub_enum_buffer; + + TU_ASSERT( !tu_bit_test(p_port_status->status_change.value, feature-16) ); + + return true; +} + +bool hub_port_reset_subtask(uint8_t hub_addr, uint8_t hub_port) +{ + enum { RESET_DELAY = 200 }; // USB specs say only 50ms but many devices require much longer + + //------------- Set Port Reset -------------// + tusb_control_request_t request = { + .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_OTHER, .type = TUSB_REQ_TYPE_CLASS, .direction = TUSB_DIR_OUT }, + .bRequest = HUB_REQUEST_SET_FEATURE, + .wValue = HUB_FEATURE_PORT_RESET, + .wIndex = hub_port, + .wLength = 0 + }; + + TU_ASSERT( usbh_control_xfer( hub_addr, &request, NULL ) ); + + osal_task_delay(RESET_DELAY); // TODO Hub wait for Status Endpoint on Reset Change + + //------------- Get Port Status to check if port is enabled, powered and reset_change -------------// + request = (tusb_control_request_t ) { + .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_OTHER, .type = TUSB_REQ_TYPE_CLASS, .direction = TUSB_DIR_IN }, + .bRequest = HUB_REQUEST_GET_STATUS, + .wValue = 0, + .wIndex = hub_port, + .wLength = 4 + }; + + TU_ASSERT( usbh_control_xfer( hub_addr, &request, hub_enum_buffer ) ); + + hub_port_status_response_t * p_port_status; + p_port_status = (hub_port_status_response_t *) hub_enum_buffer; + + TU_ASSERT ( p_port_status->status_change.reset && p_port_status->status_current.connect_status && + p_port_status->status_current.port_power && p_port_status->status_current.port_enable); + + return true; +} + +// can only get the speed RIGHT AFTER hub_port_reset_subtask call +tusb_speed_t hub_port_get_speed(void) +{ + hub_port_status_response_t * p_port_status = (hub_port_status_response_t *) hub_enum_buffer; + return (p_port_status->status_current.high_speed_device_attached) ? TUSB_SPEED_HIGH : + (p_port_status->status_current.low_speed_device_attached ) ? TUSB_SPEED_LOW : TUSB_SPEED_FULL; +} + +//--------------------------------------------------------------------+ +// CLASS-USBH API (don't require to verify parameters) +//--------------------------------------------------------------------+ +void hub_init(void) +{ + tu_memclr(hub_data, CFG_TUSB_HOST_DEVICE_MAX*sizeof(usbh_hub_t)); +// hub_enum_sem_hdl = osal_semaphore_create( OSAL_SEM_REF(hub_enum_semaphore) ); +} + +bool hub_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const *itf_desc, uint16_t *p_length) +{ + // not support multiple TT yet + if ( itf_desc->bInterfaceProtocol > 1 ) return false; + + //------------- Open Interrupt Status Pipe -------------// + tusb_desc_endpoint_t const *ep_desc; + ep_desc = (tusb_desc_endpoint_t const *) tu_desc_next(itf_desc); + + TU_ASSERT(TUSB_DESC_ENDPOINT == ep_desc->bDescriptorType); + TU_ASSERT(TUSB_XFER_INTERRUPT == ep_desc->bmAttributes.xfer); + + TU_ASSERT(hcd_edpt_open(rhport, dev_addr, ep_desc)); + + hub_data[dev_addr-1].itf_num = itf_desc->bInterfaceNumber; + hub_data[dev_addr-1].ep_status = ep_desc->bEndpointAddress; + + (*p_length) = sizeof(tusb_desc_interface_t) + sizeof(tusb_desc_endpoint_t); + + //------------- Get Hub Descriptor -------------// + tusb_control_request_t request = { + .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_DEVICE, .type = TUSB_REQ_TYPE_CLASS, .direction = TUSB_DIR_IN }, + .bRequest = HUB_REQUEST_GET_DESCRIPTOR, + .wValue = 0, + .wIndex = 0, + .wLength = sizeof(descriptor_hub_desc_t) + }; + + TU_ASSERT( usbh_control_xfer( dev_addr, &request, hub_enum_buffer ) ); + + // only care about this field in hub descriptor + hub_data[dev_addr-1].port_number = ((descriptor_hub_desc_t*) hub_enum_buffer)->bNbrPorts; + + //------------- Set Port_Power on all ports -------------// + // TODO may only power port with attached + request = (tusb_control_request_t ) { + .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_OTHER, .type = TUSB_REQ_TYPE_CLASS, .direction = TUSB_DIR_OUT }, + .bRequest = HUB_REQUEST_SET_FEATURE, + .wValue = HUB_FEATURE_PORT_POWER, + .wIndex = 0, + .wLength = 0 + }; + + for(uint8_t i=1; i <= hub_data[dev_addr-1].port_number; i++) + { + request.wIndex = i; + TU_ASSERT( usbh_control_xfer( dev_addr, &request, NULL ) ); + } + + //------------- Queue the initial Status endpoint transfer -------------// + TU_ASSERT( hcd_pipe_xfer(dev_addr, hub_data[dev_addr-1].ep_status, &hub_data[dev_addr-1].status_change, 1, true) ); + + return true; +} + +// is the response of interrupt endpoint polling +#include "usbh_hcd.h" // FIXME remove +void hub_isr(uint8_t dev_addr, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes) +{ + (void) xferred_bytes; // TODO can be more than 1 for hub with lots of ports + (void) ep_addr; + + usbh_hub_t * p_hub = &hub_data[dev_addr-1]; + + if ( event == XFER_RESULT_SUCCESS ) + { + for (uint8_t port=1; port <= p_hub->port_number; port++) + { + // TODO HUB ignore bit0 hub_status_change + if ( tu_bit_test(p_hub->status_change, port) ) + { + hcd_event_t event = + { + .rhport = _usbh_devices[dev_addr].rhport, + .event_id = HCD_EVENT_DEVICE_ATTACH + }; + + event.attach.hub_addr = dev_addr; + event.attach.hub_port = port; + + hcd_event_handler(&event, true); + break; // handle one port at a time, next port if any will be handled in the next cycle + } + } + // NOTE: next status transfer is queued by usbh.c after handling this request + } + else + { + // TODO [HUB] check if hub is still plugged before polling status endpoint since failed usually mean hub unplugged +// TU_ASSERT ( hub_status_pipe_queue(dev_addr) ); + } +} + +void hub_close(uint8_t dev_addr) +{ + tu_memclr(&hub_data[dev_addr-1], sizeof(usbh_hub_t)); +// osal_semaphore_reset(hub_enum_sem_hdl); +} + +bool hub_status_pipe_queue(uint8_t dev_addr) +{ + return hcd_pipe_xfer(dev_addr, hub_data[dev_addr-1].ep_status, &hub_data[dev_addr-1].status_change, 1, true); +} + + +#endif diff --git a/src/host/hub.h b/src/host/hub.h index 51d33d4e..62135631 100644 --- a/src/host/hub.h +++ b/src/host/hub.h @@ -1,194 +1,194 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2019 Ha Thach (tinyusb.org) - * - * 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. - * - * This file is part of the TinyUSB stack. - */ - -/** \ingroup group_class - * \defgroup ClassDriver_Hub Hub (Host only) - * \details Like most PC's OS, Hub support is completely hidden from Application. In fact, application cannot determine whether - * a device is mounted directly via roothub or via a hub's port. All Hub-related procedures are performed and managed - * by tinyusb stack. Unless you are trying to develop the stack itself, there are nothing else can be used by Application. - * \note Due to my laziness, only 1-level of Hub is supported. In other way, the stack cannot mount a hub via another hub. - * @{ - */ - -#ifndef _TUSB_HUB_H_ -#define _TUSB_HUB_H_ - -#include -#include "usbh.h" - -#ifdef __cplusplus - extern "C" { -#endif - -//D1...D0: Logical Power Switching Mode -//00: Ganged power switching (all ports’power at -//once) -//01: Individual port power switching -//1X: Reserved. Used only on 1.0 compliant hubs -//that implement no power switching -//D2: Identifies a Compound Device -//0: Hub is not part of a compound device. -//1: Hub is part of a compound device. -//D4...D3: Over-current Protection Mode -//00: Global Over-current Protection. The hub -//reports over-current as a summation of all -//ports’current draw, without a breakdown of -//individual port over-current status. -//01: Individual Port Over-current Protection. The -//hub reports over-current on a per-port basis. -//Each port has an over-current status. -//1X: No Over-current Protection. This option is -//allowed only for bus-powered hubs that do not -//implement over-current protection. -// -//D6...D5: TT Think TIme -//00: TT requires at most 8 FS bit times of inter -//transaction gap on a full-/low-speed -//downstream bus. -//01: TT requires at most 16 FS bit times. -//10: TT requires at most 24 FS bit times. -//11: TT requires at most 32 FS bit times. -//D7: Port Indicators Supported -//0: Port Indicators are not supported on its -//downstream facing ports and the -//PORT_INDICATOR request has no effect. -//1: Port Indicators are supported on its -//downstream facing ports and the -//PORT_INDICATOR request controls the -//indicators. See Section 11.5.3. -//D15...D8: Reserved - -typedef struct TU_ATTR_PACKED{ - uint8_t bLength ; ///< Size of descriptor - uint8_t bDescriptorType ; ///< Other_speed_Configuration Type - uint8_t bNbrPorts; - uint16_t wHubCharacteristics; - uint8_t bPwrOn2PwrGood; - uint8_t bHubContrCurrent; - uint8_t DeviceRemovable; // bitmap each bit for a port (from bit1) - uint8_t PortPwrCtrlMask; // just for compatibility, should be 0xff -} descriptor_hub_desc_t; - -TU_VERIFY_STATIC( sizeof(descriptor_hub_desc_t) == 9, "size is not correct"); - -enum { - HUB_REQUEST_GET_STATUS = 0 , - HUB_REQUEST_CLEAR_FEATURE = 1 , - - HUB_REQUEST_SET_FEATURE = 3 , - - HUB_REQUEST_GET_DESCRIPTOR = 6 , - HUB_REQUEST_SET_DESCRIPTOR = 7 , - HUB_REQUEST_CLEAR_TT_BUFFER = 8 , - HUB_REQUEST_RESET_TT = 9 , - HUB_REQUEST_GET_TT_STATE = 10 , - HUB_REQUEST_STOP_TT = 11 -}; - -enum { - HUB_FEATURE_HUB_LOCAL_POWER_CHANGE = 0, - HUB_FEATURE_HUB_OVER_CURRENT_CHANGE -}; - -enum{ - HUB_FEATURE_PORT_CONNECTION = 0, - HUB_FEATURE_PORT_ENABLE = 1, - HUB_FEATURE_PORT_SUSPEND = 2, - HUB_FEATURE_PORT_OVER_CURRENT = 3, - HUB_FEATURE_PORT_RESET = 4, - - HUB_FEATURE_PORT_POWER = 8, - HUB_FEATURE_PORT_LOW_SPEED = 9, - - HUB_FEATURE_PORT_CONNECTION_CHANGE = 16, - HUB_FEATURE_PORT_ENABLE_CHANGE = 17, - HUB_FEATURE_PORT_SUSPEND_CHANGE = 18, - HUB_FEATURE_PORT_OVER_CURRENT_CHANGE = 19, - HUB_FEATURE_PORT_RESET_CHANGE = 20, - HUB_FEATURE_PORT_TEST = 21, - HUB_FEATURE_PORT_INDICATOR = 22 -}; - -// data in response of HUB_REQUEST_GET_STATUS, wIndex = 0 (hub) -typedef struct { - union{ - struct TU_ATTR_PACKED { - uint16_t local_power_source : 1; - uint16_t over_current : 1; - uint16_t : 14; - }; - - uint16_t value; - } status, status_change; -} hub_status_response_t; - -TU_VERIFY_STATIC( sizeof(hub_status_response_t) == 4, "size is not correct"); - -// data in response of HUB_REQUEST_GET_STATUS, wIndex = Port num -typedef struct { - union { - struct TU_ATTR_PACKED { - uint16_t connect_status : 1; - uint16_t port_enable : 1; - uint16_t suspend : 1; - uint16_t over_current : 1; - uint16_t reset : 1; - - uint16_t : 3; - uint16_t port_power : 1; - uint16_t low_speed_device_attached : 1; - uint16_t high_speed_device_attached : 1; - uint16_t port_test_mode : 1; - uint16_t port_indicator_control : 1; - uint16_t : 0; - }; - - uint16_t value; - } status_current, status_change; -} hub_port_status_response_t; - -TU_VERIFY_STATIC( sizeof(hub_port_status_response_t) == 4, "size is not correct"); - -bool hub_port_reset_subtask(uint8_t hub_addr, uint8_t hub_port); -bool hub_port_clear_feature_subtask(uint8_t hub_addr, uint8_t hub_port, uint8_t feature); -tusb_speed_t hub_port_get_speed(void); -bool hub_status_pipe_queue(uint8_t dev_addr); - -//--------------------------------------------------------------------+ -// Internal Class Driver API -//--------------------------------------------------------------------+ -void hub_init(void); -bool hub_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const *itf_desc, uint16_t *p_length); -void hub_isr(uint8_t dev_addr, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes); -void hub_close(uint8_t dev_addr); - -#ifdef __cplusplus - } -#endif - -#endif /* _TUSB_HUB_H_ */ - -/** @} */ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +/** \ingroup group_class + * \defgroup ClassDriver_Hub Hub (Host only) + * \details Like most PC's OS, Hub support is completely hidden from Application. In fact, application cannot determine whether + * a device is mounted directly via roothub or via a hub's port. All Hub-related procedures are performed and managed + * by tinyusb stack. Unless you are trying to develop the stack itself, there are nothing else can be used by Application. + * \note Due to my laziness, only 1-level of Hub is supported. In other way, the stack cannot mount a hub via another hub. + * @{ + */ + +#ifndef _TUSB_HUB_H_ +#define _TUSB_HUB_H_ + +#include +#include "usbh.h" + +#ifdef __cplusplus + extern "C" { +#endif + +//D1...D0: Logical Power Switching Mode +//00: Ganged power switching (all ports’power at +//once) +//01: Individual port power switching +//1X: Reserved. Used only on 1.0 compliant hubs +//that implement no power switching +//D2: Identifies a Compound Device +//0: Hub is not part of a compound device. +//1: Hub is part of a compound device. +//D4...D3: Over-current Protection Mode +//00: Global Over-current Protection. The hub +//reports over-current as a summation of all +//ports’current draw, without a breakdown of +//individual port over-current status. +//01: Individual Port Over-current Protection. The +//hub reports over-current on a per-port basis. +//Each port has an over-current status. +//1X: No Over-current Protection. This option is +//allowed only for bus-powered hubs that do not +//implement over-current protection. +// +//D6...D5: TT Think TIme +//00: TT requires at most 8 FS bit times of inter +//transaction gap on a full-/low-speed +//downstream bus. +//01: TT requires at most 16 FS bit times. +//10: TT requires at most 24 FS bit times. +//11: TT requires at most 32 FS bit times. +//D7: Port Indicators Supported +//0: Port Indicators are not supported on its +//downstream facing ports and the +//PORT_INDICATOR request has no effect. +//1: Port Indicators are supported on its +//downstream facing ports and the +//PORT_INDICATOR request controls the +//indicators. See Section 11.5.3. +//D15...D8: Reserved + +typedef struct TU_ATTR_PACKED{ + uint8_t bLength ; ///< Size of descriptor + uint8_t bDescriptorType ; ///< Other_speed_Configuration Type + uint8_t bNbrPorts; + uint16_t wHubCharacteristics; + uint8_t bPwrOn2PwrGood; + uint8_t bHubContrCurrent; + uint8_t DeviceRemovable; // bitmap each bit for a port (from bit1) + uint8_t PortPwrCtrlMask; // just for compatibility, should be 0xff +} descriptor_hub_desc_t; + +TU_VERIFY_STATIC( sizeof(descriptor_hub_desc_t) == 9, "size is not correct"); + +enum { + HUB_REQUEST_GET_STATUS = 0 , + HUB_REQUEST_CLEAR_FEATURE = 1 , + + HUB_REQUEST_SET_FEATURE = 3 , + + HUB_REQUEST_GET_DESCRIPTOR = 6 , + HUB_REQUEST_SET_DESCRIPTOR = 7 , + HUB_REQUEST_CLEAR_TT_BUFFER = 8 , + HUB_REQUEST_RESET_TT = 9 , + HUB_REQUEST_GET_TT_STATE = 10 , + HUB_REQUEST_STOP_TT = 11 +}; + +enum { + HUB_FEATURE_HUB_LOCAL_POWER_CHANGE = 0, + HUB_FEATURE_HUB_OVER_CURRENT_CHANGE +}; + +enum{ + HUB_FEATURE_PORT_CONNECTION = 0, + HUB_FEATURE_PORT_ENABLE = 1, + HUB_FEATURE_PORT_SUSPEND = 2, + HUB_FEATURE_PORT_OVER_CURRENT = 3, + HUB_FEATURE_PORT_RESET = 4, + + HUB_FEATURE_PORT_POWER = 8, + HUB_FEATURE_PORT_LOW_SPEED = 9, + + HUB_FEATURE_PORT_CONNECTION_CHANGE = 16, + HUB_FEATURE_PORT_ENABLE_CHANGE = 17, + HUB_FEATURE_PORT_SUSPEND_CHANGE = 18, + HUB_FEATURE_PORT_OVER_CURRENT_CHANGE = 19, + HUB_FEATURE_PORT_RESET_CHANGE = 20, + HUB_FEATURE_PORT_TEST = 21, + HUB_FEATURE_PORT_INDICATOR = 22 +}; + +// data in response of HUB_REQUEST_GET_STATUS, wIndex = 0 (hub) +typedef struct { + union{ + struct TU_ATTR_PACKED { + uint16_t local_power_source : 1; + uint16_t over_current : 1; + uint16_t : 14; + }; + + uint16_t value; + } status, status_change; +} hub_status_response_t; + +TU_VERIFY_STATIC( sizeof(hub_status_response_t) == 4, "size is not correct"); + +// data in response of HUB_REQUEST_GET_STATUS, wIndex = Port num +typedef struct { + union { + struct TU_ATTR_PACKED { + uint16_t connect_status : 1; + uint16_t port_enable : 1; + uint16_t suspend : 1; + uint16_t over_current : 1; + uint16_t reset : 1; + + uint16_t : 3; + uint16_t port_power : 1; + uint16_t low_speed_device_attached : 1; + uint16_t high_speed_device_attached : 1; + uint16_t port_test_mode : 1; + uint16_t port_indicator_control : 1; + uint16_t : 0; + }; + + uint16_t value; + } status_current, status_change; +} hub_port_status_response_t; + +TU_VERIFY_STATIC( sizeof(hub_port_status_response_t) == 4, "size is not correct"); + +bool hub_port_reset_subtask(uint8_t hub_addr, uint8_t hub_port); +bool hub_port_clear_feature_subtask(uint8_t hub_addr, uint8_t hub_port, uint8_t feature); +tusb_speed_t hub_port_get_speed(void); +bool hub_status_pipe_queue(uint8_t dev_addr); + +//--------------------------------------------------------------------+ +// Internal Class Driver API +//--------------------------------------------------------------------+ +void hub_init(void); +bool hub_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const *itf_desc, uint16_t *p_length); +void hub_isr(uint8_t dev_addr, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes); +void hub_close(uint8_t dev_addr); + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_HUB_H_ */ + +/** @} */ diff --git a/src/host/ohci/ohci.c b/src/host/ohci/ohci.c index 9fa861ac..547622ed 100644 --- a/src/host/ohci/ohci.c +++ b/src/host/ohci/ohci.c @@ -1,651 +1,651 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2019 Ha Thach (tinyusb.org) - * - * 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. - * - * This file is part of the TinyUSB stack. - */ - -#include - -#if TUSB_OPT_HOST_ENABLED && (CFG_TUSB_MCU == OPT_MCU_LPC175X_6X || CFG_TUSB_MCU == OPT_MCU_LPC40XX) -//--------------------------------------------------------------------+ -// INCLUDE -//--------------------------------------------------------------------+ -#include "osal/osal.h" - -#include "../hcd.h" -#include "../usbh_hcd.h" -#include "ohci.h" - -// TODO remove -#include "chip.h" - -//--------------------------------------------------------------------+ -// MACRO CONSTANT TYPEDEF -//--------------------------------------------------------------------+ -#define OHCI_REG ((ohci_registers_t *) LPC_USB_BASE) - -enum { - OHCI_CONTROL_FUNCSTATE_RESET = 0, - OHCI_CONTROL_FUNCSTATE_RESUME, - OHCI_CONTROL_FUNCSTATE_OPERATIONAL, - OHCI_CONTROL_FUNCSTATE_SUSPEND -}; - -enum { - OHCI_CONTROL_CONTROL_BULK_RATIO = 3, ///< This specifies the service ratio between Control and Bulk EDs. 0 = 1:1, 3 = 4:1 - OHCI_CONTROL_LIST_PERIODIC_ENABLE_MASK = TU_BIT(2), - OHCI_CONTROL_LIST_ISOCHRONOUS_ENABLE_MASK = TU_BIT(3), - OHCI_CONTROL_LIST_CONTROL_ENABLE_MASK = TU_BIT(4), - OHCI_CONTROL_LIST_BULK_ENABLE_MASK = TU_BIT(5), -}; - -enum { - OHCI_FMINTERVAL_FI = 0x2EDF, // 7.3.1 nominal (reset) value - OHCI_FMINTERVAL_FSMPS = (6*(OHCI_FMINTERVAL_FI-210)) / 7, // 5.4 calculated based on maximum overhead + bit stuffing -}; - -enum { - OHCI_PERIODIC_START = 0x3E67 -}; - -enum { - OHCI_INT_SCHEDULING_OVERUN_MASK = TU_BIT(0), - OHCI_INT_WRITEBACK_DONEHEAD_MASK = TU_BIT(1), - OHCI_INT_SOF_MASK = TU_BIT(2), - OHCI_INT_RESUME_DETECTED_MASK = TU_BIT(3), - OHCI_INT_UNRECOVERABLE_ERROR_MASK = TU_BIT(4), - OHCI_INT_FRAME_OVERFLOW_MASK = TU_BIT(5), - OHCI_INT_RHPORT_STATUS_CHANGE_MASK = TU_BIT(6), - - OHCI_INT_OWNERSHIP_CHANGE_MASK = TU_BIT(30), - OHCI_INT_MASTER_ENABLE_MASK = TU_BIT(31), -}; - -enum { - OHCI_RHPORT_CURRENT_CONNECT_STATUS_MASK = TU_BIT(0), - OHCI_RHPORT_PORT_ENABLE_STATUS_MASK = TU_BIT(1), - OHCI_RHPORT_PORT_SUSPEND_STATUS_MASK = TU_BIT(2), - OHCI_RHPORT_PORT_OVER_CURRENT_INDICATOR_MASK = TU_BIT(3), - OHCI_RHPORT_PORT_RESET_STATUS_MASK = TU_BIT(4), ///< write '1' to reset port - - OHCI_RHPORT_PORT_POWER_STATUS_MASK = TU_BIT(8), - OHCI_RHPORT_LOW_SPEED_DEVICE_ATTACHED_MASK = TU_BIT(9), - - OHCI_RHPORT_CONNECT_STATUS_CHANGE_MASK = TU_BIT(16), - OHCI_RHPORT_PORT_ENABLE_CHANGE_MASK = TU_BIT(17), - OHCI_RHPORT_PORT_SUSPEND_CHANGE_MASK = TU_BIT(18), - OHCI_RHPORT_OVER_CURRENT_CHANGE_MASK = TU_BIT(19), - OHCI_RHPORT_PORT_RESET_CHANGE_MASK = TU_BIT(20), - - OHCI_RHPORT_ALL_CHANGE_MASK = OHCI_RHPORT_CONNECT_STATUS_CHANGE_MASK | OHCI_RHPORT_PORT_ENABLE_CHANGE_MASK | - OHCI_RHPORT_PORT_SUSPEND_CHANGE_MASK | OHCI_RHPORT_OVER_CURRENT_CHANGE_MASK | OHCI_RHPORT_PORT_RESET_CHANGE_MASK -}; - -enum { - OHCI_CCODE_NO_ERROR = 0, - OHCI_CCODE_CRC = 1, - OHCI_CCODE_BIT_STUFFING = 2, - OHCI_CCODE_DATA_TOGGLE_MISMATCH = 3, - OHCI_CCODE_STALL = 4, - OHCI_CCODE_DEVICE_NOT_RESPONDING = 5, - OHCI_CCODE_PID_CHECK_FAILURE = 6, - OHCI_CCODE_UNEXPECTED_PID = 7, - OHCI_CCODE_DATA_OVERRUN = 8, - OHCI_CCODE_DATA_UNDERRUN = 9, - OHCI_CCODE_BUFFER_OVERRUN = 12, - OHCI_CCODE_BUFFER_UNDERRUN = 13, - OHCI_CCODE_NOT_ACCESSED = 14, -}; - -enum { - OHCI_INT_ON_COMPLETE_YES = 0, - OHCI_INT_ON_COMPLETE_NO = TU_BIN8(111) -}; -//--------------------------------------------------------------------+ -// INTERNAL OBJECT & FUNCTION DECLARATION -//--------------------------------------------------------------------+ -CFG_TUSB_MEM_SECTION TU_ATTR_ALIGNED(256) static ohci_data_t ohci_data; - -static ohci_ed_t * const p_ed_head[] = -{ - [TUSB_XFER_CONTROL] = &ohci_data.control[0].ed, - [TUSB_XFER_BULK ] = &ohci_data.bulk_head_ed, - [TUSB_XFER_INTERRUPT] = &ohci_data.period_head_ed, - [TUSB_XFER_ISOCHRONOUS] = NULL // TODO Isochronous -}; - -static void ed_list_insert(ohci_ed_t * p_pre, ohci_ed_t * p_ed); -static void ed_list_remove_by_addr(ohci_ed_t * p_head, uint8_t dev_addr); - -//--------------------------------------------------------------------+ -// USBH-HCD API -//--------------------------------------------------------------------+ -// Initialization according to 5.1.1.4 -bool hcd_init(void) -{ - //------------- Data Structure init -------------// - tu_memclr(&ohci_data, sizeof(ohci_data_t)); - for(uint8_t i=0; i<32; i++) - { // assign all interrupt pointes to period head ed - ohci_data.hcca.interrupt_table[i] = (uint32_t) &ohci_data.period_head_ed; - } - - ohci_data.control[0].ed.skip = 1; - ohci_data.bulk_head_ed.skip = 1; - ohci_data.period_head_ed.skip = 1; - - // reset controller - OHCI_REG->command_status_bit.controller_reset = 1; - while( OHCI_REG->command_status_bit.controller_reset ) {} // should not take longer than 10 us - - //------------- init ohci registers -------------// - OHCI_REG->control_head_ed = (uint32_t) &ohci_data.control[0].ed; - OHCI_REG->bulk_head_ed = (uint32_t) &ohci_data.bulk_head_ed; - OHCI_REG->hcca = (uint32_t) &ohci_data.hcca; - - OHCI_REG->interrupt_disable = OHCI_REG->interrupt_enable; // disable all interrupts - OHCI_REG->interrupt_status = OHCI_REG->interrupt_status; // clear current set bits - OHCI_REG->interrupt_enable = OHCI_INT_WRITEBACK_DONEHEAD_MASK | OHCI_INT_RESUME_DETECTED_MASK | - OHCI_INT_UNRECOVERABLE_ERROR_MASK | /*OHCI_INT_FRAME_OVERFLOW_MASK |*/ OHCI_INT_RHPORT_STATUS_CHANGE_MASK | - OHCI_INT_MASTER_ENABLE_MASK; - - OHCI_REG->control |= OHCI_CONTROL_CONTROL_BULK_RATIO | OHCI_CONTROL_LIST_CONTROL_ENABLE_MASK | - OHCI_CONTROL_LIST_BULK_ENABLE_MASK | OHCI_CONTROL_LIST_PERIODIC_ENABLE_MASK; // TODO Isochronous - - OHCI_REG->frame_interval = (OHCI_FMINTERVAL_FSMPS << 16) | OHCI_FMINTERVAL_FI; - OHCI_REG->periodic_start = (OHCI_FMINTERVAL_FI * 9) / 10; // Periodic start is 90% of frame interval - - OHCI_REG->control_bit.hc_functional_state = OHCI_CONTROL_FUNCSTATE_OPERATIONAL; // make HC's state to operational state TODO use this to suspend (save power) - OHCI_REG->rh_status_bit.local_power_status_change = 1; // set global power for ports - - return true; -} - -//--------------------------------------------------------------------+ -// PORT API -//--------------------------------------------------------------------+ -void hcd_port_reset(uint8_t hostid) -{ - (void) hostid; - OHCI_REG->rhport_status[0] = OHCI_RHPORT_PORT_RESET_STATUS_MASK; -} - -bool hcd_port_connect_status(uint8_t hostid) -{ - (void) hostid; - return OHCI_REG->rhport_status_bit[0].current_connect_status; -} - -tusb_speed_t hcd_port_speed_get(uint8_t hostid) -{ - (void) hostid; - return OHCI_REG->rhport_status_bit[0].low_speed_device_attached ? TUSB_SPEED_LOW : TUSB_SPEED_FULL; -} - -// endpoints are tied to an address, which only reclaim after a long delay when enumerating -// thus there is no need to make sure ED is not in HC's cahed as it will not for sure -void hcd_device_close(uint8_t rhport, uint8_t dev_addr) -{ - // TODO OHCI - (void) rhport; - - // addr0 serves as static head --> only set skip bit - if ( dev_addr == 0 ) - { - ohci_data.control[0].ed.skip = 1; - }else - { - // remove control - ed_list_remove_by_addr( p_ed_head[TUSB_XFER_CONTROL], dev_addr); - - // remove bulk - ed_list_remove_by_addr(p_ed_head[TUSB_XFER_BULK], dev_addr); - - // remove interrupt - ed_list_remove_by_addr(p_ed_head[TUSB_XFER_INTERRUPT], dev_addr); - - // TODO remove ISO - } -} - -//--------------------------------------------------------------------+ -// Controller API -//--------------------------------------------------------------------+ - -//--------------------------------------------------------------------+ -// CONTROL PIPE API -//--------------------------------------------------------------------+ -static inline tusb_xfer_type_t ed_get_xfer_type(ohci_ed_t const * const p_ed) -{ - return (p_ed->ep_number == 0 ) ? TUSB_XFER_CONTROL : - (p_ed->is_iso ) ? TUSB_XFER_ISOCHRONOUS : - (p_ed->is_interrupt_xfer ) ? TUSB_XFER_INTERRUPT : TUSB_XFER_BULK; -} - -static void ed_init(ohci_ed_t *p_ed, uint8_t dev_addr, uint16_t max_packet_size, uint8_t endpoint_addr, uint8_t xfer_type, uint8_t interval) -{ - (void) interval; - - // address 0 is used as async head, which always on the list --> cannot be cleared - if (dev_addr != 0) - { - tu_memclr(p_ed, sizeof(ohci_ed_t)); - } - - p_ed->dev_addr = dev_addr; - p_ed->ep_number = endpoint_addr & 0x0F; - p_ed->pid = (xfer_type == TUSB_XFER_CONTROL) ? OHCI_PID_SETUP : ( (endpoint_addr & TUSB_DIR_IN_MASK) ? OHCI_PID_IN : OHCI_PID_OUT ); - p_ed->speed = _usbh_devices[dev_addr].speed; - p_ed->is_iso = (xfer_type == TUSB_XFER_ISOCHRONOUS) ? 1 : 0; - p_ed->max_packet_size = max_packet_size; - - p_ed->used = 1; - p_ed->is_interrupt_xfer = (xfer_type == TUSB_XFER_INTERRUPT ? 1 : 0); -} - -static void gtd_init(ohci_gtd_t* p_td, void* data_ptr, uint16_t total_bytes) -{ - tu_memclr(p_td, sizeof(ohci_gtd_t)); - - p_td->used = 1; - p_td->expected_bytes = total_bytes; - - p_td->buffer_rounding = 1; // less than queued length is not a error - p_td->delay_interrupt = OHCI_INT_ON_COMPLETE_NO; - p_td->condition_code = OHCI_CCODE_NOT_ACCESSED; - - p_td->current_buffer_pointer = data_ptr; - p_td->buffer_end = total_bytes ? (((uint8_t*) data_ptr) + total_bytes-1) : NULL; -} - -bool hcd_setup_send(uint8_t rhport, uint8_t dev_addr, uint8_t const setup_packet[8]) -{ - (void) rhport; - - ohci_ed_t* p_ed = &ohci_data.control[dev_addr].ed; - ohci_gtd_t *p_setup = &ohci_data.control[dev_addr].gtd; - - gtd_init(p_setup, (void*) setup_packet, 8); - p_setup->index = dev_addr; - p_setup->pid = OHCI_PID_SETUP; - p_setup->data_toggle = TU_BIN8(10); // DATA0 - p_setup->delay_interrupt = OHCI_INT_ON_COMPLETE_YES; - - //------------- Attach TDs list to Control Endpoint -------------// - p_ed->td_head.address = (uint32_t) p_setup; - - OHCI_REG->command_status_bit.control_list_filled = 1; - - return true; -} - -bool hcd_edpt_xfer(uint8_t rhport, uint8_t dev_addr, uint8_t ep_addr, uint8_t * buffer, uint16_t buflen) -{ - (void) rhport; - - uint8_t const epnum = tu_edpt_number(ep_addr); - uint8_t const dir = tu_edpt_dir(ep_addr); - - // FIXME control only for now - if ( epnum == 0 ) - { - ohci_ed_t* const p_ed = &ohci_data.control[dev_addr].ed; - ohci_gtd_t *p_data = &ohci_data.control[dev_addr].gtd; - - gtd_init(p_data, buffer, buflen); - - p_data->index = dev_addr; - p_data->pid = dir ? OHCI_PID_IN : OHCI_PID_OUT; - p_data->data_toggle = TU_BIN8(11); // DATA1 - p_data->delay_interrupt = OHCI_INT_ON_COMPLETE_YES; - - p_ed->td_head.address = (uint32_t) p_data; - - OHCI_REG->command_status_bit.control_list_filled = 1; - } - - return true; -} - -//--------------------------------------------------------------------+ -// BULK/INT/ISO PIPE API -//--------------------------------------------------------------------+ -static inline ohci_ed_t * ed_from_addr(uint8_t dev_addr, uint8_t ep_addr) -{ - if ( tu_edpt_number(ep_addr) == 0 ) return &ohci_data.control[dev_addr].ed; - - ohci_ed_t* ed_pool = ohci_data.ed_pool; - - for(uint32_t i=0; inext = p_pre->next; - p_pre->next = (uint32_t) p_ed; -} - -static void ed_list_remove_by_addr(ohci_ed_t * p_head, uint8_t dev_addr) -{ - ohci_ed_t* p_prev = p_head; - - while( p_prev->next ) - { - ohci_ed_t* ed = (ohci_ed_t*) p_prev->next; - - if (ed->dev_addr == dev_addr) - { - // unlink ed - p_prev->next = ed->next; - - // point the removed ED's next pointer to list head to make sure HC can always safely move away from this ED - ed->next = (uint32_t) p_head; - ed->used = 0; - } - - // check next valid since we could remove it - if (p_prev->next) p_prev = (ohci_ed_t*) p_prev->next; - } -} - -bool hcd_edpt_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_endpoint_t const * ep_desc) -{ - (void) rhport; - - // TODO iso support - TU_ASSERT(ep_desc->bmAttributes.xfer != TUSB_XFER_ISOCHRONOUS); - - //------------- Prepare Queue Head -------------// - ohci_ed_t * p_ed; - - if ( ep_desc->bEndpointAddress == 0 ) - { - p_ed = &ohci_data.control[dev_addr].ed; - }else - { - p_ed = ed_find_free(); - } - TU_ASSERT(p_ed); - - ed_init( p_ed, dev_addr, ep_desc->wMaxPacketSize.size, ep_desc->bEndpointAddress, - ep_desc->bmAttributes.xfer, ep_desc->bInterval ); - - // control of dev0 is used as static async head - if ( dev_addr == 0 ) - { - p_ed->skip = 0; // only need to clear skip bit - return true; - } - - ed_list_insert( p_ed_head[ep_desc->bmAttributes.xfer], p_ed ); - - return true; -} - -static ohci_gtd_t * gtd_find_free(void) -{ - for(uint8_t i=0; i < HCD_MAX_XFER; i++) - { - if ( !ohci_data.gtd_pool[i].used ) return &ohci_data.gtd_pool[i]; - } - - return NULL; -} - -static void td_insert_to_ed(ohci_ed_t* p_ed, ohci_gtd_t * p_gtd) -{ - // tail is always NULL - if ( tu_align16(p_ed->td_head.address) == 0 ) - { // TD queue is empty --> head = TD - p_ed->td_head.address |= (uint32_t) p_gtd; - } - else - { // TODO currently only support queue up to 2 TD each endpoint at a time - ((ohci_gtd_t*) tu_align16(p_ed->td_head.address))->next = (uint32_t) p_gtd; - } -} - -static bool pipe_queue_xfer(uint8_t dev_addr, uint8_t ep_addr, uint8_t buffer[], uint16_t total_bytes, bool int_on_complete) -{ - ohci_ed_t* const p_ed = ed_from_addr(dev_addr, ep_addr); - - // not support ISO yet - TU_VERIFY ( !p_ed->is_iso ); - - ohci_gtd_t * const p_gtd = gtd_find_free(); - TU_ASSERT(p_gtd); // not enough gtd - - gtd_init(p_gtd, buffer, total_bytes); - p_gtd->index = p_ed-ohci_data.ed_pool; - - if ( int_on_complete ) p_gtd->delay_interrupt = OHCI_INT_ON_COMPLETE_YES; - - td_insert_to_ed(p_ed, p_gtd); - - return true; -} - -bool hcd_pipe_queue_xfer(uint8_t dev_addr, uint8_t ep_addr, uint8_t buffer[], uint16_t total_bytes) -{ - return pipe_queue_xfer(dev_addr, ep_addr, buffer, total_bytes, false); -} - -bool hcd_pipe_xfer(uint8_t dev_addr, uint8_t ep_addr, uint8_t buffer[], uint16_t total_bytes, bool int_on_complete) -{ - (void) int_on_complete; - TU_ASSERT( pipe_queue_xfer(dev_addr, ep_addr, buffer, total_bytes, true) ); - - tusb_xfer_type_t xfer_type = ed_get_xfer_type( ed_from_addr(dev_addr, ep_addr) ); - - if (TUSB_XFER_BULK == xfer_type) OHCI_REG->command_status_bit.bulk_list_filled = 1; - - return true; -} - -bool hcd_edpt_busy(uint8_t dev_addr, uint8_t ep_addr) -{ - ohci_ed_t const * const p_ed = ed_from_addr(dev_addr, ep_addr); - return tu_align16(p_ed->td_head.address) != tu_align16(p_ed->td_tail); -} - -bool hcd_edpt_stalled(uint8_t dev_addr, uint8_t ep_addr) -{ - ohci_ed_t const * const p_ed = ed_from_addr(dev_addr, ep_addr); - return p_ed->td_head.halted && p_ed->is_stalled; -} - -bool hcd_edpt_clear_stall(uint8_t dev_addr, uint8_t ep_addr) -{ - ohci_ed_t * const p_ed = ed_from_addr(dev_addr, ep_addr); - - p_ed->is_stalled = 0; - p_ed->td_tail &= 0x0Ful; // set tail pointer back to NULL - - p_ed->td_head.toggle = 0; // reset data toggle - p_ed->td_head.halted = 0; - - if ( TUSB_XFER_BULK == ed_get_xfer_type(p_ed) ) OHCI_REG->command_status_bit.bulk_list_filled = 1; - - return true; -} - - -//--------------------------------------------------------------------+ -// OHCI Interrupt Handler -//--------------------------------------------------------------------+ -static ohci_td_item_t* list_reverse(ohci_td_item_t* td_head) -{ - ohci_td_item_t* td_reverse_head = NULL; - - while(td_head != NULL) - { - uint32_t next = td_head->next; - - // make current's item become reverse's first item - td_head->next = (uint32_t) td_reverse_head; - td_reverse_head = td_head; - - td_head = (ohci_td_item_t*) next; // advance to next item - } - - return td_reverse_head; -} - -static inline bool gtd_is_control(ohci_gtd_t const * const p_qtd) -{ - return ((uint32_t) p_qtd) < ((uint32_t) ohci_data.gtd_pool); // check ohci_data_t for memory layout -} - -static inline ohci_ed_t* gtd_get_ed(ohci_gtd_t const * const p_qtd) -{ - if ( gtd_is_control(p_qtd) ) - { - return &ohci_data.control[p_qtd->index].ed; - }else - { - return &ohci_data.ed_pool[p_qtd->index]; - } -} - -static inline uint32_t gtd_xfer_byte_left(uint32_t buffer_end, uint32_t current_buffer) -{ // 5.2.9 OHCI sample code - return (tu_align4k(buffer_end ^ current_buffer) ? 0x1000 : 0) + - tu_offset4k(buffer_end) - tu_offset4k(current_buffer) + 1; -} - -static void done_queue_isr(uint8_t hostid) -{ - (void) hostid; - - // done head is written in reversed order of completion --> need to reverse the done queue first - ohci_td_item_t* td_head = list_reverse ( (ohci_td_item_t*) tu_align16(ohci_data.hcca.done_head) ); - - while( td_head != NULL ) - { - // TODO check if td_head is iso td - //------------- Non ISO transfer -------------// - ohci_gtd_t * const p_qtd = (ohci_gtd_t *) td_head; - xfer_result_t const event = (p_qtd->condition_code == OHCI_CCODE_NO_ERROR) ? XFER_RESULT_SUCCESS : - (p_qtd->condition_code == OHCI_CCODE_STALL) ? XFER_RESULT_STALLED : XFER_RESULT_FAILED; - - p_qtd->used = 0; // free TD - if ( (p_qtd->delay_interrupt == OHCI_INT_ON_COMPLETE_YES) || (event != XFER_RESULT_SUCCESS) ) - { - ohci_ed_t * const p_ed = gtd_get_ed(p_qtd); - - uint32_t const xferred_bytes = p_qtd->expected_bytes - gtd_xfer_byte_left((uint32_t) p_qtd->buffer_end, (uint32_t) p_qtd->current_buffer_pointer); - - // NOTE Assuming the current list is BULK and there is no other EDs in the list has queued TDs. - // When there is a error resulting this ED is halted, and this EP still has other queued TD - // --> the Bulk list only has this halted EP queueing TDs (remaining) - // --> Bulk list will be considered as not empty by HC !!! while there is no attempt transaction on this list - // --> HC will not process Control list (due to service ratio when Bulk list not empty) - // To walk-around this, the halted ED will have TailP = HeadP (empty list condition), when clearing halt - // the TailP must be set back to NULL for processing remaining TDs - if ((event != XFER_RESULT_SUCCESS)) - { - p_ed->td_tail &= 0x0Ful; - p_ed->td_tail |= tu_align16(p_ed->td_head.address); // mark halted EP as empty queue - if ( event == XFER_RESULT_STALLED ) p_ed->is_stalled = 1; - } - - hcd_event_xfer_complete(p_ed->dev_addr, - tu_edpt_addr(p_ed->ep_number, p_ed->pid == OHCI_PID_IN), - event, xferred_bytes); - } - - td_head = (ohci_td_item_t*) td_head->next; - } -} - -void hcd_isr(uint8_t hostid) -{ - uint32_t const int_en = OHCI_REG->interrupt_enable; - uint32_t const int_status = OHCI_REG->interrupt_status & int_en; - - if (int_status == 0) return; - - //------------- RootHub status -------------// - if ( int_status & OHCI_INT_RHPORT_STATUS_CHANGE_MASK ) - { - uint32_t const rhport_status = OHCI_REG->rhport_status[0] & OHCI_RHPORT_ALL_CHANGE_MASK; - - // TODO dual port is not yet supported - if ( rhport_status & OHCI_RHPORT_CONNECT_STATUS_CHANGE_MASK ) - { - // TODO check if remote wake-up - if ( OHCI_REG->rhport_status_bit[0].current_connect_status ) - { - // TODO reset port immediately, without this controller will got 2-3 (debouncing connection status change) - OHCI_REG->rhport_status[0] = OHCI_RHPORT_PORT_RESET_STATUS_MASK; - hcd_event_device_attach(0); - }else - { - hcd_event_device_remove(0); - } - } - - if ( rhport_status & OHCI_RHPORT_PORT_SUSPEND_CHANGE_MASK) - { - - } - - OHCI_REG->rhport_status[0] = rhport_status; // acknowledge all interrupt - } - - //------------- Transfer Complete -------------// - if ( int_status & OHCI_INT_WRITEBACK_DONEHEAD_MASK) - { - done_queue_isr(hostid); - } - - OHCI_REG->interrupt_status = int_status; // Acknowledge handled interrupt -} -//--------------------------------------------------------------------+ -// HELPER -//--------------------------------------------------------------------+ - - -#endif - +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#include + +#if TUSB_OPT_HOST_ENABLED && (CFG_TUSB_MCU == OPT_MCU_LPC175X_6X || CFG_TUSB_MCU == OPT_MCU_LPC40XX) +//--------------------------------------------------------------------+ +// INCLUDE +//--------------------------------------------------------------------+ +#include "osal/osal.h" + +#include "../hcd.h" +#include "../usbh_hcd.h" +#include "ohci.h" + +// TODO remove +#include "chip.h" + +//--------------------------------------------------------------------+ +// MACRO CONSTANT TYPEDEF +//--------------------------------------------------------------------+ +#define OHCI_REG ((ohci_registers_t *) LPC_USB_BASE) + +enum { + OHCI_CONTROL_FUNCSTATE_RESET = 0, + OHCI_CONTROL_FUNCSTATE_RESUME, + OHCI_CONTROL_FUNCSTATE_OPERATIONAL, + OHCI_CONTROL_FUNCSTATE_SUSPEND +}; + +enum { + OHCI_CONTROL_CONTROL_BULK_RATIO = 3, ///< This specifies the service ratio between Control and Bulk EDs. 0 = 1:1, 3 = 4:1 + OHCI_CONTROL_LIST_PERIODIC_ENABLE_MASK = TU_BIT(2), + OHCI_CONTROL_LIST_ISOCHRONOUS_ENABLE_MASK = TU_BIT(3), + OHCI_CONTROL_LIST_CONTROL_ENABLE_MASK = TU_BIT(4), + OHCI_CONTROL_LIST_BULK_ENABLE_MASK = TU_BIT(5), +}; + +enum { + OHCI_FMINTERVAL_FI = 0x2EDF, // 7.3.1 nominal (reset) value + OHCI_FMINTERVAL_FSMPS = (6*(OHCI_FMINTERVAL_FI-210)) / 7, // 5.4 calculated based on maximum overhead + bit stuffing +}; + +enum { + OHCI_PERIODIC_START = 0x3E67 +}; + +enum { + OHCI_INT_SCHEDULING_OVERUN_MASK = TU_BIT(0), + OHCI_INT_WRITEBACK_DONEHEAD_MASK = TU_BIT(1), + OHCI_INT_SOF_MASK = TU_BIT(2), + OHCI_INT_RESUME_DETECTED_MASK = TU_BIT(3), + OHCI_INT_UNRECOVERABLE_ERROR_MASK = TU_BIT(4), + OHCI_INT_FRAME_OVERFLOW_MASK = TU_BIT(5), + OHCI_INT_RHPORT_STATUS_CHANGE_MASK = TU_BIT(6), + + OHCI_INT_OWNERSHIP_CHANGE_MASK = TU_BIT(30), + OHCI_INT_MASTER_ENABLE_MASK = TU_BIT(31), +}; + +enum { + OHCI_RHPORT_CURRENT_CONNECT_STATUS_MASK = TU_BIT(0), + OHCI_RHPORT_PORT_ENABLE_STATUS_MASK = TU_BIT(1), + OHCI_RHPORT_PORT_SUSPEND_STATUS_MASK = TU_BIT(2), + OHCI_RHPORT_PORT_OVER_CURRENT_INDICATOR_MASK = TU_BIT(3), + OHCI_RHPORT_PORT_RESET_STATUS_MASK = TU_BIT(4), ///< write '1' to reset port + + OHCI_RHPORT_PORT_POWER_STATUS_MASK = TU_BIT(8), + OHCI_RHPORT_LOW_SPEED_DEVICE_ATTACHED_MASK = TU_BIT(9), + + OHCI_RHPORT_CONNECT_STATUS_CHANGE_MASK = TU_BIT(16), + OHCI_RHPORT_PORT_ENABLE_CHANGE_MASK = TU_BIT(17), + OHCI_RHPORT_PORT_SUSPEND_CHANGE_MASK = TU_BIT(18), + OHCI_RHPORT_OVER_CURRENT_CHANGE_MASK = TU_BIT(19), + OHCI_RHPORT_PORT_RESET_CHANGE_MASK = TU_BIT(20), + + OHCI_RHPORT_ALL_CHANGE_MASK = OHCI_RHPORT_CONNECT_STATUS_CHANGE_MASK | OHCI_RHPORT_PORT_ENABLE_CHANGE_MASK | + OHCI_RHPORT_PORT_SUSPEND_CHANGE_MASK | OHCI_RHPORT_OVER_CURRENT_CHANGE_MASK | OHCI_RHPORT_PORT_RESET_CHANGE_MASK +}; + +enum { + OHCI_CCODE_NO_ERROR = 0, + OHCI_CCODE_CRC = 1, + OHCI_CCODE_BIT_STUFFING = 2, + OHCI_CCODE_DATA_TOGGLE_MISMATCH = 3, + OHCI_CCODE_STALL = 4, + OHCI_CCODE_DEVICE_NOT_RESPONDING = 5, + OHCI_CCODE_PID_CHECK_FAILURE = 6, + OHCI_CCODE_UNEXPECTED_PID = 7, + OHCI_CCODE_DATA_OVERRUN = 8, + OHCI_CCODE_DATA_UNDERRUN = 9, + OHCI_CCODE_BUFFER_OVERRUN = 12, + OHCI_CCODE_BUFFER_UNDERRUN = 13, + OHCI_CCODE_NOT_ACCESSED = 14, +}; + +enum { + OHCI_INT_ON_COMPLETE_YES = 0, + OHCI_INT_ON_COMPLETE_NO = TU_BIN8(111) +}; +//--------------------------------------------------------------------+ +// INTERNAL OBJECT & FUNCTION DECLARATION +//--------------------------------------------------------------------+ +CFG_TUSB_MEM_SECTION TU_ATTR_ALIGNED(256) static ohci_data_t ohci_data; + +static ohci_ed_t * const p_ed_head[] = +{ + [TUSB_XFER_CONTROL] = &ohci_data.control[0].ed, + [TUSB_XFER_BULK ] = &ohci_data.bulk_head_ed, + [TUSB_XFER_INTERRUPT] = &ohci_data.period_head_ed, + [TUSB_XFER_ISOCHRONOUS] = NULL // TODO Isochronous +}; + +static void ed_list_insert(ohci_ed_t * p_pre, ohci_ed_t * p_ed); +static void ed_list_remove_by_addr(ohci_ed_t * p_head, uint8_t dev_addr); + +//--------------------------------------------------------------------+ +// USBH-HCD API +//--------------------------------------------------------------------+ +// Initialization according to 5.1.1.4 +bool hcd_init(void) +{ + //------------- Data Structure init -------------// + tu_memclr(&ohci_data, sizeof(ohci_data_t)); + for(uint8_t i=0; i<32; i++) + { // assign all interrupt pointes to period head ed + ohci_data.hcca.interrupt_table[i] = (uint32_t) &ohci_data.period_head_ed; + } + + ohci_data.control[0].ed.skip = 1; + ohci_data.bulk_head_ed.skip = 1; + ohci_data.period_head_ed.skip = 1; + + // reset controller + OHCI_REG->command_status_bit.controller_reset = 1; + while( OHCI_REG->command_status_bit.controller_reset ) {} // should not take longer than 10 us + + //------------- init ohci registers -------------// + OHCI_REG->control_head_ed = (uint32_t) &ohci_data.control[0].ed; + OHCI_REG->bulk_head_ed = (uint32_t) &ohci_data.bulk_head_ed; + OHCI_REG->hcca = (uint32_t) &ohci_data.hcca; + + OHCI_REG->interrupt_disable = OHCI_REG->interrupt_enable; // disable all interrupts + OHCI_REG->interrupt_status = OHCI_REG->interrupt_status; // clear current set bits + OHCI_REG->interrupt_enable = OHCI_INT_WRITEBACK_DONEHEAD_MASK | OHCI_INT_RESUME_DETECTED_MASK | + OHCI_INT_UNRECOVERABLE_ERROR_MASK | /*OHCI_INT_FRAME_OVERFLOW_MASK |*/ OHCI_INT_RHPORT_STATUS_CHANGE_MASK | + OHCI_INT_MASTER_ENABLE_MASK; + + OHCI_REG->control |= OHCI_CONTROL_CONTROL_BULK_RATIO | OHCI_CONTROL_LIST_CONTROL_ENABLE_MASK | + OHCI_CONTROL_LIST_BULK_ENABLE_MASK | OHCI_CONTROL_LIST_PERIODIC_ENABLE_MASK; // TODO Isochronous + + OHCI_REG->frame_interval = (OHCI_FMINTERVAL_FSMPS << 16) | OHCI_FMINTERVAL_FI; + OHCI_REG->periodic_start = (OHCI_FMINTERVAL_FI * 9) / 10; // Periodic start is 90% of frame interval + + OHCI_REG->control_bit.hc_functional_state = OHCI_CONTROL_FUNCSTATE_OPERATIONAL; // make HC's state to operational state TODO use this to suspend (save power) + OHCI_REG->rh_status_bit.local_power_status_change = 1; // set global power for ports + + return true; +} + +//--------------------------------------------------------------------+ +// PORT API +//--------------------------------------------------------------------+ +void hcd_port_reset(uint8_t hostid) +{ + (void) hostid; + OHCI_REG->rhport_status[0] = OHCI_RHPORT_PORT_RESET_STATUS_MASK; +} + +bool hcd_port_connect_status(uint8_t hostid) +{ + (void) hostid; + return OHCI_REG->rhport_status_bit[0].current_connect_status; +} + +tusb_speed_t hcd_port_speed_get(uint8_t hostid) +{ + (void) hostid; + return OHCI_REG->rhport_status_bit[0].low_speed_device_attached ? TUSB_SPEED_LOW : TUSB_SPEED_FULL; +} + +// endpoints are tied to an address, which only reclaim after a long delay when enumerating +// thus there is no need to make sure ED is not in HC's cahed as it will not for sure +void hcd_device_close(uint8_t rhport, uint8_t dev_addr) +{ + // TODO OHCI + (void) rhport; + + // addr0 serves as static head --> only set skip bit + if ( dev_addr == 0 ) + { + ohci_data.control[0].ed.skip = 1; + }else + { + // remove control + ed_list_remove_by_addr( p_ed_head[TUSB_XFER_CONTROL], dev_addr); + + // remove bulk + ed_list_remove_by_addr(p_ed_head[TUSB_XFER_BULK], dev_addr); + + // remove interrupt + ed_list_remove_by_addr(p_ed_head[TUSB_XFER_INTERRUPT], dev_addr); + + // TODO remove ISO + } +} + +//--------------------------------------------------------------------+ +// Controller API +//--------------------------------------------------------------------+ + +//--------------------------------------------------------------------+ +// CONTROL PIPE API +//--------------------------------------------------------------------+ +static inline tusb_xfer_type_t ed_get_xfer_type(ohci_ed_t const * const p_ed) +{ + return (p_ed->ep_number == 0 ) ? TUSB_XFER_CONTROL : + (p_ed->is_iso ) ? TUSB_XFER_ISOCHRONOUS : + (p_ed->is_interrupt_xfer ) ? TUSB_XFER_INTERRUPT : TUSB_XFER_BULK; +} + +static void ed_init(ohci_ed_t *p_ed, uint8_t dev_addr, uint16_t max_packet_size, uint8_t endpoint_addr, uint8_t xfer_type, uint8_t interval) +{ + (void) interval; + + // address 0 is used as async head, which always on the list --> cannot be cleared + if (dev_addr != 0) + { + tu_memclr(p_ed, sizeof(ohci_ed_t)); + } + + p_ed->dev_addr = dev_addr; + p_ed->ep_number = endpoint_addr & 0x0F; + p_ed->pid = (xfer_type == TUSB_XFER_CONTROL) ? OHCI_PID_SETUP : ( (endpoint_addr & TUSB_DIR_IN_MASK) ? OHCI_PID_IN : OHCI_PID_OUT ); + p_ed->speed = _usbh_devices[dev_addr].speed; + p_ed->is_iso = (xfer_type == TUSB_XFER_ISOCHRONOUS) ? 1 : 0; + p_ed->max_packet_size = max_packet_size; + + p_ed->used = 1; + p_ed->is_interrupt_xfer = (xfer_type == TUSB_XFER_INTERRUPT ? 1 : 0); +} + +static void gtd_init(ohci_gtd_t* p_td, void* data_ptr, uint16_t total_bytes) +{ + tu_memclr(p_td, sizeof(ohci_gtd_t)); + + p_td->used = 1; + p_td->expected_bytes = total_bytes; + + p_td->buffer_rounding = 1; // less than queued length is not a error + p_td->delay_interrupt = OHCI_INT_ON_COMPLETE_NO; + p_td->condition_code = OHCI_CCODE_NOT_ACCESSED; + + p_td->current_buffer_pointer = data_ptr; + p_td->buffer_end = total_bytes ? (((uint8_t*) data_ptr) + total_bytes-1) : NULL; +} + +bool hcd_setup_send(uint8_t rhport, uint8_t dev_addr, uint8_t const setup_packet[8]) +{ + (void) rhport; + + ohci_ed_t* p_ed = &ohci_data.control[dev_addr].ed; + ohci_gtd_t *p_setup = &ohci_data.control[dev_addr].gtd; + + gtd_init(p_setup, (void*) setup_packet, 8); + p_setup->index = dev_addr; + p_setup->pid = OHCI_PID_SETUP; + p_setup->data_toggle = TU_BIN8(10); // DATA0 + p_setup->delay_interrupt = OHCI_INT_ON_COMPLETE_YES; + + //------------- Attach TDs list to Control Endpoint -------------// + p_ed->td_head.address = (uint32_t) p_setup; + + OHCI_REG->command_status_bit.control_list_filled = 1; + + return true; +} + +bool hcd_edpt_xfer(uint8_t rhport, uint8_t dev_addr, uint8_t ep_addr, uint8_t * buffer, uint16_t buflen) +{ + (void) rhport; + + uint8_t const epnum = tu_edpt_number(ep_addr); + uint8_t const dir = tu_edpt_dir(ep_addr); + + // FIXME control only for now + if ( epnum == 0 ) + { + ohci_ed_t* const p_ed = &ohci_data.control[dev_addr].ed; + ohci_gtd_t *p_data = &ohci_data.control[dev_addr].gtd; + + gtd_init(p_data, buffer, buflen); + + p_data->index = dev_addr; + p_data->pid = dir ? OHCI_PID_IN : OHCI_PID_OUT; + p_data->data_toggle = TU_BIN8(11); // DATA1 + p_data->delay_interrupt = OHCI_INT_ON_COMPLETE_YES; + + p_ed->td_head.address = (uint32_t) p_data; + + OHCI_REG->command_status_bit.control_list_filled = 1; + } + + return true; +} + +//--------------------------------------------------------------------+ +// BULK/INT/ISO PIPE API +//--------------------------------------------------------------------+ +static inline ohci_ed_t * ed_from_addr(uint8_t dev_addr, uint8_t ep_addr) +{ + if ( tu_edpt_number(ep_addr) == 0 ) return &ohci_data.control[dev_addr].ed; + + ohci_ed_t* ed_pool = ohci_data.ed_pool; + + for(uint32_t i=0; inext = p_pre->next; + p_pre->next = (uint32_t) p_ed; +} + +static void ed_list_remove_by_addr(ohci_ed_t * p_head, uint8_t dev_addr) +{ + ohci_ed_t* p_prev = p_head; + + while( p_prev->next ) + { + ohci_ed_t* ed = (ohci_ed_t*) p_prev->next; + + if (ed->dev_addr == dev_addr) + { + // unlink ed + p_prev->next = ed->next; + + // point the removed ED's next pointer to list head to make sure HC can always safely move away from this ED + ed->next = (uint32_t) p_head; + ed->used = 0; + } + + // check next valid since we could remove it + if (p_prev->next) p_prev = (ohci_ed_t*) p_prev->next; + } +} + +bool hcd_edpt_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_endpoint_t const * ep_desc) +{ + (void) rhport; + + // TODO iso support + TU_ASSERT(ep_desc->bmAttributes.xfer != TUSB_XFER_ISOCHRONOUS); + + //------------- Prepare Queue Head -------------// + ohci_ed_t * p_ed; + + if ( ep_desc->bEndpointAddress == 0 ) + { + p_ed = &ohci_data.control[dev_addr].ed; + }else + { + p_ed = ed_find_free(); + } + TU_ASSERT(p_ed); + + ed_init( p_ed, dev_addr, ep_desc->wMaxPacketSize.size, ep_desc->bEndpointAddress, + ep_desc->bmAttributes.xfer, ep_desc->bInterval ); + + // control of dev0 is used as static async head + if ( dev_addr == 0 ) + { + p_ed->skip = 0; // only need to clear skip bit + return true; + } + + ed_list_insert( p_ed_head[ep_desc->bmAttributes.xfer], p_ed ); + + return true; +} + +static ohci_gtd_t * gtd_find_free(void) +{ + for(uint8_t i=0; i < HCD_MAX_XFER; i++) + { + if ( !ohci_data.gtd_pool[i].used ) return &ohci_data.gtd_pool[i]; + } + + return NULL; +} + +static void td_insert_to_ed(ohci_ed_t* p_ed, ohci_gtd_t * p_gtd) +{ + // tail is always NULL + if ( tu_align16(p_ed->td_head.address) == 0 ) + { // TD queue is empty --> head = TD + p_ed->td_head.address |= (uint32_t) p_gtd; + } + else + { // TODO currently only support queue up to 2 TD each endpoint at a time + ((ohci_gtd_t*) tu_align16(p_ed->td_head.address))->next = (uint32_t) p_gtd; + } +} + +static bool pipe_queue_xfer(uint8_t dev_addr, uint8_t ep_addr, uint8_t buffer[], uint16_t total_bytes, bool int_on_complete) +{ + ohci_ed_t* const p_ed = ed_from_addr(dev_addr, ep_addr); + + // not support ISO yet + TU_VERIFY ( !p_ed->is_iso ); + + ohci_gtd_t * const p_gtd = gtd_find_free(); + TU_ASSERT(p_gtd); // not enough gtd + + gtd_init(p_gtd, buffer, total_bytes); + p_gtd->index = p_ed-ohci_data.ed_pool; + + if ( int_on_complete ) p_gtd->delay_interrupt = OHCI_INT_ON_COMPLETE_YES; + + td_insert_to_ed(p_ed, p_gtd); + + return true; +} + +bool hcd_pipe_queue_xfer(uint8_t dev_addr, uint8_t ep_addr, uint8_t buffer[], uint16_t total_bytes) +{ + return pipe_queue_xfer(dev_addr, ep_addr, buffer, total_bytes, false); +} + +bool hcd_pipe_xfer(uint8_t dev_addr, uint8_t ep_addr, uint8_t buffer[], uint16_t total_bytes, bool int_on_complete) +{ + (void) int_on_complete; + TU_ASSERT( pipe_queue_xfer(dev_addr, ep_addr, buffer, total_bytes, true) ); + + tusb_xfer_type_t xfer_type = ed_get_xfer_type( ed_from_addr(dev_addr, ep_addr) ); + + if (TUSB_XFER_BULK == xfer_type) OHCI_REG->command_status_bit.bulk_list_filled = 1; + + return true; +} + +bool hcd_edpt_busy(uint8_t dev_addr, uint8_t ep_addr) +{ + ohci_ed_t const * const p_ed = ed_from_addr(dev_addr, ep_addr); + return tu_align16(p_ed->td_head.address) != tu_align16(p_ed->td_tail); +} + +bool hcd_edpt_stalled(uint8_t dev_addr, uint8_t ep_addr) +{ + ohci_ed_t const * const p_ed = ed_from_addr(dev_addr, ep_addr); + return p_ed->td_head.halted && p_ed->is_stalled; +} + +bool hcd_edpt_clear_stall(uint8_t dev_addr, uint8_t ep_addr) +{ + ohci_ed_t * const p_ed = ed_from_addr(dev_addr, ep_addr); + + p_ed->is_stalled = 0; + p_ed->td_tail &= 0x0Ful; // set tail pointer back to NULL + + p_ed->td_head.toggle = 0; // reset data toggle + p_ed->td_head.halted = 0; + + if ( TUSB_XFER_BULK == ed_get_xfer_type(p_ed) ) OHCI_REG->command_status_bit.bulk_list_filled = 1; + + return true; +} + + +//--------------------------------------------------------------------+ +// OHCI Interrupt Handler +//--------------------------------------------------------------------+ +static ohci_td_item_t* list_reverse(ohci_td_item_t* td_head) +{ + ohci_td_item_t* td_reverse_head = NULL; + + while(td_head != NULL) + { + uint32_t next = td_head->next; + + // make current's item become reverse's first item + td_head->next = (uint32_t) td_reverse_head; + td_reverse_head = td_head; + + td_head = (ohci_td_item_t*) next; // advance to next item + } + + return td_reverse_head; +} + +static inline bool gtd_is_control(ohci_gtd_t const * const p_qtd) +{ + return ((uint32_t) p_qtd) < ((uint32_t) ohci_data.gtd_pool); // check ohci_data_t for memory layout +} + +static inline ohci_ed_t* gtd_get_ed(ohci_gtd_t const * const p_qtd) +{ + if ( gtd_is_control(p_qtd) ) + { + return &ohci_data.control[p_qtd->index].ed; + }else + { + return &ohci_data.ed_pool[p_qtd->index]; + } +} + +static inline uint32_t gtd_xfer_byte_left(uint32_t buffer_end, uint32_t current_buffer) +{ // 5.2.9 OHCI sample code + return (tu_align4k(buffer_end ^ current_buffer) ? 0x1000 : 0) + + tu_offset4k(buffer_end) - tu_offset4k(current_buffer) + 1; +} + +static void done_queue_isr(uint8_t hostid) +{ + (void) hostid; + + // done head is written in reversed order of completion --> need to reverse the done queue first + ohci_td_item_t* td_head = list_reverse ( (ohci_td_item_t*) tu_align16(ohci_data.hcca.done_head) ); + + while( td_head != NULL ) + { + // TODO check if td_head is iso td + //------------- Non ISO transfer -------------// + ohci_gtd_t * const p_qtd = (ohci_gtd_t *) td_head; + xfer_result_t const event = (p_qtd->condition_code == OHCI_CCODE_NO_ERROR) ? XFER_RESULT_SUCCESS : + (p_qtd->condition_code == OHCI_CCODE_STALL) ? XFER_RESULT_STALLED : XFER_RESULT_FAILED; + + p_qtd->used = 0; // free TD + if ( (p_qtd->delay_interrupt == OHCI_INT_ON_COMPLETE_YES) || (event != XFER_RESULT_SUCCESS) ) + { + ohci_ed_t * const p_ed = gtd_get_ed(p_qtd); + + uint32_t const xferred_bytes = p_qtd->expected_bytes - gtd_xfer_byte_left((uint32_t) p_qtd->buffer_end, (uint32_t) p_qtd->current_buffer_pointer); + + // NOTE Assuming the current list is BULK and there is no other EDs in the list has queued TDs. + // When there is a error resulting this ED is halted, and this EP still has other queued TD + // --> the Bulk list only has this halted EP queueing TDs (remaining) + // --> Bulk list will be considered as not empty by HC !!! while there is no attempt transaction on this list + // --> HC will not process Control list (due to service ratio when Bulk list not empty) + // To walk-around this, the halted ED will have TailP = HeadP (empty list condition), when clearing halt + // the TailP must be set back to NULL for processing remaining TDs + if ((event != XFER_RESULT_SUCCESS)) + { + p_ed->td_tail &= 0x0Ful; + p_ed->td_tail |= tu_align16(p_ed->td_head.address); // mark halted EP as empty queue + if ( event == XFER_RESULT_STALLED ) p_ed->is_stalled = 1; + } + + hcd_event_xfer_complete(p_ed->dev_addr, + tu_edpt_addr(p_ed->ep_number, p_ed->pid == OHCI_PID_IN), + event, xferred_bytes); + } + + td_head = (ohci_td_item_t*) td_head->next; + } +} + +void hcd_isr(uint8_t hostid) +{ + uint32_t const int_en = OHCI_REG->interrupt_enable; + uint32_t const int_status = OHCI_REG->interrupt_status & int_en; + + if (int_status == 0) return; + + //------------- RootHub status -------------// + if ( int_status & OHCI_INT_RHPORT_STATUS_CHANGE_MASK ) + { + uint32_t const rhport_status = OHCI_REG->rhport_status[0] & OHCI_RHPORT_ALL_CHANGE_MASK; + + // TODO dual port is not yet supported + if ( rhport_status & OHCI_RHPORT_CONNECT_STATUS_CHANGE_MASK ) + { + // TODO check if remote wake-up + if ( OHCI_REG->rhport_status_bit[0].current_connect_status ) + { + // TODO reset port immediately, without this controller will got 2-3 (debouncing connection status change) + OHCI_REG->rhport_status[0] = OHCI_RHPORT_PORT_RESET_STATUS_MASK; + hcd_event_device_attach(0); + }else + { + hcd_event_device_remove(0); + } + } + + if ( rhport_status & OHCI_RHPORT_PORT_SUSPEND_CHANGE_MASK) + { + + } + + OHCI_REG->rhport_status[0] = rhport_status; // acknowledge all interrupt + } + + //------------- Transfer Complete -------------// + if ( int_status & OHCI_INT_WRITEBACK_DONEHEAD_MASK) + { + done_queue_isr(hostid); + } + + OHCI_REG->interrupt_status = int_status; // Acknowledge handled interrupt +} +//--------------------------------------------------------------------+ +// HELPER +//--------------------------------------------------------------------+ + + +#endif + diff --git a/src/host/ohci/ohci.h b/src/host/ohci/ohci.h index a8aae251..6f6ef967 100644 --- a/src/host/ohci/ohci.h +++ b/src/host/ohci/ohci.h @@ -1,291 +1,291 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2019 Ha Thach (tinyusb.org) - * - * 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. - * - * This file is part of the TinyUSB stack. - */ - -/** \ingroup Group_HCD - * @{ - * \defgroup OHCI - * \brief OHCI driver. All documents sources mentioned here (eg section 3.5) is referring to OHCI Specs unless state otherwise - * @{ */ - -#ifndef _TUSB_OHCI_H_ -#define _TUSB_OHCI_H_ - -#ifdef __cplusplus - extern "C" { -#endif - -#include "common/tusb_common.h" - -//--------------------------------------------------------------------+ -// OHCI CONFIGURATION & CONSTANTS -//--------------------------------------------------------------------+ -#define HOST_HCD_XFER_INTERRUPT // TODO interrupt is used widely, should always be enalbed -#define OHCI_PERIODIC_LIST (defined HOST_HCD_XFER_INTERRUPT || defined HOST_HCD_XFER_ISOCHRONOUS) - -// TODO merge OHCI with EHCI -enum { - OHCI_MAX_ITD = 4 -}; - -enum { - OHCI_PID_SETUP = 0, - OHCI_PID_OUT, - OHCI_PID_IN, -}; - -//--------------------------------------------------------------------+ -// OHCI Data Structure -//--------------------------------------------------------------------+ -typedef struct { - uint32_t interrupt_table[32]; - volatile uint16_t frame_number; - volatile uint16_t frame_pad; - volatile uint32_t done_head; - uint8_t reserved[116+4]; // TODO try to make use of this area if possible, extra 4 byte to make the whole struct size = 256 -}ohci_hcca_t; // TU_ATTR_ALIGNED(256) - -TU_VERIFY_STATIC( sizeof(ohci_hcca_t) == 256, "size is not correct" ); - -typedef struct { - uint32_t reserved[2]; - volatile uint32_t next; - uint32_t reserved2; -}ohci_td_item_t; - - -typedef struct TU_ATTR_ALIGNED(16) -{ - // Word 0 - uint32_t used : 1; - uint32_t index : 4; // endpoint index the td belongs to, or device address in case of control xfer - uint32_t expected_bytes : 13; // TODO available for hcd - - uint32_t buffer_rounding : 1; - uint32_t pid : 2; - uint32_t delay_interrupt : 3; - volatile uint32_t data_toggle : 2; - volatile uint32_t error_count : 2; - volatile uint32_t condition_code : 4; - - // Word 1 - volatile uint8_t* current_buffer_pointer; - - // Word 2 : next TD - volatile uint32_t next; - - // Word 3 - uint8_t* buffer_end; -} ohci_gtd_t; - -TU_VERIFY_STATIC( sizeof(ohci_gtd_t) == 16, "size is not correct" ); - -typedef struct TU_ATTR_ALIGNED(16) -{ - // Word 0 - uint32_t dev_addr : 7; - uint32_t ep_number : 4; - uint32_t pid : 2; // 00b from TD, 01b Out, 10b In - uint32_t speed : 1; - uint32_t skip : 1; - uint32_t is_iso : 1; - uint32_t max_packet_size : 11; - // HCD: make use of 5 reserved bits - uint32_t used : 1; - uint32_t is_interrupt_xfer : 1; - uint32_t is_stalled : 1; - uint32_t : 2; - - // Word 1 - uint32_t td_tail; - - // Word 2 - volatile union { - uint32_t address; - struct { - uint32_t halted : 1; - uint32_t toggle : 1; - uint32_t : 30; - }; - }td_head; - - // Word 3: next ED - uint32_t next; -} ohci_ed_t; - -TU_VERIFY_STATIC( sizeof(ohci_ed_t) == 16, "size is not correct" ); - -typedef struct TU_ATTR_ALIGNED(32) -{ - /*---------- Word 1 ----------*/ - uint32_t starting_frame : 16; - uint32_t : 5; // can be used - uint32_t delay_interrupt : 3; - uint32_t frame_count : 3; - uint32_t : 1; // can be used - volatile uint32_t condition_code : 4; - - /*---------- Word 2 ----------*/ - uint32_t buffer_page0; // 12 lsb bits can be used - - /*---------- Word 3 ----------*/ - volatile uint32_t next; - - /*---------- Word 4 ----------*/ - uint32_t buffer_end; - - /*---------- Word 5-8 ----------*/ - volatile uint16_t offset_packetstatus[8]; -} ochi_itd_t; - -TU_VERIFY_STATIC( sizeof(ochi_itd_t) == 32, "size is not correct" ); - -// structure with member alignment required from large to small -typedef struct TU_ATTR_ALIGNED(256) -{ - ohci_hcca_t hcca; - - ohci_ed_t bulk_head_ed; // static bulk head (dummy) - ohci_ed_t period_head_ed; // static periodic list head (dummy) - - // control endpoints has reserved resources - struct { - ohci_ed_t ed; - ohci_gtd_t gtd; - }control[CFG_TUSB_HOST_DEVICE_MAX+1]; - - // ochi_itd_t itd[OHCI_MAX_ITD]; // itd requires alignment of 32 - ohci_ed_t ed_pool[HCD_MAX_ENDPOINT]; - ohci_gtd_t gtd_pool[HCD_MAX_XFER]; - -} ohci_data_t; - -//--------------------------------------------------------------------+ -// OHCI Operational Register -//--------------------------------------------------------------------+ - - -//--------------------------------------------------------------------+ -// OHCI Data Organization -//--------------------------------------------------------------------+ -typedef volatile struct -{ - uint32_t revision; - - union { - uint32_t control; - struct { - uint32_t control_bulk_service_ratio : 2; - uint32_t periodic_list_enable : 1; - uint32_t isochronous_enable : 1; - uint32_t control_list_enable : 1; - uint32_t bulk_list_enable : 1; - uint32_t hc_functional_state : 2; - uint32_t interrupt_routing : 1; - uint32_t remote_wakeup_connected : 1; - uint32_t remote_wakeup_enale : 1; - uint32_t : 0; - }control_bit; - }; - - union { - uint32_t command_status; - struct { - uint32_t controller_reset : 1; - uint32_t control_list_filled : 1; - uint32_t bulk_list_filled : 1; - uint32_t ownership_change_request : 1; - uint32_t : 12; - uint32_t scheduling_overrun_count : 2; - }command_status_bit; - }; - - uint32_t interrupt_status; - uint32_t interrupt_enable; - uint32_t interrupt_disable; - - uint32_t hcca; - uint32_t period_current_ed; - uint32_t control_head_ed; - uint32_t control_current_ed; - uint32_t bulk_head_ed; - uint32_t bulk_current_ed; - uint32_t done_head; - - uint32_t frame_interval; - uint32_t frame_remaining; - uint32_t frame_number; - uint32_t periodic_start; - uint32_t lowspeed_threshold; - - uint32_t rh_descriptorA; - uint32_t rh_descriptorB; - - union { - uint32_t rh_status; - struct { - uint32_t local_power_status : 1; // read Local Power Status; write: Clear Global Power - uint32_t over_current_indicator : 1; - uint32_t : 13; - uint32_t device_remote_wakeup_enable : 1; - uint32_t local_power_status_change : 1; - uint32_t over_current_indicator_change : 1; - uint32_t : 13; - uint32_t clear_remote_wakeup_enable : 1; - }rh_status_bit; - }; - - union { - uint32_t rhport_status[2]; // TODO NXP OHCI controller only has 2 ports - struct { - uint32_t current_connect_status : 1; - uint32_t port_enable_status : 1; - uint32_t port_suspend_status : 1; - uint32_t port_over_current_indicator : 1; - uint32_t port_reset_status : 1; - uint32_t : 3; - uint32_t port_power_status : 1; - uint32_t low_speed_device_attached : 1; - uint32_t : 6; - uint32_t connect_status_change : 1; - uint32_t port_enable_status_change : 1; - uint32_t port_suspend_status_change : 1; - uint32_t port_over_current_indicator_change : 1; - uint32_t port_reset_status_change : 1; - uint32_t : 0; - }rhport_status_bit[2]; - }; -}ohci_registers_t; - -TU_VERIFY_STATIC( sizeof(ohci_registers_t) == 0x5c, "size is not correct"); - -#ifdef __cplusplus - } -#endif - -#endif /* _TUSB_OHCI_H_ */ - -/** @} */ -/** @} */ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +/** \ingroup Group_HCD + * @{ + * \defgroup OHCI + * \brief OHCI driver. All documents sources mentioned here (eg section 3.5) is referring to OHCI Specs unless state otherwise + * @{ */ + +#ifndef _TUSB_OHCI_H_ +#define _TUSB_OHCI_H_ + +#ifdef __cplusplus + extern "C" { +#endif + +#include "common/tusb_common.h" + +//--------------------------------------------------------------------+ +// OHCI CONFIGURATION & CONSTANTS +//--------------------------------------------------------------------+ +#define HOST_HCD_XFER_INTERRUPT // TODO interrupt is used widely, should always be enalbed +#define OHCI_PERIODIC_LIST (defined HOST_HCD_XFER_INTERRUPT || defined HOST_HCD_XFER_ISOCHRONOUS) + +// TODO merge OHCI with EHCI +enum { + OHCI_MAX_ITD = 4 +}; + +enum { + OHCI_PID_SETUP = 0, + OHCI_PID_OUT, + OHCI_PID_IN, +}; + +//--------------------------------------------------------------------+ +// OHCI Data Structure +//--------------------------------------------------------------------+ +typedef struct { + uint32_t interrupt_table[32]; + volatile uint16_t frame_number; + volatile uint16_t frame_pad; + volatile uint32_t done_head; + uint8_t reserved[116+4]; // TODO try to make use of this area if possible, extra 4 byte to make the whole struct size = 256 +}ohci_hcca_t; // TU_ATTR_ALIGNED(256) + +TU_VERIFY_STATIC( sizeof(ohci_hcca_t) == 256, "size is not correct" ); + +typedef struct { + uint32_t reserved[2]; + volatile uint32_t next; + uint32_t reserved2; +}ohci_td_item_t; + + +typedef struct TU_ATTR_ALIGNED(16) +{ + // Word 0 + uint32_t used : 1; + uint32_t index : 4; // endpoint index the td belongs to, or device address in case of control xfer + uint32_t expected_bytes : 13; // TODO available for hcd + + uint32_t buffer_rounding : 1; + uint32_t pid : 2; + uint32_t delay_interrupt : 3; + volatile uint32_t data_toggle : 2; + volatile uint32_t error_count : 2; + volatile uint32_t condition_code : 4; + + // Word 1 + volatile uint8_t* current_buffer_pointer; + + // Word 2 : next TD + volatile uint32_t next; + + // Word 3 + uint8_t* buffer_end; +} ohci_gtd_t; + +TU_VERIFY_STATIC( sizeof(ohci_gtd_t) == 16, "size is not correct" ); + +typedef struct TU_ATTR_ALIGNED(16) +{ + // Word 0 + uint32_t dev_addr : 7; + uint32_t ep_number : 4; + uint32_t pid : 2; // 00b from TD, 01b Out, 10b In + uint32_t speed : 1; + uint32_t skip : 1; + uint32_t is_iso : 1; + uint32_t max_packet_size : 11; + // HCD: make use of 5 reserved bits + uint32_t used : 1; + uint32_t is_interrupt_xfer : 1; + uint32_t is_stalled : 1; + uint32_t : 2; + + // Word 1 + uint32_t td_tail; + + // Word 2 + volatile union { + uint32_t address; + struct { + uint32_t halted : 1; + uint32_t toggle : 1; + uint32_t : 30; + }; + }td_head; + + // Word 3: next ED + uint32_t next; +} ohci_ed_t; + +TU_VERIFY_STATIC( sizeof(ohci_ed_t) == 16, "size is not correct" ); + +typedef struct TU_ATTR_ALIGNED(32) +{ + /*---------- Word 1 ----------*/ + uint32_t starting_frame : 16; + uint32_t : 5; // can be used + uint32_t delay_interrupt : 3; + uint32_t frame_count : 3; + uint32_t : 1; // can be used + volatile uint32_t condition_code : 4; + + /*---------- Word 2 ----------*/ + uint32_t buffer_page0; // 12 lsb bits can be used + + /*---------- Word 3 ----------*/ + volatile uint32_t next; + + /*---------- Word 4 ----------*/ + uint32_t buffer_end; + + /*---------- Word 5-8 ----------*/ + volatile uint16_t offset_packetstatus[8]; +} ochi_itd_t; + +TU_VERIFY_STATIC( sizeof(ochi_itd_t) == 32, "size is not correct" ); + +// structure with member alignment required from large to small +typedef struct TU_ATTR_ALIGNED(256) +{ + ohci_hcca_t hcca; + + ohci_ed_t bulk_head_ed; // static bulk head (dummy) + ohci_ed_t period_head_ed; // static periodic list head (dummy) + + // control endpoints has reserved resources + struct { + ohci_ed_t ed; + ohci_gtd_t gtd; + }control[CFG_TUSB_HOST_DEVICE_MAX+1]; + + // ochi_itd_t itd[OHCI_MAX_ITD]; // itd requires alignment of 32 + ohci_ed_t ed_pool[HCD_MAX_ENDPOINT]; + ohci_gtd_t gtd_pool[HCD_MAX_XFER]; + +} ohci_data_t; + +//--------------------------------------------------------------------+ +// OHCI Operational Register +//--------------------------------------------------------------------+ + + +//--------------------------------------------------------------------+ +// OHCI Data Organization +//--------------------------------------------------------------------+ +typedef volatile struct +{ + uint32_t revision; + + union { + uint32_t control; + struct { + uint32_t control_bulk_service_ratio : 2; + uint32_t periodic_list_enable : 1; + uint32_t isochronous_enable : 1; + uint32_t control_list_enable : 1; + uint32_t bulk_list_enable : 1; + uint32_t hc_functional_state : 2; + uint32_t interrupt_routing : 1; + uint32_t remote_wakeup_connected : 1; + uint32_t remote_wakeup_enale : 1; + uint32_t : 0; + }control_bit; + }; + + union { + uint32_t command_status; + struct { + uint32_t controller_reset : 1; + uint32_t control_list_filled : 1; + uint32_t bulk_list_filled : 1; + uint32_t ownership_change_request : 1; + uint32_t : 12; + uint32_t scheduling_overrun_count : 2; + }command_status_bit; + }; + + uint32_t interrupt_status; + uint32_t interrupt_enable; + uint32_t interrupt_disable; + + uint32_t hcca; + uint32_t period_current_ed; + uint32_t control_head_ed; + uint32_t control_current_ed; + uint32_t bulk_head_ed; + uint32_t bulk_current_ed; + uint32_t done_head; + + uint32_t frame_interval; + uint32_t frame_remaining; + uint32_t frame_number; + uint32_t periodic_start; + uint32_t lowspeed_threshold; + + uint32_t rh_descriptorA; + uint32_t rh_descriptorB; + + union { + uint32_t rh_status; + struct { + uint32_t local_power_status : 1; // read Local Power Status; write: Clear Global Power + uint32_t over_current_indicator : 1; + uint32_t : 13; + uint32_t device_remote_wakeup_enable : 1; + uint32_t local_power_status_change : 1; + uint32_t over_current_indicator_change : 1; + uint32_t : 13; + uint32_t clear_remote_wakeup_enable : 1; + }rh_status_bit; + }; + + union { + uint32_t rhport_status[2]; // TODO NXP OHCI controller only has 2 ports + struct { + uint32_t current_connect_status : 1; + uint32_t port_enable_status : 1; + uint32_t port_suspend_status : 1; + uint32_t port_over_current_indicator : 1; + uint32_t port_reset_status : 1; + uint32_t : 3; + uint32_t port_power_status : 1; + uint32_t low_speed_device_attached : 1; + uint32_t : 6; + uint32_t connect_status_change : 1; + uint32_t port_enable_status_change : 1; + uint32_t port_suspend_status_change : 1; + uint32_t port_over_current_indicator_change : 1; + uint32_t port_reset_status_change : 1; + uint32_t : 0; + }rhport_status_bit[2]; + }; +}ohci_registers_t; + +TU_VERIFY_STATIC( sizeof(ohci_registers_t) == 0x5c, "size is not correct"); + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_OHCI_H_ */ + +/** @} */ +/** @} */ diff --git a/src/host/usbh.c b/src/host/usbh.c index 9e1861f8..f1b88259 100644 --- a/src/host/usbh.c +++ b/src/host/usbh.c @@ -1,676 +1,676 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2019 Ha Thach (tinyusb.org) - * - * 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. - * - * This file is part of the TinyUSB stack. - */ - -#include "common/tusb_common.h" - -#if TUSB_OPT_HOST_ENABLED - -#ifndef CFG_TUH_TASK_QUEUE_SZ -#define CFG_TUH_TASK_QUEUE_SZ 16 -#endif - -//--------------------------------------------------------------------+ -// INCLUDE -//--------------------------------------------------------------------+ -#include "tusb.h" -#include "hub.h" -#include "usbh_hcd.h" - -//--------------------------------------------------------------------+ -// MACRO CONSTANT TYPEDEF -//--------------------------------------------------------------------+ -static host_class_driver_t const usbh_class_drivers[] = -{ - #if CFG_TUH_CDC - { - .class_code = TUSB_CLASS_CDC, - .init = cdch_init, - .open = cdch_open, - .isr = cdch_isr, - .close = cdch_close - }, - #endif - - #if CFG_TUH_MSC - { - .class_code = TUSB_CLASS_MSC, - .init = msch_init, - .open = msch_open, - .isr = msch_isr, - .close = msch_close - }, - #endif - - #if HOST_CLASS_HID - { - .class_code = TUSB_CLASS_HID, - .init = hidh_init, - .open = hidh_open_subtask, - .isr = hidh_isr, - .close = hidh_close - }, - #endif - - #if CFG_TUH_HUB - { - .class_code = TUSB_CLASS_HUB, - .init = hub_init, - .open = hub_open, - .isr = hub_isr, - .close = hub_close - }, - #endif - - #if CFG_TUH_VENDOR - { - .class_code = TUSB_CLASS_VENDOR_SPECIFIC, - .init = cush_init, - .open = cush_open_subtask, - .isr = cush_isr, - .close = cush_close - } - #endif -}; - -enum { USBH_CLASS_DRIVER_COUNT = TU_ARRAY_SIZE(usbh_class_drivers) }; - -//--------------------------------------------------------------------+ -// INTERNAL OBJECT & FUNCTION DECLARATION -//--------------------------------------------------------------------+ - -// including zero-address -CFG_TUSB_MEM_SECTION usbh_device_t _usbh_devices[CFG_TUSB_HOST_DEVICE_MAX+1]; - -// Event queue -// role device/host is used by OS NONE for mutex (disable usb isr) only -OSAL_QUEUE_DEF(OPT_MODE_HOST, _usbh_qdef, CFG_TUH_TASK_QUEUE_SZ, hcd_event_t); -static osal_queue_t _usbh_q; - -CFG_TUSB_MEM_SECTION TU_ATTR_ALIGNED(4) static uint8_t _usbh_ctrl_buf[CFG_TUSB_HOST_ENUM_BUFFER_SIZE]; - -//------------- Reporter Task Data -------------// - -//------------- Helper Function Prototypes -------------// -static inline uint8_t get_new_address(void); -static inline uint8_t get_configure_number_for_device(tusb_desc_device_t* dev_desc); -static void mark_interface_endpoint(uint8_t ep2drv[8][2], uint8_t const* p_desc, uint16_t desc_len, uint8_t driver_id); - -//--------------------------------------------------------------------+ -// PUBLIC API (Parameter Verification is required) -//--------------------------------------------------------------------+ -tusb_device_state_t tuh_device_get_state (uint8_t const dev_addr) -{ - TU_ASSERT( dev_addr <= CFG_TUSB_HOST_DEVICE_MAX, TUSB_DEVICE_STATE_UNPLUG); - return (tusb_device_state_t) _usbh_devices[dev_addr].state; -} - -//--------------------------------------------------------------------+ -// CLASS-USBD API (don't require to verify parameters) -//--------------------------------------------------------------------+ -bool usbh_init(void) -{ - tu_memclr(_usbh_devices, sizeof(usbh_device_t)*(CFG_TUSB_HOST_DEVICE_MAX+1)); - - //------------- Enumeration & Reporter Task init -------------// - _usbh_q = osal_queue_create( &_usbh_qdef ); - TU_ASSERT(_usbh_q != NULL); - - //------------- Semaphore, Mutex for Control Pipe -------------// - for(uint8_t i=0; icontrol.sem_hdl = osal_semaphore_create(&dev->control.sem_def); - TU_ASSERT(dev->control.sem_hdl != NULL); - - dev->control.mutex_hdl = osal_mutex_create(&dev->control.mutex_def); - TU_ASSERT(dev->control.mutex_hdl != NULL); - - memset(dev->itf2drv, 0xff, sizeof(dev->itf2drv)); // invalid mapping - memset(dev->ep2drv , 0xff, sizeof(dev->ep2drv )); // invalid mapping - } - - // Class drivers init - for (uint8_t drv_id = 0; drv_id < USBH_CLASS_DRIVER_COUNT; drv_id++) usbh_class_drivers[drv_id].init(); - - TU_ASSERT(hcd_init()); - hcd_int_enable(TUH_OPT_RHPORT); - - return true; -} - -//------------- USBH control transfer -------------// -bool usbh_control_xfer (uint8_t dev_addr, tusb_control_request_t* request, uint8_t* data) -{ - usbh_device_t* dev = &_usbh_devices[dev_addr]; - const uint8_t rhport = dev->rhport; - - TU_ASSERT(osal_mutex_lock(dev->control.mutex_hdl, OSAL_TIMEOUT_NORMAL)); - - dev->control.request = *request; - dev->control.pipe_status = 0; - - // Setup Stage - hcd_setup_send(rhport, dev_addr, (uint8_t*) &dev->control.request); - TU_VERIFY(osal_semaphore_wait(dev->control.sem_hdl, OSAL_TIMEOUT_NORMAL)); - - // Data stage : first data toggle is always 1 - if ( request->wLength ) - { - hcd_edpt_xfer(rhport, dev_addr, tu_edpt_addr(0, request->bmRequestType_bit.direction), data, request->wLength); - TU_VERIFY(osal_semaphore_wait(dev->control.sem_hdl, OSAL_TIMEOUT_NORMAL)); - } - - // Status : data toggle is always 1 - hcd_edpt_xfer(rhport, dev_addr, tu_edpt_addr(0, 1-request->bmRequestType_bit.direction), NULL, 0); - TU_VERIFY(osal_semaphore_wait(dev->control.sem_hdl, OSAL_TIMEOUT_NORMAL)); - - osal_mutex_unlock(dev->control.mutex_hdl); - - if ( XFER_RESULT_STALLED == dev->control.pipe_status ) return false; - if ( XFER_RESULT_FAILED == dev->control.pipe_status ) return false; - - return true; -} - -tusb_error_t usbh_pipe_control_open(uint8_t dev_addr, uint8_t max_packet_size) -{ - osal_semaphore_reset( _usbh_devices[dev_addr].control.sem_hdl ); - //osal_mutex_reset( usbh_devices[dev_addr].control.mutex_hdl ); - - tusb_desc_endpoint_t ep0_desc = - { - .bLength = sizeof(tusb_desc_endpoint_t), - .bDescriptorType = TUSB_DESC_ENDPOINT, - .bEndpointAddress = 0, - .bmAttributes = { .xfer = TUSB_XFER_CONTROL }, - .wMaxPacketSize = { .size = max_packet_size }, - .bInterval = 0 - }; - - hcd_edpt_open(_usbh_devices[dev_addr].rhport, dev_addr, &ep0_desc); - - return TUSB_ERROR_NONE; -} - -//--------------------------------------------------------------------+ -// USBH-HCD ISR/Callback API -//--------------------------------------------------------------------+ -// interrupt caused by a TD (with IOC=1) in pipe of class class_code -void hcd_event_xfer_complete(uint8_t dev_addr, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes) -{ - usbh_device_t* dev = &_usbh_devices[ dev_addr ]; - - if (0 == tu_edpt_number(ep_addr)) - { - dev->control.pipe_status = event; -// usbh_devices[ pipe_hdl.dev_addr ].control.xferred_bytes = xferred_bytes; not yet neccessary - osal_semaphore_post( dev->control.sem_hdl, true ); - } - else - { - uint8_t drv_id = dev->ep2drv[tu_edpt_number(ep_addr)][tu_edpt_dir(ep_addr)]; - TU_ASSERT(drv_id < USBH_CLASS_DRIVER_COUNT, ); - - if (usbh_class_drivers[drv_id].isr) - { - usbh_class_drivers[drv_id].isr(dev_addr, ep_addr, event, xferred_bytes); - } - else - { - TU_BREAKPOINT(); // something wrong, no one claims the isr's source - } - } -} - -void hcd_event_device_attach(uint8_t rhport) -{ - hcd_event_t event = - { - .rhport = rhport, - .event_id = HCD_EVENT_DEVICE_ATTACH - }; - - event.attach.hub_addr = 0; - event.attach.hub_port = 0; - - hcd_event_handler(&event, true); -} - -void hcd_event_handler(hcd_event_t const* event, bool in_isr) -{ - switch (event->event_id) - { - default: - osal_queue_send(_usbh_q, event, in_isr); - break; - } -} - -void hcd_event_device_remove(uint8_t hostid) -{ - hcd_event_t event = - { - .rhport = hostid, - .event_id = HCD_EVENT_DEVICE_REMOVE - }; - - event.attach.hub_addr = 0; - event.attach.hub_port = 0; - - hcd_event_handler(&event, true); -} - - -// a device unplugged on hostid, hub_addr, hub_port -// return true if found and unmounted device, false if cannot find -static void usbh_device_unplugged(uint8_t rhport, uint8_t hub_addr, uint8_t hub_port) -{ - //------------- find the all devices (star-network) under port that is unplugged -------------// - for (uint8_t dev_addr = 0; dev_addr <= CFG_TUSB_HOST_DEVICE_MAX; dev_addr ++) - { - usbh_device_t* dev = &_usbh_devices[dev_addr]; - - // TODO Hub multiple level - if (dev->rhport == rhport && - (hub_addr == 0 || dev->hub_addr == hub_addr) && // hub_addr == 0 & hub_port == 0 means roothub - (hub_port == 0 || dev->hub_port == hub_port) && - dev->state != TUSB_DEVICE_STATE_UNPLUG) - { - // Invoke callback before close driver - if (tuh_umount_cb) tuh_umount_cb(dev_addr); - - // Close class driver - for (uint8_t drv_id = 0; drv_id < USBH_CLASS_DRIVER_COUNT; drv_id++) usbh_class_drivers[drv_id].close(dev_addr); - - memset(dev->itf2drv, 0xff, sizeof(dev->itf2drv)); // invalid mapping - memset(dev->ep2drv , 0xff, sizeof(dev->ep2drv )); // invalid mapping - - hcd_device_close(rhport, dev_addr); - - dev->state = TUSB_DEVICE_STATE_UNPLUG; - } - } -} - -//--------------------------------------------------------------------+ -// ENUMERATION TASK -//--------------------------------------------------------------------+ - -bool enum_task(hcd_event_t* event) -{ - enum { -#if 1 - // FIXME ohci LPC1769 xpresso + debugging to have 1st control xfer to work, some kind of timing or ohci driver issue !!! - POWER_STABLE_DELAY = 100, - RESET_DELAY = 500 -#else - POWER_STABLE_DELAY = 500, - RESET_DELAY = 200, // USB specs say only 50ms but many devices require much longer -#endif - }; - - // for OSAL_NONE local variable won't retain value after blocking service sem_wait/queue_recv - static uint8_t configure_selected = 1; // TODO move - - usbh_device_t* dev0 = &_usbh_devices[0]; - tusb_control_request_t request; - - dev0->rhport = event->rhport; // TODO refractor integrate to device_pool - dev0->hub_addr = event->attach.hub_addr; - dev0->hub_port = event->attach.hub_port; - dev0->state = TUSB_DEVICE_STATE_UNPLUG; - - //------------- connected/disconnected directly with roothub -------------// - if ( dev0->hub_addr == 0) - { - if( hcd_port_connect_status(dev0->rhport) ) - { - // connection event - osal_task_delay(POWER_STABLE_DELAY); // wait until device is stable. Increase this if the first 8 bytes is failed to get - - // exit if device unplugged while delaying - if ( !hcd_port_connect_status(dev0->rhport) ) return true; - - hcd_port_reset( dev0->rhport ); // port must be reset to have correct speed operation - osal_task_delay(RESET_DELAY); - - dev0->speed = hcd_port_speed_get( dev0->rhport ); - } - else - { - // disconnection event - usbh_device_unplugged(dev0->rhport, 0, 0); - return true; // restart task - } - } - #if CFG_TUH_HUB - //------------- connected/disconnected via hub -------------// - else - { - //------------- Get Port Status -------------// - request = (tusb_control_request_t ) { - .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_OTHER, .type = TUSB_REQ_TYPE_CLASS, .direction = TUSB_DIR_IN }, - .bRequest = HUB_REQUEST_GET_STATUS, - .wValue = 0, - .wIndex = dev0->hub_port, - .wLength = 4 - }; - // TODO hub refractor - TU_VERIFY_HDLR( usbh_control_xfer( dev0->hub_addr, &request, _usbh_ctrl_buf ), hub_status_pipe_queue( dev0->hub_addr) ); - - // Acknowledge Port Connection Change - hub_port_clear_feature_subtask(dev0->hub_addr, dev0->hub_port, HUB_FEATURE_PORT_CONNECTION_CHANGE); - - hub_port_status_response_t * p_port_status; - p_port_status = ((hub_port_status_response_t *) _usbh_ctrl_buf); - - if ( ! p_port_status->status_change.connect_status ) return true; // only handle connection change - - if ( ! p_port_status->status_current.connect_status ) - { - // Disconnection event - usbh_device_unplugged(dev0->rhport, dev0->hub_addr, dev0->hub_port); - - (void) hub_status_pipe_queue( dev0->hub_addr ); // done with hub, waiting for next data on status pipe - return true; // restart task - } - else - { - // Connection Event - TU_VERIFY_HDLR(hub_port_reset_subtask(dev0->hub_addr, dev0->hub_port), - hub_status_pipe_queue( dev0->hub_addr) ); // TODO hub refractor - - dev0->speed = hub_port_get_speed(); - - // Acknowledge Port Reset Change - hub_port_clear_feature_subtask(dev0->hub_addr, dev0->hub_port, HUB_FEATURE_PORT_RESET_CHANGE); - } - } - #endif - - TU_ASSERT_ERR( usbh_pipe_control_open(0, 8) ); - - //------------- Get first 8 bytes of device descriptor to get Control Endpoint Size -------------// - request = (tusb_control_request_t ) { - .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_DEVICE, .type = TUSB_REQ_TYPE_STANDARD, .direction = TUSB_DIR_IN }, - .bRequest = TUSB_REQ_GET_DESCRIPTOR, - .wValue = TUSB_DESC_DEVICE << 8, - .wIndex = 0, - .wLength = 8 - }; - bool is_ok = usbh_control_xfer(0, &request, _usbh_ctrl_buf); - - //------------- Reset device again before Set Address -------------// - if (dev0->hub_addr == 0) - { - // connected directly to roothub - TU_ASSERT(is_ok); // TODO some slow device is observed to fail the very fist controller xfer, can try more times - hcd_port_reset( dev0->rhport ); // reset port after 8 byte descriptor - osal_task_delay(RESET_DELAY); - } - #if CFG_TUH_HUB - else - { - // connected via a hub - TU_VERIFY_HDLR(is_ok, hub_status_pipe_queue( dev0->hub_addr) ); // TODO hub refractor - - if ( hub_port_reset_subtask(dev0->hub_addr, dev0->hub_port) ) - { - // Acknowledge Port Reset Change if Reset Successful - hub_port_clear_feature_subtask(dev0->hub_addr, dev0->hub_port, HUB_FEATURE_PORT_RESET_CHANGE); - } - - (void) hub_status_pipe_queue( dev0->hub_addr ); // done with hub, waiting for next data on status pipe - } - #endif - - //------------- Set new address -------------// - uint8_t const new_addr = get_new_address(); - TU_ASSERT(new_addr <= CFG_TUSB_HOST_DEVICE_MAX); // TODO notify application we reach max devices - - request = (tusb_control_request_t ) { - .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_DEVICE, .type = TUSB_REQ_TYPE_STANDARD, .direction = TUSB_DIR_OUT }, - .bRequest = TUSB_REQ_SET_ADDRESS, - .wValue = new_addr, - .wIndex = 0, - .wLength = 0 - }; - TU_ASSERT(usbh_control_xfer(0, &request, NULL)); - - //------------- update port info & close control pipe of addr0 -------------// - usbh_device_t* new_dev = &_usbh_devices[new_addr]; - new_dev->rhport = dev0->rhport; - new_dev->hub_addr = dev0->hub_addr; - new_dev->hub_port = dev0->hub_port; - new_dev->speed = dev0->speed; - - hcd_device_close(dev0->rhport, 0); // close device 0 - dev0->state = TUSB_DEVICE_STATE_UNPLUG; - - // open control pipe for new address - TU_ASSERT_ERR ( usbh_pipe_control_open(new_addr, ((tusb_desc_device_t*) _usbh_ctrl_buf)->bMaxPacketSize0 ) ); - - //------------- Get full device descriptor -------------// - request = (tusb_control_request_t ) { - .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_DEVICE, .type = TUSB_REQ_TYPE_STANDARD, .direction = TUSB_DIR_IN }, - .bRequest = TUSB_REQ_GET_DESCRIPTOR, - .wValue = TUSB_DESC_DEVICE << 8, - .wIndex = 0, - .wLength = 18 - }; - TU_ASSERT(usbh_control_xfer(new_addr, &request, _usbh_ctrl_buf)); - - // update device info TODO alignment issue - new_dev->vendor_id = ((tusb_desc_device_t*) _usbh_ctrl_buf)->idVendor; - new_dev->product_id = ((tusb_desc_device_t*) _usbh_ctrl_buf)->idProduct; - new_dev->configure_count = ((tusb_desc_device_t*) _usbh_ctrl_buf)->bNumConfigurations; - - configure_selected = get_configure_number_for_device((tusb_desc_device_t*) _usbh_ctrl_buf); - TU_ASSERT(configure_selected <= new_dev->configure_count); // TODO notify application when invalid configuration - - //------------- Get 9 bytes of configuration descriptor -------------// - request = (tusb_control_request_t ) { - .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_DEVICE, .type = TUSB_REQ_TYPE_STANDARD, .direction = TUSB_DIR_IN }, - .bRequest = TUSB_REQ_GET_DESCRIPTOR, - .wValue = (TUSB_DESC_CONFIGURATION << 8) | (configure_selected - 1), - .wIndex = 0, - .wLength = 9 - }; - TU_ASSERT( usbh_control_xfer(new_addr, &request, _usbh_ctrl_buf)); - - // TODO not enough buffer to hold configuration descriptor - TU_ASSERT( CFG_TUSB_HOST_ENUM_BUFFER_SIZE >= ((tusb_desc_configuration_t*)_usbh_ctrl_buf)->wTotalLength ); - - //------------- Get full configuration descriptor -------------// - request.wLength = ((tusb_desc_configuration_t*)_usbh_ctrl_buf)->wTotalLength; // full length - TU_ASSERT( usbh_control_xfer( new_addr, &request, _usbh_ctrl_buf ) ); - - // update configuration info - new_dev->interface_count = ((tusb_desc_configuration_t*) _usbh_ctrl_buf)->bNumInterfaces; - - //------------- Set Configure -------------// - request = (tusb_control_request_t ) { - .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_DEVICE, .type = TUSB_REQ_TYPE_STANDARD, .direction = TUSB_DIR_OUT }, - .bRequest = TUSB_REQ_SET_CONFIGURATION, - .wValue = configure_selected, - .wIndex = 0, - .wLength = 0 - }; - TU_ASSERT(usbh_control_xfer( new_addr, &request, NULL )); - - new_dev->state = TUSB_DEVICE_STATE_CONFIGURED; - - //------------- TODO Get String Descriptors -------------// - - //------------- parse configuration & install drivers -------------// - uint8_t const* p_desc = _usbh_ctrl_buf + sizeof(tusb_desc_configuration_t); - - // parse each interfaces - while( p_desc < _usbh_ctrl_buf + ((tusb_desc_configuration_t*)_usbh_ctrl_buf)->wTotalLength ) - { - // skip until we see interface descriptor - if ( TUSB_DESC_INTERFACE != tu_desc_type(p_desc) ) - { - p_desc = tu_desc_next(p_desc); // skip the descriptor, increase by the descriptor's length - }else - { - tusb_desc_interface_t* desc_itf = (tusb_desc_interface_t*) p_desc; - - // Check if class is supported - uint8_t drv_id; - for (drv_id = 0; drv_id < USBH_CLASS_DRIVER_COUNT; drv_id++) - { - if ( usbh_class_drivers[drv_id].class_code == desc_itf->bInterfaceClass ) break; - } - - if( drv_id >= USBH_CLASS_DRIVER_COUNT ) - { - // skip unsupported class - p_desc = tu_desc_next(p_desc); - } - else - { - // Interface number must not be used already TODO alternate interface - TU_ASSERT( new_dev->itf2drv[desc_itf->bInterfaceNumber] == 0xff ); - new_dev->itf2drv[desc_itf->bInterfaceNumber] = drv_id; - - if (desc_itf->bInterfaceClass == TUSB_CLASS_HUB && new_dev->hub_addr != 0) - { - // TODO Attach hub to Hub is not currently supported - // skip this interface - p_desc = tu_desc_next(p_desc); - } - else - { - uint16_t itf_len = 0; - - if ( usbh_class_drivers[drv_id].open(new_dev->rhport, new_addr, desc_itf, &itf_len) ) - { - mark_interface_endpoint(new_dev->ep2drv, p_desc, itf_len, drv_id); - } - - TU_ASSERT( itf_len >= sizeof(tusb_desc_interface_t) ); - p_desc += itf_len; - } - } - } - } - - if (tuh_mount_cb) tuh_mount_cb(new_addr); - - return true; -} - -/* USB Host Driver task - * This top level thread manages all host controller event and delegates events to class-specific drivers. - * This should be called periodically within the mainloop or rtos thread. - * - @code - int main(void) - { - application_init(); - tusb_init(); - - while(1) // the mainloop - { - application_code(); - - tuh_task(); // tinyusb host task - } - } - @endcode - */ -void tuh_task(void) -{ - // Skip if stack is not initialized - if ( !tusb_inited() ) return; - - // Loop until there is no more events in the queue - while (1) - { - hcd_event_t event; - if ( !osal_queue_receive(_usbh_q, &event) ) return; - - switch (event.event_id) - { - case HCD_EVENT_DEVICE_ATTACH: - case HCD_EVENT_DEVICE_REMOVE: - enum_task(&event); - break; - - default: break; - } - } -} - -//--------------------------------------------------------------------+ -// INTERNAL HELPER -//--------------------------------------------------------------------+ -static inline uint8_t get_new_address(void) -{ - for (uint8_t addr=1; addr <= CFG_TUSB_HOST_DEVICE_MAX; addr++) - { - if (_usbh_devices[addr].state == TUSB_DEVICE_STATE_UNPLUG) return addr; - } - return CFG_TUSB_HOST_DEVICE_MAX+1; -} - -static inline uint8_t get_configure_number_for_device(tusb_desc_device_t* dev_desc) -{ - uint8_t config_num = 1; - - // invoke callback to ask user which configuration to select - if (tuh_device_attached_cb) - { - config_num = tu_min8(1, tuh_device_attached_cb(dev_desc) ); - } - - return config_num; -} - -// Helper marking endpoint of interface belongs to class driver -// TODO merge with usbd -static void mark_interface_endpoint(uint8_t ep2drv[8][2], uint8_t const* p_desc, uint16_t desc_len, uint8_t driver_id) -{ - uint16_t len = 0; - - while( len < desc_len ) - { - if ( TUSB_DESC_ENDPOINT == tu_desc_type(p_desc) ) - { - uint8_t const ep_addr = ((tusb_desc_endpoint_t const*) p_desc)->bEndpointAddress; - - ep2drv[ tu_edpt_number(ep_addr) ][ tu_edpt_dir(ep_addr) ] = driver_id; - } - - len += tu_desc_len(p_desc); - p_desc = tu_desc_next(p_desc); - } -} - - -#endif +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#include "common/tusb_common.h" + +#if TUSB_OPT_HOST_ENABLED + +#ifndef CFG_TUH_TASK_QUEUE_SZ +#define CFG_TUH_TASK_QUEUE_SZ 16 +#endif + +//--------------------------------------------------------------------+ +// INCLUDE +//--------------------------------------------------------------------+ +#include "tusb.h" +#include "hub.h" +#include "usbh_hcd.h" + +//--------------------------------------------------------------------+ +// MACRO CONSTANT TYPEDEF +//--------------------------------------------------------------------+ +static host_class_driver_t const usbh_class_drivers[] = +{ + #if CFG_TUH_CDC + { + .class_code = TUSB_CLASS_CDC, + .init = cdch_init, + .open = cdch_open, + .isr = cdch_isr, + .close = cdch_close + }, + #endif + + #if CFG_TUH_MSC + { + .class_code = TUSB_CLASS_MSC, + .init = msch_init, + .open = msch_open, + .isr = msch_isr, + .close = msch_close + }, + #endif + + #if HOST_CLASS_HID + { + .class_code = TUSB_CLASS_HID, + .init = hidh_init, + .open = hidh_open_subtask, + .isr = hidh_isr, + .close = hidh_close + }, + #endif + + #if CFG_TUH_HUB + { + .class_code = TUSB_CLASS_HUB, + .init = hub_init, + .open = hub_open, + .isr = hub_isr, + .close = hub_close + }, + #endif + + #if CFG_TUH_VENDOR + { + .class_code = TUSB_CLASS_VENDOR_SPECIFIC, + .init = cush_init, + .open = cush_open_subtask, + .isr = cush_isr, + .close = cush_close + } + #endif +}; + +enum { USBH_CLASS_DRIVER_COUNT = TU_ARRAY_SIZE(usbh_class_drivers) }; + +//--------------------------------------------------------------------+ +// INTERNAL OBJECT & FUNCTION DECLARATION +//--------------------------------------------------------------------+ + +// including zero-address +CFG_TUSB_MEM_SECTION usbh_device_t _usbh_devices[CFG_TUSB_HOST_DEVICE_MAX+1]; + +// Event queue +// role device/host is used by OS NONE for mutex (disable usb isr) only +OSAL_QUEUE_DEF(OPT_MODE_HOST, _usbh_qdef, CFG_TUH_TASK_QUEUE_SZ, hcd_event_t); +static osal_queue_t _usbh_q; + +CFG_TUSB_MEM_SECTION TU_ATTR_ALIGNED(4) static uint8_t _usbh_ctrl_buf[CFG_TUSB_HOST_ENUM_BUFFER_SIZE]; + +//------------- Reporter Task Data -------------// + +//------------- Helper Function Prototypes -------------// +static inline uint8_t get_new_address(void); +static inline uint8_t get_configure_number_for_device(tusb_desc_device_t* dev_desc); +static void mark_interface_endpoint(uint8_t ep2drv[8][2], uint8_t const* p_desc, uint16_t desc_len, uint8_t driver_id); + +//--------------------------------------------------------------------+ +// PUBLIC API (Parameter Verification is required) +//--------------------------------------------------------------------+ +tusb_device_state_t tuh_device_get_state (uint8_t const dev_addr) +{ + TU_ASSERT( dev_addr <= CFG_TUSB_HOST_DEVICE_MAX, TUSB_DEVICE_STATE_UNPLUG); + return (tusb_device_state_t) _usbh_devices[dev_addr].state; +} + +//--------------------------------------------------------------------+ +// CLASS-USBD API (don't require to verify parameters) +//--------------------------------------------------------------------+ +bool usbh_init(void) +{ + tu_memclr(_usbh_devices, sizeof(usbh_device_t)*(CFG_TUSB_HOST_DEVICE_MAX+1)); + + //------------- Enumeration & Reporter Task init -------------// + _usbh_q = osal_queue_create( &_usbh_qdef ); + TU_ASSERT(_usbh_q != NULL); + + //------------- Semaphore, Mutex for Control Pipe -------------// + for(uint8_t i=0; icontrol.sem_hdl = osal_semaphore_create(&dev->control.sem_def); + TU_ASSERT(dev->control.sem_hdl != NULL); + + dev->control.mutex_hdl = osal_mutex_create(&dev->control.mutex_def); + TU_ASSERT(dev->control.mutex_hdl != NULL); + + memset(dev->itf2drv, 0xff, sizeof(dev->itf2drv)); // invalid mapping + memset(dev->ep2drv , 0xff, sizeof(dev->ep2drv )); // invalid mapping + } + + // Class drivers init + for (uint8_t drv_id = 0; drv_id < USBH_CLASS_DRIVER_COUNT; drv_id++) usbh_class_drivers[drv_id].init(); + + TU_ASSERT(hcd_init()); + hcd_int_enable(TUH_OPT_RHPORT); + + return true; +} + +//------------- USBH control transfer -------------// +bool usbh_control_xfer (uint8_t dev_addr, tusb_control_request_t* request, uint8_t* data) +{ + usbh_device_t* dev = &_usbh_devices[dev_addr]; + const uint8_t rhport = dev->rhport; + + TU_ASSERT(osal_mutex_lock(dev->control.mutex_hdl, OSAL_TIMEOUT_NORMAL)); + + dev->control.request = *request; + dev->control.pipe_status = 0; + + // Setup Stage + hcd_setup_send(rhport, dev_addr, (uint8_t*) &dev->control.request); + TU_VERIFY(osal_semaphore_wait(dev->control.sem_hdl, OSAL_TIMEOUT_NORMAL)); + + // Data stage : first data toggle is always 1 + if ( request->wLength ) + { + hcd_edpt_xfer(rhport, dev_addr, tu_edpt_addr(0, request->bmRequestType_bit.direction), data, request->wLength); + TU_VERIFY(osal_semaphore_wait(dev->control.sem_hdl, OSAL_TIMEOUT_NORMAL)); + } + + // Status : data toggle is always 1 + hcd_edpt_xfer(rhport, dev_addr, tu_edpt_addr(0, 1-request->bmRequestType_bit.direction), NULL, 0); + TU_VERIFY(osal_semaphore_wait(dev->control.sem_hdl, OSAL_TIMEOUT_NORMAL)); + + osal_mutex_unlock(dev->control.mutex_hdl); + + if ( XFER_RESULT_STALLED == dev->control.pipe_status ) return false; + if ( XFER_RESULT_FAILED == dev->control.pipe_status ) return false; + + return true; +} + +tusb_error_t usbh_pipe_control_open(uint8_t dev_addr, uint8_t max_packet_size) +{ + osal_semaphore_reset( _usbh_devices[dev_addr].control.sem_hdl ); + //osal_mutex_reset( usbh_devices[dev_addr].control.mutex_hdl ); + + tusb_desc_endpoint_t ep0_desc = + { + .bLength = sizeof(tusb_desc_endpoint_t), + .bDescriptorType = TUSB_DESC_ENDPOINT, + .bEndpointAddress = 0, + .bmAttributes = { .xfer = TUSB_XFER_CONTROL }, + .wMaxPacketSize = { .size = max_packet_size }, + .bInterval = 0 + }; + + hcd_edpt_open(_usbh_devices[dev_addr].rhport, dev_addr, &ep0_desc); + + return TUSB_ERROR_NONE; +} + +//--------------------------------------------------------------------+ +// USBH-HCD ISR/Callback API +//--------------------------------------------------------------------+ +// interrupt caused by a TD (with IOC=1) in pipe of class class_code +void hcd_event_xfer_complete(uint8_t dev_addr, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes) +{ + usbh_device_t* dev = &_usbh_devices[ dev_addr ]; + + if (0 == tu_edpt_number(ep_addr)) + { + dev->control.pipe_status = event; +// usbh_devices[ pipe_hdl.dev_addr ].control.xferred_bytes = xferred_bytes; not yet neccessary + osal_semaphore_post( dev->control.sem_hdl, true ); + } + else + { + uint8_t drv_id = dev->ep2drv[tu_edpt_number(ep_addr)][tu_edpt_dir(ep_addr)]; + TU_ASSERT(drv_id < USBH_CLASS_DRIVER_COUNT, ); + + if (usbh_class_drivers[drv_id].isr) + { + usbh_class_drivers[drv_id].isr(dev_addr, ep_addr, event, xferred_bytes); + } + else + { + TU_BREAKPOINT(); // something wrong, no one claims the isr's source + } + } +} + +void hcd_event_device_attach(uint8_t rhport) +{ + hcd_event_t event = + { + .rhport = rhport, + .event_id = HCD_EVENT_DEVICE_ATTACH + }; + + event.attach.hub_addr = 0; + event.attach.hub_port = 0; + + hcd_event_handler(&event, true); +} + +void hcd_event_handler(hcd_event_t const* event, bool in_isr) +{ + switch (event->event_id) + { + default: + osal_queue_send(_usbh_q, event, in_isr); + break; + } +} + +void hcd_event_device_remove(uint8_t hostid) +{ + hcd_event_t event = + { + .rhport = hostid, + .event_id = HCD_EVENT_DEVICE_REMOVE + }; + + event.attach.hub_addr = 0; + event.attach.hub_port = 0; + + hcd_event_handler(&event, true); +} + + +// a device unplugged on hostid, hub_addr, hub_port +// return true if found and unmounted device, false if cannot find +static void usbh_device_unplugged(uint8_t rhport, uint8_t hub_addr, uint8_t hub_port) +{ + //------------- find the all devices (star-network) under port that is unplugged -------------// + for (uint8_t dev_addr = 0; dev_addr <= CFG_TUSB_HOST_DEVICE_MAX; dev_addr ++) + { + usbh_device_t* dev = &_usbh_devices[dev_addr]; + + // TODO Hub multiple level + if (dev->rhport == rhport && + (hub_addr == 0 || dev->hub_addr == hub_addr) && // hub_addr == 0 & hub_port == 0 means roothub + (hub_port == 0 || dev->hub_port == hub_port) && + dev->state != TUSB_DEVICE_STATE_UNPLUG) + { + // Invoke callback before close driver + if (tuh_umount_cb) tuh_umount_cb(dev_addr); + + // Close class driver + for (uint8_t drv_id = 0; drv_id < USBH_CLASS_DRIVER_COUNT; drv_id++) usbh_class_drivers[drv_id].close(dev_addr); + + memset(dev->itf2drv, 0xff, sizeof(dev->itf2drv)); // invalid mapping + memset(dev->ep2drv , 0xff, sizeof(dev->ep2drv )); // invalid mapping + + hcd_device_close(rhport, dev_addr); + + dev->state = TUSB_DEVICE_STATE_UNPLUG; + } + } +} + +//--------------------------------------------------------------------+ +// ENUMERATION TASK +//--------------------------------------------------------------------+ + +bool enum_task(hcd_event_t* event) +{ + enum { +#if 1 + // FIXME ohci LPC1769 xpresso + debugging to have 1st control xfer to work, some kind of timing or ohci driver issue !!! + POWER_STABLE_DELAY = 100, + RESET_DELAY = 500 +#else + POWER_STABLE_DELAY = 500, + RESET_DELAY = 200, // USB specs say only 50ms but many devices require much longer +#endif + }; + + // for OSAL_NONE local variable won't retain value after blocking service sem_wait/queue_recv + static uint8_t configure_selected = 1; // TODO move + + usbh_device_t* dev0 = &_usbh_devices[0]; + tusb_control_request_t request; + + dev0->rhport = event->rhport; // TODO refractor integrate to device_pool + dev0->hub_addr = event->attach.hub_addr; + dev0->hub_port = event->attach.hub_port; + dev0->state = TUSB_DEVICE_STATE_UNPLUG; + + //------------- connected/disconnected directly with roothub -------------// + if ( dev0->hub_addr == 0) + { + if( hcd_port_connect_status(dev0->rhport) ) + { + // connection event + osal_task_delay(POWER_STABLE_DELAY); // wait until device is stable. Increase this if the first 8 bytes is failed to get + + // exit if device unplugged while delaying + if ( !hcd_port_connect_status(dev0->rhport) ) return true; + + hcd_port_reset( dev0->rhport ); // port must be reset to have correct speed operation + osal_task_delay(RESET_DELAY); + + dev0->speed = hcd_port_speed_get( dev0->rhport ); + } + else + { + // disconnection event + usbh_device_unplugged(dev0->rhport, 0, 0); + return true; // restart task + } + } + #if CFG_TUH_HUB + //------------- connected/disconnected via hub -------------// + else + { + //------------- Get Port Status -------------// + request = (tusb_control_request_t ) { + .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_OTHER, .type = TUSB_REQ_TYPE_CLASS, .direction = TUSB_DIR_IN }, + .bRequest = HUB_REQUEST_GET_STATUS, + .wValue = 0, + .wIndex = dev0->hub_port, + .wLength = 4 + }; + // TODO hub refractor + TU_VERIFY_HDLR( usbh_control_xfer( dev0->hub_addr, &request, _usbh_ctrl_buf ), hub_status_pipe_queue( dev0->hub_addr) ); + + // Acknowledge Port Connection Change + hub_port_clear_feature_subtask(dev0->hub_addr, dev0->hub_port, HUB_FEATURE_PORT_CONNECTION_CHANGE); + + hub_port_status_response_t * p_port_status; + p_port_status = ((hub_port_status_response_t *) _usbh_ctrl_buf); + + if ( ! p_port_status->status_change.connect_status ) return true; // only handle connection change + + if ( ! p_port_status->status_current.connect_status ) + { + // Disconnection event + usbh_device_unplugged(dev0->rhport, dev0->hub_addr, dev0->hub_port); + + (void) hub_status_pipe_queue( dev0->hub_addr ); // done with hub, waiting for next data on status pipe + return true; // restart task + } + else + { + // Connection Event + TU_VERIFY_HDLR(hub_port_reset_subtask(dev0->hub_addr, dev0->hub_port), + hub_status_pipe_queue( dev0->hub_addr) ); // TODO hub refractor + + dev0->speed = hub_port_get_speed(); + + // Acknowledge Port Reset Change + hub_port_clear_feature_subtask(dev0->hub_addr, dev0->hub_port, HUB_FEATURE_PORT_RESET_CHANGE); + } + } + #endif + + TU_ASSERT_ERR( usbh_pipe_control_open(0, 8) ); + + //------------- Get first 8 bytes of device descriptor to get Control Endpoint Size -------------// + request = (tusb_control_request_t ) { + .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_DEVICE, .type = TUSB_REQ_TYPE_STANDARD, .direction = TUSB_DIR_IN }, + .bRequest = TUSB_REQ_GET_DESCRIPTOR, + .wValue = TUSB_DESC_DEVICE << 8, + .wIndex = 0, + .wLength = 8 + }; + bool is_ok = usbh_control_xfer(0, &request, _usbh_ctrl_buf); + + //------------- Reset device again before Set Address -------------// + if (dev0->hub_addr == 0) + { + // connected directly to roothub + TU_ASSERT(is_ok); // TODO some slow device is observed to fail the very fist controller xfer, can try more times + hcd_port_reset( dev0->rhport ); // reset port after 8 byte descriptor + osal_task_delay(RESET_DELAY); + } + #if CFG_TUH_HUB + else + { + // connected via a hub + TU_VERIFY_HDLR(is_ok, hub_status_pipe_queue( dev0->hub_addr) ); // TODO hub refractor + + if ( hub_port_reset_subtask(dev0->hub_addr, dev0->hub_port) ) + { + // Acknowledge Port Reset Change if Reset Successful + hub_port_clear_feature_subtask(dev0->hub_addr, dev0->hub_port, HUB_FEATURE_PORT_RESET_CHANGE); + } + + (void) hub_status_pipe_queue( dev0->hub_addr ); // done with hub, waiting for next data on status pipe + } + #endif + + //------------- Set new address -------------// + uint8_t const new_addr = get_new_address(); + TU_ASSERT(new_addr <= CFG_TUSB_HOST_DEVICE_MAX); // TODO notify application we reach max devices + + request = (tusb_control_request_t ) { + .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_DEVICE, .type = TUSB_REQ_TYPE_STANDARD, .direction = TUSB_DIR_OUT }, + .bRequest = TUSB_REQ_SET_ADDRESS, + .wValue = new_addr, + .wIndex = 0, + .wLength = 0 + }; + TU_ASSERT(usbh_control_xfer(0, &request, NULL)); + + //------------- update port info & close control pipe of addr0 -------------// + usbh_device_t* new_dev = &_usbh_devices[new_addr]; + new_dev->rhport = dev0->rhport; + new_dev->hub_addr = dev0->hub_addr; + new_dev->hub_port = dev0->hub_port; + new_dev->speed = dev0->speed; + + hcd_device_close(dev0->rhport, 0); // close device 0 + dev0->state = TUSB_DEVICE_STATE_UNPLUG; + + // open control pipe for new address + TU_ASSERT_ERR ( usbh_pipe_control_open(new_addr, ((tusb_desc_device_t*) _usbh_ctrl_buf)->bMaxPacketSize0 ) ); + + //------------- Get full device descriptor -------------// + request = (tusb_control_request_t ) { + .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_DEVICE, .type = TUSB_REQ_TYPE_STANDARD, .direction = TUSB_DIR_IN }, + .bRequest = TUSB_REQ_GET_DESCRIPTOR, + .wValue = TUSB_DESC_DEVICE << 8, + .wIndex = 0, + .wLength = 18 + }; + TU_ASSERT(usbh_control_xfer(new_addr, &request, _usbh_ctrl_buf)); + + // update device info TODO alignment issue + new_dev->vendor_id = ((tusb_desc_device_t*) _usbh_ctrl_buf)->idVendor; + new_dev->product_id = ((tusb_desc_device_t*) _usbh_ctrl_buf)->idProduct; + new_dev->configure_count = ((tusb_desc_device_t*) _usbh_ctrl_buf)->bNumConfigurations; + + configure_selected = get_configure_number_for_device((tusb_desc_device_t*) _usbh_ctrl_buf); + TU_ASSERT(configure_selected <= new_dev->configure_count); // TODO notify application when invalid configuration + + //------------- Get 9 bytes of configuration descriptor -------------// + request = (tusb_control_request_t ) { + .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_DEVICE, .type = TUSB_REQ_TYPE_STANDARD, .direction = TUSB_DIR_IN }, + .bRequest = TUSB_REQ_GET_DESCRIPTOR, + .wValue = (TUSB_DESC_CONFIGURATION << 8) | (configure_selected - 1), + .wIndex = 0, + .wLength = 9 + }; + TU_ASSERT( usbh_control_xfer(new_addr, &request, _usbh_ctrl_buf)); + + // TODO not enough buffer to hold configuration descriptor + TU_ASSERT( CFG_TUSB_HOST_ENUM_BUFFER_SIZE >= ((tusb_desc_configuration_t*)_usbh_ctrl_buf)->wTotalLength ); + + //------------- Get full configuration descriptor -------------// + request.wLength = ((tusb_desc_configuration_t*)_usbh_ctrl_buf)->wTotalLength; // full length + TU_ASSERT( usbh_control_xfer( new_addr, &request, _usbh_ctrl_buf ) ); + + // update configuration info + new_dev->interface_count = ((tusb_desc_configuration_t*) _usbh_ctrl_buf)->bNumInterfaces; + + //------------- Set Configure -------------// + request = (tusb_control_request_t ) { + .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_DEVICE, .type = TUSB_REQ_TYPE_STANDARD, .direction = TUSB_DIR_OUT }, + .bRequest = TUSB_REQ_SET_CONFIGURATION, + .wValue = configure_selected, + .wIndex = 0, + .wLength = 0 + }; + TU_ASSERT(usbh_control_xfer( new_addr, &request, NULL )); + + new_dev->state = TUSB_DEVICE_STATE_CONFIGURED; + + //------------- TODO Get String Descriptors -------------// + + //------------- parse configuration & install drivers -------------// + uint8_t const* p_desc = _usbh_ctrl_buf + sizeof(tusb_desc_configuration_t); + + // parse each interfaces + while( p_desc < _usbh_ctrl_buf + ((tusb_desc_configuration_t*)_usbh_ctrl_buf)->wTotalLength ) + { + // skip until we see interface descriptor + if ( TUSB_DESC_INTERFACE != tu_desc_type(p_desc) ) + { + p_desc = tu_desc_next(p_desc); // skip the descriptor, increase by the descriptor's length + }else + { + tusb_desc_interface_t* desc_itf = (tusb_desc_interface_t*) p_desc; + + // Check if class is supported + uint8_t drv_id; + for (drv_id = 0; drv_id < USBH_CLASS_DRIVER_COUNT; drv_id++) + { + if ( usbh_class_drivers[drv_id].class_code == desc_itf->bInterfaceClass ) break; + } + + if( drv_id >= USBH_CLASS_DRIVER_COUNT ) + { + // skip unsupported class + p_desc = tu_desc_next(p_desc); + } + else + { + // Interface number must not be used already TODO alternate interface + TU_ASSERT( new_dev->itf2drv[desc_itf->bInterfaceNumber] == 0xff ); + new_dev->itf2drv[desc_itf->bInterfaceNumber] = drv_id; + + if (desc_itf->bInterfaceClass == TUSB_CLASS_HUB && new_dev->hub_addr != 0) + { + // TODO Attach hub to Hub is not currently supported + // skip this interface + p_desc = tu_desc_next(p_desc); + } + else + { + uint16_t itf_len = 0; + + if ( usbh_class_drivers[drv_id].open(new_dev->rhport, new_addr, desc_itf, &itf_len) ) + { + mark_interface_endpoint(new_dev->ep2drv, p_desc, itf_len, drv_id); + } + + TU_ASSERT( itf_len >= sizeof(tusb_desc_interface_t) ); + p_desc += itf_len; + } + } + } + } + + if (tuh_mount_cb) tuh_mount_cb(new_addr); + + return true; +} + +/* USB Host Driver task + * This top level thread manages all host controller event and delegates events to class-specific drivers. + * This should be called periodically within the mainloop or rtos thread. + * + @code + int main(void) + { + application_init(); + tusb_init(); + + while(1) // the mainloop + { + application_code(); + + tuh_task(); // tinyusb host task + } + } + @endcode + */ +void tuh_task(void) +{ + // Skip if stack is not initialized + if ( !tusb_inited() ) return; + + // Loop until there is no more events in the queue + while (1) + { + hcd_event_t event; + if ( !osal_queue_receive(_usbh_q, &event) ) return; + + switch (event.event_id) + { + case HCD_EVENT_DEVICE_ATTACH: + case HCD_EVENT_DEVICE_REMOVE: + enum_task(&event); + break; + + default: break; + } + } +} + +//--------------------------------------------------------------------+ +// INTERNAL HELPER +//--------------------------------------------------------------------+ +static inline uint8_t get_new_address(void) +{ + for (uint8_t addr=1; addr <= CFG_TUSB_HOST_DEVICE_MAX; addr++) + { + if (_usbh_devices[addr].state == TUSB_DEVICE_STATE_UNPLUG) return addr; + } + return CFG_TUSB_HOST_DEVICE_MAX+1; +} + +static inline uint8_t get_configure_number_for_device(tusb_desc_device_t* dev_desc) +{ + uint8_t config_num = 1; + + // invoke callback to ask user which configuration to select + if (tuh_device_attached_cb) + { + config_num = tu_min8(1, tuh_device_attached_cb(dev_desc) ); + } + + return config_num; +} + +// Helper marking endpoint of interface belongs to class driver +// TODO merge with usbd +static void mark_interface_endpoint(uint8_t ep2drv[8][2], uint8_t const* p_desc, uint16_t desc_len, uint8_t driver_id) +{ + uint16_t len = 0; + + while( len < desc_len ) + { + if ( TUSB_DESC_ENDPOINT == tu_desc_type(p_desc) ) + { + uint8_t const ep_addr = ((tusb_desc_endpoint_t const*) p_desc)->bEndpointAddress; + + ep2drv[ tu_edpt_number(ep_addr) ][ tu_edpt_dir(ep_addr) ] = driver_id; + } + + len += tu_desc_len(p_desc); + p_desc = tu_desc_next(p_desc); + } +} + + +#endif diff --git a/src/osal/osal.h b/src/osal/osal.h index 6b1d668a..8b7527a7 100644 --- a/src/osal/osal.h +++ b/src/osal/osal.h @@ -1,98 +1,98 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2019 Ha Thach (tinyusb.org) - * - * 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. - * - * This file is part of the TinyUSB stack. - */ - -#ifndef _TUSB_OSAL_H_ -#define _TUSB_OSAL_H_ - -#ifdef __cplusplus - extern "C" { -#endif - -/** \addtogroup group_osal - * @{ */ - -#include "common/tusb_common.h" - -enum -{ - OSAL_TIMEOUT_NOTIMEOUT = 0, // return immediately - OSAL_TIMEOUT_NORMAL = 10, // default timeout - OSAL_TIMEOUT_WAIT_FOREVER = 0xFFFFFFFFUL -}; - -#define OSAL_TIMEOUT_CONTROL_XFER OSAL_TIMEOUT_WAIT_FOREVER - -typedef void (*osal_task_func_t)( void * ); - -#if CFG_TUSB_OS == OPT_OS_NONE - #include "osal_none.h" -#elif CFG_TUSB_OS == OPT_OS_FREERTOS - #include "osal_freertos.h" -#elif CFG_TUSB_OS == OPT_OS_MYNEWT - #include "osal_mynewt.h" -#else - #error OS is not supported yet -#endif - -//--------------------------------------------------------------------+ -// OSAL Porting API -//--------------------------------------------------------------------+ -static inline void osal_task_delay(uint32_t msec); - -//------------- Semaphore -------------// -static inline osal_semaphore_t osal_semaphore_create(osal_semaphore_def_t* semdef); -static inline bool osal_semaphore_post(osal_semaphore_t sem_hdl, bool in_isr); -static inline bool osal_semaphore_wait(osal_semaphore_t sem_hdl, uint32_t msec); - -static inline void osal_semaphore_reset(osal_semaphore_t sem_hdl); // TODO removed - -//------------- Mutex -------------// -static inline osal_mutex_t osal_mutex_create(osal_mutex_def_t* mdef); -static inline bool osal_mutex_lock (osal_mutex_t sem_hdl, uint32_t msec); -static inline bool osal_mutex_unlock(osal_mutex_t mutex_hdl); - -//------------- Queue -------------// -static inline osal_queue_t osal_queue_create(osal_queue_def_t* qdef); -static inline bool osal_queue_receive(osal_queue_t const qhdl, void* data); -static inline bool osal_queue_send(osal_queue_t const qhdl, void const * data, bool in_isr); - -#if 0 // TODO remove subtask related macros later -// Sub Task -#define OSAL_SUBTASK_BEGIN -#define OSAL_SUBTASK_END return TUSB_ERROR_NONE; - -#define STASK_RETURN(_error) return _error; -#define STASK_INVOKE(_subtask, _status) (_status) = _subtask -#define STASK_ASSERT(_cond) TU_VERIFY(_cond, TUSB_ERROR_OSAL_TASK_FAILED) -#endif - -#ifdef __cplusplus - } -#endif - -/** @} */ - -#endif /* _TUSB_OSAL_H_ */ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#ifndef _TUSB_OSAL_H_ +#define _TUSB_OSAL_H_ + +#ifdef __cplusplus + extern "C" { +#endif + +/** \addtogroup group_osal + * @{ */ + +#include "common/tusb_common.h" + +enum +{ + OSAL_TIMEOUT_NOTIMEOUT = 0, // return immediately + OSAL_TIMEOUT_NORMAL = 10, // default timeout + OSAL_TIMEOUT_WAIT_FOREVER = 0xFFFFFFFFUL +}; + +#define OSAL_TIMEOUT_CONTROL_XFER OSAL_TIMEOUT_WAIT_FOREVER + +typedef void (*osal_task_func_t)( void * ); + +#if CFG_TUSB_OS == OPT_OS_NONE + #include "osal_none.h" +#elif CFG_TUSB_OS == OPT_OS_FREERTOS + #include "osal_freertos.h" +#elif CFG_TUSB_OS == OPT_OS_MYNEWT + #include "osal_mynewt.h" +#else + #error OS is not supported yet +#endif + +//--------------------------------------------------------------------+ +// OSAL Porting API +//--------------------------------------------------------------------+ +static inline void osal_task_delay(uint32_t msec); + +//------------- Semaphore -------------// +static inline osal_semaphore_t osal_semaphore_create(osal_semaphore_def_t* semdef); +static inline bool osal_semaphore_post(osal_semaphore_t sem_hdl, bool in_isr); +static inline bool osal_semaphore_wait(osal_semaphore_t sem_hdl, uint32_t msec); + +static inline void osal_semaphore_reset(osal_semaphore_t sem_hdl); // TODO removed + +//------------- Mutex -------------// +static inline osal_mutex_t osal_mutex_create(osal_mutex_def_t* mdef); +static inline bool osal_mutex_lock (osal_mutex_t sem_hdl, uint32_t msec); +static inline bool osal_mutex_unlock(osal_mutex_t mutex_hdl); + +//------------- Queue -------------// +static inline osal_queue_t osal_queue_create(osal_queue_def_t* qdef); +static inline bool osal_queue_receive(osal_queue_t const qhdl, void* data); +static inline bool osal_queue_send(osal_queue_t const qhdl, void const * data, bool in_isr); + +#if 0 // TODO remove subtask related macros later +// Sub Task +#define OSAL_SUBTASK_BEGIN +#define OSAL_SUBTASK_END return TUSB_ERROR_NONE; + +#define STASK_RETURN(_error) return _error; +#define STASK_INVOKE(_subtask, _status) (_status) = _subtask +#define STASK_ASSERT(_cond) TU_VERIFY(_cond, TUSB_ERROR_OSAL_TASK_FAILED) +#endif + +#ifdef __cplusplus + } +#endif + +/** @} */ + +#endif /* _TUSB_OSAL_H_ */ diff --git a/src/osal/osal_none.h b/src/osal/osal_none.h index 5868dfb3..b27e628a 100644 --- a/src/osal/osal_none.h +++ b/src/osal/osal_none.h @@ -1,210 +1,210 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2019 Ha Thach (tinyusb.org) - * - * 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. - * - * This file is part of the TinyUSB stack. - */ - -#ifndef _TUSB_OSAL_NONE_H_ -#define _TUSB_OSAL_NONE_H_ - -#ifdef __cplusplus - extern "C" { -#endif - -//--------------------------------------------------------------------+ -// TASK API -//--------------------------------------------------------------------+ -static inline void osal_task_delay(uint32_t msec) -{ - (void) msec; - // TODO only used by Host stack, will implement using SOF - -// uint32_t start = tusb_hal_millis(); -// while ( ( tusb_hal_millis() - start ) < msec ) {} -} - -//--------------------------------------------------------------------+ -// Binary Semaphore API -//--------------------------------------------------------------------+ -typedef struct -{ - volatile uint16_t count; -}osal_semaphore_def_t; - -typedef osal_semaphore_def_t* osal_semaphore_t; - -static inline osal_semaphore_t osal_semaphore_create(osal_semaphore_def_t* semdef) -{ - semdef->count = 0; - return semdef; -} - -static inline bool osal_semaphore_post(osal_semaphore_t sem_hdl, bool in_isr) -{ - (void) in_isr; - sem_hdl->count++; - return true; -} - -// TODO blocking for now -static inline bool osal_semaphore_wait (osal_semaphore_t sem_hdl, uint32_t msec) -{ - (void) msec; - - while (sem_hdl->count == 0) { } - sem_hdl->count--; - - return true; -} - -static inline void osal_semaphore_reset(osal_semaphore_t sem_hdl) -{ - sem_hdl->count = 0; -} - -//--------------------------------------------------------------------+ -// MUTEX API -// Within tinyusb, mutex is never used in ISR context -//--------------------------------------------------------------------+ -typedef osal_semaphore_def_t osal_mutex_def_t; -typedef osal_semaphore_t osal_mutex_t; - -static inline osal_mutex_t osal_mutex_create(osal_mutex_def_t* mdef) -{ - mdef->count = 1; - return mdef; -} - -static inline bool osal_mutex_lock (osal_mutex_t mutex_hdl, uint32_t msec) -{ - return osal_semaphore_wait(mutex_hdl, msec); -} - -static inline bool osal_mutex_unlock(osal_mutex_t mutex_hdl) -{ - return osal_semaphore_post(mutex_hdl, false); -} - -//--------------------------------------------------------------------+ -// QUEUE API -//--------------------------------------------------------------------+ -#include "common/tusb_fifo.h" - -// extern to avoid including dcd.h and hcd.h -#if TUSB_OPT_DEVICE_ENABLED -extern void dcd_int_disable(uint8_t rhport); -extern void dcd_int_enable(uint8_t rhport); -#endif - -#if TUSB_OPT_HOST_ENABLED -extern void hcd_int_disable(uint8_t rhport); -extern void hcd_int_enable(uint8_t rhport); -#endif - -typedef struct -{ - uint8_t role; // device or host - tu_fifo_t ff; -}osal_queue_def_t; - -typedef osal_queue_def_t* osal_queue_t; - -// role device/host is used by OS NONE for mutex (disable usb isr) only -#define OSAL_QUEUE_DEF(_role, _name, _depth, _type) \ - uint8_t _name##_buf[_depth*sizeof(_type)]; \ - osal_queue_def_t _name = { \ - .role = _role, \ - .ff = { \ - .buffer = _name##_buf, \ - .depth = _depth, \ - .item_size = sizeof(_type), \ - .overwritable = false, \ - }\ - } - -// lock queue by disable usb isr -static inline void _osal_q_lock(osal_queue_t qhdl) -{ - (void) qhdl; - -#if TUSB_OPT_DEVICE_ENABLED - if (qhdl->role == OPT_MODE_DEVICE) dcd_int_disable(TUD_OPT_RHPORT); -#endif - -#if TUSB_OPT_HOST_ENABLED - if (qhdl->role == OPT_MODE_HOST) hcd_int_disable(TUH_OPT_RHPORT); -#endif -} - -// unlock queue -static inline void _osal_q_unlock(osal_queue_t qhdl) -{ - (void) qhdl; - -#if TUSB_OPT_DEVICE_ENABLED - if (qhdl->role == OPT_MODE_DEVICE) dcd_int_enable(TUD_OPT_RHPORT); -#endif - -#if TUSB_OPT_HOST_ENABLED - if (qhdl->role == OPT_MODE_HOST) hcd_int_enable(TUH_OPT_RHPORT); -#endif -} - -static inline osal_queue_t osal_queue_create(osal_queue_def_t* qdef) -{ - tu_fifo_clear(&qdef->ff); - return (osal_queue_t) qdef; -} - -// non blocking -static inline bool osal_queue_receive(osal_queue_t const qhdl, void* data) -{ - _osal_q_lock(qhdl); - bool success = tu_fifo_read(&qhdl->ff, data); - _osal_q_unlock(qhdl); - - return success; -} - -static inline bool osal_queue_send(osal_queue_t const qhdl, void const * data, bool in_isr) -{ - if (!in_isr) { - _osal_q_lock(qhdl); - } - - bool success = tu_fifo_write(&qhdl->ff, data); - - if (!in_isr) { - _osal_q_unlock(qhdl); - } - - TU_ASSERT(success); - - return success; -} - -#ifdef __cplusplus - } -#endif - -#endif /* _TUSB_OSAL_NONE_H_ */ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#ifndef _TUSB_OSAL_NONE_H_ +#define _TUSB_OSAL_NONE_H_ + +#ifdef __cplusplus + extern "C" { +#endif + +//--------------------------------------------------------------------+ +// TASK API +//--------------------------------------------------------------------+ +static inline void osal_task_delay(uint32_t msec) +{ + (void) msec; + // TODO only used by Host stack, will implement using SOF + +// uint32_t start = tusb_hal_millis(); +// while ( ( tusb_hal_millis() - start ) < msec ) {} +} + +//--------------------------------------------------------------------+ +// Binary Semaphore API +//--------------------------------------------------------------------+ +typedef struct +{ + volatile uint16_t count; +}osal_semaphore_def_t; + +typedef osal_semaphore_def_t* osal_semaphore_t; + +static inline osal_semaphore_t osal_semaphore_create(osal_semaphore_def_t* semdef) +{ + semdef->count = 0; + return semdef; +} + +static inline bool osal_semaphore_post(osal_semaphore_t sem_hdl, bool in_isr) +{ + (void) in_isr; + sem_hdl->count++; + return true; +} + +// TODO blocking for now +static inline bool osal_semaphore_wait (osal_semaphore_t sem_hdl, uint32_t msec) +{ + (void) msec; + + while (sem_hdl->count == 0) { } + sem_hdl->count--; + + return true; +} + +static inline void osal_semaphore_reset(osal_semaphore_t sem_hdl) +{ + sem_hdl->count = 0; +} + +//--------------------------------------------------------------------+ +// MUTEX API +// Within tinyusb, mutex is never used in ISR context +//--------------------------------------------------------------------+ +typedef osal_semaphore_def_t osal_mutex_def_t; +typedef osal_semaphore_t osal_mutex_t; + +static inline osal_mutex_t osal_mutex_create(osal_mutex_def_t* mdef) +{ + mdef->count = 1; + return mdef; +} + +static inline bool osal_mutex_lock (osal_mutex_t mutex_hdl, uint32_t msec) +{ + return osal_semaphore_wait(mutex_hdl, msec); +} + +static inline bool osal_mutex_unlock(osal_mutex_t mutex_hdl) +{ + return osal_semaphore_post(mutex_hdl, false); +} + +//--------------------------------------------------------------------+ +// QUEUE API +//--------------------------------------------------------------------+ +#include "common/tusb_fifo.h" + +// extern to avoid including dcd.h and hcd.h +#if TUSB_OPT_DEVICE_ENABLED +extern void dcd_int_disable(uint8_t rhport); +extern void dcd_int_enable(uint8_t rhport); +#endif + +#if TUSB_OPT_HOST_ENABLED +extern void hcd_int_disable(uint8_t rhport); +extern void hcd_int_enable(uint8_t rhport); +#endif + +typedef struct +{ + uint8_t role; // device or host + tu_fifo_t ff; +}osal_queue_def_t; + +typedef osal_queue_def_t* osal_queue_t; + +// role device/host is used by OS NONE for mutex (disable usb isr) only +#define OSAL_QUEUE_DEF(_role, _name, _depth, _type) \ + uint8_t _name##_buf[_depth*sizeof(_type)]; \ + osal_queue_def_t _name = { \ + .role = _role, \ + .ff = { \ + .buffer = _name##_buf, \ + .depth = _depth, \ + .item_size = sizeof(_type), \ + .overwritable = false, \ + }\ + } + +// lock queue by disable usb isr +static inline void _osal_q_lock(osal_queue_t qhdl) +{ + (void) qhdl; + +#if TUSB_OPT_DEVICE_ENABLED + if (qhdl->role == OPT_MODE_DEVICE) dcd_int_disable(TUD_OPT_RHPORT); +#endif + +#if TUSB_OPT_HOST_ENABLED + if (qhdl->role == OPT_MODE_HOST) hcd_int_disable(TUH_OPT_RHPORT); +#endif +} + +// unlock queue +static inline void _osal_q_unlock(osal_queue_t qhdl) +{ + (void) qhdl; + +#if TUSB_OPT_DEVICE_ENABLED + if (qhdl->role == OPT_MODE_DEVICE) dcd_int_enable(TUD_OPT_RHPORT); +#endif + +#if TUSB_OPT_HOST_ENABLED + if (qhdl->role == OPT_MODE_HOST) hcd_int_enable(TUH_OPT_RHPORT); +#endif +} + +static inline osal_queue_t osal_queue_create(osal_queue_def_t* qdef) +{ + tu_fifo_clear(&qdef->ff); + return (osal_queue_t) qdef; +} + +// non blocking +static inline bool osal_queue_receive(osal_queue_t const qhdl, void* data) +{ + _osal_q_lock(qhdl); + bool success = tu_fifo_read(&qhdl->ff, data); + _osal_q_unlock(qhdl); + + return success; +} + +static inline bool osal_queue_send(osal_queue_t const qhdl, void const * data, bool in_isr) +{ + if (!in_isr) { + _osal_q_lock(qhdl); + } + + bool success = tu_fifo_write(&qhdl->ff, data); + + if (!in_isr) { + _osal_q_unlock(qhdl); + } + + TU_ASSERT(success); + + return success; +} + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_OSAL_NONE_H_ */ diff --git a/src/portable/nuvoton/nuc121/dcd_nuc121.c b/src/portable/nuvoton/nuc121/dcd_nuc121.c index 237a5fd9..57beb24b 100644 --- a/src/portable/nuvoton/nuc121/dcd_nuc121.c +++ b/src/portable/nuvoton/nuc121/dcd_nuc121.c @@ -1,436 +1,436 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2019 Peter Lawrence - * - * 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. - * - * This file is part of the TinyUSB stack. - */ - -/* - Theory of operation: - - The NUC121/NUC125/NUC126 USBD peripheral has eight "EP"s, but each is simplex, - so two collectively (peripheral nomenclature of "EP0" and "EP1") are needed to - implement USB EP0. PERIPH_EP0 and PERIPH_EP1 are used by this driver for - EP0_IN and EP0_OUT respectively. This leaves up to six for user usage. -*/ - -#include "tusb_option.h" - -#if TUSB_OPT_DEVICE_ENABLED && ( (CFG_TUSB_MCU == OPT_MCU_NUC121) || (CFG_TUSB_MCU == OPT_MCU_NUC126) ) - -#include "device/dcd.h" -#include "NuMicro.h" - -/* allocation of USBD RAM for Setup, EP0_IN, and and EP_OUT */ -#define PERIPH_SETUP_BUF_BASE 0 -#define PERIPH_SETUP_BUF_LEN 8 -#define PERIPH_EP0_BUF_BASE (PERIPH_SETUP_BUF_BASE + PERIPH_SETUP_BUF_LEN) -#define PERIPH_EP0_BUF_LEN CFG_TUD_ENDPOINT0_SIZE -#define PERIPH_EP1_BUF_BASE (PERIPH_EP0_BUF_BASE + PERIPH_EP0_BUF_LEN) -#define PERIPH_EP1_BUF_LEN CFG_TUD_ENDPOINT0_SIZE -#define PERIPH_EP2_BUF_BASE (PERIPH_EP1_BUF_BASE + PERIPH_EP1_BUF_LEN) - -/* rather important info unfortunately not provided by device include files: how much there is */ -#define USBD_BUF_SIZE ((CFG_TUSB_MCU == OPT_MCU_NUC121) ? 768 : 512) - -enum ep_enum -{ - PERIPH_EP0 = 0, - PERIPH_EP1 = 1, - PERIPH_EP2 = 2, - PERIPH_EP3 = 3, - PERIPH_EP4 = 4, - PERIPH_EP5 = 5, - PERIPH_EP6 = 6, - PERIPH_EP7 = 7, - PERIPH_MAX_EP, -}; - -/* set by dcd_set_address() */ -static volatile uint8_t assigned_address; - -/* reset by dcd_init(), this is used by dcd_edpt_open() to assign USBD peripheral buffer addresses */ -static uint32_t bufseg_addr; - -/* used by dcd_edpt_xfer() and the ISR to reset the data sync (DATA0/DATA1) in an EP0_IN transfer */ -static bool active_ep0_xfer; - -/* RAM table needed to track ongoing transfers performed by dcd_edpt_xfer(), dcd_in_xfer(), and the ISR */ -static struct xfer_ctl_t -{ - uint8_t *data_ptr; /* collectively, data_ptr and remaining_bytes track progress of endpoint transfers */ - uint16_t remaining_bytes; - uint16_t max_packet_size; /* needed since device driver only finds out this at runtime */ - uint16_t total_bytes; /* quantity needed to pass as argument to dcd_event_xfer_complete() (for IN endpoints) */ -} xfer_table[PERIPH_MAX_EP]; - -/* - local helper functions -*/ - -static void usb_attach(void) -{ - USBD->SE0 &= ~USBD_SE0_SE0_Msk; -} - -static void usb_detach(void) -{ - USBD->SE0 |= USBD_SE0_SE0_Msk; -} - -static void usb_control_send_zlp(void) -{ - USBD->EP[PERIPH_EP0].CFG |= USBD_CFG_DSQSYNC_Msk; - USBD->EP[PERIPH_EP0].MXPLD = 0; -} - -/* reconstruct ep_addr from particular USB Configuration Register */ -static uint8_t decode_ep_addr(USBD_EP_T *ep) -{ - uint8_t ep_addr = ep->CFG & USBD_CFG_EPNUM_Msk; - if ( USBD_CFG_EPMODE_IN == (ep->CFG & USBD_CFG_STATE_Msk) ) - ep_addr |= TUSB_DIR_IN_MASK; - return ep_addr; -} - -/* map 8-bit ep_addr into peripheral endpoint index (PERIPH_EP0...) */ -static USBD_EP_T *ep_entry(uint8_t ep_addr, bool add) -{ - USBD_EP_T *ep; - enum ep_enum ep_index; - - for (ep_index = PERIPH_EP0, ep = USBD->EP; ep_index < PERIPH_MAX_EP; ep_index++, ep++) - { - if (add) - { - /* take first peripheral endpoint that is unused */ - if (0 == (ep->CFG & USBD_CFG_STATE_Msk)) return ep; - } - else - { - /* find a peripheral endpoint that matches ep_addr */ - uint8_t candidate_ep_addr = decode_ep_addr(ep); - if (candidate_ep_addr == ep_addr) return ep; - } - } - - return NULL; -} - -/* perform an IN endpoint transfer; this is called by dcd_edpt_xfer() and the ISR */ -static void dcd_in_xfer(struct xfer_ctl_t *xfer, USBD_EP_T *ep) -{ - uint16_t bytes_now = tu_min16(xfer->remaining_bytes, xfer->max_packet_size); - - memcpy((uint8_t *)(USBD_BUF_BASE + ep->BUFSEG), xfer->data_ptr, bytes_now); - ep->MXPLD = bytes_now; -} - -/* centralized location for USBD interrupt enable bit mask */ -static const uint32_t enabled_irqs = USBD_INTSTS_VBDETIF_Msk | USBD_INTSTS_BUSIF_Msk | USBD_INTSTS_SETUP_Msk | USBD_INTSTS_USBIF_Msk | USBD_INTSTS_SOFIF_Msk; - -/* - NUC121/NUC125/NUC126 TinyUSB API driver implementation -*/ - -void dcd_init(uint8_t rhport) -{ - (void) rhport; - -#ifdef SUPPORT_LPM - USBD->ATTR = 0x7D0 | USBD_LPMACK; -#else - USBD->ATTR = 0x7D0; -#endif - - usb_detach(); - - USBD->STBUFSEG = PERIPH_SETUP_BUF_BASE; - - for (enum ep_enum ep_index = PERIPH_EP0; ep_index < PERIPH_MAX_EP; ep_index++) - { - USBD->EP[ep_index].CFGP &= ~USBD_CFG_STATE_Msk; - } - - /* allocate the default EP0 endpoints */ - - USBD->EP[PERIPH_EP0].CFG = USBD_CFG_CSTALL_Msk | USBD_CFG_EPMODE_IN; - USBD->EP[PERIPH_EP0].BUFSEG = PERIPH_EP0_BUF_BASE; - xfer_table[PERIPH_EP0].max_packet_size = PERIPH_EP0_BUF_LEN; - - USBD->EP[PERIPH_EP1].CFG = USBD_CFG_CSTALL_Msk | USBD_CFG_EPMODE_OUT; - USBD->EP[PERIPH_EP1].BUFSEG = PERIPH_EP1_BUF_BASE; - xfer_table[PERIPH_EP1].max_packet_size = PERIPH_EP1_BUF_LEN; - - /* USB RAM beyond what we've allocated above is available to the user */ - bufseg_addr = PERIPH_EP2_BUF_BASE; - - usb_attach(); - - USBD->INTSTS = enabled_irqs; - USBD->INTEN = enabled_irqs; -} - -void dcd_int_enable(uint8_t rhport) -{ - (void) rhport; - NVIC_EnableIRQ(USBD_IRQn); -} - -void dcd_int_disable(uint8_t rhport) -{ - (void) rhport; - NVIC_DisableIRQ(USBD_IRQn); -} - -void dcd_set_address(uint8_t rhport, uint8_t dev_addr) -{ - (void) rhport; - usb_control_send_zlp(); /* SET_ADDRESS is the one exception where TinyUSB doesn't use dcd_edpt_xfer() to generate a ZLP */ - assigned_address = dev_addr; -} - -void dcd_set_config(uint8_t rhport, uint8_t config_num) -{ - (void) rhport; - (void) config_num; -} - -void dcd_remote_wakeup(uint8_t rhport) -{ - (void) rhport; - USBD->ATTR = USBD_ATTR_RWAKEUP_Msk; -} - -bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc) -{ - (void) rhport; - - USBD_EP_T *ep = ep_entry(p_endpoint_desc->bEndpointAddress, true); - TU_ASSERT(ep); - - /* mine the data for the information we need */ - int const dir = tu_edpt_dir(p_endpoint_desc->bEndpointAddress); - int const size = p_endpoint_desc->wMaxPacketSize.size; - tusb_xfer_type_t const type = p_endpoint_desc->bmAttributes.xfer; - struct xfer_ctl_t *xfer = &xfer_table[ep - USBD->EP]; - - /* allocate buffer from USB RAM */ - ep->BUFSEG = bufseg_addr; - bufseg_addr += size; - TU_ASSERT(bufseg_addr <= USBD_BUF_SIZE); - - /* construct USB Configuration Register value and then write it */ - uint32_t cfg = tu_edpt_number(p_endpoint_desc->bEndpointAddress); - cfg |= (TUSB_DIR_IN == dir) ? USBD_CFG_EPMODE_IN : USBD_CFG_EPMODE_OUT; - if (TUSB_XFER_ISOCHRONOUS == type) - cfg |= USBD_CFG_TYPE_ISO; - ep->CFG = cfg; - - /* make a note of the endpoint size */ - xfer->max_packet_size = size; - - return true; -} - -bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t *buffer, uint16_t total_bytes) -{ - (void) rhport; - - /* mine the data for the information we need */ - tusb_dir_t dir = tu_edpt_dir(ep_addr); - USBD_EP_T *ep = ep_entry(ep_addr, false); - struct xfer_ctl_t *xfer = &xfer_table[ep - USBD->EP]; - - /* store away the information we'll needing now and later */ - xfer->data_ptr = buffer; - xfer->remaining_bytes = total_bytes; - xfer->total_bytes = total_bytes; - - /* for the first of one or more EP0_IN packets in a message, the first must be DATA1 */ - if ( (0x80 == ep_addr) && !active_ep0_xfer ) ep->CFG |= USBD_CFG_DSQSYNC_Msk; - - if (TUSB_DIR_IN == dir) - dcd_in_xfer(xfer, ep); - else - ep->MXPLD = xfer->max_packet_size; - - return true; -} - -void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr) -{ - (void) rhport; - USBD_EP_T *ep = ep_entry(ep_addr, false); - ep->CFGP |= USBD_CFGP_SSTALL_Msk; -} - -void dcd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr) -{ - (void) rhport; - USBD_EP_T *ep = ep_entry(ep_addr, false); - ep->CFG |= USBD_CFG_CSTALL_Msk; -} - -void USBD_IRQHandler(void) -{ - uint32_t status = USBD->INTSTS; -#ifdef SUPPORT_LPM - uint32_t state = USBD->ATTR & 0x300f; -#else - uint32_t state = USBD->ATTR & 0xf; -#endif - - if(status & USBD_INTSTS_VBDETIF_Msk) - { - if(USBD->VBUSDET & USBD_VBUSDET_VBUSDET_Msk) - { - /* USB connect */ - USBD->ATTR |= USBD_ATTR_USBEN_Msk | USBD_ATTR_PHYEN_Msk; - } - else - { - /* USB disconnect */ - USBD->ATTR &= ~USBD_ATTR_USBEN_Msk; - } - } - - if(status & USBD_INTSTS_BUSIF_Msk) - { - if(state & USBD_ATTR_USBRST_Msk) - { - /* USB bus reset */ - USBD->ATTR |= USBD_ATTR_USBEN_Msk | USBD_ATTR_PHYEN_Msk; - - /* Reset all endpoints to DATA0 */ - for(enum ep_enum ep_index = PERIPH_EP0; ep_index < PERIPH_MAX_EP; ep_index++) - USBD->EP[ep_index].CFG &= ~USBD_CFG_DSQSYNC_Msk; - - /* Reset USB device address */ - USBD->FADDR = 0; - - /* reset EP0_IN flag */ - active_ep0_xfer = false; - - dcd_event_bus_signal(0, DCD_EVENT_BUS_RESET, true); - } - - if(state & USBD_ATTR_SUSPEND_Msk) - { - /* Enable USB but disable PHY */ - USBD->ATTR &= ~USBD_ATTR_PHYEN_Msk; - dcd_event_bus_signal(0, DCD_EVENT_SUSPEND, true); - } - - if(state & USBD_ATTR_RESUME_Msk) - { - /* Enable USB and enable PHY */ - USBD->ATTR |= USBD_ATTR_USBEN_Msk | USBD_ATTR_PHYEN_Msk; - dcd_event_bus_signal(0, DCD_EVENT_RESUME, true); - } - } - - if(status & USBD_INTSTS_SETUP_Msk) - { - /* clear the data ready flag of control endpoints */ - USBD->EP[PERIPH_EP0].CFGP |= USBD_CFGP_CLRRDY_Msk; - USBD->EP[PERIPH_EP1].CFGP |= USBD_CFGP_CLRRDY_Msk; - - /* get SETUP packet from USB buffer */ - dcd_event_setup_received(0, (uint8_t *)USBD_BUF_BASE, true); - } - - if(status & USBD_INTSTS_USBIF_Msk) - { - if (status & USBD_INTSTS_EPEVT0_Msk) /* PERIPH_EP0 (EP0_IN) event: this is treated separately from the rest */ - { - /* given ACK from host has happened, we can now set the address (if not already done) */ - if((USBD->FADDR != assigned_address) && (USBD->FADDR == 0)) USBD->FADDR = assigned_address; - - uint16_t const available_bytes = USBD->EP[PERIPH_EP0].MXPLD; - - active_ep0_xfer = (available_bytes == xfer_table[PERIPH_EP0].max_packet_size); - - dcd_event_xfer_complete(0, 0x80, available_bytes, XFER_RESULT_SUCCESS, true); - } - - /* service PERIPH_EP1 through PERIPH_EP7 */ - enum ep_enum ep_index; - uint32_t mask; - struct xfer_ctl_t *xfer; - USBD_EP_T *ep; - for (ep_index = PERIPH_EP1, mask = USBD_INTSTS_EPEVT1_Msk, xfer = &xfer_table[PERIPH_EP1], ep = &USBD->EP[PERIPH_EP1]; ep_index <= PERIPH_EP7; ep_index++, mask <<= 1, xfer++, ep++) - { - if(status & mask) - { - USBD->INTSTS = mask; - - uint16_t const available_bytes = ep->MXPLD; - uint8_t const ep_addr = decode_ep_addr(ep); - bool const out_ep = !(ep_addr & TUSB_DIR_IN_MASK); - - if (out_ep) - { - /* copy the data from the PC to the previously provided buffer */ - memcpy(xfer->data_ptr, (uint8_t *)(USBD_BUF_BASE + ep->BUFSEG), available_bytes); - xfer->remaining_bytes -= available_bytes; - xfer->data_ptr += available_bytes; - - /* when the transfer is finished, alert TinyUSB; otherwise, accept more data */ - if ( (0 == xfer->remaining_bytes) || (available_bytes < xfer->max_packet_size) ) - dcd_event_xfer_complete(0, ep_addr, xfer->total_bytes, XFER_RESULT_SUCCESS, true); - else if (xfer->remaining_bytes) - ep->MXPLD = xfer->max_packet_size; - } - else - { - /* update the bookkeeping to reflect the data that has now been sent to the PC */ - xfer->remaining_bytes -= available_bytes; - xfer->data_ptr += available_bytes; - - /* if more data to send, send it; otherwise, alert TinyUSB that we've finished */ - if (xfer->remaining_bytes) - dcd_in_xfer(xfer, ep); - else - dcd_event_xfer_complete(0, ep_addr, xfer->total_bytes, XFER_RESULT_SUCCESS, true); - } - } - } - } - - if(status & USBD_INTSTS_SOFIF_Msk) - { - /* Start-Of-Frame event */ - dcd_event_bus_signal(0, DCD_EVENT_SOF, true); - } - - /* acknowledge all interrupts */ - USBD->INTSTS = status & enabled_irqs; -} - -void dcd_isr(uint8_t rhport) -{ - (void) rhport; - USBD_IRQHandler(); -} - -#endif +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Peter Lawrence + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +/* + Theory of operation: + + The NUC121/NUC125/NUC126 USBD peripheral has eight "EP"s, but each is simplex, + so two collectively (peripheral nomenclature of "EP0" and "EP1") are needed to + implement USB EP0. PERIPH_EP0 and PERIPH_EP1 are used by this driver for + EP0_IN and EP0_OUT respectively. This leaves up to six for user usage. +*/ + +#include "tusb_option.h" + +#if TUSB_OPT_DEVICE_ENABLED && ( (CFG_TUSB_MCU == OPT_MCU_NUC121) || (CFG_TUSB_MCU == OPT_MCU_NUC126) ) + +#include "device/dcd.h" +#include "NuMicro.h" + +/* allocation of USBD RAM for Setup, EP0_IN, and and EP_OUT */ +#define PERIPH_SETUP_BUF_BASE 0 +#define PERIPH_SETUP_BUF_LEN 8 +#define PERIPH_EP0_BUF_BASE (PERIPH_SETUP_BUF_BASE + PERIPH_SETUP_BUF_LEN) +#define PERIPH_EP0_BUF_LEN CFG_TUD_ENDPOINT0_SIZE +#define PERIPH_EP1_BUF_BASE (PERIPH_EP0_BUF_BASE + PERIPH_EP0_BUF_LEN) +#define PERIPH_EP1_BUF_LEN CFG_TUD_ENDPOINT0_SIZE +#define PERIPH_EP2_BUF_BASE (PERIPH_EP1_BUF_BASE + PERIPH_EP1_BUF_LEN) + +/* rather important info unfortunately not provided by device include files: how much there is */ +#define USBD_BUF_SIZE ((CFG_TUSB_MCU == OPT_MCU_NUC121) ? 768 : 512) + +enum ep_enum +{ + PERIPH_EP0 = 0, + PERIPH_EP1 = 1, + PERIPH_EP2 = 2, + PERIPH_EP3 = 3, + PERIPH_EP4 = 4, + PERIPH_EP5 = 5, + PERIPH_EP6 = 6, + PERIPH_EP7 = 7, + PERIPH_MAX_EP, +}; + +/* set by dcd_set_address() */ +static volatile uint8_t assigned_address; + +/* reset by dcd_init(), this is used by dcd_edpt_open() to assign USBD peripheral buffer addresses */ +static uint32_t bufseg_addr; + +/* used by dcd_edpt_xfer() and the ISR to reset the data sync (DATA0/DATA1) in an EP0_IN transfer */ +static bool active_ep0_xfer; + +/* RAM table needed to track ongoing transfers performed by dcd_edpt_xfer(), dcd_in_xfer(), and the ISR */ +static struct xfer_ctl_t +{ + uint8_t *data_ptr; /* collectively, data_ptr and remaining_bytes track progress of endpoint transfers */ + uint16_t remaining_bytes; + uint16_t max_packet_size; /* needed since device driver only finds out this at runtime */ + uint16_t total_bytes; /* quantity needed to pass as argument to dcd_event_xfer_complete() (for IN endpoints) */ +} xfer_table[PERIPH_MAX_EP]; + +/* + local helper functions +*/ + +static void usb_attach(void) +{ + USBD->SE0 &= ~USBD_SE0_SE0_Msk; +} + +static void usb_detach(void) +{ + USBD->SE0 |= USBD_SE0_SE0_Msk; +} + +static void usb_control_send_zlp(void) +{ + USBD->EP[PERIPH_EP0].CFG |= USBD_CFG_DSQSYNC_Msk; + USBD->EP[PERIPH_EP0].MXPLD = 0; +} + +/* reconstruct ep_addr from particular USB Configuration Register */ +static uint8_t decode_ep_addr(USBD_EP_T *ep) +{ + uint8_t ep_addr = ep->CFG & USBD_CFG_EPNUM_Msk; + if ( USBD_CFG_EPMODE_IN == (ep->CFG & USBD_CFG_STATE_Msk) ) + ep_addr |= TUSB_DIR_IN_MASK; + return ep_addr; +} + +/* map 8-bit ep_addr into peripheral endpoint index (PERIPH_EP0...) */ +static USBD_EP_T *ep_entry(uint8_t ep_addr, bool add) +{ + USBD_EP_T *ep; + enum ep_enum ep_index; + + for (ep_index = PERIPH_EP0, ep = USBD->EP; ep_index < PERIPH_MAX_EP; ep_index++, ep++) + { + if (add) + { + /* take first peripheral endpoint that is unused */ + if (0 == (ep->CFG & USBD_CFG_STATE_Msk)) return ep; + } + else + { + /* find a peripheral endpoint that matches ep_addr */ + uint8_t candidate_ep_addr = decode_ep_addr(ep); + if (candidate_ep_addr == ep_addr) return ep; + } + } + + return NULL; +} + +/* perform an IN endpoint transfer; this is called by dcd_edpt_xfer() and the ISR */ +static void dcd_in_xfer(struct xfer_ctl_t *xfer, USBD_EP_T *ep) +{ + uint16_t bytes_now = tu_min16(xfer->remaining_bytes, xfer->max_packet_size); + + memcpy((uint8_t *)(USBD_BUF_BASE + ep->BUFSEG), xfer->data_ptr, bytes_now); + ep->MXPLD = bytes_now; +} + +/* centralized location for USBD interrupt enable bit mask */ +static const uint32_t enabled_irqs = USBD_INTSTS_VBDETIF_Msk | USBD_INTSTS_BUSIF_Msk | USBD_INTSTS_SETUP_Msk | USBD_INTSTS_USBIF_Msk | USBD_INTSTS_SOFIF_Msk; + +/* + NUC121/NUC125/NUC126 TinyUSB API driver implementation +*/ + +void dcd_init(uint8_t rhport) +{ + (void) rhport; + +#ifdef SUPPORT_LPM + USBD->ATTR = 0x7D0 | USBD_LPMACK; +#else + USBD->ATTR = 0x7D0; +#endif + + usb_detach(); + + USBD->STBUFSEG = PERIPH_SETUP_BUF_BASE; + + for (enum ep_enum ep_index = PERIPH_EP0; ep_index < PERIPH_MAX_EP; ep_index++) + { + USBD->EP[ep_index].CFGP &= ~USBD_CFG_STATE_Msk; + } + + /* allocate the default EP0 endpoints */ + + USBD->EP[PERIPH_EP0].CFG = USBD_CFG_CSTALL_Msk | USBD_CFG_EPMODE_IN; + USBD->EP[PERIPH_EP0].BUFSEG = PERIPH_EP0_BUF_BASE; + xfer_table[PERIPH_EP0].max_packet_size = PERIPH_EP0_BUF_LEN; + + USBD->EP[PERIPH_EP1].CFG = USBD_CFG_CSTALL_Msk | USBD_CFG_EPMODE_OUT; + USBD->EP[PERIPH_EP1].BUFSEG = PERIPH_EP1_BUF_BASE; + xfer_table[PERIPH_EP1].max_packet_size = PERIPH_EP1_BUF_LEN; + + /* USB RAM beyond what we've allocated above is available to the user */ + bufseg_addr = PERIPH_EP2_BUF_BASE; + + usb_attach(); + + USBD->INTSTS = enabled_irqs; + USBD->INTEN = enabled_irqs; +} + +void dcd_int_enable(uint8_t rhport) +{ + (void) rhport; + NVIC_EnableIRQ(USBD_IRQn); +} + +void dcd_int_disable(uint8_t rhport) +{ + (void) rhport; + NVIC_DisableIRQ(USBD_IRQn); +} + +void dcd_set_address(uint8_t rhport, uint8_t dev_addr) +{ + (void) rhport; + usb_control_send_zlp(); /* SET_ADDRESS is the one exception where TinyUSB doesn't use dcd_edpt_xfer() to generate a ZLP */ + assigned_address = dev_addr; +} + +void dcd_set_config(uint8_t rhport, uint8_t config_num) +{ + (void) rhport; + (void) config_num; +} + +void dcd_remote_wakeup(uint8_t rhport) +{ + (void) rhport; + USBD->ATTR = USBD_ATTR_RWAKEUP_Msk; +} + +bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc) +{ + (void) rhport; + + USBD_EP_T *ep = ep_entry(p_endpoint_desc->bEndpointAddress, true); + TU_ASSERT(ep); + + /* mine the data for the information we need */ + int const dir = tu_edpt_dir(p_endpoint_desc->bEndpointAddress); + int const size = p_endpoint_desc->wMaxPacketSize.size; + tusb_xfer_type_t const type = p_endpoint_desc->bmAttributes.xfer; + struct xfer_ctl_t *xfer = &xfer_table[ep - USBD->EP]; + + /* allocate buffer from USB RAM */ + ep->BUFSEG = bufseg_addr; + bufseg_addr += size; + TU_ASSERT(bufseg_addr <= USBD_BUF_SIZE); + + /* construct USB Configuration Register value and then write it */ + uint32_t cfg = tu_edpt_number(p_endpoint_desc->bEndpointAddress); + cfg |= (TUSB_DIR_IN == dir) ? USBD_CFG_EPMODE_IN : USBD_CFG_EPMODE_OUT; + if (TUSB_XFER_ISOCHRONOUS == type) + cfg |= USBD_CFG_TYPE_ISO; + ep->CFG = cfg; + + /* make a note of the endpoint size */ + xfer->max_packet_size = size; + + return true; +} + +bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t *buffer, uint16_t total_bytes) +{ + (void) rhport; + + /* mine the data for the information we need */ + tusb_dir_t dir = tu_edpt_dir(ep_addr); + USBD_EP_T *ep = ep_entry(ep_addr, false); + struct xfer_ctl_t *xfer = &xfer_table[ep - USBD->EP]; + + /* store away the information we'll needing now and later */ + xfer->data_ptr = buffer; + xfer->remaining_bytes = total_bytes; + xfer->total_bytes = total_bytes; + + /* for the first of one or more EP0_IN packets in a message, the first must be DATA1 */ + if ( (0x80 == ep_addr) && !active_ep0_xfer ) ep->CFG |= USBD_CFG_DSQSYNC_Msk; + + if (TUSB_DIR_IN == dir) + dcd_in_xfer(xfer, ep); + else + ep->MXPLD = xfer->max_packet_size; + + return true; +} + +void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + USBD_EP_T *ep = ep_entry(ep_addr, false); + ep->CFGP |= USBD_CFGP_SSTALL_Msk; +} + +void dcd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + USBD_EP_T *ep = ep_entry(ep_addr, false); + ep->CFG |= USBD_CFG_CSTALL_Msk; +} + +void USBD_IRQHandler(void) +{ + uint32_t status = USBD->INTSTS; +#ifdef SUPPORT_LPM + uint32_t state = USBD->ATTR & 0x300f; +#else + uint32_t state = USBD->ATTR & 0xf; +#endif + + if(status & USBD_INTSTS_VBDETIF_Msk) + { + if(USBD->VBUSDET & USBD_VBUSDET_VBUSDET_Msk) + { + /* USB connect */ + USBD->ATTR |= USBD_ATTR_USBEN_Msk | USBD_ATTR_PHYEN_Msk; + } + else + { + /* USB disconnect */ + USBD->ATTR &= ~USBD_ATTR_USBEN_Msk; + } + } + + if(status & USBD_INTSTS_BUSIF_Msk) + { + if(state & USBD_ATTR_USBRST_Msk) + { + /* USB bus reset */ + USBD->ATTR |= USBD_ATTR_USBEN_Msk | USBD_ATTR_PHYEN_Msk; + + /* Reset all endpoints to DATA0 */ + for(enum ep_enum ep_index = PERIPH_EP0; ep_index < PERIPH_MAX_EP; ep_index++) + USBD->EP[ep_index].CFG &= ~USBD_CFG_DSQSYNC_Msk; + + /* Reset USB device address */ + USBD->FADDR = 0; + + /* reset EP0_IN flag */ + active_ep0_xfer = false; + + dcd_event_bus_signal(0, DCD_EVENT_BUS_RESET, true); + } + + if(state & USBD_ATTR_SUSPEND_Msk) + { + /* Enable USB but disable PHY */ + USBD->ATTR &= ~USBD_ATTR_PHYEN_Msk; + dcd_event_bus_signal(0, DCD_EVENT_SUSPEND, true); + } + + if(state & USBD_ATTR_RESUME_Msk) + { + /* Enable USB and enable PHY */ + USBD->ATTR |= USBD_ATTR_USBEN_Msk | USBD_ATTR_PHYEN_Msk; + dcd_event_bus_signal(0, DCD_EVENT_RESUME, true); + } + } + + if(status & USBD_INTSTS_SETUP_Msk) + { + /* clear the data ready flag of control endpoints */ + USBD->EP[PERIPH_EP0].CFGP |= USBD_CFGP_CLRRDY_Msk; + USBD->EP[PERIPH_EP1].CFGP |= USBD_CFGP_CLRRDY_Msk; + + /* get SETUP packet from USB buffer */ + dcd_event_setup_received(0, (uint8_t *)USBD_BUF_BASE, true); + } + + if(status & USBD_INTSTS_USBIF_Msk) + { + if (status & USBD_INTSTS_EPEVT0_Msk) /* PERIPH_EP0 (EP0_IN) event: this is treated separately from the rest */ + { + /* given ACK from host has happened, we can now set the address (if not already done) */ + if((USBD->FADDR != assigned_address) && (USBD->FADDR == 0)) USBD->FADDR = assigned_address; + + uint16_t const available_bytes = USBD->EP[PERIPH_EP0].MXPLD; + + active_ep0_xfer = (available_bytes == xfer_table[PERIPH_EP0].max_packet_size); + + dcd_event_xfer_complete(0, 0x80, available_bytes, XFER_RESULT_SUCCESS, true); + } + + /* service PERIPH_EP1 through PERIPH_EP7 */ + enum ep_enum ep_index; + uint32_t mask; + struct xfer_ctl_t *xfer; + USBD_EP_T *ep; + for (ep_index = PERIPH_EP1, mask = USBD_INTSTS_EPEVT1_Msk, xfer = &xfer_table[PERIPH_EP1], ep = &USBD->EP[PERIPH_EP1]; ep_index <= PERIPH_EP7; ep_index++, mask <<= 1, xfer++, ep++) + { + if(status & mask) + { + USBD->INTSTS = mask; + + uint16_t const available_bytes = ep->MXPLD; + uint8_t const ep_addr = decode_ep_addr(ep); + bool const out_ep = !(ep_addr & TUSB_DIR_IN_MASK); + + if (out_ep) + { + /* copy the data from the PC to the previously provided buffer */ + memcpy(xfer->data_ptr, (uint8_t *)(USBD_BUF_BASE + ep->BUFSEG), available_bytes); + xfer->remaining_bytes -= available_bytes; + xfer->data_ptr += available_bytes; + + /* when the transfer is finished, alert TinyUSB; otherwise, accept more data */ + if ( (0 == xfer->remaining_bytes) || (available_bytes < xfer->max_packet_size) ) + dcd_event_xfer_complete(0, ep_addr, xfer->total_bytes, XFER_RESULT_SUCCESS, true); + else if (xfer->remaining_bytes) + ep->MXPLD = xfer->max_packet_size; + } + else + { + /* update the bookkeeping to reflect the data that has now been sent to the PC */ + xfer->remaining_bytes -= available_bytes; + xfer->data_ptr += available_bytes; + + /* if more data to send, send it; otherwise, alert TinyUSB that we've finished */ + if (xfer->remaining_bytes) + dcd_in_xfer(xfer, ep); + else + dcd_event_xfer_complete(0, ep_addr, xfer->total_bytes, XFER_RESULT_SUCCESS, true); + } + } + } + } + + if(status & USBD_INTSTS_SOFIF_Msk) + { + /* Start-Of-Frame event */ + dcd_event_bus_signal(0, DCD_EVENT_SOF, true); + } + + /* acknowledge all interrupts */ + USBD->INTSTS = status & enabled_irqs; +} + +void dcd_isr(uint8_t rhport) +{ + (void) rhport; + USBD_IRQHandler(); +} + +#endif diff --git a/src/tusb.c b/src/tusb.c index f6838745..5dc6825d 100644 --- a/src/tusb.c +++ b/src/tusb.c @@ -1,148 +1,148 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2019 Ha Thach (tinyusb.org) - * - * 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. - * - * This file is part of the TinyUSB stack. - */ - -#include "tusb_option.h" - -#if TUSB_OPT_HOST_ENABLED || TUSB_OPT_DEVICE_ENABLED - -#include "tusb.h" - -static bool _initialized = false; - -// TODO clean up -#if TUSB_OPT_DEVICE_ENABLED -#include "device/usbd_pvt.h" -#endif - -bool tusb_init(void) -{ - // skip if already initialized - if (_initialized) return true; - -#if TUSB_OPT_HOST_ENABLED - TU_ASSERT( usbh_init() ); // init host stack -#endif - -#if TUSB_OPT_DEVICE_ENABLED - TU_ASSERT ( tud_init() ); // init device stack -#endif - - _initialized = true; - - return TUSB_ERROR_NONE; -} - -bool tusb_inited(void) -{ - return _initialized; -} - -/*------------------------------------------------------------------*/ -/* Debug - *------------------------------------------------------------------*/ -#if CFG_TUSB_DEBUG -#include - -char const* const tusb_strerr[TUSB_ERROR_COUNT] = { ERROR_TABLE(ERROR_STRING) }; - -static void dump_str_line(uint8_t const* buf, uint16_t count) -{ - // each line is 16 bytes - for(int i=0; i + +char const* const tusb_strerr[TUSB_ERROR_COUNT] = { ERROR_TABLE(ERROR_STRING) }; + +static void dump_str_line(uint8_t const* buf, uint16_t count) +{ + // each line is 16 bytes + for(int i=0; i= 0 ) - -// Which roothub port is configured as device -#define TUD_OPT_RHPORT ( (CFG_TUSB_RHPORT0_MODE & OPT_MODE_DEVICE) ? 0 : ((CFG_TUSB_RHPORT1_MODE & OPT_MODE_DEVICE) ? 1 : -1) ) - -#if TUD_OPT_RHPORT == 0 -#define TUD_OPT_HIGH_SPEED ( CFG_TUSB_RHPORT0_MODE & OPT_MODE_HIGH_SPEED ) -#else -#define TUD_OPT_HIGH_SPEED ( CFG_TUSB_RHPORT1_MODE & OPT_MODE_HIGH_SPEED ) -#endif - -#define TUSB_OPT_DEVICE_ENABLED ( TUD_OPT_RHPORT >= 0 ) - - -//--------------------------------------------------------------------+ -// COMMON OPTIONS -//--------------------------------------------------------------------+ - -// Debug enable to print out error message -#ifndef CFG_TUSB_DEBUG - #define CFG_TUSB_DEBUG 0 -#endif - -// place data in accessible RAM for usb controller -#ifndef CFG_TUSB_MEM_SECTION -#define CFG_TUSB_MEM_SECTION -#endif - -#ifndef CFG_TUSB_MEM_ALIGN -#define CFG_TUSB_MEM_ALIGN TU_ATTR_ALIGNED(4) -#endif - -#ifndef CFG_TUSB_OS -#define CFG_TUSB_OS OPT_OS_NONE -#endif - -//-------------------------------------------------------------------- -// DEVICE OPTIONS -//-------------------------------------------------------------------- - -#ifndef CFG_TUD_ENDPOINT0_SIZE - #define CFG_TUD_ENDPOINT0_SIZE 64 -#endif - -#ifndef CFG_TUD_CDC - #define CFG_TUD_CDC 0 -#endif - -#ifndef CFG_TUD_MSC - #define CFG_TUD_MSC 0 -#endif - -#ifndef CFG_TUD_HID - #define CFG_TUD_HID 0 -#endif - -#ifndef CFG_TUD_MIDI - #define CFG_TUD_MIDI 0 -#endif - -#ifndef CFG_TUD_VENDOR - #define CFG_TUD_VENDOR 0 -#endif - -#ifndef CFG_TUD_USBTMC - #define CFG_TUD_USBTMC 0 -#endif - -#ifndef CFG_TUD_DFU_RT - #define CFG_TUD_DFU_RT 0 -#endif - - -//-------------------------------------------------------------------- -// HOST OPTIONS -//-------------------------------------------------------------------- -#if TUSB_OPT_HOST_ENABLED - #ifndef CFG_TUSB_HOST_DEVICE_MAX - #define CFG_TUSB_HOST_DEVICE_MAX 1 - #warning CFG_TUSB_HOST_DEVICE_MAX is not defined, default value is 1 - #endif - - //------------- HUB CLASS -------------// - #if CFG_TUH_HUB && (CFG_TUSB_HOST_DEVICE_MAX == 1) - #error there is no benefit enable hub with max device is 1. Please disable hub or increase CFG_TUSB_HOST_DEVICE_MAX - #endif - - //------------- HID CLASS -------------// - #define HOST_CLASS_HID ( CFG_TUH_HID_KEYBOARD + CFG_TUH_HID_MOUSE + CFG_TUSB_HOST_HID_GENERIC ) - - #ifndef CFG_TUSB_HOST_ENUM_BUFFER_SIZE - #define CFG_TUSB_HOST_ENUM_BUFFER_SIZE 256 - #endif - - //------------- CLASS -------------// -#endif // TUSB_OPT_HOST_ENABLED - - -//------------------------------------------------------------------ -// Configuration Validation -//------------------------------------------------------------------ -#if CFG_TUD_ENDPOINT0_SIZE > 64 - #error Control Endpoint Max Packet Size cannot be larger than 64 -#endif - -#endif /* _TUSB_OPTION_H_ */ - -/** @} */ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#ifndef _TUSB_OPTION_H_ +#define _TUSB_OPTION_H_ + +#define TUSB_VERSION_MAJOR 0 +#define TUSB_VERSION_MINOR 5 +#define TUSB_VERSION_REVISION 0 +#define TUSB_VERSION_STRING TU_STRING(TUSB_VERSION_MAJOR) "." TU_STRING(TUSB_VERSION_MINOR) "." TU_STRING(TUSB_VERSION_REVISION) + +/** \defgroup group_mcu Supported MCU + * \ref CFG_TUSB_MCU must be defined to one of these + * @{ */ + +#define OPT_MCU_NONE 0 + +// LPC +#define OPT_MCU_LPC11UXX 1 ///< NXP LPC11Uxx +#define OPT_MCU_LPC13XX 2 ///< NXP LPC13xx +#define OPT_MCU_LPC15XX 3 ///< NXP LPC15xx +#define OPT_MCU_LPC175X_6X 4 ///< NXP LPC175x, LPC176x +#define OPT_MCU_LPC177X_8X 5 ///< NXP LPC177x, LPC178x +#define OPT_MCU_LPC18XX 6 ///< NXP LPC18xx +#define OPT_MCU_LPC40XX 7 ///< NXP LPC40xx +#define OPT_MCU_LPC43XX 8 ///< NXP LPC43xx +#define OPT_MCU_LPC51UXX 9 ///< NXP LPC51U6x +#define OPT_MCU_LPC54XXX 10 ///< NXP LPC54xxx +#define OPT_MCU_LPC55XX 11 ///< NXP LPC55xx + +// NRF +#define OPT_MCU_NRF5X 100 ///< Nordic nRF5x series + +// SAM +#define OPT_MCU_SAMD21 200 ///< MicroChip SAMD21 +#define OPT_MCU_SAMD51 201 ///< MicroChip SAMD51 +#define OPT_MCU_SAMG 202 ///< MicroChip SAMDG series + +// STM32 +#define OPT_MCU_STM32F0 300 ///< ST STM32F0 +#define OPT_MCU_STM32F1 301 ///< ST STM32F1 +#define OPT_MCU_STM32F2 302 ///< ST STM32F2 +#define OPT_MCU_STM32F3 303 ///< ST STM32F3 +#define OPT_MCU_STM32F4 304 ///< ST STM32F4 +#define OPT_MCU_STM32F7 305 ///< ST STM32F7 +#define OPT_MCU_STM32H7 306 ///< ST STM32H7 +#define OPT_MCU_STM32L0 307 ///< ST STM32L0 +#define OPT_MCU_STM32L1 308 ///< ST STM32L1 +#define OPT_MCU_STM32L4 309 ///< ST STM32L4 + +#define OPT_MCU_CXD56 400 ///< SONY CXD56 + +#define OPT_MCU_VALENTYUSB_EPTRI 600 ///< Fomu eptri config + +#define OPT_MCU_MIMXRT10XX 700 ///< NXP iMX RT10xx + +#define OPT_MCU_NUC121 800 +#define OPT_MCU_NUC126 801 + +/** @} */ + +/** \defgroup group_supported_os Supported RTOS + * \ref CFG_TUSB_OS must be defined to one of these + * @{ */ +#define OPT_OS_NONE 1 ///< No RTOS +#define OPT_OS_FREERTOS 2 ///< FreeRTOS +#define OPT_OS_MYNEWT 3 ///< Mynewt OS +/** @} */ + + +// Allow to use command line to change the config name/location +#ifndef CFG_TUSB_CONFIG_FILE + #define CFG_TUSB_CONFIG_FILE "tusb_config.h" +#endif + +#include CFG_TUSB_CONFIG_FILE + +/** \addtogroup group_configuration + * @{ */ + +//-------------------------------------------------------------------- +// CONTROLLER +// Only 1 roothub port can be configured to be device and/or host. +// tinyusb does not support dual devices or dual host configuration +//-------------------------------------------------------------------- +/** \defgroup group_mode Controller Mode Selection + * \brief CFG_TUSB_CONTROLLER_N_MODE must be defined with these + * @{ */ +#define OPT_MODE_NONE 0x00 ///< Disabled +#define OPT_MODE_DEVICE 0x01 ///< Device Mode +#define OPT_MODE_HOST 0x02 ///< Host Mode +#define OPT_MODE_HIGH_SPEED 0x10 ///< High speed +/** @} */ + +#ifndef CFG_TUSB_RHPORT0_MODE + #define CFG_TUSB_RHPORT0_MODE OPT_MODE_NONE +#endif + +#ifndef CFG_TUSB_RHPORT1_MODE + #define CFG_TUSB_RHPORT1_MODE OPT_MODE_NONE +#endif + +#if ((CFG_TUSB_RHPORT0_MODE & OPT_MODE_HOST) && (CFG_TUSB_RHPORT1_MODE & OPT_MODE_HOST)) || \ + ((CFG_TUSB_RHPORT0_MODE & OPT_MODE_DEVICE) && (CFG_TUSB_RHPORT1_MODE & OPT_MODE_DEVICE)) + #error "tinyusb does not support same modes on more than 1 roothub port" +#endif + +// Which roothub port is configured as host +#define TUH_OPT_RHPORT ( (CFG_TUSB_RHPORT0_MODE & OPT_MODE_HOST) ? 0 : ((CFG_TUSB_RHPORT1_MODE & OPT_MODE_HOST) ? 1 : -1) ) +#define TUSB_OPT_HOST_ENABLED ( TUH_OPT_RHPORT >= 0 ) + +// Which roothub port is configured as device +#define TUD_OPT_RHPORT ( (CFG_TUSB_RHPORT0_MODE & OPT_MODE_DEVICE) ? 0 : ((CFG_TUSB_RHPORT1_MODE & OPT_MODE_DEVICE) ? 1 : -1) ) + +#if TUD_OPT_RHPORT == 0 +#define TUD_OPT_HIGH_SPEED ( CFG_TUSB_RHPORT0_MODE & OPT_MODE_HIGH_SPEED ) +#else +#define TUD_OPT_HIGH_SPEED ( CFG_TUSB_RHPORT1_MODE & OPT_MODE_HIGH_SPEED ) +#endif + +#define TUSB_OPT_DEVICE_ENABLED ( TUD_OPT_RHPORT >= 0 ) + + +//--------------------------------------------------------------------+ +// COMMON OPTIONS +//--------------------------------------------------------------------+ + +// Debug enable to print out error message +#ifndef CFG_TUSB_DEBUG + #define CFG_TUSB_DEBUG 0 +#endif + +// place data in accessible RAM for usb controller +#ifndef CFG_TUSB_MEM_SECTION +#define CFG_TUSB_MEM_SECTION +#endif + +#ifndef CFG_TUSB_MEM_ALIGN +#define CFG_TUSB_MEM_ALIGN TU_ATTR_ALIGNED(4) +#endif + +#ifndef CFG_TUSB_OS +#define CFG_TUSB_OS OPT_OS_NONE +#endif + +//-------------------------------------------------------------------- +// DEVICE OPTIONS +//-------------------------------------------------------------------- + +#ifndef CFG_TUD_ENDPOINT0_SIZE + #define CFG_TUD_ENDPOINT0_SIZE 64 +#endif + +#ifndef CFG_TUD_CDC + #define CFG_TUD_CDC 0 +#endif + +#ifndef CFG_TUD_MSC + #define CFG_TUD_MSC 0 +#endif + +#ifndef CFG_TUD_HID + #define CFG_TUD_HID 0 +#endif + +#ifndef CFG_TUD_MIDI + #define CFG_TUD_MIDI 0 +#endif + +#ifndef CFG_TUD_VENDOR + #define CFG_TUD_VENDOR 0 +#endif + +#ifndef CFG_TUD_USBTMC + #define CFG_TUD_USBTMC 0 +#endif + +#ifndef CFG_TUD_DFU_RT + #define CFG_TUD_DFU_RT 0 +#endif + + +//-------------------------------------------------------------------- +// HOST OPTIONS +//-------------------------------------------------------------------- +#if TUSB_OPT_HOST_ENABLED + #ifndef CFG_TUSB_HOST_DEVICE_MAX + #define CFG_TUSB_HOST_DEVICE_MAX 1 + #warning CFG_TUSB_HOST_DEVICE_MAX is not defined, default value is 1 + #endif + + //------------- HUB CLASS -------------// + #if CFG_TUH_HUB && (CFG_TUSB_HOST_DEVICE_MAX == 1) + #error there is no benefit enable hub with max device is 1. Please disable hub or increase CFG_TUSB_HOST_DEVICE_MAX + #endif + + //------------- HID CLASS -------------// + #define HOST_CLASS_HID ( CFG_TUH_HID_KEYBOARD + CFG_TUH_HID_MOUSE + CFG_TUSB_HOST_HID_GENERIC ) + + #ifndef CFG_TUSB_HOST_ENUM_BUFFER_SIZE + #define CFG_TUSB_HOST_ENUM_BUFFER_SIZE 256 + #endif + + //------------- CLASS -------------// +#endif // TUSB_OPT_HOST_ENABLED + + +//------------------------------------------------------------------ +// Configuration Validation +//------------------------------------------------------------------ +#if CFG_TUD_ENDPOINT0_SIZE > 64 + #error Control Endpoint Max Packet Size cannot be larger than 64 +#endif + +#endif /* _TUSB_OPTION_H_ */ + +/** @} */ From c04bc07c2926ccc2d3404cd8ebb8c7aee69c04ee Mon Sep 17 00:00:00 2001 From: Peter Lawrence <12226419+majbthrd@users.noreply.github.com> Date: Wed, 15 Jan 2020 20:09:50 -0600 Subject: [PATCH 212/267] nuc121: enhanced driver and hopefully added readability --- src/portable/nuvoton/nuc121/dcd_nuc121.c | 28 +++++++++++++++--------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/src/portable/nuvoton/nuc121/dcd_nuc121.c b/src/portable/nuvoton/nuc121/dcd_nuc121.c index 237a5fd9..71211af0 100644 --- a/src/portable/nuvoton/nuc121/dcd_nuc121.c +++ b/src/portable/nuvoton/nuc121/dcd_nuc121.c @@ -77,8 +77,11 @@ static bool active_ep0_xfer; /* RAM table needed to track ongoing transfers performed by dcd_edpt_xfer(), dcd_in_xfer(), and the ISR */ static struct xfer_ctl_t { - uint8_t *data_ptr; /* collectively, data_ptr and remaining_bytes track progress of endpoint transfers */ - uint16_t remaining_bytes; + uint8_t *data_ptr; /* data_ptr tracks where to next copy data to (for OUT) or from (for IN) */ + union { + uint16_t in_remaining_bytes; /* for IN endpoints, we track how many bytes are left to transfer */ + uint16_t out_bytes_so_far; /* but for OUT endpoints, we track how many bytes we've transferred so far */ + }; uint16_t max_packet_size; /* needed since device driver only finds out this at runtime */ uint16_t total_bytes; /* quantity needed to pass as argument to dcd_event_xfer_complete() (for IN endpoints) */ } xfer_table[PERIPH_MAX_EP]; @@ -139,7 +142,7 @@ static USBD_EP_T *ep_entry(uint8_t ep_addr, bool add) /* perform an IN endpoint transfer; this is called by dcd_edpt_xfer() and the ISR */ static void dcd_in_xfer(struct xfer_ctl_t *xfer, USBD_EP_T *ep) { - uint16_t bytes_now = tu_min16(xfer->remaining_bytes, xfer->max_packet_size); + uint16_t bytes_now = tu_min16(xfer->in_remaining_bytes, xfer->max_packet_size); memcpy((uint8_t *)(USBD_BUF_BASE + ep->BUFSEG), xfer->data_ptr, bytes_now); ep->MXPLD = bytes_now; @@ -263,16 +266,21 @@ bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t *buffer, uint16_t to /* store away the information we'll needing now and later */ xfer->data_ptr = buffer; - xfer->remaining_bytes = total_bytes; + xfer->in_remaining_bytes = total_bytes; xfer->total_bytes = total_bytes; /* for the first of one or more EP0_IN packets in a message, the first must be DATA1 */ if ( (0x80 == ep_addr) && !active_ep0_xfer ) ep->CFG |= USBD_CFG_DSQSYNC_Msk; if (TUSB_DIR_IN == dir) + { dcd_in_xfer(xfer, ep); + } else + { + xfer->out_bytes_so_far = 0; ep->MXPLD = xfer->max_packet_size; + } return true; } @@ -392,23 +400,23 @@ void USBD_IRQHandler(void) { /* copy the data from the PC to the previously provided buffer */ memcpy(xfer->data_ptr, (uint8_t *)(USBD_BUF_BASE + ep->BUFSEG), available_bytes); - xfer->remaining_bytes -= available_bytes; + xfer->out_bytes_so_far += available_bytes; xfer->data_ptr += available_bytes; /* when the transfer is finished, alert TinyUSB; otherwise, accept more data */ - if ( (0 == xfer->remaining_bytes) || (available_bytes < xfer->max_packet_size) ) - dcd_event_xfer_complete(0, ep_addr, xfer->total_bytes, XFER_RESULT_SUCCESS, true); - else if (xfer->remaining_bytes) + if ( (xfer->total_bytes == xfer->out_bytes_so_far) || (available_bytes < xfer->max_packet_size) ) + dcd_event_xfer_complete(0, ep_addr, xfer->out_bytes_so_far, XFER_RESULT_SUCCESS, true); + else ep->MXPLD = xfer->max_packet_size; } else { /* update the bookkeeping to reflect the data that has now been sent to the PC */ - xfer->remaining_bytes -= available_bytes; + xfer->in_remaining_bytes -= available_bytes; xfer->data_ptr += available_bytes; /* if more data to send, send it; otherwise, alert TinyUSB that we've finished */ - if (xfer->remaining_bytes) + if (xfer->in_remaining_bytes) dcd_in_xfer(xfer, ep); else dcd_event_xfer_complete(0, ep_addr, xfer->total_bytes, XFER_RESULT_SUCCESS, true); From 2ed395bde313ad7d2591dc23c686469d16884e79 Mon Sep 17 00:00:00 2001 From: Peter Lawrence <12226419+majbthrd@users.noreply.github.com> Date: Wed, 15 Jan 2020 21:40:24 -0600 Subject: [PATCH 213/267] nuc121: survive USB bus reset --- src/portable/nuvoton/nuc121/dcd_nuc121.c | 61 +++++++++++++----------- 1 file changed, 33 insertions(+), 28 deletions(-) diff --git a/src/portable/nuvoton/nuc121/dcd_nuc121.c b/src/portable/nuvoton/nuc121/dcd_nuc121.c index 71211af0..9c0cefd7 100644 --- a/src/portable/nuvoton/nuc121/dcd_nuc121.c +++ b/src/portable/nuvoton/nuc121/dcd_nuc121.c @@ -148,6 +148,37 @@ static void dcd_in_xfer(struct xfer_ctl_t *xfer, USBD_EP_T *ep) ep->MXPLD = bytes_now; } +/* called by dcd_init() as well as by the ISR during a USB bus reset */ +static void bus_reset(void) +{ + USBD->STBUFSEG = PERIPH_SETUP_BUF_BASE; + + for (enum ep_enum ep_index = PERIPH_EP0; ep_index < PERIPH_MAX_EP; ep_index++) + { + USBD->EP[ep_index].CFG = 0; + USBD->EP[ep_index].CFGP = 0; + } + + /* allocate the default EP0 endpoints */ + + USBD->EP[PERIPH_EP0].CFG = USBD_CFG_CSTALL_Msk | USBD_CFG_EPMODE_IN; + USBD->EP[PERIPH_EP0].BUFSEG = PERIPH_EP0_BUF_BASE; + xfer_table[PERIPH_EP0].max_packet_size = PERIPH_EP0_BUF_LEN; + + USBD->EP[PERIPH_EP1].CFG = USBD_CFG_CSTALL_Msk | USBD_CFG_EPMODE_OUT; + USBD->EP[PERIPH_EP1].BUFSEG = PERIPH_EP1_BUF_BASE; + xfer_table[PERIPH_EP1].max_packet_size = PERIPH_EP1_BUF_LEN; + + /* USB RAM beyond what we've allocated above is available to the user */ + bufseg_addr = PERIPH_EP2_BUF_BASE; + + /* Reset USB device address */ + USBD->FADDR = 0; + + /* reset EP0_IN flag */ + active_ep0_xfer = false; +} + /* centralized location for USBD interrupt enable bit mask */ static const uint32_t enabled_irqs = USBD_INTSTS_VBDETIF_Msk | USBD_INTSTS_BUSIF_Msk | USBD_INTSTS_SETUP_Msk | USBD_INTSTS_USBIF_Msk | USBD_INTSTS_SOFIF_Msk; @@ -167,25 +198,7 @@ void dcd_init(uint8_t rhport) usb_detach(); - USBD->STBUFSEG = PERIPH_SETUP_BUF_BASE; - - for (enum ep_enum ep_index = PERIPH_EP0; ep_index < PERIPH_MAX_EP; ep_index++) - { - USBD->EP[ep_index].CFGP &= ~USBD_CFG_STATE_Msk; - } - - /* allocate the default EP0 endpoints */ - - USBD->EP[PERIPH_EP0].CFG = USBD_CFG_CSTALL_Msk | USBD_CFG_EPMODE_IN; - USBD->EP[PERIPH_EP0].BUFSEG = PERIPH_EP0_BUF_BASE; - xfer_table[PERIPH_EP0].max_packet_size = PERIPH_EP0_BUF_LEN; - - USBD->EP[PERIPH_EP1].CFG = USBD_CFG_CSTALL_Msk | USBD_CFG_EPMODE_OUT; - USBD->EP[PERIPH_EP1].BUFSEG = PERIPH_EP1_BUF_BASE; - xfer_table[PERIPH_EP1].max_packet_size = PERIPH_EP1_BUF_LEN; - - /* USB RAM beyond what we've allocated above is available to the user */ - bufseg_addr = PERIPH_EP2_BUF_BASE; + bus_reset(); usb_attach(); @@ -329,15 +342,7 @@ void USBD_IRQHandler(void) /* USB bus reset */ USBD->ATTR |= USBD_ATTR_USBEN_Msk | USBD_ATTR_PHYEN_Msk; - /* Reset all endpoints to DATA0 */ - for(enum ep_enum ep_index = PERIPH_EP0; ep_index < PERIPH_MAX_EP; ep_index++) - USBD->EP[ep_index].CFG &= ~USBD_CFG_DSQSYNC_Msk; - - /* Reset USB device address */ - USBD->FADDR = 0; - - /* reset EP0_IN flag */ - active_ep0_xfer = false; + bus_reset(); dcd_event_bus_signal(0, DCD_EVENT_BUS_RESET, true); } From 05fd02194e40d5ea5bef1cef512ae0ce2bdde48a Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 16 Jan 2020 11:12:26 +0700 Subject: [PATCH 214/267] correct return value of midid_xfer_cb --- src/class/midi/midi_device.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/class/midi/midi_device.c b/src/class/midi/midi_device.c index 31240562..ae6e3afe 100644 --- a/src/class/midi/midi_device.c +++ b/src/class/midi/midi_device.c @@ -355,7 +355,7 @@ bool midid_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32 // nothing to do with in and notif endpoint - return TUSB_ERROR_NONE; + return true; } #endif From ae68668df9c2e50ab2283485c7aca851adeedfc1 Mon Sep 17 00:00:00 2001 From: Scott Shawcroft Date: Wed, 15 Jan 2020 21:59:15 -0800 Subject: [PATCH 215/267] flush and invalidate the dcache --- .../nxp/transdimension/dcd_transdimension.c | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/src/portable/nxp/transdimension/dcd_transdimension.c b/src/portable/nxp/transdimension/dcd_transdimension.c index 2ec7ae51..b5fca9ef 100644 --- a/src/portable/nxp/transdimension/dcd_transdimension.c +++ b/src/portable/nxp/transdimension/dcd_transdimension.c @@ -1,4 +1,4 @@ -/* +/* * The MIT License (MIT) * * Copyright (c) 2019 Ha Thach (tinyusb.org) @@ -313,9 +313,12 @@ void dcd_init(uint8_t rhport) // TODO Force fullspeed on non-highspeed port // dcd_reg->PORTSC1 = PORTSC1_FORCE_FULL_SPEED; + + SCB_CleanInvalidateDCache_by_Addr(&_dcd_data, sizeof(dcd_data_t)); + dcd_reg->ENDPTLISTADDR = (uint32_t) _dcd_data.qhd; // Endpoint List Address has to be 2K alignment dcd_reg->USBSTS = dcd_reg->USBSTS; - dcd_reg->USBINTR = INTR_USB | INTR_ERROR | INTR_PORT_CHANGE | INTR_RESET | INTR_SUSPEND | INTR_SOF; + dcd_reg->USBINTR = INTR_USB | INTR_ERROR | INTR_PORT_CHANGE | INTR_RESET | INTR_SUSPEND; // | INTR_SOF; dcd_reg->USBCMD &= ~0x00FF0000; // Interrupt Threshold Interval = 0 dcd_reg->USBCMD |= TU_BIT(0); // connect @@ -418,6 +421,7 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc) p_qhd->zero_length_termination = 1; p_qhd->max_package_size = p_endpoint_desc->wMaxPacketSize.size; p_qhd->qtd_overlay.next = QTD_NEXT_INVALID; + SCB_CleanInvalidateDCache_by_Addr(&_dcd_data, sizeof(dcd_data_t)); // Enable EP Control DCD_REGS[rhport]->ENDPTCTRL[epnum] |= ((p_endpoint_desc->bmAttributes.xfer << 2) | ENDPTCTRL_ENABLE | ENDPTCTRL_TOGGLE_RESET) << (dir ? 16 : 0); @@ -441,10 +445,14 @@ bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t t dcd_qhd_t * p_qhd = &_dcd_data.qhd[ep_idx]; dcd_qtd_t * p_qtd = &_dcd_data.qtd[ep_idx]; + // Force the CPU to flush the buffer. + SCB_CleanInvalidateDCache_by_Addr(buffer, total_bytes); + //------------- Prepare qtd -------------// qtd_init(p_qtd, buffer, total_bytes); p_qtd->int_on_complete = true; p_qhd->qtd_overlay.next = (uint32_t) p_qtd; // link qtd to qhd + SCB_CleanInvalidateDCache_by_Addr(&_dcd_data, sizeof(dcd_data_t)); // start transfer DCD_REGS[rhport]->ENDPTPRIME = TU_BIT( ep_idx2bit(ep_idx) ) ; @@ -484,6 +492,9 @@ void dcd_isr(uint8_t rhport) } } + // Make sure we read the latest version of _dcd_data. + SCB_CleanInvalidateDCache_by_Addr(&_dcd_data, sizeof(dcd_data_t)); + // TODO disconnection does not generate interrupt !!!!!! // if (int_status & INTR_PORT_CHANGE) // { From cd6454a330e4251c9ff01403078a537fc180b47a Mon Sep 17 00:00:00 2001 From: Scott Shawcroft Date: Thu, 16 Jan 2020 17:17:49 -0800 Subject: [PATCH 216/267] Add if guards for dcache flushes. --- .../nxp/transdimension/dcd_transdimension.c | 27 +++++++++++++------ 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/src/portable/nxp/transdimension/dcd_transdimension.c b/src/portable/nxp/transdimension/dcd_transdimension.c index b5fca9ef..77e355ed 100644 --- a/src/portable/nxp/transdimension/dcd_transdimension.c +++ b/src/portable/nxp/transdimension/dcd_transdimension.c @@ -313,12 +313,13 @@ void dcd_init(uint8_t rhport) // TODO Force fullspeed on non-highspeed port // dcd_reg->PORTSC1 = PORTSC1_FORCE_FULL_SPEED; - - SCB_CleanInvalidateDCache_by_Addr(&_dcd_data, sizeof(dcd_data_t)); + #if defined(__CORTEX_M) && __CORTEX_M == 7 && __DCACHE_PRESENT == 1 + SCB_CleanInvalidateDCache_by_Addr((uint32_t*) &_dcd_data, sizeof(dcd_data_t)); + #endif dcd_reg->ENDPTLISTADDR = (uint32_t) _dcd_data.qhd; // Endpoint List Address has to be 2K alignment dcd_reg->USBSTS = dcd_reg->USBSTS; - dcd_reg->USBINTR = INTR_USB | INTR_ERROR | INTR_PORT_CHANGE | INTR_RESET | INTR_SUSPEND; // | INTR_SOF; + dcd_reg->USBINTR = INTR_USB | INTR_ERROR | INTR_PORT_CHANGE | INTR_RESET | INTR_SUSPEND | INTR_SOF; dcd_reg->USBCMD &= ~0x00FF0000; // Interrupt Threshold Interval = 0 dcd_reg->USBCMD |= TU_BIT(0); // connect @@ -421,7 +422,10 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc) p_qhd->zero_length_termination = 1; p_qhd->max_package_size = p_endpoint_desc->wMaxPacketSize.size; p_qhd->qtd_overlay.next = QTD_NEXT_INVALID; - SCB_CleanInvalidateDCache_by_Addr(&_dcd_data, sizeof(dcd_data_t)); + + #if defined(__CORTEX_M) && __CORTEX_M == 7 && __DCACHE_PRESENT == 1 + SCB_CleanInvalidateDCache_by_Addr((uint32_t*) &_dcd_data, sizeof(dcd_data_t)); + #endif // Enable EP Control DCD_REGS[rhport]->ENDPTCTRL[epnum] |= ((p_endpoint_desc->bmAttributes.xfer << 2) | ENDPTCTRL_ENABLE | ENDPTCTRL_TOGGLE_RESET) << (dir ? 16 : 0); @@ -445,14 +449,19 @@ bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t t dcd_qhd_t * p_qhd = &_dcd_data.qhd[ep_idx]; dcd_qtd_t * p_qtd = &_dcd_data.qtd[ep_idx]; - // Force the CPU to flush the buffer. - SCB_CleanInvalidateDCache_by_Addr(buffer, total_bytes); + // Force the CPU to flush the buffer. We increase the size by 32 because the call aligns the + // address to 32-byte boundaries. + #if defined(__CORTEX_M) && __CORTEX_M == 7 && __DCACHE_PRESENT == 1 + SCB_CleanInvalidateDCache_by_Addr((uint32_t*) buffer, total_bytes + 31); + #endif //------------- Prepare qtd -------------// qtd_init(p_qtd, buffer, total_bytes); p_qtd->int_on_complete = true; p_qhd->qtd_overlay.next = (uint32_t) p_qtd; // link qtd to qhd - SCB_CleanInvalidateDCache_by_Addr(&_dcd_data, sizeof(dcd_data_t)); + #if defined(__CORTEX_M) && __CORTEX_M == 7 && __DCACHE_PRESENT == 1 + SCB_CleanInvalidateDCache_by_Addr((uint32_t*) &_dcd_data, sizeof(dcd_data_t)); + #endif // start transfer DCD_REGS[rhport]->ENDPTPRIME = TU_BIT( ep_idx2bit(ep_idx) ) ; @@ -493,7 +502,9 @@ void dcd_isr(uint8_t rhport) } // Make sure we read the latest version of _dcd_data. - SCB_CleanInvalidateDCache_by_Addr(&_dcd_data, sizeof(dcd_data_t)); + #if defined(__CORTEX_M) && __CORTEX_M == 7 && __DCACHE_PRESENT == 1 + SCB_CleanInvalidateDCache_by_Addr((uint32_t*) &_dcd_data, sizeof(dcd_data_t)); + #endif // TODO disconnection does not generate interrupt !!!!!! // if (int_status & INTR_PORT_CHANGE) From 3208fe00b6a34032492f0ec4b8f6a4d8ca12e474 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 17 Jan 2020 12:06:59 +0700 Subject: [PATCH 217/267] clean up --- examples/rules.mk | 1 + .../nxp/transdimension/dcd_transdimension.c | 56 +++++++++---------- 2 files changed, 29 insertions(+), 28 deletions(-) diff --git a/examples/rules.mk b/examples/rules.mk index 2969a66f..87c7e964 100644 --- a/examples/rules.mk +++ b/examples/rules.mk @@ -120,6 +120,7 @@ endif # Flash using jlink flash-jlink: $(BUILD)/$(BOARD)-firmware.hex @echo halt > $(BUILD)/$(BOARD).jlink + @echo r > $(BUILD)/$(BOARD).jlink @echo loadfile $^ >> $(BUILD)/$(BOARD).jlink @echo r >> $(BUILD)/$(BOARD).jlink @echo go >> $(BUILD)/$(BOARD).jlink diff --git a/src/portable/nxp/transdimension/dcd_transdimension.c b/src/portable/nxp/transdimension/dcd_transdimension.c index 77e355ed..89f595bd 100644 --- a/src/portable/nxp/transdimension/dcd_transdimension.c +++ b/src/portable/nxp/transdimension/dcd_transdimension.c @@ -130,48 +130,48 @@ enum { typedef struct { //------------- ID + HW Parameter Registers-------------// - __I uint32_t TU_RESERVED[64]; ///< For iMX RT10xx, but not used by LPC18XX/LPC43XX + __I uint32_t TU_RESERVED[64]; ///< For iMX RT10xx, but not used by LPC18XX/LPC43XX //------------- Capability Registers-------------// - __I uint8_t CAPLENGTH; ///< Capability Registers Length + __I uint8_t CAPLENGTH; ///< Capability Registers Length __I uint8_t TU_RESERVED[1]; - __I uint16_t HCIVERSION; ///< Host Controller Interface Version + __I uint16_t HCIVERSION; ///< Host Controller Interface Version - __I uint32_t HCSPARAMS; ///< Host Controller Structural Parameters - __I uint32_t HCCPARAMS; ///< Host Controller Capability Parameters + __I uint32_t HCSPARAMS; ///< Host Controller Structural Parameters + __I uint32_t HCCPARAMS; ///< Host Controller Capability Parameters __I uint32_t TU_RESERVED[5]; - __I uint16_t DCIVERSION; ///< Device Controller Interface Version + __I uint16_t DCIVERSION; ///< Device Controller Interface Version __I uint8_t TU_RESERVED[2]; - __I uint32_t DCCPARAMS; ///< Device Controller Capability Parameters + __I uint32_t DCCPARAMS; ///< Device Controller Capability Parameters __I uint32_t TU_RESERVED[6]; //------------- Operational Registers -------------// - __IO uint32_t USBCMD; ///< USB Command Register - __IO uint32_t USBSTS; ///< USB Status Register - __IO uint32_t USBINTR; ///< Interrupt Enable Register - __IO uint32_t FRINDEX; ///< USB Frame Index + __IO uint32_t USBCMD; ///< USB Command Register + __IO uint32_t USBSTS; ///< USB Status Register + __IO uint32_t USBINTR; ///< Interrupt Enable Register + __IO uint32_t FRINDEX; ///< USB Frame Index __I uint32_t TU_RESERVED; - __IO uint32_t DEVICEADDR; ///< Device Address - __IO uint32_t ENDPTLISTADDR; ///< Endpoint List Address + __IO uint32_t DEVICEADDR; ///< Device Address + __IO uint32_t ENDPTLISTADDR; ///< Endpoint List Address __I uint32_t TU_RESERVED; - __IO uint32_t BURSTSIZE; ///< Programmable Burst Size - __IO uint32_t TXFILLTUNING; ///< TX FIFO Fill Tuning + __IO uint32_t BURSTSIZE; ///< Programmable Burst Size + __IO uint32_t TXFILLTUNING; ///< TX FIFO Fill Tuning uint32_t TU_RESERVED[4]; - __IO uint32_t ENDPTNAK; ///< Endpoint NAK - __IO uint32_t ENDPTNAKEN; ///< Endpoint NAK Enable + __IO uint32_t ENDPTNAK; ///< Endpoint NAK + __IO uint32_t ENDPTNAKEN; ///< Endpoint NAK Enable __I uint32_t TU_RESERVED; - __IO uint32_t PORTSC1; ///< Port Status & Control + __IO uint32_t PORTSC1; ///< Port Status & Control __I uint32_t TU_RESERVED[7]; - __IO uint32_t OTGSC; ///< On-The-Go Status & control - __IO uint32_t USBMODE; ///< USB Device Mode - __IO uint32_t ENDPTSETUPSTAT; ///< Endpoint Setup Status - __IO uint32_t ENDPTPRIME; ///< Endpoint Prime - __IO uint32_t ENDPTFLUSH; ///< Endpoint Flush - __I uint32_t ENDPTSTAT; ///< Endpoint Status - __IO uint32_t ENDPTCOMPLETE; ///< Endpoint Complete - __IO uint32_t ENDPTCTRL[8]; ///< Endpoint Control 0 - 7 + __IO uint32_t OTGSC; ///< On-The-Go Status & control + __IO uint32_t USBMODE; ///< USB Device Mode + __IO uint32_t ENDPTSETUPSTAT; ///< Endpoint Setup Status + __IO uint32_t ENDPTPRIME; ///< Endpoint Prime + __IO uint32_t ENDPTFLUSH; ///< Endpoint Flush + __I uint32_t ENDPTSTAT; ///< Endpoint Status + __IO uint32_t ENDPTCOMPLETE; ///< Endpoint Complete + __IO uint32_t ENDPTCTRL[8]; ///< Endpoint Control 0 - 7 } dcd_registers_t; @@ -279,9 +279,9 @@ static void bus_reset(uint8_t rhport) dcd_reg->ENDPTSETUPSTAT = dcd_reg->ENDPTSETUPSTAT; dcd_reg->ENDPTCOMPLETE = dcd_reg->ENDPTCOMPLETE; - while (dcd_reg->ENDPTPRIME); + while (dcd_reg->ENDPTPRIME) {} dcd_reg->ENDPTFLUSH = 0xFFFFFFFF; - while (dcd_reg->ENDPTFLUSH); + while (dcd_reg->ENDPTFLUSH) {} // read reset bit in portsc From 04d8671641a7d4bfa07cc7f05ea03cb99771240b Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 17 Jan 2020 12:59:00 +0700 Subject: [PATCH 218/267] clean up, disable SOF for dcd trans since we don't use it for now --- .../nxp/transdimension/dcd_transdimension.c | 74 +++++++++---------- 1 file changed, 36 insertions(+), 38 deletions(-) diff --git a/src/portable/nxp/transdimension/dcd_transdimension.c b/src/portable/nxp/transdimension/dcd_transdimension.c index 89f595bd..a9823a26 100644 --- a/src/portable/nxp/transdimension/dcd_transdimension.c +++ b/src/portable/nxp/transdimension/dcd_transdimension.c @@ -39,18 +39,19 @@ #if CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX #include "fsl_device_registers.h" -// RT1010 and RT1020 only has 1 USB controller -#if FSL_FEATURE_SOC_USBHS_COUNT == 1 - #define DCD_REGS_BASE { (dcd_registers_t*) USB_BASE } - IRQn_Type DCD_IRQn[] = { USB_OTG1_IRQn }; + // RT1010 and RT1020 only has 1 USB controller + #if FSL_FEATURE_SOC_USBHS_COUNT == 1 + #define DCD_REGS_BASE { (dcd_registers_t*) USB_BASE } + IRQn_Type DCD_IRQn[] = { USB_OTG1_IRQn }; -// RT1050, RT1060 has 2 USB controllers -#else - #define DCD_REGS_BASE { (dcd_registers_t*) USB1_BASE, (dcd_registers_t*) USB2_BASE } - IRQn_Type DCD_IRQn[] = { USB_OTG1_IRQn, USB_OTG2_IRQn }; -#endif + // RT1050, RT1060 has 2 USB controllers + #else + #define DCD_REGS_BASE { (dcd_registers_t*) USB1_BASE, (dcd_registers_t*) USB2_BASE } + IRQn_Type DCD_IRQn[] = { USB_OTG1_IRQn, USB_OTG2_IRQn }; + #endif #else + // LPCOpen for 18xx & 43xx #include "chip.h" #define DCD_REGS_BASE { (dcd_registers_t*) LPC_USB0_BASE, (dcd_registers_t*) LPC_USB1_BASE } IRQn_Type DCD_IRQn[] = { USB0_IRQn, USB1_IRQn }; @@ -218,19 +219,19 @@ typedef struct uint32_t : 0 ; // Word 1: Current qTD Pointer - volatile uint32_t qtd_addr; + volatile uint32_t qtd_addr; - // Word 2-9: Transfer Overlay - volatile dcd_qtd_t qtd_overlay; + // Word 2-9: Transfer Overlay + volatile dcd_qtd_t qtd_overlay; - // Word 10-11: Setup request (control OUT only) - volatile tusb_control_request_t setup_request; + // Word 10-11: Setup request (control OUT only) + volatile tusb_control_request_t setup_request; - //--------------------------------------------------------------------+ - /// Due to the fact QHD is 64 bytes aligned but occupies only 48 bytes - /// thus there are 16 bytes padding free that we can make use of. //--------------------------------------------------------------------+ - uint8_t reserved[16]; + /// Due to the fact QHD is 64 bytes aligned but occupies only 48 bytes + /// thus there are 16 bytes padding free that we can make use of. + //--------------------------------------------------------------------+ + uint8_t reserved[16]; } dcd_qhd_t; TU_VERIFY_STATIC( sizeof(dcd_qhd_t) == 64, "size is not correct"); @@ -251,6 +252,12 @@ typedef struct { static dcd_data_t _dcd_data CFG_TUSB_MEM_SECTION TU_ATTR_ALIGNED(2048); static dcd_registers_t* DCD_REGS[] = DCD_REGS_BASE; +#if defined(__CORTEX_M) && __CORTEX_M == 7 && __DCACHE_PRESENT == 1 + #define CleanInvalidateDCache_by_Addr SCB_CleanInvalidateDCache_by_Addr +#else + #define CleanInvalidateDCache_by_Addr(_addr, _dsize) +#endif + //--------------------------------------------------------------------+ // CONTROLLER API //--------------------------------------------------------------------+ @@ -289,11 +296,11 @@ static void bus_reset(uint8_t rhport) tu_memclr(&_dcd_data, sizeof(dcd_data_t)); //------------- Set up Control Endpoints (0 OUT, 1 IN) -------------// - _dcd_data.qhd[0].zero_length_termination = _dcd_data.qhd[1].zero_length_termination = 1; - _dcd_data.qhd[0].max_package_size = _dcd_data.qhd[1].max_package_size = CFG_TUD_ENDPOINT0_SIZE; - _dcd_data.qhd[0].qtd_overlay.next = _dcd_data.qhd[1].qtd_overlay.next = QTD_NEXT_INVALID; + _dcd_data.qhd[0].zero_length_termination = _dcd_data.qhd[1].zero_length_termination = 1; + _dcd_data.qhd[0].max_package_size = _dcd_data.qhd[1].max_package_size = CFG_TUD_ENDPOINT0_SIZE; + _dcd_data.qhd[0].qtd_overlay.next = _dcd_data.qhd[1].qtd_overlay.next = QTD_NEXT_INVALID; - _dcd_data.qhd[0].int_on_setup = 1; // OUT only + _dcd_data.qhd[0].int_on_setup = 1; // OUT only } void dcd_init(uint8_t rhport) @@ -313,13 +320,11 @@ void dcd_init(uint8_t rhport) // TODO Force fullspeed on non-highspeed port // dcd_reg->PORTSC1 = PORTSC1_FORCE_FULL_SPEED; - #if defined(__CORTEX_M) && __CORTEX_M == 7 && __DCACHE_PRESENT == 1 - SCB_CleanInvalidateDCache_by_Addr((uint32_t*) &_dcd_data, sizeof(dcd_data_t)); - #endif + CleanInvalidateDCache_by_Addr((uint32_t*) &_dcd_data, sizeof(dcd_data_t)); dcd_reg->ENDPTLISTADDR = (uint32_t) _dcd_data.qhd; // Endpoint List Address has to be 2K alignment dcd_reg->USBSTS = dcd_reg->USBSTS; - dcd_reg->USBINTR = INTR_USB | INTR_ERROR | INTR_PORT_CHANGE | INTR_RESET | INTR_SUSPEND | INTR_SOF; + dcd_reg->USBINTR = INTR_USB | INTR_ERROR | INTR_PORT_CHANGE | INTR_RESET | INTR_SUSPEND /*| INTR_SOF*/; dcd_reg->USBCMD &= ~0x00FF0000; // Interrupt Threshold Interval = 0 dcd_reg->USBCMD |= TU_BIT(0); // connect @@ -423,9 +428,7 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc) p_qhd->max_package_size = p_endpoint_desc->wMaxPacketSize.size; p_qhd->qtd_overlay.next = QTD_NEXT_INVALID; - #if defined(__CORTEX_M) && __CORTEX_M == 7 && __DCACHE_PRESENT == 1 - SCB_CleanInvalidateDCache_by_Addr((uint32_t*) &_dcd_data, sizeof(dcd_data_t)); - #endif + CleanInvalidateDCache_by_Addr((uint32_t*) &_dcd_data, sizeof(dcd_data_t)); // Enable EP Control DCD_REGS[rhport]->ENDPTCTRL[epnum] |= ((p_endpoint_desc->bmAttributes.xfer << 2) | ENDPTCTRL_ENABLE | ENDPTCTRL_TOGGLE_RESET) << (dir ? 16 : 0); @@ -451,17 +454,14 @@ bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t t // Force the CPU to flush the buffer. We increase the size by 32 because the call aligns the // address to 32-byte boundaries. - #if defined(__CORTEX_M) && __CORTEX_M == 7 && __DCACHE_PRESENT == 1 - SCB_CleanInvalidateDCache_by_Addr((uint32_t*) buffer, total_bytes + 31); - #endif + CleanInvalidateDCache_by_Addr((uint32_t*) buffer, total_bytes + 31); //------------- Prepare qtd -------------// qtd_init(p_qtd, buffer, total_bytes); p_qtd->int_on_complete = true; p_qhd->qtd_overlay.next = (uint32_t) p_qtd; // link qtd to qhd - #if defined(__CORTEX_M) && __CORTEX_M == 7 && __DCACHE_PRESENT == 1 - SCB_CleanInvalidateDCache_by_Addr((uint32_t*) &_dcd_data, sizeof(dcd_data_t)); - #endif + + CleanInvalidateDCache_by_Addr((uint32_t*) &_dcd_data, sizeof(dcd_data_t)); // start transfer DCD_REGS[rhport]->ENDPTPRIME = TU_BIT( ep_idx2bit(ep_idx) ) ; @@ -502,9 +502,7 @@ void dcd_isr(uint8_t rhport) } // Make sure we read the latest version of _dcd_data. - #if defined(__CORTEX_M) && __CORTEX_M == 7 && __DCACHE_PRESENT == 1 - SCB_CleanInvalidateDCache_by_Addr((uint32_t*) &_dcd_data, sizeof(dcd_data_t)); - #endif + CleanInvalidateDCache_by_Addr((uint32_t*) &_dcd_data, sizeof(dcd_data_t)); // TODO disconnection does not generate interrupt !!!!!! // if (int_status & INTR_PORT_CHANGE) From e2f60a5134890ab9fdeea0e1794c157f38c25918 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 17 Jan 2020 17:09:23 +0700 Subject: [PATCH 219/267] rt10xx: correct max endpoint count is 8 --- .../nxp/transdimension/dcd_transdimension.c | 106 +++++++++++------- 1 file changed, 63 insertions(+), 43 deletions(-) diff --git a/src/portable/nxp/transdimension/dcd_transdimension.c b/src/portable/nxp/transdimension/dcd_transdimension.c index a9823a26..d400a30e 100644 --- a/src/portable/nxp/transdimension/dcd_transdimension.c +++ b/src/portable/nxp/transdimension/dcd_transdimension.c @@ -38,23 +38,15 @@ #if CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX #include "fsl_device_registers.h" - - // RT1010 and RT1020 only has 1 USB controller - #if FSL_FEATURE_SOC_USBHS_COUNT == 1 - #define DCD_REGS_BASE { (dcd_registers_t*) USB_BASE } - IRQn_Type DCD_IRQn[] = { USB_OTG1_IRQn }; - - // RT1050, RT1060 has 2 USB controllers - #else - #define DCD_REGS_BASE { (dcd_registers_t*) USB1_BASE, (dcd_registers_t*) USB2_BASE } - IRQn_Type DCD_IRQn[] = { USB_OTG1_IRQn, USB_OTG2_IRQn }; - #endif - #else // LPCOpen for 18xx & 43xx #include "chip.h" - #define DCD_REGS_BASE { (dcd_registers_t*) LPC_USB0_BASE, (dcd_registers_t*) LPC_USB1_BASE } - IRQn_Type DCD_IRQn[] = { USB0_IRQn, USB1_IRQn }; +#endif + +#if defined(__CORTEX_M) && __CORTEX_M == 7 && __DCACHE_PRESENT == 1 + #define CleanInvalidateDCache_by_Addr SCB_CleanInvalidateDCache_by_Addr +#else + #define CleanInvalidateDCache_by_Addr(_addr, _dsize) #endif //--------------------------------------------------------------------+ @@ -232,7 +224,7 @@ typedef struct /// thus there are 16 bytes padding free that we can make use of. //--------------------------------------------------------------------+ uint8_t reserved[16]; -} dcd_qhd_t; +} dcd_qhd_t; TU_VERIFY_STATIC( sizeof(dcd_qhd_t) == 64, "size is not correct"); @@ -240,23 +232,48 @@ TU_VERIFY_STATIC( sizeof(dcd_qhd_t) == 64, "size is not correct"); // Variables //--------------------------------------------------------------------+ -#define QHD_MAX 12 +typedef struct +{ + dcd_registers_t* regs; // registers + const IRQn_Type irqnum; // IRQ number + const uint8_t ep_count; // Max bi-directional Endpoints +}dcd_controller_t; + +#if CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX + // Each endpoint with direction (IN/OUT) occupies a queue head + // Therefore QHD_MAX is 2 x max endpoint count + #define QHD_MAX (8*2) + + dcd_controller_t _dcd_controller[] = + { + // RT1010 and RT1020 only has 1 USB controller + #if FSL_FEATURE_SOC_USBHS_COUNT == 1 + { .regs = (dcd_registers_t*) USB_BASE , .irqnum = USB_OTG1_IRQn, .ep_count = 8 } + #else + { .regs = (dcd_registers_t*) USB1_BASE, .irqnum = USB_OTG1_IRQn, .ep_count = 8 }, + { .regs = (dcd_registers_t*) USB2_BASE, .irqnum = USB_OTG2_IRQn, .ep_count = 8 } + #endif + }; + +#else + #define QHD_MAX (6*2) + + dcd_controller_t _dcd_controller[] = + { + { .regs = (dcd_registers_t*) LPC_USB0_BASE, .irqnum = USB0_IRQn, .ep_count = 6 }, + { .regs = (dcd_registers_t*) LPC_USB1_BASE, .irqnum = USB1_IRQn, .ep_count = 4 } + }; +#endif + #define QTD_NEXT_INVALID 0x01 typedef struct { // Must be at 2K alignment dcd_qhd_t qhd[QHD_MAX] TU_ATTR_ALIGNED(64); - dcd_qtd_t qtd[QHD_MAX] TU_ATTR_ALIGNED(32); + dcd_qtd_t qtd[QHD_MAX] TU_ATTR_ALIGNED(32); // for portability, TinyUSB only queue 1 TD for each Qhd }dcd_data_t; static dcd_data_t _dcd_data CFG_TUSB_MEM_SECTION TU_ATTR_ALIGNED(2048); -static dcd_registers_t* DCD_REGS[] = DCD_REGS_BASE; - -#if defined(__CORTEX_M) && __CORTEX_M == 7 && __DCACHE_PRESENT == 1 - #define CleanInvalidateDCache_by_Addr SCB_CleanInvalidateDCache_by_Addr -#else - #define CleanInvalidateDCache_by_Addr(_addr, _dsize) -#endif //--------------------------------------------------------------------+ // CONTROLLER API @@ -265,16 +282,14 @@ static dcd_registers_t* DCD_REGS[] = DCD_REGS_BASE; /// follows LPC43xx User Manual 23.10.3 static void bus_reset(uint8_t rhport) { - dcd_registers_t* dcd_reg = DCD_REGS[rhport]; + dcd_registers_t* dcd_reg = _dcd_controller[rhport].regs; // The reset value for all endpoint types is the control endpoint. If one endpoint // direction is enabled and the paired endpoint of opposite direction is disabled, then the - // endpoint type of the unused direction must bechanged from the control type to any other - // type (e.g. bulk). Leaving an unconfigured endpoint control will cause undefined behavior + // endpoint type of the unused direction must be changed from the control type to any other + // type (e.g. bulk). Leaving an un-configured endpoint control will cause undefined behavior // for the data PID tracking on the active endpoint. - - // USB0 has 5 but USB1 only has 3 non-control endpoints - for( int i=1; i < (rhport ? 6 : 4); i++) + for( int i=1; i < _dcd_controller[rhport].ep_count; i++) { dcd_reg->ENDPTCTRL[i] = (TUSB_XFER_BULK << 2) | (TUSB_XFER_BULK << 18); } @@ -307,7 +322,7 @@ void dcd_init(uint8_t rhport) { tu_memclr(&_dcd_data, sizeof(dcd_data_t)); - dcd_registers_t* const dcd_reg = DCD_REGS[rhport]; + dcd_registers_t* const dcd_reg = _dcd_controller[rhport].regs; // Reset controller dcd_reg->USBCMD |= USBCMD_RESET; @@ -332,12 +347,12 @@ void dcd_init(uint8_t rhport) void dcd_int_enable(uint8_t rhport) { - NVIC_EnableIRQ(DCD_IRQn[rhport]); + NVIC_EnableIRQ(_dcd_controller[rhport].irqnum); } void dcd_int_disable(uint8_t rhport) { - NVIC_DisableIRQ(DCD_IRQn[rhport]); + NVIC_DisableIRQ(_dcd_controller[rhport].irqnum); } void dcd_set_address(uint8_t rhport, uint8_t dev_addr) @@ -345,7 +360,8 @@ void dcd_set_address(uint8_t rhport, uint8_t dev_addr) // Response with status first before changing device address dcd_edpt_xfer(rhport, tu_edpt_addr(0, TUSB_DIR_IN), NULL, 0); - DCD_REGS[rhport]->DEVICEADDR = (dev_addr << 25) | TU_BIT(24); + dcd_registers_t* dcd_reg = _dcd_controller[rhport].regs; + dcd_reg->DEVICEADDR = (dev_addr << 25) | TU_BIT(24); } void dcd_set_config(uint8_t rhport, uint8_t config_num) @@ -395,7 +411,8 @@ void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr) uint8_t const epnum = tu_edpt_number(ep_addr); uint8_t const dir = tu_edpt_dir(ep_addr); - DCD_REGS[rhport]->ENDPTCTRL[epnum] |= ENDPTCTRL_STALL << (dir ? 16 : 0); + dcd_registers_t* dcd_reg = _dcd_controller[rhport].regs; + dcd_reg->ENDPTCTRL[epnum] |= ENDPTCTRL_STALL << (dir ? 16 : 0); } void dcd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr) @@ -404,8 +421,9 @@ void dcd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr) uint8_t const dir = tu_edpt_dir(ep_addr); // data toggle also need to be reset - DCD_REGS[rhport]->ENDPTCTRL[epnum] |= ENDPTCTRL_TOGGLE_RESET << ( dir ? 16 : 0 ); - DCD_REGS[rhport]->ENDPTCTRL[epnum] &= ~(ENDPTCTRL_STALL << ( dir ? 16 : 0)); + dcd_registers_t* dcd_reg = _dcd_controller[rhport].regs; + dcd_reg->ENDPTCTRL[epnum] |= ENDPTCTRL_TOGGLE_RESET << ( dir ? 16 : 0 ); + dcd_reg->ENDPTCTRL[epnum] &= ~(ENDPTCTRL_STALL << ( dir ? 16 : 0)); } bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc) @@ -417,8 +435,8 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc) uint8_t const dir = tu_edpt_dir(p_endpoint_desc->bEndpointAddress); uint8_t const ep_idx = 2*epnum + dir; - // USB0 has 5, USB1 has 3 non-control endpoints - TU_ASSERT( epnum <= (rhport ? 3 : 5) ); + // Must not exceed max endpoint number + TU_ASSERT( epnum < _dcd_controller[rhport].ep_count ); //------------- Prepare Queue Head -------------// dcd_qhd_t * p_qhd = &_dcd_data.qhd[ep_idx]; @@ -431,13 +449,15 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc) CleanInvalidateDCache_by_Addr((uint32_t*) &_dcd_data, sizeof(dcd_data_t)); // Enable EP Control - DCD_REGS[rhport]->ENDPTCTRL[epnum] |= ((p_endpoint_desc->bmAttributes.xfer << 2) | ENDPTCTRL_ENABLE | ENDPTCTRL_TOGGLE_RESET) << (dir ? 16 : 0); + dcd_registers_t* dcd_reg = _dcd_controller[rhport].regs; + dcd_reg->ENDPTCTRL[epnum] |= ((p_endpoint_desc->bmAttributes.xfer << 2) | ENDPTCTRL_ENABLE | ENDPTCTRL_TOGGLE_RESET) << (dir ? 16 : 0); return true; } bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t total_bytes) { + dcd_registers_t* dcd_reg = _dcd_controller[rhport].regs; uint8_t const epnum = tu_edpt_number(ep_addr); uint8_t const dir = tu_edpt_dir(ep_addr); uint8_t const ep_idx = 2*epnum + dir; @@ -446,7 +466,7 @@ bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t t { // follows UM 24.10.8.1.1 Setup packet handling using setup lockout mechanism // wait until ENDPTSETUPSTAT before priming data/status in response TODO add time out - while(DCD_REGS[rhport]->ENDPTSETUPSTAT & TU_BIT(0)) {} + while(dcd_reg->ENDPTSETUPSTAT & TU_BIT(0)) {} } dcd_qhd_t * p_qhd = &_dcd_data.qhd[ep_idx]; @@ -464,7 +484,7 @@ bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t t CleanInvalidateDCache_by_Addr((uint32_t*) &_dcd_data, sizeof(dcd_data_t)); // start transfer - DCD_REGS[rhport]->ENDPTPRIME = TU_BIT( ep_idx2bit(ep_idx) ) ; + dcd_reg->ENDPTPRIME = TU_BIT( ep_idx2bit(ep_idx) ) ; return true; } @@ -474,7 +494,7 @@ bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t t //--------------------------------------------------------------------+ void dcd_isr(uint8_t rhport) { - dcd_registers_t* const dcd_reg = DCD_REGS[rhport]; + dcd_registers_t* const dcd_reg = _dcd_controller[rhport].regs; uint32_t const int_enable = dcd_reg->USBINTR; uint32_t const int_status = dcd_reg->USBSTS & int_enable; From cd8eb2a06bfb14c25788b56f1821784cb9c5535c Mon Sep 17 00:00:00 2001 From: Peter Lawrence <12226419+majbthrd@users.noreply.github.com> Date: Sat, 25 Jan 2020 13:10:32 -0600 Subject: [PATCH 220/267] added support for Nuvoton NUC120 --- hw/bsp/nutiny_sdk_nuc120/board.mk | 56 +++ hw/bsp/nutiny_sdk_nuc120/nuc120_flash.ld | 195 +++++++++ hw/bsp/nutiny_sdk_nuc120/nutiny_sdk_nuc120.c | 122 ++++++ hw/mcu/nuvoton | 2 +- src/portable/nuvoton/nuc120/dcd_nuc120.c | 433 +++++++++++++++++++ src/tusb_option.h | 1 + 6 files changed, 808 insertions(+), 1 deletion(-) create mode 100644 hw/bsp/nutiny_sdk_nuc120/board.mk create mode 100644 hw/bsp/nutiny_sdk_nuc120/nuc120_flash.ld create mode 100644 hw/bsp/nutiny_sdk_nuc120/nutiny_sdk_nuc120.c create mode 100644 src/portable/nuvoton/nuc120/dcd_nuc120.c diff --git a/hw/bsp/nutiny_sdk_nuc120/board.mk b/hw/bsp/nutiny_sdk_nuc120/board.mk new file mode 100644 index 00000000..f2ee09f1 --- /dev/null +++ b/hw/bsp/nutiny_sdk_nuc120/board.mk @@ -0,0 +1,56 @@ +CFLAGS += \ + -flto \ + -mthumb \ + -mabi=aapcs-linux \ + -mcpu=cortex-m0 \ + -DCFG_TUSB_MCU=OPT_MCU_NUC120 + +# All source paths should be relative to the top level. +LD_FILE = hw/bsp/nutiny_sdk_nuc120/nuc120_flash.ld + +SRC_C += \ + hw/mcu/nuvoton/nuc100_120/Device/Nuvoton/NUC100Series/Source/system_NUC100Series.c \ + hw/mcu/nuvoton/nuc100_120/StdDriver/src/acmp.c \ + hw/mcu/nuvoton/nuc100_120/StdDriver/src/adc.c \ + hw/mcu/nuvoton/nuc100_120/StdDriver/src/clk.c \ + hw/mcu/nuvoton/nuc100_120/StdDriver/src/crc.c \ + hw/mcu/nuvoton/nuc100_120/StdDriver/src/fmc.c \ + hw/mcu/nuvoton/nuc100_120/StdDriver/src/gpio.c \ + hw/mcu/nuvoton/nuc100_120/StdDriver/src/i2c.c \ + hw/mcu/nuvoton/nuc100_120/StdDriver/src/i2s.c \ + hw/mcu/nuvoton/nuc100_120/StdDriver/src/pdma.c \ + hw/mcu/nuvoton/nuc100_120/StdDriver/src/ps2.c \ + hw/mcu/nuvoton/nuc100_120/StdDriver/src/pwm.c \ + hw/mcu/nuvoton/nuc100_120/StdDriver/src/rtc.c \ + hw/mcu/nuvoton/nuc100_120/StdDriver/src/sc.c \ + hw/mcu/nuvoton/nuc100_120/StdDriver/src/spi.c \ + hw/mcu/nuvoton/nuc100_120/StdDriver/src/sys.c \ + hw/mcu/nuvoton/nuc100_120/StdDriver/src/timer.c \ + hw/mcu/nuvoton/nuc100_120/StdDriver/src/uart.c \ + hw/mcu/nuvoton/nuc100_120/StdDriver/src/usbd.c \ + hw/mcu/nuvoton/nuc100_120/StdDriver/src/wdt.c \ + hw/mcu/nuvoton/nuc100_120/StdDriver/src/wwdt.c + +SRC_S += \ + hw/mcu/nuvoton/nuc100_120/Device/Nuvoton/NUC100Series/Source/GCC/startup_NUC100Series.S + +INC += \ + $(TOP)/hw/mcu/nuvoton/nuc100_120/Device/Nuvoton/NUC100Series/Include \ + $(TOP)/hw/mcu/nuvoton/nuc100_120/StdDriver/inc \ + $(TOP)/hw/mcu/nuvoton/nuc100_120/CMSIS/Include + +# For TinyUSB port source +VENDOR = nuvoton +CHIP_FAMILY = nuc120 + +# For freeRTOS port source +FREERTOS_PORT = ARM_CM0 + +# For flash-jlink target +JLINK_DEVICE = NUC120LE3 +JLINK_IF = swd + +# Flash using Nuvoton's openocd fork at https://github.com/OpenNuvoton/OpenOCD-Nuvoton +# Please compile and install it from github source +flash: $(BUILD)/$(BOARD)-firmware.elf + openocd -f interface/nulink.cfg -f target/numicroM0.cfg -c "program $< reset exit" diff --git a/hw/bsp/nutiny_sdk_nuc120/nuc120_flash.ld b/hw/bsp/nutiny_sdk_nuc120/nuc120_flash.ld new file mode 100644 index 00000000..cab12c8b --- /dev/null +++ b/hw/bsp/nutiny_sdk_nuc120/nuc120_flash.ld @@ -0,0 +1,195 @@ +/* Linker script to configure memory regions. */ +MEMORY +{ + FLASH (rx) : ORIGIN = 0x00000000, LENGTH = 0x20000 /* 128k */ + RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 0x4000 /* 16k */ +} + +/* Library configurations */ +GROUP(libgcc.a libc.a libm.a libnosys.a) + +/* 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 + * __copy_table_start__ + * __copy_table_end__ + * __zero_table_start__ + * __zero_table_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 + * __Vectors_End + * __Vectors_Size + */ +ENTRY(Reset_Handler) + +SECTIONS +{ + .text : + { + KEEP(*(.vectors)) + __Vectors_End = .; + __Vectors_Size = __Vectors_End - __Vectors; + __end__ = .; + + *(.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 = .; + + /* To copy multiple ROM to RAM sections, + * uncomment .copy.table section and, + * define __STARTUP_COPY_MULTIPLE in startup_ARMCMx.S */ + /* + .copy.table : + { + . = ALIGN(4); + __copy_table_start__ = .; + LONG (__etext) + LONG (__data_start__) + LONG (__data_end__ - __data_start__) + LONG (__etext2) + LONG (__data2_start__) + LONG (__data2_end__ - __data2_start__) + __copy_table_end__ = .; + } > FLASH + */ + + /* To clear multiple BSS sections, + * uncomment .zero.table section and, + * define __STARTUP_CLEAR_BSS_MULTIPLE in startup_ARMCMx.S */ + /* + .zero.table : + { + . = ALIGN(4); + __zero_table_start__ = .; + LONG (__bss_start__) + LONG (__bss_end__ - __bss_start__) + LONG (__bss2_start__) + LONG (__bss2_end__ - __bss2_start__) + __zero_table_end__ = .; + } > FLASH + */ + + __etext = .; + + .data : AT (__etext) + { + __data_start__ = .; + *(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__ = .; + + } > RAM + + .bss : + { + . = ALIGN(4); + __bss_start__ = .; + *(.bss*) + *(COMMON) + . = ALIGN(4); + __bss_end__ = .; + } > RAM + + .heap (COPY): + { + __HeapBase = .; + __end__ = .; + end = __end__; + KEEP(*(.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): + { + KEEP(*(.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); + __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/hw/bsp/nutiny_sdk_nuc120/nutiny_sdk_nuc120.c b/hw/bsp/nutiny_sdk_nuc120/nutiny_sdk_nuc120.c new file mode 100644 index 00000000..0650a4e3 --- /dev/null +++ b/hw/bsp/nutiny_sdk_nuc120/nutiny_sdk_nuc120.c @@ -0,0 +1,122 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#include "bsp/board.h" +#include "NUC100Series.h" +#include "clk.h" +#include "sys.h" + +#define LED_PORT PB +#define LED_PIN 0 +#define LED_PIN_IO PB0 +#define LED_STATE_ON 0 + +void board_init(void) +{ + SYS_UnlockReg(); + + /* Enable Internal RC 22.1184 MHz clock */ + CLK_EnableXtalRC(CLK_PWRCON_OSC22M_EN_Msk); + + /* Waiting for Internal RC clock ready */ + CLK_WaitClockReady(CLK_CLKSTATUS_OSC22M_STB_Msk); + + /* Switch HCLK clock source to Internal RC and HCLK source divide 1 */ + CLK_SetHCLK(CLK_CLKSEL0_HCLK_S_HIRC, CLK_CLKDIV_HCLK(1)); + + /* Enable external XTAL 12 MHz clock */ + CLK_EnableXtalRC(CLK_PWRCON_XTL12M_EN_Msk); + + /* Waiting for external XTAL clock ready */ + CLK_WaitClockReady(CLK_CLKSTATUS_XTL12M_STB_Msk); + + /* Set core clock */ + CLK_SetCoreClock(48000000); + + /* Enable module clock */ + CLK_EnableModuleClock(USBD_MODULE); + + /* Select module clock source */ + CLK_SetModuleClock(USBD_MODULE, 0, CLK_CLKDIV_USB(1)); + + SYS_LockReg(); + +#if CFG_TUSB_OS == OPT_OS_NONE + // 1ms tick timer + SysTick_Config(48000000 / 1000); +#endif + + GPIO_SetMode(LED_PORT, 1UL << LED_PIN, GPIO_PMD_OUTPUT); +} + +#if CFG_TUSB_OS == OPT_OS_NONE +volatile uint32_t system_ticks = 0; +void SysTick_Handler (void) +{ + system_ticks++; +} + +uint32_t board_millis(void) +{ + return system_ticks; +} +#endif + +//--------------------------------------------------------------------+ +// Board porting API +//--------------------------------------------------------------------+ + +void board_led_write(bool state) +{ +#if 0 + /* this would be the simplest solution... *IF* the part supported the pin data interface */ + LED_PIN_IO = (state) ? LED_STATE_ON : (1-LED_STATE_ON); +#else + /* if the part's *PDIO pin data registers don't work, a more elaborate approach is needed */ + uint32_t irq_state = __get_PRIMASK(); + __disable_irq(); + uint32_t current = LED_PORT->DOUT & ~(1UL << LED_PIN); + LED_PORT->DOUT = current | (((state) ? LED_STATE_ON : (1UL-LED_STATE_ON)) << LED_PIN); + __set_PRIMASK(irq_state); +#endif +} + +uint32_t board_button_read(void) +{ + return 0; +} + +int board_uart_read(uint8_t* buf, int len) +{ + (void) buf; (void) len; + return 0; +} + +int board_uart_write(void const * buf, int len) +{ + (void) buf; (void) len; + return 0; +} diff --git a/hw/mcu/nuvoton b/hw/mcu/nuvoton index dc96fff7..797dc6cd 160000 --- a/hw/mcu/nuvoton +++ b/hw/mcu/nuvoton @@ -1 +1 @@ -Subproject commit dc96fff794d14818c93ea1d4d760d51a014d70c5 +Subproject commit 797dc6cd55c84aa6c23c4690da2f3900339a6e24 diff --git a/src/portable/nuvoton/nuc120/dcd_nuc120.c b/src/portable/nuvoton/nuc120/dcd_nuc120.c new file mode 100644 index 00000000..4e1db24a --- /dev/null +++ b/src/portable/nuvoton/nuc120/dcd_nuc120.c @@ -0,0 +1,433 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019-2020 Peter Lawrence + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +/* + Theory of operation: + + The NUC100/NUC120 USBD peripheral has six "EP"s, but each is simplex, + so two collectively (peripheral nomenclature of "EP0" and "EP1") are needed to + implement USB EP0. PERIPH_EP0 and PERIPH_EP1 are used by this driver for + EP0_IN and EP0_OUT respectively. This leaves up to four for user usage. +*/ + +#include "tusb_option.h" + +#if TUSB_OPT_DEVICE_ENABLED && (CFG_TUSB_MCU == OPT_MCU_NUC120) + +#include "device/dcd.h" +#include "NUC100Series.h" + +/* allocation of USBD RAM for Setup, EP0_IN, and and EP_OUT */ +#define PERIPH_SETUP_BUF_BASE 0 +#define PERIPH_SETUP_BUF_LEN 8 +#define PERIPH_EP0_BUF_BASE (PERIPH_SETUP_BUF_BASE + PERIPH_SETUP_BUF_LEN) +#define PERIPH_EP0_BUF_LEN CFG_TUD_ENDPOINT0_SIZE +#define PERIPH_EP1_BUF_BASE (PERIPH_EP0_BUF_BASE + PERIPH_EP0_BUF_LEN) +#define PERIPH_EP1_BUF_LEN CFG_TUD_ENDPOINT0_SIZE +#define PERIPH_EP2_BUF_BASE (PERIPH_EP1_BUF_BASE + PERIPH_EP1_BUF_LEN) + +/* rather important info unfortunately not provided by device include files: how much there is */ +#define USBD_BUF_SIZE 512 + +enum ep_enum +{ + PERIPH_EP0 = 0, + PERIPH_EP1 = 1, + PERIPH_EP2 = 2, + PERIPH_EP3 = 3, + PERIPH_EP4 = 4, + PERIPH_EP5 = 5, + PERIPH_MAX_EP, +}; + +/* set by dcd_set_address() */ +static volatile uint8_t assigned_address; + +/* reset by dcd_init(), this is used by dcd_edpt_open() to assign USBD peripheral buffer addresses */ +static uint32_t bufseg_addr; + +/* used by dcd_edpt_xfer() and the ISR to reset the data sync (DATA0/DATA1) in an EP0_IN transfer */ +static bool active_ep0_xfer; + +/* RAM table needed to track ongoing transfers performed by dcd_edpt_xfer(), dcd_in_xfer(), and the ISR */ +static struct xfer_ctl_t +{ + uint8_t *data_ptr; /* data_ptr tracks where to next copy data to (for OUT) or from (for IN) */ + union { + uint16_t in_remaining_bytes; /* for IN endpoints, we track how many bytes are left to transfer */ + uint16_t out_bytes_so_far; /* but for OUT endpoints, we track how many bytes we've transferred so far */ + }; + uint16_t max_packet_size; /* needed since device driver only finds out this at runtime */ + uint16_t total_bytes; /* quantity needed to pass as argument to dcd_event_xfer_complete() (for IN endpoints) */ +} xfer_table[PERIPH_MAX_EP]; + +/* + local helper functions +*/ + +static void usb_attach(void) +{ + USBD->DRVSE0 &= ~USBD_DRVSE0_DRVSE0_Msk; +} + +static void usb_detach(void) +{ + USBD->DRVSE0 |= USBD_DRVSE0_DRVSE0_Msk; +} + +static void usb_control_send_zlp(void) +{ + USBD->EP[PERIPH_EP0].CFG |= USBD_CFG_DSQ_SYNC_Msk; + USBD->EP[PERIPH_EP0].MXPLD = 0; +} + +/* reconstruct ep_addr from particular USB Configuration Register */ +static uint8_t decode_ep_addr(USBD_EP_T *ep) +{ + uint8_t ep_addr = ep->CFG & USBD_CFG_EP_NUM_Msk; + if ( USBD_CFG_EPMODE_IN == (ep->CFG & USBD_CFG_STATE_Msk) ) + ep_addr |= TUSB_DIR_IN_MASK; + return ep_addr; +} + +/* map 8-bit ep_addr into peripheral endpoint index (PERIPH_EP0...) */ +static USBD_EP_T *ep_entry(uint8_t ep_addr, bool add) +{ + USBD_EP_T *ep; + enum ep_enum ep_index; + + for (ep_index = PERIPH_EP0, ep = USBD->EP; ep_index < PERIPH_MAX_EP; ep_index++, ep++) + { + if (add) + { + /* take first peripheral endpoint that is unused */ + if (0 == (ep->CFG & USBD_CFG_STATE_Msk)) return ep; + } + else + { + /* find a peripheral endpoint that matches ep_addr */ + uint8_t candidate_ep_addr = decode_ep_addr(ep); + if (candidate_ep_addr == ep_addr) return ep; + } + } + + return NULL; +} + +/* perform an IN endpoint transfer; this is called by dcd_edpt_xfer() and the ISR */ +static void dcd_in_xfer(struct xfer_ctl_t *xfer, USBD_EP_T *ep) +{ + uint16_t bytes_now = tu_min16(xfer->in_remaining_bytes, xfer->max_packet_size); + + memcpy((uint8_t *)(USBD_BUF_BASE + ep->BUFSEG), xfer->data_ptr, bytes_now); + ep->MXPLD = bytes_now; +} + +/* called by dcd_init() as well as by the ISR during a USB bus reset */ +static void bus_reset(void) +{ + USBD->STBUFSEG = PERIPH_SETUP_BUF_BASE; + + for (enum ep_enum ep_index = PERIPH_EP0; ep_index < PERIPH_MAX_EP; ep_index++) + { + USBD->EP[ep_index].CFG = 0; + USBD->EP[ep_index].CFGP = 0; + } + + /* allocate the default EP0 endpoints */ + + USBD->EP[PERIPH_EP0].CFG = USBD_CFG_CSTALL_Msk | USBD_CFG_EPMODE_IN; + USBD->EP[PERIPH_EP0].BUFSEG = PERIPH_EP0_BUF_BASE; + xfer_table[PERIPH_EP0].max_packet_size = PERIPH_EP0_BUF_LEN; + + USBD->EP[PERIPH_EP1].CFG = USBD_CFG_CSTALL_Msk | USBD_CFG_EPMODE_OUT; + USBD->EP[PERIPH_EP1].BUFSEG = PERIPH_EP1_BUF_BASE; + xfer_table[PERIPH_EP1].max_packet_size = PERIPH_EP1_BUF_LEN; + + /* USB RAM beyond what we've allocated above is available to the user */ + bufseg_addr = PERIPH_EP2_BUF_BASE; + + /* Reset USB device address */ + USBD->FADDR = 0; + + /* reset EP0_IN flag */ + active_ep0_xfer = false; +} + +/* centralized location for USBD interrupt enable bit mask */ +static const uint32_t enabled_irqs = USBD_INTSTS_FLDET_STS_Msk | USBD_INTSTS_BUS_STS_Msk | USBD_INTSTS_SETUP_Msk | USBD_INTSTS_USB_STS_Msk; + +/* + NUC100/NUC120 TinyUSB API driver implementation +*/ + +void dcd_init(uint8_t rhport) +{ + (void) rhport; + + USBD->ATTR = 0x7D0; + + usb_detach(); + + bus_reset(); + + usb_attach(); + + USBD->INTSTS = enabled_irqs; + USBD->INTEN = enabled_irqs; +} + +void dcd_int_enable(uint8_t rhport) +{ + (void) rhport; + NVIC_EnableIRQ(USBD_IRQn); +} + +void dcd_int_disable(uint8_t rhport) +{ + (void) rhport; + NVIC_DisableIRQ(USBD_IRQn); +} + +void dcd_set_address(uint8_t rhport, uint8_t dev_addr) +{ + (void) rhport; + usb_control_send_zlp(); /* SET_ADDRESS is the one exception where TinyUSB doesn't use dcd_edpt_xfer() to generate a ZLP */ + assigned_address = dev_addr; +} + +void dcd_set_config(uint8_t rhport, uint8_t config_num) +{ + (void) rhport; + (void) config_num; +} + +void dcd_remote_wakeup(uint8_t rhport) +{ + (void) rhport; + USBD->ATTR = USBD_ATTR_RWAKEUP_Msk; +} + +bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc) +{ + (void) rhport; + + USBD_EP_T *ep = ep_entry(p_endpoint_desc->bEndpointAddress, true); + TU_ASSERT(ep); + + /* mine the data for the information we need */ + int const dir = tu_edpt_dir(p_endpoint_desc->bEndpointAddress); + int const size = p_endpoint_desc->wMaxPacketSize.size; + tusb_xfer_type_t const type = p_endpoint_desc->bmAttributes.xfer; + struct xfer_ctl_t *xfer = &xfer_table[ep - USBD->EP]; + + /* allocate buffer from USB RAM */ + ep->BUFSEG = bufseg_addr; + bufseg_addr += size; + TU_ASSERT(bufseg_addr <= USBD_BUF_SIZE); + + /* construct USB Configuration Register value and then write it */ + uint32_t cfg = tu_edpt_number(p_endpoint_desc->bEndpointAddress); + cfg |= (TUSB_DIR_IN == dir) ? USBD_CFG_EPMODE_IN : USBD_CFG_EPMODE_OUT; + if (TUSB_XFER_ISOCHRONOUS == type) + cfg |= USBD_CFG_TYPE_ISO; + ep->CFG = cfg; + + /* make a note of the endpoint size */ + xfer->max_packet_size = size; + + return true; +} + +bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t *buffer, uint16_t total_bytes) +{ + (void) rhport; + + /* mine the data for the information we need */ + tusb_dir_t dir = tu_edpt_dir(ep_addr); + USBD_EP_T *ep = ep_entry(ep_addr, false); + struct xfer_ctl_t *xfer = &xfer_table[ep - USBD->EP]; + + /* store away the information we'll needing now and later */ + xfer->data_ptr = buffer; + xfer->in_remaining_bytes = total_bytes; + xfer->total_bytes = total_bytes; + + /* for the first of one or more EP0_IN packets in a message, the first must be DATA1 */ + if ( (0x80 == ep_addr) && !active_ep0_xfer ) ep->CFG |= USBD_CFG_DSQ_SYNC_Msk; + + if (TUSB_DIR_IN == dir) + { + dcd_in_xfer(xfer, ep); + } + else + { + xfer->out_bytes_so_far = 0; + ep->MXPLD = xfer->max_packet_size; + } + + return true; +} + +void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + USBD_EP_T *ep = ep_entry(ep_addr, false); + ep->CFGP |= USBD_CFGP_SSTALL_Msk; +} + +void dcd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + USBD_EP_T *ep = ep_entry(ep_addr, false); + ep->CFG |= USBD_CFG_CSTALL_Msk; +} + +void USBD_IRQHandler(void) +{ + uint32_t status = USBD->INTSTS; + uint32_t state = USBD->ATTR & 0xf; + + if(status & USBD_INTSTS_FLDET_STS_Msk) + { + if(USBD->FLDET & USBD_FLDET_FLDET_Msk) + { + /* USB connect */ + USBD->ATTR |= USBD_ATTR_USB_EN_Msk | USBD_ATTR_PHY_EN_Msk; + } + else + { + /* USB disconnect */ + USBD->ATTR &= ~USBD_ATTR_USB_EN_Msk; + } + } + + if(status & USBD_INTSTS_BUS_STS_Msk) + { + if(state & USBD_STATE_USBRST) + { + /* USB bus reset */ + USBD->ATTR |= USBD_ATTR_USB_EN_Msk | USBD_ATTR_PHY_EN_Msk; + + bus_reset(); + + dcd_event_bus_signal(0, DCD_EVENT_BUS_RESET, true); + } + + if(state & USBD_STATE_SUSPEND) + { + /* Enable USB but disable PHY */ + USBD->ATTR &= ~USBD_ATTR_PHY_EN_Msk; + dcd_event_bus_signal(0, DCD_EVENT_SUSPEND, true); + } + + if(state & USBD_STATE_RESUME) + { + /* Enable USB and enable PHY */ + USBD->ATTR |= USBD_ATTR_USB_EN_Msk | USBD_ATTR_PHY_EN_Msk; + dcd_event_bus_signal(0, DCD_EVENT_RESUME, true); + } + } + + if(status & USBD_INTSTS_SETUP_Msk) + { + /* clear the data ready flag of control endpoints */ + USBD->EP[PERIPH_EP0].CFGP |= USBD_CFGP_CLRRDY_Msk; + USBD->EP[PERIPH_EP1].CFGP |= USBD_CFGP_CLRRDY_Msk; + + /* get SETUP packet from USB buffer */ + dcd_event_setup_received(0, (uint8_t *)USBD_BUF_BASE, true); + } + + if(status & USBD_INTSTS_USB_STS_Msk) + { + if (status & (1UL << USBD_INTSTS_EPEVT_Pos)) /* PERIPH_EP0 (EP0_IN) event: this is treated separately from the rest */ + { + /* given ACK from host has happened, we can now set the address (if not already done) */ + if((USBD->FADDR != assigned_address) && (USBD->FADDR == 0)) USBD->FADDR = assigned_address; + + uint16_t const available_bytes = USBD->EP[PERIPH_EP0].MXPLD; + + active_ep0_xfer = (available_bytes == xfer_table[PERIPH_EP0].max_packet_size); + + dcd_event_xfer_complete(0, 0x80, available_bytes, XFER_RESULT_SUCCESS, true); + } + + /* service PERIPH_EP1 through PERIPH_EP7 */ + enum ep_enum ep_index; + uint32_t mask; + struct xfer_ctl_t *xfer; + USBD_EP_T *ep; + for (ep_index = PERIPH_EP1, mask = (2UL << USBD_INTSTS_EPEVT_Pos), xfer = &xfer_table[PERIPH_EP1], ep = &USBD->EP[PERIPH_EP1]; ep_index < PERIPH_MAX_EP; ep_index++, mask <<= 1, xfer++, ep++) + { + if(status & mask) + { + USBD->INTSTS = mask; + + uint16_t const available_bytes = ep->MXPLD; + uint8_t const ep_addr = decode_ep_addr(ep); + bool const out_ep = !(ep_addr & TUSB_DIR_IN_MASK); + + if (out_ep) + { + /* copy the data from the PC to the previously provided buffer */ + memcpy(xfer->data_ptr, (uint8_t *)(USBD_BUF_BASE + ep->BUFSEG), available_bytes); + xfer->out_bytes_so_far += available_bytes; + xfer->data_ptr += available_bytes; + + /* when the transfer is finished, alert TinyUSB; otherwise, accept more data */ + if ( (xfer->total_bytes == xfer->out_bytes_so_far) || (available_bytes < xfer->max_packet_size) ) + dcd_event_xfer_complete(0, ep_addr, xfer->out_bytes_so_far, XFER_RESULT_SUCCESS, true); + else + ep->MXPLD = xfer->max_packet_size; + } + else + { + /* update the bookkeeping to reflect the data that has now been sent to the PC */ + xfer->in_remaining_bytes -= available_bytes; + xfer->data_ptr += available_bytes; + + /* if more data to send, send it; otherwise, alert TinyUSB that we've finished */ + if (xfer->in_remaining_bytes) + dcd_in_xfer(xfer, ep); + else + dcd_event_xfer_complete(0, ep_addr, xfer->total_bytes, XFER_RESULT_SUCCESS, true); + } + } + } + } + + /* acknowledge all interrupts */ + USBD->INTSTS = status & enabled_irqs; +} + +void dcd_isr(uint8_t rhport) +{ + (void) rhport; + USBD_IRQHandler(); +} + +#endif diff --git a/src/tusb_option.h b/src/tusb_option.h index d39dd104..46684ff7 100644 --- a/src/tusb_option.h +++ b/src/tusb_option.h @@ -79,6 +79,7 @@ #define OPT_MCU_NUC121 800 #define OPT_MCU_NUC126 801 +#define OPT_MCU_NUC120 802 /** @} */ From a8e66f011107582a210b95009083c7e40c205a48 Mon Sep 17 00:00:00 2001 From: Peter Lawrence <12226419+majbthrd@users.noreply.github.com> Date: Sat, 25 Jan 2020 13:32:31 -0600 Subject: [PATCH 221/267] added CFG_EXAMPLE_MSC_READONLY to NuTuny-SDK-NUC120 board.mk --- hw/bsp/nutiny_sdk_nuc120/board.mk | 1 + 1 file changed, 1 insertion(+) diff --git a/hw/bsp/nutiny_sdk_nuc120/board.mk b/hw/bsp/nutiny_sdk_nuc120/board.mk index f2ee09f1..95acdb5f 100644 --- a/hw/bsp/nutiny_sdk_nuc120/board.mk +++ b/hw/bsp/nutiny_sdk_nuc120/board.mk @@ -3,6 +3,7 @@ CFLAGS += \ -mthumb \ -mabi=aapcs-linux \ -mcpu=cortex-m0 \ + -DCFG_EXAMPLE_MSC_READONLY \ -DCFG_TUSB_MCU=OPT_MCU_NUC120 # All source paths should be relative to the top level. From b6b9fe42af1828c2ed8f794a930999ecb4da2902 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 7 Feb 2020 16:43:44 +0700 Subject: [PATCH 222/267] more log for debugging --- src/class/cdc/cdc_device.c | 11 ++++++++++- src/device/usbd_control.c | 14 +++++++++++--- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/src/class/cdc/cdc_device.c b/src/class/cdc/cdc_device.c index c0de0cad..f63418da 100644 --- a/src/class/cdc/cdc_device.c +++ b/src/class/cdc/cdc_device.c @@ -335,25 +335,34 @@ bool cdcd_control_request(uint8_t rhport, tusb_control_request_t const * request switch ( request->bRequest ) { case CDC_REQUEST_SET_LINE_CODING: + TU_LOG2(" Set Line Coding\n"); tud_control_xfer(rhport, request, &p_cdc->line_coding, sizeof(cdc_line_coding_t)); break; case CDC_REQUEST_GET_LINE_CODING: + TU_LOG2(" Get Line Coding\n"); tud_control_xfer(rhport, request, &p_cdc->line_coding, sizeof(cdc_line_coding_t)); break; case CDC_REQUEST_SET_CONTROL_LINE_STATE: + { // CDC PSTN v1.2 section 6.3.12 // Bit 0: Indicates if DTE is present or not. // This signal corresponds to V.24 signal 108/2 and RS-232 signal DTR (Data Terminal Ready) // Bit 1: Carrier control for half-duplex modems. // This signal corresponds to V.24 signal 105 and RS-232 signal RTS (Request to Send) + bool const dtr = tu_bit_test(request->wValue, 0); + bool const rts = tu_bit_test(request->wValue, 1); + p_cdc->line_state = (uint8_t) request->wValue; + TU_LOG2(" Set Control Line State: DTR = %d, RTS = %d\n", dtr, rts); + tud_control_status(rhport, request); // Invoke callback - if ( tud_cdc_line_state_cb) tud_cdc_line_state_cb(itf, tu_bit_test(request->wValue, 0), tu_bit_test(request->wValue, 1)); + if ( tud_cdc_line_state_cb) tud_cdc_line_state_cb(itf, dtr, rts); + } break; default: return false; // stall unsupported request diff --git a/src/device/usbd_control.c b/src/device/usbd_control.c index e6d1caf4..5a0ba412 100644 --- a/src/device/usbd_control.c +++ b/src/device/usbd_control.c @@ -51,8 +51,8 @@ typedef struct static usbd_control_xfer_t _ctrl_xfer; -CFG_TUSB_MEM_SECTION CFG_TUSB_MEM_ALIGN static uint8_t _usbd_ctrl_buf[CFG_TUD_ENDPOINT0_SIZE]; - +CFG_TUSB_MEM_SECTION CFG_TUSB_MEM_ALIGN +static uint8_t _usbd_ctrl_buf[CFG_TUD_ENDPOINT0_SIZE]; //--------------------------------------------------------------------+ // Application API @@ -60,8 +60,14 @@ CFG_TUSB_MEM_SECTION CFG_TUSB_MEM_ALIGN static uint8_t _usbd_ctrl_buf[CFG_TUD_EN static inline bool _status_stage_xact(uint8_t rhport, tusb_control_request_t const * request) { + // Opposite to endpoint in Data Phase + uint8_t const ep_addr = request->bmRequestType_bit.direction ? EDPT_CTRL_OUT : EDPT_CTRL_IN; + + TU_LOG2(" XFER Endpoint: 0x%02X, Bytes: %d\n", ep_addr, 0); + // status direction is reversed to one in the setup packet - return dcd_edpt_xfer(rhport, request->bmRequestType_bit.direction ? EDPT_CTRL_OUT : EDPT_CTRL_IN, NULL, 0); + // Note: Status must always be DATA1 + return dcd_edpt_xfer(rhport, ep_addr, NULL, 0); } // Status phase @@ -106,6 +112,8 @@ bool tud_control_xfer(uint8_t rhport, tusb_control_request_t const * request, vo // Data stage TU_ASSERT( _data_stage_xact(rhport) ); + + TU_LOG2(" XFER Endpoint: 0x%02X, Bytes: %d\n", request->bmRequestType_bit.direction ? EDPT_CTRL_IN : EDPT_CTRL_OUT, _ctrl_xfer.data_len); }else { // Status stage From 9ca6311ac49559570c5d7366344fb5887b09e953 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 7 Feb 2020 16:46:18 +0700 Subject: [PATCH 223/267] implement walkaround for incorrect DATA Toggle for status control. --- src/portable/microchip/samg/dcd_samg.c | 75 ++++++++++++++++++++++---- 1 file changed, 66 insertions(+), 9 deletions(-) diff --git a/src/portable/microchip/samg/dcd_samg.c b/src/portable/microchip/samg/dcd_samg.c index a93b26ca..835bbf01 100644 --- a/src/portable/microchip/samg/dcd_samg.c +++ b/src/portable/microchip/samg/dcd_samg.c @@ -51,6 +51,11 @@ typedef struct // Endpoint 0-5, each can only be either OUT or In xfer_desc_t _dcd_xfer[EP_COUNT]; +// Indicate that DATA Toggle for Control Status is incorrect, which must always be DATA1 by USB Specs. +// However SAMG DToggle is read-only, therefore we must duplicate the status phase ( D0 then D1 ) +// as walk-around to resolve this. The D0 status packet is likely to be discarded by USB Host safely. +volatile bool _walkaround_incorrect_dtoggle_control_status; + void xfer_epsize_set(xfer_desc_t* xfer, uint16_t epsize) { xfer->epsize = epsize; @@ -111,6 +116,7 @@ static void xact_ep_read(uint8_t epnum, uint8_t* buffer, uint16_t xact_len) // Set up endpoint 0, clear all other endpoints static void bus_reset(void) { + _walkaround_incorrect_dtoggle_control_status = false; tu_memclr(_dcd_xfer, sizeof(_dcd_xfer)); xfer_epsize_set(&_dcd_xfer[0], CFG_TUD_ENDPOINT0_SIZE); @@ -201,7 +207,8 @@ void dcd_edpt0_status_complete(uint8_t rhport, tusb_control_request_t const * re // Set new address & Function enable bit UDP->UDP_FADDR = UDP_FADDR_FEN_Msk | UDP_FADDR_FADD(dev_addr); - }else if (request->bRequest == TUSB_REQ_SET_CONFIGURATION) + } + else if (request->bRequest == TUSB_REQ_SET_CONFIGURATION) { // Configured State UDP->UDP_GLB_STAT |= UDP_GLB_STAT_CONFG_Msk; @@ -248,10 +255,47 @@ bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t xfer_desc_t* xfer = &_dcd_xfer[epnum]; xfer_begin(xfer, buffer, total_bytes); + // Control Endpoint direction and data toggle + if (epnum == 0) + { + // Transfer direction is opposite to one previously set on EP0 + // This transfer is Control Status Stage + if ( dir != tu_bit_test(UDP->UDP_CSR[epnum], UDP_CSR_DIR_Pos) ) + { + // Set/Clear DIR bit accordingly + if (dir) + { + UDP->UDP_CSR[epnum] |= UDP_CSR_DIR_Msk; + }else + { + UDP->UDP_CSR[epnum] &= ~UDP_CSR_DIR_Msk; + } + + // DATA Toggle is 0, USB Specs requires Status Stage must be DATA1 + // Since SAMG DToggle is read-only, we mark this and implement a walk-around + if ( !(UDP->UDP_CSR[epnum] & UDP_CSR_DTGLE_Msk) ) + { + TU_LOG2("Incorrect DATA TOGGLE, Control Status must be DATA1\n"); + + // DTGLE is read-only on SAMG, this statement has no effect + UDP->UDP_CSR[epnum] |= UDP_CSR_DTGLE_Msk; + + _walkaround_incorrect_dtoggle_control_status = true; + } + } + } + + if (dir == TUSB_DIR_IN) { - // Set DIR bit for EP0 - if ( epnum == 0 ) UDP->UDP_CSR[epnum] |= UDP_CSR_DIR_Msk; + // WALKROUND: duplicate IN transfer to send DATA1 status packet + if (_walkaround_incorrect_dtoggle_control_status) + { + UDP->UDP_CSR[epnum] |= UDP_CSR_TXPKTRDY_Msk; + while ( UDP->UDP_CSR[epnum] & UDP_CSR_TXPKTRDY_Msk ) {} + + _walkaround_incorrect_dtoggle_control_status = false; + } xact_ep_write(epnum, xfer->buffer, xfer_packet_len(xfer)); @@ -368,8 +412,17 @@ void dcd_isr(uint8_t rhport) // notify usbd dcd_event_setup_received(rhport, setup, true); - // Clear Setup bit - UDP->UDP_CSR[0] &= ~UDP_CSR_RXSETUP_Msk; + // Set EP direction bit according to DATA stage + if (setup[0] & 0x80) + { + UDP->UDP_CSR[0] |= UDP_CSR_DIR_Msk; + }else + { + UDP->UDP_CSR[0] &= ~UDP_CSR_DIR_Msk; + } + + // Clear Setup bit & stall bit if needed + UDP->UDP_CSR[0] &= ~(UDP_CSR_RXSETUP_Msk | UDP_CSR_FORCESTALL_Msk); return; } @@ -397,8 +450,12 @@ void dcd_isr(uint8_t rhport) UDP->UDP_CSR[epnum] |= UDP_CSR_TXPKTRDY_Msk; }else { - // xfer is complete - dcd_event_xfer_complete(rhport, epnum | TUSB_DIR_IN_MASK, xfer->actual_len, XFER_RESULT_SUCCESS, true); + // WALKAROUND: Skip reporting this incorrect DATA Toggle status transfer + if ( !(_walkaround_incorrect_dtoggle_control_status && (epnum == 0) && (xfer->actual_len == 0)) ) + { + // xfer is complete + dcd_event_xfer_complete(rhport, epnum | TUSB_DIR_IN_MASK, xfer->actual_len, XFER_RESULT_SUCCESS, true); + } } // Clear TX Complete bit @@ -406,8 +463,8 @@ void dcd_isr(uint8_t rhport) } // Endpoint OUT - // Ping-Pong is a must for Bulk/Iso - // When both Bank0 and Bank1 are both set, there is not way to know which one comes first + // Ping-Pong is a MUST for Bulk/Iso + // When both Bank0 and Bank1 are both set, there is no way to know which one comes first if (UDP->UDP_CSR[epnum] & (UDP_CSR_RX_DATA_BK0_Msk | UDP_CSR_RX_DATA_BK1_Msk)) { uint16_t const xact_len = (uint16_t) ((UDP->UDP_CSR[epnum] & UDP_CSR_RXBYTECNT_Msk) >> UDP_CSR_RXBYTECNT_Pos); From 02b2c602319a55226429582dfd8002c95cc3ff87 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 7 Feb 2020 17:39:20 +0700 Subject: [PATCH 224/267] samg55 work with cdc msc example --- src/portable/microchip/samg/dcd_samg.c | 56 +++++++------------------- 1 file changed, 15 insertions(+), 41 deletions(-) diff --git a/src/portable/microchip/samg/dcd_samg.c b/src/portable/microchip/samg/dcd_samg.c index 835bbf01..53ccba96 100644 --- a/src/portable/microchip/samg/dcd_samg.c +++ b/src/portable/microchip/samg/dcd_samg.c @@ -304,34 +304,6 @@ bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t } else { - // Clear DIR bit for EP0 - if ( epnum == 0 ) UDP->UDP_CSR[epnum] &= ~UDP_CSR_DIR_Msk; - - // OUT Data may already received and acked by hardware - // Read it as 1st packet then continue with transfer if needed - if ( UDP->UDP_CSR[epnum] & (UDP_CSR_RX_DATA_BK0_Msk | UDP_CSR_RX_DATA_BK1_Msk) ) - { -// uint16_t const xact_len = (uint16_t) ((UDP->UDP_CSR[epnum] & UDP_CSR_RXBYTECNT_Msk) >> UDP_CSR_RXBYTECNT_Pos); - -// TU_LOG2("xact_len = %d\r", xact_len); - -// // Read from EP fifo -// xact_ep_read(epnum, xfer->buffer, xact_len); -// xfer_packet_done(xfer); -// -// // Clear DATA Bank0 bit -// UDP->UDP_CSR[epnum] &= ~UDP_CSR_RX_DATA_BK0_Msk; -// -// if ( 0 == xfer_packet_len(xfer) ) -// { -// // Disable OUT EP interrupt when transfer is complete -// UDP->UDP_IER &= ~(1 << epnum); -// -// dcd_event_xfer_complete(rhport, epnum, xact_len, XFER_RESULT_SUCCESS, false); -// return true; // complete -// } - } - // Enable interrupt when starting OUT transfer if (epnum != 0) UDP->UDP_IER |= (1 << epnum); } @@ -387,13 +359,13 @@ void dcd_isr(uint8_t rhport) // if (intr_status & UDP_ISR_SOFINT_Msk) dcd_event_bus_signal(rhport, DCD_EVENT_SOF, true); // Suspend -// if (intr_status & UDP_ISR_RXSUSP_Msk) dcd_event_bus_signal(rhport, DCD_EVENT_SUSPEND, true); + if (intr_status & UDP_ISR_RXSUSP_Msk) dcd_event_bus_signal(rhport, DCD_EVENT_SUSPEND, true); // Resume -// if (intr_status & UDP_ISR_RXRSM_Msk) dcd_event_bus_signal(rhport, DCD_EVENT_RESUME, true); + if (intr_status & UDP_ISR_RXRSM_Msk) dcd_event_bus_signal(rhport, DCD_EVENT_RESUME, true); // Wakeup -// if (intr_status & UDP_ISR_WAKEUP_Msk) dcd_event_bus_signal(rhport, DCD_EVENT_RESUME, true); + if (intr_status & UDP_ISR_WAKEUP_Msk) dcd_event_bus_signal(rhport, DCD_EVENT_RESUME, true); //------------- Endpoints -------------// @@ -434,7 +406,7 @@ void dcd_isr(uint8_t rhport) { xfer_desc_t* xfer = &_dcd_xfer[epnum]; - // Endpoint IN + //------------- Endpoint IN -------------// if (UDP->UDP_CSR[epnum] & UDP_CSR_TXCOMP_Msk) { xfer_packet_done(xfer); @@ -455,6 +427,9 @@ void dcd_isr(uint8_t rhport) { // xfer is complete dcd_event_xfer_complete(rhport, epnum | TUSB_DIR_IN_MASK, xfer->actual_len, XFER_RESULT_SUCCESS, true); + + // Required since control OUT can happen right after before stack handle this event + xfer_end(xfer); } } @@ -462,15 +437,14 @@ void dcd_isr(uint8_t rhport) UDP->UDP_CSR[epnum] &= ~UDP_CSR_TXCOMP_Msk; } - // Endpoint OUT + //------------- Endpoint OUT -------------// // Ping-Pong is a MUST for Bulk/Iso - // When both Bank0 and Bank1 are both set, there is no way to know which one comes first - if (UDP->UDP_CSR[epnum] & (UDP_CSR_RX_DATA_BK0_Msk | UDP_CSR_RX_DATA_BK1_Msk)) + // NOTE: When both Bank0 and Bank1 are both set, there is no way to know which one comes first + uint32_t const banks_complete = UDP->UDP_CSR[epnum] & (UDP_CSR_RX_DATA_BK0_Msk | UDP_CSR_RX_DATA_BK1_Msk); + if (banks_complete) { uint16_t const xact_len = (uint16_t) ((UDP->UDP_CSR[epnum] & UDP_CSR_RXBYTECNT_Msk) >> UDP_CSR_RXBYTECNT_Pos); - //if (epnum != 0) TU_LOG2("xact_len = %d\r", xact_len); - // Read from EP fifo xact_ep_read(epnum, xfer->buffer, xact_len); xfer_packet_done(xfer); @@ -480,12 +454,12 @@ void dcd_isr(uint8_t rhport) // Disable OUT EP interrupt when transfer is complete if (epnum != 0) UDP->UDP_IDR |= (1 << epnum); - dcd_event_xfer_complete(rhport, epnum, xact_len, XFER_RESULT_SUCCESS, true); -// xfer_end(xfer); + dcd_event_xfer_complete(rhport, epnum, xfer->actual_len, XFER_RESULT_SUCCESS, true); + xfer_end(xfer); } - // Clear DATA Bank0 bit - UDP->UDP_CSR[epnum] &= ~(UDP_CSR_RX_DATA_BK0_Msk | UDP_CSR_RX_DATA_BK1_Msk); + // Clear DATA Bank0/1 bit + UDP->UDP_CSR[epnum] &= ~banks_complete; } // Stall sent to host From 46f22860fb6eaf0b65469b47b099e20f489b2e47 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 7 Feb 2020 22:13:38 +0700 Subject: [PATCH 225/267] correct waklaround with only status IN correct usb descriptor msc dual example to work with samg --- examples/device/cdc_msc/src/usb_descriptors.c | 2 +- .../device/msc_dual_lun/src/usb_descriptors.c | 18 ++++- src/portable/microchip/samg/dcd_samg.c | 73 +++++++++---------- 3 files changed, 48 insertions(+), 45 deletions(-) diff --git a/examples/device/cdc_msc/src/usb_descriptors.c b/examples/device/cdc_msc/src/usb_descriptors.c index e8527df0..5cae7760 100644 --- a/examples/device/cdc_msc/src/usb_descriptors.c +++ b/examples/device/cdc_msc/src/usb_descriptors.c @@ -95,7 +95,7 @@ enum #define EPNUM_MSC_IN 0x85 #elif CFG_TUSB_MCU == OPT_MCU_SAMG - // SAMG doesn't support a same endpoint number with IN and OUT + // SAMG doesn't support a same endpoint number with different direction IN and OUT // e.g EP1 OUT & EP1 IN cannot exist together #define EPNUM_CDC_NOTIF 0x81 #define EPNUM_CDC_OUT 0x02 diff --git a/examples/device/msc_dual_lun/src/usb_descriptors.c b/examples/device/msc_dual_lun/src/usb_descriptors.c index e0a5904a..88a96fb9 100644 --- a/examples/device/msc_dual_lun/src/usb_descriptors.c +++ b/examples/device/msc_dual_lun/src/usb_descriptors.c @@ -80,10 +80,20 @@ enum #if CFG_TUSB_MCU == OPT_MCU_LPC175X_6X || CFG_TUSB_MCU == OPT_MCU_LPC177X_8X || CFG_TUSB_MCU == OPT_MCU_LPC40XX // LPC 17xx and 40xx endpoint type (bulk/interrupt/iso) are fixed by its number - // 0 control, 1 In, 2 Bulk, 3 Iso, 4 In etc ... - #define EPNUM_MSC 0x02 + // 0 control, 1 In, 2 Bulk, 3 Iso, 4 In, 5 Bulk etc ... + #define EPNUM_MSC_OUT 0x02 + #define EPNUM_MSC_IN 0x82 + +#elif CFG_TUSB_MCU == OPT_MCU_SAMG + // SAMG doesn't support a same endpoint number with different direction IN and OUT + // e.g EP1 OUT & EP1 IN cannot exist together + #define EPNUM_MSC_OUT 0x01 + #define EPNUM_MSC_IN 0x82 + #else - #define EPNUM_MSC 0x01 + #define EPNUM_MSC_OUT 0x01 + #define EPNUM_MSC_IN 0x81 + #endif uint8_t const desc_configuration[] = @@ -92,7 +102,7 @@ uint8_t const desc_configuration[] = TUD_CONFIG_DESCRIPTOR(ITF_NUM_TOTAL, 0, CONFIG_TOTAL_LEN, TUSB_DESC_CONFIG_ATT_REMOTE_WAKEUP, 100), // Interface number, string index, EP Out & EP In address, EP size - TUD_MSC_DESCRIPTOR(ITF_NUM_MSC, 0, EPNUM_MSC, 0x80 | EPNUM_MSC, (CFG_TUSB_RHPORT0_MODE & OPT_MODE_HIGH_SPEED) ? 512 : 64), + TUD_MSC_DESCRIPTOR(ITF_NUM_MSC, 0, EPNUM_MSC_OUT, EPNUM_MSC_IN, (CFG_TUSB_RHPORT0_MODE & OPT_MODE_HIGH_SPEED) ? 512 : 64), }; // Invoked when received GET CONFIGURATION DESCRIPTOR diff --git a/src/portable/microchip/samg/dcd_samg.c b/src/portable/microchip/samg/dcd_samg.c index 53ccba96..88207252 100644 --- a/src/portable/microchip/samg/dcd_samg.c +++ b/src/portable/microchip/samg/dcd_samg.c @@ -54,6 +54,7 @@ xfer_desc_t _dcd_xfer[EP_COUNT]; // Indicate that DATA Toggle for Control Status is incorrect, which must always be DATA1 by USB Specs. // However SAMG DToggle is read-only, therefore we must duplicate the status phase ( D0 then D1 ) // as walk-around to resolve this. The D0 status packet is likely to be discarded by USB Host safely. +// Note: Only needed for IN Status e.g CDC_SET_LINE_CODING, since out data is sent by host volatile bool _walkaround_incorrect_dtoggle_control_status; void xfer_epsize_set(xfer_desc_t* xfer, uint16_t epsize) @@ -255,46 +256,43 @@ bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t xfer_desc_t* xfer = &_dcd_xfer[epnum]; xfer_begin(xfer, buffer, total_bytes); - // Control Endpoint direction and data toggle - if (epnum == 0) + if (dir == TUSB_DIR_OUT) { - // Transfer direction is opposite to one previously set on EP0 - // This transfer is Control Status Stage - if ( dir != tu_bit_test(UDP->UDP_CSR[epnum], UDP_CSR_DIR_Pos) ) - { - // Set/Clear DIR bit accordingly - if (dir) - { - UDP->UDP_CSR[epnum] |= UDP_CSR_DIR_Msk; - }else - { - UDP->UDP_CSR[epnum] &= ~UDP_CSR_DIR_Msk; - } + // Clear EP0 direction bit + if (epnum == 0) UDP->UDP_CSR[epnum] &= ~UDP_CSR_DIR_Msk; - // DATA Toggle is 0, USB Specs requires Status Stage must be DATA1 - // Since SAMG DToggle is read-only, we mark this and implement a walk-around - if ( !(UDP->UDP_CSR[epnum] & UDP_CSR_DTGLE_Msk) ) - { - TU_LOG2("Incorrect DATA TOGGLE, Control Status must be DATA1\n"); - - // DTGLE is read-only on SAMG, this statement has no effect - UDP->UDP_CSR[epnum] |= UDP_CSR_DTGLE_Msk; - - _walkaround_incorrect_dtoggle_control_status = true; - } - } + // Enable interrupt when starting OUT transfer + if (epnum != 0) UDP->UDP_IER |= (1 << epnum); } - - - if (dir == TUSB_DIR_IN) + else { - // WALKROUND: duplicate IN transfer to send DATA1 status packet - if (_walkaround_incorrect_dtoggle_control_status) + if (epnum == 0) { - UDP->UDP_CSR[epnum] |= UDP_CSR_TXPKTRDY_Msk; - while ( UDP->UDP_CSR[epnum] & UDP_CSR_TXPKTRDY_Msk ) {} + // Previous EP0 direction is OUT --> This transfer is ZLP control status. + if ( !(UDP->UDP_CSR[epnum] & UDP_CSR_DIR_Msk) ) + { + // Set EP0 dir bit + UDP->UDP_CSR[epnum] |= UDP_CSR_DIR_Msk; - _walkaround_incorrect_dtoggle_control_status = false; + // DATA Toggle is 0, USB Specs requires Status Stage must be DATA1 + // Since SAMG DToggle is read-only, we mark this and implement the walk-around + if ( !(UDP->UDP_CSR[epnum] & UDP_CSR_DTGLE_Msk) ) + { + TU_LOG2("Incorrect DATA TOGGLE, Control Status must be DATA1\n"); + + // DTGLE is read-only on SAMG, this statement has no effect + UDP->UDP_CSR[epnum] |= UDP_CSR_DTGLE_Msk; + + // WALKROUND: duplicate IN transfer to send DATA1 status packet + // set flag for irq to skip reporting first incorrect packet + _walkaround_incorrect_dtoggle_control_status = true; + + UDP->UDP_CSR[epnum] |= UDP_CSR_TXPKTRDY_Msk; + while ( UDP->UDP_CSR[epnum] & UDP_CSR_TXPKTRDY_Msk ) {} + + _walkaround_incorrect_dtoggle_control_status = false; + } + } } xact_ep_write(epnum, xfer->buffer, xfer_packet_len(xfer)); @@ -302,11 +300,6 @@ bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t // TX ready for transfer UDP->UDP_CSR[epnum] |= UDP_CSR_TXPKTRDY_Msk; } - else - { - // Enable interrupt when starting OUT transfer - if (epnum != 0) UDP->UDP_IER |= (1 << epnum); - } return true; } @@ -422,7 +415,7 @@ void dcd_isr(uint8_t rhport) UDP->UDP_CSR[epnum] |= UDP_CSR_TXPKTRDY_Msk; }else { - // WALKAROUND: Skip reporting this incorrect DATA Toggle status transfer + // WALKAROUND: Skip reporting this incorrect DATA Toggle status IN transfer if ( !(_walkaround_incorrect_dtoggle_control_status && (epnum == 0) && (xfer->actual_len == 0)) ) { // xfer is complete From 7d8ecc63a60b039b6e59961023ffb1c228e20d4f Mon Sep 17 00:00:00 2001 From: Peter Lawrence <12226419+majbthrd@users.noreply.github.com> Date: Fri, 7 Feb 2020 20:11:00 -0600 Subject: [PATCH 226/267] add Nuvoton NUC505 --- README.md | 2 +- .../device/cdc_dual_ports/src/tusb_config.h | 2 +- examples/device/cdc_msc/src/tusb_config.h | 2 +- .../cdc_msc_hid_freertos/src/tusb_config.h | 2 +- examples/device/dfu_rt/src/tusb_config.h | 2 +- .../device/hid_composite/src/tusb_config.h | 2 +- .../hid_generic_inout/src/tusb_config.h | 2 +- examples/device/midi_test/src/tusb_config.h | 2 +- .../device/msc_dual_lun/src/tusb_config.h | 2 +- examples/device/usbtmc/src/tusb_config.h | 2 +- .../device/webusb_serial/src/tusb_config.h | 2 +- hw/bsp/nutiny_sdk_nuc505/board.mk | 52 ++ hw/bsp/nutiny_sdk_nuc505/nuc505_flashtoram.ld | 199 ++++++ hw/bsp/nutiny_sdk_nuc505/nutiny_sdk_nuc505.c | 115 ++++ hw/mcu/nuvoton | 2 +- src/portable/nuvoton/nuc505/dcd_nuc505.c | 639 ++++++++++++++++++ src/tusb_option.h | 1 + 17 files changed, 1018 insertions(+), 12 deletions(-) create mode 100644 hw/bsp/nutiny_sdk_nuc505/board.mk create mode 100644 hw/bsp/nutiny_sdk_nuc505/nuc505_flashtoram.ld create mode 100644 hw/bsp/nutiny_sdk_nuc505/nutiny_sdk_nuc505.c create mode 100644 src/portable/nuvoton/nuc505/dcd_nuc505.c diff --git a/README.md b/README.md index 29052d01..7ab55f78 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,7 @@ The stack supports the following MCUs: - **Sony:** CXD56 - **ST:** STM32 series: L0, F0, F1, F2, F3, F4, F7, H7 (device only) - **[ValentyUSB](https://github.com/im-tomu/valentyusb)** eptri -- **Nuvoton:** NUC121/NUC125, NUC126 +- **Nuvoton:** NUC121/NUC125, NUC126, NUC505 [Here is the list of supported Boards](docs/boards.md) that can be used with provided examples. diff --git a/examples/device/cdc_dual_ports/src/tusb_config.h b/examples/device/cdc_dual_ports/src/tusb_config.h index 734b96c1..9783bd4f 100644 --- a/examples/device/cdc_dual_ports/src/tusb_config.h +++ b/examples/device/cdc_dual_ports/src/tusb_config.h @@ -39,7 +39,7 @@ #error CFG_TUSB_MCU must be defined #endif -#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX +#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX || CFG_TUSB_MCU == OPT_MCU_NUC505 #define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED) #else #define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE diff --git a/examples/device/cdc_msc/src/tusb_config.h b/examples/device/cdc_msc/src/tusb_config.h index 5b7a1671..d881cb63 100644 --- a/examples/device/cdc_msc/src/tusb_config.h +++ b/examples/device/cdc_msc/src/tusb_config.h @@ -39,7 +39,7 @@ #error CFG_TUSB_MCU must be defined #endif -#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX +#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX || CFG_TUSB_MCU == OPT_MCU_NUC505 #define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED) #else #define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE diff --git a/examples/device/cdc_msc_hid_freertos/src/tusb_config.h b/examples/device/cdc_msc_hid_freertos/src/tusb_config.h index 6788a748..39738333 100644 --- a/examples/device/cdc_msc_hid_freertos/src/tusb_config.h +++ b/examples/device/cdc_msc_hid_freertos/src/tusb_config.h @@ -39,7 +39,7 @@ #error CFG_TUSB_MCU must be defined #endif -#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX +#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX || CFG_TUSB_MCU == OPT_MCU_NUC505 #define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED) #else #define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE diff --git a/examples/device/dfu_rt/src/tusb_config.h b/examples/device/dfu_rt/src/tusb_config.h index 27afdb6b..96c3a246 100644 --- a/examples/device/dfu_rt/src/tusb_config.h +++ b/examples/device/dfu_rt/src/tusb_config.h @@ -21,7 +21,7 @@ #error CFG_TUSB_MCU must be defined #endif -#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX +#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX || CFG_TUSB_MCU == OPT_MCU_NUC505 #define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED) #else #define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE diff --git a/examples/device/hid_composite/src/tusb_config.h b/examples/device/hid_composite/src/tusb_config.h index dd360741..6d2fd083 100644 --- a/examples/device/hid_composite/src/tusb_config.h +++ b/examples/device/hid_composite/src/tusb_config.h @@ -39,7 +39,7 @@ #error CFG_TUSB_MCU must be defined #endif -#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX +#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX || CFG_TUSB_MCU == OPT_MCU_NUC505 #define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED) #else #define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE diff --git a/examples/device/hid_generic_inout/src/tusb_config.h b/examples/device/hid_generic_inout/src/tusb_config.h index 0053a7d0..2debafd2 100644 --- a/examples/device/hid_generic_inout/src/tusb_config.h +++ b/examples/device/hid_generic_inout/src/tusb_config.h @@ -39,7 +39,7 @@ #error CFG_TUSB_MCU must be defined #endif -#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX +#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX || CFG_TUSB_MCU == OPT_MCU_NUC505 #define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED) #else #define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE diff --git a/examples/device/midi_test/src/tusb_config.h b/examples/device/midi_test/src/tusb_config.h index 5837db4e..56f326f3 100644 --- a/examples/device/midi_test/src/tusb_config.h +++ b/examples/device/midi_test/src/tusb_config.h @@ -39,7 +39,7 @@ #error CFG_TUSB_MCU must be defined #endif -#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX +#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX || CFG_TUSB_MCU == OPT_MCU_NUC505 #define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED) #else #define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE diff --git a/examples/device/msc_dual_lun/src/tusb_config.h b/examples/device/msc_dual_lun/src/tusb_config.h index baf857b7..82d07c60 100644 --- a/examples/device/msc_dual_lun/src/tusb_config.h +++ b/examples/device/msc_dual_lun/src/tusb_config.h @@ -39,7 +39,7 @@ #error CFG_TUSB_MCU must be defined #endif -#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX +#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX || CFG_TUSB_MCU == OPT_MCU_NUC505 #define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED) #else #define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE diff --git a/examples/device/usbtmc/src/tusb_config.h b/examples/device/usbtmc/src/tusb_config.h index 2932ea4d..5dddc2c4 100644 --- a/examples/device/usbtmc/src/tusb_config.h +++ b/examples/device/usbtmc/src/tusb_config.h @@ -21,7 +21,7 @@ #error CFG_TUSB_MCU must be defined #endif -#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX +#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX || CFG_TUSB_MCU == OPT_MCU_NUC505 #define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED) #else #define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE diff --git a/examples/device/webusb_serial/src/tusb_config.h b/examples/device/webusb_serial/src/tusb_config.h index 30acdacc..b3f449f9 100644 --- a/examples/device/webusb_serial/src/tusb_config.h +++ b/examples/device/webusb_serial/src/tusb_config.h @@ -39,7 +39,7 @@ #error CFG_TUSB_MCU must be defined #endif -#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX +#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX || CFG_TUSB_MCU == OPT_MCU_NUC505 #define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED) #else #define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE diff --git a/hw/bsp/nutiny_sdk_nuc505/board.mk b/hw/bsp/nutiny_sdk_nuc505/board.mk new file mode 100644 index 00000000..259d1108 --- /dev/null +++ b/hw/bsp/nutiny_sdk_nuc505/board.mk @@ -0,0 +1,52 @@ +CFLAGS += \ + -flto \ + -mthumb \ + -mabi=aapcs-linux \ + -mcpu=cortex-m4 \ + -DCFG_TUSB_MCU=OPT_MCU_NUC505 + +# All source paths should be relative to the top level. +LD_FILE = hw/bsp/nutiny_sdk_nuc505/nuc505_flashtoram.ld + +SRC_C += \ + hw/mcu/nuvoton/nuc505/Device/Nuvoton/NUC505Series/Source/system_NUC505Series.c \ + hw/mcu/nuvoton/nuc505/StdDriver/src/adc.c \ + hw/mcu/nuvoton/nuc505/StdDriver/src/clk.c \ + hw/mcu/nuvoton/nuc505/StdDriver/src/gpio.c \ + hw/mcu/nuvoton/nuc505/StdDriver/src/i2c.c \ + hw/mcu/nuvoton/nuc505/StdDriver/src/i2s.c \ + hw/mcu/nuvoton/nuc505/StdDriver/src/pwm.c \ + hw/mcu/nuvoton/nuc505/StdDriver/src/rtc.c \ + hw/mcu/nuvoton/nuc505/StdDriver/src/sd.c \ + hw/mcu/nuvoton/nuc505/StdDriver/src/spi.c \ + hw/mcu/nuvoton/nuc505/StdDriver/src/spim.c \ + hw/mcu/nuvoton/nuc505/StdDriver/src/sys.c \ + hw/mcu/nuvoton/nuc505/StdDriver/src/timer.c \ + hw/mcu/nuvoton/nuc505/StdDriver/src/uart.c \ + hw/mcu/nuvoton/nuc505/StdDriver/src/usbd.c \ + hw/mcu/nuvoton/nuc505/StdDriver/src/wdt.c \ + hw/mcu/nuvoton/nuc505/StdDriver/src/wwdt.c + +SRC_S += \ + hw/mcu/nuvoton/nuc505/Device/Nuvoton/NUC505Series/Source/GCC/startup_NUC505Series.S + +INC += \ + $(TOP)/hw/mcu/nuvoton/nuc505/Device/Nuvoton/NUC505Series/Include \ + $(TOP)/hw/mcu/nuvoton/nuc505/StdDriver/inc \ + $(TOP)/hw/mcu/nuvoton/nuc505/CMSIS/Include + +# For TinyUSB port source +VENDOR = nuvoton +CHIP_FAMILY = nuc505 + +# For freeRTOS port source +FREERTOS_PORT = ARM_CM4 + +# For flash-jlink target +JLINK_DEVICE = NUC505YO13Y +JLINK_IF = swd + +# Flash using Nuvoton's openocd fork at https://github.com/OpenNuvoton/OpenOCD-Nuvoton +# Please compile and install it from github source +flash: $(BUILD)/$(BOARD)-firmware.elf + openocd -f interface/nulink.cfg -f target/numicroM4.cfg -c "program $< reset exit" diff --git a/hw/bsp/nutiny_sdk_nuc505/nuc505_flashtoram.ld b/hw/bsp/nutiny_sdk_nuc505/nuc505_flashtoram.ld new file mode 100644 index 00000000..53d385cd --- /dev/null +++ b/hw/bsp/nutiny_sdk_nuc505/nuc505_flashtoram.ld @@ -0,0 +1,199 @@ +/* Linker script to configure memory regions. */ +MEMORY +{ + FLASH (rx) : ORIGIN = 0x00000000, LENGTH = 0x80000 /* 512k */ + RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 0x20000 /* 128k */ +} + +/* Library configurations */ +GROUP(libgcc.a libc.a libm.a libnosys.a) + +/* 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 + * __copy_table_start__ + * __copy_table_end__ + * __zero_table_start__ + * __zero_table_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 + * __Vectors_End + * __Vectors_Size + */ +ENTRY(Reset_Handler) + +SECTIONS +{ + .startup : + { + KEEP(*(.vectors)) + __Vectors_End = .; + __Vectors_Size = __Vectors_End - __Vectors; + __end__ = .; + + KEEP(*(.preinit)) + + KEEP(*(.init)) + KEEP(*(.fini)) + + } > FLASH + + .ARM.extab : + { + *(.ARM.extab* .gnu.linkonce.armextab.*) + } > FLASH + + __exidx_start = .; + .ARM.exidx : + { + *(.ARM.exidx* .gnu.linkonce.armexidx.*) + } > FLASH + __exidx_end = .; + + /* To copy multiple ROM to RAM sections, + * uncomment .copy.table section and, + * define __STARTUP_COPY_MULTIPLE in startup_ARMCMx.S */ + /* + .copy.table : + { + . = ALIGN(4); + __copy_table_start__ = .; + LONG (__etext) + LONG (__data_start__) + LONG (__data_end__ - __data_start__) + LONG (__etext2) + LONG (__data2_start__) + LONG (__data2_end__ - __data2_start__) + __copy_table_end__ = .; + } > FLASH + */ + + /* To clear multiple BSS sections, + * uncomment .zero.table section and, + * define __STARTUP_CLEAR_BSS_MULTIPLE in startup_ARMCMx.S */ + /* + .zero.table : + { + . = ALIGN(4); + __zero_table_start__ = .; + LONG (__bss_start__) + LONG (__bss_end__ - __bss_start__) + LONG (__bss2_start__) + LONG (__bss2_end__ - __bss2_start__) + __zero_table_end__ = .; + } > FLASH + */ + + __etext = .; + + .data : AT (__etext) + { + __data_start__ = .; + + *(.text*) + + /* .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*)) + + *(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__ = .; + + } > RAM + + .bss : + { + . = ALIGN(4); + __bss_start__ = .; + *(.bss*) + *(COMMON) + . = ALIGN(4); + __bss_end__ = .; + } > RAM + + .heap (COPY): + { + __HeapBase = .; + __end__ = .; + end = __end__; + KEEP(*(.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): + { + KEEP(*(.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); + __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/hw/bsp/nutiny_sdk_nuc505/nutiny_sdk_nuc505.c b/hw/bsp/nutiny_sdk_nuc505/nutiny_sdk_nuc505.c new file mode 100644 index 00000000..e666a10a --- /dev/null +++ b/hw/bsp/nutiny_sdk_nuc505/nutiny_sdk_nuc505.c @@ -0,0 +1,115 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#include "bsp/board.h" +#include "NUC505Series.h" + +#define LED_PORT PC +#define LED_PIN 3 +#define LED_STATE_ON 0 + +void board_init(void) +{ + /* Enable XTAL */ + CLK->PWRCTL |= CLK_PWRCTL_HXTEN_Msk; + + CLK_SetCoreClock(96000000); + + /* Set PCLK divider */ + CLK_SetModuleClock(PCLK_MODULE, 0, 1); + + /* Update System Core Clock */ + SystemCoreClockUpdate(); + + /* Enable USB IP clock */ + CLK_EnableModuleClock(USBD_MODULE); + + /* Select USB IP clock source */ + CLK_SetModuleClock(USBD_MODULE, CLK_USBD_SRC_EXT, 0); + + CLK_SetModuleClock(PCLK_MODULE, 0, 1); + + /* Enable PHY */ + USBD_ENABLE_PHY(); + /* wait PHY clock ready */ + while (1) { + USBD->EP[EPA].EPMPS = 0x20; + if (USBD->EP[EPA].EPMPS == 0x20) + break; + } + + /* Force SE0, and then clear it to connect*/ + USBD_SET_SE0(); + +#if CFG_TUSB_OS == OPT_OS_NONE + // 1ms tick timer + SysTick_Config(96000000 / 1000); +#endif + + GPIO_SetMode(LED_PORT, 1UL << LED_PIN, GPIO_MODE_OUTPUT); +} + +#if CFG_TUSB_OS == OPT_OS_NONE +volatile uint32_t system_ticks = 0; +void SysTick_Handler (void) +{ + system_ticks++; +} + +uint32_t board_millis(void) +{ + return system_ticks; +} +#endif + +//--------------------------------------------------------------------+ +// Board porting API +//--------------------------------------------------------------------+ + +void board_led_write(bool state) +{ + uint32_t current = (state) ? LED_STATE_ON : (1-LED_STATE_ON); + current <<= LED_PIN; + current |= LED_PORT->DOUT & ~(1UL << LED_PIN); + LED_PORT->DOUT = current; +} + +uint32_t board_button_read(void) +{ + return 0; +} + +int board_uart_read(uint8_t* buf, int len) +{ + (void) buf; (void) len; + return 0; +} + +int board_uart_write(void const * buf, int len) +{ + (void) buf; (void) len; + return 0; +} diff --git a/hw/mcu/nuvoton b/hw/mcu/nuvoton index dc96fff7..2204191e 160000 --- a/hw/mcu/nuvoton +++ b/hw/mcu/nuvoton @@ -1 +1 @@ -Subproject commit dc96fff794d14818c93ea1d4d760d51a014d70c5 +Subproject commit 2204191ec76283371419fbcec207da02e1bc22fa diff --git a/src/portable/nuvoton/nuc505/dcd_nuc505.c b/src/portable/nuvoton/nuc505/dcd_nuc505.c new file mode 100644 index 00000000..2b6a66bc --- /dev/null +++ b/src/portable/nuvoton/nuc505/dcd_nuc505.c @@ -0,0 +1,639 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2020 Peter Lawrence + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +/* + Theory of operation: + + The NUC505 USBD peripheral has twelve "EP"s, where each is simplex, in addition + to dedicated support for the control endpoint (EP0). The non-user endpoints + are referred to as "user" EPs in this code, and follow the datasheet + nomenclature of EPA through EPL. +*/ + +#include "tusb_option.h" + +#if TUSB_OPT_DEVICE_ENABLED && (CFG_TUSB_MCU == OPT_MCU_NUC505) + +#include "device/dcd.h" +#include "NUC505Series.h" + +/* rather important info unfortunately not provided by device include files */ +#define USBD_BUF_SIZE 2048 /* how much USB buffer space there is */ +#define USBD_MAX_DMA_LEN 0x1000 /* max bytes that can be DMAed at one time */ + +enum ep_enum +{ + PERIPH_EPA = 0, + PERIPH_EPB = 1, + PERIPH_EPC = 2, + PERIPH_EPD = 3, + PERIPH_EPE = 4, + PERIPH_EPF = 5, + PERIPH_EPG = 6, + PERIPH_EPH = 7, + PERIPH_EPI = 8, + PERIPH_EPJ = 9, + PERIPH_EPK = 10, + PERIPH_EPL = 11, + PERIPH_MAX_EP, +}; + +static const uint8_t epcfg_eptype_table[] = +{ + [TUSB_XFER_CONTROL] = 0, /* won't happen, since control EPs have dedicated registers */ + [TUSB_XFER_ISOCHRONOUS] = 3 << USBD_EPCFG_EPTYPE_Pos, + [TUSB_XFER_BULK] = 1 << USBD_EPCFG_EPTYPE_Pos, + [TUSB_XFER_INTERRUPT] = 2 << USBD_EPCFG_EPTYPE_Pos, +}; + +static const uint8_t eprspctl_eptype_table[] = +{ + [TUSB_XFER_CONTROL] = 0, /* won't happen, since control EPs have dedicated registers */ + [TUSB_XFER_ISOCHRONOUS] = 2 << USBD_EPRSPCTL_MODE_Pos, /* Fly Mode */ + [TUSB_XFER_BULK] = 0 << USBD_EPRSPCTL_MODE_Pos, /* Auto-Validate Mode */ + [TUSB_XFER_INTERRUPT] = 1 << USBD_EPRSPCTL_MODE_Pos, /* Manual-Validate Mode */ +}; + +/* set by dcd_set_address() */ +static volatile uint8_t assigned_address; + +/* reset by bus_reset(), this is used by dcd_edpt_open() to assign USBD peripheral buffer addresses */ +static uint32_t bufseg_addr; + +/* RAM table needed to track ongoing transfers performed by dcd_edpt_xfer(), dcd_userEP_in_xfer(), and the ISR */ +static struct xfer_ctl_t +{ + uint8_t *data_ptr; /* data_ptr tracks where to next copy data to (for OUT) or from (for IN) */ + union { + uint16_t in_remaining_bytes; /* for IN endpoints, we track how many bytes are left to transfer */ + uint16_t out_bytes_so_far; /* but for OUT endpoints, we track how many bytes we've transferred so far */ + }; + uint16_t max_packet_size; /* needed since device driver only finds out this at runtime */ + uint16_t total_bytes; /* quantity needed to pass as argument to dcd_event_xfer_complete() (for IN endpoints) */ + uint8_t ep_addr; + bool dma_requested; +} xfer_table[PERIPH_MAX_EP]; + +/* in addition to xfer_table, additional bespoke bookkeeping is maintained for control EP0 IN */ +static struct +{ + uint8_t *data_ptr; + uint16_t in_remaining_bytes; + uint16_t total_bytes; +} ctrl_in_xfer; + +static volatile bool configuration_changed; + +static volatile struct xfer_ctl_t *current_dma_xfer; + + +/* + local helper functions +*/ + +static void usb_attach(void) +{ + USBD->PHYCTL |= USBD_PHYCTL_DPPUEN_Msk; +} + +static void usb_control_send_zlp(void) +{ + USBD->CEPINTSTS = USBD_CEPINTSTS_STSDONEIF_Msk; + USBD->CEPCTL = 0; /* clear NAKCLR bit */ + USBD->CEPINTEN = USBD_CEPINTEN_STSDONEIEN_Msk; +} + +/* map 8-bit ep_addr into peripheral endpoint index (PERIPH_EPA...) */ +static USBD_EP_T *ep_entry(uint8_t ep_addr, bool add) +{ + USBD_EP_T *ep; + enum ep_enum ep_index; + struct xfer_ctl_t *xfer; + + for (ep_index = PERIPH_EPA, xfer = &xfer_table[PERIPH_EPA], ep = USBD->EP; ep_index < PERIPH_MAX_EP; ep_index++, xfer++, ep++) + { + if (add) + { + /* take first peripheral endpoint that is unused */ + if (0 == (ep->EPCFG & USBD_EPCFG_EPEN_Msk)) return ep; + } + else + { + /* find a peripheral endpoint that matches ep_addr */ + if (xfer->ep_addr == ep_addr) return ep; + } + } + + return NULL; +} + +/* perform a non-control IN endpoint transfer; this is called by the ISR */ +static void dcd_userEP_in_xfer(struct xfer_ctl_t *xfer, USBD_EP_T *ep) +{ + uint16_t bytes_now = tu_min16(xfer->in_remaining_bytes, xfer->max_packet_size); + uint16_t countdown = bytes_now; + + /* precompute what amount of data will be left */ + xfer->in_remaining_bytes -= bytes_now; + + /* + if there will be no more data to send, we replace the BUFEMPTYIF EP interrupt with TXPKIF; + that way, we alert TinyUSB as soon as this last packet has been sent + */ + if (0 == xfer->in_remaining_bytes) + { + ep->EPINTSTS = USBD_EPINTSTS_TXPKIF_Msk; + ep->EPINTEN = USBD_EPINTEN_TXPKIEN_Msk; + } + + /* provided buffers are thankfully 32-bit aligned, allowing most data to be transfered as 32-bit */ + while (countdown > 3) + { + ep->EPDAT = *(uint32_t *)xfer->data_ptr; + xfer->data_ptr += 4; countdown -= 4; + } + while (countdown--) + ep->EPDAT_BYTE = *xfer->data_ptr++; + + /* for short packets, we must nudge the peripheral to say 'that's all folks' */ + if (bytes_now != xfer->max_packet_size) + ep->EPRSPCTL = USBD_EPRSPCTL_SHORTTXEN_Msk; +} + +/* called by dcd_init() as well as by the ISR during a USB bus reset */ +static void bus_reset(void) +{ + for (enum ep_enum ep_index = PERIPH_EPA; ep_index < PERIPH_MAX_EP; ep_index++) + { + USBD->EP[ep_index].EPCFG = 0; + xfer_table[ep_index].dma_requested = false; + } + + USBD->DMACNT = 0; + USBD->DMACTL = USBD_DMACTL_DMARST_Msk; + USBD->DMACTL = 0; + + /* allocate the default EP0 endpoints */ + + USBD->CEPBUFSTART = 0; + USBD->CEPBUFEND = 0 + CFG_TUD_ENDPOINT0_SIZE - 1; + + /* USB RAM beyond what we've allocated above is available to the user */ + bufseg_addr = CFG_TUD_ENDPOINT0_SIZE; + + /* Reset USB device address */ + USBD->FADDR = 0; + + configuration_changed = false; + current_dma_xfer = NULL; +} + +/* this must only be called by the ISR; it does its best to share the single DMA engine across all user EPs (IN and OUT) */ +static void service_dma(void) +{ + if (current_dma_xfer) + return; + + enum ep_enum ep_index; + struct xfer_ctl_t *xfer; + USBD_EP_T *ep; + + for (ep_index = PERIPH_EPA, xfer = &xfer_table[PERIPH_EPA], ep = &USBD->EP[PERIPH_EPA]; ep_index < PERIPH_MAX_EP; ep_index++, xfer++, ep++) + { + uint16_t const available_bytes = ep->EPDATCNT & USBD_EPDATCNT_DATCNT_Msk; + + if (!xfer->dma_requested || !available_bytes) + continue; + + /* + instruct DMA to copy the data from the PC to the previously provided buffer + when the bus interrupt DMADONEIEN subsequently fires, the transfer will have finished + */ + USBD->DMACTL = xfer->ep_addr & USBD_DMACTL_EPNUM_Msk; + USBD->DMAADDR = (uint32_t)xfer->data_ptr; + USBD->DMACNT = available_bytes; + USBD->BUSINTSTS = USBD_BUSINTSTS_DMADONEIF_Msk; + xfer->out_bytes_so_far += available_bytes; + current_dma_xfer = xfer; + USBD->DMACTL |= USBD_DMACTL_DMAEN_Msk; + + return; + } +} + +/* centralized location for USBD interrupt enable bit masks */ +static const uint32_t enabled_irqs = USBD_GINTEN_USBIEN_Msk | \ + USBD_GINTEN_EPAIEN_Msk | USBD_GINTEN_EPBIEN_Msk | USBD_GINTEN_EPCIEN_Msk | USBD_GINTEN_EPDIEN_Msk | USBD_GINTEN_EPEIEN_Msk | USBD_GINTEN_EPFIEN_Msk | \ + USBD_GINTEN_EPGIEN_Msk | USBD_GINTEN_EPHIEN_Msk | USBD_GINTEN_EPIIEN_Msk | USBD_GINTEN_EPJIEN_Msk | USBD_GINTEN_EPKIEN_Msk | USBD_GINTEN_EPLIEN_Msk | \ + USBD_GINTEN_CEPIEN_Msk; + +/* + NUC505 TinyUSB API driver implementation +*/ + +void dcd_init(uint8_t rhport) +{ + (void) rhport; + + /* configure interrupts in their initial state; BUSINTEN and CEPINTEN will be subsequently and dynamically re-written as needed */ + USBD->GINTEN = enabled_irqs; + USBD->BUSINTEN = USBD_BUSINTEN_RSTIEN_Msk | USBD_BUSINTEN_VBUSDETIEN_Msk | USBD_BUSINTEN_RESUMEIEN_Msk | USBD_BUSINTEN_DMADONEIEN_Msk; + USBD->CEPINTEN = 0; + + bus_reset(); + + usb_attach(); +} + +void dcd_int_enable(uint8_t rhport) +{ + (void) rhport; + NVIC_EnableIRQ(USBD_IRQn); +} + +void dcd_int_disable(uint8_t rhport) +{ + (void) rhport; + NVIC_DisableIRQ(USBD_IRQn); +} + +void dcd_set_address(uint8_t rhport, uint8_t dev_addr) +{ + (void) rhport; + usb_control_send_zlp(); /* SET_ADDRESS is the one exception where TinyUSB doesn't use dcd_edpt_xfer() to generate a ZLP */ + assigned_address = dev_addr; +} + +void dcd_set_config(uint8_t rhport, uint8_t config_num) +{ + (void) rhport; + (void) config_num; + configuration_changed = true; +} + +void dcd_remote_wakeup(uint8_t rhport) +{ + (void) rhport; + USBD->OPER |= USBD_OPER_RESUMEEN_Msk; +} + +bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc) +{ + (void) rhport; + + USBD_EP_T *ep = ep_entry(p_endpoint_desc->bEndpointAddress, true); + TU_ASSERT(ep); + + /* mine the data for the information we need */ + int const dir = tu_edpt_dir(p_endpoint_desc->bEndpointAddress); + int const size = p_endpoint_desc->wMaxPacketSize.size; + tusb_xfer_type_t const type = p_endpoint_desc->bmAttributes.xfer; + struct xfer_ctl_t *xfer = &xfer_table[ep - USBD->EP]; + + /* allocate buffer from USB RAM */ + ep->EPBUFSTART = bufseg_addr; + bufseg_addr += size; + ep->EPBUFEND = bufseg_addr - 1; + TU_ASSERT(bufseg_addr <= USBD_BUF_SIZE); + + ep->EPMPS = size; + + ep->EPRSPCTL = USB_EP_RSPCTL_FLUSH | eprspctl_eptype_table[type]; + + /* construct USB Configuration Register value and then write it */ + uint32_t cfg = (uint32_t)tu_edpt_number(p_endpoint_desc->bEndpointAddress) << USBD_EPCFG_EPNUM_Pos; + if (TUSB_DIR_IN == dir) + cfg |= USBD_EPCFG_EPDIR_Msk; + cfg |= epcfg_eptype_table[type] | USBD_EPCFG_EPEN_Msk; + ep->EPCFG = cfg; + + /* make a note of the endpoint particulars */ + xfer->max_packet_size = size; + xfer->ep_addr = p_endpoint_desc->bEndpointAddress; + + return true; +} + +bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t *buffer, uint16_t total_bytes) +{ + (void) rhport; + + if (0x80 == ep_addr) /* control EP0 IN */ + { + if (total_bytes) + { + USBD->CEPCTL = USBD_CEPCTL_FLUSH_Msk; + ctrl_in_xfer.data_ptr = buffer; + ctrl_in_xfer.in_remaining_bytes = total_bytes; + ctrl_in_xfer.total_bytes = total_bytes; + USBD->CEPINTSTS = USBD_CEPINTSTS_INTKIF_Msk; + USBD->CEPINTEN = USBD_CEPINTEN_INTKIEN_Msk; + } + else + { + usb_control_send_zlp(); + } + } + else if (0x00 == ep_addr) /* control EP0 OUT */ + { + if (total_bytes) + { + /* if TinyUSB is asking for EP0 OUT data, it is almost certainly already in the buffer */ + while (total_bytes < USBD->CEPRXCNT); + for (int count = 0; count < total_bytes; count++) + *buffer++ = USBD->CEPDAT_BYTE; + + usb_control_send_zlp(); + } + } + else + { + /* mine the data for the information we need */ + tusb_dir_t dir = tu_edpt_dir(ep_addr); + USBD_EP_T *ep = ep_entry(ep_addr, false); + struct xfer_ctl_t *xfer = &xfer_table[ep - USBD->EP]; + + /* store away the information we'll needing now and later */ + xfer->data_ptr = buffer; + xfer->in_remaining_bytes = total_bytes; + xfer->total_bytes = total_bytes; + + if (TUSB_DIR_IN == dir) + { + ep->EPINTEN = USBD_EPINTEN_BUFEMPTYIEN_Msk; + } + else + { + xfer->out_bytes_so_far = 0; + ep->EPINTEN = USBD_EPINTEN_RXPKIEN_Msk; + } + } + + return true; +} + +void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + + if (tu_edpt_number(ep_addr)) + { + USBD_EP_T *ep = ep_entry(ep_addr, false); + ep->EPRSPCTL = (ep->EPRSPCTL & 0xf7) | USBD_EPRSPCTL_HALT_Msk; + } + else + { + USBD->CEPCTL = USBD_CEPCTL_STALLEN_Msk; + } +} + +void dcd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + + if (tu_edpt_number(ep_addr)) + { + USBD_EP_T *ep = ep_entry(ep_addr, false); + ep->EPRSPCTL = USBD_EPRSPCTL_TOGGLE_Msk; + } +} + +void USBD_IRQHandler(void) +{ + uint32_t status = USBD->GINTSTS; + + /* USB interrupt */ + if (status & USBD_GINTSTS_USBIF_Msk) + { + uint32_t bus_state = USBD->BUSINTSTS; + + if (bus_state & USBD_BUSINTSTS_SOFIF_Msk) + { + /* Start-Of-Frame event */ + dcd_event_bus_signal(0, DCD_EVENT_SOF, true); + } + + if (bus_state & USBD_BUSINTSTS_RSTIF_Msk) + { + bus_reset(); + + USBD->CEPINTEN = USBD_CEPINTEN_SETUPPKIEN_Msk; + USBD->BUSINTEN = USBD_BUSINTEN_RSTIEN_Msk | USBD_BUSINTEN_RESUMEIEN_Msk | USBD_BUSINTEN_SUSPENDIEN_Msk | USBD_BUSINTEN_DMADONEIEN_Msk; + USBD->CEPINTSTS = 0x1ffc; + dcd_event_bus_signal(0, DCD_EVENT_BUS_RESET, true); + } + + if (bus_state & USBD_BUSINTSTS_RESUMEIF_Msk) + { + USBD->BUSINTEN = USBD_BUSINTEN_RSTIEN_Msk | USBD_BUSINTEN_SUSPENDIEN_Msk | USBD_BUSINTEN_DMADONEIEN_Msk; + dcd_event_bus_signal(0, DCD_EVENT_RESUME, true); + } + + if (bus_state & USBD_BUSINTSTS_SUSPENDIF_Msk) + { + USBD->BUSINTEN = USBD_BUSINTEN_RSTIEN_Msk | USBD_BUSINTEN_RESUMEIEN_Msk | USBD_BUSINTEN_DMADONEIEN_Msk; + dcd_event_bus_signal(0, DCD_EVENT_SUSPEND, true); + } + + if (bus_state & USBD_BUSINTSTS_HISPDIF_Msk) + { + USBD->CEPINTEN = USBD_CEPINTEN_SETUPPKIEN_Msk; + } + + if (bus_state & USBD_BUSINTSTS_DMADONEIF_Msk) + { + if (current_dma_xfer) + { + current_dma_xfer->dma_requested = false; + + uint16_t available_bytes = USBD->DMACNT & USBD_DMACNT_DMACNT_Msk; + + /* if the most recent DMA finishes the transfer, alert TinyUSB; otherwise, the next RXPKIF/INTKIF endpoint interrupt will prompt the next DMA */ + if ( (current_dma_xfer->total_bytes == current_dma_xfer->out_bytes_so_far) || (available_bytes < current_dma_xfer->max_packet_size) ) + { + dcd_event_xfer_complete(0, current_dma_xfer->ep_addr, current_dma_xfer->out_bytes_so_far, XFER_RESULT_SUCCESS, true); + } + + current_dma_xfer = NULL; + service_dma(); + } + } + + if (bus_state & USBD_BUSINTSTS_VBUSDETIF_Msk) + { + if (USBD->PHYCTL & USBD_PHYCTL_VBUSDET_Msk) + { + /* USB connect */ + USBD->PHYCTL |= USBD_PHYCTL_PHYEN_Msk | USBD_PHYCTL_DPPUEN_Msk; + } + else + { + /* USB disconnect */ + USBD->PHYCTL &= ~USBD_PHYCTL_DPPUEN_Msk; + } + } + + USBD->BUSINTSTS = bus_state & (USBD_BUSINTSTS_SOFIF_Msk | USBD_BUSINTSTS_RSTIF_Msk | USBD_BUSINTSTS_RESUMEIF_Msk | USBD_BUSINTSTS_SUSPENDIF_Msk | USBD_BUSINTSTS_HISPDIF_Msk | USBD_BUSINTSTS_DMADONEIF_Msk | USBD_BUSINTSTS_PHYCLKVLDIF_Msk | USBD_BUSINTSTS_VBUSDETIF_Msk); + } + + if (status & USBD_GINTSTS_CEPIF_Msk) + { + uint32_t cep_state = USBD->CEPINTSTS & USBD->CEPINTEN; + + if (cep_state & USBD_CEPINTSTS_SETUPPKIF_Msk) + { + /* get SETUP packet from USB buffer */ + uint8_t setup_packet[8]; + setup_packet[0] = (uint8_t)(USBD->SETUP1_0 >> 0); + setup_packet[1] = (uint8_t)(USBD->SETUP1_0 >> 8); + setup_packet[2] = (uint8_t)(USBD->SETUP3_2 >> 0); + setup_packet[3] = (uint8_t)(USBD->SETUP3_2 >> 8); + setup_packet[4] = (uint8_t)(USBD->SETUP5_4 >> 0); + setup_packet[5] = (uint8_t)(USBD->SETUP5_4 >> 8); + setup_packet[6] = (uint8_t)(USBD->SETUP7_6 >> 0); + setup_packet[7] = (uint8_t)(USBD->SETUP7_6 >> 8); + dcd_event_setup_received(0, setup_packet, true); + } + else if (cep_state & USBD_CEPINTSTS_INTKIF_Msk) + { + USBD->CEPINTSTS = USBD_CEPINTSTS_TXPKIF_Msk; + + if (!(cep_state & USBD_CEPINTSTS_STSDONEIF_Msk)) + { + USBD->CEPINTEN = USBD_CEPINTEN_TXPKIEN_Msk; + uint16_t bytes_now = tu_min16(ctrl_in_xfer.in_remaining_bytes, CFG_TUD_ENDPOINT0_SIZE); + for (int count = 0; count < bytes_now; count++) + USBD->CEPDAT_BYTE = *ctrl_in_xfer.data_ptr++; + ctrl_in_xfer.in_remaining_bytes -= bytes_now; + USBD_START_CEP_IN(bytes_now); + } + else + { + USBD->CEPINTEN = USBD_CEPINTEN_TXPKIEN_Msk | USBD_CEPINTEN_STSDONEIEN_Msk; + } + } + else if (cep_state & USBD_CEPINTSTS_TXPKIF_Msk) + { + USBD->CEPINTSTS = USBD_CEPINTSTS_STSDONEIF_Msk; + USBD_SET_CEP_STATE(USB_CEPCTL_NAKCLR); + + /* alert TinyUSB that the EP0 IN transfer has finished */ + if ( (0 == ctrl_in_xfer.in_remaining_bytes) || (0 == ctrl_in_xfer.total_bytes) ) + dcd_event_xfer_complete(0, 0x80, ctrl_in_xfer.total_bytes, XFER_RESULT_SUCCESS, true); + + if (ctrl_in_xfer.in_remaining_bytes) + { + USBD->CEPINTSTS = USBD_CEPINTSTS_INTKIF_Msk; + USBD->CEPINTEN = USBD_CEPINTEN_INTKIEN_Msk; + } + else + { + /* TinyUSB does its own fragmentation and ZLP for EP0; a transfer of zero means a ZLP */ + if (0 == ctrl_in_xfer.total_bytes) USBD->CEPCTL = USBD_CEPCTL_ZEROLEN_Msk; + + USBD->CEPINTSTS = USBD_CEPINTSTS_STSDONEIF_Msk; + USBD->CEPINTEN = USBD_CEPINTEN_SETUPPKIEN_Msk | USBD_CEPINTEN_STSDONEIEN_Msk; + } + } + else if (cep_state & USBD_CEPINTSTS_STSDONEIF_Msk) + { + /* given ACK from host has happened, we can now set the address (if not already done) */ + if((USBD->FADDR != assigned_address) && (USBD->FADDR == 0)) USBD->FADDR = assigned_address; + + if (configuration_changed) + { + for (enum ep_enum ep_index = PERIPH_EPA; ep_index < PERIPH_MAX_EP; ep_index++) + { + if (USBD->EP[ep_index].EPCFG & USBD_EPCFG_EPEN_Msk) USBD->EP[ep_index].EPRSPCTL = USBD_EPRSPCTL_TOGGLE_Msk; + } + configuration_changed = false; + } + + USBD->CEPINTEN = USBD_CEPINTEN_SETUPPKIEN_Msk; + } + + USBD->CEPINTSTS = cep_state; + + return; + } + + if (status & (USBD_GINTSTS_EPAIF_Msk | USBD_GINTSTS_EPBIF_Msk | USBD_GINTSTS_EPCIF_Msk | USBD_GINTSTS_EPDIF_Msk | USBD_GINTSTS_EPEIF_Msk | USBD_GINTSTS_EPFIF_Msk | USBD_GINTSTS_EPGIF_Msk | USBD_GINTSTS_EPHIF_Msk | USBD_GINTSTS_EPIIF_Msk | USBD_GINTSTS_EPJIF_Msk | USBD_GINTSTS_EPKIF_Msk | USBD_GINTSTS_EPLIF_Msk)) + { + /* service PERIPH_EPA through PERIPH_EPL */ + enum ep_enum ep_index; + uint32_t mask; + struct xfer_ctl_t *xfer; + USBD_EP_T *ep; + for (ep_index = PERIPH_EPA, mask = USBD_GINTSTS_EPAIF_Msk, xfer = &xfer_table[PERIPH_EPA], ep = &USBD->EP[PERIPH_EPA]; ep_index < PERIPH_MAX_EP; ep_index++, mask <<= 1, xfer++, ep++) + { + if(status & mask) + { + uint8_t const ep_addr = xfer->ep_addr; + bool const out_ep = !(ep_addr & TUSB_DIR_IN_MASK); + uint32_t ep_state = ep->EPINTSTS & ep->EPINTEN; + + if (out_ep) + { +#if 1 + xfer->dma_requested = true; + service_dma(); +#else + uint16_t const available_bytes = ep->EPDATCNT & USBD_EPDATCNT_DATCNT_Msk; + /* copy the data from the PC to the previously provided buffer */ + for (int count = 0; (count < available_bytes) && (xfer->out_bytes_so_far < xfer->total_bytes); count++, xfer->out_bytes_so_far++) + *xfer->data_ptr++ = ep->EPDAT_BYTE; + + /* when the transfer is finished, alert TinyUSB; otherwise, continue accepting more data */ + if ( (xfer->total_bytes == xfer->out_bytes_so_far) || (available_bytes < xfer->max_packet_size) ) + dcd_event_xfer_complete(0, ep_addr, xfer->out_bytes_so_far, XFER_RESULT_SUCCESS, true); +#endif + + } + else if (ep_state & USBD_EPINTSTS_BUFEMPTYIF_Msk) + { + /* send any remaining data */ + dcd_userEP_in_xfer(xfer, ep); + } + else if (ep_state & USBD_EPINTSTS_TXPKIF_Msk) + { + /* alert TinyUSB that we've finished */ + dcd_event_xfer_complete(0, ep_addr, xfer->total_bytes, XFER_RESULT_SUCCESS, true); + ep->EPINTEN = 0; + } + + ep->EPINTSTS = ep_state; + } + } + } +} + +void dcd_isr(uint8_t rhport) +{ + (void) rhport; + USBD_IRQHandler(); +} + +#endif diff --git a/src/tusb_option.h b/src/tusb_option.h index d39dd104..e0aa7a62 100644 --- a/src/tusb_option.h +++ b/src/tusb_option.h @@ -79,6 +79,7 @@ #define OPT_MCU_NUC121 800 #define OPT_MCU_NUC126 801 +#define OPT_MCU_NUC505 803 /** @} */ From 6ab799c7eb15918dfd86fb7bee982dc64b7fe53c Mon Sep 17 00:00:00 2001 From: Peter Lawrence <12226419+majbthrd@users.noreply.github.com> Date: Tue, 11 Feb 2020 14:34:07 -0600 Subject: [PATCH 227/267] atomic GPIO operation in BSP --- hw/bsp/nutiny_sdk_nuc505/nutiny_sdk_nuc505.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/hw/bsp/nutiny_sdk_nuc505/nutiny_sdk_nuc505.c b/hw/bsp/nutiny_sdk_nuc505/nutiny_sdk_nuc505.c index e666a10a..3a341de9 100644 --- a/hw/bsp/nutiny_sdk_nuc505/nutiny_sdk_nuc505.c +++ b/hw/bsp/nutiny_sdk_nuc505/nutiny_sdk_nuc505.c @@ -93,8 +93,11 @@ void board_led_write(bool state) { uint32_t current = (state) ? LED_STATE_ON : (1-LED_STATE_ON); current <<= LED_PIN; + uint32_t irq_state = __get_PRIMASK(); + __disable_irq(); current |= LED_PORT->DOUT & ~(1UL << LED_PIN); LED_PORT->DOUT = current; + __set_PRIMASK(irq_state); } uint32_t board_button_read(void) From 8d84bdff2177205be3ce97b4ecdc0247ae088606 Mon Sep 17 00:00:00 2001 From: Andrei Gramakov Date: Wed, 19 Feb 2020 12:45:29 +0100 Subject: [PATCH 228/267] add a number for esp32-s2 --- src/tusb_option.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/tusb_option.h b/src/tusb_option.h index d39dd104..97f14532 100644 --- a/src/tusb_option.h +++ b/src/tusb_option.h @@ -80,6 +80,8 @@ #define OPT_MCU_NUC121 800 #define OPT_MCU_NUC126 801 +#define OPT_MCU_ESP32S2 900 ///< Espressif ESP32-S2 + /** @} */ /** \defgroup group_supported_os Supported RTOS From b8ea0f0a6b11bff6a4bb3f63f09485b2445969de Mon Sep 17 00:00:00 2001 From: Chang Feng Date: Wed, 26 Feb 2020 13:07:15 +0800 Subject: [PATCH 229/267] Add langid support to descriptor string callback. Signed-off-by: Chang Feng --- src/device/usbd.c | 2 +- src/device/usbd.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/device/usbd.c b/src/device/usbd.c index 16670b94..68c5c516 100644 --- a/src/device/usbd.c +++ b/src/device/usbd.c @@ -809,7 +809,7 @@ static bool process_get_descriptor(uint8_t rhport, tusb_control_request_t const return false; }else { - uint8_t const* desc_str = (uint8_t const*) tud_descriptor_string_cb(desc_index); + uint8_t const* desc_str = (uint8_t const*) tud_descriptor_string_cb(desc_index, p_request->wIndex); TU_ASSERT(desc_str); // first byte of descriptor is its size diff --git a/src/device/usbd.h b/src/device/usbd.h index 847251ca..d80abf17 100644 --- a/src/device/usbd.h +++ b/src/device/usbd.h @@ -91,7 +91,7 @@ uint8_t const * tud_descriptor_configuration_cb(uint8_t index); // Invoked when received GET STRING DESCRIPTOR request // Application return pointer to descriptor, whose contents must exist long enough for transfer to complete -uint16_t const* tud_descriptor_string_cb(uint8_t index); +uint16_t const* tud_descriptor_string_cb(uint8_t index, uint16_t langid); // Invoked when device is mounted (configured) TU_ATTR_WEAK void tud_mount_cb(void); From 5c760e1f74a95a972df09f820f0df27a423dae44 Mon Sep 17 00:00:00 2001 From: Chang Feng Date: Wed, 26 Feb 2020 13:11:11 +0800 Subject: [PATCH 230/267] Add langid to example cdc_dual_ports. Signed-off-by: Chang Feng --- examples/device/cdc_dual_ports/src/usb_descriptors.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/examples/device/cdc_dual_ports/src/usb_descriptors.c b/examples/device/cdc_dual_ports/src/usb_descriptors.c index 1e24a0f1..1b1d171b 100644 --- a/examples/device/cdc_dual_ports/src/usb_descriptors.c +++ b/examples/device/cdc_dual_ports/src/usb_descriptors.c @@ -130,8 +130,10 @@ static uint16_t _desc_str[32]; // Invoked when received GET STRING DESCRIPTOR request // Application return pointer to descriptor, whose contents must exist long enough for transfer to complete -uint16_t const* tud_descriptor_string_cb(uint8_t index) +uint16_t const* tud_descriptor_string_cb(uint8_t index, uint16_t langid) { + (void) langid; + uint8_t chr_count; if ( index == 0) From 75afeb1266c217445e7834f0aef27f6416d765d0 Mon Sep 17 00:00:00 2001 From: Chang Feng Date: Wed, 26 Feb 2020 13:14:04 +0800 Subject: [PATCH 231/267] Add langid to example cdc_msc. Signed-off-by: Chang Feng --- examples/device/cdc_msc/src/usb_descriptors.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/examples/device/cdc_msc/src/usb_descriptors.c b/examples/device/cdc_msc/src/usb_descriptors.c index e8527df0..f91d1e6f 100644 --- a/examples/device/cdc_msc/src/usb_descriptors.c +++ b/examples/device/cdc_msc/src/usb_descriptors.c @@ -155,8 +155,10 @@ static uint16_t _desc_str[32]; // Invoked when received GET STRING DESCRIPTOR request // Application return pointer to descriptor, whose contents must exist long enough for transfer to complete -uint16_t const* tud_descriptor_string_cb(uint8_t index) +uint16_t const* tud_descriptor_string_cb(uint8_t index, uint16_t langid) { + (void) langid; + uint8_t chr_count; if ( index == 0) From b97d4709c2fcd588b7827fa76d8917d713548744 Mon Sep 17 00:00:00 2001 From: Chang Feng Date: Wed, 26 Feb 2020 13:37:02 +0800 Subject: [PATCH 232/267] Add langid to examples. Signed-off-by: Chang Feng --- examples/device/cdc_msc_hid_freertos/src/usb_descriptors.c | 4 +++- examples/device/dfu_rt/src/usb_descriptors.c | 4 +++- examples/device/hid_composite/src/usb_descriptors.c | 4 +++- examples/device/hid_generic_inout/src/usb_descriptors.c | 4 +++- examples/device/midi_test/src/usb_descriptors.c | 4 +++- examples/device/msc_dual_lun/src/usb_descriptors.c | 4 +++- examples/device/usbtmc/src/usb_descriptors.c | 4 +++- examples/device/webusb_serial/src/usb_descriptors.c | 4 +++- 8 files changed, 24 insertions(+), 8 deletions(-) diff --git a/examples/device/cdc_msc_hid_freertos/src/usb_descriptors.c b/examples/device/cdc_msc_hid_freertos/src/usb_descriptors.c index d60c9a58..84939e2d 100644 --- a/examples/device/cdc_msc_hid_freertos/src/usb_descriptors.c +++ b/examples/device/cdc_msc_hid_freertos/src/usb_descriptors.c @@ -184,8 +184,10 @@ static uint16_t _desc_str[32]; // Invoked when received GET STRING DESCRIPTOR request // Application return pointer to descriptor, whose contents must exist long enough for transfer to complete -uint16_t const* tud_descriptor_string_cb(uint8_t index) +uint16_t const* tud_descriptor_string_cb(uint8_t index, uint16_t langid) { + (void) langid; + uint8_t chr_count; if ( index == 0) diff --git a/examples/device/dfu_rt/src/usb_descriptors.c b/examples/device/dfu_rt/src/usb_descriptors.c index 0c708124..17b3fe87 100644 --- a/examples/device/dfu_rt/src/usb_descriptors.c +++ b/examples/device/dfu_rt/src/usb_descriptors.c @@ -193,8 +193,10 @@ static uint16_t _desc_str[32]; // Invoked when received GET STRING DESCRIPTOR request // Application return pointer to descriptor, whose contents must exist long enough for transfer to complete -uint16_t const* tud_descriptor_string_cb(uint8_t index) +uint16_t const* tud_descriptor_string_cb(uint8_t index, uint16_t langid) { + (void) langid; + size_t chr_count; if ( index == 0) diff --git a/examples/device/hid_composite/src/usb_descriptors.c b/examples/device/hid_composite/src/usb_descriptors.c index 01f2cb59..19689c90 100644 --- a/examples/device/hid_composite/src/usb_descriptors.c +++ b/examples/device/hid_composite/src/usb_descriptors.c @@ -134,8 +134,10 @@ static uint16_t _desc_str[32]; // Invoked when received GET STRING DESCRIPTOR request // Application return pointer to descriptor, whose contents must exist long enough for transfer to complete -uint16_t const* tud_descriptor_string_cb(uint8_t index) +uint16_t const* tud_descriptor_string_cb(uint8_t index, uint16_t langid) { + (void) langid; + uint8_t chr_count; if ( index == 0) diff --git a/examples/device/hid_generic_inout/src/usb_descriptors.c b/examples/device/hid_generic_inout/src/usb_descriptors.c index 07989c5f..87611a43 100644 --- a/examples/device/hid_generic_inout/src/usb_descriptors.c +++ b/examples/device/hid_generic_inout/src/usb_descriptors.c @@ -132,8 +132,10 @@ static uint16_t _desc_str[32]; // Invoked when received GET STRING DESCRIPTOR request // Application return pointer to descriptor, whose contents must exist long enough for transfer to complete -uint16_t const* tud_descriptor_string_cb(uint8_t index) +uint16_t const* tud_descriptor_string_cb(uint8_t index, uint16_t langid) { + (void) langid; + uint8_t chr_count; if ( index == 0) diff --git a/examples/device/midi_test/src/usb_descriptors.c b/examples/device/midi_test/src/usb_descriptors.c index 2305c9f6..94940482 100644 --- a/examples/device/midi_test/src/usb_descriptors.c +++ b/examples/device/midi_test/src/usb_descriptors.c @@ -123,8 +123,10 @@ static uint16_t _desc_str[32]; // Invoked when received GET STRING DESCRIPTOR request // Application return pointer to descriptor, whose contents must exist long enough for transfer to complete -uint16_t const* tud_descriptor_string_cb(uint8_t index) +uint16_t const* tud_descriptor_string_cb(uint8_t index, uint16_t langid) { + (void) langid; + uint8_t chr_count; if ( index == 0) diff --git a/examples/device/msc_dual_lun/src/usb_descriptors.c b/examples/device/msc_dual_lun/src/usb_descriptors.c index e0a5904a..1abc15ca 100644 --- a/examples/device/msc_dual_lun/src/usb_descriptors.c +++ b/examples/device/msc_dual_lun/src/usb_descriptors.c @@ -121,8 +121,10 @@ static uint16_t _desc_str[32]; // Invoked when received GET STRING DESCRIPTOR request // Application return pointer to descriptor, whose contents must exist long enough for transfer to complete -uint16_t const* tud_descriptor_string_cb(uint8_t index) +uint16_t const* tud_descriptor_string_cb(uint8_t index, uint16_t langid) { + (void) langid; + uint8_t chr_count; if ( index == 0) diff --git a/examples/device/usbtmc/src/usb_descriptors.c b/examples/device/usbtmc/src/usb_descriptors.c index 27e1bdaa..92b1dce6 100644 --- a/examples/device/usbtmc/src/usb_descriptors.c +++ b/examples/device/usbtmc/src/usb_descriptors.c @@ -216,8 +216,10 @@ static uint16_t _desc_str[32]; // Invoked when received GET STRING DESCRIPTOR request // Application return pointer to descriptor, whose contents must exist long enough for transfer to complete -uint16_t const* tud_descriptor_string_cb(uint8_t index) +uint16_t const* tud_descriptor_string_cb(uint8_t index, uint16_t langid) { + (void) langid; + size_t chr_count; if ( index == 0) diff --git a/examples/device/webusb_serial/src/usb_descriptors.c b/examples/device/webusb_serial/src/usb_descriptors.c index 740defe4..2925a66c 100644 --- a/examples/device/webusb_serial/src/usb_descriptors.c +++ b/examples/device/webusb_serial/src/usb_descriptors.c @@ -204,8 +204,10 @@ static uint16_t _desc_str[32]; // Invoked when received GET STRING DESCRIPTOR request // Application return pointer to descriptor, whose contents must exist long enough for transfer to complete -uint16_t const* tud_descriptor_string_cb(uint8_t index) +uint16_t const* tud_descriptor_string_cb(uint8_t index, uint16_t langid) { + (void) langid; + uint8_t chr_count; if ( index == 0) From 8d97e5819287d1317ecd4eeee492f97aa5e820a2 Mon Sep 17 00:00:00 2001 From: Chang Feng Date: Wed, 26 Feb 2020 13:37:26 +0800 Subject: [PATCH 233/267] Add langid to tests. Signed-off-by: Chang Feng --- test/test/device/msc/test_msc_device.c | 4 +++- test/test/device/usbd/test_usbd.c | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/test/test/device/msc/test_msc_device.c b/test/test/device/msc/test_msc_device.c index 5003ac83..43a8e743 100644 --- a/test/test/device/msc/test_msc_device.c +++ b/test/test/device/msc/test_msc_device.c @@ -184,8 +184,10 @@ uint8_t const * tud_descriptor_configuration_cb(uint8_t index) return desc_configuration; } -uint16_t const* tud_descriptor_string_cb(uint8_t index) +uint16_t const* tud_descriptor_string_cb(uint8_t index, uint16_t langid) { + (void) langid; + return NULL; } diff --git a/test/test/device/usbd/test_usbd.c b/test/test/device/usbd/test_usbd.c index 24535310..af30aaf8 100644 --- a/test/test/device/usbd/test_usbd.c +++ b/test/test/device/usbd/test_usbd.c @@ -111,8 +111,10 @@ uint8_t const * tud_descriptor_configuration_cb(uint8_t index) return desc_configuration; } -uint16_t const* tud_descriptor_string_cb(uint8_t index) +uint16_t const* tud_descriptor_string_cb(uint8_t index, uint16_t langid) { + (void) langid; + return NULL; } From fee79d746604f671483f5872337ea366f2d2c1a2 Mon Sep 17 00:00:00 2001 From: Peter Lawrence <12226419+majbthrd@users.noreply.github.com> Date: Mon, 2 Mar 2020 21:15:01 -0600 Subject: [PATCH 234/267] add CDC-ECM/RNDIS/CDC-EEM network device class with example --- .gitmodules | 5 +- examples/device/lwip_webserver/Makefile | 57 +++ examples/device/lwip_webserver/src/arch/cc.h | 75 ++++ examples/device/lwip_webserver/src/lwipopts.h | 57 +++ examples/device/lwip_webserver/src/main.c | 214 +++++++++++ .../device/lwip_webserver/src/tusb_config.h | 90 +++++ .../lwip_webserver/src/usb_descriptors.c | 199 ++++++++++ .../lwip_webserver/src/usb_descriptors.h | 28 ++ examples/rules.mk | 1 + lib/lwip | 1 + lib/networking/dhserver.c | 347 ++++++++++++++++++ lib/networking/dhserver.h | 63 ++++ lib/networking/dnserver.c | 200 ++++++++++ lib/networking/dnserver.h | 47 +++ lib/networking/ndis.h | 266 ++++++++++++++ lib/networking/rndis_protocol.h | 307 ++++++++++++++++ lib/networking/rndis_reports.c | 303 +++++++++++++++ src/class/net/net_device.c | 345 +++++++++++++++++ src/class/net/net_device.h | 84 +++++ src/device/usbd.c | 18 + src/device/usbd.h | 84 +++++ src/tusb.h | 4 + src/tusb_option.h | 12 + 23 files changed, 2806 insertions(+), 1 deletion(-) create mode 100644 examples/device/lwip_webserver/Makefile create mode 100644 examples/device/lwip_webserver/src/arch/cc.h create mode 100644 examples/device/lwip_webserver/src/lwipopts.h create mode 100644 examples/device/lwip_webserver/src/main.c create mode 100644 examples/device/lwip_webserver/src/tusb_config.h create mode 100644 examples/device/lwip_webserver/src/usb_descriptors.c create mode 100644 examples/device/lwip_webserver/src/usb_descriptors.h create mode 160000 lib/lwip create mode 100644 lib/networking/dhserver.c create mode 100644 lib/networking/dhserver.h create mode 100644 lib/networking/dnserver.c create mode 100644 lib/networking/dnserver.h create mode 100644 lib/networking/ndis.h create mode 100644 lib/networking/rndis_protocol.h create mode 100644 lib/networking/rndis_reports.c create mode 100644 src/class/net/net_device.c create mode 100644 src/class/net/net_device.h diff --git a/.gitmodules b/.gitmodules index 18b627bc..0dda17d6 100644 --- a/.gitmodules +++ b/.gitmodules @@ -21,4 +21,7 @@ url = https://github.com/hathach/microchip_driver.git [submodule "hw/mcu/nuvoton"] path = hw/mcu/nuvoton - url = https://github.com/majbthrd/nuc_driver.git \ No newline at end of file + url = https://github.com/majbthrd/nuc_driver.git +[submodule "lib/lwip"] + path = lib/lwip + url = https://git.savannah.nongnu.org/git/lwip.git diff --git a/examples/device/lwip_webserver/Makefile b/examples/device/lwip_webserver/Makefile new file mode 100644 index 00000000..a153c30b --- /dev/null +++ b/examples/device/lwip_webserver/Makefile @@ -0,0 +1,57 @@ +include ../../../tools/top.mk +include ../../make.mk + +CFLAGS += \ + -DPBUF_POOL_SIZE=2 \ + -DTCP_WND=2*TCP_MSS \ + -DHTTPD_USE_CUSTOM_FSDATA=0 + +INC += \ + src \ + $(TOP)/hw \ + $(TOP)/lib/lwip/src/include \ + $(TOP)/lib/lwip/src/include/ipv4 \ + $(TOP)/lib/lwip/src/include/lwip/apps \ + $(TOP)/lib/networking + +# Example source +EXAMPLE_SOURCE += $(wildcard src/*.c) +SRC_C += $(addprefix $(CURRENT_PATH)/, $(EXAMPLE_SOURCE)) +SRC_C += \ + lib/lwip/src/core/altcp.c \ + lib/lwip/src/core/altcp_alloc.c \ + lib/lwip/src/core/altcp_tcp.c \ + lib/lwip/src/core/def.c \ + lib/lwip/src/core/dns.c \ + lib/lwip/src/core/inet_chksum.c \ + lib/lwip/src/core/init.c \ + lib/lwip/src/core/ip.c \ + lib/lwip/src/core/mem.c \ + lib/lwip/src/core/memp.c \ + lib/lwip/src/core/netif.c \ + lib/lwip/src/core/pbuf.c \ + lib/lwip/src/core/raw.c \ + lib/lwip/src/core/stats.c \ + lib/lwip/src/core/sys.c \ + lib/lwip/src/core/tcp.c \ + lib/lwip/src/core/tcp_in.c \ + lib/lwip/src/core/tcp_out.c \ + lib/lwip/src/core/timeouts.c \ + lib/lwip/src/core/udp.c \ + lib/lwip/src/core/ipv4/autoip.c \ + lib/lwip/src/core/ipv4/dhcp.c \ + lib/lwip/src/core/ipv4/etharp.c \ + lib/lwip/src/core/ipv4/icmp.c \ + lib/lwip/src/core/ipv4/igmp.c \ + lib/lwip/src/core/ipv4/ip4.c \ + lib/lwip/src/core/ipv4/ip4_addr.c \ + lib/lwip/src/core/ipv4/ip4_frag.c \ + lib/lwip/src/netif/ethernet.c \ + lib/lwip/src/netif/slipif.c \ + lib/lwip/src/apps/http/httpd.c \ + lib/lwip/src/apps/http/fs.c \ + lib/networking/dhserver.c \ + lib/networking/dnserver.c \ + lib/networking/rndis_reports.c + +include ../../rules.mk diff --git a/examples/device/lwip_webserver/src/arch/cc.h b/examples/device/lwip_webserver/src/arch/cc.h new file mode 100644 index 00000000..56a0cacf --- /dev/null +++ b/examples/device/lwip_webserver/src/arch/cc.h @@ -0,0 +1,75 @@ +/* + * 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 "cpu.h" + +typedef int sys_prot_t; + + + +/* define compiler specific symbols */ +#if defined (__ICCARM__) + +#define PACK_STRUCT_BEGIN +#define PACK_STRUCT_STRUCT +#define PACK_STRUCT_END +#define PACK_STRUCT_FIELD(x) x +#define PACK_STRUCT_USE_INCLUDES + +#elif defined (__CC_ARM) + +#define PACK_STRUCT_BEGIN __packed +#define PACK_STRUCT_STRUCT +#define PACK_STRUCT_END +#define PACK_STRUCT_FIELD(x) x + +#elif defined (__GNUC__) + +#define PACK_STRUCT_BEGIN +#define PACK_STRUCT_STRUCT __attribute__ ((__packed__)) +#define PACK_STRUCT_END +#define PACK_STRUCT_FIELD(x) x + +#elif defined (__TASKING__) + +#define PACK_STRUCT_BEGIN +#define PACK_STRUCT_STRUCT +#define PACK_STRUCT_END +#define PACK_STRUCT_FIELD(x) x + +#endif + +#define LWIP_PLATFORM_ASSERT(x) do { if(!(x)) while(1); } while(0) + +#endif /* __CC_H__ */ diff --git a/examples/device/lwip_webserver/src/lwipopts.h b/examples/device/lwip_webserver/src/lwipopts.h new file mode 100644 index 00000000..23319592 --- /dev/null +++ b/examples/device/lwip_webserver/src/lwipopts.h @@ -0,0 +1,57 @@ +/* + * 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: Simon Goldschmidt + * + */ +#ifndef __LWIPOPTS_H__ +#define __LWIPOPTS_H__ + +/* Prevent having to link sys_arch.c (we don't test the API layers in unit tests) */ +#define NO_SYS 1 +#define MEM_ALIGNMENT 4 +#define LWIP_RAW 1 +#define LWIP_NETCONN 0 +#define LWIP_SOCKET 0 +#define LWIP_DHCP 0 +#define LWIP_ICMP 1 +#define LWIP_UDP 1 +#define LWIP_TCP 1 +#define ETH_PAD_SIZE 0 +#define LWIP_IP_ACCEPT_UDP_PORT(p) ((p) == PP_NTOHS(67)) + +#define TCP_MSS (1500 /*mtu*/ - 20 /*iphdr*/ - 20 /*tcphhr*/) +#define TCP_SND_BUF (2 * TCP_MSS) + +#define ETHARP_SUPPORT_STATIC_ENTRIES 1 + +#define LWIP_HTTPD_CGI 0 +#define LWIP_HTTPD_SSI 0 +#define LWIP_HTTPD_SSI_INCLUDE_TAG 0 + +#endif /* __LWIPOPTS_H__ */ diff --git a/examples/device/lwip_webserver/src/main.c b/examples/device/lwip_webserver/src/main.c new file mode 100644 index 00000000..364a2678 --- /dev/null +++ b/examples/device/lwip_webserver/src/main.c @@ -0,0 +1,214 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2020 Peter Lawrence + * + * influenced by lrndis https://github.com/fetisov/lrndis + * + * 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. + * + */ + +/* +depending on the value of CFG_TUD_NET (tusb_config.h), this can be a CDC-ECM, RNDIS, or CDC-EEM USB virtual network adapter + +CDC-ECM should be valid on Linux and MacOS hosts +RNDIS should be valid on Linux and Windows hosts +CDC-EEM should be valid on Linux hosts + +You *must* customize tusb_config.h to set the CFG_TUD_NET definition to the type of these network adapters to emulate. + +The MCU appears to the host as IP address 192.168.7.1, and provides a DHCP server, DNS server, and web server. +*/ + +#include "bsp/board.h" +#include "tusb.h" + +#include "dhserver.h" +#include "dnserver.h" +#include "lwip/init.h" +#include "httpd.h" + +/* lwip context */ +static struct netif netif_data; + +/* shared between network_recv_callback() and service_traffic() */ +static struct pbuf *received_frame; + +/* this is used by this code, ./class/net/net_driver.c, and usb_descriptors.c */ +/* ideally speaking, this should be generated from the hardware's unique ID (if available) */ +const uint8_t network_mac_address[6] = {0x20,0x89,0x84,0x6A,0x96,0x00}; + +/* network parameters of this MCU */ +static const ip_addr_t ipaddr = IPADDR4_INIT_BYTES(192, 168, 7, 1); +static const ip_addr_t netmask = IPADDR4_INIT_BYTES(255, 255, 255, 0); +static const ip_addr_t gateway = IPADDR4_INIT_BYTES(0, 0, 0, 0); + +/* database IP addresses that can be offered to the host; this must be in RAM to store assigned MAC addresses */ +static dhcp_entry_t entries[] = +{ + /* mac ip address subnet mask lease time */ + { {0}, {192, 168, 7, 2}, {255, 255, 255, 0}, 24 * 60 * 60 }, + { {0}, {192, 168, 7, 3}, {255, 255, 255, 0}, 24 * 60 * 60 }, + { {0}, {192, 168, 7, 4}, {255, 255, 255, 0}, 24 * 60 * 60 } +}; + +/* DHCP configuration parameters, leveraging "entries" above */ +static const dhcp_config_t dhcp_config = +{ + {192, 168, 7, 1}, 67, /* server address (self), port */ + {192, 168, 7, 1}, /* dns server (self) */ + "usb", /* dns suffix */ + TU_ARRAY_SIZE(entries), /* number of entries */ + entries /* pointer to entries */ +}; + +static err_t linkoutput_fn(struct netif *netif, struct pbuf *p) +{ + (void)netif; + + for (;;) + { + /* if TinyUSB isn't ready, we must signal back to lwip that there is nothing we can do */ + if (!tud_ready()) + return ERR_USE; + + /* if the network driver can accept another packet, we make it happen */ + if (network_can_xmit()) + { + network_xmit(p); + return ERR_OK; + } + + /* transfer execution to TinyUSB in the hopes that it will finish transmitting the prior packet */ + tud_task(); + } +} + +static err_t output_fn(struct netif *netif, struct pbuf *p, const ip_addr_t *addr) +{ + return etharp_output(netif, p, addr); +} + +static err_t netif_init_cb(struct netif *netif) +{ + LWIP_ASSERT("netif != NULL", (netif != NULL)); + netif->mtu = CFG_TUD_NET_MTU; + netif->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP | NETIF_FLAG_LINK_UP | NETIF_FLAG_UP; + netif->state = NULL; + netif->name[0] = 'E'; + netif->name[1] = 'X'; + netif->linkoutput = linkoutput_fn; + netif->output = output_fn; + return ERR_OK; +} + +static void init_lwip(void) +{ + struct netif *netif = &netif_data; + + lwip_init(); + netif->hwaddr_len = sizeof(network_mac_address); + memcpy(netif->hwaddr, network_mac_address, sizeof(network_mac_address)); + + netif = netif_add(netif, &ipaddr, &netmask, &gateway, NULL, netif_init_cb, ip_input); + netif_set_default(netif); +} + +/* handle any DNS requests from dns-server */ +bool dns_query_proc(const char *name, ip_addr_t *addr) +{ + if (0 == strcmp(name, "tiny.usb")) + { + *addr = ipaddr; + return true; + } + return false; +} + +bool network_recv_callback(struct pbuf *p) +{ + /* this shouldn't happen, but if we get another packet before + parsing the previous, we must signal our inability to accept it */ + if (received_frame) return false; + + /* store away the pointer for service_traffic() to later handle */ + received_frame = p; + return true; +} + +static void service_traffic(void) +{ + /* handle any packet received by network_recv_callback() */ + if (received_frame) + { + ethernet_input(received_frame, &netif_data); + pbuf_free(received_frame); + received_frame = NULL; + network_recv_renew(); + } +} + +void network_init_callback(void) +{ + /* if the network is re-initializing and we have a leftover packet, we must do a cleanup */ + if (received_frame) + { + pbuf_free(received_frame); + received_frame = NULL; + } +} + +int main(void) +{ + /* initialize TinyUSB */ + board_init(); + tusb_init(); + + /* initialize lwip, dhcp-server, dns-server, and http */ + init_lwip(); + while (!netif_is_up(&netif_data)); + while (dhserv_init(&dhcp_config) != ERR_OK); + while (dnserv_init(&ipaddr, 53, dns_query_proc) != ERR_OK); + httpd_init(); + + while (1) + { + tud_task(); + service_traffic(); + } + + return 0; +} + +/* lwip has provision for using a mutex, when applicable */ +sys_prot_t sys_arch_protect(void) +{ + return 0; +} +void sys_arch_unprotect(sys_prot_t pval) +{ + (void)pval; +} + +/* lwip needs a millisecond time source, and the TinyUSB board support code has one available */ +uint32_t sys_now(void) +{ + return board_millis(); +} diff --git a/examples/device/lwip_webserver/src/tusb_config.h b/examples/device/lwip_webserver/src/tusb_config.h new file mode 100644 index 00000000..329fc80b --- /dev/null +++ b/examples/device/lwip_webserver/src/tusb_config.h @@ -0,0 +1,90 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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 _TUSB_CONFIG_H_ +#define _TUSB_CONFIG_H_ + +#ifdef __cplusplus + extern "C" { +#endif + +//-------------------------------------------------------------------- +// COMMON CONFIGURATION +//-------------------------------------------------------------------- + +// defined by compiler flags for flexibility +#ifndef CFG_TUSB_MCU + #error CFG_TUSB_MCU must be defined +#endif + +#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX +#define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED) +#else +#define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE +#endif + +#define CFG_TUSB_OS OPT_OS_NONE + +// CFG_TUSB_DEBUG is defined by compiler in DEBUG build +// #define CFG_TUSB_DEBUG 0 + +/* USB DMA on some MCUs can only access a specific SRAM region with restriction on alignment. + * Tinyusb use follows macros to declare transferring memory so that they can be put + * into those specific section. + * e.g + * - CFG_TUSB_MEM SECTION : __attribute__ (( section(".usb_ram") )) + * - CFG_TUSB_MEM_ALIGN : __attribute__ ((aligned(4))) + */ +#ifndef CFG_TUSB_MEM_SECTION +#define CFG_TUSB_MEM_SECTION +#endif + +#ifndef CFG_TUSB_MEM_ALIGN +#define CFG_TUSB_MEM_ALIGN __attribute__ ((aligned(4))) +#endif + +//-------------------------------------------------------------------- +// DEVICE CONFIGURATION +//-------------------------------------------------------------------- + +#ifndef CFG_TUD_ENDPOINT0_SIZE +#define CFG_TUD_ENDPOINT0_SIZE 64 +#endif + +//------------- CLASS -------------// +#define CFG_TUD_CDC 0 +#define CFG_TUD_MSC 0 +#define CFG_TUD_HID 0 +#define CFG_TUD_MIDI 0 +#define CFG_TUD_VENDOR 0 +//#define CFG_TUD_NET OPT_NET_ECM +#define CFG_TUD_NET OPT_NET_RNDIS +//#define CFG_TUD_NET OPT_NET_EEM + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_CONFIG_H_ */ diff --git a/examples/device/lwip_webserver/src/usb_descriptors.c b/examples/device/lwip_webserver/src/usb_descriptors.c new file mode 100644 index 00000000..803c99c0 --- /dev/null +++ b/examples/device/lwip_webserver/src/usb_descriptors.c @@ -0,0 +1,199 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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 "tusb.h" +#include "usb_descriptors.h" + +/* A combination of interfaces must have a unique product id, since PC will save device driver after the first plug. + * Same VID/PID with different interface e.g MSC (first), then CDC (later) will possibly cause system error on PC. + * + * Auto ProductID layout's Bitmap: + * [MSB] NET1:NET0 | VENDOR | MIDI | HID | MSC | CDC [LSB] + */ +#define _PID_MAP(itf, n) ( (CFG_TUD_##itf) << (n) ) +#define USB_PID (0x4000 | _PID_MAP(CDC, 0) | _PID_MAP(MSC, 1) | _PID_MAP(HID, 2) | \ + _PID_MAP(MIDI, 3) | _PID_MAP(VENDOR, 4) | _PID_MAP(NET, 5) ) + +//--------------------------------------------------------------------+ +// Device Descriptors +//--------------------------------------------------------------------+ +tusb_desc_device_t const desc_device = +{ + .bLength = sizeof(tusb_desc_device_t), + .bDescriptorType = TUSB_DESC_DEVICE, + .bcdUSB = 0x0200, + + .bDeviceClass = TUSB_CLASS_UNSPECIFIED, + .bDeviceSubClass = 0, + .bDeviceProtocol = 0, + .bMaxPacketSize0 = CFG_TUD_ENDPOINT0_SIZE, + + .idVendor = 0xCafe, + .idProduct = USB_PID, + .bcdDevice = 0x0100, + + .iManufacturer = 0x01, + .iProduct = 0x02, + .iSerialNumber = 0x03, + + .bNumConfigurations = 0x01 +}; + +// Invoked when received GET DEVICE DESCRIPTOR +// Application return pointer to descriptor +uint8_t const * tud_descriptor_device_cb(void) +{ + return (uint8_t const *) &desc_device; +} + +//--------------------------------------------------------------------+ +// Configuration Descriptor +//--------------------------------------------------------------------+ +enum +{ + ITF_NUM_CDC = 0, + ITF_NUM_CDC_DATA, + ITF_NUM_TOTAL +}; + +enum +{ + STR_LANGID = 0, + STR_MANUFACTURER, + STR_PRODUCT, + STR_ITFNAME, + STR_MAC, +}; + +#if CFG_TUD_NET == OPT_NET_ECM +#define CONFIG_TOTAL_LEN (TUD_CONFIG_DESC_LEN + TUD_CDC_ECM_DESC_LEN) +#elif CFG_TUD_NET == OPT_NET_RNDIS +#define CONFIG_TOTAL_LEN (TUD_CONFIG_DESC_LEN + TUD_RNDIS_DESC_LEN) +#elif CFG_TUD_NET == OPT_NET_EEM +#define CONFIG_TOTAL_LEN (TUD_CONFIG_DESC_LEN + TUD_CDC_EEM_DESC_LEN) +#endif + +#if CFG_TUSB_MCU == OPT_MCU_LPC175X_6X || CFG_TUSB_MCU == OPT_MCU_LPC177X_8X || CFG_TUSB_MCU == OPT_MCU_LPC40XX + // LPC 17xx and 40xx endpoint type (bulk/interrupt/iso) are fixed by its number + // 0 control, 1 In, 2 Bulk, 3 Iso, 4 In etc ... + #define EPNUM_CDC 2 +#else + #define EPNUM_CDC 2 +#endif + +uint8_t const desc_configuration[] = +{ + // Interface count, string index, total length, attribute, power in mA + TUD_CONFIG_DESCRIPTOR(ITF_NUM_TOTAL, 0, CONFIG_TOTAL_LEN, 0, 100), + +#if CFG_TUD_NET == OPT_NET_ECM + // Interface number, description string index, MAC address string index, EP notification address and size, EP data address (out, in), and size, max segment size. + TUD_CDC_ECM_DESCRIPTOR(ITF_NUM_CDC, STR_ITFNAME, STR_MAC, 0x81, 8, EPNUM_CDC, 0x80 | EPNUM_CDC, CFG_TUD_NET_ENDPOINT_SIZE, CFG_TUD_NET_MTU), +#elif CFG_TUD_NET == OPT_NET_RNDIS + // Interface number, string index, EP notification address and size, EP data address (out, in) and size. + TUD_RNDIS_DESCRIPTOR(ITF_NUM_CDC, STR_ITFNAME, 0x81, 8, EPNUM_CDC, 0x80 | EPNUM_CDC, CFG_TUD_NET_ENDPOINT_SIZE), +#elif CFG_TUD_NET == OPT_NET_EEM + // Interface number, description string index, EP data address (out, in) and size. + TUD_CDC_EEM_DESCRIPTOR(ITF_NUM_CDC, STR_ITFNAME, EPNUM_CDC, 0x80 | EPNUM_CDC, CFG_TUD_NET_ENDPOINT_SIZE), +#endif +}; + +// Invoked when received GET CONFIGURATION DESCRIPTOR +// Application return pointer to descriptor +// Descriptor contents must exist long enough for transfer to complete +uint8_t const * tud_descriptor_configuration_cb(uint8_t index) +{ + (void) index; // for multiple configurations + return desc_configuration; +} + +//--------------------------------------------------------------------+ +// String Descriptors +//--------------------------------------------------------------------+ + +// array of pointer to string descriptors +char const* string_desc_arr [] = +{ + [STR_LANGID] = (const char[]) { 0x09, 0x04 }, // supported language is English (0x0409) + [STR_MANUFACTURER] = "TinyUSB", // Manufacturer + [STR_PRODUCT] = "TinyUSB Device", // Product + [STR_ITFNAME] = // CDC-ECM Interface +#if CFG_TUD_NET == OPT_NET_ECM + "TinyUSB CDC-ECM", +#elif CFG_TUD_NET == OPT_NET_RNDIS + "TinyUSB RNDIS", +#elif CFG_TUD_NET == OPT_NET_EEM + "TinyUSB CDC-EEM", +#endif +}; + +static uint16_t _desc_str[32]; + +// Invoked when received GET STRING DESCRIPTOR request +// Application return pointer to descriptor, whose contents must exist long enough for transfer to complete +uint16_t const* tud_descriptor_string_cb(uint8_t index, uint16_t langid) +{ + (void)langid; + + unsigned chr_count = 0; + + if (STR_LANGID == index) + { + memcpy(&_desc_str[1], string_desc_arr[0], 2); + chr_count = 1; + } + else if (STR_MAC == index) + { + // Convert MAC address into UTF-16 + + for (unsigned i=0; i> 4) & 0xf]; + _desc_str[1+chr_count++] = "0123456789ABCDEF"[(network_mac_address[i] >> 0) & 0xf]; + } + } + else + { + // Convert ASCII string into UTF-16 + + if ( !(index < sizeof(string_desc_arr)/sizeof(string_desc_arr[0])) ) return NULL; + + const char* str = string_desc_arr[index]; + + // Cap at max char + chr_count = strlen(str); + if ( chr_count > (TU_ARRAY_SIZE(_desc_str) - 1)) chr_count = TU_ARRAY_SIZE(_desc_str) - 1; + + for (unsigned i=0; i + * + * 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 "dhserver.h" + +/* DHCP message type */ +#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 options */ +enum DHCP_OPTIONS +{ + DHCP_PAD = 0, + DHCP_SUBNETMASK = 1, + DHCP_ROUTER = 3, + DHCP_DNSSERVER = 6, + DHCP_HOSTNAME = 12, + DHCP_DNSDOMAIN = 15, + DHCP_MTU = 26, + DHCP_BROADCAST = 28, + DHCP_PERFORMROUTERDISC = 31, + DHCP_STATICROUTE = 33, + DHCP_NISDOMAIN = 40, + DHCP_NISSERVER = 41, + DHCP_NTPSERVER = 42, + DHCP_VENDOR = 43, + DHCP_IPADDRESS = 50, + DHCP_LEASETIME = 51, + DHCP_OPTIONSOVERLOADED = 52, + DHCP_MESSAGETYPE = 53, + DHCP_SERVERID = 54, + DHCP_PARAMETERREQUESTLIST = 55, + DHCP_MESSAGE = 56, + DHCP_MAXMESSAGESIZE = 57, + DHCP_RENEWALTIME = 58, + DHCP_REBINDTIME = 59, + DHCP_CLASSID = 60, + DHCP_CLIENTID = 61, + DHCP_USERCLASS = 77, /* RFC 3004 */ + DHCP_FQDN = 81, + DHCP_DNSSEARCH = 119, /* RFC 3397 */ + DHCP_CSR = 121, /* RFC 3442 */ + DHCP_MSCSR = 249, /* MS code for RFC 3442 */ + DHCP_END = 255 +}; + +typedef struct +{ + uint8_t dp_op; /* packet opcode type */ + uint8_t dp_htype; /* hardware addr type */ + uint8_t dp_hlen; /* hardware addr length */ + uint8_t dp_hops; /* gateway hops */ + uint32_t dp_xid; /* transaction ID */ + uint16_t dp_secs; /* seconds since boot began */ + uint16_t dp_flags; + uint8_t dp_ciaddr[4]; /* client IP address */ + uint8_t dp_yiaddr[4]; /* 'your' IP address */ + uint8_t dp_siaddr[4]; /* server IP address */ + uint8_t dp_giaddr[4]; /* gateway IP address */ + uint8_t dp_chaddr[16]; /* client hardware address */ + uint8_t dp_legacy[192]; + uint8_t dp_magic[4]; + uint8_t dp_options[275]; /* options area */ +} DHCP_TYPE; + +DHCP_TYPE dhcp_data; +static struct udp_pcb *pcb = NULL; +static const dhcp_config_t *config = NULL; + +char magic_cookie[] = {0x63,0x82,0x53,0x63}; + +static uint32_t get_ip(const uint8_t *pnt) +{ + uint32_t result; + memcpy(&result, pnt, sizeof(result)); + return result; +} + +static void set_ip(uint8_t *pnt, uint32_t value) +{ + memcpy(pnt, &value, sizeof(value)); +} + +static dhcp_entry_t *entry_by_ip(uint32_t ip) +{ + int i; + for (i = 0; i < config->num_entry; i++) + if (get_ip(config->entries[i].addr) == ip) + return &config->entries[i]; + return NULL; +} + +static dhcp_entry_t *entry_by_mac(uint8_t *mac) +{ + int i; + for (i = 0; i < config->num_entry; i++) + if (memcmp(config->entries[i].mac, mac, 6) == 0) + return &config->entries[i]; + return NULL; +} + +static __inline bool is_vacant(dhcp_entry_t *entry) +{ + return memcmp("\0\0\0\0\0", entry->mac, 6) == 0; +} + +static dhcp_entry_t *vacant_address(void) +{ + int i; + for (i = 0; i < config->num_entry; i++) + if (is_vacant(config->entries + i)) + return config->entries + i; + return NULL; +} + +static __inline void free_entry(dhcp_entry_t *entry) +{ + memset(entry->mac, 0, 6); +} + +uint8_t *find_dhcp_option(uint8_t *attrs, int size, uint8_t attr) +{ + int i = 0; + while ((i + 1) < size) + { + int next = i + attrs[i + 1] + 2; + if (next > size) return NULL; + if (attrs[i] == attr) + return attrs + i; + i = next; + } + return NULL; +} + +int fill_options(void *dest, + uint8_t msg_type, + const char *domain, + uint32_t dns, + int lease_time, + uint32_t serverid, + uint32_t router, + uint32_t subnet) +{ + uint8_t *ptr = (uint8_t *)dest; + /* ACK message type */ + *ptr++ = 53; + *ptr++ = 1; + *ptr++ = msg_type; + + /* dhcp server identifier */ + *ptr++ = DHCP_SERVERID; + *ptr++ = 4; + set_ip(ptr, serverid); + ptr += 4; + + /* lease time */ + *ptr++ = DHCP_LEASETIME; + *ptr++ = 4; + *ptr++ = (lease_time >> 24) & 0xFF; + *ptr++ = (lease_time >> 16) & 0xFF; + *ptr++ = (lease_time >> 8) & 0xFF; + *ptr++ = (lease_time >> 0) & 0xFF; + + /* subnet mask */ + *ptr++ = DHCP_SUBNETMASK; + *ptr++ = 4; + set_ip(ptr, subnet); + ptr += 4; + + /* router */ + if (router != 0) + { + *ptr++ = DHCP_ROUTER; + *ptr++ = 4; + set_ip(ptr, router); + ptr += 4; + } + + /* domain name */ + if (domain != NULL) + { + int len = strlen(domain); + *ptr++ = DHCP_DNSDOMAIN; + *ptr++ = len; + memcpy(ptr, domain, len); + ptr += len; + } + + /* domain name server (DNS) */ + if (dns != 0) + { + *ptr++ = DHCP_DNSSERVER; + *ptr++ = 4; + set_ip(ptr, dns); + ptr += 4; + } + + /* end */ + *ptr++ = DHCP_END; + return ptr - (uint8_t *)dest; +} + +static void udp_recv_proc(void *arg, struct udp_pcb *upcb, struct pbuf *p, const ip_addr_t *addr, u16_t port) +{ + uint8_t *ptr; + dhcp_entry_t *entry; + struct pbuf *pp; + + (void)arg; + (void)addr; + + unsigned n = p->len; + if (n > sizeof(dhcp_data)) n = sizeof(dhcp_data); + memcpy(&dhcp_data, p->payload, n); + switch (dhcp_data.dp_options[2]) + { + case DHCP_DISCOVER: + entry = entry_by_mac(dhcp_data.dp_chaddr); + if (entry == NULL) entry = vacant_address(); + if (entry == NULL) break; + + dhcp_data.dp_op = 2; /* reply */ + dhcp_data.dp_secs = 0; + dhcp_data.dp_flags = 0; + set_ip(dhcp_data.dp_yiaddr, get_ip(entry->addr)); + memcpy(dhcp_data.dp_magic, magic_cookie, 4); + + memset(dhcp_data.dp_options, 0, sizeof(dhcp_data.dp_options)); + + fill_options(dhcp_data.dp_options, + DHCP_OFFER, + config->domain, + get_ip(config->dns), + entry->lease, + get_ip(config->addr), + get_ip(config->addr), + get_ip(entry->subnet)); + + pp = pbuf_alloc(PBUF_TRANSPORT, sizeof(dhcp_data), PBUF_POOL); + if (pp == NULL) break; + memcpy(pp->payload, &dhcp_data, sizeof(dhcp_data)); + udp_sendto(upcb, pp, IP_ADDR_BROADCAST, port); + pbuf_free(pp); + break; + + case DHCP_REQUEST: + /* 1. find requested ipaddr in option list */ + ptr = find_dhcp_option(dhcp_data.dp_options, sizeof(dhcp_data.dp_options), DHCP_IPADDRESS); + if (ptr == NULL) break; + if (ptr[1] != 4) break; + ptr += 2; + + /* 2. does hw-address registered? */ + entry = entry_by_mac(dhcp_data.dp_chaddr); + if (entry != NULL) free_entry(entry); + + /* 3. find requested ipaddr */ + entry = entry_by_ip(get_ip(ptr)); + if (entry == NULL) break; + if (!is_vacant(entry)) break; + + /* 4. fill struct fields */ + memcpy(dhcp_data.dp_yiaddr, ptr, 4); + dhcp_data.dp_op = 2; /* reply */ + dhcp_data.dp_secs = 0; + dhcp_data.dp_flags = 0; + memcpy(dhcp_data.dp_magic, magic_cookie, 4); + + /* 5. fill options */ + memset(dhcp_data.dp_options, 0, sizeof(dhcp_data.dp_options)); + + fill_options(dhcp_data.dp_options, + DHCP_ACK, + config->domain, + get_ip(config->dns), + entry->lease, + get_ip(config->addr), + get_ip(config->addr), + get_ip(entry->subnet)); + + /* 6. send ACK */ + pp = pbuf_alloc(PBUF_TRANSPORT, sizeof(dhcp_data), PBUF_POOL); + if (pp == NULL) break; + memcpy(entry->mac, dhcp_data.dp_chaddr, 6); + memcpy(pp->payload, &dhcp_data, sizeof(dhcp_data)); + udp_sendto(upcb, pp, IP_ADDR_BROADCAST, port); + pbuf_free(pp); + break; + + default: + break; + } + pbuf_free(p); +} + +err_t dhserv_init(const dhcp_config_t *c) +{ + err_t err; + udp_init(); + dhserv_free(); + pcb = udp_new(); + if (pcb == NULL) + return ERR_MEM; + err = udp_bind(pcb, IP_ADDR_ANY, c->port); + if (err != ERR_OK) + { + dhserv_free(); + return err; + } + udp_recv(pcb, udp_recv_proc, NULL); + config = c; + return ERR_OK; +} + +void dhserv_free(void) +{ + if (pcb == NULL) return; + udp_remove(pcb); + pcb = NULL; +} diff --git a/lib/networking/dhserver.h b/lib/networking/dhserver.h new file mode 100644 index 00000000..901f6e35 --- /dev/null +++ b/lib/networking/dhserver.h @@ -0,0 +1,63 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 by Sergey Fetisov + * + * 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. + */ + +/* + * version: 1.0 demo (7.02.2015) + * brief: tiny dhcp ipv4 server using lwip (pcb) + * ref: https://lists.gnu.org/archive/html/lwip-users/2012-12/msg00016.html + */ + +#ifndef DHSERVER_H +#define DHSERVER_H + +#include +#include +#include +#include +#include "lwip/err.h" +#include "lwip/udp.h" +#include "netif/etharp.h" + +typedef struct dhcp_entry +{ + uint8_t mac[6]; + uint8_t addr[4]; + uint8_t subnet[4]; + uint32_t lease; +} dhcp_entry_t; + +typedef struct dhcp_config +{ + uint8_t addr[4]; + uint16_t port; + uint8_t dns[4]; + const char *domain; + int num_entry; + dhcp_entry_t *entries; +} dhcp_config_t; + +err_t dhserv_init(const dhcp_config_t *config); +void dhserv_free(void); + +#endif /* DHSERVER_H */ diff --git a/lib/networking/dnserver.c b/lib/networking/dnserver.c new file mode 100644 index 00000000..6df0bd0c --- /dev/null +++ b/lib/networking/dnserver.c @@ -0,0 +1,200 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 by Sergey Fetisov + * + * 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. + */ + +/* + * version: 1.0 demo (7.02.2015) + * brief: tiny dns ipv4 server using lwip (pcb) + */ + +#include "dnserver.h" + +#define DNS_MAX_HOST_NAME_LEN 128 + +static struct udp_pcb *pcb = NULL; +dns_query_proc_t query_proc = NULL; + +#pragma pack(push, 1) +typedef struct +{ +#if BYTE_ORDER == LITTLE_ENDIAN + uint8_t rd: 1, /* Recursion Desired */ + tc: 1, /* Truncation Flag */ + aa: 1, /* Authoritative Answer Flag */ + opcode: 4, /* Operation code */ + qr: 1; /* Query/Response Flag */ + uint8_t rcode: 4, /* Response Code */ + z: 3, /* Zero */ + ra: 1; /* Recursion Available */ +#else + uint8_t qr: 1, /* Query/Response Flag */ + opcode: 4, /* Operation code */ + aa: 1, /* Authoritative Answer Flag */ + tc: 1, /* Truncation Flag */ + rd: 1; /* Recursion Desired */ + uint8_t ra: 1, /* Recursion Available */ + z: 3, /* Zero */ + rcode: 4; /* Response Code */ +#endif +} dns_header_flags_t; + +typedef struct +{ + uint16_t id; + dns_header_flags_t flags; + uint16_t n_record[4]; +} dns_header_t; + +typedef struct dns_answer +{ + uint16_t name; + uint16_t type; + uint16_t Class; + uint32_t ttl; + uint16_t len; + uint32_t addr; +} dns_answer_t; +#pragma pack(pop) + +typedef struct dns_query +{ + char name[DNS_MAX_HOST_NAME_LEN]; + uint16_t type; + uint16_t Class; +} dns_query_t; + +static uint16_t get_uint16(const uint8_t *pnt) +{ + uint16_t result; + memcpy(&result, pnt, sizeof(result)); + return result; +} + +static int parse_next_query(void *data, int size, dns_query_t *query) +{ + int len; + int lables; + uint8_t *ptr; + + len = 0; + lables = 0; + ptr = (uint8_t *)data; + + while (true) + { + uint8_t lable_len; + if (size <= 0) return -1; + lable_len = *ptr++; + size--; + if (lable_len == 0) break; + if (lables > 0) + { + if (len == DNS_MAX_HOST_NAME_LEN) return -2; + query->name[len++] = '.'; + } + if (lable_len > size) return -1; + if (len + lable_len >= DNS_MAX_HOST_NAME_LEN) return -2; + memcpy(&query->name[len], ptr, lable_len); + len += lable_len; + ptr += lable_len; + size -= lable_len; + lables++; + } + + if (size < 4) return -1; + query->name[len] = 0; + query->type = get_uint16(ptr); + ptr += 2; + query->Class = get_uint16(ptr); + ptr += 2; + return ptr - (uint8_t *)data; +} + +static void udp_recv_proc(void *arg, struct udp_pcb *upcb, struct pbuf *p, const ip_addr_t *addr, u16_t port) +{ + int len; + dns_header_t *header; + static dns_query_t query; + struct pbuf *out; + ip_addr_t host_addr; + dns_answer_t *answer; + + (void)arg; + + if (p->len <= sizeof(dns_header_t)) goto error; + header = (dns_header_t *)p->payload; + if (header->flags.qr != 0) goto error; + if (ntohs(header->n_record[0]) != 1) goto error; + + len = parse_next_query(header + 1, p->len - sizeof(dns_header_t), &query); + if (len < 0) goto error; + if (!query_proc(query.name, &host_addr)) goto error; + + len += sizeof(dns_header_t); + out = pbuf_alloc(PBUF_TRANSPORT, len + 16, PBUF_POOL); + if (out == NULL) goto error; + + memcpy(out->payload, p->payload, len); + header = (dns_header_t *)out->payload; + header->flags.qr = 1; + header->n_record[1] = htons(1); + answer = (struct dns_answer *)((uint8_t *)out->payload + len); + answer->name = htons(0xC00C); + answer->type = htons(1); + answer->Class = htons(1); + answer->ttl = htonl(32); + answer->len = htons(4); + answer->addr = host_addr.addr; + + udp_sendto(upcb, out, addr, port); + pbuf_free(out); + +error: + pbuf_free(p); +} + +err_t dnserv_init(const ip_addr_t *bind, uint16_t port, dns_query_proc_t qp) +{ + err_t err; + udp_init(); + dnserv_free(); + pcb = udp_new(); + if (pcb == NULL) + return ERR_MEM; + err = udp_bind(pcb, bind, port); + if (err != ERR_OK) + { + dnserv_free(); + return err; + } + udp_recv(pcb, udp_recv_proc, NULL); + query_proc = qp; + return ERR_OK; +} + +void dnserv_free() +{ + if (pcb == NULL) return; + udp_remove(pcb); + pcb = NULL; +} diff --git a/lib/networking/dnserver.h b/lib/networking/dnserver.h new file mode 100644 index 00000000..130991f5 --- /dev/null +++ b/lib/networking/dnserver.h @@ -0,0 +1,47 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 by Sergey Fetisov + * + * 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. + */ + +/* + * version: 1.0 demo (7.02.2015) + * brief: tiny dns ipv4 server using lwip (pcb) + */ + +#ifndef DNSERVER +#define DNSERVER + +#include +#include +#include +#include +#include "lwip/def.h" +#include "lwip/err.h" +#include "lwip/udp.h" +#include "netif/etharp.h" + +typedef bool (*dns_query_proc_t)(const char *name, ip_addr_t *addr); + +err_t dnserv_init(const ip_addr_t *bind, uint16_t port, dns_query_proc_t query_proc); +void dnserv_free(void); + +#endif diff --git a/lib/networking/ndis.h b/lib/networking/ndis.h new file mode 100644 index 00000000..1c737574 --- /dev/null +++ b/lib/networking/ndis.h @@ -0,0 +1,266 @@ +/* This file has been prepared for Doxygen automatic documentation generation.*/ +/*! \file ndis.h *************************************************************** + * + * \brief + * This file contains the possible external configuration of the USB. + * + * \addtogroup usbstick + * + * + ******************************************************************************/ + +/** + \ingroup usbstick + \defgroup RNDIS RNDIS Support + @{ + */ + +/* + * ndis.h + * + * Modified by Colin O'Flynn + * ntddndis.h modified by Benedikt Spranger + * + * Thanks to the cygwin development team, + * espacially to Casper S. Hornstrup + * + * THIS SOFTWARE IS NOT COPYRIGHTED + * + * This source code is offered for use in the public domain. You may + * use, modify or distribute it freely. + * + * This code is distributed in the hope that it will be useful but + * WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESS OR IMPLIED ARE HEREBY + * DISCLAIMED. This includes but is not limited to warranties of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * + */ + +#ifndef _LINUX_NDIS_H +#define _LINUX_NDIS_H + + +#define NDIS_STATUS_MULTICAST_FULL 0xC0010009 +#define NDIS_STATUS_MULTICAST_EXISTS 0xC001000A +#define NDIS_STATUS_MULTICAST_NOT_FOUND 0xC001000B + +/* from drivers/net/sk98lin/h/skgepnmi.h */ +#define OID_PNP_CAPABILITIES 0xFD010100 +#define OID_PNP_SET_POWER 0xFD010101 +#define OID_PNP_QUERY_POWER 0xFD010102 +#define OID_PNP_ADD_WAKE_UP_PATTERN 0xFD010103 +#define OID_PNP_REMOVE_WAKE_UP_PATTERN 0xFD010104 +#define OID_PNP_ENABLE_WAKE_UP 0xFD010106 + +enum NDIS_DEVICE_POWER_STATE { + NdisDeviceStateUnspecified = 0, + NdisDeviceStateD0, + NdisDeviceStateD1, + NdisDeviceStateD2, + NdisDeviceStateD3, + NdisDeviceStateMaximum +}; + +struct NDIS_PM_WAKE_UP_CAPABILITIES { + enum NDIS_DEVICE_POWER_STATE MinMagicPacketWakeUp; + enum NDIS_DEVICE_POWER_STATE MinPatternWakeUp; + enum NDIS_DEVICE_POWER_STATE MinLinkChangeWakeUp; +}; + +/* NDIS_PNP_CAPABILITIES.Flags constants */ +#define NDIS_DEVICE_WAKE_UP_ENABLE 0x00000001 +#define NDIS_DEVICE_WAKE_ON_PATTERN_MATCH_ENABLE 0x00000002 +#define NDIS_DEVICE_WAKE_ON_MAGIC_PACKET_ENABLE 0x00000004 + +/* +struct NDIS_PNP_CAPABILITIES { + __le32 Flags; + struct NDIS_PM_WAKE_UP_CAPABILITIES WakeUpCapabilities; +}; + +struct NDIS_PM_PACKET_PATTERN { + __le32 Priority; + __le32 Reserved; + __le32 MaskSize; + __le32 PatternOffset; + __le32 PatternSize; + __le32 PatternFlags; +}; +*/ + +/* Required Object IDs (OIDs) */ +#define OID_GEN_SUPPORTED_LIST 0x00010101 +#define OID_GEN_HARDWARE_STATUS 0x00010102 +#define OID_GEN_MEDIA_SUPPORTED 0x00010103 +#define OID_GEN_MEDIA_IN_USE 0x00010104 +#define OID_GEN_MAXIMUM_LOOKAHEAD 0x00010105 +#define OID_GEN_MAXIMUM_FRAME_SIZE 0x00010106 +#define OID_GEN_LINK_SPEED 0x00010107 +#define OID_GEN_TRANSMIT_BUFFER_SPACE 0x00010108 +#define OID_GEN_RECEIVE_BUFFER_SPACE 0x00010109 +#define OID_GEN_TRANSMIT_BLOCK_SIZE 0x0001010A +#define OID_GEN_RECEIVE_BLOCK_SIZE 0x0001010B +#define OID_GEN_VENDOR_ID 0x0001010C +#define OID_GEN_VENDOR_DESCRIPTION 0x0001010D +#define OID_GEN_CURRENT_PACKET_FILTER 0x0001010E +#define OID_GEN_CURRENT_LOOKAHEAD 0x0001010F +#define OID_GEN_DRIVER_VERSION 0x00010110 +#define OID_GEN_MAXIMUM_TOTAL_SIZE 0x00010111 +#define OID_GEN_PROTOCOL_OPTIONS 0x00010112 +#define OID_GEN_MAC_OPTIONS 0x00010113 +#define OID_GEN_MEDIA_CONNECT_STATUS 0x00010114 +#define OID_GEN_MAXIMUM_SEND_PACKETS 0x00010115 +#define OID_GEN_VENDOR_DRIVER_VERSION 0x00010116 +#define OID_GEN_SUPPORTED_GUIDS 0x00010117 +#define OID_GEN_NETWORK_LAYER_ADDRESSES 0x00010118 +#define OID_GEN_TRANSPORT_HEADER_OFFSET 0x00010119 +#define OID_GEN_MACHINE_NAME 0x0001021A +#define OID_GEN_RNDIS_CONFIG_PARAMETER 0x0001021B +#define OID_GEN_VLAN_ID 0x0001021C + +/* Optional OIDs */ +#define OID_GEN_MEDIA_CAPABILITIES 0x00010201 +#define OID_GEN_PHYSICAL_MEDIUM 0x00010202 + +/* Required statistics OIDs */ +#define OID_GEN_XMIT_OK 0x00020101 +#define OID_GEN_RCV_OK 0x00020102 +#define OID_GEN_XMIT_ERROR 0x00020103 +#define OID_GEN_RCV_ERROR 0x00020104 +#define OID_GEN_RCV_NO_BUFFER 0x00020105 + +/* Optional statistics OIDs */ +#define OID_GEN_DIRECTED_BYTES_XMIT 0x00020201 +#define OID_GEN_DIRECTED_FRAMES_XMIT 0x00020202 +#define OID_GEN_MULTICAST_BYTES_XMIT 0x00020203 +#define OID_GEN_MULTICAST_FRAMES_XMIT 0x00020204 +#define OID_GEN_BROADCAST_BYTES_XMIT 0x00020205 +#define OID_GEN_BROADCAST_FRAMES_XMIT 0x00020206 +#define OID_GEN_DIRECTED_BYTES_RCV 0x00020207 +#define OID_GEN_DIRECTED_FRAMES_RCV 0x00020208 +#define OID_GEN_MULTICAST_BYTES_RCV 0x00020209 +#define OID_GEN_MULTICAST_FRAMES_RCV 0x0002020A +#define OID_GEN_BROADCAST_BYTES_RCV 0x0002020B +#define OID_GEN_BROADCAST_FRAMES_RCV 0x0002020C +#define OID_GEN_RCV_CRC_ERROR 0x0002020D +#define OID_GEN_TRANSMIT_QUEUE_LENGTH 0x0002020E +#define OID_GEN_GET_TIME_CAPS 0x0002020F +#define OID_GEN_GET_NETCARD_TIME 0x00020210 +#define OID_GEN_NETCARD_LOAD 0x00020211 +#define OID_GEN_DEVICE_PROFILE 0x00020212 +#define OID_GEN_INIT_TIME_MS 0x00020213 +#define OID_GEN_RESET_COUNTS 0x00020214 +#define OID_GEN_MEDIA_SENSE_COUNTS 0x00020215 +#define OID_GEN_FRIENDLY_NAME 0x00020216 +#define OID_GEN_MINIPORT_INFO 0x00020217 +#define OID_GEN_RESET_VERIFY_PARAMETERS 0x00020218 + +/* IEEE 802.3 (Ethernet) OIDs */ +#define NDIS_802_3_MAC_OPTION_PRIORITY 0x00000001 + +#define OID_802_3_PERMANENT_ADDRESS 0x01010101 +#define OID_802_3_CURRENT_ADDRESS 0x01010102 +#define OID_802_3_MULTICAST_LIST 0x01010103 +#define OID_802_3_MAXIMUM_LIST_SIZE 0x01010104 +#define OID_802_3_MAC_OPTIONS 0x01010105 +#define OID_802_3_RCV_ERROR_ALIGNMENT 0x01020101 +#define OID_802_3_XMIT_ONE_COLLISION 0x01020102 +#define OID_802_3_XMIT_MORE_COLLISIONS 0x01020103 +#define OID_802_3_XMIT_DEFERRED 0x01020201 +#define OID_802_3_XMIT_MAX_COLLISIONS 0x01020202 +#define OID_802_3_RCV_OVERRUN 0x01020203 +#define OID_802_3_XMIT_UNDERRUN 0x01020204 +#define OID_802_3_XMIT_HEARTBEAT_FAILURE 0x01020205 +#define OID_802_3_XMIT_TIMES_CRS_LOST 0x01020206 +#define OID_802_3_XMIT_LATE_COLLISIONS 0x01020207 + +/* Wireless LAN OIDs */ +/* Mandatory */ +#define OID_802_11_BSSID 0x0D010101 /* Q S */ +#define OID_802_11_SSID 0x0D010102 /* Q S */ +#define OID_802_11_NETWORK_TYPE_IN_USE 0x0D010204 /* Q S */ +#define OID_802_11_RSSI 0x0D010206 /* Q I */ +#define OID_802_11_BSSID_LIST 0x0D010217 /* Q */ +#define OID_802_11_BSSID_LIST_SCAN 0x0D01011A /* S */ +#define OID_802_11_INFRASTRUCTURE_MODE 0x0D010108 /* Q S */ +#define OID_802_11_SUPPORTED_RATES 0x0D01020E /* Q */ +#define OID_802_11_CONFIGURATION 0x0D010211 /* Q S */ +#define OID_802_11_ADD_WEP 0x0D010113 /* S */ +#define OID_802_11_WEP_STATUS 0x0D01011B /* Q S */ +#define OID_802_11_REMOVE_WEP 0x0D010114 /* S */ +#define OID_802_11_DISASSOCIATE 0x0D010115 /* S */ +#define OID_802_11_AUTHENTICATION_MODE 0x0D010118 /* Q S */ +#define OID_802_11_RELOAD_DEFAULTS 0x0D01011C /* S */ + + + +/* OID_GEN_MINIPORT_INFO constants */ +#define NDIS_MINIPORT_BUS_MASTER 0x00000001 +#define NDIS_MINIPORT_WDM_DRIVER 0x00000002 +#define NDIS_MINIPORT_SG_LIST 0x00000004 +#define NDIS_MINIPORT_SUPPORTS_MEDIA_QUERY 0x00000008 +#define NDIS_MINIPORT_INDICATES_PACKETS 0x00000010 +#define NDIS_MINIPORT_IGNORE_PACKET_QUEUE 0x00000020 +#define NDIS_MINIPORT_IGNORE_REQUEST_QUEUE 0x00000040 +#define NDIS_MINIPORT_IGNORE_TOKEN_RING_ERRORS 0x00000080 +#define NDIS_MINIPORT_INTERMEDIATE_DRIVER 0x00000100 +#define NDIS_MINIPORT_IS_NDIS_5 0x00000200 +#define NDIS_MINIPORT_IS_CO 0x00000400 +#define NDIS_MINIPORT_DESERIALIZE 0x00000800 +#define NDIS_MINIPORT_REQUIRES_MEDIA_POLLING 0x00001000 +#define NDIS_MINIPORT_SUPPORTS_MEDIA_SENSE 0x00002000 +#define NDIS_MINIPORT_NETBOOT_CARD 0x00004000 +#define NDIS_MINIPORT_PM_SUPPORTED 0x00008000 +#define NDIS_MINIPORT_SUPPORTS_MAC_ADDRESS_OVERWRITE 0x00010000 +#define NDIS_MINIPORT_USES_SAFE_BUFFER_APIS 0x00020000 +#define NDIS_MINIPORT_HIDDEN 0x00040000 +#define NDIS_MINIPORT_SWENUM 0x00080000 +#define NDIS_MINIPORT_SURPRISE_REMOVE_OK 0x00100000 +#define NDIS_MINIPORT_NO_HALT_ON_SUSPEND 0x00200000 +#define NDIS_MINIPORT_HARDWARE_DEVICE 0x00400000 +#define NDIS_MINIPORT_SUPPORTS_CANCEL_SEND_PACKETS 0x00800000 +#define NDIS_MINIPORT_64BITS_DMA 0x01000000 + +#define NDIS_MEDIUM_802_3 0x00000000 +#define NDIS_MEDIUM_802_5 0x00000001 +#define NDIS_MEDIUM_FDDI 0x00000002 +#define NDIS_MEDIUM_WAN 0x00000003 +#define NDIS_MEDIUM_LOCAL_TALK 0x00000004 +#define NDIS_MEDIUM_DIX 0x00000005 +#define NDIS_MEDIUM_ARCENT_RAW 0x00000006 +#define NDIS_MEDIUM_ARCENT_878_2 0x00000007 +#define NDIS_MEDIUM_ATM 0x00000008 +#define NDIS_MEDIUM_WIRELESS_LAN 0x00000009 +#define NDIS_MEDIUM_IRDA 0x0000000A +#define NDIS_MEDIUM_BPC 0x0000000B +#define NDIS_MEDIUM_CO_WAN 0x0000000C +#define NDIS_MEDIUM_1394 0x0000000D + +#define NDIS_PACKET_TYPE_DIRECTED 0x00000001 +#define NDIS_PACKET_TYPE_MULTICAST 0x00000002 +#define NDIS_PACKET_TYPE_ALL_MULTICAST 0x00000004 +#define NDIS_PACKET_TYPE_BROADCAST 0x00000008 +#define NDIS_PACKET_TYPE_SOURCE_ROUTING 0x00000010 +#define NDIS_PACKET_TYPE_PROMISCUOUS 0x00000020 +#define NDIS_PACKET_TYPE_SMT 0x00000040 +#define NDIS_PACKET_TYPE_ALL_LOCAL 0x00000080 +#define NDIS_PACKET_TYPE_GROUP 0x00000100 +#define NDIS_PACKET_TYPE_ALL_FUNCTIONAL 0x00000200 +#define NDIS_PACKET_TYPE_FUNCTIONAL 0x00000400 +#define NDIS_PACKET_TYPE_MAC_FRAME 0x00000800 + +#define NDIS_MEDIA_STATE_CONNECTED 0x00000000 +#define NDIS_MEDIA_STATE_DISCONNECTED 0x00000001 + +#define NDIS_MAC_OPTION_COPY_LOOKAHEAD_DATA 0x00000001 +#define NDIS_MAC_OPTION_RECEIVE_SERIALIZED 0x00000002 +#define NDIS_MAC_OPTION_TRANSFERS_NOT_PEND 0x00000004 +#define NDIS_MAC_OPTION_NO_LOOPBACK 0x00000008 +#define NDIS_MAC_OPTION_FULL_DUPLEX 0x00000010 +#define NDIS_MAC_OPTION_EOTX_INDICATION 0x00000020 +#define NDIS_MAC_OPTION_8021P_PRIORITY 0x00000040 +#define NDIS_MAC_OPTION_RESERVED 0x80000000 + +#endif /* _LINUX_NDIS_H */ + +/** @} */ diff --git a/lib/networking/rndis_protocol.h b/lib/networking/rndis_protocol.h new file mode 100644 index 00000000..b45860ee --- /dev/null +++ b/lib/networking/rndis_protocol.h @@ -0,0 +1,307 @@ +/** + * \file rndis_protocol.h + * RNDIS Defines + * + * \author + * Colin O'Flynn + * + * \addtogroup usbstick + */ + +/* Copyright (c) 2008 Colin O'Flynn + + 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 copyright holders nor the names of + 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 _RNDIS_H +#define _RNDIS_H + +/** + \addtogroup RNDIS + @{ + */ + +#include + +#define RNDIS_MAJOR_VERSION 1 +#define RNDIS_MINOR_VERSION 0 + +#define RNDIS_STATUS_SUCCESS 0X00000000 +#define RNDIS_STATUS_FAILURE 0XC0000001 +#define RNDIS_STATUS_INVALID_DATA 0XC0010015 +#define RNDIS_STATUS_NOT_SUPPORTED 0XC00000BB +#define RNDIS_STATUS_MEDIA_CONNECT 0X4001000B +#define RNDIS_STATUS_MEDIA_DISCONNECT 0X4001000C + + +/* Message set for Connectionless (802.3) Devices */ +#define REMOTE_NDIS_PACKET_MSG 0x00000001 +#define REMOTE_NDIS_INITIALIZE_MSG 0X00000002 +#define REMOTE_NDIS_HALT_MSG 0X00000003 +#define REMOTE_NDIS_QUERY_MSG 0X00000004 +#define REMOTE_NDIS_SET_MSG 0X00000005 +#define REMOTE_NDIS_RESET_MSG 0X00000006 +#define REMOTE_NDIS_INDICATE_STATUS_MSG 0X00000007 +#define REMOTE_NDIS_KEEPALIVE_MSG 0X00000008 +#define REMOTE_NDIS_INITIALIZE_CMPLT 0X80000002 +#define REMOTE_NDIS_QUERY_CMPLT 0X80000004 +#define REMOTE_NDIS_SET_CMPLT 0X80000005 +#define REMOTE_NDIS_RESET_CMPLT 0X80000006 +#define REMOTE_NDIS_KEEPALIVE_CMPLT 0X80000008 + +typedef uint32_t rndis_MessageType_t; +typedef uint32_t rndis_MessageLength_t; +typedef uint32_t rndis_RequestId_t; +typedef uint32_t rndis_MajorVersion_t; +typedef uint32_t rndis_MinorVersion_t; +typedef uint32_t rndis_MaxTransferSize_t; +typedef uint32_t rndis_Status_t; + + +/* Device Flags */ +#define RNDIS_DF_CONNECTIONLESS 0x00000001 +#define RNDIS_DF_CONNECTION_ORIENTED 0x00000002 +typedef uint32_t rndis_DeviceFlags_t; + +/* Mediums */ +#define RNDIS_MEDIUM_802_3 0x00000000 +typedef uint32_t rndis_Medium_t; + + +typedef uint32_t rndis_MaxPacketsPerTransfer_t; +typedef uint32_t rndis_PacketAlignmentFactor_t; +typedef uint32_t rndis_AfListOffset_t; +typedef uint32_t rndis_AfListSize_t; + +/*** Remote NDIS Generic Message type ***/ +typedef struct{ + rndis_MessageType_t MessageType; + rndis_MessageLength_t MessageLength; + } rndis_generic_msg_t; + + +/*** Remote NDIS Initialize Message ***/ +typedef struct{ + rndis_MessageType_t MessageType; + rndis_MessageLength_t MessageLength; + rndis_RequestId_t RequestId; + rndis_MajorVersion_t MajorVersion; + rndis_MinorVersion_t MinorVersion; + rndis_MaxTransferSize_t MaxTransferSize; + } rndis_initialize_msg_t; + +/* Response: */ +typedef struct{ + rndis_MessageType_t MessageType; + rndis_MessageLength_t MessageLength; + rndis_RequestId_t RequestId; + rndis_Status_t Status; + rndis_MajorVersion_t MajorVersion; + rndis_MinorVersion_t MinorVersion; + rndis_DeviceFlags_t DeviceFlags; + rndis_Medium_t Medium; + rndis_MaxPacketsPerTransfer_t MaxPacketsPerTransfer; + rndis_MaxTransferSize_t MaxTransferSize; + rndis_PacketAlignmentFactor_t PacketAlignmentFactor; + rndis_AfListOffset_t AfListOffset; + rndis_AfListSize_t AfListSize; + } rndis_initialize_cmplt_t; + + +/*** Remote NDIS Halt Message ***/ +typedef struct{ + rndis_MessageType_t MessageType; + rndis_MessageLength_t MessageLength; + rndis_RequestId_t RequestId; + } rndis_halt_msg_t; + +typedef uint32_t rndis_Oid_t; +typedef uint32_t rndis_InformationBufferLength_t; +typedef uint32_t rndis_InformationBufferOffset_t; +typedef uint32_t rndis_DeviceVcHandle_t; + +/*** Remote NDIS Query Message ***/ +typedef struct{ + rndis_MessageType_t MessageType; + rndis_MessageLength_t MessageLength; + rndis_RequestId_t RequestId; + rndis_Oid_t Oid; + rndis_InformationBufferLength_t InformationBufferLength; + rndis_InformationBufferOffset_t InformationBufferOffset; + rndis_DeviceVcHandle_t DeviceVcHandle; + } rndis_query_msg_t; + +/* Response: */ + +typedef struct{ + rndis_MessageType_t MessageType; + rndis_MessageLength_t MessageLength; + rndis_RequestId_t RequestId; + rndis_Status_t Status; + rndis_InformationBufferLength_t InformationBufferLength; + rndis_InformationBufferOffset_t InformationBufferOffset; + } rndis_query_cmplt_t; + +/*** Remote NDIS Set Message ***/ +typedef struct{ + rndis_MessageType_t MessageType; + rndis_MessageLength_t MessageLength; + rndis_RequestId_t RequestId; + rndis_Oid_t Oid; + rndis_InformationBufferLength_t InformationBufferLength; + rndis_InformationBufferOffset_t InformationBufferOffset; + rndis_DeviceVcHandle_t DeviceVcHandle; + } rndis_set_msg_t; + +/* Response */ +typedef struct{ + rndis_MessageType_t MessageType; + rndis_MessageLength_t MessageLength; + rndis_RequestId_t RequestId; + rndis_Status_t Status; + }rndis_set_cmplt_t; + +/* Information buffer layout for OID_GEN_RNDIS_CONFIG_PARAMETER */ +typedef uint32_t rndis_ParameterNameOffset_t; +typedef uint32_t rndis_ParameterNameLength_t; +typedef uint32_t rndis_ParameterType_t; +typedef uint32_t rndis_ParameterValueOffset_t; +typedef uint32_t rndis_ParameterValueLength_t; + +#define PARAMETER_TYPE_STRING 2 +#define PARAMETER_TYPE_NUMERICAL 0 + +typedef struct{ + rndis_ParameterNameOffset_t ParameterNameOffset; + rndis_ParameterNameLength_t ParameterNameLength; + rndis_ParameterType_t ParameterType; + rndis_ParameterValueOffset_t ParameterValueOffset; + rndis_ParameterValueLength_t ParameterValueLength; + }rndis_config_parameter_t; + +typedef uint32_t rndis_Reserved_t; + +/*** Remote NDIS Soft Reset Message ***/ +typedef struct{ + rndis_MessageType_t MessageType; + rndis_MessageLength_t MessageLength; + rndis_Reserved_t Reserved; + } rndis_reset_msg_t; + +typedef uint32_t rndis_AddressingReset_t; + +/* Response: */ +typedef struct{ + rndis_MessageType_t MessageType; + rndis_MessageLength_t MessageLength; + rndis_Status_t Status; + rndis_AddressingReset_t AddressingReset; + } rndis_reset_cmplt_t; + +/*** Remote NDIS Indicate Status Message ***/ +typedef struct{ + rndis_MessageType_t MessageType; + rndis_MessageLength_t MessageLength; + rndis_Status_t Status; + rndis_Status_t StatusBufferLength; + rndis_Status_t StatusBufferOffset; + } rndis_indicate_status_t; + +typedef uint32_t rndis_DiagStatus_t; +typedef uint32_t rndis_ErrorOffset_t; + +typedef struct { + rndis_DiagStatus_t DiagStatus; + rndis_ErrorOffset_t ErrorOffset; + }rndis_diagnostic_info_t; + +/*** Remote NDIS Keepalive Message */ +typedef struct{ + rndis_MessageType_t MessageType; + rndis_MessageLength_t MessageLength; + rndis_RequestId_t RequestId; + }rndis_keepalive_msg_t; + +/* Response: */ +typedef struct{ + rndis_MessageType_t MessageType; + rndis_MessageLength_t MessageLength; + rndis_RequestId_t RequestId; + rndis_Status_t Status; + }rndis_keepalive_cmplt_t; + +/*** Remote NDIS Data Packet ***/ + +typedef uint32_t rndis_DataOffset_t; +typedef uint32_t rndis_DataLength_t; +typedef uint32_t rndis_OOBDataOffset_t; +typedef uint32_t rndis_OOBDataLength_t; +typedef uint32_t rndis_NumOOBDataElements_t; +typedef uint32_t rndis_PerPacketInfoOffset_t; +typedef uint32_t rndis_PerPacketInfoLength_t; + +typedef struct{ + rndis_MessageType_t MessageType; + rndis_MessageLength_t MessageLength; + rndis_DataOffset_t DataOffset; + rndis_DataLength_t DataLength; + rndis_OOBDataOffset_t OOBDataOffset; + rndis_OOBDataLength_t OOBDataLength; + rndis_NumOOBDataElements_t NumOOBDataElements; + rndis_PerPacketInfoOffset_t PerPacketInfoOffset; + rndis_PerPacketInfoLength_t PerPacketInfoLength; + rndis_DeviceVcHandle_t DeviceVcHandle; + rndis_Reserved_t Reserved; + }rndis_data_packet_t; + +typedef uint32_t rndis_ClassInformationOffset_t; +typedef uint32_t rndis_Size_t; +typedef uint32_t rndis_Type_t; + +typedef struct{ + rndis_Size_t Size; + rndis_Type_t Type; + rndis_ClassInformationOffset_t ClassInformationType; + }rndis_OOB_packet_t; + +#include "ndis.h" + +typedef enum rnids_state_e { + rndis_uninitialized, + rndis_initialized, + rndis_data_initialized + } rndis_state_t; + +typedef struct { + uint32_t txok; + uint32_t rxok; + uint32_t txbad; + uint32_t rxbad; +} usb_eth_stat_t; + +#endif /* _RNDIS_H */ + +/** @} */ diff --git a/lib/networking/rndis_reports.c b/lib/networking/rndis_reports.c new file mode 100644 index 00000000..535bdf85 --- /dev/null +++ b/lib/networking/rndis_reports.c @@ -0,0 +1,303 @@ +/* + The original version of this code was lrndis/usbd_rndis_core.c from https://github.com/fetisov/lrndis + It has since been overhauled to suit this application +*/ + +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 by Sergey Fetisov + * + * 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 +#include +#include "class/net/net_device.h" +#include "rndis_protocol.h" +#include "netif/ethernet.h" + +#define RNDIS_LINK_SPEED 12000000 /* Link baudrate (12Mbit/s for USB-FS) */ +#define RNDIS_VENDOR "TinyUSB" /* NIC vendor name */ + +static const uint8_t *const station_hwaddr = network_mac_address; +static const uint8_t *const permanent_hwaddr = network_mac_address; + +static usb_eth_stat_t usb_eth_stat = { 0, 0, 0, 0 }; +static uint32_t oid_packet_filter = 0x0000000; +static rndis_state_t rndis_state; + +CFG_TUSB_MEM_SECTION CFG_TUSB_MEM_ALIGN static uint8_t ndis_report[8] = { 0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }; + +static const uint32_t OIDSupportedList[] = +{ + OID_GEN_SUPPORTED_LIST, + OID_GEN_HARDWARE_STATUS, + OID_GEN_MEDIA_SUPPORTED, + OID_GEN_MEDIA_IN_USE, + OID_GEN_MAXIMUM_FRAME_SIZE, + OID_GEN_LINK_SPEED, + OID_GEN_TRANSMIT_BLOCK_SIZE, + OID_GEN_RECEIVE_BLOCK_SIZE, + OID_GEN_VENDOR_ID, + OID_GEN_VENDOR_DESCRIPTION, + OID_GEN_VENDOR_DRIVER_VERSION, + OID_GEN_CURRENT_PACKET_FILTER, + OID_GEN_MAXIMUM_TOTAL_SIZE, + OID_GEN_PROTOCOL_OPTIONS, + OID_GEN_MAC_OPTIONS, + OID_GEN_MEDIA_CONNECT_STATUS, + OID_GEN_MAXIMUM_SEND_PACKETS, + OID_802_3_PERMANENT_ADDRESS, + OID_802_3_CURRENT_ADDRESS, + OID_802_3_MULTICAST_LIST, + OID_802_3_MAXIMUM_LIST_SIZE, + OID_802_3_MAC_OPTIONS +}; + +#define OID_LIST_LENGTH TU_ARRAY_SIZE(OIDSupportedList) +#define ENC_BUF_SIZE (OID_LIST_LENGTH * 4 + 32) + +static uint8_t *encapsulated_buffer; + +static void rndis_report(void) +{ + netd_report(ndis_report, sizeof(ndis_report)); +} + +static void rndis_query_cmplt32(int status, uint32_t data) +{ + rndis_query_cmplt_t *c; + c = (rndis_query_cmplt_t *)encapsulated_buffer; + c->MessageType = REMOTE_NDIS_QUERY_CMPLT; + c->MessageLength = sizeof(rndis_query_cmplt_t) + 4; + c->InformationBufferLength = 4; + c->InformationBufferOffset = 16; + c->Status = status; + memcpy(c + 1, &data, sizeof(data)); + rndis_report(); +} + +static void rndis_query_cmplt(int status, const void *data, int size) +{ + rndis_query_cmplt_t *c; + c = (rndis_query_cmplt_t *)encapsulated_buffer; + c->MessageType = REMOTE_NDIS_QUERY_CMPLT; + c->MessageLength = sizeof(rndis_query_cmplt_t) + size; + c->InformationBufferLength = size; + c->InformationBufferOffset = 16; + c->Status = status; + memcpy(c + 1, data, size); + rndis_report(); +} + +#define MAC_OPT NDIS_MAC_OPTION_COPY_LOOKAHEAD_DATA | \ + NDIS_MAC_OPTION_RECEIVE_SERIALIZED | \ + NDIS_MAC_OPTION_TRANSFERS_NOT_PEND | \ + NDIS_MAC_OPTION_NO_LOOPBACK + +static const char *rndis_vendor = RNDIS_VENDOR; + +static void rndis_query(void) +{ + switch (((rndis_query_msg_t *)encapsulated_buffer)->Oid) + { + case OID_GEN_SUPPORTED_LIST: rndis_query_cmplt(RNDIS_STATUS_SUCCESS, OIDSupportedList, 4 * OID_LIST_LENGTH); return; + case OID_GEN_VENDOR_DRIVER_VERSION: rndis_query_cmplt32(RNDIS_STATUS_SUCCESS, 0x00001000); return; + case OID_802_3_CURRENT_ADDRESS: rndis_query_cmplt(RNDIS_STATUS_SUCCESS, &station_hwaddr, 6); return; + case OID_802_3_PERMANENT_ADDRESS: rndis_query_cmplt(RNDIS_STATUS_SUCCESS, &permanent_hwaddr, 6); return; + case OID_GEN_MEDIA_SUPPORTED: rndis_query_cmplt32(RNDIS_STATUS_SUCCESS, NDIS_MEDIUM_802_3); return; + case OID_GEN_MEDIA_IN_USE: rndis_query_cmplt32(RNDIS_STATUS_SUCCESS, NDIS_MEDIUM_802_3); return; + case OID_GEN_PHYSICAL_MEDIUM: rndis_query_cmplt32(RNDIS_STATUS_SUCCESS, NDIS_MEDIUM_802_3); return; + case OID_GEN_HARDWARE_STATUS: rndis_query_cmplt32(RNDIS_STATUS_SUCCESS, 0); return; + case OID_GEN_LINK_SPEED: rndis_query_cmplt32(RNDIS_STATUS_SUCCESS, RNDIS_LINK_SPEED / 100); return; + case OID_GEN_VENDOR_ID: rndis_query_cmplt32(RNDIS_STATUS_SUCCESS, 0x00FFFFFF); return; + case OID_GEN_VENDOR_DESCRIPTION: rndis_query_cmplt(RNDIS_STATUS_SUCCESS, rndis_vendor, strlen(rndis_vendor) + 1); return; + case OID_GEN_CURRENT_PACKET_FILTER: rndis_query_cmplt32(RNDIS_STATUS_SUCCESS, oid_packet_filter); return; + case OID_GEN_MAXIMUM_FRAME_SIZE: rndis_query_cmplt32(RNDIS_STATUS_SUCCESS, CFG_TUD_NET_MTU - SIZEOF_ETH_HDR); return; + case OID_GEN_MAXIMUM_TOTAL_SIZE: rndis_query_cmplt32(RNDIS_STATUS_SUCCESS, CFG_TUD_NET_MTU); return; + case OID_GEN_TRANSMIT_BLOCK_SIZE: rndis_query_cmplt32(RNDIS_STATUS_SUCCESS, CFG_TUD_NET_MTU); return; + case OID_GEN_RECEIVE_BLOCK_SIZE: rndis_query_cmplt32(RNDIS_STATUS_SUCCESS, CFG_TUD_NET_MTU); return; + case OID_GEN_MEDIA_CONNECT_STATUS: rndis_query_cmplt32(RNDIS_STATUS_SUCCESS, NDIS_MEDIA_STATE_CONNECTED); return; + case OID_GEN_RNDIS_CONFIG_PARAMETER: rndis_query_cmplt32(RNDIS_STATUS_SUCCESS, 0); return; + case OID_802_3_MAXIMUM_LIST_SIZE: rndis_query_cmplt32(RNDIS_STATUS_SUCCESS, 1); return; + case OID_802_3_MULTICAST_LIST: rndis_query_cmplt32(RNDIS_STATUS_NOT_SUPPORTED, 0); return; + case OID_802_3_MAC_OPTIONS: rndis_query_cmplt32(RNDIS_STATUS_NOT_SUPPORTED, 0); return; + case OID_GEN_MAC_OPTIONS: rndis_query_cmplt32(RNDIS_STATUS_SUCCESS, /*MAC_OPT*/ 0); return; + case OID_802_3_RCV_ERROR_ALIGNMENT: rndis_query_cmplt32(RNDIS_STATUS_SUCCESS, 0); return; + case OID_802_3_XMIT_ONE_COLLISION: rndis_query_cmplt32(RNDIS_STATUS_SUCCESS, 0); return; + case OID_802_3_XMIT_MORE_COLLISIONS: rndis_query_cmplt32(RNDIS_STATUS_SUCCESS, 0); return; + case OID_GEN_XMIT_OK: rndis_query_cmplt32(RNDIS_STATUS_SUCCESS, usb_eth_stat.txok); return; + case OID_GEN_RCV_OK: rndis_query_cmplt32(RNDIS_STATUS_SUCCESS, usb_eth_stat.rxok); return; + case OID_GEN_RCV_ERROR: rndis_query_cmplt32(RNDIS_STATUS_SUCCESS, usb_eth_stat.rxbad); return; + case OID_GEN_XMIT_ERROR: rndis_query_cmplt32(RNDIS_STATUS_SUCCESS, usb_eth_stat.txbad); return; + case OID_GEN_RCV_NO_BUFFER: rndis_query_cmplt32(RNDIS_STATUS_SUCCESS, 0); return; + default: rndis_query_cmplt(RNDIS_STATUS_FAILURE, NULL, 0); return; + } +} + +#define INFBUF ((uint32_t *)((uint8_t *)&(m->RequestId) + m->InformationBufferOffset)) + +static void rndis_handle_config_parm(const char *data, int keyoffset, int valoffset, int keylen, int vallen) +{ + (void)data; + (void)keyoffset; + (void)valoffset; + (void)keylen; + (void)vallen; +} + +static void rndis_packetFilter(uint32_t newfilter) +{ + (void)newfilter; +} + +static void rndis_handle_set_msg(void) +{ + rndis_set_cmplt_t *c; + rndis_set_msg_t *m; + rndis_Oid_t oid; + + c = (rndis_set_cmplt_t *)encapsulated_buffer; + m = (rndis_set_msg_t *)encapsulated_buffer; + + oid = m->Oid; + c->MessageType = REMOTE_NDIS_SET_CMPLT; + c->MessageLength = sizeof(rndis_set_cmplt_t); + c->Status = RNDIS_STATUS_SUCCESS; + + switch (oid) + { + /* Parameters set up in 'Advanced' tab */ + case OID_GEN_RNDIS_CONFIG_PARAMETER: + { + rndis_config_parameter_t *p; + char *ptr = (char *)m; + ptr += sizeof(rndis_generic_msg_t); + ptr += m->InformationBufferOffset; + p = (rndis_config_parameter_t *)ptr; + rndis_handle_config_parm(ptr, p->ParameterNameOffset, p->ParameterValueOffset, p->ParameterNameLength, p->ParameterValueLength); + } + break; + + /* Mandatory general OIDs */ + case OID_GEN_CURRENT_PACKET_FILTER: + oid_packet_filter = *INFBUF; + if (oid_packet_filter) + { + rndis_packetFilter(oid_packet_filter); + rndis_state = rndis_data_initialized; + } + else + { + rndis_state = rndis_initialized; + } + break; + + case OID_GEN_CURRENT_LOOKAHEAD: + break; + + case OID_GEN_PROTOCOL_OPTIONS: + break; + + /* Mandatory 802_3 OIDs */ + case OID_802_3_MULTICAST_LIST: + break; + + /* Power Managment: fails for now */ + case OID_PNP_ADD_WAKE_UP_PATTERN: + case OID_PNP_REMOVE_WAKE_UP_PATTERN: + case OID_PNP_ENABLE_WAKE_UP: + default: + c->Status = RNDIS_STATUS_FAILURE; + break; + } + + /* c->MessageID is same as before */ + rndis_report(); + return; +} + +void rndis_class_set_handler(uint8_t *data, int size) +{ + encapsulated_buffer = data; + (void)size; + + switch (((rndis_generic_msg_t *)data)->MessageType) + { + case REMOTE_NDIS_INITIALIZE_MSG: + { + rndis_initialize_cmplt_t *m; + m = ((rndis_initialize_cmplt_t *)encapsulated_buffer); + /* m->MessageID is same as before */ + m->MessageType = REMOTE_NDIS_INITIALIZE_CMPLT; + m->MessageLength = sizeof(rndis_initialize_cmplt_t); + m->MajorVersion = RNDIS_MAJOR_VERSION; + m->MinorVersion = RNDIS_MINOR_VERSION; + m->Status = RNDIS_STATUS_SUCCESS; + m->DeviceFlags = RNDIS_DF_CONNECTIONLESS; + m->Medium = RNDIS_MEDIUM_802_3; + m->MaxPacketsPerTransfer = 1; + m->MaxTransferSize = CFG_TUD_NET_MTU + sizeof(rndis_data_packet_t); + m->PacketAlignmentFactor = 0; + m->AfListOffset = 0; + m->AfListSize = 0; + rndis_state = rndis_initialized; + rndis_report(); + } + break; + + case REMOTE_NDIS_QUERY_MSG: + rndis_query(); + break; + + case REMOTE_NDIS_SET_MSG: + rndis_handle_set_msg(); + break; + + case REMOTE_NDIS_RESET_MSG: + { + rndis_reset_cmplt_t * m; + m = ((rndis_reset_cmplt_t *)encapsulated_buffer); + rndis_state = rndis_uninitialized; + m->MessageType = REMOTE_NDIS_RESET_CMPLT; + m->MessageLength = sizeof(rndis_reset_cmplt_t); + m->Status = RNDIS_STATUS_SUCCESS; + m->AddressingReset = 1; /* Make it look like we did something */ + /* m->AddressingReset = 0; - Windows halts if set to 1 for some reason */ + rndis_report(); + } + break; + + case REMOTE_NDIS_KEEPALIVE_MSG: + { + rndis_keepalive_cmplt_t * m; + m = (rndis_keepalive_cmplt_t *)encapsulated_buffer; + m->MessageType = REMOTE_NDIS_KEEPALIVE_CMPLT; + m->MessageLength = sizeof(rndis_keepalive_cmplt_t); + m->Status = RNDIS_STATUS_SUCCESS; + } + /* We have data to send back */ + rndis_report(); + break; + + default: + break; + } +} diff --git a/src/class/net/net_device.c b/src/class/net/net_device.c new file mode 100644 index 00000000..422d435c --- /dev/null +++ b/src/class/net/net_device.c @@ -0,0 +1,345 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2020 Peter Lawrence + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#include "tusb_option.h" + +#if ( TUSB_OPT_DEVICE_ENABLED && (CFG_TUD_NET != OPT_NET_NONE) ) + +#include "net_device.h" +#include "device/usbd_pvt.h" +#include "rndis_protocol.h" + +void rndis_class_set_handler(uint8_t *data, int size); /* found in ./misc/networking/rndis_reports.c */ + +//--------------------------------------------------------------------+ +// MACRO CONSTANT TYPEDEF +//--------------------------------------------------------------------+ +typedef struct +{ + uint8_t itf_num; + uint8_t ep_notif; + uint8_t ep_in; + uint8_t ep_out; +} netd_interface_t; + +#if CFG_TUD_NET == OPT_NET_ECM + #define CFG_TUD_NET_PACKET_PREFIX_LEN 0 + #define CFG_TUD_NET_PACKET_SUFFIX_LEN 0 + #define CFG_TUD_NET_INTERFACESUBCLASS CDC_COMM_SUBCLASS_ETHERNET_NETWORKING_CONTROL_MODEL +#elif CFG_TUD_NET == OPT_NET_RNDIS + #define CFG_TUD_NET_PACKET_PREFIX_LEN sizeof(rndis_data_packet_t) + #define CFG_TUD_NET_PACKET_SUFFIX_LEN 0 + #define CFG_TUD_NET_INTERFACESUBCLASS TUD_RNDIS_ITF_SUBCLASS +#elif CFG_TUD_NET == OPT_NET_EEM + #define CFG_TUD_NET_PACKET_PREFIX_LEN 2 + #define CFG_TUD_NET_PACKET_SUFFIX_LEN 4 + #define CFG_TUD_NET_INTERFACESUBCLASS CDC_COMM_SUBCLASS_ETHERNET_EMULATION_MODEL +#endif + +CFG_TUSB_MEM_SECTION CFG_TUSB_MEM_ALIGN static uint8_t received[CFG_TUD_NET_PACKET_PREFIX_LEN + CFG_TUD_NET_MTU + CFG_TUD_NET_PACKET_PREFIX_LEN]; +CFG_TUSB_MEM_SECTION CFG_TUSB_MEM_ALIGN static uint8_t transmitted[CFG_TUD_NET_PACKET_PREFIX_LEN + CFG_TUD_NET_MTU + CFG_TUD_NET_PACKET_PREFIX_LEN]; + +#if CFG_TUD_NET == OPT_NET_RNDIS + CFG_TUSB_MEM_SECTION CFG_TUSB_MEM_ALIGN static uint8_t rndis_buf[128]; +#endif + +//--------------------------------------------------------------------+ +// INTERNAL OBJECT & FUNCTION DECLARATION +//--------------------------------------------------------------------+ +CFG_TUSB_MEM_SECTION static netd_interface_t _netd_itf; + +static bool can_xmit; + +void network_recv_renew(void) +{ + usbd_edpt_xfer(TUD_OPT_RHPORT, _netd_itf.ep_out, received, sizeof(received)); +} + +static void do_in_xfer(uint8_t *buf, uint16_t len) +{ + can_xmit = false; + usbd_edpt_xfer(TUD_OPT_RHPORT, _netd_itf.ep_in, buf, len); +} + +void netd_report(uint8_t *buf, uint16_t len) +{ + usbd_edpt_xfer(TUD_OPT_RHPORT, _netd_itf.ep_notif, buf, len); +} + +//--------------------------------------------------------------------+ +// USBD Driver API +//--------------------------------------------------------------------+ +void netd_init(void) +{ + tu_memclr(&_netd_itf, sizeof(_netd_itf)); +} + +void netd_reset(uint8_t rhport) +{ + (void) rhport; + + netd_init(); +} + +bool netd_open(uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t *p_length) +{ + // sanity check the descriptor + TU_ASSERT (CFG_TUD_NET_INTERFACESUBCLASS == itf_desc->bInterfaceSubClass); + + // confirm interface hasn't already been allocated + TU_ASSERT(0 == _netd_itf.ep_in); + + //------------- first Interface -------------// + _netd_itf.itf_num = itf_desc->bInterfaceNumber; + + uint8_t const * p_desc = tu_desc_next( itf_desc ); + (*p_length) = sizeof(tusb_desc_interface_t); + +#if CFG_TUD_NET != OPT_NET_EEM + // Communication Functional Descriptors + while ( TUSB_DESC_CS_INTERFACE == tu_desc_type(p_desc) ) + { + (*p_length) += tu_desc_len(p_desc); + p_desc = tu_desc_next(p_desc); + } + + // notification endpoint (if any) + if ( TUSB_DESC_ENDPOINT == tu_desc_type(p_desc) ) + { + TU_ASSERT( dcd_edpt_open(rhport, (tusb_desc_endpoint_t const *) p_desc) ); + + _netd_itf.ep_notif = ((tusb_desc_endpoint_t const *) p_desc)->bEndpointAddress; + + (*p_length) += p_desc[DESC_OFFSET_LEN]; + p_desc = tu_desc_next(p_desc); + } + + //------------- second Interface -------------// + if ( (TUSB_DESC_INTERFACE == p_desc[DESC_OFFSET_TYPE]) && + (TUSB_CLASS_CDC_DATA == ((tusb_desc_interface_t const *) p_desc)->bInterfaceClass) ) + { + // next to endpoint descriptor + p_desc = tu_desc_next(p_desc); + (*p_length) += sizeof(tusb_desc_interface_t); + } +#endif + + if (TUSB_DESC_ENDPOINT == p_desc[DESC_OFFSET_TYPE]) + { + // Open endpoint pair + TU_ASSERT( usbd_open_edpt_pair(rhport, p_desc, 2, TUSB_XFER_BULK, &_netd_itf.ep_out, &_netd_itf.ep_in) ); + + (*p_length) += 2*sizeof(tusb_desc_endpoint_t); + } + + network_init_callback(); + + // we are ready to transmit a packet + can_xmit = true; + + // prepare for incoming packets + network_recv_renew(); + + return true; +} + +// Invoked when class request DATA stage is finished. +// return false to stall control endpoint (e.g Host send nonsense DATA) +bool netd_control_complete(uint8_t rhport, tusb_control_request_t const * request) +{ + (void) rhport; + + // Handle class request only + TU_VERIFY (request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS); + + TU_VERIFY (_netd_itf.itf_num == request->wIndex); + +#if CFG_TUD_NET == OPT_NET_RNDIS + if (request->bmRequestType_bit.direction == TUSB_DIR_OUT) + { + rndis_class_set_handler(rndis_buf, request->wLength); + } +#endif + + return true; +} + +// Handle class control request +// return false to stall control endpoint (e.g unsupported request) +bool netd_control_request(uint8_t rhport, tusb_control_request_t const * request) +{ + // Handle class request only + TU_VERIFY(request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS); + + TU_VERIFY (_netd_itf.itf_num == request->wIndex); + +#if CFG_TUD_NET == OPT_NET_RNDIS + tud_control_xfer(rhport, request, rndis_buf, sizeof(rndis_buf)); +#else + (void)rhport; +#endif + + return true; +} + +struct cdc_eem_packet_header +{ + uint16_t length:14; + uint16_t bmCRC:1; + uint16_t bmType:1; +}; + +static void handle_incoming_packet(uint32_t len) +{ + uint8_t *pnt = received; + uint32_t size = 0; + +#if CFG_TUD_NET == OPT_NET_ECM + size = len; +#elif CFG_TUD_NET == OPT_NET_RNDIS + rndis_data_packet_t *r = (rndis_data_packet_t *)pnt; + if (len >= sizeof(rndis_data_packet_t)) + if ( (r->MessageType == REMOTE_NDIS_PACKET_MSG) && (r->MessageLength <= len)) + if ( (r->DataOffset + offsetof(rndis_data_packet_t, DataOffset) + r->DataLength) <= len) + { + pnt = &received[r->DataOffset + offsetof(rndis_data_packet_t, DataOffset)]; + size = r->DataLength; + } +#elif CFG_TUD_NET == OPT_NET_EEM + struct cdc_eem_packet_header *hdr = (struct cdc_eem_packet_header *)pnt; + + (void)len; + + if (hdr->bmType) + { + /* EEM Control Packet: discard it */ + network_recv_renew(); + } + else + { + /* EEM Data Packet */ + pnt += CFG_TUD_NET_PACKET_PREFIX_LEN; + size = hdr->length - 4; /* discard the unused CRC-32 */ + } +#endif + + if (size) + { + struct pbuf *p = pbuf_alloc(PBUF_RAW, size, PBUF_POOL); + bool accepted = true; + + if (p) + { + memcpy(p->payload, pnt, size); + p->len = size; + accepted = network_recv_callback(p); + } + + if (!p || !accepted) + { + /* if a buffer couldn't be allocated or accepted by the callback, we must discard this packet */ + network_recv_renew(); + } + } +} + +bool netd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes) +{ + (void) rhport; + (void) result; + + /* new packet received */ + if ( ep_addr == _netd_itf.ep_out ) + { + handle_incoming_packet(xferred_bytes); + } + + /* data transmission finished */ + if ( ep_addr == _netd_itf.ep_in ) + { + /* TinyUSB requires the class driver to implement ZLP (since ZLP usage is class-specific) */ + + if ( xferred_bytes && (0 == (xferred_bytes % CFG_TUD_NET_ENDPOINT_SIZE)) ) + { + do_in_xfer(NULL, 0); /* a ZLP is needed */ + } + else + { + /* we're finally finished */ + can_xmit = true; + } + } + + return true; +} + +bool network_can_xmit(void) +{ + return can_xmit; +} + +void network_xmit(struct pbuf *p) +{ + struct pbuf *q; + uint8_t *data; + uint16_t len; + + if (!can_xmit) + return; + + len = CFG_TUD_NET_PACKET_PREFIX_LEN; + data = transmitted + len; + + for(q = p; q != NULL; q = q->next) + { + memcpy(data, (char *)q->payload, q->len); + data += q->len; + len += q->len; + } + +#if CFG_TUD_NET == OPT_NET_RNDIS + rndis_data_packet_t *hdr = (rndis_data_packet_t *)transmitted; + memset(hdr, 0, sizeof(rndis_data_packet_t)); + hdr->MessageType = REMOTE_NDIS_PACKET_MSG; + hdr->MessageLength = len; + hdr->DataOffset = sizeof(rndis_data_packet_t) - offsetof(rndis_data_packet_t, DataOffset); + hdr->DataLength = len - sizeof(rndis_data_packet_t); +#elif CFG_TUD_NET == OPT_NET_EEM + struct cdc_eem_packet_header *hdr = (struct cdc_eem_packet_header *)transmitted; + /* append a fake CRC-32; the standard allows 0xDEADBEEF, which takes less CPU time */ + data[0] = 0xDE; data[1] = 0xAD; data[2] = 0xBE; data[3] = 0xEF; + /* adjust length to reflect added fake CRC-32 */ + len += 4; + hdr->bmType = 0; /* EEM Data Packet */ + hdr->length = len - sizeof(struct cdc_eem_packet_header); + hdr->bmCRC = 0; /* Ethernet Frame CRC-32 set to 0xDEADBEEF */ +#endif + + do_in_xfer(transmitted, len); +} + +#endif diff --git a/src/class/net/net_device.h b/src/class/net/net_device.h new file mode 100644 index 00000000..c61efc86 --- /dev/null +++ b/src/class/net/net_device.h @@ -0,0 +1,84 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2020 Peter Lawrence + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#ifndef _TUSB_NET_DEVICE_H_ +#define _TUSB_NET_DEVICE_H_ + +#include "common/tusb_common.h" +#include "device/usbd.h" +#include "class/cdc/cdc.h" +#include "lwip/pbuf.h" +#include "netif/ethernet.h" + +/* declared here, NOT in usb_descriptors.c, so that the driver can intelligently ZLP as needed */ +#define CFG_TUD_NET_ENDPOINT_SIZE ((CFG_TUSB_RHPORT0_MODE & OPT_MODE_HIGH_SPEED) ? 512 : 64) + +/* Maximum Tranmission Unit (in bytes) of the network, including Ethernet header */ +#define CFG_TUD_NET_MTU (1500 + SIZEOF_ETH_HDR) + +#ifdef __cplusplus + extern "C" { +#endif + +//--------------------------------------------------------------------+ +// Application API +//--------------------------------------------------------------------+ + +// client must provide this: initialize any network state back to the beginning +void network_init_callback(void); + +// client must provide this: return false if the packet buffer was not accepted +bool network_recv_callback(struct pbuf *p); + +// client must provide this: 48-bit MAC address +extern const uint8_t network_mac_address[6]; + +// indicate to network driver that client has finished with the packet provided to network_recv_callback() +void network_recv_renew(void); + +// poll network driver for its ability to accept another packet to transmit +bool network_can_xmit(void); + +// if network_can_xmit() returns true, network_xmit() can be called once +void network_xmit(struct pbuf *p); + +//--------------------------------------------------------------------+ +// INTERNAL USBD-CLASS DRIVER API +//--------------------------------------------------------------------+ +void netd_init (void); +void netd_reset (uint8_t rhport); +bool netd_open (uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t *p_length); +bool netd_control_request (uint8_t rhport, tusb_control_request_t const * request); +bool netd_control_complete (uint8_t rhport, tusb_control_request_t const * request); +bool netd_xfer_cb (uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes); +void netd_report (uint8_t *buf, uint16_t len); + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_NET_DEVICE_H_ */ diff --git a/src/device/usbd.c b/src/device/usbd.c index 68c5c516..32a89889 100644 --- a/src/device/usbd.c +++ b/src/device/usbd.c @@ -181,6 +181,24 @@ static usbd_class_driver_t const _usbd_driver[] = .sof = NULL }, #endif + + #if CFG_TUD_NET + { + .class_code = +#if CFG_TUD_NET == OPT_NET_RNDIS + TUD_RNDIS_ITF_CLASS, +#else + TUSB_CLASS_CDC, +#endif + .init = netd_init, + .reset = netd_reset, + .open = netd_open, + .control_request = netd_control_request, + .control_complete = netd_control_complete, + .xfer_cb = netd_xfer_cb, + .sof = NULL + }, + #endif }; enum { USBD_CLASS_DRIVER_COUNT = TU_ARRAY_SIZE(_usbd_driver) }; diff --git a/src/device/usbd.h b/src/device/usbd.h index d80abf17..07163a01 100644 --- a/src/device/usbd.h +++ b/src/device/usbd.h @@ -326,6 +326,90 @@ TU_ATTR_WEAK bool tud_vendor_control_complete_cb(uint8_t rhport, tusb_control_re 9, DFU_DESC_FUNCTIONAL, _attr, U16_TO_U8S_LE(_timeout), U16_TO_U8S_LE(_xfer_size), U16_TO_U8S_LE(0x0101) +//------------- CDC-ECM -------------// + +// Length of template descriptor: 62 bytes +#define TUD_CDC_ECM_DESC_LEN (9+5+5+13+7+9+7+7) + +// CDC-ECM Descriptor Template +// Interface number, description string index, MAC address string index, EP notification address and size, EP data address (out, in), and size, max segment size. +#define TUD_CDC_ECM_DESCRIPTOR(_itfnum, _desc_stridx, _mac_stridx, _ep_notif, _ep_notif_size, _epout, _epin, _epsize, _maxsegmentsize) \ + /* CDC Control Interface */\ + 9, TUSB_DESC_INTERFACE, _itfnum, 0, 1, TUSB_CLASS_CDC, CDC_COMM_SUBCLASS_ETHERNET_NETWORKING_CONTROL_MODEL, 0, _desc_stridx,\ + /* CDC-ECM Header */\ + 5, TUSB_DESC_CS_INTERFACE, CDC_FUNC_DESC_HEADER, U16_TO_U8S_LE(0x0120),\ + /* CDC-ECM Union */\ + 5, TUSB_DESC_CS_INTERFACE, CDC_FUNC_DESC_UNION, _itfnum, (uint8_t)((_itfnum) + 1),\ + /* CDC-ECM Functional Descriptor */\ + 13, TUSB_DESC_CS_INTERFACE, CDC_FUNC_DESC_ETHERNET_NETWORKING, _mac_stridx, 0, 0, 0, 0, U16_TO_U8S_LE(_maxsegmentsize), U16_TO_U8S_LE(0), 0,\ + /* Endpoint Notification */\ + 7, TUSB_DESC_ENDPOINT, _ep_notif, TUSB_XFER_INTERRUPT, U16_TO_U8S_LE(_ep_notif_size), 1,\ + /* CDC Data Interface */\ + 9, TUSB_DESC_INTERFACE, (uint8_t)((_itfnum)+1), 0, 2, TUSB_CLASS_CDC_DATA, 0, 0, 0,\ + /* Endpoint In */\ + 7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0,\ + /* Endpoint Out */\ + 7, TUSB_DESC_ENDPOINT, _epout, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0 + + +//------------- RNDIS -------------// + +#if 0 + /* Windows XP */ + #define TUD_RNDIS_ITF_CLASS TUSB_CLASS_CDC + #define TUD_RNDIS_ITF_SUBCLASS CDC_COMM_SUBCLASS_ABSTRACT_CONTROL_MODEL + #define TUD_RNDIS_ITF_PROTOCOL CDC_COMM_PROTOCOL_MICROSOFT_RNDIS +#else + /* Windows 7+ */ + #define TUD_RNDIS_ITF_CLASS 0xE0 + #define TUD_RNDIS_ITF_SUBCLASS 0x01 + #define TUD_RNDIS_ITF_PROTOCOL 0x03 +#endif + +// Length of template descriptor: 66 bytes +#define TUD_RNDIS_DESC_LEN (8+9+5+5+4+5+7+9+7+7) + +// RNDIS Descriptor Template +// Interface number, string index, EP notification address and size, EP data address (out, in) and size. +#define TUD_RNDIS_DESCRIPTOR(_itfnum, _stridx, _ep_notif, _ep_notif_size, _epout, _epin, _epsize) \ + /* Interface Association */\ + 8, TUSB_DESC_INTERFACE_ASSOCIATION, _itfnum, 2, TUD_RNDIS_ITF_CLASS, TUD_RNDIS_ITF_SUBCLASS, TUD_RNDIS_ITF_PROTOCOL, 0,\ + /* CDC Control Interface */\ + 9, TUSB_DESC_INTERFACE, _itfnum, 0, 1, TUD_RNDIS_ITF_CLASS, TUD_RNDIS_ITF_SUBCLASS, TUD_RNDIS_ITF_PROTOCOL, _stridx,\ + /* CDC-ACM Header */\ + 5, TUSB_DESC_CS_INTERFACE, CDC_FUNC_DESC_HEADER, U16_TO_U8S_LE(0x0110),\ + /* CDC Call Management */\ + 5, TUSB_DESC_CS_INTERFACE, CDC_FUNC_DESC_CALL_MANAGEMENT, 0, (uint8_t)((_itfnum) + 1),\ + /* ACM */\ + 4, TUSB_DESC_CS_INTERFACE, CDC_FUNC_DESC_ABSTRACT_CONTROL_MANAGEMENT, 0,\ + /* CDC Union */\ + 5, TUSB_DESC_CS_INTERFACE, CDC_FUNC_DESC_UNION, _itfnum, (uint8_t)((_itfnum) + 1),\ + /* Endpoint Notification */\ + 7, TUSB_DESC_ENDPOINT, _ep_notif, TUSB_XFER_INTERRUPT, U16_TO_U8S_LE(_ep_notif_size), 1,\ + /* CDC Data Interface */\ + 9, TUSB_DESC_INTERFACE, (uint8_t)((_itfnum)+1), 0, 2, TUSB_CLASS_CDC_DATA, 0, 0, 0,\ + /* Endpoint In */\ + 7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0,\ + /* Endpoint Out */\ + 7, TUSB_DESC_ENDPOINT, _epout, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0 + + +//------------- CDC-EEM -------------// + +// Length of template descriptor: 23 bytes +#define TUD_CDC_EEM_DESC_LEN (9+7+7) + +// CDC-EEM Descriptor Template +// Interface number, description string index, EP data address (out, in) and size. +#define TUD_CDC_EEM_DESCRIPTOR(_itfnum, _stridx, _epout, _epin, _epsize) \ + /* EEM Interface */\ + 9, TUSB_DESC_INTERFACE, _itfnum, 0, 2, TUSB_CLASS_CDC, CDC_COMM_SUBCLASS_ETHERNET_EMULATION_MODEL, CDC_COMM_PROTOCOL_ETHERNET_EMULATION_MODEL, _stridx,\ + /* Endpoint In */\ + 7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0,\ + /* Endpoint Out */\ + 7, TUSB_DESC_ENDPOINT, _epout, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0 + + #ifdef __cplusplus } #endif diff --git a/src/tusb.h b/src/tusb.h index 7dcddf64..55c10512 100644 --- a/src/tusb.h +++ b/src/tusb.h @@ -91,6 +91,10 @@ #if CFG_TUD_DFU_RT #include "class/dfu/dfu_rt_device.h" #endif + + #if CFG_TUD_NET + #include "class/net/net_device.h" + #endif #endif diff --git a/src/tusb_option.h b/src/tusb_option.h index 97f14532..00d4a39d 100644 --- a/src/tusb_option.h +++ b/src/tusb_option.h @@ -117,6 +117,15 @@ #define OPT_MODE_HIGH_SPEED 0x10 ///< High speed /** @} */ +/** \defgroup group_supported_netif Supported Network Interface + * \ref CFG_TUD_NET must be defined to one of these + * @{ */ +#define OPT_NET_NONE 0 ///< No network interface +#define OPT_NET_ECM 1 ///< CDC-ECM +#define OPT_NET_RNDIS 2 ///< RNDIS +#define OPT_NET_EEM 3 ///< CDC-EEM +/** @} */ + #ifndef CFG_TUSB_RHPORT0_MODE #define CFG_TUSB_RHPORT0_MODE OPT_MODE_NONE #endif @@ -204,6 +213,9 @@ #define CFG_TUD_DFU_RT 0 #endif +#ifndef CFG_TUD_NET + #define CFG_TUD_NET 0 +#endif //-------------------------------------------------------------------- // HOST OPTIONS From 4a4682a80a2bd3d6d607d5a960443656de32955d Mon Sep 17 00:00:00 2001 From: Peter Lawrence <12226419+majbthrd@users.noreply.github.com> Date: Tue, 3 Mar 2020 10:31:46 -0600 Subject: [PATCH 235/267] update net class to follow API naming convention --- examples/device/lwip_webserver/src/main.c | 20 +++++++++---------- .../lwip_webserver/src/usb_descriptors.c | 6 +++--- lib/networking/rndis_reports.c | 4 ++-- src/class/net/net_device.c | 16 +++++++-------- src/class/net/net_device.h | 14 ++++++------- 5 files changed, 30 insertions(+), 30 deletions(-) diff --git a/examples/device/lwip_webserver/src/main.c b/examples/device/lwip_webserver/src/main.c index 364a2678..c193aeb0 100644 --- a/examples/device/lwip_webserver/src/main.c +++ b/examples/device/lwip_webserver/src/main.c @@ -48,12 +48,12 @@ The MCU appears to the host as IP address 192.168.7.1, and provides a DHCP serve /* lwip context */ static struct netif netif_data; -/* shared between network_recv_callback() and service_traffic() */ +/* shared between tud_network_recv_cb() and service_traffic() */ static struct pbuf *received_frame; /* this is used by this code, ./class/net/net_driver.c, and usb_descriptors.c */ /* ideally speaking, this should be generated from the hardware's unique ID (if available) */ -const uint8_t network_mac_address[6] = {0x20,0x89,0x84,0x6A,0x96,0x00}; +const uint8_t tud_network_mac_address[6] = {0x20,0x89,0x84,0x6A,0x96,0x00}; /* network parameters of this MCU */ static const ip_addr_t ipaddr = IPADDR4_INIT_BYTES(192, 168, 7, 1); @@ -90,9 +90,9 @@ static err_t linkoutput_fn(struct netif *netif, struct pbuf *p) return ERR_USE; /* if the network driver can accept another packet, we make it happen */ - if (network_can_xmit()) + if (tud_network_can_xmit()) { - network_xmit(p); + tud_network_xmit(p); return ERR_OK; } @@ -124,8 +124,8 @@ static void init_lwip(void) struct netif *netif = &netif_data; lwip_init(); - netif->hwaddr_len = sizeof(network_mac_address); - memcpy(netif->hwaddr, network_mac_address, sizeof(network_mac_address)); + netif->hwaddr_len = sizeof(tud_network_mac_address); + memcpy(netif->hwaddr, tud_network_mac_address, sizeof(tud_network_mac_address)); netif = netif_add(netif, &ipaddr, &netmask, &gateway, NULL, netif_init_cb, ip_input); netif_set_default(netif); @@ -142,7 +142,7 @@ bool dns_query_proc(const char *name, ip_addr_t *addr) return false; } -bool network_recv_callback(struct pbuf *p) +bool tud_network_recv_cb(struct pbuf *p) { /* this shouldn't happen, but if we get another packet before parsing the previous, we must signal our inability to accept it */ @@ -155,17 +155,17 @@ bool network_recv_callback(struct pbuf *p) static void service_traffic(void) { - /* handle any packet received by network_recv_callback() */ + /* handle any packet received by tud_network_recv_cb() */ if (received_frame) { ethernet_input(received_frame, &netif_data); pbuf_free(received_frame); received_frame = NULL; - network_recv_renew(); + tud_network_recv_renew(); } } -void network_init_callback(void) +void tud_network_init_cb(void) { /* if the network is re-initializing and we have a leftover packet, we must do a cleanup */ if (received_frame) diff --git a/examples/device/lwip_webserver/src/usb_descriptors.c b/examples/device/lwip_webserver/src/usb_descriptors.c index 803c99c0..26f8aeba 100644 --- a/examples/device/lwip_webserver/src/usb_descriptors.c +++ b/examples/device/lwip_webserver/src/usb_descriptors.c @@ -168,10 +168,10 @@ uint16_t const* tud_descriptor_string_cb(uint8_t index, uint16_t langid) { // Convert MAC address into UTF-16 - for (unsigned i=0; i> 4) & 0xf]; - _desc_str[1+chr_count++] = "0123456789ABCDEF"[(network_mac_address[i] >> 0) & 0xf]; + _desc_str[1+chr_count++] = "0123456789ABCDEF"[(tud_network_mac_address[i] >> 4) & 0xf]; + _desc_str[1+chr_count++] = "0123456789ABCDEF"[(tud_network_mac_address[i] >> 0) & 0xf]; } } else diff --git a/lib/networking/rndis_reports.c b/lib/networking/rndis_reports.c index 535bdf85..9c470b62 100644 --- a/lib/networking/rndis_reports.c +++ b/lib/networking/rndis_reports.c @@ -36,8 +36,8 @@ #define RNDIS_LINK_SPEED 12000000 /* Link baudrate (12Mbit/s for USB-FS) */ #define RNDIS_VENDOR "TinyUSB" /* NIC vendor name */ -static const uint8_t *const station_hwaddr = network_mac_address; -static const uint8_t *const permanent_hwaddr = network_mac_address; +static const uint8_t *const station_hwaddr = tud_network_mac_address; +static const uint8_t *const permanent_hwaddr = tud_network_mac_address; static usb_eth_stat_t usb_eth_stat = { 0, 0, 0, 0 }; static uint32_t oid_packet_filter = 0x0000000; diff --git a/src/class/net/net_device.c b/src/class/net/net_device.c index 422d435c..c918e587 100644 --- a/src/class/net/net_device.c +++ b/src/class/net/net_device.c @@ -74,7 +74,7 @@ CFG_TUSB_MEM_SECTION static netd_interface_t _netd_itf; static bool can_xmit; -void network_recv_renew(void) +void tud_network_recv_renew(void) { usbd_edpt_xfer(TUD_OPT_RHPORT, _netd_itf.ep_out, received, sizeof(received)); } @@ -156,13 +156,13 @@ bool netd_open(uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t (*p_length) += 2*sizeof(tusb_desc_endpoint_t); } - network_init_callback(); + tud_network_init_cb(); // we are ready to transmit a packet can_xmit = true; // prepare for incoming packets - network_recv_renew(); + tud_network_recv_renew(); return true; } @@ -237,7 +237,7 @@ static void handle_incoming_packet(uint32_t len) if (hdr->bmType) { /* EEM Control Packet: discard it */ - network_recv_renew(); + tud_network_recv_renew(); } else { @@ -256,13 +256,13 @@ static void handle_incoming_packet(uint32_t len) { memcpy(p->payload, pnt, size); p->len = size; - accepted = network_recv_callback(p); + accepted = tud_network_recv_cb(p); } if (!p || !accepted) { /* if a buffer couldn't be allocated or accepted by the callback, we must discard this packet */ - network_recv_renew(); + tud_network_recv_renew(); } } } @@ -297,12 +297,12 @@ bool netd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_ return true; } -bool network_can_xmit(void) +bool tud_network_can_xmit(void) { return can_xmit; } -void network_xmit(struct pbuf *p) +void tud_network_xmit(struct pbuf *p) { struct pbuf *q; uint8_t *data; diff --git a/src/class/net/net_device.h b/src/class/net/net_device.h index c61efc86..fee54163 100644 --- a/src/class/net/net_device.h +++ b/src/class/net/net_device.h @@ -49,22 +49,22 @@ //--------------------------------------------------------------------+ // client must provide this: initialize any network state back to the beginning -void network_init_callback(void); +void tud_network_init_cb(void); // client must provide this: return false if the packet buffer was not accepted -bool network_recv_callback(struct pbuf *p); +bool tud_network_recv_cb(struct pbuf *p); // client must provide this: 48-bit MAC address -extern const uint8_t network_mac_address[6]; +extern const uint8_t tud_network_mac_address[6]; -// indicate to network driver that client has finished with the packet provided to network_recv_callback() -void network_recv_renew(void); +// indicate to network driver that client has finished with the packet provided to network_recv_cb() +void tud_network_recv_renew(void); // poll network driver for its ability to accept another packet to transmit -bool network_can_xmit(void); +bool tud_network_can_xmit(void); // if network_can_xmit() returns true, network_xmit() can be called once -void network_xmit(struct pbuf *p); +void tud_network_xmit(struct pbuf *p); //--------------------------------------------------------------------+ // INTERNAL USBD-CLASS DRIVER API From d74facfd0aede63da35c067ae8b8f3e4ed29ac6f Mon Sep 17 00:00:00 2001 From: Peter Lawrence <12226419+majbthrd@users.noreply.github.com> Date: Wed, 4 Mar 2020 17:54:11 -0600 Subject: [PATCH 236/267] usbnet RNDIS correction --- src/class/net/net_device.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/class/net/net_device.c b/src/class/net/net_device.c index c918e587..d0d32e90 100644 --- a/src/class/net/net_device.c +++ b/src/class/net/net_device.c @@ -64,7 +64,7 @@ CFG_TUSB_MEM_SECTION CFG_TUSB_MEM_ALIGN static uint8_t received[CFG_TUD_NET_PACK CFG_TUSB_MEM_SECTION CFG_TUSB_MEM_ALIGN static uint8_t transmitted[CFG_TUD_NET_PACKET_PREFIX_LEN + CFG_TUD_NET_MTU + CFG_TUD_NET_PACKET_PREFIX_LEN]; #if CFG_TUD_NET == OPT_NET_RNDIS - CFG_TUSB_MEM_SECTION CFG_TUSB_MEM_ALIGN static uint8_t rndis_buf[128]; + CFG_TUSB_MEM_SECTION CFG_TUSB_MEM_ALIGN static uint8_t rndis_buf[120]; #endif //--------------------------------------------------------------------+ From 800330cdf0b8be9a6d5c33cb3811c39f160a5019 Mon Sep 17 00:00:00 2001 From: hathach Date: Sat, 7 Mar 2020 17:27:59 +0700 Subject: [PATCH 237/267] added feather nrf52840 sense --- hw/bsp/feather_nrf52840_sense/board.mk | 63 ++++++ .../feather_nrf52840_sense.c | 192 ++++++++++++++++++ .../nrf52840_s140_v6.ld | 38 ++++ 3 files changed, 293 insertions(+) create mode 100644 hw/bsp/feather_nrf52840_sense/board.mk create mode 100644 hw/bsp/feather_nrf52840_sense/feather_nrf52840_sense.c create mode 100644 hw/bsp/feather_nrf52840_sense/nrf52840_s140_v6.ld diff --git a/hw/bsp/feather_nrf52840_sense/board.mk b/hw/bsp/feather_nrf52840_sense/board.mk new file mode 100644 index 00000000..b4d6fbe9 --- /dev/null +++ b/hw/bsp/feather_nrf52840_sense/board.mk @@ -0,0 +1,63 @@ +CFLAGS += \ + -flto \ + -mthumb \ + -mabi=aapcs \ + -mcpu=cortex-m4 \ + -mfloat-abi=hard \ + -mfpu=fpv4-sp-d16 \ + -DCFG_TUSB_MCU=OPT_MCU_NRF5X \ + -DNRF52840_XXAA \ + -DCONFIG_GPIO_AS_PINRESET + +# nrfx issue undef _ARMCC_VERSION usage https://github.com/NordicSemiconductor/nrfx/issues/49 +CFLAGS += -Wno-error=undef -Wno-error=unused-parameter + +# due to tusb_hal_nrf_power_event +GCCVERSION = $(firstword $(subst ., ,$(shell arm-none-eabi-gcc -dumpversion))) +ifeq ($(shell expr $(GCCVERSION) \>= 8), 1) +CFLAGS += -Wno-error=cast-function-type +endif + +# All source paths should be relative to the top level. +LD_FILE = hw/bsp/feather_nrf52840_express/nrf52840_s140_v6.ld + +LDFLAGS += -L$(TOP)/hw/mcu/nordic/nrfx/mdk + +SRC_C += \ + hw/mcu/nordic/nrfx/drivers/src/nrfx_power.c \ + hw/mcu/nordic/nrfx/mdk/system_nrf52840.c \ + +INC += \ + $(TOP)/hw/mcu/nordic/cmsis/Include \ + $(TOP)/hw/mcu/nordic \ + $(TOP)/hw/mcu/nordic/nrfx \ + $(TOP)/hw/mcu/nordic/nrfx/mdk \ + $(TOP)/hw/mcu/nordic/nrfx/hal \ + $(TOP)/hw/mcu/nordic/nrfx/drivers/include \ + $(TOP)/hw/mcu/nordic/nrfx/drivers/src \ + +SRC_S += hw/mcu/nordic/nrfx/mdk/gcc_startup_nrf52840.S + +ASFLAGS += -D__HEAP_SIZE=0 + +# For TinyUSB port source +VENDOR = nordic +CHIP_FAMILY = nrf5x + +# For freeRTOS port source +FREERTOS_PORT = ARM_CM4F + +# For flash-jlink target +JLINK_DEVICE = nRF52840_xxAA +JLINK_IF = swd + +# For uf2 conversion +UF2_FAMILY = 0xADA52840 + +$(BUILD)/$(BOARD)-firmware.zip: $(BUILD)/$(BOARD)-firmware.hex + adafruit-nrfutil dfu genpkg --dev-type 0x0052 --sd-req 0xFFFE --application $^ $@ + +# flash using adafruit-nrfutil dfu +flash: $(BUILD)/$(BOARD)-firmware.zip + @:$(call check_defined, SERIAL, example: SERIAL=/dev/ttyACM0) + adafruit-nrfutil --verbose dfu serial --package $^ -p $(SERIAL) -b 115200 --singlebank --touch 1200 diff --git a/hw/bsp/feather_nrf52840_sense/feather_nrf52840_sense.c b/hw/bsp/feather_nrf52840_sense/feather_nrf52840_sense.c new file mode 100644 index 00000000..468f96c5 --- /dev/null +++ b/hw/bsp/feather_nrf52840_sense/feather_nrf52840_sense.c @@ -0,0 +1,192 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#include "bsp/board.h" + +#include "nrfx.h" +#include "nrfx/hal/nrf_gpio.h" +#include "nrfx/drivers/include/nrfx_power.h" + +#ifdef SOFTDEVICE_PRESENT +#include "nrf_sdm.h" +#include "nrf_soc.h" +#endif + +/*------------------------------------------------------------------*/ +/* MACRO TYPEDEF CONSTANT ENUM + *------------------------------------------------------------------*/ +#define _PINNUM(port, pin) ((port)*32 + (pin)) + +#define LED_PIN _PINNUM(1, 9) +#define LED_STATE_ON 1 + +#define BUTTON_PIN _PINNUM(1, 02) + +// tinyusb function that handles power event (detected, ready, removed) +// We must call it within SD's SOC event handler, or set it as power event handler if SD is not enabled. +extern void tusb_hal_nrf_power_event(uint32_t event); + +void board_init(void) +{ + // Config clock source: XTAL or RC in sdk_config.h + NRF_CLOCK->LFCLKSRC = (uint32_t)((CLOCK_LFCLKSRC_SRC_Xtal << CLOCK_LFCLKSRC_SRC_Pos) & CLOCK_LFCLKSRC_SRC_Msk); + NRF_CLOCK->TASKS_LFCLKSTART = 1UL; + + // LED + nrf_gpio_cfg_output(LED_PIN); + board_led_write(false); + + // Button + nrf_gpio_cfg_input(BUTTON_PIN, NRF_GPIO_PIN_PULLUP); + +#if CFG_TUSB_OS == OPT_OS_NONE + // 1ms tick timer + SysTick_Config(SystemCoreClock/1000); +#endif + +#if TUSB_OPT_DEVICE_ENABLED + // Priorities 0, 1, 4 (nRF52) are reserved for SoftDevice + // 2 is highest for application + NVIC_SetPriority(USBD_IRQn, 2); + + + // USB power may already be ready at this time -> no event generated + // We need to invoke the handler based on the status initially + uint32_t usb_reg; + +#ifdef SOFTDEVICE_PRESENT + uint8_t sd_en = false; + sd_softdevice_is_enabled(&sd_en); + + if ( sd_en ) { + sd_power_usbdetected_enable(true); + sd_power_usbpwrrdy_enable(true); + sd_power_usbremoved_enable(true); + + sd_power_usbregstatus_get(&usb_reg); + }else +#endif + { + // Power module init + const nrfx_power_config_t pwr_cfg = { 0 }; + nrfx_power_init(&pwr_cfg); + + // Register tusb function as USB power handler + const nrfx_power_usbevt_config_t config = { .handler = (nrfx_power_usb_event_handler_t) tusb_hal_nrf_power_event }; + nrfx_power_usbevt_init(&config); + + nrfx_power_usbevt_enable(); + + usb_reg = NRF_POWER->USBREGSTATUS; + } + + if ( usb_reg & POWER_USBREGSTATUS_VBUSDETECT_Msk ) tusb_hal_nrf_power_event(NRFX_POWER_USB_EVT_DETECTED); + if ( usb_reg & POWER_USBREGSTATUS_OUTPUTRDY_Msk ) tusb_hal_nrf_power_event(NRFX_POWER_USB_EVT_READY); +#endif +} + +//--------------------------------------------------------------------+ +// Board porting API +//--------------------------------------------------------------------+ + +void board_led_write(bool state) +{ + nrf_gpio_pin_write(LED_PIN, state ? LED_STATE_ON : (1-LED_STATE_ON)); +} + +uint32_t board_button_read(void) +{ + // button is active LOW + return (nrf_gpio_pin_read(BUTTON_PIN) ? 0 : 1); +} + +int board_uart_read(uint8_t* buf, int len) +{ + (void) buf; (void) len; + return 0; +} + +int board_uart_write(void const * buf, int len) +{ + (void) buf; (void) len; + return 0; +} + +#if CFG_TUSB_OS == OPT_OS_NONE +volatile uint32_t system_ticks = 0; +void SysTick_Handler (void) +{ + system_ticks++; +} + +uint32_t board_millis(void) +{ + return system_ticks; +} +#endif + +#ifdef SOFTDEVICE_PRESENT +// process SOC event from SD +uint32_t proc_soc(void) +{ + uint32_t soc_evt; + uint32_t err = sd_evt_get(&soc_evt); + + if (NRF_SUCCESS == err) + { + /*------------- usb power event handler -------------*/ + int32_t usbevt = (soc_evt == NRF_EVT_POWER_USB_DETECTED ) ? NRFX_POWER_USB_EVT_DETECTED: + (soc_evt == NRF_EVT_POWER_USB_POWER_READY) ? NRFX_POWER_USB_EVT_READY : + (soc_evt == NRF_EVT_POWER_USB_REMOVED ) ? NRFX_POWER_USB_EVT_REMOVED : -1; + + if ( usbevt >= 0) tusb_hal_nrf_power_event(usbevt); + } + + return err; +} + +uint32_t proc_ble(void) +{ + // do nothing with ble + return NRF_ERROR_NOT_FOUND; +} + +void SD_EVT_IRQHandler(void) +{ + // process BLE and SOC until there is no more events + while( (NRF_ERROR_NOT_FOUND != proc_ble()) || (NRF_ERROR_NOT_FOUND != proc_soc()) ) + { + + } +} + +void nrf_error_cb(uint32_t id, uint32_t pc, uint32_t info) +{ + (void) id; + (void) pc; + (void) info; +} +#endif diff --git a/hw/bsp/feather_nrf52840_sense/nrf52840_s140_v6.ld b/hw/bsp/feather_nrf52840_sense/nrf52840_s140_v6.ld new file mode 100644 index 00000000..5314a4e9 --- /dev/null +++ b/hw/bsp/feather_nrf52840_sense/nrf52840_s140_v6.ld @@ -0,0 +1,38 @@ +/* Linker script to configure memory regions. */ + +SEARCH_DIR(.) +GROUP(-lgcc -lc -lnosys) + +MEMORY +{ + FLASH (rx) : ORIGIN = 0x26000, LENGTH = 0xED000 - 0x26000 + + /* SRAM required by S132 depend on + * - Attribute Table Size + * - Vendor UUID count + * - Max ATT MTU + * - Concurrent connection peripheral + central + secure links + * - Event Len, HVN queue, Write CMD queue + */ + RAM (rwx) : ORIGIN = 0x20003400, LENGTH = 0x20040000 - 0x20003400 +} + +SECTIONS +{ + . = ALIGN(4); + .svc_data : + { + PROVIDE(__start_svc_data = .); + KEEP(*(.svc_data)) + PROVIDE(__stop_svc_data = .); + } > RAM + + .fs_data : + { + PROVIDE(__start_fs_data = .); + KEEP(*(.fs_data)) + PROVIDE(__stop_fs_data = .); + } > RAM +} INSERT AFTER .data; + +INCLUDE "nrf52_common.ld" From 3ea95c2ab60bcd0f4efc8790ec091b4645d50015 Mon Sep 17 00:00:00 2001 From: hathach Date: Sat, 7 Mar 2020 17:49:30 +0700 Subject: [PATCH 238/267] clean up LD_FILE using $(BOARD) make it easier to duplicate bsp --- hw/bsp/circuitplayground_bluefruit/board.mk | 2 +- hw/bsp/circuitplayground_express/board.mk | 2 +- hw/bsp/ea4088qs/board.mk | 2 +- hw/bsp/ea4357/board.mk | 2 +- hw/bsp/feather_m0_express/board.mk | 2 +- hw/bsp/feather_m4_express/board.mk | 2 +- hw/bsp/feather_nrf52840_express/board.mk | 2 +- hw/bsp/feather_nrf52840_sense/board.mk | 2 +- hw/bsp/feather_stm32f405/board.mk | 2 +- hw/bsp/fomu/board.mk | 2 +- hw/bsp/lpcxpresso11u37/board.mk | 2 +- hw/bsp/lpcxpresso11u68/board.mk | 2 +- hw/bsp/lpcxpresso1347/board.mk | 2 +- hw/bsp/lpcxpresso1769/board.mk | 2 +- hw/bsp/mbed1768/board.mk | 2 +- hw/bsp/mcb1800/board.mk | 2 +- hw/bsp/metro_m0_express/board.mk | 2 +- hw/bsp/metro_m4_express/board.mk | 2 +- hw/bsp/nutiny_nuc121s/board.mk | 2 +- hw/bsp/nutiny_nuc125s/board.mk | 2 +- hw/bsp/nutiny_nuc126v/board.mk | 2 +- hw/bsp/nutiny_sdk_nuc505/board.mk | 2 +- hw/bsp/pyboardv11/board.mk | 2 +- 23 files changed, 23 insertions(+), 23 deletions(-) diff --git a/hw/bsp/circuitplayground_bluefruit/board.mk b/hw/bsp/circuitplayground_bluefruit/board.mk index bfeaa235..3b2137d7 100644 --- a/hw/bsp/circuitplayground_bluefruit/board.mk +++ b/hw/bsp/circuitplayground_bluefruit/board.mk @@ -19,7 +19,7 @@ CFLAGS += -Wno-error=cast-function-type endif # All source paths should be relative to the top level. -LD_FILE = hw/bsp/circuitplayground_bluefruit/nrf52840_s140_v6.ld +LD_FILE = hw/bsp/$(BOARD)/nrf52840_s140_v6.ld LDFLAGS += -L$(TOP)/hw/mcu/nordic/nrfx/mdk diff --git a/hw/bsp/circuitplayground_express/board.mk b/hw/bsp/circuitplayground_express/board.mk index 7ea90e8e..32b44071 100644 --- a/hw/bsp/circuitplayground_express/board.mk +++ b/hw/bsp/circuitplayground_express/board.mk @@ -8,7 +8,7 @@ CFLAGS += \ -DCFG_TUSB_MCU=OPT_MCU_SAMD21 # All source paths should be relative to the top level. -LD_FILE = hw/bsp/circuitplayground_express/samd21g18a_flash.ld +LD_FILE = hw/bsp/$(BOARD)/samd21g18a_flash.ld SRC_C += \ hw/mcu/microchip/samd/asf4/samd21/gcc/gcc/startup_samd21.c \ diff --git a/hw/bsp/ea4088qs/board.mk b/hw/bsp/ea4088qs/board.mk index a88976d3..950aa484 100644 --- a/hw/bsp/ea4088qs/board.mk +++ b/hw/bsp/ea4088qs/board.mk @@ -15,7 +15,7 @@ CFLAGS += -Wno-error=strict-prototypes -Wno-error=unused-parameter MCU_DIR = hw/mcu/nxp/lpcopen/lpc40xx/lpc_chip_40xx # All source paths should be relative to the top level. -LD_FILE = hw/bsp/ea4088qs/lpc4088.ld +LD_FILE = hw/bsp/$(BOARD)/lpc4088.ld SRC_C += \ $(MCU_DIR)/../gcc/cr_startup_lpc40xx.c \ diff --git a/hw/bsp/ea4357/board.mk b/hw/bsp/ea4357/board.mk index 098fb4c9..ff7b7a15 100644 --- a/hw/bsp/ea4357/board.mk +++ b/hw/bsp/ea4357/board.mk @@ -14,7 +14,7 @@ CFLAGS += -Wno-error=unused-parameter -Wno-error=strict-prototypes MCU_DIR = hw/mcu/nxp/lpcopen/lpc43xx/lpc_chip_43xx # All source paths should be relative to the top level. -LD_FILE = hw/bsp/ea4357/lpc4357.ld +LD_FILE = hw/bsp/$(BOARD)/lpc4357.ld SRC_C += \ $(MCU_DIR)/../gcc/cr_startup_lpc43xx.c \ diff --git a/hw/bsp/feather_m0_express/board.mk b/hw/bsp/feather_m0_express/board.mk index a147cf82..d762c4ec 100644 --- a/hw/bsp/feather_m0_express/board.mk +++ b/hw/bsp/feather_m0_express/board.mk @@ -9,7 +9,7 @@ CFLAGS += \ -DCFG_TUSB_MCU=OPT_MCU_SAMD21 # All source paths should be relative to the top level. -LD_FILE = hw/bsp/feather_m0_express/samd21g18a_flash.ld +LD_FILE = hw/bsp/$(BOARD)/samd21g18a_flash.ld SRC_C += \ hw/mcu/microchip/samd/asf4/samd21/gcc/gcc/startup_samd21.c \ diff --git a/hw/bsp/feather_m4_express/board.mk b/hw/bsp/feather_m4_express/board.mk index f42aa770..49c2d7f2 100644 --- a/hw/bsp/feather_m4_express/board.mk +++ b/hw/bsp/feather_m4_express/board.mk @@ -12,7 +12,7 @@ CFLAGS += \ CFLAGS += -Wno-error=undef # All source paths should be relative to the top level. -LD_FILE = hw/bsp/metro_m4_express/samd51g19a_flash.ld +LD_FILE = hw/bsp/$(BOARD)/samd51g19a_flash.ld SRC_C += \ hw/mcu/microchip/samd/asf4/samd51/gcc/gcc/startup_samd51.c \ diff --git a/hw/bsp/feather_nrf52840_express/board.mk b/hw/bsp/feather_nrf52840_express/board.mk index b4d6fbe9..3b2137d7 100644 --- a/hw/bsp/feather_nrf52840_express/board.mk +++ b/hw/bsp/feather_nrf52840_express/board.mk @@ -19,7 +19,7 @@ CFLAGS += -Wno-error=cast-function-type endif # All source paths should be relative to the top level. -LD_FILE = hw/bsp/feather_nrf52840_express/nrf52840_s140_v6.ld +LD_FILE = hw/bsp/$(BOARD)/nrf52840_s140_v6.ld LDFLAGS += -L$(TOP)/hw/mcu/nordic/nrfx/mdk diff --git a/hw/bsp/feather_nrf52840_sense/board.mk b/hw/bsp/feather_nrf52840_sense/board.mk index b4d6fbe9..3b2137d7 100644 --- a/hw/bsp/feather_nrf52840_sense/board.mk +++ b/hw/bsp/feather_nrf52840_sense/board.mk @@ -19,7 +19,7 @@ CFLAGS += -Wno-error=cast-function-type endif # All source paths should be relative to the top level. -LD_FILE = hw/bsp/feather_nrf52840_express/nrf52840_s140_v6.ld +LD_FILE = hw/bsp/$(BOARD)/nrf52840_s140_v6.ld LDFLAGS += -L$(TOP)/hw/mcu/nordic/nrfx/mdk diff --git a/hw/bsp/feather_stm32f405/board.mk b/hw/bsp/feather_stm32f405/board.mk index 5a007cad..2d1f8bb8 100644 --- a/hw/bsp/feather_stm32f405/board.mk +++ b/hw/bsp/feather_stm32f405/board.mk @@ -13,7 +13,7 @@ ST_HAL_DRIVER = hw/mcu/st/st_driver/STM32F4xx_HAL_Driver ST_CMSIS = hw/mcu/st/st_driver/CMSIS/Device/ST/STM32F4xx # All source paths should be relative to the top level. -LD_FILE = hw/bsp/pyboardv11/STM32F405RGTx_FLASH.ld +LD_FILE = hw/bsp/$(BOARD)/STM32F405RGTx_FLASH.ld SRC_C += \ $(ST_CMSIS)/Source/Templates/system_stm32f4xx.c \ diff --git a/hw/bsp/fomu/board.mk b/hw/bsp/fomu/board.mk index 4e8101b7..8687cf41 100644 --- a/hw/bsp/fomu/board.mk +++ b/hw/bsp/fomu/board.mk @@ -9,7 +9,7 @@ MCU_DIR = hw/mcu/fomu BSP_DIR = hw/bsp/fomu # All source paths should be relative to the top level. -LD_FILE = hw/bsp/fomu/fomu.ld +LD_FILE = hw/bsp/$(BOARD)/fomu.ld # TODO remove later SRC_C += src/portable/$(VENDOR)/$(CHIP_FAMILY)/hal_$(CHIP_FAMILY).c diff --git a/hw/bsp/lpcxpresso11u37/board.mk b/hw/bsp/lpcxpresso11u37/board.mk index d3121ab9..790516c7 100644 --- a/hw/bsp/lpcxpresso11u37/board.mk +++ b/hw/bsp/lpcxpresso11u37/board.mk @@ -17,7 +17,7 @@ CFLAGS += -Wno-error=nested-externs -Wno-error=strict-prototypes -Wno-error=unus MCU_DIR = hw/mcu/nxp/lpcopen/lpc11uxx/lpc_chip_11uxx # All source paths should be relative to the top level. -LD_FILE = hw/bsp/lpcxpresso11u37/lpc11u37.ld +LD_FILE = hw/bsp/$(BOARD)/lpc11u37.ld SRC_C += \ $(MCU_DIR)/../gcc/cr_startup_lpc11xx.c \ diff --git a/hw/bsp/lpcxpresso11u68/board.mk b/hw/bsp/lpcxpresso11u68/board.mk index ba84b7d9..d9017ae1 100644 --- a/hw/bsp/lpcxpresso11u68/board.mk +++ b/hw/bsp/lpcxpresso11u68/board.mk @@ -14,7 +14,7 @@ CFLAGS += \ MCU_DIR = hw/mcu/nxp/lpcopen/lpc11u6x/lpc_chip_11u6x # All source paths should be relative to the top level. -LD_FILE = hw/bsp/lpcxpresso11u68/lpc11u68.ld +LD_FILE = hw/bsp/$(BOARD)/lpc11u68.ld SRC_C += \ $(MCU_DIR)/../gcc/cr_startup_lpc11u6x.c \ diff --git a/hw/bsp/lpcxpresso1347/board.mk b/hw/bsp/lpcxpresso1347/board.mk index 54a83a3b..6a72a798 100644 --- a/hw/bsp/lpcxpresso1347/board.mk +++ b/hw/bsp/lpcxpresso1347/board.mk @@ -17,7 +17,7 @@ CFLAGS += -Wno-error=nested-externs -Wno-error=strict-prototypes MCU_DIR = hw/mcu/nxp/lpcopen/lpc13xx/lpc_chip_13xx # All source paths should be relative to the top level. -LD_FILE = hw/bsp/lpcxpresso1347/lpc1347.ld +LD_FILE = hw/bsp/$(BOARD)/lpc1347.ld SRC_C += \ $(MCU_DIR)/../gcc/cr_startup_lpc13xx.c \ diff --git a/hw/bsp/lpcxpresso1769/board.mk b/hw/bsp/lpcxpresso1769/board.mk index b87d6afc..a345e5a2 100644 --- a/hw/bsp/lpcxpresso1769/board.mk +++ b/hw/bsp/lpcxpresso1769/board.mk @@ -15,7 +15,7 @@ CFLAGS += -Wno-error=strict-prototypes MCU_DIR = hw/mcu/nxp/lpcopen/lpc175x_6x/lpc_chip_175x_6x # All source paths should be relative to the top level. -LD_FILE = hw/bsp/lpcxpresso1769/lpc1769.ld +LD_FILE = hw/bsp/$(BOARD)/lpc1769.ld SRC_C += \ $(MCU_DIR)/../gcc/cr_startup_lpc175x_6x.c \ diff --git a/hw/bsp/mbed1768/board.mk b/hw/bsp/mbed1768/board.mk index 60428bcb..60beb5e3 100644 --- a/hw/bsp/mbed1768/board.mk +++ b/hw/bsp/mbed1768/board.mk @@ -15,7 +15,7 @@ CFLAGS += -Wno-error=nested-externs -Wno-error=strict-prototypes MCU_DIR = hw/mcu/nxp/lpcopen/lpc175x_6x/lpc_chip_175x_6x # All source paths should be relative to the top level. -LD_FILE = hw/bsp/mbed1768/lpc1768.ld +LD_FILE = hw/bsp/$(BOARD)/lpc1768.ld SRC_C += \ $(MCU_DIR)/../gcc/cr_startup_lpc175x_6x.c \ diff --git a/hw/bsp/mcb1800/board.mk b/hw/bsp/mcb1800/board.mk index b05d4d71..7806bff4 100644 --- a/hw/bsp/mcb1800/board.mk +++ b/hw/bsp/mcb1800/board.mk @@ -14,7 +14,7 @@ CFLAGS += -Wno-error=unused-parameter -Wno-error=strict-prototypes MCU_DIR = hw/mcu/nxp/lpcopen/lpc18xx/lpc_chip_18xx # All source paths should be relative to the top level. -LD_FILE = hw/bsp/mcb1800/lpc1857.ld +LD_FILE = hw/bsp/$(BOARD)/lpc1857.ld SRC_C += \ $(MCU_DIR)/../gcc/cr_startup_lpc18xx.c \ diff --git a/hw/bsp/metro_m0_express/board.mk b/hw/bsp/metro_m0_express/board.mk index 4d6dedcf..d762c4ec 100644 --- a/hw/bsp/metro_m0_express/board.mk +++ b/hw/bsp/metro_m0_express/board.mk @@ -9,7 +9,7 @@ CFLAGS += \ -DCFG_TUSB_MCU=OPT_MCU_SAMD21 # All source paths should be relative to the top level. -LD_FILE = hw/bsp/metro_m0_express/samd21g18a_flash.ld +LD_FILE = hw/bsp/$(BOARD)/samd21g18a_flash.ld SRC_C += \ hw/mcu/microchip/samd/asf4/samd21/gcc/gcc/startup_samd21.c \ diff --git a/hw/bsp/metro_m4_express/board.mk b/hw/bsp/metro_m4_express/board.mk index f42aa770..49c2d7f2 100644 --- a/hw/bsp/metro_m4_express/board.mk +++ b/hw/bsp/metro_m4_express/board.mk @@ -12,7 +12,7 @@ CFLAGS += \ CFLAGS += -Wno-error=undef # All source paths should be relative to the top level. -LD_FILE = hw/bsp/metro_m4_express/samd51g19a_flash.ld +LD_FILE = hw/bsp/$(BOARD)/samd51g19a_flash.ld SRC_C += \ hw/mcu/microchip/samd/asf4/samd51/gcc/gcc/startup_samd51.c \ diff --git a/hw/bsp/nutiny_nuc121s/board.mk b/hw/bsp/nutiny_nuc121s/board.mk index 893c8500..e8987782 100644 --- a/hw/bsp/nutiny_nuc121s/board.mk +++ b/hw/bsp/nutiny_nuc121s/board.mk @@ -9,7 +9,7 @@ CFLAGS += \ -DCFG_TUSB_MCU=OPT_MCU_NUC121 # All source paths should be relative to the top level. -LD_FILE = hw/bsp/nutiny_nuc121s/nuc121_flash.ld +LD_FILE = hw/bsp/$(BOARD)/nuc121_flash.ld SRC_C += \ hw/mcu/nuvoton/nuc121_125/Device/Nuvoton/NUC121/Source/system_NUC121.c \ diff --git a/hw/bsp/nutiny_nuc125s/board.mk b/hw/bsp/nutiny_nuc125s/board.mk index e2eecff1..5bba8dee 100644 --- a/hw/bsp/nutiny_nuc125s/board.mk +++ b/hw/bsp/nutiny_nuc125s/board.mk @@ -9,7 +9,7 @@ CFLAGS += \ -DCFG_TUSB_MCU=OPT_MCU_NUC121 # All source paths should be relative to the top level. -LD_FILE = hw/bsp/nutiny_nuc125s/nuc125_flash.ld +LD_FILE = hw/bsp/$(BOARD)/nuc125_flash.ld SRC_C += \ hw/mcu/nuvoton/nuc121_125/Device/Nuvoton/NUC121/Source/system_NUC121.c \ diff --git a/hw/bsp/nutiny_nuc126v/board.mk b/hw/bsp/nutiny_nuc126v/board.mk index cc88b552..21f2c9c5 100644 --- a/hw/bsp/nutiny_nuc126v/board.mk +++ b/hw/bsp/nutiny_nuc126v/board.mk @@ -9,7 +9,7 @@ CFLAGS += \ -DCFG_TUSB_MCU=OPT_MCU_NUC126 # All source paths should be relative to the top level. -LD_FILE = hw/bsp/nutiny_nuc126v/nuc126_flash.ld +LD_FILE = hw/bsp/$(BOARD)/nuc126_flash.ld SRC_C += \ hw/mcu/nuvoton/nuc126/Device/Nuvoton/NUC126/Source/system_NUC126.c \ diff --git a/hw/bsp/nutiny_sdk_nuc505/board.mk b/hw/bsp/nutiny_sdk_nuc505/board.mk index 259d1108..68dea63a 100644 --- a/hw/bsp/nutiny_sdk_nuc505/board.mk +++ b/hw/bsp/nutiny_sdk_nuc505/board.mk @@ -6,7 +6,7 @@ CFLAGS += \ -DCFG_TUSB_MCU=OPT_MCU_NUC505 # All source paths should be relative to the top level. -LD_FILE = hw/bsp/nutiny_sdk_nuc505/nuc505_flashtoram.ld +LD_FILE = hw/bsp/$(BOARD)/nuc505_flashtoram.ld SRC_C += \ hw/mcu/nuvoton/nuc505/Device/Nuvoton/NUC505Series/Source/system_NUC505Series.c \ diff --git a/hw/bsp/pyboardv11/board.mk b/hw/bsp/pyboardv11/board.mk index a0b07f26..9da0541e 100644 --- a/hw/bsp/pyboardv11/board.mk +++ b/hw/bsp/pyboardv11/board.mk @@ -13,7 +13,7 @@ ST_HAL_DRIVER = hw/mcu/st/st_driver/STM32F4xx_HAL_Driver ST_CMSIS = hw/mcu/st/st_driver/CMSIS/Device/ST/STM32F4xx # All source paths should be relative to the top level. -LD_FILE = hw/bsp/pyboardv11/STM32F405RGTx_FLASH.ld +LD_FILE = hw/bsp/$(BOARD)/STM32F405RGTx_FLASH.ld SRC_C += \ $(ST_CMSIS)/Source/Templates/system_stm32f4xx.c \ From bdc5e3d3bccebc78b05bcdadffa90f72b65644bb Mon Sep 17 00:00:00 2001 From: hathach Date: Sat, 7 Mar 2020 18:02:54 +0700 Subject: [PATCH 239/267] added feather sense and CLUE --- docs/boards.md | 5 +- hw/bsp/adafruit_clue/adafruit_clue.c | 192 +++++++++++++++++++++++ hw/bsp/adafruit_clue/board.mk | 63 ++++++++ hw/bsp/adafruit_clue/nrf52840_s140_v6.ld | 38 +++++ 4 files changed, 297 insertions(+), 1 deletion(-) create mode 100644 hw/bsp/adafruit_clue/adafruit_clue.c create mode 100644 hw/bsp/adafruit_clue/board.mk create mode 100755 hw/bsp/adafruit_clue/nrf52840_s140_v6.ld diff --git a/docs/boards.md b/docs/boards.md index cf5defb5..08342e0f 100644 --- a/docs/boards.md +++ b/docs/boards.md @@ -19,8 +19,10 @@ This code base already had supported for a handful of following boards (sorted a ### Nordic nRF5x -- [Adafruit Feather nRF52840 Express](https://www.adafruit.com/product/4062) - [Adafruit Circuit Playground Bluefruit](https://www.adafruit.com/product/4333) +- [Adafruit CLUE](https://www.adafruit.com/product/4500) +- [Adafruit Feather nRF52840 Express](https://www.adafruit.com/product/4062) +- [Adafruit Feather nRF52840 Sense](https://www.adafruit.com/product/4516) - [Maker Diary nRF52840 MDK Dongle](https://wiki.makerdiary.com/nrf52840-mdk-usb-dongle) - [Nordic nRF52840 Development Kit (aka pca10056)](https://www.nordicsemi.com/Software-and-Tools/Development-Kits/nRF52840-DK) - [Nordic nRF52840 Dongle (aka pca10059)](https://www.nordicsemi.com/Software-and-Tools/Development-Kits/nRF52840-Dongle) @@ -32,6 +34,7 @@ This code base already had supported for a handful of following boards (sorted a - [NuTiny NUC121S](https://direct.nuvoton.com/en/nutiny-nuc121s) - [NuTiny NUC125S](https://direct.nuvoton.com/en/nutiny-nuc125s) - [NuTiny NUC126V](https://direct.nuvoton.com/en/nutiny-nuc126v) +- [NuTiny SDK NUC505Y](https://direct.nuvoton.com/en/nutiny-nuc505y) ### NXP iMX RT diff --git a/hw/bsp/adafruit_clue/adafruit_clue.c b/hw/bsp/adafruit_clue/adafruit_clue.c new file mode 100644 index 00000000..67b5ffda --- /dev/null +++ b/hw/bsp/adafruit_clue/adafruit_clue.c @@ -0,0 +1,192 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#include "bsp/board.h" + +#include "nrfx.h" +#include "nrfx/hal/nrf_gpio.h" +#include "nrfx/drivers/include/nrfx_power.h" + +#ifdef SOFTDEVICE_PRESENT +#include "nrf_sdm.h" +#include "nrf_soc.h" +#endif + +/*------------------------------------------------------------------*/ +/* MACRO TYPEDEF CONSTANT ENUM + *------------------------------------------------------------------*/ +#define _PINNUM(port, pin) ((port)*32 + (pin)) + +#define LED_PIN _PINNUM(1, 1) +#define LED_STATE_ON 1 + +#define BUTTON_PIN _PINNUM(1, 02) + +// tinyusb function that handles power event (detected, ready, removed) +// We must call it within SD's SOC event handler, or set it as power event handler if SD is not enabled. +extern void tusb_hal_nrf_power_event(uint32_t event); + +void board_init(void) +{ + // Config clock source: XTAL or RC in sdk_config.h + NRF_CLOCK->LFCLKSRC = (uint32_t)((CLOCK_LFCLKSRC_SRC_Xtal << CLOCK_LFCLKSRC_SRC_Pos) & CLOCK_LFCLKSRC_SRC_Msk); + NRF_CLOCK->TASKS_LFCLKSTART = 1UL; + + // LED + nrf_gpio_cfg_output(LED_PIN); + board_led_write(false); + + // Button + nrf_gpio_cfg_input(BUTTON_PIN, NRF_GPIO_PIN_PULLUP); + +#if CFG_TUSB_OS == OPT_OS_NONE + // 1ms tick timer + SysTick_Config(SystemCoreClock/1000); +#endif + +#if TUSB_OPT_DEVICE_ENABLED + // Priorities 0, 1, 4 (nRF52) are reserved for SoftDevice + // 2 is highest for application + NVIC_SetPriority(USBD_IRQn, 2); + + + // USB power may already be ready at this time -> no event generated + // We need to invoke the handler based on the status initially + uint32_t usb_reg; + +#ifdef SOFTDEVICE_PRESENT + uint8_t sd_en = false; + sd_softdevice_is_enabled(&sd_en); + + if ( sd_en ) { + sd_power_usbdetected_enable(true); + sd_power_usbpwrrdy_enable(true); + sd_power_usbremoved_enable(true); + + sd_power_usbregstatus_get(&usb_reg); + }else +#endif + { + // Power module init + const nrfx_power_config_t pwr_cfg = { 0 }; + nrfx_power_init(&pwr_cfg); + + // Register tusb function as USB power handler + const nrfx_power_usbevt_config_t config = { .handler = (nrfx_power_usb_event_handler_t) tusb_hal_nrf_power_event }; + nrfx_power_usbevt_init(&config); + + nrfx_power_usbevt_enable(); + + usb_reg = NRF_POWER->USBREGSTATUS; + } + + if ( usb_reg & POWER_USBREGSTATUS_VBUSDETECT_Msk ) tusb_hal_nrf_power_event(NRFX_POWER_USB_EVT_DETECTED); + if ( usb_reg & POWER_USBREGSTATUS_OUTPUTRDY_Msk ) tusb_hal_nrf_power_event(NRFX_POWER_USB_EVT_READY); +#endif +} + +//--------------------------------------------------------------------+ +// Board porting API +//--------------------------------------------------------------------+ + +void board_led_write(bool state) +{ + nrf_gpio_pin_write(LED_PIN, state ? LED_STATE_ON : (1-LED_STATE_ON)); +} + +uint32_t board_button_read(void) +{ + // button is active LOW + return (nrf_gpio_pin_read(BUTTON_PIN) ? 0 : 1); +} + +int board_uart_read(uint8_t* buf, int len) +{ + (void) buf; (void) len; + return 0; +} + +int board_uart_write(void const * buf, int len) +{ + (void) buf; (void) len; + return 0; +} + +#if CFG_TUSB_OS == OPT_OS_NONE +volatile uint32_t system_ticks = 0; +void SysTick_Handler (void) +{ + system_ticks++; +} + +uint32_t board_millis(void) +{ + return system_ticks; +} +#endif + +#ifdef SOFTDEVICE_PRESENT +// process SOC event from SD +uint32_t proc_soc(void) +{ + uint32_t soc_evt; + uint32_t err = sd_evt_get(&soc_evt); + + if (NRF_SUCCESS == err) + { + /*------------- usb power event handler -------------*/ + int32_t usbevt = (soc_evt == NRF_EVT_POWER_USB_DETECTED ) ? NRFX_POWER_USB_EVT_DETECTED: + (soc_evt == NRF_EVT_POWER_USB_POWER_READY) ? NRFX_POWER_USB_EVT_READY : + (soc_evt == NRF_EVT_POWER_USB_REMOVED ) ? NRFX_POWER_USB_EVT_REMOVED : -1; + + if ( usbevt >= 0) tusb_hal_nrf_power_event(usbevt); + } + + return err; +} + +uint32_t proc_ble(void) +{ + // do nothing with ble + return NRF_ERROR_NOT_FOUND; +} + +void SD_EVT_IRQHandler(void) +{ + // process BLE and SOC until there is no more events + while( (NRF_ERROR_NOT_FOUND != proc_ble()) || (NRF_ERROR_NOT_FOUND != proc_soc()) ) + { + + } +} + +void nrf_error_cb(uint32_t id, uint32_t pc, uint32_t info) +{ + (void) id; + (void) pc; + (void) info; +} +#endif diff --git a/hw/bsp/adafruit_clue/board.mk b/hw/bsp/adafruit_clue/board.mk new file mode 100644 index 00000000..3b2137d7 --- /dev/null +++ b/hw/bsp/adafruit_clue/board.mk @@ -0,0 +1,63 @@ +CFLAGS += \ + -flto \ + -mthumb \ + -mabi=aapcs \ + -mcpu=cortex-m4 \ + -mfloat-abi=hard \ + -mfpu=fpv4-sp-d16 \ + -DCFG_TUSB_MCU=OPT_MCU_NRF5X \ + -DNRF52840_XXAA \ + -DCONFIG_GPIO_AS_PINRESET + +# nrfx issue undef _ARMCC_VERSION usage https://github.com/NordicSemiconductor/nrfx/issues/49 +CFLAGS += -Wno-error=undef -Wno-error=unused-parameter + +# due to tusb_hal_nrf_power_event +GCCVERSION = $(firstword $(subst ., ,$(shell arm-none-eabi-gcc -dumpversion))) +ifeq ($(shell expr $(GCCVERSION) \>= 8), 1) +CFLAGS += -Wno-error=cast-function-type +endif + +# All source paths should be relative to the top level. +LD_FILE = hw/bsp/$(BOARD)/nrf52840_s140_v6.ld + +LDFLAGS += -L$(TOP)/hw/mcu/nordic/nrfx/mdk + +SRC_C += \ + hw/mcu/nordic/nrfx/drivers/src/nrfx_power.c \ + hw/mcu/nordic/nrfx/mdk/system_nrf52840.c \ + +INC += \ + $(TOP)/hw/mcu/nordic/cmsis/Include \ + $(TOP)/hw/mcu/nordic \ + $(TOP)/hw/mcu/nordic/nrfx \ + $(TOP)/hw/mcu/nordic/nrfx/mdk \ + $(TOP)/hw/mcu/nordic/nrfx/hal \ + $(TOP)/hw/mcu/nordic/nrfx/drivers/include \ + $(TOP)/hw/mcu/nordic/nrfx/drivers/src \ + +SRC_S += hw/mcu/nordic/nrfx/mdk/gcc_startup_nrf52840.S + +ASFLAGS += -D__HEAP_SIZE=0 + +# For TinyUSB port source +VENDOR = nordic +CHIP_FAMILY = nrf5x + +# For freeRTOS port source +FREERTOS_PORT = ARM_CM4F + +# For flash-jlink target +JLINK_DEVICE = nRF52840_xxAA +JLINK_IF = swd + +# For uf2 conversion +UF2_FAMILY = 0xADA52840 + +$(BUILD)/$(BOARD)-firmware.zip: $(BUILD)/$(BOARD)-firmware.hex + adafruit-nrfutil dfu genpkg --dev-type 0x0052 --sd-req 0xFFFE --application $^ $@ + +# flash using adafruit-nrfutil dfu +flash: $(BUILD)/$(BOARD)-firmware.zip + @:$(call check_defined, SERIAL, example: SERIAL=/dev/ttyACM0) + adafruit-nrfutil --verbose dfu serial --package $^ -p $(SERIAL) -b 115200 --singlebank --touch 1200 diff --git a/hw/bsp/adafruit_clue/nrf52840_s140_v6.ld b/hw/bsp/adafruit_clue/nrf52840_s140_v6.ld new file mode 100755 index 00000000..5314a4e9 --- /dev/null +++ b/hw/bsp/adafruit_clue/nrf52840_s140_v6.ld @@ -0,0 +1,38 @@ +/* Linker script to configure memory regions. */ + +SEARCH_DIR(.) +GROUP(-lgcc -lc -lnosys) + +MEMORY +{ + FLASH (rx) : ORIGIN = 0x26000, LENGTH = 0xED000 - 0x26000 + + /* SRAM required by S132 depend on + * - Attribute Table Size + * - Vendor UUID count + * - Max ATT MTU + * - Concurrent connection peripheral + central + secure links + * - Event Len, HVN queue, Write CMD queue + */ + RAM (rwx) : ORIGIN = 0x20003400, LENGTH = 0x20040000 - 0x20003400 +} + +SECTIONS +{ + . = ALIGN(4); + .svc_data : + { + PROVIDE(__start_svc_data = .); + KEEP(*(.svc_data)) + PROVIDE(__stop_svc_data = .); + } > RAM + + .fs_data : + { + PROVIDE(__start_fs_data = .); + KEEP(*(.fs_data)) + PROVIDE(__stop_fs_data = .); + } > RAM +} INSERT AFTER .data; + +INCLUDE "nrf52_common.ld" From 659fc4f29ec8c87a6c0c26400ae2c9cd514a6777 Mon Sep 17 00:00:00 2001 From: hathach Date: Sat, 7 Mar 2020 18:26:39 +0700 Subject: [PATCH 240/267] added itsybitsy m0, m4 --- docs/boards.md | 4 +- hw/bsp/itsybitsy_m0/board.mk | 45 +++++++ hw/bsp/itsybitsy_m0/itsybitsy_m0.c | 142 ++++++++++++++++++++ hw/bsp/itsybitsy_m0/samd21g18a_flash.ld | 144 +++++++++++++++++++++ hw/bsp/itsybitsy_m4/board.mk | 48 +++++++ hw/bsp/itsybitsy_m4/itsybitsy_m4.c | 132 +++++++++++++++++++ hw/bsp/itsybitsy_m4/samd51g19a_flash.ld | 164 ++++++++++++++++++++++++ 7 files changed, 678 insertions(+), 1 deletion(-) create mode 100644 hw/bsp/itsybitsy_m0/board.mk create mode 100644 hw/bsp/itsybitsy_m0/itsybitsy_m0.c create mode 100644 hw/bsp/itsybitsy_m0/samd21g18a_flash.ld create mode 100644 hw/bsp/itsybitsy_m4/board.mk create mode 100644 hw/bsp/itsybitsy_m4/itsybitsy_m4.c create mode 100644 hw/bsp/itsybitsy_m4/samd51g19a_flash.ld diff --git a/docs/boards.md b/docs/boards.md index 08342e0f..d56e39bd 100644 --- a/docs/boards.md +++ b/docs/boards.md @@ -13,8 +13,10 @@ This code base already had supported for a handful of following boards (sorted a - [Adafruit Circuit Playground Express](https://www.adafruit.com/product/3333) - [Adafruit Feather M0 Express](https://www.adafruit.com/product/3403) -- [Adafruit Metro M0 Express](https://www.adafruit.com/product/3505) - [Adafruit Feather M4 Express](https://www.adafruit.com/product/3857) +- [Adafruit ItsyBitsy M0 Express](https://www.adafruit.com/product/3727) +- [Adafruit ItsyBitsy M4 Express](https://www.adafruit.com/product/3800) +- [Adafruit Metro M0 Express](https://www.adafruit.com/product/3505) - [Adafruit Metro M4 Express](https://www.adafruit.com/product/3382) ### Nordic nRF5x diff --git a/hw/bsp/itsybitsy_m0/board.mk b/hw/bsp/itsybitsy_m0/board.mk new file mode 100644 index 00000000..d762c4ec --- /dev/null +++ b/hw/bsp/itsybitsy_m0/board.mk @@ -0,0 +1,45 @@ +CFLAGS += \ + -flto \ + -mthumb \ + -mabi=aapcs-linux \ + -mcpu=cortex-m0plus \ + -nostdlib -nostartfiles \ + -D__SAMD21G18A__ \ + -DCONF_DFLL_OVERWRITE_CALIBRATION=0 \ + -DCFG_TUSB_MCU=OPT_MCU_SAMD21 + +# All source paths should be relative to the top level. +LD_FILE = hw/bsp/$(BOARD)/samd21g18a_flash.ld + +SRC_C += \ + hw/mcu/microchip/samd/asf4/samd21/gcc/gcc/startup_samd21.c \ + hw/mcu/microchip/samd/asf4/samd21/gcc/system_samd21.c \ + hw/mcu/microchip/samd/asf4/samd21/hpl/gclk/hpl_gclk.c \ + hw/mcu/microchip/samd/asf4/samd21/hpl/pm/hpl_pm.c \ + hw/mcu/microchip/samd/asf4/samd21/hpl/sysctrl/hpl_sysctrl.c \ + hw/mcu/microchip/samd/asf4/samd21/hal/src/hal_atomic.c + +INC += \ + $(TOP)/hw/mcu/microchip/samd/asf4/samd21/ \ + $(TOP)/hw/mcu/microchip/samd/asf4/samd21/config \ + $(TOP)/hw/mcu/microchip/samd/asf4/samd21/include \ + $(TOP)/hw/mcu/microchip/samd/asf4/samd21/hal/include \ + $(TOP)/hw/mcu/microchip/samd/asf4/samd21/hal/utils/include \ + $(TOP)/hw/mcu/microchip/samd/asf4/samd21/hpl/pm/ \ + $(TOP)/hw/mcu/microchip/samd/asf4/samd21/hpl/port \ + $(TOP)/hw/mcu/microchip/samd/asf4/samd21/hri \ + $(TOP)/hw/mcu/microchip/samd/asf4/samd21/CMSIS/Include + +# For TinyUSB port source +VENDOR = microchip +CHIP_FAMILY = samd + +# For freeRTOS port source +FREERTOS_PORT = ARM_CM0 + +# For flash-jlink target +JLINK_DEVICE = ATSAMD21G18 +JLINK_IF = swd + +# flash using jlink +flash: flash-jlink diff --git a/hw/bsp/itsybitsy_m0/itsybitsy_m0.c b/hw/bsp/itsybitsy_m0/itsybitsy_m0.c new file mode 100644 index 00000000..39fe3f35 --- /dev/null +++ b/hw/bsp/itsybitsy_m0/itsybitsy_m0.c @@ -0,0 +1,142 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#include "sam.h" +#include "bsp/board.h" + +#include "hal/include/hal_gpio.h" +#include "hal/include/hal_init.h" +#include "hri/hri_nvmctrl_d21.h" + +#include "hpl/gclk/hpl_gclk_base.h" +#include "hpl_pm_config.h" +#include "hpl/pm/hpl_pm_base.h" + +//--------------------------------------------------------------------+ +// MACRO TYPEDEF CONSTANT ENUM DECLARATION +//--------------------------------------------------------------------+ +#define LED_PIN 17 +#define BUTTON_PIN 21 // pin D7 + +/* Referenced GCLKs, should be initialized firstly */ +#define _GCLK_INIT_1ST (1 << 0 | 1 << 1) + +/* Not referenced GCLKs, initialized last */ +#define _GCLK_INIT_LAST (~_GCLK_INIT_1ST) + +void board_init(void) +{ + // Clock init ( follow hpl_init.c ) + hri_nvmctrl_set_CTRLB_RWS_bf(NVMCTRL, 2); + + _pm_init(); + _sysctrl_init_sources(); +#if _GCLK_INIT_1ST + _gclk_init_generators_by_fref(_GCLK_INIT_1ST); +#endif + _sysctrl_init_referenced_generators(); + _gclk_init_generators_by_fref(_GCLK_INIT_LAST); + + // Led init + gpio_set_pin_direction(LED_PIN, GPIO_DIRECTION_OUT); + gpio_set_pin_level(LED_PIN, 0); + + // Button init + gpio_set_pin_direction(BUTTON_PIN, GPIO_DIRECTION_IN); + gpio_set_pin_pull_mode(BUTTON_PIN, GPIO_PULL_UP); + +#if CFG_TUSB_OS == OPT_OS_NONE + // 1ms tick timer (samd SystemCoreClock may not correct) + SysTick_Config(CONF_CPU_FREQUENCY / 1000); +#endif + + /* USB Clock init + * The USB module requires a GCLK_USB of 48 MHz ~ 0.25% clock + * for low speed and full speed operation. */ + _pm_enable_bus_clock(PM_BUS_APBB, USB); + _pm_enable_bus_clock(PM_BUS_AHB, USB); + _gclk_enable_channel(USB_GCLK_ID, GCLK_CLKCTRL_GEN_GCLK0_Val); + + // USB Pin Init + gpio_set_pin_direction(PIN_PA24, GPIO_DIRECTION_OUT); + gpio_set_pin_level(PIN_PA24, false); + gpio_set_pin_pull_mode(PIN_PA24, GPIO_PULL_OFF); + gpio_set_pin_direction(PIN_PA25, GPIO_DIRECTION_OUT); + gpio_set_pin_level(PIN_PA25, false); + gpio_set_pin_pull_mode(PIN_PA25, GPIO_PULL_OFF); + + gpio_set_pin_function(PIN_PA24, PINMUX_PA24G_USB_DM); + gpio_set_pin_function(PIN_PA25, PINMUX_PA25G_USB_DP); + + // Output 500hz PWM on D12 (PA19 - TCC0 WO[3]) so we can validate the GCLK0 clock speed with a Saleae. + _pm_enable_bus_clock(PM_BUS_APBC, TCC0); + TCC0->PER.bit.PER = 48000000 / 1000; + TCC0->CC[3].bit.CC = 48000000 / 2000; + TCC0->CTRLA.bit.ENABLE = true; + + gpio_set_pin_function(PIN_PA19, PINMUX_PA19F_TCC0_WO3); + _gclk_enable_channel(TCC0_GCLK_ID, GCLK_CLKCTRL_GEN_GCLK0_Val); +} + +//--------------------------------------------------------------------+ +// Board porting API +//--------------------------------------------------------------------+ + +void board_led_write(bool state) +{ + gpio_set_pin_level(LED_PIN, state); +} + +uint32_t board_button_read(void) +{ + // button is active low + return gpio_get_pin_level(BUTTON_PIN) ? 0 : 1; +} + +int board_uart_read(uint8_t* buf, int len) +{ + (void) buf; (void) len; + return 0; +} + +int board_uart_write(void const * buf, int len) +{ + (void) buf; (void) len; + return 0; +} + +#if CFG_TUSB_OS == OPT_OS_NONE +volatile uint32_t system_ticks = 0; +void SysTick_Handler (void) +{ + system_ticks++; +} + +uint32_t board_millis(void) +{ + return system_ticks; +} +#endif diff --git a/hw/bsp/itsybitsy_m0/samd21g18a_flash.ld b/hw/bsp/itsybitsy_m0/samd21g18a_flash.ld new file mode 100644 index 00000000..7fc42171 --- /dev/null +++ b/hw/bsp/itsybitsy_m0/samd21g18a_flash.ld @@ -0,0 +1,144 @@ +/** + * \file + * + * \brief Linker script for running in internal FLASH on the SAMD21G18A + * + * Copyright (c) 2017 Microchip Technology Inc. + * + * \asf_license_start + * + * \page License + * + * 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 Licence 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. + * + * \asf_license_stop + * + */ + + +OUTPUT_FORMAT("elf32-littlearm", "elf32-littlearm", "elf32-littlearm") +OUTPUT_ARCH(arm) +SEARCH_DIR(.) + +/* Memory Spaces Definitions */ +MEMORY +{ + rom (rx) : ORIGIN = 0x00000000 + 8K, LENGTH = 0x00040000 - 8K + ram (rwx) : ORIGIN = 0x20000000, LENGTH = 0x00008000 +} + +/* The stack size used by the application. NOTE: you need to adjust according to your application. */ +STACK_SIZE = DEFINED(STACK_SIZE) ? STACK_SIZE : DEFINED(__stack_size__) ? __stack_size__ : 0x2000; + +/* Section Definitions */ +SECTIONS +{ + .text : + { + . = ALIGN(4); + _sfixed = .; + KEEP(*(.vectors .vectors.*)) + *(.text .text.* .gnu.linkonce.t.*) + *(.glue_7t) *(.glue_7) + *(.rodata .rodata* .gnu.linkonce.r.*) + *(.ARM.extab* .gnu.linkonce.armextab.*) + + /* Support C constructors, and C destructors in both user code + and the C library. This also provides support for C++ code. */ + . = 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)) + + . = ALIGN(4); + _efixed = .; /* End of text section */ + } > rom + + /* .ARM.exidx is sorted, so has to go in its own output section. */ + PROVIDE_HIDDEN (__exidx_start = .); + .ARM.exidx : + { + *(.ARM.exidx* .gnu.linkonce.armexidx.*) + } > rom + PROVIDE_HIDDEN (__exidx_end = .); + + . = ALIGN(4); + _etext = .; + + .relocate : AT (_etext) + { + . = ALIGN(4); + _srelocate = .; + *(.ramfunc .ramfunc.*); + *(.data .data.*); + . = ALIGN(4); + _erelocate = .; + } > ram + + /* .bss section which is used for uninitialized data */ + .bss (NOLOAD) : + { + . = ALIGN(4); + _sbss = . ; + _szero = .; + *(.bss .bss.*) + *(COMMON) + . = ALIGN(4); + _ebss = . ; + _ezero = .; + end = .; + } > ram + + /* stack section */ + .stack (NOLOAD): + { + . = ALIGN(8); + _sstack = .; + . = . + STACK_SIZE; + . = ALIGN(8); + _estack = .; + } > ram + + . = ALIGN(4); + _end = . ; +} diff --git a/hw/bsp/itsybitsy_m4/board.mk b/hw/bsp/itsybitsy_m4/board.mk new file mode 100644 index 00000000..49c2d7f2 --- /dev/null +++ b/hw/bsp/itsybitsy_m4/board.mk @@ -0,0 +1,48 @@ +CFLAGS += \ + -flto \ + -mthumb \ + -mabi=aapcs-linux \ + -mcpu=cortex-m4 \ + -mfloat-abi=hard \ + -mfpu=fpv4-sp-d16 \ + -nostdlib -nostartfiles \ + -D__SAMD51J19A__ \ + -DCFG_TUSB_MCU=OPT_MCU_SAMD51 + +CFLAGS += -Wno-error=undef + +# All source paths should be relative to the top level. +LD_FILE = hw/bsp/$(BOARD)/samd51g19a_flash.ld + +SRC_C += \ + hw/mcu/microchip/samd/asf4/samd51/gcc/gcc/startup_samd51.c \ + hw/mcu/microchip/samd/asf4/samd51/gcc/system_samd51.c \ + hw/mcu/microchip/samd/asf4/samd51/hpl/gclk/hpl_gclk.c \ + hw/mcu/microchip/samd/asf4/samd51/hpl/mclk/hpl_mclk.c \ + hw/mcu/microchip/samd/asf4/samd51/hpl/osc32kctrl/hpl_osc32kctrl.c \ + hw/mcu/microchip/samd/asf4/samd51/hpl/oscctrl/hpl_oscctrl.c \ + hw/mcu/microchip/samd/asf4/samd51/hal/src/hal_atomic.c + +INC += \ + $(TOP)/hw/mcu/microchip/samd/asf4/samd51/ \ + $(TOP)/hw/mcu/microchip/samd/asf4/samd51/config \ + $(TOP)/hw/mcu/microchip/samd/asf4/samd51/include \ + $(TOP)/hw/mcu/microchip/samd/asf4/samd51/hal/include \ + $(TOP)/hw/mcu/microchip/samd/asf4/samd51/hal/utils/include \ + $(TOP)/hw/mcu/microchip/samd/asf4/samd51/hpl/port \ + $(TOP)/hw/mcu/microchip/samd/asf4/samd51/hri \ + $(TOP)/hw/mcu/microchip/samd/asf4/samd51/CMSIS/Include + +# For TinyUSB port source +VENDOR = microchip +CHIP_FAMILY = samd + +# For freeRTOS port source +FREERTOS_PORT = ARM_CM4F + +# For flash-jlink target +JLINK_DEVICE = ATSAMD51J19 +JLINK_IF = swd + +# flash using jlink +flash: flash-jlink diff --git a/hw/bsp/itsybitsy_m4/itsybitsy_m4.c b/hw/bsp/itsybitsy_m4/itsybitsy_m4.c new file mode 100644 index 00000000..3afe9313 --- /dev/null +++ b/hw/bsp/itsybitsy_m4/itsybitsy_m4.c @@ -0,0 +1,132 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#include "sam.h" +#include "bsp/board.h" + +#include "hal/include/hal_gpio.h" +#include "hal/include/hal_init.h" +#include "hpl/gclk/hpl_gclk_base.h" +#include "hpl_mclk_config.h" + +//--------------------------------------------------------------------+ +// MACRO TYPEDEF CONSTANT ENUM DECLARATION +//--------------------------------------------------------------------+ +#define LED_PIN 22 +#define BUTTON_PIN 18 // pin D5 + +/* Referenced GCLKs, should be initialized firstly */ +#define _GCLK_INIT_1ST 0xFFFFFFFF + +/* Not referenced GCLKs, initialized last */ +#define _GCLK_INIT_LAST (~_GCLK_INIT_1ST) + +void board_init(void) +{ + // Clock init ( follow hpl_init.c ) + hri_nvmctrl_set_CTRLA_RWS_bf(NVMCTRL, 0); + + _osc32kctrl_init_sources(); + _oscctrl_init_sources(); + _mclk_init(); +#if _GCLK_INIT_1ST + _gclk_init_generators_by_fref(_GCLK_INIT_1ST); +#endif + _oscctrl_init_referenced_generators(); + _gclk_init_generators_by_fref(_GCLK_INIT_LAST); + + // Led init + gpio_set_pin_direction(LED_PIN, GPIO_DIRECTION_OUT); + gpio_set_pin_level(LED_PIN, 0); + + // Button init + gpio_set_pin_direction(BUTTON_PIN, GPIO_DIRECTION_IN); + gpio_set_pin_pull_mode(BUTTON_PIN, GPIO_PULL_UP); + +#if CFG_TUSB_OS == OPT_OS_NONE + // 1ms tick timer (samd SystemCoreClock may not correct) + SysTick_Config(CONF_CPU_FREQUENCY / 1000); +#endif + + /* USB Clock init + * The USB module requires a GCLK_USB of 48 MHz ~ 0.25% clock + * for low speed and full speed operation. */ + hri_gclk_write_PCHCTRL_reg(GCLK, USB_GCLK_ID, GCLK_PCHCTRL_GEN_GCLK1_Val | GCLK_PCHCTRL_CHEN); + hri_mclk_set_AHBMASK_USB_bit(MCLK); + hri_mclk_set_APBBMASK_USB_bit(MCLK); + + // USB Pin Init + gpio_set_pin_direction(PIN_PA24, GPIO_DIRECTION_OUT); + gpio_set_pin_level(PIN_PA24, false); + gpio_set_pin_pull_mode(PIN_PA24, GPIO_PULL_OFF); + gpio_set_pin_direction(PIN_PA25, GPIO_DIRECTION_OUT); + gpio_set_pin_level(PIN_PA25, false); + gpio_set_pin_pull_mode(PIN_PA25, GPIO_PULL_OFF); + + gpio_set_pin_function(PIN_PA24, PINMUX_PA24H_USB_DM); + gpio_set_pin_function(PIN_PA25, PINMUX_PA25H_USB_DP); +} + +//--------------------------------------------------------------------+ +// Board porting API +//--------------------------------------------------------------------+ + +void board_led_write(bool state) +{ + gpio_set_pin_level(LED_PIN, state); +} + +uint32_t board_button_read(void) +{ + // button is active low + return gpio_get_pin_level(BUTTON_PIN) ? 0 : 1; +} + +int board_uart_read(uint8_t* buf, int len) +{ + (void) buf; (void) len; + return 0; +} + +int board_uart_write(void const * buf, int len) +{ + (void) buf; (void) len; + return 0; +} + +#if CFG_TUSB_OS == OPT_OS_NONE +volatile uint32_t system_ticks = 0; + +void SysTick_Handler (void) +{ + system_ticks++; +} + +uint32_t board_millis(void) +{ + return system_ticks; +} +#endif diff --git a/hw/bsp/itsybitsy_m4/samd51g19a_flash.ld b/hw/bsp/itsybitsy_m4/samd51g19a_flash.ld new file mode 100644 index 00000000..cf5db380 --- /dev/null +++ b/hw/bsp/itsybitsy_m4/samd51g19a_flash.ld @@ -0,0 +1,164 @@ +/** + * \file + * + * \brief Linker script for running in internal FLASH on the SAMD51G19A + * + * Copyright (c) 2017 Microchip Technology Inc. + * + * \asf_license_start + * + * \page License + * + * 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 Licence 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. + * + * \asf_license_stop + * + */ + + +OUTPUT_FORMAT("elf32-littlearm", "elf32-littlearm", "elf32-littlearm") +OUTPUT_ARCH(arm) +SEARCH_DIR(.) + +/* Memory Spaces Definitions */ +MEMORY +{ + rom (rx) : ORIGIN = 0x00000000 + 16K, LENGTH = 0x00080000 - 16K + ram (rwx) : ORIGIN = 0x20000000, LENGTH = 0x00030000 + bkupram (rwx) : ORIGIN = 0x47000000, LENGTH = 0x00002000 + qspi (rwx) : ORIGIN = 0x04000000, LENGTH = 0x01000000 +} + +/* The stack size used by the application. NOTE: you need to adjust according to your application. */ +STACK_SIZE = DEFINED(STACK_SIZE) ? STACK_SIZE : DEFINED(__stack_size__) ? __stack_size__ : 0xC000; + +/* Section Definitions */ +SECTIONS +{ + .text : + { + . = ALIGN(4); + _sfixed = .; + KEEP(*(.vectors .vectors.*)) + *(.text .text.* .gnu.linkonce.t.*) + *(.glue_7t) *(.glue_7) + *(.rodata .rodata* .gnu.linkonce.r.*) + *(.ARM.extab* .gnu.linkonce.armextab.*) + + /* Support C constructors, and C destructors in both user code + and the C library. This also provides support for C++ code. */ + . = 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)) + + . = ALIGN(4); + _efixed = .; /* End of text section */ + } > rom + + /* .ARM.exidx is sorted, so has to go in its own output section. */ + PROVIDE_HIDDEN (__exidx_start = .); + .ARM.exidx : + { + *(.ARM.exidx* .gnu.linkonce.armexidx.*) + } > rom + PROVIDE_HIDDEN (__exidx_end = .); + + . = ALIGN(4); + _etext = .; + + .relocate : AT (_etext) + { + . = ALIGN(4); + _srelocate = .; + *(.ramfunc .ramfunc.*); + *(.data .data.*); + . = ALIGN(4); + _erelocate = .; + } > ram + + .bkupram (NOLOAD): + { + . = ALIGN(8); + _sbkupram = .; + *(.bkupram .bkupram.*); + . = ALIGN(8); + _ebkupram = .; + } > bkupram + + .qspi (NOLOAD): + { + . = ALIGN(8); + _sqspi = .; + *(.qspi .qspi.*); + . = ALIGN(8); + _eqspi = .; + } > qspi + + /* .bss section which is used for uninitialized data */ + .bss (NOLOAD) : + { + . = ALIGN(4); + _sbss = . ; + _szero = .; + *(.bss .bss.*) + *(COMMON) + . = ALIGN(4); + _ebss = . ; + _ezero = .; + end = .; + } > ram + + /* stack section */ + .stack (NOLOAD): + { + . = ALIGN(8); + _sstack = .; + . = . + STACK_SIZE; + . = ALIGN(8); + _estack = .; + } > ram + + . = ALIGN(4); + _end = . ; +} From b638aabad855426aaa50b1b8ece1bca972f92acf Mon Sep 17 00:00:00 2001 From: hathach Date: Sun, 8 Mar 2020 13:25:14 +0700 Subject: [PATCH 241/267] add uart for feather nrf52840 --- hw/bsp/feather_nrf52840_express/board.mk | 3 +- .../feather_nrf52840_express.c | 31 +++++++++++++++++-- hw/bsp/pca10056/board.mk | 2 +- 3 files changed, 32 insertions(+), 4 deletions(-) diff --git a/hw/bsp/feather_nrf52840_express/board.mk b/hw/bsp/feather_nrf52840_express/board.mk index 3b2137d7..8b32253d 100644 --- a/hw/bsp/feather_nrf52840_express/board.mk +++ b/hw/bsp/feather_nrf52840_express/board.mk @@ -25,7 +25,8 @@ LDFLAGS += -L$(TOP)/hw/mcu/nordic/nrfx/mdk SRC_C += \ hw/mcu/nordic/nrfx/drivers/src/nrfx_power.c \ - hw/mcu/nordic/nrfx/mdk/system_nrf52840.c \ + hw/mcu/nordic/nrfx/drivers/src/nrfx_uarte.c \ + hw/mcu/nordic/nrfx/mdk/system_nrf52840.c INC += \ $(TOP)/hw/mcu/nordic/cmsis/Include \ diff --git a/hw/bsp/feather_nrf52840_express/feather_nrf52840_express.c b/hw/bsp/feather_nrf52840_express/feather_nrf52840_express.c index 24cc3cf2..d98e451e 100644 --- a/hw/bsp/feather_nrf52840_express/feather_nrf52840_express.c +++ b/hw/bsp/feather_nrf52840_express/feather_nrf52840_express.c @@ -29,6 +29,7 @@ #include "nrfx.h" #include "nrfx/hal/nrf_gpio.h" #include "nrfx/drivers/include/nrfx_power.h" +#include "nrfx/drivers/include/nrfx_uarte.h" #ifdef SOFTDEVICE_PRESENT #include "nrf_sdm.h" @@ -45,12 +46,20 @@ #define BUTTON_PIN _PINNUM(1, 02) +#define UART_RX_PIN 24 +#define UART_TX_PIN 25 + +static nrfx_uarte_t _uart_id = NRFX_UARTE_INSTANCE(0); + // tinyusb function that handles power event (detected, ready, removed) // We must call it within SD's SOC event handler, or set it as power event handler if SD is not enabled. extern void tusb_hal_nrf_power_event(uint32_t event); void board_init(void) { + // stop LF clock just in case we jump from application without reset + NRF_CLOCK->TASKS_LFCLKSTOP = 1UL; + // Config clock source: XTAL or RC in sdk_config.h NRF_CLOCK->LFCLKSRC = (uint32_t)((CLOCK_LFCLKSRC_SRC_Xtal << CLOCK_LFCLKSRC_SRC_Pos) & CLOCK_LFCLKSRC_SRC_Msk); NRF_CLOCK->TASKS_LFCLKSTART = 1UL; @@ -67,6 +76,24 @@ void board_init(void) SysTick_Config(SystemCoreClock/1000); #endif + // UART + nrfx_uarte_config_t uart_cfg = + { + .pseltxd = UART_TX_PIN, + .pselrxd = UART_RX_PIN, + .pselcts = NRF_UARTE_PSEL_DISCONNECTED, + .pselrts = NRF_UARTE_PSEL_DISCONNECTED, + .p_context = NULL, + .baudrate = NRF_UARTE_BAUDRATE_115200, // CFG_BOARD_UART_BAUDRATE + .interrupt_priority = 7, + .hal_cfg = { + .hwfc = NRF_UARTE_HWFC_DISABLED, + .parity = NRF_UARTE_PARITY_EXCLUDED, + } + }; + + nrfx_uarte_init(&_uart_id, &uart_cfg, NULL); //uart_handler); + #if TUSB_OPT_DEVICE_ENABLED // Priorities 0, 1, 4 (nRF52) are reserved for SoftDevice // 2 is highest for application @@ -127,12 +154,12 @@ int board_uart_read(uint8_t* buf, int len) { (void) buf; (void) len; return 0; +// return NRFX_SUCCESS == nrfx_uart_rx(&_uart_id, buf, (size_t) len) ? len : 0; } int board_uart_write(void const * buf, int len) { - (void) buf; (void) len; - return 0; + return (NRFX_SUCCESS == nrfx_uarte_tx(&_uart_id, (uint8_t const*) buf, (size_t) len)) ? len : 0; } #if CFG_TUSB_OS == OPT_OS_NONE diff --git a/hw/bsp/pca10056/board.mk b/hw/bsp/pca10056/board.mk index b4031844..c34b451c 100644 --- a/hw/bsp/pca10056/board.mk +++ b/hw/bsp/pca10056/board.mk @@ -26,7 +26,7 @@ LDFLAGS += -L$(TOP)/hw/mcu/nordic/nrfx/mdk SRC_C += \ hw/mcu/nordic/nrfx/drivers/src/nrfx_power.c \ hw/mcu/nordic/nrfx/drivers/src/nrfx_uarte.c \ - hw/mcu/nordic/nrfx/mdk/system_nrf52840.c \ + hw/mcu/nordic/nrfx/mdk/system_nrf52840.c INC += \ $(TOP)/hw/mcu/nordic/cmsis/Include \ From 7aa5a53652270a06dc60e6293393755350bf7c85 Mon Sep 17 00:00:00 2001 From: hathach Date: Sun, 8 Mar 2020 13:26:36 +0700 Subject: [PATCH 242/267] fix log printf --- src/device/usbd.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/device/usbd.c b/src/device/usbd.c index 32a89889..335c68e8 100644 --- a/src/device/usbd.c +++ b/src/device/usbd.c @@ -264,6 +264,9 @@ static char const* const _usbd_driver_str[USBD_CLASS_DRIVER_COUNT] = #if CFG_TUD_USBTMC "USBTMC" #endif + #if CFG_TUD_NET + "NET" + #endif }; static char const* const _tusb_std_request_str[] = From c8247f0907040eb86c301e8bff8bb322fc9cb566 Mon Sep 17 00:00:00 2001 From: hathach Date: Sun, 8 Mar 2020 14:20:28 +0700 Subject: [PATCH 243/267] fix zlp for nrf52840 --- src/device/usbd_control.c | 6 ++++-- src/portable/nordic/nrf5x/dcd_nrf5x.c | 6 ++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/device/usbd_control.c b/src/device/usbd_control.c index 5a0ba412..f0a4cf84 100644 --- a/src/device/usbd_control.c +++ b/src/device/usbd_control.c @@ -96,6 +96,8 @@ static bool _data_stage_xact(uint8_t rhport) if ( xact_len ) memcpy(_usbd_ctrl_buf, _ctrl_xfer.buffer, xact_len); } + TU_LOG2(" XACT Control: 0x%02X, Bytes: %d\n", ep_addr, xact_len); + return dcd_edpt_xfer(rhport, ep_addr, xact_len ? _usbd_ctrl_buf : NULL, xact_len); } @@ -110,10 +112,10 @@ bool tud_control_xfer(uint8_t rhport, tusb_control_request_t const * request, vo { TU_ASSERT(buffer); + TU_LOG2(" XFER Endpoint: 0x%02X, Bytes: %d\n", request->bmRequestType_bit.direction ? EDPT_CTRL_IN : EDPT_CTRL_OUT, _ctrl_xfer.data_len); + // Data stage TU_ASSERT( _data_stage_xact(rhport) ); - - TU_LOG2(" XFER Endpoint: 0x%02X, Bytes: %d\n", request->bmRequestType_bit.direction ? EDPT_CTRL_IN : EDPT_CTRL_OUT, _ctrl_xfer.data_len); }else { // Status stage diff --git a/src/portable/nordic/nrf5x/dcd_nrf5x.c b/src/portable/nordic/nrf5x/dcd_nrf5x.c index 59c2f36a..2ce288d6 100644 --- a/src/portable/nordic/nrf5x/dcd_nrf5x.c +++ b/src/portable/nordic/nrf5x/dcd_nrf5x.c @@ -276,8 +276,10 @@ bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t xfer->total_len = total_bytes; xfer->actual_len = 0; - // Control endpoint with zero-length packet --> status stage - if ( epnum == 0 && total_bytes == 0 ) + // Control endpoint with zero-length packet and opposite direction to 1st request byte --> status stage + bool const control_status = (epnum == 0 && total_bytes == 0 && dir != tu_edpt_dir(NRF_USBD->BMREQUESTTYPE)); + + if ( control_status ) { // Status Phase also require Easy DMA has to be free as well !!!! edpt_dma_start(&NRF_USBD->TASKS_EP0STATUS); From e0cdab5bf7ab6c2f085a748f936afafbd94ca0d9 Mon Sep 17 00:00:00 2001 From: hathach Date: Sun, 8 Mar 2020 16:28:21 +0700 Subject: [PATCH 244/267] fix stm32 fsdev epdesc --- src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c | 30 +++++++++---------- 1 file changed, 14 insertions(+), 16 deletions(-) diff --git a/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c b/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c index a1f40d97..5eacbe65 100644 --- a/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c +++ b/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c @@ -323,29 +323,27 @@ void dcd_remote_wakeup(uint8_t rhport) remoteWakeCountdown = 4u; // required to be 1 to 15 ms, ESOF should trigger every 1ms. } -// I'm getting a weird warning about missing braces here that I don't -// know how to fix. -#if defined(__GNUC__) && (__GNUC__ >= 7) -# pragma GCC diagnostic push -# pragma GCC diagnostic ignored "-Wmissing-braces" -#endif static const tusb_desc_endpoint_t ep0OUT_desc = { - .wMaxPacketSize = CFG_TUD_ENDPOINT0_SIZE, - .bDescriptorType = TUSB_XFER_CONTROL, - .bEndpointAddress = 0x00 + .bLength = sizeof(tusb_desc_endpoint_t), + .bDescriptorType = TUSB_DESC_ENDPOINT, + + .bEndpointAddress = 0x00, + .bmAttributes = { .xfer = TUSB_XFER_CONTROL }, + .wMaxPacketSize = { .size = CFG_TUD_ENDPOINT0_SIZE }, + .bInterval = 0 }; static const tusb_desc_endpoint_t ep0IN_desc = { - .wMaxPacketSize = CFG_TUD_ENDPOINT0_SIZE, - .bDescriptorType = TUSB_XFER_CONTROL, - .bEndpointAddress = 0x80 -}; + .bLength = sizeof(tusb_desc_endpoint_t), + .bDescriptorType = TUSB_DESC_ENDPOINT, -#if defined(__GNUC__) && (__GNUC__ >= 7) -#pragma GCC diagnostic pop -#endif + .bEndpointAddress = 0x80, + .bmAttributes = { .xfer = TUSB_XFER_CONTROL }, + .wMaxPacketSize = { .size = CFG_TUD_ENDPOINT0_SIZE }, + .bInterval = 0 +}; static void dcd_handle_bus_reset(void) { From 85a3315a998ce7c625796177a665e6f4cd373e73 Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 9 Mar 2020 15:51:29 +0700 Subject: [PATCH 245/267] Adding lwip_webserver to ci - buil_al.py skip specific MCU if .skip.MCU_ exists - reduce stm32f070 heap & stack size to compile webserver --- .../device/lwip_webserver/.skip.MCU_LPC11UXX | 0 .../device/lwip_webserver/.skip.MCU_LPC13XX | 0 .../device/lwip_webserver/.skip.MCU_NUC121 | 0 .../device/lwip_webserver/.skip.MCU_STM32L0 | 0 hw/bsp/samg55xplained/samg55xplained.c | 3 +- hw/bsp/spresense/board.mk | 4 +- .../stm32f070rbnucleo/stm32F070rbtx_flash.ld | 4 +- src/class/net/net_device.h | 2 + tools/build_all.py | 56 +++++++++++++------ tools/build_success.sh | 10 ---- 10 files changed, 48 insertions(+), 31 deletions(-) create mode 100644 examples/device/lwip_webserver/.skip.MCU_LPC11UXX create mode 100644 examples/device/lwip_webserver/.skip.MCU_LPC13XX create mode 100644 examples/device/lwip_webserver/.skip.MCU_NUC121 create mode 100644 examples/device/lwip_webserver/.skip.MCU_STM32L0 delete mode 100644 tools/build_success.sh diff --git a/examples/device/lwip_webserver/.skip.MCU_LPC11UXX b/examples/device/lwip_webserver/.skip.MCU_LPC11UXX new file mode 100644 index 00000000..e69de29b diff --git a/examples/device/lwip_webserver/.skip.MCU_LPC13XX b/examples/device/lwip_webserver/.skip.MCU_LPC13XX new file mode 100644 index 00000000..e69de29b diff --git a/examples/device/lwip_webserver/.skip.MCU_NUC121 b/examples/device/lwip_webserver/.skip.MCU_NUC121 new file mode 100644 index 00000000..e69de29b diff --git a/examples/device/lwip_webserver/.skip.MCU_STM32L0 b/examples/device/lwip_webserver/.skip.MCU_STM32L0 new file mode 100644 index 00000000..e69de29b diff --git a/hw/bsp/samg55xplained/samg55xplained.c b/hw/bsp/samg55xplained/samg55xplained.c index a5e14573..66a3d137 100644 --- a/hw/bsp/samg55xplained/samg55xplained.c +++ b/hw/bsp/samg55xplained/samg55xplained.c @@ -24,13 +24,14 @@ */ #include "sam.h" +#include "bsp/board.h" + #include "peripheral_clk_config.h" #include "hal/include/hal_init.h" #include "hal/include/hpl_usart_sync.h" #include "hpl/pmc/hpl_pmc.h" #include "hal/include/hal_gpio.h" -#include "bsp/board.h" //--------------------------------------------------------------------+ // MACRO TYPEDEF CONSTANT ENUM DECLARATION diff --git a/hw/bsp/spresense/board.mk b/hw/bsp/spresense/board.mk index 2e88cf99..c6b5ce12 100644 --- a/hw/bsp/spresense/board.mk +++ b/hw/bsp/spresense/board.mk @@ -1,5 +1,4 @@ CFLAGS += \ - -DCONFIG_WCHAR_BUILTIN \ -DCONFIG_HAVE_DOUBLE \ -Dmain=spresense_main \ -pipe \ @@ -14,6 +13,9 @@ CFLAGS += \ -fomit-frame-pointer \ -DCFG_TUSB_MCU=OPT_MCU_CXD56 \ +# lwip/src/core/raw.c:334:43: error: declaration of 'recv' shadows a global declaration +CFLAGS += -Wno-error=shadow + SPRESENSE_SDK = $(TOP)/hw/mcu/sony/cxd56/spresense-exported-sdk INC += \ diff --git a/hw/bsp/stm32f070rbnucleo/stm32F070rbtx_flash.ld b/hw/bsp/stm32f070rbnucleo/stm32F070rbtx_flash.ld index 7ae8e596..59e18f37 100644 --- a/hw/bsp/stm32f070rbnucleo/stm32F070rbtx_flash.ld +++ b/hw/bsp/stm32f070rbnucleo/stm32F070rbtx_flash.ld @@ -55,8 +55,8 @@ ENTRY(Reset_Handler) /* Highest address of the user mode stack */ _estack = 0x20004000; /* end of "RAM" Ram type memory */ -_Min_Heap_Size = 0x400; /* required amount of heap */ -_Min_Stack_Size = 0x600; /* required amount of stack */ +_Min_Heap_Size = 0x200; /* required amount of heap */ +_Min_Stack_Size = 0x400; /* required amount of stack */ /* Memories definition */ MEMORY diff --git a/src/class/net/net_device.h b/src/class/net/net_device.h index fee54163..71483364 100644 --- a/src/class/net/net_device.h +++ b/src/class/net/net_device.h @@ -31,6 +31,8 @@ #include "common/tusb_common.h" #include "device/usbd.h" #include "class/cdc/cdc.h" + +// TODO should not include external files #include "lwip/pbuf.h" #include "netif/ethernet.h" diff --git a/tools/build_all.py b/tools/build_all.py index 97294a9a..45ae8d4d 100644 --- a/tools/build_all.py +++ b/tools/build_all.py @@ -1,5 +1,5 @@ import os -import shutil +import glob import sys import subprocess import time @@ -10,9 +10,8 @@ exit_status = 0 total_time = time.monotonic() +# 1st Argument is Example, build all examples if not existed all_examples = [] - -# build all example if input not existed if len(sys.argv) > 1: all_examples.append(sys.argv[1]) else: @@ -22,11 +21,17 @@ else: # TODO update freeRTOS example to work with all boards (only nrf52840 now) all_examples.remove("cdc_msc_hid_freertos") +all_examples.sort() +# 2nd Argument is Board, build all boards if not existed all_boards = [] -for entry in os.scandir("hw/bsp"): - if entry.is_dir(): - all_boards.append(entry.name) +if len(sys.argv) > 2: + all_boards.append(sys.argv[2]) +else: + for entry in os.scandir("hw/bsp"): + if entry.is_dir(): + all_boards.append(entry.name) +all_boards.sort() def build_example(example, board): @@ -35,6 +40,16 @@ def build_example(example, board): return subprocess.run("make -j 4 -C examples/device/{} BOARD={} all".format(example, board), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) +def skip_example(example, board): + ex_dir = 'examples/device/' + example + board_mk = 'hw/bsp/{}/board.mk'.format(board) + for skip_file in glob.iglob(ex_dir + '/.skip.MCU_*'): + mcu_cflag = '-DCFG_TUSB_MCU=OPT_' + os.path.basename(skip_file).split('.')[2] + with open(board_mk) as mk: + if mcu_cflag in mk.read(): + return 1 + + return 0 build_format = '| {:30} | {:30} | {:9} ' build_separator = '-' * 87 @@ -44,20 +59,27 @@ for example in all_examples: print(build_separator) for board in all_boards: start_time = time.monotonic() - build_result = build_example(example, board) - build_duration = time.monotonic() - start_time - if build_result.returncode == 0: - success = "\033[32msucceeded\033[0m" - success_count += 1 + # Check if board is skipped + if skip_example(example, board): + success = "\033[33mskipped\033[0m " + print((build_format + '| {:.2f}s |').format(example, board, success, 0)) else: - exit_status = build_result.returncode - success = "\033[31mfailed\033[0m " - fail_count += 1 + build_result = build_example(example, board) - print((build_format + '| {:.2f}s |').format(example, board, success, build_duration)) - if build_result.returncode != 0: - print(build_result.stdout.decode("utf-8")) + if build_result.returncode == 0: + success = "\033[32msucceeded\033[0m" + success_count += 1 + else: + exit_status = build_result.returncode + success = "\033[31mfailed\033[0m " + fail_count += 1 + + build_duration = time.monotonic() - start_time + print((build_format + '| {:.2f}s |').format(example, board, success, build_duration)) + + if build_result.returncode != 0: + print(build_result.stdout.decode("utf-8")) # FreeRTOS example # example = 'cdc_msc_hid_freertos' diff --git a/tools/build_success.sh b/tools/build_success.sh deleted file mode 100644 index df725bdc..00000000 --- a/tools/build_success.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env bash - -# Trigger mynewt-tinyusb-example repo each push -curl -s -X POST \ - -H "Content-Type: application/json" \ - -H "Accept: application/json" \ - -H "Travis-API-Version: 3" \ - -H "Authorization: token $TRAVIS_TOKEN" \ - -d '{ "request": { "branch":"master" }}' \ - https://api.travis-ci.com/repo/hathach%2Fmynewt-tinyusb-example/requests \ No newline at end of file From 1617b9d22e760647e1539cbf0fbb3a142f3960c2 Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 9 Mar 2020 15:53:20 +0700 Subject: [PATCH 246/267] rename lwip_webserver to net_webserver for example naming convention (with class driver) --- .../device/{lwip_webserver => net_webserver}/.skip.MCU_LPC11UXX | 0 .../device/{lwip_webserver => net_webserver}/.skip.MCU_LPC13XX | 0 .../device/{lwip_webserver => net_webserver}/.skip.MCU_NUC121 | 0 .../device/{lwip_webserver => net_webserver}/.skip.MCU_STM32L0 | 0 examples/device/{lwip_webserver => net_webserver}/Makefile | 0 examples/device/{lwip_webserver => net_webserver}/src/arch/cc.h | 0 examples/device/{lwip_webserver => net_webserver}/src/lwipopts.h | 0 examples/device/{lwip_webserver => net_webserver}/src/main.c | 0 .../device/{lwip_webserver => net_webserver}/src/tusb_config.h | 0 .../{lwip_webserver => net_webserver}/src/usb_descriptors.c | 0 .../{lwip_webserver => net_webserver}/src/usb_descriptors.h | 0 11 files changed, 0 insertions(+), 0 deletions(-) rename examples/device/{lwip_webserver => net_webserver}/.skip.MCU_LPC11UXX (100%) rename examples/device/{lwip_webserver => net_webserver}/.skip.MCU_LPC13XX (100%) rename examples/device/{lwip_webserver => net_webserver}/.skip.MCU_NUC121 (100%) rename examples/device/{lwip_webserver => net_webserver}/.skip.MCU_STM32L0 (100%) rename examples/device/{lwip_webserver => net_webserver}/Makefile (100%) rename examples/device/{lwip_webserver => net_webserver}/src/arch/cc.h (100%) rename examples/device/{lwip_webserver => net_webserver}/src/lwipopts.h (100%) rename examples/device/{lwip_webserver => net_webserver}/src/main.c (100%) rename examples/device/{lwip_webserver => net_webserver}/src/tusb_config.h (100%) rename examples/device/{lwip_webserver => net_webserver}/src/usb_descriptors.c (100%) rename examples/device/{lwip_webserver => net_webserver}/src/usb_descriptors.h (100%) diff --git a/examples/device/lwip_webserver/.skip.MCU_LPC11UXX b/examples/device/net_webserver/.skip.MCU_LPC11UXX similarity index 100% rename from examples/device/lwip_webserver/.skip.MCU_LPC11UXX rename to examples/device/net_webserver/.skip.MCU_LPC11UXX diff --git a/examples/device/lwip_webserver/.skip.MCU_LPC13XX b/examples/device/net_webserver/.skip.MCU_LPC13XX similarity index 100% rename from examples/device/lwip_webserver/.skip.MCU_LPC13XX rename to examples/device/net_webserver/.skip.MCU_LPC13XX diff --git a/examples/device/lwip_webserver/.skip.MCU_NUC121 b/examples/device/net_webserver/.skip.MCU_NUC121 similarity index 100% rename from examples/device/lwip_webserver/.skip.MCU_NUC121 rename to examples/device/net_webserver/.skip.MCU_NUC121 diff --git a/examples/device/lwip_webserver/.skip.MCU_STM32L0 b/examples/device/net_webserver/.skip.MCU_STM32L0 similarity index 100% rename from examples/device/lwip_webserver/.skip.MCU_STM32L0 rename to examples/device/net_webserver/.skip.MCU_STM32L0 diff --git a/examples/device/lwip_webserver/Makefile b/examples/device/net_webserver/Makefile similarity index 100% rename from examples/device/lwip_webserver/Makefile rename to examples/device/net_webserver/Makefile diff --git a/examples/device/lwip_webserver/src/arch/cc.h b/examples/device/net_webserver/src/arch/cc.h similarity index 100% rename from examples/device/lwip_webserver/src/arch/cc.h rename to examples/device/net_webserver/src/arch/cc.h diff --git a/examples/device/lwip_webserver/src/lwipopts.h b/examples/device/net_webserver/src/lwipopts.h similarity index 100% rename from examples/device/lwip_webserver/src/lwipopts.h rename to examples/device/net_webserver/src/lwipopts.h diff --git a/examples/device/lwip_webserver/src/main.c b/examples/device/net_webserver/src/main.c similarity index 100% rename from examples/device/lwip_webserver/src/main.c rename to examples/device/net_webserver/src/main.c diff --git a/examples/device/lwip_webserver/src/tusb_config.h b/examples/device/net_webserver/src/tusb_config.h similarity index 100% rename from examples/device/lwip_webserver/src/tusb_config.h rename to examples/device/net_webserver/src/tusb_config.h diff --git a/examples/device/lwip_webserver/src/usb_descriptors.c b/examples/device/net_webserver/src/usb_descriptors.c similarity index 100% rename from examples/device/lwip_webserver/src/usb_descriptors.c rename to examples/device/net_webserver/src/usb_descriptors.c diff --git a/examples/device/lwip_webserver/src/usb_descriptors.h b/examples/device/net_webserver/src/usb_descriptors.h similarity index 100% rename from examples/device/lwip_webserver/src/usb_descriptors.h rename to examples/device/net_webserver/src/usb_descriptors.h From 6e6b929f8e3ccc2d53e11be5283cb294dbcc6877 Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 9 Mar 2020 15:54:16 +0700 Subject: [PATCH 247/267] add net_webserver into ci build --- .github/workflows/build.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 72922251..d1e3b899 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -24,8 +24,8 @@ jobs: strategy: fail-fast: false matrix: - example: ['board_test', 'cdc_dual_ports', 'cdc_msc', 'dfu_rt', 'hid_composite', - 'hid_generic_inout', 'midi_test', 'msc_dual_lun', 'usbtmc', 'webusb_serial'] + example: ['board_test', 'cdc_dual_ports', 'cdc_msc', 'dfu_rt', 'hid_composite', 'hid_generic_inout', + 'midi_test', 'msc_dual_lun', 'net_webserver', 'usbtmc', 'webusb_serial'] steps: - name: Setup Python uses: actions/setup-python@v1 From 6f5466f017eb03aca64e397093af65b1bf80a8dd Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 9 Mar 2020 17:42:57 +0700 Subject: [PATCH 248/267] add Flash & Ram to ci build result --- tools/build_all.py | 27 +++++++++++++++++++++------ 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/tools/build_all.py b/tools/build_all.py index 45ae8d4d..039b7702 100644 --- a/tools/build_all.py +++ b/tools/build_all.py @@ -6,6 +6,7 @@ import time success_count = 0 fail_count = 0 +skip_count = 0 exit_status = 0 total_time = time.monotonic() @@ -40,6 +41,14 @@ def build_example(example, board): return subprocess.run("make -j 4 -C examples/device/{} BOARD={} all".format(example, board), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) +def build_size(example, board): + elf_file = 'examples/device/{}/_build/build-{}/{}-firmware.elf'.format(example, board, board) + size_output = subprocess.run('size {}'.format(elf_file), shell=True, stdout=subprocess.PIPE).stdout.decode("utf-8") + size_list = size_output.split('\n')[1].split('\t') + flash_size = int(size_list[0]) + sram_size = int(size_list[1]) + int(size_list[2]) + return (flash_size, sram_size) + def skip_example(example, board): ex_dir = 'examples/device/' + example board_mk = 'hw/bsp/{}/board.mk'.format(board) @@ -51,32 +60,38 @@ def skip_example(example, board): return 0 -build_format = '| {:30} | {:30} | {:9} ' -build_separator = '-' * 87 +build_format = '| {:20} | {:30} | {:9} | {:5} | {:6} | {:6} |' +build_separator = '-' * 95 print(build_separator) -print((build_format + '| {:5} |').format('Example', 'Board', 'Result', 'Time')) +print(build_format.format('Example', 'Board', 'Result', 'Time', 'Flash', 'SRAM')) + for example in all_examples: print(build_separator) for board in all_boards: start_time = time.monotonic() + flash_size = "-" + sram_size = "-" + # Check if board is skipped if skip_example(example, board): success = "\033[33mskipped\033[0m " - print((build_format + '| {:.2f}s |').format(example, board, success, 0)) + skip_count += 1 + print((build_format + '| {:.2f}s |').format(example, board, success, 0, flash_size, sram_size)) else: build_result = build_example(example, board) if build_result.returncode == 0: success = "\033[32msucceeded\033[0m" success_count += 1 + (flash_size, sram_size) = build_size(example, board) else: exit_status = build_result.returncode success = "\033[31mfailed\033[0m " fail_count += 1 build_duration = time.monotonic() - start_time - print((build_format + '| {:.2f}s |').format(example, board, success, build_duration)) + print(build_format.format(example, board, success, "{:.2f}".format(build_duration), flash_size, sram_size)) if build_result.returncode != 0: print(build_result.stdout.decode("utf-8")) @@ -88,7 +103,7 @@ for example in all_examples: total_time = time.monotonic() - total_time print(build_separator) -print("Build Sumamary: {} \033[32msucceeded\033[0m, {} \033[31mfailed\033[0m and took {:.2f}s".format(success_count, fail_count, total_time)) +print("Build Sumamary: {} \033[32msucceeded\033[0m, {} \033[31mfailed\033[0m, {} \033[33mskipped\033[0m and took {:.2f}s".format(success_count, fail_count, skip_count, total_time)) print(build_separator) sys.exit(exit_status) From ec4323277d78c4a4fc4f1f2f58147eb108d5a0f1 Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 9 Mar 2020 17:55:31 +0700 Subject: [PATCH 249/267] fix ci --- tools/build_all.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/build_all.py b/tools/build_all.py index 039b7702..4f3e2874 100644 --- a/tools/build_all.py +++ b/tools/build_all.py @@ -77,7 +77,7 @@ for example in all_examples: if skip_example(example, board): success = "\033[33mskipped\033[0m " skip_count += 1 - print((build_format + '| {:.2f}s |').format(example, board, success, 0, flash_size, sram_size)) + print(build_format.format(example, board, success, '-', flash_size, sram_size)) else: build_result = build_example(example, board) From 8a8f84cd3708781a4b2031a76b1f12dbde5d006c Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 9 Mar 2020 23:05:22 +0700 Subject: [PATCH 250/267] more rename --- .github/workflows/build.yml | 2 +- .../{net_webserver => net_lwip_webserver}/.skip.MCU_LPC11UXX | 0 .../{net_webserver => net_lwip_webserver}/.skip.MCU_LPC13XX | 0 .../{net_webserver => net_lwip_webserver}/.skip.MCU_NUC121 | 0 .../{net_webserver => net_lwip_webserver}/.skip.MCU_STM32L0 | 0 examples/device/{net_webserver => net_lwip_webserver}/Makefile | 0 .../device/{net_webserver => net_lwip_webserver}/src/arch/cc.h | 0 .../device/{net_webserver => net_lwip_webserver}/src/lwipopts.h | 0 .../device/{net_webserver => net_lwip_webserver}/src/main.c | 0 .../{net_webserver => net_lwip_webserver}/src/tusb_config.h | 0 .../{net_webserver => net_lwip_webserver}/src/usb_descriptors.c | 0 .../{net_webserver => net_lwip_webserver}/src/usb_descriptors.h | 0 12 files changed, 1 insertion(+), 1 deletion(-) rename examples/device/{net_webserver => net_lwip_webserver}/.skip.MCU_LPC11UXX (100%) rename examples/device/{net_webserver => net_lwip_webserver}/.skip.MCU_LPC13XX (100%) rename examples/device/{net_webserver => net_lwip_webserver}/.skip.MCU_NUC121 (100%) rename examples/device/{net_webserver => net_lwip_webserver}/.skip.MCU_STM32L0 (100%) rename examples/device/{net_webserver => net_lwip_webserver}/Makefile (100%) rename examples/device/{net_webserver => net_lwip_webserver}/src/arch/cc.h (100%) rename examples/device/{net_webserver => net_lwip_webserver}/src/lwipopts.h (100%) rename examples/device/{net_webserver => net_lwip_webserver}/src/main.c (100%) rename examples/device/{net_webserver => net_lwip_webserver}/src/tusb_config.h (100%) rename examples/device/{net_webserver => net_lwip_webserver}/src/usb_descriptors.c (100%) rename examples/device/{net_webserver => net_lwip_webserver}/src/usb_descriptors.h (100%) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index d1e3b899..54d4baba 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -25,7 +25,7 @@ jobs: fail-fast: false matrix: example: ['board_test', 'cdc_dual_ports', 'cdc_msc', 'dfu_rt', 'hid_composite', 'hid_generic_inout', - 'midi_test', 'msc_dual_lun', 'net_webserver', 'usbtmc', 'webusb_serial'] + 'midi_test', 'msc_dual_lun', 'net_lwip_webserver', 'usbtmc', 'webusb_serial'] steps: - name: Setup Python uses: actions/setup-python@v1 diff --git a/examples/device/net_webserver/.skip.MCU_LPC11UXX b/examples/device/net_lwip_webserver/.skip.MCU_LPC11UXX similarity index 100% rename from examples/device/net_webserver/.skip.MCU_LPC11UXX rename to examples/device/net_lwip_webserver/.skip.MCU_LPC11UXX diff --git a/examples/device/net_webserver/.skip.MCU_LPC13XX b/examples/device/net_lwip_webserver/.skip.MCU_LPC13XX similarity index 100% rename from examples/device/net_webserver/.skip.MCU_LPC13XX rename to examples/device/net_lwip_webserver/.skip.MCU_LPC13XX diff --git a/examples/device/net_webserver/.skip.MCU_NUC121 b/examples/device/net_lwip_webserver/.skip.MCU_NUC121 similarity index 100% rename from examples/device/net_webserver/.skip.MCU_NUC121 rename to examples/device/net_lwip_webserver/.skip.MCU_NUC121 diff --git a/examples/device/net_webserver/.skip.MCU_STM32L0 b/examples/device/net_lwip_webserver/.skip.MCU_STM32L0 similarity index 100% rename from examples/device/net_webserver/.skip.MCU_STM32L0 rename to examples/device/net_lwip_webserver/.skip.MCU_STM32L0 diff --git a/examples/device/net_webserver/Makefile b/examples/device/net_lwip_webserver/Makefile similarity index 100% rename from examples/device/net_webserver/Makefile rename to examples/device/net_lwip_webserver/Makefile diff --git a/examples/device/net_webserver/src/arch/cc.h b/examples/device/net_lwip_webserver/src/arch/cc.h similarity index 100% rename from examples/device/net_webserver/src/arch/cc.h rename to examples/device/net_lwip_webserver/src/arch/cc.h diff --git a/examples/device/net_webserver/src/lwipopts.h b/examples/device/net_lwip_webserver/src/lwipopts.h similarity index 100% rename from examples/device/net_webserver/src/lwipopts.h rename to examples/device/net_lwip_webserver/src/lwipopts.h diff --git a/examples/device/net_webserver/src/main.c b/examples/device/net_lwip_webserver/src/main.c similarity index 100% rename from examples/device/net_webserver/src/main.c rename to examples/device/net_lwip_webserver/src/main.c diff --git a/examples/device/net_webserver/src/tusb_config.h b/examples/device/net_lwip_webserver/src/tusb_config.h similarity index 100% rename from examples/device/net_webserver/src/tusb_config.h rename to examples/device/net_lwip_webserver/src/tusb_config.h diff --git a/examples/device/net_webserver/src/usb_descriptors.c b/examples/device/net_lwip_webserver/src/usb_descriptors.c similarity index 100% rename from examples/device/net_webserver/src/usb_descriptors.c rename to examples/device/net_lwip_webserver/src/usb_descriptors.c diff --git a/examples/device/net_webserver/src/usb_descriptors.h b/examples/device/net_lwip_webserver/src/usb_descriptors.h similarity index 100% rename from examples/device/net_webserver/src/usb_descriptors.h rename to examples/device/net_lwip_webserver/src/usb_descriptors.h From 9a0c02236e1647bbbeaf3284ab9ba4da0caf56f1 Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 10 Mar 2020 13:28:55 +0700 Subject: [PATCH 251/267] doc update --- CONTRIBUTORS.md | 8 +++++--- README.md | 3 ++- docs/boards.md | 1 + 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index e1d5db69..6c83ef9c 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -25,9 +25,11 @@ * Board support for STM32F070RB Nucleo, STM32F303 Discovery * **[Peter Lawrence](https://github.com/majbthrd)** - * Nuvoton NUC 121, 125, 126 device driver port - * Board support for NuTiny NUC121s, NUC125s, NUC126V - * Complete multiple class interfaces & add cdc_dual_ports example + * Nuvoton NUC 120, 121, 125, 126, 505 device driver port + * USBNET RNDIS, CDC-ECM, CDC-EEM class driver + * Added `net_lwip_webserver` example for demonstration of usbnet with lwip + * Board support for NuTiny NUC120, NUC121s, NUC125s, NUC126V, NUC505 + * Complete multiple class interfaces & add cdc_dual_ports example * **[Scott Shawcroft](https://github.com/tannewt)** * SAMD21 and SAMD51 device driver port diff --git a/README.md b/README.md index 7ab55f78..211dcc50 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,7 @@ The stack supports the following MCUs: - **Sony:** CXD56 - **ST:** STM32 series: L0, F0, F1, F2, F3, F4, F7, H7 (device only) - **[ValentyUSB](https://github.com/im-tomu/valentyusb)** eptri -- **Nuvoton:** NUC121/NUC125, NUC126, NUC505 +- **Nuvoton:** NUC120, NUC121/NUC125, NUC126, NUC505 [Here is the list of supported Boards](docs/boards.md) that can be used with provided examples. @@ -50,6 +50,7 @@ Supports multiple device configurations by dynamically changing usb descriptors. - Human Interface Device (HID): Generic (In & Out), Keyboard, Mouse, Gamepad etc ... - Mass Storage Class (MSC): with multiple LUNs - Musical Instrument Digital Interface (MIDI) +- Network with RNDIS, CDC-ECM, CDC-EEM (work in progress) - Vendor-specific class support with generic In & Out endpoints. Can be used with MS OS 2.0 compatible descriptor to load winUSB driver without INF file. - [WebUSB](https://github.com/WICG/webusb) with vendor-specific class diff --git a/docs/boards.md b/docs/boards.md index d56e39bd..9667f694 100644 --- a/docs/boards.md +++ b/docs/boards.md @@ -33,6 +33,7 @@ This code base already had supported for a handful of following boards (sorted a ### Nuvoton +- NuTiny SDK NUC120 - [NuTiny NUC121S](https://direct.nuvoton.com/en/nutiny-nuc121s) - [NuTiny NUC125S](https://direct.nuvoton.com/en/nutiny-nuc125s) - [NuTiny NUC126V](https://direct.nuvoton.com/en/nutiny-nuc126v) From 61d256c2e13b4cc065a9da162784adbdea3075c7 Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 10 Mar 2020 14:42:24 +0700 Subject: [PATCH 252/267] drop hid for freertos demo to match none os example --- examples/device/cdc_msc/src/tusb_config.h | 1 + .../device/cdc_msc_hid_freertos/src/main.c | 100 +----------------- .../cdc_msc_hid_freertos/src/msc_disk.c | 12 --- .../cdc_msc_hid_freertos/src/tusb_config.h | 2 +- .../src/usb_descriptors.c | 87 +++++---------- 5 files changed, 33 insertions(+), 169 deletions(-) diff --git a/examples/device/cdc_msc/src/tusb_config.h b/examples/device/cdc_msc/src/tusb_config.h index d881cb63..733fd2d0 100644 --- a/examples/device/cdc_msc/src/tusb_config.h +++ b/examples/device/cdc_msc/src/tusb_config.h @@ -68,6 +68,7 @@ //-------------------------------------------------------------------- // DEVICE CONFIGURATION //-------------------------------------------------------------------- + #ifndef CFG_TUD_ENDPOINT0_SIZE #define CFG_TUD_ENDPOINT0_SIZE 64 #endif diff --git a/examples/device/cdc_msc_hid_freertos/src/main.c b/examples/device/cdc_msc_hid_freertos/src/main.c index cb707675..b3205fc4 100644 --- a/examples/device/cdc_msc_hid_freertos/src/main.c +++ b/examples/device/cdc_msc_hid_freertos/src/main.c @@ -36,8 +36,6 @@ #include "bsp/board.h" #include "tusb.h" -#include "usb_descriptors.h" - //--------------------------------------------------------------------+ // MACRO CONSTANT TYPEDEF PROTYPES //--------------------------------------------------------------------+ @@ -58,7 +56,6 @@ TimerHandle_t blink_tm; void led_blinky_cb(TimerHandle_t xTimer); void usb_device_task(void* param); void cdc_task(void* params); -void hid_task(void* params); /*------------- MAIN -------------*/ int main(void) @@ -79,10 +76,6 @@ int main(void) xTaskCreate( cdc_task, "cdc", 128, NULL, configMAX_PRIORITIES-2, NULL); #endif -#if CFG_TUD_HID - xTaskCreate( hid_task, "hid", 128, NULL, configMAX_PRIORITIES-2, NULL); -#endif - vTaskStartScheduler(); NVIC_SystemReset(); @@ -134,6 +127,7 @@ void tud_resume_cb(void) xTimerChangePeriod(blink_tm, pdMS_TO_TICKS(BLINK_MOUNTED), 0); } + //--------------------------------------------------------------------+ // USB CDC //--------------------------------------------------------------------+ @@ -189,97 +183,7 @@ void tud_cdc_rx_cb(uint8_t itf) (void) itf; } -#endif - -//--------------------------------------------------------------------+ -// USB HID -//--------------------------------------------------------------------+ -#if CFG_TUD_HID - -void hid_task(void* params) -{ - (void) params; - - while (1) - { - // Poll every 10ms - vTaskDelay(pdMS_TO_TICKS(10)); - - uint32_t const btn = board_button_read(); - - // Remote wakeup - if ( tud_suspended() && btn ) - { - // Wake up host if we are in suspend mode - // and REMOTE_WAKEUP feature is enabled by host - tud_remote_wakeup(); - } - - /*------------- Mouse -------------*/ - if ( tud_hid_ready() ) - { - if ( btn ) - { - int8_t const delta = 5; - - // no button, right + down, no scroll pan - tud_hid_mouse_report(REPORT_ID_MOUSE, 0x00, delta, delta, 0, 0); - - // delay a bit before attempt to send keyboard report - vTaskDelay(pdMS_TO_TICKS(2)); - } - } - - /*------------- Keyboard -------------*/ - if ( tud_hid_ready() ) - { - // use to avoid send multiple consecutive zero report for keyboard - static bool has_key = false; - - if ( btn ) - { - uint8_t keycode[6] = { 0 }; - keycode[0] = HID_KEY_A; - - tud_hid_keyboard_report(REPORT_ID_KEYBOARD, 0, keycode); - - has_key = true; - }else - { - // send empty key report if previously has key pressed - if (has_key) tud_hid_keyboard_report(REPORT_ID_KEYBOARD, 0, NULL); - has_key = false; - } - } - } -} - -// Invoked when received GET_REPORT control request -// Application must fill buffer report's content and return its length. -// Return zero will cause the stack to STALL request -uint16_t tud_hid_get_report_cb(uint8_t report_id, hid_report_type_t report_type, uint8_t* buffer, uint16_t reqlen) -{ - // TODO not Implemented - (void) report_id; - (void) report_type; - (void) buffer; - (void) reqlen; - - return 0; -} - -// Invoked when received SET_REPORT control request or -// received data on OUT endpoint ( Report ID = 0, Type = 0 ) -void tud_hid_set_report_cb(uint8_t report_id, hid_report_type_t report_type, uint8_t const* buffer, uint16_t bufsize) -{ - // TODO not Implemented - (void) report_id; - (void) report_type; - (void) buffer; - (void) bufsize; -} - -#endif +#endif // CFG_TUD_CDC //--------------------------------------------------------------------+ // BLINKING TASK diff --git a/examples/device/cdc_msc_hid_freertos/src/msc_disk.c b/examples/device/cdc_msc_hid_freertos/src/msc_disk.c index b4986fbb..5aa7befc 100644 --- a/examples/device/cdc_msc_hid_freertos/src/msc_disk.c +++ b/examples/device/cdc_msc_hid_freertos/src/msc_disk.c @@ -220,18 +220,6 @@ int32_t tud_msc_scsi_cb (uint8_t lun, uint8_t const scsi_cmd[16], void* buffer, resplen = 0; break; - case SCSI_CMD_START_STOP_UNIT: - // Host try to eject/safe remove/poweroff us. We could safely disconnect with disk storage, or go into lower power - /* scsi_start_stop_unit_t const * start_stop = (scsi_start_stop_unit_t const *) scsi_cmd; - // Start bit = 0 : low power mode, if load_eject = 1 : unmount disk storage as well - // Start bit = 1 : Ready mode, if load_eject = 1 : mount disk storage - start_stop->start; - start_stop->load_eject; - */ - resplen = 0; - break; - - default: // Set Sense = Invalid Command Operation tud_msc_set_sense(lun, SCSI_SENSE_ILLEGAL_REQUEST, 0x20, 0x00); diff --git a/examples/device/cdc_msc_hid_freertos/src/tusb_config.h b/examples/device/cdc_msc_hid_freertos/src/tusb_config.h index 39738333..525019aa 100644 --- a/examples/device/cdc_msc_hid_freertos/src/tusb_config.h +++ b/examples/device/cdc_msc_hid_freertos/src/tusb_config.h @@ -76,7 +76,7 @@ //------------- CLASS -------------// #define CFG_TUD_CDC 1 #define CFG_TUD_MSC 1 -#define CFG_TUD_HID 1 +#define CFG_TUD_HID 0 #define CFG_TUD_MIDI 0 #define CFG_TUD_VENDOR 0 diff --git a/examples/device/cdc_msc_hid_freertos/src/usb_descriptors.c b/examples/device/cdc_msc_hid_freertos/src/usb_descriptors.c index 84939e2d..12700822 100644 --- a/examples/device/cdc_msc_hid_freertos/src/usb_descriptors.c +++ b/examples/device/cdc_msc_hid_freertos/src/usb_descriptors.c @@ -24,7 +24,6 @@ */ #include "tusb.h" -#include "usb_descriptors.h" /* A combination of interfaces must have a unique product id, since PC will save device driver after the first plug. * Same VID/PID with different interface e.g MSC (first), then CDC (later) will possibly cause system error on PC. @@ -45,17 +44,11 @@ tusb_desc_device_t const desc_device = .bDescriptorType = TUSB_DESC_DEVICE, .bcdUSB = 0x0200, - #if CFG_TUD_CDC // Use Interface Association Descriptor (IAD) for CDC // As required by USB Specs IAD's subclass must be common class (2) and protocol must be IAD (1) .bDeviceClass = TUSB_CLASS_MISC, .bDeviceSubClass = MISC_SUBCLASS_COMMON, .bDeviceProtocol = MISC_PROTOCOL_IAD, - #else - .bDeviceClass = 0x00, - .bDeviceSubClass = 0x00, - .bDeviceProtocol = 0x00, - #endif .bMaxPacketSize0 = CFG_TUD_ENDPOINT0_SIZE, @@ -77,84 +70,63 @@ uint8_t const * tud_descriptor_device_cb(void) return (uint8_t const *) &desc_device; } -//--------------------------------------------------------------------+ -// HID Report Descriptor -//--------------------------------------------------------------------+ -#if CFG_TUD_HID - -uint8_t const desc_hid_report[] = -{ - TUD_HID_REPORT_DESC_KEYBOARD( HID_REPORT_ID(REPORT_ID_KEYBOARD), ), - TUD_HID_REPORT_DESC_MOUSE ( HID_REPORT_ID(REPORT_ID_MOUSE), ) -}; - -// Invoked when received GET HID REPORT DESCRIPTOR -// Application return pointer to descriptor -// Descriptor contents must exist long enough for transfer to complete -uint8_t const * tud_hid_descriptor_report_cb(void) -{ - return desc_hid_report; -} - -#endif - //--------------------------------------------------------------------+ // Configuration Descriptor //--------------------------------------------------------------------+ enum { -#if CFG_TUD_CDC ITF_NUM_CDC = 0, ITF_NUM_CDC_DATA, -#endif - -#if CFG_TUD_MSC ITF_NUM_MSC, -#endif - -#if CFG_TUD_HID - ITF_NUM_HID, -#endif - ITF_NUM_TOTAL }; -#define CONFIG_TOTAL_LEN (TUD_CONFIG_DESC_LEN + CFG_TUD_CDC*TUD_CDC_DESC_LEN + CFG_TUD_MSC*TUD_MSC_DESC_LEN + CFG_TUD_HID*TUD_HID_DESC_LEN) +#define CONFIG_TOTAL_LEN (TUD_CONFIG_DESC_LEN + TUD_CDC_DESC_LEN + TUD_MSC_DESC_LEN) #if CFG_TUSB_MCU == OPT_MCU_LPC175X_6X || CFG_TUSB_MCU == OPT_MCU_LPC177X_8X || CFG_TUSB_MCU == OPT_MCU_LPC40XX // LPC 17xx and 40xx endpoint type (bulk/interrupt/iso) are fixed by its number - // 0 control, 1 In, 2 Bulk, 3 Iso, 4 In etc ... - // Note: since CDC EP ( 1 & 2), HID (4) are spot-on, thus we only need to force - // endpoint number for MSC to 5 - #define EPNUM_MSC 0x05 + // 0 control, 1 In, 2 Bulk, 3 Iso, 4 In, 5 Bulk etc ... + #define EPNUM_CDC_NOTIF 0x81 + #define EPNUM_CDC_OUT 0x02 + #define EPNUM_CDC_IN 0x82 + + #define EPNUM_MSC_OUT 0x05 + #define EPNUM_MSC_IN 0x85 + +#elif CFG_TUSB_MCU == OPT_MCU_SAMG + // SAMG doesn't support a same endpoint number with different direction IN and OUT + // e.g EP1 OUT & EP1 IN cannot exist together + #define EPNUM_CDC_NOTIF 0x81 + #define EPNUM_CDC_OUT 0x02 + #define EPNUM_CDC_IN 0x83 + + #define EPNUM_MSC_OUT 0x04 + #define EPNUM_MSC_IN 0x85 + #else - #define EPNUM_MSC 0x03 + #define EPNUM_CDC_NOTIF 0x81 + #define EPNUM_CDC_OUT 0x02 + #define EPNUM_CDC_IN 0x82 + + #define EPNUM_MSC_OUT 0x03 + #define EPNUM_MSC_IN 0x83 + #endif uint8_t const desc_configuration[] = { - // interface count, string index, total length, attribute, power in mA + // Interface count, string index, total length, attribute, power in mA TUD_CONFIG_DESCRIPTOR(ITF_NUM_TOTAL, 0, CONFIG_TOTAL_LEN, TUSB_DESC_CONFIG_ATT_REMOTE_WAKEUP, 100), -#if CFG_TUD_CDC // Interface number, string index, EP notification address and size, EP data address (out, in) and size. - TUD_CDC_DESCRIPTOR(ITF_NUM_CDC, 4, 0x81, 8, 0x02, 0x82, 64), -#endif + TUD_CDC_DESCRIPTOR(ITF_NUM_CDC, 4, EPNUM_CDC_NOTIF, 8, EPNUM_CDC_OUT, EPNUM_CDC_IN, 64), -#if CFG_TUD_MSC // Interface number, string index, EP Out & EP In address, EP size - TUD_MSC_DESCRIPTOR(ITF_NUM_MSC, 5, EPNUM_MSC, 0x80 | EPNUM_MSC, 64), // highspeed 512 -#endif - -#if CFG_TUD_HID - // Interface number, string index, protocol, report descriptor len, EP In address, size & polling interval - TUD_HID_DESCRIPTOR(ITF_NUM_HID, 6, HID_PROTOCOL_NONE, sizeof(desc_hid_report), 0x84, 16, 10) -#endif + TUD_MSC_DESCRIPTOR(ITF_NUM_MSC, 5, EPNUM_MSC_OUT, EPNUM_MSC_IN, (CFG_TUSB_RHPORT0_MODE & OPT_MODE_HIGH_SPEED) ? 512 : 64), }; - // Invoked when received GET CONFIGURATION DESCRIPTOR // Application return pointer to descriptor // Descriptor contents must exist long enough for transfer to complete @@ -177,7 +149,6 @@ char const* string_desc_arr [] = "123456", // 3: Serials, should use chip ID "TinyUSB CDC", // 4: CDC Interface "TinyUSB MSC", // 5: MSC Interface - "TinyUSB HID" // 6: HID }; static uint16_t _desc_str[32]; From 1561692e4aa0e66484c541ab4977393bd58dba86 Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 10 Mar 2020 14:43:09 +0700 Subject: [PATCH 253/267] rename to cdc_msc_freertos --- .../device/{cdc_msc_hid_freertos => cdc_msc_freertos}/Makefile | 0 .../ses/cdc_msc_hid_freertos.emProject | 0 .../ses/lpc175x_6x/FreeRTOSConfig.h | 0 .../ses/lpc175x_6x/LPC1700_Startup.s | 0 .../ses/lpc175x_6x/LPC1700_Target.js | 0 .../ses/lpc175x_6x/LPC1769_MemoryMap.xml | 0 .../ses/lpc175x_6x/LPC176x5x_Registers.xml | 0 .../ses/lpc175x_6x/LPC176x5x_Vectors.s | 0 .../ses/lpc175x_6x/flash_placement.xml | 0 .../ses/lpc175x_6x/lpc175x_6x.emProject | 0 .../ses/lpc175x_6x/thumb_crt0.s | 0 .../ses/nrf5x/flash_placement.xml | 0 .../ses/nrf5x/nRF52840_xxAA_MemoryMap.xml | 0 .../ses/nrf5x/nRF_Target.js | 0 .../ses/nrf5x/nrf52840_Registers.xml | 0 .../ses/nrf5x/nrf5x.emProject | 0 .../ses/nrf5x/thumb_crt0.s | 0 .../ses/samd21/ATSAMD21G18A_MemoryMap.xml | 0 .../ses/samd21/ATSAMD21G18A_Registers.xml | 0 .../ses/samd21/ATSAMD21G18A_Vectors.s | 0 .../ses/samd21/SAMD21_Startup.s | 0 .../ses/samd21/SAMD21_Target.js | 0 .../ses/samd21/flash_placement.xml | 0 .../ses/samd21/samd21.emProject | 0 .../ses/samd21/thumb_crt0.s | 0 .../ses/samd51/ATSAMD51J19A_MemoryMap.xml | 0 .../ses/samd51/ATSAMD51J19A_Registers.xml | 0 .../ses/samd51/ATSAMD51J19A_Vectors.s | 0 .../ses/samd51/SAMD51_Startup.s | 0 .../ses/samd51/SAMD51_Target.js | 0 .../ses/samd51/flash_placement.xml | 0 .../ses/samd51/samd51.emProject | 0 .../ses/samd51/thumb_crt0.s | 0 .../src/freertos_hook.c | 0 .../device/{cdc_msc_hid_freertos => cdc_msc_freertos}/src/main.c | 0 .../{cdc_msc_hid_freertos => cdc_msc_freertos}/src/msc_disk.c | 0 .../{cdc_msc_hid_freertos => cdc_msc_freertos}/src/tusb_config.h | 0 .../src/usb_descriptors.c | 0 .../src/usb_descriptors.h | 0 39 files changed, 0 insertions(+), 0 deletions(-) rename examples/device/{cdc_msc_hid_freertos => cdc_msc_freertos}/Makefile (100%) rename examples/device/{cdc_msc_hid_freertos => cdc_msc_freertos}/ses/cdc_msc_hid_freertos.emProject (100%) rename examples/device/{cdc_msc_hid_freertos => cdc_msc_freertos}/ses/lpc175x_6x/FreeRTOSConfig.h (100%) rename examples/device/{cdc_msc_hid_freertos => cdc_msc_freertos}/ses/lpc175x_6x/LPC1700_Startup.s (100%) rename examples/device/{cdc_msc_hid_freertos => cdc_msc_freertos}/ses/lpc175x_6x/LPC1700_Target.js (100%) rename examples/device/{cdc_msc_hid_freertos => cdc_msc_freertos}/ses/lpc175x_6x/LPC1769_MemoryMap.xml (100%) rename examples/device/{cdc_msc_hid_freertos => cdc_msc_freertos}/ses/lpc175x_6x/LPC176x5x_Registers.xml (100%) rename examples/device/{cdc_msc_hid_freertos => cdc_msc_freertos}/ses/lpc175x_6x/LPC176x5x_Vectors.s (100%) rename examples/device/{cdc_msc_hid_freertos => cdc_msc_freertos}/ses/lpc175x_6x/flash_placement.xml (100%) rename examples/device/{cdc_msc_hid_freertos => cdc_msc_freertos}/ses/lpc175x_6x/lpc175x_6x.emProject (100%) rename examples/device/{cdc_msc_hid_freertos => cdc_msc_freertos}/ses/lpc175x_6x/thumb_crt0.s (100%) rename examples/device/{cdc_msc_hid_freertos => cdc_msc_freertos}/ses/nrf5x/flash_placement.xml (100%) rename examples/device/{cdc_msc_hid_freertos => cdc_msc_freertos}/ses/nrf5x/nRF52840_xxAA_MemoryMap.xml (100%) rename examples/device/{cdc_msc_hid_freertos => cdc_msc_freertos}/ses/nrf5x/nRF_Target.js (100%) rename examples/device/{cdc_msc_hid_freertos => cdc_msc_freertos}/ses/nrf5x/nrf52840_Registers.xml (100%) rename examples/device/{cdc_msc_hid_freertos => cdc_msc_freertos}/ses/nrf5x/nrf5x.emProject (100%) rename examples/device/{cdc_msc_hid_freertos => cdc_msc_freertos}/ses/nrf5x/thumb_crt0.s (100%) rename examples/device/{cdc_msc_hid_freertos => cdc_msc_freertos}/ses/samd21/ATSAMD21G18A_MemoryMap.xml (100%) rename examples/device/{cdc_msc_hid_freertos => cdc_msc_freertos}/ses/samd21/ATSAMD21G18A_Registers.xml (100%) rename examples/device/{cdc_msc_hid_freertos => cdc_msc_freertos}/ses/samd21/ATSAMD21G18A_Vectors.s (100%) rename examples/device/{cdc_msc_hid_freertos => cdc_msc_freertos}/ses/samd21/SAMD21_Startup.s (100%) rename examples/device/{cdc_msc_hid_freertos => cdc_msc_freertos}/ses/samd21/SAMD21_Target.js (100%) rename examples/device/{cdc_msc_hid_freertos => cdc_msc_freertos}/ses/samd21/flash_placement.xml (100%) rename examples/device/{cdc_msc_hid_freertos => cdc_msc_freertos}/ses/samd21/samd21.emProject (100%) rename examples/device/{cdc_msc_hid_freertos => cdc_msc_freertos}/ses/samd21/thumb_crt0.s (100%) rename examples/device/{cdc_msc_hid_freertos => cdc_msc_freertos}/ses/samd51/ATSAMD51J19A_MemoryMap.xml (100%) rename examples/device/{cdc_msc_hid_freertos => cdc_msc_freertos}/ses/samd51/ATSAMD51J19A_Registers.xml (100%) rename examples/device/{cdc_msc_hid_freertos => cdc_msc_freertos}/ses/samd51/ATSAMD51J19A_Vectors.s (100%) rename examples/device/{cdc_msc_hid_freertos => cdc_msc_freertos}/ses/samd51/SAMD51_Startup.s (100%) rename examples/device/{cdc_msc_hid_freertos => cdc_msc_freertos}/ses/samd51/SAMD51_Target.js (100%) rename examples/device/{cdc_msc_hid_freertos => cdc_msc_freertos}/ses/samd51/flash_placement.xml (100%) rename examples/device/{cdc_msc_hid_freertos => cdc_msc_freertos}/ses/samd51/samd51.emProject (100%) rename examples/device/{cdc_msc_hid_freertos => cdc_msc_freertos}/ses/samd51/thumb_crt0.s (100%) rename examples/device/{cdc_msc_hid_freertos => cdc_msc_freertos}/src/freertos_hook.c (100%) rename examples/device/{cdc_msc_hid_freertos => cdc_msc_freertos}/src/main.c (100%) rename examples/device/{cdc_msc_hid_freertos => cdc_msc_freertos}/src/msc_disk.c (100%) rename examples/device/{cdc_msc_hid_freertos => cdc_msc_freertos}/src/tusb_config.h (100%) rename examples/device/{cdc_msc_hid_freertos => cdc_msc_freertos}/src/usb_descriptors.c (100%) rename examples/device/{cdc_msc_hid_freertos => cdc_msc_freertos}/src/usb_descriptors.h (100%) diff --git a/examples/device/cdc_msc_hid_freertos/Makefile b/examples/device/cdc_msc_freertos/Makefile similarity index 100% rename from examples/device/cdc_msc_hid_freertos/Makefile rename to examples/device/cdc_msc_freertos/Makefile diff --git a/examples/device/cdc_msc_hid_freertos/ses/cdc_msc_hid_freertos.emProject b/examples/device/cdc_msc_freertos/ses/cdc_msc_hid_freertos.emProject similarity index 100% rename from examples/device/cdc_msc_hid_freertos/ses/cdc_msc_hid_freertos.emProject rename to examples/device/cdc_msc_freertos/ses/cdc_msc_hid_freertos.emProject diff --git a/examples/device/cdc_msc_hid_freertos/ses/lpc175x_6x/FreeRTOSConfig.h b/examples/device/cdc_msc_freertos/ses/lpc175x_6x/FreeRTOSConfig.h similarity index 100% rename from examples/device/cdc_msc_hid_freertos/ses/lpc175x_6x/FreeRTOSConfig.h rename to examples/device/cdc_msc_freertos/ses/lpc175x_6x/FreeRTOSConfig.h diff --git a/examples/device/cdc_msc_hid_freertos/ses/lpc175x_6x/LPC1700_Startup.s b/examples/device/cdc_msc_freertos/ses/lpc175x_6x/LPC1700_Startup.s similarity index 100% rename from examples/device/cdc_msc_hid_freertos/ses/lpc175x_6x/LPC1700_Startup.s rename to examples/device/cdc_msc_freertos/ses/lpc175x_6x/LPC1700_Startup.s diff --git a/examples/device/cdc_msc_hid_freertos/ses/lpc175x_6x/LPC1700_Target.js b/examples/device/cdc_msc_freertos/ses/lpc175x_6x/LPC1700_Target.js similarity index 100% rename from examples/device/cdc_msc_hid_freertos/ses/lpc175x_6x/LPC1700_Target.js rename to examples/device/cdc_msc_freertos/ses/lpc175x_6x/LPC1700_Target.js diff --git a/examples/device/cdc_msc_hid_freertos/ses/lpc175x_6x/LPC1769_MemoryMap.xml b/examples/device/cdc_msc_freertos/ses/lpc175x_6x/LPC1769_MemoryMap.xml similarity index 100% rename from examples/device/cdc_msc_hid_freertos/ses/lpc175x_6x/LPC1769_MemoryMap.xml rename to examples/device/cdc_msc_freertos/ses/lpc175x_6x/LPC1769_MemoryMap.xml diff --git a/examples/device/cdc_msc_hid_freertos/ses/lpc175x_6x/LPC176x5x_Registers.xml b/examples/device/cdc_msc_freertos/ses/lpc175x_6x/LPC176x5x_Registers.xml similarity index 100% rename from examples/device/cdc_msc_hid_freertos/ses/lpc175x_6x/LPC176x5x_Registers.xml rename to examples/device/cdc_msc_freertos/ses/lpc175x_6x/LPC176x5x_Registers.xml diff --git a/examples/device/cdc_msc_hid_freertos/ses/lpc175x_6x/LPC176x5x_Vectors.s b/examples/device/cdc_msc_freertos/ses/lpc175x_6x/LPC176x5x_Vectors.s similarity index 100% rename from examples/device/cdc_msc_hid_freertos/ses/lpc175x_6x/LPC176x5x_Vectors.s rename to examples/device/cdc_msc_freertos/ses/lpc175x_6x/LPC176x5x_Vectors.s diff --git a/examples/device/cdc_msc_hid_freertos/ses/lpc175x_6x/flash_placement.xml b/examples/device/cdc_msc_freertos/ses/lpc175x_6x/flash_placement.xml similarity index 100% rename from examples/device/cdc_msc_hid_freertos/ses/lpc175x_6x/flash_placement.xml rename to examples/device/cdc_msc_freertos/ses/lpc175x_6x/flash_placement.xml diff --git a/examples/device/cdc_msc_hid_freertos/ses/lpc175x_6x/lpc175x_6x.emProject b/examples/device/cdc_msc_freertos/ses/lpc175x_6x/lpc175x_6x.emProject similarity index 100% rename from examples/device/cdc_msc_hid_freertos/ses/lpc175x_6x/lpc175x_6x.emProject rename to examples/device/cdc_msc_freertos/ses/lpc175x_6x/lpc175x_6x.emProject diff --git a/examples/device/cdc_msc_hid_freertos/ses/lpc175x_6x/thumb_crt0.s b/examples/device/cdc_msc_freertos/ses/lpc175x_6x/thumb_crt0.s similarity index 100% rename from examples/device/cdc_msc_hid_freertos/ses/lpc175x_6x/thumb_crt0.s rename to examples/device/cdc_msc_freertos/ses/lpc175x_6x/thumb_crt0.s diff --git a/examples/device/cdc_msc_hid_freertos/ses/nrf5x/flash_placement.xml b/examples/device/cdc_msc_freertos/ses/nrf5x/flash_placement.xml similarity index 100% rename from examples/device/cdc_msc_hid_freertos/ses/nrf5x/flash_placement.xml rename to examples/device/cdc_msc_freertos/ses/nrf5x/flash_placement.xml diff --git a/examples/device/cdc_msc_hid_freertos/ses/nrf5x/nRF52840_xxAA_MemoryMap.xml b/examples/device/cdc_msc_freertos/ses/nrf5x/nRF52840_xxAA_MemoryMap.xml similarity index 100% rename from examples/device/cdc_msc_hid_freertos/ses/nrf5x/nRF52840_xxAA_MemoryMap.xml rename to examples/device/cdc_msc_freertos/ses/nrf5x/nRF52840_xxAA_MemoryMap.xml diff --git a/examples/device/cdc_msc_hid_freertos/ses/nrf5x/nRF_Target.js b/examples/device/cdc_msc_freertos/ses/nrf5x/nRF_Target.js similarity index 100% rename from examples/device/cdc_msc_hid_freertos/ses/nrf5x/nRF_Target.js rename to examples/device/cdc_msc_freertos/ses/nrf5x/nRF_Target.js diff --git a/examples/device/cdc_msc_hid_freertos/ses/nrf5x/nrf52840_Registers.xml b/examples/device/cdc_msc_freertos/ses/nrf5x/nrf52840_Registers.xml similarity index 100% rename from examples/device/cdc_msc_hid_freertos/ses/nrf5x/nrf52840_Registers.xml rename to examples/device/cdc_msc_freertos/ses/nrf5x/nrf52840_Registers.xml diff --git a/examples/device/cdc_msc_hid_freertos/ses/nrf5x/nrf5x.emProject b/examples/device/cdc_msc_freertos/ses/nrf5x/nrf5x.emProject similarity index 100% rename from examples/device/cdc_msc_hid_freertos/ses/nrf5x/nrf5x.emProject rename to examples/device/cdc_msc_freertos/ses/nrf5x/nrf5x.emProject diff --git a/examples/device/cdc_msc_hid_freertos/ses/nrf5x/thumb_crt0.s b/examples/device/cdc_msc_freertos/ses/nrf5x/thumb_crt0.s similarity index 100% rename from examples/device/cdc_msc_hid_freertos/ses/nrf5x/thumb_crt0.s rename to examples/device/cdc_msc_freertos/ses/nrf5x/thumb_crt0.s diff --git a/examples/device/cdc_msc_hid_freertos/ses/samd21/ATSAMD21G18A_MemoryMap.xml b/examples/device/cdc_msc_freertos/ses/samd21/ATSAMD21G18A_MemoryMap.xml similarity index 100% rename from examples/device/cdc_msc_hid_freertos/ses/samd21/ATSAMD21G18A_MemoryMap.xml rename to examples/device/cdc_msc_freertos/ses/samd21/ATSAMD21G18A_MemoryMap.xml diff --git a/examples/device/cdc_msc_hid_freertos/ses/samd21/ATSAMD21G18A_Registers.xml b/examples/device/cdc_msc_freertos/ses/samd21/ATSAMD21G18A_Registers.xml similarity index 100% rename from examples/device/cdc_msc_hid_freertos/ses/samd21/ATSAMD21G18A_Registers.xml rename to examples/device/cdc_msc_freertos/ses/samd21/ATSAMD21G18A_Registers.xml diff --git a/examples/device/cdc_msc_hid_freertos/ses/samd21/ATSAMD21G18A_Vectors.s b/examples/device/cdc_msc_freertos/ses/samd21/ATSAMD21G18A_Vectors.s similarity index 100% rename from examples/device/cdc_msc_hid_freertos/ses/samd21/ATSAMD21G18A_Vectors.s rename to examples/device/cdc_msc_freertos/ses/samd21/ATSAMD21G18A_Vectors.s diff --git a/examples/device/cdc_msc_hid_freertos/ses/samd21/SAMD21_Startup.s b/examples/device/cdc_msc_freertos/ses/samd21/SAMD21_Startup.s similarity index 100% rename from examples/device/cdc_msc_hid_freertos/ses/samd21/SAMD21_Startup.s rename to examples/device/cdc_msc_freertos/ses/samd21/SAMD21_Startup.s diff --git a/examples/device/cdc_msc_hid_freertos/ses/samd21/SAMD21_Target.js b/examples/device/cdc_msc_freertos/ses/samd21/SAMD21_Target.js similarity index 100% rename from examples/device/cdc_msc_hid_freertos/ses/samd21/SAMD21_Target.js rename to examples/device/cdc_msc_freertos/ses/samd21/SAMD21_Target.js diff --git a/examples/device/cdc_msc_hid_freertos/ses/samd21/flash_placement.xml b/examples/device/cdc_msc_freertos/ses/samd21/flash_placement.xml similarity index 100% rename from examples/device/cdc_msc_hid_freertos/ses/samd21/flash_placement.xml rename to examples/device/cdc_msc_freertos/ses/samd21/flash_placement.xml diff --git a/examples/device/cdc_msc_hid_freertos/ses/samd21/samd21.emProject b/examples/device/cdc_msc_freertos/ses/samd21/samd21.emProject similarity index 100% rename from examples/device/cdc_msc_hid_freertos/ses/samd21/samd21.emProject rename to examples/device/cdc_msc_freertos/ses/samd21/samd21.emProject diff --git a/examples/device/cdc_msc_hid_freertos/ses/samd21/thumb_crt0.s b/examples/device/cdc_msc_freertos/ses/samd21/thumb_crt0.s similarity index 100% rename from examples/device/cdc_msc_hid_freertos/ses/samd21/thumb_crt0.s rename to examples/device/cdc_msc_freertos/ses/samd21/thumb_crt0.s diff --git a/examples/device/cdc_msc_hid_freertos/ses/samd51/ATSAMD51J19A_MemoryMap.xml b/examples/device/cdc_msc_freertos/ses/samd51/ATSAMD51J19A_MemoryMap.xml similarity index 100% rename from examples/device/cdc_msc_hid_freertos/ses/samd51/ATSAMD51J19A_MemoryMap.xml rename to examples/device/cdc_msc_freertos/ses/samd51/ATSAMD51J19A_MemoryMap.xml diff --git a/examples/device/cdc_msc_hid_freertos/ses/samd51/ATSAMD51J19A_Registers.xml b/examples/device/cdc_msc_freertos/ses/samd51/ATSAMD51J19A_Registers.xml similarity index 100% rename from examples/device/cdc_msc_hid_freertos/ses/samd51/ATSAMD51J19A_Registers.xml rename to examples/device/cdc_msc_freertos/ses/samd51/ATSAMD51J19A_Registers.xml diff --git a/examples/device/cdc_msc_hid_freertos/ses/samd51/ATSAMD51J19A_Vectors.s b/examples/device/cdc_msc_freertos/ses/samd51/ATSAMD51J19A_Vectors.s similarity index 100% rename from examples/device/cdc_msc_hid_freertos/ses/samd51/ATSAMD51J19A_Vectors.s rename to examples/device/cdc_msc_freertos/ses/samd51/ATSAMD51J19A_Vectors.s diff --git a/examples/device/cdc_msc_hid_freertos/ses/samd51/SAMD51_Startup.s b/examples/device/cdc_msc_freertos/ses/samd51/SAMD51_Startup.s similarity index 100% rename from examples/device/cdc_msc_hid_freertos/ses/samd51/SAMD51_Startup.s rename to examples/device/cdc_msc_freertos/ses/samd51/SAMD51_Startup.s diff --git a/examples/device/cdc_msc_hid_freertos/ses/samd51/SAMD51_Target.js b/examples/device/cdc_msc_freertos/ses/samd51/SAMD51_Target.js similarity index 100% rename from examples/device/cdc_msc_hid_freertos/ses/samd51/SAMD51_Target.js rename to examples/device/cdc_msc_freertos/ses/samd51/SAMD51_Target.js diff --git a/examples/device/cdc_msc_hid_freertos/ses/samd51/flash_placement.xml b/examples/device/cdc_msc_freertos/ses/samd51/flash_placement.xml similarity index 100% rename from examples/device/cdc_msc_hid_freertos/ses/samd51/flash_placement.xml rename to examples/device/cdc_msc_freertos/ses/samd51/flash_placement.xml diff --git a/examples/device/cdc_msc_hid_freertos/ses/samd51/samd51.emProject b/examples/device/cdc_msc_freertos/ses/samd51/samd51.emProject similarity index 100% rename from examples/device/cdc_msc_hid_freertos/ses/samd51/samd51.emProject rename to examples/device/cdc_msc_freertos/ses/samd51/samd51.emProject diff --git a/examples/device/cdc_msc_hid_freertos/ses/samd51/thumb_crt0.s b/examples/device/cdc_msc_freertos/ses/samd51/thumb_crt0.s similarity index 100% rename from examples/device/cdc_msc_hid_freertos/ses/samd51/thumb_crt0.s rename to examples/device/cdc_msc_freertos/ses/samd51/thumb_crt0.s diff --git a/examples/device/cdc_msc_hid_freertos/src/freertos_hook.c b/examples/device/cdc_msc_freertos/src/freertos_hook.c similarity index 100% rename from examples/device/cdc_msc_hid_freertos/src/freertos_hook.c rename to examples/device/cdc_msc_freertos/src/freertos_hook.c diff --git a/examples/device/cdc_msc_hid_freertos/src/main.c b/examples/device/cdc_msc_freertos/src/main.c similarity index 100% rename from examples/device/cdc_msc_hid_freertos/src/main.c rename to examples/device/cdc_msc_freertos/src/main.c diff --git a/examples/device/cdc_msc_hid_freertos/src/msc_disk.c b/examples/device/cdc_msc_freertos/src/msc_disk.c similarity index 100% rename from examples/device/cdc_msc_hid_freertos/src/msc_disk.c rename to examples/device/cdc_msc_freertos/src/msc_disk.c diff --git a/examples/device/cdc_msc_hid_freertos/src/tusb_config.h b/examples/device/cdc_msc_freertos/src/tusb_config.h similarity index 100% rename from examples/device/cdc_msc_hid_freertos/src/tusb_config.h rename to examples/device/cdc_msc_freertos/src/tusb_config.h diff --git a/examples/device/cdc_msc_hid_freertos/src/usb_descriptors.c b/examples/device/cdc_msc_freertos/src/usb_descriptors.c similarity index 100% rename from examples/device/cdc_msc_hid_freertos/src/usb_descriptors.c rename to examples/device/cdc_msc_freertos/src/usb_descriptors.c diff --git a/examples/device/cdc_msc_hid_freertos/src/usb_descriptors.h b/examples/device/cdc_msc_freertos/src/usb_descriptors.h similarity index 100% rename from examples/device/cdc_msc_hid_freertos/src/usb_descriptors.h rename to examples/device/cdc_msc_freertos/src/usb_descriptors.h From 39ce2e8361730e50fef7c968195d759de1800bcd Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 10 Mar 2020 14:49:01 +0700 Subject: [PATCH 254/267] adding FreeRTOS as submodule --- lib/FreeRTOS/License/license.txt | 37 - lib/FreeRTOS/Source/croutine.c | 353 -- lib/FreeRTOS/Source/event_groups.c | 738 --- lib/FreeRTOS/Source/include/FreeRTOS.h | 1168 ---- lib/FreeRTOS/Source/include/StackMacros.h | 133 - lib/FreeRTOS/Source/include/croutine.h | 720 --- .../Source/include/deprecated_definitions.h | 279 - lib/FreeRTOS/Source/include/event_groups.h | 756 --- lib/FreeRTOS/Source/include/list.h | 411 -- lib/FreeRTOS/Source/include/message_buffer.h | 779 --- lib/FreeRTOS/Source/include/mpu_prototypes.h | 155 - lib/FreeRTOS/Source/include/mpu_wrappers.h | 181 - lib/FreeRTOS/Source/include/portable.h | 165 - lib/FreeRTOS/Source/include/projdefs.h | 124 - lib/FreeRTOS/Source/include/queue.h | 1653 ------ lib/FreeRTOS/Source/include/semphr.h | 1140 ---- lib/FreeRTOS/Source/include/stack_macros.h | 129 - lib/FreeRTOS/Source/include/stdint.readme | 27 - lib/FreeRTOS/Source/include/stream_buffer.h | 852 --- lib/FreeRTOS/Source/include/task.h | 2338 -------- lib/FreeRTOS/Source/include/timers.h | 1277 ----- lib/FreeRTOS/Source/list.c | 198 - .../Source/portable/Common/mpu_wrappers.c | 1290 ----- .../Source/portable/GCC/ARM_CM0/port.c | 362 -- .../Source/portable/GCC/ARM_CM0/portmacro.h | 115 - .../Source/portable/GCC/ARM_CM3/port.c | 717 --- .../Source/portable/GCC/ARM_CM3/portmacro.h | 242 - .../Source/portable/GCC/ARM_CM4F/port.c | 775 --- .../Source/portable/GCC/ARM_CM4F/portmacro.h | 242 - .../Source/portable/MemMang/ReadMe.url | 5 - lib/FreeRTOS/Source/portable/MemMang/heap_4.c | 436 -- lib/FreeRTOS/Source/portable/readme.txt | 20 - lib/FreeRTOS/Source/queue.c | 2909 ---------- lib/FreeRTOS/Source/readme.txt | 17 - lib/FreeRTOS/Source/stream_buffer.c | 1199 ---- lib/FreeRTOS/Source/tasks.c | 5045 ----------------- lib/FreeRTOS/Source/timers.c | 1076 ---- lib/FreeRTOS/readme.txt | 21 - 38 files changed, 28084 deletions(-) delete mode 100644 lib/FreeRTOS/License/license.txt delete mode 100644 lib/FreeRTOS/Source/croutine.c delete mode 100644 lib/FreeRTOS/Source/event_groups.c delete mode 100644 lib/FreeRTOS/Source/include/FreeRTOS.h delete mode 100644 lib/FreeRTOS/Source/include/StackMacros.h delete mode 100644 lib/FreeRTOS/Source/include/croutine.h delete mode 100644 lib/FreeRTOS/Source/include/deprecated_definitions.h delete mode 100644 lib/FreeRTOS/Source/include/event_groups.h delete mode 100644 lib/FreeRTOS/Source/include/list.h delete mode 100644 lib/FreeRTOS/Source/include/message_buffer.h delete mode 100644 lib/FreeRTOS/Source/include/mpu_prototypes.h delete mode 100644 lib/FreeRTOS/Source/include/mpu_wrappers.h delete mode 100644 lib/FreeRTOS/Source/include/portable.h delete mode 100644 lib/FreeRTOS/Source/include/projdefs.h delete mode 100644 lib/FreeRTOS/Source/include/queue.h delete mode 100644 lib/FreeRTOS/Source/include/semphr.h delete mode 100644 lib/FreeRTOS/Source/include/stack_macros.h delete mode 100644 lib/FreeRTOS/Source/include/stdint.readme delete mode 100644 lib/FreeRTOS/Source/include/stream_buffer.h delete mode 100644 lib/FreeRTOS/Source/include/task.h delete mode 100644 lib/FreeRTOS/Source/include/timers.h delete mode 100644 lib/FreeRTOS/Source/list.c delete mode 100644 lib/FreeRTOS/Source/portable/Common/mpu_wrappers.c delete mode 100644 lib/FreeRTOS/Source/portable/GCC/ARM_CM0/port.c delete mode 100644 lib/FreeRTOS/Source/portable/GCC/ARM_CM0/portmacro.h delete mode 100644 lib/FreeRTOS/Source/portable/GCC/ARM_CM3/port.c delete mode 100644 lib/FreeRTOS/Source/portable/GCC/ARM_CM3/portmacro.h delete mode 100644 lib/FreeRTOS/Source/portable/GCC/ARM_CM4F/port.c delete mode 100644 lib/FreeRTOS/Source/portable/GCC/ARM_CM4F/portmacro.h delete mode 100644 lib/FreeRTOS/Source/portable/MemMang/ReadMe.url delete mode 100644 lib/FreeRTOS/Source/portable/MemMang/heap_4.c delete mode 100644 lib/FreeRTOS/Source/portable/readme.txt delete mode 100644 lib/FreeRTOS/Source/queue.c delete mode 100644 lib/FreeRTOS/Source/readme.txt delete mode 100644 lib/FreeRTOS/Source/stream_buffer.c delete mode 100644 lib/FreeRTOS/Source/tasks.c delete mode 100644 lib/FreeRTOS/Source/timers.c delete mode 100644 lib/FreeRTOS/readme.txt diff --git a/lib/FreeRTOS/License/license.txt b/lib/FreeRTOS/License/license.txt deleted file mode 100644 index 0072310c..00000000 --- a/lib/FreeRTOS/License/license.txt +++ /dev/null @@ -1,37 +0,0 @@ -The FreeRTOS kernel is released under the MIT open source license, the text of -which is provided below. - -This license covers the FreeRTOS kernel source files, which are located in the -/FreeRTOS/Source directory of the official FreeRTOS kernel download. It also -covers most of the source files in the demo application projects, which are -located in the /FreeRTOS/Demo directory of the official FreeRTOS download. The -demo projects may also include third party software that is not part of FreeRTOS -and is licensed separately to FreeRTOS. Examples of third party software -includes header files provided by chip or tools vendors, linker scripts, -peripheral drivers, etc. All the software in subdirectories of the /FreeRTOS -directory is either open source or distributed with permission, and is free for -use. For the avoidance of doubt, refer to the comments at the top of each -source file. - - -License text: -------------- - -Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. -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. - diff --git a/lib/FreeRTOS/Source/croutine.c b/lib/FreeRTOS/Source/croutine.c deleted file mode 100644 index b7158845..00000000 --- a/lib/FreeRTOS/Source/croutine.c +++ /dev/null @@ -1,353 +0,0 @@ -/* - * FreeRTOS Kernel V10.0.1 - * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * 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. - * - * http://www.FreeRTOS.org - * http://aws.amazon.com/freertos - * - * 1 tab == 4 spaces! - */ - -#include "FreeRTOS.h" -#include "task.h" -#include "croutine.h" - -/* Remove the whole file is co-routines are not being used. */ -#if( configUSE_CO_ROUTINES != 0 ) - -/* - * Some kernel aware debuggers require data to be viewed to be global, rather - * than file scope. - */ -#ifdef portREMOVE_STATIC_QUALIFIER - #define static -#endif - - -/* Lists for ready and blocked co-routines. --------------------*/ -static List_t pxReadyCoRoutineLists[ configMAX_CO_ROUTINE_PRIORITIES ]; /*< Prioritised ready co-routines. */ -static List_t xDelayedCoRoutineList1; /*< Delayed co-routines. */ -static List_t xDelayedCoRoutineList2; /*< Delayed co-routines (two lists are used - one for delays that have overflowed the current tick count. */ -static List_t * pxDelayedCoRoutineList; /*< Points to the delayed co-routine list currently being used. */ -static List_t * pxOverflowDelayedCoRoutineList; /*< Points to the delayed co-routine list currently being used to hold co-routines that have overflowed the current tick count. */ -static List_t xPendingReadyCoRoutineList; /*< Holds co-routines that have been readied by an external event. They cannot be added directly to the ready lists as the ready lists cannot be accessed by interrupts. */ - -/* Other file private variables. --------------------------------*/ -CRCB_t * pxCurrentCoRoutine = NULL; -static UBaseType_t uxTopCoRoutineReadyPriority = 0; -static TickType_t xCoRoutineTickCount = 0, xLastTickCount = 0, xPassedTicks = 0; - -/* The initial state of the co-routine when it is created. */ -#define corINITIAL_STATE ( 0 ) - -/* - * Place the co-routine represented by pxCRCB into the appropriate ready queue - * for the priority. It is inserted at the end of the list. - * - * This macro accesses the co-routine ready lists and therefore must not be - * used from within an ISR. - */ -#define prvAddCoRoutineToReadyQueue( pxCRCB ) \ -{ \ - if( pxCRCB->uxPriority > uxTopCoRoutineReadyPriority ) \ - { \ - uxTopCoRoutineReadyPriority = pxCRCB->uxPriority; \ - } \ - vListInsertEnd( ( List_t * ) &( pxReadyCoRoutineLists[ pxCRCB->uxPriority ] ), &( pxCRCB->xGenericListItem ) ); \ -} - -/* - * Utility to ready all the lists used by the scheduler. This is called - * automatically upon the creation of the first co-routine. - */ -static void prvInitialiseCoRoutineLists( void ); - -/* - * Co-routines that are readied by an interrupt cannot be placed directly into - * the ready lists (there is no mutual exclusion). Instead they are placed in - * in the pending ready list in order that they can later be moved to the ready - * list by the co-routine scheduler. - */ -static void prvCheckPendingReadyList( void ); - -/* - * Macro that looks at the list of co-routines that are currently delayed to - * see if any require waking. - * - * Co-routines are stored in the queue in the order of their wake time - - * meaning once one co-routine has been found whose timer has not expired - * we need not look any further down the list. - */ -static void prvCheckDelayedList( void ); - -/*-----------------------------------------------------------*/ - -BaseType_t xCoRoutineCreate( crCOROUTINE_CODE pxCoRoutineCode, UBaseType_t uxPriority, UBaseType_t uxIndex ) -{ -BaseType_t xReturn; -CRCB_t *pxCoRoutine; - - /* Allocate the memory that will store the co-routine control block. */ - pxCoRoutine = ( CRCB_t * ) pvPortMalloc( sizeof( CRCB_t ) ); - if( pxCoRoutine ) - { - /* If pxCurrentCoRoutine is NULL then this is the first co-routine to - be created and the co-routine data structures need initialising. */ - if( pxCurrentCoRoutine == NULL ) - { - pxCurrentCoRoutine = pxCoRoutine; - prvInitialiseCoRoutineLists(); - } - - /* Check the priority is within limits. */ - if( uxPriority >= configMAX_CO_ROUTINE_PRIORITIES ) - { - uxPriority = configMAX_CO_ROUTINE_PRIORITIES - 1; - } - - /* Fill out the co-routine control block from the function parameters. */ - pxCoRoutine->uxState = corINITIAL_STATE; - pxCoRoutine->uxPriority = uxPriority; - pxCoRoutine->uxIndex = uxIndex; - pxCoRoutine->pxCoRoutineFunction = pxCoRoutineCode; - - /* Initialise all the other co-routine control block parameters. */ - vListInitialiseItem( &( pxCoRoutine->xGenericListItem ) ); - vListInitialiseItem( &( pxCoRoutine->xEventListItem ) ); - - /* Set the co-routine control block as a link back from the ListItem_t. - This is so we can get back to the containing CRCB from a generic item - in a list. */ - listSET_LIST_ITEM_OWNER( &( pxCoRoutine->xGenericListItem ), pxCoRoutine ); - listSET_LIST_ITEM_OWNER( &( pxCoRoutine->xEventListItem ), pxCoRoutine ); - - /* Event lists are always in priority order. */ - listSET_LIST_ITEM_VALUE( &( pxCoRoutine->xEventListItem ), ( ( TickType_t ) configMAX_CO_ROUTINE_PRIORITIES - ( TickType_t ) uxPriority ) ); - - /* Now the co-routine has been initialised it can be added to the ready - list at the correct priority. */ - prvAddCoRoutineToReadyQueue( pxCoRoutine ); - - xReturn = pdPASS; - } - else - { - xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY; - } - - return xReturn; -} -/*-----------------------------------------------------------*/ - -void vCoRoutineAddToDelayedList( TickType_t xTicksToDelay, List_t *pxEventList ) -{ -TickType_t xTimeToWake; - - /* Calculate the time to wake - this may overflow but this is - not a problem. */ - xTimeToWake = xCoRoutineTickCount + xTicksToDelay; - - /* We must remove ourselves from the ready list before adding - ourselves to the blocked list as the same list item is used for - both lists. */ - ( void ) uxListRemove( ( ListItem_t * ) &( pxCurrentCoRoutine->xGenericListItem ) ); - - /* The list item will be inserted in wake time order. */ - listSET_LIST_ITEM_VALUE( &( pxCurrentCoRoutine->xGenericListItem ), xTimeToWake ); - - if( xTimeToWake < xCoRoutineTickCount ) - { - /* Wake time has overflowed. Place this item in the - overflow list. */ - vListInsert( ( List_t * ) pxOverflowDelayedCoRoutineList, ( ListItem_t * ) &( pxCurrentCoRoutine->xGenericListItem ) ); - } - else - { - /* The wake time has not overflowed, so we can use the - current block list. */ - vListInsert( ( List_t * ) pxDelayedCoRoutineList, ( ListItem_t * ) &( pxCurrentCoRoutine->xGenericListItem ) ); - } - - if( pxEventList ) - { - /* Also add the co-routine to an event list. If this is done then the - function must be called with interrupts disabled. */ - vListInsert( pxEventList, &( pxCurrentCoRoutine->xEventListItem ) ); - } -} -/*-----------------------------------------------------------*/ - -static void prvCheckPendingReadyList( void ) -{ - /* Are there any co-routines waiting to get moved to the ready list? These - are co-routines that have been readied by an ISR. The ISR cannot access - the ready lists itself. */ - while( listLIST_IS_EMPTY( &xPendingReadyCoRoutineList ) == pdFALSE ) - { - CRCB_t *pxUnblockedCRCB; - - /* The pending ready list can be accessed by an ISR. */ - portDISABLE_INTERRUPTS(); - { - pxUnblockedCRCB = ( CRCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( (&xPendingReadyCoRoutineList) ); - ( void ) uxListRemove( &( pxUnblockedCRCB->xEventListItem ) ); - } - portENABLE_INTERRUPTS(); - - ( void ) uxListRemove( &( pxUnblockedCRCB->xGenericListItem ) ); - prvAddCoRoutineToReadyQueue( pxUnblockedCRCB ); - } -} -/*-----------------------------------------------------------*/ - -static void prvCheckDelayedList( void ) -{ -CRCB_t *pxCRCB; - - xPassedTicks = xTaskGetTickCount() - xLastTickCount; - while( xPassedTicks ) - { - xCoRoutineTickCount++; - xPassedTicks--; - - /* If the tick count has overflowed we need to swap the ready lists. */ - if( xCoRoutineTickCount == 0 ) - { - List_t * pxTemp; - - /* Tick count has overflowed so we need to swap the delay lists. If there are - any items in pxDelayedCoRoutineList here then there is an error! */ - pxTemp = pxDelayedCoRoutineList; - pxDelayedCoRoutineList = pxOverflowDelayedCoRoutineList; - pxOverflowDelayedCoRoutineList = pxTemp; - } - - /* See if this tick has made a timeout expire. */ - while( listLIST_IS_EMPTY( pxDelayedCoRoutineList ) == pdFALSE ) - { - pxCRCB = ( CRCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxDelayedCoRoutineList ); - - if( xCoRoutineTickCount < listGET_LIST_ITEM_VALUE( &( pxCRCB->xGenericListItem ) ) ) - { - /* Timeout not yet expired. */ - break; - } - - portDISABLE_INTERRUPTS(); - { - /* The event could have occurred just before this critical - section. If this is the case then the generic list item will - have been moved to the pending ready list and the following - line is still valid. Also the pvContainer parameter will have - been set to NULL so the following lines are also valid. */ - ( void ) uxListRemove( &( pxCRCB->xGenericListItem ) ); - - /* Is the co-routine waiting on an event also? */ - if( pxCRCB->xEventListItem.pvContainer ) - { - ( void ) uxListRemove( &( pxCRCB->xEventListItem ) ); - } - } - portENABLE_INTERRUPTS(); - - prvAddCoRoutineToReadyQueue( pxCRCB ); - } - } - - xLastTickCount = xCoRoutineTickCount; -} -/*-----------------------------------------------------------*/ - -void vCoRoutineSchedule( void ) -{ - /* See if any co-routines readied by events need moving to the ready lists. */ - prvCheckPendingReadyList(); - - /* See if any delayed co-routines have timed out. */ - prvCheckDelayedList(); - - /* Find the highest priority queue that contains ready co-routines. */ - while( listLIST_IS_EMPTY( &( pxReadyCoRoutineLists[ uxTopCoRoutineReadyPriority ] ) ) ) - { - if( uxTopCoRoutineReadyPriority == 0 ) - { - /* No more co-routines to check. */ - return; - } - --uxTopCoRoutineReadyPriority; - } - - /* listGET_OWNER_OF_NEXT_ENTRY walks through the list, so the co-routines - of the same priority get an equal share of the processor time. */ - listGET_OWNER_OF_NEXT_ENTRY( pxCurrentCoRoutine, &( pxReadyCoRoutineLists[ uxTopCoRoutineReadyPriority ] ) ); - - /* Call the co-routine. */ - ( pxCurrentCoRoutine->pxCoRoutineFunction )( pxCurrentCoRoutine, pxCurrentCoRoutine->uxIndex ); - - return; -} -/*-----------------------------------------------------------*/ - -static void prvInitialiseCoRoutineLists( void ) -{ -UBaseType_t uxPriority; - - for( uxPriority = 0; uxPriority < configMAX_CO_ROUTINE_PRIORITIES; uxPriority++ ) - { - vListInitialise( ( List_t * ) &( pxReadyCoRoutineLists[ uxPriority ] ) ); - } - - vListInitialise( ( List_t * ) &xDelayedCoRoutineList1 ); - vListInitialise( ( List_t * ) &xDelayedCoRoutineList2 ); - vListInitialise( ( List_t * ) &xPendingReadyCoRoutineList ); - - /* Start with pxDelayedCoRoutineList using list1 and the - pxOverflowDelayedCoRoutineList using list2. */ - pxDelayedCoRoutineList = &xDelayedCoRoutineList1; - pxOverflowDelayedCoRoutineList = &xDelayedCoRoutineList2; -} -/*-----------------------------------------------------------*/ - -BaseType_t xCoRoutineRemoveFromEventList( const List_t *pxEventList ) -{ -CRCB_t *pxUnblockedCRCB; -BaseType_t xReturn; - - /* This function is called from within an interrupt. It can only access - event lists and the pending ready list. This function assumes that a - check has already been made to ensure pxEventList is not empty. */ - pxUnblockedCRCB = ( CRCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxEventList ); - ( void ) uxListRemove( &( pxUnblockedCRCB->xEventListItem ) ); - vListInsertEnd( ( List_t * ) &( xPendingReadyCoRoutineList ), &( pxUnblockedCRCB->xEventListItem ) ); - - if( pxUnblockedCRCB->uxPriority >= pxCurrentCoRoutine->uxPriority ) - { - xReturn = pdTRUE; - } - else - { - xReturn = pdFALSE; - } - - return xReturn; -} - -#endif /* configUSE_CO_ROUTINES == 0 */ - diff --git a/lib/FreeRTOS/Source/event_groups.c b/lib/FreeRTOS/Source/event_groups.c deleted file mode 100644 index 14d7b024..00000000 --- a/lib/FreeRTOS/Source/event_groups.c +++ /dev/null @@ -1,738 +0,0 @@ -/* - * FreeRTOS Kernel V10.0.1 - * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * 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. - * - * http://www.FreeRTOS.org - * http://aws.amazon.com/freertos - * - * 1 tab == 4 spaces! - */ - -/* Standard includes. */ -#include - -/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining -all the API functions to use the MPU wrappers. That should only be done when -task.h is included from an application file. */ -#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE - -/* FreeRTOS includes. */ -#include "FreeRTOS.h" -#include "task.h" -#include "timers.h" -#include "event_groups.h" - -/* Lint e961 and e750 are suppressed as a MISRA exception justified because the -MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be defined for the -header files above, but not in this file, in order to generate the correct -privileged Vs unprivileged linkage and placement. */ -#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /*lint !e961 !e750. */ - -/* The following bit fields convey control information in a task's event list -item value. It is important they don't clash with the -taskEVENT_LIST_ITEM_VALUE_IN_USE definition. */ -#if configUSE_16_BIT_TICKS == 1 - #define eventCLEAR_EVENTS_ON_EXIT_BIT 0x0100U - #define eventUNBLOCKED_DUE_TO_BIT_SET 0x0200U - #define eventWAIT_FOR_ALL_BITS 0x0400U - #define eventEVENT_BITS_CONTROL_BYTES 0xff00U -#else - #define eventCLEAR_EVENTS_ON_EXIT_BIT 0x01000000UL - #define eventUNBLOCKED_DUE_TO_BIT_SET 0x02000000UL - #define eventWAIT_FOR_ALL_BITS 0x04000000UL - #define eventEVENT_BITS_CONTROL_BYTES 0xff000000UL -#endif - -typedef struct xEventGroupDefinition -{ - EventBits_t uxEventBits; - List_t xTasksWaitingForBits; /*< List of tasks waiting for a bit to be set. */ - - #if( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxEventGroupNumber; - #endif - - #if( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) - uint8_t ucStaticallyAllocated; /*< Set to pdTRUE if the event group is statically allocated to ensure no attempt is made to free the memory. */ - #endif -} EventGroup_t; - -/*-----------------------------------------------------------*/ - -/* - * Test the bits set in uxCurrentEventBits to see if the wait condition is met. - * The wait condition is defined by xWaitForAllBits. If xWaitForAllBits is - * pdTRUE then the wait condition is met if all the bits set in uxBitsToWaitFor - * are also set in uxCurrentEventBits. If xWaitForAllBits is pdFALSE then the - * wait condition is met if any of the bits set in uxBitsToWait for are also set - * in uxCurrentEventBits. - */ -static BaseType_t prvTestWaitCondition( const EventBits_t uxCurrentEventBits, const EventBits_t uxBitsToWaitFor, const BaseType_t xWaitForAllBits ) PRIVILEGED_FUNCTION; - -/*-----------------------------------------------------------*/ - -#if( configSUPPORT_STATIC_ALLOCATION == 1 ) - - EventGroupHandle_t xEventGroupCreateStatic( StaticEventGroup_t *pxEventGroupBuffer ) - { - EventGroup_t *pxEventBits; - - /* A StaticEventGroup_t object must be provided. */ - configASSERT( pxEventGroupBuffer ); - - #if( configASSERT_DEFINED == 1 ) - { - /* Sanity check that the size of the structure used to declare a - variable of type StaticEventGroup_t equals the size of the real - event group structure. */ - volatile size_t xSize = sizeof( StaticEventGroup_t ); - configASSERT( xSize == sizeof( EventGroup_t ) ); - } - #endif /* configASSERT_DEFINED */ - - /* The user has provided a statically allocated event group - use it. */ - pxEventBits = ( EventGroup_t * ) pxEventGroupBuffer; /*lint !e740 EventGroup_t and StaticEventGroup_t are guaranteed to have the same size and alignment requirement - checked by configASSERT(). */ - - if( pxEventBits != NULL ) - { - pxEventBits->uxEventBits = 0; - vListInitialise( &( pxEventBits->xTasksWaitingForBits ) ); - - #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - { - /* Both static and dynamic allocation can be used, so note that - this event group was created statically in case the event group - is later deleted. */ - pxEventBits->ucStaticallyAllocated = pdTRUE; - } - #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ - - traceEVENT_GROUP_CREATE( pxEventBits ); - } - else - { - traceEVENT_GROUP_CREATE_FAILED(); - } - - return ( EventGroupHandle_t ) pxEventBits; - } - -#endif /* configSUPPORT_STATIC_ALLOCATION */ -/*-----------------------------------------------------------*/ - -#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - - EventGroupHandle_t xEventGroupCreate( void ) - { - EventGroup_t *pxEventBits; - - /* Allocate the event group. */ - pxEventBits = ( EventGroup_t * ) pvPortMalloc( sizeof( EventGroup_t ) ); - - if( pxEventBits != NULL ) - { - pxEventBits->uxEventBits = 0; - vListInitialise( &( pxEventBits->xTasksWaitingForBits ) ); - - #if( configSUPPORT_STATIC_ALLOCATION == 1 ) - { - /* Both static and dynamic allocation can be used, so note this - event group was allocated statically in case the event group is - later deleted. */ - pxEventBits->ucStaticallyAllocated = pdFALSE; - } - #endif /* configSUPPORT_STATIC_ALLOCATION */ - - traceEVENT_GROUP_CREATE( pxEventBits ); - } - else - { - traceEVENT_GROUP_CREATE_FAILED(); - } - - return ( EventGroupHandle_t ) pxEventBits; - } - -#endif /* configSUPPORT_DYNAMIC_ALLOCATION */ -/*-----------------------------------------------------------*/ - -EventBits_t xEventGroupSync( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet, const EventBits_t uxBitsToWaitFor, TickType_t xTicksToWait ) -{ -EventBits_t uxOriginalBitValue, uxReturn; -EventGroup_t *pxEventBits = ( EventGroup_t * ) xEventGroup; -BaseType_t xAlreadyYielded; -BaseType_t xTimeoutOccurred = pdFALSE; - - configASSERT( ( uxBitsToWaitFor & eventEVENT_BITS_CONTROL_BYTES ) == 0 ); - configASSERT( uxBitsToWaitFor != 0 ); - #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) - { - configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); - } - #endif - - vTaskSuspendAll(); - { - uxOriginalBitValue = pxEventBits->uxEventBits; - - ( void ) xEventGroupSetBits( xEventGroup, uxBitsToSet ); - - if( ( ( uxOriginalBitValue | uxBitsToSet ) & uxBitsToWaitFor ) == uxBitsToWaitFor ) - { - /* All the rendezvous bits are now set - no need to block. */ - uxReturn = ( uxOriginalBitValue | uxBitsToSet ); - - /* Rendezvous always clear the bits. They will have been cleared - already unless this is the only task in the rendezvous. */ - pxEventBits->uxEventBits &= ~uxBitsToWaitFor; - - xTicksToWait = 0; - } - else - { - if( xTicksToWait != ( TickType_t ) 0 ) - { - traceEVENT_GROUP_SYNC_BLOCK( xEventGroup, uxBitsToSet, uxBitsToWaitFor ); - - /* Store the bits that the calling task is waiting for in the - task's event list item so the kernel knows when a match is - found. Then enter the blocked state. */ - vTaskPlaceOnUnorderedEventList( &( pxEventBits->xTasksWaitingForBits ), ( uxBitsToWaitFor | eventCLEAR_EVENTS_ON_EXIT_BIT | eventWAIT_FOR_ALL_BITS ), xTicksToWait ); - - /* This assignment is obsolete as uxReturn will get set after - the task unblocks, but some compilers mistakenly generate a - warning about uxReturn being returned without being set if the - assignment is omitted. */ - uxReturn = 0; - } - else - { - /* The rendezvous bits were not set, but no block time was - specified - just return the current event bit value. */ - uxReturn = pxEventBits->uxEventBits; - xTimeoutOccurred = pdTRUE; - } - } - } - xAlreadyYielded = xTaskResumeAll(); - - if( xTicksToWait != ( TickType_t ) 0 ) - { - if( xAlreadyYielded == pdFALSE ) - { - portYIELD_WITHIN_API(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - /* The task blocked to wait for its required bits to be set - at this - point either the required bits were set or the block time expired. If - the required bits were set they will have been stored in the task's - event list item, and they should now be retrieved then cleared. */ - uxReturn = uxTaskResetEventItemValue(); - - if( ( uxReturn & eventUNBLOCKED_DUE_TO_BIT_SET ) == ( EventBits_t ) 0 ) - { - /* The task timed out, just return the current event bit value. */ - taskENTER_CRITICAL(); - { - uxReturn = pxEventBits->uxEventBits; - - /* Although the task got here because it timed out before the - bits it was waiting for were set, it is possible that since it - unblocked another task has set the bits. If this is the case - then it needs to clear the bits before exiting. */ - if( ( uxReturn & uxBitsToWaitFor ) == uxBitsToWaitFor ) - { - pxEventBits->uxEventBits &= ~uxBitsToWaitFor; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - taskEXIT_CRITICAL(); - - xTimeoutOccurred = pdTRUE; - } - else - { - /* The task unblocked because the bits were set. */ - } - - /* Control bits might be set as the task had blocked should not be - returned. */ - uxReturn &= ~eventEVENT_BITS_CONTROL_BYTES; - } - - traceEVENT_GROUP_SYNC_END( xEventGroup, uxBitsToSet, uxBitsToWaitFor, xTimeoutOccurred ); - - /* Prevent compiler warnings when trace macros are not used. */ - ( void ) xTimeoutOccurred; - - return uxReturn; -} -/*-----------------------------------------------------------*/ - -EventBits_t xEventGroupWaitBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToWaitFor, const BaseType_t xClearOnExit, const BaseType_t xWaitForAllBits, TickType_t xTicksToWait ) -{ -EventGroup_t *pxEventBits = ( EventGroup_t * ) xEventGroup; -EventBits_t uxReturn, uxControlBits = 0; -BaseType_t xWaitConditionMet, xAlreadyYielded; -BaseType_t xTimeoutOccurred = pdFALSE; - - /* Check the user is not attempting to wait on the bits used by the kernel - itself, and that at least one bit is being requested. */ - configASSERT( xEventGroup ); - configASSERT( ( uxBitsToWaitFor & eventEVENT_BITS_CONTROL_BYTES ) == 0 ); - configASSERT( uxBitsToWaitFor != 0 ); - #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) - { - configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); - } - #endif - - vTaskSuspendAll(); - { - const EventBits_t uxCurrentEventBits = pxEventBits->uxEventBits; - - /* Check to see if the wait condition is already met or not. */ - xWaitConditionMet = prvTestWaitCondition( uxCurrentEventBits, uxBitsToWaitFor, xWaitForAllBits ); - - if( xWaitConditionMet != pdFALSE ) - { - /* The wait condition has already been met so there is no need to - block. */ - uxReturn = uxCurrentEventBits; - xTicksToWait = ( TickType_t ) 0; - - /* Clear the wait bits if requested to do so. */ - if( xClearOnExit != pdFALSE ) - { - pxEventBits->uxEventBits &= ~uxBitsToWaitFor; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else if( xTicksToWait == ( TickType_t ) 0 ) - { - /* The wait condition has not been met, but no block time was - specified, so just return the current value. */ - uxReturn = uxCurrentEventBits; - xTimeoutOccurred = pdTRUE; - } - else - { - /* The task is going to block to wait for its required bits to be - set. uxControlBits are used to remember the specified behaviour of - this call to xEventGroupWaitBits() - for use when the event bits - unblock the task. */ - if( xClearOnExit != pdFALSE ) - { - uxControlBits |= eventCLEAR_EVENTS_ON_EXIT_BIT; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - if( xWaitForAllBits != pdFALSE ) - { - uxControlBits |= eventWAIT_FOR_ALL_BITS; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - /* Store the bits that the calling task is waiting for in the - task's event list item so the kernel knows when a match is - found. Then enter the blocked state. */ - vTaskPlaceOnUnorderedEventList( &( pxEventBits->xTasksWaitingForBits ), ( uxBitsToWaitFor | uxControlBits ), xTicksToWait ); - - /* This is obsolete as it will get set after the task unblocks, but - some compilers mistakenly generate a warning about the variable - being returned without being set if it is not done. */ - uxReturn = 0; - - traceEVENT_GROUP_WAIT_BITS_BLOCK( xEventGroup, uxBitsToWaitFor ); - } - } - xAlreadyYielded = xTaskResumeAll(); - - if( xTicksToWait != ( TickType_t ) 0 ) - { - if( xAlreadyYielded == pdFALSE ) - { - portYIELD_WITHIN_API(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - /* The task blocked to wait for its required bits to be set - at this - point either the required bits were set or the block time expired. If - the required bits were set they will have been stored in the task's - event list item, and they should now be retrieved then cleared. */ - uxReturn = uxTaskResetEventItemValue(); - - if( ( uxReturn & eventUNBLOCKED_DUE_TO_BIT_SET ) == ( EventBits_t ) 0 ) - { - taskENTER_CRITICAL(); - { - /* The task timed out, just return the current event bit value. */ - uxReturn = pxEventBits->uxEventBits; - - /* It is possible that the event bits were updated between this - task leaving the Blocked state and running again. */ - if( prvTestWaitCondition( uxReturn, uxBitsToWaitFor, xWaitForAllBits ) != pdFALSE ) - { - if( xClearOnExit != pdFALSE ) - { - pxEventBits->uxEventBits &= ~uxBitsToWaitFor; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - xTimeoutOccurred = pdTRUE; - } - taskEXIT_CRITICAL(); - } - else - { - /* The task unblocked because the bits were set. */ - } - - /* The task blocked so control bits may have been set. */ - uxReturn &= ~eventEVENT_BITS_CONTROL_BYTES; - } - traceEVENT_GROUP_WAIT_BITS_END( xEventGroup, uxBitsToWaitFor, xTimeoutOccurred ); - - /* Prevent compiler warnings when trace macros are not used. */ - ( void ) xTimeoutOccurred; - - return uxReturn; -} -/*-----------------------------------------------------------*/ - -EventBits_t xEventGroupClearBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToClear ) -{ -EventGroup_t *pxEventBits = ( EventGroup_t * ) xEventGroup; -EventBits_t uxReturn; - - /* Check the user is not attempting to clear the bits used by the kernel - itself. */ - configASSERT( xEventGroup ); - configASSERT( ( uxBitsToClear & eventEVENT_BITS_CONTROL_BYTES ) == 0 ); - - taskENTER_CRITICAL(); - { - traceEVENT_GROUP_CLEAR_BITS( xEventGroup, uxBitsToClear ); - - /* The value returned is the event group value prior to the bits being - cleared. */ - uxReturn = pxEventBits->uxEventBits; - - /* Clear the bits. */ - pxEventBits->uxEventBits &= ~uxBitsToClear; - } - taskEXIT_CRITICAL(); - - return uxReturn; -} -/*-----------------------------------------------------------*/ - -#if ( ( configUSE_TRACE_FACILITY == 1 ) && ( INCLUDE_xTimerPendFunctionCall == 1 ) && ( configUSE_TIMERS == 1 ) ) - - BaseType_t xEventGroupClearBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToClear ) - { - BaseType_t xReturn; - - traceEVENT_GROUP_CLEAR_BITS_FROM_ISR( xEventGroup, uxBitsToClear ); - xReturn = xTimerPendFunctionCallFromISR( vEventGroupClearBitsCallback, ( void * ) xEventGroup, ( uint32_t ) uxBitsToClear, NULL ); - - return xReturn; - } - -#endif -/*-----------------------------------------------------------*/ - -EventBits_t xEventGroupGetBitsFromISR( EventGroupHandle_t xEventGroup ) -{ -UBaseType_t uxSavedInterruptStatus; -EventGroup_t *pxEventBits = ( EventGroup_t * ) xEventGroup; -EventBits_t uxReturn; - - uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); - { - uxReturn = pxEventBits->uxEventBits; - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - - return uxReturn; -} -/*-----------------------------------------------------------*/ - -EventBits_t xEventGroupSetBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet ) -{ -ListItem_t *pxListItem, *pxNext; -ListItem_t const *pxListEnd; -List_t *pxList; -EventBits_t uxBitsToClear = 0, uxBitsWaitedFor, uxControlBits; -EventGroup_t *pxEventBits = ( EventGroup_t * ) xEventGroup; -BaseType_t xMatchFound = pdFALSE; - - /* Check the user is not attempting to set the bits used by the kernel - itself. */ - configASSERT( xEventGroup ); - configASSERT( ( uxBitsToSet & eventEVENT_BITS_CONTROL_BYTES ) == 0 ); - - pxList = &( pxEventBits->xTasksWaitingForBits ); - pxListEnd = listGET_END_MARKER( pxList ); /*lint !e826 !e740 The mini list structure is used as the list end to save RAM. This is checked and valid. */ - vTaskSuspendAll(); - { - traceEVENT_GROUP_SET_BITS( xEventGroup, uxBitsToSet ); - - pxListItem = listGET_HEAD_ENTRY( pxList ); - - /* Set the bits. */ - pxEventBits->uxEventBits |= uxBitsToSet; - - /* See if the new bit value should unblock any tasks. */ - while( pxListItem != pxListEnd ) - { - pxNext = listGET_NEXT( pxListItem ); - uxBitsWaitedFor = listGET_LIST_ITEM_VALUE( pxListItem ); - xMatchFound = pdFALSE; - - /* Split the bits waited for from the control bits. */ - uxControlBits = uxBitsWaitedFor & eventEVENT_BITS_CONTROL_BYTES; - uxBitsWaitedFor &= ~eventEVENT_BITS_CONTROL_BYTES; - - if( ( uxControlBits & eventWAIT_FOR_ALL_BITS ) == ( EventBits_t ) 0 ) - { - /* Just looking for single bit being set. */ - if( ( uxBitsWaitedFor & pxEventBits->uxEventBits ) != ( EventBits_t ) 0 ) - { - xMatchFound = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else if( ( uxBitsWaitedFor & pxEventBits->uxEventBits ) == uxBitsWaitedFor ) - { - /* All bits are set. */ - xMatchFound = pdTRUE; - } - else - { - /* Need all bits to be set, but not all the bits were set. */ - } - - if( xMatchFound != pdFALSE ) - { - /* The bits match. Should the bits be cleared on exit? */ - if( ( uxControlBits & eventCLEAR_EVENTS_ON_EXIT_BIT ) != ( EventBits_t ) 0 ) - { - uxBitsToClear |= uxBitsWaitedFor; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - /* Store the actual event flag value in the task's event list - item before removing the task from the event list. The - eventUNBLOCKED_DUE_TO_BIT_SET bit is set so the task knows - that is was unblocked due to its required bits matching, rather - than because it timed out. */ - vTaskRemoveFromUnorderedEventList( pxListItem, pxEventBits->uxEventBits | eventUNBLOCKED_DUE_TO_BIT_SET ); - } - - /* Move onto the next list item. Note pxListItem->pxNext is not - used here as the list item may have been removed from the event list - and inserted into the ready/pending reading list. */ - pxListItem = pxNext; - } - - /* Clear any bits that matched when the eventCLEAR_EVENTS_ON_EXIT_BIT - bit was set in the control word. */ - pxEventBits->uxEventBits &= ~uxBitsToClear; - } - ( void ) xTaskResumeAll(); - - return pxEventBits->uxEventBits; -} -/*-----------------------------------------------------------*/ - -void vEventGroupDelete( EventGroupHandle_t xEventGroup ) -{ -EventGroup_t *pxEventBits = ( EventGroup_t * ) xEventGroup; -const List_t *pxTasksWaitingForBits = &( pxEventBits->xTasksWaitingForBits ); - - vTaskSuspendAll(); - { - traceEVENT_GROUP_DELETE( xEventGroup ); - - while( listCURRENT_LIST_LENGTH( pxTasksWaitingForBits ) > ( UBaseType_t ) 0 ) - { - /* Unblock the task, returning 0 as the event list is being deleted - and cannot therefore have any bits set. */ - configASSERT( pxTasksWaitingForBits->xListEnd.pxNext != ( const ListItem_t * ) &( pxTasksWaitingForBits->xListEnd ) ); - vTaskRemoveFromUnorderedEventList( pxTasksWaitingForBits->xListEnd.pxNext, eventUNBLOCKED_DUE_TO_BIT_SET ); - } - - #if( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 0 ) ) - { - /* The event group can only have been allocated dynamically - free - it again. */ - vPortFree( pxEventBits ); - } - #elif( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) - { - /* The event group could have been allocated statically or - dynamically, so check before attempting to free the memory. */ - if( pxEventBits->ucStaticallyAllocated == ( uint8_t ) pdFALSE ) - { - vPortFree( pxEventBits ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ - } - ( void ) xTaskResumeAll(); -} -/*-----------------------------------------------------------*/ - -/* For internal use only - execute a 'set bits' command that was pended from -an interrupt. */ -void vEventGroupSetBitsCallback( void *pvEventGroup, const uint32_t ulBitsToSet ) -{ - ( void ) xEventGroupSetBits( pvEventGroup, ( EventBits_t ) ulBitsToSet ); -} -/*-----------------------------------------------------------*/ - -/* For internal use only - execute a 'clear bits' command that was pended from -an interrupt. */ -void vEventGroupClearBitsCallback( void *pvEventGroup, const uint32_t ulBitsToClear ) -{ - ( void ) xEventGroupClearBits( pvEventGroup, ( EventBits_t ) ulBitsToClear ); -} -/*-----------------------------------------------------------*/ - -static BaseType_t prvTestWaitCondition( const EventBits_t uxCurrentEventBits, const EventBits_t uxBitsToWaitFor, const BaseType_t xWaitForAllBits ) -{ -BaseType_t xWaitConditionMet = pdFALSE; - - if( xWaitForAllBits == pdFALSE ) - { - /* Task only has to wait for one bit within uxBitsToWaitFor to be - set. Is one already set? */ - if( ( uxCurrentEventBits & uxBitsToWaitFor ) != ( EventBits_t ) 0 ) - { - xWaitConditionMet = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* Task has to wait for all the bits in uxBitsToWaitFor to be set. - Are they set already? */ - if( ( uxCurrentEventBits & uxBitsToWaitFor ) == uxBitsToWaitFor ) - { - xWaitConditionMet = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - - return xWaitConditionMet; -} -/*-----------------------------------------------------------*/ - -#if ( ( configUSE_TRACE_FACILITY == 1 ) && ( INCLUDE_xTimerPendFunctionCall == 1 ) && ( configUSE_TIMERS == 1 ) ) - - BaseType_t xEventGroupSetBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet, BaseType_t *pxHigherPriorityTaskWoken ) - { - BaseType_t xReturn; - - traceEVENT_GROUP_SET_BITS_FROM_ISR( xEventGroup, uxBitsToSet ); - xReturn = xTimerPendFunctionCallFromISR( vEventGroupSetBitsCallback, ( void * ) xEventGroup, ( uint32_t ) uxBitsToSet, pxHigherPriorityTaskWoken ); - - return xReturn; - } - -#endif -/*-----------------------------------------------------------*/ - -#if (configUSE_TRACE_FACILITY == 1) - - UBaseType_t uxEventGroupGetNumber( void* xEventGroup ) - { - UBaseType_t xReturn; - EventGroup_t *pxEventBits = ( EventGroup_t * ) xEventGroup; - - if( xEventGroup == NULL ) - { - xReturn = 0; - } - else - { - xReturn = pxEventBits->uxEventGroupNumber; - } - - return xReturn; - } - -#endif /* configUSE_TRACE_FACILITY */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_TRACE_FACILITY == 1 ) - - void vEventGroupSetNumber( void * xEventGroup, UBaseType_t uxEventGroupNumber ) - { - ( ( EventGroup_t * ) xEventGroup )->uxEventGroupNumber = uxEventGroupNumber; - } - -#endif /* configUSE_TRACE_FACILITY */ -/*-----------------------------------------------------------*/ - - diff --git a/lib/FreeRTOS/Source/include/FreeRTOS.h b/lib/FreeRTOS/Source/include/FreeRTOS.h deleted file mode 100644 index 78d176a0..00000000 --- a/lib/FreeRTOS/Source/include/FreeRTOS.h +++ /dev/null @@ -1,1168 +0,0 @@ -/* - * FreeRTOS Kernel V10.0.1 - * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * 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. - * - * http://www.FreeRTOS.org - * http://aws.amazon.com/freertos - * - * 1 tab == 4 spaces! - */ - -#ifndef INC_FREERTOS_H -#define INC_FREERTOS_H - -/* - * Include the generic headers required for the FreeRTOS port being used. - */ -#include - -/* - * If stdint.h cannot be located then: - * + If using GCC ensure the -nostdint options is *not* being used. - * + Ensure the project's include path includes the directory in which your - * compiler stores stdint.h. - * + Set any compiler options necessary for it to support C99, as technically - * stdint.h is only mandatory with C99 (FreeRTOS does not require C99 in any - * other way). - * + The FreeRTOS download includes a simple stdint.h definition that can be - * used in cases where none is provided by the compiler. The files only - * contains the typedefs required to build FreeRTOS. Read the instructions - * in FreeRTOS/source/stdint.readme for more information. - */ -#include /* READ COMMENT ABOVE. */ - -#ifdef __cplusplus -extern "C" { -#endif - -/* Application specific configuration options. */ -#include "FreeRTOSConfig.h" - -/* Basic FreeRTOS definitions. */ -#include "projdefs.h" - -/* Definitions specific to the port being used. */ -#include "portable.h" - -/* Must be defaulted before configUSE_NEWLIB_REENTRANT is used below. */ -#ifndef configUSE_NEWLIB_REENTRANT - #define configUSE_NEWLIB_REENTRANT 0 -#endif - -/* Required if struct _reent is used. */ -#if ( configUSE_NEWLIB_REENTRANT == 1 ) - #include -#endif -/* - * Check all the required application specific macros have been defined. - * These macros are application specific and (as downloaded) are defined - * within FreeRTOSConfig.h. - */ - -#ifndef configMINIMAL_STACK_SIZE - #error Missing definition: configMINIMAL_STACK_SIZE must be defined in FreeRTOSConfig.h. configMINIMAL_STACK_SIZE defines the size (in words) of the stack allocated to the idle task. Refer to the demo project provided for your port for a suitable value. -#endif - -#ifndef configMAX_PRIORITIES - #error Missing definition: configMAX_PRIORITIES must be defined in FreeRTOSConfig.h. See the Configuration section of the FreeRTOS API documentation for details. -#endif - -#if configMAX_PRIORITIES < 1 - #error configMAX_PRIORITIES must be defined to be greater than or equal to 1. -#endif - -#ifndef configUSE_PREEMPTION - #error Missing definition: configUSE_PREEMPTION must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. -#endif - -#ifndef configUSE_IDLE_HOOK - #error Missing definition: configUSE_IDLE_HOOK must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. -#endif - -#ifndef configUSE_TICK_HOOK - #error Missing definition: configUSE_TICK_HOOK must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. -#endif - -#ifndef configUSE_16_BIT_TICKS - #error Missing definition: configUSE_16_BIT_TICKS must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. -#endif - -#ifndef configUSE_CO_ROUTINES - #define configUSE_CO_ROUTINES 0 -#endif - -#ifndef INCLUDE_vTaskPrioritySet - #define INCLUDE_vTaskPrioritySet 0 -#endif - -#ifndef INCLUDE_uxTaskPriorityGet - #define INCLUDE_uxTaskPriorityGet 0 -#endif - -#ifndef INCLUDE_vTaskDelete - #define INCLUDE_vTaskDelete 0 -#endif - -#ifndef INCLUDE_vTaskSuspend - #define INCLUDE_vTaskSuspend 0 -#endif - -#ifndef INCLUDE_vTaskDelayUntil - #define INCLUDE_vTaskDelayUntil 0 -#endif - -#ifndef INCLUDE_vTaskDelay - #define INCLUDE_vTaskDelay 0 -#endif - -#ifndef INCLUDE_xTaskGetIdleTaskHandle - #define INCLUDE_xTaskGetIdleTaskHandle 0 -#endif - -#ifndef INCLUDE_xTaskAbortDelay - #define INCLUDE_xTaskAbortDelay 0 -#endif - -#ifndef INCLUDE_xQueueGetMutexHolder - #define INCLUDE_xQueueGetMutexHolder 0 -#endif - -#ifndef INCLUDE_xSemaphoreGetMutexHolder - #define INCLUDE_xSemaphoreGetMutexHolder INCLUDE_xQueueGetMutexHolder -#endif - -#ifndef INCLUDE_xTaskGetHandle - #define INCLUDE_xTaskGetHandle 0 -#endif - -#ifndef INCLUDE_uxTaskGetStackHighWaterMark - #define INCLUDE_uxTaskGetStackHighWaterMark 0 -#endif - -#ifndef INCLUDE_eTaskGetState - #define INCLUDE_eTaskGetState 0 -#endif - -#ifndef INCLUDE_xTaskResumeFromISR - #define INCLUDE_xTaskResumeFromISR 1 -#endif - -#ifndef INCLUDE_xTimerPendFunctionCall - #define INCLUDE_xTimerPendFunctionCall 0 -#endif - -#ifndef INCLUDE_xTaskGetSchedulerState - #define INCLUDE_xTaskGetSchedulerState 0 -#endif - -#ifndef INCLUDE_xTaskGetCurrentTaskHandle - #define INCLUDE_xTaskGetCurrentTaskHandle 0 -#endif - -#if configUSE_CO_ROUTINES != 0 - #ifndef configMAX_CO_ROUTINE_PRIORITIES - #error configMAX_CO_ROUTINE_PRIORITIES must be greater than or equal to 1. - #endif -#endif - -#ifndef configUSE_DAEMON_TASK_STARTUP_HOOK - #define configUSE_DAEMON_TASK_STARTUP_HOOK 0 -#endif - -#ifndef configUSE_APPLICATION_TASK_TAG - #define configUSE_APPLICATION_TASK_TAG 0 -#endif - -#ifndef configNUM_THREAD_LOCAL_STORAGE_POINTERS - #define configNUM_THREAD_LOCAL_STORAGE_POINTERS 0 -#endif - -#ifndef configUSE_RECURSIVE_MUTEXES - #define configUSE_RECURSIVE_MUTEXES 0 -#endif - -#ifndef configUSE_MUTEXES - #define configUSE_MUTEXES 0 -#endif - -#ifndef configUSE_TIMERS - #define configUSE_TIMERS 0 -#endif - -#ifndef configUSE_COUNTING_SEMAPHORES - #define configUSE_COUNTING_SEMAPHORES 0 -#endif - -#ifndef configUSE_ALTERNATIVE_API - #define configUSE_ALTERNATIVE_API 0 -#endif - -#ifndef portCRITICAL_NESTING_IN_TCB - #define portCRITICAL_NESTING_IN_TCB 0 -#endif - -#ifndef configMAX_TASK_NAME_LEN - #define configMAX_TASK_NAME_LEN 16 -#endif - -#ifndef configIDLE_SHOULD_YIELD - #define configIDLE_SHOULD_YIELD 1 -#endif - -#if configMAX_TASK_NAME_LEN < 1 - #error configMAX_TASK_NAME_LEN must be set to a minimum of 1 in FreeRTOSConfig.h -#endif - -#ifndef configASSERT - #define configASSERT( x ) - #define configASSERT_DEFINED 0 -#else - #define configASSERT_DEFINED 1 -#endif - -/* The timers module relies on xTaskGetSchedulerState(). */ -#if configUSE_TIMERS == 1 - - #ifndef configTIMER_TASK_PRIORITY - #error If configUSE_TIMERS is set to 1 then configTIMER_TASK_PRIORITY must also be defined. - #endif /* configTIMER_TASK_PRIORITY */ - - #ifndef configTIMER_QUEUE_LENGTH - #error If configUSE_TIMERS is set to 1 then configTIMER_QUEUE_LENGTH must also be defined. - #endif /* configTIMER_QUEUE_LENGTH */ - - #ifndef configTIMER_TASK_STACK_DEPTH - #error If configUSE_TIMERS is set to 1 then configTIMER_TASK_STACK_DEPTH must also be defined. - #endif /* configTIMER_TASK_STACK_DEPTH */ - -#endif /* configUSE_TIMERS */ - -#ifndef portSET_INTERRUPT_MASK_FROM_ISR - #define portSET_INTERRUPT_MASK_FROM_ISR() 0 -#endif - -#ifndef portCLEAR_INTERRUPT_MASK_FROM_ISR - #define portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedStatusValue ) ( void ) uxSavedStatusValue -#endif - -#ifndef portCLEAN_UP_TCB - #define portCLEAN_UP_TCB( pxTCB ) ( void ) pxTCB -#endif - -#ifndef portPRE_TASK_DELETE_HOOK - #define portPRE_TASK_DELETE_HOOK( pvTaskToDelete, pxYieldPending ) -#endif - -#ifndef portSETUP_TCB - #define portSETUP_TCB( pxTCB ) ( void ) pxTCB -#endif - -#ifndef configQUEUE_REGISTRY_SIZE - #define configQUEUE_REGISTRY_SIZE 0U -#endif - -#if ( configQUEUE_REGISTRY_SIZE < 1 ) - #define vQueueAddToRegistry( xQueue, pcName ) - #define vQueueUnregisterQueue( xQueue ) - #define pcQueueGetName( xQueue ) -#endif - -#ifndef portPOINTER_SIZE_TYPE - #define portPOINTER_SIZE_TYPE uint32_t -#endif - -/* Remove any unused trace macros. */ -#ifndef traceSTART - /* Used to perform any necessary initialisation - for example, open a file - into which trace is to be written. */ - #define traceSTART() -#endif - -#ifndef traceEND - /* Use to close a trace, for example close a file into which trace has been - written. */ - #define traceEND() -#endif - -#ifndef traceTASK_SWITCHED_IN - /* Called after a task has been selected to run. pxCurrentTCB holds a pointer - to the task control block of the selected task. */ - #define traceTASK_SWITCHED_IN() -#endif - -#ifndef traceINCREASE_TICK_COUNT - /* Called before stepping the tick count after waking from tickless idle - sleep. */ - #define traceINCREASE_TICK_COUNT( x ) -#endif - -#ifndef traceLOW_POWER_IDLE_BEGIN - /* Called immediately before entering tickless idle. */ - #define traceLOW_POWER_IDLE_BEGIN() -#endif - -#ifndef traceLOW_POWER_IDLE_END - /* Called when returning to the Idle task after a tickless idle. */ - #define traceLOW_POWER_IDLE_END() -#endif - -#ifndef traceTASK_SWITCHED_OUT - /* Called before a task has been selected to run. pxCurrentTCB holds a pointer - to the task control block of the task being switched out. */ - #define traceTASK_SWITCHED_OUT() -#endif - -#ifndef traceTASK_PRIORITY_INHERIT - /* Called when a task attempts to take a mutex that is already held by a - lower priority task. pxTCBOfMutexHolder is a pointer to the TCB of the task - that holds the mutex. uxInheritedPriority is the priority the mutex holder - will inherit (the priority of the task that is attempting to obtain the - muted. */ - #define traceTASK_PRIORITY_INHERIT( pxTCBOfMutexHolder, uxInheritedPriority ) -#endif - -#ifndef traceTASK_PRIORITY_DISINHERIT - /* Called when a task releases a mutex, the holding of which had resulted in - the task inheriting the priority of a higher priority task. - pxTCBOfMutexHolder is a pointer to the TCB of the task that is releasing the - mutex. uxOriginalPriority is the task's configured (base) priority. */ - #define traceTASK_PRIORITY_DISINHERIT( pxTCBOfMutexHolder, uxOriginalPriority ) -#endif - -#ifndef traceBLOCKING_ON_QUEUE_RECEIVE - /* Task is about to block because it cannot read from a - queue/mutex/semaphore. pxQueue is a pointer to the queue/mutex/semaphore - upon which the read was attempted. pxCurrentTCB points to the TCB of the - task that attempted the read. */ - #define traceBLOCKING_ON_QUEUE_RECEIVE( pxQueue ) -#endif - -#ifndef traceBLOCKING_ON_QUEUE_PEEK - /* Task is about to block because it cannot read from a - queue/mutex/semaphore. pxQueue is a pointer to the queue/mutex/semaphore - upon which the read was attempted. pxCurrentTCB points to the TCB of the - task that attempted the read. */ - #define traceBLOCKING_ON_QUEUE_PEEK( pxQueue ) -#endif - -#ifndef traceBLOCKING_ON_QUEUE_SEND - /* Task is about to block because it cannot write to a - queue/mutex/semaphore. pxQueue is a pointer to the queue/mutex/semaphore - upon which the write was attempted. pxCurrentTCB points to the TCB of the - task that attempted the write. */ - #define traceBLOCKING_ON_QUEUE_SEND( pxQueue ) -#endif - -#ifndef configCHECK_FOR_STACK_OVERFLOW - #define configCHECK_FOR_STACK_OVERFLOW 0 -#endif - -#ifndef configRECORD_STACK_HIGH_ADDRESS - #define configRECORD_STACK_HIGH_ADDRESS 0 -#endif - -#ifndef configINCLUDE_FREERTOS_TASK_C_ADDITIONS_H - #define configINCLUDE_FREERTOS_TASK_C_ADDITIONS_H 0 -#endif - -/* The following event macros are embedded in the kernel API calls. */ - -#ifndef traceMOVED_TASK_TO_READY_STATE - #define traceMOVED_TASK_TO_READY_STATE( pxTCB ) -#endif - -#ifndef tracePOST_MOVED_TASK_TO_READY_STATE - #define tracePOST_MOVED_TASK_TO_READY_STATE( pxTCB ) -#endif - -#ifndef traceQUEUE_CREATE - #define traceQUEUE_CREATE( pxNewQueue ) -#endif - -#ifndef traceQUEUE_CREATE_FAILED - #define traceQUEUE_CREATE_FAILED( ucQueueType ) -#endif - -#ifndef traceCREATE_MUTEX - #define traceCREATE_MUTEX( pxNewQueue ) -#endif - -#ifndef traceCREATE_MUTEX_FAILED - #define traceCREATE_MUTEX_FAILED() -#endif - -#ifndef traceGIVE_MUTEX_RECURSIVE - #define traceGIVE_MUTEX_RECURSIVE( pxMutex ) -#endif - -#ifndef traceGIVE_MUTEX_RECURSIVE_FAILED - #define traceGIVE_MUTEX_RECURSIVE_FAILED( pxMutex ) -#endif - -#ifndef traceTAKE_MUTEX_RECURSIVE - #define traceTAKE_MUTEX_RECURSIVE( pxMutex ) -#endif - -#ifndef traceTAKE_MUTEX_RECURSIVE_FAILED - #define traceTAKE_MUTEX_RECURSIVE_FAILED( pxMutex ) -#endif - -#ifndef traceCREATE_COUNTING_SEMAPHORE - #define traceCREATE_COUNTING_SEMAPHORE() -#endif - -#ifndef traceCREATE_COUNTING_SEMAPHORE_FAILED - #define traceCREATE_COUNTING_SEMAPHORE_FAILED() -#endif - -#ifndef traceQUEUE_SEND - #define traceQUEUE_SEND( pxQueue ) -#endif - -#ifndef traceQUEUE_SEND_FAILED - #define traceQUEUE_SEND_FAILED( pxQueue ) -#endif - -#ifndef traceQUEUE_RECEIVE - #define traceQUEUE_RECEIVE( pxQueue ) -#endif - -#ifndef traceQUEUE_PEEK - #define traceQUEUE_PEEK( pxQueue ) -#endif - -#ifndef traceQUEUE_PEEK_FAILED - #define traceQUEUE_PEEK_FAILED( pxQueue ) -#endif - -#ifndef traceQUEUE_PEEK_FROM_ISR - #define traceQUEUE_PEEK_FROM_ISR( pxQueue ) -#endif - -#ifndef traceQUEUE_RECEIVE_FAILED - #define traceQUEUE_RECEIVE_FAILED( pxQueue ) -#endif - -#ifndef traceQUEUE_SEND_FROM_ISR - #define traceQUEUE_SEND_FROM_ISR( pxQueue ) -#endif - -#ifndef traceQUEUE_SEND_FROM_ISR_FAILED - #define traceQUEUE_SEND_FROM_ISR_FAILED( pxQueue ) -#endif - -#ifndef traceQUEUE_RECEIVE_FROM_ISR - #define traceQUEUE_RECEIVE_FROM_ISR( pxQueue ) -#endif - -#ifndef traceQUEUE_RECEIVE_FROM_ISR_FAILED - #define traceQUEUE_RECEIVE_FROM_ISR_FAILED( pxQueue ) -#endif - -#ifndef traceQUEUE_PEEK_FROM_ISR_FAILED - #define traceQUEUE_PEEK_FROM_ISR_FAILED( pxQueue ) -#endif - -#ifndef traceQUEUE_DELETE - #define traceQUEUE_DELETE( pxQueue ) -#endif - -#ifndef traceTASK_CREATE - #define traceTASK_CREATE( pxNewTCB ) -#endif - -#ifndef traceTASK_CREATE_FAILED - #define traceTASK_CREATE_FAILED() -#endif - -#ifndef traceTASK_DELETE - #define traceTASK_DELETE( pxTaskToDelete ) -#endif - -#ifndef traceTASK_DELAY_UNTIL - #define traceTASK_DELAY_UNTIL( x ) -#endif - -#ifndef traceTASK_DELAY - #define traceTASK_DELAY() -#endif - -#ifndef traceTASK_PRIORITY_SET - #define traceTASK_PRIORITY_SET( pxTask, uxNewPriority ) -#endif - -#ifndef traceTASK_SUSPEND - #define traceTASK_SUSPEND( pxTaskToSuspend ) -#endif - -#ifndef traceTASK_RESUME - #define traceTASK_RESUME( pxTaskToResume ) -#endif - -#ifndef traceTASK_RESUME_FROM_ISR - #define traceTASK_RESUME_FROM_ISR( pxTaskToResume ) -#endif - -#ifndef traceTASK_INCREMENT_TICK - #define traceTASK_INCREMENT_TICK( xTickCount ) -#endif - -#ifndef traceTIMER_CREATE - #define traceTIMER_CREATE( pxNewTimer ) -#endif - -#ifndef traceTIMER_CREATE_FAILED - #define traceTIMER_CREATE_FAILED() -#endif - -#ifndef traceTIMER_COMMAND_SEND - #define traceTIMER_COMMAND_SEND( xTimer, xMessageID, xMessageValueValue, xReturn ) -#endif - -#ifndef traceTIMER_EXPIRED - #define traceTIMER_EXPIRED( pxTimer ) -#endif - -#ifndef traceTIMER_COMMAND_RECEIVED - #define traceTIMER_COMMAND_RECEIVED( pxTimer, xMessageID, xMessageValue ) -#endif - -#ifndef traceMALLOC - #define traceMALLOC( pvAddress, uiSize ) -#endif - -#ifndef traceFREE - #define traceFREE( pvAddress, uiSize ) -#endif - -#ifndef traceEVENT_GROUP_CREATE - #define traceEVENT_GROUP_CREATE( xEventGroup ) -#endif - -#ifndef traceEVENT_GROUP_CREATE_FAILED - #define traceEVENT_GROUP_CREATE_FAILED() -#endif - -#ifndef traceEVENT_GROUP_SYNC_BLOCK - #define traceEVENT_GROUP_SYNC_BLOCK( xEventGroup, uxBitsToSet, uxBitsToWaitFor ) -#endif - -#ifndef traceEVENT_GROUP_SYNC_END - #define traceEVENT_GROUP_SYNC_END( xEventGroup, uxBitsToSet, uxBitsToWaitFor, xTimeoutOccurred ) ( void ) xTimeoutOccurred -#endif - -#ifndef traceEVENT_GROUP_WAIT_BITS_BLOCK - #define traceEVENT_GROUP_WAIT_BITS_BLOCK( xEventGroup, uxBitsToWaitFor ) -#endif - -#ifndef traceEVENT_GROUP_WAIT_BITS_END - #define traceEVENT_GROUP_WAIT_BITS_END( xEventGroup, uxBitsToWaitFor, xTimeoutOccurred ) ( void ) xTimeoutOccurred -#endif - -#ifndef traceEVENT_GROUP_CLEAR_BITS - #define traceEVENT_GROUP_CLEAR_BITS( xEventGroup, uxBitsToClear ) -#endif - -#ifndef traceEVENT_GROUP_CLEAR_BITS_FROM_ISR - #define traceEVENT_GROUP_CLEAR_BITS_FROM_ISR( xEventGroup, uxBitsToClear ) -#endif - -#ifndef traceEVENT_GROUP_SET_BITS - #define traceEVENT_GROUP_SET_BITS( xEventGroup, uxBitsToSet ) -#endif - -#ifndef traceEVENT_GROUP_SET_BITS_FROM_ISR - #define traceEVENT_GROUP_SET_BITS_FROM_ISR( xEventGroup, uxBitsToSet ) -#endif - -#ifndef traceEVENT_GROUP_DELETE - #define traceEVENT_GROUP_DELETE( xEventGroup ) -#endif - -#ifndef tracePEND_FUNC_CALL - #define tracePEND_FUNC_CALL(xFunctionToPend, pvParameter1, ulParameter2, ret) -#endif - -#ifndef tracePEND_FUNC_CALL_FROM_ISR - #define tracePEND_FUNC_CALL_FROM_ISR(xFunctionToPend, pvParameter1, ulParameter2, ret) -#endif - -#ifndef traceQUEUE_REGISTRY_ADD - #define traceQUEUE_REGISTRY_ADD(xQueue, pcQueueName) -#endif - -#ifndef traceTASK_NOTIFY_TAKE_BLOCK - #define traceTASK_NOTIFY_TAKE_BLOCK() -#endif - -#ifndef traceTASK_NOTIFY_TAKE - #define traceTASK_NOTIFY_TAKE() -#endif - -#ifndef traceTASK_NOTIFY_WAIT_BLOCK - #define traceTASK_NOTIFY_WAIT_BLOCK() -#endif - -#ifndef traceTASK_NOTIFY_WAIT - #define traceTASK_NOTIFY_WAIT() -#endif - -#ifndef traceTASK_NOTIFY - #define traceTASK_NOTIFY() -#endif - -#ifndef traceTASK_NOTIFY_FROM_ISR - #define traceTASK_NOTIFY_FROM_ISR() -#endif - -#ifndef traceTASK_NOTIFY_GIVE_FROM_ISR - #define traceTASK_NOTIFY_GIVE_FROM_ISR() -#endif - -#ifndef traceSTREAM_BUFFER_CREATE_FAILED - #define traceSTREAM_BUFFER_CREATE_FAILED( xIsMessageBuffer ) -#endif - -#ifndef traceSTREAM_BUFFER_CREATE_STATIC_FAILED - #define traceSTREAM_BUFFER_CREATE_STATIC_FAILED( xReturn, xIsMessageBuffer ) -#endif - -#ifndef traceSTREAM_BUFFER_CREATE - #define traceSTREAM_BUFFER_CREATE( pxStreamBuffer, xIsMessageBuffer ) -#endif - -#ifndef traceSTREAM_BUFFER_DELETE - #define traceSTREAM_BUFFER_DELETE( xStreamBuffer ) -#endif - -#ifndef traceSTREAM_BUFFER_RESET - #define traceSTREAM_BUFFER_RESET( xStreamBuffer ) -#endif - -#ifndef traceBLOCKING_ON_STREAM_BUFFER_SEND - #define traceBLOCKING_ON_STREAM_BUFFER_SEND( xStreamBuffer ) -#endif - -#ifndef traceSTREAM_BUFFER_SEND - #define traceSTREAM_BUFFER_SEND( xStreamBuffer, xBytesSent ) -#endif - -#ifndef traceSTREAM_BUFFER_SEND_FAILED - #define traceSTREAM_BUFFER_SEND_FAILED( xStreamBuffer ) -#endif - -#ifndef traceSTREAM_BUFFER_SEND_FROM_ISR - #define traceSTREAM_BUFFER_SEND_FROM_ISR( xStreamBuffer, xBytesSent ) -#endif - -#ifndef traceBLOCKING_ON_STREAM_BUFFER_RECEIVE - #define traceBLOCKING_ON_STREAM_BUFFER_RECEIVE( xStreamBuffer ) -#endif - -#ifndef traceSTREAM_BUFFER_RECEIVE - #define traceSTREAM_BUFFER_RECEIVE( xStreamBuffer, xReceivedLength ) -#endif - -#ifndef traceSTREAM_BUFFER_RECEIVE_FAILED - #define traceSTREAM_BUFFER_RECEIVE_FAILED( xStreamBuffer ) -#endif - -#ifndef traceSTREAM_BUFFER_RECEIVE_FROM_ISR - #define traceSTREAM_BUFFER_RECEIVE_FROM_ISR( xStreamBuffer, xReceivedLength ) -#endif - -#ifndef configGENERATE_RUN_TIME_STATS - #define configGENERATE_RUN_TIME_STATS 0 -#endif - -#if ( configGENERATE_RUN_TIME_STATS == 1 ) - - #ifndef portCONFIGURE_TIMER_FOR_RUN_TIME_STATS - #error If configGENERATE_RUN_TIME_STATS is defined then portCONFIGURE_TIMER_FOR_RUN_TIME_STATS must also be defined. portCONFIGURE_TIMER_FOR_RUN_TIME_STATS should call a port layer function to setup a peripheral timer/counter that can then be used as the run time counter time base. - #endif /* portCONFIGURE_TIMER_FOR_RUN_TIME_STATS */ - - #ifndef portGET_RUN_TIME_COUNTER_VALUE - #ifndef portALT_GET_RUN_TIME_COUNTER_VALUE - #error If configGENERATE_RUN_TIME_STATS is defined then either portGET_RUN_TIME_COUNTER_VALUE or portALT_GET_RUN_TIME_COUNTER_VALUE must also be defined. See the examples provided and the FreeRTOS web site for more information. - #endif /* portALT_GET_RUN_TIME_COUNTER_VALUE */ - #endif /* portGET_RUN_TIME_COUNTER_VALUE */ - -#endif /* configGENERATE_RUN_TIME_STATS */ - -#ifndef portCONFIGURE_TIMER_FOR_RUN_TIME_STATS - #define portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() -#endif - -#ifndef configUSE_MALLOC_FAILED_HOOK - #define configUSE_MALLOC_FAILED_HOOK 0 -#endif - -#ifndef portPRIVILEGE_BIT - #define portPRIVILEGE_BIT ( ( UBaseType_t ) 0x00 ) -#endif - -#ifndef portYIELD_WITHIN_API - #define portYIELD_WITHIN_API portYIELD -#endif - -#ifndef portSUPPRESS_TICKS_AND_SLEEP - #define portSUPPRESS_TICKS_AND_SLEEP( xExpectedIdleTime ) -#endif - -#ifndef configEXPECTED_IDLE_TIME_BEFORE_SLEEP - #define configEXPECTED_IDLE_TIME_BEFORE_SLEEP 2 -#endif - -#if configEXPECTED_IDLE_TIME_BEFORE_SLEEP < 2 - #error configEXPECTED_IDLE_TIME_BEFORE_SLEEP must not be less than 2 -#endif - -#ifndef configUSE_TICKLESS_IDLE - #define configUSE_TICKLESS_IDLE 0 -#endif - -#ifndef configPRE_SUPPRESS_TICKS_AND_SLEEP_PROCESSING - #define configPRE_SUPPRESS_TICKS_AND_SLEEP_PROCESSING( x ) -#endif - -#ifndef configPRE_SLEEP_PROCESSING - #define configPRE_SLEEP_PROCESSING( x ) -#endif - -#ifndef configPOST_SLEEP_PROCESSING - #define configPOST_SLEEP_PROCESSING( x ) -#endif - -#ifndef configUSE_QUEUE_SETS - #define configUSE_QUEUE_SETS 0 -#endif - -#ifndef portTASK_USES_FLOATING_POINT - #define portTASK_USES_FLOATING_POINT() -#endif - -#ifndef portTASK_CALLS_SECURE_FUNCTIONS - #define portTASK_CALLS_SECURE_FUNCTIONS() -#endif - -#ifndef configUSE_TIME_SLICING - #define configUSE_TIME_SLICING 1 -#endif - -#ifndef configINCLUDE_APPLICATION_DEFINED_PRIVILEGED_FUNCTIONS - #define configINCLUDE_APPLICATION_DEFINED_PRIVILEGED_FUNCTIONS 0 -#endif - -#ifndef configUSE_STATS_FORMATTING_FUNCTIONS - #define configUSE_STATS_FORMATTING_FUNCTIONS 0 -#endif - -#ifndef portASSERT_IF_INTERRUPT_PRIORITY_INVALID - #define portASSERT_IF_INTERRUPT_PRIORITY_INVALID() -#endif - -#ifndef configUSE_TRACE_FACILITY - #define configUSE_TRACE_FACILITY 0 -#endif - -#ifndef mtCOVERAGE_TEST_MARKER - #define mtCOVERAGE_TEST_MARKER() -#endif - -#ifndef mtCOVERAGE_TEST_DELAY - #define mtCOVERAGE_TEST_DELAY() -#endif - -#ifndef portASSERT_IF_IN_ISR - #define portASSERT_IF_IN_ISR() -#endif - -#ifndef configUSE_PORT_OPTIMISED_TASK_SELECTION - #define configUSE_PORT_OPTIMISED_TASK_SELECTION 0 -#endif - -#ifndef configAPPLICATION_ALLOCATED_HEAP - #define configAPPLICATION_ALLOCATED_HEAP 0 -#endif - -#ifndef configUSE_TASK_NOTIFICATIONS - #define configUSE_TASK_NOTIFICATIONS 1 -#endif - -#ifndef portTICK_TYPE_IS_ATOMIC - #define portTICK_TYPE_IS_ATOMIC 0 -#endif - -#ifndef configSUPPORT_STATIC_ALLOCATION - /* Defaults to 0 for backward compatibility. */ - #define configSUPPORT_STATIC_ALLOCATION 0 -#endif - -#ifndef configSUPPORT_DYNAMIC_ALLOCATION - /* Defaults to 1 for backward compatibility. */ - #define configSUPPORT_DYNAMIC_ALLOCATION 1 -#endif - -#ifndef configSTACK_DEPTH_TYPE - /* Defaults to uint16_t for backward compatibility, but can be overridden - in FreeRTOSConfig.h if uint16_t is too restrictive. */ - #define configSTACK_DEPTH_TYPE uint16_t -#endif - -/* Sanity check the configuration. */ -#if( configUSE_TICKLESS_IDLE != 0 ) - #if( INCLUDE_vTaskSuspend != 1 ) - #error INCLUDE_vTaskSuspend must be set to 1 if configUSE_TICKLESS_IDLE is not set to 0 - #endif /* INCLUDE_vTaskSuspend */ -#endif /* configUSE_TICKLESS_IDLE */ - -#if( ( configSUPPORT_STATIC_ALLOCATION == 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 0 ) ) - #error configSUPPORT_STATIC_ALLOCATION and configSUPPORT_DYNAMIC_ALLOCATION cannot both be 0, but can both be 1. -#endif - -#if( ( configUSE_RECURSIVE_MUTEXES == 1 ) && ( configUSE_MUTEXES != 1 ) ) - #error configUSE_MUTEXES must be set to 1 to use recursive mutexes -#endif - -#ifndef configINITIAL_TICK_COUNT - #define configINITIAL_TICK_COUNT 0 -#endif - -#if( portTICK_TYPE_IS_ATOMIC == 0 ) - /* Either variables of tick type cannot be read atomically, or - portTICK_TYPE_IS_ATOMIC was not set - map the critical sections used when - the tick count is returned to the standard critical section macros. */ - #define portTICK_TYPE_ENTER_CRITICAL() portENTER_CRITICAL() - #define portTICK_TYPE_EXIT_CRITICAL() portEXIT_CRITICAL() - #define portTICK_TYPE_SET_INTERRUPT_MASK_FROM_ISR() portSET_INTERRUPT_MASK_FROM_ISR() - #define portTICK_TYPE_CLEAR_INTERRUPT_MASK_FROM_ISR( x ) portCLEAR_INTERRUPT_MASK_FROM_ISR( ( x ) ) -#else - /* The tick type can be read atomically, so critical sections used when the - tick count is returned can be defined away. */ - #define portTICK_TYPE_ENTER_CRITICAL() - #define portTICK_TYPE_EXIT_CRITICAL() - #define portTICK_TYPE_SET_INTERRUPT_MASK_FROM_ISR() 0 - #define portTICK_TYPE_CLEAR_INTERRUPT_MASK_FROM_ISR( x ) ( void ) x -#endif - -/* Definitions to allow backward compatibility with FreeRTOS versions prior to -V8 if desired. */ -#ifndef configENABLE_BACKWARD_COMPATIBILITY - #define configENABLE_BACKWARD_COMPATIBILITY 1 -#endif - -#ifndef configPRINTF - /* configPRINTF() was not defined, so define it away to nothing. To use - configPRINTF() then define it as follows (where MyPrintFunction() is - provided by the application writer): - - void MyPrintFunction(const char *pcFormat, ... ); - #define configPRINTF( X ) MyPrintFunction X - - Then call like a standard printf() function, but placing brackets around - all parameters so they are passed as a single parameter. For example: - configPRINTF( ("Value = %d", MyVariable) ); */ - #define configPRINTF( X ) -#endif - -#ifndef configMAX - /* The application writer has not provided their own MAX macro, so define - the following generic implementation. */ - #define configMAX( a, b ) ( ( ( a ) > ( b ) ) ? ( a ) : ( b ) ) -#endif - -#ifndef configMIN - /* The application writer has not provided their own MAX macro, so define - the following generic implementation. */ - #define configMIN( a, b ) ( ( ( a ) < ( b ) ) ? ( a ) : ( b ) ) -#endif - -#if configENABLE_BACKWARD_COMPATIBILITY == 1 - #define eTaskStateGet eTaskGetState - #define portTickType TickType_t - #define xTaskHandle TaskHandle_t - #define xQueueHandle QueueHandle_t - #define xSemaphoreHandle SemaphoreHandle_t - #define xQueueSetHandle QueueSetHandle_t - #define xQueueSetMemberHandle QueueSetMemberHandle_t - #define xTimeOutType TimeOut_t - #define xMemoryRegion MemoryRegion_t - #define xTaskParameters TaskParameters_t - #define xTaskStatusType TaskStatus_t - #define xTimerHandle TimerHandle_t - #define xCoRoutineHandle CoRoutineHandle_t - #define pdTASK_HOOK_CODE TaskHookFunction_t - #define portTICK_RATE_MS portTICK_PERIOD_MS - #define pcTaskGetTaskName pcTaskGetName - #define pcTimerGetTimerName pcTimerGetName - #define pcQueueGetQueueName pcQueueGetName - #define vTaskGetTaskInfo vTaskGetInfo - - /* Backward compatibility within the scheduler code only - these definitions - are not really required but are included for completeness. */ - #define tmrTIMER_CALLBACK TimerCallbackFunction_t - #define pdTASK_CODE TaskFunction_t - #define xListItem ListItem_t - #define xList List_t -#endif /* configENABLE_BACKWARD_COMPATIBILITY */ - -#if( configUSE_ALTERNATIVE_API != 0 ) - #error The alternative API was deprecated some time ago, and was removed in FreeRTOS V9.0 0 -#endif - -/* Set configUSE_TASK_FPU_SUPPORT to 0 to omit floating point support even -if floating point hardware is otherwise supported by the FreeRTOS port in use. -This constant is not supported by all FreeRTOS ports that include floating -point support. */ -#ifndef configUSE_TASK_FPU_SUPPORT - #define configUSE_TASK_FPU_SUPPORT 1 -#endif - -/* - * In line with software engineering best practice, FreeRTOS implements a strict - * data hiding policy, so the real structures used by FreeRTOS to maintain the - * state of tasks, queues, semaphores, etc. are not accessible to the application - * code. However, if the application writer wants to statically allocate such - * an object then the size of the object needs to be know. Dummy structures - * that are guaranteed to have the same size and alignment requirements of the - * real objects are used for this purpose. The dummy list and list item - * structures below are used for inclusion in such a dummy structure. - */ -struct xSTATIC_LIST_ITEM -{ - TickType_t xDummy1; - void *pvDummy2[ 4 ]; -}; -typedef struct xSTATIC_LIST_ITEM StaticListItem_t; - -/* See the comments above the struct xSTATIC_LIST_ITEM definition. */ -struct xSTATIC_MINI_LIST_ITEM -{ - TickType_t xDummy1; - void *pvDummy2[ 2 ]; -}; -typedef struct xSTATIC_MINI_LIST_ITEM StaticMiniListItem_t; - -/* See the comments above the struct xSTATIC_LIST_ITEM definition. */ -typedef struct xSTATIC_LIST -{ - UBaseType_t uxDummy1; - void *pvDummy2; - StaticMiniListItem_t xDummy3; -} StaticList_t; - -/* - * In line with software engineering best practice, especially when supplying a - * library that is likely to change in future versions, FreeRTOS implements a - * strict data hiding policy. This means the Task structure used internally by - * FreeRTOS is not accessible to application code. However, if the application - * writer wants to statically allocate the memory required to create a task then - * the size of the task object needs to be know. The StaticTask_t structure - * below is provided for this purpose. Its sizes and alignment requirements are - * guaranteed to match those of the genuine structure, no matter which - * architecture is being used, and no matter how the values in FreeRTOSConfig.h - * are set. Its contents are somewhat obfuscated in the hope users will - * recognise that it would be unwise to make direct use of the structure members. - */ -typedef struct xSTATIC_TCB -{ - void *pxDummy1; - #if ( portUSING_MPU_WRAPPERS == 1 ) - xMPU_SETTINGS xDummy2; - #endif - StaticListItem_t xDummy3[ 2 ]; - UBaseType_t uxDummy5; - void *pxDummy6; - uint8_t ucDummy7[ configMAX_TASK_NAME_LEN ]; - #if ( ( portSTACK_GROWTH > 0 ) || ( configRECORD_STACK_HIGH_ADDRESS == 1 ) ) - void *pxDummy8; - #endif - #if ( portCRITICAL_NESTING_IN_TCB == 1 ) - UBaseType_t uxDummy9; - #endif - #if ( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxDummy10[ 2 ]; - #endif - #if ( configUSE_MUTEXES == 1 ) - UBaseType_t uxDummy12[ 2 ]; - #endif - #if ( configUSE_APPLICATION_TASK_TAG == 1 ) - void *pxDummy14; - #endif - #if( configNUM_THREAD_LOCAL_STORAGE_POINTERS > 0 ) - void *pvDummy15[ configNUM_THREAD_LOCAL_STORAGE_POINTERS ]; - #endif - #if ( configGENERATE_RUN_TIME_STATS == 1 ) - uint32_t ulDummy16; - #endif - #if ( configUSE_NEWLIB_REENTRANT == 1 ) - struct _reent xDummy17; - #endif - #if ( configUSE_TASK_NOTIFICATIONS == 1 ) - uint32_t ulDummy18; - uint8_t ucDummy19; - #endif - #if( ( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) || ( portUSING_MPU_WRAPPERS == 1 ) ) - uint8_t uxDummy20; - #endif - - #if( INCLUDE_xTaskAbortDelay == 1 ) - uint8_t ucDummy21; - #endif - -} StaticTask_t; - -/* - * In line with software engineering best practice, especially when supplying a - * library that is likely to change in future versions, FreeRTOS implements a - * strict data hiding policy. This means the Queue structure used internally by - * FreeRTOS is not accessible to application code. However, if the application - * writer wants to statically allocate the memory required to create a queue - * then the size of the queue object needs to be know. The StaticQueue_t - * structure below is provided for this purpose. Its sizes and alignment - * requirements are guaranteed to match those of the genuine structure, no - * matter which architecture is being used, and no matter how the values in - * FreeRTOSConfig.h are set. Its contents are somewhat obfuscated in the hope - * users will recognise that it would be unwise to make direct use of the - * structure members. - */ -typedef struct xSTATIC_QUEUE -{ - void *pvDummy1[ 3 ]; - - union - { - void *pvDummy2; - UBaseType_t uxDummy2; - } u; - - StaticList_t xDummy3[ 2 ]; - UBaseType_t uxDummy4[ 3 ]; - uint8_t ucDummy5[ 2 ]; - - #if( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) - uint8_t ucDummy6; - #endif - - #if ( configUSE_QUEUE_SETS == 1 ) - void *pvDummy7; - #endif - - #if ( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxDummy8; - uint8_t ucDummy9; - #endif - -} StaticQueue_t; -typedef StaticQueue_t StaticSemaphore_t; - -/* - * In line with software engineering best practice, especially when supplying a - * library that is likely to change in future versions, FreeRTOS implements a - * strict data hiding policy. This means the event group structure used - * internally by FreeRTOS is not accessible to application code. However, if - * the application writer wants to statically allocate the memory required to - * create an event group then the size of the event group object needs to be - * know. The StaticEventGroup_t structure below is provided for this purpose. - * Its sizes and alignment requirements are guaranteed to match those of the - * genuine structure, no matter which architecture is being used, and no matter - * how the values in FreeRTOSConfig.h are set. Its contents are somewhat - * obfuscated in the hope users will recognise that it would be unwise to make - * direct use of the structure members. - */ -typedef struct xSTATIC_EVENT_GROUP -{ - TickType_t xDummy1; - StaticList_t xDummy2; - - #if( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxDummy3; - #endif - - #if( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) - uint8_t ucDummy4; - #endif - -} StaticEventGroup_t; - -/* - * In line with software engineering best practice, especially when supplying a - * library that is likely to change in future versions, FreeRTOS implements a - * strict data hiding policy. This means the software timer structure used - * internally by FreeRTOS is not accessible to application code. However, if - * the application writer wants to statically allocate the memory required to - * create a software timer then the size of the queue object needs to be know. - * The StaticTimer_t structure below is provided for this purpose. Its sizes - * and alignment requirements are guaranteed to match those of the genuine - * structure, no matter which architecture is being used, and no matter how the - * values in FreeRTOSConfig.h are set. Its contents are somewhat obfuscated in - * the hope users will recognise that it would be unwise to make direct use of - * the structure members. - */ -typedef struct xSTATIC_TIMER -{ - void *pvDummy1; - StaticListItem_t xDummy2; - TickType_t xDummy3; - UBaseType_t uxDummy4; - void *pvDummy5[ 2 ]; - #if( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxDummy6; - #endif - - #if( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) - uint8_t ucDummy7; - #endif - -} StaticTimer_t; - -/* -* In line with software engineering best practice, especially when supplying a -* library that is likely to change in future versions, FreeRTOS implements a -* strict data hiding policy. This means the stream buffer structure used -* internally by FreeRTOS is not accessible to application code. However, if -* the application writer wants to statically allocate the memory required to -* create a stream buffer then the size of the stream buffer object needs to be -* know. The StaticStreamBuffer_t structure below is provided for this purpose. -* Its size and alignment requirements are guaranteed to match those of the -* genuine structure, no matter which architecture is being used, and no matter -* how the values in FreeRTOSConfig.h are set. Its contents are somewhat -* obfuscated in the hope users will recognise that it would be unwise to make -* direct use of the structure members. -*/ -typedef struct xSTATIC_STREAM_BUFFER -{ - size_t uxDummy1[ 4 ]; - void * pvDummy2[ 3 ]; - uint8_t ucDummy3; - #if ( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxDummy4; - #endif -} StaticStreamBuffer_t; - -/* Message buffers are built on stream buffers. */ -typedef StaticStreamBuffer_t StaticMessageBuffer_t; - -#ifdef __cplusplus -} -#endif - -#endif /* INC_FREERTOS_H */ - diff --git a/lib/FreeRTOS/Source/include/StackMacros.h b/lib/FreeRTOS/Source/include/StackMacros.h deleted file mode 100644 index 534f0045..00000000 --- a/lib/FreeRTOS/Source/include/StackMacros.h +++ /dev/null @@ -1,133 +0,0 @@ -/* - * FreeRTOS Kernel V10.0.1 - * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * 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. - * - * http://www.FreeRTOS.org - * http://aws.amazon.com/freertos - * - * 1 tab == 4 spaces! - */ - -#ifndef STACK_MACROS_H -#define STACK_MACROS_H - -#ifndef _MSC_VER /* Visual Studio doesn't support #warning. */ - #warning The name of this file has changed to stack_macros.h. Please update your code accordingly. This source file (which has the original name) will be removed in future released. -#endif - -/* - * Call the stack overflow hook function if the stack of the task being swapped - * out is currently overflowed, or looks like it might have overflowed in the - * past. - * - * Setting configCHECK_FOR_STACK_OVERFLOW to 1 will cause the macro to check - * the current stack state only - comparing the current top of stack value to - * the stack limit. Setting configCHECK_FOR_STACK_OVERFLOW to greater than 1 - * will also cause the last few stack bytes to be checked to ensure the value - * to which the bytes were set when the task was created have not been - * overwritten. Note this second test does not guarantee that an overflowed - * stack will always be recognised. - */ - -/*-----------------------------------------------------------*/ - -#if( ( configCHECK_FOR_STACK_OVERFLOW == 1 ) && ( portSTACK_GROWTH < 0 ) ) - - /* Only the current stack state is to be checked. */ - #define taskCHECK_FOR_STACK_OVERFLOW() \ - { \ - /* Is the currently saved stack pointer within the stack limit? */ \ - if( pxCurrentTCB->pxTopOfStack <= pxCurrentTCB->pxStack ) \ - { \ - vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \ - } \ - } - -#endif /* configCHECK_FOR_STACK_OVERFLOW == 1 */ -/*-----------------------------------------------------------*/ - -#if( ( configCHECK_FOR_STACK_OVERFLOW == 1 ) && ( portSTACK_GROWTH > 0 ) ) - - /* Only the current stack state is to be checked. */ - #define taskCHECK_FOR_STACK_OVERFLOW() \ - { \ - \ - /* Is the currently saved stack pointer within the stack limit? */ \ - if( pxCurrentTCB->pxTopOfStack >= pxCurrentTCB->pxEndOfStack ) \ - { \ - vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \ - } \ - } - -#endif /* configCHECK_FOR_STACK_OVERFLOW == 1 */ -/*-----------------------------------------------------------*/ - -#if( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) && ( portSTACK_GROWTH < 0 ) ) - - #define taskCHECK_FOR_STACK_OVERFLOW() \ - { \ - const uint32_t * const pulStack = ( uint32_t * ) pxCurrentTCB->pxStack; \ - const uint32_t ulCheckValue = ( uint32_t ) 0xa5a5a5a5; \ - \ - if( ( pulStack[ 0 ] != ulCheckValue ) || \ - ( pulStack[ 1 ] != ulCheckValue ) || \ - ( pulStack[ 2 ] != ulCheckValue ) || \ - ( pulStack[ 3 ] != ulCheckValue ) ) \ - { \ - vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \ - } \ - } - -#endif /* #if( configCHECK_FOR_STACK_OVERFLOW > 1 ) */ -/*-----------------------------------------------------------*/ - -#if( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) && ( portSTACK_GROWTH > 0 ) ) - - #define taskCHECK_FOR_STACK_OVERFLOW() \ - { \ - int8_t *pcEndOfStack = ( int8_t * ) pxCurrentTCB->pxEndOfStack; \ - static const uint8_t ucExpectedStackBytes[] = { tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ - tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ - tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ - tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ - tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE }; \ - \ - \ - pcEndOfStack -= sizeof( ucExpectedStackBytes ); \ - \ - /* Has the extremity of the task stack ever been written over? */ \ - if( memcmp( ( void * ) pcEndOfStack, ( void * ) ucExpectedStackBytes, sizeof( ucExpectedStackBytes ) ) != 0 ) \ - { \ - vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \ - } \ - } - -#endif /* #if( configCHECK_FOR_STACK_OVERFLOW > 1 ) */ -/*-----------------------------------------------------------*/ - -/* Remove stack overflow macro if not being used. */ -#ifndef taskCHECK_FOR_STACK_OVERFLOW - #define taskCHECK_FOR_STACK_OVERFLOW() -#endif - - - -#endif /* STACK_MACROS_H */ - diff --git a/lib/FreeRTOS/Source/include/croutine.h b/lib/FreeRTOS/Source/include/croutine.h deleted file mode 100644 index f4c54d2e..00000000 --- a/lib/FreeRTOS/Source/include/croutine.h +++ /dev/null @@ -1,720 +0,0 @@ -/* - * FreeRTOS Kernel V10.0.1 - * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * 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. - * - * http://www.FreeRTOS.org - * http://aws.amazon.com/freertos - * - * 1 tab == 4 spaces! - */ - -#ifndef CO_ROUTINE_H -#define CO_ROUTINE_H - -#ifndef INC_FREERTOS_H - #error "include FreeRTOS.h must appear in source files before include croutine.h" -#endif - -#include "list.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/* Used to hide the implementation of the co-routine control block. The -control block structure however has to be included in the header due to -the macro implementation of the co-routine functionality. */ -typedef void * CoRoutineHandle_t; - -/* Defines the prototype to which co-routine functions must conform. */ -typedef void (*crCOROUTINE_CODE)( CoRoutineHandle_t, UBaseType_t ); - -typedef struct corCoRoutineControlBlock -{ - crCOROUTINE_CODE pxCoRoutineFunction; - ListItem_t xGenericListItem; /*< List item used to place the CRCB in ready and blocked queues. */ - ListItem_t xEventListItem; /*< List item used to place the CRCB in event lists. */ - UBaseType_t uxPriority; /*< The priority of the co-routine in relation to other co-routines. */ - UBaseType_t uxIndex; /*< Used to distinguish between co-routines when multiple co-routines use the same co-routine function. */ - uint16_t uxState; /*< Used internally by the co-routine implementation. */ -} CRCB_t; /* Co-routine control block. Note must be identical in size down to uxPriority with TCB_t. */ - -/** - * croutine. h - *
- BaseType_t xCoRoutineCreate(
-                                 crCOROUTINE_CODE pxCoRoutineCode,
-                                 UBaseType_t uxPriority,
-                                 UBaseType_t uxIndex
-                               );
- * - * Create a new co-routine and add it to the list of co-routines that are - * ready to run. - * - * @param pxCoRoutineCode Pointer to the co-routine function. Co-routine - * functions require special syntax - see the co-routine section of the WEB - * documentation for more information. - * - * @param uxPriority The priority with respect to other co-routines at which - * the co-routine will run. - * - * @param uxIndex Used to distinguish between different co-routines that - * execute the same function. See the example below and the co-routine section - * of the WEB documentation for further information. - * - * @return pdPASS if the co-routine was successfully created and added to a ready - * list, otherwise an error code defined with ProjDefs.h. - * - * Example usage: -
- // Co-routine to be created.
- void vFlashCoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
- {
- // Variables in co-routines must be declared static if they must maintain value across a blocking call.
- // This may not be necessary for const variables.
- static const char cLedToFlash[ 2 ] = { 5, 6 };
- static const TickType_t uxFlashRates[ 2 ] = { 200, 400 };
-
-     // Must start every co-routine with a call to crSTART();
-     crSTART( xHandle );
-
-     for( ;; )
-     {
-         // This co-routine just delays for a fixed period, then toggles
-         // an LED.  Two co-routines are created using this function, so
-         // the uxIndex parameter is used to tell the co-routine which
-         // LED to flash and how int32_t to delay.  This assumes xQueue has
-         // already been created.
-         vParTestToggleLED( cLedToFlash[ uxIndex ] );
-         crDELAY( xHandle, uxFlashRates[ uxIndex ] );
-     }
-
-     // Must end every co-routine with a call to crEND();
-     crEND();
- }
-
- // Function that creates two co-routines.
- void vOtherFunction( void )
- {
- uint8_t ucParameterToPass;
- TaskHandle_t xHandle;
-
-     // Create two co-routines at priority 0.  The first is given index 0
-     // so (from the code above) toggles LED 5 every 200 ticks.  The second
-     // is given index 1 so toggles LED 6 every 400 ticks.
-     for( uxIndex = 0; uxIndex < 2; uxIndex++ )
-     {
-         xCoRoutineCreate( vFlashCoRoutine, 0, uxIndex );
-     }
- }
-   
- * \defgroup xCoRoutineCreate xCoRoutineCreate - * \ingroup Tasks - */ -BaseType_t xCoRoutineCreate( crCOROUTINE_CODE pxCoRoutineCode, UBaseType_t uxPriority, UBaseType_t uxIndex ); - - -/** - * croutine. h - *
- void vCoRoutineSchedule( void );
- * - * Run a co-routine. - * - * vCoRoutineSchedule() executes the highest priority co-routine that is able - * to run. The co-routine will execute until it either blocks, yields or is - * preempted by a task. Co-routines execute cooperatively so one - * co-routine cannot be preempted by another, but can be preempted by a task. - * - * If an application comprises of both tasks and co-routines then - * vCoRoutineSchedule should be called from the idle task (in an idle task - * hook). - * - * Example usage: -
- // This idle task hook will schedule a co-routine each time it is called.
- // The rest of the idle task will execute between co-routine calls.
- void vApplicationIdleHook( void )
- {
-	vCoRoutineSchedule();
- }
-
- // Alternatively, if you do not require any other part of the idle task to
- // execute, the idle task hook can call vCoRoutineScheduler() within an
- // infinite loop.
- void vApplicationIdleHook( void )
- {
-    for( ;; )
-    {
-        vCoRoutineSchedule();
-    }
- }
- 
- * \defgroup vCoRoutineSchedule vCoRoutineSchedule - * \ingroup Tasks - */ -void vCoRoutineSchedule( void ); - -/** - * croutine. h - *
- crSTART( CoRoutineHandle_t xHandle );
- * - * This macro MUST always be called at the start of a co-routine function. - * - * Example usage: -
- // Co-routine to be created.
- void vACoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
- {
- // Variables in co-routines must be declared static if they must maintain value across a blocking call.
- static int32_t ulAVariable;
-
-     // Must start every co-routine with a call to crSTART();
-     crSTART( xHandle );
-
-     for( ;; )
-     {
-          // Co-routine functionality goes here.
-     }
-
-     // Must end every co-routine with a call to crEND();
-     crEND();
- }
- * \defgroup crSTART crSTART - * \ingroup Tasks - */ -#define crSTART( pxCRCB ) switch( ( ( CRCB_t * )( pxCRCB ) )->uxState ) { case 0: - -/** - * croutine. h - *
- crEND();
- * - * This macro MUST always be called at the end of a co-routine function. - * - * Example usage: -
- // Co-routine to be created.
- void vACoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
- {
- // Variables in co-routines must be declared static if they must maintain value across a blocking call.
- static int32_t ulAVariable;
-
-     // Must start every co-routine with a call to crSTART();
-     crSTART( xHandle );
-
-     for( ;; )
-     {
-          // Co-routine functionality goes here.
-     }
-
-     // Must end every co-routine with a call to crEND();
-     crEND();
- }
- * \defgroup crSTART crSTART - * \ingroup Tasks - */ -#define crEND() } - -/* - * These macros are intended for internal use by the co-routine implementation - * only. The macros should not be used directly by application writers. - */ -#define crSET_STATE0( xHandle ) ( ( CRCB_t * )( xHandle ) )->uxState = (__LINE__ * 2); return; case (__LINE__ * 2): -#define crSET_STATE1( xHandle ) ( ( CRCB_t * )( xHandle ) )->uxState = ((__LINE__ * 2)+1); return; case ((__LINE__ * 2)+1): - -/** - * croutine. h - *
- crDELAY( CoRoutineHandle_t xHandle, TickType_t xTicksToDelay );
- * - * Delay a co-routine for a fixed period of time. - * - * crDELAY can only be called from the co-routine function itself - not - * from within a function called by the co-routine function. This is because - * co-routines do not maintain their own stack. - * - * @param xHandle The handle of the co-routine to delay. This is the xHandle - * parameter of the co-routine function. - * - * @param xTickToDelay The number of ticks that the co-routine should delay - * for. The actual amount of time this equates to is defined by - * configTICK_RATE_HZ (set in FreeRTOSConfig.h). The constant portTICK_PERIOD_MS - * can be used to convert ticks to milliseconds. - * - * Example usage: -
- // Co-routine to be created.
- void vACoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
- {
- // Variables in co-routines must be declared static if they must maintain value across a blocking call.
- // This may not be necessary for const variables.
- // We are to delay for 200ms.
- static const xTickType xDelayTime = 200 / portTICK_PERIOD_MS;
-
-     // Must start every co-routine with a call to crSTART();
-     crSTART( xHandle );
-
-     for( ;; )
-     {
-        // Delay for 200ms.
-        crDELAY( xHandle, xDelayTime );
-
-        // Do something here.
-     }
-
-     // Must end every co-routine with a call to crEND();
-     crEND();
- }
- * \defgroup crDELAY crDELAY - * \ingroup Tasks - */ -#define crDELAY( xHandle, xTicksToDelay ) \ - if( ( xTicksToDelay ) > 0 ) \ - { \ - vCoRoutineAddToDelayedList( ( xTicksToDelay ), NULL ); \ - } \ - crSET_STATE0( ( xHandle ) ); - -/** - *
- crQUEUE_SEND(
-                  CoRoutineHandle_t xHandle,
-                  QueueHandle_t pxQueue,
-                  void *pvItemToQueue,
-                  TickType_t xTicksToWait,
-                  BaseType_t *pxResult
-             )
- * - * The macro's crQUEUE_SEND() and crQUEUE_RECEIVE() are the co-routine - * equivalent to the xQueueSend() and xQueueReceive() functions used by tasks. - * - * crQUEUE_SEND and crQUEUE_RECEIVE can only be used from a co-routine whereas - * xQueueSend() and xQueueReceive() can only be used from tasks. - * - * crQUEUE_SEND can only be called from the co-routine function itself - not - * from within a function called by the co-routine function. This is because - * co-routines do not maintain their own stack. - * - * See the co-routine section of the WEB documentation for information on - * passing data between tasks and co-routines and between ISR's and - * co-routines. - * - * @param xHandle The handle of the calling co-routine. This is the xHandle - * parameter of the co-routine function. - * - * @param pxQueue The handle of the queue on which the data will be posted. - * The handle is obtained as the return value when the queue is created using - * the xQueueCreate() API function. - * - * @param pvItemToQueue A pointer to the data being posted onto the queue. - * The number of bytes of each queued item is specified when the queue is - * created. This number of bytes is copied from pvItemToQueue into the queue - * itself. - * - * @param xTickToDelay The number of ticks that the co-routine should block - * to wait for space to become available on the queue, should space not be - * available immediately. The actual amount of time this equates to is defined - * by configTICK_RATE_HZ (set in FreeRTOSConfig.h). The constant - * portTICK_PERIOD_MS can be used to convert ticks to milliseconds (see example - * below). - * - * @param pxResult The variable pointed to by pxResult will be set to pdPASS if - * data was successfully posted onto the queue, otherwise it will be set to an - * error defined within ProjDefs.h. - * - * Example usage: -
- // Co-routine function that blocks for a fixed period then posts a number onto
- // a queue.
- static void prvCoRoutineFlashTask( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
- {
- // Variables in co-routines must be declared static if they must maintain value across a blocking call.
- static BaseType_t xNumberToPost = 0;
- static BaseType_t xResult;
-
-    // Co-routines must begin with a call to crSTART().
-    crSTART( xHandle );
-
-    for( ;; )
-    {
-        // This assumes the queue has already been created.
-        crQUEUE_SEND( xHandle, xCoRoutineQueue, &xNumberToPost, NO_DELAY, &xResult );
-
-        if( xResult != pdPASS )
-        {
-            // The message was not posted!
-        }
-
-        // Increment the number to be posted onto the queue.
-        xNumberToPost++;
-
-        // Delay for 100 ticks.
-        crDELAY( xHandle, 100 );
-    }
-
-    // Co-routines must end with a call to crEND().
-    crEND();
- }
- * \defgroup crQUEUE_SEND crQUEUE_SEND - * \ingroup Tasks - */ -#define crQUEUE_SEND( xHandle, pxQueue, pvItemToQueue, xTicksToWait, pxResult ) \ -{ \ - *( pxResult ) = xQueueCRSend( ( pxQueue) , ( pvItemToQueue) , ( xTicksToWait ) ); \ - if( *( pxResult ) == errQUEUE_BLOCKED ) \ - { \ - crSET_STATE0( ( xHandle ) ); \ - *pxResult = xQueueCRSend( ( pxQueue ), ( pvItemToQueue ), 0 ); \ - } \ - if( *pxResult == errQUEUE_YIELD ) \ - { \ - crSET_STATE1( ( xHandle ) ); \ - *pxResult = pdPASS; \ - } \ -} - -/** - * croutine. h - *
-  crQUEUE_RECEIVE(
-                     CoRoutineHandle_t xHandle,
-                     QueueHandle_t pxQueue,
-                     void *pvBuffer,
-                     TickType_t xTicksToWait,
-                     BaseType_t *pxResult
-                 )
- * - * The macro's crQUEUE_SEND() and crQUEUE_RECEIVE() are the co-routine - * equivalent to the xQueueSend() and xQueueReceive() functions used by tasks. - * - * crQUEUE_SEND and crQUEUE_RECEIVE can only be used from a co-routine whereas - * xQueueSend() and xQueueReceive() can only be used from tasks. - * - * crQUEUE_RECEIVE can only be called from the co-routine function itself - not - * from within a function called by the co-routine function. This is because - * co-routines do not maintain their own stack. - * - * See the co-routine section of the WEB documentation for information on - * passing data between tasks and co-routines and between ISR's and - * co-routines. - * - * @param xHandle The handle of the calling co-routine. This is the xHandle - * parameter of the co-routine function. - * - * @param pxQueue The handle of the queue from which the data will be received. - * The handle is obtained as the return value when the queue is created using - * the xQueueCreate() API function. - * - * @param pvBuffer The buffer into which the received item is to be copied. - * The number of bytes of each queued item is specified when the queue is - * created. This number of bytes is copied into pvBuffer. - * - * @param xTickToDelay The number of ticks that the co-routine should block - * to wait for data to become available from the queue, should data not be - * available immediately. The actual amount of time this equates to is defined - * by configTICK_RATE_HZ (set in FreeRTOSConfig.h). The constant - * portTICK_PERIOD_MS can be used to convert ticks to milliseconds (see the - * crQUEUE_SEND example). - * - * @param pxResult The variable pointed to by pxResult will be set to pdPASS if - * data was successfully retrieved from the queue, otherwise it will be set to - * an error code as defined within ProjDefs.h. - * - * Example usage: -
- // A co-routine receives the number of an LED to flash from a queue.  It
- // blocks on the queue until the number is received.
- static void prvCoRoutineFlashWorkTask( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
- {
- // Variables in co-routines must be declared static if they must maintain value across a blocking call.
- static BaseType_t xResult;
- static UBaseType_t uxLEDToFlash;
-
-    // All co-routines must start with a call to crSTART().
-    crSTART( xHandle );
-
-    for( ;; )
-    {
-        // Wait for data to become available on the queue.
-        crQUEUE_RECEIVE( xHandle, xCoRoutineQueue, &uxLEDToFlash, portMAX_DELAY, &xResult );
-
-        if( xResult == pdPASS )
-        {
-            // We received the LED to flash - flash it!
-            vParTestToggleLED( uxLEDToFlash );
-        }
-    }
-
-    crEND();
- }
- * \defgroup crQUEUE_RECEIVE crQUEUE_RECEIVE - * \ingroup Tasks - */ -#define crQUEUE_RECEIVE( xHandle, pxQueue, pvBuffer, xTicksToWait, pxResult ) \ -{ \ - *( pxResult ) = xQueueCRReceive( ( pxQueue) , ( pvBuffer ), ( xTicksToWait ) ); \ - if( *( pxResult ) == errQUEUE_BLOCKED ) \ - { \ - crSET_STATE0( ( xHandle ) ); \ - *( pxResult ) = xQueueCRReceive( ( pxQueue) , ( pvBuffer ), 0 ); \ - } \ - if( *( pxResult ) == errQUEUE_YIELD ) \ - { \ - crSET_STATE1( ( xHandle ) ); \ - *( pxResult ) = pdPASS; \ - } \ -} - -/** - * croutine. h - *
-  crQUEUE_SEND_FROM_ISR(
-                            QueueHandle_t pxQueue,
-                            void *pvItemToQueue,
-                            BaseType_t xCoRoutinePreviouslyWoken
-                       )
- * - * The macro's crQUEUE_SEND_FROM_ISR() and crQUEUE_RECEIVE_FROM_ISR() are the - * co-routine equivalent to the xQueueSendFromISR() and xQueueReceiveFromISR() - * functions used by tasks. - * - * crQUEUE_SEND_FROM_ISR() and crQUEUE_RECEIVE_FROM_ISR() can only be used to - * pass data between a co-routine and and ISR, whereas xQueueSendFromISR() and - * xQueueReceiveFromISR() can only be used to pass data between a task and and - * ISR. - * - * crQUEUE_SEND_FROM_ISR can only be called from an ISR to send data to a queue - * that is being used from within a co-routine. - * - * See the co-routine section of the WEB documentation for information on - * passing data between tasks and co-routines and between ISR's and - * co-routines. - * - * @param xQueue The handle to the queue on which the item is to be posted. - * - * @param pvItemToQueue A pointer to the item that is to be placed on the - * queue. The size of the items the queue will hold was defined when the - * queue was created, so this many bytes will be copied from pvItemToQueue - * into the queue storage area. - * - * @param xCoRoutinePreviouslyWoken This is included so an ISR can post onto - * the same queue multiple times from a single interrupt. The first call - * should always pass in pdFALSE. Subsequent calls should pass in - * the value returned from the previous call. - * - * @return pdTRUE if a co-routine was woken by posting onto the queue. This is - * used by the ISR to determine if a context switch may be required following - * the ISR. - * - * Example usage: -
- // A co-routine that blocks on a queue waiting for characters to be received.
- static void vReceivingCoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
- {
- char cRxedChar;
- BaseType_t xResult;
-
-     // All co-routines must start with a call to crSTART().
-     crSTART( xHandle );
-
-     for( ;; )
-     {
-         // Wait for data to become available on the queue.  This assumes the
-         // queue xCommsRxQueue has already been created!
-         crQUEUE_RECEIVE( xHandle, xCommsRxQueue, &uxLEDToFlash, portMAX_DELAY, &xResult );
-
-         // Was a character received?
-         if( xResult == pdPASS )
-         {
-             // Process the character here.
-         }
-     }
-
-     // All co-routines must end with a call to crEND().
-     crEND();
- }
-
- // An ISR that uses a queue to send characters received on a serial port to
- // a co-routine.
- void vUART_ISR( void )
- {
- char cRxedChar;
- BaseType_t xCRWokenByPost = pdFALSE;
-
-     // We loop around reading characters until there are none left in the UART.
-     while( UART_RX_REG_NOT_EMPTY() )
-     {
-         // Obtain the character from the UART.
-         cRxedChar = UART_RX_REG;
-
-         // Post the character onto a queue.  xCRWokenByPost will be pdFALSE
-         // the first time around the loop.  If the post causes a co-routine
-         // to be woken (unblocked) then xCRWokenByPost will be set to pdTRUE.
-         // In this manner we can ensure that if more than one co-routine is
-         // blocked on the queue only one is woken by this ISR no matter how
-         // many characters are posted to the queue.
-         xCRWokenByPost = crQUEUE_SEND_FROM_ISR( xCommsRxQueue, &cRxedChar, xCRWokenByPost );
-     }
- }
- * \defgroup crQUEUE_SEND_FROM_ISR crQUEUE_SEND_FROM_ISR - * \ingroup Tasks - */ -#define crQUEUE_SEND_FROM_ISR( pxQueue, pvItemToQueue, xCoRoutinePreviouslyWoken ) xQueueCRSendFromISR( ( pxQueue ), ( pvItemToQueue ), ( xCoRoutinePreviouslyWoken ) ) - - -/** - * croutine. h - *
-  crQUEUE_SEND_FROM_ISR(
-                            QueueHandle_t pxQueue,
-                            void *pvBuffer,
-                            BaseType_t * pxCoRoutineWoken
-                       )
- * - * The macro's crQUEUE_SEND_FROM_ISR() and crQUEUE_RECEIVE_FROM_ISR() are the - * co-routine equivalent to the xQueueSendFromISR() and xQueueReceiveFromISR() - * functions used by tasks. - * - * crQUEUE_SEND_FROM_ISR() and crQUEUE_RECEIVE_FROM_ISR() can only be used to - * pass data between a co-routine and and ISR, whereas xQueueSendFromISR() and - * xQueueReceiveFromISR() can only be used to pass data between a task and and - * ISR. - * - * crQUEUE_RECEIVE_FROM_ISR can only be called from an ISR to receive data - * from a queue that is being used from within a co-routine (a co-routine - * posted to the queue). - * - * See the co-routine section of the WEB documentation for information on - * passing data between tasks and co-routines and between ISR's and - * co-routines. - * - * @param xQueue The handle to the queue on which the item is to be posted. - * - * @param pvBuffer A pointer to a buffer into which the received item will be - * placed. The size of the items the queue will hold was defined when the - * queue was created, so this many bytes will be copied from the queue into - * pvBuffer. - * - * @param pxCoRoutineWoken A co-routine may be blocked waiting for space to become - * available on the queue. If crQUEUE_RECEIVE_FROM_ISR causes such a - * co-routine to unblock *pxCoRoutineWoken will get set to pdTRUE, otherwise - * *pxCoRoutineWoken will remain unchanged. - * - * @return pdTRUE an item was successfully received from the queue, otherwise - * pdFALSE. - * - * Example usage: -
- // A co-routine that posts a character to a queue then blocks for a fixed
- // period.  The character is incremented each time.
- static void vSendingCoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
- {
- // cChar holds its value while this co-routine is blocked and must therefore
- // be declared static.
- static char cCharToTx = 'a';
- BaseType_t xResult;
-
-     // All co-routines must start with a call to crSTART().
-     crSTART( xHandle );
-
-     for( ;; )
-     {
-         // Send the next character to the queue.
-         crQUEUE_SEND( xHandle, xCoRoutineQueue, &cCharToTx, NO_DELAY, &xResult );
-
-         if( xResult == pdPASS )
-         {
-             // The character was successfully posted to the queue.
-         }
-		 else
-		 {
-			// Could not post the character to the queue.
-		 }
-
-         // Enable the UART Tx interrupt to cause an interrupt in this
-		 // hypothetical UART.  The interrupt will obtain the character
-		 // from the queue and send it.
-		 ENABLE_RX_INTERRUPT();
-
-		 // Increment to the next character then block for a fixed period.
-		 // cCharToTx will maintain its value across the delay as it is
-		 // declared static.
-		 cCharToTx++;
-		 if( cCharToTx > 'x' )
-		 {
-			cCharToTx = 'a';
-		 }
-		 crDELAY( 100 );
-     }
-
-     // All co-routines must end with a call to crEND().
-     crEND();
- }
-
- // An ISR that uses a queue to receive characters to send on a UART.
- void vUART_ISR( void )
- {
- char cCharToTx;
- BaseType_t xCRWokenByPost = pdFALSE;
-
-     while( UART_TX_REG_EMPTY() )
-     {
-         // Are there any characters in the queue waiting to be sent?
-		 // xCRWokenByPost will automatically be set to pdTRUE if a co-routine
-		 // is woken by the post - ensuring that only a single co-routine is
-		 // woken no matter how many times we go around this loop.
-         if( crQUEUE_RECEIVE_FROM_ISR( pxQueue, &cCharToTx, &xCRWokenByPost ) )
-		 {
-			 SEND_CHARACTER( cCharToTx );
-		 }
-     }
- }
- * \defgroup crQUEUE_RECEIVE_FROM_ISR crQUEUE_RECEIVE_FROM_ISR - * \ingroup Tasks - */ -#define crQUEUE_RECEIVE_FROM_ISR( pxQueue, pvBuffer, pxCoRoutineWoken ) xQueueCRReceiveFromISR( ( pxQueue ), ( pvBuffer ), ( pxCoRoutineWoken ) ) - -/* - * This function is intended for internal use by the co-routine macros only. - * The macro nature of the co-routine implementation requires that the - * prototype appears here. The function should not be used by application - * writers. - * - * Removes the current co-routine from its ready list and places it in the - * appropriate delayed list. - */ -void vCoRoutineAddToDelayedList( TickType_t xTicksToDelay, List_t *pxEventList ); - -/* - * This function is intended for internal use by the queue implementation only. - * The function should not be used by application writers. - * - * Removes the highest priority co-routine from the event list and places it in - * the pending ready list. - */ -BaseType_t xCoRoutineRemoveFromEventList( const List_t *pxEventList ); - -#ifdef __cplusplus -} -#endif - -#endif /* CO_ROUTINE_H */ diff --git a/lib/FreeRTOS/Source/include/deprecated_definitions.h b/lib/FreeRTOS/Source/include/deprecated_definitions.h deleted file mode 100644 index 1125673c..00000000 --- a/lib/FreeRTOS/Source/include/deprecated_definitions.h +++ /dev/null @@ -1,279 +0,0 @@ -/* - * FreeRTOS Kernel V10.0.1 - * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * 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. - * - * http://www.FreeRTOS.org - * http://aws.amazon.com/freertos - * - * 1 tab == 4 spaces! - */ - -#ifndef DEPRECATED_DEFINITIONS_H -#define DEPRECATED_DEFINITIONS_H - - -/* Each FreeRTOS port has a unique portmacro.h header file. Originally a -pre-processor definition was used to ensure the pre-processor found the correct -portmacro.h file for the port being used. That scheme was deprecated in favour -of setting the compiler's include path such that it found the correct -portmacro.h file - removing the need for the constant and allowing the -portmacro.h file to be located anywhere in relation to the port being used. The -definitions below remain in the code for backward compatibility only. New -projects should not use them. */ - -#ifdef OPEN_WATCOM_INDUSTRIAL_PC_PORT - #include "..\..\Source\portable\owatcom\16bitdos\pc\portmacro.h" - typedef void ( __interrupt __far *pxISR )(); -#endif - -#ifdef OPEN_WATCOM_FLASH_LITE_186_PORT - #include "..\..\Source\portable\owatcom\16bitdos\flsh186\portmacro.h" - typedef void ( __interrupt __far *pxISR )(); -#endif - -#ifdef GCC_MEGA_AVR - #include "../portable/GCC/ATMega323/portmacro.h" -#endif - -#ifdef IAR_MEGA_AVR - #include "../portable/IAR/ATMega323/portmacro.h" -#endif - -#ifdef MPLAB_PIC24_PORT - #include "../../Source/portable/MPLAB/PIC24_dsPIC/portmacro.h" -#endif - -#ifdef MPLAB_DSPIC_PORT - #include "../../Source/portable/MPLAB/PIC24_dsPIC/portmacro.h" -#endif - -#ifdef MPLAB_PIC18F_PORT - #include "../../Source/portable/MPLAB/PIC18F/portmacro.h" -#endif - -#ifdef MPLAB_PIC32MX_PORT - #include "../../Source/portable/MPLAB/PIC32MX/portmacro.h" -#endif - -#ifdef _FEDPICC - #include "libFreeRTOS/Include/portmacro.h" -#endif - -#ifdef SDCC_CYGNAL - #include "../../Source/portable/SDCC/Cygnal/portmacro.h" -#endif - -#ifdef GCC_ARM7 - #include "../../Source/portable/GCC/ARM7_LPC2000/portmacro.h" -#endif - -#ifdef GCC_ARM7_ECLIPSE - #include "portmacro.h" -#endif - -#ifdef ROWLEY_LPC23xx - #include "../../Source/portable/GCC/ARM7_LPC23xx/portmacro.h" -#endif - -#ifdef IAR_MSP430 - #include "..\..\Source\portable\IAR\MSP430\portmacro.h" -#endif - -#ifdef GCC_MSP430 - #include "../../Source/portable/GCC/MSP430F449/portmacro.h" -#endif - -#ifdef ROWLEY_MSP430 - #include "../../Source/portable/Rowley/MSP430F449/portmacro.h" -#endif - -#ifdef ARM7_LPC21xx_KEIL_RVDS - #include "..\..\Source\portable\RVDS\ARM7_LPC21xx\portmacro.h" -#endif - -#ifdef SAM7_GCC - #include "../../Source/portable/GCC/ARM7_AT91SAM7S/portmacro.h" -#endif - -#ifdef SAM7_IAR - #include "..\..\Source\portable\IAR\AtmelSAM7S64\portmacro.h" -#endif - -#ifdef SAM9XE_IAR - #include "..\..\Source\portable\IAR\AtmelSAM9XE\portmacro.h" -#endif - -#ifdef LPC2000_IAR - #include "..\..\Source\portable\IAR\LPC2000\portmacro.h" -#endif - -#ifdef STR71X_IAR - #include "..\..\Source\portable\IAR\STR71x\portmacro.h" -#endif - -#ifdef STR75X_IAR - #include "..\..\Source\portable\IAR\STR75x\portmacro.h" -#endif - -#ifdef STR75X_GCC - #include "..\..\Source\portable\GCC\STR75x\portmacro.h" -#endif - -#ifdef STR91X_IAR - #include "..\..\Source\portable\IAR\STR91x\portmacro.h" -#endif - -#ifdef GCC_H8S - #include "../../Source/portable/GCC/H8S2329/portmacro.h" -#endif - -#ifdef GCC_AT91FR40008 - #include "../../Source/portable/GCC/ARM7_AT91FR40008/portmacro.h" -#endif - -#ifdef RVDS_ARMCM3_LM3S102 - #include "../../Source/portable/RVDS/ARM_CM3/portmacro.h" -#endif - -#ifdef GCC_ARMCM3_LM3S102 - #include "../../Source/portable/GCC/ARM_CM3/portmacro.h" -#endif - -#ifdef GCC_ARMCM3 - #include "../../Source/portable/GCC/ARM_CM3/portmacro.h" -#endif - -#ifdef IAR_ARM_CM3 - #include "../../Source/portable/IAR/ARM_CM3/portmacro.h" -#endif - -#ifdef IAR_ARMCM3_LM - #include "../../Source/portable/IAR/ARM_CM3/portmacro.h" -#endif - -#ifdef HCS12_CODE_WARRIOR - #include "../../Source/portable/CodeWarrior/HCS12/portmacro.h" -#endif - -#ifdef MICROBLAZE_GCC - #include "../../Source/portable/GCC/MicroBlaze/portmacro.h" -#endif - -#ifdef TERN_EE - #include "..\..\Source\portable\Paradigm\Tern_EE\small\portmacro.h" -#endif - -#ifdef GCC_HCS12 - #include "../../Source/portable/GCC/HCS12/portmacro.h" -#endif - -#ifdef GCC_MCF5235 - #include "../../Source/portable/GCC/MCF5235/portmacro.h" -#endif - -#ifdef COLDFIRE_V2_GCC - #include "../../../Source/portable/GCC/ColdFire_V2/portmacro.h" -#endif - -#ifdef COLDFIRE_V2_CODEWARRIOR - #include "../../Source/portable/CodeWarrior/ColdFire_V2/portmacro.h" -#endif - -#ifdef GCC_PPC405 - #include "../../Source/portable/GCC/PPC405_Xilinx/portmacro.h" -#endif - -#ifdef GCC_PPC440 - #include "../../Source/portable/GCC/PPC440_Xilinx/portmacro.h" -#endif - -#ifdef _16FX_SOFTUNE - #include "..\..\Source\portable\Softune\MB96340\portmacro.h" -#endif - -#ifdef BCC_INDUSTRIAL_PC_PORT - /* A short file name has to be used in place of the normal - FreeRTOSConfig.h when using the Borland compiler. */ - #include "frconfig.h" - #include "..\portable\BCC\16BitDOS\PC\prtmacro.h" - typedef void ( __interrupt __far *pxISR )(); -#endif - -#ifdef BCC_FLASH_LITE_186_PORT - /* A short file name has to be used in place of the normal - FreeRTOSConfig.h when using the Borland compiler. */ - #include "frconfig.h" - #include "..\portable\BCC\16BitDOS\flsh186\prtmacro.h" - typedef void ( __interrupt __far *pxISR )(); -#endif - -#ifdef __GNUC__ - #ifdef __AVR32_AVR32A__ - #include "portmacro.h" - #endif -#endif - -#ifdef __ICCAVR32__ - #ifdef __CORE__ - #if __CORE__ == __AVR32A__ - #include "portmacro.h" - #endif - #endif -#endif - -#ifdef __91467D - #include "portmacro.h" -#endif - -#ifdef __96340 - #include "portmacro.h" -#endif - - -#ifdef __IAR_V850ES_Fx3__ - #include "../../Source/portable/IAR/V850ES/portmacro.h" -#endif - -#ifdef __IAR_V850ES_Jx3__ - #include "../../Source/portable/IAR/V850ES/portmacro.h" -#endif - -#ifdef __IAR_V850ES_Jx3_L__ - #include "../../Source/portable/IAR/V850ES/portmacro.h" -#endif - -#ifdef __IAR_V850ES_Jx2__ - #include "../../Source/portable/IAR/V850ES/portmacro.h" -#endif - -#ifdef __IAR_V850ES_Hx2__ - #include "../../Source/portable/IAR/V850ES/portmacro.h" -#endif - -#ifdef __IAR_78K0R_Kx3__ - #include "../../Source/portable/IAR/78K0R/portmacro.h" -#endif - -#ifdef __IAR_78K0R_Kx3L__ - #include "../../Source/portable/IAR/78K0R/portmacro.h" -#endif - -#endif /* DEPRECATED_DEFINITIONS_H */ - diff --git a/lib/FreeRTOS/Source/include/event_groups.h b/lib/FreeRTOS/Source/include/event_groups.h deleted file mode 100644 index 69ec2e60..00000000 --- a/lib/FreeRTOS/Source/include/event_groups.h +++ /dev/null @@ -1,756 +0,0 @@ -/* - * FreeRTOS Kernel V10.0.1 - * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * 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. - * - * http://www.FreeRTOS.org - * http://aws.amazon.com/freertos - * - * 1 tab == 4 spaces! - */ - -#ifndef EVENT_GROUPS_H -#define EVENT_GROUPS_H - -#ifndef INC_FREERTOS_H - #error "include FreeRTOS.h" must appear in source files before "include event_groups.h" -#endif - -/* FreeRTOS includes. */ -#include "timers.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * An event group is a collection of bits to which an application can assign a - * meaning. For example, an application may create an event group to convey - * the status of various CAN bus related events in which bit 0 might mean "A CAN - * message has been received and is ready for processing", bit 1 might mean "The - * application has queued a message that is ready for sending onto the CAN - * network", and bit 2 might mean "It is time to send a SYNC message onto the - * CAN network" etc. A task can then test the bit values to see which events - * are active, and optionally enter the Blocked state to wait for a specified - * bit or a group of specified bits to be active. To continue the CAN bus - * example, a CAN controlling task can enter the Blocked state (and therefore - * not consume any processing time) until either bit 0, bit 1 or bit 2 are - * active, at which time the bit that was actually active would inform the task - * which action it had to take (process a received message, send a message, or - * send a SYNC). - * - * The event groups implementation contains intelligence to avoid race - * conditions that would otherwise occur were an application to use a simple - * variable for the same purpose. This is particularly important with respect - * to when a bit within an event group is to be cleared, and when bits have to - * be set and then tested atomically - as is the case where event groups are - * used to create a synchronisation point between multiple tasks (a - * 'rendezvous'). - * - * \defgroup EventGroup - */ - - - -/** - * event_groups.h - * - * Type by which event groups are referenced. For example, a call to - * xEventGroupCreate() returns an EventGroupHandle_t variable that can then - * be used as a parameter to other event group functions. - * - * \defgroup EventGroupHandle_t EventGroupHandle_t - * \ingroup EventGroup - */ -typedef void * EventGroupHandle_t; - -/* - * The type that holds event bits always matches TickType_t - therefore the - * number of bits it holds is set by configUSE_16_BIT_TICKS (16 bits if set to 1, - * 32 bits if set to 0. - * - * \defgroup EventBits_t EventBits_t - * \ingroup EventGroup - */ -typedef TickType_t EventBits_t; - -/** - * event_groups.h - *
- EventGroupHandle_t xEventGroupCreate( void );
- 
- * - * Create a new event group. - * - * Internally, within the FreeRTOS implementation, event groups use a [small] - * block of memory, in which the event group's structure is stored. If an event - * groups is created using xEventGropuCreate() then the required memory is - * automatically dynamically allocated inside the xEventGroupCreate() function. - * (see http://www.freertos.org/a00111.html). If an event group is created - * using xEventGropuCreateStatic() then the application writer must instead - * provide the memory that will get used by the event group. - * xEventGroupCreateStatic() therefore allows an event group to be created - * without using any dynamic memory allocation. - * - * Although event groups are not related to ticks, for internal implementation - * reasons the number of bits available for use in an event group is dependent - * on the configUSE_16_BIT_TICKS setting in FreeRTOSConfig.h. If - * configUSE_16_BIT_TICKS is 1 then each event group contains 8 usable bits (bit - * 0 to bit 7). If configUSE_16_BIT_TICKS is set to 0 then each event group has - * 24 usable bits (bit 0 to bit 23). The EventBits_t type is used to store - * event bits within an event group. - * - * @return If the event group was created then a handle to the event group is - * returned. If there was insufficient FreeRTOS heap available to create the - * event group then NULL is returned. See http://www.freertos.org/a00111.html - * - * Example usage: -
-	// Declare a variable to hold the created event group.
-	EventGroupHandle_t xCreatedEventGroup;
-
-	// Attempt to create the event group.
-	xCreatedEventGroup = xEventGroupCreate();
-
-	// Was the event group created successfully?
-	if( xCreatedEventGroup == NULL )
-	{
-		// The event group was not created because there was insufficient
-		// FreeRTOS heap available.
-	}
-	else
-	{
-		// The event group was created.
-	}
-   
- * \defgroup xEventGroupCreate xEventGroupCreate - * \ingroup EventGroup - */ -#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - EventGroupHandle_t xEventGroupCreate( void ) PRIVILEGED_FUNCTION; -#endif - -/** - * event_groups.h - *
- EventGroupHandle_t xEventGroupCreateStatic( EventGroupHandle_t * pxEventGroupBuffer );
- 
- * - * Create a new event group. - * - * Internally, within the FreeRTOS implementation, event groups use a [small] - * block of memory, in which the event group's structure is stored. If an event - * groups is created using xEventGropuCreate() then the required memory is - * automatically dynamically allocated inside the xEventGroupCreate() function. - * (see http://www.freertos.org/a00111.html). If an event group is created - * using xEventGropuCreateStatic() then the application writer must instead - * provide the memory that will get used by the event group. - * xEventGroupCreateStatic() therefore allows an event group to be created - * without using any dynamic memory allocation. - * - * Although event groups are not related to ticks, for internal implementation - * reasons the number of bits available for use in an event group is dependent - * on the configUSE_16_BIT_TICKS setting in FreeRTOSConfig.h. If - * configUSE_16_BIT_TICKS is 1 then each event group contains 8 usable bits (bit - * 0 to bit 7). If configUSE_16_BIT_TICKS is set to 0 then each event group has - * 24 usable bits (bit 0 to bit 23). The EventBits_t type is used to store - * event bits within an event group. - * - * @param pxEventGroupBuffer pxEventGroupBuffer must point to a variable of type - * StaticEventGroup_t, which will be then be used to hold the event group's data - * structures, removing the need for the memory to be allocated dynamically. - * - * @return If the event group was created then a handle to the event group is - * returned. If pxEventGroupBuffer was NULL then NULL is returned. - * - * Example usage: -
-	// StaticEventGroup_t is a publicly accessible structure that has the same
-	// size and alignment requirements as the real event group structure.  It is
-	// provided as a mechanism for applications to know the size of the event
-	// group (which is dependent on the architecture and configuration file
-	// settings) without breaking the strict data hiding policy by exposing the
-	// real event group internals.  This StaticEventGroup_t variable is passed
-	// into the xSemaphoreCreateEventGroupStatic() function and is used to store
-	// the event group's data structures
-	StaticEventGroup_t xEventGroupBuffer;
-
-	// Create the event group without dynamically allocating any memory.
-	xEventGroup = xEventGroupCreateStatic( &xEventGroupBuffer );
-   
- */ -#if( configSUPPORT_STATIC_ALLOCATION == 1 ) - EventGroupHandle_t xEventGroupCreateStatic( StaticEventGroup_t *pxEventGroupBuffer ) PRIVILEGED_FUNCTION; -#endif - -/** - * event_groups.h - *
-	EventBits_t xEventGroupWaitBits( 	EventGroupHandle_t xEventGroup,
-										const EventBits_t uxBitsToWaitFor,
-										const BaseType_t xClearOnExit,
-										const BaseType_t xWaitForAllBits,
-										const TickType_t xTicksToWait );
- 
- * - * [Potentially] block to wait for one or more bits to be set within a - * previously created event group. - * - * This function cannot be called from an interrupt. - * - * @param xEventGroup The event group in which the bits are being tested. The - * event group must have previously been created using a call to - * xEventGroupCreate(). - * - * @param uxBitsToWaitFor A bitwise value that indicates the bit or bits to test - * inside the event group. For example, to wait for bit 0 and/or bit 2 set - * uxBitsToWaitFor to 0x05. To wait for bits 0 and/or bit 1 and/or bit 2 set - * uxBitsToWaitFor to 0x07. Etc. - * - * @param xClearOnExit If xClearOnExit is set to pdTRUE then any bits within - * uxBitsToWaitFor that are set within the event group will be cleared before - * xEventGroupWaitBits() returns if the wait condition was met (if the function - * returns for a reason other than a timeout). If xClearOnExit is set to - * pdFALSE then the bits set in the event group are not altered when the call to - * xEventGroupWaitBits() returns. - * - * @param xWaitForAllBits If xWaitForAllBits is set to pdTRUE then - * xEventGroupWaitBits() will return when either all the bits in uxBitsToWaitFor - * are set or the specified block time expires. If xWaitForAllBits is set to - * pdFALSE then xEventGroupWaitBits() will return when any one of the bits set - * in uxBitsToWaitFor is set or the specified block time expires. The block - * time is specified by the xTicksToWait parameter. - * - * @param xTicksToWait The maximum amount of time (specified in 'ticks') to wait - * for one/all (depending on the xWaitForAllBits value) of the bits specified by - * uxBitsToWaitFor to become set. - * - * @return The value of the event group at the time either the bits being waited - * for became set, or the block time expired. Test the return value to know - * which bits were set. If xEventGroupWaitBits() returned because its timeout - * expired then not all the bits being waited for will be set. If - * xEventGroupWaitBits() returned because the bits it was waiting for were set - * then the returned value is the event group value before any bits were - * automatically cleared in the case that xClearOnExit parameter was set to - * pdTRUE. - * - * Example usage: -
-   #define BIT_0	( 1 << 0 )
-   #define BIT_4	( 1 << 4 )
-
-   void aFunction( EventGroupHandle_t xEventGroup )
-   {
-   EventBits_t uxBits;
-   const TickType_t xTicksToWait = 100 / portTICK_PERIOD_MS;
-
-		// Wait a maximum of 100ms for either bit 0 or bit 4 to be set within
-		// the event group.  Clear the bits before exiting.
-		uxBits = xEventGroupWaitBits(
-					xEventGroup,	// The event group being tested.
-					BIT_0 | BIT_4,	// The bits within the event group to wait for.
-					pdTRUE,			// BIT_0 and BIT_4 should be cleared before returning.
-					pdFALSE,		// Don't wait for both bits, either bit will do.
-					xTicksToWait );	// Wait a maximum of 100ms for either bit to be set.
-
-		if( ( uxBits & ( BIT_0 | BIT_4 ) ) == ( BIT_0 | BIT_4 ) )
-		{
-			// xEventGroupWaitBits() returned because both bits were set.
-		}
-		else if( ( uxBits & BIT_0 ) != 0 )
-		{
-			// xEventGroupWaitBits() returned because just BIT_0 was set.
-		}
-		else if( ( uxBits & BIT_4 ) != 0 )
-		{
-			// xEventGroupWaitBits() returned because just BIT_4 was set.
-		}
-		else
-		{
-			// xEventGroupWaitBits() returned because xTicksToWait ticks passed
-			// without either BIT_0 or BIT_4 becoming set.
-		}
-   }
-   
- * \defgroup xEventGroupWaitBits xEventGroupWaitBits - * \ingroup EventGroup - */ -EventBits_t xEventGroupWaitBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToWaitFor, const BaseType_t xClearOnExit, const BaseType_t xWaitForAllBits, TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; - -/** - * event_groups.h - *
-	EventBits_t xEventGroupClearBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToClear );
- 
- * - * Clear bits within an event group. This function cannot be called from an - * interrupt. - * - * @param xEventGroup The event group in which the bits are to be cleared. - * - * @param uxBitsToClear A bitwise value that indicates the bit or bits to clear - * in the event group. For example, to clear bit 3 only, set uxBitsToClear to - * 0x08. To clear bit 3 and bit 0 set uxBitsToClear to 0x09. - * - * @return The value of the event group before the specified bits were cleared. - * - * Example usage: -
-   #define BIT_0	( 1 << 0 )
-   #define BIT_4	( 1 << 4 )
-
-   void aFunction( EventGroupHandle_t xEventGroup )
-   {
-   EventBits_t uxBits;
-
-		// Clear bit 0 and bit 4 in xEventGroup.
-		uxBits = xEventGroupClearBits(
-								xEventGroup,	// The event group being updated.
-								BIT_0 | BIT_4 );// The bits being cleared.
-
-		if( ( uxBits & ( BIT_0 | BIT_4 ) ) == ( BIT_0 | BIT_4 ) )
-		{
-			// Both bit 0 and bit 4 were set before xEventGroupClearBits() was
-			// called.  Both will now be clear (not set).
-		}
-		else if( ( uxBits & BIT_0 ) != 0 )
-		{
-			// Bit 0 was set before xEventGroupClearBits() was called.  It will
-			// now be clear.
-		}
-		else if( ( uxBits & BIT_4 ) != 0 )
-		{
-			// Bit 4 was set before xEventGroupClearBits() was called.  It will
-			// now be clear.
-		}
-		else
-		{
-			// Neither bit 0 nor bit 4 were set in the first place.
-		}
-   }
-   
- * \defgroup xEventGroupClearBits xEventGroupClearBits - * \ingroup EventGroup - */ -EventBits_t xEventGroupClearBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToClear ) PRIVILEGED_FUNCTION; - -/** - * event_groups.h - *
-	BaseType_t xEventGroupClearBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet );
- 
- * - * A version of xEventGroupClearBits() that can be called from an interrupt. - * - * Setting bits in an event group is not a deterministic operation because there - * are an unknown number of tasks that may be waiting for the bit or bits being - * set. FreeRTOS does not allow nondeterministic operations to be performed - * while interrupts are disabled, so protects event groups that are accessed - * from tasks by suspending the scheduler rather than disabling interrupts. As - * a result event groups cannot be accessed directly from an interrupt service - * routine. Therefore xEventGroupClearBitsFromISR() sends a message to the - * timer task to have the clear operation performed in the context of the timer - * task. - * - * @param xEventGroup The event group in which the bits are to be cleared. - * - * @param uxBitsToClear A bitwise value that indicates the bit or bits to clear. - * For example, to clear bit 3 only, set uxBitsToClear to 0x08. To clear bit 3 - * and bit 0 set uxBitsToClear to 0x09. - * - * @return If the request to execute the function was posted successfully then - * pdPASS is returned, otherwise pdFALSE is returned. pdFALSE will be returned - * if the timer service queue was full. - * - * Example usage: -
-   #define BIT_0	( 1 << 0 )
-   #define BIT_4	( 1 << 4 )
-
-   // An event group which it is assumed has already been created by a call to
-   // xEventGroupCreate().
-   EventGroupHandle_t xEventGroup;
-
-   void anInterruptHandler( void )
-   {
-		// Clear bit 0 and bit 4 in xEventGroup.
-		xResult = xEventGroupClearBitsFromISR(
-							xEventGroup,	 // The event group being updated.
-							BIT_0 | BIT_4 ); // The bits being set.
-
-		if( xResult == pdPASS )
-		{
-			// The message was posted successfully.
-		}
-  }
-   
- * \defgroup xEventGroupClearBitsFromISR xEventGroupClearBitsFromISR - * \ingroup EventGroup - */ -#if( configUSE_TRACE_FACILITY == 1 ) - BaseType_t xEventGroupClearBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet ) PRIVILEGED_FUNCTION; -#else - #define xEventGroupClearBitsFromISR( xEventGroup, uxBitsToClear ) xTimerPendFunctionCallFromISR( vEventGroupClearBitsCallback, ( void * ) xEventGroup, ( uint32_t ) uxBitsToClear, NULL ) -#endif - -/** - * event_groups.h - *
-	EventBits_t xEventGroupSetBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet );
- 
- * - * Set bits within an event group. - * This function cannot be called from an interrupt. xEventGroupSetBitsFromISR() - * is a version that can be called from an interrupt. - * - * Setting bits in an event group will automatically unblock tasks that are - * blocked waiting for the bits. - * - * @param xEventGroup The event group in which the bits are to be set. - * - * @param uxBitsToSet A bitwise value that indicates the bit or bits to set. - * For example, to set bit 3 only, set uxBitsToSet to 0x08. To set bit 3 - * and bit 0 set uxBitsToSet to 0x09. - * - * @return The value of the event group at the time the call to - * xEventGroupSetBits() returns. There are two reasons why the returned value - * might have the bits specified by the uxBitsToSet parameter cleared. First, - * if setting a bit results in a task that was waiting for the bit leaving the - * blocked state then it is possible the bit will be cleared automatically - * (see the xClearBitOnExit parameter of xEventGroupWaitBits()). Second, any - * unblocked (or otherwise Ready state) task that has a priority above that of - * the task that called xEventGroupSetBits() will execute and may change the - * event group value before the call to xEventGroupSetBits() returns. - * - * Example usage: -
-   #define BIT_0	( 1 << 0 )
-   #define BIT_4	( 1 << 4 )
-
-   void aFunction( EventGroupHandle_t xEventGroup )
-   {
-   EventBits_t uxBits;
-
-		// Set bit 0 and bit 4 in xEventGroup.
-		uxBits = xEventGroupSetBits(
-							xEventGroup,	// The event group being updated.
-							BIT_0 | BIT_4 );// The bits being set.
-
-		if( ( uxBits & ( BIT_0 | BIT_4 ) ) == ( BIT_0 | BIT_4 ) )
-		{
-			// Both bit 0 and bit 4 remained set when the function returned.
-		}
-		else if( ( uxBits & BIT_0 ) != 0 )
-		{
-			// Bit 0 remained set when the function returned, but bit 4 was
-			// cleared.  It might be that bit 4 was cleared automatically as a
-			// task that was waiting for bit 4 was removed from the Blocked
-			// state.
-		}
-		else if( ( uxBits & BIT_4 ) != 0 )
-		{
-			// Bit 4 remained set when the function returned, but bit 0 was
-			// cleared.  It might be that bit 0 was cleared automatically as a
-			// task that was waiting for bit 0 was removed from the Blocked
-			// state.
-		}
-		else
-		{
-			// Neither bit 0 nor bit 4 remained set.  It might be that a task
-			// was waiting for both of the bits to be set, and the bits were
-			// cleared as the task left the Blocked state.
-		}
-   }
-   
- * \defgroup xEventGroupSetBits xEventGroupSetBits - * \ingroup EventGroup - */ -EventBits_t xEventGroupSetBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet ) PRIVILEGED_FUNCTION; - -/** - * event_groups.h - *
-	BaseType_t xEventGroupSetBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet, BaseType_t *pxHigherPriorityTaskWoken );
- 
- * - * A version of xEventGroupSetBits() that can be called from an interrupt. - * - * Setting bits in an event group is not a deterministic operation because there - * are an unknown number of tasks that may be waiting for the bit or bits being - * set. FreeRTOS does not allow nondeterministic operations to be performed in - * interrupts or from critical sections. Therefore xEventGroupSetBitsFromISR() - * sends a message to the timer task to have the set operation performed in the - * context of the timer task - where a scheduler lock is used in place of a - * critical section. - * - * @param xEventGroup The event group in which the bits are to be set. - * - * @param uxBitsToSet A bitwise value that indicates the bit or bits to set. - * For example, to set bit 3 only, set uxBitsToSet to 0x08. To set bit 3 - * and bit 0 set uxBitsToSet to 0x09. - * - * @param pxHigherPriorityTaskWoken As mentioned above, calling this function - * will result in a message being sent to the timer daemon task. If the - * priority of the timer daemon task is higher than the priority of the - * currently running task (the task the interrupt interrupted) then - * *pxHigherPriorityTaskWoken will be set to pdTRUE by - * xEventGroupSetBitsFromISR(), indicating that a context switch should be - * requested before the interrupt exits. For that reason - * *pxHigherPriorityTaskWoken must be initialised to pdFALSE. See the - * example code below. - * - * @return If the request to execute the function was posted successfully then - * pdPASS is returned, otherwise pdFALSE is returned. pdFALSE will be returned - * if the timer service queue was full. - * - * Example usage: -
-   #define BIT_0	( 1 << 0 )
-   #define BIT_4	( 1 << 4 )
-
-   // An event group which it is assumed has already been created by a call to
-   // xEventGroupCreate().
-   EventGroupHandle_t xEventGroup;
-
-   void anInterruptHandler( void )
-   {
-   BaseType_t xHigherPriorityTaskWoken, xResult;
-
-		// xHigherPriorityTaskWoken must be initialised to pdFALSE.
-		xHigherPriorityTaskWoken = pdFALSE;
-
-		// Set bit 0 and bit 4 in xEventGroup.
-		xResult = xEventGroupSetBitsFromISR(
-							xEventGroup,	// The event group being updated.
-							BIT_0 | BIT_4   // The bits being set.
-							&xHigherPriorityTaskWoken );
-
-		// Was the message posted successfully?
-		if( xResult == pdPASS )
-		{
-			// If xHigherPriorityTaskWoken is now set to pdTRUE then a context
-			// switch should be requested.  The macro used is port specific and
-			// will be either portYIELD_FROM_ISR() or portEND_SWITCHING_ISR() -
-			// refer to the documentation page for the port being used.
-			portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
-		}
-  }
-   
- * \defgroup xEventGroupSetBitsFromISR xEventGroupSetBitsFromISR - * \ingroup EventGroup - */ -#if( configUSE_TRACE_FACILITY == 1 ) - BaseType_t xEventGroupSetBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet, BaseType_t *pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; -#else - #define xEventGroupSetBitsFromISR( xEventGroup, uxBitsToSet, pxHigherPriorityTaskWoken ) xTimerPendFunctionCallFromISR( vEventGroupSetBitsCallback, ( void * ) xEventGroup, ( uint32_t ) uxBitsToSet, pxHigherPriorityTaskWoken ) -#endif - -/** - * event_groups.h - *
-	EventBits_t xEventGroupSync(	EventGroupHandle_t xEventGroup,
-									const EventBits_t uxBitsToSet,
-									const EventBits_t uxBitsToWaitFor,
-									TickType_t xTicksToWait );
- 
- * - * Atomically set bits within an event group, then wait for a combination of - * bits to be set within the same event group. This functionality is typically - * used to synchronise multiple tasks, where each task has to wait for the other - * tasks to reach a synchronisation point before proceeding. - * - * This function cannot be used from an interrupt. - * - * The function will return before its block time expires if the bits specified - * by the uxBitsToWait parameter are set, or become set within that time. In - * this case all the bits specified by uxBitsToWait will be automatically - * cleared before the function returns. - * - * @param xEventGroup The event group in which the bits are being tested. The - * event group must have previously been created using a call to - * xEventGroupCreate(). - * - * @param uxBitsToSet The bits to set in the event group before determining - * if, and possibly waiting for, all the bits specified by the uxBitsToWait - * parameter are set. - * - * @param uxBitsToWaitFor A bitwise value that indicates the bit or bits to test - * inside the event group. For example, to wait for bit 0 and bit 2 set - * uxBitsToWaitFor to 0x05. To wait for bits 0 and bit 1 and bit 2 set - * uxBitsToWaitFor to 0x07. Etc. - * - * @param xTicksToWait The maximum amount of time (specified in 'ticks') to wait - * for all of the bits specified by uxBitsToWaitFor to become set. - * - * @return The value of the event group at the time either the bits being waited - * for became set, or the block time expired. Test the return value to know - * which bits were set. If xEventGroupSync() returned because its timeout - * expired then not all the bits being waited for will be set. If - * xEventGroupSync() returned because all the bits it was waiting for were - * set then the returned value is the event group value before any bits were - * automatically cleared. - * - * Example usage: -
- // Bits used by the three tasks.
- #define TASK_0_BIT		( 1 << 0 )
- #define TASK_1_BIT		( 1 << 1 )
- #define TASK_2_BIT		( 1 << 2 )
-
- #define ALL_SYNC_BITS ( TASK_0_BIT | TASK_1_BIT | TASK_2_BIT )
-
- // Use an event group to synchronise three tasks.  It is assumed this event
- // group has already been created elsewhere.
- EventGroupHandle_t xEventBits;
-
- void vTask0( void *pvParameters )
- {
- EventBits_t uxReturn;
- TickType_t xTicksToWait = 100 / portTICK_PERIOD_MS;
-
-	 for( ;; )
-	 {
-		// Perform task functionality here.
-
-		// Set bit 0 in the event flag to note this task has reached the
-		// sync point.  The other two tasks will set the other two bits defined
-		// by ALL_SYNC_BITS.  All three tasks have reached the synchronisation
-		// point when all the ALL_SYNC_BITS are set.  Wait a maximum of 100ms
-		// for this to happen.
-		uxReturn = xEventGroupSync( xEventBits, TASK_0_BIT, ALL_SYNC_BITS, xTicksToWait );
-
-		if( ( uxReturn & ALL_SYNC_BITS ) == ALL_SYNC_BITS )
-		{
-			// All three tasks reached the synchronisation point before the call
-			// to xEventGroupSync() timed out.
-		}
-	}
- }
-
- void vTask1( void *pvParameters )
- {
-	 for( ;; )
-	 {
-		// Perform task functionality here.
-
-		// Set bit 1 in the event flag to note this task has reached the
-		// synchronisation point.  The other two tasks will set the other two
-		// bits defined by ALL_SYNC_BITS.  All three tasks have reached the
-		// synchronisation point when all the ALL_SYNC_BITS are set.  Wait
-		// indefinitely for this to happen.
-		xEventGroupSync( xEventBits, TASK_1_BIT, ALL_SYNC_BITS, portMAX_DELAY );
-
-		// xEventGroupSync() was called with an indefinite block time, so
-		// this task will only reach here if the syncrhonisation was made by all
-		// three tasks, so there is no need to test the return value.
-	 }
- }
-
- void vTask2( void *pvParameters )
- {
-	 for( ;; )
-	 {
-		// Perform task functionality here.
-
-		// Set bit 2 in the event flag to note this task has reached the
-		// synchronisation point.  The other two tasks will set the other two
-		// bits defined by ALL_SYNC_BITS.  All three tasks have reached the
-		// synchronisation point when all the ALL_SYNC_BITS are set.  Wait
-		// indefinitely for this to happen.
-		xEventGroupSync( xEventBits, TASK_2_BIT, ALL_SYNC_BITS, portMAX_DELAY );
-
-		// xEventGroupSync() was called with an indefinite block time, so
-		// this task will only reach here if the syncrhonisation was made by all
-		// three tasks, so there is no need to test the return value.
-	}
- }
-
- 
- * \defgroup xEventGroupSync xEventGroupSync - * \ingroup EventGroup - */ -EventBits_t xEventGroupSync( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet, const EventBits_t uxBitsToWaitFor, TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; - - -/** - * event_groups.h - *
-	EventBits_t xEventGroupGetBits( EventGroupHandle_t xEventGroup );
- 
- * - * Returns the current value of the bits in an event group. This function - * cannot be used from an interrupt. - * - * @param xEventGroup The event group being queried. - * - * @return The event group bits at the time xEventGroupGetBits() was called. - * - * \defgroup xEventGroupGetBits xEventGroupGetBits - * \ingroup EventGroup - */ -#define xEventGroupGetBits( xEventGroup ) xEventGroupClearBits( xEventGroup, 0 ) - -/** - * event_groups.h - *
-	EventBits_t xEventGroupGetBitsFromISR( EventGroupHandle_t xEventGroup );
- 
- * - * A version of xEventGroupGetBits() that can be called from an ISR. - * - * @param xEventGroup The event group being queried. - * - * @return The event group bits at the time xEventGroupGetBitsFromISR() was called. - * - * \defgroup xEventGroupGetBitsFromISR xEventGroupGetBitsFromISR - * \ingroup EventGroup - */ -EventBits_t xEventGroupGetBitsFromISR( EventGroupHandle_t xEventGroup ) PRIVILEGED_FUNCTION; - -/** - * event_groups.h - *
-	void xEventGroupDelete( EventGroupHandle_t xEventGroup );
- 
- * - * Delete an event group that was previously created by a call to - * xEventGroupCreate(). Tasks that are blocked on the event group will be - * unblocked and obtain 0 as the event group's value. - * - * @param xEventGroup The event group being deleted. - */ -void vEventGroupDelete( EventGroupHandle_t xEventGroup ) PRIVILEGED_FUNCTION; - -/* For internal use only. */ -void vEventGroupSetBitsCallback( void *pvEventGroup, const uint32_t ulBitsToSet ) PRIVILEGED_FUNCTION; -void vEventGroupClearBitsCallback( void *pvEventGroup, const uint32_t ulBitsToClear ) PRIVILEGED_FUNCTION; - - -#if (configUSE_TRACE_FACILITY == 1) - UBaseType_t uxEventGroupGetNumber( void* xEventGroup ) PRIVILEGED_FUNCTION; - void vEventGroupSetNumber( void* xEventGroup, UBaseType_t uxEventGroupNumber ) PRIVILEGED_FUNCTION; -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* EVENT_GROUPS_H */ - - diff --git a/lib/FreeRTOS/Source/include/list.h b/lib/FreeRTOS/Source/include/list.h deleted file mode 100644 index 4a3afa16..00000000 --- a/lib/FreeRTOS/Source/include/list.h +++ /dev/null @@ -1,411 +0,0 @@ -/* - * FreeRTOS Kernel V10.0.1 - * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * 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. - * - * http://www.FreeRTOS.org - * http://aws.amazon.com/freertos - * - * 1 tab == 4 spaces! - */ - -/* - * This is the list implementation used by the scheduler. While it is tailored - * heavily for the schedulers needs, it is also available for use by - * application code. - * - * list_ts can only store pointers to list_item_ts. Each ListItem_t contains a - * numeric value (xItemValue). Most of the time the lists are sorted in - * descending item value order. - * - * Lists are created already containing one list item. The value of this - * item is the maximum possible that can be stored, it is therefore always at - * the end of the list and acts as a marker. The list member pxHead always - * points to this marker - even though it is at the tail of the list. This - * is because the tail contains a wrap back pointer to the true head of - * the list. - * - * In addition to it's value, each list item contains a pointer to the next - * item in the list (pxNext), a pointer to the list it is in (pxContainer) - * and a pointer to back to the object that contains it. These later two - * pointers are included for efficiency of list manipulation. There is - * effectively a two way link between the object containing the list item and - * the list item itself. - * - * - * \page ListIntroduction List Implementation - * \ingroup FreeRTOSIntro - */ - -#ifndef INC_FREERTOS_H - #error FreeRTOS.h must be included before list.h -#endif - -#ifndef LIST_H -#define LIST_H - -/* - * The list structure members are modified from within interrupts, and therefore - * by rights should be declared volatile. However, they are only modified in a - * functionally atomic way (within critical sections of with the scheduler - * suspended) and are either passed by reference into a function or indexed via - * a volatile variable. Therefore, in all use cases tested so far, the volatile - * qualifier can be omitted in order to provide a moderate performance - * improvement without adversely affecting functional behaviour. The assembly - * instructions generated by the IAR, ARM and GCC compilers when the respective - * compiler's options were set for maximum optimisation has been inspected and - * deemed to be as intended. That said, as compiler technology advances, and - * especially if aggressive cross module optimisation is used (a use case that - * has not been exercised to any great extend) then it is feasible that the - * volatile qualifier will be needed for correct optimisation. It is expected - * that a compiler removing essential code because, without the volatile - * qualifier on the list structure members and with aggressive cross module - * optimisation, the compiler deemed the code unnecessary will result in - * complete and obvious failure of the scheduler. If this is ever experienced - * then the volatile qualifier can be inserted in the relevant places within the - * list structures by simply defining configLIST_VOLATILE to volatile in - * FreeRTOSConfig.h (as per the example at the bottom of this comment block). - * If configLIST_VOLATILE is not defined then the preprocessor directives below - * will simply #define configLIST_VOLATILE away completely. - * - * To use volatile list structure members then add the following line to - * FreeRTOSConfig.h (without the quotes): - * "#define configLIST_VOLATILE volatile" - */ -#ifndef configLIST_VOLATILE - #define configLIST_VOLATILE -#endif /* configSUPPORT_CROSS_MODULE_OPTIMISATION */ - -#ifdef __cplusplus -extern "C" { -#endif - -/* Macros that can be used to place known values within the list structures, -then check that the known values do not get corrupted during the execution of -the application. These may catch the list data structures being overwritten in -memory. They will not catch data errors caused by incorrect configuration or -use of FreeRTOS.*/ -#if( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 0 ) - /* Define the macros to do nothing. */ - #define listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE - #define listSECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE - #define listFIRST_LIST_INTEGRITY_CHECK_VALUE - #define listSECOND_LIST_INTEGRITY_CHECK_VALUE - #define listSET_FIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) - #define listSET_SECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) - #define listSET_LIST_INTEGRITY_CHECK_1_VALUE( pxList ) - #define listSET_LIST_INTEGRITY_CHECK_2_VALUE( pxList ) - #define listTEST_LIST_ITEM_INTEGRITY( pxItem ) - #define listTEST_LIST_INTEGRITY( pxList ) -#else - /* Define macros that add new members into the list structures. */ - #define listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE TickType_t xListItemIntegrityValue1; - #define listSECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE TickType_t xListItemIntegrityValue2; - #define listFIRST_LIST_INTEGRITY_CHECK_VALUE TickType_t xListIntegrityValue1; - #define listSECOND_LIST_INTEGRITY_CHECK_VALUE TickType_t xListIntegrityValue2; - - /* Define macros that set the new structure members to known values. */ - #define listSET_FIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) ( pxItem )->xListItemIntegrityValue1 = pdINTEGRITY_CHECK_VALUE - #define listSET_SECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) ( pxItem )->xListItemIntegrityValue2 = pdINTEGRITY_CHECK_VALUE - #define listSET_LIST_INTEGRITY_CHECK_1_VALUE( pxList ) ( pxList )->xListIntegrityValue1 = pdINTEGRITY_CHECK_VALUE - #define listSET_LIST_INTEGRITY_CHECK_2_VALUE( pxList ) ( pxList )->xListIntegrityValue2 = pdINTEGRITY_CHECK_VALUE - - /* Define macros that will assert if one of the structure members does not - contain its expected value. */ - #define listTEST_LIST_ITEM_INTEGRITY( pxItem ) configASSERT( ( ( pxItem )->xListItemIntegrityValue1 == pdINTEGRITY_CHECK_VALUE ) && ( ( pxItem )->xListItemIntegrityValue2 == pdINTEGRITY_CHECK_VALUE ) ) - #define listTEST_LIST_INTEGRITY( pxList ) configASSERT( ( ( pxList )->xListIntegrityValue1 == pdINTEGRITY_CHECK_VALUE ) && ( ( pxList )->xListIntegrityValue2 == pdINTEGRITY_CHECK_VALUE ) ) -#endif /* configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES */ - - -/* - * Definition of the only type of object that a list can contain. - */ -struct xLIST_ITEM -{ - listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ - configLIST_VOLATILE TickType_t xItemValue; /*< The value being listed. In most cases this is used to sort the list in descending order. */ - struct xLIST_ITEM * configLIST_VOLATILE pxNext; /*< Pointer to the next ListItem_t in the list. */ - struct xLIST_ITEM * configLIST_VOLATILE pxPrevious; /*< Pointer to the previous ListItem_t in the list. */ - void * pvOwner; /*< Pointer to the object (normally a TCB) that contains the list item. There is therefore a two way link between the object containing the list item and the list item itself. */ - void * configLIST_VOLATILE pvContainer; /*< Pointer to the list in which this list item is placed (if any). */ - listSECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ -}; -typedef struct xLIST_ITEM ListItem_t; /* For some reason lint wants this as two separate definitions. */ - -struct xMINI_LIST_ITEM -{ - listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ - configLIST_VOLATILE TickType_t xItemValue; - struct xLIST_ITEM * configLIST_VOLATILE pxNext; - struct xLIST_ITEM * configLIST_VOLATILE pxPrevious; -}; -typedef struct xMINI_LIST_ITEM MiniListItem_t; - -/* - * Definition of the type of queue used by the scheduler. - */ -typedef struct xLIST -{ - listFIRST_LIST_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ - volatile UBaseType_t uxNumberOfItems; - ListItem_t * configLIST_VOLATILE pxIndex; /*< Used to walk through the list. Points to the last item returned by a call to listGET_OWNER_OF_NEXT_ENTRY (). */ - MiniListItem_t xListEnd; /*< List item that contains the maximum possible item value meaning it is always at the end of the list and is therefore used as a marker. */ - listSECOND_LIST_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ -} List_t; - -/* - * Access macro to set the owner of a list item. The owner of a list item - * is the object (usually a TCB) that contains the list item. - * - * \page listSET_LIST_ITEM_OWNER listSET_LIST_ITEM_OWNER - * \ingroup LinkedList - */ -#define listSET_LIST_ITEM_OWNER( pxListItem, pxOwner ) ( ( pxListItem )->pvOwner = ( void * ) ( pxOwner ) ) - -/* - * Access macro to get the owner of a list item. The owner of a list item - * is the object (usually a TCB) that contains the list item. - * - * \page listSET_LIST_ITEM_OWNER listSET_LIST_ITEM_OWNER - * \ingroup LinkedList - */ -#define listGET_LIST_ITEM_OWNER( pxListItem ) ( ( pxListItem )->pvOwner ) - -/* - * Access macro to set the value of the list item. In most cases the value is - * used to sort the list in descending order. - * - * \page listSET_LIST_ITEM_VALUE listSET_LIST_ITEM_VALUE - * \ingroup LinkedList - */ -#define listSET_LIST_ITEM_VALUE( pxListItem, xValue ) ( ( pxListItem )->xItemValue = ( xValue ) ) - -/* - * Access macro to retrieve the value of the list item. The value can - * represent anything - for example the priority of a task, or the time at - * which a task should be unblocked. - * - * \page listGET_LIST_ITEM_VALUE listGET_LIST_ITEM_VALUE - * \ingroup LinkedList - */ -#define listGET_LIST_ITEM_VALUE( pxListItem ) ( ( pxListItem )->xItemValue ) - -/* - * Access macro to retrieve the value of the list item at the head of a given - * list. - * - * \page listGET_LIST_ITEM_VALUE listGET_LIST_ITEM_VALUE - * \ingroup LinkedList - */ -#define listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxList ) ( ( ( pxList )->xListEnd ).pxNext->xItemValue ) - -/* - * Return the list item at the head of the list. - * - * \page listGET_HEAD_ENTRY listGET_HEAD_ENTRY - * \ingroup LinkedList - */ -#define listGET_HEAD_ENTRY( pxList ) ( ( ( pxList )->xListEnd ).pxNext ) - -/* - * Return the list item at the head of the list. - * - * \page listGET_NEXT listGET_NEXT - * \ingroup LinkedList - */ -#define listGET_NEXT( pxListItem ) ( ( pxListItem )->pxNext ) - -/* - * Return the list item that marks the end of the list - * - * \page listGET_END_MARKER listGET_END_MARKER - * \ingroup LinkedList - */ -#define listGET_END_MARKER( pxList ) ( ( ListItem_t const * ) ( &( ( pxList )->xListEnd ) ) ) - -/* - * Access macro to determine if a list contains any items. The macro will - * only have the value true if the list is empty. - * - * \page listLIST_IS_EMPTY listLIST_IS_EMPTY - * \ingroup LinkedList - */ -#define listLIST_IS_EMPTY( pxList ) ( ( BaseType_t ) ( ( pxList )->uxNumberOfItems == ( UBaseType_t ) 0 ) ) - -/* - * Access macro to return the number of items in the list. - */ -#define listCURRENT_LIST_LENGTH( pxList ) ( ( pxList )->uxNumberOfItems ) - -/* - * Access function to obtain the owner of the next entry in a list. - * - * The list member pxIndex is used to walk through a list. Calling - * listGET_OWNER_OF_NEXT_ENTRY increments pxIndex to the next item in the list - * and returns that entry's pxOwner parameter. Using multiple calls to this - * function it is therefore possible to move through every item contained in - * a list. - * - * The pxOwner parameter of a list item is a pointer to the object that owns - * the list item. In the scheduler this is normally a task control block. - * The pxOwner parameter effectively creates a two way link between the list - * item and its owner. - * - * @param pxTCB pxTCB is set to the address of the owner of the next list item. - * @param pxList The list from which the next item owner is to be returned. - * - * \page listGET_OWNER_OF_NEXT_ENTRY listGET_OWNER_OF_NEXT_ENTRY - * \ingroup LinkedList - */ -#define listGET_OWNER_OF_NEXT_ENTRY( pxTCB, pxList ) \ -{ \ -List_t * const pxConstList = ( pxList ); \ - /* Increment the index to the next item and return the item, ensuring */ \ - /* we don't return the marker used at the end of the list. */ \ - ( pxConstList )->pxIndex = ( pxConstList )->pxIndex->pxNext; \ - if( ( void * ) ( pxConstList )->pxIndex == ( void * ) &( ( pxConstList )->xListEnd ) ) \ - { \ - ( pxConstList )->pxIndex = ( pxConstList )->pxIndex->pxNext; \ - } \ - ( pxTCB ) = ( pxConstList )->pxIndex->pvOwner; \ -} - - -/* - * Access function to obtain the owner of the first entry in a list. Lists - * are normally sorted in ascending item value order. - * - * This function returns the pxOwner member of the first item in the list. - * The pxOwner parameter of a list item is a pointer to the object that owns - * the list item. In the scheduler this is normally a task control block. - * The pxOwner parameter effectively creates a two way link between the list - * item and its owner. - * - * @param pxList The list from which the owner of the head item is to be - * returned. - * - * \page listGET_OWNER_OF_HEAD_ENTRY listGET_OWNER_OF_HEAD_ENTRY - * \ingroup LinkedList - */ -#define listGET_OWNER_OF_HEAD_ENTRY( pxList ) ( (&( ( pxList )->xListEnd ))->pxNext->pvOwner ) - -/* - * Check to see if a list item is within a list. The list item maintains a - * "container" pointer that points to the list it is in. All this macro does - * is check to see if the container and the list match. - * - * @param pxList The list we want to know if the list item is within. - * @param pxListItem The list item we want to know if is in the list. - * @return pdTRUE if the list item is in the list, otherwise pdFALSE. - */ -#define listIS_CONTAINED_WITHIN( pxList, pxListItem ) ( ( BaseType_t ) ( ( pxListItem )->pvContainer == ( void * ) ( pxList ) ) ) - -/* - * Return the list a list item is contained within (referenced from). - * - * @param pxListItem The list item being queried. - * @return A pointer to the List_t object that references the pxListItem - */ -#define listLIST_ITEM_CONTAINER( pxListItem ) ( ( pxListItem )->pvContainer ) - -/* - * This provides a crude means of knowing if a list has been initialised, as - * pxList->xListEnd.xItemValue is set to portMAX_DELAY by the vListInitialise() - * function. - */ -#define listLIST_IS_INITIALISED( pxList ) ( ( pxList )->xListEnd.xItemValue == portMAX_DELAY ) - -/* - * Must be called before a list is used! This initialises all the members - * of the list structure and inserts the xListEnd item into the list as a - * marker to the back of the list. - * - * @param pxList Pointer to the list being initialised. - * - * \page vListInitialise vListInitialise - * \ingroup LinkedList - */ -void vListInitialise( List_t * const pxList ) PRIVILEGED_FUNCTION; - -/* - * Must be called before a list item is used. This sets the list container to - * null so the item does not think that it is already contained in a list. - * - * @param pxItem Pointer to the list item being initialised. - * - * \page vListInitialiseItem vListInitialiseItem - * \ingroup LinkedList - */ -void vListInitialiseItem( ListItem_t * const pxItem ) PRIVILEGED_FUNCTION; - -/* - * Insert a list item into a list. The item will be inserted into the list in - * a position determined by its item value (descending item value order). - * - * @param pxList The list into which the item is to be inserted. - * - * @param pxNewListItem The item that is to be placed in the list. - * - * \page vListInsert vListInsert - * \ingroup LinkedList - */ -void vListInsert( List_t * const pxList, ListItem_t * const pxNewListItem ) PRIVILEGED_FUNCTION; - -/* - * Insert a list item into a list. The item will be inserted in a position - * such that it will be the last item within the list returned by multiple - * calls to listGET_OWNER_OF_NEXT_ENTRY. - * - * The list member pxIndex is used to walk through a list. Calling - * listGET_OWNER_OF_NEXT_ENTRY increments pxIndex to the next item in the list. - * Placing an item in a list using vListInsertEnd effectively places the item - * in the list position pointed to by pxIndex. This means that every other - * item within the list will be returned by listGET_OWNER_OF_NEXT_ENTRY before - * the pxIndex parameter again points to the item being inserted. - * - * @param pxList The list into which the item is to be inserted. - * - * @param pxNewListItem The list item to be inserted into the list. - * - * \page vListInsertEnd vListInsertEnd - * \ingroup LinkedList - */ -void vListInsertEnd( List_t * const pxList, ListItem_t * const pxNewListItem ) PRIVILEGED_FUNCTION; - -/* - * Remove an item from a list. The list item has a pointer to the list that - * it is in, so only the list item need be passed into the function. - * - * @param uxListRemove The item to be removed. The item will remove itself from - * the list pointed to by it's pxContainer parameter. - * - * @return The number of items that remain in the list after the list item has - * been removed. - * - * \page uxListRemove uxListRemove - * \ingroup LinkedList - */ -UBaseType_t uxListRemove( ListItem_t * const pxItemToRemove ) PRIVILEGED_FUNCTION; - -#ifdef __cplusplus -} -#endif - -#endif - diff --git a/lib/FreeRTOS/Source/include/message_buffer.h b/lib/FreeRTOS/Source/include/message_buffer.h deleted file mode 100644 index 91e34fa1..00000000 --- a/lib/FreeRTOS/Source/include/message_buffer.h +++ /dev/null @@ -1,779 +0,0 @@ -/* - * FreeRTOS Kernel V10.0.1 - * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * 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. - * - * http://www.FreeRTOS.org - * http://aws.amazon.com/freertos - * - * 1 tab == 4 spaces! - */ - - -/* - * Message buffers build functionality on top of FreeRTOS stream buffers. - * Whereas stream buffers are used to send a continuous stream of data from one - * task or interrupt to another, message buffers are used to send variable - * length discrete messages from one task or interrupt to another. Their - * implementation is light weight, making them particularly suited for interrupt - * to task and core to core communication scenarios. - * - * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer - * implementation (so also the message buffer implementation, as message buffers - * are built on top of stream buffers) assumes there is only one task or - * interrupt that will write to the buffer (the writer), and only one task or - * interrupt that will read from the buffer (the reader). It is safe for the - * writer and reader to be different tasks or interrupts, but, unlike other - * FreeRTOS objects, it is not safe to have multiple different writers or - * multiple different readers. If there are to be multiple different writers - * then the application writer must place each call to a writing API function - * (such as xMessageBufferSend()) inside a critical section and set the send - * block time to 0. Likewise, if there are to be multiple different readers - * then the application writer must place each call to a reading API function - * (such as xMessageBufferRead()) inside a critical section and set the receive - * timeout to 0. - * - * Message buffers hold variable length messages. To enable that, when a - * message is written to the message buffer an additional sizeof( size_t ) bytes - * are also written to store the message's length (that happens internally, with - * the API function). sizeof( size_t ) is typically 4 bytes on a 32-bit - * architecture, so writing a 10 byte message to a message buffer on a 32-bit - * architecture will actually reduce the available space in the message buffer - * by 14 bytes (10 byte are used by the message, and 4 bytes to hold the length - * of the message). - */ - -#ifndef FREERTOS_MESSAGE_BUFFER_H -#define FREERTOS_MESSAGE_BUFFER_H - -/* Message buffers are built onto of stream buffers. */ -#include "stream_buffer.h" - -#if defined( __cplusplus ) -extern "C" { -#endif - -/** - * Type by which message buffers are referenced. For example, a call to - * xMessageBufferCreate() returns an MessageBufferHandle_t variable that can - * then be used as a parameter to xMessageBufferSend(), xMessageBufferReceive(), - * etc. - */ -typedef void * MessageBufferHandle_t; - -/*-----------------------------------------------------------*/ - -/** - * message_buffer.h - * -
-MessageBufferHandle_t xMessageBufferCreate( size_t xBufferSizeBytes );
-
- * - * Creates a new message buffer using dynamically allocated memory. See - * xMessageBufferCreateStatic() for a version that uses statically allocated - * memory (memory that is allocated at compile time). - * - * configSUPPORT_DYNAMIC_ALLOCATION must be set to 1 or left undefined in - * FreeRTOSConfig.h for xMessageBufferCreate() to be available. - * - * @param xBufferSizeBytes The total number of bytes (not messages) the message - * buffer will be able to hold at any one time. When a message is written to - * the message buffer an additional sizeof( size_t ) bytes are also written to - * store the message's length. sizeof( size_t ) is typically 4 bytes on a - * 32-bit architecture, so on most 32-bit architectures a 10 byte message will - * take up 14 bytes of message buffer space. - * - * @return If NULL is returned, then the message buffer cannot be created - * because there is insufficient heap memory available for FreeRTOS to allocate - * the message buffer data structures and storage area. A non-NULL value being - * returned indicates that the message buffer has been created successfully - - * the returned value should be stored as the handle to the created message - * buffer. - * - * Example use: -
-
-void vAFunction( void )
-{
-MessageBufferHandle_t xMessageBuffer;
-const size_t xMessageBufferSizeBytes = 100;
-
-    // Create a message buffer that can hold 100 bytes.  The memory used to hold
-    // both the message buffer structure and the messages themselves is allocated
-    // dynamically.  Each message added to the buffer consumes an additional 4
-    // bytes which are used to hold the lengh of the message.
-    xMessageBuffer = xMessageBufferCreate( xMessageBufferSizeBytes );
-
-    if( xMessageBuffer == NULL )
-    {
-        // There was not enough heap memory space available to create the
-        // message buffer.
-    }
-    else
-    {
-        // The message buffer was created successfully and can now be used.
-    }
-
-
- * \defgroup xMessageBufferCreate xMessageBufferCreate - * \ingroup MessageBufferManagement - */ -#define xMessageBufferCreate( xBufferSizeBytes ) ( MessageBufferHandle_t ) xStreamBufferGenericCreate( xBufferSizeBytes, ( size_t ) 0, pdTRUE ) - -/** - * message_buffer.h - * -
-MessageBufferHandle_t xMessageBufferCreateStatic( size_t xBufferSizeBytes,
-                                                  uint8_t *pucMessageBufferStorageArea,
-                                                  StaticMessageBuffer_t *pxStaticMessageBuffer );
-
- * Creates a new message buffer using statically allocated memory. See - * xMessageBufferCreate() for a version that uses dynamically allocated memory. - * - * @param xBufferSizeBytes The size, in bytes, of the buffer pointed to by the - * pucMessageBufferStorageArea parameter. When a message is written to the - * message buffer an additional sizeof( size_t ) bytes are also written to store - * the message's length. sizeof( size_t ) is typically 4 bytes on a 32-bit - * architecture, so on most 32-bit architecture a 10 byte message will take up - * 14 bytes of message buffer space. The maximum number of bytes that can be - * stored in the message buffer is actually (xBufferSizeBytes - 1). - * - * @param pucMessageBufferStorageArea Must point to a uint8_t array that is at - * least xBufferSizeBytes + 1 big. This is the array to which messages are - * copied when they are written to the message buffer. - * - * @param pxStaticMessageBuffer Must point to a variable of type - * StaticMessageBuffer_t, which will be used to hold the message buffer's data - * structure. - * - * @return If the message buffer is created successfully then a handle to the - * created message buffer is returned. If either pucMessageBufferStorageArea or - * pxStaticmessageBuffer are NULL then NULL is returned. - * - * Example use: -
-
-// Used to dimension the array used to hold the messages.  The available space
-// will actually be one less than this, so 999.
-#define STORAGE_SIZE_BYTES 1000
-
-// Defines the memory that will actually hold the messages within the message
-// buffer.
-static uint8_t ucStorageBuffer[ STORAGE_SIZE_BYTES ];
-
-// The variable used to hold the message buffer structure.
-StaticMessageBuffer_t xMessageBufferStruct;
-
-void MyFunction( void )
-{
-MessageBufferHandle_t xMessageBuffer;
-
-    xMessageBuffer = xMessageBufferCreateStatic( sizeof( ucBufferStorage ),
-                                                 ucBufferStorage,
-                                                 &xMessageBufferStruct );
-
-    // As neither the pucMessageBufferStorageArea or pxStaticMessageBuffer
-    // parameters were NULL, xMessageBuffer will not be NULL, and can be used to
-    // reference the created message buffer in other message buffer API calls.
-
-    // Other code that uses the message buffer can go here.
-}
-
-
- * \defgroup xMessageBufferCreateStatic xMessageBufferCreateStatic - * \ingroup MessageBufferManagement - */ -#define xMessageBufferCreateStatic( xBufferSizeBytes, pucMessageBufferStorageArea, pxStaticMessageBuffer ) ( MessageBufferHandle_t ) xStreamBufferGenericCreateStatic( xBufferSizeBytes, 0, pdTRUE, pucMessageBufferStorageArea, pxStaticMessageBuffer ) - -/** - * message_buffer.h - * -
-size_t xMessageBufferSend( MessageBufferHandle_t xMessageBuffer,
-                           const void *pvTxData,
-                           size_t xDataLengthBytes,
-                           TickType_t xTicksToWait );
-
- *
- * Sends a discrete message to the message buffer.  The message can be any
- * length that fits within the buffer's free space, and is copied into the
- * buffer.
- *
- * ***NOTE***:  Uniquely among FreeRTOS objects, the stream buffer
- * implementation (so also the message buffer implementation, as message buffers
- * are built on top of stream buffers) assumes there is only one task or
- * interrupt that will write to the buffer (the writer), and only one task or
- * interrupt that will read from the buffer (the reader).  It is safe for the
- * writer and reader to be different tasks or interrupts, but, unlike other
- * FreeRTOS objects, it is not safe to have multiple different writers or
- * multiple different readers.  If there are to be multiple different writers
- * then the application writer must place each call to a writing API function
- * (such as xMessageBufferSend()) inside a critical section and set the send
- * block time to 0.  Likewise, if there are to be multiple different readers
- * then the application writer must place each call to a reading API function
- * (such as xMessageBufferRead()) inside a critical section and set the receive
- * block time to 0.
- *
- * Use xMessageBufferSend() to write to a message buffer from a task.  Use
- * xMessageBufferSendFromISR() to write to a message buffer from an interrupt
- * service routine (ISR).
- *
- * @param xMessageBuffer The handle of the message buffer to which a message is
- * being sent.
- *
- * @param pvTxData A pointer to the message that is to be copied into the
- * message buffer.
- *
- * @param xDataLengthBytes The length of the message.  That is, the number of
- * bytes to copy from pvTxData into the message buffer.  When a message is
- * written to the message buffer an additional sizeof( size_t ) bytes are also
- * written to store the message's length.  sizeof( size_t ) is typically 4 bytes
- * on a 32-bit architecture, so on most 32-bit architecture setting
- * xDataLengthBytes to 20 will reduce the free space in the message buffer by 24
- * bytes (20 bytes of message data and 4 bytes to hold the message length).
- *
- * @param xTicksToWait The maximum amount of time the calling task should remain
- * in the Blocked state to wait for enough space to become available in the
- * message buffer, should the message buffer have insufficient space when
- * xMessageBufferSend() is called.  The calling task will never block if
- * xTicksToWait is zero.  The block time is specified in tick periods, so the
- * absolute time it represents is dependent on the tick frequency.  The macro
- * pdMS_TO_TICKS() can be used to convert a time specified in milliseconds into
- * a time specified in ticks.  Setting xTicksToWait to portMAX_DELAY will cause
- * the task to wait indefinitely (without timing out), provided
- * INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h.  Tasks do not use any
- * CPU time when they are in the Blocked state.
- *
- * @return The number of bytes written to the message buffer.  If the call to
- * xMessageBufferSend() times out before there was enough space to write the
- * message into the message buffer then zero is returned.  If the call did not
- * time out then xDataLengthBytes is returned.
- *
- * Example use:
-
-void vAFunction( MessageBufferHandle_t xMessageBuffer )
-{
-size_t xBytesSent;
-uint8_t ucArrayToSend[] = { 0, 1, 2, 3 };
-char *pcStringToSend = "String to send";
-const TickType_t x100ms = pdMS_TO_TICKS( 100 );
-
-    // Send an array to the message buffer, blocking for a maximum of 100ms to
-    // wait for enough space to be available in the message buffer.
-    xBytesSent = xMessageBufferSend( xMessageBuffer, ( void * ) ucArrayToSend, sizeof( ucArrayToSend ), x100ms );
-
-    if( xBytesSent != sizeof( ucArrayToSend ) )
-    {
-        // The call to xMessageBufferSend() times out before there was enough
-        // space in the buffer for the data to be written.
-    }
-
-    // Send the string to the message buffer.  Return immediately if there is
-    // not enough space in the buffer.
-    xBytesSent = xMessageBufferSend( xMessageBuffer, ( void * ) pcStringToSend, strlen( pcStringToSend ), 0 );
-
-    if( xBytesSent != strlen( pcStringToSend ) )
-    {
-        // The string could not be added to the message buffer because there was
-        // not enough free space in the buffer.
-    }
-}
-
- * \defgroup xMessageBufferSend xMessageBufferSend - * \ingroup MessageBufferManagement - */ -#define xMessageBufferSend( xMessageBuffer, pvTxData, xDataLengthBytes, xTicksToWait ) xStreamBufferSend( ( StreamBufferHandle_t ) xMessageBuffer, pvTxData, xDataLengthBytes, xTicksToWait ) - -/** - * message_buffer.h - * -
-size_t xMessageBufferSendFromISR( MessageBufferHandle_t xMessageBuffer,
-                                  const void *pvTxData,
-                                  size_t xDataLengthBytes,
-                                  BaseType_t *pxHigherPriorityTaskWoken );
-
- *
- * Interrupt safe version of the API function that sends a discrete message to
- * the message buffer.  The message can be any length that fits within the
- * buffer's free space, and is copied into the buffer.
- *
- * ***NOTE***:  Uniquely among FreeRTOS objects, the stream buffer
- * implementation (so also the message buffer implementation, as message buffers
- * are built on top of stream buffers) assumes there is only one task or
- * interrupt that will write to the buffer (the writer), and only one task or
- * interrupt that will read from the buffer (the reader).  It is safe for the
- * writer and reader to be different tasks or interrupts, but, unlike other
- * FreeRTOS objects, it is not safe to have multiple different writers or
- * multiple different readers.  If there are to be multiple different writers
- * then the application writer must place each call to a writing API function
- * (such as xMessageBufferSend()) inside a critical section and set the send
- * block time to 0.  Likewise, if there are to be multiple different readers
- * then the application writer must place each call to a reading API function
- * (such as xMessageBufferRead()) inside a critical section and set the receive
- * block time to 0.
- *
- * Use xMessageBufferSend() to write to a message buffer from a task.  Use
- * xMessageBufferSendFromISR() to write to a message buffer from an interrupt
- * service routine (ISR).
- *
- * @param xMessageBuffer The handle of the message buffer to which a message is
- * being sent.
- *
- * @param pvTxData A pointer to the message that is to be copied into the
- * message buffer.
- *
- * @param xDataLengthBytes The length of the message.  That is, the number of
- * bytes to copy from pvTxData into the message buffer.  When a message is
- * written to the message buffer an additional sizeof( size_t ) bytes are also
- * written to store the message's length.  sizeof( size_t ) is typically 4 bytes
- * on a 32-bit architecture, so on most 32-bit architecture setting
- * xDataLengthBytes to 20 will reduce the free space in the message buffer by 24
- * bytes (20 bytes of message data and 4 bytes to hold the message length).
- *
- * @param pxHigherPriorityTaskWoken  It is possible that a message buffer will
- * have a task blocked on it waiting for data.  Calling
- * xMessageBufferSendFromISR() can make data available, and so cause a task that
- * was waiting for data to leave the Blocked state.  If calling
- * xMessageBufferSendFromISR() causes a task to leave the Blocked state, and the
- * unblocked task has a priority higher than the currently executing task (the
- * task that was interrupted), then, internally, xMessageBufferSendFromISR()
- * will set *pxHigherPriorityTaskWoken to pdTRUE.  If
- * xMessageBufferSendFromISR() sets this value to pdTRUE, then normally a
- * context switch should be performed before the interrupt is exited.  This will
- * ensure that the interrupt returns directly to the highest priority Ready
- * state task.  *pxHigherPriorityTaskWoken should be set to pdFALSE before it
- * is passed into the function.  See the code example below for an example.
- *
- * @return The number of bytes actually written to the message buffer.  If the
- * message buffer didn't have enough free space for the message to be stored
- * then 0 is returned, otherwise xDataLengthBytes is returned.
- *
- * Example use:
-
-// A message buffer that has already been created.
-MessageBufferHandle_t xMessageBuffer;
-
-void vAnInterruptServiceRoutine( void )
-{
-size_t xBytesSent;
-char *pcStringToSend = "String to send";
-BaseType_t xHigherPriorityTaskWoken = pdFALSE; // Initialised to pdFALSE.
-
-    // Attempt to send the string to the message buffer.
-    xBytesSent = xMessageBufferSendFromISR( xMessageBuffer,
-                                            ( void * ) pcStringToSend,
-                                            strlen( pcStringToSend ),
-                                            &xHigherPriorityTaskWoken );
-
-    if( xBytesSent != strlen( pcStringToSend ) )
-    {
-        // The string could not be added to the message buffer because there was
-        // not enough free space in the buffer.
-    }
-
-    // If xHigherPriorityTaskWoken was set to pdTRUE inside
-    // xMessageBufferSendFromISR() then a task that has a priority above the
-    // priority of the currently executing task was unblocked and a context
-    // switch should be performed to ensure the ISR returns to the unblocked
-    // task.  In most FreeRTOS ports this is done by simply passing
-    // xHigherPriorityTaskWoken into taskYIELD_FROM_ISR(), which will test the
-    // variables value, and perform the context switch if necessary.  Check the
-    // documentation for the port in use for port specific instructions.
-    taskYIELD_FROM_ISR( xHigherPriorityTaskWoken );
-}
-
- * \defgroup xMessageBufferSendFromISR xMessageBufferSendFromISR - * \ingroup MessageBufferManagement - */ -#define xMessageBufferSendFromISR( xMessageBuffer, pvTxData, xDataLengthBytes, pxHigherPriorityTaskWoken ) xStreamBufferSendFromISR( ( StreamBufferHandle_t ) xMessageBuffer, pvTxData, xDataLengthBytes, pxHigherPriorityTaskWoken ) - -/** - * message_buffer.h - * -
-size_t xMessageBufferReceive( MessageBufferHandle_t xMessageBuffer,
-                              void *pvRxData,
-                              size_t xBufferLengthBytes,
-                              TickType_t xTicksToWait );
-
- * - * Receives a discrete message from a message buffer. Messages can be of - * variable length and are copied out of the buffer. - * - * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer - * implementation (so also the message buffer implementation, as message buffers - * are built on top of stream buffers) assumes there is only one task or - * interrupt that will write to the buffer (the writer), and only one task or - * interrupt that will read from the buffer (the reader). It is safe for the - * writer and reader to be different tasks or interrupts, but, unlike other - * FreeRTOS objects, it is not safe to have multiple different writers or - * multiple different readers. If there are to be multiple different writers - * then the application writer must place each call to a writing API function - * (such as xMessageBufferSend()) inside a critical section and set the send - * block time to 0. Likewise, if there are to be multiple different readers - * then the application writer must place each call to a reading API function - * (such as xMessageBufferRead()) inside a critical section and set the receive - * block time to 0. - * - * Use xMessageBufferReceive() to read from a message buffer from a task. Use - * xMessageBufferReceiveFromISR() to read from a message buffer from an - * interrupt service routine (ISR). - * - * @param xMessageBuffer The handle of the message buffer from which a message - * is being received. - * - * @param pvRxData A pointer to the buffer into which the received message is - * to be copied. - * - * @param xBufferLengthBytes The length of the buffer pointed to by the pvRxData - * parameter. This sets the maximum length of the message that can be received. - * If xBufferLengthBytes is too small to hold the next message then the message - * will be left in the message buffer and 0 will be returned. - * - * @param xTicksToWait The maximum amount of time the task should remain in the - * Blocked state to wait for a message, should the message buffer be empty. - * xMessageBufferReceive() will return immediately if xTicksToWait is zero and - * the message buffer is empty. The block time is specified in tick periods, so - * the absolute time it represents is dependent on the tick frequency. The - * macro pdMS_TO_TICKS() can be used to convert a time specified in milliseconds - * into a time specified in ticks. Setting xTicksToWait to portMAX_DELAY will - * cause the task to wait indefinitely (without timing out), provided - * INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h. Tasks do not use any - * CPU time when they are in the Blocked state. - * - * @return The length, in bytes, of the message read from the message buffer, if - * any. If xMessageBufferReceive() times out before a message became available - * then zero is returned. If the length of the message is greater than - * xBufferLengthBytes then the message will be left in the message buffer and - * zero is returned. - * - * Example use: -
-void vAFunction( MessageBuffer_t xMessageBuffer )
-{
-uint8_t ucRxData[ 20 ];
-size_t xReceivedBytes;
-const TickType_t xBlockTime = pdMS_TO_TICKS( 20 );
-
-    // Receive the next message from the message buffer.  Wait in the Blocked
-    // state (so not using any CPU processing time) for a maximum of 100ms for
-    // a message to become available.
-    xReceivedBytes = xMessageBufferReceive( xMessageBuffer,
-                                            ( void * ) ucRxData,
-                                            sizeof( ucRxData ),
-                                            xBlockTime );
-
-    if( xReceivedBytes > 0 )
-    {
-        // A ucRxData contains a message that is xReceivedBytes long.  Process
-        // the message here....
-    }
-}
-
- * \defgroup xMessageBufferReceive xMessageBufferReceive - * \ingroup MessageBufferManagement - */ -#define xMessageBufferReceive( xMessageBuffer, pvRxData, xBufferLengthBytes, xTicksToWait ) xStreamBufferReceive( ( StreamBufferHandle_t ) xMessageBuffer, pvRxData, xBufferLengthBytes, xTicksToWait ) - - -/** - * message_buffer.h - * -
-size_t xMessageBufferReceiveFromISR( MessageBufferHandle_t xMessageBuffer,
-                                     void *pvRxData,
-                                     size_t xBufferLengthBytes,
-                                     BaseType_t *pxHigherPriorityTaskWoken );
-
- * - * An interrupt safe version of the API function that receives a discrete - * message from a message buffer. Messages can be of variable length and are - * copied out of the buffer. - * - * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer - * implementation (so also the message buffer implementation, as message buffers - * are built on top of stream buffers) assumes there is only one task or - * interrupt that will write to the buffer (the writer), and only one task or - * interrupt that will read from the buffer (the reader). It is safe for the - * writer and reader to be different tasks or interrupts, but, unlike other - * FreeRTOS objects, it is not safe to have multiple different writers or - * multiple different readers. If there are to be multiple different writers - * then the application writer must place each call to a writing API function - * (such as xMessageBufferSend()) inside a critical section and set the send - * block time to 0. Likewise, if there are to be multiple different readers - * then the application writer must place each call to a reading API function - * (such as xMessageBufferRead()) inside a critical section and set the receive - * block time to 0. - * - * Use xMessageBufferReceive() to read from a message buffer from a task. Use - * xMessageBufferReceiveFromISR() to read from a message buffer from an - * interrupt service routine (ISR). - * - * @param xMessageBuffer The handle of the message buffer from which a message - * is being received. - * - * @param pvRxData A pointer to the buffer into which the received message is - * to be copied. - * - * @param xBufferLengthBytes The length of the buffer pointed to by the pvRxData - * parameter. This sets the maximum length of the message that can be received. - * If xBufferLengthBytes is too small to hold the next message then the message - * will be left in the message buffer and 0 will be returned. - * - * @param pxHigherPriorityTaskWoken It is possible that a message buffer will - * have a task blocked on it waiting for space to become available. Calling - * xMessageBufferReceiveFromISR() can make space available, and so cause a task - * that is waiting for space to leave the Blocked state. If calling - * xMessageBufferReceiveFromISR() causes a task to leave the Blocked state, and - * the unblocked task has a priority higher than the currently executing task - * (the task that was interrupted), then, internally, - * xMessageBufferReceiveFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE. - * If xMessageBufferReceiveFromISR() sets this value to pdTRUE, then normally a - * context switch should be performed before the interrupt is exited. That will - * ensure the interrupt returns directly to the highest priority Ready state - * task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it is - * passed into the function. See the code example below for an example. - * - * @return The length, in bytes, of the message read from the message buffer, if - * any. - * - * Example use: -
-// A message buffer that has already been created.
-MessageBuffer_t xMessageBuffer;
-
-void vAnInterruptServiceRoutine( void )
-{
-uint8_t ucRxData[ 20 ];
-size_t xReceivedBytes;
-BaseType_t xHigherPriorityTaskWoken = pdFALSE;  // Initialised to pdFALSE.
-
-    // Receive the next message from the message buffer.
-    xReceivedBytes = xMessageBufferReceiveFromISR( xMessageBuffer,
-                                                  ( void * ) ucRxData,
-                                                  sizeof( ucRxData ),
-                                                  &xHigherPriorityTaskWoken );
-
-    if( xReceivedBytes > 0 )
-    {
-        // A ucRxData contains a message that is xReceivedBytes long.  Process
-        // the message here....
-    }
-
-    // If xHigherPriorityTaskWoken was set to pdTRUE inside
-    // xMessageBufferReceiveFromISR() then a task that has a priority above the
-    // priority of the currently executing task was unblocked and a context
-    // switch should be performed to ensure the ISR returns to the unblocked
-    // task.  In most FreeRTOS ports this is done by simply passing
-    // xHigherPriorityTaskWoken into taskYIELD_FROM_ISR(), which will test the
-    // variables value, and perform the context switch if necessary.  Check the
-    // documentation for the port in use for port specific instructions.
-    taskYIELD_FROM_ISR( xHigherPriorityTaskWoken );
-}
-
- * \defgroup xMessageBufferReceiveFromISR xMessageBufferReceiveFromISR - * \ingroup MessageBufferManagement - */ -#define xMessageBufferReceiveFromISR( xMessageBuffer, pvRxData, xBufferLengthBytes, pxHigherPriorityTaskWoken ) xStreamBufferReceiveFromISR( ( StreamBufferHandle_t ) xMessageBuffer, pvRxData, xBufferLengthBytes, pxHigherPriorityTaskWoken ) - -/** - * message_buffer.h - * -
-void vMessageBufferDelete( MessageBufferHandle_t xMessageBuffer );
-
- * - * Deletes a message buffer that was previously created using a call to - * xMessageBufferCreate() or xMessageBufferCreateStatic(). If the message - * buffer was created using dynamic memory (that is, by xMessageBufferCreate()), - * then the allocated memory is freed. - * - * A message buffer handle must not be used after the message buffer has been - * deleted. - * - * @param xMessageBuffer The handle of the message buffer to be deleted. - * - */ -#define vMessageBufferDelete( xMessageBuffer ) vStreamBufferDelete( ( StreamBufferHandle_t ) xMessageBuffer ) - -/** - * message_buffer.h -
-BaseType_t xMessageBufferIsFull( MessageBufferHandle_t xMessageBuffer ) );
-
- * - * Tests to see if a message buffer is full. A message buffer is full if it - * cannot accept any more messages, of any size, until space is made available - * by a message being removed from the message buffer. - * - * @param xMessageBuffer The handle of the message buffer being queried. - * - * @return If the message buffer referenced by xMessageBuffer is full then - * pdTRUE is returned. Otherwise pdFALSE is returned. - */ -#define xMessageBufferIsFull( xMessageBuffer ) xStreamBufferIsFull( ( StreamBufferHandle_t ) xMessageBuffer ) - -/** - * message_buffer.h -
-BaseType_t xMessageBufferIsEmpty( MessageBufferHandle_t xMessageBuffer ) );
-
- * - * Tests to see if a message buffer is empty (does not contain any messages). - * - * @param xMessageBuffer The handle of the message buffer being queried. - * - * @return If the message buffer referenced by xMessageBuffer is empty then - * pdTRUE is returned. Otherwise pdFALSE is returned. - * - */ -#define xMessageBufferIsEmpty( xMessageBuffer ) xStreamBufferIsEmpty( ( StreamBufferHandle_t ) xMessageBuffer ) - -/** - * message_buffer.h -
-BaseType_t xMessageBufferReset( MessageBufferHandle_t xMessageBuffer );
-
- * - * Resets a message buffer to its initial empty state, discarding any message it - * contained. - * - * A message buffer can only be reset if there are no tasks blocked on it. - * - * @param xMessageBuffer The handle of the message buffer being reset. - * - * @return If the message buffer was reset then pdPASS is returned. If the - * message buffer could not be reset because either there was a task blocked on - * the message queue to wait for space to become available, or to wait for a - * a message to be available, then pdFAIL is returned. - * - * \defgroup xMessageBufferReset xMessageBufferReset - * \ingroup MessageBufferManagement - */ -#define xMessageBufferReset( xMessageBuffer ) xStreamBufferReset( ( StreamBufferHandle_t ) xMessageBuffer ) - - -/** - * message_buffer.h -
-size_t xMessageBufferSpaceAvailable( MessageBufferHandle_t xMessageBuffer ) );
-
- * Returns the number of bytes of free space in the message buffer. - * - * @param xMessageBuffer The handle of the message buffer being queried. - * - * @return The number of bytes that can be written to the message buffer before - * the message buffer would be full. When a message is written to the message - * buffer an additional sizeof( size_t ) bytes are also written to store the - * message's length. sizeof( size_t ) is typically 4 bytes on a 32-bit - * architecture, so if xMessageBufferSpacesAvailable() returns 10, then the size - * of the largest message that can be written to the message buffer is 6 bytes. - * - * \defgroup xMessageBufferSpaceAvailable xMessageBufferSpaceAvailable - * \ingroup MessageBufferManagement - */ -#define xMessageBufferSpaceAvailable( xMessageBuffer ) xStreamBufferSpacesAvailable( ( StreamBufferHandle_t ) xMessageBuffer ) - -/** - * message_buffer.h - * -
-BaseType_t xMessageBufferSendCompletedFromISR( MessageBufferHandle_t xStreamBuffer, BaseType_t *pxHigherPriorityTaskWoken );
-
- * - * For advanced users only. - * - * The sbSEND_COMPLETED() macro is called from within the FreeRTOS APIs when - * data is sent to a message buffer or stream buffer. If there was a task that - * was blocked on the message or stream buffer waiting for data to arrive then - * the sbSEND_COMPLETED() macro sends a notification to the task to remove it - * from the Blocked state. xMessageBufferSendCompletedFromISR() does the same - * thing. It is provided to enable application writers to implement their own - * version of sbSEND_COMPLETED(), and MUST NOT BE USED AT ANY OTHER TIME. - * - * See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for - * additional information. - * - * @param xStreamBuffer The handle of the stream buffer to which data was - * written. - * - * @param pxHigherPriorityTaskWoken *pxHigherPriorityTaskWoken should be - * initialised to pdFALSE before it is passed into - * xMessageBufferSendCompletedFromISR(). If calling - * xMessageBufferSendCompletedFromISR() removes a task from the Blocked state, - * and the task has a priority above the priority of the currently running task, - * then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a - * context switch should be performed before exiting the ISR. - * - * @return If a task was removed from the Blocked state then pdTRUE is returned. - * Otherwise pdFALSE is returned. - * - * \defgroup xMessageBufferSendCompletedFromISR xMessageBufferSendCompletedFromISR - * \ingroup StreamBufferManagement - */ -#define xMessageBufferSendCompletedFromISR( xMessageBuffer, pxHigherPriorityTaskWoken ) xStreamBufferSendCompletedFromISR( ( StreamBufferHandle_t ) xMessageBuffer, pxHigherPriorityTaskWoken ) - -/** - * message_buffer.h - * -
-BaseType_t xMessageBufferReceiveCompletedFromISR( MessageBufferHandle_t xStreamBuffer, BaseType_t *pxHigherPriorityTaskWoken );
-
- * - * For advanced users only. - * - * The sbRECEIVE_COMPLETED() macro is called from within the FreeRTOS APIs when - * data is read out of a message buffer or stream buffer. If there was a task - * that was blocked on the message or stream buffer waiting for data to arrive - * then the sbRECEIVE_COMPLETED() macro sends a notification to the task to - * remove it from the Blocked state. xMessageBufferReceiveCompletedFromISR() - * does the same thing. It is provided to enable application writers to - * implement their own version of sbRECEIVE_COMPLETED(), and MUST NOT BE USED AT - * ANY OTHER TIME. - * - * See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for - * additional information. - * - * @param xStreamBuffer The handle of the stream buffer from which data was - * read. - * - * @param pxHigherPriorityTaskWoken *pxHigherPriorityTaskWoken should be - * initialised to pdFALSE before it is passed into - * xMessageBufferReceiveCompletedFromISR(). If calling - * xMessageBufferReceiveCompletedFromISR() removes a task from the Blocked state, - * and the task has a priority above the priority of the currently running task, - * then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a - * context switch should be performed before exiting the ISR. - * - * @return If a task was removed from the Blocked state then pdTRUE is returned. - * Otherwise pdFALSE is returned. - * - * \defgroup xMessageBufferReceiveCompletedFromISR xMessageBufferReceiveCompletedFromISR - * \ingroup StreamBufferManagement - */ -#define xMessageBufferReceiveCompletedFromISR( xMessageBuffer, pxHigherPriorityTaskWoken ) xStreamBufferReceiveCompletedFromISR( ( StreamBufferHandle_t ) xMessageBuffer, pxHigherPriorityTaskWoken ) - -#if defined( __cplusplus ) -} /* extern "C" */ -#endif - -#endif /* !defined( FREERTOS_MESSAGE_BUFFER_H ) */ diff --git a/lib/FreeRTOS/Source/include/mpu_prototypes.h b/lib/FreeRTOS/Source/include/mpu_prototypes.h deleted file mode 100644 index e2c89ab8..00000000 --- a/lib/FreeRTOS/Source/include/mpu_prototypes.h +++ /dev/null @@ -1,155 +0,0 @@ -/* - * FreeRTOS Kernel V10.0.1 - * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * 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. - * - * http://www.FreeRTOS.org - * http://aws.amazon.com/freertos - * - * 1 tab == 4 spaces! - */ - -/* - * When the MPU is used the standard (non MPU) API functions are mapped to - * equivalents that start "MPU_", the prototypes for which are defined in this - * header files. This will cause the application code to call the MPU_ version - * which wraps the non-MPU version with privilege promoting then demoting code, - * so the kernel code always runs will full privileges. - */ - - -#ifndef MPU_PROTOTYPES_H -#define MPU_PROTOTYPES_H - -/* MPU versions of tasks.h API functions. */ -BaseType_t MPU_xTaskCreate( TaskFunction_t pxTaskCode, const char * const pcName, const uint16_t usStackDepth, void * const pvParameters, UBaseType_t uxPriority, TaskHandle_t * const pxCreatedTask ); -TaskHandle_t MPU_xTaskCreateStatic( TaskFunction_t pxTaskCode, const char * const pcName, const uint32_t ulStackDepth, void * const pvParameters, UBaseType_t uxPriority, StackType_t * const puxStackBuffer, StaticTask_t * const pxTaskBuffer ); -BaseType_t MPU_xTaskCreateRestricted( const TaskParameters_t * const pxTaskDefinition, TaskHandle_t *pxCreatedTask ); -BaseType_t MPU_xTaskCreateRestrictedStatic( const TaskParameters_t * const pxTaskDefinition, TaskHandle_t *pxCreatedTask ); -void MPU_vTaskAllocateMPURegions( TaskHandle_t xTask, const MemoryRegion_t * const pxRegions ); -void MPU_vTaskDelete( TaskHandle_t xTaskToDelete ); -void MPU_vTaskDelay( const TickType_t xTicksToDelay ); -void MPU_vTaskDelayUntil( TickType_t * const pxPreviousWakeTime, const TickType_t xTimeIncrement ); -BaseType_t MPU_xTaskAbortDelay( TaskHandle_t xTask ); -UBaseType_t MPU_uxTaskPriorityGet( TaskHandle_t xTask ); -eTaskState MPU_eTaskGetState( TaskHandle_t xTask ); -void MPU_vTaskGetInfo( TaskHandle_t xTask, TaskStatus_t *pxTaskStatus, BaseType_t xGetFreeStackSpace, eTaskState eState ); -void MPU_vTaskPrioritySet( TaskHandle_t xTask, UBaseType_t uxNewPriority ); -void MPU_vTaskSuspend( TaskHandle_t xTaskToSuspend ); -void MPU_vTaskResume( TaskHandle_t xTaskToResume ); -void MPU_vTaskStartScheduler( void ); -void MPU_vTaskSuspendAll( void ); -BaseType_t MPU_xTaskResumeAll( void ); -TickType_t MPU_xTaskGetTickCount( void ); -UBaseType_t MPU_uxTaskGetNumberOfTasks( void ); -char * MPU_pcTaskGetName( TaskHandle_t xTaskToQuery ); -TaskHandle_t MPU_xTaskGetHandle( const char *pcNameToQuery ); -UBaseType_t MPU_uxTaskGetStackHighWaterMark( TaskHandle_t xTask ); -void MPU_vTaskSetApplicationTaskTag( TaskHandle_t xTask, TaskHookFunction_t pxHookFunction ); -TaskHookFunction_t MPU_xTaskGetApplicationTaskTag( TaskHandle_t xTask ); -void MPU_vTaskSetThreadLocalStoragePointer( TaskHandle_t xTaskToSet, BaseType_t xIndex, void *pvValue ); -void * MPU_pvTaskGetThreadLocalStoragePointer( TaskHandle_t xTaskToQuery, BaseType_t xIndex ); -BaseType_t MPU_xTaskCallApplicationTaskHook( TaskHandle_t xTask, void *pvParameter ); -TaskHandle_t MPU_xTaskGetIdleTaskHandle( void ); -UBaseType_t MPU_uxTaskGetSystemState( TaskStatus_t * const pxTaskStatusArray, const UBaseType_t uxArraySize, uint32_t * const pulTotalRunTime ); -void MPU_vTaskList( char * pcWriteBuffer ); -void MPU_vTaskGetRunTimeStats( char *pcWriteBuffer ); -BaseType_t MPU_xTaskGenericNotify( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotificationValue ); -BaseType_t MPU_xTaskNotifyWait( uint32_t ulBitsToClearOnEntry, uint32_t ulBitsToClearOnExit, uint32_t *pulNotificationValue, TickType_t xTicksToWait ); -uint32_t MPU_ulTaskNotifyTake( BaseType_t xClearCountOnExit, TickType_t xTicksToWait ); -BaseType_t MPU_xTaskNotifyStateClear( TaskHandle_t xTask ); -BaseType_t MPU_xTaskIncrementTick( void ); -TaskHandle_t MPU_xTaskGetCurrentTaskHandle( void ); -void MPU_vTaskSetTimeOutState( TimeOut_t * const pxTimeOut ); -BaseType_t MPU_xTaskCheckForTimeOut( TimeOut_t * const pxTimeOut, TickType_t * const pxTicksToWait ); -void MPU_vTaskMissedYield( void ); -BaseType_t MPU_xTaskGetSchedulerState( void ); - -/* MPU versions of queue.h API functions. */ -BaseType_t MPU_xQueueGenericSend( QueueHandle_t xQueue, const void * const pvItemToQueue, TickType_t xTicksToWait, const BaseType_t xCopyPosition ); -BaseType_t MPU_xQueueReceive( QueueHandle_t xQueue, void * const pvBuffer, TickType_t xTicksToWait ); -BaseType_t MPU_xQueuePeek( QueueHandle_t xQueue, void * const pvBuffer, TickType_t xTicksToWait ); -BaseType_t MPU_xQueueSemaphoreTake( QueueHandle_t xQueue, TickType_t xTicksToWait ); -UBaseType_t MPU_uxQueueMessagesWaiting( const QueueHandle_t xQueue ); -UBaseType_t MPU_uxQueueSpacesAvailable( const QueueHandle_t xQueue ); -void MPU_vQueueDelete( QueueHandle_t xQueue ); -QueueHandle_t MPU_xQueueCreateMutex( const uint8_t ucQueueType ); -QueueHandle_t MPU_xQueueCreateMutexStatic( const uint8_t ucQueueType, StaticQueue_t *pxStaticQueue ); -QueueHandle_t MPU_xQueueCreateCountingSemaphore( const UBaseType_t uxMaxCount, const UBaseType_t uxInitialCount ); -QueueHandle_t MPU_xQueueCreateCountingSemaphoreStatic( const UBaseType_t uxMaxCount, const UBaseType_t uxInitialCount, StaticQueue_t *pxStaticQueue ); -void* MPU_xQueueGetMutexHolder( QueueHandle_t xSemaphore ); -BaseType_t MPU_xQueueTakeMutexRecursive( QueueHandle_t xMutex, TickType_t xTicksToWait ); -BaseType_t MPU_xQueueGiveMutexRecursive( QueueHandle_t pxMutex ); -void MPU_vQueueAddToRegistry( QueueHandle_t xQueue, const char *pcName ); -void MPU_vQueueUnregisterQueue( QueueHandle_t xQueue ); -const char * MPU_pcQueueGetName( QueueHandle_t xQueue ); -QueueHandle_t MPU_xQueueGenericCreate( const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, const uint8_t ucQueueType ); -QueueHandle_t MPU_xQueueGenericCreateStatic( const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, uint8_t *pucQueueStorage, StaticQueue_t *pxStaticQueue, const uint8_t ucQueueType ); -QueueSetHandle_t MPU_xQueueCreateSet( const UBaseType_t uxEventQueueLength ); -BaseType_t MPU_xQueueAddToSet( QueueSetMemberHandle_t xQueueOrSemaphore, QueueSetHandle_t xQueueSet ); -BaseType_t MPU_xQueueRemoveFromSet( QueueSetMemberHandle_t xQueueOrSemaphore, QueueSetHandle_t xQueueSet ); -QueueSetMemberHandle_t MPU_xQueueSelectFromSet( QueueSetHandle_t xQueueSet, const TickType_t xTicksToWait ); -BaseType_t MPU_xQueueGenericReset( QueueHandle_t xQueue, BaseType_t xNewQueue ); -void MPU_vQueueSetQueueNumber( QueueHandle_t xQueue, UBaseType_t uxQueueNumber ); -UBaseType_t MPU_uxQueueGetQueueNumber( QueueHandle_t xQueue ); -uint8_t MPU_ucQueueGetQueueType( QueueHandle_t xQueue ); - -/* MPU versions of timers.h API functions. */ -TimerHandle_t MPU_xTimerCreate( const char * const pcTimerName, const TickType_t xTimerPeriodInTicks, const UBaseType_t uxAutoReload, void * const pvTimerID, TimerCallbackFunction_t pxCallbackFunction ); -TimerHandle_t MPU_xTimerCreateStatic( const char * const pcTimerName, const TickType_t xTimerPeriodInTicks, const UBaseType_t uxAutoReload, void * const pvTimerID, TimerCallbackFunction_t pxCallbackFunction, StaticTimer_t *pxTimerBuffer ); -void * MPU_pvTimerGetTimerID( const TimerHandle_t xTimer ); -void MPU_vTimerSetTimerID( TimerHandle_t xTimer, void *pvNewID ); -BaseType_t MPU_xTimerIsTimerActive( TimerHandle_t xTimer ); -TaskHandle_t MPU_xTimerGetTimerDaemonTaskHandle( void ); -BaseType_t MPU_xTimerPendFunctionCall( PendedFunction_t xFunctionToPend, void *pvParameter1, uint32_t ulParameter2, TickType_t xTicksToWait ); -const char * MPU_pcTimerGetName( TimerHandle_t xTimer ); -TickType_t MPU_xTimerGetPeriod( TimerHandle_t xTimer ); -TickType_t MPU_xTimerGetExpiryTime( TimerHandle_t xTimer ); -BaseType_t MPU_xTimerCreateTimerTask( void ); -BaseType_t MPU_xTimerGenericCommand( TimerHandle_t xTimer, const BaseType_t xCommandID, const TickType_t xOptionalValue, BaseType_t * const pxHigherPriorityTaskWoken, const TickType_t xTicksToWait ); - -/* MPU versions of event_group.h API functions. */ -EventGroupHandle_t MPU_xEventGroupCreate( void ); -EventGroupHandle_t MPU_xEventGroupCreateStatic( StaticEventGroup_t *pxEventGroupBuffer ); -EventBits_t MPU_xEventGroupWaitBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToWaitFor, const BaseType_t xClearOnExit, const BaseType_t xWaitForAllBits, TickType_t xTicksToWait ); -EventBits_t MPU_xEventGroupClearBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToClear ); -EventBits_t MPU_xEventGroupSetBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet ); -EventBits_t MPU_xEventGroupSync( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet, const EventBits_t uxBitsToWaitFor, TickType_t xTicksToWait ); -void MPU_vEventGroupDelete( EventGroupHandle_t xEventGroup ); -UBaseType_t MPU_uxEventGroupGetNumber( void* xEventGroup ); - -/* MPU versions of message/stream_buffer.h API functions. */ -size_t MPU_xStreamBufferSend( StreamBufferHandle_t xStreamBuffer, const void *pvTxData, size_t xDataLengthBytes, TickType_t xTicksToWait ); -size_t MPU_xStreamBufferSendFromISR( StreamBufferHandle_t xStreamBuffer, const void *pvTxData, size_t xDataLengthBytes, BaseType_t * const pxHigherPriorityTaskWoken ); -size_t MPU_xStreamBufferReceive( StreamBufferHandle_t xStreamBuffer, void *pvRxData, size_t xBufferLengthBytes, TickType_t xTicksToWait ); -size_t MPU_xStreamBufferReceiveFromISR( StreamBufferHandle_t xStreamBuffer, void *pvRxData, size_t xBufferLengthBytes, BaseType_t * const pxHigherPriorityTaskWoken ); -void MPU_vStreamBufferDelete( StreamBufferHandle_t xStreamBuffer ); -BaseType_t MPU_xStreamBufferIsFull( StreamBufferHandle_t xStreamBuffer ); -BaseType_t MPU_xStreamBufferIsEmpty( StreamBufferHandle_t xStreamBuffer ); -BaseType_t MPU_xStreamBufferReset( StreamBufferHandle_t xStreamBuffer ); -size_t MPU_xStreamBufferSpacesAvailable( StreamBufferHandle_t xStreamBuffer ); -size_t MPU_xStreamBufferBytesAvailable( StreamBufferHandle_t xStreamBuffer ); -BaseType_t MPU_xStreamBufferSetTriggerLevel( StreamBufferHandle_t xStreamBuffer, size_t xTriggerLevel ); -StreamBufferHandle_t MPU_xStreamBufferGenericCreate( size_t xBufferSizeBytes, size_t xTriggerLevelBytes, BaseType_t xIsMessageBuffer ); -StreamBufferHandle_t MPU_xStreamBufferGenericCreateStatic( size_t xBufferSizeBytes, size_t xTriggerLevelBytes, BaseType_t xIsMessageBuffer, uint8_t * const pucStreamBufferStorageArea, StaticStreamBuffer_t * const pxStaticStreamBuffer ); - - - -#endif /* MPU_PROTOTYPES_H */ - diff --git a/lib/FreeRTOS/Source/include/mpu_wrappers.h b/lib/FreeRTOS/Source/include/mpu_wrappers.h deleted file mode 100644 index eb326e76..00000000 --- a/lib/FreeRTOS/Source/include/mpu_wrappers.h +++ /dev/null @@ -1,181 +0,0 @@ -/* - * FreeRTOS Kernel V10.0.1 - * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * 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. - * - * http://www.FreeRTOS.org - * http://aws.amazon.com/freertos - * - * 1 tab == 4 spaces! - */ - -#ifndef MPU_WRAPPERS_H -#define MPU_WRAPPERS_H - -/* This file redefines API functions to be called through a wrapper macro, but -only for ports that are using the MPU. */ -#ifdef portUSING_MPU_WRAPPERS - - /* MPU_WRAPPERS_INCLUDED_FROM_API_FILE will be defined when this file is - included from queue.c or task.c to prevent it from having an effect within - those files. */ - #ifndef MPU_WRAPPERS_INCLUDED_FROM_API_FILE - - /* - * Map standard (non MPU) API functions to equivalents that start - * "MPU_". This will cause the application code to call the MPU_ - * version, which wraps the non-MPU version with privilege promoting - * then demoting code, so the kernel code always runs will full - * privileges. - */ - - /* Map standard tasks.h API functions to the MPU equivalents. */ - #define xTaskCreate MPU_xTaskCreate - #define xTaskCreateStatic MPU_xTaskCreateStatic - #define xTaskCreateRestricted MPU_xTaskCreateRestricted - #define vTaskAllocateMPURegions MPU_vTaskAllocateMPURegions - #define vTaskDelete MPU_vTaskDelete - #define vTaskDelay MPU_vTaskDelay - #define vTaskDelayUntil MPU_vTaskDelayUntil - #define xTaskAbortDelay MPU_xTaskAbortDelay - #define uxTaskPriorityGet MPU_uxTaskPriorityGet - #define eTaskGetState MPU_eTaskGetState - #define vTaskGetInfo MPU_vTaskGetInfo - #define vTaskPrioritySet MPU_vTaskPrioritySet - #define vTaskSuspend MPU_vTaskSuspend - #define vTaskResume MPU_vTaskResume - #define vTaskSuspendAll MPU_vTaskSuspendAll - #define xTaskResumeAll MPU_xTaskResumeAll - #define xTaskGetTickCount MPU_xTaskGetTickCount - #define uxTaskGetNumberOfTasks MPU_uxTaskGetNumberOfTasks - #define pcTaskGetName MPU_pcTaskGetName - #define xTaskGetHandle MPU_xTaskGetHandle - #define uxTaskGetStackHighWaterMark MPU_uxTaskGetStackHighWaterMark - #define vTaskSetApplicationTaskTag MPU_vTaskSetApplicationTaskTag - #define xTaskGetApplicationTaskTag MPU_xTaskGetApplicationTaskTag - #define vTaskSetThreadLocalStoragePointer MPU_vTaskSetThreadLocalStoragePointer - #define pvTaskGetThreadLocalStoragePointer MPU_pvTaskGetThreadLocalStoragePointer - #define xTaskCallApplicationTaskHook MPU_xTaskCallApplicationTaskHook - #define xTaskGetIdleTaskHandle MPU_xTaskGetIdleTaskHandle - #define uxTaskGetSystemState MPU_uxTaskGetSystemState - #define vTaskList MPU_vTaskList - #define vTaskGetRunTimeStats MPU_vTaskGetRunTimeStats - #define xTaskGenericNotify MPU_xTaskGenericNotify - #define xTaskNotifyWait MPU_xTaskNotifyWait - #define ulTaskNotifyTake MPU_ulTaskNotifyTake - #define xTaskNotifyStateClear MPU_xTaskNotifyStateClear - - #define xTaskGetCurrentTaskHandle MPU_xTaskGetCurrentTaskHandle - #define vTaskSetTimeOutState MPU_vTaskSetTimeOutState - #define xTaskCheckForTimeOut MPU_xTaskCheckForTimeOut - #define xTaskGetSchedulerState MPU_xTaskGetSchedulerState - - /* Map standard queue.h API functions to the MPU equivalents. */ - #define xQueueGenericSend MPU_xQueueGenericSend - #define xQueueReceive MPU_xQueueReceive - #define xQueuePeek MPU_xQueuePeek - #define xQueueSemaphoreTake MPU_xQueueSemaphoreTake - #define uxQueueMessagesWaiting MPU_uxQueueMessagesWaiting - #define uxQueueSpacesAvailable MPU_uxQueueSpacesAvailable - #define vQueueDelete MPU_vQueueDelete - #define xQueueCreateMutex MPU_xQueueCreateMutex - #define xQueueCreateMutexStatic MPU_xQueueCreateMutexStatic - #define xQueueCreateCountingSemaphore MPU_xQueueCreateCountingSemaphore - #define xQueueCreateCountingSemaphoreStatic MPU_xQueueCreateCountingSemaphoreStatic - #define xQueueGetMutexHolder MPU_xQueueGetMutexHolder - #define xQueueTakeMutexRecursive MPU_xQueueTakeMutexRecursive - #define xQueueGiveMutexRecursive MPU_xQueueGiveMutexRecursive - #define xQueueGenericCreate MPU_xQueueGenericCreate - #define xQueueGenericCreateStatic MPU_xQueueGenericCreateStatic - #define xQueueCreateSet MPU_xQueueCreateSet - #define xQueueAddToSet MPU_xQueueAddToSet - #define xQueueRemoveFromSet MPU_xQueueRemoveFromSet - #define xQueueSelectFromSet MPU_xQueueSelectFromSet - #define xQueueGenericReset MPU_xQueueGenericReset - - #if( configQUEUE_REGISTRY_SIZE > 0 ) - #define vQueueAddToRegistry MPU_vQueueAddToRegistry - #define vQueueUnregisterQueue MPU_vQueueUnregisterQueue - #define pcQueueGetName MPU_pcQueueGetName - #endif - - /* Map standard timer.h API functions to the MPU equivalents. */ - #define xTimerCreate MPU_xTimerCreate - #define xTimerCreateStatic MPU_xTimerCreateStatic - #define pvTimerGetTimerID MPU_pvTimerGetTimerID - #define vTimerSetTimerID MPU_vTimerSetTimerID - #define xTimerIsTimerActive MPU_xTimerIsTimerActive - #define xTimerGetTimerDaemonTaskHandle MPU_xTimerGetTimerDaemonTaskHandle - #define xTimerPendFunctionCall MPU_xTimerPendFunctionCall - #define pcTimerGetName MPU_pcTimerGetName - #define xTimerGetPeriod MPU_xTimerGetPeriod - #define xTimerGetExpiryTime MPU_xTimerGetExpiryTime - #define xTimerGenericCommand MPU_xTimerGenericCommand - - /* Map standard event_group.h API functions to the MPU equivalents. */ - #define xEventGroupCreate MPU_xEventGroupCreate - #define xEventGroupCreateStatic MPU_xEventGroupCreateStatic - #define xEventGroupWaitBits MPU_xEventGroupWaitBits - #define xEventGroupClearBits MPU_xEventGroupClearBits - #define xEventGroupSetBits MPU_xEventGroupSetBits - #define xEventGroupSync MPU_xEventGroupSync - #define vEventGroupDelete MPU_vEventGroupDelete - - /* Map standard message/stream_buffer.h API functions to the MPU - equivalents. */ - #define xStreamBufferSend MPU_xStreamBufferSend - #define xStreamBufferSendFromISR MPU_xStreamBufferSendFromISR - #define xStreamBufferReceive MPU_xStreamBufferReceive - #define xStreamBufferReceiveFromISR MPU_xStreamBufferReceiveFromISR - #define vStreamBufferDelete MPU_vStreamBufferDelete - #define xStreamBufferIsFull MPU_xStreamBufferIsFull - #define xStreamBufferIsEmpty MPU_xStreamBufferIsEmpty - #define xStreamBufferReset MPU_xStreamBufferReset - #define xStreamBufferSpacesAvailable MPU_xStreamBufferSpacesAvailable - #define xStreamBufferBytesAvailable MPU_xStreamBufferBytesAvailable - #define xStreamBufferSetTriggerLevel MPU_xStreamBufferSetTriggerLevel - #define xStreamBufferGenericCreate MPU_xStreamBufferGenericCreate - #define xStreamBufferGenericCreateStatic MPU_xStreamBufferGenericCreateStatic - - - /* Remove the privileged function macro, but keep the PRIVILEGED_DATA - macro so applications can place data in privileged access sections - (useful when using statically allocated objects). */ - #define PRIVILEGED_FUNCTION - #define PRIVILEGED_DATA __attribute__((section("privileged_data"))) - - #else /* MPU_WRAPPERS_INCLUDED_FROM_API_FILE */ - - /* Ensure API functions go in the privileged execution section. */ - #define PRIVILEGED_FUNCTION __attribute__((section("privileged_functions"))) - #define PRIVILEGED_DATA __attribute__((section("privileged_data"))) - - #endif /* MPU_WRAPPERS_INCLUDED_FROM_API_FILE */ - -#else /* portUSING_MPU_WRAPPERS */ - - #define PRIVILEGED_FUNCTION - #define PRIVILEGED_DATA - #define portUSING_MPU_WRAPPERS 0 - -#endif /* portUSING_MPU_WRAPPERS */ - - -#endif /* MPU_WRAPPERS_H */ - diff --git a/lib/FreeRTOS/Source/include/portable.h b/lib/FreeRTOS/Source/include/portable.h deleted file mode 100644 index 3d0ef0a6..00000000 --- a/lib/FreeRTOS/Source/include/portable.h +++ /dev/null @@ -1,165 +0,0 @@ -/* - * FreeRTOS Kernel V10.0.1 - * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * 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. - * - * http://www.FreeRTOS.org - * http://aws.amazon.com/freertos - * - * 1 tab == 4 spaces! - */ - -/*----------------------------------------------------------- - * Portable layer API. Each function must be defined for each port. - *----------------------------------------------------------*/ - -#ifndef PORTABLE_H -#define PORTABLE_H - -/* Each FreeRTOS port has a unique portmacro.h header file. Originally a -pre-processor definition was used to ensure the pre-processor found the correct -portmacro.h file for the port being used. That scheme was deprecated in favour -of setting the compiler's include path such that it found the correct -portmacro.h file - removing the need for the constant and allowing the -portmacro.h file to be located anywhere in relation to the port being used. -Purely for reasons of backward compatibility the old method is still valid, but -to make it clear that new projects should not use it, support for the port -specific constants has been moved into the deprecated_definitions.h header -file. */ -#include "deprecated_definitions.h" - -/* If portENTER_CRITICAL is not defined then including deprecated_definitions.h -did not result in a portmacro.h header file being included - and it should be -included here. In this case the path to the correct portmacro.h header file -must be set in the compiler's include path. */ -#ifndef portENTER_CRITICAL - #include "portmacro.h" -#endif - -#if portBYTE_ALIGNMENT == 32 - #define portBYTE_ALIGNMENT_MASK ( 0x001f ) -#endif - -#if portBYTE_ALIGNMENT == 16 - #define portBYTE_ALIGNMENT_MASK ( 0x000f ) -#endif - -#if portBYTE_ALIGNMENT == 8 - #define portBYTE_ALIGNMENT_MASK ( 0x0007 ) -#endif - -#if portBYTE_ALIGNMENT == 4 - #define portBYTE_ALIGNMENT_MASK ( 0x0003 ) -#endif - -#if portBYTE_ALIGNMENT == 2 - #define portBYTE_ALIGNMENT_MASK ( 0x0001 ) -#endif - -#if portBYTE_ALIGNMENT == 1 - #define portBYTE_ALIGNMENT_MASK ( 0x0000 ) -#endif - -#ifndef portBYTE_ALIGNMENT_MASK - #error "Invalid portBYTE_ALIGNMENT definition" -#endif - -#ifndef portNUM_CONFIGURABLE_REGIONS - #define portNUM_CONFIGURABLE_REGIONS 1 -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -#include "mpu_wrappers.h" - -/* - * Setup the stack of a new task so it is ready to be placed under the - * scheduler control. The registers have to be placed on the stack in - * the order that the port expects to find them. - * - */ -#if( portUSING_MPU_WRAPPERS == 1 ) - StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters, BaseType_t xRunPrivileged ) PRIVILEGED_FUNCTION; -#else - StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters ) PRIVILEGED_FUNCTION; -#endif - -/* Used by heap_5.c. */ -typedef struct HeapRegion -{ - uint8_t *pucStartAddress; - size_t xSizeInBytes; -} HeapRegion_t; - -/* - * Used to define multiple heap regions for use by heap_5.c. This function - * must be called before any calls to pvPortMalloc() - not creating a task, - * queue, semaphore, mutex, software timer, event group, etc. will result in - * pvPortMalloc being called. - * - * pxHeapRegions passes in an array of HeapRegion_t structures - each of which - * defines a region of memory that can be used as the heap. The array is - * terminated by a HeapRegions_t structure that has a size of 0. The region - * with the lowest start address must appear first in the array. - */ -void vPortDefineHeapRegions( const HeapRegion_t * const pxHeapRegions ) PRIVILEGED_FUNCTION; - - -/* - * Map to the memory management routines required for the port. - */ -void *pvPortMalloc( size_t xSize ) PRIVILEGED_FUNCTION; -void vPortFree( void *pv ) PRIVILEGED_FUNCTION; -void vPortInitialiseBlocks( void ) PRIVILEGED_FUNCTION; -size_t xPortGetFreeHeapSize( void ) PRIVILEGED_FUNCTION; -size_t xPortGetMinimumEverFreeHeapSize( void ) PRIVILEGED_FUNCTION; - -/* - * Setup the hardware ready for the scheduler to take control. This generally - * sets up a tick interrupt and sets timers for the correct tick frequency. - */ -BaseType_t xPortStartScheduler( void ) PRIVILEGED_FUNCTION; - -/* - * Undo any hardware/ISR setup that was performed by xPortStartScheduler() so - * the hardware is left in its original condition after the scheduler stops - * executing. - */ -void vPortEndScheduler( void ) PRIVILEGED_FUNCTION; - -/* - * The structures and methods of manipulating the MPU are contained within the - * port layer. - * - * Fills the xMPUSettings structure with the memory region information - * contained in xRegions. - */ -#if( portUSING_MPU_WRAPPERS == 1 ) - struct xMEMORY_REGION; - void vPortStoreTaskMPUSettings( xMPU_SETTINGS *xMPUSettings, const struct xMEMORY_REGION * const xRegions, StackType_t *pxBottomOfStack, uint32_t ulStackDepth ) PRIVILEGED_FUNCTION; -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* PORTABLE_H */ - diff --git a/lib/FreeRTOS/Source/include/projdefs.h b/lib/FreeRTOS/Source/include/projdefs.h deleted file mode 100644 index 27337a89..00000000 --- a/lib/FreeRTOS/Source/include/projdefs.h +++ /dev/null @@ -1,124 +0,0 @@ -/* - * FreeRTOS Kernel V10.0.1 - * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * 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. - * - * http://www.FreeRTOS.org - * http://aws.amazon.com/freertos - * - * 1 tab == 4 spaces! - */ - -#ifndef PROJDEFS_H -#define PROJDEFS_H - -/* - * Defines the prototype to which task functions must conform. Defined in this - * file to ensure the type is known before portable.h is included. - */ -typedef void (*TaskFunction_t)( void * ); - -/* Converts a time in milliseconds to a time in ticks. This macro can be -overridden by a macro of the same name defined in FreeRTOSConfig.h in case the -definition here is not suitable for your application. */ -#ifndef pdMS_TO_TICKS - #define pdMS_TO_TICKS( xTimeInMs ) ( ( TickType_t ) ( ( ( TickType_t ) ( xTimeInMs ) * ( TickType_t ) configTICK_RATE_HZ ) / ( TickType_t ) 1000 ) ) -#endif - -#define pdFALSE ( ( BaseType_t ) 0 ) -#define pdTRUE ( ( BaseType_t ) 1 ) - -#define pdPASS ( pdTRUE ) -#define pdFAIL ( pdFALSE ) -#define errQUEUE_EMPTY ( ( BaseType_t ) 0 ) -#define errQUEUE_FULL ( ( BaseType_t ) 0 ) - -/* FreeRTOS error definitions. */ -#define errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY ( -1 ) -#define errQUEUE_BLOCKED ( -4 ) -#define errQUEUE_YIELD ( -5 ) - -/* Macros used for basic data corruption checks. */ -#ifndef configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES - #define configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES 0 -#endif - -#if( configUSE_16_BIT_TICKS == 1 ) - #define pdINTEGRITY_CHECK_VALUE 0x5a5a -#else - #define pdINTEGRITY_CHECK_VALUE 0x5a5a5a5aUL -#endif - -/* The following errno values are used by FreeRTOS+ components, not FreeRTOS -itself. */ -#define pdFREERTOS_ERRNO_NONE 0 /* No errors */ -#define pdFREERTOS_ERRNO_ENOENT 2 /* No such file or directory */ -#define pdFREERTOS_ERRNO_EINTR 4 /* Interrupted system call */ -#define pdFREERTOS_ERRNO_EIO 5 /* I/O error */ -#define pdFREERTOS_ERRNO_ENXIO 6 /* No such device or address */ -#define pdFREERTOS_ERRNO_EBADF 9 /* Bad file number */ -#define pdFREERTOS_ERRNO_EAGAIN 11 /* No more processes */ -#define pdFREERTOS_ERRNO_EWOULDBLOCK 11 /* Operation would block */ -#define pdFREERTOS_ERRNO_ENOMEM 12 /* Not enough memory */ -#define pdFREERTOS_ERRNO_EACCES 13 /* Permission denied */ -#define pdFREERTOS_ERRNO_EFAULT 14 /* Bad address */ -#define pdFREERTOS_ERRNO_EBUSY 16 /* Mount device busy */ -#define pdFREERTOS_ERRNO_EEXIST 17 /* File exists */ -#define pdFREERTOS_ERRNO_EXDEV 18 /* Cross-device link */ -#define pdFREERTOS_ERRNO_ENODEV 19 /* No such device */ -#define pdFREERTOS_ERRNO_ENOTDIR 20 /* Not a directory */ -#define pdFREERTOS_ERRNO_EISDIR 21 /* Is a directory */ -#define pdFREERTOS_ERRNO_EINVAL 22 /* Invalid argument */ -#define pdFREERTOS_ERRNO_ENOSPC 28 /* No space left on device */ -#define pdFREERTOS_ERRNO_ESPIPE 29 /* Illegal seek */ -#define pdFREERTOS_ERRNO_EROFS 30 /* Read only file system */ -#define pdFREERTOS_ERRNO_EUNATCH 42 /* Protocol driver not attached */ -#define pdFREERTOS_ERRNO_EBADE 50 /* Invalid exchange */ -#define pdFREERTOS_ERRNO_EFTYPE 79 /* Inappropriate file type or format */ -#define pdFREERTOS_ERRNO_ENMFILE 89 /* No more files */ -#define pdFREERTOS_ERRNO_ENOTEMPTY 90 /* Directory not empty */ -#define pdFREERTOS_ERRNO_ENAMETOOLONG 91 /* File or path name too long */ -#define pdFREERTOS_ERRNO_EOPNOTSUPP 95 /* Operation not supported on transport endpoint */ -#define pdFREERTOS_ERRNO_ENOBUFS 105 /* No buffer space available */ -#define pdFREERTOS_ERRNO_ENOPROTOOPT 109 /* Protocol not available */ -#define pdFREERTOS_ERRNO_EADDRINUSE 112 /* Address already in use */ -#define pdFREERTOS_ERRNO_ETIMEDOUT 116 /* Connection timed out */ -#define pdFREERTOS_ERRNO_EINPROGRESS 119 /* Connection already in progress */ -#define pdFREERTOS_ERRNO_EALREADY 120 /* Socket already connected */ -#define pdFREERTOS_ERRNO_EADDRNOTAVAIL 125 /* Address not available */ -#define pdFREERTOS_ERRNO_EISCONN 127 /* Socket is already connected */ -#define pdFREERTOS_ERRNO_ENOTCONN 128 /* Socket is not connected */ -#define pdFREERTOS_ERRNO_ENOMEDIUM 135 /* No medium inserted */ -#define pdFREERTOS_ERRNO_EILSEQ 138 /* An invalid UTF-16 sequence was encountered. */ -#define pdFREERTOS_ERRNO_ECANCELED 140 /* Operation canceled. */ - -/* The following endian values are used by FreeRTOS+ components, not FreeRTOS -itself. */ -#define pdFREERTOS_LITTLE_ENDIAN 0 -#define pdFREERTOS_BIG_ENDIAN 1 - -/* Re-defining endian values for generic naming. */ -#define pdLITTLE_ENDIAN pdFREERTOS_LITTLE_ENDIAN -#define pdBIG_ENDIAN pdFREERTOS_BIG_ENDIAN - - -#endif /* PROJDEFS_H */ - - - diff --git a/lib/FreeRTOS/Source/include/queue.h b/lib/FreeRTOS/Source/include/queue.h deleted file mode 100644 index a23fa1e6..00000000 --- a/lib/FreeRTOS/Source/include/queue.h +++ /dev/null @@ -1,1653 +0,0 @@ -/* - * FreeRTOS Kernel V10.0.1 - * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * 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. - * - * http://www.FreeRTOS.org - * http://aws.amazon.com/freertos - * - * 1 tab == 4 spaces! - */ - - -#ifndef QUEUE_H -#define QUEUE_H - -#ifndef INC_FREERTOS_H - #error "include FreeRTOS.h" must appear in source files before "include queue.h" -#endif - -#ifdef __cplusplus -extern "C" { -#endif - - -/** - * Type by which queues are referenced. For example, a call to xQueueCreate() - * returns an QueueHandle_t variable that can then be used as a parameter to - * xQueueSend(), xQueueReceive(), etc. - */ -typedef void * QueueHandle_t; - -/** - * Type by which queue sets are referenced. For example, a call to - * xQueueCreateSet() returns an xQueueSet variable that can then be used as a - * parameter to xQueueSelectFromSet(), xQueueAddToSet(), etc. - */ -typedef void * QueueSetHandle_t; - -/** - * Queue sets can contain both queues and semaphores, so the - * QueueSetMemberHandle_t is defined as a type to be used where a parameter or - * return value can be either an QueueHandle_t or an SemaphoreHandle_t. - */ -typedef void * QueueSetMemberHandle_t; - -/* For internal use only. */ -#define queueSEND_TO_BACK ( ( BaseType_t ) 0 ) -#define queueSEND_TO_FRONT ( ( BaseType_t ) 1 ) -#define queueOVERWRITE ( ( BaseType_t ) 2 ) - -/* For internal use only. These definitions *must* match those in queue.c. */ -#define queueQUEUE_TYPE_BASE ( ( uint8_t ) 0U ) -#define queueQUEUE_TYPE_SET ( ( uint8_t ) 0U ) -#define queueQUEUE_TYPE_MUTEX ( ( uint8_t ) 1U ) -#define queueQUEUE_TYPE_COUNTING_SEMAPHORE ( ( uint8_t ) 2U ) -#define queueQUEUE_TYPE_BINARY_SEMAPHORE ( ( uint8_t ) 3U ) -#define queueQUEUE_TYPE_RECURSIVE_MUTEX ( ( uint8_t ) 4U ) - -/** - * queue. h - *
- QueueHandle_t xQueueCreate(
-							  UBaseType_t uxQueueLength,
-							  UBaseType_t uxItemSize
-						  );
- * 
- * - * Creates a new queue instance, and returns a handle by which the new queue - * can be referenced. - * - * Internally, within the FreeRTOS implementation, queues use two blocks of - * memory. The first block is used to hold the queue's data structures. The - * second block is used to hold items placed into the queue. If a queue is - * created using xQueueCreate() then both blocks of memory are automatically - * dynamically allocated inside the xQueueCreate() function. (see - * http://www.freertos.org/a00111.html). If a queue is created using - * xQueueCreateStatic() then the application writer must provide the memory that - * will get used by the queue. xQueueCreateStatic() therefore allows a queue to - * be created without using any dynamic memory allocation. - * - * http://www.FreeRTOS.org/Embedded-RTOS-Queues.html - * - * @param uxQueueLength The maximum number of items that the queue can contain. - * - * @param uxItemSize The number of bytes each item in the queue will require. - * Items are queued by copy, not by reference, so this is the number of bytes - * that will be copied for each posted item. Each item on the queue must be - * the same size. - * - * @return If the queue is successfully create then a handle to the newly - * created queue is returned. If the queue cannot be created then 0 is - * returned. - * - * Example usage: -
- struct AMessage
- {
-	char ucMessageID;
-	char ucData[ 20 ];
- };
-
- void vATask( void *pvParameters )
- {
- QueueHandle_t xQueue1, xQueue2;
-
-	// Create a queue capable of containing 10 uint32_t values.
-	xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) );
-	if( xQueue1 == 0 )
-	{
-		// Queue was not created and must not be used.
-	}
-
-	// Create a queue capable of containing 10 pointers to AMessage structures.
-	// These should be passed by pointer as they contain a lot of data.
-	xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) );
-	if( xQueue2 == 0 )
-	{
-		// Queue was not created and must not be used.
-	}
-
-	// ... Rest of task code.
- }
- 
- * \defgroup xQueueCreate xQueueCreate - * \ingroup QueueManagement - */ -#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - #define xQueueCreate( uxQueueLength, uxItemSize ) xQueueGenericCreate( ( uxQueueLength ), ( uxItemSize ), ( queueQUEUE_TYPE_BASE ) ) -#endif - -/** - * queue. h - *
- QueueHandle_t xQueueCreateStatic(
-							  UBaseType_t uxQueueLength,
-							  UBaseType_t uxItemSize,
-							  uint8_t *pucQueueStorageBuffer,
-							  StaticQueue_t *pxQueueBuffer
-						  );
- * 
- * - * Creates a new queue instance, and returns a handle by which the new queue - * can be referenced. - * - * Internally, within the FreeRTOS implementation, queues use two blocks of - * memory. The first block is used to hold the queue's data structures. The - * second block is used to hold items placed into the queue. If a queue is - * created using xQueueCreate() then both blocks of memory are automatically - * dynamically allocated inside the xQueueCreate() function. (see - * http://www.freertos.org/a00111.html). If a queue is created using - * xQueueCreateStatic() then the application writer must provide the memory that - * will get used by the queue. xQueueCreateStatic() therefore allows a queue to - * be created without using any dynamic memory allocation. - * - * http://www.FreeRTOS.org/Embedded-RTOS-Queues.html - * - * @param uxQueueLength The maximum number of items that the queue can contain. - * - * @param uxItemSize The number of bytes each item in the queue will require. - * Items are queued by copy, not by reference, so this is the number of bytes - * that will be copied for each posted item. Each item on the queue must be - * the same size. - * - * @param pucQueueStorageBuffer If uxItemSize is not zero then - * pucQueueStorageBuffer must point to a uint8_t array that is at least large - * enough to hold the maximum number of items that can be in the queue at any - * one time - which is ( uxQueueLength * uxItemsSize ) bytes. If uxItemSize is - * zero then pucQueueStorageBuffer can be NULL. - * - * @param pxQueueBuffer Must point to a variable of type StaticQueue_t, which - * will be used to hold the queue's data structure. - * - * @return If the queue is created then a handle to the created queue is - * returned. If pxQueueBuffer is NULL then NULL is returned. - * - * Example usage: -
- struct AMessage
- {
-	char ucMessageID;
-	char ucData[ 20 ];
- };
-
- #define QUEUE_LENGTH 10
- #define ITEM_SIZE sizeof( uint32_t )
-
- // xQueueBuffer will hold the queue structure.
- StaticQueue_t xQueueBuffer;
-
- // ucQueueStorage will hold the items posted to the queue.  Must be at least
- // [(queue length) * ( queue item size)] bytes long.
- uint8_t ucQueueStorage[ QUEUE_LENGTH * ITEM_SIZE ];
-
- void vATask( void *pvParameters )
- {
- QueueHandle_t xQueue1;
-
-	// Create a queue capable of containing 10 uint32_t values.
-	xQueue1 = xQueueCreate( QUEUE_LENGTH, // The number of items the queue can hold.
-							ITEM_SIZE	  // The size of each item in the queue
-							&( ucQueueStorage[ 0 ] ), // The buffer that will hold the items in the queue.
-							&xQueueBuffer ); // The buffer that will hold the queue structure.
-
-	// The queue is guaranteed to be created successfully as no dynamic memory
-	// allocation is used.  Therefore xQueue1 is now a handle to a valid queue.
-
-	// ... Rest of task code.
- }
- 
- * \defgroup xQueueCreateStatic xQueueCreateStatic - * \ingroup QueueManagement - */ -#if( configSUPPORT_STATIC_ALLOCATION == 1 ) - #define xQueueCreateStatic( uxQueueLength, uxItemSize, pucQueueStorage, pxQueueBuffer ) xQueueGenericCreateStatic( ( uxQueueLength ), ( uxItemSize ), ( pucQueueStorage ), ( pxQueueBuffer ), ( queueQUEUE_TYPE_BASE ) ) -#endif /* configSUPPORT_STATIC_ALLOCATION */ - -/** - * queue. h - *
- BaseType_t xQueueSendToToFront(
-								   QueueHandle_t	xQueue,
-								   const void		*pvItemToQueue,
-								   TickType_t		xTicksToWait
-							   );
- * 
- * - * Post an item to the front of a queue. The item is queued by copy, not by - * reference. This function must not be called from an interrupt service - * routine. See xQueueSendFromISR () for an alternative which may be used - * in an ISR. - * - * @param xQueue The handle to the queue on which the item is to be posted. - * - * @param pvItemToQueue A pointer to the item that is to be placed on the - * queue. The size of the items the queue will hold was defined when the - * queue was created, so this many bytes will be copied from pvItemToQueue - * into the queue storage area. - * - * @param xTicksToWait The maximum amount of time the task should block - * waiting for space to become available on the queue, should it already - * be full. The call will return immediately if this is set to 0 and the - * queue is full. The time is defined in tick periods so the constant - * portTICK_PERIOD_MS should be used to convert to real time if this is required. - * - * @return pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL. - * - * Example usage: -
- struct AMessage
- {
-	char ucMessageID;
-	char ucData[ 20 ];
- } xMessage;
-
- uint32_t ulVar = 10UL;
-
- void vATask( void *pvParameters )
- {
- QueueHandle_t xQueue1, xQueue2;
- struct AMessage *pxMessage;
-
-	// Create a queue capable of containing 10 uint32_t values.
-	xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) );
-
-	// Create a queue capable of containing 10 pointers to AMessage structures.
-	// These should be passed by pointer as they contain a lot of data.
-	xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) );
-
-	// ...
-
-	if( xQueue1 != 0 )
-	{
-		// Send an uint32_t.  Wait for 10 ticks for space to become
-		// available if necessary.
-		if( xQueueSendToFront( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10 ) != pdPASS )
-		{
-			// Failed to post the message, even after 10 ticks.
-		}
-	}
-
-	if( xQueue2 != 0 )
-	{
-		// Send a pointer to a struct AMessage object.  Don't block if the
-		// queue is already full.
-		pxMessage = & xMessage;
-		xQueueSendToFront( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0 );
-	}
-
-	// ... Rest of task code.
- }
- 
- * \defgroup xQueueSend xQueueSend - * \ingroup QueueManagement - */ -#define xQueueSendToFront( xQueue, pvItemToQueue, xTicksToWait ) xQueueGenericSend( ( xQueue ), ( pvItemToQueue ), ( xTicksToWait ), queueSEND_TO_FRONT ) - -/** - * queue. h - *
- BaseType_t xQueueSendToBack(
-								   QueueHandle_t	xQueue,
-								   const void		*pvItemToQueue,
-								   TickType_t		xTicksToWait
-							   );
- * 
- * - * This is a macro that calls xQueueGenericSend(). - * - * Post an item to the back of a queue. The item is queued by copy, not by - * reference. This function must not be called from an interrupt service - * routine. See xQueueSendFromISR () for an alternative which may be used - * in an ISR. - * - * @param xQueue The handle to the queue on which the item is to be posted. - * - * @param pvItemToQueue A pointer to the item that is to be placed on the - * queue. The size of the items the queue will hold was defined when the - * queue was created, so this many bytes will be copied from pvItemToQueue - * into the queue storage area. - * - * @param xTicksToWait The maximum amount of time the task should block - * waiting for space to become available on the queue, should it already - * be full. The call will return immediately if this is set to 0 and the queue - * is full. The time is defined in tick periods so the constant - * portTICK_PERIOD_MS should be used to convert to real time if this is required. - * - * @return pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL. - * - * Example usage: -
- struct AMessage
- {
-	char ucMessageID;
-	char ucData[ 20 ];
- } xMessage;
-
- uint32_t ulVar = 10UL;
-
- void vATask( void *pvParameters )
- {
- QueueHandle_t xQueue1, xQueue2;
- struct AMessage *pxMessage;
-
-	// Create a queue capable of containing 10 uint32_t values.
-	xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) );
-
-	// Create a queue capable of containing 10 pointers to AMessage structures.
-	// These should be passed by pointer as they contain a lot of data.
-	xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) );
-
-	// ...
-
-	if( xQueue1 != 0 )
-	{
-		// Send an uint32_t.  Wait for 10 ticks for space to become
-		// available if necessary.
-		if( xQueueSendToBack( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10 ) != pdPASS )
-		{
-			// Failed to post the message, even after 10 ticks.
-		}
-	}
-
-	if( xQueue2 != 0 )
-	{
-		// Send a pointer to a struct AMessage object.  Don't block if the
-		// queue is already full.
-		pxMessage = & xMessage;
-		xQueueSendToBack( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0 );
-	}
-
-	// ... Rest of task code.
- }
- 
- * \defgroup xQueueSend xQueueSend - * \ingroup QueueManagement - */ -#define xQueueSendToBack( xQueue, pvItemToQueue, xTicksToWait ) xQueueGenericSend( ( xQueue ), ( pvItemToQueue ), ( xTicksToWait ), queueSEND_TO_BACK ) - -/** - * queue. h - *
- BaseType_t xQueueSend(
-							  QueueHandle_t xQueue,
-							  const void * pvItemToQueue,
-							  TickType_t xTicksToWait
-						 );
- * 
- * - * This is a macro that calls xQueueGenericSend(). It is included for - * backward compatibility with versions of FreeRTOS.org that did not - * include the xQueueSendToFront() and xQueueSendToBack() macros. It is - * equivalent to xQueueSendToBack(). - * - * Post an item on a queue. The item is queued by copy, not by reference. - * This function must not be called from an interrupt service routine. - * See xQueueSendFromISR () for an alternative which may be used in an ISR. - * - * @param xQueue The handle to the queue on which the item is to be posted. - * - * @param pvItemToQueue A pointer to the item that is to be placed on the - * queue. The size of the items the queue will hold was defined when the - * queue was created, so this many bytes will be copied from pvItemToQueue - * into the queue storage area. - * - * @param xTicksToWait The maximum amount of time the task should block - * waiting for space to become available on the queue, should it already - * be full. The call will return immediately if this is set to 0 and the - * queue is full. The time is defined in tick periods so the constant - * portTICK_PERIOD_MS should be used to convert to real time if this is required. - * - * @return pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL. - * - * Example usage: -
- struct AMessage
- {
-	char ucMessageID;
-	char ucData[ 20 ];
- } xMessage;
-
- uint32_t ulVar = 10UL;
-
- void vATask( void *pvParameters )
- {
- QueueHandle_t xQueue1, xQueue2;
- struct AMessage *pxMessage;
-
-	// Create a queue capable of containing 10 uint32_t values.
-	xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) );
-
-	// Create a queue capable of containing 10 pointers to AMessage structures.
-	// These should be passed by pointer as they contain a lot of data.
-	xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) );
-
-	// ...
-
-	if( xQueue1 != 0 )
-	{
-		// Send an uint32_t.  Wait for 10 ticks for space to become
-		// available if necessary.
-		if( xQueueSend( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10 ) != pdPASS )
-		{
-			// Failed to post the message, even after 10 ticks.
-		}
-	}
-
-	if( xQueue2 != 0 )
-	{
-		// Send a pointer to a struct AMessage object.  Don't block if the
-		// queue is already full.
-		pxMessage = & xMessage;
-		xQueueSend( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0 );
-	}
-
-	// ... Rest of task code.
- }
- 
- * \defgroup xQueueSend xQueueSend - * \ingroup QueueManagement - */ -#define xQueueSend( xQueue, pvItemToQueue, xTicksToWait ) xQueueGenericSend( ( xQueue ), ( pvItemToQueue ), ( xTicksToWait ), queueSEND_TO_BACK ) - -/** - * queue. h - *
- BaseType_t xQueueOverwrite(
-							  QueueHandle_t xQueue,
-							  const void * pvItemToQueue
-						 );
- * 
- * - * Only for use with queues that have a length of one - so the queue is either - * empty or full. - * - * Post an item on a queue. If the queue is already full then overwrite the - * value held in the queue. The item is queued by copy, not by reference. - * - * This function must not be called from an interrupt service routine. - * See xQueueOverwriteFromISR () for an alternative which may be used in an ISR. - * - * @param xQueue The handle of the queue to which the data is being sent. - * - * @param pvItemToQueue A pointer to the item that is to be placed on the - * queue. The size of the items the queue will hold was defined when the - * queue was created, so this many bytes will be copied from pvItemToQueue - * into the queue storage area. - * - * @return xQueueOverwrite() is a macro that calls xQueueGenericSend(), and - * therefore has the same return values as xQueueSendToFront(). However, pdPASS - * is the only value that can be returned because xQueueOverwrite() will write - * to the queue even when the queue is already full. - * - * Example usage: -
-
- void vFunction( void *pvParameters )
- {
- QueueHandle_t xQueue;
- uint32_t ulVarToSend, ulValReceived;
-
-	// Create a queue to hold one uint32_t value.  It is strongly
-	// recommended *not* to use xQueueOverwrite() on queues that can
-	// contain more than one value, and doing so will trigger an assertion
-	// if configASSERT() is defined.
-	xQueue = xQueueCreate( 1, sizeof( uint32_t ) );
-
-	// Write the value 10 to the queue using xQueueOverwrite().
-	ulVarToSend = 10;
-	xQueueOverwrite( xQueue, &ulVarToSend );
-
-	// Peeking the queue should now return 10, but leave the value 10 in
-	// the queue.  A block time of zero is used as it is known that the
-	// queue holds a value.
-	ulValReceived = 0;
-	xQueuePeek( xQueue, &ulValReceived, 0 );
-
-	if( ulValReceived != 10 )
-	{
-		// Error unless the item was removed by a different task.
-	}
-
-	// The queue is still full.  Use xQueueOverwrite() to overwrite the
-	// value held in the queue with 100.
-	ulVarToSend = 100;
-	xQueueOverwrite( xQueue, &ulVarToSend );
-
-	// This time read from the queue, leaving the queue empty once more.
-	// A block time of 0 is used again.
-	xQueueReceive( xQueue, &ulValReceived, 0 );
-
-	// The value read should be the last value written, even though the
-	// queue was already full when the value was written.
-	if( ulValReceived != 100 )
-	{
-		// Error!
-	}
-
-	// ...
-}
- 
- * \defgroup xQueueOverwrite xQueueOverwrite - * \ingroup QueueManagement - */ -#define xQueueOverwrite( xQueue, pvItemToQueue ) xQueueGenericSend( ( xQueue ), ( pvItemToQueue ), 0, queueOVERWRITE ) - - -/** - * queue. h - *
- BaseType_t xQueueGenericSend(
-									QueueHandle_t xQueue,
-									const void * pvItemToQueue,
-									TickType_t xTicksToWait
-									BaseType_t xCopyPosition
-								);
- * 
- * - * It is preferred that the macros xQueueSend(), xQueueSendToFront() and - * xQueueSendToBack() are used in place of calling this function directly. - * - * Post an item on a queue. The item is queued by copy, not by reference. - * This function must not be called from an interrupt service routine. - * See xQueueSendFromISR () for an alternative which may be used in an ISR. - * - * @param xQueue The handle to the queue on which the item is to be posted. - * - * @param pvItemToQueue A pointer to the item that is to be placed on the - * queue. The size of the items the queue will hold was defined when the - * queue was created, so this many bytes will be copied from pvItemToQueue - * into the queue storage area. - * - * @param xTicksToWait The maximum amount of time the task should block - * waiting for space to become available on the queue, should it already - * be full. The call will return immediately if this is set to 0 and the - * queue is full. The time is defined in tick periods so the constant - * portTICK_PERIOD_MS should be used to convert to real time if this is required. - * - * @param xCopyPosition Can take the value queueSEND_TO_BACK to place the - * item at the back of the queue, or queueSEND_TO_FRONT to place the item - * at the front of the queue (for high priority messages). - * - * @return pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL. - * - * Example usage: -
- struct AMessage
- {
-	char ucMessageID;
-	char ucData[ 20 ];
- } xMessage;
-
- uint32_t ulVar = 10UL;
-
- void vATask( void *pvParameters )
- {
- QueueHandle_t xQueue1, xQueue2;
- struct AMessage *pxMessage;
-
-	// Create a queue capable of containing 10 uint32_t values.
-	xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) );
-
-	// Create a queue capable of containing 10 pointers to AMessage structures.
-	// These should be passed by pointer as they contain a lot of data.
-	xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) );
-
-	// ...
-
-	if( xQueue1 != 0 )
-	{
-		// Send an uint32_t.  Wait for 10 ticks for space to become
-		// available if necessary.
-		if( xQueueGenericSend( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10, queueSEND_TO_BACK ) != pdPASS )
-		{
-			// Failed to post the message, even after 10 ticks.
-		}
-	}
-
-	if( xQueue2 != 0 )
-	{
-		// Send a pointer to a struct AMessage object.  Don't block if the
-		// queue is already full.
-		pxMessage = & xMessage;
-		xQueueGenericSend( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0, queueSEND_TO_BACK );
-	}
-
-	// ... Rest of task code.
- }
- 
- * \defgroup xQueueSend xQueueSend - * \ingroup QueueManagement - */ -BaseType_t xQueueGenericSend( QueueHandle_t xQueue, const void * const pvItemToQueue, TickType_t xTicksToWait, const BaseType_t xCopyPosition ) PRIVILEGED_FUNCTION; - -/** - * queue. h - *
- BaseType_t xQueuePeek(
-							 QueueHandle_t xQueue,
-							 void * const pvBuffer,
-							 TickType_t xTicksToWait
-						 );
- * - * Receive an item from a queue without removing the item from the queue. - * The item is received by copy so a buffer of adequate size must be - * provided. The number of bytes copied into the buffer was defined when - * the queue was created. - * - * Successfully received items remain on the queue so will be returned again - * by the next call, or a call to xQueueReceive(). - * - * This macro must not be used in an interrupt service routine. See - * xQueuePeekFromISR() for an alternative that can be called from an interrupt - * service routine. - * - * @param xQueue The handle to the queue from which the item is to be - * received. - * - * @param pvBuffer Pointer to the buffer into which the received item will - * be copied. - * - * @param xTicksToWait The maximum amount of time the task should block - * waiting for an item to receive should the queue be empty at the time - * of the call. The time is defined in tick periods so the constant - * portTICK_PERIOD_MS should be used to convert to real time if this is required. - * xQueuePeek() will return immediately if xTicksToWait is 0 and the queue - * is empty. - * - * @return pdTRUE if an item was successfully received from the queue, - * otherwise pdFALSE. - * - * Example usage: -
- struct AMessage
- {
-	char ucMessageID;
-	char ucData[ 20 ];
- } xMessage;
-
- QueueHandle_t xQueue;
-
- // Task to create a queue and post a value.
- void vATask( void *pvParameters )
- {
- struct AMessage *pxMessage;
-
-	// Create a queue capable of containing 10 pointers to AMessage structures.
-	// These should be passed by pointer as they contain a lot of data.
-	xQueue = xQueueCreate( 10, sizeof( struct AMessage * ) );
-	if( xQueue == 0 )
-	{
-		// Failed to create the queue.
-	}
-
-	// ...
-
-	// Send a pointer to a struct AMessage object.  Don't block if the
-	// queue is already full.
-	pxMessage = & xMessage;
-	xQueueSend( xQueue, ( void * ) &pxMessage, ( TickType_t ) 0 );
-
-	// ... Rest of task code.
- }
-
- // Task to peek the data from the queue.
- void vADifferentTask( void *pvParameters )
- {
- struct AMessage *pxRxedMessage;
-
-	if( xQueue != 0 )
-	{
-		// Peek a message on the created queue.  Block for 10 ticks if a
-		// message is not immediately available.
-		if( xQueuePeek( xQueue, &( pxRxedMessage ), ( TickType_t ) 10 ) )
-		{
-			// pcRxedMessage now points to the struct AMessage variable posted
-			// by vATask, but the item still remains on the queue.
-		}
-	}
-
-	// ... Rest of task code.
- }
- 
- * \defgroup xQueuePeek xQueuePeek - * \ingroup QueueManagement - */ -BaseType_t xQueuePeek( QueueHandle_t xQueue, void * const pvBuffer, TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; - -/** - * queue. h - *
- BaseType_t xQueuePeekFromISR(
-									QueueHandle_t xQueue,
-									void *pvBuffer,
-								);
- * - * A version of xQueuePeek() that can be called from an interrupt service - * routine (ISR). - * - * Receive an item from a queue without removing the item from the queue. - * The item is received by copy so a buffer of adequate size must be - * provided. The number of bytes copied into the buffer was defined when - * the queue was created. - * - * Successfully received items remain on the queue so will be returned again - * by the next call, or a call to xQueueReceive(). - * - * @param xQueue The handle to the queue from which the item is to be - * received. - * - * @param pvBuffer Pointer to the buffer into which the received item will - * be copied. - * - * @return pdTRUE if an item was successfully received from the queue, - * otherwise pdFALSE. - * - * \defgroup xQueuePeekFromISR xQueuePeekFromISR - * \ingroup QueueManagement - */ -BaseType_t xQueuePeekFromISR( QueueHandle_t xQueue, void * const pvBuffer ) PRIVILEGED_FUNCTION; - -/** - * queue. h - *
- BaseType_t xQueueReceive(
-								 QueueHandle_t xQueue,
-								 void *pvBuffer,
-								 TickType_t xTicksToWait
-							);
- * - * Receive an item from a queue. The item is received by copy so a buffer of - * adequate size must be provided. The number of bytes copied into the buffer - * was defined when the queue was created. - * - * Successfully received items are removed from the queue. - * - * This function must not be used in an interrupt service routine. See - * xQueueReceiveFromISR for an alternative that can. - * - * @param xQueue The handle to the queue from which the item is to be - * received. - * - * @param pvBuffer Pointer to the buffer into which the received item will - * be copied. - * - * @param xTicksToWait The maximum amount of time the task should block - * waiting for an item to receive should the queue be empty at the time - * of the call. xQueueReceive() will return immediately if xTicksToWait - * is zero and the queue is empty. The time is defined in tick periods so the - * constant portTICK_PERIOD_MS should be used to convert to real time if this is - * required. - * - * @return pdTRUE if an item was successfully received from the queue, - * otherwise pdFALSE. - * - * Example usage: -
- struct AMessage
- {
-	char ucMessageID;
-	char ucData[ 20 ];
- } xMessage;
-
- QueueHandle_t xQueue;
-
- // Task to create a queue and post a value.
- void vATask( void *pvParameters )
- {
- struct AMessage *pxMessage;
-
-	// Create a queue capable of containing 10 pointers to AMessage structures.
-	// These should be passed by pointer as they contain a lot of data.
-	xQueue = xQueueCreate( 10, sizeof( struct AMessage * ) );
-	if( xQueue == 0 )
-	{
-		// Failed to create the queue.
-	}
-
-	// ...
-
-	// Send a pointer to a struct AMessage object.  Don't block if the
-	// queue is already full.
-	pxMessage = & xMessage;
-	xQueueSend( xQueue, ( void * ) &pxMessage, ( TickType_t ) 0 );
-
-	// ... Rest of task code.
- }
-
- // Task to receive from the queue.
- void vADifferentTask( void *pvParameters )
- {
- struct AMessage *pxRxedMessage;
-
-	if( xQueue != 0 )
-	{
-		// Receive a message on the created queue.  Block for 10 ticks if a
-		// message is not immediately available.
-		if( xQueueReceive( xQueue, &( pxRxedMessage ), ( TickType_t ) 10 ) )
-		{
-			// pcRxedMessage now points to the struct AMessage variable posted
-			// by vATask.
-		}
-	}
-
-	// ... Rest of task code.
- }
- 
- * \defgroup xQueueReceive xQueueReceive - * \ingroup QueueManagement - */ -BaseType_t xQueueReceive( QueueHandle_t xQueue, void * const pvBuffer, TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; - -/** - * queue. h - *
UBaseType_t uxQueueMessagesWaiting( const QueueHandle_t xQueue );
- * - * Return the number of messages stored in a queue. - * - * @param xQueue A handle to the queue being queried. - * - * @return The number of messages available in the queue. - * - * \defgroup uxQueueMessagesWaiting uxQueueMessagesWaiting - * \ingroup QueueManagement - */ -UBaseType_t uxQueueMessagesWaiting( const QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; - -/** - * queue. h - *
UBaseType_t uxQueueSpacesAvailable( const QueueHandle_t xQueue );
- * - * Return the number of free spaces available in a queue. This is equal to the - * number of items that can be sent to the queue before the queue becomes full - * if no items are removed. - * - * @param xQueue A handle to the queue being queried. - * - * @return The number of spaces available in the queue. - * - * \defgroup uxQueueMessagesWaiting uxQueueMessagesWaiting - * \ingroup QueueManagement - */ -UBaseType_t uxQueueSpacesAvailable( const QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; - -/** - * queue. h - *
void vQueueDelete( QueueHandle_t xQueue );
- * - * Delete a queue - freeing all the memory allocated for storing of items - * placed on the queue. - * - * @param xQueue A handle to the queue to be deleted. - * - * \defgroup vQueueDelete vQueueDelete - * \ingroup QueueManagement - */ -void vQueueDelete( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; - -/** - * queue. h - *
- BaseType_t xQueueSendToFrontFromISR(
-										 QueueHandle_t xQueue,
-										 const void *pvItemToQueue,
-										 BaseType_t *pxHigherPriorityTaskWoken
-									  );
- 
- * - * This is a macro that calls xQueueGenericSendFromISR(). - * - * Post an item to the front of a queue. It is safe to use this macro from - * within an interrupt service routine. - * - * Items are queued by copy not reference so it is preferable to only - * queue small items, especially when called from an ISR. In most cases - * it would be preferable to store a pointer to the item being queued. - * - * @param xQueue The handle to the queue on which the item is to be posted. - * - * @param pvItemToQueue A pointer to the item that is to be placed on the - * queue. The size of the items the queue will hold was defined when the - * queue was created, so this many bytes will be copied from pvItemToQueue - * into the queue storage area. - * - * @param pxHigherPriorityTaskWoken xQueueSendToFrontFromISR() will set - * *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task - * to unblock, and the unblocked task has a priority higher than the currently - * running task. If xQueueSendToFromFromISR() sets this value to pdTRUE then - * a context switch should be requested before the interrupt is exited. - * - * @return pdTRUE if the data was successfully sent to the queue, otherwise - * errQUEUE_FULL. - * - * Example usage for buffered IO (where the ISR can obtain more than one value - * per call): -
- void vBufferISR( void )
- {
- char cIn;
- BaseType_t xHigherPrioritTaskWoken;
-
-	// We have not woken a task at the start of the ISR.
-	xHigherPriorityTaskWoken = pdFALSE;
-
-	// Loop until the buffer is empty.
-	do
-	{
-		// Obtain a byte from the buffer.
-		cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS );
-
-		// Post the byte.
-		xQueueSendToFrontFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWoken );
-
-	} while( portINPUT_BYTE( BUFFER_COUNT ) );
-
-	// Now the buffer is empty we can switch context if necessary.
-	if( xHigherPriorityTaskWoken )
-	{
-		taskYIELD ();
-	}
- }
- 
- * - * \defgroup xQueueSendFromISR xQueueSendFromISR - * \ingroup QueueManagement - */ -#define xQueueSendToFrontFromISR( xQueue, pvItemToQueue, pxHigherPriorityTaskWoken ) xQueueGenericSendFromISR( ( xQueue ), ( pvItemToQueue ), ( pxHigherPriorityTaskWoken ), queueSEND_TO_FRONT ) - - -/** - * queue. h - *
- BaseType_t xQueueSendToBackFromISR(
-										 QueueHandle_t xQueue,
-										 const void *pvItemToQueue,
-										 BaseType_t *pxHigherPriorityTaskWoken
-									  );
- 
- * - * This is a macro that calls xQueueGenericSendFromISR(). - * - * Post an item to the back of a queue. It is safe to use this macro from - * within an interrupt service routine. - * - * Items are queued by copy not reference so it is preferable to only - * queue small items, especially when called from an ISR. In most cases - * it would be preferable to store a pointer to the item being queued. - * - * @param xQueue The handle to the queue on which the item is to be posted. - * - * @param pvItemToQueue A pointer to the item that is to be placed on the - * queue. The size of the items the queue will hold was defined when the - * queue was created, so this many bytes will be copied from pvItemToQueue - * into the queue storage area. - * - * @param pxHigherPriorityTaskWoken xQueueSendToBackFromISR() will set - * *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task - * to unblock, and the unblocked task has a priority higher than the currently - * running task. If xQueueSendToBackFromISR() sets this value to pdTRUE then - * a context switch should be requested before the interrupt is exited. - * - * @return pdTRUE if the data was successfully sent to the queue, otherwise - * errQUEUE_FULL. - * - * Example usage for buffered IO (where the ISR can obtain more than one value - * per call): -
- void vBufferISR( void )
- {
- char cIn;
- BaseType_t xHigherPriorityTaskWoken;
-
-	// We have not woken a task at the start of the ISR.
-	xHigherPriorityTaskWoken = pdFALSE;
-
-	// Loop until the buffer is empty.
-	do
-	{
-		// Obtain a byte from the buffer.
-		cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS );
-
-		// Post the byte.
-		xQueueSendToBackFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWoken );
-
-	} while( portINPUT_BYTE( BUFFER_COUNT ) );
-
-	// Now the buffer is empty we can switch context if necessary.
-	if( xHigherPriorityTaskWoken )
-	{
-		taskYIELD ();
-	}
- }
- 
- * - * \defgroup xQueueSendFromISR xQueueSendFromISR - * \ingroup QueueManagement - */ -#define xQueueSendToBackFromISR( xQueue, pvItemToQueue, pxHigherPriorityTaskWoken ) xQueueGenericSendFromISR( ( xQueue ), ( pvItemToQueue ), ( pxHigherPriorityTaskWoken ), queueSEND_TO_BACK ) - -/** - * queue. h - *
- BaseType_t xQueueOverwriteFromISR(
-							  QueueHandle_t xQueue,
-							  const void * pvItemToQueue,
-							  BaseType_t *pxHigherPriorityTaskWoken
-						 );
- * 
- * - * A version of xQueueOverwrite() that can be used in an interrupt service - * routine (ISR). - * - * Only for use with queues that can hold a single item - so the queue is either - * empty or full. - * - * Post an item on a queue. If the queue is already full then overwrite the - * value held in the queue. The item is queued by copy, not by reference. - * - * @param xQueue The handle to the queue on which the item is to be posted. - * - * @param pvItemToQueue A pointer to the item that is to be placed on the - * queue. The size of the items the queue will hold was defined when the - * queue was created, so this many bytes will be copied from pvItemToQueue - * into the queue storage area. - * - * @param pxHigherPriorityTaskWoken xQueueOverwriteFromISR() will set - * *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task - * to unblock, and the unblocked task has a priority higher than the currently - * running task. If xQueueOverwriteFromISR() sets this value to pdTRUE then - * a context switch should be requested before the interrupt is exited. - * - * @return xQueueOverwriteFromISR() is a macro that calls - * xQueueGenericSendFromISR(), and therefore has the same return values as - * xQueueSendToFrontFromISR(). However, pdPASS is the only value that can be - * returned because xQueueOverwriteFromISR() will write to the queue even when - * the queue is already full. - * - * Example usage: -
-
- QueueHandle_t xQueue;
-
- void vFunction( void *pvParameters )
- {
- 	// Create a queue to hold one uint32_t value.  It is strongly
-	// recommended *not* to use xQueueOverwriteFromISR() on queues that can
-	// contain more than one value, and doing so will trigger an assertion
-	// if configASSERT() is defined.
-	xQueue = xQueueCreate( 1, sizeof( uint32_t ) );
-}
-
-void vAnInterruptHandler( void )
-{
-// xHigherPriorityTaskWoken must be set to pdFALSE before it is used.
-BaseType_t xHigherPriorityTaskWoken = pdFALSE;
-uint32_t ulVarToSend, ulValReceived;
-
-	// Write the value 10 to the queue using xQueueOverwriteFromISR().
-	ulVarToSend = 10;
-	xQueueOverwriteFromISR( xQueue, &ulVarToSend, &xHigherPriorityTaskWoken );
-
-	// The queue is full, but calling xQueueOverwriteFromISR() again will still
-	// pass because the value held in the queue will be overwritten with the
-	// new value.
-	ulVarToSend = 100;
-	xQueueOverwriteFromISR( xQueue, &ulVarToSend, &xHigherPriorityTaskWoken );
-
-	// Reading from the queue will now return 100.
-
-	// ...
-
-	if( xHigherPrioritytaskWoken == pdTRUE )
-	{
-		// Writing to the queue caused a task to unblock and the unblocked task
-		// has a priority higher than or equal to the priority of the currently
-		// executing task (the task this interrupt interrupted).  Perform a context
-		// switch so this interrupt returns directly to the unblocked task.
-		portYIELD_FROM_ISR(); // or portEND_SWITCHING_ISR() depending on the port.
-	}
-}
- 
- * \defgroup xQueueOverwriteFromISR xQueueOverwriteFromISR - * \ingroup QueueManagement - */ -#define xQueueOverwriteFromISR( xQueue, pvItemToQueue, pxHigherPriorityTaskWoken ) xQueueGenericSendFromISR( ( xQueue ), ( pvItemToQueue ), ( pxHigherPriorityTaskWoken ), queueOVERWRITE ) - -/** - * queue. h - *
- BaseType_t xQueueSendFromISR(
-									 QueueHandle_t xQueue,
-									 const void *pvItemToQueue,
-									 BaseType_t *pxHigherPriorityTaskWoken
-								);
- 
- * - * This is a macro that calls xQueueGenericSendFromISR(). It is included - * for backward compatibility with versions of FreeRTOS.org that did not - * include the xQueueSendToBackFromISR() and xQueueSendToFrontFromISR() - * macros. - * - * Post an item to the back of a queue. It is safe to use this function from - * within an interrupt service routine. - * - * Items are queued by copy not reference so it is preferable to only - * queue small items, especially when called from an ISR. In most cases - * it would be preferable to store a pointer to the item being queued. - * - * @param xQueue The handle to the queue on which the item is to be posted. - * - * @param pvItemToQueue A pointer to the item that is to be placed on the - * queue. The size of the items the queue will hold was defined when the - * queue was created, so this many bytes will be copied from pvItemToQueue - * into the queue storage area. - * - * @param pxHigherPriorityTaskWoken xQueueSendFromISR() will set - * *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task - * to unblock, and the unblocked task has a priority higher than the currently - * running task. If xQueueSendFromISR() sets this value to pdTRUE then - * a context switch should be requested before the interrupt is exited. - * - * @return pdTRUE if the data was successfully sent to the queue, otherwise - * errQUEUE_FULL. - * - * Example usage for buffered IO (where the ISR can obtain more than one value - * per call): -
- void vBufferISR( void )
- {
- char cIn;
- BaseType_t xHigherPriorityTaskWoken;
-
-	// We have not woken a task at the start of the ISR.
-	xHigherPriorityTaskWoken = pdFALSE;
-
-	// Loop until the buffer is empty.
-	do
-	{
-		// Obtain a byte from the buffer.
-		cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS );
-
-		// Post the byte.
-		xQueueSendFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWoken );
-
-	} while( portINPUT_BYTE( BUFFER_COUNT ) );
-
-	// Now the buffer is empty we can switch context if necessary.
-	if( xHigherPriorityTaskWoken )
-	{
-		// Actual macro used here is port specific.
-		portYIELD_FROM_ISR ();
-	}
- }
- 
- * - * \defgroup xQueueSendFromISR xQueueSendFromISR - * \ingroup QueueManagement - */ -#define xQueueSendFromISR( xQueue, pvItemToQueue, pxHigherPriorityTaskWoken ) xQueueGenericSendFromISR( ( xQueue ), ( pvItemToQueue ), ( pxHigherPriorityTaskWoken ), queueSEND_TO_BACK ) - -/** - * queue. h - *
- BaseType_t xQueueGenericSendFromISR(
-										   QueueHandle_t		xQueue,
-										   const	void	*pvItemToQueue,
-										   BaseType_t	*pxHigherPriorityTaskWoken,
-										   BaseType_t	xCopyPosition
-									   );
- 
- * - * It is preferred that the macros xQueueSendFromISR(), - * xQueueSendToFrontFromISR() and xQueueSendToBackFromISR() be used in place - * of calling this function directly. xQueueGiveFromISR() is an - * equivalent for use by semaphores that don't actually copy any data. - * - * Post an item on a queue. It is safe to use this function from within an - * interrupt service routine. - * - * Items are queued by copy not reference so it is preferable to only - * queue small items, especially when called from an ISR. In most cases - * it would be preferable to store a pointer to the item being queued. - * - * @param xQueue The handle to the queue on which the item is to be posted. - * - * @param pvItemToQueue A pointer to the item that is to be placed on the - * queue. The size of the items the queue will hold was defined when the - * queue was created, so this many bytes will be copied from pvItemToQueue - * into the queue storage area. - * - * @param pxHigherPriorityTaskWoken xQueueGenericSendFromISR() will set - * *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task - * to unblock, and the unblocked task has a priority higher than the currently - * running task. If xQueueGenericSendFromISR() sets this value to pdTRUE then - * a context switch should be requested before the interrupt is exited. - * - * @param xCopyPosition Can take the value queueSEND_TO_BACK to place the - * item at the back of the queue, or queueSEND_TO_FRONT to place the item - * at the front of the queue (for high priority messages). - * - * @return pdTRUE if the data was successfully sent to the queue, otherwise - * errQUEUE_FULL. - * - * Example usage for buffered IO (where the ISR can obtain more than one value - * per call): -
- void vBufferISR( void )
- {
- char cIn;
- BaseType_t xHigherPriorityTaskWokenByPost;
-
-	// We have not woken a task at the start of the ISR.
-	xHigherPriorityTaskWokenByPost = pdFALSE;
-
-	// Loop until the buffer is empty.
-	do
-	{
-		// Obtain a byte from the buffer.
-		cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS );
-
-		// Post each byte.
-		xQueueGenericSendFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWokenByPost, queueSEND_TO_BACK );
-
-	} while( portINPUT_BYTE( BUFFER_COUNT ) );
-
-	// Now the buffer is empty we can switch context if necessary.  Note that the
-	// name of the yield function required is port specific.
-	if( xHigherPriorityTaskWokenByPost )
-	{
-		taskYIELD_YIELD_FROM_ISR();
-	}
- }
- 
- * - * \defgroup xQueueSendFromISR xQueueSendFromISR - * \ingroup QueueManagement - */ -BaseType_t xQueueGenericSendFromISR( QueueHandle_t xQueue, const void * const pvItemToQueue, BaseType_t * const pxHigherPriorityTaskWoken, const BaseType_t xCopyPosition ) PRIVILEGED_FUNCTION; -BaseType_t xQueueGiveFromISR( QueueHandle_t xQueue, BaseType_t * const pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; - -/** - * queue. h - *
- BaseType_t xQueueReceiveFromISR(
-									   QueueHandle_t	xQueue,
-									   void	*pvBuffer,
-									   BaseType_t *pxTaskWoken
-								   );
- * 
- * - * Receive an item from a queue. It is safe to use this function from within an - * interrupt service routine. - * - * @param xQueue The handle to the queue from which the item is to be - * received. - * - * @param pvBuffer Pointer to the buffer into which the received item will - * be copied. - * - * @param pxTaskWoken A task may be blocked waiting for space to become - * available on the queue. If xQueueReceiveFromISR causes such a task to - * unblock *pxTaskWoken will get set to pdTRUE, otherwise *pxTaskWoken will - * remain unchanged. - * - * @return pdTRUE if an item was successfully received from the queue, - * otherwise pdFALSE. - * - * Example usage: -
-
- QueueHandle_t xQueue;
-
- // Function to create a queue and post some values.
- void vAFunction( void *pvParameters )
- {
- char cValueToPost;
- const TickType_t xTicksToWait = ( TickType_t )0xff;
-
-	// Create a queue capable of containing 10 characters.
-	xQueue = xQueueCreate( 10, sizeof( char ) );
-	if( xQueue == 0 )
-	{
-		// Failed to create the queue.
-	}
-
-	// ...
-
-	// Post some characters that will be used within an ISR.  If the queue
-	// is full then this task will block for xTicksToWait ticks.
-	cValueToPost = 'a';
-	xQueueSend( xQueue, ( void * ) &cValueToPost, xTicksToWait );
-	cValueToPost = 'b';
-	xQueueSend( xQueue, ( void * ) &cValueToPost, xTicksToWait );
-
-	// ... keep posting characters ... this task may block when the queue
-	// becomes full.
-
-	cValueToPost = 'c';
-	xQueueSend( xQueue, ( void * ) &cValueToPost, xTicksToWait );
- }
-
- // ISR that outputs all the characters received on the queue.
- void vISR_Routine( void )
- {
- BaseType_t xTaskWokenByReceive = pdFALSE;
- char cRxedChar;
-
-	while( xQueueReceiveFromISR( xQueue, ( void * ) &cRxedChar, &xTaskWokenByReceive) )
-	{
-		// A character was received.  Output the character now.
-		vOutputCharacter( cRxedChar );
-
-		// If removing the character from the queue woke the task that was
-		// posting onto the queue cTaskWokenByReceive will have been set to
-		// pdTRUE.  No matter how many times this loop iterates only one
-		// task will be woken.
-	}
-
-	if( cTaskWokenByPost != ( char ) pdFALSE;
-	{
-		taskYIELD ();
-	}
- }
- 
- * \defgroup xQueueReceiveFromISR xQueueReceiveFromISR - * \ingroup QueueManagement - */ -BaseType_t xQueueReceiveFromISR( QueueHandle_t xQueue, void * const pvBuffer, BaseType_t * const pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; - -/* - * Utilities to query queues that are safe to use from an ISR. These utilities - * should be used only from witin an ISR, or within a critical section. - */ -BaseType_t xQueueIsQueueEmptyFromISR( const QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; -BaseType_t xQueueIsQueueFullFromISR( const QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; -UBaseType_t uxQueueMessagesWaitingFromISR( const QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; - -/* - * The functions defined above are for passing data to and from tasks. The - * functions below are the equivalents for passing data to and from - * co-routines. - * - * These functions are called from the co-routine macro implementation and - * should not be called directly from application code. Instead use the macro - * wrappers defined within croutine.h. - */ -BaseType_t xQueueCRSendFromISR( QueueHandle_t xQueue, const void *pvItemToQueue, BaseType_t xCoRoutinePreviouslyWoken ); -BaseType_t xQueueCRReceiveFromISR( QueueHandle_t xQueue, void *pvBuffer, BaseType_t *pxTaskWoken ); -BaseType_t xQueueCRSend( QueueHandle_t xQueue, const void *pvItemToQueue, TickType_t xTicksToWait ); -BaseType_t xQueueCRReceive( QueueHandle_t xQueue, void *pvBuffer, TickType_t xTicksToWait ); - -/* - * For internal use only. Use xSemaphoreCreateMutex(), - * xSemaphoreCreateCounting() or xSemaphoreGetMutexHolder() instead of calling - * these functions directly. - */ -QueueHandle_t xQueueCreateMutex( const uint8_t ucQueueType ) PRIVILEGED_FUNCTION; -QueueHandle_t xQueueCreateMutexStatic( const uint8_t ucQueueType, StaticQueue_t *pxStaticQueue ) PRIVILEGED_FUNCTION; -QueueHandle_t xQueueCreateCountingSemaphore( const UBaseType_t uxMaxCount, const UBaseType_t uxInitialCount ) PRIVILEGED_FUNCTION; -QueueHandle_t xQueueCreateCountingSemaphoreStatic( const UBaseType_t uxMaxCount, const UBaseType_t uxInitialCount, StaticQueue_t *pxStaticQueue ) PRIVILEGED_FUNCTION; -BaseType_t xQueueSemaphoreTake( QueueHandle_t xQueue, TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; -void* xQueueGetMutexHolder( QueueHandle_t xSemaphore ) PRIVILEGED_FUNCTION; -void* xQueueGetMutexHolderFromISR( QueueHandle_t xSemaphore ) PRIVILEGED_FUNCTION; - -/* - * For internal use only. Use xSemaphoreTakeMutexRecursive() or - * xSemaphoreGiveMutexRecursive() instead of calling these functions directly. - */ -BaseType_t xQueueTakeMutexRecursive( QueueHandle_t xMutex, TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; -BaseType_t xQueueGiveMutexRecursive( QueueHandle_t pxMutex ) PRIVILEGED_FUNCTION; - -/* - * Reset a queue back to its original empty state. The return value is now - * obsolete and is always set to pdPASS. - */ -#define xQueueReset( xQueue ) xQueueGenericReset( xQueue, pdFALSE ) - -/* - * The registry is provided as a means for kernel aware debuggers to - * locate queues, semaphores and mutexes. Call vQueueAddToRegistry() add - * a queue, semaphore or mutex handle to the registry if you want the handle - * to be available to a kernel aware debugger. If you are not using a kernel - * aware debugger then this function can be ignored. - * - * configQUEUE_REGISTRY_SIZE defines the maximum number of handles the - * registry can hold. configQUEUE_REGISTRY_SIZE must be greater than 0 - * within FreeRTOSConfig.h for the registry to be available. Its value - * does not effect the number of queues, semaphores and mutexes that can be - * created - just the number that the registry can hold. - * - * @param xQueue The handle of the queue being added to the registry. This - * is the handle returned by a call to xQueueCreate(). Semaphore and mutex - * handles can also be passed in here. - * - * @param pcName The name to be associated with the handle. This is the - * name that the kernel aware debugger will display. The queue registry only - * stores a pointer to the string - so the string must be persistent (global or - * preferably in ROM/Flash), not on the stack. - */ -#if( configQUEUE_REGISTRY_SIZE > 0 ) - void vQueueAddToRegistry( QueueHandle_t xQueue, const char *pcName ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ -#endif - -/* - * The registry is provided as a means for kernel aware debuggers to - * locate queues, semaphores and mutexes. Call vQueueAddToRegistry() add - * a queue, semaphore or mutex handle to the registry if you want the handle - * to be available to a kernel aware debugger, and vQueueUnregisterQueue() to - * remove the queue, semaphore or mutex from the register. If you are not using - * a kernel aware debugger then this function can be ignored. - * - * @param xQueue The handle of the queue being removed from the registry. - */ -#if( configQUEUE_REGISTRY_SIZE > 0 ) - void vQueueUnregisterQueue( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; -#endif - -/* - * The queue registry is provided as a means for kernel aware debuggers to - * locate queues, semaphores and mutexes. Call pcQueueGetName() to look - * up and return the name of a queue in the queue registry from the queue's - * handle. - * - * @param xQueue The handle of the queue the name of which will be returned. - * @return If the queue is in the registry then a pointer to the name of the - * queue is returned. If the queue is not in the registry then NULL is - * returned. - */ -#if( configQUEUE_REGISTRY_SIZE > 0 ) - const char *pcQueueGetName( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ -#endif - -/* - * Generic version of the function used to creaet a queue using dynamic memory - * allocation. This is called by other functions and macros that create other - * RTOS objects that use the queue structure as their base. - */ -#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - QueueHandle_t xQueueGenericCreate( const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, const uint8_t ucQueueType ) PRIVILEGED_FUNCTION; -#endif - -/* - * Generic version of the function used to creaet a queue using dynamic memory - * allocation. This is called by other functions and macros that create other - * RTOS objects that use the queue structure as their base. - */ -#if( configSUPPORT_STATIC_ALLOCATION == 1 ) - QueueHandle_t xQueueGenericCreateStatic( const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, uint8_t *pucQueueStorage, StaticQueue_t *pxStaticQueue, const uint8_t ucQueueType ) PRIVILEGED_FUNCTION; -#endif - -/* - * Queue sets provide a mechanism to allow a task to block (pend) on a read - * operation from multiple queues or semaphores simultaneously. - * - * See FreeRTOS/Source/Demo/Common/Minimal/QueueSet.c for an example using this - * function. - * - * A queue set must be explicitly created using a call to xQueueCreateSet() - * before it can be used. Once created, standard FreeRTOS queues and semaphores - * can be added to the set using calls to xQueueAddToSet(). - * xQueueSelectFromSet() is then used to determine which, if any, of the queues - * or semaphores contained in the set is in a state where a queue read or - * semaphore take operation would be successful. - * - * Note 1: See the documentation on http://wwwFreeRTOS.org/RTOS-queue-sets.html - * for reasons why queue sets are very rarely needed in practice as there are - * simpler methods of blocking on multiple objects. - * - * Note 2: Blocking on a queue set that contains a mutex will not cause the - * mutex holder to inherit the priority of the blocked task. - * - * Note 3: An additional 4 bytes of RAM is required for each space in a every - * queue added to a queue set. Therefore counting semaphores that have a high - * maximum count value should not be added to a queue set. - * - * Note 4: A receive (in the case of a queue) or take (in the case of a - * semaphore) operation must not be performed on a member of a queue set unless - * a call to xQueueSelectFromSet() has first returned a handle to that set member. - * - * @param uxEventQueueLength Queue sets store events that occur on - * the queues and semaphores contained in the set. uxEventQueueLength specifies - * the maximum number of events that can be queued at once. To be absolutely - * certain that events are not lost uxEventQueueLength should be set to the - * total sum of the length of the queues added to the set, where binary - * semaphores and mutexes have a length of 1, and counting semaphores have a - * length set by their maximum count value. Examples: - * + If a queue set is to hold a queue of length 5, another queue of length 12, - * and a binary semaphore, then uxEventQueueLength should be set to - * (5 + 12 + 1), or 18. - * + If a queue set is to hold three binary semaphores then uxEventQueueLength - * should be set to (1 + 1 + 1 ), or 3. - * + If a queue set is to hold a counting semaphore that has a maximum count of - * 5, and a counting semaphore that has a maximum count of 3, then - * uxEventQueueLength should be set to (5 + 3), or 8. - * - * @return If the queue set is created successfully then a handle to the created - * queue set is returned. Otherwise NULL is returned. - */ -QueueSetHandle_t xQueueCreateSet( const UBaseType_t uxEventQueueLength ) PRIVILEGED_FUNCTION; - -/* - * Adds a queue or semaphore to a queue set that was previously created by a - * call to xQueueCreateSet(). - * - * See FreeRTOS/Source/Demo/Common/Minimal/QueueSet.c for an example using this - * function. - * - * Note 1: A receive (in the case of a queue) or take (in the case of a - * semaphore) operation must not be performed on a member of a queue set unless - * a call to xQueueSelectFromSet() has first returned a handle to that set member. - * - * @param xQueueOrSemaphore The handle of the queue or semaphore being added to - * the queue set (cast to an QueueSetMemberHandle_t type). - * - * @param xQueueSet The handle of the queue set to which the queue or semaphore - * is being added. - * - * @return If the queue or semaphore was successfully added to the queue set - * then pdPASS is returned. If the queue could not be successfully added to the - * queue set because it is already a member of a different queue set then pdFAIL - * is returned. - */ -BaseType_t xQueueAddToSet( QueueSetMemberHandle_t xQueueOrSemaphore, QueueSetHandle_t xQueueSet ) PRIVILEGED_FUNCTION; - -/* - * Removes a queue or semaphore from a queue set. A queue or semaphore can only - * be removed from a set if the queue or semaphore is empty. - * - * See FreeRTOS/Source/Demo/Common/Minimal/QueueSet.c for an example using this - * function. - * - * @param xQueueOrSemaphore The handle of the queue or semaphore being removed - * from the queue set (cast to an QueueSetMemberHandle_t type). - * - * @param xQueueSet The handle of the queue set in which the queue or semaphore - * is included. - * - * @return If the queue or semaphore was successfully removed from the queue set - * then pdPASS is returned. If the queue was not in the queue set, or the - * queue (or semaphore) was not empty, then pdFAIL is returned. - */ -BaseType_t xQueueRemoveFromSet( QueueSetMemberHandle_t xQueueOrSemaphore, QueueSetHandle_t xQueueSet ) PRIVILEGED_FUNCTION; - -/* - * xQueueSelectFromSet() selects from the members of a queue set a queue or - * semaphore that either contains data (in the case of a queue) or is available - * to take (in the case of a semaphore). xQueueSelectFromSet() effectively - * allows a task to block (pend) on a read operation on all the queues and - * semaphores in a queue set simultaneously. - * - * See FreeRTOS/Source/Demo/Common/Minimal/QueueSet.c for an example using this - * function. - * - * Note 1: See the documentation on http://wwwFreeRTOS.org/RTOS-queue-sets.html - * for reasons why queue sets are very rarely needed in practice as there are - * simpler methods of blocking on multiple objects. - * - * Note 2: Blocking on a queue set that contains a mutex will not cause the - * mutex holder to inherit the priority of the blocked task. - * - * Note 3: A receive (in the case of a queue) or take (in the case of a - * semaphore) operation must not be performed on a member of a queue set unless - * a call to xQueueSelectFromSet() has first returned a handle to that set member. - * - * @param xQueueSet The queue set on which the task will (potentially) block. - * - * @param xTicksToWait The maximum time, in ticks, that the calling task will - * remain in the Blocked state (with other tasks executing) to wait for a member - * of the queue set to be ready for a successful queue read or semaphore take - * operation. - * - * @return xQueueSelectFromSet() will return the handle of a queue (cast to - * a QueueSetMemberHandle_t type) contained in the queue set that contains data, - * or the handle of a semaphore (cast to a QueueSetMemberHandle_t type) contained - * in the queue set that is available, or NULL if no such queue or semaphore - * exists before before the specified block time expires. - */ -QueueSetMemberHandle_t xQueueSelectFromSet( QueueSetHandle_t xQueueSet, const TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; - -/* - * A version of xQueueSelectFromSet() that can be used from an ISR. - */ -QueueSetMemberHandle_t xQueueSelectFromSetFromISR( QueueSetHandle_t xQueueSet ) PRIVILEGED_FUNCTION; - -/* Not public API functions. */ -void vQueueWaitForMessageRestricted( QueueHandle_t xQueue, TickType_t xTicksToWait, const BaseType_t xWaitIndefinitely ) PRIVILEGED_FUNCTION; -BaseType_t xQueueGenericReset( QueueHandle_t xQueue, BaseType_t xNewQueue ) PRIVILEGED_FUNCTION; -void vQueueSetQueueNumber( QueueHandle_t xQueue, UBaseType_t uxQueueNumber ) PRIVILEGED_FUNCTION; -UBaseType_t uxQueueGetQueueNumber( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; -uint8_t ucQueueGetQueueType( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; - - -#ifdef __cplusplus -} -#endif - -#endif /* QUEUE_H */ - diff --git a/lib/FreeRTOS/Source/include/semphr.h b/lib/FreeRTOS/Source/include/semphr.h deleted file mode 100644 index e603b4af..00000000 --- a/lib/FreeRTOS/Source/include/semphr.h +++ /dev/null @@ -1,1140 +0,0 @@ -/* - * FreeRTOS Kernel V10.0.1 - * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * 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. - * - * http://www.FreeRTOS.org - * http://aws.amazon.com/freertos - * - * 1 tab == 4 spaces! - */ - -#ifndef SEMAPHORE_H -#define SEMAPHORE_H - -#ifndef INC_FREERTOS_H - #error "include FreeRTOS.h" must appear in source files before "include semphr.h" -#endif - -#include "queue.h" - -typedef QueueHandle_t SemaphoreHandle_t; - -#define semBINARY_SEMAPHORE_QUEUE_LENGTH ( ( uint8_t ) 1U ) -#define semSEMAPHORE_QUEUE_ITEM_LENGTH ( ( uint8_t ) 0U ) -#define semGIVE_BLOCK_TIME ( ( TickType_t ) 0U ) - - -/** - * semphr. h - *
vSemaphoreCreateBinary( SemaphoreHandle_t xSemaphore )
- * - * In many usage scenarios it is faster and more memory efficient to use a - * direct to task notification in place of a binary semaphore! - * http://www.freertos.org/RTOS-task-notifications.html - * - * This old vSemaphoreCreateBinary() macro is now deprecated in favour of the - * xSemaphoreCreateBinary() function. Note that binary semaphores created using - * the vSemaphoreCreateBinary() macro are created in a state such that the - * first call to 'take' the semaphore would pass, whereas binary semaphores - * created using xSemaphoreCreateBinary() are created in a state such that the - * the semaphore must first be 'given' before it can be 'taken'. - * - * Macro that implements a semaphore by using the existing queue mechanism. - * The queue length is 1 as this is a binary semaphore. The data size is 0 - * as we don't want to actually store any data - we just want to know if the - * queue is empty or full. - * - * This type of semaphore can be used for pure synchronisation between tasks or - * between an interrupt and a task. The semaphore need not be given back once - * obtained, so one task/interrupt can continuously 'give' the semaphore while - * another continuously 'takes' the semaphore. For this reason this type of - * semaphore does not use a priority inheritance mechanism. For an alternative - * that does use priority inheritance see xSemaphoreCreateMutex(). - * - * @param xSemaphore Handle to the created semaphore. Should be of type SemaphoreHandle_t. - * - * Example usage: -
- SemaphoreHandle_t xSemaphore = NULL;
-
- void vATask( void * pvParameters )
- {
-    // Semaphore cannot be used before a call to vSemaphoreCreateBinary ().
-    // This is a macro so pass the variable in directly.
-    vSemaphoreCreateBinary( xSemaphore );
-
-    if( xSemaphore != NULL )
-    {
-        // The semaphore was created successfully.
-        // The semaphore can now be used.
-    }
- }
- 
- * \defgroup vSemaphoreCreateBinary vSemaphoreCreateBinary - * \ingroup Semaphores - */ -#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - #define vSemaphoreCreateBinary( xSemaphore ) \ - { \ - ( xSemaphore ) = xQueueGenericCreate( ( UBaseType_t ) 1, semSEMAPHORE_QUEUE_ITEM_LENGTH, queueQUEUE_TYPE_BINARY_SEMAPHORE ); \ - if( ( xSemaphore ) != NULL ) \ - { \ - ( void ) xSemaphoreGive( ( xSemaphore ) ); \ - } \ - } -#endif - -/** - * semphr. h - *
SemaphoreHandle_t xSemaphoreCreateBinary( void )
- * - * Creates a new binary semaphore instance, and returns a handle by which the - * new semaphore can be referenced. - * - * In many usage scenarios it is faster and more memory efficient to use a - * direct to task notification in place of a binary semaphore! - * http://www.freertos.org/RTOS-task-notifications.html - * - * Internally, within the FreeRTOS implementation, binary semaphores use a block - * of memory, in which the semaphore structure is stored. If a binary semaphore - * is created using xSemaphoreCreateBinary() then the required memory is - * automatically dynamically allocated inside the xSemaphoreCreateBinary() - * function. (see http://www.freertos.org/a00111.html). If a binary semaphore - * is created using xSemaphoreCreateBinaryStatic() then the application writer - * must provide the memory. xSemaphoreCreateBinaryStatic() therefore allows a - * binary semaphore to be created without using any dynamic memory allocation. - * - * The old vSemaphoreCreateBinary() macro is now deprecated in favour of this - * xSemaphoreCreateBinary() function. Note that binary semaphores created using - * the vSemaphoreCreateBinary() macro are created in a state such that the - * first call to 'take' the semaphore would pass, whereas binary semaphores - * created using xSemaphoreCreateBinary() are created in a state such that the - * the semaphore must first be 'given' before it can be 'taken'. - * - * This type of semaphore can be used for pure synchronisation between tasks or - * between an interrupt and a task. The semaphore need not be given back once - * obtained, so one task/interrupt can continuously 'give' the semaphore while - * another continuously 'takes' the semaphore. For this reason this type of - * semaphore does not use a priority inheritance mechanism. For an alternative - * that does use priority inheritance see xSemaphoreCreateMutex(). - * - * @return Handle to the created semaphore, or NULL if the memory required to - * hold the semaphore's data structures could not be allocated. - * - * Example usage: -
- SemaphoreHandle_t xSemaphore = NULL;
-
- void vATask( void * pvParameters )
- {
-    // Semaphore cannot be used before a call to xSemaphoreCreateBinary().
-    // This is a macro so pass the variable in directly.
-    xSemaphore = xSemaphoreCreateBinary();
-
-    if( xSemaphore != NULL )
-    {
-        // The semaphore was created successfully.
-        // The semaphore can now be used.
-    }
- }
- 
- * \defgroup xSemaphoreCreateBinary xSemaphoreCreateBinary - * \ingroup Semaphores - */ -#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - #define xSemaphoreCreateBinary() xQueueGenericCreate( ( UBaseType_t ) 1, semSEMAPHORE_QUEUE_ITEM_LENGTH, queueQUEUE_TYPE_BINARY_SEMAPHORE ) -#endif - -/** - * semphr. h - *
SemaphoreHandle_t xSemaphoreCreateBinaryStatic( StaticSemaphore_t *pxSemaphoreBuffer )
- * - * Creates a new binary semaphore instance, and returns a handle by which the - * new semaphore can be referenced. - * - * NOTE: In many usage scenarios it is faster and more memory efficient to use a - * direct to task notification in place of a binary semaphore! - * http://www.freertos.org/RTOS-task-notifications.html - * - * Internally, within the FreeRTOS implementation, binary semaphores use a block - * of memory, in which the semaphore structure is stored. If a binary semaphore - * is created using xSemaphoreCreateBinary() then the required memory is - * automatically dynamically allocated inside the xSemaphoreCreateBinary() - * function. (see http://www.freertos.org/a00111.html). If a binary semaphore - * is created using xSemaphoreCreateBinaryStatic() then the application writer - * must provide the memory. xSemaphoreCreateBinaryStatic() therefore allows a - * binary semaphore to be created without using any dynamic memory allocation. - * - * This type of semaphore can be used for pure synchronisation between tasks or - * between an interrupt and a task. The semaphore need not be given back once - * obtained, so one task/interrupt can continuously 'give' the semaphore while - * another continuously 'takes' the semaphore. For this reason this type of - * semaphore does not use a priority inheritance mechanism. For an alternative - * that does use priority inheritance see xSemaphoreCreateMutex(). - * - * @param pxSemaphoreBuffer Must point to a variable of type StaticSemaphore_t, - * which will then be used to hold the semaphore's data structure, removing the - * need for the memory to be allocated dynamically. - * - * @return If the semaphore is created then a handle to the created semaphore is - * returned. If pxSemaphoreBuffer is NULL then NULL is returned. - * - * Example usage: -
- SemaphoreHandle_t xSemaphore = NULL;
- StaticSemaphore_t xSemaphoreBuffer;
-
- void vATask( void * pvParameters )
- {
-    // Semaphore cannot be used before a call to xSemaphoreCreateBinary().
-    // The semaphore's data structures will be placed in the xSemaphoreBuffer
-    // variable, the address of which is passed into the function.  The
-    // function's parameter is not NULL, so the function will not attempt any
-    // dynamic memory allocation, and therefore the function will not return
-    // return NULL.
-    xSemaphore = xSemaphoreCreateBinary( &xSemaphoreBuffer );
-
-    // Rest of task code goes here.
- }
- 
- * \defgroup xSemaphoreCreateBinaryStatic xSemaphoreCreateBinaryStatic - * \ingroup Semaphores - */ -#if( configSUPPORT_STATIC_ALLOCATION == 1 ) - #define xSemaphoreCreateBinaryStatic( pxStaticSemaphore ) xQueueGenericCreateStatic( ( UBaseType_t ) 1, semSEMAPHORE_QUEUE_ITEM_LENGTH, NULL, pxStaticSemaphore, queueQUEUE_TYPE_BINARY_SEMAPHORE ) -#endif /* configSUPPORT_STATIC_ALLOCATION */ - -/** - * semphr. h - *
xSemaphoreTake(
- *                   SemaphoreHandle_t xSemaphore,
- *                   TickType_t xBlockTime
- *               )
- * - * Macro to obtain a semaphore. The semaphore must have previously been - * created with a call to xSemaphoreCreateBinary(), xSemaphoreCreateMutex() or - * xSemaphoreCreateCounting(). - * - * @param xSemaphore A handle to the semaphore being taken - obtained when - * the semaphore was created. - * - * @param xBlockTime The time in ticks to wait for the semaphore to become - * available. The macro portTICK_PERIOD_MS can be used to convert this to a - * real time. A block time of zero can be used to poll the semaphore. A block - * time of portMAX_DELAY can be used to block indefinitely (provided - * INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h). - * - * @return pdTRUE if the semaphore was obtained. pdFALSE - * if xBlockTime expired without the semaphore becoming available. - * - * Example usage: -
- SemaphoreHandle_t xSemaphore = NULL;
-
- // A task that creates a semaphore.
- void vATask( void * pvParameters )
- {
-    // Create the semaphore to guard a shared resource.
-    xSemaphore = xSemaphoreCreateBinary();
- }
-
- // A task that uses the semaphore.
- void vAnotherTask( void * pvParameters )
- {
-    // ... Do other things.
-
-    if( xSemaphore != NULL )
-    {
-        // See if we can obtain the semaphore.  If the semaphore is not available
-        // wait 10 ticks to see if it becomes free.
-        if( xSemaphoreTake( xSemaphore, ( TickType_t ) 10 ) == pdTRUE )
-        {
-            // We were able to obtain the semaphore and can now access the
-            // shared resource.
-
-            // ...
-
-            // We have finished accessing the shared resource.  Release the
-            // semaphore.
-            xSemaphoreGive( xSemaphore );
-        }
-        else
-        {
-            // We could not obtain the semaphore and can therefore not access
-            // the shared resource safely.
-        }
-    }
- }
- 
- * \defgroup xSemaphoreTake xSemaphoreTake - * \ingroup Semaphores - */ -#define xSemaphoreTake( xSemaphore, xBlockTime ) xQueueSemaphoreTake( ( xSemaphore ), ( xBlockTime ) ) - -/** - * semphr. h - * xSemaphoreTakeRecursive( - * SemaphoreHandle_t xMutex, - * TickType_t xBlockTime - * ) - * - * Macro to recursively obtain, or 'take', a mutex type semaphore. - * The mutex must have previously been created using a call to - * xSemaphoreCreateRecursiveMutex(); - * - * configUSE_RECURSIVE_MUTEXES must be set to 1 in FreeRTOSConfig.h for this - * macro to be available. - * - * This macro must not be used on mutexes created using xSemaphoreCreateMutex(). - * - * A mutex used recursively can be 'taken' repeatedly by the owner. The mutex - * doesn't become available again until the owner has called - * xSemaphoreGiveRecursive() for each successful 'take' request. For example, - * if a task successfully 'takes' the same mutex 5 times then the mutex will - * not be available to any other task until it has also 'given' the mutex back - * exactly five times. - * - * @param xMutex A handle to the mutex being obtained. This is the - * handle returned by xSemaphoreCreateRecursiveMutex(); - * - * @param xBlockTime The time in ticks to wait for the semaphore to become - * available. The macro portTICK_PERIOD_MS can be used to convert this to a - * real time. A block time of zero can be used to poll the semaphore. If - * the task already owns the semaphore then xSemaphoreTakeRecursive() will - * return immediately no matter what the value of xBlockTime. - * - * @return pdTRUE if the semaphore was obtained. pdFALSE if xBlockTime - * expired without the semaphore becoming available. - * - * Example usage: -
- SemaphoreHandle_t xMutex = NULL;
-
- // A task that creates a mutex.
- void vATask( void * pvParameters )
- {
-    // Create the mutex to guard a shared resource.
-    xMutex = xSemaphoreCreateRecursiveMutex();
- }
-
- // A task that uses the mutex.
- void vAnotherTask( void * pvParameters )
- {
-    // ... Do other things.
-
-    if( xMutex != NULL )
-    {
-        // See if we can obtain the mutex.  If the mutex is not available
-        // wait 10 ticks to see if it becomes free.
-        if( xSemaphoreTakeRecursive( xSemaphore, ( TickType_t ) 10 ) == pdTRUE )
-        {
-            // We were able to obtain the mutex and can now access the
-            // shared resource.
-
-            // ...
-            // For some reason due to the nature of the code further calls to
-            // xSemaphoreTakeRecursive() are made on the same mutex.  In real
-            // code these would not be just sequential calls as this would make
-            // no sense.  Instead the calls are likely to be buried inside
-            // a more complex call structure.
-            xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 );
-            xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 );
-
-            // The mutex has now been 'taken' three times, so will not be
-            // available to another task until it has also been given back
-            // three times.  Again it is unlikely that real code would have
-            // these calls sequentially, but instead buried in a more complex
-            // call structure.  This is just for illustrative purposes.
-            xSemaphoreGiveRecursive( xMutex );
-            xSemaphoreGiveRecursive( xMutex );
-            xSemaphoreGiveRecursive( xMutex );
-
-            // Now the mutex can be taken by other tasks.
-        }
-        else
-        {
-            // We could not obtain the mutex and can therefore not access
-            // the shared resource safely.
-        }
-    }
- }
- 
- * \defgroup xSemaphoreTakeRecursive xSemaphoreTakeRecursive - * \ingroup Semaphores - */ -#if( configUSE_RECURSIVE_MUTEXES == 1 ) - #define xSemaphoreTakeRecursive( xMutex, xBlockTime ) xQueueTakeMutexRecursive( ( xMutex ), ( xBlockTime ) ) -#endif - -/** - * semphr. h - *
xSemaphoreGive( SemaphoreHandle_t xSemaphore )
- * - * Macro to release a semaphore. The semaphore must have previously been - * created with a call to xSemaphoreCreateBinary(), xSemaphoreCreateMutex() or - * xSemaphoreCreateCounting(). and obtained using sSemaphoreTake(). - * - * This macro must not be used from an ISR. See xSemaphoreGiveFromISR () for - * an alternative which can be used from an ISR. - * - * This macro must also not be used on semaphores created using - * xSemaphoreCreateRecursiveMutex(). - * - * @param xSemaphore A handle to the semaphore being released. This is the - * handle returned when the semaphore was created. - * - * @return pdTRUE if the semaphore was released. pdFALSE if an error occurred. - * Semaphores are implemented using queues. An error can occur if there is - * no space on the queue to post a message - indicating that the - * semaphore was not first obtained correctly. - * - * Example usage: -
- SemaphoreHandle_t xSemaphore = NULL;
-
- void vATask( void * pvParameters )
- {
-    // Create the semaphore to guard a shared resource.
-    xSemaphore = vSemaphoreCreateBinary();
-
-    if( xSemaphore != NULL )
-    {
-        if( xSemaphoreGive( xSemaphore ) != pdTRUE )
-        {
-            // We would expect this call to fail because we cannot give
-            // a semaphore without first "taking" it!
-        }
-
-        // Obtain the semaphore - don't block if the semaphore is not
-        // immediately available.
-        if( xSemaphoreTake( xSemaphore, ( TickType_t ) 0 ) )
-        {
-            // We now have the semaphore and can access the shared resource.
-
-            // ...
-
-            // We have finished accessing the shared resource so can free the
-            // semaphore.
-            if( xSemaphoreGive( xSemaphore ) != pdTRUE )
-            {
-                // We would not expect this call to fail because we must have
-                // obtained the semaphore to get here.
-            }
-        }
-    }
- }
- 
- * \defgroup xSemaphoreGive xSemaphoreGive - * \ingroup Semaphores - */ -#define xSemaphoreGive( xSemaphore ) xQueueGenericSend( ( QueueHandle_t ) ( xSemaphore ), NULL, semGIVE_BLOCK_TIME, queueSEND_TO_BACK ) - -/** - * semphr. h - *
xSemaphoreGiveRecursive( SemaphoreHandle_t xMutex )
- * - * Macro to recursively release, or 'give', a mutex type semaphore. - * The mutex must have previously been created using a call to - * xSemaphoreCreateRecursiveMutex(); - * - * configUSE_RECURSIVE_MUTEXES must be set to 1 in FreeRTOSConfig.h for this - * macro to be available. - * - * This macro must not be used on mutexes created using xSemaphoreCreateMutex(). - * - * A mutex used recursively can be 'taken' repeatedly by the owner. The mutex - * doesn't become available again until the owner has called - * xSemaphoreGiveRecursive() for each successful 'take' request. For example, - * if a task successfully 'takes' the same mutex 5 times then the mutex will - * not be available to any other task until it has also 'given' the mutex back - * exactly five times. - * - * @param xMutex A handle to the mutex being released, or 'given'. This is the - * handle returned by xSemaphoreCreateMutex(); - * - * @return pdTRUE if the semaphore was given. - * - * Example usage: -
- SemaphoreHandle_t xMutex = NULL;
-
- // A task that creates a mutex.
- void vATask( void * pvParameters )
- {
-    // Create the mutex to guard a shared resource.
-    xMutex = xSemaphoreCreateRecursiveMutex();
- }
-
- // A task that uses the mutex.
- void vAnotherTask( void * pvParameters )
- {
-    // ... Do other things.
-
-    if( xMutex != NULL )
-    {
-        // See if we can obtain the mutex.  If the mutex is not available
-        // wait 10 ticks to see if it becomes free.
-        if( xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 ) == pdTRUE )
-        {
-            // We were able to obtain the mutex and can now access the
-            // shared resource.
-
-            // ...
-            // For some reason due to the nature of the code further calls to
-			// xSemaphoreTakeRecursive() are made on the same mutex.  In real
-			// code these would not be just sequential calls as this would make
-			// no sense.  Instead the calls are likely to be buried inside
-			// a more complex call structure.
-            xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 );
-            xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 );
-
-            // The mutex has now been 'taken' three times, so will not be
-			// available to another task until it has also been given back
-			// three times.  Again it is unlikely that real code would have
-			// these calls sequentially, it would be more likely that the calls
-			// to xSemaphoreGiveRecursive() would be called as a call stack
-			// unwound.  This is just for demonstrative purposes.
-            xSemaphoreGiveRecursive( xMutex );
-			xSemaphoreGiveRecursive( xMutex );
-			xSemaphoreGiveRecursive( xMutex );
-
-			// Now the mutex can be taken by other tasks.
-        }
-        else
-        {
-            // We could not obtain the mutex and can therefore not access
-            // the shared resource safely.
-        }
-    }
- }
- 
- * \defgroup xSemaphoreGiveRecursive xSemaphoreGiveRecursive - * \ingroup Semaphores - */ -#if( configUSE_RECURSIVE_MUTEXES == 1 ) - #define xSemaphoreGiveRecursive( xMutex ) xQueueGiveMutexRecursive( ( xMutex ) ) -#endif - -/** - * semphr. h - *
- xSemaphoreGiveFromISR(
-                          SemaphoreHandle_t xSemaphore,
-                          BaseType_t *pxHigherPriorityTaskWoken
-                      )
- * - * Macro to release a semaphore. The semaphore must have previously been - * created with a call to xSemaphoreCreateBinary() or xSemaphoreCreateCounting(). - * - * Mutex type semaphores (those created using a call to xSemaphoreCreateMutex()) - * must not be used with this macro. - * - * This macro can be used from an ISR. - * - * @param xSemaphore A handle to the semaphore being released. This is the - * handle returned when the semaphore was created. - * - * @param pxHigherPriorityTaskWoken xSemaphoreGiveFromISR() will set - * *pxHigherPriorityTaskWoken to pdTRUE if giving the semaphore caused a task - * to unblock, and the unblocked task has a priority higher than the currently - * running task. If xSemaphoreGiveFromISR() sets this value to pdTRUE then - * a context switch should be requested before the interrupt is exited. - * - * @return pdTRUE if the semaphore was successfully given, otherwise errQUEUE_FULL. - * - * Example usage: -
- \#define LONG_TIME 0xffff
- \#define TICKS_TO_WAIT	10
- SemaphoreHandle_t xSemaphore = NULL;
-
- // Repetitive task.
- void vATask( void * pvParameters )
- {
-    for( ;; )
-    {
-        // We want this task to run every 10 ticks of a timer.  The semaphore
-        // was created before this task was started.
-
-        // Block waiting for the semaphore to become available.
-        if( xSemaphoreTake( xSemaphore, LONG_TIME ) == pdTRUE )
-        {
-            // It is time to execute.
-
-            // ...
-
-            // We have finished our task.  Return to the top of the loop where
-            // we will block on the semaphore until it is time to execute
-            // again.  Note when using the semaphore for synchronisation with an
-			// ISR in this manner there is no need to 'give' the semaphore back.
-        }
-    }
- }
-
- // Timer ISR
- void vTimerISR( void * pvParameters )
- {
- static uint8_t ucLocalTickCount = 0;
- static BaseType_t xHigherPriorityTaskWoken;
-
-    // A timer tick has occurred.
-
-    // ... Do other time functions.
-
-    // Is it time for vATask () to run?
-	xHigherPriorityTaskWoken = pdFALSE;
-    ucLocalTickCount++;
-    if( ucLocalTickCount >= TICKS_TO_WAIT )
-    {
-        // Unblock the task by releasing the semaphore.
-        xSemaphoreGiveFromISR( xSemaphore, &xHigherPriorityTaskWoken );
-
-        // Reset the count so we release the semaphore again in 10 ticks time.
-        ucLocalTickCount = 0;
-    }
-
-    if( xHigherPriorityTaskWoken != pdFALSE )
-    {
-        // We can force a context switch here.  Context switching from an
-        // ISR uses port specific syntax.  Check the demo task for your port
-        // to find the syntax required.
-    }
- }
- 
- * \defgroup xSemaphoreGiveFromISR xSemaphoreGiveFromISR - * \ingroup Semaphores - */ -#define xSemaphoreGiveFromISR( xSemaphore, pxHigherPriorityTaskWoken ) xQueueGiveFromISR( ( QueueHandle_t ) ( xSemaphore ), ( pxHigherPriorityTaskWoken ) ) - -/** - * semphr. h - *
- xSemaphoreTakeFromISR(
-                          SemaphoreHandle_t xSemaphore,
-                          BaseType_t *pxHigherPriorityTaskWoken
-                      )
- * - * Macro to take a semaphore from an ISR. The semaphore must have - * previously been created with a call to xSemaphoreCreateBinary() or - * xSemaphoreCreateCounting(). - * - * Mutex type semaphores (those created using a call to xSemaphoreCreateMutex()) - * must not be used with this macro. - * - * This macro can be used from an ISR, however taking a semaphore from an ISR - * is not a common operation. It is likely to only be useful when taking a - * counting semaphore when an interrupt is obtaining an object from a resource - * pool (when the semaphore count indicates the number of resources available). - * - * @param xSemaphore A handle to the semaphore being taken. This is the - * handle returned when the semaphore was created. - * - * @param pxHigherPriorityTaskWoken xSemaphoreTakeFromISR() will set - * *pxHigherPriorityTaskWoken to pdTRUE if taking the semaphore caused a task - * to unblock, and the unblocked task has a priority higher than the currently - * running task. If xSemaphoreTakeFromISR() sets this value to pdTRUE then - * a context switch should be requested before the interrupt is exited. - * - * @return pdTRUE if the semaphore was successfully taken, otherwise - * pdFALSE - */ -#define xSemaphoreTakeFromISR( xSemaphore, pxHigherPriorityTaskWoken ) xQueueReceiveFromISR( ( QueueHandle_t ) ( xSemaphore ), NULL, ( pxHigherPriorityTaskWoken ) ) - -/** - * semphr. h - *
SemaphoreHandle_t xSemaphoreCreateMutex( void )
- * - * Creates a new mutex type semaphore instance, and returns a handle by which - * the new mutex can be referenced. - * - * Internally, within the FreeRTOS implementation, mutex semaphores use a block - * of memory, in which the mutex structure is stored. If a mutex is created - * using xSemaphoreCreateMutex() then the required memory is automatically - * dynamically allocated inside the xSemaphoreCreateMutex() function. (see - * http://www.freertos.org/a00111.html). If a mutex is created using - * xSemaphoreCreateMutexStatic() then the application writer must provided the - * memory. xSemaphoreCreateMutexStatic() therefore allows a mutex to be created - * without using any dynamic memory allocation. - * - * Mutexes created using this function can be accessed using the xSemaphoreTake() - * and xSemaphoreGive() macros. The xSemaphoreTakeRecursive() and - * xSemaphoreGiveRecursive() macros must not be used. - * - * This type of semaphore uses a priority inheritance mechanism so a task - * 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the - * semaphore it is no longer required. - * - * Mutex type semaphores cannot be used from within interrupt service routines. - * - * See xSemaphoreCreateBinary() for an alternative implementation that can be - * used for pure synchronisation (where one task or interrupt always 'gives' the - * semaphore and another always 'takes' the semaphore) and from within interrupt - * service routines. - * - * @return If the mutex was successfully created then a handle to the created - * semaphore is returned. If there was not enough heap to allocate the mutex - * data structures then NULL is returned. - * - * Example usage: -
- SemaphoreHandle_t xSemaphore;
-
- void vATask( void * pvParameters )
- {
-    // Semaphore cannot be used before a call to xSemaphoreCreateMutex().
-    // This is a macro so pass the variable in directly.
-    xSemaphore = xSemaphoreCreateMutex();
-
-    if( xSemaphore != NULL )
-    {
-        // The semaphore was created successfully.
-        // The semaphore can now be used.
-    }
- }
- 
- * \defgroup xSemaphoreCreateMutex xSemaphoreCreateMutex - * \ingroup Semaphores - */ -#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - #define xSemaphoreCreateMutex() xQueueCreateMutex( queueQUEUE_TYPE_MUTEX ) -#endif - -/** - * semphr. h - *
SemaphoreHandle_t xSemaphoreCreateMutexStatic( StaticSemaphore_t *pxMutexBuffer )
- * - * Creates a new mutex type semaphore instance, and returns a handle by which - * the new mutex can be referenced. - * - * Internally, within the FreeRTOS implementation, mutex semaphores use a block - * of memory, in which the mutex structure is stored. If a mutex is created - * using xSemaphoreCreateMutex() then the required memory is automatically - * dynamically allocated inside the xSemaphoreCreateMutex() function. (see - * http://www.freertos.org/a00111.html). If a mutex is created using - * xSemaphoreCreateMutexStatic() then the application writer must provided the - * memory. xSemaphoreCreateMutexStatic() therefore allows a mutex to be created - * without using any dynamic memory allocation. - * - * Mutexes created using this function can be accessed using the xSemaphoreTake() - * and xSemaphoreGive() macros. The xSemaphoreTakeRecursive() and - * xSemaphoreGiveRecursive() macros must not be used. - * - * This type of semaphore uses a priority inheritance mechanism so a task - * 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the - * semaphore it is no longer required. - * - * Mutex type semaphores cannot be used from within interrupt service routines. - * - * See xSemaphoreCreateBinary() for an alternative implementation that can be - * used for pure synchronisation (where one task or interrupt always 'gives' the - * semaphore and another always 'takes' the semaphore) and from within interrupt - * service routines. - * - * @param pxMutexBuffer Must point to a variable of type StaticSemaphore_t, - * which will be used to hold the mutex's data structure, removing the need for - * the memory to be allocated dynamically. - * - * @return If the mutex was successfully created then a handle to the created - * mutex is returned. If pxMutexBuffer was NULL then NULL is returned. - * - * Example usage: -
- SemaphoreHandle_t xSemaphore;
- StaticSemaphore_t xMutexBuffer;
-
- void vATask( void * pvParameters )
- {
-    // A mutex cannot be used before it has been created.  xMutexBuffer is
-    // into xSemaphoreCreateMutexStatic() so no dynamic memory allocation is
-    // attempted.
-    xSemaphore = xSemaphoreCreateMutexStatic( &xMutexBuffer );
-
-    // As no dynamic memory allocation was performed, xSemaphore cannot be NULL,
-    // so there is no need to check it.
- }
- 
- * \defgroup xSemaphoreCreateMutexStatic xSemaphoreCreateMutexStatic - * \ingroup Semaphores - */ - #if( configSUPPORT_STATIC_ALLOCATION == 1 ) - #define xSemaphoreCreateMutexStatic( pxMutexBuffer ) xQueueCreateMutexStatic( queueQUEUE_TYPE_MUTEX, ( pxMutexBuffer ) ) -#endif /* configSUPPORT_STATIC_ALLOCATION */ - - -/** - * semphr. h - *
SemaphoreHandle_t xSemaphoreCreateRecursiveMutex( void )
- * - * Creates a new recursive mutex type semaphore instance, and returns a handle - * by which the new recursive mutex can be referenced. - * - * Internally, within the FreeRTOS implementation, recursive mutexs use a block - * of memory, in which the mutex structure is stored. If a recursive mutex is - * created using xSemaphoreCreateRecursiveMutex() then the required memory is - * automatically dynamically allocated inside the - * xSemaphoreCreateRecursiveMutex() function. (see - * http://www.freertos.org/a00111.html). If a recursive mutex is created using - * xSemaphoreCreateRecursiveMutexStatic() then the application writer must - * provide the memory that will get used by the mutex. - * xSemaphoreCreateRecursiveMutexStatic() therefore allows a recursive mutex to - * be created without using any dynamic memory allocation. - * - * Mutexes created using this macro can be accessed using the - * xSemaphoreTakeRecursive() and xSemaphoreGiveRecursive() macros. The - * xSemaphoreTake() and xSemaphoreGive() macros must not be used. - * - * A mutex used recursively can be 'taken' repeatedly by the owner. The mutex - * doesn't become available again until the owner has called - * xSemaphoreGiveRecursive() for each successful 'take' request. For example, - * if a task successfully 'takes' the same mutex 5 times then the mutex will - * not be available to any other task until it has also 'given' the mutex back - * exactly five times. - * - * This type of semaphore uses a priority inheritance mechanism so a task - * 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the - * semaphore it is no longer required. - * - * Mutex type semaphores cannot be used from within interrupt service routines. - * - * See xSemaphoreCreateBinary() for an alternative implementation that can be - * used for pure synchronisation (where one task or interrupt always 'gives' the - * semaphore and another always 'takes' the semaphore) and from within interrupt - * service routines. - * - * @return xSemaphore Handle to the created mutex semaphore. Should be of type - * SemaphoreHandle_t. - * - * Example usage: -
- SemaphoreHandle_t xSemaphore;
-
- void vATask( void * pvParameters )
- {
-    // Semaphore cannot be used before a call to xSemaphoreCreateMutex().
-    // This is a macro so pass the variable in directly.
-    xSemaphore = xSemaphoreCreateRecursiveMutex();
-
-    if( xSemaphore != NULL )
-    {
-        // The semaphore was created successfully.
-        // The semaphore can now be used.
-    }
- }
- 
- * \defgroup xSemaphoreCreateRecursiveMutex xSemaphoreCreateRecursiveMutex - * \ingroup Semaphores - */ -#if( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configUSE_RECURSIVE_MUTEXES == 1 ) ) - #define xSemaphoreCreateRecursiveMutex() xQueueCreateMutex( queueQUEUE_TYPE_RECURSIVE_MUTEX ) -#endif - -/** - * semphr. h - *
SemaphoreHandle_t xSemaphoreCreateRecursiveMutexStatic( StaticSemaphore_t *pxMutexBuffer )
- * - * Creates a new recursive mutex type semaphore instance, and returns a handle - * by which the new recursive mutex can be referenced. - * - * Internally, within the FreeRTOS implementation, recursive mutexs use a block - * of memory, in which the mutex structure is stored. If a recursive mutex is - * created using xSemaphoreCreateRecursiveMutex() then the required memory is - * automatically dynamically allocated inside the - * xSemaphoreCreateRecursiveMutex() function. (see - * http://www.freertos.org/a00111.html). If a recursive mutex is created using - * xSemaphoreCreateRecursiveMutexStatic() then the application writer must - * provide the memory that will get used by the mutex. - * xSemaphoreCreateRecursiveMutexStatic() therefore allows a recursive mutex to - * be created without using any dynamic memory allocation. - * - * Mutexes created using this macro can be accessed using the - * xSemaphoreTakeRecursive() and xSemaphoreGiveRecursive() macros. The - * xSemaphoreTake() and xSemaphoreGive() macros must not be used. - * - * A mutex used recursively can be 'taken' repeatedly by the owner. The mutex - * doesn't become available again until the owner has called - * xSemaphoreGiveRecursive() for each successful 'take' request. For example, - * if a task successfully 'takes' the same mutex 5 times then the mutex will - * not be available to any other task until it has also 'given' the mutex back - * exactly five times. - * - * This type of semaphore uses a priority inheritance mechanism so a task - * 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the - * semaphore it is no longer required. - * - * Mutex type semaphores cannot be used from within interrupt service routines. - * - * See xSemaphoreCreateBinary() for an alternative implementation that can be - * used for pure synchronisation (where one task or interrupt always 'gives' the - * semaphore and another always 'takes' the semaphore) and from within interrupt - * service routines. - * - * @param pxMutexBuffer Must point to a variable of type StaticSemaphore_t, - * which will then be used to hold the recursive mutex's data structure, - * removing the need for the memory to be allocated dynamically. - * - * @return If the recursive mutex was successfully created then a handle to the - * created recursive mutex is returned. If pxMutexBuffer was NULL then NULL is - * returned. - * - * Example usage: -
- SemaphoreHandle_t xSemaphore;
- StaticSemaphore_t xMutexBuffer;
-
- void vATask( void * pvParameters )
- {
-    // A recursive semaphore cannot be used before it is created.  Here a
-    // recursive mutex is created using xSemaphoreCreateRecursiveMutexStatic().
-    // The address of xMutexBuffer is passed into the function, and will hold
-    // the mutexes data structures - so no dynamic memory allocation will be
-    // attempted.
-    xSemaphore = xSemaphoreCreateRecursiveMutexStatic( &xMutexBuffer );
-
-    // As no dynamic memory allocation was performed, xSemaphore cannot be NULL,
-    // so there is no need to check it.
- }
- 
- * \defgroup xSemaphoreCreateRecursiveMutexStatic xSemaphoreCreateRecursiveMutexStatic - * \ingroup Semaphores - */ -#if( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configUSE_RECURSIVE_MUTEXES == 1 ) ) - #define xSemaphoreCreateRecursiveMutexStatic( pxStaticSemaphore ) xQueueCreateMutexStatic( queueQUEUE_TYPE_RECURSIVE_MUTEX, pxStaticSemaphore ) -#endif /* configSUPPORT_STATIC_ALLOCATION */ - -/** - * semphr. h - *
SemaphoreHandle_t xSemaphoreCreateCounting( UBaseType_t uxMaxCount, UBaseType_t uxInitialCount )
- * - * Creates a new counting semaphore instance, and returns a handle by which the - * new counting semaphore can be referenced. - * - * In many usage scenarios it is faster and more memory efficient to use a - * direct to task notification in place of a counting semaphore! - * http://www.freertos.org/RTOS-task-notifications.html - * - * Internally, within the FreeRTOS implementation, counting semaphores use a - * block of memory, in which the counting semaphore structure is stored. If a - * counting semaphore is created using xSemaphoreCreateCounting() then the - * required memory is automatically dynamically allocated inside the - * xSemaphoreCreateCounting() function. (see - * http://www.freertos.org/a00111.html). If a counting semaphore is created - * using xSemaphoreCreateCountingStatic() then the application writer can - * instead optionally provide the memory that will get used by the counting - * semaphore. xSemaphoreCreateCountingStatic() therefore allows a counting - * semaphore to be created without using any dynamic memory allocation. - * - * Counting semaphores are typically used for two things: - * - * 1) Counting events. - * - * In this usage scenario an event handler will 'give' a semaphore each time - * an event occurs (incrementing the semaphore count value), and a handler - * task will 'take' a semaphore each time it processes an event - * (decrementing the semaphore count value). The count value is therefore - * the difference between the number of events that have occurred and the - * number that have been processed. In this case it is desirable for the - * initial count value to be zero. - * - * 2) Resource management. - * - * In this usage scenario the count value indicates the number of resources - * available. To obtain control of a resource a task must first obtain a - * semaphore - decrementing the semaphore count value. When the count value - * reaches zero there are no free resources. When a task finishes with the - * resource it 'gives' the semaphore back - incrementing the semaphore count - * value. In this case it is desirable for the initial count value to be - * equal to the maximum count value, indicating that all resources are free. - * - * @param uxMaxCount The maximum count value that can be reached. When the - * semaphore reaches this value it can no longer be 'given'. - * - * @param uxInitialCount The count value assigned to the semaphore when it is - * created. - * - * @return Handle to the created semaphore. Null if the semaphore could not be - * created. - * - * Example usage: -
- SemaphoreHandle_t xSemaphore;
-
- void vATask( void * pvParameters )
- {
- SemaphoreHandle_t xSemaphore = NULL;
-
-    // Semaphore cannot be used before a call to xSemaphoreCreateCounting().
-    // The max value to which the semaphore can count should be 10, and the
-    // initial value assigned to the count should be 0.
-    xSemaphore = xSemaphoreCreateCounting( 10, 0 );
-
-    if( xSemaphore != NULL )
-    {
-        // The semaphore was created successfully.
-        // The semaphore can now be used.
-    }
- }
- 
- * \defgroup xSemaphoreCreateCounting xSemaphoreCreateCounting - * \ingroup Semaphores - */ -#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - #define xSemaphoreCreateCounting( uxMaxCount, uxInitialCount ) xQueueCreateCountingSemaphore( ( uxMaxCount ), ( uxInitialCount ) ) -#endif - -/** - * semphr. h - *
SemaphoreHandle_t xSemaphoreCreateCountingStatic( UBaseType_t uxMaxCount, UBaseType_t uxInitialCount, StaticSemaphore_t *pxSemaphoreBuffer )
- * - * Creates a new counting semaphore instance, and returns a handle by which the - * new counting semaphore can be referenced. - * - * In many usage scenarios it is faster and more memory efficient to use a - * direct to task notification in place of a counting semaphore! - * http://www.freertos.org/RTOS-task-notifications.html - * - * Internally, within the FreeRTOS implementation, counting semaphores use a - * block of memory, in which the counting semaphore structure is stored. If a - * counting semaphore is created using xSemaphoreCreateCounting() then the - * required memory is automatically dynamically allocated inside the - * xSemaphoreCreateCounting() function. (see - * http://www.freertos.org/a00111.html). If a counting semaphore is created - * using xSemaphoreCreateCountingStatic() then the application writer must - * provide the memory. xSemaphoreCreateCountingStatic() therefore allows a - * counting semaphore to be created without using any dynamic memory allocation. - * - * Counting semaphores are typically used for two things: - * - * 1) Counting events. - * - * In this usage scenario an event handler will 'give' a semaphore each time - * an event occurs (incrementing the semaphore count value), and a handler - * task will 'take' a semaphore each time it processes an event - * (decrementing the semaphore count value). The count value is therefore - * the difference between the number of events that have occurred and the - * number that have been processed. In this case it is desirable for the - * initial count value to be zero. - * - * 2) Resource management. - * - * In this usage scenario the count value indicates the number of resources - * available. To obtain control of a resource a task must first obtain a - * semaphore - decrementing the semaphore count value. When the count value - * reaches zero there are no free resources. When a task finishes with the - * resource it 'gives' the semaphore back - incrementing the semaphore count - * value. In this case it is desirable for the initial count value to be - * equal to the maximum count value, indicating that all resources are free. - * - * @param uxMaxCount The maximum count value that can be reached. When the - * semaphore reaches this value it can no longer be 'given'. - * - * @param uxInitialCount The count value assigned to the semaphore when it is - * created. - * - * @param pxSemaphoreBuffer Must point to a variable of type StaticSemaphore_t, - * which will then be used to hold the semaphore's data structure, removing the - * need for the memory to be allocated dynamically. - * - * @return If the counting semaphore was successfully created then a handle to - * the created counting semaphore is returned. If pxSemaphoreBuffer was NULL - * then NULL is returned. - * - * Example usage: -
- SemaphoreHandle_t xSemaphore;
- StaticSemaphore_t xSemaphoreBuffer;
-
- void vATask( void * pvParameters )
- {
- SemaphoreHandle_t xSemaphore = NULL;
-
-    // Counting semaphore cannot be used before they have been created.  Create
-    // a counting semaphore using xSemaphoreCreateCountingStatic().  The max
-    // value to which the semaphore can count is 10, and the initial value
-    // assigned to the count will be 0.  The address of xSemaphoreBuffer is
-    // passed in and will be used to hold the semaphore structure, so no dynamic
-    // memory allocation will be used.
-    xSemaphore = xSemaphoreCreateCounting( 10, 0, &xSemaphoreBuffer );
-
-    // No memory allocation was attempted so xSemaphore cannot be NULL, so there
-    // is no need to check its value.
- }
- 
- * \defgroup xSemaphoreCreateCountingStatic xSemaphoreCreateCountingStatic - * \ingroup Semaphores - */ -#if( configSUPPORT_STATIC_ALLOCATION == 1 ) - #define xSemaphoreCreateCountingStatic( uxMaxCount, uxInitialCount, pxSemaphoreBuffer ) xQueueCreateCountingSemaphoreStatic( ( uxMaxCount ), ( uxInitialCount ), ( pxSemaphoreBuffer ) ) -#endif /* configSUPPORT_STATIC_ALLOCATION */ - -/** - * semphr. h - *
void vSemaphoreDelete( SemaphoreHandle_t xSemaphore );
- * - * Delete a semaphore. This function must be used with care. For example, - * do not delete a mutex type semaphore if the mutex is held by a task. - * - * @param xSemaphore A handle to the semaphore to be deleted. - * - * \defgroup vSemaphoreDelete vSemaphoreDelete - * \ingroup Semaphores - */ -#define vSemaphoreDelete( xSemaphore ) vQueueDelete( ( QueueHandle_t ) ( xSemaphore ) ) - -/** - * semphr.h - *
TaskHandle_t xSemaphoreGetMutexHolder( SemaphoreHandle_t xMutex );
- * - * If xMutex is indeed a mutex type semaphore, return the current mutex holder. - * If xMutex is not a mutex type semaphore, or the mutex is available (not held - * by a task), return NULL. - * - * Note: This is a good way of determining if the calling task is the mutex - * holder, but not a good way of determining the identity of the mutex holder as - * the holder may change between the function exiting and the returned value - * being tested. - */ -#define xSemaphoreGetMutexHolder( xSemaphore ) xQueueGetMutexHolder( ( xSemaphore ) ) - -/** - * semphr.h - *
TaskHandle_t xSemaphoreGetMutexHolderFromISR( SemaphoreHandle_t xMutex );
- * - * If xMutex is indeed a mutex type semaphore, return the current mutex holder. - * If xMutex is not a mutex type semaphore, or the mutex is available (not held - * by a task), return NULL. - * - */ -#define xSemaphoreGetMutexHolderFromISR( xSemaphore ) xQueueGetMutexHolderFromISR( ( xSemaphore ) ) - -/** - * semphr.h - *
UBaseType_t uxSemaphoreGetCount( SemaphoreHandle_t xSemaphore );
- * - * If the semaphore is a counting semaphore then uxSemaphoreGetCount() returns - * its current count value. If the semaphore is a binary semaphore then - * uxSemaphoreGetCount() returns 1 if the semaphore is available, and 0 if the - * semaphore is not available. - * - */ -#define uxSemaphoreGetCount( xSemaphore ) uxQueueMessagesWaiting( ( QueueHandle_t ) ( xSemaphore ) ) - -#endif /* SEMAPHORE_H */ - - diff --git a/lib/FreeRTOS/Source/include/stack_macros.h b/lib/FreeRTOS/Source/include/stack_macros.h deleted file mode 100644 index 79a83ea3..00000000 --- a/lib/FreeRTOS/Source/include/stack_macros.h +++ /dev/null @@ -1,129 +0,0 @@ -/* - * FreeRTOS Kernel V10.0.1 - * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * 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. - * - * http://www.FreeRTOS.org - * http://aws.amazon.com/freertos - * - * 1 tab == 4 spaces! - */ - -#ifndef STACK_MACROS_H -#define STACK_MACROS_H - -/* - * Call the stack overflow hook function if the stack of the task being swapped - * out is currently overflowed, or looks like it might have overflowed in the - * past. - * - * Setting configCHECK_FOR_STACK_OVERFLOW to 1 will cause the macro to check - * the current stack state only - comparing the current top of stack value to - * the stack limit. Setting configCHECK_FOR_STACK_OVERFLOW to greater than 1 - * will also cause the last few stack bytes to be checked to ensure the value - * to which the bytes were set when the task was created have not been - * overwritten. Note this second test does not guarantee that an overflowed - * stack will always be recognised. - */ - -/*-----------------------------------------------------------*/ - -#if( ( configCHECK_FOR_STACK_OVERFLOW == 1 ) && ( portSTACK_GROWTH < 0 ) ) - - /* Only the current stack state is to be checked. */ - #define taskCHECK_FOR_STACK_OVERFLOW() \ - { \ - /* Is the currently saved stack pointer within the stack limit? */ \ - if( pxCurrentTCB->pxTopOfStack <= pxCurrentTCB->pxStack ) \ - { \ - vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \ - } \ - } - -#endif /* configCHECK_FOR_STACK_OVERFLOW == 1 */ -/*-----------------------------------------------------------*/ - -#if( ( configCHECK_FOR_STACK_OVERFLOW == 1 ) && ( portSTACK_GROWTH > 0 ) ) - - /* Only the current stack state is to be checked. */ - #define taskCHECK_FOR_STACK_OVERFLOW() \ - { \ - \ - /* Is the currently saved stack pointer within the stack limit? */ \ - if( pxCurrentTCB->pxTopOfStack >= pxCurrentTCB->pxEndOfStack ) \ - { \ - vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \ - } \ - } - -#endif /* configCHECK_FOR_STACK_OVERFLOW == 1 */ -/*-----------------------------------------------------------*/ - -#if( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) && ( portSTACK_GROWTH < 0 ) ) - - #define taskCHECK_FOR_STACK_OVERFLOW() \ - { \ - const uint32_t * const pulStack = ( uint32_t * ) pxCurrentTCB->pxStack; \ - const uint32_t ulCheckValue = ( uint32_t ) 0xa5a5a5a5; \ - \ - if( ( pulStack[ 0 ] != ulCheckValue ) || \ - ( pulStack[ 1 ] != ulCheckValue ) || \ - ( pulStack[ 2 ] != ulCheckValue ) || \ - ( pulStack[ 3 ] != ulCheckValue ) ) \ - { \ - vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \ - } \ - } - -#endif /* #if( configCHECK_FOR_STACK_OVERFLOW > 1 ) */ -/*-----------------------------------------------------------*/ - -#if( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) && ( portSTACK_GROWTH > 0 ) ) - - #define taskCHECK_FOR_STACK_OVERFLOW() \ - { \ - int8_t *pcEndOfStack = ( int8_t * ) pxCurrentTCB->pxEndOfStack; \ - static const uint8_t ucExpectedStackBytes[] = { tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ - tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ - tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ - tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ - tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE }; \ - \ - \ - pcEndOfStack -= sizeof( ucExpectedStackBytes ); \ - \ - /* Has the extremity of the task stack ever been written over? */ \ - if( memcmp( ( void * ) pcEndOfStack, ( void * ) ucExpectedStackBytes, sizeof( ucExpectedStackBytes ) ) != 0 ) \ - { \ - vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \ - } \ - } - -#endif /* #if( configCHECK_FOR_STACK_OVERFLOW > 1 ) */ -/*-----------------------------------------------------------*/ - -/* Remove stack overflow macro if not being used. */ -#ifndef taskCHECK_FOR_STACK_OVERFLOW - #define taskCHECK_FOR_STACK_OVERFLOW() -#endif - - - -#endif /* STACK_MACROS_H */ - diff --git a/lib/FreeRTOS/Source/include/stdint.readme b/lib/FreeRTOS/Source/include/stdint.readme deleted file mode 100644 index 4414c29e..00000000 --- a/lib/FreeRTOS/Source/include/stdint.readme +++ /dev/null @@ -1,27 +0,0 @@ - -#ifndef FREERTOS_STDINT -#define FREERTOS_STDINT - -/******************************************************************************* - * THIS IS NOT A FULL stdint.h IMPLEMENTATION - It only contains the definitions - * necessary to build the FreeRTOS code. It is provided to allow FreeRTOS to be - * built using compilers that do not provide their own stdint.h definition. - * - * To use this file: - * - * 1) Copy this file into the directory that contains your FreeRTOSConfig.h - * header file, as that directory will already be in the compilers include - * path. - * - * 2) Rename the copied file stdint.h. - * - */ - -typedef signed char int8_t; -typedef unsigned char uint8_t; -typedef short int16_t; -typedef unsigned short uint16_t; -typedef long int32_t; -typedef unsigned long uint32_t; - -#endif /* FREERTOS_STDINT */ diff --git a/lib/FreeRTOS/Source/include/stream_buffer.h b/lib/FreeRTOS/Source/include/stream_buffer.h deleted file mode 100644 index 5418e05b..00000000 --- a/lib/FreeRTOS/Source/include/stream_buffer.h +++ /dev/null @@ -1,852 +0,0 @@ -/* - * FreeRTOS Kernel V10.0.1 - * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * 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. - * - * http://www.FreeRTOS.org - * http://aws.amazon.com/freertos - * - * 1 tab == 4 spaces! - */ - -/* - * Stream buffers are used to send a continuous stream of data from one task or - * interrupt to another. Their implementation is light weight, making them - * particularly suited for interrupt to task and core to core communication - * scenarios. - * - * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer - * implementation (so also the message buffer implementation, as message buffers - * are built on top of stream buffers) assumes there is only one task or - * interrupt that will write to the buffer (the writer), and only one task or - * interrupt that will read from the buffer (the reader). It is safe for the - * writer and reader to be different tasks or interrupts, but, unlike other - * FreeRTOS objects, it is not safe to have multiple different writers or - * multiple different readers. If there are to be multiple different writers - * then the application writer must place each call to a writing API function - * (such as xStreamBufferSend()) inside a critical section and set the send - * block time to 0. Likewise, if there are to be multiple different readers - * then the application writer must place each call to a reading API function - * (such as xStreamBufferRead()) inside a critical section section and set the - * receive block time to 0. - * - */ - -#ifndef STREAM_BUFFER_H -#define STREAM_BUFFER_H - -#if defined( __cplusplus ) -extern "C" { -#endif - -/** - * Type by which stream buffers are referenced. For example, a call to - * xStreamBufferCreate() returns an StreamBufferHandle_t variable that can - * then be used as a parameter to xStreamBufferSend(), xStreamBufferReceive(), - * etc. - */ -typedef void * StreamBufferHandle_t; - - -/** - * message_buffer.h - * -
-StreamBufferHandle_t xStreamBufferCreate( size_t xBufferSizeBytes, size_t xTriggerLevelBytes );
-
- * - * Creates a new stream buffer using dynamically allocated memory. See - * xStreamBufferCreateStatic() for a version that uses statically allocated - * memory (memory that is allocated at compile time). - * - * configSUPPORT_DYNAMIC_ALLOCATION must be set to 1 or left undefined in - * FreeRTOSConfig.h for xStreamBufferCreate() to be available. - * - * @param xBufferSizeBytes The total number of bytes the stream buffer will be - * able to hold at any one time. - * - * @param xTriggerLevelBytes The number of bytes that must be in the stream - * buffer before a task that is blocked on the stream buffer to wait for data is - * moved out of the blocked state. For example, if a task is blocked on a read - * of an empty stream buffer that has a trigger level of 1 then the task will be - * unblocked when a single byte is written to the buffer or the task's block - * time expires. As another example, if a task is blocked on a read of an empty - * stream buffer that has a trigger level of 10 then the task will not be - * unblocked until the stream buffer contains at least 10 bytes or the task's - * block time expires. If a reading task's block time expires before the - * trigger level is reached then the task will still receive however many bytes - * are actually available. Setting a trigger level of 0 will result in a - * trigger level of 1 being used. It is not valid to specify a trigger level - * that is greater than the buffer size. - * - * @return If NULL is returned, then the stream buffer cannot be created - * because there is insufficient heap memory available for FreeRTOS to allocate - * the stream buffer data structures and storage area. A non-NULL value being - * returned indicates that the stream buffer has been created successfully - - * the returned value should be stored as the handle to the created stream - * buffer. - * - * Example use: -
-
-void vAFunction( void )
-{
-StreamBufferHandle_t xStreamBuffer;
-const size_t xStreamBufferSizeBytes = 100, xTriggerLevel = 10;
-
-    // Create a stream buffer that can hold 100 bytes.  The memory used to hold
-    // both the stream buffer structure and the data in the stream buffer is
-    // allocated dynamically.
-    xStreamBuffer = xStreamBufferCreate( xStreamBufferSizeBytes, xTriggerLevel );
-
-    if( xStreamBuffer == NULL )
-    {
-        // There was not enough heap memory space available to create the
-        // stream buffer.
-    }
-    else
-    {
-        // The stream buffer was created successfully and can now be used.
-    }
-}
-
- * \defgroup xStreamBufferCreate xStreamBufferCreate - * \ingroup StreamBufferManagement - */ -#define xStreamBufferCreate( xBufferSizeBytes, xTriggerLevelBytes ) xStreamBufferGenericCreate( xBufferSizeBytes, xTriggerLevelBytes, pdFALSE ) - -/** - * stream_buffer.h - * -
-StreamBufferHandle_t xStreamBufferCreateStatic( size_t xBufferSizeBytes,
-                                                size_t xTriggerLevelBytes,
-                                                uint8_t *pucStreamBufferStorageArea,
-                                                StaticStreamBuffer_t *pxStaticStreamBuffer );
-
- * Creates a new stream buffer using statically allocated memory. See - * xStreamBufferCreate() for a version that uses dynamically allocated memory. - * - * configSUPPORT_STATIC_ALLOCATION must be set to 1 in FreeRTOSConfig.h for - * xStreamBufferCreateStatic() to be available. - * - * @param xBufferSizeBytes The size, in bytes, of the buffer pointed to by the - * pucStreamBufferStorageArea parameter. - * - * @param xTriggerLevelBytes The number of bytes that must be in the stream - * buffer before a task that is blocked on the stream buffer to wait for data is - * moved out of the blocked state. For example, if a task is blocked on a read - * of an empty stream buffer that has a trigger level of 1 then the task will be - * unblocked when a single byte is written to the buffer or the task's block - * time expires. As another example, if a task is blocked on a read of an empty - * stream buffer that has a trigger level of 10 then the task will not be - * unblocked until the stream buffer contains at least 10 bytes or the task's - * block time expires. If a reading task's block time expires before the - * trigger level is reached then the task will still receive however many bytes - * are actually available. Setting a trigger level of 0 will result in a - * trigger level of 1 being used. It is not valid to specify a trigger level - * that is greater than the buffer size. - * - * @param pucStreamBufferStorageArea Must point to a uint8_t array that is at - * least xBufferSizeBytes + 1 big. This is the array to which streams are - * copied when they are written to the stream buffer. - * - * @param pxStaticStreamBuffer Must point to a variable of type - * StaticStreamBuffer_t, which will be used to hold the stream buffer's data - * structure. - * - * @return If the stream buffer is created successfully then a handle to the - * created stream buffer is returned. If either pucStreamBufferStorageArea or - * pxStaticstreamBuffer are NULL then NULL is returned. - * - * Example use: -
-
-// Used to dimension the array used to hold the streams.  The available space
-// will actually be one less than this, so 999.
-#define STORAGE_SIZE_BYTES 1000
-
-// Defines the memory that will actually hold the streams within the stream
-// buffer.
-static uint8_t ucStorageBuffer[ STORAGE_SIZE_BYTES ];
-
-// The variable used to hold the stream buffer structure.
-StaticStreamBuffer_t xStreamBufferStruct;
-
-void MyFunction( void )
-{
-StreamBufferHandle_t xStreamBuffer;
-const size_t xTriggerLevel = 1;
-
-    xStreamBuffer = xStreamBufferCreateStatic( sizeof( ucBufferStorage ),
-                                               xTriggerLevel,
-                                               ucBufferStorage,
-                                               &xStreamBufferStruct );
-
-    // As neither the pucStreamBufferStorageArea or pxStaticStreamBuffer
-    // parameters were NULL, xStreamBuffer will not be NULL, and can be used to
-    // reference the created stream buffer in other stream buffer API calls.
-
-    // Other code that uses the stream buffer can go here.
-}
-
-
- * \defgroup xStreamBufferCreateStatic xStreamBufferCreateStatic - * \ingroup StreamBufferManagement - */ -#define xStreamBufferCreateStatic( xBufferSizeBytes, xTriggerLevelBytes, pucStreamBufferStorageArea, pxStaticStreamBuffer ) xStreamBufferGenericCreateStatic( xBufferSizeBytes, xTriggerLevelBytes, pdFALSE, pucStreamBufferStorageArea, pxStaticStreamBuffer ) - -/** - * stream_buffer.h - * -
-size_t xStreamBufferSend( StreamBufferHandle_t xStreamBuffer,
-                          const void *pvTxData,
-                          size_t xDataLengthBytes,
-                          TickType_t xTicksToWait );
-
- *
- * Sends bytes to a stream buffer.  The bytes are copied into the stream buffer.
- *
- * ***NOTE***:  Uniquely among FreeRTOS objects, the stream buffer
- * implementation (so also the message buffer implementation, as message buffers
- * are built on top of stream buffers) assumes there is only one task or
- * interrupt that will write to the buffer (the writer), and only one task or
- * interrupt that will read from the buffer (the reader).  It is safe for the
- * writer and reader to be different tasks or interrupts, but, unlike other
- * FreeRTOS objects, it is not safe to have multiple different writers or
- * multiple different readers.  If there are to be multiple different writers
- * then the application writer must place each call to a writing API function
- * (such as xStreamBufferSend()) inside a critical section and set the send
- * block time to 0.  Likewise, if there are to be multiple different readers
- * then the application writer must place each call to a reading API function
- * (such as xStreamBufferRead()) inside a critical section and set the receive
- * block time to 0.
- *
- * Use xStreamBufferSend() to write to a stream buffer from a task.  Use
- * xStreamBufferSendFromISR() to write to a stream buffer from an interrupt
- * service routine (ISR).
- *
- * @param xStreamBuffer The handle of the stream buffer to which a stream is
- * being sent.
- *
- * @param pvTxData A pointer to the buffer that holds the bytes to be copied
- * into the stream buffer.
- *
- * @param xDataLengthBytes   The maximum number of bytes to copy from pvTxData
- * into the stream buffer.
- *
- * @param xTicksToWait The maximum amount of time the task should remain in the
- * Blocked state to wait for enough space to become available in the stream
- * buffer, should the stream buffer contain too little space to hold the
- * another xDataLengthBytes bytes.  The block time is specified in tick periods,
- * so the absolute time it represents is dependent on the tick frequency.  The
- * macro pdMS_TO_TICKS() can be used to convert a time specified in milliseconds
- * into a time specified in ticks.  Setting xTicksToWait to portMAX_DELAY will
- * cause the task to wait indefinitely (without timing out), provided
- * INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h.  If a task times out
- * before it can write all xDataLengthBytes into the buffer it will still write
- * as many bytes as possible.  A task does not use any CPU time when it is in
- * the blocked state.
- *
- * @return The number of bytes written to the stream buffer.  If a task times
- * out before it can write all xDataLengthBytes into the buffer it will still
- * write as many bytes as possible.
- *
- * Example use:
-
-void vAFunction( StreamBufferHandle_t xStreamBuffer )
-{
-size_t xBytesSent;
-uint8_t ucArrayToSend[] = { 0, 1, 2, 3 };
-char *pcStringToSend = "String to send";
-const TickType_t x100ms = pdMS_TO_TICKS( 100 );
-
-    // Send an array to the stream buffer, blocking for a maximum of 100ms to
-    // wait for enough space to be available in the stream buffer.
-    xBytesSent = xStreamBufferSend( xStreamBuffer, ( void * ) ucArrayToSend, sizeof( ucArrayToSend ), x100ms );
-
-    if( xBytesSent != sizeof( ucArrayToSend ) )
-    {
-        // The call to xStreamBufferSend() times out before there was enough
-        // space in the buffer for the data to be written, but it did
-        // successfully write xBytesSent bytes.
-    }
-
-    // Send the string to the stream buffer.  Return immediately if there is not
-    // enough space in the buffer.
-    xBytesSent = xStreamBufferSend( xStreamBuffer, ( void * ) pcStringToSend, strlen( pcStringToSend ), 0 );
-
-    if( xBytesSent != strlen( pcStringToSend ) )
-    {
-        // The entire string could not be added to the stream buffer because
-        // there was not enough free space in the buffer, but xBytesSent bytes
-        // were sent.  Could try again to send the remaining bytes.
-    }
-}
-
- * \defgroup xStreamBufferSend xStreamBufferSend - * \ingroup StreamBufferManagement - */ -size_t xStreamBufferSend( StreamBufferHandle_t xStreamBuffer, - const void *pvTxData, - size_t xDataLengthBytes, - TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; - -/** - * stream_buffer.h - * -
-size_t xStreamBufferSendFromISR( StreamBufferHandle_t xStreamBuffer,
-                                 const void *pvTxData,
-                                 size_t xDataLengthBytes,
-                                 BaseType_t *pxHigherPriorityTaskWoken );
-
- *
- * Interrupt safe version of the API function that sends a stream of bytes to
- * the stream buffer.
- *
- * ***NOTE***:  Uniquely among FreeRTOS objects, the stream buffer
- * implementation (so also the message buffer implementation, as message buffers
- * are built on top of stream buffers) assumes there is only one task or
- * interrupt that will write to the buffer (the writer), and only one task or
- * interrupt that will read from the buffer (the reader).  It is safe for the
- * writer and reader to be different tasks or interrupts, but, unlike other
- * FreeRTOS objects, it is not safe to have multiple different writers or
- * multiple different readers.  If there are to be multiple different writers
- * then the application writer must place each call to a writing API function
- * (such as xStreamBufferSend()) inside a critical section and set the send
- * block time to 0.  Likewise, if there are to be multiple different readers
- * then the application writer must place each call to a reading API function
- * (such as xStreamBufferRead()) inside a critical section and set the receive
- * block time to 0.
- *
- * Use xStreamBufferSend() to write to a stream buffer from a task.  Use
- * xStreamBufferSendFromISR() to write to a stream buffer from an interrupt
- * service routine (ISR).
- *
- * @param xStreamBuffer The handle of the stream buffer to which a stream is
- * being sent.
- *
- * @param pvTxData A pointer to the data that is to be copied into the stream
- * buffer.
- *
- * @param xDataLengthBytes The maximum number of bytes to copy from pvTxData
- * into the stream buffer.
- *
- * @param pxHigherPriorityTaskWoken  It is possible that a stream buffer will
- * have a task blocked on it waiting for data.  Calling
- * xStreamBufferSendFromISR() can make data available, and so cause a task that
- * was waiting for data to leave the Blocked state.  If calling
- * xStreamBufferSendFromISR() causes a task to leave the Blocked state, and the
- * unblocked task has a priority higher than the currently executing task (the
- * task that was interrupted), then, internally, xStreamBufferSendFromISR()
- * will set *pxHigherPriorityTaskWoken to pdTRUE.  If
- * xStreamBufferSendFromISR() sets this value to pdTRUE, then normally a
- * context switch should be performed before the interrupt is exited.  This will
- * ensure that the interrupt returns directly to the highest priority Ready
- * state task.  *pxHigherPriorityTaskWoken should be set to pdFALSE before it
- * is passed into the function.  See the example code below for an example.
- *
- * @return The number of bytes actually written to the stream buffer, which will
- * be less than xDataLengthBytes if the stream buffer didn't have enough free
- * space for all the bytes to be written.
- *
- * Example use:
-
-// A stream buffer that has already been created.
-StreamBufferHandle_t xStreamBuffer;
-
-void vAnInterruptServiceRoutine( void )
-{
-size_t xBytesSent;
-char *pcStringToSend = "String to send";
-BaseType_t xHigherPriorityTaskWoken = pdFALSE; // Initialised to pdFALSE.
-
-    // Attempt to send the string to the stream buffer.
-    xBytesSent = xStreamBufferSendFromISR( xStreamBuffer,
-                                           ( void * ) pcStringToSend,
-                                           strlen( pcStringToSend ),
-                                           &xHigherPriorityTaskWoken );
-
-    if( xBytesSent != strlen( pcStringToSend ) )
-    {
-        // There was not enough free space in the stream buffer for the entire
-        // string to be written, ut xBytesSent bytes were written.
-    }
-
-    // If xHigherPriorityTaskWoken was set to pdTRUE inside
-    // xStreamBufferSendFromISR() then a task that has a priority above the
-    // priority of the currently executing task was unblocked and a context
-    // switch should be performed to ensure the ISR returns to the unblocked
-    // task.  In most FreeRTOS ports this is done by simply passing
-    // xHigherPriorityTaskWoken into taskYIELD_FROM_ISR(), which will test the
-    // variables value, and perform the context switch if necessary.  Check the
-    // documentation for the port in use for port specific instructions.
-    taskYIELD_FROM_ISR( xHigherPriorityTaskWoken );
-}
-
- * \defgroup xStreamBufferSendFromISR xStreamBufferSendFromISR - * \ingroup StreamBufferManagement - */ -size_t xStreamBufferSendFromISR( StreamBufferHandle_t xStreamBuffer, - const void *pvTxData, - size_t xDataLengthBytes, - BaseType_t * const pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; - -/** - * stream_buffer.h - * -
-size_t xStreamBufferReceive( StreamBufferHandle_t xStreamBuffer,
-                             void *pvRxData,
-                             size_t xBufferLengthBytes,
-                             TickType_t xTicksToWait );
-
- * - * Receives bytes from a stream buffer. - * - * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer - * implementation (so also the message buffer implementation, as message buffers - * are built on top of stream buffers) assumes there is only one task or - * interrupt that will write to the buffer (the writer), and only one task or - * interrupt that will read from the buffer (the reader). It is safe for the - * writer and reader to be different tasks or interrupts, but, unlike other - * FreeRTOS objects, it is not safe to have multiple different writers or - * multiple different readers. If there are to be multiple different writers - * then the application writer must place each call to a writing API function - * (such as xStreamBufferSend()) inside a critical section and set the send - * block time to 0. Likewise, if there are to be multiple different readers - * then the application writer must place each call to a reading API function - * (such as xStreamBufferRead()) inside a critical section and set the receive - * block time to 0. - * - * Use xStreamBufferReceive() to read from a stream buffer from a task. Use - * xStreamBufferReceiveFromISR() to read from a stream buffer from an - * interrupt service routine (ISR). - * - * @param xStreamBuffer The handle of the stream buffer from which bytes are to - * be received. - * - * @param pvRxData A pointer to the buffer into which the received bytes will be - * copied. - * - * @param xBufferLengthBytes The length of the buffer pointed to by the - * pvRxData parameter. This sets the maximum number of bytes to receive in one - * call. xStreamBufferReceive will return as many bytes as possible up to a - * maximum set by xBufferLengthBytes. - * - * @param xTicksToWait The maximum amount of time the task should remain in the - * Blocked state to wait for data to become available if the stream buffer is - * empty. xStreamBufferReceive() will return immediately if xTicksToWait is - * zero. The block time is specified in tick periods, so the absolute time it - * represents is dependent on the tick frequency. The macro pdMS_TO_TICKS() can - * be used to convert a time specified in milliseconds into a time specified in - * ticks. Setting xTicksToWait to portMAX_DELAY will cause the task to wait - * indefinitely (without timing out), provided INCLUDE_vTaskSuspend is set to 1 - * in FreeRTOSConfig.h. A task does not use any CPU time when it is in the - * Blocked state. - * - * @return The number of bytes actually read from the stream buffer, which will - * be less than xBufferLengthBytes if the call to xStreamBufferReceive() timed - * out before xBufferLengthBytes were available. - * - * Example use: -
-void vAFunction( StreamBuffer_t xStreamBuffer )
-{
-uint8_t ucRxData[ 20 ];
-size_t xReceivedBytes;
-const TickType_t xBlockTime = pdMS_TO_TICKS( 20 );
-
-    // Receive up to another sizeof( ucRxData ) bytes from the stream buffer.
-    // Wait in the Blocked state (so not using any CPU processing time) for a
-    // maximum of 100ms for the full sizeof( ucRxData ) number of bytes to be
-    // available.
-    xReceivedBytes = xStreamBufferReceive( xStreamBuffer,
-                                           ( void * ) ucRxData,
-                                           sizeof( ucRxData ),
-                                           xBlockTime );
-
-    if( xReceivedBytes > 0 )
-    {
-        // A ucRxData contains another xRecievedBytes bytes of data, which can
-        // be processed here....
-    }
-}
-
- * \defgroup xStreamBufferReceive xStreamBufferReceive - * \ingroup StreamBufferManagement - */ -size_t xStreamBufferReceive( StreamBufferHandle_t xStreamBuffer, - void *pvRxData, - size_t xBufferLengthBytes, - TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; - -/** - * stream_buffer.h - * -
-size_t xStreamBufferReceiveFromISR( StreamBufferHandle_t xStreamBuffer,
-                                    void *pvRxData,
-                                    size_t xBufferLengthBytes,
-                                    BaseType_t *pxHigherPriorityTaskWoken );
-
- * - * An interrupt safe version of the API function that receives bytes from a - * stream buffer. - * - * Use xStreamBufferReceive() to read bytes from a stream buffer from a task. - * Use xStreamBufferReceiveFromISR() to read bytes from a stream buffer from an - * interrupt service routine (ISR). - * - * @param xStreamBuffer The handle of the stream buffer from which a stream - * is being received. - * - * @param pvRxData A pointer to the buffer into which the received bytes are - * copied. - * - * @param xBufferLengthBytes The length of the buffer pointed to by the - * pvRxData parameter. This sets the maximum number of bytes to receive in one - * call. xStreamBufferReceive will return as many bytes as possible up to a - * maximum set by xBufferLengthBytes. - * - * @param pxHigherPriorityTaskWoken It is possible that a stream buffer will - * have a task blocked on it waiting for space to become available. Calling - * xStreamBufferReceiveFromISR() can make space available, and so cause a task - * that is waiting for space to leave the Blocked state. If calling - * xStreamBufferReceiveFromISR() causes a task to leave the Blocked state, and - * the unblocked task has a priority higher than the currently executing task - * (the task that was interrupted), then, internally, - * xStreamBufferReceiveFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE. - * If xStreamBufferReceiveFromISR() sets this value to pdTRUE, then normally a - * context switch should be performed before the interrupt is exited. That will - * ensure the interrupt returns directly to the highest priority Ready state - * task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it is - * passed into the function. See the code example below for an example. - * - * @return The number of bytes read from the stream buffer, if any. - * - * Example use: -
-// A stream buffer that has already been created.
-StreamBuffer_t xStreamBuffer;
-
-void vAnInterruptServiceRoutine( void )
-{
-uint8_t ucRxData[ 20 ];
-size_t xReceivedBytes;
-BaseType_t xHigherPriorityTaskWoken = pdFALSE;  // Initialised to pdFALSE.
-
-    // Receive the next stream from the stream buffer.
-    xReceivedBytes = xStreamBufferReceiveFromISR( xStreamBuffer,
-                                                  ( void * ) ucRxData,
-                                                  sizeof( ucRxData ),
-                                                  &xHigherPriorityTaskWoken );
-
-    if( xReceivedBytes > 0 )
-    {
-        // ucRxData contains xReceivedBytes read from the stream buffer.
-        // Process the stream here....
-    }
-
-    // If xHigherPriorityTaskWoken was set to pdTRUE inside
-    // xStreamBufferReceiveFromISR() then a task that has a priority above the
-    // priority of the currently executing task was unblocked and a context
-    // switch should be performed to ensure the ISR returns to the unblocked
-    // task.  In most FreeRTOS ports this is done by simply passing
-    // xHigherPriorityTaskWoken into taskYIELD_FROM_ISR(), which will test the
-    // variables value, and perform the context switch if necessary.  Check the
-    // documentation for the port in use for port specific instructions.
-    taskYIELD_FROM_ISR( xHigherPriorityTaskWoken );
-}
-
- * \defgroup xStreamBufferReceiveFromISR xStreamBufferReceiveFromISR - * \ingroup StreamBufferManagement - */ -size_t xStreamBufferReceiveFromISR( StreamBufferHandle_t xStreamBuffer, - void *pvRxData, - size_t xBufferLengthBytes, - BaseType_t * const pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; - -/** - * stream_buffer.h - * -
-void vStreamBufferDelete( StreamBufferHandle_t xStreamBuffer );
-
- * - * Deletes a stream buffer that was previously created using a call to - * xStreamBufferCreate() or xStreamBufferCreateStatic(). If the stream - * buffer was created using dynamic memory (that is, by xStreamBufferCreate()), - * then the allocated memory is freed. - * - * A stream buffer handle must not be used after the stream buffer has been - * deleted. - * - * @param xStreamBuffer The handle of the stream buffer to be deleted. - * - * \defgroup vStreamBufferDelete vStreamBufferDelete - * \ingroup StreamBufferManagement - */ -void vStreamBufferDelete( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; - -/** - * stream_buffer.h - * -
-BaseType_t xStreamBufferIsFull( StreamBufferHandle_t xStreamBuffer );
-
- * - * Queries a stream buffer to see if it is full. A stream buffer is full if it - * does not have any free space, and therefore cannot accept any more data. - * - * @param xStreamBuffer The handle of the stream buffer being queried. - * - * @return If the stream buffer is full then pdTRUE is returned. Otherwise - * pdFALSE is returned. - * - * \defgroup xStreamBufferIsFull xStreamBufferIsFull - * \ingroup StreamBufferManagement - */ -BaseType_t xStreamBufferIsFull( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; - -/** - * stream_buffer.h - * -
-BaseType_t xStreamBufferIsEmpty( StreamBufferHandle_t xStreamBuffer );
-
- * - * Queries a stream buffer to see if it is empty. A stream buffer is empty if - * it does not contain any data. - * - * @param xStreamBuffer The handle of the stream buffer being queried. - * - * @return If the stream buffer is empty then pdTRUE is returned. Otherwise - * pdFALSE is returned. - * - * \defgroup xStreamBufferIsEmpty xStreamBufferIsEmpty - * \ingroup StreamBufferManagement - */ -BaseType_t xStreamBufferIsEmpty( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; - -/** - * stream_buffer.h - * -
-BaseType_t xStreamBufferReset( StreamBufferHandle_t xStreamBuffer );
-
- * - * Resets a stream buffer to its initial, empty, state. Any data that was in - * the stream buffer is discarded. A stream buffer can only be reset if there - * are no tasks blocked waiting to either send to or receive from the stream - * buffer. - * - * @param xStreamBuffer The handle of the stream buffer being reset. - * - * @return If the stream buffer is reset then pdPASS is returned. If there was - * a task blocked waiting to send to or read from the stream buffer then the - * stream buffer is not reset and pdFAIL is returned. - * - * \defgroup xStreamBufferReset xStreamBufferReset - * \ingroup StreamBufferManagement - */ -BaseType_t xStreamBufferReset( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; - -/** - * stream_buffer.h - * -
-size_t xStreamBufferSpacesAvailable( StreamBufferHandle_t xStreamBuffer );
-
- * - * Queries a stream buffer to see how much free space it contains, which is - * equal to the amount of data that can be sent to the stream buffer before it - * is full. - * - * @param xStreamBuffer The handle of the stream buffer being queried. - * - * @return The number of bytes that can be written to the stream buffer before - * the stream buffer would be full. - * - * \defgroup xStreamBufferSpacesAvailable xStreamBufferSpacesAvailable - * \ingroup StreamBufferManagement - */ -size_t xStreamBufferSpacesAvailable( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; - -/** - * stream_buffer.h - * -
-size_t xStreamBufferBytesAvailable( StreamBufferHandle_t xStreamBuffer );
-
- * - * Queries a stream buffer to see how much data it contains, which is equal to - * the number of bytes that can be read from the stream buffer before the stream - * buffer would be empty. - * - * @param xStreamBuffer The handle of the stream buffer being queried. - * - * @return The number of bytes that can be read from the stream buffer before - * the stream buffer would be empty. - * - * \defgroup xStreamBufferBytesAvailable xStreamBufferBytesAvailable - * \ingroup StreamBufferManagement - */ -size_t xStreamBufferBytesAvailable( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; - -/** - * stream_buffer.h - * -
-BaseType_t xStreamBufferSetTriggerLevel( StreamBufferHandle_t xStreamBuffer, size_t xTriggerLevel );
-
- * - * A stream buffer's trigger level is the number of bytes that must be in the - * stream buffer before a task that is blocked on the stream buffer to - * wait for data is moved out of the blocked state. For example, if a task is - * blocked on a read of an empty stream buffer that has a trigger level of 1 - * then the task will be unblocked when a single byte is written to the buffer - * or the task's block time expires. As another example, if a task is blocked - * on a read of an empty stream buffer that has a trigger level of 10 then the - * task will not be unblocked until the stream buffer contains at least 10 bytes - * or the task's block time expires. If a reading task's block time expires - * before the trigger level is reached then the task will still receive however - * many bytes are actually available. Setting a trigger level of 0 will result - * in a trigger level of 1 being used. It is not valid to specify a trigger - * level that is greater than the buffer size. - * - * A trigger level is set when the stream buffer is created, and can be modified - * using xStreamBufferSetTriggerLevel(). - * - * @param xStreamBuffer The handle of the stream buffer being updated. - * - * @param xTriggerLevel The new trigger level for the stream buffer. - * - * @return If xTriggerLevel was less than or equal to the stream buffer's length - * then the trigger level will be updated and pdTRUE is returned. Otherwise - * pdFALSE is returned. - * - * \defgroup xStreamBufferSetTriggerLevel xStreamBufferSetTriggerLevel - * \ingroup StreamBufferManagement - */ -BaseType_t xStreamBufferSetTriggerLevel( StreamBufferHandle_t xStreamBuffer, size_t xTriggerLevel ) PRIVILEGED_FUNCTION; - -/** - * stream_buffer.h - * -
-BaseType_t xStreamBufferSendCompletedFromISR( StreamBufferHandle_t xStreamBuffer, BaseType_t *pxHigherPriorityTaskWoken );
-
- * - * For advanced users only. - * - * The sbSEND_COMPLETED() macro is called from within the FreeRTOS APIs when - * data is sent to a message buffer or stream buffer. If there was a task that - * was blocked on the message or stream buffer waiting for data to arrive then - * the sbSEND_COMPLETED() macro sends a notification to the task to remove it - * from the Blocked state. xStreamBufferSendCompletedFromISR() does the same - * thing. It is provided to enable application writers to implement their own - * version of sbSEND_COMPLETED(), and MUST NOT BE USED AT ANY OTHER TIME. - * - * See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for - * additional information. - * - * @param xStreamBuffer The handle of the stream buffer to which data was - * written. - * - * @param pxHigherPriorityTaskWoken *pxHigherPriorityTaskWoken should be - * initialised to pdFALSE before it is passed into - * xStreamBufferSendCompletedFromISR(). If calling - * xStreamBufferSendCompletedFromISR() removes a task from the Blocked state, - * and the task has a priority above the priority of the currently running task, - * then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a - * context switch should be performed before exiting the ISR. - * - * @return If a task was removed from the Blocked state then pdTRUE is returned. - * Otherwise pdFALSE is returned. - * - * \defgroup xStreamBufferSendCompletedFromISR xStreamBufferSendCompletedFromISR - * \ingroup StreamBufferManagement - */ -BaseType_t xStreamBufferSendCompletedFromISR( StreamBufferHandle_t xStreamBuffer, BaseType_t *pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; - -/** - * stream_buffer.h - * -
-BaseType_t xStreamBufferReceiveCompletedFromISR( StreamBufferHandle_t xStreamBuffer, BaseType_t *pxHigherPriorityTaskWoken );
-
- * - * For advanced users only. - * - * The sbRECEIVE_COMPLETED() macro is called from within the FreeRTOS APIs when - * data is read out of a message buffer or stream buffer. If there was a task - * that was blocked on the message or stream buffer waiting for data to arrive - * then the sbRECEIVE_COMPLETED() macro sends a notification to the task to - * remove it from the Blocked state. xStreamBufferReceiveCompletedFromISR() - * does the same thing. It is provided to enable application writers to - * implement their own version of sbRECEIVE_COMPLETED(), and MUST NOT BE USED AT - * ANY OTHER TIME. - * - * See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for - * additional information. - * - * @param xStreamBuffer The handle of the stream buffer from which data was - * read. - * - * @param pxHigherPriorityTaskWoken *pxHigherPriorityTaskWoken should be - * initialised to pdFALSE before it is passed into - * xStreamBufferReceiveCompletedFromISR(). If calling - * xStreamBufferReceiveCompletedFromISR() removes a task from the Blocked state, - * and the task has a priority above the priority of the currently running task, - * then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a - * context switch should be performed before exiting the ISR. - * - * @return If a task was removed from the Blocked state then pdTRUE is returned. - * Otherwise pdFALSE is returned. - * - * \defgroup xStreamBufferReceiveCompletedFromISR xStreamBufferReceiveCompletedFromISR - * \ingroup StreamBufferManagement - */ -BaseType_t xStreamBufferReceiveCompletedFromISR( StreamBufferHandle_t xStreamBuffer, BaseType_t *pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; - -/* Functions below here are not part of the public API. */ -StreamBufferHandle_t xStreamBufferGenericCreate( size_t xBufferSizeBytes, - size_t xTriggerLevelBytes, - BaseType_t xIsMessageBuffer ) PRIVILEGED_FUNCTION; - -StreamBufferHandle_t xStreamBufferGenericCreateStatic( size_t xBufferSizeBytes, - size_t xTriggerLevelBytes, - BaseType_t xIsMessageBuffer, - uint8_t * const pucStreamBufferStorageArea, - StaticStreamBuffer_t * const pxStaticStreamBuffer ) PRIVILEGED_FUNCTION; - -#if( configUSE_TRACE_FACILITY == 1 ) - void vStreamBufferSetStreamBufferNumber( StreamBufferHandle_t xStreamBuffer, UBaseType_t uxStreamBufferNumber ) PRIVILEGED_FUNCTION; - UBaseType_t uxStreamBufferGetStreamBufferNumber( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; - uint8_t ucStreamBufferGetStreamBufferType( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; -#endif - -#if defined( __cplusplus ) -} -#endif - -#endif /* !defined( STREAM_BUFFER_H ) */ diff --git a/lib/FreeRTOS/Source/include/task.h b/lib/FreeRTOS/Source/include/task.h deleted file mode 100644 index d0ee0681..00000000 --- a/lib/FreeRTOS/Source/include/task.h +++ /dev/null @@ -1,2338 +0,0 @@ -/* - * FreeRTOS Kernel V10.0.1 - * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * 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. - * - * http://www.FreeRTOS.org - * http://aws.amazon.com/freertos - * - * 1 tab == 4 spaces! - */ - - -#ifndef INC_TASK_H -#define INC_TASK_H - -#ifndef INC_FREERTOS_H - #error "include FreeRTOS.h must appear in source files before include task.h" -#endif - -#include "list.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/*----------------------------------------------------------- - * MACROS AND DEFINITIONS - *----------------------------------------------------------*/ - -#define tskKERNEL_VERSION_NUMBER "V10.0.1" -#define tskKERNEL_VERSION_MAJOR 10 -#define tskKERNEL_VERSION_MINOR 0 -#define tskKERNEL_VERSION_BUILD 1 - -/** - * task. h - * - * Type by which tasks are referenced. For example, a call to xTaskCreate - * returns (via a pointer parameter) an TaskHandle_t variable that can then - * be used as a parameter to vTaskDelete to delete the task. - * - * \defgroup TaskHandle_t TaskHandle_t - * \ingroup Tasks - */ -typedef void * TaskHandle_t; - -/* - * Defines the prototype to which the application task hook function must - * conform. - */ -typedef BaseType_t (*TaskHookFunction_t)( void * ); - -/* Task states returned by eTaskGetState. */ -typedef enum -{ - eRunning = 0, /* A task is querying the state of itself, so must be running. */ - eReady, /* The task being queried is in a read or pending ready list. */ - eBlocked, /* The task being queried is in the Blocked state. */ - eSuspended, /* The task being queried is in the Suspended state, or is in the Blocked state with an infinite time out. */ - eDeleted, /* The task being queried has been deleted, but its TCB has not yet been freed. */ - eInvalid /* Used as an 'invalid state' value. */ -} eTaskState; - -/* Actions that can be performed when vTaskNotify() is called. */ -typedef enum -{ - eNoAction = 0, /* Notify the task without updating its notify value. */ - eSetBits, /* Set bits in the task's notification value. */ - eIncrement, /* Increment the task's notification value. */ - eSetValueWithOverwrite, /* Set the task's notification value to a specific value even if the previous value has not yet been read by the task. */ - eSetValueWithoutOverwrite /* Set the task's notification value if the previous value has been read by the task. */ -} eNotifyAction; - -/* - * Used internally only. - */ -typedef struct xTIME_OUT -{ - BaseType_t xOverflowCount; - TickType_t xTimeOnEntering; -} TimeOut_t; - -/* - * Defines the memory ranges allocated to the task when an MPU is used. - */ -typedef struct xMEMORY_REGION -{ - void *pvBaseAddress; - uint32_t ulLengthInBytes; - uint32_t ulParameters; -} MemoryRegion_t; - -/* - * Parameters required to create an MPU protected task. - */ -typedef struct xTASK_PARAMETERS -{ - TaskFunction_t pvTaskCode; - const char * const pcName; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - uint16_t usStackDepth; - void *pvParameters; - UBaseType_t uxPriority; - StackType_t *puxStackBuffer; - MemoryRegion_t xRegions[ portNUM_CONFIGURABLE_REGIONS ]; - #if ( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) - StaticTask_t * const pxTaskBuffer; - #endif -} TaskParameters_t; - -/* Used with the uxTaskGetSystemState() function to return the state of each task -in the system. */ -typedef struct xTASK_STATUS -{ - TaskHandle_t xHandle; /* The handle of the task to which the rest of the information in the structure relates. */ - const char *pcTaskName; /* A pointer to the task's name. This value will be invalid if the task was deleted since the structure was populated! */ /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - UBaseType_t xTaskNumber; /* A number unique to the task. */ - eTaskState eCurrentState; /* The state in which the task existed when the structure was populated. */ - UBaseType_t uxCurrentPriority; /* The priority at which the task was running (may be inherited) when the structure was populated. */ - UBaseType_t uxBasePriority; /* The priority to which the task will return if the task's current priority has been inherited to avoid unbounded priority inversion when obtaining a mutex. Only valid if configUSE_MUTEXES is defined as 1 in FreeRTOSConfig.h. */ - uint32_t ulRunTimeCounter; /* The total run time allocated to the task so far, as defined by the run time stats clock. See http://www.freertos.org/rtos-run-time-stats.html. Only valid when configGENERATE_RUN_TIME_STATS is defined as 1 in FreeRTOSConfig.h. */ - StackType_t *pxStackBase; /* Points to the lowest address of the task's stack area. */ - uint16_t usStackHighWaterMark; /* The minimum amount of stack space that has remained for the task since the task was created. The closer this value is to zero the closer the task has come to overflowing its stack. */ -} TaskStatus_t; - -/* Possible return values for eTaskConfirmSleepModeStatus(). */ -typedef enum -{ - eAbortSleep = 0, /* A task has been made ready or a context switch pended since portSUPPORESS_TICKS_AND_SLEEP() was called - abort entering a sleep mode. */ - eStandardSleep, /* Enter a sleep mode that will not last any longer than the expected idle time. */ - eNoTasksWaitingTimeout /* No tasks are waiting for a timeout so it is safe to enter a sleep mode that can only be exited by an external interrupt. */ -} eSleepModeStatus; - -/** - * Defines the priority used by the idle task. This must not be modified. - * - * \ingroup TaskUtils - */ -#define tskIDLE_PRIORITY ( ( UBaseType_t ) 0U ) - -/** - * task. h - * - * Macro for forcing a context switch. - * - * \defgroup taskYIELD taskYIELD - * \ingroup SchedulerControl - */ -#define taskYIELD() portYIELD() - -/** - * task. h - * - * Macro to mark the start of a critical code region. Preemptive context - * switches cannot occur when in a critical region. - * - * NOTE: This may alter the stack (depending on the portable implementation) - * so must be used with care! - * - * \defgroup taskENTER_CRITICAL taskENTER_CRITICAL - * \ingroup SchedulerControl - */ -#define taskENTER_CRITICAL() portENTER_CRITICAL() -#define taskENTER_CRITICAL_FROM_ISR() portSET_INTERRUPT_MASK_FROM_ISR() - -/** - * task. h - * - * Macro to mark the end of a critical code region. Preemptive context - * switches cannot occur when in a critical region. - * - * NOTE: This may alter the stack (depending on the portable implementation) - * so must be used with care! - * - * \defgroup taskEXIT_CRITICAL taskEXIT_CRITICAL - * \ingroup SchedulerControl - */ -#define taskEXIT_CRITICAL() portEXIT_CRITICAL() -#define taskEXIT_CRITICAL_FROM_ISR( x ) portCLEAR_INTERRUPT_MASK_FROM_ISR( x ) -/** - * task. h - * - * Macro to disable all maskable interrupts. - * - * \defgroup taskDISABLE_INTERRUPTS taskDISABLE_INTERRUPTS - * \ingroup SchedulerControl - */ -#define taskDISABLE_INTERRUPTS() portDISABLE_INTERRUPTS() - -/** - * task. h - * - * Macro to enable microcontroller interrupts. - * - * \defgroup taskENABLE_INTERRUPTS taskENABLE_INTERRUPTS - * \ingroup SchedulerControl - */ -#define taskENABLE_INTERRUPTS() portENABLE_INTERRUPTS() - -/* Definitions returned by xTaskGetSchedulerState(). taskSCHEDULER_SUSPENDED is -0 to generate more optimal code when configASSERT() is defined as the constant -is used in assert() statements. */ -#define taskSCHEDULER_SUSPENDED ( ( BaseType_t ) 0 ) -#define taskSCHEDULER_NOT_STARTED ( ( BaseType_t ) 1 ) -#define taskSCHEDULER_RUNNING ( ( BaseType_t ) 2 ) - - -/*----------------------------------------------------------- - * TASK CREATION API - *----------------------------------------------------------*/ - -/** - * task. h - *
- BaseType_t xTaskCreate(
-							  TaskFunction_t pvTaskCode,
-							  const char * const pcName,
-							  configSTACK_DEPTH_TYPE usStackDepth,
-							  void *pvParameters,
-							  UBaseType_t uxPriority,
-							  TaskHandle_t *pvCreatedTask
-						  );
- * - * Create a new task and add it to the list of tasks that are ready to run. - * - * Internally, within the FreeRTOS implementation, tasks use two blocks of - * memory. The first block is used to hold the task's data structures. The - * second block is used by the task as its stack. If a task is created using - * xTaskCreate() then both blocks of memory are automatically dynamically - * allocated inside the xTaskCreate() function. (see - * http://www.freertos.org/a00111.html). If a task is created using - * xTaskCreateStatic() then the application writer must provide the required - * memory. xTaskCreateStatic() therefore allows a task to be created without - * using any dynamic memory allocation. - * - * See xTaskCreateStatic() for a version that does not use any dynamic memory - * allocation. - * - * xTaskCreate() can only be used to create a task that has unrestricted - * access to the entire microcontroller memory map. Systems that include MPU - * support can alternatively create an MPU constrained task using - * xTaskCreateRestricted(). - * - * @param pvTaskCode Pointer to the task entry function. Tasks - * must be implemented to never return (i.e. continuous loop). - * - * @param pcName A descriptive name for the task. This is mainly used to - * facilitate debugging. Max length defined by configMAX_TASK_NAME_LEN - default - * is 16. - * - * @param usStackDepth The size of the task stack specified as the number of - * variables the stack can hold - not the number of bytes. For example, if - * the stack is 16 bits wide and usStackDepth is defined as 100, 200 bytes - * will be allocated for stack storage. - * - * @param pvParameters Pointer that will be used as the parameter for the task - * being created. - * - * @param uxPriority The priority at which the task should run. Systems that - * include MPU support can optionally create tasks in a privileged (system) - * mode by setting bit portPRIVILEGE_BIT of the priority parameter. For - * example, to create a privileged task at priority 2 the uxPriority parameter - * should be set to ( 2 | portPRIVILEGE_BIT ). - * - * @param pvCreatedTask Used to pass back a handle by which the created task - * can be referenced. - * - * @return pdPASS if the task was successfully created and added to a ready - * list, otherwise an error code defined in the file projdefs.h - * - * Example usage: -
- // Task to be created.
- void vTaskCode( void * pvParameters )
- {
-	 for( ;; )
-	 {
-		 // Task code goes here.
-	 }
- }
-
- // Function that creates a task.
- void vOtherFunction( void )
- {
- static uint8_t ucParameterToPass;
- TaskHandle_t xHandle = NULL;
-
-	 // Create the task, storing the handle.  Note that the passed parameter ucParameterToPass
-	 // must exist for the lifetime of the task, so in this case is declared static.  If it was just an
-	 // an automatic stack variable it might no longer exist, or at least have been corrupted, by the time
-	 // the new task attempts to access it.
-	 xTaskCreate( vTaskCode, "NAME", STACK_SIZE, &ucParameterToPass, tskIDLE_PRIORITY, &xHandle );
-     configASSERT( xHandle );
-
-	 // Use the handle to delete the task.
-     if( xHandle != NULL )
-     {
-	     vTaskDelete( xHandle );
-     }
- }
-   
- * \defgroup xTaskCreate xTaskCreate - * \ingroup Tasks - */ -#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - BaseType_t xTaskCreate( TaskFunction_t pxTaskCode, - const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - const configSTACK_DEPTH_TYPE usStackDepth, - void * const pvParameters, - UBaseType_t uxPriority, - TaskHandle_t * const pxCreatedTask ) PRIVILEGED_FUNCTION; -#endif - -/** - * task. h - *
- TaskHandle_t xTaskCreateStatic( TaskFunction_t pvTaskCode,
-								 const char * const pcName,
-								 uint32_t ulStackDepth,
-								 void *pvParameters,
-								 UBaseType_t uxPriority,
-								 StackType_t *pxStackBuffer,
-								 StaticTask_t *pxTaskBuffer );
- * - * Create a new task and add it to the list of tasks that are ready to run. - * - * Internally, within the FreeRTOS implementation, tasks use two blocks of - * memory. The first block is used to hold the task's data structures. The - * second block is used by the task as its stack. If a task is created using - * xTaskCreate() then both blocks of memory are automatically dynamically - * allocated inside the xTaskCreate() function. (see - * http://www.freertos.org/a00111.html). If a task is created using - * xTaskCreateStatic() then the application writer must provide the required - * memory. xTaskCreateStatic() therefore allows a task to be created without - * using any dynamic memory allocation. - * - * @param pvTaskCode Pointer to the task entry function. Tasks - * must be implemented to never return (i.e. continuous loop). - * - * @param pcName A descriptive name for the task. This is mainly used to - * facilitate debugging. The maximum length of the string is defined by - * configMAX_TASK_NAME_LEN in FreeRTOSConfig.h. - * - * @param ulStackDepth The size of the task stack specified as the number of - * variables the stack can hold - not the number of bytes. For example, if - * the stack is 32-bits wide and ulStackDepth is defined as 100 then 400 bytes - * will be allocated for stack storage. - * - * @param pvParameters Pointer that will be used as the parameter for the task - * being created. - * - * @param uxPriority The priority at which the task will run. - * - * @param pxStackBuffer Must point to a StackType_t array that has at least - * ulStackDepth indexes - the array will then be used as the task's stack, - * removing the need for the stack to be allocated dynamically. - * - * @param pxTaskBuffer Must point to a variable of type StaticTask_t, which will - * then be used to hold the task's data structures, removing the need for the - * memory to be allocated dynamically. - * - * @return If neither pxStackBuffer or pxTaskBuffer are NULL, then the task will - * be created and pdPASS is returned. If either pxStackBuffer or pxTaskBuffer - * are NULL then the task will not be created and - * errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY is returned. - * - * Example usage: -
-
-    // Dimensions the buffer that the task being created will use as its stack.
-    // NOTE:  This is the number of words the stack will hold, not the number of
-    // bytes.  For example, if each stack item is 32-bits, and this is set to 100,
-    // then 400 bytes (100 * 32-bits) will be allocated.
-    #define STACK_SIZE 200
-
-    // Structure that will hold the TCB of the task being created.
-    StaticTask_t xTaskBuffer;
-
-    // Buffer that the task being created will use as its stack.  Note this is
-    // an array of StackType_t variables.  The size of StackType_t is dependent on
-    // the RTOS port.
-    StackType_t xStack[ STACK_SIZE ];
-
-    // Function that implements the task being created.
-    void vTaskCode( void * pvParameters )
-    {
-        // The parameter value is expected to be 1 as 1 is passed in the
-        // pvParameters value in the call to xTaskCreateStatic().
-        configASSERT( ( uint32_t ) pvParameters == 1UL );
-
-        for( ;; )
-        {
-            // Task code goes here.
-        }
-    }
-
-    // Function that creates a task.
-    void vOtherFunction( void )
-    {
-        TaskHandle_t xHandle = NULL;
-
-        // Create the task without using any dynamic memory allocation.
-        xHandle = xTaskCreateStatic(
-                      vTaskCode,       // Function that implements the task.
-                      "NAME",          // Text name for the task.
-                      STACK_SIZE,      // Stack size in words, not bytes.
-                      ( void * ) 1,    // Parameter passed into the task.
-                      tskIDLE_PRIORITY,// Priority at which the task is created.
-                      xStack,          // Array to use as the task's stack.
-                      &xTaskBuffer );  // Variable to hold the task's data structure.
-
-        // puxStackBuffer and pxTaskBuffer were not NULL, so the task will have
-        // been created, and xHandle will be the task's handle.  Use the handle
-        // to suspend the task.
-        vTaskSuspend( xHandle );
-    }
-   
- * \defgroup xTaskCreateStatic xTaskCreateStatic - * \ingroup Tasks - */ -#if( configSUPPORT_STATIC_ALLOCATION == 1 ) - TaskHandle_t xTaskCreateStatic( TaskFunction_t pxTaskCode, - const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - const uint32_t ulStackDepth, - void * const pvParameters, - UBaseType_t uxPriority, - StackType_t * const puxStackBuffer, - StaticTask_t * const pxTaskBuffer ) PRIVILEGED_FUNCTION; -#endif /* configSUPPORT_STATIC_ALLOCATION */ - -/** - * task. h - *
- BaseType_t xTaskCreateRestricted( TaskParameters_t *pxTaskDefinition, TaskHandle_t *pxCreatedTask );
- * - * Only available when configSUPPORT_DYNAMIC_ALLOCATION is set to 1. - * - * xTaskCreateRestricted() should only be used in systems that include an MPU - * implementation. - * - * Create a new task and add it to the list of tasks that are ready to run. - * The function parameters define the memory regions and associated access - * permissions allocated to the task. - * - * See xTaskCreateRestrictedStatic() for a version that does not use any - * dynamic memory allocation. - * - * @param pxTaskDefinition Pointer to a structure that contains a member - * for each of the normal xTaskCreate() parameters (see the xTaskCreate() API - * documentation) plus an optional stack buffer and the memory region - * definitions. - * - * @param pxCreatedTask Used to pass back a handle by which the created task - * can be referenced. - * - * @return pdPASS if the task was successfully created and added to a ready - * list, otherwise an error code defined in the file projdefs.h - * - * Example usage: -
-// Create an TaskParameters_t structure that defines the task to be created.
-static const TaskParameters_t xCheckTaskParameters =
-{
-	vATask,		// pvTaskCode - the function that implements the task.
-	"ATask",	// pcName - just a text name for the task to assist debugging.
-	100,		// usStackDepth	- the stack size DEFINED IN WORDS.
-	NULL,		// pvParameters - passed into the task function as the function parameters.
-	( 1UL | portPRIVILEGE_BIT ),// uxPriority - task priority, set the portPRIVILEGE_BIT if the task should run in a privileged state.
-	cStackBuffer,// puxStackBuffer - the buffer to be used as the task stack.
-
-	// xRegions - Allocate up to three separate memory regions for access by
-	// the task, with appropriate access permissions.  Different processors have
-	// different memory alignment requirements - refer to the FreeRTOS documentation
-	// for full information.
-	{
-		// Base address					Length	Parameters
-        { cReadWriteArray,				32,		portMPU_REGION_READ_WRITE },
-        { cReadOnlyArray,				32,		portMPU_REGION_READ_ONLY },
-        { cPrivilegedOnlyAccessArray,	128,	portMPU_REGION_PRIVILEGED_READ_WRITE }
-	}
-};
-
-int main( void )
-{
-TaskHandle_t xHandle;
-
-	// Create a task from the const structure defined above.  The task handle
-	// is requested (the second parameter is not NULL) but in this case just for
-	// demonstration purposes as its not actually used.
-	xTaskCreateRestricted( &xRegTest1Parameters, &xHandle );
-
-	// Start the scheduler.
-	vTaskStartScheduler();
-
-	// Will only get here if there was insufficient memory to create the idle
-	// and/or timer task.
-	for( ;; );
-}
-   
- * \defgroup xTaskCreateRestricted xTaskCreateRestricted - * \ingroup Tasks - */ -#if( portUSING_MPU_WRAPPERS == 1 ) - BaseType_t xTaskCreateRestricted( const TaskParameters_t * const pxTaskDefinition, TaskHandle_t *pxCreatedTask ) PRIVILEGED_FUNCTION; -#endif - -/** - * task. h - *
- BaseType_t xTaskCreateRestrictedStatic( TaskParameters_t *pxTaskDefinition, TaskHandle_t *pxCreatedTask );
- * - * Only available when configSUPPORT_STATIC_ALLOCATION is set to 1. - * - * xTaskCreateRestrictedStatic() should only be used in systems that include an - * MPU implementation. - * - * Internally, within the FreeRTOS implementation, tasks use two blocks of - * memory. The first block is used to hold the task's data structures. The - * second block is used by the task as its stack. If a task is created using - * xTaskCreateRestricted() then the stack is provided by the application writer, - * and the memory used to hold the task's data structure is automatically - * dynamically allocated inside the xTaskCreateRestricted() function. If a task - * is created using xTaskCreateRestrictedStatic() then the application writer - * must provide the memory used to hold the task's data structures too. - * xTaskCreateRestrictedStatic() therefore allows a memory protected task to be - * created without using any dynamic memory allocation. - * - * @param pxTaskDefinition Pointer to a structure that contains a member - * for each of the normal xTaskCreate() parameters (see the xTaskCreate() API - * documentation) plus an optional stack buffer and the memory region - * definitions. If configSUPPORT_STATIC_ALLOCATION is set to 1 the structure - * contains an additional member, which is used to point to a variable of type - * StaticTask_t - which is then used to hold the task's data structure. - * - * @param pxCreatedTask Used to pass back a handle by which the created task - * can be referenced. - * - * @return pdPASS if the task was successfully created and added to a ready - * list, otherwise an error code defined in the file projdefs.h - * - * Example usage: -
-// Create an TaskParameters_t structure that defines the task to be created.
-// The StaticTask_t variable is only included in the structure when
-// configSUPPORT_STATIC_ALLOCATION is set to 1.  The PRIVILEGED_DATA macro can
-// be used to force the variable into the RTOS kernel's privileged data area.
-static PRIVILEGED_DATA StaticTask_t xTaskBuffer;
-static const TaskParameters_t xCheckTaskParameters =
-{
-	vATask,		// pvTaskCode - the function that implements the task.
-	"ATask",	// pcName - just a text name for the task to assist debugging.
-	100,		// usStackDepth	- the stack size DEFINED IN WORDS.
-	NULL,		// pvParameters - passed into the task function as the function parameters.
-	( 1UL | portPRIVILEGE_BIT ),// uxPriority - task priority, set the portPRIVILEGE_BIT if the task should run in a privileged state.
-	cStackBuffer,// puxStackBuffer - the buffer to be used as the task stack.
-
-	// xRegions - Allocate up to three separate memory regions for access by
-	// the task, with appropriate access permissions.  Different processors have
-	// different memory alignment requirements - refer to the FreeRTOS documentation
-	// for full information.
-	{
-		// Base address					Length	Parameters
-        { cReadWriteArray,				32,		portMPU_REGION_READ_WRITE },
-        { cReadOnlyArray,				32,		portMPU_REGION_READ_ONLY },
-        { cPrivilegedOnlyAccessArray,	128,	portMPU_REGION_PRIVILEGED_READ_WRITE }
-	}
-
-	&xTaskBuffer; // Holds the task's data structure.
-};
-
-int main( void )
-{
-TaskHandle_t xHandle;
-
-	// Create a task from the const structure defined above.  The task handle
-	// is requested (the second parameter is not NULL) but in this case just for
-	// demonstration purposes as its not actually used.
-	xTaskCreateRestricted( &xRegTest1Parameters, &xHandle );
-
-	// Start the scheduler.
-	vTaskStartScheduler();
-
-	// Will only get here if there was insufficient memory to create the idle
-	// and/or timer task.
-	for( ;; );
-}
-   
- * \defgroup xTaskCreateRestrictedStatic xTaskCreateRestrictedStatic - * \ingroup Tasks - */ -#if( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) - BaseType_t xTaskCreateRestrictedStatic( const TaskParameters_t * const pxTaskDefinition, TaskHandle_t *pxCreatedTask ) PRIVILEGED_FUNCTION; -#endif - -/** - * task. h - *
- void vTaskAllocateMPURegions( TaskHandle_t xTask, const MemoryRegion_t * const pxRegions );
- * - * Memory regions are assigned to a restricted task when the task is created by - * a call to xTaskCreateRestricted(). These regions can be redefined using - * vTaskAllocateMPURegions(). - * - * @param xTask The handle of the task being updated. - * - * @param xRegions A pointer to an MemoryRegion_t structure that contains the - * new memory region definitions. - * - * Example usage: -
-// Define an array of MemoryRegion_t structures that configures an MPU region
-// allowing read/write access for 1024 bytes starting at the beginning of the
-// ucOneKByte array.  The other two of the maximum 3 definable regions are
-// unused so set to zero.
-static const MemoryRegion_t xAltRegions[ portNUM_CONFIGURABLE_REGIONS ] =
-{
-	// Base address		Length		Parameters
-	{ ucOneKByte,		1024,		portMPU_REGION_READ_WRITE },
-	{ 0,				0,			0 },
-	{ 0,				0,			0 }
-};
-
-void vATask( void *pvParameters )
-{
-	// This task was created such that it has access to certain regions of
-	// memory as defined by the MPU configuration.  At some point it is
-	// desired that these MPU regions are replaced with that defined in the
-	// xAltRegions const struct above.  Use a call to vTaskAllocateMPURegions()
-	// for this purpose.  NULL is used as the task handle to indicate that this
-	// function should modify the MPU regions of the calling task.
-	vTaskAllocateMPURegions( NULL, xAltRegions );
-
-	// Now the task can continue its function, but from this point on can only
-	// access its stack and the ucOneKByte array (unless any other statically
-	// defined or shared regions have been declared elsewhere).
-}
-   
- * \defgroup xTaskCreateRestricted xTaskCreateRestricted - * \ingroup Tasks - */ -void vTaskAllocateMPURegions( TaskHandle_t xTask, const MemoryRegion_t * const pxRegions ) PRIVILEGED_FUNCTION; - -/** - * task. h - *
void vTaskDelete( TaskHandle_t xTask );
- * - * INCLUDE_vTaskDelete must be defined as 1 for this function to be available. - * See the configuration section for more information. - * - * Remove a task from the RTOS real time kernel's management. The task being - * deleted will be removed from all ready, blocked, suspended and event lists. - * - * NOTE: The idle task is responsible for freeing the kernel allocated - * memory from tasks that have been deleted. It is therefore important that - * the idle task is not starved of microcontroller processing time if your - * application makes any calls to vTaskDelete (). Memory allocated by the - * task code is not automatically freed, and should be freed before the task - * is deleted. - * - * See the demo application file death.c for sample code that utilises - * vTaskDelete (). - * - * @param xTask The handle of the task to be deleted. Passing NULL will - * cause the calling task to be deleted. - * - * Example usage: -
- void vOtherFunction( void )
- {
- TaskHandle_t xHandle;
-
-	 // Create the task, storing the handle.
-	 xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle );
-
-	 // Use the handle to delete the task.
-	 vTaskDelete( xHandle );
- }
-   
- * \defgroup vTaskDelete vTaskDelete - * \ingroup Tasks - */ -void vTaskDelete( TaskHandle_t xTaskToDelete ) PRIVILEGED_FUNCTION; - -/*----------------------------------------------------------- - * TASK CONTROL API - *----------------------------------------------------------*/ - -/** - * task. h - *
void vTaskDelay( const TickType_t xTicksToDelay );
- * - * Delay a task for a given number of ticks. The actual time that the - * task remains blocked depends on the tick rate. The constant - * portTICK_PERIOD_MS can be used to calculate real time from the tick - * rate - with the resolution of one tick period. - * - * INCLUDE_vTaskDelay must be defined as 1 for this function to be available. - * See the configuration section for more information. - * - * - * vTaskDelay() specifies a time at which the task wishes to unblock relative to - * the time at which vTaskDelay() is called. For example, specifying a block - * period of 100 ticks will cause the task to unblock 100 ticks after - * vTaskDelay() is called. vTaskDelay() does not therefore provide a good method - * of controlling the frequency of a periodic task as the path taken through the - * code, as well as other task and interrupt activity, will effect the frequency - * at which vTaskDelay() gets called and therefore the time at which the task - * next executes. See vTaskDelayUntil() for an alternative API function designed - * to facilitate fixed frequency execution. It does this by specifying an - * absolute time (rather than a relative time) at which the calling task should - * unblock. - * - * @param xTicksToDelay The amount of time, in tick periods, that - * the calling task should block. - * - * Example usage: - - void vTaskFunction( void * pvParameters ) - { - // Block for 500ms. - const TickType_t xDelay = 500 / portTICK_PERIOD_MS; - - for( ;; ) - { - // Simply toggle the LED every 500ms, blocking between each toggle. - vToggleLED(); - vTaskDelay( xDelay ); - } - } - - * \defgroup vTaskDelay vTaskDelay - * \ingroup TaskCtrl - */ -void vTaskDelay( const TickType_t xTicksToDelay ) PRIVILEGED_FUNCTION; - -/** - * task. h - *
void vTaskDelayUntil( TickType_t *pxPreviousWakeTime, const TickType_t xTimeIncrement );
- * - * INCLUDE_vTaskDelayUntil must be defined as 1 for this function to be available. - * See the configuration section for more information. - * - * Delay a task until a specified time. This function can be used by periodic - * tasks to ensure a constant execution frequency. - * - * This function differs from vTaskDelay () in one important aspect: vTaskDelay () will - * cause a task to block for the specified number of ticks from the time vTaskDelay () is - * called. It is therefore difficult to use vTaskDelay () by itself to generate a fixed - * execution frequency as the time between a task starting to execute and that task - * calling vTaskDelay () may not be fixed [the task may take a different path though the - * code between calls, or may get interrupted or preempted a different number of times - * each time it executes]. - * - * Whereas vTaskDelay () specifies a wake time relative to the time at which the function - * is called, vTaskDelayUntil () specifies the absolute (exact) time at which it wishes to - * unblock. - * - * The constant portTICK_PERIOD_MS can be used to calculate real time from the tick - * rate - with the resolution of one tick period. - * - * @param pxPreviousWakeTime Pointer to a variable that holds the time at which the - * task was last unblocked. The variable must be initialised with the current time - * prior to its first use (see the example below). Following this the variable is - * automatically updated within vTaskDelayUntil (). - * - * @param xTimeIncrement The cycle time period. The task will be unblocked at - * time *pxPreviousWakeTime + xTimeIncrement. Calling vTaskDelayUntil with the - * same xTimeIncrement parameter value will cause the task to execute with - * a fixed interface period. - * - * Example usage: -
- // Perform an action every 10 ticks.
- void vTaskFunction( void * pvParameters )
- {
- TickType_t xLastWakeTime;
- const TickType_t xFrequency = 10;
-
-	 // Initialise the xLastWakeTime variable with the current time.
-	 xLastWakeTime = xTaskGetTickCount ();
-	 for( ;; )
-	 {
-		 // Wait for the next cycle.
-		 vTaskDelayUntil( &xLastWakeTime, xFrequency );
-
-		 // Perform action here.
-	 }
- }
-   
- * \defgroup vTaskDelayUntil vTaskDelayUntil - * \ingroup TaskCtrl - */ -void vTaskDelayUntil( TickType_t * const pxPreviousWakeTime, const TickType_t xTimeIncrement ) PRIVILEGED_FUNCTION; - -/** - * task. h - *
BaseType_t xTaskAbortDelay( TaskHandle_t xTask );
- * - * INCLUDE_xTaskAbortDelay must be defined as 1 in FreeRTOSConfig.h for this - * function to be available. - * - * A task will enter the Blocked state when it is waiting for an event. The - * event it is waiting for can be a temporal event (waiting for a time), such - * as when vTaskDelay() is called, or an event on an object, such as when - * xQueueReceive() or ulTaskNotifyTake() is called. If the handle of a task - * that is in the Blocked state is used in a call to xTaskAbortDelay() then the - * task will leave the Blocked state, and return from whichever function call - * placed the task into the Blocked state. - * - * @param xTask The handle of the task to remove from the Blocked state. - * - * @return If the task referenced by xTask was not in the Blocked state then - * pdFAIL is returned. Otherwise pdPASS is returned. - * - * \defgroup xTaskAbortDelay xTaskAbortDelay - * \ingroup TaskCtrl - */ -BaseType_t xTaskAbortDelay( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; - -/** - * task. h - *
UBaseType_t uxTaskPriorityGet( TaskHandle_t xTask );
- * - * INCLUDE_uxTaskPriorityGet must be defined as 1 for this function to be available. - * See the configuration section for more information. - * - * Obtain the priority of any task. - * - * @param xTask Handle of the task to be queried. Passing a NULL - * handle results in the priority of the calling task being returned. - * - * @return The priority of xTask. - * - * Example usage: -
- void vAFunction( void )
- {
- TaskHandle_t xHandle;
-
-	 // Create a task, storing the handle.
-	 xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle );
-
-	 // ...
-
-	 // Use the handle to obtain the priority of the created task.
-	 // It was created with tskIDLE_PRIORITY, but may have changed
-	 // it itself.
-	 if( uxTaskPriorityGet( xHandle ) != tskIDLE_PRIORITY )
-	 {
-		 // The task has changed it's priority.
-	 }
-
-	 // ...
-
-	 // Is our priority higher than the created task?
-	 if( uxTaskPriorityGet( xHandle ) < uxTaskPriorityGet( NULL ) )
-	 {
-		 // Our priority (obtained using NULL handle) is higher.
-	 }
- }
-   
- * \defgroup uxTaskPriorityGet uxTaskPriorityGet - * \ingroup TaskCtrl - */ -UBaseType_t uxTaskPriorityGet( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; - -/** - * task. h - *
UBaseType_t uxTaskPriorityGetFromISR( TaskHandle_t xTask );
- * - * A version of uxTaskPriorityGet() that can be used from an ISR. - */ -UBaseType_t uxTaskPriorityGetFromISR( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; - -/** - * task. h - *
eTaskState eTaskGetState( TaskHandle_t xTask );
- * - * INCLUDE_eTaskGetState must be defined as 1 for this function to be available. - * See the configuration section for more information. - * - * Obtain the state of any task. States are encoded by the eTaskState - * enumerated type. - * - * @param xTask Handle of the task to be queried. - * - * @return The state of xTask at the time the function was called. Note the - * state of the task might change between the function being called, and the - * functions return value being tested by the calling task. - */ -eTaskState eTaskGetState( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; - -/** - * task. h - *
void vTaskGetInfo( TaskHandle_t xTask, TaskStatus_t *pxTaskStatus, BaseType_t xGetFreeStackSpace, eTaskState eState );
- * - * configUSE_TRACE_FACILITY must be defined as 1 for this function to be - * available. See the configuration section for more information. - * - * Populates a TaskStatus_t structure with information about a task. - * - * @param xTask Handle of the task being queried. If xTask is NULL then - * information will be returned about the calling task. - * - * @param pxTaskStatus A pointer to the TaskStatus_t structure that will be - * filled with information about the task referenced by the handle passed using - * the xTask parameter. - * - * @xGetFreeStackSpace The TaskStatus_t structure contains a member to report - * the stack high water mark of the task being queried. Calculating the stack - * high water mark takes a relatively long time, and can make the system - * temporarily unresponsive - so the xGetFreeStackSpace parameter is provided to - * allow the high water mark checking to be skipped. The high watermark value - * will only be written to the TaskStatus_t structure if xGetFreeStackSpace is - * not set to pdFALSE; - * - * @param eState The TaskStatus_t structure contains a member to report the - * state of the task being queried. Obtaining the task state is not as fast as - * a simple assignment - so the eState parameter is provided to allow the state - * information to be omitted from the TaskStatus_t structure. To obtain state - * information then set eState to eInvalid - otherwise the value passed in - * eState will be reported as the task state in the TaskStatus_t structure. - * - * Example usage: -
- void vAFunction( void )
- {
- TaskHandle_t xHandle;
- TaskStatus_t xTaskDetails;
-
-    // Obtain the handle of a task from its name.
-    xHandle = xTaskGetHandle( "Task_Name" );
-
-    // Check the handle is not NULL.
-    configASSERT( xHandle );
-
-    // Use the handle to obtain further information about the task.
-    vTaskGetInfo( xHandle,
-                  &xTaskDetails,
-                  pdTRUE, // Include the high water mark in xTaskDetails.
-                  eInvalid ); // Include the task state in xTaskDetails.
- }
-   
- * \defgroup vTaskGetInfo vTaskGetInfo - * \ingroup TaskCtrl - */ -void vTaskGetInfo( TaskHandle_t xTask, TaskStatus_t *pxTaskStatus, BaseType_t xGetFreeStackSpace, eTaskState eState ) PRIVILEGED_FUNCTION; - -/** - * task. h - *
void vTaskPrioritySet( TaskHandle_t xTask, UBaseType_t uxNewPriority );
- * - * INCLUDE_vTaskPrioritySet must be defined as 1 for this function to be available. - * See the configuration section for more information. - * - * Set the priority of any task. - * - * A context switch will occur before the function returns if the priority - * being set is higher than the currently executing task. - * - * @param xTask Handle to the task for which the priority is being set. - * Passing a NULL handle results in the priority of the calling task being set. - * - * @param uxNewPriority The priority to which the task will be set. - * - * Example usage: -
- void vAFunction( void )
- {
- TaskHandle_t xHandle;
-
-	 // Create a task, storing the handle.
-	 xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle );
-
-	 // ...
-
-	 // Use the handle to raise the priority of the created task.
-	 vTaskPrioritySet( xHandle, tskIDLE_PRIORITY + 1 );
-
-	 // ...
-
-	 // Use a NULL handle to raise our priority to the same value.
-	 vTaskPrioritySet( NULL, tskIDLE_PRIORITY + 1 );
- }
-   
- * \defgroup vTaskPrioritySet vTaskPrioritySet - * \ingroup TaskCtrl - */ -void vTaskPrioritySet( TaskHandle_t xTask, UBaseType_t uxNewPriority ) PRIVILEGED_FUNCTION; - -/** - * task. h - *
void vTaskSuspend( TaskHandle_t xTaskToSuspend );
- * - * INCLUDE_vTaskSuspend must be defined as 1 for this function to be available. - * See the configuration section for more information. - * - * Suspend any task. When suspended a task will never get any microcontroller - * processing time, no matter what its priority. - * - * Calls to vTaskSuspend are not accumulative - - * i.e. calling vTaskSuspend () twice on the same task still only requires one - * call to vTaskResume () to ready the suspended task. - * - * @param xTaskToSuspend Handle to the task being suspended. Passing a NULL - * handle will cause the calling task to be suspended. - * - * Example usage: -
- void vAFunction( void )
- {
- TaskHandle_t xHandle;
-
-	 // Create a task, storing the handle.
-	 xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle );
-
-	 // ...
-
-	 // Use the handle to suspend the created task.
-	 vTaskSuspend( xHandle );
-
-	 // ...
-
-	 // The created task will not run during this period, unless
-	 // another task calls vTaskResume( xHandle ).
-
-	 //...
-
-
-	 // Suspend ourselves.
-	 vTaskSuspend( NULL );
-
-	 // We cannot get here unless another task calls vTaskResume
-	 // with our handle as the parameter.
- }
-   
- * \defgroup vTaskSuspend vTaskSuspend - * \ingroup TaskCtrl - */ -void vTaskSuspend( TaskHandle_t xTaskToSuspend ) PRIVILEGED_FUNCTION; - -/** - * task. h - *
void vTaskResume( TaskHandle_t xTaskToResume );
- * - * INCLUDE_vTaskSuspend must be defined as 1 for this function to be available. - * See the configuration section for more information. - * - * Resumes a suspended task. - * - * A task that has been suspended by one or more calls to vTaskSuspend () - * will be made available for running again by a single call to - * vTaskResume (). - * - * @param xTaskToResume Handle to the task being readied. - * - * Example usage: -
- void vAFunction( void )
- {
- TaskHandle_t xHandle;
-
-	 // Create a task, storing the handle.
-	 xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle );
-
-	 // ...
-
-	 // Use the handle to suspend the created task.
-	 vTaskSuspend( xHandle );
-
-	 // ...
-
-	 // The created task will not run during this period, unless
-	 // another task calls vTaskResume( xHandle ).
-
-	 //...
-
-
-	 // Resume the suspended task ourselves.
-	 vTaskResume( xHandle );
-
-	 // The created task will once again get microcontroller processing
-	 // time in accordance with its priority within the system.
- }
-   
- * \defgroup vTaskResume vTaskResume - * \ingroup TaskCtrl - */ -void vTaskResume( TaskHandle_t xTaskToResume ) PRIVILEGED_FUNCTION; - -/** - * task. h - *
void xTaskResumeFromISR( TaskHandle_t xTaskToResume );
- * - * INCLUDE_xTaskResumeFromISR must be defined as 1 for this function to be - * available. See the configuration section for more information. - * - * An implementation of vTaskResume() that can be called from within an ISR. - * - * A task that has been suspended by one or more calls to vTaskSuspend () - * will be made available for running again by a single call to - * xTaskResumeFromISR (). - * - * xTaskResumeFromISR() should not be used to synchronise a task with an - * interrupt if there is a chance that the interrupt could arrive prior to the - * task being suspended - as this can lead to interrupts being missed. Use of a - * semaphore as a synchronisation mechanism would avoid this eventuality. - * - * @param xTaskToResume Handle to the task being readied. - * - * @return pdTRUE if resuming the task should result in a context switch, - * otherwise pdFALSE. This is used by the ISR to determine if a context switch - * may be required following the ISR. - * - * \defgroup vTaskResumeFromISR vTaskResumeFromISR - * \ingroup TaskCtrl - */ -BaseType_t xTaskResumeFromISR( TaskHandle_t xTaskToResume ) PRIVILEGED_FUNCTION; - -/*----------------------------------------------------------- - * SCHEDULER CONTROL - *----------------------------------------------------------*/ - -/** - * task. h - *
void vTaskStartScheduler( void );
- * - * Starts the real time kernel tick processing. After calling the kernel - * has control over which tasks are executed and when. - * - * See the demo application file main.c for an example of creating - * tasks and starting the kernel. - * - * Example usage: -
- void vAFunction( void )
- {
-	 // Create at least one task before starting the kernel.
-	 xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL );
-
-	 // Start the real time kernel with preemption.
-	 vTaskStartScheduler ();
-
-	 // Will not get here unless a task calls vTaskEndScheduler ()
- }
-   
- * - * \defgroup vTaskStartScheduler vTaskStartScheduler - * \ingroup SchedulerControl - */ -void vTaskStartScheduler( void ) PRIVILEGED_FUNCTION; - -/** - * task. h - *
void vTaskEndScheduler( void );
- * - * NOTE: At the time of writing only the x86 real mode port, which runs on a PC - * in place of DOS, implements this function. - * - * Stops the real time kernel tick. All created tasks will be automatically - * deleted and multitasking (either preemptive or cooperative) will - * stop. Execution then resumes from the point where vTaskStartScheduler () - * was called, as if vTaskStartScheduler () had just returned. - * - * See the demo application file main. c in the demo/PC directory for an - * example that uses vTaskEndScheduler (). - * - * vTaskEndScheduler () requires an exit function to be defined within the - * portable layer (see vPortEndScheduler () in port. c for the PC port). This - * performs hardware specific operations such as stopping the kernel tick. - * - * vTaskEndScheduler () will cause all of the resources allocated by the - * kernel to be freed - but will not free resources allocated by application - * tasks. - * - * Example usage: -
- void vTaskCode( void * pvParameters )
- {
-	 for( ;; )
-	 {
-		 // Task code goes here.
-
-		 // At some point we want to end the real time kernel processing
-		 // so call ...
-		 vTaskEndScheduler ();
-	 }
- }
-
- void vAFunction( void )
- {
-	 // Create at least one task before starting the kernel.
-	 xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL );
-
-	 // Start the real time kernel with preemption.
-	 vTaskStartScheduler ();
-
-	 // Will only get here when the vTaskCode () task has called
-	 // vTaskEndScheduler ().  When we get here we are back to single task
-	 // execution.
- }
-   
- * - * \defgroup vTaskEndScheduler vTaskEndScheduler - * \ingroup SchedulerControl - */ -void vTaskEndScheduler( void ) PRIVILEGED_FUNCTION; - -/** - * task. h - *
void vTaskSuspendAll( void );
- * - * Suspends the scheduler without disabling interrupts. Context switches will - * not occur while the scheduler is suspended. - * - * After calling vTaskSuspendAll () the calling task will continue to execute - * without risk of being swapped out until a call to xTaskResumeAll () has been - * made. - * - * API functions that have the potential to cause a context switch (for example, - * vTaskDelayUntil(), xQueueSend(), etc.) must not be called while the scheduler - * is suspended. - * - * Example usage: -
- void vTask1( void * pvParameters )
- {
-	 for( ;; )
-	 {
-		 // Task code goes here.
-
-		 // ...
-
-		 // At some point the task wants to perform a long operation during
-		 // which it does not want to get swapped out.  It cannot use
-		 // taskENTER_CRITICAL ()/taskEXIT_CRITICAL () as the length of the
-		 // operation may cause interrupts to be missed - including the
-		 // ticks.
-
-		 // Prevent the real time kernel swapping out the task.
-		 vTaskSuspendAll ();
-
-		 // Perform the operation here.  There is no need to use critical
-		 // sections as we have all the microcontroller processing time.
-		 // During this time interrupts will still operate and the kernel
-		 // tick count will be maintained.
-
-		 // ...
-
-		 // The operation is complete.  Restart the kernel.
-		 xTaskResumeAll ();
-	 }
- }
-   
- * \defgroup vTaskSuspendAll vTaskSuspendAll - * \ingroup SchedulerControl - */ -void vTaskSuspendAll( void ) PRIVILEGED_FUNCTION; - -/** - * task. h - *
BaseType_t xTaskResumeAll( void );
- * - * Resumes scheduler activity after it was suspended by a call to - * vTaskSuspendAll(). - * - * xTaskResumeAll() only resumes the scheduler. It does not unsuspend tasks - * that were previously suspended by a call to vTaskSuspend(). - * - * @return If resuming the scheduler caused a context switch then pdTRUE is - * returned, otherwise pdFALSE is returned. - * - * Example usage: -
- void vTask1( void * pvParameters )
- {
-	 for( ;; )
-	 {
-		 // Task code goes here.
-
-		 // ...
-
-		 // At some point the task wants to perform a long operation during
-		 // which it does not want to get swapped out.  It cannot use
-		 // taskENTER_CRITICAL ()/taskEXIT_CRITICAL () as the length of the
-		 // operation may cause interrupts to be missed - including the
-		 // ticks.
-
-		 // Prevent the real time kernel swapping out the task.
-		 vTaskSuspendAll ();
-
-		 // Perform the operation here.  There is no need to use critical
-		 // sections as we have all the microcontroller processing time.
-		 // During this time interrupts will still operate and the real
-		 // time kernel tick count will be maintained.
-
-		 // ...
-
-		 // The operation is complete.  Restart the kernel.  We want to force
-		 // a context switch - but there is no point if resuming the scheduler
-		 // caused a context switch already.
-		 if( !xTaskResumeAll () )
-		 {
-			  taskYIELD ();
-		 }
-	 }
- }
-   
- * \defgroup xTaskResumeAll xTaskResumeAll - * \ingroup SchedulerControl - */ -BaseType_t xTaskResumeAll( void ) PRIVILEGED_FUNCTION; - -/*----------------------------------------------------------- - * TASK UTILITIES - *----------------------------------------------------------*/ - -/** - * task. h - *
TickType_t xTaskGetTickCount( void );
- * - * @return The count of ticks since vTaskStartScheduler was called. - * - * \defgroup xTaskGetTickCount xTaskGetTickCount - * \ingroup TaskUtils - */ -TickType_t xTaskGetTickCount( void ) PRIVILEGED_FUNCTION; - -/** - * task. h - *
TickType_t xTaskGetTickCountFromISR( void );
- * - * @return The count of ticks since vTaskStartScheduler was called. - * - * This is a version of xTaskGetTickCount() that is safe to be called from an - * ISR - provided that TickType_t is the natural word size of the - * microcontroller being used or interrupt nesting is either not supported or - * not being used. - * - * \defgroup xTaskGetTickCountFromISR xTaskGetTickCountFromISR - * \ingroup TaskUtils - */ -TickType_t xTaskGetTickCountFromISR( void ) PRIVILEGED_FUNCTION; - -/** - * task. h - *
uint16_t uxTaskGetNumberOfTasks( void );
- * - * @return The number of tasks that the real time kernel is currently managing. - * This includes all ready, blocked and suspended tasks. A task that - * has been deleted but not yet freed by the idle task will also be - * included in the count. - * - * \defgroup uxTaskGetNumberOfTasks uxTaskGetNumberOfTasks - * \ingroup TaskUtils - */ -UBaseType_t uxTaskGetNumberOfTasks( void ) PRIVILEGED_FUNCTION; - -/** - * task. h - *
char *pcTaskGetName( TaskHandle_t xTaskToQuery );
- * - * @return The text (human readable) name of the task referenced by the handle - * xTaskToQuery. A task can query its own name by either passing in its own - * handle, or by setting xTaskToQuery to NULL. - * - * \defgroup pcTaskGetName pcTaskGetName - * \ingroup TaskUtils - */ -char *pcTaskGetName( TaskHandle_t xTaskToQuery ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - -/** - * task. h - *
TaskHandle_t xTaskGetHandle( const char *pcNameToQuery );
- * - * NOTE: This function takes a relatively long time to complete and should be - * used sparingly. - * - * @return The handle of the task that has the human readable name pcNameToQuery. - * NULL is returned if no matching name is found. INCLUDE_xTaskGetHandle - * must be set to 1 in FreeRTOSConfig.h for pcTaskGetHandle() to be available. - * - * \defgroup pcTaskGetHandle pcTaskGetHandle - * \ingroup TaskUtils - */ -TaskHandle_t xTaskGetHandle( const char *pcNameToQuery ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - -/** - * task.h - *
UBaseType_t uxTaskGetStackHighWaterMark( TaskHandle_t xTask );
- * - * INCLUDE_uxTaskGetStackHighWaterMark must be set to 1 in FreeRTOSConfig.h for - * this function to be available. - * - * Returns the high water mark of the stack associated with xTask. That is, - * the minimum free stack space there has been (in words, so on a 32 bit machine - * a value of 1 means 4 bytes) since the task started. The smaller the returned - * number the closer the task has come to overflowing its stack. - * - * @param xTask Handle of the task associated with the stack to be checked. - * Set xTask to NULL to check the stack of the calling task. - * - * @return The smallest amount of free stack space there has been (in words, so - * actual spaces on the stack rather than bytes) since the task referenced by - * xTask was created. - */ -UBaseType_t uxTaskGetStackHighWaterMark( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; - -/* When using trace macros it is sometimes necessary to include task.h before -FreeRTOS.h. When this is done TaskHookFunction_t will not yet have been defined, -so the following two prototypes will cause a compilation error. This can be -fixed by simply guarding against the inclusion of these two prototypes unless -they are explicitly required by the configUSE_APPLICATION_TASK_TAG configuration -constant. */ -#ifdef configUSE_APPLICATION_TASK_TAG - #if configUSE_APPLICATION_TASK_TAG == 1 - /** - * task.h - *
void vTaskSetApplicationTaskTag( TaskHandle_t xTask, TaskHookFunction_t pxHookFunction );
- * - * Sets pxHookFunction to be the task hook function used by the task xTask. - * Passing xTask as NULL has the effect of setting the calling tasks hook - * function. - */ - void vTaskSetApplicationTaskTag( TaskHandle_t xTask, TaskHookFunction_t pxHookFunction ) PRIVILEGED_FUNCTION; - - /** - * task.h - *
void xTaskGetApplicationTaskTag( TaskHandle_t xTask );
- * - * Returns the pxHookFunction value assigned to the task xTask. - */ - TaskHookFunction_t xTaskGetApplicationTaskTag( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; - #endif /* configUSE_APPLICATION_TASK_TAG ==1 */ -#endif /* ifdef configUSE_APPLICATION_TASK_TAG */ - -#if( configNUM_THREAD_LOCAL_STORAGE_POINTERS > 0 ) - - /* Each task contains an array of pointers that is dimensioned by the - configNUM_THREAD_LOCAL_STORAGE_POINTERS setting in FreeRTOSConfig.h. The - kernel does not use the pointers itself, so the application writer can use - the pointers for any purpose they wish. The following two functions are - used to set and query a pointer respectively. */ - void vTaskSetThreadLocalStoragePointer( TaskHandle_t xTaskToSet, BaseType_t xIndex, void *pvValue ) PRIVILEGED_FUNCTION; - void *pvTaskGetThreadLocalStoragePointer( TaskHandle_t xTaskToQuery, BaseType_t xIndex ) PRIVILEGED_FUNCTION; - -#endif - -/** - * task.h - *
BaseType_t xTaskCallApplicationTaskHook( TaskHandle_t xTask, void *pvParameter );
- * - * Calls the hook function associated with xTask. Passing xTask as NULL has - * the effect of calling the Running tasks (the calling task) hook function. - * - * pvParameter is passed to the hook function for the task to interpret as it - * wants. The return value is the value returned by the task hook function - * registered by the user. - */ -BaseType_t xTaskCallApplicationTaskHook( TaskHandle_t xTask, void *pvParameter ) PRIVILEGED_FUNCTION; - -/** - * xTaskGetIdleTaskHandle() is only available if - * INCLUDE_xTaskGetIdleTaskHandle is set to 1 in FreeRTOSConfig.h. - * - * Simply returns the handle of the idle task. It is not valid to call - * xTaskGetIdleTaskHandle() before the scheduler has been started. - */ -TaskHandle_t xTaskGetIdleTaskHandle( void ) PRIVILEGED_FUNCTION; - -/** - * configUSE_TRACE_FACILITY must be defined as 1 in FreeRTOSConfig.h for - * uxTaskGetSystemState() to be available. - * - * uxTaskGetSystemState() populates an TaskStatus_t structure for each task in - * the system. TaskStatus_t structures contain, among other things, members - * for the task handle, task name, task priority, task state, and total amount - * of run time consumed by the task. See the TaskStatus_t structure - * definition in this file for the full member list. - * - * NOTE: This function is intended for debugging use only as its use results in - * the scheduler remaining suspended for an extended period. - * - * @param pxTaskStatusArray A pointer to an array of TaskStatus_t structures. - * The array must contain at least one TaskStatus_t structure for each task - * that is under the control of the RTOS. The number of tasks under the control - * of the RTOS can be determined using the uxTaskGetNumberOfTasks() API function. - * - * @param uxArraySize The size of the array pointed to by the pxTaskStatusArray - * parameter. The size is specified as the number of indexes in the array, or - * the number of TaskStatus_t structures contained in the array, not by the - * number of bytes in the array. - * - * @param pulTotalRunTime If configGENERATE_RUN_TIME_STATS is set to 1 in - * FreeRTOSConfig.h then *pulTotalRunTime is set by uxTaskGetSystemState() to the - * total run time (as defined by the run time stats clock, see - * http://www.freertos.org/rtos-run-time-stats.html) since the target booted. - * pulTotalRunTime can be set to NULL to omit the total run time information. - * - * @return The number of TaskStatus_t structures that were populated by - * uxTaskGetSystemState(). This should equal the number returned by the - * uxTaskGetNumberOfTasks() API function, but will be zero if the value passed - * in the uxArraySize parameter was too small. - * - * Example usage: -
-    // This example demonstrates how a human readable table of run time stats
-	// information is generated from raw data provided by uxTaskGetSystemState().
-	// The human readable table is written to pcWriteBuffer
-	void vTaskGetRunTimeStats( char *pcWriteBuffer )
-	{
-	TaskStatus_t *pxTaskStatusArray;
-	volatile UBaseType_t uxArraySize, x;
-	uint32_t ulTotalRunTime, ulStatsAsPercentage;
-
-		// Make sure the write buffer does not contain a string.
-		*pcWriteBuffer = 0x00;
-
-		// Take a snapshot of the number of tasks in case it changes while this
-		// function is executing.
-		uxArraySize = uxTaskGetNumberOfTasks();
-
-		// Allocate a TaskStatus_t structure for each task.  An array could be
-		// allocated statically at compile time.
-		pxTaskStatusArray = pvPortMalloc( uxArraySize * sizeof( TaskStatus_t ) );
-
-		if( pxTaskStatusArray != NULL )
-		{
-			// Generate raw status information about each task.
-			uxArraySize = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, &ulTotalRunTime );
-
-			// For percentage calculations.
-			ulTotalRunTime /= 100UL;
-
-			// Avoid divide by zero errors.
-			if( ulTotalRunTime > 0 )
-			{
-				// For each populated position in the pxTaskStatusArray array,
-				// format the raw data as human readable ASCII data
-				for( x = 0; x < uxArraySize; x++ )
-				{
-					// What percentage of the total run time has the task used?
-					// This will always be rounded down to the nearest integer.
-					// ulTotalRunTimeDiv100 has already been divided by 100.
-					ulStatsAsPercentage = pxTaskStatusArray[ x ].ulRunTimeCounter / ulTotalRunTime;
-
-					if( ulStatsAsPercentage > 0UL )
-					{
-						sprintf( pcWriteBuffer, "%s\t\t%lu\t\t%lu%%\r\n", pxTaskStatusArray[ x ].pcTaskName, pxTaskStatusArray[ x ].ulRunTimeCounter, ulStatsAsPercentage );
-					}
-					else
-					{
-						// If the percentage is zero here then the task has
-						// consumed less than 1% of the total run time.
-						sprintf( pcWriteBuffer, "%s\t\t%lu\t\t<1%%\r\n", pxTaskStatusArray[ x ].pcTaskName, pxTaskStatusArray[ x ].ulRunTimeCounter );
-					}
-
-					pcWriteBuffer += strlen( ( char * ) pcWriteBuffer );
-				}
-			}
-
-			// The array is no longer needed, free the memory it consumes.
-			vPortFree( pxTaskStatusArray );
-		}
-	}
-	
- */ -UBaseType_t uxTaskGetSystemState( TaskStatus_t * const pxTaskStatusArray, const UBaseType_t uxArraySize, uint32_t * const pulTotalRunTime ) PRIVILEGED_FUNCTION; - -/** - * task. h - *
void vTaskList( char *pcWriteBuffer );
- * - * configUSE_TRACE_FACILITY and configUSE_STATS_FORMATTING_FUNCTIONS must - * both be defined as 1 for this function to be available. See the - * configuration section of the FreeRTOS.org website for more information. - * - * NOTE 1: This function will disable interrupts for its duration. It is - * not intended for normal application runtime use but as a debug aid. - * - * Lists all the current tasks, along with their current state and stack - * usage high water mark. - * - * Tasks are reported as blocked ('B'), ready ('R'), deleted ('D') or - * suspended ('S'). - * - * PLEASE NOTE: - * - * This function is provided for convenience only, and is used by many of the - * demo applications. Do not consider it to be part of the scheduler. - * - * vTaskList() calls uxTaskGetSystemState(), then formats part of the - * uxTaskGetSystemState() output into a human readable table that displays task - * names, states and stack usage. - * - * vTaskList() has a dependency on the sprintf() C library function that might - * bloat the code size, use a lot of stack, and provide different results on - * different platforms. An alternative, tiny, third party, and limited - * functionality implementation of sprintf() is provided in many of the - * FreeRTOS/Demo sub-directories in a file called printf-stdarg.c (note - * printf-stdarg.c does not provide a full snprintf() implementation!). - * - * It is recommended that production systems call uxTaskGetSystemState() - * directly to get access to raw stats data, rather than indirectly through a - * call to vTaskList(). - * - * @param pcWriteBuffer A buffer into which the above mentioned details - * will be written, in ASCII form. This buffer is assumed to be large - * enough to contain the generated report. Approximately 40 bytes per - * task should be sufficient. - * - * \defgroup vTaskList vTaskList - * \ingroup TaskUtils - */ -void vTaskList( char * pcWriteBuffer ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - -/** - * task. h - *
void vTaskGetRunTimeStats( char *pcWriteBuffer );
- * - * configGENERATE_RUN_TIME_STATS and configUSE_STATS_FORMATTING_FUNCTIONS - * must both be defined as 1 for this function to be available. The application - * must also then provide definitions for - * portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() and portGET_RUN_TIME_COUNTER_VALUE() - * to configure a peripheral timer/counter and return the timers current count - * value respectively. The counter should be at least 10 times the frequency of - * the tick count. - * - * NOTE 1: This function will disable interrupts for its duration. It is - * not intended for normal application runtime use but as a debug aid. - * - * Setting configGENERATE_RUN_TIME_STATS to 1 will result in a total - * accumulated execution time being stored for each task. The resolution - * of the accumulated time value depends on the frequency of the timer - * configured by the portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() macro. - * Calling vTaskGetRunTimeStats() writes the total execution time of each - * task into a buffer, both as an absolute count value and as a percentage - * of the total system execution time. - * - * NOTE 2: - * - * This function is provided for convenience only, and is used by many of the - * demo applications. Do not consider it to be part of the scheduler. - * - * vTaskGetRunTimeStats() calls uxTaskGetSystemState(), then formats part of the - * uxTaskGetSystemState() output into a human readable table that displays the - * amount of time each task has spent in the Running state in both absolute and - * percentage terms. - * - * vTaskGetRunTimeStats() has a dependency on the sprintf() C library function - * that might bloat the code size, use a lot of stack, and provide different - * results on different platforms. An alternative, tiny, third party, and - * limited functionality implementation of sprintf() is provided in many of the - * FreeRTOS/Demo sub-directories in a file called printf-stdarg.c (note - * printf-stdarg.c does not provide a full snprintf() implementation!). - * - * It is recommended that production systems call uxTaskGetSystemState() directly - * to get access to raw stats data, rather than indirectly through a call to - * vTaskGetRunTimeStats(). - * - * @param pcWriteBuffer A buffer into which the execution times will be - * written, in ASCII form. This buffer is assumed to be large enough to - * contain the generated report. Approximately 40 bytes per task should - * be sufficient. - * - * \defgroup vTaskGetRunTimeStats vTaskGetRunTimeStats - * \ingroup TaskUtils - */ -void vTaskGetRunTimeStats( char *pcWriteBuffer ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - -/** - * task. h - *
BaseType_t xTaskNotify( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction );
- * - * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this - * function to be available. - * - * When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private - * "notification value", which is a 32-bit unsigned integer (uint32_t). - * - * Events can be sent to a task using an intermediary object. Examples of such - * objects are queues, semaphores, mutexes and event groups. Task notifications - * are a method of sending an event directly to a task without the need for such - * an intermediary object. - * - * A notification sent to a task can optionally perform an action, such as - * update, overwrite or increment the task's notification value. In that way - * task notifications can be used to send data to a task, or be used as light - * weight and fast binary or counting semaphores. - * - * A notification sent to a task will remain pending until it is cleared by the - * task calling xTaskNotifyWait() or ulTaskNotifyTake(). If the task was - * already in the Blocked state to wait for a notification when the notification - * arrives then the task will automatically be removed from the Blocked state - * (unblocked) and the notification cleared. - * - * A task can use xTaskNotifyWait() to [optionally] block to wait for a - * notification to be pending, or ulTaskNotifyTake() to [optionally] block - * to wait for its notification value to have a non-zero value. The task does - * not consume any CPU time while it is in the Blocked state. - * - * See http://www.FreeRTOS.org/RTOS-task-notifications.html for details. - * - * @param xTaskToNotify The handle of the task being notified. The handle to a - * task can be returned from the xTaskCreate() API function used to create the - * task, and the handle of the currently running task can be obtained by calling - * xTaskGetCurrentTaskHandle(). - * - * @param ulValue Data that can be sent with the notification. How the data is - * used depends on the value of the eAction parameter. - * - * @param eAction Specifies how the notification updates the task's notification - * value, if at all. Valid values for eAction are as follows: - * - * eSetBits - - * The task's notification value is bitwise ORed with ulValue. xTaskNofify() - * always returns pdPASS in this case. - * - * eIncrement - - * The task's notification value is incremented. ulValue is not used and - * xTaskNotify() always returns pdPASS in this case. - * - * eSetValueWithOverwrite - - * The task's notification value is set to the value of ulValue, even if the - * task being notified had not yet processed the previous notification (the - * task already had a notification pending). xTaskNotify() always returns - * pdPASS in this case. - * - * eSetValueWithoutOverwrite - - * If the task being notified did not already have a notification pending then - * the task's notification value is set to ulValue and xTaskNotify() will - * return pdPASS. If the task being notified already had a notification - * pending then no action is performed and pdFAIL is returned. - * - * eNoAction - - * The task receives a notification without its notification value being - * updated. ulValue is not used and xTaskNotify() always returns pdPASS in - * this case. - * - * pulPreviousNotificationValue - - * Can be used to pass out the subject task's notification value before any - * bits are modified by the notify function. - * - * @return Dependent on the value of eAction. See the description of the - * eAction parameter. - * - * \defgroup xTaskNotify xTaskNotify - * \ingroup TaskNotifications - */ -BaseType_t xTaskGenericNotify( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotificationValue ) PRIVILEGED_FUNCTION; -#define xTaskNotify( xTaskToNotify, ulValue, eAction ) xTaskGenericNotify( ( xTaskToNotify ), ( ulValue ), ( eAction ), NULL ) -#define xTaskNotifyAndQuery( xTaskToNotify, ulValue, eAction, pulPreviousNotifyValue ) xTaskGenericNotify( ( xTaskToNotify ), ( ulValue ), ( eAction ), ( pulPreviousNotifyValue ) ) - -/** - * task. h - *
BaseType_t xTaskNotifyFromISR( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, BaseType_t *pxHigherPriorityTaskWoken );
- * - * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this - * function to be available. - * - * When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private - * "notification value", which is a 32-bit unsigned integer (uint32_t). - * - * A version of xTaskNotify() that can be used from an interrupt service routine - * (ISR). - * - * Events can be sent to a task using an intermediary object. Examples of such - * objects are queues, semaphores, mutexes and event groups. Task notifications - * are a method of sending an event directly to a task without the need for such - * an intermediary object. - * - * A notification sent to a task can optionally perform an action, such as - * update, overwrite or increment the task's notification value. In that way - * task notifications can be used to send data to a task, or be used as light - * weight and fast binary or counting semaphores. - * - * A notification sent to a task will remain pending until it is cleared by the - * task calling xTaskNotifyWait() or ulTaskNotifyTake(). If the task was - * already in the Blocked state to wait for a notification when the notification - * arrives then the task will automatically be removed from the Blocked state - * (unblocked) and the notification cleared. - * - * A task can use xTaskNotifyWait() to [optionally] block to wait for a - * notification to be pending, or ulTaskNotifyTake() to [optionally] block - * to wait for its notification value to have a non-zero value. The task does - * not consume any CPU time while it is in the Blocked state. - * - * See http://www.FreeRTOS.org/RTOS-task-notifications.html for details. - * - * @param xTaskToNotify The handle of the task being notified. The handle to a - * task can be returned from the xTaskCreate() API function used to create the - * task, and the handle of the currently running task can be obtained by calling - * xTaskGetCurrentTaskHandle(). - * - * @param ulValue Data that can be sent with the notification. How the data is - * used depends on the value of the eAction parameter. - * - * @param eAction Specifies how the notification updates the task's notification - * value, if at all. Valid values for eAction are as follows: - * - * eSetBits - - * The task's notification value is bitwise ORed with ulValue. xTaskNofify() - * always returns pdPASS in this case. - * - * eIncrement - - * The task's notification value is incremented. ulValue is not used and - * xTaskNotify() always returns pdPASS in this case. - * - * eSetValueWithOverwrite - - * The task's notification value is set to the value of ulValue, even if the - * task being notified had not yet processed the previous notification (the - * task already had a notification pending). xTaskNotify() always returns - * pdPASS in this case. - * - * eSetValueWithoutOverwrite - - * If the task being notified did not already have a notification pending then - * the task's notification value is set to ulValue and xTaskNotify() will - * return pdPASS. If the task being notified already had a notification - * pending then no action is performed and pdFAIL is returned. - * - * eNoAction - - * The task receives a notification without its notification value being - * updated. ulValue is not used and xTaskNotify() always returns pdPASS in - * this case. - * - * @param pxHigherPriorityTaskWoken xTaskNotifyFromISR() will set - * *pxHigherPriorityTaskWoken to pdTRUE if sending the notification caused the - * task to which the notification was sent to leave the Blocked state, and the - * unblocked task has a priority higher than the currently running task. If - * xTaskNotifyFromISR() sets this value to pdTRUE then a context switch should - * be requested before the interrupt is exited. How a context switch is - * requested from an ISR is dependent on the port - see the documentation page - * for the port in use. - * - * @return Dependent on the value of eAction. See the description of the - * eAction parameter. - * - * \defgroup xTaskNotify xTaskNotify - * \ingroup TaskNotifications - */ -BaseType_t xTaskGenericNotifyFromISR( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotificationValue, BaseType_t *pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; -#define xTaskNotifyFromISR( xTaskToNotify, ulValue, eAction, pxHigherPriorityTaskWoken ) xTaskGenericNotifyFromISR( ( xTaskToNotify ), ( ulValue ), ( eAction ), NULL, ( pxHigherPriorityTaskWoken ) ) -#define xTaskNotifyAndQueryFromISR( xTaskToNotify, ulValue, eAction, pulPreviousNotificationValue, pxHigherPriorityTaskWoken ) xTaskGenericNotifyFromISR( ( xTaskToNotify ), ( ulValue ), ( eAction ), ( pulPreviousNotificationValue ), ( pxHigherPriorityTaskWoken ) ) - -/** - * task. h - *
BaseType_t xTaskNotifyWait( uint32_t ulBitsToClearOnEntry, uint32_t ulBitsToClearOnExit, uint32_t *pulNotificationValue, TickType_t xTicksToWait );
- * - * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this - * function to be available. - * - * When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private - * "notification value", which is a 32-bit unsigned integer (uint32_t). - * - * Events can be sent to a task using an intermediary object. Examples of such - * objects are queues, semaphores, mutexes and event groups. Task notifications - * are a method of sending an event directly to a task without the need for such - * an intermediary object. - * - * A notification sent to a task can optionally perform an action, such as - * update, overwrite or increment the task's notification value. In that way - * task notifications can be used to send data to a task, or be used as light - * weight and fast binary or counting semaphores. - * - * A notification sent to a task will remain pending until it is cleared by the - * task calling xTaskNotifyWait() or ulTaskNotifyTake(). If the task was - * already in the Blocked state to wait for a notification when the notification - * arrives then the task will automatically be removed from the Blocked state - * (unblocked) and the notification cleared. - * - * A task can use xTaskNotifyWait() to [optionally] block to wait for a - * notification to be pending, or ulTaskNotifyTake() to [optionally] block - * to wait for its notification value to have a non-zero value. The task does - * not consume any CPU time while it is in the Blocked state. - * - * See http://www.FreeRTOS.org/RTOS-task-notifications.html for details. - * - * @param ulBitsToClearOnEntry Bits that are set in ulBitsToClearOnEntry value - * will be cleared in the calling task's notification value before the task - * checks to see if any notifications are pending, and optionally blocks if no - * notifications are pending. Setting ulBitsToClearOnEntry to ULONG_MAX (if - * limits.h is included) or 0xffffffffUL (if limits.h is not included) will have - * the effect of resetting the task's notification value to 0. Setting - * ulBitsToClearOnEntry to 0 will leave the task's notification value unchanged. - * - * @param ulBitsToClearOnExit If a notification is pending or received before - * the calling task exits the xTaskNotifyWait() function then the task's - * notification value (see the xTaskNotify() API function) is passed out using - * the pulNotificationValue parameter. Then any bits that are set in - * ulBitsToClearOnExit will be cleared in the task's notification value (note - * *pulNotificationValue is set before any bits are cleared). Setting - * ulBitsToClearOnExit to ULONG_MAX (if limits.h is included) or 0xffffffffUL - * (if limits.h is not included) will have the effect of resetting the task's - * notification value to 0 before the function exits. Setting - * ulBitsToClearOnExit to 0 will leave the task's notification value unchanged - * when the function exits (in which case the value passed out in - * pulNotificationValue will match the task's notification value). - * - * @param pulNotificationValue Used to pass the task's notification value out - * of the function. Note the value passed out will not be effected by the - * clearing of any bits caused by ulBitsToClearOnExit being non-zero. - * - * @param xTicksToWait The maximum amount of time that the task should wait in - * the Blocked state for a notification to be received, should a notification - * not already be pending when xTaskNotifyWait() was called. The task - * will not consume any processing time while it is in the Blocked state. This - * is specified in kernel ticks, the macro pdMS_TO_TICSK( value_in_ms ) can be - * used to convert a time specified in milliseconds to a time specified in - * ticks. - * - * @return If a notification was received (including notifications that were - * already pending when xTaskNotifyWait was called) then pdPASS is - * returned. Otherwise pdFAIL is returned. - * - * \defgroup xTaskNotifyWait xTaskNotifyWait - * \ingroup TaskNotifications - */ -BaseType_t xTaskNotifyWait( uint32_t ulBitsToClearOnEntry, uint32_t ulBitsToClearOnExit, uint32_t *pulNotificationValue, TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; - -/** - * task. h - *
BaseType_t xTaskNotifyGive( TaskHandle_t xTaskToNotify );
- * - * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this macro - * to be available. - * - * When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private - * "notification value", which is a 32-bit unsigned integer (uint32_t). - * - * Events can be sent to a task using an intermediary object. Examples of such - * objects are queues, semaphores, mutexes and event groups. Task notifications - * are a method of sending an event directly to a task without the need for such - * an intermediary object. - * - * A notification sent to a task can optionally perform an action, such as - * update, overwrite or increment the task's notification value. In that way - * task notifications can be used to send data to a task, or be used as light - * weight and fast binary or counting semaphores. - * - * xTaskNotifyGive() is a helper macro intended for use when task notifications - * are used as light weight and faster binary or counting semaphore equivalents. - * Actual FreeRTOS semaphores are given using the xSemaphoreGive() API function, - * the equivalent action that instead uses a task notification is - * xTaskNotifyGive(). - * - * When task notifications are being used as a binary or counting semaphore - * equivalent then the task being notified should wait for the notification - * using the ulTaskNotificationTake() API function rather than the - * xTaskNotifyWait() API function. - * - * See http://www.FreeRTOS.org/RTOS-task-notifications.html for more details. - * - * @param xTaskToNotify The handle of the task being notified. The handle to a - * task can be returned from the xTaskCreate() API function used to create the - * task, and the handle of the currently running task can be obtained by calling - * xTaskGetCurrentTaskHandle(). - * - * @return xTaskNotifyGive() is a macro that calls xTaskNotify() with the - * eAction parameter set to eIncrement - so pdPASS is always returned. - * - * \defgroup xTaskNotifyGive xTaskNotifyGive - * \ingroup TaskNotifications - */ -#define xTaskNotifyGive( xTaskToNotify ) xTaskGenericNotify( ( xTaskToNotify ), ( 0 ), eIncrement, NULL ) - -/** - * task. h - *
void vTaskNotifyGiveFromISR( TaskHandle_t xTaskHandle, BaseType_t *pxHigherPriorityTaskWoken );
- *
- * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this macro
- * to be available.
- *
- * When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private
- * "notification value", which is a 32-bit unsigned integer (uint32_t).
- *
- * A version of xTaskNotifyGive() that can be called from an interrupt service
- * routine (ISR).
- *
- * Events can be sent to a task using an intermediary object.  Examples of such
- * objects are queues, semaphores, mutexes and event groups.  Task notifications
- * are a method of sending an event directly to a task without the need for such
- * an intermediary object.
- *
- * A notification sent to a task can optionally perform an action, such as
- * update, overwrite or increment the task's notification value.  In that way
- * task notifications can be used to send data to a task, or be used as light
- * weight and fast binary or counting semaphores.
- *
- * vTaskNotifyGiveFromISR() is intended for use when task notifications are
- * used as light weight and faster binary or counting semaphore equivalents.
- * Actual FreeRTOS semaphores are given from an ISR using the
- * xSemaphoreGiveFromISR() API function, the equivalent action that instead uses
- * a task notification is vTaskNotifyGiveFromISR().
- *
- * When task notifications are being used as a binary or counting semaphore
- * equivalent then the task being notified should wait for the notification
- * using the ulTaskNotificationTake() API function rather than the
- * xTaskNotifyWait() API function.
- *
- * See http://www.FreeRTOS.org/RTOS-task-notifications.html for more details.
- *
- * @param xTaskToNotify The handle of the task being notified.  The handle to a
- * task can be returned from the xTaskCreate() API function used to create the
- * task, and the handle of the currently running task can be obtained by calling
- * xTaskGetCurrentTaskHandle().
- *
- * @param pxHigherPriorityTaskWoken  vTaskNotifyGiveFromISR() will set
- * *pxHigherPriorityTaskWoken to pdTRUE if sending the notification caused the
- * task to which the notification was sent to leave the Blocked state, and the
- * unblocked task has a priority higher than the currently running task.  If
- * vTaskNotifyGiveFromISR() sets this value to pdTRUE then a context switch
- * should be requested before the interrupt is exited.  How a context switch is
- * requested from an ISR is dependent on the port - see the documentation page
- * for the port in use.
- *
- * \defgroup xTaskNotifyWait xTaskNotifyWait
- * \ingroup TaskNotifications
- */
-void vTaskNotifyGiveFromISR( TaskHandle_t xTaskToNotify, BaseType_t *pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION;
-
-/**
- * task. h
- * 
uint32_t ulTaskNotifyTake( BaseType_t xClearCountOnExit, TickType_t xTicksToWait );
- * - * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this - * function to be available. - * - * When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private - * "notification value", which is a 32-bit unsigned integer (uint32_t). - * - * Events can be sent to a task using an intermediary object. Examples of such - * objects are queues, semaphores, mutexes and event groups. Task notifications - * are a method of sending an event directly to a task without the need for such - * an intermediary object. - * - * A notification sent to a task can optionally perform an action, such as - * update, overwrite or increment the task's notification value. In that way - * task notifications can be used to send data to a task, or be used as light - * weight and fast binary or counting semaphores. - * - * ulTaskNotifyTake() is intended for use when a task notification is used as a - * faster and lighter weight binary or counting semaphore alternative. Actual - * FreeRTOS semaphores are taken using the xSemaphoreTake() API function, the - * equivalent action that instead uses a task notification is - * ulTaskNotifyTake(). - * - * When a task is using its notification value as a binary or counting semaphore - * other tasks should send notifications to it using the xTaskNotifyGive() - * macro, or xTaskNotify() function with the eAction parameter set to - * eIncrement. - * - * ulTaskNotifyTake() can either clear the task's notification value to - * zero on exit, in which case the notification value acts like a binary - * semaphore, or decrement the task's notification value on exit, in which case - * the notification value acts like a counting semaphore. - * - * A task can use ulTaskNotifyTake() to [optionally] block to wait for a - * the task's notification value to be non-zero. The task does not consume any - * CPU time while it is in the Blocked state. - * - * Where as xTaskNotifyWait() will return when a notification is pending, - * ulTaskNotifyTake() will return when the task's notification value is - * not zero. - * - * See http://www.FreeRTOS.org/RTOS-task-notifications.html for details. - * - * @param xClearCountOnExit if xClearCountOnExit is pdFALSE then the task's - * notification value is decremented when the function exits. In this way the - * notification value acts like a counting semaphore. If xClearCountOnExit is - * not pdFALSE then the task's notification value is cleared to zero when the - * function exits. In this way the notification value acts like a binary - * semaphore. - * - * @param xTicksToWait The maximum amount of time that the task should wait in - * the Blocked state for the task's notification value to be greater than zero, - * should the count not already be greater than zero when - * ulTaskNotifyTake() was called. The task will not consume any processing - * time while it is in the Blocked state. This is specified in kernel ticks, - * the macro pdMS_TO_TICSK( value_in_ms ) can be used to convert a time - * specified in milliseconds to a time specified in ticks. - * - * @return The task's notification count before it is either cleared to zero or - * decremented (see the xClearCountOnExit parameter). - * - * \defgroup ulTaskNotifyTake ulTaskNotifyTake - * \ingroup TaskNotifications - */ -uint32_t ulTaskNotifyTake( BaseType_t xClearCountOnExit, TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; - -/** - * task. h - *
BaseType_t xTaskNotifyStateClear( TaskHandle_t xTask );
- * - * If the notification state of the task referenced by the handle xTask is - * eNotified, then set the task's notification state to eNotWaitingNotification. - * The task's notification value is not altered. Set xTask to NULL to clear the - * notification state of the calling task. - * - * @return pdTRUE if the task's notification state was set to - * eNotWaitingNotification, otherwise pdFALSE. - * \defgroup xTaskNotifyStateClear xTaskNotifyStateClear - * \ingroup TaskNotifications - */ -BaseType_t xTaskNotifyStateClear( TaskHandle_t xTask ); - -/*----------------------------------------------------------- - * SCHEDULER INTERNALS AVAILABLE FOR PORTING PURPOSES - *----------------------------------------------------------*/ - -/* - * THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE. IT IS ONLY - * INTENDED FOR USE WHEN IMPLEMENTING A PORT OF THE SCHEDULER AND IS - * AN INTERFACE WHICH IS FOR THE EXCLUSIVE USE OF THE SCHEDULER. - * - * Called from the real time kernel tick (either preemptive or cooperative), - * this increments the tick count and checks if any tasks that are blocked - * for a finite period required removing from a blocked list and placing on - * a ready list. If a non-zero value is returned then a context switch is - * required because either: - * + A task was removed from a blocked list because its timeout had expired, - * or - * + Time slicing is in use and there is a task of equal priority to the - * currently running task. - */ -BaseType_t xTaskIncrementTick( void ) PRIVILEGED_FUNCTION; - -/* - * THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE. IT IS AN - * INTERFACE WHICH IS FOR THE EXCLUSIVE USE OF THE SCHEDULER. - * - * THIS FUNCTION MUST BE CALLED WITH INTERRUPTS DISABLED. - * - * Removes the calling task from the ready list and places it both - * on the list of tasks waiting for a particular event, and the - * list of delayed tasks. The task will be removed from both lists - * and replaced on the ready list should either the event occur (and - * there be no higher priority tasks waiting on the same event) or - * the delay period expires. - * - * The 'unordered' version replaces the event list item value with the - * xItemValue value, and inserts the list item at the end of the list. - * - * The 'ordered' version uses the existing event list item value (which is the - * owning tasks priority) to insert the list item into the event list is task - * priority order. - * - * @param pxEventList The list containing tasks that are blocked waiting - * for the event to occur. - * - * @param xItemValue The item value to use for the event list item when the - * event list is not ordered by task priority. - * - * @param xTicksToWait The maximum amount of time that the task should wait - * for the event to occur. This is specified in kernel ticks,the constant - * portTICK_PERIOD_MS can be used to convert kernel ticks into a real time - * period. - */ -void vTaskPlaceOnEventList( List_t * const pxEventList, const TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; -void vTaskPlaceOnUnorderedEventList( List_t * pxEventList, const TickType_t xItemValue, const TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; - -/* - * THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE. IT IS AN - * INTERFACE WHICH IS FOR THE EXCLUSIVE USE OF THE SCHEDULER. - * - * THIS FUNCTION MUST BE CALLED WITH INTERRUPTS DISABLED. - * - * This function performs nearly the same function as vTaskPlaceOnEventList(). - * The difference being that this function does not permit tasks to block - * indefinitely, whereas vTaskPlaceOnEventList() does. - * - */ -void vTaskPlaceOnEventListRestricted( List_t * const pxEventList, TickType_t xTicksToWait, const BaseType_t xWaitIndefinitely ) PRIVILEGED_FUNCTION; - -/* - * THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE. IT IS AN - * INTERFACE WHICH IS FOR THE EXCLUSIVE USE OF THE SCHEDULER. - * - * THIS FUNCTION MUST BE CALLED WITH INTERRUPTS DISABLED. - * - * Removes a task from both the specified event list and the list of blocked - * tasks, and places it on a ready queue. - * - * xTaskRemoveFromEventList()/vTaskRemoveFromUnorderedEventList() will be called - * if either an event occurs to unblock a task, or the block timeout period - * expires. - * - * xTaskRemoveFromEventList() is used when the event list is in task priority - * order. It removes the list item from the head of the event list as that will - * have the highest priority owning task of all the tasks on the event list. - * vTaskRemoveFromUnorderedEventList() is used when the event list is not - * ordered and the event list items hold something other than the owning tasks - * priority. In this case the event list item value is updated to the value - * passed in the xItemValue parameter. - * - * @return pdTRUE if the task being removed has a higher priority than the task - * making the call, otherwise pdFALSE. - */ -BaseType_t xTaskRemoveFromEventList( const List_t * const pxEventList ) PRIVILEGED_FUNCTION; -void vTaskRemoveFromUnorderedEventList( ListItem_t * pxEventListItem, const TickType_t xItemValue ) PRIVILEGED_FUNCTION; - -/* - * THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE. IT IS ONLY - * INTENDED FOR USE WHEN IMPLEMENTING A PORT OF THE SCHEDULER AND IS - * AN INTERFACE WHICH IS FOR THE EXCLUSIVE USE OF THE SCHEDULER. - * - * Sets the pointer to the current TCB to the TCB of the highest priority task - * that is ready to run. - */ -void vTaskSwitchContext( void ) PRIVILEGED_FUNCTION; - -/* - * THESE FUNCTIONS MUST NOT BE USED FROM APPLICATION CODE. THEY ARE USED BY - * THE EVENT BITS MODULE. - */ -TickType_t uxTaskResetEventItemValue( void ) PRIVILEGED_FUNCTION; - -/* - * Return the handle of the calling task. - */ -TaskHandle_t xTaskGetCurrentTaskHandle( void ) PRIVILEGED_FUNCTION; - -/* - * Capture the current time status for future reference. - */ -void vTaskSetTimeOutState( TimeOut_t * const pxTimeOut ) PRIVILEGED_FUNCTION; - -/* - * Compare the time status now with that previously captured to see if the - * timeout has expired. - */ -BaseType_t xTaskCheckForTimeOut( TimeOut_t * const pxTimeOut, TickType_t * const pxTicksToWait ) PRIVILEGED_FUNCTION; - -/* - * Shortcut used by the queue implementation to prevent unnecessary call to - * taskYIELD(); - */ -void vTaskMissedYield( void ) PRIVILEGED_FUNCTION; - -/* - * Returns the scheduler state as taskSCHEDULER_RUNNING, - * taskSCHEDULER_NOT_STARTED or taskSCHEDULER_SUSPENDED. - */ -BaseType_t xTaskGetSchedulerState( void ) PRIVILEGED_FUNCTION; - -/* - * Raises the priority of the mutex holder to that of the calling task should - * the mutex holder have a priority less than the calling task. - */ -BaseType_t xTaskPriorityInherit( TaskHandle_t const pxMutexHolder ) PRIVILEGED_FUNCTION; - -/* - * Set the priority of a task back to its proper priority in the case that it - * inherited a higher priority while it was holding a semaphore. - */ -BaseType_t xTaskPriorityDisinherit( TaskHandle_t const pxMutexHolder ) PRIVILEGED_FUNCTION; - -/* - * If a higher priority task attempting to obtain a mutex caused a lower - * priority task to inherit the higher priority task's priority - but the higher - * priority task then timed out without obtaining the mutex, then the lower - * priority task will disinherit the priority again - but only down as far as - * the highest priority task that is still waiting for the mutex (if there were - * more than one task waiting for the mutex). - */ -void vTaskPriorityDisinheritAfterTimeout( TaskHandle_t const pxMutexHolder, UBaseType_t uxHighestPriorityWaitingTask ) PRIVILEGED_FUNCTION; - -/* - * Get the uxTCBNumber assigned to the task referenced by the xTask parameter. - */ -UBaseType_t uxTaskGetTaskNumber( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; - -/* - * Set the uxTaskNumber of the task referenced by the xTask parameter to - * uxHandle. - */ -void vTaskSetTaskNumber( TaskHandle_t xTask, const UBaseType_t uxHandle ) PRIVILEGED_FUNCTION; - -/* - * Only available when configUSE_TICKLESS_IDLE is set to 1. - * If tickless mode is being used, or a low power mode is implemented, then - * the tick interrupt will not execute during idle periods. When this is the - * case, the tick count value maintained by the scheduler needs to be kept up - * to date with the actual execution time by being skipped forward by a time - * equal to the idle period. - */ -void vTaskStepTick( const TickType_t xTicksToJump ) PRIVILEGED_FUNCTION; - -/* - * Only avilable when configUSE_TICKLESS_IDLE is set to 1. - * Provided for use within portSUPPRESS_TICKS_AND_SLEEP() to allow the port - * specific sleep function to determine if it is ok to proceed with the sleep, - * and if it is ok to proceed, if it is ok to sleep indefinitely. - * - * This function is necessary because portSUPPRESS_TICKS_AND_SLEEP() is only - * called with the scheduler suspended, not from within a critical section. It - * is therefore possible for an interrupt to request a context switch between - * portSUPPRESS_TICKS_AND_SLEEP() and the low power mode actually being - * entered. eTaskConfirmSleepModeStatus() should be called from a short - * critical section between the timer being stopped and the sleep mode being - * entered to ensure it is ok to proceed into the sleep mode. - */ -eSleepModeStatus eTaskConfirmSleepModeStatus( void ) PRIVILEGED_FUNCTION; - -/* - * For internal use only. Increment the mutex held count when a mutex is - * taken and return the handle of the task that has taken the mutex. - */ -void *pvTaskIncrementMutexHeldCount( void ) PRIVILEGED_FUNCTION; - -/* - * For internal use only. Same as vTaskSetTimeOutState(), but without a critial - * section. - */ -void vTaskInternalSetTimeOutState( TimeOut_t * const pxTimeOut ) PRIVILEGED_FUNCTION; - - -#ifdef __cplusplus -} -#endif -#endif /* INC_TASK_H */ - - - diff --git a/lib/FreeRTOS/Source/include/timers.h b/lib/FreeRTOS/Source/include/timers.h deleted file mode 100644 index 05eb90fc..00000000 --- a/lib/FreeRTOS/Source/include/timers.h +++ /dev/null @@ -1,1277 +0,0 @@ -/* - * FreeRTOS Kernel V10.0.1 - * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * 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. - * - * http://www.FreeRTOS.org - * http://aws.amazon.com/freertos - * - * 1 tab == 4 spaces! - */ - - -#ifndef TIMERS_H -#define TIMERS_H - -#ifndef INC_FREERTOS_H - #error "include FreeRTOS.h must appear in source files before include timers.h" -#endif - -/*lint -save -e537 This headers are only multiply included if the application code -happens to also be including task.h. */ -#include "task.h" -/*lint -restore */ - -#ifdef __cplusplus -extern "C" { -#endif - -/*----------------------------------------------------------- - * MACROS AND DEFINITIONS - *----------------------------------------------------------*/ - -/* IDs for commands that can be sent/received on the timer queue. These are to -be used solely through the macros that make up the public software timer API, -as defined below. The commands that are sent from interrupts must use the -highest numbers as tmrFIRST_FROM_ISR_COMMAND is used to determine if the task -or interrupt version of the queue send function should be used. */ -#define tmrCOMMAND_EXECUTE_CALLBACK_FROM_ISR ( ( BaseType_t ) -2 ) -#define tmrCOMMAND_EXECUTE_CALLBACK ( ( BaseType_t ) -1 ) -#define tmrCOMMAND_START_DONT_TRACE ( ( BaseType_t ) 0 ) -#define tmrCOMMAND_START ( ( BaseType_t ) 1 ) -#define tmrCOMMAND_RESET ( ( BaseType_t ) 2 ) -#define tmrCOMMAND_STOP ( ( BaseType_t ) 3 ) -#define tmrCOMMAND_CHANGE_PERIOD ( ( BaseType_t ) 4 ) -#define tmrCOMMAND_DELETE ( ( BaseType_t ) 5 ) - -#define tmrFIRST_FROM_ISR_COMMAND ( ( BaseType_t ) 6 ) -#define tmrCOMMAND_START_FROM_ISR ( ( BaseType_t ) 6 ) -#define tmrCOMMAND_RESET_FROM_ISR ( ( BaseType_t ) 7 ) -#define tmrCOMMAND_STOP_FROM_ISR ( ( BaseType_t ) 8 ) -#define tmrCOMMAND_CHANGE_PERIOD_FROM_ISR ( ( BaseType_t ) 9 ) - - -/** - * Type by which software timers are referenced. For example, a call to - * xTimerCreate() returns an TimerHandle_t variable that can then be used to - * reference the subject timer in calls to other software timer API functions - * (for example, xTimerStart(), xTimerReset(), etc.). - */ -typedef void * TimerHandle_t; - -/* - * Defines the prototype to which timer callback functions must conform. - */ -typedef void (*TimerCallbackFunction_t)( TimerHandle_t xTimer ); - -/* - * Defines the prototype to which functions used with the - * xTimerPendFunctionCallFromISR() function must conform. - */ -typedef void (*PendedFunction_t)( void *, uint32_t ); - -/** - * TimerHandle_t xTimerCreate( const char * const pcTimerName, - * TickType_t xTimerPeriodInTicks, - * UBaseType_t uxAutoReload, - * void * pvTimerID, - * TimerCallbackFunction_t pxCallbackFunction ); - * - * Creates a new software timer instance, and returns a handle by which the - * created software timer can be referenced. - * - * Internally, within the FreeRTOS implementation, software timers use a block - * of memory, in which the timer data structure is stored. If a software timer - * is created using xTimerCreate() then the required memory is automatically - * dynamically allocated inside the xTimerCreate() function. (see - * http://www.freertos.org/a00111.html). If a software timer is created using - * xTimerCreateStatic() then the application writer must provide the memory that - * will get used by the software timer. xTimerCreateStatic() therefore allows a - * software timer to be created without using any dynamic memory allocation. - * - * Timers are created in the dormant state. The xTimerStart(), xTimerReset(), - * xTimerStartFromISR(), xTimerResetFromISR(), xTimerChangePeriod() and - * xTimerChangePeriodFromISR() API functions can all be used to transition a - * timer into the active state. - * - * @param pcTimerName A text name that is assigned to the timer. This is done - * purely to assist debugging. The kernel itself only ever references a timer - * by its handle, and never by its name. - * - * @param xTimerPeriodInTicks The timer period. The time is defined in tick - * periods so the constant portTICK_PERIOD_MS can be used to convert a time that - * has been specified in milliseconds. For example, if the timer must expire - * after 100 ticks, then xTimerPeriodInTicks should be set to 100. - * Alternatively, if the timer must expire after 500ms, then xPeriod can be set - * to ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ is less than or - * equal to 1000. - * - * @param uxAutoReload If uxAutoReload is set to pdTRUE then the timer will - * expire repeatedly with a frequency set by the xTimerPeriodInTicks parameter. - * If uxAutoReload is set to pdFALSE then the timer will be a one-shot timer and - * enter the dormant state after it expires. - * - * @param pvTimerID An identifier that is assigned to the timer being created. - * Typically this would be used in the timer callback function to identify which - * timer expired when the same callback function is assigned to more than one - * timer. - * - * @param pxCallbackFunction The function to call when the timer expires. - * Callback functions must have the prototype defined by TimerCallbackFunction_t, - * which is "void vCallbackFunction( TimerHandle_t xTimer );". - * - * @return If the timer is successfully created then a handle to the newly - * created timer is returned. If the timer cannot be created (because either - * there is insufficient FreeRTOS heap remaining to allocate the timer - * structures, or the timer period was set to 0) then NULL is returned. - * - * Example usage: - * @verbatim - * #define NUM_TIMERS 5 - * - * // An array to hold handles to the created timers. - * TimerHandle_t xTimers[ NUM_TIMERS ]; - * - * // An array to hold a count of the number of times each timer expires. - * int32_t lExpireCounters[ NUM_TIMERS ] = { 0 }; - * - * // Define a callback function that will be used by multiple timer instances. - * // The callback function does nothing but count the number of times the - * // associated timer expires, and stop the timer once the timer has expired - * // 10 times. - * void vTimerCallback( TimerHandle_t pxTimer ) - * { - * int32_t lArrayIndex; - * const int32_t xMaxExpiryCountBeforeStopping = 10; - * - * // Optionally do something if the pxTimer parameter is NULL. - * configASSERT( pxTimer ); - * - * // Which timer expired? - * lArrayIndex = ( int32_t ) pvTimerGetTimerID( pxTimer ); - * - * // Increment the number of times that pxTimer has expired. - * lExpireCounters[ lArrayIndex ] += 1; - * - * // If the timer has expired 10 times then stop it from running. - * if( lExpireCounters[ lArrayIndex ] == xMaxExpiryCountBeforeStopping ) - * { - * // Do not use a block time if calling a timer API function from a - * // timer callback function, as doing so could cause a deadlock! - * xTimerStop( pxTimer, 0 ); - * } - * } - * - * void main( void ) - * { - * int32_t x; - * - * // Create then start some timers. Starting the timers before the scheduler - * // has been started means the timers will start running immediately that - * // the scheduler starts. - * for( x = 0; x < NUM_TIMERS; x++ ) - * { - * xTimers[ x ] = xTimerCreate( "Timer", // Just a text name, not used by the kernel. - * ( 100 * x ), // The timer period in ticks. - * pdTRUE, // The timers will auto-reload themselves when they expire. - * ( void * ) x, // Assign each timer a unique id equal to its array index. - * vTimerCallback // Each timer calls the same callback when it expires. - * ); - * - * if( xTimers[ x ] == NULL ) - * { - * // The timer was not created. - * } - * else - * { - * // Start the timer. No block time is specified, and even if one was - * // it would be ignored because the scheduler has not yet been - * // started. - * if( xTimerStart( xTimers[ x ], 0 ) != pdPASS ) - * { - * // The timer could not be set into the Active state. - * } - * } - * } - * - * // ... - * // Create tasks here. - * // ... - * - * // Starting the scheduler will start the timers running as they have already - * // been set into the active state. - * vTaskStartScheduler(); - * - * // Should not reach here. - * for( ;; ); - * } - * @endverbatim - */ -#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - TimerHandle_t xTimerCreate( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - const TickType_t xTimerPeriodInTicks, - const UBaseType_t uxAutoReload, - void * const pvTimerID, - TimerCallbackFunction_t pxCallbackFunction ) PRIVILEGED_FUNCTION; -#endif - -/** - * TimerHandle_t xTimerCreateStatic(const char * const pcTimerName, - * TickType_t xTimerPeriodInTicks, - * UBaseType_t uxAutoReload, - * void * pvTimerID, - * TimerCallbackFunction_t pxCallbackFunction, - * StaticTimer_t *pxTimerBuffer ); - * - * Creates a new software timer instance, and returns a handle by which the - * created software timer can be referenced. - * - * Internally, within the FreeRTOS implementation, software timers use a block - * of memory, in which the timer data structure is stored. If a software timer - * is created using xTimerCreate() then the required memory is automatically - * dynamically allocated inside the xTimerCreate() function. (see - * http://www.freertos.org/a00111.html). If a software timer is created using - * xTimerCreateStatic() then the application writer must provide the memory that - * will get used by the software timer. xTimerCreateStatic() therefore allows a - * software timer to be created without using any dynamic memory allocation. - * - * Timers are created in the dormant state. The xTimerStart(), xTimerReset(), - * xTimerStartFromISR(), xTimerResetFromISR(), xTimerChangePeriod() and - * xTimerChangePeriodFromISR() API functions can all be used to transition a - * timer into the active state. - * - * @param pcTimerName A text name that is assigned to the timer. This is done - * purely to assist debugging. The kernel itself only ever references a timer - * by its handle, and never by its name. - * - * @param xTimerPeriodInTicks The timer period. The time is defined in tick - * periods so the constant portTICK_PERIOD_MS can be used to convert a time that - * has been specified in milliseconds. For example, if the timer must expire - * after 100 ticks, then xTimerPeriodInTicks should be set to 100. - * Alternatively, if the timer must expire after 500ms, then xPeriod can be set - * to ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ is less than or - * equal to 1000. - * - * @param uxAutoReload If uxAutoReload is set to pdTRUE then the timer will - * expire repeatedly with a frequency set by the xTimerPeriodInTicks parameter. - * If uxAutoReload is set to pdFALSE then the timer will be a one-shot timer and - * enter the dormant state after it expires. - * - * @param pvTimerID An identifier that is assigned to the timer being created. - * Typically this would be used in the timer callback function to identify which - * timer expired when the same callback function is assigned to more than one - * timer. - * - * @param pxCallbackFunction The function to call when the timer expires. - * Callback functions must have the prototype defined by TimerCallbackFunction_t, - * which is "void vCallbackFunction( TimerHandle_t xTimer );". - * - * @param pxTimerBuffer Must point to a variable of type StaticTimer_t, which - * will be then be used to hold the software timer's data structures, removing - * the need for the memory to be allocated dynamically. - * - * @return If the timer is created then a handle to the created timer is - * returned. If pxTimerBuffer was NULL then NULL is returned. - * - * Example usage: - * @verbatim - * - * // The buffer used to hold the software timer's data structure. - * static StaticTimer_t xTimerBuffer; - * - * // A variable that will be incremented by the software timer's callback - * // function. - * UBaseType_t uxVariableToIncrement = 0; - * - * // A software timer callback function that increments a variable passed to - * // it when the software timer was created. After the 5th increment the - * // callback function stops the software timer. - * static void prvTimerCallback( TimerHandle_t xExpiredTimer ) - * { - * UBaseType_t *puxVariableToIncrement; - * BaseType_t xReturned; - * - * // Obtain the address of the variable to increment from the timer ID. - * puxVariableToIncrement = ( UBaseType_t * ) pvTimerGetTimerID( xExpiredTimer ); - * - * // Increment the variable to show the timer callback has executed. - * ( *puxVariableToIncrement )++; - * - * // If this callback has executed the required number of times, stop the - * // timer. - * if( *puxVariableToIncrement == 5 ) - * { - * // This is called from a timer callback so must not block. - * xTimerStop( xExpiredTimer, staticDONT_BLOCK ); - * } - * } - * - * - * void main( void ) - * { - * // Create the software time. xTimerCreateStatic() has an extra parameter - * // than the normal xTimerCreate() API function. The parameter is a pointer - * // to the StaticTimer_t structure that will hold the software timer - * // structure. If the parameter is passed as NULL then the structure will be - * // allocated dynamically, just as if xTimerCreate() had been called. - * xTimer = xTimerCreateStatic( "T1", // Text name for the task. Helps debugging only. Not used by FreeRTOS. - * xTimerPeriod, // The period of the timer in ticks. - * pdTRUE, // This is an auto-reload timer. - * ( void * ) &uxVariableToIncrement, // A variable incremented by the software timer's callback function - * prvTimerCallback, // The function to execute when the timer expires. - * &xTimerBuffer ); // The buffer that will hold the software timer structure. - * - * // The scheduler has not started yet so a block time is not used. - * xReturned = xTimerStart( xTimer, 0 ); - * - * // ... - * // Create tasks here. - * // ... - * - * // Starting the scheduler will start the timers running as they have already - * // been set into the active state. - * vTaskStartScheduler(); - * - * // Should not reach here. - * for( ;; ); - * } - * @endverbatim - */ -#if( configSUPPORT_STATIC_ALLOCATION == 1 ) - TimerHandle_t xTimerCreateStatic( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - const TickType_t xTimerPeriodInTicks, - const UBaseType_t uxAutoReload, - void * const pvTimerID, - TimerCallbackFunction_t pxCallbackFunction, - StaticTimer_t *pxTimerBuffer ) PRIVILEGED_FUNCTION; -#endif /* configSUPPORT_STATIC_ALLOCATION */ - -/** - * void *pvTimerGetTimerID( TimerHandle_t xTimer ); - * - * Returns the ID assigned to the timer. - * - * IDs are assigned to timers using the pvTimerID parameter of the call to - * xTimerCreated() that was used to create the timer, and by calling the - * vTimerSetTimerID() API function. - * - * If the same callback function is assigned to multiple timers then the timer - * ID can be used as time specific (timer local) storage. - * - * @param xTimer The timer being queried. - * - * @return The ID assigned to the timer being queried. - * - * Example usage: - * - * See the xTimerCreate() API function example usage scenario. - */ -void *pvTimerGetTimerID( const TimerHandle_t xTimer ) PRIVILEGED_FUNCTION; - -/** - * void vTimerSetTimerID( TimerHandle_t xTimer, void *pvNewID ); - * - * Sets the ID assigned to the timer. - * - * IDs are assigned to timers using the pvTimerID parameter of the call to - * xTimerCreated() that was used to create the timer. - * - * If the same callback function is assigned to multiple timers then the timer - * ID can be used as time specific (timer local) storage. - * - * @param xTimer The timer being updated. - * - * @param pvNewID The ID to assign to the timer. - * - * Example usage: - * - * See the xTimerCreate() API function example usage scenario. - */ -void vTimerSetTimerID( TimerHandle_t xTimer, void *pvNewID ) PRIVILEGED_FUNCTION; - -/** - * BaseType_t xTimerIsTimerActive( TimerHandle_t xTimer ); - * - * Queries a timer to see if it is active or dormant. - * - * A timer will be dormant if: - * 1) It has been created but not started, or - * 2) It is an expired one-shot timer that has not been restarted. - * - * Timers are created in the dormant state. The xTimerStart(), xTimerReset(), - * xTimerStartFromISR(), xTimerResetFromISR(), xTimerChangePeriod() and - * xTimerChangePeriodFromISR() API functions can all be used to transition a timer into the - * active state. - * - * @param xTimer The timer being queried. - * - * @return pdFALSE will be returned if the timer is dormant. A value other than - * pdFALSE will be returned if the timer is active. - * - * Example usage: - * @verbatim - * // This function assumes xTimer has already been created. - * void vAFunction( TimerHandle_t xTimer ) - * { - * if( xTimerIsTimerActive( xTimer ) != pdFALSE ) // or more simply and equivalently "if( xTimerIsTimerActive( xTimer ) )" - * { - * // xTimer is active, do something. - * } - * else - * { - * // xTimer is not active, do something else. - * } - * } - * @endverbatim - */ -BaseType_t xTimerIsTimerActive( TimerHandle_t xTimer ) PRIVILEGED_FUNCTION; - -/** - * TaskHandle_t xTimerGetTimerDaemonTaskHandle( void ); - * - * Simply returns the handle of the timer service/daemon task. It it not valid - * to call xTimerGetTimerDaemonTaskHandle() before the scheduler has been started. - */ -TaskHandle_t xTimerGetTimerDaemonTaskHandle( void ) PRIVILEGED_FUNCTION; - -/** - * BaseType_t xTimerStart( TimerHandle_t xTimer, TickType_t xTicksToWait ); - * - * Timer functionality is provided by a timer service/daemon task. Many of the - * public FreeRTOS timer API functions send commands to the timer service task - * through a queue called the timer command queue. The timer command queue is - * private to the kernel itself and is not directly accessible to application - * code. The length of the timer command queue is set by the - * configTIMER_QUEUE_LENGTH configuration constant. - * - * xTimerStart() starts a timer that was previously created using the - * xTimerCreate() API function. If the timer had already been started and was - * already in the active state, then xTimerStart() has equivalent functionality - * to the xTimerReset() API function. - * - * Starting a timer ensures the timer is in the active state. If the timer - * is not stopped, deleted, or reset in the mean time, the callback function - * associated with the timer will get called 'n' ticks after xTimerStart() was - * called, where 'n' is the timers defined period. - * - * It is valid to call xTimerStart() before the scheduler has been started, but - * when this is done the timer will not actually start until the scheduler is - * started, and the timers expiry time will be relative to when the scheduler is - * started, not relative to when xTimerStart() was called. - * - * The configUSE_TIMERS configuration constant must be set to 1 for xTimerStart() - * to be available. - * - * @param xTimer The handle of the timer being started/restarted. - * - * @param xTicksToWait Specifies the time, in ticks, that the calling task should - * be held in the Blocked state to wait for the start command to be successfully - * sent to the timer command queue, should the queue already be full when - * xTimerStart() was called. xTicksToWait is ignored if xTimerStart() is called - * before the scheduler is started. - * - * @return pdFAIL will be returned if the start command could not be sent to - * the timer command queue even after xTicksToWait ticks had passed. pdPASS will - * be returned if the command was successfully sent to the timer command queue. - * When the command is actually processed will depend on the priority of the - * timer service/daemon task relative to other tasks in the system, although the - * timers expiry time is relative to when xTimerStart() is actually called. The - * timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY - * configuration constant. - * - * Example usage: - * - * See the xTimerCreate() API function example usage scenario. - * - */ -#define xTimerStart( xTimer, xTicksToWait ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_START, ( xTaskGetTickCount() ), NULL, ( xTicksToWait ) ) - -/** - * BaseType_t xTimerStop( TimerHandle_t xTimer, TickType_t xTicksToWait ); - * - * Timer functionality is provided by a timer service/daemon task. Many of the - * public FreeRTOS timer API functions send commands to the timer service task - * through a queue called the timer command queue. The timer command queue is - * private to the kernel itself and is not directly accessible to application - * code. The length of the timer command queue is set by the - * configTIMER_QUEUE_LENGTH configuration constant. - * - * xTimerStop() stops a timer that was previously started using either of the - * The xTimerStart(), xTimerReset(), xTimerStartFromISR(), xTimerResetFromISR(), - * xTimerChangePeriod() or xTimerChangePeriodFromISR() API functions. - * - * Stopping a timer ensures the timer is not in the active state. - * - * The configUSE_TIMERS configuration constant must be set to 1 for xTimerStop() - * to be available. - * - * @param xTimer The handle of the timer being stopped. - * - * @param xTicksToWait Specifies the time, in ticks, that the calling task should - * be held in the Blocked state to wait for the stop command to be successfully - * sent to the timer command queue, should the queue already be full when - * xTimerStop() was called. xTicksToWait is ignored if xTimerStop() is called - * before the scheduler is started. - * - * @return pdFAIL will be returned if the stop command could not be sent to - * the timer command queue even after xTicksToWait ticks had passed. pdPASS will - * be returned if the command was successfully sent to the timer command queue. - * When the command is actually processed will depend on the priority of the - * timer service/daemon task relative to other tasks in the system. The timer - * service/daemon task priority is set by the configTIMER_TASK_PRIORITY - * configuration constant. - * - * Example usage: - * - * See the xTimerCreate() API function example usage scenario. - * - */ -#define xTimerStop( xTimer, xTicksToWait ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_STOP, 0U, NULL, ( xTicksToWait ) ) - -/** - * BaseType_t xTimerChangePeriod( TimerHandle_t xTimer, - * TickType_t xNewPeriod, - * TickType_t xTicksToWait ); - * - * Timer functionality is provided by a timer service/daemon task. Many of the - * public FreeRTOS timer API functions send commands to the timer service task - * through a queue called the timer command queue. The timer command queue is - * private to the kernel itself and is not directly accessible to application - * code. The length of the timer command queue is set by the - * configTIMER_QUEUE_LENGTH configuration constant. - * - * xTimerChangePeriod() changes the period of a timer that was previously - * created using the xTimerCreate() API function. - * - * xTimerChangePeriod() can be called to change the period of an active or - * dormant state timer. - * - * The configUSE_TIMERS configuration constant must be set to 1 for - * xTimerChangePeriod() to be available. - * - * @param xTimer The handle of the timer that is having its period changed. - * - * @param xNewPeriod The new period for xTimer. Timer periods are specified in - * tick periods, so the constant portTICK_PERIOD_MS can be used to convert a time - * that has been specified in milliseconds. For example, if the timer must - * expire after 100 ticks, then xNewPeriod should be set to 100. Alternatively, - * if the timer must expire after 500ms, then xNewPeriod can be set to - * ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ is less than - * or equal to 1000. - * - * @param xTicksToWait Specifies the time, in ticks, that the calling task should - * be held in the Blocked state to wait for the change period command to be - * successfully sent to the timer command queue, should the queue already be - * full when xTimerChangePeriod() was called. xTicksToWait is ignored if - * xTimerChangePeriod() is called before the scheduler is started. - * - * @return pdFAIL will be returned if the change period command could not be - * sent to the timer command queue even after xTicksToWait ticks had passed. - * pdPASS will be returned if the command was successfully sent to the timer - * command queue. When the command is actually processed will depend on the - * priority of the timer service/daemon task relative to other tasks in the - * system. The timer service/daemon task priority is set by the - * configTIMER_TASK_PRIORITY configuration constant. - * - * Example usage: - * @verbatim - * // This function assumes xTimer has already been created. If the timer - * // referenced by xTimer is already active when it is called, then the timer - * // is deleted. If the timer referenced by xTimer is not active when it is - * // called, then the period of the timer is set to 500ms and the timer is - * // started. - * void vAFunction( TimerHandle_t xTimer ) - * { - * if( xTimerIsTimerActive( xTimer ) != pdFALSE ) // or more simply and equivalently "if( xTimerIsTimerActive( xTimer ) )" - * { - * // xTimer is already active - delete it. - * xTimerDelete( xTimer ); - * } - * else - * { - * // xTimer is not active, change its period to 500ms. This will also - * // cause the timer to start. Block for a maximum of 100 ticks if the - * // change period command cannot immediately be sent to the timer - * // command queue. - * if( xTimerChangePeriod( xTimer, 500 / portTICK_PERIOD_MS, 100 ) == pdPASS ) - * { - * // The command was successfully sent. - * } - * else - * { - * // The command could not be sent, even after waiting for 100 ticks - * // to pass. Take appropriate action here. - * } - * } - * } - * @endverbatim - */ - #define xTimerChangePeriod( xTimer, xNewPeriod, xTicksToWait ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_CHANGE_PERIOD, ( xNewPeriod ), NULL, ( xTicksToWait ) ) - -/** - * BaseType_t xTimerDelete( TimerHandle_t xTimer, TickType_t xTicksToWait ); - * - * Timer functionality is provided by a timer service/daemon task. Many of the - * public FreeRTOS timer API functions send commands to the timer service task - * through a queue called the timer command queue. The timer command queue is - * private to the kernel itself and is not directly accessible to application - * code. The length of the timer command queue is set by the - * configTIMER_QUEUE_LENGTH configuration constant. - * - * xTimerDelete() deletes a timer that was previously created using the - * xTimerCreate() API function. - * - * The configUSE_TIMERS configuration constant must be set to 1 for - * xTimerDelete() to be available. - * - * @param xTimer The handle of the timer being deleted. - * - * @param xTicksToWait Specifies the time, in ticks, that the calling task should - * be held in the Blocked state to wait for the delete command to be - * successfully sent to the timer command queue, should the queue already be - * full when xTimerDelete() was called. xTicksToWait is ignored if xTimerDelete() - * is called before the scheduler is started. - * - * @return pdFAIL will be returned if the delete command could not be sent to - * the timer command queue even after xTicksToWait ticks had passed. pdPASS will - * be returned if the command was successfully sent to the timer command queue. - * When the command is actually processed will depend on the priority of the - * timer service/daemon task relative to other tasks in the system. The timer - * service/daemon task priority is set by the configTIMER_TASK_PRIORITY - * configuration constant. - * - * Example usage: - * - * See the xTimerChangePeriod() API function example usage scenario. - */ -#define xTimerDelete( xTimer, xTicksToWait ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_DELETE, 0U, NULL, ( xTicksToWait ) ) - -/** - * BaseType_t xTimerReset( TimerHandle_t xTimer, TickType_t xTicksToWait ); - * - * Timer functionality is provided by a timer service/daemon task. Many of the - * public FreeRTOS timer API functions send commands to the timer service task - * through a queue called the timer command queue. The timer command queue is - * private to the kernel itself and is not directly accessible to application - * code. The length of the timer command queue is set by the - * configTIMER_QUEUE_LENGTH configuration constant. - * - * xTimerReset() re-starts a timer that was previously created using the - * xTimerCreate() API function. If the timer had already been started and was - * already in the active state, then xTimerReset() will cause the timer to - * re-evaluate its expiry time so that it is relative to when xTimerReset() was - * called. If the timer was in the dormant state then xTimerReset() has - * equivalent functionality to the xTimerStart() API function. - * - * Resetting a timer ensures the timer is in the active state. If the timer - * is not stopped, deleted, or reset in the mean time, the callback function - * associated with the timer will get called 'n' ticks after xTimerReset() was - * called, where 'n' is the timers defined period. - * - * It is valid to call xTimerReset() before the scheduler has been started, but - * when this is done the timer will not actually start until the scheduler is - * started, and the timers expiry time will be relative to when the scheduler is - * started, not relative to when xTimerReset() was called. - * - * The configUSE_TIMERS configuration constant must be set to 1 for xTimerReset() - * to be available. - * - * @param xTimer The handle of the timer being reset/started/restarted. - * - * @param xTicksToWait Specifies the time, in ticks, that the calling task should - * be held in the Blocked state to wait for the reset command to be successfully - * sent to the timer command queue, should the queue already be full when - * xTimerReset() was called. xTicksToWait is ignored if xTimerReset() is called - * before the scheduler is started. - * - * @return pdFAIL will be returned if the reset command could not be sent to - * the timer command queue even after xTicksToWait ticks had passed. pdPASS will - * be returned if the command was successfully sent to the timer command queue. - * When the command is actually processed will depend on the priority of the - * timer service/daemon task relative to other tasks in the system, although the - * timers expiry time is relative to when xTimerStart() is actually called. The - * timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY - * configuration constant. - * - * Example usage: - * @verbatim - * // When a key is pressed, an LCD back-light is switched on. If 5 seconds pass - * // without a key being pressed, then the LCD back-light is switched off. In - * // this case, the timer is a one-shot timer. - * - * TimerHandle_t xBacklightTimer = NULL; - * - * // The callback function assigned to the one-shot timer. In this case the - * // parameter is not used. - * void vBacklightTimerCallback( TimerHandle_t pxTimer ) - * { - * // The timer expired, therefore 5 seconds must have passed since a key - * // was pressed. Switch off the LCD back-light. - * vSetBacklightState( BACKLIGHT_OFF ); - * } - * - * // The key press event handler. - * void vKeyPressEventHandler( char cKey ) - * { - * // Ensure the LCD back-light is on, then reset the timer that is - * // responsible for turning the back-light off after 5 seconds of - * // key inactivity. Wait 10 ticks for the command to be successfully sent - * // if it cannot be sent immediately. - * vSetBacklightState( BACKLIGHT_ON ); - * if( xTimerReset( xBacklightTimer, 100 ) != pdPASS ) - * { - * // The reset command was not executed successfully. Take appropriate - * // action here. - * } - * - * // Perform the rest of the key processing here. - * } - * - * void main( void ) - * { - * int32_t x; - * - * // Create then start the one-shot timer that is responsible for turning - * // the back-light off if no keys are pressed within a 5 second period. - * xBacklightTimer = xTimerCreate( "BacklightTimer", // Just a text name, not used by the kernel. - * ( 5000 / portTICK_PERIOD_MS), // The timer period in ticks. - * pdFALSE, // The timer is a one-shot timer. - * 0, // The id is not used by the callback so can take any value. - * vBacklightTimerCallback // The callback function that switches the LCD back-light off. - * ); - * - * if( xBacklightTimer == NULL ) - * { - * // The timer was not created. - * } - * else - * { - * // Start the timer. No block time is specified, and even if one was - * // it would be ignored because the scheduler has not yet been - * // started. - * if( xTimerStart( xBacklightTimer, 0 ) != pdPASS ) - * { - * // The timer could not be set into the Active state. - * } - * } - * - * // ... - * // Create tasks here. - * // ... - * - * // Starting the scheduler will start the timer running as it has already - * // been set into the active state. - * vTaskStartScheduler(); - * - * // Should not reach here. - * for( ;; ); - * } - * @endverbatim - */ -#define xTimerReset( xTimer, xTicksToWait ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_RESET, ( xTaskGetTickCount() ), NULL, ( xTicksToWait ) ) - -/** - * BaseType_t xTimerStartFromISR( TimerHandle_t xTimer, - * BaseType_t *pxHigherPriorityTaskWoken ); - * - * A version of xTimerStart() that can be called from an interrupt service - * routine. - * - * @param xTimer The handle of the timer being started/restarted. - * - * @param pxHigherPriorityTaskWoken The timer service/daemon task spends most - * of its time in the Blocked state, waiting for messages to arrive on the timer - * command queue. Calling xTimerStartFromISR() writes a message to the timer - * command queue, so has the potential to transition the timer service/daemon - * task out of the Blocked state. If calling xTimerStartFromISR() causes the - * timer service/daemon task to leave the Blocked state, and the timer service/ - * daemon task has a priority equal to or greater than the currently executing - * task (the task that was interrupted), then *pxHigherPriorityTaskWoken will - * get set to pdTRUE internally within the xTimerStartFromISR() function. If - * xTimerStartFromISR() sets this value to pdTRUE then a context switch should - * be performed before the interrupt exits. - * - * @return pdFAIL will be returned if the start command could not be sent to - * the timer command queue. pdPASS will be returned if the command was - * successfully sent to the timer command queue. When the command is actually - * processed will depend on the priority of the timer service/daemon task - * relative to other tasks in the system, although the timers expiry time is - * relative to when xTimerStartFromISR() is actually called. The timer - * service/daemon task priority is set by the configTIMER_TASK_PRIORITY - * configuration constant. - * - * Example usage: - * @verbatim - * // This scenario assumes xBacklightTimer has already been created. When a - * // key is pressed, an LCD back-light is switched on. If 5 seconds pass - * // without a key being pressed, then the LCD back-light is switched off. In - * // this case, the timer is a one-shot timer, and unlike the example given for - * // the xTimerReset() function, the key press event handler is an interrupt - * // service routine. - * - * // The callback function assigned to the one-shot timer. In this case the - * // parameter is not used. - * void vBacklightTimerCallback( TimerHandle_t pxTimer ) - * { - * // The timer expired, therefore 5 seconds must have passed since a key - * // was pressed. Switch off the LCD back-light. - * vSetBacklightState( BACKLIGHT_OFF ); - * } - * - * // The key press interrupt service routine. - * void vKeyPressEventInterruptHandler( void ) - * { - * BaseType_t xHigherPriorityTaskWoken = pdFALSE; - * - * // Ensure the LCD back-light is on, then restart the timer that is - * // responsible for turning the back-light off after 5 seconds of - * // key inactivity. This is an interrupt service routine so can only - * // call FreeRTOS API functions that end in "FromISR". - * vSetBacklightState( BACKLIGHT_ON ); - * - * // xTimerStartFromISR() or xTimerResetFromISR() could be called here - * // as both cause the timer to re-calculate its expiry time. - * // xHigherPriorityTaskWoken was initialised to pdFALSE when it was - * // declared (in this function). - * if( xTimerStartFromISR( xBacklightTimer, &xHigherPriorityTaskWoken ) != pdPASS ) - * { - * // The start command was not executed successfully. Take appropriate - * // action here. - * } - * - * // Perform the rest of the key processing here. - * - * // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch - * // should be performed. The syntax required to perform a context switch - * // from inside an ISR varies from port to port, and from compiler to - * // compiler. Inspect the demos for the port you are using to find the - * // actual syntax required. - * if( xHigherPriorityTaskWoken != pdFALSE ) - * { - * // Call the interrupt safe yield function here (actual function - * // depends on the FreeRTOS port being used). - * } - * } - * @endverbatim - */ -#define xTimerStartFromISR( xTimer, pxHigherPriorityTaskWoken ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_START_FROM_ISR, ( xTaskGetTickCountFromISR() ), ( pxHigherPriorityTaskWoken ), 0U ) - -/** - * BaseType_t xTimerStopFromISR( TimerHandle_t xTimer, - * BaseType_t *pxHigherPriorityTaskWoken ); - * - * A version of xTimerStop() that can be called from an interrupt service - * routine. - * - * @param xTimer The handle of the timer being stopped. - * - * @param pxHigherPriorityTaskWoken The timer service/daemon task spends most - * of its time in the Blocked state, waiting for messages to arrive on the timer - * command queue. Calling xTimerStopFromISR() writes a message to the timer - * command queue, so has the potential to transition the timer service/daemon - * task out of the Blocked state. If calling xTimerStopFromISR() causes the - * timer service/daemon task to leave the Blocked state, and the timer service/ - * daemon task has a priority equal to or greater than the currently executing - * task (the task that was interrupted), then *pxHigherPriorityTaskWoken will - * get set to pdTRUE internally within the xTimerStopFromISR() function. If - * xTimerStopFromISR() sets this value to pdTRUE then a context switch should - * be performed before the interrupt exits. - * - * @return pdFAIL will be returned if the stop command could not be sent to - * the timer command queue. pdPASS will be returned if the command was - * successfully sent to the timer command queue. When the command is actually - * processed will depend on the priority of the timer service/daemon task - * relative to other tasks in the system. The timer service/daemon task - * priority is set by the configTIMER_TASK_PRIORITY configuration constant. - * - * Example usage: - * @verbatim - * // This scenario assumes xTimer has already been created and started. When - * // an interrupt occurs, the timer should be simply stopped. - * - * // The interrupt service routine that stops the timer. - * void vAnExampleInterruptServiceRoutine( void ) - * { - * BaseType_t xHigherPriorityTaskWoken = pdFALSE; - * - * // The interrupt has occurred - simply stop the timer. - * // xHigherPriorityTaskWoken was set to pdFALSE where it was defined - * // (within this function). As this is an interrupt service routine, only - * // FreeRTOS API functions that end in "FromISR" can be used. - * if( xTimerStopFromISR( xTimer, &xHigherPriorityTaskWoken ) != pdPASS ) - * { - * // The stop command was not executed successfully. Take appropriate - * // action here. - * } - * - * // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch - * // should be performed. The syntax required to perform a context switch - * // from inside an ISR varies from port to port, and from compiler to - * // compiler. Inspect the demos for the port you are using to find the - * // actual syntax required. - * if( xHigherPriorityTaskWoken != pdFALSE ) - * { - * // Call the interrupt safe yield function here (actual function - * // depends on the FreeRTOS port being used). - * } - * } - * @endverbatim - */ -#define xTimerStopFromISR( xTimer, pxHigherPriorityTaskWoken ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_STOP_FROM_ISR, 0, ( pxHigherPriorityTaskWoken ), 0U ) - -/** - * BaseType_t xTimerChangePeriodFromISR( TimerHandle_t xTimer, - * TickType_t xNewPeriod, - * BaseType_t *pxHigherPriorityTaskWoken ); - * - * A version of xTimerChangePeriod() that can be called from an interrupt - * service routine. - * - * @param xTimer The handle of the timer that is having its period changed. - * - * @param xNewPeriod The new period for xTimer. Timer periods are specified in - * tick periods, so the constant portTICK_PERIOD_MS can be used to convert a time - * that has been specified in milliseconds. For example, if the timer must - * expire after 100 ticks, then xNewPeriod should be set to 100. Alternatively, - * if the timer must expire after 500ms, then xNewPeriod can be set to - * ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ is less than - * or equal to 1000. - * - * @param pxHigherPriorityTaskWoken The timer service/daemon task spends most - * of its time in the Blocked state, waiting for messages to arrive on the timer - * command queue. Calling xTimerChangePeriodFromISR() writes a message to the - * timer command queue, so has the potential to transition the timer service/ - * daemon task out of the Blocked state. If calling xTimerChangePeriodFromISR() - * causes the timer service/daemon task to leave the Blocked state, and the - * timer service/daemon task has a priority equal to or greater than the - * currently executing task (the task that was interrupted), then - * *pxHigherPriorityTaskWoken will get set to pdTRUE internally within the - * xTimerChangePeriodFromISR() function. If xTimerChangePeriodFromISR() sets - * this value to pdTRUE then a context switch should be performed before the - * interrupt exits. - * - * @return pdFAIL will be returned if the command to change the timers period - * could not be sent to the timer command queue. pdPASS will be returned if the - * command was successfully sent to the timer command queue. When the command - * is actually processed will depend on the priority of the timer service/daemon - * task relative to other tasks in the system. The timer service/daemon task - * priority is set by the configTIMER_TASK_PRIORITY configuration constant. - * - * Example usage: - * @verbatim - * // This scenario assumes xTimer has already been created and started. When - * // an interrupt occurs, the period of xTimer should be changed to 500ms. - * - * // The interrupt service routine that changes the period of xTimer. - * void vAnExampleInterruptServiceRoutine( void ) - * { - * BaseType_t xHigherPriorityTaskWoken = pdFALSE; - * - * // The interrupt has occurred - change the period of xTimer to 500ms. - * // xHigherPriorityTaskWoken was set to pdFALSE where it was defined - * // (within this function). As this is an interrupt service routine, only - * // FreeRTOS API functions that end in "FromISR" can be used. - * if( xTimerChangePeriodFromISR( xTimer, &xHigherPriorityTaskWoken ) != pdPASS ) - * { - * // The command to change the timers period was not executed - * // successfully. Take appropriate action here. - * } - * - * // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch - * // should be performed. The syntax required to perform a context switch - * // from inside an ISR varies from port to port, and from compiler to - * // compiler. Inspect the demos for the port you are using to find the - * // actual syntax required. - * if( xHigherPriorityTaskWoken != pdFALSE ) - * { - * // Call the interrupt safe yield function here (actual function - * // depends on the FreeRTOS port being used). - * } - * } - * @endverbatim - */ -#define xTimerChangePeriodFromISR( xTimer, xNewPeriod, pxHigherPriorityTaskWoken ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_CHANGE_PERIOD_FROM_ISR, ( xNewPeriod ), ( pxHigherPriorityTaskWoken ), 0U ) - -/** - * BaseType_t xTimerResetFromISR( TimerHandle_t xTimer, - * BaseType_t *pxHigherPriorityTaskWoken ); - * - * A version of xTimerReset() that can be called from an interrupt service - * routine. - * - * @param xTimer The handle of the timer that is to be started, reset, or - * restarted. - * - * @param pxHigherPriorityTaskWoken The timer service/daemon task spends most - * of its time in the Blocked state, waiting for messages to arrive on the timer - * command queue. Calling xTimerResetFromISR() writes a message to the timer - * command queue, so has the potential to transition the timer service/daemon - * task out of the Blocked state. If calling xTimerResetFromISR() causes the - * timer service/daemon task to leave the Blocked state, and the timer service/ - * daemon task has a priority equal to or greater than the currently executing - * task (the task that was interrupted), then *pxHigherPriorityTaskWoken will - * get set to pdTRUE internally within the xTimerResetFromISR() function. If - * xTimerResetFromISR() sets this value to pdTRUE then a context switch should - * be performed before the interrupt exits. - * - * @return pdFAIL will be returned if the reset command could not be sent to - * the timer command queue. pdPASS will be returned if the command was - * successfully sent to the timer command queue. When the command is actually - * processed will depend on the priority of the timer service/daemon task - * relative to other tasks in the system, although the timers expiry time is - * relative to when xTimerResetFromISR() is actually called. The timer service/daemon - * task priority is set by the configTIMER_TASK_PRIORITY configuration constant. - * - * Example usage: - * @verbatim - * // This scenario assumes xBacklightTimer has already been created. When a - * // key is pressed, an LCD back-light is switched on. If 5 seconds pass - * // without a key being pressed, then the LCD back-light is switched off. In - * // this case, the timer is a one-shot timer, and unlike the example given for - * // the xTimerReset() function, the key press event handler is an interrupt - * // service routine. - * - * // The callback function assigned to the one-shot timer. In this case the - * // parameter is not used. - * void vBacklightTimerCallback( TimerHandle_t pxTimer ) - * { - * // The timer expired, therefore 5 seconds must have passed since a key - * // was pressed. Switch off the LCD back-light. - * vSetBacklightState( BACKLIGHT_OFF ); - * } - * - * // The key press interrupt service routine. - * void vKeyPressEventInterruptHandler( void ) - * { - * BaseType_t xHigherPriorityTaskWoken = pdFALSE; - * - * // Ensure the LCD back-light is on, then reset the timer that is - * // responsible for turning the back-light off after 5 seconds of - * // key inactivity. This is an interrupt service routine so can only - * // call FreeRTOS API functions that end in "FromISR". - * vSetBacklightState( BACKLIGHT_ON ); - * - * // xTimerStartFromISR() or xTimerResetFromISR() could be called here - * // as both cause the timer to re-calculate its expiry time. - * // xHigherPriorityTaskWoken was initialised to pdFALSE when it was - * // declared (in this function). - * if( xTimerResetFromISR( xBacklightTimer, &xHigherPriorityTaskWoken ) != pdPASS ) - * { - * // The reset command was not executed successfully. Take appropriate - * // action here. - * } - * - * // Perform the rest of the key processing here. - * - * // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch - * // should be performed. The syntax required to perform a context switch - * // from inside an ISR varies from port to port, and from compiler to - * // compiler. Inspect the demos for the port you are using to find the - * // actual syntax required. - * if( xHigherPriorityTaskWoken != pdFALSE ) - * { - * // Call the interrupt safe yield function here (actual function - * // depends on the FreeRTOS port being used). - * } - * } - * @endverbatim - */ -#define xTimerResetFromISR( xTimer, pxHigherPriorityTaskWoken ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_RESET_FROM_ISR, ( xTaskGetTickCountFromISR() ), ( pxHigherPriorityTaskWoken ), 0U ) - - -/** - * BaseType_t xTimerPendFunctionCallFromISR( PendedFunction_t xFunctionToPend, - * void *pvParameter1, - * uint32_t ulParameter2, - * BaseType_t *pxHigherPriorityTaskWoken ); - * - * - * Used from application interrupt service routines to defer the execution of a - * function to the RTOS daemon task (the timer service task, hence this function - * is implemented in timers.c and is prefixed with 'Timer'). - * - * Ideally an interrupt service routine (ISR) is kept as short as possible, but - * sometimes an ISR either has a lot of processing to do, or needs to perform - * processing that is not deterministic. In these cases - * xTimerPendFunctionCallFromISR() can be used to defer processing of a function - * to the RTOS daemon task. - * - * A mechanism is provided that allows the interrupt to return directly to the - * task that will subsequently execute the pended callback function. This - * allows the callback function to execute contiguously in time with the - * interrupt - just as if the callback had executed in the interrupt itself. - * - * @param xFunctionToPend The function to execute from the timer service/ - * daemon task. The function must conform to the PendedFunction_t - * prototype. - * - * @param pvParameter1 The value of the callback function's first parameter. - * The parameter has a void * type to allow it to be used to pass any type. - * For example, unsigned longs can be cast to a void *, or the void * can be - * used to point to a structure. - * - * @param ulParameter2 The value of the callback function's second parameter. - * - * @param pxHigherPriorityTaskWoken As mentioned above, calling this function - * will result in a message being sent to the timer daemon task. If the - * priority of the timer daemon task (which is set using - * configTIMER_TASK_PRIORITY in FreeRTOSConfig.h) is higher than the priority of - * the currently running task (the task the interrupt interrupted) then - * *pxHigherPriorityTaskWoken will be set to pdTRUE within - * xTimerPendFunctionCallFromISR(), indicating that a context switch should be - * requested before the interrupt exits. For that reason - * *pxHigherPriorityTaskWoken must be initialised to pdFALSE. See the - * example code below. - * - * @return pdPASS is returned if the message was successfully sent to the - * timer daemon task, otherwise pdFALSE is returned. - * - * Example usage: - * @verbatim - * - * // The callback function that will execute in the context of the daemon task. - * // Note callback functions must all use this same prototype. - * void vProcessInterface( void *pvParameter1, uint32_t ulParameter2 ) - * { - * BaseType_t xInterfaceToService; - * - * // The interface that requires servicing is passed in the second - * // parameter. The first parameter is not used in this case. - * xInterfaceToService = ( BaseType_t ) ulParameter2; - * - * // ...Perform the processing here... - * } - * - * // An ISR that receives data packets from multiple interfaces - * void vAnISR( void ) - * { - * BaseType_t xInterfaceToService, xHigherPriorityTaskWoken; - * - * // Query the hardware to determine which interface needs processing. - * xInterfaceToService = prvCheckInterfaces(); - * - * // The actual processing is to be deferred to a task. Request the - * // vProcessInterface() callback function is executed, passing in the - * // number of the interface that needs processing. The interface to - * // service is passed in the second parameter. The first parameter is - * // not used in this case. - * xHigherPriorityTaskWoken = pdFALSE; - * xTimerPendFunctionCallFromISR( vProcessInterface, NULL, ( uint32_t ) xInterfaceToService, &xHigherPriorityTaskWoken ); - * - * // If xHigherPriorityTaskWoken is now set to pdTRUE then a context - * // switch should be requested. The macro used is port specific and will - * // be either portYIELD_FROM_ISR() or portEND_SWITCHING_ISR() - refer to - * // the documentation page for the port being used. - * portYIELD_FROM_ISR( xHigherPriorityTaskWoken ); - * - * } - * @endverbatim - */ -BaseType_t xTimerPendFunctionCallFromISR( PendedFunction_t xFunctionToPend, void *pvParameter1, uint32_t ulParameter2, BaseType_t *pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; - - /** - * BaseType_t xTimerPendFunctionCall( PendedFunction_t xFunctionToPend, - * void *pvParameter1, - * uint32_t ulParameter2, - * TickType_t xTicksToWait ); - * - * - * Used to defer the execution of a function to the RTOS daemon task (the timer - * service task, hence this function is implemented in timers.c and is prefixed - * with 'Timer'). - * - * @param xFunctionToPend The function to execute from the timer service/ - * daemon task. The function must conform to the PendedFunction_t - * prototype. - * - * @param pvParameter1 The value of the callback function's first parameter. - * The parameter has a void * type to allow it to be used to pass any type. - * For example, unsigned longs can be cast to a void *, or the void * can be - * used to point to a structure. - * - * @param ulParameter2 The value of the callback function's second parameter. - * - * @param xTicksToWait Calling this function will result in a message being - * sent to the timer daemon task on a queue. xTicksToWait is the amount of - * time the calling task should remain in the Blocked state (so not using any - * processing time) for space to become available on the timer queue if the - * queue is found to be full. - * - * @return pdPASS is returned if the message was successfully sent to the - * timer daemon task, otherwise pdFALSE is returned. - * - */ -BaseType_t xTimerPendFunctionCall( PendedFunction_t xFunctionToPend, void *pvParameter1, uint32_t ulParameter2, TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; - -/** - * const char * const pcTimerGetName( TimerHandle_t xTimer ); - * - * Returns the name that was assigned to a timer when the timer was created. - * - * @param xTimer The handle of the timer being queried. - * - * @return The name assigned to the timer specified by the xTimer parameter. - */ -const char * pcTimerGetName( TimerHandle_t xTimer ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - -/** - * TickType_t xTimerGetPeriod( TimerHandle_t xTimer ); - * - * Returns the period of a timer. - * - * @param xTimer The handle of the timer being queried. - * - * @return The period of the timer in ticks. - */ -TickType_t xTimerGetPeriod( TimerHandle_t xTimer ) PRIVILEGED_FUNCTION; - -/** -* TickType_t xTimerGetExpiryTime( TimerHandle_t xTimer ); -* -* Returns the time in ticks at which the timer will expire. If this is less -* than the current tick count then the expiry time has overflowed from the -* current time. -* -* @param xTimer The handle of the timer being queried. -* -* @return If the timer is running then the time in ticks at which the timer -* will next expire is returned. If the timer is not running then the return -* value is undefined. -*/ -TickType_t xTimerGetExpiryTime( TimerHandle_t xTimer ) PRIVILEGED_FUNCTION; - -/* - * Functions beyond this part are not part of the public API and are intended - * for use by the kernel only. - */ -BaseType_t xTimerCreateTimerTask( void ) PRIVILEGED_FUNCTION; -BaseType_t xTimerGenericCommand( TimerHandle_t xTimer, const BaseType_t xCommandID, const TickType_t xOptionalValue, BaseType_t * const pxHigherPriorityTaskWoken, const TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; - -#if( configUSE_TRACE_FACILITY == 1 ) - void vTimerSetTimerNumber( TimerHandle_t xTimer, UBaseType_t uxTimerNumber ) PRIVILEGED_FUNCTION; - UBaseType_t uxTimerGetTimerNumber( TimerHandle_t xTimer ) PRIVILEGED_FUNCTION; -#endif - -#ifdef __cplusplus -} -#endif -#endif /* TIMERS_H */ - - - diff --git a/lib/FreeRTOS/Source/list.c b/lib/FreeRTOS/Source/list.c deleted file mode 100644 index 758523a3..00000000 --- a/lib/FreeRTOS/Source/list.c +++ /dev/null @@ -1,198 +0,0 @@ -/* - * FreeRTOS Kernel V10.0.1 - * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * 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. - * - * http://www.FreeRTOS.org - * http://aws.amazon.com/freertos - * - * 1 tab == 4 spaces! - */ - - -#include -#include "FreeRTOS.h" -#include "list.h" - -/*----------------------------------------------------------- - * PUBLIC LIST API documented in list.h - *----------------------------------------------------------*/ - -void vListInitialise( List_t * const pxList ) -{ - /* The list structure contains a list item which is used to mark the - end of the list. To initialise the list the list end is inserted - as the only list entry. */ - pxList->pxIndex = ( ListItem_t * ) &( pxList->xListEnd ); /*lint !e826 !e740 The mini list structure is used as the list end to save RAM. This is checked and valid. */ - - /* The list end value is the highest possible value in the list to - ensure it remains at the end of the list. */ - pxList->xListEnd.xItemValue = portMAX_DELAY; - - /* The list end next and previous pointers point to itself so we know - when the list is empty. */ - pxList->xListEnd.pxNext = ( ListItem_t * ) &( pxList->xListEnd ); /*lint !e826 !e740 The mini list structure is used as the list end to save RAM. This is checked and valid. */ - pxList->xListEnd.pxPrevious = ( ListItem_t * ) &( pxList->xListEnd );/*lint !e826 !e740 The mini list structure is used as the list end to save RAM. This is checked and valid. */ - - pxList->uxNumberOfItems = ( UBaseType_t ) 0U; - - /* Write known values into the list if - configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ - listSET_LIST_INTEGRITY_CHECK_1_VALUE( pxList ); - listSET_LIST_INTEGRITY_CHECK_2_VALUE( pxList ); -} -/*-----------------------------------------------------------*/ - -void vListInitialiseItem( ListItem_t * const pxItem ) -{ - /* Make sure the list item is not recorded as being on a list. */ - pxItem->pvContainer = NULL; - - /* Write known values into the list item if - configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ - listSET_FIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ); - listSET_SECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ); -} -/*-----------------------------------------------------------*/ - -void vListInsertEnd( List_t * const pxList, ListItem_t * const pxNewListItem ) -{ -ListItem_t * const pxIndex = pxList->pxIndex; - - /* Only effective when configASSERT() is also defined, these tests may catch - the list data structures being overwritten in memory. They will not catch - data errors caused by incorrect configuration or use of FreeRTOS. */ - listTEST_LIST_INTEGRITY( pxList ); - listTEST_LIST_ITEM_INTEGRITY( pxNewListItem ); - - /* Insert a new list item into pxList, but rather than sort the list, - makes the new list item the last item to be removed by a call to - listGET_OWNER_OF_NEXT_ENTRY(). */ - pxNewListItem->pxNext = pxIndex; - pxNewListItem->pxPrevious = pxIndex->pxPrevious; - - /* Only used during decision coverage testing. */ - mtCOVERAGE_TEST_DELAY(); - - pxIndex->pxPrevious->pxNext = pxNewListItem; - pxIndex->pxPrevious = pxNewListItem; - - /* Remember which list the item is in. */ - pxNewListItem->pvContainer = ( void * ) pxList; - - ( pxList->uxNumberOfItems )++; -} -/*-----------------------------------------------------------*/ - -void vListInsert( List_t * const pxList, ListItem_t * const pxNewListItem ) -{ -ListItem_t *pxIterator; -const TickType_t xValueOfInsertion = pxNewListItem->xItemValue; - - /* Only effective when configASSERT() is also defined, these tests may catch - the list data structures being overwritten in memory. They will not catch - data errors caused by incorrect configuration or use of FreeRTOS. */ - listTEST_LIST_INTEGRITY( pxList ); - listTEST_LIST_ITEM_INTEGRITY( pxNewListItem ); - - /* Insert the new list item into the list, sorted in xItemValue order. - - If the list already contains a list item with the same item value then the - new list item should be placed after it. This ensures that TCB's which are - stored in ready lists (all of which have the same xItemValue value) get a - share of the CPU. However, if the xItemValue is the same as the back marker - the iteration loop below will not end. Therefore the value is checked - first, and the algorithm slightly modified if necessary. */ - if( xValueOfInsertion == portMAX_DELAY ) - { - pxIterator = pxList->xListEnd.pxPrevious; - } - else - { - /* *** NOTE *********************************************************** - If you find your application is crashing here then likely causes are - listed below. In addition see http://www.freertos.org/FAQHelp.html for - more tips, and ensure configASSERT() is defined! - http://www.freertos.org/a00110.html#configASSERT - - 1) Stack overflow - - see http://www.freertos.org/Stacks-and-stack-overflow-checking.html - 2) Incorrect interrupt priority assignment, especially on Cortex-M - parts where numerically high priority values denote low actual - interrupt priorities, which can seem counter intuitive. See - http://www.freertos.org/RTOS-Cortex-M3-M4.html and the definition - of configMAX_SYSCALL_INTERRUPT_PRIORITY on - http://www.freertos.org/a00110.html - 3) Calling an API function from within a critical section or when - the scheduler is suspended, or calling an API function that does - not end in "FromISR" from an interrupt. - 4) Using a queue or semaphore before it has been initialised or - before the scheduler has been started (are interrupts firing - before vTaskStartScheduler() has been called?). - **********************************************************************/ - - for( pxIterator = ( ListItem_t * ) &( pxList->xListEnd ); pxIterator->pxNext->xItemValue <= xValueOfInsertion; pxIterator = pxIterator->pxNext ) /*lint !e826 !e740 The mini list structure is used as the list end to save RAM. This is checked and valid. */ - { - /* There is nothing to do here, just iterating to the wanted - insertion position. */ - } - } - - pxNewListItem->pxNext = pxIterator->pxNext; - pxNewListItem->pxNext->pxPrevious = pxNewListItem; - pxNewListItem->pxPrevious = pxIterator; - pxIterator->pxNext = pxNewListItem; - - /* Remember which list the item is in. This allows fast removal of the - item later. */ - pxNewListItem->pvContainer = ( void * ) pxList; - - ( pxList->uxNumberOfItems )++; -} -/*-----------------------------------------------------------*/ - -UBaseType_t uxListRemove( ListItem_t * const pxItemToRemove ) -{ -/* The list item knows which list it is in. Obtain the list from the list -item. */ -List_t * const pxList = ( List_t * ) pxItemToRemove->pvContainer; - - pxItemToRemove->pxNext->pxPrevious = pxItemToRemove->pxPrevious; - pxItemToRemove->pxPrevious->pxNext = pxItemToRemove->pxNext; - - /* Only used during decision coverage testing. */ - mtCOVERAGE_TEST_DELAY(); - - /* Make sure the index is left pointing to a valid item. */ - if( pxList->pxIndex == pxItemToRemove ) - { - pxList->pxIndex = pxItemToRemove->pxPrevious; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - pxItemToRemove->pvContainer = NULL; - ( pxList->uxNumberOfItems )--; - - return pxList->uxNumberOfItems; -} -/*-----------------------------------------------------------*/ - diff --git a/lib/FreeRTOS/Source/portable/Common/mpu_wrappers.c b/lib/FreeRTOS/Source/portable/Common/mpu_wrappers.c deleted file mode 100644 index 6872b743..00000000 --- a/lib/FreeRTOS/Source/portable/Common/mpu_wrappers.c +++ /dev/null @@ -1,1290 +0,0 @@ -/* - * FreeRTOS Kernel V10.0.1 - * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * 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. - * - * http://www.FreeRTOS.org - * http://aws.amazon.com/freertos - * - * 1 tab == 4 spaces! - */ - -/* - * Implementation of the wrapper functions used to raise the processor privilege - * before calling a standard FreeRTOS API function. - */ - -/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining -all the API functions to use the MPU wrappers. That should only be done when -task.h is included from an application file. */ -#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE - -/* Scheduler includes. */ -#include "FreeRTOS.h" -#include "task.h" -#include "queue.h" -#include "timers.h" -#include "event_groups.h" -#include "stream_buffer.h" -#include "mpu_prototypes.h" - -#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE - -/* - * Checks to see if being called from the context of an unprivileged task, and - * if so raises the privilege level and returns false - otherwise does nothing - * other than return true. - */ -extern BaseType_t xPortRaisePrivilege( void ); - -/*-----------------------------------------------------------*/ - -#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - BaseType_t MPU_xTaskCreateRestricted( const TaskParameters_t * const pxTaskDefinition, TaskHandle_t *pxCreatedTask ) - { - BaseType_t xReturn; - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xTaskCreateRestricted( pxTaskDefinition, pxCreatedTask ); - vPortResetPrivilege( xRunningPrivileged ); - return xReturn; - } -#endif /* conifgSUPPORT_DYNAMIC_ALLOCATION */ -/*-----------------------------------------------------------*/ - -#if( configSUPPORT_STATIC_ALLOCATION == 1 ) - BaseType_t MPU_xTaskCreateRestrictedStatic( const TaskParameters_t * const pxTaskDefinition, TaskHandle_t *pxCreatedTask ) - { - BaseType_t xReturn; - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xTaskCreateRestrictedStatic( pxTaskDefinition, pxCreatedTask ); - vPortResetPrivilege( xRunningPrivileged ); - return xReturn; - } -#endif /* conifgSUPPORT_DYNAMIC_ALLOCATION */ -/*-----------------------------------------------------------*/ - -#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - BaseType_t MPU_xTaskCreate( TaskFunction_t pvTaskCode, const char * const pcName, uint16_t usStackDepth, void *pvParameters, UBaseType_t uxPriority, TaskHandle_t *pxCreatedTask ) - { - BaseType_t xReturn; - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xTaskCreate( pvTaskCode, pcName, usStackDepth, pvParameters, uxPriority, pxCreatedTask ); - vPortResetPrivilege( xRunningPrivileged ); - return xReturn; - } -#endif /* configSUPPORT_DYNAMIC_ALLOCATION */ -/*-----------------------------------------------------------*/ - -#if( configSUPPORT_STATIC_ALLOCATION == 1 ) - TaskHandle_t MPU_xTaskCreateStatic( TaskFunction_t pxTaskCode, const char * const pcName, const uint32_t ulStackDepth, void * const pvParameters, UBaseType_t uxPriority, StackType_t * const puxStackBuffer, StaticTask_t * const pxTaskBuffer ) - { - TaskHandle_t xReturn; - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xTaskCreateStatic( pxTaskCode, pcName, ulStackDepth, pvParameters, uxPriority, puxStackBuffer, pxTaskBuffer ); - vPortResetPrivilege( xRunningPrivileged ); - return xReturn; - } -#endif /* configSUPPORT_STATIC_ALLOCATION */ -/*-----------------------------------------------------------*/ - -void MPU_vTaskAllocateMPURegions( TaskHandle_t xTask, const MemoryRegion_t * const xRegions ) -{ -BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - vTaskAllocateMPURegions( xTask, xRegions ); - vPortResetPrivilege( xRunningPrivileged ); -} -/*-----------------------------------------------------------*/ - -#if ( INCLUDE_vTaskDelete == 1 ) - void MPU_vTaskDelete( TaskHandle_t pxTaskToDelete ) - { - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - vTaskDelete( pxTaskToDelete ); - vPortResetPrivilege( xRunningPrivileged ); - } -#endif -/*-----------------------------------------------------------*/ - -#if ( INCLUDE_vTaskDelayUntil == 1 ) - void MPU_vTaskDelayUntil( TickType_t * const pxPreviousWakeTime, TickType_t xTimeIncrement ) - { - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - vTaskDelayUntil( pxPreviousWakeTime, xTimeIncrement ); - vPortResetPrivilege( xRunningPrivileged ); - } -#endif -/*-----------------------------------------------------------*/ - -#if ( INCLUDE_xTaskAbortDelay == 1 ) - BaseType_t MPU_xTaskAbortDelay( TaskHandle_t xTask ) - { - BaseType_t xReturn; - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xTaskAbortDelay( xTask ); - vPortResetPrivilege( xRunningPrivileged ); - return xReturn; - } -#endif -/*-----------------------------------------------------------*/ - -#if ( INCLUDE_vTaskDelay == 1 ) - void MPU_vTaskDelay( TickType_t xTicksToDelay ) - { - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - vTaskDelay( xTicksToDelay ); - vPortResetPrivilege( xRunningPrivileged ); - } -#endif -/*-----------------------------------------------------------*/ - -#if ( INCLUDE_uxTaskPriorityGet == 1 ) - UBaseType_t MPU_uxTaskPriorityGet( TaskHandle_t pxTask ) - { - UBaseType_t uxReturn; - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - uxReturn = uxTaskPriorityGet( pxTask ); - vPortResetPrivilege( xRunningPrivileged ); - return uxReturn; - } -#endif -/*-----------------------------------------------------------*/ - -#if ( INCLUDE_vTaskPrioritySet == 1 ) - void MPU_vTaskPrioritySet( TaskHandle_t pxTask, UBaseType_t uxNewPriority ) - { - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - vTaskPrioritySet( pxTask, uxNewPriority ); - vPortResetPrivilege( xRunningPrivileged ); - } -#endif -/*-----------------------------------------------------------*/ - -#if ( INCLUDE_eTaskGetState == 1 ) - eTaskState MPU_eTaskGetState( TaskHandle_t pxTask ) - { - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - eTaskState eReturn; - - eReturn = eTaskGetState( pxTask ); - vPortResetPrivilege( xRunningPrivileged ); - return eReturn; - } -#endif -/*-----------------------------------------------------------*/ - -#if( configUSE_TRACE_FACILITY == 1 ) - void MPU_vTaskGetInfo( TaskHandle_t xTask, TaskStatus_t *pxTaskStatus, BaseType_t xGetFreeStackSpace, eTaskState eState ) - { - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - vTaskGetInfo( xTask, pxTaskStatus, xGetFreeStackSpace, eState ); - vPortResetPrivilege( xRunningPrivileged ); - } -#endif -/*-----------------------------------------------------------*/ - -#if ( INCLUDE_xTaskGetIdleTaskHandle == 1 ) - TaskHandle_t MPU_xTaskGetIdleTaskHandle( void ) - { - TaskHandle_t xReturn; - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xTaskGetIdleTaskHandle(); - vPortResetPrivilege( xRunningPrivileged ); - return xReturn; - } -#endif -/*-----------------------------------------------------------*/ - -#if ( INCLUDE_vTaskSuspend == 1 ) - void MPU_vTaskSuspend( TaskHandle_t pxTaskToSuspend ) - { - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - vTaskSuspend( pxTaskToSuspend ); - vPortResetPrivilege( xRunningPrivileged ); - } -#endif -/*-----------------------------------------------------------*/ - -#if ( INCLUDE_vTaskSuspend == 1 ) - void MPU_vTaskResume( TaskHandle_t pxTaskToResume ) - { - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - vTaskResume( pxTaskToResume ); - vPortResetPrivilege( xRunningPrivileged ); - } -#endif -/*-----------------------------------------------------------*/ - -void MPU_vTaskSuspendAll( void ) -{ -BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - vTaskSuspendAll(); - vPortResetPrivilege( xRunningPrivileged ); -} -/*-----------------------------------------------------------*/ - -BaseType_t MPU_xTaskResumeAll( void ) -{ -BaseType_t xReturn; -BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xTaskResumeAll(); - vPortResetPrivilege( xRunningPrivileged ); - return xReturn; -} -/*-----------------------------------------------------------*/ - -TickType_t MPU_xTaskGetTickCount( void ) -{ -TickType_t xReturn; -BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xTaskGetTickCount(); - vPortResetPrivilege( xRunningPrivileged ); - return xReturn; -} -/*-----------------------------------------------------------*/ - -UBaseType_t MPU_uxTaskGetNumberOfTasks( void ) -{ -UBaseType_t uxReturn; -BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - uxReturn = uxTaskGetNumberOfTasks(); - vPortResetPrivilege( xRunningPrivileged ); - return uxReturn; -} -/*-----------------------------------------------------------*/ - -char * MPU_pcTaskGetName( TaskHandle_t xTaskToQuery ) -{ -char *pcReturn; -BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - pcReturn = pcTaskGetName( xTaskToQuery ); - vPortResetPrivilege( xRunningPrivileged ); - return pcReturn; -} -/*-----------------------------------------------------------*/ - -#if ( INCLUDE_xTaskGetHandle == 1 ) - TaskHandle_t MPU_xTaskGetHandle( const char *pcNameToQuery ) - { - TaskHandle_t xReturn; - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xTaskGetHandle( pcNameToQuery ); - vPortResetPrivilege( xRunningPrivileged ); - return xReturn; - } -#endif -/*-----------------------------------------------------------*/ - -#if ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) - void MPU_vTaskList( char *pcWriteBuffer ) - { - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - vTaskList( pcWriteBuffer ); - vPortResetPrivilege( xRunningPrivileged ); - } -#endif -/*-----------------------------------------------------------*/ - -#if ( ( configGENERATE_RUN_TIME_STATS == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) - void MPU_vTaskGetRunTimeStats( char *pcWriteBuffer ) - { - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - vTaskGetRunTimeStats( pcWriteBuffer ); - vPortResetPrivilege( xRunningPrivileged ); - } -#endif -/*-----------------------------------------------------------*/ - -#if ( configUSE_APPLICATION_TASK_TAG == 1 ) - void MPU_vTaskSetApplicationTaskTag( TaskHandle_t xTask, TaskHookFunction_t pxTagValue ) - { - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - vTaskSetApplicationTaskTag( xTask, pxTagValue ); - vPortResetPrivilege( xRunningPrivileged ); - } -#endif -/*-----------------------------------------------------------*/ - -#if ( configUSE_APPLICATION_TASK_TAG == 1 ) - TaskHookFunction_t MPU_xTaskGetApplicationTaskTag( TaskHandle_t xTask ) - { - TaskHookFunction_t xReturn; - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xTaskGetApplicationTaskTag( xTask ); - vPortResetPrivilege( xRunningPrivileged ); - return xReturn; - } -#endif -/*-----------------------------------------------------------*/ - -#if ( configNUM_THREAD_LOCAL_STORAGE_POINTERS != 0 ) - void MPU_vTaskSetThreadLocalStoragePointer( TaskHandle_t xTaskToSet, BaseType_t xIndex, void *pvValue ) - { - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - vTaskSetThreadLocalStoragePointer( xTaskToSet, xIndex, pvValue ); - vPortResetPrivilege( xRunningPrivileged ); - } -#endif -/*-----------------------------------------------------------*/ - -#if ( configNUM_THREAD_LOCAL_STORAGE_POINTERS != 0 ) - void *MPU_pvTaskGetThreadLocalStoragePointer( TaskHandle_t xTaskToQuery, BaseType_t xIndex ) - { - void *pvReturn; - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - pvReturn = pvTaskGetThreadLocalStoragePointer( xTaskToQuery, xIndex ); - vPortResetPrivilege( xRunningPrivileged ); - return pvReturn; - } -#endif -/*-----------------------------------------------------------*/ - -#if ( configUSE_APPLICATION_TASK_TAG == 1 ) - BaseType_t MPU_xTaskCallApplicationTaskHook( TaskHandle_t xTask, void *pvParameter ) - { - BaseType_t xReturn; - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xTaskCallApplicationTaskHook( xTask, pvParameter ); - vPortResetPrivilege( xRunningPrivileged ); - return xReturn; - } -#endif -/*-----------------------------------------------------------*/ - -#if ( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t MPU_uxTaskGetSystemState( TaskStatus_t *pxTaskStatusArray, UBaseType_t uxArraySize, uint32_t *pulTotalRunTime ) - { - UBaseType_t uxReturn; - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - uxReturn = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, pulTotalRunTime ); - vPortResetPrivilege( xRunningPrivileged ); - return uxReturn; - } -#endif -/*-----------------------------------------------------------*/ - -#if ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) - UBaseType_t MPU_uxTaskGetStackHighWaterMark( TaskHandle_t xTask ) - { - UBaseType_t uxReturn; - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - uxReturn = uxTaskGetStackHighWaterMark( xTask ); - vPortResetPrivilege( xRunningPrivileged ); - return uxReturn; - } -#endif -/*-----------------------------------------------------------*/ - -#if ( INCLUDE_xTaskGetCurrentTaskHandle == 1 ) - TaskHandle_t MPU_xTaskGetCurrentTaskHandle( void ) - { - TaskHandle_t xReturn; - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xTaskGetCurrentTaskHandle(); - vPortResetPrivilege( xRunningPrivileged ); - return xReturn; - } -#endif -/*-----------------------------------------------------------*/ - -#if ( INCLUDE_xTaskGetSchedulerState == 1 ) - BaseType_t MPU_xTaskGetSchedulerState( void ) - { - BaseType_t xReturn; - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xTaskGetSchedulerState(); - vPortResetPrivilege( xRunningPrivileged ); - return xReturn; - } -#endif -/*-----------------------------------------------------------*/ - -void MPU_vTaskSetTimeOutState( TimeOut_t * const pxTimeOut ) -{ -BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - vTaskSetTimeOutState( pxTimeOut ); - vPortResetPrivilege( xRunningPrivileged ); -} -/*-----------------------------------------------------------*/ - -BaseType_t MPU_xTaskCheckForTimeOut( TimeOut_t * const pxTimeOut, TickType_t * const pxTicksToWait ) -{ -BaseType_t xReturn; -BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xTaskCheckForTimeOut( pxTimeOut, pxTicksToWait ); - vPortResetPrivilege( xRunningPrivileged ); - return xReturn; -} -/*-----------------------------------------------------------*/ - -#if( configUSE_TASK_NOTIFICATIONS == 1 ) - BaseType_t MPU_xTaskGenericNotify( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotificationValue ) - { - BaseType_t xReturn; - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xTaskGenericNotify( xTaskToNotify, ulValue, eAction, pulPreviousNotificationValue ); - vPortResetPrivilege( xRunningPrivileged ); - return xReturn; - } -#endif -/*-----------------------------------------------------------*/ - -#if( configUSE_TASK_NOTIFICATIONS == 1 ) - BaseType_t MPU_xTaskNotifyWait( uint32_t ulBitsToClearOnEntry, uint32_t ulBitsToClearOnExit, uint32_t *pulNotificationValue, TickType_t xTicksToWait ) - { - BaseType_t xReturn; - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xTaskNotifyWait( ulBitsToClearOnEntry, ulBitsToClearOnExit, pulNotificationValue, xTicksToWait ); - vPortResetPrivilege( xRunningPrivileged ); - return xReturn; - } -#endif -/*-----------------------------------------------------------*/ - -#if( configUSE_TASK_NOTIFICATIONS == 1 ) - uint32_t MPU_ulTaskNotifyTake( BaseType_t xClearCountOnExit, TickType_t xTicksToWait ) - { - uint32_t ulReturn; - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - ulReturn = ulTaskNotifyTake( xClearCountOnExit, xTicksToWait ); - vPortResetPrivilege( xRunningPrivileged ); - return ulReturn; - } -#endif -/*-----------------------------------------------------------*/ - -#if( configUSE_TASK_NOTIFICATIONS == 1 ) - BaseType_t MPU_xTaskNotifyStateClear( TaskHandle_t xTask ) - { - BaseType_t xReturn; - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xTaskNotifyStateClear( xTask ); - vPortResetPrivilege( xRunningPrivileged ); - return xReturn; - } -#endif -/*-----------------------------------------------------------*/ - -#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - QueueHandle_t MPU_xQueueGenericCreate( UBaseType_t uxQueueLength, UBaseType_t uxItemSize, uint8_t ucQueueType ) - { - QueueHandle_t xReturn; - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xQueueGenericCreate( uxQueueLength, uxItemSize, ucQueueType ); - vPortResetPrivilege( xRunningPrivileged ); - return xReturn; - } -#endif -/*-----------------------------------------------------------*/ - -#if( configSUPPORT_STATIC_ALLOCATION == 1 ) - QueueHandle_t MPU_xQueueGenericCreateStatic( const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, uint8_t *pucQueueStorage, StaticQueue_t *pxStaticQueue, const uint8_t ucQueueType ) - { - QueueHandle_t xReturn; - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xQueueGenericCreateStatic( uxQueueLength, uxItemSize, pucQueueStorage, pxStaticQueue, ucQueueType ); - vPortResetPrivilege( xRunningPrivileged ); - return xReturn; - } -#endif -/*-----------------------------------------------------------*/ - -BaseType_t MPU_xQueueGenericReset( QueueHandle_t pxQueue, BaseType_t xNewQueue ) -{ -BaseType_t xReturn; -BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xQueueGenericReset( pxQueue, xNewQueue ); - vPortResetPrivilege( xRunningPrivileged ); - return xReturn; -} -/*-----------------------------------------------------------*/ - -BaseType_t MPU_xQueueGenericSend( QueueHandle_t xQueue, const void * const pvItemToQueue, TickType_t xTicksToWait, BaseType_t xCopyPosition ) -{ -BaseType_t xReturn; -BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xQueueGenericSend( xQueue, pvItemToQueue, xTicksToWait, xCopyPosition ); - vPortResetPrivilege( xRunningPrivileged ); - return xReturn; -} -/*-----------------------------------------------------------*/ - -UBaseType_t MPU_uxQueueMessagesWaiting( const QueueHandle_t pxQueue ) -{ -BaseType_t xRunningPrivileged = xPortRaisePrivilege(); -UBaseType_t uxReturn; - - uxReturn = uxQueueMessagesWaiting( pxQueue ); - vPortResetPrivilege( xRunningPrivileged ); - return uxReturn; -} -/*-----------------------------------------------------------*/ - -UBaseType_t MPU_uxQueueSpacesAvailable( const QueueHandle_t xQueue ) -{ -BaseType_t xRunningPrivileged = xPortRaisePrivilege(); -UBaseType_t uxReturn; - - uxReturn = uxQueueSpacesAvailable( xQueue ); - vPortResetPrivilege( xRunningPrivileged ); - return uxReturn; -} -/*-----------------------------------------------------------*/ - -BaseType_t MPU_xQueueReceive( QueueHandle_t pxQueue, void * const pvBuffer, TickType_t xTicksToWait ) -{ -BaseType_t xRunningPrivileged = xPortRaisePrivilege(); -BaseType_t xReturn; - - xReturn = xQueueReceive( pxQueue, pvBuffer, xTicksToWait ); - vPortResetPrivilege( xRunningPrivileged ); - return xReturn; -} -/*-----------------------------------------------------------*/ - -BaseType_t MPU_xQueuePeek( QueueHandle_t xQueue, void * const pvBuffer, TickType_t xTicksToWait ) -{ -BaseType_t xRunningPrivileged = xPortRaisePrivilege(); -BaseType_t xReturn; - - xReturn = xQueuePeek( xQueue, pvBuffer, xTicksToWait ); - vPortResetPrivilege( xRunningPrivileged ); - return xReturn; -} -/*-----------------------------------------------------------*/ - -BaseType_t MPU_xQueueSemaphoreTake( QueueHandle_t xQueue, TickType_t xTicksToWait ) -{ -BaseType_t xRunningPrivileged = xPortRaisePrivilege(); -BaseType_t xReturn; - - xReturn = xQueueSemaphoreTake( xQueue, xTicksToWait ); - vPortResetPrivilege( xRunningPrivileged ); - return xReturn; -} -/*-----------------------------------------------------------*/ - -BaseType_t MPU_xQueuePeekFromISR( QueueHandle_t pxQueue, void * const pvBuffer ) -{ -BaseType_t xRunningPrivileged = xPortRaisePrivilege(); -BaseType_t xReturn; - - xReturn = xQueuePeekFromISR( pxQueue, pvBuffer ); - vPortResetPrivilege( xRunningPrivileged ); - return xReturn; -} -/*-----------------------------------------------------------*/ - -void* MPU_xQueueGetMutexHolder( QueueHandle_t xSemaphore ) -{ -BaseType_t xRunningPrivileged = xPortRaisePrivilege(); -void * xReturn; - - xReturn = ( void * ) xQueueGetMutexHolder( xSemaphore ); - vPortResetPrivilege( xRunningPrivileged ); - return xReturn; -} -/*-----------------------------------------------------------*/ - -#if( ( configUSE_MUTEXES == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) - QueueHandle_t MPU_xQueueCreateMutex( const uint8_t ucQueueType ) - { - QueueHandle_t xReturn; - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xQueueCreateMutex( ucQueueType ); - vPortResetPrivilege( xRunningPrivileged ); - return xReturn; - } -#endif -/*-----------------------------------------------------------*/ - -#if( ( configUSE_MUTEXES == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) - QueueHandle_t MPU_xQueueCreateMutexStatic( const uint8_t ucQueueType, StaticQueue_t *pxStaticQueue ) - { - QueueHandle_t xReturn; - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xQueueCreateMutexStatic( ucQueueType, pxStaticQueue ); - vPortResetPrivilege( xRunningPrivileged ); - return xReturn; - } -#endif -/*-----------------------------------------------------------*/ - -#if( ( configUSE_COUNTING_SEMAPHORES == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) - QueueHandle_t MPU_xQueueCreateCountingSemaphore( UBaseType_t uxCountValue, UBaseType_t uxInitialCount ) - { - QueueHandle_t xReturn; - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xQueueCreateCountingSemaphore( uxCountValue, uxInitialCount ); - vPortResetPrivilege( xRunningPrivileged ); - return xReturn; - } -#endif -/*-----------------------------------------------------------*/ - -#if( ( configUSE_COUNTING_SEMAPHORES == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) - - QueueHandle_t MPU_xQueueCreateCountingSemaphoreStatic( const UBaseType_t uxMaxCount, const UBaseType_t uxInitialCount, StaticQueue_t *pxStaticQueue ) - { - QueueHandle_t xReturn; - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xQueueCreateCountingSemaphoreStatic( uxMaxCount, uxInitialCount, pxStaticQueue ); - vPortResetPrivilege( xRunningPrivileged ); - return xReturn; - } -#endif -/*-----------------------------------------------------------*/ - -#if ( configUSE_RECURSIVE_MUTEXES == 1 ) - BaseType_t MPU_xQueueTakeMutexRecursive( QueueHandle_t xMutex, TickType_t xBlockTime ) - { - BaseType_t xReturn; - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xQueueTakeMutexRecursive( xMutex, xBlockTime ); - vPortResetPrivilege( xRunningPrivileged ); - return xReturn; - } -#endif -/*-----------------------------------------------------------*/ - -#if ( configUSE_RECURSIVE_MUTEXES == 1 ) - BaseType_t MPU_xQueueGiveMutexRecursive( QueueHandle_t xMutex ) - { - BaseType_t xReturn; - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xQueueGiveMutexRecursive( xMutex ); - vPortResetPrivilege( xRunningPrivileged ); - return xReturn; - } -#endif -/*-----------------------------------------------------------*/ - -#if( ( configUSE_QUEUE_SETS == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) - QueueSetHandle_t MPU_xQueueCreateSet( UBaseType_t uxEventQueueLength ) - { - QueueSetHandle_t xReturn; - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xQueueCreateSet( uxEventQueueLength ); - vPortResetPrivilege( xRunningPrivileged ); - return xReturn; - } -#endif -/*-----------------------------------------------------------*/ - -#if ( configUSE_QUEUE_SETS == 1 ) - QueueSetMemberHandle_t MPU_xQueueSelectFromSet( QueueSetHandle_t xQueueSet, TickType_t xBlockTimeTicks ) - { - QueueSetMemberHandle_t xReturn; - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xQueueSelectFromSet( xQueueSet, xBlockTimeTicks ); - vPortResetPrivilege( xRunningPrivileged ); - return xReturn; - } -#endif -/*-----------------------------------------------------------*/ - -#if ( configUSE_QUEUE_SETS == 1 ) - BaseType_t MPU_xQueueAddToSet( QueueSetMemberHandle_t xQueueOrSemaphore, QueueSetHandle_t xQueueSet ) - { - BaseType_t xReturn; - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xQueueAddToSet( xQueueOrSemaphore, xQueueSet ); - vPortResetPrivilege( xRunningPrivileged ); - return xReturn; - } -#endif -/*-----------------------------------------------------------*/ - -#if ( configUSE_QUEUE_SETS == 1 ) - BaseType_t MPU_xQueueRemoveFromSet( QueueSetMemberHandle_t xQueueOrSemaphore, QueueSetHandle_t xQueueSet ) - { - BaseType_t xReturn; - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xQueueRemoveFromSet( xQueueOrSemaphore, xQueueSet ); - vPortResetPrivilege( xRunningPrivileged ); - return xReturn; - } -#endif -/*-----------------------------------------------------------*/ - -#if configQUEUE_REGISTRY_SIZE > 0 - void MPU_vQueueAddToRegistry( QueueHandle_t xQueue, const char *pcName ) - { - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - vQueueAddToRegistry( xQueue, pcName ); - - vPortResetPrivilege( xRunningPrivileged ); - } -#endif -/*-----------------------------------------------------------*/ - -#if configQUEUE_REGISTRY_SIZE > 0 - void MPU_vQueueUnregisterQueue( QueueHandle_t xQueue ) - { - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - vQueueUnregisterQueue( xQueue ); - - vPortResetPrivilege( xRunningPrivileged ); - } -#endif -/*-----------------------------------------------------------*/ - -#if configQUEUE_REGISTRY_SIZE > 0 - const char *MPU_pcQueueGetName( QueueHandle_t xQueue ) - { - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - const char *pcReturn; - - pcReturn = pcQueueGetName( xQueue ); - - vPortResetPrivilege( xRunningPrivileged ); - return pcReturn; - } -#endif -/*-----------------------------------------------------------*/ - -void MPU_vQueueDelete( QueueHandle_t xQueue ) -{ -BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - vQueueDelete( xQueue ); - - vPortResetPrivilege( xRunningPrivileged ); -} -/*-----------------------------------------------------------*/ - -#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - void *MPU_pvPortMalloc( size_t xSize ) - { - void *pvReturn; - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - pvReturn = pvPortMalloc( xSize ); - - vPortResetPrivilege( xRunningPrivileged ); - - return pvReturn; - } -#endif /* configSUPPORT_DYNAMIC_ALLOCATION */ -/*-----------------------------------------------------------*/ - -#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - void MPU_vPortFree( void *pv ) - { - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - vPortFree( pv ); - - vPortResetPrivilege( xRunningPrivileged ); - } -#endif /* configSUPPORT_DYNAMIC_ALLOCATION */ -/*-----------------------------------------------------------*/ - -#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - void MPU_vPortInitialiseBlocks( void ) - { - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - vPortInitialiseBlocks(); - - vPortResetPrivilege( xRunningPrivileged ); - } -#endif /* configSUPPORT_DYNAMIC_ALLOCATION */ -/*-----------------------------------------------------------*/ - -#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - size_t MPU_xPortGetFreeHeapSize( void ) - { - size_t xReturn; - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xPortGetFreeHeapSize(); - - vPortResetPrivilege( xRunningPrivileged ); - - return xReturn; - } -#endif /* configSUPPORT_DYNAMIC_ALLOCATION */ -/*-----------------------------------------------------------*/ - -#if( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configUSE_TIMERS == 1 ) ) - TimerHandle_t MPU_xTimerCreate( const char * const pcTimerName, const TickType_t xTimerPeriodInTicks, const UBaseType_t uxAutoReload, void * const pvTimerID, TimerCallbackFunction_t pxCallbackFunction ) - { - TimerHandle_t xReturn; - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xTimerCreate( pcTimerName, xTimerPeriodInTicks, uxAutoReload, pvTimerID, pxCallbackFunction ); - vPortResetPrivilege( xRunningPrivileged ); - - return xReturn; - } -#endif -/*-----------------------------------------------------------*/ - -#if( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configUSE_TIMERS == 1 ) ) - TimerHandle_t MPU_xTimerCreateStatic( const char * const pcTimerName, const TickType_t xTimerPeriodInTicks, const UBaseType_t uxAutoReload, void * const pvTimerID, TimerCallbackFunction_t pxCallbackFunction, StaticTimer_t *pxTimerBuffer ) - { - TimerHandle_t xReturn; - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xTimerCreateStatic( pcTimerName, xTimerPeriodInTicks, uxAutoReload, pvTimerID, pxCallbackFunction, pxTimerBuffer ); - vPortResetPrivilege( xRunningPrivileged ); - - return xReturn; - } -#endif -/*-----------------------------------------------------------*/ - -#if( configUSE_TIMERS == 1 ) - void *MPU_pvTimerGetTimerID( const TimerHandle_t xTimer ) - { - void * pvReturn; - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - pvReturn = pvTimerGetTimerID( xTimer ); - vPortResetPrivilege( xRunningPrivileged ); - - return pvReturn; - } -#endif -/*-----------------------------------------------------------*/ - -#if( configUSE_TIMERS == 1 ) - void MPU_vTimerSetTimerID( TimerHandle_t xTimer, void *pvNewID ) - { - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - vTimerSetTimerID( xTimer, pvNewID ); - vPortResetPrivilege( xRunningPrivileged ); - } -#endif -/*-----------------------------------------------------------*/ - -#if( configUSE_TIMERS == 1 ) - BaseType_t MPU_xTimerIsTimerActive( TimerHandle_t xTimer ) - { - BaseType_t xReturn; - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xTimerIsTimerActive( xTimer ); - vPortResetPrivilege( xRunningPrivileged ); - - return xReturn; - } -#endif -/*-----------------------------------------------------------*/ - -#if( configUSE_TIMERS == 1 ) - TaskHandle_t MPU_xTimerGetTimerDaemonTaskHandle( void ) - { - TaskHandle_t xReturn; - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xTimerGetTimerDaemonTaskHandle(); - vPortResetPrivilege( xRunningPrivileged ); - - return xReturn; - } -#endif -/*-----------------------------------------------------------*/ - -#if( ( INCLUDE_xTimerPendFunctionCall == 1 ) && ( configUSE_TIMERS == 1 ) ) - BaseType_t MPU_xTimerPendFunctionCall( PendedFunction_t xFunctionToPend, void *pvParameter1, uint32_t ulParameter2, TickType_t xTicksToWait ) - { - BaseType_t xReturn; - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xTimerPendFunctionCall( xFunctionToPend, pvParameter1, ulParameter2, xTicksToWait ); - vPortResetPrivilege( xRunningPrivileged ); - - return xReturn; - } -#endif -/*-----------------------------------------------------------*/ - -#if( configUSE_TIMERS == 1 ) - const char * MPU_pcTimerGetName( TimerHandle_t xTimer ) - { - const char * pcReturn; - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - pcReturn = pcTimerGetName( xTimer ); - vPortResetPrivilege( xRunningPrivileged ); - - return pcReturn; - } -#endif -/*-----------------------------------------------------------*/ - -#if( configUSE_TIMERS == 1 ) - TickType_t MPU_xTimerGetPeriod( TimerHandle_t xTimer ) - { - TickType_t xReturn; - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xTimerGetPeriod( xTimer ); - vPortResetPrivilege( xRunningPrivileged ); - - return xReturn; - } -#endif -/*-----------------------------------------------------------*/ - -#if( configUSE_TIMERS == 1 ) - TickType_t MPU_xTimerGetExpiryTime( TimerHandle_t xTimer ) - { - TickType_t xReturn; - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xTimerGetExpiryTime( xTimer ); - vPortResetPrivilege( xRunningPrivileged ); - - return xReturn; - } -#endif -/*-----------------------------------------------------------*/ - -#if( configUSE_TIMERS == 1 ) - BaseType_t MPU_xTimerGenericCommand( TimerHandle_t xTimer, const BaseType_t xCommandID, const TickType_t xOptionalValue, BaseType_t * const pxHigherPriorityTaskWoken, const TickType_t xTicksToWait ) - { - BaseType_t xReturn; - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xTimerGenericCommand( xTimer, xCommandID, xOptionalValue, pxHigherPriorityTaskWoken, xTicksToWait ); - vPortResetPrivilege( xRunningPrivileged ); - - return xReturn; - } -#endif -/*-----------------------------------------------------------*/ - -#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - EventGroupHandle_t MPU_xEventGroupCreate( void ) - { - EventGroupHandle_t xReturn; - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xEventGroupCreate(); - vPortResetPrivilege( xRunningPrivileged ); - - return xReturn; - } -#endif -/*-----------------------------------------------------------*/ - -#if( configSUPPORT_STATIC_ALLOCATION == 1 ) - EventGroupHandle_t MPU_xEventGroupCreateStatic( StaticEventGroup_t *pxEventGroupBuffer ) - { - EventGroupHandle_t xReturn; - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xEventGroupCreateStatic( pxEventGroupBuffer ); - vPortResetPrivilege( xRunningPrivileged ); - - return xReturn; - } -#endif -/*-----------------------------------------------------------*/ - -EventBits_t MPU_xEventGroupWaitBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToWaitFor, const BaseType_t xClearOnExit, const BaseType_t xWaitForAllBits, TickType_t xTicksToWait ) -{ -EventBits_t xReturn; -BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xEventGroupWaitBits( xEventGroup, uxBitsToWaitFor, xClearOnExit, xWaitForAllBits, xTicksToWait ); - vPortResetPrivilege( xRunningPrivileged ); - - return xReturn; -} -/*-----------------------------------------------------------*/ - -EventBits_t MPU_xEventGroupClearBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToClear ) -{ -EventBits_t xReturn; -BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xEventGroupClearBits( xEventGroup, uxBitsToClear ); - vPortResetPrivilege( xRunningPrivileged ); - - return xReturn; -} -/*-----------------------------------------------------------*/ - -EventBits_t MPU_xEventGroupSetBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet ) -{ -EventBits_t xReturn; -BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xEventGroupSetBits( xEventGroup, uxBitsToSet ); - vPortResetPrivilege( xRunningPrivileged ); - - return xReturn; -} -/*-----------------------------------------------------------*/ - -EventBits_t MPU_xEventGroupSync( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet, const EventBits_t uxBitsToWaitFor, TickType_t xTicksToWait ) -{ -EventBits_t xReturn; -BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xEventGroupSync( xEventGroup, uxBitsToSet, uxBitsToWaitFor, xTicksToWait ); - vPortResetPrivilege( xRunningPrivileged ); - - return xReturn; -} -/*-----------------------------------------------------------*/ - -void MPU_vEventGroupDelete( EventGroupHandle_t xEventGroup ) -{ -BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - vEventGroupDelete( xEventGroup ); - vPortResetPrivilege( xRunningPrivileged ); -} -/*-----------------------------------------------------------*/ - -size_t MPU_xStreamBufferSend( StreamBufferHandle_t xStreamBuffer, const void *pvTxData, size_t xDataLengthBytes, TickType_t xTicksToWait ) -{ -size_t xReturn; -BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xStreamBufferSend( xStreamBuffer, pvTxData, xDataLengthBytes, xTicksToWait ); - vPortResetPrivilege( xRunningPrivileged ); - - return xReturn; -} -/*-----------------------------------------------------------*/ - -size_t MPU_xStreamBufferSendFromISR( StreamBufferHandle_t xStreamBuffer, const void *pvTxData, size_t xDataLengthBytes, BaseType_t * const pxHigherPriorityTaskWoken ) -{ -size_t xReturn; -BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xStreamBufferSendFromISR( xStreamBuffer, pvTxData, xDataLengthBytes, pxHigherPriorityTaskWoken ); - vPortResetPrivilege( xRunningPrivileged ); - - return xReturn; -} -/*-----------------------------------------------------------*/ - -size_t MPU_xStreamBufferReceive( StreamBufferHandle_t xStreamBuffer, void *pvRxData, size_t xBufferLengthBytes, TickType_t xTicksToWait ) -{ -size_t xReturn; -BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xStreamBufferReceive( xStreamBuffer, pvRxData, xBufferLengthBytes, xTicksToWait ); - vPortResetPrivilege( xRunningPrivileged ); - - return xReturn; -} -/*-----------------------------------------------------------*/ - -size_t MPU_xStreamBufferReceiveFromISR( StreamBufferHandle_t xStreamBuffer, void *pvRxData, size_t xBufferLengthBytes, BaseType_t * const pxHigherPriorityTaskWoken ) -{ -size_t xReturn; -BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xStreamBufferReceiveFromISR( xStreamBuffer, pvRxData, xBufferLengthBytes, pxHigherPriorityTaskWoken ); - vPortResetPrivilege( xRunningPrivileged ); - - return xReturn; -} -/*-----------------------------------------------------------*/ - -void MPU_vStreamBufferDelete( StreamBufferHandle_t xStreamBuffer ) -{ -BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - vStreamBufferDelete( xStreamBuffer ); - vPortResetPrivilege( xRunningPrivileged ); -} -/*-----------------------------------------------------------*/ - -BaseType_t MPU_xStreamBufferIsFull( StreamBufferHandle_t xStreamBuffer ) -{ -BaseType_t xReturn; -BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xStreamBufferIsFull( xStreamBuffer ); - vPortResetPrivilege( xRunningPrivileged ); - - return xReturn; -} -/*-----------------------------------------------------------*/ - -BaseType_t MPU_xStreamBufferIsEmpty( StreamBufferHandle_t xStreamBuffer ) -{ -BaseType_t xReturn; -BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xStreamBufferIsEmpty( xStreamBuffer ); - vPortResetPrivilege( xRunningPrivileged ); - - return xReturn; -} -/*-----------------------------------------------------------*/ - -BaseType_t MPU_xStreamBufferReset( StreamBufferHandle_t xStreamBuffer ) -{ -BaseType_t xReturn; -BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xStreamBufferReset( xStreamBuffer ); - vPortResetPrivilege( xRunningPrivileged ); - - return xReturn; -} -/*-----------------------------------------------------------*/ - -size_t MPU_xStreamBufferSpacesAvailable( StreamBufferHandle_t xStreamBuffer ) -{ -size_t xReturn; -BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xStreamBufferSpacesAvailable( xStreamBuffer ); - vPortResetPrivilege( xRunningPrivileged ); - - return xReturn; -} -/*-----------------------------------------------------------*/ - -size_t MPU_xStreamBufferBytesAvailable( StreamBufferHandle_t xStreamBuffer ) -{ -size_t xReturn; -BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xStreamBufferBytesAvailable( xStreamBuffer ); - vPortResetPrivilege( xRunningPrivileged ); - - return xReturn; -} -/*-----------------------------------------------------------*/ - -BaseType_t MPU_xStreamBufferSetTriggerLevel( StreamBufferHandle_t xStreamBuffer, size_t xTriggerLevel ) -{ -BaseType_t xReturn; -BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xStreamBufferSetTriggerLevel( xStreamBuffer, xTriggerLevel ); - vPortResetPrivilege( xRunningPrivileged ); - - return xReturn; -} -/*-----------------------------------------------------------*/ - -#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - StreamBufferHandle_t MPU_xStreamBufferGenericCreate( size_t xBufferSizeBytes, size_t xTriggerLevelBytes, BaseType_t xIsMessageBuffer ) - { - StreamBufferHandle_t xReturn; - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xStreamBufferGenericCreate( xBufferSizeBytes, xTriggerLevelBytes, xIsMessageBuffer ); - vPortResetPrivilege( xRunningPrivileged ); - - return xReturn; - } -#endif /* configSUPPORT_DYNAMIC_ALLOCATION */ -/*-----------------------------------------------------------*/ - -#if( configSUPPORT_STATIC_ALLOCATION == 1 ) - StreamBufferHandle_t MPU_xStreamBufferGenericCreateStatic( size_t xBufferSizeBytes, size_t xTriggerLevelBytes, BaseType_t xIsMessageBuffer, uint8_t * const pucStreamBufferStorageArea, StaticStreamBuffer_t * const pxStaticStreamBuffer ) - { - StreamBufferHandle_t xReturn; - BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - xReturn = xStreamBufferGenericCreateStatic( xBufferSizeBytes, xTriggerLevelBytes, xIsMessageBuffer, pucStreamBufferStorageArea, pxStaticStreamBuffer ); - vPortResetPrivilege( xRunningPrivileged ); - - return xReturn; - } -#endif /* configSUPPORT_STATIC_ALLOCATION */ -/*-----------------------------------------------------------*/ - - -/* Functions that the application writer wants to execute in privileged mode -can be defined in application_defined_privileged_functions.h. The functions -must take the same format as those above whereby the privilege state on exit -equals the privilege state on entry. For example: - -void MPU_FunctionName( [parameters ] ) -{ -BaseType_t xRunningPrivileged = xPortRaisePrivilege(); - - FunctionName( [parameters ] ); - - vPortResetPrivilege( xRunningPrivileged ); -} -*/ - -#if configINCLUDE_APPLICATION_DEFINED_PRIVILEGED_FUNCTIONS == 1 - #include "application_defined_privileged_functions.h" -#endif diff --git a/lib/FreeRTOS/Source/portable/GCC/ARM_CM0/port.c b/lib/FreeRTOS/Source/portable/GCC/ARM_CM0/port.c deleted file mode 100644 index 78d625d2..00000000 --- a/lib/FreeRTOS/Source/portable/GCC/ARM_CM0/port.c +++ /dev/null @@ -1,362 +0,0 @@ -/* - * FreeRTOS Kernel V10.0.1 - * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * 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. - * - * http://www.FreeRTOS.org - * http://aws.amazon.com/freertos - * - * 1 tab == 4 spaces! - */ - -/*----------------------------------------------------------- - * Implementation of functions defined in portable.h for the ARM CM0 port. - *----------------------------------------------------------*/ - -/* Scheduler includes. */ -#include "FreeRTOS.h" -#include "task.h" - -/* Constants required to manipulate the NVIC. */ -#define portNVIC_SYSTICK_CTRL ( ( volatile uint32_t * ) 0xe000e010 ) -#define portNVIC_SYSTICK_LOAD ( ( volatile uint32_t * ) 0xe000e014 ) -#define portNVIC_SYSTICK_CURRENT_VALUE ( ( volatile uint32_t * ) 0xe000e018 ) -#define portNVIC_INT_CTRL ( ( volatile uint32_t *) 0xe000ed04 ) -#define portNVIC_SYSPRI2 ( ( volatile uint32_t *) 0xe000ed20 ) -#define portNVIC_SYSTICK_CLK 0x00000004 -#define portNVIC_SYSTICK_INT 0x00000002 -#define portNVIC_SYSTICK_ENABLE 0x00000001 -#define portNVIC_PENDSVSET 0x10000000 -#define portMIN_INTERRUPT_PRIORITY ( 255UL ) -#define portNVIC_PENDSV_PRI ( portMIN_INTERRUPT_PRIORITY << 16UL ) -#define portNVIC_SYSTICK_PRI ( portMIN_INTERRUPT_PRIORITY << 24UL ) - -/* Constants required to set up the initial stack. */ -#define portINITIAL_XPSR ( 0x01000000 ) - -/* Let the user override the pre-loading of the initial LR with the address of -prvTaskExitError() in case it messes up unwinding of the stack in the -debugger. */ -#ifdef configTASK_RETURN_ADDRESS - #define portTASK_RETURN_ADDRESS configTASK_RETURN_ADDRESS -#else - #define portTASK_RETURN_ADDRESS prvTaskExitError -#endif - -/* - * Setup the timer to generate the tick interrupts. - */ -static void prvSetupTimerInterrupt( void ); - -/* - * Exception handlers. - */ -void xPortPendSVHandler( void ) __attribute__ (( naked )); -void xPortSysTickHandler( void ); -void vPortSVCHandler( void ); - -/* - * Start first task is a separate function so it can be tested in isolation. - */ -static void vPortStartFirstTask( void ) __attribute__ (( naked )); - -/* - * Used to catch tasks that attempt to return from their implementing function. - */ -static void prvTaskExitError( void ); - -/*-----------------------------------------------------------*/ - -/* Each task maintains its own interrupt status in the critical nesting -variable. */ -static UBaseType_t uxCriticalNesting = 0xaaaaaaaa; - -/*-----------------------------------------------------------*/ - -/* - * See header file for description. - */ -StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters ) -{ - /* Simulate the stack frame as it would be created by a context switch - interrupt. */ - pxTopOfStack--; /* Offset added to account for the way the MCU uses the stack on entry/exit of interrupts. */ - *pxTopOfStack = portINITIAL_XPSR; /* xPSR */ - pxTopOfStack--; - *pxTopOfStack = ( StackType_t ) pxCode; /* PC */ - pxTopOfStack--; - *pxTopOfStack = ( StackType_t ) portTASK_RETURN_ADDRESS; /* LR */ - pxTopOfStack -= 5; /* R12, R3, R2 and R1. */ - *pxTopOfStack = ( StackType_t ) pvParameters; /* R0 */ - pxTopOfStack -= 8; /* R11..R4. */ - - return pxTopOfStack; -} -/*-----------------------------------------------------------*/ - -static void prvTaskExitError( void ) -{ -volatile uint32_t ulDummy = 0UL; - - /* A function that implements a task must not exit or attempt to return to - its caller as there is nothing to return to. If a task wants to exit it - should instead call vTaskDelete( NULL ). - - Artificially force an assert() to be triggered if configASSERT() is - defined, then stop here so application writers can catch the error. */ - configASSERT( uxCriticalNesting == ~0UL ); - portDISABLE_INTERRUPTS(); - while( ulDummy == 0 ) - { - /* This file calls prvTaskExitError() after the scheduler has been - started to remove a compiler warning about the function being defined - but never called. ulDummy is used purely to quieten other warnings - about code appearing after this function is called - making ulDummy - volatile makes the compiler think the function could return and - therefore not output an 'unreachable code' warning for code that appears - after it. */ - } -} -/*-----------------------------------------------------------*/ - -void vPortSVCHandler( void ) -{ - /* This function is no longer used, but retained for backward - compatibility. */ -} -/*-----------------------------------------------------------*/ - -void vPortStartFirstTask( void ) -{ - /* The MSP stack is not reset as, unlike on M3/4 parts, there is no vector - table offset register that can be used to locate the initial stack value. - Not all M0 parts have the application vector table at address 0. */ - __asm volatile( - " .syntax unified \n" - " ldr r2, pxCurrentTCBConst2 \n" /* Obtain location of pxCurrentTCB. */ - " ldr r3, [r2] \n" - " ldr r0, [r3] \n" /* The first item in pxCurrentTCB is the task top of stack. */ - " adds r0, #32 \n" /* Discard everything up to r0. */ - " msr psp, r0 \n" /* This is now the new top of stack to use in the task. */ - " movs r0, #2 \n" /* Switch to the psp stack. */ - " msr CONTROL, r0 \n" - " isb \n" - " pop {r0-r5} \n" /* Pop the registers that are saved automatically. */ - " mov lr, r5 \n" /* lr is now in r5. */ - " pop {r3} \n" /* Return address is now in r3. */ - " pop {r2} \n" /* Pop and discard XPSR. */ - " cpsie i \n" /* The first task has its context and interrupts can be enabled. */ - " bx r3 \n" /* Finally, jump to the user defined task code. */ - " \n" - " .align 4 \n" - "pxCurrentTCBConst2: .word pxCurrentTCB " - ); -} -/*-----------------------------------------------------------*/ - -/* - * See header file for description. - */ -BaseType_t xPortStartScheduler( void ) -{ - /* Make PendSV, CallSV and SysTick the same priroity as the kernel. */ - *(portNVIC_SYSPRI2) |= portNVIC_PENDSV_PRI; - *(portNVIC_SYSPRI2) |= portNVIC_SYSTICK_PRI; - - /* Start the timer that generates the tick ISR. Interrupts are disabled - here already. */ - prvSetupTimerInterrupt(); - - /* Initialise the critical nesting count ready for the first task. */ - uxCriticalNesting = 0; - - /* Start the first task. */ - vPortStartFirstTask(); - - /* Should never get here as the tasks will now be executing! Call the task - exit error function to prevent compiler warnings about a static function - not being called in the case that the application writer overrides this - functionality by defining configTASK_RETURN_ADDRESS. Call - vTaskSwitchContext() so link time optimisation does not remove the - symbol. */ - vTaskSwitchContext(); - prvTaskExitError(); - - /* Should not get here! */ - return 0; -} -/*-----------------------------------------------------------*/ - -void vPortEndScheduler( void ) -{ - /* Not implemented in ports where there is nothing to return to. - Artificially force an assert. */ - configASSERT( uxCriticalNesting == 1000UL ); -} -/*-----------------------------------------------------------*/ - -void vPortYield( void ) -{ - /* Set a PendSV to request a context switch. */ - *( portNVIC_INT_CTRL ) = portNVIC_PENDSVSET; - - /* Barriers are normally not required but do ensure the code is completely - within the specified behaviour for the architecture. */ - __asm volatile( "dsb" ::: "memory" ); - __asm volatile( "isb" ); -} -/*-----------------------------------------------------------*/ - -void vPortEnterCritical( void ) -{ - portDISABLE_INTERRUPTS(); - uxCriticalNesting++; - __asm volatile( "dsb" ::: "memory" ); - __asm volatile( "isb" ); -} -/*-----------------------------------------------------------*/ - -void vPortExitCritical( void ) -{ - configASSERT( uxCriticalNesting ); - uxCriticalNesting--; - if( uxCriticalNesting == 0 ) - { - portENABLE_INTERRUPTS(); - } -} -/*-----------------------------------------------------------*/ - -uint32_t ulSetInterruptMaskFromISR( void ) -{ - __asm volatile( - " mrs r0, PRIMASK \n" - " cpsid i \n" - " bx lr " - ::: "memory" - ); - -#if !defined (__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050) - /* To avoid compiler warnings. The return statement will nevere be reached, - but some compilers warn if it is not included, while others won't compile if - it is. */ - return 0; -#endif -} -/*-----------------------------------------------------------*/ - -void vClearInterruptMaskFromISR( __attribute__( ( unused ) ) uint32_t ulMask ) -{ - __asm volatile( - " msr PRIMASK, r0 \n" - " bx lr " - ::: "memory" - ); - -#if !defined (__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050) - /* Just to avoid compiler warning. ulMask is used from the asm code but - the compiler can't see that. Some compilers generate warnings without the - following line, while others generate warnings if the line is included. */ - ( void ) ulMask; -#endif -} -/*-----------------------------------------------------------*/ - -void xPortPendSVHandler( void ) -{ - /* This is a naked function. */ - - __asm volatile - ( - " .syntax unified \n" - " mrs r0, psp \n" - " \n" - " ldr r3, pxCurrentTCBConst \n" /* Get the location of the current TCB. */ - " ldr r2, [r3] \n" - " \n" - " subs r0, r0, #32 \n" /* Make space for the remaining low registers. */ - " str r0, [r2] \n" /* Save the new top of stack. */ - " stmia r0!, {r4-r7} \n" /* Store the low registers that are not saved automatically. */ - " mov r4, r8 \n" /* Store the high registers. */ - " mov r5, r9 \n" - " mov r6, r10 \n" - " mov r7, r11 \n" - " stmia r0!, {r4-r7} \n" - " \n" - " push {r3, r14} \n" - " cpsid i \n" - " bl vTaskSwitchContext \n" - " cpsie i \n" - " pop {r2, r3} \n" /* lr goes in r3. r2 now holds tcb pointer. */ - " \n" - " ldr r1, [r2] \n" - " ldr r0, [r1] \n" /* The first item in pxCurrentTCB is the task top of stack. */ - " adds r0, r0, #16 \n" /* Move to the high registers. */ - " ldmia r0!, {r4-r7} \n" /* Pop the high registers. */ - " mov r8, r4 \n" - " mov r9, r5 \n" - " mov r10, r6 \n" - " mov r11, r7 \n" - " \n" - " msr psp, r0 \n" /* Remember the new top of stack for the task. */ - " \n" - " subs r0, r0, #32 \n" /* Go back for the low registers that are not automatically restored. */ - " ldmia r0!, {r4-r7} \n" /* Pop low registers. */ - " \n" - " bx r3 \n" - " \n" - " .align 4 \n" - "pxCurrentTCBConst: .word pxCurrentTCB " - ); -} -/*-----------------------------------------------------------*/ - -void xPortSysTickHandler( void ) -{ -uint32_t ulPreviousMask; - - ulPreviousMask = portSET_INTERRUPT_MASK_FROM_ISR(); - { - /* Increment the RTOS tick. */ - if( xTaskIncrementTick() != pdFALSE ) - { - /* Pend a context switch. */ - *(portNVIC_INT_CTRL) = portNVIC_PENDSVSET; - } - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( ulPreviousMask ); -} -/*-----------------------------------------------------------*/ - -/* - * Setup the systick timer to generate the tick interrupts at the required - * frequency. - */ -void prvSetupTimerInterrupt( void ) -{ - /* Stop and reset the SysTick. */ - *(portNVIC_SYSTICK_CTRL) = 0UL; - *(portNVIC_SYSTICK_CURRENT_VALUE) = 0UL; - - /* Configure SysTick to interrupt at the requested rate. */ - *(portNVIC_SYSTICK_LOAD) = ( configCPU_CLOCK_HZ / configTICK_RATE_HZ ) - 1UL; - *(portNVIC_SYSTICK_CTRL) = portNVIC_SYSTICK_CLK | portNVIC_SYSTICK_INT | portNVIC_SYSTICK_ENABLE; -} -/*-----------------------------------------------------------*/ - diff --git a/lib/FreeRTOS/Source/portable/GCC/ARM_CM0/portmacro.h b/lib/FreeRTOS/Source/portable/GCC/ARM_CM0/portmacro.h deleted file mode 100644 index bb42cea7..00000000 --- a/lib/FreeRTOS/Source/portable/GCC/ARM_CM0/portmacro.h +++ /dev/null @@ -1,115 +0,0 @@ -/* - * FreeRTOS Kernel V10.0.1 - * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * 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. - * - * http://www.FreeRTOS.org - * http://aws.amazon.com/freertos - * - * 1 tab == 4 spaces! - */ - - -#ifndef PORTMACRO_H -#define PORTMACRO_H - -#ifdef __cplusplus -extern "C" { -#endif - -/*----------------------------------------------------------- - * Port specific definitions. - * - * The settings in this file configure FreeRTOS correctly for the - * given hardware and compiler. - * - * These settings should not be altered. - *----------------------------------------------------------- - */ - -/* Type definitions. */ -#define portCHAR char -#define portFLOAT float -#define portDOUBLE double -#define portLONG long -#define portSHORT short -#define portSTACK_TYPE uint32_t -#define portBASE_TYPE long - -typedef portSTACK_TYPE StackType_t; -typedef long BaseType_t; -typedef unsigned long UBaseType_t; - -#if( configUSE_16_BIT_TICKS == 1 ) - typedef uint16_t TickType_t; - #define portMAX_DELAY ( TickType_t ) 0xffff -#else - typedef uint32_t TickType_t; - #define portMAX_DELAY ( TickType_t ) 0xffffffffUL - - /* 32-bit tick type on a 32-bit architecture, so reads of the tick count do - not need to be guarded with a critical section. */ - #define portTICK_TYPE_IS_ATOMIC 1 -#endif -/*-----------------------------------------------------------*/ - -/* Architecture specifics. */ -#define portSTACK_GROWTH ( -1 ) -#define portTICK_PERIOD_MS ( ( TickType_t ) 1000 / configTICK_RATE_HZ ) -#define portBYTE_ALIGNMENT 8 -/*-----------------------------------------------------------*/ - - -/* Scheduler utilities. */ -extern void vPortYield( void ); -#define portNVIC_INT_CTRL_REG ( * ( ( volatile uint32_t * ) 0xe000ed04 ) ) -#define portNVIC_PENDSVSET_BIT ( 1UL << 28UL ) -#define portYIELD() vPortYield() -#define portEND_SWITCHING_ISR( xSwitchRequired ) if( xSwitchRequired ) portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT -#define portYIELD_FROM_ISR( x ) portEND_SWITCHING_ISR( x ) -/*-----------------------------------------------------------*/ - - -/* Critical section management. */ -extern void vPortEnterCritical( void ); -extern void vPortExitCritical( void ); -extern uint32_t ulSetInterruptMaskFromISR( void ) __attribute__((naked)); -extern void vClearInterruptMaskFromISR( uint32_t ulMask ) __attribute__((naked)); - -#define portSET_INTERRUPT_MASK_FROM_ISR() ulSetInterruptMaskFromISR() -#define portCLEAR_INTERRUPT_MASK_FROM_ISR(x) vClearInterruptMaskFromISR( x ) -#define portDISABLE_INTERRUPTS() __asm volatile ( " cpsid i " ::: "memory" ) -#define portENABLE_INTERRUPTS() __asm volatile ( " cpsie i " ::: "memory" ) -#define portENTER_CRITICAL() vPortEnterCritical() -#define portEXIT_CRITICAL() vPortExitCritical() - -/*-----------------------------------------------------------*/ - -/* Task function macros as described on the FreeRTOS.org WEB site. */ -#define portTASK_FUNCTION_PROTO( vFunction, pvParameters ) void vFunction( void *pvParameters ) -#define portTASK_FUNCTION( vFunction, pvParameters ) void vFunction( void *pvParameters ) - -#define portNOP() - -#ifdef __cplusplus -} -#endif - -#endif /* PORTMACRO_H */ - diff --git a/lib/FreeRTOS/Source/portable/GCC/ARM_CM3/port.c b/lib/FreeRTOS/Source/portable/GCC/ARM_CM3/port.c deleted file mode 100644 index 23905b60..00000000 --- a/lib/FreeRTOS/Source/portable/GCC/ARM_CM3/port.c +++ /dev/null @@ -1,717 +0,0 @@ -/* - * FreeRTOS Kernel V10.0.1 - * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * 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. - * - * http://www.FreeRTOS.org - * http://aws.amazon.com/freertos - * - * 1 tab == 4 spaces! - */ - -/*----------------------------------------------------------- - * Implementation of functions defined in portable.h for the ARM CM3 port. - *----------------------------------------------------------*/ - -/* Scheduler includes. */ -#include "FreeRTOS.h" -#include "task.h" - -/* For backward compatibility, ensure configKERNEL_INTERRUPT_PRIORITY is -defined. The value should also ensure backward compatibility. -FreeRTOS.org versions prior to V4.4.0 did not include this definition. */ -#ifndef configKERNEL_INTERRUPT_PRIORITY - #define configKERNEL_INTERRUPT_PRIORITY 255 -#endif - -#ifndef configSYSTICK_CLOCK_HZ - #define configSYSTICK_CLOCK_HZ configCPU_CLOCK_HZ - /* Ensure the SysTick is clocked at the same frequency as the core. */ - #define portNVIC_SYSTICK_CLK_BIT ( 1UL << 2UL ) -#else - /* The way the SysTick is clocked is not modified in case it is not the same - as the core. */ - #define portNVIC_SYSTICK_CLK_BIT ( 0 ) -#endif - -/* Constants required to manipulate the core. Registers first... */ -#define portNVIC_SYSTICK_CTRL_REG ( * ( ( volatile uint32_t * ) 0xe000e010 ) ) -#define portNVIC_SYSTICK_LOAD_REG ( * ( ( volatile uint32_t * ) 0xe000e014 ) ) -#define portNVIC_SYSTICK_CURRENT_VALUE_REG ( * ( ( volatile uint32_t * ) 0xe000e018 ) ) -#define portNVIC_SYSPRI2_REG ( * ( ( volatile uint32_t * ) 0xe000ed20 ) ) -/* ...then bits in the registers. */ -#define portNVIC_SYSTICK_INT_BIT ( 1UL << 1UL ) -#define portNVIC_SYSTICK_ENABLE_BIT ( 1UL << 0UL ) -#define portNVIC_SYSTICK_COUNT_FLAG_BIT ( 1UL << 16UL ) -#define portNVIC_PENDSVCLEAR_BIT ( 1UL << 27UL ) -#define portNVIC_PEND_SYSTICK_CLEAR_BIT ( 1UL << 25UL ) - -#define portNVIC_PENDSV_PRI ( ( ( uint32_t ) configKERNEL_INTERRUPT_PRIORITY ) << 16UL ) -#define portNVIC_SYSTICK_PRI ( ( ( uint32_t ) configKERNEL_INTERRUPT_PRIORITY ) << 24UL ) - -/* Constants required to check the validity of an interrupt priority. */ -#define portFIRST_USER_INTERRUPT_NUMBER ( 16 ) -#define portNVIC_IP_REGISTERS_OFFSET_16 ( 0xE000E3F0 ) -#define portAIRCR_REG ( * ( ( volatile uint32_t * ) 0xE000ED0C ) ) -#define portMAX_8_BIT_VALUE ( ( uint8_t ) 0xff ) -#define portTOP_BIT_OF_BYTE ( ( uint8_t ) 0x80 ) -#define portMAX_PRIGROUP_BITS ( ( uint8_t ) 7 ) -#define portPRIORITY_GROUP_MASK ( 0x07UL << 8UL ) -#define portPRIGROUP_SHIFT ( 8UL ) - -/* Masks off all bits but the VECTACTIVE bits in the ICSR register. */ -#define portVECTACTIVE_MASK ( 0xFFUL ) - -/* Constants required to set up the initial stack. */ -#define portINITIAL_XPSR ( 0x01000000UL ) - -/* The systick is a 24-bit counter. */ -#define portMAX_24_BIT_NUMBER ( 0xffffffUL ) - -/* A fiddle factor to estimate the number of SysTick counts that would have -occurred while the SysTick counter is stopped during tickless idle -calculations. */ -#define portMISSED_COUNTS_FACTOR ( 45UL ) - -/* For strict compliance with the Cortex-M spec the task start address should -have bit-0 clear, as it is loaded into the PC on exit from an ISR. */ -#define portSTART_ADDRESS_MASK ( ( StackType_t ) 0xfffffffeUL ) - -/* Let the user override the pre-loading of the initial LR with the address of -prvTaskExitError() in case it messes up unwinding of the stack in the -debugger. */ -#ifdef configTASK_RETURN_ADDRESS - #define portTASK_RETURN_ADDRESS configTASK_RETURN_ADDRESS -#else - #define portTASK_RETURN_ADDRESS prvTaskExitError -#endif - -/* - * Setup the timer to generate the tick interrupts. The implementation in this - * file is weak to allow application writers to change the timer used to - * generate the tick interrupt. - */ -void vPortSetupTimerInterrupt( void ); - -/* - * Exception handlers. - */ -void xPortPendSVHandler( void ) __attribute__ (( naked )); -void xPortSysTickHandler( void ); -void vPortSVCHandler( void ) __attribute__ (( naked )); - -/* - * Start first task is a separate function so it can be tested in isolation. - */ -static void prvPortStartFirstTask( void ) __attribute__ (( naked )); - -/* - * Used to catch tasks that attempt to return from their implementing function. - */ -static void prvTaskExitError( void ); - -/*-----------------------------------------------------------*/ - -/* Each task maintains its own interrupt status in the critical nesting -variable. */ -static UBaseType_t uxCriticalNesting = 0xaaaaaaaa; - -/* - * The number of SysTick increments that make up one tick period. - */ -#if( configUSE_TICKLESS_IDLE == 1 ) - static uint32_t ulTimerCountsForOneTick = 0; -#endif /* configUSE_TICKLESS_IDLE */ - -/* - * The maximum number of tick periods that can be suppressed is limited by the - * 24 bit resolution of the SysTick timer. - */ -#if( configUSE_TICKLESS_IDLE == 1 ) - static uint32_t xMaximumPossibleSuppressedTicks = 0; -#endif /* configUSE_TICKLESS_IDLE */ - -/* - * Compensate for the CPU cycles that pass while the SysTick is stopped (low - * power functionality only. - */ -#if( configUSE_TICKLESS_IDLE == 1 ) - static uint32_t ulStoppedTimerCompensation = 0; -#endif /* configUSE_TICKLESS_IDLE */ - -/* - * Used by the portASSERT_IF_INTERRUPT_PRIORITY_INVALID() macro to ensure - * FreeRTOS API functions are not called from interrupts that have been assigned - * a priority above configMAX_SYSCALL_INTERRUPT_PRIORITY. - */ -#if( configASSERT_DEFINED == 1 ) - static uint8_t ucMaxSysCallPriority = 0; - static uint32_t ulMaxPRIGROUPValue = 0; - static const volatile uint8_t * const pcInterruptPriorityRegisters = ( const volatile uint8_t * const ) portNVIC_IP_REGISTERS_OFFSET_16; -#endif /* configASSERT_DEFINED */ - -/*-----------------------------------------------------------*/ - -/* - * See header file for description. - */ -StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters ) -{ - /* Simulate the stack frame as it would be created by a context switch - interrupt. */ - pxTopOfStack--; /* Offset added to account for the way the MCU uses the stack on entry/exit of interrupts. */ - *pxTopOfStack = portINITIAL_XPSR; /* xPSR */ - pxTopOfStack--; - *pxTopOfStack = ( ( StackType_t ) pxCode ) & portSTART_ADDRESS_MASK; /* PC */ - pxTopOfStack--; - *pxTopOfStack = ( StackType_t ) portTASK_RETURN_ADDRESS; /* LR */ - pxTopOfStack -= 5; /* R12, R3, R2 and R1. */ - *pxTopOfStack = ( StackType_t ) pvParameters; /* R0 */ - pxTopOfStack -= 8; /* R11, R10, R9, R8, R7, R6, R5 and R4. */ - - return pxTopOfStack; -} -/*-----------------------------------------------------------*/ - -static void prvTaskExitError( void ) -{ -volatile uint32_t ulDummy = 0UL; - - /* A function that implements a task must not exit or attempt to return to - its caller as there is nothing to return to. If a task wants to exit it - should instead call vTaskDelete( NULL ). - - Artificially force an assert() to be triggered if configASSERT() is - defined, then stop here so application writers can catch the error. */ - configASSERT( uxCriticalNesting == ~0UL ); - portDISABLE_INTERRUPTS(); - while( ulDummy == 0 ) - { - /* This file calls prvTaskExitError() after the scheduler has been - started to remove a compiler warning about the function being defined - but never called. ulDummy is used purely to quieten other warnings - about code appearing after this function is called - making ulDummy - volatile makes the compiler think the function could return and - therefore not output an 'unreachable code' warning for code that appears - after it. */ - } -} -/*-----------------------------------------------------------*/ - -void vPortSVCHandler( void ) -{ - __asm volatile ( - " ldr r3, pxCurrentTCBConst2 \n" /* Restore the context. */ - " ldr r1, [r3] \n" /* Use pxCurrentTCBConst to get the pxCurrentTCB address. */ - " ldr r0, [r1] \n" /* The first item in pxCurrentTCB is the task top of stack. */ - " ldmia r0!, {r4-r11} \n" /* Pop the registers that are not automatically saved on exception entry and the critical nesting count. */ - " msr psp, r0 \n" /* Restore the task stack pointer. */ - " isb \n" - " mov r0, #0 \n" - " msr basepri, r0 \n" - " orr r14, #0xd \n" - " bx r14 \n" - " \n" - " .align 4 \n" - "pxCurrentTCBConst2: .word pxCurrentTCB \n" - ); -} -/*-----------------------------------------------------------*/ - -static void prvPortStartFirstTask( void ) -{ - __asm volatile( - " ldr r0, =0xE000ED08 \n" /* Use the NVIC offset register to locate the stack. */ - " ldr r0, [r0] \n" - " ldr r0, [r0] \n" - " msr msp, r0 \n" /* Set the msp back to the start of the stack. */ - " cpsie i \n" /* Globally enable interrupts. */ - " cpsie f \n" - " dsb \n" - " isb \n" - " svc 0 \n" /* System call to start first task. */ - " nop \n" - ); -} -/*-----------------------------------------------------------*/ - -/* - * See header file for description. - */ -BaseType_t xPortStartScheduler( void ) -{ - /* configMAX_SYSCALL_INTERRUPT_PRIORITY must not be set to 0. - See http://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */ - configASSERT( configMAX_SYSCALL_INTERRUPT_PRIORITY ); - - #if( configASSERT_DEFINED == 1 ) - { - volatile uint32_t ulOriginalPriority; - volatile uint8_t * const pucFirstUserPriorityRegister = ( volatile uint8_t * const ) ( portNVIC_IP_REGISTERS_OFFSET_16 + portFIRST_USER_INTERRUPT_NUMBER ); - volatile uint8_t ucMaxPriorityValue; - - /* Determine the maximum priority from which ISR safe FreeRTOS API - functions can be called. ISR safe functions are those that end in - "FromISR". FreeRTOS maintains separate thread and ISR API functions to - ensure interrupt entry is as fast and simple as possible. - - Save the interrupt priority value that is about to be clobbered. */ - ulOriginalPriority = *pucFirstUserPriorityRegister; - - /* Determine the number of priority bits available. First write to all - possible bits. */ - *pucFirstUserPriorityRegister = portMAX_8_BIT_VALUE; - - /* Read the value back to see how many bits stuck. */ - ucMaxPriorityValue = *pucFirstUserPriorityRegister; - - /* Use the same mask on the maximum system call priority. */ - ucMaxSysCallPriority = configMAX_SYSCALL_INTERRUPT_PRIORITY & ucMaxPriorityValue; - - /* Calculate the maximum acceptable priority group value for the number - of bits read back. */ - ulMaxPRIGROUPValue = portMAX_PRIGROUP_BITS; - while( ( ucMaxPriorityValue & portTOP_BIT_OF_BYTE ) == portTOP_BIT_OF_BYTE ) - { - ulMaxPRIGROUPValue--; - ucMaxPriorityValue <<= ( uint8_t ) 0x01; - } - - #ifdef __NVIC_PRIO_BITS - { - /* Check the CMSIS configuration that defines the number of - priority bits matches the number of priority bits actually queried - from the hardware. */ - configASSERT( ( portMAX_PRIGROUP_BITS - ulMaxPRIGROUPValue ) == __NVIC_PRIO_BITS ); - } - #endif - - #ifdef configPRIO_BITS - { - /* Check the FreeRTOS configuration that defines the number of - priority bits matches the number of priority bits actually queried - from the hardware. */ - configASSERT( ( portMAX_PRIGROUP_BITS - ulMaxPRIGROUPValue ) == configPRIO_BITS ); - } - #endif - - /* Shift the priority group value back to its position within the AIRCR - register. */ - ulMaxPRIGROUPValue <<= portPRIGROUP_SHIFT; - ulMaxPRIGROUPValue &= portPRIORITY_GROUP_MASK; - - /* Restore the clobbered interrupt priority register to its original - value. */ - *pucFirstUserPriorityRegister = ulOriginalPriority; - } - #endif /* conifgASSERT_DEFINED */ - - /* Make PendSV and SysTick the lowest priority interrupts. */ - portNVIC_SYSPRI2_REG |= portNVIC_PENDSV_PRI; - portNVIC_SYSPRI2_REG |= portNVIC_SYSTICK_PRI; - - /* Start the timer that generates the tick ISR. Interrupts are disabled - here already. */ - vPortSetupTimerInterrupt(); - - /* Initialise the critical nesting count ready for the first task. */ - uxCriticalNesting = 0; - - /* Start the first task. */ - prvPortStartFirstTask(); - - /* Should never get here as the tasks will now be executing! Call the task - exit error function to prevent compiler warnings about a static function - not being called in the case that the application writer overrides this - functionality by defining configTASK_RETURN_ADDRESS. Call - vTaskSwitchContext() so link time optimisation does not remove the - symbol. */ - vTaskSwitchContext(); - prvTaskExitError(); - - /* Should not get here! */ - return 0; -} -/*-----------------------------------------------------------*/ - -void vPortEndScheduler( void ) -{ - /* Not implemented in ports where there is nothing to return to. - Artificially force an assert. */ - configASSERT( uxCriticalNesting == 1000UL ); -} -/*-----------------------------------------------------------*/ - -void vPortEnterCritical( void ) -{ - portDISABLE_INTERRUPTS(); - uxCriticalNesting++; - - /* This is not the interrupt safe version of the enter critical function so - assert() if it is being called from an interrupt context. Only API - functions that end in "FromISR" can be used in an interrupt. Only assert if - the critical nesting count is 1 to protect against recursive calls if the - assert function also uses a critical section. */ - if( uxCriticalNesting == 1 ) - { - configASSERT( ( portNVIC_INT_CTRL_REG & portVECTACTIVE_MASK ) == 0 ); - } -} -/*-----------------------------------------------------------*/ - -void vPortExitCritical( void ) -{ - configASSERT( uxCriticalNesting ); - uxCriticalNesting--; - if( uxCriticalNesting == 0 ) - { - portENABLE_INTERRUPTS(); - } -} -/*-----------------------------------------------------------*/ - -void xPortPendSVHandler( void ) -{ - /* This is a naked function. */ - - __asm volatile - ( - " mrs r0, psp \n" - " isb \n" - " \n" - " ldr r3, pxCurrentTCBConst \n" /* Get the location of the current TCB. */ - " ldr r2, [r3] \n" - " \n" - " stmdb r0!, {r4-r11} \n" /* Save the remaining registers. */ - " str r0, [r2] \n" /* Save the new top of stack into the first member of the TCB. */ - " \n" - " stmdb sp!, {r3, r14} \n" - " mov r0, %0 \n" - " msr basepri, r0 \n" - " bl vTaskSwitchContext \n" - " mov r0, #0 \n" - " msr basepri, r0 \n" - " ldmia sp!, {r3, r14} \n" - " \n" /* Restore the context, including the critical nesting count. */ - " ldr r1, [r3] \n" - " ldr r0, [r1] \n" /* The first item in pxCurrentTCB is the task top of stack. */ - " ldmia r0!, {r4-r11} \n" /* Pop the registers. */ - " msr psp, r0 \n" - " isb \n" - " bx r14 \n" - " \n" - " .align 4 \n" - "pxCurrentTCBConst: .word pxCurrentTCB \n" - ::"i"(configMAX_SYSCALL_INTERRUPT_PRIORITY) - ); -} -/*-----------------------------------------------------------*/ - -void xPortSysTickHandler( void ) -{ - /* The SysTick runs at the lowest interrupt priority, so when this interrupt - executes all interrupts must be unmasked. There is therefore no need to - save and then restore the interrupt mask value as its value is already - known. */ - portDISABLE_INTERRUPTS(); - { - /* Increment the RTOS tick. */ - if( xTaskIncrementTick() != pdFALSE ) - { - /* A context switch is required. Context switching is performed in - the PendSV interrupt. Pend the PendSV interrupt. */ - portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT; - } - } - portENABLE_INTERRUPTS(); -} -/*-----------------------------------------------------------*/ - -#if( configUSE_TICKLESS_IDLE == 1 ) - - __attribute__((weak)) void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime ) - { - uint32_t ulReloadValue, ulCompleteTickPeriods, ulCompletedSysTickDecrements; - TickType_t xModifiableIdleTime; - - /* Make sure the SysTick reload value does not overflow the counter. */ - if( xExpectedIdleTime > xMaximumPossibleSuppressedTicks ) - { - xExpectedIdleTime = xMaximumPossibleSuppressedTicks; - } - - /* Stop the SysTick momentarily. The time the SysTick is stopped for - is accounted for as best it can be, but using the tickless mode will - inevitably result in some tiny drift of the time maintained by the - kernel with respect to calendar time. */ - portNVIC_SYSTICK_CTRL_REG &= ~portNVIC_SYSTICK_ENABLE_BIT; - - /* Calculate the reload value required to wait xExpectedIdleTime - tick periods. -1 is used because this code will execute part way - through one of the tick periods. */ - ulReloadValue = portNVIC_SYSTICK_CURRENT_VALUE_REG + ( ulTimerCountsForOneTick * ( xExpectedIdleTime - 1UL ) ); - if( ulReloadValue > ulStoppedTimerCompensation ) - { - ulReloadValue -= ulStoppedTimerCompensation; - } - - /* Enter a critical section but don't use the taskENTER_CRITICAL() - method as that will mask interrupts that should exit sleep mode. */ - __asm volatile( "cpsid i" ::: "memory" ); - __asm volatile( "dsb" ); - __asm volatile( "isb" ); - - /* If a context switch is pending or a task is waiting for the scheduler - to be unsuspended then abandon the low power entry. */ - if( eTaskConfirmSleepModeStatus() == eAbortSleep ) - { - /* Restart from whatever is left in the count register to complete - this tick period. */ - portNVIC_SYSTICK_LOAD_REG = portNVIC_SYSTICK_CURRENT_VALUE_REG; - - /* Restart SysTick. */ - portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT; - - /* Reset the reload register to the value required for normal tick - periods. */ - portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL; - - /* Re-enable interrupts - see comments above the cpsid instruction() - above. */ - __asm volatile( "cpsie i" ::: "memory" ); - } - else - { - /* Set the new reload value. */ - portNVIC_SYSTICK_LOAD_REG = ulReloadValue; - - /* Clear the SysTick count flag and set the count value back to - zero. */ - portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL; - - /* Restart SysTick. */ - portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT; - - /* Sleep until something happens. configPRE_SLEEP_PROCESSING() can - set its parameter to 0 to indicate that its implementation contains - its own wait for interrupt or wait for event instruction, and so wfi - should not be executed again. However, the original expected idle - time variable must remain unmodified, so a copy is taken. */ - xModifiableIdleTime = xExpectedIdleTime; - configPRE_SLEEP_PROCESSING( xModifiableIdleTime ); - if( xModifiableIdleTime > 0 ) - { - __asm volatile( "dsb" ::: "memory" ); - __asm volatile( "wfi" ); - __asm volatile( "isb" ); - } - configPOST_SLEEP_PROCESSING( xExpectedIdleTime ); - - /* Re-enable interrupts to allow the interrupt that brought the MCU - out of sleep mode to execute immediately. see comments above - __disable_interrupt() call above. */ - __asm volatile( "cpsie i" ::: "memory" ); - __asm volatile( "dsb" ); - __asm volatile( "isb" ); - - /* Disable interrupts again because the clock is about to be stopped - and interrupts that execute while the clock is stopped will increase - any slippage between the time maintained by the RTOS and calendar - time. */ - __asm volatile( "cpsid i" ::: "memory" ); - __asm volatile( "dsb" ); - __asm volatile( "isb" ); - - /* Disable the SysTick clock without reading the - portNVIC_SYSTICK_CTRL_REG register to ensure the - portNVIC_SYSTICK_COUNT_FLAG_BIT is not cleared if it is set. Again, - the time the SysTick is stopped for is accounted for as best it can - be, but using the tickless mode will inevitably result in some tiny - drift of the time maintained by the kernel with respect to calendar - time*/ - portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT ); - - /* Determine if the SysTick clock has already counted to zero and - been set back to the current reload value (the reload back being - correct for the entire expected idle time) or if the SysTick is yet - to count to zero (in which case an interrupt other than the SysTick - must have brought the system out of sleep mode). */ - if( ( portNVIC_SYSTICK_CTRL_REG & portNVIC_SYSTICK_COUNT_FLAG_BIT ) != 0 ) - { - uint32_t ulCalculatedLoadValue; - - /* The tick interrupt is already pending, and the SysTick count - reloaded with ulReloadValue. Reset the - portNVIC_SYSTICK_LOAD_REG with whatever remains of this tick - period. */ - ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL ) - ( ulReloadValue - portNVIC_SYSTICK_CURRENT_VALUE_REG ); - - /* Don't allow a tiny value, or values that have somehow - underflowed because the post sleep hook did something - that took too long. */ - if( ( ulCalculatedLoadValue < ulStoppedTimerCompensation ) || ( ulCalculatedLoadValue > ulTimerCountsForOneTick ) ) - { - ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL ); - } - - portNVIC_SYSTICK_LOAD_REG = ulCalculatedLoadValue; - - /* As the pending tick will be processed as soon as this - function exits, the tick value maintained by the tick is stepped - forward by one less than the time spent waiting. */ - ulCompleteTickPeriods = xExpectedIdleTime - 1UL; - } - else - { - /* Something other than the tick interrupt ended the sleep. - Work out how long the sleep lasted rounded to complete tick - periods (not the ulReload value which accounted for part - ticks). */ - ulCompletedSysTickDecrements = ( xExpectedIdleTime * ulTimerCountsForOneTick ) - portNVIC_SYSTICK_CURRENT_VALUE_REG; - - /* How many complete tick periods passed while the processor - was waiting? */ - ulCompleteTickPeriods = ulCompletedSysTickDecrements / ulTimerCountsForOneTick; - - /* The reload value is set to whatever fraction of a single tick - period remains. */ - portNVIC_SYSTICK_LOAD_REG = ( ( ulCompleteTickPeriods + 1UL ) * ulTimerCountsForOneTick ) - ulCompletedSysTickDecrements; - } - - /* Restart SysTick so it runs from portNVIC_SYSTICK_LOAD_REG - again, then set portNVIC_SYSTICK_LOAD_REG back to its standard - value. */ - portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL; - portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT; - vTaskStepTick( ulCompleteTickPeriods ); - portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL; - - /* Exit with interrpts enabled. */ - __asm volatile( "cpsie i" ::: "memory" ); - } - } - -#endif /* configUSE_TICKLESS_IDLE */ -/*-----------------------------------------------------------*/ - -/* - * Setup the systick timer to generate the tick interrupts at the required - * frequency. - */ -__attribute__(( weak )) void vPortSetupTimerInterrupt( void ) -{ - /* Calculate the constants required to configure the tick interrupt. */ - #if( configUSE_TICKLESS_IDLE == 1 ) - { - ulTimerCountsForOneTick = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ ); - xMaximumPossibleSuppressedTicks = portMAX_24_BIT_NUMBER / ulTimerCountsForOneTick; - ulStoppedTimerCompensation = portMISSED_COUNTS_FACTOR / ( configCPU_CLOCK_HZ / configSYSTICK_CLOCK_HZ ); - } - #endif /* configUSE_TICKLESS_IDLE */ - - /* Stop and clear the SysTick. */ - portNVIC_SYSTICK_CTRL_REG = 0UL; - portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL; - - /* Configure SysTick to interrupt at the requested rate. */ - portNVIC_SYSTICK_LOAD_REG = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ ) - 1UL; - portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT ); -} -/*-----------------------------------------------------------*/ - -#if( configASSERT_DEFINED == 1 ) - - void vPortValidateInterruptPriority( void ) - { - uint32_t ulCurrentInterrupt; - uint8_t ucCurrentPriority; - - /* Obtain the number of the currently executing interrupt. */ - __asm volatile( "mrs %0, ipsr" : "=r"( ulCurrentInterrupt ) :: "memory" ); - - /* Is the interrupt number a user defined interrupt? */ - if( ulCurrentInterrupt >= portFIRST_USER_INTERRUPT_NUMBER ) - { - /* Look up the interrupt's priority. */ - ucCurrentPriority = pcInterruptPriorityRegisters[ ulCurrentInterrupt ]; - - /* The following assertion will fail if a service routine (ISR) for - an interrupt that has been assigned a priority above - configMAX_SYSCALL_INTERRUPT_PRIORITY calls an ISR safe FreeRTOS API - function. ISR safe FreeRTOS API functions must *only* be called - from interrupts that have been assigned a priority at or below - configMAX_SYSCALL_INTERRUPT_PRIORITY. - - Numerically low interrupt priority numbers represent logically high - interrupt priorities, therefore the priority of the interrupt must - be set to a value equal to or numerically *higher* than - configMAX_SYSCALL_INTERRUPT_PRIORITY. - - Interrupts that use the FreeRTOS API must not be left at their - default priority of zero as that is the highest possible priority, - which is guaranteed to be above configMAX_SYSCALL_INTERRUPT_PRIORITY, - and therefore also guaranteed to be invalid. - - FreeRTOS maintains separate thread and ISR API functions to ensure - interrupt entry is as fast and simple as possible. - - The following links provide detailed information: - http://www.freertos.org/RTOS-Cortex-M3-M4.html - http://www.freertos.org/FAQHelp.html */ - configASSERT( ucCurrentPriority >= ucMaxSysCallPriority ); - } - - /* Priority grouping: The interrupt controller (NVIC) allows the bits - that define each interrupt's priority to be split between bits that - define the interrupt's pre-emption priority bits and bits that define - the interrupt's sub-priority. For simplicity all bits must be defined - to be pre-emption priority bits. The following assertion will fail if - this is not the case (if some bits represent a sub-priority). - - If the application only uses CMSIS libraries for interrupt - configuration then the correct setting can be achieved on all Cortex-M - devices by calling NVIC_SetPriorityGrouping( 0 ); before starting the - scheduler. Note however that some vendor specific peripheral libraries - assume a non-zero priority group setting, in which cases using a value - of zero will result in unpredictable behaviour. */ - configASSERT( ( portAIRCR_REG & portPRIORITY_GROUP_MASK ) <= ulMaxPRIGROUPValue ); - } - -#endif /* configASSERT_DEFINED */ - - - - - - - - - - - - - - - - - - - - - diff --git a/lib/FreeRTOS/Source/portable/GCC/ARM_CM3/portmacro.h b/lib/FreeRTOS/Source/portable/GCC/ARM_CM3/portmacro.h deleted file mode 100644 index 77a5d272..00000000 --- a/lib/FreeRTOS/Source/portable/GCC/ARM_CM3/portmacro.h +++ /dev/null @@ -1,242 +0,0 @@ -/* - * FreeRTOS Kernel V10.0.1 - * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * 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. - * - * http://www.FreeRTOS.org - * http://aws.amazon.com/freertos - * - * 1 tab == 4 spaces! - */ - - -#ifndef PORTMACRO_H -#define PORTMACRO_H - -#ifdef __cplusplus -extern "C" { -#endif - -/*----------------------------------------------------------- - * Port specific definitions. - * - * The settings in this file configure FreeRTOS correctly for the - * given hardware and compiler. - * - * These settings should not be altered. - *----------------------------------------------------------- - */ - -/* Type definitions. */ -#define portCHAR char -#define portFLOAT float -#define portDOUBLE double -#define portLONG long -#define portSHORT short -#define portSTACK_TYPE uint32_t -#define portBASE_TYPE long - -typedef portSTACK_TYPE StackType_t; -typedef long BaseType_t; -typedef unsigned long UBaseType_t; - -#if( configUSE_16_BIT_TICKS == 1 ) - typedef uint16_t TickType_t; - #define portMAX_DELAY ( TickType_t ) 0xffff -#else - typedef uint32_t TickType_t; - #define portMAX_DELAY ( TickType_t ) 0xffffffffUL - - /* 32-bit tick type on a 32-bit architecture, so reads of the tick count do - not need to be guarded with a critical section. */ - #define portTICK_TYPE_IS_ATOMIC 1 -#endif -/*-----------------------------------------------------------*/ - -/* Architecture specifics. */ -#define portSTACK_GROWTH ( -1 ) -#define portTICK_PERIOD_MS ( ( TickType_t ) 1000 / configTICK_RATE_HZ ) -#define portBYTE_ALIGNMENT 8 -/*-----------------------------------------------------------*/ - -/* Scheduler utilities. */ -#define portYIELD() \ -{ \ - /* Set a PendSV to request a context switch. */ \ - portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT; \ - \ - /* Barriers are normally not required but do ensure the code is completely \ - within the specified behaviour for the architecture. */ \ - __asm volatile( "dsb" ::: "memory" ); \ - __asm volatile( "isb" ); \ -} - -#define portNVIC_INT_CTRL_REG ( * ( ( volatile uint32_t * ) 0xe000ed04 ) ) -#define portNVIC_PENDSVSET_BIT ( 1UL << 28UL ) -#define portEND_SWITCHING_ISR( xSwitchRequired ) if( xSwitchRequired != pdFALSE ) portYIELD() -#define portYIELD_FROM_ISR( x ) portEND_SWITCHING_ISR( x ) -/*-----------------------------------------------------------*/ - -/* Critical section management. */ -extern void vPortEnterCritical( void ); -extern void vPortExitCritical( void ); -#define portSET_INTERRUPT_MASK_FROM_ISR() ulPortRaiseBASEPRI() -#define portCLEAR_INTERRUPT_MASK_FROM_ISR(x) vPortSetBASEPRI(x) -#define portDISABLE_INTERRUPTS() vPortRaiseBASEPRI() -#define portENABLE_INTERRUPTS() vPortSetBASEPRI(0) -#define portENTER_CRITICAL() vPortEnterCritical() -#define portEXIT_CRITICAL() vPortExitCritical() - -/*-----------------------------------------------------------*/ - -/* Task function macros as described on the FreeRTOS.org WEB site. These are -not necessary for to use this port. They are defined so the common demo files -(which build with all the ports) will build. */ -#define portTASK_FUNCTION_PROTO( vFunction, pvParameters ) void vFunction( void *pvParameters ) -#define portTASK_FUNCTION( vFunction, pvParameters ) void vFunction( void *pvParameters ) -/*-----------------------------------------------------------*/ - -/* Tickless idle/low power functionality. */ -#ifndef portSUPPRESS_TICKS_AND_SLEEP - extern void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime ); - #define portSUPPRESS_TICKS_AND_SLEEP( xExpectedIdleTime ) vPortSuppressTicksAndSleep( xExpectedIdleTime ) -#endif -/*-----------------------------------------------------------*/ - -/* Architecture specific optimisations. */ -#ifndef configUSE_PORT_OPTIMISED_TASK_SELECTION - #define configUSE_PORT_OPTIMISED_TASK_SELECTION 1 -#endif - -#if configUSE_PORT_OPTIMISED_TASK_SELECTION == 1 - - /* Generic helper function. */ - __attribute__( ( always_inline ) ) static inline uint8_t ucPortCountLeadingZeros( uint32_t ulBitmap ) - { - uint8_t ucReturn; - - __asm volatile ( "clz %0, %1" : "=r" ( ucReturn ) : "r" ( ulBitmap ) : "memory" ); - return ucReturn; - } - - /* Check the configuration. */ - #if( configMAX_PRIORITIES > 32 ) - #error configUSE_PORT_OPTIMISED_TASK_SELECTION can only be set to 1 when configMAX_PRIORITIES is less than or equal to 32. It is very rare that a system requires more than 10 to 15 difference priorities as tasks that share a priority will time slice. - #endif - - /* Store/clear the ready priorities in a bit map. */ - #define portRECORD_READY_PRIORITY( uxPriority, uxReadyPriorities ) ( uxReadyPriorities ) |= ( 1UL << ( uxPriority ) ) - #define portRESET_READY_PRIORITY( uxPriority, uxReadyPriorities ) ( uxReadyPriorities ) &= ~( 1UL << ( uxPriority ) ) - - /*-----------------------------------------------------------*/ - - #define portGET_HIGHEST_PRIORITY( uxTopPriority, uxReadyPriorities ) uxTopPriority = ( 31UL - ( uint32_t ) ucPortCountLeadingZeros( ( uxReadyPriorities ) ) ) - -#endif /* configUSE_PORT_OPTIMISED_TASK_SELECTION */ - -/*-----------------------------------------------------------*/ - -#ifdef configASSERT - void vPortValidateInterruptPriority( void ); - #define portASSERT_IF_INTERRUPT_PRIORITY_INVALID() vPortValidateInterruptPriority() -#endif - -/* portNOP() is not required by this port. */ -#define portNOP() - -#define portINLINE __inline - -#ifndef portFORCE_INLINE - #define portFORCE_INLINE inline __attribute__(( always_inline)) -#endif - -portFORCE_INLINE static BaseType_t xPortIsInsideInterrupt( void ) -{ -uint32_t ulCurrentInterrupt; -BaseType_t xReturn; - - /* Obtain the number of the currently executing interrupt. */ - __asm volatile( "mrs %0, ipsr" : "=r"( ulCurrentInterrupt ) :: "memory" ); - - if( ulCurrentInterrupt == 0 ) - { - xReturn = pdFALSE; - } - else - { - xReturn = pdTRUE; - } - - return xReturn; -} - -/*-----------------------------------------------------------*/ - -portFORCE_INLINE static void vPortRaiseBASEPRI( void ) -{ -uint32_t ulNewBASEPRI; - - __asm volatile - ( - " mov %0, %1 \n" \ - " msr basepri, %0 \n" \ - " isb \n" \ - " dsb \n" \ - :"=r" (ulNewBASEPRI) : "i" ( configMAX_SYSCALL_INTERRUPT_PRIORITY ) : "memory" - ); -} - -/*-----------------------------------------------------------*/ - -portFORCE_INLINE static uint32_t ulPortRaiseBASEPRI( void ) -{ -uint32_t ulOriginalBASEPRI, ulNewBASEPRI; - - __asm volatile - ( - " mrs %0, basepri \n" \ - " mov %1, %2 \n" \ - " msr basepri, %1 \n" \ - " isb \n" \ - " dsb \n" \ - :"=r" (ulOriginalBASEPRI), "=r" (ulNewBASEPRI) : "i" ( configMAX_SYSCALL_INTERRUPT_PRIORITY ) : "memory" - ); - - /* This return will not be reached but is necessary to prevent compiler - warnings. */ - return ulOriginalBASEPRI; -} -/*-----------------------------------------------------------*/ - -portFORCE_INLINE static void vPortSetBASEPRI( uint32_t ulNewMaskValue ) -{ - __asm volatile - ( - " msr basepri, %0 " :: "r" ( ulNewMaskValue ) : "memory" - ); -} -/*-----------------------------------------------------------*/ - - -#ifdef __cplusplus -} -#endif - -#endif /* PORTMACRO_H */ - diff --git a/lib/FreeRTOS/Source/portable/GCC/ARM_CM4F/port.c b/lib/FreeRTOS/Source/portable/GCC/ARM_CM4F/port.c deleted file mode 100644 index 225c056d..00000000 --- a/lib/FreeRTOS/Source/portable/GCC/ARM_CM4F/port.c +++ /dev/null @@ -1,775 +0,0 @@ -/* - * FreeRTOS Kernel V10.0.1 - * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * 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. - * - * http://www.FreeRTOS.org - * http://aws.amazon.com/freertos - * - * 1 tab == 4 spaces! - */ - -/*----------------------------------------------------------- - * Implementation of functions defined in portable.h for the ARM CM4F port. - *----------------------------------------------------------*/ - -/* Scheduler includes. */ -#include "FreeRTOS.h" -#include "task.h" - -#ifndef __VFP_FP__ - #error This port can only be used when the project options are configured to enable hardware floating point support. -#endif - -#ifndef configSYSTICK_CLOCK_HZ - #define configSYSTICK_CLOCK_HZ configCPU_CLOCK_HZ - /* Ensure the SysTick is clocked at the same frequency as the core. */ - #define portNVIC_SYSTICK_CLK_BIT ( 1UL << 2UL ) -#else - /* The way the SysTick is clocked is not modified in case it is not the same - as the core. */ - #define portNVIC_SYSTICK_CLK_BIT ( 0 ) -#endif - -/* Constants required to manipulate the core. Registers first... */ -#define portNVIC_SYSTICK_CTRL_REG ( * ( ( volatile uint32_t * ) 0xe000e010 ) ) -#define portNVIC_SYSTICK_LOAD_REG ( * ( ( volatile uint32_t * ) 0xe000e014 ) ) -#define portNVIC_SYSTICK_CURRENT_VALUE_REG ( * ( ( volatile uint32_t * ) 0xe000e018 ) ) -#define portNVIC_SYSPRI2_REG ( * ( ( volatile uint32_t * ) 0xe000ed20 ) ) -/* ...then bits in the registers. */ -#define portNVIC_SYSTICK_INT_BIT ( 1UL << 1UL ) -#define portNVIC_SYSTICK_ENABLE_BIT ( 1UL << 0UL ) -#define portNVIC_SYSTICK_COUNT_FLAG_BIT ( 1UL << 16UL ) -#define portNVIC_PENDSVCLEAR_BIT ( 1UL << 27UL ) -#define portNVIC_PEND_SYSTICK_CLEAR_BIT ( 1UL << 25UL ) - -/* Constants used to detect a Cortex-M7 r0p1 core, which should use the ARM_CM7 -r0p1 port. */ -#define portCPUID ( * ( ( volatile uint32_t * ) 0xE000ed00 ) ) -#define portCORTEX_M7_r0p1_ID ( 0x410FC271UL ) -#define portCORTEX_M7_r0p0_ID ( 0x410FC270UL ) - -#define portNVIC_PENDSV_PRI ( ( ( uint32_t ) configKERNEL_INTERRUPT_PRIORITY ) << 16UL ) -#define portNVIC_SYSTICK_PRI ( ( ( uint32_t ) configKERNEL_INTERRUPT_PRIORITY ) << 24UL ) - -/* Constants required to check the validity of an interrupt priority. */ -#define portFIRST_USER_INTERRUPT_NUMBER ( 16 ) -#define portNVIC_IP_REGISTERS_OFFSET_16 ( 0xE000E3F0 ) -#define portAIRCR_REG ( * ( ( volatile uint32_t * ) 0xE000ED0C ) ) -#define portMAX_8_BIT_VALUE ( ( uint8_t ) 0xff ) -#define portTOP_BIT_OF_BYTE ( ( uint8_t ) 0x80 ) -#define portMAX_PRIGROUP_BITS ( ( uint8_t ) 7 ) -#define portPRIORITY_GROUP_MASK ( 0x07UL << 8UL ) -#define portPRIGROUP_SHIFT ( 8UL ) - -/* Masks off all bits but the VECTACTIVE bits in the ICSR register. */ -#define portVECTACTIVE_MASK ( 0xFFUL ) - -/* Constants required to manipulate the VFP. */ -#define portFPCCR ( ( volatile uint32_t * ) 0xe000ef34 ) /* Floating point context control register. */ -#define portASPEN_AND_LSPEN_BITS ( 0x3UL << 30UL ) - -/* Constants required to set up the initial stack. */ -#define portINITIAL_XPSR ( 0x01000000 ) -#define portINITIAL_EXC_RETURN ( 0xfffffffd ) - -/* The systick is a 24-bit counter. */ -#define portMAX_24_BIT_NUMBER ( 0xffffffUL ) - -/* For strict compliance with the Cortex-M spec the task start address should -have bit-0 clear, as it is loaded into the PC on exit from an ISR. */ -#define portSTART_ADDRESS_MASK ( ( StackType_t ) 0xfffffffeUL ) - -/* A fiddle factor to estimate the number of SysTick counts that would have -occurred while the SysTick counter is stopped during tickless idle -calculations. */ -#define portMISSED_COUNTS_FACTOR ( 45UL ) - -/* Let the user override the pre-loading of the initial LR with the address of -prvTaskExitError() in case it messes up unwinding of the stack in the -debugger. */ -#ifdef configTASK_RETURN_ADDRESS - #define portTASK_RETURN_ADDRESS configTASK_RETURN_ADDRESS -#else - #define portTASK_RETURN_ADDRESS prvTaskExitError -#endif - -/* - * Setup the timer to generate the tick interrupts. The implementation in this - * file is weak to allow application writers to change the timer used to - * generate the tick interrupt. - */ -void vPortSetupTimerInterrupt( void ); - -/* - * Exception handlers. - */ -void xPortPendSVHandler( void ) __attribute__ (( naked )); -void xPortSysTickHandler( void ); -void vPortSVCHandler( void ) __attribute__ (( naked )); - -/* - * Start first task is a separate function so it can be tested in isolation. - */ -static void prvPortStartFirstTask( void ) __attribute__ (( naked )); - -/* - * Function to enable the VFP. - */ -static void vPortEnableVFP( void ) __attribute__ (( naked )); - -/* - * Used to catch tasks that attempt to return from their implementing function. - */ -static void prvTaskExitError( void ); - -/*-----------------------------------------------------------*/ - -/* Each task maintains its own interrupt status in the critical nesting -variable. */ -static UBaseType_t uxCriticalNesting = 0xaaaaaaaa; - -/* - * The number of SysTick increments that make up one tick period. - */ -#if( configUSE_TICKLESS_IDLE == 1 ) - static uint32_t ulTimerCountsForOneTick = 0; -#endif /* configUSE_TICKLESS_IDLE */ - -/* - * The maximum number of tick periods that can be suppressed is limited by the - * 24 bit resolution of the SysTick timer. - */ -#if( configUSE_TICKLESS_IDLE == 1 ) - static uint32_t xMaximumPossibleSuppressedTicks = 0; -#endif /* configUSE_TICKLESS_IDLE */ - -/* - * Compensate for the CPU cycles that pass while the SysTick is stopped (low - * power functionality only. - */ -#if( configUSE_TICKLESS_IDLE == 1 ) - static uint32_t ulStoppedTimerCompensation = 0; -#endif /* configUSE_TICKLESS_IDLE */ - -/* - * Used by the portASSERT_IF_INTERRUPT_PRIORITY_INVALID() macro to ensure - * FreeRTOS API functions are not called from interrupts that have been assigned - * a priority above configMAX_SYSCALL_INTERRUPT_PRIORITY. - */ -#if( configASSERT_DEFINED == 1 ) - static uint8_t ucMaxSysCallPriority = 0; - static uint32_t ulMaxPRIGROUPValue = 0; - static const volatile uint8_t * const pcInterruptPriorityRegisters = ( const volatile uint8_t * const ) portNVIC_IP_REGISTERS_OFFSET_16; -#endif /* configASSERT_DEFINED */ - -/*-----------------------------------------------------------*/ - -/* - * See header file for description. - */ -StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters ) -{ - /* Simulate the stack frame as it would be created by a context switch - interrupt. */ - - /* Offset added to account for the way the MCU uses the stack on entry/exit - of interrupts, and to ensure alignment. */ - pxTopOfStack--; - - *pxTopOfStack = portINITIAL_XPSR; /* xPSR */ - pxTopOfStack--; - *pxTopOfStack = ( ( StackType_t ) pxCode ) & portSTART_ADDRESS_MASK; /* PC */ - pxTopOfStack--; - *pxTopOfStack = ( StackType_t ) portTASK_RETURN_ADDRESS; /* LR */ - - /* Save code space by skipping register initialisation. */ - pxTopOfStack -= 5; /* R12, R3, R2 and R1. */ - *pxTopOfStack = ( StackType_t ) pvParameters; /* R0 */ - - /* A save method is being used that requires each task to maintain its - own exec return value. */ - pxTopOfStack--; - *pxTopOfStack = portINITIAL_EXC_RETURN; - - pxTopOfStack -= 8; /* R11, R10, R9, R8, R7, R6, R5 and R4. */ - - return pxTopOfStack; -} -/*-----------------------------------------------------------*/ - -static void prvTaskExitError( void ) -{ -volatile uint32_t ulDummy = 0; - - /* A function that implements a task must not exit or attempt to return to - its caller as there is nothing to return to. If a task wants to exit it - should instead call vTaskDelete( NULL ). - - Artificially force an assert() to be triggered if configASSERT() is - defined, then stop here so application writers can catch the error. */ - configASSERT( uxCriticalNesting == ~0UL ); - portDISABLE_INTERRUPTS(); - while( ulDummy == 0 ) - { - /* This file calls prvTaskExitError() after the scheduler has been - started to remove a compiler warning about the function being defined - but never called. ulDummy is used purely to quieten other warnings - about code appearing after this function is called - making ulDummy - volatile makes the compiler think the function could return and - therefore not output an 'unreachable code' warning for code that appears - after it. */ - } -} -/*-----------------------------------------------------------*/ - -void vPortSVCHandler( void ) -{ - __asm volatile ( - " ldr r3, pxCurrentTCBConst2 \n" /* Restore the context. */ - " ldr r1, [r3] \n" /* Use pxCurrentTCBConst to get the pxCurrentTCB address. */ - " ldr r0, [r1] \n" /* The first item in pxCurrentTCB is the task top of stack. */ - " ldmia r0!, {r4-r11, r14} \n" /* Pop the registers that are not automatically saved on exception entry and the critical nesting count. */ - " msr psp, r0 \n" /* Restore the task stack pointer. */ - " isb \n" - " mov r0, #0 \n" - " msr basepri, r0 \n" - " bx r14 \n" - " \n" - " .align 4 \n" - "pxCurrentTCBConst2: .word pxCurrentTCB \n" - ); -} -/*-----------------------------------------------------------*/ - -static void prvPortStartFirstTask( void ) -{ - /* Start the first task. This also clears the bit that indicates the FPU is - in use in case the FPU was used before the scheduler was started - which - would otherwise result in the unnecessary leaving of space in the SVC stack - for lazy saving of FPU registers. */ - __asm volatile( - " ldr r0, =0xE000ED08 \n" /* Use the NVIC offset register to locate the stack. */ - " ldr r0, [r0] \n" - " ldr r0, [r0] \n" - " msr msp, r0 \n" /* Set the msp back to the start of the stack. */ - " mov r0, #0 \n" /* Clear the bit that indicates the FPU is in use, see comment above. */ - " msr control, r0 \n" - " cpsie i \n" /* Globally enable interrupts. */ - " cpsie f \n" - " dsb \n" - " isb \n" - " svc 0 \n" /* System call to start first task. */ - " nop \n" - ); -} -/*-----------------------------------------------------------*/ - -/* - * See header file for description. - */ -BaseType_t xPortStartScheduler( void ) -{ - /* configMAX_SYSCALL_INTERRUPT_PRIORITY must not be set to 0. - See http://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */ - configASSERT( configMAX_SYSCALL_INTERRUPT_PRIORITY ); - - /* This port can be used on all revisions of the Cortex-M7 core other than - the r0p1 parts. r0p1 parts should use the port from the - /source/portable/GCC/ARM_CM7/r0p1 directory. */ - configASSERT( portCPUID != portCORTEX_M7_r0p1_ID ); - configASSERT( portCPUID != portCORTEX_M7_r0p0_ID ); - - #if( configASSERT_DEFINED == 1 ) - { - volatile uint32_t ulOriginalPriority; - volatile uint8_t * const pucFirstUserPriorityRegister = ( volatile uint8_t * const ) ( portNVIC_IP_REGISTERS_OFFSET_16 + portFIRST_USER_INTERRUPT_NUMBER ); - volatile uint8_t ucMaxPriorityValue; - - /* Determine the maximum priority from which ISR safe FreeRTOS API - functions can be called. ISR safe functions are those that end in - "FromISR". FreeRTOS maintains separate thread and ISR API functions to - ensure interrupt entry is as fast and simple as possible. - - Save the interrupt priority value that is about to be clobbered. */ - ulOriginalPriority = *pucFirstUserPriorityRegister; - - /* Determine the number of priority bits available. First write to all - possible bits. */ - *pucFirstUserPriorityRegister = portMAX_8_BIT_VALUE; - - /* Read the value back to see how many bits stuck. */ - ucMaxPriorityValue = *pucFirstUserPriorityRegister; - - /* Use the same mask on the maximum system call priority. */ - ucMaxSysCallPriority = configMAX_SYSCALL_INTERRUPT_PRIORITY & ucMaxPriorityValue; - - /* Calculate the maximum acceptable priority group value for the number - of bits read back. */ - ulMaxPRIGROUPValue = portMAX_PRIGROUP_BITS; - while( ( ucMaxPriorityValue & portTOP_BIT_OF_BYTE ) == portTOP_BIT_OF_BYTE ) - { - ulMaxPRIGROUPValue--; - ucMaxPriorityValue <<= ( uint8_t ) 0x01; - } - - #ifdef __NVIC_PRIO_BITS - { - /* Check the CMSIS configuration that defines the number of - priority bits matches the number of priority bits actually queried - from the hardware. */ - configASSERT( ( portMAX_PRIGROUP_BITS - ulMaxPRIGROUPValue ) == __NVIC_PRIO_BITS ); - } - #endif - - #ifdef configPRIO_BITS - { - /* Check the FreeRTOS configuration that defines the number of - priority bits matches the number of priority bits actually queried - from the hardware. */ - configASSERT( ( portMAX_PRIGROUP_BITS - ulMaxPRIGROUPValue ) == configPRIO_BITS ); - } - #endif - - /* Shift the priority group value back to its position within the AIRCR - register. */ - ulMaxPRIGROUPValue <<= portPRIGROUP_SHIFT; - ulMaxPRIGROUPValue &= portPRIORITY_GROUP_MASK; - - /* Restore the clobbered interrupt priority register to its original - value. */ - *pucFirstUserPriorityRegister = ulOriginalPriority; - } - #endif /* conifgASSERT_DEFINED */ - - /* Make PendSV and SysTick the lowest priority interrupts. */ - portNVIC_SYSPRI2_REG |= portNVIC_PENDSV_PRI; - portNVIC_SYSPRI2_REG |= portNVIC_SYSTICK_PRI; - - /* Start the timer that generates the tick ISR. Interrupts are disabled - here already. */ - vPortSetupTimerInterrupt(); - - /* Initialise the critical nesting count ready for the first task. */ - uxCriticalNesting = 0; - - /* Ensure the VFP is enabled - it should be anyway. */ - vPortEnableVFP(); - - /* Lazy save always. */ - *( portFPCCR ) |= portASPEN_AND_LSPEN_BITS; - - /* Start the first task. */ - prvPortStartFirstTask(); - - /* Should never get here as the tasks will now be executing! Call the task - exit error function to prevent compiler warnings about a static function - not being called in the case that the application writer overrides this - functionality by defining configTASK_RETURN_ADDRESS. Call - vTaskSwitchContext() so link time optimisation does not remove the - symbol. */ - vTaskSwitchContext(); - prvTaskExitError(); - - /* Should not get here! */ - return 0; -} -/*-----------------------------------------------------------*/ - -void vPortEndScheduler( void ) -{ - /* Not implemented in ports where there is nothing to return to. - Artificially force an assert. */ - configASSERT( uxCriticalNesting == 1000UL ); -} -/*-----------------------------------------------------------*/ - -void vPortEnterCritical( void ) -{ - portDISABLE_INTERRUPTS(); - uxCriticalNesting++; - - /* This is not the interrupt safe version of the enter critical function so - assert() if it is being called from an interrupt context. Only API - functions that end in "FromISR" can be used in an interrupt. Only assert if - the critical nesting count is 1 to protect against recursive calls if the - assert function also uses a critical section. */ - if( uxCriticalNesting == 1 ) - { - configASSERT( ( portNVIC_INT_CTRL_REG & portVECTACTIVE_MASK ) == 0 ); - } -} -/*-----------------------------------------------------------*/ - -void vPortExitCritical( void ) -{ - configASSERT( uxCriticalNesting ); - uxCriticalNesting--; - if( uxCriticalNesting == 0 ) - { - portENABLE_INTERRUPTS(); - } -} -/*-----------------------------------------------------------*/ - -void xPortPendSVHandler( void ) -{ - /* This is a naked function. */ - - __asm volatile - ( - " mrs r0, psp \n" - " isb \n" - " \n" - " ldr r3, pxCurrentTCBConst \n" /* Get the location of the current TCB. */ - " ldr r2, [r3] \n" - " \n" - " tst r14, #0x10 \n" /* Is the task using the FPU context? If so, push high vfp registers. */ - " it eq \n" - " vstmdbeq r0!, {s16-s31} \n" - " \n" - " stmdb r0!, {r4-r11, r14} \n" /* Save the core registers. */ - " str r0, [r2] \n" /* Save the new top of stack into the first member of the TCB. */ - " \n" - " stmdb sp!, {r0, r3} \n" - " mov r0, %0 \n" - " msr basepri, r0 \n" - " dsb \n" - " isb \n" - " bl vTaskSwitchContext \n" - " mov r0, #0 \n" - " msr basepri, r0 \n" - " ldmia sp!, {r0, r3} \n" - " \n" - " ldr r1, [r3] \n" /* The first item in pxCurrentTCB is the task top of stack. */ - " ldr r0, [r1] \n" - " \n" - " ldmia r0!, {r4-r11, r14} \n" /* Pop the core registers. */ - " \n" - " tst r14, #0x10 \n" /* Is the task using the FPU context? If so, pop the high vfp registers too. */ - " it eq \n" - " vldmiaeq r0!, {s16-s31} \n" - " \n" - " msr psp, r0 \n" - " isb \n" - " \n" - #ifdef WORKAROUND_PMU_CM001 /* XMC4000 specific errata workaround. */ - #if WORKAROUND_PMU_CM001 == 1 - " push { r14 } \n" - " pop { pc } \n" - #endif - #endif - " \n" - " bx r14 \n" - " \n" - " .align 4 \n" - "pxCurrentTCBConst: .word pxCurrentTCB \n" - ::"i"(configMAX_SYSCALL_INTERRUPT_PRIORITY) - ); -} -/*-----------------------------------------------------------*/ - -void xPortSysTickHandler( void ) -{ - /* The SysTick runs at the lowest interrupt priority, so when this interrupt - executes all interrupts must be unmasked. There is therefore no need to - save and then restore the interrupt mask value as its value is already - known. */ - portDISABLE_INTERRUPTS(); - { - /* Increment the RTOS tick. */ - if( xTaskIncrementTick() != pdFALSE ) - { - /* A context switch is required. Context switching is performed in - the PendSV interrupt. Pend the PendSV interrupt. */ - portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT; - } - } - portENABLE_INTERRUPTS(); -} -/*-----------------------------------------------------------*/ - -#if( configUSE_TICKLESS_IDLE == 1 ) - - __attribute__((weak)) void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime ) - { - uint32_t ulReloadValue, ulCompleteTickPeriods, ulCompletedSysTickDecrements; - TickType_t xModifiableIdleTime; - - /* Make sure the SysTick reload value does not overflow the counter. */ - if( xExpectedIdleTime > xMaximumPossibleSuppressedTicks ) - { - xExpectedIdleTime = xMaximumPossibleSuppressedTicks; - } - - /* Stop the SysTick momentarily. The time the SysTick is stopped for - is accounted for as best it can be, but using the tickless mode will - inevitably result in some tiny drift of the time maintained by the - kernel with respect to calendar time. */ - portNVIC_SYSTICK_CTRL_REG &= ~portNVIC_SYSTICK_ENABLE_BIT; - - /* Calculate the reload value required to wait xExpectedIdleTime - tick periods. -1 is used because this code will execute part way - through one of the tick periods. */ - ulReloadValue = portNVIC_SYSTICK_CURRENT_VALUE_REG + ( ulTimerCountsForOneTick * ( xExpectedIdleTime - 1UL ) ); - if( ulReloadValue > ulStoppedTimerCompensation ) - { - ulReloadValue -= ulStoppedTimerCompensation; - } - - /* Enter a critical section but don't use the taskENTER_CRITICAL() - method as that will mask interrupts that should exit sleep mode. */ - __asm volatile( "cpsid i" ::: "memory" ); - __asm volatile( "dsb" ); - __asm volatile( "isb" ); - - /* If a context switch is pending or a task is waiting for the scheduler - to be unsuspended then abandon the low power entry. */ - if( eTaskConfirmSleepModeStatus() == eAbortSleep ) - { - /* Restart from whatever is left in the count register to complete - this tick period. */ - portNVIC_SYSTICK_LOAD_REG = portNVIC_SYSTICK_CURRENT_VALUE_REG; - - /* Restart SysTick. */ - portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT; - - /* Reset the reload register to the value required for normal tick - periods. */ - portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL; - - /* Re-enable interrupts - see comments above the cpsid instruction() - above. */ - __asm volatile( "cpsie i" ::: "memory" ); - } - else - { - /* Set the new reload value. */ - portNVIC_SYSTICK_LOAD_REG = ulReloadValue; - - /* Clear the SysTick count flag and set the count value back to - zero. */ - portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL; - - /* Restart SysTick. */ - portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT; - - /* Sleep until something happens. configPRE_SLEEP_PROCESSING() can - set its parameter to 0 to indicate that its implementation contains - its own wait for interrupt or wait for event instruction, and so wfi - should not be executed again. However, the original expected idle - time variable must remain unmodified, so a copy is taken. */ - xModifiableIdleTime = xExpectedIdleTime; - configPRE_SLEEP_PROCESSING( xModifiableIdleTime ); - if( xModifiableIdleTime > 0 ) - { - __asm volatile( "dsb" ::: "memory" ); - __asm volatile( "wfi" ); - __asm volatile( "isb" ); - } - configPOST_SLEEP_PROCESSING( xExpectedIdleTime ); - - /* Re-enable interrupts to allow the interrupt that brought the MCU - out of sleep mode to execute immediately. see comments above - __disable_interrupt() call above. */ - __asm volatile( "cpsie i" ::: "memory" ); - __asm volatile( "dsb" ); - __asm volatile( "isb" ); - - /* Disable interrupts again because the clock is about to be stopped - and interrupts that execute while the clock is stopped will increase - any slippage between the time maintained by the RTOS and calendar - time. */ - __asm volatile( "cpsid i" ::: "memory" ); - __asm volatile( "dsb" ); - __asm volatile( "isb" ); - - /* Disable the SysTick clock without reading the - portNVIC_SYSTICK_CTRL_REG register to ensure the - portNVIC_SYSTICK_COUNT_FLAG_BIT is not cleared if it is set. Again, - the time the SysTick is stopped for is accounted for as best it can - be, but using the tickless mode will inevitably result in some tiny - drift of the time maintained by the kernel with respect to calendar - time*/ - portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT ); - - /* Determine if the SysTick clock has already counted to zero and - been set back to the current reload value (the reload back being - correct for the entire expected idle time) or if the SysTick is yet - to count to zero (in which case an interrupt other than the SysTick - must have brought the system out of sleep mode). */ - if( ( portNVIC_SYSTICK_CTRL_REG & portNVIC_SYSTICK_COUNT_FLAG_BIT ) != 0 ) - { - uint32_t ulCalculatedLoadValue; - - /* The tick interrupt is already pending, and the SysTick count - reloaded with ulReloadValue. Reset the - portNVIC_SYSTICK_LOAD_REG with whatever remains of this tick - period. */ - ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL ) - ( ulReloadValue - portNVIC_SYSTICK_CURRENT_VALUE_REG ); - - /* Don't allow a tiny value, or values that have somehow - underflowed because the post sleep hook did something - that took too long. */ - if( ( ulCalculatedLoadValue < ulStoppedTimerCompensation ) || ( ulCalculatedLoadValue > ulTimerCountsForOneTick ) ) - { - ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL ); - } - - portNVIC_SYSTICK_LOAD_REG = ulCalculatedLoadValue; - - /* As the pending tick will be processed as soon as this - function exits, the tick value maintained by the tick is stepped - forward by one less than the time spent waiting. */ - ulCompleteTickPeriods = xExpectedIdleTime - 1UL; - } - else - { - /* Something other than the tick interrupt ended the sleep. - Work out how long the sleep lasted rounded to complete tick - periods (not the ulReload value which accounted for part - ticks). */ - ulCompletedSysTickDecrements = ( xExpectedIdleTime * ulTimerCountsForOneTick ) - portNVIC_SYSTICK_CURRENT_VALUE_REG; - - /* How many complete tick periods passed while the processor - was waiting? */ - ulCompleteTickPeriods = ulCompletedSysTickDecrements / ulTimerCountsForOneTick; - - /* The reload value is set to whatever fraction of a single tick - period remains. */ - portNVIC_SYSTICK_LOAD_REG = ( ( ulCompleteTickPeriods + 1UL ) * ulTimerCountsForOneTick ) - ulCompletedSysTickDecrements; - } - - /* Restart SysTick so it runs from portNVIC_SYSTICK_LOAD_REG - again, then set portNVIC_SYSTICK_LOAD_REG back to its standard - value. */ - portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL; - portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT; - vTaskStepTick( ulCompleteTickPeriods ); - portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL; - - /* Exit with interrpts enabled. */ - __asm volatile( "cpsie i" ::: "memory" ); - } - } - -#endif /* #if configUSE_TICKLESS_IDLE */ -/*-----------------------------------------------------------*/ - -/* - * Setup the systick timer to generate the tick interrupts at the required - * frequency. - */ -__attribute__(( weak )) void vPortSetupTimerInterrupt( void ) -{ - /* Calculate the constants required to configure the tick interrupt. */ - #if( configUSE_TICKLESS_IDLE == 1 ) - { - ulTimerCountsForOneTick = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ ); - xMaximumPossibleSuppressedTicks = portMAX_24_BIT_NUMBER / ulTimerCountsForOneTick; - ulStoppedTimerCompensation = portMISSED_COUNTS_FACTOR / ( configCPU_CLOCK_HZ / configSYSTICK_CLOCK_HZ ); - } - #endif /* configUSE_TICKLESS_IDLE */ - - /* Stop and clear the SysTick. */ - portNVIC_SYSTICK_CTRL_REG = 0UL; - portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL; - - /* Configure SysTick to interrupt at the requested rate. */ - portNVIC_SYSTICK_LOAD_REG = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ ) - 1UL; - portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT ); -} -/*-----------------------------------------------------------*/ - -/* This is a naked function. */ -static void vPortEnableVFP( void ) -{ - __asm volatile - ( - " ldr.w r0, =0xE000ED88 \n" /* The FPU enable bits are in the CPACR. */ - " ldr r1, [r0] \n" - " \n" - " orr r1, r1, #( 0xf << 20 ) \n" /* Enable CP10 and CP11 coprocessors, then save back. */ - " str r1, [r0] \n" - " bx r14 " - ); -} -/*-----------------------------------------------------------*/ - -#if( configASSERT_DEFINED == 1 ) - - void vPortValidateInterruptPriority( void ) - { - uint32_t ulCurrentInterrupt; - uint8_t ucCurrentPriority; - - /* Obtain the number of the currently executing interrupt. */ - __asm volatile( "mrs %0, ipsr" : "=r"( ulCurrentInterrupt ) :: "memory" ); - - /* Is the interrupt number a user defined interrupt? */ - if( ulCurrentInterrupt >= portFIRST_USER_INTERRUPT_NUMBER ) - { - /* Look up the interrupt's priority. */ - ucCurrentPriority = pcInterruptPriorityRegisters[ ulCurrentInterrupt ]; - - /* The following assertion will fail if a service routine (ISR) for - an interrupt that has been assigned a priority above - configMAX_SYSCALL_INTERRUPT_PRIORITY calls an ISR safe FreeRTOS API - function. ISR safe FreeRTOS API functions must *only* be called - from interrupts that have been assigned a priority at or below - configMAX_SYSCALL_INTERRUPT_PRIORITY. - - Numerically low interrupt priority numbers represent logically high - interrupt priorities, therefore the priority of the interrupt must - be set to a value equal to or numerically *higher* than - configMAX_SYSCALL_INTERRUPT_PRIORITY. - - Interrupts that use the FreeRTOS API must not be left at their - default priority of zero as that is the highest possible priority, - which is guaranteed to be above configMAX_SYSCALL_INTERRUPT_PRIORITY, - and therefore also guaranteed to be invalid. - - FreeRTOS maintains separate thread and ISR API functions to ensure - interrupt entry is as fast and simple as possible. - - The following links provide detailed information: - http://www.freertos.org/RTOS-Cortex-M3-M4.html - http://www.freertos.org/FAQHelp.html */ - configASSERT( ucCurrentPriority >= ucMaxSysCallPriority ); - } - - /* Priority grouping: The interrupt controller (NVIC) allows the bits - that define each interrupt's priority to be split between bits that - define the interrupt's pre-emption priority bits and bits that define - the interrupt's sub-priority. For simplicity all bits must be defined - to be pre-emption priority bits. The following assertion will fail if - this is not the case (if some bits represent a sub-priority). - - If the application only uses CMSIS libraries for interrupt - configuration then the correct setting can be achieved on all Cortex-M - devices by calling NVIC_SetPriorityGrouping( 0 ); before starting the - scheduler. Note however that some vendor specific peripheral libraries - assume a non-zero priority group setting, in which cases using a value - of zero will result in unpredictable behaviour. */ - configASSERT( ( portAIRCR_REG & portPRIORITY_GROUP_MASK ) <= ulMaxPRIGROUPValue ); - } - -#endif /* configASSERT_DEFINED */ - - diff --git a/lib/FreeRTOS/Source/portable/GCC/ARM_CM4F/portmacro.h b/lib/FreeRTOS/Source/portable/GCC/ARM_CM4F/portmacro.h deleted file mode 100644 index 1a950161..00000000 --- a/lib/FreeRTOS/Source/portable/GCC/ARM_CM4F/portmacro.h +++ /dev/null @@ -1,242 +0,0 @@ -/* - * FreeRTOS Kernel V10.0.1 - * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * 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. - * - * http://www.FreeRTOS.org - * http://aws.amazon.com/freertos - * - * 1 tab == 4 spaces! - */ - - -#ifndef PORTMACRO_H -#define PORTMACRO_H - -#ifdef __cplusplus -extern "C" { -#endif - -/*----------------------------------------------------------- - * Port specific definitions. - * - * The settings in this file configure FreeRTOS correctly for the - * given hardware and compiler. - * - * These settings should not be altered. - *----------------------------------------------------------- - */ - -/* Type definitions. */ -#define portCHAR char -#define portFLOAT float -#define portDOUBLE double -#define portLONG long -#define portSHORT short -#define portSTACK_TYPE uint32_t -#define portBASE_TYPE long - -typedef portSTACK_TYPE StackType_t; -typedef long BaseType_t; -typedef unsigned long UBaseType_t; - -#if( configUSE_16_BIT_TICKS == 1 ) - typedef uint16_t TickType_t; - #define portMAX_DELAY ( TickType_t ) 0xffff -#else - typedef uint32_t TickType_t; - #define portMAX_DELAY ( TickType_t ) 0xffffffffUL - - /* 32-bit tick type on a 32-bit architecture, so reads of the tick count do - not need to be guarded with a critical section. */ - #define portTICK_TYPE_IS_ATOMIC 1 -#endif -/*-----------------------------------------------------------*/ - -/* Architecture specifics. */ -#define portSTACK_GROWTH ( -1 ) -#define portTICK_PERIOD_MS ( ( TickType_t ) 1000 / configTICK_RATE_HZ ) -#define portBYTE_ALIGNMENT 8 -/*-----------------------------------------------------------*/ - -/* Scheduler utilities. */ -#define portYIELD() \ -{ \ - /* Set a PendSV to request a context switch. */ \ - portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT; \ - \ - /* Barriers are normally not required but do ensure the code is completely \ - within the specified behaviour for the architecture. */ \ - __asm volatile( "dsb" ::: "memory" ); \ - __asm volatile( "isb" ); \ -} - -#define portNVIC_INT_CTRL_REG ( * ( ( volatile uint32_t * ) 0xe000ed04 ) ) -#define portNVIC_PENDSVSET_BIT ( 1UL << 28UL ) -#define portEND_SWITCHING_ISR( xSwitchRequired ) if( xSwitchRequired != pdFALSE ) portYIELD() -#define portYIELD_FROM_ISR( x ) portEND_SWITCHING_ISR( x ) -/*-----------------------------------------------------------*/ - -/* Critical section management. */ -extern void vPortEnterCritical( void ); -extern void vPortExitCritical( void ); -#define portSET_INTERRUPT_MASK_FROM_ISR() ulPortRaiseBASEPRI() -#define portCLEAR_INTERRUPT_MASK_FROM_ISR(x) vPortSetBASEPRI(x) -#define portDISABLE_INTERRUPTS() vPortRaiseBASEPRI() -#define portENABLE_INTERRUPTS() vPortSetBASEPRI(0) -#define portENTER_CRITICAL() vPortEnterCritical() -#define portEXIT_CRITICAL() vPortExitCritical() - -/*-----------------------------------------------------------*/ - -/* Task function macros as described on the FreeRTOS.org WEB site. These are -not necessary for to use this port. They are defined so the common demo files -(which build with all the ports) will build. */ -#define portTASK_FUNCTION_PROTO( vFunction, pvParameters ) void vFunction( void *pvParameters ) -#define portTASK_FUNCTION( vFunction, pvParameters ) void vFunction( void *pvParameters ) -/*-----------------------------------------------------------*/ - -/* Tickless idle/low power functionality. */ -#ifndef portSUPPRESS_TICKS_AND_SLEEP - extern void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime ); - #define portSUPPRESS_TICKS_AND_SLEEP( xExpectedIdleTime ) vPortSuppressTicksAndSleep( xExpectedIdleTime ) -#endif -/*-----------------------------------------------------------*/ - -/* Architecture specific optimisations. */ -#ifndef configUSE_PORT_OPTIMISED_TASK_SELECTION - #define configUSE_PORT_OPTIMISED_TASK_SELECTION 1 -#endif - -#if configUSE_PORT_OPTIMISED_TASK_SELECTION == 1 - - /* Generic helper function. */ - __attribute__( ( always_inline ) ) static inline uint8_t ucPortCountLeadingZeros( uint32_t ulBitmap ) - { - uint8_t ucReturn; - - __asm volatile ( "clz %0, %1" : "=r" ( ucReturn ) : "r" ( ulBitmap ) : "memory" ); - return ucReturn; - } - - /* Check the configuration. */ - #if( configMAX_PRIORITIES > 32 ) - #error configUSE_PORT_OPTIMISED_TASK_SELECTION can only be set to 1 when configMAX_PRIORITIES is less than or equal to 32. It is very rare that a system requires more than 10 to 15 difference priorities as tasks that share a priority will time slice. - #endif - - /* Store/clear the ready priorities in a bit map. */ - #define portRECORD_READY_PRIORITY( uxPriority, uxReadyPriorities ) ( uxReadyPriorities ) |= ( 1UL << ( uxPriority ) ) - #define portRESET_READY_PRIORITY( uxPriority, uxReadyPriorities ) ( uxReadyPriorities ) &= ~( 1UL << ( uxPriority ) ) - - /*-----------------------------------------------------------*/ - - #define portGET_HIGHEST_PRIORITY( uxTopPriority, uxReadyPriorities ) uxTopPriority = ( 31UL - ( uint32_t ) ucPortCountLeadingZeros( ( uxReadyPriorities ) ) ) - -#endif /* configUSE_PORT_OPTIMISED_TASK_SELECTION */ - -/*-----------------------------------------------------------*/ - -#ifdef configASSERT - void vPortValidateInterruptPriority( void ); - #define portASSERT_IF_INTERRUPT_PRIORITY_INVALID() vPortValidateInterruptPriority() -#endif - -/* portNOP() is not required by this port. */ -#define portNOP() - -#define portINLINE __inline - -#ifndef portFORCE_INLINE - #define portFORCE_INLINE inline __attribute__(( always_inline)) -#endif - -portFORCE_INLINE static BaseType_t xPortIsInsideInterrupt( void ) -{ -uint32_t ulCurrentInterrupt; -BaseType_t xReturn; - - /* Obtain the number of the currently executing interrupt. */ - __asm volatile( "mrs %0, ipsr" : "=r"( ulCurrentInterrupt ) :: "memory" ); - - if( ulCurrentInterrupt == 0 ) - { - xReturn = pdFALSE; - } - else - { - xReturn = pdTRUE; - } - - return xReturn; -} - -/*-----------------------------------------------------------*/ - -portFORCE_INLINE static void vPortRaiseBASEPRI( void ) -{ -uint32_t ulNewBASEPRI; - - __asm volatile - ( - " mov %0, %1 \n" \ - " msr basepri, %0 \n" \ - " isb \n" \ - " dsb \n" \ - :"=r" (ulNewBASEPRI) : "i" ( configMAX_SYSCALL_INTERRUPT_PRIORITY ) : "memory" - ); -} - -/*-----------------------------------------------------------*/ - -portFORCE_INLINE static uint32_t ulPortRaiseBASEPRI( void ) -{ -uint32_t ulOriginalBASEPRI, ulNewBASEPRI; - - __asm volatile - ( - " mrs %0, basepri \n" \ - " mov %1, %2 \n" \ - " msr basepri, %1 \n" \ - " isb \n" \ - " dsb \n" \ - :"=r" (ulOriginalBASEPRI), "=r" (ulNewBASEPRI) : "i" ( configMAX_SYSCALL_INTERRUPT_PRIORITY ) : "memory" - ); - - /* This return will not be reached but is necessary to prevent compiler - warnings. */ - return ulOriginalBASEPRI; -} -/*-----------------------------------------------------------*/ - -portFORCE_INLINE static void vPortSetBASEPRI( uint32_t ulNewMaskValue ) -{ - __asm volatile - ( - " msr basepri, %0 " :: "r" ( ulNewMaskValue ) : "memory" - ); -} -/*-----------------------------------------------------------*/ - - -#ifdef __cplusplus -} -#endif - -#endif /* PORTMACRO_H */ - diff --git a/lib/FreeRTOS/Source/portable/MemMang/ReadMe.url b/lib/FreeRTOS/Source/portable/MemMang/ReadMe.url deleted file mode 100644 index 6c23737d..00000000 --- a/lib/FreeRTOS/Source/portable/MemMang/ReadMe.url +++ /dev/null @@ -1,5 +0,0 @@ -[{000214A0-0000-0000-C000-000000000046}] -Prop3=19,2 -[InternetShortcut] -URL=http://www.freertos.org/a00111.html -IDList= diff --git a/lib/FreeRTOS/Source/portable/MemMang/heap_4.c b/lib/FreeRTOS/Source/portable/MemMang/heap_4.c deleted file mode 100644 index 02251c09..00000000 --- a/lib/FreeRTOS/Source/portable/MemMang/heap_4.c +++ /dev/null @@ -1,436 +0,0 @@ -/* - * FreeRTOS Kernel V10.0.1 - * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * 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. - * - * http://www.FreeRTOS.org - * http://aws.amazon.com/freertos - * - * 1 tab == 4 spaces! - */ - -/* - * A sample implementation of pvPortMalloc() and vPortFree() that combines - * (coalescences) adjacent memory blocks as they are freed, and in so doing - * limits memory fragmentation. - * - * See heap_1.c, heap_2.c and heap_3.c for alternative implementations, and the - * memory management pages of http://www.FreeRTOS.org for more information. - */ -#include - -/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining -all the API functions to use the MPU wrappers. That should only be done when -task.h is included from an application file. */ -#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE - -#include "FreeRTOS.h" -#include "task.h" - -#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE - -#if( configSUPPORT_DYNAMIC_ALLOCATION == 0 ) - #error This file must not be used if configSUPPORT_DYNAMIC_ALLOCATION is 0 -#endif - -/* Block sizes must not get too small. */ -#define heapMINIMUM_BLOCK_SIZE ( ( size_t ) ( xHeapStructSize << 1 ) ) - -/* Assumes 8bit bytes! */ -#define heapBITS_PER_BYTE ( ( size_t ) 8 ) - -/* Allocate the memory for the heap. */ -#if( configAPPLICATION_ALLOCATED_HEAP == 1 ) - /* The application writer has already defined the array used for the RTOS - heap - probably so it can be placed in a special segment or address. */ - extern uint8_t ucHeap[ configTOTAL_HEAP_SIZE ]; -#else - static uint8_t ucHeap[ configTOTAL_HEAP_SIZE ]; -#endif /* configAPPLICATION_ALLOCATED_HEAP */ - -/* Define the linked list structure. This is used to link free blocks in order -of their memory address. */ -typedef struct A_BLOCK_LINK -{ - struct A_BLOCK_LINK *pxNextFreeBlock; /*<< The next free block in the list. */ - size_t xBlockSize; /*<< The size of the free block. */ -} BlockLink_t; - -/*-----------------------------------------------------------*/ - -/* - * Inserts a block of memory that is being freed into the correct position in - * the list of free memory blocks. The block being freed will be merged with - * the block in front it and/or the block behind it if the memory blocks are - * adjacent to each other. - */ -static void prvInsertBlockIntoFreeList( BlockLink_t *pxBlockToInsert ); - -/* - * Called automatically to setup the required heap structures the first time - * pvPortMalloc() is called. - */ -static void prvHeapInit( void ); - -/*-----------------------------------------------------------*/ - -/* The size of the structure placed at the beginning of each allocated memory -block must by correctly byte aligned. */ -static const size_t xHeapStructSize = ( sizeof( BlockLink_t ) + ( ( size_t ) ( portBYTE_ALIGNMENT - 1 ) ) ) & ~( ( size_t ) portBYTE_ALIGNMENT_MASK ); - -/* Create a couple of list links to mark the start and end of the list. */ -static BlockLink_t xStart, *pxEnd = NULL; - -/* Keeps track of the number of free bytes remaining, but says nothing about -fragmentation. */ -static size_t xFreeBytesRemaining = 0U; -static size_t xMinimumEverFreeBytesRemaining = 0U; - -/* Gets set to the top bit of an size_t type. When this bit in the xBlockSize -member of an BlockLink_t structure is set then the block belongs to the -application. When the bit is free the block is still part of the free heap -space. */ -static size_t xBlockAllocatedBit = 0; - -/*-----------------------------------------------------------*/ - -void *pvPortMalloc( size_t xWantedSize ) -{ -BlockLink_t *pxBlock, *pxPreviousBlock, *pxNewBlockLink; -void *pvReturn = NULL; - - vTaskSuspendAll(); - { - /* If this is the first call to malloc then the heap will require - initialisation to setup the list of free blocks. */ - if( pxEnd == NULL ) - { - prvHeapInit(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - /* Check the requested block size is not so large that the top bit is - set. The top bit of the block size member of the BlockLink_t structure - is used to determine who owns the block - the application or the - kernel, so it must be free. */ - if( ( xWantedSize & xBlockAllocatedBit ) == 0 ) - { - /* The wanted size is increased so it can contain a BlockLink_t - structure in addition to the requested amount of bytes. */ - if( xWantedSize > 0 ) - { - xWantedSize += xHeapStructSize; - - /* Ensure that blocks are always aligned to the required number - of bytes. */ - if( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0x00 ) - { - /* Byte alignment required. */ - xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) ); - configASSERT( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) == 0 ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - if( ( xWantedSize > 0 ) && ( xWantedSize <= xFreeBytesRemaining ) ) - { - /* Traverse the list from the start (lowest address) block until - one of adequate size is found. */ - pxPreviousBlock = &xStart; - pxBlock = xStart.pxNextFreeBlock; - while( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock != NULL ) ) - { - pxPreviousBlock = pxBlock; - pxBlock = pxBlock->pxNextFreeBlock; - } - - /* If the end marker was reached then a block of adequate size - was not found. */ - if( pxBlock != pxEnd ) - { - /* Return the memory space pointed to - jumping over the - BlockLink_t structure at its start. */ - pvReturn = ( void * ) ( ( ( uint8_t * ) pxPreviousBlock->pxNextFreeBlock ) + xHeapStructSize ); - - /* This block is being returned for use so must be taken out - of the list of free blocks. */ - pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock; - - /* If the block is larger than required it can be split into - two. */ - if( ( pxBlock->xBlockSize - xWantedSize ) > heapMINIMUM_BLOCK_SIZE ) - { - /* This block is to be split into two. Create a new - block following the number of bytes requested. The void - cast is used to prevent byte alignment warnings from the - compiler. */ - pxNewBlockLink = ( void * ) ( ( ( uint8_t * ) pxBlock ) + xWantedSize ); - configASSERT( ( ( ( size_t ) pxNewBlockLink ) & portBYTE_ALIGNMENT_MASK ) == 0 ); - - /* Calculate the sizes of two blocks split from the - single block. */ - pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize; - pxBlock->xBlockSize = xWantedSize; - - /* Insert the new block into the list of free blocks. */ - prvInsertBlockIntoFreeList( pxNewBlockLink ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - xFreeBytesRemaining -= pxBlock->xBlockSize; - - if( xFreeBytesRemaining < xMinimumEverFreeBytesRemaining ) - { - xMinimumEverFreeBytesRemaining = xFreeBytesRemaining; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - /* The block is being returned - it is allocated and owned - by the application and has no "next" block. */ - pxBlock->xBlockSize |= xBlockAllocatedBit; - pxBlock->pxNextFreeBlock = NULL; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - traceMALLOC( pvReturn, xWantedSize ); - } - ( void ) xTaskResumeAll(); - - #if( configUSE_MALLOC_FAILED_HOOK == 1 ) - { - if( pvReturn == NULL ) - { - extern void vApplicationMallocFailedHook( void ); - vApplicationMallocFailedHook(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif - - configASSERT( ( ( ( size_t ) pvReturn ) & ( size_t ) portBYTE_ALIGNMENT_MASK ) == 0 ); - return pvReturn; -} -/*-----------------------------------------------------------*/ - -void vPortFree( void *pv ) -{ -uint8_t *puc = ( uint8_t * ) pv; -BlockLink_t *pxLink; - - if( pv != NULL ) - { - /* The memory being freed will have an BlockLink_t structure immediately - before it. */ - puc -= xHeapStructSize; - - /* This casting is to keep the compiler from issuing warnings. */ - pxLink = ( void * ) puc; - - /* Check the block is actually allocated. */ - configASSERT( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 ); - configASSERT( pxLink->pxNextFreeBlock == NULL ); - - if( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 ) - { - if( pxLink->pxNextFreeBlock == NULL ) - { - /* The block is being returned to the heap - it is no longer - allocated. */ - pxLink->xBlockSize &= ~xBlockAllocatedBit; - - vTaskSuspendAll(); - { - /* Add this block to the list of free blocks. */ - xFreeBytesRemaining += pxLink->xBlockSize; - traceFREE( pv, pxLink->xBlockSize ); - prvInsertBlockIntoFreeList( ( ( BlockLink_t * ) pxLink ) ); - } - ( void ) xTaskResumeAll(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } -} -/*-----------------------------------------------------------*/ - -size_t xPortGetFreeHeapSize( void ) -{ - return xFreeBytesRemaining; -} -/*-----------------------------------------------------------*/ - -size_t xPortGetMinimumEverFreeHeapSize( void ) -{ - return xMinimumEverFreeBytesRemaining; -} -/*-----------------------------------------------------------*/ - -void vPortInitialiseBlocks( void ) -{ - /* This just exists to keep the linker quiet. */ -} -/*-----------------------------------------------------------*/ - -static void prvHeapInit( void ) -{ -BlockLink_t *pxFirstFreeBlock; -uint8_t *pucAlignedHeap; -size_t uxAddress; -size_t xTotalHeapSize = configTOTAL_HEAP_SIZE; - - /* Ensure the heap starts on a correctly aligned boundary. */ - uxAddress = ( size_t ) ucHeap; - - if( ( uxAddress & portBYTE_ALIGNMENT_MASK ) != 0 ) - { - uxAddress += ( portBYTE_ALIGNMENT - 1 ); - uxAddress &= ~( ( size_t ) portBYTE_ALIGNMENT_MASK ); - xTotalHeapSize -= uxAddress - ( size_t ) ucHeap; - } - - pucAlignedHeap = ( uint8_t * ) uxAddress; - - /* xStart is used to hold a pointer to the first item in the list of free - blocks. The void cast is used to prevent compiler warnings. */ - xStart.pxNextFreeBlock = ( void * ) pucAlignedHeap; - xStart.xBlockSize = ( size_t ) 0; - - /* pxEnd is used to mark the end of the list of free blocks and is inserted - at the end of the heap space. */ - uxAddress = ( ( size_t ) pucAlignedHeap ) + xTotalHeapSize; - uxAddress -= xHeapStructSize; - uxAddress &= ~( ( size_t ) portBYTE_ALIGNMENT_MASK ); - pxEnd = ( void * ) uxAddress; - pxEnd->xBlockSize = 0; - pxEnd->pxNextFreeBlock = NULL; - - /* To start with there is a single free block that is sized to take up the - entire heap space, minus the space taken by pxEnd. */ - pxFirstFreeBlock = ( void * ) pucAlignedHeap; - pxFirstFreeBlock->xBlockSize = uxAddress - ( size_t ) pxFirstFreeBlock; - pxFirstFreeBlock->pxNextFreeBlock = pxEnd; - - /* Only one block exists - and it covers the entire usable heap space. */ - xMinimumEverFreeBytesRemaining = pxFirstFreeBlock->xBlockSize; - xFreeBytesRemaining = pxFirstFreeBlock->xBlockSize; - - /* Work out the position of the top bit in a size_t variable. */ - xBlockAllocatedBit = ( ( size_t ) 1 ) << ( ( sizeof( size_t ) * heapBITS_PER_BYTE ) - 1 ); -} -/*-----------------------------------------------------------*/ - -static void prvInsertBlockIntoFreeList( BlockLink_t *pxBlockToInsert ) -{ -BlockLink_t *pxIterator; -uint8_t *puc; - - /* Iterate through the list until a block is found that has a higher address - than the block being inserted. */ - for( pxIterator = &xStart; pxIterator->pxNextFreeBlock < pxBlockToInsert; pxIterator = pxIterator->pxNextFreeBlock ) - { - /* Nothing to do here, just iterate to the right position. */ - } - - /* Do the block being inserted, and the block it is being inserted after - make a contiguous block of memory? */ - puc = ( uint8_t * ) pxIterator; - if( ( puc + pxIterator->xBlockSize ) == ( uint8_t * ) pxBlockToInsert ) - { - pxIterator->xBlockSize += pxBlockToInsert->xBlockSize; - pxBlockToInsert = pxIterator; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - /* Do the block being inserted, and the block it is being inserted before - make a contiguous block of memory? */ - puc = ( uint8_t * ) pxBlockToInsert; - if( ( puc + pxBlockToInsert->xBlockSize ) == ( uint8_t * ) pxIterator->pxNextFreeBlock ) - { - if( pxIterator->pxNextFreeBlock != pxEnd ) - { - /* Form one big block from the two blocks. */ - pxBlockToInsert->xBlockSize += pxIterator->pxNextFreeBlock->xBlockSize; - pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock->pxNextFreeBlock; - } - else - { - pxBlockToInsert->pxNextFreeBlock = pxEnd; - } - } - else - { - pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock; - } - - /* If the block being inserted plugged a gab, so was merged with the block - before and the block after, then it's pxNextFreeBlock pointer will have - already been set, and should not be set here as that would make it point - to itself. */ - if( pxIterator != pxBlockToInsert ) - { - pxIterator->pxNextFreeBlock = pxBlockToInsert; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } -} - diff --git a/lib/FreeRTOS/Source/portable/readme.txt b/lib/FreeRTOS/Source/portable/readme.txt deleted file mode 100644 index b68d2d57..00000000 --- a/lib/FreeRTOS/Source/portable/readme.txt +++ /dev/null @@ -1,20 +0,0 @@ -Each real time kernel port consists of three files that contain the core kernel -components and are common to every port, and one or more files that are -specific to a particular microcontroller and/or compiler. - - -+ The FreeRTOS/Source/Portable/MemMang directory contains the five sample -memory allocators as described on the http://www.FreeRTOS.org WEB site. - -+ The other directories each contain files specific to a particular -microcontroller or compiler, where the directory name denotes the compiler -specific files the directory contains. - - - -For example, if you are interested in the [compiler] port for the [architecture] -microcontroller, then the port specific files are contained in -FreeRTOS/Source/Portable/[compiler]/[architecture] directory. If this is the -only port you are interested in then all the other directories can be -ignored. - diff --git a/lib/FreeRTOS/Source/queue.c b/lib/FreeRTOS/Source/queue.c deleted file mode 100644 index c37d285f..00000000 --- a/lib/FreeRTOS/Source/queue.c +++ /dev/null @@ -1,2909 +0,0 @@ -/* - * FreeRTOS Kernel V10.0.1 - * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * 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. - * - * http://www.FreeRTOS.org - * http://aws.amazon.com/freertos - * - * 1 tab == 4 spaces! - */ - -#include -#include - -/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining -all the API functions to use the MPU wrappers. That should only be done when -task.h is included from an application file. */ -#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE - -#include "FreeRTOS.h" -#include "task.h" -#include "queue.h" - -#if ( configUSE_CO_ROUTINES == 1 ) - #include "croutine.h" -#endif - -/* Lint e961 and e750 are suppressed as a MISRA exception justified because the -MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be defined for the -header files above, but not in this file, in order to generate the correct -privileged Vs unprivileged linkage and placement. */ -#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /*lint !e961 !e750. */ - - -/* Constants used with the cRxLock and cTxLock structure members. */ -#define queueUNLOCKED ( ( int8_t ) -1 ) -#define queueLOCKED_UNMODIFIED ( ( int8_t ) 0 ) - -/* When the Queue_t structure is used to represent a base queue its pcHead and -pcTail members are used as pointers into the queue storage area. When the -Queue_t structure is used to represent a mutex pcHead and pcTail pointers are -not necessary, and the pcHead pointer is set to NULL to indicate that the -pcTail pointer actually points to the mutex holder (if any). Map alternative -names to the pcHead and pcTail structure members to ensure the readability of -the code is maintained despite this dual use of two structure members. An -alternative implementation would be to use a union, but use of a union is -against the coding standard (although an exception to the standard has been -permitted where the dual use also significantly changes the type of the -structure member). */ -#define pxMutexHolder pcTail -#define uxQueueType pcHead -#define queueQUEUE_IS_MUTEX NULL - -/* Semaphores do not actually store or copy data, so have an item size of -zero. */ -#define queueSEMAPHORE_QUEUE_ITEM_LENGTH ( ( UBaseType_t ) 0 ) -#define queueMUTEX_GIVE_BLOCK_TIME ( ( TickType_t ) 0U ) - -#if( configUSE_PREEMPTION == 0 ) - /* If the cooperative scheduler is being used then a yield should not be - performed just because a higher priority task has been woken. */ - #define queueYIELD_IF_USING_PREEMPTION() -#else - #define queueYIELD_IF_USING_PREEMPTION() portYIELD_WITHIN_API() -#endif - -/* - * Definition of the queue used by the scheduler. - * Items are queued by copy, not reference. See the following link for the - * rationale: http://www.freertos.org/Embedded-RTOS-Queues.html - */ -typedef struct QueueDefinition -{ - int8_t *pcHead; /*< Points to the beginning of the queue storage area. */ - int8_t *pcTail; /*< Points to the byte at the end of the queue storage area. Once more byte is allocated than necessary to store the queue items, this is used as a marker. */ - int8_t *pcWriteTo; /*< Points to the free next place in the storage area. */ - - union /* Use of a union is an exception to the coding standard to ensure two mutually exclusive structure members don't appear simultaneously (wasting RAM). */ - { - int8_t *pcReadFrom; /*< Points to the last place that a queued item was read from when the structure is used as a queue. */ - UBaseType_t uxRecursiveCallCount;/*< Maintains a count of the number of times a recursive mutex has been recursively 'taken' when the structure is used as a mutex. */ - } u; - - List_t xTasksWaitingToSend; /*< List of tasks that are blocked waiting to post onto this queue. Stored in priority order. */ - List_t xTasksWaitingToReceive; /*< List of tasks that are blocked waiting to read from this queue. Stored in priority order. */ - - volatile UBaseType_t uxMessagesWaiting;/*< The number of items currently in the queue. */ - UBaseType_t uxLength; /*< The length of the queue defined as the number of items it will hold, not the number of bytes. */ - UBaseType_t uxItemSize; /*< The size of each items that the queue will hold. */ - - volatile int8_t cRxLock; /*< Stores the number of items received from the queue (removed from the queue) while the queue was locked. Set to queueUNLOCKED when the queue is not locked. */ - volatile int8_t cTxLock; /*< Stores the number of items transmitted to the queue (added to the queue) while the queue was locked. Set to queueUNLOCKED when the queue is not locked. */ - - #if( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) - uint8_t ucStaticallyAllocated; /*< Set to pdTRUE if the memory used by the queue was statically allocated to ensure no attempt is made to free the memory. */ - #endif - - #if ( configUSE_QUEUE_SETS == 1 ) - struct QueueDefinition *pxQueueSetContainer; - #endif - - #if ( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxQueueNumber; - uint8_t ucQueueType; - #endif - -} xQUEUE; - -/* The old xQUEUE name is maintained above then typedefed to the new Queue_t -name below to enable the use of older kernel aware debuggers. */ -typedef xQUEUE Queue_t; - -/*-----------------------------------------------------------*/ - -/* - * The queue registry is just a means for kernel aware debuggers to locate - * queue structures. It has no other purpose so is an optional component. - */ -#if ( configQUEUE_REGISTRY_SIZE > 0 ) - - /* The type stored within the queue registry array. This allows a name - to be assigned to each queue making kernel aware debugging a little - more user friendly. */ - typedef struct QUEUE_REGISTRY_ITEM - { - const char *pcQueueName; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - QueueHandle_t xHandle; - } xQueueRegistryItem; - - /* The old xQueueRegistryItem name is maintained above then typedefed to the - new xQueueRegistryItem name below to enable the use of older kernel aware - debuggers. */ - typedef xQueueRegistryItem QueueRegistryItem_t; - - /* The queue registry is simply an array of QueueRegistryItem_t structures. - The pcQueueName member of a structure being NULL is indicative of the - array position being vacant. */ - PRIVILEGED_DATA QueueRegistryItem_t xQueueRegistry[ configQUEUE_REGISTRY_SIZE ]; - -#endif /* configQUEUE_REGISTRY_SIZE */ - -/* - * Unlocks a queue locked by a call to prvLockQueue. Locking a queue does not - * prevent an ISR from adding or removing items to the queue, but does prevent - * an ISR from removing tasks from the queue event lists. If an ISR finds a - * queue is locked it will instead increment the appropriate queue lock count - * to indicate that a task may require unblocking. When the queue in unlocked - * these lock counts are inspected, and the appropriate action taken. - */ -static void prvUnlockQueue( Queue_t * const pxQueue ) PRIVILEGED_FUNCTION; - -/* - * Uses a critical section to determine if there is any data in a queue. - * - * @return pdTRUE if the queue contains no items, otherwise pdFALSE. - */ -static BaseType_t prvIsQueueEmpty( const Queue_t *pxQueue ) PRIVILEGED_FUNCTION; - -/* - * Uses a critical section to determine if there is any space in a queue. - * - * @return pdTRUE if there is no space, otherwise pdFALSE; - */ -static BaseType_t prvIsQueueFull( const Queue_t *pxQueue ) PRIVILEGED_FUNCTION; - -/* - * Copies an item into the queue, either at the front of the queue or the - * back of the queue. - */ -static BaseType_t prvCopyDataToQueue( Queue_t * const pxQueue, const void *pvItemToQueue, const BaseType_t xPosition ) PRIVILEGED_FUNCTION; - -/* - * Copies an item out of a queue. - */ -static void prvCopyDataFromQueue( Queue_t * const pxQueue, void * const pvBuffer ) PRIVILEGED_FUNCTION; - -#if ( configUSE_QUEUE_SETS == 1 ) - /* - * Checks to see if a queue is a member of a queue set, and if so, notifies - * the queue set that the queue contains data. - */ - static BaseType_t prvNotifyQueueSetContainer( const Queue_t * const pxQueue, const BaseType_t xCopyPosition ) PRIVILEGED_FUNCTION; -#endif - -/* - * Called after a Queue_t structure has been allocated either statically or - * dynamically to fill in the structure's members. - */ -static void prvInitialiseNewQueue( const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, uint8_t *pucQueueStorage, const uint8_t ucQueueType, Queue_t *pxNewQueue ) PRIVILEGED_FUNCTION; - -/* - * Mutexes are a special type of queue. When a mutex is created, first the - * queue is created, then prvInitialiseMutex() is called to configure the queue - * as a mutex. - */ -#if( configUSE_MUTEXES == 1 ) - static void prvInitialiseMutex( Queue_t *pxNewQueue ) PRIVILEGED_FUNCTION; -#endif - -#if( configUSE_MUTEXES == 1 ) - /* - * If a task waiting for a mutex causes the mutex holder to inherit a - * priority, but the waiting task times out, then the holder should - * disinherit the priority - but only down to the highest priority of any - * other tasks that are waiting for the same mutex. This function returns - * that priority. - */ - static UBaseType_t prvGetDisinheritPriorityAfterTimeout( const Queue_t * const pxQueue ) PRIVILEGED_FUNCTION; -#endif -/*-----------------------------------------------------------*/ - -/* - * Macro to mark a queue as locked. Locking a queue prevents an ISR from - * accessing the queue event lists. - */ -#define prvLockQueue( pxQueue ) \ - taskENTER_CRITICAL(); \ - { \ - if( ( pxQueue )->cRxLock == queueUNLOCKED ) \ - { \ - ( pxQueue )->cRxLock = queueLOCKED_UNMODIFIED; \ - } \ - if( ( pxQueue )->cTxLock == queueUNLOCKED ) \ - { \ - ( pxQueue )->cTxLock = queueLOCKED_UNMODIFIED; \ - } \ - } \ - taskEXIT_CRITICAL() -/*-----------------------------------------------------------*/ - -BaseType_t xQueueGenericReset( QueueHandle_t xQueue, BaseType_t xNewQueue ) -{ -Queue_t * const pxQueue = ( Queue_t * ) xQueue; - - configASSERT( pxQueue ); - - taskENTER_CRITICAL(); - { - pxQueue->pcTail = pxQueue->pcHead + ( pxQueue->uxLength * pxQueue->uxItemSize ); - pxQueue->uxMessagesWaiting = ( UBaseType_t ) 0U; - pxQueue->pcWriteTo = pxQueue->pcHead; - pxQueue->u.pcReadFrom = pxQueue->pcHead + ( ( pxQueue->uxLength - ( UBaseType_t ) 1U ) * pxQueue->uxItemSize ); - pxQueue->cRxLock = queueUNLOCKED; - pxQueue->cTxLock = queueUNLOCKED; - - if( xNewQueue == pdFALSE ) - { - /* If there are tasks blocked waiting to read from the queue, then - the tasks will remain blocked as after this function exits the queue - will still be empty. If there are tasks blocked waiting to write to - the queue, then one should be unblocked as after this function exits - it will be possible to write to it. */ - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) - { - queueYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* Ensure the event queues start in the correct state. */ - vListInitialise( &( pxQueue->xTasksWaitingToSend ) ); - vListInitialise( &( pxQueue->xTasksWaitingToReceive ) ); - } - } - taskEXIT_CRITICAL(); - - /* A value is returned for calling semantic consistency with previous - versions. */ - return pdPASS; -} -/*-----------------------------------------------------------*/ - -#if( configSUPPORT_STATIC_ALLOCATION == 1 ) - - QueueHandle_t xQueueGenericCreateStatic( const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, uint8_t *pucQueueStorage, StaticQueue_t *pxStaticQueue, const uint8_t ucQueueType ) - { - Queue_t *pxNewQueue; - - configASSERT( uxQueueLength > ( UBaseType_t ) 0 ); - - /* The StaticQueue_t structure and the queue storage area must be - supplied. */ - configASSERT( pxStaticQueue != NULL ); - - /* A queue storage area should be provided if the item size is not 0, and - should not be provided if the item size is 0. */ - configASSERT( !( ( pucQueueStorage != NULL ) && ( uxItemSize == 0 ) ) ); - configASSERT( !( ( pucQueueStorage == NULL ) && ( uxItemSize != 0 ) ) ); - - #if( configASSERT_DEFINED == 1 ) - { - /* Sanity check that the size of the structure used to declare a - variable of type StaticQueue_t or StaticSemaphore_t equals the size of - the real queue and semaphore structures. */ - volatile size_t xSize = sizeof( StaticQueue_t ); - configASSERT( xSize == sizeof( Queue_t ) ); - } - #endif /* configASSERT_DEFINED */ - - /* The address of a statically allocated queue was passed in, use it. - The address of a statically allocated storage area was also passed in - but is already set. */ - pxNewQueue = ( Queue_t * ) pxStaticQueue; /*lint !e740 Unusual cast is ok as the structures are designed to have the same alignment, and the size is checked by an assert. */ - - if( pxNewQueue != NULL ) - { - #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - { - /* Queues can be allocated wither statically or dynamically, so - note this queue was allocated statically in case the queue is - later deleted. */ - pxNewQueue->ucStaticallyAllocated = pdTRUE; - } - #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ - - prvInitialiseNewQueue( uxQueueLength, uxItemSize, pucQueueStorage, ucQueueType, pxNewQueue ); - } - else - { - traceQUEUE_CREATE_FAILED( ucQueueType ); - } - - return pxNewQueue; - } - -#endif /* configSUPPORT_STATIC_ALLOCATION */ -/*-----------------------------------------------------------*/ - -#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - - QueueHandle_t xQueueGenericCreate( const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, const uint8_t ucQueueType ) - { - Queue_t *pxNewQueue; - size_t xQueueSizeInBytes; - uint8_t *pucQueueStorage; - - configASSERT( uxQueueLength > ( UBaseType_t ) 0 ); - - if( uxItemSize == ( UBaseType_t ) 0 ) - { - /* There is not going to be a queue storage area. */ - xQueueSizeInBytes = ( size_t ) 0; - } - else - { - /* Allocate enough space to hold the maximum number of items that - can be in the queue at any time. */ - xQueueSizeInBytes = ( size_t ) ( uxQueueLength * uxItemSize ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - } - - pxNewQueue = ( Queue_t * ) pvPortMalloc( sizeof( Queue_t ) + xQueueSizeInBytes ); - - if( pxNewQueue != NULL ) - { - /* Jump past the queue structure to find the location of the queue - storage area. */ - pucQueueStorage = ( ( uint8_t * ) pxNewQueue ) + sizeof( Queue_t ); - - #if( configSUPPORT_STATIC_ALLOCATION == 1 ) - { - /* Queues can be created either statically or dynamically, so - note this task was created dynamically in case it is later - deleted. */ - pxNewQueue->ucStaticallyAllocated = pdFALSE; - } - #endif /* configSUPPORT_STATIC_ALLOCATION */ - - prvInitialiseNewQueue( uxQueueLength, uxItemSize, pucQueueStorage, ucQueueType, pxNewQueue ); - } - else - { - traceQUEUE_CREATE_FAILED( ucQueueType ); - } - - return pxNewQueue; - } - -#endif /* configSUPPORT_STATIC_ALLOCATION */ -/*-----------------------------------------------------------*/ - -static void prvInitialiseNewQueue( const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, uint8_t *pucQueueStorage, const uint8_t ucQueueType, Queue_t *pxNewQueue ) -{ - /* Remove compiler warnings about unused parameters should - configUSE_TRACE_FACILITY not be set to 1. */ - ( void ) ucQueueType; - - if( uxItemSize == ( UBaseType_t ) 0 ) - { - /* No RAM was allocated for the queue storage area, but PC head cannot - be set to NULL because NULL is used as a key to say the queue is used as - a mutex. Therefore just set pcHead to point to the queue as a benign - value that is known to be within the memory map. */ - pxNewQueue->pcHead = ( int8_t * ) pxNewQueue; - } - else - { - /* Set the head to the start of the queue storage area. */ - pxNewQueue->pcHead = ( int8_t * ) pucQueueStorage; - } - - /* Initialise the queue members as described where the queue type is - defined. */ - pxNewQueue->uxLength = uxQueueLength; - pxNewQueue->uxItemSize = uxItemSize; - ( void ) xQueueGenericReset( pxNewQueue, pdTRUE ); - - #if ( configUSE_TRACE_FACILITY == 1 ) - { - pxNewQueue->ucQueueType = ucQueueType; - } - #endif /* configUSE_TRACE_FACILITY */ - - #if( configUSE_QUEUE_SETS == 1 ) - { - pxNewQueue->pxQueueSetContainer = NULL; - } - #endif /* configUSE_QUEUE_SETS */ - - traceQUEUE_CREATE( pxNewQueue ); -} -/*-----------------------------------------------------------*/ - -#if( configUSE_MUTEXES == 1 ) - - static void prvInitialiseMutex( Queue_t *pxNewQueue ) - { - if( pxNewQueue != NULL ) - { - /* The queue create function will set all the queue structure members - correctly for a generic queue, but this function is creating a - mutex. Overwrite those members that need to be set differently - - in particular the information required for priority inheritance. */ - pxNewQueue->pxMutexHolder = NULL; - pxNewQueue->uxQueueType = queueQUEUE_IS_MUTEX; - - /* In case this is a recursive mutex. */ - pxNewQueue->u.uxRecursiveCallCount = 0; - - traceCREATE_MUTEX( pxNewQueue ); - - /* Start with the semaphore in the expected state. */ - ( void ) xQueueGenericSend( pxNewQueue, NULL, ( TickType_t ) 0U, queueSEND_TO_BACK ); - } - else - { - traceCREATE_MUTEX_FAILED(); - } - } - -#endif /* configUSE_MUTEXES */ -/*-----------------------------------------------------------*/ - -#if( ( configUSE_MUTEXES == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) - - QueueHandle_t xQueueCreateMutex( const uint8_t ucQueueType ) - { - Queue_t *pxNewQueue; - const UBaseType_t uxMutexLength = ( UBaseType_t ) 1, uxMutexSize = ( UBaseType_t ) 0; - - pxNewQueue = ( Queue_t * ) xQueueGenericCreate( uxMutexLength, uxMutexSize, ucQueueType ); - prvInitialiseMutex( pxNewQueue ); - - return pxNewQueue; - } - -#endif /* configUSE_MUTEXES */ -/*-----------------------------------------------------------*/ - -#if( ( configUSE_MUTEXES == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) - - QueueHandle_t xQueueCreateMutexStatic( const uint8_t ucQueueType, StaticQueue_t *pxStaticQueue ) - { - Queue_t *pxNewQueue; - const UBaseType_t uxMutexLength = ( UBaseType_t ) 1, uxMutexSize = ( UBaseType_t ) 0; - - /* Prevent compiler warnings about unused parameters if - configUSE_TRACE_FACILITY does not equal 1. */ - ( void ) ucQueueType; - - pxNewQueue = ( Queue_t * ) xQueueGenericCreateStatic( uxMutexLength, uxMutexSize, NULL, pxStaticQueue, ucQueueType ); - prvInitialiseMutex( pxNewQueue ); - - return pxNewQueue; - } - -#endif /* configUSE_MUTEXES */ -/*-----------------------------------------------------------*/ - -#if ( ( configUSE_MUTEXES == 1 ) && ( INCLUDE_xSemaphoreGetMutexHolder == 1 ) ) - - void* xQueueGetMutexHolder( QueueHandle_t xSemaphore ) - { - void *pxReturn; - - /* This function is called by xSemaphoreGetMutexHolder(), and should not - be called directly. Note: This is a good way of determining if the - calling task is the mutex holder, but not a good way of determining the - identity of the mutex holder, as the holder may change between the - following critical section exiting and the function returning. */ - taskENTER_CRITICAL(); - { - if( ( ( Queue_t * ) xSemaphore )->uxQueueType == queueQUEUE_IS_MUTEX ) - { - pxReturn = ( void * ) ( ( Queue_t * ) xSemaphore )->pxMutexHolder; - } - else - { - pxReturn = NULL; - } - } - taskEXIT_CRITICAL(); - - return pxReturn; - } /*lint !e818 xSemaphore cannot be a pointer to const because it is a typedef. */ - -#endif -/*-----------------------------------------------------------*/ - -#if ( ( configUSE_MUTEXES == 1 ) && ( INCLUDE_xSemaphoreGetMutexHolder == 1 ) ) - - void* xQueueGetMutexHolderFromISR( QueueHandle_t xSemaphore ) - { - void *pxReturn; - - configASSERT( xSemaphore ); - - /* Mutexes cannot be used in interrupt service routines, so the mutex - holder should not change in an ISR, and therefore a critical section is - not required here. */ - if( ( ( Queue_t * ) xSemaphore )->uxQueueType == queueQUEUE_IS_MUTEX ) - { - pxReturn = ( void * ) ( ( Queue_t * ) xSemaphore )->pxMutexHolder; - } - else - { - pxReturn = NULL; - } - - return pxReturn; - } /*lint !e818 xSemaphore cannot be a pointer to const because it is a typedef. */ - -#endif -/*-----------------------------------------------------------*/ - -#if ( configUSE_RECURSIVE_MUTEXES == 1 ) - - BaseType_t xQueueGiveMutexRecursive( QueueHandle_t xMutex ) - { - BaseType_t xReturn; - Queue_t * const pxMutex = ( Queue_t * ) xMutex; - - configASSERT( pxMutex ); - - /* If this is the task that holds the mutex then pxMutexHolder will not - change outside of this task. If this task does not hold the mutex then - pxMutexHolder can never coincidentally equal the tasks handle, and as - this is the only condition we are interested in it does not matter if - pxMutexHolder is accessed simultaneously by another task. Therefore no - mutual exclusion is required to test the pxMutexHolder variable. */ - if( pxMutex->pxMutexHolder == ( void * ) xTaskGetCurrentTaskHandle() ) /*lint !e961 Not a redundant cast as TaskHandle_t is a typedef. */ - { - traceGIVE_MUTEX_RECURSIVE( pxMutex ); - - /* uxRecursiveCallCount cannot be zero if pxMutexHolder is equal to - the task handle, therefore no underflow check is required. Also, - uxRecursiveCallCount is only modified by the mutex holder, and as - there can only be one, no mutual exclusion is required to modify the - uxRecursiveCallCount member. */ - ( pxMutex->u.uxRecursiveCallCount )--; - - /* Has the recursive call count unwound to 0? */ - if( pxMutex->u.uxRecursiveCallCount == ( UBaseType_t ) 0 ) - { - /* Return the mutex. This will automatically unblock any other - task that might be waiting to access the mutex. */ - ( void ) xQueueGenericSend( pxMutex, NULL, queueMUTEX_GIVE_BLOCK_TIME, queueSEND_TO_BACK ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - xReturn = pdPASS; - } - else - { - /* The mutex cannot be given because the calling task is not the - holder. */ - xReturn = pdFAIL; - - traceGIVE_MUTEX_RECURSIVE_FAILED( pxMutex ); - } - - return xReturn; - } - -#endif /* configUSE_RECURSIVE_MUTEXES */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_RECURSIVE_MUTEXES == 1 ) - - BaseType_t xQueueTakeMutexRecursive( QueueHandle_t xMutex, TickType_t xTicksToWait ) - { - BaseType_t xReturn; - Queue_t * const pxMutex = ( Queue_t * ) xMutex; - - configASSERT( pxMutex ); - - /* Comments regarding mutual exclusion as per those within - xQueueGiveMutexRecursive(). */ - - traceTAKE_MUTEX_RECURSIVE( pxMutex ); - - if( pxMutex->pxMutexHolder == ( void * ) xTaskGetCurrentTaskHandle() ) /*lint !e961 Cast is not redundant as TaskHandle_t is a typedef. */ - { - ( pxMutex->u.uxRecursiveCallCount )++; - xReturn = pdPASS; - } - else - { - xReturn = xQueueSemaphoreTake( pxMutex, xTicksToWait ); - - /* pdPASS will only be returned if the mutex was successfully - obtained. The calling task may have entered the Blocked state - before reaching here. */ - if( xReturn != pdFAIL ) - { - ( pxMutex->u.uxRecursiveCallCount )++; - } - else - { - traceTAKE_MUTEX_RECURSIVE_FAILED( pxMutex ); - } - } - - return xReturn; - } - -#endif /* configUSE_RECURSIVE_MUTEXES */ -/*-----------------------------------------------------------*/ - -#if( ( configUSE_COUNTING_SEMAPHORES == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) - - QueueHandle_t xQueueCreateCountingSemaphoreStatic( const UBaseType_t uxMaxCount, const UBaseType_t uxInitialCount, StaticQueue_t *pxStaticQueue ) - { - QueueHandle_t xHandle; - - configASSERT( uxMaxCount != 0 ); - configASSERT( uxInitialCount <= uxMaxCount ); - - xHandle = xQueueGenericCreateStatic( uxMaxCount, queueSEMAPHORE_QUEUE_ITEM_LENGTH, NULL, pxStaticQueue, queueQUEUE_TYPE_COUNTING_SEMAPHORE ); - - if( xHandle != NULL ) - { - ( ( Queue_t * ) xHandle )->uxMessagesWaiting = uxInitialCount; - - traceCREATE_COUNTING_SEMAPHORE(); - } - else - { - traceCREATE_COUNTING_SEMAPHORE_FAILED(); - } - - return xHandle; - } - -#endif /* ( ( configUSE_COUNTING_SEMAPHORES == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) */ -/*-----------------------------------------------------------*/ - -#if( ( configUSE_COUNTING_SEMAPHORES == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) - - QueueHandle_t xQueueCreateCountingSemaphore( const UBaseType_t uxMaxCount, const UBaseType_t uxInitialCount ) - { - QueueHandle_t xHandle; - - configASSERT( uxMaxCount != 0 ); - configASSERT( uxInitialCount <= uxMaxCount ); - - xHandle = xQueueGenericCreate( uxMaxCount, queueSEMAPHORE_QUEUE_ITEM_LENGTH, queueQUEUE_TYPE_COUNTING_SEMAPHORE ); - - if( xHandle != NULL ) - { - ( ( Queue_t * ) xHandle )->uxMessagesWaiting = uxInitialCount; - - traceCREATE_COUNTING_SEMAPHORE(); - } - else - { - traceCREATE_COUNTING_SEMAPHORE_FAILED(); - } - - return xHandle; - } - -#endif /* ( ( configUSE_COUNTING_SEMAPHORES == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) */ -/*-----------------------------------------------------------*/ - -BaseType_t xQueueGenericSend( QueueHandle_t xQueue, const void * const pvItemToQueue, TickType_t xTicksToWait, const BaseType_t xCopyPosition ) -{ -BaseType_t xEntryTimeSet = pdFALSE, xYieldRequired; -TimeOut_t xTimeOut; -Queue_t * const pxQueue = ( Queue_t * ) xQueue; - - configASSERT( pxQueue ); - configASSERT( !( ( pvItemToQueue == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) ); - configASSERT( !( ( xCopyPosition == queueOVERWRITE ) && ( pxQueue->uxLength != 1 ) ) ); - #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) - { - configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); - } - #endif - - - /* This function relaxes the coding standard somewhat to allow return - statements within the function itself. This is done in the interest - of execution time efficiency. */ - for( ;; ) - { - taskENTER_CRITICAL(); - { - /* Is there room on the queue now? The running task must be the - highest priority task wanting to access the queue. If the head item - in the queue is to be overwritten then it does not matter if the - queue is full. */ - if( ( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) || ( xCopyPosition == queueOVERWRITE ) ) - { - traceQUEUE_SEND( pxQueue ); - xYieldRequired = prvCopyDataToQueue( pxQueue, pvItemToQueue, xCopyPosition ); - - #if ( configUSE_QUEUE_SETS == 1 ) - { - if( pxQueue->pxQueueSetContainer != NULL ) - { - if( prvNotifyQueueSetContainer( pxQueue, xCopyPosition ) != pdFALSE ) - { - /* The queue is a member of a queue set, and posting - to the queue set caused a higher priority task to - unblock. A context switch is required. */ - queueYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* If there was a task waiting for data to arrive on the - queue then unblock it now. */ - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) - { - /* The unblocked task has a priority higher than - our own so yield immediately. Yes it is ok to - do this from within the critical section - the - kernel takes care of that. */ - queueYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else if( xYieldRequired != pdFALSE ) - { - /* This path is a special case that will only get - executed if the task was holding multiple mutexes - and the mutexes were given back in an order that is - different to that in which they were taken. */ - queueYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } - #else /* configUSE_QUEUE_SETS */ - { - /* If there was a task waiting for data to arrive on the - queue then unblock it now. */ - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) - { - /* The unblocked task has a priority higher than - our own so yield immediately. Yes it is ok to do - this from within the critical section - the kernel - takes care of that. */ - queueYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else if( xYieldRequired != pdFALSE ) - { - /* This path is a special case that will only get - executed if the task was holding multiple mutexes and - the mutexes were given back in an order that is - different to that in which they were taken. */ - queueYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configUSE_QUEUE_SETS */ - - taskEXIT_CRITICAL(); - return pdPASS; - } - else - { - if( xTicksToWait == ( TickType_t ) 0 ) - { - /* The queue was full and no block time is specified (or - the block time has expired) so leave now. */ - taskEXIT_CRITICAL(); - - /* Return to the original privilege level before exiting - the function. */ - traceQUEUE_SEND_FAILED( pxQueue ); - return errQUEUE_FULL; - } - else if( xEntryTimeSet == pdFALSE ) - { - /* The queue was full and a block time was specified so - configure the timeout structure. */ - vTaskInternalSetTimeOutState( &xTimeOut ); - xEntryTimeSet = pdTRUE; - } - else - { - /* Entry time was already set. */ - mtCOVERAGE_TEST_MARKER(); - } - } - } - taskEXIT_CRITICAL(); - - /* Interrupts and other tasks can send to and receive from the queue - now the critical section has been exited. */ - - vTaskSuspendAll(); - prvLockQueue( pxQueue ); - - /* Update the timeout state to see if it has expired yet. */ - if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ) - { - if( prvIsQueueFull( pxQueue ) != pdFALSE ) - { - traceBLOCKING_ON_QUEUE_SEND( pxQueue ); - vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToSend ), xTicksToWait ); - - /* Unlocking the queue means queue events can effect the - event list. It is possible that interrupts occurring now - remove this task from the event list again - but as the - scheduler is suspended the task will go onto the pending - ready last instead of the actual ready list. */ - prvUnlockQueue( pxQueue ); - - /* Resuming the scheduler will move tasks from the pending - ready list into the ready list - so it is feasible that this - task is already in a ready list before it yields - in which - case the yield will not cause a context switch unless there - is also a higher priority task in the pending ready list. */ - if( xTaskResumeAll() == pdFALSE ) - { - portYIELD_WITHIN_API(); - } - } - else - { - /* Try again. */ - prvUnlockQueue( pxQueue ); - ( void ) xTaskResumeAll(); - } - } - else - { - /* The timeout has expired. */ - prvUnlockQueue( pxQueue ); - ( void ) xTaskResumeAll(); - - traceQUEUE_SEND_FAILED( pxQueue ); - return errQUEUE_FULL; - } - } -} -/*-----------------------------------------------------------*/ - -BaseType_t xQueueGenericSendFromISR( QueueHandle_t xQueue, const void * const pvItemToQueue, BaseType_t * const pxHigherPriorityTaskWoken, const BaseType_t xCopyPosition ) -{ -BaseType_t xReturn; -UBaseType_t uxSavedInterruptStatus; -Queue_t * const pxQueue = ( Queue_t * ) xQueue; - - configASSERT( pxQueue ); - configASSERT( !( ( pvItemToQueue == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) ); - configASSERT( !( ( xCopyPosition == queueOVERWRITE ) && ( pxQueue->uxLength != 1 ) ) ); - - /* RTOS ports that support interrupt nesting have the concept of a maximum - system call (or maximum API call) interrupt priority. Interrupts that are - above the maximum system call priority are kept permanently enabled, even - when the RTOS kernel is in a critical section, but cannot make any calls to - FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h - then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion - failure if a FreeRTOS API function is called from an interrupt that has been - assigned a priority above the configured maximum system call priority. - Only FreeRTOS functions that end in FromISR can be called from interrupts - that have been assigned a priority at or (logically) below the maximum - system call interrupt priority. FreeRTOS maintains a separate interrupt - safe API to ensure interrupt entry is as fast and as simple as possible. - More information (albeit Cortex-M specific) is provided on the following - link: http://www.freertos.org/RTOS-Cortex-M3-M4.html */ - portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); - - /* Similar to xQueueGenericSend, except without blocking if there is no room - in the queue. Also don't directly wake a task that was blocked on a queue - read, instead return a flag to say whether a context switch is required or - not (i.e. has a task with a higher priority than us been woken by this - post). */ - uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); - { - if( ( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) || ( xCopyPosition == queueOVERWRITE ) ) - { - const int8_t cTxLock = pxQueue->cTxLock; - - traceQUEUE_SEND_FROM_ISR( pxQueue ); - - /* Semaphores use xQueueGiveFromISR(), so pxQueue will not be a - semaphore or mutex. That means prvCopyDataToQueue() cannot result - in a task disinheriting a priority and prvCopyDataToQueue() can be - called here even though the disinherit function does not check if - the scheduler is suspended before accessing the ready lists. */ - ( void ) prvCopyDataToQueue( pxQueue, pvItemToQueue, xCopyPosition ); - - /* The event list is not altered if the queue is locked. This will - be done when the queue is unlocked later. */ - if( cTxLock == queueUNLOCKED ) - { - #if ( configUSE_QUEUE_SETS == 1 ) - { - if( pxQueue->pxQueueSetContainer != NULL ) - { - if( prvNotifyQueueSetContainer( pxQueue, xCopyPosition ) != pdFALSE ) - { - /* The queue is a member of a queue set, and posting - to the queue set caused a higher priority task to - unblock. A context switch is required. */ - if( pxHigherPriorityTaskWoken != NULL ) - { - *pxHigherPriorityTaskWoken = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) - { - /* The task waiting has a higher priority so - record that a context switch is required. */ - if( pxHigherPriorityTaskWoken != NULL ) - { - *pxHigherPriorityTaskWoken = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } - #else /* configUSE_QUEUE_SETS */ - { - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) - { - /* The task waiting has a higher priority so record that a - context switch is required. */ - if( pxHigherPriorityTaskWoken != NULL ) - { - *pxHigherPriorityTaskWoken = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configUSE_QUEUE_SETS */ - } - else - { - /* Increment the lock count so the task that unlocks the queue - knows that data was posted while it was locked. */ - pxQueue->cTxLock = ( int8_t ) ( cTxLock + 1 ); - } - - xReturn = pdPASS; - } - else - { - traceQUEUE_SEND_FROM_ISR_FAILED( pxQueue ); - xReturn = errQUEUE_FULL; - } - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - - return xReturn; -} -/*-----------------------------------------------------------*/ - -BaseType_t xQueueGiveFromISR( QueueHandle_t xQueue, BaseType_t * const pxHigherPriorityTaskWoken ) -{ -BaseType_t xReturn; -UBaseType_t uxSavedInterruptStatus; -Queue_t * const pxQueue = ( Queue_t * ) xQueue; - - /* Similar to xQueueGenericSendFromISR() but used with semaphores where the - item size is 0. Don't directly wake a task that was blocked on a queue - read, instead return a flag to say whether a context switch is required or - not (i.e. has a task with a higher priority than us been woken by this - post). */ - - configASSERT( pxQueue ); - - /* xQueueGenericSendFromISR() should be used instead of xQueueGiveFromISR() - if the item size is not 0. */ - configASSERT( pxQueue->uxItemSize == 0 ); - - /* Normally a mutex would not be given from an interrupt, especially if - there is a mutex holder, as priority inheritance makes no sense for an - interrupts, only tasks. */ - configASSERT( !( ( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) && ( pxQueue->pxMutexHolder != NULL ) ) ); - - /* RTOS ports that support interrupt nesting have the concept of a maximum - system call (or maximum API call) interrupt priority. Interrupts that are - above the maximum system call priority are kept permanently enabled, even - when the RTOS kernel is in a critical section, but cannot make any calls to - FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h - then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion - failure if a FreeRTOS API function is called from an interrupt that has been - assigned a priority above the configured maximum system call priority. - Only FreeRTOS functions that end in FromISR can be called from interrupts - that have been assigned a priority at or (logically) below the maximum - system call interrupt priority. FreeRTOS maintains a separate interrupt - safe API to ensure interrupt entry is as fast and as simple as possible. - More information (albeit Cortex-M specific) is provided on the following - link: http://www.freertos.org/RTOS-Cortex-M3-M4.html */ - portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); - - uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); - { - const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting; - - /* When the queue is used to implement a semaphore no data is ever - moved through the queue but it is still valid to see if the queue 'has - space'. */ - if( uxMessagesWaiting < pxQueue->uxLength ) - { - const int8_t cTxLock = pxQueue->cTxLock; - - traceQUEUE_SEND_FROM_ISR( pxQueue ); - - /* A task can only have an inherited priority if it is a mutex - holder - and if there is a mutex holder then the mutex cannot be - given from an ISR. As this is the ISR version of the function it - can be assumed there is no mutex holder and no need to determine if - priority disinheritance is needed. Simply increase the count of - messages (semaphores) available. */ - pxQueue->uxMessagesWaiting = uxMessagesWaiting + ( UBaseType_t ) 1; - - /* The event list is not altered if the queue is locked. This will - be done when the queue is unlocked later. */ - if( cTxLock == queueUNLOCKED ) - { - #if ( configUSE_QUEUE_SETS == 1 ) - { - if( pxQueue->pxQueueSetContainer != NULL ) - { - if( prvNotifyQueueSetContainer( pxQueue, queueSEND_TO_BACK ) != pdFALSE ) - { - /* The semaphore is a member of a queue set, and - posting to the queue set caused a higher priority - task to unblock. A context switch is required. */ - if( pxHigherPriorityTaskWoken != NULL ) - { - *pxHigherPriorityTaskWoken = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) - { - /* The task waiting has a higher priority so - record that a context switch is required. */ - if( pxHigherPriorityTaskWoken != NULL ) - { - *pxHigherPriorityTaskWoken = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } - #else /* configUSE_QUEUE_SETS */ - { - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) - { - /* The task waiting has a higher priority so record that a - context switch is required. */ - if( pxHigherPriorityTaskWoken != NULL ) - { - *pxHigherPriorityTaskWoken = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configUSE_QUEUE_SETS */ - } - else - { - /* Increment the lock count so the task that unlocks the queue - knows that data was posted while it was locked. */ - pxQueue->cTxLock = ( int8_t ) ( cTxLock + 1 ); - } - - xReturn = pdPASS; - } - else - { - traceQUEUE_SEND_FROM_ISR_FAILED( pxQueue ); - xReturn = errQUEUE_FULL; - } - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - - return xReturn; -} -/*-----------------------------------------------------------*/ - -BaseType_t xQueueReceive( QueueHandle_t xQueue, void * const pvBuffer, TickType_t xTicksToWait ) -{ -BaseType_t xEntryTimeSet = pdFALSE; -TimeOut_t xTimeOut; -Queue_t * const pxQueue = ( Queue_t * ) xQueue; - - /* Check the pointer is not NULL. */ - configASSERT( ( pxQueue ) ); - - /* The buffer into which data is received can only be NULL if the data size - is zero (so no data is copied into the buffer. */ - configASSERT( !( ( ( pvBuffer ) == NULL ) && ( ( pxQueue )->uxItemSize != ( UBaseType_t ) 0U ) ) ); - - /* Cannot block if the scheduler is suspended. */ - #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) - { - configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); - } - #endif - - - /* This function relaxes the coding standard somewhat to allow return - statements within the function itself. This is done in the interest - of execution time efficiency. */ - - for( ;; ) - { - taskENTER_CRITICAL(); - { - const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting; - - /* Is there data in the queue now? To be running the calling task - must be the highest priority task wanting to access the queue. */ - if( uxMessagesWaiting > ( UBaseType_t ) 0 ) - { - /* Data available, remove one item. */ - prvCopyDataFromQueue( pxQueue, pvBuffer ); - traceQUEUE_RECEIVE( pxQueue ); - pxQueue->uxMessagesWaiting = uxMessagesWaiting - ( UBaseType_t ) 1; - - /* There is now space in the queue, were any tasks waiting to - post to the queue? If so, unblock the highest priority waiting - task. */ - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) - { - queueYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - taskEXIT_CRITICAL(); - return pdPASS; - } - else - { - if( xTicksToWait == ( TickType_t ) 0 ) - { - /* The queue was empty and no block time is specified (or - the block time has expired) so leave now. */ - taskEXIT_CRITICAL(); - traceQUEUE_RECEIVE_FAILED( pxQueue ); - return errQUEUE_EMPTY; - } - else if( xEntryTimeSet == pdFALSE ) - { - /* The queue was empty and a block time was specified so - configure the timeout structure. */ - vTaskInternalSetTimeOutState( &xTimeOut ); - xEntryTimeSet = pdTRUE; - } - else - { - /* Entry time was already set. */ - mtCOVERAGE_TEST_MARKER(); - } - } - } - taskEXIT_CRITICAL(); - - /* Interrupts and other tasks can send to and receive from the queue - now the critical section has been exited. */ - - vTaskSuspendAll(); - prvLockQueue( pxQueue ); - - /* Update the timeout state to see if it has expired yet. */ - if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ) - { - /* The timeout has not expired. If the queue is still empty place - the task on the list of tasks waiting to receive from the queue. */ - if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) - { - traceBLOCKING_ON_QUEUE_RECEIVE( pxQueue ); - vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait ); - prvUnlockQueue( pxQueue ); - if( xTaskResumeAll() == pdFALSE ) - { - portYIELD_WITHIN_API(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* The queue contains data again. Loop back to try and read the - data. */ - prvUnlockQueue( pxQueue ); - ( void ) xTaskResumeAll(); - } - } - else - { - /* Timed out. If there is no data in the queue exit, otherwise loop - back and attempt to read the data. */ - prvUnlockQueue( pxQueue ); - ( void ) xTaskResumeAll(); - - if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) - { - traceQUEUE_RECEIVE_FAILED( pxQueue ); - return errQUEUE_EMPTY; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } -} -/*-----------------------------------------------------------*/ - -BaseType_t xQueueSemaphoreTake( QueueHandle_t xQueue, TickType_t xTicksToWait ) -{ -BaseType_t xEntryTimeSet = pdFALSE; -TimeOut_t xTimeOut; -Queue_t * const pxQueue = ( Queue_t * ) xQueue; - -#if( configUSE_MUTEXES == 1 ) - BaseType_t xInheritanceOccurred = pdFALSE; -#endif - - /* Check the queue pointer is not NULL. */ - configASSERT( ( pxQueue ) ); - - /* Check this really is a semaphore, in which case the item size will be - 0. */ - configASSERT( pxQueue->uxItemSize == 0 ); - - /* Cannot block if the scheduler is suspended. */ - #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) - { - configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); - } - #endif - - - /* This function relaxes the coding standard somewhat to allow return - statements within the function itself. This is done in the interest - of execution time efficiency. */ - - for( ;; ) - { - taskENTER_CRITICAL(); - { - /* Semaphores are queues with an item size of 0, and where the - number of messages in the queue is the semaphore's count value. */ - const UBaseType_t uxSemaphoreCount = pxQueue->uxMessagesWaiting; - - /* Is there data in the queue now? To be running the calling task - must be the highest priority task wanting to access the queue. */ - if( uxSemaphoreCount > ( UBaseType_t ) 0 ) - { - traceQUEUE_RECEIVE( pxQueue ); - - /* Semaphores are queues with a data size of zero and where the - messages waiting is the semaphore's count. Reduce the count. */ - pxQueue->uxMessagesWaiting = uxSemaphoreCount - ( UBaseType_t ) 1; - - #if ( configUSE_MUTEXES == 1 ) - { - if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) - { - /* Record the information required to implement - priority inheritance should it become necessary. */ - pxQueue->pxMutexHolder = ( int8_t * ) pvTaskIncrementMutexHeldCount(); /*lint !e961 Cast is not redundant as TaskHandle_t is a typedef. */ - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configUSE_MUTEXES */ - - /* Check to see if other tasks are blocked waiting to give the - semaphore, and if so, unblock the highest priority such task. */ - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) - { - queueYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - taskEXIT_CRITICAL(); - return pdPASS; - } - else - { - if( xTicksToWait == ( TickType_t ) 0 ) - { - /* For inheritance to have occurred there must have been an - initial timeout, and an adjusted timeout cannot become 0, as - if it were 0 the function would have exited. */ - #if( configUSE_MUTEXES == 1 ) - { - configASSERT( xInheritanceOccurred == pdFALSE ); - } - #endif /* configUSE_MUTEXES */ - - /* The semaphore count was 0 and no block time is specified - (or the block time has expired) so exit now. */ - taskEXIT_CRITICAL(); - traceQUEUE_RECEIVE_FAILED( pxQueue ); - return errQUEUE_EMPTY; - } - else if( xEntryTimeSet == pdFALSE ) - { - /* The semaphore count was 0 and a block time was specified - so configure the timeout structure ready to block. */ - vTaskInternalSetTimeOutState( &xTimeOut ); - xEntryTimeSet = pdTRUE; - } - else - { - /* Entry time was already set. */ - mtCOVERAGE_TEST_MARKER(); - } - } - } - taskEXIT_CRITICAL(); - - /* Interrupts and other tasks can give to and take from the semaphore - now the critical section has been exited. */ - - vTaskSuspendAll(); - prvLockQueue( pxQueue ); - - /* Update the timeout state to see if it has expired yet. */ - if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ) - { - /* A block time is specified and not expired. If the semaphore - count is 0 then enter the Blocked state to wait for a semaphore to - become available. As semaphores are implemented with queues the - queue being empty is equivalent to the semaphore count being 0. */ - if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) - { - traceBLOCKING_ON_QUEUE_RECEIVE( pxQueue ); - - #if ( configUSE_MUTEXES == 1 ) - { - if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) - { - taskENTER_CRITICAL(); - { - xInheritanceOccurred = xTaskPriorityInherit( ( void * ) pxQueue->pxMutexHolder ); - } - taskEXIT_CRITICAL(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif - - vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait ); - prvUnlockQueue( pxQueue ); - if( xTaskResumeAll() == pdFALSE ) - { - portYIELD_WITHIN_API(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* There was no timeout and the semaphore count was not 0, so - attempt to take the semaphore again. */ - prvUnlockQueue( pxQueue ); - ( void ) xTaskResumeAll(); - } - } - else - { - /* Timed out. */ - prvUnlockQueue( pxQueue ); - ( void ) xTaskResumeAll(); - - /* If the semaphore count is 0 exit now as the timeout has - expired. Otherwise return to attempt to take the semaphore that is - known to be available. As semaphores are implemented by queues the - queue being empty is equivalent to the semaphore count being 0. */ - if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) - { - #if ( configUSE_MUTEXES == 1 ) - { - /* xInheritanceOccurred could only have be set if - pxQueue->uxQueueType == queueQUEUE_IS_MUTEX so no need to - test the mutex type again to check it is actually a mutex. */ - if( xInheritanceOccurred != pdFALSE ) - { - taskENTER_CRITICAL(); - { - UBaseType_t uxHighestWaitingPriority; - - /* This task blocking on the mutex caused another - task to inherit this task's priority. Now this task - has timed out the priority should be disinherited - again, but only as low as the next highest priority - task that is waiting for the same mutex. */ - uxHighestWaitingPriority = prvGetDisinheritPriorityAfterTimeout( pxQueue ); - vTaskPriorityDisinheritAfterTimeout( ( void * ) pxQueue->pxMutexHolder, uxHighestWaitingPriority ); - } - taskEXIT_CRITICAL(); - } - } - #endif /* configUSE_MUTEXES */ - - traceQUEUE_RECEIVE_FAILED( pxQueue ); - return errQUEUE_EMPTY; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } -} -/*-----------------------------------------------------------*/ - -BaseType_t xQueuePeek( QueueHandle_t xQueue, void * const pvBuffer, TickType_t xTicksToWait ) -{ -BaseType_t xEntryTimeSet = pdFALSE; -TimeOut_t xTimeOut; -int8_t *pcOriginalReadPosition; -Queue_t * const pxQueue = ( Queue_t * ) xQueue; - - /* Check the pointer is not NULL. */ - configASSERT( ( pxQueue ) ); - - /* The buffer into which data is received can only be NULL if the data size - is zero (so no data is copied into the buffer. */ - configASSERT( !( ( ( pvBuffer ) == NULL ) && ( ( pxQueue )->uxItemSize != ( UBaseType_t ) 0U ) ) ); - - /* Cannot block if the scheduler is suspended. */ - #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) - { - configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); - } - #endif - - - /* This function relaxes the coding standard somewhat to allow return - statements within the function itself. This is done in the interest - of execution time efficiency. */ - - for( ;; ) - { - taskENTER_CRITICAL(); - { - const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting; - - /* Is there data in the queue now? To be running the calling task - must be the highest priority task wanting to access the queue. */ - if( uxMessagesWaiting > ( UBaseType_t ) 0 ) - { - /* Remember the read position so it can be reset after the data - is read from the queue as this function is only peeking the - data, not removing it. */ - pcOriginalReadPosition = pxQueue->u.pcReadFrom; - - prvCopyDataFromQueue( pxQueue, pvBuffer ); - traceQUEUE_PEEK( pxQueue ); - - /* The data is not being removed, so reset the read pointer. */ - pxQueue->u.pcReadFrom = pcOriginalReadPosition; - - /* The data is being left in the queue, so see if there are - any other tasks waiting for the data. */ - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) - { - /* The task waiting has a higher priority than this task. */ - queueYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - taskEXIT_CRITICAL(); - return pdPASS; - } - else - { - if( xTicksToWait == ( TickType_t ) 0 ) - { - /* The queue was empty and no block time is specified (or - the block time has expired) so leave now. */ - taskEXIT_CRITICAL(); - traceQUEUE_PEEK_FAILED( pxQueue ); - return errQUEUE_EMPTY; - } - else if( xEntryTimeSet == pdFALSE ) - { - /* The queue was empty and a block time was specified so - configure the timeout structure ready to enter the blocked - state. */ - vTaskInternalSetTimeOutState( &xTimeOut ); - xEntryTimeSet = pdTRUE; - } - else - { - /* Entry time was already set. */ - mtCOVERAGE_TEST_MARKER(); - } - } - } - taskEXIT_CRITICAL(); - - /* Interrupts and other tasks can send to and receive from the queue - now the critical section has been exited. */ - - vTaskSuspendAll(); - prvLockQueue( pxQueue ); - - /* Update the timeout state to see if it has expired yet. */ - if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ) - { - /* Timeout has not expired yet, check to see if there is data in the - queue now, and if not enter the Blocked state to wait for data. */ - if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) - { - traceBLOCKING_ON_QUEUE_PEEK( pxQueue ); - vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait ); - prvUnlockQueue( pxQueue ); - if( xTaskResumeAll() == pdFALSE ) - { - portYIELD_WITHIN_API(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* There is data in the queue now, so don't enter the blocked - state, instead return to try and obtain the data. */ - prvUnlockQueue( pxQueue ); - ( void ) xTaskResumeAll(); - } - } - else - { - /* The timeout has expired. If there is still no data in the queue - exit, otherwise go back and try to read the data again. */ - prvUnlockQueue( pxQueue ); - ( void ) xTaskResumeAll(); - - if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) - { - traceQUEUE_PEEK_FAILED( pxQueue ); - return errQUEUE_EMPTY; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } -} -/*-----------------------------------------------------------*/ - -BaseType_t xQueueReceiveFromISR( QueueHandle_t xQueue, void * const pvBuffer, BaseType_t * const pxHigherPriorityTaskWoken ) -{ -BaseType_t xReturn; -UBaseType_t uxSavedInterruptStatus; -Queue_t * const pxQueue = ( Queue_t * ) xQueue; - - configASSERT( pxQueue ); - configASSERT( !( ( pvBuffer == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) ); - - /* RTOS ports that support interrupt nesting have the concept of a maximum - system call (or maximum API call) interrupt priority. Interrupts that are - above the maximum system call priority are kept permanently enabled, even - when the RTOS kernel is in a critical section, but cannot make any calls to - FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h - then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion - failure if a FreeRTOS API function is called from an interrupt that has been - assigned a priority above the configured maximum system call priority. - Only FreeRTOS functions that end in FromISR can be called from interrupts - that have been assigned a priority at or (logically) below the maximum - system call interrupt priority. FreeRTOS maintains a separate interrupt - safe API to ensure interrupt entry is as fast and as simple as possible. - More information (albeit Cortex-M specific) is provided on the following - link: http://www.freertos.org/RTOS-Cortex-M3-M4.html */ - portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); - - uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); - { - const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting; - - /* Cannot block in an ISR, so check there is data available. */ - if( uxMessagesWaiting > ( UBaseType_t ) 0 ) - { - const int8_t cRxLock = pxQueue->cRxLock; - - traceQUEUE_RECEIVE_FROM_ISR( pxQueue ); - - prvCopyDataFromQueue( pxQueue, pvBuffer ); - pxQueue->uxMessagesWaiting = uxMessagesWaiting - ( UBaseType_t ) 1; - - /* If the queue is locked the event list will not be modified. - Instead update the lock count so the task that unlocks the queue - will know that an ISR has removed data while the queue was - locked. */ - if( cRxLock == queueUNLOCKED ) - { - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) - { - /* The task waiting has a higher priority than us so - force a context switch. */ - if( pxHigherPriorityTaskWoken != NULL ) - { - *pxHigherPriorityTaskWoken = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* Increment the lock count so the task that unlocks the queue - knows that data was removed while it was locked. */ - pxQueue->cRxLock = ( int8_t ) ( cRxLock + 1 ); - } - - xReturn = pdPASS; - } - else - { - xReturn = pdFAIL; - traceQUEUE_RECEIVE_FROM_ISR_FAILED( pxQueue ); - } - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - - return xReturn; -} -/*-----------------------------------------------------------*/ - -BaseType_t xQueuePeekFromISR( QueueHandle_t xQueue, void * const pvBuffer ) -{ -BaseType_t xReturn; -UBaseType_t uxSavedInterruptStatus; -int8_t *pcOriginalReadPosition; -Queue_t * const pxQueue = ( Queue_t * ) xQueue; - - configASSERT( pxQueue ); - configASSERT( !( ( pvBuffer == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) ); - configASSERT( pxQueue->uxItemSize != 0 ); /* Can't peek a semaphore. */ - - /* RTOS ports that support interrupt nesting have the concept of a maximum - system call (or maximum API call) interrupt priority. Interrupts that are - above the maximum system call priority are kept permanently enabled, even - when the RTOS kernel is in a critical section, but cannot make any calls to - FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h - then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion - failure if a FreeRTOS API function is called from an interrupt that has been - assigned a priority above the configured maximum system call priority. - Only FreeRTOS functions that end in FromISR can be called from interrupts - that have been assigned a priority at or (logically) below the maximum - system call interrupt priority. FreeRTOS maintains a separate interrupt - safe API to ensure interrupt entry is as fast and as simple as possible. - More information (albeit Cortex-M specific) is provided on the following - link: http://www.freertos.org/RTOS-Cortex-M3-M4.html */ - portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); - - uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); - { - /* Cannot block in an ISR, so check there is data available. */ - if( pxQueue->uxMessagesWaiting > ( UBaseType_t ) 0 ) - { - traceQUEUE_PEEK_FROM_ISR( pxQueue ); - - /* Remember the read position so it can be reset as nothing is - actually being removed from the queue. */ - pcOriginalReadPosition = pxQueue->u.pcReadFrom; - prvCopyDataFromQueue( pxQueue, pvBuffer ); - pxQueue->u.pcReadFrom = pcOriginalReadPosition; - - xReturn = pdPASS; - } - else - { - xReturn = pdFAIL; - traceQUEUE_PEEK_FROM_ISR_FAILED( pxQueue ); - } - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - - return xReturn; -} -/*-----------------------------------------------------------*/ - -UBaseType_t uxQueueMessagesWaiting( const QueueHandle_t xQueue ) -{ -UBaseType_t uxReturn; - - configASSERT( xQueue ); - - taskENTER_CRITICAL(); - { - uxReturn = ( ( Queue_t * ) xQueue )->uxMessagesWaiting; - } - taskEXIT_CRITICAL(); - - return uxReturn; -} /*lint !e818 Pointer cannot be declared const as xQueue is a typedef not pointer. */ -/*-----------------------------------------------------------*/ - -UBaseType_t uxQueueSpacesAvailable( const QueueHandle_t xQueue ) -{ -UBaseType_t uxReturn; -Queue_t *pxQueue; - - pxQueue = ( Queue_t * ) xQueue; - configASSERT( pxQueue ); - - taskENTER_CRITICAL(); - { - uxReturn = pxQueue->uxLength - pxQueue->uxMessagesWaiting; - } - taskEXIT_CRITICAL(); - - return uxReturn; -} /*lint !e818 Pointer cannot be declared const as xQueue is a typedef not pointer. */ -/*-----------------------------------------------------------*/ - -UBaseType_t uxQueueMessagesWaitingFromISR( const QueueHandle_t xQueue ) -{ -UBaseType_t uxReturn; - - configASSERT( xQueue ); - - uxReturn = ( ( Queue_t * ) xQueue )->uxMessagesWaiting; - - return uxReturn; -} /*lint !e818 Pointer cannot be declared const as xQueue is a typedef not pointer. */ -/*-----------------------------------------------------------*/ - -void vQueueDelete( QueueHandle_t xQueue ) -{ -Queue_t * const pxQueue = ( Queue_t * ) xQueue; - - configASSERT( pxQueue ); - traceQUEUE_DELETE( pxQueue ); - - #if ( configQUEUE_REGISTRY_SIZE > 0 ) - { - vQueueUnregisterQueue( pxQueue ); - } - #endif - - #if( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 0 ) ) - { - /* The queue can only have been allocated dynamically - free it - again. */ - vPortFree( pxQueue ); - } - #elif( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) - { - /* The queue could have been allocated statically or dynamically, so - check before attempting to free the memory. */ - if( pxQueue->ucStaticallyAllocated == ( uint8_t ) pdFALSE ) - { - vPortFree( pxQueue ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #else - { - /* The queue must have been statically allocated, so is not going to be - deleted. Avoid compiler warnings about the unused parameter. */ - ( void ) pxQueue; - } - #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ -} -/*-----------------------------------------------------------*/ - -#if ( configUSE_TRACE_FACILITY == 1 ) - - UBaseType_t uxQueueGetQueueNumber( QueueHandle_t xQueue ) - { - return ( ( Queue_t * ) xQueue )->uxQueueNumber; - } - -#endif /* configUSE_TRACE_FACILITY */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_TRACE_FACILITY == 1 ) - - void vQueueSetQueueNumber( QueueHandle_t xQueue, UBaseType_t uxQueueNumber ) - { - ( ( Queue_t * ) xQueue )->uxQueueNumber = uxQueueNumber; - } - -#endif /* configUSE_TRACE_FACILITY */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_TRACE_FACILITY == 1 ) - - uint8_t ucQueueGetQueueType( QueueHandle_t xQueue ) - { - return ( ( Queue_t * ) xQueue )->ucQueueType; - } - -#endif /* configUSE_TRACE_FACILITY */ -/*-----------------------------------------------------------*/ - -#if( configUSE_MUTEXES == 1 ) - - static UBaseType_t prvGetDisinheritPriorityAfterTimeout( const Queue_t * const pxQueue ) - { - UBaseType_t uxHighestPriorityOfWaitingTasks; - - /* If a task waiting for a mutex causes the mutex holder to inherit a - priority, but the waiting task times out, then the holder should - disinherit the priority - but only down to the highest priority of any - other tasks that are waiting for the same mutex. For this purpose, - return the priority of the highest priority task that is waiting for the - mutex. */ - if( listCURRENT_LIST_LENGTH( &( pxQueue->xTasksWaitingToReceive ) ) > 0 ) - { - uxHighestPriorityOfWaitingTasks = configMAX_PRIORITIES - listGET_ITEM_VALUE_OF_HEAD_ENTRY( &( pxQueue->xTasksWaitingToReceive ) ); - } - else - { - uxHighestPriorityOfWaitingTasks = tskIDLE_PRIORITY; - } - - return uxHighestPriorityOfWaitingTasks; - } - -#endif /* configUSE_MUTEXES */ -/*-----------------------------------------------------------*/ - -static BaseType_t prvCopyDataToQueue( Queue_t * const pxQueue, const void *pvItemToQueue, const BaseType_t xPosition ) -{ -BaseType_t xReturn = pdFALSE; -UBaseType_t uxMessagesWaiting; - - /* This function is called from a critical section. */ - - uxMessagesWaiting = pxQueue->uxMessagesWaiting; - - if( pxQueue->uxItemSize == ( UBaseType_t ) 0 ) - { - #if ( configUSE_MUTEXES == 1 ) - { - if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) - { - /* The mutex is no longer being held. */ - xReturn = xTaskPriorityDisinherit( ( void * ) pxQueue->pxMutexHolder ); - pxQueue->pxMutexHolder = NULL; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configUSE_MUTEXES */ - } - else if( xPosition == queueSEND_TO_BACK ) - { - ( void ) memcpy( ( void * ) pxQueue->pcWriteTo, pvItemToQueue, ( size_t ) pxQueue->uxItemSize ); /*lint !e961 !e418 MISRA exception as the casts are only redundant for some ports, plus previous logic ensures a null pointer can only be passed to memcpy() if the copy size is 0. */ - pxQueue->pcWriteTo += pxQueue->uxItemSize; - if( pxQueue->pcWriteTo >= pxQueue->pcTail ) /*lint !e946 MISRA exception justified as comparison of pointers is the cleanest solution. */ - { - pxQueue->pcWriteTo = pxQueue->pcHead; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - ( void ) memcpy( ( void * ) pxQueue->u.pcReadFrom, pvItemToQueue, ( size_t ) pxQueue->uxItemSize ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - pxQueue->u.pcReadFrom -= pxQueue->uxItemSize; - if( pxQueue->u.pcReadFrom < pxQueue->pcHead ) /*lint !e946 MISRA exception justified as comparison of pointers is the cleanest solution. */ - { - pxQueue->u.pcReadFrom = ( pxQueue->pcTail - pxQueue->uxItemSize ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - if( xPosition == queueOVERWRITE ) - { - if( uxMessagesWaiting > ( UBaseType_t ) 0 ) - { - /* An item is not being added but overwritten, so subtract - one from the recorded number of items in the queue so when - one is added again below the number of recorded items remains - correct. */ - --uxMessagesWaiting; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - - pxQueue->uxMessagesWaiting = uxMessagesWaiting + ( UBaseType_t ) 1; - - return xReturn; -} -/*-----------------------------------------------------------*/ - -static void prvCopyDataFromQueue( Queue_t * const pxQueue, void * const pvBuffer ) -{ - if( pxQueue->uxItemSize != ( UBaseType_t ) 0 ) - { - pxQueue->u.pcReadFrom += pxQueue->uxItemSize; - if( pxQueue->u.pcReadFrom >= pxQueue->pcTail ) /*lint !e946 MISRA exception justified as use of the relational operator is the cleanest solutions. */ - { - pxQueue->u.pcReadFrom = pxQueue->pcHead; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - ( void ) memcpy( ( void * ) pvBuffer, ( void * ) pxQueue->u.pcReadFrom, ( size_t ) pxQueue->uxItemSize ); /*lint !e961 !e418 MISRA exception as the casts are only redundant for some ports. Also previous logic ensures a null pointer can only be passed to memcpy() when the count is 0. */ - } -} -/*-----------------------------------------------------------*/ - -static void prvUnlockQueue( Queue_t * const pxQueue ) -{ - /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED. */ - - /* The lock counts contains the number of extra data items placed or - removed from the queue while the queue was locked. When a queue is - locked items can be added or removed, but the event lists cannot be - updated. */ - taskENTER_CRITICAL(); - { - int8_t cTxLock = pxQueue->cTxLock; - - /* See if data was added to the queue while it was locked. */ - while( cTxLock > queueLOCKED_UNMODIFIED ) - { - /* Data was posted while the queue was locked. Are any tasks - blocked waiting for data to become available? */ - #if ( configUSE_QUEUE_SETS == 1 ) - { - if( pxQueue->pxQueueSetContainer != NULL ) - { - if( prvNotifyQueueSetContainer( pxQueue, queueSEND_TO_BACK ) != pdFALSE ) - { - /* The queue is a member of a queue set, and posting to - the queue set caused a higher priority task to unblock. - A context switch is required. */ - vTaskMissedYield(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* Tasks that are removed from the event list will get - added to the pending ready list as the scheduler is still - suspended. */ - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) - { - /* The task waiting has a higher priority so record that a - context switch is required. */ - vTaskMissedYield(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - break; - } - } - } - #else /* configUSE_QUEUE_SETS */ - { - /* Tasks that are removed from the event list will get added to - the pending ready list as the scheduler is still suspended. */ - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) - { - /* The task waiting has a higher priority so record that - a context switch is required. */ - vTaskMissedYield(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - break; - } - } - #endif /* configUSE_QUEUE_SETS */ - - --cTxLock; - } - - pxQueue->cTxLock = queueUNLOCKED; - } - taskEXIT_CRITICAL(); - - /* Do the same for the Rx lock. */ - taskENTER_CRITICAL(); - { - int8_t cRxLock = pxQueue->cRxLock; - - while( cRxLock > queueLOCKED_UNMODIFIED ) - { - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) - { - vTaskMissedYield(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - --cRxLock; - } - else - { - break; - } - } - - pxQueue->cRxLock = queueUNLOCKED; - } - taskEXIT_CRITICAL(); -} -/*-----------------------------------------------------------*/ - -static BaseType_t prvIsQueueEmpty( const Queue_t *pxQueue ) -{ -BaseType_t xReturn; - - taskENTER_CRITICAL(); - { - if( pxQueue->uxMessagesWaiting == ( UBaseType_t ) 0 ) - { - xReturn = pdTRUE; - } - else - { - xReturn = pdFALSE; - } - } - taskEXIT_CRITICAL(); - - return xReturn; -} -/*-----------------------------------------------------------*/ - -BaseType_t xQueueIsQueueEmptyFromISR( const QueueHandle_t xQueue ) -{ -BaseType_t xReturn; - - configASSERT( xQueue ); - if( ( ( Queue_t * ) xQueue )->uxMessagesWaiting == ( UBaseType_t ) 0 ) - { - xReturn = pdTRUE; - } - else - { - xReturn = pdFALSE; - } - - return xReturn; -} /*lint !e818 xQueue could not be pointer to const because it is a typedef. */ -/*-----------------------------------------------------------*/ - -static BaseType_t prvIsQueueFull( const Queue_t *pxQueue ) -{ -BaseType_t xReturn; - - taskENTER_CRITICAL(); - { - if( pxQueue->uxMessagesWaiting == pxQueue->uxLength ) - { - xReturn = pdTRUE; - } - else - { - xReturn = pdFALSE; - } - } - taskEXIT_CRITICAL(); - - return xReturn; -} -/*-----------------------------------------------------------*/ - -BaseType_t xQueueIsQueueFullFromISR( const QueueHandle_t xQueue ) -{ -BaseType_t xReturn; - - configASSERT( xQueue ); - if( ( ( Queue_t * ) xQueue )->uxMessagesWaiting == ( ( Queue_t * ) xQueue )->uxLength ) - { - xReturn = pdTRUE; - } - else - { - xReturn = pdFALSE; - } - - return xReturn; -} /*lint !e818 xQueue could not be pointer to const because it is a typedef. */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_CO_ROUTINES == 1 ) - - BaseType_t xQueueCRSend( QueueHandle_t xQueue, const void *pvItemToQueue, TickType_t xTicksToWait ) - { - BaseType_t xReturn; - Queue_t * const pxQueue = ( Queue_t * ) xQueue; - - /* If the queue is already full we may have to block. A critical section - is required to prevent an interrupt removing something from the queue - between the check to see if the queue is full and blocking on the queue. */ - portDISABLE_INTERRUPTS(); - { - if( prvIsQueueFull( pxQueue ) != pdFALSE ) - { - /* The queue is full - do we want to block or just leave without - posting? */ - if( xTicksToWait > ( TickType_t ) 0 ) - { - /* As this is called from a coroutine we cannot block directly, but - return indicating that we need to block. */ - vCoRoutineAddToDelayedList( xTicksToWait, &( pxQueue->xTasksWaitingToSend ) ); - portENABLE_INTERRUPTS(); - return errQUEUE_BLOCKED; - } - else - { - portENABLE_INTERRUPTS(); - return errQUEUE_FULL; - } - } - } - portENABLE_INTERRUPTS(); - - portDISABLE_INTERRUPTS(); - { - if( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) - { - /* There is room in the queue, copy the data into the queue. */ - prvCopyDataToQueue( pxQueue, pvItemToQueue, queueSEND_TO_BACK ); - xReturn = pdPASS; - - /* Were any co-routines waiting for data to become available? */ - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) - { - /* In this instance the co-routine could be placed directly - into the ready list as we are within a critical section. - Instead the same pending ready list mechanism is used as if - the event were caused from within an interrupt. */ - if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) - { - /* The co-routine waiting has a higher priority so record - that a yield might be appropriate. */ - xReturn = errQUEUE_YIELD; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - xReturn = errQUEUE_FULL; - } - } - portENABLE_INTERRUPTS(); - - return xReturn; - } - -#endif /* configUSE_CO_ROUTINES */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_CO_ROUTINES == 1 ) - - BaseType_t xQueueCRReceive( QueueHandle_t xQueue, void *pvBuffer, TickType_t xTicksToWait ) - { - BaseType_t xReturn; - Queue_t * const pxQueue = ( Queue_t * ) xQueue; - - /* If the queue is already empty we may have to block. A critical section - is required to prevent an interrupt adding something to the queue - between the check to see if the queue is empty and blocking on the queue. */ - portDISABLE_INTERRUPTS(); - { - if( pxQueue->uxMessagesWaiting == ( UBaseType_t ) 0 ) - { - /* There are no messages in the queue, do we want to block or just - leave with nothing? */ - if( xTicksToWait > ( TickType_t ) 0 ) - { - /* As this is a co-routine we cannot block directly, but return - indicating that we need to block. */ - vCoRoutineAddToDelayedList( xTicksToWait, &( pxQueue->xTasksWaitingToReceive ) ); - portENABLE_INTERRUPTS(); - return errQUEUE_BLOCKED; - } - else - { - portENABLE_INTERRUPTS(); - return errQUEUE_FULL; - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - portENABLE_INTERRUPTS(); - - portDISABLE_INTERRUPTS(); - { - if( pxQueue->uxMessagesWaiting > ( UBaseType_t ) 0 ) - { - /* Data is available from the queue. */ - pxQueue->u.pcReadFrom += pxQueue->uxItemSize; - if( pxQueue->u.pcReadFrom >= pxQueue->pcTail ) - { - pxQueue->u.pcReadFrom = pxQueue->pcHead; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - --( pxQueue->uxMessagesWaiting ); - ( void ) memcpy( ( void * ) pvBuffer, ( void * ) pxQueue->u.pcReadFrom, ( unsigned ) pxQueue->uxItemSize ); - - xReturn = pdPASS; - - /* Were any co-routines waiting for space to become available? */ - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) - { - /* In this instance the co-routine could be placed directly - into the ready list as we are within a critical section. - Instead the same pending ready list mechanism is used as if - the event were caused from within an interrupt. */ - if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) - { - xReturn = errQUEUE_YIELD; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - xReturn = pdFAIL; - } - } - portENABLE_INTERRUPTS(); - - return xReturn; - } - -#endif /* configUSE_CO_ROUTINES */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_CO_ROUTINES == 1 ) - - BaseType_t xQueueCRSendFromISR( QueueHandle_t xQueue, const void *pvItemToQueue, BaseType_t xCoRoutinePreviouslyWoken ) - { - Queue_t * const pxQueue = ( Queue_t * ) xQueue; - - /* Cannot block within an ISR so if there is no space on the queue then - exit without doing anything. */ - if( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) - { - prvCopyDataToQueue( pxQueue, pvItemToQueue, queueSEND_TO_BACK ); - - /* We only want to wake one co-routine per ISR, so check that a - co-routine has not already been woken. */ - if( xCoRoutinePreviouslyWoken == pdFALSE ) - { - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) - { - if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) - { - return pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - return xCoRoutinePreviouslyWoken; - } - -#endif /* configUSE_CO_ROUTINES */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_CO_ROUTINES == 1 ) - - BaseType_t xQueueCRReceiveFromISR( QueueHandle_t xQueue, void *pvBuffer, BaseType_t *pxCoRoutineWoken ) - { - BaseType_t xReturn; - Queue_t * const pxQueue = ( Queue_t * ) xQueue; - - /* We cannot block from an ISR, so check there is data available. If - not then just leave without doing anything. */ - if( pxQueue->uxMessagesWaiting > ( UBaseType_t ) 0 ) - { - /* Copy the data from the queue. */ - pxQueue->u.pcReadFrom += pxQueue->uxItemSize; - if( pxQueue->u.pcReadFrom >= pxQueue->pcTail ) - { - pxQueue->u.pcReadFrom = pxQueue->pcHead; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - --( pxQueue->uxMessagesWaiting ); - ( void ) memcpy( ( void * ) pvBuffer, ( void * ) pxQueue->u.pcReadFrom, ( unsigned ) pxQueue->uxItemSize ); - - if( ( *pxCoRoutineWoken ) == pdFALSE ) - { - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) - { - if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) - { - *pxCoRoutineWoken = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - xReturn = pdPASS; - } - else - { - xReturn = pdFAIL; - } - - return xReturn; - } - -#endif /* configUSE_CO_ROUTINES */ -/*-----------------------------------------------------------*/ - -#if ( configQUEUE_REGISTRY_SIZE > 0 ) - - void vQueueAddToRegistry( QueueHandle_t xQueue, const char *pcQueueName ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - { - UBaseType_t ux; - - /* See if there is an empty space in the registry. A NULL name denotes - a free slot. */ - for( ux = ( UBaseType_t ) 0U; ux < ( UBaseType_t ) configQUEUE_REGISTRY_SIZE; ux++ ) - { - if( xQueueRegistry[ ux ].pcQueueName == NULL ) - { - /* Store the information on this queue. */ - xQueueRegistry[ ux ].pcQueueName = pcQueueName; - xQueueRegistry[ ux ].xHandle = xQueue; - - traceQUEUE_REGISTRY_ADD( xQueue, pcQueueName ); - break; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } - -#endif /* configQUEUE_REGISTRY_SIZE */ -/*-----------------------------------------------------------*/ - -#if ( configQUEUE_REGISTRY_SIZE > 0 ) - - const char *pcQueueGetName( QueueHandle_t xQueue ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - { - UBaseType_t ux; - const char *pcReturn = NULL; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - - /* Note there is nothing here to protect against another task adding or - removing entries from the registry while it is being searched. */ - for( ux = ( UBaseType_t ) 0U; ux < ( UBaseType_t ) configQUEUE_REGISTRY_SIZE; ux++ ) - { - if( xQueueRegistry[ ux ].xHandle == xQueue ) - { - pcReturn = xQueueRegistry[ ux ].pcQueueName; - break; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - - return pcReturn; - } /*lint !e818 xQueue cannot be a pointer to const because it is a typedef. */ - -#endif /* configQUEUE_REGISTRY_SIZE */ -/*-----------------------------------------------------------*/ - -#if ( configQUEUE_REGISTRY_SIZE > 0 ) - - void vQueueUnregisterQueue( QueueHandle_t xQueue ) - { - UBaseType_t ux; - - /* See if the handle of the queue being unregistered in actually in the - registry. */ - for( ux = ( UBaseType_t ) 0U; ux < ( UBaseType_t ) configQUEUE_REGISTRY_SIZE; ux++ ) - { - if( xQueueRegistry[ ux ].xHandle == xQueue ) - { - /* Set the name to NULL to show that this slot if free again. */ - xQueueRegistry[ ux ].pcQueueName = NULL; - - /* Set the handle to NULL to ensure the same queue handle cannot - appear in the registry twice if it is added, removed, then - added again. */ - xQueueRegistry[ ux ].xHandle = ( QueueHandle_t ) 0; - break; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - - } /*lint !e818 xQueue could not be pointer to const because it is a typedef. */ - -#endif /* configQUEUE_REGISTRY_SIZE */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_TIMERS == 1 ) - - void vQueueWaitForMessageRestricted( QueueHandle_t xQueue, TickType_t xTicksToWait, const BaseType_t xWaitIndefinitely ) - { - Queue_t * const pxQueue = ( Queue_t * ) xQueue; - - /* This function should not be called by application code hence the - 'Restricted' in its name. It is not part of the public API. It is - designed for use by kernel code, and has special calling requirements. - It can result in vListInsert() being called on a list that can only - possibly ever have one item in it, so the list will be fast, but even - so it should be called with the scheduler locked and not from a critical - section. */ - - /* Only do anything if there are no messages in the queue. This function - will not actually cause the task to block, just place it on a blocked - list. It will not block until the scheduler is unlocked - at which - time a yield will be performed. If an item is added to the queue while - the queue is locked, and the calling task blocks on the queue, then the - calling task will be immediately unblocked when the queue is unlocked. */ - prvLockQueue( pxQueue ); - if( pxQueue->uxMessagesWaiting == ( UBaseType_t ) 0U ) - { - /* There is nothing in the queue, block for the specified period. */ - vTaskPlaceOnEventListRestricted( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait, xWaitIndefinitely ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - prvUnlockQueue( pxQueue ); - } - -#endif /* configUSE_TIMERS */ -/*-----------------------------------------------------------*/ - -#if( ( configUSE_QUEUE_SETS == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) - - QueueSetHandle_t xQueueCreateSet( const UBaseType_t uxEventQueueLength ) - { - QueueSetHandle_t pxQueue; - - pxQueue = xQueueGenericCreate( uxEventQueueLength, ( UBaseType_t ) sizeof( Queue_t * ), queueQUEUE_TYPE_SET ); - - return pxQueue; - } - -#endif /* configUSE_QUEUE_SETS */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_QUEUE_SETS == 1 ) - - BaseType_t xQueueAddToSet( QueueSetMemberHandle_t xQueueOrSemaphore, QueueSetHandle_t xQueueSet ) - { - BaseType_t xReturn; - - taskENTER_CRITICAL(); - { - if( ( ( Queue_t * ) xQueueOrSemaphore )->pxQueueSetContainer != NULL ) - { - /* Cannot add a queue/semaphore to more than one queue set. */ - xReturn = pdFAIL; - } - else if( ( ( Queue_t * ) xQueueOrSemaphore )->uxMessagesWaiting != ( UBaseType_t ) 0 ) - { - /* Cannot add a queue/semaphore to a queue set if there are already - items in the queue/semaphore. */ - xReturn = pdFAIL; - } - else - { - ( ( Queue_t * ) xQueueOrSemaphore )->pxQueueSetContainer = xQueueSet; - xReturn = pdPASS; - } - } - taskEXIT_CRITICAL(); - - return xReturn; - } - -#endif /* configUSE_QUEUE_SETS */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_QUEUE_SETS == 1 ) - - BaseType_t xQueueRemoveFromSet( QueueSetMemberHandle_t xQueueOrSemaphore, QueueSetHandle_t xQueueSet ) - { - BaseType_t xReturn; - Queue_t * const pxQueueOrSemaphore = ( Queue_t * ) xQueueOrSemaphore; - - if( pxQueueOrSemaphore->pxQueueSetContainer != xQueueSet ) - { - /* The queue was not a member of the set. */ - xReturn = pdFAIL; - } - else if( pxQueueOrSemaphore->uxMessagesWaiting != ( UBaseType_t ) 0 ) - { - /* It is dangerous to remove a queue from a set when the queue is - not empty because the queue set will still hold pending events for - the queue. */ - xReturn = pdFAIL; - } - else - { - taskENTER_CRITICAL(); - { - /* The queue is no longer contained in the set. */ - pxQueueOrSemaphore->pxQueueSetContainer = NULL; - } - taskEXIT_CRITICAL(); - xReturn = pdPASS; - } - - return xReturn; - } /*lint !e818 xQueueSet could not be declared as pointing to const as it is a typedef. */ - -#endif /* configUSE_QUEUE_SETS */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_QUEUE_SETS == 1 ) - - QueueSetMemberHandle_t xQueueSelectFromSet( QueueSetHandle_t xQueueSet, TickType_t const xTicksToWait ) - { - QueueSetMemberHandle_t xReturn = NULL; - - ( void ) xQueueReceive( ( QueueHandle_t ) xQueueSet, &xReturn, xTicksToWait ); /*lint !e961 Casting from one typedef to another is not redundant. */ - return xReturn; - } - -#endif /* configUSE_QUEUE_SETS */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_QUEUE_SETS == 1 ) - - QueueSetMemberHandle_t xQueueSelectFromSetFromISR( QueueSetHandle_t xQueueSet ) - { - QueueSetMemberHandle_t xReturn = NULL; - - ( void ) xQueueReceiveFromISR( ( QueueHandle_t ) xQueueSet, &xReturn, NULL ); /*lint !e961 Casting from one typedef to another is not redundant. */ - return xReturn; - } - -#endif /* configUSE_QUEUE_SETS */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_QUEUE_SETS == 1 ) - - static BaseType_t prvNotifyQueueSetContainer( const Queue_t * const pxQueue, const BaseType_t xCopyPosition ) - { - Queue_t *pxQueueSetContainer = pxQueue->pxQueueSetContainer; - BaseType_t xReturn = pdFALSE; - - /* This function must be called form a critical section. */ - - configASSERT( pxQueueSetContainer ); - configASSERT( pxQueueSetContainer->uxMessagesWaiting < pxQueueSetContainer->uxLength ); - - if( pxQueueSetContainer->uxMessagesWaiting < pxQueueSetContainer->uxLength ) - { - const int8_t cTxLock = pxQueueSetContainer->cTxLock; - - traceQUEUE_SEND( pxQueueSetContainer ); - - /* The data copied is the handle of the queue that contains data. */ - xReturn = prvCopyDataToQueue( pxQueueSetContainer, &pxQueue, xCopyPosition ); - - if( cTxLock == queueUNLOCKED ) - { - if( listLIST_IS_EMPTY( &( pxQueueSetContainer->xTasksWaitingToReceive ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueueSetContainer->xTasksWaitingToReceive ) ) != pdFALSE ) - { - /* The task waiting has a higher priority. */ - xReturn = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - pxQueueSetContainer->cTxLock = ( int8_t ) ( cTxLock + 1 ); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - return xReturn; - } - -#endif /* configUSE_QUEUE_SETS */ - - - - - - - - - - - - diff --git a/lib/FreeRTOS/Source/readme.txt b/lib/FreeRTOS/Source/readme.txt deleted file mode 100644 index 58480c56..00000000 --- a/lib/FreeRTOS/Source/readme.txt +++ /dev/null @@ -1,17 +0,0 @@ -Each real time kernel port consists of three files that contain the core kernel -components and are common to every port, and one or more files that are -specific to a particular microcontroller and or compiler. - -+ The FreeRTOS/Source directory contains the three files that are common to -every port - list.c, queue.c and tasks.c. The kernel is contained within these -three files. croutine.c implements the optional co-routine functionality - which -is normally only used on very memory limited systems. - -+ The FreeRTOS/Source/Portable directory contains the files that are specific to -a particular microcontroller and or compiler. - -+ The FreeRTOS/Source/include directory contains the real time kernel header -files. - -See the readme file in the FreeRTOS/Source/Portable directory for more -information. \ No newline at end of file diff --git a/lib/FreeRTOS/Source/stream_buffer.c b/lib/FreeRTOS/Source/stream_buffer.c deleted file mode 100644 index c60045f6..00000000 --- a/lib/FreeRTOS/Source/stream_buffer.c +++ /dev/null @@ -1,1199 +0,0 @@ -/* - * FreeRTOS Kernel V10.0.1 - * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * 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. - * - * http://www.FreeRTOS.org - * http://aws.amazon.com/freertos - * - * 1 tab == 4 spaces! - */ - -/* Standard includes. */ -#include -#include - -/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining -all the API functions to use the MPU wrappers. That should only be done when -task.h is included from an application file. */ -#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE - -/* FreeRTOS includes. */ -#include "FreeRTOS.h" -#include "task.h" -#include "stream_buffer.h" - -#if( configUSE_TASK_NOTIFICATIONS != 1 ) - #error configUSE_TASK_NOTIFICATIONS must be set to 1 to build stream_buffer.c -#endif - -/* Lint e961 and e750 are suppressed as a MISRA exception justified because the -MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be defined for the -header files above, but not in this file, in order to generate the correct -privileged Vs unprivileged linkage and placement. */ -#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /*lint !e961 !e750. */ - -/* If the user has not provided application specific Rx notification macros, -or #defined the notification macros away, them provide default implementations -that uses task notifications. */ -/*lint -save -e9026 Function like macros allowed and needed here so they can be overidden. */ -#ifndef sbRECEIVE_COMPLETED - #define sbRECEIVE_COMPLETED( pxStreamBuffer ) \ - vTaskSuspendAll(); \ - { \ - if( ( pxStreamBuffer )->xTaskWaitingToSend != NULL ) \ - { \ - ( void ) xTaskNotify( ( pxStreamBuffer )->xTaskWaitingToSend, \ - ( uint32_t ) 0, \ - eNoAction ); \ - ( pxStreamBuffer )->xTaskWaitingToSend = NULL; \ - } \ - } \ - ( void ) xTaskResumeAll(); -#endif /* sbRECEIVE_COMPLETED */ - -#ifndef sbRECEIVE_COMPLETED_FROM_ISR - #define sbRECEIVE_COMPLETED_FROM_ISR( pxStreamBuffer, \ - pxHigherPriorityTaskWoken ) \ - { \ - UBaseType_t uxSavedInterruptStatus; \ - \ - uxSavedInterruptStatus = ( UBaseType_t ) portSET_INTERRUPT_MASK_FROM_ISR(); \ - { \ - if( ( pxStreamBuffer )->xTaskWaitingToSend != NULL ) \ - { \ - ( void ) xTaskNotifyFromISR( ( pxStreamBuffer )->xTaskWaitingToSend, \ - ( uint32_t ) 0, \ - eNoAction, \ - pxHigherPriorityTaskWoken ); \ - ( pxStreamBuffer )->xTaskWaitingToSend = NULL; \ - } \ - } \ - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); \ - } -#endif /* sbRECEIVE_COMPLETED_FROM_ISR */ - -/* If the user has not provided an application specific Tx notification macro, -or #defined the notification macro away, them provide a default implementation -that uses task notifications. */ -#ifndef sbSEND_COMPLETED - #define sbSEND_COMPLETED( pxStreamBuffer ) \ - vTaskSuspendAll(); \ - { \ - if( ( pxStreamBuffer )->xTaskWaitingToReceive != NULL ) \ - { \ - ( void ) xTaskNotify( ( pxStreamBuffer )->xTaskWaitingToReceive, \ - ( uint32_t ) 0, \ - eNoAction ); \ - ( pxStreamBuffer )->xTaskWaitingToReceive = NULL; \ - } \ - } \ - ( void ) xTaskResumeAll(); -#endif /* sbSEND_COMPLETED */ - -#ifndef sbSEND_COMPLETE_FROM_ISR - #define sbSEND_COMPLETE_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken ) \ - { \ - UBaseType_t uxSavedInterruptStatus; \ - \ - uxSavedInterruptStatus = ( UBaseType_t ) portSET_INTERRUPT_MASK_FROM_ISR(); \ - { \ - if( ( pxStreamBuffer )->xTaskWaitingToReceive != NULL ) \ - { \ - ( void ) xTaskNotifyFromISR( ( pxStreamBuffer )->xTaskWaitingToReceive, \ - ( uint32_t ) 0, \ - eNoAction, \ - pxHigherPriorityTaskWoken ); \ - ( pxStreamBuffer )->xTaskWaitingToReceive = NULL; \ - } \ - } \ - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); \ - } -#endif /* sbSEND_COMPLETE_FROM_ISR */ -/*lint -restore (9026) */ - -/* The number of bytes used to hold the length of a message in the buffer. */ -#define sbBYTES_TO_STORE_MESSAGE_LENGTH ( sizeof( size_t ) ) - -/* Bits stored in the ucFlags field of the stream buffer. */ -#define sbFLAGS_IS_MESSAGE_BUFFER ( ( uint8_t ) 1 ) /* Set if the stream buffer was created as a message buffer, in which case it holds discrete messages rather than a stream. */ -#define sbFLAGS_IS_STATICALLY_ALLOCATED ( ( uint8_t ) 2 ) /* Set if the stream buffer was created using statically allocated memory. */ - -/*-----------------------------------------------------------*/ - -/* Structure that hold state information on the buffer. */ -typedef struct xSTREAM_BUFFER /*lint !e9058 Style convention uses tag. */ -{ - volatile size_t xTail; /* Index to the next item to read within the buffer. */ - volatile size_t xHead; /* Index to the next item to write within the buffer. */ - size_t xLength; /* The length of the buffer pointed to by pucBuffer. */ - size_t xTriggerLevelBytes; /* The number of bytes that must be in the stream buffer before a task that is waiting for data is unblocked. */ - volatile TaskHandle_t xTaskWaitingToReceive; /* Holds the handle of a task waiting for data, or NULL if no tasks are waiting. */ - volatile TaskHandle_t xTaskWaitingToSend; /* Holds the handle of a task waiting to send data to a message buffer that is full. */ - uint8_t *pucBuffer; /* Points to the buffer itself - that is - the RAM that stores the data passed through the buffer. */ - uint8_t ucFlags; - - #if ( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxStreamBufferNumber; /* Used for tracing purposes. */ - #endif -} StreamBuffer_t; - -/* - * The number of bytes available to be read from the buffer. - */ -static size_t prvBytesInBuffer( const StreamBuffer_t * const pxStreamBuffer ) PRIVILEGED_FUNCTION; - -/* - * Add xCount bytes from pucData into the pxStreamBuffer message buffer. - * Returns the number of bytes written, which will either equal xCount in the - * success case, or 0 if there was not enough space in the buffer (in which case - * no data is written into the buffer). - */ -static size_t prvWriteBytesToBuffer( StreamBuffer_t * const pxStreamBuffer, const uint8_t *pucData, size_t xCount ) PRIVILEGED_FUNCTION; - -/* - * If the stream buffer is being used as a message buffer, then reads an entire - * message out of the buffer. If the stream buffer is being used as a stream - * buffer then read as many bytes as possible from the buffer. - * prvReadBytesFromBuffer() is called to actually extract the bytes from the - * buffer's data storage area. - */ -static size_t prvReadMessageFromBuffer( StreamBuffer_t *pxStreamBuffer, - void *pvRxData, - size_t xBufferLengthBytes, - size_t xBytesAvailable, - size_t xBytesToStoreMessageLength ) PRIVILEGED_FUNCTION; - -/* - * If the stream buffer is being used as a message buffer, then writes an entire - * message to the buffer. If the stream buffer is being used as a stream - * buffer then write as many bytes as possible to the buffer. - * prvWriteBytestoBuffer() is called to actually send the bytes to the buffer's - * data storage area. - */ -static size_t prvWriteMessageToBuffer( StreamBuffer_t * const pxStreamBuffer, - const void * pvTxData, - size_t xDataLengthBytes, - size_t xSpace, - size_t xRequiredSpace ) PRIVILEGED_FUNCTION; - -/* - * Read xMaxCount bytes from the pxStreamBuffer message buffer and write them - * to pucData. - */ -static size_t prvReadBytesFromBuffer( StreamBuffer_t *pxStreamBuffer, - uint8_t *pucData, - size_t xMaxCount, - size_t xBytesAvailable ); PRIVILEGED_FUNCTION - -/* - * Called by both pxStreamBufferCreate() and pxStreamBufferCreateStatic() to - * initialise the members of the newly created stream buffer structure. - */ -static void prvInitialiseNewStreamBuffer( StreamBuffer_t * const pxStreamBuffer, - uint8_t * const pucBuffer, - size_t xBufferSizeBytes, - size_t xTriggerLevelBytes, - BaseType_t xIsMessageBuffer ) PRIVILEGED_FUNCTION; - -/*-----------------------------------------------------------*/ - -#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - - StreamBufferHandle_t xStreamBufferGenericCreate( size_t xBufferSizeBytes, size_t xTriggerLevelBytes, BaseType_t xIsMessageBuffer ) - { - uint8_t *pucAllocatedMemory; - - /* In case the stream buffer is going to be used as a message buffer - (that is, it will hold discrete messages with a little meta data that - says how big the next message is) check the buffer will be large enough - to hold at least one message. */ - configASSERT( xBufferSizeBytes > sbBYTES_TO_STORE_MESSAGE_LENGTH ); - configASSERT( xTriggerLevelBytes <= xBufferSizeBytes ); - - /* A trigger level of 0 would cause a waiting task to unblock even when - the buffer was empty. */ - if( xTriggerLevelBytes == ( size_t ) 0 ) - { - xTriggerLevelBytes = ( size_t ) 1; /*lint !e9044 Parameter modified to ensure it doesn't have a dangerous value. */ - } - - /* A stream buffer requires a StreamBuffer_t structure and a buffer. - Both are allocated in a single call to pvPortMalloc(). The - StreamBuffer_t structure is placed at the start of the allocated memory - and the buffer follows immediately after. The requested size is - incremented so the free space is returned as the user would expect - - this is a quirk of the implementation that means otherwise the free - space would be reported as one byte smaller than would be logically - expected. */ - xBufferSizeBytes++; - pucAllocatedMemory = ( uint8_t * ) pvPortMalloc( xBufferSizeBytes + sizeof( StreamBuffer_t ) ); /*lint !e9079 malloc() only returns void*. */ - - if( pucAllocatedMemory != NULL ) - { - prvInitialiseNewStreamBuffer( ( StreamBuffer_t * ) pucAllocatedMemory, /* Structure at the start of the allocated memory. */ /*lint !e9087 Safe cast as allocated memory is aligned. */ /*lint !e826 Area is not too small and alignment is guaranteed provided malloc() behaves as expected and returns aligned buffer. */ - pucAllocatedMemory + sizeof( StreamBuffer_t ), /* Storage area follows. */ /*lint !e9016 Indexing past structure valid for uint8_t pointer, also storage area has no alignment requirement. */ - xBufferSizeBytes, - xTriggerLevelBytes, - xIsMessageBuffer ); - - traceSTREAM_BUFFER_CREATE( ( ( StreamBuffer_t * ) pucAllocatedMemory ), xIsMessageBuffer ); - } - else - { - traceSTREAM_BUFFER_CREATE_FAILED( xIsMessageBuffer ); - } - - return ( StreamBufferHandle_t * ) pucAllocatedMemory; /*lint !e9087 !e826 Safe cast as allocated memory is aligned. */ - } - -#endif /* configSUPPORT_DYNAMIC_ALLOCATION */ -/*-----------------------------------------------------------*/ - -#if( configSUPPORT_STATIC_ALLOCATION == 1 ) - - StreamBufferHandle_t xStreamBufferGenericCreateStatic( size_t xBufferSizeBytes, - size_t xTriggerLevelBytes, - BaseType_t xIsMessageBuffer, - uint8_t * const pucStreamBufferStorageArea, - StaticStreamBuffer_t * const pxStaticStreamBuffer ) - { - StreamBuffer_t * const pxStreamBuffer = ( StreamBuffer_t * ) pxStaticStreamBuffer; /*lint !e740 !e9087 Safe cast as StaticStreamBuffer_t is opaque Streambuffer_t. */ - StreamBufferHandle_t xReturn; - - configASSERT( pucStreamBufferStorageArea ); - configASSERT( pxStaticStreamBuffer ); - configASSERT( xTriggerLevelBytes <= xBufferSizeBytes ); - - /* A trigger level of 0 would cause a waiting task to unblock even when - the buffer was empty. */ - if( xTriggerLevelBytes == ( size_t ) 0 ) - { - xTriggerLevelBytes = ( size_t ) 1; /*lint !e9044 Function parameter deliberately modified to ensure it is in range. */ - } - - /* In case the stream buffer is going to be used as a message buffer - (that is, it will hold discrete messages with a little meta data that - says how big the next message is) check the buffer will be large enough - to hold at least one message. */ - configASSERT( xBufferSizeBytes > sbBYTES_TO_STORE_MESSAGE_LENGTH ); - - #if( configASSERT_DEFINED == 1 ) - { - /* Sanity check that the size of the structure used to declare a - variable of type StaticStreamBuffer_t equals the size of the real - message buffer structure. */ - volatile size_t xSize = sizeof( StaticStreamBuffer_t ); - configASSERT( xSize == sizeof( StreamBuffer_t ) ); - } - #endif /* configASSERT_DEFINED */ - - if( ( pucStreamBufferStorageArea != NULL ) && ( pxStaticStreamBuffer != NULL ) ) - { - prvInitialiseNewStreamBuffer( pxStreamBuffer, - pucStreamBufferStorageArea, - xBufferSizeBytes, - xTriggerLevelBytes, - xIsMessageBuffer ); - - /* Remember this was statically allocated in case it is ever deleted - again. */ - pxStreamBuffer->ucFlags |= sbFLAGS_IS_STATICALLY_ALLOCATED; - - traceSTREAM_BUFFER_CREATE( pxStreamBuffer, xIsMessageBuffer ); - - xReturn = ( StreamBufferHandle_t ) pxStaticStreamBuffer; /*lint !e9087 Data hiding requires cast to opaque type. */ - } - else - { - xReturn = NULL; - traceSTREAM_BUFFER_CREATE_STATIC_FAILED( xReturn, xIsMessageBuffer ); - } - - return xReturn; - } - -#endif /* ( configSUPPORT_STATIC_ALLOCATION == 1 ) */ -/*-----------------------------------------------------------*/ - -void vStreamBufferDelete( StreamBufferHandle_t xStreamBuffer ) -{ -StreamBuffer_t * pxStreamBuffer = ( StreamBuffer_t * ) xStreamBuffer; /*lint !e9087 !e9079 Safe cast as StreamBufferHandle_t is opaque Streambuffer_t. */ - - configASSERT( pxStreamBuffer ); - - traceSTREAM_BUFFER_DELETE( xStreamBuffer ); - - if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_STATICALLY_ALLOCATED ) == ( uint8_t ) pdFALSE ) - { - #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - { - /* Both the structure and the buffer were allocated using a single call - to pvPortMalloc(), hence only one call to vPortFree() is required. */ - vPortFree( ( void * ) pxStreamBuffer ); /*lint !e9087 Standard free() semantics require void *, plus pxStreamBuffer was allocated by pvPortMalloc(). */ - } - #else - { - /* Should not be possible to get here, ucFlags must be corrupt. - Force an assert. */ - configASSERT( xStreamBuffer == ( StreamBufferHandle_t ) ~0 ); - } - #endif - } - else - { - /* The structure and buffer were not allocated dynamically and cannot be - freed - just scrub the structure so future use will assert. */ - memset( pxStreamBuffer, 0x00, sizeof( StreamBuffer_t ) ); - } -} -/*-----------------------------------------------------------*/ - -BaseType_t xStreamBufferReset( StreamBufferHandle_t xStreamBuffer ) -{ -StreamBuffer_t * const pxStreamBuffer = ( StreamBuffer_t * ) xStreamBuffer; /*lint !e9087 !e9079 Safe cast as StreamBufferHandle_t is opaque Streambuffer_t. */ -BaseType_t xReturn = pdFAIL, xIsMessageBuffer; - -#if( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxStreamBufferNumber; -#endif - - configASSERT( pxStreamBuffer ); - - #if( configUSE_TRACE_FACILITY == 1 ) - { - /* Store the stream buffer number so it can be restored after the - reset. */ - uxStreamBufferNumber = pxStreamBuffer->uxStreamBufferNumber; - } - #endif - - /* Can only reset a message buffer if there are no tasks blocked on it. */ - if( pxStreamBuffer->xTaskWaitingToReceive == NULL ) - { - if( pxStreamBuffer->xTaskWaitingToSend == NULL ) - { - if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) - { - xIsMessageBuffer = pdTRUE; - } - else - { - xIsMessageBuffer = pdFALSE; - } - - prvInitialiseNewStreamBuffer( pxStreamBuffer, - pxStreamBuffer->pucBuffer, - pxStreamBuffer->xLength, - pxStreamBuffer->xTriggerLevelBytes, - xIsMessageBuffer ); - xReturn = pdPASS; - - #if( configUSE_TRACE_FACILITY == 1 ) - { - pxStreamBuffer->uxStreamBufferNumber = uxStreamBufferNumber; - } - #endif - - traceSTREAM_BUFFER_RESET( xStreamBuffer ); - } - } - - return xReturn; -} -/*-----------------------------------------------------------*/ - -BaseType_t xStreamBufferSetTriggerLevel( StreamBufferHandle_t xStreamBuffer, size_t xTriggerLevel ) -{ -StreamBuffer_t * const pxStreamBuffer = ( StreamBuffer_t * ) xStreamBuffer; /*lint !e9087 !e9079 Safe cast as StreamBufferHandle_t is opaque Streambuffer_t. */ -BaseType_t xReturn; - - configASSERT( pxStreamBuffer ); - - /* It is not valid for the trigger level to be 0. */ - if( xTriggerLevel == ( size_t ) 0 ) - { - xTriggerLevel = ( size_t ) 1; /*lint !e9044 Parameter modified to ensure it doesn't have a dangerous value. */ - } - - /* The trigger level is the number of bytes that must be in the stream - buffer before a task that is waiting for data is unblocked. */ - if( xTriggerLevel <= pxStreamBuffer->xLength ) - { - pxStreamBuffer->xTriggerLevelBytes = xTriggerLevel; - xReturn = pdPASS; - } - else - { - xReturn = pdFALSE; - } - - return xReturn; -} -/*-----------------------------------------------------------*/ - -size_t xStreamBufferSpacesAvailable( StreamBufferHandle_t xStreamBuffer ) -{ -const StreamBuffer_t * const pxStreamBuffer = ( StreamBuffer_t * ) xStreamBuffer; /*lint !e9087 !e9079 Safe cast as StreamBufferHandle_t is opaque Streambuffer_t. */ -size_t xSpace; - - configASSERT( pxStreamBuffer ); - - xSpace = pxStreamBuffer->xLength + pxStreamBuffer->xTail; - xSpace -= pxStreamBuffer->xHead; - xSpace -= ( size_t ) 1; - - if( xSpace >= pxStreamBuffer->xLength ) - { - xSpace -= pxStreamBuffer->xLength; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - return xSpace; -} -/*-----------------------------------------------------------*/ - -size_t xStreamBufferBytesAvailable( StreamBufferHandle_t xStreamBuffer ) -{ -const StreamBuffer_t * const pxStreamBuffer = ( StreamBuffer_t * ) xStreamBuffer; /*lint !e9087 !e9079 Safe cast as StreamBufferHandle_t is opaque Streambuffer_t. */ -size_t xReturn; - - configASSERT( pxStreamBuffer ); - - xReturn = prvBytesInBuffer( pxStreamBuffer ); - return xReturn; -} -/*-----------------------------------------------------------*/ - -size_t xStreamBufferSend( StreamBufferHandle_t xStreamBuffer, - const void *pvTxData, - size_t xDataLengthBytes, - TickType_t xTicksToWait ) -{ -StreamBuffer_t * const pxStreamBuffer = ( StreamBuffer_t * ) xStreamBuffer; /*lint !e9087 !e9079 Safe cast as StreamBufferHandle_t is opaque Streambuffer_t. */ -size_t xReturn, xSpace = 0; -size_t xRequiredSpace = xDataLengthBytes; -TimeOut_t xTimeOut; - - configASSERT( pvTxData ); - configASSERT( pxStreamBuffer ); - - /* This send function is used to write to both message buffers and stream - buffers. If this is a message buffer then the space needed must be - increased by the amount of bytes needed to store the length of the - message. */ - if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) - { - xRequiredSpace += sbBYTES_TO_STORE_MESSAGE_LENGTH; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - if( xTicksToWait != ( TickType_t ) 0 ) - { - vTaskSetTimeOutState( &xTimeOut ); - - do - { - /* Wait until the required number of bytes are free in the message - buffer. */ - taskENTER_CRITICAL(); - { - xSpace = xStreamBufferSpacesAvailable( pxStreamBuffer ); - - if( xSpace < xRequiredSpace ) - { - /* Clear notification state as going to wait for space. */ - ( void ) xTaskNotifyStateClear( NULL ); - - /* Should only be one writer. */ - configASSERT( pxStreamBuffer->xTaskWaitingToSend == NULL ); - pxStreamBuffer->xTaskWaitingToSend = xTaskGetCurrentTaskHandle(); - } - else - { - taskEXIT_CRITICAL(); - break; - } - } - taskEXIT_CRITICAL(); - - traceBLOCKING_ON_STREAM_BUFFER_SEND( xStreamBuffer ); - ( void ) xTaskNotifyWait( ( uint32_t ) 0, UINT32_MAX, NULL, xTicksToWait ); - pxStreamBuffer->xTaskWaitingToSend = NULL; - - } while( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - if( xSpace == ( size_t ) 0 ) - { - xSpace = xStreamBufferSpacesAvailable( pxStreamBuffer ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - xReturn = prvWriteMessageToBuffer( pxStreamBuffer, pvTxData, xDataLengthBytes, xSpace, xRequiredSpace ); - - if( xReturn > ( size_t ) 0 ) - { - traceSTREAM_BUFFER_SEND( xStreamBuffer, xReturn ); - - /* Was a task waiting for the data? */ - if( prvBytesInBuffer( pxStreamBuffer ) >= pxStreamBuffer->xTriggerLevelBytes ) - { - sbSEND_COMPLETED( pxStreamBuffer ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - traceSTREAM_BUFFER_SEND_FAILED( xStreamBuffer ); - } - - return xReturn; -} -/*-----------------------------------------------------------*/ - -size_t xStreamBufferSendFromISR( StreamBufferHandle_t xStreamBuffer, - const void *pvTxData, - size_t xDataLengthBytes, - BaseType_t * const pxHigherPriorityTaskWoken ) -{ -StreamBuffer_t * const pxStreamBuffer = ( StreamBuffer_t * ) xStreamBuffer; /*lint !e9087 !e9079 Safe cast as StreamBufferHandle_t is opaque Streambuffer_t. */ -size_t xReturn, xSpace; -size_t xRequiredSpace = xDataLengthBytes; - - configASSERT( pvTxData ); - configASSERT( pxStreamBuffer ); - - /* This send function is used to write to both message buffers and stream - buffers. If this is a message buffer then the space needed must be - increased by the amount of bytes needed to store the length of the - message. */ - if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) - { - xRequiredSpace += sbBYTES_TO_STORE_MESSAGE_LENGTH; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - xSpace = xStreamBufferSpacesAvailable( pxStreamBuffer ); - xReturn = prvWriteMessageToBuffer( pxStreamBuffer, pvTxData, xDataLengthBytes, xSpace, xRequiredSpace ); - - if( xReturn > ( size_t ) 0 ) - { - /* Was a task waiting for the data? */ - if( prvBytesInBuffer( pxStreamBuffer ) >= pxStreamBuffer->xTriggerLevelBytes ) - { - sbSEND_COMPLETE_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - traceSTREAM_BUFFER_SEND_FROM_ISR( xStreamBuffer, xReturn ); - - return xReturn; -} -/*-----------------------------------------------------------*/ - -static size_t prvWriteMessageToBuffer( StreamBuffer_t * const pxStreamBuffer, - const void * pvTxData, - size_t xDataLengthBytes, - size_t xSpace, - size_t xRequiredSpace ) -{ - BaseType_t xShouldWrite; - size_t xReturn; - - if( xSpace == ( size_t ) 0 ) - { - /* Doesn't matter if this is a stream buffer or a message buffer, there - is no space to write. */ - xShouldWrite = pdFALSE; - } - else if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) == ( uint8_t ) 0 ) - { - /* This is a stream buffer, as opposed to a message buffer, so writing a - stream of bytes rather than discrete messages. Write as many bytes as - possible. */ - xShouldWrite = pdTRUE; - xDataLengthBytes = configMIN( xDataLengthBytes, xSpace ); /*lint !e9044 Function parameter modified to ensure it is capped to available space. */ - } - else if( xSpace >= xRequiredSpace ) - { - /* This is a message buffer, as opposed to a stream buffer, and there - is enough space to write both the message length and the message itself - into the buffer. Start by writing the length of the data, the data - itself will be written later in this function. */ - xShouldWrite = pdTRUE; - ( void ) prvWriteBytesToBuffer( pxStreamBuffer, ( const uint8_t * ) &( xDataLengthBytes ), sbBYTES_TO_STORE_MESSAGE_LENGTH ); - } - else - { - /* There is space available, but not enough space. */ - xShouldWrite = pdFALSE; - } - - if( xShouldWrite != pdFALSE ) - { - /* Writes the data itself. */ - xReturn = prvWriteBytesToBuffer( pxStreamBuffer, ( const uint8_t * ) pvTxData, xDataLengthBytes ); /*lint !e9079 Storage buffer is implemented as uint8_t for ease of sizing, alighment and access. */ - } - else - { - xReturn = 0; - } - - return xReturn; -} -/*-----------------------------------------------------------*/ - -size_t xStreamBufferReceive( StreamBufferHandle_t xStreamBuffer, - void *pvRxData, - size_t xBufferLengthBytes, - TickType_t xTicksToWait ) -{ -StreamBuffer_t * const pxStreamBuffer = ( StreamBuffer_t * ) xStreamBuffer; /*lint !e9087 !e9079 Safe cast as StreamBufferHandle_t is opaque Streambuffer_t. */ -size_t xReceivedLength = 0, xBytesAvailable, xBytesToStoreMessageLength; - - configASSERT( pvRxData ); - configASSERT( pxStreamBuffer ); - - /* This receive function is used by both message buffers, which store - discrete messages, and stream buffers, which store a continuous stream of - bytes. Discrete messages include an additional - sbBYTES_TO_STORE_MESSAGE_LENGTH bytes that hold the length of the - message. */ - if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) - { - xBytesToStoreMessageLength = sbBYTES_TO_STORE_MESSAGE_LENGTH; - } - else - { - xBytesToStoreMessageLength = 0; - } - - if( xTicksToWait != ( TickType_t ) 0 ) - { - /* Checking if there is data and clearing the notification state must be - performed atomically. */ - taskENTER_CRITICAL(); - { - xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); - - /* If this function was invoked by a message buffer read then - xBytesToStoreMessageLength holds the number of bytes used to hold - the length of the next discrete message. If this function was - invoked by a stream buffer read then xBytesToStoreMessageLength will - be 0. */ - if( xBytesAvailable <= xBytesToStoreMessageLength ) - { - /* Clear notification state as going to wait for data. */ - ( void ) xTaskNotifyStateClear( NULL ); - - /* Should only be one reader. */ - configASSERT( pxStreamBuffer->xTaskWaitingToReceive == NULL ); - pxStreamBuffer->xTaskWaitingToReceive = xTaskGetCurrentTaskHandle(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - taskEXIT_CRITICAL(); - - if( xBytesAvailable <= xBytesToStoreMessageLength ) - { - /* Wait for data to be available. */ - traceBLOCKING_ON_STREAM_BUFFER_RECEIVE( xStreamBuffer ); - ( void ) xTaskNotifyWait( ( uint32_t ) 0, UINT32_MAX, NULL, xTicksToWait ); - pxStreamBuffer->xTaskWaitingToReceive = NULL; - - /* Recheck the data available after blocking. */ - xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); - } - - /* Whether receiving a discrete message (where xBytesToStoreMessageLength - holds the number of bytes used to store the message length) or a stream of - bytes (where xBytesToStoreMessageLength is zero), the number of bytes - available must be greater than xBytesToStoreMessageLength to be able to - read bytes from the buffer. */ - if( xBytesAvailable > xBytesToStoreMessageLength ) - { - xReceivedLength = prvReadMessageFromBuffer( pxStreamBuffer, pvRxData, xBufferLengthBytes, xBytesAvailable, xBytesToStoreMessageLength ); - - /* Was a task waiting for space in the buffer? */ - if( xReceivedLength != ( size_t ) 0 ) - { - traceSTREAM_BUFFER_RECEIVE( xStreamBuffer, xReceivedLength ); - sbRECEIVE_COMPLETED( pxStreamBuffer ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - traceSTREAM_BUFFER_RECEIVE_FAILED( xStreamBuffer ); - mtCOVERAGE_TEST_MARKER(); - } - - return xReceivedLength; -} -/*-----------------------------------------------------------*/ - -size_t xStreamBufferReceiveFromISR( StreamBufferHandle_t xStreamBuffer, - void *pvRxData, - size_t xBufferLengthBytes, - BaseType_t * const pxHigherPriorityTaskWoken ) -{ -StreamBuffer_t * const pxStreamBuffer = ( StreamBuffer_t * ) xStreamBuffer; /*lint !e9087 !e9079 Safe cast as StreamBufferHandle_t is opaque Streambuffer_t. */ -size_t xReceivedLength = 0, xBytesAvailable, xBytesToStoreMessageLength; - - configASSERT( pvRxData ); - configASSERT( pxStreamBuffer ); - - /* This receive function is used by both message buffers, which store - discrete messages, and stream buffers, which store a continuous stream of - bytes. Discrete messages include an additional - sbBYTES_TO_STORE_MESSAGE_LENGTH bytes that hold the length of the - message. */ - if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) - { - xBytesToStoreMessageLength = sbBYTES_TO_STORE_MESSAGE_LENGTH; - } - else - { - xBytesToStoreMessageLength = 0; - } - - xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); - - /* Whether receiving a discrete message (where xBytesToStoreMessageLength - holds the number of bytes used to store the message length) or a stream of - bytes (where xBytesToStoreMessageLength is zero), the number of bytes - available must be greater than xBytesToStoreMessageLength to be able to - read bytes from the buffer. */ - if( xBytesAvailable > xBytesToStoreMessageLength ) - { - xReceivedLength = prvReadMessageFromBuffer( pxStreamBuffer, pvRxData, xBufferLengthBytes, xBytesAvailable, xBytesToStoreMessageLength ); - - /* Was a task waiting for space in the buffer? */ - if( xReceivedLength != ( size_t ) 0 ) - { - sbRECEIVE_COMPLETED_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - traceSTREAM_BUFFER_RECEIVE_FROM_ISR( xStreamBuffer, xReceivedLength ); - - return xReceivedLength; -} -/*-----------------------------------------------------------*/ - -static size_t prvReadMessageFromBuffer( StreamBuffer_t *pxStreamBuffer, - void *pvRxData, - size_t xBufferLengthBytes, - size_t xBytesAvailable, - size_t xBytesToStoreMessageLength ) -{ -size_t xOriginalTail, xReceivedLength, xNextMessageLength; - - if( xBytesToStoreMessageLength != ( size_t ) 0 ) - { - /* A discrete message is being received. First receive the length - of the message. A copy of the tail is stored so the buffer can be - returned to its prior state if the length of the message is too - large for the provided buffer. */ - xOriginalTail = pxStreamBuffer->xTail; - ( void ) prvReadBytesFromBuffer( pxStreamBuffer, ( uint8_t * ) &xNextMessageLength, xBytesToStoreMessageLength, xBytesAvailable ); - - /* Reduce the number of bytes available by the number of bytes just - read out. */ - xBytesAvailable -= xBytesToStoreMessageLength; - - /* Check there is enough space in the buffer provided by the - user. */ - if( xNextMessageLength > xBufferLengthBytes ) - { - /* The user has provided insufficient space to read the message - so return the buffer to its previous state (so the length of - the message is in the buffer again). */ - pxStreamBuffer->xTail = xOriginalTail; - xNextMessageLength = 0; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* A stream of bytes is being received (as opposed to a discrete - message), so read as many bytes as possible. */ - xNextMessageLength = xBufferLengthBytes; - } - - /* Read the actual data. */ - xReceivedLength = prvReadBytesFromBuffer( pxStreamBuffer, ( uint8_t * ) pvRxData, xNextMessageLength, xBytesAvailable ); /*lint !e9079 Data storage area is implemented as uint8_t array for ease of sizing, indexing and alignment. */ - - return xReceivedLength; -} -/*-----------------------------------------------------------*/ - -BaseType_t xStreamBufferIsEmpty( StreamBufferHandle_t xStreamBuffer ) -{ -const StreamBuffer_t * const pxStreamBuffer = ( StreamBuffer_t * ) xStreamBuffer; /*lint !e9087 !e9079 Safe cast as StreamBufferHandle_t is opaque Streambuffer_t. */ -BaseType_t xReturn; -size_t xTail; - - configASSERT( pxStreamBuffer ); - - /* True if no bytes are available. */ - xTail = pxStreamBuffer->xTail; - if( pxStreamBuffer->xHead == xTail ) - { - xReturn = pdTRUE; - } - else - { - xReturn = pdFALSE; - } - - return xReturn; -} -/*-----------------------------------------------------------*/ - -BaseType_t xStreamBufferIsFull( StreamBufferHandle_t xStreamBuffer ) -{ -BaseType_t xReturn; -size_t xBytesToStoreMessageLength; -const StreamBuffer_t * const pxStreamBuffer = ( StreamBuffer_t * ) xStreamBuffer; /*lint !e9087 !e9079 Safe cast as StreamBufferHandle_t is opaque Streambuffer_t. */ - - configASSERT( pxStreamBuffer ); - - /* This generic version of the receive function is used by both message - buffers, which store discrete messages, and stream buffers, which store a - continuous stream of bytes. Discrete messages include an additional - sbBYTES_TO_STORE_MESSAGE_LENGTH bytes that hold the length of the message. */ - if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) - { - xBytesToStoreMessageLength = sbBYTES_TO_STORE_MESSAGE_LENGTH; - } - else - { - xBytesToStoreMessageLength = 0; - } - - /* True if the available space equals zero. */ - if( xStreamBufferSpacesAvailable( xStreamBuffer ) <= xBytesToStoreMessageLength ) - { - xReturn = pdTRUE; - } - else - { - xReturn = pdFALSE; - } - - return xReturn; -} -/*-----------------------------------------------------------*/ - -BaseType_t xStreamBufferSendCompletedFromISR( StreamBufferHandle_t xStreamBuffer, BaseType_t *pxHigherPriorityTaskWoken ) -{ -StreamBuffer_t * const pxStreamBuffer = ( StreamBuffer_t * ) xStreamBuffer; /*lint !e9087 !e9079 Safe cast as StreamBufferHandle_t is opaque Streambuffer_t. */ -BaseType_t xReturn; -UBaseType_t uxSavedInterruptStatus; - - configASSERT( pxStreamBuffer ); - - uxSavedInterruptStatus = ( UBaseType_t ) portSET_INTERRUPT_MASK_FROM_ISR(); - { - if( ( pxStreamBuffer )->xTaskWaitingToReceive != NULL ) - { - ( void ) xTaskNotifyFromISR( ( pxStreamBuffer )->xTaskWaitingToReceive, - ( uint32_t ) 0, - eNoAction, - pxHigherPriorityTaskWoken ); - ( pxStreamBuffer )->xTaskWaitingToReceive = NULL; - xReturn = pdTRUE; - } - else - { - xReturn = pdFALSE; - } - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - - return xReturn; -} -/*-----------------------------------------------------------*/ - -BaseType_t xStreamBufferReceiveCompletedFromISR( StreamBufferHandle_t xStreamBuffer, BaseType_t *pxHigherPriorityTaskWoken ) -{ -StreamBuffer_t * const pxStreamBuffer = ( StreamBuffer_t * ) xStreamBuffer; /*lint !e9087 !e9079 Safe cast as StreamBufferHandle_t is opaque Streambuffer_t. */ -BaseType_t xReturn; -UBaseType_t uxSavedInterruptStatus; - - configASSERT( pxStreamBuffer ); - - uxSavedInterruptStatus = ( UBaseType_t ) portSET_INTERRUPT_MASK_FROM_ISR(); - { - if( ( pxStreamBuffer )->xTaskWaitingToSend != NULL ) - { - ( void ) xTaskNotifyFromISR( ( pxStreamBuffer )->xTaskWaitingToSend, - ( uint32_t ) 0, - eNoAction, - pxHigherPriorityTaskWoken ); - ( pxStreamBuffer )->xTaskWaitingToSend = NULL; - xReturn = pdTRUE; - } - else - { - xReturn = pdFALSE; - } - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - - return xReturn; -} -/*-----------------------------------------------------------*/ - -static size_t prvWriteBytesToBuffer( StreamBuffer_t * const pxStreamBuffer, const uint8_t *pucData, size_t xCount ) -{ -size_t xNextHead, xFirstLength; - - configASSERT( xCount > ( size_t ) 0 ); - - xNextHead = pxStreamBuffer->xHead; - - /* Calculate the number of bytes that can be added in the first write - - which may be less than the total number of bytes that need to be added if - the buffer will wrap back to the beginning. */ - xFirstLength = configMIN( pxStreamBuffer->xLength - xNextHead, xCount ); - - /* Write as many bytes as can be written in the first write. */ - configASSERT( ( xNextHead + xFirstLength ) <= pxStreamBuffer->xLength ); - memcpy( ( void* ) ( &( pxStreamBuffer->pucBuffer[ xNextHead ] ) ), ( const void * ) pucData, xFirstLength ); /*lint !e9087 memcpy() requires void *. */ - - /* If the number of bytes written was less than the number that could be - written in the first write... */ - if( xCount > xFirstLength ) - { - /* ...then write the remaining bytes to the start of the buffer. */ - configASSERT( ( xCount - xFirstLength ) <= pxStreamBuffer->xLength ); - memcpy( ( void * ) pxStreamBuffer->pucBuffer, ( const void * ) &( pucData[ xFirstLength ] ), xCount - xFirstLength ); /*lint !e9087 memcpy() requires void *. */ - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - xNextHead += xCount; - if( xNextHead >= pxStreamBuffer->xLength ) - { - xNextHead -= pxStreamBuffer->xLength; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - pxStreamBuffer->xHead = xNextHead; - - return xCount; -} -/*-----------------------------------------------------------*/ - -static size_t prvReadBytesFromBuffer( StreamBuffer_t *pxStreamBuffer, uint8_t *pucData, size_t xMaxCount, size_t xBytesAvailable ) -{ -size_t xCount, xFirstLength, xNextTail; - - /* Use the minimum of the wanted bytes and the available bytes. */ - xCount = configMIN( xBytesAvailable, xMaxCount ); - - if( xCount > ( size_t ) 0 ) - { - xNextTail = pxStreamBuffer->xTail; - - /* Calculate the number of bytes that can be read - which may be - less than the number wanted if the data wraps around to the start of - the buffer. */ - xFirstLength = configMIN( pxStreamBuffer->xLength - xNextTail, xCount ); - - /* Obtain the number of bytes it is possible to obtain in the first - read. Asserts check bounds of read and write. */ - configASSERT( xFirstLength <= xMaxCount ); - configASSERT( ( xNextTail + xFirstLength ) <= pxStreamBuffer->xLength ); - memcpy( ( void * ) pucData, ( const void * ) &( pxStreamBuffer->pucBuffer[ xNextTail ] ), xFirstLength ); /*lint !e9087 memcpy() requires void *. */ - - /* If the total number of wanted bytes is greater than the number - that could be read in the first read... */ - if( xCount > xFirstLength ) - { - /*...then read the remaining bytes from the start of the buffer. */ - configASSERT( xCount <= xMaxCount ); - memcpy( ( void * ) &( pucData[ xFirstLength ] ), ( void * ) ( pxStreamBuffer->pucBuffer ), xCount - xFirstLength ); /*lint !e9087 memcpy() requires void *. */ - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - /* Move the tail pointer to effectively remove the data read from - the buffer. */ - xNextTail += xCount; - - if( xNextTail >= pxStreamBuffer->xLength ) - { - xNextTail -= pxStreamBuffer->xLength; - } - - pxStreamBuffer->xTail = xNextTail; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - return xCount; -} -/*-----------------------------------------------------------*/ - -static size_t prvBytesInBuffer( const StreamBuffer_t * const pxStreamBuffer ) -{ -/* Returns the distance between xTail and xHead. */ -size_t xCount; - - xCount = pxStreamBuffer->xLength + pxStreamBuffer->xHead; - xCount -= pxStreamBuffer->xTail; - if ( xCount >= pxStreamBuffer->xLength ) - { - xCount -= pxStreamBuffer->xLength; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - return xCount; -} -/*-----------------------------------------------------------*/ - -static void prvInitialiseNewStreamBuffer( StreamBuffer_t * const pxStreamBuffer, - uint8_t * const pucBuffer, - size_t xBufferSizeBytes, - size_t xTriggerLevelBytes, - BaseType_t xIsMessageBuffer ) -{ - /* Assert here is deliberately writing to the entire buffer to ensure it can - be written to without generating exceptions, and is setting the buffer to a - known value to assist in development/debugging. */ - #if( configASSERT_DEFINED == 1 ) - { - /* The value written just has to be identifiable when looking at the - memory. Don't use 0xA5 as that is the stack fill value and could - result in confusion as to what is actually being observed. */ - const BaseType_t xWriteValue = 0x55; - configASSERT( memset( pucBuffer, ( int ) xWriteValue, xBufferSizeBytes ) == pucBuffer ); - } - #endif - - memset( ( void * ) pxStreamBuffer, 0x00, sizeof( StreamBuffer_t ) ); /*lint !e9087 memset() requires void *. */ - pxStreamBuffer->pucBuffer = pucBuffer; - pxStreamBuffer->xLength = xBufferSizeBytes; - pxStreamBuffer->xTriggerLevelBytes = xTriggerLevelBytes; - - if( xIsMessageBuffer != pdFALSE ) - { - pxStreamBuffer->ucFlags |= sbFLAGS_IS_MESSAGE_BUFFER; - } -} - -#if ( configUSE_TRACE_FACILITY == 1 ) - - UBaseType_t uxStreamBufferGetStreamBufferNumber( StreamBufferHandle_t xStreamBuffer ) - { - return ( ( StreamBuffer_t * ) xStreamBuffer )->uxStreamBufferNumber; - } - -#endif /* configUSE_TRACE_FACILITY */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_TRACE_FACILITY == 1 ) - - void vStreamBufferSetStreamBufferNumber( StreamBufferHandle_t xStreamBuffer, UBaseType_t uxStreamBufferNumber ) - { - ( ( StreamBuffer_t * ) xStreamBuffer )->uxStreamBufferNumber = uxStreamBufferNumber; - } - -#endif /* configUSE_TRACE_FACILITY */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_TRACE_FACILITY == 1 ) - - uint8_t ucStreamBufferGetStreamBufferType( StreamBufferHandle_t xStreamBuffer ) - { - return ( ( StreamBuffer_t * )xStreamBuffer )->ucFlags | sbFLAGS_IS_MESSAGE_BUFFER; - } - -#endif /* configUSE_TRACE_FACILITY */ -/*-----------------------------------------------------------*/ diff --git a/lib/FreeRTOS/Source/tasks.c b/lib/FreeRTOS/Source/tasks.c deleted file mode 100644 index 20c39626..00000000 --- a/lib/FreeRTOS/Source/tasks.c +++ /dev/null @@ -1,5045 +0,0 @@ -/* - * FreeRTOS Kernel V10.0.1 - * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * 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. - * - * http://www.FreeRTOS.org - * http://aws.amazon.com/freertos - * - * 1 tab == 4 spaces! - */ - -/* Standard includes. */ -#include -#include - -/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining -all the API functions to use the MPU wrappers. That should only be done when -task.h is included from an application file. */ -#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE - -/* FreeRTOS includes. */ -#include "FreeRTOS.h" -#include "task.h" -#include "timers.h" -#include "stack_macros.h" - -/* Lint e961 and e750 are suppressed as a MISRA exception justified because the -MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be defined for the -header files above, but not in this file, in order to generate the correct -privileged Vs unprivileged linkage and placement. */ -#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /*lint !e961 !e750. */ - -/* Set configUSE_STATS_FORMATTING_FUNCTIONS to 2 to include the stats formatting -functions but without including stdio.h here. */ -#if ( configUSE_STATS_FORMATTING_FUNCTIONS == 1 ) - /* At the bottom of this file are two optional functions that can be used - to generate human readable text from the raw data generated by the - uxTaskGetSystemState() function. Note the formatting functions are provided - for convenience only, and are NOT considered part of the kernel. */ - #include -#endif /* configUSE_STATS_FORMATTING_FUNCTIONS == 1 ) */ - -#if( configUSE_PREEMPTION == 0 ) - /* If the cooperative scheduler is being used then a yield should not be - performed just because a higher priority task has been woken. */ - #define taskYIELD_IF_USING_PREEMPTION() -#else - #define taskYIELD_IF_USING_PREEMPTION() portYIELD_WITHIN_API() -#endif - -/* Values that can be assigned to the ucNotifyState member of the TCB. */ -#define taskNOT_WAITING_NOTIFICATION ( ( uint8_t ) 0 ) -#define taskWAITING_NOTIFICATION ( ( uint8_t ) 1 ) -#define taskNOTIFICATION_RECEIVED ( ( uint8_t ) 2 ) - -/* - * The value used to fill the stack of a task when the task is created. This - * is used purely for checking the high water mark for tasks. - */ -#define tskSTACK_FILL_BYTE ( 0xa5U ) - -/* Sometimes the FreeRTOSConfig.h settings only allow a task to be created using -dynamically allocated RAM, in which case when any task is deleted it is known -that both the task's stack and TCB need to be freed. Sometimes the -FreeRTOSConfig.h settings only allow a task to be created using statically -allocated RAM, in which case when any task is deleted it is known that neither -the task's stack or TCB should be freed. Sometimes the FreeRTOSConfig.h -settings allow a task to be created using either statically or dynamically -allocated RAM, in which case a member of the TCB is used to record whether the -stack and/or TCB were allocated statically or dynamically, so when a task is -deleted the RAM that was allocated dynamically is freed again and no attempt is -made to free the RAM that was allocated statically. -tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE is only true if it is possible for a -task to be created using either statically or dynamically allocated RAM. Note -that if portUSING_MPU_WRAPPERS is 1 then a protected task can be created with -a statically allocated stack and a dynamically allocated TCB. -!!!NOTE!!! If the definition of tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE is -changed then the definition of StaticTask_t must also be updated. */ -#define tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE ( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) -#define tskDYNAMICALLY_ALLOCATED_STACK_AND_TCB ( ( uint8_t ) 0 ) -#define tskSTATICALLY_ALLOCATED_STACK_ONLY ( ( uint8_t ) 1 ) -#define tskSTATICALLY_ALLOCATED_STACK_AND_TCB ( ( uint8_t ) 2 ) - -/* If any of the following are set then task stacks are filled with a known -value so the high water mark can be determined. If none of the following are -set then don't fill the stack so there is no unnecessary dependency on memset. */ -#if( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) || ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) ) - #define tskSET_NEW_STACKS_TO_KNOWN_VALUE 1 -#else - #define tskSET_NEW_STACKS_TO_KNOWN_VALUE 0 -#endif - -/* - * Macros used by vListTask to indicate which state a task is in. - */ -#define tskRUNNING_CHAR ( 'X' ) -#define tskBLOCKED_CHAR ( 'B' ) -#define tskREADY_CHAR ( 'R' ) -#define tskDELETED_CHAR ( 'D' ) -#define tskSUSPENDED_CHAR ( 'S' ) - -/* - * Some kernel aware debuggers require the data the debugger needs access to be - * global, rather than file scope. - */ -#ifdef portREMOVE_STATIC_QUALIFIER - #define static -#endif - -/* The name allocated to the Idle task. This can be overridden by defining -configIDLE_TASK_NAME in FreeRTOSConfig.h. */ -#ifndef configIDLE_TASK_NAME - #define configIDLE_TASK_NAME "IDLE" -#endif - -#if ( configUSE_PORT_OPTIMISED_TASK_SELECTION == 0 ) - - /* If configUSE_PORT_OPTIMISED_TASK_SELECTION is 0 then task selection is - performed in a generic way that is not optimised to any particular - microcontroller architecture. */ - - /* uxTopReadyPriority holds the priority of the highest priority ready - state task. */ - #define taskRECORD_READY_PRIORITY( uxPriority ) \ - { \ - if( ( uxPriority ) > uxTopReadyPriority ) \ - { \ - uxTopReadyPriority = ( uxPriority ); \ - } \ - } /* taskRECORD_READY_PRIORITY */ - - /*-----------------------------------------------------------*/ - - #define taskSELECT_HIGHEST_PRIORITY_TASK() \ - { \ - UBaseType_t uxTopPriority = uxTopReadyPriority; \ - \ - /* Find the highest priority queue that contains ready tasks. */ \ - while( listLIST_IS_EMPTY( &( pxReadyTasksLists[ uxTopPriority ] ) ) ) \ - { \ - configASSERT( uxTopPriority ); \ - --uxTopPriority; \ - } \ - \ - /* listGET_OWNER_OF_NEXT_ENTRY indexes through the list, so the tasks of \ - the same priority get an equal share of the processor time. */ \ - listGET_OWNER_OF_NEXT_ENTRY( pxCurrentTCB, &( pxReadyTasksLists[ uxTopPriority ] ) ); \ - uxTopReadyPriority = uxTopPriority; \ - } /* taskSELECT_HIGHEST_PRIORITY_TASK */ - - /*-----------------------------------------------------------*/ - - /* Define away taskRESET_READY_PRIORITY() and portRESET_READY_PRIORITY() as - they are only required when a port optimised method of task selection is - being used. */ - #define taskRESET_READY_PRIORITY( uxPriority ) - #define portRESET_READY_PRIORITY( uxPriority, uxTopReadyPriority ) - -#else /* configUSE_PORT_OPTIMISED_TASK_SELECTION */ - - /* If configUSE_PORT_OPTIMISED_TASK_SELECTION is 1 then task selection is - performed in a way that is tailored to the particular microcontroller - architecture being used. */ - - /* A port optimised version is provided. Call the port defined macros. */ - #define taskRECORD_READY_PRIORITY( uxPriority ) portRECORD_READY_PRIORITY( uxPriority, uxTopReadyPriority ) - - /*-----------------------------------------------------------*/ - - #define taskSELECT_HIGHEST_PRIORITY_TASK() \ - { \ - UBaseType_t uxTopPriority; \ - \ - /* Find the highest priority list that contains ready tasks. */ \ - portGET_HIGHEST_PRIORITY( uxTopPriority, uxTopReadyPriority ); \ - configASSERT( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ uxTopPriority ] ) ) > 0 ); \ - listGET_OWNER_OF_NEXT_ENTRY( pxCurrentTCB, &( pxReadyTasksLists[ uxTopPriority ] ) ); \ - } /* taskSELECT_HIGHEST_PRIORITY_TASK() */ - - /*-----------------------------------------------------------*/ - - /* A port optimised version is provided, call it only if the TCB being reset - is being referenced from a ready list. If it is referenced from a delayed - or suspended list then it won't be in a ready list. */ - #define taskRESET_READY_PRIORITY( uxPriority ) \ - { \ - if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ ( uxPriority ) ] ) ) == ( UBaseType_t ) 0 ) \ - { \ - portRESET_READY_PRIORITY( ( uxPriority ), ( uxTopReadyPriority ) ); \ - } \ - } - -#endif /* configUSE_PORT_OPTIMISED_TASK_SELECTION */ - -/*-----------------------------------------------------------*/ - -/* pxDelayedTaskList and pxOverflowDelayedTaskList are switched when the tick -count overflows. */ -#define taskSWITCH_DELAYED_LISTS() \ -{ \ - List_t *pxTemp; \ - \ - /* The delayed tasks list should be empty when the lists are switched. */ \ - configASSERT( ( listLIST_IS_EMPTY( pxDelayedTaskList ) ) ); \ - \ - pxTemp = pxDelayedTaskList; \ - pxDelayedTaskList = pxOverflowDelayedTaskList; \ - pxOverflowDelayedTaskList = pxTemp; \ - xNumOfOverflows++; \ - prvResetNextTaskUnblockTime(); \ -} - -/*-----------------------------------------------------------*/ - -/* - * Place the task represented by pxTCB into the appropriate ready list for - * the task. It is inserted at the end of the list. - */ -#define prvAddTaskToReadyList( pxTCB ) \ - traceMOVED_TASK_TO_READY_STATE( pxTCB ); \ - taskRECORD_READY_PRIORITY( ( pxTCB )->uxPriority ); \ - vListInsertEnd( &( pxReadyTasksLists[ ( pxTCB )->uxPriority ] ), &( ( pxTCB )->xStateListItem ) ); \ - tracePOST_MOVED_TASK_TO_READY_STATE( pxTCB ) -/*-----------------------------------------------------------*/ - -/* - * Several functions take an TaskHandle_t parameter that can optionally be NULL, - * where NULL is used to indicate that the handle of the currently executing - * task should be used in place of the parameter. This macro simply checks to - * see if the parameter is NULL and returns a pointer to the appropriate TCB. - */ -#define prvGetTCBFromHandle( pxHandle ) ( ( ( pxHandle ) == NULL ) ? ( TCB_t * ) pxCurrentTCB : ( TCB_t * ) ( pxHandle ) ) - -/* The item value of the event list item is normally used to hold the priority -of the task to which it belongs (coded to allow it to be held in reverse -priority order). However, it is occasionally borrowed for other purposes. It -is important its value is not updated due to a task priority change while it is -being used for another purpose. The following bit definition is used to inform -the scheduler that the value should not be changed - in which case it is the -responsibility of whichever module is using the value to ensure it gets set back -to its original value when it is released. */ -#if( configUSE_16_BIT_TICKS == 1 ) - #define taskEVENT_LIST_ITEM_VALUE_IN_USE 0x8000U -#else - #define taskEVENT_LIST_ITEM_VALUE_IN_USE 0x80000000UL -#endif - -/* - * Task control block. A task control block (TCB) is allocated for each task, - * and stores task state information, including a pointer to the task's context - * (the task's run time environment, including register values) - */ -typedef struct tskTaskControlBlock -{ - volatile StackType_t *pxTopOfStack; /*< Points to the location of the last item placed on the tasks stack. THIS MUST BE THE FIRST MEMBER OF THE TCB STRUCT. */ - - #if ( portUSING_MPU_WRAPPERS == 1 ) - xMPU_SETTINGS xMPUSettings; /*< The MPU settings are defined as part of the port layer. THIS MUST BE THE SECOND MEMBER OF THE TCB STRUCT. */ - #endif - - ListItem_t xStateListItem; /*< The list that the state list item of a task is reference from denotes the state of that task (Ready, Blocked, Suspended ). */ - ListItem_t xEventListItem; /*< Used to reference a task from an event list. */ - UBaseType_t uxPriority; /*< The priority of the task. 0 is the lowest priority. */ - StackType_t *pxStack; /*< Points to the start of the stack. */ - char pcTaskName[ configMAX_TASK_NAME_LEN ];/*< Descriptive name given to the task when created. Facilitates debugging only. */ /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - - #if ( ( portSTACK_GROWTH > 0 ) || ( configRECORD_STACK_HIGH_ADDRESS == 1 ) ) - StackType_t *pxEndOfStack; /*< Points to the highest valid address for the stack. */ - #endif - - #if ( portCRITICAL_NESTING_IN_TCB == 1 ) - UBaseType_t uxCriticalNesting; /*< Holds the critical section nesting depth for ports that do not maintain their own count in the port layer. */ - #endif - - #if ( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxTCBNumber; /*< Stores a number that increments each time a TCB is created. It allows debuggers to determine when a task has been deleted and then recreated. */ - UBaseType_t uxTaskNumber; /*< Stores a number specifically for use by third party trace code. */ - #endif - - #if ( configUSE_MUTEXES == 1 ) - UBaseType_t uxBasePriority; /*< The priority last assigned to the task - used by the priority inheritance mechanism. */ - UBaseType_t uxMutexesHeld; - #endif - - #if ( configUSE_APPLICATION_TASK_TAG == 1 ) - TaskHookFunction_t pxTaskTag; - #endif - - #if( configNUM_THREAD_LOCAL_STORAGE_POINTERS > 0 ) - void *pvThreadLocalStoragePointers[ configNUM_THREAD_LOCAL_STORAGE_POINTERS ]; - #endif - - #if( configGENERATE_RUN_TIME_STATS == 1 ) - uint32_t ulRunTimeCounter; /*< Stores the amount of time the task has spent in the Running state. */ - #endif - - #if ( configUSE_NEWLIB_REENTRANT == 1 ) - /* Allocate a Newlib reent structure that is specific to this task. - Note Newlib support has been included by popular demand, but is not - used by the FreeRTOS maintainers themselves. FreeRTOS is not - responsible for resulting newlib operation. User must be familiar with - newlib and must provide system-wide implementations of the necessary - stubs. Be warned that (at the time of writing) the current newlib design - implements a system-wide malloc() that must be provided with locks. */ - struct _reent xNewLib_reent; - #endif - - #if( configUSE_TASK_NOTIFICATIONS == 1 ) - volatile uint32_t ulNotifiedValue; - volatile uint8_t ucNotifyState; - #endif - - /* See the comments above the definition of - tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE. */ - #if( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e731 Macro has been consolidated for readability reasons. */ - uint8_t ucStaticallyAllocated; /*< Set to pdTRUE if the task is a statically allocated to ensure no attempt is made to free the memory. */ - #endif - - #if( INCLUDE_xTaskAbortDelay == 1 ) - uint8_t ucDelayAborted; - #endif - -} tskTCB; - -/* The old tskTCB name is maintained above then typedefed to the new TCB_t name -below to enable the use of older kernel aware debuggers. */ -typedef tskTCB TCB_t; - -/*lint -save -e956 A manual analysis and inspection has been used to determine -which static variables must be declared volatile. */ - -PRIVILEGED_DATA TCB_t * volatile pxCurrentTCB = NULL; - -/* Lists for ready and blocked tasks. --------------------*/ -PRIVILEGED_DATA static List_t pxReadyTasksLists[ configMAX_PRIORITIES ];/*< Prioritised ready tasks. */ -PRIVILEGED_DATA static List_t xDelayedTaskList1; /*< Delayed tasks. */ -PRIVILEGED_DATA static List_t xDelayedTaskList2; /*< Delayed tasks (two lists are used - one for delays that have overflowed the current tick count. */ -PRIVILEGED_DATA static List_t * volatile pxDelayedTaskList; /*< Points to the delayed task list currently being used. */ -PRIVILEGED_DATA static List_t * volatile pxOverflowDelayedTaskList; /*< Points to the delayed task list currently being used to hold tasks that have overflowed the current tick count. */ -PRIVILEGED_DATA static List_t xPendingReadyList; /*< Tasks that have been readied while the scheduler was suspended. They will be moved to the ready list when the scheduler is resumed. */ - -#if( INCLUDE_vTaskDelete == 1 ) - - PRIVILEGED_DATA static List_t xTasksWaitingTermination; /*< Tasks that have been deleted - but their memory not yet freed. */ - PRIVILEGED_DATA static volatile UBaseType_t uxDeletedTasksWaitingCleanUp = ( UBaseType_t ) 0U; - -#endif - -#if ( INCLUDE_vTaskSuspend == 1 ) - - PRIVILEGED_DATA static List_t xSuspendedTaskList; /*< Tasks that are currently suspended. */ - -#endif - -/* Other file private variables. --------------------------------*/ -PRIVILEGED_DATA static volatile UBaseType_t uxCurrentNumberOfTasks = ( UBaseType_t ) 0U; -PRIVILEGED_DATA static volatile TickType_t xTickCount = ( TickType_t ) configINITIAL_TICK_COUNT; -PRIVILEGED_DATA static volatile UBaseType_t uxTopReadyPriority = tskIDLE_PRIORITY; -PRIVILEGED_DATA static volatile BaseType_t xSchedulerRunning = pdFALSE; -PRIVILEGED_DATA static volatile UBaseType_t uxPendedTicks = ( UBaseType_t ) 0U; -PRIVILEGED_DATA static volatile BaseType_t xYieldPending = pdFALSE; -PRIVILEGED_DATA static volatile BaseType_t xNumOfOverflows = ( BaseType_t ) 0; -PRIVILEGED_DATA static UBaseType_t uxTaskNumber = ( UBaseType_t ) 0U; -PRIVILEGED_DATA static volatile TickType_t xNextTaskUnblockTime = ( TickType_t ) 0U; /* Initialised to portMAX_DELAY before the scheduler starts. */ -PRIVILEGED_DATA static TaskHandle_t xIdleTaskHandle = NULL; /*< Holds the handle of the idle task. The idle task is created automatically when the scheduler is started. */ - -/* Context switches are held pending while the scheduler is suspended. Also, -interrupts must not manipulate the xStateListItem of a TCB, or any of the -lists the xStateListItem can be referenced from, if the scheduler is suspended. -If an interrupt needs to unblock a task while the scheduler is suspended then it -moves the task's event list item into the xPendingReadyList, ready for the -kernel to move the task from the pending ready list into the real ready list -when the scheduler is unsuspended. The pending ready list itself can only be -accessed from a critical section. */ -PRIVILEGED_DATA static volatile UBaseType_t uxSchedulerSuspended = ( UBaseType_t ) pdFALSE; - -#if ( configGENERATE_RUN_TIME_STATS == 1 ) - - PRIVILEGED_DATA static uint32_t ulTaskSwitchedInTime = 0UL; /*< Holds the value of a timer/counter the last time a task was switched in. */ - PRIVILEGED_DATA static uint32_t ulTotalRunTime = 0UL; /*< Holds the total amount of execution time as defined by the run time counter clock. */ - -#endif - -/*lint -restore */ - -/*-----------------------------------------------------------*/ - -/* Callback function prototypes. --------------------------*/ -#if( configCHECK_FOR_STACK_OVERFLOW > 0 ) - - extern void vApplicationStackOverflowHook( TaskHandle_t xTask, char *pcTaskName ); - -#endif - -#if( configUSE_TICK_HOOK > 0 ) - - extern void vApplicationTickHook( void ); - -#endif - -#if( configSUPPORT_STATIC_ALLOCATION == 1 ) - - extern void vApplicationGetIdleTaskMemory( StaticTask_t **ppxIdleTaskTCBBuffer, StackType_t **ppxIdleTaskStackBuffer, uint32_t *pulIdleTaskStackSize ); - -#endif - -/* File private functions. --------------------------------*/ - -/** - * Utility task that simply returns pdTRUE if the task referenced by xTask is - * currently in the Suspended state, or pdFALSE if the task referenced by xTask - * is in any other state. - */ -#if ( INCLUDE_vTaskSuspend == 1 ) - - static BaseType_t prvTaskIsTaskSuspended( const TaskHandle_t xTask ) PRIVILEGED_FUNCTION; - -#endif /* INCLUDE_vTaskSuspend */ - -/* - * Utility to ready all the lists used by the scheduler. This is called - * automatically upon the creation of the first task. - */ -static void prvInitialiseTaskLists( void ) PRIVILEGED_FUNCTION; - -/* - * The idle task, which as all tasks is implemented as a never ending loop. - * The idle task is automatically created and added to the ready lists upon - * creation of the first user task. - * - * The portTASK_FUNCTION_PROTO() macro is used to allow port/compiler specific - * language extensions. The equivalent prototype for this function is: - * - * void prvIdleTask( void *pvParameters ); - * - */ -static portTASK_FUNCTION_PROTO( prvIdleTask, pvParameters ); - -/* - * Utility to free all memory allocated by the scheduler to hold a TCB, - * including the stack pointed to by the TCB. - * - * This does not free memory allocated by the task itself (i.e. memory - * allocated by calls to pvPortMalloc from within the tasks application code). - */ -#if ( INCLUDE_vTaskDelete == 1 ) - - static void prvDeleteTCB( TCB_t *pxTCB ) PRIVILEGED_FUNCTION; - -#endif - -/* - * Used only by the idle task. This checks to see if anything has been placed - * in the list of tasks waiting to be deleted. If so the task is cleaned up - * and its TCB deleted. - */ -static void prvCheckTasksWaitingTermination( void ) PRIVILEGED_FUNCTION; - -/* - * The currently executing task is entering the Blocked state. Add the task to - * either the current or the overflow delayed task list. - */ -static void prvAddCurrentTaskToDelayedList( TickType_t xTicksToWait, const BaseType_t xCanBlockIndefinitely ) PRIVILEGED_FUNCTION; - -/* - * Fills an TaskStatus_t structure with information on each task that is - * referenced from the pxList list (which may be a ready list, a delayed list, - * a suspended list, etc.). - * - * THIS FUNCTION IS INTENDED FOR DEBUGGING ONLY, AND SHOULD NOT BE CALLED FROM - * NORMAL APPLICATION CODE. - */ -#if ( configUSE_TRACE_FACILITY == 1 ) - - static UBaseType_t prvListTasksWithinSingleList( TaskStatus_t *pxTaskStatusArray, List_t *pxList, eTaskState eState ) PRIVILEGED_FUNCTION; - -#endif - -/* - * Searches pxList for a task with name pcNameToQuery - returning a handle to - * the task if it is found, or NULL if the task is not found. - */ -#if ( INCLUDE_xTaskGetHandle == 1 ) - - static TCB_t *prvSearchForNameWithinSingleList( List_t *pxList, const char pcNameToQuery[] ) PRIVILEGED_FUNCTION; - -#endif - -/* - * When a task is created, the stack of the task is filled with a known value. - * This function determines the 'high water mark' of the task stack by - * determining how much of the stack remains at the original preset value. - */ -#if ( ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) ) - - static uint16_t prvTaskCheckFreeStackSpace( const uint8_t * pucStackByte ) PRIVILEGED_FUNCTION; - -#endif - -/* - * Return the amount of time, in ticks, that will pass before the kernel will - * next move a task from the Blocked state to the Running state. - * - * This conditional compilation should use inequality to 0, not equality to 1. - * This is to ensure portSUPPRESS_TICKS_AND_SLEEP() can be called when user - * defined low power mode implementations require configUSE_TICKLESS_IDLE to be - * set to a value other than 1. - */ -#if ( configUSE_TICKLESS_IDLE != 0 ) - - static TickType_t prvGetExpectedIdleTime( void ) PRIVILEGED_FUNCTION; - -#endif - -/* - * Set xNextTaskUnblockTime to the time at which the next Blocked state task - * will exit the Blocked state. - */ -static void prvResetNextTaskUnblockTime( void ); - -#if ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) ) - - /* - * Helper function used to pad task names with spaces when printing out - * human readable tables of task information. - */ - static char *prvWriteNameToBuffer( char *pcBuffer, const char *pcTaskName ) PRIVILEGED_FUNCTION; - -#endif - -/* - * Called after a Task_t structure has been allocated either statically or - * dynamically to fill in the structure's members. - */ -static void prvInitialiseNewTask( TaskFunction_t pxTaskCode, - const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - const uint32_t ulStackDepth, - void * const pvParameters, - UBaseType_t uxPriority, - TaskHandle_t * const pxCreatedTask, - TCB_t *pxNewTCB, - const MemoryRegion_t * const xRegions ) PRIVILEGED_FUNCTION; - -/* - * Called after a new task has been created and initialised to place the task - * under the control of the scheduler. - */ -static void prvAddNewTaskToReadyList( TCB_t *pxNewTCB ) PRIVILEGED_FUNCTION; - -/* - * freertos_tasks_c_additions_init() should only be called if the user definable - * macro FREERTOS_TASKS_C_ADDITIONS_INIT() is defined, as that is the only macro - * called by the function. - */ -#ifdef FREERTOS_TASKS_C_ADDITIONS_INIT - - static void freertos_tasks_c_additions_init( void ) PRIVILEGED_FUNCTION; - -#endif - -/*-----------------------------------------------------------*/ - -#if( configSUPPORT_STATIC_ALLOCATION == 1 ) - - TaskHandle_t xTaskCreateStatic( TaskFunction_t pxTaskCode, - const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - const uint32_t ulStackDepth, - void * const pvParameters, - UBaseType_t uxPriority, - StackType_t * const puxStackBuffer, - StaticTask_t * const pxTaskBuffer ) - { - TCB_t *pxNewTCB; - TaskHandle_t xReturn; - - configASSERT( puxStackBuffer != NULL ); - configASSERT( pxTaskBuffer != NULL ); - - #if( configASSERT_DEFINED == 1 ) - { - /* Sanity check that the size of the structure used to declare a - variable of type StaticTask_t equals the size of the real task - structure. */ - volatile size_t xSize = sizeof( StaticTask_t ); - configASSERT( xSize == sizeof( TCB_t ) ); - } - #endif /* configASSERT_DEFINED */ - - - if( ( pxTaskBuffer != NULL ) && ( puxStackBuffer != NULL ) ) - { - /* The memory used for the task's TCB and stack are passed into this - function - use them. */ - pxNewTCB = ( TCB_t * ) pxTaskBuffer; /*lint !e740 Unusual cast is ok as the structures are designed to have the same alignment, and the size is checked by an assert. */ - pxNewTCB->pxStack = ( StackType_t * ) puxStackBuffer; - - #if( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e731 Macro has been consolidated for readability reasons. */ - { - /* Tasks can be created statically or dynamically, so note this - task was created statically in case the task is later deleted. */ - pxNewTCB->ucStaticallyAllocated = tskSTATICALLY_ALLOCATED_STACK_AND_TCB; - } - #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ - - prvInitialiseNewTask( pxTaskCode, pcName, ulStackDepth, pvParameters, uxPriority, &xReturn, pxNewTCB, NULL ); - prvAddNewTaskToReadyList( pxNewTCB ); - } - else - { - xReturn = NULL; - } - - return xReturn; - } - -#endif /* SUPPORT_STATIC_ALLOCATION */ -/*-----------------------------------------------------------*/ - -#if( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) - - BaseType_t xTaskCreateRestrictedStatic( const TaskParameters_t * const pxTaskDefinition, TaskHandle_t *pxCreatedTask ) - { - TCB_t *pxNewTCB; - BaseType_t xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY; - - configASSERT( pxTaskDefinition->puxStackBuffer != NULL ); - configASSERT( pxTaskDefinition->pxTaskBuffer != NULL ); - - if( ( pxTaskDefinition->puxStackBuffer != NULL ) && ( pxTaskDefinition->pxTaskBuffer != NULL ) ) - { - /* Allocate space for the TCB. Where the memory comes from depends - on the implementation of the port malloc function and whether or - not static allocation is being used. */ - pxNewTCB = ( TCB_t * ) pxTaskDefinition->pxTaskBuffer; - - /* Store the stack location in the TCB. */ - pxNewTCB->pxStack = pxTaskDefinition->puxStackBuffer; - - #if( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) - { - /* Tasks can be created statically or dynamically, so note this - task was created statically in case the task is later deleted. */ - pxNewTCB->ucStaticallyAllocated = tskSTATICALLY_ALLOCATED_STACK_AND_TCB; - } - #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ - - prvInitialiseNewTask( pxTaskDefinition->pvTaskCode, - pxTaskDefinition->pcName, - ( uint32_t ) pxTaskDefinition->usStackDepth, - pxTaskDefinition->pvParameters, - pxTaskDefinition->uxPriority, - pxCreatedTask, pxNewTCB, - pxTaskDefinition->xRegions ); - - prvAddNewTaskToReadyList( pxNewTCB ); - xReturn = pdPASS; - } - - return xReturn; - } - -#endif /* ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) */ -/*-----------------------------------------------------------*/ - -#if( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) - - BaseType_t xTaskCreateRestricted( const TaskParameters_t * const pxTaskDefinition, TaskHandle_t *pxCreatedTask ) - { - TCB_t *pxNewTCB; - BaseType_t xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY; - - configASSERT( pxTaskDefinition->puxStackBuffer ); - - if( pxTaskDefinition->puxStackBuffer != NULL ) - { - /* Allocate space for the TCB. Where the memory comes from depends - on the implementation of the port malloc function and whether or - not static allocation is being used. */ - pxNewTCB = ( TCB_t * ) pvPortMalloc( sizeof( TCB_t ) ); - - if( pxNewTCB != NULL ) - { - /* Store the stack location in the TCB. */ - pxNewTCB->pxStack = pxTaskDefinition->puxStackBuffer; - - #if( configSUPPORT_STATIC_ALLOCATION == 1 ) - { - /* Tasks can be created statically or dynamically, so note - this task had a statically allocated stack in case it is - later deleted. The TCB was allocated dynamically. */ - pxNewTCB->ucStaticallyAllocated = tskSTATICALLY_ALLOCATED_STACK_ONLY; - } - #endif - - prvInitialiseNewTask( pxTaskDefinition->pvTaskCode, - pxTaskDefinition->pcName, - ( uint32_t ) pxTaskDefinition->usStackDepth, - pxTaskDefinition->pvParameters, - pxTaskDefinition->uxPriority, - pxCreatedTask, pxNewTCB, - pxTaskDefinition->xRegions ); - - prvAddNewTaskToReadyList( pxNewTCB ); - xReturn = pdPASS; - } - } - - return xReturn; - } - -#endif /* portUSING_MPU_WRAPPERS */ -/*-----------------------------------------------------------*/ - -#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - - BaseType_t xTaskCreate( TaskFunction_t pxTaskCode, - const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - const configSTACK_DEPTH_TYPE usStackDepth, - void * const pvParameters, - UBaseType_t uxPriority, - TaskHandle_t * const pxCreatedTask ) - { - TCB_t *pxNewTCB; - BaseType_t xReturn; - - /* If the stack grows down then allocate the stack then the TCB so the stack - does not grow into the TCB. Likewise if the stack grows up then allocate - the TCB then the stack. */ - #if( portSTACK_GROWTH > 0 ) - { - /* Allocate space for the TCB. Where the memory comes from depends on - the implementation of the port malloc function and whether or not static - allocation is being used. */ - pxNewTCB = ( TCB_t * ) pvPortMalloc( sizeof( TCB_t ) ); - - if( pxNewTCB != NULL ) - { - /* Allocate space for the stack used by the task being created. - The base of the stack memory stored in the TCB so the task can - be deleted later if required. */ - pxNewTCB->pxStack = ( StackType_t * ) pvPortMalloc( ( ( ( size_t ) usStackDepth ) * sizeof( StackType_t ) ) ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - - if( pxNewTCB->pxStack == NULL ) - { - /* Could not allocate the stack. Delete the allocated TCB. */ - vPortFree( pxNewTCB ); - pxNewTCB = NULL; - } - } - } - #else /* portSTACK_GROWTH */ - { - StackType_t *pxStack; - - /* Allocate space for the stack used by the task being created. */ - pxStack = ( StackType_t * ) pvPortMalloc( ( ( ( size_t ) usStackDepth ) * sizeof( StackType_t ) ) ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - - if( pxStack != NULL ) - { - /* Allocate space for the TCB. */ - pxNewTCB = ( TCB_t * ) pvPortMalloc( sizeof( TCB_t ) ); /*lint !e961 MISRA exception as the casts are only redundant for some paths. */ - - if( pxNewTCB != NULL ) - { - /* Store the stack location in the TCB. */ - pxNewTCB->pxStack = pxStack; - } - else - { - /* The stack cannot be used as the TCB was not created. Free - it again. */ - vPortFree( pxStack ); - } - } - else - { - pxNewTCB = NULL; - } - } - #endif /* portSTACK_GROWTH */ - - if( pxNewTCB != NULL ) - { - #if( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e731 Macro has been consolidated for readability reasons. */ - { - /* Tasks can be created statically or dynamically, so note this - task was created dynamically in case it is later deleted. */ - pxNewTCB->ucStaticallyAllocated = tskDYNAMICALLY_ALLOCATED_STACK_AND_TCB; - } - #endif /* configSUPPORT_STATIC_ALLOCATION */ - - prvInitialiseNewTask( pxTaskCode, pcName, ( uint32_t ) usStackDepth, pvParameters, uxPriority, pxCreatedTask, pxNewTCB, NULL ); - prvAddNewTaskToReadyList( pxNewTCB ); - xReturn = pdPASS; - } - else - { - xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY; - } - - return xReturn; - } - -#endif /* configSUPPORT_DYNAMIC_ALLOCATION */ -/*-----------------------------------------------------------*/ - -static void prvInitialiseNewTask( TaskFunction_t pxTaskCode, - const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - const uint32_t ulStackDepth, - void * const pvParameters, - UBaseType_t uxPriority, - TaskHandle_t * const pxCreatedTask, - TCB_t *pxNewTCB, - const MemoryRegion_t * const xRegions ) -{ -StackType_t *pxTopOfStack; -UBaseType_t x; - - #if( portUSING_MPU_WRAPPERS == 1 ) - /* Should the task be created in privileged mode? */ - BaseType_t xRunPrivileged; - if( ( uxPriority & portPRIVILEGE_BIT ) != 0U ) - { - xRunPrivileged = pdTRUE; - } - else - { - xRunPrivileged = pdFALSE; - } - uxPriority &= ~portPRIVILEGE_BIT; - #endif /* portUSING_MPU_WRAPPERS == 1 */ - - /* Avoid dependency on memset() if it is not required. */ - #if( tskSET_NEW_STACKS_TO_KNOWN_VALUE == 1 ) - { - /* Fill the stack with a known value to assist debugging. */ - ( void ) memset( pxNewTCB->pxStack, ( int ) tskSTACK_FILL_BYTE, ( size_t ) ulStackDepth * sizeof( StackType_t ) ); - } - #endif /* tskSET_NEW_STACKS_TO_KNOWN_VALUE */ - - /* Calculate the top of stack address. This depends on whether the stack - grows from high memory to low (as per the 80x86) or vice versa. - portSTACK_GROWTH is used to make the result positive or negative as required - by the port. */ - #if( portSTACK_GROWTH < 0 ) - { - pxTopOfStack = pxNewTCB->pxStack + ( ulStackDepth - ( uint32_t ) 1 ); - pxTopOfStack = ( StackType_t * ) ( ( ( portPOINTER_SIZE_TYPE ) pxTopOfStack ) & ( ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) ) ); /*lint !e923 MISRA exception. Avoiding casts between pointers and integers is not practical. Size differences accounted for using portPOINTER_SIZE_TYPE type. */ - - /* Check the alignment of the calculated top of stack is correct. */ - configASSERT( ( ( ( portPOINTER_SIZE_TYPE ) pxTopOfStack & ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) == 0UL ) ); - - #if( configRECORD_STACK_HIGH_ADDRESS == 1 ) - { - /* Also record the stack's high address, which may assist - debugging. */ - pxNewTCB->pxEndOfStack = pxTopOfStack; - } - #endif /* configRECORD_STACK_HIGH_ADDRESS */ - } - #else /* portSTACK_GROWTH */ - { - pxTopOfStack = pxNewTCB->pxStack; - - /* Check the alignment of the stack buffer is correct. */ - configASSERT( ( ( ( portPOINTER_SIZE_TYPE ) pxNewTCB->pxStack & ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) == 0UL ) ); - - /* The other extreme of the stack space is required if stack checking is - performed. */ - pxNewTCB->pxEndOfStack = pxNewTCB->pxStack + ( ulStackDepth - ( uint32_t ) 1 ); - } - #endif /* portSTACK_GROWTH */ - - /* Store the task name in the TCB. */ - for( x = ( UBaseType_t ) 0; x < ( UBaseType_t ) configMAX_TASK_NAME_LEN; x++ ) - { - pxNewTCB->pcTaskName[ x ] = pcName[ x ]; - - /* Don't copy all configMAX_TASK_NAME_LEN if the string is shorter than - configMAX_TASK_NAME_LEN characters just in case the memory after the - string is not accessible (extremely unlikely). */ - if( pcName[ x ] == 0x00 ) - { - break; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - - /* Ensure the name string is terminated in the case that the string length - was greater or equal to configMAX_TASK_NAME_LEN. */ - pxNewTCB->pcTaskName[ configMAX_TASK_NAME_LEN - 1 ] = '\0'; - - /* This is used as an array index so must ensure it's not too large. First - remove the privilege bit if one is present. */ - if( uxPriority >= ( UBaseType_t ) configMAX_PRIORITIES ) - { - uxPriority = ( UBaseType_t ) configMAX_PRIORITIES - ( UBaseType_t ) 1U; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - pxNewTCB->uxPriority = uxPriority; - #if ( configUSE_MUTEXES == 1 ) - { - pxNewTCB->uxBasePriority = uxPriority; - pxNewTCB->uxMutexesHeld = 0; - } - #endif /* configUSE_MUTEXES */ - - vListInitialiseItem( &( pxNewTCB->xStateListItem ) ); - vListInitialiseItem( &( pxNewTCB->xEventListItem ) ); - - /* Set the pxNewTCB as a link back from the ListItem_t. This is so we can get - back to the containing TCB from a generic item in a list. */ - listSET_LIST_ITEM_OWNER( &( pxNewTCB->xStateListItem ), pxNewTCB ); - - /* Event lists are always in priority order. */ - listSET_LIST_ITEM_VALUE( &( pxNewTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) uxPriority ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - listSET_LIST_ITEM_OWNER( &( pxNewTCB->xEventListItem ), pxNewTCB ); - - #if ( portCRITICAL_NESTING_IN_TCB == 1 ) - { - pxNewTCB->uxCriticalNesting = ( UBaseType_t ) 0U; - } - #endif /* portCRITICAL_NESTING_IN_TCB */ - - #if ( configUSE_APPLICATION_TASK_TAG == 1 ) - { - pxNewTCB->pxTaskTag = NULL; - } - #endif /* configUSE_APPLICATION_TASK_TAG */ - - #if ( configGENERATE_RUN_TIME_STATS == 1 ) - { - pxNewTCB->ulRunTimeCounter = 0UL; - } - #endif /* configGENERATE_RUN_TIME_STATS */ - - #if ( portUSING_MPU_WRAPPERS == 1 ) - { - vPortStoreTaskMPUSettings( &( pxNewTCB->xMPUSettings ), xRegions, pxNewTCB->pxStack, ulStackDepth ); - } - #else - { - /* Avoid compiler warning about unreferenced parameter. */ - ( void ) xRegions; - } - #endif - - #if( configNUM_THREAD_LOCAL_STORAGE_POINTERS != 0 ) - { - for( x = 0; x < ( UBaseType_t ) configNUM_THREAD_LOCAL_STORAGE_POINTERS; x++ ) - { - pxNewTCB->pvThreadLocalStoragePointers[ x ] = NULL; - } - } - #endif - - #if ( configUSE_TASK_NOTIFICATIONS == 1 ) - { - pxNewTCB->ulNotifiedValue = 0; - pxNewTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION; - } - #endif - - #if ( configUSE_NEWLIB_REENTRANT == 1 ) - { - /* Initialise this task's Newlib reent structure. */ - _REENT_INIT_PTR( ( &( pxNewTCB->xNewLib_reent ) ) ); - } - #endif - - #if( INCLUDE_xTaskAbortDelay == 1 ) - { - pxNewTCB->ucDelayAborted = pdFALSE; - } - #endif - - /* Initialize the TCB stack to look as if the task was already running, - but had been interrupted by the scheduler. The return address is set - to the start of the task function. Once the stack has been initialised - the top of stack variable is updated. */ - #if( portUSING_MPU_WRAPPERS == 1 ) - { - pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxTaskCode, pvParameters, xRunPrivileged ); - } - #else /* portUSING_MPU_WRAPPERS */ - { - pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxTaskCode, pvParameters ); - } - #endif /* portUSING_MPU_WRAPPERS */ - - if( ( void * ) pxCreatedTask != NULL ) - { - /* Pass the handle out in an anonymous way. The handle can be used to - change the created task's priority, delete the created task, etc.*/ - *pxCreatedTask = ( TaskHandle_t ) pxNewTCB; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } -} -/*-----------------------------------------------------------*/ - -static void prvAddNewTaskToReadyList( TCB_t *pxNewTCB ) -{ - /* Ensure interrupts don't access the task lists while the lists are being - updated. */ - taskENTER_CRITICAL(); - { - uxCurrentNumberOfTasks++; - if( pxCurrentTCB == NULL ) - { - /* There are no other tasks, or all the other tasks are in - the suspended state - make this the current task. */ - pxCurrentTCB = pxNewTCB; - - if( uxCurrentNumberOfTasks == ( UBaseType_t ) 1 ) - { - /* This is the first task to be created so do the preliminary - initialisation required. We will not recover if this call - fails, but we will report the failure. */ - prvInitialiseTaskLists(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* If the scheduler is not already running, make this task the - current task if it is the highest priority task to be created - so far. */ - if( xSchedulerRunning == pdFALSE ) - { - if( pxCurrentTCB->uxPriority <= pxNewTCB->uxPriority ) - { - pxCurrentTCB = pxNewTCB; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - - uxTaskNumber++; - - #if ( configUSE_TRACE_FACILITY == 1 ) - { - /* Add a counter into the TCB for tracing only. */ - pxNewTCB->uxTCBNumber = uxTaskNumber; - } - #endif /* configUSE_TRACE_FACILITY */ - traceTASK_CREATE( pxNewTCB ); - - prvAddTaskToReadyList( pxNewTCB ); - - portSETUP_TCB( pxNewTCB ); - } - taskEXIT_CRITICAL(); - - if( xSchedulerRunning != pdFALSE ) - { - /* If the created task is of a higher priority than the current task - then it should run now. */ - if( pxCurrentTCB->uxPriority < pxNewTCB->uxPriority ) - { - taskYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } -} -/*-----------------------------------------------------------*/ - -#if ( INCLUDE_vTaskDelete == 1 ) - - void vTaskDelete( TaskHandle_t xTaskToDelete ) - { - TCB_t *pxTCB; - - taskENTER_CRITICAL(); - { - /* If null is passed in here then it is the calling task that is - being deleted. */ - pxTCB = prvGetTCBFromHandle( xTaskToDelete ); - - /* Remove task from the ready list. */ - if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) - { - taskRESET_READY_PRIORITY( pxTCB->uxPriority ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - /* Is the task waiting on an event also? */ - if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) - { - ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - /* Increment the uxTaskNumber also so kernel aware debuggers can - detect that the task lists need re-generating. This is done before - portPRE_TASK_DELETE_HOOK() as in the Windows port that macro will - not return. */ - uxTaskNumber++; - - if( pxTCB == pxCurrentTCB ) - { - /* A task is deleting itself. This cannot complete within the - task itself, as a context switch to another task is required. - Place the task in the termination list. The idle task will - check the termination list and free up any memory allocated by - the scheduler for the TCB and stack of the deleted task. */ - vListInsertEnd( &xTasksWaitingTermination, &( pxTCB->xStateListItem ) ); - - /* Increment the ucTasksDeleted variable so the idle task knows - there is a task that has been deleted and that it should therefore - check the xTasksWaitingTermination list. */ - ++uxDeletedTasksWaitingCleanUp; - - /* The pre-delete hook is primarily for the Windows simulator, - in which Windows specific clean up operations are performed, - after which it is not possible to yield away from this task - - hence xYieldPending is used to latch that a context switch is - required. */ - portPRE_TASK_DELETE_HOOK( pxTCB, &xYieldPending ); - } - else - { - --uxCurrentNumberOfTasks; - prvDeleteTCB( pxTCB ); - - /* Reset the next expected unblock time in case it referred to - the task that has just been deleted. */ - prvResetNextTaskUnblockTime(); - } - - traceTASK_DELETE( pxTCB ); - } - taskEXIT_CRITICAL(); - - /* Force a reschedule if it is the currently running task that has just - been deleted. */ - if( xSchedulerRunning != pdFALSE ) - { - if( pxTCB == pxCurrentTCB ) - { - configASSERT( uxSchedulerSuspended == 0 ); - portYIELD_WITHIN_API(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } - -#endif /* INCLUDE_vTaskDelete */ -/*-----------------------------------------------------------*/ - -#if ( INCLUDE_vTaskDelayUntil == 1 ) - - void vTaskDelayUntil( TickType_t * const pxPreviousWakeTime, const TickType_t xTimeIncrement ) - { - TickType_t xTimeToWake; - BaseType_t xAlreadyYielded, xShouldDelay = pdFALSE; - - configASSERT( pxPreviousWakeTime ); - configASSERT( ( xTimeIncrement > 0U ) ); - configASSERT( uxSchedulerSuspended == 0 ); - - vTaskSuspendAll(); - { - /* Minor optimisation. The tick count cannot change in this - block. */ - const TickType_t xConstTickCount = xTickCount; - - /* Generate the tick time at which the task wants to wake. */ - xTimeToWake = *pxPreviousWakeTime + xTimeIncrement; - - if( xConstTickCount < *pxPreviousWakeTime ) - { - /* The tick count has overflowed since this function was - lasted called. In this case the only time we should ever - actually delay is if the wake time has also overflowed, - and the wake time is greater than the tick time. When this - is the case it is as if neither time had overflowed. */ - if( ( xTimeToWake < *pxPreviousWakeTime ) && ( xTimeToWake > xConstTickCount ) ) - { - xShouldDelay = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* The tick time has not overflowed. In this case we will - delay if either the wake time has overflowed, and/or the - tick time is less than the wake time. */ - if( ( xTimeToWake < *pxPreviousWakeTime ) || ( xTimeToWake > xConstTickCount ) ) - { - xShouldDelay = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - - /* Update the wake time ready for the next call. */ - *pxPreviousWakeTime = xTimeToWake; - - if( xShouldDelay != pdFALSE ) - { - traceTASK_DELAY_UNTIL( xTimeToWake ); - - /* prvAddCurrentTaskToDelayedList() needs the block time, not - the time to wake, so subtract the current tick count. */ - prvAddCurrentTaskToDelayedList( xTimeToWake - xConstTickCount, pdFALSE ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - xAlreadyYielded = xTaskResumeAll(); - - /* Force a reschedule if xTaskResumeAll has not already done so, we may - have put ourselves to sleep. */ - if( xAlreadyYielded == pdFALSE ) - { - portYIELD_WITHIN_API(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - -#endif /* INCLUDE_vTaskDelayUntil */ -/*-----------------------------------------------------------*/ - -#if ( INCLUDE_vTaskDelay == 1 ) - - void vTaskDelay( const TickType_t xTicksToDelay ) - { - BaseType_t xAlreadyYielded = pdFALSE; - - /* A delay time of zero just forces a reschedule. */ - if( xTicksToDelay > ( TickType_t ) 0U ) - { - configASSERT( uxSchedulerSuspended == 0 ); - vTaskSuspendAll(); - { - traceTASK_DELAY(); - - /* A task that is removed from the event list while the - scheduler is suspended will not get placed in the ready - list or removed from the blocked list until the scheduler - is resumed. - - This task cannot be in an event list as it is the currently - executing task. */ - prvAddCurrentTaskToDelayedList( xTicksToDelay, pdFALSE ); - } - xAlreadyYielded = xTaskResumeAll(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - /* Force a reschedule if xTaskResumeAll has not already done so, we may - have put ourselves to sleep. */ - if( xAlreadyYielded == pdFALSE ) - { - portYIELD_WITHIN_API(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - -#endif /* INCLUDE_vTaskDelay */ -/*-----------------------------------------------------------*/ - -#if( ( INCLUDE_eTaskGetState == 1 ) || ( configUSE_TRACE_FACILITY == 1 ) ) - - eTaskState eTaskGetState( TaskHandle_t xTask ) - { - eTaskState eReturn; - List_t *pxStateList; - const TCB_t * const pxTCB = ( TCB_t * ) xTask; - - configASSERT( pxTCB ); - - if( pxTCB == pxCurrentTCB ) - { - /* The task calling this function is querying its own state. */ - eReturn = eRunning; - } - else - { - taskENTER_CRITICAL(); - { - pxStateList = ( List_t * ) listLIST_ITEM_CONTAINER( &( pxTCB->xStateListItem ) ); - } - taskEXIT_CRITICAL(); - - if( ( pxStateList == pxDelayedTaskList ) || ( pxStateList == pxOverflowDelayedTaskList ) ) - { - /* The task being queried is referenced from one of the Blocked - lists. */ - eReturn = eBlocked; - } - - #if ( INCLUDE_vTaskSuspend == 1 ) - else if( pxStateList == &xSuspendedTaskList ) - { - /* The task being queried is referenced from the suspended - list. Is it genuinely suspended or is it block - indefinitely? */ - if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL ) - { - eReturn = eSuspended; - } - else - { - eReturn = eBlocked; - } - } - #endif - - #if ( INCLUDE_vTaskDelete == 1 ) - else if( ( pxStateList == &xTasksWaitingTermination ) || ( pxStateList == NULL ) ) - { - /* The task being queried is referenced from the deleted - tasks list, or it is not referenced from any lists at - all. */ - eReturn = eDeleted; - } - #endif - - else /*lint !e525 Negative indentation is intended to make use of pre-processor clearer. */ - { - /* If the task is not in any other state, it must be in the - Ready (including pending ready) state. */ - eReturn = eReady; - } - } - - return eReturn; - } /*lint !e818 xTask cannot be a pointer to const because it is a typedef. */ - -#endif /* INCLUDE_eTaskGetState */ -/*-----------------------------------------------------------*/ - -#if ( INCLUDE_uxTaskPriorityGet == 1 ) - - UBaseType_t uxTaskPriorityGet( TaskHandle_t xTask ) - { - TCB_t *pxTCB; - UBaseType_t uxReturn; - - taskENTER_CRITICAL(); - { - /* If null is passed in here then it is the priority of the that - called uxTaskPriorityGet() that is being queried. */ - pxTCB = prvGetTCBFromHandle( xTask ); - uxReturn = pxTCB->uxPriority; - } - taskEXIT_CRITICAL(); - - return uxReturn; - } - -#endif /* INCLUDE_uxTaskPriorityGet */ -/*-----------------------------------------------------------*/ - -#if ( INCLUDE_uxTaskPriorityGet == 1 ) - - UBaseType_t uxTaskPriorityGetFromISR( TaskHandle_t xTask ) - { - TCB_t *pxTCB; - UBaseType_t uxReturn, uxSavedInterruptState; - - /* RTOS ports that support interrupt nesting have the concept of a - maximum system call (or maximum API call) interrupt priority. - Interrupts that are above the maximum system call priority are keep - permanently enabled, even when the RTOS kernel is in a critical section, - but cannot make any calls to FreeRTOS API functions. If configASSERT() - is defined in FreeRTOSConfig.h then - portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion - failure if a FreeRTOS API function is called from an interrupt that has - been assigned a priority above the configured maximum system call - priority. Only FreeRTOS functions that end in FromISR can be called - from interrupts that have been assigned a priority at or (logically) - below the maximum system call interrupt priority. FreeRTOS maintains a - separate interrupt safe API to ensure interrupt entry is as fast and as - simple as possible. More information (albeit Cortex-M specific) is - provided on the following link: - http://www.freertos.org/RTOS-Cortex-M3-M4.html */ - portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); - - uxSavedInterruptState = portSET_INTERRUPT_MASK_FROM_ISR(); - { - /* If null is passed in here then it is the priority of the calling - task that is being queried. */ - pxTCB = prvGetTCBFromHandle( xTask ); - uxReturn = pxTCB->uxPriority; - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptState ); - - return uxReturn; - } - -#endif /* INCLUDE_uxTaskPriorityGet */ -/*-----------------------------------------------------------*/ - -#if ( INCLUDE_vTaskPrioritySet == 1 ) - - void vTaskPrioritySet( TaskHandle_t xTask, UBaseType_t uxNewPriority ) - { - TCB_t *pxTCB; - UBaseType_t uxCurrentBasePriority, uxPriorityUsedOnEntry; - BaseType_t xYieldRequired = pdFALSE; - - configASSERT( ( uxNewPriority < configMAX_PRIORITIES ) ); - - /* Ensure the new priority is valid. */ - if( uxNewPriority >= ( UBaseType_t ) configMAX_PRIORITIES ) - { - uxNewPriority = ( UBaseType_t ) configMAX_PRIORITIES - ( UBaseType_t ) 1U; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - taskENTER_CRITICAL(); - { - /* If null is passed in here then it is the priority of the calling - task that is being changed. */ - pxTCB = prvGetTCBFromHandle( xTask ); - - traceTASK_PRIORITY_SET( pxTCB, uxNewPriority ); - - #if ( configUSE_MUTEXES == 1 ) - { - uxCurrentBasePriority = pxTCB->uxBasePriority; - } - #else - { - uxCurrentBasePriority = pxTCB->uxPriority; - } - #endif - - if( uxCurrentBasePriority != uxNewPriority ) - { - /* The priority change may have readied a task of higher - priority than the calling task. */ - if( uxNewPriority > uxCurrentBasePriority ) - { - if( pxTCB != pxCurrentTCB ) - { - /* The priority of a task other than the currently - running task is being raised. Is the priority being - raised above that of the running task? */ - if( uxNewPriority >= pxCurrentTCB->uxPriority ) - { - xYieldRequired = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* The priority of the running task is being raised, - but the running task must already be the highest - priority task able to run so no yield is required. */ - } - } - else if( pxTCB == pxCurrentTCB ) - { - /* Setting the priority of the running task down means - there may now be another task of higher priority that - is ready to execute. */ - xYieldRequired = pdTRUE; - } - else - { - /* Setting the priority of any other task down does not - require a yield as the running task must be above the - new priority of the task being modified. */ - } - - /* Remember the ready list the task might be referenced from - before its uxPriority member is changed so the - taskRESET_READY_PRIORITY() macro can function correctly. */ - uxPriorityUsedOnEntry = pxTCB->uxPriority; - - #if ( configUSE_MUTEXES == 1 ) - { - /* Only change the priority being used if the task is not - currently using an inherited priority. */ - if( pxTCB->uxBasePriority == pxTCB->uxPriority ) - { - pxTCB->uxPriority = uxNewPriority; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - /* The base priority gets set whatever. */ - pxTCB->uxBasePriority = uxNewPriority; - } - #else - { - pxTCB->uxPriority = uxNewPriority; - } - #endif - - /* Only reset the event list item value if the value is not - being used for anything else. */ - if( ( listGET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ) ) & taskEVENT_LIST_ITEM_VALUE_IN_USE ) == 0UL ) - { - listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), ( ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) uxNewPriority ) ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - /* If the task is in the blocked or suspended list we need do - nothing more than change its priority variable. However, if - the task is in a ready list it needs to be removed and placed - in the list appropriate to its new priority. */ - if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ uxPriorityUsedOnEntry ] ), &( pxTCB->xStateListItem ) ) != pdFALSE ) - { - /* The task is currently in its ready list - remove before - adding it to it's new ready list. As we are in a critical - section we can do this even if the scheduler is suspended. */ - if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) - { - /* It is known that the task is in its ready list so - there is no need to check again and the port level - reset macro can be called directly. */ - portRESET_READY_PRIORITY( uxPriorityUsedOnEntry, uxTopReadyPriority ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - prvAddTaskToReadyList( pxTCB ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - if( xYieldRequired != pdFALSE ) - { - taskYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - /* Remove compiler warning about unused variables when the port - optimised task selection is not being used. */ - ( void ) uxPriorityUsedOnEntry; - } - } - taskEXIT_CRITICAL(); - } - -#endif /* INCLUDE_vTaskPrioritySet */ -/*-----------------------------------------------------------*/ - -#if ( INCLUDE_vTaskSuspend == 1 ) - - void vTaskSuspend( TaskHandle_t xTaskToSuspend ) - { - TCB_t *pxTCB; - - taskENTER_CRITICAL(); - { - /* If null is passed in here then it is the running task that is - being suspended. */ - pxTCB = prvGetTCBFromHandle( xTaskToSuspend ); - - traceTASK_SUSPEND( pxTCB ); - - /* Remove task from the ready/delayed list and place in the - suspended list. */ - if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) - { - taskRESET_READY_PRIORITY( pxTCB->uxPriority ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - /* Is the task waiting on an event also? */ - if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) - { - ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - vListInsertEnd( &xSuspendedTaskList, &( pxTCB->xStateListItem ) ); - - #if( configUSE_TASK_NOTIFICATIONS == 1 ) - { - if( pxTCB->ucNotifyState == taskWAITING_NOTIFICATION ) - { - /* The task was blocked to wait for a notification, but is - now suspended, so no notification was received. */ - pxTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION; - } - } - #endif - } - taskEXIT_CRITICAL(); - - if( xSchedulerRunning != pdFALSE ) - { - /* Reset the next expected unblock time in case it referred to the - task that is now in the Suspended state. */ - taskENTER_CRITICAL(); - { - prvResetNextTaskUnblockTime(); - } - taskEXIT_CRITICAL(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - if( pxTCB == pxCurrentTCB ) - { - if( xSchedulerRunning != pdFALSE ) - { - /* The current task has just been suspended. */ - configASSERT( uxSchedulerSuspended == 0 ); - portYIELD_WITHIN_API(); - } - else - { - /* The scheduler is not running, but the task that was pointed - to by pxCurrentTCB has just been suspended and pxCurrentTCB - must be adjusted to point to a different task. */ - if( listCURRENT_LIST_LENGTH( &xSuspendedTaskList ) == uxCurrentNumberOfTasks ) - { - /* No other tasks are ready, so set pxCurrentTCB back to - NULL so when the next task is created pxCurrentTCB will - be set to point to it no matter what its relative priority - is. */ - pxCurrentTCB = NULL; - } - else - { - vTaskSwitchContext(); - } - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - -#endif /* INCLUDE_vTaskSuspend */ -/*-----------------------------------------------------------*/ - -#if ( INCLUDE_vTaskSuspend == 1 ) - - static BaseType_t prvTaskIsTaskSuspended( const TaskHandle_t xTask ) - { - BaseType_t xReturn = pdFALSE; - const TCB_t * const pxTCB = ( TCB_t * ) xTask; - - /* Accesses xPendingReadyList so must be called from a critical - section. */ - - /* It does not make sense to check if the calling task is suspended. */ - configASSERT( xTask ); - - /* Is the task being resumed actually in the suspended list? */ - if( listIS_CONTAINED_WITHIN( &xSuspendedTaskList, &( pxTCB->xStateListItem ) ) != pdFALSE ) - { - /* Has the task already been resumed from within an ISR? */ - if( listIS_CONTAINED_WITHIN( &xPendingReadyList, &( pxTCB->xEventListItem ) ) == pdFALSE ) - { - /* Is it in the suspended list because it is in the Suspended - state, or because is is blocked with no timeout? */ - if( listIS_CONTAINED_WITHIN( NULL, &( pxTCB->xEventListItem ) ) != pdFALSE ) /*lint !e961. The cast is only redundant when NULL is used. */ - { - xReturn = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - return xReturn; - } /*lint !e818 xTask cannot be a pointer to const because it is a typedef. */ - -#endif /* INCLUDE_vTaskSuspend */ -/*-----------------------------------------------------------*/ - -#if ( INCLUDE_vTaskSuspend == 1 ) - - void vTaskResume( TaskHandle_t xTaskToResume ) - { - TCB_t * const pxTCB = ( TCB_t * ) xTaskToResume; - - /* It does not make sense to resume the calling task. */ - configASSERT( xTaskToResume ); - - /* The parameter cannot be NULL as it is impossible to resume the - currently executing task. */ - if( ( pxTCB != NULL ) && ( pxTCB != pxCurrentTCB ) ) - { - taskENTER_CRITICAL(); - { - if( prvTaskIsTaskSuspended( pxTCB ) != pdFALSE ) - { - traceTASK_RESUME( pxTCB ); - - /* The ready list can be accessed even if the scheduler is - suspended because this is inside a critical section. */ - ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); - prvAddTaskToReadyList( pxTCB ); - - /* A higher priority task may have just been resumed. */ - if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority ) - { - /* This yield may not cause the task just resumed to run, - but will leave the lists in the correct state for the - next yield. */ - taskYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - taskEXIT_CRITICAL(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - -#endif /* INCLUDE_vTaskSuspend */ - -/*-----------------------------------------------------------*/ - -#if ( ( INCLUDE_xTaskResumeFromISR == 1 ) && ( INCLUDE_vTaskSuspend == 1 ) ) - - BaseType_t xTaskResumeFromISR( TaskHandle_t xTaskToResume ) - { - BaseType_t xYieldRequired = pdFALSE; - TCB_t * const pxTCB = ( TCB_t * ) xTaskToResume; - UBaseType_t uxSavedInterruptStatus; - - configASSERT( xTaskToResume ); - - /* RTOS ports that support interrupt nesting have the concept of a - maximum system call (or maximum API call) interrupt priority. - Interrupts that are above the maximum system call priority are keep - permanently enabled, even when the RTOS kernel is in a critical section, - but cannot make any calls to FreeRTOS API functions. If configASSERT() - is defined in FreeRTOSConfig.h then - portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion - failure if a FreeRTOS API function is called from an interrupt that has - been assigned a priority above the configured maximum system call - priority. Only FreeRTOS functions that end in FromISR can be called - from interrupts that have been assigned a priority at or (logically) - below the maximum system call interrupt priority. FreeRTOS maintains a - separate interrupt safe API to ensure interrupt entry is as fast and as - simple as possible. More information (albeit Cortex-M specific) is - provided on the following link: - http://www.freertos.org/RTOS-Cortex-M3-M4.html */ - portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); - - uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); - { - if( prvTaskIsTaskSuspended( pxTCB ) != pdFALSE ) - { - traceTASK_RESUME_FROM_ISR( pxTCB ); - - /* Check the ready lists can be accessed. */ - if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) - { - /* Ready lists can be accessed so move the task from the - suspended list to the ready list directly. */ - if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority ) - { - xYieldRequired = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); - prvAddTaskToReadyList( pxTCB ); - } - else - { - /* The delayed or ready lists cannot be accessed so the task - is held in the pending ready list until the scheduler is - unsuspended. */ - vListInsertEnd( &( xPendingReadyList ), &( pxTCB->xEventListItem ) ); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - - return xYieldRequired; - } - -#endif /* ( ( INCLUDE_xTaskResumeFromISR == 1 ) && ( INCLUDE_vTaskSuspend == 1 ) ) */ -/*-----------------------------------------------------------*/ - -void vTaskStartScheduler( void ) -{ -BaseType_t xReturn; - - /* Add the idle task at the lowest priority. */ - #if( configSUPPORT_STATIC_ALLOCATION == 1 ) - { - StaticTask_t *pxIdleTaskTCBBuffer = NULL; - StackType_t *pxIdleTaskStackBuffer = NULL; - uint32_t ulIdleTaskStackSize; - - /* The Idle task is created using user provided RAM - obtain the - address of the RAM then create the idle task. */ - vApplicationGetIdleTaskMemory( &pxIdleTaskTCBBuffer, &pxIdleTaskStackBuffer, &ulIdleTaskStackSize ); - xIdleTaskHandle = xTaskCreateStatic( prvIdleTask, - configIDLE_TASK_NAME, - ulIdleTaskStackSize, - ( void * ) NULL, /*lint !e961. The cast is not redundant for all compilers. */ - ( tskIDLE_PRIORITY | portPRIVILEGE_BIT ), - pxIdleTaskStackBuffer, - pxIdleTaskTCBBuffer ); /*lint !e961 MISRA exception, justified as it is not a redundant explicit cast to all supported compilers. */ - - if( xIdleTaskHandle != NULL ) - { - xReturn = pdPASS; - } - else - { - xReturn = pdFAIL; - } - } - #else - { - /* The Idle task is being created using dynamically allocated RAM. */ - xReturn = xTaskCreate( prvIdleTask, - configIDLE_TASK_NAME, - configMINIMAL_STACK_SIZE, - ( void * ) NULL, - ( tskIDLE_PRIORITY | portPRIVILEGE_BIT ), - &xIdleTaskHandle ); /*lint !e961 MISRA exception, justified as it is not a redundant explicit cast to all supported compilers. */ - } - #endif /* configSUPPORT_STATIC_ALLOCATION */ - - #if ( configUSE_TIMERS == 1 ) - { - if( xReturn == pdPASS ) - { - xReturn = xTimerCreateTimerTask(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configUSE_TIMERS */ - - if( xReturn == pdPASS ) - { - /* freertos_tasks_c_additions_init() should only be called if the user - definable macro FREERTOS_TASKS_C_ADDITIONS_INIT() is defined, as that is - the only macro called by the function. */ - #ifdef FREERTOS_TASKS_C_ADDITIONS_INIT - { - freertos_tasks_c_additions_init(); - } - #endif - - /* Interrupts are turned off here, to ensure a tick does not occur - before or during the call to xPortStartScheduler(). The stacks of - the created tasks contain a status word with interrupts switched on - so interrupts will automatically get re-enabled when the first task - starts to run. */ - portDISABLE_INTERRUPTS(); - - #if ( configUSE_NEWLIB_REENTRANT == 1 ) - { - /* Switch Newlib's _impure_ptr variable to point to the _reent - structure specific to the task that will run first. */ - _impure_ptr = &( pxCurrentTCB->xNewLib_reent ); - } - #endif /* configUSE_NEWLIB_REENTRANT */ - - xNextTaskUnblockTime = portMAX_DELAY; - xSchedulerRunning = pdTRUE; - xTickCount = ( TickType_t ) 0U; - - /* If configGENERATE_RUN_TIME_STATS is defined then the following - macro must be defined to configure the timer/counter used to generate - the run time counter time base. NOTE: If configGENERATE_RUN_TIME_STATS - is set to 0 and the following line fails to build then ensure you do not - have portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() defined in your - FreeRTOSConfig.h file. */ - portCONFIGURE_TIMER_FOR_RUN_TIME_STATS(); - - /* Setting up the timer tick is hardware specific and thus in the - portable interface. */ - if( xPortStartScheduler() != pdFALSE ) - { - /* Should not reach here as if the scheduler is running the - function will not return. */ - } - else - { - /* Should only reach here if a task calls xTaskEndScheduler(). */ - } - } - else - { - /* This line will only be reached if the kernel could not be started, - because there was not enough FreeRTOS heap to create the idle task - or the timer task. */ - configASSERT( xReturn != errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY ); - } - - /* Prevent compiler warnings if INCLUDE_xTaskGetIdleTaskHandle is set to 0, - meaning xIdleTaskHandle is not used anywhere else. */ - ( void ) xIdleTaskHandle; -} -/*-----------------------------------------------------------*/ - -void vTaskEndScheduler( void ) -{ - /* Stop the scheduler interrupts and call the portable scheduler end - routine so the original ISRs can be restored if necessary. The port - layer must ensure interrupts enable bit is left in the correct state. */ - portDISABLE_INTERRUPTS(); - xSchedulerRunning = pdFALSE; - vPortEndScheduler(); -} -/*----------------------------------------------------------*/ - -void vTaskSuspendAll( void ) -{ - /* A critical section is not required as the variable is of type - BaseType_t. Please read Richard Barry's reply in the following link to a - post in the FreeRTOS support forum before reporting this as a bug! - - http://goo.gl/wu4acr */ - ++uxSchedulerSuspended; -} -/*----------------------------------------------------------*/ - -#if ( configUSE_TICKLESS_IDLE != 0 ) - - static TickType_t prvGetExpectedIdleTime( void ) - { - TickType_t xReturn; - UBaseType_t uxHigherPriorityReadyTasks = pdFALSE; - - /* uxHigherPriorityReadyTasks takes care of the case where - configUSE_PREEMPTION is 0, so there may be tasks above the idle priority - task that are in the Ready state, even though the idle task is - running. */ - #if( configUSE_PORT_OPTIMISED_TASK_SELECTION == 0 ) - { - if( uxTopReadyPriority > tskIDLE_PRIORITY ) - { - uxHigherPriorityReadyTasks = pdTRUE; - } - } - #else - { - const UBaseType_t uxLeastSignificantBit = ( UBaseType_t ) 0x01; - - /* When port optimised task selection is used the uxTopReadyPriority - variable is used as a bit map. If bits other than the least - significant bit are set then there are tasks that have a priority - above the idle priority that are in the Ready state. This takes - care of the case where the co-operative scheduler is in use. */ - if( uxTopReadyPriority > uxLeastSignificantBit ) - { - uxHigherPriorityReadyTasks = pdTRUE; - } - } - #endif - - if( pxCurrentTCB->uxPriority > tskIDLE_PRIORITY ) - { - xReturn = 0; - } - else if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ tskIDLE_PRIORITY ] ) ) > 1 ) - { - /* There are other idle priority tasks in the ready state. If - time slicing is used then the very next tick interrupt must be - processed. */ - xReturn = 0; - } - else if( uxHigherPriorityReadyTasks != pdFALSE ) - { - /* There are tasks in the Ready state that have a priority above the - idle priority. This path can only be reached if - configUSE_PREEMPTION is 0. */ - xReturn = 0; - } - else - { - xReturn = xNextTaskUnblockTime - xTickCount; - } - - return xReturn; - } - -#endif /* configUSE_TICKLESS_IDLE */ -/*----------------------------------------------------------*/ - -BaseType_t xTaskResumeAll( void ) -{ -TCB_t *pxTCB = NULL; -BaseType_t xAlreadyYielded = pdFALSE; - - /* If uxSchedulerSuspended is zero then this function does not match a - previous call to vTaskSuspendAll(). */ - configASSERT( uxSchedulerSuspended ); - - /* It is possible that an ISR caused a task to be removed from an event - list while the scheduler was suspended. If this was the case then the - removed task will have been added to the xPendingReadyList. Once the - scheduler has been resumed it is safe to move all the pending ready - tasks from this list into their appropriate ready list. */ - taskENTER_CRITICAL(); - { - --uxSchedulerSuspended; - - if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) - { - if( uxCurrentNumberOfTasks > ( UBaseType_t ) 0U ) - { - /* Move any readied tasks from the pending list into the - appropriate ready list. */ - while( listLIST_IS_EMPTY( &xPendingReadyList ) == pdFALSE ) - { - pxTCB = ( TCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( ( &xPendingReadyList ) ); - ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); - ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); - prvAddTaskToReadyList( pxTCB ); - - /* If the moved task has a priority higher than the current - task then a yield must be performed. */ - if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority ) - { - xYieldPending = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - - if( pxTCB != NULL ) - { - /* A task was unblocked while the scheduler was suspended, - which may have prevented the next unblock time from being - re-calculated, in which case re-calculate it now. Mainly - important for low power tickless implementations, where - this can prevent an unnecessary exit from low power - state. */ - prvResetNextTaskUnblockTime(); - } - - /* If any ticks occurred while the scheduler was suspended then - they should be processed now. This ensures the tick count does - not slip, and that any delayed tasks are resumed at the correct - time. */ - { - UBaseType_t uxPendedCounts = uxPendedTicks; /* Non-volatile copy. */ - - if( uxPendedCounts > ( UBaseType_t ) 0U ) - { - do - { - if( xTaskIncrementTick() != pdFALSE ) - { - xYieldPending = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - --uxPendedCounts; - } while( uxPendedCounts > ( UBaseType_t ) 0U ); - - uxPendedTicks = 0; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - - if( xYieldPending != pdFALSE ) - { - #if( configUSE_PREEMPTION != 0 ) - { - xAlreadyYielded = pdTRUE; - } - #endif - taskYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - taskEXIT_CRITICAL(); - - return xAlreadyYielded; -} -/*-----------------------------------------------------------*/ - -TickType_t xTaskGetTickCount( void ) -{ -TickType_t xTicks; - - /* Critical section required if running on a 16 bit processor. */ - portTICK_TYPE_ENTER_CRITICAL(); - { - xTicks = xTickCount; - } - portTICK_TYPE_EXIT_CRITICAL(); - - return xTicks; -} -/*-----------------------------------------------------------*/ - -TickType_t xTaskGetTickCountFromISR( void ) -{ -TickType_t xReturn; -UBaseType_t uxSavedInterruptStatus; - - /* RTOS ports that support interrupt nesting have the concept of a maximum - system call (or maximum API call) interrupt priority. Interrupts that are - above the maximum system call priority are kept permanently enabled, even - when the RTOS kernel is in a critical section, but cannot make any calls to - FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h - then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion - failure if a FreeRTOS API function is called from an interrupt that has been - assigned a priority above the configured maximum system call priority. - Only FreeRTOS functions that end in FromISR can be called from interrupts - that have been assigned a priority at or (logically) below the maximum - system call interrupt priority. FreeRTOS maintains a separate interrupt - safe API to ensure interrupt entry is as fast and as simple as possible. - More information (albeit Cortex-M specific) is provided on the following - link: http://www.freertos.org/RTOS-Cortex-M3-M4.html */ - portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); - - uxSavedInterruptStatus = portTICK_TYPE_SET_INTERRUPT_MASK_FROM_ISR(); - { - xReturn = xTickCount; - } - portTICK_TYPE_CLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - - return xReturn; -} -/*-----------------------------------------------------------*/ - -UBaseType_t uxTaskGetNumberOfTasks( void ) -{ - /* A critical section is not required because the variables are of type - BaseType_t. */ - return uxCurrentNumberOfTasks; -} -/*-----------------------------------------------------------*/ - -char *pcTaskGetName( TaskHandle_t xTaskToQuery ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ -{ -TCB_t *pxTCB; - - /* If null is passed in here then the name of the calling task is being - queried. */ - pxTCB = prvGetTCBFromHandle( xTaskToQuery ); - configASSERT( pxTCB ); - return &( pxTCB->pcTaskName[ 0 ] ); -} -/*-----------------------------------------------------------*/ - -#if ( INCLUDE_xTaskGetHandle == 1 ) - - static TCB_t *prvSearchForNameWithinSingleList( List_t *pxList, const char pcNameToQuery[] ) - { - TCB_t *pxNextTCB, *pxFirstTCB, *pxReturn = NULL; - UBaseType_t x; - char cNextChar; - - /* This function is called with the scheduler suspended. */ - - if( listCURRENT_LIST_LENGTH( pxList ) > ( UBaseType_t ) 0 ) - { - listGET_OWNER_OF_NEXT_ENTRY( pxFirstTCB, pxList ); - - do - { - listGET_OWNER_OF_NEXT_ENTRY( pxNextTCB, pxList ); - - /* Check each character in the name looking for a match or - mismatch. */ - for( x = ( UBaseType_t ) 0; x < ( UBaseType_t ) configMAX_TASK_NAME_LEN; x++ ) - { - cNextChar = pxNextTCB->pcTaskName[ x ]; - - if( cNextChar != pcNameToQuery[ x ] ) - { - /* Characters didn't match. */ - break; - } - else if( cNextChar == 0x00 ) - { - /* Both strings terminated, a match must have been - found. */ - pxReturn = pxNextTCB; - break; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - - if( pxReturn != NULL ) - { - /* The handle has been found. */ - break; - } - - } while( pxNextTCB != pxFirstTCB ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - return pxReturn; - } - -#endif /* INCLUDE_xTaskGetHandle */ -/*-----------------------------------------------------------*/ - -#if ( INCLUDE_xTaskGetHandle == 1 ) - - TaskHandle_t xTaskGetHandle( const char *pcNameToQuery ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - { - UBaseType_t uxQueue = configMAX_PRIORITIES; - TCB_t* pxTCB; - - /* Task names will be truncated to configMAX_TASK_NAME_LEN - 1 bytes. */ - configASSERT( strlen( pcNameToQuery ) < configMAX_TASK_NAME_LEN ); - - vTaskSuspendAll(); - { - /* Search the ready lists. */ - do - { - uxQueue--; - pxTCB = prvSearchForNameWithinSingleList( ( List_t * ) &( pxReadyTasksLists[ uxQueue ] ), pcNameToQuery ); - - if( pxTCB != NULL ) - { - /* Found the handle. */ - break; - } - - } while( uxQueue > ( UBaseType_t ) tskIDLE_PRIORITY ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - - /* Search the delayed lists. */ - if( pxTCB == NULL ) - { - pxTCB = prvSearchForNameWithinSingleList( ( List_t * ) pxDelayedTaskList, pcNameToQuery ); - } - - if( pxTCB == NULL ) - { - pxTCB = prvSearchForNameWithinSingleList( ( List_t * ) pxOverflowDelayedTaskList, pcNameToQuery ); - } - - #if ( INCLUDE_vTaskSuspend == 1 ) - { - if( pxTCB == NULL ) - { - /* Search the suspended list. */ - pxTCB = prvSearchForNameWithinSingleList( &xSuspendedTaskList, pcNameToQuery ); - } - } - #endif - - #if( INCLUDE_vTaskDelete == 1 ) - { - if( pxTCB == NULL ) - { - /* Search the deleted list. */ - pxTCB = prvSearchForNameWithinSingleList( &xTasksWaitingTermination, pcNameToQuery ); - } - } - #endif - } - ( void ) xTaskResumeAll(); - - return ( TaskHandle_t ) pxTCB; - } - -#endif /* INCLUDE_xTaskGetHandle */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_TRACE_FACILITY == 1 ) - - UBaseType_t uxTaskGetSystemState( TaskStatus_t * const pxTaskStatusArray, const UBaseType_t uxArraySize, uint32_t * const pulTotalRunTime ) - { - UBaseType_t uxTask = 0, uxQueue = configMAX_PRIORITIES; - - vTaskSuspendAll(); - { - /* Is there a space in the array for each task in the system? */ - if( uxArraySize >= uxCurrentNumberOfTasks ) - { - /* Fill in an TaskStatus_t structure with information on each - task in the Ready state. */ - do - { - uxQueue--; - uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), &( pxReadyTasksLists[ uxQueue ] ), eReady ); - - } while( uxQueue > ( UBaseType_t ) tskIDLE_PRIORITY ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - - /* Fill in an TaskStatus_t structure with information on each - task in the Blocked state. */ - uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), ( List_t * ) pxDelayedTaskList, eBlocked ); - uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), ( List_t * ) pxOverflowDelayedTaskList, eBlocked ); - - #if( INCLUDE_vTaskDelete == 1 ) - { - /* Fill in an TaskStatus_t structure with information on - each task that has been deleted but not yet cleaned up. */ - uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), &xTasksWaitingTermination, eDeleted ); - } - #endif - - #if ( INCLUDE_vTaskSuspend == 1 ) - { - /* Fill in an TaskStatus_t structure with information on - each task in the Suspended state. */ - uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), &xSuspendedTaskList, eSuspended ); - } - #endif - - #if ( configGENERATE_RUN_TIME_STATS == 1) - { - if( pulTotalRunTime != NULL ) - { - #ifdef portALT_GET_RUN_TIME_COUNTER_VALUE - portALT_GET_RUN_TIME_COUNTER_VALUE( ( *pulTotalRunTime ) ); - #else - *pulTotalRunTime = portGET_RUN_TIME_COUNTER_VALUE(); - #endif - } - } - #else - { - if( pulTotalRunTime != NULL ) - { - *pulTotalRunTime = 0; - } - } - #endif - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - ( void ) xTaskResumeAll(); - - return uxTask; - } - -#endif /* configUSE_TRACE_FACILITY */ -/*----------------------------------------------------------*/ - -#if ( INCLUDE_xTaskGetIdleTaskHandle == 1 ) - - TaskHandle_t xTaskGetIdleTaskHandle( void ) - { - /* If xTaskGetIdleTaskHandle() is called before the scheduler has been - started, then xIdleTaskHandle will be NULL. */ - configASSERT( ( xIdleTaskHandle != NULL ) ); - return xIdleTaskHandle; - } - -#endif /* INCLUDE_xTaskGetIdleTaskHandle */ -/*----------------------------------------------------------*/ - -/* This conditional compilation should use inequality to 0, not equality to 1. -This is to ensure vTaskStepTick() is available when user defined low power mode -implementations require configUSE_TICKLESS_IDLE to be set to a value other than -1. */ -#if ( configUSE_TICKLESS_IDLE != 0 ) - - void vTaskStepTick( const TickType_t xTicksToJump ) - { - /* Correct the tick count value after a period during which the tick - was suppressed. Note this does *not* call the tick hook function for - each stepped tick. */ - configASSERT( ( xTickCount + xTicksToJump ) <= xNextTaskUnblockTime ); - xTickCount += xTicksToJump; - traceINCREASE_TICK_COUNT( xTicksToJump ); - } - -#endif /* configUSE_TICKLESS_IDLE */ -/*----------------------------------------------------------*/ - -#if ( INCLUDE_xTaskAbortDelay == 1 ) - - BaseType_t xTaskAbortDelay( TaskHandle_t xTask ) - { - TCB_t *pxTCB = ( TCB_t * ) xTask; - BaseType_t xReturn; - - configASSERT( pxTCB ); - - vTaskSuspendAll(); - { - /* A task can only be prematurely removed from the Blocked state if - it is actually in the Blocked state. */ - if( eTaskGetState( xTask ) == eBlocked ) - { - xReturn = pdPASS; - - /* Remove the reference to the task from the blocked list. An - interrupt won't touch the xStateListItem because the - scheduler is suspended. */ - ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); - - /* Is the task waiting on an event also? If so remove it from - the event list too. Interrupts can touch the event list item, - even though the scheduler is suspended, so a critical section - is used. */ - taskENTER_CRITICAL(); - { - if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) - { - ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); - pxTCB->ucDelayAborted = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - taskEXIT_CRITICAL(); - - /* Place the unblocked task into the appropriate ready list. */ - prvAddTaskToReadyList( pxTCB ); - - /* A task being unblocked cannot cause an immediate context - switch if preemption is turned off. */ - #if ( configUSE_PREEMPTION == 1 ) - { - /* Preemption is on, but a context switch should only be - performed if the unblocked task has a priority that is - equal to or higher than the currently executing task. */ - if( pxTCB->uxPriority > pxCurrentTCB->uxPriority ) - { - /* Pend the yield to be performed when the scheduler - is unsuspended. */ - xYieldPending = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configUSE_PREEMPTION */ - } - else - { - xReturn = pdFAIL; - } - } - ( void ) xTaskResumeAll(); - - return xReturn; - } - -#endif /* INCLUDE_xTaskAbortDelay */ -/*----------------------------------------------------------*/ - -BaseType_t xTaskIncrementTick( void ) -{ -TCB_t * pxTCB; -TickType_t xItemValue; -BaseType_t xSwitchRequired = pdFALSE; - - /* Called by the portable layer each time a tick interrupt occurs. - Increments the tick then checks to see if the new tick value will cause any - tasks to be unblocked. */ - traceTASK_INCREMENT_TICK( xTickCount ); - if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) - { - /* Minor optimisation. The tick count cannot change in this - block. */ - const TickType_t xConstTickCount = xTickCount + ( TickType_t ) 1; - - /* Increment the RTOS tick, switching the delayed and overflowed - delayed lists if it wraps to 0. */ - xTickCount = xConstTickCount; - - if( xConstTickCount == ( TickType_t ) 0U ) /*lint !e774 'if' does not always evaluate to false as it is looking for an overflow. */ - { - taskSWITCH_DELAYED_LISTS(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - /* See if this tick has made a timeout expire. Tasks are stored in - the queue in the order of their wake time - meaning once one task - has been found whose block time has not expired there is no need to - look any further down the list. */ - if( xConstTickCount >= xNextTaskUnblockTime ) - { - for( ;; ) - { - if( listLIST_IS_EMPTY( pxDelayedTaskList ) != pdFALSE ) - { - /* The delayed list is empty. Set xNextTaskUnblockTime - to the maximum possible value so it is extremely - unlikely that the - if( xTickCount >= xNextTaskUnblockTime ) test will pass - next time through. */ - xNextTaskUnblockTime = portMAX_DELAY; /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - break; - } - else - { - /* The delayed list is not empty, get the value of the - item at the head of the delayed list. This is the time - at which the task at the head of the delayed list must - be removed from the Blocked state. */ - pxTCB = ( TCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxDelayedTaskList ); - xItemValue = listGET_LIST_ITEM_VALUE( &( pxTCB->xStateListItem ) ); - - if( xConstTickCount < xItemValue ) - { - /* It is not time to unblock this item yet, but the - item value is the time at which the task at the head - of the blocked list must be removed from the Blocked - state - so record the item value in - xNextTaskUnblockTime. */ - xNextTaskUnblockTime = xItemValue; - break; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - /* It is time to remove the item from the Blocked state. */ - ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); - - /* Is the task waiting on an event also? If so remove - it from the event list. */ - if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) - { - ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - /* Place the unblocked task into the appropriate ready - list. */ - prvAddTaskToReadyList( pxTCB ); - - /* A task being unblocked cannot cause an immediate - context switch if preemption is turned off. */ - #if ( configUSE_PREEMPTION == 1 ) - { - /* Preemption is on, but a context switch should - only be performed if the unblocked task has a - priority that is equal to or higher than the - currently executing task. */ - if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority ) - { - xSwitchRequired = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configUSE_PREEMPTION */ - } - } - } - - /* Tasks of equal priority to the currently running task will share - processing time (time slice) if preemption is on, and the application - writer has not explicitly turned time slicing off. */ - #if ( ( configUSE_PREEMPTION == 1 ) && ( configUSE_TIME_SLICING == 1 ) ) - { - if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ pxCurrentTCB->uxPriority ] ) ) > ( UBaseType_t ) 1 ) - { - xSwitchRequired = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* ( ( configUSE_PREEMPTION == 1 ) && ( configUSE_TIME_SLICING == 1 ) ) */ - - #if ( configUSE_TICK_HOOK == 1 ) - { - /* Guard against the tick hook being called when the pended tick - count is being unwound (when the scheduler is being unlocked). */ - if( uxPendedTicks == ( UBaseType_t ) 0U ) - { - vApplicationTickHook(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configUSE_TICK_HOOK */ - } - else - { - ++uxPendedTicks; - - /* The tick hook gets called at regular intervals, even if the - scheduler is locked. */ - #if ( configUSE_TICK_HOOK == 1 ) - { - vApplicationTickHook(); - } - #endif - } - - #if ( configUSE_PREEMPTION == 1 ) - { - if( xYieldPending != pdFALSE ) - { - xSwitchRequired = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configUSE_PREEMPTION */ - - return xSwitchRequired; -} -/*-----------------------------------------------------------*/ - -#if ( configUSE_APPLICATION_TASK_TAG == 1 ) - - void vTaskSetApplicationTaskTag( TaskHandle_t xTask, TaskHookFunction_t pxHookFunction ) - { - TCB_t *xTCB; - - /* If xTask is NULL then it is the task hook of the calling task that is - getting set. */ - if( xTask == NULL ) - { - xTCB = ( TCB_t * ) pxCurrentTCB; - } - else - { - xTCB = ( TCB_t * ) xTask; - } - - /* Save the hook function in the TCB. A critical section is required as - the value can be accessed from an interrupt. */ - taskENTER_CRITICAL(); - xTCB->pxTaskTag = pxHookFunction; - taskEXIT_CRITICAL(); - } - -#endif /* configUSE_APPLICATION_TASK_TAG */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_APPLICATION_TASK_TAG == 1 ) - - TaskHookFunction_t xTaskGetApplicationTaskTag( TaskHandle_t xTask ) - { - TCB_t *xTCB; - TaskHookFunction_t xReturn; - - /* If xTask is NULL then we are setting our own task hook. */ - if( xTask == NULL ) - { - xTCB = ( TCB_t * ) pxCurrentTCB; - } - else - { - xTCB = ( TCB_t * ) xTask; - } - - /* Save the hook function in the TCB. A critical section is required as - the value can be accessed from an interrupt. */ - taskENTER_CRITICAL(); - { - xReturn = xTCB->pxTaskTag; - } - taskEXIT_CRITICAL(); - - return xReturn; - } - -#endif /* configUSE_APPLICATION_TASK_TAG */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_APPLICATION_TASK_TAG == 1 ) - - BaseType_t xTaskCallApplicationTaskHook( TaskHandle_t xTask, void *pvParameter ) - { - TCB_t *xTCB; - BaseType_t xReturn; - - /* If xTask is NULL then we are calling our own task hook. */ - if( xTask == NULL ) - { - xTCB = ( TCB_t * ) pxCurrentTCB; - } - else - { - xTCB = ( TCB_t * ) xTask; - } - - if( xTCB->pxTaskTag != NULL ) - { - xReturn = xTCB->pxTaskTag( pvParameter ); - } - else - { - xReturn = pdFAIL; - } - - return xReturn; - } - -#endif /* configUSE_APPLICATION_TASK_TAG */ -/*-----------------------------------------------------------*/ - -void vTaskSwitchContext( void ) -{ - if( uxSchedulerSuspended != ( UBaseType_t ) pdFALSE ) - { - /* The scheduler is currently suspended - do not allow a context - switch. */ - xYieldPending = pdTRUE; - } - else - { - xYieldPending = pdFALSE; - traceTASK_SWITCHED_OUT(); - - #if ( configGENERATE_RUN_TIME_STATS == 1 ) - { - #ifdef portALT_GET_RUN_TIME_COUNTER_VALUE - portALT_GET_RUN_TIME_COUNTER_VALUE( ulTotalRunTime ); - #else - ulTotalRunTime = portGET_RUN_TIME_COUNTER_VALUE(); - #endif - - /* Add the amount of time the task has been running to the - accumulated time so far. The time the task started running was - stored in ulTaskSwitchedInTime. Note that there is no overflow - protection here so count values are only valid until the timer - overflows. The guard against negative values is to protect - against suspect run time stat counter implementations - which - are provided by the application, not the kernel. */ - if( ulTotalRunTime > ulTaskSwitchedInTime ) - { - pxCurrentTCB->ulRunTimeCounter += ( ulTotalRunTime - ulTaskSwitchedInTime ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - ulTaskSwitchedInTime = ulTotalRunTime; - } - #endif /* configGENERATE_RUN_TIME_STATS */ - - /* Check for stack overflow, if configured. */ - taskCHECK_FOR_STACK_OVERFLOW(); - - /* Select a new task to run using either the generic C or port - optimised asm code. */ - taskSELECT_HIGHEST_PRIORITY_TASK(); - traceTASK_SWITCHED_IN(); - - #if ( configUSE_NEWLIB_REENTRANT == 1 ) - { - /* Switch Newlib's _impure_ptr variable to point to the _reent - structure specific to this task. */ - _impure_ptr = &( pxCurrentTCB->xNewLib_reent ); - } - #endif /* configUSE_NEWLIB_REENTRANT */ - } -} -/*-----------------------------------------------------------*/ - -void vTaskPlaceOnEventList( List_t * const pxEventList, const TickType_t xTicksToWait ) -{ - configASSERT( pxEventList ); - - /* THIS FUNCTION MUST BE CALLED WITH EITHER INTERRUPTS DISABLED OR THE - SCHEDULER SUSPENDED AND THE QUEUE BEING ACCESSED LOCKED. */ - - /* Place the event list item of the TCB in the appropriate event list. - This is placed in the list in priority order so the highest priority task - is the first to be woken by the event. The queue that contains the event - list is locked, preventing simultaneous access from interrupts. */ - vListInsert( pxEventList, &( pxCurrentTCB->xEventListItem ) ); - - prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE ); -} -/*-----------------------------------------------------------*/ - -void vTaskPlaceOnUnorderedEventList( List_t * pxEventList, const TickType_t xItemValue, const TickType_t xTicksToWait ) -{ - configASSERT( pxEventList ); - - /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED. It is used by - the event groups implementation. */ - configASSERT( uxSchedulerSuspended != 0 ); - - /* Store the item value in the event list item. It is safe to access the - event list item here as interrupts won't access the event list item of a - task that is not in the Blocked state. */ - listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xEventListItem ), xItemValue | taskEVENT_LIST_ITEM_VALUE_IN_USE ); - - /* Place the event list item of the TCB at the end of the appropriate event - list. It is safe to access the event list here because it is part of an - event group implementation - and interrupts don't access event groups - directly (instead they access them indirectly by pending function calls to - the task level). */ - vListInsertEnd( pxEventList, &( pxCurrentTCB->xEventListItem ) ); - - prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE ); -} -/*-----------------------------------------------------------*/ - -#if( configUSE_TIMERS == 1 ) - - void vTaskPlaceOnEventListRestricted( List_t * const pxEventList, TickType_t xTicksToWait, const BaseType_t xWaitIndefinitely ) - { - configASSERT( pxEventList ); - - /* This function should not be called by application code hence the - 'Restricted' in its name. It is not part of the public API. It is - designed for use by kernel code, and has special calling requirements - - it should be called with the scheduler suspended. */ - - - /* Place the event list item of the TCB in the appropriate event list. - In this case it is assume that this is the only task that is going to - be waiting on this event list, so the faster vListInsertEnd() function - can be used in place of vListInsert. */ - vListInsertEnd( pxEventList, &( pxCurrentTCB->xEventListItem ) ); - - /* If the task should block indefinitely then set the block time to a - value that will be recognised as an indefinite delay inside the - prvAddCurrentTaskToDelayedList() function. */ - if( xWaitIndefinitely != pdFALSE ) - { - xTicksToWait = portMAX_DELAY; - } - - traceTASK_DELAY_UNTIL( ( xTickCount + xTicksToWait ) ); - prvAddCurrentTaskToDelayedList( xTicksToWait, xWaitIndefinitely ); - } - -#endif /* configUSE_TIMERS */ -/*-----------------------------------------------------------*/ - -BaseType_t xTaskRemoveFromEventList( const List_t * const pxEventList ) -{ -TCB_t *pxUnblockedTCB; -BaseType_t xReturn; - - /* THIS FUNCTION MUST BE CALLED FROM A CRITICAL SECTION. It can also be - called from a critical section within an ISR. */ - - /* The event list is sorted in priority order, so the first in the list can - be removed as it is known to be the highest priority. Remove the TCB from - the delayed list, and add it to the ready list. - - If an event is for a queue that is locked then this function will never - get called - the lock count on the queue will get modified instead. This - means exclusive access to the event list is guaranteed here. - - This function assumes that a check has already been made to ensure that - pxEventList is not empty. */ - pxUnblockedTCB = ( TCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxEventList ); - configASSERT( pxUnblockedTCB ); - ( void ) uxListRemove( &( pxUnblockedTCB->xEventListItem ) ); - - if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) - { - ( void ) uxListRemove( &( pxUnblockedTCB->xStateListItem ) ); - prvAddTaskToReadyList( pxUnblockedTCB ); - } - else - { - /* The delayed and ready lists cannot be accessed, so hold this task - pending until the scheduler is resumed. */ - vListInsertEnd( &( xPendingReadyList ), &( pxUnblockedTCB->xEventListItem ) ); - } - - if( pxUnblockedTCB->uxPriority > pxCurrentTCB->uxPriority ) - { - /* Return true if the task removed from the event list has a higher - priority than the calling task. This allows the calling task to know if - it should force a context switch now. */ - xReturn = pdTRUE; - - /* Mark that a yield is pending in case the user is not using the - "xHigherPriorityTaskWoken" parameter to an ISR safe FreeRTOS function. */ - xYieldPending = pdTRUE; - } - else - { - xReturn = pdFALSE; - } - - #if( configUSE_TICKLESS_IDLE != 0 ) - { - /* If a task is blocked on a kernel object then xNextTaskUnblockTime - might be set to the blocked task's time out time. If the task is - unblocked for a reason other than a timeout xNextTaskUnblockTime is - normally left unchanged, because it is automatically reset to a new - value when the tick count equals xNextTaskUnblockTime. However if - tickless idling is used it might be more important to enter sleep mode - at the earliest possible time - so reset xNextTaskUnblockTime here to - ensure it is updated at the earliest possible time. */ - prvResetNextTaskUnblockTime(); - } - #endif - - return xReturn; -} -/*-----------------------------------------------------------*/ - -void vTaskRemoveFromUnorderedEventList( ListItem_t * pxEventListItem, const TickType_t xItemValue ) -{ -TCB_t *pxUnblockedTCB; - - /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED. It is used by - the event flags implementation. */ - configASSERT( uxSchedulerSuspended != pdFALSE ); - - /* Store the new item value in the event list. */ - listSET_LIST_ITEM_VALUE( pxEventListItem, xItemValue | taskEVENT_LIST_ITEM_VALUE_IN_USE ); - - /* Remove the event list form the event flag. Interrupts do not access - event flags. */ - pxUnblockedTCB = ( TCB_t * ) listGET_LIST_ITEM_OWNER( pxEventListItem ); - configASSERT( pxUnblockedTCB ); - ( void ) uxListRemove( pxEventListItem ); - - /* Remove the task from the delayed list and add it to the ready list. The - scheduler is suspended so interrupts will not be accessing the ready - lists. */ - ( void ) uxListRemove( &( pxUnblockedTCB->xStateListItem ) ); - prvAddTaskToReadyList( pxUnblockedTCB ); - - if( pxUnblockedTCB->uxPriority > pxCurrentTCB->uxPriority ) - { - /* The unblocked task has a priority above that of the calling task, so - a context switch is required. This function is called with the - scheduler suspended so xYieldPending is set so the context switch - occurs immediately that the scheduler is resumed (unsuspended). */ - xYieldPending = pdTRUE; - } -} -/*-----------------------------------------------------------*/ - -void vTaskSetTimeOutState( TimeOut_t * const pxTimeOut ) -{ - configASSERT( pxTimeOut ); - taskENTER_CRITICAL(); - { - pxTimeOut->xOverflowCount = xNumOfOverflows; - pxTimeOut->xTimeOnEntering = xTickCount; - } - taskEXIT_CRITICAL(); -} -/*-----------------------------------------------------------*/ - -void vTaskInternalSetTimeOutState( TimeOut_t * const pxTimeOut ) -{ - /* For internal use only as it does not use a critical section. */ - pxTimeOut->xOverflowCount = xNumOfOverflows; - pxTimeOut->xTimeOnEntering = xTickCount; -} -/*-----------------------------------------------------------*/ - -BaseType_t xTaskCheckForTimeOut( TimeOut_t * const pxTimeOut, TickType_t * const pxTicksToWait ) -{ -BaseType_t xReturn; - - configASSERT( pxTimeOut ); - configASSERT( pxTicksToWait ); - - taskENTER_CRITICAL(); - { - /* Minor optimisation. The tick count cannot change in this block. */ - const TickType_t xConstTickCount = xTickCount; - const TickType_t xElapsedTime = xConstTickCount - pxTimeOut->xTimeOnEntering; - - #if( INCLUDE_xTaskAbortDelay == 1 ) - if( pxCurrentTCB->ucDelayAborted != pdFALSE ) - { - /* The delay was aborted, which is not the same as a time out, - but has the same result. */ - pxCurrentTCB->ucDelayAborted = pdFALSE; - xReturn = pdTRUE; - } - else - #endif - - #if ( INCLUDE_vTaskSuspend == 1 ) - if( *pxTicksToWait == portMAX_DELAY ) - { - /* If INCLUDE_vTaskSuspend is set to 1 and the block time - specified is the maximum block time then the task should block - indefinitely, and therefore never time out. */ - xReturn = pdFALSE; - } - else - #endif - - if( ( xNumOfOverflows != pxTimeOut->xOverflowCount ) && ( xConstTickCount >= pxTimeOut->xTimeOnEntering ) ) /*lint !e525 Indentation preferred as is to make code within pre-processor directives clearer. */ - { - /* The tick count is greater than the time at which - vTaskSetTimeout() was called, but has also overflowed since - vTaskSetTimeOut() was called. It must have wrapped all the way - around and gone past again. This passed since vTaskSetTimeout() - was called. */ - xReturn = pdTRUE; - } - else if( xElapsedTime < *pxTicksToWait ) /*lint !e961 Explicit casting is only redundant with some compilers, whereas others require it to prevent integer conversion errors. */ - { - /* Not a genuine timeout. Adjust parameters for time remaining. */ - *pxTicksToWait -= xElapsedTime; - vTaskInternalSetTimeOutState( pxTimeOut ); - xReturn = pdFALSE; - } - else - { - *pxTicksToWait = 0; - xReturn = pdTRUE; - } - } - taskEXIT_CRITICAL(); - - return xReturn; -} -/*-----------------------------------------------------------*/ - -void vTaskMissedYield( void ) -{ - xYieldPending = pdTRUE; -} -/*-----------------------------------------------------------*/ - -#if ( configUSE_TRACE_FACILITY == 1 ) - - UBaseType_t uxTaskGetTaskNumber( TaskHandle_t xTask ) - { - UBaseType_t uxReturn; - TCB_t *pxTCB; - - if( xTask != NULL ) - { - pxTCB = ( TCB_t * ) xTask; - uxReturn = pxTCB->uxTaskNumber; - } - else - { - uxReturn = 0U; - } - - return uxReturn; - } - -#endif /* configUSE_TRACE_FACILITY */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_TRACE_FACILITY == 1 ) - - void vTaskSetTaskNumber( TaskHandle_t xTask, const UBaseType_t uxHandle ) - { - TCB_t *pxTCB; - - if( xTask != NULL ) - { - pxTCB = ( TCB_t * ) xTask; - pxTCB->uxTaskNumber = uxHandle; - } - } - -#endif /* configUSE_TRACE_FACILITY */ - -/* - * ----------------------------------------------------------- - * The Idle task. - * ---------------------------------------------------------- - * - * The portTASK_FUNCTION() macro is used to allow port/compiler specific - * language extensions. The equivalent prototype for this function is: - * - * void prvIdleTask( void *pvParameters ); - * - */ -static portTASK_FUNCTION( prvIdleTask, pvParameters ) -{ - /* Stop warnings. */ - ( void ) pvParameters; - - /** THIS IS THE RTOS IDLE TASK - WHICH IS CREATED AUTOMATICALLY WHEN THE - SCHEDULER IS STARTED. **/ - - /* In case a task that has a secure context deletes itself, in which case - the idle task is responsible for deleting the task's secure context, if - any. */ - portTASK_CALLS_SECURE_FUNCTIONS(); - - for( ;; ) - { - /* See if any tasks have deleted themselves - if so then the idle task - is responsible for freeing the deleted task's TCB and stack. */ - prvCheckTasksWaitingTermination(); - - #if ( configUSE_PREEMPTION == 0 ) - { - /* If we are not using preemption we keep forcing a task switch to - see if any other task has become available. If we are using - preemption we don't need to do this as any task becoming available - will automatically get the processor anyway. */ - taskYIELD(); - } - #endif /* configUSE_PREEMPTION */ - - #if ( ( configUSE_PREEMPTION == 1 ) && ( configIDLE_SHOULD_YIELD == 1 ) ) - { - /* When using preemption tasks of equal priority will be - timesliced. If a task that is sharing the idle priority is ready - to run then the idle task should yield before the end of the - timeslice. - - A critical region is not required here as we are just reading from - the list, and an occasional incorrect value will not matter. If - the ready list at the idle priority contains more than one task - then a task other than the idle task is ready to execute. */ - if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ tskIDLE_PRIORITY ] ) ) > ( UBaseType_t ) 1 ) - { - taskYIELD(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* ( ( configUSE_PREEMPTION == 1 ) && ( configIDLE_SHOULD_YIELD == 1 ) ) */ - - #if ( configUSE_IDLE_HOOK == 1 ) - { - extern void vApplicationIdleHook( void ); - - /* Call the user defined function from within the idle task. This - allows the application designer to add background functionality - without the overhead of a separate task. - NOTE: vApplicationIdleHook() MUST NOT, UNDER ANY CIRCUMSTANCES, - CALL A FUNCTION THAT MIGHT BLOCK. */ - vApplicationIdleHook(); - } - #endif /* configUSE_IDLE_HOOK */ - - /* This conditional compilation should use inequality to 0, not equality - to 1. This is to ensure portSUPPRESS_TICKS_AND_SLEEP() is called when - user defined low power mode implementations require - configUSE_TICKLESS_IDLE to be set to a value other than 1. */ - #if ( configUSE_TICKLESS_IDLE != 0 ) - { - TickType_t xExpectedIdleTime; - - /* It is not desirable to suspend then resume the scheduler on - each iteration of the idle task. Therefore, a preliminary - test of the expected idle time is performed without the - scheduler suspended. The result here is not necessarily - valid. */ - xExpectedIdleTime = prvGetExpectedIdleTime(); - - if( xExpectedIdleTime >= configEXPECTED_IDLE_TIME_BEFORE_SLEEP ) - { - vTaskSuspendAll(); - { - /* Now the scheduler is suspended, the expected idle - time can be sampled again, and this time its value can - be used. */ - configASSERT( xNextTaskUnblockTime >= xTickCount ); - xExpectedIdleTime = prvGetExpectedIdleTime(); - - /* Define the following macro to set xExpectedIdleTime to 0 - if the application does not want - portSUPPRESS_TICKS_AND_SLEEP() to be called. */ - configPRE_SUPPRESS_TICKS_AND_SLEEP_PROCESSING( xExpectedIdleTime ); - - if( xExpectedIdleTime >= configEXPECTED_IDLE_TIME_BEFORE_SLEEP ) - { - traceLOW_POWER_IDLE_BEGIN(); - portSUPPRESS_TICKS_AND_SLEEP( xExpectedIdleTime ); - traceLOW_POWER_IDLE_END(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - ( void ) xTaskResumeAll(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configUSE_TICKLESS_IDLE */ - } -} -/*-----------------------------------------------------------*/ - -#if( configUSE_TICKLESS_IDLE != 0 ) - - eSleepModeStatus eTaskConfirmSleepModeStatus( void ) - { - /* The idle task exists in addition to the application tasks. */ - const UBaseType_t uxNonApplicationTasks = 1; - eSleepModeStatus eReturn = eStandardSleep; - - if( listCURRENT_LIST_LENGTH( &xPendingReadyList ) != 0 ) - { - /* A task was made ready while the scheduler was suspended. */ - eReturn = eAbortSleep; - } - else if( xYieldPending != pdFALSE ) - { - /* A yield was pended while the scheduler was suspended. */ - eReturn = eAbortSleep; - } - else - { - /* If all the tasks are in the suspended list (which might mean they - have an infinite block time rather than actually being suspended) - then it is safe to turn all clocks off and just wait for external - interrupts. */ - if( listCURRENT_LIST_LENGTH( &xSuspendedTaskList ) == ( uxCurrentNumberOfTasks - uxNonApplicationTasks ) ) - { - eReturn = eNoTasksWaitingTimeout; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - - return eReturn; - } - -#endif /* configUSE_TICKLESS_IDLE */ -/*-----------------------------------------------------------*/ - -#if ( configNUM_THREAD_LOCAL_STORAGE_POINTERS != 0 ) - - void vTaskSetThreadLocalStoragePointer( TaskHandle_t xTaskToSet, BaseType_t xIndex, void *pvValue ) - { - TCB_t *pxTCB; - - if( xIndex < configNUM_THREAD_LOCAL_STORAGE_POINTERS ) - { - pxTCB = prvGetTCBFromHandle( xTaskToSet ); - pxTCB->pvThreadLocalStoragePointers[ xIndex ] = pvValue; - } - } - -#endif /* configNUM_THREAD_LOCAL_STORAGE_POINTERS */ -/*-----------------------------------------------------------*/ - -#if ( configNUM_THREAD_LOCAL_STORAGE_POINTERS != 0 ) - - void *pvTaskGetThreadLocalStoragePointer( TaskHandle_t xTaskToQuery, BaseType_t xIndex ) - { - void *pvReturn = NULL; - TCB_t *pxTCB; - - if( xIndex < configNUM_THREAD_LOCAL_STORAGE_POINTERS ) - { - pxTCB = prvGetTCBFromHandle( xTaskToQuery ); - pvReturn = pxTCB->pvThreadLocalStoragePointers[ xIndex ]; - } - else - { - pvReturn = NULL; - } - - return pvReturn; - } - -#endif /* configNUM_THREAD_LOCAL_STORAGE_POINTERS */ -/*-----------------------------------------------------------*/ - -#if ( portUSING_MPU_WRAPPERS == 1 ) - - void vTaskAllocateMPURegions( TaskHandle_t xTaskToModify, const MemoryRegion_t * const xRegions ) - { - TCB_t *pxTCB; - - /* If null is passed in here then we are modifying the MPU settings of - the calling task. */ - pxTCB = prvGetTCBFromHandle( xTaskToModify ); - - vPortStoreTaskMPUSettings( &( pxTCB->xMPUSettings ), xRegions, NULL, 0 ); - } - -#endif /* portUSING_MPU_WRAPPERS */ -/*-----------------------------------------------------------*/ - -static void prvInitialiseTaskLists( void ) -{ -UBaseType_t uxPriority; - - for( uxPriority = ( UBaseType_t ) 0U; uxPriority < ( UBaseType_t ) configMAX_PRIORITIES; uxPriority++ ) - { - vListInitialise( &( pxReadyTasksLists[ uxPriority ] ) ); - } - - vListInitialise( &xDelayedTaskList1 ); - vListInitialise( &xDelayedTaskList2 ); - vListInitialise( &xPendingReadyList ); - - #if ( INCLUDE_vTaskDelete == 1 ) - { - vListInitialise( &xTasksWaitingTermination ); - } - #endif /* INCLUDE_vTaskDelete */ - - #if ( INCLUDE_vTaskSuspend == 1 ) - { - vListInitialise( &xSuspendedTaskList ); - } - #endif /* INCLUDE_vTaskSuspend */ - - /* Start with pxDelayedTaskList using list1 and the pxOverflowDelayedTaskList - using list2. */ - pxDelayedTaskList = &xDelayedTaskList1; - pxOverflowDelayedTaskList = &xDelayedTaskList2; -} -/*-----------------------------------------------------------*/ - -static void prvCheckTasksWaitingTermination( void ) -{ - - /** THIS FUNCTION IS CALLED FROM THE RTOS IDLE TASK **/ - - #if ( INCLUDE_vTaskDelete == 1 ) - { - TCB_t *pxTCB; - - /* uxDeletedTasksWaitingCleanUp is used to prevent vTaskSuspendAll() - being called too often in the idle task. */ - while( uxDeletedTasksWaitingCleanUp > ( UBaseType_t ) 0U ) - { - taskENTER_CRITICAL(); - { - pxTCB = ( TCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( ( &xTasksWaitingTermination ) ); - ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); - --uxCurrentNumberOfTasks; - --uxDeletedTasksWaitingCleanUp; - } - taskEXIT_CRITICAL(); - - prvDeleteTCB( pxTCB ); - } - } - #endif /* INCLUDE_vTaskDelete */ -} -/*-----------------------------------------------------------*/ - -#if( configUSE_TRACE_FACILITY == 1 ) - - void vTaskGetInfo( TaskHandle_t xTask, TaskStatus_t *pxTaskStatus, BaseType_t xGetFreeStackSpace, eTaskState eState ) - { - TCB_t *pxTCB; - - /* xTask is NULL then get the state of the calling task. */ - pxTCB = prvGetTCBFromHandle( xTask ); - - pxTaskStatus->xHandle = ( TaskHandle_t ) pxTCB; - pxTaskStatus->pcTaskName = ( const char * ) &( pxTCB->pcTaskName [ 0 ] ); - pxTaskStatus->uxCurrentPriority = pxTCB->uxPriority; - pxTaskStatus->pxStackBase = pxTCB->pxStack; - pxTaskStatus->xTaskNumber = pxTCB->uxTCBNumber; - - #if ( configUSE_MUTEXES == 1 ) - { - pxTaskStatus->uxBasePriority = pxTCB->uxBasePriority; - } - #else - { - pxTaskStatus->uxBasePriority = 0; - } - #endif - - #if ( configGENERATE_RUN_TIME_STATS == 1 ) - { - pxTaskStatus->ulRunTimeCounter = pxTCB->ulRunTimeCounter; - } - #else - { - pxTaskStatus->ulRunTimeCounter = 0; - } - #endif - - /* Obtaining the task state is a little fiddly, so is only done if the - value of eState passed into this function is eInvalid - otherwise the - state is just set to whatever is passed in. */ - if( eState != eInvalid ) - { - if( pxTCB == pxCurrentTCB ) - { - pxTaskStatus->eCurrentState = eRunning; - } - else - { - pxTaskStatus->eCurrentState = eState; - - #if ( INCLUDE_vTaskSuspend == 1 ) - { - /* If the task is in the suspended list then there is a - chance it is actually just blocked indefinitely - so really - it should be reported as being in the Blocked state. */ - if( eState == eSuspended ) - { - vTaskSuspendAll(); - { - if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) - { - pxTaskStatus->eCurrentState = eBlocked; - } - } - ( void ) xTaskResumeAll(); - } - } - #endif /* INCLUDE_vTaskSuspend */ - } - } - else - { - pxTaskStatus->eCurrentState = eTaskGetState( pxTCB ); - } - - /* Obtaining the stack space takes some time, so the xGetFreeStackSpace - parameter is provided to allow it to be skipped. */ - if( xGetFreeStackSpace != pdFALSE ) - { - #if ( portSTACK_GROWTH > 0 ) - { - pxTaskStatus->usStackHighWaterMark = prvTaskCheckFreeStackSpace( ( uint8_t * ) pxTCB->pxEndOfStack ); - } - #else - { - pxTaskStatus->usStackHighWaterMark = prvTaskCheckFreeStackSpace( ( uint8_t * ) pxTCB->pxStack ); - } - #endif - } - else - { - pxTaskStatus->usStackHighWaterMark = 0; - } - } - -#endif /* configUSE_TRACE_FACILITY */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_TRACE_FACILITY == 1 ) - - static UBaseType_t prvListTasksWithinSingleList( TaskStatus_t *pxTaskStatusArray, List_t *pxList, eTaskState eState ) - { - configLIST_VOLATILE TCB_t *pxNextTCB, *pxFirstTCB; - UBaseType_t uxTask = 0; - - if( listCURRENT_LIST_LENGTH( pxList ) > ( UBaseType_t ) 0 ) - { - listGET_OWNER_OF_NEXT_ENTRY( pxFirstTCB, pxList ); - - /* Populate an TaskStatus_t structure within the - pxTaskStatusArray array for each task that is referenced from - pxList. See the definition of TaskStatus_t in task.h for the - meaning of each TaskStatus_t structure member. */ - do - { - listGET_OWNER_OF_NEXT_ENTRY( pxNextTCB, pxList ); - vTaskGetInfo( ( TaskHandle_t ) pxNextTCB, &( pxTaskStatusArray[ uxTask ] ), pdTRUE, eState ); - uxTask++; - } while( pxNextTCB != pxFirstTCB ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - return uxTask; - } - -#endif /* configUSE_TRACE_FACILITY */ -/*-----------------------------------------------------------*/ - -#if ( ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) ) - - static uint16_t prvTaskCheckFreeStackSpace( const uint8_t * pucStackByte ) - { - uint32_t ulCount = 0U; - - while( *pucStackByte == ( uint8_t ) tskSTACK_FILL_BYTE ) - { - pucStackByte -= portSTACK_GROWTH; - ulCount++; - } - - ulCount /= ( uint32_t ) sizeof( StackType_t ); /*lint !e961 Casting is not redundant on smaller architectures. */ - - return ( uint16_t ) ulCount; - } - -#endif /* ( ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) ) */ -/*-----------------------------------------------------------*/ - -#if ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) - - UBaseType_t uxTaskGetStackHighWaterMark( TaskHandle_t xTask ) - { - TCB_t *pxTCB; - uint8_t *pucEndOfStack; - UBaseType_t uxReturn; - - pxTCB = prvGetTCBFromHandle( xTask ); - - #if portSTACK_GROWTH < 0 - { - pucEndOfStack = ( uint8_t * ) pxTCB->pxStack; - } - #else - { - pucEndOfStack = ( uint8_t * ) pxTCB->pxEndOfStack; - } - #endif - - uxReturn = ( UBaseType_t ) prvTaskCheckFreeStackSpace( pucEndOfStack ); - - return uxReturn; - } - -#endif /* INCLUDE_uxTaskGetStackHighWaterMark */ -/*-----------------------------------------------------------*/ - -#if ( INCLUDE_vTaskDelete == 1 ) - - static void prvDeleteTCB( TCB_t *pxTCB ) - { - /* This call is required specifically for the TriCore port. It must be - above the vPortFree() calls. The call is also used by ports/demos that - want to allocate and clean RAM statically. */ - portCLEAN_UP_TCB( pxTCB ); - - /* Free up the memory allocated by the scheduler for the task. It is up - to the task to free any memory allocated at the application level. */ - #if ( configUSE_NEWLIB_REENTRANT == 1 ) - { - _reclaim_reent( &( pxTCB->xNewLib_reent ) ); - } - #endif /* configUSE_NEWLIB_REENTRANT */ - - #if( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 0 ) && ( portUSING_MPU_WRAPPERS == 0 ) ) - { - /* The task can only have been allocated dynamically - free both - the stack and TCB. */ - vPortFree( pxTCB->pxStack ); - vPortFree( pxTCB ); - } - #elif( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e731 Macro has been consolidated for readability reasons. */ - { - /* The task could have been allocated statically or dynamically, so - check what was statically allocated before trying to free the - memory. */ - if( pxTCB->ucStaticallyAllocated == tskDYNAMICALLY_ALLOCATED_STACK_AND_TCB ) - { - /* Both the stack and TCB were allocated dynamically, so both - must be freed. */ - vPortFree( pxTCB->pxStack ); - vPortFree( pxTCB ); - } - else if( pxTCB->ucStaticallyAllocated == tskSTATICALLY_ALLOCATED_STACK_ONLY ) - { - /* Only the stack was statically allocated, so the TCB is the - only memory that must be freed. */ - vPortFree( pxTCB ); - } - else - { - /* Neither the stack nor the TCB were allocated dynamically, so - nothing needs to be freed. */ - configASSERT( pxTCB->ucStaticallyAllocated == tskSTATICALLY_ALLOCATED_STACK_AND_TCB ); - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ - } - -#endif /* INCLUDE_vTaskDelete */ -/*-----------------------------------------------------------*/ - -static void prvResetNextTaskUnblockTime( void ) -{ -TCB_t *pxTCB; - - if( listLIST_IS_EMPTY( pxDelayedTaskList ) != pdFALSE ) - { - /* The new current delayed list is empty. Set xNextTaskUnblockTime to - the maximum possible value so it is extremely unlikely that the - if( xTickCount >= xNextTaskUnblockTime ) test will pass until - there is an item in the delayed list. */ - xNextTaskUnblockTime = portMAX_DELAY; - } - else - { - /* The new current delayed list is not empty, get the value of - the item at the head of the delayed list. This is the time at - which the task at the head of the delayed list should be removed - from the Blocked state. */ - ( pxTCB ) = ( TCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxDelayedTaskList ); - xNextTaskUnblockTime = listGET_LIST_ITEM_VALUE( &( ( pxTCB )->xStateListItem ) ); - } -} -/*-----------------------------------------------------------*/ - -#if ( ( INCLUDE_xTaskGetCurrentTaskHandle == 1 ) || ( configUSE_MUTEXES == 1 ) ) - - TaskHandle_t xTaskGetCurrentTaskHandle( void ) - { - TaskHandle_t xReturn; - - /* A critical section is not required as this is not called from - an interrupt and the current TCB will always be the same for any - individual execution thread. */ - xReturn = pxCurrentTCB; - - return xReturn; - } - -#endif /* ( ( INCLUDE_xTaskGetCurrentTaskHandle == 1 ) || ( configUSE_MUTEXES == 1 ) ) */ -/*-----------------------------------------------------------*/ - -#if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) - - BaseType_t xTaskGetSchedulerState( void ) - { - BaseType_t xReturn; - - if( xSchedulerRunning == pdFALSE ) - { - xReturn = taskSCHEDULER_NOT_STARTED; - } - else - { - if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) - { - xReturn = taskSCHEDULER_RUNNING; - } - else - { - xReturn = taskSCHEDULER_SUSPENDED; - } - } - - return xReturn; - } - -#endif /* ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_MUTEXES == 1 ) - - BaseType_t xTaskPriorityInherit( TaskHandle_t const pxMutexHolder ) - { - TCB_t * const pxMutexHolderTCB = ( TCB_t * ) pxMutexHolder; - BaseType_t xReturn = pdFALSE; - - /* If the mutex was given back by an interrupt while the queue was - locked then the mutex holder might now be NULL. _RB_ Is this still - needed as interrupts can no longer use mutexes? */ - if( pxMutexHolder != NULL ) - { - /* If the holder of the mutex has a priority below the priority of - the task attempting to obtain the mutex then it will temporarily - inherit the priority of the task attempting to obtain the mutex. */ - if( pxMutexHolderTCB->uxPriority < pxCurrentTCB->uxPriority ) - { - /* Adjust the mutex holder state to account for its new - priority. Only reset the event list item value if the value is - not being used for anything else. */ - if( ( listGET_LIST_ITEM_VALUE( &( pxMutexHolderTCB->xEventListItem ) ) & taskEVENT_LIST_ITEM_VALUE_IN_USE ) == 0UL ) - { - listSET_LIST_ITEM_VALUE( &( pxMutexHolderTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) pxCurrentTCB->uxPriority ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - /* If the task being modified is in the ready state it will need - to be moved into a new list. */ - if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ pxMutexHolderTCB->uxPriority ] ), &( pxMutexHolderTCB->xStateListItem ) ) != pdFALSE ) - { - if( uxListRemove( &( pxMutexHolderTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) - { - taskRESET_READY_PRIORITY( pxMutexHolderTCB->uxPriority ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - /* Inherit the priority before being moved into the new list. */ - pxMutexHolderTCB->uxPriority = pxCurrentTCB->uxPriority; - prvAddTaskToReadyList( pxMutexHolderTCB ); - } - else - { - /* Just inherit the priority. */ - pxMutexHolderTCB->uxPriority = pxCurrentTCB->uxPriority; - } - - traceTASK_PRIORITY_INHERIT( pxMutexHolderTCB, pxCurrentTCB->uxPriority ); - - /* Inheritance occurred. */ - xReturn = pdTRUE; - } - else - { - if( pxMutexHolderTCB->uxBasePriority < pxCurrentTCB->uxPriority ) - { - /* The base priority of the mutex holder is lower than the - priority of the task attempting to take the mutex, but the - current priority of the mutex holder is not lower than the - priority of the task attempting to take the mutex. - Therefore the mutex holder must have already inherited a - priority, but inheritance would have occurred if that had - not been the case. */ - xReturn = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - return xReturn; - } - -#endif /* configUSE_MUTEXES */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_MUTEXES == 1 ) - - BaseType_t xTaskPriorityDisinherit( TaskHandle_t const pxMutexHolder ) - { - TCB_t * const pxTCB = ( TCB_t * ) pxMutexHolder; - BaseType_t xReturn = pdFALSE; - - if( pxMutexHolder != NULL ) - { - /* A task can only have an inherited priority if it holds the mutex. - If the mutex is held by a task then it cannot be given from an - interrupt, and if a mutex is given by the holding task then it must - be the running state task. */ - configASSERT( pxTCB == pxCurrentTCB ); - configASSERT( pxTCB->uxMutexesHeld ); - ( pxTCB->uxMutexesHeld )--; - - /* Has the holder of the mutex inherited the priority of another - task? */ - if( pxTCB->uxPriority != pxTCB->uxBasePriority ) - { - /* Only disinherit if no other mutexes are held. */ - if( pxTCB->uxMutexesHeld == ( UBaseType_t ) 0 ) - { - /* A task can only have an inherited priority if it holds - the mutex. If the mutex is held by a task then it cannot be - given from an interrupt, and if a mutex is given by the - holding task then it must be the running state task. Remove - the holding task from the ready list. */ - if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) - { - taskRESET_READY_PRIORITY( pxTCB->uxPriority ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - /* Disinherit the priority before adding the task into the - new ready list. */ - traceTASK_PRIORITY_DISINHERIT( pxTCB, pxTCB->uxBasePriority ); - pxTCB->uxPriority = pxTCB->uxBasePriority; - - /* Reset the event list item value. It cannot be in use for - any other purpose if this task is running, and it must be - running to give back the mutex. */ - listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) pxTCB->uxPriority ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - prvAddTaskToReadyList( pxTCB ); - - /* Return true to indicate that a context switch is required. - This is only actually required in the corner case whereby - multiple mutexes were held and the mutexes were given back - in an order different to that in which they were taken. - If a context switch did not occur when the first mutex was - returned, even if a task was waiting on it, then a context - switch should occur when the last mutex is returned whether - a task is waiting on it or not. */ - xReturn = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - return xReturn; - } - -#endif /* configUSE_MUTEXES */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_MUTEXES == 1 ) - - void vTaskPriorityDisinheritAfterTimeout( TaskHandle_t const pxMutexHolder, UBaseType_t uxHighestPriorityWaitingTask ) - { - TCB_t * const pxTCB = ( TCB_t * ) pxMutexHolder; - UBaseType_t uxPriorityUsedOnEntry, uxPriorityToUse; - const UBaseType_t uxOnlyOneMutexHeld = ( UBaseType_t ) 1; - - if( pxMutexHolder != NULL ) - { - /* If pxMutexHolder is not NULL then the holder must hold at least - one mutex. */ - configASSERT( pxTCB->uxMutexesHeld ); - - /* Determine the priority to which the priority of the task that - holds the mutex should be set. This will be the greater of the - holding task's base priority and the priority of the highest - priority task that is waiting to obtain the mutex. */ - if( pxTCB->uxBasePriority < uxHighestPriorityWaitingTask ) - { - uxPriorityToUse = uxHighestPriorityWaitingTask; - } - else - { - uxPriorityToUse = pxTCB->uxBasePriority; - } - - /* Does the priority need to change? */ - if( pxTCB->uxPriority != uxPriorityToUse ) - { - /* Only disinherit if no other mutexes are held. This is a - simplification in the priority inheritance implementation. If - the task that holds the mutex is also holding other mutexes then - the other mutexes may have caused the priority inheritance. */ - if( pxTCB->uxMutexesHeld == uxOnlyOneMutexHeld ) - { - /* If a task has timed out because it already holds the - mutex it was trying to obtain then it cannot of inherited - its own priority. */ - configASSERT( pxTCB != pxCurrentTCB ); - - /* Disinherit the priority, remembering the previous - priority to facilitate determining the subject task's - state. */ - traceTASK_PRIORITY_DISINHERIT( pxTCB, pxTCB->uxBasePriority ); - uxPriorityUsedOnEntry = pxTCB->uxPriority; - pxTCB->uxPriority = uxPriorityToUse; - - /* Only reset the event list item value if the value is not - being used for anything else. */ - if( ( listGET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ) ) & taskEVENT_LIST_ITEM_VALUE_IN_USE ) == 0UL ) - { - listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) uxPriorityToUse ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - /* If the running task is not the task that holds the mutex - then the task that holds the mutex could be in either the - Ready, Blocked or Suspended states. Only remove the task - from its current state list if it is in the Ready state as - the task's priority is going to change and there is one - Ready list per priority. */ - if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ uxPriorityUsedOnEntry ] ), &( pxTCB->xStateListItem ) ) != pdFALSE ) - { - if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) - { - taskRESET_READY_PRIORITY( pxTCB->uxPriority ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - prvAddTaskToReadyList( pxTCB ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - -#endif /* configUSE_MUTEXES */ -/*-----------------------------------------------------------*/ - -#if ( portCRITICAL_NESTING_IN_TCB == 1 ) - - void vTaskEnterCritical( void ) - { - portDISABLE_INTERRUPTS(); - - if( xSchedulerRunning != pdFALSE ) - { - ( pxCurrentTCB->uxCriticalNesting )++; - - /* This is not the interrupt safe version of the enter critical - function so assert() if it is being called from an interrupt - context. Only API functions that end in "FromISR" can be used in an - interrupt. Only assert if the critical nesting count is 1 to - protect against recursive calls if the assert function also uses a - critical section. */ - if( pxCurrentTCB->uxCriticalNesting == 1 ) - { - portASSERT_IF_IN_ISR(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - -#endif /* portCRITICAL_NESTING_IN_TCB */ -/*-----------------------------------------------------------*/ - -#if ( portCRITICAL_NESTING_IN_TCB == 1 ) - - void vTaskExitCritical( void ) - { - if( xSchedulerRunning != pdFALSE ) - { - if( pxCurrentTCB->uxCriticalNesting > 0U ) - { - ( pxCurrentTCB->uxCriticalNesting )--; - - if( pxCurrentTCB->uxCriticalNesting == 0U ) - { - portENABLE_INTERRUPTS(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - -#endif /* portCRITICAL_NESTING_IN_TCB */ -/*-----------------------------------------------------------*/ - -#if ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) ) - - static char *prvWriteNameToBuffer( char *pcBuffer, const char *pcTaskName ) - { - size_t x; - - /* Start by copying the entire string. */ - strcpy( pcBuffer, pcTaskName ); - - /* Pad the end of the string with spaces to ensure columns line up when - printed out. */ - for( x = strlen( pcBuffer ); x < ( size_t ) ( configMAX_TASK_NAME_LEN - 1 ); x++ ) - { - pcBuffer[ x ] = ' '; - } - - /* Terminate. */ - pcBuffer[ x ] = 0x00; - - /* Return the new end of string. */ - return &( pcBuffer[ x ] ); - } - -#endif /* ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) */ -/*-----------------------------------------------------------*/ - -#if ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) - - void vTaskList( char * pcWriteBuffer ) - { - TaskStatus_t *pxTaskStatusArray; - volatile UBaseType_t uxArraySize, x; - char cStatus; - - /* - * PLEASE NOTE: - * - * This function is provided for convenience only, and is used by many - * of the demo applications. Do not consider it to be part of the - * scheduler. - * - * vTaskList() calls uxTaskGetSystemState(), then formats part of the - * uxTaskGetSystemState() output into a human readable table that - * displays task names, states and stack usage. - * - * vTaskList() has a dependency on the sprintf() C library function that - * might bloat the code size, use a lot of stack, and provide different - * results on different platforms. An alternative, tiny, third party, - * and limited functionality implementation of sprintf() is provided in - * many of the FreeRTOS/Demo sub-directories in a file called - * printf-stdarg.c (note printf-stdarg.c does not provide a full - * snprintf() implementation!). - * - * It is recommended that production systems call uxTaskGetSystemState() - * directly to get access to raw stats data, rather than indirectly - * through a call to vTaskList(). - */ - - - /* Make sure the write buffer does not contain a string. */ - *pcWriteBuffer = 0x00; - - /* Take a snapshot of the number of tasks in case it changes while this - function is executing. */ - uxArraySize = uxCurrentNumberOfTasks; - - /* Allocate an array index for each task. NOTE! if - configSUPPORT_DYNAMIC_ALLOCATION is set to 0 then pvPortMalloc() will - equate to NULL. */ - pxTaskStatusArray = pvPortMalloc( uxCurrentNumberOfTasks * sizeof( TaskStatus_t ) ); - - if( pxTaskStatusArray != NULL ) - { - /* Generate the (binary) data. */ - uxArraySize = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, NULL ); - - /* Create a human readable table from the binary data. */ - for( x = 0; x < uxArraySize; x++ ) - { - switch( pxTaskStatusArray[ x ].eCurrentState ) - { - case eRunning: cStatus = tskRUNNING_CHAR; - break; - - case eReady: cStatus = tskREADY_CHAR; - break; - - case eBlocked: cStatus = tskBLOCKED_CHAR; - break; - - case eSuspended: cStatus = tskSUSPENDED_CHAR; - break; - - case eDeleted: cStatus = tskDELETED_CHAR; - break; - - default: /* Should not get here, but it is included - to prevent static checking errors. */ - cStatus = 0x00; - break; - } - - /* Write the task name to the string, padding with spaces so it - can be printed in tabular form more easily. */ - pcWriteBuffer = prvWriteNameToBuffer( pcWriteBuffer, pxTaskStatusArray[ x ].pcTaskName ); - - /* Write the rest of the string. */ - sprintf( pcWriteBuffer, "\t%c\t%u\t%u\t%u\r\n", cStatus, ( unsigned int ) pxTaskStatusArray[ x ].uxCurrentPriority, ( unsigned int ) pxTaskStatusArray[ x ].usStackHighWaterMark, ( unsigned int ) pxTaskStatusArray[ x ].xTaskNumber ); - pcWriteBuffer += strlen( pcWriteBuffer ); - } - - /* Free the array again. NOTE! If configSUPPORT_DYNAMIC_ALLOCATION - is 0 then vPortFree() will be #defined to nothing. */ - vPortFree( pxTaskStatusArray ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - -#endif /* ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) */ -/*----------------------------------------------------------*/ - -#if ( ( configGENERATE_RUN_TIME_STATS == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) - - void vTaskGetRunTimeStats( char *pcWriteBuffer ) - { - TaskStatus_t *pxTaskStatusArray; - volatile UBaseType_t uxArraySize, x; - uint32_t ulTotalTime, ulStatsAsPercentage; - - #if( configUSE_TRACE_FACILITY != 1 ) - { - #error configUSE_TRACE_FACILITY must also be set to 1 in FreeRTOSConfig.h to use vTaskGetRunTimeStats(). - } - #endif - - /* - * PLEASE NOTE: - * - * This function is provided for convenience only, and is used by many - * of the demo applications. Do not consider it to be part of the - * scheduler. - * - * vTaskGetRunTimeStats() calls uxTaskGetSystemState(), then formats part - * of the uxTaskGetSystemState() output into a human readable table that - * displays the amount of time each task has spent in the Running state - * in both absolute and percentage terms. - * - * vTaskGetRunTimeStats() has a dependency on the sprintf() C library - * function that might bloat the code size, use a lot of stack, and - * provide different results on different platforms. An alternative, - * tiny, third party, and limited functionality implementation of - * sprintf() is provided in many of the FreeRTOS/Demo sub-directories in - * a file called printf-stdarg.c (note printf-stdarg.c does not provide - * a full snprintf() implementation!). - * - * It is recommended that production systems call uxTaskGetSystemState() - * directly to get access to raw stats data, rather than indirectly - * through a call to vTaskGetRunTimeStats(). - */ - - /* Make sure the write buffer does not contain a string. */ - *pcWriteBuffer = 0x00; - - /* Take a snapshot of the number of tasks in case it changes while this - function is executing. */ - uxArraySize = uxCurrentNumberOfTasks; - - /* Allocate an array index for each task. NOTE! If - configSUPPORT_DYNAMIC_ALLOCATION is set to 0 then pvPortMalloc() will - equate to NULL. */ - pxTaskStatusArray = pvPortMalloc( uxCurrentNumberOfTasks * sizeof( TaskStatus_t ) ); - - if( pxTaskStatusArray != NULL ) - { - /* Generate the (binary) data. */ - uxArraySize = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, &ulTotalTime ); - - /* For percentage calculations. */ - ulTotalTime /= 100UL; - - /* Avoid divide by zero errors. */ - if( ulTotalTime > 0 ) - { - /* Create a human readable table from the binary data. */ - for( x = 0; x < uxArraySize; x++ ) - { - /* What percentage of the total run time has the task used? - This will always be rounded down to the nearest integer. - ulTotalRunTimeDiv100 has already been divided by 100. */ - ulStatsAsPercentage = pxTaskStatusArray[ x ].ulRunTimeCounter / ulTotalTime; - - /* Write the task name to the string, padding with - spaces so it can be printed in tabular form more - easily. */ - pcWriteBuffer = prvWriteNameToBuffer( pcWriteBuffer, pxTaskStatusArray[ x ].pcTaskName ); - - if( ulStatsAsPercentage > 0UL ) - { - #ifdef portLU_PRINTF_SPECIFIER_REQUIRED - { - sprintf( pcWriteBuffer, "\t%lu\t\t%lu%%\r\n", pxTaskStatusArray[ x ].ulRunTimeCounter, ulStatsAsPercentage ); - } - #else - { - /* sizeof( int ) == sizeof( long ) so a smaller - printf() library can be used. */ - sprintf( pcWriteBuffer, "\t%u\t\t%u%%\r\n", ( unsigned int ) pxTaskStatusArray[ x ].ulRunTimeCounter, ( unsigned int ) ulStatsAsPercentage ); - } - #endif - } - else - { - /* If the percentage is zero here then the task has - consumed less than 1% of the total run time. */ - #ifdef portLU_PRINTF_SPECIFIER_REQUIRED - { - sprintf( pcWriteBuffer, "\t%lu\t\t<1%%\r\n", pxTaskStatusArray[ x ].ulRunTimeCounter ); - } - #else - { - /* sizeof( int ) == sizeof( long ) so a smaller - printf() library can be used. */ - sprintf( pcWriteBuffer, "\t%u\t\t<1%%\r\n", ( unsigned int ) pxTaskStatusArray[ x ].ulRunTimeCounter ); - } - #endif - } - - pcWriteBuffer += strlen( pcWriteBuffer ); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - /* Free the array again. NOTE! If configSUPPORT_DYNAMIC_ALLOCATION - is 0 then vPortFree() will be #defined to nothing. */ - vPortFree( pxTaskStatusArray ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - -#endif /* ( ( configGENERATE_RUN_TIME_STATS == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) */ -/*-----------------------------------------------------------*/ - -TickType_t uxTaskResetEventItemValue( void ) -{ -TickType_t uxReturn; - - uxReturn = listGET_LIST_ITEM_VALUE( &( pxCurrentTCB->xEventListItem ) ); - - /* Reset the event list item to its normal value - so it can be used with - queues and semaphores. */ - listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xEventListItem ), ( ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) pxCurrentTCB->uxPriority ) ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - - return uxReturn; -} -/*-----------------------------------------------------------*/ - -#if ( configUSE_MUTEXES == 1 ) - - void *pvTaskIncrementMutexHeldCount( void ) - { - /* If xSemaphoreCreateMutex() is called before any tasks have been created - then pxCurrentTCB will be NULL. */ - if( pxCurrentTCB != NULL ) - { - ( pxCurrentTCB->uxMutexesHeld )++; - } - - return pxCurrentTCB; - } - -#endif /* configUSE_MUTEXES */ -/*-----------------------------------------------------------*/ - -#if( configUSE_TASK_NOTIFICATIONS == 1 ) - - uint32_t ulTaskNotifyTake( BaseType_t xClearCountOnExit, TickType_t xTicksToWait ) - { - uint32_t ulReturn; - - taskENTER_CRITICAL(); - { - /* Only block if the notification count is not already non-zero. */ - if( pxCurrentTCB->ulNotifiedValue == 0UL ) - { - /* Mark this task as waiting for a notification. */ - pxCurrentTCB->ucNotifyState = taskWAITING_NOTIFICATION; - - if( xTicksToWait > ( TickType_t ) 0 ) - { - prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE ); - traceTASK_NOTIFY_TAKE_BLOCK(); - - /* All ports are written to allow a yield in a critical - section (some will yield immediately, others wait until the - critical section exits) - but it is not something that - application code should ever do. */ - portYIELD_WITHIN_API(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - taskEXIT_CRITICAL(); - - taskENTER_CRITICAL(); - { - traceTASK_NOTIFY_TAKE(); - ulReturn = pxCurrentTCB->ulNotifiedValue; - - if( ulReturn != 0UL ) - { - if( xClearCountOnExit != pdFALSE ) - { - pxCurrentTCB->ulNotifiedValue = 0UL; - } - else - { - pxCurrentTCB->ulNotifiedValue = ulReturn - ( uint32_t ) 1; - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - pxCurrentTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION; - } - taskEXIT_CRITICAL(); - - return ulReturn; - } - -#endif /* configUSE_TASK_NOTIFICATIONS */ -/*-----------------------------------------------------------*/ - -#if( configUSE_TASK_NOTIFICATIONS == 1 ) - - BaseType_t xTaskNotifyWait( uint32_t ulBitsToClearOnEntry, uint32_t ulBitsToClearOnExit, uint32_t *pulNotificationValue, TickType_t xTicksToWait ) - { - BaseType_t xReturn; - - taskENTER_CRITICAL(); - { - /* Only block if a notification is not already pending. */ - if( pxCurrentTCB->ucNotifyState != taskNOTIFICATION_RECEIVED ) - { - /* Clear bits in the task's notification value as bits may get - set by the notifying task or interrupt. This can be used to - clear the value to zero. */ - pxCurrentTCB->ulNotifiedValue &= ~ulBitsToClearOnEntry; - - /* Mark this task as waiting for a notification. */ - pxCurrentTCB->ucNotifyState = taskWAITING_NOTIFICATION; - - if( xTicksToWait > ( TickType_t ) 0 ) - { - prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE ); - traceTASK_NOTIFY_WAIT_BLOCK(); - - /* All ports are written to allow a yield in a critical - section (some will yield immediately, others wait until the - critical section exits) - but it is not something that - application code should ever do. */ - portYIELD_WITHIN_API(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - taskEXIT_CRITICAL(); - - taskENTER_CRITICAL(); - { - traceTASK_NOTIFY_WAIT(); - - if( pulNotificationValue != NULL ) - { - /* Output the current notification value, which may or may not - have changed. */ - *pulNotificationValue = pxCurrentTCB->ulNotifiedValue; - } - - /* If ucNotifyValue is set then either the task never entered the - blocked state (because a notification was already pending) or the - task unblocked because of a notification. Otherwise the task - unblocked because of a timeout. */ - if( pxCurrentTCB->ucNotifyState != taskNOTIFICATION_RECEIVED ) - { - /* A notification was not received. */ - xReturn = pdFALSE; - } - else - { - /* A notification was already pending or a notification was - received while the task was waiting. */ - pxCurrentTCB->ulNotifiedValue &= ~ulBitsToClearOnExit; - xReturn = pdTRUE; - } - - pxCurrentTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION; - } - taskEXIT_CRITICAL(); - - return xReturn; - } - -#endif /* configUSE_TASK_NOTIFICATIONS */ -/*-----------------------------------------------------------*/ - -#if( configUSE_TASK_NOTIFICATIONS == 1 ) - - BaseType_t xTaskGenericNotify( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotificationValue ) - { - TCB_t * pxTCB; - BaseType_t xReturn = pdPASS; - uint8_t ucOriginalNotifyState; - - configASSERT( xTaskToNotify ); - pxTCB = ( TCB_t * ) xTaskToNotify; - - taskENTER_CRITICAL(); - { - if( pulPreviousNotificationValue != NULL ) - { - *pulPreviousNotificationValue = pxTCB->ulNotifiedValue; - } - - ucOriginalNotifyState = pxTCB->ucNotifyState; - - pxTCB->ucNotifyState = taskNOTIFICATION_RECEIVED; - - switch( eAction ) - { - case eSetBits : - pxTCB->ulNotifiedValue |= ulValue; - break; - - case eIncrement : - ( pxTCB->ulNotifiedValue )++; - break; - - case eSetValueWithOverwrite : - pxTCB->ulNotifiedValue = ulValue; - break; - - case eSetValueWithoutOverwrite : - if( ucOriginalNotifyState != taskNOTIFICATION_RECEIVED ) - { - pxTCB->ulNotifiedValue = ulValue; - } - else - { - /* The value could not be written to the task. */ - xReturn = pdFAIL; - } - break; - - case eNoAction: - /* The task is being notified without its notify value being - updated. */ - break; - } - - traceTASK_NOTIFY(); - - /* If the task is in the blocked state specifically to wait for a - notification then unblock it now. */ - if( ucOriginalNotifyState == taskWAITING_NOTIFICATION ) - { - ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); - prvAddTaskToReadyList( pxTCB ); - - /* The task should not have been on an event list. */ - configASSERT( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL ); - - #if( configUSE_TICKLESS_IDLE != 0 ) - { - /* If a task is blocked waiting for a notification then - xNextTaskUnblockTime might be set to the blocked task's time - out time. If the task is unblocked for a reason other than - a timeout xNextTaskUnblockTime is normally left unchanged, - because it will automatically get reset to a new value when - the tick count equals xNextTaskUnblockTime. However if - tickless idling is used it might be more important to enter - sleep mode at the earliest possible time - so reset - xNextTaskUnblockTime here to ensure it is updated at the - earliest possible time. */ - prvResetNextTaskUnblockTime(); - } - #endif - - if( pxTCB->uxPriority > pxCurrentTCB->uxPriority ) - { - /* The notified task has a priority above the currently - executing task so a yield is required. */ - taskYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - taskEXIT_CRITICAL(); - - return xReturn; - } - -#endif /* configUSE_TASK_NOTIFICATIONS */ -/*-----------------------------------------------------------*/ - -#if( configUSE_TASK_NOTIFICATIONS == 1 ) - - BaseType_t xTaskGenericNotifyFromISR( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotificationValue, BaseType_t *pxHigherPriorityTaskWoken ) - { - TCB_t * pxTCB; - uint8_t ucOriginalNotifyState; - BaseType_t xReturn = pdPASS; - UBaseType_t uxSavedInterruptStatus; - - configASSERT( xTaskToNotify ); - - /* RTOS ports that support interrupt nesting have the concept of a - maximum system call (or maximum API call) interrupt priority. - Interrupts that are above the maximum system call priority are keep - permanently enabled, even when the RTOS kernel is in a critical section, - but cannot make any calls to FreeRTOS API functions. If configASSERT() - is defined in FreeRTOSConfig.h then - portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion - failure if a FreeRTOS API function is called from an interrupt that has - been assigned a priority above the configured maximum system call - priority. Only FreeRTOS functions that end in FromISR can be called - from interrupts that have been assigned a priority at or (logically) - below the maximum system call interrupt priority. FreeRTOS maintains a - separate interrupt safe API to ensure interrupt entry is as fast and as - simple as possible. More information (albeit Cortex-M specific) is - provided on the following link: - http://www.freertos.org/RTOS-Cortex-M3-M4.html */ - portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); - - pxTCB = ( TCB_t * ) xTaskToNotify; - - uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); - { - if( pulPreviousNotificationValue != NULL ) - { - *pulPreviousNotificationValue = pxTCB->ulNotifiedValue; - } - - ucOriginalNotifyState = pxTCB->ucNotifyState; - pxTCB->ucNotifyState = taskNOTIFICATION_RECEIVED; - - switch( eAction ) - { - case eSetBits : - pxTCB->ulNotifiedValue |= ulValue; - break; - - case eIncrement : - ( pxTCB->ulNotifiedValue )++; - break; - - case eSetValueWithOverwrite : - pxTCB->ulNotifiedValue = ulValue; - break; - - case eSetValueWithoutOverwrite : - if( ucOriginalNotifyState != taskNOTIFICATION_RECEIVED ) - { - pxTCB->ulNotifiedValue = ulValue; - } - else - { - /* The value could not be written to the task. */ - xReturn = pdFAIL; - } - break; - - case eNoAction : - /* The task is being notified without its notify value being - updated. */ - break; - } - - traceTASK_NOTIFY_FROM_ISR(); - - /* If the task is in the blocked state specifically to wait for a - notification then unblock it now. */ - if( ucOriginalNotifyState == taskWAITING_NOTIFICATION ) - { - /* The task should not have been on an event list. */ - configASSERT( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL ); - - if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) - { - ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); - prvAddTaskToReadyList( pxTCB ); - } - else - { - /* The delayed and ready lists cannot be accessed, so hold - this task pending until the scheduler is resumed. */ - vListInsertEnd( &( xPendingReadyList ), &( pxTCB->xEventListItem ) ); - } - - if( pxTCB->uxPriority > pxCurrentTCB->uxPriority ) - { - /* The notified task has a priority above the currently - executing task so a yield is required. */ - if( pxHigherPriorityTaskWoken != NULL ) - { - *pxHigherPriorityTaskWoken = pdTRUE; - } - else - { - /* Mark that a yield is pending in case the user is not - using the "xHigherPriorityTaskWoken" parameter to an ISR - safe FreeRTOS function. */ - xYieldPending = pdTRUE; - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - - return xReturn; - } - -#endif /* configUSE_TASK_NOTIFICATIONS */ -/*-----------------------------------------------------------*/ - -#if( configUSE_TASK_NOTIFICATIONS == 1 ) - - void vTaskNotifyGiveFromISR( TaskHandle_t xTaskToNotify, BaseType_t *pxHigherPriorityTaskWoken ) - { - TCB_t * pxTCB; - uint8_t ucOriginalNotifyState; - UBaseType_t uxSavedInterruptStatus; - - configASSERT( xTaskToNotify ); - - /* RTOS ports that support interrupt nesting have the concept of a - maximum system call (or maximum API call) interrupt priority. - Interrupts that are above the maximum system call priority are keep - permanently enabled, even when the RTOS kernel is in a critical section, - but cannot make any calls to FreeRTOS API functions. If configASSERT() - is defined in FreeRTOSConfig.h then - portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion - failure if a FreeRTOS API function is called from an interrupt that has - been assigned a priority above the configured maximum system call - priority. Only FreeRTOS functions that end in FromISR can be called - from interrupts that have been assigned a priority at or (logically) - below the maximum system call interrupt priority. FreeRTOS maintains a - separate interrupt safe API to ensure interrupt entry is as fast and as - simple as possible. More information (albeit Cortex-M specific) is - provided on the following link: - http://www.freertos.org/RTOS-Cortex-M3-M4.html */ - portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); - - pxTCB = ( TCB_t * ) xTaskToNotify; - - uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); - { - ucOriginalNotifyState = pxTCB->ucNotifyState; - pxTCB->ucNotifyState = taskNOTIFICATION_RECEIVED; - - /* 'Giving' is equivalent to incrementing a count in a counting - semaphore. */ - ( pxTCB->ulNotifiedValue )++; - - traceTASK_NOTIFY_GIVE_FROM_ISR(); - - /* If the task is in the blocked state specifically to wait for a - notification then unblock it now. */ - if( ucOriginalNotifyState == taskWAITING_NOTIFICATION ) - { - /* The task should not have been on an event list. */ - configASSERT( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL ); - - if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) - { - ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); - prvAddTaskToReadyList( pxTCB ); - } - else - { - /* The delayed and ready lists cannot be accessed, so hold - this task pending until the scheduler is resumed. */ - vListInsertEnd( &( xPendingReadyList ), &( pxTCB->xEventListItem ) ); - } - - if( pxTCB->uxPriority > pxCurrentTCB->uxPriority ) - { - /* The notified task has a priority above the currently - executing task so a yield is required. */ - if( pxHigherPriorityTaskWoken != NULL ) - { - *pxHigherPriorityTaskWoken = pdTRUE; - } - else - { - /* Mark that a yield is pending in case the user is not - using the "xHigherPriorityTaskWoken" parameter in an ISR - safe FreeRTOS function. */ - xYieldPending = pdTRUE; - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - } - -#endif /* configUSE_TASK_NOTIFICATIONS */ - -/*-----------------------------------------------------------*/ - -#if( configUSE_TASK_NOTIFICATIONS == 1 ) - - BaseType_t xTaskNotifyStateClear( TaskHandle_t xTask ) - { - TCB_t *pxTCB; - BaseType_t xReturn; - - /* If null is passed in here then it is the calling task that is having - its notification state cleared. */ - pxTCB = prvGetTCBFromHandle( xTask ); - - taskENTER_CRITICAL(); - { - if( pxTCB->ucNotifyState == taskNOTIFICATION_RECEIVED ) - { - pxTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION; - xReturn = pdPASS; - } - else - { - xReturn = pdFAIL; - } - } - taskEXIT_CRITICAL(); - - return xReturn; - } - -#endif /* configUSE_TASK_NOTIFICATIONS */ -/*-----------------------------------------------------------*/ - - -static void prvAddCurrentTaskToDelayedList( TickType_t xTicksToWait, const BaseType_t xCanBlockIndefinitely ) -{ -TickType_t xTimeToWake; -const TickType_t xConstTickCount = xTickCount; - - #if( INCLUDE_xTaskAbortDelay == 1 ) - { - /* About to enter a delayed list, so ensure the ucDelayAborted flag is - reset to pdFALSE so it can be detected as having been set to pdTRUE - when the task leaves the Blocked state. */ - pxCurrentTCB->ucDelayAborted = pdFALSE; - } - #endif - - /* Remove the task from the ready list before adding it to the blocked list - as the same list item is used for both lists. */ - if( uxListRemove( &( pxCurrentTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) - { - /* The current task must be in a ready list, so there is no need to - check, and the port reset macro can be called directly. */ - portRESET_READY_PRIORITY( pxCurrentTCB->uxPriority, uxTopReadyPriority ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - #if ( INCLUDE_vTaskSuspend == 1 ) - { - if( ( xTicksToWait == portMAX_DELAY ) && ( xCanBlockIndefinitely != pdFALSE ) ) - { - /* Add the task to the suspended task list instead of a delayed task - list to ensure it is not woken by a timing event. It will block - indefinitely. */ - vListInsertEnd( &xSuspendedTaskList, &( pxCurrentTCB->xStateListItem ) ); - } - else - { - /* Calculate the time at which the task should be woken if the event - does not occur. This may overflow but this doesn't matter, the - kernel will manage it correctly. */ - xTimeToWake = xConstTickCount + xTicksToWait; - - /* The list item will be inserted in wake time order. */ - listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xStateListItem ), xTimeToWake ); - - if( xTimeToWake < xConstTickCount ) - { - /* Wake time has overflowed. Place this item in the overflow - list. */ - vListInsert( pxOverflowDelayedTaskList, &( pxCurrentTCB->xStateListItem ) ); - } - else - { - /* The wake time has not overflowed, so the current block list - is used. */ - vListInsert( pxDelayedTaskList, &( pxCurrentTCB->xStateListItem ) ); - - /* If the task entering the blocked state was placed at the - head of the list of blocked tasks then xNextTaskUnblockTime - needs to be updated too. */ - if( xTimeToWake < xNextTaskUnblockTime ) - { - xNextTaskUnblockTime = xTimeToWake; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } - } - #else /* INCLUDE_vTaskSuspend */ - { - /* Calculate the time at which the task should be woken if the event - does not occur. This may overflow but this doesn't matter, the kernel - will manage it correctly. */ - xTimeToWake = xConstTickCount + xTicksToWait; - - /* The list item will be inserted in wake time order. */ - listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xStateListItem ), xTimeToWake ); - - if( xTimeToWake < xConstTickCount ) - { - /* Wake time has overflowed. Place this item in the overflow list. */ - vListInsert( pxOverflowDelayedTaskList, &( pxCurrentTCB->xStateListItem ) ); - } - else - { - /* The wake time has not overflowed, so the current block list is used. */ - vListInsert( pxDelayedTaskList, &( pxCurrentTCB->xStateListItem ) ); - - /* If the task entering the blocked state was placed at the head of the - list of blocked tasks then xNextTaskUnblockTime needs to be updated - too. */ - if( xTimeToWake < xNextTaskUnblockTime ) - { - xNextTaskUnblockTime = xTimeToWake; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - - /* Avoid compiler warning when INCLUDE_vTaskSuspend is not 1. */ - ( void ) xCanBlockIndefinitely; - } - #endif /* INCLUDE_vTaskSuspend */ -} - -/* Code below here allows additional code to be inserted into this source file, -especially where access to file scope functions and data is needed (for example -when performing module tests). */ - -#ifdef FREERTOS_MODULE_TEST - #include "tasks_test_access_functions.h" -#endif - - -#if( configINCLUDE_FREERTOS_TASK_C_ADDITIONS_H == 1 ) - - #include "freertos_tasks_c_additions.h" - - static void freertos_tasks_c_additions_init( void ) - { - #ifdef FREERTOS_TASKS_C_ADDITIONS_INIT - FREERTOS_TASKS_C_ADDITIONS_INIT(); - #endif - } - -#endif - - diff --git a/lib/FreeRTOS/Source/timers.c b/lib/FreeRTOS/Source/timers.c deleted file mode 100644 index 29d8cb9f..00000000 --- a/lib/FreeRTOS/Source/timers.c +++ /dev/null @@ -1,1076 +0,0 @@ -/* - * FreeRTOS Kernel V10.0.1 - * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * 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. - * - * http://www.FreeRTOS.org - * http://aws.amazon.com/freertos - * - * 1 tab == 4 spaces! - */ - -/* Standard includes. */ -#include - -/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining -all the API functions to use the MPU wrappers. That should only be done when -task.h is included from an application file. */ -#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE - -#include "FreeRTOS.h" -#include "task.h" -#include "queue.h" -#include "timers.h" - -#if ( INCLUDE_xTimerPendFunctionCall == 1 ) && ( configUSE_TIMERS == 0 ) - #error configUSE_TIMERS must be set to 1 to make the xTimerPendFunctionCall() function available. -#endif - -/* Lint e961 and e750 are suppressed as a MISRA exception justified because the -MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be defined for the -header files above, but not in this file, in order to generate the correct -privileged Vs unprivileged linkage and placement. */ -#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /*lint !e961 !e750. */ - - -/* This entire source file will be skipped if the application is not configured -to include software timer functionality. This #if is closed at the very bottom -of this file. If you want to include software timer functionality then ensure -configUSE_TIMERS is set to 1 in FreeRTOSConfig.h. */ -#if ( configUSE_TIMERS == 1 ) - -/* Misc definitions. */ -#define tmrNO_DELAY ( TickType_t ) 0U - -/* The name assigned to the timer service task. This can be overridden by -defining trmTIMER_SERVICE_TASK_NAME in FreeRTOSConfig.h. */ -#ifndef configTIMER_SERVICE_TASK_NAME - #define configTIMER_SERVICE_TASK_NAME "Tmr Svc" -#endif - -/* The definition of the timers themselves. */ -typedef struct tmrTimerControl -{ - const char *pcTimerName; /*<< Text name. This is not used by the kernel, it is included simply to make debugging easier. */ /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - ListItem_t xTimerListItem; /*<< Standard linked list item as used by all kernel features for event management. */ - TickType_t xTimerPeriodInTicks;/*<< How quickly and often the timer expires. */ - UBaseType_t uxAutoReload; /*<< Set to pdTRUE if the timer should be automatically restarted once expired. Set to pdFALSE if the timer is, in effect, a one-shot timer. */ - void *pvTimerID; /*<< An ID to identify the timer. This allows the timer to be identified when the same callback is used for multiple timers. */ - TimerCallbackFunction_t pxCallbackFunction; /*<< The function that will be called when the timer expires. */ - #if( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxTimerNumber; /*<< An ID assigned by trace tools such as FreeRTOS+Trace */ - #endif - - #if( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) - uint8_t ucStaticallyAllocated; /*<< Set to pdTRUE if the timer was created statically so no attempt is made to free the memory again if the timer is later deleted. */ - #endif -} xTIMER; - -/* The old xTIMER name is maintained above then typedefed to the new Timer_t -name below to enable the use of older kernel aware debuggers. */ -typedef xTIMER Timer_t; - -/* The definition of messages that can be sent and received on the timer queue. -Two types of message can be queued - messages that manipulate a software timer, -and messages that request the execution of a non-timer related callback. The -two message types are defined in two separate structures, xTimerParametersType -and xCallbackParametersType respectively. */ -typedef struct tmrTimerParameters -{ - TickType_t xMessageValue; /*<< An optional value used by a subset of commands, for example, when changing the period of a timer. */ - Timer_t * pxTimer; /*<< The timer to which the command will be applied. */ -} TimerParameter_t; - - -typedef struct tmrCallbackParameters -{ - PendedFunction_t pxCallbackFunction; /* << The callback function to execute. */ - void *pvParameter1; /* << The value that will be used as the callback functions first parameter. */ - uint32_t ulParameter2; /* << The value that will be used as the callback functions second parameter. */ -} CallbackParameters_t; - -/* The structure that contains the two message types, along with an identifier -that is used to determine which message type is valid. */ -typedef struct tmrTimerQueueMessage -{ - BaseType_t xMessageID; /*<< The command being sent to the timer service task. */ - union - { - TimerParameter_t xTimerParameters; - - /* Don't include xCallbackParameters if it is not going to be used as - it makes the structure (and therefore the timer queue) larger. */ - #if ( INCLUDE_xTimerPendFunctionCall == 1 ) - CallbackParameters_t xCallbackParameters; - #endif /* INCLUDE_xTimerPendFunctionCall */ - } u; -} DaemonTaskMessage_t; - -/*lint -save -e956 A manual analysis and inspection has been used to determine -which static variables must be declared volatile. */ - -/* The list in which active timers are stored. Timers are referenced in expire -time order, with the nearest expiry time at the front of the list. Only the -timer service task is allowed to access these lists. */ -PRIVILEGED_DATA static List_t xActiveTimerList1; -PRIVILEGED_DATA static List_t xActiveTimerList2; -PRIVILEGED_DATA static List_t *pxCurrentTimerList; -PRIVILEGED_DATA static List_t *pxOverflowTimerList; - -/* A queue that is used to send commands to the timer service task. */ -PRIVILEGED_DATA static QueueHandle_t xTimerQueue = NULL; -PRIVILEGED_DATA static TaskHandle_t xTimerTaskHandle = NULL; - -/*lint -restore */ - -/*-----------------------------------------------------------*/ - -#if( configSUPPORT_STATIC_ALLOCATION == 1 ) - - /* If static allocation is supported then the application must provide the - following callback function - which enables the application to optionally - provide the memory that will be used by the timer task as the task's stack - and TCB. */ - extern void vApplicationGetTimerTaskMemory( StaticTask_t **ppxTimerTaskTCBBuffer, StackType_t **ppxTimerTaskStackBuffer, uint32_t *pulTimerTaskStackSize ); - -#endif - -/* - * Initialise the infrastructure used by the timer service task if it has not - * been initialised already. - */ -static void prvCheckForValidListAndQueue( void ) PRIVILEGED_FUNCTION; - -/* - * The timer service task (daemon). Timer functionality is controlled by this - * task. Other tasks communicate with the timer service task using the - * xTimerQueue queue. - */ -static void prvTimerTask( void *pvParameters ) PRIVILEGED_FUNCTION; - -/* - * Called by the timer service task to interpret and process a command it - * received on the timer queue. - */ -static void prvProcessReceivedCommands( void ) PRIVILEGED_FUNCTION; - -/* - * Insert the timer into either xActiveTimerList1, or xActiveTimerList2, - * depending on if the expire time causes a timer counter overflow. - */ -static BaseType_t prvInsertTimerInActiveList( Timer_t * const pxTimer, const TickType_t xNextExpiryTime, const TickType_t xTimeNow, const TickType_t xCommandTime ) PRIVILEGED_FUNCTION; - -/* - * An active timer has reached its expire time. Reload the timer if it is an - * auto reload timer, then call its callback. - */ -static void prvProcessExpiredTimer( const TickType_t xNextExpireTime, const TickType_t xTimeNow ) PRIVILEGED_FUNCTION; - -/* - * The tick count has overflowed. Switch the timer lists after ensuring the - * current timer list does not still reference some timers. - */ -static void prvSwitchTimerLists( void ) PRIVILEGED_FUNCTION; - -/* - * Obtain the current tick count, setting *pxTimerListsWereSwitched to pdTRUE - * if a tick count overflow occurred since prvSampleTimeNow() was last called. - */ -static TickType_t prvSampleTimeNow( BaseType_t * const pxTimerListsWereSwitched ) PRIVILEGED_FUNCTION; - -/* - * If the timer list contains any active timers then return the expire time of - * the timer that will expire first and set *pxListWasEmpty to false. If the - * timer list does not contain any timers then return 0 and set *pxListWasEmpty - * to pdTRUE. - */ -static TickType_t prvGetNextExpireTime( BaseType_t * const pxListWasEmpty ) PRIVILEGED_FUNCTION; - -/* - * If a timer has expired, process it. Otherwise, block the timer service task - * until either a timer does expire or a command is received. - */ -static void prvProcessTimerOrBlockTask( const TickType_t xNextExpireTime, BaseType_t xListWasEmpty ) PRIVILEGED_FUNCTION; - -/* - * Called after a Timer_t structure has been allocated either statically or - * dynamically to fill in the structure's members. - */ -static void prvInitialiseNewTimer( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - const TickType_t xTimerPeriodInTicks, - const UBaseType_t uxAutoReload, - void * const pvTimerID, - TimerCallbackFunction_t pxCallbackFunction, - Timer_t *pxNewTimer ) PRIVILEGED_FUNCTION; -/*-----------------------------------------------------------*/ - -BaseType_t xTimerCreateTimerTask( void ) -{ -BaseType_t xReturn = pdFAIL; - - /* This function is called when the scheduler is started if - configUSE_TIMERS is set to 1. Check that the infrastructure used by the - timer service task has been created/initialised. If timers have already - been created then the initialisation will already have been performed. */ - prvCheckForValidListAndQueue(); - - if( xTimerQueue != NULL ) - { - #if( configSUPPORT_STATIC_ALLOCATION == 1 ) - { - StaticTask_t *pxTimerTaskTCBBuffer = NULL; - StackType_t *pxTimerTaskStackBuffer = NULL; - uint32_t ulTimerTaskStackSize; - - vApplicationGetTimerTaskMemory( &pxTimerTaskTCBBuffer, &pxTimerTaskStackBuffer, &ulTimerTaskStackSize ); - xTimerTaskHandle = xTaskCreateStatic( prvTimerTask, - configTIMER_SERVICE_TASK_NAME, - ulTimerTaskStackSize, - NULL, - ( ( UBaseType_t ) configTIMER_TASK_PRIORITY ) | portPRIVILEGE_BIT, - pxTimerTaskStackBuffer, - pxTimerTaskTCBBuffer ); - - if( xTimerTaskHandle != NULL ) - { - xReturn = pdPASS; - } - } - #else - { - xReturn = xTaskCreate( prvTimerTask, - configTIMER_SERVICE_TASK_NAME, - configTIMER_TASK_STACK_DEPTH, - NULL, - ( ( UBaseType_t ) configTIMER_TASK_PRIORITY ) | portPRIVILEGE_BIT, - &xTimerTaskHandle ); - } - #endif /* configSUPPORT_STATIC_ALLOCATION */ - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - configASSERT( xReturn ); - return xReturn; -} -/*-----------------------------------------------------------*/ - -#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - - TimerHandle_t xTimerCreate( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - const TickType_t xTimerPeriodInTicks, - const UBaseType_t uxAutoReload, - void * const pvTimerID, - TimerCallbackFunction_t pxCallbackFunction ) - { - Timer_t *pxNewTimer; - - pxNewTimer = ( Timer_t * ) pvPortMalloc( sizeof( Timer_t ) ); - - if( pxNewTimer != NULL ) - { - prvInitialiseNewTimer( pcTimerName, xTimerPeriodInTicks, uxAutoReload, pvTimerID, pxCallbackFunction, pxNewTimer ); - - #if( configSUPPORT_STATIC_ALLOCATION == 1 ) - { - /* Timers can be created statically or dynamically, so note this - timer was created dynamically in case the timer is later - deleted. */ - pxNewTimer->ucStaticallyAllocated = pdFALSE; - } - #endif /* configSUPPORT_STATIC_ALLOCATION */ - } - - return pxNewTimer; - } - -#endif /* configSUPPORT_STATIC_ALLOCATION */ -/*-----------------------------------------------------------*/ - -#if( configSUPPORT_STATIC_ALLOCATION == 1 ) - - TimerHandle_t xTimerCreateStatic( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - const TickType_t xTimerPeriodInTicks, - const UBaseType_t uxAutoReload, - void * const pvTimerID, - TimerCallbackFunction_t pxCallbackFunction, - StaticTimer_t *pxTimerBuffer ) - { - Timer_t *pxNewTimer; - - #if( configASSERT_DEFINED == 1 ) - { - /* Sanity check that the size of the structure used to declare a - variable of type StaticTimer_t equals the size of the real timer - structure. */ - volatile size_t xSize = sizeof( StaticTimer_t ); - configASSERT( xSize == sizeof( Timer_t ) ); - } - #endif /* configASSERT_DEFINED */ - - /* A pointer to a StaticTimer_t structure MUST be provided, use it. */ - configASSERT( pxTimerBuffer ); - pxNewTimer = ( Timer_t * ) pxTimerBuffer; /*lint !e740 Unusual cast is ok as the structures are designed to have the same alignment, and the size is checked by an assert. */ - - if( pxNewTimer != NULL ) - { - prvInitialiseNewTimer( pcTimerName, xTimerPeriodInTicks, uxAutoReload, pvTimerID, pxCallbackFunction, pxNewTimer ); - - #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - { - /* Timers can be created statically or dynamically so note this - timer was created statically in case it is later deleted. */ - pxNewTimer->ucStaticallyAllocated = pdTRUE; - } - #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ - } - - return pxNewTimer; - } - -#endif /* configSUPPORT_STATIC_ALLOCATION */ -/*-----------------------------------------------------------*/ - -static void prvInitialiseNewTimer( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - const TickType_t xTimerPeriodInTicks, - const UBaseType_t uxAutoReload, - void * const pvTimerID, - TimerCallbackFunction_t pxCallbackFunction, - Timer_t *pxNewTimer ) -{ - /* 0 is not a valid value for xTimerPeriodInTicks. */ - configASSERT( ( xTimerPeriodInTicks > 0 ) ); - - if( pxNewTimer != NULL ) - { - /* Ensure the infrastructure used by the timer service task has been - created/initialised. */ - prvCheckForValidListAndQueue(); - - /* Initialise the timer structure members using the function - parameters. */ - pxNewTimer->pcTimerName = pcTimerName; - pxNewTimer->xTimerPeriodInTicks = xTimerPeriodInTicks; - pxNewTimer->uxAutoReload = uxAutoReload; - pxNewTimer->pvTimerID = pvTimerID; - pxNewTimer->pxCallbackFunction = pxCallbackFunction; - vListInitialiseItem( &( pxNewTimer->xTimerListItem ) ); - traceTIMER_CREATE( pxNewTimer ); - } -} -/*-----------------------------------------------------------*/ - -BaseType_t xTimerGenericCommand( TimerHandle_t xTimer, const BaseType_t xCommandID, const TickType_t xOptionalValue, BaseType_t * const pxHigherPriorityTaskWoken, const TickType_t xTicksToWait ) -{ -BaseType_t xReturn = pdFAIL; -DaemonTaskMessage_t xMessage; - - configASSERT( xTimer ); - - /* Send a message to the timer service task to perform a particular action - on a particular timer definition. */ - if( xTimerQueue != NULL ) - { - /* Send a command to the timer service task to start the xTimer timer. */ - xMessage.xMessageID = xCommandID; - xMessage.u.xTimerParameters.xMessageValue = xOptionalValue; - xMessage.u.xTimerParameters.pxTimer = ( Timer_t * ) xTimer; - - if( xCommandID < tmrFIRST_FROM_ISR_COMMAND ) - { - if( xTaskGetSchedulerState() == taskSCHEDULER_RUNNING ) - { - xReturn = xQueueSendToBack( xTimerQueue, &xMessage, xTicksToWait ); - } - else - { - xReturn = xQueueSendToBack( xTimerQueue, &xMessage, tmrNO_DELAY ); - } - } - else - { - xReturn = xQueueSendToBackFromISR( xTimerQueue, &xMessage, pxHigherPriorityTaskWoken ); - } - - traceTIMER_COMMAND_SEND( xTimer, xCommandID, xOptionalValue, xReturn ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - return xReturn; -} -/*-----------------------------------------------------------*/ - -TaskHandle_t xTimerGetTimerDaemonTaskHandle( void ) -{ - /* If xTimerGetTimerDaemonTaskHandle() is called before the scheduler has been - started, then xTimerTaskHandle will be NULL. */ - configASSERT( ( xTimerTaskHandle != NULL ) ); - return xTimerTaskHandle; -} -/*-----------------------------------------------------------*/ - -TickType_t xTimerGetPeriod( TimerHandle_t xTimer ) -{ -Timer_t *pxTimer = ( Timer_t * ) xTimer; - - configASSERT( xTimer ); - return pxTimer->xTimerPeriodInTicks; -} -/*-----------------------------------------------------------*/ - -TickType_t xTimerGetExpiryTime( TimerHandle_t xTimer ) -{ -Timer_t * pxTimer = ( Timer_t * ) xTimer; -TickType_t xReturn; - - configASSERT( xTimer ); - xReturn = listGET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ) ); - return xReturn; -} -/*-----------------------------------------------------------*/ - -const char * pcTimerGetName( TimerHandle_t xTimer ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ -{ -Timer_t *pxTimer = ( Timer_t * ) xTimer; - - configASSERT( xTimer ); - return pxTimer->pcTimerName; -} -/*-----------------------------------------------------------*/ - -static void prvProcessExpiredTimer( const TickType_t xNextExpireTime, const TickType_t xTimeNow ) -{ -BaseType_t xResult; -Timer_t * const pxTimer = ( Timer_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxCurrentTimerList ); - - /* Remove the timer from the list of active timers. A check has already - been performed to ensure the list is not empty. */ - ( void ) uxListRemove( &( pxTimer->xTimerListItem ) ); - traceTIMER_EXPIRED( pxTimer ); - - /* If the timer is an auto reload timer then calculate the next - expiry time and re-insert the timer in the list of active timers. */ - if( pxTimer->uxAutoReload == ( UBaseType_t ) pdTRUE ) - { - /* The timer is inserted into a list using a time relative to anything - other than the current time. It will therefore be inserted into the - correct list relative to the time this task thinks it is now. */ - if( prvInsertTimerInActiveList( pxTimer, ( xNextExpireTime + pxTimer->xTimerPeriodInTicks ), xTimeNow, xNextExpireTime ) != pdFALSE ) - { - /* The timer expired before it was added to the active timer - list. Reload it now. */ - xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START_DONT_TRACE, xNextExpireTime, NULL, tmrNO_DELAY ); - configASSERT( xResult ); - ( void ) xResult; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - /* Call the timer callback. */ - pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer ); -} -/*-----------------------------------------------------------*/ - -static void prvTimerTask( void *pvParameters ) -{ -TickType_t xNextExpireTime; -BaseType_t xListWasEmpty; - - /* Just to avoid compiler warnings. */ - ( void ) pvParameters; - - #if( configUSE_DAEMON_TASK_STARTUP_HOOK == 1 ) - { - extern void vApplicationDaemonTaskStartupHook( void ); - - /* Allow the application writer to execute some code in the context of - this task at the point the task starts executing. This is useful if the - application includes initialisation code that would benefit from - executing after the scheduler has been started. */ - vApplicationDaemonTaskStartupHook(); - } - #endif /* configUSE_DAEMON_TASK_STARTUP_HOOK */ - - for( ;; ) - { - /* Query the timers list to see if it contains any timers, and if so, - obtain the time at which the next timer will expire. */ - xNextExpireTime = prvGetNextExpireTime( &xListWasEmpty ); - - /* If a timer has expired, process it. Otherwise, block this task - until either a timer does expire, or a command is received. */ - prvProcessTimerOrBlockTask( xNextExpireTime, xListWasEmpty ); - - /* Empty the command queue. */ - prvProcessReceivedCommands(); - } -} -/*-----------------------------------------------------------*/ - -static void prvProcessTimerOrBlockTask( const TickType_t xNextExpireTime, BaseType_t xListWasEmpty ) -{ -TickType_t xTimeNow; -BaseType_t xTimerListsWereSwitched; - - vTaskSuspendAll(); - { - /* Obtain the time now to make an assessment as to whether the timer - has expired or not. If obtaining the time causes the lists to switch - then don't process this timer as any timers that remained in the list - when the lists were switched will have been processed within the - prvSampleTimeNow() function. */ - xTimeNow = prvSampleTimeNow( &xTimerListsWereSwitched ); - if( xTimerListsWereSwitched == pdFALSE ) - { - /* The tick count has not overflowed, has the timer expired? */ - if( ( xListWasEmpty == pdFALSE ) && ( xNextExpireTime <= xTimeNow ) ) - { - ( void ) xTaskResumeAll(); - prvProcessExpiredTimer( xNextExpireTime, xTimeNow ); - } - else - { - /* The tick count has not overflowed, and the next expire - time has not been reached yet. This task should therefore - block to wait for the next expire time or a command to be - received - whichever comes first. The following line cannot - be reached unless xNextExpireTime > xTimeNow, except in the - case when the current timer list is empty. */ - if( xListWasEmpty != pdFALSE ) - { - /* The current timer list is empty - is the overflow list - also empty? */ - xListWasEmpty = listLIST_IS_EMPTY( pxOverflowTimerList ); - } - - vQueueWaitForMessageRestricted( xTimerQueue, ( xNextExpireTime - xTimeNow ), xListWasEmpty ); - - if( xTaskResumeAll() == pdFALSE ) - { - /* Yield to wait for either a command to arrive, or the - block time to expire. If a command arrived between the - critical section being exited and this yield then the yield - will not cause the task to block. */ - portYIELD_WITHIN_API(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } - else - { - ( void ) xTaskResumeAll(); - } - } -} -/*-----------------------------------------------------------*/ - -static TickType_t prvGetNextExpireTime( BaseType_t * const pxListWasEmpty ) -{ -TickType_t xNextExpireTime; - - /* Timers are listed in expiry time order, with the head of the list - referencing the task that will expire first. Obtain the time at which - the timer with the nearest expiry time will expire. If there are no - active timers then just set the next expire time to 0. That will cause - this task to unblock when the tick count overflows, at which point the - timer lists will be switched and the next expiry time can be - re-assessed. */ - *pxListWasEmpty = listLIST_IS_EMPTY( pxCurrentTimerList ); - if( *pxListWasEmpty == pdFALSE ) - { - xNextExpireTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxCurrentTimerList ); - } - else - { - /* Ensure the task unblocks when the tick count rolls over. */ - xNextExpireTime = ( TickType_t ) 0U; - } - - return xNextExpireTime; -} -/*-----------------------------------------------------------*/ - -static TickType_t prvSampleTimeNow( BaseType_t * const pxTimerListsWereSwitched ) -{ -TickType_t xTimeNow; -PRIVILEGED_DATA static TickType_t xLastTime = ( TickType_t ) 0U; /*lint !e956 Variable is only accessible to one task. */ - - xTimeNow = xTaskGetTickCount(); - - if( xTimeNow < xLastTime ) - { - prvSwitchTimerLists(); - *pxTimerListsWereSwitched = pdTRUE; - } - else - { - *pxTimerListsWereSwitched = pdFALSE; - } - - xLastTime = xTimeNow; - - return xTimeNow; -} -/*-----------------------------------------------------------*/ - -static BaseType_t prvInsertTimerInActiveList( Timer_t * const pxTimer, const TickType_t xNextExpiryTime, const TickType_t xTimeNow, const TickType_t xCommandTime ) -{ -BaseType_t xProcessTimerNow = pdFALSE; - - listSET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ), xNextExpiryTime ); - listSET_LIST_ITEM_OWNER( &( pxTimer->xTimerListItem ), pxTimer ); - - if( xNextExpiryTime <= xTimeNow ) - { - /* Has the expiry time elapsed between the command to start/reset a - timer was issued, and the time the command was processed? */ - if( ( ( TickType_t ) ( xTimeNow - xCommandTime ) ) >= pxTimer->xTimerPeriodInTicks ) /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - { - /* The time between a command being issued and the command being - processed actually exceeds the timers period. */ - xProcessTimerNow = pdTRUE; - } - else - { - vListInsert( pxOverflowTimerList, &( pxTimer->xTimerListItem ) ); - } - } - else - { - if( ( xTimeNow < xCommandTime ) && ( xNextExpiryTime >= xCommandTime ) ) - { - /* If, since the command was issued, the tick count has overflowed - but the expiry time has not, then the timer must have already passed - its expiry time and should be processed immediately. */ - xProcessTimerNow = pdTRUE; - } - else - { - vListInsert( pxCurrentTimerList, &( pxTimer->xTimerListItem ) ); - } - } - - return xProcessTimerNow; -} -/*-----------------------------------------------------------*/ - -static void prvProcessReceivedCommands( void ) -{ -DaemonTaskMessage_t xMessage; -Timer_t *pxTimer; -BaseType_t xTimerListsWereSwitched, xResult; -TickType_t xTimeNow; - - while( xQueueReceive( xTimerQueue, &xMessage, tmrNO_DELAY ) != pdFAIL ) /*lint !e603 xMessage does not have to be initialised as it is passed out, not in, and it is not used unless xQueueReceive() returns pdTRUE. */ - { - #if ( INCLUDE_xTimerPendFunctionCall == 1 ) - { - /* Negative commands are pended function calls rather than timer - commands. */ - if( xMessage.xMessageID < ( BaseType_t ) 0 ) - { - const CallbackParameters_t * const pxCallback = &( xMessage.u.xCallbackParameters ); - - /* The timer uses the xCallbackParameters member to request a - callback be executed. Check the callback is not NULL. */ - configASSERT( pxCallback ); - - /* Call the function. */ - pxCallback->pxCallbackFunction( pxCallback->pvParameter1, pxCallback->ulParameter2 ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* INCLUDE_xTimerPendFunctionCall */ - - /* Commands that are positive are timer commands rather than pended - function calls. */ - if( xMessage.xMessageID >= ( BaseType_t ) 0 ) - { - /* The messages uses the xTimerParameters member to work on a - software timer. */ - pxTimer = xMessage.u.xTimerParameters.pxTimer; - - if( listIS_CONTAINED_WITHIN( NULL, &( pxTimer->xTimerListItem ) ) == pdFALSE ) /*lint !e961. The cast is only redundant when NULL is passed into the macro. */ - { - /* The timer is in a list, remove it. */ - ( void ) uxListRemove( &( pxTimer->xTimerListItem ) ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - traceTIMER_COMMAND_RECEIVED( pxTimer, xMessage.xMessageID, xMessage.u.xTimerParameters.xMessageValue ); - - /* In this case the xTimerListsWereSwitched parameter is not used, but - it must be present in the function call. prvSampleTimeNow() must be - called after the message is received from xTimerQueue so there is no - possibility of a higher priority task adding a message to the message - queue with a time that is ahead of the timer daemon task (because it - pre-empted the timer daemon task after the xTimeNow value was set). */ - xTimeNow = prvSampleTimeNow( &xTimerListsWereSwitched ); - - switch( xMessage.xMessageID ) - { - case tmrCOMMAND_START : - case tmrCOMMAND_START_FROM_ISR : - case tmrCOMMAND_RESET : - case tmrCOMMAND_RESET_FROM_ISR : - case tmrCOMMAND_START_DONT_TRACE : - /* Start or restart a timer. */ - if( prvInsertTimerInActiveList( pxTimer, xMessage.u.xTimerParameters.xMessageValue + pxTimer->xTimerPeriodInTicks, xTimeNow, xMessage.u.xTimerParameters.xMessageValue ) != pdFALSE ) - { - /* The timer expired before it was added to the active - timer list. Process it now. */ - pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer ); - traceTIMER_EXPIRED( pxTimer ); - - if( pxTimer->uxAutoReload == ( UBaseType_t ) pdTRUE ) - { - xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START_DONT_TRACE, xMessage.u.xTimerParameters.xMessageValue + pxTimer->xTimerPeriodInTicks, NULL, tmrNO_DELAY ); - configASSERT( xResult ); - ( void ) xResult; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - break; - - case tmrCOMMAND_STOP : - case tmrCOMMAND_STOP_FROM_ISR : - /* The timer has already been removed from the active list. - There is nothing to do here. */ - break; - - case tmrCOMMAND_CHANGE_PERIOD : - case tmrCOMMAND_CHANGE_PERIOD_FROM_ISR : - pxTimer->xTimerPeriodInTicks = xMessage.u.xTimerParameters.xMessageValue; - configASSERT( ( pxTimer->xTimerPeriodInTicks > 0 ) ); - - /* The new period does not really have a reference, and can - be longer or shorter than the old one. The command time is - therefore set to the current time, and as the period cannot - be zero the next expiry time can only be in the future, - meaning (unlike for the xTimerStart() case above) there is - no fail case that needs to be handled here. */ - ( void ) prvInsertTimerInActiveList( pxTimer, ( xTimeNow + pxTimer->xTimerPeriodInTicks ), xTimeNow, xTimeNow ); - break; - - case tmrCOMMAND_DELETE : - /* The timer has already been removed from the active list, - just free up the memory if the memory was dynamically - allocated. */ - #if( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 0 ) ) - { - /* The timer can only have been allocated dynamically - - free it again. */ - vPortFree( pxTimer ); - } - #elif( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) - { - /* The timer could have been allocated statically or - dynamically, so check before attempting to free the - memory. */ - if( pxTimer->ucStaticallyAllocated == ( uint8_t ) pdFALSE ) - { - vPortFree( pxTimer ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ - break; - - default : - /* Don't expect to get here. */ - break; - } - } - } -} -/*-----------------------------------------------------------*/ - -static void prvSwitchTimerLists( void ) -{ -TickType_t xNextExpireTime, xReloadTime; -List_t *pxTemp; -Timer_t *pxTimer; -BaseType_t xResult; - - /* The tick count has overflowed. The timer lists must be switched. - If there are any timers still referenced from the current timer list - then they must have expired and should be processed before the lists - are switched. */ - while( listLIST_IS_EMPTY( pxCurrentTimerList ) == pdFALSE ) - { - xNextExpireTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxCurrentTimerList ); - - /* Remove the timer from the list. */ - pxTimer = ( Timer_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxCurrentTimerList ); - ( void ) uxListRemove( &( pxTimer->xTimerListItem ) ); - traceTIMER_EXPIRED( pxTimer ); - - /* Execute its callback, then send a command to restart the timer if - it is an auto-reload timer. It cannot be restarted here as the lists - have not yet been switched. */ - pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer ); - - if( pxTimer->uxAutoReload == ( UBaseType_t ) pdTRUE ) - { - /* Calculate the reload value, and if the reload value results in - the timer going into the same timer list then it has already expired - and the timer should be re-inserted into the current list so it is - processed again within this loop. Otherwise a command should be sent - to restart the timer to ensure it is only inserted into a list after - the lists have been swapped. */ - xReloadTime = ( xNextExpireTime + pxTimer->xTimerPeriodInTicks ); - if( xReloadTime > xNextExpireTime ) - { - listSET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ), xReloadTime ); - listSET_LIST_ITEM_OWNER( &( pxTimer->xTimerListItem ), pxTimer ); - vListInsert( pxCurrentTimerList, &( pxTimer->xTimerListItem ) ); - } - else - { - xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START_DONT_TRACE, xNextExpireTime, NULL, tmrNO_DELAY ); - configASSERT( xResult ); - ( void ) xResult; - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - - pxTemp = pxCurrentTimerList; - pxCurrentTimerList = pxOverflowTimerList; - pxOverflowTimerList = pxTemp; -} -/*-----------------------------------------------------------*/ - -static void prvCheckForValidListAndQueue( void ) -{ - /* Check that the list from which active timers are referenced, and the - queue used to communicate with the timer service, have been - initialised. */ - taskENTER_CRITICAL(); - { - if( xTimerQueue == NULL ) - { - vListInitialise( &xActiveTimerList1 ); - vListInitialise( &xActiveTimerList2 ); - pxCurrentTimerList = &xActiveTimerList1; - pxOverflowTimerList = &xActiveTimerList2; - - #if( configSUPPORT_STATIC_ALLOCATION == 1 ) - { - /* The timer queue is allocated statically in case - configSUPPORT_DYNAMIC_ALLOCATION is 0. */ - static StaticQueue_t xStaticTimerQueue; /*lint !e956 Ok to declare in this manner to prevent additional conditional compilation guards in other locations. */ - static uint8_t ucStaticTimerQueueStorage[ ( size_t ) configTIMER_QUEUE_LENGTH * sizeof( DaemonTaskMessage_t ) ]; /*lint !e956 Ok to declare in this manner to prevent additional conditional compilation guards in other locations. */ - - xTimerQueue = xQueueCreateStatic( ( UBaseType_t ) configTIMER_QUEUE_LENGTH, ( UBaseType_t ) sizeof( DaemonTaskMessage_t ), &( ucStaticTimerQueueStorage[ 0 ] ), &xStaticTimerQueue ); - } - #else - { - xTimerQueue = xQueueCreate( ( UBaseType_t ) configTIMER_QUEUE_LENGTH, sizeof( DaemonTaskMessage_t ) ); - } - #endif - - #if ( configQUEUE_REGISTRY_SIZE > 0 ) - { - if( xTimerQueue != NULL ) - { - vQueueAddToRegistry( xTimerQueue, "TmrQ" ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configQUEUE_REGISTRY_SIZE */ - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - taskEXIT_CRITICAL(); -} -/*-----------------------------------------------------------*/ - -BaseType_t xTimerIsTimerActive( TimerHandle_t xTimer ) -{ -BaseType_t xTimerIsInActiveList; -Timer_t *pxTimer = ( Timer_t * ) xTimer; - - configASSERT( xTimer ); - - /* Is the timer in the list of active timers? */ - taskENTER_CRITICAL(); - { - /* Checking to see if it is in the NULL list in effect checks to see if - it is referenced from either the current or the overflow timer lists in - one go, but the logic has to be reversed, hence the '!'. */ - xTimerIsInActiveList = ( BaseType_t ) !( listIS_CONTAINED_WITHIN( NULL, &( pxTimer->xTimerListItem ) ) ); /*lint !e961. Cast is only redundant when NULL is passed into the macro. */ - } - taskEXIT_CRITICAL(); - - return xTimerIsInActiveList; -} /*lint !e818 Can't be pointer to const due to the typedef. */ -/*-----------------------------------------------------------*/ - -void *pvTimerGetTimerID( const TimerHandle_t xTimer ) -{ -Timer_t * const pxTimer = ( Timer_t * ) xTimer; -void *pvReturn; - - configASSERT( xTimer ); - - taskENTER_CRITICAL(); - { - pvReturn = pxTimer->pvTimerID; - } - taskEXIT_CRITICAL(); - - return pvReturn; -} -/*-----------------------------------------------------------*/ - -void vTimerSetTimerID( TimerHandle_t xTimer, void *pvNewID ) -{ -Timer_t * const pxTimer = ( Timer_t * ) xTimer; - - configASSERT( xTimer ); - - taskENTER_CRITICAL(); - { - pxTimer->pvTimerID = pvNewID; - } - taskEXIT_CRITICAL(); -} -/*-----------------------------------------------------------*/ - -#if( INCLUDE_xTimerPendFunctionCall == 1 ) - - BaseType_t xTimerPendFunctionCallFromISR( PendedFunction_t xFunctionToPend, void *pvParameter1, uint32_t ulParameter2, BaseType_t *pxHigherPriorityTaskWoken ) - { - DaemonTaskMessage_t xMessage; - BaseType_t xReturn; - - /* Complete the message with the function parameters and post it to the - daemon task. */ - xMessage.xMessageID = tmrCOMMAND_EXECUTE_CALLBACK_FROM_ISR; - xMessage.u.xCallbackParameters.pxCallbackFunction = xFunctionToPend; - xMessage.u.xCallbackParameters.pvParameter1 = pvParameter1; - xMessage.u.xCallbackParameters.ulParameter2 = ulParameter2; - - xReturn = xQueueSendFromISR( xTimerQueue, &xMessage, pxHigherPriorityTaskWoken ); - - tracePEND_FUNC_CALL_FROM_ISR( xFunctionToPend, pvParameter1, ulParameter2, xReturn ); - - return xReturn; - } - -#endif /* INCLUDE_xTimerPendFunctionCall */ -/*-----------------------------------------------------------*/ - -#if( INCLUDE_xTimerPendFunctionCall == 1 ) - - BaseType_t xTimerPendFunctionCall( PendedFunction_t xFunctionToPend, void *pvParameter1, uint32_t ulParameter2, TickType_t xTicksToWait ) - { - DaemonTaskMessage_t xMessage; - BaseType_t xReturn; - - /* This function can only be called after a timer has been created or - after the scheduler has been started because, until then, the timer - queue does not exist. */ - configASSERT( xTimerQueue ); - - /* Complete the message with the function parameters and post it to the - daemon task. */ - xMessage.xMessageID = tmrCOMMAND_EXECUTE_CALLBACK; - xMessage.u.xCallbackParameters.pxCallbackFunction = xFunctionToPend; - xMessage.u.xCallbackParameters.pvParameter1 = pvParameter1; - xMessage.u.xCallbackParameters.ulParameter2 = ulParameter2; - - xReturn = xQueueSendToBack( xTimerQueue, &xMessage, xTicksToWait ); - - tracePEND_FUNC_CALL( xFunctionToPend, pvParameter1, ulParameter2, xReturn ); - - return xReturn; - } - -#endif /* INCLUDE_xTimerPendFunctionCall */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_TRACE_FACILITY == 1 ) - - UBaseType_t uxTimerGetTimerNumber( TimerHandle_t xTimer ) - { - return ( ( Timer_t * ) xTimer )->uxTimerNumber; - } - -#endif /* configUSE_TRACE_FACILITY */ -/*-----------------------------------------------------------*/ - -#if ( configUSE_TRACE_FACILITY == 1 ) - - void vTimerSetTimerNumber( TimerHandle_t xTimer, UBaseType_t uxTimerNumber ) - { - ( ( Timer_t * ) xTimer )->uxTimerNumber = uxTimerNumber; - } - -#endif /* configUSE_TRACE_FACILITY */ -/*-----------------------------------------------------------*/ - -/* This entire source file will be skipped if the application is not configured -to include software timer functionality. If you want to include software timer -functionality then ensure configUSE_TIMERS is set to 1 in FreeRTOSConfig.h. */ -#endif /* configUSE_TIMERS == 1 */ - - - diff --git a/lib/FreeRTOS/readme.txt b/lib/FreeRTOS/readme.txt deleted file mode 100644 index 7fa63a75..00000000 --- a/lib/FreeRTOS/readme.txt +++ /dev/null @@ -1,21 +0,0 @@ -Directories: - -+ The FreeRTOS/Source directory contains the FreeRTOS source code, and contains - its own readme file. - -+ The FreeRTOS/Demo directory contains a demo application for every official -FreeRTOS port, and contains its own readme file. - -+ See http://www.freertos.org/a00017.html for full details of the directory - structure and information on locating the files you require. - -The easiest way to use FreeRTOS is to start with one of the pre-configured demo -application projects (found in the FreeRTOS/Demo directory). That way you will -have the correct FreeRTOS source files included, and the correct include paths -configured. Once a demo application is building and executing you can remove -the demo application file, and start to add in your own application source -files. - -See also - -http://www.freertos.org/FreeRTOS-quick-start-guide.html -http://www.freertos.org/FAQHelp.html From 554006508512f08295d7fe1049f5238ab5ac44df Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 10 Mar 2020 14:55:56 +0700 Subject: [PATCH 255/267] added FreeRTOS as submodule --- .gitmodules | 3 +++ lib/FreeRTOS | 1 + 2 files changed, 4 insertions(+) create mode 160000 lib/FreeRTOS diff --git a/.gitmodules b/.gitmodules index 0dda17d6..0f9ad34c 100644 --- a/.gitmodules +++ b/.gitmodules @@ -25,3 +25,6 @@ [submodule "lib/lwip"] path = lib/lwip url = https://git.savannah.nongnu.org/git/lwip.git +[submodule "lib/FreeRTOS"] + path = lib/FreeRTOS + url = https://github.com/FreeRTOS/FreeRTOS.git diff --git a/lib/FreeRTOS b/lib/FreeRTOS new file mode 160000 index 00000000..c40a6da2 --- /dev/null +++ b/lib/FreeRTOS @@ -0,0 +1 @@ +Subproject commit c40a6da2e4cb8042b56d1b174051cbbe9813781a From fd5c64d7b5a70599031c9f95eaa5c4b57c94a7f3 Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 10 Mar 2020 15:34:05 +0700 Subject: [PATCH 256/267] fix freertos compile --- examples/device/cdc_msc_freertos/Makefile | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/examples/device/cdc_msc_freertos/Makefile b/examples/device/cdc_msc_freertos/Makefile index 7401f355..ac213ee7 100644 --- a/examples/device/cdc_msc_freertos/Makefile +++ b/examples/device/cdc_msc_freertos/Makefile @@ -1,11 +1,13 @@ include ../../../tools/top.mk include ../../make.mk +FREERTOS_SRC = lib/FreeRTOS/FreeRTOS/Source + INC += \ src \ $(TOP)/hw \ - $(TOP)/lib/FreeRTOS/Source/include \ - $(TOP)/lib/FreeRTOS/Source/portable/GCC/$(FREERTOS_PORT) + $(TOP)/$(FREERTOS_SRC)/include \ + $(TOP)/$(FREERTOS_SRC)/portable/GCC/$(FREERTOS_PORT) # Example source EXAMPLE_SOURCE += $(wildcard src/*.c) @@ -13,12 +15,12 @@ SRC_C += $(addprefix $(CURRENT_PATH)/, $(EXAMPLE_SOURCE)) # FreeRTOS source SRC_C += \ - lib/FreeRTOS/Source/list.c \ - lib/FreeRTOS/Source/queue.c \ - lib/FreeRTOS/Source/tasks.c \ - lib/FreeRTOS/Source/timers.c \ - lib/FreeRTOS/Source/portable/MemMang/heap_4.c \ - lib/FreeRTOS/Source/portable/GCC/$(FREERTOS_PORT)/port.c \ + $(FREERTOS_SRC)/list.c \ + $(FREERTOS_SRC)/queue.c \ + $(FREERTOS_SRC)/tasks.c \ + $(FREERTOS_SRC)/timers.c \ + $(FREERTOS_SRC)/portable/MemMang/heap_4.c \ + $(FREERTOS_SRC)/portable/GCC/$(FREERTOS_PORT)/port.c \ # FreeRTOS (lto + Os) linker issue LDFLAGS += -Wl,--undefined=vTaskSwitchContext From 65578dec44cb0143871e9b5b6f54fe4e38940ea8 Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 10 Mar 2020 23:16:09 +0700 Subject: [PATCH 257/267] update freertos example work with samd21 samd51 and nrf --- examples/device/cdc_msc_freertos/Makefile | 2 +- .../cdc_msc_freertos/src}/FreeRTOSConfig.h | 42 +++++++++---------- examples/device/cdc_msc_freertos/src/main.c | 14 ++++++- hw/bsp/circuitplayground_express/board.mk | 3 +- .../circuitplayground_express.c | 11 +++-- .../feather_m0_express/feather_m0_express.c | 11 +++-- .../feather_m4_express/feather_m4_express.c | 14 +++++-- .../feather_nrf52840_express.c | 3 -- .../feather_nrf52840_sense.c | 3 -- hw/bsp/itsybitsy_m0/itsybitsy_m0.c | 11 +++-- hw/bsp/itsybitsy_m4/itsybitsy_m4.c | 14 +++++-- hw/bsp/metro_m0_express/metro_m0_express.c | 11 +++-- hw/bsp/metro_m4_express/metro_m4_express.c | 14 +++++-- hw/bsp/pca10056/pca10056.c | 2 - hw/bsp/pca10059/pca10059.c | 2 - hw/bsp/pca10100/pca10100.c | 2 - 16 files changed, 101 insertions(+), 58 deletions(-) rename {hw/mcu/nordic => examples/device/cdc_msc_freertos/src}/FreeRTOSConfig.h (90%) diff --git a/examples/device/cdc_msc_freertos/Makefile b/examples/device/cdc_msc_freertos/Makefile index ac213ee7..f9261310 100644 --- a/examples/device/cdc_msc_freertos/Makefile +++ b/examples/device/cdc_msc_freertos/Makefile @@ -20,7 +20,7 @@ SRC_C += \ $(FREERTOS_SRC)/tasks.c \ $(FREERTOS_SRC)/timers.c \ $(FREERTOS_SRC)/portable/MemMang/heap_4.c \ - $(FREERTOS_SRC)/portable/GCC/$(FREERTOS_PORT)/port.c \ + $(FREERTOS_SRC)/portable/GCC/$(FREERTOS_PORT)/port.c # FreeRTOS (lto + Os) linker issue LDFLAGS += -Wl,--undefined=vTaskSwitchContext diff --git a/hw/mcu/nordic/FreeRTOSConfig.h b/examples/device/cdc_msc_freertos/src/FreeRTOSConfig.h similarity index 90% rename from hw/mcu/nordic/FreeRTOSConfig.h rename to examples/device/cdc_msc_freertos/src/FreeRTOSConfig.h index 53f72a06..0697bfca 100644 --- a/hw/mcu/nordic/FreeRTOSConfig.h +++ b/examples/device/cdc_msc_freertos/src/FreeRTOSConfig.h @@ -41,8 +41,17 @@ * * See http://www.freertos.org/a00110.html. *----------------------------------------------------------*/ -#include "nrf.h" +// for OPT_MCU_ +#include "tusb_option.h" + +#if CFG_TUSB_MCU == OPT_MCU_NRF5X + #include "nrf.h" +#elif CFG_TUSB_MCU == OPT_MCU_SAMD21 || CFG_TUSB_MCU == OPT_MCU_SAMD51 + #include "sam.h" +#else + #error "FreeRTOSConfig.h need to include low level mcu header for configuration" +#endif #define configUSE_PREEMPTION 1 #define configUSE_PORT_OPTIMISED_TASK_SELECTION 0 @@ -50,7 +59,7 @@ #define configTICK_RATE_HZ ( 1000 ) #define configMAX_PRIORITIES ( 5 ) #define configMINIMAL_STACK_SIZE ( 128 ) -#define configTOTAL_HEAP_SIZE ( 16*1024 ) +#define configTOTAL_HEAP_SIZE ( 4*1024 ) #define configMAX_TASK_NAME_LEN 16 #define configUSE_16_BIT_TICKS 0 #define configIDLE_SHOULD_YIELD 1 @@ -108,18 +117,18 @@ /* Define to trap errors during development. */ // Halt CPU (breakpoint) when hitting error, only apply for Cortex M3, M4, M7 #if defined(__ARM_ARCH_7M__) || defined (__ARM_ARCH_7EM__) -#define configASSERT(_exp) \ - do {\ - if ( !(_exp) ) { \ - volatile uint32_t* ARM_CM_DHCSR = ((volatile uint32_t*) 0xE000EDF0UL); /* Cortex M CoreDebug->DHCSR */ \ - if ( (*ARM_CM_DHCSR) & 1UL ) { /* Only halt mcu if debugger is attached */ \ - taskDISABLE_INTERRUPTS(); \ - __asm("BKPT #0\n"); \ + #define configASSERT(_exp) \ + do {\ + if ( !(_exp) ) { \ + volatile uint32_t* ARM_CM_DHCSR = ((volatile uint32_t*) 0xE000EDF0UL); /* Cortex M CoreDebug->DHCSR */ \ + if ( (*ARM_CM_DHCSR) & 1UL ) { /* Only halt mcu if debugger is attached */ \ + taskDISABLE_INTERRUPTS(); \ + __asm("BKPT #0\n"); \ + }\ }\ - }\ - } while(0) + } while(0) #else -#define configASSERT( x ) + #define configASSERT( x ) #endif /* FreeRTOS hooks to NVIC vectors */ @@ -144,15 +153,6 @@ routine that makes calls to interrupt safe FreeRTOS API functions. DO NOT CALL INTERRUPT SAFE FREERTOS API FUNCTIONS FROM ANY INTERRUPT THAT HAS A HIGHER PRIORITY THAN THIS! (higher priorities are lower numeric values. */ - -/* SD priority - * 0: SD timing critical - * 1: SD memory protection - * 2: App Highest - * 3: App High - * 4: SD non-time-critical - * 5+ Remaining Application - */ #define configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY 2 /* Interrupt priorities used by the kernel port layer itself. These are generic diff --git a/examples/device/cdc_msc_freertos/src/main.c b/examples/device/cdc_msc_freertos/src/main.c index b3205fc4..e4d8264e 100644 --- a/examples/device/cdc_msc_freertos/src/main.c +++ b/examples/device/cdc_msc_freertos/src/main.c @@ -53,6 +53,16 @@ enum { TimerHandle_t blink_tm; +// static task +#define USBD_STACK_SIZE 150 +StackType_t stack_usbd[USBD_STACK_SIZE]; +StaticTask_t static_task_usbd; + +#define CDC_STACK_SZIE 128 +StackType_t stack_cdc[CDC_STACK_SZIE]; +StaticTask_t static_task_cdc; + + void led_blinky_cb(TimerHandle_t xTimer); void usb_device_task(void* param); void cdc_task(void* params); @@ -69,11 +79,11 @@ int main(void) tusb_init(); // Create a task for tinyusb device stack - xTaskCreate( usb_device_task, "usbd", 150, NULL, configMAX_PRIORITIES-1, NULL); + (void) xTaskCreateStatic( usb_device_task, "usbd", USBD_STACK_SIZE, NULL, configMAX_PRIORITIES-1, stack_usbd, &static_task_usbd); // Create task #if CFG_TUD_CDC - xTaskCreate( cdc_task, "cdc", 128, NULL, configMAX_PRIORITIES-2, NULL); + (void) xTaskCreateStatic( cdc_task, "cdc", CDC_STACK_SZIE, NULL, configMAX_PRIORITIES-2, stack_cdc, &static_task_cdc); #endif vTaskStartScheduler(); diff --git a/hw/bsp/circuitplayground_express/board.mk b/hw/bsp/circuitplayground_express/board.mk index 32b44071..e20272ad 100644 --- a/hw/bsp/circuitplayground_express/board.mk +++ b/hw/bsp/circuitplayground_express/board.mk @@ -41,4 +41,5 @@ JLINK_DEVICE = ATSAMD21G18 JLINK_IF = swd # flash using jlink -flash: flash-jlink +flash: $(BUILD)/$(BOARD)-firmware.uf2 + cp $< /media/$(USER)/CPLAYBOOT/ diff --git a/hw/bsp/circuitplayground_express/circuitplayground_express.c b/hw/bsp/circuitplayground_express/circuitplayground_express.c index c48d1446..cdd75580 100644 --- a/hw/bsp/circuitplayground_express/circuitplayground_express.c +++ b/hw/bsp/circuitplayground_express/circuitplayground_express.c @@ -60,6 +60,11 @@ void board_init(void) _sysctrl_init_referenced_generators(); _gclk_init_generators_by_fref(_GCLK_INIT_LAST); + // Update SystemCoreClock since it is hard coded with asf4 and not correct + // Init 1ms tick timer (samd SystemCoreClock may not correct) + SystemCoreClock = CONF_CPU_FREQUENCY; + SysTick_Config(CONF_CPU_FREQUENCY / 1000); + // Led init gpio_set_pin_direction(LED_PIN, GPIO_DIRECTION_OUT); gpio_set_pin_level(LED_PIN, 0); @@ -68,9 +73,9 @@ void board_init(void) gpio_set_pin_direction(BUTTON_PIN, GPIO_DIRECTION_IN); gpio_set_pin_pull_mode(BUTTON_PIN, GPIO_PULL_DOWN); -#if CFG_TUSB_OS == OPT_OS_NONE - // 1ms tick timer (samd SystemCoreClock may not correct) - SysTick_Config(CONF_CPU_FREQUENCY / 1000); +#if CFG_TUSB_OS == OPT_OS_FREERTOS + // If freeRTOS is used, IRQ priority is limit by max syscall ( smaller is higher ) + NVIC_SetPriority(USB_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY); #endif /* USB Clock init diff --git a/hw/bsp/feather_m0_express/feather_m0_express.c b/hw/bsp/feather_m0_express/feather_m0_express.c index 6fb14b5a..df81940f 100644 --- a/hw/bsp/feather_m0_express/feather_m0_express.c +++ b/hw/bsp/feather_m0_express/feather_m0_express.c @@ -60,6 +60,11 @@ void board_init(void) _sysctrl_init_referenced_generators(); _gclk_init_generators_by_fref(_GCLK_INIT_LAST); + // Update SystemCoreClock since it is hard coded with asf4 and not correct + // Init 1ms tick timer (samd SystemCoreClock may not correct) + SystemCoreClock = CONF_CPU_FREQUENCY; + SysTick_Config(CONF_CPU_FREQUENCY / 1000); + // Led init gpio_set_pin_direction(LED_PIN, GPIO_DIRECTION_OUT); gpio_set_pin_level(LED_PIN, 0); @@ -68,9 +73,9 @@ void board_init(void) gpio_set_pin_direction(BUTTON_PIN, GPIO_DIRECTION_IN); gpio_set_pin_pull_mode(BUTTON_PIN, GPIO_PULL_UP); -#if CFG_TUSB_OS == OPT_OS_NONE - // 1ms tick timer (samd SystemCoreClock may not correct) - SysTick_Config(CONF_CPU_FREQUENCY / 1000); +#if CFG_TUSB_OS == OPT_OS_FREERTOS + // If freeRTOS is used, IRQ priority is limit by max syscall ( smaller is higher ) + NVIC_SetPriority(USB_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY); #endif /* USB Clock init diff --git a/hw/bsp/feather_m4_express/feather_m4_express.c b/hw/bsp/feather_m4_express/feather_m4_express.c index 1e20c846..60939c99 100644 --- a/hw/bsp/feather_m4_express/feather_m4_express.c +++ b/hw/bsp/feather_m4_express/feather_m4_express.c @@ -58,6 +58,11 @@ void board_init(void) _oscctrl_init_referenced_generators(); _gclk_init_generators_by_fref(_GCLK_INIT_LAST); + // Update SystemCoreClock since it is hard coded with asf4 and not correct + // Init 1ms tick timer (samd SystemCoreClock may not correct) + SystemCoreClock = CONF_CPU_FREQUENCY; + SysTick_Config(CONF_CPU_FREQUENCY / 1000); + // Led init gpio_set_pin_direction(LED_PIN, GPIO_DIRECTION_OUT); gpio_set_pin_level(LED_PIN, 0); @@ -66,9 +71,12 @@ void board_init(void) gpio_set_pin_direction(BUTTON_PIN, GPIO_DIRECTION_IN); gpio_set_pin_pull_mode(BUTTON_PIN, GPIO_PULL_UP); -#if CFG_TUSB_OS == OPT_OS_NONE - // 1ms tick timer (samd SystemCoreClock may not correct) - SysTick_Config(CONF_CPU_FREQUENCY / 1000); +#if CFG_TUSB_OS == OPT_OS_FREERTOS + // If freeRTOS is used, IRQ priority is limit by max syscall ( smaller is higher ) + NVIC_SetPriority(USB_0_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY); + NVIC_SetPriority(USB_1_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY); + NVIC_SetPriority(USB_2_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY); + NVIC_SetPriority(USB_3_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY); #endif /* USB Clock init diff --git a/hw/bsp/feather_nrf52840_express/feather_nrf52840_express.c b/hw/bsp/feather_nrf52840_express/feather_nrf52840_express.c index d98e451e..5dc3a4c4 100644 --- a/hw/bsp/feather_nrf52840_express/feather_nrf52840_express.c +++ b/hw/bsp/feather_nrf52840_express/feather_nrf52840_express.c @@ -71,10 +71,8 @@ void board_init(void) // Button nrf_gpio_cfg_input(BUTTON_PIN, NRF_GPIO_PIN_PULLUP); -#if CFG_TUSB_OS == OPT_OS_NONE // 1ms tick timer SysTick_Config(SystemCoreClock/1000); -#endif // UART nrfx_uarte_config_t uart_cfg = @@ -99,7 +97,6 @@ void board_init(void) // 2 is highest for application NVIC_SetPriority(USBD_IRQn, 2); - // USB power may already be ready at this time -> no event generated // We need to invoke the handler based on the status initially uint32_t usb_reg; diff --git a/hw/bsp/feather_nrf52840_sense/feather_nrf52840_sense.c b/hw/bsp/feather_nrf52840_sense/feather_nrf52840_sense.c index 468f96c5..473abc2d 100644 --- a/hw/bsp/feather_nrf52840_sense/feather_nrf52840_sense.c +++ b/hw/bsp/feather_nrf52840_sense/feather_nrf52840_sense.c @@ -62,17 +62,14 @@ void board_init(void) // Button nrf_gpio_cfg_input(BUTTON_PIN, NRF_GPIO_PIN_PULLUP); -#if CFG_TUSB_OS == OPT_OS_NONE // 1ms tick timer SysTick_Config(SystemCoreClock/1000); -#endif #if TUSB_OPT_DEVICE_ENABLED // Priorities 0, 1, 4 (nRF52) are reserved for SoftDevice // 2 is highest for application NVIC_SetPriority(USBD_IRQn, 2); - // USB power may already be ready at this time -> no event generated // We need to invoke the handler based on the status initially uint32_t usb_reg; diff --git a/hw/bsp/itsybitsy_m0/itsybitsy_m0.c b/hw/bsp/itsybitsy_m0/itsybitsy_m0.c index 39fe3f35..dd7d4da0 100644 --- a/hw/bsp/itsybitsy_m0/itsybitsy_m0.c +++ b/hw/bsp/itsybitsy_m0/itsybitsy_m0.c @@ -60,6 +60,11 @@ void board_init(void) _sysctrl_init_referenced_generators(); _gclk_init_generators_by_fref(_GCLK_INIT_LAST); + // Update SystemCoreClock since it is hard coded with asf4 and not correct + // Init 1ms tick timer (samd SystemCoreClock may not correct) + SystemCoreClock = CONF_CPU_FREQUENCY; + SysTick_Config(CONF_CPU_FREQUENCY / 1000); + // Led init gpio_set_pin_direction(LED_PIN, GPIO_DIRECTION_OUT); gpio_set_pin_level(LED_PIN, 0); @@ -68,9 +73,9 @@ void board_init(void) gpio_set_pin_direction(BUTTON_PIN, GPIO_DIRECTION_IN); gpio_set_pin_pull_mode(BUTTON_PIN, GPIO_PULL_UP); -#if CFG_TUSB_OS == OPT_OS_NONE - // 1ms tick timer (samd SystemCoreClock may not correct) - SysTick_Config(CONF_CPU_FREQUENCY / 1000); +#if CFG_TUSB_OS == OPT_OS_FREERTOS + // If freeRTOS is used, IRQ priority is limit by max syscall ( smaller is higher ) + NVIC_SetPriority(USB_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY); #endif /* USB Clock init diff --git a/hw/bsp/itsybitsy_m4/itsybitsy_m4.c b/hw/bsp/itsybitsy_m4/itsybitsy_m4.c index 3afe9313..43432d3e 100644 --- a/hw/bsp/itsybitsy_m4/itsybitsy_m4.c +++ b/hw/bsp/itsybitsy_m4/itsybitsy_m4.c @@ -58,6 +58,11 @@ void board_init(void) _oscctrl_init_referenced_generators(); _gclk_init_generators_by_fref(_GCLK_INIT_LAST); + // Update SystemCoreClock since it is hard coded with asf4 and not correct + // Init 1ms tick timer (samd SystemCoreClock may not correct) + SystemCoreClock = CONF_CPU_FREQUENCY; + SysTick_Config(CONF_CPU_FREQUENCY / 1000); + // Led init gpio_set_pin_direction(LED_PIN, GPIO_DIRECTION_OUT); gpio_set_pin_level(LED_PIN, 0); @@ -66,9 +71,12 @@ void board_init(void) gpio_set_pin_direction(BUTTON_PIN, GPIO_DIRECTION_IN); gpio_set_pin_pull_mode(BUTTON_PIN, GPIO_PULL_UP); -#if CFG_TUSB_OS == OPT_OS_NONE - // 1ms tick timer (samd SystemCoreClock may not correct) - SysTick_Config(CONF_CPU_FREQUENCY / 1000); +#if CFG_TUSB_OS == OPT_OS_FREERTOS + // If freeRTOS is used, IRQ priority is limit by max syscall ( smaller is higher ) + NVIC_SetPriority(USB_0_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY); + NVIC_SetPriority(USB_1_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY); + NVIC_SetPriority(USB_2_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY); + NVIC_SetPriority(USB_3_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY); #endif /* USB Clock init diff --git a/hw/bsp/metro_m0_express/metro_m0_express.c b/hw/bsp/metro_m0_express/metro_m0_express.c index 6fb14b5a..df81940f 100644 --- a/hw/bsp/metro_m0_express/metro_m0_express.c +++ b/hw/bsp/metro_m0_express/metro_m0_express.c @@ -60,6 +60,11 @@ void board_init(void) _sysctrl_init_referenced_generators(); _gclk_init_generators_by_fref(_GCLK_INIT_LAST); + // Update SystemCoreClock since it is hard coded with asf4 and not correct + // Init 1ms tick timer (samd SystemCoreClock may not correct) + SystemCoreClock = CONF_CPU_FREQUENCY; + SysTick_Config(CONF_CPU_FREQUENCY / 1000); + // Led init gpio_set_pin_direction(LED_PIN, GPIO_DIRECTION_OUT); gpio_set_pin_level(LED_PIN, 0); @@ -68,9 +73,9 @@ void board_init(void) gpio_set_pin_direction(BUTTON_PIN, GPIO_DIRECTION_IN); gpio_set_pin_pull_mode(BUTTON_PIN, GPIO_PULL_UP); -#if CFG_TUSB_OS == OPT_OS_NONE - // 1ms tick timer (samd SystemCoreClock may not correct) - SysTick_Config(CONF_CPU_FREQUENCY / 1000); +#if CFG_TUSB_OS == OPT_OS_FREERTOS + // If freeRTOS is used, IRQ priority is limit by max syscall ( smaller is higher ) + NVIC_SetPriority(USB_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY); #endif /* USB Clock init diff --git a/hw/bsp/metro_m4_express/metro_m4_express.c b/hw/bsp/metro_m4_express/metro_m4_express.c index c3c0468a..11a95b40 100644 --- a/hw/bsp/metro_m4_express/metro_m4_express.c +++ b/hw/bsp/metro_m4_express/metro_m4_express.c @@ -58,6 +58,11 @@ void board_init(void) _oscctrl_init_referenced_generators(); _gclk_init_generators_by_fref(_GCLK_INIT_LAST); + // Update SystemCoreClock since it is hard coded with asf4 and not correct + // Init 1ms tick timer (samd SystemCoreClock may not correct) + SystemCoreClock = CONF_CPU_FREQUENCY; + SysTick_Config(CONF_CPU_FREQUENCY / 1000); + // Led init gpio_set_pin_direction(LED_PIN, GPIO_DIRECTION_OUT); gpio_set_pin_level(LED_PIN, 0); @@ -66,9 +71,12 @@ void board_init(void) gpio_set_pin_direction(BUTTON_PIN, GPIO_DIRECTION_IN); gpio_set_pin_pull_mode(BUTTON_PIN, GPIO_PULL_UP); -#if CFG_TUSB_OS == OPT_OS_NONE - // 1ms tick timer (samd SystemCoreClock may not correct) - SysTick_Config(CONF_CPU_FREQUENCY / 1000); +#if CFG_TUSB_OS == OPT_OS_FREERTOS + // If freeRTOS is used, IRQ priority is limit by max syscall ( smaller is higher ) + NVIC_SetPriority(USB_0_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY); + NVIC_SetPriority(USB_1_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY); + NVIC_SetPriority(USB_2_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY); + NVIC_SetPriority(USB_3_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY); #endif /* USB Clock init diff --git a/hw/bsp/pca10056/pca10056.c b/hw/bsp/pca10056/pca10056.c index b9cc9fc3..8d9764c3 100644 --- a/hw/bsp/pca10056/pca10056.c +++ b/hw/bsp/pca10056/pca10056.c @@ -71,10 +71,8 @@ void board_init(void) // Button nrf_gpio_cfg_input(BUTTON_PIN, NRF_GPIO_PIN_PULLUP); -#if CFG_TUSB_OS == OPT_OS_NONE // 1ms tick timer SysTick_Config(SystemCoreClock/1000); -#endif // UART nrfx_uarte_config_t uart_cfg = diff --git a/hw/bsp/pca10059/pca10059.c b/hw/bsp/pca10059/pca10059.c index 69246f4a..e0f4bc93 100644 --- a/hw/bsp/pca10059/pca10059.c +++ b/hw/bsp/pca10059/pca10059.c @@ -62,10 +62,8 @@ void board_init(void) // Button nrf_gpio_cfg_input(BUTTON_PIN, NRF_GPIO_PIN_PULLUP); -#if CFG_TUSB_OS == OPT_OS_NONE // 1ms tick timer SysTick_Config(SystemCoreClock/1000); -#endif #if TUSB_OPT_DEVICE_ENABLED // Priorities 0, 1, 4 (nRF52) are reserved for SoftDevice diff --git a/hw/bsp/pca10100/pca10100.c b/hw/bsp/pca10100/pca10100.c index b9cc9fc3..8d9764c3 100644 --- a/hw/bsp/pca10100/pca10100.c +++ b/hw/bsp/pca10100/pca10100.c @@ -71,10 +71,8 @@ void board_init(void) // Button nrf_gpio_cfg_input(BUTTON_PIN, NRF_GPIO_PIN_PULLUP); -#if CFG_TUSB_OS == OPT_OS_NONE // 1ms tick timer SysTick_Config(SystemCoreClock/1000); -#endif // UART nrfx_uarte_config_t uart_cfg = From 487b887f80f1b73a72a627a21b12c1185a147104 Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 11 Mar 2020 00:09:37 +0700 Subject: [PATCH 258/267] freertos demo use static only for most optmized sram --- .../.skip.MCU_VALENTYUSB_EPTRI | 0 examples/device/cdc_msc_freertos/Makefile | 1 - .../cdc_msc_freertos/src/FreeRTOSConfig.h | 58 +++++++++++++++++-- examples/device/cdc_msc_freertos/src/main.c | 7 ++- hw/bsp/ea4357/board.mk | 2 +- hw/bsp/fomu/board.mk | 3 + hw/bsp/lpcxpresso54114/board.mk | 2 +- hw/bsp/ngx4330/board.mk | 2 +- hw/bsp/nutiny_sdk_nuc505/board.mk | 2 +- hw/bsp/samg55xplained/samg55xplained.c | 1 - 10 files changed, 66 insertions(+), 12 deletions(-) create mode 100644 examples/device/cdc_msc_freertos/.skip.MCU_VALENTYUSB_EPTRI diff --git a/examples/device/cdc_msc_freertos/.skip.MCU_VALENTYUSB_EPTRI b/examples/device/cdc_msc_freertos/.skip.MCU_VALENTYUSB_EPTRI new file mode 100644 index 00000000..e69de29b diff --git a/examples/device/cdc_msc_freertos/Makefile b/examples/device/cdc_msc_freertos/Makefile index f9261310..da6044c1 100644 --- a/examples/device/cdc_msc_freertos/Makefile +++ b/examples/device/cdc_msc_freertos/Makefile @@ -19,7 +19,6 @@ SRC_C += \ $(FREERTOS_SRC)/queue.c \ $(FREERTOS_SRC)/tasks.c \ $(FREERTOS_SRC)/timers.c \ - $(FREERTOS_SRC)/portable/MemMang/heap_4.c \ $(FREERTOS_SRC)/portable/GCC/$(FREERTOS_PORT)/port.c # FreeRTOS (lto + Os) linker issue diff --git a/examples/device/cdc_msc_freertos/src/FreeRTOSConfig.h b/examples/device/cdc_msc_freertos/src/FreeRTOSConfig.h index 0697bfca..309a9a01 100644 --- a/examples/device/cdc_msc_freertos/src/FreeRTOSConfig.h +++ b/examples/device/cdc_msc_freertos/src/FreeRTOSConfig.h @@ -45,10 +45,60 @@ // for OPT_MCU_ #include "tusb_option.h" -#if CFG_TUSB_MCU == OPT_MCU_NRF5X +#if CFG_TUSB_MCU == OPT_MCU_LPC11UXX || CFG_TUSB_MCU == OPT_MCU_LPC13XX || \ + CFG_TUSB_MCU == OPT_MCU_LPC15XX || CFG_TUSB_MCU == OPT_MCU_LPC175X_6X || \ + CFG_TUSB_MCU == OPT_MCU_LPC177X_8X || CFG_TUSB_MCU == OPT_MCU_LPC18XX || \ + CFG_TUSB_MCU == OPT_MCU_LPC40XX || CFG_TUSB_MCU == OPT_MCU_LPC43XX + #include "chip.h" + +#elif CFG_TUSB_MCU == OPT_MCU_LPC51UXX || CFG_TUSB_MCU == OPT_MCU_LPC54XXX || \ + CFG_TUSB_MCU == OPT_MCU_LPC55XX + #include "fsl_device_registers.h" + +#elif CFG_TUSB_MCU == OPT_MCU_NRF5X #include "nrf.h" -#elif CFG_TUSB_MCU == OPT_MCU_SAMD21 || CFG_TUSB_MCU == OPT_MCU_SAMD51 + +#elif CFG_TUSB_MCU == OPT_MCU_SAMD21 || CFG_TUSB_MCU == OPT_MCU_SAMD51 || \ + CFG_TUSB_MCU == OPT_MCU_SAMG #include "sam.h" + +#elif CFG_TUSB_MCU == OPT_MCU_STM32F0 + #include "stm32f0xx.h" + +#elif CFG_TUSB_MCU == OPT_MCU_STM32F1 + #include "stm32f1xx.h" + +#elif CFG_TUSB_MCU == OPT_MCU_STM32F2 + #include "stm32f2xx.h" + +#elif CFG_TUSB_MCU == OPT_MCU_STM32F3 + #include "stm32f3xx.h" + +#elif CFG_TUSB_MCU == OPT_MCU_STM32F4 + #include "stm32f4xx.h" + +#elif CFG_TUSB_MCU == OPT_MCU_STM32F7 + #include "stm32f7xx.h" + +#elif CFG_TUSB_MCU == OPT_MCU_STM32H7 + #include "stm32h7xx.h" + +#elif CFG_TUSB_MCU == OPT_MCU_STM32L0 + #include "stm32l0xx.h" + +#elif CFG_TUSB_MCU == OPT_MCU_STM32L1 + #include "stm32l1xx.h" + +#elif CFG_TUSB_MCU == OPT_MCU_STM32L4 + #include "stm32l4xx.h" + +#elif CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX + #include "fsl_device_registers.h" + +#elif CFG_TUSB_MCU == OPT_MCU_NUC120 || CFG_TUSB_MCU == OPT_MCU_NUC121 || \ + CFG_TUSB_MCU == OPT_MCU_NUC126 || CFG_TUSB_MCU == OPT_MCU_NUC505 + #include "NuMicro.h" + #else #error "FreeRTOSConfig.h need to include low level mcu header for configuration" #endif @@ -59,7 +109,7 @@ #define configTICK_RATE_HZ ( 1000 ) #define configMAX_PRIORITIES ( 5 ) #define configMINIMAL_STACK_SIZE ( 128 ) -#define configTOTAL_HEAP_SIZE ( 4*1024 ) +#define configTOTAL_HEAP_SIZE ( 0*1024 ) // dynamic is not used #define configMAX_TASK_NAME_LEN 16 #define configUSE_16_BIT_TICKS 0 #define configIDLE_SHOULD_YIELD 1 @@ -73,7 +123,7 @@ #define configENABLE_BACKWARD_COMPATIBILITY 1 #define configSUPPORT_STATIC_ALLOCATION 1 -#define configSUPPORT_DYNAMIC_ALLOCATION 1 +#define configSUPPORT_DYNAMIC_ALLOCATION 0 /* Hook function related definitions. */ #define configUSE_IDLE_HOOK 0 diff --git a/examples/device/cdc_msc_freertos/src/main.c b/examples/device/cdc_msc_freertos/src/main.c index e4d8264e..704d0803 100644 --- a/examples/device/cdc_msc_freertos/src/main.c +++ b/examples/device/cdc_msc_freertos/src/main.c @@ -51,13 +51,16 @@ enum { BLINK_SUSPENDED = 2500, }; +// static timer +StaticTimer_t static_blink; TimerHandle_t blink_tm; -// static task +// static task for usbd #define USBD_STACK_SIZE 150 StackType_t stack_usbd[USBD_STACK_SIZE]; StaticTask_t static_task_usbd; +// static task for cdc #define CDC_STACK_SZIE 128 StackType_t stack_cdc[CDC_STACK_SZIE]; StaticTask_t static_task_cdc; @@ -73,7 +76,7 @@ int main(void) board_init(); // soft timer for blinky - blink_tm = xTimerCreate(NULL, pdMS_TO_TICKS(BLINK_NOT_MOUNTED), true, NULL, led_blinky_cb); + blink_tm = xTimerCreateStatic(NULL, pdMS_TO_TICKS(BLINK_NOT_MOUNTED), true, NULL, led_blinky_cb, &static_blink); xTimerStart(blink_tm, 0); tusb_init(); diff --git a/hw/bsp/ea4357/board.mk b/hw/bsp/ea4357/board.mk index ff7b7a15..d79cf141 100644 --- a/hw/bsp/ea4357/board.mk +++ b/hw/bsp/ea4357/board.mk @@ -35,7 +35,7 @@ VENDOR = nxp CHIP_FAMILY = transdimension # For freeRTOS port source -FREERTOS_PORT = ARM_CM4 +FREERTOS_PORT = ARM_CM4F # For flash-jlink target JLINK_DEVICE = LPC4357 diff --git a/hw/bsp/fomu/board.mk b/hw/bsp/fomu/board.mk index 8687cf41..b824b697 100644 --- a/hw/bsp/fomu/board.mk +++ b/hw/bsp/fomu/board.mk @@ -25,6 +25,9 @@ INC += \ VENDOR = valentyusb CHIP_FAMILY = eptri +# For freeRTOS port source +FREERTOS_PORT = RISC-V + # flash using dfu-util flash: $(BUILD)/$(BOARD)-firmware.dfu dfu-util -D $^ diff --git a/hw/bsp/lpcxpresso54114/board.mk b/hw/bsp/lpcxpresso54114/board.mk index 474a1ac5..2bab0340 100644 --- a/hw/bsp/lpcxpresso54114/board.mk +++ b/hw/bsp/lpcxpresso54114/board.mk @@ -39,7 +39,7 @@ VENDOR = nxp CHIP_FAMILY = lpc_ip3511 # For freeRTOS port source -FREERTOS_PORT = ARM_CM4 +FREERTOS_PORT = ARM_CM4F # For flash-jlink target JLINK_DEVICE = LPC54114J256_M4 diff --git a/hw/bsp/ngx4330/board.mk b/hw/bsp/ngx4330/board.mk index d95aaf05..df9df63a 100644 --- a/hw/bsp/ngx4330/board.mk +++ b/hw/bsp/ngx4330/board.mk @@ -33,7 +33,7 @@ VENDOR = nxp CHIP_FAMILY = transdimension # For freeRTOS port source -FREERTOS_PORT = ARM_CM4 +FREERTOS_PORT = ARM_CM4F # For flash-jlink target JLINK_DEVICE = LPC4330 diff --git a/hw/bsp/nutiny_sdk_nuc505/board.mk b/hw/bsp/nutiny_sdk_nuc505/board.mk index 68dea63a..1c1cbcf0 100644 --- a/hw/bsp/nutiny_sdk_nuc505/board.mk +++ b/hw/bsp/nutiny_sdk_nuc505/board.mk @@ -40,7 +40,7 @@ VENDOR = nuvoton CHIP_FAMILY = nuc505 # For freeRTOS port source -FREERTOS_PORT = ARM_CM4 +FREERTOS_PORT = ARM_CM4F # For flash-jlink target JLINK_DEVICE = NUC505YO13Y diff --git a/hw/bsp/samg55xplained/samg55xplained.c b/hw/bsp/samg55xplained/samg55xplained.c index 66a3d137..1eb5105b 100644 --- a/hw/bsp/samg55xplained/samg55xplained.c +++ b/hw/bsp/samg55xplained/samg55xplained.c @@ -42,7 +42,6 @@ #define BUTTON_PIN GPIO(GPIO_PORTA, 2) #define BUTTON_STATE_ACTIVE 0 - #define UART_TX_PIN GPIO(GPIO_PORTA, 28) #define UART_RX_PIN GPIO(GPIO_PORTA, 27) From 6a1416d18a81b7c82261f38ffc85c8ed5bf8df30 Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 11 Mar 2020 00:47:13 +0700 Subject: [PATCH 259/267] fix cortex M7, M23, M33 freertos build --- examples/device/cdc_msc_freertos/Makefile | 4 ++-- examples/device/cdc_msc_freertos/src/FreeRTOSConfig.h | 9 +++++++++ hw/bsp/ea4357/board.mk | 2 ++ hw/bsp/lpcxpresso55s69/board.mk | 2 +- hw/bsp/mimxrt1010_evk/board.mk | 2 +- hw/bsp/mimxrt1015_evk/board.mk | 2 +- hw/bsp/mimxrt1020_evk/board.mk | 2 +- hw/bsp/mimxrt1050_evkb/board.mk | 2 +- hw/bsp/mimxrt1060_evk/board.mk | 2 +- hw/bsp/mimxrt1064_evk/board.mk | 2 +- hw/bsp/teensy_40/board.mk | 2 +- 11 files changed, 21 insertions(+), 10 deletions(-) diff --git a/examples/device/cdc_msc_freertos/Makefile b/examples/device/cdc_msc_freertos/Makefile index da6044c1..3570daa4 100644 --- a/examples/device/cdc_msc_freertos/Makefile +++ b/examples/device/cdc_msc_freertos/Makefile @@ -13,13 +13,13 @@ INC += \ EXAMPLE_SOURCE += $(wildcard src/*.c) SRC_C += $(addprefix $(CURRENT_PATH)/, $(EXAMPLE_SOURCE)) -# FreeRTOS source +# FreeRTOS source, all files in port folder SRC_C += \ $(FREERTOS_SRC)/list.c \ $(FREERTOS_SRC)/queue.c \ $(FREERTOS_SRC)/tasks.c \ $(FREERTOS_SRC)/timers.c \ - $(FREERTOS_SRC)/portable/GCC/$(FREERTOS_PORT)/port.c + $(subst ../../../,,$(wildcard ../../../$(FREERTOS_SRC)/portable/GCC/$(FREERTOS_PORT)/*.c)) # FreeRTOS (lto + Os) linker issue LDFLAGS += -Wl,--undefined=vTaskSwitchContext diff --git a/examples/device/cdc_msc_freertos/src/FreeRTOSConfig.h b/examples/device/cdc_msc_freertos/src/FreeRTOSConfig.h index 309a9a01..8083cad7 100644 --- a/examples/device/cdc_msc_freertos/src/FreeRTOSConfig.h +++ b/examples/device/cdc_msc_freertos/src/FreeRTOSConfig.h @@ -103,6 +103,15 @@ #error "FreeRTOSConfig.h need to include low level mcu header for configuration" #endif +extern uint32_t SystemCoreClock; + + +/* Cortex M23/M33 port configuration. */ +#define configENABLE_MPU 0 +#define configENABLE_FPU 1 +#define configENABLE_TRUSTZONE 0 +#define configMINIMAL_SECURE_STACK_SIZE ( 1024 ) + #define configUSE_PREEMPTION 1 #define configUSE_PORT_OPTIMISED_TASK_SELECTION 0 #define configCPU_CLOCK_HZ SystemCoreClock diff --git a/hw/bsp/ea4357/board.mk b/hw/bsp/ea4357/board.mk index d79cf141..dc002215 100644 --- a/hw/bsp/ea4357/board.mk +++ b/hw/bsp/ea4357/board.mk @@ -3,6 +3,8 @@ CFLAGS += \ -mthumb \ -mabi=aapcs \ -mcpu=cortex-m4 \ + -mfloat-abi=hard \ + -mfpu=fpv4-sp-d16 \ -nostdlib \ -DCORE_M4 \ -DCFG_TUSB_MCU=OPT_MCU_LPC43XX \ diff --git a/hw/bsp/lpcxpresso55s69/board.mk b/hw/bsp/lpcxpresso55s69/board.mk index 5977ce9f..722f6c6c 100644 --- a/hw/bsp/lpcxpresso55s69/board.mk +++ b/hw/bsp/lpcxpresso55s69/board.mk @@ -39,7 +39,7 @@ VENDOR = nxp CHIP_FAMILY = lpc_ip3511 # For freeRTOS port source -FREERTOS_PORT = ARM_CM33 +FREERTOS_PORT = ARM_CM33/non_secure # For flash-jlink target JLINK_DEVICE = LPC55S69 diff --git a/hw/bsp/mimxrt1010_evk/board.mk b/hw/bsp/mimxrt1010_evk/board.mk index 7b61cb24..4dc11693 100644 --- a/hw/bsp/mimxrt1010_evk/board.mk +++ b/hw/bsp/mimxrt1010_evk/board.mk @@ -42,7 +42,7 @@ VENDOR = nxp CHIP_FAMILY = transdimension # For freeRTOS port source -FREERTOS_PORT = ARM_CM7 +FREERTOS_PORT = ARM_CM7/r0p1 # For flash-jlink target JLINK_DEVICE = MIMXRT1011DAE5A diff --git a/hw/bsp/mimxrt1015_evk/board.mk b/hw/bsp/mimxrt1015_evk/board.mk index a538c7dc..abb6bc38 100644 --- a/hw/bsp/mimxrt1015_evk/board.mk +++ b/hw/bsp/mimxrt1015_evk/board.mk @@ -41,7 +41,7 @@ VENDOR = nxp CHIP_FAMILY = transdimension # For freeRTOS port source -FREERTOS_PORT = ARM_CM7 +FREERTOS_PORT = ARM_CM7/r0p1 # For flash-jlink target JLINK_DEVICE = MIMXRT1015DAF5A diff --git a/hw/bsp/mimxrt1020_evk/board.mk b/hw/bsp/mimxrt1020_evk/board.mk index 83a57085..5720da95 100644 --- a/hw/bsp/mimxrt1020_evk/board.mk +++ b/hw/bsp/mimxrt1020_evk/board.mk @@ -42,7 +42,7 @@ VENDOR = nxp CHIP_FAMILY = transdimension # For freeRTOS port source -FREERTOS_PORT = ARM_CM7 +FREERTOS_PORT = ARM_CM7/r0p1 # For flash-jlink target JLINK_DEVICE = MIMXRT1021DAG5A diff --git a/hw/bsp/mimxrt1050_evkb/board.mk b/hw/bsp/mimxrt1050_evkb/board.mk index 2303df11..de07cdb0 100644 --- a/hw/bsp/mimxrt1050_evkb/board.mk +++ b/hw/bsp/mimxrt1050_evkb/board.mk @@ -42,7 +42,7 @@ VENDOR = nxp CHIP_FAMILY = transdimension # For freeRTOS port source -FREERTOS_PORT = ARM_CM7 +FREERTOS_PORT = ARM_CM7/r0p1 # For flash-jlink target JLINK_DEVICE = MIMXRT1052xxx6B diff --git a/hw/bsp/mimxrt1060_evk/board.mk b/hw/bsp/mimxrt1060_evk/board.mk index 4bfc48bb..2f6d0f7a 100644 --- a/hw/bsp/mimxrt1060_evk/board.mk +++ b/hw/bsp/mimxrt1060_evk/board.mk @@ -42,7 +42,7 @@ VENDOR = nxp CHIP_FAMILY = transdimension # For freeRTOS port source -FREERTOS_PORT = ARM_CM7 +FREERTOS_PORT = ARM_CM7/r0p1 # For flash-jlink target JLINK_DEVICE = MIMXRT1062xxx6A diff --git a/hw/bsp/mimxrt1064_evk/board.mk b/hw/bsp/mimxrt1064_evk/board.mk index 7b992da3..6ebf2327 100644 --- a/hw/bsp/mimxrt1064_evk/board.mk +++ b/hw/bsp/mimxrt1064_evk/board.mk @@ -42,7 +42,7 @@ VENDOR = nxp CHIP_FAMILY = transdimension # For freeRTOS port source -FREERTOS_PORT = ARM_CM7 +FREERTOS_PORT = ARM_CM7/r0p1 # For flash-jlink target JLINK_DEVICE = MIMXRT1064xxx6A diff --git a/hw/bsp/teensy_40/board.mk b/hw/bsp/teensy_40/board.mk index 955603e3..6ec04a47 100644 --- a/hw/bsp/teensy_40/board.mk +++ b/hw/bsp/teensy_40/board.mk @@ -42,7 +42,7 @@ VENDOR = nxp CHIP_FAMILY = transdimension # For freeRTOS port source -FREERTOS_PORT = ARM_CM7 +FREERTOS_PORT = ARM_CM7/r0p1 # For flash-jlink target JLINK_DEVICE = MIMXRT1062xxx6A From ba74223c2e93e95ac1479ed86379852adaf8141b Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 11 Mar 2020 00:58:28 +0700 Subject: [PATCH 260/267] fix more build --- examples/device/cdc_msc_freertos/src/FreeRTOSConfig.h | 9 +++++++-- hw/bsp/ngx4330/board.mk | 2 ++ hw/bsp/nutiny_sdk_nuc505/board.mk | 2 ++ hw/bsp/stm32f767nucleo/board.mk | 3 +++ hw/bsp/stm32h743nucleo/board.mk | 3 +++ 5 files changed, 17 insertions(+), 2 deletions(-) diff --git a/examples/device/cdc_msc_freertos/src/FreeRTOSConfig.h b/examples/device/cdc_msc_freertos/src/FreeRTOSConfig.h index 8083cad7..ac274b5f 100644 --- a/examples/device/cdc_msc_freertos/src/FreeRTOSConfig.h +++ b/examples/device/cdc_msc_freertos/src/FreeRTOSConfig.h @@ -95,10 +95,15 @@ #elif CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX #include "fsl_device_registers.h" -#elif CFG_TUSB_MCU == OPT_MCU_NUC120 || CFG_TUSB_MCU == OPT_MCU_NUC121 || \ - CFG_TUSB_MCU == OPT_MCU_NUC126 || CFG_TUSB_MCU == OPT_MCU_NUC505 +#elif CFG_TUSB_MCU == OPT_MCU_NUC120 + #include "NUC100Series.h" + +#elif CFG_TUSB_MCU == OPT_MCU_NUC121 || CFG_TUSB_MCU == OPT_MCU_NUC126 #include "NuMicro.h" +#elif CFG_TUSB_MCU == OPT_MCU_NUC505 + #include "NUC505Series.h" + #else #error "FreeRTOSConfig.h need to include low level mcu header for configuration" #endif diff --git a/hw/bsp/ngx4330/board.mk b/hw/bsp/ngx4330/board.mk index df9df63a..97c24b40 100644 --- a/hw/bsp/ngx4330/board.mk +++ b/hw/bsp/ngx4330/board.mk @@ -3,6 +3,8 @@ CFLAGS += \ -mthumb \ -mabi=aapcs \ -mcpu=cortex-m4 \ + -mfloat-abi=hard \ + -mfpu=fpv4-sp-d16 \ -nostdlib \ -DCORE_M4 \ -DCFG_TUSB_MCU=OPT_MCU_LPC43XX \ diff --git a/hw/bsp/nutiny_sdk_nuc505/board.mk b/hw/bsp/nutiny_sdk_nuc505/board.mk index 1c1cbcf0..39df77d2 100644 --- a/hw/bsp/nutiny_sdk_nuc505/board.mk +++ b/hw/bsp/nutiny_sdk_nuc505/board.mk @@ -3,6 +3,8 @@ CFLAGS += \ -mthumb \ -mabi=aapcs-linux \ -mcpu=cortex-m4 \ + -mfloat-abi=hard \ + -mfpu=fpv4-sp-d16 \ -DCFG_TUSB_MCU=OPT_MCU_NUC505 # All source paths should be relative to the top level. diff --git a/hw/bsp/stm32f767nucleo/board.mk b/hw/bsp/stm32f767nucleo/board.mk index 8d733b9b..e5f0736d 100644 --- a/hw/bsp/stm32f767nucleo/board.mk +++ b/hw/bsp/stm32f767nucleo/board.mk @@ -41,5 +41,8 @@ INC += \ VENDOR = st CHIP_FAMILY = synopsys +# For freeRTOS port source +FREERTOS_PORT = ARM_CM7/r0p1 + # flash target using on-board stlink flash: flash-stlink diff --git a/hw/bsp/stm32h743nucleo/board.mk b/hw/bsp/stm32h743nucleo/board.mk index a45c667d..94cc44b5 100644 --- a/hw/bsp/stm32h743nucleo/board.mk +++ b/hw/bsp/stm32h743nucleo/board.mk @@ -40,5 +40,8 @@ INC += \ VENDOR = st CHIP_FAMILY = synopsys +# For freeRTOS port source +FREERTOS_PORT = ARM_CM7/r0p1 + # flash target using on-board stlink flash: flash-stlink From 4e6d464c7a073fe0b330d5087ebc4671ea3c47a5 Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 11 Mar 2020 10:25:46 +0700 Subject: [PATCH 261/267] add cdc_msc_freertos to ci --- .github/workflows/build.yml | 5 +++-- tools/build_all.py | 3 --- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 54d4baba..4cf2f139 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -24,8 +24,9 @@ jobs: strategy: fail-fast: false matrix: - example: ['board_test', 'cdc_dual_ports', 'cdc_msc', 'dfu_rt', 'hid_composite', 'hid_generic_inout', - 'midi_test', 'msc_dual_lun', 'net_lwip_webserver', 'usbtmc', 'webusb_serial'] + example: ['board_test', 'cdc_dual_ports', 'cdc_msc', 'cdc_msc_freertos', 'dfu_rt', + 'hid_composite', 'hid_generic_inout', 'midi_test', 'msc_dual_lun', 'net_lwip_webserver', + 'usbtmc', 'webusb_serial'] steps: - name: Setup Python uses: actions/setup-python@v1 diff --git a/tools/build_all.py b/tools/build_all.py index 4f3e2874..08964bb7 100644 --- a/tools/build_all.py +++ b/tools/build_all.py @@ -19,9 +19,6 @@ else: for entry in os.scandir("examples/device"): if entry.is_dir(): all_examples.append(entry.name) - - # TODO update freeRTOS example to work with all boards (only nrf52840 now) - all_examples.remove("cdc_msc_hid_freertos") all_examples.sort() # 2nd Argument is Board, build all boards if not existed From cc494ab58521c8393240844f3f8f46347a44fc03 Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 11 Mar 2020 11:57:38 +0700 Subject: [PATCH 262/267] skip spresense --- examples/device/cdc_msc_freertos/.skip.MCU_CXD56 | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 examples/device/cdc_msc_freertos/.skip.MCU_CXD56 diff --git a/examples/device/cdc_msc_freertos/.skip.MCU_CXD56 b/examples/device/cdc_msc_freertos/.skip.MCU_CXD56 new file mode 100644 index 00000000..e69de29b From 5fa1e6e242f08d340a46b9a8c885b8495dbe2c76 Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 11 Mar 2020 12:32:29 +0700 Subject: [PATCH 263/267] hack to undef LITTLE_ENDIAN for samg55 --- examples/device/cdc_msc_freertos/src/FreeRTOSConfig.h | 7 +++++-- hw/bsp/board.h | 7 +++++-- hw/bsp/lpcxpresso55s69/board.mk | 2 +- hw/bsp/samg55xplained/board.mk | 3 ++- 4 files changed, 13 insertions(+), 6 deletions(-) diff --git a/examples/device/cdc_msc_freertos/src/FreeRTOSConfig.h b/examples/device/cdc_msc_freertos/src/FreeRTOSConfig.h index ac274b5f..0945baf1 100644 --- a/examples/device/cdc_msc_freertos/src/FreeRTOSConfig.h +++ b/examples/device/cdc_msc_freertos/src/FreeRTOSConfig.h @@ -58,8 +58,11 @@ #elif CFG_TUSB_MCU == OPT_MCU_NRF5X #include "nrf.h" -#elif CFG_TUSB_MCU == OPT_MCU_SAMD21 || CFG_TUSB_MCU == OPT_MCU_SAMD51 || \ - CFG_TUSB_MCU == OPT_MCU_SAMG +#elif CFG_TUSB_MCU == OPT_MCU_SAMD21 || CFG_TUSB_MCU == OPT_MCU_SAMD51 + #include "sam.h" + +#elif CFG_TUSB_MCU == OPT_MCU_SAMG + #undef LITTLE_ENDIAN // hack to suppress "LITTLE_ENDIAN" redefined #include "sam.h" #elif CFG_TUSB_MCU == OPT_MCU_STM32F0 diff --git a/hw/bsp/board.h b/hw/bsp/board.h index 4c5716d9..a8f973a7 100644 --- a/hw/bsp/board.h +++ b/hw/bsp/board.h @@ -39,7 +39,6 @@ #include #include "ansi_escape.h" - #include "tusb.h" #define CFG_BOARD_UART_BAUDRATE 115200 @@ -68,18 +67,21 @@ int board_uart_write(void const * buf, int len); #if CFG_TUSB_OS == OPT_OS_NONE // Get current milliseconds, must be implemented when no RTOS is used uint32_t board_millis(void); + #elif CFG_TUSB_OS == OPT_OS_FREERTOS static inline uint32_t board_millis(void) { return ( ( ((uint64_t) xTaskGetTickCount()) * 1000) / configTICK_RATE_HZ ); } + #elif CFG_TUSB_OS == OPT_OS_MYNEWT static inline uint32_t board_millis(void) { return os_time_ticks_to_ms32( os_time_get() ); } + #else - #error "Need to implement board_millis() for this OS" + #error "board_millis() is not implemented for this OS" #endif //--------------------------------------------------------------------+ @@ -95,6 +97,7 @@ static inline void board_led_off(void) board_led_write(false); } +// TODO remove static inline void board_delay(uint32_t ms) { uint32_t start_ms = board_millis(); diff --git a/hw/bsp/lpcxpresso55s69/board.mk b/hw/bsp/lpcxpresso55s69/board.mk index 722f6c6c..4cb2d00e 100644 --- a/hw/bsp/lpcxpresso55s69/board.mk +++ b/hw/bsp/lpcxpresso55s69/board.mk @@ -39,7 +39,7 @@ VENDOR = nxp CHIP_FAMILY = lpc_ip3511 # For freeRTOS port source -FREERTOS_PORT = ARM_CM33/non_secure +FREERTOS_PORT = ARM_CM33_NTZ/non_secure # For flash-jlink target JLINK_DEVICE = LPC55S69 diff --git a/hw/bsp/samg55xplained/board.mk b/hw/bsp/samg55xplained/board.mk index 1fd13746..e0c24ed9 100644 --- a/hw/bsp/samg55xplained/board.mk +++ b/hw/bsp/samg55xplained/board.mk @@ -9,7 +9,8 @@ CFLAGS += \ -D__SAMG55J19__ \ -DCFG_TUSB_MCU=OPT_MCU_SAMG -#CFLAGS += -Wno-error=undef +# suppress following warnings from mcu driver +CFLAGS += -Wno-error=undef ASF_DIR = hw/mcu/microchip/samg55 From 7f6316dbe1c98d2f00ded0913176a85e871353fa Mon Sep 17 00:00:00 2001 From: Nathan Conrad Date: Sat, 14 Mar 2020 14:22:08 -0400 Subject: [PATCH 264/267] Use CRLF on UART. --- examples/device/board_test/src/main.c | 2 +- src/class/cdc/cdc_device.c | 6 +++--- src/class/msc/msc_device.c | 6 +++--- src/common/tusb_common.h | 2 +- src/common/tusb_verify.h | 4 ++-- src/device/usbd_control.c | 6 +++--- 6 files changed, 13 insertions(+), 13 deletions(-) diff --git a/examples/device/board_test/src/main.c b/examples/device/board_test/src/main.c index 86582174..584ff799 100644 --- a/examples/device/board_test/src/main.c +++ b/examples/device/board_test/src/main.c @@ -42,7 +42,7 @@ enum { BLINK_UNPRESSED = 1000 }; -#define HELLO_STR "Hello from TinyUSB\n" +#define HELLO_STR "Hello from TinyUSB\r\n" int main(void) { diff --git a/src/class/cdc/cdc_device.c b/src/class/cdc/cdc_device.c index f63418da..14b9a315 100644 --- a/src/class/cdc/cdc_device.c +++ b/src/class/cdc/cdc_device.c @@ -335,12 +335,12 @@ bool cdcd_control_request(uint8_t rhport, tusb_control_request_t const * request switch ( request->bRequest ) { case CDC_REQUEST_SET_LINE_CODING: - TU_LOG2(" Set Line Coding\n"); + TU_LOG2(" Set Line Coding\r\n"); tud_control_xfer(rhport, request, &p_cdc->line_coding, sizeof(cdc_line_coding_t)); break; case CDC_REQUEST_GET_LINE_CODING: - TU_LOG2(" Get Line Coding\n"); + TU_LOG2(" Get Line Coding\r\n"); tud_control_xfer(rhport, request, &p_cdc->line_coding, sizeof(cdc_line_coding_t)); break; @@ -356,7 +356,7 @@ bool cdcd_control_request(uint8_t rhport, tusb_control_request_t const * request p_cdc->line_state = (uint8_t) request->wValue; - TU_LOG2(" Set Control Line State: DTR = %d, RTS = %d\n", dtr, rts); + TU_LOG2(" Set Control Line State: DTR = %d, RTS = %d\r\n", dtr, rts); tud_control_status(rhport, request); diff --git a/src/class/msc/msc_device.c b/src/class/msc/msc_device.c index 3ff0eba9..06cc9dbb 100644 --- a/src/class/msc/msc_device.c +++ b/src/class/msc/msc_device.c @@ -407,7 +407,7 @@ bool mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t TU_ASSERT( event == XFER_RESULT_SUCCESS && xferred_bytes == sizeof(msc_cbw_t) && p_cbw->signature == MSC_CBW_SIGNATURE ); - TU_LOG2(" SCSI Command: %s\n", lookup_find(&_msc_scsi_cmd_table, p_cbw->command[0])); + TU_LOG2(" SCSI Command: %s\r\n", lookup_find(&_msc_scsi_cmd_table, p_cbw->command[0])); // TU_LOG2_MEM(p_cbw, xferred_bytes, 2); p_csw->signature = MSC_CSW_SIGNATURE; @@ -480,7 +480,7 @@ bool mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t break; case MSC_STAGE_DATA: - TU_LOG2(" SCSI Data\n"); + TU_LOG2(" SCSI Data\r\n"); //TU_LOG2_MEM(_mscd_buf, xferred_bytes, 2); // OUT transfer, invoke callback if needed @@ -577,7 +577,7 @@ bool mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t // Wait for the Status phase to complete if( (ep_addr == p_msc->ep_in) && (xferred_bytes == sizeof(msc_csw_t)) ) { - TU_LOG2(" SCSI Status: %u\n", p_csw->status); + TU_LOG2(" SCSI Status: %u\r\n", p_csw->status); // TU_LOG2_MEM(p_csw, xferred_bytes, 2); // Move to default CMD stage diff --git a/src/common/tusb_common.h b/src/common/tusb_common.h index 5e6a8bb1..ef232a59 100644 --- a/src/common/tusb_common.h +++ b/src/common/tusb_common.h @@ -222,7 +222,7 @@ void tu_print_mem(void const *buf, uint16_t count, uint8_t indent); // Log with debug level 1 #define TU_LOG1 tu_printf #define TU_LOG1_MEM tu_print_mem -#define TU_LOG1_LOCATION() tu_printf("%s: %d:\n", __PRETTY_FUNCTION__, __LINE__) +#define TU_LOG1_LOCATION() tu_printf("%s: %d:\r\n", __PRETTY_FUNCTION__, __LINE__) // Log with debug level 2 #if CFG_TUSB_DEBUG > 1 diff --git a/src/common/tusb_verify.h b/src/common/tusb_verify.h index 1ad6d3fb..74150d6c 100644 --- a/src/common/tusb_verify.h +++ b/src/common/tusb_verify.h @@ -76,8 +76,8 @@ #if CFG_TUSB_DEBUG #include - #define _MESS_ERR(_err) printf("%s %d: failed, error = %s\n", __func__, __LINE__, tusb_strerr[_err]) - #define _MESS_FAILED() printf("%s %d: assert failed\n", __func__, __LINE__) + #define _MESS_ERR(_err) printf("%s %d: failed, error = %s\r\n", __func__, __LINE__, tusb_strerr[_err]) + #define _MESS_FAILED() printf("%s %d: assert failed\r\n", __func__, __LINE__) #else #define _MESS_ERR(_err) #define _MESS_FAILED() diff --git a/src/device/usbd_control.c b/src/device/usbd_control.c index f0a4cf84..7c35fe76 100644 --- a/src/device/usbd_control.c +++ b/src/device/usbd_control.c @@ -63,7 +63,7 @@ static inline bool _status_stage_xact(uint8_t rhport, tusb_control_request_t con // Opposite to endpoint in Data Phase uint8_t const ep_addr = request->bmRequestType_bit.direction ? EDPT_CTRL_OUT : EDPT_CTRL_IN; - TU_LOG2(" XFER Endpoint: 0x%02X, Bytes: %d\n", ep_addr, 0); + TU_LOG2(" XFER Endpoint: 0x%02X, Bytes: %d\r\n", ep_addr, 0); // status direction is reversed to one in the setup packet // Note: Status must always be DATA1 @@ -96,7 +96,7 @@ static bool _data_stage_xact(uint8_t rhport) if ( xact_len ) memcpy(_usbd_ctrl_buf, _ctrl_xfer.buffer, xact_len); } - TU_LOG2(" XACT Control: 0x%02X, Bytes: %d\n", ep_addr, xact_len); + TU_LOG2(" XACT Control: 0x%02X, Bytes: %d\r\n", ep_addr, xact_len); return dcd_edpt_xfer(rhport, ep_addr, xact_len ? _usbd_ctrl_buf : NULL, xact_len); } @@ -112,7 +112,7 @@ bool tud_control_xfer(uint8_t rhport, tusb_control_request_t const * request, vo { TU_ASSERT(buffer); - TU_LOG2(" XFER Endpoint: 0x%02X, Bytes: %d\n", request->bmRequestType_bit.direction ? EDPT_CTRL_IN : EDPT_CTRL_OUT, _ctrl_xfer.data_len); + TU_LOG2(" XFER Endpoint: 0x%02X, Bytes: %d\r\n", request->bmRequestType_bit.direction ? EDPT_CTRL_IN : EDPT_CTRL_OUT, _ctrl_xfer.data_len); // Data stage TU_ASSERT( _data_stage_xact(rhport) ); From 5e8ff1f7c2887abb5459b0d9d6812e2da437d4d0 Mon Sep 17 00:00:00 2001 From: Peter Lawrence <12226419+majbthrd@users.noreply.github.com> Date: Sun, 15 Mar 2020 16:05:45 -0500 Subject: [PATCH 265/267] usb RNDIS revision on @pigrew suggestions --- src/class/net/net_device.c | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/class/net/net_device.c b/src/class/net/net_device.c index d0d32e90..7bb11d57 100644 --- a/src/class/net/net_device.c +++ b/src/class/net/net_device.c @@ -198,7 +198,17 @@ bool netd_control_request(uint8_t rhport, tusb_control_request_t const * request TU_VERIFY (_netd_itf.itf_num == request->wIndex); #if CFG_TUD_NET == OPT_NET_RNDIS - tud_control_xfer(rhport, request, rndis_buf, sizeof(rndis_buf)); + if (request->bmRequestType_bit.direction == TUSB_DIR_IN) + { + rndis_generic_msg_t *rndis_msg = (rndis_generic_msg_t *)rndis_buf; + uint32_t msglen = tu_le32toh(rndis_msg->MessageLength); + TU_ASSERT(msglen <= sizeof(rndis_buf)); + tud_control_xfer(rhport, request, rndis_buf, msglen); + } + else + { + tud_control_xfer(rhport, request, rndis_buf, sizeof(rndis_buf)); + } #else (void)rhport; #endif From fb56c02a6f7cc03b2f9fd970a5b1bc772ccf4795 Mon Sep 17 00:00:00 2001 From: Peter Lawrence <12226419+majbthrd@users.noreply.github.com> Date: Sun, 15 Mar 2020 17:10:14 -0500 Subject: [PATCH 266/267] NUC505 : fix operation with net_lwip_webserver --- examples/device/net_lwip_webserver/src/tusb_config.h | 2 +- src/portable/nuvoton/nuc505/dcd_nuc505.c | 8 ++++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/examples/device/net_lwip_webserver/src/tusb_config.h b/examples/device/net_lwip_webserver/src/tusb_config.h index 329fc80b..0b40fefa 100644 --- a/examples/device/net_lwip_webserver/src/tusb_config.h +++ b/examples/device/net_lwip_webserver/src/tusb_config.h @@ -39,7 +39,7 @@ #error CFG_TUSB_MCU must be defined #endif -#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX +#if CFG_TUSB_MCU == OPT_MCU_LPC43XX || CFG_TUSB_MCU == OPT_MCU_LPC18XX || CFG_TUSB_MCU == OPT_MCU_MIMXRT10XX || CFG_TUSB_MCU == OPT_MCU_NUC505 #define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED) #else #define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE diff --git a/src/portable/nuvoton/nuc505/dcd_nuc505.c b/src/portable/nuvoton/nuc505/dcd_nuc505.c index 2b6a66bc..031bfc5e 100644 --- a/src/portable/nuvoton/nuc505/dcd_nuc505.c +++ b/src/portable/nuvoton/nuc505/dcd_nuc505.c @@ -211,6 +211,7 @@ static void bus_reset(void) current_dma_xfer = NULL; } +#if 0 /* this must only be called by the ISR; it does its best to share the single DMA engine across all user EPs (IN and OUT) */ static void service_dma(void) { @@ -243,6 +244,7 @@ static void service_dma(void) return; } } +#endif /* centralized location for USBD interrupt enable bit masks */ static const uint32_t enabled_irqs = USBD_GINTEN_USBIEN_Msk | \ @@ -366,7 +368,7 @@ bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t *buffer, uint16_t to for (int count = 0; count < total_bytes; count++) *buffer++ = USBD->CEPDAT_BYTE; - usb_control_send_zlp(); + dcd_event_xfer_complete(0, ep_addr, total_bytes, XFER_RESULT_SUCCESS, true); } } else @@ -465,6 +467,7 @@ void USBD_IRQHandler(void) if (bus_state & USBD_BUSINTSTS_DMADONEIF_Msk) { +#if 0 if (current_dma_xfer) { current_dma_xfer->dma_requested = false; @@ -480,6 +483,7 @@ void USBD_IRQHandler(void) current_dma_xfer = NULL; service_dma(); } +#endif } if (bus_state & USBD_BUSINTSTS_VBUSDETIF_Msk) @@ -597,7 +601,7 @@ void USBD_IRQHandler(void) if (out_ep) { -#if 1 +#if 0 xfer->dma_requested = true; service_dma(); #else From df05440d92f0d05532476df5f544d00751f03bce Mon Sep 17 00:00:00 2001 From: Peter Lawrence <12226419+majbthrd@users.noreply.github.com> Date: Mon, 16 Mar 2020 13:20:17 -0500 Subject: [PATCH 267/267] NUC505 : added comment on DMA choice --- src/portable/nuvoton/nuc505/dcd_nuc505.c | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/portable/nuvoton/nuc505/dcd_nuc505.c b/src/portable/nuvoton/nuc505/dcd_nuc505.c index 031bfc5e..e05e73ef 100644 --- a/src/portable/nuvoton/nuc505/dcd_nuc505.c +++ b/src/portable/nuvoton/nuc505/dcd_nuc505.c @@ -33,6 +33,12 @@ nomenclature of EPA through EPL. */ +/* + Note on OPT_MCU_NUC505_USB_DMA: the author suggests against using this option. + The DMA functionality of the USBD peripheral does not appear to succeed with + transfer lengths that are longer (> 64 bytes) and are not a multiple of 4. +*/ + #include "tusb_option.h" #if TUSB_OPT_DEVICE_ENABLED && (CFG_TUSB_MCU == OPT_MCU_NUC505) @@ -211,7 +217,7 @@ static void bus_reset(void) current_dma_xfer = NULL; } -#if 0 +#ifdef OPT_MCU_NUC505_USB_DMA /* this must only be called by the ISR; it does its best to share the single DMA engine across all user EPs (IN and OUT) */ static void service_dma(void) { @@ -467,7 +473,7 @@ void USBD_IRQHandler(void) if (bus_state & USBD_BUSINTSTS_DMADONEIF_Msk) { -#if 0 +#ifdef OPT_MCU_NUC505_USB_DMA if (current_dma_xfer) { current_dma_xfer->dma_requested = false; @@ -601,7 +607,7 @@ void USBD_IRQHandler(void) if (out_ep) { -#if 0 +#ifdef OPT_MCU_NUC505_USB_DMA xfer->dma_requested = true; service_dma(); #else