From 3ea2f152f07f666ee058f485424d94e8ceff587f Mon Sep 17 00:00:00 2001 From: Neucrack Date: Thu, 28 Mar 2019 11:44:34 +0800 Subject: [PATCH] remove sdk --- .../kendryte-standalone-sdk/.gitignore | 814 --- .../kendryte-standalone-sdk/.travis.yml | 74 - .../kendryte-standalone-sdk/CHANGELOG.md | 94 - .../kendryte-standalone-sdk/CMakeLists.txt | 31 - cores/arduino/kendryte-standalone-sdk/LICENSE | 202 - .../arduino/kendryte-standalone-sdk/README.md | 25 - .../kendryte-standalone-sdk/lds/kendryte.ld | 252 - .../lib/CMakeLists.txt | 27 - .../kendryte-standalone-sdk/lib/bsp/crt.S | 318 - .../kendryte-standalone-sdk/lib/bsp/entry.c | 37 - .../lib/bsp/entry_user.c | 102 - .../lib/bsp/include/atomic.h | 243 - .../lib/bsp/include/bsp.h | 7 - .../lib/bsp/include/dump.h | 141 - .../lib/bsp/include/encoding.h | 1326 ---- .../lib/bsp/include/entry.h | 81 - .../lib/bsp/include/interrupt.h | 47 - .../lib/bsp/include/platform.h | 99 - .../lib/bsp/include/printf.h | 209 - .../lib/bsp/include/sleep.h | 36 - .../lib/bsp/include/syscalls.h | 46 - .../lib/bsp/include/util.h | 198 - .../lib/bsp/interrupt.c | 66 - .../kendryte-standalone-sdk/lib/bsp/printf.c | 653 -- .../kendryte-standalone-sdk/lib/bsp/sleep.c | 39 - .../lib/bsp/syscalls.c | 631 -- .../kendryte-standalone-sdk/lib/drivers/aes.c | 803 --- .../kendryte-standalone-sdk/lib/drivers/apu.c | 513 -- .../lib/drivers/clint.c | 219 - .../lib/drivers/dmac.c | 792 --- .../kendryte-standalone-sdk/lib/drivers/dvp.c | 297 - .../kendryte-standalone-sdk/lib/drivers/fft.c | 68 - .../lib/drivers/fpioa.c | 5430 ----------------- .../lib/drivers/gpio.c | 79 - .../lib/drivers/gpiohs.c | 218 - .../kendryte-standalone-sdk/lib/drivers/i2c.c | 251 - .../kendryte-standalone-sdk/lib/drivers/i2s.c | 636 -- .../lib/drivers/include/aes.h | 767 --- .../lib/drivers/include/apu.h | 323 - .../lib/drivers/include/clint.h | 338 - .../lib/drivers/include/dmac.h | 1542 ----- .../lib/drivers/include/dvp.h | 269 - .../lib/drivers/include/fft.h | 247 - .../lib/drivers/include/fpioa.h | 1003 --- .../lib/drivers/include/gpio.h | 168 - .../lib/drivers/include/gpio_common.h | 51 - .../lib/drivers/include/gpiohs.h | 267 - .../lib/drivers/include/i2c.h | 446 -- .../lib/drivers/include/i2s.h | 753 --- .../lib/drivers/include/io.h | 50 - .../lib/drivers/include/kpu.h | 848 --- .../lib/drivers/include/plic.h | 492 -- .../lib/drivers/include/pwm.h | 74 - .../lib/drivers/include/rtc.h | 398 -- .../lib/drivers/include/sha256.h | 128 - .../lib/drivers/include/spi.h | 460 -- .../lib/drivers/include/sysctl.h | 1078 ---- .../lib/drivers/include/timer.h | 161 - .../lib/drivers/include/uart.h | 334 - .../lib/drivers/include/uarths.h | 292 - .../lib/drivers/include/utils.h | 347 -- .../lib/drivers/include/wdt.h | 170 - .../kendryte-standalone-sdk/lib/drivers/kpu.c | 1521 ----- .../lib/drivers/plic.c | 209 - .../kendryte-standalone-sdk/lib/drivers/pwm.c | 58 - .../kendryte-standalone-sdk/lib/drivers/rtc.c | 587 -- .../lib/drivers/sha256.c | 120 - .../kendryte-standalone-sdk/lib/drivers/spi.c | 1298 ---- .../lib/drivers/sysctl.c | 1860 ------ .../lib/drivers/timer.c | 391 -- .../lib/drivers/uart.c | 338 - .../lib/drivers/uarths.c | 176 - .../lib/drivers/utils.c | 44 - .../kendryte-standalone-sdk/lib/drivers/wdt.c | 115 - .../lib/freertos/conf/FreeRTOSConfig.h | 142 - .../lib/freertos/core_sync.c | 100 - .../lib/freertos/croutine.c | 367 -- .../lib/freertos/event_groups.c | 752 --- .../lib/freertos/include/FreeRTOS.h | 1183 ---- .../lib/freertos/include/StackMacros.h | 147 - .../lib/freertos/include/core_sync.h | 43 - .../lib/freertos/include/croutine.h | 734 --- .../lib/freertos/include/event_groups.h | 770 --- .../lib/freertos/include/list.h | 425 -- .../lib/freertos/include/message_buffer.h | 793 --- .../lib/freertos/include/mpu_prototypes.h | 169 - .../lib/freertos/include/mpu_wrappers.h | 195 - .../lib/freertos/include/portable.h | 178 - .../lib/freertos/include/projdefs.h | 138 - .../lib/freertos/include/queue.h | 1667 ----- .../lib/freertos/include/semphr.h | 1154 ---- .../lib/freertos/include/stack_macros.h | 143 - .../lib/freertos/include/stdint.readme | 27 - .../lib/freertos/include/stream_buffer.h | 866 --- .../lib/freertos/include/task.h | 2363 ------- .../lib/freertos/include/timers.h | 1291 ---- .../lib/freertos/list.c | 212 - .../lib/freertos/locks.c | 48 - .../lib/freertos/os_entry.c | 49 - .../lib/freertos/portable/heap_4.c | 451 -- .../lib/freertos/portable/port.c | 208 - .../lib/freertos/portable/portasm.S | 287 - .../lib/freertos/portable/portmacro.h | 162 - .../lib/freertos/pthread.c | 4 - .../lib/freertos/queue.c | 2923 --------- .../lib/freertos/readme.txt | 17 - .../lib/freertos/stream_buffer.c | 1213 ---- .../lib/freertos/tasks.c | 5149 ---------------- .../lib/freertos/timers.c | 1090 ---- .../lib/utils/include/syslog.h | 141 - 110 files changed, 58428 deletions(-) delete mode 100644 cores/arduino/kendryte-standalone-sdk/.gitignore delete mode 100644 cores/arduino/kendryte-standalone-sdk/.travis.yml delete mode 100644 cores/arduino/kendryte-standalone-sdk/CHANGELOG.md delete mode 100644 cores/arduino/kendryte-standalone-sdk/CMakeLists.txt delete mode 100644 cores/arduino/kendryte-standalone-sdk/LICENSE delete mode 100644 cores/arduino/kendryte-standalone-sdk/README.md delete mode 100644 cores/arduino/kendryte-standalone-sdk/lds/kendryte.ld delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/CMakeLists.txt delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/bsp/crt.S delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/bsp/entry.c delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/bsp/entry_user.c delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/bsp/include/atomic.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/bsp/include/bsp.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/bsp/include/dump.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/bsp/include/encoding.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/bsp/include/entry.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/bsp/include/interrupt.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/bsp/include/platform.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/bsp/include/printf.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/bsp/include/sleep.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/bsp/include/syscalls.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/bsp/include/util.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/bsp/interrupt.c delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/bsp/printf.c delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/bsp/sleep.c delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/bsp/syscalls.c delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/aes.c delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/apu.c delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/clint.c delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/dmac.c delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/dvp.c delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/fft.c delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/fpioa.c delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/gpio.c delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/gpiohs.c delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/i2c.c delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/i2s.c delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/include/aes.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/include/apu.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/include/clint.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/include/dmac.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/include/dvp.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/include/fft.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/include/fpioa.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/include/gpio.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/include/gpio_common.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/include/gpiohs.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/include/i2c.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/include/i2s.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/include/io.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/include/kpu.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/include/plic.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/include/pwm.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/include/rtc.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/include/sha256.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/include/spi.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/include/sysctl.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/include/timer.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/include/uart.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/include/uarths.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/include/utils.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/include/wdt.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/kpu.c delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/plic.c delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/pwm.c delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/rtc.c delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/sha256.c delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/spi.c delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/sysctl.c delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/timer.c delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/uart.c delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/uarths.c delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/utils.c delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/drivers/wdt.c delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/freertos/conf/FreeRTOSConfig.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/freertos/core_sync.c delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/freertos/croutine.c delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/freertos/event_groups.c delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/freertos/include/FreeRTOS.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/freertos/include/StackMacros.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/freertos/include/core_sync.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/freertos/include/croutine.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/freertos/include/event_groups.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/freertos/include/list.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/freertos/include/message_buffer.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/freertos/include/mpu_prototypes.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/freertos/include/mpu_wrappers.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/freertos/include/portable.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/freertos/include/projdefs.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/freertos/include/queue.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/freertos/include/semphr.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/freertos/include/stack_macros.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/freertos/include/stdint.readme delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/freertos/include/stream_buffer.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/freertos/include/task.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/freertos/include/timers.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/freertos/list.c delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/freertos/locks.c delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/freertos/os_entry.c delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/freertos/portable/heap_4.c delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/freertos/portable/port.c delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/freertos/portable/portasm.S delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/freertos/portable/portmacro.h delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/freertos/pthread.c delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/freertos/queue.c delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/freertos/readme.txt delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/freertos/stream_buffer.c delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/freertos/tasks.c delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/freertos/timers.c delete mode 100644 cores/arduino/kendryte-standalone-sdk/lib/utils/include/syslog.h diff --git a/cores/arduino/kendryte-standalone-sdk/.gitignore b/cores/arduino/kendryte-standalone-sdk/.gitignore deleted file mode 100644 index 16d2451..0000000 --- a/cores/arduino/kendryte-standalone-sdk/.gitignore +++ /dev/null @@ -1,814 +0,0 @@ -# File created using '.gitignore Generator' for Visual Studio Code: https://bit.ly/vscode-gig - -# Created by https://www.gitignore.io/api/visualstudiocode,windows,c,c++,cmake,codeblocks,intellij+all,jetbrains+all,kdevelop4,linux,macos,osx,pycharm+all,vim,visualstudio,xcode -# Edit at https://www.gitignore.io/?templates=visualstudiocode,windows,c,c++,cmake,codeblocks,intellij+all,jetbrains+all,kdevelop4,linux,macos,osx,pycharm+all,vim,visualstudio,xcode - -### C ### -# Prerequisites -*.d - -# Object files -*.o -*.ko -*.obj -*.elf - -# Linker output -*.ilk -*.map -*.exp - -# Precompiled Headers -*.gch -*.pch - -# Libraries -*.lib -*.a -*.la -*.lo - -# Shared objects (inc. Windows DLLs) -*.dll -*.so -*.so.* -*.dylib - -# Executables -*.exe -*.out -*.app -*.i*86 -*.x86_64 -*.hex - -# Debug files -*.dSYM/ -*.su -*.idb -*.pdb - -# Kernel Module Compile Results -*.mod* -*.cmd -.tmp_versions/ -modules.order -Module.symvers -Mkfile.old -dkms.conf - -### C++ ### -# Prerequisites - -# Compiled Object files -*.slo - -# Precompiled Headers - -# Compiled Dynamic libraries - -# Fortran module files -*.mod -*.smod - -# Compiled Static libraries -*.lai - -# Executables - -### CMake ### -CMakeCache.txt -CMakeFiles -CMakeScripts -Testing -Makefile -cmake_install.cmake -install_manifest.txt -compile_commands.json -CTestTestfile.cmake - -### CodeBlocks ### -# specific to CodeBlocks IDE -*.layout -*.depend -*.cbp -# generated directories -bin/ -obj/ - -### Intellij+all ### -# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm -# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 - -# User-specific stuff -.idea/**/workspace.xml -.idea/**/tasks.xml -.idea/**/usage.statistics.xml -.idea/**/dictionaries -.idea/**/shelf - -# Generated files -.idea/**/contentModel.xml - -# Sensitive or high-churn files -.idea/**/dataSources/ -.idea/**/dataSources.ids -.idea/**/dataSources.local.xml -.idea/**/sqlDataSources.xml -.idea/**/dynamic.xml -.idea/**/uiDesigner.xml -.idea/**/dbnavigator.xml - -# Gradle -.idea/**/gradle.xml -.idea/**/libraries - -# Gradle and Maven with auto-import -# When using Gradle or Maven with auto-import, you should exclude module files, -# since they will be recreated, and may cause churn. Uncomment if using -# auto-import. -# .idea/modules.xml -# .idea/*.iml -# .idea/modules - -# CMake -cmake-build-*/ - -# Mongo Explorer plugin -.idea/**/mongoSettings.xml - -# File-based project format -*.iws - -# IntelliJ -out/ - -# mpeltonen/sbt-idea plugin -.idea_modules/ - -# JIRA plugin -atlassian-ide-plugin.xml - -# Cursive Clojure plugin -.idea/replstate.xml - -# Crashlytics plugin (for Android Studio and IntelliJ) -com_crashlytics_export_strings.xml -crashlytics.properties -crashlytics-build.properties -fabric.properties - -# Editor-based Rest Client -.idea/httpRequests - -# Android studio 3.1+ serialized cache file -.idea/caches/build_file_checksums.ser - -### Intellij+all Patch ### -# Ignores the whole .idea folder and all .iml files -# See https://github.com/joeblau/gitignore.io/issues/186 and https://github.com/joeblau/gitignore.io/issues/360 - -.idea/ - -# Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-249601023 - -*.iml -modules.xml -.idea/misc.xml -*.ipr - -### JetBrains+all ### -# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm -# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 - -# User-specific stuff - -# Generated files - -# Sensitive or high-churn files - -# Gradle - -# Gradle and Maven with auto-import -# When using Gradle or Maven with auto-import, you should exclude module files, -# since they will be recreated, and may cause churn. Uncomment if using -# auto-import. -# .idea/modules.xml -# .idea/*.iml -# .idea/modules - -# CMake - -# Mongo Explorer plugin - -# File-based project format - -# IntelliJ - -# mpeltonen/sbt-idea plugin - -# JIRA plugin - -# Cursive Clojure plugin - -# Crashlytics plugin (for Android Studio and IntelliJ) - -# Editor-based Rest Client - -# Android studio 3.1+ serialized cache file - -### JetBrains+all Patch ### -# Ignores the whole .idea folder and all .iml files -# See https://github.com/joeblau/gitignore.io/issues/186 and https://github.com/joeblau/gitignore.io/issues/360 - - -# Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-249601023 - - -### KDevelop4 ### -*.kdev4 -.kdev4/ - -### Linux ### -*~ - -# temporary files which can be created if a process still has a handle open of a deleted file -.fuse_hidden* - -# KDE directory preferences -.directory - -# Linux trash folder which might appear on any partition or disk -.Trash-* - -# .nfs files are created when an open file is removed but is still being accessed -.nfs* - -### macOS ### -# General -.DS_Store -.AppleDouble -.LSOverride - -# Icon must end with two \r -Icon - -# Thumbnails -._* - -# Files that might appear in the root of a volume -.DocumentRevisions-V100 -.fseventsd -.Spotlight-V100 -.TemporaryItems -.Trashes -.VolumeIcon.icns -.com.apple.timemachine.donotpresent - -# Directories potentially created on remote AFP share -.AppleDB -.AppleDesktop -Network Trash Folder -Temporary Items -.apdisk - -### OSX ### -# General - -# Icon must end with two \r - -# Thumbnails - -# Files that might appear in the root of a volume - -# Directories potentially created on remote AFP share - -### PyCharm+all ### -# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm -# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 - -# User-specific stuff - -# Generated files - -# Sensitive or high-churn files - -# Gradle - -# Gradle and Maven with auto-import -# When using Gradle or Maven with auto-import, you should exclude module files, -# since they will be recreated, and may cause churn. Uncomment if using -# auto-import. -# .idea/modules.xml -# .idea/*.iml -# .idea/modules - -# CMake - -# Mongo Explorer plugin - -# File-based project format - -# IntelliJ - -# mpeltonen/sbt-idea plugin - -# JIRA plugin - -# Cursive Clojure plugin - -# Crashlytics plugin (for Android Studio and IntelliJ) - -# Editor-based Rest Client - -# Android studio 3.1+ serialized cache file - -### PyCharm+all Patch ### -# Ignores the whole .idea folder and all .iml files -# See https://github.com/joeblau/gitignore.io/issues/186 and https://github.com/joeblau/gitignore.io/issues/360 - - -# Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-249601023 - - -### Vim ### -# Swap -[._]*.s[a-v][a-z] -[._]*.sw[a-p] -[._]s[a-rt-v][a-z] -[._]ss[a-gi-z] -[._]sw[a-p] - -# Session -Session.vim - -# Temporary -.netrwhist -# Auto-generated tag files -tags -# Persistent undo -[._]*.un~ - -### VisualStudioCode ### -.vscode/* -!.vscode/settings.json -!.vscode/tasks.json -!.vscode/launch.json -!.vscode/extensions.json - -### Windows ### -# Windows thumbnail cache files -Thumbs.db -ehthumbs.db -ehthumbs_vista.db - -# Dump file -*.stackdump - -# Folder config file -[Dd]esktop.ini - -# Recycle Bin used on file shares -$RECYCLE.BIN/ - -# Windows Installer files -*.cab -*.msi -*.msix -*.msm -*.msp - -# Windows shortcuts -*.lnk - -### Xcode ### -# Xcode -# -# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore - -## Build generated -build/ -DerivedData/ - -## Various settings -*.pbxuser -!default.pbxuser -*.mode1v3 -!default.mode1v3 -*.mode2v3 -!default.mode2v3 -*.perspectivev3 -!default.perspectivev3 -xcuserdata/ - -## Other -*.moved-aside -*.xccheckout -*.xcscmblueprint - -## Obj-C/Swift specific -*.hmap -*.ipa -*.dSYM.zip -*.dSYM - -## Playgrounds -timeline.xctimeline -playground.xcworkspace - -# Swift Package Manager -# -# Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. -# Packages/ -# Package.pins -# Package.resolved -.build/ - -# CocoaPods -# -# We recommend against adding the Pods directory to your .gitignore. However -# you should judge for yourself, the pros and cons are mentioned at: -# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control -# -# Pods/ -# -# Add this line if you want to avoid checking in source code from the Xcode workspace -# *.xcworkspace - -# Carthage -# -# Add this line if you want to avoid checking in source code from Carthage dependencies. -# Carthage/Checkouts - -Carthage/Build - -# fastlane -# -# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the -# screenshots whenever they are needed. -# For more information about the recommended setup visit: -# https://docs.fastlane.tools/best-practices/source-control/#source-control - -fastlane/report.xml -fastlane/Preview.html -fastlane/screenshots/**/*.png -fastlane/test_output - -# Code Injection -# -# After new code Injection tools there's a generated folder /iOSInjectionProject -# https://github.com/johnno1962/injectionforxcode - -iOSInjectionProject/ - - -### Xcode Patch ### -*.xcodeproj/* -!*.xcodeproj/project.pbxproj -!*.xcodeproj/xcshareddata/ -!*.xcworkspace/contents.xcworkspacedata -/*.gcno -**/xcshareddata/WorkspaceSettings.xcsettings - -### VisualStudio ### -## Ignore Visual Studio temporary files, build results, and -## files generated by popular Visual Studio add-ons. -## -## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore - -# User-specific files -*.rsuser -*.suo -*.user -*.userosscache -*.sln.docstates - -# User-specific files (MonoDevelop/Xamarin Studio) -*.userprefs - -# Build results -[Dd]ebug/ -[Dd]ebugPublic/ -[Rr]elease/ -[Rr]eleases/ -x64/ -x86/ -bld/ -[Bb]in/ -[Oo]bj/ -[Ll]og/ - -# Visual Studio 2015/2017 cache/options directory -.vs/ -# Uncomment if you have tasks that create the project's static files in wwwroot -#wwwroot/ - -# Visual Studio 2017 auto generated files -Generated\ Files/ - -# MSTest test Results -[Tt]est[Rr]esult*/ -[Bb]uild[Ll]og.* - -# NUNIT -*.VisualState.xml -TestResult.xml - -# Build Results of an ATL Project -[Dd]ebugPS/ -[Rr]eleasePS/ -dlldata.c - -# Benchmark Results -BenchmarkDotNet.Artifacts/ - -# .NET Core -project.lock.json -project.fragment.lock.json -artifacts/ - -# StyleCop -StyleCopReport.xml - -# Files built by Visual Studio -*_i.c -*_p.c -*_h.h -*.meta -*.iobj -*.ipdb -*.pgc -*.pgd -*.rsp -*.sbr -*.tlb -*.tli -*.tlh -*.tmp -*.tmp_proj -*_wpftmp.csproj -*.log -*.vspscc -*.vssscc -.builds -*.pidb -*.svclog -*.scc - -# Chutzpah Test files -_Chutzpah* - -# Visual C++ cache files -ipch/ -*.aps -*.ncb -*.opendb -*.opensdf -*.sdf -*.cachefile -*.VC.db -*.VC.VC.opendb - -# Visual Studio profiler -*.psess -*.vsp -*.vspx -*.sap - -# Visual Studio Trace Files -*.e2e - -# TFS 2012 Local Workspace -$tf/ - -# Guidance Automation Toolkit -*.gpState - -# ReSharper is a .NET coding add-in -_ReSharper*/ -*.[Rr]e[Ss]harper -*.DotSettings.user - -# JustCode is a .NET coding add-in -.JustCode - -# TeamCity is a build add-in -_TeamCity* - -# DotCover is a Code Coverage Tool -*.dotCover - -# AxoCover is a Code Coverage Tool -.axoCover/* -!.axoCover/settings.json - -# Visual Studio code coverage results -*.coverage -*.coveragexml - -# NCrunch -_NCrunch_* -.*crunch*.local.xml -nCrunchTemp_* - -# MightyMoose -*.mm.* -AutoTest.Net/ - -# Web workbench (sass) -.sass-cache/ - -# Installshield output folder -[Ee]xpress/ - -# DocProject is a documentation generator add-in -DocProject/buildhelp/ -DocProject/Help/*.HxT -DocProject/Help/*.HxC -DocProject/Help/*.hhc -DocProject/Help/*.hhk -DocProject/Help/*.hhp -DocProject/Help/Html2 -DocProject/Help/html - -# Click-Once directory -publish/ - -# Publish Web Output -*.[Pp]ublish.xml -*.azurePubxml -# Note: Comment the next line if you want to checkin your web deploy settings, -# but database connection strings (with potential passwords) will be unencrypted -*.pubxml -*.publishproj - -# Microsoft Azure Web App publish settings. Comment the next line if you want to -# checkin your Azure Web App publish settings, but sensitive information contained -# in these scripts will be unencrypted -PublishScripts/ - -# NuGet Packages -*.nupkg -# The packages folder can be ignored because of Package Restore -**/[Pp]ackages/* -# except build/, which is used as an MSBuild target. -!**/[Pp]ackages/build/ -# Uncomment if necessary however generally it will be regenerated when needed -#!**/[Pp]ackages/repositories.config -# NuGet v3's project.json files produces more ignorable files -*.nuget.props -*.nuget.targets - -# Microsoft Azure Build Output -csx/ -*.build.csdef - -# Microsoft Azure Emulator -ecf/ -rcf/ - -# Windows Store app package directories and files -AppPackages/ -BundleArtifacts/ -Package.StoreAssociation.xml -_pkginfo.txt -*.appx - -# Visual Studio cache files -# files ending in .cache can be ignored -*.[Cc]ache -# but keep track of directories ending in .cache -!*.[Cc]ache/ - -# Others -ClientBin/ -~$* -*.dbmdl -*.dbproj.schemaview -*.jfm -*.pfx -*.publishsettings -orleans.codegen.cs - -# Including strong name files can present a security risk -# (https://github.com/github/gitignore/pull/2483#issue-259490424) -#*.snk - -# Since there are multiple workflows, uncomment next line to ignore bower_components -# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) -#bower_components/ - -# RIA/Silverlight projects -Generated_Code/ - -# Backup & report files from converting an old project file -# to a newer Visual Studio version. Backup files are not needed, -# because we have git ;-) -_UpgradeReport_Files/ -Backup*/ -UpgradeLog*.XML -UpgradeLog*.htm -ServiceFabricBackup/ -*.rptproj.bak - -# SQL Server files -*.mdf -*.ldf -*.ndf - -# Business Intelligence projects -*.rdl.data -*.bim.layout -*.bim_*.settings -*.rptproj.rsuser - -# Microsoft Fakes -FakesAssemblies/ - -# GhostDoc plugin setting file -*.GhostDoc.xml - -# Node.js Tools for Visual Studio -.ntvs_analysis.dat -node_modules/ - -# Visual Studio 6 build log -*.plg - -# Visual Studio 6 workspace options file -*.opt - -# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) -*.vbw - -# Visual Studio LightSwitch build output -**/*.HTMLClient/GeneratedArtifacts -**/*.DesktopClient/GeneratedArtifacts -**/*.DesktopClient/ModelManifest.xml -**/*.Server/GeneratedArtifacts -**/*.Server/ModelManifest.xml -_Pvt_Extensions - -# Paket dependency manager -.paket/paket.exe -paket-files/ - -# FAKE - F# Make -.fake/ - -# JetBrains Rider -*.sln.iml - -# CodeRush personal settings -.cr/personal - -# Python Tools for Visual Studio (PTVS) -__pycache__/ -*.pyc - -# Cake - Uncomment if you are using it -# tools/** -# !tools/packages.config - -# Tabs Studio -*.tss - -# Telerik's JustMock configuration file -*.jmconfig - -# BizTalk build output -*.btp.cs -*.btm.cs -*.odx.cs -*.xsd.cs - -# OpenCover UI analysis results -OpenCover/ - -# Azure Stream Analytics local run output -ASALocalRun/ - -# MSBuild Binary and Structured Log -*.binlog - -# NVidia Nsight GPU debugger configuration file -*.nvuser - -# MFractors (Xamarin productivity tool) working folder -.mfractor/ - -# Local History for Visual Studio -.localhistory/ - -# End of https://www.gitignore.io/api/visualstudiocode,windows,c,c++,cmake,codeblocks,intellij+all,jetbrains+all,kdevelop4,linux,macos,osx,pycharm+all,vim,visualstudio,xcode - -# Custom rules (everything added below won't be overriden by 'Generate .gitignore File' if you use 'Update' option) - -kendryte-standlone-sdk.si4project/ - -kendryte-standalone-demo -kendryte-standalone-demo-bak -src/ -!src/hello_world -/CMakeSettings.json -/build_i diff --git a/cores/arduino/kendryte-standalone-sdk/.travis.yml b/cores/arduino/kendryte-standalone-sdk/.travis.yml deleted file mode 100644 index 404f05b..0000000 --- a/cores/arduino/kendryte-standalone-sdk/.travis.yml +++ /dev/null @@ -1,74 +0,0 @@ -sudo: false -language: cpp -git: - submodules: false -addons: - apt: - packages: - - python - - python-pip - - git - - wget - - make - - cmake - - libncurses-dev - - flex - - bison - - gperf - - aria2 -cache: - - pip - - directories: - - cache -before_install: -- export TOOLCHAIN_URL=https://github.com/kendryte/kendryte-gnu-toolchain/releases/download/v8.2.0-20190213/kendryte-toolchain-ubuntu-amd64-8.2.0-20190213.tar.gz -- export TOOLCHAIN=${TOOLCHAIN_URL##*/} -- | - if [ ! -f $TRAVIS_BUILD_DIR/cache/$TOOLCHAIN ]; then - echo "Download toolchain ..." - aria2c $TOOLCHAIN_URL -d $TRAVIS_BUILD_DIR/cache -o $TOOLCHAIN - else - echo "Toolchain is ready download in cache" - fi -- | - if [ ! -d $TRAVIS_BUILD_DIR/cache/kendryte-toolchain ]; then - echo "Extract toolchain ..." - tar -C $TRAVIS_BUILD_DIR/cache -zxvf $TRAVIS_BUILD_DIR/cache/$TOOLCHAIN - else - echo "Toolchain is ready extract in cache" - fi -install: -- export PATH=$TRAVIS_BUILD_DIR/cache/kendryte-toolchain/bin:$PATH -- export LD_LIBRARY_PATH=$TRAVIS_BUILD_DIR/cache/kendryte-toolchain/bin:$LD_LIBRARY_PATH -- | - cd $TRAVIS_BUILD_DIR - export BRANCH=$(if [ "$TRAVIS_BRANCH" == "master" ]; then echo $TRAVIS_BRANCH; else echo "develop"; fi) - git clone --single-branch --branch $BRANCH https://github.com/kendryte/kendryte-standalone-demo.git - echo "Build branch $BRANCH" - -script: -- export BUILD_DATE=$(date +%Y%m%d) -## Copy all example code -- | - cd $TRAVIS_BUILD_DIR/src - cp -rf $TRAVIS_BUILD_DIR/kendryte-standalone-demo/* . - mv $TRAVIS_BUILD_DIR/kendryte-standalone-demo ~/demo -## Check example code -- | - for DIR in $(ls $TRAVIS_BUILD_DIR/src) - do - echo "[MAKE]" $TRAVIS_BUILD_DIR/src/$DIR - cd $TRAVIS_BUILD_DIR/src/$DIR - if [ ! -f "Makefile" ]; then - COUNT=$(expr $(ls -1 *.c 2>/dev/null | wc -l) + $(ls -1 *.cpp 2>/dev/null | wc -l) + $(ls -1 *.S 2>/dev/null | wc -l)) - if [ $COUNT -gt 0 ]; then - mkdir build && cd build - cmake -DPROJ=$DIR -DTOOLCHAIN=$TRAVIS_BUILD_DIR/cache/kendryte-toolchain/bin ../../../ || exit -1 - make || exit -1 - else - echo "[IGNORE]" $TRAVIS_BUILD_DIR/src/$DIR - fi - else - make || exit -1 - fi - done diff --git a/cores/arduino/kendryte-standalone-sdk/CHANGELOG.md b/cores/arduino/kendryte-standalone-sdk/CHANGELOG.md deleted file mode 100644 index 6d40362..0000000 --- a/cores/arduino/kendryte-standalone-sdk/CHANGELOG.md +++ /dev/null @@ -1,94 +0,0 @@ -Changelog for Kendryte K210 -====== - -## 0.1.0 - -Kendryte K210 first SDK with FreeRTOS, have fun. - -## 0.2.0 - -- Major changes - - Rework trap handling - - New functions to enable spi0 and dvp pin - - New functions to select IO power mode -- Breaking changes - - Modify struct enum union format -- Non-breaking bug fixes - - Fix spi lcd unwork issues - - Fix dual core startup issues - - Use "__global_pointer$" instead of "_gp" - -## 0.3.0 - -- Major change - - Modify AES、FFT、SHA、I2C、SPI、WDT、SPI driver -- Breaking changes - - Modify struct enum union format -- Non-breaking bug fixes - - Fix out of memory issues - - Fix lcd unused issues - -## 0.4.1 - -- Major change - - Add dma support for aes driver - - Add uarths driver - - Add dma interrupt handler - -- Non-breaking bug fixes - - Fix the procedure of setting pll - - Fix wdt interrupt bug - - Fix serveral bugs in i2s drivers - -## 0.5.0 - -- Major change - - Add KPU driver - - Find toolchain automatically - -- Non-breaking bug fixes - - Fix aes gcm bug - - Fix dmac interrupt bug - - Fix i2s transfer bug - -## 0.5.1 - -- Major changes - - Add i2c slave driver - -- Non-breaking bug fixes - - Fix pll init issues - - Fix spi receive mode issues - - Fix redefine function does not report error issues - - Reduce stack size - -## 0.5.2 -- Major change - - Add KPU driver for latest model compiler - - Automatic set PROJ if user not set it - - Update timer driver to support better interrupt - - Add uart dma and interrupt function -- Non-breaking bug fixes - - Fix rtc issues - - Fix sccb issues - -- Breaking change - - Fix timer interrupt lost problem - - Add new timer interrupt API - -## 0.5.3 -- Major change - - Modify KPU driver for latest model compiler - - Add freertos - - Add new gpiohs and wdt interrupt function - - Add dvp xclk setting - - Add sysctl reset status - -- Non-breaking bug fixes - - Fix i2c issues - - Fix spi issues - -- Breaking change - - Fix uarths stopbit problem - - Fix core1 stack problem - - Fix core1 interrupt problem \ No newline at end of file diff --git a/cores/arduino/kendryte-standalone-sdk/CMakeLists.txt b/cores/arduino/kendryte-standalone-sdk/CMakeLists.txt deleted file mode 100644 index a00df20..0000000 --- a/cores/arduino/kendryte-standalone-sdk/CMakeLists.txt +++ /dev/null @@ -1,31 +0,0 @@ -### This file is used for build example projects. - -# set this will supress some warnings -set(BUILDING_SDK "yes" CACHE INTERNAL "") - -# basic config -if (NOT PROJ) - get_filename_component(PROJ ${CMAKE_CURRENT_BINARY_DIR} DIRECTORY) - get_filename_component(PROJ ${PROJ} NAME) - string(REPLACE " " "_" PROJ ${PROJ}) - message(STATUS "PROJ not set, use ${PROJ} as PROJ. Also, you can set it manually. e.g. -DPROJ=hello_world") -else() - message("PROJ = ${PROJ}") -endif () -cmake_minimum_required(VERSION 3.0) -include(./cmake/common.cmake) -project(${PROJ} C CXX ASM) - -# config self use headers -include(./cmake/macros.internal.cmake) -header_directories(${SDK_ROOT}/lib) -header_directories(src/${PROJ}) -header_directories(kendryte-standalone-demo/${PROJ}) -# build library first -add_subdirectory(lib) - -# compile project -add_source_files(src/${PROJ}/*.c src/${PROJ}/*.s src/${PROJ}/*.S src/${PROJ}/*.cpp) -add_source_files(kendryte-standalone-demo/${PROJ}/*.c kendryte-standalone-demo/${PROJ}/*.s kendryte-standalone-demo/${PROJ}/*.S kendryte-standalone-demo/${PROJ}/*.cpp) -include(./cmake/executable.cmake) - diff --git a/cores/arduino/kendryte-standalone-sdk/LICENSE b/cores/arduino/kendryte-standalone-sdk/LICENSE deleted file mode 100644 index e2c4705..0000000 --- a/cores/arduino/kendryte-standalone-sdk/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright 2018 Canaan Inc. - - 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. diff --git a/cores/arduino/kendryte-standalone-sdk/README.md b/cores/arduino/kendryte-standalone-sdk/README.md deleted file mode 100644 index e21f63b..0000000 --- a/cores/arduino/kendryte-standalone-sdk/README.md +++ /dev/null @@ -1,25 +0,0 @@ -# Kendryte K210 standalone SDK - -[![Build Status](https://travis-ci.org/kendryte/kendryte-standalone-sdk.svg)](https://travis-ci.org/kendryte/kendryte-standalone-sdk) -[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) - -This SDK is for Kendryte K210 without OS support. -If you have any questions, please be free to contact us. - -## Usage - -If you want to start a new project, for instance, `hello_world`, you only need to: - -`mkdir` your project in `src/`, `cd src && mkdir hello_world`, then put your codes in it, and build it. - -```bash -mkdir build && cd build -cmake .. -DPROJ= -DTOOLCHAIN=/opt/riscv-toolchain/bin && make -``` - -You will get 2 key files, `hello_world` and `hello_world.bin`. - -1. If you are using JLink to run or debug your program, use `hello_world` -2. If you want to flash it in UOG, using `hello_world.bin`, then using flash-tool(s) burn .bin to your flash. - -This is very important, don't make a mistake in files. diff --git a/cores/arduino/kendryte-standalone-sdk/lds/kendryte.ld b/cores/arduino/kendryte-standalone-sdk/lds/kendryte.ld deleted file mode 100644 index 154a91b..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lds/kendryte.ld +++ /dev/null @@ -1,252 +0,0 @@ -/* - * The MEMORY command describes the location and size of blocks of memory - * in the target. You can use it to describe which memory regions may be - * used by the linker, and which memory regions it must avoid. - */ -MEMORY -{ - /* - * Memory with CPU cache. - *6M CPU SRAM - */ - ram (wxa!ri) : ORIGIN = 0x80000000, LENGTH = (6 * 1024 * 1024) - /* - * Memory without CPU cache - * 6M CPU SRAM - */ - ram_nocache (wxa!ri) : ORIGIN = 0x40000000, LENGTH = (6 * 1024 * 1024) -} - -PROVIDE( _rom_start = ORIGIN(rom) ); -PROVIDE( _rom_end = ORIGIN(rom) + LENGTH(rom) ); -PROVIDE( _ram_start = ORIGIN(ram) ); -PROVIDE( _ram_end = ORIGIN(ram) + LENGTH(ram) ); -PROVIDE( _io_start = 0x40000000 ); -PROVIDE( _io_end = _io_start + LENGTH(ram) ); -PROVIDE( _stack_size = 1 << 15 ); - - -/* - * The OUTPUT_ARCH command specifies the machine architecture where the - * argument is one of the names used in the Kendryte library. - */ -OUTPUT_ARCH( "riscv" ) - -/* - * The ENTRY command specifies the entry point (ie. first instruction to - * execute). The symbol _start is defined in crt0.S - */ -ENTRY(_start) - -/* - * The GROUP command is special since the listed archives will be - * searched repeatedly until there are no new undefined references. We - * need this since -lc depends on -lgloss and -lgloss depends on -lc. I - * thought gcc would automatically include -lgcc when needed, but - * in this file includes it explicitly here and I was seeing link errors - * without it. - */ -/* GROUP( -lc -lgloss -lgcc ) */ - -/* - * The linker only pays attention to the PHDRS command when generating - * an ELF output file. In other cases, the linker will simply ignore PHDRS. - */ -PHDRS -{ - ram_ro PT_LOAD; - ram_init PT_LOAD; - ram PT_NULL; -} - -/* - * This is where we specify how the input sections map to output - * sections. - */ -SECTIONS -{ - /* Program code segment, also known as a text segment */ - .text : - { - PROVIDE( _text = ABSOLUTE(.) ); - /* Initialization code segment */ - KEEP( *(.text.start) ) - KEEP( *(.text.systick) ) - *(.text.unlikely .text.unlikely.*) - *(.text.startup .text.startup.*) - /* Normal code segment */ - *(.text .text.*) - *(.gnu.linkonce.t.*) - - . = ALIGN(8); - PROVIDE( _etext = ABSOLUTE(.) ); - } >ram AT>ram :ram_ro - - /* Read-only data segment */ - .rodata : - { - *(.rdata) - *(.rodata .rodata.*) - *(.gnu.linkonce.r.*) - } >ram AT>ram :ram_ro - - . = ALIGN(8); - - /* Init array and fini array */ - .preinit_array : - { - PROVIDE_HIDDEN (__preinit_array_start = .); - KEEP (*(.preinit_array)) - PROVIDE_HIDDEN (__preinit_array_end = .); - } >ram AT>ram :ram_ro - - .init_array : - { - PROVIDE_HIDDEN (__init_array_start = .); - KEEP (*(SORT_BY_INIT_PRIORITY(.init_array.*) SORT_BY_INIT_PRIORITY(.ctors.*))) - KEEP (*(.init_array EXCLUDE_FILE (*crtbegin.o *crtbegin?.o *crtend.o *crtend?.o ) .ctors)) - PROVIDE_HIDDEN (__init_array_end = .); - } >ram AT>ram :ram_ro - - .fini_array : - { - PROVIDE_HIDDEN (__fini_array_start = .); - KEEP (*(SORT_BY_INIT_PRIORITY(.fini_array.*) SORT_BY_INIT_PRIORITY(.dtors.*))) - KEEP (*(.fini_array EXCLUDE_FILE (*crtbegin.o *crtbegin?.o *crtend.o *crtend?.o ) .dtors)) - PROVIDE_HIDDEN (__fini_array_end = .); - } >ram AT>ram :ram_ro - - .ctors : - { - /* gcc uses crtbegin.o to find the start of - the constructors, so we make sure it is - first. Because this is a wildcard, it - doesn't matter if the user does not - actually link against crtbegin.o; the - linker won't look for a file to match a - wildcard. The wildcard also means that it - doesn't matter which directory crtbegin.o - is in. */ - KEEP (*crtbegin.o(.ctors)) - KEEP (*crtbegin?.o(.ctors)) - /* We don't want to include the .ctor section from - the crtend.o file until after the sorted ctors. - The .ctor section from the crtend file contains the - end of ctors marker and it must be last */ - KEEP (*(EXCLUDE_FILE (*crtend.o *crtend?.o ) .ctors)) - KEEP (*(SORT(.ctors.*))) - KEEP (*(.ctors)) - } >ram AT>ram :ram_ro - - .dtors : - { - KEEP (*crtbegin.o(.dtors)) - KEEP (*crtbegin?.o(.dtors)) - KEEP (*(EXCLUDE_FILE (*crtend.o *crtend?.o ) .dtors)) - KEEP (*(SORT(.dtors.*))) - KEEP (*(.dtors)) - } >ram AT>ram :ram_ro - - . = ALIGN(8); - - .lalign : - { - . = ALIGN(8); - PROVIDE( _data_lma = . ); - } >ram AT>ram :ram_ro - - .dalign : - { - . = ALIGN(8); - PROVIDE( _data = . ); - } >ram AT>ram :ram_init - - . = ALIGN(8); - - /* .data, .sdata and .srodata segment */ - .data : - { - /* Writable data segment (.data segment) */ - *(.data .data.*) - *(.gnu.linkonce.d.*) - /* Have _gp point to middle of sdata/sbss to maximize displacement range */ - . = ALIGN(8); - PROVIDE( __global_pointer$ = ABSOLUTE(.) + 0x800); - /* Writable small data segment (.sdata segment) */ - *(.sdata .sdata.*) - *(.gnu.linkonce.s.*) - /* Read-only small data segment (.srodata segment) */ - . = ALIGN(8); - *(.srodata.cst16) - *(.srodata.cst8) - *(.srodata.cst4) - *(.srodata.cst2) - *(.srodata .srodata.*) - /* Align _edata to cache line size */ - . = ALIGN(64); - PROVIDE( _edata = ABSOLUTE(.) ); - } >ram AT>ram :ram_init - - /* .bss and .sbss segment */ - .bss : - { - PROVIDE( _bss = ABSOLUTE(.) ); - /* Writable uninitialized small data segment (.sbss segment)*/ - *(.sbss .sbss.*) - *(.gnu.linkonce.sb.*) - *(.scommon) - /* Uninitialized writeable data section (.bss segment)*/ - *(.bss .bss.*) - *(.gnu.linkonce.b.*) - *(COMMON) - - . = ALIGN(8); - PROVIDE( _ebss = ABSOLUTE(.) ); - } >ram AT>ram :ram - - PROVIDE( _tls_data = ABSOLUTE(.) ); - /* - * Thread Local Storage (TLS) are per-thread global variables. - * Compilers such as GCC provide a __thread keyword to mark global - * variables as per-thread. Support is required in the program loader - * and thread creator. - */ - - /* Thread-local data segment, .tdata (initialized tls). */ - .tdata : - { - KEEP( *(.tdata.begin) ) - *(.tdata .tdata.*) - *(.gnu.linkonce.td.*) - KEEP( *(.tdata.end) ) - } >ram AT>ram :ram - - /* Thread-local bss segment, .tbss (zero-initialized tls). */ - .tbss : - { - *(.tbss .tbss.*) - *(.gnu.linkonce.tb.*) - KEEP( *(.tbss.end) ) - } >ram AT>ram :ram - - /* - * End of uninitalized data segement - * - * Actually the stack needs 16B alignment, and it won't hurt to also slightly - * increase the alignment to 32 or even 64 (cache line size). - * - * Align _heap_start to cache line size - */ - . = ALIGN(64); - PROVIDE( _end = ABSOLUTE(.) ); - /* Leave 2 holes for stack & TLS, the size can set in kconfig */ - PROVIDE( _heap_start = ABSOLUTE(.) + _stack_size * 2 ); - PROVIDE( _tp0 = (_end + 63) & (-64) ); - PROVIDE( _tp1 = _tp0 + _stack_size ); - PROVIDE( _sp0 = _tp0 + _stack_size ); - PROVIDE( _sp1 = _tp1 + _stack_size ); - - /* Heap end is at the end of memory, the memory size can set in kconfig */ - PROVIDE( _heap_end = _ram_end ); -} - diff --git a/cores/arduino/kendryte-standalone-sdk/lib/CMakeLists.txt b/cores/arduino/kendryte-standalone-sdk/lib/CMakeLists.txt deleted file mode 100644 index c2f8a81..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/CMakeLists.txt +++ /dev/null @@ -1,27 +0,0 @@ -#project(maix_drivers) - -# create driver library - -FILE(GLOB_RECURSE LIB_SRC - "${CMAKE_CURRENT_LIST_DIR}/*.h" - "${CMAKE_CURRENT_LIST_DIR}/*.hpp" - "${CMAKE_CURRENT_LIST_DIR}/*.cpp" - "${CMAKE_CURRENT_LIST_DIR}/*.c" - "${CMAKE_CURRENT_LIST_DIR}/*.s" - "${CMAKE_CURRENT_LIST_DIR}/*.S" - ) - -FILE(GLOB_RECURSE ASSEMBLY_FILES - "${CMAKE_CURRENT_LIST_DIR}/*.s" - "${CMAKE_CURRENT_LIST_DIR}/*.S" - ) - -include_directories(${CMAKE_CURRENT_LIST_DIR}/drivers/include ${CMAKE_CURRENT_LIST_DIR}/bsp/include) - -SET_PROPERTY(SOURCE ${ASSEMBLY_FILES} PROPERTY LANGUAGE C) -SET_SOURCE_FILES_PROPERTIES(${ASSEMBLY_FILES} PROPERTIES COMPILE_FLAGS "-x assembler-with-cpp -D __riscv64") - -ADD_LIBRARY(kendryte - ${LIB_SRC} - ) -SET_TARGET_PROPERTIES(kendryte PROPERTIES LINKER_LANGUAGE C) diff --git a/cores/arduino/kendryte-standalone-sdk/lib/bsp/crt.S b/cores/arduino/kendryte-standalone-sdk/lib/bsp/crt.S deleted file mode 100644 index 1852ddd..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/bsp/crt.S +++ /dev/null @@ -1,318 +0,0 @@ -# Copyright 2018 Canaan Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -#include "encoding.h" - -# define LREG ld -# define SREG sd -# define LFREG flw -# define SFREG fsw -# define REGBYTES 8 -# define STKSHIFT 15 - - -.section .text.start, "ax", @progbits -.globl _start -_start: - j 1f - .word 0xdeadbeef - .align 3 - .global g_wake_up - g_wake_up: - .dword 1 - .dword 0 -1: - csrw mideleg, 0 - csrw medeleg, 0 - csrw mie, 0 - csrw mip, 0 - la t0, trap_entry - csrw mtvec, t0 - - li x1, 0 - li x2, 0 - li x3, 0 - li x4, 0 - li x5, 0 - li x6, 0 - li x7, 0 - li x8, 0 - li x9, 0 - li x10,0 - li x11,0 - li x12,0 - li x13,0 - li x14,0 - li x15,0 - li x16,0 - li x17,0 - li x18,0 - li x19,0 - li x20,0 - li x21,0 - li x22,0 - li x23,0 - li x24,0 - li x25,0 - li x26,0 - li x27,0 - li x28,0 - li x29,0 - li x30,0 - li x31,0 - - li t0, MSTATUS_FS - csrs mstatus, t0 - - fssr x0 - fmv.w.x f0, x0 - fmv.w.x f1, x0 - fmv.w.x f2, x0 - fmv.w.x f3, x0 - fmv.w.x f4, x0 - fmv.w.x f5, x0 - fmv.w.x f6, x0 - fmv.w.x f7, x0 - fmv.w.x f8, x0 - fmv.w.x f9, x0 - fmv.w.x f10,x0 - fmv.w.x f11,x0 - fmv.w.x f12,x0 - fmv.w.x f13,x0 - fmv.w.x f14,x0 - fmv.w.x f15,x0 - fmv.w.x f16,x0 - fmv.w.x f17,x0 - fmv.w.x f18,x0 - fmv.w.x f19,x0 - fmv.w.x f20,x0 - fmv.w.x f21,x0 - fmv.w.x f22,x0 - fmv.w.x f23,x0 - fmv.w.x f24,x0 - fmv.w.x f25,x0 - fmv.w.x f26,x0 - fmv.w.x f27,x0 - fmv.w.x f28,x0 - fmv.w.x f29,x0 - fmv.w.x f30,x0 - fmv.w.x f31,x0 - - .option push - .option norelax - la gp, __global_pointer$ - .option pop - la tp, _end + 63 - and tp, tp, -64 - csrr a0, mhartid - - add sp, a0, 1 - sll sp, sp, STKSHIFT - add sp, sp, tp - - j _init_bsp - - .globl trap_entry - .type trap_entry, @function - .align 2 -trap_entry: - addi sp, sp, -REGBYTES - sd t0, 0x0(sp) - csrr t0, mcause - bgez t0, .handle_other - # Test soft interrupt - slli t0, t0, 1 - addi t0, t0, -(IRQ_M_SOFT << 1) - bnez t0, .handle_other - # Interupt is soft interrupt - # Get event - addi sp, sp, -REGBYTES - sd t1, 0x0(sp) - la t0, g_core_pending_switch - csrr t1, mhartid - slli t1, t1, 3 - add t0, t0, t1 - ld t1, 0x0(sp) - addi sp, sp, REGBYTES - # Test ContextSwitch event - ld t0, 0x0(t0) - beqz t0, .handle_other - - ld t0, 0x0(sp) - addi sp, sp, REGBYTES - # Do not use jal here - j xPortSysTickInt - mret -.handle_other: - ld t0, 0x0(sp) - addi sp, sp, REGBYTES - addi sp, sp, -64*REGBYTES - - SREG x1, 1*REGBYTES(sp) - SREG x2, 2*REGBYTES(sp) - SREG x3, 3*REGBYTES(sp) - SREG x4, 4*REGBYTES(sp) - SREG x5, 5*REGBYTES(sp) - SREG x6, 6*REGBYTES(sp) - SREG x7, 7*REGBYTES(sp) - SREG x8, 8*REGBYTES(sp) - SREG x9, 9*REGBYTES(sp) - SREG x10, 10*REGBYTES(sp) - SREG x11, 11*REGBYTES(sp) - SREG x12, 12*REGBYTES(sp) - SREG x13, 13*REGBYTES(sp) - SREG x14, 14*REGBYTES(sp) - SREG x15, 15*REGBYTES(sp) - SREG x16, 16*REGBYTES(sp) - SREG x17, 17*REGBYTES(sp) - SREG x18, 18*REGBYTES(sp) - SREG x19, 19*REGBYTES(sp) - SREG x20, 20*REGBYTES(sp) - SREG x21, 21*REGBYTES(sp) - SREG x22, 22*REGBYTES(sp) - SREG x23, 23*REGBYTES(sp) - SREG x24, 24*REGBYTES(sp) - SREG x25, 25*REGBYTES(sp) - SREG x26, 26*REGBYTES(sp) - SREG x27, 27*REGBYTES(sp) - SREG x28, 28*REGBYTES(sp) - SREG x29, 29*REGBYTES(sp) - SREG x30, 30*REGBYTES(sp) - SREG x31, 31*REGBYTES(sp) - - SFREG f0, ( 0 + 32)*REGBYTES(sp) - SFREG f1, ( 1 + 32)*REGBYTES(sp) - SFREG f2, ( 2 + 32)*REGBYTES(sp) - SFREG f3, ( 3 + 32)*REGBYTES(sp) - SFREG f4, ( 4 + 32)*REGBYTES(sp) - SFREG f5, ( 5 + 32)*REGBYTES(sp) - SFREG f6, ( 6 + 32)*REGBYTES(sp) - SFREG f7, ( 7 + 32)*REGBYTES(sp) - SFREG f8, ( 8 + 32)*REGBYTES(sp) - SFREG f9, ( 9 + 32)*REGBYTES(sp) - SFREG f10,( 10 + 32)*REGBYTES(sp) - SFREG f11,( 11 + 32)*REGBYTES(sp) - SFREG f12,( 12 + 32)*REGBYTES(sp) - SFREG f13,( 13 + 32)*REGBYTES(sp) - SFREG f14,( 14 + 32)*REGBYTES(sp) - SFREG f15,( 15 + 32)*REGBYTES(sp) - SFREG f16,( 16 + 32)*REGBYTES(sp) - SFREG f17,( 17 + 32)*REGBYTES(sp) - SFREG f18,( 18 + 32)*REGBYTES(sp) - SFREG f19,( 19 + 32)*REGBYTES(sp) - SFREG f20,( 20 + 32)*REGBYTES(sp) - SFREG f21,( 21 + 32)*REGBYTES(sp) - SFREG f22,( 22 + 32)*REGBYTES(sp) - SFREG f23,( 23 + 32)*REGBYTES(sp) - SFREG f24,( 24 + 32)*REGBYTES(sp) - SFREG f25,( 25 + 32)*REGBYTES(sp) - SFREG f26,( 26 + 32)*REGBYTES(sp) - SFREG f27,( 27 + 32)*REGBYTES(sp) - SFREG f28,( 28 + 32)*REGBYTES(sp) - SFREG f29,( 29 + 32)*REGBYTES(sp) - SFREG f30,( 30 + 32)*REGBYTES(sp) - SFREG f31,( 31 + 32)*REGBYTES(sp) - - csrr a0, mcause - csrr a1, mepc - mv a2, sp - add a3, sp, 32*REGBYTES - bgez a0, .handle_syscall -.handle_irq: - jal handle_irq - j .restore -.handle_syscall: - jal handle_syscall -.restore: - csrw mepc, a0 - LREG x1, 1*REGBYTES(sp) - LREG x2, 2*REGBYTES(sp) - LREG x3, 3*REGBYTES(sp) - LREG x4, 4*REGBYTES(sp) - LREG x5, 5*REGBYTES(sp) - LREG x6, 6*REGBYTES(sp) - LREG x7, 7*REGBYTES(sp) - LREG x8, 8*REGBYTES(sp) - LREG x9, 9*REGBYTES(sp) - LREG x10, 10*REGBYTES(sp) - LREG x11, 11*REGBYTES(sp) - LREG x12, 12*REGBYTES(sp) - LREG x13, 13*REGBYTES(sp) - LREG x14, 14*REGBYTES(sp) - LREG x15, 15*REGBYTES(sp) - LREG x16, 16*REGBYTES(sp) - LREG x17, 17*REGBYTES(sp) - LREG x18, 18*REGBYTES(sp) - LREG x19, 19*REGBYTES(sp) - LREG x20, 20*REGBYTES(sp) - LREG x21, 21*REGBYTES(sp) - LREG x22, 22*REGBYTES(sp) - LREG x23, 23*REGBYTES(sp) - LREG x24, 24*REGBYTES(sp) - LREG x25, 25*REGBYTES(sp) - LREG x26, 26*REGBYTES(sp) - LREG x27, 27*REGBYTES(sp) - LREG x28, 28*REGBYTES(sp) - LREG x29, 29*REGBYTES(sp) - LREG x30, 30*REGBYTES(sp) - LREG x31, 31*REGBYTES(sp) - - LFREG f0, ( 0 + 32)*REGBYTES(sp) - LFREG f1, ( 1 + 32)*REGBYTES(sp) - LFREG f2, ( 2 + 32)*REGBYTES(sp) - LFREG f3, ( 3 + 32)*REGBYTES(sp) - LFREG f4, ( 4 + 32)*REGBYTES(sp) - LFREG f5, ( 5 + 32)*REGBYTES(sp) - LFREG f6, ( 6 + 32)*REGBYTES(sp) - LFREG f7, ( 7 + 32)*REGBYTES(sp) - LFREG f8, ( 8 + 32)*REGBYTES(sp) - LFREG f9, ( 9 + 32)*REGBYTES(sp) - LFREG f10,( 10 + 32)*REGBYTES(sp) - LFREG f11,( 11 + 32)*REGBYTES(sp) - LFREG f12,( 12 + 32)*REGBYTES(sp) - LFREG f13,( 13 + 32)*REGBYTES(sp) - LFREG f14,( 14 + 32)*REGBYTES(sp) - LFREG f15,( 15 + 32)*REGBYTES(sp) - LFREG f16,( 16 + 32)*REGBYTES(sp) - LFREG f17,( 17 + 32)*REGBYTES(sp) - LFREG f18,( 18 + 32)*REGBYTES(sp) - LFREG f19,( 19 + 32)*REGBYTES(sp) - LFREG f20,( 20 + 32)*REGBYTES(sp) - LFREG f21,( 21 + 32)*REGBYTES(sp) - LFREG f22,( 22 + 32)*REGBYTES(sp) - LFREG f23,( 23 + 32)*REGBYTES(sp) - LFREG f24,( 24 + 32)*REGBYTES(sp) - LFREG f25,( 25 + 32)*REGBYTES(sp) - LFREG f26,( 26 + 32)*REGBYTES(sp) - LFREG f27,( 27 + 32)*REGBYTES(sp) - LFREG f28,( 28 + 32)*REGBYTES(sp) - LFREG f29,( 29 + 32)*REGBYTES(sp) - LFREG f30,( 30 + 32)*REGBYTES(sp) - LFREG f31,( 31 + 32)*REGBYTES(sp) - - addi sp, sp, 64*REGBYTES - mret - -.section ".tdata.begin" -.globl _tdata_begin -_tdata_begin: - -.section ".tdata.end" -.globl _tdata_end -_tdata_end: - -.section ".tbss.end" -.globl _tbss_end -_tbss_end: - diff --git a/cores/arduino/kendryte-standalone-sdk/lib/bsp/entry.c b/cores/arduino/kendryte-standalone-sdk/lib/bsp/entry.c deleted file mode 100644 index 50385a3..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/bsp/entry.c +++ /dev/null @@ -1,37 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "entry.h" - -/** - * @brief Dummy function for __libc_init_array called - */ -void __attribute__((weak)) _init(void) -{ - /** - * These don't have to do anything since we use init_array/fini_array. - */ -} - -/** - * @brief Dummy function for __libc_fini_array called - */ -void __attribute__((weak)) _fini(void) -{ - /** - * These don't have to do anything since we use init_array/fini_array. - */ -} - diff --git a/cores/arduino/kendryte-standalone-sdk/lib/bsp/entry_user.c b/cores/arduino/kendryte-standalone-sdk/lib/bsp/entry_user.c deleted file mode 100644 index 85cda3a..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/bsp/entry_user.c +++ /dev/null @@ -1,102 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include "atomic.h" -#include "clint.h" -#include "dmac.h" -#include "entry.h" -#include "fpioa.h" -#include "platform.h" -#include "plic.h" -#include "sysctl.h" -#include "syslog.h" -#include "uarths.h" - -extern volatile uint64_t g_wake_up[2]; - -core_instance_t core1_instance; - -volatile char * const ram = (volatile char*)RAM_BASE_ADDR; - -extern char _heap_start[]; -extern char _heap_end[]; - -void thread_entry(int core_id) -{ - while (!atomic_read(&g_wake_up[core_id])); -} - -void core_enable(int core_id) -{ - clint_ipi_send(core_id); - atomic_set(&g_wake_up[core_id], 1); -} - -int register_core1(core_function func, void *ctx) -{ - if(func == NULL) - return -1; - core1_instance.callback = func; - core1_instance.ctx = ctx; - core_enable(1); - return 0; -} - -int __attribute__((weak)) os_entry(int core_id, int number_of_cores, int (*user_main)(int, char**)) -{ - /* Call main if there is no OS */ - return user_main(0, 0); -} - -void _init_bsp(int core_id, int number_of_cores) -{ - extern int main(int argc, char* argv[]); - extern void __libc_init_array(void); - extern void __libc_fini_array(void); - - if (core_id == 0) - { - /* Initialize bss data to 0 */ - init_bss(); - /* Init UART */ - uarths_init(); - /* Init FPIOA */ - fpioa_init(); - /* Register finalization function */ - atexit(__libc_fini_array); - /* Init libc array for C++ */ - __libc_init_array(); - /* Get reset status */ - sysctl_get_reset_status(); - } - - int ret = 0; - if (core_id == 0) - { - core1_instance.callback = NULL; - core1_instance.ctx = NULL; - ret = os_entry(core_id, number_of_cores, main); - } - else - { - thread_entry(core_id); - if(core1_instance.callback == NULL) - asm volatile ("wfi"); - else - ret = core1_instance.callback(core1_instance.ctx); - } - exit(ret); -} diff --git a/cores/arduino/kendryte-standalone-sdk/lib/bsp/include/atomic.h b/cores/arduino/kendryte-standalone-sdk/lib/bsp/include/atomic.h deleted file mode 100644 index 1e2e07a..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/bsp/include/atomic.h +++ /dev/null @@ -1,243 +0,0 @@ - -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef _BSP_ATOMIC_H -#define _BSP_ATOMIC_H - -#ifdef __cplusplus -extern "C" { -#endif - - -#define SPINLOCK_INIT \ - { \ - 0 \ - } - -#define CORELOCK_INIT \ - { \ - .lock = SPINLOCK_INIT, \ - .count = 0, \ - .core = -1 \ - } - - -/* Defination of memory barrier macro */ -#define mb() \ - { \ - asm volatile("fence" :: \ - : "memory"); \ - } - -#define atomic_set(ptr, val) (*(volatile typeof(*(ptr))*)(ptr) = val) -#define atomic_read(ptr) (*(volatile typeof(*(ptr))*)(ptr)) - -#ifndef __riscv_atomic -#error "atomic extension is required." -#endif -#define atomic_add(ptr, inc) __sync_fetch_and_add(ptr, inc) -#define atomic_or(ptr, inc) __sync_fetch_and_or(ptr, inc) -#define atomic_swap(ptr, swp) __sync_lock_test_and_set(ptr, swp) -#define atomic_cas(ptr, cmp, swp) __sync_val_compare_and_swap(ptr, cmp, swp) - -typedef struct _spinlock -{ - int lock; -} spinlock_t; - -typedef struct _semaphore -{ - spinlock_t lock; - int count; - int waiting; -} semaphore_t; - - -typedef struct _corelock -{ - spinlock_t lock; - int count; - int core; -} corelock_t; - -static inline int spinlock_trylock(spinlock_t *lock) -{ - int res = atomic_swap(&lock->lock, -1); - /* Use memory barrier to keep coherency */ - mb(); - return res; -} - -static inline void spinlock_lock(spinlock_t *lock) -{ - while (spinlock_trylock(lock)); -} - -static inline void spinlock_unlock(spinlock_t *lock) -{ - /* Use memory barrier to keep coherency */ - mb(); - atomic_set(&lock->lock, 0); - asm volatile ("nop"); -} - -static inline void semaphore_signal(semaphore_t *semaphore, int i) -{ - spinlock_lock(&(semaphore->lock)); - semaphore->count += i; - spinlock_unlock(&(semaphore->lock)); -} - -static inline void semaphore_wait(semaphore_t *semaphore, int i) -{ - atomic_add(&(semaphore->waiting), 1); - while (1) - { - spinlock_lock(&(semaphore->lock)); - if (semaphore->count >= i) - { - semaphore->count -= i; - atomic_add(&(semaphore->waiting), -1); - spinlock_unlock(&(semaphore->lock)); - break; - } - spinlock_unlock(&(semaphore->lock)); - } -} - -static inline int semaphore_count(semaphore_t *semaphore) -{ - int res = 0; - - spinlock_lock(&(semaphore->lock)); - res = semaphore->count; - spinlock_unlock(&(semaphore->lock)); - return res; -} - -static inline int semaphore_waiting(semaphore_t *semaphore) -{ - return atomic_read(&(semaphore->waiting)); -} - -static inline int corelock_trylock(corelock_t *lock) -{ - int res = 0; - unsigned long core; - - asm volatile("csrr %0, mhartid;" - : "=r"(core)); - if(spinlock_trylock(&lock->lock)) - { - return -1; - } - - if (lock->count == 0) - { - /* First time get lock */ - lock->count++; - lock->core = core; - res = 0; - } - else if (lock->core == core) - { - /* Same core get lock */ - lock->count++; - res = 0; - } - else - { - /* Different core get lock */ - res = -1; - } - spinlock_unlock(&lock->lock); - - return res; -} - -static inline void corelock_lock(corelock_t *lock) -{ - unsigned long core; - - asm volatile("csrr %0, mhartid;" - : "=r"(core)); - spinlock_lock(&lock->lock); - - if (lock->count == 0) - { - /* First time get lock */ - lock->count++; - lock->core = core; - } - else if (lock->core == core) - { - /* Same core get lock */ - lock->count++; - } - else - { - /* Different core get lock */ - spinlock_unlock(&lock->lock); - - do - { - while (atomic_read(&lock->count)) - ; - } while (corelock_trylock(lock)); - } - spinlock_unlock(&lock->lock); -} - -static inline void corelock_unlock(corelock_t *lock) -{ - unsigned long core; - - asm volatile("csrr %0, mhartid;" - : "=r"(core)); - spinlock_lock(&lock->lock); - - if (lock->core == core) - { - /* Same core release lock */ - lock->count--; - if (lock->count <= 0) - { - lock->core = -1; - lock->count = 0; - } - } - else - { - /* Different core release lock */ - spinlock_unlock(&lock->lock); - - register unsigned long a7 asm("a7") = 93; - register unsigned long a0 asm("a0") = 0; - register unsigned long a1 asm("a1") = 0; - register unsigned long a2 asm("a2") = 0; - - asm volatile("scall" - : "+r"(a0) - : "r"(a1), "r"(a2), "r"(a7)); - } - spinlock_unlock(&lock->lock); -} - -#ifdef __cplusplus -} -#endif - -#endif /* _BSP_ATOMIC_H */ - diff --git a/cores/arduino/kendryte-standalone-sdk/lib/bsp/include/bsp.h b/cores/arduino/kendryte-standalone-sdk/lib/bsp/include/bsp.h deleted file mode 100644 index deecc67..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/bsp/include/bsp.h +++ /dev/null @@ -1,7 +0,0 @@ -#ifndef _KENDRYTE_BSP_H -#define _KENDRYTE_BSP_H -#include "atomic.h" -#include "entry.h" -#include "sleep.h" -#include "encoding.h" -#endif \ No newline at end of file diff --git a/cores/arduino/kendryte-standalone-sdk/lib/bsp/include/dump.h b/cores/arduino/kendryte-standalone-sdk/lib/bsp/include/dump.h deleted file mode 100644 index cb8131a..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/bsp/include/dump.h +++ /dev/null @@ -1,141 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef _BSP_DUMP_H -#define _BSP_DUMP_H - -#include -#include -#include "syslog.h" -#include "uarths.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#define DUMP_PRINTF printk - -static inline void -dump_core(const char *reason, uintptr_t cause, uintptr_t epc, uintptr_t regs[32], uintptr_t fregs[32]) -{ - static const char *const reg_usage[][2] = - { - {"zero ", "Hard-wired zero"}, - {"ra ", "Return address"}, - {"sp ", "Stack pointer"}, - {"gp ", "Global pointer"}, - {"tp ", "Thread pointer"}, - {"t0 ", "Temporaries Caller"}, - {"t1 ", "Temporaries Caller"}, - {"t2 ", "Temporaries Caller"}, - {"s0/fp", "Saved register/frame pointer"}, - {"s1 ", "Saved register"}, - {"a0 ", "Function arguments/return values"}, - {"a1 ", "Function arguments/return values"}, - {"a2 ", "Function arguments values"}, - {"a3 ", "Function arguments values"}, - {"a4 ", "Function arguments values"}, - {"a5 ", "Function arguments values"}, - {"a6 ", "Function arguments values"}, - {"a7 ", "Function arguments values"}, - {"s2 ", "Saved registers"}, - {"s3 ", "Saved registers"}, - {"s4 ", "Saved registers"}, - {"s5 ", "Saved registers"}, - {"s6 ", "Saved registers"}, - {"s7 ", "Saved registers"}, - {"s8 ", "Saved registers"}, - {"s9 ", "Saved registers"}, - {"s10 ", "Saved registers"}, - {"s11 ", "Saved registers"}, - {"t3 ", "Temporaries Caller"}, - {"t4 ", "Temporaries Caller"}, - {"t5 ", "Temporaries Caller"}, - {"t6 ", "Temporaries Caller"}, - }; - - static const char *const regf_usage[][2] = - { - {"ft0 ", "FP temporaries"}, - {"ft1 ", "FP temporaries"}, - {"ft2 ", "FP temporaries"}, - {"ft3 ", "FP temporaries"}, - {"ft4 ", "FP temporaries"}, - {"ft5 ", "FP temporaries"}, - {"ft6 ", "FP temporaries"}, - {"ft7 ", "FP temporaries"}, - {"fs0 ", "FP saved registers"}, - {"fs1 ", "FP saved registers"}, - {"fa0 ", "FP arguments/return values"}, - {"fa1 ", "FP arguments/return values"}, - {"fa2 ", "FP arguments values"}, - {"fa3 ", "FP arguments values"}, - {"fa4 ", "FP arguments values"}, - {"fa5 ", "FP arguments values"}, - {"fa6 ", "FP arguments values"}, - {"fa7 ", "FP arguments values"}, - {"fs2 ", "FP Saved registers"}, - {"fs3 ", "FP Saved registers"}, - {"fs4 ", "FP Saved registers"}, - {"fs5 ", "FP Saved registers"}, - {"fs6 ", "FP Saved registers"}, - {"fs7 ", "FP Saved registers"}, - {"fs8 ", "FP Saved registers"}, - {"fs9 ", "FP Saved registers"}, - {"fs10", "FP Saved registers"}, - {"fs11", "FP Saved registers"}, - {"ft8 ", "FP Temporaries Caller"}, - {"ft9 ", "FP Temporaries Caller"}, - {"ft10", "FP Temporaries Caller"}, - {"ft11", "FP Temporaries Caller"}, - }; - - if (CONFIG_LOG_LEVEL >= LOG_ERROR) - { - const char unknown_reason[] = "unknown"; - - if (!reason) - reason = unknown_reason; - - DUMP_PRINTF("core dump: %s\r\n", reason); - DUMP_PRINTF("Cause 0x%016lx, EPC 0x%016lx\r\n", cause, epc); - - int i = 0; - for (i = 0; i < 32 / 2; i++) - { - DUMP_PRINTF( - "reg[%02d](%s) = 0x%016lx, reg[%02d](%s) = 0x%016lx\r\n", - i * 2, reg_usage[i * 2][0], regs[i * 2], - i * 2 + 1, reg_usage[i * 2 + 1][0], regs[i * 2 + 1]); - } - - for (i = 0; i < 32 / 2; i++) - { - DUMP_PRINTF( - "freg[%02d](%s) = 0x%016lx(%f), freg[%02d](%s) = 0x%016lx(%f)\r\n", - i * 2, regf_usage[i * 2][0], fregs[i * 2], (float)fregs[i * 2], - i * 2 + 1, regf_usage[i * 2 + 1][0], fregs[i * 2 + 1], (float)fregs[i * 2 + 1]); - } - } -} - -#undef DUMP_PRINTF - -#ifdef __cplusplus -} -#endif - -#endif /* _BSP_DUMP_H */ - diff --git a/cores/arduino/kendryte-standalone-sdk/lib/bsp/include/encoding.h b/cores/arduino/kendryte-standalone-sdk/lib/bsp/include/encoding.h deleted file mode 100644 index 06cacea..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/bsp/include/encoding.h +++ /dev/null @@ -1,1326 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef RISCV_CSR_ENCODING_H -#define RISCV_CSR_ENCODING_H - -#define MSTATUS_UIE 0x00000001U -#define MSTATUS_SIE 0x00000002U -#define MSTATUS_HIE 0x00000004U -#define MSTATUS_MIE 0x00000008U -#define MSTATUS_UPIE 0x00000010U -#define MSTATUS_SPIE 0x00000020U -#define MSTATUS_HPIE 0x00000040U -#define MSTATUS_MPIE 0x00000080U -#define MSTATUS_SPP 0x00000100U -#define MSTATUS_HPP 0x00000600U -#define MSTATUS_MPP 0x00001800U -#define MSTATUS_FS 0x00006000U -#define MSTATUS_XS 0x00018000U -#define MSTATUS_MPRV 0x00020000U -#define MSTATUS_PUM 0x00040000U -#define MSTATUS_MXR 0x00080000U -#define MSTATUS_VM 0x1F000000U -#define MSTATUS32_SD 0x80000000U -#define MSTATUS64_SD 0x8000000000000000U - -#define SSTATUS_UIE 0x00000001U -#define SSTATUS_SIE 0x00000002U -#define SSTATUS_UPIE 0x00000010U -#define SSTATUS_SPIE 0x00000020U -#define SSTATUS_SPP 0x00000100U -#define SSTATUS_FS 0x00006000U -#define SSTATUS_XS 0x00018000U -#define SSTATUS_PUM 0x00040000U -#define SSTATUS32_SD 0x80000000U -#define SSTATUS64_SD 0x8000000000000000U - -#define DCSR_XDEBUGVER (3U<<30) -#define DCSR_NDRESET (1U<<29) -#define DCSR_FULLRESET (1U<<28) -#define DCSR_EBREAKM (1U<<15) -#define DCSR_EBREAKH (1U<<14) -#define DCSR_EBREAKS (1U<<13) -#define DCSR_EBREAKU (1U<<12) -#define DCSR_STOPCYCLE (1U<<10) -#define DCSR_STOPTIME (1U<<9) -#define DCSR_CAUSE (7U<<6) -#define DCSR_DEBUGINT (1U<<5) -#define DCSR_HALT (1U<<3) -#define DCSR_STEP (1U<<2) -#define DCSR_PRV (3U<<0) - -#define DCSR_CAUSE_NONE 0 -#define DCSR_CAUSE_SWBP 1 -#define DCSR_CAUSE_HWBP 2 -#define DCSR_CAUSE_DEBUGINT 3 -#define DCSR_CAUSE_STEP 4 -#define DCSR_CAUSE_HALT 5 - -#define MCONTROL_SELECT (1U<<19) -#define MCONTROL_TIMING (1U<<18) -#define MCONTROL_ACTION (0x3fU<<12) -#define MCONTROL_CHAIN (1U<<11) -#define MCONTROL_MATCH (0xfU<<7) -#define MCONTROL_M (1U<<6) -#define MCONTROL_H (1U<<5) -#define MCONTROL_S (1U<<4) -#define MCONTROL_U (1U<<3) -#define MCONTROL_EXECUTE (1U<<2) -#define MCONTROL_STORE (1U<<1) -#define MCONTROL_LOAD (1U<<0) - -#define MCONTROL_TYPE_NONE 0 -#define MCONTROL_TYPE_MATCH 2 - -#define MCONTROL_ACTION_DEBUG_EXCEPTION 0 -#define MCONTROL_ACTION_DEBUG_MODE 1 -#define MCONTROL_ACTION_TRACE_START 2 -#define MCONTROL_ACTION_TRACE_STOP 3 -#define MCONTROL_ACTION_TRACE_EMIT 4 - -#define MCONTROL_MATCH_EQUAL 0 -#define MCONTROL_MATCH_NAPOT 1 -#define MCONTROL_MATCH_GE 2 -#define MCONTROL_MATCH_LT 3 -#define MCONTROL_MATCH_MASK_LOW 4 -#define MCONTROL_MATCH_MASK_HIGH 5 - -#define MIP_SSIP (1U << IRQ_S_SOFT) -#define MIP_HSIP (1U << IRQ_H_SOFT) -#define MIP_MSIP (1U << IRQ_M_SOFT) -#define MIP_STIP (1U << IRQ_S_TIMER) -#define MIP_HTIP (1U << IRQ_H_TIMER) -#define MIP_MTIP (1U << IRQ_M_TIMER) -#define MIP_SEIP (1U << IRQ_S_EXT) -#define MIP_HEIP (1U << IRQ_H_EXT) -#define MIP_MEIP (1U << IRQ_M_EXT) - -#define SIP_SSIP MIP_SSIP -#define SIP_STIP MIP_STIP - -#define PRV_U 0 -#define PRV_S 1 -#define PRV_H 2 -#define PRV_M 3 - -#define VM_MBARE 0 -#define VM_MBB 1 -#define VM_MBBID 2 -#define VM_SV32 8 -#define VM_SV39 9 -#define VM_SV48 10 - -#define IRQ_S_SOFT 1 -#define IRQ_H_SOFT 2 -#define IRQ_M_SOFT 3 -#define IRQ_S_TIMER 5 -#define IRQ_H_TIMER 6 -#define IRQ_M_TIMER 7 -#define IRQ_S_EXT 9 -#define IRQ_H_EXT 10 -#define IRQ_M_EXT 11 -#define IRQ_COP 12 -#define IRQ_HOST 13 - -#define DEFAULT_RSTVEC 0x00001000U -#define DEFAULT_NMIVEC 0x00001004U -#define DEFAULT_MTVEC 0x00001010U -#define CONFIG_STRING_ADDR 0x0000100CU -#define EXT_IO_BASE 0x40000000U -#define DRAM_BASE 0x80000000U - -/* page table entry (PTE) fields */ -#define PTE_V 0x001U /* Valid */ -#define PTE_R 0x002U /* Read */ -#define PTE_W 0x004U /* Write */ -#define PTE_X 0x008U /* Execute */ -#define PTE_U 0x010U /* User */ -#define PTE_G 0x020U /* Global */ -#define PTE_A 0x040U /* Accessed */ -#define PTE_D 0x080U /* Dirty */ -#define PTE_SOFT 0x300U /* Reserved for Software */ - -#define PTE_PPN_SHIFT 10 - -#define MCONTROL_TYPE(xlen) (0xfULL<<((xlen)-4)) -#define MCONTROL_DMODE(xlen) (1ULL<<((xlen)-5)) -#define MCONTROL_MASKMAX(xlen) (0x3fULL<<((xlen)-11)) - -#define PTE_TABLE(PTE) (((PTE) & (PTE_V | PTE_R | PTE_W | PTE_X)) == PTE_V) - -#if defined(__riscv) - -#if defined(__riscv64) -# define MSTATUS_SD MSTATUS64_SD -# define SSTATUS_SD SSTATUS64_SD -# define RISCV_PGLEVEL_BITS 9 -#else -# define MSTATUS_SD MSTATUS32_SD -# define SSTATUS_SD SSTATUS32_SD -# define RISCV_PGLEVEL_BITS 10 -#endif -#define RISCV_PGSHIFT 12 -#define RISCV_PGSIZE (1 << RISCV_PGSHIFT) - -#ifndef __ASSEMBLER__ - -#if defined(__GNUC__) - -#define read_csr(reg) ({ unsigned long __tmp; \ - asm volatile ("csrr %0, " #reg : "=r"(__tmp)); \ - __tmp; }) - -#define write_csr(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 swap_csr(reg, val) ({ unsigned long __tmp; \ - if (__builtin_constant_p(val) && (unsigned long)(val) < 32) \ - asm volatile ("csrrw %0, " #reg ", %1" : "=r"(__tmp) : "i"(val)); \ - else \ - asm volatile ("csrrw %0, " #reg ", %1" : "=r"(__tmp) : "r"(val)); \ - __tmp; }) - -#define set_csr(reg, bit) ({ unsigned long __tmp; \ - if (__builtin_constant_p(bit) && (unsigned long)(bit) < 32) \ - asm volatile ("csrrs %0, " #reg ", %1" : "=r"(__tmp) : "i"(bit)); \ - else \ - asm volatile ("csrrs %0, " #reg ", %1" : "=r"(__tmp) : "r"(bit)); \ - __tmp; }) - -#define clear_csr(reg, bit) ({ unsigned long __tmp; \ - if (__builtin_constant_p(bit) && (unsigned long)(bit) < 32) \ - asm volatile ("csrrc %0, " #reg ", %1" : "=r"(__tmp) : "i"(bit)); \ - else \ - asm volatile ("csrrc %0, " #reg ", %1" : "=r"(__tmp) : "r"(bit)); \ - __tmp; }) - -#define read_time() read_csr(mtime) -#define read_cycle() read_csr(mcycle) -#define current_coreid() read_csr(mhartid) - -#endif - -#endif - -#endif - -#endif - -#ifndef RISCV_ENCODING_H -#define RISCV_ENCODING_H -#define MATCH_BEQ 0x63U -#define MASK_BEQ 0x707fU -#define MATCH_BNE 0x1063U -#define MASK_BNE 0x707fU -#define MATCH_BLT 0x4063U -#define MASK_BLT 0x707fU -#define MATCH_BGE 0x5063U -#define MASK_BGE 0x707fU -#define MATCH_BLTU 0x6063U -#define MASK_BLTU 0x707fU -#define MATCH_BGEU 0x7063U -#define MASK_BGEU 0x707fU -#define MATCH_JALR 0x67U -#define MASK_JALR 0x707fU -#define MATCH_JAL 0x6fU -#define MASK_JAL 0x7fU -#define MATCH_LUI 0x37U -#define MASK_LUI 0x7fU -#define MATCH_AUIPC 0x17U -#define MASK_AUIPC 0x7fU -#define MATCH_ADDI 0x13U -#define MASK_ADDI 0x707fU -#define MATCH_SLLI 0x1013U -#define MASK_SLLI 0xfc00707fU -#define MATCH_SLTI 0x2013U -#define MASK_SLTI 0x707fU -#define MATCH_SLTIU 0x3013U -#define MASK_SLTIU 0x707fU -#define MATCH_XORI 0x4013U -#define MASK_XORI 0x707fU -#define MATCH_SRLI 0x5013U -#define MASK_SRLI 0xfc00707fU -#define MATCH_SRAI 0x40005013U -#define MASK_SRAI 0xfc00707fU -#define MATCH_ORI 0x6013U -#define MASK_ORI 0x707fU -#define MATCH_ANDI 0x7013U -#define MASK_ANDI 0x707fU -#define MATCH_ADD 0x33U -#define MASK_ADD 0xfe00707fU -#define MATCH_SUB 0x40000033U -#define MASK_SUB 0xfe00707fU -#define MATCH_SLL 0x1033U -#define MASK_SLL 0xfe00707fU -#define MATCH_SLT 0x2033U -#define MASK_SLT 0xfe00707fU -#define MATCH_SLTU 0x3033U -#define MASK_SLTU 0xfe00707fU -#define MATCH_XOR 0x4033U -#define MASK_XOR 0xfe00707fU -#define MATCH_SRL 0x5033U -#define MASK_SRL 0xfe00707fU -#define MATCH_SRA 0x40005033U -#define MASK_SRA 0xfe00707fU -#define MATCH_OR 0x6033U -#define MASK_OR 0xfe00707fU -#define MATCH_AND 0x7033U -#define MASK_AND 0xfe00707fU -#define MATCH_ADDIW 0x1bU -#define MASK_ADDIW 0x707fU -#define MATCH_SLLIW 0x101bU -#define MASK_SLLIW 0xfe00707fU -#define MATCH_SRLIW 0x501bU -#define MASK_SRLIW 0xfe00707fU -#define MATCH_SRAIW 0x4000501bU -#define MASK_SRAIW 0xfe00707fU -#define MATCH_ADDW 0x3bU -#define MASK_ADDW 0xfe00707fU -#define MATCH_SUBW 0x4000003bU -#define MASK_SUBW 0xfe00707fU -#define MATCH_SLLW 0x103bU -#define MASK_SLLW 0xfe00707fU -#define MATCH_SRLW 0x503bU -#define MASK_SRLW 0xfe00707fU -#define MATCH_SRAW 0x4000503bU -#define MASK_SRAW 0xfe00707fU -#define MATCH_LB 0x3U -#define MASK_LB 0x707fU -#define MATCH_LH 0x1003U -#define MASK_LH 0x707fU -#define MATCH_LW 0x2003U -#define MASK_LW 0x707fU -#define MATCH_LD 0x3003U -#define MASK_LD 0x707fU -#define MATCH_LBU 0x4003U -#define MASK_LBU 0x707fU -#define MATCH_LHU 0x5003U -#define MASK_LHU 0x707fU -#define MATCH_LWU 0x6003U -#define MASK_LWU 0x707fU -#define MATCH_SB 0x23U -#define MASK_SB 0x707fU -#define MATCH_SH 0x1023U -#define MASK_SH 0x707fU -#define MATCH_SW 0x2023U -#define MASK_SW 0x707fU -#define MATCH_SD 0x3023U -#define MASK_SD 0x707fU -#define MATCH_FENCE 0xfU -#define MASK_FENCE 0x707fU -#define MATCH_FENCE_I 0x100fU -#define MASK_FENCE_I 0x707fU -#define MATCH_MUL 0x2000033U -#define MASK_MUL 0xfe00707fU -#define MATCH_MULH 0x2001033U -#define MASK_MULH 0xfe00707fU -#define MATCH_MULHSU 0x2002033U -#define MASK_MULHSU 0xfe00707fU -#define MATCH_MULHU 0x2003033U -#define MASK_MULHU 0xfe00707fU -#define MATCH_DIV 0x2004033U -#define MASK_DIV 0xfe00707fU -#define MATCH_DIVU 0x2005033U -#define MASK_DIVU 0xfe00707fU -#define MATCH_REM 0x2006033U -#define MASK_REM 0xfe00707fU -#define MATCH_REMU 0x2007033U -#define MASK_REMU 0xfe00707fU -#define MATCH_MULW 0x200003bU -#define MASK_MULW 0xfe00707fU -#define MATCH_DIVW 0x200403bU -#define MASK_DIVW 0xfe00707fU -#define MATCH_DIVUW 0x200503bU -#define MASK_DIVUW 0xfe00707fU -#define MATCH_REMW 0x200603bU -#define MASK_REMW 0xfe00707fU -#define MATCH_REMUW 0x200703bU -#define MASK_REMUW 0xfe00707fU -#define MATCH_AMOADD_W 0x202fU -#define MASK_AMOADD_W 0xf800707fU -#define MATCH_AMOXOR_W 0x2000202fU -#define MASK_AMOXOR_W 0xf800707fU -#define MATCH_AMOOR_W 0x4000202fU -#define MASK_AMOOR_W 0xf800707fU -#define MATCH_AMOAND_W 0x6000202fU -#define MASK_AMOAND_W 0xf800707fU -#define MATCH_AMOMIN_W 0x8000202fU -#define MASK_AMOMIN_W 0xf800707fU -#define MATCH_AMOMAX_W 0xa000202fU -#define MASK_AMOMAX_W 0xf800707fU -#define MATCH_AMOMINU_W 0xc000202fU -#define MASK_AMOMINU_W 0xf800707fU -#define MATCH_AMOMAXU_W 0xe000202fU -#define MASK_AMOMAXU_W 0xf800707fU -#define MATCH_AMOSWAP_W 0x800202fU -#define MASK_AMOSWAP_W 0xf800707fU -#define MATCH_LR_W 0x1000202fU -#define MASK_LR_W 0xf9f0707fU -#define MATCH_SC_W 0x1800202fU -#define MASK_SC_W 0xf800707fU -#define MATCH_AMOADD_D 0x302fU -#define MASK_AMOADD_D 0xf800707fU -#define MATCH_AMOXOR_D 0x2000302fU -#define MASK_AMOXOR_D 0xf800707fU -#define MATCH_AMOOR_D 0x4000302fU -#define MASK_AMOOR_D 0xf800707fU -#define MATCH_AMOAND_D 0x6000302fU -#define MASK_AMOAND_D 0xf800707fU -#define MATCH_AMOMIN_D 0x8000302fU -#define MASK_AMOMIN_D 0xf800707fU -#define MATCH_AMOMAX_D 0xa000302fU -#define MASK_AMOMAX_D 0xf800707fU -#define MATCH_AMOMINU_D 0xc000302fU -#define MASK_AMOMINU_D 0xf800707fU -#define MATCH_AMOMAXU_D 0xe000302fU -#define MASK_AMOMAXU_D 0xf800707fU -#define MATCH_AMOSWAP_D 0x800302fU -#define MASK_AMOSWAP_D 0xf800707fU -#define MATCH_LR_D 0x1000302fU -#define MASK_LR_D 0xf9f0707fU -#define MATCH_SC_D 0x1800302fU -#define MASK_SC_D 0xf800707fU -#define MATCH_ECALL 0x73U -#define MASK_ECALL 0xffffffffU -#define MATCH_EBREAK 0x100073U -#define MASK_EBREAK 0xffffffffU -#define MATCH_URET 0x200073U -#define MASK_URET 0xffffffffU -#define MATCH_SRET 0x10200073U -#define MASK_SRET 0xffffffffU -#define MATCH_HRET 0x20200073U -#define MASK_HRET 0xffffffffU -#define MATCH_MRET 0x30200073U -#define MASK_MRET 0xffffffffU -#define MATCH_DRET 0x7b200073U -#define MASK_DRET 0xffffffffU -#define MATCH_SFENCE_VM 0x10400073U -#define MASK_SFENCE_VM 0xfff07fffU -#define MATCH_WFI 0x10500073U -#define MASK_WFI 0xffffffffU -#define MATCH_CSRRW 0x1073U -#define MASK_CSRRW 0x707fU -#define MATCH_CSRRS 0x2073U -#define MASK_CSRRS 0x707fU -#define MATCH_CSRRC 0x3073U -#define MASK_CSRRC 0x707fU -#define MATCH_CSRRWI 0x5073U -#define MASK_CSRRWI 0x707fU -#define MATCH_CSRRSI 0x6073U -#define MASK_CSRRSI 0x707fU -#define MATCH_CSRRCI 0x7073U -#define MASK_CSRRCI 0x707fU -#define MATCH_FADD_S 0x53U -#define MASK_FADD_S 0xfe00007fU -#define MATCH_FSUB_S 0x8000053U -#define MASK_FSUB_S 0xfe00007fU -#define MATCH_FMUL_S 0x10000053U -#define MASK_FMUL_S 0xfe00007fU -#define MATCH_FDIV_S 0x18000053U -#define MASK_FDIV_S 0xfe00007fU -#define MATCH_FSGNJ_S 0x20000053U -#define MASK_FSGNJ_S 0xfe00707fU -#define MATCH_FSGNJN_S 0x20001053U -#define MASK_FSGNJN_S 0xfe00707fU -#define MATCH_FSGNJX_S 0x20002053U -#define MASK_FSGNJX_S 0xfe00707fU -#define MATCH_FMIN_S 0x28000053U -#define MASK_FMIN_S 0xfe00707fU -#define MATCH_FMAX_S 0x28001053U -#define MASK_FMAX_S 0xfe00707fU -#define MATCH_FSQRT_S 0x58000053U -#define MASK_FSQRT_S 0xfff0007fU -#define MATCH_FADD_D 0x2000053U -#define MASK_FADD_D 0xfe00007fU -#define MATCH_FSUB_D 0xa000053U -#define MASK_FSUB_D 0xfe00007fU -#define MATCH_FMUL_D 0x12000053U -#define MASK_FMUL_D 0xfe00007fU -#define MATCH_FDIV_D 0x1a000053U -#define MASK_FDIV_D 0xfe00007fU -#define MATCH_FSGNJ_D 0x22000053U -#define MASK_FSGNJ_D 0xfe00707fU -#define MATCH_FSGNJN_D 0x22001053U -#define MASK_FSGNJN_D 0xfe00707fU -#define MATCH_FSGNJX_D 0x22002053U -#define MASK_FSGNJX_D 0xfe00707fU -#define MATCH_FMIN_D 0x2a000053U -#define MASK_FMIN_D 0xfe00707fU -#define MATCH_FMAX_D 0x2a001053U -#define MASK_FMAX_D 0xfe00707fU -#define MATCH_FCVT_S_D 0x40100053U -#define MASK_FCVT_S_D 0xfff0007fU -#define MATCH_FCVT_D_S 0x42000053U -#define MASK_FCVT_D_S 0xfff0007fU -#define MATCH_FSQRT_D 0x5a000053U -#define MASK_FSQRT_D 0xfff0007fU -#define MATCH_FLE_S 0xa0000053U -#define MASK_FLE_S 0xfe00707fU -#define MATCH_FLT_S 0xa0001053U -#define MASK_FLT_S 0xfe00707fU -#define MATCH_FEQ_S 0xa0002053U -#define MASK_FEQ_S 0xfe00707fU -#define MATCH_FLE_D 0xa2000053U -#define MASK_FLE_D 0xfe00707fU -#define MATCH_FLT_D 0xa2001053U -#define MASK_FLT_D 0xfe00707fU -#define MATCH_FEQ_D 0xa2002053U -#define MASK_FEQ_D 0xfe00707fU -#define MATCH_FCVT_W_S 0xc0000053U -#define MASK_FCVT_W_S 0xfff0007fU -#define MATCH_FCVT_WU_S 0xc0100053U -#define MASK_FCVT_WU_S 0xfff0007fU -#define MATCH_FCVT_L_S 0xc0200053U -#define MASK_FCVT_L_S 0xfff0007fU -#define MATCH_FCVT_LU_S 0xc0300053U -#define MASK_FCVT_LU_S 0xfff0007fU -#define MATCH_FMV_X_S 0xe0000053U -#define MASK_FMV_X_S 0xfff0707fU -#define MATCH_FCLASS_S 0xe0001053U -#define MASK_FCLASS_S 0xfff0707fU -#define MATCH_FCVT_W_D 0xc2000053U -#define MASK_FCVT_W_D 0xfff0007fU -#define MATCH_FCVT_WU_D 0xc2100053U -#define MASK_FCVT_WU_D 0xfff0007fU -#define MATCH_FCVT_L_D 0xc2200053U -#define MASK_FCVT_L_D 0xfff0007fU -#define MATCH_FCVT_LU_D 0xc2300053U -#define MASK_FCVT_LU_D 0xfff0007fU -#define MATCH_FMV_X_D 0xe2000053U -#define MASK_FMV_X_D 0xfff0707fU -#define MATCH_FCLASS_D 0xe2001053U -#define MASK_FCLASS_D 0xfff0707fU -#define MATCH_FCVT_S_W 0xd0000053U -#define MASK_FCVT_S_W 0xfff0007fU -#define MATCH_FCVT_S_WU 0xd0100053U -#define MASK_FCVT_S_WU 0xfff0007fU -#define MATCH_FCVT_S_L 0xd0200053U -#define MASK_FCVT_S_L 0xfff0007fU -#define MATCH_FCVT_S_LU 0xd0300053U -#define MASK_FCVT_S_LU 0xfff0007fU -#define MATCH_FMV_S_X 0xf0000053U -#define MASK_FMV_S_X 0xfff0707fU -#define MATCH_FCVT_D_W 0xd2000053U -#define MASK_FCVT_D_W 0xfff0007fU -#define MATCH_FCVT_D_WU 0xd2100053U -#define MASK_FCVT_D_WU 0xfff0007fU -#define MATCH_FCVT_D_L 0xd2200053U -#define MASK_FCVT_D_L 0xfff0007fU -#define MATCH_FCVT_D_LU 0xd2300053U -#define MASK_FCVT_D_LU 0xfff0007fU -#define MATCH_FMV_D_X 0xf2000053U -#define MASK_FMV_D_X 0xfff0707fU -#define MATCH_FLW 0x2007U -#define MASK_FLW 0x707fU -#define MATCH_FLD 0x3007U -#define MASK_FLD 0x707fU -#define MATCH_FSW 0x2027U -#define MASK_FSW 0x707fU -#define MATCH_FSD 0x3027U -#define MASK_FSD 0x707fU -#define MATCH_FMADD_S 0x43U -#define MASK_FMADD_S 0x600007fU -#define MATCH_FMSUB_S 0x47U -#define MASK_FMSUB_S 0x600007fU -#define MATCH_FNMSUB_S 0x4bU -#define MASK_FNMSUB_S 0x600007fU -#define MATCH_FNMADD_S 0x4fU -#define MASK_FNMADD_S 0x600007fU -#define MATCH_FMADD_D 0x2000043U -#define MASK_FMADD_D 0x600007fU -#define MATCH_FMSUB_D 0x2000047U -#define MASK_FMSUB_D 0x600007fU -#define MATCH_FNMSUB_D 0x200004bU -#define MASK_FNMSUB_D 0x600007fU -#define MATCH_FNMADD_D 0x200004fU -#define MASK_FNMADD_D 0x600007fU -#define MATCH_C_NOP 0x1U -#define MASK_C_NOP 0xffffU -#define MATCH_C_ADDI16SP 0x6101U -#define MASK_C_ADDI16SP 0xef83U -#define MATCH_C_JR 0x8002U -#define MASK_C_JR 0xf07fU -#define MATCH_C_JALR 0x9002U -#define MASK_C_JALR 0xf07fU -#define MATCH_C_EBREAK 0x9002U -#define MASK_C_EBREAK 0xffffU -#define MATCH_C_LD 0x6000U -#define MASK_C_LD 0xe003U -#define MATCH_C_SD 0xe000U -#define MASK_C_SD 0xe003U -#define MATCH_C_ADDIW 0x2001U -#define MASK_C_ADDIW 0xe003U -#define MATCH_C_LDSP 0x6002U -#define MASK_C_LDSP 0xe003U -#define MATCH_C_SDSP 0xe002U -#define MASK_C_SDSP 0xe003U -#define MATCH_C_ADDI4SPN 0x0U -#define MASK_C_ADDI4SPN 0xe003U -#define MATCH_C_FLD 0x2000U -#define MASK_C_FLD 0xe003U -#define MATCH_C_LW 0x4000U -#define MASK_C_LW 0xe003U -#define MATCH_C_FLW 0x6000U -#define MASK_C_FLW 0xe003U -#define MATCH_C_FSD 0xa000U -#define MASK_C_FSD 0xe003U -#define MATCH_C_SW 0xc000U -#define MASK_C_SW 0xe003U -#define MATCH_C_FSW 0xe000U -#define MASK_C_FSW 0xe003U -#define MATCH_C_ADDI 0x1U -#define MASK_C_ADDI 0xe003U -#define MATCH_C_JAL 0x2001U -#define MASK_C_JAL 0xe003U -#define MATCH_C_LI 0x4001U -#define MASK_C_LI 0xe003U -#define MATCH_C_LUI 0x6001U -#define MASK_C_LUI 0xe003U -#define MATCH_C_SRLI 0x8001U -#define MASK_C_SRLI 0xec03U -#define MATCH_C_SRAI 0x8401U -#define MASK_C_SRAI 0xec03U -#define MATCH_C_ANDI 0x8801U -#define MASK_C_ANDI 0xec03U -#define MATCH_C_SUB 0x8c01U -#define MASK_C_SUB 0xfc63U -#define MATCH_C_XOR 0x8c21U -#define MASK_C_XOR 0xfc63U -#define MATCH_C_OR 0x8c41U -#define MASK_C_OR 0xfc63U -#define MATCH_C_AND 0x8c61U -#define MASK_C_AND 0xfc63U -#define MATCH_C_SUBW 0x9c01U -#define MASK_C_SUBW 0xfc63U -#define MATCH_C_ADDW 0x9c21U -#define MASK_C_ADDW 0xfc63U -#define MATCH_C_J 0xa001U -#define MASK_C_J 0xe003U -#define MATCH_C_BEQZ 0xc001U -#define MASK_C_BEQZ 0xe003U -#define MATCH_C_BNEZ 0xe001U -#define MASK_C_BNEZ 0xe003U -#define MATCH_C_SLLI 0x2U -#define MASK_C_SLLI 0xe003U -#define MATCH_C_FLDSP 0x2002U -#define MASK_C_FLDSP 0xe003U -#define MATCH_C_LWSP 0x4002U -#define MASK_C_LWSP 0xe003U -#define MATCH_C_FLWSP 0x6002U -#define MASK_C_FLWSP 0xe003U -#define MATCH_C_MV 0x8002U -#define MASK_C_MV 0xf003U -#define MATCH_C_ADD 0x9002U -#define MASK_C_ADD 0xf003U -#define MATCH_C_FSDSP 0xa002U -#define MASK_C_FSDSP 0xe003U -#define MATCH_C_SWSP 0xc002U -#define MASK_C_SWSP 0xe003U -#define MATCH_C_FSWSP 0xe002U -#define MASK_C_FSWSP 0xe003U -#define MATCH_CUSTOM0 0xbU -#define MASK_CUSTOM0 0x707fU -#define MATCH_CUSTOM0_RS1 0x200bU -#define MASK_CUSTOM0_RS1 0x707fU -#define MATCH_CUSTOM0_RS1_RS2 0x300bU -#define MASK_CUSTOM0_RS1_RS2 0x707fU -#define MATCH_CUSTOM0_RD 0x400bU -#define MASK_CUSTOM0_RD 0x707fU -#define MATCH_CUSTOM0_RD_RS1 0x600bU -#define MASK_CUSTOM0_RD_RS1 0x707fU -#define MATCH_CUSTOM0_RD_RS1_RS2 0x700bU -#define MASK_CUSTOM0_RD_RS1_RS2 0x707fU -#define MATCH_CUSTOM1 0x2bU -#define MASK_CUSTOM1 0x707fU -#define MATCH_CUSTOM1_RS1 0x202bU -#define MASK_CUSTOM1_RS1 0x707fU -#define MATCH_CUSTOM1_RS1_RS2 0x302bU -#define MASK_CUSTOM1_RS1_RS2 0x707fU -#define MATCH_CUSTOM1_RD 0x402bU -#define MASK_CUSTOM1_RD 0x707fU -#define MATCH_CUSTOM1_RD_RS1 0x602bU -#define MASK_CUSTOM1_RD_RS1 0x707fU -#define MATCH_CUSTOM1_RD_RS1_RS2 0x702bU -#define MASK_CUSTOM1_RD_RS1_RS2 0x707fU -#define MATCH_CUSTOM2 0x5bU -#define MASK_CUSTOM2 0x707fU -#define MATCH_CUSTOM2_RS1 0x205bU -#define MASK_CUSTOM2_RS1 0x707fU -#define MATCH_CUSTOM2_RS1_RS2 0x305bU -#define MASK_CUSTOM2_RS1_RS2 0x707fU -#define MATCH_CUSTOM2_RD 0x405bU -#define MASK_CUSTOM2_RD 0x707fU -#define MATCH_CUSTOM2_RD_RS1 0x605bU -#define MASK_CUSTOM2_RD_RS1 0x707fU -#define MATCH_CUSTOM2_RD_RS1_RS2 0x705bU -#define MASK_CUSTOM2_RD_RS1_RS2 0x707fU -#define MATCH_CUSTOM3 0x7bU -#define MASK_CUSTOM3 0x707fU -#define MATCH_CUSTOM3_RS1 0x207bU -#define MASK_CUSTOM3_RS1 0x707fU -#define MATCH_CUSTOM3_RS1_RS2 0x307bU -#define MASK_CUSTOM3_RS1_RS2 0x707fU -#define MATCH_CUSTOM3_RD 0x407bU -#define MASK_CUSTOM3_RD 0x707fU -#define MATCH_CUSTOM3_RD_RS1 0x607bU -#define MASK_CUSTOM3_RD_RS1 0x707fU -#define MATCH_CUSTOM3_RD_RS1_RS2 0x707bU -#define MASK_CUSTOM3_RD_RS1_RS2 0x707fU -#define CSR_FFLAGS 0x1U -#define CSR_FRM 0x2U -#define CSR_FCSR 0x3U -#define CSR_CYCLE 0xc00U -#define CSR_TIME 0xc01U -#define CSR_INSTRET 0xc02U -#define CSR_HPMCOUNTER3 0xc03U -#define CSR_HPMCOUNTER4 0xc04U -#define CSR_HPMCOUNTER5 0xc05U -#define CSR_HPMCOUNTER6 0xc06U -#define CSR_HPMCOUNTER7 0xc07U -#define CSR_HPMCOUNTER8 0xc08U -#define CSR_HPMCOUNTER9 0xc09U -#define CSR_HPMCOUNTER10 0xc0aU -#define CSR_HPMCOUNTER11 0xc0bU -#define CSR_HPMCOUNTER12 0xc0cU -#define CSR_HPMCOUNTER13 0xc0dU -#define CSR_HPMCOUNTER14 0xc0eU -#define CSR_HPMCOUNTER15 0xc0fU -#define CSR_HPMCOUNTER16 0xc10U -#define CSR_HPMCOUNTER17 0xc11U -#define CSR_HPMCOUNTER18 0xc12U -#define CSR_HPMCOUNTER19 0xc13U -#define CSR_HPMCOUNTER20 0xc14U -#define CSR_HPMCOUNTER21 0xc15U -#define CSR_HPMCOUNTER22 0xc16U -#define CSR_HPMCOUNTER23 0xc17U -#define CSR_HPMCOUNTER24 0xc18U -#define CSR_HPMCOUNTER25 0xc19U -#define CSR_HPMCOUNTER26 0xc1aU -#define CSR_HPMCOUNTER27 0xc1bU -#define CSR_HPMCOUNTER28 0xc1cU -#define CSR_HPMCOUNTER29 0xc1dU -#define CSR_HPMCOUNTER30 0xc1eU -#define CSR_HPMCOUNTER31 0xc1fU -#define CSR_SSTATUS 0x100U -#define CSR_SIE 0x104U -#define CSR_STVEC 0x105U -#define CSR_SSCRATCH 0x140U -#define CSR_SEPC 0x141U -#define CSR_SCAUSE 0x142U -#define CSR_SBADADDR 0x143U -#define CSR_SIP 0x144U -#define CSR_SPTBR 0x180U -#define CSR_MSTATUS 0x300U -#define CSR_MISA 0x301U -#define CSR_MEDELEG 0x302U -#define CSR_MIDELEG 0x303U -#define CSR_MIE 0x304U -#define CSR_MTVEC 0x305U -#define CSR_MSCRATCH 0x340U -#define CSR_MEPC 0x341U -#define CSR_MCAUSE 0x342U -#define CSR_MBADADDR 0x343U -#define CSR_MIP 0x344U -#define CSR_TSELECT 0x7a0U -#define CSR_TDATA1 0x7a1U -#define CSR_TDATA2 0x7a2U -#define CSR_TDATA3 0x7a3U -#define CSR_DCSR 0x7b0U -#define CSR_DPC 0x7b1U -#define CSR_DSCRATCH 0x7b2U -#define CSR_MCYCLE 0xb00U -#define CSR_MINSTRET 0xb02U -#define CSR_MHPMCOUNTER3 0xb03U -#define CSR_MHPMCOUNTER4 0xb04U -#define CSR_MHPMCOUNTER5 0xb05U -#define CSR_MHPMCOUNTER6 0xb06U -#define CSR_MHPMCOUNTER7 0xb07U -#define CSR_MHPMCOUNTER8 0xb08U -#define CSR_MHPMCOUNTER9 0xb09U -#define CSR_MHPMCOUNTER10 0xb0aU -#define CSR_MHPMCOUNTER11 0xb0bU -#define CSR_MHPMCOUNTER12 0xb0cU -#define CSR_MHPMCOUNTER13 0xb0dU -#define CSR_MHPMCOUNTER14 0xb0eU -#define CSR_MHPMCOUNTER15 0xb0fU -#define CSR_MHPMCOUNTER16 0xb10U -#define CSR_MHPMCOUNTER17 0xb11U -#define CSR_MHPMCOUNTER18 0xb12U -#define CSR_MHPMCOUNTER19 0xb13U -#define CSR_MHPMCOUNTER20 0xb14U -#define CSR_MHPMCOUNTER21 0xb15U -#define CSR_MHPMCOUNTER22 0xb16U -#define CSR_MHPMCOUNTER23 0xb17U -#define CSR_MHPMCOUNTER24 0xb18U -#define CSR_MHPMCOUNTER25 0xb19U -#define CSR_MHPMCOUNTER26 0xb1aU -#define CSR_MHPMCOUNTER27 0xb1bU -#define CSR_MHPMCOUNTER28 0xb1cU -#define CSR_MHPMCOUNTER29 0xb1dU -#define CSR_MHPMCOUNTER30 0xb1eU -#define CSR_MHPMCOUNTER31 0xb1fU -#define CSR_MUCOUNTEREN 0x320U -#define CSR_MSCOUNTEREN 0x321U -#define CSR_MHPMEVENT3 0x323U -#define CSR_MHPMEVENT4 0x324U -#define CSR_MHPMEVENT5 0x325U -#define CSR_MHPMEVENT6 0x326U -#define CSR_MHPMEVENT7 0x327U -#define CSR_MHPMEVENT8 0x328U -#define CSR_MHPMEVENT9 0x329U -#define CSR_MHPMEVENT10 0x32aU -#define CSR_MHPMEVENT11 0x32bU -#define CSR_MHPMEVENT12 0x32cU -#define CSR_MHPMEVENT13 0x32dU -#define CSR_MHPMEVENT14 0x32eU -#define CSR_MHPMEVENT15 0x32fU -#define CSR_MHPMEVENT16 0x330U -#define CSR_MHPMEVENT17 0x331U -#define CSR_MHPMEVENT18 0x332U -#define CSR_MHPMEVENT19 0x333U -#define CSR_MHPMEVENT20 0x334U -#define CSR_MHPMEVENT21 0x335U -#define CSR_MHPMEVENT22 0x336U -#define CSR_MHPMEVENT23 0x337U -#define CSR_MHPMEVENT24 0x338U -#define CSR_MHPMEVENT25 0x339U -#define CSR_MHPMEVENT26 0x33aU -#define CSR_MHPMEVENT27 0x33bU -#define CSR_MHPMEVENT28 0x33cU -#define CSR_MHPMEVENT29 0x33dU -#define CSR_MHPMEVENT30 0x33eU -#define CSR_MHPMEVENT31 0x33fU -#define CSR_MVENDORID 0xf11U -#define CSR_MARCHID 0xf12U -#define CSR_MIMPID 0xf13U -#define CSR_MHARTID 0xf14U -#define CSR_CYCLEH 0xc80U -#define CSR_TIMEH 0xc81U -#define CSR_INSTRETH 0xc82U -#define CSR_HPMCOUNTER3H 0xc83U -#define CSR_HPMCOUNTER4H 0xc84U -#define CSR_HPMCOUNTER5H 0xc85U -#define CSR_HPMCOUNTER6H 0xc86U -#define CSR_HPMCOUNTER7H 0xc87U -#define CSR_HPMCOUNTER8H 0xc88U -#define CSR_HPMCOUNTER9H 0xc89U -#define CSR_HPMCOUNTER10H 0xc8aU -#define CSR_HPMCOUNTER11H 0xc8bU -#define CSR_HPMCOUNTER12H 0xc8cU -#define CSR_HPMCOUNTER13H 0xc8dU -#define CSR_HPMCOUNTER14H 0xc8eU -#define CSR_HPMCOUNTER15H 0xc8fU -#define CSR_HPMCOUNTER16H 0xc90U -#define CSR_HPMCOUNTER17H 0xc91U -#define CSR_HPMCOUNTER18H 0xc92U -#define CSR_HPMCOUNTER19H 0xc93U -#define CSR_HPMCOUNTER20H 0xc94U -#define CSR_HPMCOUNTER21H 0xc95U -#define CSR_HPMCOUNTER22H 0xc96U -#define CSR_HPMCOUNTER23H 0xc97U -#define CSR_HPMCOUNTER24H 0xc98U -#define CSR_HPMCOUNTER25H 0xc99U -#define CSR_HPMCOUNTER26H 0xc9aU -#define CSR_HPMCOUNTER27H 0xc9bU -#define CSR_HPMCOUNTER28H 0xc9cU -#define CSR_HPMCOUNTER29H 0xc9dU -#define CSR_HPMCOUNTER30H 0xc9eU -#define CSR_HPMCOUNTER31H 0xc9fU -#define CSR_MCYCLEH 0xb80U -#define CSR_MINSTRETH 0xb82U -#define CSR_MHPMCOUNTER3H 0xb83U -#define CSR_MHPMCOUNTER4H 0xb84U -#define CSR_MHPMCOUNTER5H 0xb85U -#define CSR_MHPMCOUNTER6H 0xb86U -#define CSR_MHPMCOUNTER7H 0xb87U -#define CSR_MHPMCOUNTER8H 0xb88U -#define CSR_MHPMCOUNTER9H 0xb89U -#define CSR_MHPMCOUNTER10H 0xb8aU -#define CSR_MHPMCOUNTER11H 0xb8bU -#define CSR_MHPMCOUNTER12H 0xb8cU -#define CSR_MHPMCOUNTER13H 0xb8dU -#define CSR_MHPMCOUNTER14H 0xb8eU -#define CSR_MHPMCOUNTER15H 0xb8fU -#define CSR_MHPMCOUNTER16H 0xb90U -#define CSR_MHPMCOUNTER17H 0xb91U -#define CSR_MHPMCOUNTER18H 0xb92U -#define CSR_MHPMCOUNTER19H 0xb93U -#define CSR_MHPMCOUNTER20H 0xb94U -#define CSR_MHPMCOUNTER21H 0xb95U -#define CSR_MHPMCOUNTER22H 0xb96U -#define CSR_MHPMCOUNTER23H 0xb97U -#define CSR_MHPMCOUNTER24H 0xb98U -#define CSR_MHPMCOUNTER25H 0xb99U -#define CSR_MHPMCOUNTER26H 0xb9aU -#define CSR_MHPMCOUNTER27H 0xb9bU -#define CSR_MHPMCOUNTER28H 0xb9cU -#define CSR_MHPMCOUNTER29H 0xb9dU -#define CSR_MHPMCOUNTER30H 0xb9eU -#define CSR_MHPMCOUNTER31H 0xb9fU -#define CAUSE_MISALIGNED_FETCH 0x0 -#define CAUSE_FAULT_FETCH 0x1 -#define CAUSE_ILLEGAL_INSTRUCTION 0x2 -#define CAUSE_BREAKPOINT 0x3 -#define CAUSE_MISALIGNED_LOAD 0x4 -#define CAUSE_FAULT_LOAD 0x5 -#define CAUSE_MISALIGNED_STORE 0x6 -#define CAUSE_FAULT_STORE 0x7 -#define CAUSE_USER_ECALL 0x8 -#define CAUSE_SUPERVISOR_ECALL 0x9 -#define CAUSE_HYPERVISOR_ECALL 0xa -#define CAUSE_MACHINE_ECALL 0xb -#endif -#if defined(DECLARE_INSN) -DECLARE_INSN(beq, MATCH_BEQ, MASK_BEQ) -DECLARE_INSN(bne, MATCH_BNE, MASK_BNE) -DECLARE_INSN(blt, MATCH_BLT, MASK_BLT) -DECLARE_INSN(bge, MATCH_BGE, MASK_BGE) -DECLARE_INSN(bltu, MATCH_BLTU, MASK_BLTU) -DECLARE_INSN(bgeu, MATCH_BGEU, MASK_BGEU) -DECLARE_INSN(jalr, MATCH_JALR, MASK_JALR) -DECLARE_INSN(jal, MATCH_JAL, MASK_JAL) -DECLARE_INSN(lui, MATCH_LUI, MASK_LUI) -DECLARE_INSN(auipc, MATCH_AUIPC, MASK_AUIPC) -DECLARE_INSN(addi, MATCH_ADDI, MASK_ADDI) -DECLARE_INSN(slli, MATCH_SLLI, MASK_SLLI) -DECLARE_INSN(slti, MATCH_SLTI, MASK_SLTI) -DECLARE_INSN(sltiu, MATCH_SLTIU, MASK_SLTIU) -DECLARE_INSN(xori, MATCH_XORI, MASK_XORI) -DECLARE_INSN(srli, MATCH_SRLI, MASK_SRLI) -DECLARE_INSN(srai, MATCH_SRAI, MASK_SRAI) -DECLARE_INSN(ori, MATCH_ORI, MASK_ORI) -DECLARE_INSN(andi, MATCH_ANDI, MASK_ANDI) -DECLARE_INSN(add, MATCH_ADD, MASK_ADD) -DECLARE_INSN(sub, MATCH_SUB, MASK_SUB) -DECLARE_INSN(sll, MATCH_SLL, MASK_SLL) -DECLARE_INSN(slt, MATCH_SLT, MASK_SLT) -DECLARE_INSN(sltu, MATCH_SLTU, MASK_SLTU) -DECLARE_INSN(xor, MATCH_XOR, MASK_XOR) -DECLARE_INSN(srl, MATCH_SRL, MASK_SRL) -DECLARE_INSN(sra, MATCH_SRA, MASK_SRA) -DECLARE_INSN(or, MATCH_OR, MASK_OR) -DECLARE_INSN(and, MATCH_AND, MASK_AND) -DECLARE_INSN(addiw, MATCH_ADDIW, MASK_ADDIW) -DECLARE_INSN(slliw, MATCH_SLLIW, MASK_SLLIW) -DECLARE_INSN(srliw, MATCH_SRLIW, MASK_SRLIW) -DECLARE_INSN(sraiw, MATCH_SRAIW, MASK_SRAIW) -DECLARE_INSN(addw, MATCH_ADDW, MASK_ADDW) -DECLARE_INSN(subw, MATCH_SUBW, MASK_SUBW) -DECLARE_INSN(sllw, MATCH_SLLW, MASK_SLLW) -DECLARE_INSN(srlw, MATCH_SRLW, MASK_SRLW) -DECLARE_INSN(sraw, MATCH_SRAW, MASK_SRAW) -DECLARE_INSN(lb, MATCH_LB, MASK_LB) -DECLARE_INSN(lh, MATCH_LH, MASK_LH) -DECLARE_INSN(lw, MATCH_LW, MASK_LW) -DECLARE_INSN(ld, MATCH_LD, MASK_LD) -DECLARE_INSN(lbu, MATCH_LBU, MASK_LBU) -DECLARE_INSN(lhu, MATCH_LHU, MASK_LHU) -DECLARE_INSN(lwu, MATCH_LWU, MASK_LWU) -DECLARE_INSN(sb, MATCH_SB, MASK_SB) -DECLARE_INSN(sh, MATCH_SH, MASK_SH) -DECLARE_INSN(sw, MATCH_SW, MASK_SW) -DECLARE_INSN(sd, MATCH_SD, MASK_SD) -DECLARE_INSN(fence, MATCH_FENCE, MASK_FENCE) -DECLARE_INSN(fence_i, MATCH_FENCE_I, MASK_FENCE_I) -DECLARE_INSN(mul, MATCH_MUL, MASK_MUL) -DECLARE_INSN(mulh, MATCH_MULH, MASK_MULH) -DECLARE_INSN(mulhsu, MATCH_MULHSU, MASK_MULHSU) -DECLARE_INSN(mulhu, MATCH_MULHU, MASK_MULHU) -DECLARE_INSN(div, MATCH_DIV, MASK_DIV) -DECLARE_INSN(divu, MATCH_DIVU, MASK_DIVU) -DECLARE_INSN(rem, MATCH_REM, MASK_REM) -DECLARE_INSN(remu, MATCH_REMU, MASK_REMU) -DECLARE_INSN(mulw, MATCH_MULW, MASK_MULW) -DECLARE_INSN(divw, MATCH_DIVW, MASK_DIVW) -DECLARE_INSN(divuw, MATCH_DIVUW, MASK_DIVUW) -DECLARE_INSN(remw, MATCH_REMW, MASK_REMW) -DECLARE_INSN(remuw, MATCH_REMUW, MASK_REMUW) -DECLARE_INSN(amoadd_w, MATCH_AMOADD_W, MASK_AMOADD_W) -DECLARE_INSN(amoxor_w, MATCH_AMOXOR_W, MASK_AMOXOR_W) -DECLARE_INSN(amoor_w, MATCH_AMOOR_W, MASK_AMOOR_W) -DECLARE_INSN(amoand_w, MATCH_AMOAND_W, MASK_AMOAND_W) -DECLARE_INSN(amomin_w, MATCH_AMOMIN_W, MASK_AMOMIN_W) -DECLARE_INSN(amomax_w, MATCH_AMOMAX_W, MASK_AMOMAX_W) -DECLARE_INSN(amominu_w, MATCH_AMOMINU_W, MASK_AMOMINU_W) -DECLARE_INSN(amomaxu_w, MATCH_AMOMAXU_W, MASK_AMOMAXU_W) -DECLARE_INSN(amoswap_w, MATCH_AMOSWAP_W, MASK_AMOSWAP_W) -DECLARE_INSN(lr_w, MATCH_LR_W, MASK_LR_W) -DECLARE_INSN(sc_w, MATCH_SC_W, MASK_SC_W) -DECLARE_INSN(amoadd_d, MATCH_AMOADD_D, MASK_AMOADD_D) -DECLARE_INSN(amoxor_d, MATCH_AMOXOR_D, MASK_AMOXOR_D) -DECLARE_INSN(amoor_d, MATCH_AMOOR_D, MASK_AMOOR_D) -DECLARE_INSN(amoand_d, MATCH_AMOAND_D, MASK_AMOAND_D) -DECLARE_INSN(amomin_d, MATCH_AMOMIN_D, MASK_AMOMIN_D) -DECLARE_INSN(amomax_d, MATCH_AMOMAX_D, MASK_AMOMAX_D) -DECLARE_INSN(amominu_d, MATCH_AMOMINU_D, MASK_AMOMINU_D) -DECLARE_INSN(amomaxu_d, MATCH_AMOMAXU_D, MASK_AMOMAXU_D) -DECLARE_INSN(amoswap_d, MATCH_AMOSWAP_D, MASK_AMOSWAP_D) -DECLARE_INSN(lr_d, MATCH_LR_D, MASK_LR_D) -DECLARE_INSN(sc_d, MATCH_SC_D, MASK_SC_D) -DECLARE_INSN(ecall, MATCH_ECALL, MASK_ECALL) -DECLARE_INSN(ebreak, MATCH_EBREAK, MASK_EBREAK) -DECLARE_INSN(uret, MATCH_URET, MASK_URET) -DECLARE_INSN(sret, MATCH_SRET, MASK_SRET) -DECLARE_INSN(hret, MATCH_HRET, MASK_HRET) -DECLARE_INSN(mret, MATCH_MRET, MASK_MRET) -DECLARE_INSN(dret, MATCH_DRET, MASK_DRET) -DECLARE_INSN(sfence_vm, MATCH_SFENCE_VM, MASK_SFENCE_VM) -DECLARE_INSN(wfi, MATCH_WFI, MASK_WFI) -DECLARE_INSN(csrrw, MATCH_CSRRW, MASK_CSRRW) -DECLARE_INSN(csrrs, MATCH_CSRRS, MASK_CSRRS) -DECLARE_INSN(csrrc, MATCH_CSRRC, MASK_CSRRC) -DECLARE_INSN(csrrwi, MATCH_CSRRWI, MASK_CSRRWI) -DECLARE_INSN(csrrsi, MATCH_CSRRSI, MASK_CSRRSI) -DECLARE_INSN(csrrci, MATCH_CSRRCI, MASK_CSRRCI) -DECLARE_INSN(fadd_s, MATCH_FADD_S, MASK_FADD_S) -DECLARE_INSN(fsub_s, MATCH_FSUB_S, MASK_FSUB_S) -DECLARE_INSN(fmul_s, MATCH_FMUL_S, MASK_FMUL_S) -DECLARE_INSN(fdiv_s, MATCH_FDIV_S, MASK_FDIV_S) -DECLARE_INSN(fsgnj_s, MATCH_FSGNJ_S, MASK_FSGNJ_S) -DECLARE_INSN(fsgnjn_s, MATCH_FSGNJN_S, MASK_FSGNJN_S) -DECLARE_INSN(fsgnjx_s, MATCH_FSGNJX_S, MASK_FSGNJX_S) -DECLARE_INSN(fmin_s, MATCH_FMIN_S, MASK_FMIN_S) -DECLARE_INSN(fmax_s, MATCH_FMAX_S, MASK_FMAX_S) -DECLARE_INSN(fsqrt_s, MATCH_FSQRT_S, MASK_FSQRT_S) -DECLARE_INSN(fadd_d, MATCH_FADD_D, MASK_FADD_D) -DECLARE_INSN(fsub_d, MATCH_FSUB_D, MASK_FSUB_D) -DECLARE_INSN(fmul_d, MATCH_FMUL_D, MASK_FMUL_D) -DECLARE_INSN(fdiv_d, MATCH_FDIV_D, MASK_FDIV_D) -DECLARE_INSN(fsgnj_d, MATCH_FSGNJ_D, MASK_FSGNJ_D) -DECLARE_INSN(fsgnjn_d, MATCH_FSGNJN_D, MASK_FSGNJN_D) -DECLARE_INSN(fsgnjx_d, MATCH_FSGNJX_D, MASK_FSGNJX_D) -DECLARE_INSN(fmin_d, MATCH_FMIN_D, MASK_FMIN_D) -DECLARE_INSN(fmax_d, MATCH_FMAX_D, MASK_FMAX_D) -DECLARE_INSN(fcvt_s_d, MATCH_FCVT_S_D, MASK_FCVT_S_D) -DECLARE_INSN(fcvt_d_s, MATCH_FCVT_D_S, MASK_FCVT_D_S) -DECLARE_INSN(fsqrt_d, MATCH_FSQRT_D, MASK_FSQRT_D) -DECLARE_INSN(fle_s, MATCH_FLE_S, MASK_FLE_S) -DECLARE_INSN(flt_s, MATCH_FLT_S, MASK_FLT_S) -DECLARE_INSN(feq_s, MATCH_FEQ_S, MASK_FEQ_S) -DECLARE_INSN(fle_d, MATCH_FLE_D, MASK_FLE_D) -DECLARE_INSN(flt_d, MATCH_FLT_D, MASK_FLT_D) -DECLARE_INSN(feq_d, MATCH_FEQ_D, MASK_FEQ_D) -DECLARE_INSN(fcvt_w_s, MATCH_FCVT_W_S, MASK_FCVT_W_S) -DECLARE_INSN(fcvt_wu_s, MATCH_FCVT_WU_S, MASK_FCVT_WU_S) -DECLARE_INSN(fcvt_l_s, MATCH_FCVT_L_S, MASK_FCVT_L_S) -DECLARE_INSN(fcvt_lu_s, MATCH_FCVT_LU_S, MASK_FCVT_LU_S) -DECLARE_INSN(fmv_x_s, MATCH_FMV_X_S, MASK_FMV_X_S) -DECLARE_INSN(fclass_s, MATCH_FCLASS_S, MASK_FCLASS_S) -DECLARE_INSN(fcvt_w_d, MATCH_FCVT_W_D, MASK_FCVT_W_D) -DECLARE_INSN(fcvt_wu_d, MATCH_FCVT_WU_D, MASK_FCVT_WU_D) -DECLARE_INSN(fcvt_l_d, MATCH_FCVT_L_D, MASK_FCVT_L_D) -DECLARE_INSN(fcvt_lu_d, MATCH_FCVT_LU_D, MASK_FCVT_LU_D) -DECLARE_INSN(fmv_x_d, MATCH_FMV_X_D, MASK_FMV_X_D) -DECLARE_INSN(fclass_d, MATCH_FCLASS_D, MASK_FCLASS_D) -DECLARE_INSN(fcvt_s_w, MATCH_FCVT_S_W, MASK_FCVT_S_W) -DECLARE_INSN(fcvt_s_wu, MATCH_FCVT_S_WU, MASK_FCVT_S_WU) -DECLARE_INSN(fcvt_s_l, MATCH_FCVT_S_L, MASK_FCVT_S_L) -DECLARE_INSN(fcvt_s_lu, MATCH_FCVT_S_LU, MASK_FCVT_S_LU) -DECLARE_INSN(fmv_s_x, MATCH_FMV_S_X, MASK_FMV_S_X) -DECLARE_INSN(fcvt_d_w, MATCH_FCVT_D_W, MASK_FCVT_D_W) -DECLARE_INSN(fcvt_d_wu, MATCH_FCVT_D_WU, MASK_FCVT_D_WU) -DECLARE_INSN(fcvt_d_l, MATCH_FCVT_D_L, MASK_FCVT_D_L) -DECLARE_INSN(fcvt_d_lu, MATCH_FCVT_D_LU, MASK_FCVT_D_LU) -DECLARE_INSN(fmv_d_x, MATCH_FMV_D_X, MASK_FMV_D_X) -DECLARE_INSN(flw, MATCH_FLW, MASK_FLW) -DECLARE_INSN(fld, MATCH_FLD, MASK_FLD) -DECLARE_INSN(fsw, MATCH_FSW, MASK_FSW) -DECLARE_INSN(fsd, MATCH_FSD, MASK_FSD) -DECLARE_INSN(fmadd_s, MATCH_FMADD_S, MASK_FMADD_S) -DECLARE_INSN(fmsub_s, MATCH_FMSUB_S, MASK_FMSUB_S) -DECLARE_INSN(fnmsub_s, MATCH_FNMSUB_S, MASK_FNMSUB_S) -DECLARE_INSN(fnmadd_s, MATCH_FNMADD_S, MASK_FNMADD_S) -DECLARE_INSN(fmadd_d, MATCH_FMADD_D, MASK_FMADD_D) -DECLARE_INSN(fmsub_d, MATCH_FMSUB_D, MASK_FMSUB_D) -DECLARE_INSN(fnmsub_d, MATCH_FNMSUB_D, MASK_FNMSUB_D) -DECLARE_INSN(fnmadd_d, MATCH_FNMADD_D, MASK_FNMADD_D) -DECLARE_INSN(c_nop, MATCH_C_NOP, MASK_C_NOP) -DECLARE_INSN(c_addi16sp, MATCH_C_ADDI16SP, MASK_C_ADDI16SP) -DECLARE_INSN(c_jr, MATCH_C_JR, MASK_C_JR) -DECLARE_INSN(c_jalr, MATCH_C_JALR, MASK_C_JALR) -DECLARE_INSN(c_ebreak, MATCH_C_EBREAK, MASK_C_EBREAK) -DECLARE_INSN(c_ld, MATCH_C_LD, MASK_C_LD) -DECLARE_INSN(c_sd, MATCH_C_SD, MASK_C_SD) -DECLARE_INSN(c_addiw, MATCH_C_ADDIW, MASK_C_ADDIW) -DECLARE_INSN(c_ldsp, MATCH_C_LDSP, MASK_C_LDSP) -DECLARE_INSN(c_sdsp, MATCH_C_SDSP, MASK_C_SDSP) -DECLARE_INSN(c_addi4spn, MATCH_C_ADDI4SPN, MASK_C_ADDI4SPN) -DECLARE_INSN(c_fld, MATCH_C_FLD, MASK_C_FLD) -DECLARE_INSN(c_lw, MATCH_C_LW, MASK_C_LW) -DECLARE_INSN(c_flw, MATCH_C_FLW, MASK_C_FLW) -DECLARE_INSN(c_fsd, MATCH_C_FSD, MASK_C_FSD) -DECLARE_INSN(c_sw, MATCH_C_SW, MASK_C_SW) -DECLARE_INSN(c_fsw, MATCH_C_FSW, MASK_C_FSW) -DECLARE_INSN(c_addi, MATCH_C_ADDI, MASK_C_ADDI) -DECLARE_INSN(c_jal, MATCH_C_JAL, MASK_C_JAL) -DECLARE_INSN(c_li, MATCH_C_LI, MASK_C_LI) -DECLARE_INSN(c_lui, MATCH_C_LUI, MASK_C_LUI) -DECLARE_INSN(c_srli, MATCH_C_SRLI, MASK_C_SRLI) -DECLARE_INSN(c_srai, MATCH_C_SRAI, MASK_C_SRAI) -DECLARE_INSN(c_andi, MATCH_C_ANDI, MASK_C_ANDI) -DECLARE_INSN(c_sub, MATCH_C_SUB, MASK_C_SUB) -DECLARE_INSN(c_xor, MATCH_C_XOR, MASK_C_XOR) -DECLARE_INSN(c_or, MATCH_C_OR, MASK_C_OR) -DECLARE_INSN(c_and, MATCH_C_AND, MASK_C_AND) -DECLARE_INSN(c_subw, MATCH_C_SUBW, MASK_C_SUBW) -DECLARE_INSN(c_addw, MATCH_C_ADDW, MASK_C_ADDW) -DECLARE_INSN(c_j, MATCH_C_J, MASK_C_J) -DECLARE_INSN(c_beqz, MATCH_C_BEQZ, MASK_C_BEQZ) -DECLARE_INSN(c_bnez, MATCH_C_BNEZ, MASK_C_BNEZ) -DECLARE_INSN(c_slli, MATCH_C_SLLI, MASK_C_SLLI) -DECLARE_INSN(c_fldsp, MATCH_C_FLDSP, MASK_C_FLDSP) -DECLARE_INSN(c_lwsp, MATCH_C_LWSP, MASK_C_LWSP) -DECLARE_INSN(c_flwsp, MATCH_C_FLWSP, MASK_C_FLWSP) -DECLARE_INSN(c_mv, MATCH_C_MV, MASK_C_MV) -DECLARE_INSN(c_add, MATCH_C_ADD, MASK_C_ADD) -DECLARE_INSN(c_fsdsp, MATCH_C_FSDSP, MASK_C_FSDSP) -DECLARE_INSN(c_swsp, MATCH_C_SWSP, MASK_C_SWSP) -DECLARE_INSN(c_fswsp, MATCH_C_FSWSP, MASK_C_FSWSP) -DECLARE_INSN(custom0, MATCH_CUSTOM0, MASK_CUSTOM0) -DECLARE_INSN(custom0_rs1, MATCH_CUSTOM0_RS1, MASK_CUSTOM0_RS1) -DECLARE_INSN(custom0_rs1_rs2, MATCH_CUSTOM0_RS1_RS2, MASK_CUSTOM0_RS1_RS2) -DECLARE_INSN(custom0_rd, MATCH_CUSTOM0_RD, MASK_CUSTOM0_RD) -DECLARE_INSN(custom0_rd_rs1, MATCH_CUSTOM0_RD_RS1, MASK_CUSTOM0_RD_RS1) -DECLARE_INSN(custom0_rd_rs1_rs2, MATCH_CUSTOM0_RD_RS1_RS2, MASK_CUSTOM0_RD_RS1_RS2) -DECLARE_INSN(custom1, MATCH_CUSTOM1, MASK_CUSTOM1) -DECLARE_INSN(custom1_rs1, MATCH_CUSTOM1_RS1, MASK_CUSTOM1_RS1) -DECLARE_INSN(custom1_rs1_rs2, MATCH_CUSTOM1_RS1_RS2, MASK_CUSTOM1_RS1_RS2) -DECLARE_INSN(custom1_rd, MATCH_CUSTOM1_RD, MASK_CUSTOM1_RD) -DECLARE_INSN(custom1_rd_rs1, MATCH_CUSTOM1_RD_RS1, MASK_CUSTOM1_RD_RS1) -DECLARE_INSN(custom1_rd_rs1_rs2, MATCH_CUSTOM1_RD_RS1_RS2, MASK_CUSTOM1_RD_RS1_RS2) -DECLARE_INSN(custom2, MATCH_CUSTOM2, MASK_CUSTOM2) -DECLARE_INSN(custom2_rs1, MATCH_CUSTOM2_RS1, MASK_CUSTOM2_RS1) -DECLARE_INSN(custom2_rs1_rs2, MATCH_CUSTOM2_RS1_RS2, MASK_CUSTOM2_RS1_RS2) -DECLARE_INSN(custom2_rd, MATCH_CUSTOM2_RD, MASK_CUSTOM2_RD) -DECLARE_INSN(custom2_rd_rs1, MATCH_CUSTOM2_RD_RS1, MASK_CUSTOM2_RD_RS1) -DECLARE_INSN(custom2_rd_rs1_rs2, MATCH_CUSTOM2_RD_RS1_RS2, MASK_CUSTOM2_RD_RS1_RS2) -DECLARE_INSN(custom3, MATCH_CUSTOM3, MASK_CUSTOM3) -DECLARE_INSN(custom3_rs1, MATCH_CUSTOM3_RS1, MASK_CUSTOM3_RS1) -DECLARE_INSN(custom3_rs1_rs2, MATCH_CUSTOM3_RS1_RS2, MASK_CUSTOM3_RS1_RS2) -DECLARE_INSN(custom3_rd, MATCH_CUSTOM3_RD, MASK_CUSTOM3_RD) -DECLARE_INSN(custom3_rd_rs1, MATCH_CUSTOM3_RD_RS1, MASK_CUSTOM3_RD_RS1) -DECLARE_INSN(custom3_rd_rs1_rs2, MATCH_CUSTOM3_RD_RS1_RS2, MASK_CUSTOM3_RD_RS1_RS2) -#endif -#if defined(DECLARE_CSR) -DECLARE_CSR(fflags, CSR_FFLAGS) -DECLARE_CSR(frm, CSR_FRM) -DECLARE_CSR(fcsr, CSR_FCSR) -DECLARE_CSR(cycle, CSR_CYCLE) -DECLARE_CSR(time, CSR_TIME) -DECLARE_CSR(instret, CSR_INSTRET) -DECLARE_CSR(hpmcounter3, CSR_HPMCOUNTER3) -DECLARE_CSR(hpmcounter4, CSR_HPMCOUNTER4) -DECLARE_CSR(hpmcounter5, CSR_HPMCOUNTER5) -DECLARE_CSR(hpmcounter6, CSR_HPMCOUNTER6) -DECLARE_CSR(hpmcounter7, CSR_HPMCOUNTER7) -DECLARE_CSR(hpmcounter8, CSR_HPMCOUNTER8) -DECLARE_CSR(hpmcounter9, CSR_HPMCOUNTER9) -DECLARE_CSR(hpmcounter10, CSR_HPMCOUNTER10) -DECLARE_CSR(hpmcounter11, CSR_HPMCOUNTER11) -DECLARE_CSR(hpmcounter12, CSR_HPMCOUNTER12) -DECLARE_CSR(hpmcounter13, CSR_HPMCOUNTER13) -DECLARE_CSR(hpmcounter14, CSR_HPMCOUNTER14) -DECLARE_CSR(hpmcounter15, CSR_HPMCOUNTER15) -DECLARE_CSR(hpmcounter16, CSR_HPMCOUNTER16) -DECLARE_CSR(hpmcounter17, CSR_HPMCOUNTER17) -DECLARE_CSR(hpmcounter18, CSR_HPMCOUNTER18) -DECLARE_CSR(hpmcounter19, CSR_HPMCOUNTER19) -DECLARE_CSR(hpmcounter20, CSR_HPMCOUNTER20) -DECLARE_CSR(hpmcounter21, CSR_HPMCOUNTER21) -DECLARE_CSR(hpmcounter22, CSR_HPMCOUNTER22) -DECLARE_CSR(hpmcounter23, CSR_HPMCOUNTER23) -DECLARE_CSR(hpmcounter24, CSR_HPMCOUNTER24) -DECLARE_CSR(hpmcounter25, CSR_HPMCOUNTER25) -DECLARE_CSR(hpmcounter26, CSR_HPMCOUNTER26) -DECLARE_CSR(hpmcounter27, CSR_HPMCOUNTER27) -DECLARE_CSR(hpmcounter28, CSR_HPMCOUNTER28) -DECLARE_CSR(hpmcounter29, CSR_HPMCOUNTER29) -DECLARE_CSR(hpmcounter30, CSR_HPMCOUNTER30) -DECLARE_CSR(hpmcounter31, CSR_HPMCOUNTER31) -DECLARE_CSR(sstatus, CSR_SSTATUS) -DECLARE_CSR(sie, CSR_SIE) -DECLARE_CSR(stvec, CSR_STVEC) -DECLARE_CSR(sscratch, CSR_SSCRATCH) -DECLARE_CSR(sepc, CSR_SEPC) -DECLARE_CSR(scause, CSR_SCAUSE) -DECLARE_CSR(sbadaddr, CSR_SBADADDR) -DECLARE_CSR(sip, CSR_SIP) -DECLARE_CSR(sptbr, CSR_SPTBR) -DECLARE_CSR(mstatus, CSR_MSTATUS) -DECLARE_CSR(misa, CSR_MISA) -DECLARE_CSR(medeleg, CSR_MEDELEG) -DECLARE_CSR(mideleg, CSR_MIDELEG) -DECLARE_CSR(mie, CSR_MIE) -DECLARE_CSR(mtvec, CSR_MTVEC) -DECLARE_CSR(mscratch, CSR_MSCRATCH) -DECLARE_CSR(mepc, CSR_MEPC) -DECLARE_CSR(mcause, CSR_MCAUSE) -DECLARE_CSR(mbadaddr, CSR_MBADADDR) -DECLARE_CSR(mip, CSR_MIP) -DECLARE_CSR(tselect, CSR_TSELECT) -DECLARE_CSR(tdata1, CSR_TDATA1) -DECLARE_CSR(tdata2, CSR_TDATA2) -DECLARE_CSR(tdata3, CSR_TDATA3) -DECLARE_CSR(dcsr, CSR_DCSR) -DECLARE_CSR(dpc, CSR_DPC) -DECLARE_CSR(dscratch, CSR_DSCRATCH) -DECLARE_CSR(mcycle, CSR_MCYCLE) -DECLARE_CSR(minstret, CSR_MINSTRET) -DECLARE_CSR(mhpmcounter3, CSR_MHPMCOUNTER3) -DECLARE_CSR(mhpmcounter4, CSR_MHPMCOUNTER4) -DECLARE_CSR(mhpmcounter5, CSR_MHPMCOUNTER5) -DECLARE_CSR(mhpmcounter6, CSR_MHPMCOUNTER6) -DECLARE_CSR(mhpmcounter7, CSR_MHPMCOUNTER7) -DECLARE_CSR(mhpmcounter8, CSR_MHPMCOUNTER8) -DECLARE_CSR(mhpmcounter9, CSR_MHPMCOUNTER9) -DECLARE_CSR(mhpmcounter10, CSR_MHPMCOUNTER10) -DECLARE_CSR(mhpmcounter11, CSR_MHPMCOUNTER11) -DECLARE_CSR(mhpmcounter12, CSR_MHPMCOUNTER12) -DECLARE_CSR(mhpmcounter13, CSR_MHPMCOUNTER13) -DECLARE_CSR(mhpmcounter14, CSR_MHPMCOUNTER14) -DECLARE_CSR(mhpmcounter15, CSR_MHPMCOUNTER15) -DECLARE_CSR(mhpmcounter16, CSR_MHPMCOUNTER16) -DECLARE_CSR(mhpmcounter17, CSR_MHPMCOUNTER17) -DECLARE_CSR(mhpmcounter18, CSR_MHPMCOUNTER18) -DECLARE_CSR(mhpmcounter19, CSR_MHPMCOUNTER19) -DECLARE_CSR(mhpmcounter20, CSR_MHPMCOUNTER20) -DECLARE_CSR(mhpmcounter21, CSR_MHPMCOUNTER21) -DECLARE_CSR(mhpmcounter22, CSR_MHPMCOUNTER22) -DECLARE_CSR(mhpmcounter23, CSR_MHPMCOUNTER23) -DECLARE_CSR(mhpmcounter24, CSR_MHPMCOUNTER24) -DECLARE_CSR(mhpmcounter25, CSR_MHPMCOUNTER25) -DECLARE_CSR(mhpmcounter26, CSR_MHPMCOUNTER26) -DECLARE_CSR(mhpmcounter27, CSR_MHPMCOUNTER27) -DECLARE_CSR(mhpmcounter28, CSR_MHPMCOUNTER28) -DECLARE_CSR(mhpmcounter29, CSR_MHPMCOUNTER29) -DECLARE_CSR(mhpmcounter30, CSR_MHPMCOUNTER30) -DECLARE_CSR(mhpmcounter31, CSR_MHPMCOUNTER31) -DECLARE_CSR(mucounteren, CSR_MUCOUNTEREN) -DECLARE_CSR(mscounteren, CSR_MSCOUNTEREN) -DECLARE_CSR(mhpmevent3, CSR_MHPMEVENT3) -DECLARE_CSR(mhpmevent4, CSR_MHPMEVENT4) -DECLARE_CSR(mhpmevent5, CSR_MHPMEVENT5) -DECLARE_CSR(mhpmevent6, CSR_MHPMEVENT6) -DECLARE_CSR(mhpmevent7, CSR_MHPMEVENT7) -DECLARE_CSR(mhpmevent8, CSR_MHPMEVENT8) -DECLARE_CSR(mhpmevent9, CSR_MHPMEVENT9) -DECLARE_CSR(mhpmevent10, CSR_MHPMEVENT10) -DECLARE_CSR(mhpmevent11, CSR_MHPMEVENT11) -DECLARE_CSR(mhpmevent12, CSR_MHPMEVENT12) -DECLARE_CSR(mhpmevent13, CSR_MHPMEVENT13) -DECLARE_CSR(mhpmevent14, CSR_MHPMEVENT14) -DECLARE_CSR(mhpmevent15, CSR_MHPMEVENT15) -DECLARE_CSR(mhpmevent16, CSR_MHPMEVENT16) -DECLARE_CSR(mhpmevent17, CSR_MHPMEVENT17) -DECLARE_CSR(mhpmevent18, CSR_MHPMEVENT18) -DECLARE_CSR(mhpmevent19, CSR_MHPMEVENT19) -DECLARE_CSR(mhpmevent20, CSR_MHPMEVENT20) -DECLARE_CSR(mhpmevent21, CSR_MHPMEVENT21) -DECLARE_CSR(mhpmevent22, CSR_MHPMEVENT22) -DECLARE_CSR(mhpmevent23, CSR_MHPMEVENT23) -DECLARE_CSR(mhpmevent24, CSR_MHPMEVENT24) -DECLARE_CSR(mhpmevent25, CSR_MHPMEVENT25) -DECLARE_CSR(mhpmevent26, CSR_MHPMEVENT26) -DECLARE_CSR(mhpmevent27, CSR_MHPMEVENT27) -DECLARE_CSR(mhpmevent28, CSR_MHPMEVENT28) -DECLARE_CSR(mhpmevent29, CSR_MHPMEVENT29) -DECLARE_CSR(mhpmevent30, CSR_MHPMEVENT30) -DECLARE_CSR(mhpmevent31, CSR_MHPMEVENT31) -DECLARE_CSR(mvendorid, CSR_MVENDORID) -DECLARE_CSR(marchid, CSR_MARCHID) -DECLARE_CSR(mimpid, CSR_MIMPID) -DECLARE_CSR(mhartid, CSR_MHARTID) -DECLARE_CSR(cycleh, CSR_CYCLEH) -DECLARE_CSR(timeh, CSR_TIMEH) -DECLARE_CSR(instreth, CSR_INSTRETH) -DECLARE_CSR(hpmcounter3h, CSR_HPMCOUNTER3H) -DECLARE_CSR(hpmcounter4h, CSR_HPMCOUNTER4H) -DECLARE_CSR(hpmcounter5h, CSR_HPMCOUNTER5H) -DECLARE_CSR(hpmcounter6h, CSR_HPMCOUNTER6H) -DECLARE_CSR(hpmcounter7h, CSR_HPMCOUNTER7H) -DECLARE_CSR(hpmcounter8h, CSR_HPMCOUNTER8H) -DECLARE_CSR(hpmcounter9h, CSR_HPMCOUNTER9H) -DECLARE_CSR(hpmcounter10h, CSR_HPMCOUNTER10H) -DECLARE_CSR(hpmcounter11h, CSR_HPMCOUNTER11H) -DECLARE_CSR(hpmcounter12h, CSR_HPMCOUNTER12H) -DECLARE_CSR(hpmcounter13h, CSR_HPMCOUNTER13H) -DECLARE_CSR(hpmcounter14h, CSR_HPMCOUNTER14H) -DECLARE_CSR(hpmcounter15h, CSR_HPMCOUNTER15H) -DECLARE_CSR(hpmcounter16h, CSR_HPMCOUNTER16H) -DECLARE_CSR(hpmcounter17h, CSR_HPMCOUNTER17H) -DECLARE_CSR(hpmcounter18h, CSR_HPMCOUNTER18H) -DECLARE_CSR(hpmcounter19h, CSR_HPMCOUNTER19H) -DECLARE_CSR(hpmcounter20h, CSR_HPMCOUNTER20H) -DECLARE_CSR(hpmcounter21h, CSR_HPMCOUNTER21H) -DECLARE_CSR(hpmcounter22h, CSR_HPMCOUNTER22H) -DECLARE_CSR(hpmcounter23h, CSR_HPMCOUNTER23H) -DECLARE_CSR(hpmcounter24h, CSR_HPMCOUNTER24H) -DECLARE_CSR(hpmcounter25h, CSR_HPMCOUNTER25H) -DECLARE_CSR(hpmcounter26h, CSR_HPMCOUNTER26H) -DECLARE_CSR(hpmcounter27h, CSR_HPMCOUNTER27H) -DECLARE_CSR(hpmcounter28h, CSR_HPMCOUNTER28H) -DECLARE_CSR(hpmcounter29h, CSR_HPMCOUNTER29H) -DECLARE_CSR(hpmcounter30h, CSR_HPMCOUNTER30H) -DECLARE_CSR(hpmcounter31h, CSR_HPMCOUNTER31H) -DECLARE_CSR(mcycleh, CSR_MCYCLEH) -DECLARE_CSR(minstreth, CSR_MINSTRETH) -DECLARE_CSR(mhpmcounter3h, CSR_MHPMCOUNTER3H) -DECLARE_CSR(mhpmcounter4h, CSR_MHPMCOUNTER4H) -DECLARE_CSR(mhpmcounter5h, CSR_MHPMCOUNTER5H) -DECLARE_CSR(mhpmcounter6h, CSR_MHPMCOUNTER6H) -DECLARE_CSR(mhpmcounter7h, CSR_MHPMCOUNTER7H) -DECLARE_CSR(mhpmcounter8h, CSR_MHPMCOUNTER8H) -DECLARE_CSR(mhpmcounter9h, CSR_MHPMCOUNTER9H) -DECLARE_CSR(mhpmcounter10h, CSR_MHPMCOUNTER10H) -DECLARE_CSR(mhpmcounter11h, CSR_MHPMCOUNTER11H) -DECLARE_CSR(mhpmcounter12h, CSR_MHPMCOUNTER12H) -DECLARE_CSR(mhpmcounter13h, CSR_MHPMCOUNTER13H) -DECLARE_CSR(mhpmcounter14h, CSR_MHPMCOUNTER14H) -DECLARE_CSR(mhpmcounter15h, CSR_MHPMCOUNTER15H) -DECLARE_CSR(mhpmcounter16h, CSR_MHPMCOUNTER16H) -DECLARE_CSR(mhpmcounter17h, CSR_MHPMCOUNTER17H) -DECLARE_CSR(mhpmcounter18h, CSR_MHPMCOUNTER18H) -DECLARE_CSR(mhpmcounter19h, CSR_MHPMCOUNTER19H) -DECLARE_CSR(mhpmcounter20h, CSR_MHPMCOUNTER20H) -DECLARE_CSR(mhpmcounter21h, CSR_MHPMCOUNTER21H) -DECLARE_CSR(mhpmcounter22h, CSR_MHPMCOUNTER22H) -DECLARE_CSR(mhpmcounter23h, CSR_MHPMCOUNTER23H) -DECLARE_CSR(mhpmcounter24h, CSR_MHPMCOUNTER24H) -DECLARE_CSR(mhpmcounter25h, CSR_MHPMCOUNTER25H) -DECLARE_CSR(mhpmcounter26h, CSR_MHPMCOUNTER26H) -DECLARE_CSR(mhpmcounter27h, CSR_MHPMCOUNTER27H) -DECLARE_CSR(mhpmcounter28h, CSR_MHPMCOUNTER28H) -DECLARE_CSR(mhpmcounter29h, CSR_MHPMCOUNTER29H) -DECLARE_CSR(mhpmcounter30h, CSR_MHPMCOUNTER30H) -DECLARE_CSR(mhpmcounter31h, CSR_MHPMCOUNTER31H) -#endif -#if defined(DECLARE_CAUSE) -DECLARE_CAUSE("misaligned fetch", CAUSE_MISALIGNED_FETCH) -DECLARE_CAUSE("fault fetch", CAUSE_FAULT_FETCH) -DECLARE_CAUSE("illegal instruction", CAUSE_ILLEGAL_INSTRUCTION) -DECLARE_CAUSE("breakpoint", CAUSE_BREAKPOINT) -DECLARE_CAUSE("misaligned load", CAUSE_MISALIGNED_LOAD) -DECLARE_CAUSE("fault load", CAUSE_FAULT_LOAD) -DECLARE_CAUSE("misaligned store", CAUSE_MISALIGNED_STORE) -DECLARE_CAUSE("fault store", CAUSE_FAULT_STORE) -DECLARE_CAUSE("user_ecall", CAUSE_USER_ECALL) -DECLARE_CAUSE("supervisor_ecall", CAUSE_SUPERVISOR_ECALL) -DECLARE_CAUSE("hypervisor_ecall", CAUSE_HYPERVISOR_ECALL) -DECLARE_CAUSE("machine_ecall", CAUSE_MACHINE_ECALL) -#endif - diff --git a/cores/arduino/kendryte-standalone-sdk/lib/bsp/include/entry.h b/cores/arduino/kendryte-standalone-sdk/lib/bsp/include/entry.h deleted file mode 100644 index e9ab5b9..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/bsp/include/entry.h +++ /dev/null @@ -1,81 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef _BSP_ENTRY_H -#define _BSP_ENTRY_H - -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -typedef int (*core_function)(void *ctx); - -typedef struct _core_instance_t -{ - core_function callback; - void *ctx; -} core_instance_t; - -int register_core1(core_function func, void *ctx); - -static inline void init_lma(void) -{ - extern unsigned int _data_lma; - extern unsigned int _data; - extern unsigned int _edata; - unsigned int *src, *dst; - - src = &_data_lma; - dst = &_data; - while (dst < &_edata) - *dst++ = *src++; -} - -static inline void init_bss(void) -{ - extern unsigned int _bss; - extern unsigned int _ebss; - unsigned int *dst; - - dst = &_bss; - while (dst < &_ebss) - *dst++ = 0; -} - -static inline void init_tls(void) -{ - register void *thread_pointer asm("tp"); - extern char _tls_data; - - extern __thread char _tdata_begin, _tdata_end, _tbss_end; - - size_t tdata_size = &_tdata_end - &_tdata_begin; - - memcpy(thread_pointer, &_tls_data, tdata_size); - - size_t tbss_size = &_tbss_end - &_tdata_end; - - memset(thread_pointer + tdata_size, 0, tbss_size); -} - -#ifdef __cplusplus -} -#endif - -#endif /* _BSP_ENTRY_H */ - diff --git a/cores/arduino/kendryte-standalone-sdk/lib/bsp/include/interrupt.h b/cores/arduino/kendryte-standalone-sdk/lib/bsp/include/interrupt.h deleted file mode 100644 index 160690e..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/bsp/include/interrupt.h +++ /dev/null @@ -1,47 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef _BSP_INTERRUPT_H -#define _BSP_INTERRUPT_H - -#ifdef __cplusplus -extern "C" { -#endif -/* clang-format off */ -/* Machine interrupt mask for 64 bit system, 0x8000 0000 0000 0000 */ -#define CAUSE_MACHINE_IRQ_MASK (0x1ULL << 63) - -/* Machine interrupt reason mask for 64 bit system, 0x7FFF FFFF FFFF FFFF */ -#define CAUSE_MACHINE_IRQ_REASON_MASK (CAUSE_MACHINE_IRQ_MASK - 1) - -/* Hypervisor interrupt mask for 64 bit system, 0x8000 0000 0000 0000 */ -#define CAUSE_HYPERVISOR_IRQ_MASK (0x1ULL << 63) - -/* Hypervisor interrupt reason mask for 64 bit system, 0x7FFF FFFF FFFF FFFF */ -#define CAUSE_HYPERVISOR_IRQ_REASON_MASK (CAUSE_HYPERVISOR_IRQ_MASK - 1) - -/* Supervisor interrupt mask for 64 bit system, 0x8000 0000 0000 0000 */ -#define CAUSE_SUPERVISOR_IRQ_MASK (0x1ULL << 63) - -/* Supervisor interrupt reason mask for 64 bit system, 0x7FFF FFFF FFFF FFFF */ -#define CAUSE_SUPERVISOR_IRQ_REASON_MASK (CAUSE_SUPERVISOR_IRQ_MASK - 1) -/* clang-format on */ - -#ifdef __cplusplus -} -#endif - -#endif /* _BSP_INTERRUPT_H */ - diff --git a/cores/arduino/kendryte-standalone-sdk/lib/bsp/include/platform.h b/cores/arduino/kendryte-standalone-sdk/lib/bsp/include/platform.h deleted file mode 100644 index 6ce0355..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/bsp/include/platform.h +++ /dev/null @@ -1,99 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef _BSP_PLATFORM_H -#define _BSP_PLATFORM_H - -#ifdef __cplusplus -extern "C" { -#endif - -/* clang-format off */ -/* Register base address */ - -/* Under Coreplex */ -#define CLINT_BASE_ADDR (0x02000000U) -#define PLIC_BASE_ADDR (0x0C000000U) - -/* Under TileLink */ -#define UARTHS_BASE_ADDR (0x38000000U) -#define GPIOHS_BASE_ADDR (0x38001000U) - -/* Under AXI 64 bit */ -#define RAM_BASE_ADDR (0x80000000U) -#define RAM_SIZE (6 * 1024 * 1024U) - -#define IO_BASE_ADDR (0x40000000U) -#define IO_SIZE (6 * 1024 * 1024U) - -#define AI_RAM_BASE_ADDR (0x80600000U) -#define AI_RAM_SIZE (2 * 1024 * 1024U) - -#define AI_IO_BASE_ADDR (0x40600000U) -#define AI_IO_SIZE (2 * 1024 * 1024U) - -#define AI_BASE_ADDR (0x40800000U) -#define AI_SIZE (12 * 1024 * 1024U) - -#define FFT_BASE_ADDR (0x42000000U) -#define FFT_SIZE (4 * 1024 * 1024U) - -#define ROM_BASE_ADDR (0x88000000U) -#define ROM_SIZE (128 * 1024U) - -/* Under AHB 32 bit */ -#define DMAC_BASE_ADDR (0x50000000U) - -/* Under APB1 32 bit */ -#define GPIO_BASE_ADDR (0x50200000U) -#define UART1_BASE_ADDR (0x50210000U) -#define UART2_BASE_ADDR (0x50220000U) -#define UART3_BASE_ADDR (0x50230000U) -#define SPI_SLAVE_BASE_ADDR (0x50240000U) -#define I2S0_BASE_ADDR (0x50250000U) -#define I2S1_BASE_ADDR (0x50260000U) -#define I2S2_BASE_ADDR (0x50270000U) -#define I2C0_BASE_ADDR (0x50280000U) -#define I2C1_BASE_ADDR (0x50290000U) -#define I2C2_BASE_ADDR (0x502A0000U) -#define FPIOA_BASE_ADDR (0x502B0000U) -#define SHA256_BASE_ADDR (0x502C0000U) -#define TIMER0_BASE_ADDR (0x502D0000U) -#define TIMER1_BASE_ADDR (0x502E0000U) -#define TIMER2_BASE_ADDR (0x502F0000U) - -/* Under APB2 32 bit */ -#define WDT0_BASE_ADDR (0x50400000U) -#define WDT1_BASE_ADDR (0x50410000U) -#define OTP_BASE_ADDR (0x50420000U) -#define DVP_BASE_ADDR (0x50430000U) -#define SYSCTL_BASE_ADDR (0x50440000U) -#define AES_BASE_ADDR (0x50450000U) -#define RTC_BASE_ADDR (0x50460000U) - - -/* Under APB3 32 bit */ -#define SPI0_BASE_ADDR (0x52000000U) -#define SPI1_BASE_ADDR (0x53000000U) -#define SPI3_BASE_ADDR (0x54000000U) - -/* clang-format on */ - -#ifdef __cplusplus -} -#endif - -#endif /* _BSP_PLATFORM_H */ - diff --git a/cores/arduino/kendryte-standalone-sdk/lib/bsp/include/printf.h b/cores/arduino/kendryte-standalone-sdk/lib/bsp/include/printf.h deleted file mode 100644 index fa19cd4..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/bsp/include/printf.h +++ /dev/null @@ -1,209 +0,0 @@ -/** - * File: printf.h - * - * Copyright (c) 2004,2012 Kustaa Nyholm / SpareTimeLabs - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of Kustaa Nyholm or SpareTimeLabs nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this library; if not, write to the Free Software Foundation, - * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * This library is really just two files: 'tinyprintf.h' and 'tinyprintf.c'. - * - * They provide a simple and small (+400 loc) printf functionality to be used - * in embedded systems. - * - * I've found them so useful in debugging that I do not bother with a debugger - * at all. - * - * They are distributed in source form, so to use them, just compile them into - * your project. - * - * Two printf variants are provided: printf and the 'sprintf' family of - * functions ('snprintf', 'sprintf', 'vsnprintf', 'vsprintf'). - * - * The formats supported by this implementation are: 'c' 'd' 'i' 'o' 'p' 'u' - * 's' 'x' 'X'. - * - * Zero padding, field width, and precision are also supported. - * - * If the library is compiled with 'PRINTF_SUPPORT_LONG' defined, then the - * long specifier is also supported. Note that this will pull in some long - * math routines (pun intended!) and thus make your executable noticeably - * longer. Likewise with 'PRINTF_LONG_LONG_SUPPORT' for the long long - * specifier, and with 'PRINTF_SIZE_T_SUPPORT' for the size_t specifier. - * - * The memory footprint of course depends on the target CPU, compiler and - * compiler options, but a rough guesstimate (based on a H8S target) is about - * 1.4 kB for code and some twenty 'int's and 'char's, say 60 bytes of stack - * space. Not too bad. Your mileage may vary. By hacking the source code you - * can get rid of some hundred bytes, I'm sure, but personally I feel the - * balance of functionality and flexibility versus code size is close to - * optimal for many embedded systems. - * - * To use the printf, you need to supply your own character output function, - * something like : - * - * void putc ( void* p, char c) { while (!SERIAL_PORT_EMPTY) ; - * SERIAL_PORT_TX_REGISTER = c; } - * - * Before you can call printf, you need to initialize it to use your character - * output function with something like: - * - * init_printf(NULL,putc); - * - * Notice the 'NULL' in 'init_printf' and the parameter 'void* p' in 'putc', - * the NULL (or any pointer) you pass into the 'init_printf' will eventually - * be passed to your 'putc' routine. This allows you to pass some storage - * space (or anything really) to the character output function, if necessary. - * This is not often needed but it was implemented like that because it made - * implementing the sprintf function so neat (look at the source code). - * - * The code is re-entrant, except for the 'init_printf' function, so it is - * safe to call it from interrupts too, although this may result in mixed - * output. If you rely on re-entrancy, take care that your 'putc' function is - * re-entrant! - * - * The printf and sprintf functions are actually macros that translate to - * 'tfp_printf' and 'tfp_sprintf' when 'TINYPRINTF_OVERRIDE_LIBC' is set - * (default). Setting it to 0 makes it possible to use them along with - * 'stdio.h' printf's in a single source file. When 'TINYPRINTF_OVERRIDE_LIBC' - * is set, please note that printf/sprintf are not function-like macros, so if - * you have variables or struct members with these names, things will explode - * in your face. Without variadic macros this is the best we can do to wrap - * these function. If it is a problem, just give up the macros and use the - * functions directly, or rename them. - * - * It is also possible to avoid defining tfp_printf and/or tfp_sprintf by - * clearing 'TINYPRINTF_DEFINE_TFP_PRINTF' and/or - * 'TINYPRINTF_DEFINE_TFP_SPRINTF' to 0. This allows for example to export - * only tfp_format, which is at the core of all the other functions. - * - * For further details see source code. - * - * regs Kusti, 23.10.2004 - */ - -#ifndef _BSP_PRINTF_H -#define _BSP_PRINTF_H - -#include -#include - -/* Global configuration */ - -/* Set this to 0 if you do not want to provide tfp_printf */ -#ifndef TINYPRINTF_DEFINE_TFP_PRINTF -#define TINYPRINTF_DEFINE_TFP_PRINTF 1 -#endif - -/** - * Set this to 0 if you do not want to provide - * tfp_sprintf/snprintf/vsprintf/vsnprintf - */ -#ifndef TINYPRINTF_DEFINE_TFP_SPRINTF -#define TINYPRINTF_DEFINE_TFP_SPRINTF 1 -#endif - -/** - * Set this to 0 if you do not want tfp_printf and - * tfp_{vsn,sn,vs,s}printf to be also available as - * printf/{vsn,sn,vs,s}printf - */ -#ifndef TINYPRINTF_OVERRIDE_LIBC -#define TINYPRINTF_OVERRIDE_LIBC 0 -#endif - -/* Optional external types dependencies */ - -/* Declarations */ - -#if defined(__GNUC__) -#define _TFP_SPECIFY_PRINTF_FMT(fmt_idx, arg1_idx) \ - __attribute__((format(printf, fmt_idx, arg1_idx))) -#else -#define _TFP_SPECIFY_PRINTF_FMT(fmt_idx, arg1_idx) -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -typedef void (*putcf)(void*, char); - -/** - * 'tfp_format' really is the central function for all tinyprintf. For - * each output character after formatting, the 'putf' callback is - * called with 2 args: - * - an arbitrary void* 'putp' param defined by the user and - * passed unmodified from 'tfp_format', - * - the character. - * The 'tfp_printf' and 'tfp_sprintf' functions simply define their own - * callback and pass to it the right 'putp' it is expecting. - */ -void tfp_format(void *putp, putcf putf, const char *fmt, va_list va); - -#if TINYPRINTF_DEFINE_TFP_SPRINTF -int tfp_vsnprintf(char *str, size_t size, const char *fmt, va_list ap); -int tfp_snprintf(char *str, size_t size, const char *fmt, ...) - _TFP_SPECIFY_PRINTF_FMT(3, 4); -int tfp_vsprintf(char *str, const char *fmt, va_list ap); -int tfp_sprintf(char *str, const char *fmt, ...) _TFP_SPECIFY_PRINTF_FMT(2, 3); -#if TINYPRINTF_OVERRIDE_LIBC -#define vsnprintf tfp_vsnprintf -#define snprintf tfp_snprintf -#define vsprintf tfp_vsprintf -#define sprintf tfp_sprintf -#endif -#endif - -#if TINYPRINTF_DEFINE_TFP_PRINTF -void init_printf(void *putp, putcf putf); -void tfp_printf(char *fmt, ...) _TFP_SPECIFY_PRINTF_FMT(1, 2); -#if TINYPRINTF_OVERRIDE_LIBC -#define printf tfp_printf - -#ifdef __cplusplus -#include -namespace std -{ - template - auto tfp_printf(Args&&... args) -> decltype(::tfp_printf(std::forward(args)...)) - { - return ::tfp_printf(std::forward(args)...); - } -} -#endif -#endif -#endif - -int printk(const char *format, ...) _TFP_SPECIFY_PRINTF_FMT(1, 2); - -#ifdef __cplusplus -} -#endif - -#endif /* _BSP_PRINTF_H */ - diff --git a/cores/arduino/kendryte-standalone-sdk/lib/bsp/include/sleep.h b/cores/arduino/kendryte-standalone-sdk/lib/bsp/include/sleep.h deleted file mode 100644 index 6eb1d24..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/bsp/include/sleep.h +++ /dev/null @@ -1,36 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef _BSP_SLEEP_H -#define _BSP_SLEEP_H - -#include "encoding.h" -#include "clint.h" -#include "syscalls.h" - -#ifdef __cplusplus -extern "C" { -#endif - -int usleep(uint64_t usec); -int msleep(uint64_t msec); -unsigned int sleep(unsigned int seconds); - -#ifdef __cplusplus -} -#endif - -#endif /* _BSP_SLEEP_H */ - diff --git a/cores/arduino/kendryte-standalone-sdk/lib/bsp/include/syscalls.h b/cores/arduino/kendryte-standalone-sdk/lib/bsp/include/syscalls.h deleted file mode 100644 index 12713c3..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/bsp/include/syscalls.h +++ /dev/null @@ -1,46 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef _BSP_SYSCALLS_H -#define _BSP_SYSCALLS_H - -#include -#include -#include -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -void __attribute__((noreturn)) sys_exit(int code); - -void setStats(int enable); - -#undef putchar -int putchar(int ch); -void printstr(const char *s); - -void printhex(uint64_t x); - -size_t get_free_heap_size(void); - -#ifdef __cplusplus -} -#endif - -#endif /* _BSP_SYSCALLS_H */ - diff --git a/cores/arduino/kendryte-standalone-sdk/lib/bsp/include/util.h b/cores/arduino/kendryte-standalone-sdk/lib/bsp/include/util.h deleted file mode 100644 index c62e748..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/bsp/include/util.h +++ /dev/null @@ -1,198 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef _BSP_UTIL_H -#define _BSP_UTIL_H - - -#include -#if defined(__riscv) -#include "encoding.h" -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -#if defined(__GNUC__) -#pragma GCC diagnostic ignored "-Wunused-parameter" -#pragma GCC diagnostic ignored "-Wunused-function" -#endif - -/** - * -------------------------------------------------------------------------- - * Macros - - * Set HOST_DEBUG to 1 if you are going to compile this for a host - * machine (ie Athena/Linux) for debug purposes and set HOST_DEBUG - * to 0 if you are compiling with the smips-gcc toolchain. - */ - -#ifndef HOST_DEBUG -#define HOST_DEBUG 0 -#endif - -/** - * Set PREALLOCATE to 1 if you want to preallocate the benchmark - * function before starting stats. If you have instruction/data - * caches and you don't want to count the overhead of misses, then - * you will need to use preallocation. -*/ - -#ifndef PREALLOCATE -#define PREALLOCATE 0 -#endif - - -#define static_assert(cond) \ - { \ - switch (0) \ - { \ - case 0: \ - case !!(long)(cond):; \ - } \ - } - -#define stringify_1(s) #s -#define stringify(s) stringify_1(s) -#define stats(code, iter) \ - do \ - { \ - unsigned long _c = -read_cycle(), _i = -read_csr(minstret); \ - code; \ - _c += read_cycle(), _i += read_csr(minstret); \ - if (cid == 0) \ - printf("\r\n%s: %ld cycles, %ld.%ld cycles/iter, %ld.%ld CPI\r\n", \ - stringify(code), _c, _c / iter, 10 * _c / iter % 10, _c / _i, 10 * _c / _i % 10); \ - } while (0) - - -/** - * Set SET_STATS to 1 if you want to carve out the piece that actually - * does the computation. - */ - -#if HOST_DEBUG -#include -static void setStats(int enable) {} -#else -extern void setStats(int enable); -#endif - - -static void printArray(const char name[], int n, const int arr[]) -{ -#if HOST_DEBUG - int i; - - printf(" %10s :", name); - for (i = 0; i < n; i++) - printf(" %3d ", arr[i]); - printf("\r\n"); -#endif -} - -static void printDoubleArray(const char name[], int n, const double arr[]) -{ -#if HOST_DEBUG - int i; - - printf(" %10s :", name); - for (i = 0; i < n; i++) - printf(" %g ", arr[i]); - printf("\r\n"); -#endif -} - -static int verify(int n, const volatile int *test, const int *verify) -{ - int i; - /* Unrolled for faster verification */ - for (i = 0; i < n / 2 * 2; i += 2) - { - int t0 = test[i], t1 = test[i + 1]; - int v0 = verify[i], v1 = verify[i + 1]; - - if (t0 != v0) - return i + 1; - if (t1 != v1) - return i + 2; - } - if (n % 2 != 0 && test[n - 1] != verify[n - 1]) - return n; - return 0; -} - -static int verifyDouble(int n, const volatile double *test, const double *verify) -{ - int i; - /* Unrolled for faster verification */ - for (i = 0; i < n / 2 * 2; i += 2) - { - double t0 = test[i], t1 = test[i + 1]; - double v0 = verify[i], v1 = verify[i + 1]; - int eq1 = t0 == v0, eq2 = t1 == v1; - - if (!(eq1 & eq2)) - return i + 1 + eq1; - } - if (n % 2 != 0 && test[n - 1] != verify[n - 1]) - return n; - return 0; -} - -static void __attribute__((noinline)) barrier(int ncores) -{ - static volatile int sense = 0; - static volatile int count = 0; - - static __thread int threadsense; - - __sync_synchronize(); - - threadsense = !threadsense; - if (__sync_fetch_and_add(&count, 1) == ncores - 1) - { - count = 0; - sense = threadsense; - } - else - { - while (sense != threadsense) - ; - } - - __sync_synchronize(); -} - -static uint64_t lfsr(uint64_t x) -{ - uint64_t bit = (x ^ (x >> 1)) & 1; - - return (x >> 1) | (bit << 62); -} - - -#if defined(__GNUC__) -#pragma GCC diagnostic warning "-Wunused-parameter" -#pragma GCC diagnostic warning "-Wunused-function" -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* _BSP_UTIL_H */ - diff --git a/cores/arduino/kendryte-standalone-sdk/lib/bsp/interrupt.c b/cores/arduino/kendryte-standalone-sdk/lib/bsp/interrupt.c deleted file mode 100644 index a82fea8..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/bsp/interrupt.c +++ /dev/null @@ -1,66 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * 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. - */ - -/* Enable kernel-mode log API */ - -#include -#include -#include "interrupt.h" -#include "dump.h" -#include "syscalls.h" -#include "syslog.h" - -uintptr_t __attribute__((weak)) -handle_irq_dummy(uintptr_t cause, uintptr_t epc, uintptr_t regs[32], uintptr_t fregs[32]) -{ - dump_core("unhandled interrupt", cause, epc, regs, fregs); - sys_exit(1337); - return epc; -} - -uintptr_t __attribute__((weak, alias("handle_irq_dummy"))) -handle_irq_m_soft(uintptr_t cause, uintptr_t epc, uintptr_t regs[32], uintptr_t fregs[32]); - -uintptr_t __attribute__((weak, alias("handle_irq_dummy"))) -handle_irq_m_timer(uintptr_t cause, uintptr_t epc, uintptr_t regs[32], uintptr_t fregs[32]); - -extern uintptr_t -handle_irq_m_ext(uintptr_t cause, uintptr_t epc, uintptr_t regs[32], uintptr_t fregs[32]); - -uintptr_t __attribute__((weak)) -handle_irq(uintptr_t cause, uintptr_t epc, uintptr_t regs[32], uintptr_t fregs[32]) -{ -#if defined(__GNUC__) -#pragma GCC diagnostic ignored "-Woverride-init" -#endif - /* clang-format off */ - static uintptr_t (* const irq_table[])( - uintptr_t cause, - uintptr_t epc, - uintptr_t regs[32], - uintptr_t fregs[32]) = - { - [0 ... 14] = handle_irq_dummy, - [IRQ_M_SOFT] = handle_irq_m_soft, - [IRQ_M_TIMER] = handle_irq_m_timer, - [IRQ_M_EXT] = handle_irq_m_ext, - }; - /* clang-format on */ -#if defined(__GNUC__) -#pragma GCC diagnostic warning "-Woverride-init" -#endif - return irq_table[cause & CAUSE_MACHINE_IRQ_REASON_MASK](cause, epc, regs, fregs); -} - diff --git a/cores/arduino/kendryte-standalone-sdk/lib/bsp/printf.c b/cores/arduino/kendryte-standalone-sdk/lib/bsp/printf.c deleted file mode 100644 index 3be8d51..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/bsp/printf.c +++ /dev/null @@ -1,653 +0,0 @@ -/** - * File: printf.c - * - * Copyright (c) 2004,2012 Kustaa Nyholm / SpareTimeLabs - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of Kustaa Nyholm or SpareTimeLabs nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include -#include "printf.h" -#include "atomic.h" -#include "uarths.h" - - -/** - * Configuration - */ - -/* Enable long int support */ -#define PRINTF_LONG_SUPPORT - -/* Enable long long int support (implies long int support) */ -#define PRINTF_LONG_LONG_SUPPORT - -/* Enable %z (size_t) support */ -#define PRINTF_SIZE_T_SUPPORT - -/** - * Configuration adjustments - */ -#if defined(PRINTF_LONG_LONG_SUPPORT) -#define PRINTF_LONG_SUPPORT -#endif - -/* __SIZEOF___ defined at least by gcc */ -#if defined(__SIZEOF_POINTER__) -#define SIZEOF_POINTER __SIZEOF_POINTER__ -#endif -#if defined(__SIZEOF_LONG_LONG__) -#define SIZEOF_LONG_LONG __SIZEOF_LONG_LONG__ -#endif -#if defined(__SIZEOF_LONG__) -#define SIZEOF_LONG __SIZEOF_LONG__ -#endif -#if defined(__SIZEOF_INT__) -#define SIZEOF_INT __SIZEOF_INT__ -#endif - -#if defined(__GNUC__) -#define _TFP_GCC_NO_INLINE_ __attribute__((noinline)) -#else -#define _TFP_GCC_NO_INLINE_ -#endif - - -#if defined(PRINTF_LONG_SUPPORT) -#define BF_MAX 20 /* long = 64b on some architectures */ -#else -#define BF_MAX 10 /* int = 32b on some architectures */ -#endif - - -#define IS_DIGIT(x) ((x) >= '0' && (x) <= '9') - -/* Clear unused warnings for actually unused variables */ -#define UNUSED(x) (void)(x) - - - -/** - * Implementation - */ -struct param -{ - char lz : 1; /* Leading zeros */ - char alt : 1; /* alternate form */ - char uc : 1; /* Upper case (for base16 only) */ - char align_left : 1; /* 0 == align right (default), 1 == align left */ - int width; /* field width */ - int prec; /* precision */ - char sign; /* The sign to display (if any) */ - unsigned int base; /* number base (e.g.: 8, 10, 16) */ - char *bf; /* Buffer to output */ - size_t bf_len; /* Buffer length */ -}; - -static corelock_t lock = CORELOCK_INIT; - - - -#if defined(PRINTF_LONG_LONG_SUPPORT) -static void _TFP_GCC_NO_INLINE_ ulli2a(unsigned long long int num, struct param *p) -{ - unsigned long long int d = 1; - char *bf = p->bf; - if ((p->prec == 0) && (num == 0)) - return; - while (num / d >= p->base) - { - d *= p->base; - } - while (d != 0) - { - int dgt = num / d; - num %= d; - d /= p->base; - *bf++ = dgt + (dgt < 10 ? '0' : (p->uc ? 'A' : 'a') - 10); - } - p->bf_len = bf - p->bf; -} - -static void lli2a(long long int num, struct param *p) -{ - if (num < 0) - { - num = -num; - p->sign = '-'; - } - ulli2a(num, p); -} -#endif - -#if defined(PRINTF_LONG_SUPPORT) -static void uli2a(unsigned long int num, struct param *p) -{ - unsigned long int d = 1; - char *bf = p->bf; - if ((p->prec == 0) && (num == 0)) - return; - while (num / d >= p->base) - { - d *= p->base; - } - while (d != 0) - { - int dgt = num / d; - num %= d; - d /= p->base; - *bf++ = dgt + (dgt < 10 ? '0' : (p->uc ? 'A' : 'a') - 10); - } - p->bf_len = bf - p->bf; -} - -static void li2a(long num, struct param *p) -{ - if (num < 0) - { - num = -num; - p->sign = '-'; - } - uli2a(num, p); -} -#endif - -static void ui2a(unsigned int num, struct param *p) -{ - unsigned int d = 1; - char *bf = p->bf; - if ((p->prec == 0) && (num == 0)) - return; - while (num / d >= p->base) - { - d *= p->base; - } - while (d != 0) - { - int dgt = num / d; - num %= d; - d /= p->base; - *bf++ = dgt + (dgt < 10 ? '0' : (p->uc ? 'A' : 'a') - 10); - } - p->bf_len = bf - p->bf; -} - -static void i2a(int num, struct param *p) -{ - if (num < 0) - { - num = -num; - p->sign = '-'; - } - ui2a(num, p); -} - -static int a2d(char ch) -{ - if (IS_DIGIT(ch)) - return ch - '0'; - else if (ch >= 'a' && ch <= 'f') - return ch - 'a' + 10; - else if (ch >= 'A' && ch <= 'F') - return ch - 'A' + 10; - else - return -1; -} - -static char a2u(char ch, const char **src, int base, unsigned int *nump) -{ - const char *p = *src; - unsigned int num = 0; - int digit; - while ((digit = a2d(ch)) >= 0) - { - if (digit > base) - break; - num = num * base + digit; - ch = *p++; - } - *src = p; - *nump = num; - return ch; -} - -static void putchw(void *putp, putcf putf, struct param *p) -{ - char ch; - int width = p->width; - int prec = p->prec; - char *bf = p->bf; - size_t bf_len = p->bf_len; - - /* Number of filling characters */ - width -= bf_len; - prec -= bf_len; - if (p->sign) - width--; - if (p->alt && p->base == 16) - width -= 2; - else if (p->alt && p->base == 8) - width--; - if (prec > 0) - width -= prec; - - /* Fill with space to align to the right, before alternate or sign */ - if (!p->lz && !p->align_left) - { - while (width-- > 0) - putf(putp, ' '); - } - - /* print sign */ - if (p->sign) - putf(putp, p->sign); - - /* Alternate */ - if (p->alt && p->base == 16) - { - putf(putp, '0'); - putf(putp, (p->uc ? 'X' : 'x')); - } - else if (p->alt && p->base == 8) - { - putf(putp, '0'); - } - - /* Fill with zeros, after alternate or sign */ - while (prec-- > 0) - putf(putp, '0'); - if (p->lz) - { - while (width-- > 0) - putf(putp, '0'); - } - - /* Put actual buffer */ - while ((bf_len-- > 0) && (ch = *bf++)) - putf(putp, ch); - - /* Fill with space to align to the left, after string */ - if (!p->lz && p->align_left) - { - while (width-- > 0) - putf(putp, ' '); - } -} - -void tfp_format(void *putp, putcf putf, const char *fmt, va_list va) -{ - struct param p; - char bf[BF_MAX]; - char ch; - - while ((ch = *(fmt++))) - { - if (ch != '%') - { - putf(putp, ch); - } - else - { -#if defined(PRINTF_LONG_SUPPORT) - char lng = 0; /* 1 for long, 2 for long long */ -#endif - /* Init parameter struct */ - p.lz = 0; - p.alt = 0; - p.uc = 0; - p.align_left = 0; - p.width = 0; - p.prec = -1; - p.sign = 0; - p.bf = bf; - p.bf_len = 0; - - /* Flags */ - while ((ch = *(fmt++))) - { - switch (ch) - { - case '-': - p.align_left = 1; - continue; - case '0': - p.lz = 1; - continue; - case '#': - p.alt = 1; - continue; - default: - break; - } - break; - } - - if (p.align_left) - p.lz = 0; - - /* Width */ - if (ch == '*') - { - ch = *(fmt++); - p.width = va_arg(va, int); - if (p.width < 0) - { - p.align_left = 1; - p.width = -p.width; - } - } - else if (IS_DIGIT(ch)) - { - unsigned int width; - ch = a2u(ch, &fmt, 10, &(width)); - p.width = width; - } - - /* Precision */ - if (ch == '.') - { - ch = *(fmt++); - if (ch == '*') - { - int prec; - ch = *(fmt++); - prec = va_arg(va, int); - if (prec < 0) - /* act as if precision was - * omitted */ - p.prec = -1; - else - p.prec = prec; - } - else if (IS_DIGIT(ch)) - { - unsigned int prec; - ch = a2u(ch, &fmt, 10, &(prec)); - p.prec = prec; - } - else - { - p.prec = 0; - } - } - if (p.prec >= 0) - /* precision causes zero pad to be ignored */ - p.lz = 0; - -#if defined(PRINTF_SIZE_T_SUPPORT) -#if defined(PRINTF_LONG_SUPPORT) - if (ch == 'z') - { - ch = *(fmt++); - if (sizeof(size_t) == sizeof(unsigned long int)) - lng = 1; -#if defined(PRINTF_LONG_LONG_SUPPORT) - else if (sizeof(size_t) == sizeof(unsigned long long int)) - lng = 2; -#endif - } - else -#endif -#endif - -#if defined(PRINTF_LONG_SUPPORT) - if (ch == 'l') - { - ch = *(fmt++); - lng = 1; -#if defined(PRINTF_LONG_LONG_SUPPORT) - if (ch == 'l') - { - ch = *(fmt++); - lng = 2; - } -#endif - } -#endif - switch (ch) - { - case 0: - goto abort; - case 'u': - p.base = 10; - if (p.prec < 0) - p.prec = 1; -#if defined(PRINTF_LONG_SUPPORT) -#if defined(PRINTF_LONG_LONG_SUPPORT) - if (2 == lng) - ulli2a(va_arg(va, unsigned long long int), &p); - else -#endif - if (1 == lng) - uli2a(va_arg(va, unsigned long int), &p); - else -#endif - ui2a(va_arg(va, unsigned int), &p); - putchw(putp, putf, &p); - break; - case 'd': /* No break */ - case 'i': - p.base = 10; - if (p.prec < 0) - p.prec = 1; -#if defined(PRINTF_LONG_SUPPORT) -#if defined(PRINTF_LONG_LONG_SUPPORT) - if (2 == lng) - lli2a(va_arg(va, long long int), &p); - else -#endif - if (1 == lng) - li2a(va_arg(va, long int), &p); - else -#endif - i2a(va_arg(va, int), &p); - putchw(putp, putf, &p); - break; -#if defined(SIZEOF_POINTER) - case 'p': - p.alt = 1; -#if defined(SIZEOF_INT) && SIZEOF_POINTER <= SIZEOF_INT - lng = 0; -#elif defined(SIZEOF_LONG) && SIZEOF_POINTER <= SIZEOF_LONG - lng = 1; -#elif defined(SIZEOF_LONG_LONG) && SIZEOF_POINTER <= SIZEOF_LONG_LONG - lng = 2; -#endif -#endif - /* No break */ - case 'x': /* No break */ - case 'X': - p.base = 16; - p.uc = (ch == 'X') ? 1 : 0; - if (p.prec < 0) - p.prec = 1; -#if defined(PRINTF_LONG_SUPPORT) -#if defined(PRINTF_LONG_LONG_SUPPORT) - if (2 == lng) - ulli2a(va_arg(va, unsigned long long int), &p); - else -#endif - if (1 == lng) - uli2a(va_arg(va, unsigned long int), &p); - else -#endif - ui2a(va_arg(va, unsigned int), &p); - putchw(putp, putf, &p); - break; - case 'o': - p.base = 8; - if (p.prec < 0) - p.prec = 1; - ui2a(va_arg(va, unsigned int), &p); - putchw(putp, putf, &p); - break; - case 'c': - putf(putp, (char)(va_arg(va, int))); - break; - case 's': - { - unsigned int prec = p.prec; - char *b; - p.bf = va_arg(va, char*); - b = p.bf; - while ((prec-- != 0) && *b++) - { - p.bf_len++; - } - p.prec = -1; - putchw(putp, putf, &p); - } - break; - case '%': - putf(putp, ch); - break; - default: - break; - } - } - } -abort:; -} - -#if defined(TINYPRINTF_DEFINE_TFP_PRINTF) -static putcf stdout_putf; -static void *stdout_putp; - -void init_printf(void *putp, putcf putf) -{ - stdout_putf = putf; - stdout_putp = putp; -} - -void tfp_printf(char *fmt, ...) -{ - va_list va; - va_start(va, fmt); - tfp_format(stdout_putp, stdout_putf, fmt, va); - va_end(va); -} -#endif - -#if defined(TINYPRINTF_DEFINE_TFP_SPRINTF) -struct _vsnprintf_putcf_data -{ - size_t dest_capacity; - char *dest; - size_t num_chars; -}; - -static void _vsnprintf_putcf(void *p, char c) -{ - struct _vsnprintf_putcf_data *data = (struct _vsnprintf_putcf_data*)p; - if (data->num_chars < data->dest_capacity) - data->dest[data->num_chars] = c; - data->num_chars++; -} - -int tfp_vsnprintf(char *str, size_t size, const char *format, va_list ap) -{ - struct _vsnprintf_putcf_data data; - - if (size < 1) - return 0; - - data.dest = str; - data.dest_capacity = size - 1; - data.num_chars = 0; - tfp_format(&data, _vsnprintf_putcf, format, ap); - - if (data.num_chars < data.dest_capacity) - data.dest[data.num_chars] = '\0'; - else - data.dest[data.dest_capacity] = '\0'; - - return data.num_chars; -} - -int tfp_snprintf(char *str, size_t size, const char *format, ...) -{ - va_list ap; - int retval; - - va_start(ap, format); - retval = tfp_vsnprintf(str, size, format, ap); - va_end(ap); - return retval; -} - -struct _vsprintf_putcf_data -{ - char *dest; - size_t num_chars; -}; - -static void _vsprintf_putcf(void *p, char c) -{ - struct _vsprintf_putcf_data *data = (struct _vsprintf_putcf_data*)p; - data->dest[data->num_chars++] = c; -} - -int tfp_vsprintf(char *str, const char *format, va_list ap) -{ - struct _vsprintf_putcf_data data; - data.dest = str; - data.num_chars = 0; - tfp_format(&data, _vsprintf_putcf, format, ap); - data.dest[data.num_chars] = '\0'; - return data.num_chars; -} - -int tfp_sprintf(char *str, const char *format, ...) -{ - va_list ap; - int retval; - - va_start(ap, format); - retval = tfp_vsprintf(str, format, ap); - va_end(ap); - return retval; -} -#endif - -static void uart_putf(void *unused, char c) -{ - UNUSED(unused); - uarths_putchar(c); -} - -int printk(const char *format, ...) -{ - va_list ap; - - va_start(ap, format); - /* Begin protected code */ - corelock_lock(&lock); - tfp_format(stdout_putp, uart_putf, format, ap); - /* End protected code */ - corelock_unlock(&lock); - va_end(ap); - - return 0; -} - diff --git a/cores/arduino/kendryte-standalone-sdk/lib/bsp/sleep.c b/cores/arduino/kendryte-standalone-sdk/lib/bsp/sleep.c deleted file mode 100644 index ef4c76c..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/bsp/sleep.c +++ /dev/null @@ -1,39 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "sleep.h" -#include "sysctl.h" - -int usleep(uint64_t usec) -{ - uint64_t cycle = read_cycle(); - uint64_t nop_all = usec * sysctl_clock_get_freq(SYSCTL_CLOCK_CPU) / 1000000UL; - while (1) - { - if(read_cycle() - cycle >= nop_all) - break; - } - return 0; -} - -int msleep(uint64_t msec) -{ - return (unsigned int)usleep(msec * 1000); -} - -unsigned int sleep(unsigned int seconds) -{ - return (unsigned int)msleep(seconds * 1000); -} - diff --git a/cores/arduino/kendryte-standalone-sdk/lib/bsp/syscalls.c b/cores/arduino/kendryte-standalone-sdk/lib/bsp/syscalls.c deleted file mode 100644 index 93f25e4..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/bsp/syscalls.c +++ /dev/null @@ -1,631 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * 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. - */ - -/* Enable kernel-mode log API */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "syscalls.h" -#include "atomic.h" -#include "clint.h" -#include "fpioa.h" -#include "interrupt.h" -#include "sysctl.h" -#include "uarths.h" -#include "util.h" -#include "syslog.h" -#include "dump.h" - -/** - * @note System call list - * - * See also riscv-newlib/libgloss/riscv/syscalls.c - * - * | System call | Number | - * |------------------|--------| - * | SYS_exit | 93 | - * | SYS_exit_group | 94 | - * | SYS_getpid | 172 | - * | SYS_kill | 129 | - * | SYS_read | 63 | - * | SYS_write | 64 | - * | SYS_open | 1024 | - * | SYS_openat | 56 | - * | SYS_close | 57 | - * | SYS_lseek | 62 | - * | SYS_brk | 214 | - * | SYS_link | 1025 | - * | SYS_unlink | 1026 | - * | SYS_mkdir | 1030 | - * | SYS_chdir | 49 | - * | SYS_getcwd | 17 | - * | SYS_stat | 1038 | - * | SYS_fstat | 80 | - * | SYS_lstat | 1039 | - * | SYS_fstatat | 79 | - * | SYS_access | 1033 | - * | SYS_faccessat | 48 | - * | SYS_pread | 67 | - * | SYS_pwrite | 68 | - * | SYS_uname | 160 | - * | SYS_getuid | 174 | - * | SYS_geteuid | 175 | - * | SYS_getgid | 176 | - * | SYS_getegid | 177 | - * | SYS_mmap | 222 | - * | SYS_munmap | 215 | - * | SYS_mremap | 216 | - * | SYS_time | 1062 | - * | SYS_getmainvars | 2011 | - * | SYS_rt_sigaction | 134 | - * | SYS_writev | 66 | - * | SYS_gettimeofday | 169 | - * | SYS_times | 153 | - * | SYS_fcntl | 25 | - * | SYS_getdents | 61 | - * | SYS_dup | 23 | - * - */ - -#ifndef UNUSED -#define UNUSED(x) (void)(x) -#endif - -static const char *TAG = "SYSCALL"; - -extern char _heap_start[]; -extern char _heap_end[]; -char *_heap_cur = &_heap_start[0]; - - -void __attribute__((noreturn)) sys_exit(int code) -{ - /* Read core id */ - unsigned long core_id = current_coreid(); - /* First print some diagnostic information. */ - LOGW(TAG, "sys_exit called by core %ld with 0x%lx\r\n", core_id, (uint64_t)code); - while (1) - continue; -} - -static int sys_nosys(long a0, long a1, long a2, long a3, long a4, long a5, unsigned long n) -{ - UNUSED(a3); - UNUSED(a4); - UNUSED(a5); - - LOGE(TAG, "Unsupported syscall %ld: a0=%lx, a1=%lx, a2=%lx!\r\n", n, a0, a1, a2); - while (1) - continue; - return -ENOSYS; -} - -static int sys_success(void) -{ - return 0; -} - -static size_t sys_brk(size_t pos) -{ - uintptr_t res = 0; - /** - * brk() sets the end of the data segment to the value - * specified by addr, when that value is reasonable, the system - * has enough memory, and the process does not exceed its - * maximum data size. - * - * sbrk() increments the program's data space by increment - * bytes. Calling sbrk() with an increment of 0 can be used to - * find the current location of the program break. - * - * uintptr_t brk(uintptr_t ptr); - * - * IN : regs[10] = ptr - * OUT: regs[10] = ptr - */ - - /** - * First call: Initialization brk pointer. newlib will pass - * ptr = 0 when it is first called. In this case the address - * _heap_start will be return. - * - * Call again: Adjust brk pointer. The ptr never equal with - * 0. If ptr is below _heap_end, then allocate memory. - * Otherwise throw out of memory error, return -1. - */ - - if (pos) - { - /* Call again */ - if ((uintptr_t)pos > (uintptr_t)&_heap_end[0]) - { - /* Memory out, return -ENOMEM */ - LOGE(TAG, "Out of memory\r\n"); - res = -ENOMEM; - } - else - { - /* Adjust brk pointer. */ - _heap_cur = (char *)(uintptr_t)pos; - /* Return current address. */ - res = (uintptr_t)_heap_cur; - } - } - else - { - /* First call, return initial address */ - res = (uintptr_t)&_heap_start[0]; - } - return (size_t)res; -} - -static ssize_t sys_write(int file, const void *ptr, size_t len) -{ - ssize_t res = -EBADF; - - /** - * Write to a file. - * - * ssize_t write(int file, const void *ptr, size_t len) - * - * IN : regs[10] = file, regs[11] = ptr, regs[12] = len - * OUT: regs[10] = len - */ - - /* Get size to write */ - register size_t length = len; - /* Get data pointer */ - register char *data = (char *)ptr; - - if (STDOUT_FILENO == file || STDERR_FILENO == file) - { - /* Write data */ - while (length-- > 0 && *data != 0) - uarths_putchar(*(data++)); - - /* Return the actual size written */ - res = len; - } - else - { - /* Not support yet */ - res = -ENOSYS; - } - - return res; -} - -static int sys_fstat(int file, struct stat *st) -{ - int res = -EBADF; - - /** - * Status of an open file. The sys/stat.h header file required - * is - * distributed in the include subdirectory for this C library. - * - * int fstat(int file, struct stat* st) - * - * IN : regs[10] = file, regs[11] = st - * OUT: regs[10] = Upon successful completion, 0 shall be - * returned. - * Otherwise, -1 shall be returned and errno set to indicate - * the error. - */ - - UNUSED(file); - - if (st != NULL) - memset(st, 0, sizeof(struct stat)); - /* Return the result */ - res = -ENOSYS; - /** - * Note: This value will return to syscall wrapper, syscall - * wrapper will set errno to ENOSYS and return -1 - */ - - return res; -} - -static int sys_close(int file) -{ - int res = -EBADF; - - /** - * Close a file. - * - * int close(int file) - * - * IN : regs[10] = file - * OUT: regs[10] = Upon successful completion, 0 shall be - * returned. - * Otherwise, -1 shall be returned and errno set to indicate - * the error. - */ - - UNUSED(file); - /* Return the result */ - res = 0; - return res; -} - -static int sys_gettimeofday(struct timeval *tp, void *tzp) -{ - /** - * Get the current time. Only relatively correct. - * - * int gettimeofday(struct timeval *tp, void *tzp) - * - * IN : regs[10] = tp - * OUT: regs[10] = Upon successful completion, 0 shall be - * returned. - * Otherwise, -1 shall be returned and errno set to indicate - * the error. - */ - UNUSED(tzp); - - if (tp != NULL) - { - uint64_t clint_usec = clint->mtime / (sysctl_clock_get_freq(SYSCTL_CLOCK_CPU) / CLINT_CLOCK_DIV / 1000000UL); - - tp->tv_sec = clint_usec / 1000000UL; - tp->tv_usec = clint_usec % 1000000UL; - } - /* Return the result */ - return 0; -} - -uintptr_t __attribute__((weak)) -handle_ecall(uintptr_t cause, uintptr_t epc, uintptr_t regs[32], uintptr_t fregs[32]) -{ - UNUSED(cause); - UNUSED(fregs); - enum syscall_id_e - { - SYS_ID_NOSYS, - SYS_ID_SUCCESS, - SYS_ID_EXIT, - SYS_ID_BRK, - SYS_ID_WRITE, - SYS_ID_FSTAT, - SYS_ID_CLOSE, - SYS_ID_GETTIMEOFDAY, - SYS_ID_MAX - }; - - static uintptr_t (* const syscall_table[])(long a0, long a1, long a2, long a3, long a4, long a5, unsigned long n) = - { - [SYS_ID_NOSYS] = (void *)sys_nosys, - [SYS_ID_SUCCESS] = (void *)sys_success, - [SYS_ID_EXIT] = (void *)sys_exit, - [SYS_ID_BRK] = (void *)sys_brk, - [SYS_ID_WRITE] = (void *)sys_write, - [SYS_ID_FSTAT] = (void *)sys_fstat, - [SYS_ID_CLOSE] = (void *)sys_close, - [SYS_ID_GETTIMEOFDAY] = (void *)sys_gettimeofday, - }; - -#if defined(__GNUC__) -#pragma GCC diagnostic ignored "-Woverride-init" -#endif - static const uint8_t syscall_id_table[0x100] = - { - [0x00 ... 0xFF] = SYS_ID_NOSYS, - [0xFF & SYS_exit] = SYS_ID_EXIT, - [0xFF & SYS_exit_group] = SYS_ID_EXIT, - [0xFF & SYS_getpid] = SYS_ID_NOSYS, - [0xFF & SYS_kill] = SYS_ID_NOSYS, - [0xFF & SYS_read] = SYS_ID_NOSYS, - [0xFF & SYS_write] = SYS_ID_WRITE, - [0xFF & SYS_open] = SYS_ID_NOSYS, - [0xFF & SYS_openat] = SYS_ID_NOSYS, - [0xFF & SYS_close] = SYS_ID_CLOSE, - [0xFF & SYS_lseek] = SYS_ID_NOSYS, - [0xFF & SYS_brk] = SYS_ID_BRK, - [0xFF & SYS_link] = SYS_ID_NOSYS, - [0xFF & SYS_unlink] = SYS_ID_NOSYS, - [0xFF & SYS_mkdir] = SYS_ID_NOSYS, - [0xFF & SYS_chdir] = SYS_ID_NOSYS, - [0xFF & SYS_getcwd] = SYS_ID_NOSYS, - [0xFF & SYS_stat] = SYS_ID_NOSYS, - [0xFF & SYS_fstat] = SYS_ID_FSTAT, - [0xFF & SYS_lstat] = SYS_ID_NOSYS, - [0xFF & SYS_fstatat] = SYS_ID_NOSYS, - [0xFF & SYS_access] = SYS_ID_NOSYS, - [0xFF & SYS_faccessat] = SYS_ID_NOSYS, - [0xFF & SYS_pread] = SYS_ID_NOSYS, - [0xFF & SYS_pwrite] = SYS_ID_NOSYS, - [0xFF & SYS_uname] = SYS_ID_NOSYS, - [0xFF & SYS_getuid] = SYS_ID_NOSYS, - [0xFF & SYS_geteuid] = SYS_ID_NOSYS, - [0xFF & SYS_getgid] = SYS_ID_NOSYS, - [0xFF & SYS_getegid] = SYS_ID_NOSYS, - [0xFF & SYS_mmap] = SYS_ID_NOSYS, - [0xFF & SYS_munmap] = SYS_ID_NOSYS, - [0xFF & SYS_mremap] = SYS_ID_NOSYS, - [0xFF & SYS_time] = SYS_ID_NOSYS, - [0xFF & SYS_getmainvars] = SYS_ID_NOSYS, - [0xFF & SYS_rt_sigaction] = SYS_ID_NOSYS, - [0xFF & SYS_writev] = SYS_ID_NOSYS, - [0xFF & SYS_gettimeofday] = SYS_ID_GETTIMEOFDAY, - [0xFF & SYS_times] = SYS_ID_NOSYS, - [0xFF & SYS_fcntl] = SYS_ID_NOSYS, - [0xFF & SYS_getdents] = SYS_ID_NOSYS, - [0xFF & SYS_dup] = SYS_ID_NOSYS, - }; -#if defined(__GNUC__) -#pragma GCC diagnostic warning "-Woverride-init" -#endif - - regs[10] = syscall_table[syscall_id_table[0xFF & regs[17]]] - ( - regs[10], /* a0 */ - regs[11], /* a1 */ - regs[12], /* a2 */ - regs[13], /* a3 */ - regs[14], /* a4 */ - regs[15], /* a5 */ - regs[17] /* n */ - ); - - return epc + 4; -} - -uintptr_t __attribute__((weak, alias("handle_ecall"))) -handle_ecall_u(uintptr_t cause, uintptr_t epc, uintptr_t regs[32], uintptr_t fregs[32]); - -uintptr_t __attribute__((weak, alias("handle_ecall"))) -handle_ecall_h(uintptr_t cause, uintptr_t epc, uintptr_t regs[32], uintptr_t fregs[32]); - -uintptr_t __attribute__((weak, alias("handle_ecall"))) -handle_ecall_s(uintptr_t cause, uintptr_t epc, uintptr_t regs[32], uintptr_t fregs[32]); - -uintptr_t __attribute__((weak, alias("handle_ecall"))) -handle_ecall_m(uintptr_t cause, uintptr_t epc, uintptr_t regs[32], uintptr_t fregs[32]); - -uintptr_t __attribute__((weak)) -handle_misaligned_fetch(uintptr_t cause, uintptr_t epc, uintptr_t regs[32], uintptr_t fregs[32]) -{ - dump_core("misaligned fetch", cause, epc, regs, fregs); - sys_exit(1337); - return epc; -} - -uintptr_t __attribute__((weak)) -handle_fault_fetch(uintptr_t cause, uintptr_t epc, uintptr_t regs[32], uintptr_t fregs[32]) -{ - dump_core("fault fetch", cause, epc, regs, fregs); - sys_exit(1337); - return epc; -} - -uintptr_t __attribute__((weak)) -handle_illegal_instruction(uintptr_t cause, uintptr_t epc, uintptr_t regs[32], uintptr_t fregs[32]) -{ - dump_core("illegal instruction", cause, epc, regs, fregs); - sys_exit(1337); - return epc; -} - -uintptr_t __attribute__((weak)) -handle_breakpoint(uintptr_t cause, uintptr_t epc, uintptr_t regs[32], uintptr_t fregs[32]) -{ - dump_core("breakpoint", cause, epc, regs, fregs); - sys_exit(1337); - return epc; -} - -uintptr_t __attribute__((weak)) -handle_misaligned_load(uintptr_t cause, uintptr_t epc, uintptr_t regs[32], uintptr_t fregs[32]) -{ - /* notice this function only support 16bit or 32bit instruction */ - - bool compressed = (*(unsigned short *)epc & 3) != 3; - bool fpu = 0; /* load to fpu ? */ - uintptr_t addr = 0; /* src addr */ - uint8_t src = 0; /* src register */ - uint8_t dst = 0; /* dst register */ - uint8_t len = 0; /* data length */ - int offset = 0; /* addr offset to addr in reg */ - bool unsigned_ = 0; /* unsigned */ - uint64_t data_load = 0;/* real data load */ - - if (compressed) - { - /* compressed instruction should not get this fault. */ - goto on_error; - } - else - { - uint32_t instruct = *(uint32_t *)epc; - uint8_t opcode = instruct&0x7F; - - dst = (instruct >> 7)&0x1F; - len = (instruct >> 12)&3; - unsigned_ = (instruct >> 14)&1; - src = (instruct >> 15)&0x1F; - offset = (instruct >> 20); - len = 1 << len; - switch (opcode) - { - case 3:/* load */ - break; - case 7:/* fpu load */ - fpu = 1; - break; - default: - goto on_error; - } - } - - if (offset >> 11) - offset = -((offset & 0x3FF) + 1); - - addr = (uint64_t)((uint64_t)regs[src] + offset); - - for (int i = 0; i < len; ++i) - data_load |= ((uint64_t)*((uint8_t *)addr + i)) << (8 * i); - - - if (!unsigned_ & !fpu) - { - /* adjust sign */ - switch (len) - { - case 1: - data_load = (uint64_t)(int64_t)((int8_t)data_load); - break; - case 2: - data_load = (uint64_t)(int64_t)((int16_t)data_load); - break; - case 4: - data_load = (uint64_t)(int64_t)((int32_t)data_load); - break; - default: - break; - } - } - - if (fpu) - fregs[dst] = data_load; - else - regs[dst] = data_load; - - LOGV(TAG, "misaligned load recovered at %08lx. len:%02d,addr:%08lx,reg:%02d,data:%016lx,signed:%1d,float:%1d", (uint64_t)epc, len, (uint64_t)addr, dst, data_load, !unsigned_, fpu); - - return epc + (compressed ? 2 : 4); -on_error: - dump_core("misaligned load", cause, epc, regs, fregs); - sys_exit(1337); - return epc; -} - -uintptr_t __attribute__((weak)) -handle_fault_load(uintptr_t cause, uintptr_t epc, uintptr_t regs[32], uintptr_t fregs[32]) -{ - dump_core("fault load", cause, epc, regs, fregs); - sys_exit(1337); - return epc; -} - -uintptr_t __attribute__((weak)) -handle_misaligned_store(uintptr_t cause, uintptr_t epc, uintptr_t regs[32], uintptr_t fregs[32]) -{ - /* notice this function only support 16bit or 32bit instruction */ - - bool compressed = (*(unsigned short *)epc & 3) != 3; - bool fpu = 0; /* store to fpu*/ - uintptr_t addr = 0; /* src addr*/ - uint8_t src = 0; /* src register*/ - uint8_t dst = 0; /* dst register*/ - uint8_t len = 0; /* data length*/ - int offset = 0; /* addr offset to addr in reg*/ - uint64_t data_store = 0;/* real data store*/ - - if (compressed) - { - /* compressed instruction should not get this fault. */ - goto on_error; - } - else - { - uint32_t instruct = *(uint32_t *)epc; - uint8_t opcode = instruct&0x7F; - - len = (instruct >> 12)&7; - dst = (instruct >> 15)&0x1F; - src = (instruct >> 20)&0x1F; - offset = ((instruct >> 7)&0x1F) | ((instruct >> 20)&0xFE0); - len = 1 << len; - switch (opcode) - { - case 0x23:/* store */ - break; - case 0x27:/* fpu store */ - fpu = 1; - break; - default: - goto on_error; - } - } - - if (offset >> 11) - offset = -((offset & 0x3FF) + 1); - - addr = (uint64_t)((uint64_t)regs[dst] + offset); - - - if (fpu) - data_store = fregs[src]; - else - data_store = regs[src]; - - for (int i = 0; i < len; ++i) - *((uint8_t *)addr + i) = (data_store >> (i*8)) & 0xFF; - - LOGV(TAG, "misaligned store recovered at %08lx. len:%02d,addr:%08lx,reg:%02d,data:%016lx,float:%1d", (uint64_t)epc, len, (uint64_t)addr, src, data_store, fpu); - - return epc + (compressed ? 2 : 4); -on_error: - dump_core("misaligned store", cause, epc, regs, fregs); - sys_exit(1337); - return epc; -} - -uintptr_t __attribute__((weak)) -handle_fault_store(uintptr_t cause, uintptr_t epc, uintptr_t regs[32], uintptr_t fregs[32]) -{ - dump_core("fault store", cause, epc, regs, fregs); - sys_exit(1337); - return epc; -} - -uintptr_t handle_syscall(uintptr_t cause, uintptr_t epc, uintptr_t regs[32], uintptr_t fregs[32]) -{ - - static uintptr_t (* const cause_table[])(uintptr_t cause, uintptr_t epc, uintptr_t regs[32], uintptr_t fregs[32]) = - { - [CAUSE_MISALIGNED_FETCH] = handle_misaligned_fetch, - [CAUSE_FAULT_FETCH] = handle_fault_fetch, - [CAUSE_ILLEGAL_INSTRUCTION] = handle_illegal_instruction, - [CAUSE_BREAKPOINT] = handle_breakpoint, - [CAUSE_MISALIGNED_LOAD] = handle_misaligned_load, - [CAUSE_FAULT_LOAD] = handle_fault_load, - [CAUSE_MISALIGNED_STORE] = handle_misaligned_store, - [CAUSE_FAULT_STORE] = handle_fault_store, - [CAUSE_USER_ECALL] = handle_ecall_u, - [CAUSE_SUPERVISOR_ECALL] = handle_ecall_h, - [CAUSE_HYPERVISOR_ECALL] = handle_ecall_s, - [CAUSE_MACHINE_ECALL] = handle_ecall_m, - }; - - return cause_table[cause](cause, epc, regs, fregs); -} - -size_t get_free_heap_size(void) -{ - return (size_t)(&_heap_end[0] - _heap_cur); -} - diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/aes.c b/cores/arduino/kendryte-standalone-sdk/lib/drivers/aes.c deleted file mode 100644 index 2e7e61b..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/aes.c +++ /dev/null @@ -1,803 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include -#include -#include "sysctl.h" -#include "aes.h" -#include "utils.h" - -volatile aes_t *const aes = (volatile aes_t *)AES_BASE_ADDR; - -static void aes_clk_init() -{ - sysctl_clock_enable(SYSCTL_CLOCK_AES); - sysctl_reset(SYSCTL_RESET_AES); -} - -static void aes_write_aad(uint32_t aad_data) -{ - aes->aes_aad_data = aad_data; -} - -static void aes_write_text(uint32_t text_data) -{ - aes->aes_text_data = text_data; -} - -static void gcm_write_tag(uint32_t *tag) -{ - aes->gcm_in_tag[0] = tag[3]; - aes->gcm_in_tag[1] = tag[2]; - aes->gcm_in_tag[2] = tag[1]; - aes->gcm_in_tag[3] = tag[0]; -} - -static uint32_t aes_get_data_in_flag(void) -{ - return aes->data_in_flag; -} - -static uint32_t aes_get_data_out_flag(void) -{ - return aes->data_out_flag; -} - -static uint32_t gcm_get_tag_in_flag(void) -{ - return aes->tag_in_flag; -} - -static uint32_t aes_read_out_data(void) -{ - return aes->aes_out_data; -} - -static uint32_t gcm_get_tag_chk(void) -{ - return aes->tag_chk; -} - -static void gcm_clear_chk_tag(void) -{ - aes->tag_clear = 0; -} - -static uint32_t gcm_check_tag(uint32_t *gcm_tag) -{ - while (!gcm_get_tag_in_flag()) - ; - gcm_write_tag(gcm_tag); - while (!gcm_get_tag_chk()) - ; - if (gcm_get_tag_chk() == 0x2) - { - gcm_clear_chk_tag(); - return 1; - } - else - { - gcm_clear_chk_tag(); - return 0; - } -} - -void gcm_get_tag(uint8_t *gcm_tag) -{ - uint32_t uint32_tag; - uint8_t i = 0; - - uint32_tag = aes->gcm_out_tag[3]; - gcm_tag[i++] = (uint8_t)((uint32_tag >> 24) & 0xff); - gcm_tag[i++] = (uint8_t)((uint32_tag >> 16) & 0xff); - gcm_tag[i++] = (uint8_t)((uint32_tag >> 8) & 0xff); - gcm_tag[i++] = (uint8_t)((uint32_tag)&0xff); - - uint32_tag = aes->gcm_out_tag[2]; - gcm_tag[i++] = (uint8_t)((uint32_tag >> 24) & 0xff); - gcm_tag[i++] = (uint8_t)((uint32_tag >> 16) & 0xff); - gcm_tag[i++] = (uint8_t)((uint32_tag >> 8) & 0xff); - gcm_tag[i++] = (uint8_t)((uint32_tag)&0xff); - - uint32_tag = aes->gcm_out_tag[1]; - gcm_tag[i++] = (uint8_t)((uint32_tag >> 24) & 0xff); - gcm_tag[i++] = (uint8_t)((uint32_tag >> 16) & 0xff); - gcm_tag[i++] = (uint8_t)((uint32_tag >> 8) & 0xff); - gcm_tag[i++] = (uint8_t)((uint32_tag)&0xff); - - uint32_tag = aes->gcm_out_tag[0]; - gcm_tag[i++] = (uint8_t)((uint32_tag >> 24) & 0xff); - gcm_tag[i++] = (uint8_t)((uint32_tag >> 16) & 0xff); - gcm_tag[i++] = (uint8_t)((uint32_tag >> 8) & 0xff); - gcm_tag[i++] = (uint8_t)((uint32_tag)&0xff); - - gcm_check_tag((uint32_t *)gcm_tag); -} - - -void aes_init(uint8_t *input_key, size_t input_key_len, uint8_t *iv,size_t iv_len, uint8_t *gcm_aad, - aes_cipher_mode_t cipher_mode, aes_encrypt_sel_t encrypt_sel, size_t gcm_aad_len, size_t input_data_len) -{ - size_t remainder, uint32_num, uint8_num, i; - uint32_t uint32_data; - uint8_t uint8_data[4] = {0}; - size_t padding_len = input_data_len; - aes_clk_init(); - if ((cipher_mode == AES_ECB) || (cipher_mode == AES_CBC)) - padding_len = ((input_data_len + 15) / 16) * 16; - aes->aes_endian |= 1; - uint32_num = input_key_len / 4; - for (i = 0; i < uint32_num; i++) - { - if (i < 4) - aes->aes_key[i] = *((uint32_t *)(&input_key[input_key_len - (4 * i) - 4])); - else - aes->aes_key_ext[i - 4] = *((uint32_t *)(&input_key[input_key_len - (4 * i) - 4])); - } - - uint32_num = iv_len / 4; - for (i = 0; i < uint32_num; i++) - aes->aes_iv[i] = *((uint32_t *)(&iv[iv_len - (4 * i) - 4])); - - aes->mode_ctl.kmode = input_key_len / 8 - 2; /* b'00:AES_128 b'01:AES_192 b'10:AES_256 b'11:RESERVED */ - aes->mode_ctl.cipher_mode = cipher_mode; - aes->encrypt_sel = encrypt_sel; - aes->gb_aad_num = gcm_aad_len - 1; - aes->gb_pc_num = padding_len - 1; - aes->gb_aes_en |= 1; - - if (cipher_mode == AES_GCM) - { - uint32_num = gcm_aad_len / 4; - for (i = 0; i < uint32_num; i++) - { - uint32_data = *((uint32_t *)(&gcm_aad[i * 4])); - while (!aes_get_data_in_flag()) - ; - aes_write_aad(uint32_data); - } - uint8_num = 4 * uint32_num; - remainder = gcm_aad_len % 4; - if (remainder) - { - switch (remainder) - { - case 1: - uint8_data[0] = gcm_aad[uint8_num]; - break; - case 2: - uint8_data[0] = gcm_aad[uint8_num]; - uint8_data[1] = gcm_aad[uint8_num + 1]; - break; - case 3: - uint8_data[0] = gcm_aad[uint8_num]; - uint8_data[1] = gcm_aad[uint8_num + 1]; - uint8_data[2] = gcm_aad[uint8_num + 2]; - break; - default: - break; - } - uint32_data = *((uint32_t *)(&uint8_data[0])); - while (!aes_get_data_in_flag()) - ; - aes_write_aad(uint32_data); - } - } -} - -static void aes_input_bytes(const uint8_t *input_data, size_t input_data_len, aes_cipher_mode_t cipher_mode) -{ - size_t padding_len, uint32_num, uint8_num, remainder, i; - uint32_t uint32_data; - uint8_t uint8_data[4] = {0}; - - padding_len = ((input_data_len + 15) / 16) * 16; - uint32_num = input_data_len / 4; - for (i = 0; i < uint32_num; i++) - { - uint32_data = *((uint32_t *)(&input_data[i * 4])); - while (!aes_get_data_in_flag()) - ; - aes_write_text(uint32_data); - } - uint8_num = 4 * uint32_num; - remainder = input_data_len % 4; - if (remainder) - { - switch (remainder) - { - case 1: - uint8_data[0] = input_data[uint8_num]; - break; - case 2: - uint8_data[0] = input_data[uint8_num]; - uint8_data[1] = input_data[uint8_num + 1]; - break; - case 3: - uint8_data[0] = input_data[uint8_num]; - uint8_data[1] = input_data[uint8_num + 1]; - uint8_data[2] = input_data[uint8_num + 2]; - break; - default: - break; - } - uint32_data = *((uint32_t *)(&uint8_data[0])); - while (!aes_get_data_in_flag()) - ; - aes_write_text(uint32_data); - } - if ((cipher_mode == AES_ECB) || (cipher_mode == AES_CBC)) - { - uint32_num = (padding_len - input_data_len) / 4; - for (i = 0; i < uint32_num; i++) - { - while (!aes_get_data_in_flag()) - ; - aes_write_text(0); - } - uint32_num = padding_len / 4; - } -} - -static void process_less_80_bytes(uint8_t *input_data, uint8_t *output_data, size_t input_data_len, aes_cipher_mode_t cipher_mode) -{ - size_t padding_len, uint32_num, uint8_num, remainder, i; - uint32_t uint32_data; - uint8_t uint8_data[4] = {0}; - - padding_len = ((input_data_len + 15) / 16) * 16; - uint32_num = input_data_len / 4; - for (i = 0; i < uint32_num; i++) - { - uint32_data = *((uint32_t *)(&input_data[i * 4])); - while (!aes_get_data_in_flag()) - ; - aes_write_text(uint32_data); - } - uint8_num = 4 * uint32_num; - remainder = input_data_len % 4; - if (remainder) - { - switch (remainder) - { - case 1: - uint8_data[0] = input_data[uint8_num]; - break; - case 2: - uint8_data[0] = input_data[uint8_num]; - uint8_data[1] = input_data[uint8_num + 1]; - break; - case 3: - uint8_data[0] = input_data[uint8_num]; - uint8_data[1] = input_data[uint8_num + 1]; - uint8_data[2] = input_data[uint8_num + 2]; - break; - default: - break; - } - uint32_data = *((uint32_t *)(&uint8_data[0])); - while (!aes_get_data_in_flag()) - ; - aes_write_text(uint32_data); - } - if ((cipher_mode == AES_ECB) || (cipher_mode == AES_CBC)) - { - uint32_num = (padding_len - input_data_len) / 4; - for (i = 0; i < uint32_num; i++) - { - while (!aes_get_data_in_flag()) - ; - aes_write_text(0); - } - uint32_num = padding_len / 4; - } - for (i = 0; i < uint32_num; i++) - { - while (!aes_get_data_out_flag()) - ; - *((uint32_t *)(&output_data[i * 4])) = aes_read_out_data(); - } - if ((cipher_mode == AES_GCM) && (remainder)) - { - while (!aes_get_data_out_flag()) - ; - *((uint32_t *)(&uint8_data[0])) = aes_read_out_data(); - switch (remainder) - { - case 1: - output_data[uint32_num * 4] = uint8_data[0]; - break; - case 2: - output_data[uint32_num * 4] = uint8_data[0]; - output_data[(i * 4) + 1] = uint8_data[1]; - break; - case 3: - output_data[uint32_num * 4] = uint8_data[0]; - output_data[(i * 4) + 1] = uint8_data[1]; - output_data[(i * 4) + 2] = uint8_data[2]; - break; - default: - break; - } - } -} - -void aes_process(uint8_t *input_data, uint8_t *output_data, size_t input_data_len, aes_cipher_mode_t cipher_mode) -{ - size_t temp_len = 0; - uint32_t i = 0; - - if (input_data_len >= 80) - { - for (i = 0; i < (input_data_len / 80); i++) - process_less_80_bytes(&input_data[i * 80], &output_data[i * 80], 80, cipher_mode); - } - temp_len = input_data_len % 80; - if (temp_len) - process_less_80_bytes(&input_data[i * 80], &output_data[i * 80], temp_len, cipher_mode); -} - -void aes_ecb128_hard_decrypt(uint8_t *input_key, uint8_t *input_data, size_t input_len, uint8_t *output_data) -{ - size_t padding_len = ((input_len + 15) / 16) * 16; - aes_init(input_key, AES_128, NULL, 0L, NULL, AES_ECB, AES_HARD_DECRYPTION, 0L, input_len); - aes_process(input_data, output_data, padding_len, AES_ECB); -} - -void aes_ecb128_hard_encrypt(uint8_t *input_key, uint8_t *input_data, size_t input_len, uint8_t *output_data) -{ - aes_init(input_key, AES_128, NULL, 0L, NULL, AES_ECB, AES_HARD_ENCRYPTION, 0L, input_len); - aes_process(input_data, output_data, input_len, AES_ECB); -} - -void aes_ecb192_hard_decrypt(uint8_t *input_key, uint8_t *input_data, size_t input_len, uint8_t *output_data) -{ - size_t padding_len = ((input_len + 15) / 16) * 16; - aes_init(input_key, AES_192, NULL, 0L, NULL, AES_ECB, AES_HARD_DECRYPTION, 0L, input_len); - aes_process(input_data, output_data, padding_len, AES_ECB); -} - -void aes_ecb192_hard_encrypt(uint8_t *input_key, uint8_t *input_data, size_t input_len, uint8_t *output_data) -{ - aes_init(input_key, AES_192, NULL, 0L, NULL, AES_ECB, AES_HARD_ENCRYPTION, 0L, input_len); - aes_process(input_data, output_data, input_len, AES_ECB); -} - -void aes_ecb256_hard_decrypt(uint8_t *input_key, uint8_t *input_data, size_t input_len, uint8_t *output_data) -{ - size_t padding_len = ((input_len + 15) / 16) * 16; - aes_init(input_key, AES_256, NULL, 0L, NULL, AES_ECB, AES_HARD_DECRYPTION, 0L, input_len); - aes_process(input_data, output_data, padding_len, AES_ECB); -} - -void aes_ecb256_hard_encrypt(uint8_t *input_key, uint8_t *input_data, size_t input_len, uint8_t *output_data) -{ - aes_init(input_key, AES_256, NULL, 0L, NULL, AES_ECB, AES_HARD_ENCRYPTION, 0L, input_len); - aes_process(input_data, output_data, input_len, AES_ECB); -} - -void aes_cbc128_hard_decrypt(cbc_context_t *context, uint8_t *input_data, size_t input_len, uint8_t *output_data) -{ - size_t padding_len = ((input_len + 15) / 16) * 16; - aes_init(context->input_key, AES_128, context->iv, IV_LEN_128, NULL, AES_CBC, AES_HARD_DECRYPTION, 0L, input_len); - aes_process(input_data, output_data, padding_len, AES_CBC); -} - -void aes_cbc128_hard_encrypt(cbc_context_t *context, uint8_t *input_data, size_t input_len, uint8_t *output_data) -{ - aes_init(context->input_key, AES_128, context->iv, IV_LEN_128, NULL, AES_CBC, AES_HARD_ENCRYPTION, 0L, input_len); - aes_process(input_data, output_data, input_len, AES_CBC); -} - -void aes_cbc192_hard_decrypt(cbc_context_t *context, uint8_t *input_data, size_t input_len, uint8_t *output_data) -{ - size_t padding_len = ((input_len + 15) / 16) * 16; - aes_init(context->input_key, AES_192, context->iv, IV_LEN_128, NULL, AES_CBC, AES_HARD_DECRYPTION, 0L, input_len); - aes_process(input_data, output_data, padding_len, AES_CBC); -} - -void aes_cbc192_hard_encrypt(cbc_context_t *context, uint8_t *input_data, size_t input_len, uint8_t *output_data) -{ - aes_init(context->input_key, AES_192, context->iv, IV_LEN_128, NULL, AES_CBC, AES_HARD_ENCRYPTION, 0L, input_len); - aes_process(input_data, output_data, input_len, AES_CBC); -} - -void aes_cbc256_hard_decrypt(cbc_context_t *context, uint8_t *input_data, size_t input_len, uint8_t *output_data) -{ - size_t padding_len = ((input_len + 15) / 16) * 16; - aes_init(context->input_key, AES_256, context->iv, IV_LEN_128, NULL, AES_CBC, AES_HARD_DECRYPTION, 0L, input_len); - aes_process(input_data, output_data, padding_len, AES_CBC); -} - -void aes_cbc256_hard_encrypt(cbc_context_t *context, uint8_t *input_data, size_t input_len, uint8_t *output_data) -{ - aes_init(context->input_key, AES_256, context->iv, IV_LEN_128, NULL, AES_CBC, AES_HARD_ENCRYPTION, 0L, input_len); - aes_process(input_data, output_data, input_len, AES_CBC); -} - -void aes_gcm128_hard_decrypt(gcm_context_t *context, uint8_t *input_data, size_t input_len, uint8_t *output_data, uint8_t *gcm_tag) -{ - aes_init(context->input_key, AES_128, context->iv, IV_LEN_96, context->gcm_aad, - AES_GCM, AES_HARD_DECRYPTION, context->gcm_aad_len, input_len); - aes_process(input_data, output_data, input_len, AES_GCM); - gcm_get_tag(gcm_tag); -} - -void aes_gcm128_hard_encrypt(gcm_context_t *context, uint8_t *input_data, size_t input_len, uint8_t *output_data, uint8_t *gcm_tag) -{ - aes_init(context->input_key, AES_128, context->iv, IV_LEN_96, context->gcm_aad, - AES_GCM, AES_HARD_ENCRYPTION, context->gcm_aad_len, input_len); - aes_process(input_data, output_data, input_len, AES_GCM); - gcm_get_tag(gcm_tag); -} - -void aes_gcm192_hard_decrypt(gcm_context_t *context, uint8_t *input_data, size_t input_len, uint8_t *output_data, uint8_t *gcm_tag) -{ - aes_init(context->input_key, AES_192, context->iv, IV_LEN_96, context->gcm_aad, - AES_GCM, AES_HARD_DECRYPTION, context->gcm_aad_len, input_len); - aes_process(input_data, output_data, input_len, AES_GCM); - gcm_get_tag(gcm_tag); -} - -void aes_gcm192_hard_encrypt(gcm_context_t *context, uint8_t *input_data, size_t input_len, uint8_t *output_data, uint8_t *gcm_tag) -{ - aes_init(context->input_key, AES_192, context->iv, IV_LEN_96, context->gcm_aad, - AES_GCM, AES_HARD_ENCRYPTION, context->gcm_aad_len, input_len); - aes_process(input_data, output_data, input_len, AES_GCM); - gcm_get_tag(gcm_tag); -} - -void aes_gcm256_hard_decrypt(gcm_context_t *context, uint8_t *input_data, size_t input_len, uint8_t *output_data, uint8_t *gcm_tag) -{ - aes_init(context->input_key, AES_256, context->iv, IV_LEN_96, context->gcm_aad, - AES_GCM, AES_HARD_DECRYPTION, context->gcm_aad_len, input_len); - aes_process(input_data, output_data, input_len, AES_GCM); - gcm_get_tag(gcm_tag); -} - -void aes_gcm256_hard_encrypt(gcm_context_t *context, uint8_t *input_data, size_t input_len, uint8_t *output_data, uint8_t *gcm_tag) -{ - aes_init(context->input_key, AES_256, context->iv, IV_LEN_96, context->gcm_aad, - AES_GCM, AES_HARD_ENCRYPTION, context->gcm_aad_len, input_len); - aes_process(input_data, output_data, input_len, AES_GCM); - gcm_get_tag(gcm_tag); -} - -void aes_ecb128_hard_decrypt_dma(dmac_channel_number_t dma_receive_channel_num, - uint8_t *input_key, - uint8_t *input_data, - size_t input_len, - uint8_t *output_data) -{ - size_t padding_len = ((input_len + 15) / 16) * 16; - aes_init(input_key, AES_128, NULL, 0L, NULL, AES_ECB, AES_HARD_DECRYPTION, 0L, input_len); - - sysctl_dma_select(dma_receive_channel_num, SYSCTL_DMA_SELECT_AES_REQ); - aes->dma_sel = 1; - dmac_set_single_mode(dma_receive_channel_num, (void *)(&aes->aes_out_data), output_data, DMAC_ADDR_NOCHANGE, DMAC_ADDR_INCREMENT, - DMAC_MSIZE_4, DMAC_TRANS_WIDTH_32, padding_len >> 2); - aes_input_bytes(input_data, input_len, AES_ECB); - - dmac_wait_done(dma_receive_channel_num); -} - - -void aes_ecb128_hard_encrypt_dma(dmac_channel_number_t dma_receive_channel_num, - uint8_t *input_key, - uint8_t *input_data, - size_t input_len, - uint8_t *output_data) -{ - aes_init(input_key, AES_128, NULL, 0L, NULL, AES_ECB, AES_HARD_ENCRYPTION, 0L, input_len); - size_t padding_len = ((input_len + 15) / 16) * 16; - - sysctl_dma_select(dma_receive_channel_num, SYSCTL_DMA_SELECT_AES_REQ); - aes->dma_sel = 1; - dmac_set_single_mode(dma_receive_channel_num, (void *)(&aes->aes_out_data), output_data, DMAC_ADDR_NOCHANGE, DMAC_ADDR_INCREMENT, - DMAC_MSIZE_4, DMAC_TRANS_WIDTH_32, padding_len >> 2); - aes_input_bytes(input_data, input_len, AES_ECB); - dmac_wait_done(dma_receive_channel_num); -} - -void aes_ecb192_hard_decrypt_dma(dmac_channel_number_t dma_receive_channel_num, - uint8_t *input_key, - uint8_t *input_data, - size_t input_len, - uint8_t *output_data) -{ - size_t padding_len = ((input_len + 15) / 16) * 16; - aes_init(input_key, AES_192, NULL, 0L, NULL, AES_ECB, AES_HARD_DECRYPTION, 0L, input_len); - - sysctl_dma_select(dma_receive_channel_num, SYSCTL_DMA_SELECT_AES_REQ); - aes->dma_sel = 1; - dmac_set_single_mode(dma_receive_channel_num, (void *)(&aes->aes_out_data), output_data, DMAC_ADDR_NOCHANGE, DMAC_ADDR_INCREMENT, - DMAC_MSIZE_4, DMAC_TRANS_WIDTH_32, padding_len >> 2); - aes_input_bytes(input_data, input_len, AES_ECB); - dmac_wait_done(dma_receive_channel_num); -} - -void aes_ecb192_hard_encrypt_dma(dmac_channel_number_t dma_receive_channel_num, - uint8_t *input_key, - uint8_t *input_data, - size_t input_len, - uint8_t *output_data) -{ - aes_init(input_key, AES_192, NULL, 0L, NULL, AES_ECB, AES_HARD_ENCRYPTION, 0L, input_len); - size_t padding_len = ((input_len + 15) / 16) * 16; - - sysctl_dma_select(dma_receive_channel_num, SYSCTL_DMA_SELECT_AES_REQ); - aes->dma_sel = 1; - dmac_set_single_mode(dma_receive_channel_num, (void *)(&aes->aes_out_data), output_data, DMAC_ADDR_NOCHANGE, DMAC_ADDR_INCREMENT, - DMAC_MSIZE_4, DMAC_TRANS_WIDTH_32, padding_len >> 2); - aes_input_bytes(input_data, input_len, AES_ECB); - dmac_wait_done(dma_receive_channel_num); -} - -void aes_ecb256_hard_decrypt_dma(dmac_channel_number_t dma_receive_channel_num, - uint8_t *input_key, - uint8_t *input_data, - size_t input_len, - uint8_t *output_data) -{ - size_t padding_len = ((input_len + 15) / 16) * 16; - aes_init(input_key, AES_256, NULL, 0L, NULL, AES_ECB, AES_HARD_DECRYPTION, 0L, input_len); - - sysctl_dma_select(dma_receive_channel_num, SYSCTL_DMA_SELECT_AES_REQ); - aes->dma_sel = 1; - dmac_set_single_mode(dma_receive_channel_num, (void *)(&aes->aes_out_data), output_data, DMAC_ADDR_NOCHANGE, DMAC_ADDR_INCREMENT, - DMAC_MSIZE_4, DMAC_TRANS_WIDTH_32, padding_len >> 2); - aes_input_bytes(input_data, input_len, AES_ECB); - dmac_wait_done(dma_receive_channel_num); -} - -void aes_ecb256_hard_encrypt_dma(dmac_channel_number_t dma_receive_channel_num, - uint8_t *input_key, - uint8_t *input_data, - size_t input_len, - uint8_t *output_data) -{ - aes_init(input_key, AES_256, NULL, 0L, NULL, AES_ECB, AES_HARD_ENCRYPTION, 0L, input_len); - size_t padding_len = ((input_len + 15) / 16) * 16; - - sysctl_dma_select(dma_receive_channel_num, SYSCTL_DMA_SELECT_AES_REQ); - aes->dma_sel = 1; - dmac_set_single_mode(dma_receive_channel_num, (void *)(&aes->aes_out_data), output_data, DMAC_ADDR_NOCHANGE, DMAC_ADDR_INCREMENT, - DMAC_MSIZE_4, DMAC_TRANS_WIDTH_32, padding_len >> 2); - aes_input_bytes(input_data, input_len, AES_ECB); - - dmac_wait_done(dma_receive_channel_num); -} - -void aes_cbc128_hard_decrypt_dma(dmac_channel_number_t dma_receive_channel_num, - cbc_context_t *context, - uint8_t *input_data, - size_t input_len, - uint8_t *output_data) -{ - size_t padding_len = ((input_len + 15) / 16) * 16; - aes_init(context->input_key, AES_128, context->iv, IV_LEN_128, NULL, AES_CBC, AES_HARD_DECRYPTION, 0L, input_len); - - sysctl_dma_select(dma_receive_channel_num, SYSCTL_DMA_SELECT_AES_REQ); - aes->dma_sel = 1; - dmac_set_single_mode(dma_receive_channel_num, (void *)(&aes->aes_out_data), output_data, DMAC_ADDR_NOCHANGE, DMAC_ADDR_INCREMENT, - DMAC_MSIZE_4, DMAC_TRANS_WIDTH_32, padding_len >> 2); - aes_input_bytes(input_data, input_len, AES_CBC); - dmac_wait_done(dma_receive_channel_num); -} - -void aes_cbc128_hard_encrypt_dma(dmac_channel_number_t dma_receive_channel_num, - cbc_context_t *context, - uint8_t *input_data, - size_t input_len, - uint8_t *output_data) -{ - aes_init(context->input_key, AES_128, context->iv, IV_LEN_128, NULL, AES_CBC, AES_HARD_ENCRYPTION, 0L, input_len); - size_t padding_len = ((input_len + 15) / 16) * 16; - - sysctl_dma_select(dma_receive_channel_num, SYSCTL_DMA_SELECT_AES_REQ); - aes->dma_sel = 1; - dmac_set_single_mode(dma_receive_channel_num, (void *)(&aes->aes_out_data), output_data, DMAC_ADDR_NOCHANGE, DMAC_ADDR_INCREMENT, - DMAC_MSIZE_4, DMAC_TRANS_WIDTH_32, padding_len >> 2); - aes_input_bytes(input_data, input_len, AES_CBC); - dmac_wait_done(dma_receive_channel_num); -} - -void aes_cbc192_hard_decrypt_dma(dmac_channel_number_t dma_receive_channel_num, - cbc_context_t *context, - uint8_t *input_data, - size_t input_len, - uint8_t *output_data) -{ - size_t padding_len = ((input_len + 15) / 16) * 16; - aes_init(context->input_key, AES_192, context->iv, IV_LEN_128, NULL, AES_CBC, AES_HARD_DECRYPTION, 0L, input_len); - - sysctl_dma_select(dma_receive_channel_num, SYSCTL_DMA_SELECT_AES_REQ); - aes->dma_sel = 1; - dmac_set_single_mode(dma_receive_channel_num, (void *)(&aes->aes_out_data), output_data, DMAC_ADDR_NOCHANGE, DMAC_ADDR_INCREMENT, - DMAC_MSIZE_4, DMAC_TRANS_WIDTH_32, padding_len >> 2); - aes_input_bytes(input_data, input_len, AES_CBC); - dmac_wait_done(dma_receive_channel_num); -} - -void aes_cbc192_hard_encrypt_dma(dmac_channel_number_t dma_receive_channel_num, - cbc_context_t *context, - uint8_t *input_data, - size_t input_len, - uint8_t *output_data) -{ - aes_init(context->input_key, AES_192, context->iv, IV_LEN_128, NULL, AES_CBC, AES_HARD_ENCRYPTION, 0L, input_len); - size_t padding_len = ((input_len + 15) / 16) * 16; - - sysctl_dma_select(dma_receive_channel_num, SYSCTL_DMA_SELECT_AES_REQ); - aes->dma_sel = 1; - dmac_set_single_mode(dma_receive_channel_num, (void *)(&aes->aes_out_data), output_data, DMAC_ADDR_NOCHANGE, DMAC_ADDR_INCREMENT, - DMAC_MSIZE_4, DMAC_TRANS_WIDTH_32, padding_len >> 2); - aes_input_bytes(input_data, input_len, AES_CBC); - dmac_wait_done(dma_receive_channel_num); -} - -void aes_cbc256_hard_decrypt_dma(dmac_channel_number_t dma_receive_channel_num, - cbc_context_t *context, - uint8_t *input_data, - size_t input_len, - uint8_t *output_data) -{ - size_t padding_len = ((input_len + 15) / 16) * 16; - aes_init(context->input_key, AES_256, context->iv, IV_LEN_128, NULL, AES_CBC, AES_HARD_DECRYPTION, 0L, input_len); - - sysctl_dma_select(dma_receive_channel_num, SYSCTL_DMA_SELECT_AES_REQ); - aes->dma_sel = 1; - dmac_set_single_mode(dma_receive_channel_num, (void *)(&aes->aes_out_data), output_data, DMAC_ADDR_NOCHANGE, DMAC_ADDR_INCREMENT, - DMAC_MSIZE_4, DMAC_TRANS_WIDTH_32, padding_len >> 2); - aes_input_bytes(input_data, input_len, AES_CBC); - dmac_wait_done(dma_receive_channel_num); -} - -void aes_cbc256_hard_encrypt_dma(dmac_channel_number_t dma_receive_channel_num, - cbc_context_t *context, - uint8_t *input_data, - size_t input_len, - uint8_t *output_data) -{ - aes_init(context->input_key, AES_256, context->iv, IV_LEN_128, NULL, AES_CBC, AES_HARD_ENCRYPTION, 0L, input_len); - size_t padding_len = ((input_len + 15) / 16) * 16; - - sysctl_dma_select(dma_receive_channel_num, SYSCTL_DMA_SELECT_AES_REQ); - aes->dma_sel = 1; - dmac_set_single_mode(dma_receive_channel_num, (void *)(&aes->aes_out_data), output_data, DMAC_ADDR_NOCHANGE, DMAC_ADDR_INCREMENT, - DMAC_MSIZE_4, DMAC_TRANS_WIDTH_32, padding_len >> 2); - aes_input_bytes(input_data, input_len, AES_CBC); - dmac_wait_done(dma_receive_channel_num); -} - -void aes_gcm128_hard_decrypt_dma(dmac_channel_number_t dma_receive_channel_num, - gcm_context_t *context, - uint8_t *input_data, - size_t input_len, - uint8_t *output_data, - uint8_t *gcm_tag) -{ - aes_init(context->input_key, AES_128, context->iv, IV_LEN_96, context->gcm_aad, - AES_GCM, AES_HARD_DECRYPTION, context->gcm_aad_len, input_len); - - sysctl_dma_select(dma_receive_channel_num, SYSCTL_DMA_SELECT_AES_REQ); - aes->dma_sel = 1; - dmac_set_single_mode(dma_receive_channel_num, (void *)(&aes->aes_out_data), output_data, DMAC_ADDR_NOCHANGE, DMAC_ADDR_INCREMENT, - DMAC_MSIZE_4, DMAC_TRANS_WIDTH_32, (input_len + 3) >> 2); - aes_input_bytes(input_data, input_len, AES_GCM); - dmac_wait_done(dma_receive_channel_num); - - gcm_get_tag(gcm_tag); -} - -void aes_gcm128_hard_encrypt_dma(dmac_channel_number_t dma_receive_channel_num, - gcm_context_t *context, - uint8_t *input_data, - size_t input_len, - uint8_t *output_data, - uint8_t *gcm_tag) -{ - aes_init(context->input_key, AES_128, context->iv, IV_LEN_96, context->gcm_aad, - AES_GCM, AES_HARD_ENCRYPTION, context->gcm_aad_len, input_len); - - sysctl_dma_select(dma_receive_channel_num, SYSCTL_DMA_SELECT_AES_REQ); - aes->dma_sel = 1; - dmac_set_single_mode(dma_receive_channel_num, (void *)(&aes->aes_out_data), output_data, DMAC_ADDR_NOCHANGE, DMAC_ADDR_INCREMENT, - DMAC_MSIZE_4, DMAC_TRANS_WIDTH_32, (input_len + 3) >> 2); - aes_input_bytes(input_data, input_len, AES_GCM); - dmac_wait_done(dma_receive_channel_num); - - gcm_get_tag(gcm_tag); -} - -void aes_gcm192_hard_decrypt_dma(dmac_channel_number_t dma_receive_channel_num, - gcm_context_t *context, - uint8_t *input_data, - size_t input_len, - uint8_t *output_data, - uint8_t *gcm_tag) -{ - aes_init(context->input_key, AES_192, context->iv, IV_LEN_96, context->gcm_aad, - AES_GCM, AES_HARD_DECRYPTION, context->gcm_aad_len, input_len); - - sysctl_dma_select(dma_receive_channel_num, SYSCTL_DMA_SELECT_AES_REQ); - aes->dma_sel = 1; - dmac_set_single_mode(dma_receive_channel_num, (void *)(&aes->aes_out_data), output_data, DMAC_ADDR_NOCHANGE, DMAC_ADDR_INCREMENT, - DMAC_MSIZE_4, DMAC_TRANS_WIDTH_32, (input_len + 3) >> 2); - aes_input_bytes(input_data, input_len, AES_GCM); - dmac_wait_done(dma_receive_channel_num); - - gcm_get_tag(gcm_tag); -} - -void aes_gcm192_hard_encrypt_dma(dmac_channel_number_t dma_receive_channel_num, - gcm_context_t *context, - uint8_t *input_data, - size_t input_len, - uint8_t *output_data, - uint8_t *gcm_tag) -{ - aes_init(context->input_key, AES_192, context->iv, IV_LEN_96, context->gcm_aad, - AES_GCM, AES_HARD_ENCRYPTION, context->gcm_aad_len, input_len); - - sysctl_dma_select(dma_receive_channel_num, SYSCTL_DMA_SELECT_AES_REQ); - aes->dma_sel = 1; - dmac_set_single_mode(dma_receive_channel_num, (void *)(&aes->aes_out_data), output_data, DMAC_ADDR_NOCHANGE, DMAC_ADDR_INCREMENT, - DMAC_MSIZE_4, DMAC_TRANS_WIDTH_32, (input_len + 3) >> 2); - aes_input_bytes(input_data, input_len, AES_GCM); - dmac_wait_done(dma_receive_channel_num); - - gcm_get_tag(gcm_tag); -} - -void aes_gcm256_hard_decrypt_dma(dmac_channel_number_t dma_receive_channel_num, - gcm_context_t *context, - uint8_t *input_data, - size_t input_len, - uint8_t *output_data, - uint8_t *gcm_tag) -{ - aes_init(context->input_key, AES_256, context->iv, IV_LEN_96, context->gcm_aad, - AES_GCM, AES_HARD_DECRYPTION, context->gcm_aad_len, input_len); - - sysctl_dma_select(dma_receive_channel_num, SYSCTL_DMA_SELECT_AES_REQ); - aes->dma_sel = 1; - dmac_set_single_mode(dma_receive_channel_num, (void *)(&aes->aes_out_data), output_data, DMAC_ADDR_NOCHANGE, DMAC_ADDR_INCREMENT, - DMAC_MSIZE_4, DMAC_TRANS_WIDTH_32, (input_len + 3) >> 2); - aes_input_bytes(input_data, input_len, AES_GCM); - dmac_wait_done(dma_receive_channel_num); - - gcm_get_tag(gcm_tag); -} - -void aes_gcm256_hard_encrypt_dma(dmac_channel_number_t dma_receive_channel_num, - gcm_context_t *context, - uint8_t *input_data, - size_t input_len, - uint8_t *output_data, - uint8_t *gcm_tag) -{ - aes_init(context->input_key, AES_256, context->iv, IV_LEN_96, context->gcm_aad, - AES_GCM, AES_HARD_ENCRYPTION, context->gcm_aad_len, input_len); - - sysctl_dma_select(dma_receive_channel_num, SYSCTL_DMA_SELECT_AES_REQ); - aes->dma_sel = 1; - dmac_set_single_mode(dma_receive_channel_num, (void *)(&aes->aes_out_data), output_data, DMAC_ADDR_NOCHANGE, DMAC_ADDR_INCREMENT, - DMAC_MSIZE_4, DMAC_TRANS_WIDTH_32, (input_len + 3) >> 2); - aes_input_bytes(input_data, input_len, AES_GCM); - dmac_wait_done(dma_receive_channel_num); - - gcm_get_tag(gcm_tag); -} - diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/apu.c b/cores/arduino/kendryte-standalone-sdk/lib/drivers/apu.c deleted file mode 100644 index 17f662d..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/apu.c +++ /dev/null @@ -1,513 +0,0 @@ -#include -#include -#include -#include "syscalls.h" -#include "sysctl.h" -#include "apu.h" - -#define BEAFORMING_BASE_ADDR (0x50250200) -#ifndef M_PI -#define M_PI 3.14159265358979323846264338327950288 -#endif - -volatile apu_reg_t *const apu = (volatile apu_reg_t *)BEAFORMING_BASE_ADDR; - -/* -Voice strength average value right shift factor. When performing sound direction detect, -the average value of samples from different channels is required, this right shift factor -is used to perform division. -0x0: no right shift; 0x1: right shift by 1-bit; - . . . . . . -0xF: right shift by 14-bit. -*/ -void apu_set_audio_gain(uint16_t gain) -{ - apu_ch_cfg_t ch_cfg = apu->bf_ch_cfg_reg; - - ch_cfg.we_bf_target_dir = 0; - ch_cfg.we_bf_sound_ch_en = 0; - ch_cfg.we_data_src_mode = 0; - ch_cfg.we_audio_gain = 1; - ch_cfg.audio_gain = gain; - apu->bf_ch_cfg_reg = ch_cfg; -} - -/*set sampling shift*/ -void apu_set_smpl_shift(uint8_t smpl_shift) -{ - apu_dwsz_cfg_t tmp = apu->bf_dwsz_cfg_reg; - - tmp.smpl_shift_bits = smpl_shift; - apu->bf_dwsz_cfg_reg = tmp; -} -/*get sampling shift*/ -uint8_t apu_get_smpl_shift(void) -{ - apu_dwsz_cfg_t tmp = apu->bf_dwsz_cfg_reg; - - return tmp.smpl_shift_bits; -} - -/* - * BF unit sound channel enable control bits. Bit 'x' corresponds to enable bit for sound - * channel 'x' (x = 0, 1, 2, . . ., 7). BF sound channels are related with I2S host RX channels. - * BF sound channel 0/1 correspond to the left/right channel of I2S RX0; BF channel 2/3 correspond - * to left/right channels of I2S RX1; and things like that. Software write '1' to enable a sound - * channel and hardware automatically clear the bit after the sample buffers used for direction - * searching is filled full. - * 0x1: writing '1' to enable the corresponding BF sound channel. - */ -void apu_set_channel_enabled(uint8_t channel_bit) -{ - apu_ch_cfg_t ch_cfg; - - ch_cfg.we_audio_gain = 0; - ch_cfg.we_bf_target_dir = 0; - ch_cfg.we_bf_sound_ch_en = 1; - ch_cfg.bf_sound_ch_en = channel_bit; - apu->bf_ch_cfg_reg = ch_cfg; -} - -/* - * BF unit sound channel enable control bits. Bit 'x' corresponds to enable bit for sound - * channel 'x' (x = 0, 1, 2, . . ., 7). BF sound channels are related with I2S host RX channels. - * BF sound channel 0/1 correspond to the left/right channel of I2S RX0; BF channel 2/3 correspond - * to left/right channels of I2S RX1; and things like that. Software write '1' to enable a sound - * channel and hardware automatically clear the bit after the sample buffers used for direction - * searching is filled full. - * 0x1: writing '1' to enable the corresponding BF sound channel. - */ -void apu_channel_enable(uint8_t channel_bit) -{ - apu_ch_cfg_t ch_cfg = apu->bf_ch_cfg_reg; - - ch_cfg.we_audio_gain = 0; - ch_cfg.we_bf_target_dir = 0; - ch_cfg.we_data_src_mode = 0; - ch_cfg.we_bf_sound_ch_en = 1; - ch_cfg.bf_sound_ch_en = channel_bit; - apu->bf_ch_cfg_reg = ch_cfg; -} - -/* - * audio data source configure parameter. This parameter controls where the audio data source comes from. - * 0x0: audio data directly sourcing from apu internal buffer; - * 0x1: audio data sourcing from FFT result buffer. - */ -void apu_set_src_mode(uint8_t src_mode) -{ - apu_ch_cfg_t ch_cfg = apu->bf_ch_cfg_reg; - - ch_cfg.we_audio_gain = 0; - ch_cfg.we_bf_target_dir = 0; - ch_cfg.we_bf_sound_ch_en = 0; - ch_cfg.we_data_src_mode = 1; - ch_cfg.data_src_mode = src_mode; - apu->bf_ch_cfg_reg = ch_cfg; -} - -/* - * I2S host beam-forming direction sample ibuffer read index configure register - */ -void apu_set_direction_delay(uint8_t dir_num, uint8_t *dir_bidx) -{ - apu->bf_dir_bidx[dir_num][0] =(apu_dir_bidx_t) - { - .dir_rd_idx0 = dir_bidx[0], - .dir_rd_idx1 = dir_bidx[1], - .dir_rd_idx2 = dir_bidx[2], - .dir_rd_idx3 = dir_bidx[3] - }; - apu->bf_dir_bidx[dir_num][1] =(apu_dir_bidx_t) - { - .dir_rd_idx0 = dir_bidx[4], - .dir_rd_idx1 = dir_bidx[5], - .dir_rd_idx2 = dir_bidx[6], - .dir_rd_idx3 = dir_bidx[7] - }; -} - -/* - * radius mic_num_a_circle: the num of mic per circle; center: 0: no center mic, 1:have center mic - */ -void apu_set_delay(float radius, uint8_t mic_num_a_circle, uint8_t center) -{ - uint8_t offsets[16][8]; - int i,j; - float seta[8], delay[8], hudu_jiao; - float cm_tick = (float)SOUND_SPEED * 100 / I2S_FS;/*distance per tick (cm)*/ - float min; - - for (i = 0; i < mic_num_a_circle; ++i) - { - seta[i] = 360 * i / mic_num_a_circle; - hudu_jiao = 2 * M_PI * seta[i] / 360; - delay[i] = radius * (1 - cos(hudu_jiao)) / cm_tick; - } - if(center) - delay[mic_num_a_circle] = radius / cm_tick; - - for (i = 0; i < mic_num_a_circle + center; ++i) - { - offsets[0][i] = (int)(delay[i] + 0.5); - } - for(; i < 8; i++) - offsets[0][i] = 0; - - - for (j = 1; j < DIRECTION_RES; ++j) - { - for (i = 0; i < mic_num_a_circle; ++i) - { - seta[i] -= 360 / DIRECTION_RES; - hudu_jiao = 2 * M_PI * seta[i] / 360; - delay[i] = radius * (1 - cos(hudu_jiao)) / cm_tick; - } - if(center) - delay[mic_num_a_circle] = radius / cm_tick; - - min = 2 * radius; - for (i = 0; i < mic_num_a_circle; ++i) - { - if(delay[i] < min) - min = delay[i]; - } - if(min) - { - for (i = 0; i < mic_num_a_circle + center; ++i) - { - delay[i] = delay[i] - min; - } - } - - for (i = 0; i < mic_num_a_circle + center; ++i) - { - offsets[j][i] = (int)(delay[i] + 0.5); - } - for(; i < 8; i++) - offsets[0][i] = 0; - } - for (size_t i = 0; i < DIRECTION_RES; i++) - { - apu_set_direction_delay(i, offsets[i]); - } -} - -/* - Sound direction searching enable bit. Software writes '1' to start sound direction searching function. - When all the sound sample buffers are filled full, this bit is cleared by hardware (this sample buffers - are used for direction detect only). - 0x1: enable direction searching. - */ -void apu_dir_enable(void) -{ - apu_ctl_t bf_en_tmp = apu->bf_ctl_reg; - - bf_en_tmp.we_bf_dir_search_en = 1; - bf_en_tmp.bf_dir_search_en = 1; - apu->bf_ctl_reg = bf_en_tmp; -} - -void apu_dir_reset(void) -{ - apu_ctl_t bf_en_tmp = apu->bf_ctl_reg; - - bf_en_tmp.we_search_path_rst = 1; - bf_en_tmp.search_path_reset = 1; - apu->bf_ctl_reg = bf_en_tmp; -} - -/* - Valid voice sample stream generation enable bit. After sound direction searching is done, software can - configure this bit to generate a stream of voice samples for voice recognition. - 0x1: enable output of voice sample stream. - 0x0: stop the voice samlpe stream output. - */ -void apu_voc_enable(uint8_t enable_flag) -{ - apu_ctl_t bf_en_tmp = apu->bf_ctl_reg; - - bf_en_tmp.we_bf_stream_gen = 1; - bf_en_tmp.bf_stream_gen_en = enable_flag; - apu->bf_ctl_reg = bf_en_tmp; -} - -void apu_voc_reset(void) -{ - apu_ctl_t bf_en_tmp = apu->bf_ctl_reg; - - bf_en_tmp.we_voice_gen_path_rst = 1; - bf_en_tmp.voice_gen_path_reset = 1; - apu->bf_ctl_reg = bf_en_tmp; -} - -/* -Target direction select for valid voice output. When the source voice direaction searching -is done, software can use this field to select one from 16 sound directions for the following -voice recognition -0x0: select sound direction 0; 0x1: select sound direction 1; - . . . . . . -0xF: select sound direction 15. -*/ -void apu_voc_set_direction(en_bf_dir_t direction) -{ - apu_ch_cfg_t ch_cfg = apu->bf_ch_cfg_reg; - - ch_cfg.we_bf_sound_ch_en = 0; - ch_cfg.we_audio_gain = 0; - ch_cfg.we_data_src_mode = 0; - ch_cfg.we_bf_target_dir = 1; - ch_cfg.bf_target_dir = direction; - apu->bf_ch_cfg_reg = ch_cfg; - - apu_ctl_t bf_en_tmp = apu->bf_ctl_reg; - - bf_en_tmp.we_update_voice_dir = 1; - bf_en_tmp.update_voice_dir = 1; - apu->bf_ctl_reg = bf_en_tmp; -} - - -/* - *I2S host beam-forming Filter FIR16 Coefficient Register - */ -void apu_dir_set_prev_fir(uint16_t *fir_coef) -{ - uint8_t i = 0; - - for (i = 0; i < 9; i++) { - apu->bf_pre_fir0_coef[i] = - (apu_fir_coef_t){ - .fir_tap0 = fir_coef[i * 2], - .fir_tap1 = i == 8 ? 0 : fir_coef[i * 2 + 1] - }; - } -} -void apu_dir_set_post_fir(uint16_t *fir_coef) -{ - uint8_t i = 0; - - for (i = 0; i < 9; i++) { - apu->bf_post_fir0_coef[i] = - (apu_fir_coef_t){ - .fir_tap0 = fir_coef[i * 2], - .fir_tap1 = i == 8 ? 0 : fir_coef[i * 2 + 1] - }; - } -} -void apu_voc_set_prev_fir(uint16_t *fir_coef) -{ - uint8_t i = 0; - - for (i = 0; i < 9; i++) { - apu->bf_pre_fir1_coef[i] = - (apu_fir_coef_t){ - .fir_tap0 = fir_coef[i * 2], - .fir_tap1 = i == 8 ? 0 : fir_coef[i * 2 + 1] - }; - } -} -void apu_voc_set_post_fir(uint16_t *fir_coef) -{ - uint8_t i = 0; - - for (i = 0; i < 9; i++) { - apu->bf_post_fir1_coef[i] = - (apu_fir_coef_t){ - .fir_tap0 = fir_coef[i * 2], - .fir_tap1 = i == 8 ? 0 : fir_coef[i * 2 + 1] - }; - } -} - -void apu_set_fft_shift_factor(uint8_t enable_flag, uint16_t shift_factor) -{ - apu->bf_fft_cfg_reg = - (apu_fft_cfg_t){ - .fft_enable = enable_flag, - .fft_shift_factor = shift_factor - }; - - apu_ch_cfg_t ch_cfg = apu->bf_ch_cfg_reg; - - ch_cfg.we_data_src_mode = 1; - ch_cfg.data_src_mode = enable_flag; - apu->bf_ch_cfg_reg = ch_cfg; -} - -void apu_dir_set_down_size(uint8_t dir_dwn_size) -{ - apu_dwsz_cfg_t tmp = apu->bf_dwsz_cfg_reg; - - tmp.dir_dwn_siz_rate = dir_dwn_size; - apu->bf_dwsz_cfg_reg = tmp; -} - -void apu_dir_set_interrupt_mask(uint8_t dir_int_mask) -{ - apu_int_mask_t tmp = apu->bf_int_mask_reg; - - tmp.dir_data_rdy_msk = dir_int_mask; - apu->bf_int_mask_reg = tmp; -} - -void apu_voc_set_down_size(uint8_t voc_dwn_size) -{ - apu_dwsz_cfg_t tmp = apu->bf_dwsz_cfg_reg; - - tmp.voc_dwn_siz_rate = voc_dwn_size; - apu->bf_dwsz_cfg_reg = tmp; -} - -void apu_voc_set_interrupt_mask(uint8_t voc_int_mask) -{ - apu_int_mask_t tmp = apu->bf_int_mask_reg; - - tmp.voc_buf_rdy_msk = voc_int_mask; - apu->bf_int_mask_reg = tmp; -} - - -void apu_set_down_size(uint8_t dir_dwn_size, uint8_t voc_dwn_size) -{ - apu_dwsz_cfg_t tmp = apu->bf_dwsz_cfg_reg; - - tmp.dir_dwn_siz_rate = dir_dwn_size; - tmp.voc_dwn_siz_rate = voc_dwn_size; - apu->bf_dwsz_cfg_reg = tmp; -} - -void apu_set_interrupt_mask(uint8_t dir_int_mask, uint8_t voc_int_mask) -{ - apu->bf_int_mask_reg = - (apu_int_mask_t){ - .dir_data_rdy_msk = dir_int_mask, - .voc_buf_rdy_msk = voc_int_mask - }; -} - -void apu_dir_clear_int_state(void) -{ - apu->bf_int_stat_reg = - (apu_int_stat_t){ - .dir_search_data_rdy = 1 - }; -} - -void apu_voc_clear_int_state(void) -{ - apu->bf_int_stat_reg = - (apu_int_stat_t){ - .voc_buf_data_rdy = 1 - }; -} - -/* reset saturation_counter */ -void apu_voc_reset_saturation_counter(void) -{ - apu->saturation_counter = 1<<31; -} - -/*get saturation counter*/ -/*heigh 16 bit is counter, low 16 bit is total.*/ -uint32_t apu_voc_get_saturation_counter(void) -{ - return apu->saturation_counter; -} - -/*set saturation limit*/ -void apu_voc_set_saturation_limit(uint16_t upper, uint16_t bottom) -{ - apu->saturation_limits = (uint32_t)bottom<<16 | upper; -} - -/*get saturation limit*/ -/*heigh 16 bit is counter, low 16 bit is total.*/ -uint32_t apu_voc_get_saturation_limit(void) -{ - return apu->saturation_limits; -} - -static void print_fir(const char *member_name, volatile apu_fir_coef_t *pfir) -{ - printf(" for(int i = 0; i < 9; i++){\n"); - for (int i = 0; i < 9; i++) { - apu_fir_coef_t fir = pfir[i]; - - printf(" apu->%s[%d] = (apu_fir_coef_t){\n", member_name, i); - printf(" .fir_tap0 = 0x%x,\n", fir.fir_tap0); - printf(" .fir_tap1 = 0x%x\n", fir.fir_tap1); - printf(" };\n"); - } - printf(" }\n"); -} - -void apu_print_setting(void) -{ - printf("void apu_setting(void) {\n"); - apu_ch_cfg_t bf_ch_cfg_reg = apu->bf_ch_cfg_reg; - - printf(" apu->bf_ch_cfg_reg = (apu_ch_cfg_t){\n"); - printf(" .we_audio_gain = 1, .we_bf_target_dir = 1, .we_bf_sound_ch_en = 1,\n"); - printf(" .audio_gain = 0x%x, .bf_target_dir = %d, .bf_sound_ch_en = %d, .data_src_mode = %d\n", - bf_ch_cfg_reg.audio_gain, bf_ch_cfg_reg.bf_target_dir, bf_ch_cfg_reg.bf_sound_ch_en, bf_ch_cfg_reg.data_src_mode); - printf(" };\n"); - - apu_ctl_t bf_ctl_reg = apu->bf_ctl_reg; - - printf(" apu->bf_ctl_reg = (apu_ctl_t){\n"); - printf(" .we_bf_stream_gen = 1, .we_bf_dir_search_en = 1,\n"); - printf(" .bf_stream_gen_en = %d, .bf_dir_search_en = %d\n", - bf_ctl_reg.bf_stream_gen_en, bf_ctl_reg.bf_dir_search_en); - printf(" };\n"); - - printf(" for(int i = 0; i < 16; i++){\n"); - for (int i = 0; i < 16; i++) { - apu_dir_bidx_t bidx0 = apu->bf_dir_bidx[i][0]; - apu_dir_bidx_t bidx1 = apu->bf_dir_bidx[i][1]; - - printf(" apu->bf_dir_bidx[%d][0] = (apu_dir_bidx_t){\n", i); - printf(" .dir_rd_idx0 = 0x%x,\n", bidx0.dir_rd_idx0); - printf(" .dir_rd_idx1 = 0x%x,\n", bidx0.dir_rd_idx1); - printf(" .dir_rd_idx2 = 0x%x,\n", bidx0.dir_rd_idx2); - printf(" .dir_rd_idx3 = 0x%x\n", bidx0.dir_rd_idx3); - printf(" };\n"); - printf(" apu->bf_dir_bidx[%d][1] = (apu_dir_bidx_t){\n", i); - printf(" .dir_rd_idx0 = 0x%x,\n", bidx1.dir_rd_idx0); - printf(" .dir_rd_idx1 = 0x%x,\n", bidx1.dir_rd_idx1); - printf(" .dir_rd_idx2 = 0x%x,\n", bidx1.dir_rd_idx2); - printf(" .dir_rd_idx3 = 0x%x\n", bidx1.dir_rd_idx3); - printf(" };\n"); - } - printf(" }\n"); - - print_fir("bf_pre_fir0_coef", apu->bf_pre_fir0_coef); - print_fir("bf_post_fir0_coef", apu->bf_post_fir0_coef); - print_fir("bf_pre_fir1_coef", apu->bf_pre_fir1_coef); - print_fir("bf_post_fir1_coef", apu->bf_post_fir1_coef); - - - apu_dwsz_cfg_t bf_dwsz_cfg_reg = apu->bf_dwsz_cfg_reg; - - printf(" apu->bf_dwsz_cfg_reg = (apu_dwsz_cfg_t){\n"); - printf(" .dir_dwn_siz_rate = %d, .voc_dwn_siz_rate = %d\n", - bf_dwsz_cfg_reg.dir_dwn_siz_rate, bf_dwsz_cfg_reg.voc_dwn_siz_rate); - printf(" };\n"); - - apu_fft_cfg_t bf_fft_cfg_reg = apu->bf_fft_cfg_reg; - - printf(" apu->bf_fft_cfg_reg = (apu_fft_cfg_t){\n"); - printf(" .fft_enable = %d, .fft_shift_factor = 0x%x\n", - bf_fft_cfg_reg.fft_enable, bf_fft_cfg_reg.fft_shift_factor); - printf(" };\n"); - - apu_int_mask_t bf_int_mask_reg = apu->bf_int_mask_reg; - - printf(" apu->bf_int_mask_reg = (apu_int_mask_t){\n"); - printf(" .dir_data_rdy_msk = %d, .voc_buf_rdy_msk = %d\n", - bf_int_mask_reg.dir_data_rdy_msk, bf_int_mask_reg.voc_buf_rdy_msk); - printf(" };\n"); - - printf("}\n"); -} - diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/clint.c b/cores/arduino/kendryte-standalone-sdk/lib/drivers/clint.c deleted file mode 100644 index e29a1cb..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/clint.c +++ /dev/null @@ -1,219 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include -#include -#include "encoding.h" -#include "clint.h" -#include "sysctl.h" - -volatile clint_t* const clint = (volatile clint_t*)CLINT_BASE_ADDR; -static clint_timer_instance_t clint_timer_instance[CLINT_NUM_CORES]; -static clint_ipi_instance_t clint_ipi_instance[CLINT_NUM_CORES]; - -uint64_t clint_get_time(void) -{ - /* No difference on cores */ - return clint->mtime; -} - -int clint_timer_init(void) -{ - /* Read core id */ - unsigned long core_id = current_coreid(); - /* Clear the Machine-Timer bit in MIE */ - clear_csr(mie, MIP_MTIP); - /* Fill core's instance with original data */ - - /* clang-format off */ - clint_timer_instance[core_id] = (const clint_timer_instance_t) - { - .interval = 0, - .cycles = 0, - .single_shot = 0, - .callback = NULL, - .ctx = NULL, - }; - /* clang-format on */ - - return 0; -} - -int clint_timer_stop(void) -{ - /* Clear the Machine-Timer bit in MIE */ - clear_csr(mie, MIP_MTIP); - return 0; -} - -uint64_t clint_timer_get_freq(void) -{ - /* The clock is divided by CLINT_CLOCK_DIV */ - return sysctl_clock_get_freq(SYSCTL_CLOCK_CPU) / CLINT_CLOCK_DIV; -} - -int clint_timer_start(uint64_t interval, int single_shot) -{ - /* Read core id */ - unsigned long core_id = current_coreid(); - /* Set timer interval */ - if (clint_timer_set_interval(interval) != 0) - return -1; - /* Set timer single shot */ - if (clint_timer_set_single_shot(single_shot) != 0) - return -1; - /* Check settings to prevent interval is 0 */ - if (clint_timer_instance[core_id].interval == 0) - return -1; - /* Check settings to prevent cycles is 0 */ - if (clint_timer_instance[core_id].cycles == 0) - return -1; - /* Add cycle interval to mtimecmp */ - uint64_t now = clint->mtime; - uint64_t then = now + clint_timer_instance[core_id].cycles; - /* Set mtimecmp by core id */ - clint->mtimecmp[core_id] = then; - /* Enable interrupts in general */ - set_csr(mstatus, MSTATUS_MIE); - /* Enable the Machine-Timer bit in MIE */ - set_csr(mie, MIP_MTIP); - return 0; -} - -uint64_t clint_timer_get_interval(void) -{ - /* Read core id */ - unsigned long core_id = current_coreid(); - return clint_timer_instance[core_id].interval; -} - -int clint_timer_set_interval(uint64_t interval) -{ - /* Read core id */ - unsigned long core_id = current_coreid(); - /* Check parameter */ - if (interval == 0) - return -1; - - /* Assign user interval with Millisecond(ms) */ - clint_timer_instance[core_id].interval = interval; - /* Convert interval to cycles */ - clint_timer_instance[core_id].cycles = interval * clint_timer_get_freq() / 1000ULL; - return 0; -} - -int clint_timer_get_single_shot(void) -{ - /* Read core id */ - unsigned long core_id = current_coreid(); - /* Get single shot mode by core id */ - return clint_timer_instance[core_id].single_shot; -} - -int clint_timer_set_single_shot(int single_shot) -{ - /* Read core id */ - unsigned long core_id = current_coreid(); - /* Set single shot mode by core id */ - clint_timer_instance[core_id].single_shot = single_shot; - return 0; -} - -int clint_timer_register(clint_timer_callback_t callback, void *ctx) -{ - /* Read core id */ - unsigned long core_id = current_coreid(); - /* Set user callback function */ - clint_timer_instance[core_id].callback = callback; - /* Assign user context */ - clint_timer_instance[core_id].ctx = ctx; - return 0; -} - -int clint_timer_unregister(void) -{ - /* Just assign NULL to user callback function and context */ - return clint_timer_register(NULL, NULL); -} - -int clint_ipi_init(void) -{ - /* Read core id */ - unsigned long core_id = current_coreid(); - /* Clear the Machine-Software bit in MIE */ - clear_csr(mie, MIP_MSIP); - /* Fill core's instance with original data */ - /* clang-format off */ - clint_ipi_instance[core_id] = (const clint_ipi_instance_t){ - .callback = NULL, - .ctx = NULL, - }; - /* clang-format on */ - - return 0; -} - -int clint_ipi_enable(void) -{ - /* Enable interrupts in general */ - set_csr(mstatus, MSTATUS_MIE); - /* Set the Machine-Software bit in MIE */ - set_csr(mie, MIP_MSIP); - return 0; -} - -int clint_ipi_disable(void) -{ - /* Clear the Machine-Software bit in MIE */ - clear_csr(mie, MIP_MSIP); - return 0; -} - -int clint_ipi_send(size_t core_id) -{ - if (core_id >= CLINT_NUM_CORES) - return -1; - clint->msip[core_id].msip = 1; - return 0; -} - -int clint_ipi_clear(size_t core_id) -{ - if (core_id >= CLINT_NUM_CORES) - return -1; - if (clint->msip[core_id].msip) - { - clint->msip[core_id].msip = 0; - return 1; - } - return 0; -} - -int clint_ipi_register(clint_ipi_callback_t callback, void *ctx) -{ - /* Read core id */ - unsigned long core_id = current_coreid(); - /* Set user callback function */ - clint_ipi_instance[core_id].callback = callback; - /* Assign user context */ - clint_ipi_instance[core_id].ctx = ctx; - return 0; -} - -int clint_ipi_unregister(void) -{ - /* Just assign NULL to user callback function and context */ - return clint_ipi_register(NULL, NULL); -} - diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/dmac.c b/cores/arduino/kendryte-standalone-sdk/lib/drivers/dmac.c deleted file mode 100644 index 6288c92..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/dmac.c +++ /dev/null @@ -1,792 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include -#include -#include -#include "dmac.h" -#include "sysctl.h" -#include "fpioa.h" -#include "utils.h" -#include "plic.h" -#include "stdlib.h" - -volatile dmac_t *const dmac = (dmac_t *)DMAC_BASE_ADDR; - -typedef struct _dmac_context -{ - dmac_channel_number_t dmac_channel; - plic_irq_callback_t callback; - void *ctx; -} dmac_context_t; - -dmac_context_t dmac_context[6]; - -static int is_memory(uintptr_t address) -{ - enum { - mem_len = 6 * 1024 * 1024, - mem_no_cache_len = 8 * 1024 * 1024, - }; - return ((address >= 0x80000000) && (address < 0x80000000 + mem_len)) || ((address >= 0x40000000) && (address < 0x40000000 + mem_no_cache_len)) || (address == 0x50450040); -} - -uint64_t dmac_read_id(void) -{ - return dmac->id; -} - -uint64_t dmac_read_version(void) -{ - return dmac->compver; -} - -uint64_t dmac_read_channel_id(dmac_channel_number_t channel_num) -{ - return dmac->channel[channel_num].axi_id; -} - -static void dmac_enable(void) -{ - dmac_cfg_u_t dmac_cfg; - - dmac_cfg.data = readq(&dmac->cfg); - dmac_cfg.cfg.dmac_en = 1; - dmac_cfg.cfg.int_en = 1; - writeq(dmac_cfg.data, &dmac->cfg); -} - -void dmac_disable(void) -{ - dmac_cfg_u_t dmac_cfg; - - dmac_cfg.data = readq(&dmac->cfg); - dmac_cfg.cfg.dmac_en = 0; - dmac_cfg.cfg.int_en = 0; - writeq(dmac_cfg.data, &dmac->cfg); -} - -void src_transaction_complete_int_enable(dmac_channel_number_t channel_num) -{ - dmac_ch_intstatus_enable_u_t ch_intstat; - - ch_intstat.data = readq(&dmac->channel[channel_num].intstatus_en); - ch_intstat.ch_intstatus_enable.enable_src_transcomp_intstat = 1; - - writeq(ch_intstat.data, &dmac->channel[channel_num].intstatus_en); -} - -void dmac_channel_enable(dmac_channel_number_t channel_num) -{ - dmac_chen_u_t chen; - - chen.data = readq(&dmac->chen); - - switch (channel_num) { - case DMAC_CHANNEL0: - chen.dmac_chen.ch1_en = 1; - chen.dmac_chen.ch1_en_we = 1; - break; - case DMAC_CHANNEL1: - chen.dmac_chen.ch2_en = 1; - chen.dmac_chen.ch2_en_we = 1; - break; - case DMAC_CHANNEL2: - chen.dmac_chen.ch3_en = 1; - chen.dmac_chen.ch3_en_we = 1; - break; - case DMAC_CHANNEL3: - chen.dmac_chen.ch4_en = 1; - chen.dmac_chen.ch4_en_we = 1; - break; - case DMAC_CHANNEL4: - chen.dmac_chen.ch5_en = 1; - chen.dmac_chen.ch5_en_we = 1; - break; - case DMAC_CHANNEL5: - chen.dmac_chen.ch6_en = 1; - chen.dmac_chen.ch6_en_we = 1; - break; - default: - break; - } - - writeq(chen.data, &dmac->chen); -} - -void dmac_channel_disable(dmac_channel_number_t channel_num) -{ - dmac_chen_u_t chen; - - chen.data = readq(&dmac->chen); - - switch (channel_num) - { - case DMAC_CHANNEL0: - chen.dmac_chen.ch1_en = 0; - chen.dmac_chen.ch1_en_we = 1; - break; - case DMAC_CHANNEL1: - chen.dmac_chen.ch2_en = 0; - chen.dmac_chen.ch2_en_we = 1; - break; - case DMAC_CHANNEL2: - chen.dmac_chen.ch3_en = 0; - chen.dmac_chen.ch3_en_we = 1; - break; - case DMAC_CHANNEL3: - chen.dmac_chen.ch4_en = 0; - chen.dmac_chen.ch4_en_we = 1; - break; - case DMAC_CHANNEL4: - chen.dmac_chen.ch5_en = 0; - chen.dmac_chen.ch5_en_we = 1; - break; - case DMAC_CHANNEL5: - chen.dmac_chen.ch6_en = 0; - chen.dmac_chen.ch6_en_we = 1; - break; - default: - break; - } - - writeq(chen.data, &dmac->chen); -} - -int32_t dmac_check_channel_busy(dmac_channel_number_t channel_num) -{ - int32_t ret = 0; - dmac_chen_u_t chen_u; - - chen_u.data = readq(&dmac->chen); - switch (channel_num) { - case DMAC_CHANNEL0: - if (chen_u.dmac_chen.ch1_en == 1) - ret = 1; - break; - case DMAC_CHANNEL1: - if (chen_u.dmac_chen.ch2_en == 1) - ret = 1; - break; - case DMAC_CHANNEL2: - if (chen_u.dmac_chen.ch3_en == 1) - ret = 1; - break; - case DMAC_CHANNEL3: - if (chen_u.dmac_chen.ch4_en == 1) - ret = 1; - break; - case DMAC_CHANNEL4: - if (chen_u.dmac_chen.ch5_en == 1) - ret = 1; - break; - case DMAC_CHANNEL5: - if (chen_u.dmac_chen.ch6_en == 1) - ret = 1; - break; - default: - break; - } - - writeq(chen_u.data, &dmac->chen); - - return ret; -} - -int32_t dmac_set_list_master_select(dmac_channel_number_t channel_num, - dmac_src_dst_select_t sd_sel, dmac_master_number_t mst_num) -{ - int32_t ret = 0; - uint64_t tmp = 0; - dmac_ch_ctl_u_t ctl; - - ctl.data = readq(&dmac->channel[channel_num].ctl); - ret = dmac_check_channel_busy(channel_num); - if (ret == 0) { - if (sd_sel == DMAC_SRC || sd_sel == DMAC_SRC_DST) - ctl.ch_ctl.sms = mst_num; - - if (sd_sel == DMAC_DST || sd_sel == DMAC_SRC_DST) - ctl.ch_ctl.dms = mst_num; - tmp |= *(uint64_t *)&dmac->channel[channel_num].ctl; - writeq(ctl.data, &dmac->channel[channel_num].ctl); - } - - return ret; -} - -void dmac_enable_common_interrupt_status(void) -{ - dmac_commonreg_intstatus_enable_u_t intstatus; - - intstatus.data = readq(&dmac->com_intstatus_en); - intstatus.intstatus_enable.enable_slvif_dec_err_intstat = 1; - intstatus.intstatus_enable.enable_slvif_wr2ro_err_intstat = 1; - intstatus.intstatus_enable.enable_slvif_rd2wo_err_intstat = 1; - intstatus.intstatus_enable.enable_slvif_wronhold_err_intstat = 1; - intstatus.intstatus_enable.enable_slvif_undefinedreg_dec_err_intstat = 1; - - writeq(intstatus.data, &dmac->com_intstatus_en); -} - -void dmac_enable_common_interrupt_signal(void) -{ - dmac_commonreg_intsignal_enable_u_t intsignal; - - intsignal.data = readq(&dmac->com_intsignal_en); - intsignal.intsignal_enable.enable_slvif_dec_err_intsignal = 1; - intsignal.intsignal_enable.enable_slvif_wr2ro_err_intsignal = 1; - intsignal.intsignal_enable.enable_slvif_rd2wo_err_intsignal = 1; - intsignal.intsignal_enable.enable_slvif_wronhold_err_intsignal = 1; - intsignal.intsignal_enable.enable_slvif_undefinedreg_dec_err_intsignal = 1; - - writeq(intsignal.data, &dmac->com_intsignal_en); -} - -static void dmac_enable_channel_interrupt(dmac_channel_number_t channel_num) -{ - writeq(0xffffffff, &dmac->channel[channel_num].intclear); - writeq(0x2, &dmac->channel[channel_num].intstatus_en); -} - -void dmac_disable_channel_interrupt(dmac_channel_number_t channel_num) -{ - writeq(0, &dmac->channel[channel_num].intstatus_en); -} - -static void dmac_chanel_interrupt_clear(dmac_channel_number_t channel_num) -{ - writeq(0xffffffff, &dmac->channel[channel_num].intclear); -} - -int dmac_set_channel_config(dmac_channel_number_t channel_num, - dmac_channel_config_t *cfg_param) -{ - dmac_ch_ctl_u_t ctl; - dmac_ch_cfg_u_t cfg; - dmac_ch_llp_u_t ch_llp; - - if (cfg_param->ctl_sms > DMAC_MASTER2) - return -1; - if (cfg_param->ctl_dms > DMAC_MASTER2) - return -1; - if (cfg_param->ctl_src_msize > DMAC_MSIZE_256) - return -1; - if (cfg_param->ctl_drc_msize > DMAC_MSIZE_256) - return -1; - - /** - * cfg register must configure before ts_block and - * sar dar register - */ - cfg.data = readq(&dmac->channel[channel_num].cfg); - - cfg.ch_cfg.hs_sel_src = cfg_param->cfg_hs_sel_src; - cfg.ch_cfg.hs_sel_dst = cfg_param->cfg_hs_sel_dst; - cfg.ch_cfg.src_hwhs_pol = cfg_param->cfg_src_hs_pol; - cfg.ch_cfg.dst_hwhs_pol = cfg_param->cfg_dst_hs_pol; - cfg.ch_cfg.src_per = cfg_param->cfg_src_per; - cfg.ch_cfg.dst_per = cfg_param->cfg_dst_per; - cfg.ch_cfg.ch_prior = cfg_param->cfg_ch_prior; - cfg.ch_cfg.tt_fc = cfg_param->ctl_tt_fc; - - cfg.ch_cfg.src_multblk_type = cfg_param->cfg_src_multblk_type; - cfg.ch_cfg.dst_multblk_type = cfg_param->cfg_dst_multblk_type; - - writeq(cfg.data, &dmac->channel[channel_num].cfg); - - ctl.data = readq(&dmac->channel[channel_num].ctl); - ctl.ch_ctl.sms = cfg_param->ctl_sms; - ctl.ch_ctl.dms = cfg_param->ctl_dms; - /* master select */ - ctl.ch_ctl.sinc = cfg_param->ctl_sinc; - ctl.ch_ctl.dinc = cfg_param->ctl_dinc; - /* address incrememt */ - ctl.ch_ctl.src_tr_width = cfg_param->ctl_src_tr_width; - ctl.ch_ctl.dst_tr_width = cfg_param->ctl_dst_tr_width; - /* transfer width */ - ctl.ch_ctl.src_msize = cfg_param->ctl_src_msize; - ctl.ch_ctl.dst_msize = cfg_param->ctl_drc_msize; - /* Burst transaction length */ - ctl.ch_ctl.ioc_blktfr = cfg_param->ctl_ioc_blktfr; - /* interrupt on completion of block transfer */ - /* 0x1 enable BLOCK_TFR_DONE_IntStat field */ - - writeq(cfg_param->ctl_block_ts, &dmac->channel[channel_num].block_ts); - /* the number of (blcok_ts +1) data of width SRC_TR_WIDTF to be */ - /* transferred in a dma block transfer */ - - dmac->channel[channel_num].sar = cfg_param->sar; - dmac->channel[channel_num].dar = cfg_param->dar; - - ch_llp.data = readq(&dmac->channel[channel_num].llp); - ch_llp.llp.loc = cfg_param->llp_loc; - ch_llp.llp.lms = cfg_param->llp_lms; - writeq(ch_llp.data, &dmac->channel[channel_num].llp); - writeq(ctl.data, &dmac->channel[channel_num].ctl); - readq(&dmac->channel[channel_num].swhssrc); - - return 0; -} - -int dmac_set_channel_param(dmac_channel_number_t channel_num, - const void *src, void *dest, dmac_address_increment_t src_inc, dmac_address_increment_t dest_inc, - dmac_burst_trans_length_t dmac_burst_size, - dmac_transfer_width_t dmac_trans_width, - uint32_t blockSize) -{ - dmac_ch_ctl_u_t ctl; - dmac_ch_cfg_u_t cfg_u; - - int mem_type_src = is_memory((uintptr_t)src), mem_type_dest = is_memory((uintptr_t)dest); - dmac_transfer_flow_t flow_control; - if (mem_type_src == 0 && mem_type_dest == 0) - { - flow_control = DMAC_PRF2PRF_DMA; - }else if (mem_type_src == 1 && mem_type_dest == 0) - flow_control = DMAC_MEM2PRF_DMA; - else if (mem_type_src == 0 && mem_type_dest == 1) - flow_control = DMAC_PRF2MEM_DMA; - else - flow_control = DMAC_MEM2MEM_DMA; - - /** - * cfg register must configure before ts_block and - * sar dar register - */ - cfg_u.data = readq(&dmac->channel[channel_num].cfg); - - cfg_u.ch_cfg.tt_fc = flow_control; - cfg_u.ch_cfg.hs_sel_src = mem_type_src ? DMAC_HS_SOFTWARE : DMAC_HS_HARDWARE; - cfg_u.ch_cfg.hs_sel_dst = mem_type_dest ? DMAC_HS_SOFTWARE : DMAC_HS_HARDWARE; - cfg_u.ch_cfg.src_per = channel_num; - cfg_u.ch_cfg.dst_per = channel_num; - cfg_u.ch_cfg.src_multblk_type = 0; - cfg_u.ch_cfg.dst_multblk_type = 0; - - writeq(cfg_u.data, &dmac->channel[channel_num].cfg); - - dmac->channel[channel_num].sar = (uint64_t)src; - dmac->channel[channel_num].dar = (uint64_t)dest; - - ctl.data = readq(&dmac->channel[channel_num].ctl); - ctl.ch_ctl.sms = DMAC_MASTER1; - ctl.ch_ctl.dms = DMAC_MASTER2; - /* master select */ - ctl.ch_ctl.sinc = src_inc; - ctl.ch_ctl.dinc = dest_inc; - /* address incrememt */ - ctl.ch_ctl.src_tr_width = dmac_trans_width; - ctl.ch_ctl.dst_tr_width = dmac_trans_width; - /* transfer width */ - ctl.ch_ctl.src_msize = dmac_burst_size; - ctl.ch_ctl.dst_msize = dmac_burst_size; - - writeq(ctl.data, &dmac->channel[channel_num].ctl); - - writeq(blockSize - 1, &dmac->channel[channel_num].block_ts); - /*the number of (blcok_ts +1) data of width SRC_TR_WIDTF to be */ - /* transferred in a dma block transfer */ - return 0; -} - -int dmac_get_channel_config(dmac_channel_number_t channel_num, - dmac_channel_config_t *cfg_param) -{ - dmac_ch_ctl_u_t ctl; - dmac_ch_cfg_u_t cfg; - dmac_ch_llp_u_t ch_llp; - - if (cfg_param == 0) - return -1; - if (channel_num < DMAC_CHANNEL0 || - channel_num > DMAC_CHANNEL3) - return -1; - - ctl.data = readq(&dmac->channel[channel_num].ctl); - - cfg_param->ctl_sms = ctl.ch_ctl.sms; - cfg_param->ctl_dms = ctl.ch_ctl.dms; - cfg_param->ctl_sinc = ctl.ch_ctl.sinc; - cfg_param->ctl_dinc = ctl.ch_ctl.dinc; - cfg_param->ctl_src_tr_width = ctl.ch_ctl.src_tr_width; - cfg_param->ctl_dst_tr_width = ctl.ch_ctl.dst_tr_width; - cfg_param->ctl_src_msize = ctl.ch_ctl.src_msize; - cfg_param->ctl_drc_msize = ctl.ch_ctl.dst_msize; - cfg_param->ctl_ioc_blktfr = ctl.ch_ctl.ioc_blktfr; - - cfg.data = readq(&dmac->channel[channel_num].cfg); - cfg_param->cfg_hs_sel_src = cfg.ch_cfg.hs_sel_src; - cfg_param->cfg_hs_sel_dst = cfg.ch_cfg.hs_sel_dst; - cfg_param->cfg_src_hs_pol = cfg.ch_cfg.src_hwhs_pol; - cfg_param->cfg_dst_hs_pol = cfg.ch_cfg.dst_hwhs_pol; - cfg_param->cfg_src_per = cfg.ch_cfg.src_per; - cfg_param->cfg_dst_per = cfg.ch_cfg.dst_per; - cfg_param->cfg_ch_prior = cfg.ch_cfg.ch_prior; - cfg_param->cfg_src_multblk_type = cfg.ch_cfg.src_multblk_type; - cfg_param->cfg_dst_multblk_type = cfg.ch_cfg.dst_multblk_type; - - cfg_param->sar = dmac->channel[channel_num].sar; - cfg_param->dar = dmac->channel[channel_num].dar; - - ch_llp.data = readq(&dmac->channel[channel_num].llp); - cfg_param->llp_loc = ch_llp.llp.loc; - cfg_param->llp_lms = ch_llp.llp.lms; - - cfg_param->ctl_block_ts = readq(&dmac->channel[channel_num].block_ts); - - return 0; -} - -void dmac_set_address(dmac_channel_number_t channel_num, uint64_t src_addr, - uint64_t dst_addr) -{ - writeq(src_addr, &dmac->channel[channel_num].sar); - writeq(dst_addr, &dmac->channel[channel_num].dar); -} - -void dmac_set_block_ts(dmac_channel_number_t channel_num, - uint32_t block_size) -{ - uint32_t block_ts; - - block_ts = block_size & 0x3fffff; - writeq(block_ts, &dmac->channel[channel_num].block_ts); -} - -void dmac_source_control(dmac_channel_number_t channel_num, - dmac_master_number_t master_select, - dmac_address_increment_t address_mode, - dmac_transfer_width_t tr_width, - dmac_burst_trans_length_t burst_length) -{ - dmac_ch_ctl_u_t ctl_u; - - ctl_u.data = readq(&dmac->channel[channel_num].ctl); - ctl_u.ch_ctl.sms = master_select; - ctl_u.ch_ctl.sinc = address_mode; - ctl_u.ch_ctl.src_tr_width = tr_width; - ctl_u.ch_ctl.src_msize = burst_length; - - writeq(ctl_u.data, &dmac->channel[channel_num].ctl); -} - -void dmac_master_control(dmac_channel_number_t channel_num, - dmac_master_number_t master_select, - dmac_address_increment_t address_mode, - dmac_transfer_width_t tr_width, - dmac_burst_trans_length_t burst_length) -{ - dmac_ch_ctl_u_t ctl_u; - - ctl_u.data = readq(&dmac->channel[channel_num].ctl); - ctl_u.ch_ctl.dms = master_select; - ctl_u.ch_ctl.dinc = address_mode; - ctl_u.ch_ctl.dst_tr_width = tr_width; - ctl_u.ch_ctl.dst_msize = burst_length; - - writeq(ctl_u.data, &dmac->channel[channel_num].ctl); -} - -void dmac_set_source_transfer_control(dmac_channel_number_t channel_num, - dmac_multiblk_transfer_type_t transfer_type, - dmac_sw_hw_hs_select_t handshak_select) -{ - dmac_ch_cfg_u_t cfg_u; - - cfg_u.data = readq(&dmac->channel[channel_num].cfg); - cfg_u.ch_cfg.src_multblk_type = transfer_type; - cfg_u.ch_cfg.hs_sel_src = handshak_select; - - writeq(cfg_u.data, &dmac->channel[channel_num].cfg); -} - -void dmac_set_destination_transfer_control(dmac_channel_number_t channel_num, - dmac_multiblk_transfer_type_t transfer_type, - dmac_sw_hw_hs_select_t handshak_select) -{ - dmac_ch_cfg_u_t cfg_u; - - cfg_u.data = readq(&dmac->channel[channel_num].cfg); - cfg_u.ch_cfg.dst_multblk_type = transfer_type; - cfg_u.ch_cfg.hs_sel_dst = handshak_select; - - writeq(cfg_u.data, &dmac->channel[channel_num].cfg); -} - -void dmac_set_flow_control(dmac_channel_number_t channel_num, - dmac_transfer_flow_t flow_control) -{ - dmac_ch_cfg_u_t cfg_u; - - cfg_u.data = readq(&dmac->channel[channel_num].cfg); - cfg_u.ch_cfg.tt_fc = flow_control; - - writeq(cfg_u.data, &dmac->channel[channel_num].cfg); -} - -void dmac_set_linked_list_addr_point(dmac_channel_number_t channel_num, - uint64_t *addr) -{ - dmac_ch_llp_u_t llp_u; - - llp_u.data = readq(&dmac->channel[channel_num].llp); - /* Cast pointer to uint64_t */ - llp_u.llp.loc = (uint64_t)addr; - writeq(llp_u.data, &dmac->channel[channel_num].llp); -} - -void dmac_init(void) -{ - uint64_t tmp; - dmac_commonreg_intclear_u_t intclear; - dmac_cfg_u_t dmac_cfg; - dmac_reset_u_t dmac_reset; - - sysctl_clock_enable(SYSCTL_CLOCK_DMA); - - dmac_reset.data = readq(&dmac->reset); - dmac_reset.reset.rst = 1; - writeq(dmac_reset.data, &dmac->reset); - while (dmac_reset.reset.rst) - dmac_reset.data = readq(&dmac->reset); - - /*reset dmac */ - - intclear.data = readq(&dmac->com_intclear); - intclear.com_intclear.cear_slvif_dec_err_intstat = 1; - intclear.com_intclear.clear_slvif_wr2ro_err_intstat = 1; - intclear.com_intclear.clear_slvif_rd2wo_err_intstat = 1; - intclear.com_intclear.clear_slvif_wronhold_err_intstat = 1; - intclear.com_intclear.clear_slvif_undefinedreg_dec_err_intstat = 1; - writeq(intclear.data, &dmac->com_intclear); - /* clear common register interrupt */ - - dmac_cfg.data = readq(&dmac->cfg); - dmac_cfg.cfg.dmac_en = 0; - dmac_cfg.cfg.int_en = 0; - writeq(dmac_cfg.data, &dmac->cfg); - /* disable dmac and disable interrupt */ - - while (readq(&dmac->cfg)) - ; - tmp = readq(&dmac->chen); - tmp &= ~0xf; - writeq(tmp, &dmac->chen); - /* disable all channel before configure */ - dmac_enable(); -} - -static void list_add(struct list_head_t *new, struct list_head_t *prev, - struct list_head_t *next) -{ - next->prev = new; - new->next = next; - new->prev = prev; - prev->next = new; -} - -void list_add_tail(struct list_head_t *new, struct list_head_t *head) -{ - list_add(new, head->prev, head); -} - -void INIT_LIST_HEAD(struct list_head_t *list) -{ - list->next = list; - list->prev = list; -} - -void dmac_link_list_item(dmac_channel_number_t channel_num, - uint8_t LLI_row_num, int8_t LLI_last_row, - dmac_lli_item_t *lli_item, - dmac_channel_config_t *cfg_param) -{ - dmac_ch_ctl_u_t ctl; - dmac_ch_llp_u_t llp_u; - - lli_item[LLI_row_num].sar = cfg_param->sar; - lli_item[LLI_row_num].dar = cfg_param->dar; - - ctl.data = readq(&dmac->channel[channel_num].ctl); - ctl.ch_ctl.sms = cfg_param->ctl_sms; - ctl.ch_ctl.dms = cfg_param->ctl_dms; - ctl.ch_ctl.sinc = cfg_param->ctl_sinc; - ctl.ch_ctl.dinc = cfg_param->ctl_dinc; - ctl.ch_ctl.src_tr_width = cfg_param->ctl_src_tr_width; - ctl.ch_ctl.dst_tr_width = cfg_param->ctl_dst_tr_width; - ctl.ch_ctl.src_msize = cfg_param->ctl_src_msize; - ctl.ch_ctl.dst_msize = cfg_param->ctl_drc_msize; - ctl.ch_ctl.src_stat_en = cfg_param->ctl_src_stat_en; - ctl.ch_ctl.dst_stat_en = cfg_param->ctl_dst_stat_en; - - if (LLI_last_row != LAST_ROW) { - ctl.ch_ctl.shadowreg_or_lli_valid = 1; - ctl.ch_ctl.shadowreg_or_lli_last = 0; - } else { - ctl.ch_ctl.shadowreg_or_lli_valid = 1; - ctl.ch_ctl.shadowreg_or_lli_last = 1; - } - - lli_item[LLI_row_num].ctl = ctl.data; - - lli_item[LLI_row_num].ch_block_ts = cfg_param->ctl_block_ts; - lli_item[LLI_row_num].sstat = 0; - lli_item[LLI_row_num].dstat = 0; - - llp_u.data = readq(&dmac->channel[channel_num].llp); - - if (LLI_last_row != LAST_ROW) - llp_u.llp.loc = ((uint64_t)&lli_item[LLI_row_num + 1]) >> 6; - else - llp_u.llp.loc = 0; - - lli_item[LLI_row_num].llp = llp_u.data; -} - -void dmac_update_shandow_register(dmac_channel_number_t channel_num, - int8_t last_block, dmac_channel_config_t *cfg_param) -{ - dmac_ch_ctl_u_t ctl_u; - - do { - ctl_u.data = readq(&dmac->channel[channel_num].ctl); - } while (ctl_u.ch_ctl.shadowreg_or_lli_valid); - - writeq(cfg_param->sar, &dmac->channel[channel_num].sar); - writeq(cfg_param->dar, &dmac->channel[channel_num].dar); - writeq(cfg_param->ctl_block_ts, &dmac->channel[channel_num].block_ts); - - ctl_u.ch_ctl.sms = cfg_param->ctl_sms; - ctl_u.ch_ctl.dms = cfg_param->ctl_dms; - ctl_u.ch_ctl.sinc = cfg_param->ctl_sinc; - ctl_u.ch_ctl.dinc = cfg_param->ctl_dinc; - ctl_u.ch_ctl.src_tr_width = cfg_param->ctl_src_tr_width; - ctl_u.ch_ctl.dst_tr_width = cfg_param->ctl_dst_tr_width; - ctl_u.ch_ctl.src_msize = cfg_param->ctl_src_msize; - ctl_u.ch_ctl.dst_msize = cfg_param->ctl_drc_msize; - ctl_u.ch_ctl.src_stat_en = cfg_param->ctl_src_stat_en; - ctl_u.ch_ctl.dst_stat_en = cfg_param->ctl_dst_stat_en; - if (last_block != LAST_ROW) - { - ctl_u.ch_ctl.shadowreg_or_lli_valid = 1; - ctl_u.ch_ctl.shadowreg_or_lli_last = 0; - } else { - ctl_u.ch_ctl.shadowreg_or_lli_valid = 1; - ctl_u.ch_ctl.shadowreg_or_lli_last = 1; - } - - writeq(ctl_u.data, &dmac->channel[channel_num].ctl); - writeq(0, &dmac->channel[channel_num].blk_tfr); -} - -void dmac_set_shadow_invalid_flag(dmac_channel_number_t channel_num) -{ - dmac_ch_ctl_u_t ctl_u; - - ctl_u.data = readq(&dmac->channel[channel_num].ctl); - ctl_u.ch_ctl.shadowreg_or_lli_valid = 1; - ctl_u.ch_ctl.shadowreg_or_lli_last = 0; - writeq(ctl_u.data, &dmac->channel[channel_num].ctl); -} - -void dmac_set_single_mode(dmac_channel_number_t channel_num, - const void *src, void *dest, dmac_address_increment_t src_inc, - dmac_address_increment_t dest_inc, - dmac_burst_trans_length_t dmac_burst_size, - dmac_transfer_width_t dmac_trans_width, - size_t block_size) { - dmac_chanel_interrupt_clear(channel_num); - dmac_channel_disable(channel_num); - dmac_wait_idle(channel_num); - dmac_set_channel_param(channel_num, src, dest, src_inc, dest_inc, - dmac_burst_size, dmac_trans_width, block_size); - dmac_enable(); - dmac_channel_enable(channel_num); -} - -int dmac_is_done(dmac_channel_number_t channel_num) -{ - if(readq(&dmac->channel[channel_num].intstatus) & 0x2) - return 1; - else - return 0; -} - -void dmac_wait_done(dmac_channel_number_t channel_num) -{ - dmac_wait_idle(channel_num); -} - -int dmac_is_idle(dmac_channel_number_t channel_num) -{ - dmac_chen_u_t chen; - chen.data = readq(&dmac->chen); - if((chen.data >> channel_num) & 0x1UL) - return 0; - else - return 1; -} - -void dmac_wait_idle(dmac_channel_number_t channel_num) -{ - while(!dmac_is_idle(channel_num)); - dmac_chanel_interrupt_clear(channel_num); /* clear interrupt */ -} - -void dmac_set_src_dest_length(dmac_channel_number_t channel_num, const void *src, void *dest, size_t len) -{ - if(src != NULL) - dmac->channel[channel_num].sar = (uint64_t)src; - if(dest != NULL) - dmac->channel[channel_num].dar = (uint64_t)dest; - if(len > 0) - dmac_set_block_ts(channel_num, len - 1); - dmac_channel_enable(channel_num); -} - -static int dmac_irq_callback(void *ctx) -{ - dmac_context_t *v_dmac_context = (dmac_context_t *)(ctx); - dmac_channel_number_t v_dmac_channel = v_dmac_context->dmac_channel; - dmac_chanel_interrupt_clear(v_dmac_channel); - if(v_dmac_context->callback != NULL) - v_dmac_context->callback(v_dmac_context->ctx); - - return 0; -} - -void dmac_irq_register(dmac_channel_number_t channel_num , plic_irq_callback_t dmac_callback, void *ctx, uint32_t priority) -{ - dmac_context[channel_num].dmac_channel = channel_num; - dmac_context[channel_num].callback = dmac_callback; - dmac_context[channel_num].ctx = ctx; - dmac_enable_channel_interrupt(channel_num); - plic_set_priority(IRQN_DMA0_INTERRUPT + channel_num, priority); - plic_irq_enable(IRQN_DMA0_INTERRUPT + channel_num); - plic_irq_register(IRQN_DMA0_INTERRUPT + channel_num, dmac_irq_callback, &dmac_context[channel_num]); -} - -void __attribute__((weak, alias("dmac_irq_register"))) dmac_set_irq(dmac_channel_number_t channel_num , plic_irq_callback_t dmac_callback, void *ctx, uint32_t priority); - -void dmac_irq_unregister(dmac_channel_number_t channel_num) -{ - dmac_context[channel_num].callback = NULL; - dmac_context[channel_num].ctx = NULL; - dmac_disable_channel_interrupt(channel_num); - plic_irq_unregister(IRQN_DMA0_INTERRUPT + channel_num); -} - -void __attribute__((weak, alias("dmac_irq_unregister"))) dmac_free_irq(dmac_channel_number_t channel_num); - diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/dvp.c b/cores/arduino/kendryte-standalone-sdk/lib/drivers/dvp.c deleted file mode 100644 index 5758bc2..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/dvp.c +++ /dev/null @@ -1,297 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include -#include -#include "dvp.h" -#include "utils.h" -#include "fpioa.h" -#include "sysctl.h" -#include - -volatile dvp_t* const dvp = (volatile dvp_t*)DVP_BASE_ADDR; -static uint8_t g_sccb_reg_len = 8; - -static void mdelay(uint32_t ms) -{ - uint32_t i; - - while (ms && ms--) - { - for (i = 0; i < 25000; i++) - __asm__ __volatile__("nop"); - } -} - -static void dvp_sccb_clk_init(void) -{ - uint32_t tmp; - - tmp = dvp->sccb_cfg & (~(DVP_SCCB_SCL_LCNT_MASK | DVP_SCCB_SCL_HCNT_MASK)); - tmp |= DVP_SCCB_SCL_LCNT(255) | DVP_SCCB_SCL_HCNT(255); - - dvp->sccb_cfg = tmp; -} - -uint32_t dvp_sccb_set_clk_rate(uint32_t clk_rate) -{ - uint32_t tmp; - uint32_t v_sccb_freq = sysctl_clock_get_freq(SYSCTL_CLOCK_APB1); - uint16_t v_period_clk_cnt = round(v_sccb_freq / clk_rate / 2.0); - if(v_period_clk_cnt > 255) - { - return 0; - } - tmp = dvp->sccb_cfg & (~(DVP_SCCB_SCL_LCNT_MASK | DVP_SCCB_SCL_HCNT_MASK)); - tmp |= DVP_SCCB_SCL_LCNT(v_period_clk_cnt) | DVP_SCCB_SCL_HCNT(v_period_clk_cnt); - dvp->sccb_cfg = tmp; - return sysctl_clock_get_freq(SYSCTL_CLOCK_DVP) / (v_period_clk_cnt * 2); -} - -static void dvp_sccb_start_transfer(void) -{ - while (dvp->sts & DVP_STS_SCCB_EN) - ; - dvp->sts = DVP_STS_SCCB_EN | DVP_STS_SCCB_EN_WE; - while (dvp->sts & DVP_STS_SCCB_EN) - ; -} - -void dvp_sccb_send_data(uint8_t dev_addr, uint16_t reg_addr, uint8_t reg_data) -{ - uint32_t tmp; - - tmp = dvp->sccb_cfg & (~DVP_SCCB_BYTE_NUM_MASK); - - (g_sccb_reg_len == 8) ? (tmp |= DVP_SCCB_BYTE_NUM_3) : (tmp |= DVP_SCCB_BYTE_NUM_4); - - dvp->sccb_cfg = tmp; - - if (g_sccb_reg_len == 8) - { - dvp->sccb_ctl = DVP_SCCB_WRITE_DATA_ENABLE | DVP_SCCB_DEVICE_ADDRESS(dev_addr) | DVP_SCCB_REG_ADDRESS(reg_addr) | DVP_SCCB_WDATA_BYTE0(reg_data); - } - else - { - dvp->sccb_ctl = DVP_SCCB_WRITE_DATA_ENABLE | DVP_SCCB_DEVICE_ADDRESS(dev_addr) | DVP_SCCB_REG_ADDRESS(reg_addr >> 8) | DVP_SCCB_WDATA_BYTE0(reg_addr & 0xff) | DVP_SCCB_WDATA_BYTE1(reg_data); - } - dvp_sccb_start_transfer(); -} - -uint8_t dvp_sccb_receive_data(uint8_t dev_addr, uint16_t reg_addr) -{ - uint32_t tmp; - - tmp = dvp->sccb_cfg & (~DVP_SCCB_BYTE_NUM_MASK); - - if (g_sccb_reg_len == 8) - tmp |= DVP_SCCB_BYTE_NUM_2; - else - tmp |= DVP_SCCB_BYTE_NUM_3; - - dvp->sccb_cfg = tmp; - - if (g_sccb_reg_len == 8) - { - dvp->sccb_ctl = DVP_SCCB_WRITE_DATA_ENABLE | DVP_SCCB_DEVICE_ADDRESS(dev_addr) | DVP_SCCB_REG_ADDRESS(reg_addr); - } - else - { - dvp->sccb_ctl = DVP_SCCB_WRITE_DATA_ENABLE | DVP_SCCB_DEVICE_ADDRESS(dev_addr) | DVP_SCCB_REG_ADDRESS(reg_addr >> 8) | DVP_SCCB_WDATA_BYTE0(reg_addr & 0xff); - } - dvp_sccb_start_transfer(); - - dvp->sccb_ctl = DVP_SCCB_DEVICE_ADDRESS(dev_addr); - - dvp_sccb_start_transfer(); - - return (uint8_t) DVP_SCCB_RDATA_BYTE(dvp->sccb_cfg); -} - -static void dvp_reset(void) -{ - /* First power down */ - dvp->cmos_cfg |= DVP_CMOS_POWER_DOWN; - mdelay(200); - dvp->cmos_cfg &= ~DVP_CMOS_POWER_DOWN; - mdelay(200); - - /* Second reset */ - dvp->cmos_cfg &= ~DVP_CMOS_RESET; - mdelay(200); - dvp->cmos_cfg |= DVP_CMOS_RESET; - mdelay(200); -} - -void dvp_init(uint8_t reg_len) -{ - g_sccb_reg_len = reg_len; - sysctl_clock_enable(SYSCTL_CLOCK_DVP); - sysctl_reset(SYSCTL_RESET_DVP); - dvp->cmos_cfg &= (~DVP_CMOS_CLK_DIV_MASK); - dvp->cmos_cfg |= DVP_CMOS_CLK_DIV(3) | DVP_CMOS_CLK_ENABLE; - dvp_sccb_clk_init(); - dvp_reset(); -} - -uint32_t dvp_set_xclk_rate(uint32_t xclk_rate) -{ - uint32_t v_apb1_clk = sysctl_clock_get_freq(SYSCTL_CLOCK_APB1); - uint32_t v_period; - if(v_apb1_clk > xclk_rate * 2) - v_period = round(v_apb1_clk / (xclk_rate * 2.0)) - 1; - else - v_period = 0; - if(v_period > 255) - v_period = 255; - dvp->cmos_cfg &= (~DVP_CMOS_CLK_DIV_MASK); - dvp->cmos_cfg |= DVP_CMOS_CLK_DIV(v_period) | DVP_CMOS_CLK_ENABLE; - dvp_reset(); - return v_apb1_clk / ((v_period + 1) * 2); -} - -void dvp_set_image_format(uint32_t format) -{ - uint32_t tmp; - - tmp = dvp->dvp_cfg & (~DVP_CFG_FORMAT_MASK); - dvp->dvp_cfg = tmp | format; -} - -void dvp_enable_burst(void) -{ - dvp->dvp_cfg |= DVP_CFG_BURST_SIZE_4BEATS; - - dvp->axi &= (~DVP_AXI_GM_MLEN_MASK); - dvp->axi |= DVP_AXI_GM_MLEN_4BYTE; -} - -void dvp_disable_burst(void) -{ - dvp->dvp_cfg &= (~DVP_CFG_BURST_SIZE_4BEATS); - - dvp->axi &= (~DVP_AXI_GM_MLEN_MASK); - dvp->axi |= DVP_AXI_GM_MLEN_1BYTE; -} - -void dvp_set_image_size(uint32_t width, uint32_t height) -{ - uint32_t tmp; - - tmp = dvp->dvp_cfg & (~(DVP_CFG_HREF_BURST_NUM_MASK | DVP_CFG_LINE_NUM_MASK)); - - tmp |= DVP_CFG_LINE_NUM(height); - - if (dvp->dvp_cfg & DVP_CFG_BURST_SIZE_4BEATS) - tmp |= DVP_CFG_HREF_BURST_NUM(width / 8 / 4); - else - tmp |= DVP_CFG_HREF_BURST_NUM(width / 8 / 1); - - dvp->dvp_cfg = tmp; -} - -void dvp_set_ai_addr(uint32_t r_addr, uint32_t g_addr, uint32_t b_addr) -{ - dvp->r_addr = r_addr; - dvp->g_addr = g_addr; - dvp->b_addr = b_addr; -} - -void dvp_set_display_addr(uint32_t addr) -{ - dvp->rgb_addr = addr; -} - -void dvp_start_frame(void) -{ - while (!(dvp->sts & DVP_STS_FRAME_START)) - ; - dvp->sts = (DVP_STS_FRAME_START | DVP_STS_FRAME_START_WE); -} - -void dvp_start_convert(void) -{ - dvp->sts = DVP_STS_DVP_EN | DVP_STS_DVP_EN_WE; -} - -void dvp_finish_convert(void) -{ - while (!(dvp->sts & DVP_STS_FRAME_FINISH)) - ; - dvp->sts = DVP_STS_FRAME_FINISH | DVP_STS_FRAME_FINISH_WE; -} - -void dvp_get_image(void) -{ - while (!(dvp->sts & DVP_STS_FRAME_START)) - ; - dvp->sts = DVP_STS_FRAME_START | DVP_STS_FRAME_START_WE; - while (!(dvp->sts & DVP_STS_FRAME_START)) - ; - dvp->sts = DVP_STS_FRAME_FINISH | DVP_STS_FRAME_FINISH_WE | DVP_STS_FRAME_START | DVP_STS_FRAME_START_WE | DVP_STS_DVP_EN | DVP_STS_DVP_EN_WE; - while (!(dvp->sts & DVP_STS_FRAME_FINISH)) - ; -} - -void dvp_config_interrupt(uint32_t interrupt, uint8_t enable) -{ - if (enable) - dvp->dvp_cfg |= interrupt; - else - dvp->dvp_cfg &= (~interrupt); -} - -int dvp_get_interrupt(uint32_t interrupt) -{ - if (dvp->sts & interrupt) - return 1; - return 0; -} - -void dvp_clear_interrupt(uint32_t interrupt) -{ - interrupt |= (interrupt << 1); - dvp->sts |= interrupt; -} - -void dvp_enable_auto(void) -{ - dvp->dvp_cfg |= DVP_CFG_AUTO_ENABLE; -} - -void dvp_disable_auto(void) -{ - dvp->dvp_cfg &= (~DVP_CFG_AUTO_ENABLE); -} - -void dvp_set_output_enable(dvp_output_mode_t index, int enable) -{ - configASSERT(index < 2); - - if (index == 0) - { - if (enable) - dvp->dvp_cfg |= DVP_CFG_AI_OUTPUT_ENABLE; - else - dvp->dvp_cfg &= ~DVP_CFG_AI_OUTPUT_ENABLE; - } - else - { - if (enable) - dvp->dvp_cfg |= DVP_CFG_DISPLAY_OUTPUT_ENABLE; - else - dvp->dvp_cfg &= ~DVP_CFG_DISPLAY_OUTPUT_ENABLE; - } -} - diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/fft.c b/cores/arduino/kendryte-standalone-sdk/lib/drivers/fft.c deleted file mode 100644 index 102dacf..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/fft.c +++ /dev/null @@ -1,68 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include -#include "dmac.h" -#include "utils.h" -#include "sysctl.h" -#include "fft.h" - -static volatile fft_t *const fft = (volatile fft_t *)FFT_BASE_ADDR; - -static void fft_init(uint8_t point, uint8_t mode, uint16_t shift, uint8_t is_dma, uint8_t input_mode, uint8_t data_mode) -{ - fft->fft_ctrl.fft_point = point; - fft->fft_ctrl.fft_mode = mode; - fft->fft_ctrl.fft_shift = shift; - fft->fft_ctrl.dma_send = is_dma; - fft->fft_ctrl.fft_enable = 1; - fft->fft_ctrl.fft_input_mode = input_mode; - fft->fft_ctrl.fft_data_mode = data_mode; -} - -void fft_complex_uint16_dma(dmac_channel_number_t dma_send_channel_num, dmac_channel_number_t dma_receive_channel_num, - uint16_t shift, fft_direction_t direction, const uint64_t *input, size_t point_num, uint64_t *output) -{ - fft_point_t point = FFT_512; - switch(point_num) - { - case 512: - point = FFT_512; - break; - case 256: - point = FFT_256; - break; - case 128: - point = FFT_128; - break; - case 64: - point = FFT_64; - break; - default: - configASSERT(!"fft point error"); - break; - } - sysctl_clock_enable(SYSCTL_CLOCK_FFT); - sysctl_reset(SYSCTL_RESET_FFT); - fft_init(point, direction, shift, 1, 0, 0); - sysctl_dma_select(dma_receive_channel_num, SYSCTL_DMA_SELECT_FFT_RX_REQ); - sysctl_dma_select(dma_send_channel_num, SYSCTL_DMA_SELECT_FFT_TX_REQ); - dmac_set_single_mode(dma_receive_channel_num, (void *)(&fft->fft_output_fifo), output, DMAC_ADDR_NOCHANGE, DMAC_ADDR_INCREMENT, - DMAC_MSIZE_4, DMAC_TRANS_WIDTH_64, point_num>>1); - dmac_set_single_mode(dma_send_channel_num, input, (void *)(&fft->fft_input_fifo), DMAC_ADDR_INCREMENT, DMAC_ADDR_NOCHANGE, - DMAC_MSIZE_4, DMAC_TRANS_WIDTH_64, point_num>>1); - dmac_wait_done(dma_receive_channel_num); -} - - diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/fpioa.c b/cores/arduino/kendryte-standalone-sdk/lib/drivers/fpioa.c deleted file mode 100644 index 2534725..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/fpioa.c +++ /dev/null @@ -1,5430 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include -#include -#include "sysctl.h" -#include "fpioa.h" - -volatile fpioa_t *const fpioa = (volatile fpioa_t *)FPIOA_BASE_ADDR; - -/** - * @brief Internal used FPIOA function initialize cell - * - * This is NOT fpioa_io_config_t, can't assign directly - * - */ -typedef struct _fpioa_assign_t -{ - uint32_t ch_sel : 8; - /* Channel select from 256 input. */ - uint32_t ds : 4; - /* Driving selector. */ - uint32_t oe_en : 1; - /* Static output enable, will AND with OE_INV. */ - uint32_t oe_inv : 1; - /* Invert output enable. */ - uint32_t do_sel : 1; - /* Data output select: 0 for DO, 1 for OE. */ - uint32_t do_inv : 1; - /* Invert the result of data output select (DO_SEL). */ - uint32_t pu : 1; - /* Pull up enable. 0 for nothing, 1 for pull up. */ - uint32_t pd : 1; - /* Pull down enable. 0 for nothing, 1 for pull down. */ - uint32_t resv0 : 1; - /* Reserved bits. */ - uint32_t sl : 1; - /* Slew rate control enable. */ - uint32_t ie_en : 1; - /* Static input enable, will AND with IE_INV. */ - uint32_t ie_inv : 1; - /* Invert input enable. */ - uint32_t di_inv : 1; - /* Invert Data input. */ - uint32_t st : 1; - /* Schmitt trigger. */ - uint32_t tie_en : 1; - /* Input tie enable, 1 for enable, 0 for disable. */ - uint32_t tie_val : 1; - /* Input tie value, 1 for high, 0 for low. */ - uint32_t resv1 : 5; - /* Reserved bits. */ - uint32_t pad_di : 1; - /* Read current PAD's data input. */ -} __attribute__((packed, aligned(4))) fpioa_assign_t; - -/* Function list */ -static const fpioa_assign_t function_config[FUNC_MAX] = -{ - { - .ch_sel = FUNC_JTAG_TCLK, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_JTAG_TDI, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_JTAG_TMS, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_JTAG_TDO, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_SPI0_D0, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 1, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 1, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_SPI0_D1, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 1, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 1, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_SPI0_D2, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 1, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 1, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_SPI0_D3, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 1, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 1, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_SPI0_D4, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 1, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 1, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_SPI0_D5, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 1, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 1, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_SPI0_D6, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 1, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 1, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_SPI0_D7, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 1, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 1, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_SPI0_SS0, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_SPI0_SS1, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_SPI0_SS2, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_SPI0_SS3, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_SPI0_ARB, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 1, - .tie_val = 1, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_SPI0_SCLK, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UARTHS_RX, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UARTHS_TX, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_RESV6, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_RESV7, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_CLK_SPI1, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_CLK_I2C1, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_GPIOHS0, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_GPIOHS1, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_GPIOHS2, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_GPIOHS3, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_GPIOHS4, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_GPIOHS5, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_GPIOHS6, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_GPIOHS7, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_GPIOHS8, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_GPIOHS9, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_GPIOHS10, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_GPIOHS11, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_GPIOHS12, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_GPIOHS13, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_GPIOHS14, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_GPIOHS15, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_GPIOHS16, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_GPIOHS17, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_GPIOHS18, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_GPIOHS19, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_GPIOHS20, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_GPIOHS21, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_GPIOHS22, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_GPIOHS23, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_GPIOHS24, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_GPIOHS25, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_GPIOHS26, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_GPIOHS27, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_GPIOHS28, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_GPIOHS29, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_GPIOHS30, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_GPIOHS31, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_GPIO0, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_GPIO1, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_GPIO2, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_GPIO3, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_GPIO4, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_GPIO5, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_GPIO6, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_GPIO7, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART1_RX, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART1_TX, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART2_RX, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART2_TX, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART3_RX, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART3_TX, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_SPI1_D0, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 1, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 1, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_SPI1_D1, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 1, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 1, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_SPI1_D2, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 1, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 1, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_SPI1_D3, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 1, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 1, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_SPI1_D4, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 1, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 1, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_SPI1_D5, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 1, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 1, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_SPI1_D6, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 1, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 1, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_SPI1_D7, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 1, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 1, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_SPI1_SS0, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_SPI1_SS1, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_SPI1_SS2, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_SPI1_SS3, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_SPI1_ARB, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 1, - .tie_val = 1, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_SPI1_SCLK, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_SPI_SLAVE_D0, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 1, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 1, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_SPI_SLAVE_SS, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_SPI_SLAVE_SCLK, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_I2S0_MCLK, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_I2S0_SCLK, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_I2S0_WS, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_I2S0_IN_D0, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_I2S0_IN_D1, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_I2S0_IN_D2, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_I2S0_IN_D3, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_I2S0_OUT_D0, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_I2S0_OUT_D1, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_I2S0_OUT_D2, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_I2S0_OUT_D3, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_I2S1_MCLK, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_I2S1_SCLK, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_I2S1_WS, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_I2S1_IN_D0, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_I2S1_IN_D1, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_I2S1_IN_D2, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_I2S1_IN_D3, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_I2S1_OUT_D0, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_I2S1_OUT_D1, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_I2S1_OUT_D2, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_I2S1_OUT_D3, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_I2S2_MCLK, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_I2S2_SCLK, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_I2S2_WS, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_I2S2_IN_D0, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_I2S2_IN_D1, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_I2S2_IN_D2, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_I2S2_IN_D3, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_I2S2_OUT_D0, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_I2S2_OUT_D1, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_I2S2_OUT_D2, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_I2S2_OUT_D3, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_RESV0, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_RESV1, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_RESV2, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_RESV3, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_RESV4, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_RESV5, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_I2C0_SCLK, - .ds = 0x0, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 1, - .pd = 0, - .resv1 = 0, - .sl = 1, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_I2C0_SDA, - .ds = 0x0, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 1, - .pd = 0, - .resv1 = 0, - .sl = 1, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_I2C1_SCLK, - .ds = 0x0, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 1, - .pd = 0, - .resv1 = 0, - .sl = 1, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_I2C1_SDA, - .ds = 0x0, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 1, - .pd = 0, - .resv1 = 0, - .sl = 1, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_I2C2_SCLK, - .ds = 0x0, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 1, - .pd = 0, - .resv1 = 0, - .sl = 1, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_I2C2_SDA, - .ds = 0x0, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 1, - .pd = 0, - .resv1 = 0, - .sl = 1, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_CMOS_XCLK, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_CMOS_RST, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_CMOS_PWDN, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_CMOS_VSYNC, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_CMOS_HREF, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_CMOS_PCLK, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_CMOS_D0, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_CMOS_D1, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_CMOS_D2, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_CMOS_D3, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_CMOS_D4, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_CMOS_D5, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_CMOS_D6, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_CMOS_D7, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_SCCB_SCLK, - .ds = 0x0, - .oe_en = 1, - .oe_inv = 1, - .do_sel = 0, - .do_inv = 0, - .pu = 1, - .pd = 0, - .resv1 = 0, - .sl = 1, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_SCCB_SDA, - .ds = 0x0, - .oe_en = 1, - .oe_inv = 1, - .do_sel = 0, - .do_inv = 0, - .pu = 1, - .pd = 0, - .resv1 = 0, - .sl = 1, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART1_CTS, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART1_DSR, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART1_DCD, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART1_RI, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART1_SIR_IN, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART1_DTR, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART1_RTS, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART1_OUT2, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART1_OUT1, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART1_SIR_OUT, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART1_BAUD, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART1_RE, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART1_DE, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART1_RS485_EN, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART2_CTS, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART2_DSR, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART2_DCD, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART2_RI, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART2_SIR_IN, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART2_DTR, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART2_RTS, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART2_OUT2, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART2_OUT1, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART2_SIR_OUT, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART2_BAUD, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART2_RE, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART2_DE, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART2_RS485_EN, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART3_CTS, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART3_DSR, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART3_DCD, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART3_RI, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART3_SIR_IN, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART3_DTR, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART3_RTS, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART3_OUT2, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART3_OUT1, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART3_SIR_OUT, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART3_BAUD, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART3_RE, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART3_DE, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_UART3_RS485_EN, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_TIMER0_TOGGLE1, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_TIMER0_TOGGLE2, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_TIMER0_TOGGLE3, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_TIMER0_TOGGLE4, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_TIMER1_TOGGLE1, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_TIMER1_TOGGLE2, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_TIMER1_TOGGLE3, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_TIMER1_TOGGLE4, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_TIMER2_TOGGLE1, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_TIMER2_TOGGLE2, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_TIMER2_TOGGLE3, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_TIMER2_TOGGLE4, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_CLK_SPI2, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_CLK_I2C2, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_INTERNAL0, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_INTERNAL1, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_INTERNAL2, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_INTERNAL3, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_INTERNAL4, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_INTERNAL5, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_INTERNAL6, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_INTERNAL7, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_INTERNAL8, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_INTERNAL9, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_INTERNAL10, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_INTERNAL11, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_INTERNAL12, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_INTERNAL13, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 1, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_INTERNAL14, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 1, - .pd = 0, - .resv1 = 0, - .sl = 1, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_INTERNAL15, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_INTERNAL16, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_INTERNAL17, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_CONSTANT, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_INTERNAL18, - .ds = 0x0, - .oe_en = 0, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 1, - .ie_inv = 0, - .di_inv = 0, - .st = 1, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_DEBUG0, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_DEBUG1, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_DEBUG2, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_DEBUG3, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_DEBUG4, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_DEBUG5, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_DEBUG6, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_DEBUG7, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_DEBUG8, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_DEBUG9, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_DEBUG10, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_DEBUG11, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_DEBUG12, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_DEBUG13, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_DEBUG14, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_DEBUG15, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_DEBUG16, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_DEBUG17, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_DEBUG18, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_DEBUG19, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_DEBUG20, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_DEBUG21, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_DEBUG22, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_DEBUG23, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_DEBUG24, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_DEBUG25, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_DEBUG26, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_DEBUG27, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_DEBUG28, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_DEBUG29, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_DEBUG30, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, - { - .ch_sel = FUNC_DEBUG31, - .ds = 0xf, - .oe_en = 1, - .oe_inv = 0, - .do_sel = 0, - .do_inv = 0, - .pu = 0, - .pd = 0, - .resv1 = 0, - .sl = 0, - .ie_en = 0, - .ie_inv = 0, - .di_inv = 0, - .st = 0, - .tie_en = 0, - .tie_val = 0, - .resv0 = 0, - .pad_di = 0 - }, -}; - -int fpioa_init(void) -{ - int i = 0; - - /* Enable fpioa clock in system controller */ - sysctl_clock_enable(SYSCTL_CLOCK_FPIOA); - - /* Initialize tie */ - fpioa_tie_t tie = { 0 }; - - /* Set tie enable and tie value */ - for (i = 0; i < FUNC_MAX; i++) - { - tie.en[i / 32] |= (function_config[i].tie_en << (i % 32)); - tie.val[i / 32] |= (function_config[i].tie_val << (i % 32)); - } - - /* Atomic write every 32bit register to fpioa function */ - for (i = 0; i < FUNC_MAX / 32; i++) - { - /* Set value before enable */ - fpioa->tie.val[i] = tie.val[i]; - fpioa->tie.en[i] = tie.en[i]; - } - - return 0; -} - -int fpioa_get_io(int number, fpioa_io_config_t *cfg) -{ - /* Check parameters */ - if (number < 0 || number >= FPIOA_NUM_IO || cfg == NULL) - return -1; - /* Atomic read register */ - *cfg = fpioa->io[number]; - return 0; -} - -int fpioa_set_io(int number, fpioa_io_config_t *cfg) -{ - /* Check parameters */ - if (number < 0 || number >= FPIOA_NUM_IO || cfg == NULL) - return -1; - /* Atomic write register */ - fpioa->io[number] = *cfg; - return 0; -} - -int fpioa_set_io_pull(int number, fpioa_pull_t pull) -{ - /* Check parameters */ - if (number < 0 || number >= FPIOA_NUM_IO || pull >= FPIOA_PULL_MAX) - return -1; - - /* Atomic read register */ - fpioa_io_config_t cfg = fpioa->io[number]; - - switch (pull) - { - case FPIOA_PULL_NONE: - cfg.pu = 0; - cfg.pd = 0; - break; - case FPIOA_PULL_DOWN: - cfg.pu = 0; - cfg.pd = 1; - break; - case FPIOA_PULL_UP: - cfg.pu = 1; - cfg.pd = 0; - break; - default: - break; - } - /* Atomic write register */ - fpioa->io[number] = cfg; - return 0; -} - -int fpioa_get_io_pull(int number) -{ - /* Check parameters */ - if (number < 0 || number >= FPIOA_NUM_IO) - return -1; - - fpioa_pull_t pull; - /* Atomic read register */ - fpioa_io_config_t cfg = fpioa->io[number]; - - if (cfg.pu == 0 && cfg.pd == 1) - pull = FPIOA_PULL_DOWN; - else if (cfg.pu == 1 && cfg.pd == 0) - pull = FPIOA_PULL_UP; - else - pull = FPIOA_PULL_NONE; - return pull; -} - -int fpioa_set_io_driving(int number, fpioa_driving_t driving) -{ - /* Check parameters */ - if (number < 0 || number >= FPIOA_NUM_IO || driving >= FPIOA_DRIVING_MAX) - return -1; - - /* Atomic read register */ - fpioa_io_config_t cfg = fpioa->io[number]; - /* Set IO driving */ - cfg.ds = driving; - /* Atomic write register */ - fpioa->io[number] = cfg; - return 0; -} - -int fpioa_set_sl(int number, uint8_t sl_value) -{ - /* Check parameters */ - if (number < 0 || number >= FPIOA_NUM_IO) - return -1; - - /* Atomic read register */ - fpioa_io_config_t cfg = fpioa->io[number]; - /* Set IO driving */ - cfg.sl = sl_value; - /* Atomic write register */ - fpioa->io[number] = cfg; - return 0; -} - - -int fpioa_set_st(int number, uint8_t st_value) -{ - /* Check parameters */ - if (number < 0 || number >= FPIOA_NUM_IO) - return -1; - - /* Atomic read register */ - fpioa_io_config_t cfg = fpioa->io[number]; - /* Set IO driving */ - cfg.sl = st_value; - /* Atomic write register */ - fpioa->io[number] = cfg; - return 0; -} - - -int fpioa_get_io_driving(int number) -{ - /* Check parameters */ - if (number < 0 || number >= FPIOA_NUM_IO) - return -1; - - return fpioa->io[number].ds; -} - -int fpioa_set_function_raw(int number, fpioa_function_t function) -{ - /* Check parameters */ - if (number < 0 || number >= FPIOA_NUM_IO || function < 0 || function >= FUNC_MAX) - return -1; - /* Atomic write register */ - fpioa->io[number] =(const fpioa_io_config_t) - { - .ch_sel = function_config[function].ch_sel, - .ds = function_config[function].ds, - .oe_en = function_config[function].oe_en, - .oe_inv = function_config[function].oe_inv, - .do_sel = function_config[function].do_sel, - .do_inv = function_config[function].do_inv, - .pu = function_config[function].pu, - .pd = function_config[function].pd, - .sl = function_config[function].sl, - .ie_en = function_config[function].ie_en, - .ie_inv = function_config[function].ie_inv, - .di_inv = function_config[function].di_inv, - .st = function_config[function].st, - /* resv and pad_di do not need initialization */ - }; - return 0; -} - -int fpioa_set_function(int number, fpioa_function_t function) -{ - uint8_t index = 0; - /* Check parameters */ - if (number < 0 || number >= FPIOA_NUM_IO || function < 0 || function >= FUNC_MAX) - return -1; - if (function == FUNC_RESV0) - { - fpioa_set_function_raw(number, FUNC_RESV0); - return 0; - } - /* Compare all IO */ - for (index = 0; index < FPIOA_NUM_IO; index++) - { - if ((fpioa->io[index].ch_sel == function) && (index != number)) - fpioa_set_function_raw(index, FUNC_RESV0); - } - fpioa_set_function_raw(number, function); - return 0; -} - -int fpioa_set_tie_enable(fpioa_function_t function, int enable) -{ - /* Check parameters */ - if (function < 0 || function >= FUNC_MAX) - return -1; - /* Set tie enable */ - if (enable) - fpioa->tie.en[function / 32] |= (1UL << (function % 32)); - else - fpioa->tie.en[function / 32] &= (~(1UL << (function % 32))); - return 0; -} - -int fpioa_set_tie_value(fpioa_function_t function, int value) -{ - /* Check parameters */ - if (function < 0 || function >= FUNC_MAX) - return -1; - /* Set tie value */ - if (value) - fpioa->tie.val[function / 32] |= (1UL << (function % 32)); - else - fpioa->tie.val[function / 32] &= (~(1UL << (function % 32))); - return 0; -} - -int fpioa_get_io_by_function(fpioa_function_t function) -{ - int index = 0; - for (index = 0; index < FPIOA_NUM_IO; index++) - { - if (fpioa->io[index].ch_sel == function) - return index; - } - - return -1; -} diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/gpio.c b/cores/arduino/kendryte-standalone-sdk/lib/drivers/gpio.c deleted file mode 100644 index ba996d8..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/gpio.c +++ /dev/null @@ -1,79 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "gpio.h" -#include "utils.h" -#include "fpioa.h" -#include "sysctl.h" -#define GPIO_MAX_PINNO 8 - -volatile gpio_t* const gpio = (volatile gpio_t*)GPIO_BASE_ADDR; - -int gpio_init(void) -{ - return sysctl_clock_enable(SYSCTL_CLOCK_GPIO); -} - -void gpio_set_drive_mode(uint8_t pin, gpio_drive_mode_t mode) -{ - configASSERT(pin < GPIO_MAX_PINNO); - int io_number = fpioa_get_io_by_function(FUNC_GPIO0 + pin); - configASSERT(io_number > 0); - - fpioa_pull_t pull; - uint32_t dir; - - switch (mode) - { - case GPIO_DM_INPUT: - pull = FPIOA_PULL_NONE; - dir = 0; - break; - case GPIO_DM_INPUT_PULL_DOWN: - pull = FPIOA_PULL_DOWN; - dir = 0; - break; - case GPIO_DM_INPUT_PULL_UP: - pull = FPIOA_PULL_UP; - dir = 0; - break; - case GPIO_DM_OUTPUT: - pull = FPIOA_PULL_DOWN; - dir = 1; - break; - default: - configASSERT(!"GPIO drive mode is not supported.") break; - } - - fpioa_set_io_pull(io_number, pull); - set_gpio_bit(gpio->direction.u32, pin, dir); -} - -gpio_pin_value_t gpio_get_pin(uint8_t pin) -{ - configASSERT(pin < GPIO_MAX_PINNO); - uint32_t dir = get_gpio_bit(gpio->direction.u32, pin); - volatile uint32_t *reg = dir ? gpio->data_output.u32 : gpio->data_input.u32; - return get_gpio_bit(reg, pin); -} - -void gpio_set_pin(uint8_t pin, gpio_pin_value_t value) -{ - configASSERT(pin < GPIO_MAX_PINNO); - uint32_t dir = get_gpio_bit(gpio->direction.u32, pin); - volatile uint32_t *reg = dir ? gpio->data_output.u32 : gpio->data_input.u32; - configASSERT(dir == 1); - set_gpio_bit(reg, pin, value); -} - diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/gpiohs.c b/cores/arduino/kendryte-standalone-sdk/lib/drivers/gpiohs.c deleted file mode 100644 index 49fe355..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/gpiohs.c +++ /dev/null @@ -1,218 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "gpiohs.h" -#include "utils.h" -#include "fpioa.h" -#include "sysctl.h" -#define GPIOHS_MAX_PINNO 32 - -volatile gpiohs_t* const gpiohs = (volatile gpiohs_t*)GPIOHS_BASE_ADDR; - -typedef struct _gpiohs_pin_instance -{ - size_t pin; - gpio_pin_edge_t edge; - void (*callback)(); - plic_irq_callback_t gpiohs_callback; - void *context; -} gpiohs_pin_instance_t; - -static gpiohs_pin_instance_t pin_instance[32]; - -void gpiohs_set_drive_mode(uint8_t pin, gpio_drive_mode_t mode) -{ - configASSERT(pin < GPIOHS_MAX_PINNO); - int io_number = fpioa_get_io_by_function(FUNC_GPIOHS0 + pin); - configASSERT(io_number > 0); - - fpioa_pull_t pull; - uint32_t dir; - - switch (mode) - { - case GPIO_DM_INPUT: - pull = FPIOA_PULL_NONE; - dir = 0; - break; - case GPIO_DM_INPUT_PULL_DOWN: - pull = FPIOA_PULL_DOWN; - dir = 0; - break; - case GPIO_DM_INPUT_PULL_UP: - pull = FPIOA_PULL_UP; - dir = 0; - break; - case GPIO_DM_OUTPUT: - pull = FPIOA_PULL_DOWN; - dir = 1; - break; - default: - configASSERT(!"GPIO drive mode is not supported.") break; - } - - fpioa_set_io_pull(io_number, pull); - volatile uint32_t *reg = dir ? gpiohs->output_en.u32 : gpiohs->input_en.u32; - volatile uint32_t *reg_d = !dir ? gpiohs->output_en.u32 : gpiohs->input_en.u32; - set_gpio_bit(reg_d, pin, 0); - set_gpio_bit(reg, pin, 1); -} - -gpio_pin_value_t gpiohs_get_pin(uint8_t pin) -{ - configASSERT(pin < GPIOHS_MAX_PINNO); - return get_gpio_bit(gpiohs->input_val.u32, pin); -} - -void gpiohs_set_pin(uint8_t pin, gpio_pin_value_t value) -{ - configASSERT(pin < GPIOHS_MAX_PINNO); - set_gpio_bit(gpiohs->output_val.u32, pin, value); -} - -void gpiohs_set_pin_edge(uint8_t pin, gpio_pin_edge_t edge) -{ - set_gpio_bit(gpiohs->rise_ie.u32, pin, 0); - set_gpio_bit(gpiohs->rise_ip.u32, pin, 1); - - set_gpio_bit(gpiohs->fall_ie.u32, pin, 0); - set_gpio_bit(gpiohs->fall_ip.u32, pin, 1); - - set_gpio_bit(gpiohs->low_ie.u32, pin, 0); - set_gpio_bit(gpiohs->low_ip.u32, pin, 1); - - set_gpio_bit(gpiohs->high_ie.u32, pin, 0); - set_gpio_bit(gpiohs->high_ip.u32, pin, 1); - - if(edge & GPIO_PE_FALLING) - { - set_gpio_bit(gpiohs->fall_ie.u32, pin, 1); - } - else - { - set_gpio_bit(gpiohs->fall_ie.u32, pin, 0); - } - - if(edge & GPIO_PE_RISING) - { - set_gpio_bit(gpiohs->rise_ie.u32, pin, 1); - } - else - { - set_gpio_bit(gpiohs->rise_ie.u32, pin, 0); - } - - if(edge & GPIO_PE_LOW) - { - set_gpio_bit(gpiohs->low_ie.u32, pin, 1); - } - else - { - set_gpio_bit(gpiohs->low_ie.u32, pin, 0); - } - - if(edge & GPIO_PE_HIGH) - { - set_gpio_bit(gpiohs->high_ie.u32, pin, 1); - } - else - { - set_gpio_bit(gpiohs->high_ie.u32, pin, 0); - } - - pin_instance[pin].edge = edge; -} - -int gpiohs_pin_onchange_isr(void *userdata) -{ - gpiohs_pin_instance_t *ctx = (gpiohs_pin_instance_t *)userdata; - size_t pin = ctx->pin; - - if(ctx->edge & GPIO_PE_FALLING) - { - set_gpio_bit(gpiohs->fall_ie.u32, pin, 0); - set_gpio_bit(gpiohs->fall_ip.u32, pin, 1); - set_gpio_bit(gpiohs->fall_ie.u32, pin, 1); - } - - if(ctx->edge & GPIO_PE_RISING) - { - set_gpio_bit(gpiohs->rise_ie.u32, pin, 0); - set_gpio_bit(gpiohs->rise_ip.u32, pin, 1); - set_gpio_bit(gpiohs->rise_ie.u32, pin, 1); - } - - if(ctx->edge & GPIO_PE_LOW) - { - set_gpio_bit(gpiohs->low_ie.u32, pin, 0); - set_gpio_bit(gpiohs->low_ip.u32, pin, 1); - set_gpio_bit(gpiohs->low_ie.u32, pin, 1); - } - - if(ctx->edge & GPIO_PE_HIGH) - { - set_gpio_bit(gpiohs->high_ie.u32, pin, 0); - set_gpio_bit(gpiohs->high_ip.u32, pin, 1); - set_gpio_bit(gpiohs->high_ie.u32, pin, 1); - } - - if (ctx->callback) - ctx->callback(); - if(ctx->gpiohs_callback) - ctx->gpiohs_callback(ctx->context); - - return 0; -} - -void gpiohs_set_irq(uint8_t pin, uint32_t priority, void (*func)()) -{ - - pin_instance[pin].pin = pin; - pin_instance[pin].callback = func; - - plic_set_priority(IRQN_GPIOHS0_INTERRUPT + pin, priority); - plic_irq_register(IRQN_GPIOHS0_INTERRUPT + pin, gpiohs_pin_onchange_isr, &(pin_instance[pin])); - plic_irq_enable(IRQN_GPIOHS0_INTERRUPT + pin); -} - -void gpiohs_irq_register(uint8_t pin, uint32_t priority, plic_irq_callback_t callback, void *ctx) -{ - pin_instance[pin].pin = pin; - pin_instance[pin].gpiohs_callback = callback; - pin_instance[pin].context = ctx; - - plic_set_priority(IRQN_GPIOHS0_INTERRUPT + pin, priority); - plic_irq_register(IRQN_GPIOHS0_INTERRUPT + pin, gpiohs_pin_onchange_isr, &(pin_instance[pin])); - plic_irq_enable(IRQN_GPIOHS0_INTERRUPT + pin); -} - -void gpiohs_irq_unregister(uint8_t pin) -{ - pin_instance[pin] = (gpiohs_pin_instance_t){ - .callback = NULL, - .gpiohs_callback = NULL, - .context = NULL, - }; - set_gpio_bit(gpiohs->rise_ie.u32, pin, 0); - set_gpio_bit(gpiohs->fall_ie.u32, pin, 0); - set_gpio_bit(gpiohs->low_ie.u32, pin, 0); - set_gpio_bit(gpiohs->high_ie.u32, pin, 0); - plic_irq_unregister(IRQN_GPIOHS0_INTERRUPT + pin); -} - -void gpiohs_irq_disable(size_t pin) -{ - plic_irq_disable(IRQN_GPIOHS0_INTERRUPT + pin); -} - diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/i2c.c b/cores/arduino/kendryte-standalone-sdk/lib/drivers/i2c.c deleted file mode 100644 index ba0bf18..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/i2c.c +++ /dev/null @@ -1,251 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include -#include "i2c.h" -#include "utils.h" -#include "fpioa.h" -#include "platform.h" -#include "stdlib.h" -#include "string.h" -#include "sysctl.h" - -typedef struct _i2c_slave_instance -{ - uint32_t i2c_num; - const i2c_slave_handler_t *slave_handler; -} i2c_slave_instance_t; - -static i2c_slave_instance_t slave_instance[I2C_MAX_NUM]; - -volatile i2c_t* const i2c[3] = -{ - (volatile i2c_t*)I2C0_BASE_ADDR, - (volatile i2c_t*)I2C1_BASE_ADDR, - (volatile i2c_t*)I2C2_BASE_ADDR -}; - -static void i2c_clk_init(i2c_device_number_t i2c_num) -{ - configASSERT(i2c_num < I2C_MAX_NUM); - sysctl_clock_enable(SYSCTL_CLOCK_I2C0 + i2c_num); - sysctl_clock_set_threshold(SYSCTL_THRESHOLD_I2C0 + i2c_num, 3); -} - -void i2c_init(i2c_device_number_t i2c_num, uint32_t slave_address, uint32_t address_width, - uint32_t i2c_clk) -{ - configASSERT(i2c_num < I2C_MAX_NUM); - configASSERT(address_width == 7 || address_width == 10); - - volatile i2c_t *i2c_adapter = i2c[i2c_num]; - - i2c_clk_init(i2c_num); - - uint32_t v_i2c_freq = sysctl_clock_get_freq(SYSCTL_CLOCK_I2C0 + i2c_num); - uint16_t v_period_clk_cnt = v_i2c_freq / i2c_clk / 2; - - if(v_period_clk_cnt == 0) - v_period_clk_cnt = 1; - - i2c_adapter->enable = 0; - i2c_adapter->con = I2C_CON_MASTER_MODE | I2C_CON_SLAVE_DISABLE | I2C_CON_RESTART_EN | - (address_width == 10 ? I2C_CON_10BITADDR_SLAVE : 0) | I2C_CON_SPEED(1); - i2c_adapter->ss_scl_hcnt = I2C_SS_SCL_HCNT_COUNT(v_period_clk_cnt); - i2c_adapter->ss_scl_lcnt = I2C_SS_SCL_LCNT_COUNT(v_period_clk_cnt); - - i2c_adapter->tar = I2C_TAR_ADDRESS(slave_address); - i2c_adapter->intr_mask = 0; - i2c_adapter->dma_cr = 0x3; - i2c_adapter->dma_rdlr = 0; - i2c_adapter->dma_tdlr = 4; - i2c_adapter->enable = I2C_ENABLE_ENABLE; -} - -static int i2c_slave_irq(void *userdata) -{ - i2c_slave_instance_t *instance = (i2c_slave_instance_t *)userdata; - volatile i2c_t *i2c_adapter = i2c[instance->i2c_num]; - uint32_t status = i2c_adapter->intr_stat; - if (status & I2C_INTR_STAT_START_DET) - { - instance->slave_handler->on_event(I2C_EV_START); - readl(&i2c_adapter->clr_start_det); - } - if (status & I2C_INTR_STAT_STOP_DET) - { - instance->slave_handler->on_event(I2C_EV_STOP); - readl(&i2c_adapter->clr_stop_det); - } - if (status & I2C_INTR_STAT_RX_FULL) - { - instance->slave_handler->on_receive(i2c_adapter->data_cmd); - } - if (status & I2C_INTR_STAT_RD_REQ) - { - i2c_adapter->data_cmd = instance->slave_handler->on_transmit(); - readl(&i2c_adapter->clr_rd_req); - } - return 0; -} - -void i2c_init_as_slave(i2c_device_number_t i2c_num, uint32_t slave_address, uint32_t address_width, - const i2c_slave_handler_t *handler) -{ - configASSERT(address_width == 7 || address_width == 10); - volatile i2c_t *i2c_adapter = i2c[i2c_num]; - slave_instance[i2c_num].i2c_num = i2c_num; - slave_instance[i2c_num].slave_handler = handler; - - i2c_clk_init(i2c_num); - i2c_adapter->enable = 0; - i2c_adapter->con = (address_width == 10 ? I2C_CON_10BITADDR_SLAVE : 0) | I2C_CON_SPEED(1) | I2C_CON_STOP_DET_IFADDRESSED; - i2c_adapter->ss_scl_hcnt = I2C_SS_SCL_HCNT_COUNT(37); - i2c_adapter->ss_scl_lcnt = I2C_SS_SCL_LCNT_COUNT(40); - i2c_adapter->sar = I2C_SAR_ADDRESS(slave_address); - i2c_adapter->rx_tl = I2C_RX_TL_VALUE(0); - i2c_adapter->tx_tl = I2C_TX_TL_VALUE(0); - i2c_adapter->intr_mask = I2C_INTR_MASK_RX_FULL | I2C_INTR_MASK_START_DET | I2C_INTR_MASK_STOP_DET | I2C_INTR_MASK_RD_REQ; - - plic_set_priority(IRQN_I2C0_INTERRUPT + i2c_num, 1); - plic_irq_register(IRQN_I2C0_INTERRUPT + i2c_num, i2c_slave_irq, slave_instance + i2c_num); - plic_irq_enable(IRQN_I2C0_INTERRUPT + i2c_num); - - i2c_adapter->enable = I2C_ENABLE_ENABLE; -} - -int i2c_send_data(i2c_device_number_t i2c_num, const uint8_t *send_buf, size_t send_buf_len) -{ - configASSERT(i2c_num < I2C_MAX_NUM); - volatile i2c_t* i2c_adapter = i2c[i2c_num]; - size_t fifo_len, index; - i2c_adapter->clr_tx_abrt = i2c_adapter->clr_tx_abrt; - while (send_buf_len) - { - fifo_len = 8 - i2c_adapter->txflr; - fifo_len = send_buf_len < fifo_len ? send_buf_len : fifo_len; - for (index = 0; index < fifo_len; index++) - i2c_adapter->data_cmd = I2C_DATA_CMD_DATA(*send_buf++); - if (i2c_adapter->tx_abrt_source != 0) - return 1; - send_buf_len -= fifo_len; - } - while ((i2c_adapter->status & I2C_STATUS_ACTIVITY) || !(i2c_adapter->status & I2C_STATUS_TFE)) - ; - - if (i2c_adapter->tx_abrt_source != 0) - return 1; - - return 0; -} - -void i2c_send_data_dma(dmac_channel_number_t dma_channel_num, i2c_device_number_t i2c_num, const uint8_t *send_buf, - size_t send_buf_len) -{ - configASSERT(i2c_num < I2C_MAX_NUM); - volatile i2c_t* i2c_adapter = i2c[i2c_num]; - i2c_adapter->clr_tx_abrt = i2c_adapter->clr_tx_abrt; - uint32_t *buf = malloc(send_buf_len * sizeof(uint32_t)); - int i; - for (i = 0; i < send_buf_len; i++) - { - buf[i] = send_buf[i]; - } - - sysctl_dma_select((sysctl_dma_channel_t)dma_channel_num, SYSCTL_DMA_SELECT_I2C0_TX_REQ + i2c_num * 2); - dmac_set_single_mode(dma_channel_num, buf, (void *)(&i2c_adapter->data_cmd), DMAC_ADDR_INCREMENT, DMAC_ADDR_NOCHANGE, - DMAC_MSIZE_4, DMAC_TRANS_WIDTH_32, send_buf_len); - - dmac_wait_done(dma_channel_num); - free((void *)buf); - - while ((i2c_adapter->status & I2C_STATUS_ACTIVITY) || !(i2c_adapter->status & I2C_STATUS_TFE)) - { - if (i2c_adapter->tx_abrt_source != 0) - configASSERT(!"source abort"); - } -} - -int i2c_recv_data(i2c_device_number_t i2c_num, const uint8_t *send_buf, size_t send_buf_len, uint8_t *receive_buf, - size_t receive_buf_len) -{ - configASSERT(i2c_num < I2C_MAX_NUM); - - size_t fifo_len, index; - size_t rx_len = receive_buf_len; - volatile i2c_t* i2c_adapter = i2c[i2c_num]; - - while (send_buf_len) - { - fifo_len = 8 - i2c_adapter->txflr; - fifo_len = send_buf_len < fifo_len ? send_buf_len : fifo_len; - for (index = 0; index < fifo_len; index++) - i2c_adapter->data_cmd = I2C_DATA_CMD_DATA(*send_buf++); - if (i2c_adapter->tx_abrt_source != 0) - return 1; - send_buf_len -= fifo_len; - } - - while (receive_buf_len || rx_len) - { - fifo_len = i2c_adapter->rxflr; - fifo_len = rx_len < fifo_len ? rx_len : fifo_len; - for (index = 0; index < fifo_len; index++) - *receive_buf++ = (uint8_t)i2c_adapter->data_cmd; - rx_len -= fifo_len; - fifo_len = 8 - i2c_adapter->txflr; - fifo_len = receive_buf_len < fifo_len ? receive_buf_len : fifo_len; - for (index = 0; index < fifo_len; index++) - i2c_adapter->data_cmd = I2C_DATA_CMD_CMD; - if (i2c_adapter->tx_abrt_source != 0) - return 1; - receive_buf_len -= fifo_len; - } - return 0; -} - -void i2c_recv_data_dma(dmac_channel_number_t dma_send_channel_num, dmac_channel_number_t dma_receive_channel_num, - i2c_device_number_t i2c_num, const uint8_t *send_buf, size_t send_buf_len, - uint8_t *receive_buf, size_t receive_buf_len) -{ - configASSERT(i2c_num < I2C_MAX_NUM); - - volatile i2c_t* i2c_adapter = i2c[i2c_num]; - - uint32_t *write_cmd = malloc(sizeof(uint32_t) * (send_buf_len + receive_buf_len)); - size_t i; - for(i = 0; i < send_buf_len; i++) - write_cmd[i] = *send_buf++; - for (i = 0; i < receive_buf_len; i++) - write_cmd[i + send_buf_len] = I2C_DATA_CMD_CMD; - - sysctl_dma_select((sysctl_dma_channel_t)dma_send_channel_num, SYSCTL_DMA_SELECT_I2C0_TX_REQ + i2c_num * 2); - sysctl_dma_select((sysctl_dma_channel_t)dma_receive_channel_num, SYSCTL_DMA_SELECT_I2C0_RX_REQ + i2c_num * 2); - - dmac_set_single_mode(dma_receive_channel_num, (void *)(&i2c_adapter->data_cmd), write_cmd, DMAC_ADDR_NOCHANGE, - DMAC_ADDR_INCREMENT,DMAC_MSIZE_1, DMAC_TRANS_WIDTH_32, receive_buf_len); - - dmac_set_single_mode(dma_send_channel_num, write_cmd, (void *)(&i2c_adapter->data_cmd), DMAC_ADDR_INCREMENT, - DMAC_ADDR_NOCHANGE,DMAC_MSIZE_4, DMAC_TRANS_WIDTH_32, receive_buf_len + send_buf_len); - - dmac_wait_done(dma_send_channel_num); - dmac_wait_done(dma_receive_channel_num); - - for (i = 0; i < receive_buf_len; i++) - { - receive_buf[i] = (uint8_t)write_cmd[i]; - } - - free(write_cmd); -} diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/i2s.c b/cores/arduino/kendryte-standalone-sdk/lib/drivers/i2s.c deleted file mode 100644 index 07a90cd..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/i2s.c +++ /dev/null @@ -1,636 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include -#include -#include -#include "i2s.h" -#include "sysctl.h" -#include "stdlib.h" -#include "utils.h" - -volatile i2s_t *const i2s[3] = -{ - (volatile i2s_t *)I2S0_BASE_ADDR, - (volatile i2s_t *)I2S1_BASE_ADDR, - (volatile i2s_t *)I2S2_BASE_ADDR -}; - -static int i2s_recv_channel_enable(i2s_device_number_t device_num, - i2s_channel_num_t channel_num, uint32_t enable) -{ - rer_t u_rer; - - if (channel_num < I2S_CHANNEL_0 || channel_num > I2S_CHANNEL_3) - return -1; - u_rer.reg_data = readl(&i2s[device_num]->channel[channel_num].rer); - u_rer.rer.rxchenx = enable; - writel(u_rer.reg_data, &i2s[device_num]->channel[channel_num].rer); - return 0; -} - -static int i2s_transmit_channel_enable(i2s_device_number_t device_num, - i2s_channel_num_t channel_num, uint32_t enable) -{ - ter_t u_ter; - - if (channel_num < I2S_CHANNEL_0 || channel_num > I2S_CHANNEL_3) - return -1; - - u_ter.reg_data = readl(&i2s[device_num]->channel[channel_num].ter); - u_ter.ter.txchenx = enable; - writel(u_ter.reg_data, &i2s[device_num]->channel[channel_num].ter); - return 0; -} - -static void i2s_receive_enable(i2s_device_number_t device_num, i2s_channel_num_t channel_num) -{ - irer_t u_irer; - - u_irer.reg_data = readl(&i2s[device_num]->irer); - u_irer.irer.rxen = 1; - writel(u_irer.reg_data, &i2s[device_num]->irer); - /* Receiver block enable */ - - i2s_recv_channel_enable(device_num, channel_num, 1); - /* Receive channel enable */ -} - -static void i2s_transimit_enable(i2s_device_number_t device_num, i2s_channel_num_t channel_num) -{ - iter_t u_iter; - - u_iter.reg_data = readl(&i2s[device_num]->iter); - u_iter.iter.txen = 1; - writel(u_iter.reg_data, &i2s[device_num]->iter); - /* Transmitter block enable */ - - i2s_transmit_channel_enable(device_num, channel_num, 1); - /* Transmit channel enable */ -} - -static void i2s_set_enable(i2s_device_number_t device_num, uint32_t enable) -{ - ier_t u_ier; - - u_ier.reg_data = readl(&i2s[device_num]->ier); - u_ier.ier.ien = enable; - writel(u_ier.reg_data, &i2s[device_num]->ier); -} - -static void i2s_disable_block(i2s_device_number_t device_num, i2s_transmit_t rxtx_mode) -{ - irer_t u_irer; - iter_t u_iter; - - if (rxtx_mode == I2S_RECEIVER) - { - u_irer.reg_data = readl(&i2s[device_num]->irer); - u_irer.irer.rxen = 0; - writel(u_irer.reg_data, &i2s[device_num]->irer); - /* Receiver block disable */ - } - else - { - u_iter.reg_data = readl(&i2s[device_num]->iter); - u_iter.iter.txen = 0; - writel(u_iter.reg_data, &i2s[device_num]->iter); - /* Transmitter block disable */ - } -} - -static int i2s_set_rx_word_length(i2s_device_number_t device_num, - i2s_word_length_t word_length, - i2s_channel_num_t channel_num) -{ - rcr_tcr_t u_rcr; - - if (word_length > RESOLUTION_32_BIT || word_length < IGNORE_WORD_LENGTH) - return -1; - if (channel_num < I2S_CHANNEL_0 || channel_num > I2S_CHANNEL_3) - return -1; - - u_rcr.reg_data = readl(&i2s[device_num]->channel[channel_num].rcr); - u_rcr.rcr_tcr.wlen = word_length; - writel(u_rcr.reg_data, &i2s[device_num]->channel[channel_num].rcr); - return 0; -} - -static int i2s_set_tx_word_length(i2s_device_number_t device_num, - i2s_word_length_t word_length, - i2s_channel_num_t channel_num) -{ - rcr_tcr_t u_tcr; - - if (word_length > RESOLUTION_32_BIT || word_length < IGNORE_WORD_LENGTH) - return -1; - if (channel_num < I2S_CHANNEL_0 || channel_num > I2S_CHANNEL_3) - return -1; - - u_tcr.reg_data = readl(&i2s[device_num]->channel[channel_num].tcr); - u_tcr.rcr_tcr.wlen = word_length; - writel(u_tcr.reg_data, &i2s[device_num]->channel[channel_num].tcr); - return 0; -} - -static void i2s_master_configure(i2s_device_number_t device_num, - i2s_word_select_cycles_t word_select_size, - i2s_sclk_gating_cycles_t gating_cycles, - i2s_work_mode_t word_mode) -{ - configASSERT(!(word_select_size < SCLK_CYCLES_16 || - word_select_size > SCLK_CYCLES_32)); - configASSERT(!(gating_cycles < NO_CLOCK_GATING || - gating_cycles > CLOCK_CYCLES_24)); - - ccr_t u_ccr; - cer_t u_cer; - - u_ccr.reg_data = readl(&i2s[device_num]->ccr); - u_ccr.ccr.clk_word_size = word_select_size; - u_ccr.ccr.clk_gate = gating_cycles; - u_ccr.ccr.align_mode = word_mode; - writel(u_ccr.reg_data, &i2s[device_num]->ccr); - - u_cer.reg_data = readl(&i2s[device_num]->cer); - u_cer.cer.clken = 1; - writel(u_cer.reg_data, &i2s[device_num]->cer); - /* Clock generation enable */ - -} - -static int i2s_set_rx_threshold(i2s_device_number_t device_num, - i2s_fifo_threshold_t threshold, - i2s_channel_num_t channel_num) -{ - rfcr_t u_rfcr; - - if (threshold < TRIGGER_LEVEL_1 || threshold > TRIGGER_LEVEL_16) - return -1; - if (channel_num < I2S_CHANNEL_0 || channel_num > I2S_CHANNEL_3) - return -1; - - u_rfcr.reg_data = readl(&i2s[device_num]->channel[channel_num].rfcr); - u_rfcr.rfcr.rxchdt = threshold; - writel(u_rfcr.reg_data, &i2s[device_num]->channel[channel_num].rfcr); - - return 0; -} - -static int i2s_set_tx_threshold(i2s_device_number_t device_num, - i2s_fifo_threshold_t threshold, - i2s_channel_num_t channel_num) -{ - tfcr_t u_tfcr; - - if (threshold < TRIGGER_LEVEL_1 || threshold > TRIGGER_LEVEL_16) - return -1; - if (channel_num < I2S_CHANNEL_0 || channel_num > I2S_CHANNEL_3) - return -1; - - u_tfcr.reg_data = readl(&i2s[device_num]->channel[channel_num].tfcr); - u_tfcr.tfcr.txchet = threshold; - writel(u_tfcr.reg_data, &i2s[device_num]->channel[channel_num].tfcr); - return 0; -} - -static int i2s_set_mask_interrupt(i2s_device_number_t device_num, - i2s_channel_num_t channel_num, - uint32_t rx_available_int, uint32_t rx_overrun_int, - uint32_t tx_empty_int, uint32_t tx_overrun_int) -{ - imr_t u_imr; - - if (channel_num < I2S_CHANNEL_0 || channel_num > I2S_CHANNEL_3) - return -1; - u_imr.reg_data = readl(&i2s[device_num]->channel[channel_num].imr); - - if (rx_available_int == 1) - u_imr.imr.rxdam = 1; - else - u_imr.imr.rxdam = 0; - if (rx_overrun_int == 1) - u_imr.imr.rxfom = 1; - else - u_imr.imr.rxfom = 0; - - if (tx_empty_int == 1) - u_imr.imr.txfem = 1; - else - u_imr.imr.txfem = 0; - if (tx_overrun_int == 1) - u_imr.imr.txfom = 1; - else - u_imr.imr.txfom = 0; - writel(u_imr.reg_data, &i2s[device_num]->channel[channel_num].imr); - return 0; -} - -static int i2s_transmit_dma_enable(i2s_device_number_t device_num, uint32_t enable) -{ - ccr_t u_ccr; - - if (device_num >= I2S_DEVICE_MAX) - return -1; - - u_ccr.reg_data = readl(&i2s[device_num]->ccr); - u_ccr.ccr.dma_tx_en = enable; - writel(u_ccr.reg_data, &i2s[device_num]->ccr); - - return 0; -} - -static int i2s_receive_dma_enable(i2s_device_number_t device_num, uint32_t enable) -{ - ccr_t u_ccr; - - if (device_num >= I2S_DEVICE_MAX) - return -1; - - u_ccr.reg_data = readl(&i2s[device_num]->ccr); - u_ccr.ccr.dma_rx_en = enable; - writel(u_ccr.reg_data, &i2s[device_num]->ccr); - - return 0; -} - -int i2s_set_dma_divide_16(i2s_device_number_t device_num, uint32_t enable) -{ - ccr_t u_ccr; - - if (device_num >= I2S_DEVICE_MAX) - return -1; - - u_ccr.reg_data = readl(&i2s[device_num]->ccr); - u_ccr.ccr.dma_divide_16 = enable; - writel(u_ccr.reg_data, &i2s[device_num]->ccr); - - return 0; -} - -int i2s_get_dma_divide_16(i2s_device_number_t device_num) -{ - if (device_num >= I2S_DEVICE_MAX) - return -1; - ccr_t u_ccr; - u_ccr.reg_data = readl(&i2s[device_num]->ccr); - return u_ccr.ccr.dma_divide_16; -} - -int i2s_receive_data(i2s_device_number_t device_num, i2s_channel_num_t channel_num, uint64_t *buf, size_t buf_len) -{ - uint32_t i = 0; - isr_t u_isr; - - readl(&i2s[device_num]->channel[channel_num].ror); - /*clear over run*/ - - for (i = 0; i < buf_len;) - { - u_isr.reg_data = readl(&i2s[device_num]->channel[channel_num].isr); - if (u_isr.isr.rxda == 1) - { - buf[i] = readl(&i2s[device_num]->channel[channel_num].left_rxtx); - buf[i] <<= 32; - buf[i++] |= readl(&i2s[device_num]->channel[channel_num].right_rxtx); - } - } - return 0; -} - -void i2s_receive_data_dma(i2s_device_number_t device_num, uint32_t *buf, - size_t buf_len, dmac_channel_number_t channel_num) -{ - dmac_wait_idle(channel_num); - sysctl_dma_select((sysctl_dma_channel_t)channel_num, SYSCTL_DMA_SELECT_I2S0_RX_REQ + device_num * 2); - dmac_set_single_mode(channel_num, (void *)(&i2s[device_num]->rxdma), buf, DMAC_ADDR_NOCHANGE, DMAC_ADDR_INCREMENT, - DMAC_MSIZE_1, DMAC_TRANS_WIDTH_32, buf_len); -} - -int i2s_rx_to_tx(i2s_device_number_t device_src_num, i2s_device_number_t device_dest_num, - size_t buf_len, dmac_channel_number_t channel_num) -{ - static uint8_t dmac_recv_flag[6] = {0,0,0,0,0,0}; - if(dmac_recv_flag[channel_num]) - dmac_wait_done(channel_num); - else - dmac_recv_flag[channel_num] = 1; - sysctl_dma_select((sysctl_dma_channel_t)channel_num, SYSCTL_DMA_SELECT_I2S0_RX_REQ + device_src_num * 2); - dmac_set_single_mode(channel_num, (void *)(&i2s[device_src_num]->rxdma), (void *)(&i2s[device_dest_num]->txdma), DMAC_ADDR_NOCHANGE, DMAC_ADDR_NOCHANGE, - DMAC_MSIZE_1, DMAC_TRANS_WIDTH_32, buf_len); - return 0; -} - -int i2s_send_data(i2s_device_number_t device_num, i2s_channel_num_t channel_num, const uint8_t *pcm, size_t buf_len, - size_t single_length) -{ - isr_t u_isr; - uint32_t left_buffer = 0; - uint32_t right_buffer = 0; - uint32_t i = 0; - uint32_t j = 0; - if (channel_num < I2S_CHANNEL_0 || channel_num > I2S_CHANNEL_3) - return -1; - - buf_len = buf_len / (single_length / 8) / 2; /* sample num */ - readl(&i2s[device_num]->channel[channel_num].tor); - /* read clear overrun flag */ - - for (j = 0; j < buf_len;) - { - u_isr.reg_data = readl(&i2s[device_num]->channel[channel_num].isr); - if (u_isr.isr.txfe == 1) - { - switch(single_length) - { - case 16: - left_buffer = ((uint16_t *)pcm)[i++]; - right_buffer = ((uint16_t *)pcm)[i++]; - break; - case 24: - left_buffer = 0; - left_buffer |= pcm[i++]; - left_buffer |= pcm[i++] << 8; - left_buffer |= pcm[i++] << 16; - right_buffer = 0; - right_buffer |= pcm[i++]; - right_buffer |= pcm[i++] << 8; - right_buffer |= pcm[i++] << 16; - break; - case 32: - left_buffer = ((uint32_t *)pcm)[i++]; - right_buffer = ((uint32_t *)pcm)[i++]; - break; - default: - left_buffer = pcm[i++]; - right_buffer = pcm[i++]; - break; - } - writel(left_buffer, &i2s[device_num]->channel[channel_num].left_rxtx); - writel(right_buffer, &i2s[device_num]->channel[channel_num].right_rxtx); - j++; - } - } - return 0; -} - -void i2s_send_data_dma(i2s_device_number_t device_num, const void *buf, size_t buf_len, dmac_channel_number_t channel_num) -{ - - dmac_wait_idle(channel_num); - sysctl_dma_select((sysctl_dma_channel_t)channel_num, SYSCTL_DMA_SELECT_I2S0_TX_REQ + device_num * 2); - dmac_set_single_mode(channel_num, buf, (void *)(&i2s[device_num]->txdma), DMAC_ADDR_INCREMENT, - DMAC_ADDR_NOCHANGE, DMAC_MSIZE_1, DMAC_TRANS_WIDTH_32, buf_len); -} - -static void i2s_parse_voice(i2s_device_number_t device_num, uint32_t *buf, const uint8_t *pcm, size_t length, size_t bits_per_sample, - uint8_t track_num, size_t *send_len) -{ - uint32_t i,j=0; - *send_len = length * 2; - switch(bits_per_sample) - { - case 16: - for(i = 0; i < length; i++) - { - buf[2*i] = ((uint16_t *)pcm)[i]; - buf[2*i+1] = 0; - } - break; - case 24: - for(i = 0; i < length; i++) - { - buf[2*i] = 0; - buf[2*i] |= pcm[j++]; - buf[2*i] |= pcm[j++] << 8; - buf[2*i] |= pcm[j++] << 16; - buf[2*i+1] = 0; - if(track_num == 2) - { - buf[2*i+1] |= pcm[j++]; - buf[2*i+1] |= pcm[j++] << 8; - buf[2*i+1] |= pcm[j++] << 16; - } - } - break; - case 32: - default: - for(i = 0; i < length; i++) - { - buf[2*i] = ((uint32_t *)pcm)[i]; - buf[2*i+1] = 0; - } - break; - } -} - - -void i2s_play(i2s_device_number_t device_num, dmac_channel_number_t channel_num, - const uint8_t *buf, size_t buf_len, size_t frame, size_t bits_per_sample, uint8_t track_num) -{ - const uint8_t *trans_buf; - uint32_t i; - size_t sample_cnt = buf_len / ( bits_per_sample / 8 ) / track_num; - size_t frame_cnt = sample_cnt / frame; - size_t frame_remain = sample_cnt % frame; - i2s_set_dma_divide_16(device_num, 0); - - if (bits_per_sample == 16 && track_num == 2) - { - i2s_set_dma_divide_16(device_num, 1); - for (i = 0; i < frame_cnt; i++) - { - trans_buf = buf + i * frame * (bits_per_sample / 8) * track_num; - i2s_send_data_dma(device_num,trans_buf, frame, channel_num); - } - if(frame_remain) - { - trans_buf = buf + frame_cnt * frame * (bits_per_sample / 8) * track_num; - i2s_send_data_dma(device_num, trans_buf, frame_remain, channel_num); - } - } - else if (bits_per_sample == 32 && track_num == 2) - { - for (i = 0; i < frame_cnt; i++) - { - trans_buf = buf + i * frame * (bits_per_sample / 8) * track_num; - i2s_send_data_dma(device_num,trans_buf, frame * 2, channel_num); - } - if(frame_remain) - { - trans_buf = buf + frame_cnt * frame * (bits_per_sample / 8) * track_num; - i2s_send_data_dma(device_num, trans_buf, frame_remain * 2, channel_num); - } - } - else - { - uint32_t *buff[2]; - buff[0] = malloc(frame * 2 * sizeof(uint32_t) * 2); - buff[1] = buff[0] + frame * 2; - uint8_t flag = 0; - size_t send_len = 0; - for (i = 0; i < frame_cnt; i++) - { - trans_buf = buf + i * frame * (bits_per_sample / 8) * track_num; - i2s_parse_voice(device_num, buff[flag], trans_buf, frame, bits_per_sample, track_num, &send_len); - i2s_send_data_dma(device_num,buff[flag], send_len, channel_num); - flag = !flag; - } - if (frame_remain) - { - trans_buf = buf + frame_cnt * frame * (bits_per_sample / 8) * track_num; - i2s_parse_voice(device_num, buff[flag], trans_buf, frame_remain, bits_per_sample, track_num, &send_len); - i2s_send_data_dma(device_num, trans_buf, send_len, channel_num); - } - free(buff[0]); - } -} - -static inline void i2s_set_sign_expand_en(i2s_device_number_t device_num, uint32_t enable) -{ - ccr_t u_ccr; - u_ccr.reg_data = readl(&i2s[device_num]->ccr); - u_ccr.ccr.sign_expand_en = enable; - writel(u_ccr.reg_data, &i2s[device_num]->ccr); -} - -void i2s_rx_channel_config(i2s_device_number_t device_num, - i2s_channel_num_t channel_num, - i2s_word_length_t word_length, - i2s_word_select_cycles_t word_select_size, - i2s_fifo_threshold_t trigger_level, - i2s_work_mode_t word_mode) -{ - i2s_recv_channel_enable(device_num, channel_num, 0); - /* Receive channel disable */ - - writel(0, &i2s[device_num]->channel[channel_num].ter); - /* disable tx */ - - writel(1, &i2s[device_num]->channel[channel_num].rff); - /* flash individual fifo */ - - writel(1, &i2s[device_num]->rxffr); - /* flush tx fifo*/ - - i2s_set_rx_word_length(device_num, word_length, channel_num); - /* Word buf_len is RESOLUTION_32_BIT */ - - i2s_master_configure(device_num, - word_select_size, NO_CLOCK_GATING, word_mode); - /* word select size is 32 bits,no clock gating */ - - i2s_set_rx_threshold(device_num, trigger_level, channel_num); - /* Interrupt trigger when FIFO level is 8 */ - - readl(&i2s[device_num]->channel[channel_num].ror); - readl(&i2s[device_num]->channel[channel_num].tor); - - i2s_recv_channel_enable(device_num, channel_num, 1); -} - -void i2s_tx_channel_config(i2s_device_number_t device_num, - i2s_channel_num_t channel_num, - i2s_word_length_t word_length, - i2s_word_select_cycles_t word_select_size, - i2s_fifo_threshold_t trigger_level, - i2s_work_mode_t word_mode) -{ - writel(0, &i2s[device_num]->channel[channel_num].rer); - /* disable rx */ - - i2s_transmit_channel_enable(device_num, channel_num, 0); - /* Transmit channel disable */ - - writel(1, &i2s[device_num]->txffr); - /* flush tx fifo */ - writel(1, &i2s[device_num]->channel[channel_num].tff); - /* flush individual fifo */ - - i2s_set_tx_word_length(device_num, word_length, channel_num); - /* Word buf_len is RESOLUTION_16_BIT */ - - i2s_master_configure(device_num, word_select_size, NO_CLOCK_GATING, word_mode); - /* word select size is 16 bits,gating after 16 bit */ - - i2s_set_tx_threshold(device_num, trigger_level, channel_num); - /* Interrupt trigger when FIFO level is 8 */ - - i2s_transmit_channel_enable(device_num, channel_num, 1); -} - - -void i2s_init(i2s_device_number_t device_num, i2s_transmit_t rxtx_mode, uint32_t channel_mask) -{ - sysctl_clock_enable(SYSCTL_CLOCK_I2S0 + device_num); - sysctl_reset(SYSCTL_RESET_I2S0 + device_num); - sysctl_clock_set_threshold(SYSCTL_THRESHOLD_I2S0 + device_num, 7); - /*96k:5,44k:12,24k:23,22k:25 16k:35 sampling*/ - /*sample rate*32bit*2 =75MHz/((N+1)*2) */ - i2s_set_enable(device_num, 1); - i2s_disable_block(device_num, I2S_TRANSMITTER); - i2s_disable_block(device_num, I2S_RECEIVER); - - if (rxtx_mode == I2S_TRANSMITTER) - { - for (int i=0; i<4; i++) - { - if ((channel_mask & 0x3) == 0x3) - { - i2s_set_mask_interrupt(device_num, I2S_CHANNEL_0 + i, 1, 1, 1, 1); - i2s_transimit_enable(device_num, I2S_CHANNEL_0 + i); - } - else - { - i2s_transmit_channel_enable(device_num, I2S_CHANNEL_0 + i, 0); - } - channel_mask >>= 2; - } - i2s_transmit_dma_enable(device_num, 1); - } - else - { - for (int i=0; i<4; i++) - { - if ((channel_mask & 0x3) == 0x3) - { - i2s_set_mask_interrupt(device_num, I2S_CHANNEL_0 + i, 1, 1, 1, 1); - i2s_receive_enable(device_num, I2S_CHANNEL_0 + i); - } - else - { - i2s_recv_channel_enable(device_num, I2S_CHANNEL_0 + i, 0); - } - channel_mask >>= 2; - } - /* Set expand_en when receive */ - i2s_set_sign_expand_en(device_num, 1); - i2s_receive_dma_enable(device_num, 1); - } -} - -uint32_t i2s_set_sample_rate(i2s_device_number_t device_num, uint32_t sample_rate) -{ - ccr_t u_ccr; - uint32_t pll2_clock = 0; - pll2_clock = sysctl_pll_get_freq(SYSCTL_PLL2); - - u_ccr.reg_data = readl(&i2s[device_num]->ccr); - /* 0x0 for 16sclk cycles, 0x1 for 24 sclk cycles 0x2 for 32 sclk */ - uint32_t v_clk_word_size = (u_ccr.ccr.clk_word_size + 2) * 8; - uint32_t threshold = round(pll2_clock / (sample_rate * 2.0 * v_clk_word_size * 2.0) - 1); - sysctl_clock_set_threshold(SYSCTL_THRESHOLD_I2S0 + device_num, threshold); - return sysctl_clock_get_freq(SYSCTL_CLOCK_I2S0 + device_num); -} - diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/aes.h b/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/aes.h deleted file mode 100644 index 97085d0..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/aes.h +++ /dev/null @@ -1,767 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef _DRIVER_AES_H -#define _DRIVER_AES_H -#include -#include -#include "platform.h" -#include "dmac.h" - -#ifdef __cplusplus -extern "C" { -#endif - -typedef enum _aes_cipher_mode -{ - AES_ECB = 0, - AES_CBC = 1, - AES_GCM = 2, - AES_CIPHER_MAX, -} aes_cipher_mode_t; - -typedef enum _aes_kmode -{ - AES_128 = 16, - AES_192 = 24, - AES_256 = 32, -} aes_kmode_t; - -typedef enum _aes_iv_len -{ - IV_LEN_96 = 12, - IV_LEN_128 = 16, -} aes_iv_len_t; - -typedef enum _aes_encrypt_sel -{ - AES_HARD_ENCRYPTION = 0, - AES_HARD_DECRYPTION = 1, -} aes_encrypt_sel_t; - -typedef struct _aes_mode_ctl -{ - /* [2:0]:000:ecb; 001:cbc,010:gcm */ - uint32_t cipher_mode : 3; - /* [4:3]:00:aes-128; 01:aes-192; 10:aes-256;11:reserved*/ - uint32_t kmode : 2; - /* [6:5]:input key order 1:little endian; 0: big endian */ - uint32_t key_order : 2; - /* [8:7]:input data order 1:little endian; 0: big endian */ - uint32_t input_order : 2; - /* [10:9]:output data order 1:little endian; 0: big endian */ - uint32_t output_order : 2; - uint32_t reserved : 21; -} __attribute__((packed, aligned(4))) aes_mode_ctl_t; - -/** - * @brief AES - */ -typedef struct _aes -{ - /* (0x00) customer key.1st~4th byte key */ - uint32_t aes_key[4]; - /* (0x10) 0: encryption; 1: decryption */ - uint32_t encrypt_sel; - /* (0x14) aes mode reg */ - aes_mode_ctl_t mode_ctl; - /* (0x18) Initialisation Vector. GCM support 96bit. CBC support 128bit */ - uint32_t aes_iv[4]; - /* (0x28) input data endian;1:little endian; 0:big endian */ - uint32_t aes_endian; - /* (0x2c) calculate status. 1:finish; 0:not finish */ - uint32_t aes_finish; - /* (0x30) aes out data to dma 0:cpu 1:dma */ - uint32_t dma_sel; - /* (0x34) gcm Additional authenticated data number */ - uint32_t gb_aad_num; - uint32_t reserved; - /* (0x3c) aes plantext/ciphter text input data number */ - uint32_t gb_pc_num; - /* (0x40) aes plantext/ciphter text input data */ - uint32_t aes_text_data; - /* (0x44) Additional authenticated data */ - uint32_t aes_aad_data; - /** - * (0x48) [1:0],b'00:check not finish; b'01:check fail; b'10:check success; - * b'11:reversed - */ - uint32_t tag_chk; - /* (0x4c) data can input flag. 1: data can input; 0 : data cannot input */ - uint32_t data_in_flag; - /* (0x50) gcm input tag for compare with the calculate tag */ - uint32_t gcm_in_tag[4]; - /* (0x60) aes plantext/ciphter text output data */ - uint32_t aes_out_data; - /* (0x64) aes module enable */ - uint32_t gb_aes_en; - /* (0x68) data can output flag 1: data ready 0: data not ready */ - uint32_t data_out_flag; - /* (0x6c) allow tag input when use gcm */ - uint32_t tag_in_flag; - /* (0x70) clear tag_chk */ - uint32_t tag_clear; - uint32_t gcm_out_tag[4]; - /* (0x84) customer key for aes-192 aes-256.5th~8th byte key */ - uint32_t aes_key_ext[4]; -} __attribute__((packed, aligned(4))) aes_t; - -typedef struct _gcm_context -{ - /* The buffer holding the encryption or decryption key. */ - uint8_t *input_key; - /* The initialization vector. must be 96 bit */ - uint8_t *iv; - /* The buffer holding the Additional authenticated data. or NULL */ - uint8_t *gcm_aad; - /* The length of the Additional authenticated data. or 0L */ - size_t gcm_aad_len; -} gcm_context_t; - -typedef struct _cbc_context -{ - /* The buffer holding the encryption or decryption key. */ - uint8_t *input_key; - /* The initialization vector. must be 128 bit */ - uint8_t *iv; -} cbc_context_t; - -/** - * @brief AES-ECB-128 decryption - * - * @param[in] input_key The decryption key. must be 16bytes. - * @param[in] input_data The buffer holding the input data. - * @param[in] input_len The length of a data unit in bytes. - * This can be any length between 16 bytes and 2^31 bytes inclusive - * (between 1 and 2^27 block cipher blocks). - * @param[out] output_data The buffer holding the output data. - * The buffer size must be larger than the size after padding by 16 byte multiples. - */ -void aes_ecb128_hard_decrypt(uint8_t *input_key, uint8_t *input_data, size_t input_len, uint8_t *output_data); - -/** - * @brief AES-ECB-128 encryption - * - * @param[in] input_key The encryption key. must be 16bytes. - * @param[in] input_data The buffer holding the input data. - * @param[in] input_len The length of a data unit in bytes. - * This can be any length between 16 bytes and 2^31 bytes inclusive - * (between 1 and 2^27 block cipher blocks). - * @param[out] output_data The buffer holding the output data. - * The buffer size must be larger than the size after padding by 16 byte multiples. - */ -void aes_ecb128_hard_encrypt(uint8_t *input_key, uint8_t *input_data, size_t input_len, uint8_t *output_data); - -/** - * @brief AES-ECB-192 decryption - * - * @param[in] input_key The decryption key. must be 24bytes. - * @param[in] input_data The buffer holding the input data. - * @param[in] input_len The length of a data unit in bytes. - * This can be any length between 16 bytes and 2^31 bytes inclusive - * (between 1 and 2^27 block cipher blocks). - * @param[out] output_data The buffer holding the output data. - * The buffer size must be larger than the size after padding by 16 byte multiples. - */ -void aes_ecb192_hard_decrypt(uint8_t *input_key, uint8_t *input_data, size_t input_len, uint8_t *output_data); - -/** - * @brief AES-ECB-192 encryption - * - * @param[in] input_key The encryption key. must be 24bytes. - * @param[in] input_data The buffer holding the input data. - * @param[in] input_len The length of a data unit in bytes. - * This can be any length between 16 bytes and 2^31 bytes inclusive - * (between 1 and 2^27 block cipher blocks). - * @param[out] output_data The buffer holding the output data. - * The buffer size must be larger than the size after padding by 16 byte multiples. - */ -void aes_ecb192_hard_encrypt(uint8_t *input_key, uint8_t *input_data, size_t input_len, uint8_t *output_data); - -/** - * @brief AES-ECB-256 decryption - * - * @param[in] input_key The decryption key. must be 32bytes. - * @param[in] input_data The buffer holding the input data. - * @param[in] input_len The length of a data unit in bytes. - * This can be any length between 16 bytes and 2^31 bytes inclusive - * (between 1 and 2^27 block cipher blocks). - * @param[out] output_data The buffer holding the output data. - * The buffer size must be larger than the size after padding by 16 byte multiples. - */ -void aes_ecb256_hard_decrypt(uint8_t *input_key, uint8_t *input_data, size_t input_len, uint8_t *output_data); - -/** - * @brief AES-ECB-256 encryption - * - * @param[in] input_key The encryption key. must be 32bytes. - * @param[in] input_data The buffer holding the input data. - * @param[in] input_len The length of a data unit in bytes. - * This can be any length between 16 bytes and 2^31 bytes inclusive - * (between 1 and 2^27 block cipher blocks). - * @param[out] output_data The buffer holding the output data. - * The buffer size must be larger than the size after padding by 16 byte multiples. - */ -void aes_ecb256_hard_encrypt(uint8_t *input_key, uint8_t *input_data, size_t input_len, uint8_t *output_data); - -/** - * @brief AES-CBC-128 decryption - * - * @param[in] context The cbc context to use for encryption or decryption. - * @param[in] input_key The decryption key. must be 16bytes. - * @param[in] input_data The buffer holding the input data. - * @param[in] input_len The length of a data unit in bytes. - * This can be any length between 16 bytes and 2^31 bytes inclusive - * (between 1 and 2^27 block cipher blocks). - * @param[out] output_data The buffer holding the output data. - * The buffer size must be larger than the size after padding by 16 byte multiples. - */ -void aes_cbc128_hard_decrypt(cbc_context_t *context, uint8_t *input_data, size_t input_len, uint8_t *output_data); - -/** - * @brief AES-CBC-128 encryption - * - * @param[in] context The cbc context to use for encryption or decryption. - * @param[in] input_key The encryption key. must be 16bytes. - * @param[in] input_data The buffer holding the input data. - * @param[in] input_len The length of a data unit in bytes. - * This can be any length between 16 bytes and 2^31 bytes inclusive - * (between 1 and 2^27 block cipher blocks). - * @param[out] output_data The buffer holding the output data. - * The buffer size must be larger than the size after padding by 16 byte multiples. - */ -void aes_cbc128_hard_encrypt(cbc_context_t *context, uint8_t *input_data, size_t input_len, uint8_t *output_data); - -/** - * @brief AES-CBC-192 decryption - * - * @param[in] context The cbc context to use for encryption or decryption. - * @param[in] input_key The decryption key. must be 24bytes. - * @param[in] input_data The buffer holding the input data. - * @param[in] input_len The length of a data unit in bytes. - * This can be any length between 16 bytes and 2^31 bytes inclusive - * (between 1 and 2^27 block cipher blocks). - * @param[out] output_data The buffer holding the output data. - * The buffer size must be larger than the size after padding by 16 byte multiples. - */ -void aes_cbc192_hard_decrypt(cbc_context_t *context, uint8_t *input_data, size_t input_len, uint8_t *output_data); - -/** - * @brief AES-CBC-192 encryption - * - * @param[in] context The cbc context to use for encryption or decryption. - * @param[in] input_key The encryption key. must be 24bytes. - * @param[in] input_data The buffer holding the input data. - * @param[in] input_len The length of a data unit in bytes. - * This can be any length between 16 bytes and 2^31 bytes inclusive - * (between 1 and 2^27 block cipher blocks). - * @param[out] output_data The buffer holding the output data. - * The buffer size must be larger than the size after padding by 16 byte multiples. - */ -void aes_cbc192_hard_encrypt(cbc_context_t *context, uint8_t *input_data, size_t input_len, uint8_t *output_data); - -/** - * @brief AES-CBC-256 decryption - * - * @param[in] context The cbc context to use for encryption or decryption. - * @param[in] input_key The decryption key. must be 32bytes. - * @param[in] input_data The buffer holding the input data. - * @param[in] input_len The length of a data unit in bytes. - * This can be any length between 16 bytes and 2^31 bytes inclusive - * (between 1 and 2^27 block cipher blocks). - * @param[out] output_data The buffer holding the output data. - * The buffer size must be larger than the size after padding by 16 byte multiples. - */ -void aes_cbc256_hard_decrypt(cbc_context_t *context, uint8_t *input_data, size_t input_len, uint8_t *output_data); - -/** - * @brief AES-CBC-256 encryption - * - * @param[in] context The cbc context to use for encryption or decryption. - * @param[in] input_key The encryption key. must be 32bytes. - * @param[in] input_data The buffer holding the input data. - * @param[in] input_len The length of a data unit in bytes. - * This can be any length between 16 bytes and 2^31 bytes inclusive - * (between 1 and 2^27 block cipher blocks). - * @param[out] output_data The buffer holding the output data. - * The buffer size must be larger than the size after padding by 16 byte multiples. - */ -void aes_cbc256_hard_encrypt(cbc_context_t *context, uint8_t *input_data, size_t input_len, uint8_t *output_data); - -/** - * @brief AES-GCM-128 decryption - * - * @param[in] context The gcm context to use for encryption or decryption. - * @param[in] input_key The decryption key. must be 16bytes. - * @param[in] input_data The buffer holding the input data. - * @param[in] input_len The length of a data unit in bytes. - * This can be any length between 16 bytes and 2^31 bytes inclusive - * (between 1 and 2^27 block cipher blocks). - * @param[out] output_data The buffer holding the output data. - * @param[out] gcm_tag The buffer for holding the tag.The length of the tag must be 4 bytes. - */ -void aes_gcm128_hard_decrypt(gcm_context_t *context, uint8_t *input_data, size_t input_len, uint8_t *output_data, uint8_t *gcm_tag); - -/** - * @brief AES-GCM-128 encryption - * - * @param[in] context The gcm context to use for encryption or decryption. - * @param[in] input_key The encryption key. must be 16bytes. - * @param[in] input_data The buffer holding the input data. - * @param[in] input_len The length of a data unit in bytes. - * This can be any length between 16 bytes and 2^31 bytes inclusive - * (between 1 and 2^27 block cipher blocks). - * @param[out] output_data The buffer holding the output data. - * @param[out] gcm_tag The buffer for holding the tag.The length of the tag must be 4 bytes. - */ -void aes_gcm128_hard_encrypt(gcm_context_t *context, uint8_t *input_data, size_t input_len, uint8_t *output_data, uint8_t *gcm_tag); - -/** - * @brief AES-GCM-192 decryption - * - * @param[in] context The gcm context to use for encryption or decryption. - * @param[in] input_key The decryption key. must be 24bytes. - * @param[in] input_data The buffer holding the input data. - * @param[in] input_len The length of a data unit in bytes. - * This can be any length between 16 bytes and 2^31 bytes inclusive - * (between 1 and 2^27 block cipher blocks). - * @param[out] output_data The buffer holding the output data. - * @param[out] gcm_tag The buffer for holding the tag.The length of the tag must be 4 bytes. - */ -void aes_gcm192_hard_decrypt(gcm_context_t *context, uint8_t *input_data, size_t input_len, uint8_t *output_data, uint8_t *gcm_tag); - -/** - * @brief AES-GCM-192 encryption - * - * @param[in] context The gcm context to use for encryption or decryption. - * @param[in] input_key The encryption key. must be 24bytes. - * @param[in] input_data The buffer holding the input data. - * @param[in] input_len The length of a data unit in bytes. - * This can be any length between 16 bytes and 2^31 bytes inclusive - * (between 1 and 2^27 block cipher blocks). - * @param[out] output_data The buffer holding the output data. - * @param[out] gcm_tag The buffer for holding the tag.The length of the tag must be 4 bytes. - */ -void aes_gcm192_hard_encrypt(gcm_context_t *context, uint8_t *input_data, size_t input_len, uint8_t *output_data, uint8_t *gcm_tag); - -/** - * @brief AES-GCM-256 decryption - * - * @param[in] context The gcm context to use for encryption or decryption. - * @param[in] input_key The decryption key. must be 32bytes. - * @param[in] input_data The buffer holding the input data. - * @param[in] input_len The length of a data unit in bytes. - * This can be any length between 16 bytes and 2^31 bytes inclusive - * (between 1 and 2^27 block cipher blocks). - * @param[out] output_data The buffer holding the output data. - * @param[out] gcm_tag The buffer for holding the tag.The length of the tag must be 4 bytes. - */ -void aes_gcm256_hard_decrypt(gcm_context_t *context, uint8_t *input_data, size_t input_len, uint8_t *output_data, uint8_t *gcm_tag); - -/** - * @brief AES-GCM-256 encryption - * - * @param[in] context The gcm context to use for encryption or decryption. - * @param[in] input_key The encryption key. must be 32bytes. - * @param[in] input_data The buffer holding the input data. - * @param[in] input_len The length of a data unit in bytes. - * This can be any length between 16 bytes and 2^31 bytes inclusive - * (between 1 and 2^27 block cipher blocks). - * @param[out] output_data The buffer holding the output data. - * @param[out] gcm_tag The buffer for holding the tag.The length of the tag must be 4 bytes. - */ -void aes_gcm256_hard_encrypt(gcm_context_t *context, uint8_t *input_data, size_t input_len, uint8_t *output_data, uint8_t *gcm_tag); - -/** - * @brief AES-ECB-128 decryption by dma - * - * @param[in] dma_receive_channel_num Dmac receive channel number. - * @param[in] input_key The decryption key. must be 16bytes. - * @param[in] input_data The buffer holding the input data. - * @param[in] input_len The length of a data unit in bytes. - * This can be any length between 16 bytes and 2^31 bytes inclusive - * (between 1 and 2^27 block cipher blocks). - * @param[out] output_data The buffer holding the output data. - * The buffer size must be larger than the size after padding by 16 byte multiples. - */ -void aes_ecb128_hard_decrypt_dma(dmac_channel_number_t dma_receive_channel_num, - uint8_t *input_key, - uint8_t *input_data, - size_t input_len, - uint8_t *output_data); - -/** - * @brief AES-ECB-128 encryption by dma - * - * @param[in] dma_receive_channel_num Dmac receive channel number. - * @param[in] input_key The encryption key. must be 16bytes. - * @param[in] input_data The buffer holding the input data. - * @param[in] input_len The length of a data unit in bytes. - * This can be any length between 16 bytes and 2^31 bytes inclusive - * (between 1 and 2^27 block cipher blocks). - * @param[out] output_data The buffer holding the output data. - * The buffer size must be larger than the size after padding by 16 byte multiples. - */ -void aes_ecb128_hard_encrypt_dma(dmac_channel_number_t dma_receive_channel_num, - uint8_t *input_key, - uint8_t *input_data, - size_t input_len, - uint8_t *output_data); - -/** - * @brief AES-ECB-192 decryption by dma - * - * @param[in] dma_receive_channel_num Dmac receive channel number. - * @param[in] input_key The decryption key. must be 16bytes. - * @param[in] input_data The buffer holding the input data. - * @param[in] input_len The length of a data unit in bytes. - * This can be any length between 16 bytes and 2^31 bytes inclusive - * (between 1 and 2^27 block cipher blocks). - * @param[out] output_data The buffer holding the output data. - * The buffer size must be larger than the size after padding by 16 byte multiples. - */ -void aes_ecb192_hard_decrypt_dma(dmac_channel_number_t dma_receive_channel_num, - uint8_t *input_key, - uint8_t *input_data, - size_t input_len, - uint8_t *output_data); - -/** - * @brief AES-ECB-192 encryption by dma - * - * @param[in] dma_receive_channel_num Dmac receive channel number. - * @param[in] input_key The encryption key. must be 16bytes. - * @param[in] input_data The buffer holding the input data. - * @param[in] input_len The length of a data unit in bytes. - * This can be any length between 16 bytes and 2^31 bytes inclusive - * (between 1 and 2^27 block cipher blocks). - * @param[out] output_data The buffer holding the output data. - * The buffer size must be larger than the size after padding by 16 byte multiples. - */ -void aes_ecb192_hard_encrypt_dma(dmac_channel_number_t dma_receive_channel_num, - uint8_t *input_key, - uint8_t *input_data, - size_t input_len, - uint8_t *output_data); - -/** - * @brief AES-ECB-256 decryption by dma - * - * @param[in] dma_receive_channel_num Dmac receive channel number. - * @param[in] input_key The decryption key. must be 16bytes. - * @param[in] input_data The buffer holding the input data. - * @param[in] input_len The length of a data unit in bytes. - * This can be any length between 16 bytes and 2^31 bytes inclusive - * (between 1 and 2^27 block cipher blocks). - * @param[out] output_data The buffer holding the output data. - * The buffer size must be larger than the size after padding by 16 byte multiples. - */ -void aes_ecb256_hard_decrypt_dma(dmac_channel_number_t dma_receive_channel_num, - uint8_t *input_key, - uint8_t *input_data, - size_t input_len, - uint8_t *output_data); - -/** - * @brief AES-ECB-256 encryption by dma - * - * @param[in] dma_receive_channel_num Dmac receive channel number. - * @param[in] input_key The encryption key. must be 16bytes. - * @param[in] input_data The buffer holding the input data. - * @param[in] input_len The length of a data unit in bytes. - * This can be any length between 16 bytes and 2^31 bytes inclusive - * (between 1 and 2^27 block cipher blocks). - * @param[out] output_data The buffer holding the output data. - * The buffer size must be larger than the size after padding by 16 byte multiples. - */ -void aes_ecb256_hard_encrypt_dma(dmac_channel_number_t dma_receive_channel_num, - uint8_t *input_key, - uint8_t *input_data, - size_t input_len, - uint8_t *output_data); - -/** - * @brief AES-CBC-128 decryption - * - * @param[in] dma_receive_channel_num Dmac receive channel number. - * @param[in] context The cbc context to use for encryption or decryption. - * @param[in] input_key The encryption key. must be 24bytes. - * @param[in] input_data The buffer holding the input data. - * @param[in] input_len The length of a data unit in bytes. - * This can be any length between 16 bytes and 2^31 bytes inclusive - * (between 1 and 2^27 block cipher blocks). - * @param[out] output_data The buffer holding the output data. - * The buffer size must be larger than the size after padding by 16 byte multiples. - */ -void aes_cbc128_hard_decrypt_dma(dmac_channel_number_t dma_receive_channel_num, - cbc_context_t *context, - uint8_t *input_data, - size_t input_len, - uint8_t *output_data); - -/** - * @brief AES-CBC-128 encryption - * - * @param[in] dma_receive_channel_num Dmac receive channel number. - * @param[in] context The cbc context to use for encryption or decryption. - * @param[in] input_key The encryption key. must be 24bytes. - * @param[in] input_data The buffer holding the input data. - * @param[in] input_len The length of a data unit in bytes. - * This can be any length between 16 bytes and 2^31 bytes inclusive - * (between 1 and 2^27 block cipher blocks). - * @param[out] output_data The buffer holding the output data. - * The buffer size must be larger than the size after padding by 16 byte multiples. - */ -void aes_cbc128_hard_encrypt_dma(dmac_channel_number_t dma_receive_channel_num, - cbc_context_t *context, - uint8_t *input_data, - size_t input_len, - uint8_t *output_data); - -/** - * @brief AES-CBC-192 decryption - * - * @param[in] dma_receive_channel_num Dmac receive channel number. - * @param[in] context The cbc context to use for encryption or decryption. - * @param[in] input_key The decryption key. must be 24bytes. - * @param[in] input_data The buffer holding the input data. - * @param[in] input_len The length of a data unit in bytes. - * This can be any length between 16 bytes and 2^31 bytes inclusive - * (between 1 and 2^27 block cipher blocks). - * @param[out] output_data The buffer holding the output data. - * The buffer size must be larger than the size after padding by 16 byte multiples. - */ -void aes_cbc192_hard_decrypt_dma(dmac_channel_number_t dma_receive_channel_num, - cbc_context_t *context, - uint8_t *input_data, - size_t input_len, - uint8_t *output_data); - -/** - * @brief AES-CBC-192 encryption - * - * @param[in] dma_receive_channel_num Dmac receive channel number. - * @param[in] context The cbc context to use for encryption or decryption. - * @param[in] input_key The encryption key. must be 24bytes. - * @param[in] input_data The buffer holding the input data. - * @param[in] input_len The length of a data unit in bytes. - * This can be any length between 16 bytes and 2^31 bytes inclusive - * (between 1 and 2^27 block cipher blocks). - * @param[out] output_data The buffer holding the output data. - * The buffer size must be larger than the size after padding by 16 byte multiples. - */ -void aes_cbc192_hard_encrypt_dma(dmac_channel_number_t dma_receive_channel_num, - cbc_context_t *context, - uint8_t *input_data, - size_t input_len, - uint8_t *output_data); - -/** - * @brief AES-CBC-256 decryption - * - * @param[in] dma_receive_channel_num Dmac receive channel number. - * @param[in] context The cbc context to use for encryption or decryption. - * @param[in] input_key The decryption key. must be 24bytes. - * @param[in] input_data The buffer holding the input data. - * @param[in] input_len The length of a data unit in bytes. - * This can be any length between 16 bytes and 2^31 bytes inclusive - * (between 1 and 2^27 block cipher blocks). - * @param[out] output_data The buffer holding the output data. - * The buffer size must be larger than the size after padding by 16 byte multiples. - */ -void aes_cbc256_hard_decrypt_dma(dmac_channel_number_t dma_receive_channel_num, - cbc_context_t *context, - uint8_t *input_data, - size_t input_len, - uint8_t *output_data); - -/** - * @brief AES-CBC-256 encryption - * - * @param[in] dma_receive_channel_num Dmac receive channel number. - * @param[in] context The cbc context to use for encryption or decryption. - * @param[in] input_key The encryption key. must be 24bytes. - * @param[in] input_data The buffer holding the input data. - * @param[in] input_len The length of a data unit in bytes. - * This can be any length between 16 bytes and 2^31 bytes inclusive - * (between 1 and 2^27 block cipher blocks). - * @param[out] output_data The buffer holding the output data. - * The buffer size must be larger than the size after padding by 16 byte multiples. - */ -void aes_cbc256_hard_encrypt_dma(dmac_channel_number_t dma_receive_channel_num, - cbc_context_t *context, - uint8_t *input_data, - size_t input_len, - uint8_t *output_data); - -/** - * @brief AES-GCM-128 decryption - * - * @param[in] dma_receive_channel_num Dmac receive channel number. - * @param[in] context The gcm context to use for encryption or decryption. - * @param[in] input_key The decryption key. must be 16bytes. - * @param[in] input_data The buffer holding the input data. - * @param[in] input_len The length of a data unit in bytes. Must be 4 byte multiples. - * This can be any length between 16 bytes and 2^31 bytes inclusive - * (between 1 and 2^27 block cipher blocks). - * @param[out] output_data The buffer holding the output data. - * @param[out] gcm_tag The buffer for holding the tag.The length of the tag must be 4 bytes. - */ -void aes_gcm128_hard_decrypt_dma(dmac_channel_number_t dma_receive_channel_num, - gcm_context_t *context, - uint8_t *input_data, - size_t input_len, - uint8_t *output_data, - uint8_t *gcm_tag); - -/** - * @brief AES-GCM-128 encryption - * - * @param[in] dma_receive_channel_num Dmac receive channel number. - * @param[in] context The gcm context to use for encryption or decryption. - * @param[in] input_key The encryption key. must be 16bytes. - * @param[in] input_data The buffer holding the input data. - * @param[in] input_len The length of a data unit in bytes. Must be 4 byte multiples. - * This can be any length between 16 bytes and 2^31 bytes inclusive - * (between 1 and 2^27 block cipher blocks). - * @param[out] output_data The buffer holding the output data. - * @param[out] gcm_tag The buffer for holding the tag.The length of the tag must be 4 bytes. - */ -void aes_gcm128_hard_encrypt_dma(dmac_channel_number_t dma_receive_channel_num, - gcm_context_t *context, - uint8_t *input_data, - size_t input_len, - uint8_t *output_data, - uint8_t *gcm_tag); - -/** - * @brief AES-GCM-192 decryption - * - * @param[in] dma_receive_channel_num Dmac receive channel number. - * @param[in] context The gcm context to use for encryption or decryption. - * @param[in] input_key The decryption key. must be 16bytes. - * @param[in] input_data The buffer holding the input data. - * @param[in] input_len The length of a data unit in bytes. Must be 4 byte multiples. - * This can be any length between 16 bytes and 2^31 bytes inclusive - * (between 1 and 2^27 block cipher blocks). - * @param[out] output_data The buffer holding the output data. - * @param[out] gcm_tag The buffer for holding the tag.The length of the tag must be 4 bytes. - */ -void aes_gcm192_hard_decrypt_dma(dmac_channel_number_t dma_receive_channel_num, - gcm_context_t *context, - uint8_t *input_data, - size_t input_len, - uint8_t *output_data, - uint8_t *gcm_tag); - -/** - * @brief AES-GCM-192 encryption - * - * @param[in] dma_receive_channel_num Dmac receive channel number. - * @param[in] context The gcm context to use for encryption or decryption. - * @param[in] input_key The encryption key. must be 16bytes. - * @param[in] input_data The buffer holding the input data. - * @param[in] input_len The length of a data unit in bytes. Must be 4 byte multiples. - * This can be any length between 16 bytes and 2^31 bytes inclusive - * (between 1 and 2^27 block cipher blocks). - * @param[out] output_data The buffer holding the output data. - * @param[out] gcm_tag The buffer for holding the tag.The length of the tag must be 4 bytes. - */ -void aes_gcm192_hard_encrypt_dma(dmac_channel_number_t dma_receive_channel_num, - gcm_context_t *context, - uint8_t *input_data, - size_t input_len, - uint8_t *output_data, - uint8_t *gcm_tag); - -/** - * @brief AES-GCM-256 decryption - * - * @param[in] dma_receive_channel_num Dmac receive channel number. - * @param[in] context The gcm context to use for encryption or decryption. - * @param[in] input_key The decryption key. must be 16bytes. - * @param[in] input_data The buffer holding the input data. - * @param[in] input_len The length of a data unit in bytes. Must be 4 byte multiples. - * This can be any length between 16 bytes and 2^31 bytes inclusive - * (between 1 and 2^27 block cipher blocks). - * @param[out] output_data The buffer holding the output data. - * @param[out] gcm_tag The buffer for holding the tag.The length of the tag must be 4 bytes. - */ -void aes_gcm256_hard_decrypt_dma(dmac_channel_number_t dma_receive_channel_num, - gcm_context_t *context, - uint8_t *input_data, - size_t input_len, - uint8_t *output_data, - uint8_t *gcm_tag); - -/** - * @brief AES-GCM-256 encryption - * - * @param[in] dma_receive_channel_num Dmac receive channel number. - * @param[in] context The gcm context to use for encryption or decryption. - * @param[in] input_key The encryption key. must be 16bytes. - * @param[in] input_data The buffer holding the input data. - * @param[in] input_len The length of a data unit in bytes. Must be 4 byte multiples. - * This can be any length between 16 bytes and 2^31 bytes inclusive - * (between 1 and 2^27 block cipher blocks). - * @param[out] output_data The buffer holding the output data. - * @param[out] gcm_tag The buffer for holding the tag.The length of the tag must be 4 bytes. - */ -void aes_gcm256_hard_encrypt_dma(dmac_channel_number_t dma_receive_channel_num, - gcm_context_t *context, - uint8_t *input_data, - size_t input_len, - uint8_t *output_data, - uint8_t *gcm_tag); - -/** - * @brief This function initializes the AES hard module. - * - * @param[in] input_key The buffer holding the encryption or decryption key. - * @param[in] input_key_len The length of the input_key.must be 16bytes || 24bytes || 32bytes. - * @param[in] iv The initialization vector. - * @param[in] iv_len The length of the iv.GCM must be 12bytes. CBC must be 16bytes. ECB set 0L. - * @param[in] gcm_aad The buffer holding the Additional authenticated data. or NULL - * @param[in] cipher_mode Cipher Modes.must be AES_CBC || AES_ECB || AES_GCM. - * Other cipher modes, please look forward to the next generation of kendryte. - * @param[in] encrypt_sel The operation to perform:encryption or decryption. - * @param[in] gcm_aad_len The length of the gcm_aad. - * @param[in] input_data_len The length of the input_data. - */ -void aes_init(uint8_t *input_key, size_t input_key_len, uint8_t *iv,size_t iv_len, uint8_t *gcm_aad, - aes_cipher_mode_t cipher_mode, aes_encrypt_sel_t encrypt_sel, size_t gcm_aad_len, size_t input_data_len); - -/** - * @brief This function feeds an input buffer into an encryption or decryption operation. - * - * @param[in] input_data The buffer holding the input data. - * @param[out] output_data The buffer holding the output data. - * @param[in] input_data_len The length of the input_data. - * @param[in] cipher_mode Cipher Modes.must be AES_CBC || AES_ECB || AES_GCM. - * Other cipher modes, please look forward to the next generation of kendryte. - */ -void aes_process(uint8_t *input_data, uint8_t *output_data, size_t input_data_len, aes_cipher_mode_t cipher_mode); - -/** - * @brief This function get the gcm tag to verify. - * - * @param[out] gcm_tag The buffer holding the gcm tag.The length of the tag must be 16bytes. - */ -void gcm_get_tag(uint8_t *gcm_tag); - -#ifdef __cplusplus -} -#endif - -#endif /* _DRIVER_AES_H */ diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/apu.h b/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/apu.h deleted file mode 100644 index 5d4fef2..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/apu.h +++ /dev/null @@ -1,323 +0,0 @@ -#ifndef _apu_H_ -#define _apu_H_ - -#if defined(__cplusplus) -extern “C” { -#endif - -#define DIRECTION_RES 16 -#define I2S_FS 44100 -#define SOUND_SPEED 340 - -typedef enum en_bf_dir -{ - APU_DIR0 = 0, - APU_DIR1, - APU_DIR2, - APU_DIR3, - APU_DIR4, - APU_DIR5, - APU_DIR6, - APU_DIR7, - APU_DIR8, - APU_DIR9, - APU_DIR10, - APU_DIR11, - APU_DIR12, - APU_DIR13, - APU_DIR14, - APU_DIR15, -} en_bf_dir_t; - -typedef struct _apu_ch_cfg -{ - /** - * BF unit sound channel enable control bits. - * Bit 'x' corresponds to enable bit for sound channel 'x' (x = 0, 1, 2, - * . . ., 7). BF sound channels are related with I2S host RX channels. - * BF sound channel 0/1 correspond to the left/right channel of I2S RX0; - * BF channel 2/3 correspond to left/right channels of I2S RX1; and - * things like that. 0x1: writing '1' to enable the corresponding BF - * sound channel. 0x0: writing '0' to close the corresponding BF sound - * channel. - */ - uint32_t bf_sound_ch_en : 8; - /** - * Target direction select for valid voice output. - * When the source voice direaction searching is done, software can use - * this field to select one from 16 sound directions for the following - * voice recognition. 0x0: select sound direction 0; 0x1: select sound - * direction 1; . . . . . . 0xF: select sound direction 15. - */ - uint32_t bf_target_dir : 4; - /** - * This is the audio sample gain factor. Using this gain factor to - * enhance or reduce the stength of the sum of at most 8 source - * sound channel outputs. This is a unsigned 11-bit fix-point number, - * bit 10 is integer part and bit 9~0 are the fractional part. - */ - uint32_t audio_gain : 11; - uint32_t reserved1 : 1; - /** - * audio data source configure parameter. This parameter controls where - * the audio data source comes from. 0x0: audio data directly sourcing - * from apu internal buffer; 0x1: audio data sourcing from - * FFT result buffer. - */ - uint32_t data_src_mode : 1; - uint32_t reserved2 : 3; - /** - * write enable for bf_sound_ch_en parameter. - * 0x1: allowing updates made to 'bf_sound_ch_en'. - * Access Mode: write only - */ - uint32_t we_bf_sound_ch_en : 1; - /** - * write enable for bf_target_dir parameter. - * 0x1: allowing updates made to 'bf_target_dir'. - * Access Mode: write only - */ - uint32_t we_bf_target_dir : 1; - /** - * write enable for audio_gain parameter. - * 0x1: allowing updates made to 'audio_gain'. - * Access Mode: write only - */ - uint32_t we_audio_gain : 1; - /** - * write enable for data_out_mode parameter. - * 0x1: allowing updates made to 'data_src_mode'. - */ - uint32_t we_data_src_mode : 1; -} __attribute__((packed, aligned(4))) apu_ch_cfg_t; - -typedef struct _apu_ctl_t -{ - /** - * Sound direction searching enable bit. - * Software writes '1' to start sound direction searching function. - * When all the sound sample buffers are filled full, this bit is - * cleared by hardware (this sample buffers are used for direction - * detect only). 0x1: enable direction searching. - */ - uint32_t bf_dir_search_en : 1; - /* - *use this parameter to reset all the control logic on direction search processing path. This bit is self-clearing. - * 0x1: apply reset to direction searching control logic; - * 0x0: No operation. - */ - uint32_t search_path_reset : 1; - uint32_t reserved : 2; - /** - * Valid voice sample stream generation enable bit. - * After sound direction searching is done, software can configure this - * bit to generate a stream of voice samples for voice recognition. 0x1: - * enable output of voice sample stream. 0x0: stop the voice samlpe - * stream output. - */ - uint32_t bf_stream_gen_en : 1; - /* - *use this parameter to reset all the control logic on voice stream generating path. This bit is self-clearing. - * 0x1: apply reset to voice stream generating control logic; - * 0x0: No operation. - */ - uint32_t voice_gen_path_reset : 1; - /* - *use this parameter to switch to a new voice source direction. Software write '1' here and hardware will automatically clear it. - * 0x1: write '1' here to request switching to new voice source direction. - */ - uint32_t update_voice_dir : 1; - - uint32_t reserved1 : 1; - //write enable for 'bf_dir_search_en' parameter. - uint32_t we_bf_dir_search_en : 1; - uint32_t we_search_path_rst : 1; - uint32_t we_bf_stream_gen : 1; - uint32_t we_voice_gen_path_rst : 1; - uint32_t we_update_voice_dir : 1; - uint32_t reserved2 : 19; - -} __attribute__((packed, aligned(4))) apu_ctl_t; - -typedef struct _apu_dir_bidx -{ - uint32_t dir_rd_idx0 : 6; - uint32_t reserved : 2; - uint32_t dir_rd_idx1 : 6; - uint32_t reserved1 : 2; - uint32_t dir_rd_idx2 : 6; - uint32_t reserved2 : 2; - uint32_t dir_rd_idx3 : 6; - uint32_t reserved3 : 2; -} __attribute__((packed, aligned(4))) apu_dir_bidx_t; - -typedef struct _apu_fir_coef -{ - uint32_t fir_tap0 : 16; - uint32_t fir_tap1 : 16; -} __attribute__((packed, aligned(4))) apu_fir_coef_t; - -typedef struct _apu_dwsz_cfg -{ - /** - * TThe down-sizing ratio used for direction searching. - * 0x0: no down-sizing; - * 0x1: 1/2 down sizing; - * 0x2: 1/3 down sizing; - * . . . . . . - * 0xF: 1/16 down sizing. - */ - uint32_t dir_dwn_siz_rate : 4; - /** - * The down-sizing ratio used for voice stream generation. - * 0x0: no down-sizing; - * 0x1: 1/2 down sizing; - * 0x2: 1/3 down sizing; - * . . . . . . - * 0xF: 1/16 down sizing. - */ - uint32_t voc_dwn_siz_rate : 4; - /** - * This bit field is used to perform sample precision reduction when - * the source sound sample (from I2S0 host receiving channels) - * precision is 20/24/32 bits. - * 0x0: take bits 15~0 from the source sound sample; - * 0x1: take bits 16~1 from the source sound sample; - * 0x2: take bits 17~2 from the source sound sample; - * . . . . . . - * 0x10: take bits 31~16 from the source sound sample; - */ - uint32_t smpl_shift_bits : 5; - uint32_t reserved : 19; -} __attribute__((packed, aligned(4))) apu_dwsz_cfg_t; - -/*0x31c*/ -typedef struct _apu_fft_cfg -{ - uint32_t fft_shift_factor : 9; - uint32_t reserved1 : 3; - uint32_t fft_enable : 1; - uint32_t reserved2 : 19; -} __attribute__((packed, aligned(4))) apu_fft_cfg_t; - -/*0x328*/ -typedef struct _apu_int_stat -{ - /** - * sound direction searching data ready interrupt event. - * Writing '1' to clear this interrupt event. - * 0x1: data is ready for sound direction detect; - * 0x0: no event. - */ - uint32_t dir_search_data_rdy : 1; - /** - * voice output stream buffer data ready interrupt event. - * When a block of 512 voice samples are collected, this interrupt event - * is asserted. Writing '1' to clear this interrupt event. 0x1: voice - * output stream buffer data is ready; 0x0: no event. - */ - uint32_t voc_buf_data_rdy : 1; - uint32_t reserved : 30; -} __attribute__((packed, aligned(4))) apu_int_stat_t; - -/*0x32c*/ -typedef struct _apu_int_mask -{ - /** - * This is the interrupt mask to dir searching data ready interrupt. - * 0x1: mask off this interrupt; - * 0x0: enable this interrupt. - */ - uint32_t dir_data_rdy_msk : 1; - /** - * This is the interrupt mask to voice output stream buffer ready - * interrupt. 0x1: mask off this interrupt; 0x0: enable this interrupt. - */ - uint32_t voc_buf_rdy_msk : 1; - uint32_t reserved : 30; -} __attribute__((packed, aligned(4))) apu_int_mask_t; - -typedef struct _apu_reg -{ - //0x200 - apu_ch_cfg_t bf_ch_cfg_reg; - //0x204 - apu_ctl_t bf_ctl_reg; - //0x208 - apu_dir_bidx_t bf_dir_bidx[16][2]; - //0x288 - apu_fir_coef_t bf_pre_fir0_coef[9]; - //0x2ac - apu_fir_coef_t bf_post_fir0_coef[9]; - //0x2d0 - apu_fir_coef_t bf_pre_fir1_coef[9]; - //0x2f4 - apu_fir_coef_t bf_post_fir1_coef[9]; - //0x318 - apu_dwsz_cfg_t bf_dwsz_cfg_reg; - //0x31c - apu_fft_cfg_t bf_fft_cfg_reg; - // 0x320 - /** - * This is the read register for system DMA to read data stored in - * sample out buffers (the sample out buffers are used for sound - * direction detect). Each data contains two sound samples. - */ - volatile uint32_t sobuf_dma_rdata; - // 0x324 - /** - * This is the read register for system DMA to read data stored in voice - * out buffers (the voice out buffers are used for voice recognition). - * Each data contains two sound samples. - */ - volatile uint32_t vobuf_dma_rdata; - /*0x328*/ - apu_int_stat_t bf_int_stat_reg; - /*0x32c*/ - apu_int_mask_t bf_int_mask_reg; - /*0x330*/ - uint32_t saturation_counter; - /*0x334*/ - uint32_t saturation_limits; -} __attribute__((packed, aligned(4))) apu_reg_t; - -extern volatile apu_reg_t *const apu; - -void apu_set_audio_gain(uint16_t gain); -void apu_set_smpl_shift(uint8_t smpl_shift); -uint8_t apu_get_smpl_shift(void); -void apu_set_channel_enabled(uint8_t channel_bit); -void apu_set_direction_delay(uint8_t dir_num, uint8_t *dir_bidx); -void apu_set_delay(float radius, uint8_t mic_num_a_circle, uint8_t center); - -void apu_set_fft_shift_factor(uint8_t enable_flag, uint16_t shift_factor); -void apu_set_down_size(uint8_t dir_dwn_siz, uint8_t voc_dwn_siz); /*split to 2 functions*/ -void apu_set_interrupt_mask(uint8_t dir_int_mask, uint8_t voc_int_mask); /*split to 2 functions*/ - -void apu_dir_enable(void); -void apu_dir_reset(void); -void apu_dir_set_prev_fir(uint16_t *fir_coef); -void apu_dir_set_post_fir(uint16_t *fir_coef); -void apu_dir_set_down_size(uint8_t dir_dwn_size); -void apu_dir_set_interrupt_mask(uint8_t dir_int_mask); -void apu_dir_clear_int_state(void); - -void apu_voc_enable(uint8_t enable_flag); -void apu_voc_reset(void); -void apu_voc_set_direction(en_bf_dir_t direction); -void apu_voc_set_prev_fir(uint16_t *fir_coef); -void apu_voc_set_post_fir(uint16_t *fir_coef); -void apu_voc_set_down_size(uint8_t voc_dwn_size); -void apu_voc_set_interrupt_mask(uint8_t voc_int_mask); -void apu_voc_clear_int_state(void); -void apu_voc_reset_saturation_counter(void); -uint32_t apu_voc_get_saturation_counter(void); -void apu_voc_set_saturation_limit(uint16_t upper, uint16_t bottom); -uint32_t apu_voc_get_saturation_limit(void); - -void apu_print_setting(void); - -#if defined(__cplusplus) -} -#endif -#endif diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/clint.h b/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/clint.h deleted file mode 100644 index 07c2f4c..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/clint.h +++ /dev/null @@ -1,338 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * 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. - */ -/** - * @file - * @brief The CLINT block holds memory-mapped control and status registers - * associated with local interrupts for a Coreplex. - * - * @note CLINT RAM Layout - * - * | Address -| Description | - * |------------|---------------------------------| - * | 0x02000000 | msip for core 0 | - * | 0x02000004 | msip for core 1 | - * | ... | ... | - * | 0x02003FF8 | msip for core 4094 | - * | | | - * | 0x02004000 | mtimecmp for core 0 | - * | 0x02004008 | mtimecmp for core 1 | - * | ... | ... | - * | 0x0200BFF0 | mtimecmp For core 4094 | - * | 0x0200BFF8 | mtime | - * | | | - * | 0x0200C000 | Reserved | - * | ... | ... | - * | 0x0200EFFC | Reserved | - */ - -#ifndef _DRIVER_CLINT_H -#define _DRIVER_CLINT_H - -#include -#include -#include "platform.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/* clang-format off */ -/* Register address offsets */ -#define CLINT_MSIP (0x0000) -#define CLINT_MSIP_SIZE (0x4) -#define CLINT_MTIMECMP (0x4000) -#define CLINT_MTIMECMP_SIZE (0x8) -#define CLINT_MTIME (0xBFF8) -#define CLINT_MTIME_SIZE (0x8) -/* Max number of cores */ -#define CLINT_MAX_CORES (4095) -/* Real number of cores */ -#define CLINT_NUM_CORES (2) -/* Clock frequency division factor */ -#define CLINT_CLOCK_DIV (50) -/* clang-format on */ - -/** - * @brief MSIP Registers - * - * Machine-mode software interrupts are generated by writing to a - * per-core memory-mapped control register. The msip registers are - * 32-bit wide WARL registers, where the LSB is reflected in the - * msip bit of the associated core’s mip register. Other bits in - * the msip registers are hardwired to zero. The mapping supports - * up to 4095 machine-mode cores. - */ -typedef struct _clint_msip -{ - uint32_t msip : 1; /*!< Bit 0 is msip */ - uint32_t zero : 31; /*!< Bits [32:1] is 0 */ -} __attribute__((packed, aligned(4))) clint_msip_t; - -/** - * @brief Timer compare Registers Machine-mode timer interrupts are - * generated by a real-time counter and a per-core comparator. The - * mtime register is a 64-bit read-only register that contains the - * current value of the real-time counter. Each mtimecmp register - * holds its core’s time comparator. A timer interrupt is pending - * whenever mtime is greater than or equal to the value in a - * core’s mtimecmp register. The timer interrupt is reflected in - * the mtip bit of the associated core’s mip register. - */ -typedef uint64_t clint_mtimecmp_t; - -/** - * @brief Timer Registers - * - * The mtime register has a 64-bit precision on all RV32, RV64, - * and RV128 systems. Platforms provide a 64-bit memory-mapped - * machine-mode timer compare register (mtimecmp), which causes a - * timer interrupt to be posted when the mtime register contains a - * value greater than or equal to the value in the mtimecmp - * register. The interrupt remains posted until it is cleared by - * writing the mtimecmp register. The interrupt will only be taken - * if interrupts are enabled and the MTIE bit is set in the mie - * register. - */ -typedef uint64_t clint_mtime_t; - -/** - * @brief CLINT object - * - * Coreplex-Local INTerrupts, which includes software interrupts, - * local timer interrupts, and other interrupts routed directly to - * a core. - */ -typedef struct _clint -{ - /* 0x0000 to 0x3FF8, MSIP Registers */ - clint_msip_t msip[CLINT_MAX_CORES]; - /* Resverd space, do not use */ - uint32_t resv0; - /* 0x4000 to 0xBFF0, Timer Compare Registers */ - clint_mtimecmp_t mtimecmp[CLINT_MAX_CORES]; - /* 0xBFF8, Time Register */ - clint_mtime_t mtime; -} __attribute__((packed, aligned(4))) clint_t; - -/** - * @brief Clint object instanse - */ -extern volatile clint_t* const clint; - -/** - * @brief Definitions for the timer callbacks - */ -typedef int (*clint_timer_callback_t)(void *ctx); - -/** - * @brief Definitions for local interprocessor interrupt callbacks - */ -typedef int (*clint_ipi_callback_t)(void *ctx); - -typedef struct _clint_timer_instance -{ - uint64_t interval; - uint64_t cycles; - uint64_t single_shot; - clint_timer_callback_t callback; - void *ctx; -} clint_timer_instance_t; - -typedef struct _clint_ipi_instance -{ - clint_ipi_callback_t callback; - void *ctx; -} clint_ipi_instance_t; - -/** - * @brief Get the time form CLINT timer register - * - * @note The CLINT must init to get right time - * - * @return 64bit Time - */ -uint64_t clint_get_time(void); - -/** - * @brief Init the CLINT timer - * - * @note MIP_MTIP will be clear after init. The MSTATUS_MIE must set by - * user. - * - * @return result - * - 0 Success - * - Other Fail - */ -int clint_timer_init(void); - -/** - * @brief Stop the CLINT timer - * - * @note MIP_MTIP will be clear after stop - * - * @return result - * - 0 Success - * - Other Fail - */ -int clint_timer_stop(void); - -/** - * @brief Start the CLINT timer - * - * @param[in] interval The interval with Millisecond(ms) - * @param[in] single_shot Single shot or repeat - * - * @return result - * - 0 Success - * - Other Fail - */ -int clint_timer_start(uint64_t interval, int single_shot); - -/** - * @brief Get the interval of timer - * - * @return The interval with Millisecond(ms) - */ -uint64_t clint_timer_get_interval(void); - -/** - * @brief Set the interval with Millisecond(ms) - * - * @param[in] interval The interval with Millisecond(ms) - * - * @return result - * - 0 Success - * - Other Fail - */ -int clint_timer_set_interval(uint64_t interval); - -/** - * @brief Get whether the timer is a single shot timer - * - * @return result - * - 0 It is a repeat timer - * - 1 It is a single shot timer - */ -int clint_timer_get_single_shot(void); - -/** - * @brief Set the timer working as a single shot timer or repeat timer - * - * @param[in] single_shot Single shot or repeat - * - * @return result - * - 0 Success - * - Other Fail - */ -int clint_timer_set_single_shot(int single_shot); - -/** - * @brief Set user callback function when timer is timeout - * - * @param[in] callback The callback function - * @param[in] ctx The context - * - * @return result - * - 0 Success - * - Other Fail - */ -int clint_timer_register(clint_timer_callback_t callback, void *ctx); - -/** - * @brief Deregister user callback function - * - * @return result - * - 0 Success - * - Other Fail - */ -int clint_timer_unregister(void); - -/** - * @brief Initialize local interprocessor interrupt - * - * @return result - * - 0 Success - * - Other Fail - */ -int clint_ipi_init(void); - -/** - * @brief Enable local interprocessor interrupt - * - * @return result - * - 0 Success - * - Other Fail - */ -int clint_ipi_enable(void); - -/** - * @brief Disable local interprocessor interrupt - * - * @return result - * - 0 Success - * - Other Fail - */ -int clint_ipi_disable(void); - -/** - * @brief Send local interprocessor interrupt to core by core id - * - * @param[in] core_id The core identifier - * - * @return result - * - 0 Success - * - Other Fail - */ -int clint_ipi_send(size_t core_id); - -/** - * @brief Clear local interprocessor interrupt - * - * @param[in] core_id The core identifier - * - * @return result - * - 1 An IPI was pending - * - 0 Non IPI was pending - * - -1 Fail - */ -int clint_ipi_clear(size_t core_id); - -/** - * @brief Set user callback function when interprocessor interrupt - * - * @param[in] callback The callback function - * @param[in] ctx The context - * - * @return result - * - 0 Success - * - Other Fail - */ -int clint_ipi_register(clint_ipi_callback_t callback, void *ctx); - -/** - * @brief Deregister user callback function - * - * @return result - * - 0 Success - * - Other Fail - */ -int clint_ipi_unregister(void); - -#ifdef __cplusplus -} -#endif - -#endif /* _DRIVER_CLINT_H */ - diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/dmac.h b/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/dmac.h deleted file mode 100644 index e1ee649..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/dmac.h +++ /dev/null @@ -1,1542 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef _DRIVER_DMAC_H -#define _DRIVER_DMAC_H - -#include -#include "io.h" -#include "platform.h" -#include "stdbool.h" -#include "plic.h" -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/* DMAC */ -#define DMAC_CHANNEL_COUNT (DMAC_CHANNEL_MAX) -#define LAST_ROW (-1) - -typedef enum _dmac_channel_number -{ - DMAC_CHANNEL0 = 0, - DMAC_CHANNEL1 = 1, - DMAC_CHANNEL2 = 2, - DMAC_CHANNEL3 = 3, - DMAC_CHANNEL4 = 4, - DMAC_CHANNEL5 = 5, - DMAC_CHANNEL_MAX -} dmac_channel_number_t; - -typedef enum _dmac_src_dst_select -{ - DMAC_SRC = 0x1, - DMAC_DST = 0x2, - DMAC_SRC_DST = 0x3 -} dmac_src_dst_select_t; - -typedef enum _state_value -{ - clear = 0, - set = 1 -} state_value_t; - -typedef enum _dmac_lock_bus_ch -{ - DMAC_LOCK_BUS = 0x1, - DMAC_LOCK_CHANNEL = 0x2, - DMAC_LOCK_BUS_CH = 0x3 -} dmac_lock_bus_ch_t; - -typedef enum _dmac_sw_hw_hs_select -{ - DMAC_HS_HARDWARE = 0x0, - DMAC_HS_SOFTWARE = 0x1 -} dmac_sw_hw_hs_select_t; - -typedef enum _dmac_scatter_gather_param -{ - DMAC_SG_COUNT = 0x0, - DMAC_SG_INTERVAL = 0x1 -} dmac_scatter_gather_param_t; - -typedef enum _dmac_irq -{ - /* no interrupts */ - DMAC_IRQ_NONE = 0x00, - /* transfer complete */ - DMAC_IRQ_TFR = 0x01, - /* block transfer complete */ - DMAC_IRQ_BLOCK = 0x02, - /* source transaction complete */ - DMAC_IRQ_SRCTRAN = 0x04, - /* destination transaction complete */ - DMAC_IRQ_DSTTRAN = 0x08, - /* error */ - DMAC_IRQ_ERR = 0x10, - /* all interrupts */ - DMAC_IRQ_ALL = 0x1f -} dmac_irq_t; - -typedef enum _dmac_software_req -{ - /* ReqSrcReq/ReqDstReq */ - DMAC_REQUEST = 0x1, - /* SglReqSrcReq/SglReqDstReq */ - DMAC_SINGLE_REQUEST = 0x2, - /* LstReqSrcReq/LstReqDstReq */ - DMAC_LAST_REQUEST = 0x4 -} dmac_software_req_t; - -typedef enum _dmac_master_number -{ - DMAC_MASTER1 = 0x0, - DMAC_MASTER2 = 0x1 -} dmac_master_number_t; - -typedef enum _dmac_transfer_flow -{ - /* mem to mem - DMAC flow ctlr */ - DMAC_MEM2MEM_DMA = 0x0, - /* mem to prf - DMAC flow ctlr */ - DMAC_MEM2PRF_DMA = 0x1, - /* prf to mem - DMAC flow ctlr */ - DMAC_PRF2MEM_DMA = 0x2, - /* prf to prf - DMAC flow ctlr */ - DMAC_PRF2PRF_DMA = 0x3, - /* prf to mem - periph flow ctlr */ - DMAC_PRF2MEM_PRF = 0x4, - /* prf to prf - source flow ctlr */ - DMAC_PRF2PRF_SRCPRF = 0x5, - /* mem to prf - periph flow ctlr */ - DMAC_MEM2PRF_PRF = 0x6, - /* prf to prf - dest flow ctlr */ - DMAC_PRF2PRF_DSTPRF = 0x7 -} dmac_transfer_flow_t; - -typedef enum _dmac_burst_trans_length -{ - DMAC_MSIZE_1 = 0x0, - DMAC_MSIZE_4 = 0x1, - DMAC_MSIZE_8 = 0x2, - DMAC_MSIZE_16 = 0x3, - DMAC_MSIZE_32 = 0x4, - DMAC_MSIZE_64 = 0x5, - DMAC_MSIZE_128 = 0x6, - DMAC_MSIZE_256 = 0x7 -} dmac_burst_trans_length_t; - -typedef enum _dmac_address_increment -{ - DMAC_ADDR_INCREMENT = 0x0, - DMAC_ADDR_NOCHANGE = 0x1 -} dmac_address_increment_t; - -typedef enum _dmac_transfer_width -{ - DMAC_TRANS_WIDTH_8 = 0x0, - DMAC_TRANS_WIDTH_16 = 0x1, - DMAC_TRANS_WIDTH_32 = 0x2, - DMAC_TRANS_WIDTH_64 = 0x3, - DMAC_TRANS_WIDTH_128 = 0x4, - DMAC_TRANS_WIDTH_256 = 0x5 -} dmac_transfer_width_t; - -typedef enum _dmac_hs_interface -{ - DMAC_HS_IF0 = 0x0, - DMAC_HS_IF1 = 0x1, - DMAC_HS_IF2 = 0x2, - DMAC_HS_IF3 = 0x3, - DMAC_HS_IF4 = 0x4, - DMAC_HS_IF5 = 0x5, - DMAC_HS_IF6 = 0x6, - DMAC_HS_IF7 = 0x7, - DMAC_HS_IF8 = 0x8, - DMAC_HS_IF9 = 0x9, - DMAC_HS_IF10 = 0xa, - DMAC_HS_IF11 = 0xb, - DMAC_HS_IF12 = 0xc, - DMAC_HS_IF13 = 0xd, - DMAC_HS_IF14 = 0xe, - DMAC_HS_IF15 = 0xf -} dmac_hs_interface_t; - -typedef enum _dmac_multiblk_transfer_type -{ - CONTIGUOUS = 0, - RELOAD = 1, - SHADOWREGISTER = 2, - LINKEDLIST = 3 -} dmac_multiblk_transfer_type_t; - -typedef enum _dmac_multiblk_type -{ - DMAC_SRC_DST_CONTINUE = 0, - DMAC_SRC_CONTINUE_DST_RELAOD = 2, - DMAC_SRC_CONTINUE_DST_LINKEDLIST = 3, - DMAC_SRC_RELOAD_DST_CONTINUE = 4, - DMAC_SRC_RELOAD_DST_RELOAD = 5, - DMAC_SRC_RELOAD_DST_LINKEDLIST = 6, - DMAC_SRC_LINKEDLIST_DST_CONTINUE = 7, - DMAC_SRC_LINKEDLIST_DST_RELOAD = 8, - DMAC_SRC_LINKEDLIST_DST_LINKEDLIST = 9, - DMAC_SRC_SHADOWREG_DST_CONTINUE = 10 -} dmac_multiblk_type_t; - -typedef enum _dmac_transfer_type -{ - DMAC_TRANSFER_ROW1 = 0x1, - DMAC_TRANSFER_ROW2 = 0x2, - DMAC_TRANSFER_ROW3 = 0x3, - DMAC_TRANSFER_ROW4 = 0x4, - DMAC_TRANSFER_ROW5 = 0x5, - DMAC_TRANSFER_ROW6 = 0x6, - DMAC_TRANSFER_ROW7 = 0x7, - DMAC_TRANSFER_ROW8 = 0x8, - DMAC_TRANSFER_ROW9 = 0x9, - DMAC_TRANSFER_ROW10 = 0xa -} dmac_transfer_type_t; - -typedef enum _dmac_prot_level -{ - /* default prot level */ - DMAC_NONCACHE_NONBUFF_NONPRIV_OPCODE = 0x0, - DMAC_NONCACHE_NONBUFF_NONPRIV_DATA = 0x1, - DMAC_NONCACHE_NONBUFF_PRIV_OPCODE = 0x2, - DMAC_NONCACHE_NONBUFF_PRIV_DATA = 0x3, - DMAC_NONCACHE_BUFF_NONPRIV_OPCODE = 0x4, - DMAC_NONCACHE_BUFF_NONPRIV_DATA = 0x5, - DMAC_NONCACHE_BUFF_PRIV_OPCODE = 0x6, - DMAC_NONCACHE_BUFF_PRIV_DATA = 0x7, - DMAC_CACHE_NONBUFF_NONPRIV_OPCODE = 0x8, - DMAC_CACHE_NONBUFF_NONPRIV_DATA = 0x9, - DMAC_CACHE_NONBUFF_PRIV_OPCODE = 0xa, - DMAC_CACHE_NONBUFF_PRIV_DATA = 0xb, - DMAC_CACHE_BUFF_NONPRIV_OPCODE = 0xc, - DMAC_CACHE_BUFF_NONPRIV_DATA = 0xd, - DMAC_CACHE_BUFF_PRIV_OPCODE = 0xe, - DMAC_CACHE_BUFF_PRIV_DATA = 0xf -} dmac_prot_level_t; - -typedef enum _dmac_fifo_mode -{ - DMAC_FIFO_MODE_SINGLE = 0x0, - DMAC_FIFO_MODE_HALF = 0x1 -} dmac_fifo_mode_t; - -typedef enum _dw_dmac_flow_ctl_mode -{ - DMAC_DATA_PREFETCH_ENABLED = 0x0, - DMAC_DATA_PREFETCH_DISABLED = 0x1 -} dw_dmac_flow_ctl_mode_t; - -typedef enum _dmac_polarity_level -{ - DMAC_ACTIVE_HIGH = 0x0, - DMAC_ACTIVE_LOW = 0x1 -} dmac_polarity_level_t; - -typedef enum _dmac_lock_level -{ - DMAC_LOCK_LEVEL_DMA_TRANSFER = 0x0, - DMAC_LOCK_LEVEL_BLOCK_TRANSFER = 0x1, - DMAC_LOCK_LEVEL_TRANSACTION = 0x2 -} dmac_lock_level_t; - -typedef enum _dmac_channel_priority -{ - DMAC_PRIORITY_0 = 0x0, - DMAC_PRIORITY_1 = 0x1, - DMAC_PRIORITY_2 = 0x2, - DMAC_PRIORITY_3 = 0x3, - DMAC_PRIORITY_4 = 0x4, - DMAC_PRIORITY_5 = 0x5, - DMAC_PRIORITY_6 = 0x6, - DMAC_PRIORITY_7 = 0x7 -} dmac_channel_priority_t; - -typedef enum _dmac_state -{ - ZERO, - ONE -} dmac_state_t; - -typedef enum _dmac_common_int -{ - SLVIF_COMMON_DEC_ERR = 0, - SLVIF_COMMON_WR2RO_ERR = 1, - SLVIF_COMMON_RD2WO_ERR = 2, - SLVIF_COMMON__WRONHOLD_ERR = 3, - SLVIF_UNDEFINED_DEC_ERR = 4, - SLVIF_ALL_INT = 5 -} dmac_common_int_t; - -typedef struct _dmac_cfg -{ - /** - * Bit 0 is used to enable dmac - * 0x1 for enable, 0x0 for disable - */ - uint64_t dmac_en : 1; - /** - * Bit 1 is used to glabally enable interrupt generation - * 0x1 for enable interrupt, 0x0 for disable interrupt - */ - uint64_t int_en : 1; - /* Bits [63:2] is reserved */ - uint64_t rsvd : 62; -} __attribute__((packed, aligned(8))) dmac_cfg_t; - -typedef union _dmac_cfg_u -{ - dmac_cfg_t cfg; - uint64_t data; -} dmac_cfg_u_t; - -typedef struct _damc_chen -{ - /** - * Bit 0 is used to enable channel 1 - * 0x1 for enable, 0x0 for disable - */ - uint64_t ch1_en : 1; - /** - * Bit 1 is used to enable channel 2 - * 0x1 for enable, 0x0 for disable - */ - uint64_t ch2_en : 1; - /** - * Bit 2 is used to enable channel 3 - * 0x1 for enable, 0x0 for disable - */ - uint64_t ch3_en : 1; - /** - * Bit 3 is used to enable channel 4 - * 0x1 for enable, 0x0 for disable - */ - uint64_t ch4_en : 1; - /** - * Bit 4 is used to enable channel 5 - * 0x1 for enable, 0x0 for disable - */ - uint64_t ch5_en : 1; - /** - * Bit 5 is used to enable channel 6 - * 0x1 for enable, 0x0 for disable - */ - uint64_t ch6_en : 1; - /* Bits [7:6] is reserved */ - uint64_t rsvd1 : 2; - /** - * Bit 8 is write enable bit - * 0x1 for enable, 0x0 for disable - */ - uint64_t ch1_en_we : 1; - /** - * Bit 9 is write enable bit - * 0x1 for enable, 0x0 for disable - */ - uint64_t ch2_en_we : 1; - /** - * Bit 10 is write enable bit - * 0x1 for enable, 0x0 for disable - */ - uint64_t ch3_en_we : 1; - /** - * Bit 11 is write enable bit - * 0x1 for enable, 0x0 for disable - */ - uint64_t ch4_en_we : 1; - /** - * Bit 12 is write enable bit - * 0x1 for enable, 0x0 for disable - */ - uint64_t ch5_en_we : 1; - /** - * Bit 13 is write enable bit - * 0x1 for enable, 0x0 for disable - */ - uint64_t ch6_en_we : 1; - /* Bits [15:14] is reserved */ - uint64_t rsvd2 : 2; - /** - * Bit 16 is susped reuest - * 0x1 for request channel suspend - * 0x0 for no channel suspend request - */ - uint64_t ch1_susp : 1; - /** - * Bit 17 is susped reuest - * 0x1 for request channel suspend - * 0x0 for no channel suspend request - */ - uint64_t ch2_susp : 1; - /* Bit 18 is susped reuest - * 0x1 for request channel suspend - * 0x0 for no channel suspend request - */ - uint64_t ch3_susp : 1; - /** - * Bit 19 is susped reuest - * 0x1 for request channel suspend - * 0x0 for no channel suspend request - */ - uint64_t ch4_susp : 1; - /** - * Bit 20 is susped reuest - * 0x1 for request channel suspend - * 0x0 for no channel suspend request - */ - uint64_t ch5_susp : 1; - /** - * Bit 21 is susped reuest - * 0x1 for request channel suspend - * 0x0 for no channel suspend request - */ - uint64_t ch6_susp : 1; - /* Bits [23:22] is reserved */ - uint64_t rsvd3 : 2; - /** - * Bit 24 is write enable to the channel suspend bit - * 0x1 for enable write to CH1_SUSP bit - * 0x0 for disable write to CH1_SUSP bit - */ - uint64_t ch1_susp_we : 1; - /** - * Bit 25 is write enable to the channel suspend bit - * 0x1 for enable write to CH2_SUSP bit - * 0x0 for disable write to CH2_SUSP bit - */ - uint64_t ch2_susp_we : 1; - /** - * Bit 26 is write enable to the channel suspend bit - * 0x1 for enable write to CH3_SUSP bit - * 0x0 for disable write to CH3_SUSP bit - */ - uint64_t ch3_susp_we : 1; - /** - * Bit 27 is write enable to the channel suspend bit - * 0x1 for enable write to CH4_SUSP bit - * 0x0 for disable write to CH4_SUSP bit - */ - uint64_t ch4_susp_we : 1; - /** - * Bit 28 is write enable to the channel suspend bit - * 0x1 for enable write to CH5_SUSP bit - * 0x0 for disable write to CH5_SUSP bit - */ - uint64_t ch5_susp_we : 1; - /** - * Bit 29 is write enable to the channel suspend bit - * 0x1 for enable write to CH6_SUSP bit - * 0x0 for disable write to CH6_SUSP bit - */ - uint64_t ch6_susp_we : 1; - /* Bits [31:30] is reserved */ - uint64_t rsvd4 : 2; - /** - * Bit 32 is channel-1 abort requst bit - * 0x1 for request for channnel abort - * 0x0 for no channel abort request - */ - uint64_t ch1_abort : 1; - /** - * Bit 33 is channel-2 abort requst bit - * 0x1 for request for channnel abort - * 0x0 for no channel abort request - */ - uint64_t ch2_abort : 1; - /** - * Bit 34 is channel-3 abort requst bit - * 0x1 for request for channnel abort - * 0x0 for no channel abort request - */ - uint64_t ch3_abort : 1; - /** - * Bit 35 is channel-4 abort requst bit - * 0x1 for request for channnel abort - * 0x0 for no channel abort request - */ - uint64_t ch4_abort : 1; - /** - * Bit 36 is channel-5 abort requst bit - * 0x1 for request for channnel abort - * 0x0 for no channel abort request - */ - uint64_t ch5_abort : 1; - /** - * Bit 37 is channel-6 abort requst bit - * 0x1 for request for channnel abort - * 0x0 for no channel abort request - */ - uint64_t ch6_abort : 1; - /* Bits [39:38] is reserved */ - uint64_t rsvd5 : 2; - /** - * Bit 40 is ued to write enable channel-1 abort bit - * 0x1 for enable write to CH1_ABORT bit - * 0x0 for disable write to CH1_ABORT bit - */ - uint64_t ch1_abort_we : 1; - /** - * Bit 41 is ued to write enable channel-2 abort bit - * 0x1 for enable write to CH2_ABORT bit - * 0x0 for disable write to CH2_ABORT bit - */ - uint64_t ch2_abort_we : 1; - /** - * Bit 42 is ued to write enable channel-3 abort bit - * 0x1 for enable write to CH3_ABORT bit - * 0x0 for disable write to CH3_ABORT bit - */ - uint64_t ch3_abort_we : 1; - /** - * Bit 43 is ued to write enable channel-4 abort bit - * 0x1 for enable write to CH4_ABORT bit - * 0x0 for disable write to CH4_ABORT bit - */ - uint64_t ch4_abort_we : 1; - /** - * Bit 44 is ued to write enable channel-5 abort bit - * 0x1 for enable write to CH5_ABORT bit - * 0x0 for disable write to CH5_ABORT bit - */ - uint64_t ch5_abort_we : 1; - /** - * Bit 45 is ued to write enable channel-6 abort bit - * 0x1 for enable write to CH6_ABORT bit - * 0x0 for disable write to CH6_ABORT bit - */ - uint64_t ch6_abort_we : 1; - /* Bits [47:46] is reserved */ - uint64_t rsvd6 : 2; - /* Bits [63:48] is reserved */ - uint64_t rsvd7 : 16; -} __attribute__((packed, aligned(8))) damc_chen_t; - -typedef union _dmac_chen_u -{ - damc_chen_t dmac_chen; - uint64_t data; -} dmac_chen_u_t; - -typedef struct _dmac_intstatus -{ - /** - * Bit 0 is channel 1 interrupt bit - * 0x1 for channel 1 interrupt active - * 0x0 for channel 1 interrupt inactive - */ - uint64_t ch1_intstat : 1; - /** - * Bit 1 is channel 1 interrupt bit - * 0x1 for channel 2 interrupt active - * 0x0 for channel 2 interrupt inactive - */ - uint64_t ch2_intstat : 1; - /** - * Bit 2 is channel 3 interrupt bit - * 0x1 for channel 3 interrupt active - * 0x0 for channel 3 interrupt inactive - */ - uint64_t ch3_intstat : 1; - /** - * Bit 3 is channel 4 interrupt bit - * 0x1 for channel 4 interrupt active - * 0x0 for channel 4 interrupt inactive - */ - uint64_t ch4_intstat : 1; - /** - * Bit 4 is channel 5 interrupt bit - * 0x1 for channel 5 interrupt active - * 0x0 for channel 5 interrupt inactive - */ - uint64_t ch5_intstat : 1; - /** - * Bit 5 is channel 6 interrupt bit - * 0x1 for channel 6 interrupt active - * 0x0 for channel 6 interrupt inactive - */ - uint64_t ch6_intstat : 1; - /* Bits [15:6] is reserved */ - uint64_t rsvd1 : 10; - /** - * Bit 16 is commom register status bit - * 0x1 for common register interrupt is active - * 0x0 for common register interrupt inactive - */ - uint64_t commonreg_intstat : 1; - /* Bits [63:17] is reserved */ - uint64_t rsvd2 : 47; -} __attribute__((packed, aligned(8))) dmac_intstatus_t; - -typedef union _dmac_intstatus_u -{ - dmac_intstatus_t intstatus; - uint64_t data; -} dmac_intstatus_u_t; - -typedef struct _dmac_commonreg_intclear -{ - /** - * Bit 0 is slave nterface Common Register - * Decode Error Interrupt clear Bit - * x01 for clear SLVIF_CommonReg_DEC_ERR interrupt - * in DMAC_COMMONREG_INTSTATUSREG - * 0x0 for inactive signal - */ - uint64_t cear_slvif_dec_err_intstat : 1; - /** - * Bit 1 is Slave Interface Common Register Write - * to Read only Error Interrupt clear Bit - * x01 for clear SLVIF_CommonReg_WR2RO_ERR interrupt - * in DMAC_COMMONREG_INTSTATUSREG - * 0x0 for inactive signal - */ - uint64_t clear_slvif_wr2ro_err_intstat : 1; - /** - * Bit 2 is Slave Interface Common Register Read to - * Write only Error Interrupt clear Bit - * x01 for clear SLVIF_CommonReg_RD2WO_ERR interrupt - * in DMAC_COMMONREG_INTSTATUSREG - * 0x0 for inactive signal - */ - uint64_t clear_slvif_rd2wo_err_intstat : 1; - /** - * Bit 3 is Slave Interface Common Register Write - * On Hold Error Interrupt clear Bit - * x01 for clear SSLVIF_CommonReg_WrOnHold_ERR interrupt - * in DMAC_COMMONREG_INTSTATUSREG - * 0x0 for inactive signal - */ - uint64_t clear_slvif_wronhold_err_intstat : 1; - /* Bits [7:4] is reserved */ - uint64_t rsvd1 : 4; - /** - * Bit 8 is Slave Interface Undefined register - * Decode Error Interrupt clear Bit - * x01 for clear SLVIF_UndefinedReg_DEC_ERRinterrupt - * in DMAC_COMMONREG_INTSTATUSREG - * 0x0 for inactive signal - */ - uint64_t clear_slvif_undefinedreg_dec_err_intstat : 1; - /* Bits [63:9] is reserved */ - uint64_t rsvd2 : 55; -} __attribute__((packed, aligned(8))) dmac_commonreg_intclear_t; - -typedef union _dmac_commonreg_intclear_u -{ - dmac_commonreg_intclear_t com_intclear; - uint64_t data; -} dmac_commonreg_intclear_u_t; - -typedef struct _dmac_commonreg_intstatus_enable -{ - /** - * Bit 0 is Slave Interface Common Register Decode Error - * Interrupt Status Enable Bit - * 0x1 for SLVIF_CommonReg_DEC_ERR_IntStat bit enable - * 0x0 for SLVIF_CommonReg_DEC_ERR_IntStat bit disable - */ - uint64_t enable_slvif_dec_err_intstat : 1; - /** - * Bit 1 is Slave Interface Common Register Write to Read - * only Error Interrupt Status Enable Bit - * 0x1 for SLVIF_CommonReg_WR2RO_ERR_IntStat bit enable - * 0x0 for SLVIF_CommonReg_WR2RO_ERR_IntStat bit disable - */ - uint64_t enable_slvif_wr2ro_err_intstat : 1; - /*!< - * Bit 2 is Slave Interface Common Register Read to Write - * only Error Interrupt Status Enable Bit - * 0x1 for SLVIF_CommonReg_RD2WO_ERR_IntStat bit enable - * 0x0 for SLVIF_CommonReg_RD2WO_ERR_IntStat bit disable - */ - uint64_t enable_slvif_rd2wo_err_intstat : 1; - /** - * Bit 3 is Slave Interface Common Register Write On Hold - * Error Interrupt Status Enable Bit - * 0x1 for SLVIF_CommonReg_WrOnHold_ERR_IntStat bit enable - * 0x0 for SLVIF_CommonReg_WrOnHold_ERR_IntStat bit disable - */ - uint64_t enable_slvif_wronhold_err_intstat : 1; - /* Bits [7:4] is reserved */ - uint64_t rsvd1 : 4; - /** - * Bit 8 is Slave Interface Undefined register Decode - * Error Interrupt Status enable Bit - * 0x1 for SLVIF_UndefinedReg_DEC_ERR_IntStat bit enable - * 0x0 for SLVIF_UndefinedReg_DEC_ERR_IntStat disable - */ - uint64_t enable_slvif_undefinedreg_dec_err_intstat : 1; - /* Bits [63:9] is reserved */ - uint64_t rsvd2 : 55; -} __attribute__((packed, aligned(8))) dmac_commonreg_intstatus_enable_t; - -typedef union _dmac_commonreg_intstatus_enable_u -{ - dmac_commonreg_intstatus_enable_t intstatus_enable; - uint64_t data; -} dmac_commonreg_intstatus_enable_u_t; - -typedef struct _dmac_commonreg_intsignal_enable -{ - /** - * Bit 0 is Slave Interface Common Register Decode Error - * Interrupt Signal Enable Bit - * 0x1 for SLVIF_CommonReg_DEC_ERR_IntStat signal enable - * 0x0 for SLVIF_CommonReg_DEC_ERR_IntStat signal disable - */ - uint64_t enable_slvif_dec_err_intsignal : 1; - /** - * Bit 1 is Slave Interface Common Register Write to Read only - * Error Interrupt Signal Enable Bit - * 0x1 for SLVIF_CommonReg_WR2RO_ERR_IntStat signal enable - * 0x0 for SLVIF_CommonReg_WR2RO_ERR_IntStat signal disable - */ - uint64_t enable_slvif_wr2ro_err_intsignal : 1; - /** - * Bit 2 is Slave Interface Common Register Read to - * Write only Error Interrupt Status Enable Bit - * 0x1 for SLVIF_CommonReg_RD2WO_ERR_IntStat bit enable - * 0x0 for SLVIF_CommonReg_RD2WO_ERR_IntStat bit disable - */ - uint64_t enable_slvif_rd2wo_err_intsignal : 1; - /** - * Bit 3 is Slave Interface Common Register Write On Hold Error - * Interrupt Signal Enable Bit - * 0x1 for SLVIF_CommonReg_WrOnHold_ERR_IntStat signal enable - * 0x0 for SLVIF_CommonReg_WrOnHold_ERR_IntStat signal disable - */ - uint64_t enable_slvif_wronhold_err_intsignal : 1; - /* Bits [7:4] is reserved */ - uint64_t rsvd1 : 4; - /** - * Bit 8 is Slave Interface Undefined register Decode Error - * Interrupt Signal Enable Bit - * 0x1 for SLVIF_UndefinedReg_DEC_ERR_IntStat signal enable - * 0x0 for SLVIF_UndefinedReg_DEC_ERR_IntStat signal disable - */ - uint64_t enable_slvif_undefinedreg_dec_err_intsignal : 1; - /* Bits [63:9] is reserved */ - uint64_t rsvd2 : 55; -} __attribute__((packed, aligned(8))) dmac_commonreg_intsignal_enable_t; - -typedef union _dmac_commonreg_intsignal_enable_u -{ - dmac_commonreg_intsignal_enable_t intsignal_enable; - uint64_t data; -} dmac_commonreg_intsignal_enable_u_t; - -typedef struct _dmac_commonreg_intstatus -{ - /** - * Bit 0 is Slave Interface Common Register Decode - * Error Interrupt Status Bit - * 0x1 for Slave Interface Decode Error detected - * 0x0 for No Slave Interface Decode Errors - */ - uint64_t slvif_dec_err_intstat : 1; - /** - * Bit 1 is Slave Interface Common Register Write to Read Only - * Error Interrupt Status bit - * 0x1 for Slave Interface Write to Read Only Error detected - * 0x0 No Slave Interface Write to Read Only Errors - */ - uint64_t slvif_wr2ro_err_intstat : 1; - /** - * Bit 2 is Slave Interface Common Register Read to Write - * only Error Interrupt Status bit - * 0x1 for Slave Interface Read to Write Only Error detected - * 0x0 for No Slave Interface Read to Write Only Errors - */ - uint64_t slvif_rd2wo_err_intstat : 1; - /** - * Bit 3 is Slave Interface Common Register Write On - * Hold Error Interrupt Status Bit - * 0x1 for Slave Interface Common Register Write On Hold Error detected - * 0x0 for No Slave Interface Common Register Write On Hold Errors - */ - uint64_t slvif_wronhold_err_intstat : 1; - /*!< Bits [7:4] is reserved */ - uint64_t rsvd1 : 4; - /** - * Bit 8 is Slave Interface Undefined register Decode - * Error Interrupt Signal Enable Bit - * 0x1 for Slave Interface Decode Error detected - * 0x0 for No Slave Interface Decode Errors - */ - uint64_t slvif_undefinedreg_dec_err_intstat : 1; - /* Bits [63:9] is reserved */ - uint64_t rsvd2 : 55; -} __attribute__((packed, aligned(8))) dmac_commonreg_intstatus_t; - -typedef union _dmac_commonreg_intstatus_u -{ - dmac_commonreg_intstatus_t commonreg_intstatus; - uint64_t data; -} dmac_commonreg_intstatus_u_t; - -typedef struct _dmac_reset -{ - /* Bit 0 is DMAC reset request bit */ - uint64_t rst : 1; - /* Bits [63:1] is reserved */ - uint64_t rsvd : 63; -} __attribute__((packed, aligned(8))) dmac_reset_t; - -typedef union _dmac_reset_u -{ - dmac_reset_t reset; - uint64_t data; -} dmac_reset_u_t; - -typedef struct _dmac_ch_block_ts -{ - uint64_t block_ts : 22; - /*!< Bit [21:0] is block transfer size*/ - uint64_t rsvd : 42; - /*!< Bits [63:22] is reserved */ -} __attribute__((packed, aligned(8))) dmac_ch_block_ts_t; - -typedef union _dmac_ch_block_ts_u -{ - dmac_ch_block_ts_t block_ts; - uint64_t data; -} dmac_ch_block_ts_u_t; - -typedef struct _dmac_ch_ctl -{ - /** - * Bit 0 is source master select - * 1 for AXI master 2, 0 for AXI master 1 - */ - uint64_t sms : 1; - /* Bit 1 is reserved */ - uint64_t rsvd1 : 1; - /** - * Bit 2 is destination master select - * 0x1 for AXI master 2,0x0 for AXI master 1 - */ - uint64_t dms : 1; - /* Bit 3 is reserved */ - uint64_t rsvd2 : 1; - /** - * Bit 4 is source address increment - * 0x1 for no change, 0x0 for incremnet - */ - uint64_t sinc : 1; - /** - * Bit 5 is reserved - */ - uint64_t rsvd3 : 1; - /** - * Bit 6 is destination address incremnet - * 0x1 for no change, 0x0 for increment - */ - uint64_t dinc : 1; - /* Bit 7 is reserved*/ - uint64_t rsvd4 : 1; - /** - * Bits [10:8] is source transfer width - * 0x0 for source transfer width is 8 bits - * 0x1 for source transfer width is 16 bits - * 0x2 for source transfer width is 32 bits - * 0x3 for source transfer width is 64 bits - * 0x4 for source transfer width is 128 bits - * 0x5 for source transfer width is 256 bits - * 0x6 for source transfer width is 512 bits - */ - uint64_t src_tr_width : 3; - /** - * Bits [13:11] is detination transfer width - * 0x0 for detination transfer width is 8 bits - * 0x1 for detination transfer width is 16 bits - * 0x2 for detination transfer width is 32 bits - * 0x3 for detination transfer width is 64 bits - * 0x4 for detination transfer width is 128 bits - * 0x5 for detination transfer width is 256 bits - * 0x6 for detination transfer width is 512 bits - */ - uint64_t dst_tr_width : 3; - /** - * Bits [17:14] is source burst transaction length - * 0x0 for 1 data item read from rource in the burst transaction - * 0x1 for 4 data item read from rource in the burst transaction - * 0x2 for 8 data item read from rource in the burst transaction - * 0x3 for 16 data item read from rource in the burst transaction - * 0x4 for 32 data item read from rource in the burst transaction - * 0x5 for 64 data item read from rource in the burst transaction - * 0x6 for 128 data item read from rource in the burst transaction - * 0x7 for 256 data item read from rource in the burst transaction - * 0x8 for 512 data item read from rource in the burst transaction - * 0x9 for 1024 data item read from rource in the burst transaction - */ - uint64_t src_msize : 4; - /** - * Bits [17:14] is sdestination burst transaction length - * 0x0 for 1 data item read from rource in the burst transaction - * 0x1 for 4 data item read from rource in the burst transaction - * 0x2 for 8 data item read from rource in the burst transaction - * 0x3 for 16 data item read from rource in the burst transaction - * 0x4 for 32 data item read from rource in the burst transaction - * 0x5 for 64 data item read from rource in the burst transaction - * 0x6 for 128 data item read from rource in the burst transaction - * 0x7 for 256 data item read from rource in the burst transaction - * 0x8 for 512 data item read from rource in the burst transaction - * 0x9 for 1024 data item read from rource in the burst transaction - */ - uint64_t dst_msize : 4; - /** - * Bits [25:22] is reserved - */ - uint64_t rsvd5 : 4; - /*!< Bits [29:26] is reserved */ - uint64_t rsvd6 : 4; - /** - * Bit 30 is Non Posted Last Write Enable - * 0x1 for posted writes may be used till the end of the block - * 0x 0 for posted writes may be used throughout the block transfer - */ - uint64_t nonposted_lastwrite_en : 1; - /* Bit 31 is resrved */ - uint64_t rsvd7 : 1; - /* Bits [34:32] is reserved*/ - uint64_t rsvd8 : 3; - /* Bits [37:35] is reserved*/ - uint64_t rsvd9 : 3; - /** - * Bit 38 is source burst length enable - * 1 for enable, 0 for disable - */ - uint64_t arlen_en : 1; - /* Bits [46:39] is source burst length*/ - uint64_t arlen : 8; - /** - * Bit 47 is destination burst length enable - * 1 for enable, 0 for disable - */ - uint64_t awlen_en : 1; - /* Bits [55:48] is destination burst length */ - uint64_t awlen : 8; - /** - * Bit 56 is source status enable - * 0x1 for enable, 0x0 for disable - */ - uint64_t src_stat_en : 1; - /** - * Bit 57 is destination status enable - * 0x1 for enable, 0x0 for disable - */ - uint64_t dst_stat_en : 1; - /** - * Bit 58 is interrupt completion of block transfer - * 0x1 for enable CHx_IntStatusReg.BLOCK_TFR_DONE_IntStat field - * 0x0 for dsiable CHx_IntStatusReg.BLOCK_TFR_DONE_IntStat field - */ - uint64_t ioc_blktfr : 1; - /** - * Bits [61:59] is reserved - */ - uint64_t rsvd10 : 3; - /** - * Bit 62 is last shadow linked list item - * 0x1 for indicate shadowreg/LLI content is the last one - * 0x0 for indicate shadowreg/LLI content not the last one - */ - uint64_t shadowreg_or_lli_last : 1; - /** - * Bit 63 is last shadow linked list item valid - * 0x1 for indicate shadowreg/LLI content is valid - * 0x0 for indicate shadowreg/LLI content is invalid - */ - uint64_t shadowreg_or_lli_valid : 1; -} __attribute__((packed, aligned(8))) dmac_ch_ctl_t; - -typedef union _dmac_ch_ctl_u -{ - dmac_ch_ctl_t ch_ctl; - uint64_t data; -} dmac_ch_ctl_u_t; - -typedef struct _dmac_ch_cfg -{ - /** - * Bit[1:0] is source multi block transfer type - * 0x0 for continuous multiblock type - * 0x1 for reload multiblock type - * 0x2 for shadow register based multiblock type - * 0x3 for linked lisr bases multiblock type - */ - uint64_t src_multblk_type : 2; - /** - * Bit[3:2] is source multi block transfer type - * 0x0 for continuous multiblock type - * 0x1 for reload multiblock type - * 0x2 for shadow register based multiblock type - * 0x3 for linked lisr bases multiblock type - */ - uint64_t dst_multblk_type : 2; - /* Bits [31:4] is reserved*/ - uint64_t rsvd1 : 28; - /** - * Bits [34:32] is transfer type and flow control - * 0x0 transfer memory to memory and flow controler is dmac - * 0x1 transfer memory to peripheral and flow controler is dmac - * 0x2 transfer peripheral to memory and flow controler is dmac - * 0x3 transfer peripheral to peripheral and flow controler is dmac - * 0x4 transfer peripheral to memory and flow controler is - * source peripheral - * 0x5 transfer peripheral to peripheral and flow controler - * is source peripheral - * 0x6 transfer memory to peripheral and flow controler is - * destination peripheral - * 0x7 transfer peripheral to peripheral and flow controler - * is destination peripheral - */ - uint64_t tt_fc : 3; - /** - * Bit 35 is source software or hardware handshaking select - * 0x1 for software handshaking is used - * 0x0 for hardware handshaking is used - */ - uint64_t hs_sel_src : 1; - /** - * Bit 36 is destination software or hardware handshaking select - *0x1 for software handshaking is used - *0x0 for hardware handshaking is used - */ - uint64_t hs_sel_dst : 1; - /** - * Bit 37 is sorce hardware handshaking interface polarity - * 0x1 active low, 0x0 active high - */ - uint64_t src_hwhs_pol : 1; - /** - * Bit 38 is destination hardware handshaking interface polarity - * 0x1 active low, 0x0 active high - */ - uint64_t dst_hwhs_pol : 1; - /** - * Bits [41:39] is assign a hardware handshaking interface - * to source of channel x - */ - uint64_t src_per : 4; - /* Bit 43 is reserved*/ - uint64_t rsvd3 : 1; - /** - * Bits [46:44] is assign a hardware handshaking interface - * to destination of channel x - */ - uint64_t dst_per : 4; - /* Bit 48 is reserved*/ - uint64_t rsvd5 : 1; - /* Bits [51:49] is channel priority,7 is highest, 0 is lowest*/ - uint64_t ch_prior : 3; - /** - * Bit 52 is channel lock bit - * 0x0 for channel is not locked, 0x1 for channel is locked - */ - uint64_t lock_ch : 1; - /** - * Bits [54:53] is chnannel lock level - * 0x0 for duration of channel is locked for entire DMA transfer - * 0x1 for duration of channel is locked for current block transfer - */ - uint64_t lock_ch_l : 2; - uint64_t src_osr_lmt : 4; - /* Bits [58:55] is source outstanding request limit */ - uint64_t dst_osr_lmt : 4; - /* Bits [62:59] is destination outstanding request limit */ -} __attribute__((packed, aligned(8))) dmac_ch_cfg_t; - -typedef union _dmac_ch_cfg_u -{ - dmac_ch_cfg_t ch_cfg; - uint64_t data; -} dmac_ch_cfg_u_t; - -typedef struct _dmac_ch_llp -{ - /** - * Bit 0 is LLI master select - * 0x0 for next linked list item resides on AXI madster1 interface - * 0x1 for next linked list item resides on AXI madster2 interface - */ - uint64_t lms : 1; - /* Bits [5:1] is reserved */ - uint64_t rsvd1 : 5; - /* Bits [63:6] is starting address memeory of LLI block */ - uint64_t loc : 58; -} __attribute__((packed, aligned(8))) dmac_ch_llp_t; - -typedef union _dmac_ch_llp_u -{ - dmac_ch_llp_t llp; - uint64_t data; -} dmac_ch_llp_u_t; - -typedef struct _dmac_ch_status -{ - /* Bits [21:0] is completed block transfer size */ - uint64_t cmpltd_blk_size : 22; - /* Bits [46:32] is reserved */ - uint64_t rsvd1 : 15; - /* Bits [63:47] is reserved */ - uint64_t rsvd2 : 17; -} __attribute__((packed, aligned(8))) dmac_ch_status_t; - -typedef union _dmac_ch_status_u -{ - dmac_ch_status_t status; - uint64_t data; -} dmac_ch_status_u_t; - -typedef struct _dmac_ch_swhssrc -{ - /** - * Bit 0 is software handshake request for channel source - * 0x1 source periphraral request for a dma transfer - * 0x0 source peripheral is not request for a burst transfer - */ - uint64_t swhs_req_src : 1; - /** - * Bit 1 is write enable bit for software handshake request - *0x1 for enable, 0x0 for disable - */ - uint64_t swhs_req_src_we : 1; - /** - * Bit 2 is software handshake single request for channel source - * 0x1 for source peripheral requesr for a single dma transfer - * 0x0 for source peripheral is not requesting for a single transfer - */ - uint64_t swhs_sglreq_src : 1; - /** - * Bit 3 is write enable bit for software handshake - * single request for channle source - * 0x1 for enable write, 0x0 for disable write - */ - uint64_t swhs_sglreq_src_we : 1; - /** - * Bit 4 software handshake last request for channel source - * 0x1 for current transfer is last transfer - * 0x0 for current transfer is not the last transfer - */ - uint64_t swhs_lst_src : 1; - /** - * Bit 5 is write enable bit for software - * handshake last request - * 0x1 for enable, 0x0 for disable - */ - uint64_t swhs_lst_src_we : 1; - /* Bits [63:6] is reserved */ - uint64_t rsvd : 58; -} __attribute__((packed, aligned(8))) dmac_ch_swhssrc_t; - -typedef union _dmac_ch_swhssrc_u -{ - dmac_ch_swhssrc_t swhssrc; - uint64_t data; -} dmac_ch_swhssrc_u_t; - -typedef struct _dmac_ch_swhsdst -{ - /** - * Bit 0 is software handshake request for channel destination - * 0x1 destination periphraral request for a dma transfer - * 0x0 destination peripheral is not request for a burst transfer - */ - uint64_t swhs_req_dst : 1; - /** - * Bit 1 is write enable bit for software handshake request - * 0x1 for enable, 0x0 for disable - */ - uint64_t swhs_req_dst_we : 1; - /** - * Bit 2 is software handshake single request for channel destination - * 0x1 for destination peripheral requesr for a single dma transfer - * 0x0 for destination peripheral is not requesting - * for a single transfer - */ - uint64_t swhs_sglreq_dst : 1; - /** - * Bit 3 is write enable bit for software handshake - * single request for channle destination - * 0x1 for enable write, 0x0 for disable write - */ - uint64_t swhs_sglreq_dst_we : 1; - /** - * Bit 4 software handshake last request for channel dstination - * 0x1 for current transfer is last transfer - * 0x0 for current transfer is not the last transfer - */ - uint64_t swhs_lst_dst : 1; - /** - * Bit 5 is write enable bit for software handshake last request - * 0x1 for enable, 0x0 for disable - */ - uint64_t swhs_lst_dst_we : 1; - /* Bits [63:6] is reserved */ - uint64_t rsvd : 58; -} __attribute__((packed, aligned(8))) dmac_ch_swhsdst_t; - -typedef union _dmac_ch_swhsdst_u -{ - dmac_ch_swhsdst_t swhsdst; - uint64_t data; -} dmac_ch_swhsdst_u_t; - -typedef struct _dmac_ch_blk_tfr_resumereq -{ - /** - * Bit 0 is block transfer resume request bit - * 0x1 for request for resuming - * 0x0 for no request to resume - */ - uint64_t blk_tfr_resumereq : 1; - /* Bits [63:1] is reserved */ - uint64_t rsvd : 63; -} __attribute__((packed, aligned(8))) dmac_ch_blk_tfr_resumereq_t; - -typedef union _dmac_ch_blk_tfr_resumereq_u -{ - dmac_ch_blk_tfr_resumereq_t blk_tfr_resumereq; - uint64_t data; -} dmac_ch_blk_tfr_resumereq_u_t; - -typedef struct _dmac_ch_intstatus_enable -{ - /* Bit 0 is block transfer done interrupt status enable */ - uint64_t enable_block_tfr_done_intstatus : 1; - /* DMA transfer done interrupt status enable */ - uint64_t enable_dma_tfr_done_intstat : 1; - /* Bit 2 reserved */ - uint64_t rsvd1 : 1; - /* Bit 3 source transaction complete status enable */ - uint64_t enable_src_transcomp_intstat : 1; - /* Bit 4 destination transaction complete */ - uint64_t enable_dst_transcomp_intstat : 1; - /* Bit 5 Source Decode Error Status Enable */ - uint64_t enable_src_dec_err_intstat : 1; - /* Bit 6 Destination Decode Error Status Enable */ - uint64_t enable_dst_dec_err_intstat : 1; - /* Bit 7 Source Slave Error Status Enable */ - uint64_t enable_src_slv_err_intstat : 1; - /* Bit 8 Destination Slave Error Status Enable */ - uint64_t enable_dst_slv_err_intstat : 1; - /* Bit 9 LLI Read Decode Error Status Enable */ - uint64_t enable_lli_rd_dec_err_intstat : 1; - /* Bit 10 LLI WRITE Decode Error Status Enable */ - uint64_t enable_lli_wr_dec_err_intstat : 1; - /* Bit 11 LLI Read Slave Error Status Enable */ - uint64_t enable_lli_rd_slv_err_intstat : 1; - /* Bit 12 LLI WRITE Slave Error Status Enable */ - uint64_t enable_lli_wr_slv_err_intstat : 1; - uint64_t rsvd2 : 51; -} dmac_ch_intstatus_enable_t; - -typedef union _dmac_ch_intstatus_enable_u -{ - dmac_ch_intstatus_enable_t ch_intstatus_enable; - uint64_t data; -} dmac_ch_intstatus_enable_u_t; - -typedef struct _dmac_ch_intclear -{ - /* Bit 0 block transfer done interrupt clear bit.*/ - uint64_t blk_tfr_done_intstat : 1; - /* Bit 1 DMA transfer done interrupt clear bit */ - uint64_t dma_tfr_done_intstat : 1; - /* Bit 2 is reserved */ - uint64_t resv1 : 1; - uint64_t resv2 : 61; -} __attribute__((packed, aligned(8))) dmac_ch_intclear_t; - -typedef union _dmac_ch_intclear_u -{ - uint64_t data; - dmac_ch_intclear_t intclear; -} dmac_ch_intclear_u_t; - -typedef struct _dmac_channel -{ - /* (0x100) SAR Address Register */ - uint64_t sar; - /* (0x108) DAR Address Register */ - uint64_t dar; - /* (0x110) Block Transfer Size Register */ - uint64_t block_ts; - /* (0x118) Control Register */ - uint64_t ctl; - /* (0x120) Configure Register */ - uint64_t cfg; - /* (0x128) Linked List Pointer register */ - uint64_t llp; - /* (0x130) Channelx Status Register */ - uint64_t status; - /* (0x138) Channelx Software handshake Source Register */ - uint64_t swhssrc; - /* (0x140) Channelx Software handshake Destination Register */ - uint64_t swhsdst; - /* (0x148) Channelx Block Transfer Resume Request Register */ - uint64_t blk_tfr; - /* (0x150) Channelx AXI ID Register */ - uint64_t axi_id; - /* (0x158) Channelx AXI QOS Register */ - uint64_t axi_qos; - /* Reserved address */ - uint64_t reserved1[4]; - /* (0x180) Interrupt Status Enable Register */ - uint64_t intstatus_en; - /* (0x188) Channelx Interrupt Status Register */ - uint64_t intstatus; - /* (0x190) Interrupt Siganl Enable Register */ - uint64_t intsignal_en; - /* (0x198) Interrupt Clear Register */ - uint64_t intclear; - uint64_t reserved2[12]; -} __attribute__((packed, aligned(8))) dmac_channel_t; - -typedef struct _dmac -{ - /* (0x00) DMAC ID Rgister */ - uint64_t id; - /* (0x08) DMAC COMPVER Register */ - uint64_t compver; - /* (0x10) DMAC Configure Register */ - uint64_t cfg; - /* (0x18) Channel Enable Register */ - uint64_t chen; - uint64_t reserved1[2]; - /* (0x30) DMAC Interrupt Status Register */ - uint64_t intstatus; - /* (0x38) DMAC Common register Interrupt Status Register */ - uint64_t com_intclear; - /* (0x40) DMAC Common Interrupt Enable Register */ - uint64_t com_intstatus_en; - /* (0x48) DMAC Common Interrupt Signal Enable Register */ - uint64_t com_intsignal_en; - /* (0x50) DMAC Common Interrupt Status */ - uint64_t com_intstatus; - /* (0x58) DMAC Reset register */ - uint64_t reset; - uint64_t reserved2[20]; - dmac_channel_t channel[DMAC_CHANNEL_COUNT]; -} __attribute__((packed, aligned(8))) dmac_t; - -typedef struct _dmac_channel_config -{ - uint64_t sar; - uint64_t dar; - uint8_t ctl_sms; - uint8_t ctl_dms; - uint8_t ctl_src_msize; - uint8_t ctl_drc_msize; - uint8_t ctl_sinc; - uint8_t ctl_dinc; - uint8_t ctl_src_tr_width; - uint8_t ctl_dst_tr_width; - uint8_t ctl_ioc_blktfr; - uint8_t ctl_src_stat_en; - uint8_t ctl_dst_stat_en; - uint8_t cfg_dst_per; - uint8_t cfg_src_per; - uint8_t cfg_src_hs_pol; - uint8_t cfg_dst_hs_pol; - uint8_t cfg_hs_sel_src; - uint8_t cfg_hs_sel_dst; - uint64_t cfg_src_multblk_type; - uint64_t cfg_dst_multblk_type; - uint64_t llp_loc; - uint8_t llp_lms; - uint64_t ctl_block_ts; - uint8_t ctl_tt_fc; - uint8_t cfg_protctl; - uint8_t cfg_fifo_mode; - uint8_t cfg_fcmode; - uint8_t cfg_lock_ch_l; - uint8_t cfg_ch_prior; -} dmac_channel_config_t; - -#define LIST_ENTRY(ptr, type, member) \ - ((type *)((char *)(ptr) - (unsigned long)(&((type *)0)->member))) - -struct list_head_t -{ - struct list_head_t *next, *prev; -}; - -/** - * @brief Dmac.data/dw_dmac_lli_item - * - * @desc This structure is used when creating Linked List Items. - * - * @see dw_dmac_addLliItem() - */ -typedef struct _dmac_lli_item -{ - uint64_t sar; - uint64_t dar; - uint64_t ch_block_ts; - uint64_t llp; - uint64_t ctl; - uint64_t sstat; - uint64_t dstat; - uint64_t resv; -} __attribute__((packed, aligned(64))) dmac_lli_item_t; - -extern volatile dmac_t *const dmac; - -/** - * @brief Dmac initialize - */ -void dmac_init(void); - -/** - * @brief Set dmac param - * - * @param[in] channel_num Dmac channel - * @param[in] src Dmac source - * @param[in] dest Dmac dest - * @param[in] src_inc Source address increase or not - * @param[in] dest_inc Dest address increase or not - * @param[in] dmac_burst_size Dmac burst length - * @param[in] dmac_trans_width Dmac transfer data width - * @param[in] block_size Dmac transfer length - * - */ -void dmac_set_single_mode(dmac_channel_number_t channel_num, - const void *src, void *dest, dmac_address_increment_t src_inc, - dmac_address_increment_t dest_inc, - dmac_burst_trans_length_t dmac_burst_size, - dmac_transfer_width_t dmac_trans_width, - size_t block_size); - -/** - * @brief Determine the transfer is complete or not - * - * @param[in] channel_num Dmac channel - * - * @return result - * - 0 uncompleted - * - 1 completed -*/ -int dmac_is_done(dmac_channel_number_t channel_num); - -/** - * @brief Wait for dmac work done - * - * @param[in] channel_num Dmac channel - * - */ -void dmac_wait_done(dmac_channel_number_t channel_num); - -/** - * @brief Determine the dma is idle or not - * - * @param[in] channel_num Dmac channel - * - * @return result - * - 0 busy - * - 1 idel -*/ -int dmac_is_idle(dmac_channel_number_t channel_num); - -/** - * @brief Wait for dmac idle - * - * @param[in] channel_num Dmac channel - * - */ -void dmac_wait_idle(dmac_channel_number_t channel_num); - -/** - * @brief Set interrupt param - * - * @param[in] channel_num Dmac channel - * @param[in] dmac_callback Dmac interrupt callback - * @param[in] ctx The param of callback - * @param[in] priority Interrupt priority - */ -void dmac_set_irq(dmac_channel_number_t channel_num , plic_irq_callback_t dmac_callback, void *ctx, uint32_t priority); - -/** - * @brief Set interrupt param - * - * @param[in] channel_num Dmac channel - * @param[in] dmac_callback Dmac interrupt callback - * @param[in] ctx The param of callback - * @param[in] priority Interrupt priority - */ -void dmac_irq_register(dmac_channel_number_t channel_num , plic_irq_callback_t dmac_callback, void *ctx, uint32_t priority); - - -/** - * @brief Unregister dmac interrupt - * - * @param[in] channel_num Dmac channel - * - */ -void dmac_irq_unregister(dmac_channel_number_t channel_num); - -/** - * @brief Disable dmac interrupt - * - * @param[in] channel_num Dmac channel - * - */ -void dmac_free_irq(dmac_channel_number_t channel_num); - -/** - * @brief Set source dest and length - * - * @param[in] channel_num Dmac channel - * @param[in] src Source - * @param[in] dest Dest - * @param[in] len The length of dmac transfer - */ -void dmac_set_src_dest_length(dmac_channel_number_t channel_num, const void *src, void *dest, size_t len); - -/** - * @brief Disable dmac channel interrupt - * - * @param[in] channel_num Dmac channel - * -*/ -void dmac_disable_channel_interrupt(dmac_channel_number_t channel_num); - -/** - * @brief Disable dmac channel - * - * @param[in] channel_num Dmac channel - * -*/ -void dmac_channel_disable(dmac_channel_number_t channel_num); - -/** - * @brief Enable dmac channel - * - * @param[in] channel_num Dmac channel - * -*/ -void dmac_channel_enable(dmac_channel_number_t channel_num); - -#ifdef __cplusplus -} -#endif - -#endif /* _DRIVER_DMAC_H */ diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/dvp.h b/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/dvp.h deleted file mode 100644 index c6d6a7f..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/dvp.h +++ /dev/null @@ -1,269 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef _DRIVER_DVP_H -#define _DRIVER_DVP_H -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/* clang-format off */ -/** - * @brief DVP object - */ -typedef struct _dvp -{ - uint32_t dvp_cfg; - uint32_t r_addr; - uint32_t g_addr; - uint32_t b_addr; - uint32_t cmos_cfg; - uint32_t sccb_cfg; - uint32_t sccb_ctl; - uint32_t axi; - uint32_t sts; - uint32_t reverse; - uint32_t rgb_addr; -} __attribute__((packed, aligned(4))) dvp_t; - -/* DVP Config Register */ -#define DVP_CFG_START_INT_ENABLE 0x00000001U -#define DVP_CFG_FINISH_INT_ENABLE 0x00000002U -#define DVP_CFG_AI_OUTPUT_ENABLE 0x00000004U -#define DVP_CFG_DISPLAY_OUTPUT_ENABLE 0x00000008U -#define DVP_CFG_AUTO_ENABLE 0x00000010U -#define DVP_CFG_BURST_SIZE_4BEATS 0x00000100U -#define DVP_CFG_FORMAT_MASK 0x00000600U -#define DVP_CFG_RGB_FORMAT 0x00000000U -#define DVP_CFG_YUV_FORMAT 0x00000200U -#define DVP_CFG_Y_FORMAT 0x00000600U -#define DVP_CFG_HREF_BURST_NUM_MASK 0x000FF000U -#define DVP_CFG_HREF_BURST_NUM(x) ((x) << 12) -#define DVP_CFG_LINE_NUM_MASK 0x3FF00000U -#define DVP_CFG_LINE_NUM(x) ((x) << 20) - -/* DVP CMOS Config Register */ -#define DVP_CMOS_CLK_DIV_MASK 0x000000FFU -#define DVP_CMOS_CLK_DIV(x) ((x) << 0) -#define DVP_CMOS_CLK_ENABLE 0x00000100U -#define DVP_CMOS_RESET 0x00010000U -#define DVP_CMOS_POWER_DOWN 0x01000000U - -/* DVP SCCB Config Register */ -#define DVP_SCCB_BYTE_NUM_MASK 0x00000003U -#define DVP_SCCB_BYTE_NUM_2 0x00000001U -#define DVP_SCCB_BYTE_NUM_3 0x00000002U -#define DVP_SCCB_BYTE_NUM_4 0x00000003U -#define DVP_SCCB_SCL_LCNT_MASK 0x0000FF00U -#define DVP_SCCB_SCL_LCNT(x) ((x) << 8) -#define DVP_SCCB_SCL_HCNT_MASK 0x00FF0000U -#define DVP_SCCB_SCL_HCNT(x) ((x) << 16) -#define DVP_SCCB_RDATA_BYTE(x) ((x) >> 24) - -/* DVP SCCB Control Register */ -#define DVP_SCCB_WRITE_DATA_ENABLE 0x00000001U -#define DVP_SCCB_DEVICE_ADDRESS(x) ((x) << 0) -#define DVP_SCCB_REG_ADDRESS(x) ((x) << 8) -#define DVP_SCCB_WDATA_BYTE0(x) ((x) << 16) -#define DVP_SCCB_WDATA_BYTE1(x) ((x) << 24) - -/* DVP AXI Register */ -#define DVP_AXI_GM_MLEN_MASK 0x000000FFU -#define DVP_AXI_GM_MLEN_1BYTE 0x00000000U -#define DVP_AXI_GM_MLEN_4BYTE 0x00000003U - -/* DVP STS Register */ -#define DVP_STS_FRAME_START 0x00000001U -#define DVP_STS_FRAME_START_WE 0x00000002U -#define DVP_STS_FRAME_FINISH 0x00000100U -#define DVP_STS_FRAME_FINISH_WE 0x00000200U -#define DVP_STS_DVP_EN 0x00010000U -#define DVP_STS_DVP_EN_WE 0x00020000U -#define DVP_STS_SCCB_EN 0x01000000U -#define DVP_STS_SCCB_EN_WE 0x02000000U -/* clang-format on */ - -typedef enum _dvp_output_mode -{ - DVP_OUTPUT_AI, - DVP_OUTPUT_DISPLAY, -} dvp_output_mode_t; - -/** - * @brief DVP object instance - */ -extern volatile dvp_t* const dvp; - -/** - * @brief Initialize DVP - */ -void dvp_init(uint8_t reg_len); - -/** - * @brief Set image format - * - * @param[in] format The image format - */ -void dvp_set_image_format(uint32_t format); - -/** - * @brief Set image size - * - * @param[in] width The width of image - * @param[in] height The height of image - */ -void dvp_set_image_size(uint32_t width, uint32_t height); - -/** - * @brief Set the address of RGB for AI - * - * @param[in] r_addr The R address of RGB - * @param[in] g_addr The G address of RGB - * @param[in] b_addr The B address of RGB - */ -void dvp_set_ai_addr(uint32_t r_addr, uint32_t g_addr, uint32_t b_addr); - -/** - * @brief Set the address of RGB for display - * - * @param[in] r_addr The R address of RGB - * @param[in] g_addr The G address of RGB - * @param[in] b_addr The B address of RGB - */ -void dvp_set_display_addr(uint32_t addr); - -/** - * @brief The frame start transfer - */ -void dvp_start_frame(void); - -/** - * @brief The DVP convert start - */ -void dvp_start_convert(void); - -/** - * @brief The DVP convert finish - */ -void dvp_finish_convert(void); - -/** - * @brief Get the image data - * - * @note The image data stored in the address of RGB - */ -void dvp_get_image(void); - -/** - * @brief Use SCCB write register - * - * @param[in] dev_addr The device address - * @param[in] reg_addr The register address - * @param[in] reg_data The register data - */ -void dvp_sccb_send_data(uint8_t dev_addr, uint16_t reg_addr, uint8_t reg_data); - -/** - * @brief Use SCCB read register - * - * @param[in] dev_addr The device address - * @param[in] reg_addr The register address - * - * @return The register value - */ -uint8_t dvp_sccb_receive_data(uint8_t dev_addr, uint16_t reg_addr); - -/** - * @brief Enable dvp burst - */ -void dvp_enable_burst(void); - -/** - * @brief Disable dvp burst - */ -void dvp_disable_burst(void); - -/** - * @brief Enable or disable dvp interrupt - * - * @param[in] interrupt Dvp interrupt - * @param[in] status 0:disable 1:enable - * - */ -void dvp_config_interrupt(uint32_t interrupt, uint8_t enable); - -/** - * @brief Get dvp interrupt status - * - * @param[in] interrupt Dvp interrupt - * - * - * @return Interrupt status - * - 0 false - * - 1 true - */ -int dvp_get_interrupt(uint32_t interrupt); - -/** - * @brief Clear dvp interrupt status - * - * @param[in] interrupt Dvp interrupt - * - */ -void dvp_clear_interrupt(uint32_t interrupt); - -/** - * @brief Enable dvp auto mode - */ -void dvp_enable_auto(void); - -/** - * @brief Disable dvp auto mode - */ -void dvp_disable_auto(void); - -/** - * @brief Dvp ouput data enable or not - * - * @param[in] index 0:AI, 1:display - * @param[in] enable 0:disable, 1:enable - * - */ -void dvp_set_output_enable(dvp_output_mode_t index, int enable); - -/** - * @brief Set sccb clock rate - * - * @param[in] clk_rate Sccb clock rate - * - * @return The real sccb clock rate - */ -uint32_t dvp_sccb_set_clk_rate(uint32_t clk_rate); - -/** - * @brief Set xclk rate - * - * @param[in] clk_rate xclk rate - * - * @return The real xclk rate - */ -uint32_t dvp_set_xclk_rate(uint32_t xclk_rate); - -#ifdef __cplusplus -} -#endif - -#endif /* _DRIVER_DVP_H */ diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/fft.h b/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/fft.h deleted file mode 100644 index 6faa8c5..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/fft.h +++ /dev/null @@ -1,247 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef _DRIVER_FFT_H -#define _DRIVER_FFT_H - -#include -#include "platform.h" - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct _complex_hard -{ - int16_t real; - int16_t imag; -} complex_hard_t; - -typedef struct _fft_data -{ - int16_t I1; - int16_t R1; - int16_t I2; - int16_t R2; -} fft_data_t; - -typedef enum _fft_point -{ - FFT_512, - FFT_256, - FFT_128, - FFT_64, -} fft_point_t; - -typedef enum _fft_direction -{ - FFT_DIR_BACKWARD, - FFT_DIR_FORWARD, - FFT_DIR_MAX, -} fft_direction_t; - -/** - * @brief FFT algorithm accelerator register - * - * @note FFT algorithm accelerator register table - * - * | Offset | Name | Description | - * |-----------|----------------|-------------------------------------| - * | 0x00 | fft_input_fifo | input data fifo | - * | 0x08 | fft_ctrl | fft ctrl reg | - * | 0x10 | fifo_ctrl | fifo ctrl | - * | 0x18 | intr_mask | interrupt mask | - * | 0x20 | intr_clear | interrupt clear | - * | 0x28 | fft_status | fft status reg | - * | 0x30 | fft_status_raw | fft_status_raw | - * | 0x38 | fft_output_fifo| fft_output_fifo | - * - */ - -/** - * @brief The calculation data is input through this register - * - * No. 0 Register (0x00) - */ -typedef struct _fft_input_fifo -{ - uint64_t fft_input_fifo : 64; -} __attribute__((packed, aligned(8))) fft_input_fifo_t; - -/** - * @brief fft ctrl reg - * - * No. 1 Register (0x08) - */ -typedef struct _fft_fft_ctrl -{ - /** - *FFT calculation data length: - *b'000:512 point; b'001:256 point; b'010:128 point; b'011:64 point; - */ - uint64_t fft_point : 3; - /* FFT mode: b'0:FFT b'1:IFFT */ - uint64_t fft_mode : 1; - /* Corresponding to the nine layer butterfly shift operation, 0x0: does not shift; 0x1: shift 1st layer. ...*/ - uint64_t fft_shift : 9; - /* FFT enable: b'0:disable b'1:enable */ - uint64_t fft_enable : 1; - /* FFT DMA enable: b'0:disable b'1:enable */ - uint64_t dma_send : 1; - /** - *Input data arrangement: b'00:RIRI; b'01:only real part exist, RRRR; - *b'10:First input the real part and then input the imaginary part. - */ - uint64_t fft_input_mode : 2; - /* Effective width of input data. b'0:64bit effective; b'1:32bit effective */ - uint64_t fft_data_mode : 1; - uint64_t reserved : 46; -} __attribute__((packed, aligned(8))) fft_fft_ctrl_t; - -/** - * @brief fifo ctrl - * - * No. 2 Register (0x10) - */ -typedef struct _fft_fifo_ctrl -{ - /* Response memory initialization flag.b'1:initialization */ - uint64_t resp_fifo_flush_n : 1; - /* Command memory initialization flag.b'1:initialization */ - uint64_t cmd_fifo_flush_n : 1; - /* Output interface memory initialization flag.b'1:initialization */ - uint64_t gs_fifo_flush_n : 1; - uint64_t reserved : 61; -} __attribute__((packed, aligned(8))) fft_fifo_ctrl_t; - -/** - * @brief interrupt mask - * - * No. 3 Register (0x18) - */ -typedef struct _fft_intr_mask -{ - /** - *FFT return status set. - *b'0:FFT returns to the state after completion. - *b'1:FFT does not return to the state after completion - */ - uint64_t fft_done_mask : 1; - uint64_t reserved : 63; -} __attribute__((packed, aligned(8))) fft_intr_mask_t; - -/** - * @brief interrupt clear - * - * No. 4 Register (0x20) - */ -typedef struct _fft_intr_clear -{ - /* The interrupt state clears. b'1:clear current interrupt request */ - uint64_t fft_done_clear : 1; - uint64_t reserved1 : 63; -} __attribute__((packed, aligned(8))) fft_intr_clear_t; - -/** - * @brief fft status reg - * - * No. 5 Register (0x28) - */ -typedef struct _fft_status -{ - /* FFT calculation state.b'0:not completed; b'1:completed */ - uint64_t fft_done_status : 1; - uint64_t reserved1 : 63; -} __attribute__((packed, aligned(8))) fft_status_t; - -/** - * @brief fft status raw - * - * No. 6 Register (0x30) - */ -typedef struct _fft_status_raw -{ - /* FFT calculation state. b'1:done */ - uint64_t fft_done_status_raw : 1; - /* FFT calculation state. b'1:working */ - uint64_t fft_work_status_raw : 1; - uint64_t reserved : 62; -} __attribute__((packed, aligned(8))) fft_status_raw_t; - -/** - * @brief Output of FFT calculation data through this register - * - * No. 7 Register (0x38) - */ -typedef struct _fft_output_fifo -{ - uint64_t fft_output_fifo : 64; -} __attribute__((packed, aligned(8))) fft_output_fifo_t; - -/** - * @brief Fast Fourier transform (FFT) algorithm accelerator object - * - * A fast Fourier transform (FFT) algorithm computes the discrete - * Fourier transform (DFT) of a sequence, or its inverse (IFFT). - * Fourier analysis converts a signal from its original domain - * (often time or space) to a representation in the frequency - * domain and vice versa. An FFT rapidly computes such - * transformations by factorizing the DFT matrix into a product of - * sparse (mostly zero) factors. - */ -typedef struct _fft -{ - /* No. 0 (0x00): input data fifo */ - fft_input_fifo_t fft_input_fifo; - /* No. 1 (0x08): fft ctrl reg */ - fft_fft_ctrl_t fft_ctrl; - /* No. 2 (0x10): fifo ctrl */ - fft_fifo_ctrl_t fifo_ctrl; - /* No. 3 (0x18): interrupt mask */ - fft_intr_mask_t intr_mask; - /* No. 4 (0x20): interrupt clear */ - fft_intr_clear_t intr_clear; - /* No. 5 (0x28): fft status reg */ - fft_status_t fft_status; - /* No. 6 (0x30): fft_status_raw */ - fft_status_raw_t fft_status_raw; - /* No. 7 (0x38): fft_output_fifo */ - fft_output_fifo_t fft_output_fifo; -} __attribute__((packed, aligned(8))) fft_t; - -/** - * @brief Do 16bit quantized complex FFT by DMA - * - * @param[in] dma_send_channel_num Dmac send channel number. - * @param[in] dma_receive_channel_num Dmac receive channel number. - * @param[in] shift The shifts selection in 9 stage - * @param[in] direction The direction - * @param[in] input The input data - * @param[in] point The FFT points count - * @param[out] output The output data - */ -void fft_complex_uint16_dma(dmac_channel_number_t dma_send_channel_num, - dmac_channel_number_t dma_receive_channel_num, - uint16_t shift, - fft_direction_t direction, - const uint64_t *input, - size_t point_num, - uint64_t *output); - -#ifdef __cplusplus -} -#endif - -#endif /* _DRIVER_FFT_H */ - diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/fpioa.h b/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/fpioa.h deleted file mode 100644 index 8d9f111..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/fpioa.h +++ /dev/null @@ -1,1003 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * 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. - */ -/** - * @file - * @brief Field Programmable GPIO Array (FPIOA) - * - * The FPIOA peripheral supports the following features: - * - * - 48 IO with 256 functions - * - * - Schmitt trigger - * - * - Invert input and output - * - * - Pull up and pull down - * - * - Driving selector - * - * - Static input and output - * - */ - -#ifndef _DRIVER_FPIOA_H -#define _DRIVER_FPIOA_H - -#include -#include "platform.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/* clang-format off */ -/* Pad number settings */ -#define FPIOA_NUM_IO (48) -/* clang-format on */ - -/** - * @brief FPIOA IO functions - * - * @note FPIOA pin function table - * - * | Function | Name | Description | - * |-----------|------------------|-----------------------------------| - * | 0 | JTAG_TCLK | JTAG Test Clock | - * | 1 | JTAG_TDI | JTAG Test Data In | - * | 2 | JTAG_TMS | JTAG Test Mode Select | - * | 3 | JTAG_TDO | JTAG Test Data Out | - * | 4 | SPI0_D0 | SPI0 Data 0 | - * | 5 | SPI0_D1 | SPI0 Data 1 | - * | 6 | SPI0_D2 | SPI0 Data 2 | - * | 7 | SPI0_D3 | SPI0 Data 3 | - * | 8 | SPI0_D4 | SPI0 Data 4 | - * | 9 | SPI0_D5 | SPI0 Data 5 | - * | 10 | SPI0_D6 | SPI0 Data 6 | - * | 11 | SPI0_D7 | SPI0 Data 7 | - * | 12 | SPI0_SS0 | SPI0 Chip Select 0 | - * | 13 | SPI0_SS1 | SPI0 Chip Select 1 | - * | 14 | SPI0_SS2 | SPI0 Chip Select 2 | - * | 15 | SPI0_SS3 | SPI0 Chip Select 3 | - * | 16 | SPI0_ARB | SPI0 Arbitration | - * | 17 | SPI0_SCLK | SPI0 Serial Clock | - * | 18 | UARTHS_RX | UART High speed Receiver | - * | 19 | UARTHS_TX | UART High speed Transmitter | - * | 20 | RESV6 | Reserved function | - * | 21 | RESV7 | Reserved function | - * | 22 | CLK_SPI1 | Clock SPI1 | - * | 23 | CLK_I2C1 | Clock I2C1 | - * | 24 | GPIOHS0 | GPIO High speed 0 | - * | 25 | GPIOHS1 | GPIO High speed 1 | - * | 26 | GPIOHS2 | GPIO High speed 2 | - * | 27 | GPIOHS3 | GPIO High speed 3 | - * | 28 | GPIOHS4 | GPIO High speed 4 | - * | 29 | GPIOHS5 | GPIO High speed 5 | - * | 30 | GPIOHS6 | GPIO High speed 6 | - * | 31 | GPIOHS7 | GPIO High speed 7 | - * | 32 | GPIOHS8 | GPIO High speed 8 | - * | 33 | GPIOHS9 | GPIO High speed 9 | - * | 34 | GPIOHS10 | GPIO High speed 10 | - * | 35 | GPIOHS11 | GPIO High speed 11 | - * | 36 | GPIOHS12 | GPIO High speed 12 | - * | 37 | GPIOHS13 | GPIO High speed 13 | - * | 38 | GPIOHS14 | GPIO High speed 14 | - * | 39 | GPIOHS15 | GPIO High speed 15 | - * | 40 | GPIOHS16 | GPIO High speed 16 | - * | 41 | GPIOHS17 | GPIO High speed 17 | - * | 42 | GPIOHS18 | GPIO High speed 18 | - * | 43 | GPIOHS19 | GPIO High speed 19 | - * | 44 | GPIOHS20 | GPIO High speed 20 | - * | 45 | GPIOHS21 | GPIO High speed 21 | - * | 46 | GPIOHS22 | GPIO High speed 22 | - * | 47 | GPIOHS23 | GPIO High speed 23 | - * | 48 | GPIOHS24 | GPIO High speed 24 | - * | 49 | GPIOHS25 | GPIO High speed 25 | - * | 50 | GPIOHS26 | GPIO High speed 26 | - * | 51 | GPIOHS27 | GPIO High speed 27 | - * | 52 | GPIOHS28 | GPIO High speed 28 | - * | 53 | GPIOHS29 | GPIO High speed 29 | - * | 54 | GPIOHS30 | GPIO High speed 30 | - * | 55 | GPIOHS31 | GPIO High speed 31 | - * | 56 | GPIO0 | GPIO pin 0 | - * | 57 | GPIO1 | GPIO pin 1 | - * | 58 | GPIO2 | GPIO pin 2 | - * | 59 | GPIO3 | GPIO pin 3 | - * | 60 | GPIO4 | GPIO pin 4 | - * | 61 | GPIO5 | GPIO pin 5 | - * | 62 | GPIO6 | GPIO pin 6 | - * | 63 | GPIO7 | GPIO pin 7 | - * | 64 | UART1_RX | UART1 Receiver | - * | 65 | UART1_TX | UART1 Transmitter | - * | 66 | UART2_RX | UART2 Receiver | - * | 67 | UART2_TX | UART2 Transmitter | - * | 68 | UART3_RX | UART3 Receiver | - * | 69 | UART3_TX | UART3 Transmitter | - * | 70 | SPI1_D0 | SPI1 Data 0 | - * | 71 | SPI1_D1 | SPI1 Data 1 | - * | 72 | SPI1_D2 | SPI1 Data 2 | - * | 73 | SPI1_D3 | SPI1 Data 3 | - * | 74 | SPI1_D4 | SPI1 Data 4 | - * | 75 | SPI1_D5 | SPI1 Data 5 | - * | 76 | SPI1_D6 | SPI1 Data 6 | - * | 77 | SPI1_D7 | SPI1 Data 7 | - * | 78 | SPI1_SS0 | SPI1 Chip Select 0 | - * | 79 | SPI1_SS1 | SPI1 Chip Select 1 | - * | 80 | SPI1_SS2 | SPI1 Chip Select 2 | - * | 81 | SPI1_SS3 | SPI1 Chip Select 3 | - * | 82 | SPI1_ARB | SPI1 Arbitration | - * | 83 | SPI1_SCLK | SPI1 Serial Clock | - * | 84 | SPI_SLAVE_D0 | SPI Slave Data 0 | - * | 85 | SPI_SLAVE_SS | SPI Slave Select | - * | 86 | SPI_SLAVE_SCLK | SPI Slave Serial Clock | - * | 87 | I2S0_MCLK | I2S0 Master Clock | - * | 88 | I2S0_SCLK | I2S0 Serial Clock(BCLK) | - * | 89 | I2S0_WS | I2S0 Word Select(LRCLK) | - * | 90 | I2S0_IN_D0 | I2S0 Serial Data Input 0 | - * | 91 | I2S0_IN_D1 | I2S0 Serial Data Input 1 | - * | 92 | I2S0_IN_D2 | I2S0 Serial Data Input 2 | - * | 93 | I2S0_IN_D3 | I2S0 Serial Data Input 3 | - * | 94 | I2S0_OUT_D0 | I2S0 Serial Data Output 0 | - * | 95 | I2S0_OUT_D1 | I2S0 Serial Data Output 1 | - * | 96 | I2S0_OUT_D2 | I2S0 Serial Data Output 2 | - * | 97 | I2S0_OUT_D3 | I2S0 Serial Data Output 3 | - * | 98 | I2S1_MCLK | I2S1 Master Clock | - * | 99 | I2S1_SCLK | I2S1 Serial Clock(BCLK) | - * | 100 | I2S1_WS | I2S1 Word Select(LRCLK) | - * | 101 | I2S1_IN_D0 | I2S1 Serial Data Input 0 | - * | 102 | I2S1_IN_D1 | I2S1 Serial Data Input 1 | - * | 103 | I2S1_IN_D2 | I2S1 Serial Data Input 2 | - * | 104 | I2S1_IN_D3 | I2S1 Serial Data Input 3 | - * | 105 | I2S1_OUT_D0 | I2S1 Serial Data Output 0 | - * | 106 | I2S1_OUT_D1 | I2S1 Serial Data Output 1 | - * | 107 | I2S1_OUT_D2 | I2S1 Serial Data Output 2 | - * | 108 | I2S1_OUT_D3 | I2S1 Serial Data Output 3 | - * | 109 | I2S2_MCLK | I2S2 Master Clock | - * | 110 | I2S2_SCLK | I2S2 Serial Clock(BCLK) | - * | 111 | I2S2_WS | I2S2 Word Select(LRCLK) | - * | 112 | I2S2_IN_D0 | I2S2 Serial Data Input 0 | - * | 113 | I2S2_IN_D1 | I2S2 Serial Data Input 1 | - * | 114 | I2S2_IN_D2 | I2S2 Serial Data Input 2 | - * | 115 | I2S2_IN_D3 | I2S2 Serial Data Input 3 | - * | 116 | I2S2_OUT_D0 | I2S2 Serial Data Output 0 | - * | 117 | I2S2_OUT_D1 | I2S2 Serial Data Output 1 | - * | 118 | I2S2_OUT_D2 | I2S2 Serial Data Output 2 | - * | 119 | I2S2_OUT_D3 | I2S2 Serial Data Output 3 | - * | 120 | RESV0 | Reserved function | - * | 121 | RESV1 | Reserved function | - * | 122 | RESV2 | Reserved function | - * | 123 | RESV3 | Reserved function | - * | 124 | RESV4 | Reserved function | - * | 125 | RESV5 | Reserved function | - * | 126 | I2C0_SCLK | I2C0 Serial Clock | - * | 127 | I2C0_SDA | I2C0 Serial Data | - * | 128 | I2C1_SCLK | I2C1 Serial Clock | - * | 129 | I2C1_SDA | I2C1 Serial Data | - * | 130 | I2C2_SCLK | I2C2 Serial Clock | - * | 131 | I2C2_SDA | I2C2 Serial Data | - * | 132 | CMOS_XCLK | DVP System Clock | - * | 133 | CMOS_RST | DVP System Reset | - * | 134 | CMOS_PWDN | DVP Power Down Mode | - * | 135 | CMOS_VSYNC | DVP Vertical Sync | - * | 136 | CMOS_HREF | DVP Horizontal Reference output | - * | 137 | CMOS_PCLK | Pixel Clock | - * | 138 | CMOS_D0 | Data Bit 0 | - * | 139 | CMOS_D1 | Data Bit 1 | - * | 140 | CMOS_D2 | Data Bit 2 | - * | 141 | CMOS_D3 | Data Bit 3 | - * | 142 | CMOS_D4 | Data Bit 4 | - * | 143 | CMOS_D5 | Data Bit 5 | - * | 144 | CMOS_D6 | Data Bit 6 | - * | 145 | CMOS_D7 | Data Bit 7 | - * | 146 | SCCB_SCLK | SCCB Serial Clock | - * | 147 | SCCB_SDA | SCCB Serial Data | - * | 148 | UART1_CTS | UART1 Clear To Send | - * | 149 | UART1_DSR | UART1 Data Set Ready | - * | 150 | UART1_DCD | UART1 Data Carrier Detect | - * | 151 | UART1_RI | UART1 Ring Indicator | - * | 152 | UART1_SIR_IN | UART1 Serial Infrared Input | - * | 153 | UART1_DTR | UART1 Data Terminal Ready | - * | 154 | UART1_RTS | UART1 Request To Send | - * | 155 | UART1_OUT2 | UART1 User-designated Output 2 | - * | 156 | UART1_OUT1 | UART1 User-designated Output 1 | - * | 157 | UART1_SIR_OUT | UART1 Serial Infrared Output | - * | 158 | UART1_BAUD | UART1 Transmit Clock Output | - * | 159 | UART1_RE | UART1 Receiver Output Enable | - * | 160 | UART1_DE | UART1 Driver Output Enable | - * | 161 | UART1_RS485_EN | UART1 RS485 Enable | - * | 162 | UART2_CTS | UART2 Clear To Send | - * | 163 | UART2_DSR | UART2 Data Set Ready | - * | 164 | UART2_DCD | UART2 Data Carrier Detect | - * | 165 | UART2_RI | UART2 Ring Indicator | - * | 166 | UART2_SIR_IN | UART2 Serial Infrared Input | - * | 167 | UART2_DTR | UART2 Data Terminal Ready | - * | 168 | UART2_RTS | UART2 Request To Send | - * | 169 | UART2_OUT2 | UART2 User-designated Output 2 | - * | 170 | UART2_OUT1 | UART2 User-designated Output 1 | - * | 171 | UART2_SIR_OUT | UART2 Serial Infrared Output | - * | 172 | UART2_BAUD | UART2 Transmit Clock Output | - * | 173 | UART2_RE | UART2 Receiver Output Enable | - * | 174 | UART2_DE | UART2 Driver Output Enable | - * | 175 | UART2_RS485_EN | UART2 RS485 Enable | - * | 176 | UART3_CTS | UART3 Clear To Send | - * | 177 | UART3_DSR | UART3 Data Set Ready | - * | 178 | UART3_DCD | UART3 Data Carrier Detect | - * | 179 | UART3_RI | UART3 Ring Indicator | - * | 180 | UART3_SIR_IN | UART3 Serial Infrared Input | - * | 181 | UART3_DTR | UART3 Data Terminal Ready | - * | 182 | UART3_RTS | UART3 Request To Send | - * | 183 | UART3_OUT2 | UART3 User-designated Output 2 | - * | 184 | UART3_OUT1 | UART3 User-designated Output 1 | - * | 185 | UART3_SIR_OUT | UART3 Serial Infrared Output | - * | 186 | UART3_BAUD | UART3 Transmit Clock Output | - * | 187 | UART3_RE | UART3 Receiver Output Enable | - * | 188 | UART3_DE | UART3 Driver Output Enable | - * | 189 | UART3_RS485_EN | UART3 RS485 Enable | - * | 190 | TIMER0_TOGGLE1 | TIMER0 Toggle Output 1 | - * | 191 | TIMER0_TOGGLE2 | TIMER0 Toggle Output 2 | - * | 192 | TIMER0_TOGGLE3 | TIMER0 Toggle Output 3 | - * | 193 | TIMER0_TOGGLE4 | TIMER0 Toggle Output 4 | - * | 194 | TIMER1_TOGGLE1 | TIMER1 Toggle Output 1 | - * | 195 | TIMER1_TOGGLE2 | TIMER1 Toggle Output 2 | - * | 196 | TIMER1_TOGGLE3 | TIMER1 Toggle Output 3 | - * | 197 | TIMER1_TOGGLE4 | TIMER1 Toggle Output 4 | - * | 198 | TIMER2_TOGGLE1 | TIMER2 Toggle Output 1 | - * | 199 | TIMER2_TOGGLE2 | TIMER2 Toggle Output 2 | - * | 200 | TIMER2_TOGGLE3 | TIMER2 Toggle Output 3 | - * | 201 | TIMER2_TOGGLE4 | TIMER2 Toggle Output 4 | - * | 202 | CLK_SPI2 | Clock SPI2 | - * | 203 | CLK_I2C2 | Clock I2C2 | - * | 204 | INTERNAL0 | Internal function signal 0 | - * | 205 | INTERNAL1 | Internal function signal 1 | - * | 206 | INTERNAL2 | Internal function signal 2 | - * | 207 | INTERNAL3 | Internal function signal 3 | - * | 208 | INTERNAL4 | Internal function signal 4 | - * | 209 | INTERNAL5 | Internal function signal 5 | - * | 210 | INTERNAL6 | Internal function signal 6 | - * | 211 | INTERNAL7 | Internal function signal 7 | - * | 212 | INTERNAL8 | Internal function signal 8 | - * | 213 | INTERNAL9 | Internal function signal 9 | - * | 214 | INTERNAL10 | Internal function signal 10 | - * | 215 | INTERNAL11 | Internal function signal 11 | - * | 216 | INTERNAL12 | Internal function signal 12 | - * | 217 | INTERNAL13 | Internal function signal 13 | - * | 218 | INTERNAL14 | Internal function signal 14 | - * | 219 | INTERNAL15 | Internal function signal 15 | - * | 220 | INTERNAL16 | Internal function signal 16 | - * | 221 | INTERNAL17 | Internal function signal 17 | - * | 222 | CONSTANT | Constant function | - * | 223 | INTERNAL18 | Internal function signal 18 | - * | 224 | DEBUG0 | Debug function 0 | - * | 225 | DEBUG1 | Debug function 1 | - * | 226 | DEBUG2 | Debug function 2 | - * | 227 | DEBUG3 | Debug function 3 | - * | 228 | DEBUG4 | Debug function 4 | - * | 229 | DEBUG5 | Debug function 5 | - * | 230 | DEBUG6 | Debug function 6 | - * | 231 | DEBUG7 | Debug function 7 | - * | 232 | DEBUG8 | Debug function 8 | - * | 233 | DEBUG9 | Debug function 9 | - * | 234 | DEBUG10 | Debug function 10 | - * | 235 | DEBUG11 | Debug function 11 | - * | 236 | DEBUG12 | Debug function 12 | - * | 237 | DEBUG13 | Debug function 13 | - * | 238 | DEBUG14 | Debug function 14 | - * | 239 | DEBUG15 | Debug function 15 | - * | 240 | DEBUG16 | Debug function 16 | - * | 241 | DEBUG17 | Debug function 17 | - * | 242 | DEBUG18 | Debug function 18 | - * | 243 | DEBUG19 | Debug function 19 | - * | 244 | DEBUG20 | Debug function 20 | - * | 245 | DEBUG21 | Debug function 21 | - * | 246 | DEBUG22 | Debug function 22 | - * | 247 | DEBUG23 | Debug function 23 | - * | 248 | DEBUG24 | Debug function 24 | - * | 249 | DEBUG25 | Debug function 25 | - * | 250 | DEBUG26 | Debug function 26 | - * | 251 | DEBUG27 | Debug function 27 | - * | 252 | DEBUG28 | Debug function 28 | - * | 253 | DEBUG29 | Debug function 29 | - * | 254 | DEBUG30 | Debug function 30 | - * | 255 | DEBUG31 | Debug function 31 | - * - * Any IO of FPIOA have 256 functions, it is a IO-function matrix. - * All IO have default reset function, after reset, re-configure - * IO function is required. - */ - -/* clang-format off */ -typedef enum _fpioa_function -{ - FUNC_JTAG_TCLK = 0, /*!< JTAG Test Clock */ - FUNC_JTAG_TDI = 1, /*!< JTAG Test Data In */ - FUNC_JTAG_TMS = 2, /*!< JTAG Test Mode Select */ - FUNC_JTAG_TDO = 3, /*!< JTAG Test Data Out */ - FUNC_SPI0_D0 = 4, /*!< SPI0 Data 0 */ - FUNC_SPI0_D1 = 5, /*!< SPI0 Data 1 */ - FUNC_SPI0_D2 = 6, /*!< SPI0 Data 2 */ - FUNC_SPI0_D3 = 7, /*!< SPI0 Data 3 */ - FUNC_SPI0_D4 = 8, /*!< SPI0 Data 4 */ - FUNC_SPI0_D5 = 9, /*!< SPI0 Data 5 */ - FUNC_SPI0_D6 = 10, /*!< SPI0 Data 6 */ - FUNC_SPI0_D7 = 11, /*!< SPI0 Data 7 */ - FUNC_SPI0_SS0 = 12, /*!< SPI0 Chip Select 0 */ - FUNC_SPI0_SS1 = 13, /*!< SPI0 Chip Select 1 */ - FUNC_SPI0_SS2 = 14, /*!< SPI0 Chip Select 2 */ - FUNC_SPI0_SS3 = 15, /*!< SPI0 Chip Select 3 */ - FUNC_SPI0_ARB = 16, /*!< SPI0 Arbitration */ - FUNC_SPI0_SCLK = 17, /*!< SPI0 Serial Clock */ - FUNC_UARTHS_RX = 18, /*!< UART High speed Receiver */ - FUNC_UARTHS_TX = 19, /*!< UART High speed Transmitter */ - FUNC_RESV6 = 20, /*!< Reserved function */ - FUNC_RESV7 = 21, /*!< Reserved function */ - FUNC_CLK_SPI1 = 22, /*!< Clock SPI1 */ - FUNC_CLK_I2C1 = 23, /*!< Clock I2C1 */ - FUNC_GPIOHS0 = 24, /*!< GPIO High speed 0 */ - FUNC_GPIOHS1 = 25, /*!< GPIO High speed 1 */ - FUNC_GPIOHS2 = 26, /*!< GPIO High speed 2 */ - FUNC_GPIOHS3 = 27, /*!< GPIO High speed 3 */ - FUNC_GPIOHS4 = 28, /*!< GPIO High speed 4 */ - FUNC_GPIOHS5 = 29, /*!< GPIO High speed 5 */ - FUNC_GPIOHS6 = 30, /*!< GPIO High speed 6 */ - FUNC_GPIOHS7 = 31, /*!< GPIO High speed 7 */ - FUNC_GPIOHS8 = 32, /*!< GPIO High speed 8 */ - FUNC_GPIOHS9 = 33, /*!< GPIO High speed 9 */ - FUNC_GPIOHS10 = 34, /*!< GPIO High speed 10 */ - FUNC_GPIOHS11 = 35, /*!< GPIO High speed 11 */ - FUNC_GPIOHS12 = 36, /*!< GPIO High speed 12 */ - FUNC_GPIOHS13 = 37, /*!< GPIO High speed 13 */ - FUNC_GPIOHS14 = 38, /*!< GPIO High speed 14 */ - FUNC_GPIOHS15 = 39, /*!< GPIO High speed 15 */ - FUNC_GPIOHS16 = 40, /*!< GPIO High speed 16 */ - FUNC_GPIOHS17 = 41, /*!< GPIO High speed 17 */ - FUNC_GPIOHS18 = 42, /*!< GPIO High speed 18 */ - FUNC_GPIOHS19 = 43, /*!< GPIO High speed 19 */ - FUNC_GPIOHS20 = 44, /*!< GPIO High speed 20 */ - FUNC_GPIOHS21 = 45, /*!< GPIO High speed 21 */ - FUNC_GPIOHS22 = 46, /*!< GPIO High speed 22 */ - FUNC_GPIOHS23 = 47, /*!< GPIO High speed 23 */ - FUNC_GPIOHS24 = 48, /*!< GPIO High speed 24 */ - FUNC_GPIOHS25 = 49, /*!< GPIO High speed 25 */ - FUNC_GPIOHS26 = 50, /*!< GPIO High speed 26 */ - FUNC_GPIOHS27 = 51, /*!< GPIO High speed 27 */ - FUNC_GPIOHS28 = 52, /*!< GPIO High speed 28 */ - FUNC_GPIOHS29 = 53, /*!< GPIO High speed 29 */ - FUNC_GPIOHS30 = 54, /*!< GPIO High speed 30 */ - FUNC_GPIOHS31 = 55, /*!< GPIO High speed 31 */ - FUNC_GPIO0 = 56, /*!< GPIO pin 0 */ - FUNC_GPIO1 = 57, /*!< GPIO pin 1 */ - FUNC_GPIO2 = 58, /*!< GPIO pin 2 */ - FUNC_GPIO3 = 59, /*!< GPIO pin 3 */ - FUNC_GPIO4 = 60, /*!< GPIO pin 4 */ - FUNC_GPIO5 = 61, /*!< GPIO pin 5 */ - FUNC_GPIO6 = 62, /*!< GPIO pin 6 */ - FUNC_GPIO7 = 63, /*!< GPIO pin 7 */ - FUNC_UART1_RX = 64, /*!< UART1 Receiver */ - FUNC_UART1_TX = 65, /*!< UART1 Transmitter */ - FUNC_UART2_RX = 66, /*!< UART2 Receiver */ - FUNC_UART2_TX = 67, /*!< UART2 Transmitter */ - FUNC_UART3_RX = 68, /*!< UART3 Receiver */ - FUNC_UART3_TX = 69, /*!< UART3 Transmitter */ - FUNC_SPI1_D0 = 70, /*!< SPI1 Data 0 */ - FUNC_SPI1_D1 = 71, /*!< SPI1 Data 1 */ - FUNC_SPI1_D2 = 72, /*!< SPI1 Data 2 */ - FUNC_SPI1_D3 = 73, /*!< SPI1 Data 3 */ - FUNC_SPI1_D4 = 74, /*!< SPI1 Data 4 */ - FUNC_SPI1_D5 = 75, /*!< SPI1 Data 5 */ - FUNC_SPI1_D6 = 76, /*!< SPI1 Data 6 */ - FUNC_SPI1_D7 = 77, /*!< SPI1 Data 7 */ - FUNC_SPI1_SS0 = 78, /*!< SPI1 Chip Select 0 */ - FUNC_SPI1_SS1 = 79, /*!< SPI1 Chip Select 1 */ - FUNC_SPI1_SS2 = 80, /*!< SPI1 Chip Select 2 */ - FUNC_SPI1_SS3 = 81, /*!< SPI1 Chip Select 3 */ - FUNC_SPI1_ARB = 82, /*!< SPI1 Arbitration */ - FUNC_SPI1_SCLK = 83, /*!< SPI1 Serial Clock */ - FUNC_SPI_SLAVE_D0 = 84, /*!< SPI Slave Data 0 */ - FUNC_SPI_SLAVE_SS = 85, /*!< SPI Slave Select */ - FUNC_SPI_SLAVE_SCLK = 86, /*!< SPI Slave Serial Clock */ - FUNC_I2S0_MCLK = 87, /*!< I2S0 Master Clock */ - FUNC_I2S0_SCLK = 88, /*!< I2S0 Serial Clock(BCLK) */ - FUNC_I2S0_WS = 89, /*!< I2S0 Word Select(LRCLK) */ - FUNC_I2S0_IN_D0 = 90, /*!< I2S0 Serial Data Input 0 */ - FUNC_I2S0_IN_D1 = 91, /*!< I2S0 Serial Data Input 1 */ - FUNC_I2S0_IN_D2 = 92, /*!< I2S0 Serial Data Input 2 */ - FUNC_I2S0_IN_D3 = 93, /*!< I2S0 Serial Data Input 3 */ - FUNC_I2S0_OUT_D0 = 94, /*!< I2S0 Serial Data Output 0 */ - FUNC_I2S0_OUT_D1 = 95, /*!< I2S0 Serial Data Output 1 */ - FUNC_I2S0_OUT_D2 = 96, /*!< I2S0 Serial Data Output 2 */ - FUNC_I2S0_OUT_D3 = 97, /*!< I2S0 Serial Data Output 3 */ - FUNC_I2S1_MCLK = 98, /*!< I2S1 Master Clock */ - FUNC_I2S1_SCLK = 99, /*!< I2S1 Serial Clock(BCLK) */ - FUNC_I2S1_WS = 100, /*!< I2S1 Word Select(LRCLK) */ - FUNC_I2S1_IN_D0 = 101, /*!< I2S1 Serial Data Input 0 */ - FUNC_I2S1_IN_D1 = 102, /*!< I2S1 Serial Data Input 1 */ - FUNC_I2S1_IN_D2 = 103, /*!< I2S1 Serial Data Input 2 */ - FUNC_I2S1_IN_D3 = 104, /*!< I2S1 Serial Data Input 3 */ - FUNC_I2S1_OUT_D0 = 105, /*!< I2S1 Serial Data Output 0 */ - FUNC_I2S1_OUT_D1 = 106, /*!< I2S1 Serial Data Output 1 */ - FUNC_I2S1_OUT_D2 = 107, /*!< I2S1 Serial Data Output 2 */ - FUNC_I2S1_OUT_D3 = 108, /*!< I2S1 Serial Data Output 3 */ - FUNC_I2S2_MCLK = 109, /*!< I2S2 Master Clock */ - FUNC_I2S2_SCLK = 110, /*!< I2S2 Serial Clock(BCLK) */ - FUNC_I2S2_WS = 111, /*!< I2S2 Word Select(LRCLK) */ - FUNC_I2S2_IN_D0 = 112, /*!< I2S2 Serial Data Input 0 */ - FUNC_I2S2_IN_D1 = 113, /*!< I2S2 Serial Data Input 1 */ - FUNC_I2S2_IN_D2 = 114, /*!< I2S2 Serial Data Input 2 */ - FUNC_I2S2_IN_D3 = 115, /*!< I2S2 Serial Data Input 3 */ - FUNC_I2S2_OUT_D0 = 116, /*!< I2S2 Serial Data Output 0 */ - FUNC_I2S2_OUT_D1 = 117, /*!< I2S2 Serial Data Output 1 */ - FUNC_I2S2_OUT_D2 = 118, /*!< I2S2 Serial Data Output 2 */ - FUNC_I2S2_OUT_D3 = 119, /*!< I2S2 Serial Data Output 3 */ - FUNC_RESV0 = 120, /*!< Reserved function */ - FUNC_RESV1 = 121, /*!< Reserved function */ - FUNC_RESV2 = 122, /*!< Reserved function */ - FUNC_RESV3 = 123, /*!< Reserved function */ - FUNC_RESV4 = 124, /*!< Reserved function */ - FUNC_RESV5 = 125, /*!< Reserved function */ - FUNC_I2C0_SCLK = 126, /*!< I2C0 Serial Clock */ - FUNC_I2C0_SDA = 127, /*!< I2C0 Serial Data */ - FUNC_I2C1_SCLK = 128, /*!< I2C1 Serial Clock */ - FUNC_I2C1_SDA = 129, /*!< I2C1 Serial Data */ - FUNC_I2C2_SCLK = 130, /*!< I2C2 Serial Clock */ - FUNC_I2C2_SDA = 131, /*!< I2C2 Serial Data */ - FUNC_CMOS_XCLK = 132, /*!< DVP System Clock */ - FUNC_CMOS_RST = 133, /*!< DVP System Reset */ - FUNC_CMOS_PWDN = 134, /*!< DVP Power Down Mode */ - FUNC_CMOS_VSYNC = 135, /*!< DVP Vertical Sync */ - FUNC_CMOS_HREF = 136, /*!< DVP Horizontal Reference output */ - FUNC_CMOS_PCLK = 137, /*!< Pixel Clock */ - FUNC_CMOS_D0 = 138, /*!< Data Bit 0 */ - FUNC_CMOS_D1 = 139, /*!< Data Bit 1 */ - FUNC_CMOS_D2 = 140, /*!< Data Bit 2 */ - FUNC_CMOS_D3 = 141, /*!< Data Bit 3 */ - FUNC_CMOS_D4 = 142, /*!< Data Bit 4 */ - FUNC_CMOS_D5 = 143, /*!< Data Bit 5 */ - FUNC_CMOS_D6 = 144, /*!< Data Bit 6 */ - FUNC_CMOS_D7 = 145, /*!< Data Bit 7 */ - FUNC_SCCB_SCLK = 146, /*!< SCCB Serial Clock */ - FUNC_SCCB_SDA = 147, /*!< SCCB Serial Data */ - FUNC_UART1_CTS = 148, /*!< UART1 Clear To Send */ - FUNC_UART1_DSR = 149, /*!< UART1 Data Set Ready */ - FUNC_UART1_DCD = 150, /*!< UART1 Data Carrier Detect */ - FUNC_UART1_RI = 151, /*!< UART1 Ring Indicator */ - FUNC_UART1_SIR_IN = 152, /*!< UART1 Serial Infrared Input */ - FUNC_UART1_DTR = 153, /*!< UART1 Data Terminal Ready */ - FUNC_UART1_RTS = 154, /*!< UART1 Request To Send */ - FUNC_UART1_OUT2 = 155, /*!< UART1 User-designated Output 2 */ - FUNC_UART1_OUT1 = 156, /*!< UART1 User-designated Output 1 */ - FUNC_UART1_SIR_OUT = 157, /*!< UART1 Serial Infrared Output */ - FUNC_UART1_BAUD = 158, /*!< UART1 Transmit Clock Output */ - FUNC_UART1_RE = 159, /*!< UART1 Receiver Output Enable */ - FUNC_UART1_DE = 160, /*!< UART1 Driver Output Enable */ - FUNC_UART1_RS485_EN = 161, /*!< UART1 RS485 Enable */ - FUNC_UART2_CTS = 162, /*!< UART2 Clear To Send */ - FUNC_UART2_DSR = 163, /*!< UART2 Data Set Ready */ - FUNC_UART2_DCD = 164, /*!< UART2 Data Carrier Detect */ - FUNC_UART2_RI = 165, /*!< UART2 Ring Indicator */ - FUNC_UART2_SIR_IN = 166, /*!< UART2 Serial Infrared Input */ - FUNC_UART2_DTR = 167, /*!< UART2 Data Terminal Ready */ - FUNC_UART2_RTS = 168, /*!< UART2 Request To Send */ - FUNC_UART2_OUT2 = 169, /*!< UART2 User-designated Output 2 */ - FUNC_UART2_OUT1 = 170, /*!< UART2 User-designated Output 1 */ - FUNC_UART2_SIR_OUT = 171, /*!< UART2 Serial Infrared Output */ - FUNC_UART2_BAUD = 172, /*!< UART2 Transmit Clock Output */ - FUNC_UART2_RE = 173, /*!< UART2 Receiver Output Enable */ - FUNC_UART2_DE = 174, /*!< UART2 Driver Output Enable */ - FUNC_UART2_RS485_EN = 175, /*!< UART2 RS485 Enable */ - FUNC_UART3_CTS = 176, /*!< UART3 Clear To Send */ - FUNC_UART3_DSR = 177, /*!< UART3 Data Set Ready */ - FUNC_UART3_DCD = 178, /*!< UART3 Data Carrier Detect */ - FUNC_UART3_RI = 179, /*!< UART3 Ring Indicator */ - FUNC_UART3_SIR_IN = 180, /*!< UART3 Serial Infrared Input */ - FUNC_UART3_DTR = 181, /*!< UART3 Data Terminal Ready */ - FUNC_UART3_RTS = 182, /*!< UART3 Request To Send */ - FUNC_UART3_OUT2 = 183, /*!< UART3 User-designated Output 2 */ - FUNC_UART3_OUT1 = 184, /*!< UART3 User-designated Output 1 */ - FUNC_UART3_SIR_OUT = 185, /*!< UART3 Serial Infrared Output */ - FUNC_UART3_BAUD = 186, /*!< UART3 Transmit Clock Output */ - FUNC_UART3_RE = 187, /*!< UART3 Receiver Output Enable */ - FUNC_UART3_DE = 188, /*!< UART3 Driver Output Enable */ - FUNC_UART3_RS485_EN = 189, /*!< UART3 RS485 Enable */ - FUNC_TIMER0_TOGGLE1 = 190, /*!< TIMER0 Toggle Output 1 */ - FUNC_TIMER0_TOGGLE2 = 191, /*!< TIMER0 Toggle Output 2 */ - FUNC_TIMER0_TOGGLE3 = 192, /*!< TIMER0 Toggle Output 3 */ - FUNC_TIMER0_TOGGLE4 = 193, /*!< TIMER0 Toggle Output 4 */ - FUNC_TIMER1_TOGGLE1 = 194, /*!< TIMER1 Toggle Output 1 */ - FUNC_TIMER1_TOGGLE2 = 195, /*!< TIMER1 Toggle Output 2 */ - FUNC_TIMER1_TOGGLE3 = 196, /*!< TIMER1 Toggle Output 3 */ - FUNC_TIMER1_TOGGLE4 = 197, /*!< TIMER1 Toggle Output 4 */ - FUNC_TIMER2_TOGGLE1 = 198, /*!< TIMER2 Toggle Output 1 */ - FUNC_TIMER2_TOGGLE2 = 199, /*!< TIMER2 Toggle Output 2 */ - FUNC_TIMER2_TOGGLE3 = 200, /*!< TIMER2 Toggle Output 3 */ - FUNC_TIMER2_TOGGLE4 = 201, /*!< TIMER2 Toggle Output 4 */ - FUNC_CLK_SPI2 = 202, /*!< Clock SPI2 */ - FUNC_CLK_I2C2 = 203, /*!< Clock I2C2 */ - FUNC_INTERNAL0 = 204, /*!< Internal function signal 0 */ - FUNC_INTERNAL1 = 205, /*!< Internal function signal 1 */ - FUNC_INTERNAL2 = 206, /*!< Internal function signal 2 */ - FUNC_INTERNAL3 = 207, /*!< Internal function signal 3 */ - FUNC_INTERNAL4 = 208, /*!< Internal function signal 4 */ - FUNC_INTERNAL5 = 209, /*!< Internal function signal 5 */ - FUNC_INTERNAL6 = 210, /*!< Internal function signal 6 */ - FUNC_INTERNAL7 = 211, /*!< Internal function signal 7 */ - FUNC_INTERNAL8 = 212, /*!< Internal function signal 8 */ - FUNC_INTERNAL9 = 213, /*!< Internal function signal 9 */ - FUNC_INTERNAL10 = 214, /*!< Internal function signal 10 */ - FUNC_INTERNAL11 = 215, /*!< Internal function signal 11 */ - FUNC_INTERNAL12 = 216, /*!< Internal function signal 12 */ - FUNC_INTERNAL13 = 217, /*!< Internal function signal 13 */ - FUNC_INTERNAL14 = 218, /*!< Internal function signal 14 */ - FUNC_INTERNAL15 = 219, /*!< Internal function signal 15 */ - FUNC_INTERNAL16 = 220, /*!< Internal function signal 16 */ - FUNC_INTERNAL17 = 221, /*!< Internal function signal 17 */ - FUNC_CONSTANT = 222, /*!< Constant function */ - FUNC_INTERNAL18 = 223, /*!< Internal function signal 18 */ - FUNC_DEBUG0 = 224, /*!< Debug function 0 */ - FUNC_DEBUG1 = 225, /*!< Debug function 1 */ - FUNC_DEBUG2 = 226, /*!< Debug function 2 */ - FUNC_DEBUG3 = 227, /*!< Debug function 3 */ - FUNC_DEBUG4 = 228, /*!< Debug function 4 */ - FUNC_DEBUG5 = 229, /*!< Debug function 5 */ - FUNC_DEBUG6 = 230, /*!< Debug function 6 */ - FUNC_DEBUG7 = 231, /*!< Debug function 7 */ - FUNC_DEBUG8 = 232, /*!< Debug function 8 */ - FUNC_DEBUG9 = 233, /*!< Debug function 9 */ - FUNC_DEBUG10 = 234, /*!< Debug function 10 */ - FUNC_DEBUG11 = 235, /*!< Debug function 11 */ - FUNC_DEBUG12 = 236, /*!< Debug function 12 */ - FUNC_DEBUG13 = 237, /*!< Debug function 13 */ - FUNC_DEBUG14 = 238, /*!< Debug function 14 */ - FUNC_DEBUG15 = 239, /*!< Debug function 15 */ - FUNC_DEBUG16 = 240, /*!< Debug function 16 */ - FUNC_DEBUG17 = 241, /*!< Debug function 17 */ - FUNC_DEBUG18 = 242, /*!< Debug function 18 */ - FUNC_DEBUG19 = 243, /*!< Debug function 19 */ - FUNC_DEBUG20 = 244, /*!< Debug function 20 */ - FUNC_DEBUG21 = 245, /*!< Debug function 21 */ - FUNC_DEBUG22 = 246, /*!< Debug function 22 */ - FUNC_DEBUG23 = 247, /*!< Debug function 23 */ - FUNC_DEBUG24 = 248, /*!< Debug function 24 */ - FUNC_DEBUG25 = 249, /*!< Debug function 25 */ - FUNC_DEBUG26 = 250, /*!< Debug function 26 */ - FUNC_DEBUG27 = 251, /*!< Debug function 27 */ - FUNC_DEBUG28 = 252, /*!< Debug function 28 */ - FUNC_DEBUG29 = 253, /*!< Debug function 29 */ - FUNC_DEBUG30 = 254, /*!< Debug function 30 */ - FUNC_DEBUG31 = 255, /*!< Debug function 31 */ - FUNC_MAX = 256, /*!< Function numbers */ -} fpioa_function_t; -/* clang-format on */ - -/** - * @brief FPIOA pull settings - * - * @note FPIOA pull settings description - * - * | PU | PD | Description | - * |-----|-----|-----------------------------------| - * | 0 | 0 | No Pull | - * | 0 | 1 | Pull Down | - * | 1 | 0 | Pull Up | - * | 1 | 1 | Undefined | - * - */ - -/* clang-format off */ -typedef enum _fpioa_pull -{ - FPIOA_PULL_NONE, /*!< No Pull */ - FPIOA_PULL_DOWN, /*!< Pull Down */ - FPIOA_PULL_UP, /*!< Pull Up */ - FPIOA_PULL_MAX /*!< Count of pull settings */ -} fpioa_pull_t; -/* clang-format on */ - -/** - * @brief FPIOA driving settings - * - * @note FPIOA driving settings description - * There are 16 kinds of driving settings - * - * @note Low Level Output Current - * - * |DS[3:0] |Min(mA)|Typ(mA)|Max(mA)| - * |--------|-------|-------|-------| - * |0000 |3.2 |5.4 |8.3 | - * |0001 |4.7 |8.0 |12.3 | - * |0010 |6.3 |10.7 |16.4 | - * |0011 |7.8 |13.2 |20.2 | - * |0100 |9.4 |15.9 |24.2 | - * |0101 |10.9 |18.4 |28.1 | - * |0110 |12.4 |20.9 |31.8 | - * |0111 |13.9 |23.4 |35.5 | - * - * @note High Level Output Current - * - * |DS[3:0] |Min(mA)|Typ(mA)|Max(mA)| - * |--------|-------|-------|-------| - * |0000 |5.0 |7.6 |11.2 | - * |0001 |7.5 |11.4 |16.8 | - * |0010 |10.0 |15.2 |22.3 | - * |0011 |12.4 |18.9 |27.8 | - * |0100 |14.9 |22.6 |33.3 | - * |0101 |17.4 |26.3 |38.7 | - * |0110 |19.8 |30.0 |44.1 | - * |0111 |22.3 |33.7 |49.5 | - * - */ - -/* clang-format off */ -typedef enum _fpioa_driving -{ - FPIOA_DRIVING_0, /*!< 0000 */ - FPIOA_DRIVING_1, /*!< 0001 */ - FPIOA_DRIVING_2, /*!< 0010 */ - FPIOA_DRIVING_3, /*!< 0011 */ - FPIOA_DRIVING_4, /*!< 0100 */ - FPIOA_DRIVING_5, /*!< 0101 */ - FPIOA_DRIVING_6, /*!< 0110 */ - FPIOA_DRIVING_7, /*!< 0111 */ - FPIOA_DRIVING_8, /*!< 1000 */ - FPIOA_DRIVING_9, /*!< 1001 */ - FPIOA_DRIVING_10, /*!< 1010 */ - FPIOA_DRIVING_11, /*!< 1011 */ - FPIOA_DRIVING_12, /*!< 1100 */ - FPIOA_DRIVING_13, /*!< 1101 */ - FPIOA_DRIVING_14, /*!< 1110 */ - FPIOA_DRIVING_15, /*!< 1111 */ - FPIOA_DRIVING_MAX /*!< Count of driving settings */ -} fpioa_driving_t; -/* clang-format on */ - -/** - * @brief FPIOA IO - * - * FPIOA IO is the specific pin of the chip package. Every IO - * has a 32bit width register that can independently implement - * schmitt trigger, invert input, invert output, strong pull - * up, driving selector, static input and static output. And more, - * it can implement any pin of any peripheral devices. - * - * @note FPIOA IO's register bits Layout - * - * | Bits | Name |Description | - * |-----------|----------|---------------------------------------------------| - * | 31 | PAD_DI | Read current IO's data input. | - * | 30:24 | NA | Reserved bits. | - * | 23 | ST | Schmitt trigger. | - * | 22 | DI_INV | Invert Data input. | - * | 21 | IE_INV | Invert the input enable signal. | - * | 20 | IE_EN | Input enable. It can disable or enable IO input. | - * | 19 | SL | Slew rate control enable. | - * | 18 | SPU | Strong pull up. | - * | 17 | PD | Pull select: 0 for pull down, 1 for pull up. | - * | 16 | PU | Pull enable. | - * | 15 | DO_INV | Invert the result of data output select (DO_SEL). | - * | 14 | DO_SEL | Data output select: 0 for DO, 1 for OE. | - * | 13 | OE_INV | Invert the output enable signal. | - * | 12 | OE_EN | Output enable.It can disable or enable IO output. | - * | 11:8 | DS | Driving selector. | - * | 7:0 | CH_SEL | Channel select from 256 input. | - * - */ -typedef struct _fpioa_io_config -{ - uint32_t ch_sel : 8; - /*!< Channel select from 256 input. */ - uint32_t ds : 4; - /*!< Driving selector. */ - uint32_t oe_en : 1; - /*!< Static output enable, will AND with OE_INV. */ - uint32_t oe_inv : 1; - /*!< Invert output enable. */ - uint32_t do_sel : 1; - /*!< Data output select: 0 for DO, 1 for OE. */ - uint32_t do_inv : 1; - /*!< Invert the result of data output select (DO_SEL). */ - uint32_t pu : 1; - /*!< Pull up enable. 0 for nothing, 1 for pull up. */ - uint32_t pd : 1; - /*!< Pull down enable. 0 for nothing, 1 for pull down. */ - uint32_t resv0 : 1; - /*!< Reserved bits. */ - uint32_t sl : 1; - /*!< Slew rate control enable. */ - uint32_t ie_en : 1; - /*!< Static input enable, will AND with IE_INV. */ - uint32_t ie_inv : 1; - /*!< Invert input enable. */ - uint32_t di_inv : 1; - /*!< Invert Data input. */ - uint32_t st : 1; - /*!< Schmitt trigger. */ - uint32_t resv1 : 7; - /*!< Reserved bits. */ - uint32_t pad_di : 1; - /*!< Read current IO's data input. */ -} __attribute__((packed, aligned(4))) fpioa_io_config_t; - -/** - * @brief FPIOA tie setting - * - * FPIOA Object have 48 IO pin object and 256 bit input tie bits. - * All SPI arbitration signal will tie high by default. - * - * @note FPIOA function tie bits RAM Layout - * - * | Address | Name |Description | - * |-----------|------------------|----------------------------------| - * | 0x000 | TIE_EN[31:0] | Input tie enable bits [31:0] | - * | 0x004 | TIE_EN[63:32] | Input tie enable bits [63:32] | - * | 0x008 | TIE_EN[95:64] | Input tie enable bits [95:64] | - * | 0x00C | TIE_EN[127:96] | Input tie enable bits [127:96] | - * | 0x010 | TIE_EN[159:128] | Input tie enable bits [159:128] | - * | 0x014 | TIE_EN[191:160] | Input tie enable bits [191:160] | - * | 0x018 | TIE_EN[223:192] | Input tie enable bits [223:192] | - * | 0x01C | TIE_EN[255:224] | Input tie enable bits [255:224] | - * | 0x020 | TIE_VAL[31:0] | Input tie value bits [31:0] | - * | 0x024 | TIE_VAL[63:32] | Input tie value bits [63:32] | - * | 0x028 | TIE_VAL[95:64] | Input tie value bits [95:64] | - * | 0x02C | TIE_VAL[127:96] | Input tie value bits [127:96] | - * | 0x030 | TIE_VAL[159:128] | Input tie value bits [159:128] | - * | 0x034 | TIE_VAL[191:160] | Input tie value bits [191:160] | - * | 0x038 | TIE_VAL[223:192] | Input tie value bits [223:192] | - * | 0x03C | TIE_VAL[255:224] | Input tie value bits [255:224] | - * - * @note Function which input tie high by default - * - * | Name |Description | - * |---------------|---------------------------------------| - * | SPI0_ARB | Arbitration function of SPI master 0 | - * | SPI1_ARB | Arbitration function of SPI master 1 | - * - * Tie high means the SPI Arbitration input is 1 - * - */ -typedef struct _fpioa_tie -{ - uint32_t en[FUNC_MAX / 32]; - /*!< FPIOA GPIO multiplexer tie enable array */ - uint32_t val[FUNC_MAX / 32]; - /*!< FPIOA GPIO multiplexer tie value array */ -} __attribute__((packed, aligned(4))) fpioa_tie_t; - -/** - * @brief FPIOA Object - * - * FPIOA Object have 48 IO pin object and 256 bit input tie bits. - * All SPI arbitration signal will tie high by default. - * - * @note FPIOA IO Pin RAM Layout - * - * | Address | Name |Description | - * |-----------|----------|--------------------------------| - * | 0x000 | PAD0 | FPIOA GPIO multiplexer io 0 | - * | 0x004 | PAD1 | FPIOA GPIO multiplexer io 1 | - * | 0x008 | PAD2 | FPIOA GPIO multiplexer io 2 | - * | 0x00C | PAD3 | FPIOA GPIO multiplexer io 3 | - * | 0x010 | PAD4 | FPIOA GPIO multiplexer io 4 | - * | 0x014 | PAD5 | FPIOA GPIO multiplexer io 5 | - * | 0x018 | PAD6 | FPIOA GPIO multiplexer io 6 | - * | 0x01C | PAD7 | FPIOA GPIO multiplexer io 7 | - * | 0x020 | PAD8 | FPIOA GPIO multiplexer io 8 | - * | 0x024 | PAD9 | FPIOA GPIO multiplexer io 9 | - * | 0x028 | PAD10 | FPIOA GPIO multiplexer io 10 | - * | 0x02C | PAD11 | FPIOA GPIO multiplexer io 11 | - * | 0x030 | PAD12 | FPIOA GPIO multiplexer io 12 | - * | 0x034 | PAD13 | FPIOA GPIO multiplexer io 13 | - * | 0x038 | PAD14 | FPIOA GPIO multiplexer io 14 | - * | 0x03C | PAD15 | FPIOA GPIO multiplexer io 15 | - * | 0x040 | PAD16 | FPIOA GPIO multiplexer io 16 | - * | 0x044 | PAD17 | FPIOA GPIO multiplexer io 17 | - * | 0x048 | PAD18 | FPIOA GPIO multiplexer io 18 | - * | 0x04C | PAD19 | FPIOA GPIO multiplexer io 19 | - * | 0x050 | PAD20 | FPIOA GPIO multiplexer io 20 | - * | 0x054 | PAD21 | FPIOA GPIO multiplexer io 21 | - * | 0x058 | PAD22 | FPIOA GPIO multiplexer io 22 | - * | 0x05C | PAD23 | FPIOA GPIO multiplexer io 23 | - * | 0x060 | PAD24 | FPIOA GPIO multiplexer io 24 | - * | 0x064 | PAD25 | FPIOA GPIO multiplexer io 25 | - * | 0x068 | PAD26 | FPIOA GPIO multiplexer io 26 | - * | 0x06C | PAD27 | FPIOA GPIO multiplexer io 27 | - * | 0x070 | PAD28 | FPIOA GPIO multiplexer io 28 | - * | 0x074 | PAD29 | FPIOA GPIO multiplexer io 29 | - * | 0x078 | PAD30 | FPIOA GPIO multiplexer io 30 | - * | 0x07C | PAD31 | FPIOA GPIO multiplexer io 31 | - * | 0x080 | PAD32 | FPIOA GPIO multiplexer io 32 | - * | 0x084 | PAD33 | FPIOA GPIO multiplexer io 33 | - * | 0x088 | PAD34 | FPIOA GPIO multiplexer io 34 | - * | 0x08C | PAD35 | FPIOA GPIO multiplexer io 35 | - * | 0x090 | PAD36 | FPIOA GPIO multiplexer io 36 | - * | 0x094 | PAD37 | FPIOA GPIO multiplexer io 37 | - * | 0x098 | PAD38 | FPIOA GPIO multiplexer io 38 | - * | 0x09C | PAD39 | FPIOA GPIO multiplexer io 39 | - * | 0x0A0 | PAD40 | FPIOA GPIO multiplexer io 40 | - * | 0x0A4 | PAD41 | FPIOA GPIO multiplexer io 41 | - * | 0x0A8 | PAD42 | FPIOA GPIO multiplexer io 42 | - * | 0x0AC | PAD43 | FPIOA GPIO multiplexer io 43 | - * | 0x0B0 | PAD44 | FPIOA GPIO multiplexer io 44 | - * | 0x0B4 | PAD45 | FPIOA GPIO multiplexer io 45 | - * | 0x0B8 | PAD46 | FPIOA GPIO multiplexer io 46 | - * | 0x0BC | PAD47 | FPIOA GPIO multiplexer io 47 | - * - */ -typedef struct _fpioa -{ - fpioa_io_config_t io[FPIOA_NUM_IO]; - /*!< FPIOA GPIO multiplexer io array */ - fpioa_tie_t tie; - /*!< FPIOA GPIO multiplexer tie */ -} __attribute__((packed, aligned(4))) fpioa_t; - -/** - * @brief FPIOA object instanse - */ -extern volatile fpioa_t *const fpioa; - -/** - * @brief Initialize FPIOA user custom default settings - * - * @note This function will set all FPIOA pad registers to user-defined - * values from kconfig - * - * @return result - * - 0 Success - * - Other Fail - */ -int fpioa_init(void); - -/** - * @brief Get IO configuration - * - * @param[in] number The IO number - * @param cfg Pointer to struct of IO configuration for specified IO - * - * @return result - * - 0 Success - * - Other Fail - */ -int fpioa_get_io(int number, fpioa_io_config_t *cfg); - -/** - * @brief Set IO configuration - * - * @param[in] number The IO number - * @param[in] cfg Pointer to struct of IO configuration for specified IO - * - * @return result - * - 0 Success - * - Other Fail - */ -int fpioa_set_io(int number, fpioa_io_config_t *cfg); - -/** - * @brief Set IO configuration with function number - * - * @note The default IO configuration which bind to function number will - * set automatically - * - * @param[in] number The IO number - * @param[in] function The function enum number - * - * @return result - * - 0 Success - * - Other Fail - */ -int fpioa_set_function_raw(int number, fpioa_function_t function); - -/** - * @brief Set only IO configuration with function number - * - * @note The default IO configuration which bind to function number will - * set automatically - * - * @param[in] number The IO number - * @param[in] function The function enum number - * - * @return result - * - 0 Success - * - Other Fail - */ -int fpioa_set_function(int number, fpioa_function_t function); - -/** - * @brief Set tie enable to function - * - * @param[in] function The function enum number - * @param[in] enable Tie enable to set, 1 is enable, 0 is disable - * - * @return result - * - 0 Success - * - Other Fail - */ -int fpioa_set_tie_enable(fpioa_function_t function, int enable); - -/** - * @brief Set tie value to function - * - * @param[in] function The function enum number - * @param[in] value Tie value to set, 1 is HIGH, 0 is LOW - * - * @return result - * - 0 Success - * - Other Fail - */ -int fpioa_set_tie_value(fpioa_function_t function, int value); - -/** - * @brief Set IO pull function - * - * @param[in] number The IO number - * @param[in] pull The pull enum number - * - * @return result - * - 0 Success - * - Other Fail - */ -int fpioa_set_io_pull(int number, fpioa_pull_t pull); - -/** - * @brief Get IO pull function - * - * @param[in] number The IO number - * - * @return result - * - -1 Fail - * - Other The pull enum number - */ -int fpioa_get_io_pull(int number); - -/** - * @brief Set IO driving - * - * @param[in] number The IO number - * @param[in] driving The driving enum number - * - * @return result - * - 0 Success - * - Other Fail - */ -int fpioa_set_io_driving(int number, fpioa_driving_t driving); - -/** - * @brief Get IO driving - * - * @param[in] number The IO number - * - * @return result - * - -1 Fail - * - Other The driving enum number - */ -int fpioa_get_io_driving(int number); - -/** - * @brief Get IO by function - * - * @param[in] function The function enum number - * - * @return result - * - -1 Fail - * - Other The IO number - */ -int fpioa_get_io_by_function(fpioa_function_t function); - -int fpioa_set_sl(int number, uint8_t sl_value); -int fpioa_set_st(int number, uint8_t st_value); - -#ifdef __cplusplus -} -#endif - -#endif /* _DRIVER_FPIOA_H */ - diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/gpio.h b/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/gpio.h deleted file mode 100644 index 9d96e17..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/gpio.h +++ /dev/null @@ -1,168 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef _DRIVER_GPIO_H -#define _DRIVER_GPIO_H - -#include "platform.h" -#include -#include -#include "gpio_common.h" -#ifdef __cplusplus -extern "C" { -#endif - -/** - * @brief Structure for accessing GPIO registers by individual bit - */ -typedef struct _gpio_bits -{ - uint32_t b0 : 1; - uint32_t b1 : 1; - uint32_t b2 : 1; - uint32_t b3 : 1; - uint32_t b4 : 1; - uint32_t b5 : 1; - uint32_t b6 : 1; - uint32_t b7 : 1; - uint32_t b8 : 1; - uint32_t b9 : 1; - uint32_t b10 : 1; - uint32_t b11 : 1; - uint32_t b12 : 1; - uint32_t b13 : 1; - uint32_t b14 : 1; - uint32_t b15 : 1; - uint32_t b16 : 1; - uint32_t b17 : 1; - uint32_t b18 : 1; - uint32_t b19 : 1; - uint32_t b20 : 1; - uint32_t b21 : 1; - uint32_t b22 : 1; - uint32_t b23 : 1; - uint32_t b24 : 1; - uint32_t b25 : 1; - uint32_t b26 : 1; - uint32_t b27 : 1; - uint32_t b28 : 1; - uint32_t b29 : 1; - uint32_t b30 : 1; - uint32_t b31 : 1; -} __attribute__((packed, aligned(4))) gpio_bits_t; - -/** - * @brief Structure of templates for accessing GPIO registers - */ -typedef union _gpio_access_tp -{ - /* 32x1 bit mode */ - uint32_t u32[1]; - /* 16x2 bit mode */ - uint16_t u16[2]; - /* 8x4 bit mode */ - uint8_t u8[4]; - /* 1 bit mode */ - gpio_bits_t bits; -} __attribute__((packed, aligned(4))) gpio_access_tp_t; - -/** - * @brief The GPIO address map - */ -typedef struct _gpio -{ - /* Offset 0x00: Data (output) registers */ - gpio_access_tp_t data_output; - /* Offset 0x04: Data direction registers */ - gpio_access_tp_t direction; - /* Offset 0x08: Data source registers */ - gpio_access_tp_t source; - /* Offset 0x10 - 0x2f: Unused registers, 9x4 bytes */ - uint32_t unused_0[9]; - /* Offset 0x30: Interrupt enable/disable registers */ - gpio_access_tp_t interrupt_enable; - /* Offset 0x34: Interrupt mask registers */ - gpio_access_tp_t interrupt_mask; - /* Offset 0x38: Interrupt level registers */ - gpio_access_tp_t interrupt_level; - /* Offset 0x3c: Interrupt polarity registers */ - gpio_access_tp_t interrupt_polarity; - /* Offset 0x40: Interrupt status registers */ - gpio_access_tp_t interrupt_status; - /* Offset 0x44: Raw interrupt status registers */ - gpio_access_tp_t interrupt_status_raw; - /* Offset 0x48: Interrupt debounce registers */ - gpio_access_tp_t interrupt_debounce; - /* Offset 0x4c: Registers for clearing interrupts */ - gpio_access_tp_t interrupt_clear; - /* Offset 0x50: External port (data input) registers */ - gpio_access_tp_t data_input; - /* Offset 0x54 - 0x5f: Unused registers, 3x4 bytes */ - uint32_t unused_1[3]; - /* Offset 0x60: Sync level registers */ - gpio_access_tp_t sync_level; - /* Offset 0x64: ID code */ - gpio_access_tp_t id_code; - /* Offset 0x68: Interrupt both edge type */ - gpio_access_tp_t interrupt_bothedge; - -} __attribute__((packed, aligned(4))) gpio_t; - -/** - * @brief Bus GPIO object instance - */ -extern volatile gpio_t *const gpio; - -/** - * @brief Gpio initialize - * - * @return Result - * - 0 Success - * - Other Fail - */ -int gpio_init(void); - -/** - * @brief Set Gpio drive mode - * - * @param[in] pin Gpio pin - * @param[in] mode Gpio pin drive mode - */ -void gpio_set_drive_mode(uint8_t pin, gpio_drive_mode_t mode); - -/** - * @brief Get Gpio pin value - * - * @param[in] pin Gpio pin - * @return Pin value - * - * - GPIO_PV_Low Gpio pin low - * - GPIO_PV_High Gpio pin high - */ -gpio_pin_value_t gpio_get_pin(uint8_t pin); - -/** - * @brief Set Gpio pin value - * - * @param[in] pin Gpio pin - * @param[in] value Gpio pin value - */ -void gpio_set_pin(uint8_t pin, gpio_pin_value_t value); - -#ifdef __cplusplus -} -#endif - -#endif /* _DRIVER_GPIO_H */ - diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/gpio_common.h b/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/gpio_common.h deleted file mode 100644 index 71fc0c0..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/gpio_common.h +++ /dev/null @@ -1,51 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef _GPIO_COMMON_H -#define _GPIO_COMMON_H - -#ifdef __cplusplus -extern "C" { -#endif - -typedef enum _gpio_drive_mode -{ - GPIO_DM_INPUT, - GPIO_DM_INPUT_PULL_DOWN, - GPIO_DM_INPUT_PULL_UP, - GPIO_DM_OUTPUT, -} gpio_drive_mode_t; - -typedef enum _gpio_pin_edge -{ - GPIO_PE_NONE, - GPIO_PE_FALLING, - GPIO_PE_RISING, - GPIO_PE_BOTH, - GPIO_PE_LOW, - GPIO_PE_HIGH = 8, -} gpio_pin_edge_t; - -typedef enum _gpio_pin_value -{ - GPIO_PV_LOW, - GPIO_PV_HIGH -} gpio_pin_value_t; - -#ifdef __cplusplus -} -#endif - -#endif /* _GPIO_COMMON_H */ - diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/gpiohs.h b/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/gpiohs.h deleted file mode 100644 index bbc7101..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/gpiohs.h +++ /dev/null @@ -1,267 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef _DRIVER_GPIOHS_H -#define _DRIVER_GPIOHS_H - -#include -#include "platform.h" -#include -#include "gpio_common.h" -#include "plic.h" -#ifdef __cplusplus -extern "C" { -#endif - -/* clang-format off */ -/* Register address offsets */ -#define GPIOHS_INPUT_VAL (0x00) -#define GPIOHS_INPUT_EN (0x04) -#define GPIOHS_OUTPUT_EN (0x08) -#define GPIOHS_OUTPUT_VAL (0x0C) -#define GPIOHS_PULLUP_EN (0x10) -#define GPIOHS_DRIVE (0x14) -#define GPIOHS_RISE_IE (0x18) -#define GPIOHS_RISE_IP (0x1C) -#define GPIOHS_FALL_IE (0x20) -#define GPIOHS_FALL_IP (0x24) -#define GPIOHS_HIGH_IE (0x28) -#define GPIOHS_HIGH_IP (0x2C) -#define GPIOHS_LOW_IE (0x30) -#define GPIOHS_LOW_IP (0x34) -#define GPIOHS_IOF_EN (0x38) -#define GPIOHS_IOF_SEL (0x3C) -#define GPIOHS_OUTPUT_XOR (0x40) -/* clang-format on */ - -/** - * @brief GPIO bits raw object - */ -typedef struct _gpiohs_raw -{ - /* Address offset 0x00 */ - uint32_t input_val; - /* Address offset 0x04 */ - uint32_t input_en; - /* Address offset 0x08 */ - uint32_t output_en; - /* Address offset 0x0c */ - uint32_t output_val; - /* Address offset 0x10 */ - uint32_t pullup_en; - /* Address offset 0x14 */ - uint32_t drive; - /* Address offset 0x18 */ - uint32_t rise_ie; - /* Address offset 0x1c */ - uint32_t rise_ip; - /* Address offset 0x20 */ - uint32_t fall_ie; - /* Address offset 0x24 */ - uint32_t fall_ip; - /* Address offset 0x28 */ - uint32_t high_ie; - /* Address offset 0x2c */ - uint32_t high_ip; - /* Address offset 0x30 */ - uint32_t low_ie; - /* Address offset 0x34 */ - uint32_t low_ip; - /* Address offset 0x38 */ - uint32_t iof_en; - /* Address offset 0x3c */ - uint32_t iof_sel; - /* Address offset 0x40 */ - uint32_t output_xor; -} __attribute__((packed, aligned(4))) gpiohs_raw_t; - -/** - * @brief GPIO bits object - */ -typedef struct _gpiohs_bits -{ - uint32_t b0 : 1; - uint32_t b1 : 1; - uint32_t b2 : 1; - uint32_t b3 : 1; - uint32_t b4 : 1; - uint32_t b5 : 1; - uint32_t b6 : 1; - uint32_t b7 : 1; - uint32_t b8 : 1; - uint32_t b9 : 1; - uint32_t b10 : 1; - uint32_t b11 : 1; - uint32_t b12 : 1; - uint32_t b13 : 1; - uint32_t b14 : 1; - uint32_t b15 : 1; - uint32_t b16 : 1; - uint32_t b17 : 1; - uint32_t b18 : 1; - uint32_t b19 : 1; - uint32_t b20 : 1; - uint32_t b21 : 1; - uint32_t b22 : 1; - uint32_t b23 : 1; - uint32_t b24 : 1; - uint32_t b25 : 1; - uint32_t b26 : 1; - uint32_t b27 : 1; - uint32_t b28 : 1; - uint32_t b29 : 1; - uint32_t b30 : 1; - uint32_t b31 : 1; -} __attribute__((packed, aligned(4))) gpiohs_bits_t; - -/** - * @brief GPIO bits multi access union - */ -typedef union _gpiohs_u32 -{ - /* 32x1 bit mode */ - uint32_t u32[1]; - /* 16x2 bit mode */ - uint16_t u16[2]; - /* 8x4 bit mode */ - uint8_t u8[4]; - /* 1 bit mode */ - gpiohs_bits_t bits; -} __attribute__((packed, aligned(4))) gpiohs_u32_t; - -/** - * @brief GPIO object - * - * The GPIO controller is a peripheral device mapped in the - * internal memory map, discoverable in the Configuration String. - * It is responsible for low-level configuration of the actual - * GPIO pads on the device (direction, pull up-enable, and drive - * value), as well as selecting between various sources of the - * controls for these signals. The GPIO controller allows seperate - * configuration of each of N GPIO bits. - * - * Once the interrupt is pending, it will remain set until a 1 is - * written to the *_ip register at that bit. - */ - -typedef struct _gpiohs -{ - /* Address offset 0x00, Input Values */ - gpiohs_u32_t input_val; - /* Address offset 0x04, Input enable */ - gpiohs_u32_t input_en; - /* Address offset 0x08, Output enable */ - gpiohs_u32_t output_en; - /* Address offset 0x0c, Onput Values */ - gpiohs_u32_t output_val; - /* Address offset 0x10, Internal Pull-Ups enable */ - gpiohs_u32_t pullup_en; - /* Address offset 0x14, Drive Strength */ - gpiohs_u32_t drive; - /* Address offset 0x18, Rise interrupt enable */ - gpiohs_u32_t rise_ie; - /* Address offset 0x1c, Rise interrupt pending */ - gpiohs_u32_t rise_ip; - /* Address offset 0x20, Fall interrupt enable */ - gpiohs_u32_t fall_ie; - /* Address offset 0x24, Fall interrupt pending */ - gpiohs_u32_t fall_ip; - /* Address offset 0x28, High interrupt enable */ - gpiohs_u32_t high_ie; - /* Address offset 0x2c, High interrupt pending */ - gpiohs_u32_t high_ip; - /* Address offset 0x30, Low interrupt enable */ - gpiohs_u32_t low_ie; - /* Address offset 0x34, Low interrupt pending */ - gpiohs_u32_t low_ip; - /* Address offset 0x38, HW I/O Function enable */ - gpiohs_u32_t iof_en; - /* Address offset 0x3c, HW I/O Function select */ - gpiohs_u32_t iof_sel; - /* Address offset 0x40, Output XOR (invert) */ - gpiohs_u32_t output_xor; -} __attribute__((packed, aligned(4))) gpiohs_t; - -/** - * @brief GPIO High-speed object instanse - */ -extern volatile gpiohs_t *const gpiohs; - -/** - * @brief Set Gpiohs drive mode - * - * @param[in] pin Gpiohs pin - * @param[in] mode Gpiohs pin drive mode - */ -void gpiohs_set_drive_mode(uint8_t pin, gpio_drive_mode_t mode); - -/** - * @brief Get Gpiohs pin value - * - * @param[in] pin Gpiohs pin - * @return Pin value - * - * - GPIO_PV_Low Gpiohs pin low - * - GPIO_PV_High Gpiohs pin high - */ -gpio_pin_value_t gpiohs_get_pin(uint8_t pin); - -/** - * @brief Set Gpiohs pin value - * - * @param[in] pin Gpiohs pin - * @param[in] value Gpiohs pin value - */ -void gpiohs_set_pin(uint8_t pin, gpio_pin_value_t value); - -/** - * @brief Set Gpiohs pin edge for interrupt - * - * @param[in] pin Gpiohs pin - * @param[in] edge Gpiohs pin edge type - */ -void gpiohs_set_pin_edge(uint8_t pin, gpio_pin_edge_t edge); - -/** - * @brief Set Gpiohs pin interrupt - * - * @param[in] pin Gpiohs pin - * @param[in] priority Gpiohs pin interrupt priority - * @param[in] func Gpiohs pin interrupt service routine - */ -void gpiohs_set_irq(uint8_t pin, uint32_t priority, void(*func)()); - -/** - * @brief Set Gpiohs pin interrupt - * - * @param[in] pin Gpiohs pin - * @param[in] priority Gpiohs pin interrupt priority - * @param[in] callback Gpiohs pin interrupt service routine - * @param[in] ctx Gpiohs interrupt param - */ -void gpiohs_irq_register(uint8_t pin, uint32_t priority, plic_irq_callback_t callback, void *ctx); - -/** - * @brief Unregister Gpiohs pin interrupt - * - * @param[in] pin Gpiohs pin - */ -void gpiohs_irq_unregister(uint8_t pin); - -#ifdef __cplusplus -} -#endif - -#endif /* _DRIVER_GPIOHS_H */ - diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/i2c.h b/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/i2c.h deleted file mode 100644 index 6b0bb5c..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/i2c.h +++ /dev/null @@ -1,446 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef _DRIVER_I2C_H -#define _DRIVER_I2C_H - -#include -#include -#include "dmac.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#define I2C_MAX_NUM 3 - -/* clang-format off */ -typedef struct _i2c -{ - /* I2C Control Register (0x00) */ - volatile uint32_t con; - /* I2C Target Address Register (0x04) */ - volatile uint32_t tar; - /* I2C Slave Address Register (0x08) */ - volatile uint32_t sar; - /* reserved (0x0c) */ - volatile uint32_t resv1; - /* I2C Data Buffer and Command Register (0x10) */ - volatile uint32_t data_cmd; - /* I2C Standard Speed Clock SCL High Count Register (0x14) */ - volatile uint32_t ss_scl_hcnt; - /* I2C Standard Speed Clock SCL Low Count Register (0x18) */ - volatile uint32_t ss_scl_lcnt; - /* reserverd (0x1c-0x28) */ - volatile uint32_t resv2[4]; - /* I2C Interrupt Status Register (0x2c) */ - volatile uint32_t intr_stat; - /* I2C Interrupt Mask Register (0x30) */ - volatile uint32_t intr_mask; - /* I2C Raw Interrupt Status Register (0x34) */ - volatile uint32_t raw_intr_stat; - /* I2C Receive FIFO Threshold Register (0x38) */ - volatile uint32_t rx_tl; - /* I2C Transmit FIFO Threshold Register (0x3c) */ - volatile uint32_t tx_tl; - /* I2C Clear Combined and Individual Interrupt Register (0x40) */ - volatile uint32_t clr_intr; - /* I2C Clear RX_UNDER Interrupt Register (0x44) */ - volatile uint32_t clr_rx_under; - /* I2C Clear RX_OVER Interrupt Register (0x48) */ - volatile uint32_t clr_rx_over; - /* I2C Clear TX_OVER Interrupt Register (0x4c) */ - volatile uint32_t clr_tx_over; - /* I2C Clear RD_REQ Interrupt Register (0x50) */ - volatile uint32_t clr_rd_req; - /* I2C Clear TX_ABRT Interrupt Register (0x54) */ - volatile uint32_t clr_tx_abrt; - /* I2C Clear RX_DONE Interrupt Register (0x58) */ - volatile uint32_t clr_rx_done; - /* I2C Clear ACTIVITY Interrupt Register (0x5c) */ - volatile uint32_t clr_activity; - /* I2C Clear STOP_DET Interrupt Register (0x60) */ - volatile uint32_t clr_stop_det; - /* I2C Clear START_DET Interrupt Register (0x64) */ - volatile uint32_t clr_start_det; - /* I2C Clear GEN_CALL Interrupt Register (0x68) */ - volatile uint32_t clr_gen_call; - /* I2C Enable Register (0x6c) */ - volatile uint32_t enable; - /* I2C Status Register (0x70) */ - volatile uint32_t status; - /* I2C Transmit FIFO Level Register (0x74) */ - volatile uint32_t txflr; - /* I2C Receive FIFO Level Register (0x78) */ - volatile uint32_t rxflr; - /* I2C SDA Hold Time Length Register (0x7c) */ - volatile uint32_t sda_hold; - /* I2C Transmit Abort Source Register (0x80) */ - volatile uint32_t tx_abrt_source; - /* reserved (0x84) */ - volatile uint32_t resv3; - /* I2C DMA Control Register (0x88) */ - volatile uint32_t dma_cr; - /* I2C DMA Transmit Data Level Register (0x8c) */ - volatile uint32_t dma_tdlr; - /* I2C DMA Receive Data Level Register (0x90) */ - volatile uint32_t dma_rdlr; - /* I2C SDA Setup Register (0x94) */ - volatile uint32_t sda_setup; - /* I2C ACK General Call Register (0x98) */ - volatile uint32_t general_call; - /* I2C Enable Status Register (0x9c) */ - volatile uint32_t enable_status; - /* I2C SS, FS or FM+ spike suppression limit (0xa0) */ - volatile uint32_t fs_spklen; - /* reserved (0xa4-0xf0) */ - volatile uint32_t resv4[20]; - /* I2C Component Parameter Register 1 (0xf4) */ - volatile uint32_t comp_param_1; - /* I2C Component Version Register (0xf8) */ - volatile uint32_t comp_version; - /* I2C Component Type Register (0xfc) */ - volatile uint32_t comp_type; -} __attribute__((packed, aligned(4))) i2c_t; - -/* I2C Control Register*/ -#define I2C_CON_MASTER_MODE 0x00000001U -#define I2C_CON_SPEED_MASK 0x00000006U -#define I2C_CON_SPEED(x) ((x) << 1) -#define I2C_CON_10BITADDR_SLAVE 0x00000008U -#define I2C_CON_RESTART_EN 0x00000020U -#define I2C_CON_SLAVE_DISABLE 0x00000040U -#define I2C_CON_STOP_DET_IFADDRESSED 0x00000080U -#define I2C_CON_TX_EMPTY_CTRL 0x00000100U - -/* I2C Target Address Register*/ -#define I2C_TAR_ADDRESS_MASK 0x000003FFU -#define I2C_TAR_ADDRESS(x) ((x) << 0) -#define I2C_TAR_GC_OR_START 0x00000400U -#define I2C_TAR_SPECIAL 0x00000800U -#define I2C_TAR_10BITADDR_MASTER 0x00001000U - -/* I2C Slave Address Register*/ -#define I2C_SAR_ADDRESS_MASK 0x000003FFU -#define I2C_SAR_ADDRESS(x) ((x) << 0) - -/* I2C Rx/Tx Data Buffer and Command Register*/ -#define I2C_DATA_CMD_CMD 0x00000100U -#define I2C_DATA_CMD_DATA_MASK 0x000000FFU -#define I2C_DATA_CMD_DATA(x) ((x) << 0) - -/* Standard Speed I2C Clock SCL High Count Register*/ -#define I2C_SS_SCL_HCNT_COUNT_MASK 0x0000FFFFU -#define I2C_SS_SCL_HCNT_COUNT(x) ((x) << 0) - -/* Standard Speed I2C Clock SCL Low Count Register*/ -#define I2C_SS_SCL_LCNT_COUNT_MASK 0x0000FFFFU -#define I2C_SS_SCL_LCNT_COUNT(x) ((x) << 0) - -/* I2C Interrupt Status Register*/ -#define I2C_INTR_STAT_RX_UNDER 0x00000001U -#define I2C_INTR_STAT_RX_OVER 0x00000002U -#define I2C_INTR_STAT_RX_FULL 0x00000004U -#define I2C_INTR_STAT_TX_OVER 0x00000008U -#define I2C_INTR_STAT_TX_EMPTY 0x00000010U -#define I2C_INTR_STAT_RD_REQ 0x00000020U -#define I2C_INTR_STAT_TX_ABRT 0x00000040U -#define I2C_INTR_STAT_RX_DONE 0x00000080U -#define I2C_INTR_STAT_ACTIVITY 0x00000100U -#define I2C_INTR_STAT_STOP_DET 0x00000200U -#define I2C_INTR_STAT_START_DET 0x00000400U -#define I2C_INTR_STAT_GEN_CALL 0x00000800U - -/* I2C Interrupt Mask Register*/ -#define I2C_INTR_MASK_RX_UNDER 0x00000001U -#define I2C_INTR_MASK_RX_OVER 0x00000002U -#define I2C_INTR_MASK_RX_FULL 0x00000004U -#define I2C_INTR_MASK_TX_OVER 0x00000008U -#define I2C_INTR_MASK_TX_EMPTY 0x00000010U -#define I2C_INTR_MASK_RD_REQ 0x00000020U -#define I2C_INTR_MASK_TX_ABRT 0x00000040U -#define I2C_INTR_MASK_RX_DONE 0x00000080U -#define I2C_INTR_MASK_ACTIVITY 0x00000100U -#define I2C_INTR_MASK_STOP_DET 0x00000200U -#define I2C_INTR_MASK_START_DET 0x00000400U -#define I2C_INTR_MASK_GEN_CALL 0x00000800U - -/* I2C Raw Interrupt Status Register*/ -#define I2C_RAW_INTR_MASK_RX_UNDER 0x00000001U -#define I2C_RAW_INTR_MASK_RX_OVER 0x00000002U -#define I2C_RAW_INTR_MASK_RX_FULL 0x00000004U -#define I2C_RAW_INTR_MASK_TX_OVER 0x00000008U -#define I2C_RAW_INTR_MASK_TX_EMPTY 0x00000010U -#define I2C_RAW_INTR_MASK_RD_REQ 0x00000020U -#define I2C_RAW_INTR_MASK_TX_ABRT 0x00000040U -#define I2C_RAW_INTR_MASK_RX_DONE 0x00000080U -#define I2C_RAW_INTR_MASK_ACTIVITY 0x00000100U -#define I2C_RAW_INTR_MASK_STOP_DET 0x00000200U -#define I2C_RAW_INTR_MASK_START_DET 0x00000400U -#define I2C_RAW_INTR_MASK_GEN_CALL 0x00000800U - -/* I2C Receive FIFO Threshold Register*/ -#define I2C_RX_TL_VALUE_MASK 0x00000007U -#define I2C_RX_TL_VALUE(x) ((x) << 0) - -/* I2C Transmit FIFO Threshold Register*/ -#define I2C_TX_TL_VALUE_MASK 0x00000007U -#define I2C_TX_TL_VALUE(x) ((x) << 0) - -/* Clear Combined and Individual Interrupt Register*/ -#define I2C_CLR_INTR_CLR 0x00000001U - -/* Clear RX_UNDER Interrupt Register*/ -#define I2C_CLR_RX_UNDER_CLR 0x00000001U - -/* Clear RX_OVER Interrupt Register*/ -#define I2C_CLR_RX_OVER_CLR 0x00000001U - -/* Clear TX_OVER Interrupt Register*/ -#define I2C_CLR_TX_OVER_CLR 0x00000001U - -/* Clear RD_REQ Interrupt Register*/ -#define I2C_CLR_RD_REQ_CLR 0x00000001U - -/* Clear TX_ABRT Interrupt Register*/ -#define I2C_CLR_TX_ABRT_CLR 0x00000001U - -/* Clear RX_DONE Interrupt Register*/ -#define I2C_CLR_RX_DONE_CLR 0x00000001U - -/* Clear ACTIVITY Interrupt Register*/ -#define I2C_CLR_ACTIVITY_CLR 0x00000001U - -/* Clear STOP_DET Interrupt Register*/ -#define I2C_CLR_STOP_DET_CLR 0x00000001U - -/* Clear START_DET Interrupt Register*/ -#define I2C_CLR_START_DET_CLR 0x00000001U - -/* Clear GEN_CALL Interrupt Register*/ -#define I2C_CLR_GEN_CALL_CLR 0x00000001U - -/* I2C Enable Register*/ -#define I2C_ENABLE_ENABLE 0x00000001U -#define I2C_ENABLE_ABORT 0x00000002U -#define I2C_ENABLE_TX_CMD_BLOCK 0x00000004U - -/* I2C Status Register*/ -#define I2C_STATUS_ACTIVITY 0x00000001U -#define I2C_STATUS_TFNF 0x00000002U -#define I2C_STATUS_TFE 0x00000004U -#define I2C_STATUS_RFNE 0x00000008U -#define I2C_STATUS_RFF 0x00000010U -#define I2C_STATUS_MST_ACTIVITY 0x00000020U -#define I2C_STATUS_SLV_ACTIVITY 0x00000040U - -/* I2C Transmit FIFO Level Register*/ -#define I2C_TXFLR_VALUE_MASK 0x00000007U -#define I2C_TXFLR_VALUE(x) ((x) << 0) - -/* I2C Receive FIFO Level Register*/ -#define I2C_RXFLR_VALUE_MASK 0x00000007U -#define I2C_RXFLR_VALUE(x) ((x) << 0) - -/* I2C SDA Hold Time Length Register*/ -#define I2C_SDA_HOLD_TX_MASK 0x0000FFFFU -#define I2C_SDA_HOLD_TX(x) ((x) << 0) -#define I2C_SDA_HOLD_RX_MASK 0x00FF0000U -#define I2C_SDA_HOLD_RX(x) ((x) << 16) - -/* I2C Transmit Abort Source Register*/ -#define I2C_TX_ABRT_SOURCE_7B_ADDR_NOACK 0x00000001U -#define I2C_TX_ABRT_SOURCE_10B_ADDR1_NOACK 0x00000002U -#define I2C_TX_ABRT_SOURCE_10B_ADDR2_NOACK 0x00000004U -#define I2C_TX_ABRT_SOURCE_TXDATA_NOACK 0x00000008U -#define I2C_TX_ABRT_SOURCE_GCALL_NOACK 0x00000010U -#define I2C_TX_ABRT_SOURCE_GCALL_READ 0x00000020U -#define I2C_TX_ABRT_SOURCE_HS_ACKDET 0x00000040U -#define I2C_TX_ABRT_SOURCE_SBYTE_ACKDET 0x00000080U -#define I2C_TX_ABRT_SOURCE_HS_NORSTRT 0x00000100U -#define I2C_TX_ABRT_SOURCE_SBYTE_NORSTRT 0x00000200U -#define I2C_TX_ABRT_SOURCE_10B_RD_NORSTRT 0x00000400U -#define I2C_TX_ABRT_SOURCE_MASTER_DIS 0x00000800U -#define I2C_TX_ABRT_SOURCE_MST_ARBLOST 0x00001000U -#define I2C_TX_ABRT_SOURCE_SLVFLUSH_TXFIFO 0x00002000U -#define I2C_TX_ABRT_SOURCE_SLV_ARBLOST 0x00004000U -#define I2C_TX_ABRT_SOURCE_SLVRD_INTX 0x00008000U -#define I2C_TX_ABRT_SOURCE_USER_ABRT 0x00010000U - -/* DMA Control Register*/ -#define I2C_DMA_CR_RDMAE 0x00000001U -#define I2C_DMA_CR_TDMAE 0x00000002U - -/* DMA Transmit Data Level Register*/ -#define I2C_DMA_TDLR_VALUE_MASK 0x00000007U -#define I2C_DMA_TDLR_VALUE(x) ((x) << 0) - -/* DMA Receive Data Level Register*/ -#define I2C_DMA_RDLR_VALUE_MASK 0x00000007U -#define I2C_DMA_RDLR_VALUE(x) ((x) << 0) - -/* I2C SDA Setup Register*/ -#define I2C_SDA_SETUP_VALUE_MASK 0x000000FFU -#define I2C_SDA_SETUP_VALUE(x) ((x) << 0) - -/* I2C ACK General Call Register*/ -#define I2C_ACK_GENERAL_CALL_ENABLE 0x00000001U - -/* I2C Enable Status Register*/ -#define I2C_ENABLE_STATUS_IC_ENABLE 0x00000001U -#define I2C_ENABLE_STATUS_SLV_DIS_BUSY 0x00000002U -#define I2C_ENABLE_STATUS_SLV_RX_DATA_LOST 0x00000004U - -/* I2C SS, FS or FM+ spike suppression limit*/ -#define I2C_FS_SPKLEN_VALUE_MASK 0x000000FFU -#define I2C_FS_SPKLEN_VALUE(x) ((x) << 0) - -/* Component Parameter Register 1*/ -#define I2C_COMP_PARAM1_APB_DATA_WIDTH 0x00000003U -#define I2C_COMP_PARAM1_MAX_SPEED_MODE 0x0000000CU -#define I2C_COMP_PARAM1_HC_COUNT_VALUES 0x00000010U -#define I2C_COMP_PARAM1_INTR_IO 0x00000020U -#define I2C_COMP_PARAM1_HAS_DMA 0x00000040U -#define I2C_COMP_PARAM1_ENCODED_PARAMS 0x00000080U -#define I2C_COMP_PARAM1_RX_BUFFER_DEPTH 0x0000FF00U -#define I2C_COMP_PARAM1_TX_BUFFER_DEPTH 0x00FF0000U - -/* I2C Component Version Register*/ -#define I2C_COMP_VERSION_VALUE 0xFFFFFFFFU - -/* I2C Component Type Register*/ -#define I2C_COMP_TYPE_VALUE 0xFFFFFFFFU -/* clang-format on */ - -extern volatile i2c_t *const i2c[3]; - -typedef enum _i2c_device_number -{ - I2C_DEVICE_0, - I2C_DEVICE_1, - I2C_DEVICE_2, - I2C_DEVICE_MAX, -} i2c_device_number_t; - -typedef enum _i2c_bus_speed_mode -{ - I2C_BS_STANDARD, - I2C_BS_FAST, - I2C_BS_HIGHSPEED -} i2c_bus_speed_mode_t; - -typedef enum _i2c_event -{ - I2C_EV_START, - I2C_EV_RESTART, - I2C_EV_STOP -} i2c_event_t; - -typedef struct _i2c_slave_handler -{ - void(*on_receive)(uint32_t data); - uint32_t(*on_transmit)(); - void(*on_event)(i2c_event_t event); -} i2c_slave_handler_t; - -/** - * @brief Set i2c params - * - * @param[in] i2c_num i2c number - * @param[in] slave_address i2c slave device address - * @param[in] address_width address width 7bit or 10bit - * @param[in] i2c_clk i2c clk rate - */ -void i2c_init(i2c_device_number_t i2c_num, uint32_t slave_address, uint32_t address_width, - uint32_t i2c_clk); - -/** - * @brief I2c send data - * - * @param[in] i2c_num i2c number - * @param[in] send_buf send data - * @param[in] send_buf_len send data length - * - * @return result - * - 0 Success - * - Other Fail - */ -int i2c_send_data(i2c_device_number_t i2c_num, const uint8_t *send_buf, size_t send_buf_len); - -/** - * @brief Init i2c as slave mode. - * - * @param[in] i2c_num i2c number - * @param[in] slave_address i2c slave device address - * @param[in] address_width address width 7bit or 10bit - * @param[in] handler Handle of i2c slave interrupt function. - */ -void i2c_init_as_slave(i2c_device_number_t i2c_num, uint32_t slave_address, uint32_t address_width, - const i2c_slave_handler_t *handler); - -/** - * @brief I2c send data by dma - * - * @param[in] dma_channel_num dma channel - * @param[in] i2c_num i2c number - * @param[in] send_buf send data - * @param[in] send_buf_len send data length - * - * @return result - * - 0 Success - * - Other Fail - */ -void i2c_send_data_dma(dmac_channel_number_t dma_channel_num, i2c_device_number_t i2c_num, const uint8_t *send_buf, - size_t send_buf_len); - -/** - * @brief I2c receive data - * - * @param[in] i2c_num i2c number - * @param[in] send_buf send data address - * @param[in] send_buf_len length of send buf - * @param[in] receive_buf receive buf address - * @param[in] receive_buf_len length of receive buf - * - * @return result - * - 0 Success - * - Other Fail -*/ -int i2c_recv_data(i2c_device_number_t i2c_num, const uint8_t *send_buf, size_t send_buf_len, uint8_t *receive_buf, - size_t receive_buf_len); - -/** - * @brief I2c receive data by dma - * - * @param[in] dma_send_channel_num send dma channel - * @param[in] dma_receive_channel_num receive dma channel - * @param[in] i2c_num i2c number - * @param[in] send_buf send data address - * @param[in] send_buf_len length of send buf - * @param[in] receive_buf receive buf address - * @param[in] receive_buf_len length of receive buf - * - * @return result - * - 0 Success - * - Other Fail -*/ -void i2c_recv_data_dma(dmac_channel_number_t dma_send_channel_num, dmac_channel_number_t dma_receive_channel_num, - i2c_device_number_t i2c_num, const uint8_t *send_buf, size_t send_buf_len, - uint8_t *receive_buf, size_t receive_buf_len); - -#ifdef __cplusplus -} -#endif - -#endif /* _DRIVER_I2C_H */ diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/i2s.h b/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/i2s.h deleted file mode 100644 index 16eb0c1..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/i2s.h +++ /dev/null @@ -1,753 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef _DRIVER_I2S_H -#define _DRIVER_I2S_H - -#include -#include -#include "platform.h" -#include "io.h" -#include "dmac.h" - -#ifdef __cplusplus -extern "C" { -#endif - - -#define I2S0_IN_D0 90 -#define I2S0_SCLK 88 -#define I2S0_WS 89 - -typedef enum _i2s_device_number -{ - I2S_DEVICE_0 = 0, - I2S_DEVICE_1 = 1, - I2S_DEVICE_2 = 2, - I2S_DEVICE_MAX -} i2s_device_number_t; - -typedef enum _i2s_channel_num -{ - I2S_CHANNEL_0 = 0, - I2S_CHANNEL_1 = 1, - I2S_CHANNEL_2 = 2, - I2S_CHANNEL_3 = 3 -} i2s_channel_num_t; - -typedef enum _i2s_transmit -{ - I2S_TRANSMITTER = 0, - I2S_RECEIVER = 1 -} i2s_transmit_t; - -typedef enum _i2s_work_mode -{ - STANDARD_MODE = 1, - RIGHT_JUSTIFYING_MODE = 2, - LEFT_JUSTIFYING_MODE = 4 -} i2s_work_mode_t; - -typedef enum _sclk_gating_cycles -{ - /* Clock gating is diable */ - NO_CLOCK_GATING = 0x0, - /* Gating after 12 sclk cycles */ - CLOCK_CYCLES_12 = 0x1, - /* Gating after 16 sclk cycles */ - CLOCK_CYCLES_16 = 0x2, - /* Gating after 20 sclk cycles */ - CLOCK_CYCLES_20 = 0x3, - /* Gating after 24 sclk cycles */ - CLOCK_CYCLES_24 = 0x4 -} i2s_sclk_gating_cycles_t; - -typedef enum _word_select_cycles -{ - /* 16 sclk cycles */ - SCLK_CYCLES_16 = 0x0, - /* 24 sclk cycles */ - SCLK_CYCLES_24 = 0x1, - /* 32 sclk cycles */ - SCLK_CYCLES_32 = 0x2 -} i2s_word_select_cycles_t; - -typedef enum _word_length -{ - /* Ignore the word length */ - IGNORE_WORD_LENGTH = 0x0, - /* 12-bit data resolution of the receiver */ - RESOLUTION_12_BIT = 0x1, - /* 16-bit data resolution of the receiver */ - RESOLUTION_16_BIT = 0x2, - /* 20-bit data resolution of the receiver */ - RESOLUTION_20_BIT = 0x3, - /* 24-bit data resolution of the receiver */ - RESOLUTION_24_BIT = 0x4, - /* 32-bit data resolution of the receiver */ - RESOLUTION_32_BIT = 0x5 -} i2s_word_length_t; - -typedef enum _fifo_threshold -{ - /* Interrupt trigger when FIFO level is 1 */ - TRIGGER_LEVEL_1 = 0x0, - /* Interrupt trigger when FIFO level is 2 */ - TRIGGER_LEVEL_2 = 0x1, - /* Interrupt trigger when FIFO level is 3 */ - TRIGGER_LEVEL_3 = 0x2, - /* Interrupt trigger when FIFO level is 4 */ - TRIGGER_LEVEL_4 = 0x3, - /* Interrupt trigger when FIFO level is 5 */ - TRIGGER_LEVEL_5 = 0x4, - /* Interrupt trigger when FIFO level is 6 */ - TRIGGER_LEVEL_6 = 0x5, - /* Interrupt trigger when FIFO level is 7 */ - TRIGGER_LEVEL_7 = 0x6, - /* Interrupt trigger when FIFO level is 8 */ - TRIGGER_LEVEL_8 = 0x7, - /* Interrupt trigger when FIFO level is 9 */ - TRIGGER_LEVEL_9 = 0x8, - /* Interrupt trigger when FIFO level is 10 */ - TRIGGER_LEVEL_10 = 0x9, - /* Interrupt trigger when FIFO level is 11 */ - TRIGGER_LEVEL_11 = 0xa, - /* Interrupt trigger when FIFO level is 12 */ - TRIGGER_LEVEL_12 = 0xb, - /* Interrupt trigger when FIFO level is 13 */ - TRIGGER_LEVEL_13 = 0xc, - /* Interrupt trigger when FIFO level is 14 */ - TRIGGER_LEVEL_14 = 0xd, - /* Interrupt trigger when FIFO level is 15 */ - TRIGGER_LEVEL_15 = 0xe, - /* Interrupt trigger when FIFO level is 16 */ - TRIGGER_LEVEL_16 = 0xf -} i2s_fifo_threshold_t; - - -typedef struct _i2s_ier -{ - /* Bit 0 is ien, 0 for disable i2s and 1 for enable i2s */ - uint32_t ien : 1; - /* Bits [31:1] is reserved */ - uint32_t resv : 31; -} __attribute__((packed, aligned(4))) i2s_ier_t; - -typedef union _ier_u -{ - i2s_ier_t ier; - uint32_t reg_data; -} ier_t; - -typedef struct _i2s_irer -{ - /* Bit 0 is receiver block enable, - * 0 for receiver disable - * 1 for receiver enable - */ - uint32_t rxen : 1; - /* Bits [31:1] is reserved */ - uint32_t resv : 31; -} __attribute__((packed, aligned(4))) i2s_irer_t; - -typedef union _irer_u -{ - i2s_irer_t irer; - uint32_t reg_data; -} irer_t; - -typedef struct _i2s_iter -{ - uint32_t txen : 1; - /* Bit 0 is transmitter block enable, - * 0 for transmitter disable - * 1 for transmitter enable - */ - uint32_t resv : 31; - /* Bits [31:1] is reserved */ -} __attribute__((packed, aligned(4))) i2s_iter_t; - -typedef union _iter_u -{ - i2s_iter_t iter; - uint32_t reg_data; -} iter_t; - -typedef struct _i2s_cer -{ - uint32_t clken : 1; - /* Bit 0 is clock generation enable/disable, - * 0 for clock generation disable, - * 1 for clock generation enable - */ - uint32_t resv : 31; - /* Bits [31:1] is reserved */ -} __attribute__((packed, aligned(4))) i2s_cer_t; - -typedef union _cer_u -{ - i2s_cer_t cer; - uint32_t reg_data; -} cer_t; - -typedef struct _i2s_ccr -{ - /* Bits [2:0] is used to program the gating of sclk, - * 0x0 for clock gating is diable, - * 0x1 for gating after 12 sclk cycles - * 0x2 for gating after 16 sclk cycles - * 0x3 for gating after 20 sclk cycles - * 0x4 for gating after 24 sclk cycles - */ - uint32_t clk_gate : 3; - /* Bits [4:3] used program the number of sclk cycles for which the - * word select line stayd in the left aligned or right aligned mode. - * 0x0 for 16sclk cycles, 0x1 for 24 sclk cycles 0x2 for 32 sclk - * cycles - */ - uint32_t clk_word_size : 2; - /* Bit[5:7] is alignment mode setting. - * 0x1 for standard i2s format - * 0x2 for right aligned format - * 0x4 for left aligned format - */ - uint32_t align_mode : 3; - /* Bit[8] is DMA transmit enable control */ - uint32_t dma_tx_en : 1; - /* Bit[9] is DMA receive enable control */ - uint32_t dma_rx_en : 1; - uint32_t dma_divide_16 : 1; - /* Bit[10] split 32bit data to two 16 bit data and filled in left - * and right channel. Used with dma_tx_en or dma_rx_en - */ - uint32_t sign_expand_en : 1; - uint32_t resv : 20; - /* Bits [31:11] is reseved */ -} __attribute__((packed, aligned(4))) i2s_ccr_t; - -typedef union _ccr_u -{ - i2s_ccr_t ccr; - uint32_t reg_data; -} ccr_t; - -typedef struct _i2s_rxffr -{ - uint32_t rxffr : 1; - /* Bit 0 is receiver FIFO reset, - * 0 for does not flush RX FIFO, 1 for flush RX FIFO - */ - uint32_t resv : 31; - /* Bits [31:1] is reserved */ -} __attribute__((packed, aligned(4))) i2s_rxffr_t; - -typedef union _rxffr_u -{ - i2s_rxffr_t rxffr; - uint32_t reg_data; -} rxffr_t; - -typedef struct _i2s_lrbrthr -{ - uint32_t fifo : 16; - /* Bits [15:0] if used data receive or transmit */ - uint32_t resv : 16; -} i2s_lrbrthr_t; - -typedef union _lrbthr_u -{ - i2s_lrbrthr_t buffer; - uint32_t reg_data; -} lrbthr_t; - -typedef struct _i2s_rthr -{ - /* Bits [15:0] is right stereo data transmitted serially - * from transmit channel input - */ - uint32_t rthrx : 16; - /* Bits [31:16] is reserved */ - uint32_t resv : 16; -} __attribute__((packed, aligned(4))) i2s_rthr_t; - -typedef union _rthr_u -{ - i2s_rthr_t rthr; - uint32_t reg_data; -} rthr_t; - -typedef struct _i2s_rer -{ - /* Bit 0 is receive channel enable/disable, 0 for receive channel disable, - *1 for receive channel enable - */ - uint32_t rxchenx : 1; - /* Bits [31:1] is reseved */ - uint32_t resv : 31; -} __attribute__((packed, aligned(4))) i2s_rer_t; - -typedef union _rer_u -{ - i2s_rer_t rer; - uint32_t reg_data; -} rer_t; - -typedef struct _i2s_ter -{ - /* Bit 0 is transmit channel enable/disable, 0 for transmit channel disable, - * 1 for transmit channel enable - */ - uint32_t txchenx : 1; - /* Bits [31:1] is reseved */ - uint32_t resv : 31; -} __attribute__((packed, aligned(4))) i2s_ter_t; - -typedef union _ter_u -{ - i2s_ter_t ter; - uint32_t reg_data; -} ter_t; - -typedef struct _i2s_rcr_tcr -{ - /* Bits [2:0] is used to program desired data resolution of - * receiver/transmitter, - * 0x0 for ignore the word length - * 0x1 for 12-bit data resolution of the receiver/transmitter, - * 0x2 for 16-bit data resolution of the receiver/transmitter, - * 0x3 for 20-bit data resolution of the receiver/transmitter, - * 0x4 for 24-bit data resolution of the receiver/transmitter, - * 0x5 for 32-bit data resolution of the receiver/transmitter - */ - uint32_t wlen : 3; - /* Bits [31:3] is reseved */ - uint32_t resv : 29; -} __attribute__((packed, aligned(4))) i2s_rcr_tcr_t; - -typedef union _rcr_tcr_u { - i2s_rcr_tcr_t rcr_tcr; - uint32_t reg_data; -} rcr_tcr_t; - -typedef struct _i2s_isr -{ - /* Bit 0 is status of receiver data avaliable interrupt - * 0x0 for RX FIFO trigger level not reached - * 0x1 for RX FIFO trigger level is reached - */ - uint32_t rxda : 1; - /* Bit 1 is status of data overrun interrupt for rx channel - * 0x0 for RX FIFO write valid - * 0x1 for RX FIFO write overrun - */ - uint32_t rxfo : 1; - /* Bits [3:2] is reserved */ - uint32_t resv1 : 2; - /* Bit 4 is status of transmit empty triger interrupt - * 0x0 for TX FIFO triiger level is reach - * 0x1 for TX FIFO trigger level is not reached - */ - uint32_t txfe : 1; - /* BIt 5 is status of data overrun interrupt for the TX channel - * 0x0 for TX FIFO write valid - * 0x1 for TX FIFO write overrun - */ - uint32_t txfo : 1; - /* BIts [31:6] is reserved */ - uint32_t resv2 : 26; -} __attribute__((packed, aligned(4))) i2s_isr_t; - -typedef union _isr_u -{ - i2s_isr_t isr; - uint32_t reg_data; -} isr_t; - -typedef struct _i2s_imr -{ - /* Bit 0 is mask RX FIFO data available interrupt - * 0x0 for unmask RX FIFO data available interrupt - * 0x1 for mask RX FIFO data available interrupt - */ - uint32_t rxdam : 1; - /* Bit 1 is mask RX FIFO overrun interrupt - * 0x0 for unmask RX FIFO overrun interrupt - * 0x1 for mask RX FIFO overrun interrupt - */ - uint32_t rxfom : 1; - /* Bits [3:2] is reserved */ - uint32_t resv1 : 2; - /* Bit 4 is mask TX FIFO empty interrupt, - * 0x0 for unmask TX FIFO empty interrupt, - * 0x1 for mask TX FIFO empty interrupt - */ - uint32_t txfem : 1; - /* BIt 5 is mask TX FIFO overrun interrupt - * 0x0 for mask TX FIFO overrun interrupt - * 0x1 for unmash TX FIFO overrun interrupt - */ - uint32_t txfom : 1; - /* Bits [31:6] is reserved */ - uint32_t resv2 : 26; -} __attribute__((packed, aligned(4))) i2s_imr_t; - -typedef union _imr_u -{ - i2s_imr_t imr; - uint32_t reg_data; -} imr_t; - -typedef struct _i2s_ror -{ - /* Bit 0 is read this bit to clear RX FIFO data overrun interrupt - * 0x0 for RX FIFO write valid, - *0x1 for RX FIFO write overrun - */ - uint32_t rxcho : 1; - /* Bits [31:1] is reserved */ - uint32_t resv : 31; -} __attribute__((packed, aligned(4))) i2s_ror_t; - -typedef union _ror_u -{ - i2s_ror_t ror; - uint32_t reg_data; -} ror_t; - -typedef struct _i2s_tor -{ - /* Bit 0 is read this bit to clear TX FIFO data overrun interrupt - * 0x0 for TX FIFO write valid, - *0x1 for TX FIFO write overrun - */ - uint32_t txcho : 1; - /* Bits [31:1] is reserved */ - uint32_t resv : 31; -} __attribute__((packed, aligned(4))) i2s_tor_t; - -typedef union _tor_u -{ - i2s_tor_t tor; - uint32_t reg_data; -} tor_t; - -typedef struct _i2s_rfcr -{ - /* Bits [3:0] is used program the trigger level in the RX FIFO at - * which the receiver data available interrupt generate, - * 0x0 for interrupt trigger when FIFO level is 1, - * 0x2 for interrupt trigger when FIFO level is 2, - * 0x3 for interrupt trigger when FIFO level is 4, - * 0x4 for interrupt trigger when FIFO level is 5, - * 0x5 for interrupt trigger when FIFO level is 6, - * 0x6 for interrupt trigger when FIFO level is 7, - * 0x7 for interrupt trigger when FIFO level is 8, - * 0x8 for interrupt trigger when FIFO level is 9, - * 0x9 for interrupt trigger when FIFO level is 10, - * 0xa for interrupt trigger when FIFO level is 11, - * 0xb for interrupt trigger when FIFO level is 12, - * 0xc for interrupt trigger when FIFO level is 13, - * 0xd for interrupt trigger when FIFO level is 14, - * 0xe for interrupt trigger when FIFO level is 15, - * 0xf for interrupt trigger when FIFO level is 16 - */ - uint32_t rxchdt : 4; - /* Bits [31:4] is reserved */ - uint32_t rsvd_rfcrx : 28; -} __attribute__((packed, aligned(4))) i2s_rfcr_t; - -typedef union _rfcr_u -{ - i2s_rfcr_t rfcr; - uint32_t reg_data; -} rfcr_t; - -typedef struct _i2s_tfcr -{ - /* Bits [3:0] is used program the trigger level in the TX FIFO at - * which the receiver data available interrupt generate, - * 0x0 for interrupt trigger when FIFO level is 1, - * 0x2 for interrupt trigger when FIFO level is 2, - * 0x3 for interrupt trigger when FIFO level is 4, - * 0x4 for interrupt trigger when FIFO level is 5, - * 0x5 for interrupt trigger when FIFO level is 6, - * 0x6 for interrupt trigger when FIFO level is 7, - * 0x7 for interrupt trigger when FIFO level is 8, - * 0x8 for interrupt trigger when FIFO level is 9, - * 0x9 for interrupt trigger when FIFO level is 10, - * 0xa for interrupt trigger when FIFO level is 11, - * 0xb for interrupt trigger when FIFO level is 12, - * 0xc for interrupt trigger when FIFO level is 13, - * 0xd for interrupt trigger when FIFO level is 14, - * 0xe for interrupt trigger when FIFO level is 15, - * 0xf for interrupt trigger when FIFO level is 16 - */ - uint32_t txchet : 4; - /* Bits [31:4] is reserved */ - uint32_t rsvd_tfcrx : 28; -} __attribute__((packed, aligned(4))) i2s_tfcr_t; - -typedef union _tfcr_u -{ - i2s_tfcr_t tfcr; - uint32_t reg_data; -} tfcr_t; - -typedef struct _i2s_rff -{ - /* Bit 0 is receiver channel FIFO reset, - * 0x0 for does not flush an individual RX FIFO, - * 0x1 for flush an indiviadual RX FIFO - */ - uint32_t rxchfr : 1; - /*< Bits [31:1] is reserved ,write only */ - uint32_t rsvd_rffx : 31; -} __attribute__((packed, aligned(4))) i2s_rff_t; - -typedef union _rff_u -{ - i2s_rff_t rff; - uint32_t reg_data; -} rff_t; - -typedef struct _i2s_tff -{ - /* Bit 0 is transmit channel FIFO reset, - * 0x0 for does not flush an individual TX FIFO, - * 0x1 for flush an indiviadual TX FIFO - */ - uint32_t rtxchfr : 1; - /*< Bits [31:1] is reserved ,write only */ - uint32_t rsvd_rffx : 31; -} __attribute__((packed, aligned(4))) i2s_tff_t; - -typedef union tff_u -{ - i2s_tff_t tff; - uint32_t reg_data; -} tff_t; - -typedef struct _i2s_channel -{ - /* Left Receive or Left Transmit Register (0x20) */ - volatile uint32_t left_rxtx; - /* Right Receive or Right Transmit Register (0x24) */ - volatile uint32_t right_rxtx; - /* Receive Enable Register (0x28) */ - volatile uint32_t rer; - /* Transmit Enable Register (0x2c) */ - volatile uint32_t ter; - /* Receive Configuration Register (0x30) */ - volatile uint32_t rcr; - /* Transmit Configuration Register (0x34) */ - volatile uint32_t tcr; - /* Interrupt Status Register (0x38) */ - volatile uint32_t isr; - /* Interrupt Mask Register (0x3c) */ - volatile uint32_t imr; - /* Receive Overrun Register (0x40) */ - volatile uint32_t ror; - /* Transmit Overrun Register (0x44) */ - volatile uint32_t tor; - /* Receive FIFO Configuration Register (0x48) */ - volatile uint32_t rfcr; - /* Transmit FIFO Configuration Register (0x4c) */ - volatile uint32_t tfcr; - /* Receive FIFO Flush Register (0x50) */ - volatile uint32_t rff; - /* Transmit FIFO Flush Register (0x54) */ - volatile uint32_t tff; - /* reserved (0x58-0x5c) */ - volatile uint32_t reserved1[2]; -} __attribute__((packed, aligned(4))) i2s_channel_t; - -/****is* i2s.api/dw_i2s_portmap - * NAME - * i2s_t - * DESCRIPTION - * This is the structure used for accessing the i2s register - * portmap. - * EXAMPLE - * struct i2s_t *portmap; - * portmap = (struct dw_i2s_portmap *) DW_APB_I2S_BASE; - * SOURCE - */ -typedef struct _i2s -{ - /* I2S Enable Register (0x00) */ - volatile uint32_t ier; - /* I2S Receiver Block Enable Register (0x04) */ - volatile uint32_t irer; - /* I2S Transmitter Block Enable Register (0x08) */ - volatile uint32_t iter; - /* Clock Enable Register (0x0c) */ - volatile uint32_t cer; - /* Clock Configuration Register (0x10) */ - volatile uint32_t ccr; - /* Receiver Block FIFO Reset Register (0x04) */ - volatile uint32_t rxffr; - /* Transmitter Block FIFO Reset Register (0x18) */ - volatile uint32_t txffr; - /* reserved (0x1c) */ - volatile uint32_t reserved1; - volatile i2s_channel_t channel[4]; - /* reserved (0x118-0x1bc) */ - volatile uint32_t reserved2[40]; - /* Receiver Block DMA Register (0x1c0) */ - volatile uint32_t rxdma; - /* Reset Receiver Block DMA Register (0x1c4) */ - volatile uint32_t rrxdma; - /* Transmitter Block DMA Register (0x1c8) */ - volatile uint32_t txdma; - /* Reset Transmitter Block DMA Register (0x1cc) */ - volatile uint32_t rtxdma; - /* reserved (0x1d0-0x1ec) */ - volatile uint32_t reserved3[8]; - /* Component Parameter Register 2 (0x1f0) */ - volatile uint32_t i2s_comp_param_2; - /* Component Parameter Register 1 (0x1f4) */ - volatile uint32_t i2s_comp_param_1; - /* I2S Component Version Register (0x1f8) */ - volatile uint32_t i2s_comp_version_1; - /* I2S Component Type Register (0x1fc) */ - volatile uint32_t i2s_comp_type; -} __attribute__((packed, aligned(4))) i2s_t; - -/** - * @brief I2S object instance - */ -extern volatile i2s_t *const i2s[3]; - -/** -* @brief I2s init -* -* @param[in] device_num The device number -* @param[in] rxtx_mode I2s work mode -* @param[in] channel_mask Channel mask to which channel work -* -*/ -void i2s_init(i2s_device_number_t device_num, i2s_transmit_t rxtx_mode, uint32_t channel_mask); - -/** - * @brief Read pcm data from dma - * - * @param[in] device_num which of device - * @param[in] buf save read data - * @param[in] buf_len the length to read form i2s - * @param[in] channel_num The dma channel number - * - * @return result - * - 0 Success - * - Other Fail - */ -void i2s_receive_data_dma(i2s_device_number_t device_num, uint32_t *buf, size_t buf_len, - dmac_channel_number_t channel_num); - -/** - * @brief Write pcm data to channel_num channel by dma, first wait dmac done - * - * @param[in] device_num which of device - * @param[in] pcm Send data - * @param[in] buf_len Send data length - * @param[in] channel_num dmac channel - * - */ -void i2s_send_data_dma(i2s_device_number_t device_num, const void *buf, size_t buf_len, dmac_channel_number_t channel_num); - -/** - * @brief I2S receive channel configure - * - * @param[in] device_num The device number - * @param[in] channel_num The channel number - * @param[in] word_length The word length - * @param[in] word_select_size The word select size - * @param[in] trigger_level The trigger level - */ -void i2s_rx_channel_config(i2s_device_number_t device_num, - i2s_channel_num_t channel_num, - i2s_word_length_t word_length, - i2s_word_select_cycles_t word_select_size, - i2s_fifo_threshold_t trigger_level, - i2s_work_mode_t word_mode); - -/** - * @brief I2S transmit channel enable - * - * @param[in] device_num The device number - * @param[in] channel_num The channel number - * @param[in] word_length The word length - * @param[in] word_select_size The word select size - * @param[in] trigger_level The trigger level - */ -void i2s_tx_channel_config(i2s_device_number_t device_num, - i2s_channel_num_t channel_num, - i2s_word_length_t word_length, - i2s_word_select_cycles_t word_select_size, - i2s_fifo_threshold_t trigger_level, - i2s_work_mode_t word_mode); - -/** - * @brief Play PCM format audio - * - * @param[in] device_num The device number - * @param[in] channel_num The channel number - * @param[in] buf PCM data - * @param[in] buf_len PCM data length - * @param[in] frame Transmit amount once - * @param[in] bits_per_sample Sample bit length - * @param[in] track_num Track amount - */ -void i2s_play(i2s_device_number_t device_num, dmac_channel_number_t channel_num, - const uint8_t *buf, size_t buf_len, size_t frame, size_t bits_per_sample, uint8_t track_num); - -/** - * @brief Play PCM format audio - * - * @param[in] device_num The device number - * @param[in] sample_rate The Sample rate - * - * - * @return The real sample rate - */ -uint32_t i2s_set_sample_rate(i2s_device_number_t device_num, uint32_t sample_rate); - -/** - * @brief Set dma_divide_16 split 32bit data to two 16 bit data and filled in left -* and right channel. Used with dma_tx_en or dma_rx_en - * - * @param[in] device_num The device number - * @param[in] enable The value of dma_divide_16 0:disable 1:enable - * - * @return result - * - 0 Success - * - Other Fail - */ -int i2s_set_dma_divide_16(i2s_device_number_t device_num, uint32_t enable); - -/** - * @brief Get dma_divide_16. - * - * @param[in] device_num The device number - * - * @return result - * - <0 Fail - * - other value of dma_divide_16 - */ -int i2s_get_dma_divide_16(i2s_device_number_t device_num); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/io.h b/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/io.h deleted file mode 100644 index 190263f..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/io.h +++ /dev/null @@ -1,50 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef _DRIVER_IO_H -#define _DRIVER_IO_H - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -#define readb(addr) (*(volatile uint8_t *)(addr)) -#define readw(addr) (*(volatile uint16_t *)(addr)) -#define readl(addr) (*(volatile uint32_t *)(addr)) -#define readq(addr) (*(volatile uint64_t *)(addr)) - -#define writeb(v, addr) \ - { \ - (*(volatile uint8_t *)(addr)) = (v); \ - } -#define writew(v, addr) \ - { \ - (*(volatile uint16_t *)(addr)) = (v); \ - } -#define writel(v, addr) \ - { \ - (*(volatile uint32_t *)(addr)) = (v); \ - } -#define writeq(v, addr) \ - { \ - (*(volatile uint64_t *)(addr)) = (v); \ - } - -#ifdef __cplusplus -} -#endif - -#endif /* _DRIVER_IO_H */ diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/kpu.h b/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/kpu.h deleted file mode 100644 index 3f67372..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/kpu.h +++ /dev/null @@ -1,848 +0,0 @@ -#ifndef _KPU_H -#define _KPU_H - -#include -#include -#include "dmac.h" - -#define kpu_matmul_begin kpu_conv2d_output - -typedef int (*plic_irq_callback_t)(void *ctx); - -typedef struct -{ - union - { - uint64_t reg; - struct - { - uint64_t int_en:1; - uint64_t ram_flag:1; - uint64_t full_add:1; - uint64_t depth_wise_layer:1; - uint64_t reserved:60; - } data; - } interrupt_enabe; - - union - { - uint64_t reg; - struct - { - uint64_t image_src_addr:15; - uint64_t reserved0:17; - uint64_t image_dst_addr:15; - uint64_t reserved1:17; - } data; - } image_addr; - - union - { - uint64_t reg; - struct - { - uint64_t i_ch_num:10; - uint64_t reserved0:22; - uint64_t o_ch_num:10; - uint64_t reserved1:6; - uint64_t o_ch_num_coef:10; - uint64_t reserved2:6; - } data; - } image_channel_num; - - union - { - uint64_t reg; - struct - { - uint64_t i_row_wid:10; - uint64_t i_col_high:9; - uint64_t reserved0:13; - uint64_t o_row_wid:10; - uint64_t o_col_high:9; - uint64_t reserved1:13; - } data; - } image_size; - - union - { - uint64_t reg; - struct - { - uint64_t kernel_type:3; - uint64_t pad_type:1; - uint64_t pool_type:4; - uint64_t first_stride:1; - uint64_t bypass_conv:1; - uint64_t load_para:1; - uint64_t reserved0:5; - uint64_t dma_burst_size:8; - uint64_t pad_value:8; - uint64_t bwsx_base_addr:32; - } data; - } kernel_pool_type_cfg; - - union - { - uint64_t reg; - struct - { - uint64_t load_coor:1; - uint64_t load_time:6; - uint64_t reserved0:8; - uint64_t para_size:17; - uint64_t para_start_addr:32; - } data; - } kernel_load_cfg; - - union - { - uint64_t reg; - struct - { - uint64_t coef_column_offset:4; - uint64_t coef_row_offset:12; - uint64_t reserved0:48; - } data; - } kernel_offset; - - union - { - uint64_t reg; - struct - { - uint64_t channel_switch_addr:15; - uint64_t reserved:1; - uint64_t row_switch_addr:4; - uint64_t coef_size:8; - uint64_t coef_group:3; - uint64_t load_act:1; - uint64_t active_addr:32; - } data; - } kernel_calc_type_cfg; - - union - { - uint64_t reg; - struct - { - uint64_t wb_channel_switch_addr:15; - uint64_t reserved0:1; - uint64_t wb_row_switch_addr:4; - uint64_t wb_group:3; - uint64_t reserved1:41; - } data; - } write_back_cfg; - - union - { - uint64_t reg; - struct - { - uint64_t shr_w:4; - uint64_t shr_x:4; - uint64_t arg_w:24; - uint64_t arg_x:24; - uint64_t reserved0:8; - } data; - } conv_value; - - union - { - uint64_t reg; - struct - { - uint64_t arg_add:40; - uint64_t reserved:24; - } data; - } conv_value2; - - union - { - uint64_t reg; - struct - { - uint64_t send_data_out:1; - uint64_t reserved:15; - uint64_t channel_byte_num:16; - uint64_t dma_total_byte:32; - } data; - } dma_parameter; -} kpu_layer_argument_t; - -typedef struct -{ - union - { - uint64_t reg; - struct - { - uint64_t shift_number:8; - uint64_t y_mul:16; - uint64_t x_start:36; - } data; - } activate_para[16]; - - union - { - uint64_t reg; - struct - { - uint8_t result_bias[8]; - } data; - } activate_para_bias0; - - union - { - uint64_t reg; - struct - { - uint8_t result_bias[8]; - } data; - } activate_para_bias1; -} kpu_activate_table_t; - -typedef struct -{ - union - { - uint64_t reg; - struct - { - uint64_t norm_mul:24; - uint64_t norm_add:32; - uint64_t norm_shift:4; - } data; - } batchnorm; -} kpu_batchnorm_argument_t; - - -typedef struct -{ - union - { - uint64_t reg; - struct - { - uint16_t weight[9]; - } data; - } weights; -} kpu_weights_kernel_16_3x3_t; - -typedef struct -{ - uint64_t calc_done_int:1; - uint64_t layer_cfg_almost_empty_int:1; - uint64_t layer_cfg_almost_full_int:1; - uint64_t reserved:61; -} kpu_config_interrupt_t; - -typedef struct -{ - uint64_t fifo_full_threshold:4; - uint64_t fifo_empty_threshold:4; - uint64_t reserved:56; -} kpu_config_fifo_threshold_t; - -typedef struct -{ - uint64_t dma_fifo_flush_n:1; - uint64_t gs_fifo_flush_n:1; - uint64_t cfg_fifo_flush_n:1; - uint64_t cmd_fifo_flush_n:1; - uint64_t resp_fifo_flush_n:1; - uint64_t reserved:59; -} kpu_config_fifo_ctrl_t; - -typedef struct -{ - uint64_t eight_bit_mode:1; - uint64_t reserved:63; -} kpu_config_eight_bit_mode_t; - - -typedef struct -{ - volatile uint64_t layer_argument_fifo; - - volatile union - { - uint64_t reg; - kpu_config_interrupt_t data; - } interrupt_status; - - volatile union - { - uint64_t reg; - kpu_config_interrupt_t data; - } interrupt_raw; - - volatile union { - uint64_t reg; - kpu_config_interrupt_t data; - } interrupt_mask; - - volatile union - { - uint64_t reg; - kpu_config_interrupt_t data; - } interrupt_clear; - - volatile union - { - uint64_t reg; - kpu_config_fifo_threshold_t data; - } fifo_threshold; - - volatile uint64_t fifo_data_out; - - volatile union - { - uint64_t reg; - kpu_config_fifo_ctrl_t data; - } fifo_ctrl; - - volatile union - { - uint64_t reg; - kpu_config_eight_bit_mode_t data; - } eight_bit_mode; -} kpu_config_t; - -typedef struct -{ - kpu_layer_argument_t *layers; - kpu_layer_argument_t *remain_layers; - plic_irq_callback_t callback; - void *ctx; - uint64_t *src; - uint64_t *dst; - uint32_t src_length; - uint32_t dst_length; - uint32_t layers_length; - uint32_t remain_layers_length; - dmac_channel_number_t dma_ch; - uint32_t eight_bit_mode; - float output_scale; - float output_bias; - float input_scale; - float input_bias; -} kpu_task_t; - -typedef struct -{ - uint32_t version; - uint32_t flags; - uint32_t arch; - uint32_t layers_length; - uint32_t max_start_address; - uint32_t main_mem_usage; - uint32_t output_count; -} kpu_kmodel_header_t; - -typedef struct -{ - uint32_t version; - uint32_t flags; - uint32_t layers_length; - uint32_t max_start_address; - uint32_t layers_argument_start; -} kpu_model_header_t; - -typedef struct -{ - uint32_t address; - uint32_t size; -} kpu_model_output_t; - -typedef enum -{ - KL_INVALID = 0, - KL_ADD, - KL_QUANTIZED_ADD, - KL_GLOBAL_MAX_POOL2D, - KL_QUANTIZED_GLOBAL_MAX_POOL2D, - KL_GLOBAL_AVERAGE_POOL2D, - KL_QUANTIZED_GLOBAL_AVERAGE_POOL2D, - KL_MAX_POOL2D, - KL_QUANTIZED_MAX_POOL2D, - KL_AVERAGE_POOL2D, - KL_QUANTIZED_AVERAGE_POOL2D, - KL_QUANTIZE, - KL_DEQUANTIZE, - KL_REQUANTIZE, - KL_L2_NORMALIZATION, - KL_SOFTMAX, - KL_CONCAT, - KL_QUANTIZED_CONCAT, - KL_FULLY_CONNECTED, - KL_QUANTIZED_FULLY_CONNECTED, - KL_TENSORFLOW_FLATTEN, - KL_QUANTIZED_TENSORFLOW_FLATTEN, - KL_K210_CONV = 10240, - KL_K210_ADD_PADDING, - KL_K210_REMOVE_PADDING, - KL_K210_UPLOAD -} kpu_model_layer_type_t; - -typedef struct -{ - uint32_t type; - uint32_t body_size; -} kpu_model_layer_header_t; - -typedef enum -{ - KLF_NONE = 0, - KLF_MAIN_MEM_OUT = 1 -} kpu_model_layer_flags_t; - -typedef enum -{ - KLP_SAME = 0, - KLP_VALID = 1 -} kpu_model_padding_t; - -typedef enum -{ - KLA_LINEAR = 0, - KLA_RELU = 1, - KLA_RELU6 = 2 -} kpu_model_activation_t; - -typedef struct -{ - float scale; - float bias; -} kpu_model_quant_param_t; - -typedef struct -{ - uint32_t width; - uint32_t height; - uint32_t channels; -} kpu_model_shape_t; - -typedef struct -{ - uint32_t start; - uint32_t size; -} kpu_model_memory_range_t; - -typedef struct -{ - uint32_t flags; - uint32_t main_mem_out_address; - uint32_t layer_offset; - uint32_t weights_offset; - uint32_t bn_offset; - uint32_t act_offset; -} kpu_model_conv_layer_argument_t; - -typedef struct -{ - uint32_t flags; - uint32_t main_mem_in_a_address; - uint32_t main_mem_in_b_address; - uint32_t main_mem_out_address; - uint32_t count; -} kpu_model_add_layer_argument_t; - -typedef struct -{ - uint32_t flags; - uint32_t main_mem_in_a_address; - uint32_t main_mem_in_b_address; - uint32_t main_mem_out_address; - uint32_t count; - int32_t in_a_offset; - int32_t in_a_mul; - int32_t in_a_shift; - int32_t in_b_offset; - int32_t in_b_mul; - int32_t in_b_shift; - int32_t out_offset; - int32_t out_mul; - int32_t out_shift; -} kpu_model_quant_add_layer_argument_t; - -typedef struct -{ - uint32_t flags; - uint32_t main_mem_in_address; - uint32_t main_mem_out_address; - uint32_t kernel_size; - uint32_t channels; -} kpu_model_gap2d_layer_argument_t; - -typedef struct -{ - uint32_t flags; - uint32_t main_mem_in_address; - uint32_t main_mem_out_address; - kpu_model_shape_t in_shape; - kpu_model_shape_t out_shape; - uint32_t kernel_width; - uint32_t kernel_height; - uint32_t stride_width; - uint32_t stride_height; - uint32_t padding_width; - uint32_t padding_height; -} kpu_model_quant_max_pool2d_layer_argument_t; - -typedef struct -{ - uint32_t flags; - uint32_t main_mem_in_address; - uint32_t main_mem_out_address; - kpu_model_shape_t in_shape; - kpu_model_shape_t out_shape; - uint32_t kernel_width; - uint32_t kernel_height; - uint32_t stride_width; - uint32_t stride_height; - uint32_t padding_width; - uint32_t padding_height; - kpu_model_activation_t act; -} kpu_model_ave_pool2d_layer_argument_t; - -typedef struct -{ - uint32_t flags; - uint32_t main_mem_in_address; - uint32_t mem_out_address; - uint32_t count; - kpu_model_quant_param_t quant_param; -} kpu_model_quantize_layer_argument_t; - -typedef struct -{ - uint32_t flags; - uint32_t main_mem_in_address; - uint32_t main_mem_out_address; - uint32_t count; - kpu_model_quant_param_t quant_param; -} kpu_model_dequantize_layer_argument_t; - -typedef struct -{ - uint32_t flags; - uint32_t main_mem_in_address; - uint32_t main_mem_out_address; - uint32_t count; - uint8_t table[256]; -} kpu_model_requantize_layer_argument_t; - -typedef struct -{ - uint32_t flags; - uint32_t main_mem_in_address; - uint32_t kpu_mem_out_address; - uint32_t channels; -} kpu_model_add_padding_layer_argument_t; - -typedef struct -{ - uint32_t flags; - uint32_t main_mem_in_address; - uint32_t main_mem_out_address; - uint32_t channels; -} kpu_model_remove_padding_layer_argument_t; - -typedef struct -{ - uint32_t flags; - uint32_t main_mem_in_address; - uint32_t kpu_mem_out_address; - uint32_t width; - uint32_t height; - uint32_t channels; -} kpu_model_upload_layer_argument_t; - -typedef struct -{ - uint32_t flags; - uint32_t main_mem_in_address; - uint32_t main_mem_out_address; - uint32_t channels; -} kpu_model_l2_norm_layer_argument_t; - -typedef struct -{ - uint32_t flags; - uint32_t main_mem_in_address; - uint32_t main_mem_out_address; - uint32_t channels; -} kpu_model_softmax_layer_argument_t; - -typedef struct -{ - uint32_t flags; - uint32_t main_mem_out_address; - uint32_t input_count; - kpu_model_memory_range_t inputs_mem[0]; -} kpu_model_concat_layer_argument_t; - -typedef struct -{ - uint32_t flags; - uint32_t main_mem_in_address; - uint32_t main_mem_out_address; - uint32_t in_channels; - uint32_t out_channels; - kpu_model_activation_t act; - float weights[0]; -} kpu_model_fully_connected_layer_argument_t; - -typedef struct -{ - uint32_t flags; - uint32_t main_mem_in_address; - uint32_t main_mem_out_address; - kpu_model_shape_t shape; -} kpu_model_tf_flatten_layer_argument_t; - -typedef void(*kpu_done_callback_t)(void* userdata); - -typedef struct -{ - const uint8_t *model_buffer; - uint8_t *main_buffer; - uint32_t output_count; - const kpu_model_output_t *outputs; - const kpu_model_layer_header_t *layer_headers; - const uint8_t *body_start; - uint32_t layers_length; - volatile uint32_t current_layer; - const uint8_t * volatile current_body; - dmac_channel_number_t dma_ch; - kpu_done_callback_t done_callback; - void *userdata; -} kpu_model_context_t; - -typedef struct -{ - uint32_t weigths_offset; - uint32_t bn_offset; - uint32_t act_offset; - float input_scale; - float input_bias; - float output_scale; - float output_bias; -} kpu_model_layer_metadata_t; - -typedef struct _quantize_param -{ - float scale; - float bias; -} quantize_param_t; - -extern volatile kpu_config_t *const kpu; - -/** - * @brief Modle complier init kpu handler - * - * @param[in] task Kpu handler - * - * @return Kpu handler - */ -extern kpu_task_t *kpu_task_init(kpu_task_t* task); - -/** - * @brief Kpu run for AI - * - * @param[in] task Kpu handler - * @param[in] dma_ch DMA for kpu - * @param[in] src The picture data - * @param[in] dest The result of kpu - * @param[in] callback The callback of kpu - * - * @return result - * - 0 Success - * - Other Fail.Kpu is busy. - */ -int kpu_run(kpu_task_t* task, dmac_channel_number_t dma_ch, const void *src, void* dest, plic_irq_callback_t callback); - -/** - * @brief Get kpu result buf - * - * @param[in] task Kpu handler - * - * @return Kpu result buf - */ -uint8_t *kpu_get_output_buf(kpu_task_t* task); - -/** - * @brief Release kpu output buf - * - * @param[in] output_buf Kpu output buf - * - */ -void kpu_release_output_buf(uint8_t *output_buf); - -/** - * @brief Kpu run for AI - * - * @param[in] task Kpu handler -* -* @return result -* - 0 Success -* - Other Fail.Kpu is busy. -*/ -int kpu_start(kpu_task_t *task); - -/** - * @brief Initialize kpu handler - * - * @param[in] task Kpu handler - * - * @return result - * - 0 Success - * - Other Fail. - */ -int kpu_single_task_init(kpu_task_t *task); - -/** - * @brief Uninitialize kpu handler - * - * @param[in] task Kpu handler - * - * @return result - * - 0 Success - * - Other Fail. - */ -int kpu_single_task_deinit(kpu_task_t *task); - -/** - * @brief Load kmodel and init kpu task - * - * @param[in] task Kpu handler - * @param[in] buffer Kmodel - * @param[in] meta Test data - * - * @return result - * - 0 Success - * - Other Fail. - */ -int kpu_model_load_from_buffer(kpu_task_t *task, uint8_t *buffer, kpu_model_layer_metadata_t **meta); - -/** - * @brief Kpu initialize - * - * @param[in] eight_bit_mode 0:16bit mode 1:8bit mode - * @param[in] callback Callback of kpu - * @param[in] userdata Data of callback - * - */ -void kpu_init(int eight_bit_mode, plic_irq_callback_t callback, void *userdata); - -/** - * @brief Kpu input data by dma - * - * @param[in] layer Kpu task layer - * @param[in] src Image data - * @param[in] dma_ch Dmac channel - * @param[in] callback Dmac complete callback - * @param[in] userdata Data of callback - * - */ -void kpu_input_dma(const kpu_layer_argument_t *layer, const uint8_t *src, dmac_channel_number_t dma_ch, plic_irq_callback_t callback, void *userdata); - -/** - * @brief Kpu input data by cpu - * - * @param[in] layer Kpu task layer - * @param[in] src Image data - * @param[in] width Image width - * @param[in] height Image heigth - * @param[in] channels Color channel, RGB is 3 - * - */ -void kpu_input_with_padding(kpu_layer_argument_t *layer, const uint8_t *src, int width, int height, int channels); - -/** - * @brief Kpu run only one layer - * - * @param[in] layer Kpu task layer - * - */ -void kpu_conv2d(kpu_layer_argument_t *layer); - -/** - * @brief Kpu run only one layer then get the result by dma - * - * @param[in] layer Kpu task layer - * @param[in] dma_ch Dmac channel - * @param[in] dest Result - * @param[in] callback Dmac complete callback - * @param[in] userdata Data of callback - * - */ -void kpu_conv2d_output(kpu_layer_argument_t *layer, dmac_channel_number_t dma_ch, uint8_t *dest, plic_irq_callback_t callback, void *userdata); - -/** - * @brief Kpu pooling - * - * @param[in] src Source - * @param[in] src_param Source param - * @param[in] kernel_size Kernel size, 7*7 is 49 - * @param[in] channels Channels - * @param[in] dest Dest - * @param[in] dest_param Dest param - * - */ -void kpu_global_average_pool(const uint8_t *src, const quantize_param_t *src_param, int kernel_size, int channels, uint8_t *dest, const quantize_param_t *dest_param); - -/** - * @brief Kpu pooling - * - * @param[in] src Source - * @param[in] src_param Source param - * @param[in] kernel_size Kernel size, 7*7 is 49 - * @param[in] channels Channels - * @param[in] dest Dest - * - */ -void kpu_global_average_pool_float(const uint8_t *src, const quantize_param_t *src_param, int kernel_size, int channels, float *dest); - -/** - * @brief Kpu fullly connected by cpu - * - * @param[in] src Source - * @param[in] weights Weight - * @param[in] biases Biases - * @param[in] dest Dest - * @param[in] input_channels Input channels - * @param[in] output_channels Output channels - * - */ -void kpu_fully_connected(const float *src, const float *weights, const float *biases, float *dest, int input_channels, int output_channels); - -/** - * @brief Kpu matrix multiplication - * - * @param[in] src Source - * @param[in] channels Channels - * @param[in] dest Dest - * @param[in] dest_param Dest param - * - */ -void kpu_matmul_end(const uint8_t *src, int channels, float *dest, const quantize_param_t *dest_param); - -/** - * @brief Kpu dequantize - * - * @param[in] src Source - * @param[in] src_param Source param - * @param[in] count Dequantize count - * @param[in] dest Dest - * - */ -void kpu_dequantize(const uint8_t *src, const quantize_param_t *src_param, size_t count, float *dest); - -int kpu_load_kmodel(kpu_model_context_t *ctx, const uint8_t *buffer); -void kpu_model_free(kpu_model_context_t *ctx); -int kpu_get_output(kpu_model_context_t *ctx, uint32_t index, uint8_t **data, size_t *size); -int kpu_run_kmodel(kpu_model_context_t *ctx, const uint8_t *src, dmac_channel_number_t dma_ch, kpu_done_callback_t done_callback, void *userdata); - -#endif diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/plic.h b/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/plic.h deleted file mode 100644 index ec56ee2..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/plic.h +++ /dev/null @@ -1,492 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * 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. - */ -/** - * @file - * @brief The PLIC complies with the RISC-V Privileged Architecture - * specification, and can support a maximum of 1023 external - * interrupt sources targeting up to 15,872 core contexts. - * - * @note PLIC RAM Layout - * - * | Address | Description | - * |-----------|---------------------------------| - * |0x0C000000 | Reserved | - * |0x0C000004 | source 1 priority | - * |0x0C000008 | source 2 priority | - * |... | ... | - * |0x0C000FFC | source 1023 priority | - * | | | - * |0x0C001000 | Start of pending array | - * |... | (read-only) | - * |0x0C00107C | End of pending array | - * |0x0C001080 | Reserved | - * |... | ... | - * |0x0C001FFF | Reserved | - * | | | - * |0x0C002000 | target 0 enables | - * |0x0C002080 | target 1 enables | - * |... | ... | - * |0x0C1F1F80 | target 15871 enables | - * |0x0C1F2000 | Reserved | - * |... | ... | - * |0x0C1FFFFC | Reserved | - * | | | - * |0x0C200000 | target 0 priority threshold | - * |0x0C200004 | target 0 claim/complete | - * |... | ... | - * |0x0C201000 | target 1 priority threshold | - * |0x0C201004 | target 1 claim/complete | - * |... | ... | - * |0x0FFFF000 | target 15871 priority threshold | - * |0x0FFFF004 | target 15871 claim/complete | - * - */ - -#ifndef _DRIVER_PLIC_H -#define _DRIVER_PLIC_H - -#include -#include "encoding.h" -#include "platform.h" - -/* For c++ compatibility */ -#ifdef __cplusplus -extern "C" { -#endif - -/* clang-format off */ -/* IRQ number settings */ -#define PLIC_NUM_SOURCES (IRQN_MAX - 1) -#define PLIC_NUM_PRIORITIES (7) - -/* Real number of cores */ -#define PLIC_NUM_CORES (2) -/* clang-format on */ - -/** - * @brief PLIC External Interrupt Numbers - * - * @note PLIC interrupt sources - * - * | Source | Name | Description | - * |--------|--------------------------|------------------------------------| - * | 0 | IRQN_NO_INTERRUPT | The non-existent interrupt | - * | 1 | IRQN_SPI0_INTERRUPT | SPI0 interrupt | - * | 2 | IRQN_SPI1_INTERRUPT | SPI1 interrupt | - * | 3 | IRQN_SPI_SLAVE_INTERRUPT | SPI_SLAVE interrupt | - * | 4 | IRQN_SPI3_INTERRUPT | SPI3 interrupt | - * | 5 | IRQN_I2S0_INTERRUPT | I2S0 interrupt | - * | 6 | IRQN_I2S1_INTERRUPT | I2S1 interrupt | - * | 7 | IRQN_I2S2_INTERRUPT | I2S2 interrupt | - * | 8 | IRQN_I2C0_INTERRUPT | I2C0 interrupt | - * | 9 | IRQN_I2C1_INTERRUPT | I2C1 interrupt | - * | 10 | IRQN_I2C2_INTERRUPT | I2C2 interrupt | - * | 11 | IRQN_UART1_INTERRUPT | UART1 interrupt | - * | 12 | IRQN_UART2_INTERRUPT | UART2 interrupt | - * | 13 | IRQN_UART3_INTERRUPT | UART3 interrupt | - * | 14 | IRQN_TIMER0A_INTERRUPT | TIMER0 channel 0 or 1 interrupt | - * | 15 | IRQN_TIMER0B_INTERRUPT | TIMER0 channel 2 or 3 interrupt | - * | 16 | IRQN_TIMER1A_INTERRUPT | TIMER1 channel 0 or 1 interrupt | - * | 17 | IRQN_TIMER1B_INTERRUPT | TIMER1 channel 2 or 3 interrupt | - * | 18 | IRQN_TIMER2A_INTERRUPT | TIMER2 channel 0 or 1 interrupt | - * | 19 | IRQN_TIMER2B_INTERRUPT | TIMER2 channel 2 or 3 interrupt | - * | 20 | IRQN_RTC_INTERRUPT | RTC tick and alarm interrupt | - * | 21 | IRQN_WDT0_INTERRUPT | Watching dog timer0 interrupt | - * | 22 | IRQN_WDT1_INTERRUPT | Watching dog timer1 interrupt | - * | 23 | IRQN_APB_GPIO_INTERRUPT | APB GPIO interrupt | - * | 24 | IRQN_DVP_INTERRUPT | Digital video port interrupt | - * | 25 | IRQN_AI_INTERRUPT | AI accelerator interrupt | - * | 26 | IRQN_FFT_INTERRUPT | FFT accelerator interrupt | - * | 27 | IRQN_DMA0_INTERRUPT | DMA channel0 interrupt | - * | 28 | IRQN_DMA1_INTERRUPT | DMA channel1 interrupt | - * | 29 | IRQN_DMA2_INTERRUPT | DMA channel2 interrupt | - * | 30 | IRQN_DMA3_INTERRUPT | DMA channel3 interrupt | - * | 31 | IRQN_DMA4_INTERRUPT | DMA channel4 interrupt | - * | 32 | IRQN_DMA5_INTERRUPT | DMA channel5 interrupt | - * | 33 | IRQN_UARTHS_INTERRUPT | Hi-speed UART0 interrupt | - * | 34 | IRQN_GPIOHS0_INTERRUPT | Hi-speed GPIO0 interrupt | - * | 35 | IRQN_GPIOHS1_INTERRUPT | Hi-speed GPIO1 interrupt | - * | 36 | IRQN_GPIOHS2_INTERRUPT | Hi-speed GPIO2 interrupt | - * | 37 | IRQN_GPIOHS3_INTERRUPT | Hi-speed GPIO3 interrupt | - * | 38 | IRQN_GPIOHS4_INTERRUPT | Hi-speed GPIO4 interrupt | - * | 39 | IRQN_GPIOHS5_INTERRUPT | Hi-speed GPIO5 interrupt | - * | 40 | IRQN_GPIOHS6_INTERRUPT | Hi-speed GPIO6 interrupt | - * | 41 | IRQN_GPIOHS7_INTERRUPT | Hi-speed GPIO7 interrupt | - * | 42 | IRQN_GPIOHS8_INTERRUPT | Hi-speed GPIO8 interrupt | - * | 43 | IRQN_GPIOHS9_INTERRUPT | Hi-speed GPIO9 interrupt | - * | 44 | IRQN_GPIOHS10_INTERRUPT | Hi-speed GPIO10 interrupt | - * | 45 | IRQN_GPIOHS11_INTERRUPT | Hi-speed GPIO11 interrupt | - * | 46 | IRQN_GPIOHS12_INTERRUPT | Hi-speed GPIO12 interrupt | - * | 47 | IRQN_GPIOHS13_INTERRUPT | Hi-speed GPIO13 interrupt | - * | 48 | IRQN_GPIOHS14_INTERRUPT | Hi-speed GPIO14 interrupt | - * | 49 | IRQN_GPIOHS15_INTERRUPT | Hi-speed GPIO15 interrupt | - * | 50 | IRQN_GPIOHS16_INTERRUPT | Hi-speed GPIO16 interrupt | - * | 51 | IRQN_GPIOHS17_INTERRUPT | Hi-speed GPIO17 interrupt | - * | 52 | IRQN_GPIOHS18_INTERRUPT | Hi-speed GPIO18 interrupt | - * | 53 | IRQN_GPIOHS19_INTERRUPT | Hi-speed GPIO19 interrupt | - * | 54 | IRQN_GPIOHS20_INTERRUPT | Hi-speed GPIO20 interrupt | - * | 55 | IRQN_GPIOHS21_INTERRUPT | Hi-speed GPIO21 interrupt | - * | 56 | IRQN_GPIOHS22_INTERRUPT | Hi-speed GPIO22 interrupt | - * | 57 | IRQN_GPIOHS23_INTERRUPT | Hi-speed GPIO23 interrupt | - * | 58 | IRQN_GPIOHS24_INTERRUPT | Hi-speed GPIO24 interrupt | - * | 59 | IRQN_GPIOHS25_INTERRUPT | Hi-speed GPIO25 interrupt | - * | 60 | IRQN_GPIOHS26_INTERRUPT | Hi-speed GPIO26 interrupt | - * | 61 | IRQN_GPIOHS27_INTERRUPT | Hi-speed GPIO27 interrupt | - * | 62 | IRQN_GPIOHS28_INTERRUPT | Hi-speed GPIO28 interrupt | - * | 63 | IRQN_GPIOHS29_INTERRUPT | Hi-speed GPIO29 interrupt | - * | 64 | IRQN_GPIOHS30_INTERRUPT | Hi-speed GPIO30 interrupt | - * | 65 | IRQN_GPIOHS31_INTERRUPT | Hi-speed GPIO31 interrupt | - * - */ -/* clang-format off */ -typedef enum _plic_irq -{ - IRQN_NO_INTERRUPT = 0, /*!< The non-existent interrupt */ - IRQN_SPI0_INTERRUPT = 1, /*!< SPI0 interrupt */ - IRQN_SPI1_INTERRUPT = 2, /*!< SPI1 interrupt */ - IRQN_SPI_SLAVE_INTERRUPT = 3, /*!< SPI_SLAVE interrupt */ - IRQN_SPI3_INTERRUPT = 4, /*!< SPI3 interrupt */ - IRQN_I2S0_INTERRUPT = 5, /*!< I2S0 interrupt */ - IRQN_I2S1_INTERRUPT = 6, /*!< I2S1 interrupt */ - IRQN_I2S2_INTERRUPT = 7, /*!< I2S2 interrupt */ - IRQN_I2C0_INTERRUPT = 8, /*!< I2C0 interrupt */ - IRQN_I2C1_INTERRUPT = 9, /*!< I2C1 interrupt */ - IRQN_I2C2_INTERRUPT = 10, /*!< I2C2 interrupt */ - IRQN_UART1_INTERRUPT = 11, /*!< UART1 interrupt */ - IRQN_UART2_INTERRUPT = 12, /*!< UART2 interrupt */ - IRQN_UART3_INTERRUPT = 13, /*!< UART3 interrupt */ - IRQN_TIMER0A_INTERRUPT = 14, /*!< TIMER0 channel 0 or 1 interrupt */ - IRQN_TIMER0B_INTERRUPT = 15, /*!< TIMER0 channel 2 or 3 interrupt */ - IRQN_TIMER1A_INTERRUPT = 16, /*!< TIMER1 channel 0 or 1 interrupt */ - IRQN_TIMER1B_INTERRUPT = 17, /*!< TIMER1 channel 2 or 3 interrupt */ - IRQN_TIMER2A_INTERRUPT = 18, /*!< TIMER2 channel 0 or 1 interrupt */ - IRQN_TIMER2B_INTERRUPT = 19, /*!< TIMER2 channel 2 or 3 interrupt */ - IRQN_RTC_INTERRUPT = 20, /*!< RTC tick and alarm interrupt */ - IRQN_WDT0_INTERRUPT = 21, /*!< Watching dog timer0 interrupt */ - IRQN_WDT1_INTERRUPT = 22, /*!< Watching dog timer1 interrupt */ - IRQN_APB_GPIO_INTERRUPT = 23, /*!< APB GPIO interrupt */ - IRQN_DVP_INTERRUPT = 24, /*!< Digital video port interrupt */ - IRQN_AI_INTERRUPT = 25, /*!< AI accelerator interrupt */ - IRQN_FFT_INTERRUPT = 26, /*!< FFT accelerator interrupt */ - IRQN_DMA0_INTERRUPT = 27, /*!< DMA channel0 interrupt */ - IRQN_DMA1_INTERRUPT = 28, /*!< DMA channel1 interrupt */ - IRQN_DMA2_INTERRUPT = 29, /*!< DMA channel2 interrupt */ - IRQN_DMA3_INTERRUPT = 30, /*!< DMA channel3 interrupt */ - IRQN_DMA4_INTERRUPT = 31, /*!< DMA channel4 interrupt */ - IRQN_DMA5_INTERRUPT = 32, /*!< DMA channel5 interrupt */ - IRQN_UARTHS_INTERRUPT = 33, /*!< Hi-speed UART0 interrupt */ - IRQN_GPIOHS0_INTERRUPT = 34, /*!< Hi-speed GPIO0 interrupt */ - IRQN_GPIOHS1_INTERRUPT = 35, /*!< Hi-speed GPIO1 interrupt */ - IRQN_GPIOHS2_INTERRUPT = 36, /*!< Hi-speed GPIO2 interrupt */ - IRQN_GPIOHS3_INTERRUPT = 37, /*!< Hi-speed GPIO3 interrupt */ - IRQN_GPIOHS4_INTERRUPT = 38, /*!< Hi-speed GPIO4 interrupt */ - IRQN_GPIOHS5_INTERRUPT = 39, /*!< Hi-speed GPIO5 interrupt */ - IRQN_GPIOHS6_INTERRUPT = 40, /*!< Hi-speed GPIO6 interrupt */ - IRQN_GPIOHS7_INTERRUPT = 41, /*!< Hi-speed GPIO7 interrupt */ - IRQN_GPIOHS8_INTERRUPT = 42, /*!< Hi-speed GPIO8 interrupt */ - IRQN_GPIOHS9_INTERRUPT = 43, /*!< Hi-speed GPIO9 interrupt */ - IRQN_GPIOHS10_INTERRUPT = 44, /*!< Hi-speed GPIO10 interrupt */ - IRQN_GPIOHS11_INTERRUPT = 45, /*!< Hi-speed GPIO11 interrupt */ - IRQN_GPIOHS12_INTERRUPT = 46, /*!< Hi-speed GPIO12 interrupt */ - IRQN_GPIOHS13_INTERRUPT = 47, /*!< Hi-speed GPIO13 interrupt */ - IRQN_GPIOHS14_INTERRUPT = 48, /*!< Hi-speed GPIO14 interrupt */ - IRQN_GPIOHS15_INTERRUPT = 49, /*!< Hi-speed GPIO15 interrupt */ - IRQN_GPIOHS16_INTERRUPT = 50, /*!< Hi-speed GPIO16 interrupt */ - IRQN_GPIOHS17_INTERRUPT = 51, /*!< Hi-speed GPIO17 interrupt */ - IRQN_GPIOHS18_INTERRUPT = 52, /*!< Hi-speed GPIO18 interrupt */ - IRQN_GPIOHS19_INTERRUPT = 53, /*!< Hi-speed GPIO19 interrupt */ - IRQN_GPIOHS20_INTERRUPT = 54, /*!< Hi-speed GPIO20 interrupt */ - IRQN_GPIOHS21_INTERRUPT = 55, /*!< Hi-speed GPIO21 interrupt */ - IRQN_GPIOHS22_INTERRUPT = 56, /*!< Hi-speed GPIO22 interrupt */ - IRQN_GPIOHS23_INTERRUPT = 57, /*!< Hi-speed GPIO23 interrupt */ - IRQN_GPIOHS24_INTERRUPT = 58, /*!< Hi-speed GPIO24 interrupt */ - IRQN_GPIOHS25_INTERRUPT = 59, /*!< Hi-speed GPIO25 interrupt */ - IRQN_GPIOHS26_INTERRUPT = 60, /*!< Hi-speed GPIO26 interrupt */ - IRQN_GPIOHS27_INTERRUPT = 61, /*!< Hi-speed GPIO27 interrupt */ - IRQN_GPIOHS28_INTERRUPT = 62, /*!< Hi-speed GPIO28 interrupt */ - IRQN_GPIOHS29_INTERRUPT = 63, /*!< Hi-speed GPIO29 interrupt */ - IRQN_GPIOHS30_INTERRUPT = 64, /*!< Hi-speed GPIO30 interrupt */ - IRQN_GPIOHS31_INTERRUPT = 65, /*!< Hi-speed GPIO31 interrupt */ - IRQN_MAX -} plic_irq_t; -/* clang-format on */ - -/** - * @brief Interrupt Source Priorities - * - * Each external interrupt source can be assigned a priority by - * writing to its 32-bit memory-mapped priority register. The - * number and value of supported priority levels can vary by - * implementa- tion, with the simplest implementations having all - * devices hardwired at priority 1, in which case, interrupts with - * the lowest ID have the highest effective priority. The priority - * registers are all WARL. - */ -typedef struct _plic_source_priorities -{ - /* 0x0C000000: Reserved, 0x0C000004-0x0C000FFC: 1-1023 priorities */ - uint32_t priority[1024]; -} __attribute__((packed, aligned(4))) plic_source_priorities_t; - -/** - * @brief Interrupt Pending Bits - * - * The current status of the interrupt source pending bits in the - * PLIC core can be read from the pending array, organized as 32 - * words of 32 bits. The pending bit for interrupt ID N is stored - * in bit (N mod 32) of word (N/32). Bit 0 of word 0, which - * represents the non-existent interrupt source 0, is always - * hardwired to zero. The pending bits are read-only. A pending - * bit in the PLIC core can be cleared by setting enable bits to - * only enable the desired interrupt, then performing a claim. A - * pending bit can be set by instructing the associated gateway to - * send an interrupt service request. - */ -typedef struct _plic_pending_bits -{ - /* 0x0C001000-0x0C00107C: Bit 0 is zero, Bits 1-1023 is pending bits */ - uint32_t u32[32]; - /* 0x0C001080-0x0C001FFF: Reserved */ - uint8_t resv[0xF80]; -} __attribute__((packed, aligned(4))) plic_pending_bits_t; - -/** - * @brief Target Interrupt Enables - * - * For each interrupt target, each device’s interrupt can be - * enabled by setting the corresponding bit in that target’s - * enables registers. The enables for a target are accessed as a - * contiguous array of 32×32-bit words, packed the same way as the - * pending bits. For each target, bit 0 of enable word 0 - * represents the non-existent interrupt ID 0 and is hardwired to - * 0. Unused interrupt IDs are also hardwired to zero. The enables - * arrays for different targets are packed contiguously in the - * address space. Only 32-bit word accesses are supported by the - * enables array in RV32 systems. Implementations can trap on - * accesses to enables for non-existent targets, but must allow - * access to the full enables array for any extant target, - * treating all non-existent interrupt source’s enables as - * hardwired to zero. - */ -typedef struct _plic_target_enables -{ - /* 0x0C002000-0x0C1F1F80: target 0-15871 enables */ - struct - { - uint32_t enable[32 * 2];/* Offset 0x00-0x7C: Bit 0 is zero, Bits 1-1023 is bits*/ - } target[15872 / 2]; - - /* 0x0C1F2000-0x0C1FFFFC: Reserved, size 0xE000 */ - uint8_t resv[0xE000]; -} __attribute__((packed, aligned(4))) plic_target_enables_t; - -/** - * @brief PLIC Targets - * - * Target Priority Thresholds The threshold for a pending - * interrupt priority that can interrupt each target can be set in - * the target’s threshold register. The threshold is a WARL field, - * where different implementations can support different numbers - * of thresholds. The simplest implementation has a threshold - * hardwired to zero. - * - * Target Claim Each target can perform a claim by reading the - * claim/complete register, which returns the ID of the highest - * priority pending interrupt or zero if there is no pending - * interrupt for the target. A successful claim will also - * atomically clear the corresponding pending bit on the interrupt - * source. A target can perform a claim at any time, even if the - * EIP is not set. The claim operation is not affected by the - * setting of the target’s priority threshold register. - * - * Target Completion A target signals it has completed running a - * handler by writing the interrupt ID it received from the claim - * to the claim/complete register. This is routed to the - * corresponding interrupt gateway, which can now send another - * interrupt request to the PLIC. The PLIC does not check whether - * the completion ID is the same as the last claim ID for that - * target. If the completion ID does not match an interrupt source - * that is currently enabled for the target, the completion is - * silently ignored. - */ -typedef struct _plic_target -{ - /* 0x0C200000-0x0FFFF004: target 0-15871 */ - struct { - uint32_t priority_threshold;/* Offset 0x000 */ - uint32_t claim_complete; /* Offset 0x004 */ - uint8_t resv[0x1FF8]; /* Offset 0x008, Size 0xFF8 */ - } target[15872 / 2]; -} __attribute__((packed, aligned(4))) plic_target_t; - -/** - * @brief Platform-Level Interrupt Controller - * - * PLIC is Platform-Level Interrupt Controller. The PLIC complies - * with the RISC-V Privileged Architecture specification, and can - * support a maximum of 1023 external interrupt sources targeting - * up to 15,872 core contexts. - */ -typedef struct _plic -{ - /* 0x0C000000-0x0C000FFC */ - plic_source_priorities_t source_priorities; - /* 0x0C001000-0x0C001FFF */ - const plic_pending_bits_t pending_bits; - /* 0x0C002000-0x0C1FFFFC */ - plic_target_enables_t target_enables; - /* 0x0C200000-0x0FFFF004 */ - plic_target_t targets; -} __attribute__((packed, aligned(4))) plic_t; - -extern volatile plic_t *const plic; - -/** - * @brief Definitions for the interrupt callbacks - */ -typedef int (*plic_irq_callback_t)(void *ctx); - -/** - * @brief Definitions for IRQ table instance - */ -typedef struct _plic_instance_t -{ - plic_irq_callback_t callback; - void *ctx; -} plic_instance_t; - -/** - * @brief Initialize PLIC external interrupt - * - * @note This function will set MIP_MEIP. The MSTATUS_MIE must set by user. - * - * @return result - * - 0 Success - * - Other Fail - */ -void plic_init(void); - -/** - * @brief Enable PLIC external interrupt - * - * @param[in] irq_number external interrupt number - * - * @return result - * - 0 Success - * - Other Fail - */ - -int plic_irq_enable(plic_irq_t irq_number); - -/** - * @brief Disable PLIC external interrupt - * - * @param[in] irq_number The external interrupt number - * - * @return result - * - 0 Success - * - Other Fail - */ -int plic_irq_disable(plic_irq_t irq_number); - -/** - * @brief Set IRQ priority - * - * @param[in] irq_number The external interrupt number - * @param[in] priority The priority of external interrupt number - * - * @return result - * - 0 Success - * - Other Fail - */ -int plic_set_priority(plic_irq_t irq_number, uint32_t priority); - -/** - * @brief Get IRQ priority - * - * @param[in] irq_number The external interrupt number - * - * @return The priority of external interrupt number - */ -uint32_t plic_get_priority(plic_irq_t irq_number); - -/** - * @brief Claim an IRQ - * - * @return The current IRQ number - */ -uint32_t plic_irq_claim(void); - -/** - * @brief Complete an IRQ - * - * @param[in] source The source IRQ number to complete - * - * @return result - * - 0 Success - * - Other Fail - */ -int plic_irq_complete(uint32_t source); - -/** - * @brief Register user callback function by IRQ number - * - * @param[in] irq The irq - * @param[in] callback The callback - * @param ctx The context - * - * @return result - * - 0 Success - * - Other Fail - */ -void plic_irq_register(plic_irq_t irq, plic_irq_callback_t callback, void *ctx); - -/** - * @brief Deegister user callback function by IRQ number - * - * @param[in] irq The irq - * - * @return result - * - 0 Success - * - Other Fail - */ -void plic_irq_deregister(plic_irq_t irq); - -/** - * @brief Deegister user callback function by IRQ number - * - * @param[in] irq The irq - * - * @return result - * - 0 Success - * - Other Fail - */ -void plic_irq_unregister(plic_irq_t irq); - -/** - * @brief Get IRQ table, Usage: - * plic_instance_t (*plic_instance)[IRQN_MAX] = plic_get_instance(); - * ... plic_instance[x][y] ...; - * - * @return the point of IRQ table - */ -plic_instance_t (*plic_get_instance(void))[IRQN_MAX]; - -/* For c++ compatibility */ -#ifdef __cplusplus -} -#endif - -#endif /* _DRIVER_PLIC_H */ diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/pwm.h b/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/pwm.h deleted file mode 100644 index 45af61d..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/pwm.h +++ /dev/null @@ -1,74 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef _DRIVER_PWM_H -#define _DRIVER_PWM_H - -#include -#include -#ifdef __cplusplus -extern "C" { -#endif - -typedef enum _pwm_device_number -{ - PWM_DEVICE_0, - PWM_DEVICE_1, - PWM_DEVICE_2, - PWM_DEVICE_MAX, -} pwm_device_number_t; - -typedef enum _pwm_channel_number -{ - PWM_CHANNEL_0, - PWM_CHANNEL_1, - PWM_CHANNEL_2, - PWM_CHANNEL_3, - PWM_CHANNEL_MAX, -} pwm_channel_number_t; - -/** - * @brief Init pwm timer - * - * @param[in] timer timer - */ -void pwm_init(pwm_device_number_t pwm_number); - -/** - * @brief Enable timer - * - * @param[in] timer timer - * @param[in] channel channel - * @param[in] enable Enable or disable - * - */ -void pwm_set_enable(pwm_device_number_t pwm_number, pwm_channel_number_t channel, int enable); - -/** - * @brief Set pwm duty - * - * @param[in] timer timer - * @param[in] channel channel - * @param[in] frequency pwm frequency - * @param[in] duty duty - * - */ -double pwm_set_frequency(pwm_device_number_t pwm_number, pwm_channel_number_t channel, double frequency, double duty); - - -#ifdef __cplusplus -} -#endif - -#endif /* _DRIVER_PWM_H */ diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/rtc.h b/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/rtc.h deleted file mode 100644 index 91fde34..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/rtc.h +++ /dev/null @@ -1,398 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * 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. - */ -/** - * @file - * @brief A real-time clock (RTC) is a computer clock that keeps track of - * the current time. - */ - -#ifndef _DRIVER_RTC_H -#define _DRIVER_RTC_H - -#include -#include -#include "platform.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * @brief RTC timer mode - * - * Timer mode selector - * | Mode | Description | - * |------|------------------------| - * | 0 | Timer pause | - * | 1 | Timer time running | - * | 2 | Timer time setting | - */ -typedef enum _rtc_timer_mode_e -{ - /* 0: Timer pause */ - RTC_TIMER_PAUSE, - /* 1: Timer time running */ - RTC_TIMER_RUNNING, - /* 2: Timer time setting */ - RTC_TIMER_SETTING, - /* Max count of this enum*/ - RTC_TIMER_MAX -} rtc_timer_mode_t; - -/* - * @brief RTC tick interrupt mode - * - * Tick interrupt mode selector - * | Mode | Description | - * |------|------------------------| - * | 0 | Interrupt every second | - * | 1 | Interrupt every minute | - * | 2 | Interrupt every hour | - * | 3 | Interrupt every day | - */ -typedef enum _rtc_tick_interrupt_mode_e -{ - /* 0: Interrupt every second */ - RTC_INT_SECOND, - /* 1: Interrupt every minute */ - RTC_INT_MINUTE, - /* 2: Interrupt every hour */ - RTC_INT_HOUR, - /* 3: Interrupt every day */ - RTC_INT_DAY, - /* Max count of this enum*/ - RTC_INT_MAX -} rtc_tick_interrupt_mode_t; - -/** - * @brief RTC mask structure - * - * RTC mask structure for common use - */ -typedef struct _rtc_mask -{ - /* Reserved */ - uint32_t resv : 1; - /* Second mask */ - uint32_t second : 1; - /* Minute mask */ - uint32_t minute : 1; - /* Hour mask */ - uint32_t hour : 1; - /* Week mask */ - uint32_t week : 1; - /* Day mask */ - uint32_t day : 1; - /* Month mask */ - uint32_t month : 1; - /* Year mask */ - uint32_t year : 1; -} __attribute__((packed, aligned(1))) rtc_mask_t; - -/** - * @brief RTC register - * - * @note RTC register table - * - * | Offset | Name | Description | - * |-----------|----------------|-------------------------------------| - * | 0x00 | date | Timer date information | - * | 0x04 | time | Timer time information | - * | 0x08 | alarm_date | Alarm date information | - * | 0x0c | alarm_time | Alarm time information | - * | 0x10 | initial_count | Timer counter initial value | - * | 0x14 | current_count | Timer counter current value | - * | 0x18 | interrupt_ctrl | RTC interrupt settings | - * | 0x1c | register_ctrl | RTC register settings | - * | 0x20 | reserved0 | Reserved | - * | 0x24 | reserved1 | Reserved | - * | 0x28 | extended | Timer extended information | - * - */ - - -/** - * @brief Timer date information - * - * No. 0 Register (0x00) - */ -typedef struct _rtc_date -{ - /* Week. Range [0,6]. 0 is Sunday. */ - uint32_t week : 3; - /* Reserved */ - uint32_t resv0 : 5; - /* Day. Range [1,31] or [1,30] or [1,29] or [1,28] */ - uint32_t day : 5; - /* Reserved */ - uint32_t resv1 : 3; - /* Month. Range [1,12] */ - uint32_t month : 4; - /* Year. Range [0,99] */ - uint32_t year : 12; -} __attribute__((packed, aligned(4))) rtc_date_t; - -/** - * @brief Timer time information - * - * No. 1 Register (0x04) - */ -typedef struct _rtc_time -{ - /* Reserved */ - uint32_t resv0 : 10; - /* Second. Range [0,59] */ - uint32_t second : 6; - /* Minute. Range [0,59] */ - uint32_t minute : 6; - /* Reserved */ - uint32_t resv1 : 2; - /* Hour. Range [0,23] */ - uint32_t hour : 5; - /* Reserved */ - uint32_t resv2 : 3; -} __attribute__((packed, aligned(4))) rtc_time_t; - -/** - * @brief Alarm date information - * - * No. 2 Register (0x08) - */ -typedef struct _rtc_alarm_date -{ - /* Alarm Week. Range [0,6]. 0 is Sunday. */ - uint32_t week : 3; - /* Reserved */ - uint32_t resv0 : 5; - /* Alarm Day. Range [1,31] or [1,30] or [1,29] or [1,28] */ - uint32_t day : 5; - /* Reserved */ - uint32_t resv1 : 3; - /* Alarm Month. Range [1,12] */ - uint32_t month : 4; - /* Alarm Year. Range [0,99] */ - uint32_t year : 12; -} __attribute__((packed, aligned(4))) rtc_alarm_date_t; - -/** - * @brief Alarm time information - * - * No. 3 Register (0x0c) - */ -typedef struct _rtc_alarm_time -{ - /* Reserved */ - uint32_t resv0 : 10; - /* Alarm Second. Range [0,59] */ - uint32_t second : 6; - /* Alarm Minute. Range [0,59] */ - uint32_t minute : 6; - /* Reserved */ - uint32_t resv1 : 2; - /* Alarm Hour. Range [0,23] */ - uint32_t hour : 5; - /* Reserved */ - uint32_t resv2 : 3; -} __attribute__((packed, aligned(4))) rtc_alarm_time_t; - -/** - * @brief Timer counter initial value - * - * No. 4 Register (0x10) - */ -typedef struct _rtc_initial_count -{ - /* RTC counter initial value */ - uint32_t count : 32; -} __attribute__((packed, aligned(4))) rtc_initial_count_t; - -/** - * @brief Timer counter current value - * - * No. 5 Register (0x14) - */ -typedef struct _rtc_current_count -{ - /* RTC counter current value */ - uint32_t count : 32; -} __attribute__((packed, aligned(4))) rtc_current_count_t; - -/** - * @brief RTC interrupt settings - * - * No. 6 Register (0x18) - */ -typedef struct _rtc_interrupt_ctrl -{ - /* Reserved */ - uint32_t tick_enable : 1; - /* Alarm interrupt enable */ - uint32_t alarm_enable : 1; - /* Tick interrupt enable */ - uint32_t tick_int_mode : 2; - /* Reserved */ - uint32_t resv : 20; - /* Alarm compare mask for interrupt */ - uint32_t alarm_compare_mask : 8; -} __attribute__((packed, aligned(4))) rtc_interrupt_ctrl_t; - -/** - * @brief RTC register settings - * - * No. 7 Register (0x1c) - */ -typedef struct _rtc_register_ctrl -{ - /* RTC timer read enable */ - uint32_t read_enable : 1; - /* RTC timer write enable */ - uint32_t write_enable : 1; - /* Reserved */ - uint32_t resv0 : 11; - /* RTC timer mask */ - uint32_t timer_mask : 8; - /* RTC alarm mask */ - uint32_t alarm_mask : 8; - /* RTC counter initial count value mask */ - uint32_t initial_count_mask : 1; - /* RTC interrupt register mask */ - uint32_t interrupt_register_mask : 1; - /* Reserved */ - uint32_t resv1 : 1; -} __attribute__((packed, aligned(4))) rtc_register_ctrl_t; - -/** - * @brief Reserved - * - * No. 8 Register (0x20) - */ -typedef struct _rtc_reserved0 -{ - /* Reserved */ - uint32_t resv : 32; -} __attribute__((packed, aligned(4))) rtc_reserved0_t; - -/** - * @brief Reserved - * - * No. 9 Register (0x24) - */ -typedef struct _rtc_reserved1 -{ - /* Reserved */ - uint32_t resv : 32; -} __attribute__((packed, aligned(4))) rtc_reserved1_t; - -/** - * @brief Timer extended information - * - * No. 10 Register (0x28) - */ -typedef struct _rtc_extended -{ - /* Century. Range [0,31] */ - uint32_t century : 5; - /* Is leap year. 1 is leap year, 0 is not leap year */ - uint32_t leap_year : 1; - /* Reserved */ - uint32_t resv : 26; -} __attribute__((packed, aligned(4))) rtc_extended_t; - - -/** - * @brief Real-time clock struct - * - * A real-time clock (RTC) is a computer clock that keeps track of - * the current time. - */ -typedef struct _rtc -{ - /* No. 0 (0x00): Timer date information */ - rtc_date_t date; - /* No. 1 (0x04): Timer time information */ - rtc_time_t time; - /* No. 2 (0x08): Alarm date information */ - rtc_alarm_date_t alarm_date; - /* No. 3 (0x0c): Alarm time information */ - rtc_alarm_time_t alarm_time; - /* No. 4 (0x10): Timer counter initial value */ - rtc_initial_count_t initial_count; - /* No. 5 (0x14): Timer counter current value */ - rtc_current_count_t current_count; - /* No. 6 (0x18): RTC interrupt settings */ - rtc_interrupt_ctrl_t interrupt_ctrl; - /* No. 7 (0x1c): RTC register settings */ - rtc_register_ctrl_t register_ctrl; - /* No. 8 (0x20): Reserved */ - rtc_reserved0_t reserved0; - /* No. 9 (0x24): Reserved */ - rtc_reserved1_t reserved1; - /* No. 10 (0x28): Timer extended information */ - rtc_extended_t extended; -} __attribute__((packed, aligned(4))) rtc_t; - - -/** - * @brief Real-time clock object - */ -extern volatile rtc_t *const rtc; -extern volatile uint32_t *const rtc_base; - -/** - * @brief Set date time to RTC - * - * @param[in] year The year - * @param[in] month The month - * @param[in] day The day - * @param[in] hour The hour - * @param[in] minute The minute - * @param[in] second The second - * - * @return result - * - 0 Success - * - Other Fail - */ -int rtc_timer_set(int year, int month, int day, int hour, int minute, int second); - -/** - * @brief Get date time from RTC - * - * @param year The year - * @param month The month - * @param day The day - * @param hour The hour - * @param minute The minute - * @param second The second - * - * @return result - * - 0 Success - * - Other Fail - */ -int rtc_timer_get(int *year, int *month, int *day, int *hour, int *minute, int *second); - -/** - * @brief Initialize RTC - * - * @return Result - * - 0 Success - * - Other Fail - */ -int rtc_init(void); - -#ifdef __cplusplus -} -#endif - -#endif /* _DRIVER_RTC_H */ diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/sha256.h b/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/sha256.h deleted file mode 100644 index b23c165..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/sha256.h +++ /dev/null @@ -1,128 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef _SHA256_H -#define _SHA256_H -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -#define ENABLE_SHA (0x1) -#define SHA256_BIG_ENDIAN (0x1) - -#define SHA256_HASH_LEN 32 -#define SHA256_HASH_WORDS 8 -#define SHA256_BLOCK_LEN 64L - -typedef struct _sha_num_reg -{ - /* The total amount of data calculated by SHA256 is set by this register, and the smallest unit is 512bit. */ - uint32_t sha_data_cnt : 16; - /* currently calculated block number. 512bit=1block*/ - uint32_t sha_data_num : 16; -} __attribute__((packed, aligned(4))) sha_num_reg_t; - -typedef struct _sha_function_reg_0 -{ - /* write:SHA256 enable register. read:Calculation completed flag */ - uint32_t sha_en : 1; - uint32_t reserved00 : 7; - /* SHA256 calculation overflow flag */ - uint32_t sha_overflow : 1; - uint32_t reserved01 : 7; - /* Endian setting; b'0:little endian b'1:big endian */ - uint32_t sha_endian : 1; - uint32_t reserved02 : 15; -} __attribute__((packed, aligned(4))) sha_function_reg_0_t; - -typedef struct _sha_function_reg_1 -{ - /* Sha and DMA handshake signals enable.b'1:enable;b'0:disable */ - uint32_t dma_en : 1; - uint32_t reserved10 : 7; - /* b'1:sha256 fifo is full; b'0:not full */ - uint32_t fifo_in_full : 1; - uint32_t reserved11 : 23; -} __attribute__((packed, aligned(4))) sha_function_reg_1_t; - -typedef struct _sha256 -{ - /* Calculated sha256 return value. */ - uint32_t sha_result[8]; - /* SHA256 input data from this register. */ - uint32_t sha_data_in1; - uint32_t reselved0; - sha_num_reg_t sha_num_reg; - sha_function_reg_0_t sha_function_reg_0; - uint32_t reserved1; - sha_function_reg_1_t sha_function_reg_1; -} __attribute__((packed, aligned(4))) sha256_t; - -typedef struct _sha256_context -{ - size_t total_len; - size_t buffer_len; - union - { - uint32_t words[16]; - uint8_t bytes[64]; - } buffer; -} sha256_context_t; - -/** - * @brief Init SHA256 calculation context - * - * @param[in] context SHA256 context object - * - */ -void sha256_init(sha256_context_t *context, size_t input_len); - -/** - * @brief Called repeatedly with chunks of the message to be hashed - * - * @param[in] context SHA256 context object - * @param[in] data_buf data chunk to be hashed - * @param[in] buf_len length of data chunk - * - */ -void sha256_update(sha256_context_t *context, const void *input, size_t input_len); - -/** - * @brief Finish SHA256 hash process, output the result. - * - * @param[in] context SHA256 context object - * @param[out] output The buffer where SHA256 hash will be output - * - */ -void sha256_final(sha256_context_t *context, uint8_t *output); - -/** - * @brief Simple SHA256 hash once. - * - * @param[in] data Data will be hashed - * @param[in] data_len Data length - * @param[out] output Output buffer - * - */ -void sha256_hard_calculate(const uint8_t *input, size_t input_len, uint8_t *output); - -#ifdef __cplusplus -} -#endif - -#endif - diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/spi.h b/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/spi.h deleted file mode 100644 index ef5d3e8..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/spi.h +++ /dev/null @@ -1,460 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef _DRIVER_SPI_H -#define _DRIVER_SPI_H - -#include -#include -#include "dmac.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/* clang-format off */ -typedef struct _spi -{ - /* SPI Control Register 0 (0x00)*/ - volatile uint32_t ctrlr0; - /* SPI Control Register 1 (0x04)*/ - volatile uint32_t ctrlr1; - /* SPI Enable Register (0x08)*/ - volatile uint32_t ssienr; - /* SPI Microwire Control Register (0x0c)*/ - volatile uint32_t mwcr; - /* SPI Slave Enable Register (0x10)*/ - volatile uint32_t ser; - /* SPI Baud Rate Select (0x14)*/ - volatile uint32_t baudr; - /* SPI Transmit FIFO Threshold Level (0x18)*/ - volatile uint32_t txftlr; - /* SPI Receive FIFO Threshold Level (0x1c)*/ - volatile uint32_t rxftlr; - /* SPI Transmit FIFO Level Register (0x20)*/ - volatile uint32_t txflr; - /* SPI Receive FIFO Level Register (0x24)*/ - volatile uint32_t rxflr; - /* SPI Status Register (0x28)*/ - volatile uint32_t sr; - /* SPI Interrupt Mask Register (0x2c)*/ - volatile uint32_t imr; - /* SPI Interrupt Status Register (0x30)*/ - volatile uint32_t isr; - /* SPI Raw Interrupt Status Register (0x34)*/ - volatile uint32_t risr; - /* SPI Transmit FIFO Overflow Interrupt Clear Register (0x38)*/ - volatile uint32_t txoicr; - /* SPI Receive FIFO Overflow Interrupt Clear Register (0x3c)*/ - volatile uint32_t rxoicr; - /* SPI Receive FIFO Underflow Interrupt Clear Register (0x40)*/ - volatile uint32_t rxuicr; - /* SPI Multi-Master Interrupt Clear Register (0x44)*/ - volatile uint32_t msticr; - /* SPI Interrupt Clear Register (0x48)*/ - volatile uint32_t icr; - /* SPI DMA Control Register (0x4c)*/ - volatile uint32_t dmacr; - /* SPI DMA Transmit Data Level (0x50)*/ - volatile uint32_t dmatdlr; - /* SPI DMA Receive Data Level (0x54)*/ - volatile uint32_t dmardlr; - /* SPI Identification Register (0x58)*/ - volatile uint32_t idr; - /* SPI DWC_ssi component version (0x5c)*/ - volatile uint32_t ssic_version_id; - /* SPI Data Register 0-36 (0x60 -- 0xec)*/ - volatile uint32_t dr[36]; - /* SPI RX Sample Delay Register (0xf0)*/ - volatile uint32_t rx_sample_delay; - /* SPI SPI Control Register (0xf4)*/ - volatile uint32_t spi_ctrlr0; - /* reserved (0xf8)*/ - volatile uint32_t resv; - /* SPI XIP Mode bits (0xfc)*/ - volatile uint32_t xip_mode_bits; - /* SPI XIP INCR transfer opcode (0x100)*/ - volatile uint32_t xip_incr_inst; - /* SPI XIP WRAP transfer opcode (0x104)*/ - volatile uint32_t xip_wrap_inst; - /* SPI XIP Control Register (0x108)*/ - volatile uint32_t xip_ctrl; - /* SPI XIP Slave Enable Register (0x10c)*/ - volatile uint32_t xip_ser; - /* SPI XIP Receive FIFO Overflow Interrupt Clear Register (0x110)*/ - volatile uint32_t xrxoicr; - /* SPI XIP time out register for continuous transfers (0x114)*/ - volatile uint32_t xip_cnt_time_out; - volatile uint32_t endian; -} __attribute__((packed, aligned(4))) spi_t; -/* clang-format on */ - -typedef enum _spi_device_num -{ - SPI_DEVICE_0, - SPI_DEVICE_1, - SPI_DEVICE_2, - SPI_DEVICE_3, - SPI_DEVICE_MAX, -} spi_device_num_t; - -typedef enum _spi_work_mode -{ - SPI_WORK_MODE_0, - SPI_WORK_MODE_1, - SPI_WORK_MODE_2, - SPI_WORK_MODE_3, -} spi_work_mode_t; - -typedef enum _spi_frame_format -{ - SPI_FF_STANDARD, - SPI_FF_DUAL, - SPI_FF_QUAD, - SPI_FF_OCTAL -} spi_frame_format_t; - -typedef enum _spi_instruction_address_trans_mode -{ - SPI_AITM_STANDARD, - SPI_AITM_ADDR_STANDARD, - SPI_AITM_AS_FRAME_FORMAT -} spi_instruction_address_trans_mode_t; - -typedef enum _spi_transfer_mode -{ - SPI_TMOD_TRANS_RECV, - SPI_TMOD_TRANS, - SPI_TMOD_RECV, - SPI_TMOD_EEROM -} spi_transfer_mode_t; - - -typedef enum _spi_transfer_width -{ - SPI_TRANS_CHAR = 0x1, - SPI_TRANS_SHORT = 0x2, - SPI_TRANS_INT = 0x4, -} spi_transfer_width_t; - -typedef enum _spi_chip_select -{ - SPI_CHIP_SELECT_0, - SPI_CHIP_SELECT_1, - SPI_CHIP_SELECT_2, - SPI_CHIP_SELECT_3, - SPI_CHIP_SELECT_MAX, -} spi_chip_select_t; - -typedef enum { - WRITE_CONFIG, - READ_CONFIG, - WRITE_DATA_BYTE, - READ_DATA_BYTE, - WRITE_DATA_BLOCK, - READ_DATA_BLOCK, -} spi_slave_command_e; - -typedef struct -{ - uint8_t cmd; - uint8_t err; - uint32_t addr; - uint32_t len; -} spi_slave_command_t; - -typedef enum -{ - IDLE, - COMMAND, - TRANSFER, -} spi_slave_status_e; - -typedef int (*spi_slave_receive_callback_t)(void *ctx); - -typedef struct _spi_slave_instance -{ - uint8_t int_pin; - uint8_t ready_pin; - dmac_channel_number_t dmac_channel; - uint8_t dfs; - uint8_t slv_oe; - uint8_t work_mode; - size_t data_bit_length; - volatile spi_slave_status_e status; - volatile spi_slave_command_t command; - volatile uint8_t *config_ptr; - uint32_t config_len; - spi_slave_receive_callback_t callback; -} spi_slave_instance_t; - -extern volatile spi_t *const spi[4]; - -/** - * @brief Set spi configuration - * - * @param[in] spi_num Spi bus number - * @param[in] mode Spi mode - * @param[in] frame_format Spi frame format - * @param[in] data_bit_length Spi data bit length - * @param[in] endian 0:little-endian 1:big-endian - * - * @return Void - */ -void spi_init(spi_device_num_t spi_num, spi_work_mode_t work_mode, spi_frame_format_t frame_format, - size_t data_bit_length, uint32_t endian); - -/** - * @brief Set multiline configuration - * - * @param[in] spi_num Spi bus number - * @param[in] instruction_length Instruction length - * @param[in] address_length Address length - * @param[in] wait_cycles Wait cycles - * @param[in] instruction_address_trans_mode Spi transfer mode - * - */ -void spi_init_non_standard(spi_device_num_t spi_num, uint32_t instruction_length, uint32_t address_length, - uint32_t wait_cycles, spi_instruction_address_trans_mode_t instruction_address_trans_mode); - -/** - * @brief Spi send data - * - * @param[in] spi_num Spi bus number - * @param[in] chip_select Spi chip select - * @param[in] cmd_buff Spi command buffer point - * @param[in] cmd_len Spi command length - * @param[in] tx_buff Spi transmit buffer point - * @param[in] tx_len Spi transmit buffer length - * - * @return Result - * - 0 Success - * - Other Fail - */ -void spi_send_data_standard(spi_device_num_t spi_num, spi_chip_select_t chip_select, const uint8_t *cmd_buff, - size_t cmd_len, const uint8_t *tx_buff, size_t tx_len); - -/** - * @brief Spi receive data - * - * @param[in] spi_num Spi bus number - * @param[in] chip_select Spi chip select - * @param[in] cmd_buff Spi command buffer point - * @param[in] cmd_len Spi command length - * @param[in] rx_buff Spi receive buffer point - * @param[in] rx_len Spi receive buffer length - * - * @return Result - * - 0 Success - * - Other Fail - */ -void spi_receive_data_standard(spi_device_num_t spi_num, spi_chip_select_t chip_select, const uint8_t *cmd_buff, - size_t cmd_len, uint8_t *rx_buff, size_t rx_len); - -/** - * @brief Spi special receive data - * - * @param[in] spi_num Spi bus number - * @param[in] chip_select Spi chip select - * @param[in] cmd_buff Spi command buffer point - * @param[in] cmd_len Spi command length - * @param[in] rx_buff Spi receive buffer point - * @param[in] rx_len Spi receive buffer length - * - * @return Result - * - 0 Success - * - Other Fail - */ -void spi_receive_data_multiple(spi_device_num_t spi_num, spi_chip_select_t chip_select, const uint32_t *cmd_buff, - size_t cmd_len, uint8_t *rx_buff, size_t rx_len); - -/** - * @brief Spi special send data - * - * @param[in] spi_num Spi bus number - * @param[in] chip_select Spi chip select - * @param[in] cmd_buff Spi command buffer point - * @param[in] cmd_len Spi command length - * @param[in] tx_buff Spi transmit buffer point - * @param[in] tx_len Spi transmit buffer length - * - * @return Result - * - 0 Success - * - Other Fail - */ -void spi_send_data_multiple(spi_device_num_t spi_num, spi_chip_select_t chip_select, const uint32_t *cmd_buff, - size_t cmd_len, const uint8_t *tx_buff, size_t tx_len); - -/** - * @brief Spi send data by dma - * - * @param[in] channel_num Dmac channel number - * @param[in] spi_num Spi bus number - * @param[in] chip_select Spi chip select - * @param[in] cmd_buff Spi command buffer point - * @param[in] cmd_len Spi command length - * @param[in] tx_buff Spi transmit buffer point - * @param[in] tx_len Spi transmit buffer length - * - * @return Result - * - 0 Success - * - Other Fail - */ -void spi_send_data_standard_dma(dmac_channel_number_t channel_num, spi_device_num_t spi_num, - spi_chip_select_t chip_select, - const uint8_t *cmd_buff, size_t cmd_len, const uint8_t *tx_buff, size_t tx_len); - -/** - * @brief Spi receive data by dma - * - * @param[in] w_channel_num Dmac write channel number - * @param[in] r_channel_num Dmac read channel number - * @param[in] spi_num Spi bus number - * @param[in] chip_select Spi chip select - * @param[in] cmd_buff Spi command buffer point - * @param[in] cmd_len Spi command length - * @param[in] rx_buff Spi receive buffer point - * @param[in] rx_len Spi receive buffer length - * - * @return Result - * - 0 Success - * - Other Fail - */ -void spi_receive_data_standard_dma(dmac_channel_number_t dma_send_channel_num, - dmac_channel_number_t dma_receive_channel_num, - spi_device_num_t spi_num, spi_chip_select_t chip_select, const uint8_t *cmd_buff, - size_t cmd_len, uint8_t *rx_buff, size_t rx_len); - -/** - * @brief Spi special send data by dma - * - * @param[in] channel_num Dmac channel number - * @param[in] spi_num Spi bus number - * @param[in] chip_select Spi chip select - * @param[in] cmd_buff Spi command buffer point - * @param[in] cmd_len Spi command length - * @param[in] tx_buff Spi transmit buffer point - * @param[in] tx_len Spi transmit buffer length - * - * @return Result - * - 0 Success - * - Other Fail - */ -void spi_send_data_multiple_dma(dmac_channel_number_t channel_num, spi_device_num_t spi_num, - spi_chip_select_t chip_select, - const uint32_t *cmd_buff, size_t cmd_len, const uint8_t *tx_buff, size_t tx_len); - -/** - * @brief Spi special receive data by dma - * - * @param[in] dma_send_channel_num Dmac write channel number - * @param[in] dma_receive_channel_num Dmac read channel number - * @param[in] spi_num Spi bus number - * @param[in] chip_select Spi chip select - * @param[in] cmd_buff Spi command buffer point - * @param[in] cmd_len Spi command length - * @param[in] rx_buff Spi receive buffer point - * @param[in] rx_len Spi receive buffer length - * - * @return Result - * - 0 Success - * - Other Fail - */ -void spi_receive_data_multiple_dma(dmac_channel_number_t dma_send_channel_num, - dmac_channel_number_t dma_receive_channel_num, - spi_device_num_t spi_num, spi_chip_select_t chip_select, const uint32_t *cmd_buff, - size_t cmd_len, uint8_t *rx_buff, size_t rx_len); - -/** - * @brief Spi fill dma - * - * @param[in] channel_num Dmac channel number - * @param[in] spi_num Spi bus number - * @param[in] chip_select Spi chip select - * @param[in] tx_buff Spi command buffer point - * @param[in] tx_len Spi command length - * - * @return Result - * - 0 Success - * - Other Fail - */ -void spi_fill_data_dma(dmac_channel_number_t channel_num, spi_device_num_t spi_num, spi_chip_select_t chip_select, - const uint32_t *tx_buff, size_t tx_len); - -/** - * @brief Spi normal send by dma - * - * @param[in] channel_num Dmac channel number - * @param[in] spi_num Spi bus number - * @param[in] chip_select Spi chip select - * @param[in] tx_buff Spi transmit buffer point - * @param[in] tx_len Spi transmit buffer length - * @param[in] stw Spi transfer width - * - * @return Result - * - 0 Success - * - Other Fail - */ -void spi_send_data_normal_dma(dmac_channel_number_t channel_num, spi_device_num_t spi_num, - spi_chip_select_t chip_select, - const void *tx_buff, size_t tx_len, spi_transfer_width_t spi_transfer_width); - -/** - * @brief Spi normal send by dma - * - * @param[in] spi_num Spi bus number - * @param[in] spi_clk Spi clock rate - * - * @return The real spi clock rate - */ -uint32_t spi_set_clk_rate(spi_device_num_t spi_num, uint32_t spi_clk); - -/** - * @brief Spi full duplex send receive data by dma - * - * @param[in] dma_send_channel_num Dmac write channel number - * @param[in] dma_receive_channel_num Dmac read channel number - * @param[in] spi_num Spi bus number - * @param[in] chip_select Spi chip select - * @param[in] tx_buf Spi send buffer - * @param[in] tx_len Spi send buffer length - * @param[in] rx_buf Spi receive buffer - * @param[in] rx_len Spi receive buffer length - * - */ -void spi_dup_send_receive_data_dma(dmac_channel_number_t dma_send_channel_num, - dmac_channel_number_t dma_receive_channel_num, - spi_device_num_t spi_num, spi_chip_select_t chip_select, - const uint8_t *tx_buf, size_t tx_len, uint8_t *rx_buf, size_t rx_len); - -/** - * @brief Set spi slave configuration - * - * @param[in] int_pin SPI master starts sending data interrupt. - * @param[in] ready_pin SPI slave ready. - * @param[in] dmac_channel Dmac channel number for block. - * @param[in] data_bit_length Spi data bit length - * @param[in] data SPI slave device data buffer. - * @param[in] len The length of SPI slave device data buffer. - * @param[in] callback Callback of spi slave. - * - * @return Void - */ -void spi_slave_config(uint8_t int_pin, uint8_t ready_pin, dmac_channel_number_t dmac_channel, size_t data_bit_length, uint8_t *data, uint32_t len, spi_slave_receive_callback_t callback); - -#ifdef __cplusplus -} -#endif - -#endif /* _DRIVER_SPI_H */ diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/sysctl.h b/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/sysctl.h deleted file mode 100644 index 4a06a39..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/sysctl.h +++ /dev/null @@ -1,1078 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef _DRIVER_SYSCTL_H -#define _DRIVER_SYSCTL_H - -#include -#include "platform.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * @brief System controller register - * - * @note System controller register table - * - * | Offset | Name | Description | - * |-----------|----------------|-------------------------------------| - * | 0x00 | git_id | Git short commit id | - * | 0x04 | clk_freq | System clock base frequency | - * | 0x08 | pll0 | PLL0 controller | - * | 0x0c | pll1 | PLL1 controller | - * | 0x10 | pll2 | PLL2 controller | - * | 0x14 | resv5 | Reserved | - * | 0x18 | pll_lock | PLL lock tester | - * | 0x1c | rom_error | AXI ROM detector | - * | 0x20 | clk_sel0 | Clock select controller0 | - * | 0x24 | clk_sel1 | Clock select controller1 | - * | 0x28 | clk_en_cent | Central clock enable | - * | 0x2c | clk_en_peri | Peripheral clock enable | - * | 0x30 | soft_reset | Soft reset ctrl | - * | 0x34 | peri_reset | Peripheral reset controller | - * | 0x38 | clk_th0 | Clock threshold controller 0 | - * | 0x3c | clk_th1 | Clock threshold controller 1 | - * | 0x40 | clk_th2 | Clock threshold controller 2 | - * | 0x44 | clk_th3 | Clock threshold controller 3 | - * | 0x48 | clk_th4 | Clock threshold controller 4 | - * | 0x4c | clk_th5 | Clock threshold controller 5 | - * | 0x50 | clk_th6 | Clock threshold controller 6 | - * | 0x54 | misc | Miscellaneous controller | - * | 0x58 | peri | Peripheral controller | - * | 0x5c | spi_sleep | SPI sleep controller | - * | 0x60 | reset_status | Reset source status | - * | 0x64 | dma_sel0 | DMA handshake selector | - * | 0x68 | dma_sel1 | DMA handshake selector | - * | 0x6c | power_sel | IO Power Mode Select controller | - * | 0x70 | resv28 | Reserved | - * | 0x74 | resv29 | Reserved | - * | 0x78 | resv30 | Reserved | - * | 0x7c | resv31 | Reserved | - * - */ - -typedef enum _sysctl_pll_t -{ - SYSCTL_PLL0, - SYSCTL_PLL1, - SYSCTL_PLL2, - SYSCTL_PLL_MAX -} sysctl_pll_t; - -typedef enum _sysctl_clock_source_t -{ - SYSCTL_SOURCE_IN0, - SYSCTL_SOURCE_PLL0, - SYSCTL_SOURCE_PLL1, - SYSCTL_SOURCE_PLL2, - SYSCTL_SOURCE_ACLK, - SYSCTL_SOURCE_MAX -} sysctl_clock_source_t; - -typedef enum _sysctl_dma_channel_t -{ - SYSCTL_DMA_CHANNEL_0, - SYSCTL_DMA_CHANNEL_1, - SYSCTL_DMA_CHANNEL_2, - SYSCTL_DMA_CHANNEL_3, - SYSCTL_DMA_CHANNEL_4, - SYSCTL_DMA_CHANNEL_5, - SYSCTL_DMA_CHANNEL_MAX -} sysctl_dma_channel_t; - -typedef enum _sysctl_dma_select_t -{ - SYSCTL_DMA_SELECT_SSI0_RX_REQ, - SYSCTL_DMA_SELECT_SSI0_TX_REQ, - SYSCTL_DMA_SELECT_SSI1_RX_REQ, - SYSCTL_DMA_SELECT_SSI1_TX_REQ, - SYSCTL_DMA_SELECT_SSI2_RX_REQ, - SYSCTL_DMA_SELECT_SSI2_TX_REQ, - SYSCTL_DMA_SELECT_SSI3_RX_REQ, - SYSCTL_DMA_SELECT_SSI3_TX_REQ, - SYSCTL_DMA_SELECT_I2C0_RX_REQ, - SYSCTL_DMA_SELECT_I2C0_TX_REQ, - SYSCTL_DMA_SELECT_I2C1_RX_REQ, - SYSCTL_DMA_SELECT_I2C1_TX_REQ, - SYSCTL_DMA_SELECT_I2C2_RX_REQ, - SYSCTL_DMA_SELECT_I2C2_TX_REQ, - SYSCTL_DMA_SELECT_UART1_RX_REQ, - SYSCTL_DMA_SELECT_UART1_TX_REQ, - SYSCTL_DMA_SELECT_UART2_RX_REQ, - SYSCTL_DMA_SELECT_UART2_TX_REQ, - SYSCTL_DMA_SELECT_UART3_RX_REQ, - SYSCTL_DMA_SELECT_UART3_TX_REQ, - SYSCTL_DMA_SELECT_AES_REQ, - SYSCTL_DMA_SELECT_SHA_RX_REQ, - SYSCTL_DMA_SELECT_AI_RX_REQ, - SYSCTL_DMA_SELECT_FFT_RX_REQ, - SYSCTL_DMA_SELECT_FFT_TX_REQ, - SYSCTL_DMA_SELECT_I2S0_TX_REQ, - SYSCTL_DMA_SELECT_I2S0_RX_REQ, - SYSCTL_DMA_SELECT_I2S1_TX_REQ, - SYSCTL_DMA_SELECT_I2S1_RX_REQ, - SYSCTL_DMA_SELECT_I2S2_TX_REQ, - SYSCTL_DMA_SELECT_I2S2_RX_REQ, - SYSCTL_DMA_SELECT_I2S0_BF_DIR_REQ, - SYSCTL_DMA_SELECT_I2S0_BF_VOICE_REQ, - SYSCTL_DMA_SELECT_MAX -} sysctl_dma_select_t; - -/** - * @brief System controller clock id - */ -typedef enum _sysctl_clock_t -{ - SYSCTL_CLOCK_PLL0, - SYSCTL_CLOCK_PLL1, - SYSCTL_CLOCK_PLL2, - SYSCTL_CLOCK_CPU, - SYSCTL_CLOCK_SRAM0, - SYSCTL_CLOCK_SRAM1, - SYSCTL_CLOCK_APB0, - SYSCTL_CLOCK_APB1, - SYSCTL_CLOCK_APB2, - SYSCTL_CLOCK_ROM, - SYSCTL_CLOCK_DMA, - SYSCTL_CLOCK_AI, - SYSCTL_CLOCK_DVP, - SYSCTL_CLOCK_FFT, - SYSCTL_CLOCK_GPIO, - SYSCTL_CLOCK_SPI0, - SYSCTL_CLOCK_SPI1, - SYSCTL_CLOCK_SPI2, - SYSCTL_CLOCK_SPI3, - SYSCTL_CLOCK_I2S0, - SYSCTL_CLOCK_I2S1, - SYSCTL_CLOCK_I2S2, - SYSCTL_CLOCK_I2C0, - SYSCTL_CLOCK_I2C1, - SYSCTL_CLOCK_I2C2, - SYSCTL_CLOCK_UART1, - SYSCTL_CLOCK_UART2, - SYSCTL_CLOCK_UART3, - SYSCTL_CLOCK_AES, - SYSCTL_CLOCK_FPIOA, - SYSCTL_CLOCK_TIMER0, - SYSCTL_CLOCK_TIMER1, - SYSCTL_CLOCK_TIMER2, - SYSCTL_CLOCK_WDT0, - SYSCTL_CLOCK_WDT1, - SYSCTL_CLOCK_SHA, - SYSCTL_CLOCK_OTP, - SYSCTL_CLOCK_RTC, - SYSCTL_CLOCK_ACLK = 40, - SYSCTL_CLOCK_HCLK, - SYSCTL_CLOCK_IN0, - SYSCTL_CLOCK_MAX -} sysctl_clock_t; - -/** - * @brief System controller clock select id - */ -typedef enum _sysctl_clock_select_t -{ - SYSCTL_CLOCK_SELECT_PLL0_BYPASS, - SYSCTL_CLOCK_SELECT_PLL1_BYPASS, - SYSCTL_CLOCK_SELECT_PLL2_BYPASS, - SYSCTL_CLOCK_SELECT_PLL2, - SYSCTL_CLOCK_SELECT_ACLK, - SYSCTL_CLOCK_SELECT_SPI3, - SYSCTL_CLOCK_SELECT_TIMER0, - SYSCTL_CLOCK_SELECT_TIMER1, - SYSCTL_CLOCK_SELECT_TIMER2, - SYSCTL_CLOCK_SELECT_SPI3_SAMPLE, - SYSCTL_CLOCK_SELECT_MAX = 11 -} sysctl_clock_select_t; - -/** - * @brief System controller clock threshold id - */ -typedef enum _sysctl_threshold_t -{ - SYSCTL_THRESHOLD_ACLK, - SYSCTL_THRESHOLD_APB0, - SYSCTL_THRESHOLD_APB1, - SYSCTL_THRESHOLD_APB2, - SYSCTL_THRESHOLD_SRAM0, - SYSCTL_THRESHOLD_SRAM1, - SYSCTL_THRESHOLD_AI, - SYSCTL_THRESHOLD_DVP, - SYSCTL_THRESHOLD_ROM, - SYSCTL_THRESHOLD_SPI0, - SYSCTL_THRESHOLD_SPI1, - SYSCTL_THRESHOLD_SPI2, - SYSCTL_THRESHOLD_SPI3, - SYSCTL_THRESHOLD_TIMER0, - SYSCTL_THRESHOLD_TIMER1, - SYSCTL_THRESHOLD_TIMER2, - SYSCTL_THRESHOLD_I2S0, - SYSCTL_THRESHOLD_I2S1, - SYSCTL_THRESHOLD_I2S2, - SYSCTL_THRESHOLD_I2S0_M, - SYSCTL_THRESHOLD_I2S1_M, - SYSCTL_THRESHOLD_I2S2_M, - SYSCTL_THRESHOLD_I2C0, - SYSCTL_THRESHOLD_I2C1, - SYSCTL_THRESHOLD_I2C2, - SYSCTL_THRESHOLD_WDT0, - SYSCTL_THRESHOLD_WDT1, - SYSCTL_THRESHOLD_MAX = 28 -} sysctl_threshold_t; - -/** - * @brief System controller reset control id - */ -typedef enum _sysctl_reset_t -{ - SYSCTL_RESET_SOC, - SYSCTL_RESET_ROM, - SYSCTL_RESET_DMA, - SYSCTL_RESET_AI, - SYSCTL_RESET_DVP, - SYSCTL_RESET_FFT, - SYSCTL_RESET_GPIO, - SYSCTL_RESET_SPI0, - SYSCTL_RESET_SPI1, - SYSCTL_RESET_SPI2, - SYSCTL_RESET_SPI3, - SYSCTL_RESET_I2S0, - SYSCTL_RESET_I2S1, - SYSCTL_RESET_I2S2, - SYSCTL_RESET_I2C0, - SYSCTL_RESET_I2C1, - SYSCTL_RESET_I2C2, - SYSCTL_RESET_UART1, - SYSCTL_RESET_UART2, - SYSCTL_RESET_UART3, - SYSCTL_RESET_AES, - SYSCTL_RESET_FPIOA, - SYSCTL_RESET_TIMER0, - SYSCTL_RESET_TIMER1, - SYSCTL_RESET_TIMER2, - SYSCTL_RESET_WDT0, - SYSCTL_RESET_WDT1, - SYSCTL_RESET_SHA, - SYSCTL_RESET_RTC, - SYSCTL_RESET_MAX = 31 -} sysctl_reset_t; - -/** - * @brief System controller power bank id - */ -typedef enum _sysctl_power_bank -{ - SYSCTL_POWER_BANK0, - SYSCTL_POWER_BANK1, - SYSCTL_POWER_BANK2, - SYSCTL_POWER_BANK3, - SYSCTL_POWER_BANK4, - SYSCTL_POWER_BANK5, - SYSCTL_POWER_BANK6, - SYSCTL_POWER_BANK7, - SYSCTL_POWER_BANK_MAX, -} sysctl_power_bank_t; - -/** - * @brief System controller reset control id - */ -typedef enum _sysctl_io_power_mode -{ - SYSCTL_POWER_V33, - SYSCTL_POWER_V18 -} sysctl_io_power_mode_t; - -/** - * @brief System reset status - */ -typedef enum _sysctl_reset_enum_status -{ - SYSCTL_RESET_STATUS_HARD, - SYSCTL_RESET_STATUS_SOFT, - SYSCTL_RESET_STATUS_WDT0, - SYSCTL_RESET_STATUS_WDT1, - SYSCTL_RESET_STATUS_MAX, -} sysctl_reset_enum_status_t; - -/** - * @brief Git short commit id - * - * No. 0 Register (0x00) - */ -typedef struct _sysctl_git_id -{ - uint32_t git_id : 32; -} __attribute__((packed, aligned(4))) sysctl_git_id_t; - -/** - * @brief System clock base frequency - * - * No. 1 Register (0x04) - */ -typedef struct _sysctl_clk_freq -{ - uint32_t clk_freq : 32; -} __attribute__((packed, aligned(4))) sysctl_clk_freq_t; - -/** - * @brief PLL0 controller - * - * No. 2 Register (0x08) - */ -typedef struct _sysctl_pll0 -{ - uint32_t clkr0 : 4; - uint32_t clkf0 : 6; - uint32_t clkod0 : 4; - uint32_t bwadj0 : 6; - uint32_t pll_reset0 : 1; - uint32_t pll_pwrd0 : 1; - uint32_t pll_intfb0 : 1; - uint32_t pll_bypass0 : 1; - uint32_t pll_test0 : 1; - uint32_t pll_out_en0 : 1; - uint32_t pll_test_en : 1; - uint32_t reserved : 5; -} __attribute__((packed, aligned(4))) sysctl_pll0_t; - -/** - * @brief PLL1 controller - * - * No. 3 Register (0x0c) - */ -typedef struct _sysctl_pll1 -{ - uint32_t clkr1 : 4; - uint32_t clkf1 : 6; - uint32_t clkod1 : 4; - uint32_t bwadj1 : 6; - uint32_t pll_reset1 : 1; - uint32_t pll_pwrd1 : 1; - uint32_t pll_intfb1 : 1; - uint32_t pll_bypass1 : 1; - uint32_t pll_test1 : 1; - uint32_t pll_out_en1 : 1; - uint32_t reserved : 6; -} __attribute__((packed, aligned(4))) sysctl_pll1_t; - -/** - * @brief PLL2 controller - * - * No. 4 Register (0x10) - */ -typedef struct _sysctl_pll2 -{ - uint32_t clkr2 : 4; - uint32_t clkf2 : 6; - uint32_t clkod2 : 4; - uint32_t bwadj2 : 6; - uint32_t pll_reset2 : 1; - uint32_t pll_pwrd2 : 1; - uint32_t pll_intfb2 : 1; - uint32_t pll_bypass2 : 1; - uint32_t pll_test2 : 1; - uint32_t pll_out_en2 : 1; - uint32_t pll_ckin_sel2 : 2; - uint32_t reserved : 4; -} __attribute__((packed, aligned(4))) sysctl_pll2_t; - -/** - * @brief PLL lock tester - * - * No. 6 Register (0x18) - */ -typedef struct _sysctl_pll_lock -{ - uint32_t pll_lock0 : 2; - uint32_t pll_slip_clear0 : 1; - uint32_t test_clk_out0 : 1; - uint32_t reserved0 : 4; - uint32_t pll_lock1 : 2; - uint32_t pll_slip_clear1 : 1; - uint32_t test_clk_out1 : 1; - uint32_t reserved1 : 4; - uint32_t pll_lock2 : 2; - uint32_t pll_slip_clear2 : 1; - uint32_t test_clk_out2 : 1; - uint32_t reserved2 : 12; -} __attribute__((packed, aligned(4))) sysctl_pll_lock_t; - -/** - * @brief AXI ROM detector - * - * No. 7 Register (0x1c) - */ -typedef struct _sysctl_rom_error -{ - uint32_t rom_mul_error : 1; - uint32_t rom_one_error : 1; - uint32_t reserved : 30; -} __attribute__((packed, aligned(4))) sysctl_rom_error_t; - -/** - * @brief Clock select controller0 - * - * No. 8 Register (0x20) - */ -typedef struct _sysctl_clk_sel0 -{ - uint32_t aclk_sel : 1; - uint32_t aclk_divider_sel : 2; - uint32_t apb0_clk_sel : 3; - uint32_t apb1_clk_sel : 3; - uint32_t apb2_clk_sel : 3; - uint32_t spi3_clk_sel : 1; - uint32_t timer0_clk_sel : 1; - uint32_t timer1_clk_sel : 1; - uint32_t timer2_clk_sel : 1; - uint32_t reserved : 16; -} __attribute__((packed, aligned(4))) sysctl_clk_sel0_t; - -/** - * @brief Clock select controller1 - * - * No. 9 Register (0x24) - */ -typedef struct _sysctl_clk_sel1 -{ - uint32_t spi3_sample_clk_sel : 1; - uint32_t reserved0 : 30; - uint32_t reserved1 : 1; -} __attribute__((packed, aligned(4))) sysctl_clk_sel1_t; - -/** - * @brief Central clock enable - * - * No. 10 Register (0x28) - */ -typedef struct _sysctl_clk_en_cent -{ - uint32_t cpu_clk_en : 1; - uint32_t sram0_clk_en : 1; - uint32_t sram1_clk_en : 1; - uint32_t apb0_clk_en : 1; - uint32_t apb1_clk_en : 1; - uint32_t apb2_clk_en : 1; - uint32_t reserved : 26; -} __attribute__((packed, aligned(4))) sysctl_clk_en_cent_t; - -/** - * @brief Peripheral clock enable - * - * No. 11 Register (0x2c) - */ -typedef struct _sysctl_clk_en_peri -{ - uint32_t rom_clk_en : 1; - uint32_t dma_clk_en : 1; - uint32_t ai_clk_en : 1; - uint32_t dvp_clk_en : 1; - uint32_t fft_clk_en : 1; - uint32_t gpio_clk_en : 1; - uint32_t spi0_clk_en : 1; - uint32_t spi1_clk_en : 1; - uint32_t spi2_clk_en : 1; - uint32_t spi3_clk_en : 1; - uint32_t i2s0_clk_en : 1; - uint32_t i2s1_clk_en : 1; - uint32_t i2s2_clk_en : 1; - uint32_t i2c0_clk_en : 1; - uint32_t i2c1_clk_en : 1; - uint32_t i2c2_clk_en : 1; - uint32_t uart1_clk_en : 1; - uint32_t uart2_clk_en : 1; - uint32_t uart3_clk_en : 1; - uint32_t aes_clk_en : 1; - uint32_t fpioa_clk_en : 1; - uint32_t timer0_clk_en : 1; - uint32_t timer1_clk_en : 1; - uint32_t timer2_clk_en : 1; - uint32_t wdt0_clk_en : 1; - uint32_t wdt1_clk_en : 1; - uint32_t sha_clk_en : 1; - uint32_t otp_clk_en : 1; - uint32_t reserved : 1; - uint32_t rtc_clk_en : 1; - uint32_t reserved0 : 2; -} __attribute__((packed, aligned(4))) sysctl_clk_en_peri_t; - -/** - * @brief Soft reset ctrl - * - * No. 12 Register (0x30) - */ -typedef struct _sysctl_soft_reset -{ - uint32_t soft_reset : 1; - uint32_t reserved : 31; -} __attribute__((packed, aligned(4))) sysctl_soft_reset_t; - -/** - * @brief Peripheral reset controller - * - * No. 13 Register (0x34) - */ -typedef struct _sysctl_peri_reset -{ - uint32_t rom_reset : 1; - uint32_t dma_reset : 1; - uint32_t ai_reset : 1; - uint32_t dvp_reset : 1; - uint32_t fft_reset : 1; - uint32_t gpio_reset : 1; - uint32_t spi0_reset : 1; - uint32_t spi1_reset : 1; - uint32_t spi2_reset : 1; - uint32_t spi3_reset : 1; - uint32_t i2s0_reset : 1; - uint32_t i2s1_reset : 1; - uint32_t i2s2_reset : 1; - uint32_t i2c0_reset : 1; - uint32_t i2c1_reset : 1; - uint32_t i2c2_reset : 1; - uint32_t uart1_reset : 1; - uint32_t uart2_reset : 1; - uint32_t uart3_reset : 1; - uint32_t aes_reset : 1; - uint32_t fpioa_reset : 1; - uint32_t timer0_reset : 1; - uint32_t timer1_reset : 1; - uint32_t timer2_reset : 1; - uint32_t wdt0_reset : 1; - uint32_t wdt1_reset : 1; - uint32_t sha_reset : 1; - uint32_t reserved : 2; - uint32_t rtc_reset : 1; - uint32_t reserved0 : 2; -} __attribute__((packed, aligned(4))) sysctl_peri_reset_t; - -/** - * @brief Clock threshold controller 0 - * - * No. 14 Register (0x38) - */ -typedef struct _sysctl_clk_th0 -{ - uint32_t sram0_gclk_threshold : 4; - uint32_t sram1_gclk_threshold : 4; - uint32_t ai_gclk_threshold : 4; - uint32_t dvp_gclk_threshold : 4; - uint32_t rom_gclk_threshold : 4; - uint32_t reserved : 12; -} __attribute__((packed, aligned(4))) sysctl_clk_th0_t; - -/** - * @brief Clock threshold controller 1 - * - * No. 15 Register (0x3c) - */ -typedef struct _sysctl_clk_th1 -{ - uint32_t spi0_clk_threshold : 8; - uint32_t spi1_clk_threshold : 8; - uint32_t spi2_clk_threshold : 8; - uint32_t spi3_clk_threshold : 8; -} __attribute__((packed, aligned(4))) sysctl_clk_th1_t; - -/** - * @brief Clock threshold controller 2 - * - * No. 16 Register (0x40) - */ -typedef struct _sysctl_clk_th2 -{ - uint32_t timer0_clk_threshold : 8; - uint32_t timer1_clk_threshold : 8; - uint32_t timer2_clk_threshold : 8; - uint32_t reserved : 8; -} __attribute__((packed, aligned(4))) sysctl_clk_th2_t; - -/** - * @brief Clock threshold controller 3 - * - * No. 17 Register (0x44) - */ -typedef struct _sysctl_clk_th3 -{ - uint32_t i2s0_clk_threshold : 16; - uint32_t i2s1_clk_threshold : 16; -} __attribute__((packed, aligned(4))) sysctl_clk_th3_t; - -/** - * @brief Clock threshold controller 4 - * - * No. 18 Register (0x48) - */ -typedef struct _sysctl_clk_th4 -{ - uint32_t i2s2_clk_threshold : 16; - uint32_t i2s0_mclk_threshold : 8; - uint32_t i2s1_mclk_threshold : 8; -} __attribute__((packed, aligned(4))) sysctl_clk_th4_t; - -/** - * @brief Clock threshold controller 5 - * - * No. 19 Register (0x4c) - */ -typedef struct _sysctl_clk_th5 -{ - uint32_t i2s2_mclk_threshold : 8; - uint32_t i2c0_clk_threshold : 8; - uint32_t i2c1_clk_threshold : 8; - uint32_t i2c2_clk_threshold : 8; -} __attribute__((packed, aligned(4))) sysctl_clk_th5_t; - -/** - * @brief Clock threshold controller 6 - * - * No. 20 Register (0x50) - */ -typedef struct _sysctl_clk_th6 -{ - uint32_t wdt0_clk_threshold : 8; - uint32_t wdt1_clk_threshold : 8; - uint32_t reserved0 : 8; - uint32_t reserved1 : 8; -} __attribute__((packed, aligned(4))) sysctl_clk_th6_t; - -/** - * @brief Miscellaneous controller - * - * No. 21 Register (0x54) - */ -typedef struct _sysctl_misc -{ - uint32_t debug_sel : 6; - uint32_t reserved0 : 4; - uint32_t spi_dvp_data_enable: 1; - uint32_t reserved1 : 21; -} __attribute__((packed, aligned(4))) sysctl_misc_t; - -/** - * @brief Peripheral controller - * - * No. 22 Register (0x58) - */ -typedef struct _sysctl_peri -{ - uint32_t timer0_pause : 1; - uint32_t timer1_pause : 1; - uint32_t timer2_pause : 1; - uint32_t timer3_pause : 1; - uint32_t timer4_pause : 1; - uint32_t timer5_pause : 1; - uint32_t timer6_pause : 1; - uint32_t timer7_pause : 1; - uint32_t timer8_pause : 1; - uint32_t timer9_pause : 1; - uint32_t timer10_pause : 1; - uint32_t timer11_pause : 1; - uint32_t spi0_xip_en : 1; - uint32_t spi1_xip_en : 1; - uint32_t spi2_xip_en : 1; - uint32_t spi3_xip_en : 1; - uint32_t spi0_clk_bypass : 1; - uint32_t spi1_clk_bypass : 1; - uint32_t spi2_clk_bypass : 1; - uint32_t i2s0_clk_bypass : 1; - uint32_t i2s1_clk_bypass : 1; - uint32_t i2s2_clk_bypass : 1; - uint32_t jtag_clk_bypass : 1; - uint32_t dvp_clk_bypass : 1; - uint32_t debug_clk_bypass : 1; - uint32_t reserved0 : 1; - uint32_t reserved1 : 6; -} __attribute__((packed, aligned(4))) sysctl_peri_t; - -/** - * @brief SPI sleep controller - * - * No. 23 Register (0x5c) - */ -typedef struct _sysctl_spi_sleep -{ - uint32_t ssi0_sleep : 1; - uint32_t ssi1_sleep : 1; - uint32_t ssi2_sleep : 1; - uint32_t ssi3_sleep : 1; - uint32_t reserved : 28; -} __attribute__((packed, aligned(4))) sysctl_spi_sleep_t; - -/** - * @brief Reset source status - * - * No. 24 Register (0x60) - */ -typedef struct _sysctl_reset_status -{ - uint32_t reset_sts_clr : 1; - uint32_t pin_reset_sts : 1; - uint32_t wdt0_reset_sts : 1; - uint32_t wdt1_reset_sts : 1; - uint32_t soft_reset_sts : 1; - uint32_t reserved : 27; -} __attribute__((packed, aligned(4))) sysctl_reset_status_t; - -/** - * @brief DMA handshake selector - * - * No. 25 Register (0x64) - */ -typedef struct _sysctl_dma_sel0 -{ - uint32_t dma_sel0 : 6; - uint32_t dma_sel1 : 6; - uint32_t dma_sel2 : 6; - uint32_t dma_sel3 : 6; - uint32_t dma_sel4 : 6; - uint32_t reserved : 2; -} __attribute__((packed, aligned(4))) sysctl_dma_sel0_t; - -/** - * @brief DMA handshake selector - * - * No. 26 Register (0x68) - */ -typedef struct _sysctl_dma_sel1 -{ - uint32_t dma_sel5 : 6; - uint32_t reserved : 26; -} __attribute__((packed, aligned(4))) sysctl_dma_sel1_t; - -/** - * @brief IO Power Mode Select controller - * - * No. 27 Register (0x6c) - */ -typedef struct _sysctl_power_sel -{ - uint32_t power_mode_sel0 : 1; - uint32_t power_mode_sel1 : 1; - uint32_t power_mode_sel2 : 1; - uint32_t power_mode_sel3 : 1; - uint32_t power_mode_sel4 : 1; - uint32_t power_mode_sel5 : 1; - uint32_t power_mode_sel6 : 1; - uint32_t power_mode_sel7 : 1; - uint32_t reserved : 24; -} __attribute__((packed, aligned(4))) sysctl_power_sel_t; - -/** - * @brief System controller object - * - * The System controller is a peripheral device mapped in the - * internal memory map, discoverable in the Configuration String. - * It is responsible for low-level configuration of all system - * related peripheral device. It contain PLL controller, clock - * controller, reset controller, DMA handshake controller, SPI - * controller, timer controller, WDT controller and sleep - * controller. - */ -typedef struct _sysctl -{ - /* No. 0 (0x00): Git short commit id */ - sysctl_git_id_t git_id; - /* No. 1 (0x04): System clock base frequency */ - sysctl_clk_freq_t clk_freq; - /* No. 2 (0x08): PLL0 controller */ - sysctl_pll0_t pll0; - /* No. 3 (0x0c): PLL1 controller */ - sysctl_pll1_t pll1; - /* No. 4 (0x10): PLL2 controller */ - sysctl_pll2_t pll2; - /* No. 5 (0x14): Reserved */ - uint32_t resv5; - /* No. 6 (0x18): PLL lock tester */ - sysctl_pll_lock_t pll_lock; - /* No. 7 (0x1c): AXI ROM detector */ - sysctl_rom_error_t rom_error; - /* No. 8 (0x20): Clock select controller0 */ - sysctl_clk_sel0_t clk_sel0; - /* No. 9 (0x24): Clock select controller1 */ - sysctl_clk_sel1_t clk_sel1; - /* No. 10 (0x28): Central clock enable */ - sysctl_clk_en_cent_t clk_en_cent; - /* No. 11 (0x2c): Peripheral clock enable */ - sysctl_clk_en_peri_t clk_en_peri; - /* No. 12 (0x30): Soft reset ctrl */ - sysctl_soft_reset_t soft_reset; - /* No. 13 (0x34): Peripheral reset controller */ - sysctl_peri_reset_t peri_reset; - /* No. 14 (0x38): Clock threshold controller 0 */ - sysctl_clk_th0_t clk_th0; - /* No. 15 (0x3c): Clock threshold controller 1 */ - sysctl_clk_th1_t clk_th1; - /* No. 16 (0x40): Clock threshold controller 2 */ - sysctl_clk_th2_t clk_th2; - /* No. 17 (0x44): Clock threshold controller 3 */ - sysctl_clk_th3_t clk_th3; - /* No. 18 (0x48): Clock threshold controller 4 */ - sysctl_clk_th4_t clk_th4; - /* No. 19 (0x4c): Clock threshold controller 5 */ - sysctl_clk_th5_t clk_th5; - /* No. 20 (0x50): Clock threshold controller 6 */ - sysctl_clk_th6_t clk_th6; - /* No. 21 (0x54): Miscellaneous controller */ - sysctl_misc_t misc; - /* No. 22 (0x58): Peripheral controller */ - sysctl_peri_t peri; - /* No. 23 (0x5c): SPI sleep controller */ - sysctl_spi_sleep_t spi_sleep; - /* No. 24 (0x60): Reset source status */ - sysctl_reset_status_t reset_status; - /* No. 25 (0x64): DMA handshake selector */ - sysctl_dma_sel0_t dma_sel0; - /* No. 26 (0x68): DMA handshake selector */ - sysctl_dma_sel1_t dma_sel1; - /* No. 27 (0x6c): IO Power Mode Select controller */ - sysctl_power_sel_t power_sel; - /* No. 28 (0x70): Reserved */ - uint32_t resv28; - /* No. 29 (0x74): Reserved */ - uint32_t resv29; - /* No. 30 (0x78): Reserved */ - uint32_t resv30; - /* No. 31 (0x7c): Reserved */ - uint32_t resv31; -} __attribute__((packed, aligned(4))) sysctl_t; - -/** - * @brief Abstruct PLL struct - */ -typedef struct _sysctl_general_pll -{ - uint32_t clkr : 4; - uint32_t clkf : 6; - uint32_t clkod : 4; - uint32_t bwadj : 6; - uint32_t pll_reset : 1; - uint32_t pll_pwrd : 1; - uint32_t pll_intfb : 1; - uint32_t pll_bypass : 1; - uint32_t pll_test : 1; - uint32_t pll_out_en : 1; - uint32_t pll_ckin_sel : 2; - uint32_t reserved : 4; -} __attribute__((packed, aligned(4))) sysctl_general_pll_t; - -/** - * @brief System controller object instanse - */ -extern volatile sysctl_t *const sysctl; - -/** - * @brief Enable clock for peripheral - * - * @param[in] clock The clock to be enable - * - * @return result - * - 0 Success - * - Other Fail - */ -int sysctl_clock_enable(sysctl_clock_t clock); - -/** - * @brief Enable clock for peripheral - * - * @param[in] clock The clock to be disable - * - * @return result - * - 0 Success - * - Other Fail - */ -int sysctl_clock_disable(sysctl_clock_t clock); - -/** - * @brief Sysctl clock set threshold - * - * @param[in] which Which threshold to set - * @param[in] threshold The threshold value - * - * @return result - * - 0 Success - * - Other Fail - */ -int sysctl_clock_set_threshold(sysctl_threshold_t which, int threshold); - -/** - * @brief Sysctl clock get threshold - * - * @param[in] which Which threshold to get - * - * @return The threshold value - * - Other Value of threshold - * - -1 Fail - */ -int sysctl_clock_get_threshold(sysctl_threshold_t which); - -/** - * @brief Sysctl clock set clock select - * - * @param[in] which Which clock select to set - * @param[in] select The clock select value - * - * @return result - * - 0 Success - * - Other Fail - */ -int sysctl_clock_set_clock_select(sysctl_clock_select_t which, int select); - -/** - * @brief Sysctl clock get clock select - * - * @param[in] which Which clock select to get - * - * @return The clock select value - * - Other Value of clock select - * - -1 Fail - */ -int sysctl_clock_get_clock_select(sysctl_clock_select_t which); - -/** - * @brief Get PLL frequency - * - * @param[in] pll The PLL id - * - * @return The frequency of PLL - */ -uint32_t sysctl_pll_get_freq(sysctl_pll_t pll); - -/** - * @brief Get base clock frequency by clock id - * - * @param[in] clock The clock id - * - * @return The clock frequency - */ -uint32_t sysctl_clock_get_freq(sysctl_clock_t clock); - -/** - * @brief Reset device by reset controller - * - * @param[in] reset The reset signal - */ -void sysctl_reset(sysctl_reset_t reset); - -/** - * @brief Enable the PLL and power on with reset - * - * @param[in] pll The pll id - * - * @return Result - * - 0 Success - * - Other Fail - */ -int sysctl_pll_enable(sysctl_pll_t pll); - -/** - * @brief Disable the PLL and power off - * - * @param[in] pll The pll id - * - * @return Result - * - 0 Success - * - Other Fail - */ -int sysctl_pll_disable(sysctl_pll_t pll); - -/** - * @brief Select DMA channel handshake peripheral signal - * - * @param[in] channel The DMA channel - * @param[in] select The peripheral select - * - * @return Result - * - 0 Success - * - Other Fail - */ -int sysctl_dma_select(sysctl_dma_channel_t channel, sysctl_dma_select_t select); - -/** - * @brief Set SPI0_D0-D7 DVP_D0-D7 as spi and dvp data pin - * - * @param[in] en Enable or not - * - * @return Result - * - 0 Success - * - Other Fail - */ -uint32_t sysctl_set_spi0_dvp_data(uint8_t en); - -/** - * @brief Set io power mode - * - * @param[in] power_bank IO power bank - * @param[in] io_power_mode Set power mode 3.3v or 1.8 - * - * @return Result - * - 0 Success - * - Other Fail - */ -void sysctl_set_power_mode(sysctl_power_bank_t power_bank, sysctl_io_power_mode_t io_power_mode); - -/** - * @brief get the frequency of CPU - * - * @return The frequency of CPU - */ -uint32_t sysctl_cpu_get_freq(void); - -/** - * @brief Set frequency of CPU - * @param[in] freq The desired frequency in Hz - * - * @return The actual frequency of CPU after set - */ -uint32_t sysctl_cpu_set_freq(uint32_t freq); - -/** - * @brief Init PLL freqency - * @param[in] pll The PLL id - * @param[in] pll_freq The desired frequency in Hz - - */ -uint32_t sysctl_pll_set_freq(sysctl_pll_t pll, uint32_t pll_freq); - -/** - * @brief Enable interrupt - */ -void sysctl_enable_irq(void); - -/** - * @brief Disable interrupt - */ -void sysctl_disable_irq(void); - -/** - * @brief Get the time start up to now - * - * @return The time of microsecond - */ -uint64_t sysctl_get_time_us(void); - -/** - * @brief Get reset status - * - * @return The status of reset - */ -sysctl_reset_enum_status_t sysctl_get_reset_status(void); - -#ifdef __cplusplus -} -#endif - -#endif /* _DRIVER_SYSCTL_H */ diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/timer.h b/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/timer.h deleted file mode 100644 index b7408b6..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/timer.h +++ /dev/null @@ -1,161 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef _DRIVER_TIMER_H -#define _DRIVER_TIMER_H - -#include -#include -#ifdef __cplusplus -extern "C" { -#endif - -/* clang-format off */ -typedef struct _timer_channel -{ - /* TIMER_N Load Count Register (0x00+(N-1)*0x14) */ - volatile uint32_t load_count; - /* TIMER_N Current Value Register (0x04+(N-1)*0x14) */ - volatile uint32_t current_value; - /* TIMER_N Control Register (0x08+(N-1)*0x14) */ - volatile uint32_t control; - /* TIMER_N Interrupt Clear Register (0x0c+(N-1)*0x14) */ - volatile uint32_t eoi; - /* TIMER_N Interrupt Status Register (0x10+(N-1)*0x14) */ - volatile uint32_t intr_stat; -} __attribute__((packed, aligned(4))) timer_channel_t; - -typedef struct _kendryte_timer -{ - /* TIMER_N Register (0x00-0x4c) */ - volatile timer_channel_t channel[4]; - /* reserverd (0x50-0x9c) */ - volatile uint32_t resv1[20]; - /* TIMER Interrupt Status Register (0xa0) */ - volatile uint32_t intr_stat; - /* TIMER Interrupt Clear Register (0xa4) */ - volatile uint32_t eoi; - /* TIMER Raw Interrupt Status Register (0xa8) */ - volatile uint32_t raw_intr_stat; - /* TIMER Component Version Register (0xac) */ - volatile uint32_t comp_version; - /* TIMER_N Load Count2 Register (0xb0-0xbc) */ - volatile uint32_t load_count2[4]; -} __attribute__((packed, aligned(4))) kendryte_timer_t; - -typedef enum _timer_deivce_number -{ - TIMER_DEVICE_0, - TIMER_DEVICE_1, - TIMER_DEVICE_2, - TIMER_DEVICE_MAX, -} timer_device_number_t; - -typedef enum _timer_channel_number -{ - TIMER_CHANNEL_0, - TIMER_CHANNEL_1, - TIMER_CHANNEL_2, - TIMER_CHANNEL_3, - TIMER_CHANNEL_MAX, -} timer_channel_number_t; - -/* TIMER Control Register */ -#define TIMER_CR_ENABLE 0x00000001 -#define TIMER_CR_MODE_MASK 0x00000002 -#define TIMER_CR_FREE_MODE 0x00000000 -#define TIMER_CR_USER_MODE 0x00000002 -#define TIMER_CR_INTERRUPT_MASK 0x00000004 -#define TIMER_CR_PWM_ENABLE 0x00000008 -/* clang-format on */ - -extern volatile kendryte_timer_t *const timer[3]; - -/** - * @brief Definitions for the timer callbacks - */ -typedef int (*timer_callback_t)(void *ctx); - -/** - * @brief Set timer timeout - * - * @param[in] timer timer - * @param[in] channel channel - * @param[in] nanoseconds timeout - * - * @return the real timeout - */ -size_t timer_set_interval(timer_device_number_t timer_number, timer_channel_number_t channel, size_t nanoseconds); - -/** - * @brief Init timer - * - * @param[in] timer timer - */ -void timer_init(timer_device_number_t timer_number); - -/** - * @brief [DEPRECATED] Set timer timeout function - * - * @param[in] timer timer - * @param[in] channel channel - * @param[in] func timeout function - * @param[in] priority interrupt priority - * - */ -void timer_set_irq(timer_device_number_t timer_number, timer_channel_number_t channel, void(*func)(), uint32_t priority); - -/** - * @brief Register timer interrupt user callback function - * - * @param[in] device The timer device number - * @param[in] channel The channel - * @param[in] is_one_shot Indicates if single shot - * @param[in] priority The priority - * @param[in] callback The callback function - * @param[in] ctx The context - * - * @return result - * - 0 Success - * - Other Fail - */ -int timer_irq_register(timer_device_number_t device, timer_channel_number_t channel, int is_single_shot, uint32_t priority, timer_callback_t callback, void *ctx); - -/** - * @brief Deregister timer interrupt user callback function - * - * @param[in] device The timer device number - * @param[in] channel The channel - * - * @return result - * - 0 Success - * - Other Fail - */ -int timer_irq_unregister(timer_device_number_t device, timer_channel_number_t channel); - -/** - * @brief Enable timer - * - * @param[in] timer timer - * @param[in] channel channel - * @param[in] enable Enable or disable - * - */ -void timer_set_enable(timer_device_number_t timer_number, timer_channel_number_t channel, uint32_t enable); - -#ifdef __cplusplus -} -#endif - -#endif /* _DRIVER_TIMER_H */ diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/uart.h b/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/uart.h deleted file mode 100644 index 945233b..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/uart.h +++ /dev/null @@ -1,334 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * 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. - */ - -/** - * @file - * @brief Universal Asynchronous Receiver/Transmitter (UART) - * - * The UART peripheral supports the following features: - * - * - 8-N-1 and 8-N-2 formats: 8 data bits, no parity bit, 1 start - * bit, 1 or 2 stop bits - * - * - 8-entry transmit and receive FIFO buffers with programmable - * watermark interrupts - * - * - 16× Rx oversampling with 2/3 majority voting per bit - * - * The UART peripheral does not support hardware flow control or - * other modem control signals, or synchronous serial data - * tranfesrs. - * - * - */ - -#ifndef _DRIVER_APBUART_H -#define _DRIVER_APBUART_H - -#include -#include "platform.h" -#include "plic.h" -#include "dmac.h" - -#ifdef __cplusplus -extern "C" { -#endif - -typedef enum _uart_dev -{ - UART_DEV1 = 0, - UART_DEV2, - UART_DEV3, -} uart_dev_t; - -typedef struct _uart -{ - union - { - volatile uint32_t RBR; - volatile uint32_t DLL; - volatile uint32_t THR; - }; - - union - { - volatile uint32_t DLH; - volatile uint32_t IER; - }; - - union - { - volatile uint32_t FCR; - volatile uint32_t IIR; - }; - - volatile uint32_t LCR; - volatile uint32_t MCR; - volatile uint32_t LSR; - volatile uint32_t MSR; - - volatile uint32_t SCR; - volatile uint32_t LPDLL; - volatile uint32_t LPDLH; - - volatile uint32_t reserved1[2]; - - union - { - volatile uint32_t SRBR[16]; - volatile uint32_t STHR[16]; - }; - - volatile uint32_t FAR; - volatile uint32_t TFR; - volatile uint32_t RFW; - volatile uint32_t USR; - volatile uint32_t TFL; - volatile uint32_t RFL; - volatile uint32_t SRR; - volatile uint32_t SRTS; - volatile uint32_t SBCR; - volatile uint32_t SDMAM; - volatile uint32_t SFE; - volatile uint32_t SRT; - volatile uint32_t STET; - volatile uint32_t HTX; - volatile uint32_t DMASA; - volatile uint32_t TCR; - volatile uint32_t DE_EN; - volatile uint32_t RE_EN; - volatile uint32_t DET; - volatile uint32_t TAT; - volatile uint32_t DLF; - volatile uint32_t RAR; - volatile uint32_t TAR; - volatile uint32_t LCR_EXT; - volatile uint32_t reserved2[9]; - volatile uint32_t CPR; - volatile uint32_t UCV; - volatile uint32_t CTR; -} uart_t; - -typedef enum _uart_device_number -{ - UART_DEVICE_1, - UART_DEVICE_2, - UART_DEVICE_3, - UART_DEVICE_MAX, -} uart_device_number_t; - -typedef enum _uart_bitwidth -{ - UART_BITWIDTH_5BIT = 5, - UART_BITWIDTH_6BIT, - UART_BITWIDTH_7BIT, - UART_BITWIDTH_8BIT, -} uart_bitwidth_t; - -typedef enum _uart_stopbit -{ - UART_STOP_1, - UART_STOP_1_5, - UART_STOP_2 -} uart_stopbit_t; - -typedef enum _uart_rede_sel -{ - DISABLE = 0, - ENABLE, -} uart_rede_sel_t; - -typedef enum _uart_parity -{ - UART_PARITY_NONE, - UART_PARITY_ODD, - UART_PARITY_EVEN -} uart_parity_t; - -typedef enum _uart_interrupt_mode -{ - UART_SEND = 1, - UART_RECEIVE = 2, -} uart_interrupt_mode_t; - -typedef enum _uart_send_trigger -{ - UART_SEND_FIFO_0, - UART_SEND_FIFO_2, - UART_SEND_FIFO_4, - UART_SEND_FIFO_8, -} uart_send_trigger_t; - -typedef enum _uart_receive_trigger -{ - UART_RECEIVE_FIFO_1, - UART_RECEIVE_FIFO_4, - UART_RECEIVE_FIFO_8, - UART_RECEIVE_FIFO_14, -} uart_receive_trigger_t; - -/** - * @brief Send data from uart - * - * @param[in] channel Uart index - * @param[in] buffer The data be transfer - * @param[in] len The data length - * - * @return Transfer length - */ -int uart_send_data(uart_device_number_t channel, const char *buffer, size_t buf_len); - -/** - * @brief Read data from uart - * - * @param[in] channel Uart index - * @param[in] buffer The Data received - * @param[in] len Receive length - * - * @return Receive length - */ -int uart_receive_data(uart_device_number_t channel, char *buffer, size_t buf_len); - -/** - * @brief Init uart - * - * @param[in] channel Uart index - * - */ -void uart_init(uart_device_number_t channel); - -/** - * @brief Set uart param - * - * @param[in] channel Uart index - * @param[in] baud_rate Baudrate - * @param[in] data_width Data width - * @param[in] stopbit Stop bit - * @param[in] parity Odd Even parity - * - */ -void uart_config(uart_device_number_t channel, uint32_t baud_rate, uart_bitwidth_t data_width, uart_stopbit_t stopbit, uart_parity_t parity); - -/** - * @brief Set uart param - * - * @param[in] channel Uart index - * @param[in] baud_rate Baudrate - * @param[in] data_width Data width - * @param[in] stopbit Stop bit - * @param[in] parity Odd Even parity - * - */ -void uart_configure(uart_device_number_t channel, uint32_t baud_rate, uart_bitwidth_t data_width, uart_stopbit_t stopbit, uart_parity_t parity); - -/** - * @brief Register uart interrupt - * - * @param[in] channel Uart index - * @param[in] interrupt_mode Interrupt Mode receive or send - * @param[in] uart_callback Call back - * @param[in] ctx Param of call back - * @param[in] priority Interrupt priority - * - */ -void uart_irq_register(uart_device_number_t channel, uart_interrupt_mode_t interrupt_mode, plic_irq_callback_t uart_callback, void *ctx, uint32_t priority); - -/** - * @brief Deregister uart interrupt - * - * @param[in] channel Uart index - * @param[in] interrupt_mode Interrupt Mode receive or send - * - */ -void uart_irq_unregister(uart_device_number_t channel, uart_interrupt_mode_t interrupt_mode); - -/** - * @brief Set send interrupt threshold - * - * @param[in] channel Uart index - * @param[in] trigger Threshold of send interrupt - * - */ -void uart_set_send_trigger(uart_device_number_t channel, uart_send_trigger_t trigger); - -/** - * @brief Set receive interrupt threshold - * - * @param[in] channel Uart index - * @param[in] trigger Threshold of receive interrupt - * - */ -void uart_set_receive_trigger(uart_device_number_t channel, uart_receive_trigger_t trigger); - -/** - * @brief Send data by dma - * - * @param[in] channel Uart index - * @param[in] dmac_channel Dmac channel - * @param[in] buffer Send data - * @param[in] buf_len Data length - * - */ -void uart_send_data_dma(uart_device_number_t uart_channel, dmac_channel_number_t dmac_channel, const uint8_t *buffer, size_t buf_len); - -/** - * @brief Receive data by dma - * - * @param[in] channel Uart index - * @param[in] dmac_channel Dmac channel - * @param[in] buffer Receive data - * @param[in] buf_len Data length - * - */ -void uart_receive_data_dma(uart_device_number_t uart_channel, dmac_channel_number_t dmac_channel, uint8_t *buffer, size_t buf_len); - - -/** - * @brief Send data by dma - * - * @param[in] uart_channel Uart index - * @param[in] dmac_channel Dmac channel - * @param[in] buffer Send data - * @param[in] buf_len Data length - * @param[in] uart_callback Call back - * @param[in] ctx Param of call back - * @param[in] priority Interrupt priority - * - */ -void uart_send_data_dma_irq(uart_device_number_t uart_channel, dmac_channel_number_t dmac_channel, - const uint8_t *buffer, size_t buf_len, plic_irq_callback_t uart_callback, - void *ctx, uint32_t priority); - -/** - * @brief Receive data by dma - * - * @param[in] uart_channel Uart index - * @param[in] dmac_channel Dmac channel - * @param[in] buffer Receive data - * @param[in] buf_len Data length - * @param[in] uart_callback Call back - * @param[in] ctx Param of call back - * @param[in] priority Interrupt priority - * - */ -void uart_receive_data_dma_irq(uart_device_number_t uart_channel, dmac_channel_number_t dmac_channel, - uint8_t *buffer, size_t buf_len, plic_irq_callback_t uart_callback, - void *ctx, uint32_t priority); - -#ifdef __cplusplus -} -#endif - -#endif /* _DRIVER_APBUART_H */ diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/uarths.h b/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/uarths.h deleted file mode 100644 index 3421421..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/uarths.h +++ /dev/null @@ -1,292 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * 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. - */ - -/** - * @file - * @brief Universal Asynchronous Receiver/Transmitter (UART) - * - * The UART peripheral supports the following features: - * - * - 8-N-1 and 8-N-2 formats: 8 data bits, no parity bit, 1 start - * bit, 1 or 2 stop bits - * - * - 8-entry transmit and receive FIFO buffers with programmable - * watermark interrupts - * - * - 16× Rx oversampling with 2/3 majority voting per bit - * - * The UART peripheral does not support hardware flow control or - * other modem control signals, or synchronous serial data - * tranfesrs. - * - * @note UART RAM Layout - * - * | Address | Name | Description | - * |-----------|----------|---------------------------------| - * | 0x000 | txdata | Transmit data register | - * | 0x004 | rxdata | Receive data register | - * | 0x008 | txctrl | Transmit control register | - * | 0x00C | rxctrl | Receive control register | - * | 0x010 | ie | UART interrupt enable | - * | 0x014 | ip | UART Interrupt pending | - * | 0x018 | div | Baud rate divisor | - * - */ - -#ifndef _DRIVER_UARTHS_H -#define _DRIVER_UARTHS_H - -#include -#include "platform.h" -#include "plic.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/* clang-format off */ -/* Register address offsets */ -#define UARTHS_REG_TXFIFO (0x00) -#define UARTHS_REG_RXFIFO (0x04) -#define UARTHS_REG_TXCTRL (0x08) -#define UARTHS_REG_RXCTRL (0x0c) -#define UARTHS_REG_IE (0x10) -#define UARTHS_REG_IP (0x14) -#define UARTHS_REG_DIV (0x18) - -/* TXCTRL register */ -#define UARTHS_TXEN (0x01) -#define UARTHS_TXWM(x) (((x) & 0xffff) << 16) - -/* RXCTRL register */ -#define UARTHS_RXEN (0x01) -#define UARTHS_RXWM(x) (((x) & 0xffff) << 16) - -/* IP register */ -#define UARTHS_IP_TXWM (0x01) -#define UARTHS_IP_RXWM (0x02) -/* clang-format on */ - -typedef struct _uarths_txdata -{ - /* Bits [7:0] is data */ - uint32_t data : 8; - /* Bits [30:8] is 0 */ - uint32_t zero : 23; - /* Bit 31 is full status */ - uint32_t full : 1; -} __attribute__((packed, aligned(4))) uarths_txdata_t; - -typedef struct _uarths_rxdata -{ - /* Bits [7:0] is data */ - uint32_t data : 8; - /* Bits [30:8] is 0 */ - uint32_t zero : 23; - /* Bit 31 is empty status */ - uint32_t empty : 1; -} __attribute__((packed, aligned(4))) uarths_rxdata_t; - -typedef struct _uarths_txctrl -{ - /* Bit 0 is txen, controls whether the Tx channel is active. */ - uint32_t txen : 1; - /* Bit 1 is nstop, 0 for one stop bit and 1 for two stop bits */ - uint32_t nstop : 1; - /* Bits [15:2] is reserved */ - uint32_t resv0 : 14; - /* Bits [18:16] is threshold of interrupt triggers */ - uint32_t txcnt : 3; - /* Bits [31:19] is reserved */ - uint32_t resv1 : 13; -} __attribute__((packed, aligned(4))) uarths_txctrl_t; - -typedef struct _uarths_rxctrl -{ - /* Bit 0 is txen, controls whether the Tx channel is active. */ - uint32_t rxen : 1; - /* Bits [15:1] is reserved */ - uint32_t resv0 : 15; - /* Bits [18:16] is threshold of interrupt triggers */ - uint32_t rxcnt : 3; - /* Bits [31:19] is reserved */ - uint32_t resv1 : 13; -} __attribute__((packed, aligned(4))) uarths_rxctrl_t; - -typedef struct _uarths_ip -{ - /* Bit 0 is txwm, raised less than txcnt */ - uint32_t txwm : 1; - /* Bit 1 is txwm, raised greater than rxcnt */ - uint32_t rxwm : 1; - /* Bits [31:2] is 0 */ - uint32_t zero : 30; -} __attribute__((packed, aligned(4))) uarths_ip_t; - -typedef struct _uarths_ie -{ - /* Bit 0 is txwm, raised less than txcnt */ - uint32_t txwm : 1; - /* Bit 1 is txwm, raised greater than rxcnt */ - uint32_t rxwm : 1; - /* Bits [31:2] is 0 */ - uint32_t zero : 30; -} __attribute__((packed, aligned(4))) uarths_ie_t; - -typedef struct _uarths_div -{ - /* Bits [31:2] is baud rate divisor register */ - uint32_t div : 16; - /* Bits [31:16] is 0 */ - uint32_t zero : 16; -} __attribute__((packed, aligned(4))) uarths_div_t; - -typedef struct _uarths -{ - /* Address offset 0x00 */ - uarths_txdata_t txdata; - /* Address offset 0x04 */ - uarths_rxdata_t rxdata; - /* Address offset 0x08 */ - uarths_txctrl_t txctrl; - /* Address offset 0x0c */ - uarths_rxctrl_t rxctrl; - /* Address offset 0x10 */ - uarths_ie_t ie; - /* Address offset 0x14 */ - uarths_ip_t ip; - /* Address offset 0x18 */ - uarths_div_t div; -} __attribute__((packed, aligned(4))) uarths_t; - -typedef enum _uarths_interrupt_mode -{ - UARTHS_SEND = 1, - UARTHS_RECEIVE = 2, - UARTHS_SEND_RECEIVE = 3, -} uarths_interrupt_mode_t; - -typedef enum _uarths_stopbit -{ - UARTHS_STOP_1, - UARTHS_STOP_2 -} uarths_stopbit_t; - -extern volatile uarths_t *const uarths; - -/** - * @brief Initialization Core UART - * - * @return result - * - 0 Success - * - Other Fail - */ -void uarths_init(void); - -/** - * @brief Put a char to UART - * - * @param[in] c The char to put - * - * @note If c is '\n', a '\r' will be appended automatically - * - * @return result - * - 0 Success - * - Other Fail - */ -int uarths_putchar(char c); - -/** - * @brief Send a string to UART - * - * @param[in] s The string to send - * - * @note The string must ending with '\0' - * - * @return result - * - 0 Success - * - Other Fail - */ -int uarths_puts(const char *s); - - -/** - * @brief Get a byte from UART - * - * @return byte as int type from UART - */ -int uarths_getc(void); - -/** - * @brief Set uarths interrupt callback - * - * @param[in] interrupt_mode Interrupt mode recevice or send - * @param[in] uarths_callback Interrupt callback - * @param[in] ctx Param of callback - * @param[in] priority Interrupt priority - * - */ -void uarths_set_irq(uarths_interrupt_mode_t interrupt_mode, plic_irq_callback_t uarths_callback, void *ctx, uint32_t priority); - -/** - * @brief Uarths receive data - * - * @param[in] buf The data received - * @param[in] buf_len The length of data - * - * @return Number of received data - */ -size_t uarths_receive_data(uint8_t *buf, size_t buf_len); - -/** - * @brief Uarths receive data - * - * @param[in] buf The data sended - * @param[in] buf_len The length of data - * - * @return Number of sended data - */ -size_t uarths_send_data(const uint8_t *buf, size_t buf_len); - -/** - * @brief Get interrupt mode - * - * @return Mode of interrupt - */ -uarths_interrupt_mode_t uarths_get_interrupt_mode(void); - -/** - * @brief Set uarths baud rate and stopbit - * - * @param[in] baud_rate The baud rate - * @param[in] stopbit The stopbit of data - * - */ -void uarths_config(uint32_t baud_rate, uarths_stopbit_t stopbit); - -/** - * @brief Set uart interrupt condition - * - * @param[in] interrupt_mode The interrupt mode - * @param[in] cnt The count of tigger - * - */ -void uarths_set_interrupt_cnt(uarths_interrupt_mode_t interrupt_mode, uint8_t cnt); - -#ifdef __cplusplus -} -#endif - -#endif /* _DRIVER_UARTHS_H */ diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/utils.h b/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/utils.h deleted file mode 100644 index 69d2f8d..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/utils.h +++ /dev/null @@ -1,347 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef _DRIVER_UTILS_H -#define _DRIVER_UTILS_H - -#ifdef __cplusplus -#include -#include -#include -#else /* __cplusplus */ -#include -#include -#include -#include -#endif /* __cplusplus */ - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -#define KENDRYTE_MIN(a, b) ((a) > (b) ? (b) : (a)) -#define KENDRYTE_MAX(a, b) ((a) > (b) ? (a) : (b)) - -#ifdef __ASSEMBLY__ -#define KENDRYTE_CAST(type, ptr) ptr -#else /* __ASSEMBLY__ */ -/** - * @brief Cast the pointer to specified pointer type. - * - * @param[in] type The pointer type to cast to - * @param[in] ptr The pointer to apply the type cast to - */ -#define KENDRYTE_CAST(type, ptr) ((type)(ptr)) -#endif /* __ASSEMBLY__ */ - -/** - * @addtogroup UTIL_RW_FUNC Memory Read/Write Utilities - * - * This section implements read and write functionality for various - * memory untis. The memory unit terms used for these functions are - * consistent with those used in the ARM Architecture Reference Manual - * ARMv7-A and ARMv7-R edition manual. The terms used for units of memory are: - * - * Unit of Memory | Abbreviation | Size in Bits - * :---------------|:-------------|:------------: - * Byte | byte | 8 - * Half Word | hword | 16 - * Word | word | 32 - * Double Word | dword | 64 - * - */ - -/** - * @brief Write the 8 bit byte to the destination address in device memory. - * - * @param[in] dest Write destination pointer address - * @param[in] src 8 bit data byte to write to memory - */ -#define kendryte_write_byte(dest, src) \ - (*KENDRYTE_CAST(volatile uint8_t*, (dest)) = (src)) - -/** - * @brief Read and return the 8 bit byte from the source address in device memory. - * - * @param[in] src Read source pointer address - * - * @return 8 bit data byte value - */ -#define kendryte_read_byte(src) (*KENDRYTE_CAST(volatile uint8_t*, (src))) - -/** - * @brief Write the 16 bit half word to the destination address in device memory. - * - * @param[in] dest Write destination pointer address - * @param[in] src 16 bit data half word to write to memory - */ -#define kendryte_write_hword(dest, src) \ - (*KENDRYTE_CAST(volatile uint16_t*, (dest)) = (src)) - -/** - * @brief Read and return the 16 bit half word from the source address in device - * - * @param[in] src Read source pointer address - * - * @return 16 bit data half word value - */ -#define kendryte_read_hword(src) (*KENDRYTE_CAST(volatile uint16_t*, (src))) - -/** - * @brief Write the 32 bit word to the destination address in device memory. - * - * @param[in] dest Write destination pointer address - * @param[in] src 32 bit data word to write to memory - */ -#define kendryte_write_word(dest, src) \ - (*KENDRYTE_CAST(volatile uint32_t*, (dest)) = (src)) - -/** - * @brief Read and return the 32 bit word from the source address in device memory. - * - * @param[in] src Read source pointer address - * - * @return 32 bit data half word value - */ -#define kendryte_read_word(src) (*KENDRYTE_CAST(volatile uint32_t*, (src))) - -/** - * @brief Write the 64 bit double word to the destination address in device memory. - * - * @param[in] dest Write destination pointer address - * @param[in] src 64 bit data word to write to memory - */ -#define kendryte_write_dword(dest, src) \ - (*KENDRYTE_CAST(volatile uint64_t*, (dest)) = (src)) - -/** - * @brief Read and return the 64 bit double word from the source address in device - * - * @param[in] src Read source pointer address - * - * @return 64 bit data half word value - */ -#define kendryte_read_dword(src) (*KENDRYTE_CAST(volatile uint64_t*, (src))) - -/** - * @brief Set selected bits in the 8 bit byte at the destination address in device - * - * @param[in] dest Destination pointer address - * @param[in] bits Bits to set in destination byte - */ -#define kendryte_setbits_byte(dest, bits) \ - (kendryte_write_byte(dest, kendryte_read_byte(dest) | (bits))) - -/** - * @brief Clear selected bits in the 8 bit byte at the destination address in device - * - * @param[in] dest Destination pointer address - * @param[in] bits Bits to clear in destination byte - */ -#define kendryte_clrbits_byte(dest, bits) \ - (kendryte_write_byte(dest, kendryte_read_byte(dest) & ~(bits))) - -/** - * @brief Change or toggle selected bits in the 8 bit byte at the destination address - * - * @param[in] dest Destination pointer address - * @param[in] bits Bits to change in destination byte - */ -#define kendryte_xorbits_byte(dest, bits) \ - (kendryte_write_byte(dest, kendryte_read_byte(dest) ^ (bits))) - -/** - * @brief Replace selected bits in the 8 bit byte at the destination address in device - * - * @param[in] dest Destination pointer address - * @param[in] msk Bits to replace in destination byte - * @param[in] src Source bits to write to cleared bits in destination byte - */ -#define kendryte_replbits_byte(dest, msk, src) \ - (kendryte_write_byte(dest, (kendryte_read_byte(dest) & ~(msk)) | ((src) & (msk)))) - -/** - * @brief Set selected bits in the 16 bit halfword at the destination address in - * - * @param[in] dest Destination pointer address - * @param[in] bits Bits to set in destination halfword - */ -#define kendryte_setbits_hword(dest, bits) \ - (kendryte_write_hword(dest, kendryte_read_hword(dest) | (bits))) - -/** - * @brief Clear selected bits in the 16 bit halfword at the destination address in - * - * @param[in] dest Destination pointer address - * @param[in] bits Bits to clear in destination halfword - */ -#define kendryte_clrbits_hword(dest, bits) \ - (kendryte_write_hword(dest, kendryte_read_hword(dest) & ~(bits))) - -/** - * @brief Change or toggle selected bits in the 16 bit halfword at the destination - * - * @param[in] dest Destination pointer address - * @param[in] bits Bits to change in destination halfword - */ -#define kendryte_xorbits_hword(dest, bits) \ - (kendryte_write_hword(dest, kendryte_read_hword(dest) ^ (bits))) - -/** - * @brief Replace selected bits in the 16 bit halfword at the destination address in - * - * @param[in] dest Destination pointer address - * @param[in] msk Bits to replace in destination byte - * @param[in] src Source bits to write to cleared bits in destination halfword - */ -#define kendryte_replbits_hword(dest, msk, src) \ - (kendryte_write_hword(dest, (kendryte_read_hword(dest) & ~(msk)) | ((src) & (msk)))) - -/** - * @brief Set selected bits in the 32 bit word at the destination address in device - * - * @param[in] dest Destination pointer address - * @param[in] bits Bits to set in destination word - */ -#define kendryte_setbits_word(dest, bits) \ - (kendryte_write_word(dest, kendryte_read_word(dest) | (bits))) - -/** - * @brief Clear selected bits in the 32 bit word at the destination address in device - * - * @param[in] dest Destination pointer address - * @param[in] bits Bits to clear in destination word - */ -#define kendryte_clrbits_word(dest, bits) \ - (kendryte_write_word(dest, kendryte_read_word(dest) & ~(bits))) - -/** - * @brief Change or toggle selected bits in the 32 bit word at the destination address - * - * @param[in] dest Destination pointer address - * @param[in] bits Bits to change in destination word - */ -#define kendryte_xorbits_word(dest, bits) \ - (kendryte_write_word(dest, kendryte_read_word(dest) ^ (bits))) - -/** - * @brief Replace selected bits in the 32 bit word at the destination address in - * - * @param[in] dest Destination pointer address - * @param[in] msk Bits to replace in destination word - * @param[in] src Source bits to write to cleared bits in destination word - */ -#define kendryte_replbits_word(dest, msk, src) \ - (kendryte_write_word(dest, (kendryte_read_word(dest) & ~(msk)) | ((src) & (msk)))) - -/** - * @brief Set selected bits in the 64 bit doubleword at the destination address in - * - * @param[in] dest Destination pointer address - * @param[in] bits Bits to set in destination doubleword - */ -#define kendryte_setbits_dword(dest, bits) \ - (kendryte_write_dword(dest, kendryte_read_dword(dest) | (bits))) - -/** - * @brief Clear selected bits in the 64 bit doubleword at the destination address in - * - * @param[in] dest Destination pointer address - * @param[in] bits Bits to clear in destination doubleword - */ -#define kendryte_clrbits_dword(dest, bits) \ - (kendryte_write_dword(dest, kendryte_read_dword(dest) & ~(bits))) - -/** - * @brief Change or toggle selected bits in the 64 bit doubleword at the destination - * - * @param[in] dest Destination pointer address - * @param[in] bits Bits to change in destination doubleword - */ -#define kendryte_xorbits_dword(dest, bits) \ - (kendryte_write_dword(dest, kendryte_read_dword(dest) ^ (bits))) - -/** - * @brief Replace selected bits in the 64 bit doubleword at the destination address in - * - * @param[in] dest Destination pointer address - * @param[in] msk its to replace in destination doubleword - * @param[in] src Source bits to write to cleared bits in destination word - */ -#define kendryte_replbits_dword(dest, msk, src) \ - (kendryte_write_dword(dest, (kendryte_read_dword(dest) & ~(msk)) | ((src) & (msk)))) - -#define configASSERT(x) \ - if ((x) == 0) \ - { \ - printf("(%s:%d) %s\r\n", __FILE__, __LINE__, #x); \ - for (;;) \ - ; \ - } - -/** - * @brief Set value by mask - * - * @param[in] bits The one be set - * @param[in] mask mask value - * @param[in] value The value to set - */ -void set_bit(volatile uint32_t *bits, uint32_t mask, uint32_t value); - -/** - * @brief Set value by mask - * - * @param[in] bits The one be set - * @param[in] mask Mask value - * @param[in] offset Mask's offset - * @param[in] value The value to set - */ -void set_bit_offset(volatile uint32_t *bits, uint32_t mask, size_t offset, uint32_t value); - -/** - * @brief Set bit for gpio, only set one bit - * - * @param[in] bits The one be set - * @param[in] idx Offset value - * @param[in] value The value to set - */ -void set_gpio_bit(volatile uint32_t *bits, size_t idx, uint32_t value); - -/** - * @brief Get bits value of mask - * - * @param[in] bits The source data - * @param[in] mask Mask value - * @param[in] offset Mask's offset - * - * @return The bits value of mask - */ -uint32_t get_bit(volatile uint32_t *bits, uint32_t mask, size_t offset); - -/** - * @brief Get a bit value by offset - * - * @param[in] bits The source data - * @param[in] offset Bit's offset - * - * - * @return The bit value - */ -uint32_t get_gpio_bit(volatile uint32_t *bits, size_t offset); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ -#endif /* _DRIVER_COMMON_H */ - diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/wdt.h b/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/wdt.h deleted file mode 100644 index f6e1bd6..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/include/wdt.h +++ /dev/null @@ -1,170 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef _DRIVER_WDT_H -#define _DRIVER_WDT_H - -#include -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/* clang-format off */ -typedef struct _wdt -{ - /* WDT Control Register (0x00) */ - volatile uint32_t cr; - /* WDT Timeout Range Register (0x04) */ - volatile uint32_t torr; - /* WDT Current Counter Value Register (0x08) */ - volatile uint32_t ccvr; - /* WDT Counter Restart Register (0x0c) */ - volatile uint32_t crr; - /* WDT Interrupt Status Register (0x10) */ - volatile uint32_t stat; - /* WDT Interrupt Clear Register (0x14) */ - volatile uint32_t eoi; - /* reserverd (0x18) */ - volatile uint32_t resv1; - /* WDT Protection level Register (0x1c) */ - volatile uint32_t prot_level; - /* reserved (0x20-0xe0) */ - volatile uint32_t resv4[49]; - /* WDT Component Parameters Register 5 (0xe4) */ - volatile uint32_t comp_param_5; - /* WDT Component Parameters Register 4 (0xe8) */ - volatile uint32_t comp_param_4; - /* WDT Component Parameters Register 3 (0xec) */ - volatile uint32_t comp_param_3; - /* WDT Component Parameters Register 2 (0xf0) */ - volatile uint32_t comp_param_2; - /* WDT Component Parameters Register 1 (0xf4) */ - volatile uint32_t comp_param_1; - /* WDT Component Version Register (0xf8) */ - volatile uint32_t comp_version; - /* WDT Component Type Register (0xfc) */ - volatile uint32_t comp_type; -} __attribute__((packed, aligned(4))) wdt_t; - -typedef enum _wdt_device_number -{ - WDT_DEVICE_0, - WDT_DEVICE_1, - WDT_DEVICE_MAX, -} wdt_device_number_t; - - -#define WDT_RESET_ALL 0x00000000U -#define WDT_RESET_CPU 0x00000001U - -/* WDT Control Register */ -#define WDT_CR_ENABLE 0x00000001U -#define WDT_CR_RMOD_MASK 0x00000002U -#define WDT_CR_RMOD_RESET 0x00000000U -#define WDT_CR_RMOD_INTERRUPT 0x00000002U -#define WDT_CR_RPL_MASK 0x0000001CU -#define WDT_CR_RPL(x) ((x) << 2) -/* WDT Timeout Range Register */ -#define WDT_TORR_TOP_MASK 0x000000FFU -#define WDT_TORR_TOP(x) ((x) << 4 | (x) << 0) -/* WDT Current Counter Value Register */ -#define WDT_CCVR_MASK 0xFFFFFFFFU -/* WDT Counter Restart Register */ -#define WDT_CRR_MASK 0x00000076U -/* WDT Interrupt Status Register */ -#define WDT_STAT_MASK 0x00000001U -/* WDT Interrupt Clear Register */ -#define WDT_EOI_MASK 0x00000001U -/* WDT Protection level Register */ -#define WDT_PROT_LEVEL_MASK 0x00000007U -/* WDT Component Parameter Register 5 */ -#define WDT_COMP_PARAM_5_CP_WDT_USER_TOP_MAX_MASK 0xFFFFFFFFU -/* WDT Component Parameter Register 4 */ -#define WDT_COMP_PARAM_4_CP_WDT_USER_TOP_INIT_MAX_MASK 0xFFFFFFFFU -/* WDT Component Parameter Register 3 */ -#define WDT_COMP_PARAM_3_CD_WDT_TOP_RST_MASK 0xFFFFFFFFU -/* WDT Component Parameter Register 2 */ -#define WDT_COMP_PARAM_3_CP_WDT_CNT_RST_MASK 0xFFFFFFFFU -/* WDT Component Parameter Register 1 */ -#define WDT_COMP_PARAM_1_WDT_ALWAYS_EN_MASK 0x00000001U -#define WDT_COMP_PARAM_1_WDT_DFLT_RMOD_MASK 0x00000002U -#define WDT_COMP_PARAM_1_WDT_DUAL_TOP_MASK 0x00000004U -#define WDT_COMP_PARAM_1_WDT_HC_RMOD_MASK 0x00000008U -#define WDT_COMP_PARAM_1_WDT_HC_RPL_MASK 0x00000010U -#define WDT_COMP_PARAM_1_WDT_HC_TOP_MASK 0x00000020U -#define WDT_COMP_PARAM_1_WDT_USE_FIX_TOP_MASK 0x00000040U -#define WDT_COMP_PARAM_1_WDT_PAUSE_MASK 0x00000080U -#define WDT_COMP_PARAM_1_APB_DATA_WIDTH_MASK 0x00000300U -#define WDT_COMP_PARAM_1_WDT_DFLT_RPL_MASK 0x00001C00U -#define WDT_COMP_PARAM_1_WDT_DFLT_TOP_MASK 0x000F0000U -#define WDT_COMP_PARAM_1_WDT_DFLT_TOP_INIT_MASK 0x00F00000U -#define WDT_COMP_PARAM_1_WDT_CNT_WIDTH_MASK 0x1F000000U -/* WDT Component Version Register */ -#define WDT_COMP_VERSION_MASK 0xFFFFFFFFU -/* WDT Component Type Register */ -#define WDT_COMP_TYPE_MASK 0xFFFFFFFFU -/* clang-format on */ - -/** - * @brief Feed wdt - */ -void wdt_feed(wdt_device_number_t id); - -/** - * @brief Start wdt - * - * @param[in] id Wdt id 0 or 1 - * @param[in] time_out_ms Wdt trigger time - * @param[in] on_irq Wdt interrupt callback - * - */ -void wdt_start(wdt_device_number_t id, uint64_t time_out_ms, plic_irq_callback_t on_irq); - -/** - * @brief Start wdt - * - * @param[in] id Wdt id 0 or 1 - * @param[in] time_out_ms Wdt trigger time - * @param[in] on_irq Wdt interrupt callback - * @param[in] ctx Param of callback - * - * @return Wdt time - * - */ -uint32_t wdt_init(wdt_device_number_t id, uint64_t time_out_ms, plic_irq_callback_t on_irq, void *ctx); - -/** - * @brief Stop wdt - * - * @param[in] id Wdt id 0 or 1 - * - */ -void wdt_stop(wdt_device_number_t id); - -/** - * @brief Clear wdt interrupt - * - * @param[in] id Wdt id 0 or 1 - * - */ -void wdt_clear_interrupt(wdt_device_number_t id); - -#ifdef __cplusplus -} -#endif - -#endif /* _DRIVER_WDT_H */ diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/kpu.c b/cores/arduino/kendryte-standalone-sdk/lib/drivers/kpu.c deleted file mode 100644 index 8207293..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/kpu.c +++ /dev/null @@ -1,1521 +0,0 @@ -#include "kpu.h" -#include -#include -#include -#include -#include -#include "printf.h" -#include "dmac.h" -#include -#include "bsp.h" -#include -#include - -#define LAYER_BURST_SIZE 12 - -volatile kpu_config_t *const kpu = (volatile kpu_config_t *)AI_BASE_ADDR; -static volatile uint32_t kpu_status; - -typedef struct kpu_context -{ - kpu_task_t kpu_task; - uint32_t kpu_status; -} kpu_context_t; - -volatile kpu_context_t g_kpu_context; - -static int kpu_run_all_done(void* _task) -{ - atomic_swap(&g_kpu_context.kpu_status, 0); - kpu_task_t* task = (kpu_task_t*)_task; - task->callback(task); - return 0; -} - -int kpu_continue(void* _task) -{ - kpu_task_t* task = (kpu_task_t*)_task; - int layer_burst_size = 1; - - kpu->interrupt_clear.data = (kpu_config_interrupt_t) - { - .calc_done_int=1, - .layer_cfg_almost_empty_int=1, - .layer_cfg_almost_full_int=1 - }; - - if(task->remain_layers_length == 0) - { - return 0; - } - if(task->remain_layers_length <= layer_burst_size) - { - for(uint32_t i=0; iremain_layers_length; i++) - { - kpu->layer_argument_fifo = task->remain_layers[i].interrupt_enabe.reg; - kpu->layer_argument_fifo = task->remain_layers[i].image_addr.reg; - kpu->layer_argument_fifo = task->remain_layers[i].image_channel_num.reg; - kpu->layer_argument_fifo = task->remain_layers[i].image_size.reg; - kpu->layer_argument_fifo = task->remain_layers[i].kernel_pool_type_cfg.reg; - kpu->layer_argument_fifo = task->remain_layers[i].kernel_load_cfg.reg; - kpu->layer_argument_fifo = task->remain_layers[i].kernel_offset.reg; - kpu->layer_argument_fifo = task->remain_layers[i].kernel_calc_type_cfg.reg; - kpu->layer_argument_fifo = task->remain_layers[i].write_back_cfg.reg; - kpu->layer_argument_fifo = task->remain_layers[i].conv_value.reg; - kpu->layer_argument_fifo = task->remain_layers[i].conv_value2.reg; - kpu->layer_argument_fifo = task->remain_layers[i].dma_parameter.reg; - } - task->remain_layers_length = 0; - } - else - { - for(uint32_t i=0; ilayer_argument_fifo = task->remain_layers[i].interrupt_enabe.reg; - kpu->layer_argument_fifo = task->remain_layers[i].image_addr.reg; - kpu->layer_argument_fifo = task->remain_layers[i].image_channel_num.reg; - kpu->layer_argument_fifo = task->remain_layers[i].image_size.reg; - kpu->layer_argument_fifo = task->remain_layers[i].kernel_pool_type_cfg.reg; - kpu->layer_argument_fifo = task->remain_layers[i].kernel_load_cfg.reg; - kpu->layer_argument_fifo = task->remain_layers[i].kernel_offset.reg; - kpu->layer_argument_fifo = task->remain_layers[i].kernel_calc_type_cfg.reg; - kpu->layer_argument_fifo = task->remain_layers[i].write_back_cfg.reg; - kpu->layer_argument_fifo = task->remain_layers[i].conv_value.reg; - kpu->layer_argument_fifo = task->remain_layers[i].conv_value2.reg; - kpu->layer_argument_fifo = task->remain_layers[i].dma_parameter.reg; - } - task->remain_layers += layer_burst_size; - task->remain_layers_length -= layer_burst_size; - } - return 0; -} - -static int kpu_run_dma_output(uint32_t dma_ch, void* dst, uint32_t length, plic_irq_callback_t cb, void* _task) -{ - sysctl_dma_select(dma_ch, SYSCTL_DMA_SELECT_AI_RX_REQ); - dmac_irq_register(dma_ch, kpu_run_all_done, _task, 1); - dmac_set_single_mode(dma_ch, (void *)(&kpu->fifo_data_out), (void *)(dst), DMAC_ADDR_NOCHANGE, DMAC_ADDR_INCREMENT, - DMAC_MSIZE_8, DMAC_TRANS_WIDTH_64, (length+7)/8); - return 0; -} - -static int kpu_run_dma_input_done_push_layers(void* _task) -{ - kpu_task_t* task = (kpu_task_t*)_task; - kpu->interrupt_clear.reg = 7; - dmac->channel[task->dma_ch].intclear = 0xFFFFFFFF; - kpu->fifo_threshold.data = (kpu_config_fifo_threshold_t) - { - .fifo_full_threshold = 10, .fifo_empty_threshold=1 - }; - kpu->eight_bit_mode.data = (kpu_config_eight_bit_mode_t) - { - .eight_bit_mode=task->eight_bit_mode - }; - - kpu_layer_argument_t* last_layer = &task->layers[task->layers_length-1]; - - kpu_run_dma_output(task->dma_ch, task->dst, last_layer->dma_parameter.data.dma_total_byte+1, kpu_run_all_done, task); - - kpu->interrupt_mask.data = (kpu_config_interrupt_t) - { - .calc_done_int=0, - .layer_cfg_almost_empty_int=0, - .layer_cfg_almost_full_int=1 - }; - kpu_continue(task); - return 0; -} - -static void kpu_run_dma_input(uint32_t dma_ch, const void* src, plic_irq_callback_t cb, void* _task) -{ - kpu_task_t* task = _task; - kpu_layer_argument_t* first_layer = &task->layers[0]; - uint64_t input_size = first_layer->kernel_calc_type_cfg.data.channel_switch_addr * 64 * (first_layer->image_channel_num.data.i_ch_num+1); - dmac_irq_register(dma_ch, cb, _task, 1); - dmac_set_single_mode(dma_ch, (void *)src, (void *)(AI_IO_BASE_ADDR), DMAC_ADDR_INCREMENT, DMAC_ADDR_INCREMENT, - DMAC_MSIZE_16, DMAC_TRANS_WIDTH_64, input_size / 8); -} - -int kpu_run(kpu_task_t* v_task, dmac_channel_number_t dma_ch, const void *src, void* dest, plic_irq_callback_t callback) -{ - if(atomic_cas(&g_kpu_context.kpu_status, 0, 1)) - return -1; - - memcpy((void *)&g_kpu_context.kpu_task, v_task, sizeof(kpu_task_t)); - kpu_task_t *task = (kpu_task_t *)&g_kpu_context.kpu_task; - - kpu_layer_argument_t* last_layer = &task->layers[task->layers_length-1]; - - uint64_t output_size = last_layer->dma_parameter.data.dma_total_byte+1; - - last_layer->dma_parameter.data.send_data_out = 1; - last_layer->interrupt_enabe.data.int_en = 1; - - task->dma_ch = dma_ch; - task->dst = dest; - task->dst_length = output_size; - task->callback = callback; - task->remain_layers_length = task->layers_length; - task->remain_layers = task->layers; - - plic_irq_enable(IRQN_AI_INTERRUPT); - plic_set_priority(IRQN_AI_INTERRUPT, 1); - plic_irq_register(IRQN_AI_INTERRUPT, kpu_continue, task); - - kpu_run_dma_input(dma_ch, src, kpu_run_dma_input_done_push_layers, task); - - return 0; -} - -uint8_t *kpu_get_output_buf(kpu_task_t* task) -{ - kpu_layer_argument_t* last_layer = &task->layers[task->layers_length-1]; - size_t output_size = ((last_layer->dma_parameter.data.dma_total_byte+1) + 7) / 8 * 8; - return malloc(output_size); -} - -void kpu_release_output_buf(uint8_t *output_buf) -{ - if(output_buf != NULL) - free(output_buf); -} - -static int kpu_done(void *ctx) -{ - atomic_swap(&kpu_status, 0); - kpu_task_t *task = (kpu_task_t *)ctx; - task->callback(task->ctx); - return 0; -} - -static int kpu_config_input(void *ctx) -{ - kpu_task_t *task = (kpu_task_t *)ctx; - kpu->interrupt_clear.reg = 7; - if (task->remain_layers_length <= LAYER_BURST_SIZE) - { - for (uint32_t i = 0; i < task->remain_layers_length; i++) - { - kpu->layer_argument_fifo = task->remain_layers[i].interrupt_enabe.reg; - kpu->layer_argument_fifo = task->remain_layers[i].image_addr.reg; - kpu->layer_argument_fifo = task->remain_layers[i].image_channel_num.reg; - kpu->layer_argument_fifo = task->remain_layers[i].image_size.reg; - kpu->layer_argument_fifo = task->remain_layers[i].kernel_pool_type_cfg.reg; - kpu->layer_argument_fifo = task->remain_layers[i].kernel_load_cfg.reg; - kpu->layer_argument_fifo = task->remain_layers[i].kernel_offset.reg; - kpu->layer_argument_fifo = task->remain_layers[i].kernel_calc_type_cfg.reg; - kpu->layer_argument_fifo = task->remain_layers[i].write_back_cfg.reg; - kpu->layer_argument_fifo = task->remain_layers[i].conv_value.reg; - kpu->layer_argument_fifo = task->remain_layers[i].conv_value2.reg; - kpu->layer_argument_fifo = task->remain_layers[i].dma_parameter.reg; - } - task->remain_layers_length = 0; - kpu->interrupt_mask.reg = 7; - } - else - { - for (uint32_t i = 0; i < LAYER_BURST_SIZE; i++) - { - kpu->layer_argument_fifo = task->remain_layers[i].interrupt_enabe.reg; - kpu->layer_argument_fifo = task->remain_layers[i].image_addr.reg; - kpu->layer_argument_fifo = task->remain_layers[i].image_channel_num.reg; - kpu->layer_argument_fifo = task->remain_layers[i].image_size.reg; - kpu->layer_argument_fifo = task->remain_layers[i].kernel_pool_type_cfg.reg; - kpu->layer_argument_fifo = task->remain_layers[i].kernel_load_cfg.reg; - kpu->layer_argument_fifo = task->remain_layers[i].kernel_offset.reg; - kpu->layer_argument_fifo = task->remain_layers[i].kernel_calc_type_cfg.reg; - kpu->layer_argument_fifo = task->remain_layers[i].write_back_cfg.reg; - kpu->layer_argument_fifo = task->remain_layers[i].conv_value.reg; - kpu->layer_argument_fifo = task->remain_layers[i].conv_value2.reg; - kpu->layer_argument_fifo = task->remain_layers[i].dma_parameter.reg; - } - task->remain_layers += LAYER_BURST_SIZE; - task->remain_layers_length -= LAYER_BURST_SIZE; - } - return 0; -} - -static void kpu_data_output(kpu_task_t *task) -{ - sysctl_dma_select(task->dma_ch, SYSCTL_DMA_SELECT_AI_RX_REQ); - dmac_irq_register(task->dma_ch, kpu_done, task, 1); - dmac_set_single_mode(task->dma_ch, (void *)(&kpu->fifo_data_out), (void *)(task->dst), DMAC_ADDR_NOCHANGE, DMAC_ADDR_INCREMENT, - DMAC_MSIZE_8, DMAC_TRANS_WIDTH_64, task->dst_length); -} - -static int kpu_data_ready(void *ctx) -{ - kpu_task_t *task = (kpu_task_t *)ctx; - - dmac->channel[task->dma_ch].intclear = 0xFFFFFFFF; - kpu_data_output(task); - - kpu->eight_bit_mode.reg = task->eight_bit_mode; - kpu->interrupt_mask.reg = 7; - kpu->interrupt_clear.reg = 7; - kpu->fifo_threshold.data = (kpu_config_fifo_threshold_t) - { - .fifo_full_threshold = 12, .fifo_empty_threshold = 1 - }; - plic_irq_enable(IRQN_AI_INTERRUPT); - plic_set_priority(IRQN_AI_INTERRUPT, 2); - plic_irq_register(IRQN_AI_INTERRUPT, kpu_config_input, task); - kpu_config_input(task); - kpu->interrupt_mask.data = (kpu_config_interrupt_t) - { - .calc_done_int = 1, - .layer_cfg_almost_empty_int = 0, - .layer_cfg_almost_full_int = 1 - }; - return 0; -} - -static void kpu_data_input(kpu_task_t *task) -{ - if (task->src == NULL) - { - kpu_data_ready(task); - return; - } - dmac_irq_register(task->dma_ch, kpu_data_ready, task, 1); - kpu_layer_argument_t *layer = &task->layers[0]; - dmac_set_single_mode(task->dma_ch, task->src, (void *)(AI_IO_BASE_ADDR + layer->image_addr.data.image_src_addr * 64), DMAC_ADDR_INCREMENT, DMAC_ADDR_INCREMENT, - DMAC_MSIZE_16, DMAC_TRANS_WIDTH_64, task->src_length); -} - -int kpu_single_task_init(kpu_task_t *task) -{ - sysctl_clock_enable(SYSCTL_CLOCK_AI); - kpu_layer_argument_t *first_layer = &task->layers[0]; - kpu_layer_argument_t *last_layer = &task->layers[task->layers_length - 1]; - - last_layer->dma_parameter.data.send_data_out = 1; - last_layer->interrupt_enabe.data.int_en = 1; - task->src_length = first_layer->kernel_calc_type_cfg.data.channel_switch_addr * 64 * (first_layer->image_channel_num.data.i_ch_num + 1) / 8; - task->dst_length = ((last_layer->dma_parameter.data.dma_total_byte + 1) + 7) / 8; - task->dst = (uint64_t *)malloc(task->dst_length * 8); - memset(task->dst, 0, task->dst_length * 8); - if (task->dst == NULL) - return 1; - return 0; -} - -int kpu_single_task_deinit(kpu_task_t *task) -{ - free(task->dst); - return 0; -} - -int kpu_model_load_from_buffer(kpu_task_t *task, uint8_t *buffer, kpu_model_layer_metadata_t **meta) -{ - uintptr_t base_addr = (uintptr_t)buffer; - kpu_model_header_t *header = (kpu_model_header_t *)buffer; - kpu_model_layer_metadata_t *layer_meta = (kpu_model_layer_metadata_t *)(base_addr + sizeof(kpu_model_header_t)); - kpu_layer_argument_t *layers = (kpu_layer_argument_t *)(base_addr + header->layers_argument_start); - - if (header->version != 1) - return -1; - uint32_t layers_length = header->layers_length; - task->layers_length = layers_length; - task->eight_bit_mode = header->flags & 1; - task->layers = layers; - task->output_scale = layer_meta[layers_length - 1].output_scale; - task->output_bias = layer_meta[layers_length - 1].output_bias; - size_t i; - for (i = 0; i < layers_length; i++) - { - layers[i].kernel_load_cfg.data.para_start_addr = (uint64_t)(base_addr + layer_meta[i].weigths_offset); - layers[i].kernel_pool_type_cfg.data.bwsx_base_addr = (uint64_t)(base_addr + layer_meta[i].bn_offset); - layers[i].kernel_calc_type_cfg.data.active_addr = (uint64_t)(base_addr + layer_meta[i].act_offset); - } - - if (meta) - *meta = layer_meta; - return 0; -} - -int kpu_start(kpu_task_t *task) -{ - if (atomic_cas(&kpu_status, 0, 1)) - return -1; - - task->remain_layers_length = task->layers_length; - task->remain_layers = task->layers; - kpu_data_input(task); - return 0; -} - -static void kpu_send_layer(const kpu_layer_argument_t *layer) -{ - kpu->layer_argument_fifo = layer->interrupt_enabe.reg; - kpu->layer_argument_fifo = layer->image_addr.reg; - kpu->layer_argument_fifo = layer->image_channel_num.reg; - kpu->layer_argument_fifo = layer->image_size.reg; - kpu->layer_argument_fifo = layer->kernel_pool_type_cfg.reg; - kpu->layer_argument_fifo = layer->kernel_load_cfg.reg; - kpu->layer_argument_fifo = layer->kernel_offset.reg; - kpu->layer_argument_fifo = layer->kernel_calc_type_cfg.reg; - kpu->layer_argument_fifo = layer->write_back_cfg.reg; - kpu->layer_argument_fifo = layer->conv_value.reg; - kpu->layer_argument_fifo = layer->conv_value2.reg; - kpu->layer_argument_fifo = layer->dma_parameter.reg; -} - -void kpu_init(int eight_bit_mode, plic_irq_callback_t callback, void *userdata) -{ - kpu->interrupt_clear.reg = 7; - kpu->fifo_threshold.data = (kpu_config_fifo_threshold_t) - { - .fifo_full_threshold = 10, .fifo_empty_threshold = 1 - }; - kpu->eight_bit_mode.data = (kpu_config_eight_bit_mode_t) - { - .eight_bit_mode = eight_bit_mode - }; - kpu->interrupt_mask.data = (kpu_config_interrupt_t) - { - .calc_done_int = 1, - .layer_cfg_almost_empty_int = 0, - .layer_cfg_almost_full_int = 1 - }; - - plic_irq_enable(IRQN_AI_INTERRUPT); - plic_set_priority(IRQN_AI_INTERRUPT, 1); - plic_irq_register(IRQN_AI_INTERRUPT, callback, userdata); -} - -#if 0 -void kpu_input_dma(kpu_layer_argument_t *layer, const uint8_t *src, dmac_channel_number_t dma_ch, plic_irq_callback_t callback, void *userdata) -{ - uint64_t input_size = layer->kernel_calc_type_cfg.data.channel_switch_addr * 64 * (layer->image_channel_num.data.i_ch_num + 1); - dmac_set_irq(dma_ch, callback, userdata, 1); - dmac_set_single_mode(dma_ch, (void *)src, (void *)(AI_IO_BASE_ADDR + layer->image_addr.data.image_src_addr * 64), DMAC_ADDR_INCREMENT, DMAC_ADDR_INCREMENT, - DMAC_MSIZE_16, DMAC_TRANS_WIDTH_64, input_size / 8); -} -#endif - -void kpu_input_dma(const kpu_layer_argument_t *layer, const uint8_t *src, dmac_channel_number_t dma_ch, plic_irq_callback_t callback, void *userdata) -{ - uint64_t input_size = layer->kernel_calc_type_cfg.data.channel_switch_addr * 64 * (layer->image_channel_num.data.i_ch_num + 1); - - dmac_set_irq(dma_ch, callback, userdata, 1); - dmac_set_single_mode(dma_ch, (void *)src, (void *)(uintptr_t)(AI_IO_BASE_ADDR + layer->image_addr.data.image_src_addr * 64), DMAC_ADDR_INCREMENT, DMAC_ADDR_INCREMENT, - DMAC_MSIZE_16, DMAC_TRANS_WIDTH_64, input_size / 8); -} - -static void kpu_conv2d_core(kpu_layer_argument_t *layer) -{ - kpu_send_layer(layer); -} - -void kpu_conv2d(kpu_layer_argument_t *layer) -{ - kpu->interrupt_clear.data = (kpu_config_interrupt_t) - { - .calc_done_int = 1, - .layer_cfg_almost_empty_int = 1, - .layer_cfg_almost_full_int = 1 - }; - kpu->interrupt_mask.data = (kpu_config_interrupt_t) - { - .calc_done_int = 1, - .layer_cfg_almost_empty_int = 0, - .layer_cfg_almost_full_int = 1 - }; - kpu_conv2d_core(layer); -} - -void kpu_conv2d_output(kpu_layer_argument_t *layer, dmac_channel_number_t dma_ch, uint8_t *dest, plic_irq_callback_t callback, void *userdata) -{ - kpu->interrupt_clear.data = (kpu_config_interrupt_t) - { - .calc_done_int = 1, - .layer_cfg_almost_empty_int = 1, - .layer_cfg_almost_full_int = 1 - }; - kpu->interrupt_mask.data = (kpu_config_interrupt_t) - { - .calc_done_int = 1, - .layer_cfg_almost_empty_int = 1, - .layer_cfg_almost_full_int = 1 - }; - layer->dma_parameter.data.send_data_out = 1; - sysctl_dma_select(dma_ch, SYSCTL_DMA_SELECT_AI_RX_REQ); - dmac_set_irq(dma_ch, callback, userdata, 1); - dmac_set_single_mode(dma_ch, (void *)(&kpu->fifo_data_out), dest, DMAC_ADDR_NOCHANGE, DMAC_ADDR_INCREMENT, - DMAC_MSIZE_8, DMAC_TRANS_WIDTH_64, (layer->dma_parameter.data.dma_total_byte + 8) / 8); - kpu_conv2d_core(layer); -} - -void kpu_conv2d_output_full_add(kpu_layer_argument_t *layer, dmac_channel_number_t dma_ch, uint64_t *dest, plic_irq_callback_t callback, void *userdata) -{ - uint32_t channels = layer->image_channel_num.data.o_ch_num + 1; - layer->interrupt_enabe.data.full_add = 1; - - kpu->interrupt_clear.data = (kpu_config_interrupt_t) - { - .calc_done_int = 1, - .layer_cfg_almost_empty_int = 1, - .layer_cfg_almost_full_int = 1 - }; - kpu->interrupt_mask.data = (kpu_config_interrupt_t) - { - .calc_done_int = 1, - .layer_cfg_almost_empty_int = 1, - .layer_cfg_almost_full_int = 1 - }; - layer->dma_parameter.data.send_data_out = 1; - sysctl_dma_select(dma_ch, SYSCTL_DMA_SELECT_AI_RX_REQ); - dmac_set_irq(dma_ch, callback, userdata, 1); - dmac_set_single_mode(dma_ch, (void *)(&kpu->fifo_data_out), dest, DMAC_ADDR_NOCHANGE, DMAC_ADDR_INCREMENT, - DMAC_MSIZE_8, DMAC_TRANS_WIDTH_64, channels); - kpu_conv2d_core(layer); -} - -void kpu_add(const uint8_t *src1, const quantize_param_t *src1_param, const uint8_t *src2, const quantize_param_t *src2_param, size_t count, uint8_t *dest, const quantize_param_t *dest_param) -{ - quantize_param_t q1 = *src1_param, q2 = *src2_param, q3 = *dest_param; - - size_t i; - for (i = 0; i < count; i++) - { - int value = ((*src1++ * q1.scale + q1.bias + *src2++ * q2.scale + q2.bias) - q3.bias) / q3.scale; - if (value < 0) value = 0; - if (value > 0xFF) value = 0xFF; - *dest++ = value; - } -} - -void kpu_global_average_pool(const uint8_t *src, const quantize_param_t *src_param, int kernel_size, int channels, uint8_t *dest, const quantize_param_t *dest_param) -{ - quantize_param_t q1 = *src_param, q2 = *dest_param; - size_t oc, y, x; - - if (((uintptr_t)dest) >= AI_IO_BASE_ADDR && ((uintptr_t)dest) < AI_IO_BASE_ADDR + 2 * 1024 * 1024) - { - uint32_t row_padding = 16; - uint32_t row_group = 4; - uint32_t row_length = 1; - uint32_t height = 4; - - for (oc = 0; oc < channels; oc++) - { - uint8_t *channel_origin = dest + oc / row_group * row_length * height * 64 + oc % row_group * row_padding; - for (y = 0; y < 1; y++) - { - uint8_t *y_origin = channel_origin + y * row_length * 64; - for (x = 0; x < 1; x++) - { - int64_t sum = 0; - size_t i; - for (i = 0; i < kernel_size; i++) - sum += *src++; - - int value = ((sum * q1.scale + q1.bias) / kernel_size - q2.bias) / q2.scale; - if (value < 0) value = 0; - if (value > 0xFF) value = 0xFF; - y_origin[x] = value; - } - } - } - } - else - { - for (oc = 0; oc < channels; oc++) - { - int64_t sum = 0; - size_t i; - for (i = 0; i < kernel_size; i++) - sum += *src++; - - int value = ((sum * q1.scale + q1.bias) / kernel_size - q2.bias) / q2.scale; - if (value < 0) value = 0; - if (value > 0xFF) value = 0xFF; - dest[oc] = value; - } - } -} - -void kpu_global_average_pool_float(const uint8_t *src, const quantize_param_t *src_param, int kernel_size, int channels, float *dest) -{ - quantize_param_t q = *src_param; - size_t oc; - - for (oc = 0; oc < channels; oc++) - { - int64_t sum = 0; - size_t i; - for (i = 0; i < kernel_size; i++) - sum += *src++; - - float value = (sum * q.scale + q.bias) / kernel_size; - dest[oc] = value; - } -} - -void kpu_matmul_end(const uint8_t *src, int channels, float *dest, const quantize_param_t *dest_param) -{ - quantize_param_t q1 = *dest_param; - size_t i = 0; - for (i = 0; i < channels; i++) - *dest++ = src[i * 16] * q1.scale + q1.bias; -} - -void kpu_fully_connected(const float *src, const float *weights, const float *biases, float *dest, int input_channels, int output_channels) -{ - int ic, oc; - for (oc = 0; oc < output_channels; oc++) - { - const float *c_weights = weights + oc * input_channels; - - float sum = 0.0f; - for (ic = 0; ic < input_channels; ic++) - sum += src[ic] * c_weights[ic]; - dest[oc] = sum + biases[oc]; - } -} - -void kpu_dequantize(const uint8_t *src, const quantize_param_t *src_param, size_t count, float *dest) -{ - quantize_param_t q1 = *src_param; - size_t i = 0; - for (i = 0; i < count; i++) - *dest++ = src[i] * q1.scale + q1.bias; -} - - -void kpu_input_with_padding(kpu_layer_argument_t *layer, const uint8_t *src, int width, int height, int channels) -{ - uint8_t *dest = (uint8_t *)(AI_IO_BASE_ADDR + layer->image_addr.data.image_src_addr * 64); - size_t oc, y, x; - - uint32_t row_padding; - uint32_t row_group; - uint32_t row_length; - - if (width <= 16) - { - row_padding = 16; - row_group = 4; - row_length = 1; - } - else if (width <= 32) - { - row_padding = 32; - row_group = 2; - row_length = 1; - } - else - { - row_padding = 64; - row_group = 1; - row_length = (width + 63) / 64; - } - - for (oc = 0; oc < channels; oc++) - { - uint8_t *channel_origin = dest + oc / row_group * row_length * height * 64 + oc % row_group * row_padding; - for (y = 0; y < height; y++) - { - uint8_t *y_origin = channel_origin + y * row_length * 64; - for (x = 0; x < width; x++) - y_origin[x] = *src++; - } - } -} - -#define KPU_DEBUG 0 -#define USE_CACHED_AI_RAM 0 - -#define min(a, b) (((a) < (b)) ? (a) : (b)) -#define max(a, b) (((a) > (b)) ? (a) : (b)) -#define ALIGN_UP(x, align) ((x + (align - 1)) & (~(align - 1))) - -static int ai_step(void *userdata); -static int kpu_kmodel_done(kpu_model_context_t *ctx); - -static void kpu_flush_cache(uint32_t addr, size_t lines) -{ - size_t line; - for (line = 0; line < lines; line++) - { - const uint64_t *src = (const uint64_t *)(AI_RAM_BASE_ADDR + (addr + line) * 64); - uint64_t *dest = (uint64_t *)(AI_IO_BASE_ADDR + (addr + line) * 64); - size_t i; - for (i = 0; i < 8; i++) - dest[i] = src[i]; - } -} - -static void kpu_upload_core(size_t width, size_t height, size_t channels, const uint8_t *src, uint32_t kpu_addr) -{ - uint8_t *dest = AI_IO_BASE_ADDR + kpu_addr * 64; - size_t oc, y, x; - uint32_t row_padding; - uint32_t row_group; - uint32_t row_length; - if (width <= 16) - { - row_padding = 16; - row_group = 4; - row_length = 1; - } - else if (width <= 32) - { - row_padding = 32; - row_group = 2; - row_length = 1; - } - else - { - row_padding = 64; - row_group = 1; - row_length = (width + 63) / 64; - } - - if ((uintptr_t)src % 8 == 0 && width % 8 == 0) - { -#define UPLOAD_BEGIN() \ - for (oc = 0; oc < channels; oc++) \ - { \ - uint8_t* channel_origin = dest + oc / row_group * row_length * height * 64 + oc % row_group * row_padding; \ - for (y = 0; y < height; y++) \ - { \ - uint64_t* y_origin = channel_origin + y * row_length * 64; \ - -#define UPLOAD_END() \ - } \ - } - - width /= 8; - const uint64_t *u64_src = src; - if (width == 1) - { - UPLOAD_BEGIN() - y_origin[0] = *u64_src++; - UPLOAD_END() - } - else if (width == 2) - { - UPLOAD_BEGIN() - { - y_origin[0] = *u64_src++; - y_origin[1] = *u64_src++; - } - UPLOAD_END() - } - else if (width == 4) - { - UPLOAD_BEGIN() - { - y_origin[0] = *u64_src++; - y_origin[1] = *u64_src++; - y_origin[2] = *u64_src++; - y_origin[3] = *u64_src++; - } - UPLOAD_END() - } - else - { - UPLOAD_BEGIN() - for (x = 0; x < width; x++) - y_origin[x] = *u64_src++; - UPLOAD_END() - } - } - else - { - for (oc = 0; oc < channels; oc++) - { - uint8_t *channel_origin = dest + oc / row_group * row_length * height * 64 + oc % row_group * row_padding; - for (y = 0; y < height; y++) - { - uint8_t *y_origin = channel_origin + y * row_length * 64; - for (x = 0; x < width; x++) - y_origin[x] = *src++; - } - } - } -} -static void kpu_kmodel_input_with_padding(const kpu_layer_argument_t *layer, const uint8_t *src) -{ - size_t width = layer->image_size.data.i_row_wid + 1; - size_t height = layer->image_size.data.i_col_high + 1; - size_t channels = layer->image_channel_num.data.i_ch_num + 1; - - kpu_upload_core(width, height, channels, src, layer->image_addr.data.image_src_addr); -} - -static void kpu_kmodel_add(const kpu_model_add_layer_argument_t *arg, kpu_model_context_t *ctx) -{ - const float *src_a = (const float *)(ctx->main_buffer + arg->main_mem_in_a_address); - const float *src_b = (const float *)(ctx->main_buffer + arg->main_mem_in_b_address); - float *dest = (float *)(ctx->main_buffer + arg->main_mem_out_address); - size_t i, count = arg->count; - - for (i = 0; i < count; i++) - dest[i] = src_a[i] + src_b[i]; -} - -static void kpu_quantized_add(const kpu_model_quant_add_layer_argument_t *arg, kpu_model_context_t *ctx) -{ - const uint8_t *src_a = (const uint8_t*)(ctx->main_buffer + arg->main_mem_in_a_address); - const uint8_t *src_b = (const uint8_t*)(ctx->main_buffer + arg->main_mem_in_b_address); - size_t count = ALIGN_UP(arg->count, 8) / 8; - int64_t off_a = arg->in_a_offset, mul_a = arg->in_a_mul, sh_a = arg->in_a_shift; - int64_t off_b = arg->in_b_offset, mul_b = arg->in_b_mul, sh_b = arg->in_b_shift; - int64_t off_o = arg->out_offset, mul_o = arg->out_mul, sh_o = arg->out_shift; - - uint8_t* dest = (uint8_t*)(ctx->main_buffer + arg->main_mem_out_address); - size_t i; - - if (sh_a == sh_b) - { -#define QADD_UNROLL_1(x) \ - int64_t a##x = *src_a++; \ - int64_t b##x = *src_b++; - -#define QADD_UNROLL_2(x) \ - a##x += off_a; \ - b##x += off_b; - -#define QADD_UNROLL_3(x) \ - a##x *= mul_a; \ - b##x *= mul_b; - -#define QADD_UNROLL_4(x) \ - int64_t v##x = a##x + b##x; - -#define QADD_UNROLL_5(x) \ - v##x >>= sh_a; - -#define QADD_UNROLL_6(x) \ - v##x *= mul_o; - -#define QADD_UNROLL_7(x) \ - v##x >>= sh_o; - -#define QADD_UNROLL_8(x) \ - v##x += off_o; - -#define QADD_UNROLL_9(x) \ - v##x = min(0xFF, max(0, v##x)); - -#define QADD_UNROLL_10(x) \ - *dest++ = v##x; - -#define QADD_UNROLL_S(x) \ - QADD_UNROLL_##x(0) \ - QADD_UNROLL_##x(1) \ - QADD_UNROLL_##x(2) \ - QADD_UNROLL_##x(3) \ - QADD_UNROLL_##x(4) \ - QADD_UNROLL_##x(5) \ - QADD_UNROLL_##x(6) \ - QADD_UNROLL_##x(7) - - for (i = 0; i < count; i++) - { - QADD_UNROLL_S(1); - QADD_UNROLL_S(2); - QADD_UNROLL_S(3); - QADD_UNROLL_S(4); - QADD_UNROLL_S(5); - QADD_UNROLL_S(6); - QADD_UNROLL_S(7); - QADD_UNROLL_S(8); - QADD_UNROLL_S(9); - QADD_UNROLL_S(10); - } - } - else - { -#define QADD_UNROLL_1(x) \ - int64_t a##x = *src_a++; \ - int64_t b##x = *src_b++; - -#define QADD_UNROLL_2(x) \ - a##x += off_a; \ - b##x += off_b; - -#define QADD_UNROLL_3(x) \ - a##x *= mul_a; \ - b##x *= mul_b; - -#define QADD_UNROLL_4(x) \ - a##x >>= sh_a; \ - b##x >>= sh_b; - -#define QADD_UNROLL_5(x) \ - int64_t v##x = a##x + b##x; - -#define QADD_UNROLL_6(x) \ - v##x *= mul_o; - -#define QADD_UNROLL_7(x) \ - v##x >>= sh_o; - -#define QADD_UNROLL_8(x) \ - v##x += off_o; - -#define QADD_UNROLL_9(x) \ - v##x = min(0xFF, max(0, v##x)); - -#define QADD_UNROLL_10(x) \ - *dest++ = v##x; - -#define QADD_UNROLL_S(x) \ - QADD_UNROLL_##x(0) \ - QADD_UNROLL_##x(1) \ - QADD_UNROLL_##x(2) \ - QADD_UNROLL_##x(3) \ - QADD_UNROLL_##x(4) \ - QADD_UNROLL_##x(5) \ - QADD_UNROLL_##x(6) \ - QADD_UNROLL_##x(7) - - for (i = 0; i < count; i++) - { - QADD_UNROLL_S(1); - QADD_UNROLL_S(2); - QADD_UNROLL_S(3); - QADD_UNROLL_S(4); - QADD_UNROLL_S(5); - QADD_UNROLL_S(6); - QADD_UNROLL_S(7); - QADD_UNROLL_S(8); - QADD_UNROLL_S(9); - QADD_UNROLL_S(10); - } - } -} - -static void kpu_global_average_pool2d(const kpu_model_gap2d_layer_argument_t *arg, kpu_model_context_t *ctx) -{ - const float *src = (const float *)(ctx->main_buffer + arg->main_mem_in_address); - float *dest = (float *)(ctx->main_buffer + arg->main_mem_out_address); - size_t oc, channels = arg->channels, kernel_size = arg->kernel_size; - - for (oc = 0; oc < channels; oc++) - { - float sum = 0.f; - size_t i; - for (i = 0; i < kernel_size; i++) - sum += *src++; - - dest[oc] = sum / kernel_size; - } -} - -static void kpu_quantized_max_pool2d(const kpu_model_quant_max_pool2d_layer_argument_t *arg, kpu_model_context_t *ctx) -{ - const uint8_t *src = (const uint8_t *)(ctx->main_buffer + arg->main_mem_in_address); - uint8_t *dest = (uint8_t *)(ctx->main_buffer + arg->main_mem_out_address); - kpu_model_shape_t in_shape = arg->in_shape, out_shape = arg->out_shape; - uint32_t kernel_width = arg->kernel_width, kernel_height = arg->kernel_height; - uint32_t stride_width = arg->stride_width, stride_height = arg->stride_height; - uint32_t padding_width = arg->padding_width, padding_height = arg->padding_height; - - uint32_t out_y, out_x, oc; - - for (oc = 0; oc < out_shape.channels; oc++) - { - const uint8_t *channel_src = src + in_shape.width * in_shape.height * oc; - for (out_y = 0; out_y < out_shape.height; out_y++) - { - for (out_x = 0; out_x < out_shape.width; out_x++) - { - int32_t in_x_origin = (int32_t)(out_x * stride_width) - padding_width; - int32_t in_y_origin = (int32_t)(out_y * stride_height) - padding_height; - int32_t kernel_x_start = max(0, -in_x_origin); - int32_t kernel_x_end = min(kernel_width, in_shape.width - in_x_origin); - int32_t kernel_y_start = max(0, -in_y_origin); - int32_t kernel_y_end = min(kernel_height, in_shape.height - in_y_origin); - uint8_t value = 0; - - int32_t kernel_y, kernel_x; - for (kernel_y = kernel_y_start; kernel_y < kernel_y_end; kernel_y++) - { - for (kernel_x = kernel_x_start; kernel_x < kernel_x_end; kernel_x++) - { - int32_t in_x = in_x_origin + kernel_x; - int32_t in_y = in_y_origin + kernel_y; - value = max(value, channel_src[in_y * in_shape.width + in_x]); - } - } - - *dest++ = value; - } - } - } -} - -static void kpu_average_pool2d(const kpu_model_ave_pool2d_layer_argument_t *arg, kpu_model_context_t *ctx) -{ - const float *src = (const float *)(ctx->main_buffer + arg->main_mem_in_address); - float *dest = (float *)(ctx->main_buffer + arg->main_mem_out_address); - kpu_model_shape_t in_shape = arg->in_shape, out_shape = arg->out_shape; - uint32_t kernel_width = arg->kernel_width, kernel_height = arg->kernel_height; - uint32_t stride_width = arg->stride_width, stride_height = arg->stride_height; - uint32_t padding_width = arg->padding_width, padding_height = arg->padding_height; - - uint32_t out_y, out_x, oc; - - for (oc = 0; oc < out_shape.channels; oc++) - { - const float *channel_src = src + in_shape.width * in_shape.height * oc; - for (out_y = 0; out_y < out_shape.height; out_y++) - { - for (out_x = 0; out_x < out_shape.width; out_x++) - { - int32_t in_x_origin = (int32_t)(out_x * stride_width) - padding_width; - int32_t in_y_origin = (int32_t)(out_y * stride_height) - padding_height; - int32_t kernel_x_start = max(0, -in_x_origin); - int32_t kernel_x_end = min(kernel_width, in_shape.width - in_x_origin); - int32_t kernel_y_start = max(0, -in_y_origin); - int32_t kernel_y_end = min(kernel_height, in_shape.height - in_y_origin); - float value = 0; - float kernel_count = 0; - - int32_t kernel_y, kernel_x; - for (kernel_y = kernel_y_start; kernel_y < kernel_y_end; kernel_y++) - { - for (kernel_x = kernel_x_start; kernel_x < kernel_x_end; kernel_x++) - { - int32_t in_x = in_x_origin + kernel_x; - int32_t in_y = in_y_origin + kernel_y; - value += channel_src[in_y * in_shape.width + in_x]; - kernel_count++; - } - } - - *dest++ = value / kernel_count; - } - } - } -} - -static void kpu_quantize(const kpu_model_quantize_layer_argument_t *arg, kpu_model_context_t *ctx) -{ - size_t count = arg->count; - const float *src = (const float *)(ctx->main_buffer + arg->main_mem_in_address);; - const kpu_model_quant_param_t q = arg->quant_param; - float scale = 1.f / q.scale; - - uint8_t *dest = (uint8_t *)(ctx->main_buffer + arg->mem_out_address); - size_t i; - for (i = 0; i < count; i++) - { - int value = (*src++ - q.bias) * scale; - if (value < 0) value = 0; - if (value > 0xFF) value = 0xFF; - *dest++ = (uint8_t)value; - } -} - -static void kpu_kmodel_dequantize(const kpu_model_dequantize_layer_argument_t *arg, kpu_model_context_t *ctx) -{ - const uint8_t *src = (const uint8_t *)(ctx->main_buffer + arg->main_mem_in_address); - float *dest = (float *)(ctx->main_buffer + arg->main_mem_out_address); - size_t oc, count = arg->count; - const kpu_model_quant_param_t q = arg->quant_param; - - for (oc = 0; oc < count; oc++) - dest[oc] = *src++ * q.scale + q.bias; -} - -static void kpu_requantize(const kpu_model_requantize_layer_argument_t *arg, kpu_model_context_t *ctx) -{ - const uint8_t *src = (const uint8_t *)(ctx->main_buffer + arg->main_mem_in_address); - uint8_t *dest = (uint8_t *)(ctx->main_buffer + arg->main_mem_out_address); - size_t oc, count = ALIGN_UP(arg->count, 8) / 8; - const uint8_t *table = arg->table; - - for (oc = 0; oc < count;) - { - dest[oc++] = table[*src++]; - dest[oc++] = table[*src++]; - dest[oc++] = table[*src++]; - dest[oc++] = table[*src++]; - dest[oc++] = table[*src++]; - dest[oc++] = table[*src++]; - dest[oc++] = table[*src++]; - dest[oc++] = table[*src++]; - } -} - -static void kpu_l2_normalization(const kpu_model_l2_norm_layer_argument_t *arg, kpu_model_context_t *ctx) -{ - const float *src = (const float *)(ctx->main_buffer + arg->main_mem_in_address); - float *dest = (float *)(ctx->main_buffer + arg->main_mem_out_address); - size_t oc, channels = arg->channels; - - float sum = 0.f; - const float epsilon = 1e-10f; - for (oc = 0; oc < channels; oc++) - sum += src[oc] * src[oc]; - if (sum < epsilon) - sum = epsilon; - sum = 1.f / sqrtf(sum); - for (oc = 0; oc < channels; oc++) - dest[oc] = src[oc] * sum; -} - -static void kpu_softmax(const kpu_model_softmax_layer_argument_t *arg, kpu_model_context_t *ctx) -{ - const float *src = (const float *)(ctx->main_buffer + arg->main_mem_in_address); - float *dest = (float *)(ctx->main_buffer + arg->main_mem_out_address); - size_t oc, channels = arg->channels; - - float max = FLT_MIN; - for (oc = 0; oc < channels; oc++) - max = fmaxf(max, src[oc]); - - float sum = 0.f; - for (oc = 0; oc < channels; oc++) - { - float value = expf(src[oc] - max); - sum += value; - dest[oc] = value; - } - - for (oc = 0; oc < channels; oc++) - dest[oc] /= sum; -} - -static void kpu_concat(const kpu_model_concat_layer_argument_t *arg, kpu_model_context_t *ctx) -{ - uint8_t *dest = (uint8_t *)(ctx->main_buffer + arg->main_mem_out_address); - uint32_t count = arg->input_count, i; - - for (i = 0; i < count; i++) - { - kpu_model_memory_range_t input = arg->inputs_mem[i]; - const uint8_t *src = (const uint8_t *)(ctx->main_buffer + input.start); - memcpy(dest, src, input.size); - dest += input.size; - } -} - -static void kpu_kmodel_fully_connected(const kpu_model_fully_connected_layer_argument_t *arg, kpu_model_context_t *ctx) -{ - const float *src = (const float *)(ctx->main_buffer + arg->main_mem_in_address); - float *dest = (float *)(ctx->main_buffer + arg->main_mem_out_address); - uint32_t in_channels = arg->in_channels, out_channels = arg->out_channels, ic, oc; - float *weights = arg->weights, *bias = arg->weights + in_channels * out_channels; - - for (oc = 0; oc < out_channels; oc++) - { - const float *c_weights = weights + oc * in_channels; - - float sum = 0.0f; - for (ic = 0; ic < in_channels; ic++) - sum += src[ic] * c_weights[ic]; - dest[oc] = sum + bias[oc]; - } -} - -static void kpu_tf_flatten(const kpu_model_tf_flatten_layer_argument_t *arg, kpu_model_context_t *ctx) -{ - const float *src = (const float *)(ctx->main_buffer + arg->main_mem_in_address); - float *dest = (float *)(ctx->main_buffer + arg->main_mem_out_address); - kpu_model_shape_t in_shape = arg->shape; - uint32_t oc, oy, ox; - - for (oy = 0; oy < in_shape.height; oy++) - for (ox = 0; ox < in_shape.width; ox++) - for (oc = 0; oc < in_shape.channels; oc++) - *dest++ = src[(oc * in_shape.height + oy) * in_shape.width + ox]; -} - -static void kpu_conv(const kpu_model_conv_layer_argument_t *arg, kpu_model_context_t *ctx) -{ - volatile kpu_layer_argument_t layer = *(const volatile kpu_layer_argument_t *)(ctx->model_buffer + arg->layer_offset); - layer.kernel_load_cfg.data.para_start_addr = (uintptr_t)(ctx->model_buffer + arg->weights_offset); - layer.kernel_pool_type_cfg.data.bwsx_base_addr = (uintptr_t)(ctx->model_buffer + arg->bn_offset); - layer.kernel_calc_type_cfg.data.active_addr = (uintptr_t)(ctx->model_buffer + arg->act_offset); - - if (arg->flags & KLF_MAIN_MEM_OUT) - { - dmac_channel_number_t dma_ch = ctx->dma_ch; - uint8_t *dest = ctx->main_buffer + arg->main_mem_out_address; - kpu->interrupt_clear.data = (kpu_config_interrupt_t) - { - .calc_done_int = 1, - .layer_cfg_almost_empty_int = 1, - .layer_cfg_almost_full_int = 1 - }; - kpu->interrupt_mask.data = (kpu_config_interrupt_t) - { - .calc_done_int = 1, - .layer_cfg_almost_empty_int = 1, - .layer_cfg_almost_full_int = 1 - }; - layer.dma_parameter.data.send_data_out = 1; - sysctl_dma_select(dma_ch, SYSCTL_DMA_SELECT_AI_RX_REQ); - if (ctx->current_layer != ctx->layers_length) - dmac_set_irq(dma_ch, ai_step, ctx, 1); - else - dmac_set_irq(dma_ch, kpu_kmodel_done, ctx, 1); - dmac_set_single_mode(dma_ch, (void *)(&kpu->fifo_data_out), dest, DMAC_ADDR_NOCHANGE, DMAC_ADDR_INCREMENT, - DMAC_MSIZE_8, DMAC_TRANS_WIDTH_64, (layer.dma_parameter.data.dma_total_byte + 8) / 8); - } - else - { - kpu->interrupt_clear.data = (kpu_config_interrupt_t) - { - .calc_done_int = 1, - .layer_cfg_almost_empty_int = 1, - .layer_cfg_almost_full_int = 1 - }; -#if KPU_DEBUG - kpu->interrupt_mask.data = (kpu_config_interrupt_t) - { - .calc_done_int = 0, - .layer_cfg_almost_empty_int = 1, - .layer_cfg_almost_full_int = 1 - }; - layer.interrupt_enabe.data.int_en = 1; -#else - kpu->interrupt_mask.data = (kpu_config_interrupt_t) - { - .calc_done_int = 1, - .layer_cfg_almost_empty_int = 0, - .layer_cfg_almost_full_int = 1 - }; -#endif - } - - kpu_send_layer(&layer); -} - -static void kpu_add_padding(const kpu_model_add_padding_layer_argument_t *arg, kpu_model_context_t *ctx) -{ - const uint8_t *src = (const uint8_t *)(ctx->main_buffer + arg->main_mem_in_address); -#if USE_CACHED_AI_RAM - uint8_t *dest = AI_RAM_BASE_ADDR + arg->kpu_mem_out_address * 64; -#else - uint8_t *dest = AI_IO_BASE_ADDR + arg->kpu_mem_out_address * 64; -#endif - - uint32_t row_padding = 16; - uint32_t row_group = 4; - uint32_t row_length = 1; - uint32_t height = 4; - uint32_t oc, x, y, channels = arg->channels; - - for (oc = 0; oc < channels; oc++) - { - uint8_t *channel_origin = dest + oc / row_group * row_length * height * 64 + oc % row_group * row_padding; - for (y = 0; y < 1; y++) - { - uint8_t *y_origin = channel_origin + y * row_length * 64; - for (x = 0; x < 1; x++) - y_origin[x] = *src++; - } - } - -#if USE_CACHED_AI_RAM - uint32_t lines = row_length * height * channels / row_group; - kpu_flush_cache(arg->kpu_mem_out_address, lines); -#endif -} - -static void kpu_remove_padding(const kpu_model_remove_padding_layer_argument_t *arg, kpu_model_context_t *ctx) -{ - const uint8_t *src = (const uint8_t *)(ctx->main_buffer + arg->main_mem_in_address); - uint8_t *dest = (uint8_t *)(ctx->main_buffer + arg->main_mem_out_address); - uint32_t oc, channels = arg->channels; - - for (oc = 0; oc < channels; oc++) - *dest++ = src[oc * 16]; -} - -static void kpu_upload(const kpu_model_upload_layer_argument_t *arg, kpu_model_context_t *ctx) -{ - size_t width = arg->width; - size_t height = arg->height; - size_t channels = arg->channels; - - kpu_upload_core(width, height, channels, ctx->main_buffer + arg->main_mem_in_address, arg->kpu_mem_out_address); -} - -int kpu_load_kmodel(kpu_model_context_t *ctx, const uint8_t *buffer) -{ - uintptr_t base_addr = (uintptr_t)buffer; - const kpu_kmodel_header_t *header = (const kpu_kmodel_header_t *)buffer; - - if (header->version == 3 && header->arch == 0) - { - ctx->model_buffer = buffer; - ctx->output_count = header->output_count; - ctx->outputs = (const kpu_model_output_t *)(base_addr + sizeof(kpu_kmodel_header_t)); - ctx->layer_headers = (const kpu_model_layer_header_t *)((uintptr_t)ctx->outputs + sizeof(kpu_model_output_t) * ctx->output_count); - ctx->layers_length = header->layers_length; - ctx->body_start = (const uint8_t *)((uintptr_t)ctx->layer_headers + sizeof(kpu_model_layer_header_t) * header->layers_length); - ctx->main_buffer = (uint8_t *)malloc(header->main_mem_usage); - if (!ctx->main_buffer) - return -1; - } - else - { - return -1; - } - - return 0; -} - -int kpu_get_output(kpu_model_context_t *ctx, uint32_t index, uint8_t **data, size_t *size) -{ - if (index >= ctx->output_count) - return -1; - - const kpu_model_output_t * output = ctx->outputs + index; - *data = ctx->main_buffer + output->address; - *size = output->size; - return 0; -} - -void kpu_model_free(kpu_model_context_t *ctx) -{ - free(ctx->main_buffer); - ctx->main_buffer = NULL; -} - -#if KPU_DEBUG -static uint64_t last_time; -static uint64_t total_time; -static uint32_t last_layer_type; - -static const char *str_layer_type(uint32_t type) -{ - switch (type) - { - case KL_ADD: - return "Add"; - case KL_QUANTIZED_ADD: - return "QuantAdd"; - case KL_GLOBAL_AVERAGE_POOL2D: - return "GAP"; - case KL_QUANTIZED_MAX_POOL2D: - return "QuantMaxPool2d"; - case KL_AVERAGE_POOL2D: - return "AveragePool2d"; - case KL_QUANTIZE: - return "Quantize"; - case KL_DEQUANTIZE: - return "Dequantize"; - case KL_REQUANTIZE: - return "Requantize"; - case KL_L2_NORMALIZATION: - return "L2Norm"; - case KL_SOFTMAX: - return "Softmax"; - case KL_CONCAT: - return "Concat"; - case KL_QUANTIZED_CONCAT: - return "QuantConcat"; - case KL_FULLY_CONNECTED: - return "FullyConnected"; - case KL_TENSORFLOW_FLATTEN: - return "TFFlatten"; - case KL_K210_CONV: - return "K210Conv"; - case KL_K210_ADD_PADDING: - return "K210AddPad"; - case KL_K210_REMOVE_PADDING: - return "K210RemovePad"; - case KL_K210_UPLOAD: - return "K210Upload"; - default: - return "Unknown"; - } -} -#endif - -static int kpu_kmodel_done(kpu_model_context_t *ctx) -{ - kpu->interrupt_clear.data = (kpu_config_interrupt_t) - { - .calc_done_int = 1, - .layer_cfg_almost_empty_int = 1, - .layer_cfg_almost_full_int = 1 - }; - kpu->interrupt_mask.data = (kpu_config_interrupt_t) - { - .calc_done_int = 1, - .layer_cfg_almost_empty_int = 1, - .layer_cfg_almost_full_int = 1 - }; -#if KPU_DEBUG - uint32_t cnt_layer_id = ctx->current_layer - 1; - uint64_t time = sysctl_get_time_us(); - if (last_time != 0) - { - uint64_t layer_time = time - last_time; - printf("layer %d [%s]: %f ms\n", cnt_layer_id, str_layer_type(last_layer_type), layer_time / 1000.0); - total_time += layer_time; - } - - printf("Model: %f ms\n", total_time / 1000.0); -#endif - ctx->done_callback(ctx->userdata); - return 0; -} - -static int ai_step(void *userdata) -{ - kpu_model_context_t *ctx = (kpu_model_context_t *)userdata; - - uint32_t cnt_layer_id = ctx->current_layer++; - const uint8_t *layer_body = ctx->current_body; - const kpu_model_layer_header_t *cnt_layer_header = ctx->layer_headers + cnt_layer_id; - ctx->current_body += cnt_layer_header->body_size; - -#if KPU_DEBUG - uint64_t time = sysctl_get_time_us(); - if (last_time != 0) - { - uint64_t layer_time = time - last_time; - printf("layer %d [%s]: %f ms\n", cnt_layer_id - 1, str_layer_type(last_layer_type), layer_time / 1000.0); - total_time += layer_time; - } - - last_layer_type = cnt_layer_header->type; - last_time = sysctl_get_time_us(); -#endif - - switch (cnt_layer_header->type) - { - case KL_ADD: - kpu_kmodel_add((const kpu_model_add_layer_argument_t *)layer_body, ctx); - break; - case KL_QUANTIZED_ADD: - kpu_quantized_add((const kpu_model_quant_add_layer_argument_t *)layer_body, ctx); - break; - case KL_GLOBAL_AVERAGE_POOL2D: - kpu_global_average_pool2d((const kpu_model_gap2d_layer_argument_t *)layer_body, ctx); - break; - case KL_QUANTIZED_MAX_POOL2D: - kpu_quantized_max_pool2d((const kpu_model_quant_max_pool2d_layer_argument_t *)layer_body, ctx); - break; - case KL_AVERAGE_POOL2D: - kpu_average_pool2d((const kpu_model_ave_pool2d_layer_argument_t *)layer_body, ctx); - break; - case KL_QUANTIZE: - kpu_quantize((const kpu_model_quantize_layer_argument_t *)layer_body, ctx); - break; - case KL_DEQUANTIZE: - kpu_kmodel_dequantize((const kpu_model_dequantize_layer_argument_t *)layer_body, ctx); - break; - case KL_REQUANTIZE: - kpu_requantize((const kpu_model_requantize_layer_argument_t *)layer_body, ctx); - break; - case KL_L2_NORMALIZATION: - kpu_l2_normalization((const kpu_model_l2_norm_layer_argument_t *)layer_body, ctx); - break; - case KL_SOFTMAX: - kpu_softmax((const kpu_model_softmax_layer_argument_t *)layer_body, ctx); - break; - case KL_CONCAT: - case KL_QUANTIZED_CONCAT: - kpu_concat((const kpu_model_concat_layer_argument_t *)layer_body, ctx); - break; - case KL_FULLY_CONNECTED: - kpu_kmodel_fully_connected((const kpu_model_fully_connected_layer_argument_t *)layer_body, ctx); - break; - case KL_TENSORFLOW_FLATTEN: - kpu_tf_flatten((const kpu_model_tf_flatten_layer_argument_t *)layer_body, ctx); - break; - case KL_K210_CONV: - kpu_conv((const kpu_model_conv_layer_argument_t *)layer_body, ctx); - return 0; - case KL_K210_ADD_PADDING: - kpu_add_padding((const kpu_model_add_padding_layer_argument_t *)layer_body, ctx); - break; - case KL_K210_REMOVE_PADDING: - kpu_remove_padding((const kpu_model_remove_padding_layer_argument_t *)layer_body, ctx); - break; - case KL_K210_UPLOAD: - kpu_upload((const kpu_model_upload_layer_argument_t *)layer_body, ctx); - break; - default: - assert(!"Layer is not supported."); - } - - if (cnt_layer_id != (ctx->layers_length - 1)) - ai_step(userdata); - else - kpu_kmodel_done(ctx); - return 0; -} - -static void ai_step_not_isr(void *userdata) -{ - sysctl_disable_irq(); - ai_step(userdata); - sysctl_enable_irq(); -} - -int kpu_run_kmodel(kpu_model_context_t *ctx, const uint8_t *src, dmac_channel_number_t dma_ch, kpu_done_callback_t done_callback, void *userdata) -{ - ctx->dma_ch = dma_ch; - ctx->done_callback = done_callback; - ctx->userdata = userdata; - ctx->current_layer = 0; - ctx->current_body = ctx->body_start; -#if KPU_DEBUG - last_time = 0; - total_time = 0; -#endif - - kpu_kmodel_header_t *header = (kpu_kmodel_header_t *)ctx->model_buffer; - kpu->interrupt_clear.reg = 7; - kpu->fifo_threshold.data = (kpu_config_fifo_threshold_t) - { - .fifo_full_threshold = 10, .fifo_empty_threshold = 1 - }; - kpu->eight_bit_mode.data = (kpu_config_eight_bit_mode_t) - { - .eight_bit_mode = header->flags & 1 - }; - kpu->interrupt_mask.data = (kpu_config_interrupt_t) - { - .calc_done_int = 1, - .layer_cfg_almost_empty_int = 0, - .layer_cfg_almost_full_int = 1 - }; - - plic_irq_enable(IRQN_AI_INTERRUPT); - plic_set_priority(IRQN_AI_INTERRUPT, 1); - plic_irq_register(IRQN_AI_INTERRUPT, ai_step, ctx); - - const kpu_model_layer_header_t *first_layer_header = ctx->layer_headers; - if (first_layer_header->type != KL_K210_CONV) - return -1; - const kpu_model_conv_layer_argument_t *first_layer = (const kpu_model_conv_layer_argument_t *)ctx->body_start; - kpu_layer_argument_t layer_arg = *(volatile kpu_layer_argument_t *)(ctx->model_buffer + first_layer->layer_offset); - - if ((layer_arg.image_size.data.i_row_wid + 1) % 64 != 0) - { - kpu_kmodel_input_with_padding(&layer_arg, src); - ai_step_not_isr(ctx); - } - else - { - kpu_input_dma(&layer_arg, src, ctx->dma_ch, ai_step, ctx); - } - - return 0; -} - - - - - - - - - - diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/plic.c b/cores/arduino/kendryte-standalone-sdk/lib/drivers/plic.c deleted file mode 100644 index 5fc1231..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/plic.c +++ /dev/null @@ -1,209 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include -#include -#include "encoding.h" -#include "plic.h" -#include "syscalls.h" -#include "syslog.h" - -volatile plic_t* const plic = (volatile plic_t*)PLIC_BASE_ADDR; - -static plic_instance_t plic_instance[PLIC_NUM_CORES][IRQN_MAX]; - -void plic_init(void) -{ - int i = 0; - - /* Get current core id */ - unsigned long core_id = current_coreid(); - - /* Disable all interrupts for the current core. */ - for (i = 0; i < ((PLIC_NUM_SOURCES + 32u) / 32u); i++) - plic->target_enables.target[core_id].enable[i] = 0; - - static uint8_t s_plic_priorities_init_flag = 0; - /* Set priorities to zero. */ - if(s_plic_priorities_init_flag == 0) - { - for (i = 0; i < PLIC_NUM_SOURCES; i++) - plic->source_priorities.priority[i] = 0; - s_plic_priorities_init_flag = 1; - } - - /* Set the threshold to zero. */ - plic->targets.target[core_id].priority_threshold = 0; - - /* Clear PLIC instance for every cores */ - for (i = 0; i < IRQN_MAX; i++) - { - /* clang-format off */ - plic_instance[core_id][i] = (const plic_instance_t){ - .callback = NULL, - .ctx = NULL, - }; - /* clang-format on */ - } - - /* - * A successful claim will also atomically clear the corresponding - * pending bit on the interrupt source. A target can perform a claim - * at any time, even if the EIP is not set. - */ - i = 0; - while (plic->targets.target[core_id].claim_complete > 0 && i < 100) - { - /* This loop will clear pending bit on the interrupt source */ - i++; - } - - /* Enable machine external interrupts. */ - set_csr(mie, MIP_MEIP); -} - -int plic_irq_enable(plic_irq_t irq_number) -{ - /* Check parameters */ - if (PLIC_NUM_SOURCES < irq_number || 0 > irq_number) - return -1; - unsigned long core_id = current_coreid(); - /* Get current enable bit array by IRQ number */ - uint32_t current = plic->target_enables.target[core_id].enable[irq_number / 32]; - /* Set enable bit in enable bit array */ - current |= (uint32_t)1 << (irq_number % 32); - /* Write back the enable bit array */ - plic->target_enables.target[core_id].enable[irq_number / 32] = current; - return 0; -} - -int plic_irq_disable(plic_irq_t irq_number) -{ - /* Check parameters */ - if (PLIC_NUM_SOURCES < irq_number || 0 > irq_number) - return -1; - unsigned long core_id = current_coreid(); - /* Get current enable bit array by IRQ number */ - uint32_t current = plic->target_enables.target[core_id].enable[irq_number / 32]; - /* Clear enable bit in enable bit array */ - current &= ~((uint32_t)1 << (irq_number % 32)); - /* Write back the enable bit array */ - plic->target_enables.target[core_id].enable[irq_number / 32] = current; - return 0; -} - -int plic_set_priority(plic_irq_t irq_number, uint32_t priority) -{ - /* Check parameters */ - if (PLIC_NUM_SOURCES < irq_number || 0 > irq_number) - return -1; - /* Set interrupt priority by IRQ number */ - plic->source_priorities.priority[irq_number] = priority; - return 0; -} - -uint32_t plic_get_priority(plic_irq_t irq_number) -{ - /* Check parameters */ - if (PLIC_NUM_SOURCES < irq_number || 0 > irq_number) - return 0; - /* Get interrupt priority by IRQ number */ - return plic->source_priorities.priority[irq_number]; -} - -uint32_t plic_irq_claim(void) -{ - unsigned long core_id = current_coreid(); - /* Perform IRQ claim */ - return plic->targets.target[core_id].claim_complete; -} - -int plic_irq_complete(uint32_t source) -{ - unsigned long core_id = current_coreid(); - /* Perform IRQ complete */ - plic->targets.target[core_id].claim_complete = source; - return 0; -} - -void plic_irq_register(plic_irq_t irq, plic_irq_callback_t callback, void *ctx) -{ - /* Read core id */ - unsigned long core_id = current_coreid(); - /* Set user callback function */ - plic_instance[core_id][irq].callback = callback; - /* Assign user context */ - plic_instance[core_id][irq].ctx = ctx; -} - -void plic_irq_unregister(plic_irq_t irq) -{ - /* Just assign NULL to user callback function and context */ - plic_irq_register(irq, NULL, NULL); -} - -void __attribute__((weak, alias("plic_irq_unregister"))) plic_irq_deregister(plic_irq_t irq); - -plic_instance_t (*plic_get_instance(void))[IRQN_MAX] -{ - return plic_instance; -} - -/*Entry Point for PLIC Interrupt Handler*/ -uintptr_t __attribute__((weak)) -handle_irq_m_ext(uintptr_t cause, uintptr_t epc) -{ - /* - * After the highest-priority pending interrupt is claimed by a target - * and the corresponding IP bit is cleared, other lower-priority - * pending interrupts might then become visible to the target, and so - * the PLIC EIP bit might not be cleared after a claim. The interrupt - * handler can check the local meip/heip/seip/ueip bits before exiting - * the handler, to allow more efficient service of other interrupts - * without first restoring the interrupted context and taking another - * interrupt trap. - */ - if (read_csr(mip) & MIP_MEIP) - { - /* Get current core id */ - uint64_t core_id = current_coreid(); - /* Get primitive interrupt enable flag */ - uint64_t ie_flag = read_csr(mie); - /* Get current IRQ num */ - uint32_t int_num = plic->targets.target[core_id].claim_complete; - /* Get primitive IRQ threshold */ - uint32_t int_threshold = plic->targets.target[core_id].priority_threshold; - /* Set new IRQ threshold = current IRQ threshold */ - plic->targets.target[core_id].priority_threshold = plic->source_priorities.priority[int_num]; - /* Disable software interrupt and timer interrupt */ - clear_csr(mie, MIP_MTIP | MIP_MSIP); - /* Enable global interrupt */ - set_csr(mstatus, MSTATUS_MIE); - if (plic_instance[core_id][int_num].callback) - plic_instance[core_id][int_num].callback( - plic_instance[core_id][int_num].ctx); - /* Perform IRQ complete */ - plic->targets.target[core_id].claim_complete = int_num; - /* Disable global interrupt */ - clear_csr(mstatus, MSTATUS_MIE); - /* Set MPIE and MPP flag used to MRET instructions restore MIE flag */ - set_csr(mstatus, MSTATUS_MPIE | MSTATUS_MPP); - /* Restore primitive interrupt enable flag */ - write_csr(mie, ie_flag); - /* Restore primitive IRQ threshold */ - plic->targets.target[core_id].priority_threshold = int_threshold; - } - - return epc; -} diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/pwm.c b/cores/arduino/kendryte-standalone-sdk/lib/drivers/pwm.c deleted file mode 100644 index 347324b..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/pwm.c +++ /dev/null @@ -1,58 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "timer.h" -#include "pwm.h" -#include "sysctl.h" -#include -#include "utils.h" -#include "plic.h" -#include "io.h" - -void pwm_init(pwm_device_number_t pwm_number) -{ - sysctl_clock_enable(SYSCTL_CLOCK_TIMER0 + pwm_number); -} - -void pwm_set_enable(pwm_device_number_t pwm_number, pwm_channel_number_t channel, int enable) -{ - if (enable) - { - if (timer[pwm_number]->channel[channel].load_count == 0) - timer[pwm_number]->channel[channel].load_count = 1; - if (timer[pwm_number]->load_count2[channel] == 0) - timer[pwm_number]->load_count2[channel] = 1; - timer[pwm_number]->channel[channel].control = TIMER_CR_INTERRUPT_MASK | TIMER_CR_PWM_ENABLE | TIMER_CR_USER_MODE | TIMER_CR_ENABLE; - } - else - { - timer[pwm_number]->channel[channel].control = TIMER_CR_INTERRUPT_MASK; - } -} - -double pwm_set_frequency(pwm_device_number_t pwm_number, pwm_channel_number_t channel, double frequency, double duty) -{ - uint32_t clk_freq = sysctl_clock_get_freq(SYSCTL_CLOCK_TIMER0 + pwm_number); - - int32_t periods = (int32_t)(clk_freq / frequency); - configASSERT(periods > 0 && periods <= INT32_MAX); - frequency = clk_freq / (double)periods; - - uint32_t percent = (uint32_t)(duty * periods); - timer[pwm_number]->channel[channel].load_count = periods - percent; - timer[pwm_number]->load_count2[channel] = percent; - - return frequency; -} - diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/rtc.c b/cores/arduino/kendryte-standalone-sdk/lib/drivers/rtc.c deleted file mode 100644 index 473069a..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/rtc.c +++ /dev/null @@ -1,587 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include -#include -#include -#include "encoding.h" -#include "sysctl.h" -#include "rtc.h" - -volatile rtc_t *const rtc = (volatile rtc_t *)RTC_BASE_ADDR; - -struct tm rtc_date_time; - -void rtc_timer_set_mode(rtc_timer_mode_t timer_mode) -{ - rtc_register_ctrl_t register_ctrl = rtc->register_ctrl; - - switch (timer_mode) - { - case RTC_TIMER_PAUSE: - register_ctrl.read_enable = 0; - register_ctrl.write_enable = 0; - break; - case RTC_TIMER_RUNNING: - register_ctrl.read_enable = 1; - register_ctrl.write_enable = 0; - break; - case RTC_TIMER_SETTING: - register_ctrl.read_enable = 0; - register_ctrl.write_enable = 1; - break; - default: - register_ctrl.read_enable = 0; - register_ctrl.write_enable = 0; - break; - } - rtc->register_ctrl = register_ctrl; -} - -rtc_timer_mode_t rtc_timer_get_mode(void) -{ - rtc_register_ctrl_t register_ctrl = rtc->register_ctrl; - rtc_timer_mode_t timer_mode = RTC_TIMER_PAUSE; - - if ((!register_ctrl.read_enable) && (!register_ctrl.write_enable)) - { - /* RTC_TIMER_PAUSE */ - timer_mode = RTC_TIMER_PAUSE; - } - else if ((register_ctrl.read_enable) && (!register_ctrl.write_enable)) - { - /* RTC_TIMER_RUNNING */ - timer_mode = RTC_TIMER_RUNNING; - } - else if ((!register_ctrl.read_enable) && (register_ctrl.write_enable)) { - /* RTC_TIMER_SETTING */ - timer_mode = RTC_TIMER_SETTING; - } - else - { - /* Something is error, reset timer mode */ - rtc_timer_set_mode(timer_mode); - } - - return timer_mode; -} - -static inline int rtc_in_range(int value, int min, int max) -{ - return ((value >= min) && (value <= max)); -} - -int rtc_timer_set_tm(const struct tm *tm) -{ - rtc_date_t timer_date; - rtc_time_t timer_time; - rtc_extended_t timer_extended; - - if (tm) - { - /* - * Range of tm->tm_sec could be [0,61] - * - * Range of tm->tm_sec allows for a positive leap second. Two - * leap seconds in the same minute are not allowed (the C90 - * range 0..61 was a defect) - */ - if (rtc_in_range(tm->tm_sec, 0, 59)) - timer_time.second = tm->tm_sec; - else - return -1; - - /* Range of tm->tm_min could be [0,59] */ - if (rtc_in_range(tm->tm_min, 0, 59)) - timer_time.minute = tm->tm_min; - else - return -1; - - /* Range of tm->tm_hour could be [0, 23] */ - if (rtc_in_range(tm->tm_hour, 0, 23)) - timer_time.hour = tm->tm_hour; - else - return -1; - - /* Range of tm->tm_mday could be [1, 31] */ - if (rtc_in_range(tm->tm_mday, 1, 31)) - timer_date.day = tm->tm_mday; - else - return -1; - - /* - * Range of tm->tm_mon could be [0, 11] - * But in this RTC, date.month should be [1, 12] - */ - if (rtc_in_range(tm->tm_mon, 0, 11)) - timer_date.month = tm->tm_mon + 1; - else - return -1; - - /* - * Range of tm->tm_year is the years since 1900 - * But in this RTC, year is split into year and century - * In this RTC, century range is [0,31], year range is [0,99] - */ - int human_year = tm->tm_year + 1900; - int rtc_year = human_year % 100; - int rtc_century = human_year / 100; - - if (rtc_in_range(rtc_year, 0, 99) && - rtc_in_range(rtc_century, 0, 31)) - { - timer_date.year = rtc_year; - timer_extended.century = rtc_century; - } - else - return -1; - - /* Range of tm->tm_wday could be [0, 6] */ - if (rtc_in_range(tm->tm_wday, 0, 6)) - timer_date.week = tm->tm_wday; - else - return -1; - - /* Set RTC mode to timer setting mode */ - rtc_timer_set_mode(RTC_TIMER_SETTING); - /* Write value to RTC */ - rtc->date = timer_date; - rtc->time = timer_time; - rtc->extended = timer_extended; - /* Get CPU current freq */ - unsigned long freq = sysctl_clock_get_freq(SYSCTL_CLOCK_CPU); - /* Set threshold to 1/26000000 s */ - freq = freq / 26000000; - /* Get current CPU cycle */ - unsigned long start_cycle = read_cycle(); - /* Wait for 1/26000000 s to sync data */ - while (read_cycle() - start_cycle < freq) - continue; - /* Set RTC mode to timer running mode */ - rtc_timer_set_mode(RTC_TIMER_RUNNING); - } - - return 0; -} - -int rtc_timer_set_alarm_tm(const struct tm *tm) -{ - rtc_alarm_date_t alarm_date; - rtc_alarm_time_t alarm_time; - - if (tm) { - /* - * Range of tm->tm_sec could be [0,61] - * - * Range of tm->tm_sec allows for a positive leap second. Two - * leap seconds in the same minute are not allowed (the C90 - * range 0..61 was a defect) - */ - if (rtc_in_range(tm->tm_sec, 0, 59)) - alarm_time.second = tm->tm_sec; - else - return -1; - - /* Range of tm->tm_min could be [0,59] */ - if (rtc_in_range(tm->tm_min, 0, 59)) - alarm_time.minute = tm->tm_min; - else - return -1; - - /* Range of tm->tm_hour could be [0, 23] */ - if (rtc_in_range(tm->tm_hour, 0, 23)) - alarm_time.hour = tm->tm_hour; - else - return -1; - - /* Range of tm->tm_mday could be [1, 31] */ - if (rtc_in_range(tm->tm_mday, 1, 31)) - alarm_date.day = tm->tm_mday; - else - return -1; - - /* - * Range of tm->tm_mon could be [0, 11] - * But in this RTC, date.month should be [1, 12] - */ - if (rtc_in_range(tm->tm_mon, 0, 11)) - alarm_date.month = tm->tm_mon + 1; - else - return -1; - - /* - * Range of tm->tm_year is the years since 1900 - * But in this RTC, year is split into year and century - * In this RTC, century range is [0,31], year range is [0,99] - */ - int human_year = tm->tm_year + 1900; - int rtc_year = human_year % 100; - int rtc_century = human_year / 100; - - if (rtc_in_range(rtc_year, 0, 99) && - rtc_in_range(rtc_century, 0, 31)) - { - alarm_date.year = rtc_year; - } else - return -1; - - /* Range of tm->tm_wday could be [0, 6] */ - if (rtc_in_range(tm->tm_wday, 0, 6)) - alarm_date.week = tm->tm_wday; - else - return -1; - - /* Write value to RTC */ - rtc->alarm_date = alarm_date; - rtc->alarm_time = alarm_time; - } - - return 0; -} - -static int rtc_year_is_leap(int year) -{ - return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0); -} - -static int rtc_get_yday(int year, int month, int day) -{ - static const int days[2][13] = - { - {0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334}, - {0, 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335} - }; - int leap = rtc_year_is_leap(year); - - return days[leap][month] + day; -} - -static int rtc_get_wday(int year, int month, int day) -{ - /* Magic method to get weekday */ - int weekday = (day += month < 3 ? year-- : year - 2, 23 * month / 9 + day + 4 + year / 4 - year / 100 + year / 400) % 7; - return weekday; -} - -struct tm *rtc_timer_get_tm(void) -{ - if (rtc_timer_get_mode() != RTC_TIMER_RUNNING) - return NULL; - - rtc_date_t timer_date = rtc->date; - rtc_time_t timer_time = rtc->time; - rtc_extended_t timer_extended = rtc->extended; - - struct tm *tm = &rtc_date_time; - - tm->tm_sec = timer_time.second % 60; - tm->tm_min = timer_time.minute % 60; - tm->tm_hour = timer_time.hour % 24; - tm->tm_mday = (timer_date.day - 1) % 31 + 1; - tm->tm_mon = (timer_date.month - 1)% 12; - tm->tm_year = (timer_date.year % 100) + (timer_extended.century * 100) - 1900; - tm->tm_wday = timer_date.week; - tm->tm_yday = rtc_get_yday(tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday); - tm->tm_isdst = -1; - - return tm; -} - -struct tm *rtc_timer_get_alarm_tm(void) -{ - if (rtc_timer_get_mode() != RTC_TIMER_RUNNING) - return NULL; - - rtc_alarm_date_t alarm_date = rtc->alarm_date; - rtc_alarm_time_t alarm_time = rtc->alarm_time; - rtc_extended_t timer_extended = rtc->extended; - - struct tm *tm = &rtc_date_time; - - tm->tm_sec = alarm_time.second % 60; - tm->tm_min = alarm_time.minute % 60; - tm->tm_hour = alarm_time.hour % 24; - tm->tm_mday = alarm_date.day % 31; - tm->tm_mon = (alarm_date.month % 12) - 1; - /* Alarm and Timer use same timer_extended.century */ - tm->tm_year = (alarm_date.year % 100) + (timer_extended.century * 100) - 1900; - tm->tm_wday = alarm_date.week; - tm->tm_yday = rtc_get_yday(tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday); - tm->tm_isdst = -1; - - return tm; -} - -int rtc_timer_set(int year, int month, int day, int hour, int minute, int second) -{ - struct tm date_time = - { - .tm_sec = second, - .tm_min = minute, - .tm_hour = hour, - .tm_mday = day, - .tm_mon = month - 1, - .tm_year = year - 1900, - .tm_wday = rtc_get_wday(year, month, day), - .tm_yday = rtc_get_yday(year, month, day), - .tm_isdst = -1, - }; - return rtc_timer_set_tm(&date_time); -} - -int rtc_timer_get(int *year, int *month, int *day, int *hour, int *minute, int *second) -{ - struct tm *tm = rtc_timer_get_tm(); - - if (tm) - { - if (year) - *year = tm->tm_year + 1900; - if (month) - *month = tm->tm_mon + 1; - if (day) - *day = tm->tm_mday; - if (hour) - *hour = tm->tm_hour; - if (minute) - *minute = tm->tm_min; - if (second) - *second = tm->tm_sec; - } else - return -1; - - return 0; -} - -int rtc_timer_set_alarm(int year, int month, int day, int hour, int minute, int second) -{ - struct tm date_time = { - .tm_sec = second, - .tm_min = minute, - .tm_hour = hour, - .tm_mday = day, - .tm_mon = month - 1, - .tm_year = year - 1900, - .tm_wday = rtc_get_wday(year, month, day), - .tm_yday = rtc_get_yday(year, month, day), - .tm_isdst = -1, - }; - - return rtc_timer_set_alarm_tm(&date_time); -} - -int rtc_timer_get_alarm(int *year, int *month, int *day, int *hour, int *minute, int *second) -{ - struct tm *tm = rtc_timer_get_alarm_tm(); - - if (tm) { - if (year) - *year = tm->tm_year + 1900; - if (month) - *month = tm->tm_mon + 1; - if (day) - *day = tm->tm_mday; - if (hour) - *hour = tm->tm_hour; - if (minute) - *minute = tm->tm_min; - if (second) - *second = tm->tm_sec; - } else - return -1; - - return 0; -} - -int rtc_timer_set_clock_frequency(unsigned int frequency) -{ - - rtc_initial_count_t initial_count; - - initial_count.count = frequency; - rtc_timer_set_mode(RTC_TIMER_SETTING); - rtc->initial_count = initial_count; - rtc_timer_set_mode(RTC_TIMER_RUNNING); - return 0; -} - -unsigned int rtc_timer_get_clock_frequency(void) -{ - return rtc->initial_count.count; -} - -int rtc_timer_set_clock_count_value(unsigned int count) -{ - - rtc_current_count_t current_count; - - current_count.count = count; - rtc_timer_set_mode(RTC_TIMER_SETTING); - rtc->current_count = current_count; - rtc_timer_set_mode(RTC_TIMER_RUNNING); - return 0; -} - -unsigned int rtc_timer_get_clock_count_value(void) -{ - return rtc->current_count.count; -} - -int rtc_tick_interrupt_set(int enable) -{ - rtc_interrupt_ctrl_t interrupt_ctrl = rtc->interrupt_ctrl; - interrupt_ctrl.tick_enable = enable; - rtc_timer_set_mode(RTC_TIMER_SETTING); - rtc->interrupt_ctrl = interrupt_ctrl; - rtc_timer_set_mode(RTC_TIMER_RUNNING); - return 0; -} - -int rtc_tick_interrupt_get(void) -{ - rtc_interrupt_ctrl_t interrupt_ctrl = rtc->interrupt_ctrl; - - return interrupt_ctrl.tick_enable; -} - -int rtc_tick_interrupt_mode_set(rtc_tick_interrupt_mode_t mode) -{ - rtc_interrupt_ctrl_t interrupt_ctrl = rtc->interrupt_ctrl; - - interrupt_ctrl.tick_int_mode = mode; - rtc_timer_set_mode(RTC_TIMER_SETTING); - rtc->interrupt_ctrl = interrupt_ctrl; - rtc_timer_set_mode(RTC_TIMER_RUNNING); - return 0; -} - -rtc_tick_interrupt_mode_t rtc_tick_interrupt_mode_get(void) -{ - rtc_interrupt_ctrl_t interrupt_ctrl = rtc->interrupt_ctrl; - - return interrupt_ctrl.tick_int_mode; -} - -int rtc_alarm_interrupt_set(int enable) -{ - rtc_interrupt_ctrl_t interrupt_ctrl = rtc->interrupt_ctrl; - - interrupt_ctrl.alarm_enable = enable; - rtc->interrupt_ctrl = interrupt_ctrl; - return 0; -} - -int rtc_alarm_interrupt_get(void) -{ - rtc_interrupt_ctrl_t interrupt_ctrl = rtc->interrupt_ctrl; - - return interrupt_ctrl.alarm_enable; -} - -int rtc_alarm_interrupt_mask_set(rtc_mask_t mask) -{ - rtc_interrupt_ctrl_t interrupt_ctrl = rtc->interrupt_ctrl; - - interrupt_ctrl.alarm_compare_mask = *(uint8_t *)&mask; - rtc->interrupt_ctrl = interrupt_ctrl; - return 0; -} - -rtc_mask_t rtc_alarm_interrupt_mask_get(void) -{ - rtc_interrupt_ctrl_t interrupt_ctrl = rtc->interrupt_ctrl; - - uint8_t compare_mask = interrupt_ctrl.alarm_compare_mask; - - return *(rtc_mask_t *)&compare_mask; -} - -int rtc_protect_set(int enable) -{ - rtc_register_ctrl_t register_ctrl = rtc->register_ctrl; - - rtc_mask_t mask = - { - .second = 1, - /* Second mask */ - .minute = 1, - /* Minute mask */ - .hour = 1, - /* Hour mask */ - .week = 1, - /* Week mask */ - .day = 1, - /* Day mask */ - .month = 1, - /* Month mask */ - .year = 1, - }; - - rtc_mask_t unmask = - { - .second = 0, - /* Second mask */ - .minute = 0, - /* Minute mask */ - .hour = 0, - /* Hour mask */ - .week = 0, - /* Week mask */ - .day = 0, - /* Day mask */ - .month = 0, - /* Month mask */ - .year = 0, - }; - - if (enable) - { - /* Turn RTC in protect mode, no one can write time */ - register_ctrl.timer_mask = *(uint8_t *)&unmask; - register_ctrl.alarm_mask = *(uint8_t *)&unmask; - register_ctrl.initial_count_mask = 0; - register_ctrl.interrupt_register_mask = 0; - } - else - { - /* Turn RTC in unprotect mode, everyone can write time */ - register_ctrl.timer_mask = *(uint8_t *)&mask; - register_ctrl.alarm_mask = *(uint8_t *)&mask; - register_ctrl.initial_count_mask = 1; - register_ctrl.interrupt_register_mask = 1; - } - rtc_timer_set_mode(RTC_TIMER_SETTING); - rtc->register_ctrl = register_ctrl; - rtc_timer_set_mode(RTC_TIMER_RUNNING); - return 0; -} - -int rtc_init(void) -{ - /* Reset RTC */ - sysctl_reset(SYSCTL_RESET_RTC); - /* Enable RTC */ - sysctl_clock_enable(SYSCTL_CLOCK_RTC); - /* Unprotect RTC */ - rtc_protect_set(0); - /* Set RTC clock frequency */ - rtc_timer_set_clock_frequency( - sysctl_clock_get_freq(SYSCTL_CLOCK_IN0) - ); - rtc_timer_set_clock_count_value(1); - - /* Set RTC mode to timer running mode */ - rtc_timer_set_mode(RTC_TIMER_RUNNING); - return 0; -} diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/sha256.c b/cores/arduino/kendryte-standalone-sdk/lib/drivers/sha256.c deleted file mode 100644 index 2200911..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/sha256.c +++ /dev/null @@ -1,120 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include -#include "sysctl.h" -#include "sha256.h" -#include "utils.h" - -#define ROTL(x, n) (((x) << (n)) | ((x) >> (32 - (n)))) -#define ROTR(x, n) (((x) >> (n)) | ((x) << (32 - (n)))) -#define BYTESWAP(x) ((ROTR((x), 8) & 0xff00ff00L) | (ROTL((x), 8) & 0x00ff00ffL)) -#define BYTESWAP64(x) byteswap64(x) - -volatile sha256_t* const sha256 = (volatile sha256_t*)SHA256_BASE_ADDR; -static const uint8_t padding[64] = -{ - 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 -}; - -static inline uint64_t byteswap64(uint64_t x) -{ - uint32_t a = (uint32_t)(x >> 32); - uint32_t b = (uint32_t)x; - return ((uint64_t)BYTESWAP(b) << 32) | (uint64_t)BYTESWAP(a); -} - -void sha256_init(sha256_context_t *context, size_t input_len) -{ - sysctl_clock_enable(SYSCTL_CLOCK_SHA); - sysctl_reset(SYSCTL_RESET_SHA); - - sha256->sha_num_reg.sha_data_cnt = (uint32_t)((input_len + SHA256_BLOCK_LEN + 8) / SHA256_BLOCK_LEN); - sha256->sha_function_reg_1.dma_en = 0x0; - sha256->sha_function_reg_0.sha_endian = SHA256_BIG_ENDIAN; - sha256->sha_function_reg_0.sha_en = ENABLE_SHA; - context->total_len = 0L; - context->buffer_len = 0L; -} - -void sha256_update(sha256_context_t *context, const void *input, size_t input_len) -{ - const uint8_t *data = input; - size_t buffer_bytes_left; - size_t bytes_to_copy; - uint32_t i; - - while (input_len) - { - buffer_bytes_left = SHA256_BLOCK_LEN - context->buffer_len; - bytes_to_copy = buffer_bytes_left; - if (bytes_to_copy > input_len) - bytes_to_copy = input_len; - memcpy(&context->buffer.bytes[context->buffer_len], data, bytes_to_copy); - context->total_len += bytes_to_copy * 8L; - context->buffer_len += bytes_to_copy; - data += bytes_to_copy; - input_len -= bytes_to_copy; - if (context->buffer_len == SHA256_BLOCK_LEN) - { - for (i = 0; i < 16; i++) - { - while (sha256->sha_function_reg_1.fifo_in_full) - ; - sha256->sha_data_in1 = context->buffer.words[i]; - } - context->buffer_len = 0L; - } - } -} - -void sha256_final(sha256_context_t *context, uint8_t *output) -{ - size_t bytes_to_pad; - size_t length_pad; - uint32_t i; - - bytes_to_pad = 120L - context->buffer_len; - if (bytes_to_pad > 64L) - bytes_to_pad -= 64L; - length_pad = BYTESWAP64(context->total_len); - sha256_update(context, padding, bytes_to_pad); - sha256_update(context, &length_pad, 8L); - while (!(sha256->sha_function_reg_0.sha_en)) - ; - if (output) - { - for (i = 0; i < SHA256_HASH_WORDS; i++) - { - *((uint32_t *)output) = sha256->sha_result[SHA256_HASH_WORDS - i - 1]; - output += 4; - } - } -} - -void sha256_hard_calculate(const uint8_t *input, size_t input_len, uint8_t *output) -{ - sha256_context_t sha; - sha256_init(&sha, input_len); - sha256_update(&sha, input, input_len); - sha256_final(&sha, output); -} - diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/spi.c b/cores/arduino/kendryte-standalone-sdk/lib/drivers/spi.c deleted file mode 100644 index 17df33f..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/spi.c +++ /dev/null @@ -1,1298 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "platform.h" -#include "spi.h" -#include "fpioa.h" -#include "utils.h" -#include "gpiohs.h" -#include "sysctl.h" -#include -#include - -volatile spi_t *const spi[4] = -{ - (volatile spi_t *)SPI0_BASE_ADDR, - (volatile spi_t *)SPI1_BASE_ADDR, - (volatile spi_t *)SPI_SLAVE_BASE_ADDR, - (volatile spi_t *)SPI3_BASE_ADDR -}; - -static spi_slave_instance_t g_instance; - -static spi_frame_format_t spi_get_frame_format(spi_device_num_t spi_num) -{ - uint8_t frf_offset; - switch(spi_num) - { - case 0: - case 1: - frf_offset = 21; - break; - case 2: - configASSERT(!"Spi Bus 2 Not Support!"); - break; - case 3: - default: - frf_offset = 22; - break; - } - volatile spi_t *spi_adapter = spi[spi_num]; - return ((spi_adapter->ctrlr0 >> frf_offset) & 0x3); -} - -static spi_transfer_width_t spi_get_frame_size(size_t data_bit_length) -{ - if (data_bit_length < 8) - return SPI_TRANS_CHAR; - else if (data_bit_length < 16) - return SPI_TRANS_SHORT; - return SPI_TRANS_INT; -} - -static int spi_clk_init(uint8_t spi_num) -{ - configASSERT(spi_num < SPI_DEVICE_MAX && spi_num != 2); - if(spi_num == 3) - sysctl_clock_set_clock_select(SYSCTL_CLOCK_SELECT_SPI3, 1); - sysctl_clock_enable(SYSCTL_CLOCK_SPI0 + spi_num); - sysctl_clock_set_threshold(SYSCTL_THRESHOLD_SPI0 + spi_num, 0); - return 0; -} - -static void spi_set_tmod(uint8_t spi_num, uint32_t tmod) -{ - configASSERT(spi_num < SPI_DEVICE_MAX); - volatile spi_t *spi_handle = spi[spi_num]; - uint8_t tmod_offset = 0; - switch(spi_num) - { - case 0: - case 1: - case 2: - tmod_offset = 8; - break; - case 3: - default: - tmod_offset = 10; - break; - } - set_bit(&spi_handle->ctrlr0, 3 << tmod_offset, tmod << tmod_offset); -} - -void spi_init(spi_device_num_t spi_num, spi_work_mode_t work_mode, spi_frame_format_t frame_format, - size_t data_bit_length, uint32_t endian) -{ - configASSERT(data_bit_length >= 4 && data_bit_length <= 32); - configASSERT(spi_num < SPI_DEVICE_MAX && spi_num != 2); - spi_clk_init(spi_num); - - uint8_t dfs_offset, frf_offset, work_mode_offset; - switch(spi_num) - { - case 0: - case 1: - dfs_offset = 16; - frf_offset = 21; - work_mode_offset = 6; - break; - case 2: - configASSERT(!"Spi Bus 2 Not Support!"); - break; - case 3: - default: - dfs_offset = 0; - frf_offset = 22; - work_mode_offset = 8; - break; - } - - switch (frame_format) - { - case SPI_FF_DUAL: - configASSERT(data_bit_length % 2 == 0); - break; - case SPI_FF_QUAD: - configASSERT(data_bit_length % 4 == 0); - break; - case SPI_FF_OCTAL: - configASSERT(data_bit_length % 8 == 0); - break; - default: - break; - } - volatile spi_t *spi_adapter = spi[spi_num]; - if(spi_adapter->baudr == 0) - spi_adapter->baudr = 0x14; - spi_adapter->imr = 0x00; - spi_adapter->dmacr = 0x00; - spi_adapter->dmatdlr = 0x10; - spi_adapter->dmardlr = 0x00; - spi_adapter->ser = 0x00; - spi_adapter->ssienr = 0x00; - spi_adapter->ctrlr0 = (work_mode << work_mode_offset) | (frame_format << frf_offset) | ((data_bit_length - 1) << dfs_offset); - spi_adapter->spi_ctrlr0 = 0; - spi_adapter->endian = endian; -} - -void spi_init_non_standard(spi_device_num_t spi_num, uint32_t instruction_length, uint32_t address_length, - uint32_t wait_cycles, spi_instruction_address_trans_mode_t instruction_address_trans_mode) -{ - configASSERT(wait_cycles < (1 << 5)); - configASSERT(instruction_address_trans_mode < 3); - configASSERT(spi_num < SPI_DEVICE_MAX && spi_num != 2); - volatile spi_t *spi_handle = spi[spi_num]; - uint32_t inst_l = 0; - switch (instruction_length) - { - case 0: - inst_l = 0; - break; - case 4: - inst_l = 1; - break; - case 8: - inst_l = 2; - break; - case 16: - inst_l = 3; - break; - default: - configASSERT(!"Invalid instruction length"); - break; - } - - configASSERT(address_length % 4 == 0 && address_length <= 60); - uint32_t addr_l = address_length / 4; - - spi_handle->spi_ctrlr0 = (wait_cycles << 11) | (inst_l << 8) | (addr_l << 2) | instruction_address_trans_mode; -} - -uint32_t spi_set_clk_rate(spi_device_num_t spi_num, uint32_t spi_clk) -{ - uint32_t spi_baudr = sysctl_clock_get_freq(SYSCTL_CLOCK_SPI0 + spi_num) / spi_clk; - if(spi_baudr < 2 ) - { - spi_baudr = 2; - } - else if(spi_baudr > 65534) - { - spi_baudr = 65534; - } - volatile spi_t *spi_adapter = spi[spi_num]; - spi_adapter->baudr = spi_baudr; - return sysctl_clock_get_freq(SYSCTL_CLOCK_SPI0 + spi_num) / spi_baudr; -} - -void spi_send_data_normal(spi_device_num_t spi_num, spi_chip_select_t chip_select, const uint8_t *tx_buff, size_t tx_len) -{ - configASSERT(spi_num < SPI_DEVICE_MAX && spi_num != 2); - - size_t index, fifo_len; - spi_set_tmod(spi_num, SPI_TMOD_TRANS); - - volatile spi_t *spi_handle = spi[spi_num]; - - uint8_t dfs_offset; - switch(spi_num) - { - case 0: - case 1: - dfs_offset = 16; - break; - case 2: - configASSERT(!"Spi Bus 2 Not Support!"); - break; - case 3: - default: - dfs_offset = 0; - break; - } - uint32_t data_bit_length = (spi_handle->ctrlr0 >> dfs_offset) & 0x1F; - spi_transfer_width_t frame_width = spi_get_frame_size(data_bit_length); - - spi_handle->ssienr = 0x01; - spi_handle->ser = 1U << chip_select; - uint32_t i = 0; - while (tx_len) - { - fifo_len = 32 - spi_handle->txflr; - fifo_len = fifo_len < tx_len ? fifo_len : tx_len; - switch(frame_width) - { - case SPI_TRANS_INT: - fifo_len = fifo_len / 4 * 4; - for (index = 0; index < fifo_len / 4; index++) - spi_handle->dr[0] = ((uint32_t *)tx_buff)[i++]; - break; - case SPI_TRANS_SHORT: - fifo_len = fifo_len / 2 * 2; - for (index = 0; index < fifo_len / 2; index++) - spi_handle->dr[0] = ((uint16_t *)tx_buff)[i++]; - break; - default: - for (index = 0; index < fifo_len; index++) - spi_handle->dr[0] = tx_buff[i++]; - break; - } - tx_len -= fifo_len; - } - while ((spi_handle->sr & 0x05) != 0x04) - ; - spi_handle->ser = 0x00; - spi_handle->ssienr = 0x00; - -} - -void spi_send_data_standard(spi_device_num_t spi_num, spi_chip_select_t chip_select, const uint8_t *cmd_buff, - size_t cmd_len, const uint8_t *tx_buff, size_t tx_len) -{ - configASSERT(spi_num < SPI_DEVICE_MAX && spi_num != 2); - uint8_t *v_buf = malloc(cmd_len + tx_len); - size_t i; - for(i = 0; i < cmd_len; i++) - v_buf[i] = cmd_buff[i]; - for(i = 0; i < tx_len; i++) - v_buf[cmd_len + i] = tx_buff[i]; - - spi_send_data_normal(spi_num, chip_select, v_buf, cmd_len + tx_len); - free((void *)v_buf); -} - -void spi_send_data_standard_dma(dmac_channel_number_t channel_num, spi_device_num_t spi_num, - spi_chip_select_t chip_select, - const uint8_t *cmd_buff, size_t cmd_len, const uint8_t *tx_buff, size_t tx_len) -{ - configASSERT(spi_num < SPI_DEVICE_MAX && spi_num != 2); - - volatile spi_t *spi_handle = spi[spi_num]; - - uint8_t dfs_offset; - switch(spi_num) - { - case 0: - case 1: - dfs_offset = 16; - break; - case 2: - configASSERT(!"Spi Bus 2 Not Support!"); - break; - case 3: - default: - dfs_offset = 0; - break; - } - uint32_t data_bit_length = (spi_handle->ctrlr0 >> dfs_offset) & 0x1F; - spi_transfer_width_t frame_width = spi_get_frame_size(data_bit_length); - - uint32_t *buf; - size_t v_send_len; - int i; - switch(frame_width) - { - case SPI_TRANS_INT: - buf = malloc(cmd_len + tx_len); - for(i = 0; i < cmd_len / 4; i++) - buf[i] = ((uint32_t *)cmd_buff)[i]; - for(i = 0; i < tx_len / 4; i++) - buf[cmd_len / 4 + i] = ((uint32_t *)tx_buff)[i]; - v_send_len = (cmd_len + tx_len) / 4; - break; - case SPI_TRANS_SHORT: - buf = malloc((cmd_len + tx_len) / 2 * sizeof(uint32_t)); - for(i = 0; i < cmd_len / 2; i++) - buf[i] = ((uint16_t *)cmd_buff)[i]; - for(i = 0; i < tx_len / 2; i++) - buf[cmd_len / 2 + i] = ((uint16_t *)tx_buff)[i]; - v_send_len = (cmd_len + tx_len) / 2; - break; - default: - buf = malloc((cmd_len + tx_len) * sizeof(uint32_t)); - for(i = 0; i < cmd_len; i++) - buf[i] = cmd_buff[i]; - for(i = 0; i < tx_len; i++) - buf[cmd_len + i] = tx_buff[i]; - v_send_len = cmd_len + tx_len; - break; - } - - spi_send_data_normal_dma(channel_num, spi_num, chip_select, buf, v_send_len, SPI_TRANS_INT); - - free((void *)buf); -} - -void spi_send_data_normal_dma(dmac_channel_number_t channel_num, spi_device_num_t spi_num, - spi_chip_select_t chip_select, - const void *tx_buff, size_t tx_len, spi_transfer_width_t spi_transfer_width) -{ - configASSERT(spi_num < SPI_DEVICE_MAX && spi_num != 2); - spi_set_tmod(spi_num, SPI_TMOD_TRANS); - volatile spi_t *spi_handle = spi[spi_num]; - uint32_t *buf; - int i; - switch(spi_transfer_width) - { - case SPI_TRANS_SHORT: - buf = malloc((tx_len) * sizeof(uint32_t)); - for(i = 0; i < tx_len; i++) - buf[i] = ((uint16_t *)tx_buff)[i]; - break; - case SPI_TRANS_INT: - buf = (uint32_t *)tx_buff; - break; - case SPI_TRANS_CHAR: - default: - buf = malloc((tx_len) * sizeof(uint32_t)); - for(i = 0; i < tx_len; i++) - buf[i] = ((uint8_t *)tx_buff)[i]; - break; - } - spi_handle->dmacr = 0x2; /*enable dma transmit*/ - spi_handle->ssienr = 0x01; - - sysctl_dma_select((sysctl_dma_channel_t) channel_num, SYSCTL_DMA_SELECT_SSI0_TX_REQ + spi_num * 2); - dmac_set_single_mode(channel_num, buf, (void *)(&spi_handle->dr[0]), DMAC_ADDR_INCREMENT, DMAC_ADDR_NOCHANGE, - DMAC_MSIZE_4, DMAC_TRANS_WIDTH_32, tx_len); - spi_handle->ser = 1U << chip_select; - dmac_wait_done(channel_num); - if(spi_transfer_width != SPI_TRANS_INT) - free((void *)buf); - - while ((spi_handle->sr & 0x05) != 0x04) - ; - spi_handle->ser = 0x00; - spi_handle->ssienr = 0x00; -} - -void spi_dup_send_receive_data_dma(dmac_channel_number_t dma_send_channel_num, - dmac_channel_number_t dma_receive_channel_num, - spi_device_num_t spi_num, spi_chip_select_t chip_select, - const uint8_t *tx_buf, size_t tx_len, uint8_t *rx_buf, size_t rx_len) -{ - spi_set_tmod(spi_num, SPI_TMOD_TRANS_RECV); - volatile spi_t *spi_handle = spi[spi_num]; - - uint8_t dfs_offset; - switch(spi_num) - { - case 0: - case 1: - dfs_offset = 16; - break; - case 2: - configASSERT(!"Spi Bus 2 Not Support!"); - break; - case 3: - default: - dfs_offset = 0; - break; - } - uint32_t data_bit_length = (spi_handle->ctrlr0 >> dfs_offset) & 0x1F; - spi_transfer_width_t frame_width = spi_get_frame_size(data_bit_length); - size_t v_tx_len = tx_len / frame_width; - size_t v_rx_len = rx_len / frame_width; - - size_t v_max_len = v_tx_len > v_rx_len ? v_tx_len : v_rx_len; - - uint32_t *v_tx_buf = malloc(v_max_len * 4); - uint32_t *v_rx_buf = malloc(v_max_len * 4); - uint32_t i = 0; - switch(frame_width) - { - case SPI_TRANS_INT: - for(i = 0; i < v_tx_len; i++) - { - v_tx_buf[i] = ((uint32_t *)tx_buf)[i]; - } - if(v_max_len > v_tx_len) - { - while(i < v_max_len) - { - v_tx_buf[i++] = 0xFFFFFFFF; - } - } - break; - case SPI_TRANS_SHORT: - for(i = 0; i < v_tx_len; i++) - { - v_tx_buf[i] = ((uint16_t *)tx_buf)[i]; - } - if(v_max_len > v_tx_len) - { - while(i < v_max_len) - { - v_tx_buf[i++] = 0xFFFFFFFF; - } - } - break; - default: - for(i = 0; i < v_tx_len; i++) - { - v_tx_buf[i] = tx_buf[i]; - } - if(v_max_len > v_tx_len) - { - while(i < v_max_len) - { - v_tx_buf[i++] = 0xFFFFFFFF; - } - } - break; - } - - spi_handle->dmacr = 0x3; - spi_handle->ssienr = 0x01; - - sysctl_dma_select((sysctl_dma_channel_t)dma_send_channel_num, SYSCTL_DMA_SELECT_SSI0_TX_REQ + spi_num * 2); - sysctl_dma_select((sysctl_dma_channel_t)dma_receive_channel_num, SYSCTL_DMA_SELECT_SSI0_RX_REQ + spi_num * 2); - - dmac_set_single_mode(dma_receive_channel_num, (void *)(&spi_handle->dr[0]), v_rx_buf, DMAC_ADDR_NOCHANGE, DMAC_ADDR_INCREMENT, - DMAC_MSIZE_1, DMAC_TRANS_WIDTH_32, v_max_len); - - dmac_set_single_mode(dma_send_channel_num, v_tx_buf, (void *)(&spi_handle->dr[0]), DMAC_ADDR_INCREMENT, DMAC_ADDR_NOCHANGE, - DMAC_MSIZE_4, DMAC_TRANS_WIDTH_32, v_max_len); - - spi_handle->ser = 1U << chip_select; - dmac_wait_done(dma_send_channel_num); - dmac_wait_done(dma_receive_channel_num); - - spi_handle->ser = 0x00; - spi_handle->ssienr = 0x00; - - switch(frame_width) - { - case SPI_TRANS_INT: - for(i = 0; i < v_rx_len; i++) - ((uint32_t *)rx_buf)[i] = v_rx_buf[i]; - break; - case SPI_TRANS_SHORT: - for(i = 0; i < v_rx_len; i++) - ((uint16_t *)rx_buf)[i] = v_rx_buf[i]; - break; - default: - for(i = 0; i < v_rx_len; i++) - rx_buf[i] = v_rx_buf[i]; - break; - } - free(v_tx_buf); - free(v_rx_buf); -} - -void spi_receive_data_standard(spi_device_num_t spi_num, spi_chip_select_t chip_select, const uint8_t *cmd_buff, - size_t cmd_len, uint8_t *rx_buff, size_t rx_len) -{ - configASSERT(spi_num < SPI_DEVICE_MAX && spi_num != 2); - size_t index, fifo_len; - if(cmd_len == 0) - spi_set_tmod(spi_num, SPI_TMOD_RECV); - else - spi_set_tmod(spi_num, SPI_TMOD_EEROM); - volatile spi_t *spi_handle = spi[spi_num]; - - uint8_t dfs_offset; - switch(spi_num) - { - case 0: - case 1: - dfs_offset = 16; - break; - case 2: - configASSERT(!"Spi Bus 2 Not Support!"); - break; - case 3: - default: - dfs_offset = 0; - break; - } - uint32_t data_bit_length = (spi_handle->ctrlr0 >> dfs_offset) & 0x1F; - spi_transfer_width_t frame_width = spi_get_frame_size(data_bit_length); - - uint32_t i = 0; - size_t v_cmd_len = cmd_len / frame_width; - uint32_t v_rx_len = rx_len / frame_width; - - spi_handle->ctrlr1 = (uint32_t)(v_rx_len - 1); - spi_handle->ssienr = 0x01; - - while (v_cmd_len) - { - fifo_len = 32 - spi_handle->txflr; - fifo_len = fifo_len < v_cmd_len ? fifo_len : v_cmd_len; - switch(frame_width) - { - case SPI_TRANS_INT: - for (index = 0; index < fifo_len; index++) - spi_handle->dr[0] = ((uint32_t *)cmd_buff)[i++]; - break; - case SPI_TRANS_SHORT: - for (index = 0; index < fifo_len; index++) - spi_handle->dr[0] = ((uint16_t *)cmd_buff)[i++]; - break; - default: - for (index = 0; index < fifo_len; index++) - spi_handle->dr[0] = cmd_buff[i++]; - break; - } - spi_handle->ser = 1U << chip_select; - v_cmd_len -= fifo_len; - } - - if(cmd_len == 0) - { - spi_handle->dr[0] = 0xffffffff; - spi_handle->ser = 1U << chip_select; - } - - i = 0; - while (v_rx_len) - { - fifo_len = spi_handle->rxflr; - fifo_len = fifo_len < v_rx_len ? fifo_len : v_rx_len; - switch(frame_width) - { - case SPI_TRANS_INT: - for (index = 0; index < fifo_len; index++) - ((uint32_t *)rx_buff)[i++] = spi_handle->dr[0]; - break; - case SPI_TRANS_SHORT: - for (index = 0; index < fifo_len; index++) - ((uint16_t *)rx_buff)[i++] = (uint16_t)spi_handle->dr[0]; - break; - default: - for (index = 0; index < fifo_len; index++) - rx_buff[i++] = (uint8_t)spi_handle->dr[0]; - break; - } - - v_rx_len -= fifo_len; - } - - spi_handle->ser = 0x00; - spi_handle->ssienr = 0x00; -} - -void spi_receive_data_normal_dma(dmac_channel_number_t dma_send_channel_num, - dmac_channel_number_t dma_receive_channel_num, - spi_device_num_t spi_num, spi_chip_select_t chip_select, const void *cmd_buff, - size_t cmd_len, void *rx_buff, size_t rx_len) -{ - configASSERT(spi_num < SPI_DEVICE_MAX && spi_num != 2); - - if(cmd_len == 0) - spi_set_tmod(spi_num, SPI_TMOD_RECV); - else - spi_set_tmod(spi_num, SPI_TMOD_EEROM); - - volatile spi_t *spi_handle = spi[spi_num]; - - spi_handle->ctrlr1 = (uint32_t)(rx_len - 1); - spi_handle->dmacr = 0x3; - spi_handle->ssienr = 0x01; - if(cmd_len) - sysctl_dma_select((sysctl_dma_channel_t)dma_send_channel_num, SYSCTL_DMA_SELECT_SSI0_TX_REQ + spi_num * 2); - sysctl_dma_select((sysctl_dma_channel_t)dma_receive_channel_num, SYSCTL_DMA_SELECT_SSI0_RX_REQ + spi_num * 2); - - dmac_set_single_mode(dma_receive_channel_num, (void *)(&spi_handle->dr[0]), rx_buff, DMAC_ADDR_NOCHANGE, DMAC_ADDR_INCREMENT, - DMAC_MSIZE_1, DMAC_TRANS_WIDTH_32, rx_len); - if(cmd_len) - dmac_set_single_mode(dma_send_channel_num, cmd_buff, (void *)(&spi_handle->dr[0]), DMAC_ADDR_INCREMENT, DMAC_ADDR_NOCHANGE, - DMAC_MSIZE_4, DMAC_TRANS_WIDTH_32, cmd_len); - if(cmd_len == 0 && spi_get_frame_format(spi_num) == SPI_FF_STANDARD) - spi[spi_num]->dr[0] = 0xffffffff; - spi_handle->ser = 1U << chip_select; - if(cmd_len) - dmac_wait_done(dma_send_channel_num); - dmac_wait_done(dma_receive_channel_num); - - spi_handle->ser = 0x00; - spi_handle->ssienr = 0x00; -} - - -void spi_receive_data_standard_dma(dmac_channel_number_t dma_send_channel_num, - dmac_channel_number_t dma_receive_channel_num, - spi_device_num_t spi_num, spi_chip_select_t chip_select, const uint8_t *cmd_buff, - size_t cmd_len, uint8_t *rx_buff, size_t rx_len) -{ - configASSERT(spi_num < SPI_DEVICE_MAX && spi_num != 2); - volatile spi_t *spi_handle = spi[spi_num]; - - uint8_t dfs_offset; - switch(spi_num) - { - case 0: - case 1: - dfs_offset = 16; - break; - case 2: - configASSERT(!"Spi Bus 2 Not Support!"); - break; - case 3: - default: - dfs_offset = 0; - break; - } - uint32_t data_bit_length = (spi_handle->ctrlr0 >> dfs_offset) & 0x1F; - spi_transfer_width_t frame_width = spi_get_frame_size(data_bit_length); - - size_t i; - - uint32_t *write_cmd; - uint32_t *read_buf; - size_t v_recv_len; - size_t v_cmd_len; - switch(frame_width) - { - case SPI_TRANS_INT: - write_cmd = malloc(cmd_len + rx_len); - for(i = 0; i < cmd_len / 4; i++) - write_cmd[i] = ((uint32_t *)cmd_buff)[i]; - read_buf = &write_cmd[i]; - v_recv_len = rx_len / 4; - v_cmd_len = cmd_len / 4; - break; - case SPI_TRANS_SHORT: - write_cmd = malloc((cmd_len + rx_len) /2 * sizeof(uint32_t)); - for(i = 0; i < cmd_len / 2; i++) - write_cmd[i] = ((uint16_t *)cmd_buff)[i]; - read_buf = &write_cmd[i]; - v_recv_len = rx_len / 2; - v_cmd_len = cmd_len / 2; - break; - default: - write_cmd = malloc((cmd_len + rx_len) * sizeof(uint32_t)); - for(i = 0; i < cmd_len; i++) - write_cmd[i] = cmd_buff[i]; - read_buf = &write_cmd[i]; - v_recv_len = rx_len; - v_cmd_len = cmd_len; - break; - } - - spi_receive_data_normal_dma(dma_send_channel_num, dma_receive_channel_num, spi_num, chip_select, write_cmd, v_cmd_len, read_buf, v_recv_len); - - switch(frame_width) - { - case SPI_TRANS_INT: - for(i = 0; i < v_recv_len; i++) - ((uint32_t *)rx_buff)[i] = read_buf[i]; - break; - case SPI_TRANS_SHORT: - for(i = 0; i < v_recv_len; i++) - ((uint16_t *)rx_buff)[i] = read_buf[i]; - break; - default: - for(i = 0; i < v_recv_len; i++) - rx_buff[i] = read_buf[i]; - break; - } - - free(write_cmd); -} - - -void spi_receive_data_multiple(spi_device_num_t spi_num, spi_chip_select_t chip_select, const uint32_t *cmd_buff, - size_t cmd_len, uint8_t *rx_buff, size_t rx_len) -{ - configASSERT(spi_num < SPI_DEVICE_MAX && spi_num != 2); - - size_t index, fifo_len; - if(cmd_len == 0) - spi_set_tmod(spi_num, SPI_TMOD_RECV); - else - spi_set_tmod(spi_num, SPI_TMOD_EEROM); - volatile spi_t *spi_handle = spi[spi_num]; - - uint8_t dfs_offset; - switch(spi_num) - { - case 0: - case 1: - dfs_offset = 16; - break; - case 2: - configASSERT(!"Spi Bus 2 Not Support!"); - break; - case 3: - default: - dfs_offset = 0; - break; - } - uint32_t data_bit_length = (spi_handle->ctrlr0 >> dfs_offset) & 0x1F; - spi_transfer_width_t frame_width = spi_get_frame_size(data_bit_length); - - uint32_t v_cmd_len = cmd_len; - uint32_t i = 0; - - uint32_t v_rx_len = rx_len / frame_width; - - spi_handle->ctrlr1 = (uint32_t)(v_rx_len - 1); - spi_handle->ssienr = 0x01; - - while (v_cmd_len) - { - fifo_len = 32 - spi_handle->txflr; - fifo_len = fifo_len < v_cmd_len ? fifo_len : v_cmd_len; - - for (index = 0; index < fifo_len; index++) - spi_handle->dr[0] = *cmd_buff++; - - spi_handle->ser = 1U << chip_select; - v_cmd_len -= fifo_len; - } - - if(cmd_len == 0) - { - spi_handle->ser = 1U << chip_select; - } - - while (v_rx_len) - { - fifo_len = spi_handle->rxflr; - fifo_len = fifo_len < v_rx_len ? fifo_len : v_rx_len; - switch(frame_width) - { - case SPI_TRANS_INT: - for (index = 0; index < fifo_len; index++) - ((uint32_t *)rx_buff)[i++] = spi_handle->dr[0]; - break; - case SPI_TRANS_SHORT: - for (index = 0; index < fifo_len; index++) - ((uint16_t *)rx_buff)[i++] = (uint16_t)spi_handle->dr[0]; - - break; - default: - for (index = 0; index < fifo_len; index++) - rx_buff[i++] = (uint8_t)spi_handle->dr[0]; - break; - } - - v_rx_len -= fifo_len; - } - - spi_handle->ser = 0x00; - spi_handle->ssienr = 0x00; - -} - -void spi_receive_data_multiple_dma(dmac_channel_number_t dma_send_channel_num, - dmac_channel_number_t dma_receive_channel_num, - spi_device_num_t spi_num, spi_chip_select_t chip_select, const uint32_t *cmd_buff, - size_t cmd_len, uint8_t *rx_buff, size_t rx_len) -{ - configASSERT(spi_num < SPI_DEVICE_MAX && spi_num != 2); - - volatile spi_t *spi_handle = spi[spi_num]; - - uint8_t dfs_offset; - switch(spi_num) - { - case 0: - case 1: - dfs_offset = 16; - break; - case 2: - configASSERT(!"Spi Bus 2 Not Support!"); - break; - case 3: - default: - dfs_offset = 0; - break; - } - uint32_t data_bit_length = (spi_handle->ctrlr0 >> dfs_offset) & 0x1F; - spi_transfer_width_t frame_width = spi_get_frame_size(data_bit_length); - - size_t i; - - uint32_t *write_cmd; - uint32_t *read_buf; - size_t v_recv_len; - switch(frame_width) - { - case SPI_TRANS_INT: - write_cmd = malloc(cmd_len + rx_len); - for(i = 0; i < cmd_len; i++) - write_cmd[i] = cmd_buff[i]; - read_buf = &write_cmd[i]; - v_recv_len = rx_len / 4; - break; - case SPI_TRANS_SHORT: - write_cmd = malloc(cmd_len + rx_len /2 * sizeof(uint32_t)); - for(i = 0; i < cmd_len; i++) - write_cmd[i] = cmd_buff[i]; - read_buf = &write_cmd[i]; - v_recv_len = rx_len / 2; - break; - default: - write_cmd = malloc(cmd_len + rx_len * sizeof(uint32_t)); - for(i = 0; i < cmd_len; i++) - write_cmd[i] = cmd_buff[i]; - read_buf = &write_cmd[i]; - v_recv_len = rx_len; - break; - } - - spi_receive_data_normal_dma(dma_send_channel_num, dma_receive_channel_num, spi_num, chip_select, write_cmd, cmd_len, read_buf, v_recv_len); - - switch(frame_width) - { - case SPI_TRANS_INT: - for(i = 0; i < v_recv_len; i++) - ((uint32_t *)rx_buff)[i] = read_buf[i]; - break; - case SPI_TRANS_SHORT: - for(i = 0; i < v_recv_len; i++) - ((uint16_t *)rx_buff)[i] = read_buf[i]; - break; - default: - for(i = 0; i < v_recv_len; i++) - rx_buff[i] = read_buf[i]; - break; - } - - free(write_cmd); -} - - -void spi_send_data_multiple(spi_device_num_t spi_num, spi_chip_select_t chip_select, const uint32_t *cmd_buff, - size_t cmd_len, const uint8_t *tx_buff, size_t tx_len) -{ - configASSERT(spi_num < SPI_DEVICE_MAX && spi_num != 2); - - size_t index, fifo_len; - spi_set_tmod(spi_num, SPI_TMOD_TRANS); - volatile spi_t *spi_handle = spi[spi_num]; - spi_handle->ssienr = 0x01; - spi_handle->ser = 1U << chip_select; - - size_t v_cmd_len = cmd_len * 4; - while(v_cmd_len) - { - fifo_len = 32 - spi_handle->txflr; - fifo_len = fifo_len < v_cmd_len ? fifo_len : v_cmd_len; - fifo_len = fifo_len / 4 * 4; - for (index = 0; index < fifo_len / 4; index++) - spi_handle->dr[0] = *cmd_buff++; - v_cmd_len -= fifo_len; - } - spi_send_data_normal(spi_num, chip_select, tx_buff, tx_len); -} - -void spi_send_data_multiple_dma(dmac_channel_number_t channel_num, spi_device_num_t spi_num, - spi_chip_select_t chip_select, - const uint32_t *cmd_buff, size_t cmd_len, const uint8_t *tx_buff, size_t tx_len) -{ - configASSERT(spi_num < SPI_DEVICE_MAX && spi_num != 2); - volatile spi_t *spi_handle = spi[spi_num]; - - uint8_t dfs_offset; - switch(spi_num) - { - case 0: - case 1: - dfs_offset = 16; - break; - case 2: - configASSERT(!"Spi Bus 2 Not Support!"); - break; - case 3: - default: - dfs_offset = 0; - break; - } - uint32_t data_bit_length = (spi_handle->ctrlr0 >> dfs_offset) & 0x1F; - spi_transfer_width_t frame_width = spi_get_frame_size(data_bit_length); - - uint32_t *buf; - size_t v_send_len; - int i; - switch(frame_width) - { - case SPI_TRANS_INT: - buf = malloc(cmd_len * sizeof(uint32_t) + tx_len); - for(i = 0; i < cmd_len; i++) - buf[i] = cmd_buff[i]; - for(i = 0; i < tx_len / 4; i++) - buf[cmd_len + i] = ((uint32_t *)tx_buff)[i]; - v_send_len = cmd_len + tx_len / 4; - break; - case SPI_TRANS_SHORT: - buf = malloc(cmd_len * sizeof(uint32_t) + tx_len / 2 * sizeof(uint32_t)); - for(i = 0; i < cmd_len; i++) - buf[i] = cmd_buff[i]; - for(i = 0; i < tx_len / 2; i++) - buf[cmd_len + i] = ((uint16_t *)tx_buff)[i]; - v_send_len = cmd_len + tx_len / 2; - break; - default: - buf = malloc((cmd_len + tx_len) * sizeof(uint32_t)); - for(i = 0; i < cmd_len; i++) - buf[i] = cmd_buff[i]; - for(i = 0; i < tx_len; i++) - buf[cmd_len + i] = tx_buff[i]; - v_send_len = cmd_len + tx_len; - break; - } - - spi_send_data_normal_dma(channel_num, spi_num, chip_select, buf, v_send_len, SPI_TRANS_INT); - - free((void *)buf); -} - -void spi_fill_data_dma(dmac_channel_number_t channel_num, spi_device_num_t spi_num, spi_chip_select_t chip_select, - const uint32_t *tx_buff, size_t tx_len) -{ - configASSERT(spi_num < SPI_DEVICE_MAX && spi_num != 2); - - spi_set_tmod(spi_num, SPI_TMOD_TRANS); - volatile spi_t *spi_handle = spi[spi_num]; - spi_handle->dmacr = 0x2; /*enable dma transmit*/ - spi_handle->ssienr = 0x01; - - sysctl_dma_select((sysctl_dma_channel_t)channel_num, SYSCTL_DMA_SELECT_SSI0_TX_REQ + spi_num * 2); - dmac_set_single_mode(channel_num, tx_buff, (void *)(&spi_handle->dr[0]), DMAC_ADDR_NOCHANGE, DMAC_ADDR_NOCHANGE, - DMAC_MSIZE_1, DMAC_TRANS_WIDTH_32, tx_len); - spi_handle->ser = 1U << chip_select; - dmac_wait_done(channel_num); - - while ((spi_handle->sr & 0x05) != 0x04) - ; - spi_handle->ser = 0x00; - spi_handle->ssienr = 0x00; -} - -static int spi_slave_irq(void *ctx) -{ - volatile spi_t *spi_handle = spi[2]; - - spi_handle->imr = 0x00; - *(volatile uint32_t *)(spi_handle->icr); - if (g_instance.status == IDLE) - g_instance.status = COMMAND; - return 0; -} - -static void spi_slave_idle_mode(void) -{ - volatile spi_t *spi_handle = spi[2]; - uint32_t data_width = g_instance.data_bit_length / 8; - g_instance.status = IDLE; - spi_handle->ssienr = 0x00; - spi_handle->ctrlr0 = (0x0 << g_instance.work_mode) | (0x1 << g_instance.slv_oe) | ((g_instance.data_bit_length - 1) << g_instance.dfs); - spi_handle->rxftlr = 0x08 / data_width - 1; - - spi_handle->dmacr = 0x00; - spi_handle->imr = 0x10; - spi_handle->ssienr = 0x01; - gpiohs_set_pin(g_instance.ready_pin, GPIO_PV_HIGH); -} - -static void spi_slave_command_mode(void) -{ - volatile spi_t *spi_handle = spi[2]; - uint8_t cmd_data[8], sum = 0; - - spi_transfer_width_t frame_width = spi_get_frame_size(g_instance.data_bit_length - 1); - uint32_t data_width = g_instance.data_bit_length / 8; - spi_device_num_t spi_num = SPI_DEVICE_2; - switch(frame_width) - { - case SPI_TRANS_INT: - for (uint32_t i = 0; i < 8 / 4; i++) - ((uint32_t *)cmd_data)[i] = spi_handle->dr[0]; - break; - case SPI_TRANS_SHORT: - for (uint32_t i = 0; i < 8 / 2; i++) - ((uint16_t *)cmd_data)[i] = spi_handle->dr[0]; - break; - default: - for (uint32_t i = 0; i < 8; i++) - cmd_data[i] = spi_handle->dr[0]; - break; - } - - for (uint32_t i = 0; i < 7; i++) - { - sum += cmd_data[i]; - } - if (cmd_data[7] != sum) - { - spi_slave_idle_mode(); - return; - } - g_instance.command.cmd = cmd_data[0]; - g_instance.command.addr = cmd_data[1] | (cmd_data[2] << 8) | (cmd_data[3] << 16) | (cmd_data[4] << 24); - g_instance.command.len = cmd_data[5] | (cmd_data[6] << 8); - if (g_instance.command.len == 0) - g_instance.command.len = 65536; - if ((g_instance.command.cmd < WRITE_DATA_BLOCK) && (g_instance.command.len > 8)) - { - spi_slave_idle_mode(); - return; - } - g_instance.status = TRANSFER; - spi_handle->ssienr = 0x00; - if (g_instance.command.cmd == WRITE_CONFIG) - { - spi_handle->ctrlr0 = (0x0 << g_instance.work_mode) | (0x1 << g_instance.slv_oe) | ((g_instance.data_bit_length - 1) << g_instance.dfs); - spi[2]->rxftlr = g_instance.command.len / data_width - 1; - spi_handle->imr = 0x00; - spi_handle->ssienr = 0x01; - } - else if (g_instance.command.cmd == READ_CONFIG) - { - spi_handle->ctrlr0 = (0x0 << g_instance.work_mode) | (0x0 << g_instance.slv_oe) | ((g_instance.data_bit_length - 1) << g_instance.dfs); - spi_set_tmod(2, SPI_TMOD_TRANS); - spi_handle->txftlr = 0x00; - spi_handle->imr = 0x00; - spi_handle->ssienr = 0x01; - switch(frame_width) - { - case SPI_TRANS_INT: - for (uint32_t i = 0; i < g_instance.command.len / 4; i++) - { - spi_handle->dr[0] = ((uint32_t *)&g_instance.config_ptr[g_instance.command.addr])[i]; - } - break; - case SPI_TRANS_SHORT: - for (uint32_t i = 0; i < g_instance.command.len / 2; i++) - { - spi_handle->dr[0] = ((uint16_t *)&g_instance.config_ptr[g_instance.command.addr])[i]; - } - break; - default: - for (uint32_t i = 0; i < g_instance.command.len; i++) - { - spi_handle->dr[0] = ((uint8_t *)&g_instance.config_ptr[g_instance.command.addr])[i]; - } - break; - } - } - else if (g_instance.command.cmd == WRITE_DATA_BYTE) - { - spi_handle->ctrlr0 = (0x0 << g_instance.work_mode) | (0x1 << g_instance.slv_oe) | ((g_instance.data_bit_length - 1) << g_instance.dfs); - spi[2]->rxftlr = g_instance.command.len / data_width - 1; - spi_handle->imr = 0x00; - spi_handle->ssienr = 0x01; - } - else if (g_instance.command.cmd == READ_DATA_BYTE) - { - spi_handle->ctrlr0 = (0x0 << g_instance.work_mode) | (0x0 << g_instance.slv_oe) | ((g_instance.data_bit_length - 1) << g_instance.dfs); - spi_set_tmod(2, SPI_TMOD_TRANS); - spi_handle->txftlr = 0x00; - spi_handle->imr = 0x00; - spi_handle->ssienr = 0x01; - switch(frame_width) - { - case SPI_TRANS_INT: - for (uint32_t i = 0; i < g_instance.command.len / 4; i++) - { - spi_handle->dr[0] = ((uint32_t *)g_instance.command.addr)[i]; - } - break; - case SPI_TRANS_SHORT: - for (uint32_t i = 0; i < g_instance.command.len / 2; i++) - { - spi_handle->dr[0] = ((uint16_t *)g_instance.command.addr)[i]; - } - break; - default: - for (uint32_t i = 0; i < g_instance.command.len; i++) - { - spi_handle->dr[0] = ((uint8_t *)g_instance.command.addr)[i]; - } - break; - } - } - else if (g_instance.command.cmd == WRITE_DATA_BLOCK) - { - spi_handle->ctrlr0 = (0x0 << g_instance.work_mode) | (0x1 << g_instance.slv_oe) | ((32 - 1) << g_instance.dfs); - - spi_handle->dmacr = 0x01; - spi_handle->imr = 0x00; - spi_handle->ssienr = 0x01; - - sysctl_dma_select(g_instance.dmac_channel, SYSCTL_DMA_SELECT_SSI0_RX_REQ + spi_num * 2); - - dmac_set_single_mode(g_instance.dmac_channel, (void *)(&spi_handle->dr[0]), (void *)(g_instance.command.addr & 0xFFFFFFF0), DMAC_ADDR_NOCHANGE, DMAC_ADDR_INCREMENT, - DMAC_MSIZE_4, DMAC_TRANS_WIDTH_32, g_instance.command.len * 4); - } - else if (g_instance.command.cmd == READ_DATA_BLOCK) - { - spi_handle->ctrlr0 = (0x0 << g_instance.work_mode) | (0x0 << g_instance.slv_oe) | ((32 - 1) << g_instance.dfs); - spi_set_tmod(2, SPI_TMOD_TRANS); - spi_handle->dmacr = 0x02; - spi_handle->imr = 0x00; - spi_handle->ssienr = 0x01; - - sysctl_dma_select(g_instance.dmac_channel, SYSCTL_DMA_SELECT_SSI0_TX_REQ + spi_num * 2); - dmac_set_single_mode(g_instance.dmac_channel, (void *)(g_instance.command.addr & 0xFFFFFFF0), (void *)(&spi_handle->dr[0]), DMAC_ADDR_INCREMENT, DMAC_ADDR_NOCHANGE, - DMAC_MSIZE_4, DMAC_TRANS_WIDTH_32, g_instance.command.len * 4); - } - else - { - spi_slave_idle_mode(); - return; - } - gpiohs_set_pin(g_instance.ready_pin, GPIO_PV_LOW); -} - -static void spi_slave_transfer_mode(void) -{ - spi_transfer_width_t frame_width = spi_get_frame_size(g_instance.data_bit_length - 1); - uint32_t command_len = 0; - - switch(frame_width) - { - case SPI_TRANS_INT: - command_len = g_instance.command.len / 4; - break; - case SPI_TRANS_SHORT: - command_len = g_instance.command.len / 2; - break; - default: - command_len = g_instance.command.len; - break; - } - volatile spi_t *spi_handle = spi[2]; - g_instance.command.err = 0; - if (g_instance.command.cmd == WRITE_CONFIG || g_instance.command.cmd == WRITE_DATA_BYTE) - { - if (spi_handle->rxflr < command_len - 1) - g_instance.command.err = 1; - } - else if (g_instance.command.cmd == READ_CONFIG || g_instance.command.cmd == READ_DATA_BYTE) - { - if (spi_handle->txflr != 0) - g_instance.command.err = 2; - } else if (g_instance.command.cmd == WRITE_DATA_BLOCK || g_instance.command.cmd == READ_DATA_BLOCK) - { - if (dmac->channel[g_instance.dmac_channel].intstatus != 0x02) - g_instance.command.err = 3; - } - else - { - spi_slave_idle_mode(); - return; - } - - if (g_instance.command.err == 0) - { - if (g_instance.command.cmd == WRITE_CONFIG) - { - switch(frame_width) - { - case SPI_TRANS_INT: - for (uint32_t i = 0; i < command_len; i++) - { - ((uint32_t *)&g_instance.config_ptr[g_instance.command.addr])[i] = spi_handle->dr[0]; - } - break; - case SPI_TRANS_SHORT: - for (uint32_t i = 0; i < command_len; i++) - { - ((uint16_t *)&g_instance.config_ptr[g_instance.command.addr])[i] = spi_handle->dr[0]; - } - break; - default: - for (uint32_t i = 0; i < command_len; i++) - { - ((uint8_t *)&g_instance.config_ptr[g_instance.command.addr])[i] = spi_handle->dr[0]; - } - break; - } - } - else if (g_instance.command.cmd == WRITE_DATA_BYTE) - { - switch(frame_width) - { - case SPI_TRANS_INT: - for (uint32_t i = 0; i < command_len; i++) - { - ((uint32_t *)g_instance.command.addr)[i] = spi_handle->dr[0]; - } - break; - case SPI_TRANS_SHORT: - for (uint32_t i = 0; i < command_len; i++) - { - ((uint16_t *)g_instance.command.addr)[i] = spi_handle->dr[0]; - } - break; - default: - for (uint32_t i = 0; i < command_len; i++) - { - ((uint8_t *)g_instance.command.addr)[i] = spi_handle->dr[0]; - } - break; - } - } - } - if(g_instance.callback != NULL) - { - g_instance.callback((void *)&g_instance.command); - } - spi_slave_idle_mode(); -} - -static void spi_slave_cs_irq(void) -{ - if (g_instance.status == IDLE) - spi_slave_idle_mode(); - else if (g_instance.status == COMMAND) - spi_slave_command_mode(); - else if (g_instance.status == TRANSFER) - spi_slave_transfer_mode(); -} - -void spi_slave_config(uint8_t int_pin, uint8_t ready_pin, dmac_channel_number_t dmac_channel, size_t data_bit_length, uint8_t *data, uint32_t len, spi_slave_receive_callback_t callback) -{ - g_instance.status = IDLE; - g_instance.config_ptr = data; - g_instance.config_len = len; - g_instance.work_mode = 6; - g_instance.slv_oe = 10; - g_instance.dfs = 16; - g_instance.data_bit_length = data_bit_length; - g_instance.ready_pin = ready_pin; - g_instance.int_pin = int_pin; - g_instance.callback = callback; - g_instance.dmac_channel = dmac_channel; - sysctl_reset(SYSCTL_RESET_SPI2); - sysctl_clock_enable(SYSCTL_CLOCK_SPI2); - sysctl_clock_set_threshold(SYSCTL_THRESHOLD_SPI2, 9); - - uint32_t data_width = data_bit_length / 8; - volatile spi_t *spi_handle = spi[2]; - spi_handle->ssienr = 0x00; - spi_handle->ctrlr0 = (0x0 << g_instance.work_mode) | (0x1 << g_instance.slv_oe) | ((data_bit_length - 1) << g_instance.dfs); - spi_handle->dmatdlr = 0x04; - spi_handle->dmardlr = 0x03; - spi_handle->dmacr = 0x00; - spi_handle->txftlr = 0x00; - spi_handle->rxftlr = 0x08 / data_width - 1; - spi_handle->imr = 0x10; - spi_handle->ssienr = 0x01; - - gpiohs_set_drive_mode(g_instance.ready_pin, GPIO_DM_OUTPUT); - gpiohs_set_pin(g_instance.ready_pin, GPIO_PV_HIGH); - - gpiohs_set_drive_mode(g_instance.int_pin, GPIO_DM_INPUT_PULL_UP); - gpiohs_set_pin_edge(g_instance.int_pin, GPIO_PE_RISING); - gpiohs_set_irq(g_instance.int_pin, 3, spi_slave_cs_irq); - - plic_set_priority(IRQN_SPI_SLAVE_INTERRUPT, 4); - plic_irq_enable(IRQN_SPI_SLAVE_INTERRUPT); - plic_irq_register(IRQN_SPI_SLAVE_INTERRUPT, spi_slave_irq, NULL); -} - diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/sysctl.c b/cores/arduino/kendryte-standalone-sdk/lib/drivers/sysctl.c deleted file mode 100644 index eab3087..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/sysctl.c +++ /dev/null @@ -1,1860 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include -#include -#include -#include -#include "sysctl.h" -#include "string.h" -#include "encoding.h" -#include "bsp.h" - -#define SYSCTRL_CLOCK_FREQ_IN0 (26000000UL) - -const uint8_t get_select_pll2[] = -{ - [SYSCTL_SOURCE_IN0] = 0, - [SYSCTL_SOURCE_PLL0] = 1, - [SYSCTL_SOURCE_PLL1] = 2, -}; - -const uint8_t get_source_pll2[] = -{ - [0] = SYSCTL_SOURCE_IN0, - [1] = SYSCTL_SOURCE_PLL0, - [2] = SYSCTL_SOURCE_PLL1, -}; - -const uint8_t get_select_aclk[] = -{ - [SYSCTL_SOURCE_IN0] = 0, - [SYSCTL_SOURCE_PLL0] = 1, -}; - -const uint8_t get_source_aclk[] = -{ - [0] = SYSCTL_SOURCE_IN0, - [1] = SYSCTL_SOURCE_PLL0, -}; - -volatile sysctl_t *const sysctl = (volatile sysctl_t *)SYSCTL_BASE_ADDR; - -uint32_t sysctl_get_git_id(void) -{ - return sysctl->git_id.git_id; -} - -uint32_t sysctl_get_freq(void) -{ - return sysctl->clk_freq.clk_freq; -} - -static void sysctl_reset_ctl(sysctl_reset_t reset, uint8_t rst_value) -{ - switch (reset) - { - case SYSCTL_RESET_SOC: - sysctl->soft_reset.soft_reset = rst_value; - break; - case SYSCTL_RESET_ROM: - sysctl->peri_reset.rom_reset = rst_value; - break; - case SYSCTL_RESET_DMA: - sysctl->peri_reset.dma_reset = rst_value; - break; - case SYSCTL_RESET_AI: - sysctl->peri_reset.ai_reset = rst_value; - break; - case SYSCTL_RESET_DVP: - sysctl->peri_reset.dvp_reset = rst_value; - break; - case SYSCTL_RESET_FFT: - sysctl->peri_reset.fft_reset = rst_value; - break; - case SYSCTL_RESET_GPIO: - sysctl->peri_reset.gpio_reset = rst_value; - break; - case SYSCTL_RESET_SPI0: - sysctl->peri_reset.spi0_reset = rst_value; - break; - case SYSCTL_RESET_SPI1: - sysctl->peri_reset.spi1_reset = rst_value; - break; - case SYSCTL_RESET_SPI2: - sysctl->peri_reset.spi2_reset = rst_value; - break; - case SYSCTL_RESET_SPI3: - sysctl->peri_reset.spi3_reset = rst_value; - break; - case SYSCTL_RESET_I2S0: - sysctl->peri_reset.i2s0_reset = rst_value; - break; - case SYSCTL_RESET_I2S1: - sysctl->peri_reset.i2s1_reset = rst_value; - break; - case SYSCTL_RESET_I2S2: - sysctl->peri_reset.i2s2_reset = rst_value; - break; - case SYSCTL_RESET_I2C0: - sysctl->peri_reset.i2c0_reset = rst_value; - break; - case SYSCTL_RESET_I2C1: - sysctl->peri_reset.i2c1_reset = rst_value; - break; - case SYSCTL_RESET_I2C2: - sysctl->peri_reset.i2c2_reset = rst_value; - break; - case SYSCTL_RESET_UART1: - sysctl->peri_reset.uart1_reset = rst_value; - break; - case SYSCTL_RESET_UART2: - sysctl->peri_reset.uart2_reset = rst_value; - break; - case SYSCTL_RESET_UART3: - sysctl->peri_reset.uart3_reset = rst_value; - break; - case SYSCTL_RESET_AES: - sysctl->peri_reset.aes_reset = rst_value; - break; - case SYSCTL_RESET_FPIOA: - sysctl->peri_reset.fpioa_reset = rst_value; - break; - case SYSCTL_RESET_TIMER0: - sysctl->peri_reset.timer0_reset = rst_value; - break; - case SYSCTL_RESET_TIMER1: - sysctl->peri_reset.timer1_reset = rst_value; - break; - case SYSCTL_RESET_TIMER2: - sysctl->peri_reset.timer2_reset = rst_value; - break; - case SYSCTL_RESET_WDT0: - sysctl->peri_reset.wdt0_reset = rst_value; - break; - case SYSCTL_RESET_WDT1: - sysctl->peri_reset.wdt1_reset = rst_value; - break; - case SYSCTL_RESET_SHA: - sysctl->peri_reset.sha_reset = rst_value; - break; - case SYSCTL_RESET_RTC: - sysctl->peri_reset.rtc_reset = rst_value; - break; - - default: - break; - } -} - -void sysctl_reset(sysctl_reset_t reset) -{ - sysctl_reset_ctl(reset, 1); - sysctl_reset_ctl(reset, 0); -} - -static int sysctl_clock_bus_en(sysctl_clock_t clock, uint8_t en) -{ - /* - * The timer is under APB0, to prevent apb0_clk_en1 and apb0_clk_en0 - * on same register, we split it to peripheral and central two - * registers, to protect CPU close apb0 clock accidentally. - * - * The apb0_clk_en0 and apb0_clk_en1 have same function, - * one of them set, the APB0 clock enable. - */ - - /* The APB clock should carefully disable */ - if (en) - { - switch (clock) - { - /* - * These peripheral devices are under APB0 - * GPIO, UART1, UART2, UART3, SPI_SLAVE, I2S0, I2S1, - * I2S2, I2C0, I2C1, I2C2, FPIOA, SHA256, TIMER0, - * TIMER1, TIMER2 - */ - case SYSCTL_CLOCK_GPIO: - case SYSCTL_CLOCK_SPI2: - case SYSCTL_CLOCK_I2S0: - case SYSCTL_CLOCK_I2S1: - case SYSCTL_CLOCK_I2S2: - case SYSCTL_CLOCK_I2C0: - case SYSCTL_CLOCK_I2C1: - case SYSCTL_CLOCK_I2C2: - case SYSCTL_CLOCK_UART1: - case SYSCTL_CLOCK_UART2: - case SYSCTL_CLOCK_UART3: - case SYSCTL_CLOCK_FPIOA: - case SYSCTL_CLOCK_TIMER0: - case SYSCTL_CLOCK_TIMER1: - case SYSCTL_CLOCK_TIMER2: - case SYSCTL_CLOCK_SHA: - sysctl->clk_en_cent.apb0_clk_en = en; - break; - - /* - * These peripheral devices are under APB1 - * WDT, AES, OTP, DVP, SYSCTL - */ - case SYSCTL_CLOCK_AES: - case SYSCTL_CLOCK_WDT0: - case SYSCTL_CLOCK_WDT1: - case SYSCTL_CLOCK_OTP: - case SYSCTL_CLOCK_RTC: - sysctl->clk_en_cent.apb1_clk_en = en; - break; - - /* - * These peripheral devices are under APB2 - * SPI0, SPI1 - */ - case SYSCTL_CLOCK_SPI0: - case SYSCTL_CLOCK_SPI1: - sysctl->clk_en_cent.apb2_clk_en = en; - break; - - default: - break; - } - } - - return 0; -} - -static int sysctl_clock_device_en(sysctl_clock_t clock, uint8_t en) -{ - switch (clock) - { - /* - * These devices are PLL - */ - case SYSCTL_CLOCK_PLL0: - sysctl->pll0.pll_out_en0 = en; - break; - case SYSCTL_CLOCK_PLL1: - sysctl->pll1.pll_out_en1 = en; - break; - case SYSCTL_CLOCK_PLL2: - sysctl->pll2.pll_out_en2 = en; - break; - - /* - * These devices are CPU, SRAM, APB bus, ROM, DMA, AI - */ - case SYSCTL_CLOCK_CPU: - sysctl->clk_en_cent.cpu_clk_en = en; - break; - case SYSCTL_CLOCK_SRAM0: - sysctl->clk_en_cent.sram0_clk_en = en; - break; - case SYSCTL_CLOCK_SRAM1: - sysctl->clk_en_cent.sram1_clk_en = en; - break; - case SYSCTL_CLOCK_APB0: - sysctl->clk_en_cent.apb0_clk_en = en; - break; - case SYSCTL_CLOCK_APB1: - sysctl->clk_en_cent.apb1_clk_en = en; - break; - case SYSCTL_CLOCK_APB2: - sysctl->clk_en_cent.apb2_clk_en = en; - break; - case SYSCTL_CLOCK_ROM: - sysctl->clk_en_peri.rom_clk_en = en; - break; - case SYSCTL_CLOCK_DMA: - sysctl->clk_en_peri.dma_clk_en = en; - break; - case SYSCTL_CLOCK_AI: - sysctl->clk_en_peri.ai_clk_en = en; - break; - case SYSCTL_CLOCK_DVP: - sysctl->clk_en_peri.dvp_clk_en = en; - break; - case SYSCTL_CLOCK_FFT: - sysctl->clk_en_peri.fft_clk_en = en; - break; - case SYSCTL_CLOCK_SPI3: - sysctl->clk_en_peri.spi3_clk_en = en; - break; - - /* - * These peripheral devices are under APB0 - * GPIO, UART1, UART2, UART3, SPI_SLAVE, I2S0, I2S1, - * I2S2, I2C0, I2C1, I2C2, FPIOA, SHA256, TIMER0, - * TIMER1, TIMER2 - */ - case SYSCTL_CLOCK_GPIO: - sysctl->clk_en_peri.gpio_clk_en = en; - break; - case SYSCTL_CLOCK_SPI2: - sysctl->clk_en_peri.spi2_clk_en = en; - break; - case SYSCTL_CLOCK_I2S0: - sysctl->clk_en_peri.i2s0_clk_en = en; - break; - case SYSCTL_CLOCK_I2S1: - sysctl->clk_en_peri.i2s1_clk_en = en; - break; - case SYSCTL_CLOCK_I2S2: - sysctl->clk_en_peri.i2s2_clk_en = en; - break; - case SYSCTL_CLOCK_I2C0: - sysctl->clk_en_peri.i2c0_clk_en = en; - break; - case SYSCTL_CLOCK_I2C1: - sysctl->clk_en_peri.i2c1_clk_en = en; - break; - case SYSCTL_CLOCK_I2C2: - sysctl->clk_en_peri.i2c2_clk_en = en; - break; - case SYSCTL_CLOCK_UART1: - sysctl->clk_en_peri.uart1_clk_en = en; - break; - case SYSCTL_CLOCK_UART2: - sysctl->clk_en_peri.uart2_clk_en = en; - break; - case SYSCTL_CLOCK_UART3: - sysctl->clk_en_peri.uart3_clk_en = en; - break; - case SYSCTL_CLOCK_FPIOA: - sysctl->clk_en_peri.fpioa_clk_en = en; - break; - case SYSCTL_CLOCK_TIMER0: - sysctl->clk_en_peri.timer0_clk_en = en; - break; - case SYSCTL_CLOCK_TIMER1: - sysctl->clk_en_peri.timer1_clk_en = en; - break; - case SYSCTL_CLOCK_TIMER2: - sysctl->clk_en_peri.timer2_clk_en = en; - break; - case SYSCTL_CLOCK_SHA: - sysctl->clk_en_peri.sha_clk_en = en; - break; - - /* - * These peripheral devices are under APB1 - * WDT, AES, OTP, DVP, SYSCTL - */ - case SYSCTL_CLOCK_AES: - sysctl->clk_en_peri.aes_clk_en = en; - break; - case SYSCTL_CLOCK_WDT0: - sysctl->clk_en_peri.wdt0_clk_en = en; - break; - case SYSCTL_CLOCK_WDT1: - sysctl->clk_en_peri.wdt1_clk_en = en; - break; - case SYSCTL_CLOCK_OTP: - sysctl->clk_en_peri.otp_clk_en = en; - break; - case SYSCTL_CLOCK_RTC: - sysctl->clk_en_peri.rtc_clk_en = en; - break; - - /* - * These peripheral devices are under APB2 - * SPI0, SPI1 - */ - case SYSCTL_CLOCK_SPI0: - sysctl->clk_en_peri.spi0_clk_en = en; - break; - case SYSCTL_CLOCK_SPI1: - sysctl->clk_en_peri.spi1_clk_en = en; - break; - - default: - break; - } - - return 0; -} - -int sysctl_clock_enable(sysctl_clock_t clock) -{ - if (clock >= SYSCTL_CLOCK_MAX) - return -1; - sysctl_clock_bus_en(clock, 1); - sysctl_clock_device_en(clock, 1); - return 0; -} - -int sysctl_clock_disable(sysctl_clock_t clock) -{ - if (clock >= SYSCTL_CLOCK_MAX) - return -1; - sysctl_clock_bus_en(clock, 0); - sysctl_clock_device_en(clock, 0); - return 0; -} - -int sysctl_clock_set_threshold(sysctl_threshold_t which, int threshold) -{ - int result = 0; - switch (which) - { - /* - * These threshold is 2 bit width - */ - case SYSCTL_THRESHOLD_ACLK: - sysctl->clk_sel0.aclk_divider_sel = (uint8_t)threshold & 0x03; - break; - - /* - * These threshold is 3 bit width - */ - case SYSCTL_THRESHOLD_APB0: - sysctl->clk_sel0.apb0_clk_sel = (uint8_t)threshold & 0x07; - break; - case SYSCTL_THRESHOLD_APB1: - sysctl->clk_sel0.apb1_clk_sel = (uint8_t)threshold & 0x07; - break; - case SYSCTL_THRESHOLD_APB2: - sysctl->clk_sel0.apb2_clk_sel = (uint8_t)threshold & 0x07; - break; - - /* - * These threshold is 4 bit width - */ - case SYSCTL_THRESHOLD_SRAM0: - sysctl->clk_th0.sram0_gclk_threshold = (uint8_t)threshold & 0x0F; - break; - case SYSCTL_THRESHOLD_SRAM1: - sysctl->clk_th0.sram1_gclk_threshold = (uint8_t)threshold & 0x0F; - break; - case SYSCTL_THRESHOLD_AI: - sysctl->clk_th0.ai_gclk_threshold = (uint8_t)threshold & 0x0F; - break; - case SYSCTL_THRESHOLD_DVP: - sysctl->clk_th0.dvp_gclk_threshold = (uint8_t)threshold & 0x0F; - break; - case SYSCTL_THRESHOLD_ROM: - sysctl->clk_th0.rom_gclk_threshold = (uint8_t)threshold & 0x0F; - break; - - /* - * These threshold is 8 bit width - */ - case SYSCTL_THRESHOLD_SPI0: - sysctl->clk_th1.spi0_clk_threshold = (uint8_t)threshold; - break; - case SYSCTL_THRESHOLD_SPI1: - sysctl->clk_th1.spi1_clk_threshold = (uint8_t)threshold; - break; - case SYSCTL_THRESHOLD_SPI2: - sysctl->clk_th1.spi2_clk_threshold = (uint8_t)threshold; - break; - case SYSCTL_THRESHOLD_SPI3: - sysctl->clk_th1.spi3_clk_threshold = (uint8_t)threshold; - break; - case SYSCTL_THRESHOLD_TIMER0: - sysctl->clk_th2.timer0_clk_threshold = (uint8_t)threshold; - break; - case SYSCTL_THRESHOLD_TIMER1: - sysctl->clk_th2.timer1_clk_threshold = (uint8_t)threshold; - break; - case SYSCTL_THRESHOLD_TIMER2: - sysctl->clk_th2.timer2_clk_threshold = (uint8_t)threshold; - break; - case SYSCTL_THRESHOLD_I2S0_M: - sysctl->clk_th4.i2s0_mclk_threshold = (uint8_t)threshold; - break; - case SYSCTL_THRESHOLD_I2S1_M: - sysctl->clk_th4.i2s1_mclk_threshold = (uint8_t)threshold; - break; - case SYSCTL_THRESHOLD_I2S2_M: - sysctl->clk_th5.i2s2_mclk_threshold = (uint8_t)threshold; - break; - case SYSCTL_THRESHOLD_I2C0: - sysctl->clk_th5.i2c0_clk_threshold = (uint8_t)threshold; - break; - case SYSCTL_THRESHOLD_I2C1: - sysctl->clk_th5.i2c1_clk_threshold = (uint8_t)threshold; - break; - case SYSCTL_THRESHOLD_I2C2: - sysctl->clk_th5.i2c2_clk_threshold = (uint8_t)threshold; - break; - case SYSCTL_THRESHOLD_WDT0: - sysctl->clk_th6.wdt0_clk_threshold = (uint8_t)threshold; - break; - case SYSCTL_THRESHOLD_WDT1: - sysctl->clk_th6.wdt1_clk_threshold = (uint8_t)threshold; - break; - - /* - * These threshold is 16 bit width - */ - case SYSCTL_THRESHOLD_I2S0: - sysctl->clk_th3.i2s0_clk_threshold = (uint16_t)threshold; - break; - case SYSCTL_THRESHOLD_I2S1: - sysctl->clk_th3.i2s1_clk_threshold = (uint16_t)threshold; - break; - case SYSCTL_THRESHOLD_I2S2: - sysctl->clk_th4.i2s2_clk_threshold = (uint16_t)threshold; - break; - - default: - result = -1; - break; - } - return result; -} - -int sysctl_clock_get_threshold(sysctl_threshold_t which) -{ - int threshold = 0; - - switch (which) - { - /* - * Select and get threshold value - */ - case SYSCTL_THRESHOLD_ACLK: - threshold = (int)sysctl->clk_sel0.aclk_divider_sel; - break; - case SYSCTL_THRESHOLD_APB0: - threshold = (int)sysctl->clk_sel0.apb0_clk_sel; - break; - case SYSCTL_THRESHOLD_APB1: - threshold = (int)sysctl->clk_sel0.apb1_clk_sel; - break; - case SYSCTL_THRESHOLD_APB2: - threshold = (int)sysctl->clk_sel0.apb2_clk_sel; - break; - case SYSCTL_THRESHOLD_SRAM0: - threshold = (int)sysctl->clk_th0.sram0_gclk_threshold; - break; - case SYSCTL_THRESHOLD_SRAM1: - threshold = (int)sysctl->clk_th0.sram1_gclk_threshold; - break; - case SYSCTL_THRESHOLD_AI: - threshold = (int)sysctl->clk_th0.ai_gclk_threshold; - break; - case SYSCTL_THRESHOLD_DVP: - threshold = (int)sysctl->clk_th0.dvp_gclk_threshold; - break; - case SYSCTL_THRESHOLD_ROM: - threshold = (int)sysctl->clk_th0.rom_gclk_threshold; - break; - case SYSCTL_THRESHOLD_SPI0: - threshold = (int)sysctl->clk_th1.spi0_clk_threshold; - break; - case SYSCTL_THRESHOLD_SPI1: - threshold = (int)sysctl->clk_th1.spi1_clk_threshold; - break; - case SYSCTL_THRESHOLD_SPI2: - threshold = (int)sysctl->clk_th1.spi2_clk_threshold; - break; - case SYSCTL_THRESHOLD_SPI3: - threshold = (int)sysctl->clk_th1.spi3_clk_threshold; - break; - case SYSCTL_THRESHOLD_TIMER0: - threshold = (int)sysctl->clk_th2.timer0_clk_threshold; - break; - case SYSCTL_THRESHOLD_TIMER1: - threshold = (int)sysctl->clk_th2.timer1_clk_threshold; - break; - case SYSCTL_THRESHOLD_TIMER2: - threshold = (int)sysctl->clk_th2.timer2_clk_threshold; - break; - case SYSCTL_THRESHOLD_I2S0: - threshold = (int)sysctl->clk_th3.i2s0_clk_threshold; - break; - case SYSCTL_THRESHOLD_I2S1: - threshold = (int)sysctl->clk_th3.i2s1_clk_threshold; - break; - case SYSCTL_THRESHOLD_I2S2: - threshold = (int)sysctl->clk_th4.i2s2_clk_threshold; - break; - case SYSCTL_THRESHOLD_I2S0_M: - threshold = (int)sysctl->clk_th4.i2s0_mclk_threshold; - break; - case SYSCTL_THRESHOLD_I2S1_M: - threshold = (int)sysctl->clk_th4.i2s1_mclk_threshold; - break; - case SYSCTL_THRESHOLD_I2S2_M: - threshold = (int)sysctl->clk_th5.i2s2_mclk_threshold; - break; - case SYSCTL_THRESHOLD_I2C0: - threshold = (int)sysctl->clk_th5.i2c0_clk_threshold; - break; - case SYSCTL_THRESHOLD_I2C1: - threshold = (int)sysctl->clk_th5.i2c1_clk_threshold; - break; - case SYSCTL_THRESHOLD_I2C2: - threshold = (int)sysctl->clk_th5.i2c2_clk_threshold; - break; - case SYSCTL_THRESHOLD_WDT0: - threshold = (int)sysctl->clk_th6.wdt0_clk_threshold; - break; - case SYSCTL_THRESHOLD_WDT1: - threshold = (int)sysctl->clk_th6.wdt1_clk_threshold; - break; - - default: - break; - } - - return threshold; -} - -int sysctl_clock_set_clock_select(sysctl_clock_select_t which, int select) -{ - int result = 0; - switch (which) - { - /* - * These clock select is 1 bit width - */ - case SYSCTL_CLOCK_SELECT_PLL0_BYPASS: - sysctl->pll0.pll_bypass0 = select & 0x01; - break; - case SYSCTL_CLOCK_SELECT_PLL1_BYPASS: - sysctl->pll1.pll_bypass1 = select & 0x01; - break; - case SYSCTL_CLOCK_SELECT_PLL2_BYPASS: - sysctl->pll2.pll_bypass2 = select & 0x01; - break; - case SYSCTL_CLOCK_SELECT_ACLK: - sysctl->clk_sel0.aclk_sel = select & 0x01; - break; - case SYSCTL_CLOCK_SELECT_SPI3: - sysctl->clk_sel0.spi3_clk_sel = select & 0x01; - break; - case SYSCTL_CLOCK_SELECT_TIMER0: - sysctl->clk_sel0.timer0_clk_sel = select & 0x01; - break; - case SYSCTL_CLOCK_SELECT_TIMER1: - sysctl->clk_sel0.timer1_clk_sel = select & 0x01; - break; - case SYSCTL_CLOCK_SELECT_TIMER2: - sysctl->clk_sel0.timer2_clk_sel = select & 0x01; - break; - case SYSCTL_CLOCK_SELECT_SPI3_SAMPLE: - sysctl->clk_sel1.spi3_sample_clk_sel = select & 0x01; - break; - - /* - * These clock select is 2 bit width - */ - case SYSCTL_CLOCK_SELECT_PLL2: - sysctl->pll2.pll_ckin_sel2 = select & 0x03; - break; - - default: - result = -1; - break; - } - - return result; -} - -int sysctl_clock_get_clock_select(sysctl_clock_select_t which) -{ - int clock_select = 0; - - switch (which) - { - /* - * Select and get clock select value - */ - case SYSCTL_CLOCK_SELECT_PLL0_BYPASS: - clock_select = (int)sysctl->pll0.pll_bypass0; - break; - case SYSCTL_CLOCK_SELECT_PLL1_BYPASS: - clock_select = (int)sysctl->pll1.pll_bypass1; - break; - case SYSCTL_CLOCK_SELECT_PLL2_BYPASS: - clock_select = (int)sysctl->pll2.pll_bypass2; - break; - case SYSCTL_CLOCK_SELECT_PLL2: - clock_select = (int)sysctl->pll2.pll_ckin_sel2; - break; - case SYSCTL_CLOCK_SELECT_ACLK: - clock_select = (int)sysctl->clk_sel0.aclk_sel; - break; - case SYSCTL_CLOCK_SELECT_SPI3: - clock_select = (int)sysctl->clk_sel0.spi3_clk_sel; - break; - case SYSCTL_CLOCK_SELECT_TIMER0: - clock_select = (int)sysctl->clk_sel0.timer0_clk_sel; - break; - case SYSCTL_CLOCK_SELECT_TIMER1: - clock_select = (int)sysctl->clk_sel0.timer1_clk_sel; - break; - case SYSCTL_CLOCK_SELECT_TIMER2: - clock_select = (int)sysctl->clk_sel0.timer2_clk_sel; - break; - case SYSCTL_CLOCK_SELECT_SPI3_SAMPLE: - clock_select = (int)sysctl->clk_sel1.spi3_sample_clk_sel; - break; - - default: - break; - } - - return clock_select; -} - -uint32_t sysctl_clock_source_get_freq(sysctl_clock_source_t input) -{ - uint32_t result; - - switch (input) - { - case SYSCTL_SOURCE_IN0: - result = SYSCTRL_CLOCK_FREQ_IN0; - break; - case SYSCTL_SOURCE_PLL0: - result = sysctl_pll_get_freq(SYSCTL_PLL0); - break; - case SYSCTL_SOURCE_PLL1: - result = sysctl_pll_get_freq(SYSCTL_PLL1); - break; - case SYSCTL_SOURCE_PLL2: - result = sysctl_pll_get_freq(SYSCTL_PLL2); - break; - case SYSCTL_SOURCE_ACLK: - result = sysctl_clock_get_freq(SYSCTL_CLOCK_ACLK); - break; - default: - result = 0; - break; - } - return result; -} - -static int sysctl_pll_is_lock(sysctl_pll_t pll) -{ - /* - * All bit enable means PLL lock - * - * struct pll_lock_t - * { - * uint8_t overflow : 1; - * uint8_t rfslip : 1; - * uint8_t fbslip : 1; - * }; - * - */ - - if (pll >= SYSCTL_PLL_MAX) - return 0; - - switch (pll) - { - case SYSCTL_PLL0: - return sysctl->pll_lock.pll_lock0 == 3; - - case SYSCTL_PLL1: - return sysctl->pll_lock.pll_lock1 & 1; - - case SYSCTL_PLL2: - return sysctl->pll_lock.pll_lock2 & 1; - - default: - break; - } - - return 0; -} - -static int sysctl_pll_clear_slip(sysctl_pll_t pll) -{ - if (pll >= SYSCTL_PLL_MAX) - return -1; - - switch (pll) - { - case SYSCTL_PLL0: - sysctl->pll_lock.pll_slip_clear0 = 1; - break; - - case SYSCTL_PLL1: - sysctl->pll_lock.pll_slip_clear1 = 1; - break; - - case SYSCTL_PLL2: - sysctl->pll_lock.pll_slip_clear2 = 1; - break; - - default: - break; - } - - return sysctl_pll_is_lock(pll) ? 0 : -1; -} - -int sysctl_pll_enable(sysctl_pll_t pll) -{ - /* - * ---+ - * PWRDN | - * +------------------------------------------------------------- - * ^ - * | - * | - * t1 - * +------------------+ - * RESET | | - * ----------+ +----------------------------------- - * ^ ^ ^ - * |<----- t_rst ---->|<---------- t_lock ---------->| - * | | | - * t2 t3 t4 - */ - - if (pll >= SYSCTL_PLL_MAX) - return -1; - - switch (pll) - { - case SYSCTL_PLL0: - /* Do not bypass PLL */ - sysctl->pll0.pll_bypass0 = 0; - /* - * Power on the PLL, negtive from PWRDN - * 0 is power off - * 1 is power on - */ - sysctl->pll0.pll_pwrd0 = 1; - /* - * Reset trigger of the PLL, connected RESET - * 0 is free - * 1 is reset - */ - sysctl->pll0.pll_reset0 = 0; - sysctl->pll0.pll_reset0 = 1; - asm volatile ("nop"); - asm volatile ("nop"); - sysctl->pll0.pll_reset0 = 0; - break; - - case SYSCTL_PLL1: - /* Do not bypass PLL */ - sysctl->pll1.pll_bypass1 = 0; - /* - * Power on the PLL, negtive from PWRDN - * 0 is power off - * 1 is power on - */ - sysctl->pll1.pll_pwrd1 = 1; - /* - * Reset trigger of the PLL, connected RESET - * 0 is free - * 1 is reset - */ - sysctl->pll1.pll_reset1 = 0; - sysctl->pll1.pll_reset1 = 1; - asm volatile ("nop"); - asm volatile ("nop"); - sysctl->pll1.pll_reset1 = 0; - break; - - case SYSCTL_PLL2: - /* Do not bypass PLL */ - sysctl->pll2.pll_bypass2 = 0; - /* - * Power on the PLL, negtive from PWRDN - * 0 is power off - * 1 is power on - */ - sysctl->pll2.pll_pwrd2 = 1; - /* - * Reset trigger of the PLL, connected RESET - * 0 is free - * 1 is reset - */ - sysctl->pll2.pll_reset2 = 0; - sysctl->pll2.pll_reset2 = 1; - asm volatile ("nop"); - asm volatile ("nop"); - sysctl->pll2.pll_reset2 = 0; - break; - - default: - break; - } - - return 0; -} - -int sysctl_pll_disable(sysctl_pll_t pll) -{ - if (pll >= SYSCTL_PLL_MAX) - return -1; - - switch (pll) - { - case SYSCTL_PLL0: - /* Bypass PLL */ - sysctl->pll0.pll_bypass0 = 1; - /* - * Power on the PLL, negtive from PWRDN - * 0 is power off - * 1 is power on - */ - sysctl->pll0.pll_pwrd0 = 0; - break; - - case SYSCTL_PLL1: - /* Bypass PLL */ - sysctl->pll1.pll_bypass1 = 1; - /* - * Power on the PLL, negtive from PWRDN - * 0 is power off - * 1 is power on - */ - sysctl->pll1.pll_pwrd1 = 0; - break; - - case SYSCTL_PLL2: - /* Bypass PLL */ - sysctl->pll2.pll_bypass2 = 1; - /* - * Power on the PLL, negtive from PWRDN - * 0 is power off - * 1 is power on - */ - sysctl->pll2.pll_pwrd2 = 0; - break; - - default: - break; - } - - return 0; -} - -uint32_t sysctl_pll_get_freq(sysctl_pll_t pll) -{ - uint32_t freq_in = 0, freq_out = 0; - uint32_t nr = 0, nf = 0, od = 0; - uint8_t select = 0; - - if (pll >= SYSCTL_PLL_MAX) - return 0; - - switch (pll) - { - case SYSCTL_PLL0: - freq_in = sysctl_clock_source_get_freq(SYSCTL_SOURCE_IN0); - nr = sysctl->pll0.clkr0 + 1; - nf = sysctl->pll0.clkf0 + 1; - od = sysctl->pll0.clkod0 + 1; - break; - - case SYSCTL_PLL1: - freq_in = sysctl_clock_source_get_freq(SYSCTL_SOURCE_IN0); - nr = sysctl->pll1.clkr1 + 1; - nf = sysctl->pll1.clkf1 + 1; - od = sysctl->pll1.clkod1 + 1; - break; - - case SYSCTL_PLL2: - /* - * Get input freq accroding select register - */ - select = sysctl->pll2.pll_ckin_sel2; - if (select < sizeof(get_source_pll2)) - freq_in = sysctl_clock_source_get_freq(get_source_pll2[select]); - else - return 0; - - nr = sysctl->pll2.clkr2 + 1; - nf = sysctl->pll2.clkf2 + 1; - od = sysctl->pll2.clkod2 + 1; - break; - - default: - break; - } - - /* - * Get final PLL output freq - * FOUT = FIN / NR * NF / OD - */ - freq_out = (double)freq_in / (double)nr * (double)nf / (double)od; - return freq_out; -} - -static uint32_t sysctl_pll_source_set_freq(sysctl_pll_t pll, sysctl_clock_source_t source, uint32_t freq) -{ - uint32_t freq_in = 0; - - if (pll >= SYSCTL_PLL_MAX) - return 0; - - if (source >= SYSCTL_SOURCE_MAX) - return 0; - - switch (pll) - { - case SYSCTL_PLL0: - case SYSCTL_PLL1: - /* - * Check input clock source - */ - if (source != SYSCTL_SOURCE_IN0) - return 0; - freq_in = sysctl_clock_source_get_freq(SYSCTL_SOURCE_IN0); - /* - * Check input clock freq - */ - if (freq_in == 0) - return 0; - break; - - case SYSCTL_PLL2: - /* - * Check input clock source - */ - if (source < sizeof(get_select_pll2)) - freq_in = sysctl_clock_source_get_freq(source); - /* - * Check input clock freq - */ - if (freq_in == 0) - return 0; - break; - - default: - return 0; - } - - /* - * Begin calculate PLL registers' value - */ - - /* constants */ - const double vco_min = 3.5e+08; - const double vco_max = 1.75e+09; - const double ref_min = 1.36719e+07; - const double ref_max = 1.75e+09; - const int nr_min = 1; - const int nr_max = 16; - const int nf_min = 1; - const int nf_max = 64; - const int no_min = 1; - const int no_max = 16; - const int nb_min = 1; - const int nb_max = 64; - const int max_vco = 1; - const int ref_rng = 1; - - /* variables */ - int nr = 0; - int nrx = 0; - int nf = 0; - int nfi = 0; - int no = 0; - int noe = 0; - int not = 0; - int nor = 0; - int nore = 0; - int nb = 0; - int first = 0; - int firstx = 0; - int found = 0; - - long long nfx = 0; - double fin = 0, fout = 0, fvco = 0; - double val = 0, nval = 0, err = 0, merr = 0, terr = 0; - int x_nrx = 0, x_no = 0, x_nb = 0; - long long x_nfx = 0; - double x_fvco = 0, x_err = 0; - - fin = freq_in; - fout = freq; - val = fout / fin; - terr = 0.5 / ((double)(nf_max / 2)); - first = firstx = 1; - if (terr != -2) - { - first = 0; - if (terr == 0) - terr = 1e-16; - merr = fabs(terr); - } - found = 0; - for (nfi = val; nfi < nf_max; ++nfi) - { - nr = rint(((double)nfi) / val); - if (nr == 0) - continue; - if ((ref_rng) && (nr < nr_min)) - continue; - if (fin / ((double)nr) > ref_max) - continue; - nrx = nr; - nf = nfx = nfi; - nval = ((double)nfx) / ((double)nr); - if (nf == 0) - nf = 1; - err = 1 - nval / val; - - if ((first) || (fabs(err) < merr * (1 + 1e-6)) || (fabs(err) < 1e-16)) - { - not = floor(vco_max / fout); - for (no = (not > no_max) ? no_max : not; no > no_min; --no) - { - if ((ref_rng) && ((nr / no) < nr_min)) - continue; - if ((nr % no) == 0) - break; - } - if ((nr % no) != 0) - continue; - nor = ((not > no_max) ? no_max : not) / no; - nore = nf_max / nf; - if (nor > nore) - nor = nore; - noe = ceil(vco_min / fout); - if (!max_vco) - { - nore = (noe - 1) / no + 1; - nor = nore; - not = 0; /* force next if to fail */ - } - if ((((no * nor) < (not >> 1)) || ((no * nor) < noe)) && ((no * nor) < (nf_max / nf))) - { - no = nf_max / nf; - if (no > no_max) - no = no_max; - if (no > not) - no = not; - nfx *= no; - nf *= no; - if ((no > 1) && (!firstx)) - continue; - /* wait for larger nf in later iterations */ - } - else - { - nrx /= no; - nfx *= nor; - nf *= nor; - no *= nor; - if (no > no_max) - continue; - if ((nor > 1) && (!firstx)) - continue; - /* wait for larger nf in later iterations */ - } - - nb = nfx; - if (nb < nb_min) - nb = nb_min; - if (nb > nb_max) - continue; - - fvco = fin / ((double)nrx) * ((double)nfx); - if (fvco < vco_min) - continue; - if (fvco > vco_max) - continue; - if (nf < nf_min) - continue; - if ((ref_rng) && (fin / ((double)nrx) < ref_min)) - continue; - if ((ref_rng) && (nrx > nr_max)) - continue; - if (!(((firstx) && (terr < 0)) || (fabs(err) < merr * (1 - 1e-6)) || ((max_vco) && (no > x_no)))) - continue; - if ((!firstx) && (terr >= 0) && (nrx > x_nrx)) - continue; - - found = 1; - x_no = no; - x_nrx = nrx; - x_nfx = nfx; - x_nb = nb; - x_fvco = fvco; - x_err = err; - first = firstx = 0; - merr = fabs(err); - if (terr != -1) - continue; - } - } - if (!found) - { - return 0; - } - - nrx = x_nrx; - nfx = x_nfx; - no = x_no; - nb = x_nb; - fvco = x_fvco; - err = x_err; - if ((terr != -2) && (fabs(err) >= terr * (1 - 1e-6))) - { - return 0; - } - - /* - * Begin write PLL registers' value, - * Using atomic write method. - */ - sysctl_pll0_t pll0; - sysctl_pll1_t pll1; - sysctl_pll2_t pll2; - - switch (pll) - { - case SYSCTL_PLL0: - /* Read register from bus */ - pll0 = sysctl->pll0; - /* Set register temporary value */ - pll0.clkr0 = nrx - 1; - pll0.clkf0 = nfx - 1; - pll0.clkod0 = no - 1; - pll0.bwadj0 = nb - 1; - /* Write register back to bus */ - sysctl->pll0 = pll0; - break; - - case SYSCTL_PLL1: - /* Read register from bus */ - pll1 = sysctl->pll1; - /* Set register temporary value */ - pll1.clkr1 = nrx - 1; - pll1.clkf1 = nfx - 1; - pll1.clkod1 = no - 1; - pll1.bwadj1 = nb - 1; - /* Write register back to bus */ - sysctl->pll1 = pll1; - break; - - case SYSCTL_PLL2: - /* Read register from bus */ - pll2 = sysctl->pll2; - /* Set register temporary value */ - if (source < sizeof(get_select_pll2)) - pll2.pll_ckin_sel2 = get_select_pll2[source]; - - pll2.clkr2 = nrx - 1; - pll2.clkf2 = nfx - 1; - pll2.clkod2 = no - 1; - pll2.bwadj2 = nb - 1; - /* Write register back to bus */ - sysctl->pll2 = pll2; - break; - - default: - return 0; - } - - return sysctl_pll_get_freq(pll); -} - -uint32_t sysctl_clock_get_freq(sysctl_clock_t clock) -{ - uint32_t source = 0; - uint32_t result = 0; - - switch (clock) - { - /* - * The clock IN0 - */ - case SYSCTL_CLOCK_IN0: - source = sysctl_clock_source_get_freq(SYSCTL_SOURCE_IN0); - result = source; - break; - - /* - * These clock directly under PLL clock domain - * They are using gated divider. - */ - case SYSCTL_CLOCK_PLL0: - source = sysctl_clock_source_get_freq(SYSCTL_SOURCE_PLL0); - result = source; - break; - case SYSCTL_CLOCK_PLL1: - source = sysctl_clock_source_get_freq(SYSCTL_SOURCE_PLL1); - result = source; - break; - case SYSCTL_CLOCK_PLL2: - source = sysctl_clock_source_get_freq(SYSCTL_SOURCE_PLL2); - result = source; - break; - - /* - * These clock directly under ACLK clock domain - */ - case SYSCTL_CLOCK_CPU: - switch (sysctl_clock_get_clock_select(SYSCTL_CLOCK_SELECT_ACLK)) - { - case 0: - source = sysctl_clock_source_get_freq(SYSCTL_SOURCE_IN0); - break; - case 1: - source = sysctl_clock_source_get_freq(SYSCTL_SOURCE_PLL0) / - (2ULL << sysctl_clock_get_threshold(SYSCTL_THRESHOLD_ACLK)); - break; - default: - break; - } - result = source; - break; - case SYSCTL_CLOCK_DMA: - switch (sysctl_clock_get_clock_select(SYSCTL_CLOCK_SELECT_ACLK)) - { - case 0: - source = sysctl_clock_source_get_freq(SYSCTL_SOURCE_IN0); - break; - case 1: - source = sysctl_clock_source_get_freq(SYSCTL_SOURCE_PLL0) / - (2ULL << sysctl_clock_get_threshold(SYSCTL_THRESHOLD_ACLK)); - break; - default: - break; - } - result = source; - break; - case SYSCTL_CLOCK_FFT: - switch (sysctl_clock_get_clock_select(SYSCTL_CLOCK_SELECT_ACLK)) - { - case 0: - source = sysctl_clock_source_get_freq(SYSCTL_SOURCE_IN0); - break; - case 1: - source = sysctl_clock_source_get_freq(SYSCTL_SOURCE_PLL0) / - (2ULL << sysctl_clock_get_threshold(SYSCTL_THRESHOLD_ACLK)); - break; - default: - break; - } - result = source; - break; - case SYSCTL_CLOCK_ACLK: - switch (sysctl_clock_get_clock_select(SYSCTL_CLOCK_SELECT_ACLK)) - { - case 0: - source = sysctl_clock_source_get_freq(SYSCTL_SOURCE_IN0); - break; - case 1: - source = sysctl_clock_source_get_freq(SYSCTL_SOURCE_PLL0) / - (2ULL << sysctl_clock_get_threshold(SYSCTL_THRESHOLD_ACLK)); - break; - default: - break; - } - result = source; - break; - case SYSCTL_CLOCK_HCLK: - switch (sysctl_clock_get_clock_select(SYSCTL_CLOCK_SELECT_ACLK)) - { - case 0: - source = sysctl_clock_source_get_freq(SYSCTL_SOURCE_IN0); - break; - case 1: - source = sysctl_clock_source_get_freq(SYSCTL_SOURCE_PLL0) / - (2ULL << sysctl_clock_get_threshold(SYSCTL_THRESHOLD_ACLK)); - break; - default: - break; - } - result = source; - break; - - /* - * These clock under ACLK clock domain. - * They are using gated divider. - */ - case SYSCTL_CLOCK_SRAM0: - source = sysctl_clock_source_get_freq(SYSCTL_SOURCE_ACLK); - result = source / (sysctl_clock_get_threshold(SYSCTL_THRESHOLD_SRAM0) + 1); - break; - case SYSCTL_CLOCK_SRAM1: - source = sysctl_clock_source_get_freq(SYSCTL_SOURCE_ACLK); - result = source / (sysctl_clock_get_threshold(SYSCTL_THRESHOLD_SRAM1) + 1); - break; - case SYSCTL_CLOCK_ROM: - source = sysctl_clock_source_get_freq(SYSCTL_SOURCE_ACLK); - result = source / (sysctl_clock_get_threshold(SYSCTL_THRESHOLD_ROM) + 1); - break; - case SYSCTL_CLOCK_DVP: - source = sysctl_clock_source_get_freq(SYSCTL_SOURCE_ACLK); - result = source / (sysctl_clock_get_threshold(SYSCTL_THRESHOLD_DVP) + 1); - break; - - /* - * These clock under ACLK clock domain. - * They are using even divider. - */ - case SYSCTL_CLOCK_APB0: - source = sysctl_clock_source_get_freq(SYSCTL_SOURCE_ACLK); - result = source / (sysctl_clock_get_threshold(SYSCTL_THRESHOLD_APB0) + 1); - break; - case SYSCTL_CLOCK_APB1: - source = sysctl_clock_source_get_freq(SYSCTL_SOURCE_ACLK); - result = source / (sysctl_clock_get_threshold(SYSCTL_THRESHOLD_APB1) + 1); - break; - case SYSCTL_CLOCK_APB2: - source = sysctl_clock_source_get_freq(SYSCTL_SOURCE_ACLK); - result = source / (sysctl_clock_get_threshold(SYSCTL_THRESHOLD_APB2) + 1); - break; - - /* - * These clock under AI clock domain. - * They are using gated divider. - */ - case SYSCTL_CLOCK_AI: - source = sysctl_clock_source_get_freq(SYSCTL_SOURCE_PLL1); - result = source / (sysctl_clock_get_threshold(SYSCTL_THRESHOLD_AI) + 1); - break; - - /* - * These clock under I2S clock domain. - * They are using even divider. - */ - case SYSCTL_CLOCK_I2S0: - source = sysctl_clock_source_get_freq(SYSCTL_SOURCE_PLL2); - result = source / ((sysctl_clock_get_threshold(SYSCTL_THRESHOLD_I2S0) + 1) * 2); - break; - case SYSCTL_CLOCK_I2S1: - source = sysctl_clock_source_get_freq(SYSCTL_SOURCE_PLL2); - result = source / ((sysctl_clock_get_threshold(SYSCTL_THRESHOLD_I2S1) + 1) * 2); - break; - case SYSCTL_CLOCK_I2S2: - source = sysctl_clock_source_get_freq(SYSCTL_SOURCE_PLL2); - result = source / ((sysctl_clock_get_threshold(SYSCTL_THRESHOLD_I2S2) + 1) * 2); - break; - - /* - * These clock under WDT clock domain. - * They are using even divider. - */ - case SYSCTL_CLOCK_WDT0: - source = sysctl_clock_source_get_freq(SYSCTL_SOURCE_IN0); - result = source / ((sysctl_clock_get_threshold(SYSCTL_THRESHOLD_WDT0) + 1) * 2); - break; - case SYSCTL_CLOCK_WDT1: - source = sysctl_clock_source_get_freq(SYSCTL_SOURCE_IN0); - result = source / ((sysctl_clock_get_threshold(SYSCTL_THRESHOLD_WDT1) + 1) * 2); - break; - - /* - * These clock under PLL0 clock domain. - * They are using even divider. - */ - case SYSCTL_CLOCK_SPI0: - source = sysctl_clock_source_get_freq(SYSCTL_SOURCE_PLL0); - result = source / ((sysctl_clock_get_threshold(SYSCTL_THRESHOLD_SPI0) + 1) * 2); - break; - case SYSCTL_CLOCK_SPI1: - source = sysctl_clock_source_get_freq(SYSCTL_SOURCE_PLL0); - result = source / ((sysctl_clock_get_threshold(SYSCTL_THRESHOLD_SPI1) + 1) * 2); - break; - case SYSCTL_CLOCK_SPI2: - source = sysctl_clock_source_get_freq(SYSCTL_SOURCE_PLL0); - result = source / ((sysctl_clock_get_threshold(SYSCTL_THRESHOLD_SPI2) + 1) * 2); - break; - case SYSCTL_CLOCK_I2C0: - source = sysctl_clock_source_get_freq(SYSCTL_SOURCE_PLL0); - result = source / ((sysctl_clock_get_threshold(SYSCTL_THRESHOLD_I2C0) + 1) * 2); - break; - case SYSCTL_CLOCK_I2C1: - source = sysctl_clock_source_get_freq(SYSCTL_SOURCE_PLL0); - result = source / ((sysctl_clock_get_threshold(SYSCTL_THRESHOLD_I2C1) + 1) * 2); - break; - case SYSCTL_CLOCK_I2C2: - source = sysctl_clock_source_get_freq(SYSCTL_SOURCE_PLL0); - result = source / ((sysctl_clock_get_threshold(SYSCTL_THRESHOLD_I2C2) + 1) * 2); - break; - - /* - * These clock under PLL0_SEL clock domain. - * They are using even divider. - */ - case SYSCTL_CLOCK_SPI3: - switch (sysctl_clock_get_clock_select(SYSCTL_CLOCK_SELECT_SPI3)) - { - case 0: - source = sysctl_clock_source_get_freq(SYSCTL_SOURCE_IN0); - break; - case 1: - source = sysctl_clock_source_get_freq(SYSCTL_SOURCE_PLL0); - break; - default: - break; - } - - result = source / ((sysctl_clock_get_threshold(SYSCTL_THRESHOLD_SPI3) + 1) * 2); - break; - case SYSCTL_CLOCK_TIMER0: - switch (sysctl_clock_get_clock_select(SYSCTL_CLOCK_SELECT_TIMER0)) - { - case 0: - source = sysctl_clock_source_get_freq(SYSCTL_SOURCE_IN0); - break; - case 1: - source = sysctl_clock_source_get_freq(SYSCTL_SOURCE_PLL0); - break; - default: - break; - } - - result = source / ((sysctl_clock_get_threshold(SYSCTL_THRESHOLD_TIMER0) + 1) * 2); - break; - case SYSCTL_CLOCK_TIMER1: - switch (sysctl_clock_get_clock_select(SYSCTL_CLOCK_SELECT_TIMER1)) - { - case 0: - source = sysctl_clock_source_get_freq(SYSCTL_SOURCE_IN0); - break; - case 1: - source = sysctl_clock_source_get_freq(SYSCTL_SOURCE_PLL0); - break; - default: - break; - } - - result = source / ((sysctl_clock_get_threshold(SYSCTL_THRESHOLD_TIMER1) + 1) * 2); - break; - case SYSCTL_CLOCK_TIMER2: - switch (sysctl_clock_get_clock_select(SYSCTL_CLOCK_SELECT_TIMER2)) - { - case 0: - source = sysctl_clock_source_get_freq(SYSCTL_SOURCE_IN0); - break; - case 1: - source = sysctl_clock_source_get_freq(SYSCTL_SOURCE_PLL0); - break; - default: - break; - } - - result = source / ((sysctl_clock_get_threshold(SYSCTL_THRESHOLD_TIMER2) + 1) * 2); - break; - - /* - * These clock under MISC clock domain. - * They are using even divider. - */ - - /* - * These clock under APB0 clock domain. - * They are using even divider. - */ - case SYSCTL_CLOCK_GPIO: - source = sysctl_clock_get_freq(SYSCTL_CLOCK_APB0); - result = source; - break; - case SYSCTL_CLOCK_UART1: - source = sysctl_clock_get_freq(SYSCTL_CLOCK_APB0); - result = source; - break; - case SYSCTL_CLOCK_UART2: - source = sysctl_clock_get_freq(SYSCTL_CLOCK_APB0); - result = source; - break; - case SYSCTL_CLOCK_UART3: - source = sysctl_clock_get_freq(SYSCTL_CLOCK_APB0); - result = source; - break; - case SYSCTL_CLOCK_FPIOA: - source = sysctl_clock_get_freq(SYSCTL_CLOCK_APB0); - result = source; - break; - case SYSCTL_CLOCK_SHA: - source = sysctl_clock_get_freq(SYSCTL_CLOCK_APB0); - result = source; - break; - - /* - * These clock under APB1 clock domain. - * They are using even divider. - */ - case SYSCTL_CLOCK_AES: - source = sysctl_clock_get_freq(SYSCTL_CLOCK_APB1); - result = source; - break; - case SYSCTL_CLOCK_OTP: - source = sysctl_clock_get_freq(SYSCTL_CLOCK_APB1); - result = source; - break; - case SYSCTL_CLOCK_RTC: - source = sysctl_clock_source_get_freq(SYSCTL_SOURCE_IN0); - result = source; - break; - - /* - * These clock under APB2 clock domain. - * They are using even divider. - */ - /* - * Do nothing. - */ - default: - break; - } - return result; -} - -int sysctl_dma_select(sysctl_dma_channel_t channel, sysctl_dma_select_t select) -{ - sysctl_dma_sel0_t dma_sel0; - sysctl_dma_sel1_t dma_sel1; - - /* Read register from bus */ - dma_sel0 = sysctl->dma_sel0; - dma_sel1 = sysctl->dma_sel1; - switch (channel) - { - case SYSCTL_DMA_CHANNEL_0: - dma_sel0.dma_sel0 = select; - break; - - case SYSCTL_DMA_CHANNEL_1: - dma_sel0.dma_sel1 = select; - break; - - case SYSCTL_DMA_CHANNEL_2: - dma_sel0.dma_sel2 = select; - break; - - case SYSCTL_DMA_CHANNEL_3: - dma_sel0.dma_sel3 = select; - break; - - case SYSCTL_DMA_CHANNEL_4: - dma_sel0.dma_sel4 = select; - break; - - case SYSCTL_DMA_CHANNEL_5: - dma_sel1.dma_sel5 = select; - break; - - default: - return -1; - } - - /* Write register back to bus */ - sysctl->dma_sel0 = dma_sel0; - sysctl->dma_sel1 = dma_sel1; - - return 0; -} - -uint32_t sysctl_pll_fast_enable_pll(void) -{ - /* - * Begin write PLL registers' value, - * Using atomic write method. - */ - sysctl_pll0_t pll0; - sysctl_pll1_t pll1; - sysctl_pll2_t pll2; - - /* Read register from bus */ - pll0 = sysctl->pll0; - pll1 = sysctl->pll1; - pll2 = sysctl->pll2; - - /* PLL VCO MAX freq: 1.8GHz */ - - /* PLL0: 26M reference clk get 793M output clock */ - pll0.clkr0 = 0; - pll0.clkf0 = 60; - pll0.clkod0 = 1; - pll0.bwadj0 = 60; - - /* PLL1: 26M reference clk get 390M output clock */ - pll1.clkr1 = 0; - pll1.clkf1 = 59; - pll1.clkod1 = 3; - pll1.bwadj1 = 59; - - /* PLL2: 26M reference clk get 390M output clock */ - pll2.clkr2 = 0; - pll2.clkf2 = 59; - pll2.clkod2 = 3; - pll2.bwadj2 = 59; - - /* Write register to bus */ - sysctl->pll0 = pll0; - sysctl->pll1 = pll1; - sysctl->pll2 = pll2; - - sysctl_pll_enable(SYSCTL_PLL0); - sysctl_pll_enable(SYSCTL_PLL1); - sysctl_pll_enable(SYSCTL_PLL2); - - while (sysctl_pll_is_lock(SYSCTL_PLL0) == 0) - sysctl_pll_clear_slip(SYSCTL_PLL0); - while (sysctl_pll_is_lock(SYSCTL_PLL1) == 0) - sysctl_pll_clear_slip(SYSCTL_PLL1); - while (sysctl_pll_is_lock(SYSCTL_PLL2) == 0) - sysctl_pll_clear_slip(SYSCTL_PLL2); - - sysctl_clock_enable(SYSCTL_CLOCK_PLL0); - sysctl_clock_enable(SYSCTL_CLOCK_PLL1); - sysctl_clock_enable(SYSCTL_CLOCK_PLL2); - - /* Set ACLK to PLL0 */ - sysctl_clock_set_clock_select(SYSCTL_CLOCK_SELECT_ACLK, SYSCTL_SOURCE_PLL0); - - return 0; -} - -uint32_t sysctl_set_spi0_dvp_data(uint8_t en) -{ - sysctl->misc.spi_dvp_data_enable = en; - return 0; -} - -void sysctl_set_power_mode(sysctl_power_bank_t power_bank, sysctl_io_power_mode_t io_power_mode) -{ - if(io_power_mode) - *((uint32_t *)(&sysctl->power_sel)) |= (1 << power_bank); - else - *((uint32_t *)(&sysctl->power_sel)) &= ~(1 << power_bank); -} - -uint32_t sysctl_pll_set_freq(sysctl_pll_t pll, uint32_t pll_freq) -{ - if(pll_freq == 0) - return 0; - - volatile sysctl_general_pll_t *v_pll_t; - switch(pll) - { - case SYSCTL_PLL0: - v_pll_t = (sysctl_general_pll_t *)(&sysctl->pll0); - break; - case SYSCTL_PLL1: - v_pll_t = (sysctl_general_pll_t *)(&sysctl->pll1); - break; - case SYSCTL_PLL2: - v_pll_t = (sysctl_general_pll_t *)(&sysctl->pll2); - break; - default: - return 0; - break; - } - - /* 1. Change CPU CLK to XTAL */ - if(pll == SYSCTL_PLL0) - sysctl_clock_set_clock_select(SYSCTL_CLOCK_SELECT_ACLK, SYSCTL_SOURCE_IN0); - - /* 2. Disable PLL output */ - v_pll_t->pll_out_en = 0; - - /* 3. Turn off PLL */ - v_pll_t->pll_pwrd = 0; - - /* 4. Set PLL new value */ - uint32_t result; - if(pll == SYSCTL_PLL2) - result = sysctl_pll_source_set_freq(pll, v_pll_t->pll_ckin_sel, pll_freq); - else - result = sysctl_pll_source_set_freq(pll, SYSCTL_SOURCE_IN0, pll_freq); - - /* 5. Power on PLL */ - v_pll_t->pll_pwrd = 1; - /* wait >100ns */ - usleep(1); - - /* 6. Reset PLL then Release Reset*/ - v_pll_t->pll_reset = 0; - v_pll_t->pll_reset = 1; - /* wait >100ns */ - usleep(1); - v_pll_t->pll_reset = 0; - - /* 7. Get lock status, wait PLL stable */ - while (sysctl_pll_is_lock(pll) == 0) - sysctl_pll_clear_slip(pll); - - /* 8. Enable PLL output */ - v_pll_t->pll_out_en = 1; - - /* 9. Change CPU CLK to PLL */ - if(pll == SYSCTL_PLL0) - sysctl_clock_set_clock_select(SYSCTL_CLOCK_SELECT_ACLK, SYSCTL_SOURCE_PLL0); - - return result; -} - -static uint32_t cpu_freq = 390000000; - -uint32_t sysctl_cpu_get_freq(void) -{ - return cpu_freq; -} - -uint32_t sysctl_cpu_set_freq(uint32_t freq) -{ - if(freq == 0) - return 0; - - cpu_freq = sysctl_pll_set_freq(SYSCTL_PLL0, (sysctl->clk_sel0.aclk_divider_sel + 1) * 2 * freq); - return cpu_freq; -} - -void sysctl_enable_irq(void) -{ - set_csr(mie, MIP_MEIP); - set_csr(mstatus, MSTATUS_MIE); -} - -void sysctl_disable_irq(void) -{ - clear_csr(mie, MIP_MEIP); - clear_csr(mstatus, MSTATUS_MIE); -} - -uint64_t sysctl_get_time_us(void) -{ - uint64_t v_cycle = read_cycle(); - return v_cycle * 1000000 / sysctl_clock_get_freq(SYSCTL_CLOCK_CPU); -} - -sysctl_reset_enum_status_t sysctl_get_reset_status(void) -{ - static sysctl_reset_enum_status_t s_reset_status = 0; - if(s_reset_status != 0) - { - return s_reset_status; - } - - if(sysctl->reset_status.wdt0_reset_sts) - { - s_reset_status = SYSCTL_RESET_STATUS_WDT0; - } - else if(sysctl->reset_status.wdt1_reset_sts) - { - s_reset_status = SYSCTL_RESET_STATUS_WDT1; - } - else if(sysctl->reset_status.soft_reset_sts) - { - s_reset_status = SYSCTL_RESET_STATUS_SOFT; - } - else - { - s_reset_status = SYSCTL_RESET_STATUS_HARD; - } - sysctl->reset_status.reset_sts_clr = 1; - - return s_reset_status; -} - diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/timer.c b/cores/arduino/kendryte-standalone-sdk/lib/drivers/timer.c deleted file mode 100644 index b638ccc..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/timer.c +++ /dev/null @@ -1,391 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include "timer.h" -#include "sysctl.h" -#include "stddef.h" -#include "utils.h" -#include "plic.h" -#include "io.h" - -/** - * @brief Private definitions for the timer instance - */ -typedef struct timer_instance -{ - timer_callback_t callback; - void *ctx; - bool single_shot; -} timer_instance_t; - -volatile timer_instance_t timer_instance[TIMER_DEVICE_MAX][TIMER_CHANNEL_MAX]; - -volatile kendryte_timer_t *const timer[3] = -{ - (volatile kendryte_timer_t *)TIMER0_BASE_ADDR, - (volatile kendryte_timer_t *)TIMER1_BASE_ADDR, - (volatile kendryte_timer_t *)TIMER2_BASE_ADDR -}; - -void timer_init(timer_device_number_t timer_number) -{ - for(size_t i = 0; i < TIMER_CHANNEL_MAX; i++) - timer_instance[timer_number][i] = (const timer_instance_t) { - .callback = NULL, - .ctx = NULL, - .single_shot = 0, - }; - - sysctl_clock_enable(SYSCTL_CLOCK_TIMER0 + timer_number); -} - -void timer_set_clock_div(timer_device_number_t timer_number, uint32_t div) -{ - sysctl_clock_set_threshold(timer_number == 0 ? SYSCTL_THRESHOLD_TIMER0 : - timer_number == 1 ? SYSCTL_THRESHOLD_TIMER1 : - SYSCTL_THRESHOLD_TIMER2, div); -} - -void timer_enable(timer_device_number_t timer_number, timer_channel_number_t channel) -{ - timer[timer_number]->channel[channel].control |= TIMER_CR_ENABLE; -} - -void timer_disable(timer_device_number_t timer_number, timer_channel_number_t channel) -{ - timer[timer_number]->channel[channel].control &= (~TIMER_CR_ENABLE); -} - -void timer_enable_pwm(timer_device_number_t timer_number, timer_channel_number_t channel) -{ - timer[timer_number]->channel[channel].control |= TIMER_CR_PWM_ENABLE; -} - -void timer_disable_pwm(timer_device_number_t timer_number, timer_channel_number_t channel) -{ - timer[timer_number]->channel[channel].control &= (~TIMER_CR_PWM_ENABLE); -} - -void timer_enable_interrupt(timer_device_number_t timer_number, timer_channel_number_t channel) -{ - timer[timer_number]->channel[channel].control &= (~TIMER_CR_INTERRUPT_MASK); -} - -void timer_disable_interrupt(timer_device_number_t timer_number, timer_channel_number_t channel) -{ - timer[timer_number]->channel[channel].control |= TIMER_CR_INTERRUPT_MASK; -} - -void timer_set_mode(timer_device_number_t timer_number, timer_channel_number_t channel, uint32_t mode) -{ - timer[timer_number]->channel[channel].control &= (~TIMER_CR_MODE_MASK); - timer[timer_number]->channel[channel].control |= mode; -} - -void timer_set_reload(timer_device_number_t timer_number, timer_channel_number_t channel, uint32_t count) -{ - timer[timer_number]->channel[channel].load_count = count; -} - -void timer_set_reload2(timer_device_number_t timer_number, timer_channel_number_t channel, uint32_t count) -{ - timer[timer_number]->load_count2[channel] = count; -} - -uint32_t timer_get_count(timer_device_number_t timer_number, timer_channel_number_t channel) -{ - return timer[timer_number]->channel[channel].current_value; -} - -uint32_t timer_get_reload(timer_device_number_t timer_number, timer_channel_number_t channel) -{ - return timer[timer_number]->channel[channel].load_count; -} - -uint32_t timer_get_reload2(timer_device_number_t timer_number, timer_channel_number_t channel) -{ - return timer[timer_number]->load_count2[channel]; -} - -uint32_t timer_get_interrupt_status(timer_device_number_t timer_number) -{ - return timer[timer_number]->intr_stat; -} - -uint32_t timer_get_raw_interrupt_status(timer_device_number_t timer_number) -{ - return timer[timer_number]->raw_intr_stat; -} - -uint32_t timer_channel_get_interrupt_status(timer_device_number_t timer_number, timer_channel_number_t channel) -{ - return timer[timer_number]->channel[channel].intr_stat; -} - -void timer_clear_interrupt(timer_device_number_t timer_number) -{ - timer[timer_number]->eoi = timer[timer_number]->eoi; -} - -void timer_channel_clear_interrupt(timer_device_number_t timer_number, timer_channel_number_t channel) -{ - timer[timer_number]->channel[channel].eoi = timer[timer_number]->channel[channel].eoi; -} - -void timer_set_enable(timer_device_number_t timer_number, timer_channel_number_t channel, uint32_t enable) -{ - if (enable) - timer[timer_number]->channel[channel].control = TIMER_CR_USER_MODE | TIMER_CR_ENABLE; - else - timer[timer_number]->channel[channel].control = TIMER_CR_INTERRUPT_MASK; -} - -size_t timer_set_interval(timer_device_number_t timer_number, timer_channel_number_t channel, size_t nanoseconds) -{ - uint32_t clk_freq = sysctl_clock_get_freq(SYSCTL_CLOCK_TIMER0 + timer_number); - - double min_step = 1e9 / clk_freq; - size_t value = (size_t)(nanoseconds / min_step); - configASSERT(value > 0 && value < UINT32_MAX); - timer[timer_number]->channel[channel].load_count = (uint32_t)value; - return (size_t)(min_step * value); -} - -typedef void(*timer_ontick)(); -timer_ontick time_irq[3][4] = { NULL }; - -static int timer_isr(void *parm) -{ - uint32_t timer_number; - for (timer_number = 0; timer_number < 3; timer_number++) - { - if (parm == timer[timer_number]) - break; - } - - uint32_t channel = timer[timer_number]->intr_stat; - size_t i = 0; - for (i = 0; i < 4; i++) - { - if (channel & 1) - { - if (time_irq[timer_number][i]) - (time_irq[timer_number][i])(); - break; - } - - channel >>= 1; - } - - readl(&timer[timer_number]->eoi); - return 0; -} - -void timer_set_irq(timer_device_number_t timer_number, timer_channel_number_t channel, void(*func)(), uint32_t priority) -{ - time_irq[timer_number][channel] = func; - if (channel < 2) - { - plic_set_priority(IRQN_TIMER0A_INTERRUPT + timer_number * 2, priority); - plic_irq_register(IRQN_TIMER0A_INTERRUPT + timer_number * 2, timer_isr, (void *)timer[timer_number]); - plic_irq_enable(IRQN_TIMER0A_INTERRUPT + timer_number * 2); - } - else - { - plic_set_priority(IRQN_TIMER0B_INTERRUPT + timer_number * 2, priority); - plic_irq_register(IRQN_TIMER0B_INTERRUPT + timer_number * 2, timer_isr, (void *)timer[timer_number]); - plic_irq_enable(IRQN_TIMER0B_INTERRUPT + timer_number * 2); - } -} - -/** - * @brief Get the timer irqn by device and channel object - * - * @note Internal function, not public - * @param device The device - * @param channel The channel - * @return plic_irq_t IRQ number - */ -static plic_irq_t get_timer_irqn_by_device_and_channel(timer_device_number_t device, timer_channel_number_t channel) -{ - if (device < TIMER_DEVICE_MAX && channel < TIMER_CHANNEL_MAX) { - /* - * Select timer interrupt part - * Hierarchy of Timer interrupt to PLIC - * +---------+ +-----------+ - * | 0+----+ | | - * | | +--+0A | - * | 1+----+ | | - * | TIMER0 | | | - * | 2+----+ | | - * | | +--+0B | - * | 3+----+ | | - * +---------+ | | - * | | - * +---------+ | | - * | 0+----+ | | - * | | +--+1A | - * | 1+----+ | | - * | TIMER1 | | PLIC | - * | 2+----+ | | - * | | +--+1B | - * | 3+----+ | | - * +---------+ | | - * | | - * +---------+ | | - * | 0+----+ | | - * | | +--+2A | - * | 1+----+ | | - * | TIMER2 | | | - * | 2+----+ | | - * | | +--+2B | - * | 3+----+ | | - * +---------+ +-----------+ - * - */ - if (channel < 2) { - /* It is part A interrupt, offset + 0 */ - return IRQN_TIMER0A_INTERRUPT + device * 2; - } - else { - /* It is part B interrupt, offset + 1 */ - return IRQN_TIMER0B_INTERRUPT + device * 2; - } - } - return IRQN_NO_INTERRUPT; -} - -/** - * @brief Process user callback function - * - * @note Internal function, not public - * @param device The timer device - * @param ctx The context - * @return int The callback result - */ -static int timer_interrupt_handler(timer_device_number_t device, void *ctx) -{ - uint32_t channel_int_stat = timer[device]->intr_stat; - - for (size_t i = 0; i < TIMER_CHANNEL_MAX; i++) - { - /* Check every bit for interrupt status */ - if (channel_int_stat & 1) - { - if (timer_instance[device][i].callback) { - /* Process user callback function */ - timer_instance[device][i].callback(timer_instance[device][i].ctx); - /* Check if this timer is a single shot timer */ - if (timer_instance[device][i].single_shot) { - /* Single shot timer, disable it */ - timer_set_enable(device, i, 0); - } - } - /* Clear timer interrupt flag for specific channel */ - readl(&timer[device]->channel[i].eoi); - } - channel_int_stat >>= 1; - } - - /* - * NOTE: - * Don't read timer[device]->eoi here, or you will lost some interrupt - * readl(&timer[device]->eoi); - */ - - return 0; -} - -/** - * @brief Callback function bus for timer interrupt - * - * @note Internal function, not public - * @param ctx The context - * @return int The callback result - */ -static int timer0_interrupt_callback(void *ctx) -{ - return timer_interrupt_handler(TIMER_DEVICE_0, ctx); -} - -/** - * @brief Callback function bus for timer interrupt - * - * @note Internal function, not public - * @param ctx The context - * @return int The callback result - */ -static int timer1_interrupt_callback(void *ctx) -{ - return timer_interrupt_handler(TIMER_DEVICE_1, ctx); -} - -/** - * @brief Callback function bus for timer interrupt - * - * @note Internal function, not public - * @param ctx The context - * @return int The callback result - */ -static int timer2_interrupt_callback(void *ctx) -{ - return timer_interrupt_handler(TIMER_DEVICE_2, ctx); -} - -int timer_irq_register(timer_device_number_t device, timer_channel_number_t channel, int is_single_shot, uint32_t priority, timer_callback_t callback, void *ctx) -{ - if (device < TIMER_DEVICE_MAX && channel < TIMER_CHANNEL_MAX) { - plic_irq_t irq_number = get_timer_irqn_by_device_and_channel(device, channel); - plic_irq_callback_t plic_irq_callback[TIMER_DEVICE_MAX] = { - timer0_interrupt_callback, - timer1_interrupt_callback, - timer2_interrupt_callback, - }; - - timer_instance[device][channel] = (const timer_instance_t) { - .callback = callback, - .ctx = ctx, - .single_shot = is_single_shot, - }; - plic_set_priority(irq_number, priority); - plic_irq_register(irq_number, plic_irq_callback[device], (void *)&timer_instance[device]); - plic_irq_enable(irq_number); - return 0; - } - return -1; -} - -int timer_irq_unregister(timer_device_number_t device, timer_channel_number_t channel) -{ - if (device < TIMER_DEVICE_MAX && channel < TIMER_CHANNEL_MAX) { - timer_instance[device][channel] = (const timer_instance_t) { - .callback = NULL, - .ctx = NULL, - .single_shot = 0, - }; - - /* Combine 0 and 1 to A interrupt, 2 and 3 to B interrupt */ - if ((!(timer_instance[device][TIMER_CHANNEL_0].callback || - timer_instance[device][TIMER_CHANNEL_1].callback)) || - (!(timer_instance[device][TIMER_CHANNEL_2].callback || - timer_instance[device][TIMER_CHANNEL_3].callback))) { - plic_irq_t irq_number = get_timer_irqn_by_device_and_channel(device, channel); - plic_irq_unregister(irq_number); - } - return 0; - } - return -1; -} \ No newline at end of file diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/uart.c b/cores/arduino/kendryte-standalone-sdk/lib/drivers/uart.c deleted file mode 100644 index b31b696..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/uart.c +++ /dev/null @@ -1,338 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include -#include -#include "plic.h" -#include "sysctl.h" -#include "uart.h" -#include "utils.h" -#include "atomic.h" - -#define __UART_BRATE_CONST 16 - -volatile uart_t* const uart[3] = -{ - (volatile uart_t*)UART1_BASE_ADDR, - (volatile uart_t*)UART2_BASE_ADDR, - (volatile uart_t*)UART3_BASE_ADDR -}; - -#define UART_INTERRUPT_SEND 0x02U -#define UART_INTERRUPT_RECEIVE 0x04U -#define UART_INTERRUPT_CHARACTER_TIMEOUT 0x0CU - -typedef struct _uart_interrupt_instance -{ - plic_irq_callback_t callback; - void *ctx; -} uart_interrupt_instance_t; - -typedef struct _uart_instance -{ - uart_interrupt_instance_t uart_receive_instance; - uart_interrupt_instance_t uart_send_instance; - uint32_t uart_num; -} uart_instance_t; - -uart_instance_t g_uart_instance[3]; - -typedef struct _uart_dma_instance -{ - uint8_t *buffer; - size_t buf_len; - uint32_t *malloc_buffer; - uart_interrupt_mode_t int_mode; - dmac_channel_number_t dmac_channel; - uart_device_number_t uart_num; - uart_interrupt_instance_t uart_int_instance; -} uart_dma_instance_t; - -uart_dma_instance_t uart_send_dma_instance[3]; -uart_dma_instance_t uart_recv_dma_instance[3]; - -volatile int g_write_count = 0; - -static int uart_irq_callback(void *param) -{ - uart_instance_t *uart_instance = (uart_instance_t *)param; - uint32_t v_channel = uart_instance->uart_num; - uint8_t v_int_status = uart[v_channel]->IIR & 0xF; - - if(v_int_status == UART_INTERRUPT_SEND && g_write_count != 0) - { - if(uart_instance->uart_send_instance.callback != NULL) - uart_instance->uart_send_instance.callback(uart_instance->uart_send_instance.ctx); - } - else if(v_int_status == UART_INTERRUPT_RECEIVE || v_int_status == UART_INTERRUPT_CHARACTER_TIMEOUT) - { - if(uart_instance->uart_receive_instance.callback != NULL) - uart_instance->uart_receive_instance.callback(uart_instance->uart_receive_instance.ctx); - } - return 0; -} - -static int uartapb_putc(uart_device_number_t channel, char c) -{ - while (uart[channel]->LSR & (1u << 5)) - continue; - uart[channel]->THR = c; - return 0; -} - -int uartapb_getc(uart_device_number_t channel) -{ - while (!(uart[channel]->LSR & 1)) - continue; - - return (char)(uart[channel]->RBR & 0xff); -} - -static int uart_dma_callback(void *ctx) -{ - uart_dma_instance_t *v_uart_dma_instance = (uart_dma_instance_t *)ctx; - dmac_channel_number_t dmac_channel = v_uart_dma_instance->dmac_channel; - dmac_irq_unregister(dmac_channel); - - if(v_uart_dma_instance->int_mode == UART_RECEIVE) - { - size_t v_buf_len = v_uart_dma_instance->buf_len; - uint8_t *v_buffer = v_uart_dma_instance->buffer; - uint32_t *v_recv_buffer = v_uart_dma_instance->malloc_buffer; - for(size_t i = 0; i < v_buf_len; i++) - { - v_buffer[i] = v_recv_buffer[i]; - } - } - free(v_uart_dma_instance->malloc_buffer); - if(v_uart_dma_instance->uart_int_instance.callback) - v_uart_dma_instance->uart_int_instance.callback(v_uart_dma_instance->uart_int_instance.ctx); - return 0; -} - -int uart_receive_data(uart_device_number_t channel, char *buffer, size_t buf_len) -{ - size_t i = 0; - for(i = 0;i < buf_len; i++) - { - if(uart[channel]->LSR & 1) - buffer[i] = (char)(uart[channel]->RBR & 0xff); - else - break; - } - return i; -} - -void uart_receive_data_dma(uart_device_number_t uart_channel, dmac_channel_number_t dmac_channel, uint8_t *buffer, size_t buf_len) -{ - uint32_t *v_recv_buf = malloc(buf_len * sizeof(uint32_t)); - configASSERT(v_recv_buf!=NULL); - - sysctl_dma_select((sysctl_dma_channel_t)dmac_channel, SYSCTL_DMA_SELECT_UART1_RX_REQ + uart_channel * 2); - dmac_set_single_mode(dmac_channel, (void *)(&uart[uart_channel]->RBR), v_recv_buf, DMAC_ADDR_NOCHANGE, DMAC_ADDR_INCREMENT, - DMAC_MSIZE_1, DMAC_TRANS_WIDTH_32, buf_len); - dmac_wait_done(dmac_channel); - for(uint32_t i = 0; i < buf_len; i++) - { - buffer[i] = (uint8_t)(v_recv_buf[i] & 0xff); - } -} - -void uart_receive_data_dma_irq(uart_device_number_t uart_channel, dmac_channel_number_t dmac_channel, - uint8_t *buffer, size_t buf_len, plic_irq_callback_t uart_callback, - void *ctx, uint32_t priority) -{ - uint32_t *v_recv_buf = malloc(buf_len * sizeof(uint32_t)); - configASSERT(v_recv_buf!=NULL); - - uart_recv_dma_instance[uart_channel].dmac_channel = dmac_channel; - uart_recv_dma_instance[uart_channel].uart_num = uart_channel; - uart_recv_dma_instance[uart_channel].malloc_buffer = v_recv_buf; - uart_recv_dma_instance[uart_channel].buffer = buffer; - uart_recv_dma_instance[uart_channel].buf_len = buf_len; - uart_recv_dma_instance[uart_channel].int_mode = UART_RECEIVE; - uart_recv_dma_instance[uart_channel].uart_int_instance.callback = uart_callback; - uart_recv_dma_instance[uart_channel].uart_int_instance.ctx = ctx; - - dmac_irq_register(dmac_channel, uart_dma_callback, &uart_recv_dma_instance[uart_channel], priority); - sysctl_dma_select((sysctl_dma_channel_t)dmac_channel, SYSCTL_DMA_SELECT_UART1_RX_REQ + uart_channel * 2); - dmac_set_single_mode(dmac_channel, (void *)(&uart[uart_channel]->RBR), v_recv_buf, DMAC_ADDR_NOCHANGE, DMAC_ADDR_INCREMENT, - DMAC_MSIZE_1, DMAC_TRANS_WIDTH_32, buf_len); -} - -int uart_send_data(uart_device_number_t channel, const char *buffer, size_t buf_len) -{ - g_write_count = 0; - while (g_write_count < buf_len) - { - uartapb_putc(channel, *buffer++); - g_write_count++; - } - return g_write_count; -} - -void uart_send_data_dma(uart_device_number_t uart_channel, dmac_channel_number_t dmac_channel, const uint8_t *buffer, size_t buf_len) -{ - uint32_t *v_send_buf = malloc(buf_len * sizeof(uint32_t)); - configASSERT(v_send_buf!=NULL); - for(uint32_t i = 0; i < buf_len; i++) - v_send_buf[i] = buffer[i]; - sysctl_dma_select((sysctl_dma_channel_t)dmac_channel, SYSCTL_DMA_SELECT_UART1_TX_REQ + uart_channel * 2); - dmac_set_single_mode(dmac_channel, v_send_buf, (void *)(&uart[uart_channel]->THR), DMAC_ADDR_INCREMENT, DMAC_ADDR_NOCHANGE, - DMAC_MSIZE_1, DMAC_TRANS_WIDTH_32, buf_len); - dmac_wait_done(dmac_channel); - free((void *)v_send_buf); -} - -void uart_send_data_dma_irq(uart_device_number_t uart_channel, dmac_channel_number_t dmac_channel, - const uint8_t *buffer, size_t buf_len, plic_irq_callback_t uart_callback, - void *ctx, uint32_t priority) -{ - uint32_t *v_send_buf = malloc(buf_len * sizeof(uint32_t)); - configASSERT(v_send_buf!=NULL); - - uart_send_dma_instance[uart_channel] = (uart_dma_instance_t) { - .dmac_channel = dmac_channel, - .uart_num = uart_channel, - .malloc_buffer = v_send_buf, - .buffer = (uint8_t *)buffer, - .buf_len = buf_len, - .int_mode = UART_SEND, - .uart_int_instance.callback = uart_callback, - .uart_int_instance.ctx = ctx, - }; - - for(uint32_t i = 0; i < buf_len; i++) - v_send_buf[i] = buffer[i]; - dmac_irq_register(dmac_channel, uart_dma_callback, &uart_send_dma_instance[uart_channel], priority); - sysctl_dma_select((sysctl_dma_channel_t)dmac_channel, SYSCTL_DMA_SELECT_UART1_TX_REQ + uart_channel * 2); - dmac_set_single_mode(dmac_channel, v_send_buf, (void *)(&uart[uart_channel]->THR), DMAC_ADDR_INCREMENT, DMAC_ADDR_NOCHANGE, - DMAC_MSIZE_1, DMAC_TRANS_WIDTH_32, buf_len); - -} - -void uart_configure(uart_device_number_t channel, uint32_t baud_rate, uart_bitwidth_t data_width, uart_stopbit_t stopbit, uart_parity_t parity) -{ - configASSERT(data_width >= 5 && data_width <= 8); - if (data_width == 5) - { - configASSERT(stopbit != UART_STOP_2); - } - else - { - configASSERT(stopbit != UART_STOP_1_5); - } - - uint32_t stopbit_val = stopbit == UART_STOP_1 ? 0 : 1; - uint32_t parity_val; - switch (parity) - { - case UART_PARITY_NONE: - parity_val = 0; - break; - case UART_PARITY_ODD: - parity_val = 1; - break; - case UART_PARITY_EVEN: - parity_val = 3; - break; - default: - configASSERT(!"Invalid parity"); - break; - } - - uint32_t freq = sysctl_clock_get_freq(SYSCTL_CLOCK_APB0); - uint32_t divisor = freq / baud_rate; - uint8_t dlh = divisor >> 12; - uint8_t dll = (divisor - (dlh << 12)) / __UART_BRATE_CONST; - uint8_t dlf = divisor - (dlh << 12) - dll * __UART_BRATE_CONST; - - /* Set UART registers */ - uart[channel]->TCR &= ~(1u); - uart[channel]->TCR &= ~(1u << 3); - uart[channel]->TCR &= ~(1u << 4); - uart[channel]->TCR |= (1u << 2); - uart[channel]->TCR &= ~(1u << 1); - uart[channel]->DE_EN &= ~(1u); - - uart[channel]->LCR |= 1u << 7; - uart[channel]->DLH = dlh; - uart[channel]->DLL = dll; - uart[channel]->DLF = dlf; - uart[channel]->LCR = 0; - uart[channel]->LCR = (data_width - 5) | (stopbit_val << 2) | (parity_val << 3); - uart[channel]->LCR &= ~(1u << 7); - uart[channel]->MCR &= ~3; - uart[channel]->IER |= 0x80; /* THRE */ - uart[channel]->FCR = UART_RECEIVE_FIFO_1 << 6 | UART_SEND_FIFO_8 << 4 | 0x1 << 3 | 0x1; -} - -void __attribute__((weak, alias("uart_configure"))) -uart_config(uart_device_number_t channel, uint32_t baud_rate, uart_bitwidth_t data_width, uart_stopbit_t stopbit, uart_parity_t parity); - -void uart_init(uart_device_number_t channel) -{ - sysctl_clock_enable(SYSCTL_CLOCK_UART1 + channel); -} - -void uart_set_send_trigger(uart_device_number_t channel, uart_send_trigger_t trigger) -{ - uart[channel]->STET = trigger; -} - -void uart_set_receive_trigger(uart_device_number_t channel, uart_receive_trigger_t trigger) -{ - uart[channel]->SRT = trigger; -} - -void uart_irq_register(uart_device_number_t channel, uart_interrupt_mode_t interrupt_mode, plic_irq_callback_t uart_callback, void *ctx, uint32_t priority) -{ - if(interrupt_mode == UART_SEND) - { - uart[channel]->IER |= 0x2; - g_uart_instance[channel].uart_send_instance.callback = uart_callback; - g_uart_instance[channel].uart_send_instance.ctx = ctx; - } - else if(interrupt_mode == UART_RECEIVE) - { - uart[channel]->IER |= 0x1; - g_uart_instance[channel].uart_receive_instance.callback = uart_callback; - g_uart_instance[channel].uart_receive_instance.ctx = ctx; - } - g_uart_instance[channel].uart_num = channel; - plic_set_priority(IRQN_UART1_INTERRUPT + channel, priority); - plic_irq_register(IRQN_UART1_INTERRUPT + channel, uart_irq_callback, &g_uart_instance[channel]); - plic_irq_enable(IRQN_UART1_INTERRUPT + channel); -} - -void uart_irq_unregister(uart_device_number_t channel, uart_interrupt_mode_t interrupt_mode) -{ - if(interrupt_mode == UART_SEND) - { - uart[channel]->IER &= ~(0x2); - g_uart_instance[channel].uart_send_instance.callback = NULL; - g_uart_instance[channel].uart_send_instance.ctx = NULL; - } - else if(interrupt_mode == UART_RECEIVE) - { - uart[channel]->IER &= ~(0x1); - g_uart_instance[channel].uart_receive_instance.callback = NULL; - g_uart_instance[channel].uart_receive_instance.ctx = NULL; - } - if(uart[channel]->IER == 0) - { - plic_irq_unregister(IRQN_UART1_INTERRUPT + channel); - } -} - diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/uarths.c b/cores/arduino/kendryte-standalone-sdk/lib/drivers/uarths.c deleted file mode 100644 index aa6ee10..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/uarths.c +++ /dev/null @@ -1,176 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include -#include "uarths.h" -#include "sysctl.h" -#include "encoding.h" - -volatile uarths_t *const uarths = (volatile uarths_t *)UARTHS_BASE_ADDR; - -typedef struct _uarths_instance -{ - plic_irq_callback_t callback; - void *ctx; - uarths_interrupt_mode_t uarths_interrupt_mode; -} uarths_instance_t; - -uarths_instance_t g_uarths_instance; - -uarths_interrupt_mode_t uarths_get_interrupt_mode(void) -{ - uint32_t v_rx_interrupt = uarths->ip.rxwm; - uint32_t v_tx_interrupt = uarths->ip.txwm; - return (v_rx_interrupt << 1) | v_tx_interrupt; -} - -int uarths_irq_callback(void *ctx) -{ - uarths_instance_t *uart_context = (uarths_instance_t *)ctx; - - if(uart_context->callback) - uart_context->callback(uart_context->ctx); - return 0; -} - -void uarths_set_interrupt_cnt(uarths_interrupt_mode_t interrupt_mode, uint8_t cnt) -{ - switch(interrupt_mode) - { - case UARTHS_SEND: - uarths->txctrl.txcnt = cnt; - break; - case UARTHS_RECEIVE: - uarths->rxctrl.rxcnt = cnt; - break; - case UARTHS_SEND_RECEIVE: - default: - uarths->txctrl.txcnt = cnt; - uarths->rxctrl.rxcnt = cnt; - break; - } -} - -void uarths_set_irq(uarths_interrupt_mode_t interrupt_mode, plic_irq_callback_t uarths_callback, void *ctx, uint32_t priority) -{ - g_uarths_instance.callback = uarths_callback; - g_uarths_instance.ctx = ctx; - - switch(interrupt_mode) - { - case UARTHS_SEND: - uarths->ie.txwm = 1; - uarths->ie.rxwm = 0; - break; - case UARTHS_RECEIVE: - uarths->ie.txwm = 0; - uarths->ie.rxwm = 1; - break; - default: - uarths->ie.txwm = 1; - uarths->ie.rxwm = 1; - break; - } - g_uarths_instance.uarths_interrupt_mode = interrupt_mode; - - plic_set_priority(IRQN_UARTHS_INTERRUPT, priority); - plic_irq_register(IRQN_UARTHS_INTERRUPT, uarths_irq_callback, &g_uarths_instance); - plic_irq_enable(IRQN_UARTHS_INTERRUPT); -} - -static inline int uarths_putc(char c) -{ - while (uarths->txdata.full) - continue; - uarths->txdata.data = (uint8_t)c; - - return 0; -} - -size_t uarths_receive_data(uint8_t *buf, size_t buf_len) -{ - size_t i; - for(i = 0; i < buf_len; i++) - { - uarths_rxdata_t recv = uarths->rxdata; - if(recv.empty) - break; - else - buf[i] = (recv.data & 0xFF); - } - return i; -} - -size_t uarths_send_data(const uint8_t *buf, size_t buf_len) -{ - size_t write = 0; - while (write < buf_len) - { - uarths_putc(*buf++); - write++; - } - return write; -} - -int uarths_getc(void) -{ - /* while not empty */ - uarths_rxdata_t recv = uarths->rxdata; - - if (recv.empty) - return EOF; - else - return recv.data; -} - -int uarths_putchar(char c) -{ - return uarths_putc(c); -} - -int uarths_puts(const char *s) -{ - while (*s) - if (uarths_putc(*s++) != 0) - return -1; - return 0; -} - -void uarths_init(void) -{ - uint32_t freq = sysctl_clock_get_freq(SYSCTL_CLOCK_CPU); - uint16_t div = freq / 115200 - 1; - - /* Set UART registers */ - uarths->div.div = div; - uarths->txctrl.txen = 1; - uarths->rxctrl.rxen = 1; - uarths->txctrl.txcnt = 0; - uarths->rxctrl.rxcnt = 0; - uarths->ip.txwm = 1; - uarths->ip.rxwm = 1; - uarths->ie.txwm = 0; - uarths->ie.rxwm = 1; -} - -void uarths_config(uint32_t baud_rate, uarths_stopbit_t stopbit) -{ - uint32_t freq = sysctl_clock_get_freq(SYSCTL_CLOCK_CPU); - uint16_t div = freq / baud_rate - 1; - uarths->div.div = div; - uarths->txctrl.nstop = stopbit; -} - diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/utils.c b/cores/arduino/kendryte-standalone-sdk/lib/drivers/utils.c deleted file mode 100644 index d21a3b3..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/utils.c +++ /dev/null @@ -1,44 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include -#include "encoding.h" -#include "utils.h" - -void set_bit(volatile uint32_t *bits, uint32_t mask, uint32_t value) -{ - uint32_t org = (*bits) & ~mask; - *bits = org | (value & mask); -} - -void set_bit_offset(volatile uint32_t *bits, uint32_t mask, size_t offset, uint32_t value) -{ - set_bit(bits, mask << offset, value << offset); -} - -void set_gpio_bit(volatile uint32_t *bits, size_t offset, uint32_t value) -{ - set_bit_offset(bits, 1, offset, value); -} - -uint32_t get_bit(volatile uint32_t *bits, uint32_t mask, size_t offset) -{ - return ((*bits) & (mask << offset)) >> offset; -} - -uint32_t get_gpio_bit(volatile uint32_t *bits, size_t offset) -{ - return get_bit(bits, 1, offset); -} - diff --git a/cores/arduino/kendryte-standalone-sdk/lib/drivers/wdt.c b/cores/arduino/kendryte-standalone-sdk/lib/drivers/wdt.c deleted file mode 100644 index 74d0224..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/drivers/wdt.c +++ /dev/null @@ -1,115 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "wdt.h" -#include "platform.h" -#include "stddef.h" -#include "utils.h" -#include "sysctl.h" -#include "plic.h" -#include "math.h" - -volatile wdt_t *const wdt[2] = -{ - (volatile wdt_t *)WDT0_BASE_ADDR, - (volatile wdt_t *)WDT1_BASE_ADDR -}; - -static void wdt_enable(wdt_device_number_t id) -{ - wdt[id]->crr = WDT_CRR_MASK; - wdt[id]->cr |= WDT_CR_ENABLE; -} - -static void wdt_disable(wdt_device_number_t id) -{ - wdt[id]->crr = WDT_CRR_MASK; - wdt[id]->cr &= (~WDT_CR_ENABLE); -} - -static void wdt_set_timeout(wdt_device_number_t id, uint8_t timeout) -{ - wdt[id]->torr = WDT_TORR_TOP(timeout); -} - -static void wdt_response_mode(wdt_device_number_t id, uint8_t mode) -{ - wdt[id]->cr &= (~WDT_CR_RMOD_MASK); - wdt[id]->cr |= mode; -} - -static uint64_t wdt_get_pclk(wdt_device_number_t id) -{ - return id ? sysctl_clock_get_freq(SYSCTL_CLOCK_WDT1) : sysctl_clock_get_freq(SYSCTL_CLOCK_WDT0); -} - -static uint8_t wdt_get_top(wdt_device_number_t id, uint64_t timeout_ms) -{ - uint64_t wdt_clk = wdt_get_pclk(id); - uint64_t ret = (timeout_ms * wdt_clk / 1000) >> 16; - if (ret) - ret = (uint32_t)log2(ret); - if (ret > 0xf) - ret = 0xf; - return (uint8_t)ret; -} - -void wdt_feed(wdt_device_number_t id) -{ - wdt[id]->crr = WDT_CRR_MASK; -} - -void wdt_clear_interrupt(wdt_device_number_t id) -{ - wdt[id]->eoi = wdt[id]->eoi; -} - -void wdt_start(wdt_device_number_t id, uint64_t time_out_ms, plic_irq_callback_t on_irq) -{ - sysctl_reset(id ? SYSCTL_RESET_WDT1 : SYSCTL_RESET_WDT0); - sysctl_clock_set_threshold(id ? SYSCTL_THRESHOLD_WDT1 : SYSCTL_THRESHOLD_WDT0, 0); - sysctl_clock_enable(id ? SYSCTL_CLOCK_WDT1 : SYSCTL_CLOCK_WDT0); - - plic_set_priority(id ? IRQN_WDT1_INTERRUPT : IRQN_WDT0_INTERRUPT, 1); - plic_irq_enable(id ? IRQN_WDT1_INTERRUPT : IRQN_WDT0_INTERRUPT); - plic_irq_register(id ? IRQN_WDT1_INTERRUPT : IRQN_WDT0_INTERRUPT, on_irq, NULL); - - wdt_response_mode(id, WDT_CR_RMOD_INTERRUPT); - uint8_t m_top = wdt_get_top(id, time_out_ms); - wdt_set_timeout(id, m_top); - wdt_enable(id); -} - -uint32_t wdt_init(wdt_device_number_t id, uint64_t time_out_ms, plic_irq_callback_t on_irq, void *ctx) -{ - sysctl_reset(id ? SYSCTL_RESET_WDT1 : SYSCTL_RESET_WDT0); - sysctl_clock_set_threshold(id ? SYSCTL_THRESHOLD_WDT1 : SYSCTL_THRESHOLD_WDT0, 0); - sysctl_clock_enable(id ? SYSCTL_CLOCK_WDT1 : SYSCTL_CLOCK_WDT0); - - plic_set_priority(id ? IRQN_WDT1_INTERRUPT : IRQN_WDT0_INTERRUPT, 1); - plic_irq_enable(id ? IRQN_WDT1_INTERRUPT : IRQN_WDT0_INTERRUPT); - plic_irq_register(id ? IRQN_WDT1_INTERRUPT : IRQN_WDT0_INTERRUPT, on_irq, ctx); - - wdt_response_mode(id, WDT_CR_RMOD_INTERRUPT); - uint8_t m_top = wdt_get_top(id, time_out_ms); - wdt_set_timeout(id, m_top); - wdt_enable(id); - return (1UL << (m_top + 16 + 1)) * 1000UL / wdt_get_pclk(id); -} - -void wdt_stop(wdt_device_number_t id) -{ - wdt_disable(id); -} - diff --git a/cores/arduino/kendryte-standalone-sdk/lib/freertos/conf/FreeRTOSConfig.h b/cores/arduino/kendryte-standalone-sdk/lib/freertos/conf/FreeRTOSConfig.h deleted file mode 100644 index bd0f11e..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/freertos/conf/FreeRTOSConfig.h +++ /dev/null @@ -1,142 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * 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. - */ -/* -* 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 FREERTOS_CONFIG_H -#define FREERTOS_CONFIG_H -/*----------------------------------------------------------- - * Application specific definitions. - * - * These definitions should be adjusted for your particular hardware and - * application requirements. - * - * THESE PARAMETERS ARE DESCRIBED WITHIN THE 'CONFIGURATION' SECTION OF THE - * FreeRTOS API DOCUMENTATION AVAILABLE ON THE FreeRTOS.org WEB SITE. - * - * See http://www.freertos.org/a00110.html. - *----------------------------------------------------------*/ - -#include - -/* clock */ -#define configCPU_CLOCK_HZ uxPortGetCPUClock() -#define configTICK_CLOCK_HZ ( configCPU_CLOCK_HZ / 50 ) -#define configTICK_RATE_HZ ( ( TickType_t ) 100 ) - -/* multithreading */ -#define configUSE_NEWLIB_REENTRANT 1 - -#define configUSE_PREEMPTION 1 -#define configUSE_PORT_OPTIMISED_TASK_SELECTION 0 -#define configMAX_PRIORITIES ( 5 ) -#define configMAX_TASK_NAME_LEN ( 16 ) -#define configUSE_TRACE_FACILITY 0 -#define configUSE_16_BIT_TICKS 0 -#define configIDLE_SHOULD_YIELD 0 -#define configQUEUE_REGISTRY_SIZE 8 - -/* TLS */ -enum -{ - PTHREAD_TLS_INDEX = 0 -}; - -#define configNUM_THREAD_LOCAL_STORAGE_POINTERS 1 - -/* mutex */ -#define configUSE_MUTEXES 1 -#define configUSE_RECURSIVE_MUTEXES 1 - -/* hooks */ -#define configUSE_MALLOC_FAILED_HOOK 0 -#define configUSE_IDLE_HOOK 1 -#define configUSE_TICK_HOOK 0 -#define configUSE_DAEMON_TASK_STARTUP_HOOK 0 - -/* memory */ -#define configMINIMAL_STACK_SIZE ( ( unsigned short ) 2048 ) -#define configTOTAL_HEAP_SIZE ( ( size_t ) ( 1024 * 512 ) ) -#define configSUPPORT_STATIC_ALLOCATION 1 -#define configSUPPORT_DYNAMIC_ALLOCATION 1 - -#define configUSE_APPLICATION_TASK_TAG 1 -#define configUSE_COUNTING_SEMAPHORES 1 -#define configUSE_TICKLESS_IDLE 1 -#define configGENERATE_RUN_TIME_STATS 0 -#define configUSE_STATS_FORMATTING_FUNCTIONS 1 - -/* Co-routine definitions. */ -#define configUSE_CO_ROUTINES 0 -#define configMAX_CO_ROUTINE_PRIORITIES ( 2 ) - -/* Software timer definitions. */ -#define configUSE_TIMERS 0 -#define configTIMER_TASK_PRIORITY ( 2 ) -#define configTIMER_QUEUE_LENGTH 2 -#define configTIMER_TASK_STACK_DEPTH ( configMINIMAL_STACK_SIZE ) - -/* Set the following definitions to 1 to include the API function, or zero to exclude the API function. */ -#define INCLUDE_vTaskPrioritySet 1 -#define INCLUDE_uxTaskPriorityGet 1 -#define INCLUDE_vTaskDelete 1 -#define INCLUDE_vTaskCleanUpResources 1 -#define INCLUDE_vTaskSuspend 1 -#define INCLUDE_vTaskDelayUntil 1 -#define INCLUDE_vTaskDelay 1 -#define INCLUDE_eTaskGetState 1 -#define INCLUDE_xTaskAbortDelay 1 - -#define INCLUDE_xSemaphoreGetMutexHolder 1 - -/* Diagnostics */ -#define configCHECK_FOR_STACK_OVERFLOW 1 - -#ifdef configASSERT -#undef configASSERT -#endif -/* configASSERT behaviour */ -extern void vPortFatal(const char* file, int line, const char* message); -/* Normal assert() semantics without relying on the provision of an assert.h header file. */ -#define configASSERT( x ) if( ( x ) == 0 ) { \ - vPortFatal(__FILE__, __LINE__, #x); \ -} - -#endif /* FREERTOS_CONFIG_H */ diff --git a/cores/arduino/kendryte-standalone-sdk/lib/freertos/core_sync.c b/cores/arduino/kendryte-standalone-sdk/lib/freertos/core_sync.c deleted file mode 100644 index 969d292..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/freertos/core_sync.c +++ /dev/null @@ -1,100 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include -#include -#include -#include -#include -#include "FreeRTOS.h" -#include "task.h" - -volatile UBaseType_t g_core_pending_switch[portNUM_PROCESSORS] = { 0 }; -static volatile UBaseType_t s_core_sync_events[portNUM_PROCESSORS] = { 0 }; -static volatile TaskHandle_t s_pending_to_add_tasks[portNUM_PROCESSORS] = { 0 }; -static volatile UBaseType_t s_core_sync_in_progress[portNUM_PROCESSORS] = { 0 }; - -uintptr_t handle_irq_m_soft(uintptr_t cause, uintptr_t epc, uintptr_t regs[32], uintptr_t fregs[32]) -{ - uint64_t core_id = uxPortGetProcessorId(); - atomic_set(&s_core_sync_in_progress[core_id], 1); - switch (s_core_sync_events[core_id]) - { - case CORE_SYNC_ADD_TCB: - { - TaskHandle_t newTask = atomic_read(&s_pending_to_add_tasks[core_id]); - if (newTask) - { - vAddNewTaskToCurrentReadyList(newTask); - atomic_set(&s_pending_to_add_tasks[core_id], NULL); - } - } - break; - default: - break; - } - - core_sync_complete(core_id); - return epc; -} - -uintptr_t handle_irq_m_timer(uintptr_t cause, uintptr_t epc, uintptr_t regs[32], uintptr_t fregs[32]) -{ - prvSetNextTimerInterrupt(); - - /* Increment the RTOS tick. */ - if (xTaskIncrementTick() != pdFALSE) - { - core_sync_request_context_switch(uxPortGetProcessorId()); - } - - return epc; -} - -void core_sync_request_context_switch(uint64_t core_id) -{ - atomic_set(&g_core_pending_switch[core_id], 1); - clint_ipi_send(core_id); -} - -void core_sync_complete(uint64_t core_id) -{ - if (atomic_read(&g_core_pending_switch[core_id]) == 0) - clint_ipi_clear(core_id); - atomic_set(&s_core_sync_events[core_id], CORE_SYNC_NONE); - atomic_set(&s_core_sync_in_progress[core_id], 0); -} - -void core_sync_complete_context_switch(uint64_t core_id) -{ - if (atomic_read(&s_core_sync_events[core_id]) == CORE_SYNC_NONE) - clint_ipi_clear(core_id); - atomic_set(&g_core_pending_switch[core_id], 0); -} - -int core_sync_is_in_progress(uint64_t core_id) -{ - return !!atomic_read(&s_core_sync_in_progress[core_id]); -} - -void vPortAddNewTaskToReadyListAsync(UBaseType_t uxPsrId, void* pxNewTaskHandle) -{ - // Wait for last adding tcb complete - while (atomic_read(&s_pending_to_add_tasks[uxPsrId])); - atomic_set(&s_pending_to_add_tasks[uxPsrId], pxNewTaskHandle); - - while (atomic_cas(&s_core_sync_events[uxPsrId], CORE_SYNC_NONE, CORE_SYNC_ADD_TCB) != CORE_SYNC_NONE) - ; - clint_ipi_send(uxPsrId); -} diff --git a/cores/arduino/kendryte-standalone-sdk/lib/freertos/croutine.c b/cores/arduino/kendryte-standalone-sdk/lib/freertos/croutine.c deleted file mode 100644 index 955d28e..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/freertos/croutine.c +++ /dev/null @@ -1,367 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * 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. - */ -/* - * 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/cores/arduino/kendryte-standalone-sdk/lib/freertos/event_groups.c b/cores/arduino/kendryte-standalone-sdk/lib/freertos/event_groups.c deleted file mode 100644 index d8c22c3..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/freertos/event_groups.c +++ /dev/null @@ -1,752 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * 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. - */ -/* - * 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/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/FreeRTOS.h b/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/FreeRTOS.h deleted file mode 100644 index 049e972..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/FreeRTOS.h +++ /dev/null @@ -1,1183 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * 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. - */ -/* - * 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 - #define INCLUDE_uxTaskGetStackHighWaterMark 1 -#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/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/StackMacros.h b/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/StackMacros.h deleted file mode 100644 index 187e2c9..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/StackMacros.h +++ /dev/null @@ -1,147 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * 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. - */ -/* - * 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/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/core_sync.h b/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/core_sync.h deleted file mode 100644 index 4a38ece..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/core_sync.h +++ /dev/null @@ -1,43 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * 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. - */ -// -// Core Synchronization - -#ifndef CORE_SYNC_H -#define CORE_SYNC_H - -#include "FreeRTOS.h" - -#ifdef __cplusplus -extern "C" -{ -#endif - -typedef enum -{ - CORE_SYNC_NONE, - CORE_SYNC_ADD_TCB -} core_sync_event_t; - -void core_sync_request_context_switch(uint64_t core_id); -void core_sync_complete_context_switch(uint64_t core_id); -void core_sync_complete(uint64_t core_id); -int core_sync_is_in_progress(uint64_t core_id); - -#ifdef __cplusplus -} -#endif - -#endif /* CORE_SYNC_H */ diff --git a/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/croutine.h b/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/croutine.h deleted file mode 100644 index 47a2562..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/croutine.h +++ /dev/null @@ -1,734 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * 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. - */ -/* - * 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/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/event_groups.h b/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/event_groups.h deleted file mode 100644 index 4dc1bfd..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/event_groups.h +++ /dev/null @@ -1,770 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * 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. - */ -/* - * 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/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/list.h b/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/list.h deleted file mode 100644 index 6bcf698..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/list.h +++ /dev/null @@ -1,425 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * 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. - */ -/* - * 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/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/message_buffer.h b/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/message_buffer.h deleted file mode 100644 index 62f9778..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/message_buffer.h +++ /dev/null @@ -1,793 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * 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. - */ -/* - * 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/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/mpu_prototypes.h b/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/mpu_prototypes.h deleted file mode 100644 index b66f4c3..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/mpu_prototypes.h +++ /dev/null @@ -1,169 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * 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. - */ -/* - * 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/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/mpu_wrappers.h b/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/mpu_wrappers.h deleted file mode 100644 index 33a15de..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/mpu_wrappers.h +++ /dev/null @@ -1,195 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * 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. - */ -/* - * 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/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/portable.h b/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/portable.h deleted file mode 100644 index c345a16..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/portable.h +++ /dev/null @@ -1,178 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * 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. - */ -/* - * 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. */ - -/* 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/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/projdefs.h b/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/projdefs.h deleted file mode 100644 index a0dadf0..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/projdefs.h +++ /dev/null @@ -1,138 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * 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. - */ -/* - * 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/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/queue.h b/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/queue.h deleted file mode 100644 index cfd7917..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/queue.h +++ /dev/null @@ -1,1667 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * 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. - */ -/* - * 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/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/semphr.h b/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/semphr.h deleted file mode 100644 index a3e1098..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/semphr.h +++ /dev/null @@ -1,1154 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * 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. - */ -/* - * 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/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/stack_macros.h b/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/stack_macros.h deleted file mode 100644 index 97d122e..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/stack_macros.h +++ /dev/null @@ -1,143 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * 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. - */ -/* - * 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[uxPsrId]->pxTopOfStack <= pxCurrentTCB[uxPsrId]->pxStack ) \ - { \ - vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB[uxPsrId], pxCurrentTCB[uxPsrId]->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/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/stdint.readme b/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/stdint.readme deleted file mode 100644 index 4414c29..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/freertos/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/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/stream_buffer.h b/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/stream_buffer.h deleted file mode 100644 index 7bd8f47..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/stream_buffer.h +++ /dev/null @@ -1,866 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * 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. - */ -/* - * 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/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/task.h b/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/task.h deleted file mode 100644 index 29553ee..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/task.h +++ /dev/null @@ -1,2363 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * 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. - */ -/* - * 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 ) - -UBaseType_t uxTaskGetProcessorId(void); - - -/*----------------------------------------------------------- - * 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; - - BaseType_t xTaskCreateAtProcessor(UBaseType_t uxProcessor, - 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() 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; - -void vAddNewTaskToCurrentReadyList(TaskHandle_t pxNewTCB) PRIVILEGED_FUNCTION; - -#ifdef __cplusplus -} -#endif -#endif /* INC_TASK_H */ - - - diff --git a/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/timers.h b/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/timers.h deleted file mode 100644 index 28fbc09..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/freertos/include/timers.h +++ /dev/null @@ -1,1291 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * 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. - */ -/* - * 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/cores/arduino/kendryte-standalone-sdk/lib/freertos/list.c b/cores/arduino/kendryte-standalone-sdk/lib/freertos/list.c deleted file mode 100644 index 4933f46..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/freertos/list.c +++ /dev/null @@ -1,212 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * 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. - */ -/* - * 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/cores/arduino/kendryte-standalone-sdk/lib/freertos/locks.c b/cores/arduino/kendryte-standalone-sdk/lib/freertos/locks.c deleted file mode 100644 index d33e4de..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/freertos/locks.c +++ /dev/null @@ -1,48 +0,0 @@ -#include -#include -#include "FreeRTOS.h" -#include "semphr.h" -#include "portmacro.h" -#include "task.h" - -typedef long _lock_t; - -void _lock_init(_lock_t *lock) -{ -} - -void _lock_init_recursive(_lock_t *lock) -{ -} - -void _lock_close(_lock_t *lock) -{ -} - -void _lock_close_recursive(_lock_t *lock) __attribute__((alias("_lock_close"))); - -void _lock_acquire(_lock_t *lock) -{ -} - -void _lock_acquire_recursive(_lock_t *lock) -{ -} - -int _lock_try_acquire(_lock_t *lock) -{ - return 1; -} - -int _lock_try_acquire_recursive(_lock_t *lock) -{ - return 1; -} - -void _lock_release(_lock_t *lock) -{ -} - -void _lock_release_recursive(_lock_t *lock) -{ -} diff --git a/cores/arduino/kendryte-standalone-sdk/lib/freertos/os_entry.c b/cores/arduino/kendryte-standalone-sdk/lib/freertos/os_entry.c deleted file mode 100644 index 745133c..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/freertos/os_entry.c +++ /dev/null @@ -1,49 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "FreeRTOS.h" -#include "core_sync.h" -#include "task.h" -#include -#include -#include -#include -#include - -static StaticTask_t s_idle_task; -static StackType_t s_idle_task_stack[configMINIMAL_STACK_SIZE]; - -void vApplicationIdleHook(void) -{ -} - -void vApplicationGetIdleTaskMemory(StaticTask_t **ppxIdleTaskTCBBuffer, StackType_t **ppxIdleTaskStackBuffer, uint32_t *pulIdleTaskStackSize) -{ - /* Pass out a pointer to the StaticTask_t structure in which the Idle task's - state will be stored. */ - *ppxIdleTaskTCBBuffer = &s_idle_task; - - /* Pass out the array that will be used as the Idle task's stack. */ - *ppxIdleTaskStackBuffer = s_idle_task_stack; - - /* Pass out the size of the array pointed to by *ppxIdleTaskStackBuffer. - Note that, as the array is necessarily of type StackType_t, - configMINIMAL_STACK_SIZE is specified in words, not bytes. */ - *pulIdleTaskStackSize = configMINIMAL_STACK_SIZE; -} - -void vApplicationStackOverflowHook(TaskHandle_t xTask, char *pcTaskName) -{ - configASSERT(!"Stackoverflow !"); -} diff --git a/cores/arduino/kendryte-standalone-sdk/lib/freertos/portable/heap_4.c b/cores/arduino/kendryte-standalone-sdk/lib/freertos/portable/heap_4.c deleted file mode 100644 index 9494ad2..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/freertos/portable/heap_4.c +++ /dev/null @@ -1,451 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * 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. - */ -/* -* 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 "atomic.h" -#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; - - taskENTER_CRITICAL(); - { - /* 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)taskEXIT_CRITICAL(); - -#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; - - taskENTER_CRITICAL(); - { - /* Add this block to the list of free blocks. */ - xFreeBytesRemaining += pxLink->xBlockSize; - traceFREE(pv, pxLink->xBlockSize); - prvInsertBlockIntoFreeList(((BlockLink_t *)pxLink)); - } - (void)taskEXIT_CRITICAL(); - } - 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/cores/arduino/kendryte-standalone-sdk/lib/freertos/portable/port.c b/cores/arduino/kendryte-standalone-sdk/lib/freertos/portable/port.c deleted file mode 100644 index bb5fb03..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/freertos/portable/port.c +++ /dev/null @@ -1,208 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * 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. - */ -/* -* 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 RISC-V port. - *----------------------------------------------------------*/ - -/* Scheduler includes. */ -#include -#include -#include -#include -#include -#include -#include -#include -#include "core_sync.h" -#include "FreeRTOS.h" -#include "portmacro.h" -#include "task.h" - -/* A variable is used to keep track of the critical section nesting. This -variable has to be stored as part of the task context and must be initialised to -a non zero value to ensure interrupts don't inadvertently become unmasked before -the scheduler starts. As it is stored as part of the task context it will -automatically be set to 0 when the first task is started. */ -static UBaseType_t uxCriticalNesting[portNUM_PROCESSORS] = {[0 ... portNUM_PROCESSORS - 1] = 0xaaaaaaaa}; -PRIVILEGED_DATA static corelock_t xCoreLock = CORELOCK_INIT; - -/* Contains context when starting scheduler, save all 31 registers */ -#ifdef __gracefulExit -#error Not ported -BaseType_t xStartContext[31] = {0}; -#endif - -/* - * Handler for timer interrupt - */ -void vPortSysTickHandler(void); - -/* - * Setup the timer to generate the tick interrupts. - */ -void vPortSetupTimer(void); - -/* - * Used to catch tasks that attempt to return from their implementing function. - */ -static void prvTaskExitError(void); - -UBaseType_t uxPortGetProcessorId() -{ - return (UBaseType_t)read_csr(mhartid); -} - -/*-----------------------------------------------------------*/ - -/* Sets and enable the timer interrupt */ -void vPortSetupTimer(void) -{ - UBaseType_t uxPsrId = uxPortGetProcessorId(); - clint->mtimecmp[uxPsrId] = clint->mtime + (configTICK_CLOCK_HZ / configTICK_RATE_HZ); - /* Enable timer and soft interupt */ - __asm volatile("csrs mie,%0" ::"r"(0x88)); -} - -/*-----------------------------------------------------------*/ - -/* Sets the next timer interrupt - * Reads previous timer compare register, and adds tickrate */ -void prvSetNextTimerInterrupt(void) -{ - UBaseType_t uxPsrId = uxPortGetProcessorId(); - clint->mtimecmp[uxPsrId] += (configTICK_CLOCK_HZ / configTICK_RATE_HZ); -} -/*-----------------------------------------------------------*/ - -void prvTaskExitError(void) -{ - /* 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. */ - UBaseType_t uxPsrId = uxPortGetProcessorId(); - configASSERT(uxCriticalNesting[uxPsrId] == ~0UL); - portDISABLE_INTERRUPTS(); - for (;;) - ; -} -/*-----------------------------------------------------------*/ - -/* Clear current interrupt mask and set given mask */ -void vPortClearInterruptMask(int mask) -{ - __asm volatile("csrw mie, %0" ::"r"(mask)); -} -/*-----------------------------------------------------------*/ - -/* Set interrupt mask and return current interrupt enable register */ -int vPortSetInterruptMask(void) -{ - int ret; - __asm volatile("csrr %0,mie" - : "=r"(ret)); - __asm volatile("csrc mie,%0" ::"i"(7)); - return ret; -} -/*-----------------------------------------------------------*/ - -/* - * 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 -= 64; - memset(pxTopOfStack, 0, sizeof(StackType_t) * 64); - - pxTopOfStack[0] = (portSTACK_TYPE)prvTaskExitError; /* Register ra */ - pxTopOfStack[1] = (portSTACK_TYPE)pxTopOfStack; - pxTopOfStack[8] = (portSTACK_TYPE)pvParameters; /* Register a0 */ - pxTopOfStack[30] = 0; /* Register fsr */ - pxTopOfStack[31] = (portSTACK_TYPE)pxCode; /* Register mepc */ - - return pxTopOfStack; -} -/*-----------------------------------------------------------*/ -void vPortSysTickHandler(void) -{ - core_sync_complete_context_switch(uxPortGetProcessorId()); - vTaskSwitchContext(); -} -/*-----------------------------------------------------------*/ - -void vPortEnterCritical(void) -{ - if (!core_sync_is_in_progress(uxPortGetProcessorId())) - vTaskEnterCritical(); - corelock_lock(&xCoreLock); -} - -void vPortExitCritical(void) -{ - corelock_unlock(&xCoreLock); - if (!core_sync_is_in_progress(uxPortGetProcessorId())) - vTaskExitCritical(); -} - -void vPortYield() -{ - core_sync_request_context_switch(uxPortGetProcessorId()); -} - -void vPortFatal(const char* file, int line, const char* message) -{ - portDISABLE_INTERRUPTS(); - corelock_lock(&xCoreLock); - LOGE("FreeRTOS", "(%s:%d) %s", file, line, message); - exit(-1); - while (1) - ; -} - -UBaseType_t uxPortGetCPUClock() -{ - return (UBaseType_t)sysctl_cpu_get_freq(); -} diff --git a/cores/arduino/kendryte-standalone-sdk/lib/freertos/portable/portasm.S b/cores/arduino/kendryte-standalone-sdk/lib/freertos/portable/portasm.S deleted file mode 100644 index acd4a5f..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/freertos/portable/portasm.S +++ /dev/null @@ -1,287 +0,0 @@ -# Copyright 2018 Canaan Inc. -# -# 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. -# -# FreeRTOS V9.0.0 - Copyright (C) 2016 Real Time Engineers Ltd. -# All rights reserved - -# VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION. - -# This file is part of the FreeRTOS distribution and was contributed -# to the project by Technolution B.V. (www.technolution.nl, -# freertos-riscv@technolution.eu) under the terms of the FreeRTOS -# contributors license. - -# FreeRTOS is free software; you can redistribute it and/or modify it under -# the terms of the GNU General Public License (version 2) as published by the -# Free Software Foundation >>>> AND MODIFIED BY <<<< the FreeRTOS exception. - -# *************************************************************************** -# >>! NOTE: The modification to the GPL is included to allow you to !<< -# >>! distribute a combined work that includes FreeRTOS without being !<< -# >>! obliged to provide the source code for proprietary components !<< -# >>! outside of the FreeRTOS kernel. !<< -# *************************************************************************** - -# FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY -# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. Full license text is available on the following -# link: http://www.freertos.org/a00114.html - -# *************************************************************************** -# * * -# * FreeRTOS provides completely free yet professionally developed, * -# * robust, strictly quality controlled, supported, and cross * -# * platform software that is more than just the market leader, it * -# * is the industry's de facto standard. * -# * * -# * Help yourself get started quickly while simultaneously helping * -# * to support the FreeRTOS project by purchasing a FreeRTOS * -# * tutorial book, reference manual, or both: * -# * http://www.FreeRTOS.org/Documentation * -# * * -# *************************************************************************** - -# http://www.FreeRTOS.org/FAQHelp.html - Having a problem? Start by reading -# the FAQ page "My application does not run, what could be wrong?". Have you -# defined configASSERT()? - -# http://www.FreeRTOS.org/support - In return for receiving this top quality -# embedded software for free we request you assist our global community by -# participating in the support forum. - -# http://www.FreeRTOS.org/training - Investing in training allows your team to -# be as productive as possible as early as possible. Now you can receive -# FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers -# Ltd, and the world's leading authority on the world's leading RTOS. - -# http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products, -# including FreeRTOS+Trace - an indispensable productivity tool, a DOS -# compatible FAT file system, and our tiny thread aware UDP/IP stack. - -# http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate. -# Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS. - -# http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High -# Integrity Systems ltd. to sell under the OpenRTOS brand. Low cost OpenRTOS -# licenses offer ticketed support, indemnification and commercial middleware. - -# http://www.SafeRTOS.com - High Integrity Systems also provide a safety -# engineered and independently SIL3 certified version for use in safety and -# mission critical applications that require provable dependability. - -# 1 tab == 4 spaces! -# - -# include "encoding.h" - -# define REGBYTES 8 - -.global xPortSysTickInt -.global xPortStartScheduler -.global vPortYield -.global vTaskIncrementTick -.global vPortEndScheduler -.global xExitStack -.global uxPortGetProcessorId - -# /* Macro for saving task context */ -.macro portSAVE_CONTEXT - .global pxCurrentTCB - # /* make room in stack */ - addi sp, sp, -REGBYTES * 64 - - # /* Save Context */ - sd ra, 0 * REGBYTES(sp) - sd sp, 1 * REGBYTES(sp) - sd tp, 2 * REGBYTES(sp) - sd t0, 3 * REGBYTES(sp) - sd t1, 4 * REGBYTES(sp) - sd t2, 5 * REGBYTES(sp) - sd s0, 6 * REGBYTES(sp) - sd s1, 7 * REGBYTES(sp) - sd a0, 8 * REGBYTES(sp) - sd a1, 9 * REGBYTES(sp) - sd a2, 10 * REGBYTES(sp) - sd a3, 11 * REGBYTES(sp) - sd a4, 12 * REGBYTES(sp) - sd a5, 13 * REGBYTES(sp) - sd a6, 14 * REGBYTES(sp) - sd a7, 15 * REGBYTES(sp) - sd s2, 16 * REGBYTES(sp) - sd s3, 17 * REGBYTES(sp) - sd s4, 18 * REGBYTES(sp) - sd s5, 19 * REGBYTES(sp) - sd s6, 20 * REGBYTES(sp) - sd s7, 21 * REGBYTES(sp) - sd s8, 22 * REGBYTES(sp) - sd s9, 23 * REGBYTES(sp) - sd s10, 24 * REGBYTES(sp) - sd s11, 25 * REGBYTES(sp) - sd t3, 26 * REGBYTES(sp) - sd t4, 27 * REGBYTES(sp) - sd t5, 28 * REGBYTES(sp) - sd t6, 29 * REGBYTES(sp) - - frsr t0 - sd t0, 30 * REGBYTES(sp) - - csrr t0, mepc - sd t0, 31 * REGBYTES(sp) - - fsd f0, ( 0 + 32) * REGBYTES(sp) - fsd f1, ( 1 + 32) * REGBYTES(sp) - fsd f2, ( 2 + 32) * REGBYTES(sp) - fsd f3, ( 3 + 32) * REGBYTES(sp) - fsd f4, ( 4 + 32) * REGBYTES(sp) - fsd f5, ( 5 + 32) * REGBYTES(sp) - fsd f6, ( 6 + 32) * REGBYTES(sp) - fsd f7, ( 7 + 32) * REGBYTES(sp) - fsd f8, ( 8 + 32) * REGBYTES(sp) - fsd f9, ( 9 + 32) * REGBYTES(sp) - fsd f10, (10 + 32) * REGBYTES(sp) - fsd f11, (11 + 32) * REGBYTES(sp) - fsd f12, (12 + 32) * REGBYTES(sp) - fsd f13, (13 + 32) * REGBYTES(sp) - fsd f14, (14 + 32) * REGBYTES(sp) - fsd f15, (15 + 32) * REGBYTES(sp) - fsd f16, (16 + 32) * REGBYTES(sp) - fsd f17, (17 + 32) * REGBYTES(sp) - fsd f18, (18 + 32) * REGBYTES(sp) - fsd f19, (19 + 32) * REGBYTES(sp) - fsd f20, (20 + 32) * REGBYTES(sp) - fsd f21, (21 + 32) * REGBYTES(sp) - fsd f22, (22 + 32) * REGBYTES(sp) - fsd f23, (23 + 32) * REGBYTES(sp) - fsd f24, (24 + 32) * REGBYTES(sp) - fsd f25, (25 + 32) * REGBYTES(sp) - fsd f26, (26 + 32) * REGBYTES(sp) - fsd f27, (27 + 32) * REGBYTES(sp) - fsd f28, (28 + 32) * REGBYTES(sp) - fsd f29, (29 + 32) * REGBYTES(sp) - fsd f30, (30 + 32) * REGBYTES(sp) - fsd f31, (31 + 32) * REGBYTES(sp) - - # /* Store current stackpointer in task control block (TCB) */ - la t0, pxCurrentTCB - csrr t1, mhartid - slli t1, t1, 3 - add t0, t0, t1 - - ld t0, 0x0(t0) - sd sp, 0x0(t0) - .endm - -# /* Macro for restoring task context */ -.macro portRESTORE_CONTEXT - .global pxCurrentTCB - # /* Load stack pointer from the current TCB */ - la t0, pxCurrentTCB - csrr t1, mhartid - slli t1, t1, 3 - add t0, t0, t1 - - ld sp, 0x0(t0) - ld sp, 0x0(sp) - - ld t0, 30 * REGBYTES(sp) - fssr t0 - - ld t0, 31 * REGBYTES(sp) - csrw mepc, t0 - - # /* Run in machine mode */ - li t0, MSTATUS_MPP | MSTATUS_MPIE - csrs mstatus, t0 - - # /* Restore registers */ - ld ra, 0 * REGBYTES(sp) - ld sp, 1 * REGBYTES(sp) - ld tp, 2 * REGBYTES(sp) - ld t0, 3 * REGBYTES(sp) - ld t1, 4 * REGBYTES(sp) - ld t2, 5 * REGBYTES(sp) - ld s0, 6 * REGBYTES(sp) - ld s1, 7 * REGBYTES(sp) - ld a0, 8 * REGBYTES(sp) - ld a1, 9 * REGBYTES(sp) - ld a2, 10 * REGBYTES(sp) - ld a3, 11 * REGBYTES(sp) - ld a4, 12 * REGBYTES(sp) - ld a5, 13 * REGBYTES(sp) - ld a6, 14 * REGBYTES(sp) - ld a7, 15 * REGBYTES(sp) - ld s2, 16 * REGBYTES(sp) - ld s3, 17 * REGBYTES(sp) - ld s4, 18 * REGBYTES(sp) - ld s5, 19 * REGBYTES(sp) - ld s6, 20 * REGBYTES(sp) - ld s7, 21 * REGBYTES(sp) - ld s8, 22 * REGBYTES(sp) - ld s9, 23 * REGBYTES(sp) - ld s10, 24 * REGBYTES(sp) - ld s11, 25 * REGBYTES(sp) - ld t3, 26 * REGBYTES(sp) - ld t4, 27 * REGBYTES(sp) - ld t5, 28 * REGBYTES(sp) - ld t6, 29 * REGBYTES(sp) - - fld f0, ( 0 + 32) * REGBYTES(sp) - fld f1, ( 1 + 32) * REGBYTES(sp) - fld f2, ( 2 + 32) * REGBYTES(sp) - fld f3, ( 3 + 32) * REGBYTES(sp) - fld f4, ( 4 + 32) * REGBYTES(sp) - fld f5, ( 5 + 32) * REGBYTES(sp) - fld f6, ( 6 + 32) * REGBYTES(sp) - fld f7, ( 7 + 32) * REGBYTES(sp) - fld f8, ( 8 + 32) * REGBYTES(sp) - fld f9, ( 9 + 32) * REGBYTES(sp) - fld f10, (10 + 32) * REGBYTES(sp) - fld f11, (11 + 32) * REGBYTES(sp) - fld f12, (12 + 32) * REGBYTES(sp) - fld f13, (13 + 32) * REGBYTES(sp) - fld f14, (14 + 32) * REGBYTES(sp) - fld f15, (15 + 32) * REGBYTES(sp) - fld f16, (16 + 32) * REGBYTES(sp) - fld f17, (17 + 32) * REGBYTES(sp) - fld f18, (18 + 32) * REGBYTES(sp) - fld f19, (19 + 32) * REGBYTES(sp) - fld f20, (20 + 32) * REGBYTES(sp) - fld f21, (21 + 32) * REGBYTES(sp) - fld f22, (22 + 32) * REGBYTES(sp) - fld f23, (23 + 32) * REGBYTES(sp) - fld f24, (24 + 32) * REGBYTES(sp) - fld f25, (25 + 32) * REGBYTES(sp) - fld f26, (26 + 32) * REGBYTES(sp) - fld f27, (27 + 32) * REGBYTES(sp) - fld f28, (28 + 32) * REGBYTES(sp) - fld f29, (29 + 32) * REGBYTES(sp) - fld f30, (30 + 32) * REGBYTES(sp) - fld f31, (31 + 32) * REGBYTES(sp) - - addi sp, sp, REGBYTES * 64 - mret - .endm - -xPortStartScheduler: - jal vPortSetupTimer - portRESTORE_CONTEXT - -vPortEndScheduler: - ret - -.section .text.systick, "ax", @progbits -xPortSysTickInt: - portSAVE_CONTEXT - call vPortSysTickHandler - portRESTORE_CONTEXT \ No newline at end of file diff --git a/cores/arduino/kendryte-standalone-sdk/lib/freertos/portable/portmacro.h b/cores/arduino/kendryte-standalone-sdk/lib/freertos/portable/portmacro.h deleted file mode 100644 index 2658770..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/freertos/portable/portmacro.h +++ /dev/null @@ -1,162 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * 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. - */ -/* - * 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. - *----------------------------------------------------------- - */ -#include -/* Multi-Core */ -#define portNUM_PROCESSORS 2 - -/* Type definitions. */ -#define portCHAR char -#define portFLOAT float -#define portDOUBLE double -#define portLONG long -#define portSHORT short -#define portBASE_TYPE long - -#define portSTACK_TYPE uintptr_t -#define portPOINTER_SIZE_TYPE uintptr_t - -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 -#endif -/*-----------------------------------------------------------*/ - -/* Architecture specifics. */ -#define portSTACK_GROWTH ( -1 ) -#define portTICK_PERIOD_MS ( ( TickType_t ) (1000 / configTICK_RATE_HZ) ) -#ifdef __riscv64 - #define portBYTE_ALIGNMENT 8 -#else - #define portBYTE_ALIGNMENT 4 -#endif -#define portCRITICAL_NESTING_IN_TCB 1 -/*-----------------------------------------------------------*/ - - -/* Scheduler utilities. */ -extern void vPortYield( void ); -#define portYIELD() vPortYield() - -extern void vPortYieldFromISR(void); -/*-----------------------------------------------------------*/ - -/* Architecture specific optimisations. */ -#ifndef configUSE_PORT_OPTIMISED_TASK_SELECTION -#define configUSE_PORT_OPTIMISED_TASK_SELECTION 1 -#endif - -#if configUSE_PORT_OPTIMISED_TASK_SELECTION == 1 - -/* 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 = ( 31 - __builtin_clz( ( uxReadyPriorities ) ) ) - -#endif /* configUSE_PORT_OPTIMISED_TASK_SELECTION */ - -/* Critical section management. */ -extern int vPortSetInterruptMask( void ); -extern void vPortClearInterruptMask( int ); -extern void vTaskEnterCritical( void ); -extern void vTaskExitCritical( void ); -extern UBaseType_t uxPortGetProcessorId(void); -void prvSetNextTimerInterrupt(); -void vPortAddNewTaskToReadyListAsync(UBaseType_t uxPsrId, void* pxNewTaskHandle); - -void vPortEnterCritical(void); -void vPortExitCritical(void); - -UBaseType_t uxPortGetCPUClock(); - -#define portGET_PROCESSOR_ID() uxPortGetProcessorId() - -#define portDISABLE_INTERRUPTS() __asm volatile ( "csrc mstatus,8" ) -#define portENABLE_INTERRUPTS() __asm volatile ( "csrs mstatus,8" ) -#define portENTER_CRITICAL() vPortEnterCritical() -#define portEXIT_CRITICAL() vPortExitCritical() -#define portSET_INTERRUPT_MASK_FROM_ISR() vPortSetInterruptMask() -#define portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedStatusValue ) vPortClearInterruptMask( uxSavedStatusValue ) -/*-----------------------------------------------------------*/ - -/* 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() __asm volatile ( " nop " ) - -#ifdef __cplusplus -} -#endif - -#endif /* PORTMACRO_H */ - diff --git a/cores/arduino/kendryte-standalone-sdk/lib/freertos/pthread.c b/cores/arduino/kendryte-standalone-sdk/lib/freertos/pthread.c deleted file mode 100644 index 3283138..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/freertos/pthread.c +++ /dev/null @@ -1,4 +0,0 @@ -int pthread_setcancelstate(int __state, int *__oldstate) -{ - return 0; -} \ No newline at end of file diff --git a/cores/arduino/kendryte-standalone-sdk/lib/freertos/queue.c b/cores/arduino/kendryte-standalone-sdk/lib/freertos/queue.c deleted file mode 100644 index 8642b8a..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/freertos/queue.c +++ /dev/null @@ -1,2923 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * 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. - */ -/* - * 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/cores/arduino/kendryte-standalone-sdk/lib/freertos/readme.txt b/cores/arduino/kendryte-standalone-sdk/lib/freertos/readme.txt deleted file mode 100644 index 58480c5..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/freertos/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/cores/arduino/kendryte-standalone-sdk/lib/freertos/stream_buffer.c b/cores/arduino/kendryte-standalone-sdk/lib/freertos/stream_buffer.c deleted file mode 100644 index 44b552a..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/freertos/stream_buffer.c +++ /dev/null @@ -1,1213 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * 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. - */ -/* - * 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/cores/arduino/kendryte-standalone-sdk/lib/freertos/tasks.c b/cores/arduino/kendryte-standalone-sdk/lib/freertos/tasks.c deleted file mode 100644 index c77ec82..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/freertos/tasks.c +++ /dev/null @@ -1,5149 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * 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. - */ -/* - * 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[uxPsrId] ) \ - { \ - uxTopReadyPriority[uxPsrId] = ( uxPriority ); \ - } \ - } /* taskRECORD_READY_PRIORITY */ - - /*-----------------------------------------------------------*/ - - #define taskSELECT_HIGHEST_PRIORITY_TASK() \ - { \ - UBaseType_t uxTopPriority = uxTopReadyPriority[uxPsrId]; \ - \ - /* Find the highest priority queue that contains ready tasks. */ \ - while( listLIST_IS_EMPTY( &( pxReadyTasksLists[uxPsrId][ 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[uxPsrId], &( pxReadyTasksLists[uxPsrId][ uxTopPriority ] ) ); \ - uxTopReadyPriority[uxPsrId] = 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[uxPsrId] ) ) ); \ - \ - pxTemp = pxDelayedTaskList[uxPsrId]; \ - pxDelayedTaskList[uxPsrId] = pxOverflowDelayedTaskList[uxPsrId]; \ - pxOverflowDelayedTaskList[uxPsrId] = pxTemp; \ - xNumOfOverflows[uxPsrId]++; \ - 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[uxPsrId][ ( 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[uxPsrId] : ( 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[portNUM_PROCESSORS] = { NULL }; - -/* Lists for ready and blocked tasks. --------------------*/ -PRIVILEGED_DATA static List_t pxReadyTasksLists[portNUM_PROCESSORS][ configMAX_PRIORITIES ];/*< Prioritised ready tasks. */ -PRIVILEGED_DATA static List_t xDelayedTaskList1[portNUM_PROCESSORS]; /*< Delayed tasks. */ -PRIVILEGED_DATA static List_t xDelayedTaskList2[portNUM_PROCESSORS]; /*< Delayed tasks (two lists are used - one for delays that have overflowed the current tick count. */ -PRIVILEGED_DATA static List_t * volatile pxDelayedTaskList[portNUM_PROCESSORS]; /*< Points to the delayed task list currently being used. */ -PRIVILEGED_DATA static List_t * volatile pxOverflowDelayedTaskList[portNUM_PROCESSORS]; /*< 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[portNUM_PROCESSORS]; /*< 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[portNUM_PROCESSORS]; /*< Tasks that have been deleted - but their memory not yet freed. */ - PRIVILEGED_DATA static volatile UBaseType_t uxDeletedTasksWaitingCleanUp[portNUM_PROCESSORS] = { (UBaseType_t)0U }; - -#endif - -#if ( INCLUDE_vTaskSuspend == 1 ) - - PRIVILEGED_DATA static List_t xSuspendedTaskList[portNUM_PROCESSORS]; /*< Tasks that are currently suspended. */ - -#endif - -/* Other file private variables. --------------------------------*/ -PRIVILEGED_DATA static volatile UBaseType_t uxCurrentNumberOfTasks[portNUM_PROCESSORS] = { ( UBaseType_t ) 0U }; -PRIVILEGED_DATA static volatile TickType_t xTickCount[portNUM_PROCESSORS] = { ( TickType_t ) configINITIAL_TICK_COUNT }; -PRIVILEGED_DATA static volatile UBaseType_t uxTopReadyPriority[portNUM_PROCESSORS] = { tskIDLE_PRIORITY }; -PRIVILEGED_DATA static volatile BaseType_t xSchedulerRunning[portNUM_PROCESSORS] = { pdFALSE }; -PRIVILEGED_DATA static volatile UBaseType_t uxPendedTicks[portNUM_PROCESSORS] = { ( UBaseType_t ) 0U }; -PRIVILEGED_DATA static volatile BaseType_t xYieldPending[portNUM_PROCESSORS] = { pdFALSE }; -PRIVILEGED_DATA static volatile BaseType_t xNumOfOverflows[portNUM_PROCESSORS] = { ( BaseType_t ) 0 }; -PRIVILEGED_DATA static UBaseType_t uxTaskNumber[portNUM_PROCESSORS] = { ( UBaseType_t ) 0U }; -PRIVILEGED_DATA static volatile TickType_t xNextTaskUnblockTime[portNUM_PROCESSORS] = { ( TickType_t ) 0U }; /* Initialised to portMAX_DELAY before the scheduler starts. */ -PRIVILEGED_DATA static TaskHandle_t xIdleTaskHandle[portNUM_PROCESSORS] = { (TaskHandle_t) 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[portNUM_PROCESSORS] = { ( UBaseType_t ) pdFALSE }; - -#if ( configGENERATE_RUN_TIME_STATS == 1 ) - - PRIVILEGED_DATA static uint32_t ulTaskSwitchedInTime[portNUM_PROCESSORS] = { 0UL }; /*< Holds the value of a timer/counter the last time a task was switched in. */ - PRIVILEGED_DATA static uint32_t ulTotalRunTime[portNUM_PROCESSORS] = { 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( UBaseType_t xProcessorId, 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 - -/*-----------------------------------------------------------*/ - - UBaseType_t uxTaskGetProcessorId(void) - { - return portGET_PROCESSOR_ID(); - } - -#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( uxPortGetProcessorId(), 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 xTaskCreateAtProcessor(UBaseType_t uxProcessor, - 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(uxProcessor, pxNewTCB ); - xReturn = pdPASS; - } - else - { - xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY; - } - - return xReturn; - } - - 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) - { - return xTaskCreateAtProcessor(uxPortGetProcessorId(), pxTaskCode, pcName, usStackDepth, pvParameters, uxPriority, pxCreatedTask); - } - -#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(); - } -} -/*-----------------------------------------------------------*/ - -void vAddNewTaskToCurrentReadyList(TaskHandle_t pxNewTaskHandle) -{ - UBaseType_t uxPsrId = uxPortGetProcessorId(); - TCB_t* pxNewTCB = (TCB_t*)pxNewTaskHandle; - /* Ensure interrupts don't access the task lists while the lists are being - updated. */ - taskENTER_CRITICAL(); - { - uxCurrentNumberOfTasks[uxPsrId]++; - if( pxCurrentTCB[uxPsrId] == NULL ) - { - /* There are no other tasks, or all the other tasks are in - the suspended state - make this the current task. */ - pxCurrentTCB[uxPsrId] = pxNewTCB; - - if( uxCurrentNumberOfTasks[uxPsrId] == ( 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[uxPsrId] == pdFALSE ) - { - if( pxCurrentTCB[uxPsrId]->uxPriority <= pxNewTCB->uxPriority ) - { - pxCurrentTCB[uxPsrId] = pxNewTCB; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - - uxTaskNumber[uxPsrId]++; - - #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[uxPsrId] != pdFALSE ) - { - /* If the created task is of a higher priority than the current task - then it should run now. */ - if( pxCurrentTCB[uxPsrId]->uxPriority < pxNewTCB->uxPriority ) - { - taskYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } -} - -static void prvAddNewTaskToReadyList( UBaseType_t uxPsrId, TCB_t *pxNewTCB ) -{ - UBaseType_t xMyPsrId = uxPortGetProcessorId(); - if (uxPsrId == xMyPsrId) - vAddNewTaskToCurrentReadyList(pxNewTCB); - else - { - taskENTER_CRITICAL(); - { - vPortAddNewTaskToReadyListAsync(uxPsrId, pxNewTCB); - } - taskEXIT_CRITICAL(); - } -} -/*-----------------------------------------------------------*/ - -#if ( INCLUDE_vTaskDelete == 1 ) - - void vTaskDelete( TaskHandle_t xTaskToDelete ) - { - TCB_t *pxTCB; - UBaseType_t uxPsrId = uxPortGetProcessorId(); - - 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[uxPsrId]++; - - if( pxTCB == pxCurrentTCB[uxPsrId] ) - { - /* 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[uxPsrId], &( 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[uxPsrId]; - - /* 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[uxPsrId]); - } - else - { - --uxCurrentNumberOfTasks[uxPsrId]; - 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[uxPsrId] != pdFALSE ) - { - if( pxTCB == pxCurrentTCB[uxPsrId]) - { - configASSERT( uxSchedulerSuspended[uxPsrId] == 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; - UBaseType_t uxPsrId = uxPortGetProcessorId(); - - configASSERT( pxPreviousWakeTime ); - configASSERT( ( xTimeIncrement > 0U ) ); - configASSERT( uxSchedulerSuspended[uxPsrId] == 0 ); - - vTaskSuspendAll(); - { - /* Minor optimisation. The tick count cannot change in this - block. */ - const TickType_t xConstTickCount = xTickCount[uxPsrId]; - - /* 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; - UBaseType_t uxPsrId = uxPortGetProcessorId(); - - /* A delay time of zero just forces a reschedule. */ - if( xTicksToDelay > ( TickType_t ) 0U ) - { - configASSERT( uxSchedulerSuspended[uxPsrId] == 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; - UBaseType_t uxPsrId = uxPortGetProcessorId(); - - configASSERT( pxTCB ); - - if( pxTCB == pxCurrentTCB[uxPsrId] ) - { - /* 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[uxPsrId]) || ( pxStateList == pxOverflowDelayedTaskList[uxPsrId] ) ) - { - /* The task being queried is referenced from one of the Blocked - lists. */ - eReturn = eBlocked; - } - - #if ( INCLUDE_vTaskSuspend == 1 ) - else if( pxStateList == &xSuspendedTaskList[uxPsrId] ) - { - /* 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[uxPsrId] ) || ( 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; - UBaseType_t uxPsrId = uxPortGetProcessorId(); - - 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; - UBaseType_t uxPsrId = uxPortGetProcessorId(); - - /* 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; - UBaseType_t uxPsrId = uxPortGetProcessorId(); - - 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[uxPsrId] ) - { - /* 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[uxPsrId]->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[uxPsrId] ) - { - /* 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[uxPsrId][ 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[uxPsrId] ); - } - 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; - UBaseType_t uxPsrId = uxPortGetProcessorId(); - - 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[uxPsrId], &( 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[uxPsrId] != 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[uxPsrId] ) - { - if( xSchedulerRunning[uxPsrId] != pdFALSE ) - { - /* The current task has just been suspended. */ - configASSERT( uxSchedulerSuspended[uxPsrId] == 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[uxPsrId] ) == uxCurrentNumberOfTasks[uxPsrId] ) - { - /* 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[uxPsrId] = 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; - UBaseType_t uxPsrId = uxPortGetProcessorId(); - - /* 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[uxPsrId], &( pxTCB->xStateListItem ) ) != pdFALSE ) - { - /* Has the task already been resumed from within an ISR? */ - if( listIS_CONTAINED_WITHIN( &xPendingReadyList[uxPsrId], &( 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; - UBaseType_t uxPsrId = uxPortGetProcessorId(); - - /* 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[uxPsrId] ) ) - { - 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[uxPsrId]->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; - UBaseType_t uxPsrId = uxPortGetProcessorId(); - - 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[uxPsrId] == ( 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[uxPsrId]->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[uxPsrId] ), &( pxTCB->xEventListItem ) ); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - - return xYieldRequired; - } - -#endif /* ( ( INCLUDE_xTaskResumeFromISR == 1 ) && ( INCLUDE_vTaskSuspend == 1 ) ) */ -/*-----------------------------------------------------------*/ - -void vTaskStartScheduler() -{ -BaseType_t xReturn; -UBaseType_t uxPsrId = uxPortGetProcessorId(); - - /* Add the idle task at the lowest priority. */ - #if( configSUPPORT_STATIC_ALLOCATION == 1 && 0) - { - 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[uxPsrId] = 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[uxPsrId] ); /*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[uxPsrId]->xNewLib_reent ); - } - #endif /* configUSE_NEWLIB_REENTRANT */ - - xNextTaskUnblockTime[uxPsrId] = portMAX_DELAY; - xSchedulerRunning[uxPsrId] = pdTRUE; - xTickCount[uxPsrId] = ( 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(); - UBaseType_t uxPsrId = uxPortGetProcessorId(); - xSchedulerRunning[uxPsrId] = 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 */ - UBaseType_t uxPsrId = uxPortGetProcessorId(); - ++uxSchedulerSuspended[uxPsrId]; -} -/*----------------------------------------------------------*/ - -#if ( configUSE_TICKLESS_IDLE != 0 ) - - static TickType_t prvGetExpectedIdleTime( void ) - { - TickType_t xReturn; - UBaseType_t uxHigherPriorityReadyTasks = pdFALSE; - UBaseType_t uxPsrId = uxPortGetProcessorId(); - - /* 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[uxPsrId] > 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[uxPsrId]->uxPriority > tskIDLE_PRIORITY ) - { - xReturn = 0; - } - else if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[uxPsrId][ 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[uxPsrId] - xTickCount[uxPsrId]; - } - - return xReturn; - } - -#endif /* configUSE_TICKLESS_IDLE */ -/*----------------------------------------------------------*/ - -BaseType_t xTaskResumeAll( void ) -{ -TCB_t *pxTCB = NULL; -BaseType_t xAlreadyYielded = pdFALSE; -UBaseType_t uxPsrId = uxPortGetProcessorId(); - - /* If uxSchedulerSuspended is zero then this function does not match a - previous call to vTaskSuspendAll(). */ - configASSERT( uxSchedulerSuspended[uxPsrId] ); - - /* 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[uxPsrId]; - - if( uxSchedulerSuspended[uxPsrId] == ( UBaseType_t ) pdFALSE ) - { - if( uxCurrentNumberOfTasks[uxPsrId] > ( UBaseType_t ) 0U ) - { - /* Move any readied tasks from the pending list into the - appropriate ready list. */ - while( listLIST_IS_EMPTY( &xPendingReadyList[uxPsrId] ) == pdFALSE ) - { - pxTCB = ( TCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( ( &xPendingReadyList[uxPsrId] ) ); - ( 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[uxPsrId]->uxPriority ) - { - xYieldPending[uxPsrId] = 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[uxPsrId]; /* Non-volatile copy. */ - - if( uxPendedCounts > ( UBaseType_t ) 0U ) - { - do - { - if( xTaskIncrementTick() != pdFALSE ) - { - xYieldPending[uxPsrId] = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - --uxPendedCounts; - } while( uxPendedCounts > ( UBaseType_t ) 0U ); - - uxPendedTicks[uxPsrId] = 0; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - - if( xYieldPending[uxPsrId] != 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; -UBaseType_t uxPsrId = uxPortGetProcessorId(); - - /* Critical section required if running on a 16 bit processor. */ - portTICK_TYPE_ENTER_CRITICAL(); - { - xTicks = xTickCount[uxPsrId]; - } - portTICK_TYPE_EXIT_CRITICAL(); - - return xTicks; -} -/*-----------------------------------------------------------*/ - -TickType_t xTaskGetTickCountFromISR( void ) -{ -TickType_t xReturn; -UBaseType_t uxSavedInterruptStatus; -UBaseType_t uxPsrId = uxPortGetProcessorId(); - - /* 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[uxPsrId]; - } - 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. */ - UBaseType_t uxPsrId = uxPortGetProcessorId(); - return uxCurrentNumberOfTasks[uxPsrId]; -} -/*-----------------------------------------------------------*/ - -char *pcTaskGetName( TaskHandle_t xTaskToQuery ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ -{ -TCB_t *pxTCB; -UBaseType_t uxPsrId = uxPortGetProcessorId(); - - /* 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 ) - { - UBaseType_t uxPsrId = uxPortGetProcessorId(); - /* 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[uxPsrId] + xTicksToJump ) <= xNextTaskUnblockTime[uxPsrId]); - xTickCount[uxPsrId] += 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; - UBaseType_t uxPsrId = uxPortGetProcessorId(); - - 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[uxPsrId]->uxPriority ) - { - /* Pend the yield to be performed when the scheduler - is unsuspended. */ - xYieldPending[uxPsrId] = 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; -UBaseType_t uxPsrId = uxPortGetProcessorId(); - - /* 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[uxPsrId] ); - if( uxSchedulerSuspended[uxPsrId] == ( UBaseType_t ) pdFALSE ) - { - /* Minor optimisation. The tick count cannot change in this - block. */ - const TickType_t xConstTickCount = xTickCount[uxPsrId] + ( TickType_t ) 1; - - /* Increment the RTOS tick, switching the delayed and overflowed - delayed lists if it wraps to 0. */ - xTickCount[uxPsrId] = 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[uxPsrId]) - { - for( ;; ) - { - if( listLIST_IS_EMPTY( pxDelayedTaskList[uxPsrId] ) != 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[uxPsrId] = 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[uxPsrId] ); - 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[uxPsrId] = 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[uxPsrId]->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[uxPsrId][ pxCurrentTCB[uxPsrId]->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[uxPsrId]; - - /* 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[uxPsrId] != 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; - UBaseType_t uxPsrId = uxPortGetProcessorId(); - - /* 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[uxPsrId]; - } - 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; - UBaseType_t uxPsrId = uxPortGetProcessorId(); - TaskHookFunction_t xReturn; - - /* If xTask is NULL then we are setting our own task hook. */ - if( xTask == NULL ) - { - xTCB = ( TCB_t * ) pxCurrentTCB[uxPsrId]; - } - 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; - UBaseType_t uxPsrId = uxPortGetProcessorId(); - BaseType_t xReturn; - - /* If xTask is NULL then we are calling our own task hook. */ - if( xTask == NULL ) - { - xTCB = ( TCB_t * ) pxCurrentTCB[uxPsrId]; - } - 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 ) -{ - UBaseType_t uxPsrId = uxPortGetProcessorId(); - if( uxSchedulerSuspended[uxPsrId] != ( UBaseType_t ) pdFALSE ) - { - /* The scheduler is currently suspended - do not allow a context - switch. */ - xYieldPending[uxPsrId] = pdTRUE; - } - else - { - xYieldPending[uxPsrId] = 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[uxPsrId]->xNewLib_reent ); - } - #endif /* configUSE_NEWLIB_REENTRANT */ - } -} -/*-----------------------------------------------------------*/ - -void vTaskPlaceOnEventList( List_t * const pxEventList, const TickType_t xTicksToWait ) -{ - configASSERT( pxEventList ); - UBaseType_t uxPsrId = uxPortGetProcessorId(); - - /* 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[uxPsrId]->xEventListItem ) ); - - prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE ); -} -/*-----------------------------------------------------------*/ - -void vTaskPlaceOnUnorderedEventList( List_t * pxEventList, const TickType_t xItemValue, const TickType_t xTicksToWait ) -{ - configASSERT( pxEventList ); - - UBaseType_t uxPsrId = uxPortGetProcessorId(); - /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED. It is used by - the event groups implementation. */ - configASSERT( uxSchedulerSuspended[uxPsrId] != 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[uxPsrId]->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[uxPsrId]->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; -UBaseType_t uxPsrId = uxPortGetProcessorId(); - - /* 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[uxPsrId] == ( 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[uxPsrId] ), &( pxUnblockedTCB->xEventListItem ) ); - } - - if( pxUnblockedTCB->uxPriority > pxCurrentTCB[uxPsrId]->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[uxPsrId] = 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; -UBaseType_t uxPsrId = uxPortGetProcessorId(); - - /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED. It is used by - the event flags implementation. */ - configASSERT( uxSchedulerSuspended[uxPsrId] != 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[uxPsrId]->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[uxPsrId] = pdTRUE; - } -} -/*-----------------------------------------------------------*/ - -void vTaskSetTimeOutState( TimeOut_t * const pxTimeOut ) -{ - configASSERT( pxTimeOut ); - UBaseType_t uxPsrId = uxPortGetProcessorId(); - taskENTER_CRITICAL(); - { - pxTimeOut->xOverflowCount = xNumOfOverflows[uxPsrId]; - pxTimeOut->xTimeOnEntering = xTickCount[uxPsrId]; - } - taskEXIT_CRITICAL(); -} -/*-----------------------------------------------------------*/ - -void vTaskInternalSetTimeOutState( TimeOut_t * const pxTimeOut ) -{ - UBaseType_t uxPsrId = uxPortGetProcessorId(); - /* For internal use only as it does not use a critical section. */ - pxTimeOut->xOverflowCount = xNumOfOverflows[uxPsrId]; - pxTimeOut->xTimeOnEntering = xTickCount[uxPsrId]; -} -/*-----------------------------------------------------------*/ - -BaseType_t xTaskCheckForTimeOut( TimeOut_t * const pxTimeOut, TickType_t * const pxTicksToWait ) -{ -BaseType_t xReturn; -UBaseType_t uxPsrId = uxPortGetProcessorId(); - - configASSERT( pxTimeOut ); - configASSERT( pxTicksToWait ); - - taskENTER_CRITICAL(); - { - /* Minor optimisation. The tick count cannot change in this block. */ - const TickType_t xConstTickCount = xTickCount[uxPsrId]; - const TickType_t xElapsedTime = xConstTickCount - pxTimeOut->xTimeOnEntering; - - #if( INCLUDE_xTaskAbortDelay == 1 ) - if( pxCurrentTCB[uxPsrId]->ucDelayAborted != pdFALSE ) - { - /* The delay was aborted, which is not the same as a time out, - but has the same result. */ - pxCurrentTCB[uxPsrId]->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[uxPsrId] != 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 ) -{ - UBaseType_t uxPsrId = uxPortGetProcessorId(); - xYieldPending[uxPsrId] = 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; - UBaseType_t uxPsrId = uxPortGetProcessorId(); - - /** 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[uxPsrId] >= xTickCount[uxPsrId]); - 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; - UBaseType_t uxPsrId = uxPortGetProcessorId(); - - if( listCURRENT_LIST_LENGTH( &xPendingReadyList[uxPsrId] ) != 0 ) - { - /* A task was made ready while the scheduler was suspended. */ - eReturn = eAbortSleep; - } - else if( xYieldPending[uxPsrId] != 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[uxPsrId] ) == ( uxCurrentNumberOfTasks[uxPsrId] - 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; - UBaseType_t uxPsrId = uxPortGetProcessorId(); - - 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; - UBaseType_t uxPsrId = uxPortGetProcessorId(); - - 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; -UBaseType_t uxPsrId = uxPortGetProcessorId(); - - for( uxPriority = ( UBaseType_t ) 0U; uxPriority < ( UBaseType_t ) configMAX_PRIORITIES; uxPriority++ ) - { - vListInitialise( &( pxReadyTasksLists[uxPsrId][ uxPriority ] ) ); - } - - vListInitialise( &xDelayedTaskList1[uxPsrId] ); - vListInitialise( &xDelayedTaskList2[uxPsrId] ); - vListInitialise( &xPendingReadyList[uxPsrId] ); - - #if ( INCLUDE_vTaskDelete == 1 ) - { - vListInitialise( &xTasksWaitingTermination[uxPsrId] ); - } - #endif /* INCLUDE_vTaskDelete */ - - #if ( INCLUDE_vTaskSuspend == 1 ) - { - vListInitialise( &xSuspendedTaskList[uxPsrId] ); - } - #endif /* INCLUDE_vTaskSuspend */ - - /* Start with pxDelayedTaskList using list1 and the pxOverflowDelayedTaskList - using list2. */ - pxDelayedTaskList[uxPsrId] = &xDelayedTaskList1[uxPsrId]; - pxOverflowDelayedTaskList[uxPsrId] = &xDelayedTaskList2[uxPsrId]; -} -/*-----------------------------------------------------------*/ - -static void prvCheckTasksWaitingTermination( void ) -{ - - /** THIS FUNCTION IS CALLED FROM THE RTOS IDLE TASK **/ - - #if ( INCLUDE_vTaskDelete == 1 ) - { - TCB_t *pxTCB; - UBaseType_t uxPsrId = uxPortGetProcessorId(); - - /* uxDeletedTasksWaitingCleanUp is used to prevent vTaskSuspendAll() - being called too often in the idle task. */ - while( uxDeletedTasksWaitingCleanUp[uxPsrId] > ( UBaseType_t ) 0U ) - { - taskENTER_CRITICAL(); - { - pxTCB = ( TCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( ( &xTasksWaitingTermination[uxPsrId] ) ); - ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); - --uxCurrentNumberOfTasks[uxPsrId]; - --uxDeletedTasksWaitingCleanUp[uxPsrId]; - } - 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; - UBaseType_t uxPsrId = uxPortGetProcessorId(); - 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; -UBaseType_t uxPsrId = uxPortGetProcessorId(); - - if( listLIST_IS_EMPTY( pxDelayedTaskList[uxPsrId] ) != 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[uxPsrId] = 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[uxPsrId] ); - xNextTaskUnblockTime[uxPsrId] = listGET_LIST_ITEM_VALUE( &( ( pxTCB )->xStateListItem ) ); - } -} -/*-----------------------------------------------------------*/ - -#if ( ( INCLUDE_xTaskGetCurrentTaskHandle == 1 ) || ( configUSE_MUTEXES == 1 ) ) - - TaskHandle_t xTaskGetCurrentTaskHandle( void ) - { - TaskHandle_t xReturn; - UBaseType_t uxPsrId = uxPortGetProcessorId(); - - /* 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[uxPsrId]; - - 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[uxPsrId] == ( 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; - UBaseType_t uxPsrId = uxPortGetProcessorId(); - - /* 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[uxPsrId]->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[uxPsrId]->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[uxPsrId][ 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[uxPsrId]->uxPriority; - prvAddTaskToReadyList( pxMutexHolderTCB ); - } - else - { - /* Just inherit the priority. */ - pxMutexHolderTCB->uxPriority = pxCurrentTCB[uxPsrId]->uxPriority; - } - - traceTASK_PRIORITY_INHERIT( pxMutexHolderTCB, pxCurrentTCB[uxPsrId]->uxPriority ); - - /* Inheritance occurred. */ - xReturn = pdTRUE; - } - else - { - if( pxMutexHolderTCB->uxBasePriority < pxCurrentTCB[uxPsrId]->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; - UBaseType_t uxPsrId = uxPortGetProcessorId(); - - 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[uxPsrId] ); - 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; - UBaseType_t uxPsrId = uxPortGetProcessorId(); - - 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[uxPsrId] ); - - /* 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[uxPsrId][ 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(); - UBaseType_t uxPsrId = uxPortGetProcessorId(); - - if( xSchedulerRunning[uxPsrId] != pdFALSE ) - { - ( pxCurrentTCB[uxPsrId]->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[uxPsrId]->uxCriticalNesting == 1 ) - { - portASSERT_IF_IN_ISR(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - -#endif /* portCRITICAL_NESTING_IN_TCB */ -/*-----------------------------------------------------------*/ - -#if ( portCRITICAL_NESTING_IN_TCB == 1 ) - - void vTaskExitCritical( void ) - { - UBaseType_t uxPsrId = uxPortGetProcessorId(); - if( xSchedulerRunning[uxPsrId] != pdFALSE ) - { - if( pxCurrentTCB[uxPsrId]->uxCriticalNesting > 0U ) - { - ( pxCurrentTCB[uxPsrId]->uxCriticalNesting )--; - - if( pxCurrentTCB[uxPsrId]->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; -UBaseType_t uxPsrId = uxPortGetProcessorId(); - - uxReturn = listGET_LIST_ITEM_VALUE( &( pxCurrentTCB[uxPsrId]->xEventListItem ) ); - - /* Reset the event list item to its normal value - so it can be used with - queues and semaphores. */ - listSET_LIST_ITEM_VALUE( &( pxCurrentTCB[uxPsrId]->xEventListItem ), ( ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) pxCurrentTCB[uxPsrId]->uxPriority ) ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - - return uxReturn; -} -/*-----------------------------------------------------------*/ - -#if ( configUSE_MUTEXES == 1 ) - - void *pvTaskIncrementMutexHeldCount( void ) - { - UBaseType_t uxPsrId = uxPortGetProcessorId(); - /* If xSemaphoreCreateMutex() is called before any tasks have been created - then pxCurrentTCB will be NULL. */ - if( pxCurrentTCB[uxPsrId] != NULL ) - { - ( pxCurrentTCB[uxPsrId]->uxMutexesHeld )++; - } - - return pxCurrentTCB[uxPsrId]; - } - -#endif /* configUSE_MUTEXES */ -/*-----------------------------------------------------------*/ - -#if( configUSE_TASK_NOTIFICATIONS == 1 ) - - uint32_t ulTaskNotifyTake( BaseType_t xClearCountOnExit, TickType_t xTicksToWait ) - { - uint32_t ulReturn; - UBaseType_t uxPsrId = uxPortGetProcessorId(); - - taskENTER_CRITICAL(); - { - /* Only block if the notification count is not already non-zero. */ - if( pxCurrentTCB[uxPsrId]->ulNotifiedValue == 0UL ) - { - /* Mark this task as waiting for a notification. */ - pxCurrentTCB[uxPsrId]->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[uxPsrId]->ulNotifiedValue; - - if( ulReturn != 0UL ) - { - if( xClearCountOnExit != pdFALSE ) - { - pxCurrentTCB[uxPsrId]->ulNotifiedValue = 0UL; - } - else - { - pxCurrentTCB[uxPsrId]->ulNotifiedValue = ulReturn - ( uint32_t ) 1; - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - - pxCurrentTCB[uxPsrId]->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; - UBaseType_t uxPsrId = uxPortGetProcessorId(); - - taskENTER_CRITICAL(); - { - /* Only block if a notification is not already pending. */ - if( pxCurrentTCB[uxPsrId]->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[uxPsrId]->ulNotifiedValue &= ~ulBitsToClearOnEntry; - - /* Mark this task as waiting for a notification. */ - pxCurrentTCB[uxPsrId]->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[uxPsrId]->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[uxPsrId]->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[uxPsrId]->ulNotifiedValue &= ~ulBitsToClearOnExit; - xReturn = pdTRUE; - } - - pxCurrentTCB[uxPsrId]->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; - UBaseType_t uxPsrId = uxPortGetProcessorId(); - - 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[uxPsrId]->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; - UBaseType_t uxPsrId = uxPortGetProcessorId(); - - 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[uxPsrId] == ( 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[uxPsrId] ), &( pxTCB->xEventListItem ) ); - } - - if( pxTCB->uxPriority > pxCurrentTCB[uxPsrId]->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[uxPsrId] = 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; - UBaseType_t uxPsrId = uxPortGetProcessorId(); - - 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[uxPsrId] == ( 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[uxPsrId] ), &( pxTCB->xEventListItem ) ); - } - - if( pxTCB->uxPriority > pxCurrentTCB[uxPsrId]->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[uxPsrId] = 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; - UBaseType_t uxPsrId = uxPortGetProcessorId(); - - /* 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; -UBaseType_t uxPsrId = uxPortGetProcessorId(); -const TickType_t xConstTickCount = xTickCount[uxPsrId]; - - #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[uxPsrId]->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[uxPsrId]->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[uxPsrId]->uxPriority, uxTopReadyPriority[uxPsrId] ); - } - 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[uxPsrId], &( pxCurrentTCB[uxPsrId]->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[uxPsrId]->xStateListItem ), xTimeToWake ); - - if( xTimeToWake < xConstTickCount ) - { - /* Wake time has overflowed. Place this item in the overflow - list. */ - vListInsert( pxOverflowDelayedTaskList[uxPsrId], &( pxCurrentTCB[uxPsrId]->xStateListItem ) ); - } - else - { - /* The wake time has not overflowed, so the current block list - is used. */ - vListInsert( pxDelayedTaskList[uxPsrId], &( pxCurrentTCB[uxPsrId]->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[uxPsrId]) - { - xNextTaskUnblockTime[uxPsrId] = 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/cores/arduino/kendryte-standalone-sdk/lib/freertos/timers.c b/cores/arduino/kendryte-standalone-sdk/lib/freertos/timers.c deleted file mode 100644 index a845b81..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/freertos/timers.c +++ /dev/null @@ -1,1090 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * 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. - */ -/* - * 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/cores/arduino/kendryte-standalone-sdk/lib/utils/include/syslog.h b/cores/arduino/kendryte-standalone-sdk/lib/utils/include/syslog.h deleted file mode 100644 index cc10b4f..0000000 --- a/cores/arduino/kendryte-standalone-sdk/lib/utils/include/syslog.h +++ /dev/null @@ -1,141 +0,0 @@ -/* Copyright 2018 Canaan Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef _SYSLOG_H -#define _SYSLOG_H - -#include -#include -#include "printf.h" -#include "encoding.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * @brief Logging library - * - * Log library has two ways of managing log verbosity: compile time, set via - * menuconfig - * - * At compile time, filtering is done using CONFIG_LOG_DEFAULT_LEVEL macro, set via - * menuconfig. All logging statments for levels higher than CONFIG_LOG_DEFAULT_LEVEL - * will be removed by the preprocessor. - * - * - * How to use this library: - * - * In each C file which uses logging functionality, define TAG variable like this: - * - * static const char *TAG = "MODULE_NAME"; - * - * then use one of logging macros to produce output, e.g: - * - * LOGW(TAG, "Interrupt error %d", error); - * - * Several macros are available for different verbosity levels: - * - * LOGE - error - * LOGW - warning - * LOGI - info - * LOGD - debug - * LOGV - verbose - * - * To override default verbosity level at file or component scope, define LOG_LEVEL macro. - * At file scope, define it before including esp_log.h, e.g.: - * - * #define LOG_LEVEL LOG_VERBOSE - * #include "dxx_log.h" - * - * At component scope, define it in component makefile: - * - * CFLAGS += -D LOG_LEVEL=LOG_DEBUG - * - * - */ - -/* clang-format off */ -typedef enum _kendryte_log_level -{ - LOG_NONE, /*!< No log output */ - LOG_ERROR, /*!< Critical errors, software module can not recover on its own */ - LOG_WARN, /*!< Error conditions from which recovery measures have been taken */ - LOG_INFO, /*!< Information messages which describe normal flow of events */ - LOG_DEBUG, /*!< Extra information which is not necessary for normal use (values, pointers, sizes, etc). */ - LOG_VERBOSE /*!< Bigger chunks of debugging information, or frequent messages which can potentially flood the output. */ -} kendryte_log_level_t ; -/* clang-format on */ - -/* clang-format off */ -#if CONFIG_LOG_COLORS -#define LOG_COLOR_BLACK "30" -#define LOG_COLOR_RED "31" -#define LOG_COLOR_GREEN "32" -#define LOG_COLOR_BROWN "33" -#define LOG_COLOR_BLUE "34" -#define LOG_COLOR_PURPLE "35" -#define LOG_COLOR_CYAN "36" -#define LOG_COLOR(COLOR) "\033[0;" COLOR "m" -#define LOG_BOLD(COLOR) "\033[1;" COLOR "m" -#define LOG_RESET_COLOR "\033[0m" -#define LOG_COLOR_E LOG_COLOR(LOG_COLOR_RED) -#define LOG_COLOR_W LOG_COLOR(LOG_COLOR_BROWN) -#define LOG_COLOR_I LOG_COLOR(LOG_COLOR_GREEN) -#define LOG_COLOR_D -#define LOG_COLOR_V -#else /* CONFIG_LOG_COLORS */ -#define LOG_COLOR_E -#define LOG_COLOR_W -#define LOG_COLOR_I -#define LOG_COLOR_D -#define LOG_COLOR_V -#define LOG_RESET_COLOR -#endif /* CONFIG_LOG_COLORS */ -/* clang-format on */ - -#define LOG_FORMAT(letter, format) LOG_COLOR_ ## letter #letter " (%lu) %s: " format LOG_RESET_COLOR "\n" - -#ifdef LOG_LEVEL -#undef CONFIG_LOG_LEVEL -#define CONFIG_LOG_LEVEL LOG_LEVEL -#endif - -#ifdef LOG_KERNEL -#define LOG_PRINTF printk -#else -#define LOG_PRINTF printf -#endif - -#ifdef CONFIG_LOG_ENABLE -#define LOGE(tag, format, ...) do {if (CONFIG_LOG_LEVEL >= LOG_ERROR) LOG_PRINTF(LOG_FORMAT(E, format), read_cycle(), tag, ##__VA_ARGS__); } while (0) -#define LOGW(tag, format, ...) do {if (CONFIG_LOG_LEVEL >= LOG_WARN) LOG_PRINTF(LOG_FORMAT(W, format), read_cycle(), tag, ##__VA_ARGS__); } while (0) -#define LOGI(tag, format, ...) do {if (CONFIG_LOG_LEVEL >= LOG_INFO) LOG_PRINTF(LOG_FORMAT(I, format), read_cycle(), tag, ##__VA_ARGS__); } while (0) -#define LOGD(tag, format, ...) do {if (CONFIG_LOG_LEVEL >= LOG_DEBUG) LOG_PRINTF(LOG_FORMAT(D, format), read_cycle(), tag, ##__VA_ARGS__); } while (0) -#define LOGV(tag, format, ...) do {if (CONFIG_LOG_LEVEL >= LOG_VERBOSE) LOG_PRINTF(LOG_FORMAT(V, format), read_cycle(), tag, ##__VA_ARGS__); } while (0) -#else -#define LOGE(tag, format, ...) -#define LOGW(tag, format, ...) -#define LOGI(tag, format, ...) -#define LOGD(tag, format, ...) -#define LOGV(tag, format, ...) -#endif /* LOG_ENABLE */ - -#ifdef __cplusplus -} -#endif - - -#endif /* _SYSLOG_H */ -