diff --git a/.circleci/config.yml b/.circleci/config.yml index 28afafb00..c2f6c4356 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -19,16 +19,40 @@ jobs: echo "MATRIX_JSON=$MATRIX_JSON" BUILDSYSTEM_TOOLCHAIN=( + "cmake aarch64-gcc" "cmake arm-clang" - "make aarch64-gcc" - "make arm-gcc" - "make msp430-gcc" - "make riscv-gcc" - "make rx-gcc" + "cmake arm-gcc" "cmake esp-idf" + "cmake msp430-gcc" + "cmake riscv-gcc" ) - RESOURCE_LARGE='["nrf", "imxrt"]' + # only build IAR if not forked PR, since IAR token is not shared + if [ -z $CIRCLE_PR_USERNAME ]; then + BUILDSYSTEM_TOOLCHAIN+=("cmake arm-iar") + fi + + RESOURCE_LARGE='["nrf", "imxrt", "stm32f4", "stm32h7"]' + + gen_build_entry() { + local build_system="$1" + local toolchain="$2" + local family="$3" + local resource_class="$4" + + if [[ "$toolchain" == "esp-idf" ]]; then + echo " - build-vm:" >> .circleci/config2.yml + else + echo " - build:" >> .circleci/config2.yml + fi + + echo " matrix:" >> .circleci/config2.yml + echo " parameters:" >> .circleci/config2.yml + echo " build-system: ['$build_system']" >> .circleci/config2.yml + echo " toolchain: ['$toolchain']" >> .circleci/config2.yml + echo " family: $family" >> .circleci/config2.yml + echo " resource_class: ['$resource_class']" >> .circleci/config2.yml + } for e in "${BUILDSYSTEM_TOOLCHAIN[@]}"; do e_arr=($e) @@ -42,27 +66,15 @@ jobs: FAMILY_LARGE=$(jq -n --argjson family "$FAMILY" --argjson resource "$RESOURCE_LARGE" '$family | map(select(IN($resource[])))') FAMILY=$(jq -n --argjson family "$FAMILY" --argjson resource "$RESOURCE_LARGE" '$family | map(select(IN($resource[]) | not))') - if [[ $toolchain == esp-idf ]]; then - echo " - build-vm:" >> .circleci/config2.yml + if [[ $toolchain == esp-idf || $toolchain == arm-iar ]]; then + gen_build_entry "$build_system" "$toolchain" "$FAMILY" "large" else - echo " - build:" >> .circleci/config2.yml - fi - echo " matrix:" >> .circleci/config2.yml - echo " parameters:" >> .circleci/config2.yml - echo " build-system: ['$build_system']" >> .circleci/config2.yml - echo " toolchain: ['$toolchain']" >> .circleci/config2.yml - echo " family: $FAMILY" >> .circleci/config2.yml - #echo " resource_class: ['medium+']" >> .circleci/config2.yml + gen_build_entry "$build_system" "$toolchain" "$FAMILY" "medium+" - # add large resources - if [ "$(echo $FAMILY_LARGE | jq 'length')" -gt 0 ]; then - echo " - build:" >> .circleci/config2.yml - echo " matrix:" >> .circleci/config2.yml - echo " parameters:" >> .circleci/config2.yml - echo " build-system: ['$build_system']" >> .circleci/config2.yml - echo " toolchain: ['$toolchain']" >> .circleci/config2.yml - echo " family: $FAMILY_LARGE" >> .circleci/config2.yml - echo " resource_class: ['large']" >> .circleci/config2.yml + # add large resources if available + if [ "$(echo $FAMILY_LARGE | jq 'length')" -gt 0 ]; then + gen_build_entry "$build_system" "$toolchain" "$FAMILY_LARGE" "large" + fi fi done diff --git a/.circleci/config2.yml b/.circleci/config2.yml index e811ef3ed..d86a3f662 100644 --- a/.circleci/config2.yml +++ b/.circleci/config2.yml @@ -10,16 +10,7 @@ commands: - run: name: Set toolchain url and key command: | - TOOLCHAIN_JSON='{ - "aarch64-gcc": "https://developer.arm.com/-/media/Files/downloads/gnu-a/10.3-2021.07/binrel/gcc-arm-10.3-2021.07-x86_64-aarch64-none-elf.tar.xz", - "arm-clang": "https://github.com/ARM-software/LLVM-embedded-toolchain-for-Arm/releases/download/release-19.1.1/LLVM-ET-Arm-19.1.1-Linux-x86_64.tar.xz", - "arm-gcc": "https://github.com/xpack-dev-tools/arm-none-eabi-gcc-xpack/releases/download/v13.2.1-1.1/xpack-arm-none-eabi-gcc-13.2.1-1.1-linux-x64.tar.gz", - "msp430-gcc": "http://software-dl.ti.com/msp430/msp430_public_sw/mcu/msp430/MSPGCC/9_2_0_0/export/msp430-gcc-9.2.0.50_linux64.tar.bz2", - "riscv-gcc": "https://github.com/xpack-dev-tools/riscv-none-elf-gcc-xpack/releases/download/v13.2.0-2/xpack-riscv-none-elf-gcc-13.2.0-2-linux-x64.tar.gz", - "rx-gcc": "https://llvm-gcc-renesas.com/downloads/get.php?f=rx/8.3.0.202004-gnurx/gcc-8.3.0.202004-GNURX-ELF.run" - }' - toolchain_url=$(echo $TOOLCHAIN_JSON | jq -r '.["<< parameters.toolchain >>"]') - + toolchain_url=$(jq -r '."<< parameters.toolchain >>"' .github/actions/setup_toolchain/toolchain.json) # only cache if not a github link if [[ $toolchain_url != "https://github.com"* ]]; then echo "<< parameters.toolchain >>-$toolchain_url" > toolchain_key @@ -38,18 +29,26 @@ commands: # download if folder does not exist (not cached) if [ ! -d ~/cache/<< parameters.toolchain >> ]; then mkdir -p ~/cache/<< parameters.toolchain >> - wget --progress=dot:giga $toolchain_url -O toolchain.tar.gz if [[ << parameters.toolchain >> == rx-gcc ]]; then - mv toolchain.tar.gz toolchain.run + wget --progress=dot:giga $toolchain_url -O toolchain.run chmod +x toolchain.run ./toolchain.run -p ~/cache/<< parameters.toolchain >>/gnurx -y + elif [[ << parameters.toolchain >> == arm-iar ]]; then + wget --progress=dot:giga $toolchain_url -O ~/cache/<< parameters.toolchain >>/toolchain.deb else + wget --progress=dot:giga $toolchain_url -O toolchain.tar.gz tar -C ~/cache/<< parameters.toolchain >> -xaf toolchain.tar.gz fi fi # Add toolchain to PATH - echo "export PATH=$PATH:`echo ~/cache/<< parameters.toolchain >>/*/bin`" >> $BASH_ENV + if [[ << parameters.toolchain >> == arm-iar ]]; then + # Install IAR since we only cache deb file + sudo dpkg --ignore-depends=libusb-1.0-0 -i ~/cache/<< parameters.toolchain >>/toolchain.deb + echo "export PATH=$PATH:/opt/iar/cxarm/arm/bin" >> $BASH_ENV + else + echo "export PATH=$PATH:`echo ~/cache/<< parameters.toolchain >>/*/bin`" >> $BASH_ENV + fi - save_cache: name: Save Toolchain Cache @@ -105,11 +104,14 @@ commands: name: Build command: | if [ << parameters.toolchain >> == esp-idf ]; then - docker run --rm -v $PWD:/project -w /project espressif/idf:v5.3.1 python tools/build.py << parameters.family >> + docker run --rm -v $PWD:/project -w /project espressif/idf:v5.3.2 python tools/build.py << parameters.family >> else # Toolchain option default is gcc if [ << parameters.toolchain >> == arm-clang ]; then TOOLCHAIN_OPTION="--toolchain clang" + elif [ << parameters.toolchain >> == arm-iar ]; then + TOOLCHAIN_OPTION="--toolchain iar" + iccarm --version elif [ << parameters.toolchain >> == arm-gcc ]; then TOOLCHAIN_OPTION="--toolchain gcc" fi diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index d00ee78bd..35576a439 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -22,10 +22,17 @@ body: validations: required: true + - type: input + attributes: + label: Commit SHA + placeholder: e.g 3a042b37da28d0ba1e5593eb1068ca5645d77b56 or version bundled by esp-idf or pico-sdk + validations: + required: true + - type: input attributes: label: Board - placeholder: e.g Feather nRF52840 Express + placeholder: e.g Adafruit Feather nRF52840 Express validations: required: true diff --git a/.github/actions/setup_toolchain/action.yml b/.github/actions/setup_toolchain/action.yml index 8406a812d..6fd5c9d4e 100644 --- a/.github/actions/setup_toolchain/action.yml +++ b/.github/actions/setup_toolchain/action.yml @@ -4,9 +4,6 @@ inputs: toolchain: description: 'Toolchain name' required: true - toolchain_version: - description: 'Toolchain version' - required: false outputs: build_option: @@ -20,30 +17,21 @@ runs: if: inputs.toolchain == 'arm-gcc' uses: carlosperate/arm-none-eabi-gcc-action@v1 with: - release: '13.2.Rel1' + release: '14.2.Rel1' - name: Pull ESP-IDF docker if: inputs.toolchain == 'esp-idf' uses: ./.github/actions/setup_toolchain/espressif with: toolchain: ${{ inputs.toolchain }} - toolchain_version: ${{ inputs.toolchain_version }} - name: Get Toolchain URL if: >- inputs.toolchain != 'arm-gcc' && - inputs.toolchain != 'arm-iar' && inputs.toolchain != 'esp-idf' id: set-toolchain-url run: | - TOOLCHAIN_JSON='{ - "aarch64-gcc": "https://developer.arm.com/-/media/Files/downloads/gnu-a/10.3-2021.07/binrel/gcc-arm-10.3-2021.07-x86_64-aarch64-none-elf.tar.xz", - "arm-clang": "https://github.com/ARM-software/LLVM-embedded-toolchain-for-Arm/releases/download/release-19.1.1/LLVM-ET-Arm-19.1.1-Linux-x86_64.tar.xz", - "msp430-gcc": "http://software-dl.ti.com/msp430/msp430_public_sw/mcu/msp430/MSPGCC/9_2_0_0/export/msp430-gcc-9.2.0.50_linux64.tar.bz2", - "riscv-gcc": "https://github.com/xpack-dev-tools/riscv-none-elf-gcc-xpack/releases/download/v13.2.0-2/xpack-riscv-none-elf-gcc-13.2.0-2-linux-x64.tar.gz", - "rx-gcc": "http://gcc-renesas.com/downloads/get.php?f=rx/8.3.0.202004-gnurx/gcc-8.3.0.202004-GNURX-ELF.run" - }' - TOOLCHAIN_URL=$(echo $TOOLCHAIN_JSON | jq -r '.["${{ inputs.toolchain }}"]') + TOOLCHAIN_URL=$(jq -r '."${{ inputs.toolchain }}"' .github/actions/setup_toolchain/toolchain.json) echo "toolchain_url=$TOOLCHAIN_URL" echo "toolchain_url=$TOOLCHAIN_URL" >> $GITHUB_OUTPUT shell: bash @@ -51,7 +39,6 @@ runs: - name: Download Toolchain if: >- inputs.toolchain != 'arm-gcc' && - inputs.toolchain != 'arm-iar' && inputs.toolchain != 'esp-idf' uses: ./.github/actions/setup_toolchain/download with: diff --git a/.github/actions/setup_toolchain/download/action.yml b/.github/actions/setup_toolchain/download/action.yml index 813197208..ce9643010 100644 --- a/.github/actions/setup_toolchain/download/action.yml +++ b/.github/actions/setup_toolchain/download/action.yml @@ -23,17 +23,25 @@ runs: if: steps.cache-toolchain-download.outputs.cache-hit != 'true' run: | mkdir -p ~/cache/${{ inputs.toolchain }} - wget --progress=dot:giga ${{ inputs.toolchain_url }} -O toolchain.tar.gz + if [[ ${{ inputs.toolchain }} == rx-gcc ]]; then - mv toolchain.tar.gz toolchain.run + wget --progress=dot:giga ${{ inputs.toolchain_url }} -O toolchain.run chmod +x toolchain.run ./toolchain.run -p ~/cache/${{ inputs.toolchain }}/gnurx -y + elif [[ ${{ inputs.toolchain }} == arm-iar ]]; then + wget --progress=dot:giga ${{ inputs.toolchain_url }} -O ~/cache/${{ inputs.toolchain }}/cxarm.deb else + wget --progress=dot:giga ${{ inputs.toolchain_url }} -O toolchain.tar.gz tar -C ~/cache/${{ inputs.toolchain }} -xaf toolchain.tar.gz fi shell: bash - - name: Set Toolchain Path + - name: Setup Toolchain run: | - echo >> $GITHUB_PATH `echo ~/cache/${{ inputs.toolchain }}/*/bin` + if [[ ${{ inputs.toolchain }} == arm-iar ]]; then + sudo apt-get install -y ~/cache/${{ inputs.toolchain }}/cxarm.deb + echo >> $GITHUB_PATH "/opt/iar/cxarm/arm/bin" + else + echo >> $GITHUB_PATH `echo ~/cache/${{ inputs.toolchain }}/*/bin` + fi shell: bash diff --git a/.github/actions/setup_toolchain/espressif/action.yml b/.github/actions/setup_toolchain/espressif/action.yml index 1e3ce18f1..b50ffd41d 100644 --- a/.github/actions/setup_toolchain/espressif/action.yml +++ b/.github/actions/setup_toolchain/espressif/action.yml @@ -6,7 +6,8 @@ inputs: required: true toolchain_version: description: 'Toolchain version' - required: true + required: false + default: 'v5.3.2' runs: using: "composite" @@ -39,3 +40,9 @@ runs: du -sh $DOCKER_ESP_IDF docker load --input $DOCKER_ESP_IDF shell: bash + + - name: Tag Local Image + run: | + docker tag espressif/idf:${{ inputs.toolchain_version }} espressif/idf:tinyusb + docker images + shell: bash diff --git a/.github/actions/setup_toolchain/toolchain.json b/.github/actions/setup_toolchain/toolchain.json new file mode 100644 index 000000000..f7123ef11 --- /dev/null +++ b/.github/actions/setup_toolchain/toolchain.json @@ -0,0 +1,9 @@ +{ + "aarch64-gcc": "https://developer.arm.com/-/media/Files/downloads/gnu-a/10.3-2021.07/binrel/gcc-arm-10.3-2021.07-x86_64-aarch64-none-elf.tar.xz", + "arm-clang": "https://github.com/ARM-software/LLVM-embedded-toolchain-for-Arm/releases/download/release-19.1.1/LLVM-ET-Arm-19.1.1-Linux-x86_64.tar.xz", + "arm-gcc": "https://github.com/xpack-dev-tools/arm-none-eabi-gcc-xpack/releases/download/v14.2.1-1.1/xpack-arm-none-eabi-gcc-14.2.1-1.1-linux-x64.tar.gz", + "msp430-gcc": "http://software-dl.ti.com/msp430/msp430_public_sw/mcu/msp430/MSPGCC/9_2_0_0/export/msp430-gcc-9.2.0.50_linux64.tar.bz2", + "riscv-gcc": "https://github.com/xpack-dev-tools/riscv-none-elf-gcc-xpack/releases/download/v13.2.0-2/xpack-riscv-none-elf-gcc-13.2.0-2-linux-x64.tar.gz", + "rx-gcc": "https://github.com/hathach/rx_device/releases/download/0.0.1/gcc-8.3.0.202411-GNURX-ELF.run", + "arm-iar": "https://netstorage.iar.com/FileStore/STANDARD/001/003/583/cxarm-9.60.4.deb" +} diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 283b72061..5e11f8a29 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -8,8 +8,8 @@ on: - 'examples/**' - 'lib/**' - 'hw/**' - - 'tools/get_deps.py' - 'tools/build.py' + - 'tools/get_deps.py' - '.github/actions/**' - '.github/workflows/build.yml' - '.github/workflows/build_util.yml' @@ -21,8 +21,9 @@ on: - 'examples/**' - 'lib/**' - 'hw/**' - - 'tools/get_deps.py' + - 'test/hil/**' - 'tools/build.py' + - 'tools/get_deps.py' - '.github/actions/**' - '.github/workflows/build.yml' - '.github/workflows/build_util.yml' @@ -31,11 +32,15 @@ concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true +env: + HIL_JSON: test/hil/tinyusb.json + jobs: set-matrix: runs-on: ubuntu-latest outputs: json: ${{ steps.set-matrix-json.outputs.matrix }} + hil_json: ${{ steps.set-matrix-json.outputs.hil_matrix }} steps: - name: Checkout TinyUSB uses: actions/checkout@v4 @@ -43,33 +48,41 @@ jobs: - name: Generate matrix json id: set-matrix-json run: | + # build matrix MATRIX_JSON=$(python .github/workflows/ci_set_matrix.py) echo "matrix=$MATRIX_JSON" echo "matrix=$MATRIX_JSON" >> $GITHUB_OUTPUT + # hil matrix + HIL_MATRIX_JSON=$(python test/hil/hil_ci_set_matrix.py ${{ env.HIL_JSON }}) + echo "hil_matrix=$HIL_MATRIX_JSON" + echo "hil_matrix=$HIL_MATRIX_JSON" >> $GITHUB_OUTPUT # --------------------------------------- - # Build CMake + # Build CMake: only build on push with one-per-family. + # Full built is done by CircleCI in PR # --------------------------------------- cmake: + if: github.event_name == 'push' needs: set-matrix uses: ./.github/workflows/build_util.yml strategy: fail-fast: false matrix: toolchain: - # - 'arm-clang' is built by circle-ci in PR - 'aarch64-gcc' + #- 'arm-clang' - 'arm-gcc' + - 'esp-idf' - 'msp430-gcc' - 'riscv-gcc' with: build-system: 'cmake' toolchain: ${{ matrix.toolchain }} build-args: ${{ toJSON(fromJSON(needs.set-matrix.outputs.json)[matrix.toolchain]) }} - one-per-family: ${{ github.event_name == 'push' }} + one-per-family: true # --------------------------------------- - # Build Make (built by circle-ci in PR, only build on push here) + # Build Make: only build on push with one-per-family # --------------------------------------- make: if: github.event_name == 'push' @@ -79,19 +92,40 @@ jobs: fail-fast: false matrix: toolchain: - # 'arm-clang' - - 'arm-gcc' - 'aarch64-gcc' + #- 'arm-clang' + - 'arm-gcc' - 'msp430-gcc' - 'riscv-gcc' - 'rx-gcc' - - 'esp-idf' # build-system is ignored with: build-system: 'make' toolchain: ${{ matrix.toolchain }} build-args: ${{ toJSON(fromJSON(needs.set-matrix.outputs.json)[matrix.toolchain]) }} one-per-family: true + # --------------------------------------- + # Build IAR + # Since IAR Token secret is not passed to forked PR, only build non-forked PR with make. + # cmake is built by circle-ci. Due to IAR limit capacity, only build oe per family + # --------------------------------------- + arm-iar: + if: false # disable for now since we got reach capacity limit too often + #if: github.event_name == 'push' && github.repository_owner == 'hathach' + needs: set-matrix + uses: ./.github/workflows/build_util.yml + secrets: inherit + strategy: + fail-fast: false + matrix: + build-system: + - 'make' + with: + build-system: ${{ matrix.build-system }} + toolchain: 'arm-iar' + build-args: ${{ toJSON(fromJSON(needs.set-matrix.outputs.json)['arm-iar']) }} + one-per-family: true + # --------------------------------------- # Build Make on Windows/MacOS # --------------------------------------- @@ -110,16 +144,59 @@ jobs: one-per-family: true # --------------------------------------- - # Build IAR on HFP self-hosted + # Zephyr # --------------------------------------- - arm-iar: - if: github.repository_owner == 'hathach' + zephyr: + if: github.event_name == 'push' + runs-on: ubuntu-latest + steps: + - name: Checkout TinyUSB + uses: actions/checkout@v4 + + - name: Setup Zephyr project + uses: zephyrproject-rtos/action-zephyr-setup@v1 + with: + app-path: examples + toolchains: arm-zephyr-eabi + + - name: Build + run: | + west build -b pca10056 -d examples/device/cdc_msc/build examples/device/cdc_msc -- -DRTOS=zephyr + west build -b pca10056 -d examples/device/msc_dual_lun/build examples/device/msc_dual_lun -- -DRTOS=zephyr + + # --------------------------------------- + # Hardware in the loop (HIL) + # Run on PR only (hil-tinyusb), hil-hfp only run on non-forked PR + # --------------------------------------- + hil-build: + if: | + github.repository_owner == 'hathach' && + (github.event_name == 'pull_request' || github.event_name == 'workflow_dispatch') needs: set-matrix - runs-on: [self-hosted, Linux, X64, hifiphile] - env: - BUILD_ARGS: ${{ join(fromJSON(needs.set-matrix.outputs.json)['arm-iar'], ' ') }} - IAR_LMS_CLOUD_URL: https://license.cloud.iar.com - IAR_LMS_BEARER_TOKEN: ${{ secrets.IAR_LMS_BEARER_TOKEN }} + uses: ./.github/workflows/build_util.yml + strategy: + fail-fast: false + matrix: + toolchain: + - 'arm-gcc' + - 'esp-idf' + with: + build-system: 'cmake' + toolchain: ${{ matrix.toolchain }} + build-args: ${{ toJSON(fromJSON(needs.set-matrix.outputs.hil_json)[matrix.toolchain]) }} + one-per-family: true + upload-artifacts: true + + # --------------------------------------- + # Hardware in the loop (HIL) + # self-hosted on local VM, for attached hardware checkout HIL_JSON + # --------------------------------------- + hil-tinyusb: + if: | + github.repository_owner == 'hathach' && + (github.event_name == 'pull_request' || github.event_name == 'workflow_dispatch') + needs: hil-build + runs-on: [self-hosted, X64, hathach, hardware-in-the-loop] steps: - name: Clean workspace run: | @@ -127,19 +204,61 @@ jobs: rm -rf "${{ github.workspace }}" mkdir -p "${{ github.workspace }}" + - name: Checkout TinyUSB + uses: actions/checkout@v4 + with: + sparse-checkout: test/hil + + - name: Download Artifacts + uses: actions/download-artifact@v4 + with: + path: cmake-build + merge-multiple: true + + - name: Test on actual hardware + run: | + ls cmake-build/ + python3 test/hil/hil_test.py ${{ env.HIL_JSON }} + + # --------------------------------------- + # Hardware in the loop (HIL) + # self-hosted by HFP, build with IAR toolchain, for attached hardware checkout test/hil/hfp.json + # Since IAR Token secret is not passed to forked PR, only build non-forked PR + # --------------------------------------- + hil-hfp: + if: | + github.repository_owner == 'hathach' && + github.event.pull_request.head.repo.fork == false && + (github.event_name == 'pull_request' || github.event_name == 'workflow_dispatch') + runs-on: [self-hosted, Linux, X64, hifiphile] + env: + IAR_LMS_BEARER_TOKEN: ${{ secrets.IAR_LMS_BEARER_TOKEN }} + steps: + - name: Clean workspace + run: | + echo "Cleaning up previous run" + rm -rf "${{ github.workspace }}"3 + mkdir -p "${{ github.workspace }}" + - name: Toolchain version - run: iccarm --version + run: | + iccarm --version - name: Checkout TinyUSB uses: actions/checkout@v4 + - name: Get build boards + run: | + MATRIX_JSON=$(python test/hil/hil_ci_set_matrix.py test/hil/hfp.json) + BUILD_ARGS=$(echo $MATRIX_JSON | jq -r '.["arm-gcc"] | join(" ")') + echo "BUILD_ARGS=$BUILD_ARGS" + echo "BUILD_ARGS=$BUILD_ARGS" >> $GITHUB_ENV + - name: Get Dependencies run: python3 tools/get_deps.py $BUILD_ARGS - name: Build - run: python3 tools/build.py --one-per-family --toolchain iar $BUILD_ARGS + run: python3 tools/build.py -j 4 --toolchain iar $BUILD_ARGS - name: Test on actual hardware (hardware in the loop) - if: github.event_name == 'pull_request' - run: | - python3 test/hil/hil_test.py hfp.json + run: python3 test/hil/hil_test.py hfp.json diff --git a/.github/workflows/build_util.yml b/.github/workflows/build_util.yml index 706ded1c1..a2c96f3c0 100644 --- a/.github/workflows/build_util.yml +++ b/.github/workflows/build_util.yml @@ -41,7 +41,6 @@ jobs: uses: ./.github/actions/setup_toolchain with: toolchain: ${{ inputs.toolchain }} - toolchain_version: 'v5.3.1' - name: Get Dependencies uses: ./.github/actions/get_deps @@ -59,9 +58,11 @@ jobs: shell: bash - name: Build + env: + IAR_LMS_BEARER_TOKEN: ${{ secrets.IAR_LMS_BEARER_TOKEN }} run: | if [ "${{ inputs.toolchain }}" == "esp-idf" ]; then - docker run --rm -v $PWD:/project -w /project espressif/idf:v5.3.1 python tools/build.py ${{ matrix.arg }} + docker run --rm -v $PWD:/project -w /project espressif/idf:tinyusb python tools/build.py ${{ matrix.arg }} else python tools/build.py -s ${{ inputs.build-system }} ${{ steps.setup-toolchain.outputs.build_option }} ${{ steps.set-one-per-family.outputs.build_option }} ${{ matrix.arg }} fi diff --git a/.github/workflows/ci_set_matrix.py b/.github/workflows/ci_set_matrix.py index 78fcac68a..ddb3ee1fb 100755 --- a/.github/workflows/ci_set_matrix.py +++ b/.github/workflows/ci_set_matrix.py @@ -24,7 +24,7 @@ family_list = { "lpc11 lpc13 lpc15": ["arm-gcc", "arm-clang"], "lpc17 lpc18 lpc40 lpc43": ["arm-gcc", "arm-clang"], "lpc51 lpc54 lpc55": ["arm-gcc", "arm-clang"], - "max32650 max32666 max32690 max78002": ["arm-gcc"], + "maxim": ["arm-gcc"], "mcx": ["arm-gcc"], "mm32": ["arm-gcc"], "msp430": ["msp430-gcc"], @@ -40,13 +40,15 @@ family_list = { "stm32f4": ["arm-gcc", "arm-clang", "arm-iar"], "stm32f7": ["arm-gcc", "arm-clang", "arm-iar"], "stm32g0 stm32g4 stm32h5": ["arm-gcc", "arm-clang", "arm-iar"], - "stm32h7": ["arm-gcc", "arm-clang", "arm-iar"], + "stm32h7 stm32h7rs": ["arm-gcc", "arm-clang", "arm-iar"], "stm32l0 stm32l4": ["arm-gcc", "arm-clang", "arm-iar"], + "stm32n6": ["arm-gcc"], "stm32u5 stm32wb": ["arm-gcc", "arm-clang", "arm-iar"], "xmc4000": ["arm-gcc"], - "-bespressif_kaluga_1": ["esp-idf"], - "-bespressif_s3_devkitm": ["esp-idf"], - "-bespressif_p4_function_ev": ["esp-idf"], + "-bespressif_s2_devkitc": ["esp-idf"], + # S3, P4 will be built by hil test + # "-bespressif_s3_devkitm": ["esp-idf"], + # "-bespressif_p4_function_ev": ["esp-idf"], } @@ -55,14 +57,6 @@ def set_matrix_json(): for toolchain in toolchain_list: filtered_families = [family for family, supported_toolchain in family_list.items() if toolchain in supported_toolchain] - - # always add board in hfp.json for arm-iar - if toolchain == 'arm-iar': - with open('test/hil/hfp.json') as f: - hfp_data = json.load(f) - hfp_boards = [f"-b{board['name']}" for board in hfp_data['boards']] - filtered_families = filtered_families + hfp_boards - matrix[toolchain] = filtered_families print(json.dumps(matrix)) diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index be4c2dd87..dfcca6315 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -66,7 +66,7 @@ jobs: # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL - uses: github/codeql-action/init@v2 + uses: github/codeql-action/init@v3 with: languages: ${{ matrix.language }} # If you wish to specify custom queries, you can do so here or in a config file. @@ -93,7 +93,7 @@ jobs: ./.github/workflows/codeql-buildscript.sh - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v2 + uses: github/codeql-action/analyze@v3 with: category: "/language:${{matrix.language}}" upload: false @@ -124,12 +124,12 @@ jobs: output: ${{ steps.step1.outputs.sarif-output }}/cpp.sarif - name: Upload SARIF - uses: github/codeql-action/upload-sarif@v2 + uses: github/codeql-action/upload-sarif@v3 with: sarif_file: ${{ steps.step1.outputs.sarif-output }} category: "/language:${{matrix.language}}" - - name: Archive CodeQL results + - name: Upload CodeQL results as an artifact uses: actions/upload-artifact@v4 with: name: codeql-results diff --git a/.github/workflows/hil_test.yml b/.github/workflows/hil_test.yml deleted file mode 100644 index c6e7f33b0..000000000 --- a/.github/workflows/hil_test.yml +++ /dev/null @@ -1,88 +0,0 @@ -name: Hardware Test - -on: - workflow_dispatch: - pull_request: - branches: [ master ] - paths: - - 'src/**' - - 'examples/**' - - 'lib/**' - - 'hw/**' - - 'test/hil/**' - - 'tools/get_deps.py' - - '.github/actions/**' - - '.github/workflows/hil_test.yml' -concurrency: - group: ${{ github.workflow }}-${{ github.ref }} - cancel-in-progress: true - -env: - HIL_JSON: test/hil/tinyusb.json - -jobs: - set-matrix: - runs-on: ubuntu-latest - outputs: - json: ${{ steps.set-matrix-json.outputs.matrix }} - steps: - - name: Checkout TinyUSB - uses: actions/checkout@v4 - - - name: Generate matrix json - id: set-matrix-json - run: | - MATRIX_JSON=$(python test/hil/hil_ci_set_matrix.py ${{ env.HIL_JSON }}) - echo "matrix=$MATRIX_JSON" - echo "matrix=$MATRIX_JSON" >> $GITHUB_OUTPUT - - # --------------------------------------- - # Build arm-gcc - # --------------------------------------- - build: - if: github.repository_owner == 'hathach' - needs: set-matrix - uses: ./.github/workflows/build_util.yml - strategy: - fail-fast: false - matrix: - toolchain: - - 'arm-gcc' - - 'esp-idf' - with: - build-system: 'cmake' - toolchain: ${{ matrix.toolchain }} - build-args: ${{ toJSON(fromJSON(needs.set-matrix.outputs.json)[matrix.toolchain]) }} - one-per-family: true - upload-artifacts: true - - # --------------------------------------- - # Hardware in the loop (HIL) - # self-hosted running on an VM. For attached hardware checkout HIL_JSON - # --------------------------------------- - hil-tinyusb: - if: github.repository_owner == 'hathach' - needs: build - runs-on: [self-hosted, X64, hathach, hardware-in-the-loop] - steps: - - name: Clean workspace - run: | - echo "Cleaning up previous run" - rm -rf "${{ github.workspace }}" - mkdir -p "${{ github.workspace }}" - - - name: Checkout TinyUSB - uses: actions/checkout@v4 - with: - sparse-checkout: test/hil - - - name: Download Artifacts - uses: actions/download-artifact@v4 - with: - path: cmake-build - merge-multiple: true - - - name: Test on actual hardware - run: | - ls cmake-build/ - python3 test/hil/hil_test.py ${{ env.HIL_JSON }} diff --git a/.github/workflows/pre-commit.yml b/.github/workflows/pre-commit.yml index 530484079..ed0efd66e 100644 --- a/.github/workflows/pre-commit.yml +++ b/.github/workflows/pre-commit.yml @@ -33,6 +33,8 @@ jobs: - name: Build Fuzzer run: | + sudo apt install libc++-dev libc++abi-dev + clang --version export CC=clang export CXX=clang++ fuzz_harness=$(ls -d test/fuzz/device/*/) diff --git a/.gitignore b/.gitignore index 309d7466a..5638a09db 100644 --- a/.gitignore +++ b/.gitignore @@ -1,16 +1,28 @@ html latex +*.a *.d *.o *.P -*.map *.axf *.bin +*.elf +*.env +*.ind +*.log +*.map +*.obj *.jlink *.emSession -*.elf -*.ind -.env +*.ninja* +*.eww +*.ewp +*.ewt +*.ewd +*.hex +cmake_install.cmake +CMakeCache.txt +settings/ .settings/ .vscode/ .gdb_history @@ -33,4 +45,10 @@ cmake-build-* sdkconfig .PVS-Studio .vscode/ -build/ +build +CMakeFiles +Debug +RelWithDebInfo +Release +BrowseInfo +.cmake_build diff --git a/.idea/cmake.xml b/.idea/cmake.xml index 25a8513ca..dd219bc77 100644 --- a/.idea/cmake.xml +++ b/.idea/cmake.xml @@ -6,12 +6,14 @@ - - + + + + @@ -81,16 +83,19 @@ + - + + - + + @@ -118,10 +123,13 @@ + - - + + + + @@ -159,7 +167,6 @@ - \ No newline at end of file diff --git a/.idea/debugServers/esp32s2.xml b/.idea/debugServers/esp32s2.xml new file mode 100644 index 000000000..6a4aff3da --- /dev/null +++ b/.idea/debugServers/esp32s2.xml @@ -0,0 +1,14 @@ + + + + $USER_HOME$/.espressif/tools/xtensa-esp-elf-gdb/14.2_20240403/xtensa-esp-elf-gdb/bin/xtensa-esp32s2-elf-gdb + + + + + + + + + + \ No newline at end of file diff --git a/.idea/debugServers/rp2040.xml b/.idea/debugServers/rp2040.xml new file mode 100644 index 000000000..f451611f3 --- /dev/null +++ b/.idea/debugServers/rp2040.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/debugServers/rp2350.xml b/.idea/debugServers/rp2350.xml new file mode 100644 index 000000000..52243a297 --- /dev/null +++ b/.idea/debugServers/rp2350.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/debugServers/rt1060.xml b/.idea/debugServers/rt1060.xml new file mode 100644 index 000000000..cbd295b4e --- /dev/null +++ b/.idea/debugServers/rt1060.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/debugServers/rt1064.xml b/.idea/debugServers/rt1064.xml new file mode 100644 index 000000000..4fb2fdf6a --- /dev/null +++ b/.idea/debugServers/rt1064.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/debugServers/sam21.xml b/.idea/debugServers/sam21.xml new file mode 100644 index 000000000..3f6735bd1 --- /dev/null +++ b/.idea/debugServers/sam21.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/debugServers/sam51.xml b/.idea/debugServers/sam51.xml new file mode 100644 index 000000000..99a92c174 --- /dev/null +++ b/.idea/debugServers/sam51.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/debugServers/stm32f769.xml b/.idea/debugServers/stm32f769.xml new file mode 100644 index 000000000..22a452218 --- /dev/null +++ b/.idea/debugServers/stm32f769.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/debugServers/stm32h563.xml b/.idea/debugServers/stm32h563.xml new file mode 100644 index 000000000..637839314 --- /dev/null +++ b/.idea/debugServers/stm32h563.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/debugServers/stm32h743.xml b/.idea/debugServers/stm32h743.xml new file mode 100644 index 000000000..b04e4a708 --- /dev/null +++ b/.idea/debugServers/stm32h743.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/runConfigurations/stlink.xml b/.idea/runConfigurations/stlink.xml index 2d94e66d6..e84445add 100644 --- a/.idea/runConfigurations/stlink.xml +++ b/.idea/runConfigurations/stlink.xml @@ -1,6 +1,6 @@ - - + + diff --git a/.idea/vcs.xml b/.idea/vcs.xml index 94a25f7f4..d44b5516f 100644 --- a/.idea/vcs.xml +++ b/.idea/vcs.xml @@ -2,5 +2,6 @@ + \ No newline at end of file diff --git a/CONTRIBUTORS.rst b/CONTRIBUTORS.rst index 085f8082a..451ac0783 100644 --- a/CONTRIBUTORS.rst +++ b/CONTRIBUTORS.rst @@ -31,6 +31,13 @@ Notable contributors - Most features development +`Heiko Kuester `__ +-------------------------------------------- + +- Add CH34x and PL2303 support (CDC host) +- Improve FTDI and CP210x support (CDC host) + + `Hristo Gochkov `__ ------------------------------------------------- diff --git a/README.rst b/README.rst index db36cad3b..b873bc42b 100644 --- a/README.rst +++ b/README.rst @@ -15,10 +15,7 @@ TinyUSB Project .. figure:: docs/assets/logo.svg :alt: TinyUSB -TinyUSB is an open-source cross-platform USB Host/Device stack for -embedded system, designed to be memory-safe with no dynamic allocation -and thread-safe with all interrupt events are deferred then handled in -the non-ISR task function. Check out the online `documentation `__ for more details. +TinyUSB is an open-source cross-platform USB Host/Device stack for embedded system, designed to be memory-safe with no dynamic allocation and thread-safe with all interrupt events are deferred then handled in the non-ISR task function. Check out the online `documentation `__ for more details. .. figure:: docs/assets/stack.svg :width: 500px @@ -32,7 +29,7 @@ the non-ISR task function. Check out the online `documentation `_ for information about using TinyUSB and how it is implemented. +Check out `Getting Started`_ guide for adding TinyUSB to your project or building the examples. If you are new to TinyUSB, we recommend starting with the ``cdc_msc`` example. There is a handful of `Supported Boards`_ that should work out of the box. + We use `GitHub Discussions `_ as our forum. It is a great place to ask questions and advice from the community or to discuss your TinyUSB-based projects. For bugs and feature requests, please `raise an issue `_ and follow the templates there. -Check out `Getting Started`_ guide for adding TinyUSB to your project or building the examples. If you are new to TinyUSB, we recommend starting with the `cdc_msc` example. - See `Porting`_ guide for adding support for new MCUs and boards. Device Stack @@ -69,7 +66,7 @@ Supports multiple device configurations by dynamically changing USB descriptors, - Vendor-specific class support with generic In & Out endpoints. Can be used with MS OS 2.0 compatible descriptor to load winUSB driver without INF file. - `WebUSB `__ with vendor-specific class -If you have a special requirement, `usbd_app_driver_get_cb()` can be used to write your own class driver without modifying the stack. Here is how the RPi team added their reset interface `raspberrypi/pico-sdk#197 `_ +If you have a special requirement, ``usbd_app_driver_get_cb()`` can be used to write your own class driver without modifying the stack. Here is how the RPi team added their reset interface `raspberrypi/pico-sdk#197 `_ Host Stack ========== @@ -77,13 +74,13 @@ Host Stack - Human Interface Device (HID): Keyboard, Mouse, Generic - Mass Storage Class (MSC) - Communication Device Class: CDC-ACM -- Vendor serial over USB: FTDI, CP210x, CH34x +- Vendor serial over USB: FTDI, CP210x, CH34x, PL2303 - Hub with multiple-level support -Similar to the Device Stack, if you have a special requirement, `usbh_app_driver_get_cb()` can be used to write your own class driver without modifying the stack. +Similar to the Device Stack, if you have a special requirement, ``usbh_app_driver_get_cb()`` can be used to write your own class driver without modifying the stack. -TypeC PD Stack -============== +Power Delivery Stack +==================== - Power Delivery 3.0 (PD3.0) with USB Type-C support (WIP) - Super early stage, only for testing purpose @@ -102,100 +99,139 @@ TinyUSB is completely thread-safe by pushing all Interrupt Service Request (ISR) Supported CPUs ============== -Following CPUs are supported, check out `Supported Devices`_ for comprehensive list of driver, features for each CPU. ++--------------+-----------------------------+--------+------+-----------+------------------------+-------------------+ +| Manufacturer | Family | Device | Host | Highspeed | Driver | Note | ++==============+=============================+========+======+===========+========================+===================+ +| Allwinner | F1C100s/F1C200s | ✔ | | ✔ | sunxi | musb variant | ++--------------+-----------------------------+--------+------+-----------+------------------------+-------------------+ +| Analog | MAX3421E | | ✔ | ✖ | max3421 | via SPI | +| +-----------------------------+--------+------+-----------+------------------------+-------------------+ +| | MAX32 650, 666, 690, | ✔ | | ✔ | musb | 1-dir ep | +| | MAX78002 | | | | | | ++--------------+-----------------------------+--------+------+-----------+------------------------+-------------------+ +| Brigetek | FT90x | ✔ | | ✔ | ft9xx | 1-dir ep | ++--------------+-----------------------------+--------+------+-----------+------------------------+-------------------+ +| Broadcom | BCM2711, BCM2837 | ✔ | | ✔ | dwc2 | | ++--------------+-----------------------------+--------+------+-----------+------------------------+-------------------+ +| Dialog | DA1469x | ✔ | ✖ | ✖ | da146xx | | ++--------------+-----------------------------+--------+------+-----------+------------------------+-------------------+ +| Espressif | S2, S3 | ✔ | ✔ | ✖ | dwc2 or esp32sx | | +| ESP32 +-----------------------------+--------+------+-----------+------------------------+-------------------+ +| | P4 | ✔ | ✔ | ✔ | dwc2 | | ++--------------+----+------------------------+--------+------+-----------+------------------------+-------------------+ +| GigaDevice | GD32VF103 | ✔ | | ✖ | dwc2 | | ++--------------+-----------------------------+--------+------+-----------+------------------------+-------------------+ +| Infineon | XMC4500 | ✔ | ✔ | ✖ | dwc2 | | ++--------------+-----+-----------------------+--------+------+-----------+------------------------+-------------------+ +| MicroChip | SAM | D11, D21, L21, L22 | ✔ | | ✖ | samd | | +| | +-----------------------+--------+------+-----------+------------------------+-------------------+ +| | | D51, E5x | ✔ | | ✖ | samd | | +| | +-----------------------+--------+------+-----------+------------------------+-------------------+ +| | | G55 | ✔ | | ✖ | samg | 1-dir ep | +| | +-----------------------+--------+------+-----------+------------------------+-------------------+ +| | | E70,S70,V70,V71 | ✔ | | ✔ | samx7x | 1-dir ep | +| +-----+-----------------------+--------+------+-----------+------------------------+-------------------+ +| | PIC | 24 | ✔ | | | pic | ci_fs variant | +| | +-----------------------+--------+------+-----------+------------------------+-------------------+ +| | | 32 mm, mk, mx | ✔ | | | pic | ci_fs variant | +| | +-----------------------+--------+------+-----------+------------------------+-------------------+ +| | | dsPIC33 | ✔ | | | pic | ci_fs variant | +| | +-----------------------+--------+------+-----------+------------------------+-------------------+ +| | | 32mz | ✔ | | | pic32mz | musb variant | ++--------------+-----+-----------------------+--------+------+-----------+------------------------+-------------------+ +| Mind Montion | mm32 | ✔ | | ✖ | mm32f327x_otg | ci_fs variant | ++--------------+-----+-----------------------+--------+------+-----------+------------------------+-------------------+ +| NordicSemi | nRF 52833, 52840, 5340 | ✔ | ✖ | ✖ | nrf5x | only ep8 is ISO | ++--------------+-----------------------------+--------+------+-----------+------------------------+-------------------+ +| Nuvoton | NUC120 | ✔ | ✖ | ✖ | nuc120 | | +| +-----------------------------+--------+------+-----------+------------------------+-------------------+ +| | NUC121/NUC125 | ✔ | ✖ | ✖ | nuc121 | | +| +-----------------------------+--------+------+-----------+------------------------+-------------------+ +| | NUC126 | ✔ | ✖ | ✖ | nuc121 | | +| +-----------------------------+--------+------+-----------+------------------------+-------------------+ +| | NUC505 | ✔ | | ✔ | nuc505 | | ++--------------+---------+-------------------+--------+------+-----------+------------------------+-------------------+ +| NXP | iMXRT | RT 10xx, 11xx | ✔ | ✔ | ✔ | ci_hs | | +| +---------+-------------------+--------+------+-----------+------------------------+-------------------+ +| | Kinetis | KL | ✔ | ⚠ | ✖ | ci_fs, khci | | +| | +-------------------+--------+------+-----------+------------------------+-------------------+ +| | | K32L2 | ✔ | | ✖ | khci | ci_fs variant | +| +---------+-------------------+--------+------+-----------+------------------------+-------------------+ +| | LPC | 11u, 13, 15 | ✔ | ✖ | ✖ | lpc_ip3511 | | +| | +-------------------+--------+------+-----------+------------------------+-------------------+ +| | | 17, 40 | ✔ | ⚠ | ✖ | lpc17_40 | | +| | +-------------------+--------+------+-----------+------------------------+-------------------+ +| | | 18, 43 | ✔ | ✔ | ✔ | ci_hs | | +| | +-------------------+--------+------+-----------+------------------------+-------------------+ +| | | 51u | ✔ | ✖ | ✖ | lpc_ip3511 | | +| | +-------------------+--------+------+-----------+------------------------+-------------------+ +| | | 54, 55 | ✔ | | ✔ | lpc_ip3511 | | +| +---------+-------------------+--------+------+-----------+------------------------+-------------------+ +| | MCX | N9 | ✔ | | ✔ | ci_fs, ci_hs | | +| | +-------------------+--------+------+-----------+------------------------+-------------------+ +| | | A15 | ✔ | | | ci_fs | | ++--------------+---------+-------------------+--------+------+-----------+------------------------+-------------------+ +| Raspberry Pi | RP2040, RP2350 | ✔ | ✔ | ✖ | rp2040, pio_usb | | ++--------------+-----+-----------------------+--------+------+-----------+------------------------+-------------------+ +| Renesas | RX | 63N, 65N, 72N | ✔ | ✔ | ✖ | rusb2 | | +| +-----+-----------------------+--------+------+-----------+------------------------+-------------------+ +| | RA | 4M1, 4M3, 6M1 | ✔ | ✔ | ✖ | rusb2 | | +| | +-----------------------+--------+------+-----------+------------------------+-------------------+ +| | | 6M5 | ✔ | ✔ | ✔ | rusb2 | | ++--------------+-----+-----------------------+--------+------+-----------+------------------------+-------------------+ +| Silabs | EFM32GG12 | ✔ | | ✖ | dwc2 | | ++--------------+-----------------------------+--------+------+-----------+------------------------+-------------------+ +| Sony | CXD56 | ✔ | ✖ | ✔ | cxd56 | | ++--------------+-----------------------------+--------+------+-----------+------------------------+-------------------+ +| ST STM32 | F0, F3, L0, L1, L5, WBx5 | ✔ | ✖ | ✖ | stm32_fsdev | | +| +----+------------------------+--------+------+-----------+------------------------+-------------------+ +| | F1 | 102, 103 | ✔ | ✖ | ✖ | stm32_fsdev | | +| | +------------------------+--------+------+-----------+------------------------+-------------------+ +| | | 105, 107 | ✔ | ✔ | ✖ | dwc2 | | +| +----+------------------------+--------+------+-----------+------------------------+-------------------+ +| | F2, F4, F7, H7, H7RS | ✔ | ✔ | ✔ | dwc2 | | +| +-----------------------------+--------+------+-----------+------------------------+-------------------+ +| | C0, G0, H5 | ✔ | | ✖ | stm32_fsdev | | +| +-----------------------------+--------+------+-----------+------------------------+-------------------+ +| | G4 | ✔ | ✖ | ✖ | stm32_fsdev | | +| +-----------------------------+--------+------+-----------+------------------------+-------------------+ +| | L0, L1 | ✔ | ✖ | ✖ | stm32_fsdev | | +| +----+------------------------+--------+------+-----------+------------------------+-------------------+ +| | L4 | 4x2, 4x3 | ✔ | ✖ | ✖ | stm32_fsdev | | +| | +------------------------+--------+------+-----------+------------------------+-------------------+ +| | | 4x5, 4x6, 4+ | ✔ | ✔ | ✖ | dwc2 | | +| +----+------------------------+--------+------+-----------+------------------------+-------------------+ +| | N6 | ✔ | ✔ | ✔ | dwc2 | | +| +----+------------------------+--------+------+-----------+------------------------+-------------------+ +| | U5 | 535, 545 | ✔ | | ✖ | stm32_fsdev | | +| | +------------------------+--------+------+-----------+------------------------+-------------------+ +| | | 575, 585 | ✔ | ✔ | ✖ | dwc2 | | +| | +------------------------+--------+------+-----------+------------------------+-------------------+ +| | | 59x,5Ax,5Fx,5Gx | ✔ | ✔ | ✔ | dwc2 | | ++--------------+----+------------------------+--------+------+-----------+------------------------+-------------------+ +| TI | MSP430 | ✔ | ✖ | ✖ | msp430x5xx | | +| +-----------------------------+--------+------+-----------+------------------------+-------------------+ +| | MSP432E4, TM4C123 | ✔ | | ✖ | musb | | ++--------------+-----------------------------+--------+------+-----------+------------------------+-------------------+ +| ValentyUSB | eptri | ✔ | ✖ | ✖ | eptri | | ++--------------+-----------------------------+--------+------+-----------+------------------------+-------------------+ +| WCH | CH32F20x | ✔ | | ✔ | ch32_usbhs | | +| +-----------------------------+--------+------+-----------+------------------------+-------------------+ +| | CH32V20x | ✔ | | ✖ | stm32_fsdev/ch32_usbfs | | +| +-----------------------------+--------+------+-----------+------------------------+-------------------+ +| | CH32V307 | ✔ | | ✔ | ch32_usbfs/hs | | ++--------------+-----------------------------+--------+------+-----------+------------------------+-------------------+ -+--------------+------------------------------------------------------------+ -| Manufacturer | Family | -+==============+============================================================+ -| Allwinner | F1C100s/F1C200s | -+--------------+------------------------------------------------------------+ -| Analog | max32: 650, 666, 690. max78002 | -| | | -| | max3421e (spi host) | -+--------------+------------------------------------------------------------+ -| Brigetek | FT90x | -+--------------+------------------------------------------------------------+ -| Broadcom | BCM2711, BCM2837 | -+--------------+------------------------------------------------------------+ -| Dialog | DA1469x | -+--------------+------------------------------------------------------------+ -| Espressif | ESP32 S2, S3 | -+--------------+------------------------------------------------------------+ -| GigaDevice | GD32VF103 | -+--------------+------------------------------------------------------------+ -| Infineon | XMC4500 | -+--------------+------------------------------------------------------------+ -| | SAM: D11, D21, D51, E5x, G55, L2x, E7x, S7x, V7x | -| MicroChip | | -| | PIC: 24, 32mm, 32mk, 32mx, 32mz, dsPIC33 | -+--------------+------------------------------------------------------------+ -| Mind Montion | mm32 | -+--------------+------------------------------------------------------------+ -| NordicSemi | nRF52833, nRF52840, nRF5340 | -+--------------+------------------------------------------------------------+ -| Nuvoton | NUC 120, 121, 125, 126, 505 | -+--------------+------------------------------------------------------------+ -| NXP | iMXRT: RT10xx, RT11xx | -| | | -| | Kinetis: KL, K32L2 | -| | | -| | LPC: 11u, 13, 15, 17, 18, 40, 43, 51u, 54, 55 | -| | | -| | MCX: A15, N9 | -+--------------+------------------------------------------------------------+ -| Raspberry Pi | RP2040, RP2350 | -+--------------+-----+------------------------------------------------------+ -| Renesas | RA: 4M1, 4M3, 6M1, 6M5 | -| | | -| | RX: 63N, 65N, 72N | -+--------------+-----+------------------------------------------------------+ -| Silabs | EFM32GG12 | -+--------------+------------------------------------------------------------+ -| Sony | CXD56 | -+--------------+------------------------------------------------------------+ -| ST STM32 | C0, F0, F1, F2, F3, F4, F7, G0, G4, H5, H7, | -| | | -| | L0, L1, L4, L4+, L5, U5, WB | -+--------------+------------------------------------------------------------+ -| TI | MSP430, MSP432E4, TM4C123 | -+--------------+------------------------------------------------------------+ -| ValentyUSB | eptri | -+--------------+------------------------------------------------------------+ -| WCH | CH32F: F20x | -| | | -| | CH32V: V20x, V307 | -+--------------+------------------------------------------------------------+ +Table Legend +------------ -License -======= +========= ========================= +✔ Supported +⚠ Partial support +✖ Not supported by hardware +\[empty\] Unknown +========= ========================= -All TinyUSB sources in the ``src`` folder are licensed under MIT -license, the `Full license is here `__. However, each file can be -individually licensed especially those in ``lib`` and ``hw/mcu`` folder. -Please make sure you understand all the license term for files you use -in your project. - -Docs -==== - -- Info - - - `Uses`_ - - `Changelog`_ - - `Contributors`_ - -- `Reference`_ - - - `Supported Devices`_ - - `Getting Started`_ - - `Dependencies`_ - - `Concurrency`_ - -- `Contributing`_ - - - `Code of Conduct`_ - - `Structure`_ - - `Porting`_ .. |Build Status| image:: https://github.com/hathach/tinyusb/actions/workflows/build.yml/badge.svg :target: https://github.com/hathach/tinyusb/actions @@ -209,15 +245,12 @@ Docs :target: https://opensource.org/licenses/MIT -.. _Uses: docs/info/uses.rst .. _Changelog: docs/info/changelog.rst .. _Contributors: CONTRIBUTORS.rst -.. _Reference: docs/reference/index.rst -.. _Supported Devices: docs/reference/supported.rst .. _Getting Started: docs/reference/getting_started.rst +.. _Supported Boards: docs/reference/boards.rst .. _Dependencies: docs/reference/dependencies.rst .. _Concurrency: docs/reference/concurrency.rst .. _Contributing: docs/contributing/index.rst .. _Code of Conduct: CODE_OF_CONDUCT.rst -.. _Structure: docs/contributing/structure.rst .. _Porting: docs/contributing/porting.rst diff --git a/docs/conf.py b/docs/conf.py index af44b7339..4249d41f7 100755 --- a/docs/conf.py +++ b/docs/conf.py @@ -5,13 +5,16 @@ # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html +import re +from pathlib import Path + # -- Path setup -------------------------------------------------------------- # -- Project information ----------------------------------------------------- project = 'TinyUSB' -copyright = '2021, Ha Thach' +copyright = '2024, Ha Thach' author = 'Ha Thach' @@ -40,3 +43,16 @@ html_theme_options = { } todo_include_todos = True + +# pre-process path in README.rst +def preprocess_readme(): + """Modify figure paths in README.rst for Sphinx builds.""" + src = Path(__file__).parent.parent / "README.rst" + tgt = Path(__file__).parent.parent / "README_processed.rst" + if src.exists(): + content = src.read_text() + content = re.sub(r"docs/", r"", content) + content = re.sub(r".rst", r".html", content) + tgt.write_text(content) + +preprocess_readme() diff --git a/docs/contributing/code_of_conduct.rst b/docs/contributing/code_of_conduct.rst deleted file mode 120000 index b52bf14c5..000000000 --- a/docs/contributing/code_of_conduct.rst +++ /dev/null @@ -1 +0,0 @@ -../../CODE_OF_CONDUCT.rst \ No newline at end of file diff --git a/docs/contributing/code_of_conduct.rst b/docs/contributing/code_of_conduct.rst new file mode 100644 index 000000000..fb1859c75 --- /dev/null +++ b/docs/contributing/code_of_conduct.rst @@ -0,0 +1 @@ +.. include:: ../../CODE_OF_CONDUCT.rst \ No newline at end of file diff --git a/docs/contributing/index.rst b/docs/contributing/index.rst index 7ff79cb32..78933a3ca 100644 --- a/docs/contributing/index.rst +++ b/docs/contributing/index.rst @@ -19,5 +19,4 @@ Index :maxdepth: 2 code_of_conduct - structure porting diff --git a/docs/contributing/porting.rst b/docs/contributing/porting.rst index f81d98782..c3076354c 100644 --- a/docs/contributing/porting.rst +++ b/docs/contributing/porting.rst @@ -9,7 +9,7 @@ data transactions on different endpoints. Porting is the process of adding low-l the rest of the common stack. Once the low-level is implemented, it is very easy to add USB support for the microcontroller to other projects, especially those already using TinyUSB such as CircuitPython. -Below are instructions on how to get the cdc_msc device example running on a new microcontroller. Doing so includes adding the common code necessary for other uses while minimizing other extra code. Whenever you see a phrase or word in <> it should be replaced. +Below are instructions on how to get the cdc_msc device example running on a new microcontroller. Doing so includes adding the common code necessary for other uses while minimizing other extra code. Whenever you see a phrase or word in ``<>`` it should be replaced. Register defs ------------- @@ -18,25 +18,27 @@ The first step to adding support is including the register definitions and start microcontroller in TinyUSB. We write the TinyUSB implementation against these structs instead of higher level functions to keep the code small and to prevent function name collisions in linking of larger projects. For ARM microcontrollers this is the CMSIS definitions. They should be placed in the ``hw/mcu//`` directory. -Once this is done, create a directory in ``hw/bsp/`` for the specific board you are using to test the code. (Duplicating an existing board's directory is the best way to get started.) The board should be a readily available development board so that others can also test. +Once this is done, create a directory in ``hw/bsp/`` for the specific board you are using to test the code (duplicating an existing board's directory is the best way to get started). The board should be a readily available development board so that others can also test. Build ----- Now that those directories are in place, we can start our iteration process to get the example building successfully. To build, run from the root of TinyUSB: -``make -C examples/device/cdc_msc BOARD=`` +.. code-block:: bash -Unless, you've read ahead, this will fail miserably. Now, lets get it to fail less by updating the files in the board directory. The code in the board's directory is responsible for setting up the microcontroller's clocks and pins so that USB works. TinyUSB itself only operates on the USB peripheral. The board directory also includes information what files are needed to build the example. + make -C examples/device/cdc_msc BOARD= -One of the first things to change is the ``-DCFG_TUSB_MCU`` cflag in the ``board.mk`` file. This is used to tell TinyUSB what platform is being built. So, add an entry to ``src/tusb_option.h`` and update the CFLAG to match. +Unless you've read ahead, this will fail miserably. Now, lets get it to fail less by updating the files in the board directory. The code in the board's directory is responsible for setting up the microcontroller's clocks and pins so that USB works. TinyUSB itself only operates on the USB peripheral. The board directory also includes information what files are needed to build the example. -Update ``board.mk``\ 's VENDOR and CHIP_FAMILY values when creating the directory for the struct files. Duplicate one of the other sources from ``src/portable`` into ``src/portable//`` and delete all of the implementation internals. We'll cover what everything there does later. For now, get it compiling. +One of the first things to change is the ``-DCFG_TUSB_MCU`` C flag in the ``board.mk`` file. This is used to tell TinyUSB what platform is being built. So, add an entry to ``src/tusb_option.h`` and update the ``CFLAGS`` to match. + +Update ``board.mk``'s VENDOR and CHIP_FAMILY values when creating the directory for the struct files. Duplicate one of the other sources from ``src/portable`` into ``src/portable//`` and delete all of the implementation internals. We'll cover what everything there does later. For now, get it compiling. Implementation -------------- -At this point you should get an error due to an implementation issue and hopefully the build is setup for the new MCU. You will still need to modify the ``board.mk`` to include specific CFLAGS, the linker script, linker flags, source files, include directories. All file paths are relative to the top of the TinyUSB repo. +At this point you should get an error due to an implementation issue and hopefully the build is setup for the new MCU. You will still need to modify the ``board.mk`` to include specific ``CFLAGS``, the linker script, linker flags, source files, include directories. All file paths are relative to the top of the TinyUSB repo. Board Support (BSP) ^^^^^^^^^^^^^^^^^^^ @@ -45,17 +47,17 @@ The board support code is only used for self-contained examples and testing. It It is located in ``hw/bsp//board_.c``. -board_init -~~~~~~~~~~ +``board_init()`` +~~~~~~~~~~~~~~~~ -``board_init`` is responsible for starting the MCU, setting up the USB clock and USB pins. It is also responsible for initializing LED pins. +``board_init()`` is responsible for starting the MCU, setting up the USB clock and USB pins. It is also responsible for initializing LED pins. One useful clock debugging technique is to set up a PWM output at a known value such as 500hz based on the USB clock so that you can verify it is correct with a logic probe or oscilloscope. Setup your USB in a crystal-less mode when available. That makes the code easier to port across boards. -board_led_write -~~~~~~~~~~~~~~~ +``board_led_write()`` +~~~~~~~~~~~~~~~~~~~~~ Feel free to skip this until you want to verify your demo code is running. To implement, set the pin corresponding to the led to output a value that lights the LED when ``state`` is true. @@ -64,48 +66,48 @@ OS Abstraction Layer (OSAL) The OS Abstraction Layer is responsible for providing basic data structures for TinyUSB that may allow for concurrency when used with an RTOS. Without an RTOS it simply handles concurrency issues between the main code and interrupts. The code is almost entirely agnostic of MCU and lives in ``src/osal``. -In RTOS configurations, tud_task()/tuh_task() blocks behind a synchronization structure when the event queue is empty, so that the scheduler may give the CPU to a different task. To take advantage of the library's capability to yield the CPU when there are no actionable USB device events, ensure that the `CFG_TUSB_OS` symbol is defined, e.g `OPT_OS_FREERTOS` enables the FreeRTOS scheduler to schedule other threads than that which calls `tud_task()/tuh_task()`. +In RTOS configurations, ``tud_task()``/``tuh_task()`` blocks behind a synchronization structure when the event queue is empty, so that the scheduler may give the CPU to a different task. To take advantage of the library's capability to yield the CPU when there are no actionable USB device events, ensure that the ``CFG_TUSB_OS`` symbol is defined, e.g ``OPT_OS_FREERTOS`` enables the FreeRTOS scheduler to schedule other threads than that which calls ``tud_task()``/``tuh_task()``. Device API ^^^^^^^^^^ -After the USB device is setup, the USB device code works by processing events on the main thread (by calling ``tud_task``\ ). These events are queued by the USB interrupt handler. So, there are three parts to the device low-level API: device setup, endpoint setup and interrupt processing. +After the USB device is setup, the USB device code works by processing events on the main thread (by calling ``tud_task()``). These events are queued by the USB interrupt handler. So, there are three parts to the device low-level API: device setup, endpoint setup and interrupt processing. All of the code for the low-level device API is in ``src/portable///dcd_.c``. Device Setup ~~~~~~~~~~~~ -dcd_init -"""""""" +``dcd_init()`` +"""""""""""""" Initializes the USB peripheral for device mode and enables it. This function should enable internal D+/D- pull-up for enumeration. -dcd_int_enable / dcd_int_disable -"""""""""""""""""""""""""""""""" +``dcd_int_enable()`` / ``dcd_int_disable()`` +"""""""""""""""""""""""""""""""""""""""""""" Enables or disables the USB device interrupt(s). May be used to prevent concurrency issues when mutating data structures shared between main code and the interrupt handler. -dcd_int_handler -""""""""""""""" +``dcd_int_handler()`` +""""""""""""""""""""" Processes all the hardware generated events e.g Bus reset, new data packet from host etc ... It will be called by application in the MCU USB interrupt handler. -dcd_set_address -""""""""""""""" +``dcd_set_address()`` +""""""""""""""""""""" Called when the device is given a new bus address. If your peripheral automatically changes address during enumeration (like the nrf52) you may leave this empty and also no queue an event for the corresponding SETUP packet. -dcd_remote_wakeup -""""""""""""""""" +``dcd_remote_wakeup()`` +""""""""""""""""""""""" Called to remote wake up host when suspended (e.g hid keyboard) -dcd_connect / dcd_disconnect -"""""""""""""""""""""""""""" +``dcd_connect()`` / ``dcd_disconnect()`` +"""""""""""""""""""""""""""""""""""""""" Connect or disconnect the data-line pull-up resistor. Define only if MCU has an internal pull-up. (BSP may define for MCU without internal pull-up.) @@ -114,8 +116,8 @@ Special events You must let TinyUSB know when certain events occur so that it can continue its work. There are a few methods you can call to queue events for TinyUSB to process. -dcd_event_bus_signal -"""""""""""""""""""" +``dcd_event_bus_signal()`` +"""""""""""""""""""""""""" There are a number of events that your peripheral may communicate about the state of the bus. Here is an overview of what they are. Events in **BOLD** must be provided for TinyUSB to work. @@ -125,51 +127,51 @@ There are a number of events that your peripheral may communicate about the stat Calls to this look like: -.. code-block:: +.. code-block:: c dcd_event_bus_signal(0, DCD_EVENT_BUS_RESET, true); -The first ``0`` is the USB peripheral number. Statically saying 0 is common for single USB device MCUs. +The first ``0`` is the USB peripheral number. Statically saying ``0`` is common for single USB device MCUs. The ``true`` indicates the call is from an interrupt handler and will always be the case when porting in this way. -dcd_setup_received -"""""""""""""""""" +``dcd_setup_received()`` +"""""""""""""""""""""""" SETUP packets are a special type of transaction that can occur at any time on the control endpoint, numbered ``0``. Since they are unique, most peripherals have special handling for them. Their data is always 8 bytes in length as well. Calls to this look like: -.. code-block:: +.. code-block:: c dcd_event_setup_received(0, setup, true); -As before with ``dcd_event_bus_signal`` the first argument is the USB peripheral number and the third is true to signal its being called from an interrupt handler. The middle argument is byte array of length 8 with the contents of the SETUP packet. It can be stack allocated because it is copied into the queue. +As before with ``dcd_event_bus_signal()`` the first argument is the USB peripheral number and the third is true to signal its being called from an interrupt handler. The middle argument is byte array of length 8 with the contents of the SETUP packet. It can be stack allocated because it is copied into the queue. Endpoints ~~~~~~~~~ Endpoints are the core of the USB data transfer process. They come in a few forms such as control, isochronous, bulk, and interrupt. We won't cover the details here except with some caveats in open below. In general, data is transferred by setting up a buffer of a given length to be transferred on a given endpoint address and then waiting for an interrupt to signal that the transfer is finished. Further details below. -Endpoints within USB have an address which encodes both the number and direction of an endpoint. TinyUSB provides ``tu_edpt_number`` and ``tu_edpt_dir`` to unpack this data from the address. Here is a snippet that does it. +Endpoints within USB have an address which encodes both the number and direction of an endpoint. TinyUSB provides ``tu_edpt_number()`` and ``tu_edpt_dir()`` to unpack this data from the address. Here is a snippet that does it. -.. code-block:: +.. code-block:: c uint8_t epnum = tu_edpt_number(ep_addr); uint8_t dir = tu_edpt_dir(ep_addr); -dcd_edpt_open -""""""""""""" +``dcd_edpt_open()`` +""""""""""""""""""" Opening an endpoint is done for all non-control endpoints once the host picks a configuration that the device should use. At this point, the endpoint should be enabled in the peripheral and configured to match the endpoint descriptor. Pay special attention to the direction of the endpoint you can get from the helper methods above. It will likely change what registers you are setting. Also make sure to enable endpoint specific interrupts. -dcd_edpt_close -"""""""""""""" +``dcd_edpt_close()`` +"""""""""""""""""""" Close an endpoint. his function is used for implementing alternate settings. @@ -177,10 +179,10 @@ After calling this, the device should not respond to any packets directed toward Implementation is optional. Must be called from the USB task. Interrupts could be disabled or enabled during the call. -dcd_edpt_xfer -""""""""""""" +``dcd_edpt_xfer()`` +""""""""""""""""""" -``dcd_edpt_xfer`` is responsible for configuring the peripheral to send or receive data from the host. "xfer" is short for "transfer". **This is one of the core methods you must implement for TinyUSB to work (one other is the interrupt handler).** Data from the host is the OUT direction and data to the host is IN. It is used for all endpoints including the control endpoint 0. Make sure to handle the zero-length packet STATUS packet on endpoint 0 correctly. It may be a special transaction to the peripheral. +``dcd_edpt_xfer()`` is responsible for configuring the peripheral to send or receive data from the host. "xfer" is short for "transfer". **This is one of the core methods you must implement for TinyUSB to work (one other is the interrupt handler).** Data from the host is the OUT direction and data to the host is IN. It is used for all endpoints including the control endpoint 0. Make sure to handle the zero-length packet STATUS packet on endpoint 0 correctly. It may be a special transaction to the peripheral. Besides that, all other transactions are relatively straight-forward. The endpoint address provides the endpoint number and direction which usually determines where to write the buffer info. The buffer and its length are usually @@ -195,21 +197,21 @@ Others (like the nRF52) may need each USB packet queued individually. To make th some state for yourself and queue up an intermediate USB packet from the interrupt handler. Once the transaction is going, the interrupt handler will notify TinyUSB of transfer completion. -During transmission, the IN data buffer is guaranteed to remain unchanged in memory until the ``dcd_xfer_complete`` function is called. +During transmission, the IN data buffer is guaranteed to remain unchanged in memory until the ``dcd_xfer_complete()`` function is called. -The dcd_edpt_xfer function must never add zero-length-packets (ZLP) on its own to a transfer. If a ZLP is required, -then it must be explicitly sent by the stack calling dcd_edpt_xfer(), by calling dcd_edpt_xfer() a second time with len=0. +The ``dcd_edpt_xfer()`` function must never add zero-length-packets (ZLP) on its own to a transfer. If a ZLP is required, +then it must be explicitly sent by the stack calling ``dcd_edpt_xfer()``, by calling ``dcd_edpt_xfer()`` a second time with len=0. For control transfers, this is automatically done in ``usbd_control.c``. -At the moment, only a single buffer can be transmitted at once. There is no provision for double-buffering. new dcd_edpt_xfer() will not -be called again on the same endpoint address until the driver calls dcd_xfer_complete() (except in cases of USB resets). +At the moment, only a single buffer can be transmitted at once. There is no provision for double-buffering. new ``dcd_edpt_xfer()`` will not +be called again on the same endpoint address until the driver calls ``dcd_xfer_complete()`` (except in cases of USB resets). -dcd_xfer_complete -""""""""""""""""" +``dcd_xfer_complete()`` +""""""""""""""""""""""" -Once a transfer completes you must call dcd_xfer_complete from the USB interrupt handler to let TinyUSB know that a transaction has completed. Here is a sample call: +Once a transfer completes you must call ``dcd_xfer_complete()`` from the USB interrupt handler to let TinyUSB know that a transaction has completed. Here is a sample call: -.. code-block:: +.. code-block:: c dcd_event_xfer_complete(0, ep_addr, xfer->actual_len, XFER_RESULT_SUCCESS, true); @@ -219,23 +221,23 @@ The arguments are: * the USB peripheral number * the endpoint address -* the actual length of the transfer. (OUT transfers may be smaller than the buffer given in ``dcd_edpt_xfer``\ ) +* the actual length of the transfer. (OUT transfers may be smaller than the buffer given in ``dcd_edpt_xfer()``) * the result of the transfer. Failure isn't handled yet. * ``true`` to note the call is from an interrupt handler. -dcd_edpt_stall / dcd_edpt_clear_stall -""""""""""""""""""""""""""""""""""""" +``dcd_edpt_stall()`` / ``dcd_edpt_clear_stall()`` +""""""""""""""""""""""""""""""""""""""""""""""""" -Stalling is one way an endpoint can indicate failure such as when an unsupported command is transmitted. The pair of ``dcd_edpt_stall``\ , ``dcd_edpt_clear_stall`` help manage the stall state of all endpoints. +Stalling is one way an endpoint can indicate failure such as when an unsupported command is transmitted. The pair of ``dcd_edpt_stall()``, ``dcd_edpt_clear_stall()`` help manage the stall state of all endpoints. Woohoo! ------- -At this point you should have everything working! ;-) Of course, you may not write perfect code. Here are some tips and tricks for debugging. +At this point you should have everything working! 🙂 Of course, you may not write perfect code. Here are some tips and tricks for debugging. Use `WireShark `_ or `a Beagle `_ to sniff the USB traffic. When things aren't working its likely very early in the USB enumeration process. Figuring out where can help clue in where the issue is. For example: * If the host sends a SETUP packet and its not ACKed then your USB peripheral probably isn't started correctly. -* If the peripheral is started correctly but it still didn't work, then verify your usb clock is correct. (You did output a PWM based on it right? ;-) ) -* If the SETUP packet is ACKed but nothing is sent back then you interrupt handler isn't queueing the setup packet correctly. (Also, if you are using your own code instead of an example ``tud_task`` may not be called.) If that's OK, the ``dcd_xfer_complete`` may not be setting up the next transaction correctly. +* If the peripheral is started correctly but it still didn't work, then verify your usb clock is correct. (You did output a PWM based on it right? 🙂) +* If the SETUP packet is ACKed but nothing is sent back then you interrupt handler isn't queueing the setup packet correctly. (Also, if you are using your own code instead of an example ``tud_task()`` may not be called.) If that's OK, the ``dcd_xfer_complete()`` may not be setting up the next transaction correctly. diff --git a/docs/contributing/structure.rst b/docs/contributing/structure.rst deleted file mode 100644 index e8c658850..000000000 --- a/docs/contributing/structure.rst +++ /dev/null @@ -1,59 +0,0 @@ -********* -Structure -********* - -Tree -==== - -:: - - . - ├── docs - ├── examples - ├── hw - │   ├── bsp - │   └── mcu - ├── lib - ├── src - ├── test - └── tools - -docs ----- - -Documentation - -examples --------- - -Sample with Makefile build support - -hw/bsp ------- - -Supported boards source files - -hw/mcu ------- - -Low level mcu core & peripheral drivers - -lib ---- - -Sources from 3rd party such as freeRTOS, fatfs ... - -src ---- - -All sources files for TinyUSB stack itself. - -test ----- - -Unit tests for the stack - -tools ------ - -Files used internally diff --git a/docs/index.rst b/docs/index.rst index 2a032c51e..c1c8e4d99 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -1,12 +1,6 @@ :hide-toc: -********* -TinyUSB -********* - -TinyUSB is an open-source cross-platform USB Host/Device stack for embedded systems, -designed to be memory-safe with no dynamic allocation and thread-safe with all interrupt events being deferred and then handled in the non-ISR task function. - +.. include:: ../README_processed.rst .. toctree:: :caption: Index diff --git a/docs/info/changelog.rst b/docs/info/changelog.rst index d11e1134a..6024bb9e3 100644 --- a/docs/info/changelog.rst +++ b/docs/info/changelog.rst @@ -2,6 +2,59 @@ Changelog ********* +0.18.0 +====== + +General +------- + +- New MCUs: + + - Add esp32p4 OTG highspeed support + - Add stm32 u0, c0, h7rs + +- Better support dcache, make sure all usb-transferred buffer are cache line aligned and occupy full cache line +- Build ARM IAR with CircleCI +- Improve HIL with `dual/host_info_to_device_cdc`` optional for pico/pico2, enable dwc2 dma test + +API Changes +----------- + +- Change signature of ``tusb_init(rhport, tusb_rhport_init_t*)``, ``tusb_init(void)`` is now deprecated but still available for backward compatibility +- Add new ``tusb_int_handler(rhport, in_isr)`` +- Add time-related APIs: ``tusb_time_millis_api()`` and ``tusb_time_delay_ms_api()`` for non-RTOS, required for some ports/configuration +- New configuration macros: + + - ``CFG_TUD/TUH_MEM_DCACHE_ENABLE`` enable data cache sync for endpoint buffer + - ``CFG_TUD/TUH_MEM_DCACHE_LINE_SIZE`` set cache line size + - ``CFG_TUD/TUH_DWC2_SLAVE_ENABLE`` enable dwc2 slave mode + - ``CFG_TUD/TUH_DWC2_DMA_ENABLE`` enable dwc2 dma mode + +Controller Driver (DCD & HCD) +----------------------------- + +- DWC2 + - Add DMA support for both device and host controller + - Add host driver support including: full/high speed, control/bulk/interrupt (CBI) transfer, split CBI i.e FS/LS attached via highspeed hub, hub support + +- RP2: implement ``dcd_edpt_iso_alloc()`` and ``dcd_edpt_iso_activate()`` for isochronous endpoint +- iMXRT1170 support M4 core + +Device Stack +------------ + +- Vendor Fix class reset +- NCM fix recursions in ``tud_network_recv_renew()`` +- Audio fix align issue of ``_audiod_fct.alt_setting`` +- UVC support format frame based +- Change ``dcd_dcache_()`` return type from void to bool +- HID add Usage Table for Physical Input Device Page (0x0F) + +Host Stack +---------- + +- Fix an duplicated attach issue which cause USBH Defer Attach until current enumeration complete message + 0.17.0 ====== @@ -36,20 +89,20 @@ Controller Driver (DCD & HCD) - Add support for ch32 usbd e.g ch32v203 - Add support for STM32G4 and STM32U5 microcontrollers. - Fix h5 (32-bit) errata 2.15.1: Buffer description table update completes after CTR interrupt triggers - - ISO EP buffer allocation improvements, implement dcd_edpt_close_all() + - ISO EP buffer allocation improvements, implement ``dcd_edpt_close_all()`` - Fix ch32v203 race condition and stability issue with - fix ch32v203 seems to unconditionally accept ZLP on EP0 OUT. - fix v203 race condition between rx bufsize and RX_STAT which cause PMAOVR, occurs with WRITE10 - - correctly handle setup prepare at dcd_edpt0_status_complete(), which fixes the race condition with windows where we could miss setup packet (setup bit set, but count = 0) + - correctly handle setup prepare at ``dcd_edpt0_status_complete()``, which fixes the race condition with windows where we could miss setup packet (setup bit set, but count = 0) - MAX3421E - Add support for rp2040, esp32 (c3, c6, h2, etc..) - - Add hcd_deinit() for max3421 + - Add ``hcd_deinit()`` for max3421 - Retry NAK handling next frame to reduce CPU and SPI bus usage - - add cpuctl and pinctl to tuh_configure() option for max3421 + - add ``cpuctl`` and ``pinctl`` to ``tuh_configure()`` option for max3421 - Implement hcd abort transfer for Max3421 - Properly Handle NAK Response in MAX3421E driver: correctly switch and skip writing to 2 FIFOs when NAK received. Otherwise, the driver may hang in certain conditions. @@ -61,7 +114,7 @@ Controller Driver (DCD & HCD) - nRF - - Fix dcd_edpt_open for iso endpoint + - Fix ``dcd_edpt_open()`` for iso endpoint - Handle ISOOUT CRC errors - Add compile support with old nordic sdk - Fix a few race conditions @@ -88,7 +141,7 @@ Controller Driver (DCD & HCD) Device Stack ------------ -- Add tud_deinit() and class driver deinit() to deinitialize TinyUSB device stack. +- Add ``tud_deinit()`` and ``class driver deinit()`` to deinitialize TinyUSB device stack. - Add support for generic SOF callback. - Add set address recovery time 2ms per USB spec. @@ -104,7 +157,7 @@ Device Stack - CDC - - Add tud_cdc_configure_fifo() to make RX/TX buffer persistent (not clear when disconnected) + - Add ``tud_cdc_configure_fifo()`` to make RX/TX buffer persistent (not clear when disconnected) - Add missing capability bit for CDC ACM serial break support - Enhanced CDC class with better handling of large data transmissions. - Add missing capability bit for CDC ACM serial break support @@ -122,39 +175,39 @@ Device Stack - Net - Rewrite of NCM device driver to improve throughput - - removed obsolete tud_network_link_state_cb() + - removed obsolete ``tud_network_link_state_cb()`` - USBTMC Added notification support - Vendor - Migrate to new endpoint stream API, support non-buffered TX/RX - - Add ZLP for write() when needed + - Add ZLP for ``write()`` when needed - Video - Enhance UVC descriptors and example - Video Added support for USB Video Class (UVC) with MJPEG. - Fix multiple interfaces, add an example of 2ch video capture. - - Fix race for tud_video_n_streaming check + - Fix race for ``tud_video_n_streaming()`` check Host Stack ---------- -- Added tuh_deinit() to de-initialize TinyUSB host stack. +- Added ``tuh_deinit()`` to de-initialize TinyUSB host stack. - Added support for new USB mass storage class APIs. - Improved error handling and retry mechanisms for unstable devices. - CDC Serial - Add support for ch34x - - Allow to overwrite CFG_TUH_CDC_FTDI/CP210X/CH32X_VID_PID_LIST + - Allow to overwrite ``CFG_TUH_CDC_FTDI/CP210X/CH32X_VID_PID_LIST`` - Enhanced stability of CDC-ACM devices during enumeration. - HID - - Add tuh_hid_receive_abort() - - Add tuh_hid_get_report() + - Add ``tuh_hid_receive_abort()`` + - Add ``tuh_hid_get_report()`` - Hub @@ -171,14 +224,14 @@ Host Stack - Remove submodules and use python script to manage repo dependencies #1947 - Add CMake support for most families and boards, move build file from tools/ to examples/build_system - Add ETM trace support with JTrace for nrf52840, nrf5340, mcb1857, stm32h743eval, ra6m5 -- [osal] Make it possible to override the osal_task_delay() in osal_none +- [osal] Make it possible to override the ``osal_task_delay()`` in osal_none - Add CDC+UAC2 composite device example - Enhance Hardware-in-the-loop (HIL) testing with more boards: rp2040, stm32l412nucleo, stm32f746disco, lpcxpresso43s67 Controller Driver (DCD & HCD) ----------------------------- -- Add new ISO endpoint API: dcd_edpt_iso_alloc() and dcd_edpt_iso_activate() +- Add new ISO endpoint API: ``dcd_edpt_iso_alloc()`` and ``dcd_edpt_iso_activate()`` - Remove legacy driver st/synopsys - EHCI @@ -191,10 +244,10 @@ Controller Driver (DCD & HCD) - Fix error on EHCI causes xfer error in non-queued qhd which cause memory fault - Un-roll recursive hub removal with usbh queue - Fix issue when removing queue head - - Implement hcd_edpt_abort_xfer() + - Implement ``hcd_edpt_abort_xfer()`` - use standard USB complete interrupt instead of custom chipidea async/period interrupt to be more compatible with other ehci implementation - refactor usb complete & error isr processing, merge, update. Fix EHCI QHD reuses QTD on wrong endpoint - - Improve bus reset, fix send_setup() not carried out if halted previously + - Improve bus reset, fix ``send_setup()`` not carried out if halted previously - Fix clear qhd halted bit if not caused by STALL protocol to allow for next transfer - ChipIdea Highspeed @@ -220,12 +273,12 @@ Controller Driver (DCD & HCD) - rp2040 - [dcd] Make writes to SIE_CTRL aware of concurrent access - - [hcd] add hcd_frame_number(), hcd_edpt_abort_xfer() for pio-usb host + - [hcd] add ``hcd_frame_number()``, ``hcd_edpt_abort_xfer()`` for pio-usb host - stm32 fsdev: - Add STM32L5 support - - Implement dcd_edpt_iso_alloc() and dcd_edpt_iso_activate() + - Implement ``dcd_edpt_iso_alloc()`` and ``dcd_edpt_iso_activate()`` - OHCI @@ -239,7 +292,7 @@ Controller Driver (DCD & HCD) Device Stack ------------ -- Add optional hooks tud_event_hook_cb() +- Add optional hooks ``tud_event_hook_cb()`` - Audio (UAC2) - Fix feedback EP buffer alignment. @@ -257,12 +310,12 @@ Device Stack - MIDI - - Fix stream_write() always writes system messages to cable 0 + - Fix ``stream_write()`` always writes system messages to cable 0 - Fix incorrect NOTE_ON, NOTE_OFF definitions - USBTMC: Fix tmc488 bit order -- Vendor: fix read()/write() race condition +- Vendor: fix ``read()``/``write()`` race condition - Video (UVC) @@ -273,26 +326,26 @@ Host Stack - USBH - - Add new APIs: tuh_interface_set(), tuh_task_event_ready(), tuh_edpt_abort_xfer(), tuh_rhport_reset_bus(), tuh_rhport_is_active() + - Add new APIs: ``tuh_interface_set()``, ``tuh_task_event_ready()``, ``tuh_edpt_abort_xfer()``, ``tuh_rhport_reset_bus()``, ``tuh_rhport_is_active()`` - Fix issue when device generate multiple attach/detach/attach when plugging in - Prefer application callback over built-in driver on transfer complete event - - Correct hcd_edpt_clear_stall() API signature + - Correct ``hcd_edpt_clear_stall()`` API signature - Separate bus reset delay and contact debouncing delay in enumeration - - Support usbh_app_driver_get_cb() for application drivers + - Support ``usbh_app_driver_get_cb()`` for application drivers - Fix usbh enumeration removal race condition - - Add optional hooks tuh_event_hook_cb() + - Add optional hooks ``tuh_event_hook_cb()`` - CDC - - Breaking: change tuh_cdc_itf_get_info() to use tuh_itf_info_t instead of tuh_cdc_info_t + - Breaking: change ``tuh_cdc_itf_get_info()`` to use tuh_itf_info_t instead of tuh_cdc_info_t - Fix cdc host enumeration issue when device does not support line request - Add support for vendor usb2uart serial: ftdi, cp210x, ch9102f - - Improve sync control API e.g tuh_cdc_set_control_line_state(), tuh_cdc_set_line_coding() + - Improve sync control API e.g ``tuh_cdc_set_control_line_state()``, ``tuh_cdc_set_line_coding()`` - HID - - Add new APIs tuh_hid_send_report(), tuh_hid_itf_get_info(), tuh_hid_receive_ready(), tuh_hid_send_ready(), tuh_hid_set_default_protocol() - - Change meaning of CFG_TUH_HID to total number of HID interfaces supported. Previously CFG_TUH_HID is max number of interfaces per device which is rather limited and consume more resources than needed. + - Add new APIs ``tuh_hid_send_report()``, ``tuh_hid_itf_get_info()``, ``tuh_hid_receive_ready()``, ``tuh_hid_send_ready()``, ``tuh_hid_set_default_protocol()`` + - Change meaning of CFG_TUH_HID to total number of HID interfaces supported. Previously ``CFG_TUH_HID`` is max number of interfaces per device which is rather limited and consume more resources than needed. - HUB @@ -301,7 +354,7 @@ Host Stack - MSC - - Fix bug in tuh_msc_ready() + - Fix bug in ``tuh_msc_ready()`` - Fix host msc get maxlun not using aligned section memory 0.15.0 @@ -332,7 +385,7 @@ Controller Driver (DCD & HCD) - [rp2040] - [dcd] Implement workaround for Errata 15. This enable SOF when bulk-in endpoint is in use and reduce its bandwidth to only 80% - - [hcd] Fix shared irq slots filling up when hcd_init() is called multiple times + - [hcd] Fix shared irq slots filling up when ``hcd_init()`` is called multiple times - [hcd] Support host bulk endpoint using hw "interrupt" endpoint. Note speed limit is 64KB/s - [samd][dcd] Add support for ISO endpoint @@ -357,12 +410,12 @@ Device Stack - [HID] - Add FIDO descriptor template - - change length in tud_hid_report_complete_cb() from uint8 to uint16 + - change length in ``tud_hid_report_complete_cb()`` from ``uint8_t`` to ``uint16_t`` - [CDC] - Fix autoflush for FIFO < MPS - - Fix tx fifo memory overflown when DTR is not set and tud_cdc_write() is called repeatedly with large enough data + - Fix tx fifo memory overflown when DTR is not set and ``tud_cdc_write()`` is called repeatedly with large enough data - [USBTMC] Fix packet size with highspeed @@ -370,7 +423,7 @@ Host Stack ---------- - Retry a few times with transfers in enumeration since device can be unstable when starting up -- [MSC] Rework host masstorage API. Add new **host/msc_file_explorer** example +- [MSC] Rework host masstorage API. Add new ``host/msc_file_explorer`` example - [CDC] - Add support for host cdc @@ -380,22 +433,22 @@ Host Stack ====== - Improve compiler support for CCRX and IAR -- Add timeout to osal_queue_receive() -- Add tud_task_ext(timeout, in_isr) as generic version of tud_task(). Same as tuh_task_ext(), tuh_task() -- Enable more warnings -Wnull-dereference -Wuninitialized -Wunused -Wredundant-decls -Wconversion +- Add timeout to ``osal_queue_receive()`` +- Add ``tud_task_ext(timeout, in_isr)`` as generic version of ``tud_task()``. Same as ``tuh_task_ext()``, ``tuh_task()`` +- Enable more warnings ``-Wnull-dereference -Wuninitialized -Wunused -Wredundant-decls -Wconversion`` - Add new examples - - host/bare_api to demonstrate generic (app-level) enumeration and endpoint transfer - - dual/host_hid_to_device_cdc to run both device and host stack concurrently, get HID report from host and print out to device CDC. This example only work with multiple-controller MCUs and rp2040 with the help of pio-usb as added controller. + - ``host/bare_api`` to demonstrate generic (app-level) enumeration and endpoint transfer + - ``dual/host_hid_to_device_cdc`` to run both device and host stack concurrently, get HID report from host and print out to device CDC. This example only work with multiple-controller MCUs and rp2040 with the help of pio-usb as added controller. Controller Driver (DCD & HCD) ----------------------------- - Enhance rhports management to better support dual roles - - CFG_TUD_ENABLED/CFG_TUH_ENABLED, CFG_TUD_MAX_SPEED/CFG_TUH_MAX_SPEED can be used to replace CFG_TUSB_RHPORT0_MODE/CFG_TUSB_RHPORT1_MODE - - tud_init(rphort), tuh_init(rhport) can be used to init stack on specified roothub port (controller) instead of tusb_init(void) -- Add dcd/hcd port specific defines `TUP_` (stand for tinyusb port-specific) + - ``CFG_TUD_ENABLED``/``CFG_TUH_ENABLED``, ``CFG_TUD_MAX_SPEED``/``CFG_TUH_MAX_SPEED`` can be used to replace ``CFG_TUSB_RHPORT0_MODE``/``CFG_TUSB_RHPORT1_MODE`` + - ``tud_init(rphort)``, ``tuh_init(rhport)`` can be used to init stack on specified roothub port (controller) instead of ``tusb_init(void)`` +- Add dcd/hcd port specific defines ``TUP_`` (stand for tinyusb port-specific) - [dwc2] - Update to support stm32 h72x, h73x with only 1 otg controller @@ -416,10 +469,10 @@ Device Stack - [Audio] Add support for feedback endpoint computation - - New API tud_audio_feedback_params_cb(), tud_audio_feedback_interval_isr(). + - New API ``tud_audio_feedback_params_cb()``, ``tud_audio_feedback_interval_isr()``. - Supported computation method are: frequency with fixed/float or power of 2. Feedback with fifo count is not yet supported. - - Fix nitfs (should be 3) in TUD_AUDIO_HEADSET_STEREO_DESCRIPTOR - - Fix typo in audiod_rx_done_cb() + - Fix nitfs (should be 3) in ``TUD_AUDIO_HEADSET_STEREO_DESCRIPTOR`` + - Fix typo in ``audiod_rx_done_cb()`` - [DFU] Fix coexistence with other interfaces BTH, RNDIS - [MSC] Fix inquiry response additional length field @@ -428,23 +481,23 @@ Device Stack Host Stack ---------- -- Add new API tuh_configure(rhport, cfg_id, cfg_param) for dynamnic port specific behavior configuration +- Add new API ``tuh_configure(rhport, cfg_id, cfg_param)`` for dynamnic port specific behavior configuration - [HID] Open OUT endpoint if available - [Hub] hub clear port and device interrupts - [USBH] Major improvement - - Rework usbh control transfer with complete callback. New API tuh_control_xfer() though still only carry 1 usbh (no queueing) at a time. - - Add generic endpoint transfer with tuh_edpt_open(), tuh_edpt_xfer(). Require `CFG_TUH_API_EDPT_XFER=1` + - Rework usbh control transfer with complete callback. New API ``tuh_control_xfer()`` though still only carry 1 usbh (no queueing) at a time. + - Add generic endpoint transfer with ``tuh_edpt_open()``, ``tuh_edpt_xfer()``. Require ``CFG_TUH_API_EDPT_XFER=1`` - Support app-level enumeration with new APIs - - tuh_descriptor_get(), tuh_descriptor_get_device(), tuh_descriptor_get_configuration(), tuh_descriptor_get_hid_report() - - tuh_descriptor_get_string(), tuh_descriptor_get_manufacturer_string(), tuh_descriptor_get_product_string(), tuh_descriptor_get_serial_string() - - Also add _sync() as sync/blocking version for above APIs + - ``tuh_descriptor_get()``, ``tuh_descriptor_get_device()``, ``tuh_descriptor_get_configuration()``, ``tuh_descriptor_get_hid_report()`` + - ``tuh_descriptor_get_string()``, ``tuh_descriptor_get_manufacturer_string()``, ``tuh_descriptor_get_product_string()``, ``tuh_descriptor_get_serial_string()`` + - Also add ``_sync()`` as sync/blocking version for above APIs 0.13.0 ====== -- [tu_fifo] Fix locked mutex when full, and return type in peek_n() +- [tu_fifo] Fix locked mutex when full, and return type in ``peek_n()`` Controller Driver (DCD & HCD) ----------------------------- @@ -473,7 +526,7 @@ Device Stack ------------ - [Audio] Support disabling feedback format correction (16.16 <-> 10.14 format) -- [MSC] Add tud_msc_request_sense_cb() callback, change most default sense error to medium not present (0x02, 0x3A, 0x00) +- [MSC] Add ``tud_msc_request_sense_cb()`` callback, change most default sense error to medium not present (0x02, 0x3A, 0x00) - [Video] Fix video_capture example fails enumeration when 8FPS Host Stack @@ -484,22 +537,22 @@ No notable changes 0.12.0 ====== -- add CFG_TUSB_OS_INC_PATH for os include path +- add ``CFG_TUSB_OS_INC_PATH`` for os include path Device Controller Driver (DCD) ------------------------------ - Getting device stack to pass USB Compliance Verification test (chapter9, HID, MSC). Ports are tested: nRF, SAMD 21/51, rp2040, stm32f4, Renesas RX, iMXRT, ESP32-S2/3, Kinetic KL25/32, DA146xx -- Added dcd_edpt_close_all() for switching configuration -- [Transdimension] Support dcd_edpt_xfer_fifo() with auto wrap over if fifo buffer is 4K aligned and size is multiple of 4K. +- Added ``dcd_edpt_close_all()`` for switching configuration +- [Transdimension] Support ``dcd_edpt_xfer_fifo()`` with auto wrap over if fifo buffer is 4K aligned and size is multiple of 4K. - [DA146xx] Improve vbus, reset, suspend, resume detection, and remote wakeup. Device Stack ------------ -- Add new network driver Network Control Model (CDC-NCM), update net_lwip_webserver to work with NCM (need re-configure example) -- Add new USB Video Class UVC 1.5 driver and video_capture example ((work in progress) +- Add new network driver Network Control Model (CDC-NCM), update ``net_lwip_webserver`` to work with NCM (need re-configure example) +- Add new USB Video Class UVC 1.5 driver and video_capture example (work in progress) - Fix potential buffer overflow for HID, bluetooth drivers Host Controller Driver (HCD) @@ -536,13 +589,13 @@ Synopsys ^^^^^^^^ - Fix Synopsys set address bug which could cause re-enumeration failed -- Fix dcd_synopsys driver integer overflow in HS mode (issue #968) +- Fix ``dcd_synopsys`` driver integer overflow in HS mode (issue #968) nRF5x ^^^^^ - Add nRF5x suspend, resume and remote wakeup -- Fix nRF5x race condition with TASKS_EP0RCVOUT +- Fix nRF5x race condition with ``TASKS_EP0RCVOUT`` RP2040 ^^^^^^ @@ -557,8 +610,8 @@ USBD ^^^^ - Better support big endian mcu -- Add tuh_inited() and tud_inited(), will separate tusb_init/inited() to tud/tuh init/inited -- Add dcd_attr.h for defining common controller attribute such as max endpoints +- Add ``tuh_inited()`` and ``tud_inited()``, will separate ``tusb_init/inited()`` to ``tud/tuh_init/inited()`` +- Add ``dcd_attr.h`` for defining common controller attribute such as max endpoints Bluetooth ^^^^^^^^^ @@ -568,8 +621,8 @@ Bluetooth DFU ^^^ -- Enhance DFU implementation to support multiple alternate interface and better support bwPollTimeout -- Rename CFG_TUD_DFU_MODE to simply CFG_TUD_DFU +- Enhance DFU implementation to support multiple alternate interface and better support ``bwPollTimeout`` +- Rename ``CFG_TUD_DFU_MODE`` to simply ``CFG_TUD_DFU`` HID ^^^ @@ -594,7 +647,7 @@ Vendor ^^^^^^ - Fix vendor fifo deadlock in certain case -- Add tud_vendor_n_read_flush +- Add ``tud_vendor_n_read_flush()`` Host Controller Driver (HCD) ---------------------------- @@ -611,7 +664,7 @@ Host Stack - Major update and rework most of host stack, still needs more improvement - Lots of improvement and update in parsing configuration and control - Rework and major update to HID driver. Will default to enable boot interface if available -- Separate CFG_TUH_DEVICE_MAX and CFG_TUH_HUB for better management and reduce SRAM usage +- Separate ``CFG_TUH_DEVICE_MAX`` and ``CFG_TUH_HUB`` for better management and reduce SRAM usage 0.10.1 (2021-06-03) =================== @@ -623,9 +676,9 @@ Host Controller Driver (HCD) - Fix rp2040 host driver: incorrect PID with low speed device with max packet size of 8 bytes - Improve hub driver -- Remove obsolete hcd_pipe_queue_xfer()/hcd_pipe_xfer() -- Use hcd_frame_number() instead of micro frame -- Fix OHCI endpoint address and xferred_bytes in xfer complete event +- Remove obsolete ``hcd_pipe_queue_xfer()``/``hcd_pipe_xfer()`` +- Use ``hcd_frame_number()`` instead of micro frame +- Fix OHCI endpoint address and ``xferred_bytes`` in xfer complete event 0.10.0 (2021-05-28) =================== @@ -644,7 +697,7 @@ Device Controller Driver (DCD) - Fix build with nRF5340 - Fix build with lpc15 and lpc54 - Fix build with lpc177x_8x -- STM32 Synopsys: greatly improve Isochronous transfer with edpt_xfer_fifo API +- STM32 Synopsys: greatly improve Isochronous transfer with ``edpt_xfer_fifo()`` API - Support LPC55 port1 highspeed - Add support for Espressif esp32s3 - nRF: fix race condition that could cause drop packet of Bulk OUT transfer @@ -652,14 +705,14 @@ Device Controller Driver (DCD) USB Device Driver (USBD) ------------------------ -- Add new (optional) endpoint ADPI usbd_edpt_xfer_fifo +- Add new (optional) endpoint ADPI ``usbd_edpt_xfer_fifo()`` Device Class Driver ------------------- CDC -- [Breaking] tud_cdc_peek(), tud_vendor_peek() no longer support random offset and dropped position parameter. +- [Breaking] ``tud_cdc_peek()``, ``tud_vendor_peek()`` no longer support random offset and dropped position parameter. DFU @@ -671,19 +724,19 @@ HID - Add more hid keys constant from 0x6B to 0xA4 - [Breaking] rename API - - HID_PROTOCOL_NONE/KEYBOARD/MOUST to HID_ITF_PROTOCOL_NONE/KEYBOARD/MOUSE - - tud_hid_boot_mode() to tud_hid_get_protocol() - - tud_hid_boot_mode_cb() to tud_hid_set_protocol_cb() + - ``HID_PROTOCOL_NONE/KEYBOARD/MOUSE`` to ``HID_ITF_PROTOCOL_NONE/KEYBOARD/MOUSE`` + - ``tud_hid_boot_mode()`` to ``tud_hid_get_protocol()`` + - ``tud_hid_boot_mode_cb()`` to ``tud_hid_set_protocol_cb()`` MIDI - Fix MIDI buffer overflow issue - [Breaking] rename API - - Rename tud_midi_read() to tud_midi_stream_read() - - Rename tud_midi_write() to tud_midi_stream_write() - - Rename tud_midi_receive() to tud_midi_packet_read() - - Rename tud_midi_send() to tud_midi_packet_write() + - Rename ``tud_midi_read()`` to ``tud_midi_stream_read()`` + - Rename ``tud_midi_write()`` to ``tud_midi_stream_write()`` + - Rename ``tud_midi_receive()`` to ``tud_midi_packet_read()`` + - Rename ``tud_midi_send()`` to ``tud_midi_packet_write()`` Host Controller Driver (HCD) ---------------------------- @@ -730,7 +783,7 @@ NXP Transdimention USB Device Driver (USBD) ^^^^^^^^^^^^^^^^^^^^^^^^ -- Fix issue with status zlp (tud_control_status) is returned by class driver with SET/CLEAR_FEATURE for endpoint. +- Fix issue with status zlp (``tud_control_status()``) is returned by class driver with SET/CLEAR_FEATURE for endpoint. - Correct endpoint size check for fullspeed bulk, can be 8, 16, 32, 64 - Ack SET_INTERFACE even if it is not implemented by class driver. @@ -739,34 +792,34 @@ Device Class Driver DFU Runtime -- rename dfu_rt to dfu_runtime for easy reading +- rename ``dfu_rt()`` to ``dfu_runtime()`` for easy reading CDC -- Add tud_cdc_send_break_cb() to support break request -- Improve CDC receive, minor behavior changes: when tud_cdc_rx_wanted_cb() is invoked wanted_char may not be the last byte in the fifo +- Add ``tud_cdc_send_break_cb()`` to support break request +- Improve CDC receive, minor behavior changes: when ``tud_cdc_rx_wanted_cb()`` is invoked wanted_char may not be the last byte in the fifo HID - [Breaking] Add itf argument to hid API to support multiple instances, follow API has signature changes - - tud_hid_descriptor_report_cb() - - tud_hid_get_report_cb() - - tud_hid_set_report_cb() - - tud_hid_boot_mode_cb() - - tud_hid_set_idle_cb() + - ``tud_hid_descriptor_report_cb()`` + - ``tud_hid_get_report_cb()`` + - ``tud_hid_set_report_cb()`` + - ``tud_hid_boot_mode_cb()`` + - ``tud_hid_set_idle_cb()`` -- Add report complete callback tud_hid_report_complete_cb() API +- Add report complete callback ``tud_hid_report_complete_cb()`` API - Add DPad/Hat support for HID Gamepad - - `TUD_HID_REPORT_DESC_GAMEPAD()` now support 16 buttons, 2 joysticks, 1 hat/dpad - - Add hid_gamepad_report_t along with `GAMEPAD_BUTTON_` and `GAMEPAD_HAT_` enum - - Add Gamepad to hid_composite / hid_composite_freertos example + - ``TUD_HID_REPORT_DESC_GAMEPAD()`` now support 16 buttons, 2 joysticks, 1 hat/dpad + - Add ``hid_gamepad_report_t`` along with ``GAMEPAD_BUTTON_`` and ``GAMEPAD_HAT_`` enum + - Add Gamepad to ``hid_composite`` / ``hid_composite_freertos`` example MIDI - Fix dropping MIDI sysex message when fifo is full -- Fix typo in tud_midi_write24(), make example less ambiguous for cable and channel +- Fix typo in ``tud_midi_write24()``, make example less ambiguous for cable and channel - Fix incorrect endpoint descriptor length, MIDI v1 use Audio v1 which has 9-byte endpoint descriptor (instead of 7) Host Stack @@ -775,14 +828,14 @@ Host Stack Host Controller Driver (HCD) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -- Add rhport to hcd_init() +- Add rhport to ``hcd_init()`` - Improve EHCI/OHCI driver abstraction - Move echi/ohci files to portable/ - - Rename hcd_lpc18_43 to hcd_transdimension - - Sub hcd API with hcd_ehci_init(), hcd_ehci_register_addr() + - Rename ``hcd_lpc18_43`` to ``hcd_transdimension`` + - Sub hcd API with ``hcd_ehci_init()``, ``hcd_ehci_register_addr()`` -- Update NXP transdimention hcd_init() to reset controller to host mode +- Update NXP transdimension ``hcd_init()`` to reset controller to host mode - Ported hcd to rt10xx @@ -796,20 +849,20 @@ Host Class Driver MSC -- Rename tuh_msc_scsi_inquiry() to tuh_msc_inquiry() -- Rename tuh_msc_mounted_cb/tuh_msc_unmounted_cb to tuh_msc_mount_cb/tuh_msc_unmount_cb to match device stack naming -- Change tuh_msc_is_busy() to tuh_msc_ready() -- Add read10 and write10 function: tuh_msc_read10(), tuh_msc_write10() +- Rename ``tuh_msc_scsi_inquiry()`` to ``tuh_msc_inquiry()`` +- Rename ``tuh_msc_mounted_cb()``/``tuh_msc_unmounted_cb()`` to ``tuh_msc_mount_cb()``/``tuh_msc_unmount_cb()`` to match device stack naming +- Change ``tuh_msc_is_busy()`` to ``tuh_msc_ready()`` +- Add read10 and write10 function: ``tuh_msc_read10()``, ``tuh_msc_write10()`` - Read_Capacity is invoked as part of enumeration process -- Add tuh_msc_get_block_count(), tuh_msc_get_block_size() -- Add CFG_TUH_MSC_MAXLUN (default to 4) to hold lun capacities +- Add ``tuh_msc_get_block_count()``, ``tuh_msc_get_block_size()`` +- Add ``CFG_TUH_MSC_MAXLUN`` (default to 4) to hold lun capacities Others ------ - Add basic support for rt-thread OS - Change zero bitfield length to more explicit padding -- Build example now fetch required submodules on the fly while running `make` without prio submodule init for mcu drivers +- Build example now fetch required submodules on the fly while running ``make`` without prior submodule init for mcu drivers - Update pico-sdk to v1.1.0 **New Boards** @@ -827,7 +880,7 @@ Device Controller Driver - Added new device support for Raspberry Pi RP2040 - Added new device support for NXP Kinetis KL25ZXX -- Use dcd_event_bus_reset() with link speed to replace bus_signal +- Use ``dcd_event_bus_reset()`` with link speed to replace bus_signal - ESP32-S2: - Add bus suspend and wakeup support @@ -849,8 +902,8 @@ USB Device **USBD** - Rework usbd control transfer to have additional stage parameter for setup, data, status -- Fix tusb_init() return true instead of TUSB_ERROR_NONE -- Added new API tud_connected() that return true after device got out of bus reset and received the very first setup packet +- Fix ``tusb_init()`` return true instead of ``TUSB_ERROR_NONE`` +- Added new API ``tud_connected()`` that return true after device got out of bus reset and received the very first setup packet **Class Driver** @@ -858,22 +911,22 @@ USB Device - Allow to transmit data, even if the host does not support control line states i.e set DTR - HID - - change default CFG_TUD_HID_EP_BUFSIZE from 16 to 64 + - change default ``CFG_TUD_HID_EP_BUFSIZE`` from 16 to 64 - MIDI - Fix midi sysex sending bug - MSC - Invoke only scsi complete callback after status transaction is complete. - - Fix scsi_mode_sense6_t padding, which cause IAR compiler internal error. + - Fix ``scsi_mode_sense6_t`` padding, which cause IAR compiler internal error. - USBTMC - Change interrupt endpoint example size to 8 instead of 2 for better compatibility with mcu **Example** -- Support make from windows cmd.exe -- Add HID Consumer Control (media keys) to hid_composite & hid_composite_freertos examples +- Support make from windows ``cmd.exe`` +- Add HID Consumer Control (media keys) to ``hid_composite`` & ``hid_composite_freertos`` examples USB Host @@ -914,28 +967,28 @@ Device Controller Driver - Support multiple usb ports with rhport=1 is highspeed on selected MCUs e.g H743, F23. It is possible to have OTG_HS to run on Fullspeed PHY (e.g lacking external PHY) - Add ISO transfer, fix odd/even frame - Fix FIFO flush during stall - - Implement dcd_edpt_close() API + - Implement ``dcd_edpt_close()`` API - Support F105, F107 - Enhance STM32 fsdev - Improve dcd fifo allocation - Fix ISTR race condition - Support remap USB IRQ on supported MCUs - - Implement dcd_edpt_close() API + - Implement ``dcd_edpt_close()`` API - Enhance NUC 505: enhance set configure behavior - Enhance SAMD - Fix race condition with setup packet - - Add SAMD11 option `OPT_MCU_SAMD11` - - Add SAME5x option `OPT_MCU_SAME5X` + - Add SAMD11 option ``OPT_MCU_SAMD11`` + - Add SAME5x option ``OPT_MCU_SAME5X`` - Fix SAMG control data toggle and stall race condition - Enhance nRF - - Fix hanged when tud_task() is called within critical section (disabled interrupt) + - Fix hanged when ``tud_task()`` is called within critical section (disabled interrupt) - Fix disconnect bus event not submitted - - Implement ISO transfer and dcd_edpt_close() + - Implement ISO transfer and ``dcd_edpt_close()`` USB Device @@ -944,26 +997,26 @@ USB Device **USBD** - Add new class driver for **Bluetooth HCI** class driver with example can be found in [mynewt-tinyusb-example](https://github.com/hathach/mynewt-tinyusb-example) since it needs mynewt OS to run with. -- Fix USBD endpoint usage racing condition with `usbd_edpt_claim()/usbd_edpt_release()` -- Added `tud_task_event_ready()` and `osal_queue_empty()`. This API is needed to check before enter low power mode with WFI/WFE -- Rename USB IRQ Handler to `dcd_int_handler()`. Application must define IRQ handler in which it calls this API. -- Add `dcd_connect()` and `dcd_disconnect()` to enable/disable internal pullup on D+/D- on supported MCUs. -- Add `usbd_edpt_open()` -- Remove `dcd_set_config()` -- Add *OPT_OS_CUMSTOM* as hook for application to overwrite and/or add their own OS implementation +- Fix USBD endpoint usage racing condition with ``usbd_edpt_claim()``/``usbd_edpt_release()`` +- Added ``tud_task_event_ready()`` and ``osal_queue_empty()``. This API is needed to check before enter low power mode with WFI/WFE +- Rename USB IRQ Handler to ``dcd_int_handler()``. Application must define IRQ handler in which it calls this API. +- Add ``dcd_connect()`` and ``dcd_disconnect()`` to enable/disable internal pullup on D+/D- on supported MCUs. +- Add ``usbd_edpt_open()`` +- Remove ``dcd_set_config()`` +- Add ``OPT_OS_CUMSTOM`` as hook for application to overwrite and/or add their own OS implementation - Support SET_INTERFACE, GET_INTERFACE request -- Add Logging for debug with optional uart/rtt/swo printf retarget or `CFG_TUSB_DEBUG_PRINTF` hook +- Add Logging for debug with optional uart/rtt/swo printf retarget or ``CFG_TUSB_DEBUG_PRINTF`` hook - Add IAR compiler support -- Support multiple configuration descriptors. `TUD_CONFIG_DESCRIPTOR()` template has extra config_num as 1st argument -- Improve USB Highspeed support with actual link speed detection with `dcd_event_bus_reset()` +- Support multiple configuration descriptors. ``TUD_CONFIG_DESCRIPTOR()`` template has extra config_num as 1st argument +- Improve USB Highspeed support with actual link speed detection with ``dcd_event_bus_reset()`` - Enhance class driver management - - `usbd_driver_open()` add max length argument, and return length of interface (0 for not supported). Return value is used for finding appropriate driver - - Add application implemented class driver via `usbd_app_driver_get_cb()` + - ``usbd_driver_open()`` add max length argument, and return length of interface (0 for not supported). Return value is used for finding appropriate driver + - Add application implemented class driver via ``usbd_app_driver_get_cb()`` - IAD is handled to assign driver id -- Added `tud_descriptor_device_qualifier_cb()` callback -- Optimize `tu_fifo` bulk write/read transfer +- Added ``tud_descriptor_device_qualifier_cb()`` callback +- Optimize ``tu_fifo`` bulk write/read transfer - Forward non-std control request to class driver - Let application handle Microsoft OS 1.0 Descriptors (the 0xEE index string) - Fix OSAL FreeRTOS yield from ISR @@ -975,8 +1028,8 @@ USB Device - CDC: - Send zero length packet for end of data when needed - - Add `tud_cdc_tx_complete_cb()` callback - - Change tud_cdc_n_write_flush() return number of bytes forced to transfer, and flush when writing enough data to fifo + - Add ``tud_cdc_tx_complete_cb()`` callback + - Change ``tud_cdc_n_write_flush()`` return number of bytes forced to transfer, and flush when writing enough data to fifo - MIDI: - Add packet interface @@ -986,10 +1039,10 @@ USB Device - DFU Runtime: fix response to SET_INTERFACE and DFU_GETSTATUS request - Rename some configure macro to make it clear that those are used directly for endpoint transfer - - CFG_TUD_HID_BUFSIZE to CFG_TUD_HID_EP_BUFSIZE - - CFG_TUD_CDC_EPSIZE to CFG_TUD_CDC_EP_BUFSIZE - - CFG_TUD_MSC_BUFSIZE to CFG_TUD_MSC_EP_BUFSIZE - - CFG_TUD_MIDI_EPSIZE to CFG_TUD_MIDI_EP_BUFSIZE + - ``CFG_TUD_HID_BUFSIZE`` to ``CFG_TUD_HID_EP_BUFSIZE`` + - ``CFG_TUD_CDC_EPSIZE`` to ``CFG_TUD_CDC_EP_BUFSIZE`` + - ``CFG_TUD_MSC_BUFSIZE`` to ``CFG_TUD_MSC_EP_BUFSIZE`` + - ``CFG_TUD_MIDI_EPSIZE`` to ``CFG_TUD_MIDI_EP_BUFSIZE`` - HID: - Fix gamepad template descriptor @@ -1008,15 +1061,15 @@ USB Host Examples -------- -- Add new hid_composite_freertos -- Add new dynamic_configuration to demonstrate how to switch configuration descriptors -- Add new hid_multiple_interface +- Add new ``hid_composite_freertos`` +- Add new ``dynamic_configuration`` to demonstrate how to switch configuration descriptors +- Add new ``hid_multiple_interface`` -- Enhance `net_lwip_webserver` example +- Enhance ``net_lwip_webserver`` example - Add multiple configuration: RNDIS for Windows, CDC-ECM for macOS (Linux will work with both) - - Update lwip to STABLE-2_1_2_RELEASE for net_lwip_webserver + - Update lwip to STABLE-2_1_2_RELEASE for ``net_lwip_webserver`` -- Added new Audio example: audio_test uac2_headsest +- Added new Audio example: ``audio_test`` ``uac2_headsest`` New Boards ---------- @@ -1057,37 +1110,37 @@ Added - Added multiple instances support for CDC and MIDI - Added a handful of unit test with Ceedling. - Added LOG support for debugging with CFG_TUSB_DEBUG -- Added `tud_descriptor_bos_cb()` for BOS descriptor (required for USB 2.1) -- Added `dcd_edpt0_status_complete()` as optional API for DCD +- Added ``tud_descriptor_bos_cb()`` for BOS descriptor (required for USB 2.1) +- Added ``dcd_edpt0_status_complete()`` as optional API for DCD **Examples** Following examples are added: -- board_test -- cdc_dual_ports -- dfu_rt -- hid_composite -- net_lwip_webserver -- usbtmc -- webusb_serial +- ``board_test`` +- ``cdc_dual_ports`` +- ``dfu_rt`` +- ``hid_composite`` +- ``net_lwip_webserver`` +- ``usbtmc`` +- ``webusb_serial`` Changed ------- -- Changed `tud_descriptor_string_cb()` to have additional Language ID argument -- Merged hal_nrf5x.c into dcd_nrf5x.c -- Merged dcd_samd21.c and dcd_samd51.c into dcd_samd.c -- Generalized dcd_stm32f4.c to dcd_synopsys.c -- Changed cdc_msc_hid to cdc_msc (drop hid) due to limited endpoints number of some MCUs +- Changed ``tud_descriptor_string_cb()`` to have additional Language ID argument +- Merged ``hal_nrf5x.c`` into ``dcd_nrf5x.c`` +- Merged ``dcd_samd21.c`` and ``dcd_samd51.c`` into ``dcd_samd.c`` +- Generalized ``dcd_stm32f4.c`` to ``dcd_synopsys.c`` +- Changed ``cdc_msc_hid`` to ``cdc_msc`` (drop hid) due to limited endpoints number of some MCUs - Improved DCD SAMD stability, fix missing setup packet occasionally -- Improved usbd/usbd_control with proper handling of zero-length packet (ZLP) +- Improved ``usbd/usbd_control`` with proper handling of zero-length packet (ZLP) - Improved STM32 DCD FSDev - Improved STM32 DCD Synopsys - Migrated CI from Travis to Github Action - Updated nrfx submodule to 2.1.0 - Fixed mynewt osal queue definition -- Fixed cdc_msc_freertos example build for all MCUs +- Fixed ``cdc_msc_freertos`` example build for all MCUs 0.5.0 (2019-06) diff --git a/docs/info/contributors.rst b/docs/info/contributors.rst deleted file mode 120000 index b3748ccb5..000000000 --- a/docs/info/contributors.rst +++ /dev/null @@ -1 +0,0 @@ -../../CONTRIBUTORS.rst \ No newline at end of file diff --git a/docs/info/contributors.rst b/docs/info/contributors.rst new file mode 100644 index 000000000..35e0b05f5 --- /dev/null +++ b/docs/info/contributors.rst @@ -0,0 +1 @@ +.. include:: ../../CONTRIBUTORS.rst \ No newline at end of file diff --git a/docs/info/index.rst b/docs/info/index.rst index fa56512b6..a636f37dc 100644 --- a/docs/info/index.rst +++ b/docs/info/index.rst @@ -8,6 +8,5 @@ Index .. toctree:: :maxdepth: 2 - uses changelog contributors diff --git a/docs/info/uses.rst b/docs/info/uses.rst deleted file mode 100644 index f67df49f8..000000000 --- a/docs/info/uses.rst +++ /dev/null @@ -1,17 +0,0 @@ -**** -Uses -**** - -TinyUSB is currently used by these other projects: - -- `Adafruit nRF52 Arduino `__ -- `Adafruit nRF52 Bootloader `__ -- `Adafruit SAMD Arduino `__ -- `CircuitPython `__ -- `Espressif IDF `__ -- `MicroPython `__ -- `mynewt `__ -- `openinput `__ -- `Raspberry Pi Pico SDK `__ -- `TinyUF2 Bootloader `__ -- `TinyUSB Arduino Library `__ diff --git a/docs/reference/boards.rst b/docs/reference/boards.rst new file mode 100644 index 000000000..41e765683 --- /dev/null +++ b/docs/reference/boards.rst @@ -0,0 +1,330 @@ +**************** +Supported Boards +**************** + +The board support code is only used for self-contained examples and testing. It is not used when TinyUSB is part of a larger project. +It is responsible for getting the MCU started and the USB peripheral clocked with minimal of on-board devices + +- One LED : for status +- One Button : to get input from user +- One UART : needed for logging with LOGGER=uart, maybe required for host/dual examples + +Following boards are supported + +Analog Devices +-------------- + +============= ================ ======== ================================================================================================================= ====== +Board Name Family URL Note +============= ================ ======== ================================================================================================================= ====== +apard32690 APARD32690-SL maxim https://www.analog.com/en/resources/evaluation-hardware-and-software/evaluation-boards-kits/ad-apard32690-sl.html +max32650evkit MAX32650 EVKIT maxim https://www.analog.com/en/resources/evaluation-hardware-and-software/evaluation-boards-kits/max32650-evkit.html +max32650fthr MAX32650 Feather maxim https://www.analog.com/en/resources/evaluation-hardware-and-software/evaluation-boards-kits/max32650fthr.html +max32651evkit MAX32651 EVKIT maxim https://www.analog.com/en/resources/evaluation-hardware-and-software/evaluation-boards-kits/max32651-evkit.html +max32666evkit MAX32666 EVKIT maxim https://www.analog.com/en/resources/evaluation-hardware-and-software/evaluation-boards-kits/max32666evkit.html +max32666fthr MAX32666 Feather maxim https://www.analog.com/en/resources/evaluation-hardware-and-software/evaluation-boards-kits/max32666fthr.html +max32690evkit MAX32690 EVKIT maxim https://www.analog.com/en/resources/evaluation-hardware-and-software/evaluation-boards-kits/max32690evkit.html +max78002evkit MAX78002 EVKIT maxim https://www.analog.com/en/resources/evaluation-hardware-and-software/evaluation-boards-kits/max78002evkit.html +============= ================ ======== ================================================================================================================= ====== + +Bridgetek +--------- + +========= ========= ======== ===================================== ====== +Board Name Family URL Note +========= ========= ======== ===================================== ====== +mm900evxb MM900EVxB brtmm90x https://brtchip.com/product/mm900ev1b +========= ========= ======== ===================================== ====== + +Espressif +--------- + +========================= ============================== ========= ======================================================================================================== ====== +Board Name Family URL Note +========================= ============================== ========= ======================================================================================================== ====== +adafruit_feather_esp32_v2 Adafruit Feather ESP32 v2 espressif https://www.adafruit.com/product/5400 +adafruit_feather_esp32c6 Adafruit Feather EPS32-C6 espressif https://www.adafruit.com/product/5933 +adafruit_feather_esp32s2 Adafruit Feather ESP32S2 espressif https://www.adafruit.com/product/5000 +adafruit_feather_esp32s3 Adafruit Feather ESP32S3 espressif https://www.adafruit.com/product/5323 +adafruit_magtag_29gray Adafruit MagTag 2.9" Grayscale espressif https://www.adafruit.com/product/4800 +adafruit_metro_esp32s2 Adafruit Metro ESP32-S2 espressif https://www.adafruit.com/product/4775 +espressif_addax_1 Espresif Addax-1 espressif n/a +espressif_c3_devkitc Espresif C3 DevKitC espressif https://docs.espressif.com/projects/esp-dev-kits/en/latest/esp32c3/esp32-c3-devkitc-02/index.html +espressif_c6_devkitc Espresif C6 DevKitC espressif https://docs.espressif.com/projects/esp-dev-kits/en/latest/esp32c6/esp32-c6-devkitc-1/index.html +espressif_kaluga_1 Espresif Kaluga 1 espressif https://docs.espressif.com/projects/esp-dev-kits/en/latest/esp32s2/esp32-s2-kaluga-1/index.html +espressif_p4_function_ev Espresif P4 Function EV espressif https://docs.espressif.com/projects/esp-dev-kits/en/latest/esp32p4/esp32-p4-function-ev-board/index.html +espressif_s2_devkitc Espresif S2 DevKitC espressif https://docs.espressif.com/projects/esp-dev-kits/en/latest/esp32s2/esp32-s2-devkitc-1/index.html +espressif_s3_devkitc Espresif S3 DevKitC espressif https://docs.espressif.com/projects/esp-dev-kits/en/latest/esp32s3/esp32-s3-devkitc-1/index.html +espressif_s3_devkitm Espresif S3 DevKitM espressif https://docs.espressif.com/projects/esp-dev-kits/en/latest/esp32s3/esp32-s3-devkitm-1/index.html +espressif_saola_1 Espresif S2 Saola 1 espressif https://docs.espressif.com/projects/esp-dev-kits/en/latest/esp32s2/esp32-s2-saola-1/index.html +========================= ============================== ========= ======================================================================================================== ====== + +GigaDevice +---------- + +================== ================== ========= ============================= ====== +Board Name Family URL Note +================== ================== ========= ============================= ====== +sipeed_longan_nano Sipeed Longan Nano gd32vf103 https://longan.sipeed.com/en/ +================== ================== ========= ============================= ====== + +Infineon +-------- + +============= ================= ======== ============================================================================= ====== +Board Name Family URL Note +============= ================= ======== ============================================================================= ====== +xmc4500_relax XMC4500 relax kit xmc4000 https://www.infineon.com/cms/en/product/evaluation-boards/kit_xmc45_relax_v1/ +xmc4700_relax XMC4700 relax kit xmc4000 https://www.infineon.com/cms/en/product/evaluation-boards/kit_xmc47_relax_v1/ +============= ================= ======== ============================================================================= ====== + +Microchip +--------- + +========================= =================================== ========== ================================================================================= ====== +Board Name Family URL Note +========================= =================================== ========== ================================================================================= ====== +olimex_emz64 Olimex PIC32-EMZ64 pic32mz https://www.olimex.com/Products/PIC/Development/PIC32-EMZ64/open-source-hardware +olimex_hmz144 Olimex PIC32-HMZ144 pic32mz https://www.olimex.com/Products/PIC/Development/PIC32-HMZ144/open-source-hardware +cynthion_d11 Great Scott Gadgets Cynthion samd11 https://greatscottgadgets.com/cynthion/ +samd11_xplained SAMD11 Xplained Pro samd11 https://www.microchip.com/en-us/development-tool/ATSAMD11-XPRO +atsamd21_xpro SAMD21 Xplained Pro samd21 https://www.microchip.com/DevelopmentTools/ProductDetails/ATSAMD21-XPRO +circuitplayground_express Adafruit Circuit Playground Express samd21 https://www.adafruit.com/product/3333 +curiosity_nano SAMD21 Curiosty Nano samd21 https://www.microchip.com/en-us/development-tool/dm320119 +cynthion_d21 Great Scott Gadgets Cynthion samd21 https://greatscottgadgets.com/cynthion/ +feather_m0_express Adafruit Feather M0 Express samd21 https://www.adafruit.com/product/3403 +itsybitsy_m0 Adafruit ItsyBitsy M0 samd21 https://www.adafruit.com/product/3727 +metro_m0_express Adafruit Metro M0 Express samd21 https://www.adafruit.com/product/3505 +qtpy Adafruit QT Py samd21 https://www.adafruit.com/product/4600 +seeeduino_xiao Seeeduino XIAO samd21 https://wiki.seeedstudio.com/Seeeduino-XIAO/ +sparkfun_samd21_mini_usb SparkFun SAMD21 Mini samd21 https://www.sparkfun.com/products/13664 +trinket_m0 Adafruit Trinket M0 samd21 https://www.adafruit.com/product/3500 +d5035_01 D5035-01 samd5x_e5x https://github.com/RudolphRiedel/USB_CAN-FD +feather_m4_express Adafruit Feather M4 Express samd5x_e5x https://www.adafruit.com/product/3857 +itsybitsy_m4 Adafruit ItsyBitsy M4 samd5x_e5x https://www.adafruit.com/product/3800 +metro_m4_express Adafruit Metro M4 Express samd5x_e5x https://www.adafruit.com/product/3382 +pybadge Adafruit PyBadge samd5x_e5x https://www.adafruit.com/product/4200 +pyportal Adafruit PyPortal samd5x_e5x https://www.adafruit.com/product/4116 +same54_xplained SAME54 Xplained Pro samd5x_e5x https://www.microchip.com/DevelopmentTools/ProductDetails/ATSAME54-XPRO +samg55_xplained SAMG55 Xplained Pro samg https://www.microchip.com/DevelopmentTools/ProductDetails/ATSAMG55-XPRO +atsaml21_xpro SAML21 Xplained Pro saml2x https://www.microchip.com/en-us/development-tool/atsaml21-xpro-b +saml22_feather SAML22 Feather saml2x https://github.com/joeycastillo/Feather-Projects/tree/main/SAML22%20Feather +sensorwatch_m0 SensorWatch saml2x https://github.com/joeycastillo/Sensor-Watch +========================= =================================== ========== ================================================================================= ====== + +MindMotion +---------- + +===================== ====================================== ======== =============================================================================================== ====== +Board Name Family URL Note +===================== ====================================== ======== =============================================================================================== ====== +mm32f327x_mb39 MM32F3273G9P MB-039 mm32 https://www.mindmotion.com.cn/support/development_tools/evaluation_boards/evboard/mm32f3273g9p/ +mm32f327x_pitaya_lite DshanMCU Pitaya Lite with MM32F3273G8P mm32 https://gitee.com/weidongshan/DshanMCU-Pitaya-c +===================== ====================================== ======== =============================================================================================== ====== + +NXP +--- + +================== ========================================= ============= ========================================================================================================================================================================= ====== +Board Name Family URL Note +================== ========================================= ============= ========================================================================================================================================================================= ====== +metro_m7_1011 Adafruit Metro M7 1011 imxrt https://www.adafruit.com/product/5600 +metro_m7_1011_sd Adafruit Metro M7 1011 SD imxrt https://www.adafruit.com/product/5600 +mimxrt1010_evk i.MX RT1010 Evaluation Kit imxrt https://www.nxp.com/design/design-center/development-boards-and-designs/i-mx-evaluation-and-development-boards/i-mx-rt1010-evaluation-kit:MIMXRT1010-EVK +mimxrt1015_evk i.MX RT1015 Evaluation Kit imxrt https://www.nxp.com/design/design-center/development-boards-and-designs/MIMXRT1015-EVK +mimxrt1020_evk i.MX RT1020 Evaluation Kit imxrt https://www.nxp.com/design/design-center/development-boards-and-designs/MIMXRT1020-EVK +mimxrt1024_evk i.MX RT1024 Evaluation Kit imxrt https://www.nxp.com/design/design-center/development-boards-and-designs/i-mx-evaluation-and-development-boards/i-mx-rt1024-evaluation-kit:MIMXRT1024-EVK +mimxrt1050_evkb i.MX RT1050 Evaluation Kit revB imxrt https://www.nxp.com/part/IMXRT1050-EVKB +mimxrt1060_evk i.MX RT1060 Evaluation Kit revB imxrt https://www.nxp.com/design/design-center/development-boards-and-designs/MIMXRT1060-EVKB +mimxrt1064_evk i.MX RT1064 Evaluation Kit imxrt https://www.nxp.com/design/design-center/development-boards-and-designs/MIMXRT1064-EVK +mimxrt1170_evkb i.MX RT1070 Evaluation Kit imxrt https://www.nxp.com/design/design-center/development-boards-and-designs/i-mx-evaluation-and-development-boards/i-mx-rt1170-evaluation-kit:MIMXRT1170-EVKB +teensy_40 Teensy 4.0 imxrt https://www.pjrc.com/store/teensy40.html +teensy_41 Teensy 4.1 imxrt https://www.pjrc.com/store/teensy41.html +frdm_k64f Freedom K64F kinetis_k https://www.nxp.com/design/design-center/development-boards-and-designs/general-purpose-mcus/freedom-development-platform-for-kinetis-k64-k63-and-k24-mcus:FRDM-K64F +teensy_35 Teensy 3.5 kinetis_k https://www.pjrc.com/store/teensy35.html +frdm_k32l2a4s Freedom K32L2A4S kinetis_k32l2 https://www.nxp.com/design/design-center/development-boards-and-designs/FRDM-K32L2A4S +frdm_k32l2b Freedom K32L2B3 kinetis_k32l2 https://www.nxp.com/design/design-center/development-boards-and-designs/general-purpose-mcus/nxp-freedom-development-platform-for-k32-l2b-mcus:FRDM-K32L2B3 +kuiic Kuiic kinetis_k32l2 https://github.com/nxf58843/kuiic +frdm_kl25z fomu kinetis_kl https://www.nxp.com/design/design-center/development-boards-and-designs/general-purpose-mcus/freedom-development-platform-for-kinetis-kl14-kl15-kl24-kl25-mcus:FRDM-KL25Z +lpcxpresso11u37 LPCXpresso11U37 lpc11 https://www.nxp.com/design/design-center/development-boards-and-designs/OM13074 +lpcxpresso11u68 LPCXpresso11U68 lpc11 https://www.nxp.com/design/design-center/development-boards-and-designs/OM13058 +lpcxpresso1347 LPCXpresso1347 lpc13 https://www.nxp.com/products/no-longer-manufactured/lpcxpresso-board-for-lpc1347:OM13045 +lpcxpresso1549 LPCXpresso1549 lpc15 https://www.nxp.com/design/design-center/development-boards-and-designs/OM13056 +lpcxpresso1769 LPCXpresso1769 lpc17 https://www.nxp.com/design/design-center/development-boards-and-designs/OM13000 +mbed1768 mbed 1768 lpc17 https://www.nxp.com/products/processors-and-microcontrollers/arm-microcontrollers/general-purpose-mcus/lpc1700-arm-cortex-m3/arm-mbed-lpc1768-board:OM11043 +lpcxpresso18s37 LPCXpresso18s37 lpc18 https://www.nxp.com/design/design-center/software/development-software/mcuxpresso-software-and-tools-/lpcxpresso-boards/lpcxpresso18s37-development-board:OM13076 +mcb1800 Keil MCB1800 lpc18 https://www.keil.com/arm/mcb1800/ +ea4088_quickstart Embedded Artists LPC4088 QuickStart Board lpc40 https://www.embeddedartists.com/products/lpc4088-quickstart-board/ +ea4357 Embedded Artists LPC4357 Development Kit lpc43 https://www.embeddedartists.com/products/lpc4357-developers-kit/ +lpcxpresso43s67 LPCXpresso43S67 lpc43 https://www.nxp.com/design/design-center/software/development-software/mcuxpresso-software-and-tools-/lpcxpresso-boards/lpcxpresso43s67-development-board:OM13084 +lpcxpresso51u68 LPCXpresso51u68 lpc51 https://www.nxp.com/products/processors-and-microcontrollers/arm-microcontrollers/general-purpose-mcus/lpcxpresso51u68-for-the-lpc51u68-mcus:OM40005 +lpcxpresso54114 LPCXpresso54114 lpc54 https://www.nxp.com/design/design-center/software/development-software/mcuxpresso-software-and-tools-/lpcxpresso-boards/lpcxpresso54114-board:OM13089 +lpcxpresso54608 LPCXpresso54608 lpc54 https://www.nxp.com/design/design-center/software/development-software/mcuxpresso-software-and-tools-/lpcxpresso-development-board-for-lpc5460x-mcus:OM13092 +lpcxpresso54628 LPCXpresso54628 lpc54 https://www.nxp.com/design/design-center/software/development-software/mcuxpresso-software-and-tools-/lpcxpresso-boards/lpcxpresso54628-development-board:OM13098 +double_m33_express Double M33 Express lpc55 https://www.crowdsupply.com/steiert-solutions/double-m33-express +lpcxpresso55s28 LPCXpresso55s28 lpc55 https://www.nxp.com/design/design-center/software/development-software/mcuxpresso-software-and-tools-/lpcxpresso-boards/lpcxpresso55s28-development-board:LPC55S28-EVK +lpcxpresso55s69 LPCXpresso55s69 lpc55 https://www.nxp.com/design/design-center/software/development-software/mcuxpresso-software-and-tools-/lpcxpresso-boards/lpcxpresso55s69-development-board:LPC55S69-EVK +mcu_link MCU Link lpc55 https://www.nxp.com/design/design-center/software/development-software/mcuxpresso-software-and-tools-/mcu-link-debug-probe:MCU-LINK +frdm_mcxa153 Freedom MCXA153 mcx https://www.nxp.com/design/design-center/development-boards-and-designs/FRDM-MCXA153 +frdm_mcxa156 Freedom MCXA156 mcx https://www.nxp.com/design/design-center/development-boards-and-designs/FRDM-MCXA156 +frdm_mcxn947 Freedom MCXN947 mcx https://www.nxp.com/design/design-center/development-boards-and-designs/FRDM-MCXN947 +mcxn947brk MCXN947 Breakout mcx n/a +================== ========================================= ============= ========================================================================================================================================================================= ====== + +Nordic Semiconductor +-------------------- + +=========================== ===================================== ======== ============================================================================== ====== +Board Name Family URL Note +=========================== ===================================== ======== ============================================================================== ====== +adafruit_clue Adafruit CLUE nrf https://www.adafruit.com/product/4500 +arduino_nano33_ble Arduino Nano 33 BLE nrf https://store.arduino.cc/arduino-nano-33-ble +circuitplayground_bluefruit Adafruit Circuit Playground Bluefruit nrf https://www.adafruit.com/product/4333 +feather_nrf52840_express Adafruit Feather nRF52840 Express nrf https://www.adafruit.com/product/4062 +feather_nrf52840_sense Adafruit Feather nRF52840 Sense nrf https://www.adafruit.com/product/4516 +itsybitsy_nrf52840 Adafruit ItsyBitsy nRF52840 Express nrf https://www.adafruit.com/product/4481 +pca10056 Nordic nRF52840DK nrf https://www.nordicsemi.com/Software-and-Tools/Development-Kits/nRF52840-DK +pca10059 Nordic nRF52840 Dongle nrf https://www.nordicsemi.com/Software-and-Tools/Development-Kits/nRF52840-Dongle +pca10095 Nordic nRF5340 DK nrf https://www.nordicsemi.com/Software-and-Tools/Development-Kits/nRF5340-DK +pca10100 Nordic nRF52833 DK nrf https://www.nordicsemi.com/Software-and-Tools/Development-Kits/nRF52833-DK +=========================== ===================================== ======== ============================================================================== ====== + +Raspberry Pi +------------ + +================================ ============================================ ============== ========================================================== ====== +Board Name Family URL Note +================================ ============================================ ============== ========================================================== ====== +raspberrypi_zero Raspberry Pi Zero broadcom_32bit https://www.raspberrypi.org/products/raspberry-pi-zero/ +raspberrypi_cm4 Raspberry CM4 broadcom_64bit https://www.raspberrypi.org/products/compute-module-4 +raspberrypi_zero2 Raspberry Zero2 broadcom_64bit https://www.raspberrypi.org/products/raspberry-pi-zero-2-w +adafruit_feather_rp2040_usb_host Adafruit Feather RP2040 with USB Type A Host rp2040 https://www.adafruit.com/product/5723 +adafruit_fruit_jam Adafruit Fruit Jam - Mini RP2350 rp2040 https://www.adafruit.com/product/6200 +adafruit_metro_rp2350 Adafruit Metro RP2350 rp2040 https://www.adafruit.com/product/6003 +raspberry_pi_pico Pico rp2040 https://www.raspberrypi.com/products/raspberry-pi-pico/ +raspberry_pi_pico2 Pico2 rp2040 https://www.raspberrypi.com/products/raspberry-pi-pico-2/ +raspberry_pi_pico_w Pico rp2040 https://www.raspberrypi.com/products/raspberry-pi-pico/ +================================ ============================================ ============== ========================================================== ====== + +Renesas +------- + +============== =========================== ======== ================================================================================================================================================================ ====== +Board Name Family URL Note +============== =========================== ======== ================================================================================================================================================================ ====== +da14695_dk_usb DA14695-00HQDEVKT-U da1469x https://www.renesas.com/en/products/wireless-connectivity/bluetooth-low-energy/da14695-00hqdevkt-u-smartbond-da14695-bluetooth-low-energy-52-usb-development-kit +da1469x_dk_pro DA1469x Development Kit Pro da1469x https://lpccs-docs.renesas.com/um-b-090-da1469x_getting_started/DA1469x_The_hardware/DA1469x_The_hardware.html +portenta_c33 Arduino Portenta C33 ra https://www.arduino.cc/pro/hardware-product-portenta-c33/ +ra2a1_ek RA2A1 EK ra https://www.renesas.com/en/products/microcontrollers-microprocessors/ra-cortex-m-mcus/ek-ra2a1-evaluation-kit-ra2a1-mcu-group +ra4m1_ek RA4M1 EK ra https://www.renesas.com/en/products/microcontrollers-microprocessors/ra-cortex-m-mcus/ek-ra4m1-evaluation-kit-ra4m1-mcu-group +ra4m3_ek RA4M3 EK ra https://www.renesas.com/en/products/microcontrollers-microprocessors/ra-cortex-m-mcus/ek-ra4m3-evaluation-kit-ra4m3-mcu-group +ra6m1_ek RA6M1 EK ra https://www.renesas.com/en/products/microcontrollers-microprocessors/ra-cortex-m-mcus/ek-ra6m1-evaluation-kit-ra6m1-mcu-group +ra6m5_ek RA6M5 EK ra https://www.renesas.com/en/products/microcontrollers-microprocessors/ra-cortex-m-mcus/ek-ra6m5-evaluation-kit-ra6m5-mcu-group +ra8m1_ek RA8M1 EK ra https://www.renesas.com/en/products/microcontrollers-microprocessors/ra-cortex-m-mcus/ek-ra8m1-evaluation-kit-ra8m1-mcu-group +uno_r4 Arduino UNO R4 ra https://store-usa.arduino.cc/pages/uno-r4 +============== =========================== ======== ================================================================================================================================================================ ====== + +STMicroelectronics +------------------ + +=================== ================================= ========= ================================================================= ====== +Board Name Family URL Note +=================== ================================= ========= ================================================================= ====== +stm32c071nucleo STM32C071 Nucleo stm32c0 https://www.st.com/en/evaluation-tools/nucleo-g071rb.html +stm32f070rbnucleo STM32 F070 Nucleo stm32f0 https://www.st.com/en/evaluation-tools/nucleo-f070rb.html +stm32f072disco STM32 F072 Discovery stm32f0 https://www.st.com/en/evaluation-tools/32f072bdiscovery.html +stm32f072eval STM32 F072 Eval stm32f0 https://www.st.com/en/evaluation-tools/stm32072b-eval.html +stm32f103_bluepill STM32 F103 Bluepill stm32f1 https://stm32-base.org/boards/STM32F103C8T6-Blue-Pill +stm32f103_mini_2 STM32 F103 Mini v2 stm32f1 https://stm32-base.org/boards/STM32F103RCT6-STM32-Mini-V2.0 +stm32f103ze_iar IAR STM32 F103ze starter kit stm32f1 n/a +stm32f207nucleo STM32 F207 Nucleo stm32f2 https://www.st.com/en/evaluation-tools/nucleo-f207zg.html +stm32f303disco STM32 F303 Discovery stm32f3 https://www.st.com/en/evaluation-tools/stm32f3discovery.html +feather_stm32f405 Adafruit Feather STM32F405 stm32f4 https://www.adafruit.com/product/4382 +pyboardv11 Pyboard v1.1 stm32f4 https://www.adafruit.com/product/2390 +stm32f401blackpill STM32 F401 Blackpill stm32f4 https://stm32-base.org/boards/STM32F401CCU6-WeAct-Black-Pill-V1.2 +stm32f407blackvet STM32 F407 Blackvet stm32f4 https://stm32-base.org/boards/STM32F407VET6-STM32-F4VE-V2.0 +stm32f407disco STM32 F407 Discovery stm32f4 https://www.st.com/en/evaluation-tools/stm32f4discovery.html +stm32f411blackpill STM32 F411 Blackpill stm32f4 https://stm32-base.org/boards/STM32F411CEU6-WeAct-Black-Pill-V2.0 +stm32f411disco STM32 F411 Discovery stm32f4 https://www.st.com/en/evaluation-tools/32f411ediscovery.html +stm32f412disco STM32 F412 Discovery stm32f4 https://www.st.com/en/evaluation-tools/32f412gdiscovery.html +stm32f412nucleo STM32 F412 Nucleo stm32f4 https://www.st.com/en/evaluation-tools/nucleo-f412zg.html +stm32f439nucleo STM32 F439 Nucleo stm32f4 https://www.st.com/en/evaluation-tools/nucleo-f439zi.html +stlinkv3mini Stlink-v3 mini stm32f7 https://www.st.com/en/development-tools/stlink-v3mini.html +stm32f723disco STM32 F723 Discovery stm32f7 https://www.st.com/en/evaluation-tools/32f723ediscovery.html +stm32f746disco STM32 F746 Discovery stm32f7 https://www.st.com/en/evaluation-tools/32f746gdiscovery.html +stm32f746nucleo STM32 F746 Nucleo stm32f7 https://www.st.com/en/evaluation-tools/nucleo-f746zg.html +stm32f767nucleo STM32 F767 Nucleo stm32f7 https://www.st.com/en/evaluation-tools/nucleo-f767zi.html +stm32f769disco STM32 F769 Discovery stm32f7 https://www.st.com/en/evaluation-tools/32f769idiscovery.html +stm32g0b1nucleo STM32 G0B1 Nucleo stm32g0 https://www.st.com/en/evaluation-tools/nucleo-g0b1re.html +b_g474e_dpow1 STM32 B-G474E-DPOW1 Discovery kit stm32g4 https://www.st.com/en/evaluation-tools/b-g474e-dpow1.html +stm32g474nucleo STM32 G474 Nucleo stm32g4 https://www.st.com/en/evaluation-tools/nucleo-g474re.html +stm32g491nucleo STM32 G491 Nucleo stm32g4 https://www.st.com/en/evaluation-tools/nucleo-g491re.html +stm32h503nucleo STM32 H503 Nucleo stm32h5 https://www.st.com/en/evaluation-tools/nucleo-h503rb.html +stm32h563nucleo STM32 H563 Nucleo stm32h5 https://www.st.com/en/evaluation-tools/nucleo-h563zi.html +stm32h573i_dk STM32 H573i Discovery stm32h5 https://www.st.com/en/evaluation-tools/stm32h573i-dk.html +daisyseed Daisy Seed stm32h7 https://electro-smith.com/products/daisy-seed +stm32h723nucleo STM32 H723 Nucleo stm32h7 https://www.st.com/en/evaluation-tools/nucleo-h723zg.html +stm32h743eval STM32 H743 Eval stm32h7 https://www.st.com/en/evaluation-tools/stm32h743i-eval.html +stm32h743nucleo STM32 H743 Nucleo stm32h7 https://www.st.com/en/evaluation-tools/nucleo-h743zi.html +stm32h745disco STM32 H745 Discovery stm32h7 https://www.st.com/en/evaluation-tools/stm32h745i-disco.html +stm32h750_weact STM32 H750 WeAct stm32h7 https://www.adafruit.com/product/5032 +stm32h750bdk STM32 H750b Discovery Kit stm32h7 https://www.st.com/en/evaluation-tools/stm32h750b-dk.html +waveshare_openh743i Waveshare Open H743i stm32h7 https://www.waveshare.com/openh743i-c-standard.htm +stm32h7s3nucleo STM32 H7S3L8 Nucleo stm32h7rs https://www.st.com/en/evaluation-tools/nucleo-h7s3l8.html +stm32l052dap52 STM32 L052 DAP stm32l0 n/a +stm32l0538disco STM32 L0538 Discovery stm32l0 https://www.st.com/en/evaluation-tools/32l0538discovery.html +stm32l412nucleo STM32 L412 Nucleo stm32l4 https://www.st.com/en/evaluation-tools/nucleo-l412kb.html +stm32l476disco STM32 L476 Disco stm32l4 https://www.st.com/en/evaluation-tools/32l476gdiscovery.html +stm32l4p5nucleo STM32 L4P5 Nucleo stm32l4 https://www.st.com/en/evaluation-tools/nucleo-l4p5zg.html +stm32l4r5nucleo STM32 L4R5 Nucleo stm32l4 https://www.st.com/en/evaluation-tools/nucleo-l4r5zi.html +stm32n657nucleo STM32 N657X0-Q Nucleo stm32n6 https://www.st.com/en/evaluation-tools/nucleo-n657x0-q.html +b_u585i_iot2a STM32 B-U585i IOT2A Discovery kit stm32u5 https://www.st.com/en/evaluation-tools/b-u585i-iot02a.html +stm32u545nucleo STM32 U545 Nucleo stm32u5 https://www.st.com/en/evaluation-tools/nucleo-u545re-q.html +stm32u575eval STM32 U575 Eval stm32u5 https://www.st.com/en/evaluation-tools/stm32u575i-ev.html +stm32u575nucleo STM32 U575 Nucleo stm32u5 https://www.st.com/en/evaluation-tools/nucleo-u575zi-q.html +stm32u5a5nucleo STM32 U5a5 Nucleo stm32u5 https://www.st.com/en/evaluation-tools/nucleo-u5a5zj-q.html +stm32wb55nucleo STM32 P-NUCLEO-WB55 stm32wb https://www.st.com/en/evaluation-tools/p-nucleo-wb55.html +=================== ================================= ========= ================================================================= ====== + +Sunxi +----- + +======= ================= ======== ========================================= ====== +Board Name Family URL Note +======= ================= ======== ========================================= ====== +f1c100s Lctech Pi F1C200s f1c100s https://linux-sunxi.org/Lctech_Pi_F1C200s +======= ================= ======== ========================================= ====== + +Texas Instruments +----------------- + +================= ===================== ======== ========================================= ====== +Board Name Family URL Note +================= ===================== ======== ========================================= ====== +msp_exp430f5529lp MSP430F5529 LaunchPad msp430 https://www.ti.com/tool/MSP-EXP430F5529LP +msp_exp432e401y MSP432E401Y LaunchPad msp432e4 https://www.ti.com/tool/MSP-EXP432E401Y +ek_tm4c123gxl TM4C123G LaunchPad tm4c https://www.ti.com/tool/EK-TM4C123GXL +================= ===================== ======== ========================================= ====== + +Tomu +---- + +======= ====== ======== ========================= ====== +Board Name Family URL Note +======= ====== ======== ========================= ====== +fomu fomu fomu https://tomu.im/fomu.html +======= ====== ======== ========================= ====== + +WCH +--- + +================ ================ ======== ===================================================================== ====== +Board Name Family URL Note +================ ================ ======== ===================================================================== ====== +ch32f205r-r0 CH32F205r-r0 ch32f20x https://github.com/openwch/ch32f20x +ch32v103r_r1_1v0 CH32V103R-R1-1v1 ch32v10x https://github.com/openwch/ch32v103/tree/main/SCHPCB/CH32V103R-R1-1v1 +ch32v203c_r0_1v0 CH32V203C-R0-1v0 ch32v20x https://github.com/openwch/ch32v20x/tree/main/SCHPCB/CH32V203C-R0 +ch32v203g_r0_1v0 CH32V203G-R0-1v0 ch32v20x https://github.com/openwch/ch32v20x/tree/main/SCHPCB/CH32V203C-R0 +nanoch32v203 nanoCH32V203 ch32v20x https://github.com/wuxx/nanoCH32V203 +ch32v307v_r1_1v0 CH32V307V-R1-1v0 ch32v307 https://github.com/openwch/ch32v307/tree/main/SCHPCB/CH32V307V-R1-1v0 +================ ================ ======== ===================================================================== ====== diff --git a/docs/reference/dependencies.rst b/docs/reference/dependencies.rst index 65ee31f22..5104c6456 100644 --- a/docs/reference/dependencies.rst +++ b/docs/reference/dependencies.rst @@ -4,66 +4,74 @@ Dependencies MCU low-level peripheral driver and external libraries for building TinyUSB examples -======================================== ============================================================== ======================================== ========================================================================================================================================================================================================================================================================================================================== -Local Path Repo Commit Required by -======================================== ============================================================== ======================================== ========================================================================================================================================================================================================================================================================================================================== -hw/mcu/allwinner https://github.com/hathach/allwinner_driver.git 8e5e89e8e132c0fd90e72d5422e5d3d68232b756 fc100s -hw/mcu/analog/max32 https://github.com/analogdevicesinc/msdk.git b20b398d3e5e2007594e54a74ba3d2a2e50ddd75 max32650 max32666 max32690 max78002 -hw/mcu/bridgetek/ft9xx/ft90x-sdk https://github.com/BRTSG-FOSS/ft90x-sdk.git 91060164afe239fcb394122e8bf9eb24d3194eb1 brtmm90x -hw/mcu/broadcom https://github.com/adafruit/broadcom-peripherals.git 08370086080759ed54ac1136d62d2ad24c6fa267 broadcom_32bit broadcom_64bit -hw/mcu/gd/nuclei-sdk https://github.com/Nuclei-Software/nuclei-sdk.git 7eb7bfa9ea4fbeacfafe1d5f77d5a0e6ed3922e7 gd32vf103 -hw/mcu/infineon/mtb-xmclib-cat3 https://github.com/Infineon/mtb-xmclib-cat3.git daf5500d03cba23e68c2f241c30af79cd9d63880 xmc4000 -hw/mcu/microchip https://github.com/hathach/microchip_driver.git 9e8b37e307d8404033bb881623a113931e1edf27 sam3x samd11 samd21 samd51 samd5x_e5x same5x same7x saml2x samg -hw/mcu/mindmotion/mm32sdk https://github.com/hathach/mm32sdk.git b93e856211060ae825216c6a1d6aa347ec758843 mm32 -hw/mcu/nordic/nrfx https://github.com/NordicSemiconductor/nrfx.git 7c47cc0a56ce44658e6da2458e86cd8783ccc4a2 nrf -hw/mcu/nuvoton https://github.com/majbthrd/nuc_driver.git 2204191ec76283371419fbcec207da02e1bc22fa nuc -hw/mcu/nxp/lpcopen https://github.com/hathach/nxp_lpcopen.git b41cf930e65c734d8ec6de04f1d57d46787c76ae lpc11 lpc13 lpc15 lpc17 lpc18 lpc40 lpc43 -hw/mcu/nxp/mcux-sdk https://github.com/hathach/mcux-sdk.git 144f1eb7ea8c06512e12f12b27383601c0272410 kinetis_k kinetis_k32l2 kinetis_kl lpc51 lpc54 lpc55 mcx imxrt -hw/mcu/raspberry_pi/Pico-PIO-USB https://github.com/sekigon-gonnoc/Pico-PIO-USB.git fe9133fc513b82cc3dc62c67cb51f2339cf29ef7 rp2040 -hw/mcu/renesas/fsp https://github.com/renesas/fsp.git d52e5a6a59b7c638da860c2bb309b6e78e752ff8 ra -hw/mcu/renesas/rx https://github.com/kkitayam/rx_device.git 706b4e0cf485605c32351e2f90f5698267996023 rx -hw/mcu/silabs/cmsis-dfp-efm32gg12b https://github.com/cmsis-packs/cmsis-dfp-efm32gg12b.git f1c31b7887669cb230b3ea63f9b56769078960bc efm32 -hw/mcu/sony/cxd56/spresense-exported-sdk https://github.com/sonydevworld/spresense-exported-sdk.git 2ec2a1538362696118dc3fdf56f33dacaf8f4067 spresense -hw/mcu/st/cmsis_device_f0 https://github.com/STMicroelectronics/cmsis_device_f0.git 2fc25ee22264bc27034358be0bd400b893ef837e stm32f0 -hw/mcu/st/cmsis_device_f1 https://github.com/STMicroelectronics/cmsis_device_f1.git 6601104a6397299b7304fd5bcd9a491f56cb23a6 stm32f1 -hw/mcu/st/cmsis_device_f2 https://github.com/STMicroelectronics/cmsis_device_f2.git 182fcb3681ce116816feb41b7764f1b019ce796f stm32f2 -hw/mcu/st/cmsis_device_f3 https://github.com/STMicroelectronics/cmsis_device_f3.git 5e4ee5ed7a7b6c85176bb70a9fd3c72d6eb99f1b stm32f3 -hw/mcu/st/cmsis_device_f4 https://github.com/STMicroelectronics/cmsis_device_f4.git 2615e866fa48fe1ff1af9e31c348813f2b19e7ec stm32f4 -hw/mcu/st/cmsis_device_f7 https://github.com/STMicroelectronics/cmsis_device_f7.git 25b0463439303b7a38f0d27b161f7d2f3c096e79 stm32f7 -hw/mcu/st/cmsis_device_g0 https://github.com/STMicroelectronics/cmsis_device_g0.git 3a23e1224417f3f2d00300ecd620495e363f2094 stm32g0 -hw/mcu/st/cmsis_device_g4 https://github.com/STMicroelectronics/cmsis_device_g4.git ce822adb1dc552b3aedd13621edbc7fdae124878 stm32g4 -hw/mcu/st/cmsis_device_h5 https://github.com/STMicroelectronics/cmsis_device_h5.git cd2d1d579743de57b88ccaf61a968b9c05848ffc stm32h5 -hw/mcu/st/cmsis_device_h7 https://github.com/STMicroelectronics/cmsis_device_h7.git 60dc2c913203dc8629dc233d4384dcc41c91e77f stm32h7 -hw/mcu/st/cmsis_device_l0 https://github.com/STMicroelectronics/cmsis_device_l0.git 69cd5999fd40ae6e546d4905b21635c6ca1bcb92 stm32l0 -hw/mcu/st/cmsis_device_l1 https://github.com/STMicroelectronics/cmsis_device_l1.git 7f16ec0a1c4c063f84160b4cc6bf88ad554a823e stm32l1 -hw/mcu/st/cmsis_device_l4 https://github.com/STMicroelectronics/cmsis_device_l4.git 6ca7312fa6a5a460b5a5a63d66da527fdd8359a6 stm32l4 -hw/mcu/st/cmsis_device_l5 https://github.com/STMicroelectronics/cmsis_device_l5.git d922865fc0326a102c26211c44b8e42f52c1e53d stm32l5 -hw/mcu/st/cmsis_device_u5 https://github.com/STMicroelectronics/cmsis_device_u5.git 5ad9797c54ec3e55eff770fc9b3cd4a1aefc1309 stm32u5 -hw/mcu/st/cmsis_device_wb https://github.com/STMicroelectronics/cmsis_device_wb.git 9c5d1920dd9fabbe2548e10561d63db829bb744f stm32wb -hw/mcu/st/stm32f0xx_hal_driver https://github.com/STMicroelectronics/stm32f0xx_hal_driver.git 0e95cd88657030f640a11e690a8a5186c7712ea5 stm32f0 -hw/mcu/st/stm32f1xx_hal_driver https://github.com/STMicroelectronics/stm32f1xx_hal_driver.git 1dd9d3662fb7eb2a7f7d3bc0a4c1dc7537915a29 stm32f1 -hw/mcu/st/stm32f2xx_hal_driver https://github.com/STMicroelectronics/stm32f2xx_hal_driver.git c75ace9b908a9aca631193ebf2466963b8ea33d0 stm32f2 -hw/mcu/st/stm32f3xx_hal_driver https://github.com/STMicroelectronics/stm32f3xx_hal_driver.git 1761b6207318ede021706e75aae78f452d72b6fa stm32f3 -hw/mcu/st/stm32f4xx_hal_driver https://github.com/STMicroelectronics/stm32f4xx_hal_driver.git 04e99fbdabd00ab8f370f377c66b0a4570365b58 stm32f4 -hw/mcu/st/stm32f7xx_hal_driver https://github.com/STMicroelectronics/stm32f7xx_hal_driver.git f7ffdf6bf72110e58b42c632b0a051df5997e4ee stm32f7 -hw/mcu/st/stm32g0xx_hal_driver https://github.com/STMicroelectronics/stm32g0xx_hal_driver.git e911b12c7f67084d7f6b76157a4c0d4e2ec3779c stm32g0 -hw/mcu/st/stm32g4xx_hal_driver https://github.com/STMicroelectronics/stm32g4xx_hal_driver.git 8b4518417706d42eef5c14e56a650005abf478a8 stm32g4 -hw/mcu/st/stm32h5xx_hal_driver https://github.com/STMicroelectronics/stm32h5xx_hal_driver.git 2cf77de584196d619cec1b4586c3b9e2820a254e stm32h5 -hw/mcu/st/stm32h7xx_hal_driver https://github.com/STMicroelectronics/stm32h7xx_hal_driver.git d8461b980b59b1625207d8c4f2ce0a9c2a7a3b04 stm32h7 -hw/mcu/st/stm32l0xx_hal_driver https://github.com/STMicroelectronics/stm32l0xx_hal_driver.git fbdacaf6f8c82a4e1eb9bd74ba650b491e97e17b stm32l0 -hw/mcu/st/stm32l1xx_hal_driver https://github.com/STMicroelectronics/stm32l1xx_hal_driver.git 44efc446fa69ed8344e7fd966e68ed11043b35d9 stm32l1 -hw/mcu/st/stm32l4xx_hal_driver https://github.com/STMicroelectronics/stm32l4xx_hal_driver.git aee3d5bf283ae5df87532b781bdd01b7caf256fc stm32l4 -hw/mcu/st/stm32l5xx_hal_driver https://github.com/STMicroelectronics/stm32l5xx_hal_driver.git 675c32a75df37f39d50d61f51cb0dcf53f07e1cb stm32l5 -hw/mcu/st/stm32u5xx_hal_driver https://github.com/STMicroelectronics/stm32u5xx_hal_driver.git 4d93097a67928e9377e655ddd14622adc31b9770 stm32u5 -hw/mcu/st/stm32wbxx_hal_driver https://github.com/STMicroelectronics/stm32wbxx_hal_driver.git 2c5f06638be516c1b772f768456ba637f077bac8 stm32wb -hw/mcu/ti https://github.com/hathach/ti_driver.git 143ed6cc20a7615d042b03b21e070197d473e6e5 msp430 msp432e4 tm4c -hw/mcu/wch/ch32f20x https://github.com/openwch/ch32f20x.git 77c4095087e5ed2c548ec9058e655d0b8757663b ch32f20x -hw/mcu/wch/ch32v103 https://github.com/openwch/ch32v103.git 7578cae0b21f86dd053a1f781b2fc6ab99d0ec17 ch32v10x -hw/mcu/wch/ch32v20x https://github.com/openwch/ch32v20x.git c4c38f507e258a4e69b059ccc2dc27dde33cea1b ch32v20x -hw/mcu/wch/ch32v307 https://github.com/openwch/ch32v307.git 184f21b852cb95eed58e86e901837bc9fff68775 ch32v307 -lib/CMSIS_5 https://github.com/ARM-software/CMSIS_5.git 20285262657d1b482d132d20d755c8c330d55c1f imxrt kinetis_k32l2 kinetis_kl lpc51 lpc54 lpc55 mcx mm32 msp432e4 nrf ra saml2xlpc11 lpc13 lpc15 lpc17 lpc18 lpc40 lpc43stm32f0 stm32f1 stm32f2 stm32f3 stm32f4 stm32f7 stm32g0 stm32g4 stm32h5stm32h7 stm32l0 stm32l1 stm32l4 stm32l5 stm32u5 stm32wbsam3x samd11 samd21 samd51 samd5x_e5x same5x same7x saml2x samgtm4c -lib/FreeRTOS-Kernel https://github.com/FreeRTOS/FreeRTOS-Kernel.git cc0e0707c0c748713485b870bb980852b210877f all -lib/lwip https://github.com/lwip-tcpip/lwip.git 159e31b689577dbf69cf0683bbaffbd71fa5ee10 all -lib/sct_neopixel https://github.com/gsteiert/sct_neopixel.git e73e04ca63495672d955f9268e003cffe168fcd8 lpc55 -tools/uf2 https://github.com/microsoft/uf2.git c594542b2faa01cc33a2b97c9fbebc38549df80a all -======================================== ============================================================== ======================================== ========================================================================================================================================================================================================================================================================================================================== +======================================== ================================================================ ======================================== ====================================================================================================================================================================================================================================================================================================================================================== +Local Path Repo Commit Required by +======================================== ================================================================ ======================================== ====================================================================================================================================================================================================================================================================================================================================================== +hw/mcu/allwinner https://github.com/hathach/allwinner_driver.git 8e5e89e8e132c0fd90e72d5422e5d3d68232b756 fc100s +hw/mcu/analog/msdk https://github.com/analogdevicesinc/msdk.git b20b398d3e5e2007594e54a74ba3d2a2e50ddd75 maxim +hw/mcu/bridgetek/ft9xx/ft90x-sdk https://github.com/BRTSG-FOSS/ft90x-sdk.git 91060164afe239fcb394122e8bf9eb24d3194eb1 brtmm90x +hw/mcu/broadcom https://github.com/adafruit/broadcom-peripherals.git 08370086080759ed54ac1136d62d2ad24c6fa267 broadcom_32bit broadcom_64bit +hw/mcu/gd/nuclei-sdk https://github.com/Nuclei-Software/nuclei-sdk.git 7eb7bfa9ea4fbeacfafe1d5f77d5a0e6ed3922e7 gd32vf103 +hw/mcu/infineon/mtb-xmclib-cat3 https://github.com/Infineon/mtb-xmclib-cat3.git daf5500d03cba23e68c2f241c30af79cd9d63880 xmc4000 +hw/mcu/microchip https://github.com/hathach/microchip_driver.git 9e8b37e307d8404033bb881623a113931e1edf27 sam3x samd11 samd21 samd51 samd5x_e5x same5x same7x saml2x samg +hw/mcu/mindmotion/mm32sdk https://github.com/hathach/mm32sdk.git b93e856211060ae825216c6a1d6aa347ec758843 mm32 +hw/mcu/nordic/nrfx https://github.com/NordicSemiconductor/nrfx.git 7c47cc0a56ce44658e6da2458e86cd8783ccc4a2 nrf +hw/mcu/nuvoton https://github.com/majbthrd/nuc_driver.git 2204191ec76283371419fbcec207da02e1bc22fa nuc +hw/mcu/nxp/lpcopen https://github.com/hathach/nxp_lpcopen.git b41cf930e65c734d8ec6de04f1d57d46787c76ae lpc11 lpc13 lpc15 lpc17 lpc18 lpc40 lpc43 +hw/mcu/nxp/mcux-sdk https://github.com/nxp-mcuxpresso/mcux-sdk a1bdae309a14ec95a4f64a96d3315a4f89c397c6 kinetis_k kinetis_k32l2 kinetis_kl lpc51 lpc54 lpc55 mcx imxrt +hw/mcu/raspberry_pi/Pico-PIO-USB https://github.com/sekigon-gonnoc/Pico-PIO-USB.git 3c1eec341a5232640e4c00628b889b641af34b28 rp2040 +hw/mcu/renesas/fsp https://github.com/renesas/fsp.git edcc97d684b6f716728a60d7a6fea049d9870bd6 ra +hw/mcu/renesas/rx https://github.com/kkitayam/rx_device.git 706b4e0cf485605c32351e2f90f5698267996023 rx +hw/mcu/silabs/cmsis-dfp-efm32gg12b https://github.com/cmsis-packs/cmsis-dfp-efm32gg12b.git f1c31b7887669cb230b3ea63f9b56769078960bc efm32 +hw/mcu/sony/cxd56/spresense-exported-sdk https://github.com/sonydevworld/spresense-exported-sdk.git 2ec2a1538362696118dc3fdf56f33dacaf8f4067 spresense +hw/mcu/st/cmsis_device_c0 https://github.com/STMicroelectronics/cmsis_device_c0.git fb56b1b70c73b74eacda2a4bcc36886444364ab3 stm32c0 +hw/mcu/st/cmsis_device_f0 https://github.com/STMicroelectronics/cmsis_device_f0.git 2fc25ee22264bc27034358be0bd400b893ef837e stm32f0 +hw/mcu/st/cmsis_device_f1 https://github.com/STMicroelectronics/cmsis_device_f1.git 6601104a6397299b7304fd5bcd9a491f56cb23a6 stm32f1 +hw/mcu/st/cmsis_device_f2 https://github.com/STMicroelectronics/cmsis_device_f2.git 182fcb3681ce116816feb41b7764f1b019ce796f stm32f2 +hw/mcu/st/cmsis_device_f3 https://github.com/STMicroelectronics/cmsis_device_f3.git 5e4ee5ed7a7b6c85176bb70a9fd3c72d6eb99f1b stm32f3 +hw/mcu/st/cmsis_device_f4 https://github.com/STMicroelectronics/cmsis_device_f4.git 2615e866fa48fe1ff1af9e31c348813f2b19e7ec stm32f4 +hw/mcu/st/cmsis_device_f7 https://github.com/STMicroelectronics/cmsis_device_f7.git 25b0463439303b7a38f0d27b161f7d2f3c096e79 stm32f7 +hw/mcu/st/cmsis_device_g0 https://github.com/STMicroelectronics/cmsis_device_g0.git 3a23e1224417f3f2d00300ecd620495e363f2094 stm32g0 +hw/mcu/st/cmsis_device_g4 https://github.com/STMicroelectronics/cmsis_device_g4.git ce822adb1dc552b3aedd13621edbc7fdae124878 stm32g4 +hw/mcu/st/cmsis_device_h5 https://github.com/STMicroelectronics/cmsis_device_h5.git cd2d1d579743de57b88ccaf61a968b9c05848ffc stm32h5 +hw/mcu/st/cmsis_device_h7 https://github.com/STMicroelectronics/cmsis_device_h7.git 60dc2c913203dc8629dc233d4384dcc41c91e77f stm32h7 +hw/mcu/st/cmsis_device_h7rs https://github.com/STMicroelectronics/cmsis_device_h7rs.git 832649d1fd09bd901e9f68e979522e5c209ebf20 stm32h7rs +hw/mcu/st/cmsis_device_l0 https://github.com/STMicroelectronics/cmsis_device_l0.git 69cd5999fd40ae6e546d4905b21635c6ca1bcb92 stm32l0 +hw/mcu/st/cmsis_device_l1 https://github.com/STMicroelectronics/cmsis_device_l1.git 7f16ec0a1c4c063f84160b4cc6bf88ad554a823e stm32l1 +hw/mcu/st/cmsis_device_l4 https://github.com/STMicroelectronics/cmsis_device_l4.git 6ca7312fa6a5a460b5a5a63d66da527fdd8359a6 stm32l4 +hw/mcu/st/cmsis_device_l5 https://github.com/STMicroelectronics/cmsis_device_l5.git d922865fc0326a102c26211c44b8e42f52c1e53d stm32l5 +hw/mcu/st/cmsis_device_n6 https://github.com/STMicroelectronics/cmsis-device-n6.git f818b00f775444e8d19ef6cad822534c345e054f stm32n6 +hw/mcu/st/cmsis_device_u5 https://github.com/STMicroelectronics/cmsis_device_u5.git 5ad9797c54ec3e55eff770fc9b3cd4a1aefc1309 stm32u5 +hw/mcu/st/cmsis_device_wb https://github.com/STMicroelectronics/cmsis_device_wb.git d6a7fa2e7de084f5e5e47f2ab88b022fe9b50e5a stm32wb +hw/mcu/st/stm32-mfxstm32l152 https://github.com/STMicroelectronics/stm32-mfxstm32l152.git 7f4389efee9c6a655b55e5df3fceef5586b35f9b stm32h7 +hw/mcu/st/stm32c0xx_hal_driver https://github.com/STMicroelectronics/stm32c0xx_hal_driver.git 41253e2f1d7ae4a4d0c379cf63f5bcf71fcf8eb3 stm32c0 +hw/mcu/st/stm32f0xx_hal_driver https://github.com/STMicroelectronics/stm32f0xx_hal_driver.git 0e95cd88657030f640a11e690a8a5186c7712ea5 stm32f0 +hw/mcu/st/stm32f1xx_hal_driver https://github.com/STMicroelectronics/stm32f1xx_hal_driver.git 1dd9d3662fb7eb2a7f7d3bc0a4c1dc7537915a29 stm32f1 +hw/mcu/st/stm32f2xx_hal_driver https://github.com/STMicroelectronics/stm32f2xx_hal_driver.git c75ace9b908a9aca631193ebf2466963b8ea33d0 stm32f2 +hw/mcu/st/stm32f3xx_hal_driver https://github.com/STMicroelectronics/stm32f3xx_hal_driver.git 1761b6207318ede021706e75aae78f452d72b6fa stm32f3 +hw/mcu/st/stm32f4xx_hal_driver https://github.com/STMicroelectronics/stm32f4xx_hal_driver.git 04e99fbdabd00ab8f370f377c66b0a4570365b58 stm32f4 +hw/mcu/st/stm32f7xx_hal_driver https://github.com/STMicroelectronics/stm32f7xx_hal_driver.git f7ffdf6bf72110e58b42c632b0a051df5997e4ee stm32f7 +hw/mcu/st/stm32g0xx_hal_driver https://github.com/STMicroelectronics/stm32g0xx_hal_driver.git e911b12c7f67084d7f6b76157a4c0d4e2ec3779c stm32g0 +hw/mcu/st/stm32g4xx_hal_driver https://github.com/STMicroelectronics/stm32g4xx_hal_driver.git 8b4518417706d42eef5c14e56a650005abf478a8 stm32g4 +hw/mcu/st/stm32h5xx_hal_driver https://github.com/STMicroelectronics/stm32h5xx_hal_driver.git 2cf77de584196d619cec1b4586c3b9e2820a254e stm32h5 +hw/mcu/st/stm32h7rsxx_hal_driver https://github.com/STMicroelectronics/stm32h7rsxx-hal-driver.git 7ca2e07ca21bc66b53654e845b4c85c884343b60 stm32h7rs +hw/mcu/st/stm32h7xx_hal_driver https://github.com/STMicroelectronics/stm32h7xx_hal_driver.git d8461b980b59b1625207d8c4f2ce0a9c2a7a3b04 stm32h7 +hw/mcu/st/stm32l0xx_hal_driver https://github.com/STMicroelectronics/stm32l0xx_hal_driver.git fbdacaf6f8c82a4e1eb9bd74ba650b491e97e17b stm32l0 +hw/mcu/st/stm32l1xx_hal_driver https://github.com/STMicroelectronics/stm32l1xx_hal_driver.git 44efc446fa69ed8344e7fd966e68ed11043b35d9 stm32l1 +hw/mcu/st/stm32l4xx_hal_driver https://github.com/STMicroelectronics/stm32l4xx_hal_driver.git aee3d5bf283ae5df87532b781bdd01b7caf256fc stm32l4 +hw/mcu/st/stm32l5xx_hal_driver https://github.com/STMicroelectronics/stm32l5xx_hal_driver.git 675c32a75df37f39d50d61f51cb0dcf53f07e1cb stm32l5 +hw/mcu/st/stm32n6xx_hal_driver https://github.com/STMicroelectronics/stm32n6xx-hal-driver.git 49f9989d10cf6817d4b07ac01848956b46bd0fd6 stm32n6 +hw/mcu/st/stm32u5xx_hal_driver https://github.com/STMicroelectronics/stm32u5xx_hal_driver.git 4d93097a67928e9377e655ddd14622adc31b9770 stm32u5 +hw/mcu/st/stm32wbxx_hal_driver https://github.com/STMicroelectronics/stm32wbxx_hal_driver.git 2c5f06638be516c1b772f768456ba637f077bac8 stm32wb +hw/mcu/ti https://github.com/hathach/ti_driver.git 143ed6cc20a7615d042b03b21e070197d473e6e5 msp430 msp432e4 tm4c +hw/mcu/wch/ch32f20x https://github.com/openwch/ch32f20x.git 77c4095087e5ed2c548ec9058e655d0b8757663b ch32f20x +hw/mcu/wch/ch32v103 https://github.com/openwch/ch32v103.git 7578cae0b21f86dd053a1f781b2fc6ab99d0ec17 ch32v10x +hw/mcu/wch/ch32v20x https://github.com/openwch/ch32v20x.git c4c38f507e258a4e69b059ccc2dc27dde33cea1b ch32v20x +hw/mcu/wch/ch32v307 https://github.com/openwch/ch32v307.git 184f21b852cb95eed58e86e901837bc9fff68775 ch32v307 +lib/CMSIS_5 https://github.com/ARM-software/CMSIS_5.git 2b7495b8535bdcb306dac29b9ded4cfb679d7e5c imxrt kinetis_k32l2 kinetis_kl lpc51 lpc54 lpc55 mcx mm32 msp432e4 nrf saml2x lpc11 lpc13 lpc15 lpc17 lpc18 lpc40 lpc43 stm32c0 stm32f0 stm32f1 stm32f2 stm32f3 stm32f4 stm32f7 stm32g0 stm32g4 stm32h5 stm32h7 stm32h7rs stm32l0 stm32l1 stm32l4 stm32l5 stm32n6 stm32u5 stm32wb sam3x samd11 samd21 samd51 samd5x_e5x same5x same7x saml2x samg tm4c +lib/CMSIS_6 https://github.com/ARM-software/CMSIS_6.git b0bbb0423b278ca632cfe1474eb227961d835fd2 ra +lib/FreeRTOS-Kernel https://github.com/FreeRTOS/FreeRTOS-Kernel.git cc0e0707c0c748713485b870bb980852b210877f all +lib/lwip https://github.com/lwip-tcpip/lwip.git 159e31b689577dbf69cf0683bbaffbd71fa5ee10 all +lib/sct_neopixel https://github.com/gsteiert/sct_neopixel.git e73e04ca63495672d955f9268e003cffe168fcd8 lpc55 +tools/uf2 https://github.com/microsoft/uf2.git c594542b2faa01cc33a2b97c9fbebc38549df80a all +======================================== ================================================================ ======================================== ====================================================================================================================================================================================================================================================================================================================================================== diff --git a/docs/reference/getting_started.rst b/docs/reference/getting_started.rst index ac4ab6392..bb9ff1cb4 100644 --- a/docs/reference/getting_started.rst +++ b/docs/reference/getting_started.rst @@ -5,23 +5,32 @@ Getting Started Add TinyUSB to your project --------------------------- -It is relatively simple to incorporate tinyusb to your project +To incorporate tinyusb to your project -* Copy or ``git submodule`` this repo into your project in a subfolder. Let's say it is *your_project/tinyusb* -* Add all the .c in the ``tinyusb/src`` folder to your project -* Add *your_project/tinyusb/src* to your include path. Also make sure your current include path also contains the configuration file tusb_config.h. -* Make sure all required macros are all defined properly in tusb_config.h (configure file in demo application is sufficient, but you need to add a few more such as CFG_TUSB_MCU, CFG_TUSB_OS since they are passed by IDE/compiler to maintain a unique configure for all boards). +* Copy or ``git submodule`` this repo into your project in a subfolder. Let's say it is ``your_project/tinyusb`` +* Add all the ``.c`` in the ``tinyusb/src`` folder to your project +* Add ``your_project/tinyusb/src`` to your include path. Also make sure your current include path also contains the configuration file ``tusb_config.h``. +* Make sure all required macros are all defined properly in ``tusb_config.h`` (configure file in demo application is sufficient, but you need to add a few more such as ``CFG_TUSB_MCU``, ``CFG_TUSB_OS`` since they are passed by make/cmake to maintain a unique configure for all boards). * If you use the device stack, make sure you have created/modified usb descriptors for your own need. Ultimately you need to implement all **tud descriptor** callbacks for the stack to work. -* Add tusb_init(rhport, role) call to your reset initialization code. +* Add ``tusb_init(rhport, role)`` call to your reset initialization code. * Call ``tusb_int_handler(rhport, in_isr)`` in your USB IRQ Handler * Implement all enabled classes's callbacks. -* If you don't use any RTOSes at all, you need to continuously and/or periodically call tud_task()/tuh_task() function. All of the callbacks and functionality are handled and invoked within the call of that task runner. +* If you don't use any RTOSes at all, you need to continuously and/or periodically call ``tud_task()``/``tuh_task()`` function. All of the callbacks and functionality are handled and invoked within the call of that task runner. -.. code-block:: +.. code-block:: c int main(void) { - your_init_code(); - tusb_init(0, TUSB_ROLE_DEVICE); // initialize device stack on roothub port 0 + tusb_rhport_init_t dev_init = { + .role = TUSB_ROLE_DEVICE, + .speed = TUSB_SPEED_AUTO + }; + tusb_init(0, &dev_init); // initialize device stack on roothub port 0 + + tusb_rhport_init_t host_init = { + .role = TUSB_ROLE_HOST, + .speed = TUSB_SPEED_AUTO + }; + tusb_init(1, &host_init); // initialize host stack on roothub port 1 while(1) { // the mainloop your_application_code(); @@ -30,12 +39,20 @@ It is relatively simple to incorporate tinyusb to your project } } + void USB0_IRQHandler(void) { + tusb_int_handler(0, true); + } + + void USB1_IRQHandler(void) { + tusb_int_handler(1, true); + } + Examples -------- -For your convenience, TinyUSB contains a handful of examples for both host and device with/without RTOS to quickly test the functionality as well as demonstrate how API() should be used. Most examples will work on most of `the supported boards `_. Firstly we need to ``git clone`` if not already +For your convenience, TinyUSB contains a handful of examples for both host and device with/without RTOS to quickly test the functionality as well as demonstrate how API should be used. Most examples will work on most of `the supported boards `_. Firstly we need to ``git clone`` if not already -.. code-block:: +.. code-block:: bash $ git clone https://github.com/hathach/tinyusb tinyusb $ cd tinyusb @@ -45,41 +62,53 @@ Some ports will also require a port-specific SDK (e.g. RP2040) or binary (e.g. S Dependencies ^^^^^^^^^^^^ -The hardware code is located in ``hw/bsp`` folder, and is organized by family/boards. e.g raspberry_pi_pico is located in ``hw/bsp/rp2040/boards/raspberry_pi_pico`` where FAMILY=rp2040 and BOARD=raspberry_pi_pico. Before building, we firstly need to download dependencies such as: MCU low-level peripheral driver and external libraries e.g FreeRTOS (required by some examples). We can do that by either ways: +The hardware code is located in ``hw/bsp`` folder, and is organized by family/boards. e.g raspberry_pi_pico is located in ``hw/bsp/rp2040/boards/raspberry_pi_pico`` where ``FAMILY=rp2040`` and ``BOARD=raspberry_pi_pico``. Before building, we firstly need to download dependencies such as: MCU low-level peripheral driver and external libraries e.g FreeRTOS (required by some examples). We can do that by either ways: 1. Run ``tools/get_deps.py {FAMILY}`` script to download all dependencies for a family as follow. Note: For TinyUSB developer to download all dependencies, use FAMILY=all. -.. code-block:: +.. code-block:: bash $ python tools/get_deps.py rp2040 2. Or run the ``get-deps`` target in one of the example folder as follow. -.. code-block:: +.. code-block:: bash $ cd examples/device/cdc_msc - $ make BOARD=raspberry_pi_pico get-deps + $ make BOARD=feather_nrf52840_express get-deps You only need to do this once per family. Check out `complete list of dependencies and their designated path here `_ -Build -^^^^^ +Build Examples +^^^^^^^^^^^^^^ -To build example, first change directory to an example folder. +Examples support make and cmake build system for most MCUs, however some MCU families such as espressif or rp2040 only support cmake. First change directory to an example folder. -.. code-block:: +.. code-block:: bash $ cd examples/device/cdc_msc -Then compile with ``make BOARD={board_name} all`` , for example +Then compile with make or cmake -.. code-block:: +.. code-block:: bash - $ make BOARD=raspberry_pi_pico all + $ # make + $ make BOARD=feather_nrf52840_express all + + $ # cmake + $ mkdir build && cd build + $ cmake -DBOARD=raspberry_pi_pico .. + $ make + +To list all available targets with cmake + +.. code-block:: bash + + $ cmake --build . --target help Note: some examples especially those that uses Vendor class (e.g webUSB) may requires udev permission on Linux (and/or macOS) to access usb device. It depends on your OS distro, typically copy ``99-tinyusb.rules`` and reload your udev is good to go -.. code-block:: +.. code-block:: bash $ cp examples/device/99-tinyusb.rules /etc/udev/rules.d/ $ sudo udevadm control --reload-rules && sudo udevadm trigger @@ -87,27 +116,31 @@ Note: some examples especially those that uses Vendor class (e.g webUSB) may req RootHub Port Selection ~~~~~~~~~~~~~~~~~~~~~~ -If a board has several ports, one port is chosen by default in the individual board.mk file. Use option ``PORT=x`` To choose another port. For example to select the HS port of a STM32F746Disco board, use: +If a board has several ports, one port is chosen by default in the individual board.mk file. Use option ``RHPORT_DEVICE=x`` or ``RHPORT_HOST=x`` To choose another port. For example to select the HS port of a STM32F746Disco board, use: -.. code-block:: +.. code-block:: bash - $ make BOARD=stm32f746disco PORT=1 all + $ make BOARD=stm32f746disco RHPORT_DEVICE=1 all + + $ cmake -DBOARD=stm32f746disco -DRHPORT_DEVICE=1 .. Port Speed ~~~~~~~~~~ -A MCU can support multiple operational speed. By default, the example build system will use the fastest supported on the board. Use option ``SPEED=full/high`` e.g To force F723 operate at full instead of default high speed +A MCU can support multiple operational speed. By default, the example build system will use the fastest supported on the board. Use option ``RHPORT_DEVICE_SPEED=OPT_MODE_FULL/HIGH_SPEED/`` or ``RHPORT_HOST_SPEED=OPT_MODE_FULL/HIGH_SPEED/`` e.g To force F723 operate at full instead of default high speed -.. code-block:: +.. code-block:: bash - $ make BOARD=stm32f746disco SPEED=full all + $ make BOARD=stm32f746disco RHPORT_DEVICE_SPEED=OPT_MODE_FULL_SPEED all + + $ cmake -DBOARD=stm32f746disco -DRHPORT_DEVICE_SPEED=OPT_MODE_FULL_SPEED .. Size Analysis ~~~~~~~~~~~~~ -First install `linkermap tool `_ then ``linkermap`` target can be used to analyze code size. You may want to compile with ``NO_LTO=1`` since -flto merges code across .o files and make it difficult to analyze. +First install `linkermap tool `_ then ``linkermap`` target can be used to analyze code size. You may want to compile with ``NO_LTO=1`` since ``-flto`` merges code across ``.o`` files and make it difficult to analyze. -.. code-block:: +.. code-block:: bash $ make BOARD=feather_nrf52840_express NO_LTO=1 all linkermap @@ -116,19 +149,23 @@ Debug To compile for debugging add ``DEBUG=1``\ , for example -.. code-block:: +.. code-block:: bash $ make BOARD=feather_nrf52840_express DEBUG=1 all + $ cmake -DBOARD=feather_nrf52840_express -DCMAKE_BUILD_TYPE=Debug .. + Log ~~~ -Should you have an issue running example and/or submitting an bug report. You could enable TinyUSB built-in debug logging with optional ``LOG=``. LOG=1 will only print out error message, LOG=2 print more information with on-going events. LOG=3 or higher is not used yet. +Should you have an issue running example and/or submitting an bug report. You could enable TinyUSB built-in debug logging with optional ``LOG=``. ``LOG=1`` will only print out error message, ``LOG=2`` print more information with on-going events. ``LOG=3`` or higher is not used yet. -.. code-block:: +.. code-block:: bash $ make BOARD=feather_nrf52840_express LOG=2 all + $ cmake -DBOARD=feather_nrf52840_express -DLOG=2 .. + Logger ~~~~~~ @@ -147,74 +184,80 @@ By default log message is printed via on-board UART which is slow and take lots * Pros: should be compatible with more debugger that support SWO. * Software viewer should be provided along with your debugger driver. -.. code-block:: +.. code-block:: bash $ make BOARD=feather_nrf52840_express LOG=2 LOGGER=rtt all $ make BOARD=feather_nrf52840_express LOG=2 LOGGER=swo all + $ cmake -DBOARD=feather_nrf52840_express -DLOG=2 -DLOGGER=rtt .. + $ cmake -DBOARD=feather_nrf52840_express -DLOG=2 -DLOGGER=swo .. + Flash ^^^^^ ``flash`` target will use the default on-board debugger (jlink/cmsisdap/stlink/dfu) to flash the binary, please install those support software in advance. Some board use bootloader/DFU via serial which is required to pass to make command -.. code-block:: +.. code-block:: bash $ make BOARD=feather_nrf52840_express flash $ make SERIAL=/dev/ttyACM0 BOARD=feather_nrf52840_express flash -Since jlink can be used with most of the boards, there is also ``flash-jlink`` target for your convenience. +Since jlink/openocd can be used with most of the boards, there is also ``flash-jlink/openocd`` (make) and ``EXAMPLE-jlink/openocd`` target for your convenience. Note for stm32 board with stlink, you can use ``flash-stlink`` target as well. -.. code-block:: +.. code-block:: bash $ make BOARD=feather_nrf52840_express flash-jlink + $ make BOARD=feather_nrf52840_express flash-openocd + + $ cmake --build . --target cdc_msc-jlink + $ cmake --build . --target cdc_msc-openocd Some board use uf2 bootloader for drag & drop in to mass storage device, uf2 can be generated with ``uf2`` target -.. code-block:: +.. code-block:: bash $ make BOARD=feather_nrf52840_express all uf2 + $ cmake --build . --target cdc_msc-uf2 + IAR Support ------------ +^^^^^^^^^^^ Use project connection -^^^^^^^^^^^^^^^^^^^^^^ +~~~~~~~~~~~~~~~~~~~~~~ IAR Project Connection files are provided to import TinyUSB stack into your project. -* A buldable project of your MCU need to be created in advance. - +* A buildable project of your MCU need to be created in advance. * Take example of STM32F0: - - You need `stm32l0xx.h`, `startup_stm32f0xx.s`, `system_stm32f0xx.c`. + - You need ``stm32l0xx.h``, ``startup_stm32f0xx.s``, ``system_stm32f0xx.c``. - - `STM32L0xx_HAL_Driver` is only needed to run examples, TinyUSB stack itself doesn't rely on MCU's SDKs. + - ``STM32L0xx_HAL_Driver`` is only needed to run examples, TinyUSB stack itself doesn't rely on MCU's SDKs. -* Open ``Tools -> Configure Custom Argument Variables`` (Switch to `Global` tab if you want to do it for all your projects) - Click `New Group ...`, name it to `TUSB`, Click `Add Variable ...`, name it to `TUSB_DIR`, change it's value to the path of your TinyUSB stack, - for example `C:\\tinyusb` +* Open ``Tools -> Configure Custom Argument Variables`` (Switch to ``Global`` tab if you want to do it for all your projects) + Click ``New Group ...``, name it to ``TUSB``, Click ``Add Variable ...``, name it to ``TUSB_DIR``, change it's value to the path of your TinyUSB stack, + for example ``C:\\tinyusb`` -Import stack only -~~~~~~~~~~~~~~~~~ +**Import stack only** -1. Open ``Project -> Add project Connection ...``, click `OK`, choose `tinyusb\\tools\\iar_template.ipcf`. +Open ``Project -> Add project Connection ...``, click ``OK``, choose ``tinyusb\\tools\\iar_template.ipcf``. -Run examples -~~~~~~~~~~~~ +**Run examples** -1. (Python3 is needed) Run ``iar_gen.py`` to generate .ipcf files of examples: +1. Run ``iar_gen.py`` to generate .ipcf files of examples: .. code-block:: - cd C:\tinyusb\tools - python iar_gen.py + > cd C:\tinyusb\tools + > python iar_gen.py -2. Open `Project -> Add project Connection ...`, click `OK`, choose `tinyusb\\examples\\(.ipcf of example)`. - For example `C:\\tinyusb\\examples\\device\\cdc_msc\\iar_cdc_msc.ipcf` +2. Open ``Project -> Add project Connection ...``, click ``OK``, choose ``tinyusb\\examples\\(.ipcf of example)``. + For example ``C:\\tinyusb\\examples\\device\\cdc_msc\\iar_cdc_msc.ipcf`` -Native CMake support (9.50.1+) -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Native CMake support +~~~~~~~~~~~~~~~~~~~~ With 9.50.1 release, IAR added experimental native CMake support (strangely not mentioned in public release note). Now it's possible to import CMakeLists.txt then build and debug as a normal project. @@ -222,5 +265,5 @@ Following these steps: 1. Add IAR compiler binary path to system ``PATH`` environment variable, such as ``C:\Program Files\IAR Systems\Embedded Workbench 9.2\arm\bin``. 2. Create new project in IAR, in Tool chain dropdown menu, choose CMake for Arm then Import ``CMakeLists.txt`` from chosen example directory. -3. Set up board option in ``Option - CMake/CMSIS-TOOLBOX - CMake``, for example :code:`-DBOARD=stm32f439nucleo -DTOOLCHAIN=iar`, **Uncheck 'Override tools in env'**. +3. Set up board option in ``Option - CMake/CMSIS-TOOLBOX - CMake``, for example ``-DBOARD=stm32f439nucleo -DTOOLCHAIN=iar``, **Uncheck 'Override tools in env'**. 4. (For debug only) Choose correct CPU model in ``Option - General Options - Target``, to profit register and memory view. diff --git a/docs/reference/index.rst b/docs/reference/index.rst index 9ecdf619b..8ac3cf924 100644 --- a/docs/reference/index.rst +++ b/docs/reference/index.rst @@ -1,85 +1,10 @@ -********* -Reference -********* - -.. figure:: ../assets/stack.svg - :width: 1600px - :alt: TinyUSB - -:: - - . - ├── docs # Documentation - ├── examples # Examples with make and cmake build system - ├── hw - │ ├── bsp # Supported boards source files - │ └── mcu # Low level mcu core & peripheral drivers - ├── lib # Sources from 3rd party such as freeRTOS, fatfs ... - ├── src # All sources files for TinyUSB stack itself. - ├── test # Tests: unit test, fuzzing, hardware test - └── tools # Files used internally - - -Device Stack -============ - -Supports multiple device configurations by dynamically changing USB descriptors, low power functions such like suspend, resume, and remote wakeup. The following device classes are supported: - -- Audio Class 2.0 (UAC2) -- Bluetooth Host Controller Interface (BTH HCI) -- Communication Device Class (CDC) -- Device Firmware Update (DFU): DFU mode (WIP) and Runtime -- Human Interface Device (HID): Generic (In & Out), Keyboard, Mouse, Gamepad etc ... -- Mass Storage Class (MSC): with multiple LUNs -- Musical Instrument Digital Interface (MIDI) -- Network with RNDIS, Ethernet Control Model (ECM), Network Control Model (NCM) -- Test and Measurement Class (USBTMC) -- Video class 1.5 (UVC): work in progress -- Vendor-specific class support with generic In & Out endpoints. Can be used with MS OS 2.0 compatible descriptor to load winUSB driver without INF file. -- `WebUSB `__ with vendor-specific class - -If you have a special requirement, `usbd_app_driver_get_cb()` can be used to write your own class driver without modifying the stack. Here is how the RPi team added their reset interface `raspberrypi/pico-sdk#197 `_ - -Host Stack -========== - -- Human Interface Device (HID): Keyboard, Mouse, Generic -- Mass Storage Class (MSC) -- Communication Device Class: CDC-ACM -- Vendor serial over USB: FTDI, CP210x -- Hub with multiple-level support - -Similar to the Device Stack, if you have a special requirement, `usbh_app_driver_get_cb()` can be used to write your own class driver without modifying the stack. - -TypeC PD Stack -============== - -- Power Delivery 3.0 (PD3.0) with USB Type-C support (WIP) -- Super early stage, only for testing purpose -- Only support STM32 G4 - -OS Abstraction layer -==================== - -TinyUSB is completely thread-safe by pushing all Interrupt Service Request (ISR) events into a central queue, then processing them later in the non-ISR context task function. It also uses semaphore/mutex to access shared resources such as Communication Device Class (CDC) FIFO. Therefore the stack needs to use some of the OS's basic APIs. Following OSes are already supported out of the box. - -- **No OS** -- **FreeRTOS** -- `RT-Thread `_: `repo `_ -- **Mynewt** Due to the newt package build system, Mynewt examples are better to be on its `own repo `_ - -License -======= - -All TinyUSB sources in the `src` folder are licensed under MIT license. However, each file can be individually licensed especially those in `lib` and `hw/mcu` folder. Please make sure you understand all the license term for files you use in your project. - Index ===== .. toctree:: :maxdepth: 2 - supported getting_started + boards dependencies concurrency diff --git a/docs/reference/supported.rst b/docs/reference/supported.rst deleted file mode 100644 index cbd6c4786..000000000 --- a/docs/reference/supported.rst +++ /dev/null @@ -1,442 +0,0 @@ -***************** -Supported Devices -***************** - -Supported MCUs -============== - -+--------------+-----------------------------+--------+------+-----------+------------------------+-------------------+ -| Manufacturer | Family | Device | Host | Highspeed | Driver | Note | -+==============+=============================+========+======+===========+========================+===================+ -| Allwinner | F1C100s/F1C200s | ✔ | | ✔ | sunxi | musb variant | -+--------------+-----------------------------+--------+------+-----------+------------------------+-------------------+ -| Analog | MAX3421E | | ✔ | ✖ | max3421 | via SPI | -| +-----------------------------+--------+------+-----------+------------------------+-------------------+ -| | MAX32 650, 666, 690, | ✔ | | ✔ | musb | 1-dir ep | -| | MAX78002 | | | | | | -+--------------+-----------------------------+--------+------+-----------+------------------------+-------------------+ -| Brigetek | FT90x | ✔ | | ✔ | ft9xx | 1-dir ep | -+--------------+-----------------------------+--------+------+-----------+------------------------+-------------------+ -| Broadcom | BCM2711, BCM2837 | ✔ | | ✔ | dwc2 | | -+--------------+-----------------------------+--------+------+-----------+------------------------+-------------------+ -| Dialog | DA1469x | ✔ | ✖ | ✖ | da146xx | | -+--------------+-----------------------------+--------+------+-----------+------------------------+-------------------+ -| Espressif | S2, S3 | ✔ | ✔ | ✖ | dwc2 or esp32sx | | -| ESP32 +-----------------------------+--------+------+-----------+------------------------+-------------------+ -| | P4 | ✔ | ✔ | ✔ | dwc2 | | -+--------------+----+------------------------+--------+------+-----------+------------------------+-------------------+ -| GigaDevice | GD32VF103 | ✔ | | ✖ | dwc2 | | -+--------------+-----------------------------+--------+------+-----------+------------------------+-------------------+ -| Infineon | XMC4500 | ✔ | ✔ | ✖ | dwc2 | | -+--------------+-----+-----------------------+--------+------+-----------+------------------------+-------------------+ -| MicroChip | SAM | D11, D21, L21, L22 | ✔ | | ✖ | samd | | -| | +-----------------------+--------+------+-----------+------------------------+-------------------+ -| | | D51, E5x | ✔ | | ✖ | samd | | -| | +-----------------------+--------+------+-----------+------------------------+-------------------+ -| | | G55 | ✔ | | ✖ | samg | 1-dir ep | -| | +-----------------------+--------+------+-----------+------------------------+-------------------+ -| | | E70,S70,V70,V71 | ✔ | | ✔ | samx7x | 1-dir ep | -| +-----+-----------------------+--------+------+-----------+------------------------+-------------------+ -| | PIC | 24 | ✔ | | | pic | ci_fs variant | -| | +-----------------------+--------+------+-----------+------------------------+-------------------+ -| | | 32 mm, mk, mx | ✔ | | | pic | ci_fs variant | -| | +-----------------------+--------+------+-----------+------------------------+-------------------+ -| | | dsPIC33 | ✔ | | | pic | ci_fs variant | -| | +-----------------------+--------+------+-----------+------------------------+-------------------+ -| | | 32mz | ✔ | | | pic32mz | musb variant | -+--------------+-----+-----------------------+--------+------+-----------+------------------------+-------------------+ -| Mind Montion | mm32 | ✔ | | ✖ | mm32f327x_otg | ci_fs variant | -+--------------+-----+-----------------------+--------+------+-----------+------------------------+-------------------+ -| NordicSemi | nRF 52833, 52840, 5340 | ✔ | ✖ | ✖ | nrf5x | only ep8 is ISO | -+--------------+-----------------------------+--------+------+-----------+------------------------+-------------------+ -| Nuvoton | NUC120 | ✔ | ✖ | ✖ | nuc120 | | -| +-----------------------------+--------+------+-----------+------------------------+-------------------+ -| | NUC121/NUC125 | ✔ | ✖ | ✖ | nuc121 | | -| +-----------------------------+--------+------+-----------+------------------------+-------------------+ -| | NUC126 | ✔ | ✖ | ✖ | nuc121 | | -| +-----------------------------+--------+------+-----------+------------------------+-------------------+ -| | NUC505 | ✔ | | ✔ | nuc505 | | -+--------------+---------+-------------------+--------+------+-----------+------------------------+-------------------+ -| NXP | iMXRT | RT 10xx, 11xx | ✔ | ✔ | ✔ | ci_hs | | -| +---------+-------------------+--------+------+-----------+------------------------+-------------------+ -| | Kinetis | KL | ✔ | ⚠ | ✖ | ci_fs, khci | | -| | +-------------------+--------+------+-----------+------------------------+-------------------+ -| | | K32L2 | ✔ | | ✖ | khci | ci_fs variant | -| +---------+-------------------+--------+------+-----------+------------------------+-------------------+ -| | LPC | 11u, 13, 15 | ✔ | ✖ | ✖ | lpc_ip3511 | | -| | +-------------------+--------+------+-----------+------------------------+-------------------+ -| | | 17, 40 | ✔ | ⚠ | ✖ | lpc17_40 | | -| | +-------------------+--------+------+-----------+------------------------+-------------------+ -| | | 18, 43 | ✔ | ✔ | ✔ | ci_hs | | -| | +-------------------+--------+------+-----------+------------------------+-------------------+ -| | | 51u | ✔ | ✖ | ✖ | lpc_ip3511 | | -| | +-------------------+--------+------+-----------+------------------------+-------------------+ -| | | 54, 55 | ✔ | | ✔ | lpc_ip3511 | | -| +---------+-------------------+--------+------+-----------+------------------------+-------------------+ -| | MCX | N9, A15 | ✔ | | ✔ | ci_fs, ci_hs | | -+--------------+---------+-------------------+--------+------+-----------+------------------------+-------------------+ -| Raspberry Pi | RP2040, RP2350 | ✔ | ✔ | ✖ | rp2040, pio_usb | | -+--------------+-----+-----------------------+--------+------+-----------+------------------------+-------------------+ -| Renesas | RX | 63N, 65N, 72N | ✔ | ✔ | ✖ | rusb2 | | -| +-----+-----------------------+--------+------+-----------+------------------------+-------------------+ -| | RA | 4M1, 4M3, 6M1 | ✔ | ✔ | ✖ | rusb2 | | -| | +-----------------------+--------+------+-----------+------------------------+-------------------+ -| | | 6M5 | ✔ | ✔ | ✔ | rusb2 | | -+--------------+-----+-----------------------+--------+------+-----------+------------------------+-------------------+ -| Silabs | EFM32GG12 | ✔ | | ✖ | dwc2 | | -+--------------+-----------------------------+--------+------+-----------+------------------------+-------------------+ -| Sony | CXD56 | ✔ | ✖ | ✔ | cxd56 | | -+--------------+-----------------------------+--------+------+-----------+------------------------+-------------------+ -| ST STM32 | F0 | ✔ | ✖ | ✖ | stm32_fsdev | | -| +----+------------------------+--------+------+-----------+------------------------+-------------------+ -| | F1 | 102, 103 | ✔ | ✖ | ✖ | stm32_fsdev | | -| | +------------------------+--------+------+-----------+------------------------+-------------------+ -| | | 105, 107 | ✔ | ✔ | ✖ | dwc2 | | -| +----+------------------------+--------+------+-----------+------------------------+-------------------+ -| | F2, F4, F7, H7 | ✔ | ✔ | ✔ | dwc2 | | -| +-----------------------------+--------+------+-----------+------------------------+-------------------+ -| | F3 | ✔ | ✖ | ✖ | stm32_fsdev | | -| +-----------------------------+--------+------+-----------+------------------------+-------------------+ -| | C0, G0, H5 | ✔ | | ✖ | stm32_fsdev | | -| +-----------------------------+--------+------+-----------+------------------------+-------------------+ -| | G4 | ✔ | ✖ | ✖ | stm32_fsdev | | -| +-----------------------------+--------+------+-----------+------------------------+-------------------+ -| | L0, L1 | ✔ | ✖ | ✖ | stm32_fsdev | | -| +----+------------------------+--------+------+-----------+------------------------+-------------------+ -| | L4 | 4x2, 4x3 | ✔ | ✖ | ✖ | stm32_fsdev | | -| | +------------------------+--------+------+-----------+------------------------+-------------------+ -| | | 4x5, 4x6 | ✔ | ✔ | ✖ | dwc2 | | -| +----+------------------------+--------+------+-----------+------------------------+-------------------+ -| | L4+ | ✔ | ✔ | ✖ | dwc2 | | -| +-----------------------------+--------+------+-----------+------------------------+-------------------+ -| | L5 | ✔ | ✖ | ✖ | stm32_fsdev | | -| +----+------------------------+--------+------+-----------+------------------------+-------------------+ -| | U5 | 535, 545 | ✔ | | ✖ | stm32_fsdev | | -| | +------------------------+--------+------+-----------+------------------------+-------------------+ -| | | 575, 585 | ✔ | ✔ | ✖ | dwc2 | | -| | +------------------------+--------+------+-----------+------------------------+-------------------+ -| | | 59x,5Ax,5Fx,5Gx | ✔ | ✔ | ✔ | dwc2 | | -| +----+------------------------+--------+------+-----------+------------------------+-------------------+ -| | WBx5 | ✔ | ✖ | ✖ | stm32_fsdev | | -+--------------+-----------------------------+--------+------+-----------+------------------------+-------------------+ -| TI | MSP430 | ✔ | ✖ | ✖ | msp430x5xx | | -| +-----------------------------+--------+------+-----------+------------------------+-------------------+ -| | MSP432E4 | ✔ | | ✖ | musb | | -| +-----------------------------+--------+------+-----------+------------------------+-------------------+ -| | TM4C123 | ✔ | | ✖ | musb | | -+--------------+-----------------------------+--------+------+-----------+------------------------+-------------------+ -| ValentyUSB | eptri | ✔ | ✖ | ✖ | eptri | | -+--------------+-----------------------------+--------+------+-----------+------------------------+-------------------+ -| WCH | CH32F20x | ✔ | | ✔ | ch32_usbhs | | -| +-----------------------------+--------+------+-----------+------------------------+-------------------+ -| | CH32V20x | ✔ | | ✖ | stm32_fsdev/ch32_usbfs | | -| +-----------------------------+--------+------+-----------+------------------------+-------------------+ -| | CH32V307 | ✔ | | ✔ | ch32_usbfs/hs | | -+--------------+-----------------------------+--------+------+-----------+------------------------+-------------------+ - - -Table Legend ------------- - -========= ========================= -✔ Supported -⚠ Partial support -✖ Not supported by hardware -\[empty\] Unknown -========= ========================= - -Supported Boards -================ - -The board support code is only used for self-contained examples and testing. It is not used when TinyUSB is part of a larger project. It is responsible for getting the MCU started and the USB peripheral clocked with minimal of on-board devices - -- One LED : for status -- One Button : to get input from user -- One UART : optional for device, but required for host examples - -The following boards are supported (sorted alphabetically): - -Broadcom --------- - -- `Raspberry Pi CM4 `__ - -Dialog DA146xx --------------- - -- `DA14695 Development Kit – USB `__ -- `DA1469x Development Kit – Pro `__ - -Espressif ESP32-S2 ------------------- - -- `Adafruit Feather ESP32-S2 `__ -- `Adafruit Magtag 2.9" E-Ink WiFi Display `__ -- `Adafruit Metro ESP32-S2 `__ -- `ESP32-S2-Kaluga-1 `__ -- `ESP32-S2-Saola-1 `__ - -GigaDevice ----------- - -- `Sipeed Longan Nano `__ - -Infineon ---------- - -XMC4000 -^^^^^^^ - -- `XMC4500 Relax (Lite) Kit `__ - -MicroChip ---------- - -SAMD11 & SAMD21 -^^^^^^^^^^^^^^^ - -- `Adafruit Circuit Playground Express `__ -- `Adafruit Feather M0 Express `__ -- `Adafruit ItsyBitsy M0 Express `__ -- `Adafruit Metro M0 Express `__ -- `Great Scott Gadgets Cynthion `__ -- `Microchip SAMD11 Xplained Pro `__ -- `Microchip SAMD21 Xplained Pro `__ -- `Seeeduino Xiao `__ - -SAMD51 & SAME54 -^^^^^^^^^^^^^^^ - -- `Adafruit Feather M4 Express `__ -- `Adafruit ItsyBitsy M4 Express `__ -- `Adafruit PyBadge `__ -- `Adafruit PyPortal `__ -- `Adafruit Metro M4 Express `__ -- `D5035-01 `__ -- `Microchip SAME54 Xplained Pro `__ - -SAME7x -^^^^^^ - -- `Microchip SAME70 Xplained `_ -- `QMTECH ATSAME70N19 `_ - -SAMG -^^^^ - -- `Microchip SAMG55 Xplained Pro `__ - -SAML2x -^^^^^^ - -- `SAML21 Xplaind Pro `__ -- `SAML22 Feather `__ -- `Sensor Watch `__ - -Nordic nRF5x ------------- - -- `Adafruit Circuit Playground Bluefruit `__ -- `Adafruit CLUE `__ -- `Adafruit Feather nRF52840 Express `__ -- `Adafruit Feather nRF52840 Sense `__ -- `Adafruit ItsyBitsy nRF52840 Express `__ -- `Arduino Nano 33 BLE `__ -- `Arduino Nano 33 BLE Sense `__ -- `Maker Diary nRF52840 MDK Dongle `__ -- `Nordic nRF52840 Development Kit (aka pca10056) `__ -- `Nordic nRF52840 Dongle (aka pca10059) `__ -- `Nordic nRF52833 Development Kit (aka pca10100) `__ -- `Raytac MDBT50Q-RX Dongle `__ - -Nuvoton -------- - -- NuTiny SDK NUC120 -- `NuTiny NUC121S `__ -- `NuTiny NUC125S `__ -- `NuTiny NUC126V `__ -- `NuTiny SDK NUC505Y `__ - -NXP ---- - -iMX RT -^^^^^^ - -- `MIMX RT1010 Evaluation Kit `__ -- `MIMX RT1015 Evaluation Kit `__ -- `MIMX RT1020 Evaluation Kit `__ -- `MIMX RT1050 Evaluation Kit `__ -- `MIMX RT1060 Evaluation Kit `__ -- `MIMX RT1064 Evaluation Kit `__ -- `Teensy 4.0 Development Board `__ -- `Teensy 4.1 Development Board `__ - -Kinetis -^^^^^^^ - -- `Freedom FRDM-KL25Z `__ -- `Freedom FRDM-K32L2A4S `__ -- `Freedom FRDM-K32L2B3 `__ -- `KUIIC `__ - -LPC 11-13-15 -^^^^^^^^^^^^ - -- `LPCXpresso 11u37 `__ -- `LPCXpresso 11u68 `__ -- `LPCXpresso 1347 `__ -- `LPCXpresso 1549 `__ - -LPC 17-40 -^^^^^^^^^ - -- `ARM mbed LPC1768 `__ -- `Embedded Artists LPC4088 Quick Start board `__ -- `LPCXpresso 1769 `__ - -LPC 18-43 -^^^^^^^^^ - -- `Embedded Artists LPC4357 Developer Kit `__ -- `Keil MCB1800 Evaluation Board `__ -- `LPCXpresso18S37 Development Board `__ - -LPC 51 -^^^^^^ - -- `LPCXpresso 51U68 `__ - -LPC 54 -^^^^^^ - -- `LPCXpresso 54114 `__ - -LPC55 -^^^^^ - -- `Double M33 Express `__ -- `LPCXpresso 55s28 EVK `__ -- `LPCXpresso 55s69 EVK `__ -- `MCU-Link `__ - -Renesas -------- - -RA -^^ - -- `Evaluation Kit for RA4M1 `__ -- `Evaluation Kit for RA4M3 `__ - -RX -^^ - -- `GR-CITRUS `__ -- `Renesas RX65N Target Board `__ - -Raspberry Pi RP2040 -------------------- - -- `Adafruit Feather RP2040 `__ -- `Adafruit ItsyBitsy RP2040 `__ -- `Adafruit QT Py RP2040 `__ -- `Raspberry Pi Pico `__ - -Silabs ------- - -- `EFM32GG12 Thunderboard Kit (SLTB009A) `__ - -Sony ----- - -- `Sony Spresense CXD5602 `__ - -ST STM32 --------- - -F0 -^^ -- `STM32 F070rb Nucleo `__ -- `STM32 F072 Evaluation `__ -- `STM32 F072rb Discovery `__ - -F1 -^^ -- `STM32 F103c8 Blue Pill `__ -- `STM32 F103rc Mini v2.0 `__ - -F2 -^^ -- `STM32 F207zg Nucleo `__ - -F3 -^^ -- `STM32 F303vc Discovery `__ - -F4 -^^ -- `Adafruit Feather STM32F405 `__ -- `Micro Python PyBoard v1.1 `__ -- `STM32 F401cc Black Pill `__ -- `STM32 F407vg Discovery `__ -- `STM32 F411ce Black Pill `__ -- `STM32 F411ve Discovery `__ -- `STM32 F412zg Discovery `__ -- `STM32 F412zg Nucleo `__ -- `STM32 F439zi Nucleo `__ - -F7 -^^ - -- `STLink-V3 Mini `__ -- `STM32 F723e Discovery `__ -- `STM32 F746zg Nucleo `__ -- `STM32 F746g Discovery `__ -- `STM32 F767zi Nucleo `__ -- `STM32 F769i Discovery `__ - -H7 -^^ -- `STM32 H743zi Nucleo `__ -- `STM32 H743i Evaluation `__ -- `STM32 H745i Discovery `__ -- `Waveshare OpenH743I-C `__ - -G4 -^^ -- `STM32 G474RE Nucleo `__ - -L0 -^^ -- `STM32 L035c8 Discovery `__ - -L4 -^^ -- `STM32 L476vg Discovery `__ -- `STM32 L4P5zg Nucleo `__ -- `STM32 L4R5zi Nucleo `__ - -WB -^^ -- `STM32 WB55 Nucleo `__ - -TI --- - -- `MSP430F5529 USB LaunchPad Evaluation Kit `__ -- `MSP-EXP432E401Y LaunchPad Evaluation Kit `__ -- `TM4C123GXL LaunchPad Evaluation Kit `__ - -Tomu ----- - -- `Fomu `__ - -WCH ---- - -- `CH32V307V-R1-1v0 `__ -- `CH32F205R-R0-1v0 `__ diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index c603d0c22..d34c6ed5d 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.17) +cmake_minimum_required(VERSION 3.20) #set(CMAKE_EXPORT_COMPILE_COMMANDS ON) include(${CMAKE_CURRENT_SOURCE_DIR}/../hw/bsp/family_support.cmake) diff --git a/examples/CMakePresets.json b/examples/CMakePresets.json new file mode 100644 index 000000000..2f904a269 --- /dev/null +++ b/examples/CMakePresets.json @@ -0,0 +1,6 @@ +{ + "version": 6, + "include": [ + "../hw/bsp/BoardPresets.json" + ] +} diff --git a/examples/build_system/cmake/cpu/cortex-m0.cmake b/examples/build_system/cmake/cpu/cortex-m0.cmake index 62019d90d..f837c7eb8 100644 --- a/examples/build_system/cmake/cpu/cortex-m0.cmake +++ b/examples/build_system/cmake/cpu/cortex-m0.cmake @@ -1,7 +1,7 @@ if (TOOLCHAIN STREQUAL "gcc") set(TOOLCHAIN_COMMON_FLAGS -mthumb - -mcpu=cortex-m0plus + -mcpu=cortex-m0 -mfloat-abi=soft ) set(FREERTOS_PORT GCC_ARM_CM0 CACHE INTERNAL "") diff --git a/examples/build_system/cmake/cpu/cortex-m55.cmake b/examples/build_system/cmake/cpu/cortex-m55.cmake new file mode 100644 index 000000000..a7a57957c --- /dev/null +++ b/examples/build_system/cmake/cpu/cortex-m55.cmake @@ -0,0 +1,26 @@ +if (TOOLCHAIN STREQUAL "gcc") + set(TOOLCHAIN_COMMON_FLAGS + -mthumb + -mcpu=cortex-m55 + -mfloat-abi=hard + -mfpu=fpv5-d16 + -mcmse + ) + set(FREERTOS_PORT GCC_ARM_CM55_NTZ_NONSECURE CACHE INTERNAL "") + +elseif (TOOLCHAIN STREQUAL "clang") + set(TOOLCHAIN_COMMON_FLAGS + --target=arm-none-eabi + -mcpu=cortex-m55 + -mfpu=fpv5-d16 + ) + set(FREERTOS_PORT GCC_ARM_CM55_NTZ_NONSECURE CACHE INTERNAL "") + +elseif (TOOLCHAIN STREQUAL "iar") + set(TOOLCHAIN_COMMON_FLAGS + --cpu cortex-m55 + --fpu VFPv5_D16 + ) + set(FREERTOS_PORT IAR_ARM_CM55_NTZ_NONSECURE CACHE INTERNAL "") + +endif () diff --git a/examples/build_system/cmake/cpu/cortex-m85.cmake b/examples/build_system/cmake/cpu/cortex-m85.cmake new file mode 100644 index 000000000..30314acbc --- /dev/null +++ b/examples/build_system/cmake/cpu/cortex-m85.cmake @@ -0,0 +1,25 @@ +if (TOOLCHAIN STREQUAL "gcc") + set(TOOLCHAIN_COMMON_FLAGS + -mthumb + -mcpu=cortex-m85 + -mfloat-abi=hard + -mfpu=fpv5-d16 + ) + set(FREERTOS_PORT GCC_ARM_CM85_NTZ_NONSECURE CACHE INTERNAL "") + +elseif (TOOLCHAIN STREQUAL "clang") + set(TOOLCHAIN_COMMON_FLAGS + --target=arm-none-eabi + -mcpu=cortex-m85 + -mfpu=fpv5-d16 + ) + set(FREERTOS_PORT GCC_ARM_CM85_NTZ_NONSECURE CACHE INTERNAL "") + +elseif (TOOLCHAIN STREQUAL "iar") + set(TOOLCHAIN_COMMON_FLAGS + --cpu cortex-m85 + --fpu VFPv5_D16 + ) + set(FREERTOS_PORT IAR_ARM_CM85_NTZ_NONSECURE CACHE INTERNAL "") + +endif () diff --git a/examples/build_system/cmake/toolchain/arm_gcc.cmake b/examples/build_system/cmake/toolchain/arm_gcc.cmake index 0b0949dd8..6a660e259 100644 --- a/examples/build_system/cmake/toolchain/arm_gcc.cmake +++ b/examples/build_system/cmake/toolchain/arm_gcc.cmake @@ -1,3 +1,7 @@ +if (RTOS STREQUAL zephyr) + return() +endif () + if (NOT DEFINED CMAKE_C_COMPILER) set(CMAKE_C_COMPILER "arm-none-eabi-gcc") endif () diff --git a/examples/build_system/cmake/toolchain/common.cmake b/examples/build_system/cmake/toolchain/common.cmake index 688715914..4c181137b 100644 --- a/examples/build_system/cmake/toolchain/common.cmake +++ b/examples/build_system/cmake/toolchain/common.cmake @@ -4,6 +4,7 @@ include(CMakePrintHelpers) # Common # ---------------------------------------------------------------------------- set(CMAKE_SYSTEM_NAME Generic) +set(CMAKE_SYSTEM_PROCESSOR ${CMAKE_SYSTEM_CPU}) set_property(GLOBAL PROPERTY TARGET_SUPPORTS_SHARED_LIBS FALSE) # Look for includes and libraries only in the target system prefix. @@ -13,8 +14,8 @@ set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) # pass TOOLCHAIN_CPU to -set(CMAKE_TRY_COMPILE_PLATFORM_VARIABLES CMAKE_SYSTEM_PROCESSOR) -include(${CMAKE_CURRENT_LIST_DIR}/../cpu/${CMAKE_SYSTEM_PROCESSOR}.cmake) +set(CMAKE_TRY_COMPILE_PLATFORM_VARIABLES CMAKE_SYSTEM_PROCESSOR CMAKE_SYSTEM_CPU) +include(${CMAKE_CURRENT_LIST_DIR}/../cpu/${CMAKE_SYSTEM_CPU}.cmake) # ---------------------------------------------------------------------------- # Compile flags diff --git a/examples/build_system/make/cpu/cortex-m4.mk b/examples/build_system/make/cpu/cortex-m4.mk index 4e16819d1..57d6e126d 100644 --- a/examples/build_system/make/cpu/cortex-m4.mk +++ b/examples/build_system/make/cpu/cortex-m4.mk @@ -12,8 +12,8 @@ else ifeq ($(TOOLCHAIN),clang) -mfpu=fpv4-sp-d16 \ else ifeq ($(TOOLCHAIN),iar) - CFLAGS += --cpu cortex-m4 --fpu VFPv4 - ASFLAGS += --cpu cortex-m4 --fpu VFPv4 + CFLAGS += --cpu cortex-m4 --fpu VFPv4-SP + ASFLAGS += --cpu cortex-m4 --fpu VFPv4-SP else $(error "TOOLCHAIN is not supported") diff --git a/examples/build_system/make/cpu/cortex-m55.mk b/examples/build_system/make/cpu/cortex-m55.mk new file mode 100644 index 000000000..de627caed --- /dev/null +++ b/examples/build_system/make/cpu/cortex-m55.mk @@ -0,0 +1,28 @@ +ifeq ($(TOOLCHAIN),gcc) + CFLAGS += \ + -mthumb \ + -mcpu=cortex-m55 \ + -mfloat-abi=hard \ + -mfpu=fpv5-d16 \ + -mcmse + +else ifeq ($(TOOLCHAIN),clang) + CFLAGS += \ + --target=arm-none-eabi \ + -mcpu=cortex-m55 \ + -mfpu=fpv5-d16 \ + +else ifeq ($(TOOLCHAIN),iar) + CFLAGS += \ + --cpu cortex-m55 \ + --fpu VFPv5_D16 \ + + ASFLAGS += \ + --cpu cortex-m55 \ + --fpu VFPv5_D16 \ + +else + $(error "TOOLCHAIN is not supported") +endif + +FREERTOS_PORTABLE_SRC ?= $(FREERTOS_PORTABLE_PATH)/ARM_CM55_NTZ/non_secure diff --git a/examples/build_system/make/cpu/cortex-m85.mk b/examples/build_system/make/cpu/cortex-m85.mk new file mode 100644 index 000000000..75e8f3aaf --- /dev/null +++ b/examples/build_system/make/cpu/cortex-m85.mk @@ -0,0 +1,27 @@ +ifeq ($(TOOLCHAIN),gcc) + CFLAGS += \ + -mthumb \ + -mcpu=cortex-m85 \ + -mfloat-abi=hard \ + -mfpu=fpv5-d16 \ + +else ifeq ($(TOOLCHAIN),clang) + CFLAGS += \ + --target=arm-none-eabi \ + -mcpu=cortex-m85 \ + -mfpu=fpv5-d16 \ + +else ifeq ($(TOOLCHAIN),iar) + CFLAGS += \ + --cpu cortex-m85 \ + --fpu VFPv5_D16 \ + + ASFLAGS += \ + --cpu cortex-m85 \ + --fpu VFPv5_D16 \ + +else + $(error "TOOLCHAIN is not supported") +endif + +FREERTOS_PORTABLE_SRC ?= $(FREERTOS_PORTABLE_PATH)/ARM_CM85_NTZ/non_secure diff --git a/examples/build_system/make/make.mk b/examples/build_system/make/make.mk index 1500a51e0..f70748d34 100644 --- a/examples/build_system/make/make.mk +++ b/examples/build_system/make/make.mk @@ -2,11 +2,13 @@ # Common make definition for all examples # --------------------------------------- +# upper helper function +to_upper = $(subst a,A,$(subst b,B,$(subst c,C,$(subst d,D,$(subst e,E,$(subst f,F,$(subst g,G,$(subst h,H,$(subst i,I,$(subst j,J,$(subst k,K,$(subst l,L,$(subst m,M,$(subst n,N,$(subst o,O,$(subst p,P,$(subst q,Q,$(subst r,R,$(subst s,S,$(subst t,T,$(subst u,U,$(subst v,V,$(subst w,W,$(subst x,X,$(subst y,Y,$(subst z,Z,$(subst -,_,$(1)))))))))))))))))))))))))))) + #------------------------------------------------------------- # Toolchain # Can be changed via TOOLCHAIN=gcc|iar or CC=arm-none-eabi-gcc|iccarm|clang #------------------------------------------------------------- - ifneq (,$(findstring clang,$(CC))) TOOLCHAIN = clang else ifneq (,$(findstring iccarm,$(CC))) @@ -65,7 +67,9 @@ BUILD := _build/$(BOARD) PROJECT := $(notdir $(CURDIR)) BIN := $(TOP)/_bin/$(BOARD)/$(notdir $(CURDIR)) -#-------------- Select the board to build for. ------------ +#------------------------------------------------------------- +# Board / Family +#------------------------------------------------------------- # Board without family ifneq ($(wildcard $(TOP)/hw/bsp/$(BOARD)/board.mk),) @@ -93,7 +97,9 @@ else SRC_C += $(subst $(TOP)/,,$(wildcard $(TOP)/$(FAMILY_PATH)/*.c)) endif -#-------------- Source files and compiler flags -------------- +#------------------------------------------------------------- +# Source files and compiler flags +#------------------------------------------------------------- # tinyusb makefile include $(TOP)/src/tinyusb.mk SRC_C += $(TINYUSB_SRC_C) @@ -106,7 +112,7 @@ INC += \ $(TOP)/$(FAMILY_PATH) \ $(TOP)/src \ -BOARD_UPPER = $(subst a,A,$(subst b,B,$(subst c,C,$(subst d,D,$(subst e,E,$(subst f,F,$(subst g,G,$(subst h,H,$(subst i,I,$(subst j,J,$(subst k,K,$(subst l,L,$(subst m,M,$(subst n,N,$(subst o,O,$(subst p,P,$(subst q,Q,$(subst r,R,$(subst s,S,$(subst t,T,$(subst u,U,$(subst v,V,$(subst w,W,$(subst x,X,$(subst y,Y,$(subst z,Z,$(subst -,_,$(BOARD)))))))))))))))))))))))))))) +BOARD_UPPER = $(call to_upper,$(BOARD)) CFLAGS += -DBOARD_$(BOARD_UPPER) ifdef CFLAGS_CLI @@ -117,27 +123,24 @@ endif ifeq (${MAX3421_HOST},1) SRC_C += src/portable/analog/max3421/hcd_max3421.c CFLAGS += -DCFG_TUH_MAX3421=1 - CMAKE_DEFSYM += -DMAX3421_HOST=1 endif # Log level is mapped to TUSB DEBUG option ifneq ($(LOG),) - CMAKE_DEFSYM += -DLOG=$(LOG) CFLAGS += -DCFG_TUSB_DEBUG=$(LOG) endif # Logger: default is uart, can be set to rtt or swo -ifneq ($(LOGGER),) - CMAKE_DEFSYM += -DLOGGER=$(LOGGER) -endif - ifeq ($(LOGGER),rtt) - CFLAGS += -DLOGGER_RTT -DSEGGER_RTT_MODE_DEFAULT=SEGGER_RTT_MODE_BLOCK_IF_FIFO_FULL - RTT_SRC = lib/SEGGER_RTT - INC += $(TOP)/$(RTT_SRC)/RTT - SRC_C += $(RTT_SRC)/RTT/SEGGER_RTT.c -else ifeq ($(LOGGER),swo) + CFLAGS += -DLOGGER_RTT + #CFLAGS += -DSEGGER_RTT_MODE_DEFAULT=SEGGER_RTT_MODE_BLOCK_IF_FIFO_FULL + INC += $(TOP)/$(lib/SEGGER_RTT)/RTT + SRC_C += $(lib/SEGGER_RTT)/RTT/SEGGER_RTT.c +endif +ifeq ($(LOGGER),swo) CFLAGS += -DLOGGER_SWO +else + CFLAGS += -DLOGGER_UART endif # CPU specific flags @@ -148,7 +151,37 @@ endif # toolchain specific include ${TOP}/examples/build_system/make/toolchain/arm_$(TOOLCHAIN).mk -# Handy check parameter function +#---------------------- FreeRTOS ----------------------- +FREERTOS_SRC = lib/FreeRTOS-Kernel +FREERTOS_PORTABLE_PATH = $(FREERTOS_SRC)/portable/$(if $(findstring iar,$(TOOLCHAIN)),IAR,GCC) + +ifeq ($(RTOS),freertos) + SRC_C += \ + $(FREERTOS_SRC)/list.c \ + $(FREERTOS_SRC)/queue.c \ + $(FREERTOS_SRC)/tasks.c \ + $(FREERTOS_SRC)/timers.c \ + $(subst $(TOP)/,,$(wildcard $(TOP)/$(FREERTOS_PORTABLE_SRC)/*.c)) + + SRC_S += $(subst $(TOP)/,,$(wildcard $(TOP)/$(FREERTOS_PORTABLE_SRC)/*.s)) + INC += \ + $(TOP)/hw/bsp/$(FAMILY)/FreeRTOSConfig \ + $(TOP)/$(FREERTOS_SRC)/include \ + $(TOP)/$(FREERTOS_PORTABLE_SRC) + + CFLAGS += -DCFG_TUSB_OS=OPT_OS_FREERTOS + + # Suppress FreeRTOSConfig.h warnings + CFLAGS_GCC += -Wno-error=redundant-decls + + # Suppress FreeRTOS source warnings + CFLAGS_GCC += -Wno-error=cast-qual + + # FreeRTOS (lto + Os) linker issue + LDFLAGS_GCC += -Wl,--undefined=vTaskSwitchContext +endif + +#---------------- Helper ---------------- check_defined = \ $(strip $(foreach 1,$1, \ $(call __check_defined,$1,$(strip $(value 2))))) diff --git a/examples/device/CMakeLists.txt b/examples/device/CMakeLists.txt index 26a808a21..bb7dd0a0f 100644 --- a/examples/device/CMakeLists.txt +++ b/examples/device/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.17) +cmake_minimum_required(VERSION 3.20) include(${CMAKE_CURRENT_SOURCE_DIR}/../../hw/bsp/family_support.cmake) diff --git a/examples/device/CMakePresets.json b/examples/device/CMakePresets.json new file mode 100644 index 000000000..c22e8c0ec --- /dev/null +++ b/examples/device/CMakePresets.json @@ -0,0 +1,6 @@ +{ + "version": 6, + "include": [ + "../../hw/bsp/BoardPresets.json" + ] +} diff --git a/examples/device/audio_4_channel_mic/CMakeLists.txt b/examples/device/audio_4_channel_mic/CMakeLists.txt index 0f5d36193..c8086ae46 100644 --- a/examples/device/audio_4_channel_mic/CMakeLists.txt +++ b/examples/device/audio_4_channel_mic/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.17) +cmake_minimum_required(VERSION 3.20) include(${CMAKE_CURRENT_SOURCE_DIR}/../../../hw/bsp/family_support.cmake) diff --git a/examples/device/audio_4_channel_mic/CMakePresets.json b/examples/device/audio_4_channel_mic/CMakePresets.json new file mode 100644 index 000000000..5cd8971e9 --- /dev/null +++ b/examples/device/audio_4_channel_mic/CMakePresets.json @@ -0,0 +1,6 @@ +{ + "version": 6, + "include": [ + "../../../hw/bsp/BoardPresets.json" + ] +} diff --git a/examples/device/audio_4_channel_mic/src/main.c b/examples/device/audio_4_channel_mic/src/main.c index e8c40309e..f78e48f0c 100644 --- a/examples/device/audio_4_channel_mic/src/main.c +++ b/examples/device/audio_4_channel_mic/src/main.c @@ -69,13 +69,8 @@ uint8_t clkValid; audio_control_range_2_n_t(1) volumeRng[CFG_TUD_AUDIO_FUNC_1_N_CHANNELS_TX+1]; // Volume range state audio_control_range_4_n_t(1) sampleFreqRng; // Sample frequency range state -#if CFG_TUD_AUDIO_ENABLE_ENCODING -// Audio test data, each buffer contains 2 channels, buffer[0] for CH0-1, buffer[1] for CH1-2 -uint16_t i2s_dummy_buffer[CFG_TUD_AUDIO_FUNC_1_N_TX_SUPP_SW_FIFO][CFG_TUD_AUDIO_FUNC_1_N_CHANNELS_TX*CFG_TUD_AUDIO_FUNC_1_SAMPLE_RATE/1000/CFG_TUD_AUDIO_FUNC_1_N_TX_SUPP_SW_FIFO]; -#else // Audio test data, 4 channels muxed together, buffer[0] for CH0, buffer[1] for CH1, buffer[2] for CH2, buffer[3] for CH3 uint16_t i2s_dummy_buffer[CFG_TUD_AUDIO_FUNC_1_N_CHANNELS_TX*CFG_TUD_AUDIO_FUNC_1_SAMPLE_RATE/1000]; -#endif void led_blinking_task(void); void audio_task(void); @@ -106,27 +101,6 @@ int main(void) sampleFreqRng.subrange[0].bRes = 0; // Generate dummy data -#if CFG_TUD_AUDIO_ENABLE_ENCODING - uint16_t * p_buff = i2s_dummy_buffer[0]; - uint16_t dataVal = 0; - for (uint16_t cnt = 0; cnt < AUDIO_SAMPLE_RATE/1000; cnt++) - { - // CH0 saw wave - *p_buff++ = dataVal; - // CH1 inverted saw wave - *p_buff++ = 3200 + AUDIO_SAMPLE_RATE/1000 - dataVal; - dataVal+= 32; - } - p_buff = i2s_dummy_buffer[1]; - for (uint16_t cnt = 0; cnt < AUDIO_SAMPLE_RATE/1000; cnt++) - { - // CH3 square wave - *p_buff++ = cnt < (AUDIO_SAMPLE_RATE/1000/2) ? 3400:5000; - // CH4 sinus wave - float t = 2*3.1415f * cnt / (AUDIO_SAMPLE_RATE/1000); - *p_buff++ = (uint16_t)((int16_t)(sinf(t) * 750) + 6000); - } -#else uint16_t * p_buff = i2s_dummy_buffer; uint16_t dataVal = 0; for (uint16_t cnt = 0; cnt < AUDIO_SAMPLE_RATE/1000; cnt++) @@ -142,7 +116,6 @@ int main(void) float t = 2*3.1415f * cnt / (AUDIO_SAMPLE_RATE/1000); *p_buff++ = (uint16_t)((int16_t)(sinf(t) * 750) + 6000); } -#endif while (1) { @@ -195,15 +168,7 @@ void audio_task(void) uint32_t curr_ms = board_millis(); if ( start_ms == curr_ms ) return; // not enough time start_ms = curr_ms; -#if CFG_TUD_AUDIO_ENABLE_ENCODING - // Write I2S buffer into FIFO - for (uint8_t cnt=0; cnt < 2; cnt++) - { - tud_audio_write_support_ff(cnt, i2s_dummy_buffer[cnt], AUDIO_SAMPLE_RATE/1000 * CFG_TUD_AUDIO_FUNC_1_N_BYTES_PER_SAMPLE_TX * CFG_TUD_AUDIO_FUNC_1_CHANNEL_PER_FIFO_TX); - } -#else tud_audio_write(i2s_dummy_buffer, AUDIO_SAMPLE_RATE/1000 * CFG_TUD_AUDIO_FUNC_1_N_BYTES_PER_SAMPLE_TX * CFG_TUD_AUDIO_FUNC_1_N_CHANNELS_TX); -#endif } //--------------------------------------------------------------------+ diff --git a/examples/device/audio_4_channel_mic/src/tusb_config.h b/examples/device/audio_4_channel_mic/src/tusb_config.h index 46484f847..446a7a32a 100644 --- a/examples/device/audio_4_channel_mic/src/tusb_config.h +++ b/examples/device/audio_4_channel_mic/src/tusb_config.h @@ -115,26 +115,11 @@ extern "C" { #define CFG_TUD_AUDIO_FUNC_1_N_CHANNELS_TX 4 // This value is not required by the driver, it parses this information from the descriptor once the alternate interface is set by the host - we use it for the setup #define CFG_TUD_AUDIO_EP_SZ_IN TUD_AUDIO_EP_SIZE(CFG_TUD_AUDIO_FUNC_1_SAMPLE_RATE, CFG_TUD_AUDIO_FUNC_1_N_BYTES_PER_SAMPLE_TX, CFG_TUD_AUDIO_FUNC_1_N_CHANNELS_TX) -#define CFG_TUD_AUDIO_ENABLE_ENCODING 1 #define CFG_TUD_AUDIO_EP_IN_FLOW_CONTROL 1 -#if CFG_TUD_AUDIO_ENABLE_ENCODING - -#define CFG_TUD_AUDIO_FUNC_1_EP_IN_SZ_MAX CFG_TUD_AUDIO_EP_SZ_IN -#define CFG_TUD_AUDIO_FUNC_1_EP_IN_SW_BUF_SZ CFG_TUD_AUDIO_EP_SZ_IN - -#define CFG_TUD_AUDIO_ENABLE_TYPE_I_ENCODING 1 -#define CFG_TUD_AUDIO_FUNC_1_CHANNEL_PER_FIFO_TX 2 // One I2S stream contains two channels, each stream is saved within one support FIFO - this value is currently fixed, the driver does not support a changing value -#define CFG_TUD_AUDIO_FUNC_1_N_TX_SUPP_SW_FIFO (CFG_TUD_AUDIO_FUNC_1_N_CHANNELS_TX / CFG_TUD_AUDIO_FUNC_1_CHANNEL_PER_FIFO_TX) -#define CFG_TUD_AUDIO_FUNC_1_TX_SUPP_SW_FIFO_SZ (TUD_OPT_HIGH_SPEED ? 32 : 4) * (CFG_TUD_AUDIO_EP_SZ_IN / CFG_TUD_AUDIO_FUNC_1_N_TX_SUPP_SW_FIFO) // Example write FIFO every 1ms, so it should be 8 times larger for HS device - -#else - #define CFG_TUD_AUDIO_FUNC_1_EP_IN_SZ_MAX CFG_TUD_AUDIO_EP_SZ_IN #define CFG_TUD_AUDIO_FUNC_1_EP_IN_SW_BUF_SZ (TUD_OPT_HIGH_SPEED ? 32 : 4) * CFG_TUD_AUDIO_EP_SZ_IN // Example write FIFO every 1ms, so it should be 8 times larger for HS device -#endif - #ifdef __cplusplus } #endif diff --git a/examples/device/audio_4_channel_mic_freertos/CMakeLists.txt b/examples/device/audio_4_channel_mic_freertos/CMakeLists.txt index 285d4490b..c50d4fef7 100644 --- a/examples/device/audio_4_channel_mic_freertos/CMakeLists.txt +++ b/examples/device/audio_4_channel_mic_freertos/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.17) +cmake_minimum_required(VERSION 3.20) include(${CMAKE_CURRENT_SOURCE_DIR}/../../../hw/bsp/family_support.cmake) diff --git a/examples/device/audio_4_channel_mic_freertos/CMakePresets.json b/examples/device/audio_4_channel_mic_freertos/CMakePresets.json new file mode 100644 index 000000000..5cd8971e9 --- /dev/null +++ b/examples/device/audio_4_channel_mic_freertos/CMakePresets.json @@ -0,0 +1,6 @@ +{ + "version": 6, + "include": [ + "../../../hw/bsp/BoardPresets.json" + ] +} diff --git a/examples/device/audio_4_channel_mic_freertos/Makefile b/examples/device/audio_4_channel_mic_freertos/Makefile index 0202f631c..bd625b345 100644 --- a/examples/device/audio_4_channel_mic_freertos/Makefile +++ b/examples/device/audio_4_channel_mic_freertos/Makefile @@ -1,14 +1,9 @@ +RTOS = freertos include ../../build_system/make/make.mk -FREERTOS_SRC = lib/FreeRTOS-Kernel -FREERTOS_PORTABLE_PATH = $(FREERTOS_SRC)/portable/$(if $(findstring iar,$(TOOLCHAIN)),IAR,GCC) - INC += \ src \ - src/FreeRTOSConfig \ $(TOP)/hw \ - $(TOP)/$(FREERTOS_SRC)/include \ - $(TOP)/$(FREERTOS_PORTABLE_SRC) \ # Example source EXAMPLE_SOURCE = \ @@ -17,21 +12,4 @@ EXAMPLE_SOURCE = \ SRC_C += $(addprefix $(CURRENT_PATH)/, $(EXAMPLE_SOURCE)) -# FreeRTOS source, all files in port folder -SRC_C += \ - $(FREERTOS_SRC)/list.c \ - $(FREERTOS_SRC)/queue.c \ - $(FREERTOS_SRC)/tasks.c \ - $(FREERTOS_SRC)/timers.c \ - $(subst $(TOP)/,,$(wildcard $(TOP)/$(FREERTOS_PORTABLE_SRC)/*.c)) - -SRC_S += \ - $(subst $(TOP)/,,$(wildcard $(TOP)/$(FREERTOS_PORTABLE_SRC)/*.s)) - -# Suppress FreeRTOS warnings -CFLAGS += -Wno-error=cast-qual -Wno-error=redundant-decls - -# FreeRTOS (lto + Os) linker issue -LDFLAGS += -Wl,--undefined=vTaskSwitchContext - include ../../build_system/make/rules.mk diff --git a/examples/device/audio_4_channel_mic_freertos/src/FreeRTOSConfig/FreeRTOSConfig.h b/examples/device/audio_4_channel_mic_freertos/src/FreeRTOSConfig/FreeRTOSConfig.h deleted file mode 100644 index 902a54f08..000000000 --- a/examples/device/audio_4_channel_mic_freertos/src/FreeRTOSConfig/FreeRTOSConfig.h +++ /dev/null @@ -1,191 +0,0 @@ -/* - * FreeRTOS Kernel V10.0.0 - * 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. If you wish to use our Amazon - * FreeRTOS name, please do so in a fair use way that does not cause confusion. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS - * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR - * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER - * IN AN ACTION 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. - *----------------------------------------------------------*/ - -// skip if included from IAR assembler -#ifndef __IASMARM__ - -// Include MCU header -#include "bsp/board_mcu.h" - -#if TUSB_MCU_VENDOR_ESPRESSIF - #error "ESP32-Sx should use IDF's FreeRTOSConfig.h" -#endif - -// TODO fix later -#if CFG_TUSB_MCU == OPT_MCU_MM32F327X - extern u32 SystemCoreClock; -#else - // FIXME cause redundant-decls warnings - extern uint32_t SystemCoreClock; -#endif - -#endif - -/* Cortex M23/M33 port configuration. */ -#define configENABLE_MPU 0 -#define configENABLE_FPU 1 -#define configENABLE_TRUSTZONE 0 -#define configMINIMAL_SECURE_STACK_SIZE ( 1024 ) -#define configRUN_FREERTOS_SECURE_ONLY 1 - -#define configUSE_PREEMPTION 1 -#define configUSE_PORT_OPTIMISED_TASK_SELECTION 0 -#define configCPU_CLOCK_HZ SystemCoreClock -#define configTICK_RATE_HZ ( 1000 ) -#define configMAX_PRIORITIES ( 5 ) -#define configMINIMAL_STACK_SIZE ( 128 ) -#define configTOTAL_HEAP_SIZE ( configSUPPORT_DYNAMIC_ALLOCATION*4*1024 ) -#define configMAX_TASK_NAME_LEN 16 -#define configUSE_16_BIT_TICKS 0 -#define configIDLE_SHOULD_YIELD 1 -#define configUSE_MUTEXES 1 -#define configUSE_RECURSIVE_MUTEXES 1 -#define configUSE_COUNTING_SEMAPHORES 1 -#define configQUEUE_REGISTRY_SIZE 4 -#define configUSE_QUEUE_SETS 0 -#define configUSE_TIME_SLICING 0 -#define configUSE_NEWLIB_REENTRANT 0 -#define configENABLE_BACKWARD_COMPATIBILITY 1 -#define configSTACK_ALLOCATION_FROM_SEPARATE_HEAP 0 - -#define configSUPPORT_STATIC_ALLOCATION 1 -#define configSUPPORT_DYNAMIC_ALLOCATION 0 - -/* Hook function related definitions. */ -#define configUSE_IDLE_HOOK 0 -#define configUSE_TICK_HOOK 0 -#define configUSE_MALLOC_FAILED_HOOK 0 // cause nested extern warning -#define configCHECK_FOR_STACK_OVERFLOW 2 -#define configCHECK_HANDLER_INSTALLATION 0 - -/* Run time and task stats gathering related definitions. */ -#define configGENERATE_RUN_TIME_STATS 0 -#define configUSE_TRACE_FACILITY 1 // legacy trace -#define configUSE_STATS_FORMATTING_FUNCTIONS 0 - -/* Co-routine definitions. */ -#define configUSE_CO_ROUTINES 0 -#define configMAX_CO_ROUTINE_PRIORITIES 2 - -/* Software timer related definitions. */ -#define configUSE_TIMERS 1 -#define configTIMER_TASK_PRIORITY (configMAX_PRIORITIES-2) -#define configTIMER_QUEUE_LENGTH 32 -#define configTIMER_TASK_STACK_DEPTH configMINIMAL_STACK_SIZE - -/* Optional functions - most linkers will remove unused functions anyway. */ -#define INCLUDE_vTaskPrioritySet 0 -#define INCLUDE_uxTaskPriorityGet 0 -#define INCLUDE_vTaskDelete 0 -#define INCLUDE_vTaskSuspend 1 // required for queue, semaphore, mutex to be blocked indefinitely with portMAX_DELAY -#define INCLUDE_xResumeFromISR 0 -#define INCLUDE_vTaskDelayUntil 1 -#define INCLUDE_vTaskDelay 1 -#define INCLUDE_xTaskGetSchedulerState 0 -#define INCLUDE_xTaskGetCurrentTaskHandle 0 -#define INCLUDE_uxTaskGetStackHighWaterMark 0 -#define INCLUDE_xTaskGetIdleTaskHandle 0 -#define INCLUDE_xTimerGetTimerDaemonTaskHandle 0 -#define INCLUDE_pcTaskGetTaskName 0 -#define INCLUDE_eTaskGetState 0 -#define INCLUDE_xEventGroupSetBitFromISR 0 -#define INCLUDE_xTimerPendFunctionCall 0 - -#ifdef __RX__ -/* Renesas RX series */ -#define vSoftwareInterruptISR INT_Excep_ICU_SWINT -#define vTickISR INT_Excep_CMT0_CMI0 -#define configPERIPHERAL_CLOCK_HZ (configCPU_CLOCK_HZ/2) -#define configKERNEL_INTERRUPT_PRIORITY 1 -#define configMAX_SYSCALL_INTERRUPT_PRIORITY 4 - -#else - -/* FreeRTOS hooks to NVIC vectors */ -#define xPortPendSVHandler PendSV_Handler -#define xPortSysTickHandler SysTick_Handler -#define vPortSVCHandler SVC_Handler - -//--------------------------------------------------------------------+ -// Interrupt nesting behavior configuration. -//--------------------------------------------------------------------+ -#if defined(__NVIC_PRIO_BITS) - // For Cortex-M specific: __NVIC_PRIO_BITS is defined in core_cmx.h - #define configPRIO_BITS __NVIC_PRIO_BITS - -#elif defined(__ECLIC_INTCTLBITS) - // RISC-V Bumblebee core from nuclei - #define configPRIO_BITS __ECLIC_INTCTLBITS - -#elif defined(__IASMARM__) - // FIXME: IAR Assembler cannot include mcu header directly to get __NVIC_PRIO_BITS. - // Therefore we will hard coded it to minimum value of 2 to get pass ci build. - // IAR user must update this to correct value of the target MCU - #message "configPRIO_BITS is hard coded to 2 to pass IAR build only. User should update it per MCU" - #define configPRIO_BITS 2 - -#else - #error "FreeRTOS configPRIO_BITS to be defined" -#endif - -/* The lowest interrupt priority that can be used in a call to a "set priority" function. */ -#define configLIBRARY_LOWEST_INTERRUPT_PRIORITY ((1< 0) { + board_putchar(ch); + #ifndef LOGGER_UART + board_uart_write(&ch, 1); + #endif + } + // Blink and print every interval ms if (!(board_millis() - start_ms < interval_ms)) { - board_uart_write(HELLO_STR, strlen(HELLO_STR)); - start_ms = board_millis(); + if (ch < 0) { + // skip if echoing + printf(HELLO_STR); + + #ifndef LOGGER_UART + board_uart_write(HELLO_STR, strlen(HELLO_STR)); + #endif + } + board_led_write(led_state); led_state = 1 - led_state; // toggle } - - // echo - uint8_t ch; - if (board_uart_read(&ch, 1) > 0) { - board_uart_write(&ch, 1); - } } } -#if TUSB_MCU_VENDOR_ESPRESSIF +#ifdef ESP_PLATFORM void app_main(void) { main(); } diff --git a/examples/device/board_test/src/tusb_config.h b/examples/device/board_test/src/tusb_config.h index 8ac3bc8de..81829d450 100644 --- a/examples/device/board_test/src/tusb_config.h +++ b/examples/device/board_test/src/tusb_config.h @@ -44,7 +44,7 @@ #endif // Espressif IDF requires "freertos/" prefix in include path -#if TUSB_MCU_VENDOR_ESPRESSIF +#ifdef ESP_PLATFORM #define CFG_TUSB_OS_INC_PATH freertos/ #endif diff --git a/examples/device/cdc_dual_ports/CMakeLists.txt b/examples/device/cdc_dual_ports/CMakeLists.txt index f61e1b640..6a7e68c3d 100644 --- a/examples/device/cdc_dual_ports/CMakeLists.txt +++ b/examples/device/cdc_dual_ports/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.17) +cmake_minimum_required(VERSION 3.20) include(${CMAKE_CURRENT_SOURCE_DIR}/../../../hw/bsp/family_support.cmake) diff --git a/examples/device/cdc_dual_ports/CMakePresets.json b/examples/device/cdc_dual_ports/CMakePresets.json new file mode 100644 index 000000000..5cd8971e9 --- /dev/null +++ b/examples/device/cdc_dual_ports/CMakePresets.json @@ -0,0 +1,6 @@ +{ + "version": 6, + "include": [ + "../../../hw/bsp/BoardPresets.json" + ] +} diff --git a/examples/device/cdc_msc/CMakeLists.txt b/examples/device/cdc_msc/CMakeLists.txt index c2f9cb095..b07f92342 100644 --- a/examples/device/cdc_msc/CMakeLists.txt +++ b/examples/device/cdc_msc/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.17) +cmake_minimum_required(VERSION 3.20) #set_property(GLOBAL PROPERTY USE_FOLDERS ON) include(${CMAKE_CURRENT_SOURCE_DIR}/../../../hw/bsp/family_support.cmake) @@ -16,20 +16,25 @@ if(FAMILY STREQUAL "espressif") return() endif() -add_executable(${PROJECT}) +if (RTOS STREQUAL zephyr) + set(EXE_NAME app) +else() + set(EXE_NAME ${PROJECT}) + add_executable(${EXE_NAME}) +endif() # Example source -target_sources(${PROJECT} PUBLIC +target_sources(${EXE_NAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/main.c ${CMAKE_CURRENT_SOURCE_DIR}/src/msc_disk.c ${CMAKE_CURRENT_SOURCE_DIR}/src/usb_descriptors.c ) # Example include -target_include_directories(${PROJECT} PUBLIC +target_include_directories(${EXE_NAME} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/src ) -# Configure compilation flags and libraries for the example... see the corresponding function -# in hw/bsp/FAMILY/family.cmake for details. -family_configure_device_example(${PROJECT} noos) +# Configure compilation flags and libraries for the example without RTOS. +# See the corresponding function in hw/bsp/FAMILY/family.cmake for details. +family_configure_device_example(${EXE_NAME} ${RTOS}) diff --git a/examples/device/cdc_msc/CMakePresets.json b/examples/device/cdc_msc/CMakePresets.json new file mode 100644 index 000000000..5cd8971e9 --- /dev/null +++ b/examples/device/cdc_msc/CMakePresets.json @@ -0,0 +1,6 @@ +{ + "version": 6, + "include": [ + "../../../hw/bsp/BoardPresets.json" + ] +} diff --git a/examples/device/cdc_msc/prj.conf b/examples/device/cdc_msc/prj.conf new file mode 100644 index 000000000..2f5139d9d --- /dev/null +++ b/examples/device/cdc_msc/prj.conf @@ -0,0 +1,6 @@ +CONFIG_GPIO=y +CONFIG_FPU=y +CONFIG_NO_OPTIMIZATIONS=y +CONFIG_UART_INTERRUPT_DRIVEN=y +CONFIG_NRFX_POWER=y +CONFIG_NRFX_UARTE0=y diff --git a/examples/device/cdc_msc/src/msc_disk.c b/examples/device/cdc_msc/src/msc_disk.c index d2f8628f1..458681f58 100644 --- a/examples/device/cdc_msc/src/msc_disk.c +++ b/examples/device/cdc_msc/src/msc_disk.c @@ -40,17 +40,15 @@ static bool ejected = false; If you find any bugs or get any questions, feel free to file an\r\n\ issue at github.com/hathach/tinyusb" -enum -{ - DISK_BLOCK_NUM = 16, // 8KB is the smallest size that windows allow to mount +enum { + DISK_BLOCK_NUM = 16,// 8KB is the smallest size that windows allow to mount DISK_BLOCK_SIZE = 512 }; #ifdef CFG_EXAMPLE_MSC_READONLY const #endif -uint8_t msc_disk[DISK_BLOCK_NUM][DISK_BLOCK_SIZE] = -{ +uint8_t msc_disk[DISK_BLOCK_NUM][DISK_BLOCK_SIZE] = { //------------- Block0: Boot Sector -------------// // byte_per_sector = DISK_BLOCK_SIZE; fat12_sector_num_16 = DISK_BLOCK_NUM; // sector_per_cluster = 1; reserved_sectors = 1; @@ -59,60 +57,59 @@ uint8_t msc_disk[DISK_BLOCK_NUM][DISK_BLOCK_SIZE] = // drive_number = 0x80; media_type = 0xf8; extended_boot_signature = 0x29; // filesystem_type = "FAT12 "; volume_serial_number = 0x1234; volume_label = "TinyUSB MSC"; // FAT magic code at offset 510-511 - { - 0xEB, 0x3C, 0x90, 0x4D, 0x53, 0x44, 0x4F, 0x53, 0x35, 0x2E, 0x30, 0x00, 0x02, 0x01, 0x01, 0x00, - 0x01, 0x10, 0x00, 0x10, 0x00, 0xF8, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x29, 0x34, 0x12, 0x00, 0x00, 'T' , 'i' , 'n' , 'y' , 'U' , - 'S' , 'B' , ' ' , 'M' , 'S' , 'C' , 0x46, 0x41, 0x54, 0x31, 0x32, 0x20, 0x20, 0x20, 0x00, 0x00, +{ + 0xEB, 0x3C, 0x90, 0x4D, 0x53, 0x44, 0x4F, 0x53, 0x35, 0x2E, 0x30, 0x00, 0x02, 0x01, 0x01, 0x00, + 0x01, 0x10, 0x00, 0x10, 0x00, 0xF8, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x29, 0x34, 0x12, 0x00, 0x00, 'T', 'i', 'n', 'y', 'U', + 'S', 'B', ' ', 'M', 'S', 'C', 0x46, 0x41, 0x54, 0x31, 0x32, 0x20, 0x20, 0x20, 0x00, 0x00, - // Zero up to 2 last bytes of FAT magic code - 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, 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, 0x00, 0x00, + // Zero up to 2 last bytes of FAT magic code + 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0xAA - }, + 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, 0x55, 0xAA}, //------------- Block1: FAT12 Table -------------// - { - 0xF8, 0xFF, 0xFF, 0xFF, 0x0F // // first 2 entries must be F8FF, third entry is cluster end of readme file +{ + 0xF8, 0xFF, 0xFF, 0xFF, 0x0F// // first 2 entries must be F8FF, third entry is cluster end of readme file }, //------------- Block2: Root Directory -------------// - { - // first entry is volume label - 'T' , 'i' , 'n' , 'y' , 'U' , 'S' , 'B' , ' ' , 'M' , 'S' , 'C' , 0x08, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4F, 0x6D, 0x65, 0x43, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - // second entry is readme file - 'R' , 'E' , 'A' , 'D' , 'M' , 'E' , ' ' , ' ' , 'T' , 'X' , 'T' , 0x20, 0x00, 0xC6, 0x52, 0x6D, - 0x65, 0x43, 0x65, 0x43, 0x00, 0x00, 0x88, 0x6D, 0x65, 0x43, 0x02, 0x00, - sizeof(README_CONTENTS)-1, 0x00, 0x00, 0x00 // readme's files size (4 Bytes) +{ + // first entry is volume label + 'T', 'i', 'n', 'y', 'U', 'S', 'B', ' ', 'M', 'S', 'C', 0x08, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4F, 0x6D, 0x65, 0x43, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + // second entry is readme file + 'R', 'E', 'A', 'D', 'M', 'E', ' ', ' ', 'T', 'X', 'T', 0x20, 0x00, 0xC6, 0x52, 0x6D, + 0x65, 0x43, 0x65, 0x43, 0x00, 0x00, 0x88, 0x6D, 0x65, 0x43, 0x02, 0x00, + sizeof(README_CONTENTS) - 1, 0x00, 0x00, 0x00// readme's files size (4 Bytes) }, //------------- Block3: Readme Content -------------// @@ -121,23 +118,21 @@ uint8_t msc_disk[DISK_BLOCK_NUM][DISK_BLOCK_SIZE] = // Invoked when received SCSI_CMD_INQUIRY // Application fill vendor id, product id and revision with string up to 8, 16, 4 characters respectively -void tud_msc_inquiry_cb(uint8_t lun, uint8_t vendor_id[8], uint8_t product_id[16], uint8_t product_rev[4]) -{ +void tud_msc_inquiry_cb(uint8_t lun, uint8_t vendor_id[8], uint8_t product_id[16], uint8_t product_rev[4]) { (void) lun; const char vid[] = "TinyUSB"; const char pid[] = "Mass Storage"; const char rev[] = "1.0"; - memcpy(vendor_id , vid, strlen(vid)); - memcpy(product_id , pid, strlen(pid)); + memcpy(vendor_id, vid, strlen(vid)); + memcpy(product_id, pid, strlen(pid)); memcpy(product_rev, rev, strlen(rev)); } // Invoked when received Test Unit Ready command. // return true allowing host to read/write this LUN e.g SD card inserted -bool tud_msc_test_unit_ready_cb(uint8_t lun) -{ +bool tud_msc_test_unit_ready_cb(uint8_t lun) { (void) lun; // RAM disk is ready until ejected @@ -152,29 +147,24 @@ bool tud_msc_test_unit_ready_cb(uint8_t lun) // Invoked when received SCSI_CMD_READ_CAPACITY_10 and SCSI_CMD_READ_FORMAT_CAPACITY to determine the disk size // Application update block count and block size -void tud_msc_capacity_cb(uint8_t lun, uint32_t* block_count, uint16_t* block_size) -{ +void tud_msc_capacity_cb(uint8_t lun, uint32_t *block_count, uint16_t *block_size) { (void) lun; *block_count = DISK_BLOCK_NUM; - *block_size = DISK_BLOCK_SIZE; + *block_size = DISK_BLOCK_SIZE; } // Invoked when received Start Stop Unit command // - Start = 0 : stopped power mode, if load_eject = 1 : unload disk storage // - Start = 1 : active mode, if load_eject = 1 : load disk storage -bool tud_msc_start_stop_cb(uint8_t lun, uint8_t power_condition, bool start, bool load_eject) -{ +bool tud_msc_start_stop_cb(uint8_t lun, uint8_t power_condition, bool start, bool load_eject) { (void) lun; (void) power_condition; - if ( load_eject ) - { - if (start) - { + if (load_eject) { + if (start) { // load disk storage - }else - { + } else { // unload disk storage ejected = true; } @@ -185,45 +175,51 @@ bool tud_msc_start_stop_cb(uint8_t lun, uint8_t power_condition, bool start, boo // Callback invoked when received READ10 command. // Copy disk's data to buffer (up to bufsize) and return number of copied bytes. -int32_t tud_msc_read10_cb(uint8_t lun, uint32_t lba, uint32_t offset, void* buffer, uint32_t bufsize) -{ +int32_t tud_msc_read10_cb(uint8_t lun, uint32_t lba, uint32_t offset, void *buffer, uint32_t bufsize) { (void) lun; // out of ramdisk - if ( lba >= DISK_BLOCK_NUM ) return -1; + if (lba >= DISK_BLOCK_NUM) { + return -1; + } - uint8_t const* addr = msc_disk[lba] + offset; + // Check for overflow of offset + bufsize + if (lba * DISK_BLOCK_SIZE + offset + bufsize > DISK_BLOCK_NUM * DISK_BLOCK_SIZE) { + return -1; + } + + uint8_t const *addr = msc_disk[lba] + offset; memcpy(buffer, addr, bufsize); return (int32_t) bufsize; } -bool tud_msc_is_writable_cb (uint8_t lun) -{ +bool tud_msc_is_writable_cb(uint8_t lun) { (void) lun; -#ifdef CFG_EXAMPLE_MSC_READONLY + #ifdef CFG_EXAMPLE_MSC_READONLY return false; -#else + #else return true; -#endif + #endif } // Callback invoked when received WRITE10 command. // Process data in buffer to disk's storage and return number of written bytes -int32_t tud_msc_write10_cb(uint8_t lun, uint32_t lba, uint32_t offset, uint8_t* buffer, uint32_t bufsize) -{ +int32_t tud_msc_write10_cb(uint8_t lun, uint32_t lba, uint32_t offset, uint8_t *buffer, uint32_t bufsize) { (void) lun; // out of ramdisk - if ( lba >= DISK_BLOCK_NUM ) return -1; + if (lba >= DISK_BLOCK_NUM) return -1; -#ifndef CFG_EXAMPLE_MSC_READONLY - uint8_t* addr = msc_disk[lba] + offset; + #ifndef CFG_EXAMPLE_MSC_READONLY + uint8_t *addr = msc_disk[lba] + offset; memcpy(addr, buffer, bufsize); -#else - (void) lba; (void) offset; (void) buffer; -#endif + #else + (void) lba; + (void) offset; + (void) buffer; + #endif return (int32_t) bufsize; } @@ -231,42 +227,18 @@ int32_t tud_msc_write10_cb(uint8_t lun, uint32_t lba, uint32_t offset, uint8_t* // Callback invoked when received an SCSI command not in built-in list below // - READ_CAPACITY10, READ_FORMAT_CAPACITY, INQUIRY, MODE_SENSE6, REQUEST_SENSE // - READ10 and WRITE10 has their own callbacks -int32_t tud_msc_scsi_cb (uint8_t lun, uint8_t const scsi_cmd[16], void* buffer, uint16_t bufsize) -{ - // read10 & write10 has their own callback and MUST not be handled here +int32_t tud_msc_scsi_cb(uint8_t lun, uint8_t const scsi_cmd[16], void *buffer, uint16_t bufsize) { + (void) buffer; + (void) bufsize; - void const* response = NULL; - int32_t resplen = 0; - - // most scsi handled is input - bool in_xfer = true; - - switch (scsi_cmd[0]) - { + switch (scsi_cmd[0]) { default: // Set Sense = Invalid Command Operation tud_msc_set_sense(lun, SCSI_SENSE_ILLEGAL_REQUEST, 0x20, 0x00); // negative means error -> tinyusb could stall and/or response with failed status - resplen = -1; - break; + return -1; } - - // return resplen must not larger than bufsize - if ( resplen > bufsize ) resplen = bufsize; - - if ( response && (resplen > 0) ) - { - if(in_xfer) - { - memcpy(buffer, response, (size_t) resplen); - }else - { - // SCSI output - } - } - - return (int32_t) resplen; } #endif diff --git a/examples/device/cdc_msc_freertos/CMakeLists.txt b/examples/device/cdc_msc_freertos/CMakeLists.txt index 32a9e2930..f7636a07a 100644 --- a/examples/device/cdc_msc_freertos/CMakeLists.txt +++ b/examples/device/cdc_msc_freertos/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.17) +cmake_minimum_required(VERSION 3.20) include(${CMAKE_CURRENT_SOURCE_DIR}/../../../hw/bsp/family_support.cmake) diff --git a/examples/device/cdc_msc_freertos/CMakePresets.json b/examples/device/cdc_msc_freertos/CMakePresets.json new file mode 100644 index 000000000..5cd8971e9 --- /dev/null +++ b/examples/device/cdc_msc_freertos/CMakePresets.json @@ -0,0 +1,6 @@ +{ + "version": 6, + "include": [ + "../../../hw/bsp/BoardPresets.json" + ] +} diff --git a/examples/device/cdc_msc_freertos/Makefile b/examples/device/cdc_msc_freertos/Makefile index c90922b0c..10cff57a0 100644 --- a/examples/device/cdc_msc_freertos/Makefile +++ b/examples/device/cdc_msc_freertos/Makefile @@ -1,14 +1,9 @@ +RTOS = freertos include ../../build_system/make/make.mk -FREERTOS_SRC = lib/FreeRTOS-Kernel -FREERTOS_PORTABLE_PATH = $(FREERTOS_SRC)/portable/$(if $(findstring iar,$(TOOLCHAIN)),IAR,GCC) - INC += \ src \ - src/FreeRTOSConfig \ $(TOP)/hw \ - $(TOP)/$(FREERTOS_SRC)/include \ - $(TOP)/$(FREERTOS_PORTABLE_SRC) \ # Example source EXAMPLE_SOURCE = \ @@ -18,28 +13,4 @@ EXAMPLE_SOURCE = \ SRC_C += $(addprefix $(CURRENT_PATH)/, $(EXAMPLE_SOURCE)) -# FreeRTOS source, all files in port folder -SRC_C += \ - $(FREERTOS_SRC)/list.c \ - $(FREERTOS_SRC)/queue.c \ - $(FREERTOS_SRC)/tasks.c \ - $(FREERTOS_SRC)/timers.c \ - $(subst $(TOP)/,,$(wildcard $(TOP)/$(FREERTOS_PORTABLE_SRC)/*.c)) - -SRC_S += \ - $(subst $(TOP)/,,$(wildcard $(TOP)/$(FREERTOS_PORTABLE_SRC)/*.s)) - -# include heap manage if configSUPPORT_DYNAMIC_ALLOCATION = 1 -# SRC_C += $(FREERTOS_SRC)/portable/MemMang/heap_1.c -# CFLAGS += -Wno-error=sign-compare - -# Suppress FreeRTOSConfig.h warnings -CFLAGS_GCC += -Wno-error=redundant-decls - -# Suppress FreeRTOS source warnings -CFLAGS_GCC += -Wno-error=cast-qual - -# FreeRTOS (lto + Os) linker issue -LDFLAGS_GCC += -Wl,--undefined=vTaskSwitchContext - include ../../build_system/make/rules.mk diff --git a/examples/device/cdc_msc_freertos/src/FreeRTOSConfig/FreeRTOSConfig.h b/examples/device/cdc_msc_freertos/src/FreeRTOSConfig/FreeRTOSConfig.h deleted file mode 100644 index 902a54f08..000000000 --- a/examples/device/cdc_msc_freertos/src/FreeRTOSConfig/FreeRTOSConfig.h +++ /dev/null @@ -1,191 +0,0 @@ -/* - * FreeRTOS Kernel V10.0.0 - * 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. If you wish to use our Amazon - * FreeRTOS name, please do so in a fair use way that does not cause confusion. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS - * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR - * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER - * IN AN ACTION 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. - *----------------------------------------------------------*/ - -// skip if included from IAR assembler -#ifndef __IASMARM__ - -// Include MCU header -#include "bsp/board_mcu.h" - -#if TUSB_MCU_VENDOR_ESPRESSIF - #error "ESP32-Sx should use IDF's FreeRTOSConfig.h" -#endif - -// TODO fix later -#if CFG_TUSB_MCU == OPT_MCU_MM32F327X - extern u32 SystemCoreClock; -#else - // FIXME cause redundant-decls warnings - extern uint32_t SystemCoreClock; -#endif - -#endif - -/* Cortex M23/M33 port configuration. */ -#define configENABLE_MPU 0 -#define configENABLE_FPU 1 -#define configENABLE_TRUSTZONE 0 -#define configMINIMAL_SECURE_STACK_SIZE ( 1024 ) -#define configRUN_FREERTOS_SECURE_ONLY 1 - -#define configUSE_PREEMPTION 1 -#define configUSE_PORT_OPTIMISED_TASK_SELECTION 0 -#define configCPU_CLOCK_HZ SystemCoreClock -#define configTICK_RATE_HZ ( 1000 ) -#define configMAX_PRIORITIES ( 5 ) -#define configMINIMAL_STACK_SIZE ( 128 ) -#define configTOTAL_HEAP_SIZE ( configSUPPORT_DYNAMIC_ALLOCATION*4*1024 ) -#define configMAX_TASK_NAME_LEN 16 -#define configUSE_16_BIT_TICKS 0 -#define configIDLE_SHOULD_YIELD 1 -#define configUSE_MUTEXES 1 -#define configUSE_RECURSIVE_MUTEXES 1 -#define configUSE_COUNTING_SEMAPHORES 1 -#define configQUEUE_REGISTRY_SIZE 4 -#define configUSE_QUEUE_SETS 0 -#define configUSE_TIME_SLICING 0 -#define configUSE_NEWLIB_REENTRANT 0 -#define configENABLE_BACKWARD_COMPATIBILITY 1 -#define configSTACK_ALLOCATION_FROM_SEPARATE_HEAP 0 - -#define configSUPPORT_STATIC_ALLOCATION 1 -#define configSUPPORT_DYNAMIC_ALLOCATION 0 - -/* Hook function related definitions. */ -#define configUSE_IDLE_HOOK 0 -#define configUSE_TICK_HOOK 0 -#define configUSE_MALLOC_FAILED_HOOK 0 // cause nested extern warning -#define configCHECK_FOR_STACK_OVERFLOW 2 -#define configCHECK_HANDLER_INSTALLATION 0 - -/* Run time and task stats gathering related definitions. */ -#define configGENERATE_RUN_TIME_STATS 0 -#define configUSE_TRACE_FACILITY 1 // legacy trace -#define configUSE_STATS_FORMATTING_FUNCTIONS 0 - -/* Co-routine definitions. */ -#define configUSE_CO_ROUTINES 0 -#define configMAX_CO_ROUTINE_PRIORITIES 2 - -/* Software timer related definitions. */ -#define configUSE_TIMERS 1 -#define configTIMER_TASK_PRIORITY (configMAX_PRIORITIES-2) -#define configTIMER_QUEUE_LENGTH 32 -#define configTIMER_TASK_STACK_DEPTH configMINIMAL_STACK_SIZE - -/* Optional functions - most linkers will remove unused functions anyway. */ -#define INCLUDE_vTaskPrioritySet 0 -#define INCLUDE_uxTaskPriorityGet 0 -#define INCLUDE_vTaskDelete 0 -#define INCLUDE_vTaskSuspend 1 // required for queue, semaphore, mutex to be blocked indefinitely with portMAX_DELAY -#define INCLUDE_xResumeFromISR 0 -#define INCLUDE_vTaskDelayUntil 1 -#define INCLUDE_vTaskDelay 1 -#define INCLUDE_xTaskGetSchedulerState 0 -#define INCLUDE_xTaskGetCurrentTaskHandle 0 -#define INCLUDE_uxTaskGetStackHighWaterMark 0 -#define INCLUDE_xTaskGetIdleTaskHandle 0 -#define INCLUDE_xTimerGetTimerDaemonTaskHandle 0 -#define INCLUDE_pcTaskGetTaskName 0 -#define INCLUDE_eTaskGetState 0 -#define INCLUDE_xEventGroupSetBitFromISR 0 -#define INCLUDE_xTimerPendFunctionCall 0 - -#ifdef __RX__ -/* Renesas RX series */ -#define vSoftwareInterruptISR INT_Excep_ICU_SWINT -#define vTickISR INT_Excep_CMT0_CMI0 -#define configPERIPHERAL_CLOCK_HZ (configCPU_CLOCK_HZ/2) -#define configKERNEL_INTERRUPT_PRIORITY 1 -#define configMAX_SYSCALL_INTERRUPT_PRIORITY 4 - -#else - -/* FreeRTOS hooks to NVIC vectors */ -#define xPortPendSVHandler PendSV_Handler -#define xPortSysTickHandler SysTick_Handler -#define vPortSVCHandler SVC_Handler - -//--------------------------------------------------------------------+ -// Interrupt nesting behavior configuration. -//--------------------------------------------------------------------+ -#if defined(__NVIC_PRIO_BITS) - // For Cortex-M specific: __NVIC_PRIO_BITS is defined in core_cmx.h - #define configPRIO_BITS __NVIC_PRIO_BITS - -#elif defined(__ECLIC_INTCTLBITS) - // RISC-V Bumblebee core from nuclei - #define configPRIO_BITS __ECLIC_INTCTLBITS - -#elif defined(__IASMARM__) - // FIXME: IAR Assembler cannot include mcu header directly to get __NVIC_PRIO_BITS. - // Therefore we will hard coded it to minimum value of 2 to get pass ci build. - // IAR user must update this to correct value of the target MCU - #message "configPRIO_BITS is hard coded to 2 to pass IAR build only. User should update it per MCU" - #define configPRIO_BITS 2 - -#else - #error "FreeRTOS configPRIO_BITS to be defined" -#endif - -/* The lowest interrupt priority that can be used in a call to a "set priority" function. */ -#define configLIBRARY_LOWEST_INTERRUPT_PRIORITY ((1<= DISK_BLOCK_NUM ) return -1; + if (lba >= DISK_BLOCK_NUM) { + return TUD_MSC_RET_ERROR; + } - uint8_t const* addr = msc_disk[lba] + offset; + // Check for overflow of offset + bufsize + if (lba * DISK_BLOCK_SIZE + offset + bufsize > DISK_BLOCK_NUM * DISK_BLOCK_SIZE) { + return TUD_MSC_RET_ERROR; + } + + #if CFG_EXAMPLE_MSC_ASYNC_IO + io_ops_t io_ops = {.is_read = true, .lun = lun, .lba = lba, .offset = offset, .buffer = buffer, .bufsize = bufsize}; + + // Send IO operation to IO task + TU_ASSERT(xQueueSend(io_queue, &io_ops, 0) == pdPASS); + + return TUD_MSC_RET_ASYNC; + #else + uint8_t const *addr = msc_disk[lba] + offset; memcpy(buffer, addr, bufsize); - - return (int32_t) bufsize; + return bufsize; + #endif } -bool tud_msc_is_writable_cb (uint8_t lun) -{ +bool tud_msc_is_writable_cb (uint8_t lun) { (void) lun; -#ifdef CFG_EXAMPLE_MSC_READONLY + #ifdef CFG_EXAMPLE_MSC_READONLY return false; -#else + #else return true; -#endif + #endif } // Callback invoked when received WRITE10 command. // Process data in buffer to disk's storage and return number of written bytes -int32_t tud_msc_write10_cb(uint8_t lun, uint32_t lba, uint32_t offset, uint8_t* buffer, uint32_t bufsize) -{ - (void) lun; - +int32_t tud_msc_write10_cb(uint8_t lun, uint32_t lba, uint32_t offset, uint8_t* buffer, uint32_t bufsize) { // out of ramdisk - if ( lba >= DISK_BLOCK_NUM ) return -1; + if (lba >= DISK_BLOCK_NUM) { + return TUD_MSC_RET_ERROR; + } -#ifndef CFG_EXAMPLE_MSC_READONLY - uint8_t* addr = msc_disk[lba] + offset; + // Check for overflow of offset + bufsize + if (lba * DISK_BLOCK_SIZE + offset + bufsize > DISK_BLOCK_NUM * DISK_BLOCK_SIZE) { + return TUD_MSC_RET_ERROR; + } + + #ifdef CFG_EXAMPLE_MSC_READONLY + (void) lun; + (void) buffer; + return bufsize; + #endif + + #if CFG_EXAMPLE_MSC_ASYNC_IO + io_ops_t io_ops = {.is_read = false, .lun = lun, .lba = lba, .offset = offset, .buffer = buffer, .bufsize = bufsize}; + + // Send IO operation to IO task + TU_ASSERT(xQueueSend(io_queue, &io_ops, 0) == pdPASS); + + return TUD_MSC_RET_ASYNC; + #else + uint8_t *addr = msc_disk[lba] + offset; memcpy(addr, buffer, bufsize); -#else - (void) lba; (void) offset; (void) buffer; -#endif + tusb_time_delay_ms_api(CFG_EXAMPLE_MSC_IO_DELAY_MS); - return (int32_t) bufsize; + return bufsize; + #endif } // Callback invoked when received an SCSI command not in built-in list below // - READ_CAPACITY10, READ_FORMAT_CAPACITY, INQUIRY, MODE_SENSE6, REQUEST_SENSE // - READ10 and WRITE10 has their own callbacks -int32_t tud_msc_scsi_cb (uint8_t lun, uint8_t const scsi_cmd[16], void* buffer, uint16_t bufsize) -{ +int32_t tud_msc_scsi_cb (uint8_t lun, uint8_t const scsi_cmd[16], void* buffer, uint16_t bufsize) { // read10 & write10 has their own callback and MUST not be handled here - void const* response = NULL; + void const *response = NULL; int32_t resplen = 0; // most scsi handled is input bool in_xfer = true; - switch (scsi_cmd[0]) - { + switch (scsi_cmd[0]) { default: // Set Sense = Invalid Command Operation tud_msc_set_sense(lun, SCSI_SENSE_ILLEGAL_REQUEST, 0x20, 0x00); // negative means error -> tinyusb could stall and/or response with failed status resplen = -1; - break; + break; } // return resplen must not larger than bufsize - if ( resplen > bufsize ) resplen = bufsize; + if (resplen > bufsize) { resplen = bufsize; } - if ( response && (resplen > 0) ) - { - if(in_xfer) - { + if (response && (resplen > 0)) { + if (in_xfer) { memcpy(buffer, response, (size_t) resplen); - }else - { + } else { // SCSI output } } diff --git a/examples/device/cdc_msc_freertos/src/tusb_config.h b/examples/device/cdc_msc_freertos/src/tusb_config.h index c3f2f7fb5..71a0e985a 100644 --- a/examples/device/cdc_msc_freertos/src/tusb_config.h +++ b/examples/device/cdc_msc_freertos/src/tusb_config.h @@ -59,7 +59,7 @@ #endif // Espressif IDF requires "freertos/" prefix in include path -#if TUSB_MCU_VENDOR_ESPRESSIF +#ifdef ESP_PLATFORM #define CFG_TUSB_OS_INC_PATH freertos/ #endif diff --git a/examples/device/cdc_uac2/CMakeLists.txt b/examples/device/cdc_uac2/CMakeLists.txt index 64e4374e9..c8c797637 100644 --- a/examples/device/cdc_uac2/CMakeLists.txt +++ b/examples/device/cdc_uac2/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.17) +cmake_minimum_required(VERSION 3.20) include(${CMAKE_CURRENT_SOURCE_DIR}/../../../hw/bsp/family_support.cmake) diff --git a/examples/device/cdc_uac2/CMakePresets.json b/examples/device/cdc_uac2/CMakePresets.json new file mode 100644 index 000000000..5cd8971e9 --- /dev/null +++ b/examples/device/cdc_uac2/CMakePresets.json @@ -0,0 +1,6 @@ +{ + "version": 6, + "include": [ + "../../../hw/bsp/BoardPresets.json" + ] +} diff --git a/examples/device/dfu/CMakeLists.txt b/examples/device/dfu/CMakeLists.txt index a01eb3456..3da8ee3df 100644 --- a/examples/device/dfu/CMakeLists.txt +++ b/examples/device/dfu/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.17) +cmake_minimum_required(VERSION 3.20) include(${CMAKE_CURRENT_SOURCE_DIR}/../../../hw/bsp/family_support.cmake) diff --git a/examples/device/dfu/CMakePresets.json b/examples/device/dfu/CMakePresets.json new file mode 100644 index 000000000..5cd8971e9 --- /dev/null +++ b/examples/device/dfu/CMakePresets.json @@ -0,0 +1,6 @@ +{ + "version": 6, + "include": [ + "../../../hw/bsp/BoardPresets.json" + ] +} diff --git a/examples/device/dfu_runtime/CMakeLists.txt b/examples/device/dfu_runtime/CMakeLists.txt index a01eb3456..3da8ee3df 100644 --- a/examples/device/dfu_runtime/CMakeLists.txt +++ b/examples/device/dfu_runtime/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.17) +cmake_minimum_required(VERSION 3.20) include(${CMAKE_CURRENT_SOURCE_DIR}/../../../hw/bsp/family_support.cmake) diff --git a/examples/device/dfu_runtime/CMakePresets.json b/examples/device/dfu_runtime/CMakePresets.json new file mode 100644 index 000000000..5cd8971e9 --- /dev/null +++ b/examples/device/dfu_runtime/CMakePresets.json @@ -0,0 +1,6 @@ +{ + "version": 6, + "include": [ + "../../../hw/bsp/BoardPresets.json" + ] +} diff --git a/examples/device/dynamic_configuration/CMakeLists.txt b/examples/device/dynamic_configuration/CMakeLists.txt index 2b20d2234..8a62d6ba2 100644 --- a/examples/device/dynamic_configuration/CMakeLists.txt +++ b/examples/device/dynamic_configuration/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.17) +cmake_minimum_required(VERSION 3.20) include(${CMAKE_CURRENT_SOURCE_DIR}/../../../hw/bsp/family_support.cmake) diff --git a/examples/device/dynamic_configuration/CMakePresets.json b/examples/device/dynamic_configuration/CMakePresets.json new file mode 100644 index 000000000..5cd8971e9 --- /dev/null +++ b/examples/device/dynamic_configuration/CMakePresets.json @@ -0,0 +1,6 @@ +{ + "version": 6, + "include": [ + "../../../hw/bsp/BoardPresets.json" + ] +} diff --git a/examples/device/hid_boot_interface/CMakeLists.txt b/examples/device/hid_boot_interface/CMakeLists.txt index a01eb3456..3da8ee3df 100644 --- a/examples/device/hid_boot_interface/CMakeLists.txt +++ b/examples/device/hid_boot_interface/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.17) +cmake_minimum_required(VERSION 3.20) include(${CMAKE_CURRENT_SOURCE_DIR}/../../../hw/bsp/family_support.cmake) diff --git a/examples/device/hid_boot_interface/CMakePresets.json b/examples/device/hid_boot_interface/CMakePresets.json new file mode 100644 index 000000000..5cd8971e9 --- /dev/null +++ b/examples/device/hid_boot_interface/CMakePresets.json @@ -0,0 +1,6 @@ +{ + "version": 6, + "include": [ + "../../../hw/bsp/BoardPresets.json" + ] +} diff --git a/examples/device/hid_composite/CMakeLists.txt b/examples/device/hid_composite/CMakeLists.txt index a01eb3456..3da8ee3df 100644 --- a/examples/device/hid_composite/CMakeLists.txt +++ b/examples/device/hid_composite/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.17) +cmake_minimum_required(VERSION 3.20) include(${CMAKE_CURRENT_SOURCE_DIR}/../../../hw/bsp/family_support.cmake) diff --git a/examples/device/hid_composite/CMakePresets.json b/examples/device/hid_composite/CMakePresets.json new file mode 100644 index 000000000..5cd8971e9 --- /dev/null +++ b/examples/device/hid_composite/CMakePresets.json @@ -0,0 +1,6 @@ +{ + "version": 6, + "include": [ + "../../../hw/bsp/BoardPresets.json" + ] +} diff --git a/examples/device/hid_composite/src/main.c b/examples/device/hid_composite/src/main.c index 5302af3b8..a58107b6f 100644 --- a/examples/device/hid_composite/src/main.c +++ b/examples/device/hid_composite/src/main.c @@ -197,11 +197,43 @@ static void send_hid_report(uint8_t report_id, uint32_t btn) } } break; - default: break; } } +/* use this to send stylus touch signal through USB. */ +static void send_stylus_touch(uint16_t x, uint16_t y, bool state) +{ + // skip if hid is not ready yet + if ( !tud_hid_ready() ) return; + + static bool has_stylus_pen = false; + + hid_stylus_report_t report = + { + .attr = 0, + .x = 0, + .y = 0 + }; + + report.x = x; + report.y = y; + + if (state) + { + report.attr = STYLUS_ATTR_TIP_SWITCH | STYLUS_ATTR_IN_RANGE; + tud_hid_report(REPORT_ID_STYLUS_PEN, &report, sizeof(report)); + + has_stylus_pen = true; + }else + { + report.attr = 0; + if (has_stylus_pen) tud_hid_report(REPORT_ID_STYLUS_PEN, &report, sizeof(report)); + has_stylus_pen = false; + } + +} + // Every 10ms, we will sent 1 report for each HID profile (keyboard, mouse etc ..) // tud_hid_report_complete_cb() is used to send the next report after previous one is complete void hid_task(void) @@ -209,6 +241,14 @@ void hid_task(void) // Poll every 10ms const uint32_t interval_ms = 10; static uint32_t start_ms = 0; + static uint32_t touch_ms = 0; + static bool touch_state = false; + + if (board_millis() - touch_ms < 100) { + touch_ms = board_millis(); + send_stylus_touch(0, 0, touch_state = !touch_state); + return; + } if ( board_millis() - start_ms < interval_ms) return; // not enough time start_ms += interval_ms; diff --git a/examples/device/hid_composite/src/usb_descriptors.c b/examples/device/hid_composite/src/usb_descriptors.c index e174db46d..15c6e1f73 100644 --- a/examples/device/hid_composite/src/usb_descriptors.c +++ b/examples/device/hid_composite/src/usb_descriptors.c @@ -79,6 +79,7 @@ uint8_t const desc_hid_report[] = { TUD_HID_REPORT_DESC_KEYBOARD( HID_REPORT_ID(REPORT_ID_KEYBOARD )), TUD_HID_REPORT_DESC_MOUSE ( HID_REPORT_ID(REPORT_ID_MOUSE )), + TUD_HID_REPORT_DESC_STYLUS_PEN( HID_REPORT_ID(REPORT_ID_STYLUS_PEN )), TUD_HID_REPORT_DESC_CONSUMER( HID_REPORT_ID(REPORT_ID_CONSUMER_CONTROL )), TUD_HID_REPORT_DESC_GAMEPAD ( HID_REPORT_ID(REPORT_ID_GAMEPAD )) }; diff --git a/examples/device/hid_composite/src/usb_descriptors.h b/examples/device/hid_composite/src/usb_descriptors.h index e733d31dd..18d31172b 100644 --- a/examples/device/hid_composite/src/usb_descriptors.h +++ b/examples/device/hid_composite/src/usb_descriptors.h @@ -29,6 +29,7 @@ enum { REPORT_ID_KEYBOARD = 1, REPORT_ID_MOUSE, + REPORT_ID_STYLUS_PEN, REPORT_ID_CONSUMER_CONTROL, REPORT_ID_GAMEPAD, REPORT_ID_COUNT diff --git a/examples/device/hid_composite_freertos/CMakeLists.txt b/examples/device/hid_composite_freertos/CMakeLists.txt index 33f3b915f..6ce9e72fe 100644 --- a/examples/device/hid_composite_freertos/CMakeLists.txt +++ b/examples/device/hid_composite_freertos/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.17) +cmake_minimum_required(VERSION 3.20) include(${CMAKE_CURRENT_SOURCE_DIR}/../../../hw/bsp/family_support.cmake) diff --git a/examples/device/hid_composite_freertos/CMakePresets.json b/examples/device/hid_composite_freertos/CMakePresets.json new file mode 100644 index 000000000..5cd8971e9 --- /dev/null +++ b/examples/device/hid_composite_freertos/CMakePresets.json @@ -0,0 +1,6 @@ +{ + "version": 6, + "include": [ + "../../../hw/bsp/BoardPresets.json" + ] +} diff --git a/examples/device/hid_composite_freertos/Makefile b/examples/device/hid_composite_freertos/Makefile index 38d842b3a..bd625b345 100644 --- a/examples/device/hid_composite_freertos/Makefile +++ b/examples/device/hid_composite_freertos/Makefile @@ -1,16 +1,9 @@ -DEPS_SUBMODULES += lib/FreeRTOS-Kernel - +RTOS = freertos include ../../build_system/make/make.mk -FREERTOS_SRC = lib/FreeRTOS-Kernel -FREERTOS_PORTABLE_PATH= $(FREERTOS_SRC)/portable/$(if $(findstring iar,$(TOOLCHAIN)),IAR,GCC) - INC += \ src \ - src/FreeRTOSConfig \ $(TOP)/hw \ - $(TOP)/$(FREERTOS_SRC)/include \ - $(TOP)/$(FREERTOS_PORTABLE_SRC) # Example source EXAMPLE_SOURCE = \ @@ -19,28 +12,4 @@ EXAMPLE_SOURCE = \ SRC_C += $(addprefix $(CURRENT_PATH)/, $(EXAMPLE_SOURCE)) -# FreeRTOS source, all files in port folder -SRC_C += \ - $(FREERTOS_SRC)/list.c \ - $(FREERTOS_SRC)/queue.c \ - $(FREERTOS_SRC)/tasks.c \ - $(FREERTOS_SRC)/timers.c \ - $(subst $(TOP)/,,$(wildcard $(TOP)/$(FREERTOS_PORTABLE_SRC)/*.c)) - -SRC_S += \ - $(subst $(TOP)/,,$(wildcard $(TOP)/$(FREERTOS_PORTABLE_SRC)/*.s)) - -# include heap manage if configSUPPORT_DYNAMIC_ALLOCATION = 1 -# SRC_C += $(FREERTOS_SRC)/portable/MemMang/heap_1.c -# CFLAGS += -Wno-error=sign-compare - -# Suppress FreeRTOSConfig.h warnings -CFLAGS_GCC += -Wno-error=redundant-decls - -# Suppress FreeRTOS source warnings -CFLAGS_GCC += -Wno-error=cast-qual - -# FreeRTOS (lto + Os) linker issue -LDFLAGS_GCC += -Wl,--undefined=vTaskSwitchContext - include ../../build_system/make/rules.mk diff --git a/examples/device/hid_composite_freertos/src/FreeRTOSConfig/FreeRTOSConfig.h b/examples/device/hid_composite_freertos/src/FreeRTOSConfig/FreeRTOSConfig.h deleted file mode 100644 index 902a54f08..000000000 --- a/examples/device/hid_composite_freertos/src/FreeRTOSConfig/FreeRTOSConfig.h +++ /dev/null @@ -1,191 +0,0 @@ -/* - * FreeRTOS Kernel V10.0.0 - * 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. If you wish to use our Amazon - * FreeRTOS name, please do so in a fair use way that does not cause confusion. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS - * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR - * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER - * IN AN ACTION 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. - *----------------------------------------------------------*/ - -// skip if included from IAR assembler -#ifndef __IASMARM__ - -// Include MCU header -#include "bsp/board_mcu.h" - -#if TUSB_MCU_VENDOR_ESPRESSIF - #error "ESP32-Sx should use IDF's FreeRTOSConfig.h" -#endif - -// TODO fix later -#if CFG_TUSB_MCU == OPT_MCU_MM32F327X - extern u32 SystemCoreClock; -#else - // FIXME cause redundant-decls warnings - extern uint32_t SystemCoreClock; -#endif - -#endif - -/* Cortex M23/M33 port configuration. */ -#define configENABLE_MPU 0 -#define configENABLE_FPU 1 -#define configENABLE_TRUSTZONE 0 -#define configMINIMAL_SECURE_STACK_SIZE ( 1024 ) -#define configRUN_FREERTOS_SECURE_ONLY 1 - -#define configUSE_PREEMPTION 1 -#define configUSE_PORT_OPTIMISED_TASK_SELECTION 0 -#define configCPU_CLOCK_HZ SystemCoreClock -#define configTICK_RATE_HZ ( 1000 ) -#define configMAX_PRIORITIES ( 5 ) -#define configMINIMAL_STACK_SIZE ( 128 ) -#define configTOTAL_HEAP_SIZE ( configSUPPORT_DYNAMIC_ALLOCATION*4*1024 ) -#define configMAX_TASK_NAME_LEN 16 -#define configUSE_16_BIT_TICKS 0 -#define configIDLE_SHOULD_YIELD 1 -#define configUSE_MUTEXES 1 -#define configUSE_RECURSIVE_MUTEXES 1 -#define configUSE_COUNTING_SEMAPHORES 1 -#define configQUEUE_REGISTRY_SIZE 4 -#define configUSE_QUEUE_SETS 0 -#define configUSE_TIME_SLICING 0 -#define configUSE_NEWLIB_REENTRANT 0 -#define configENABLE_BACKWARD_COMPATIBILITY 1 -#define configSTACK_ALLOCATION_FROM_SEPARATE_HEAP 0 - -#define configSUPPORT_STATIC_ALLOCATION 1 -#define configSUPPORT_DYNAMIC_ALLOCATION 0 - -/* Hook function related definitions. */ -#define configUSE_IDLE_HOOK 0 -#define configUSE_TICK_HOOK 0 -#define configUSE_MALLOC_FAILED_HOOK 0 // cause nested extern warning -#define configCHECK_FOR_STACK_OVERFLOW 2 -#define configCHECK_HANDLER_INSTALLATION 0 - -/* Run time and task stats gathering related definitions. */ -#define configGENERATE_RUN_TIME_STATS 0 -#define configUSE_TRACE_FACILITY 1 // legacy trace -#define configUSE_STATS_FORMATTING_FUNCTIONS 0 - -/* Co-routine definitions. */ -#define configUSE_CO_ROUTINES 0 -#define configMAX_CO_ROUTINE_PRIORITIES 2 - -/* Software timer related definitions. */ -#define configUSE_TIMERS 1 -#define configTIMER_TASK_PRIORITY (configMAX_PRIORITIES-2) -#define configTIMER_QUEUE_LENGTH 32 -#define configTIMER_TASK_STACK_DEPTH configMINIMAL_STACK_SIZE - -/* Optional functions - most linkers will remove unused functions anyway. */ -#define INCLUDE_vTaskPrioritySet 0 -#define INCLUDE_uxTaskPriorityGet 0 -#define INCLUDE_vTaskDelete 0 -#define INCLUDE_vTaskSuspend 1 // required for queue, semaphore, mutex to be blocked indefinitely with portMAX_DELAY -#define INCLUDE_xResumeFromISR 0 -#define INCLUDE_vTaskDelayUntil 1 -#define INCLUDE_vTaskDelay 1 -#define INCLUDE_xTaskGetSchedulerState 0 -#define INCLUDE_xTaskGetCurrentTaskHandle 0 -#define INCLUDE_uxTaskGetStackHighWaterMark 0 -#define INCLUDE_xTaskGetIdleTaskHandle 0 -#define INCLUDE_xTimerGetTimerDaemonTaskHandle 0 -#define INCLUDE_pcTaskGetTaskName 0 -#define INCLUDE_eTaskGetState 0 -#define INCLUDE_xEventGroupSetBitFromISR 0 -#define INCLUDE_xTimerPendFunctionCall 0 - -#ifdef __RX__ -/* Renesas RX series */ -#define vSoftwareInterruptISR INT_Excep_ICU_SWINT -#define vTickISR INT_Excep_CMT0_CMI0 -#define configPERIPHERAL_CLOCK_HZ (configCPU_CLOCK_HZ/2) -#define configKERNEL_INTERRUPT_PRIORITY 1 -#define configMAX_SYSCALL_INTERRUPT_PRIORITY 4 - -#else - -/* FreeRTOS hooks to NVIC vectors */ -#define xPortPendSVHandler PendSV_Handler -#define xPortSysTickHandler SysTick_Handler -#define vPortSVCHandler SVC_Handler - -//--------------------------------------------------------------------+ -// Interrupt nesting behavior configuration. -//--------------------------------------------------------------------+ -#if defined(__NVIC_PRIO_BITS) - // For Cortex-M specific: __NVIC_PRIO_BITS is defined in core_cmx.h - #define configPRIO_BITS __NVIC_PRIO_BITS - -#elif defined(__ECLIC_INTCTLBITS) - // RISC-V Bumblebee core from nuclei - #define configPRIO_BITS __ECLIC_INTCTLBITS - -#elif defined(__IASMARM__) - // FIXME: IAR Assembler cannot include mcu header directly to get __NVIC_PRIO_BITS. - // Therefore we will hard coded it to minimum value of 2 to get pass ci build. - // IAR user must update this to correct value of the target MCU - #message "configPRIO_BITS is hard coded to 2 to pass IAR build only. User should update it per MCU" - #define configPRIO_BITS 2 - -#else - #error "FreeRTOS configPRIO_BITS to be defined" -#endif - -/* The lowest interrupt priority that can be used in a call to a "set priority" function. */ -#define configLIBRARY_LOWEST_INTERRUPT_PRIORITY ((1<= DISK_BLOCK_NUM) return -1; + if (lba >= DISK_BLOCK_NUM) { + return -1; + } -#if defined(CFG_EXAMPLE_MSC_READONLY) || defined(CFG_EXAMPLE_MSC_DUAL_READONLY) + #if defined(CFG_EXAMPLE_MSC_READONLY) || defined(CFG_EXAMPLE_MSC_DUAL_READONLY) (void) lun; (void) lba; (void) offset; @@ -302,11 +303,8 @@ int32_t tud_msc_write10_cb(uint8_t lun, uint32_t lba, uint32_t offset, uint8_t* // - READ_CAPACITY10, READ_FORMAT_CAPACITY, INQUIRY, MODE_SENSE6, REQUEST_SENSE // - READ10 and WRITE10 has their own callbacks (MUST not be handled here) int32_t tud_msc_scsi_cb(uint8_t lun, uint8_t const scsi_cmd[16], void* buffer, uint16_t bufsize) { - void const* response = NULL; - int32_t resplen = 0; - - // most scsi handled is input - bool in_xfer = true; + (void) buffer; + (void) bufsize; switch (scsi_cmd[0]) { default: @@ -316,19 +314,6 @@ int32_t tud_msc_scsi_cb(uint8_t lun, uint8_t const scsi_cmd[16], void* buffer, u // negative means error -> tinyusb could stall and/or response with failed status return -1; } - - // return resplen must not larger than bufsize - if (resplen > bufsize) resplen = bufsize; - - if (response && (resplen > 0)) { - if (in_xfer) { - memcpy(buffer, response, (size_t) resplen); - } else { - // SCSI output - } - } - - return resplen; } #endif diff --git a/examples/device/net_lwip_webserver/CMakeLists.txt b/examples/device/net_lwip_webserver/CMakeLists.txt index 13923b583..87b92f4dc 100644 --- a/examples/device/net_lwip_webserver/CMakeLists.txt +++ b/examples/device/net_lwip_webserver/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.17) +cmake_minimum_required(VERSION 3.20) include(${CMAKE_CURRENT_LIST_DIR}/../../../hw/bsp/family_support.cmake) diff --git a/examples/device/net_lwip_webserver/CMakePresets.json b/examples/device/net_lwip_webserver/CMakePresets.json new file mode 100644 index 000000000..5cd8971e9 --- /dev/null +++ b/examples/device/net_lwip_webserver/CMakePresets.json @@ -0,0 +1,6 @@ +{ + "version": 6, + "include": [ + "../../../hw/bsp/BoardPresets.json" + ] +} diff --git a/examples/device/net_lwip_webserver/Makefile b/examples/device/net_lwip_webserver/Makefile index 141532466..4ad110dec 100644 --- a/examples/device/net_lwip_webserver/Makefile +++ b/examples/device/net_lwip_webserver/Makefile @@ -1,5 +1,3 @@ -DEPS_SUBMODULES += lib/lwip - include ../../build_system/make/make.mk # suppress warning caused by lwip diff --git a/examples/device/net_lwip_webserver/skip.txt b/examples/device/net_lwip_webserver/skip.txt index 5ebe71612..20a264387 100644 --- a/examples/device/net_lwip_webserver/skip.txt +++ b/examples/device/net_lwip_webserver/skip.txt @@ -10,6 +10,8 @@ mcu:SAMD11 mcu:STM32L0 mcu:STM32F0 mcu:KINETIS_KL +mcu:STM32H7RS +mcu:STM32N6 family:broadcom_64bit family:broadcom_32bit family:espressif diff --git a/examples/device/net_lwip_webserver/src/lwipopts.h b/examples/device/net_lwip_webserver/src/lwipopts.h index 41e8f0d67..04949cef9 100644 --- a/examples/device/net_lwip_webserver/src/lwipopts.h +++ b/examples/device/net_lwip_webserver/src/lwipopts.h @@ -58,6 +58,7 @@ #define LWIP_HTTPD_SSI_INCLUDE_TAG 0 #define LWIP_SINGLE_NETIF 1 +#define LWIP_NETIF_LINK_CALLBACK 1 #define PBUF_POOL_SIZE 4 diff --git a/examples/device/net_lwip_webserver/src/main.c b/examples/device/net_lwip_webserver/src/main.c index 36f402332..4bdddf6c5 100644 --- a/examples/device/net_lwip_webserver/src/main.c +++ b/examples/device/net_lwip_webserver/src/main.c @@ -31,6 +31,12 @@ this appears as either a RNDIS or CDC-ECM USB virtual network adapter; the OS pi RNDIS should be valid on Linux and Windows hosts, and CDC-ECM should be valid on Linux and macOS hosts The MCU appears to the host as IP address 192.168.7.1, and provides a DHCP server, DNS server, and web server. + +Link State Control: +- Press the user button to toggle the network link state (UP/DOWN) +- This simulates "ethernet cable unplugged/plugged" events +- The host OS will see the network interface as disconnected/connected accordingly +- Use this to test network error handling and recovery in host applications */ /* Some smartphones *may* work with this implementation as well, but likely have limited (broken) drivers, @@ -63,9 +69,6 @@ try changing the first byte of tud_network_mac_address[] below from 0x02 to 0x00 /* lwip context */ static struct netif netif_data; -/* shared between tud_network_recv_cb() and service_traffic() */ -static struct pbuf *received_frame; - /* this is used by this code, ./class/net/net_driver.c, and usb_descriptors.c */ /* ideally speaking, this should be generated from the hardware's unique ID (if available) */ /* it is suggested that the first byte is 0x02 to indicate a link-local address */ @@ -137,6 +140,12 @@ static err_t netif_init_cb(struct netif *netif) { return ERR_OK; } +/* notifies the USB host about the link state change. */ +static void usbnet_netif_link_callback(struct netif *netif) { + bool link_up = netif_is_link_up(netif); + tud_network_link_state(BOARD_TUD_RHPORT, link_up); +} + static void init_lwip(void) { struct netif *netif = &netif_data; @@ -147,11 +156,19 @@ static void init_lwip(void) { memcpy(netif->hwaddr, tud_network_mac_address, sizeof(tud_network_mac_address)); netif->hwaddr[5] ^= 0x01; - netif = netif_add(netif, &ipaddr, &netmask, &gateway, NULL, netif_init_cb, ip_input); + netif = netif_add(netif, &ipaddr, &netmask, &gateway, NULL, netif_init_cb, ethernet_input); #if LWIP_IPV6 netif_create_ip6_linklocal_address(netif, 1); #endif netif_set_default(netif); + +#if LWIP_NETIF_LINK_CALLBACK + // Set the link callback to notify USB host about link state changes + netif_set_link_callback(netif, usbnet_netif_link_callback); + netif_set_link_up(netif); +#else + tud_network_link_state(BOARD_TUD_RHPORT, true); +#endif } /* handle any DNS requests from dns-server */ @@ -164,20 +181,29 @@ bool dns_query_proc(const char *name, ip4_addr_t *addr) { } bool tud_network_recv_cb(const uint8_t *src, uint16_t size) { - /* this shouldn't happen, but if we get another packet before - parsing the previous, we must signal our inability to accept it */ - if (received_frame) return false; + struct netif *netif = &netif_data; if (size) { struct pbuf *p = pbuf_alloc(PBUF_RAW, size, PBUF_POOL); - if (p) { - /* pbuf_alloc() has already initialized struct; all we need to do is copy the data */ - memcpy(p->payload, src, size); - - /* store away the pointer for service_traffic() to later handle */ - received_frame = p; + if (p == NULL) { + printf("ERROR: Failed to allocate pbuf of size %d\n", size); + return false; } + + /* Copy buf to pbuf */ + pbuf_take(p, src, size); + + // Surrender ownership of our pbuf unless there was an error + // Only call pbuf_free if not Ok else it will panic with "pbuf_free: p->ref > 0" + // or steal it from whatever took ownership of it with undefined consequences. + // See: https://savannah.nongnu.org/patch/index.php?10121 + if (netif->input(p, netif) != ERR_OK) { + printf("ERROR: netif input failed\n"); + pbuf_free(p); + } + // Signal tinyusb that the current frame has been processed. + tud_network_recv_renew(); } return true; @@ -191,29 +217,26 @@ uint16_t tud_network_xmit_cb(uint8_t *dst, void *ref, uint16_t arg) { return pbuf_copy_partial(p, dst, p->tot_len, 0); } -static void service_traffic(void) { - /* handle any packet received by tud_network_recv_cb() */ - if (received_frame) { - // Surrender ownership of our pbuf unless there was an error - // Only call pbuf_free if not Ok else it will panic with "pbuf_free: p->ref > 0" - // or steal it from whatever took ownership of it with undefined consequences. - // See: https://savannah.nongnu.org/patch/index.php?10121 - if (ethernet_input(received_frame, &netif_data)!=ERR_OK) { - pbuf_free(received_frame); +static void handle_link_state_switch(void) { + /* Check for button press to toggle link state */ + static bool last_link_state = true; + static bool last_button_state = false; + bool current_button_state = board_button_read(); + + if (current_button_state && !last_button_state) { + /* Button pressed - toggle link state */ + last_link_state = !last_link_state; + if (last_link_state) { + printf("Link state: UP\n"); + netif_set_link_up(&netif_data); + } else { + printf("Link state: DOWN\n"); + netif_set_link_down(&netif_data); } - received_frame = NULL; - tud_network_recv_renew(); + /* LWIP callback will notify USB host about the change */ } + last_button_state = current_button_state; - sys_check_timeouts(); -} - -void tud_network_init_cb(void) { - /* if the network is re-initializing and we have a leftover packet, we must do a cleanup */ - if (received_frame) { - pbuf_free(received_frame); - received_frame = NULL; - } } int main(void) { @@ -243,15 +266,23 @@ int main(void) { lwiperf_start_tcp_server_default(NULL, NULL); #endif +#if CFG_TUD_NCM + printf("USB NCM network interface initialized\n"); +#elif CFG_TUD_ECM_RNDIS + printf("USB RNDIS/ECM network interface initialized\n"); +#endif + while (1) { tud_task(); - service_traffic(); + sys_check_timeouts(); // service lwip + handle_link_state_switch(); } return 0; } /* lwip has provision for using a mutex, when applicable */ +/* This implementation is for single-threaded use only */ sys_prot_t sys_arch_protect(void) { return 0; } diff --git a/examples/device/net_lwip_webserver/src/tusb_config.h b/examples/device/net_lwip_webserver/src/tusb_config.h index 22082fc81..c774f59ff 100644 --- a/examples/device/net_lwip_webserver/src/tusb_config.h +++ b/examples/device/net_lwip_webserver/src/tusb_config.h @@ -85,6 +85,7 @@ extern "C" { #endif // Use different configurations to test all net devices (also due to resource limitations) +#ifndef USE_ECM #if TU_CHECK_MCU(OPT_MCU_LPC15XX, OPT_MCU_LPC40XX, OPT_MCU_LPC51UXX, OPT_MCU_LPC54) #define USE_ECM 1 #elif TU_CHECK_MCU(OPT_MCU_SAMD21, OPT_MCU_SAML21, OPT_MCU_SAML22) @@ -97,6 +98,7 @@ extern "C" { #define USE_ECM 0 #define INCLUDE_IPERF #endif +#endif //-------------------------------------------------------------------- // NCM CLASS CONFIGURATION, SEE "ncm.h" FOR PERFORMANCE TUNING diff --git a/examples/device/uac2_headset/CMakeLists.txt b/examples/device/uac2_headset/CMakeLists.txt index e92a57148..ced98a909 100644 --- a/examples/device/uac2_headset/CMakeLists.txt +++ b/examples/device/uac2_headset/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.17) +cmake_minimum_required(VERSION 3.20) include(${CMAKE_CURRENT_SOURCE_DIR}/../../../hw/bsp/family_support.cmake) diff --git a/examples/device/uac2_headset/CMakePresets.json b/examples/device/uac2_headset/CMakePresets.json new file mode 100644 index 000000000..5cd8971e9 --- /dev/null +++ b/examples/device/uac2_headset/CMakePresets.json @@ -0,0 +1,6 @@ +{ + "version": 6, + "include": [ + "../../../hw/bsp/BoardPresets.json" + ] +} diff --git a/examples/device/uac2_speaker_fb/CMakeLists.txt b/examples/device/uac2_speaker_fb/CMakeLists.txt index f40ca8716..0ed3db646 100644 --- a/examples/device/uac2_speaker_fb/CMakeLists.txt +++ b/examples/device/uac2_speaker_fb/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.17) +cmake_minimum_required(VERSION 3.20) include(${CMAKE_CURRENT_SOURCE_DIR}/../../../hw/bsp/family_support.cmake) diff --git a/examples/device/uac2_speaker_fb/CMakePresets.json b/examples/device/uac2_speaker_fb/CMakePresets.json new file mode 100644 index 000000000..5cd8971e9 --- /dev/null +++ b/examples/device/uac2_speaker_fb/CMakePresets.json @@ -0,0 +1,6 @@ +{ + "version": 6, + "include": [ + "../../../hw/bsp/BoardPresets.json" + ] +} diff --git a/examples/device/usbtmc/CMakeLists.txt b/examples/device/usbtmc/CMakeLists.txt index a63ca2d81..d2deb72d5 100644 --- a/examples/device/usbtmc/CMakeLists.txt +++ b/examples/device/usbtmc/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.17) +cmake_minimum_required(VERSION 3.20) include(${CMAKE_CURRENT_SOURCE_DIR}/../../../hw/bsp/family_support.cmake) diff --git a/examples/device/usbtmc/CMakePresets.json b/examples/device/usbtmc/CMakePresets.json new file mode 100644 index 000000000..5cd8971e9 --- /dev/null +++ b/examples/device/usbtmc/CMakePresets.json @@ -0,0 +1,6 @@ +{ + "version": 6, + "include": [ + "../../../hw/bsp/BoardPresets.json" + ] +} diff --git a/examples/device/video_capture/CMakeLists.txt b/examples/device/video_capture/CMakeLists.txt index 80dc39ca5..90788fa60 100644 --- a/examples/device/video_capture/CMakeLists.txt +++ b/examples/device/video_capture/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.17) +cmake_minimum_required(VERSION 3.20) include(${CMAKE_CURRENT_SOURCE_DIR}/../../../hw/bsp/family_support.cmake) diff --git a/examples/device/video_capture/CMakePresets.json b/examples/device/video_capture/CMakePresets.json new file mode 100644 index 000000000..5cd8971e9 --- /dev/null +++ b/examples/device/video_capture/CMakePresets.json @@ -0,0 +1,6 @@ +{ + "version": 6, + "include": [ + "../../../hw/bsp/BoardPresets.json" + ] +} diff --git a/examples/device/video_capture/src/main.c b/examples/device/video_capture/src/main.c index 8bb924c61..0406279fd 100644 --- a/examples/device/video_capture/src/main.c +++ b/examples/device/video_capture/src/main.c @@ -185,7 +185,7 @@ static void fill_color_bar(uint8_t* buffer, unsigned start_position) { #endif -void video_send_frame(void) { +static void video_send_frame(void) { static unsigned start_ms = 0; static unsigned already_sent = 0; @@ -292,7 +292,7 @@ void led_blinking_task(void* param) { #define BLINKY_STACK_SIZE configMINIMAL_STACK_SIZE #define VIDEO_STACK_SIZE (configMINIMAL_STACK_SIZE*4) -#if TUSB_MCU_VENDOR_ESPRESSIF +#ifdef ESP_PLATFORM #define USBD_STACK_SIZE 4096 int main(void); void app_main(void) { @@ -351,8 +351,8 @@ void freertos_init_task(void) { xTaskCreate(video_task, "video", VIDEO_STACK_SZIE, NULL, configMAX_PRIORITIES - 2, NULL); #endif - // skip starting scheduler (and return) for ESP32-S2 or ESP32-S3 - #if !TUSB_MCU_VENDOR_ESPRESSIF + // only start scheduler for non-espressif mcu + #ifndef ESP_PLATFORM vTaskStartScheduler(); #endif } diff --git a/examples/device/video_capture/src/tusb_config.h b/examples/device/video_capture/src/tusb_config.h index 6dbd6f2a5..4ba86ca65 100644 --- a/examples/device/video_capture/src/tusb_config.h +++ b/examples/device/video_capture/src/tusb_config.h @@ -58,7 +58,7 @@ #endif // Espressif IDF requires "freertos/" prefix in include path -#if TUSB_MCU_VENDOR_ESPRESSIF +#ifdef ESP_PLATFORM #define CFG_TUSB_OS_INC_PATH freertos/ #endif diff --git a/examples/device/video_capture_2ch/CMakeLists.txt b/examples/device/video_capture_2ch/CMakeLists.txt index 80dc39ca5..90788fa60 100644 --- a/examples/device/video_capture_2ch/CMakeLists.txt +++ b/examples/device/video_capture_2ch/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.17) +cmake_minimum_required(VERSION 3.20) include(${CMAKE_CURRENT_SOURCE_DIR}/../../../hw/bsp/family_support.cmake) diff --git a/examples/device/video_capture_2ch/CMakePresets.json b/examples/device/video_capture_2ch/CMakePresets.json new file mode 100644 index 000000000..5cd8971e9 --- /dev/null +++ b/examples/device/video_capture_2ch/CMakePresets.json @@ -0,0 +1,6 @@ +{ + "version": 6, + "include": [ + "../../../hw/bsp/BoardPresets.json" + ] +} diff --git a/examples/device/video_capture_2ch/src/main.c b/examples/device/video_capture_2ch/src/main.c index 245e7abb8..dc616e3fa 100644 --- a/examples/device/video_capture_2ch/src/main.c +++ b/examples/device/video_capture_2ch/src/main.c @@ -300,7 +300,7 @@ void led_blinking_task(void* param) { #define BLINKY_STACK_SIZE configMINIMAL_STACK_SIZE #define VIDEO_STACK_SIZE (configMINIMAL_STACK_SIZE*4) -#if TUSB_MCU_VENDOR_ESPRESSIF +#ifdef ESP_PLATFORM #define USBD_STACK_SIZE 4096 int main(void); void app_main(void) { @@ -359,8 +359,8 @@ void freertos_init_task(void) { xTaskCreate(video_task, "video", VIDEO_STACK_SZIE, NULL, configMAX_PRIORITIES - 2, NULL); #endif - // skip starting scheduler (and return) for ESP32-S2 or ESP32-S3 - #if !TUSB_MCU_VENDOR_ESPRESSIF + // only start scheduler for non-espressif mcu + #ifndef ESP_PLATFORM vTaskStartScheduler(); #endif } diff --git a/examples/device/video_capture_2ch/src/tusb_config.h b/examples/device/video_capture_2ch/src/tusb_config.h index 91775a327..e84e49879 100644 --- a/examples/device/video_capture_2ch/src/tusb_config.h +++ b/examples/device/video_capture_2ch/src/tusb_config.h @@ -58,7 +58,7 @@ #endif // Espressif IDF requires "freertos/" prefix in include path -#if TUSB_MCU_VENDOR_ESPRESSIF +#ifdef ESP_PLATFORM #define CFG_TUSB_OS_INC_PATH freertos/ #endif diff --git a/examples/device/webusb_serial/CMakeLists.txt b/examples/device/webusb_serial/CMakeLists.txt index e92a57148..ced98a909 100644 --- a/examples/device/webusb_serial/CMakeLists.txt +++ b/examples/device/webusb_serial/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.17) +cmake_minimum_required(VERSION 3.20) include(${CMAKE_CURRENT_SOURCE_DIR}/../../../hw/bsp/family_support.cmake) diff --git a/examples/device/webusb_serial/CMakePresets.json b/examples/device/webusb_serial/CMakePresets.json new file mode 100644 index 000000000..5cd8971e9 --- /dev/null +++ b/examples/device/webusb_serial/CMakePresets.json @@ -0,0 +1,6 @@ +{ + "version": 6, + "include": [ + "../../../hw/bsp/BoardPresets.json" + ] +} diff --git a/examples/dual/CMakeLists.txt b/examples/dual/CMakeLists.txt index f11074e93..c5e3ffce4 100644 --- a/examples/dual/CMakeLists.txt +++ b/examples/dual/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.17) +cmake_minimum_required(VERSION 3.20) include(${CMAKE_CURRENT_SOURCE_DIR}/../../hw/bsp/family_support.cmake) diff --git a/examples/dual/CMakePresets.json b/examples/dual/CMakePresets.json new file mode 100644 index 000000000..c22e8c0ec --- /dev/null +++ b/examples/dual/CMakePresets.json @@ -0,0 +1,6 @@ +{ + "version": 6, + "include": [ + "../../hw/bsp/BoardPresets.json" + ] +} diff --git a/examples/dual/host_hid_to_device_cdc/CMakeLists.txt b/examples/dual/host_hid_to_device_cdc/CMakeLists.txt index 54e36e3d3..6ae5b5766 100644 --- a/examples/dual/host_hid_to_device_cdc/CMakeLists.txt +++ b/examples/dual/host_hid_to_device_cdc/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.17) +cmake_minimum_required(VERSION 3.20) include(${CMAKE_CURRENT_SOURCE_DIR}/../../../hw/bsp/family_support.cmake) diff --git a/examples/dual/host_hid_to_device_cdc/CMakePresets.json b/examples/dual/host_hid_to_device_cdc/CMakePresets.json new file mode 100644 index 000000000..5cd8971e9 --- /dev/null +++ b/examples/dual/host_hid_to_device_cdc/CMakePresets.json @@ -0,0 +1,6 @@ +{ + "version": 6, + "include": [ + "../../../hw/bsp/BoardPresets.json" + ] +} diff --git a/examples/dual/host_hid_to_device_cdc/src/main.c b/examples/dual/host_hid_to_device_cdc/src/main.c index 633f7a6ac..6f30ca381 100644 --- a/examples/dual/host_hid_to_device_cdc/src/main.c +++ b/examples/dual/host_hid_to_device_cdc/src/main.c @@ -190,7 +190,9 @@ void tuh_hid_umount_cb(uint8_t dev_addr, uint8_t instance) { // look up new key in previous keys static inline bool find_key_in_report(hid_keyboard_report_t const* report, uint8_t keycode) { for (uint8_t i = 0; i < 6; i++) { - if (report->keycode[i] == keycode) return true; + if (report->keycode[i] == keycode) { + return true; + } } return false; @@ -230,7 +232,9 @@ static void process_kbd_report(uint8_t dev_addr, hid_keyboard_report_t const* re // TODO example skips key released } - if (flush) tud_cdc_write_flush(); + if (flush) { + tud_cdc_write_flush(); + } prev_report = *report; } diff --git a/examples/dual/host_info_to_device_cdc/CMakeLists.txt b/examples/dual/host_info_to_device_cdc/CMakeLists.txt index 54e36e3d3..6ae5b5766 100644 --- a/examples/dual/host_info_to_device_cdc/CMakeLists.txt +++ b/examples/dual/host_info_to_device_cdc/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.17) +cmake_minimum_required(VERSION 3.20) include(${CMAKE_CURRENT_SOURCE_DIR}/../../../hw/bsp/family_support.cmake) diff --git a/examples/dual/host_info_to_device_cdc/CMakePresets.json b/examples/dual/host_info_to_device_cdc/CMakePresets.json new file mode 100644 index 000000000..5cd8971e9 --- /dev/null +++ b/examples/dual/host_info_to_device_cdc/CMakePresets.json @@ -0,0 +1,6 @@ +{ + "version": 6, + "include": [ + "../../../hw/bsp/BoardPresets.json" + ] +} diff --git a/examples/dual/host_info_to_device_cdc/src/main.c b/examples/dual/host_info_to_device_cdc/src/main.c index 668808db2..a2a505952 100644 --- a/examples/dual/host_info_to_device_cdc/src/main.c +++ b/examples/dual/host_info_to_device_cdc/src/main.c @@ -70,11 +70,30 @@ enum { static uint32_t blink_interval_ms = BLINK_NOT_MOUNTED; static bool is_print[CFG_TUH_DEVICE_MAX+1] = { 0 }; +static tusb_desc_device_t descriptor_device[CFG_TUH_DEVICE_MAX+1]; static void print_utf16(uint16_t *temp_buf, size_t buf_len); +static void print_device_info(uint8_t daddr, const tusb_desc_device_t* desc_device); + void led_blinking_task(void); void cdc_task(void); +#define cdc_printf(...) \ + do { \ + char _tempbuf[256]; \ + char* _bufptr = _tempbuf; \ + uint32_t count = (uint32_t) sprintf(_tempbuf, __VA_ARGS__); \ + while (count > 0) { \ + uint32_t wr_count = tud_cdc_write(_bufptr, count); \ + count -= wr_count; \ + _bufptr += wr_count; \ + if (count > 0){ \ + tud_task(); \ + tud_cdc_write_flush(); \ + } \ + } \ + } while(0) + /*------------- MAIN -------------*/ int main(void) { board_init(); @@ -135,84 +154,20 @@ void tud_resume_cb(void) { blink_interval_ms = tud_mounted() ? BLINK_MOUNTED : BLINK_NOT_MOUNTED; } -#if 1 -#define cdc_printf(...) \ - do { \ - char _tempbuf[256]; \ - int count = sprintf(_tempbuf, __VA_ARGS__); \ - tud_cdc_write(_tempbuf, (uint32_t) count); \ - tud_cdc_write_flush(); \ - tud_task(); \ - } while(0) -#endif - -//#define cdc_printf printf - -void print_device_info(uint8_t daddr) { - tusb_desc_device_t desc_device; - uint8_t xfer_result = tuh_descriptor_get_device_sync(daddr, &desc_device, 18); - if (XFER_RESULT_SUCCESS != xfer_result) { - tud_cdc_write_str("Failed to get device descriptor\r\n"); +void cdc_task(void) { + if (!tud_cdc_connected()) { + // delay a bit otherwise we can outpace host's terminal. Linux will set LineState (DTR) then Line Coding. + // If we send data before Linux's terminal set Line Coding, it can be ignored --> missing data with hardware test loop + board_delay(20); return; } - // Get String descriptor using Sync API - uint16_t serial[64]; - uint16_t buf[128]; - - cdc_printf("Device %u: ID %04x:%04x SN ", daddr, desc_device.idVendor, desc_device.idProduct); - xfer_result = tuh_descriptor_get_serial_string_sync(daddr, LANGUAGE_ID, serial, sizeof(serial)); - if (XFER_RESULT_SUCCESS != xfer_result) { - serial[0] = 'n'; - serial[1] = '/'; - serial[2] = 'a'; - serial[3] = 0; - } - print_utf16(serial, TU_ARRAY_SIZE(serial)); - tud_cdc_write_str("\r\n"); - - cdc_printf("Device Descriptor:\r\n"); - cdc_printf(" bLength %u\r\n" , desc_device.bLength); - cdc_printf(" bDescriptorType %u\r\n" , desc_device.bDescriptorType); - cdc_printf(" bcdUSB %04x\r\n" , desc_device.bcdUSB); - cdc_printf(" bDeviceClass %u\r\n" , desc_device.bDeviceClass); - cdc_printf(" bDeviceSubClass %u\r\n" , desc_device.bDeviceSubClass); - cdc_printf(" bDeviceProtocol %u\r\n" , desc_device.bDeviceProtocol); - cdc_printf(" bMaxPacketSize0 %u\r\n" , desc_device.bMaxPacketSize0); - cdc_printf(" idVendor 0x%04x\r\n" , desc_device.idVendor); - cdc_printf(" idProduct 0x%04x\r\n" , desc_device.idProduct); - cdc_printf(" bcdDevice %04x\r\n" , desc_device.bcdDevice); - - cdc_printf(" iManufacturer %u " , desc_device.iManufacturer); - xfer_result = tuh_descriptor_get_manufacturer_string_sync(daddr, LANGUAGE_ID, buf, sizeof(buf)); - if (XFER_RESULT_SUCCESS == xfer_result ) { - print_utf16(buf, TU_ARRAY_SIZE(buf)); - } - tud_cdc_write_str("\r\n"); - - cdc_printf(" iProduct %u " , desc_device.iProduct); - xfer_result = tuh_descriptor_get_product_string_sync(daddr, LANGUAGE_ID, buf, sizeof(buf)); - if (XFER_RESULT_SUCCESS == xfer_result) { - print_utf16(buf, TU_ARRAY_SIZE(buf)); - } - tud_cdc_write_str("\r\n"); - - cdc_printf(" iSerialNumber %u " , desc_device.iSerialNumber); - tud_cdc_write_str((char*)serial); // serial is already to UTF-8 - tud_cdc_write_str("\r\n"); - - cdc_printf(" bNumConfigurations %u\r\n" , desc_device.bNumConfigurations); -} - -void cdc_task(void) { - if (tud_cdc_connected()) { - for (uint8_t daddr = 1; daddr <= CFG_TUH_DEVICE_MAX; daddr++) { - if (tuh_mounted(daddr)) { - if (is_print[daddr]) { - is_print[daddr] = false; - print_device_info(daddr); - tud_cdc_write_flush(); - } + for (uint8_t daddr = 1; daddr <= CFG_TUH_DEVICE_MAX; daddr++) { + if (tuh_mounted(daddr)) { + if (is_print[daddr]) { + is_print[daddr] = false; + print_device_info(daddr, &descriptor_device[daddr]); + tud_cdc_write_flush(); } } } @@ -221,13 +176,70 @@ void cdc_task(void) { //--------------------------------------------------------------------+ // Host Get device information //--------------------------------------------------------------------+ +static void print_device_info(uint8_t daddr, const tusb_desc_device_t* desc_device) { + // Get String descriptor using Sync API + uint16_t serial[64]; + uint16_t buf[128]; + (void) buf; + + cdc_printf("Device %u: ID %04x:%04x SN ", daddr, desc_device->idVendor, desc_device->idProduct); + uint8_t xfer_result = tuh_descriptor_get_serial_string_sync(daddr, LANGUAGE_ID, serial, sizeof(serial)); + if (XFER_RESULT_SUCCESS != xfer_result) { + serial[0] = 'n'; + serial[1] = '/'; + serial[2] = 'a'; + serial[3] = 0; + } + print_utf16(serial, TU_ARRAY_SIZE(serial)); + cdc_printf("\r\n"); + + cdc_printf("Device Descriptor:\r\n"); + cdc_printf(" bLength %u\r\n" , desc_device->bLength); + cdc_printf(" bDescriptorType %u\r\n" , desc_device->bDescriptorType); + cdc_printf(" bcdUSB %04x\r\n" , desc_device->bcdUSB); + cdc_printf(" bDeviceClass %u\r\n" , desc_device->bDeviceClass); + cdc_printf(" bDeviceSubClass %u\r\n" , desc_device->bDeviceSubClass); + cdc_printf(" bDeviceProtocol %u\r\n" , desc_device->bDeviceProtocol); + cdc_printf(" bMaxPacketSize0 %u\r\n" , desc_device->bMaxPacketSize0); + cdc_printf(" idVendor 0x%04x\r\n" , desc_device->idVendor); + cdc_printf(" idProduct 0x%04x\r\n" , desc_device->idProduct); + cdc_printf(" bcdDevice %04x\r\n" , desc_device->bcdDevice); + + cdc_printf(" iManufacturer %u " , desc_device->iManufacturer); + xfer_result = tuh_descriptor_get_manufacturer_string_sync(daddr, LANGUAGE_ID, buf, sizeof(buf)); + if (XFER_RESULT_SUCCESS == xfer_result) { + print_utf16(buf, TU_ARRAY_SIZE(buf)); + } + cdc_printf("\r\n"); + + cdc_printf(" iProduct %u " , desc_device->iProduct); + xfer_result = tuh_descriptor_get_product_string_sync(daddr, LANGUAGE_ID, buf, sizeof(buf)); + if (XFER_RESULT_SUCCESS == xfer_result) { + print_utf16(buf, TU_ARRAY_SIZE(buf)); + } + cdc_printf("\r\n"); + + cdc_printf(" iSerialNumber %u " , desc_device->iSerialNumber); + cdc_printf((char*)serial); // serial is already to UTF-8 + cdc_printf("\r\n"); + + cdc_printf(" bNumConfigurations %u\r\n" , desc_device->bNumConfigurations); +} + +void tuh_enum_descriptor_device_cb(uint8_t daddr, tusb_desc_device_t const* desc_device) { + (void) daddr; + descriptor_device[daddr] = *desc_device; // save device descriptor +} + void tuh_mount_cb(uint8_t daddr) { - printf("mounted device %u\r\n", daddr); + cdc_printf("mounted device %u\r\n", daddr); + tud_cdc_write_flush(); is_print[daddr] = true; } void tuh_umount_cb(uint8_t daddr) { - printf("unmounted device %u\r\n", daddr); + cdc_printf("unmounted device %u\r\n", daddr); + tud_cdc_write_flush(); is_print[daddr] = false; } @@ -239,7 +251,9 @@ void led_blinking_task(void) { static bool led_state = false; // Blink every interval ms - if (board_millis() - start_ms < blink_interval_ms) return; // not enough time + if (board_millis() - start_ms < blink_interval_ms) { + return;// not enough time + } start_ms += blink_interval_ms; board_led_write(led_state); @@ -290,13 +304,13 @@ static int _count_utf8_bytes(const uint16_t *buf, size_t len) { } static void print_utf16(uint16_t *temp_buf, size_t buf_len) { - if ((temp_buf[0] & 0xff) == 0) return; // empty + if ((temp_buf[0] & 0xff) == 0) { + return;// empty + } size_t utf16_len = ((temp_buf[0] & 0xff) - 2) / sizeof(uint16_t); size_t utf8_len = (size_t) _count_utf8_bytes(temp_buf + 1, utf16_len); _convert_utf16le_to_utf8(temp_buf + 1, utf16_len, (uint8_t *) temp_buf, sizeof(uint16_t) * buf_len); ((uint8_t*) temp_buf)[utf8_len] = '\0'; - tud_cdc_write(temp_buf, utf8_len); - tud_cdc_write_flush(); - tud_task(); + cdc_printf((char*) temp_buf); } diff --git a/examples/host/CMakeLists.txt b/examples/host/CMakeLists.txt index 793f6ab08..2783dd84e 100644 --- a/examples/host/CMakeLists.txt +++ b/examples/host/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.17) +cmake_minimum_required(VERSION 3.20) include(${CMAKE_CURRENT_SOURCE_DIR}/../../hw/bsp/family_support.cmake) @@ -11,4 +11,5 @@ family_add_subdirectory(cdc_msc_hid) family_add_subdirectory(cdc_msc_hid_freertos) family_add_subdirectory(device_info) family_add_subdirectory(hid_controller) +family_add_subdirectory(midi_rx) family_add_subdirectory(msc_file_explorer) diff --git a/examples/host/CMakePresets.json b/examples/host/CMakePresets.json new file mode 100644 index 000000000..c22e8c0ec --- /dev/null +++ b/examples/host/CMakePresets.json @@ -0,0 +1,6 @@ +{ + "version": 6, + "include": [ + "../../hw/bsp/BoardPresets.json" + ] +} diff --git a/examples/host/bare_api/CMakeLists.txt b/examples/host/bare_api/CMakeLists.txt index 76182d6fa..0efe84b60 100644 --- a/examples/host/bare_api/CMakeLists.txt +++ b/examples/host/bare_api/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.17) +cmake_minimum_required(VERSION 3.20) include(${CMAKE_CURRENT_SOURCE_DIR}/../../../hw/bsp/family_support.cmake) diff --git a/examples/host/bare_api/CMakePresets.json b/examples/host/bare_api/CMakePresets.json new file mode 100644 index 000000000..5cd8971e9 --- /dev/null +++ b/examples/host/bare_api/CMakePresets.json @@ -0,0 +1,6 @@ +{ + "version": 6, + "include": [ + "../../../hw/bsp/BoardPresets.json" + ] +} diff --git a/examples/host/bare_api/only.txt b/examples/host/bare_api/only.txt index 95f9f1d82..dcdaf41c7 100644 --- a/examples/host/bare_api/only.txt +++ b/examples/host/bare_api/only.txt @@ -15,3 +15,5 @@ mcu:MAX3421 mcu:STM32F4 mcu:STM32F7 mcu:STM32H7 +mcu:STM32H7RS +mcu:STM32N6 diff --git a/examples/host/bare_api/src/main.c b/examples/host/bare_api/src/main.c index f582f4f5a..0c76ff0c9 100644 --- a/examples/host/bare_api/src/main.c +++ b/examples/host/bare_api/src/main.c @@ -55,16 +55,15 @@ uint8_t* get_hid_buf(uint8_t daddr); void free_hid_buf(uint8_t daddr); /*------------- MAIN -------------*/ -int main(void) -{ +int main(void) { board_init(); printf("TinyUSB Bare API Example\r\n"); // init host stack on configured roothub port tusb_rhport_init_t host_init = { - .role = TUSB_ROLE_HOST, - .speed = TUSB_SPEED_AUTO + .role = TUSB_ROLE_HOST, + .speed = TUSB_SPEED_AUTO }; tusb_init(BOARD_TUH_RHPORT, &host_init); @@ -72,8 +71,7 @@ int main(void) board_init_after_tusb(); } - while (1) - { + while (1) { // tinyusb host task tuh_task(); led_blinking_task(); @@ -85,8 +83,7 @@ int main(void) /*------------- TinyUSB Callbacks -------------*/ // Invoked when device is mounted (configured) -void tuh_mount_cb (uint8_t daddr) -{ +void tuh_mount_cb(uint8_t daddr) { printf("Device attached, address = %d\r\n", daddr); // Get Device Descriptor @@ -95,8 +92,7 @@ void tuh_mount_cb (uint8_t daddr) } /// Invoked when device is unmounted (bus reset/unplugged) -void tuh_umount_cb(uint8_t daddr) -{ +void tuh_umount_cb(uint8_t daddr) { printf("Device removed, address = %d\r\n", daddr); free_hid_buf(daddr); } @@ -104,11 +100,8 @@ void tuh_umount_cb(uint8_t daddr) //--------------------------------------------------------------------+ // Device Descriptor //--------------------------------------------------------------------+ - -void print_device_descriptor(tuh_xfer_t* xfer) -{ - if ( XFER_RESULT_SUCCESS != xfer->result ) - { +void print_device_descriptor(tuh_xfer_t *xfer) { + if (XFER_RESULT_SUCCESS != xfer->result) { printf("Failed to get device descriptor\r\n"); return; } @@ -131,33 +124,29 @@ void print_device_descriptor(tuh_xfer_t* xfer) // Get String descriptor using Sync API uint16_t temp_buf[128]; - printf(" iManufacturer %u " , desc_device.iManufacturer); - if (XFER_RESULT_SUCCESS == tuh_descriptor_get_manufacturer_string_sync(daddr, LANGUAGE_ID, temp_buf, sizeof(temp_buf)) ) - { + printf(" iManufacturer %u ", desc_device.iManufacturer); + if (XFER_RESULT_SUCCESS == tuh_descriptor_get_manufacturer_string_sync(daddr, LANGUAGE_ID, temp_buf, sizeof(temp_buf))) { print_utf16(temp_buf, TU_ARRAY_SIZE(temp_buf)); } printf("\r\n"); - printf(" iProduct %u " , desc_device.iProduct); - if (XFER_RESULT_SUCCESS == tuh_descriptor_get_product_string_sync(daddr, LANGUAGE_ID, temp_buf, sizeof(temp_buf))) - { + printf(" iProduct %u ", desc_device.iProduct); + if (XFER_RESULT_SUCCESS == tuh_descriptor_get_product_string_sync(daddr, LANGUAGE_ID, temp_buf, sizeof(temp_buf))) { print_utf16(temp_buf, TU_ARRAY_SIZE(temp_buf)); } printf("\r\n"); - printf(" iSerialNumber %u " , desc_device.iSerialNumber); - if (XFER_RESULT_SUCCESS == tuh_descriptor_get_serial_string_sync(daddr, LANGUAGE_ID, temp_buf, sizeof(temp_buf))) - { + printf(" iSerialNumber %u ", desc_device.iSerialNumber); + if (XFER_RESULT_SUCCESS == tuh_descriptor_get_serial_string_sync(daddr, LANGUAGE_ID, temp_buf, sizeof(temp_buf))) { print_utf16(temp_buf, TU_ARRAY_SIZE(temp_buf)); } printf("\r\n"); - printf(" bNumConfigurations %u\r\n" , desc_device.bNumConfigurations); + printf(" bNumConfigurations %u\r\n", desc_device.bNumConfigurations); // Get configuration descriptor with sync API - if (XFER_RESULT_SUCCESS == tuh_descriptor_get_configuration_sync(daddr, 0, temp_buf, sizeof(temp_buf))) - { - parse_config_descriptor(daddr, (tusb_desc_configuration_t*) temp_buf); + if (XFER_RESULT_SUCCESS == tuh_descriptor_get_configuration_sync(daddr, 0, temp_buf, sizeof(temp_buf))) { + parse_config_descriptor(daddr, (tusb_desc_configuration_t *) temp_buf); } } @@ -171,37 +160,33 @@ uint16_t count_interface_total_len(tusb_desc_interface_t const* desc_itf, uint8_ void open_hid_interface(uint8_t daddr, tusb_desc_interface_t const *desc_itf, uint16_t max_len); // simple configuration parser to open and listen to HID Endpoint IN -void parse_config_descriptor(uint8_t dev_addr, tusb_desc_configuration_t const* desc_cfg) -{ - uint8_t const* desc_end = ((uint8_t const*) desc_cfg) + tu_le16toh(desc_cfg->wTotalLength); - uint8_t const* p_desc = tu_desc_next(desc_cfg); +void parse_config_descriptor(uint8_t dev_addr, tusb_desc_configuration_t const *desc_cfg) { + uint8_t const *desc_end = ((uint8_t const *) desc_cfg) + tu_le16toh(desc_cfg->wTotalLength); + uint8_t const *p_desc = tu_desc_next(desc_cfg); // parse each interfaces - while( p_desc < desc_end ) - { + while (p_desc < desc_end) { uint8_t assoc_itf_count = 1; // Class will always starts with Interface Association (if any) and then Interface descriptor - if ( TUSB_DESC_INTERFACE_ASSOCIATION == tu_desc_type(p_desc) ) - { - tusb_desc_interface_assoc_t const * desc_iad = (tusb_desc_interface_assoc_t const *) p_desc; + if (TUSB_DESC_INTERFACE_ASSOCIATION == tu_desc_type(p_desc)) { + tusb_desc_interface_assoc_t const *desc_iad = (tusb_desc_interface_assoc_t const *) p_desc; assoc_itf_count = desc_iad->bInterfaceCount; - p_desc = tu_desc_next(p_desc); // next to Interface + p_desc = tu_desc_next(p_desc);// next to Interface } // must be interface from now - if( TUSB_DESC_INTERFACE != tu_desc_type(p_desc) ) return; - tusb_desc_interface_t const* desc_itf = (tusb_desc_interface_t const*) p_desc; + if (TUSB_DESC_INTERFACE != tu_desc_type(p_desc)) { return; } + tusb_desc_interface_t const *desc_itf = (tusb_desc_interface_t const *) p_desc; - uint16_t const drv_len = count_interface_total_len(desc_itf, assoc_itf_count, (uint16_t) (desc_end-p_desc)); + uint16_t const drv_len = count_interface_total_len(desc_itf, assoc_itf_count, (uint16_t) (desc_end - p_desc)); // probably corrupted descriptor - if(drv_len < sizeof(tusb_desc_interface_t)) return; + if (drv_len < sizeof(tusb_desc_interface_t)) { return; } // only open and listen to HID endpoint IN - if (desc_itf->bInterfaceClass == TUSB_CLASS_HID) - { + if (desc_itf->bInterfaceClass == TUSB_CLASS_HID) { open_hid_interface(dev_addr, desc_itf, drv_len); } @@ -210,25 +195,21 @@ void parse_config_descriptor(uint8_t dev_addr, tusb_desc_configuration_t const* } } -uint16_t count_interface_total_len(tusb_desc_interface_t const* desc_itf, uint8_t itf_count, uint16_t max_len) -{ - uint8_t const* p_desc = (uint8_t const*) desc_itf; +uint16_t count_interface_total_len(tusb_desc_interface_t const *desc_itf, uint8_t itf_count, uint16_t max_len) { + uint8_t const *p_desc = (uint8_t const *) desc_itf; uint16_t len = 0; - while (itf_count--) - { + while (itf_count--) { // Next on interface desc len += tu_desc_len(desc_itf); p_desc = tu_desc_next(p_desc); - while (len < max_len) - { + while (len < max_len) { // return on IAD regardless of itf count - if ( tu_desc_type(p_desc) == TUSB_DESC_INTERFACE_ASSOCIATION ) return len; + if (tu_desc_type(p_desc) == TUSB_DESC_INTERFACE_ASSOCIATION) { return len; } - if ( (tu_desc_type(p_desc) == TUSB_DESC_INTERFACE) && - ((tusb_desc_interface_t const*) p_desc)->bAlternateSetting == 0 ) - { + if ((tu_desc_type(p_desc) == TUSB_DESC_INTERFACE) && + ((tusb_desc_interface_t const *) p_desc)->bAlternateSetting == 0) { break; } @@ -246,46 +227,45 @@ uint16_t count_interface_total_len(tusb_desc_interface_t const* desc_itf, uint8_ void hid_report_received(tuh_xfer_t* xfer); -void open_hid_interface(uint8_t daddr, tusb_desc_interface_t const *desc_itf, uint16_t max_len) -{ +void open_hid_interface(uint8_t daddr, tusb_desc_interface_t const *desc_itf, uint16_t max_len) { // len = interface + hid + n*endpoints uint16_t const drv_len = (uint16_t) (sizeof(tusb_desc_interface_t) + sizeof(tusb_hid_descriptor_hid_t) + desc_itf->bNumEndpoints * sizeof(tusb_desc_endpoint_t)); // corrupted descriptor - if (max_len < drv_len) return; + if (max_len < drv_len) { return; } uint8_t const *p_desc = (uint8_t const *) desc_itf; // HID descriptor p_desc = tu_desc_next(p_desc); tusb_hid_descriptor_hid_t const *desc_hid = (tusb_hid_descriptor_hid_t const *) p_desc; - if(HID_DESC_TYPE_HID != desc_hid->bDescriptorType) return; + if (HID_DESC_TYPE_HID != desc_hid->bDescriptorType) { return; } // Endpoint descriptor p_desc = tu_desc_next(p_desc); - tusb_desc_endpoint_t const * desc_ep = (tusb_desc_endpoint_t const *) p_desc; + tusb_desc_endpoint_t const *desc_ep = (tusb_desc_endpoint_t const *) p_desc; - for(int i = 0; i < desc_itf->bNumEndpoints; i++) - { - if (TUSB_DESC_ENDPOINT != desc_ep->bDescriptorType) return; + for (int i = 0; i < desc_itf->bNumEndpoints; i++) { + if (TUSB_DESC_ENDPOINT != desc_ep->bDescriptorType) { return; } - if(tu_edpt_dir(desc_ep->bEndpointAddress) == TUSB_DIR_IN) - { - // skip if failed to open endpoint - if ( ! tuh_edpt_open(daddr, desc_ep) ) return; + if (tu_edpt_dir(desc_ep->bEndpointAddress) == TUSB_DIR_IN) { + if (!tuh_edpt_open(daddr, desc_ep)) { + return; // skip if failed to open endpoint + } - uint8_t* buf = get_hid_buf(daddr); - if (!buf) return; // out of memory + uint8_t *buf = get_hid_buf(daddr); + if (!buf) { + return;// out of memory + } - tuh_xfer_t xfer = - { - .daddr = daddr, - .ep_addr = desc_ep->bEndpointAddress, - .buflen = 64, - .buffer = buf, - .complete_cb = hid_report_received, - .user_data = (uintptr_t) buf, // since buffer is not available in callback, use user data to store the buffer + tuh_xfer_t xfer = { + .daddr = daddr, + .ep_addr = desc_ep->bEndpointAddress, + .buflen = 64, + .buffer = buf, + .complete_cb = hid_report_received, + .user_data = (uintptr_t) buf,// since buffer is not available in callback, use user data to store the buffer }; // submit transfer for this EP @@ -299,18 +279,17 @@ void open_hid_interface(uint8_t daddr, tusb_desc_interface_t const *desc_itf, ui } } -void hid_report_received(tuh_xfer_t* xfer) -{ +void hid_report_received(tuh_xfer_t *xfer) { // Note: not all field in xfer is available for use (i.e filled by tinyusb stack) in callback to save sram // For instance, xfer->buffer is NULL. We have used user_data to store buffer when submitted callback - uint8_t* buf = (uint8_t*) xfer->user_data; + uint8_t *buf = (uint8_t *) xfer->user_data; - if (xfer->result == XFER_RESULT_SUCCESS) - { + if (xfer->result == XFER_RESULT_SUCCESS) { printf("[dev %u: ep %02x] HID Report:", xfer->daddr, xfer->ep_addr); - for(uint32_t i=0; iactual_len; i++) - { - if (i%16 == 0) printf("\r\n "); + for (uint32_t i = 0; i < xfer->actual_len; i++) { + if (i % 16 == 0) { + printf("\r\n "); + } printf("%02X ", buf[i]); } printf("\r\n"); @@ -329,12 +308,9 @@ void hid_report_received(tuh_xfer_t* xfer) //--------------------------------------------------------------------+ // get an buffer from pool -uint8_t* get_hid_buf(uint8_t daddr) -{ - for(size_t i=0; i> 6 & 0x1F)); - *utf8++ = (uint8_t)(0x80 | (chr >> 0 & 0x3F)); - } else { - // TODO: Verify surrogate. - *utf8++ = (uint8_t)(0xE0 | (chr >> 12 & 0x0F)); - *utf8++ = (uint8_t)(0x80 | (chr >> 6 & 0x3F)); - *utf8++ = (uint8_t)(0x80 | (chr >> 0 & 0x3F)); - } - // TODO: Handle UTF-16 code points that take two entries. + for (size_t i = 0; i < utf16_len; i++) { + uint16_t chr = utf16[i]; + if (chr < 0x80) { + *utf8++ = chr & 0xffu; + } else if (chr < 0x800) { + *utf8++ = (uint8_t) (0xC0 | (chr >> 6 & 0x1F)); + *utf8++ = (uint8_t) (0x80 | (chr >> 0 & 0x3F)); + } else { + // TODO: Verify surrogate. + *utf8++ = (uint8_t) (0xE0 | (chr >> 12 & 0x0F)); + *utf8++ = (uint8_t) (0x80 | (chr >> 6 & 0x3F)); + *utf8++ = (uint8_t) (0x80 | (chr >> 0 & 0x3F)); } + // TODO: Handle UTF-16 code points that take two entries. + } } // Count how many bytes a utf-16-le encoded string will take in utf-8. static int _count_utf8_bytes(const uint16_t *buf, size_t len) { - size_t total_bytes = 0; - for (size_t i = 0; i < len; i++) { - uint16_t chr = buf[i]; - if (chr < 0x80) { - total_bytes += 1; - } else if (chr < 0x800) { - total_bytes += 2; - } else { - total_bytes += 3; - } - // TODO: Handle UTF-16 code points that take two entries. + size_t total_bytes = 0; + for (size_t i = 0; i < len; i++) { + uint16_t chr = buf[i]; + if (chr < 0x80) { + total_bytes += 1; + } else if (chr < 0x800) { + total_bytes += 2; + } else { + total_bytes += 3; } - return (int) total_bytes; + // TODO: Handle UTF-16 code points that take two entries. + } + return (int) total_bytes; } static void print_utf16(uint16_t *temp_buf, size_t buf_len) { - if ((temp_buf[0] & 0xff) == 0) return; // empty - size_t utf16_len = ((temp_buf[0] & 0xff) - 2) / sizeof(uint16_t); - size_t utf8_len = (size_t) _count_utf8_bytes(temp_buf + 1, utf16_len); - _convert_utf16le_to_utf8(temp_buf + 1, utf16_len, (uint8_t *) temp_buf, sizeof(uint16_t) * buf_len); - ((uint8_t*) temp_buf)[utf8_len] = '\0'; + if ((temp_buf[0] & 0xff) == 0) return;// empty + size_t utf16_len = ((temp_buf[0] & 0xff) - 2) / sizeof(uint16_t); + size_t utf8_len = (size_t) _count_utf8_bytes(temp_buf + 1, utf16_len); + _convert_utf16le_to_utf8(temp_buf + 1, utf16_len, (uint8_t *) temp_buf, sizeof(uint16_t) * buf_len); + ((uint8_t *) temp_buf)[utf8_len] = '\0'; - printf("%s", (char*)temp_buf); + printf("%s", (char *) temp_buf); } diff --git a/examples/host/bare_api/src/tusb_config.h b/examples/host/bare_api/src/tusb_config.h index fab233be0..a03675c5f 100644 --- a/examples/host/bare_api/src/tusb_config.h +++ b/examples/host/bare_api/src/tusb_config.h @@ -69,9 +69,10 @@ // Enable Host stack #define CFG_TUH_ENABLED 1 +// #define CFG_TUH_MAX3421 1 // use max3421 as host controller + #if CFG_TUSB_MCU == OPT_MCU_RP2040 // #define CFG_TUH_RPI_PIO_USB 1 // use pio-usb as host controller - // #define CFG_TUH_MAX3421 1 // use max3421 as host controller // host roothub port is 1 if using either pio-usb or max3421 #if (defined(CFG_TUH_RPI_PIO_USB) && CFG_TUH_RPI_PIO_USB) || (defined(CFG_TUH_MAX3421) && CFG_TUH_MAX3421) diff --git a/examples/host/cdc_msc_hid/CMakeLists.txt b/examples/host/cdc_msc_hid/CMakeLists.txt index a7c372a34..e8928cda5 100644 --- a/examples/host/cdc_msc_hid/CMakeLists.txt +++ b/examples/host/cdc_msc_hid/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.17) +cmake_minimum_required(VERSION 3.20) include(${CMAKE_CURRENT_SOURCE_DIR}/../../../hw/bsp/family_support.cmake) diff --git a/examples/host/cdc_msc_hid/CMakePresets.json b/examples/host/cdc_msc_hid/CMakePresets.json new file mode 100644 index 000000000..5cd8971e9 --- /dev/null +++ b/examples/host/cdc_msc_hid/CMakePresets.json @@ -0,0 +1,6 @@ +{ + "version": 6, + "include": [ + "../../../hw/bsp/BoardPresets.json" + ] +} diff --git a/examples/host/cdc_msc_hid/only.txt b/examples/host/cdc_msc_hid/only.txt index 95f9f1d82..dcdaf41c7 100644 --- a/examples/host/cdc_msc_hid/only.txt +++ b/examples/host/cdc_msc_hid/only.txt @@ -15,3 +15,5 @@ mcu:MAX3421 mcu:STM32F4 mcu:STM32F7 mcu:STM32H7 +mcu:STM32H7RS +mcu:STM32N6 diff --git a/examples/host/cdc_msc_hid/src/cdc_app.c b/examples/host/cdc_msc_hid/src/cdc_app.c index 4a13f8b27..97f1a96d6 100644 --- a/examples/host/cdc_msc_hid/src/cdc_app.c +++ b/examples/host/cdc_msc_hid/src/cdc_app.c @@ -27,12 +27,11 @@ #include "tusb.h" #include "bsp/board_api.h" -size_t get_console_inputs(uint8_t* buf, size_t bufsize) { +static size_t get_console_inputs(uint8_t* buf, size_t bufsize) { size_t count = 0; while (count < bufsize) { int ch = board_getchar(); - if (ch <= 0) break; - + if (ch <= 0) { break; } buf[count] = (uint8_t) ch; count++; } @@ -69,10 +68,15 @@ void tuh_cdc_rx_cb(uint8_t idx) { uint32_t const bufsize = sizeof(buf) - 1; // forward cdc interfaces -> console - uint32_t count = tuh_cdc_read(idx, buf, bufsize); - buf[count] = 0; + const uint32_t count = tuh_cdc_read(idx, buf, bufsize); + if (count) { + buf[count] = 0; + printf("%s", (char*) buf); - printf("%s", (char*) buf); + #ifndef __ICCARM__ // TODO IAR doesn't support stream control ? + fflush(stdout);// flush right away, else nanolib will wait for newline + #endif + } } // Invoked when a device with CDC interface is mounted @@ -88,7 +92,7 @@ void tuh_cdc_mount_cb(uint8_t idx) { // If CFG_TUH_CDC_LINE_CODING_ON_ENUM is defined, line coding will be set by tinyusb stack // while eneumerating new cdc device cdc_line_coding_t line_coding = {0}; - if (tuh_cdc_get_local_line_coding(idx, &line_coding)) { + if (tuh_cdc_get_line_coding_local(idx, &line_coding)) { printf(" Baudrate: %" PRIu32 ", Stop Bits : %u\r\n", line_coding.bit_rate, line_coding.stop_bits); printf(" Parity : %u, Data Width: %u\r\n", line_coding.parity, line_coding.data_bits); } diff --git a/examples/host/cdc_msc_hid/src/hid_app.c b/examples/host/cdc_msc_hid/src/hid_app.c index 3f98ec89f..6f01d6f45 100644 --- a/examples/host/cdc_msc_hid/src/hid_app.c +++ b/examples/host/cdc_msc_hid/src/hid_app.c @@ -29,28 +29,21 @@ //--------------------------------------------------------------------+ // MACRO TYPEDEF CONSTANT ENUM DECLARATION //--------------------------------------------------------------------+ +#define MAX_REPORT 4 -// If your host terminal support ansi escape code such as TeraTerm -// it can be use to simulate mouse cursor movement within terminal -#define USE_ANSI_ESCAPE 0 - -#define MAX_REPORT 4 - -static uint8_t const keycode2ascii[128][2] = { HID_KEYCODE_TO_ASCII }; +static uint8_t const keycode2ascii[128][2] = {HID_KEYCODE_TO_ASCII}; // Each HID instance can has multiple reports -static struct -{ +static struct { uint8_t report_count; tuh_hid_report_info_t report_info[MAX_REPORT]; -}hid_info[CFG_TUH_HID]; +} hid_info[CFG_TUH_HID]; static void process_kbd_report(hid_keyboard_report_t const *report); -static void process_mouse_report(hid_mouse_report_t const * report); -static void process_generic_report(uint8_t dev_addr, uint8_t instance, uint8_t const* report, uint16_t len); +static void process_mouse_report(hid_mouse_report_t const *report); +static void process_generic_report(uint8_t dev_addr, uint8_t instance, uint8_t const *report, uint16_t len); -void hid_app_task(void) -{ +void hid_app_task(void) { // nothing to do } @@ -63,64 +56,57 @@ void hid_app_task(void) // can be used to parse common/simple enough descriptor. // Note: if report descriptor length > CFG_TUH_ENUMERATION_BUFSIZE, it will be skipped // therefore report_desc = NULL, desc_len = 0 -void tuh_hid_mount_cb(uint8_t dev_addr, uint8_t instance, uint8_t const* desc_report, uint16_t desc_len) -{ +void tuh_hid_mount_cb(uint8_t dev_addr, uint8_t instance, uint8_t const *desc_report, uint16_t desc_len) { printf("HID device address = %d, instance = %d is mounted\r\n", dev_addr, instance); // Interface protocol (hid_interface_protocol_enum_t) - const char* protocol_str[] = { "None", "Keyboard", "Mouse" }; + const char *protocol_str[] = {"None", "Keyboard", "Mouse"}; uint8_t const itf_protocol = tuh_hid_interface_protocol(dev_addr, instance); printf("HID Interface Protocol = %s\r\n", protocol_str[itf_protocol]); - // By default host stack will use activate boot protocol on supported interface. + // By default, host stack will use boot protocol on supported interface. // Therefore for this simple example, we only need to parse generic report descriptor (with built-in parser) - if ( itf_protocol == HID_ITF_PROTOCOL_NONE ) - { + if (itf_protocol == HID_ITF_PROTOCOL_NONE) { hid_info[instance].report_count = tuh_hid_parse_report_descriptor(hid_info[instance].report_info, MAX_REPORT, desc_report, desc_len); printf("HID has %u reports \r\n", hid_info[instance].report_count); } // request to receive report // tuh_hid_report_received_cb() will be invoked when report is available - if ( !tuh_hid_receive_report(dev_addr, instance) ) - { + if (!tuh_hid_receive_report(dev_addr, instance)) { printf("Error: cannot request to receive report\r\n"); } } // Invoked when device with hid interface is un-mounted -void tuh_hid_umount_cb(uint8_t dev_addr, uint8_t instance) -{ +void tuh_hid_umount_cb(uint8_t dev_addr, uint8_t instance) { printf("HID device address = %d, instance = %d is unmounted\r\n", dev_addr, instance); } // Invoked when received report from device via interrupt endpoint -void tuh_hid_report_received_cb(uint8_t dev_addr, uint8_t instance, uint8_t const* report, uint16_t len) -{ +void tuh_hid_report_received_cb(uint8_t dev_addr, uint8_t instance, uint8_t const *report, uint16_t len) { uint8_t const itf_protocol = tuh_hid_interface_protocol(dev_addr, instance); - switch (itf_protocol) - { + switch (itf_protocol) { case HID_ITF_PROTOCOL_KEYBOARD: TU_LOG2("HID receive boot keyboard report\r\n"); - process_kbd_report( (hid_keyboard_report_t const*) report ); - break; + process_kbd_report((hid_keyboard_report_t const *) report); + break; case HID_ITF_PROTOCOL_MOUSE: TU_LOG2("HID receive boot mouse report\r\n"); - process_mouse_report( (hid_mouse_report_t const*) report ); - break; + process_mouse_report((hid_mouse_report_t const *) report); + break; default: // Generic report requires matching ReportID and contents with previous parsed report info process_generic_report(dev_addr, instance, report, len); - break; + break; } // continue to request to receive report - if ( !tuh_hid_receive_report(dev_addr, instance) ) - { + if (!tuh_hid_receive_report(dev_addr, instance)) { printf("Error: cannot request to receive report\r\n"); } } @@ -130,7 +116,7 @@ void tuh_hid_report_received_cb(uint8_t dev_addr, uint8_t instance, uint8_t cons //--------------------------------------------------------------------+ // look up new key in previous keys -static inline bool find_key_in_report(hid_keyboard_report_t const* report, uint8_t keycode) { +static inline bool find_key_in_report(hid_keyboard_report_t const *report, uint8_t keycode) { for (uint8_t i = 0; i < 6; i++) { if (report->keycode[i] == keycode) { return true; @@ -139,28 +125,25 @@ static inline bool find_key_in_report(hid_keyboard_report_t const* report, uint8 return false; } -static void process_kbd_report(hid_keyboard_report_t const *report) -{ - static hid_keyboard_report_t prev_report = { 0, 0, {0} }; // previous report to check key released +static void process_kbd_report(hid_keyboard_report_t const *report) { + static hid_keyboard_report_t prev_report = {0, 0, {0}};// previous report to check key released //------------- example code ignore control (non-printable) key affects -------------// - for(uint8_t i=0; i<6; i++) - { - if ( report->keycode[i] ) - { - if ( find_key_in_report(&prev_report, report->keycode[i]) ) - { + for (uint8_t i = 0; i < 6; i++) { + if (report->keycode[i]) { + if (find_key_in_report(&prev_report, report->keycode[i])) { // exist in previous report means the current key is holding - }else - { + } else { // not existed in previous report means the current key is pressed bool const is_shift = report->modifier & (KEYBOARD_MODIFIER_LEFTSHIFT | KEYBOARD_MODIFIER_RIGHTSHIFT); uint8_t ch = keycode2ascii[report->keycode[i]][is_shift ? 1 : 0]; putchar(ch); - if ( ch == '\r' ) putchar('\n'); // added new line for enter key + if (ch == '\r') { + putchar('\n'); + } - #ifndef __ICCARM__ // TODO IAR doesn't support stream control ? - fflush(stdout); // flush right away, else nanolib will wait for newline + #ifndef __ICCARM__ // TODO IAR doesn't support stream control ? + fflush(stdout);// flush right away, else nanolib will wait for newline #endif } } @@ -174,86 +157,47 @@ static void process_kbd_report(hid_keyboard_report_t const *report) // Mouse //--------------------------------------------------------------------+ -void cursor_movement(int8_t x, int8_t y, int8_t wheel) -{ -#if USE_ANSI_ESCAPE - // Move X using ansi escape - if ( x < 0) - { - printf(ANSI_CURSOR_BACKWARD(%d), (-x)); // move left - }else if ( x > 0) - { - printf(ANSI_CURSOR_FORWARD(%d), x); // move right - } - - // Move Y using ansi escape - if ( y < 0) - { - printf(ANSI_CURSOR_UP(%d), (-y)); // move up - }else if ( y > 0) - { - printf(ANSI_CURSOR_DOWN(%d), y); // move down - } - - // Scroll using ansi escape - if (wheel < 0) - { - printf(ANSI_SCROLL_UP(%d), (-wheel)); // scroll up - }else if (wheel > 0) - { - printf(ANSI_SCROLL_DOWN(%d), wheel); // scroll down - } - - printf("\r\n"); -#else +static void cursor_movement(int8_t x, int8_t y, int8_t wheel) { printf("(%d %d %d)\r\n", x, y, wheel); -#endif } -static void process_mouse_report(hid_mouse_report_t const * report) -{ - static hid_mouse_report_t prev_report = { 0 }; +static void process_mouse_report(hid_mouse_report_t const *report) { + static hid_mouse_report_t prev_report = {0}; - //------------- button state -------------// + // button state uint8_t button_changed_mask = report->buttons ^ prev_report.buttons; - if ( button_changed_mask & report->buttons) - { + if (button_changed_mask & report->buttons) { printf(" %c%c%c ", - report->buttons & MOUSE_BUTTON_LEFT ? 'L' : '-', - report->buttons & MOUSE_BUTTON_MIDDLE ? 'M' : '-', - report->buttons & MOUSE_BUTTON_RIGHT ? 'R' : '-'); + report->buttons & MOUSE_BUTTON_LEFT ? 'L' : '-', + report->buttons & MOUSE_BUTTON_MIDDLE ? 'M' : '-', + report->buttons & MOUSE_BUTTON_RIGHT ? 'R' : '-'); } - //------------- cursor movement -------------// + // cursor movement cursor_movement(report->x, report->y, report->wheel); } //--------------------------------------------------------------------+ // Generic Report //--------------------------------------------------------------------+ -static void process_generic_report(uint8_t dev_addr, uint8_t instance, uint8_t const* report, uint16_t len) -{ +static void process_generic_report(uint8_t dev_addr, uint8_t instance, uint8_t const *report, uint16_t len) { (void) dev_addr; (void) len; uint8_t const rpt_count = hid_info[instance].report_count; - tuh_hid_report_info_t* rpt_info_arr = hid_info[instance].report_info; - tuh_hid_report_info_t* rpt_info = NULL; + tuh_hid_report_info_t *rpt_info_arr = hid_info[instance].report_info; + tuh_hid_report_info_t *rpt_info = NULL; - if ( rpt_count == 1 && rpt_info_arr[0].report_id == 0) - { + if (rpt_count == 1 && rpt_info_arr[0].report_id == 0) { // Simple report without report ID as 1st byte rpt_info = &rpt_info_arr[0]; - }else - { + } else { // Composite report, 1st byte is report ID, data starts from 2nd byte uint8_t const rpt_id = report[0]; // Find report id in the array - for(uint8_t i=0; iusage_page == HID_USAGE_PAGE_DESKTOP ) - { - switch (rpt_info->usage) - { + if (rpt_info->usage_page == HID_USAGE_PAGE_DESKTOP) { + switch (rpt_info->usage) { case HID_USAGE_DESKTOP_KEYBOARD: - TU_LOG1("HID receive keyboard report\r\n"); + TU_LOG2("HID receive keyboard report\r\n"); // Assume keyboard follow boot report layout - process_kbd_report( (hid_keyboard_report_t const*) report ); - break; + process_kbd_report((hid_keyboard_report_t const *) report); + break; case HID_USAGE_DESKTOP_MOUSE: - TU_LOG1("HID receive mouse report\r\n"); + TU_LOG2("HID receive mouse report\r\n"); // Assume mouse follow boot report layout - process_mouse_report( (hid_mouse_report_t const*) report ); - break; + process_mouse_report((hid_mouse_report_t const *) report); + break; - default: break; + default: + printf("report[%u] ", rpt_info->report_id); + for (uint8_t i = 0; i < len; i++) { + printf("%02X ", report[i]); + } + printf("\r\n"); + break; } } } diff --git a/examples/host/cdc_msc_hid/src/main.c b/examples/host/cdc_msc_hid/src/main.c index 71257c0fe..7b02e238e 100644 --- a/examples/host/cdc_msc_hid/src/main.c +++ b/examples/host/cdc_msc_hid/src/main.c @@ -31,18 +31,12 @@ #include "tusb.h" //--------------------------------------------------------------------+ -// MACRO CONSTANT TYPEDEF PROTYPES +// MACRO CONSTANT TYPEDEF PROTOTYPES //--------------------------------------------------------------------+ void led_blinking_task(void); extern void cdc_app_task(void); extern void hid_app_task(void); -#if CFG_TUH_ENABLED && CFG_TUH_MAX3421 -// API to read/rite MAX3421's register. Implemented by TinyUSB -extern uint8_t tuh_max3421_reg_read(uint8_t rhport, uint8_t reg, bool in_isr); -extern bool tuh_max3421_reg_write(uint8_t rhport, uint8_t reg, uint8_t data, bool in_isr); -#endif - /*------------- MAIN -------------*/ int main(void) { board_init(); @@ -82,12 +76,12 @@ int main(void) { void tuh_mount_cb(uint8_t dev_addr) { // application set-up - printf("A device with address %d is mounted\r\n", dev_addr); + printf("A device with address %u is mounted\r\n", dev_addr); } void tuh_umount_cb(uint8_t dev_addr) { // application tear-down - printf("A device with address %d is unmounted \r\n", dev_addr); + printf("A device with address %u is unmounted \r\n", dev_addr); } @@ -101,7 +95,9 @@ void led_blinking_task(void) { static bool led_state = false; // Blink every interval ms - if (board_millis() - start_ms < interval_ms) return; // not enough time + if (board_millis() - start_ms < interval_ms) { + return;// not enough time + } start_ms += interval_ms; board_led_write(led_state); diff --git a/examples/host/cdc_msc_hid/src/msc_app.c b/examples/host/cdc_msc_hid/src/msc_app.c index 1d7e18e6e..0e9c99766 100644 --- a/examples/host/cdc_msc_hid/src/msc_app.c +++ b/examples/host/cdc_msc_hid/src/msc_app.c @@ -30,13 +30,11 @@ //--------------------------------------------------------------------+ static scsi_inquiry_resp_t inquiry_resp; -bool inquiry_complete_cb(uint8_t dev_addr, tuh_msc_complete_data_t const * cb_data) -{ +static bool inquiry_complete_cb(uint8_t dev_addr, tuh_msc_complete_data_t const * cb_data) { msc_cbw_t const* cbw = cb_data->cbw; msc_csw_t const* csw = cb_data->csw; - if (csw->status != 0) - { + if (csw->status != 0) { printf("Inquiry failed\r\n"); return false; } @@ -55,16 +53,14 @@ bool inquiry_complete_cb(uint8_t dev_addr, tuh_msc_complete_data_t const * cb_da } //------------- IMPLEMENTATION -------------// -void tuh_msc_mount_cb(uint8_t dev_addr) -{ +void tuh_msc_mount_cb(uint8_t dev_addr) { printf("A MassStorage device is mounted\r\n"); uint8_t const lun = 0; tuh_msc_inquiry(dev_addr, lun, &inquiry_resp, inquiry_complete_cb, 0); } -void tuh_msc_umount_cb(uint8_t dev_addr) -{ +void tuh_msc_umount_cb(uint8_t dev_addr) { (void) dev_addr; printf("A MassStorage device is unmounted\r\n"); } diff --git a/examples/host/cdc_msc_hid/src/tusb_config.h b/examples/host/cdc_msc_hid/src/tusb_config.h index a59a0ffb9..2f8cb5e03 100644 --- a/examples/host/cdc_msc_hid/src/tusb_config.h +++ b/examples/host/cdc_msc_hid/src/tusb_config.h @@ -69,9 +69,10 @@ // Enable Host stack #define CFG_TUH_ENABLED 1 +// #define CFG_TUH_MAX3421 1 // use max3421 as host controller + #if CFG_TUSB_MCU == OPT_MCU_RP2040 // #define CFG_TUH_RPI_PIO_USB 1 // use pio-usb as host controller - // #define CFG_TUH_MAX3421 1 // use max3421 as host controller // host roothub port is 1 if using either pio-usb or max3421 #if (defined(CFG_TUH_RPI_PIO_USB) && CFG_TUH_RPI_PIO_USB) || (defined(CFG_TUH_MAX3421) && CFG_TUH_MAX3421) @@ -102,10 +103,11 @@ #define CFG_TUH_ENUMERATION_BUFSIZE 256 #define CFG_TUH_HUB 1 // number of supported hubs -#define CFG_TUH_CDC 1 // CDC ACM +#define CFG_TUH_CDC 2 // number of supported CDC devices. also activates CDC ACM #define CFG_TUH_CDC_FTDI 1 // FTDI Serial. FTDI is not part of CDC class, only to re-use CDC driver API #define CFG_TUH_CDC_CP210X 1 // CP210x Serial. CP210X is not part of CDC class, only to re-use CDC driver API #define CFG_TUH_CDC_CH34X 1 // CH340 or CH341 Serial. CH34X is not part of CDC class, only to re-use CDC driver API +#define CFG_TUH_CDC_PL2303 1 // PL2303 Serial. PL2303 is not part of CDC class, only to re-use CDC driver API #define CFG_TUH_HID (3*CFG_TUH_DEVICE_MAX) // typical keyboard + mouse device can have 3-4 HID interfaces #define CFG_TUH_MSC 1 #define CFG_TUH_VENDOR 0 @@ -121,7 +123,7 @@ // Set Line Control state on enumeration/mounted: // DTR ( bit 0), RTS (bit 1) -#define CFG_TUH_CDC_LINE_CONTROL_ON_ENUM 0x03 +#define CFG_TUH_CDC_LINE_CONTROL_ON_ENUM (CDC_CONTROL_LINE_STATE_DTR | CDC_CONTROL_LINE_STATE_RTS) // Set Line Coding on enumeration/mounted, value for cdc_line_coding_t // bit rate = 115200, 1 stop bit, no parity, 8 bit data width diff --git a/examples/host/cdc_msc_hid_freertos/CMakeLists.txt b/examples/host/cdc_msc_hid_freertos/CMakeLists.txt index b4004f8d7..78b2784fe 100644 --- a/examples/host/cdc_msc_hid_freertos/CMakeLists.txt +++ b/examples/host/cdc_msc_hid_freertos/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.17) +cmake_minimum_required(VERSION 3.20) include(${CMAKE_CURRENT_SOURCE_DIR}/../../../hw/bsp/family_support.cmake) diff --git a/examples/host/cdc_msc_hid_freertos/CMakePresets.json b/examples/host/cdc_msc_hid_freertos/CMakePresets.json new file mode 100644 index 000000000..5cd8971e9 --- /dev/null +++ b/examples/host/cdc_msc_hid_freertos/CMakePresets.json @@ -0,0 +1,6 @@ +{ + "version": 6, + "include": [ + "../../../hw/bsp/BoardPresets.json" + ] +} diff --git a/examples/host/cdc_msc_hid_freertos/Makefile b/examples/host/cdc_msc_hid_freertos/Makefile index 67fbb9af3..178341f81 100644 --- a/examples/host/cdc_msc_hid_freertos/Makefile +++ b/examples/host/cdc_msc_hid_freertos/Makefile @@ -1,14 +1,9 @@ +RTOS = freertos include ../../build_system/make/make.mk -FREERTOS_SRC = lib/FreeRTOS-Kernel -FREERTOS_PORTABLE_PATH= $(FREERTOS_SRC)/portable/$(if $(findstring iar,$(TOOLCHAIN)),IAR,GCC) - INC += \ src \ - src/FreeRTOSConfig \ $(TOP)/hw \ - $(TOP)/$(FREERTOS_SRC)/include \ - $(TOP)/$(FREERTOS_PORTABLE_SRC) \ # Example source EXAMPLE_SOURCE = \ @@ -19,15 +14,4 @@ EXAMPLE_SOURCE = \ SRC_C += $(addprefix $(CURRENT_PATH)/, $(EXAMPLE_SOURCE)) -# FreeRTOS source, all files in port folder -SRC_C += \ - $(FREERTOS_SRC)/list.c \ - $(FREERTOS_SRC)/queue.c \ - $(FREERTOS_SRC)/tasks.c \ - $(FREERTOS_SRC)/timers.c \ - $(subst $(TOP)/,,$(wildcard $(TOP)/$(FREERTOS_PORTABLE_SRC)/*.c)) - -SRC_S += \ - $(subst $(TOP)/,,$(wildcard $(TOP)/$(FREERTOS_PORTABLE_SRC)/*.s)) - include ../../build_system/make/rules.mk diff --git a/examples/host/cdc_msc_hid_freertos/only.txt b/examples/host/cdc_msc_hid_freertos/only.txt index e3ae25260..d939d4e7b 100644 --- a/examples/host/cdc_msc_hid_freertos/only.txt +++ b/examples/host/cdc_msc_hid_freertos/only.txt @@ -13,3 +13,5 @@ mcu:MAX3421 mcu:STM32F4 mcu:STM32F7 mcu:STM32H7 +mcu:STM32H7RS +mcu:STM32N6 diff --git a/examples/host/cdc_msc_hid_freertos/src/FreeRTOSConfig/FreeRTOSConfig.h b/examples/host/cdc_msc_hid_freertos/src/FreeRTOSConfig/FreeRTOSConfig.h deleted file mode 100644 index 6a886adec..000000000 --- a/examples/host/cdc_msc_hid_freertos/src/FreeRTOSConfig/FreeRTOSConfig.h +++ /dev/null @@ -1,199 +0,0 @@ -/* - * FreeRTOS Kernel V10.0.0 - * 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. If you wish to use our Amazon - * FreeRTOS name, please do so in a fair use way that does not cause confusion. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS - * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR - * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER - * IN AN ACTION 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. - *----------------------------------------------------------*/ - -// skip if included from IAR assembler -#ifndef __IASMARM__ - -// Include MCU header -#include "bsp/board_mcu.h" - -#if TUSB_MCU_VENDOR_ESPRESSIF - #error "ESP32-Sx should use IDF's FreeRTOSConfig.h" -#endif - -#ifdef __GNUC__ -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wredundant-decls" -#endif - -// TODO fix later -// FIXME cause redundant-decls warnings -#if CFG_TUSB_MCU == OPT_MCU_MM32F327X - extern u32 SystemCoreClock; -#else - extern uint32_t SystemCoreClock; -#endif - -#ifdef __GNUC__ -#pragma GCC diagnostic pop -#endif - -#endif - -/* Cortex M23/M33 port configuration. */ -#define configENABLE_MPU 0 -#define configENABLE_FPU 1 -#define configENABLE_TRUSTZONE 0 -#define configMINIMAL_SECURE_STACK_SIZE ( 1024 ) - -#define configUSE_PREEMPTION 1 -#define configUSE_PORT_OPTIMISED_TASK_SELECTION 0 -#define configCPU_CLOCK_HZ SystemCoreClock -#define configTICK_RATE_HZ ( 1000 ) -#define configMAX_PRIORITIES ( 5 ) -#define configMINIMAL_STACK_SIZE ( 128 ) -#define configTOTAL_HEAP_SIZE ( configSUPPORT_DYNAMIC_ALLOCATION*4*1024 ) -#define configMAX_TASK_NAME_LEN 16 -#define configUSE_16_BIT_TICKS 0 -#define configIDLE_SHOULD_YIELD 1 -#define configUSE_MUTEXES 1 -#define configUSE_RECURSIVE_MUTEXES 1 -#define configUSE_COUNTING_SEMAPHORES 1 -#define configQUEUE_REGISTRY_SIZE 4 -#define configUSE_QUEUE_SETS 0 -#define configUSE_TIME_SLICING 0 -#define configUSE_NEWLIB_REENTRANT 0 -#define configENABLE_BACKWARD_COMPATIBILITY 1 -#define configSTACK_ALLOCATION_FROM_SEPARATE_HEAP 0 - -#define configSUPPORT_STATIC_ALLOCATION 1 -#define configSUPPORT_DYNAMIC_ALLOCATION 0 - -/* Hook function related definitions. */ -#define configUSE_IDLE_HOOK 0 -#define configUSE_TICK_HOOK 0 -#define configUSE_MALLOC_FAILED_HOOK 0 // cause nested extern warning -#define configCHECK_FOR_STACK_OVERFLOW 2 -#define configCHECK_HANDLER_INSTALLATION 0 - -/* Run time and task stats gathering related definitions. */ -#define configGENERATE_RUN_TIME_STATS 0 -#define configUSE_TRACE_FACILITY 1 // legacy trace -#define configUSE_STATS_FORMATTING_FUNCTIONS 0 - -/* Co-routine definitions. */ -#define configUSE_CO_ROUTINES 0 -#define configMAX_CO_ROUTINE_PRIORITIES 2 - -/* Software timer related definitions. */ -#define configUSE_TIMERS 1 -#define configTIMER_TASK_PRIORITY (configMAX_PRIORITIES-2) -#define configTIMER_QUEUE_LENGTH 32 -#define configTIMER_TASK_STACK_DEPTH configMINIMAL_STACK_SIZE - -/* Optional functions - most linkers will remove unused functions anyway. */ -#define INCLUDE_vTaskPrioritySet 0 -#define INCLUDE_uxTaskPriorityGet 0 -#define INCLUDE_vTaskDelete 0 -#define INCLUDE_vTaskSuspend 1 // required for queue, semaphore, mutex to be blocked indefinitely with portMAX_DELAY -#define INCLUDE_xResumeFromISR 0 -#define INCLUDE_vTaskDelayUntil 1 -#define INCLUDE_vTaskDelay 1 -#define INCLUDE_xTaskGetSchedulerState 0 -#define INCLUDE_xTaskGetCurrentTaskHandle 0 -#define INCLUDE_uxTaskGetStackHighWaterMark 0 -#define INCLUDE_xTaskGetIdleTaskHandle 0 -#define INCLUDE_xTimerGetTimerDaemonTaskHandle 0 -#define INCLUDE_pcTaskGetTaskName 0 -#define INCLUDE_eTaskGetState 0 -#define INCLUDE_xEventGroupSetBitFromISR 0 -#define INCLUDE_xTimerPendFunctionCall 0 - -#ifdef __RX__ -/* Renesas RX series */ -#define vSoftwareInterruptISR INT_Excep_ICU_SWINT -#define vTickISR INT_Excep_CMT0_CMI0 -#define configPERIPHERAL_CLOCK_HZ (configCPU_CLOCK_HZ/2) -#define configKERNEL_INTERRUPT_PRIORITY 1 -#define configMAX_SYSCALL_INTERRUPT_PRIORITY 4 - -#else - -/* FreeRTOS hooks to NVIC vectors */ -#define xPortPendSVHandler PendSV_Handler -#define xPortSysTickHandler SysTick_Handler -#define vPortSVCHandler SVC_Handler - -//--------------------------------------------------------------------+ -// Interrupt nesting behavior configuration. -//--------------------------------------------------------------------+ -#if defined(__NVIC_PRIO_BITS) - // For Cortex-M specific: __NVIC_PRIO_BITS is defined in core_cmx.h - #define configPRIO_BITS __NVIC_PRIO_BITS - -#elif defined(__ECLIC_INTCTLBITS) - // RISC-V Bumblebee core from nuclei - #define configPRIO_BITS __ECLIC_INTCTLBITS - -#elif defined(__IASMARM__) - // FIXME: IAR Assembler cannot include mcu header directly to get __NVIC_PRIO_BITS. - // Therefore we will hard coded it to minimum value of 2 to get pass ci build. - // IAR user must update this to correct value of the target MCU - #message "configPRIO_BITS is hard coded to 2 to pass IAR build only. User should update it per MCU" - #define configPRIO_BITS 2 - -#else - #error "FreeRTOS configPRIO_BITS to be defined" -#endif - -/* The lowest interrupt priority that can be used in a call to a "set priority" function. */ -#define configLIBRARY_LOWEST_INTERRUPT_PRIORITY ((1<cbw; msc_csw_t const *csw = cb_data->csw; diff --git a/examples/host/cdc_msc_hid_freertos/src/tusb_config.h b/examples/host/cdc_msc_hid_freertos/src/tusb_config.h index 02de4197b..3cdb227e2 100644 --- a/examples/host/cdc_msc_hid_freertos/src/tusb_config.h +++ b/examples/host/cdc_msc_hid_freertos/src/tusb_config.h @@ -44,7 +44,7 @@ #endif // Espressif IDF requires "freertos/" prefix in include path -#if TUSB_MCU_VENDOR_ESPRESSIF +#ifdef ESP_PLATFORM #define CFG_TUSB_OS_INC_PATH freertos/ #endif @@ -74,9 +74,10 @@ // Enable Host stack #define CFG_TUH_ENABLED 1 +// #define CFG_TUH_MAX3421 1 // use max3421 as host controller + #if CFG_TUSB_MCU == OPT_MCU_RP2040 // #define CFG_TUH_RPI_PIO_USB 1 // use pio-usb as host controller - // #define CFG_TUH_MAX3421 1 // use max3421 as host controller // host roothub port is 1 if using either pio-usb or max3421 #if (defined(CFG_TUH_RPI_PIO_USB) && CFG_TUH_RPI_PIO_USB) || (defined(CFG_TUH_MAX3421) && CFG_TUH_MAX3421) @@ -107,10 +108,11 @@ #define CFG_TUH_ENUMERATION_BUFSIZE 256 #define CFG_TUH_HUB 1 // number of supported hubs -#define CFG_TUH_CDC 1 // CDC ACM +#define CFG_TUH_CDC 1 // number of supported CDC devices. also activates CDC ACM #define CFG_TUH_CDC_FTDI 1 // FTDI Serial. FTDI is not part of CDC class, only to re-use CDC driver API #define CFG_TUH_CDC_CP210X 1 // CP210x Serial. CP210X is not part of CDC class, only to re-use CDC driver API #define CFG_TUH_CDC_CH34X 1 // CH340 or CH341 Serial. CH34X is not part of CDC class, only to re-use CDC driver API +#define CFG_TUH_CDC_PL2303 1 // PL2303 Serial. PL2303 is not part of CDC class, only to re-use CDC driver API #define CFG_TUH_HID (3*CFG_TUH_DEVICE_MAX) // typical keyboard + mouse device can have 3-4 HID interfaces #define CFG_TUH_MSC 1 #define CFG_TUH_VENDOR 0 @@ -126,7 +128,7 @@ // Set Line Control state on enumeration/mounted: // DTR ( bit 0), RTS (bit 1) -#define CFG_TUH_CDC_LINE_CONTROL_ON_ENUM 0x03 +#define CFG_TUH_CDC_LINE_CONTROL_ON_ENUM (CDC_CONTROL_LINE_STATE_DTR | CDC_CONTROL_LINE_STATE_RTS) // Set Line Coding on enumeration/mounted, value for cdc_line_coding_t // bit rate = 115200, 1 stop bit, no parity, 8 bit data width diff --git a/examples/host/device_info/CMakeLists.txt b/examples/host/device_info/CMakeLists.txt index 6a16155ec..33953233d 100644 --- a/examples/host/device_info/CMakeLists.txt +++ b/examples/host/device_info/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.17) +cmake_minimum_required(VERSION 3.20) include(${CMAKE_CURRENT_SOURCE_DIR}/../../../hw/bsp/family_support.cmake) diff --git a/examples/host/device_info/CMakePresets.json b/examples/host/device_info/CMakePresets.json new file mode 100644 index 000000000..5cd8971e9 --- /dev/null +++ b/examples/host/device_info/CMakePresets.json @@ -0,0 +1,6 @@ +{ + "version": 6, + "include": [ + "../../../hw/bsp/BoardPresets.json" + ] +} diff --git a/examples/host/device_info/only.txt b/examples/host/device_info/only.txt index b6f87f423..b5a4b6739 100644 --- a/examples/host/device_info/only.txt +++ b/examples/host/device_info/only.txt @@ -18,3 +18,5 @@ mcu:RAXXX mcu:STM32F4 mcu:STM32F7 mcu:STM32H7 +mcu:STM32H7RS +mcu:STM32N6 diff --git a/examples/host/device_info/src/main.c b/examples/host/device_info/src/main.c index 775968c16..7189972d6 100644 --- a/examples/host/device_info/src/main.c +++ b/examples/host/device_info/src/main.c @@ -81,7 +81,7 @@ void init_freertos_task(void); //-------------------------------------------------------------------- // Main //-------------------------------------------------------------------- -void init_tinyusb(void) { +static void init_tinyusb(void) { // init host stack on configured roothub port tusb_rhport_init_t host_init = { .role = TUSB_ROLE_HOST, @@ -124,13 +124,18 @@ void tuh_mount_cb(uint8_t daddr) { } printf("Device %u: ID %04x:%04x SN ", daddr, desc.device.idVendor, desc.device.idProduct); - xfer_result = tuh_descriptor_get_serial_string_sync(daddr, LANGUAGE_ID, desc.serial, sizeof(desc.serial)); + + xfer_result = XFER_RESULT_FAILED; + if (desc.device.iSerialNumber != 0) { + xfer_result = tuh_descriptor_get_serial_string_sync(daddr, LANGUAGE_ID, desc.serial, sizeof(desc.serial)); + } if (XFER_RESULT_SUCCESS != xfer_result) { uint16_t* serial = (uint16_t*)(uintptr_t) desc.serial; - serial[0] = 'n'; - serial[1] = '/'; - serial[2] = 'a'; - serial[3] = 0; + serial[0] = (uint16_t) ((TUSB_DESC_STRING << 8) | (2 * 3 + 2)); + serial[1] = 'n'; + serial[2] = '/'; + serial[3] = 'a'; + serial[4] = 0; } print_utf16((uint16_t*)(uintptr_t) desc.serial, sizeof(desc.serial)/2); printf("\r\n"); @@ -150,16 +155,20 @@ void tuh_mount_cb(uint8_t daddr) { // Get String descriptor using Sync API printf(" iManufacturer %u ", desc.device.iManufacturer); - xfer_result = tuh_descriptor_get_manufacturer_string_sync(daddr, LANGUAGE_ID, desc.buf, sizeof(desc.buf)); - if (XFER_RESULT_SUCCESS == xfer_result) { - print_utf16((uint16_t*)(uintptr_t) desc.buf, sizeof(desc.buf)/2); + if (desc.device.iManufacturer != 0) { + xfer_result = tuh_descriptor_get_manufacturer_string_sync(daddr, LANGUAGE_ID, desc.buf, sizeof(desc.buf)); + if (XFER_RESULT_SUCCESS == xfer_result) { + print_utf16((uint16_t*)(uintptr_t) desc.buf, sizeof(desc.buf)/2); + } } printf("\r\n"); printf(" iProduct %u ", desc.device.iProduct); - xfer_result = tuh_descriptor_get_product_string_sync(daddr, LANGUAGE_ID, desc.buf, sizeof(desc.buf)); - if (XFER_RESULT_SUCCESS == xfer_result) { - print_utf16((uint16_t*)(uintptr_t) desc.buf, sizeof(desc.buf)/2); + if (desc.device.iProduct != 0) { + xfer_result = tuh_descriptor_get_product_string_sync(daddr, LANGUAGE_ID, desc.buf, sizeof(desc.buf)); + if (XFER_RESULT_SUCCESS == xfer_result) { + print_utf16((uint16_t*)(uintptr_t) desc.buf, sizeof(desc.buf)/2); + } } printf("\r\n"); @@ -259,7 +268,7 @@ void led_blinking_task(void* param) { #define BLINKY_STACK_SIZE configMINIMAL_STACK_SIZE -#if TUSB_MCU_VENDOR_ESPRESSIF +#ifdef ESP_PLATFORM #define USB_STACK_SIZE 4096 #else // Increase stack size when debug log is enabled @@ -276,7 +285,7 @@ StackType_t usb_stack[USB_STACK_SIZE]; StaticTask_t usb_taskdef; #endif -#if TUSB_MCU_VENDOR_ESPRESSIF +#ifdef ESP_PLATFORM void app_main(void) { main(); } @@ -299,8 +308,8 @@ void init_freertos_task(void) { xTaskCreate(usb_host_task, "usbh", USB_STACK_SIZE, NULL, configMAX_PRIORITIES - 1, NULL); #endif - // skip starting scheduler (and return) for ESP32-S2 or ESP32-S3 -#if !TUSB_MCU_VENDOR_ESPRESSIF + // only start scheduler for non-espressif mcu +#ifndef ESP_PLATFORM vTaskStartScheduler(); #endif } diff --git a/examples/host/device_info/src/tusb_config.h b/examples/host/device_info/src/tusb_config.h index 5190b5b1f..e4ca2528e 100644 --- a/examples/host/device_info/src/tusb_config.h +++ b/examples/host/device_info/src/tusb_config.h @@ -40,7 +40,7 @@ #endif // Espressif IDF requires "freertos/" prefix in include path -#if TUSB_MCU_VENDOR_ESPRESSIF +#ifdef ESP_PLATFORM #define CFG_TUSB_OS_INC_PATH freertos/ #endif @@ -74,9 +74,10 @@ // Enable Host stack #define CFG_TUH_ENABLED 1 +// #define CFG_TUH_MAX3421 1 // use max3421 as host controller + #if CFG_TUSB_MCU == OPT_MCU_RP2040 // #define CFG_TUH_RPI_PIO_USB 1 // use pio-usb as host controller - // #define CFG_TUH_MAX3421 1 // use max3421 as host controller // host roothub port is 1 if using either pio-usb or max3421 #if (defined(CFG_TUH_RPI_PIO_USB) && CFG_TUH_RPI_PIO_USB) || (defined(CFG_TUH_MAX3421) && CFG_TUH_MAX3421) @@ -109,8 +110,7 @@ // only hub class is enabled #define CFG_TUH_HUB 1 -// max device support (excluding hub device) -// 1 hub typically has 4 ports +// max device support (excluding hub device): 1 hub typically has 4 ports #define CFG_TUH_DEVICE_MAX (3*CFG_TUH_HUB + 1) #ifdef __cplusplus diff --git a/examples/host/hid_controller/CMakeLists.txt b/examples/host/hid_controller/CMakeLists.txt index c1b500dd8..fb5faf210 100644 --- a/examples/host/hid_controller/CMakeLists.txt +++ b/examples/host/hid_controller/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.17) +cmake_minimum_required(VERSION 3.20) include(${CMAKE_CURRENT_SOURCE_DIR}/../../../hw/bsp/family_support.cmake) diff --git a/examples/host/hid_controller/CMakePresets.json b/examples/host/hid_controller/CMakePresets.json new file mode 100644 index 000000000..5cd8971e9 --- /dev/null +++ b/examples/host/hid_controller/CMakePresets.json @@ -0,0 +1,6 @@ +{ + "version": 6, + "include": [ + "../../../hw/bsp/BoardPresets.json" + ] +} diff --git a/examples/host/hid_controller/only.txt b/examples/host/hid_controller/only.txt index 95f9f1d82..dcdaf41c7 100644 --- a/examples/host/hid_controller/only.txt +++ b/examples/host/hid_controller/only.txt @@ -15,3 +15,5 @@ mcu:MAX3421 mcu:STM32F4 mcu:STM32F7 mcu:STM32H7 +mcu:STM32H7RS +mcu:STM32N6 diff --git a/examples/host/hid_controller/src/hid_app.c b/examples/host/hid_controller/src/hid_app.c index 6ffe0b6d4..1d6ca8b07 100644 --- a/examples/host/hid_controller/src/hid_app.c +++ b/examples/host/hid_controller/src/hid_app.c @@ -231,14 +231,12 @@ void tuh_hid_umount_cb(uint8_t dev_addr, uint8_t instance) } // check if different than 2 -bool diff_than_2(uint8_t x, uint8_t y) -{ +static inline bool diff_than_2(uint8_t x, uint8_t y) { return (x - y > 2) || (y - x > 2); } // check if 2 reports are different enough -bool diff_report(sony_ds4_report_t const* rpt1, sony_ds4_report_t const* rpt2) -{ +static bool diff_report(sony_ds4_report_t const* rpt1, sony_ds4_report_t const* rpt2) { bool result; // x, y, z, rz must different than 2 to be counted @@ -251,7 +249,7 @@ bool diff_report(sony_ds4_report_t const* rpt1, sony_ds4_report_t const* rpt2) return result; } -void process_sony_ds4(uint8_t const* report, uint16_t len) +static void process_sony_ds4(uint8_t const* report, uint16_t len) { (void)len; const char* dpad_str[] = { "N", "NE", "E", "SE", "S", "SW", "W", "NW", "none" }; @@ -310,16 +308,13 @@ void process_sony_ds4(uint8_t const* report, uint16_t len) } // Invoked when received report from device via interrupt endpoint -void tuh_hid_report_received_cb(uint8_t dev_addr, uint8_t instance, uint8_t const* report, uint16_t len) -{ - if ( is_sony_ds4(dev_addr) ) - { +void tuh_hid_report_received_cb(uint8_t dev_addr, uint8_t instance, uint8_t const *report, uint16_t len) { + if (is_sony_ds4(dev_addr)) { process_sony_ds4(report, len); } // continue to request to receive report - if ( !tuh_hid_receive_report(dev_addr, instance) ) - { + if (!tuh_hid_receive_report(dev_addr, instance)) { printf("Error: cannot request to receive report\r\n"); } } diff --git a/examples/host/hid_controller/src/tusb_config.h b/examples/host/hid_controller/src/tusb_config.h index 3ac591d8f..351fe0178 100644 --- a/examples/host/hid_controller/src/tusb_config.h +++ b/examples/host/hid_controller/src/tusb_config.h @@ -69,9 +69,10 @@ // Enable Host stack #define CFG_TUH_ENABLED 1 +// #define CFG_TUH_MAX3421 1 // use max3421 as host controller + #if CFG_TUSB_MCU == OPT_MCU_RP2040 // #define CFG_TUH_RPI_PIO_USB 1 // use pio-usb as host controller - // #define CFG_TUH_MAX3421 1 // use max3421 as host controller // host roothub port is 1 if using either pio-usb or max3421 #if (defined(CFG_TUH_RPI_PIO_USB) && CFG_TUH_RPI_PIO_USB) || (defined(CFG_TUH_MAX3421) && CFG_TUH_MAX3421) diff --git a/examples/host/midi_rx/CMakeLists.txt b/examples/host/midi_rx/CMakeLists.txt new file mode 100644 index 000000000..33953233d --- /dev/null +++ b/examples/host/midi_rx/CMakeLists.txt @@ -0,0 +1,32 @@ +cmake_minimum_required(VERSION 3.20) + +include(${CMAKE_CURRENT_SOURCE_DIR}/../../../hw/bsp/family_support.cmake) + +# gets PROJECT name for the example +family_get_project_name(PROJECT ${CMAKE_CURRENT_LIST_DIR}) + +project(${PROJECT} C CXX ASM) + +# Checks this example is valid for the family and initializes the project +family_initialize_project(${PROJECT} ${CMAKE_CURRENT_LIST_DIR}) + +# Espressif has its own cmake build system +if(FAMILY STREQUAL "espressif") + return() +endif() + +add_executable(${PROJECT}) + +# Example source +target_sources(${PROJECT} PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR}/src/main.c + ) + +# Example include +target_include_directories(${PROJECT} PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR}/src + ) + +# Configure compilation flags and libraries for the example without RTOS. +# See the corresponding function in hw/bsp/FAMILY/family.cmake for details. +family_configure_host_example(${PROJECT} noos) diff --git a/examples/host/midi_rx/Makefile b/examples/host/midi_rx/Makefile new file mode 100644 index 000000000..0235e08c3 --- /dev/null +++ b/examples/host/midi_rx/Makefile @@ -0,0 +1,13 @@ +include ../../build_system/make/make.mk + +INC += \ + src \ + $(TOP)/hw \ + +# Example source +EXAMPLE_SOURCE += \ + src/main.c + +SRC_C += $(addprefix $(CURRENT_PATH)/, $(EXAMPLE_SOURCE)) + +include ../../build_system/make/rules.mk diff --git a/examples/host/midi_rx/only.txt b/examples/host/midi_rx/only.txt new file mode 100644 index 000000000..b5a4b6739 --- /dev/null +++ b/examples/host/midi_rx/only.txt @@ -0,0 +1,22 @@ +mcu:ESP32S2 +mcu:ESP32S3 +mcu:ESP32P4 +mcu:KINETIS_KL +mcu:LPC175X_6X +mcu:LPC177X_8X +mcu:LPC18XX +mcu:LPC40XX +mcu:LPC43XX +mcu:MAX3421 +mcu:MIMXRT1XXX +mcu:MIMXRT10XX +mcu:MIMXRT11XX +mcu:MSP432E4 +mcu:RP2040 +mcu:RX65X +mcu:RAXXX +mcu:STM32F4 +mcu:STM32F7 +mcu:STM32H7 +mcu:STM32H7RS +mcu:STM32N6 diff --git a/examples/host/midi_rx/src/main.c b/examples/host/midi_rx/src/main.c new file mode 100644 index 000000000..78b1a11b9 --- /dev/null +++ b/examples/host/midi_rx/src/main.c @@ -0,0 +1,123 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +#include +#include +#include + +#include "bsp/board_api.h" +#include "tusb.h" + +//--------------------------------------------------------------------+ +// STATIC GLOBALS DECLARATION +//--------------------------------------------------------------------+ + +//--------------------------------------------------------------------+ +// MACRO CONSTANT TYPEDEF PROTOTYPES +//--------------------------------------------------------------------+ +void led_blinking_task(void); +void midi_host_rx_task(void); + +/*------------- MAIN -------------*/ +int main(void) { + board_init(); + + printf("TinyUSB Host MIDI Example\r\n"); + + // init host stack on configured roothub port + tusb_rhport_init_t host_init = { + .role = TUSB_ROLE_HOST, + .speed = TUSB_SPEED_AUTO + }; + tusb_init(BOARD_TUH_RHPORT, &host_init); + + while (1) { + tuh_task(); + led_blinking_task(); + midi_host_rx_task(); + } + + return 0; +} + +//--------------------------------------------------------------------+ +// Blinking Task +//--------------------------------------------------------------------+ +void led_blinking_task(void) { + const uint32_t interval_ms = 1000; + static uint32_t start_ms = 0; + + static bool led_state = false; + + // Blink every interval ms + if (board_millis() - start_ms < interval_ms) return;// not enough time + start_ms += interval_ms; + + board_led_write(led_state); + led_state = 1 - led_state;// toggle +} + +//--------------------------------------------------------------------+ +// MIDI host receive task +//--------------------------------------------------------------------+ +void midi_host_rx_task(void) { + // nothing to do, we just print out received data in callback +} + +//--------------------------------------------------------------------+ +// TinyUSB Callbacks +//--------------------------------------------------------------------+ + +// Invoked when device with MIDI interface is mounted. +void tuh_midi_mount_cb(uint8_t idx, const tuh_midi_mount_cb_t* mount_cb_data) { + printf("MIDI Interface Index = %u, Address = %u, Number of RX cables = %u, Number of TX cables = %u\r\n", + idx, mount_cb_data->daddr, mount_cb_data->rx_cable_count, mount_cb_data->tx_cable_count); +} + +// Invoked when device with hid interface is un-mounted +void tuh_midi_umount_cb(uint8_t idx) { + printf("MIDI Interface Index = %u is unmounted\r\n", idx); +} + +void tuh_midi_rx_cb(uint8_t idx, uint32_t xferred_bytes) { + if (xferred_bytes == 0) { + return; + } + + uint8_t buffer[48]; + uint8_t cable_num = 0; + uint32_t bytes_read = tuh_midi_stream_read(idx, &cable_num, buffer, sizeof(buffer)); + + printf("Cable %u rx: ", cable_num); + for (uint32_t i = 0; i < bytes_read; i++) { + printf("%02X ", buffer[i]); + } + printf("\r\n"); +} + +void tuh_midi_tx_cb(uint8_t idx, uint32_t xferred_bytes) { + (void) idx; + (void) xferred_bytes; +} diff --git a/examples/host/midi_rx/src/tusb_config.h b/examples/host/midi_rx/src/tusb_config.h new file mode 100644 index 000000000..76bdf87f3 --- /dev/null +++ b/examples/host/midi_rx/src/tusb_config.h @@ -0,0 +1,118 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +#ifndef TUSB_CONFIG_H_ +#define TUSB_CONFIG_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +//-------------------------------------------------------------------- +// Common Configuration +//-------------------------------------------------------------------- + +// defined by compiler flags for flexibility +#ifndef CFG_TUSB_MCU +#error CFG_TUSB_MCU must be defined +#endif + +// Espressif IDF requires "freertos/" prefix in include path +#ifdef ESP_PLATFORM +#define CFG_TUSB_OS_INC_PATH freertos/ +#endif + +#ifndef CFG_TUSB_OS +#define CFG_TUSB_OS OPT_OS_NONE +#endif + +#ifndef CFG_TUSB_DEBUG +#define CFG_TUSB_DEBUG 0 +#endif + +/* USB DMA on some MCUs can only access a specific SRAM region with restriction on alignment. + * Tinyusb use follows macros to declare transferring memory so that they can be put + * into those specific section. + * e.g + * - CFG_TUSB_MEM SECTION : __attribute__ (( section(".usb_ram") )) + * - CFG_TUSB_MEM_ALIGN : __attribute__ ((aligned(4))) + */ +#ifndef CFG_TUH_MEM_SECTION +#define CFG_TUH_MEM_SECTION +#endif + +#ifndef CFG_TUH_MEM_ALIGN +#define CFG_TUH_MEM_ALIGN __attribute__ ((aligned(4))) +#endif + +//-------------------------------------------------------------------- +// Host Configuration +//-------------------------------------------------------------------- + +// Enable Host stack +#define CFG_TUH_ENABLED 1 + +#if CFG_TUSB_MCU == OPT_MCU_RP2040 + // #define CFG_TUH_RPI_PIO_USB 1 // use pio-usb as host controller + // #define CFG_TUH_MAX3421 1 // use max3421 as host controller + + // host roothub port is 1 if using either pio-usb or max3421 + #if (defined(CFG_TUH_RPI_PIO_USB) && CFG_TUH_RPI_PIO_USB) || (defined(CFG_TUH_MAX3421) && CFG_TUH_MAX3421) + #define BOARD_TUH_RHPORT 1 + #endif +#endif + +// Default is max speed that hardware controller could support with on-chip PHY +#define CFG_TUH_MAX_SPEED BOARD_TUH_MAX_SPEED + +//------------------------- Board Specific -------------------------- + +// RHPort number used for host can be defined by board.mk, default to port 0 +#ifndef BOARD_TUH_RHPORT +#define BOARD_TUH_RHPORT 0 +#endif + +// RHPort max operational speed can defined by board.mk +#ifndef BOARD_TUH_MAX_SPEED +#define BOARD_TUH_MAX_SPEED OPT_MODE_DEFAULT_SPEED +#endif + +//-------------------------------------------------------------------- +// Driver Configuration +//-------------------------------------------------------------------- + +// Size of buffer to hold descriptors and other data used for enumeration +#define CFG_TUH_ENUMERATION_BUFSIZE 256 + +#define CFG_TUH_HUB 1 +// max device support (excluding hub device): 1 hub typically has 4 ports +#define CFG_TUH_DEVICE_MAX (3*CFG_TUH_HUB + 1) +#define CFG_TUH_MIDI CFG_TUH_DEVICE_MAX + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/examples/host/msc_file_explorer/CMakeLists.txt b/examples/host/msc_file_explorer/CMakeLists.txt index 1a57c7466..5ac75c04a 100644 --- a/examples/host/msc_file_explorer/CMakeLists.txt +++ b/examples/host/msc_file_explorer/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.17) +cmake_minimum_required(VERSION 3.20) include(${CMAKE_CURRENT_SOURCE_DIR}/../../../hw/bsp/family_support.cmake) diff --git a/examples/host/msc_file_explorer/CMakePresets.json b/examples/host/msc_file_explorer/CMakePresets.json new file mode 100644 index 000000000..5cd8971e9 --- /dev/null +++ b/examples/host/msc_file_explorer/CMakePresets.json @@ -0,0 +1,6 @@ +{ + "version": 6, + "include": [ + "../../../hw/bsp/BoardPresets.json" + ] +} diff --git a/examples/host/msc_file_explorer/Makefile b/examples/host/msc_file_explorer/Makefile index c7d6a7cae..f0872376f 100644 --- a/examples/host/msc_file_explorer/Makefile +++ b/examples/host/msc_file_explorer/Makefile @@ -22,6 +22,6 @@ SRC_C += \ $(FATFS_PATH)/ffunicode.c \ # suppress warning caused by fatfs -CFLAGS += -Wno-error=cast-qual +CFLAGS_GCC += -Wno-error=cast-qual include ../../build_system/make/rules.mk diff --git a/examples/host/msc_file_explorer/only.txt b/examples/host/msc_file_explorer/only.txt index 95f9f1d82..dcdaf41c7 100644 --- a/examples/host/msc_file_explorer/only.txt +++ b/examples/host/msc_file_explorer/only.txt @@ -15,3 +15,5 @@ mcu:MAX3421 mcu:STM32F4 mcu:STM32F7 mcu:STM32H7 +mcu:STM32H7RS +mcu:STM32N6 diff --git a/examples/host/msc_file_explorer/src/main.c b/examples/host/msc_file_explorer/src/main.c index 9509035b4..8197c3c8d 100644 --- a/examples/host/msc_file_explorer/src/main.c +++ b/examples/host/msc_file_explorer/src/main.c @@ -62,15 +62,13 @@ #include "bsp/board_api.h" #include "tusb.h" +#include "msc_app.h" + //--------------------------------------------------------------------+ // MACRO CONSTANT TYPEDEF PROTYPES //--------------------------------------------------------------------+ void led_blinking_task(void); -// from msc_app.c -extern bool msc_app_init(void); -extern void msc_app_task(void); - /*------------- MAIN -------------*/ int main(void) { board_init(); diff --git a/examples/host/msc_file_explorer/src/msc_app.c b/examples/host/msc_file_explorer/src/msc_app.c index 035d74689..40a9ef57e 100644 --- a/examples/host/msc_file_explorer/src/msc_app.c +++ b/examples/host/msc_file_explorer/src/msc_app.c @@ -34,6 +34,8 @@ #define EMBEDDED_CLI_IMPL #include "embedded_cli.h" +#include "msc_app.h" + //--------------------------------------------------------------------+ // MACRO TYPEDEF CONSTANT ENUM DECLARATION @@ -67,7 +69,9 @@ bool cli_init(void); bool msc_app_init(void) { - for(size_t i=0; i 0 ) @@ -99,8 +105,7 @@ void msc_app_task(void) // //--------------------------------------------------------------------+ -bool inquiry_complete_cb(uint8_t dev_addr, tuh_msc_complete_data_t const * cb_data) -{ +static bool inquiry_complete_cb(uint8_t dev_addr, tuh_msc_complete_data_t const * cb_data) { msc_cbw_t const* cbw = cb_data->cbw; msc_csw_t const* csw = cb_data->csw; @@ -294,18 +299,11 @@ void cli_cmd_mkdir(EmbeddedCli *cli, char *args, void *context); void cli_cmd_mv(EmbeddedCli *cli, char *args, void *context); void cli_cmd_rm(EmbeddedCli *cli, char *args, void *context); -void cli_write_char(EmbeddedCli *cli, char c) -{ +static void cli_write_char(EmbeddedCli *cli, char c) { (void) cli; putchar((int) c); } -void cli_cmd_unknown(EmbeddedCli *cli, CliCommand *command) -{ - (void) cli; - printf("%s: command not found\r\n", command->name); -} - bool cli_init(void) { EmbeddedCliConfig *config = embeddedCliDefaultConfig(); diff --git a/examples/host/msc_file_explorer/src/msc_app.h b/examples/host/msc_file_explorer/src/msc_app.h new file mode 100644 index 000000000..3ba03d0dc --- /dev/null +++ b/examples/host/msc_file_explorer/src/msc_app.h @@ -0,0 +1,35 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2025 Ha Thach (tinyusb.org) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * This file is part of the TinyUSB stack. + */ +#ifndef MSC_APP_H +#define MSC_APP_H + +#include + +bool msc_app_init(void); +void msc_app_task(void); + + +#endif diff --git a/examples/host/msc_file_explorer/src/tusb_config.h b/examples/host/msc_file_explorer/src/tusb_config.h index c798b4383..c1829c300 100644 --- a/examples/host/msc_file_explorer/src/tusb_config.h +++ b/examples/host/msc_file_explorer/src/tusb_config.h @@ -69,9 +69,10 @@ // Enable Host stack #define CFG_TUH_ENABLED 1 +// #define CFG_TUH_MAX3421 1 // use max3421 as host controller + #if CFG_TUSB_MCU == OPT_MCU_RP2040 // #define CFG_TUH_RPI_PIO_USB 1 // use pio-usb as host controller - // #define CFG_TUH_MAX3421 1 // use max3421 as host controller // host roothub port is 1 if using either pio-usb or max3421 #if (defined(CFG_TUH_RPI_PIO_USB) && CFG_TUH_RPI_PIO_USB) || (defined(CFG_TUH_MAX3421) && CFG_TUH_MAX3421) diff --git a/examples/typec/CMakeLists.txt b/examples/typec/CMakeLists.txt index c7641494e..24c25908a 100644 --- a/examples/typec/CMakeLists.txt +++ b/examples/typec/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.17) +cmake_minimum_required(VERSION 3.20) include(${CMAKE_CURRENT_SOURCE_DIR}/../../hw/bsp/family_support.cmake) diff --git a/examples/typec/CMakePresets.json b/examples/typec/CMakePresets.json new file mode 100644 index 000000000..c22e8c0ec --- /dev/null +++ b/examples/typec/CMakePresets.json @@ -0,0 +1,6 @@ +{ + "version": 6, + "include": [ + "../../hw/bsp/BoardPresets.json" + ] +} diff --git a/examples/typec/power_delivery/CMakeLists.txt b/examples/typec/power_delivery/CMakeLists.txt index 012eff095..837b4996a 100644 --- a/examples/typec/power_delivery/CMakeLists.txt +++ b/examples/typec/power_delivery/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.17) +cmake_minimum_required(VERSION 3.20) include(${CMAKE_CURRENT_SOURCE_DIR}/../../../hw/bsp/family_support.cmake) diff --git a/examples/typec/power_delivery/CMakePresets.json b/examples/typec/power_delivery/CMakePresets.json new file mode 100644 index 000000000..5cd8971e9 --- /dev/null +++ b/examples/typec/power_delivery/CMakePresets.json @@ -0,0 +1,6 @@ +{ + "version": 6, + "include": [ + "../../../hw/bsp/BoardPresets.json" + ] +} diff --git a/examples/typec/power_delivery/src/main.c b/examples/typec/power_delivery/src/main.c index 068dbbeb1..de0db4721 100644 --- a/examples/typec/power_delivery/src/main.c +++ b/examples/typec/power_delivery/src/main.c @@ -71,9 +71,8 @@ int main(void) } } -#if TUSB_MCU_VENDOR_ESPRESSIF -void app_main(void) -{ +#ifdef ESP_PLATFORM +void app_main(void) { main(); } #endif diff --git a/examples/west.yml b/examples/west.yml new file mode 100644 index 000000000..0683f6861 --- /dev/null +++ b/examples/west.yml @@ -0,0 +1,12 @@ +manifest: + remotes: + - name: zephyrproject-rtos + url-base: https://github.com/zephyrproject-rtos + projects: + - name: zephyr + remote: zephyrproject-rtos + revision: main + path: zephyr + import: true + self: + path: . diff --git a/hw/bsp/BoardPresets.json b/hw/bsp/BoardPresets.json new file mode 100644 index 000000000..24da362da --- /dev/null +++ b/hw/bsp/BoardPresets.json @@ -0,0 +1,4012 @@ +{ + "version": 6, + "configurePresets": [ + { + "name": "default", + "hidden": true, + "description": "Configure preset for the ${presetName} board", + "generator": "Ninja Multi-Config", + "binaryDir": "${sourceDir}/build/${presetName}", + "cacheVariables": { + "CMAKE_DEFAULT_BUILD_TYPE": "RelWithDebInfo", + "BOARD": "${presetName}" + } + }, + { + "name": "default single", + "hidden": true, + "description": "Configure preset for the ${presetName} board", + "generator": "Ninja", + "binaryDir": "${sourceDir}/build/${presetName}", + "cacheVariables": { + "BOARD": "${presetName}" + } + }, + { + "name": "adafruit_clue", + "inherits": "default" + }, + { + "name": "adafruit_feather_esp32_v2", + "inherits": "default single" + }, + { + "name": "adafruit_feather_esp32s2", + "inherits": "default single" + }, + { + "name": "adafruit_feather_esp32s3", + "inherits": "default single" + }, + { + "name": "adafruit_magtag_29gray", + "inherits": "default" + }, + { + "name": "adafruit_metro_esp32s2", + "inherits": "default single" + }, + { + "name": "apard32690", + "inherits": "default" + }, + { + "name": "arduino_nano33_ble", + "inherits": "default" + }, + { + "name": "atsamd21_xpro", + "inherits": "default" + }, + { + "name": "atsaml21_xpro", + "inherits": "default" + }, + { + "name": "b_g474e_dpow1", + "inherits": "default" + }, + { + "name": "b_u585i_iot2a", + "inherits": "default" + }, + { + "name": "ch32v103r_r1_1v0", + "inherits": "default" + }, + { + "name": "ch32v203c_r0_1v0", + "inherits": "default" + }, + { + "name": "ch32v203g_r0_1v0", + "inherits": "default" + }, + { + "name": "ch32v307v_r1_1v0", + "inherits": "default" + }, + { + "name": "circuitplayground_bluefruit", + "inherits": "default" + }, + { + "name": "circuitplayground_express", + "inherits": "default" + }, + { + "name": "curiosity_nano", + "inherits": "default" + }, + { + "name": "cynthion_d11", + "inherits": "default" + }, + { + "name": "cynthion_d21", + "inherits": "default" + }, + { + "name": "d5035_01", + "inherits": "default" + }, + { + "name": "da14695_dk_usb", + "inherits": "default" + }, + { + "name": "da1469x_dk_pro", + "inherits": "default" + }, + { + "name": "daisyseed", + "inherits": "default" + }, + { + "name": "double_m33_express", + "inherits": "default" + }, + { + "name": "ea4088_quickstart", + "inherits": "default" + }, + { + "name": "ea4357", + "inherits": "default" + }, + { + "name": "ek_tm4c123gxl", + "inherits": "default" + }, + { + "name": "espressif_addax_1", + "inherits": "default single" + }, + { + "name": "espressif_c3_devkitc", + "inherits": "default single" + }, + { + "name": "espressif_c6_devkitc", + "inherits": "default single" + }, + { + "name": "espressif_kaluga_1", + "inherits": "default single" + }, + { + "name": "espressif_p4_function_ev", + "inherits": "default single" + }, + { + "name": "espressif_s2_devkitc", + "inherits": "default single" + }, + { + "name": "espressif_s3_devkitc", + "inherits": "default single" + }, + { + "name": "espressif_s3_devkitm", + "inherits": "default single" + }, + { + "name": "espressif_saola_1", + "inherits": "default single" + }, + { + "name": "f1c100s", + "inherits": "default" + }, + { + "name": "feather_m0_express", + "inherits": "default" + }, + { + "name": "feather_m4_express", + "inherits": "default" + }, + { + "name": "feather_nrf52840_express", + "inherits": "default" + }, + { + "name": "feather_nrf52840_sense", + "inherits": "default" + }, + { + "name": "feather_rp2040_max3421", + "inherits": "default" + }, + { + "name": "feather_stm32f405", + "inherits": "default" + }, + { + "name": "fomu", + "inherits": "default" + }, + { + "name": "frdm_k32l2a4s", + "inherits": "default" + }, + { + "name": "frdm_k32l2b", + "inherits": "default" + }, + { + "name": "frdm_k64f", + "inherits": "default" + }, + { + "name": "frdm_kl25z", + "inherits": "default" + }, + { + "name": "frdm_mcxa153", + "inherits": "default" + }, + { + "name": "frdm_mcxn947", + "inherits": "default" + }, + { + "name": "itsybitsy_m0", + "inherits": "default" + }, + { + "name": "itsybitsy_m4", + "inherits": "default" + }, + { + "name": "itsybitsy_nrf52840", + "inherits": "default" + }, + { + "name": "kuiic", + "inherits": "default" + }, + { + "name": "lpcxpresso11u37", + "inherits": "default" + }, + { + "name": "lpcxpresso11u68", + "inherits": "default" + }, + { + "name": "lpcxpresso1347", + "inherits": "default" + }, + { + "name": "lpcxpresso1549", + "inherits": "default" + }, + { + "name": "lpcxpresso1769", + "inherits": "default" + }, + { + "name": "lpcxpresso18s37", + "inherits": "default" + }, + { + "name": "lpcxpresso43s67", + "inherits": "default" + }, + { + "name": "lpcxpresso51u68", + "inherits": "default" + }, + { + "name": "lpcxpresso54114", + "inherits": "default" + }, + { + "name": "lpcxpresso54608", + "inherits": "default" + }, + { + "name": "lpcxpresso54628", + "inherits": "default" + }, + { + "name": "lpcxpresso55s28", + "inherits": "default" + }, + { + "name": "lpcxpresso55s69", + "inherits": "default" + }, + { + "name": "max32650evkit", + "inherits": "default" + }, + { + "name": "max32650fthr", + "inherits": "default" + }, + { + "name": "max32651evkit", + "inherits": "default" + }, + { + "name": "max32666evkit", + "inherits": "default" + }, + { + "name": "max32666fthr", + "inherits": "default" + }, + { + "name": "max32690evkit", + "inherits": "default" + }, + { + "name": "max78002evkit", + "inherits": "default" + }, + { + "name": "mbed1768", + "inherits": "default" + }, + { + "name": "mcb1800", + "inherits": "default" + }, + { + "name": "mcu_link", + "inherits": "default" + }, + { + "name": "mcxn947brk", + "inherits": "default" + }, + { + "name": "metro_m0_express", + "inherits": "default" + }, + { + "name": "metro_m4_express", + "inherits": "default" + }, + { + "name": "metro_m7_1011", + "inherits": "default" + }, + { + "name": "metro_m7_1011_sd", + "inherits": "default" + }, + { + "name": "mimxrt1010_evk", + "inherits": "default" + }, + { + "name": "mimxrt1015_evk", + "inherits": "default" + }, + { + "name": "mimxrt1020_evk", + "inherits": "default" + }, + { + "name": "mimxrt1024_evk", + "inherits": "default" + }, + { + "name": "mimxrt1050_evkb", + "inherits": "default" + }, + { + "name": "mimxrt1060_evk", + "inherits": "default" + }, + { + "name": "mimxrt1064_evk", + "inherits": "default" + }, + { + "name": "mimxrt1170_evkb", + "inherits": "default" + }, + { + "name": "mm32f327x_mb39", + "inherits": "default" + }, + { + "name": "mm32f327x_pitaya_lite", + "inherits": "default" + }, + { + "name": "msp_exp430f5529lp", + "inherits": "default" + }, + { + "name": "msp_exp432e401y", + "inherits": "default" + }, + { + "name": "nanoch32v203", + "inherits": "default" + }, + { + "name": "pca10056", + "inherits": "default" + }, + { + "name": "pca10059", + "inherits": "default" + }, + { + "name": "pca10095", + "inherits": "default" + }, + { + "name": "pca10100", + "inherits": "default" + }, + { + "name": "pico_sdk", + "inherits": "default" + }, + { + "name": "portenta_c33", + "inherits": "default" + }, + { + "name": "pybadge", + "inherits": "default" + }, + { + "name": "pyboardv11", + "inherits": "default" + }, + { + "name": "pyportal", + "inherits": "default" + }, + { + "name": "qtpy", + "inherits": "default" + }, + { + "name": "ra2a1_ek", + "inherits": "default" + }, + { + "name": "ra4m1_ek", + "inherits": "default" + }, + { + "name": "ra4m3_ek", + "inherits": "default" + }, + { + "name": "ra6m1_ek", + "inherits": "default" + }, + { + "name": "ra6m5_ek", + "inherits": "default" + }, + { + "name": "ra8m1_ek", + "inherits": "default" + }, + { + "name": "raspberry_pi_pico", + "inherits": "default" + }, + { + "name": "raspberry_pi_pico2", + "inherits": "default" + }, + { + "name": "raspberrypi_cm4", + "inherits": "default" + }, + { + "name": "raspberrypi_zero", + "inherits": "default" + }, + { + "name": "raspberrypi_zero2", + "inherits": "default" + }, + { + "name": "samd11_xplained", + "inherits": "default" + }, + { + "name": "same54_xplained", + "inherits": "default" + }, + { + "name": "samg55_xplained", + "inherits": "default" + }, + { + "name": "saml22_feather", + "inherits": "default" + }, + { + "name": "seeeduino_xiao", + "inherits": "default" + }, + { + "name": "sensorwatch_m0", + "inherits": "default" + }, + { + "name": "sipeed_longan_nano", + "inherits": "default" + }, + { + "name": "sparkfun_samd21_mini_usb", + "inherits": "default" + }, + { + "name": "stlinkv3mini", + "inherits": "default" + }, + { + "name": "stm32c071nucleo", + "inherits": "default" + }, + { + "name": "stm32f070rbnucleo", + "inherits": "default" + }, + { + "name": "stm32f072disco", + "inherits": "default" + }, + { + "name": "stm32f072eval", + "inherits": "default" + }, + { + "name": "stm32f103_bluepill", + "inherits": "default" + }, + { + "name": "stm32f103_mini_2", + "inherits": "default" + }, + { + "name": "stm32f103ze_iar", + "inherits": "default" + }, + { + "name": "stm32f207nucleo", + "inherits": "default" + }, + { + "name": "stm32f303disco", + "inherits": "default" + }, + { + "name": "stm32f401blackpill", + "inherits": "default" + }, + { + "name": "stm32f407blackvet", + "inherits": "default" + }, + { + "name": "stm32f407disco", + "inherits": "default" + }, + { + "name": "stm32f411blackpill", + "inherits": "default" + }, + { + "name": "stm32f411disco", + "inherits": "default" + }, + { + "name": "stm32f412disco", + "inherits": "default" + }, + { + "name": "stm32f412nucleo", + "inherits": "default" + }, + { + "name": "stm32f439nucleo", + "inherits": "default" + }, + { + "name": "stm32f723disco", + "inherits": "default" + }, + { + "name": "stm32f746disco", + "inherits": "default" + }, + { + "name": "stm32f746nucleo", + "inherits": "default" + }, + { + "name": "stm32f767nucleo", + "inherits": "default" + }, + { + "name": "stm32f769disco", + "inherits": "default" + }, + { + "name": "stm32g0b1nucleo", + "inherits": "default" + }, + { + "name": "stm32g474nucleo", + "inherits": "default" + }, + { + "name": "stm32g491nucleo", + "inherits": "default" + }, + { + "name": "stm32h503nucleo", + "inherits": "default" + }, + { + "name": "stm32h563nucleo", + "inherits": "default" + }, + { + "name": "stm32h573i_dk", + "inherits": "default" + }, + { + "name": "stm32h723nucleo", + "inherits": "default" + }, + { + "name": "stm32h743eval", + "inherits": "default" + }, + { + "name": "stm32h743nucleo", + "inherits": "default" + }, + { + "name": "stm32h745disco", + "inherits": "default" + }, + { + "name": "stm32h750_weact", + "inherits": "default" + }, + { + "name": "stm32h750bdk", + "inherits": "default" + }, + { + "name": "stm32h7s3nucleo", + "inherits": "default" + }, + { + "name": "stm32l052dap52", + "inherits": "default" + }, + { + "name": "stm32l0538disco", + "inherits": "default" + }, + { + "name": "stm32l412nucleo", + "inherits": "default" + }, + { + "name": "stm32l476disco", + "inherits": "default" + }, + { + "name": "stm32l4p5nucleo", + "inherits": "default" + }, + { + "name": "stm32l4r5nucleo", + "inherits": "default" + }, + { + "name": "stm32u545nucleo", + "inherits": "default" + }, + { + "name": "stm32u575eval", + "inherits": "default" + }, + { + "name": "stm32u575nucleo", + "inherits": "default" + }, + { + "name": "stm32u5a5nucleo", + "inherits": "default" + }, + { + "name": "stm32wb55nucleo", + "inherits": "default" + }, + { + "name": "teensy_35", + "inherits": "default" + }, + { + "name": "teensy_40", + "inherits": "default" + }, + { + "name": "teensy_41", + "inherits": "default" + }, + { + "name": "trinket_m0", + "inherits": "default" + }, + { + "name": "uno_r4", + "inherits": "default" + }, + { + "name": "waveshare_openh743i", + "inherits": "default" + }, + { + "name": "xmc4500_relax", + "inherits": "default" + }, + { + "name": "xmc4700_relax", + "inherits": "default" + } + ], + "buildPresets": [ + { + "name": "adafruit_clue", + "description": "Build preset for the adafruit_clue board", + "configurePreset": "adafruit_clue" + }, + { + "name": "adafruit_feather_esp32_v2", + "description": "Build preset for the adafruit_feather_esp32_v2 board", + "configurePreset": "adafruit_feather_esp32_v2" + }, + { + "name": "adafruit_feather_esp32s2", + "description": "Build preset for the adafruit_feather_esp32s2 board", + "configurePreset": "adafruit_feather_esp32s2" + }, + { + "name": "adafruit_feather_esp32s3", + "description": "Build preset for the adafruit_feather_esp32s3 board", + "configurePreset": "adafruit_feather_esp32s3" + }, + { + "name": "adafruit_magtag_29gray", + "description": "Build preset for the adafruit_magtag_29gray board", + "configurePreset": "adafruit_magtag_29gray" + }, + { + "name": "adafruit_metro_esp32s2", + "description": "Build preset for the adafruit_metro_esp32s2 board", + "configurePreset": "adafruit_metro_esp32s2" + }, + { + "name": "apard32690", + "description": "Build preset for the apard32690 board", + "configurePreset": "apard32690" + }, + { + "name": "arduino_nano33_ble", + "description": "Build preset for the arduino_nano33_ble board", + "configurePreset": "arduino_nano33_ble" + }, + { + "name": "atsamd21_xpro", + "description": "Build preset for the atsamd21_xpro board", + "configurePreset": "atsamd21_xpro" + }, + { + "name": "atsaml21_xpro", + "description": "Build preset for the atsaml21_xpro board", + "configurePreset": "atsaml21_xpro" + }, + { + "name": "b_g474e_dpow1", + "description": "Build preset for the b_g474e_dpow1 board", + "configurePreset": "b_g474e_dpow1" + }, + { + "name": "b_u585i_iot2a", + "description": "Build preset for the b_u585i_iot2a board", + "configurePreset": "b_u585i_iot2a" + }, + { + "name": "ch32v103r_r1_1v0", + "description": "Build preset for the ch32v103r_r1_1v0 board", + "configurePreset": "ch32v103r_r1_1v0" + }, + { + "name": "ch32v203c_r0_1v0", + "description": "Build preset for the ch32v203c_r0_1v0 board", + "configurePreset": "ch32v203c_r0_1v0" + }, + { + "name": "ch32v203g_r0_1v0", + "description": "Build preset for the ch32v203g_r0_1v0 board", + "configurePreset": "ch32v203g_r0_1v0" + }, + { + "name": "ch32v307v_r1_1v0", + "description": "Build preset for the ch32v307v_r1_1v0 board", + "configurePreset": "ch32v307v_r1_1v0" + }, + { + "name": "circuitplayground_bluefruit", + "description": "Build preset for the circuitplayground_bluefruit board", + "configurePreset": "circuitplayground_bluefruit" + }, + { + "name": "circuitplayground_express", + "description": "Build preset for the circuitplayground_express board", + "configurePreset": "circuitplayground_express" + }, + { + "name": "curiosity_nano", + "description": "Build preset for the curiosity_nano board", + "configurePreset": "curiosity_nano" + }, + { + "name": "cynthion_d11", + "description": "Build preset for the cynthion_d11 board", + "configurePreset": "cynthion_d11" + }, + { + "name": "cynthion_d21", + "description": "Build preset for the cynthion_d21 board", + "configurePreset": "cynthion_d21" + }, + { + "name": "d5035_01", + "description": "Build preset for the d5035_01 board", + "configurePreset": "d5035_01" + }, + { + "name": "da14695_dk_usb", + "description": "Build preset for the da14695_dk_usb board", + "configurePreset": "da14695_dk_usb" + }, + { + "name": "da1469x_dk_pro", + "description": "Build preset for the da1469x_dk_pro board", + "configurePreset": "da1469x_dk_pro" + }, + { + "name": "daisyseed", + "description": "Build preset for the daisyseed board", + "configurePreset": "daisyseed" + }, + { + "name": "double_m33_express", + "description": "Build preset for the double_m33_express board", + "configurePreset": "double_m33_express" + }, + { + "name": "ea4088_quickstart", + "description": "Build preset for the ea4088_quickstart board", + "configurePreset": "ea4088_quickstart" + }, + { + "name": "ea4357", + "description": "Build preset for the ea4357 board", + "configurePreset": "ea4357" + }, + { + "name": "ek_tm4c123gxl", + "description": "Build preset for the ek_tm4c123gxl board", + "configurePreset": "ek_tm4c123gxl" + }, + { + "name": "espressif_addax_1", + "description": "Build preset for the espressif_addax_1 board", + "configurePreset": "espressif_addax_1" + }, + { + "name": "espressif_c3_devkitc", + "description": "Build preset for the espressif_c3_devkitc board", + "configurePreset": "espressif_c3_devkitc" + }, + { + "name": "espressif_c6_devkitc", + "description": "Build preset for the espressif_c6_devkitc board", + "configurePreset": "espressif_c6_devkitc" + }, + { + "name": "espressif_kaluga_1", + "description": "Build preset for the espressif_kaluga_1 board", + "configurePreset": "espressif_kaluga_1" + }, + { + "name": "espressif_p4_function_ev", + "description": "Build preset for the espressif_p4_function_ev board", + "configurePreset": "espressif_p4_function_ev" + }, + { + "name": "espressif_s2_devkitc", + "description": "Build preset for the espressif_s2_devkitc board", + "configurePreset": "espressif_s2_devkitc" + }, + { + "name": "espressif_s3_devkitc", + "description": "Build preset for the espressif_s3_devkitc board", + "configurePreset": "espressif_s3_devkitc" + }, + { + "name": "espressif_s3_devkitm", + "description": "Build preset for the espressif_s3_devkitm board", + "configurePreset": "espressif_s3_devkitm" + }, + { + "name": "espressif_saola_1", + "description": "Build preset for the espressif_saola_1 board", + "configurePreset": "espressif_saola_1" + }, + { + "name": "f1c100s", + "description": "Build preset for the f1c100s board", + "configurePreset": "f1c100s" + }, + { + "name": "feather_m0_express", + "description": "Build preset for the feather_m0_express board", + "configurePreset": "feather_m0_express" + }, + { + "name": "feather_m4_express", + "description": "Build preset for the feather_m4_express board", + "configurePreset": "feather_m4_express" + }, + { + "name": "feather_nrf52840_express", + "description": "Build preset for the feather_nrf52840_express board", + "configurePreset": "feather_nrf52840_express" + }, + { + "name": "feather_nrf52840_sense", + "description": "Build preset for the feather_nrf52840_sense board", + "configurePreset": "feather_nrf52840_sense" + }, + { + "name": "feather_rp2040_max3421", + "description": "Build preset for the feather_rp2040_max3421 board", + "configurePreset": "feather_rp2040_max3421" + }, + { + "name": "feather_stm32f405", + "description": "Build preset for the feather_stm32f405 board", + "configurePreset": "feather_stm32f405" + }, + { + "name": "fomu", + "description": "Build preset for the fomu board", + "configurePreset": "fomu" + }, + { + "name": "frdm_k32l2a4s", + "description": "Build preset for the frdm_k32l2a4s board", + "configurePreset": "frdm_k32l2a4s" + }, + { + "name": "frdm_k32l2b", + "description": "Build preset for the frdm_k32l2b board", + "configurePreset": "frdm_k32l2b" + }, + { + "name": "frdm_k64f", + "description": "Build preset for the frdm_k64f board", + "configurePreset": "frdm_k64f" + }, + { + "name": "frdm_kl25z", + "description": "Build preset for the frdm_kl25z board", + "configurePreset": "frdm_kl25z" + }, + { + "name": "frdm_mcxa153", + "description": "Build preset for the frdm_mcxa153 board", + "configurePreset": "frdm_mcxa153" + }, + { + "name": "frdm_mcxn947", + "description": "Build preset for the frdm_mcxn947 board", + "configurePreset": "frdm_mcxn947" + }, + { + "name": "itsybitsy_m0", + "description": "Build preset for the itsybitsy_m0 board", + "configurePreset": "itsybitsy_m0" + }, + { + "name": "itsybitsy_m4", + "description": "Build preset for the itsybitsy_m4 board", + "configurePreset": "itsybitsy_m4" + }, + { + "name": "itsybitsy_nrf52840", + "description": "Build preset for the itsybitsy_nrf52840 board", + "configurePreset": "itsybitsy_nrf52840" + }, + { + "name": "kuiic", + "description": "Build preset for the kuiic board", + "configurePreset": "kuiic" + }, + { + "name": "lpcxpresso11u37", + "description": "Build preset for the lpcxpresso11u37 board", + "configurePreset": "lpcxpresso11u37" + }, + { + "name": "lpcxpresso11u68", + "description": "Build preset for the lpcxpresso11u68 board", + "configurePreset": "lpcxpresso11u68" + }, + { + "name": "lpcxpresso1347", + "description": "Build preset for the lpcxpresso1347 board", + "configurePreset": "lpcxpresso1347" + }, + { + "name": "lpcxpresso1549", + "description": "Build preset for the lpcxpresso1549 board", + "configurePreset": "lpcxpresso1549" + }, + { + "name": "lpcxpresso1769", + "description": "Build preset for the lpcxpresso1769 board", + "configurePreset": "lpcxpresso1769" + }, + { + "name": "lpcxpresso18s37", + "description": "Build preset for the lpcxpresso18s37 board", + "configurePreset": "lpcxpresso18s37" + }, + { + "name": "lpcxpresso43s67", + "description": "Build preset for the lpcxpresso43s67 board", + "configurePreset": "lpcxpresso43s67" + }, + { + "name": "lpcxpresso51u68", + "description": "Build preset for the lpcxpresso51u68 board", + "configurePreset": "lpcxpresso51u68" + }, + { + "name": "lpcxpresso54114", + "description": "Build preset for the lpcxpresso54114 board", + "configurePreset": "lpcxpresso54114" + }, + { + "name": "lpcxpresso54608", + "description": "Build preset for the lpcxpresso54608 board", + "configurePreset": "lpcxpresso54608" + }, + { + "name": "lpcxpresso54628", + "description": "Build preset for the lpcxpresso54628 board", + "configurePreset": "lpcxpresso54628" + }, + { + "name": "lpcxpresso55s28", + "description": "Build preset for the lpcxpresso55s28 board", + "configurePreset": "lpcxpresso55s28" + }, + { + "name": "lpcxpresso55s69", + "description": "Build preset for the lpcxpresso55s69 board", + "configurePreset": "lpcxpresso55s69" + }, + { + "name": "max32650evkit", + "description": "Build preset for the max32650evkit board", + "configurePreset": "max32650evkit" + }, + { + "name": "max32650fthr", + "description": "Build preset for the max32650fthr board", + "configurePreset": "max32650fthr" + }, + { + "name": "max32651evkit", + "description": "Build preset for the max32651evkit board", + "configurePreset": "max32651evkit" + }, + { + "name": "max32666evkit", + "description": "Build preset for the max32666evkit board", + "configurePreset": "max32666evkit" + }, + { + "name": "max32666fthr", + "description": "Build preset for the max32666fthr board", + "configurePreset": "max32666fthr" + }, + { + "name": "max32690evkit", + "description": "Build preset for the max32690evkit board", + "configurePreset": "max32690evkit" + }, + { + "name": "max78002evkit", + "description": "Build preset for the max78002evkit board", + "configurePreset": "max78002evkit" + }, + { + "name": "mbed1768", + "description": "Build preset for the mbed1768 board", + "configurePreset": "mbed1768" + }, + { + "name": "mcb1800", + "description": "Build preset for the mcb1800 board", + "configurePreset": "mcb1800" + }, + { + "name": "mcu_link", + "description": "Build preset for the mcu_link board", + "configurePreset": "mcu_link" + }, + { + "name": "mcxn947brk", + "description": "Build preset for the mcxn947brk board", + "configurePreset": "mcxn947brk" + }, + { + "name": "metro_m0_express", + "description": "Build preset for the metro_m0_express board", + "configurePreset": "metro_m0_express" + }, + { + "name": "metro_m4_express", + "description": "Build preset for the metro_m4_express board", + "configurePreset": "metro_m4_express" + }, + { + "name": "metro_m7_1011", + "description": "Build preset for the metro_m7_1011 board", + "configurePreset": "metro_m7_1011" + }, + { + "name": "metro_m7_1011_sd", + "description": "Build preset for the metro_m7_1011_sd board", + "configurePreset": "metro_m7_1011_sd" + }, + { + "name": "mimxrt1010_evk", + "description": "Build preset for the mimxrt1010_evk board", + "configurePreset": "mimxrt1010_evk" + }, + { + "name": "mimxrt1015_evk", + "description": "Build preset for the mimxrt1015_evk board", + "configurePreset": "mimxrt1015_evk" + }, + { + "name": "mimxrt1020_evk", + "description": "Build preset for the mimxrt1020_evk board", + "configurePreset": "mimxrt1020_evk" + }, + { + "name": "mimxrt1024_evk", + "description": "Build preset for the mimxrt1024_evk board", + "configurePreset": "mimxrt1024_evk" + }, + { + "name": "mimxrt1050_evkb", + "description": "Build preset for the mimxrt1050_evkb board", + "configurePreset": "mimxrt1050_evkb" + }, + { + "name": "mimxrt1060_evk", + "description": "Build preset for the mimxrt1060_evk board", + "configurePreset": "mimxrt1060_evk" + }, + { + "name": "mimxrt1064_evk", + "description": "Build preset for the mimxrt1064_evk board", + "configurePreset": "mimxrt1064_evk" + }, + { + "name": "mimxrt1170_evkb", + "description": "Build preset for the mimxrt1170_evkb board", + "configurePreset": "mimxrt1170_evkb" + }, + { + "name": "mm32f327x_mb39", + "description": "Build preset for the mm32f327x_mb39 board", + "configurePreset": "mm32f327x_mb39" + }, + { + "name": "mm32f327x_pitaya_lite", + "description": "Build preset for the mm32f327x_pitaya_lite board", + "configurePreset": "mm32f327x_pitaya_lite" + }, + { + "name": "msp_exp430f5529lp", + "description": "Build preset for the msp_exp430f5529lp board", + "configurePreset": "msp_exp430f5529lp" + }, + { + "name": "msp_exp432e401y", + "description": "Build preset for the msp_exp432e401y board", + "configurePreset": "msp_exp432e401y" + }, + { + "name": "nanoch32v203", + "description": "Build preset for the nanoch32v203 board", + "configurePreset": "nanoch32v203" + }, + { + "name": "pca10056", + "description": "Build preset for the pca10056 board", + "configurePreset": "pca10056" + }, + { + "name": "pca10059", + "description": "Build preset for the pca10059 board", + "configurePreset": "pca10059" + }, + { + "name": "pca10095", + "description": "Build preset for the pca10095 board", + "configurePreset": "pca10095" + }, + { + "name": "pca10100", + "description": "Build preset for the pca10100 board", + "configurePreset": "pca10100" + }, + { + "name": "pico_sdk", + "description": "Build preset for the pico_sdk board", + "configurePreset": "pico_sdk" + }, + { + "name": "portenta_c33", + "description": "Build preset for the portenta_c33 board", + "configurePreset": "portenta_c33" + }, + { + "name": "pybadge", + "description": "Build preset for the pybadge board", + "configurePreset": "pybadge" + }, + { + "name": "pyboardv11", + "description": "Build preset for the pyboardv11 board", + "configurePreset": "pyboardv11" + }, + { + "name": "pyportal", + "description": "Build preset for the pyportal board", + "configurePreset": "pyportal" + }, + { + "name": "qtpy", + "description": "Build preset for the qtpy board", + "configurePreset": "qtpy" + }, + { + "name": "ra2a1_ek", + "description": "Build preset for the ra2a1_ek board", + "configurePreset": "ra2a1_ek" + }, + { + "name": "ra4m1_ek", + "description": "Build preset for the ra4m1_ek board", + "configurePreset": "ra4m1_ek" + }, + { + "name": "ra4m3_ek", + "description": "Build preset for the ra4m3_ek board", + "configurePreset": "ra4m3_ek" + }, + { + "name": "ra6m1_ek", + "description": "Build preset for the ra6m1_ek board", + "configurePreset": "ra6m1_ek" + }, + { + "name": "ra6m5_ek", + "description": "Build preset for the ra6m5_ek board", + "configurePreset": "ra6m5_ek" + }, + { + "name": "ra8m1_ek", + "description": "Build preset for the ra8m1_ek board", + "configurePreset": "ra8m1_ek" + }, + { + "name": "raspberry_pi_pico", + "description": "Build preset for the raspberry_pi_pico board", + "configurePreset": "raspberry_pi_pico" + }, + { + "name": "raspberry_pi_pico2", + "description": "Build preset for the raspberry_pi_pico2 board", + "configurePreset": "raspberry_pi_pico2" + }, + { + "name": "raspberrypi_cm4", + "description": "Build preset for the raspberrypi_cm4 board", + "configurePreset": "raspberrypi_cm4" + }, + { + "name": "raspberrypi_zero", + "description": "Build preset for the raspberrypi_zero board", + "configurePreset": "raspberrypi_zero" + }, + { + "name": "raspberrypi_zero2", + "description": "Build preset for the raspberrypi_zero2 board", + "configurePreset": "raspberrypi_zero2" + }, + { + "name": "samd11_xplained", + "description": "Build preset for the samd11_xplained board", + "configurePreset": "samd11_xplained" + }, + { + "name": "same54_xplained", + "description": "Build preset for the same54_xplained board", + "configurePreset": "same54_xplained" + }, + { + "name": "samg55_xplained", + "description": "Build preset for the samg55_xplained board", + "configurePreset": "samg55_xplained" + }, + { + "name": "saml22_feather", + "description": "Build preset for the saml22_feather board", + "configurePreset": "saml22_feather" + }, + { + "name": "seeeduino_xiao", + "description": "Build preset for the seeeduino_xiao board", + "configurePreset": "seeeduino_xiao" + }, + { + "name": "sensorwatch_m0", + "description": "Build preset for the sensorwatch_m0 board", + "configurePreset": "sensorwatch_m0" + }, + { + "name": "sipeed_longan_nano", + "description": "Build preset for the sipeed_longan_nano board", + "configurePreset": "sipeed_longan_nano" + }, + { + "name": "sparkfun_samd21_mini_usb", + "description": "Build preset for the sparkfun_samd21_mini_usb board", + "configurePreset": "sparkfun_samd21_mini_usb" + }, + { + "name": "stlinkv3mini", + "description": "Build preset for the stlinkv3mini board", + "configurePreset": "stlinkv3mini" + }, + { + "name": "stm32c071nucleo", + "description": "Build preset for the stm32c071nucleo board", + "configurePreset": "stm32c071nucleo" + }, + { + "name": "stm32f070rbnucleo", + "description": "Build preset for the stm32f070rbnucleo board", + "configurePreset": "stm32f070rbnucleo" + }, + { + "name": "stm32f072disco", + "description": "Build preset for the stm32f072disco board", + "configurePreset": "stm32f072disco" + }, + { + "name": "stm32f072eval", + "description": "Build preset for the stm32f072eval board", + "configurePreset": "stm32f072eval" + }, + { + "name": "stm32f103_bluepill", + "description": "Build preset for the stm32f103_bluepill board", + "configurePreset": "stm32f103_bluepill" + }, + { + "name": "stm32f103_mini_2", + "description": "Build preset for the stm32f103_mini_2 board", + "configurePreset": "stm32f103_mini_2" + }, + { + "name": "stm32f103ze_iar", + "description": "Build preset for the stm32f103ze_iar board", + "configurePreset": "stm32f103ze_iar" + }, + { + "name": "stm32f207nucleo", + "description": "Build preset for the stm32f207nucleo board", + "configurePreset": "stm32f207nucleo" + }, + { + "name": "stm32f303disco", + "description": "Build preset for the stm32f303disco board", + "configurePreset": "stm32f303disco" + }, + { + "name": "stm32f401blackpill", + "description": "Build preset for the stm32f401blackpill board", + "configurePreset": "stm32f401blackpill" + }, + { + "name": "stm32f407blackvet", + "description": "Build preset for the stm32f407blackvet board", + "configurePreset": "stm32f407blackvet" + }, + { + "name": "stm32f407disco", + "description": "Build preset for the stm32f407disco board", + "configurePreset": "stm32f407disco" + }, + { + "name": "stm32f411blackpill", + "description": "Build preset for the stm32f411blackpill board", + "configurePreset": "stm32f411blackpill" + }, + { + "name": "stm32f411disco", + "description": "Build preset for the stm32f411disco board", + "configurePreset": "stm32f411disco" + }, + { + "name": "stm32f412disco", + "description": "Build preset for the stm32f412disco board", + "configurePreset": "stm32f412disco" + }, + { + "name": "stm32f412nucleo", + "description": "Build preset for the stm32f412nucleo board", + "configurePreset": "stm32f412nucleo" + }, + { + "name": "stm32f439nucleo", + "description": "Build preset for the stm32f439nucleo board", + "configurePreset": "stm32f439nucleo" + }, + { + "name": "stm32f723disco", + "description": "Build preset for the stm32f723disco board", + "configurePreset": "stm32f723disco" + }, + { + "name": "stm32f746disco", + "description": "Build preset for the stm32f746disco board", + "configurePreset": "stm32f746disco" + }, + { + "name": "stm32f746nucleo", + "description": "Build preset for the stm32f746nucleo board", + "configurePreset": "stm32f746nucleo" + }, + { + "name": "stm32f767nucleo", + "description": "Build preset for the stm32f767nucleo board", + "configurePreset": "stm32f767nucleo" + }, + { + "name": "stm32f769disco", + "description": "Build preset for the stm32f769disco board", + "configurePreset": "stm32f769disco" + }, + { + "name": "stm32g0b1nucleo", + "description": "Build preset for the stm32g0b1nucleo board", + "configurePreset": "stm32g0b1nucleo" + }, + { + "name": "stm32g474nucleo", + "description": "Build preset for the stm32g474nucleo board", + "configurePreset": "stm32g474nucleo" + }, + { + "name": "stm32g491nucleo", + "description": "Build preset for the stm32g491nucleo board", + "configurePreset": "stm32g491nucleo" + }, + { + "name": "stm32h503nucleo", + "description": "Build preset for the stm32h503nucleo board", + "configurePreset": "stm32h503nucleo" + }, + { + "name": "stm32h563nucleo", + "description": "Build preset for the stm32h563nucleo board", + "configurePreset": "stm32h563nucleo" + }, + { + "name": "stm32h573i_dk", + "description": "Build preset for the stm32h573i_dk board", + "configurePreset": "stm32h573i_dk" + }, + { + "name": "stm32h723nucleo", + "description": "Build preset for the stm32h723nucleo board", + "configurePreset": "stm32h723nucleo" + }, + { + "name": "stm32h743eval", + "description": "Build preset for the stm32h743eval board", + "configurePreset": "stm32h743eval" + }, + { + "name": "stm32h743nucleo", + "description": "Build preset for the stm32h743nucleo board", + "configurePreset": "stm32h743nucleo" + }, + { + "name": "stm32h745disco", + "description": "Build preset for the stm32h745disco board", + "configurePreset": "stm32h745disco" + }, + { + "name": "stm32h750_weact", + "description": "Build preset for the stm32h750_weact board", + "configurePreset": "stm32h750_weact" + }, + { + "name": "stm32h750bdk", + "description": "Build preset for the stm32h750bdk board", + "configurePreset": "stm32h750bdk" + }, + { + "name": "stm32h7s3nucleo", + "description": "Build preset for the stm32h7s3nucleo board", + "configurePreset": "stm32h7s3nucleo" + }, + { + "name": "stm32l052dap52", + "description": "Build preset for the stm32l052dap52 board", + "configurePreset": "stm32l052dap52" + }, + { + "name": "stm32l0538disco", + "description": "Build preset for the stm32l0538disco board", + "configurePreset": "stm32l0538disco" + }, + { + "name": "stm32l412nucleo", + "description": "Build preset for the stm32l412nucleo board", + "configurePreset": "stm32l412nucleo" + }, + { + "name": "stm32l476disco", + "description": "Build preset for the stm32l476disco board", + "configurePreset": "stm32l476disco" + }, + { + "name": "stm32l4p5nucleo", + "description": "Build preset for the stm32l4p5nucleo board", + "configurePreset": "stm32l4p5nucleo" + }, + { + "name": "stm32l4r5nucleo", + "description": "Build preset for the stm32l4r5nucleo board", + "configurePreset": "stm32l4r5nucleo" + }, + { + "name": "stm32u545nucleo", + "description": "Build preset for the stm32u545nucleo board", + "configurePreset": "stm32u545nucleo" + }, + { + "name": "stm32u575eval", + "description": "Build preset for the stm32u575eval board", + "configurePreset": "stm32u575eval" + }, + { + "name": "stm32u575nucleo", + "description": "Build preset for the stm32u575nucleo board", + "configurePreset": "stm32u575nucleo" + }, + { + "name": "stm32u5a5nucleo", + "description": "Build preset for the stm32u5a5nucleo board", + "configurePreset": "stm32u5a5nucleo" + }, + { + "name": "stm32wb55nucleo", + "description": "Build preset for the stm32wb55nucleo board", + "configurePreset": "stm32wb55nucleo" + }, + { + "name": "teensy_35", + "description": "Build preset for the teensy_35 board", + "configurePreset": "teensy_35" + }, + { + "name": "teensy_40", + "description": "Build preset for the teensy_40 board", + "configurePreset": "teensy_40" + }, + { + "name": "teensy_41", + "description": "Build preset for the teensy_41 board", + "configurePreset": "teensy_41" + }, + { + "name": "trinket_m0", + "description": "Build preset for the trinket_m0 board", + "configurePreset": "trinket_m0" + }, + { + "name": "uno_r4", + "description": "Build preset for the uno_r4 board", + "configurePreset": "uno_r4" + }, + { + "name": "waveshare_openh743i", + "description": "Build preset for the waveshare_openh743i board", + "configurePreset": "waveshare_openh743i" + }, + { + "name": "xmc4500_relax", + "description": "Build preset for the xmc4500_relax board", + "configurePreset": "xmc4500_relax" + }, + { + "name": "xmc4700_relax", + "description": "Build preset for the xmc4700_relax board", + "configurePreset": "xmc4700_relax" + } + ], + "workflowPresets": [ + { + "name": "adafruit_clue", + "steps": [ + { + "type": "configure", + "name": "adafruit_clue" + }, + { + "type": "build", + "name": "adafruit_clue" + } + ] + }, + { + "name": "adafruit_feather_esp32_v2", + "steps": [ + { + "type": "configure", + "name": "adafruit_feather_esp32_v2" + }, + { + "type": "build", + "name": "adafruit_feather_esp32_v2" + } + ] + }, + { + "name": "adafruit_feather_esp32s2", + "steps": [ + { + "type": "configure", + "name": "adafruit_feather_esp32s2" + }, + { + "type": "build", + "name": "adafruit_feather_esp32s2" + } + ] + }, + { + "name": "adafruit_feather_esp32s3", + "steps": [ + { + "type": "configure", + "name": "adafruit_feather_esp32s3" + }, + { + "type": "build", + "name": "adafruit_feather_esp32s3" + } + ] + }, + { + "name": "adafruit_magtag_29gray", + "steps": [ + { + "type": "configure", + "name": "adafruit_magtag_29gray" + }, + { + "type": "build", + "name": "adafruit_magtag_29gray" + } + ] + }, + { + "name": "adafruit_metro_esp32s2", + "steps": [ + { + "type": "configure", + "name": "adafruit_metro_esp32s2" + }, + { + "type": "build", + "name": "adafruit_metro_esp32s2" + } + ] + }, + { + "name": "apard32690", + "steps": [ + { + "type": "configure", + "name": "apard32690" + }, + { + "type": "build", + "name": "apard32690" + } + ] + }, + { + "name": "arduino_nano33_ble", + "steps": [ + { + "type": "configure", + "name": "arduino_nano33_ble" + }, + { + "type": "build", + "name": "arduino_nano33_ble" + } + ] + }, + { + "name": "atsamd21_xpro", + "steps": [ + { + "type": "configure", + "name": "atsamd21_xpro" + }, + { + "type": "build", + "name": "atsamd21_xpro" + } + ] + }, + { + "name": "atsaml21_xpro", + "steps": [ + { + "type": "configure", + "name": "atsaml21_xpro" + }, + { + "type": "build", + "name": "atsaml21_xpro" + } + ] + }, + { + "name": "b_g474e_dpow1", + "steps": [ + { + "type": "configure", + "name": "b_g474e_dpow1" + }, + { + "type": "build", + "name": "b_g474e_dpow1" + } + ] + }, + { + "name": "b_u585i_iot2a", + "steps": [ + { + "type": "configure", + "name": "b_u585i_iot2a" + }, + { + "type": "build", + "name": "b_u585i_iot2a" + } + ] + }, + { + "name": "ch32v103r_r1_1v0", + "steps": [ + { + "type": "configure", + "name": "ch32v103r_r1_1v0" + }, + { + "type": "build", + "name": "ch32v103r_r1_1v0" + } + ] + }, + { + "name": "ch32v203c_r0_1v0", + "steps": [ + { + "type": "configure", + "name": "ch32v203c_r0_1v0" + }, + { + "type": "build", + "name": "ch32v203c_r0_1v0" + } + ] + }, + { + "name": "ch32v203g_r0_1v0", + "steps": [ + { + "type": "configure", + "name": "ch32v203g_r0_1v0" + }, + { + "type": "build", + "name": "ch32v203g_r0_1v0" + } + ] + }, + { + "name": "ch32v307v_r1_1v0", + "steps": [ + { + "type": "configure", + "name": "ch32v307v_r1_1v0" + }, + { + "type": "build", + "name": "ch32v307v_r1_1v0" + } + ] + }, + { + "name": "circuitplayground_bluefruit", + "steps": [ + { + "type": "configure", + "name": "circuitplayground_bluefruit" + }, + { + "type": "build", + "name": "circuitplayground_bluefruit" + } + ] + }, + { + "name": "circuitplayground_express", + "steps": [ + { + "type": "configure", + "name": "circuitplayground_express" + }, + { + "type": "build", + "name": "circuitplayground_express" + } + ] + }, + { + "name": "curiosity_nano", + "steps": [ + { + "type": "configure", + "name": "curiosity_nano" + }, + { + "type": "build", + "name": "curiosity_nano" + } + ] + }, + { + "name": "cynthion_d11", + "steps": [ + { + "type": "configure", + "name": "cynthion_d11" + }, + { + "type": "build", + "name": "cynthion_d11" + } + ] + }, + { + "name": "cynthion_d21", + "steps": [ + { + "type": "configure", + "name": "cynthion_d21" + }, + { + "type": "build", + "name": "cynthion_d21" + } + ] + }, + { + "name": "d5035_01", + "steps": [ + { + "type": "configure", + "name": "d5035_01" + }, + { + "type": "build", + "name": "d5035_01" + } + ] + }, + { + "name": "da14695_dk_usb", + "steps": [ + { + "type": "configure", + "name": "da14695_dk_usb" + }, + { + "type": "build", + "name": "da14695_dk_usb" + } + ] + }, + { + "name": "da1469x_dk_pro", + "steps": [ + { + "type": "configure", + "name": "da1469x_dk_pro" + }, + { + "type": "build", + "name": "da1469x_dk_pro" + } + ] + }, + { + "name": "daisyseed", + "steps": [ + { + "type": "configure", + "name": "daisyseed" + }, + { + "type": "build", + "name": "daisyseed" + } + ] + }, + { + "name": "double_m33_express", + "steps": [ + { + "type": "configure", + "name": "double_m33_express" + }, + { + "type": "build", + "name": "double_m33_express" + } + ] + }, + { + "name": "ea4088_quickstart", + "steps": [ + { + "type": "configure", + "name": "ea4088_quickstart" + }, + { + "type": "build", + "name": "ea4088_quickstart" + } + ] + }, + { + "name": "ea4357", + "steps": [ + { + "type": "configure", + "name": "ea4357" + }, + { + "type": "build", + "name": "ea4357" + } + ] + }, + { + "name": "ek_tm4c123gxl", + "steps": [ + { + "type": "configure", + "name": "ek_tm4c123gxl" + }, + { + "type": "build", + "name": "ek_tm4c123gxl" + } + ] + }, + { + "name": "espressif_addax_1", + "steps": [ + { + "type": "configure", + "name": "espressif_addax_1" + }, + { + "type": "build", + "name": "espressif_addax_1" + } + ] + }, + { + "name": "espressif_c3_devkitc", + "steps": [ + { + "type": "configure", + "name": "espressif_c3_devkitc" + }, + { + "type": "build", + "name": "espressif_c3_devkitc" + } + ] + }, + { + "name": "espressif_c6_devkitc", + "steps": [ + { + "type": "configure", + "name": "espressif_c6_devkitc" + }, + { + "type": "build", + "name": "espressif_c6_devkitc" + } + ] + }, + { + "name": "espressif_kaluga_1", + "steps": [ + { + "type": "configure", + "name": "espressif_kaluga_1" + }, + { + "type": "build", + "name": "espressif_kaluga_1" + } + ] + }, + { + "name": "espressif_p4_function_ev", + "steps": [ + { + "type": "configure", + "name": "espressif_p4_function_ev" + }, + { + "type": "build", + "name": "espressif_p4_function_ev" + } + ] + }, + { + "name": "espressif_s2_devkitc", + "steps": [ + { + "type": "configure", + "name": "espressif_s2_devkitc" + }, + { + "type": "build", + "name": "espressif_s2_devkitc" + } + ] + }, + { + "name": "espressif_s3_devkitc", + "steps": [ + { + "type": "configure", + "name": "espressif_s3_devkitc" + }, + { + "type": "build", + "name": "espressif_s3_devkitc" + } + ] + }, + { + "name": "espressif_s3_devkitm", + "steps": [ + { + "type": "configure", + "name": "espressif_s3_devkitm" + }, + { + "type": "build", + "name": "espressif_s3_devkitm" + } + ] + }, + { + "name": "espressif_saola_1", + "steps": [ + { + "type": "configure", + "name": "espressif_saola_1" + }, + { + "type": "build", + "name": "espressif_saola_1" + } + ] + }, + { + "name": "f1c100s", + "steps": [ + { + "type": "configure", + "name": "f1c100s" + }, + { + "type": "build", + "name": "f1c100s" + } + ] + }, + { + "name": "feather_m0_express", + "steps": [ + { + "type": "configure", + "name": "feather_m0_express" + }, + { + "type": "build", + "name": "feather_m0_express" + } + ] + }, + { + "name": "feather_m4_express", + "steps": [ + { + "type": "configure", + "name": "feather_m4_express" + }, + { + "type": "build", + "name": "feather_m4_express" + } + ] + }, + { + "name": "feather_nrf52840_express", + "steps": [ + { + "type": "configure", + "name": "feather_nrf52840_express" + }, + { + "type": "build", + "name": "feather_nrf52840_express" + } + ] + }, + { + "name": "feather_nrf52840_sense", + "steps": [ + { + "type": "configure", + "name": "feather_nrf52840_sense" + }, + { + "type": "build", + "name": "feather_nrf52840_sense" + } + ] + }, + { + "name": "feather_rp2040_max3421", + "steps": [ + { + "type": "configure", + "name": "feather_rp2040_max3421" + }, + { + "type": "build", + "name": "feather_rp2040_max3421" + } + ] + }, + { + "name": "feather_stm32f405", + "steps": [ + { + "type": "configure", + "name": "feather_stm32f405" + }, + { + "type": "build", + "name": "feather_stm32f405" + } + ] + }, + { + "name": "fomu", + "steps": [ + { + "type": "configure", + "name": "fomu" + }, + { + "type": "build", + "name": "fomu" + } + ] + }, + { + "name": "frdm_k32l2a4s", + "steps": [ + { + "type": "configure", + "name": "frdm_k32l2a4s" + }, + { + "type": "build", + "name": "frdm_k32l2a4s" + } + ] + }, + { + "name": "frdm_k32l2b", + "steps": [ + { + "type": "configure", + "name": "frdm_k32l2b" + }, + { + "type": "build", + "name": "frdm_k32l2b" + } + ] + }, + { + "name": "frdm_k64f", + "steps": [ + { + "type": "configure", + "name": "frdm_k64f" + }, + { + "type": "build", + "name": "frdm_k64f" + } + ] + }, + { + "name": "frdm_kl25z", + "steps": [ + { + "type": "configure", + "name": "frdm_kl25z" + }, + { + "type": "build", + "name": "frdm_kl25z" + } + ] + }, + { + "name": "frdm_mcxa153", + "steps": [ + { + "type": "configure", + "name": "frdm_mcxa153" + }, + { + "type": "build", + "name": "frdm_mcxa153" + } + ] + }, + { + "name": "frdm_mcxn947", + "steps": [ + { + "type": "configure", + "name": "frdm_mcxn947" + }, + { + "type": "build", + "name": "frdm_mcxn947" + } + ] + }, + { + "name": "itsybitsy_m0", + "steps": [ + { + "type": "configure", + "name": "itsybitsy_m0" + }, + { + "type": "build", + "name": "itsybitsy_m0" + } + ] + }, + { + "name": "itsybitsy_m4", + "steps": [ + { + "type": "configure", + "name": "itsybitsy_m4" + }, + { + "type": "build", + "name": "itsybitsy_m4" + } + ] + }, + { + "name": "itsybitsy_nrf52840", + "steps": [ + { + "type": "configure", + "name": "itsybitsy_nrf52840" + }, + { + "type": "build", + "name": "itsybitsy_nrf52840" + } + ] + }, + { + "name": "kuiic", + "steps": [ + { + "type": "configure", + "name": "kuiic" + }, + { + "type": "build", + "name": "kuiic" + } + ] + }, + { + "name": "lpcxpresso11u37", + "steps": [ + { + "type": "configure", + "name": "lpcxpresso11u37" + }, + { + "type": "build", + "name": "lpcxpresso11u37" + } + ] + }, + { + "name": "lpcxpresso11u68", + "steps": [ + { + "type": "configure", + "name": "lpcxpresso11u68" + }, + { + "type": "build", + "name": "lpcxpresso11u68" + } + ] + }, + { + "name": "lpcxpresso1347", + "steps": [ + { + "type": "configure", + "name": "lpcxpresso1347" + }, + { + "type": "build", + "name": "lpcxpresso1347" + } + ] + }, + { + "name": "lpcxpresso1549", + "steps": [ + { + "type": "configure", + "name": "lpcxpresso1549" + }, + { + "type": "build", + "name": "lpcxpresso1549" + } + ] + }, + { + "name": "lpcxpresso1769", + "steps": [ + { + "type": "configure", + "name": "lpcxpresso1769" + }, + { + "type": "build", + "name": "lpcxpresso1769" + } + ] + }, + { + "name": "lpcxpresso18s37", + "steps": [ + { + "type": "configure", + "name": "lpcxpresso18s37" + }, + { + "type": "build", + "name": "lpcxpresso18s37" + } + ] + }, + { + "name": "lpcxpresso43s67", + "steps": [ + { + "type": "configure", + "name": "lpcxpresso43s67" + }, + { + "type": "build", + "name": "lpcxpresso43s67" + } + ] + }, + { + "name": "lpcxpresso51u68", + "steps": [ + { + "type": "configure", + "name": "lpcxpresso51u68" + }, + { + "type": "build", + "name": "lpcxpresso51u68" + } + ] + }, + { + "name": "lpcxpresso54114", + "steps": [ + { + "type": "configure", + "name": "lpcxpresso54114" + }, + { + "type": "build", + "name": "lpcxpresso54114" + } + ] + }, + { + "name": "lpcxpresso54608", + "steps": [ + { + "type": "configure", + "name": "lpcxpresso54608" + }, + { + "type": "build", + "name": "lpcxpresso54608" + } + ] + }, + { + "name": "lpcxpresso54628", + "steps": [ + { + "type": "configure", + "name": "lpcxpresso54628" + }, + { + "type": "build", + "name": "lpcxpresso54628" + } + ] + }, + { + "name": "lpcxpresso55s28", + "steps": [ + { + "type": "configure", + "name": "lpcxpresso55s28" + }, + { + "type": "build", + "name": "lpcxpresso55s28" + } + ] + }, + { + "name": "lpcxpresso55s69", + "steps": [ + { + "type": "configure", + "name": "lpcxpresso55s69" + }, + { + "type": "build", + "name": "lpcxpresso55s69" + } + ] + }, + { + "name": "max32650evkit", + "steps": [ + { + "type": "configure", + "name": "max32650evkit" + }, + { + "type": "build", + "name": "max32650evkit" + } + ] + }, + { + "name": "max32650fthr", + "steps": [ + { + "type": "configure", + "name": "max32650fthr" + }, + { + "type": "build", + "name": "max32650fthr" + } + ] + }, + { + "name": "max32651evkit", + "steps": [ + { + "type": "configure", + "name": "max32651evkit" + }, + { + "type": "build", + "name": "max32651evkit" + } + ] + }, + { + "name": "max32666evkit", + "steps": [ + { + "type": "configure", + "name": "max32666evkit" + }, + { + "type": "build", + "name": "max32666evkit" + } + ] + }, + { + "name": "max32666fthr", + "steps": [ + { + "type": "configure", + "name": "max32666fthr" + }, + { + "type": "build", + "name": "max32666fthr" + } + ] + }, + { + "name": "max32690evkit", + "steps": [ + { + "type": "configure", + "name": "max32690evkit" + }, + { + "type": "build", + "name": "max32690evkit" + } + ] + }, + { + "name": "max78002evkit", + "steps": [ + { + "type": "configure", + "name": "max78002evkit" + }, + { + "type": "build", + "name": "max78002evkit" + } + ] + }, + { + "name": "mbed1768", + "steps": [ + { + "type": "configure", + "name": "mbed1768" + }, + { + "type": "build", + "name": "mbed1768" + } + ] + }, + { + "name": "mcb1800", + "steps": [ + { + "type": "configure", + "name": "mcb1800" + }, + { + "type": "build", + "name": "mcb1800" + } + ] + }, + { + "name": "mcu_link", + "steps": [ + { + "type": "configure", + "name": "mcu_link" + }, + { + "type": "build", + "name": "mcu_link" + } + ] + }, + { + "name": "mcxn947brk", + "steps": [ + { + "type": "configure", + "name": "mcxn947brk" + }, + { + "type": "build", + "name": "mcxn947brk" + } + ] + }, + { + "name": "metro_m0_express", + "steps": [ + { + "type": "configure", + "name": "metro_m0_express" + }, + { + "type": "build", + "name": "metro_m0_express" + } + ] + }, + { + "name": "metro_m4_express", + "steps": [ + { + "type": "configure", + "name": "metro_m4_express" + }, + { + "type": "build", + "name": "metro_m4_express" + } + ] + }, + { + "name": "metro_m7_1011", + "steps": [ + { + "type": "configure", + "name": "metro_m7_1011" + }, + { + "type": "build", + "name": "metro_m7_1011" + } + ] + }, + { + "name": "metro_m7_1011_sd", + "steps": [ + { + "type": "configure", + "name": "metro_m7_1011_sd" + }, + { + "type": "build", + "name": "metro_m7_1011_sd" + } + ] + }, + { + "name": "mimxrt1010_evk", + "steps": [ + { + "type": "configure", + "name": "mimxrt1010_evk" + }, + { + "type": "build", + "name": "mimxrt1010_evk" + } + ] + }, + { + "name": "mimxrt1015_evk", + "steps": [ + { + "type": "configure", + "name": "mimxrt1015_evk" + }, + { + "type": "build", + "name": "mimxrt1015_evk" + } + ] + }, + { + "name": "mimxrt1020_evk", + "steps": [ + { + "type": "configure", + "name": "mimxrt1020_evk" + }, + { + "type": "build", + "name": "mimxrt1020_evk" + } + ] + }, + { + "name": "mimxrt1024_evk", + "steps": [ + { + "type": "configure", + "name": "mimxrt1024_evk" + }, + { + "type": "build", + "name": "mimxrt1024_evk" + } + ] + }, + { + "name": "mimxrt1050_evkb", + "steps": [ + { + "type": "configure", + "name": "mimxrt1050_evkb" + }, + { + "type": "build", + "name": "mimxrt1050_evkb" + } + ] + }, + { + "name": "mimxrt1060_evk", + "steps": [ + { + "type": "configure", + "name": "mimxrt1060_evk" + }, + { + "type": "build", + "name": "mimxrt1060_evk" + } + ] + }, + { + "name": "mimxrt1064_evk", + "steps": [ + { + "type": "configure", + "name": "mimxrt1064_evk" + }, + { + "type": "build", + "name": "mimxrt1064_evk" + } + ] + }, + { + "name": "mimxrt1170_evkb", + "steps": [ + { + "type": "configure", + "name": "mimxrt1170_evkb" + }, + { + "type": "build", + "name": "mimxrt1170_evkb" + } + ] + }, + { + "name": "mm32f327x_mb39", + "steps": [ + { + "type": "configure", + "name": "mm32f327x_mb39" + }, + { + "type": "build", + "name": "mm32f327x_mb39" + } + ] + }, + { + "name": "mm32f327x_pitaya_lite", + "steps": [ + { + "type": "configure", + "name": "mm32f327x_pitaya_lite" + }, + { + "type": "build", + "name": "mm32f327x_pitaya_lite" + } + ] + }, + { + "name": "msp_exp430f5529lp", + "steps": [ + { + "type": "configure", + "name": "msp_exp430f5529lp" + }, + { + "type": "build", + "name": "msp_exp430f5529lp" + } + ] + }, + { + "name": "msp_exp432e401y", + "steps": [ + { + "type": "configure", + "name": "msp_exp432e401y" + }, + { + "type": "build", + "name": "msp_exp432e401y" + } + ] + }, + { + "name": "nanoch32v203", + "steps": [ + { + "type": "configure", + "name": "nanoch32v203" + }, + { + "type": "build", + "name": "nanoch32v203" + } + ] + }, + { + "name": "pca10056", + "steps": [ + { + "type": "configure", + "name": "pca10056" + }, + { + "type": "build", + "name": "pca10056" + } + ] + }, + { + "name": "pca10059", + "steps": [ + { + "type": "configure", + "name": "pca10059" + }, + { + "type": "build", + "name": "pca10059" + } + ] + }, + { + "name": "pca10095", + "steps": [ + { + "type": "configure", + "name": "pca10095" + }, + { + "type": "build", + "name": "pca10095" + } + ] + }, + { + "name": "pca10100", + "steps": [ + { + "type": "configure", + "name": "pca10100" + }, + { + "type": "build", + "name": "pca10100" + } + ] + }, + { + "name": "pico_sdk", + "steps": [ + { + "type": "configure", + "name": "pico_sdk" + }, + { + "type": "build", + "name": "pico_sdk" + } + ] + }, + { + "name": "portenta_c33", + "steps": [ + { + "type": "configure", + "name": "portenta_c33" + }, + { + "type": "build", + "name": "portenta_c33" + } + ] + }, + { + "name": "pybadge", + "steps": [ + { + "type": "configure", + "name": "pybadge" + }, + { + "type": "build", + "name": "pybadge" + } + ] + }, + { + "name": "pyboardv11", + "steps": [ + { + "type": "configure", + "name": "pyboardv11" + }, + { + "type": "build", + "name": "pyboardv11" + } + ] + }, + { + "name": "pyportal", + "steps": [ + { + "type": "configure", + "name": "pyportal" + }, + { + "type": "build", + "name": "pyportal" + } + ] + }, + { + "name": "qtpy", + "steps": [ + { + "type": "configure", + "name": "qtpy" + }, + { + "type": "build", + "name": "qtpy" + } + ] + }, + { + "name": "ra2a1_ek", + "steps": [ + { + "type": "configure", + "name": "ra2a1_ek" + }, + { + "type": "build", + "name": "ra2a1_ek" + } + ] + }, + { + "name": "ra4m1_ek", + "steps": [ + { + "type": "configure", + "name": "ra4m1_ek" + }, + { + "type": "build", + "name": "ra4m1_ek" + } + ] + }, + { + "name": "ra4m3_ek", + "steps": [ + { + "type": "configure", + "name": "ra4m3_ek" + }, + { + "type": "build", + "name": "ra4m3_ek" + } + ] + }, + { + "name": "ra6m1_ek", + "steps": [ + { + "type": "configure", + "name": "ra6m1_ek" + }, + { + "type": "build", + "name": "ra6m1_ek" + } + ] + }, + { + "name": "ra6m5_ek", + "steps": [ + { + "type": "configure", + "name": "ra6m5_ek" + }, + { + "type": "build", + "name": "ra6m5_ek" + } + ] + }, + { + "name": "ra8m1_ek", + "steps": [ + { + "type": "configure", + "name": "ra8m1_ek" + }, + { + "type": "build", + "name": "ra8m1_ek" + } + ] + }, + { + "name": "raspberry_pi_pico", + "steps": [ + { + "type": "configure", + "name": "raspberry_pi_pico" + }, + { + "type": "build", + "name": "raspberry_pi_pico" + } + ] + }, + { + "name": "raspberry_pi_pico2", + "steps": [ + { + "type": "configure", + "name": "raspberry_pi_pico2" + }, + { + "type": "build", + "name": "raspberry_pi_pico2" + } + ] + }, + { + "name": "raspberrypi_cm4", + "steps": [ + { + "type": "configure", + "name": "raspberrypi_cm4" + }, + { + "type": "build", + "name": "raspberrypi_cm4" + } + ] + }, + { + "name": "raspberrypi_zero", + "steps": [ + { + "type": "configure", + "name": "raspberrypi_zero" + }, + { + "type": "build", + "name": "raspberrypi_zero" + } + ] + }, + { + "name": "raspberrypi_zero2", + "steps": [ + { + "type": "configure", + "name": "raspberrypi_zero2" + }, + { + "type": "build", + "name": "raspberrypi_zero2" + } + ] + }, + { + "name": "samd11_xplained", + "steps": [ + { + "type": "configure", + "name": "samd11_xplained" + }, + { + "type": "build", + "name": "samd11_xplained" + } + ] + }, + { + "name": "same54_xplained", + "steps": [ + { + "type": "configure", + "name": "same54_xplained" + }, + { + "type": "build", + "name": "same54_xplained" + } + ] + }, + { + "name": "samg55_xplained", + "steps": [ + { + "type": "configure", + "name": "samg55_xplained" + }, + { + "type": "build", + "name": "samg55_xplained" + } + ] + }, + { + "name": "saml22_feather", + "steps": [ + { + "type": "configure", + "name": "saml22_feather" + }, + { + "type": "build", + "name": "saml22_feather" + } + ] + }, + { + "name": "seeeduino_xiao", + "steps": [ + { + "type": "configure", + "name": "seeeduino_xiao" + }, + { + "type": "build", + "name": "seeeduino_xiao" + } + ] + }, + { + "name": "sensorwatch_m0", + "steps": [ + { + "type": "configure", + "name": "sensorwatch_m0" + }, + { + "type": "build", + "name": "sensorwatch_m0" + } + ] + }, + { + "name": "sipeed_longan_nano", + "steps": [ + { + "type": "configure", + "name": "sipeed_longan_nano" + }, + { + "type": "build", + "name": "sipeed_longan_nano" + } + ] + }, + { + "name": "sparkfun_samd21_mini_usb", + "steps": [ + { + "type": "configure", + "name": "sparkfun_samd21_mini_usb" + }, + { + "type": "build", + "name": "sparkfun_samd21_mini_usb" + } + ] + }, + { + "name": "stlinkv3mini", + "steps": [ + { + "type": "configure", + "name": "stlinkv3mini" + }, + { + "type": "build", + "name": "stlinkv3mini" + } + ] + }, + { + "name": "stm32c071nucleo", + "steps": [ + { + "type": "configure", + "name": "stm32c071nucleo" + }, + { + "type": "build", + "name": "stm32c071nucleo" + } + ] + }, + { + "name": "stm32f070rbnucleo", + "steps": [ + { + "type": "configure", + "name": "stm32f070rbnucleo" + }, + { + "type": "build", + "name": "stm32f070rbnucleo" + } + ] + }, + { + "name": "stm32f072disco", + "steps": [ + { + "type": "configure", + "name": "stm32f072disco" + }, + { + "type": "build", + "name": "stm32f072disco" + } + ] + }, + { + "name": "stm32f072eval", + "steps": [ + { + "type": "configure", + "name": "stm32f072eval" + }, + { + "type": "build", + "name": "stm32f072eval" + } + ] + }, + { + "name": "stm32f103_bluepill", + "steps": [ + { + "type": "configure", + "name": "stm32f103_bluepill" + }, + { + "type": "build", + "name": "stm32f103_bluepill" + } + ] + }, + { + "name": "stm32f103_mini_2", + "steps": [ + { + "type": "configure", + "name": "stm32f103_mini_2" + }, + { + "type": "build", + "name": "stm32f103_mini_2" + } + ] + }, + { + "name": "stm32f103ze_iar", + "steps": [ + { + "type": "configure", + "name": "stm32f103ze_iar" + }, + { + "type": "build", + "name": "stm32f103ze_iar" + } + ] + }, + { + "name": "stm32f207nucleo", + "steps": [ + { + "type": "configure", + "name": "stm32f207nucleo" + }, + { + "type": "build", + "name": "stm32f207nucleo" + } + ] + }, + { + "name": "stm32f303disco", + "steps": [ + { + "type": "configure", + "name": "stm32f303disco" + }, + { + "type": "build", + "name": "stm32f303disco" + } + ] + }, + { + "name": "stm32f401blackpill", + "steps": [ + { + "type": "configure", + "name": "stm32f401blackpill" + }, + { + "type": "build", + "name": "stm32f401blackpill" + } + ] + }, + { + "name": "stm32f407blackvet", + "steps": [ + { + "type": "configure", + "name": "stm32f407blackvet" + }, + { + "type": "build", + "name": "stm32f407blackvet" + } + ] + }, + { + "name": "stm32f407disco", + "steps": [ + { + "type": "configure", + "name": "stm32f407disco" + }, + { + "type": "build", + "name": "stm32f407disco" + } + ] + }, + { + "name": "stm32f411blackpill", + "steps": [ + { + "type": "configure", + "name": "stm32f411blackpill" + }, + { + "type": "build", + "name": "stm32f411blackpill" + } + ] + }, + { + "name": "stm32f411disco", + "steps": [ + { + "type": "configure", + "name": "stm32f411disco" + }, + { + "type": "build", + "name": "stm32f411disco" + } + ] + }, + { + "name": "stm32f412disco", + "steps": [ + { + "type": "configure", + "name": "stm32f412disco" + }, + { + "type": "build", + "name": "stm32f412disco" + } + ] + }, + { + "name": "stm32f412nucleo", + "steps": [ + { + "type": "configure", + "name": "stm32f412nucleo" + }, + { + "type": "build", + "name": "stm32f412nucleo" + } + ] + }, + { + "name": "stm32f439nucleo", + "steps": [ + { + "type": "configure", + "name": "stm32f439nucleo" + }, + { + "type": "build", + "name": "stm32f439nucleo" + } + ] + }, + { + "name": "stm32f723disco", + "steps": [ + { + "type": "configure", + "name": "stm32f723disco" + }, + { + "type": "build", + "name": "stm32f723disco" + } + ] + }, + { + "name": "stm32f746disco", + "steps": [ + { + "type": "configure", + "name": "stm32f746disco" + }, + { + "type": "build", + "name": "stm32f746disco" + } + ] + }, + { + "name": "stm32f746nucleo", + "steps": [ + { + "type": "configure", + "name": "stm32f746nucleo" + }, + { + "type": "build", + "name": "stm32f746nucleo" + } + ] + }, + { + "name": "stm32f767nucleo", + "steps": [ + { + "type": "configure", + "name": "stm32f767nucleo" + }, + { + "type": "build", + "name": "stm32f767nucleo" + } + ] + }, + { + "name": "stm32f769disco", + "steps": [ + { + "type": "configure", + "name": "stm32f769disco" + }, + { + "type": "build", + "name": "stm32f769disco" + } + ] + }, + { + "name": "stm32g0b1nucleo", + "steps": [ + { + "type": "configure", + "name": "stm32g0b1nucleo" + }, + { + "type": "build", + "name": "stm32g0b1nucleo" + } + ] + }, + { + "name": "stm32g474nucleo", + "steps": [ + { + "type": "configure", + "name": "stm32g474nucleo" + }, + { + "type": "build", + "name": "stm32g474nucleo" + } + ] + }, + { + "name": "stm32g491nucleo", + "steps": [ + { + "type": "configure", + "name": "stm32g491nucleo" + }, + { + "type": "build", + "name": "stm32g491nucleo" + } + ] + }, + { + "name": "stm32h503nucleo", + "steps": [ + { + "type": "configure", + "name": "stm32h503nucleo" + }, + { + "type": "build", + "name": "stm32h503nucleo" + } + ] + }, + { + "name": "stm32h563nucleo", + "steps": [ + { + "type": "configure", + "name": "stm32h563nucleo" + }, + { + "type": "build", + "name": "stm32h563nucleo" + } + ] + }, + { + "name": "stm32h573i_dk", + "steps": [ + { + "type": "configure", + "name": "stm32h573i_dk" + }, + { + "type": "build", + "name": "stm32h573i_dk" + } + ] + }, + { + "name": "stm32h723nucleo", + "steps": [ + { + "type": "configure", + "name": "stm32h723nucleo" + }, + { + "type": "build", + "name": "stm32h723nucleo" + } + ] + }, + { + "name": "stm32h743eval", + "steps": [ + { + "type": "configure", + "name": "stm32h743eval" + }, + { + "type": "build", + "name": "stm32h743eval" + } + ] + }, + { + "name": "stm32h743nucleo", + "steps": [ + { + "type": "configure", + "name": "stm32h743nucleo" + }, + { + "type": "build", + "name": "stm32h743nucleo" + } + ] + }, + { + "name": "stm32h745disco", + "steps": [ + { + "type": "configure", + "name": "stm32h745disco" + }, + { + "type": "build", + "name": "stm32h745disco" + } + ] + }, + { + "name": "stm32h750_weact", + "steps": [ + { + "type": "configure", + "name": "stm32h750_weact" + }, + { + "type": "build", + "name": "stm32h750_weact" + } + ] + }, + { + "name": "stm32h750bdk", + "steps": [ + { + "type": "configure", + "name": "stm32h750bdk" + }, + { + "type": "build", + "name": "stm32h750bdk" + } + ] + }, + { + "name": "stm32h7s3nucleo", + "steps": [ + { + "type": "configure", + "name": "stm32h7s3nucleo" + }, + { + "type": "build", + "name": "stm32h7s3nucleo" + } + ] + }, + { + "name": "stm32l052dap52", + "steps": [ + { + "type": "configure", + "name": "stm32l052dap52" + }, + { + "type": "build", + "name": "stm32l052dap52" + } + ] + }, + { + "name": "stm32l0538disco", + "steps": [ + { + "type": "configure", + "name": "stm32l0538disco" + }, + { + "type": "build", + "name": "stm32l0538disco" + } + ] + }, + { + "name": "stm32l412nucleo", + "steps": [ + { + "type": "configure", + "name": "stm32l412nucleo" + }, + { + "type": "build", + "name": "stm32l412nucleo" + } + ] + }, + { + "name": "stm32l476disco", + "steps": [ + { + "type": "configure", + "name": "stm32l476disco" + }, + { + "type": "build", + "name": "stm32l476disco" + } + ] + }, + { + "name": "stm32l4p5nucleo", + "steps": [ + { + "type": "configure", + "name": "stm32l4p5nucleo" + }, + { + "type": "build", + "name": "stm32l4p5nucleo" + } + ] + }, + { + "name": "stm32l4r5nucleo", + "steps": [ + { + "type": "configure", + "name": "stm32l4r5nucleo" + }, + { + "type": "build", + "name": "stm32l4r5nucleo" + } + ] + }, + { + "name": "stm32u545nucleo", + "steps": [ + { + "type": "configure", + "name": "stm32u545nucleo" + }, + { + "type": "build", + "name": "stm32u545nucleo" + } + ] + }, + { + "name": "stm32u575eval", + "steps": [ + { + "type": "configure", + "name": "stm32u575eval" + }, + { + "type": "build", + "name": "stm32u575eval" + } + ] + }, + { + "name": "stm32u575nucleo", + "steps": [ + { + "type": "configure", + "name": "stm32u575nucleo" + }, + { + "type": "build", + "name": "stm32u575nucleo" + } + ] + }, + { + "name": "stm32u5a5nucleo", + "steps": [ + { + "type": "configure", + "name": "stm32u5a5nucleo" + }, + { + "type": "build", + "name": "stm32u5a5nucleo" + } + ] + }, + { + "name": "stm32wb55nucleo", + "steps": [ + { + "type": "configure", + "name": "stm32wb55nucleo" + }, + { + "type": "build", + "name": "stm32wb55nucleo" + } + ] + }, + { + "name": "teensy_35", + "steps": [ + { + "type": "configure", + "name": "teensy_35" + }, + { + "type": "build", + "name": "teensy_35" + } + ] + }, + { + "name": "teensy_40", + "steps": [ + { + "type": "configure", + "name": "teensy_40" + }, + { + "type": "build", + "name": "teensy_40" + } + ] + }, + { + "name": "teensy_41", + "steps": [ + { + "type": "configure", + "name": "teensy_41" + }, + { + "type": "build", + "name": "teensy_41" + } + ] + }, + { + "name": "trinket_m0", + "steps": [ + { + "type": "configure", + "name": "trinket_m0" + }, + { + "type": "build", + "name": "trinket_m0" + } + ] + }, + { + "name": "uno_r4", + "steps": [ + { + "type": "configure", + "name": "uno_r4" + }, + { + "type": "build", + "name": "uno_r4" + } + ] + }, + { + "name": "waveshare_openh743i", + "steps": [ + { + "type": "configure", + "name": "waveshare_openh743i" + }, + { + "type": "build", + "name": "waveshare_openh743i" + } + ] + }, + { + "name": "xmc4500_relax", + "steps": [ + { + "type": "configure", + "name": "xmc4500_relax" + }, + { + "type": "build", + "name": "xmc4500_relax" + } + ] + }, + { + "name": "xmc4700_relax", + "steps": [ + { + "type": "configure", + "name": "xmc4700_relax" + }, + { + "type": "build", + "name": "xmc4700_relax" + } + ] + } + ] +} diff --git a/hw/bsp/board.c b/hw/bsp/board.c index 5bcdb7f15..1ba5a1b9d 100644 --- a/hw/bsp/board.c +++ b/hw/bsp/board.c @@ -60,19 +60,29 @@ int sys_read(int fhdl, char *buf, size_t count) { int rd = (int) SEGGER_RTT_Read(0, buf, count); return (rd > 0) ? rd : -1; } - #endif #elif defined(LOGGER_SWO) -// Logging with SWO for ARM Cortex -#include "board_mcu.h" +#define ITM_BASE 0xE0000000 +#define ITM_STIM0 (*((volatile uint8_t*)(ITM_BASE + 0))) +#define ITM_TER *((volatile uint32_t*)(ITM_BASE + 0xE00)) +#define ITM_TCR *((volatile uint32_t*)(ITM_BASE + 0xE80)) + +#define ITM_TCR_ITMENA (1 << 0) + +// Logging with SWO for ARM Cortex-M int sys_write (int fhdl, const char *buf, size_t count) { (void) fhdl; uint8_t const* buf8 = (uint8_t const*) buf; - for(size_t i=0; i 0) ? (int) c : (-1); } +void board_putchar(int c) { + sys_write(0, (const char*)&c, 1); +} uint32_t tusb_time_millis_api(void) { return board_millis(); @@ -146,7 +159,7 @@ uint32_t tusb_time_millis_api(void) { //-------------------------------------------------------------------- // FreeRTOS hooks //-------------------------------------------------------------------- -#if CFG_TUSB_OS == OPT_OS_FREERTOS && !TUSB_MCU_VENDOR_ESPRESSIF +#if CFG_TUSB_OS == OPT_OS_FREERTOS && !defined(ESP_PLATFORM) #include "FreeRTOS.h" #include "task.h" @@ -228,5 +241,4 @@ void vApplicationSetupTimerInterrupt(void) { } #endif - #endif diff --git a/hw/bsp/board_api.h b/hw/bsp/board_api.h index eaee1ee97..328fe9363 100644 --- a/hw/bsp/board_api.h +++ b/hw/bsp/board_api.h @@ -38,22 +38,24 @@ extern "C" { #include "tusb.h" -#if CFG_TUSB_OS == OPT_OS_FREERTOS -#if TUSB_MCU_VENDOR_ESPRESSIF - // ESP-IDF need "freertos/" prefix in include path. - // CFG_TUSB_OS_INC_PATH should be defined accordingly. - #include "freertos/FreeRTOS.h" - #include "freertos/semphr.h" - #include "freertos/queue.h" - #include "freertos/task.h" - #include "freertos/timers.h" -#else - #include "FreeRTOS.h" - #include "semphr.h" - #include "queue.h" - #include "task.h" - #include "timers.h" -#endif +#if CFG_TUSB_OS == OPT_OS_ZEPHYR + #include +#elif CFG_TUSB_OS == OPT_OS_FREERTOS + #ifdef ESP_PLATFORM + // ESP-IDF need "freertos/" prefix in include path. + // CFG_TUSB_OS_INC_PATH should be defined accordingly. + #include "freertos/FreeRTOS.h" + #include "freertos/semphr.h" + #include "freertos/queue.h" + #include "freertos/task.h" + #include "freertos/timers.h" + #else + #include "FreeRTOS.h" + #include "semphr.h" + #include "queue.h" + #include "task.h" + #include "timers.h" + #endif #endif // Define the default baudrate @@ -124,6 +126,10 @@ static inline uint32_t board_millis(void) { // Implement your own board_millis() in any of .c file uint32_t board_millis(void); +#elif CFG_TUSB_OS == OPT_OS_ZEPHYR +static inline uint32_t board_millis(void) { + return k_uptime_get_32(); +} #else #error "board_millis() is not implemented for this OS" #endif @@ -189,6 +195,7 @@ static inline void board_delay(uint32_t ms) { // stdio getchar() is blocking, this is non-blocking version int board_getchar(void); +void board_putchar(int c); #ifdef __cplusplus } diff --git a/hw/bsp/board_mcu.h b/hw/bsp/board_mcu.h deleted file mode 100644 index e720cd747..000000000 --- a/hw/bsp/board_mcu.h +++ /dev/null @@ -1,193 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2020, Ha Thach (tinyusb.org) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - * This file is part of the TinyUSB stack. - */ - - -#ifndef BOARD_MCU_H_ -#define BOARD_MCU_H_ - -#include "tusb_option.h" - -//--------------------------------------------------------------------+ -// Low Level MCU header include. Example should be -// platform independent and mostly doesn't need to include this file. -// However there are still certain situation where this file is needed: -// - FreeRTOSConfig.h to set up correct clock and NVIC interrupts for ARM Cortex -// - SWO logging for Cortex M with ITM_SendChar() / ITM_ReceiveChar() -//--------------------------------------------------------------------+ - -// Include order follows OPT_MCU_ number -#if TU_CHECK_MCU(OPT_MCU_LPC11UXX, OPT_MCU_LPC13XX, OPT_MCU_LPC15XX) || \ - TU_CHECK_MCU(OPT_MCU_LPC175X_6X, OPT_MCU_LPC177X_8X, OPT_MCU_LPC18XX) || \ - TU_CHECK_MCU(OPT_MCU_LPC40XX, OPT_MCU_LPC43XX) - #include "chip.h" - -#elif TU_CHECK_MCU(OPT_MCU_LPC51UXX, OPT_MCU_LPC54XXX, OPT_MCU_LPC55XX, OPT_MCU_MCXN9) - #include "fsl_device_registers.h" - -#elif TU_CHECK_MCU(OPT_MCU_KINETIS_KL, OPT_MCU_KINETIS_K32L, OPT_MCU_KINETIS_K) - #include "fsl_device_registers.h" - -#elif CFG_TUSB_MCU == OPT_MCU_NRF5X - #include "nrf.h" - -#elif CFG_TUSB_MCU == OPT_MCU_SAMD11 || CFG_TUSB_MCU == OPT_MCU_SAMD21 || \ - CFG_TUSB_MCU == OPT_MCU_SAMD51 || CFG_TUSB_MCU == OPT_MCU_SAME5X || \ - CFG_TUSB_MCU == OPT_MCU_SAML22 || CFG_TUSB_MCU == OPT_MCU_SAML21 - #include "sam.h" - -#elif CFG_TUSB_MCU == OPT_MCU_SAMG - #undef LITTLE_ENDIAN // hack to suppress "LITTLE_ENDIAN" redefined - #include "sam.h" - -#elif CFG_TUSB_MCU == OPT_MCU_STM32F0 - #include "stm32f0xx.h" - -#elif CFG_TUSB_MCU == OPT_MCU_STM32F1 - #include "stm32f1xx.h" - -#elif CFG_TUSB_MCU == OPT_MCU_STM32F2 - #include "stm32f2xx.h" - -#elif CFG_TUSB_MCU == OPT_MCU_STM32F3 - #include "stm32f3xx.h" - -#elif CFG_TUSB_MCU == OPT_MCU_STM32F4 - #include "stm32f4xx.h" - -#elif CFG_TUSB_MCU == OPT_MCU_STM32F7 - #include "stm32f7xx.h" - -#elif CFG_TUSB_MCU == OPT_MCU_STM32G4 - #include "stm32g4xx.h" - -#elif CFG_TUSB_MCU == OPT_MCU_STM32H5 - #include "stm32h5xx.h" - -#elif CFG_TUSB_MCU == OPT_MCU_STM32H7 - #include "stm32h7xx.h" - -#elif CFG_TUSB_MCU == OPT_MCU_STM32L0 - #include "stm32l0xx.h" - -#elif CFG_TUSB_MCU == OPT_MCU_STM32L1 - #include "stm32l1xx.h" - -#elif CFG_TUSB_MCU == OPT_MCU_STM32L4 - #include "stm32l4xx.h" - -#elif CFG_TUSB_MCU == OPT_MCU_STM32WB - #include "stm32wbxx.h" - -#elif CFG_TUSB_MCU == OPT_MCU_STM32U5 - #include "stm32u5xx.h" - -#elif CFG_TUSB_MCU == OPT_MCU_STM32G0 - #include "stm32g0xx.h" - -#elif CFG_TUSB_MCU == OPT_MCU_STM32C0 - #include "stm32c0xx.h" - -#elif CFG_TUSB_MCU == OPT_MCU_CXD56 - // no header needed - -#elif CFG_TUSB_MCU == OPT_MCU_MSP430x5xx - #include "msp430.h" - -#elif CFG_TUSB_MCU == OPT_MCU_MSP432E4 - #include "msp.h" - -#elif CFG_TUSB_MCU == OPT_MCU_VALENTYUSB_EPTRI - // no header needed - -#elif CFG_TUSB_MCU == OPT_MCU_MIMXRT1XXX - #include "fsl_device_registers.h" - -#elif CFG_TUSB_MCU == OPT_MCU_NUC120 - #include "NUC100Series.h" - -#elif CFG_TUSB_MCU == OPT_MCU_NUC121 || CFG_TUSB_MCU == OPT_MCU_NUC126 - #include "NuMicro.h" - -#elif CFG_TUSB_MCU == OPT_MCU_NUC505 - #include "NUC505Series.h" - -#elif CFG_TUSB_MCU == OPT_MCU_ESP32S2 - // no header needed - -#elif CFG_TUSB_MCU == OPT_MCU_ESP32S3 - // no header needed - -#elif CFG_TUSB_MCU == OPT_MCU_DA1469X - #include "DA1469xAB.h" - -#elif CFG_TUSB_MCU == OPT_MCU_RP2040 - #include "pico.h" - -#elif CFG_TUSB_MCU == OPT_MCU_EFM32GG - #include "em_device.h" - -#elif CFG_TUSB_MCU == OPT_MCU_RX63X || CFG_TUSB_MCU == OPT_MCU_RX65X - // no header needed - -#elif CFG_TUSB_MCU == OPT_MCU_RAXXX - #include "bsp_api.h" - -#elif CFG_TUSB_MCU == OPT_MCU_GD32VF103 - #include "gd32vf103.h" - -#elif CFG_TUSB_MCU == OPT_MCU_MM32F327X - #include "mm32_device.h" - -#elif CFG_TUSB_MCU == OPT_MCU_XMC4000 - #include "xmc_device.h" - -#elif CFG_TUSB_MCU == OPT_MCU_TM4C123 - #include "TM4C123.h" - -#elif CFG_TUSB_MCU == OPT_MCU_CH32F20X - #include "ch32f20x.h" - -#elif TU_CHECK_MCU(OPT_MCU_BCM2711, OPT_MCU_BCM2835, OPT_MCU_BCM2837) - // no header needed - -#elif CFG_TUSB_MCU == OPT_MCU_MAX32690 - #include "max32690.h" - -#elif CFG_TUSB_MCU == OPT_MCU_MAX32650 - #include "max32650.h" - -#elif CFG_TUSB_MCU == OPT_MCU_MAX32666 - #include "max32665.h" - -#elif CFG_TUSB_MCU == OPT_MCU_MAX78002 - #include "max78002.h" - -#else - #error "Missing MCU header" -#endif - - -#endif /* BOARD_MCU_H_ */ diff --git a/hw/bsp/broadcom_32bit/boards/raspberrypi_zero/board.cmake b/hw/bsp/broadcom_32bit/boards/raspberrypi_zero/board.cmake index 2b8cc19e0..616a83fe2 100644 --- a/hw/bsp/broadcom_32bit/boards/raspberrypi_zero/board.cmake +++ b/hw/bsp/broadcom_32bit/boards/raspberrypi_zero/board.cmake @@ -1,4 +1,4 @@ -set(CMAKE_SYSTEM_PROCESSOR arm1176jzf-s CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU arm1176jzf-s CACHE INTERNAL "System Processor") #set(SUFFIX "") function(update_board TARGET) diff --git a/hw/bsp/broadcom_32bit/boards/raspberrypi_zero/board.h b/hw/bsp/broadcom_32bit/boards/raspberrypi_zero/board.h index 84a106346..40a9dd198 100644 --- a/hw/bsp/broadcom_32bit/boards/raspberrypi_zero/board.h +++ b/hw/bsp/broadcom_32bit/boards/raspberrypi_zero/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Raspberry Pi Zero + url: https://www.raspberrypi.org/products/raspberry-pi-zero/ +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/broadcom_32bit/family.c b/hw/bsp/broadcom_32bit/family.c index 0062e2e83..f8f3b0b70 100644 --- a/hw/bsp/broadcom_32bit/family.c +++ b/hw/bsp/broadcom_32bit/family.c @@ -24,6 +24,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: Raspberry Pi +*/ + #include "bsp/board_api.h" #include "board.h" diff --git a/hw/bsp/broadcom_32bit/family.cmake b/hw/bsp/broadcom_32bit/family.cmake index 93e7d3545..5e57d8b1e 100644 --- a/hw/bsp/broadcom_32bit/family.cmake +++ b/hw/bsp/broadcom_32bit/family.cmake @@ -94,17 +94,17 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_BCM2835 ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC + family_add_tinyusb(${TARGET} OPT_MCU_BCM2835) + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/synopsys/dwc2/dcd_dwc2.c ${TOP}/src/portable/synopsys/dwc2/hcd_dwc2.c ${TOP}/src/portable/synopsys/dwc2/dwc2_common.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) # Flashing + family_add_bin_hex(${TARGET}) family_flash_jlink(${TARGET}) endfunction() diff --git a/hw/bsp/broadcom_32bit/family.mk b/hw/bsp/broadcom_32bit/family.mk index a282e9961..9d4a3b76c 100644 --- a/hw/bsp/broadcom_32bit/family.mk +++ b/hw/bsp/broadcom_32bit/family.mk @@ -15,7 +15,7 @@ CFLAGS += \ CROSS_COMPILE = arm-none-eabi- # mcu driver cause following warnings -CFLAGS += -Wno-error=cast-qual -Wno-error=redundant-decls +CFLAGS_GCC += -Wno-error=cast-qual -Wno-error=redundant-decls SRC_C += \ src/portable/synopsys/dwc2/dcd_dwc2.c \ diff --git a/hw/bsp/broadcom_64bit/boards/raspberrypi_cm4/board.cmake b/hw/bsp/broadcom_64bit/boards/raspberrypi_cm4/board.cmake index 919068f1d..6f1fc0225 100644 --- a/hw/bsp/broadcom_64bit/boards/raspberrypi_cm4/board.cmake +++ b/hw/bsp/broadcom_64bit/boards/raspberrypi_cm4/board.cmake @@ -1,4 +1,4 @@ -set(CMAKE_SYSTEM_PROCESSOR cortex-a72 CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU cortex-a72 CACHE INTERNAL "System Processor") set(BCM_VERSION 2711) function(update_board TARGET) diff --git a/hw/bsp/broadcom_64bit/boards/raspberrypi_cm4/board.h b/hw/bsp/broadcom_64bit/boards/raspberrypi_cm4/board.h index 84a106346..cadad2b27 100644 --- a/hw/bsp/broadcom_64bit/boards/raspberrypi_cm4/board.h +++ b/hw/bsp/broadcom_64bit/boards/raspberrypi_cm4/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Raspberry CM4 + url: https://www.raspberrypi.org/products/compute-module-4 +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/broadcom_64bit/boards/raspberrypi_zero2/board.cmake b/hw/bsp/broadcom_64bit/boards/raspberrypi_zero2/board.cmake index 85f84e947..80747363a 100644 --- a/hw/bsp/broadcom_64bit/boards/raspberrypi_zero2/board.cmake +++ b/hw/bsp/broadcom_64bit/boards/raspberrypi_zero2/board.cmake @@ -1,4 +1,4 @@ -set(CMAKE_SYSTEM_PROCESSOR cortex-a53 CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU cortex-a53 CACHE INTERNAL "System Processor") set(BCM_VERSION 2837) function(update_board TARGET) diff --git a/hw/bsp/broadcom_64bit/boards/raspberrypi_zero2/board.h b/hw/bsp/broadcom_64bit/boards/raspberrypi_zero2/board.h index 84a106346..e6caa0294 100644 --- a/hw/bsp/broadcom_64bit/boards/raspberrypi_zero2/board.h +++ b/hw/bsp/broadcom_64bit/boards/raspberrypi_zero2/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Raspberry Zero2 + url: https://www.raspberrypi.org/products/raspberry-pi-zero-2-w +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/broadcom_64bit/family.c b/hw/bsp/broadcom_64bit/family.c index 0062e2e83..f8f3b0b70 100644 --- a/hw/bsp/broadcom_64bit/family.c +++ b/hw/bsp/broadcom_64bit/family.c @@ -24,6 +24,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: Raspberry Pi +*/ + #include "bsp/board_api.h" #include "board.h" diff --git a/hw/bsp/broadcom_64bit/family.cmake b/hw/bsp/broadcom_64bit/family.cmake index d790944bc..1a088c2c0 100644 --- a/hw/bsp/broadcom_64bit/family.cmake +++ b/hw/bsp/broadcom_64bit/family.cmake @@ -101,17 +101,17 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_BCM${BCM_VERSION} ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC + family_add_tinyusb(${TARGET} OPT_MCU_BCM${BCM_VERSION}) + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/synopsys/dwc2/dcd_dwc2.c ${TOP}/src/portable/synopsys/dwc2/hcd_dwc2.c ${TOP}/src/portable/synopsys/dwc2/dwc2_common.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) # Flashing + family_add_bin_hex(${TARGET}) family_flash_jlink(${TARGET}) endfunction() diff --git a/hw/bsp/broadcom_64bit/family.mk b/hw/bsp/broadcom_64bit/family.mk index 37d381f9f..1ce80e22b 100644 --- a/hw/bsp/broadcom_64bit/family.mk +++ b/hw/bsp/broadcom_64bit/family.mk @@ -14,7 +14,7 @@ CFLAGS += \ CROSS_COMPILE = aarch64-none-elf- # mcu driver cause following warnings -CFLAGS += -Wno-error=cast-qual -Wno-error=redundant-decls +CFLAGS_GCC += -Wno-error=cast-qual -Wno-error=redundant-decls SRC_C += \ src/portable/synopsys/dwc2/dcd_dwc2.c \ diff --git a/hw/bsp/brtmm90x/boards/mm900evxb/board.h b/hw/bsp/brtmm90x/boards/mm900evxb/board.h index 771779108..623033c2c 100644 --- a/hw/bsp/brtmm90x/boards/mm900evxb/board.h +++ b/hw/bsp/brtmm90x/boards/mm900evxb/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: MM900EVxB + url: https://brtchip.com/product/mm900ev1b +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/brtmm90x/family.c b/hw/bsp/brtmm90x/family.c index 4d81e7d52..15ff4b8ee 100644 --- a/hw/bsp/brtmm90x/family.c +++ b/hw/bsp/brtmm90x/family.c @@ -24,6 +24,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: Bridgetek +*/ + #include "bsp/board_api.h" #include "board.h" diff --git a/hw/bsp/brtmm90x/family.mk b/hw/bsp/brtmm90x/family.mk index 6df0bfdfe..2de4dc760 100644 --- a/hw/bsp/brtmm90x/family.mk +++ b/hw/bsp/brtmm90x/family.mk @@ -13,7 +13,6 @@ else # The submodule BRTSG-FOSS/ft90x-sdk contains header files and source # code for the Bridgetek SDK. This can be used instead of the prebuilt # library. -DEPS_SUBMODULES += hw/mcu/bridgetek/ft9xx/ft90x-sdk # The SDK can be used to load specific files from the Bridgetek SDK. FT9XX_SDK = hw/mcu/bridgetek/ft9xx/ft90x-sdk/Source INC += "$(TOP)/$(FT9XX_SDK)/include" diff --git a/hw/bsp/ch32f20x/boards/ch32f205r-r0/board.h b/hw/bsp/ch32f20x/boards/ch32f205r-r0/board.h index d5849bddb..b855804a9 100644 --- a/hw/bsp/ch32f20x/boards/ch32f205r-r0/board.h +++ b/hw/bsp/ch32f20x/boards/ch32f205r-r0/board.h @@ -22,6 +22,11 @@ * THE SOFTWARE. */ +/* metadata: + name: CH32F205r-r0 + url: https://github.com/openwch/ch32f20x +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/ch32f20x/family.c b/hw/bsp/ch32f20x/family.c index 9717832d6..7fef71d47 100644 --- a/hw/bsp/ch32f20x/family.c +++ b/hw/bsp/ch32f20x/family.c @@ -24,6 +24,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: WCH +*/ + #include "stdio.h" #include "debug_uart.h" diff --git a/hw/bsp/ch32f20x/family.mk b/hw/bsp/ch32f20x/family.mk index c08451b9c..2ff9f79e3 100644 --- a/hw/bsp/ch32f20x/family.mk +++ b/hw/bsp/ch32f20x/family.mk @@ -1,6 +1,5 @@ # Submodules CH32F20X_SDK = hw/mcu/wch/ch32f20x -DEPS_SUBMODULES += $(CH32F20X_SDK) # WCH-SDK paths CH32F20X_SDK_SRC = $(CH32F20X_SDK)/EVT/EXAM/SRC diff --git a/hw/bsp/ch32v10x/boards/ch32v103r_r1_1v0/board.h b/hw/bsp/ch32v10x/boards/ch32v103r_r1_1v0/board.h index 3b1187c3a..1fde4244c 100644 --- a/hw/bsp/ch32v10x/boards/ch32v103r_r1_1v0/board.h +++ b/hw/bsp/ch32v10x/boards/ch32v103r_r1_1v0/board.h @@ -1,3 +1,8 @@ +/* metadata: + name: CH32V103R-R1-1v1 + url: https://github.com/openwch/ch32v103/tree/main/SCHPCB/CH32V103R-R1-1v1 +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/ch32v10x/family.c b/hw/bsp/ch32v10x/family.c index 15f754e11..f25102494 100644 --- a/hw/bsp/ch32v10x/family.c +++ b/hw/bsp/ch32v10x/family.c @@ -1,3 +1,7 @@ +/* metadata: + manufacturer: WCH +*/ + #include // https://github.com/openwch/ch32v307/pull/90 diff --git a/hw/bsp/ch32v10x/family.cmake b/hw/bsp/ch32v10x/family.cmake index c0af0ef44..a73898050 100644 --- a/hw/bsp/ch32v10x/family.cmake +++ b/hw/bsp/ch32v10x/family.cmake @@ -9,7 +9,7 @@ set(SDK_SRC_DIR ${SDK_DIR}/EVT/EXAM/SRC) include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) # toolchain set up -set(CMAKE_SYSTEM_PROCESSOR rv32imac-ilp32 CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU rv32imac-ilp32 CACHE INTERNAL "System Processor") set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/riscv_${TOOLCHAIN}.cmake) set(FAMILY_MCUS CH32V103 CACHE INTERNAL "") @@ -98,15 +98,14 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_CH32V103 ${RTOS}) + family_add_tinyusb(${TARGET} OPT_MCU_CH32V103) - target_sources(${TARGET}-tinyusb PUBLIC + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/wch/dcd_ch32_usbfs.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) # Flashing family_add_bin_hex(${TARGET}) diff --git a/hw/bsp/ch32v20x/boards/ch32v203c_r0_1v0/board.h b/hw/bsp/ch32v20x/boards/ch32v203c_r0_1v0/board.h index 692cf11bf..56f49205c 100644 --- a/hw/bsp/ch32v20x/boards/ch32v203c_r0_1v0/board.h +++ b/hw/bsp/ch32v20x/boards/ch32v203c_r0_1v0/board.h @@ -1,3 +1,8 @@ +/* metadata: + name: CH32V203C-R0-1v0 + url: https://github.com/openwch/ch32v20x/tree/main/SCHPCB/CH32V203C-R0 +*/ + #ifndef BOARD_H_ #define BOARD_H_ @@ -8,6 +13,8 @@ extern "C" { #define LED_PORT GPIOA #define LED_PIN GPIO_Pin_0 #define LED_STATE_ON 0 +#define LED_CLOCK_EN() RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE) +#define LED_MODE GPIO_Mode_Out_OD #define UART_DEV USART1 #define UART_CLOCK_EN() RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE) diff --git a/hw/bsp/ch32v20x/boards/ch32v203g_r0_1v0/board.h b/hw/bsp/ch32v20x/boards/ch32v203g_r0_1v0/board.h index 783831edd..4a040e0df 100644 --- a/hw/bsp/ch32v20x/boards/ch32v203g_r0_1v0/board.h +++ b/hw/bsp/ch32v20x/boards/ch32v203g_r0_1v0/board.h @@ -1,3 +1,8 @@ +/* metadata: + name: CH32V203G-R0-1v0 + url: https://github.com/openwch/ch32v20x/tree/main/SCHPCB/CH32V203C-R0 +*/ + #ifndef BOARD_H_ #define BOARD_H_ @@ -8,6 +13,8 @@ extern "C" { #define LED_PORT GPIOA #define LED_PIN GPIO_Pin_0 #define LED_STATE_ON 0 +#define LED_CLOCK_EN() RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE) +#define LED_MODE GPIO_Mode_Out_OD #define UART_DEV USART2 #define UART_CLOCK_EN() RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE) diff --git a/hw/bsp/ch32v20x/boards/nanoch32v203/board.h b/hw/bsp/ch32v20x/boards/nanoch32v203/board.h index 64eaf931e..63237861c 100644 --- a/hw/bsp/ch32v20x/boards/nanoch32v203/board.h +++ b/hw/bsp/ch32v20x/boards/nanoch32v203/board.h @@ -1,3 +1,8 @@ +/* metadata: + name: nanoCH32V203 + url: https://github.com/wuxx/nanoCH32V203 +*/ + #ifndef BOARD_H_ #define BOARD_H_ @@ -8,6 +13,8 @@ extern "C" { #define LED_PORT GPIOA #define LED_PIN GPIO_Pin_15 #define LED_STATE_ON 0 +#define LED_CLOCK_EN() RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE) +#define LED_MODE GPIO_Mode_Out_OD #define UART_DEV USART1 #define UART_CLOCK_EN() RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE) diff --git a/hw/bsp/ch32v20x/family.c b/hw/bsp/ch32v20x/family.c index 43dd7e032..21ed94b0a 100644 --- a/hw/bsp/ch32v20x/family.c +++ b/hw/bsp/ch32v20x/family.c @@ -1,3 +1,7 @@ +/* metadata: +manufacturer: WCH +*/ + #include // https://github.com/openwch/ch32v307/pull/90 @@ -92,11 +96,11 @@ void board_init(void) { SysTick_Config(SystemCoreClock / 1000); #endif - RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE); + LED_CLOCK_EN(); GPIO_InitTypeDef GPIO_InitStructure = { .GPIO_Pin = LED_PIN, - .GPIO_Mode = GPIO_Mode_Out_OD, + .GPIO_Mode = LED_MODE, .GPIO_Speed = GPIO_Speed_10MHz, }; GPIO_Init(LED_PORT, &GPIO_InitStructure); diff --git a/hw/bsp/ch32v20x/family.cmake b/hw/bsp/ch32v20x/family.cmake index 380ef190d..a5976e0ea 100644 --- a/hw/bsp/ch32v20x/family.cmake +++ b/hw/bsp/ch32v20x/family.cmake @@ -9,7 +9,7 @@ set(SDK_SRC_DIR ${SDK_DIR}/EVT/EXAM/SRC) include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) # toolchain set up -set(CMAKE_SYSTEM_PROCESSOR rv32imac-ilp32 CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU rv32imac-ilp32 CACHE INTERNAL "System Processor") set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/riscv_${TOOLCHAIN}.cmake) set(FAMILY_MCUS CH32V20X CACHE INTERNAL "") @@ -123,16 +123,15 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_CH32V20X ${RTOS}) + family_add_tinyusb(${TARGET} OPT_MCU_CH32V20X) - target_sources(${TARGET}-tinyusb PUBLIC + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/wch/dcd_ch32_usbfs.c ${TOP}/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) # Flashing family_add_bin_hex(${TARGET}) diff --git a/hw/bsp/ch32v307/boards/ch32v307v_r1_1v0/board.h b/hw/bsp/ch32v307/boards/ch32v307v_r1_1v0/board.h index 7b488096e..491347034 100644 --- a/hw/bsp/ch32v307/boards/ch32v307v_r1_1v0/board.h +++ b/hw/bsp/ch32v307/boards/ch32v307v_r1_1v0/board.h @@ -22,6 +22,11 @@ * THE SOFTWARE. */ +/* metadata: + name: CH32V307V-R1-1v0 + url: https://github.com/openwch/ch32v307/tree/main/SCHPCB/CH32V307V-R1-1v0 +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/ch32v307/family.c b/hw/bsp/ch32v307/family.c index adf2dbea5..48eb8a38c 100644 --- a/hw/bsp/ch32v307/family.c +++ b/hw/bsp/ch32v307/family.c @@ -24,6 +24,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: WCH +*/ + #include "stdio.h" // https://github.com/openwch/ch32v307/pull/90 diff --git a/hw/bsp/ch32v307/family.cmake b/hw/bsp/ch32v307/family.cmake index d603af62d..446e850c5 100644 --- a/hw/bsp/ch32v307/family.cmake +++ b/hw/bsp/ch32v307/family.cmake @@ -8,7 +8,7 @@ set(SDK_SRC_DIR ${SDK_DIR}/EVT/EXAM/SRC) include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) # toolchain set up -set(CMAKE_SYSTEM_PROCESSOR rv32imac-ilp32 CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU rv32imac-ilp32 CACHE INTERNAL "System Processor") set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/riscv_${TOOLCHAIN}.cmake) set(FAMILY_MCUS CH32V307 CACHE INTERNAL "") @@ -113,15 +113,14 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_CH32V307 ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC + family_add_tinyusb(${TARGET} OPT_MCU_CH32V307) + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/wch/dcd_ch32_usbhs.c ${TOP}/src/portable/wch/dcd_ch32_usbfs.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) # Flashing family_add_bin_hex(${TARGET}) diff --git a/hw/bsp/da1469x/boards/da14695_dk_usb/board.h b/hw/bsp/da1469x/boards/da14695_dk_usb/board.h index 5efdd43e0..c0810c2b6 100644 --- a/hw/bsp/da1469x/boards/da14695_dk_usb/board.h +++ b/hw/bsp/da1469x/boards/da14695_dk_usb/board.h @@ -1,3 +1,8 @@ +/* metadata: + name: DA14695-00HQDEVKT-U + url: https://www.renesas.com/en/products/wireless-connectivity/bluetooth-low-energy/da14695-00hqdevkt-u-smartbond-da14695-bluetooth-low-energy-52-usb-development-kit +*/ + #ifndef BOARD_H #define BOARD_H diff --git a/hw/bsp/da1469x/boards/da1469x_dk_pro/board.h b/hw/bsp/da1469x/boards/da1469x_dk_pro/board.h index f969acf90..2b61e810e 100644 --- a/hw/bsp/da1469x/boards/da1469x_dk_pro/board.h +++ b/hw/bsp/da1469x/boards/da1469x_dk_pro/board.h @@ -1,3 +1,8 @@ +/* metadata: + name: DA1469x Development Kit Pro + url: https://lpccs-docs.renesas.com/um-b-090-da1469x_getting_started/DA1469x_The_hardware/DA1469x_The_hardware.html +*/ + #ifndef BOARD_H #define BOARD_H diff --git a/hw/bsp/da1469x/family.c b/hw/bsp/da1469x/family.c index 70bedf6d9..a64ffce67 100644 --- a/hw/bsp/da1469x/family.c +++ b/hw/bsp/da1469x/family.c @@ -24,6 +24,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: Renesas +*/ + #include "bsp/board_api.h" #include "board.h" #include diff --git a/hw/bsp/da1469x/family.cmake b/hw/bsp/da1469x/family.cmake index 8c89141fe..20d6cbc44 100644 --- a/hw/bsp/da1469x/family.cmake +++ b/hw/bsp/da1469x/family.cmake @@ -5,7 +5,7 @@ set(MCU_DIR ${TOP}/hw/mcu/dialog/da1469x) # include board specific include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) -set(CMAKE_SYSTEM_PROCESSOR cortex-m33-nodsp CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU cortex-m33-nodsp CACHE INTERNAL "System Processor") set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) set(FAMILY_MCUS DA1469X CACHE INTERNAL "") @@ -126,14 +126,13 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_DA1469X ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC + family_add_tinyusb(${TARGET} OPT_MCU_DA1469X) + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/dialog/da146xx/dcd_da146xx.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) # Flashing family_add_bin_hex(${TARGET}) diff --git a/hw/bsp/espressif/boards/adafruit_feather_esp32_v2/board.h b/hw/bsp/espressif/boards/adafruit_feather_esp32_v2/board.h index 0c53df06b..15e5091f9 100644 --- a/hw/bsp/espressif/boards/adafruit_feather_esp32_v2/board.h +++ b/hw/bsp/espressif/boards/adafruit_feather_esp32_v2/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Adafruit Feather ESP32 v2 + url: https://www.adafruit.com/product/5400 +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/espressif/boards/adafruit_feather_esp32c6/board.cmake b/hw/bsp/espressif/boards/adafruit_feather_esp32c6/board.cmake new file mode 100644 index 000000000..9adaefb17 --- /dev/null +++ b/hw/bsp/espressif/boards/adafruit_feather_esp32c6/board.cmake @@ -0,0 +1,3 @@ +# Apply board specific content here +set(IDF_TARGET "esp32c6") +set(MAX3421_HOST 1) diff --git a/hw/bsp/espressif/boards/adafruit_feather_esp32c6/board.h b/hw/bsp/espressif/boards/adafruit_feather_esp32c6/board.h new file mode 100644 index 000000000..18b51410d --- /dev/null +++ b/hw/bsp/espressif/boards/adafruit_feather_esp32c6/board.h @@ -0,0 +1,56 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2020, Ha Thach (tinyusb.org) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * This file is part of the TinyUSB stack. + */ + +/* metadata: + name: Adafruit Feather EPS32-C6 + url: https://www.adafruit.com/product/5933 +*/ + +#ifndef BOARD_H_ +#define BOARD_H_ + +#ifdef __cplusplus + extern "C" { +#endif + +#define NEOPIXEL_PIN 15 + +#define BUTTON_PIN 9 +#define BUTTON_STATE_ACTIVE 0 + +// SPI for USB host shield +#define MAX3421_SPI_HOST SPI2_HOST +#define MAX3421_SCK_PIN 21 +#define MAX3421_MOSI_PIN 22 +#define MAX3421_MISO_PIN 23 +#define MAX3421_CS_PIN 8 +#define MAX3421_INTR_PIN 7 + +#ifdef __cplusplus + } +#endif + +#endif /* BOARD_H_ */ diff --git a/hw/bsp/espressif/boards/adafruit_feather_esp32s2/board.h b/hw/bsp/espressif/boards/adafruit_feather_esp32s2/board.h index 9aa2e7535..0f607c755 100644 --- a/hw/bsp/espressif/boards/adafruit_feather_esp32s2/board.h +++ b/hw/bsp/espressif/boards/adafruit_feather_esp32s2/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Adafruit Feather ESP32S2 + url: https://www.adafruit.com/product/5000 +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/espressif/boards/adafruit_feather_esp32s3/board.h b/hw/bsp/espressif/boards/adafruit_feather_esp32s3/board.h index 9aa2e7535..35c268cf5 100644 --- a/hw/bsp/espressif/boards/adafruit_feather_esp32s3/board.h +++ b/hw/bsp/espressif/boards/adafruit_feather_esp32s3/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Adafruit Feather ESP32S3 + url: https://www.adafruit.com/product/5323 +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/espressif/boards/adafruit_magtag_29gray/board.h b/hw/bsp/espressif/boards/adafruit_magtag_29gray/board.h index 084a7aaf2..b86089400 100644 --- a/hw/bsp/espressif/boards/adafruit_magtag_29gray/board.h +++ b/hw/bsp/espressif/boards/adafruit_magtag_29gray/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Adafruit MagTag 2.9" Grayscale + url: https://www.adafruit.com/product/4800 +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/espressif/boards/adafruit_metro_esp32s2/board.h b/hw/bsp/espressif/boards/adafruit_metro_esp32s2/board.h index 137ea71ae..bc45678f7 100644 --- a/hw/bsp/espressif/boards/adafruit_metro_esp32s2/board.h +++ b/hw/bsp/espressif/boards/adafruit_metro_esp32s2/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Adafruit Metro ESP32-S2 + url: https://www.adafruit.com/product/4775 +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/espressif/boards/espressif_addax_1/board.h b/hw/bsp/espressif/boards/espressif_addax_1/board.h index d4690f732..4a4a15e1b 100644 --- a/hw/bsp/espressif/boards/espressif_addax_1/board.h +++ b/hw/bsp/espressif/boards/espressif_addax_1/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Espresif Addax-1 + url: n/a +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/espressif/boards/espressif_c3_devkitc/board.h b/hw/bsp/espressif/boards/espressif_c3_devkitc/board.h index 243dd47f6..a03cb5052 100644 --- a/hw/bsp/espressif/boards/espressif_c3_devkitc/board.h +++ b/hw/bsp/espressif/boards/espressif_c3_devkitc/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Espresif C3 DevKitC + url: https://docs.espressif.com/projects/esp-dev-kits/en/latest/esp32c3/esp32-c3-devkitc-02/index.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/espressif/boards/espressif_c6_devkitc/board.h b/hw/bsp/espressif/boards/espressif_c6_devkitc/board.h index 243dd47f6..eedd36a89 100644 --- a/hw/bsp/espressif/boards/espressif_c6_devkitc/board.h +++ b/hw/bsp/espressif/boards/espressif_c6_devkitc/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Espresif C6 DevKitC + url: https://docs.espressif.com/projects/esp-dev-kits/en/latest/esp32c6/esp32-c6-devkitc-1/index.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/espressif/boards/espressif_kaluga_1/board.h b/hw/bsp/espressif/boards/espressif_kaluga_1/board.h index 613e6ae0c..d49dc2af6 100644 --- a/hw/bsp/espressif/boards/espressif_kaluga_1/board.h +++ b/hw/bsp/espressif/boards/espressif_kaluga_1/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Espresif Kaluga 1 + url: https://docs.espressif.com/projects/esp-dev-kits/en/latest/esp32s2/esp32-s2-kaluga-1/index.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/espressif/boards/espressif_p4_function_ev/board.h b/hw/bsp/espressif/boards/espressif_p4_function_ev/board.h index e57f7c51f..40c4963d9 100644 --- a/hw/bsp/espressif/boards/espressif_p4_function_ev/board.h +++ b/hw/bsp/espressif/boards/espressif_p4_function_ev/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Espresif P4 Function EV + url: https://docs.espressif.com/projects/esp-dev-kits/en/latest/esp32p4/esp32-p4-function-ev-board/index.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ @@ -36,9 +41,10 @@ #define BUTTON_PIN 35 #define BUTTON_STATE_ACTIVE 0 -// For CI hardware test, to test both device and host on the same HS port with help of -#define HIL_DEVICE_HOST_MUX_PIN 47 -#define HIL_DEVICE_STATE 1 +// For CI hardware test, to test both device and host on the same HS port with help of TS3USB30 +// https://www.adafruit.com/product/5871 +#define HIL_TS3USB30_MODE_PIN 47 +#define HIL_TS3USB30_MODE_DEVICE 1 #ifdef __cplusplus } diff --git a/hw/bsp/espressif/boards/espressif_s2_devkitc/board.h b/hw/bsp/espressif/boards/espressif_s2_devkitc/board.h index e068efef9..499a626a6 100644 --- a/hw/bsp/espressif/boards/espressif_s2_devkitc/board.h +++ b/hw/bsp/espressif/boards/espressif_s2_devkitc/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Espresif S2 DevKitC + url: https://docs.espressif.com/projects/esp-dev-kits/en/latest/esp32s2/esp32-s2-devkitc-1/index.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ @@ -31,13 +36,19 @@ extern "C" { #endif -// Note: On the production version (v1.2) WS2812 is connected to GPIO 18, -// however earlier revision v1.1 WS2812 is connected to GPIO 17 #define NEOPIXEL_PIN 18 #define BUTTON_PIN 0 #define BUTTON_STATE_ACTIVE 0 +// SPI for USB host shield +#define MAX3421_SPI_HOST SPI2_HOST +#define MAX3421_SCK_PIN 36 +#define MAX3421_MOSI_PIN 35 +#define MAX3421_MISO_PIN 37 +#define MAX3421_CS_PIN 15 +#define MAX3421_INTR_PIN 14 + #ifdef __cplusplus } #endif diff --git a/hw/bsp/espressif/boards/espressif_s3_devkitc/board.h b/hw/bsp/espressif/boards/espressif_s3_devkitc/board.h index a319fbc61..d2483c84f 100644 --- a/hw/bsp/espressif/boards/espressif_s3_devkitc/board.h +++ b/hw/bsp/espressif/boards/espressif_s3_devkitc/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Espresif S3 DevKitC + url: https://docs.espressif.com/projects/esp-dev-kits/en/latest/esp32s3/esp32-s3-devkitc-1/index.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ @@ -31,7 +36,7 @@ extern "C" { #endif -#define NEOPIXEL_PIN 48 +#define NEOPIXEL_PIN 38 #define BUTTON_PIN 0 #define BUTTON_STATE_ACTIVE 0 diff --git a/hw/bsp/espressif/boards/espressif_s3_devkitm/board.h b/hw/bsp/espressif/boards/espressif_s3_devkitm/board.h index a319fbc61..5c1914ebe 100644 --- a/hw/bsp/espressif/boards/espressif_s3_devkitm/board.h +++ b/hw/bsp/espressif/boards/espressif_s3_devkitm/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Espresif S3 DevKitM + url: https://docs.espressif.com/projects/esp-dev-kits/en/latest/esp32s3/esp32-s3-devkitm-1/index.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ @@ -44,6 +49,11 @@ #define MAX3421_CS_PIN 15 #define MAX3421_INTR_PIN 14 +// For CI hardware test, to test both device and host on the same HS port with help of TS3USB30 +// https://www.adafruit.com/product/5871 +#define HIL_TS3USB30_MODE_PIN 47 +#define HIL_TS3USB30_MODE_DEVICE 1 + #ifdef __cplusplus } #endif diff --git a/hw/bsp/espressif/boards/espressif_saola_1/board.h b/hw/bsp/espressif/boards/espressif_saola_1/board.h index e068efef9..ea369f19c 100644 --- a/hw/bsp/espressif/boards/espressif_saola_1/board.h +++ b/hw/bsp/espressif/boards/espressif_saola_1/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Espresif S2 Saola 1 + url: https://docs.espressif.com/projects/esp-dev-kits/en/latest/esp32s2/esp32-s2-saola-1/index.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/espressif/boards/family.c b/hw/bsp/espressif/boards/family.c index 048b431fb..2a5deed26 100644 --- a/hw/bsp/espressif/boards/family.c +++ b/hw/bsp/espressif/boards/family.c @@ -24,6 +24,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: Espressif +*/ + #include "bsp/board_api.h" #include "board.h" @@ -45,7 +49,9 @@ static led_strip_handle_t led_strip; static void max3421_init(void); #endif +#if TU_CHECK_MCU(OPT_MCU_ESP32S2, OPT_MCU_ESP32S3, OPT_MCU_ESP32P4) static bool usb_init(void); +#endif //--------------------------------------------------------------------+ // Implementation @@ -88,10 +94,10 @@ void board_init(void) { usb_init(); #endif -#ifdef HIL_DEVICE_HOST_MUX_PIN - gpio_reset_pin(HIL_DEVICE_HOST_MUX_PIN); - gpio_set_direction(HIL_DEVICE_HOST_MUX_PIN, GPIO_MODE_OUTPUT); - gpio_set_level(HIL_DEVICE_HOST_MUX_PIN, CFG_TUD_ENABLED ? HIL_DEVICE_STATE : (1-HIL_DEVICE_STATE)); +#ifdef HIL_TS3USB30_MODE_PIN + gpio_reset_pin(HIL_TS3USB30_MODE_PIN); + gpio_set_direction(HIL_TS3USB30_MODE_PIN, GPIO_MODE_OUTPUT); + gpio_set_level(HIL_TS3USB30_MODE_PIN, CFG_TUD_ENABLED ? HIL_TS3USB30_MODE_DEVICE : (1-HIL_TS3USB30_MODE_DEVICE)); #endif #if CFG_TUH_ENABLED && CFG_TUH_MAX3421 @@ -150,6 +156,10 @@ int board_getchar(void) { return getchar(); } +void board_putchar(int c) { + putchar(c); +} + //-------------------------------------------------------------------- // PHY Init //-------------------------------------------------------------------- @@ -158,7 +168,6 @@ int board_getchar(void) { #if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 3, 0) #include "esp_private/usb_phy.h" -#include "soc/usb_pins.h" static usb_phy_handle_t phy_hdl; @@ -171,20 +180,14 @@ bool usb_init(void) { // maybe we can use USB_OTG_MODE_DEFAULT and switch using dwc2 driver #if CFG_TUD_ENABLED .otg_mode = USB_OTG_MODE_DEVICE, - .otg_speed = BOARD_TUD_RHPORT ? USB_PHY_SPEED_HIGH : USB_PHY_SPEED_FULL, #elif CFG_TUH_ENABLED .otg_mode = USB_OTG_MODE_HOST, - .otg_speed= BOARD_TUH_RHPORT ? USB_PHY_SPEED_HIGH : USB_PHY_SPEED_FULL, #endif + // https://github.com/hathach/tinyusb/issues/2943#issuecomment-2601888322 + // Set speed to undefined (auto-detect) to avoid timinng/racing issue with S3 with host such as macOS + .otg_speed = USB_PHY_SPEED_UNDEFINED, }; - // OTG IOs config - // const usb_phy_otg_io_conf_t otg_io_conf = USB_PHY_SELF_POWERED_DEVICE(config->vbus_monitor_io); - // if (config->self_powered) { - // phy_conf.otg_io_conf = &otg_io_conf; - // } - // ESP_RETURN_ON_ERROR(usb_new_phy(&phy_conf, &phy_hdl), TAG, "Install USB PHY failed"); - usb_new_phy(&phy_conf, &phy_hdl); return true; diff --git a/hw/bsp/espressif/family.cmake b/hw/bsp/espressif/family.cmake index daa12cdb4..ca9eadaf6 100644 --- a/hw/bsp/espressif/family.cmake +++ b/hw/bsp/espressif/family.cmake @@ -1,5 +1,3 @@ -cmake_minimum_required(VERSION 3.5) - # Apply board specific content i.e IDF_TARGET must be set before project.cmake is included include("${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake") string(TOUPPER ${IDF_TARGET} FAMILY_MCUS) @@ -32,8 +30,6 @@ endif () # Add example src and bsp directories set(EXTRA_COMPONENT_DIRS "src" "${CMAKE_CURRENT_LIST_DIR}/boards" "${CMAKE_CURRENT_LIST_DIR}/components") - -# set SDKCONFIG for each IDF Target -set(SDKCONFIG ${CMAKE_SOURCE_DIR}/sdkconfig.${IDF_TARGET}) +set(SDKCONFIG ${CMAKE_BINARY_DIR}/sdkconfig) include($ENV{IDF_PATH}/tools/cmake/project.cmake) diff --git a/hw/bsp/espressif/family.mk b/hw/bsp/espressif/family.mk deleted file mode 100644 index 0dc21b8eb..000000000 --- a/hw/bsp/espressif/family.mk +++ /dev/null @@ -1,34 +0,0 @@ -#DEPS_SUBMODULES += - -UF2_FAMILY_ID_esp32s2 = 0xbfdd4eee -UF2_FAMILY_ID_esp32s3 = 0xc47e5767 - -BOARD_CMAKE := $(file < $(TOP)/$(BOARD_PATH)/board.cmake) -ifneq ($(findstring esp32s2,$(BOARD_CMAKE)),) - IDF_TARGET = esp32s2 -else -ifneq ($(findstring esp32s3,$(BOARD_CMAKE)),) - IDF_TARGET = esp32s3 -endif -endif - -.PHONY: all clean flash bootloader-flash app-flash erase monitor dfu-flash dfu - -all: - idf.py -B$(BUILD) -DFAMILY=$(FAMILY) -DBOARD=$(BOARD) $(CMAKE_DEFSYM) build - -build: all - -fullclean: - if test -f sdkconfig; then $(RM) -f sdkconfig ; fi - if test -d $(BUILD); then $(RM) -rf $(BUILD) ; fi - idf.py -B$(BUILD) -DFAMILY=$(FAMILY) -DBOARD=$(BOARD) $(CMAKE_DEFSYM) $@ - -clean flash bootloader-flash app-flash erase monitor dfu-flash dfu size size-components size-files: - idf.py -B$(BUILD) -DFAMILY=$(FAMILY) -DBOARD=$(BOARD) $(CMAKE_DEFSYM) $@ - -uf2: $(BUILD)/$(PROJECT).uf2 - -$(BUILD)/$(PROJECT).uf2: $(BUILD)/$(PROJECT).bin - @echo CREATE $@ - $(PYTHON) $(TOP)/tools/uf2/utils/uf2conv.py -f $(UF2_FAMILY_ID_$(IDF_TARGET)) -b 0x0 -c -o $@ $^ diff --git a/hw/bsp/f1c100s/boards/f1c100s/board.h b/hw/bsp/f1c100s/boards/f1c100s/board.h index 3b56a3a57..44b78f8fb 100644 --- a/hw/bsp/f1c100s/boards/f1c100s/board.h +++ b/hw/bsp/f1c100s/boards/f1c100s/board.h @@ -1,3 +1,8 @@ +/* metadata: + name: Lctech Pi F1C200s + url: https://linux-sunxi.org/Lctech_Pi_F1C200s +*/ + #ifndef BOARD_H #define BOARD_H diff --git a/hw/bsp/f1c100s/family.c b/hw/bsp/f1c100s/family.c index 6df4a0ed8..9e864363f 100644 --- a/hw/bsp/f1c100s/family.c +++ b/hw/bsp/f1c100s/family.c @@ -24,6 +24,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: Sunxi +*/ + #include #include #include diff --git a/hw/bsp/f1c100s/family.cmake b/hw/bsp/f1c100s/family.cmake index 0903a0143..211c6645c 100644 --- a/hw/bsp/f1c100s/family.cmake +++ b/hw/bsp/f1c100s/family.cmake @@ -5,7 +5,7 @@ set(SDK_DIR ${TOP}/hw/mcu/allwinner/f1c100s) include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) # toolchain set up -set(CMAKE_SYSTEM_PROCESSOR arm926ej-s CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU arm926ej-s CACHE INTERNAL "System Processor") set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) set(FAMILY_MCUS F1C100S CACHE INTERNAL "") @@ -100,15 +100,15 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_F1C100S ${RTOS}) - target_sources(${TARGET}-tinyusb PRIVATE + family_add_tinyusb(${TARGET} OPT_MCU_F1C100S) + target_sources(${TARGET} PRIVATE ${TOP}/src/portable/sunxi/dcd_sunxi_musb.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) # Flashing + family_add_bin_hex(${TARGET}) family_flash_jlink(${TARGET}) endfunction() diff --git a/hw/bsp/family_support.cmake b/hw/bsp/family_support.cmake index 82e3badb3..9ec80df91 100644 --- a/hw/bsp/family_support.cmake +++ b/hw/bsp/family_support.cmake @@ -8,6 +8,13 @@ get_filename_component(TOP ${TOP} ABSOLUTE) set(UF2CONV_PY ${TOP}/tools/uf2/utils/uf2conv.py) +#------------------------------------------------------------- +# RTOS +#------------------------------------------------------------- +if (NOT DEFINED RTOS) + set(RTOS noos CACHE STRING "RTOS") +endif () + #------------------------------------------------------------- # Toolchain # Can be changed via -DTOOLCHAIN=gcc|iar or -DCMAKE_C_COMPILER= @@ -27,11 +34,15 @@ if (DEFINED CMAKE_C_COMPILER) endif () endif () -# default to gcc if (NOT DEFINED TOOLCHAIN) set(TOOLCHAIN gcc) endif () +# Optimization +if (NOT DEFINED CMAKE_BUILD_TYPE OR CMAKE_BUILD_TYPE STREQUAL "") + set(CMAKE_BUILD_TYPE MinSizeRel CACHE STRING "Build type" FORCE) +endif () + #------------------------------------------------------------- # FAMILY and BOARD #------------------------------------------------------------- @@ -53,6 +64,7 @@ if (NOT DEFINED FAMILY) # replace / with ; so that we can get the first element as FAMILY string(REPLACE "/" ";" BOARD_PATH ${BOARD_PATH}) list(GET BOARD_PATH 0 FAMILY) + set(FAMILY ${FAMILY} CACHE STRING "Board family") endif () if (NOT EXISTS ${CMAKE_CURRENT_LIST_DIR}/${FAMILY}/family.cmake) @@ -73,33 +85,14 @@ if (NOT NO_WARN_RWX_SEGMENTS_SUPPORTED) set(NO_WARN_RWX_SEGMENTS_SUPPORTED 1) endif() -set(WARNING_FLAGS_GNU - -Wall - -Wextra - -Werror - -Wfatal-errors - -Wdouble-promotion - -Wstrict-prototypes - -Wstrict-overflow - -Werror-implicit-function-declaration - -Wfloat-equal - -Wundef - -Wshadow - -Wwrite-strings - -Wsign-compare - -Wmissing-format-attribute - -Wunreachable-code - -Wcast-align - -Wcast-function-type - -Wcast-qual - -Wnull-dereference - -Wuninitialized - -Wunused - -Wreturn-type - -Wredundant-decls - ) - -set(WARNING_FLAGS_IAR "") +#---------------------------------- +# Zephyr +#---------------------------------- +if (RTOS STREQUAL zephyr) + set(BOARD_ROOT ${TOP}/hw/bsp/${FAMILY}) + set(ZEPHYR_BOARD_ALIASES ${CMAKE_CURRENT_LIST_DIR}/zephyr_board_aliases.cmake) + find_package(Zephyr REQUIRED HINTS ${TOP}/zephyr) +endif () #------------------------------------------------------------- # Functions @@ -177,7 +170,6 @@ endfunction() # Add RTOS to example function(family_add_rtos TARGET RTOS) if (RTOS STREQUAL "freertos") - # freertos config if (NOT TARGET freertos_config) add_library(freertos_config INTERFACE) target_include_directories(freertos_config INTERFACE ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/${FAMILY}/FreeRTOSConfig) @@ -185,12 +177,15 @@ function(family_add_rtos TARGET RTOS) target_link_libraries(freertos_config INTERFACE board_${BOARD}) endif() - # freertos kernel if (NOT TARGET freertos_kernel) add_subdirectory(${TOP}/lib/FreeRTOS-Kernel ${CMAKE_BINARY_DIR}/lib/freertos_kernel) endif () target_link_libraries(${TARGET} PUBLIC freertos_kernel) + target_compile_definitions(${TARGET} PUBLIC CFG_TUSB_OS=OPT_OS_FREERTOS) + elseif (RTOS STREQUAL "zephyr") + target_compile_definitions(${TARGET} PUBLIC CFG_TUSB_OS=OPT_OS_ZEPHYR) + target_include_directories(${TARGET} PUBLIC ${ZEPHYR_BASE}/include) endif () endfunction() @@ -198,6 +193,7 @@ endfunction() function(family_configure_common TARGET RTOS) family_add_rtos(${TARGET} ${RTOS}) + # Add BOARD_${BOARD} define string(TOUPPER ${BOARD} BOARD_UPPER) string(REPLACE "-" "_" BOARD_UPPER ${BOARD_UPPER}) target_compile_definitions(${TARGET} PUBLIC @@ -210,20 +206,6 @@ function(family_configure_common TARGET RTOS) target_compile_options(${TARGET} PUBLIC ${CFLAGS_CLI}) endif() - target_compile_options(${TARGET} PUBLIC ${WARNING_FLAGS_${CMAKE_C_COMPILER_ID}}) - - # Generate linker map file - if (CMAKE_C_COMPILER_ID STREQUAL "GNU") - target_link_options(${TARGET} PUBLIC "LINKER:-Map=$.map") - if (CMAKE_C_COMPILER_VERSION VERSION_GREATER_EQUAL 12.0 AND NO_WARN_RWX_SEGMENTS_SUPPORTED) - target_link_options(${TARGET} PUBLIC "LINKER:--no-warn-rwx-segments") - endif () - elseif (CMAKE_C_COMPILER_ID STREQUAL "Clang") - target_link_options(${TARGET} PUBLIC "LINKER:-Map=$.map") - elseif (CMAKE_C_COMPILER_ID STREQUAL "IAR") - target_link_options(${TARGET} PUBLIC "LINKER:--map=$.map") - endif() - # ETM Trace option if (TRACE_ETM STREQUAL "1") target_compile_definitions(${TARGET} PUBLIC TRACE_ETM) @@ -231,79 +213,101 @@ function(family_configure_common TARGET RTOS) # LOGGER option if (DEFINED LOGGER) + string(TOUPPER ${LOGGER} LOGGER) target_compile_definitions(${TARGET} PUBLIC LOGGER_${LOGGER}) # Add segger rtt to example - if(LOGGER STREQUAL "RTT" OR LOGGER STREQUAL "rtt") - if (NOT TARGET segger_rtt) - add_library(segger_rtt STATIC ${TOP}/lib/SEGGER_RTT/RTT/SEGGER_RTT.c) - target_include_directories(segger_rtt PUBLIC ${TOP}/lib/SEGGER_RTT/RTT) -# target_compile_definitions(segger_rtt PUBLIC SEGGER_RTT_MODE_DEFAULT=SEGGER_RTT_MODE_BLOCK_IF_FIFO_FULL) - endif() - target_link_libraries(${TARGET} PUBLIC segger_rtt) + if(LOGGER STREQUAL "RTT") + target_sources(${TARGET} PUBLIC ${TOP}/lib/SEGGER_RTT/RTT/SEGGER_RTT.c) + target_include_directories(${TARGET} PUBLIC ${TOP}/lib/SEGGER_RTT/RTT) +# target_compile_definitions(${TARGET} PUBLIC SEGGER_RTT_MODE_DEFAULT=SEGGER_RTT_MODE_BLOCK_IF_FIFO_FULL) endif () + else () + target_compile_definitions(${TARGET} PUBLIC LOGGER_UART) + endif () + + if (CMAKE_C_COMPILER_ID STREQUAL "GNU" OR CMAKE_C_COMPILER_ID STREQUAL "Clang") + target_compile_options(${TARGET} PRIVATE + -Wall + -Wextra + #-Werror + -Wfatal-errors + -Wdouble-promotion + -Wstrict-prototypes + -Wstrict-overflow + -Werror-implicit-function-declaration + -Wfloat-equal + -Wundef + -Wshadow + -Wwrite-strings + -Wsign-compare + -Wmissing-format-attribute + -Wunreachable-code + -Wcast-align + -Wcast-function-type + -Wcast-qual + -Wnull-dereference + -Wuninitialized + -Wunused + -Wunused-function + -Wreturn-type + -Wredundant-decls + -Wmissing-prototypes + ) + target_link_options(${TARGET} PUBLIC "LINKER:-Map=$.map") + if (CMAKE_C_COMPILER_ID STREQUAL "GNU" AND CMAKE_C_COMPILER_VERSION VERSION_GREATER_EQUAL 12.0 + AND NO_WARN_RWX_SEGMENTS_SUPPORTED AND (NOT RTOS STREQUAL zephyr)) + target_link_options(${TARGET} PUBLIC "LINKER:--no-warn-rwx-segments") + endif () + elseif (CMAKE_C_COMPILER_ID STREQUAL "IAR") + target_link_options(${TARGET} PUBLIC "LINKER:--map=$.map") endif () # run size after build - find_program(SIZE_EXE ${CMAKE_SIZE}) - if(NOT ${SIZE_EXE} STREQUAL SIZE_EXE-NOTFOUND) - add_custom_command(TARGET ${TARGET} POST_BUILD - COMMAND ${SIZE_EXE} $ - ) - endif () +# find_program(SIZE_EXE ${CMAKE_SIZE}) +# if(NOT ${SIZE_EXE} STREQUAL SIZE_EXE-NOTFOUND) +# add_custom_command(TARGET ${TARGET} POST_BUILD +# COMMAND ${SIZE_EXE} $ +# ) +# endif () endfunction() -# Add tinyusb to example -function(family_add_tinyusb TARGET OPT_MCU RTOS) - # tinyusb target is built for each example since it depends on example's tusb_config.h - set(TINYUSB_TARGET_PREFIX ${TARGET}-) - add_library(${TARGET}-tinyusb_config INTERFACE) - - # path to tusb_config.h - target_include_directories(${TARGET}-tinyusb_config INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/src) - target_compile_definitions(${TARGET}-tinyusb_config INTERFACE CFG_TUSB_MCU=${OPT_MCU}) - - if (DEFINED LOG) - target_compile_definitions(${TARGET}-tinyusb_config INTERFACE CFG_TUSB_DEBUG=${LOG}) - if (LOG STREQUAL "4") - # no inline for debug level 4 - target_compile_definitions(${TARGET}-tinyusb_config INTERFACE TU_ATTR_ALWAYS_INLINE=) - endif () - endif() - - if (RTOS STREQUAL "freertos") - target_compile_definitions(${TARGET}-tinyusb_config INTERFACE CFG_TUSB_OS=OPT_OS_FREERTOS) - endif () - +# Add tinyusb to target +function(family_add_tinyusb TARGET OPT_MCU) # tinyusb's CMakeList.txt add_subdirectory(${TOP}/src ${CMAKE_CURRENT_BINARY_DIR}/tinyusb) - if (RTOS STREQUAL "freertos") - # link tinyusb with freeRTOS kernel - target_link_libraries(${TARGET}-tinyusb PUBLIC freertos_kernel) - endif () + # Add TinyUSB sources, include and common define + tinyusb_target_add(${TARGET}) + target_compile_definitions(${TARGET} PUBLIC CFG_TUSB_MCU=${OPT_MCU}) + if (DEFINED LOG) + target_compile_definitions(${TARGET} PUBLIC CFG_TUSB_DEBUG=${LOG}) + if (LOG STREQUAL "4") # no inline for debug level 4 + target_compile_definitions(${TARGET} PUBLIC TU_ATTR_ALWAYS_INLINE=) + endif () + endif() # use max3421 as host controller if (MAX3421_HOST STREQUAL "1") - target_compile_definitions(${TARGET}-tinyusb_config INTERFACE CFG_TUH_MAX3421=1) - target_sources(${TARGET}-tinyusb PUBLIC + target_compile_definitions(${TARGET} PUBLIC CFG_TUH_MAX3421=1) + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/analog/max3421/hcd_max3421.c ) endif () - - # compile define from command line - if(DEFINED CFLAGS_CLI) - separate_arguments(CFLAGS_CLI) - target_compile_options(${TARGET}-tinyusb PUBLIC ${CFLAGS_CLI}) - endif() - endfunction() # Add bin/hex output function(family_add_bin_hex TARGET) - add_custom_command(TARGET ${TARGET} POST_BUILD - COMMAND ${CMAKE_OBJCOPY} -Obinary $ $/${TARGET}.bin - COMMAND ${CMAKE_OBJCOPY} -Oihex $ $/${TARGET}.hex - VERBATIM) + if (CMAKE_C_COMPILER_ID STREQUAL "IAR") + add_custom_command(TARGET ${TARGET} POST_BUILD + COMMAND ${CMAKE_OBJCOPY} --bin $ $/${TARGET}.bin + COMMAND ${CMAKE_OBJCOPY} --ihex $ $/${TARGET}.hex + VERBATIM) + else() + add_custom_command(TARGET ${TARGET} POST_BUILD + COMMAND ${CMAKE_OBJCOPY} -Obinary $ $/${TARGET}.bin + COMMAND ${CMAKE_OBJCOPY} -Oihex $ $/${TARGET}.hex + VERBATIM) + endif() endfunction() # Add uf2 output @@ -314,10 +318,10 @@ function(family_add_uf2 TARGET FAMILY_ID) VERBATIM) endfunction() -#---------------------------------- +#------------------------------------------------------- # Example Target Configure (Default rule) # These function can be redefined in FAMILY/family.cmake -#---------------------------------- +#-------------------------------------------------------- function(family_configure_example TARGET RTOS) # empty function, should be redefined in FAMILY/family.cmake @@ -399,7 +403,11 @@ endfunction() # Add flash jlink target function(family_flash_jlink TARGET) if (NOT DEFINED JLINKEXE) - set(JLINKEXE JLinkExe) + if(CMAKE_HOST_WIN32) + set(JLINKEXE JLink.exe) + else() + set(JLINKEXE JLinkExe) + endif() endif () if (NOT DEFINED JLINK_IF) @@ -411,26 +419,28 @@ function(family_flash_jlink TARGET) endif () separate_arguments(OPTION_LIST UNIX_COMMAND ${JLINK_OPTION}) + if (RTOS STREQUAL zephyr) + set(BINARY_TARGET zephyr_final) + set(NAME_TARGET ${CMAKE_PROJECT_NAME}) + else () + set(BINARY_TARGET ${TARGET}) + set(NAME_TARGET ${TARGET}) + endif () + file(GENERATE - OUTPUT $/${TARGET}.jlink + OUTPUT $/${BINARY_TARGET}.jlink CONTENT "halt -loadfile $ +loadfile $ r go exit" ) - add_custom_target(${TARGET}-jlink - DEPENDS ${TARGET} - COMMAND ${JLINKEXE} -device ${JLINK_DEVICE} ${OPTION_LIST} -if ${JLINK_IF} -JTAGConf -1,-1 -speed auto -CommandFile $/${TARGET}.jlink + add_custom_target(${NAME_TARGET}-jlink + DEPENDS ${BINARY_TARGET} + COMMAND ${JLINKEXE} -device ${JLINK_DEVICE} ${OPTION_LIST} -if ${JLINK_IF} -JTAGConf -1,-1 -speed auto -CommandFile $/${BINARY_TARGET}.jlink VERBATIM ) - - # optional flash post build -# add_custom_command(TARGET ${TARGET} POST_BUILD -# COMMAND ${JLINKEXE} -device ${JLINK_DEVICE} ${OPTION_LIST} -if ${JLINK_IF} -JTAGConf -1,-1 -speed auto -CommandFile $/${TARGET}.jlink -# VERBATIM -# ) endfunction() @@ -470,13 +480,17 @@ function(family_flash_openocd TARGET) set(OPENOCD_OPTION2 "") endif () + if (DEFINED OPENOCD_SERIAL) + set(OPENOCD_OPTION "-c \"adapter serial ${OPENOCD_SERIAL}\" ${OPENOCD_OPTION}") + endif () + separate_arguments(OPTION_LIST UNIX_COMMAND ${OPENOCD_OPTION}) separate_arguments(OPTION_LIST2 UNIX_COMMAND ${OPENOCD_OPTION2}) # note skip verify since it has issue with rp2040 add_custom_target(${TARGET}-openocd DEPENDS ${TARGET} - COMMAND ${OPENOCD} -c "tcl_port disabled" -c "gdb_port disabled" ${OPTION_LIST} -c init -c halt -c "program $" -c reset ${OPTION_LIST2} -c exit + COMMAND ${OPENOCD} -c "tcl_port disabled; gdb_port disabled" ${OPTION_LIST} -c "init; halt; program $" -c reset ${OPTION_LIST2} -c exit VERBATIM ) endfunction() @@ -496,10 +510,16 @@ endfunction() # Add flash openocd adi (Analog Devices) target # included with msdk or compiled from release branch of https://github.com/analogdevicesinc/openocd function(family_flash_openocd_adi TARGET) - if (DEFINED $ENV{MAXIM_PATH}) - # use openocd from msdk - set(OPENOCD ENV{MAXIM_PATH}/Tools/OpenOCD/openocd) - set(OPENOCD_OPTION2 "-s ENV{MAXIM_PATH}/Tools/OpenOCD/scripts") + if (DEFINED MAXIM_PATH) + # use openocd from msdk with MAXIM_PATH cmake variable first if the user specified it + set(OPENOCD ${MAXIM_PATH}/Tools/OpenOCD/openocd) + set(OPENOCD_OPTION2 "-s ${MAXIM_PATH}/Tools/OpenOCD/scripts") + elseif (DEFINED ENV{MAXIM_PATH}) + # use openocd from msdk with MAXIM_PATH environment variable. Normalize + # since msdk can be Windows (MinGW) or Linux + file(TO_CMAKE_PATH "$ENV{MAXIM_PATH}" MAXIM_PATH_NORM) + set(OPENOCD ${MAXIM_PATH_NORM}/Tools/OpenOCD/openocd) + set(OPENOCD_OPTION2 "-s ${MAXIM_PATH_NORM}/Tools/OpenOCD/scripts") else() # compiled from source if (NOT DEFINED OPENOCD_ADI_PATH) @@ -606,7 +626,6 @@ function(family_flash_msp430flasher TARGET) ) endfunction() - function(family_flash_uniflash TARGET) if (NOT DEFINED DSLITE) set(DSLITE dslite.sh) diff --git a/hw/bsp/fomu/boards/fomu/board.h b/hw/bsp/fomu/boards/fomu/board.h index 666ba1d98..2651c823d 100644 --- a/hw/bsp/fomu/boards/fomu/board.h +++ b/hw/bsp/fomu/boards/fomu/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: fomu + url: https://tomu.im/fomu.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/fomu/family.c b/hw/bsp/fomu/family.c index ccf2b12f4..61943cb01 100644 --- a/hw/bsp/fomu/family.c +++ b/hw/bsp/fomu/family.c @@ -24,6 +24,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: Tomu +*/ + #include #include #include "csr.h" diff --git a/hw/bsp/fomu/family.cmake b/hw/bsp/fomu/family.cmake index 8d5ab144c..639373695 100644 --- a/hw/bsp/fomu/family.cmake +++ b/hw/bsp/fomu/family.cmake @@ -4,7 +4,7 @@ include_guard() include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) # toolchain set up -set(CMAKE_SYSTEM_PROCESSOR rv32i-ilp32 CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU rv32i-ilp32 CACHE INTERNAL "System Processor") set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/riscv_${TOOLCHAIN}.cmake) set(FAMILY_MCUS VALENTYUSB_EPTRI CACHE INTERNAL "") @@ -77,14 +77,13 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_VALENTYUSB_EPTRI ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC + family_add_tinyusb(${TARGET} OPT_MCU_VALENTYUSB_EPTRI) + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/valentyusb/eptri/dcd_eptri.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) # Flashing family_add_bin_hex(${TARGET}) diff --git a/hw/bsp/gd32vf103/boards/sipeed_longan_nano/board.h b/hw/bsp/gd32vf103/boards/sipeed_longan_nano/board.h index fae7c40b7..cb564a340 100644 --- a/hw/bsp/gd32vf103/boards/sipeed_longan_nano/board.h +++ b/hw/bsp/gd32vf103/boards/sipeed_longan_nano/board.h @@ -1,3 +1,8 @@ +/* metadata: + name: Sipeed Longan Nano + url: https://longan.sipeed.com/en/ +*/ + #ifndef _NUCLEI_SDK_HAL_H #define _NUCLEI_SDK_HAL_H diff --git a/hw/bsp/gd32vf103/family.c b/hw/bsp/gd32vf103/family.c index d4a819fb3..9d15755fc 100644 --- a/hw/bsp/gd32vf103/family.c +++ b/hw/bsp/gd32vf103/family.c @@ -24,6 +24,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: GigaDevice +*/ + #include "drv_usb_hw.h" #include "drv_usb_dev.h" diff --git a/hw/bsp/gd32vf103/family.cmake b/hw/bsp/gd32vf103/family.cmake index 1441e41de..a47871b38 100644 --- a/hw/bsp/gd32vf103/family.cmake +++ b/hw/bsp/gd32vf103/family.cmake @@ -7,7 +7,7 @@ set(SOC_DIR ${SDK_DIR}/SoC/gd32vf103) include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) # toolchain set up -set(CMAKE_SYSTEM_PROCESSOR rv32imac-ilp32 CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU rv32imac-ilp32 CACHE INTERNAL "System Processor") set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/riscv_${TOOLCHAIN}.cmake) set(FAMILY_MCUS GD32VF103 CACHE INTERNAL "") @@ -105,17 +105,17 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_GD32VF103 ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC + family_add_tinyusb(${TARGET} OPT_MCU_GD32VF103) + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/synopsys/dwc2/dcd_dwc2.c ${TOP}/src/portable/synopsys/dwc2/hcd_dwc2.c ${TOP}/src/portable/synopsys/dwc2/dwc2_common.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) # Flashing + family_add_bin_hex(${TARGET}) family_flash_jlink(${TARGET}) endfunction() diff --git a/hw/bsp/imxrt/boards/metro_m7_1011/board.h b/hw/bsp/imxrt/boards/metro_m7_1011/board.h index 24141f5f4..ccc4d6b9a 100644 --- a/hw/bsp/imxrt/boards/metro_m7_1011/board.h +++ b/hw/bsp/imxrt/boards/metro_m7_1011/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Adafruit Metro M7 1011 + url: https://www.adafruit.com/product/5600 +*/ + #ifndef BOARD_M7_1011_H_ #define BOARD_M7_1011_H_ diff --git a/hw/bsp/imxrt/boards/metro_m7_1011_sd/board.h b/hw/bsp/imxrt/boards/metro_m7_1011_sd/board.h index 343e17f81..04d5b01b5 100644 --- a/hw/bsp/imxrt/boards/metro_m7_1011_sd/board.h +++ b/hw/bsp/imxrt/boards/metro_m7_1011_sd/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Adafruit Metro M7 1011 SD + url: https://www.adafruit.com/product/5600 +*/ + #ifndef BOARD_METRO_M7_1011_SD_H_ #define BOARD_METRO_M7_1011_SD_H_ diff --git a/hw/bsp/imxrt/boards/mimxrt1010_evk/board.h b/hw/bsp/imxrt/boards/mimxrt1010_evk/board.h index da12075a0..6b9ec0ae1 100644 --- a/hw/bsp/imxrt/boards/mimxrt1010_evk/board.h +++ b/hw/bsp/imxrt/boards/mimxrt1010_evk/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: i.MX RT1010 Evaluation Kit + url: https://www.nxp.com/design/design-center/development-boards-and-designs/i-mx-evaluation-and-development-boards/i-mx-rt1010-evaluation-kit:MIMXRT1010-EVK +*/ + #ifndef BOARD_MIMXRT1010_EVK_H_ #define BOARD_MIMXRT1010_EVK_H_ diff --git a/hw/bsp/imxrt/boards/mimxrt1015_evk/board.h b/hw/bsp/imxrt/boards/mimxrt1015_evk/board.h index 6ac78453f..e2ec4e627 100644 --- a/hw/bsp/imxrt/boards/mimxrt1015_evk/board.h +++ b/hw/bsp/imxrt/boards/mimxrt1015_evk/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: i.MX RT1015 Evaluation Kit + url: https://www.nxp.com/design/design-center/development-boards-and-designs/MIMXRT1015-EVK +*/ + #ifndef BOARD_MIMXRT1015_EVK_H_ #define BOARD_MIMXRT1015_EVK_H_ diff --git a/hw/bsp/imxrt/boards/mimxrt1015_evk/board/clock_config.c b/hw/bsp/imxrt/boards/mimxrt1015_evk/board/clock_config.c index ae1aa7fb1..b9e4851bf 100644 --- a/hw/bsp/imxrt/boards/mimxrt1015_evk/board/clock_config.c +++ b/hw/bsp/imxrt/boards/mimxrt1015_evk/board/clock_config.c @@ -15,11 +15,11 @@ /* TEXT BELOW IS USED AS SETTING FOR TOOLS ************************************* !!GlobalInfo -product: Clocks v11.0 +product: Clocks v15.0 processor: MIMXRT1015xxxxx package_id: MIMXRT1015DAF5A mcu_data: ksdk2_0 -processor_version: 13.0.2 +processor_version: 24.12.10 board: MIMXRT1015-EVK * BE CAREFUL MODIFYING THIS COMMENT - IT IS YAML SETTINGS FOR TOOLS **********/ diff --git a/hw/bsp/imxrt/boards/mimxrt1015_evk/board/clock_config.h b/hw/bsp/imxrt/boards/mimxrt1015_evk/board/clock_config.h index 2acdb16a7..cccbe487a 100644 --- a/hw/bsp/imxrt/boards/mimxrt1015_evk/board/clock_config.h +++ b/hw/bsp/imxrt/boards/mimxrt1015_evk/board/clock_config.h @@ -36,39 +36,39 @@ void BOARD_InitBootClocks(void); #define BOARD_BOOTCLOCKRUN_CORE_CLOCK 500000000U /*!< Core clock frequency: 500000000Hz */ /* Clock outputs (values are in Hz): */ -#define BOARD_BOOTCLOCKRUN_AHB_CLK_ROOT 500000000UL -#define BOARD_BOOTCLOCKRUN_CKIL_SYNC_CLK_ROOT 32768UL -#define BOARD_BOOTCLOCKRUN_CLKO1_CLK 0UL -#define BOARD_BOOTCLOCKRUN_CLKO2_CLK 0UL -#define BOARD_BOOTCLOCKRUN_CLK_1M 1000000UL -#define BOARD_BOOTCLOCKRUN_CLK_24M 24000000UL -#define BOARD_BOOTCLOCKRUN_ENET_500M_REF_CLK 500000000UL -#define BOARD_BOOTCLOCKRUN_FLEXIO1_CLK_ROOT 30000000UL -#define BOARD_BOOTCLOCKRUN_FLEXSPI_CLK_ROOT 196363636UL -#define BOARD_BOOTCLOCKRUN_GPT1_IPG_CLK_HIGHFREQ 62500000UL -#define BOARD_BOOTCLOCKRUN_GPT2_IPG_CLK_HIGHFREQ 62500000UL -#define BOARD_BOOTCLOCKRUN_IPG_CLK_ROOT 125000000UL -#define BOARD_BOOTCLOCKRUN_LPI2C_CLK_ROOT 60000000UL -#define BOARD_BOOTCLOCKRUN_LPSPI_CLK_ROOT 105600000UL -#define BOARD_BOOTCLOCKRUN_MQS_MCLK 63529411UL -#define BOARD_BOOTCLOCKRUN_PERCLK_CLK_ROOT 62500000UL -#define BOARD_BOOTCLOCKRUN_SAI1_CLK_ROOT 63529411UL -#define BOARD_BOOTCLOCKRUN_SAI1_MCLK1 63529411UL -#define BOARD_BOOTCLOCKRUN_SAI1_MCLK2 63529411UL -#define BOARD_BOOTCLOCKRUN_SAI1_MCLK3 30000000UL -#define BOARD_BOOTCLOCKRUN_SAI2_CLK_ROOT 63529411UL -#define BOARD_BOOTCLOCKRUN_SAI2_MCLK1 63529411UL -#define BOARD_BOOTCLOCKRUN_SAI2_MCLK2 0UL -#define BOARD_BOOTCLOCKRUN_SAI2_MCLK3 30000000UL -#define BOARD_BOOTCLOCKRUN_SAI3_CLK_ROOT 63529411UL -#define BOARD_BOOTCLOCKRUN_SAI3_MCLK1 63529411UL -#define BOARD_BOOTCLOCKRUN_SAI3_MCLK2 0UL -#define BOARD_BOOTCLOCKRUN_SAI3_MCLK3 30000000UL -#define BOARD_BOOTCLOCKRUN_SPDIF0_CLK_ROOT 30000000UL -#define BOARD_BOOTCLOCKRUN_SPDIF0_EXTCLK_OUT 0UL -#define BOARD_BOOTCLOCKRUN_TRACE_CLK_ROOT 117333333UL -#define BOARD_BOOTCLOCKRUN_UART_CLK_ROOT 80000000UL -#define BOARD_BOOTCLOCKRUN_USBPHY1_CLK 480000000UL +#define BOARD_BOOTCLOCKRUN_AHB_CLK_ROOT 500000000UL /* Clock consumers of AHB_CLK_ROOT output : AIPSTZ1, AIPSTZ2, AIPSTZ3, AIPSTZ4, ARM, FLEXSPI */ +#define BOARD_BOOTCLOCKRUN_CKIL_SYNC_CLK_ROOT 32768UL /* Clock consumers of CKIL_SYNC_CLK_ROOT output : CSU, EWM, GPT1, GPT2, KPP, PIT, RTWDOG, SNVS, SPDIF, TEMPMON, USB, WDOG1, WDOG2 */ +#define BOARD_BOOTCLOCKRUN_CLKO1_CLK 0UL /* Clock consumers of CLKO1_CLK output : N/A */ +#define BOARD_BOOTCLOCKRUN_CLKO2_CLK 0UL /* Clock consumers of CLKO2_CLK output : N/A */ +#define BOARD_BOOTCLOCKRUN_CLK_1M 1000000UL /* Clock consumers of CLK_1M output : EWM, RTWDOG */ +#define BOARD_BOOTCLOCKRUN_CLK_24M 24000000UL /* Clock consumers of CLK_24M output : GPT1, GPT2 */ +#define BOARD_BOOTCLOCKRUN_ENET_500M_REF_CLK 500000000UL /* Clock consumers of ENET_500M_REF_CLK output : N/A */ +#define BOARD_BOOTCLOCKRUN_FLEXIO1_CLK_ROOT 30000000UL /* Clock consumers of FLEXIO1_CLK_ROOT output : FLEXIO1 */ +#define BOARD_BOOTCLOCKRUN_FLEXSPI_CLK_ROOT 196363636UL /* Clock consumers of FLEXSPI_CLK_ROOT output : FLEXSPI */ +#define BOARD_BOOTCLOCKRUN_GPT1_IPG_CLK_HIGHFREQ 62500000UL /* Clock consumers of GPT1_ipg_clk_highfreq output : GPT1 */ +#define BOARD_BOOTCLOCKRUN_GPT2_IPG_CLK_HIGHFREQ 62500000UL /* Clock consumers of GPT2_ipg_clk_highfreq output : GPT2 */ +#define BOARD_BOOTCLOCKRUN_IPG_CLK_ROOT 125000000UL /* Clock consumers of IPG_CLK_ROOT output : ADC1, ADC_ETC, AOI, ARM, BEE, CCM, CSU, DCDC, DCP, DMA0, DMAMUX, ENC1, EWM, FLEXIO1, FLEXRAM, FLEXSPI, GPC, GPIO1, GPIO2, GPIO3, GPIO5, IOMUXC, KPP, LPI2C1, LPI2C2, LPSPI1, LPSPI2, LPUART1, LPUART2, LPUART3, LPUART4, NVIC, OCOTP, PWM1, RTWDOG, SAI1, SAI2, SAI3, SNVS, SPDIF, SRC, TEMPMON, TMR1, TRNG, USB, WDOG1, WDOG2, XBARA, XBARB */ +#define BOARD_BOOTCLOCKRUN_LPI2C_CLK_ROOT 60000000UL /* Clock consumers of LPI2C_CLK_ROOT output : LPI2C1, LPI2C2 */ +#define BOARD_BOOTCLOCKRUN_LPSPI_CLK_ROOT 105600000UL /* Clock consumers of LPSPI_CLK_ROOT output : LPSPI1, LPSPI2 */ +#define BOARD_BOOTCLOCKRUN_MQS_MCLK 63529411UL /* Clock consumers of MQS_MCLK output : N/A */ +#define BOARD_BOOTCLOCKRUN_PERCLK_CLK_ROOT 62500000UL /* Clock consumers of PERCLK_CLK_ROOT output : GPT1, GPT2, PIT */ +#define BOARD_BOOTCLOCKRUN_SAI1_CLK_ROOT 63529411UL /* Clock consumers of SAI1_CLK_ROOT output : N/A */ +#define BOARD_BOOTCLOCKRUN_SAI1_MCLK1 63529411UL /* Clock consumers of SAI1_MCLK1 output : SAI1 */ +#define BOARD_BOOTCLOCKRUN_SAI1_MCLK2 63529411UL /* Clock consumers of SAI1_MCLK2 output : SAI1 */ +#define BOARD_BOOTCLOCKRUN_SAI1_MCLK3 30000000UL /* Clock consumers of SAI1_MCLK3 output : SAI1 */ +#define BOARD_BOOTCLOCKRUN_SAI2_CLK_ROOT 63529411UL /* Clock consumers of SAI2_CLK_ROOT output : N/A */ +#define BOARD_BOOTCLOCKRUN_SAI2_MCLK1 63529411UL /* Clock consumers of SAI2_MCLK1 output : SAI2 */ +#define BOARD_BOOTCLOCKRUN_SAI2_MCLK2 0UL /* Clock consumers of SAI2_MCLK2 output : SAI2 */ +#define BOARD_BOOTCLOCKRUN_SAI2_MCLK3 30000000UL /* Clock consumers of SAI2_MCLK3 output : SAI2 */ +#define BOARD_BOOTCLOCKRUN_SAI3_CLK_ROOT 63529411UL /* Clock consumers of SAI3_CLK_ROOT output : N/A */ +#define BOARD_BOOTCLOCKRUN_SAI3_MCLK1 63529411UL /* Clock consumers of SAI3_MCLK1 output : SAI3 */ +#define BOARD_BOOTCLOCKRUN_SAI3_MCLK2 0UL /* Clock consumers of SAI3_MCLK2 output : SAI3 */ +#define BOARD_BOOTCLOCKRUN_SAI3_MCLK3 30000000UL /* Clock consumers of SAI3_MCLK3 output : SAI3 */ +#define BOARD_BOOTCLOCKRUN_SPDIF0_CLK_ROOT 30000000UL /* Clock consumers of SPDIF0_CLK_ROOT output : SPDIF */ +#define BOARD_BOOTCLOCKRUN_SPDIF0_EXTCLK_OUT 0UL /* Clock consumers of SPDIF0_EXTCLK_OUT output : SPDIF */ +#define BOARD_BOOTCLOCKRUN_TRACE_CLK_ROOT 117333333UL /* Clock consumers of TRACE_CLK_ROOT output : ARM */ +#define BOARD_BOOTCLOCKRUN_UART_CLK_ROOT 80000000UL /* Clock consumers of UART_CLK_ROOT output : LPUART1, LPUART2, LPUART3, LPUART4 */ +#define BOARD_BOOTCLOCKRUN_USBPHY1_CLK 480000000UL /* Clock consumers of USBPHY1_CLK output : TEMPMON, USB */ /*! @brief Usb1 PLL set for BOARD_BootClockRUN configuration. */ diff --git a/hw/bsp/imxrt/boards/mimxrt1015_evk/board/pin_mux.c b/hw/bsp/imxrt/boards/mimxrt1015_evk/board/pin_mux.c index 97224a332..76c1dae70 100644 --- a/hw/bsp/imxrt/boards/mimxrt1015_evk/board/pin_mux.c +++ b/hw/bsp/imxrt/boards/mimxrt1015_evk/board/pin_mux.c @@ -6,11 +6,11 @@ /* * TEXT BELOW IS USED AS SETTING FOR TOOLS ************************************* !!GlobalInfo -product: Pins v13.1 +product: Pins v17.0 processor: MIMXRT1015xxxxx package_id: MIMXRT1015DAF5A mcu_data: ksdk2_0 -processor_version: 13.0.2 +processor_version: 24.12.10 board: MIMXRT1015-EVK external_user_signals: {} pin_labels: @@ -32,6 +32,7 @@ power_domains: {NVCC_GPIO: '3.3'} * END ****************************************************************************************************************/ void BOARD_InitBootPins(void) { BOARD_InitPins(); + BOARD_InitDEBUG_UARTPins(); } /* @@ -40,8 +41,6 @@ BOARD_InitPins: - options: {callFromInitBoot: 'true', coreID: core0, enableClock: 'true'} - pin_list: - {pin_num: '1', peripheral: GPIO2, signal: 'gpio_io, 09', pin_signal: GPIO_EMC_09, direction: INPUT, pull_keeper_select: Pull, pull_up_down_config: Pull_Up_47K_Ohm} - - {pin_num: '68', peripheral: LPUART1, signal: RX, pin_signal: GPIO_AD_B0_07, pull_up_down_config: Pull_Down_100K_Ohm} - - {pin_num: '72', peripheral: LPUART1, signal: TX, pin_signal: GPIO_AD_B0_06} - {pin_num: '21', peripheral: GPIO3, signal: 'gpio_io, 21', pin_signal: GPIO_SD_B1_01, direction: OUTPUT} * BE CAREFUL MODIFYING THIS COMMENT - IT IS YAML SETTINGS FOR TOOLS *********** */ @@ -73,15 +72,11 @@ void BOARD_InitPins(void) { /* Initialize GPIO functionality on GPIO_SD_B1_01 (pin 21) */ GPIO_PinInit(GPIO3, 21U, &USER_LED_config); - IOMUXC_SetPinMux(IOMUXC_GPIO_AD_B0_06_LPUART1_TX, 0U); - IOMUXC_SetPinMux(IOMUXC_GPIO_AD_B0_07_LPUART1_RX, 0U); IOMUXC_SetPinMux(IOMUXC_GPIO_EMC_09_GPIO2_IO09, 0U); IOMUXC_SetPinMux(IOMUXC_GPIO_SD_B1_01_GPIO3_IO21, 0U); - IOMUXC_SetPinConfig(IOMUXC_GPIO_AD_B0_07_LPUART1_RX, 0x10B0U); IOMUXC_SetPinConfig(IOMUXC_GPIO_EMC_09_GPIO2_IO09, 0x70B0U); } - /* * TEXT BELOW IS USED AS SETTING FOR TOOLS ************************************* BOARD_InitQSPIPins: @@ -113,6 +108,30 @@ void BOARD_InitQSPIPins(void) { IOMUXC_SetPinMux(IOMUXC_GPIO_SD_B1_11_FLEXSPI_A_SS0_B, 0U); } +/* + * TEXT BELOW IS USED AS SETTING FOR TOOLS ************************************* +BOARD_InitDEBUG_UARTPins: +- options: {callFromInitBoot: 'true', coreID: core0, enableClock: 'true'} +- pin_list: + - {pin_num: '68', peripheral: LPUART1, signal: RX, pin_signal: GPIO_AD_B0_07, slew_rate: Slow} + - {pin_num: '72', peripheral: LPUART1, signal: TX, pin_signal: GPIO_AD_B0_06, slew_rate: Slow} + * BE CAREFUL MODIFYING THIS COMMENT - IT IS YAML SETTINGS FOR TOOLS *********** + */ + +/* FUNCTION ************************************************************************************************************ + * + * Function Name : BOARD_InitDEBUG_UARTPins + * Description : Configures pin routing and optionally pin electrical features. + * + * END ****************************************************************************************************************/ +void BOARD_InitDEBUG_UARTPins(void) { + CLOCK_EnableClock(kCLOCK_Iomuxc); + + IOMUXC_SetPinMux(IOMUXC_GPIO_AD_B0_06_LPUART1_TX, 0U); + IOMUXC_SetPinMux(IOMUXC_GPIO_AD_B0_07_LPUART1_RX, 0U); + IOMUXC_SetPinConfig(IOMUXC_GPIO_AD_B0_06_LPUART1_TX, 0x10B0U); + IOMUXC_SetPinConfig(IOMUXC_GPIO_AD_B0_07_LPUART1_RX, 0x10B0U); +} /*********************************************************************************************************************** * EOF **********************************************************************************************************************/ diff --git a/hw/bsp/imxrt/boards/mimxrt1015_evk/board/pin_mux.h b/hw/bsp/imxrt/boards/mimxrt1015_evk/board/pin_mux.h index c9cbe3b72..2f3bf2c4c 100644 --- a/hw/bsp/imxrt/boards/mimxrt1015_evk/board/pin_mux.h +++ b/hw/bsp/imxrt/boards/mimxrt1015_evk/board/pin_mux.h @@ -37,7 +37,7 @@ extern "C" { */ void BOARD_InitBootPins(void); -/* GPIO_EMC_09 (number 1), USER_BUTTON */ +/* GPIO_EMC_09 (number 1), USER_BUTTON/SW4 */ /* Routed pin properties */ #define BOARD_INITPINS_USER_BUTTON_PERIPHERAL GPIO2 /*!< Peripheral name */ #define BOARD_INITPINS_USER_BUTTON_SIGNAL gpio_io /*!< Signal name */ @@ -51,16 +51,6 @@ void BOARD_InitBootPins(void); #define BOARD_INITPINS_USER_BUTTON_PIN 9U /*!< PORT pin number */ #define BOARD_INITPINS_USER_BUTTON_PIN_MASK (1U << 9U) /*!< PORT pin mask */ -/* GPIO_AD_B0_07 (number 68), LPUART1_RXD */ -/* Routed pin properties */ -#define BOARD_INITPINS_UART1_RXD_PERIPHERAL LPUART1 /*!< Peripheral name */ -#define BOARD_INITPINS_UART1_RXD_SIGNAL RX /*!< Signal name */ - -/* GPIO_AD_B0_06 (number 72), LPUART1_TXD */ -/* Routed pin properties */ -#define BOARD_INITPINS_UART1_TXD_PERIPHERAL LPUART1 /*!< Peripheral name */ -#define BOARD_INITPINS_UART1_TXD_SIGNAL TX /*!< Signal name */ - /* GPIO_SD_B1_01 (number 21), GPIO SD_B1_01 */ /* Routed pin properties */ #define BOARD_INITPINS_USER_LED_PERIPHERAL GPIO3 /*!< Peripheral name */ @@ -69,6 +59,7 @@ void BOARD_InitBootPins(void); /* Symbols to be used with GPIO driver */ #define BOARD_INITPINS_USER_LED_GPIO GPIO3 /*!< GPIO peripheral base pointer */ +#define BOARD_INITPINS_USER_LED_INIT_GPIO_VALUE 0U /*!< GPIO output initial state */ #define BOARD_INITPINS_USER_LED_GPIO_PIN 21U /*!< GPIO pin number */ #define BOARD_INITPINS_USER_LED_GPIO_PIN_MASK (1U << 21U) /*!< GPIO pin mask */ #define BOARD_INITPINS_USER_LED_PORT GPIO3 /*!< PORT peripheral base pointer */ @@ -119,6 +110,23 @@ void BOARD_InitPins(void); */ void BOARD_InitQSPIPins(void); +/* GPIO_AD_B0_07 (number 68), LPUART1_RXD */ +/* Routed pin properties */ +#define BOARD_INITDEBUG_UARTPINS_UART1_RXD_PERIPHERAL LPUART1 /*!< Peripheral name */ +#define BOARD_INITDEBUG_UARTPINS_UART1_RXD_SIGNAL RX /*!< Signal name */ + +/* GPIO_AD_B0_06 (number 72), LPUART1_TXD */ +/* Routed pin properties */ +#define BOARD_INITDEBUG_UARTPINS_UART1_TXD_PERIPHERAL LPUART1 /*!< Peripheral name */ +#define BOARD_INITDEBUG_UARTPINS_UART1_TXD_SIGNAL TX /*!< Signal name */ + + +/*! + * @brief Configures pin routing and optionally pin electrical features. + * + */ +void BOARD_InitDEBUG_UARTPins(void); + #if defined(__cplusplus) } #endif diff --git a/hw/bsp/imxrt/boards/mimxrt1015_evk/mimxrt1015_evk.mex b/hw/bsp/imxrt/boards/mimxrt1015_evk/mimxrt1015_evk.mex index 88265d32e..917bed375 100644 --- a/hw/bsp/imxrt/boards/mimxrt1015_evk/mimxrt1015_evk.mex +++ b/hw/bsp/imxrt/boards/mimxrt1015_evk/mimxrt1015_evk.mex @@ -1,5 +1,5 @@ - + MIMXRT1015xxxxx MIMXRT1015DAF5A @@ -13,19 +13,18 @@ true - false false true false - + - 13.0.2 + 24.12.10 @@ -45,12 +44,7 @@ true - - - true - - - + true @@ -79,12 +73,6 @@ - - - - - - @@ -100,7 +88,7 @@ true - + true @@ -125,15 +113,52 @@ + + Configures pin routing and optionally pin electrical features. + + true + core0 + true + + + + + true + + + + + true + + + + + true + + + + + + + + + + + + + + + + - + - 13.0.2 + 24.12.10 diff --git a/hw/bsp/imxrt/boards/mimxrt1020_evk/board.h b/hw/bsp/imxrt/boards/mimxrt1020_evk/board.h index 4f4593524..3f9c97e11 100644 --- a/hw/bsp/imxrt/boards/mimxrt1020_evk/board.h +++ b/hw/bsp/imxrt/boards/mimxrt1020_evk/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: i.MX RT1020 Evaluation Kit + url: https://www.nxp.com/design/design-center/development-boards-and-designs/MIMXRT1020-EVK +*/ + #ifndef BOARD_MIMXRT1020_EVK_H_ #define BOARD_MIMXRT1020_EVK_H_ diff --git a/hw/bsp/imxrt/boards/mimxrt1024_evk/board.h b/hw/bsp/imxrt/boards/mimxrt1024_evk/board.h index 27a64b464..39e63c472 100644 --- a/hw/bsp/imxrt/boards/mimxrt1024_evk/board.h +++ b/hw/bsp/imxrt/boards/mimxrt1024_evk/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: i.MX RT1024 Evaluation Kit + url: https://www.nxp.com/design/design-center/development-boards-and-designs/i-mx-evaluation-and-development-boards/i-mx-rt1024-evaluation-kit:MIMXRT1024-EVK +*/ + #ifndef BOARD_MIMXRT1024_EVK_H_ #define BOARD_MIMXRT1024_EVK_H_ diff --git a/hw/bsp/imxrt/boards/mimxrt1050_evkb/board.h b/hw/bsp/imxrt/boards/mimxrt1050_evkb/board.h index 97d1e446c..de7ab0535 100644 --- a/hw/bsp/imxrt/boards/mimxrt1050_evkb/board.h +++ b/hw/bsp/imxrt/boards/mimxrt1050_evkb/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: i.MX RT1050 Evaluation Kit revB + url: https://www.nxp.com/part/IMXRT1050-EVKB +*/ + #ifndef BOARD_MIMXRT1050_EVKB_H_ #define BOARD_MIMXRT1050_EVKB_H_ diff --git a/hw/bsp/imxrt/boards/mimxrt1060_evk/board.h b/hw/bsp/imxrt/boards/mimxrt1060_evk/board.h index 40b99860f..5bbacadaf 100644 --- a/hw/bsp/imxrt/boards/mimxrt1060_evk/board.h +++ b/hw/bsp/imxrt/boards/mimxrt1060_evk/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: i.MX RT1060 Evaluation Kit revB + url: https://www.nxp.com/design/design-center/development-boards-and-designs/MIMXRT1060-EVKB +*/ + #ifndef BOARD_MIMXRT1060_EVKB_H_ #define BOARD_MIMXRT1060_EVKB_H_ diff --git a/hw/bsp/imxrt/boards/mimxrt1064_evk/board.h b/hw/bsp/imxrt/boards/mimxrt1064_evk/board.h index 7fca5adef..6dc01e3e7 100644 --- a/hw/bsp/imxrt/boards/mimxrt1064_evk/board.h +++ b/hw/bsp/imxrt/boards/mimxrt1064_evk/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: i.MX RT1064 Evaluation Kit + url: https://www.nxp.com/design/design-center/development-boards-and-designs/MIMXRT1064-EVK +*/ + #ifndef BOARD_MIMXRT1064_EVKB_H_ #define BOARD_MIMXRT1064_EVKB_H_ diff --git a/hw/bsp/imxrt/boards/mimxrt1064_evk/board/clock_config.c b/hw/bsp/imxrt/boards/mimxrt1064_evk/board/clock_config.c index 778ab02f2..be684faee 100644 --- a/hw/bsp/imxrt/boards/mimxrt1064_evk/board/clock_config.c +++ b/hw/bsp/imxrt/boards/mimxrt1064_evk/board/clock_config.c @@ -15,11 +15,11 @@ /* TEXT BELOW IS USED AS SETTING FOR TOOLS ************************************* !!GlobalInfo -product: Clocks v11.0 +product: Clocks v15.0 processor: MIMXRT1064xxxxA package_id: MIMXRT1064DVL6A mcu_data: ksdk2_0 -processor_version: 13.0.2 +processor_version: 24.12.10 board: MIMXRT1064-EVK * BE CAREFUL MODIFYING THIS COMMENT - IT IS YAML SETTINGS FOR TOOLS **********/ diff --git a/hw/bsp/imxrt/boards/mimxrt1064_evk/board/clock_config.h b/hw/bsp/imxrt/boards/mimxrt1064_evk/board/clock_config.h index 7ce24b6f4..2fa713c0d 100644 --- a/hw/bsp/imxrt/boards/mimxrt1064_evk/board/clock_config.h +++ b/hw/bsp/imxrt/boards/mimxrt1064_evk/board/clock_config.h @@ -36,56 +36,56 @@ void BOARD_InitBootClocks(void); #define BOARD_BOOTCLOCKRUN_CORE_CLOCK 600000000U /*!< Core clock frequency: 600000000Hz */ /* Clock outputs (values are in Hz): */ -#define BOARD_BOOTCLOCKRUN_AHB_CLK_ROOT 600000000UL -#define BOARD_BOOTCLOCKRUN_CAN_CLK_ROOT 40000000UL -#define BOARD_BOOTCLOCKRUN_CKIL_SYNC_CLK_ROOT 32768UL -#define BOARD_BOOTCLOCKRUN_CLKO1_CLK 0UL -#define BOARD_BOOTCLOCKRUN_CLKO2_CLK 0UL -#define BOARD_BOOTCLOCKRUN_CLK_1M 1000000UL -#define BOARD_BOOTCLOCKRUN_CLK_24M 24000000UL -#define BOARD_BOOTCLOCKRUN_CSI_CLK_ROOT 12000000UL -#define BOARD_BOOTCLOCKRUN_ENET2_125M_CLK 1200000UL -#define BOARD_BOOTCLOCKRUN_ENET2_REF_CLK 0UL -#define BOARD_BOOTCLOCKRUN_ENET2_TX_CLK 0UL -#define BOARD_BOOTCLOCKRUN_ENET_125M_CLK 2400000UL -#define BOARD_BOOTCLOCKRUN_ENET_25M_REF_CLK 1200000UL -#define BOARD_BOOTCLOCKRUN_ENET_REF_CLK 0UL -#define BOARD_BOOTCLOCKRUN_ENET_TX_CLK 0UL -#define BOARD_BOOTCLOCKRUN_FLEXIO1_CLK_ROOT 30000000UL -#define BOARD_BOOTCLOCKRUN_FLEXIO2_CLK_ROOT 30000000UL -#define BOARD_BOOTCLOCKRUN_FLEXSPI2_CLK_ROOT 130909090UL -#define BOARD_BOOTCLOCKRUN_FLEXSPI_CLK_ROOT 130909090UL -#define BOARD_BOOTCLOCKRUN_GPT1_IPG_CLK_HIGHFREQ 75000000UL -#define BOARD_BOOTCLOCKRUN_GPT2_IPG_CLK_HIGHFREQ 75000000UL -#define BOARD_BOOTCLOCKRUN_IPG_CLK_ROOT 150000000UL -#define BOARD_BOOTCLOCKRUN_LCDIF_CLK_ROOT 67500000UL -#define BOARD_BOOTCLOCKRUN_LPI2C_CLK_ROOT 60000000UL -#define BOARD_BOOTCLOCKRUN_LPSPI_CLK_ROOT 105600000UL -#define BOARD_BOOTCLOCKRUN_LVDS1_CLK 1200000000UL -#define BOARD_BOOTCLOCKRUN_MQS_MCLK 63529411UL -#define BOARD_BOOTCLOCKRUN_PERCLK_CLK_ROOT 75000000UL -#define BOARD_BOOTCLOCKRUN_PLL7_MAIN_CLK 480000000UL -#define BOARD_BOOTCLOCKRUN_SAI1_CLK_ROOT 63529411UL -#define BOARD_BOOTCLOCKRUN_SAI1_MCLK1 63529411UL -#define BOARD_BOOTCLOCKRUN_SAI1_MCLK2 63529411UL -#define BOARD_BOOTCLOCKRUN_SAI1_MCLK3 30000000UL -#define BOARD_BOOTCLOCKRUN_SAI2_CLK_ROOT 63529411UL -#define BOARD_BOOTCLOCKRUN_SAI2_MCLK1 63529411UL -#define BOARD_BOOTCLOCKRUN_SAI2_MCLK2 0UL -#define BOARD_BOOTCLOCKRUN_SAI2_MCLK3 30000000UL -#define BOARD_BOOTCLOCKRUN_SAI3_CLK_ROOT 63529411UL -#define BOARD_BOOTCLOCKRUN_SAI3_MCLK1 63529411UL -#define BOARD_BOOTCLOCKRUN_SAI3_MCLK2 0UL -#define BOARD_BOOTCLOCKRUN_SAI3_MCLK3 30000000UL -#define BOARD_BOOTCLOCKRUN_SEMC_CLK_ROOT 75000000UL -#define BOARD_BOOTCLOCKRUN_SPDIF0_CLK_ROOT 30000000UL -#define BOARD_BOOTCLOCKRUN_SPDIF0_EXTCLK_OUT 0UL -#define BOARD_BOOTCLOCKRUN_TRACE_CLK_ROOT 132000000UL -#define BOARD_BOOTCLOCKRUN_UART_CLK_ROOT 80000000UL -#define BOARD_BOOTCLOCKRUN_USBPHY1_CLK 480000000UL -#define BOARD_BOOTCLOCKRUN_USBPHY2_CLK 480000000UL -#define BOARD_BOOTCLOCKRUN_USDHC1_CLK_ROOT 198000000UL -#define BOARD_BOOTCLOCKRUN_USDHC2_CLK_ROOT 198000000UL +#define BOARD_BOOTCLOCKRUN_AHB_CLK_ROOT 600000000UL /* Clock consumers of AHB_CLK_ROOT output : AIPSTZ1, AIPSTZ2, AIPSTZ3, AIPSTZ4, ARM, FLEXIO3, FLEXSPI, FLEXSPI2, GPIO6, GPIO7, GPIO8, GPIO9 */ +#define BOARD_BOOTCLOCKRUN_CAN_CLK_ROOT 40000000UL /* Clock consumers of CAN_CLK_ROOT output : CAN1, CAN2, CAN3 */ +#define BOARD_BOOTCLOCKRUN_CKIL_SYNC_CLK_ROOT 32768UL /* Clock consumers of CKIL_SYNC_CLK_ROOT output : CSU, EWM, GPT1, GPT2, KPP, PIT, RTWDOG, SNVS, SPDIF, TEMPMON, TSC, USB1, USB2, WDOG1, WDOG2 */ +#define BOARD_BOOTCLOCKRUN_CLKO1_CLK 0UL /* Clock consumers of CLKO1_CLK output : N/A */ +#define BOARD_BOOTCLOCKRUN_CLKO2_CLK 0UL /* Clock consumers of CLKO2_CLK output : N/A */ +#define BOARD_BOOTCLOCKRUN_CLK_1M 1000000UL /* Clock consumers of CLK_1M output : EWM, RTWDOG */ +#define BOARD_BOOTCLOCKRUN_CLK_24M 24000000UL /* Clock consumers of CLK_24M output : GPT1, GPT2 */ +#define BOARD_BOOTCLOCKRUN_CSI_CLK_ROOT 12000000UL /* Clock consumers of CSI_CLK_ROOT output : CSI */ +#define BOARD_BOOTCLOCKRUN_ENET2_125M_CLK 1200000UL /* Clock consumers of ENET2_125M_CLK output : N/A */ +#define BOARD_BOOTCLOCKRUN_ENET2_REF_CLK 0UL /* Clock consumers of ENET2_REF_CLK output : ENET2 */ +#define BOARD_BOOTCLOCKRUN_ENET2_TX_CLK 0UL /* Clock consumers of ENET2_TX_CLK output : ENET2 */ +#define BOARD_BOOTCLOCKRUN_ENET_125M_CLK 2400000UL /* Clock consumers of ENET_125M_CLK output : N/A */ +#define BOARD_BOOTCLOCKRUN_ENET_25M_REF_CLK 1200000UL /* Clock consumers of ENET_25M_REF_CLK output : ENET, ENET2 */ +#define BOARD_BOOTCLOCKRUN_ENET_REF_CLK 0UL /* Clock consumers of ENET_REF_CLK output : ENET */ +#define BOARD_BOOTCLOCKRUN_ENET_TX_CLK 0UL /* Clock consumers of ENET_TX_CLK output : ENET */ +#define BOARD_BOOTCLOCKRUN_FLEXIO1_CLK_ROOT 30000000UL /* Clock consumers of FLEXIO1_CLK_ROOT output : FLEXIO1 */ +#define BOARD_BOOTCLOCKRUN_FLEXIO2_CLK_ROOT 30000000UL /* Clock consumers of FLEXIO2_CLK_ROOT output : FLEXIO2, FLEXIO3 */ +#define BOARD_BOOTCLOCKRUN_FLEXSPI2_CLK_ROOT 130909090UL /* Clock consumers of FLEXSPI2_CLK_ROOT output : FLEXSPI2 */ +#define BOARD_BOOTCLOCKRUN_FLEXSPI_CLK_ROOT 130909090UL /* Clock consumers of FLEXSPI_CLK_ROOT output : FLEXSPI */ +#define BOARD_BOOTCLOCKRUN_GPT1_IPG_CLK_HIGHFREQ 75000000UL /* Clock consumers of GPT1_ipg_clk_highfreq output : GPT1 */ +#define BOARD_BOOTCLOCKRUN_GPT2_IPG_CLK_HIGHFREQ 75000000UL /* Clock consumers of GPT2_ipg_clk_highfreq output : GPT2 */ +#define BOARD_BOOTCLOCKRUN_IPG_CLK_ROOT 150000000UL /* Clock consumers of IPG_CLK_ROOT output : ADC1, ADC2, ADC_ETC, AOI1, AOI2, ARM, BEE, CAN1, CAN2, CAN3, CCM, CMP1, CMP2, CMP3, CMP4, CSI, CSU, DCDC, DCP, DMA0, DMAMUX, ENC1, ENC2, ENC3, ENC4, ENET, ENET2, EWM, FLEXIO1, FLEXIO2, FLEXIO3, FLEXRAM, FLEXSPI, FLEXSPI2, GPC, GPIO1, GPIO10, GPIO2, GPIO3, GPIO4, GPIO5, IOMUXC, KPP, LCDIF, LPI2C1, LPI2C2, LPI2C3, LPI2C4, LPSPI1, LPSPI2, LPSPI3, LPSPI4, LPUART1, LPUART2, LPUART3, LPUART4, LPUART5, LPUART6, LPUART7, LPUART8, NVIC, OCOTP, PMU, PWM1, PWM2, PWM3, PWM4, PXP, ROMC, RTWDOG, SAI1, SAI2, SAI3, SNVS, SPDIF, SRC, TEMPMON, TMR1, TMR2, TMR3, TMR4, TRNG, TSC, USB1, USB2, USDHC1, USDHC2, WDOG1, WDOG2, XBARA1, XBARB2, XBARB3 */ +#define BOARD_BOOTCLOCKRUN_LCDIF_CLK_ROOT 67500000UL /* Clock consumers of LCDIF_CLK_ROOT output : LCDIF */ +#define BOARD_BOOTCLOCKRUN_LPI2C_CLK_ROOT 60000000UL /* Clock consumers of LPI2C_CLK_ROOT output : LPI2C1, LPI2C2, LPI2C3, LPI2C4 */ +#define BOARD_BOOTCLOCKRUN_LPSPI_CLK_ROOT 105600000UL /* Clock consumers of LPSPI_CLK_ROOT output : LPSPI1, LPSPI2, LPSPI3, LPSPI4 */ +#define BOARD_BOOTCLOCKRUN_LVDS1_CLK 1200000000UL /* Clock consumers of LVDS1_CLK output : N/A */ +#define BOARD_BOOTCLOCKRUN_MQS_MCLK 63529411UL /* Clock consumers of MQS_MCLK output : N/A */ +#define BOARD_BOOTCLOCKRUN_PERCLK_CLK_ROOT 75000000UL /* Clock consumers of PERCLK_CLK_ROOT output : GPT1, GPT2, PIT */ +#define BOARD_BOOTCLOCKRUN_PLL7_MAIN_CLK 480000000UL /* Clock consumers of PLL7_MAIN_CLK output : N/A */ +#define BOARD_BOOTCLOCKRUN_SAI1_CLK_ROOT 63529411UL /* Clock consumers of SAI1_CLK_ROOT output : N/A */ +#define BOARD_BOOTCLOCKRUN_SAI1_MCLK1 63529411UL /* Clock consumers of SAI1_MCLK1 output : SAI1 */ +#define BOARD_BOOTCLOCKRUN_SAI1_MCLK2 63529411UL /* Clock consumers of SAI1_MCLK2 output : SAI1 */ +#define BOARD_BOOTCLOCKRUN_SAI1_MCLK3 30000000UL /* Clock consumers of SAI1_MCLK3 output : SAI1 */ +#define BOARD_BOOTCLOCKRUN_SAI2_CLK_ROOT 63529411UL /* Clock consumers of SAI2_CLK_ROOT output : N/A */ +#define BOARD_BOOTCLOCKRUN_SAI2_MCLK1 63529411UL /* Clock consumers of SAI2_MCLK1 output : SAI2 */ +#define BOARD_BOOTCLOCKRUN_SAI2_MCLK2 0UL /* Clock consumers of SAI2_MCLK2 output : SAI2 */ +#define BOARD_BOOTCLOCKRUN_SAI2_MCLK3 30000000UL /* Clock consumers of SAI2_MCLK3 output : SAI2 */ +#define BOARD_BOOTCLOCKRUN_SAI3_CLK_ROOT 63529411UL /* Clock consumers of SAI3_CLK_ROOT output : N/A */ +#define BOARD_BOOTCLOCKRUN_SAI3_MCLK1 63529411UL /* Clock consumers of SAI3_MCLK1 output : SAI3 */ +#define BOARD_BOOTCLOCKRUN_SAI3_MCLK2 0UL /* Clock consumers of SAI3_MCLK2 output : SAI3 */ +#define BOARD_BOOTCLOCKRUN_SAI3_MCLK3 30000000UL /* Clock consumers of SAI3_MCLK3 output : SAI3 */ +#define BOARD_BOOTCLOCKRUN_SEMC_CLK_ROOT 75000000UL /* Clock consumers of SEMC_CLK_ROOT output : SEMC */ +#define BOARD_BOOTCLOCKRUN_SPDIF0_CLK_ROOT 30000000UL /* Clock consumers of SPDIF0_CLK_ROOT output : SPDIF */ +#define BOARD_BOOTCLOCKRUN_SPDIF0_EXTCLK_OUT 0UL /* Clock consumers of SPDIF0_EXTCLK_OUT output : SPDIF */ +#define BOARD_BOOTCLOCKRUN_TRACE_CLK_ROOT 132000000UL /* Clock consumers of TRACE_CLK_ROOT output : ARM */ +#define BOARD_BOOTCLOCKRUN_UART_CLK_ROOT 80000000UL /* Clock consumers of UART_CLK_ROOT output : LPUART1, LPUART2, LPUART3, LPUART4, LPUART5, LPUART6, LPUART7, LPUART8 */ +#define BOARD_BOOTCLOCKRUN_USBPHY1_CLK 480000000UL /* Clock consumers of USBPHY1_CLK output : TEMPMON, USB1 */ +#define BOARD_BOOTCLOCKRUN_USBPHY2_CLK 480000000UL /* Clock consumers of USBPHY2_CLK output : USB2 */ +#define BOARD_BOOTCLOCKRUN_USDHC1_CLK_ROOT 198000000UL /* Clock consumers of USDHC1_CLK_ROOT output : USDHC1 */ +#define BOARD_BOOTCLOCKRUN_USDHC2_CLK_ROOT 198000000UL /* Clock consumers of USDHC2_CLK_ROOT output : USDHC2 */ /*! @brief Arm PLL set for BOARD_BootClockRUN configuration. */ diff --git a/hw/bsp/imxrt/boards/mimxrt1064_evk/board/pin_mux.c b/hw/bsp/imxrt/boards/mimxrt1064_evk/board/pin_mux.c index 8e975dc72..60c4bab37 100644 --- a/hw/bsp/imxrt/boards/mimxrt1064_evk/board/pin_mux.c +++ b/hw/bsp/imxrt/boards/mimxrt1064_evk/board/pin_mux.c @@ -6,11 +6,11 @@ /* * TEXT BELOW IS USED AS SETTING FOR TOOLS ************************************* !!GlobalInfo -product: Pins v13.1 +product: Pins v17.0 processor: MIMXRT1064xxxxA package_id: MIMXRT1064DVL6A mcu_data: ksdk2_0 -processor_version: 13.0.2 +processor_version: 24.12.10 board: MIMXRT1064-EVK pin_labels: - {pin_num: F14, pin_signal: GPIO_AD_B0_09, label: 'JTAG_TDI/J21[5]/ENET_RST/J22[5]', identifier: USER_LED} @@ -81,7 +81,6 @@ void BOARD_InitPins(void) { IOMUXC_SetPinConfig(IOMUXC_GPIO_AD_B0_09_GPIO1_IO09, 0x50A0U); } - /* * TEXT BELOW IS USED AS SETTING FOR TOOLS ************************************* BOARD_InitDEBUG_UARTPins: @@ -109,7 +108,6 @@ void BOARD_InitDEBUG_UARTPins(void) { IOMUXC_SetPinConfig(IOMUXC_GPIO_AD_B0_13_LPUART1_RX, 0x10B0U); } - /* * TEXT BELOW IS USED AS SETTING FOR TOOLS ************************************* BOARD_InitSDRAMPins: @@ -209,7 +207,6 @@ void BOARD_InitSDRAMPins(void) { IOMUXC_SetPinMux(IOMUXC_GPIO_EMC_39_SEMC_DQS, 0U); } - /* * TEXT BELOW IS USED AS SETTING FOR TOOLS ************************************* BOARD_InitCSIPins: @@ -267,7 +264,6 @@ void BOARD_InitCSIPins(void) { IOMUXC_SetPinConfig(IOMUXC_GPIO_AD_B1_01_LPI2C1_SDA, 0xD8B0U); } - /* * TEXT BELOW IS USED AS SETTING FOR TOOLS ************************************* BOARD_InitLCDPins: @@ -360,7 +356,6 @@ void BOARD_InitLCDPins(void) { IOMUXC_SetPinConfig(IOMUXC_GPIO_B1_15_GPIO2_IO31, 0x10B0U); } - /* * TEXT BELOW IS USED AS SETTING FOR TOOLS ************************************* BOARD_InitCANPins: @@ -384,7 +379,6 @@ void BOARD_InitCANPins(void) { IOMUXC_SetPinMux(IOMUXC_GPIO_AD_B0_15_FLEXCAN2_RX, 0U); } - /* * TEXT BELOW IS USED AS SETTING FOR TOOLS ************************************* BOARD_InitENETPins: @@ -424,7 +418,6 @@ void BOARD_InitENETPins(void) { IOMUXC_SetPinMux(IOMUXC_GPIO_EMC_41_ENET_MDIO, 0U); } - /* * TEXT BELOW IS USED AS SETTING FOR TOOLS ************************************* BOARD_InitUSDHCPins: @@ -458,7 +451,6 @@ void BOARD_InitUSDHCPins(void) { IOMUXC_SetPinMux(IOMUXC_GPIO_SD_B0_05_USDHC1_DATA3, 0U); } - /* * TEXT BELOW IS USED AS SETTING FOR TOOLS ************************************* BOARD_InitQSPIPins: @@ -491,7 +483,6 @@ void BOARD_InitQSPIPins(void) { IOMUXC_SetPinMux(IOMUXC_GPIO_SD_B1_10_FLEXSPIA_DATA02, 0U); IOMUXC_SetPinMux(IOMUXC_GPIO_SD_B1_11_FLEXSPIA_DATA03, 0U); } - /*********************************************************************************************************************** * EOF **********************************************************************************************************************/ diff --git a/hw/bsp/imxrt/boards/mimxrt1064_evk/board/pin_mux.h b/hw/bsp/imxrt/boards/mimxrt1064_evk/board/pin_mux.h index bf494b6f6..be1461f16 100644 --- a/hw/bsp/imxrt/boards/mimxrt1064_evk/board/pin_mux.h +++ b/hw/bsp/imxrt/boards/mimxrt1064_evk/board/pin_mux.h @@ -47,6 +47,7 @@ void BOARD_InitBootPins(void); /* Symbols to be used with GPIO driver */ #define BOARD_INITPINS_USER_LED_GPIO GPIO1 /*!< GPIO peripheral base pointer */ +#define BOARD_INITPINS_USER_LED_INIT_GPIO_VALUE 0U /*!< GPIO output initial state */ #define BOARD_INITPINS_USER_LED_GPIO_PIN 9U /*!< GPIO pin number */ #define BOARD_INITPINS_USER_LED_GPIO_PIN_MASK (1U << 9U) /*!< GPIO pin mask */ #define BOARD_INITPINS_USER_LED_PORT GPIO1 /*!< PORT peripheral base pointer */ diff --git a/hw/bsp/imxrt/boards/mimxrt1064_evk/mimxrt1064_evk.mex b/hw/bsp/imxrt/boards/mimxrt1064_evk/mimxrt1064_evk.mex index 3f0948101..58247fa5b 100644 --- a/hw/bsp/imxrt/boards/mimxrt1064_evk/mimxrt1064_evk.mex +++ b/hw/bsp/imxrt/boards/mimxrt1064_evk/mimxrt1064_evk.mex @@ -1,5 +1,5 @@ - + MIMXRT1064xxxxA MIMXRT1064DVL6A @@ -13,19 +13,18 @@ true - false false true false - + - 13.0.2 + 24.12.10 @@ -41,7 +40,7 @@ true - + true @@ -84,7 +83,7 @@ true - + true @@ -137,7 +136,7 @@ true - + true @@ -204,12 +203,12 @@ true - + true - + true @@ -277,7 +276,7 @@ true - + true @@ -450,7 +449,7 @@ true - + true @@ -479,7 +478,7 @@ true - + true @@ -516,7 +515,7 @@ true - + true @@ -550,7 +549,7 @@ true - + true @@ -578,13 +577,13 @@ - + - 13.0.2 + 24.12.10 @@ -751,10 +750,7 @@ - - - - + 13.0.2 diff --git a/hw/bsp/imxrt/boards/mimxrt1170_evkb/board.cmake b/hw/bsp/imxrt/boards/mimxrt1170_evkb/board.cmake index 692d9e498..d5629f8ba 100644 --- a/hw/bsp/imxrt/boards/mimxrt1170_evkb/board.cmake +++ b/hw/bsp/imxrt/boards/mimxrt1170_evkb/board.cmake @@ -1,8 +1,17 @@ set(MCU_VARIANT MIMXRT1176) -set(MCU_CORE _cm7) -set(JLINK_DEVICE MIMXRT1176xxxA_M7) -set(PYOCD_TARGET mimxrt1170_cm7) +if (M4 STREQUAL "1") + set(MCU_CORE _cm4) + set(JLINK_CORE _M4) + set(LD_FILE_GNU ${SDK_DIR}/devices/${MCU_VARIANT}/gcc/${MCU_VARIANT}xxxxx${MCU_CORE}_ram.ld) + set(CMAKE_SYSTEM_CPU cortex-m4 CACHE INTERNAL "System Processor") +else () + set(MCU_CORE _cm7) + set(JLINK_CORE _M7) +endif() + +set(JLINK_DEVICE MIMXRT1176xxxA${JLINK_CORE}) +set(PYOCD_TARGET mimxrt1170${MCU_CORE}) set(NXPLINK_DEVICE MIMXRT1176xxxxx:MIMXRT1170-EVK) function(update_board TARGET) @@ -10,7 +19,7 @@ function(update_board TARGET) ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/evkbmimxrt1170_flexspi_nor_config.c ) target_compile_definitions(${TARGET} PUBLIC - CPU_MIMXRT1176DVMAA_cm7 + CPU_MIMXRT1176DVMAA${MCU_CORE} BOARD_TUD_RHPORT=0 BOARD_TUH_RHPORT=1 ) diff --git a/hw/bsp/imxrt/boards/mimxrt1170_evkb/board.h b/hw/bsp/imxrt/boards/mimxrt1170_evkb/board.h index 303935517..c5d54b7a7 100644 --- a/hw/bsp/imxrt/boards/mimxrt1170_evkb/board.h +++ b/hw/bsp/imxrt/boards/mimxrt1170_evkb/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: i.MX RT1070 Evaluation Kit + url: https://www.nxp.com/design/design-center/development-boards-and-designs/i-mx-evaluation-and-development-boards/i-mx-rt1170-evaluation-kit:MIMXRT1170-EVKB +*/ + #ifndef BOARD_MIMXRT1170_EVKB_H_ #define BOARD_MIMXRT1170_EVKB_H_ diff --git a/hw/bsp/imxrt/boards/mimxrt1170_evkb/board.mk b/hw/bsp/imxrt/boards/mimxrt1170_evkb/board.mk index e8500a4c9..8270ae587 100644 --- a/hw/bsp/imxrt/boards/mimxrt1170_evkb/board.mk +++ b/hw/bsp/imxrt/boards/mimxrt1170_evkb/board.mk @@ -1,12 +1,22 @@ -CFLAGS += -DCPU_MIMXRT1176DVMAA_cm7 MCU_VARIANT = MIMXRT1176 -MCU_CORE = _cm7 + +ifeq ($(M4), 1) + MCU_CORE = _cm4 + JLINK_CORE = _M4 + CPU_CORE = cortex-m4 + LD_FILE ?= $(MCU_DIR)/gcc/$(MCU_VARIANT)xxxxx${MCU_CORE}_ram.ld +else + MCU_CORE = _cm7 + JLINK_CORE = _M7 +endif + +CFLAGS += -DCPU_MIMXRT1176DVMAA$(MCU_CORE) # For flash-jlink target -JLINK_DEVICE = MIMXRT1176xxxA_M7 +JLINK_DEVICE = MIMXRT1176xxxA$(JLINK_CORE) # For flash-pyocd target -PYOCD_TARGET = mimxrt1170_cm7 +PYOCD_TARGET = mimxrt1170$(MCU_CORE) BOARD_TUD_RHPORT = 0 BOARD_TUH_RHPORT = 1 diff --git a/hw/bsp/imxrt/boards/mimxrt1170_evkb/board/clock_config.c b/hw/bsp/imxrt/boards/mimxrt1170_evkb/board/clock_config.c index 88b3b3770..4f06299de 100644 --- a/hw/bsp/imxrt/boards/mimxrt1170_evkb/board/clock_config.c +++ b/hw/bsp/imxrt/boards/mimxrt1170_evkb/board/clock_config.c @@ -11,11 +11,11 @@ /* TEXT BELOW IS USED AS SETTING FOR TOOLS ************************************* !!GlobalInfo -product: Clocks v12.0 +product: Clocks v15.0 processor: MIMXRT1176xxxxx package_id: MIMXRT1176DVMAA mcu_data: ksdk2_0 -processor_version: 14.0.1 +processor_version: 24.12.10 board: MIMXRT1170-EVKB * BE CAREFUL MODIFYING THIS COMMENT - IT IS YAML SETTINGS FOR TOOLS **********/ @@ -335,7 +335,6 @@ void BOARD_BootClockRUN(void) /* Init OSC RC 400M */ CLOCK_OSC_EnableOscRc400M(); - CLOCK_OSC_GateOscRc400M(false); /* Init OSC RC 48M */ CLOCK_OSC_EnableOsc48M(true); @@ -349,22 +348,29 @@ void BOARD_BootClockRUN(void) { } - /* Switch both core, M7 Systick and Bus_Lpsr to OscRC48MDiv2 first */ + /* Switch core M7 clock root to OscRC48MDiv2 first */ #if __CORTEX_M == 7 rootCfg.mux = kCLOCK_M7_ClockRoot_MuxOscRc48MDiv2; rootCfg.div = 1; CLOCK_SetRootClock(kCLOCK_Root_M7, &rootCfg); +#endif + /* Switch core M7 systick clock root to OscRC48MDiv2 first */ +#if __CORTEX_M == 7 rootCfg.mux = kCLOCK_M7_SYSTICK_ClockRoot_MuxOscRc48MDiv2; rootCfg.div = 1; CLOCK_SetRootClock(kCLOCK_Root_M7_Systick, &rootCfg); #endif + /* Switch core M4 clock root to OscRC48MDiv2 first */ #if __CORTEX_M == 4 rootCfg.mux = kCLOCK_M4_ClockRoot_MuxOscRc48MDiv2; rootCfg.div = 1; CLOCK_SetRootClock(kCLOCK_Root_M4, &rootCfg); +#endif + /* Switch the Bus_Lpsr clock root to OscRC48MDiv2 first */ +#if __CORTEX_M == 4 rootCfg.mux = kCLOCK_BUS_LPSR_ClockRoot_MuxOscRc48MDiv2; rootCfg.div = 1; CLOCK_SetRootClock(kCLOCK_Root_Bus_Lpsr, &rootCfg); diff --git a/hw/bsp/imxrt/boards/mimxrt1170_evkb/board/clock_config.h b/hw/bsp/imxrt/boards/mimxrt1170_evkb/board/clock_config.h index 4a4d35eaa..f68724314 100644 --- a/hw/bsp/imxrt/boards/mimxrt1170_evkb/board/clock_config.h +++ b/hw/bsp/imxrt/boards/mimxrt1170_evkb/board/clock_config.h @@ -48,7 +48,7 @@ void BOARD_InitBootClocks(void); #define BOARD_BOOTCLOCKRUN_ARM_PLL_CLK 996000000UL /* Clock consumers of ARM_PLL_CLK output : N/A */ #define BOARD_BOOTCLOCKRUN_ASRC_CLK_ROOT 24000000UL /* Clock consumers of ASRC_CLK_ROOT output : ASRC */ #define BOARD_BOOTCLOCKRUN_AXI_CLK_ROOT 996000000UL /* Clock consumers of AXI_CLK_ROOT output : FLEXRAM */ -#define BOARD_BOOTCLOCKRUN_BUS_CLK_ROOT 240000000UL /* Clock consumers of BUS_CLK_ROOT output : ADC_ETC, AOI1, AOI2, CAAM, CAN1, CAN2, CM7_GPIO2, CM7_GPIO3, CMP1, CMP2, CMP3, CMP4, CSI, DAC, DMA0, DMAMUX0, DSI_HOST, EMVSIM1, EMVSIM2, ENC1, ENC2, ENC3, ENC4, ENET, ENET_1G, ENET_QOS, EWM, FLEXIO1, FLEXIO2, FLEXSPI1, FLEXSPI2, GPIO1, GPIO2, GPIO3, GPIO4, GPIO5, GPIO6, IEE_APC, IOMUXC, IOMUXC_GPR, KPP, LCDIF, LCDIFV2, LPADC1, LPADC2, LPI2C1, LPI2C2, LPI2C3, LPI2C4, LPSPI1, LPSPI2, LPSPI3, LPSPI4, LPUART1, LPUART10, LPUART2, LPUART3, LPUART4, LPUART5, LPUART6, LPUART7, LPUART8, LPUART9, MECC1, MECC2, MIPI_CSI2RX, PIT1, PWM1, PWM2, PWM3, PWM4, PXP, RTWDOG3, SAI1, SAI2, SAI3, SPDIF, TMR1, TMR2, TMR3, TMR4, USBPHY1, USBPHY2, USB_OTG1, USB_OTG2, USDHC1, USDHC2, WDOG1, WDOG2, XBARA1, XBARB2, XBARB3, XECC_FLEXSPI1, XECC_FLEXSPI2, XECC_SEMC, XRDC2_D0, XRDC2_D1 */ +#define BOARD_BOOTCLOCKRUN_BUS_CLK_ROOT 240000000UL /* Clock consumers of BUS_CLK_ROOT output : ADC_ETC, AOI1, AOI2, CAAM, CAN1, CAN2, CM7_GPIO2, CM7_GPIO3, CMP1, CMP2, CMP3, CMP4, CSI, DAC, DMA0, DMAMUX0, DSI_HOST, EMVSIM1, EMVSIM2, ENC1, ENC2, ENC3, ENC4, ENET, ENET_1G, ENET_QOS, EWM, FLEXIO1, FLEXIO2, FLEXSPI1, FLEXSPI2, GPIO1, GPIO2, GPIO3, GPIO4, GPIO5, GPIO6, IEE_APC, IEE__IEE_RT1170, IOMUXC, IOMUXC_GPR, KPP, LCDIF, LCDIFV2, LPADC1, LPADC2, LPI2C1, LPI2C2, LPI2C3, LPI2C4, LPSPI1, LPSPI2, LPSPI3, LPSPI4, LPUART1, LPUART10, LPUART2, LPUART3, LPUART4, LPUART5, LPUART6, LPUART7, LPUART8, LPUART9, MECC1, MECC2, MIPI_CSI2RX, PIT1, PWM1, PWM2, PWM3, PWM4, PXP, RTWDOG3, SAI1, SAI2, SAI3, SPDIF, TMR1, TMR2, TMR3, TMR4, USBPHY1, USBPHY2, USB_OTG1, USB_OTG2, USDHC1, USDHC2, WDOG1, WDOG2, XBARA1, XBARB2, XBARB3, XECC_FLEXSPI1, XECC_FLEXSPI2, XECC_SEMC, XRDC2_D0, XRDC2_D1 */ #define BOARD_BOOTCLOCKRUN_BUS_LPSR_CLK_ROOT 160000000UL /* Clock consumers of BUS_LPSR_CLK_ROOT output : CAN3, GPIO10, GPIO11, GPIO12, GPIO7, GPIO8, GPIO9, IOMUXC_LPSR, LPI2C5, LPI2C6, LPSPI5, LPSPI6, LPUART11, LPUART12, MUA, MUB, PDM, PIT2, RDC, RTWDOG4, SAI4, SNVS, XRDC2_D0, XRDC2_D1 */ #define BOARD_BOOTCLOCKRUN_CAN1_CLK_ROOT 24000000UL /* Clock consumers of CAN1_CLK_ROOT output : CAN1 */ #define BOARD_BOOTCLOCKRUN_CAN2_CLK_ROOT 24000000UL /* Clock consumers of CAN2_CLK_ROOT output : CAN2 */ diff --git a/hw/bsp/imxrt/boards/mimxrt1170_evkb/board/pin_mux.c b/hw/bsp/imxrt/boards/mimxrt1170_evkb/board/pin_mux.c index 81ffb35e3..5e8cb91c1 100644 --- a/hw/bsp/imxrt/boards/mimxrt1170_evkb/board/pin_mux.c +++ b/hw/bsp/imxrt/boards/mimxrt1170_evkb/board/pin_mux.c @@ -6,11 +6,11 @@ /* * TEXT BELOW IS USED AS SETTING FOR TOOLS ************************************* !!GlobalInfo -product: Pins v14.0 +product: Pins v17.0 processor: MIMXRT1176xxxxx package_id: MIMXRT1176DVMAA mcu_data: ksdk2_0 -processor_version: 14.0.1 +processor_version: 24.12.10 board: MIMXRT1170-EVKB external_user_signals: {} pin_labels: @@ -31,6 +31,7 @@ pin_labels: * END ****************************************************************************************************************/ void BOARD_InitBootPins(void) { BOARD_InitPins(); + BOARD_InitDEBUG_UARTPins(); } /* @@ -38,10 +39,6 @@ void BOARD_InitBootPins(void) { BOARD_InitPins: - options: {callFromInitBoot: 'true', coreID: cm7, enableClock: 'true'} - pin_list: - - {pin_num: M15, peripheral: LPUART1, signal: RXD, pin_signal: GPIO_AD_25, software_input_on: Disable, pull_up_down_config: Pull_Down, pull_keeper_select: Keeper, - open_drain: Disable, drive_strength: High, slew_rate: Slow} - - {pin_num: L13, peripheral: LPUART1, signal: TXD, pin_signal: GPIO_AD_24, software_input_on: Disable, pull_up_down_config: Pull_Down, pull_keeper_select: Keeper, - open_drain: Disable, drive_strength: High, slew_rate: Slow} - {pin_num: M13, peripheral: GPIO9, signal: 'gpio_io, 03', pin_signal: GPIO_AD_04, identifier: USER_LED, direction: OUTPUT, pull_up_down_config: Pull_Down, pull_keeper_select: Keeper} - {pin_num: T8, peripheral: GPIO13, signal: 'gpio_io, 00', pin_signal: WAKEUP, direction: INPUT, pull_up_down_config: Pull_Up} * BE CAREFUL MODIFYING THIS COMMENT - IT IS YAML SETTINGS FOR TOOLS *********** @@ -77,12 +74,6 @@ void BOARD_InitPins(void) { IOMUXC_SetPinMux( IOMUXC_GPIO_AD_04_GPIO9_IO03, /* GPIO_AD_04 is configured as GPIO9_IO03 */ 0U); /* Software Input On Field: Input Path is determined by functionality */ - IOMUXC_SetPinMux( - IOMUXC_GPIO_AD_24_LPUART1_TXD, /* GPIO_AD_24 is configured as LPUART1_TXD */ - 0U); /* Software Input On Field: Input Path is determined by functionality */ - IOMUXC_SetPinMux( - IOMUXC_GPIO_AD_25_LPUART1_RXD, /* GPIO_AD_25 is configured as LPUART1_RXD */ - 0U); /* Software Input On Field: Input Path is determined by functionality */ IOMUXC_SetPinMux( IOMUXC_WAKEUP_DIG_GPIO13_IO00, /* WAKEUP_DIG is configured as GPIO13_IO00 */ 0U); /* Software Input On Field: Input Path is determined by functionality */ @@ -90,16 +81,50 @@ void BOARD_InitPins(void) { IOMUXC_GPIO_AD_04_GPIO9_IO03, /* GPIO_AD_04 PAD functional properties : */ 0x02U); /* Slew Rate Field: Slow Slew Rate Drive Strength Field: high drive strength - Pull / Keep Select Field: Pull Disable, Highz + Pull / Keep Select Field: Pull Disable Pull Up / Down Config. Field: Weak pull down Open Drain Field: Disabled Domain write protection: Both cores are allowed Domain write protection lock: Neither of DWP bits is locked */ + IOMUXC_SetPinConfig( + IOMUXC_WAKEUP_DIG_GPIO13_IO00, /* WAKEUP_DIG PAD functional properties : */ + 0x0EU); /* Pull / Keep Select Field: Pull Enable + Pull Up / Down Config. Field: Weak pull up + Open Drain SNVS Field: Disabled + Domain write protection: Both cores are allowed + Domain write protection lock: Neither of DWP bits is locked */ +} + +/* + * TEXT BELOW IS USED AS SETTING FOR TOOLS ************************************* +BOARD_InitDEBUG_UARTPins: +- options: {callFromInitBoot: 'true', coreID: cm7, enableClock: 'true'} +- pin_list: + - {pin_num: L13, peripheral: LPUART1, signal: TXD, pin_signal: GPIO_AD_24, pull_keeper_select: Keeper, slew_rate: Slow} + - {pin_num: M15, peripheral: LPUART1, signal: RXD, pin_signal: GPIO_AD_25, pull_keeper_select: Keeper, slew_rate: Slow} + * BE CAREFUL MODIFYING THIS COMMENT - IT IS YAML SETTINGS FOR TOOLS *********** + */ + +/* FUNCTION ************************************************************************************************************ + * + * Function Name : BOARD_InitDEBUG_UARTPins, assigned for the Cortex-M7F core. + * Description : Configures pin routing and optionally pin electrical features. + * + * END ****************************************************************************************************************/ +void BOARD_InitDEBUG_UARTPins(void) { + CLOCK_EnableClock(kCLOCK_Iomuxc); /* LPCG on: LPCG is ON. */ + + IOMUXC_SetPinMux( + IOMUXC_GPIO_AD_24_LPUART1_TXD, /* GPIO_AD_24 is configured as LPUART1_TXD */ + 0U); /* Software Input On Field: Input Path is determined by functionality */ + IOMUXC_SetPinMux( + IOMUXC_GPIO_AD_25_LPUART1_RXD, /* GPIO_AD_25 is configured as LPUART1_RXD */ + 0U); /* Software Input On Field: Input Path is determined by functionality */ IOMUXC_SetPinConfig( IOMUXC_GPIO_AD_24_LPUART1_TXD, /* GPIO_AD_24 PAD functional properties : */ 0x02U); /* Slew Rate Field: Slow Slew Rate Drive Strength Field: high drive strength - Pull / Keep Select Field: Pull Disable, Highz + Pull / Keep Select Field: Pull Disable Pull Up / Down Config. Field: Weak pull down Open Drain Field: Disabled Domain write protection: Both cores are allowed @@ -108,22 +133,12 @@ void BOARD_InitPins(void) { IOMUXC_GPIO_AD_25_LPUART1_RXD, /* GPIO_AD_25 PAD functional properties : */ 0x02U); /* Slew Rate Field: Slow Slew Rate Drive Strength Field: high drive strength - Pull / Keep Select Field: Pull Disable, Highz + Pull / Keep Select Field: Pull Disable Pull Up / Down Config. Field: Weak pull down Open Drain Field: Disabled Domain write protection: Both cores are allowed Domain write protection lock: Neither of DWP bits is locked */ - IOMUXC_SetPinConfig( - IOMUXC_WAKEUP_DIG_GPIO13_IO00, /* WAKEUP_DIG PAD functional properties : */ - 0x0EU); /* Slew Rate Field: Slow Slew Rate - Drive Strength Field: high driver - Pull / Keep Select Field: Pull Enable - Pull Up / Down Config. Field: Weak pull up - Open Drain SNVS Field: Disabled - Domain write protection: Both cores are allowed - Domain write protection lock: Neither of DWP bits is locked */ } - /*********************************************************************************************************************** * EOF **********************************************************************************************************************/ diff --git a/hw/bsp/imxrt/boards/mimxrt1170_evkb/board/pin_mux.h b/hw/bsp/imxrt/boards/mimxrt1170_evkb/board/pin_mux.h index 550bd1474..0e0368ef6 100644 --- a/hw/bsp/imxrt/boards/mimxrt1170_evkb/board/pin_mux.h +++ b/hw/bsp/imxrt/boards/mimxrt1170_evkb/board/pin_mux.h @@ -25,16 +25,6 @@ extern "C" { */ void BOARD_InitBootPins(void); -/* GPIO_AD_25 (coord M15), LPUART1_RXD */ -/* Routed pin properties */ -#define BOARD_INITPINS_LPUART1_RXD_PERIPHERAL LPUART1 /*!< Peripheral name */ -#define BOARD_INITPINS_LPUART1_RXD_SIGNAL RXD /*!< Signal name */ - -/* GPIO_AD_24 (coord L13), LPUART1_TXD */ -/* Routed pin properties */ -#define BOARD_INITPINS_LPUART1_TXD_PERIPHERAL LPUART1 /*!< Peripheral name */ -#define BOARD_INITPINS_LPUART1_TXD_SIGNAL TXD /*!< Signal name */ - /* GPIO_AD_04 (coord M13), SIM1_PD/J44[C8]/USER_LED_CTL1/J9[8]/J25[7] */ /* Routed pin properties */ #define BOARD_INITPINS_USER_LED_PERIPHERAL GPIO9 /*!< Peripheral name */ @@ -43,10 +33,11 @@ void BOARD_InitBootPins(void); /* Symbols to be used with GPIO driver */ #define BOARD_INITPINS_USER_LED_GPIO GPIO9 /*!< GPIO peripheral base pointer */ +#define BOARD_INITPINS_USER_LED_INIT_GPIO_VALUE 0U /*!< GPIO output initial state */ #define BOARD_INITPINS_USER_LED_GPIO_PIN 3U /*!< GPIO pin number */ #define BOARD_INITPINS_USER_LED_GPIO_PIN_MASK (1U << 3U) /*!< GPIO pin mask */ -/* WAKEUP (coord T8), USER_BUTTON */ +/* WAKEUP (coord T8), USER_BUTTON/SW7 */ /* Routed pin properties */ #define BOARD_INITPINS_USER_BUTTON_PERIPHERAL GPIO13 /*!< Peripheral name */ #define BOARD_INITPINS_USER_BUTTON_SIGNAL gpio_io /*!< Signal name */ @@ -63,6 +54,22 @@ void BOARD_InitBootPins(void); */ void BOARD_InitPins(void); /* Function assigned for the Cortex-M7F */ +/* GPIO_AD_24 (coord L13), LPUART1_TXD */ +/* Routed pin properties */ +#define BOARD_INITDEBUG_UARTPINS_LPUART1_TXD_PERIPHERAL LPUART1 /*!< Peripheral name */ +#define BOARD_INITDEBUG_UARTPINS_LPUART1_TXD_SIGNAL TXD /*!< Signal name */ + +/* GPIO_AD_25 (coord M15), LPUART1_RXD */ +/* Routed pin properties */ +#define BOARD_INITDEBUG_UARTPINS_LPUART1_RXD_PERIPHERAL LPUART1 /*!< Peripheral name */ +#define BOARD_INITDEBUG_UARTPINS_LPUART1_RXD_SIGNAL RXD /*!< Signal name */ + +/*! + * @brief Configures pin routing and optionally pin electrical features. + * + */ +void BOARD_InitDEBUG_UARTPins(void); /* Function assigned for the Cortex-M7F */ + #if defined(__cplusplus) } #endif diff --git a/hw/bsp/imxrt/boards/mimxrt1170_evkb/mimxrt1170_evkb.mex b/hw/bsp/imxrt/boards/mimxrt1170_evkb/mimxrt1170_evkb.mex index e68b9ea7e..de6b12394 100644 --- a/hw/bsp/imxrt/boards/mimxrt1170_evkb/mimxrt1170_evkb.mex +++ b/hw/bsp/imxrt/boards/mimxrt1170_evkb/mimxrt1170_evkb.mex @@ -1,5 +1,5 @@ - + MIMXRT1176xxxxx MIMXRT1176DVMAA @@ -13,24 +13,22 @@ true - false false true false - + - 14.0.1 + 24.12.10 - @@ -44,11 +42,6 @@ true - - - true - - true @@ -66,26 +59,6 @@ - - - - - - - - - - - - - - - - - - - - @@ -102,15 +75,54 @@ + + Configures pin routing and optionally pin electrical features. + + true + cm7 + true + + + + + true + + + + + true + + + + + true + + + + + + + + + + + + + + + + + + - + - 14.0.1 + 24.12.10 diff --git a/hw/bsp/imxrt/boards/teensy_40/board.h b/hw/bsp/imxrt/boards/teensy_40/board.h index 4a173c834..ae749e894 100644 --- a/hw/bsp/imxrt/boards/teensy_40/board.h +++ b/hw/bsp/imxrt/boards/teensy_40/board.h @@ -24,11 +24,14 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Teensy 4.0 + url: https://www.pjrc.com/store/teensy40.html +*/ #ifndef BOARD_H_ #define BOARD_H_ - // required since iMXRT MCUX-SDK include this file for board size #define BOARD_FLASH_SIZE (2 * 1024 * 1024) diff --git a/hw/bsp/imxrt/boards/teensy_41/board.h b/hw/bsp/imxrt/boards/teensy_41/board.h index 358684126..1bc022c54 100644 --- a/hw/bsp/imxrt/boards/teensy_41/board.h +++ b/hw/bsp/imxrt/boards/teensy_41/board.h @@ -24,11 +24,14 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Teensy 4.1 + url: https://www.pjrc.com/store/teensy41.html +*/ #ifndef BOARD_H_ #define BOARD_H_ - // required since iMXRT MCUX-SDK include this file for board size #define BOARD_FLASH_SIZE (8 * 1024 * 1024) diff --git a/hw/bsp/imxrt/family.c b/hw/bsp/imxrt/family.c index 6087ee37d..7e4734a66 100644 --- a/hw/bsp/imxrt/family.c +++ b/hw/bsp/imxrt/family.c @@ -24,6 +24,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: NXP +*/ + #include "bsp/board_api.h" #include "board/clock_config.h" #include "board/pin_mux.h" @@ -31,23 +35,36 @@ // Suppress warning caused by mcu driver #ifdef __GNUC__ -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wunused-parameter" + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wunused-parameter" #endif +#include "fsl_clock.h" #include "fsl_device_registers.h" #include "fsl_gpio.h" #include "fsl_iomuxc.h" -#include "fsl_clock.h" #include "fsl_lpuart.h" #include "fsl_ocotp.h" #ifdef __GNUC__ -#pragma GCC diagnostic pop + #pragma GCC diagnostic pop #endif +/* --- Note about USB buffer RAM --- + For M7 core it's recommended to put USB buffer in DTCM for better performance (flexspi_nor linker default) + Otherwise you have to put the buffer in a non-cacheable section by configurate MPU manually or using BOARD_ConfigMPU(): + - Define CFG_TUSB_MEM_SECTION=__attribute__((section("NonCacheable"))) + - (IAR only) Change __NCACHE_REGION_SIZE in linker script to cover the size of non-cacheable section, multiple of 2^N + + For secondary M4 core, the USB controller doesn't support transfer from DTCM so OCRAM must be used: + - __NCACHE_REGION_SIZE is defined by the linker script by default + - Define CFG_TUSB_MEM_SECTION=__attribute__((section("NonCacheable"))) +*/ + +// static void BOARD_ConfigMPU(void); + // needed by fsl_flexspi_nor_boot -TU_ATTR_USED const uint8_t dcd_data[] = { 0x00 }; +TU_ATTR_USED const uint8_t dcd_data[] = {0x00}; //--------------------------------------------------------------------+ // @@ -59,20 +76,20 @@ TU_ATTR_USED const uint8_t dcd_data[] = { 0x00 }; #endif static void init_usb_phy(uint8_t usb_id) { - USBPHY_Type* usb_phy; + USBPHY_Type *usb_phy; if (usb_id == 0) { usb_phy = USBPHY1; CLOCK_EnableUsbhs0PhyPllClock(kCLOCK_Usbphy480M, BOARD_XTAL0_CLK_HZ); CLOCK_EnableUsbhs0Clock(kCLOCK_Usb480M, BOARD_XTAL0_CLK_HZ); } - #ifdef USBPHY2 +#ifdef USBPHY2 else if (usb_id == 1) { usb_phy = USBPHY2; CLOCK_EnableUsbhs1PhyPllClock(kCLOCK_Usbphy480M, BOARD_XTAL0_CLK_HZ); CLOCK_EnableUsbhs1Clock(kCLOCK_Usb480M, BOARD_XTAL0_CLK_HZ); } - #endif +#endif else { return; } @@ -91,14 +108,9 @@ static void init_usb_phy(uint8_t usb_id) { usb_phy->TX = phytx; } -void board_init(void) -{ - // make sure the dcache is on. -#if defined(__DCACHE_PRESENT) && __DCACHE_PRESENT - if (SCB_CCR_DC_Msk != (SCB_CCR_DC_Msk & SCB->CCR)) SCB_EnableDCache(); -#endif - - BOARD_InitPins(); +void board_init(void) { + // BOARD_ConfigMPU(); + BOARD_InitBootPins(); BOARD_BootClockRUN(); SystemCoreClockUpdate(); @@ -113,9 +125,9 @@ void board_init(void) #elif CFG_TUSB_OS == OPT_OS_FREERTOS // If freeRTOS is used, IRQ priority is limit by max syscall ( smaller is higher ) NVIC_SetPriority(USB_OTG1_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY); -#ifdef USBPHY2 + #ifdef USBPHY2 NVIC_SetPriority(USB_OTG2_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY); -#endif + #endif #endif board_led_write(true); @@ -127,16 +139,16 @@ void board_init(void) uart_config.enableTx = true; uart_config.enableRx = true; - if ( kStatus_Success != LPUART_Init(UART_PORT, &uart_config, UART_CLK_ROOT) ) { + if (kStatus_Success != LPUART_Init(UART_PORT, &uart_config, UART_CLK_ROOT)) { // failed to init uart, probably baudrate is not supported // TU_BREAKPOINT(); } //------------- USB -------------// // Note: RT105x RT106x and later have dual USB controllers. - init_usb_phy(0); // USB0 + init_usb_phy(0);// USB0 #ifdef USBPHY2 - init_usb_phy(1); // USB1 + init_usb_phy(1);// USB1 #endif } @@ -166,18 +178,18 @@ uint32_t board_button_read(void) { size_t board_get_unique_id(uint8_t id[], size_t max_len) { (void) max_len; - #if FSL_FEATURE_OCOTP_HAS_TIMING_CTRL +#if FSL_FEATURE_OCOTP_HAS_TIMING_CTRL OCOTP_Init(OCOTP, CLOCK_GetFreq(kCLOCK_IpgClk)); - #else +#else OCOTP_Init(OCOTP, 0u); - #endif +#endif // Reads shadow registers 0x01 - 0x04 (Configuration and Manufacturing Info) // into 8 bit wide destination, avoiding punning. for (int i = 0; i < 4; ++i) { uint32_t wr = OCOTP_ReadFuseShadowRegister(OCOTP, i + 1); for (int j = 0; j < 4; j++) { - id[i*4+j] = wr & 0xff; + id[i * 4 + j] = wr & 0xff; wr >>= 8; } } @@ -186,7 +198,7 @@ size_t board_get_unique_id(uint8_t id[], size_t max_len) { return 16; } -int board_uart_read(uint8_t* buf, int len) { +int board_uart_read(uint8_t *buf, int len) { int count = 0; while (count < len) { @@ -209,8 +221,8 @@ int board_uart_read(uint8_t* buf, int len) { return count; } -int board_uart_write(void const * buf, int len) { - LPUART_WriteBlocking(UART_PORT, (uint8_t const*)buf, len); +int board_uart_write(void const *buf, int len) { + LPUART_WriteBlocking(UART_PORT, (uint8_t const *) buf, len); return len; } @@ -237,9 +249,392 @@ TU_ATTR_UNUSED void _start(void) { } #ifdef __clang__ -void _exit (int __status) { +void _exit(int __status) { while (1) {} } #endif - +#endif + +//-------------------------------------------------------------------- +// MPU configuration +//-------------------------------------------------------------------- +#if 0 // TODO move to per board specific +#if __CORTEX_M == 7 +static void BOARD_ConfigMPU(void) { + #if defined(__CC_ARM) || defined(__ARMCC_VERSION) + extern uint32_t Image$$RW_m_ncache$$Base[]; + /* RW_m_ncache_unused is a auxiliary region which is used to get the whole size of noncache section */ + extern uint32_t Image$$RW_m_ncache_unused$$Base[]; + extern uint32_t Image$$RW_m_ncache_unused$$ZI$$Limit[]; + uint32_t nonCacheStart = (uint32_t) Image$$RW_m_ncache$$Base; + uint32_t size = ((uint32_t) Image$$RW_m_ncache_unused$$Base == nonCacheStart) ? 0 : ((uint32_t) Image$$RW_m_ncache_unused$$ZI$$Limit - nonCacheStart); + #elif defined(__MCUXPRESSO) + #if defined(__USE_SHMEM) + extern uint32_t __base_rpmsg_sh_mem; + extern uint32_t __top_rpmsg_sh_mem; + uint32_t nonCacheStart = (uint32_t) (&__base_rpmsg_sh_mem); + uint32_t size = (uint32_t) (&__top_rpmsg_sh_mem) - nonCacheStart; + #else + extern uint32_t __base_NCACHE_REGION; + extern uint32_t __top_NCACHE_REGION; + uint32_t nonCacheStart = (uint32_t) (&__base_NCACHE_REGION); + uint32_t size = (uint32_t) (&__top_NCACHE_REGION) - nonCacheStart; + #endif + #elif defined(__ICCARM__) || defined(__GNUC__) + extern uint32_t __NCACHE_REGION_START[]; + extern uint32_t __NCACHE_REGION_SIZE[]; + uint32_t nonCacheStart = (uint32_t) __NCACHE_REGION_START; + uint32_t size = (uint32_t) __NCACHE_REGION_SIZE; + #endif + volatile uint32_t i = 0; + + #if defined(__ICACHE_PRESENT) && __ICACHE_PRESENT + /* Disable I cache and D cache */ + if (SCB_CCR_IC_Msk == (SCB_CCR_IC_Msk & SCB->CCR)) { + SCB_DisableICache(); + } + #endif + #if defined(__DCACHE_PRESENT) && __DCACHE_PRESENT + if (SCB_CCR_DC_Msk == (SCB_CCR_DC_Msk & SCB->CCR)) { + SCB_DisableDCache(); + } + #endif + + /* Disable MPU */ + ARM_MPU_Disable(); + + /* MPU configure: + * Use ARM_MPU_RASR(DisableExec, AccessPermission, TypeExtField, IsShareable, IsCacheable, IsBufferable, + * SubRegionDisable, Size) + * API in mpu_armv7.h. + * param DisableExec Instruction access (XN) disable bit,0=instruction fetches enabled, 1=instruction fetches + * disabled. + * param AccessPermission Data access permissions, allows you to configure read/write access for User and + * Privileged mode. + * Use MACROS defined in mpu_armv7.h: + * ARM_MPU_AP_NONE/ARM_MPU_AP_PRIV/ARM_MPU_AP_URO/ARM_MPU_AP_FULL/ARM_MPU_AP_PRO/ARM_MPU_AP_RO + * Combine TypeExtField/IsShareable/IsCacheable/IsBufferable to configure MPU memory access attributes. + * TypeExtField IsShareable IsCacheable IsBufferable Memory Attribute Shareability Cache + * 0 x 0 0 Strongly Ordered shareable + * 0 x 0 1 Device shareable + * 0 0 1 0 Normal not shareable Outer and inner write + * through no write allocate + * 0 0 1 1 Normal not shareable Outer and inner write + * back no write allocate + * 0 1 1 0 Normal shareable Outer and inner write + * through no write allocate + * 0 1 1 1 Normal shareable Outer and inner write + * back no write allocate + * 1 0 0 0 Normal not shareable outer and inner + * noncache + * 1 1 0 0 Normal shareable outer and inner + * noncache + * 1 0 1 1 Normal not shareable outer and inner write + * back write/read acllocate + * 1 1 1 1 Normal shareable outer and inner write + * back write/read acllocate + * 2 x 0 0 Device not shareable + * Above are normal use settings, if your want to see more details or want to config different inner/outer cache + * policy. + * please refer to Table 4-55 /4-56 in arm cortex-M7 generic user guide + * param SubRegionDisable Sub-region disable field. 0=sub-region is enabled, 1=sub-region is disabled. + * param Size Region size of the region to be configured. use ARM_MPU_REGION_SIZE_xxx MACRO in + * mpu_armv7.h. + */ + + /* + * Add default region to deny access to whole address space to workaround speculative prefetch. + * Refer to Arm errata 1013783-B for more details. + * + */ + /* Region 0 setting: Instruction access disabled, No data access permission. */ + MPU->RBAR = ARM_MPU_RBAR(0, 0x00000000U); + MPU->RASR = ARM_MPU_RASR(1, ARM_MPU_AP_NONE, 0, 0, 0, 0, 0, ARM_MPU_REGION_SIZE_4GB); + + /* Region 1 setting: Memory with Device type, not shareable, non-cacheable. */ + MPU->RBAR = ARM_MPU_RBAR(1, 0x80000000U); + MPU->RASR = ARM_MPU_RASR(0, ARM_MPU_AP_FULL, 2, 0, 0, 0, 0, ARM_MPU_REGION_SIZE_512MB); + + /* Region 2 setting: Memory with Device type, not shareable, non-cacheable. */ + MPU->RBAR = ARM_MPU_RBAR(2, 0x60000000U); + MPU->RASR = ARM_MPU_RASR(0, ARM_MPU_AP_FULL, 2, 0, 0, 0, 0, ARM_MPU_REGION_SIZE_512MB); + + /* Region 3 setting: Memory with Device type, not shareable, non-cacheable. */ + MPU->RBAR = ARM_MPU_RBAR(3, 0x00000000U); + MPU->RASR = ARM_MPU_RASR(0, ARM_MPU_AP_FULL, 2, 0, 0, 0, 0, ARM_MPU_REGION_SIZE_1GB); + + /* Region 4 setting: Memory with Normal type, not shareable, outer/inner write back */ + MPU->RBAR = ARM_MPU_RBAR(4, 0x00000000U); + MPU->RASR = ARM_MPU_RASR(0, ARM_MPU_AP_FULL, 0, 0, 1, 1, 0, ARM_MPU_REGION_SIZE_256KB); + + /* Region 5 setting: Memory with Normal type, not shareable, outer/inner write back */ + MPU->RBAR = ARM_MPU_RBAR(5, 0x20000000U); + MPU->RASR = ARM_MPU_RASR(0, ARM_MPU_AP_FULL, 0, 0, 1, 1, 0, ARM_MPU_REGION_SIZE_256KB); + + #if defined(CACHE_MODE_WRITE_THROUGH) && CACHE_MODE_WRITE_THROUGH + /* Region 6 setting: Memory with Normal type, not shareable, write through */ + MPU->RBAR = ARM_MPU_RBAR(6, 0x20200000U); + MPU->RASR = ARM_MPU_RASR(0, ARM_MPU_AP_FULL, 0, 0, 1, 0, 0, ARM_MPU_REGION_SIZE_1MB); + + /* Region 7 setting: Memory with Normal type, not shareable, write through */ + MPU->RBAR = ARM_MPU_RBAR(7, 0x20300000U); + MPU->RASR = ARM_MPU_RASR(0, ARM_MPU_AP_FULL, 0, 0, 1, 0, 0, ARM_MPU_REGION_SIZE_512KB); + #else + /* Region 6 setting: Memory with Normal type, not shareable, outer/inner write back */ + MPU->RBAR = ARM_MPU_RBAR(6, 0x20200000U); + MPU->RASR = ARM_MPU_RASR(0, ARM_MPU_AP_FULL, 0, 0, 1, 1, 0, ARM_MPU_REGION_SIZE_1MB); + + /* Region 7 setting: Memory with Normal type, not shareable, outer/inner write back */ + MPU->RBAR = ARM_MPU_RBAR(7, 0x20300000U); + MPU->RASR = ARM_MPU_RASR(0, ARM_MPU_AP_FULL, 0, 0, 1, 1, 0, ARM_MPU_REGION_SIZE_512KB); + #endif + + #if defined(XIP_EXTERNAL_FLASH) && (XIP_EXTERNAL_FLASH == 1) + /* Region 8 setting: Memory with Normal type, not shareable, outer/inner write back. */ + MPU->RBAR = ARM_MPU_RBAR(8, 0x30000000U); + MPU->RASR = ARM_MPU_RASR(0, ARM_MPU_AP_RO, 0, 0, 1, 1, 0, ARM_MPU_REGION_SIZE_16MB); + #endif + + #ifdef USE_SDRAM + #if defined(CACHE_MODE_WRITE_THROUGH) && CACHE_MODE_WRITE_THROUGH + /* Region 9 setting: Memory with Normal type, not shareable, write through */ + MPU->RBAR = ARM_MPU_RBAR(9, 0x80000000U); + MPU->RASR = ARM_MPU_RASR(0, ARM_MPU_AP_FULL, 0, 0, 1, 0, 0, ARM_MPU_REGION_SIZE_64MB); + #else + /* Region 9 setting: Memory with Normal type, not shareable, outer/inner write back */ + MPU->RBAR = ARM_MPU_RBAR(9, 0x80000000U); + MPU->RASR = ARM_MPU_RASR(0, ARM_MPU_AP_FULL, 0, 0, 1, 1, 0, ARM_MPU_REGION_SIZE_64MB); + #endif + #endif + + while ((size >> i) > 0x1U) { + i++; + } + + if (i != 0) { + /* The MPU region size should be 2^N, 5<=N<=32, region base should be multiples of size. */ + assert(!(nonCacheStart % size)); + assert(size == (uint32_t) (1 << i)); + assert(i >= 5); + + /* Region 10 setting: Memory with Normal type, not shareable, non-cacheable */ + MPU->RBAR = ARM_MPU_RBAR(10, nonCacheStart); + MPU->RASR = ARM_MPU_RASR(0, ARM_MPU_AP_FULL, 1, 0, 0, 0, 0, i - 1); + } + + /* Region 11 setting: Memory with Device type, not shareable, non-cacheable */ + MPU->RBAR = ARM_MPU_RBAR(11, 0x40000000); + MPU->RASR = ARM_MPU_RASR(0, ARM_MPU_AP_FULL, 2, 0, 0, 0, 0, ARM_MPU_REGION_SIZE_16MB); + + /* Region 12 setting: Memory with Device type, not shareable, non-cacheable */ + MPU->RBAR = ARM_MPU_RBAR(12, 0x41000000); + MPU->RASR = ARM_MPU_RASR(0, ARM_MPU_AP_FULL, 2, 0, 0, 0, 0, ARM_MPU_REGION_SIZE_2MB); + + /* Region 13 setting: Memory with Device type, not shareable, non-cacheable */ + MPU->RBAR = ARM_MPU_RBAR(13, 0x41400000); + MPU->RASR = ARM_MPU_RASR(0, ARM_MPU_AP_FULL, 2, 0, 0, 0, 0, ARM_MPU_REGION_SIZE_1MB); + + /* Region 14 setting: Memory with Device type, not shareable, non-cacheable */ + MPU->RBAR = ARM_MPU_RBAR(14, 0x41800000); + MPU->RASR = ARM_MPU_RASR(0, ARM_MPU_AP_FULL, 2, 0, 0, 0, 0, ARM_MPU_REGION_SIZE_2MB); + + /* Region 15 setting: Memory with Device type, not shareable, non-cacheable */ + MPU->RBAR = ARM_MPU_RBAR(15, 0x42000000); + MPU->RASR = ARM_MPU_RASR(0, ARM_MPU_AP_FULL, 2, 0, 0, 0, 0, ARM_MPU_REGION_SIZE_1MB); + + /* Enable MPU */ + ARM_MPU_Enable(MPU_CTRL_PRIVDEFENA_Msk | MPU_CTRL_HFNMIENA_Msk); + + /* Enable I cache and D cache */ + #if defined(__DCACHE_PRESENT) && __DCACHE_PRESENT + SCB_EnableDCache(); + #endif + #if defined(__ICACHE_PRESENT) && __ICACHE_PRESENT + SCB_EnableICache(); + #endif +} + +#elif __CORTEX_M == 4 + +static void BOARD_ConfigMPU(void) { + #if defined(__CC_ARM) || defined(__ARMCC_VERSION) + extern uint32_t Image$$RW_m_ncache$$Base[]; + /* RW_m_ncache_unused is a auxiliary region which is used to get the whole size of noncache section */ + extern uint32_t Image$$RW_m_ncache_unused$$Base[]; + extern uint32_t Image$$RW_m_ncache_unused$$ZI$$Limit[]; + uint32_t nonCacheStart = (uint32_t) Image$$RW_m_ncache$$Base; + uint32_t nonCacheSize = ((uint32_t) Image$$RW_m_ncache_unused$$Base == nonCacheStart) ? 0 : ((uint32_t) Image$$RW_m_ncache_unused$$ZI$$Limit - nonCacheStart); + #elif defined(__MCUXPRESSO) + extern uint32_t __base_NCACHE_REGION; + extern uint32_t __top_NCACHE_REGION; + uint32_t nonCacheStart = (uint32_t) (&__base_NCACHE_REGION); + uint32_t nonCacheSize = (uint32_t) (&__top_NCACHE_REGION) - nonCacheStart; + #elif defined(__ICCARM__) || defined(__GNUC__) + extern uint32_t __NCACHE_REGION_START[]; + extern uint32_t __NCACHE_REGION_SIZE[]; + uint32_t nonCacheStart = (uint32_t) __NCACHE_REGION_START; + uint32_t nonCacheSize = (uint32_t) __NCACHE_REGION_SIZE; + #endif + #if defined(__USE_SHMEM) + #if defined(__CC_ARM) || defined(__ARMCC_VERSION) + extern uint32_t Image$$RPMSG_SH_MEM$$Base[]; + /* RPMSG_SH_MEM_unused is a auxiliary region which is used to get the whole size of RPMSG_SH_MEM section */ + extern uint32_t Image$$RPMSG_SH_MEM_unused$$Base[]; + extern uint32_t Image$$RPMSG_SH_MEM_unused$$ZI$$Limit[]; + uint32_t rpmsgShmemStart = (uint32_t) Image$$RPMSG_SH_MEM$$Base; + uint32_t rpmsgShmemSize = (uint32_t) Image$$RPMSG_SH_MEM_unused$$ZI$$Limit - rpmsgShmemStart; + #elif defined(__MCUXPRESSO) + extern uint32_t __base_rpmsg_sh_mem; + extern uint32_t __top_rpmsg_sh_mem; + uint32_t rpmsgShmemStart = (uint32_t) (&__base_rpmsg_sh_mem); + uint32_t rpmsgShmemSize = (uint32_t) (&__top_rpmsg_sh_mem) - rpmsgShmemStart; + #elif defined(__ICCARM__) || defined(__GNUC__) + extern uint32_t __RPMSG_SH_MEM_START[]; + extern uint32_t __RPMSG_SH_MEM_SIZE[]; + uint32_t rpmsgShmemStart = (uint32_t) __RPMSG_SH_MEM_START; + uint32_t rpmsgShmemSize = (uint32_t) __RPMSG_SH_MEM_SIZE; + #endif + #endif + uint32_t i = 0; + + /* Only config non-cacheable region on system bus */ + assert(nonCacheStart >= 0x20000000); + + /* Disable code bus cache */ + if (LMEM_PCCCR_ENCACHE_MASK == (LMEM_PCCCR_ENCACHE_MASK & LMEM->PCCCR)) { + /* Enable the processor code bus to push all modified lines. */ + LMEM->PCCCR |= LMEM_PCCCR_PUSHW0_MASK | LMEM_PCCCR_PUSHW1_MASK | LMEM_PCCCR_GO_MASK; + /* Wait until the cache command completes. */ + while ((LMEM->PCCCR & LMEM_PCCCR_GO_MASK) != 0U) { + } + /* As a precaution clear the bits to avoid inadvertently re-running this command. */ + LMEM->PCCCR &= ~(LMEM_PCCCR_PUSHW0_MASK | LMEM_PCCCR_PUSHW1_MASK); + /* Now disable the cache. */ + LMEM->PCCCR &= ~LMEM_PCCCR_ENCACHE_MASK; + } + + /* Disable system bus cache */ + if (LMEM_PSCCR_ENCACHE_MASK == (LMEM_PSCCR_ENCACHE_MASK & LMEM->PSCCR)) { + /* Enable the processor system bus to push all modified lines. */ + LMEM->PSCCR |= LMEM_PSCCR_PUSHW0_MASK | LMEM_PSCCR_PUSHW1_MASK | LMEM_PSCCR_GO_MASK; + /* Wait until the cache command completes. */ + while ((LMEM->PSCCR & LMEM_PSCCR_GO_MASK) != 0U) { + } + /* As a precaution clear the bits to avoid inadvertently re-running this command. */ + LMEM->PSCCR &= ~(LMEM_PSCCR_PUSHW0_MASK | LMEM_PSCCR_PUSHW1_MASK); + /* Now disable the cache. */ + LMEM->PSCCR &= ~LMEM_PSCCR_ENCACHE_MASK; + } + + /* Disable MPU */ + ARM_MPU_Disable(); + + #if defined(CACHE_MODE_WRITE_THROUGH) && CACHE_MODE_WRITE_THROUGH + /* Region 0 setting: Memory with Normal type, not shareable, write through */ + MPU->RBAR = ARM_MPU_RBAR(0, 0x20200000U); + MPU->RASR = ARM_MPU_RASR(0, ARM_MPU_AP_FULL, 0, 0, 1, 0, 0, ARM_MPU_REGION_SIZE_1MB); + + /* Region 1 setting: Memory with Normal type, not shareable, write through */ + MPU->RBAR = ARM_MPU_RBAR(1, 0x20300000U); + MPU->RASR = ARM_MPU_RASR(0, ARM_MPU_AP_FULL, 0, 0, 1, 0, 0, ARM_MPU_REGION_SIZE_512KB); + + /* Region 2 setting: Memory with Normal type, not shareable, write through */ + MPU->RBAR = ARM_MPU_RBAR(2, 0x80000000U); + MPU->RASR = ARM_MPU_RASR(0, ARM_MPU_AP_FULL, 0, 0, 1, 0, 0, ARM_MPU_REGION_SIZE_64MB); + + while ((nonCacheSize >> i) > 0x1U) { + i++; + } + + if (i != 0) { + /* The MPU region size should be 2^N, 5<=N<=32, region base should be multiples of size. */ + assert(!(nonCacheStart % nonCacheSize)); + assert(nonCacheSize == (uint32_t) (1 << i)); + assert(i >= 5); + + /* Region 3 setting: Memory with device type, not shareable, non-cacheable */ + MPU->RBAR = ARM_MPU_RBAR(3, nonCacheStart); + MPU->RASR = ARM_MPU_RASR(0, ARM_MPU_AP_FULL, 2, 0, 0, 0, 0, i - 1); + } + + #if defined(__USE_SHMEM) + i = 0; + + while ((rpmsgShmemSize >> i) > 0x1U) { + i++; + } + + if (i != 0) { + /* The MPU region size should be 2^N, 5<=N<=32, region base should be multiples of size. */ + assert(!(rpmsgShmemStart % rpmsgShmemSize)); + assert(rpmsgShmemSize == (uint32_t) (1 << i)); + assert(i >= 5); + + /* Region 4 setting: Memory with device type, not shareable, non-cacheable */ + MPU->RBAR = ARM_MPU_RBAR(4, rpmsgShmemStart); + MPU->RASR = ARM_MPU_RASR(0, ARM_MPU_AP_FULL, 2, 0, 0, 0, 0, i - 1); + } + #endif + #else + while ((nonCacheSize >> i) > 0x1U) { + i++; + } + + if (i != 0) { + /* The MPU region size should be 2^N, 5<=N<=32, region base should be multiples of size. */ + assert(!(nonCacheStart % nonCacheSize)); + assert(nonCacheSize == (uint32_t) (1 << i)); + assert(i >= 5); + + /* Region 0 setting: Memory with device type, not shareable, non-cacheable */ + MPU->RBAR = ARM_MPU_RBAR(0, nonCacheStart); + MPU->RASR = ARM_MPU_RASR(0, ARM_MPU_AP_FULL, 2, 0, 0, 0, 0, i - 1); + } + + #if defined(__USE_SHMEM) + i = 0; + + while ((rpmsgShmemSize >> i) > 0x1U) { + i++; + } + + if (i != 0) { + /* The MPU region size should be 2^N, 5<=N<=32, region base should be multiples of size. */ + assert(!(rpmsgShmemStart % rpmsgShmemSize)); + assert(rpmsgShmemSize == (uint32_t) (1 << i)); + assert(i >= 5); + + /* Region 1 setting: Memory with device type, not shareable, non-cacheable */ + MPU->RBAR = ARM_MPU_RBAR(1, rpmsgShmemStart); + MPU->RASR = ARM_MPU_RASR(0, ARM_MPU_AP_FULL, 2, 0, 0, 0, 0, i - 1); + } + #endif + #endif + + /* Enable MPU */ + ARM_MPU_Enable(MPU_CTRL_PRIVDEFENA_Msk | MPU_CTRL_HFNMIENA_Msk); + + /* Enables the processor system bus to invalidate all lines in both ways. + and Initiate the processor system bus cache command. */ + LMEM->PSCCR |= LMEM_PSCCR_INVW0_MASK | LMEM_PSCCR_INVW1_MASK | LMEM_PSCCR_GO_MASK; + /* Wait until the cache command completes */ + while ((LMEM->PSCCR & LMEM_PSCCR_GO_MASK) != 0U) { + } + /* As a precaution clear the bits to avoid inadvertently re-running this command. */ + LMEM->PSCCR &= ~(LMEM_PSCCR_INVW0_MASK | LMEM_PSCCR_INVW1_MASK); + /* Now enable the system bus cache. */ + LMEM->PSCCR |= LMEM_PSCCR_ENCACHE_MASK; + + /* Enables the processor code bus to invalidate all lines in both ways. + and Initiate the processor code bus code cache command. */ + LMEM->PCCCR |= LMEM_PCCCR_INVW0_MASK | LMEM_PCCCR_INVW1_MASK | LMEM_PCCCR_GO_MASK; + /* Wait until the cache command completes. */ + while ((LMEM->PCCCR & LMEM_PCCCR_GO_MASK) != 0U) { + } + /* As a precaution clear the bits to avoid inadvertently re-running this command. */ + LMEM->PCCCR &= ~(LMEM_PCCCR_INVW0_MASK | LMEM_PCCCR_INVW1_MASK); + /* Now enable the code bus cache. */ + LMEM->PCCCR |= LMEM_PCCCR_ENCACHE_MASK; +} +#endif #endif diff --git a/hw/bsp/imxrt/family.cmake b/hw/bsp/imxrt/family.cmake index d917e9777..6224b63a4 100644 --- a/hw/bsp/imxrt/family.cmake +++ b/hw/bsp/imxrt/family.cmake @@ -8,7 +8,9 @@ include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) set(MCU_VARIANT_WITH_CORE ${MCU_VARIANT}${MCU_CORE}) # toolchain set up -set(CMAKE_SYSTEM_PROCESSOR cortex-m7 CACHE INTERNAL "System Processor") +if (NOT DEFINED CMAKE_SYSTEM_CPU) + set(CMAKE_SYSTEM_CPU cortex-m7 CACHE INTERNAL "System Processor") +endif () set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) set(FAMILY_MCUS MIMXRT1XXX CACHE INTERNAL "") @@ -25,13 +27,13 @@ function(add_board_target BOARD_TARGET) # LD_FILE and STARTUP_FILE can be defined in board.cmake if (NOT DEFINED LD_FILE_${CMAKE_C_COMPILER_ID}) set(LD_FILE_GNU ${SDK_DIR}/devices/${MCU_VARIANT}/gcc/${MCU_VARIANT}xxxxx${MCU_CORE}_flexspi_nor.ld) - #set(LD_FILE_IAR ${SDK_DIR}/devices/${MCU_VARIANT}/gcc/${MCU_VARIANT}xxxxx_flexspi_nor.ld) + set(LD_FILE_IAR ${SDK_DIR}/devices/${MCU_VARIANT}/iar/${MCU_VARIANT}xxxxx${MCU_CORE}_flexspi_nor.icf) endif () set(LD_FILE_Clang ${LD_FILE_GNU}) if (NOT DEFINED STARTUP_FILE_${CMAKE_C_COMPILER_ID}) set(STARTUP_FILE_GNU ${SDK_DIR}/devices/${MCU_VARIANT}/gcc/startup_${MCU_VARIANT_WITH_CORE}.S) - #set(STARTUP_FILE_IAR ${SDK_DIR}/devices/${MCU_VARIANT}/gcc/startup_${MCU_VARIANT_WITH_CORE}.S) + set(STARTUP_FILE_IAR ${SDK_DIR}/devices/${MCU_VARIANT}/iar/startup_${MCU_VARIANT_WITH_CORE}.s) endif () set(STARTUP_FILE_Clang ${STARTUP_FILE_GNU}) @@ -58,13 +60,21 @@ function(add_board_target BOARD_TARGET) endif() endforeach() + target_compile_definitions(${BOARD_TARGET} PUBLIC - __ARMVFP__=0 - __ARMFPV5__=0 - XIP_EXTERNAL_FLASH=1 - XIP_BOOT_HEADER_ENABLE=1 __STARTUP_CLEAR_BSS + CFG_TUSB_MEM_SECTION=__attribute__\(\(section\(\"NonCacheable\"\)\)\) ) + + if (NOT M4 STREQUAL "1") + target_compile_definitions(${BOARD_TARGET} PUBLIC + __ARMVFP__=0 + __ARMFPV5__=0 + XIP_EXTERNAL_FLASH=1 + XIP_BOOT_HEADER_ENABLE=1 + ) + endif () + target_include_directories(${BOARD_TARGET} PUBLIC ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/boards/${BOARD} ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/boards/${BOARD}/board @@ -113,8 +123,6 @@ function(family_configure_example TARGET RTOS) # Board target add_board_target(board_${BOARD}) - #---------- Port Specific ---------- - # These files are built for each example since it depends on example's tusb_config.h target_sources(${TARGET} PUBLIC # BSP ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/family.c @@ -128,18 +136,16 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_MIMXRT1XXX ${RTOS}) - target_sources(${TARGET}-tinyusb PRIVATE + family_add_tinyusb(${TARGET} OPT_MCU_MIMXRT1XXX) + target_sources(${TARGET} PRIVATE ${TOP}/src/portable/chipidea/ci_hs/dcd_ci_hs.c ${TOP}/src/portable/chipidea/ci_hs/hcd_ci_hs.c ${TOP}/src/portable/ehci/ehci.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) - - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) # Flashing + family_add_bin_hex(${TARGET}) family_flash_jlink(${TARGET}) #family_flash_nxplink(${TARGET}) #family_flash_pyocd(${TARGET}) diff --git a/hw/bsp/imxrt/family.mk b/hw/bsp/imxrt/family.mk index f00afb6a4..9a2c37121 100644 --- a/hw/bsp/imxrt/family.mk +++ b/hw/bsp/imxrt/family.mk @@ -1,6 +1,5 @@ UF2_FAMILY_ID = 0x4fb2d5bd SDK_DIR = hw/mcu/nxp/mcux-sdk -DEPS_SUBMODULES += $(SDK_DIR) lib/CMSIS_5 include $(TOP)/$(BOARD_PATH)/board.mk @@ -8,13 +7,18 @@ CPU_CORE ?= cortex-m7 MCU_VARIANT_WITH_CORE = ${MCU_VARIANT}${MCU_CORE} MCU_DIR = $(SDK_DIR)/devices/$(MCU_VARIANT) +CFLAGS += \ + -D__STARTUP_CLEAR_BSS \ + -DCFG_TUSB_MCU=OPT_MCU_MIMXRT1XXX \ + -DCFG_TUSB_MEM_SECTION='__attribute__((section("NonCacheable")))' \ + +ifneq ($(M4), 1) CFLAGS += \ -D__ARMVFP__=0 \ -D__ARMFPV5__=0 \ - -D__STARTUP_CLEAR_BSS \ -DXIP_EXTERNAL_FLASH=1 \ - -DXIP_BOOT_HEADER_ENABLE=1 \ - -DCFG_TUSB_MCU=OPT_MCU_MIMXRT1XXX + -DXIP_BOOT_HEADER_ENABLE=1 +endif ifdef BOARD_TUD_RHPORT CFLAGS += -DBOARD_TUD_RHPORT=$(BOARD_TUD_RHPORT) diff --git a/hw/bsp/kinetis_k/boards/frdm_k64f/board.h b/hw/bsp/kinetis_k/boards/frdm_k64f/board.h index ae8c66182..75a10f961 100644 --- a/hw/bsp/kinetis_k/boards/frdm_k64f/board.h +++ b/hw/bsp/kinetis_k/boards/frdm_k64f/board.h @@ -22,6 +22,11 @@ * THE SOFTWARE. */ +/* metadata: + name: Freedom K64F + url: https://www.nxp.com/design/design-center/development-boards-and-designs/general-purpose-mcus/freedom-development-platform-for-kinetis-k64-k63-and-k24-mcus:FRDM-K64F +*/ + #ifndef BOARD_H #define BOARD_H diff --git a/hw/bsp/kinetis_k/boards/teensy_35/board.h b/hw/bsp/kinetis_k/boards/teensy_35/board.h index f8173447a..4718a0241 100644 --- a/hw/bsp/kinetis_k/boards/teensy_35/board.h +++ b/hw/bsp/kinetis_k/boards/teensy_35/board.h @@ -22,6 +22,11 @@ * THE SOFTWARE. */ +/* metadata: + name: Teensy 3.5 + url: https://www.pjrc.com/store/teensy35.html +*/ + #ifndef BOARD_H #define BOARD_H diff --git a/hw/bsp/kinetis_k/family.c b/hw/bsp/kinetis_k/family.c index 30dfe6d76..59d80fa18 100644 --- a/hw/bsp/kinetis_k/family.c +++ b/hw/bsp/kinetis_k/family.c @@ -23,6 +23,10 @@ * THE SOFTWARE. */ +/* metadata: + manufacturer: NXP +*/ + #include "bsp/board_api.h" #include "board.h" #include "fsl_device_registers.h" diff --git a/hw/bsp/kinetis_k/family.cmake b/hw/bsp/kinetis_k/family.cmake index c30268629..ce91777c9 100644 --- a/hw/bsp/kinetis_k/family.cmake +++ b/hw/bsp/kinetis_k/family.cmake @@ -11,7 +11,7 @@ set(CMSIS_DIR ${TOP}/lib/CMSIS_5) include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) # toolchain set up -set(CMAKE_SYSTEM_PROCESSOR cortex-m4 CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU cortex-m4 CACHE INTERNAL "System Processor") set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) set(FAMILY_MCUS KINETIS_K CACHE INTERNAL "") @@ -97,17 +97,17 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_KINETIS_K ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC + family_add_tinyusb(${TARGET} OPT_MCU_KINETIS_K) + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/chipidea/ci_fs/dcd_ci_fs.c ${TOP}/src/portable/nxp/khci/hcd_khci.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) # Flashing + family_add_bin_hex(${TARGET}) family_flash_jlink(${TARGET}) if (DEFINED TEENSY_MCU) diff --git a/hw/bsp/kinetis_k/family.mk b/hw/bsp/kinetis_k/family.mk index 844ce332e..e95cdb717 100644 --- a/hw/bsp/kinetis_k/family.mk +++ b/hw/bsp/kinetis_k/family.mk @@ -1,5 +1,4 @@ SDK_DIR = hw/mcu/nxp/mcux-sdk -DEPS_SUBMODULES += $(SDK_DIR) lib/CMSIS_5 MCU_DIR = $(SDK_DIR)/devices/${MCU_VARIANT} include $(TOP)/$(BOARD_PATH)/board.mk diff --git a/hw/bsp/kinetis_k32l2/boards/frdm_k32l2a4s/board.h b/hw/bsp/kinetis_k32l2/boards/frdm_k32l2a4s/board.h index 16f832722..9e2534307 100644 --- a/hw/bsp/kinetis_k32l2/boards/frdm_k32l2a4s/board.h +++ b/hw/bsp/kinetis_k32l2/boards/frdm_k32l2a4s/board.h @@ -24,6 +24,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Freedom K32L2A4S + url: https://www.nxp.com/design/design-center/development-boards-and-designs/FRDM-K32L2A4S +*/ #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/kinetis_k32l2/boards/frdm_k32l2a4s/board.mk b/hw/bsp/kinetis_k32l2/boards/frdm_k32l2a4s/board.mk index c4dc65b63..fb3eb2a03 100644 --- a/hw/bsp/kinetis_k32l2/boards/frdm_k32l2a4s/board.mk +++ b/hw/bsp/kinetis_k32l2/boards/frdm_k32l2a4s/board.mk @@ -3,7 +3,7 @@ MCU = K32L2A41A CFLAGS += -DCPU_K32L2A41VLH1A # mcu driver cause following warnings -CFLAGS += -Wno-error=unused-parameter -Wno-error=redundant-decls -Wno-error=cast-qual +CFLAGS_GCC += -Wno-error=unused-parameter -Wno-error=redundant-decls -Wno-error=cast-qual # All source paths should be relative to the top level. LD_FILE = $(MCU_DIR)/gcc/K32L2A41xxxxA_flash.ld diff --git a/hw/bsp/kinetis_k32l2/boards/frdm_k32l2b/board.h b/hw/bsp/kinetis_k32l2/boards/frdm_k32l2b/board.h index 790d6fcb0..854340d6d 100644 --- a/hw/bsp/kinetis_k32l2/boards/frdm_k32l2b/board.h +++ b/hw/bsp/kinetis_k32l2/boards/frdm_k32l2b/board.h @@ -24,6 +24,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Freedom K32L2B3 + url: https://www.nxp.com/design/design-center/development-boards-and-designs/general-purpose-mcus/nxp-freedom-development-platform-for-k32-l2b-mcus:FRDM-K32L2B3 +*/ #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/kinetis_k32l2/boards/kuiic/board.h b/hw/bsp/kinetis_k32l2/boards/kuiic/board.h index ec3702376..f5895fc65 100644 --- a/hw/bsp/kinetis_k32l2/boards/kuiic/board.h +++ b/hw/bsp/kinetis_k32l2/boards/kuiic/board.h @@ -24,6 +24,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Kuiic + url: https://github.com/nxf58843/kuiic +*/ #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/kinetis_k32l2/family.c b/hw/bsp/kinetis_k32l2/family.c index 92f5ba6d3..2fcc1b2af 100644 --- a/hw/bsp/kinetis_k32l2/family.c +++ b/hw/bsp/kinetis_k32l2/family.c @@ -25,6 +25,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: NXP +*/ + #include "fsl_gpio.h" #include "fsl_port.h" #include "fsl_clock.h" diff --git a/hw/bsp/kinetis_k32l2/family.cmake b/hw/bsp/kinetis_k32l2/family.cmake index 406ae99d3..946614a03 100644 --- a/hw/bsp/kinetis_k32l2/family.cmake +++ b/hw/bsp/kinetis_k32l2/family.cmake @@ -7,7 +7,7 @@ set(CMSIS_DIR ${TOP}/lib/CMSIS_5) include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) # toolchain set up -set(CMAKE_SYSTEM_PROCESSOR cortex-m0plus CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU cortex-m0plus CACHE INTERNAL "System Processor") set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) set(FAMILY_MCUS KINETIS_K32L CACHE INTERNAL "") @@ -92,21 +92,20 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_KINETIS_K32L ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC + family_add_tinyusb(${TARGET} OPT_MCU_KINETIS_K32L) + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/nxp/khci/dcd_khci.c ${TOP}/src/portable/nxp/khci/hcd_khci.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) # Flashing family_flash_jlink(${TARGET}) + family_add_bin_hex(${TARGET}) if (DEFINED TEENSY_MCU) - family_add_bin_hex(${TARGET}) family_flash_teensy(${TARGET}) endif () endfunction() diff --git a/hw/bsp/kinetis_kl/boards/frdm_kl25z/board.h b/hw/bsp/kinetis_kl/boards/frdm_kl25z/board.h index 23f144666..b03fe91a8 100644 --- a/hw/bsp/kinetis_kl/boards/frdm_kl25z/board.h +++ b/hw/bsp/kinetis_kl/boards/frdm_kl25z/board.h @@ -22,6 +22,11 @@ * THE SOFTWARE. */ +/* metadata: + name: fomu + url: https://www.nxp.com/design/design-center/development-boards-and-designs/general-purpose-mcus/freedom-development-platform-for-kinetis-kl14-kl15-kl24-kl25-mcus:FRDM-KL25Z +*/ + #ifndef BOARD_H #define BOARD_H diff --git a/hw/bsp/kinetis_kl/family.c b/hw/bsp/kinetis_kl/family.c index 254a95176..fe864f3a0 100644 --- a/hw/bsp/kinetis_kl/family.c +++ b/hw/bsp/kinetis_kl/family.c @@ -23,6 +23,10 @@ * THE SOFTWARE. */ +/* metadata: + manufacturer: NXP +*/ + #include "bsp/board_api.h" #include "board.h" #include "fsl_device_registers.h" diff --git a/hw/bsp/kinetis_kl/family.cmake b/hw/bsp/kinetis_kl/family.cmake index 85a913d54..51a646258 100644 --- a/hw/bsp/kinetis_kl/family.cmake +++ b/hw/bsp/kinetis_kl/family.cmake @@ -11,7 +11,7 @@ set(CMSIS_DIR ${TOP}/lib/CMSIS_5) include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) # toolchain set up -set(CMAKE_SYSTEM_PROCESSOR cortex-m0plus CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU cortex-m0plus CACHE INTERNAL "System Processor") set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) set(FAMILY_MCUS KINETIS_KL CACHE INTERNAL "") @@ -96,16 +96,16 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_KINETIS_KL ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC + family_add_tinyusb(${TARGET} OPT_MCU_KINETIS_KL) + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/chipidea/ci_fs/dcd_ci_fs.c ${TOP}/src/portable/nxp/khci/hcd_khci.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) # Flashing + family_add_bin_hex(${TARGET}) family_flash_jlink(${TARGET}) endfunction() diff --git a/hw/bsp/kinetis_kl/family.mk b/hw/bsp/kinetis_kl/family.mk index 1fdce981a..8d113aecf 100644 --- a/hw/bsp/kinetis_kl/family.mk +++ b/hw/bsp/kinetis_kl/family.mk @@ -1,5 +1,4 @@ SDK_DIR = hw/mcu/nxp/mcux-sdk -DEPS_SUBMODULES += $(SDK_DIR) lib/CMSIS_5 MCU_DIR = $(SDK_DIR)/devices/$(MCU) include $(TOP)/$(BOARD_PATH)/board.mk diff --git a/hw/bsp/lpc11/boards/lpcxpresso11u37/board.h b/hw/bsp/lpc11/boards/lpcxpresso11u37/board.h index 930462f28..c8a48eecb 100644 --- a/hw/bsp/lpc11/boards/lpcxpresso11u37/board.h +++ b/hw/bsp/lpc11/boards/lpcxpresso11u37/board.h @@ -1,3 +1,8 @@ +/* metadata: + name: LPCXpresso11U37 + url: https://www.nxp.com/design/design-center/development-boards-and-designs/OM13074 +*/ + #ifndef BOARD_H #define BOARD_H diff --git a/hw/bsp/lpc11/boards/lpcxpresso11u68/board.h b/hw/bsp/lpc11/boards/lpcxpresso11u68/board.h index a12fcbef1..50141e4a5 100644 --- a/hw/bsp/lpc11/boards/lpcxpresso11u68/board.h +++ b/hw/bsp/lpc11/boards/lpcxpresso11u68/board.h @@ -1,3 +1,8 @@ +/* metadata: + name: LPCXpresso11U68 + url: https://www.nxp.com/design/design-center/development-boards-and-designs/OM13058 +*/ + #ifndef BOARD_H #define BOARD_H diff --git a/hw/bsp/lpc11/family.c b/hw/bsp/lpc11/family.c index e75bc4919..b5371632c 100644 --- a/hw/bsp/lpc11/family.c +++ b/hw/bsp/lpc11/family.c @@ -24,6 +24,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: NXP +*/ + #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" @@ -38,6 +42,10 @@ #include "bsp/board_api.h" #include "board.h" +extern void USB_IRQHandler(void); +extern void SysTick_Handler(void); +void SystemInit(void); + //--------------------------------------------------------------------+ // Forward USB interrupt events to TinyUSB IRQ Handler //--------------------------------------------------------------------+ diff --git a/hw/bsp/lpc11/family.cmake b/hw/bsp/lpc11/family.cmake index 818600656..6781b20c6 100644 --- a/hw/bsp/lpc11/family.cmake +++ b/hw/bsp/lpc11/family.cmake @@ -11,7 +11,7 @@ else() endif() # toolchain set up -set(CMAKE_SYSTEM_PROCESSOR cortex-m0plus CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU cortex-m0plus CACHE INTERNAL "System Processor") set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) set(FAMILY_MCUS LPC11UXX CACHE INTERNAL "") @@ -49,7 +49,10 @@ function(add_board_target BOARD_TARGET) update_board(${BOARD_TARGET}) if (CMAKE_C_COMPILER_ID STREQUAL "GNU") - target_compile_options(${BOARD_TARGET} PUBLIC -nostdlib) + target_compile_options(${BOARD_TARGET} PUBLIC + -nostdlib + -Wno-error=incompatible-pointer-types + ) target_link_options(${BOARD_TARGET} PUBLIC "LINKER:--script=${LD_FILE_GNU}" --specs=nosys.specs --specs=nano.specs @@ -90,16 +93,16 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_LPC11UXX ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC + family_add_tinyusb(${TARGET} OPT_MCU_LPC11UXX) + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/nxp/lpc_ip3511/dcd_lpc_ip3511.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) # Flashing + family_add_bin_hex(${TARGET}) family_flash_jlink(${TARGET}) #family_flash_nxplink(${TARGET}) endfunction() diff --git a/hw/bsp/lpc13/boards/lpcxpresso1347/board.h b/hw/bsp/lpc13/boards/lpcxpresso1347/board.h index 71e608b46..acf29fdc6 100644 --- a/hw/bsp/lpc13/boards/lpcxpresso1347/board.h +++ b/hw/bsp/lpc13/boards/lpcxpresso1347/board.h @@ -1,3 +1,8 @@ +/* metadata: + name: LPCXpresso1347 + url: https://www.nxp.com/products/no-longer-manufactured/lpcxpresso-board-for-lpc1347:OM13045 +*/ + #ifndef BOARD_H #define BOARD_H diff --git a/hw/bsp/lpc13/boards/lpcxpresso1347/board.mk b/hw/bsp/lpc13/boards/lpcxpresso1347/board.mk index 31eb2f28f..8513c24ca 100644 --- a/hw/bsp/lpc13/boards/lpcxpresso1347/board.mk +++ b/hw/bsp/lpc13/boards/lpcxpresso1347/board.mk @@ -1,5 +1,3 @@ -DEPS_SUBMODULES += hw/mcu/nxp/lpcopen - CFLAGS += \ -DCFG_TUSB_MEM_SECTION='__attribute__((section(".data.$$RAM2")))' diff --git a/hw/bsp/lpc13/family.c b/hw/bsp/lpc13/family.c index 7e04c1cf5..1faa54485 100644 --- a/hw/bsp/lpc13/family.c +++ b/hw/bsp/lpc13/family.c @@ -24,6 +24,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: NXP +*/ + #include "chip.h" #include "bsp/board_api.h" #include "board.h" diff --git a/hw/bsp/lpc13/family.cmake b/hw/bsp/lpc13/family.cmake index f7f5c0180..e3c0b18c7 100644 --- a/hw/bsp/lpc13/family.cmake +++ b/hw/bsp/lpc13/family.cmake @@ -8,7 +8,7 @@ set(CMSIS_DIR ${TOP}/lib/CMSIS_5) include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) # toolchain set up -set(CMAKE_SYSTEM_PROCESSOR cortex-m3 CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU cortex-m3 CACHE INTERNAL "System Processor") set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) set(FAMILY_MCUS LPC13XX CACHE INTERNAL "") @@ -87,16 +87,16 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_LPC13XX ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC + family_add_tinyusb(${TARGET} OPT_MCU_LPC13XX) + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/nxp/lpc_ip3511/dcd_lpc_ip3511.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) # Flashing + family_add_bin_hex(${TARGET}) family_flash_jlink(${TARGET}) #family_flash_nxplink(${TARGET}) endfunction() diff --git a/hw/bsp/lpc13/family.mk b/hw/bsp/lpc13/family.mk index 4f8b48c4b..7ff2c058a 100644 --- a/hw/bsp/lpc13/family.mk +++ b/hw/bsp/lpc13/family.mk @@ -1,5 +1,3 @@ -DEPS_SUBMODULES += hw/mcu/nxp/lpcopen - MCU_DIR = hw/mcu/nxp/lpcopen/lpc13xx/lpc_chip_13xx include $(TOP)/$(BOARD_PATH)/board.mk CPU_CORE ?= cortex-m3 diff --git a/hw/bsp/lpc15/boards/lpcxpresso1549/board.h b/hw/bsp/lpc15/boards/lpcxpresso1549/board.h index 5ed5b75b2..1be2045a9 100644 --- a/hw/bsp/lpc15/boards/lpcxpresso1549/board.h +++ b/hw/bsp/lpc15/boards/lpcxpresso1549/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: LPCXpresso1549 + url: https://www.nxp.com/design/design-center/development-boards-and-designs/OM13056 +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/lpc15/family.c b/hw/bsp/lpc15/family.c index b9ce39648..e23fdec43 100644 --- a/hw/bsp/lpc15/family.c +++ b/hw/bsp/lpc15/family.c @@ -24,6 +24,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: NXP +*/ + #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstrict-prototypes" diff --git a/hw/bsp/lpc15/family.cmake b/hw/bsp/lpc15/family.cmake index 61b47d852..761c5a619 100644 --- a/hw/bsp/lpc15/family.cmake +++ b/hw/bsp/lpc15/family.cmake @@ -8,7 +8,7 @@ set(CMSIS_DIR ${TOP}/lib/CMSIS_5) include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) # toolchain set up -set(CMAKE_SYSTEM_PROCESSOR cortex-m3 CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU cortex-m3 CACHE INTERNAL "System Processor") set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) set(FAMILY_MCUS LPC15XX CACHE INTERNAL "") @@ -89,16 +89,16 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_LPC15XX ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC + family_add_tinyusb(${TARGET} OPT_MCU_LPC15XX) + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/nxp/lpc_ip3511/dcd_lpc_ip3511.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) # Flashing + family_add_bin_hex(${TARGET}) family_flash_jlink(${TARGET}) #family_flash_nxplink(${TARGET}) endfunction() diff --git a/hw/bsp/lpc15/family.mk b/hw/bsp/lpc15/family.mk index b83e008e8..3267e973a 100644 --- a/hw/bsp/lpc15/family.mk +++ b/hw/bsp/lpc15/family.mk @@ -1,5 +1,3 @@ -DEPS_SUBMODULES += hw/mcu/nxp/lpcopen - include $(TOP)/$(BOARD_PATH)/board.mk CPU_CORE ?= cortex-m3 @@ -15,7 +13,7 @@ CFLAGS += \ LDFLAGS_GCC += -specs=nosys.specs -specs=nano.specs # mcu driver cause following warnings -CFLAGS += -Wno-error=strict-prototypes -Wno-error=unused-parameter -Wno-error=unused-variable -Wno-error=cast-qual +CFLAGS_GCC += -Wno-error=strict-prototypes -Wno-error=unused-parameter -Wno-error=unused-variable -Wno-error=cast-qual MCU_DIR = hw/mcu/nxp/lpcopen/lpc15xx/lpc_chip_15xx diff --git a/hw/bsp/lpc17/boards/lpcxpresso1769/board.h b/hw/bsp/lpc17/boards/lpcxpresso1769/board.h index d6aa98ed9..6f5c12854 100644 --- a/hw/bsp/lpc17/boards/lpcxpresso1769/board.h +++ b/hw/bsp/lpc17/boards/lpcxpresso1769/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: LPCXpresso1769 + url: https://www.nxp.com/design/design-center/development-boards-and-designs/OM13000 +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/lpc17/boards/mbed1768/board.h b/hw/bsp/lpc17/boards/mbed1768/board.h index 2b3ddc905..2c75cede4 100644 --- a/hw/bsp/lpc17/boards/mbed1768/board.h +++ b/hw/bsp/lpc17/boards/mbed1768/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: mbed 1768 + url: https://www.nxp.com/products/processors-and-microcontrollers/arm-microcontrollers/general-purpose-mcus/lpc1700-arm-cortex-m3/arm-mbed-lpc1768-board:OM11043 +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/lpc17/family.c b/hw/bsp/lpc17/family.c index 79281ba41..7d3231f6a 100644 --- a/hw/bsp/lpc17/family.c +++ b/hw/bsp/lpc17/family.c @@ -24,6 +24,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: NXP +*/ + #include "chip.h" #include "bsp/board_api.h" #include "board.h" diff --git a/hw/bsp/lpc17/family.cmake b/hw/bsp/lpc17/family.cmake index cccfdac9f..771a0f405 100644 --- a/hw/bsp/lpc17/family.cmake +++ b/hw/bsp/lpc17/family.cmake @@ -7,7 +7,7 @@ set(CMSIS_DIR ${TOP}/lib/CMSIS_5) include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) # toolchain set up -set(CMAKE_SYSTEM_PROCESSOR cortex-m3 CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU cortex-m3 CACHE INTERNAL "System Processor") set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) set(FAMILY_MCUS LPC175X_6X CACHE INTERNAL "") @@ -86,18 +86,18 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_LPC175X_6X ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC + family_add_tinyusb(${TARGET} OPT_MCU_LPC175X_6X) + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/nxp/lpc17_40/dcd_lpc17_40.c ${TOP}/src/portable/nxp/lpc17_40/hcd_lpc17_40.c ${TOP}/src/portable/ohci/ohci.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) # Flashing + family_add_bin_hex(${TARGET}) family_flash_jlink(${TARGET}) #family_flash_nxplink(${TARGET}) endfunction() diff --git a/hw/bsp/lpc17/family.mk b/hw/bsp/lpc17/family.mk index d719a47b7..e8d707ea5 100644 --- a/hw/bsp/lpc17/family.mk +++ b/hw/bsp/lpc17/family.mk @@ -1,5 +1,3 @@ -DEPS_SUBMODULES += hw/mcu/nxp/lpcopen - MCU_DIR = hw/mcu/nxp/lpcopen/lpc175x_6x/lpc_chip_175x_6x include $(TOP)/$(BOARD_PATH)/board.mk CPU_CORE ?= cortex-m3 @@ -13,7 +11,7 @@ CFLAGS += \ -DRTC_EV_SUPPORT=0 # lpc_types.h cause following errors -CFLAGS += -Wno-error=strict-prototypes -Wno-error=cast-qual +CFLAGS_GCC += -Wno-error=strict-prototypes -Wno-error=cast-qual # caused by freeRTOS port !! CFLAGS += -Wno-error=maybe-uninitialized diff --git a/hw/bsp/lpc18/boards/lpcxpresso18s37/board.h b/hw/bsp/lpc18/boards/lpcxpresso18s37/board.h index f4c85ddc9..2cf4dbdf8 100644 --- a/hw/bsp/lpc18/boards/lpcxpresso18s37/board.h +++ b/hw/bsp/lpc18/boards/lpcxpresso18s37/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: LPCXpresso18s37 + url: https://www.nxp.com/design/design-center/software/development-software/mcuxpresso-software-and-tools-/lpcxpresso-boards/lpcxpresso18s37-development-board:OM13076 +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/lpc18/boards/mcb1800/board.h b/hw/bsp/lpc18/boards/mcb1800/board.h index 93b3cd112..dba7a62a3 100644 --- a/hw/bsp/lpc18/boards/mcb1800/board.h +++ b/hw/bsp/lpc18/boards/mcb1800/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Keil MCB1800 + url: https://www.keil.com/arm/mcb1800/ +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/lpc18/family.c b/hw/bsp/lpc18/family.c index 55ef31ee4..0db5c83b6 100644 --- a/hw/bsp/lpc18/family.c +++ b/hw/bsp/lpc18/family.c @@ -24,10 +24,19 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: NXP +*/ + #include "chip.h" #include "bsp/board_api.h" #include "board.h" +extern void USB0_IRQHandler(void); +extern void USB1_IRQHandler(void); +extern void SysTick_Handler(void); +void SystemInit(void); + //--------------------------------------------------------------------+ // USB Interrupt Handler //--------------------------------------------------------------------+ diff --git a/hw/bsp/lpc18/family.cmake b/hw/bsp/lpc18/family.cmake index 309186667..6af1149bf 100644 --- a/hw/bsp/lpc18/family.cmake +++ b/hw/bsp/lpc18/family.cmake @@ -7,7 +7,7 @@ set(CMSIS_5 ${TOP}/lib/CMSIS_5) include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) # toolchain set up -set(CMAKE_SYSTEM_PROCESSOR cortex-m3 CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU cortex-m3 CACHE INTERNAL "System Processor") set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) set(FAMILY_MCUS LPC18XX CACHE INTERNAL "") @@ -84,17 +84,17 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_LPC18XX ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC + family_add_tinyusb(${TARGET} OPT_MCU_LPC18XX) + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/chipidea/ci_hs/dcd_ci_hs.c ${TOP}/src/portable/chipidea/ci_hs/hcd_ci_hs.c ${TOP}/src/portable/ehci/ehci.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) # Flashing + family_add_bin_hex(${TARGET}) family_flash_jlink(${TARGET}) endfunction() diff --git a/hw/bsp/lpc18/family.mk b/hw/bsp/lpc18/family.mk index f625e926a..3bbafed11 100644 --- a/hw/bsp/lpc18/family.mk +++ b/hw/bsp/lpc18/family.mk @@ -1,4 +1,3 @@ -DEPS_SUBMODULES += hw/mcu/nxp/lpcopen MCU_DIR = hw/mcu/nxp/lpcopen/lpc18xx/lpc_chip_18xx include $(TOP)/$(BOARD_PATH)/board.mk @@ -12,7 +11,7 @@ CFLAGS += \ -DCFG_TUSB_MCU=OPT_MCU_LPC18XX # mcu driver cause following warnings -CFLAGS += -Wno-error=unused-parameter -Wno-error=strict-prototypes -Wno-error=cast-qual +CFLAGS_GCC += -Wno-error=unused-parameter -Wno-error=cast-qual LDFLAGS_GCC += --specs=nosys.specs --specs=nano.specs diff --git a/hw/bsp/lpc40/boards/ea4088_quickstart/board.h b/hw/bsp/lpc40/boards/ea4088_quickstart/board.h index d5489c154..ede0a306d 100644 --- a/hw/bsp/lpc40/boards/ea4088_quickstart/board.h +++ b/hw/bsp/lpc40/boards/ea4088_quickstart/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Embedded Artists LPC4088 QuickStart Board + url: https://www.embeddedartists.com/products/lpc4088-quickstart-board/ +*/ + #ifndef EA4088QS__BOARD_H #define EA4088QS__BOARD_H diff --git a/hw/bsp/lpc40/family.c b/hw/bsp/lpc40/family.c index d6c8ef32a..b8bc99452 100644 --- a/hw/bsp/lpc40/family.c +++ b/hw/bsp/lpc40/family.c @@ -24,6 +24,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: NXP +*/ + #include "chip.h" #include "bsp/board_api.h" #include "board.h" diff --git a/hw/bsp/lpc40/family.cmake b/hw/bsp/lpc40/family.cmake index 4c14da8a7..3a680eae6 100644 --- a/hw/bsp/lpc40/family.cmake +++ b/hw/bsp/lpc40/family.cmake @@ -7,7 +7,7 @@ set(CMSIS_DIR ${TOP}/lib/CMSIS_5) include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) # toolchain set up -set(CMAKE_SYSTEM_PROCESSOR cortex-m4 CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU cortex-m4 CACHE INTERNAL "System Processor") set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) set(FAMILY_MCUS LPC40XX CACHE INTERNAL "") @@ -87,18 +87,18 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_LPC40XX ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC + family_add_tinyusb(${TARGET} OPT_MCU_LPC40XX) + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/nxp/lpc17_40/dcd_lpc17_40.c ${TOP}/src/portable/nxp/lpc17_40/hcd_lpc17_40.c ${TOP}/src/portable/ohci/ohci.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) # Flashing + family_add_bin_hex(${TARGET}) family_flash_jlink(${TARGET}) #family_flash_nxplink(${TARGET}) endfunction() diff --git a/hw/bsp/lpc40/family.mk b/hw/bsp/lpc40/family.mk index ef9fe57b2..c72631235 100644 --- a/hw/bsp/lpc40/family.mk +++ b/hw/bsp/lpc40/family.mk @@ -1,5 +1,3 @@ -DEPS_SUBMODULES += hw/mcu/nxp/lpcopen - MCU_DIR = hw/mcu/nxp/lpcopen/lpc40xx/lpc_chip_40xx include $(TOP)/$(BOARD_PATH)/board.mk CPU_CORE ?= cortex-m4 @@ -13,7 +11,7 @@ CFLAGS += \ -DCFG_TUSB_MCU=OPT_MCU_LPC40XX # mcu driver cause following warnings -CFLAGS += -Wno-error=strict-prototypes -Wno-error=unused-parameter -Wno-error=cast-qual +CFLAGS_GCC += -Wno-error=strict-prototypes -Wno-error=unused-parameter -Wno-error=cast-qual LDFLAGS_GCC += --specs=nosys.specs --specs=nano.specs diff --git a/hw/bsp/lpc43/boards/ea4357/board.h b/hw/bsp/lpc43/boards/ea4357/board.h index fb52e32a7..fca617361 100644 --- a/hw/bsp/lpc43/boards/ea4357/board.h +++ b/hw/bsp/lpc43/boards/ea4357/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Embedded Artists LPC4357 Development Kit + url: https://www.embeddedartists.com/products/lpc4357-developers-kit/ +*/ + #ifndef _BOARD_EA4357_H #define _BOARD_EA4357_H diff --git a/hw/bsp/lpc43/boards/lpcxpresso43s67/board.h b/hw/bsp/lpc43/boards/lpcxpresso43s67/board.h index 4dd90fe29..4427905e8 100644 --- a/hw/bsp/lpc43/boards/lpcxpresso43s67/board.h +++ b/hw/bsp/lpc43/boards/lpcxpresso43s67/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: LPCXpresso43S67 + url: https://www.nxp.com/design/design-center/software/development-software/mcuxpresso-software-and-tools-/lpcxpresso-boards/lpcxpresso43s67-development-board:OM13084 +*/ + #ifndef _BOARD_LPCXPRESSO43S67_H_ #define _BOARD_LPCXPRESSO43S67_H_ diff --git a/hw/bsp/lpc43/family.c b/hw/bsp/lpc43/family.c index dfee9f5ea..591090c36 100644 --- a/hw/bsp/lpc43/family.c +++ b/hw/bsp/lpc43/family.c @@ -24,6 +24,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: NXP +*/ + // Suppress warning caused by mcu driver #ifdef __GNUC__ #pragma GCC diagnostic push @@ -43,6 +47,11 @@ const uint32_t OscRateIn = 12000000; const uint32_t ExtRateIn = 0; +extern void USB0_IRQHandler(void); +extern void USB1_IRQHandler(void); +extern void SysTick_Handler(void); +void SystemInit(void); + /*------------------------------------------------------------------*/ /* BOARD API *------------------------------------------------------------------*/ diff --git a/hw/bsp/lpc43/family.cmake b/hw/bsp/lpc43/family.cmake index 2bacd9ea4..23c4aecea 100644 --- a/hw/bsp/lpc43/family.cmake +++ b/hw/bsp/lpc43/family.cmake @@ -7,7 +7,7 @@ set(CMSIS_5 ${TOP}/lib/CMSIS_5) include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) # toolchain set up -set(CMAKE_SYSTEM_PROCESSOR cortex-m4 CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU cortex-m4 CACHE INTERNAL "System Processor") set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) set(FAMILY_MCUS LPC43XX CACHE INTERNAL "") @@ -51,7 +51,10 @@ function(add_board_target BOARD_TARGET) update_board(${BOARD_TARGET}) if (CMAKE_C_COMPILER_ID STREQUAL "GNU") - target_compile_options(${BOARD_TARGET} PUBLIC -nostdlib) + target_compile_options(${BOARD_TARGET} PUBLIC + -nostdlib + -Wno-error=incompatible-pointer-types + ) target_link_options(${BOARD_TARGET} PUBLIC "LINKER:--script=${LD_FILE_GNU}" --specs=nosys.specs --specs=nano.specs @@ -92,17 +95,17 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_LPC43XX ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC + family_add_tinyusb(${TARGET} OPT_MCU_LPC43XX) + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/chipidea/ci_hs/dcd_ci_hs.c ${TOP}/src/portable/chipidea/ci_hs/hcd_ci_hs.c ${TOP}/src/portable/ehci/ehci.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) # Flashing + family_add_bin_hex(${TARGET}) family_flash_jlink(${TARGET}) endfunction() diff --git a/hw/bsp/lpc43/family.mk b/hw/bsp/lpc43/family.mk index 84e7c30b3..39be867d1 100644 --- a/hw/bsp/lpc43/family.mk +++ b/hw/bsp/lpc43/family.mk @@ -1,20 +1,18 @@ -DEPS_SUBMODULES += hw/mcu/nxp/lpcopen SDK_DIR = hw/mcu/nxp/lpcopen/lpc43xx/lpc_chip_43xx include ${TOP}/${BOARD_PATH}/board.mk CPU_CORE ?= cortex-m4 CFLAGS += \ - -flto \ - -nostdlib \ -DCORE_M4 \ -D__USE_LPCOPEN \ -DCFG_TUSB_MCU=OPT_MCU_LPC43XX # mcu driver cause following warnings -CFLAGS += \ +CFLAGS_GCC += \ + -flto \ + -nostdlib \ -Wno-error=unused-parameter \ - -Wno-error=strict-prototypes \ -Wno-error=cast-qual \ -Wno-error=incompatible-pointer-types \ diff --git a/hw/bsp/lpc51/boards/lpcxpresso51u68/board.h b/hw/bsp/lpc51/boards/lpcxpresso51u68/board.h index 0a3b37fda..151fae24b 100644 --- a/hw/bsp/lpc51/boards/lpcxpresso51u68/board.h +++ b/hw/bsp/lpc51/boards/lpcxpresso51u68/board.h @@ -1,3 +1,8 @@ +/* metadata: + name: LPCXpresso51u68 + url: https://www.nxp.com/products/processors-and-microcontrollers/arm-microcontrollers/general-purpose-mcus/lpcxpresso51u68-for-the-lpc51u68-mcus:OM40005 +*/ + #ifndef BOARD_H #define BOARD_H diff --git a/hw/bsp/lpc51/family.c b/hw/bsp/lpc51/family.c index a0667a741..0afe33d41 100644 --- a/hw/bsp/lpc51/family.c +++ b/hw/bsp/lpc51/family.c @@ -24,6 +24,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: NXP +*/ + #include "fsl_device_registers.h" #include "fsl_gpio.h" #include "fsl_power.h" diff --git a/hw/bsp/lpc51/family.cmake b/hw/bsp/lpc51/family.cmake index b9dd8829e..09d97d256 100644 --- a/hw/bsp/lpc51/family.cmake +++ b/hw/bsp/lpc51/family.cmake @@ -7,7 +7,7 @@ set(CMSIS_DIR ${TOP}/lib/CMSIS_5) include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) # toolchain set up -set(CMAKE_SYSTEM_PROCESSOR cortex-m0plus CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU cortex-m0plus CACHE INTERNAL "System Processor") set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) set(FAMILY_MCUS LPC51 CACHE INTERNAL "") @@ -36,7 +36,7 @@ function(add_board_target BOARD_TARGET) # driver ${SDK_DIR}/drivers/lpc_gpio/fsl_gpio.c ${SDK_DIR}/drivers/flexcomm/fsl_flexcomm.c - ${SDK_DIR}/drivers/flexcomm/fsl_usart.c + ${SDK_DIR}/drivers/flexcomm/usart/fsl_usart.c # mcu ${SDK_DIR}/devices/${MCU_VARIANT}/system_${MCU_VARIANT}.c ${SDK_DIR}/devices/${MCU_VARIANT}/drivers/fsl_clock.c @@ -106,16 +106,16 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_LPC51 ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC + family_add_tinyusb(${TARGET} OPT_MCU_LPC51) + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/nxp/lpc_ip3511/dcd_lpc_ip3511.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) # Flashing + family_add_bin_hex(${TARGET}) family_flash_jlink(${TARGET}) #family_flash_nxplink(${TARGET}) #family_flash_pyocd(${TARGET}) diff --git a/hw/bsp/lpc51/family.mk b/hw/bsp/lpc51/family.mk index b41b5438e..91d1261cb 100644 --- a/hw/bsp/lpc51/family.mk +++ b/hw/bsp/lpc51/family.mk @@ -28,15 +28,16 @@ SRC_C += \ $(MCU_DIR)/drivers/fsl_reset.c \ $(SDK_DIR)/drivers/lpc_gpio/fsl_gpio.c \ $(SDK_DIR)/drivers/flexcomm/fsl_flexcomm.c \ - $(SDK_DIR)/drivers/flexcomm/fsl_usart.c + $(SDK_DIR)/drivers/flexcomm/usart/fsl_usart.c INC += \ - $(TOP)/$(BOARD_PATH) \ - $(TOP)/lib/CMSIS_5/CMSIS/Core/Include \ + $(TOP)/$(BOARD_PATH) \ + $(TOP)/lib/CMSIS_5/CMSIS/Core/Include \ $(TOP)/$(MCU_DIR) \ $(TOP)/$(MCU_DIR)/drivers \ $(TOP)/$(SDK_DIR)/drivers/common \ $(TOP)/$(SDK_DIR)/drivers/flexcomm \ + $(TOP)/$(SDK_DIR)/drivers/flexcomm/usart \ $(TOP)/$(SDK_DIR)/drivers/lpc_iocon \ $(TOP)/$(SDK_DIR)/drivers/lpc_gpio diff --git a/hw/bsp/lpc54/boards/lpcxpresso54114/board.h b/hw/bsp/lpc54/boards/lpcxpresso54114/board.h index b1ad4258c..c43ca9d7d 100644 --- a/hw/bsp/lpc54/boards/lpcxpresso54114/board.h +++ b/hw/bsp/lpc54/boards/lpcxpresso54114/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: LPCXpresso54114 + url: https://www.nxp.com/design/design-center/software/development-software/mcuxpresso-software-and-tools-/lpcxpresso-boards/lpcxpresso54114-board:OM13089 +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/lpc54/boards/lpcxpresso54608/board.h b/hw/bsp/lpc54/boards/lpcxpresso54608/board.h index 8bbe18155..e985e97e0 100644 --- a/hw/bsp/lpc54/boards/lpcxpresso54608/board.h +++ b/hw/bsp/lpc54/boards/lpcxpresso54608/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: LPCXpresso54608 + url: https://www.nxp.com/design/design-center/software/development-software/mcuxpresso-software-and-tools-/lpcxpresso-development-board-for-lpc5460x-mcus:OM13092 +*/ + #ifndef BOARD_LPCXPRESSO54608_H_ #define BOARD_LPCXPRESSO54608_H_ diff --git a/hw/bsp/lpc54/boards/lpcxpresso54628/board.h b/hw/bsp/lpc54/boards/lpcxpresso54628/board.h index 670277512..837d26aef 100644 --- a/hw/bsp/lpc54/boards/lpcxpresso54628/board.h +++ b/hw/bsp/lpc54/boards/lpcxpresso54628/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: LPCXpresso54628 + url: https://www.nxp.com/design/design-center/software/development-software/mcuxpresso-software-and-tools-/lpcxpresso-boards/lpcxpresso54628-development-board:OM13098 +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/lpc54/family.c b/hw/bsp/lpc54/family.c index 5e6ff2231..9b9b5841b 100644 --- a/hw/bsp/lpc54/family.c +++ b/hw/bsp/lpc54/family.c @@ -24,6 +24,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: NXP +*/ + #include "fsl_device_registers.h" #include "fsl_gpio.h" #include "fsl_power.h" diff --git a/hw/bsp/lpc54/family.cmake b/hw/bsp/lpc54/family.cmake index 5c61a07f0..66320870a 100644 --- a/hw/bsp/lpc54/family.cmake +++ b/hw/bsp/lpc54/family.cmake @@ -7,7 +7,7 @@ set(CMSIS_DIR ${TOP}/lib/CMSIS_5) include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) # toolchain set up -set(CMAKE_SYSTEM_PROCESSOR cortex-m4 CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU cortex-m4 CACHE INTERNAL "System Processor") set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) set(FAMILY_MCUS LPC54 CACHE INTERNAL "") @@ -44,7 +44,7 @@ function(add_board_target BOARD_TARGET) ${SDK_DIR}/drivers/lpc_gpio/fsl_gpio.c ${SDK_DIR}/drivers/common/fsl_common_arm.c ${SDK_DIR}/drivers/flexcomm/fsl_flexcomm.c - ${SDK_DIR}/drivers/flexcomm/fsl_usart.c + ${SDK_DIR}/drivers/flexcomm/usart/fsl_usart.c # mcu ${SDK_DIR}/devices/${MCU_VARIANT}/system_${MCU_CORE}.c ${SDK_DIR}/devices/${MCU_VARIANT}/drivers/fsl_clock.c @@ -56,6 +56,7 @@ function(add_board_target BOARD_TARGET) # driver ${SDK_DIR}/drivers/common ${SDK_DIR}/drivers/flexcomm + ${SDK_DIR}/drivers/flexcomm/usart ${SDK_DIR}/drivers/lpc_iocon ${SDK_DIR}/drivers/lpc_gpio ${SDK_DIR}/drivers/lpuart @@ -139,16 +140,16 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_LPC54 ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC + family_add_tinyusb(${TARGET} OPT_MCU_LPC54) + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/nxp/lpc_ip3511/dcd_lpc_ip3511.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) # Flashing + family_add_bin_hex(${TARGET}) family_flash_jlink(${TARGET}) #family_flash_nxplink(${TARGET}) #family_flash_pyocd(${TARGET}) diff --git a/hw/bsp/lpc54/family.mk b/hw/bsp/lpc54/family.mk index ea4c9c39c..94168f6b2 100644 --- a/hw/bsp/lpc54/family.mk +++ b/hw/bsp/lpc54/family.mk @@ -1,5 +1,4 @@ SDK_DIR = hw/mcu/nxp/mcux-sdk -DEPS_SUBMODULES += $(SDK_DIR) lib/CMSIS_5 include $(TOP)/$(BOARD_PATH)/board.mk CPU_CORE ?= cortex-m4 @@ -36,7 +35,7 @@ SRC_C += \ $(MCU_DIR)/drivers/fsl_reset.c \ $(SDK_DIR)/drivers/lpc_gpio/fsl_gpio.c \ $(SDK_DIR)/drivers/flexcomm/fsl_flexcomm.c \ - $(SDK_DIR)/drivers/flexcomm/fsl_usart.c \ + $(SDK_DIR)/drivers/flexcomm/usart/fsl_usart.c \ $(SDK_DIR)/drivers/common/fsl_common_arm.c INC += \ @@ -46,6 +45,7 @@ INC += \ $(TOP)/$(MCU_DIR)/drivers \ $(TOP)/$(SDK_DIR)/drivers/common \ $(TOP)/$(SDK_DIR)/drivers/flexcomm \ + $(TOP)/$(SDK_DIR)/drivers/flexcomm/usart \ $(TOP)/$(SDK_DIR)/drivers/lpc_iocon \ $(TOP)/$(SDK_DIR)/drivers/lpc_gpio diff --git a/hw/bsp/lpc55/boards/double_m33_express/board.h b/hw/bsp/lpc55/boards/double_m33_express/board.h index 975e74e92..dc11e47fc 100644 --- a/hw/bsp/lpc55/boards/double_m33_express/board.h +++ b/hw/bsp/lpc55/boards/double_m33_express/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Double M33 Express + url: https://www.crowdsupply.com/steiert-solutions/double-m33-express +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/lpc55/boards/lpcxpresso55s28/board.h b/hw/bsp/lpc55/boards/lpcxpresso55s28/board.h index f85701b08..907aee6a4 100644 --- a/hw/bsp/lpc55/boards/lpcxpresso55s28/board.h +++ b/hw/bsp/lpc55/boards/lpcxpresso55s28/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: LPCXpresso55s28 + url: https://www.nxp.com/design/design-center/software/development-software/mcuxpresso-software-and-tools-/lpcxpresso-boards/lpcxpresso55s28-development-board:LPC55S28-EVK +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/lpc55/boards/lpcxpresso55s69/board.h b/hw/bsp/lpc55/boards/lpcxpresso55s69/board.h index f85701b08..e18d5bbad 100644 --- a/hw/bsp/lpc55/boards/lpcxpresso55s69/board.h +++ b/hw/bsp/lpc55/boards/lpcxpresso55s69/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: LPCXpresso55s69 + url: https://www.nxp.com/design/design-center/software/development-software/mcuxpresso-software-and-tools-/lpcxpresso-boards/lpcxpresso55s69-development-board:LPC55S69-EVK +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/lpc55/boards/mcu_link/board.h b/hw/bsp/lpc55/boards/mcu_link/board.h index 5e17cf9fd..1d71b3e79 100644 --- a/hw/bsp/lpc55/boards/mcu_link/board.h +++ b/hw/bsp/lpc55/boards/mcu_link/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: MCU Link + url: https://www.nxp.com/design/design-center/software/development-software/mcuxpresso-software-and-tools-/mcu-link-debug-probe:MCU-LINK +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/lpc55/family.c b/hw/bsp/lpc55/family.c index 68ccf52d5..dbf8d71b7 100644 --- a/hw/bsp/lpc55/family.c +++ b/hw/bsp/lpc55/family.c @@ -24,6 +24,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: NXP +*/ + #include "bsp/board_api.h" #include "board.h" #include "fsl_device_registers.h" diff --git a/hw/bsp/lpc55/family.cmake b/hw/bsp/lpc55/family.cmake index 21c57fc1f..a89548635 100644 --- a/hw/bsp/lpc55/family.cmake +++ b/hw/bsp/lpc55/family.cmake @@ -7,7 +7,7 @@ set(CMSIS_DIR ${TOP}/lib/CMSIS_5) include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) # toolchain set up -set(CMAKE_SYSTEM_PROCESSOR cortex-m33 CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU cortex-m33 CACHE INTERNAL "System Processor") set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) set(FAMILY_MCUS LPC55 CACHE INTERNAL "") @@ -44,7 +44,7 @@ function(add_board_target BOARD_TARGET) ${SDK_DIR}/drivers/lpc_gpio/fsl_gpio.c ${SDK_DIR}/drivers/common/fsl_common_arm.c ${SDK_DIR}/drivers/flexcomm/fsl_flexcomm.c - ${SDK_DIR}/drivers/flexcomm/fsl_usart.c + ${SDK_DIR}/drivers/flexcomm/usart/fsl_usart.c # mcu ${SDK_DIR}/devices/${MCU_VARIANT}/system_${MCU_CORE}.c ${SDK_DIR}/devices/${MCU_VARIANT}/drivers/fsl_clock.c @@ -56,9 +56,9 @@ function(add_board_target BOARD_TARGET) # driver ${SDK_DIR}/drivers/common ${SDK_DIR}/drivers/flexcomm + ${SDK_DIR}/drivers/flexcomm/usart ${SDK_DIR}/drivers/lpc_iocon ${SDK_DIR}/drivers/lpc_gpio - ${SDK_DIR}/drivers/lpuart ${SDK_DIR}/drivers/sctimer # mcu ${SDK_DIR}/devices/${MCU_VARIANT} @@ -140,16 +140,16 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_LPC55 ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC + family_add_tinyusb(${TARGET} OPT_MCU_LPC55) + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/nxp/lpc_ip3511/dcd_lpc_ip3511.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) # Flashing + family_add_bin_hex(${TARGET}) family_flash_jlink(${TARGET}) #family_flash_nxplink(${TARGET}) #family_flash_pyocd(${TARGET}) diff --git a/hw/bsp/lpc55/family.mk b/hw/bsp/lpc55/family.mk index d82e85904..fadf852cd 100644 --- a/hw/bsp/lpc55/family.mk +++ b/hw/bsp/lpc55/family.mk @@ -1,6 +1,5 @@ UF2_FAMILY_ID = 0x2abc77ec SDK_DIR = hw/mcu/nxp/mcux-sdk -DEPS_SUBMODULES += lib/CMSIS_5 lib/sct_neopixel $(SDK_DIR) include $(TOP)/$(BOARD_PATH)/board.mk CPU_CORE ?= cortex-m33 @@ -45,7 +44,7 @@ SRC_C += \ $(SDK_DIR)/drivers/lpc_gpio/fsl_gpio.c \ $(SDK_DIR)/drivers/common/fsl_common_arm.c \ $(SDK_DIR)/drivers/flexcomm/fsl_flexcomm.c \ - $(SDK_DIR)/drivers/flexcomm/fsl_usart.c \ + $(SDK_DIR)/drivers/flexcomm/usart/fsl_usart.c \ lib/sct_neopixel/sct_neopixel.c INC += \ @@ -55,11 +54,10 @@ INC += \ $(TOP)/$(MCU_DIR) \ $(TOP)/$(MCU_DIR)/drivers \ $(TOP)/$(SDK_DIR)/drivers/common \ - $(TOP)/$(SDK_DIR)/drivers/flexcomm \ + $(TOP)/$(SDK_DIR)/drivers/flexcomm/usart \ + $(TOP)/$(SDK_DIR)/drivers/flexcomm/ \ $(TOP)/$(SDK_DIR)/drivers/lpc_iocon \ $(TOP)/$(SDK_DIR)/drivers/lpc_gpio \ $(TOP)/$(SDK_DIR)/drivers/sctimer SRC_S += $(MCU_DIR)/gcc/startup_$(MCU_CORE).S - -LIBS += $(TOP)/$(MCU_DIR)/gcc/libpower_hardabi.a diff --git a/hw/bsp/max32650/README.md b/hw/bsp/max32650/README.md deleted file mode 100644 index ca66a1ac4..000000000 --- a/hw/bsp/max32650/README.md +++ /dev/null @@ -1,46 +0,0 @@ -# Analog Devices MAX32650/1/2 - -This BSP is for working with the Analog Devices -[MAX32650](https://www.analog.com/en/products/max32650.html), -[MAX32651](https://www.analog.com/en/products/max32651.html) and -[MAX32652](https://www.analog.com/en/products/max32652.html) -microcontrollers. The following boards are supported: - * [MAX32650EVKIT](https://www.analog.com/en/resources/evaluation-hardware-and-software/evaluation-boards-kits/max32650-evkit.html) - * [MAX32650FTHR](https://www.analog.com/en/resources/evaluation-hardware-and-software/evaluation-boards-kits/max32650fthr.html) - * [MAX32651EVKIT](https://www.analog.com/en/resources/evaluation-hardware-and-software/evaluation-boards-kits/max32651-evkit.html) (Secure Bootloader) - -This part family leverages the Maxim Microcontrollers SDK (MSDK) for the device -interfaces and hardware abstraction layers. This source code package is fetched -as part of the get-deps script. - -The microcontrollers utilize the standard GNU ARM toolchain. If this toolchain -is not already available on your build machine, it can be installed by using the -bundled MSDK installation. Details on downloading and installing can be found -in the [User's Guide](https://analogdevicesinc.github.io/msdk//USERGUIDE/). - -## Flashing - -### MAX32650 and MAX32652 - -The default flashing behavior in this BSP for the MAX32650 and MAX32652 is to -utilize JLink. This can be done by running the `flash` or `flash-jlink` rule -for Makefiles, or the `-jlink` target for CMake. - -Both the Evaluation Kit and Feather boards are shipped with a CMSIS-DAP -compatible debug probe. However, at the time of writing, the necessary flashing -algorithms for OpenOCD have not yet been incorporated into the OpenOCD master -branch. To utilize the provided debug probes, please install the bundled MSDK -package which includes the appropriate OpenOCD modifications. To leverage this -OpenOCD instance, run the `flash-msdk` Makefile rule, or `-msdk` CMake -target. - -### MAX32651 - -The MAX32651 features an integrated secure bootloader which requires the -application image be signed prior to flashing. Both the Makefile and CMake -scripts account for this signing automatically when building for the -MAX32651EVKIT. - -To flash the signed image, the MSDK's OpenOCD variant must be used. To flash -the MAX32651EVKIT please install the bundled MSDK, and utilize the `flash-msdk` -and `-msdk` rule and target. diff --git a/hw/bsp/max32650/boards/max32650evkit/board.cmake b/hw/bsp/max32650/boards/max32650evkit/board.cmake deleted file mode 100644 index fffdcc9fb..000000000 --- a/hw/bsp/max32650/boards/max32650evkit/board.cmake +++ /dev/null @@ -1,10 +0,0 @@ -# Use the standard, non-secure linker file -set(LD_FILE_GNU ${CMAKE_CURRENT_LIST_DIR}/max32650.ld) - -function(update_board_extras TARGET) - #No extra arguments -endfunction() - -function(prepare_image TARGET_IN) - #No signing required -endfunction() diff --git a/hw/bsp/max32650/boards/max32650evkit/board.mk b/hw/bsp/max32650/boards/max32650evkit/board.mk deleted file mode 100644 index 0bc210e11..000000000 --- a/hw/bsp/max32650/boards/max32650evkit/board.mk +++ /dev/null @@ -1,2 +0,0 @@ -# Use the standard, non-secure linker file -LD_FILE = $(BOARD_PATH)/max32650.ld diff --git a/hw/bsp/max32650/boards/max32650fthr/board.cmake b/hw/bsp/max32650/boards/max32650fthr/board.cmake deleted file mode 100644 index fffdcc9fb..000000000 --- a/hw/bsp/max32650/boards/max32650fthr/board.cmake +++ /dev/null @@ -1,10 +0,0 @@ -# Use the standard, non-secure linker file -set(LD_FILE_GNU ${CMAKE_CURRENT_LIST_DIR}/max32650.ld) - -function(update_board_extras TARGET) - #No extra arguments -endfunction() - -function(prepare_image TARGET_IN) - #No signing required -endfunction() diff --git a/hw/bsp/max32650/boards/max32650fthr/board.mk b/hw/bsp/max32650/boards/max32650fthr/board.mk deleted file mode 100644 index 0bc210e11..000000000 --- a/hw/bsp/max32650/boards/max32650fthr/board.mk +++ /dev/null @@ -1,2 +0,0 @@ -# Use the standard, non-secure linker file -LD_FILE = $(BOARD_PATH)/max32650.ld diff --git a/hw/bsp/max32650/boards/max32650fthr/max32650.ld b/hw/bsp/max32650/boards/max32650fthr/max32650.ld deleted file mode 100644 index 0e56a91ec..000000000 --- a/hw/bsp/max32650/boards/max32650fthr/max32650.ld +++ /dev/null @@ -1,119 +0,0 @@ -MEMORY { - ROM (rx) : ORIGIN = 0x00000000, LENGTH = 0x00010000 /* 64kB ROM */ - FLASH (rx) : ORIGIN = 0x10000000, LENGTH = 0x00300000 /* 3MB flash */ - SRAM (rwx) : ORIGIN = 0x20000000, LENGTH = 0x00100000 /* 1MB SRAM */ -} - -SECTIONS { - .text : - { - _text = .; - KEEP(*(.isr_vector)) - *(.text*) /* program code */ - *(.rodata*) /* read-only data: "const" */ - - KEEP(*(.init)) - KEEP(*(.fini)) - - /* .ctors */ - *crtbegin.o(.ctors) - *crtbegin?.o(.ctors) - *(EXCLUDE_FILE(*crtend?.o *crtend.o) .ctors) - *(SORT(.ctors.*)) - *(.ctors) - - /* .dtors */ - *crtbegin.o(.dtors) - *crtbegin?.o(.dtors) - *(EXCLUDE_FILE(*crtend?.o *crtend.o) .dtors) - *(SORT(.dtors.*)) - *(.dtors) - - /* C++ Exception handling */ - KEEP(*(.eh_frame*)) - _etext = .; - } > FLASH - - .ARM.extab : - { - *(.ARM.extab* .gnu.linkonce.armextab.*) - } > FLASH - - /* it's used for C++ exception handling */ - /* we need to keep this to avoid overlapping */ - .ARM.exidx : - { - __exidx_start = .; - *(.ARM.exidx* .gnu.linkonce.armexidx.*) - __exidx_end = .; - } > FLASH - - .data : - { - _data = ALIGN(., 4); - *(vtable) - *(.data*) /*read-write initialized data: initialized global variable*/ - *(.spix_config*) /* SPIX configuration functions need to be run from SRAM */ - *(.flashprog*) /* Flash program */ - - - /* These array sections are used by __libc_init_array to call static C++ constructors */ - . = ALIGN(4); - /* preinit data */ - PROVIDE_HIDDEN (__preinit_array_start = .); - KEEP(*(.preinit_array)) - PROVIDE_HIDDEN (__preinit_array_end = .); - - . = ALIGN(4); - /* init data */ - PROVIDE_HIDDEN (__init_array_start = .); - KEEP(*(SORT(.init_array.*))) - KEEP(*(.init_array)) - PROVIDE_HIDDEN (__init_array_end = .); - - . = ALIGN(4); - /* finit data */ - PROVIDE_HIDDEN (__fini_array_start = .); - KEEP(*(SORT(.fini_array.*))) - KEEP(*(.fini_array)) - PROVIDE_HIDDEN (__fini_array_end = .); - - _edata = ALIGN(., 4); - } > SRAM AT>FLASH - __load_data = LOADADDR(.data); - .bss : - { - . = ALIGN(4); - _bss = .; - *(.bss*) /*read-write zero initialized data: uninitialized global variable*/ - *(COMMON) - _ebss = ALIGN(., 4); - } > SRAM - - /* Set stack top to end of RAM, and stack limit move down by - * size of stack_dummy section */ - __StackTop = ORIGIN(SRAM) + LENGTH(SRAM); - __StackLimit = __StackTop - SIZEOF(.stack_dummy); - - /* .stack_dummy section doesn't contains any symbols. It is only - * used for linker to calculate size of stack sections, and assign - * values to stack symbols later */ - .stack_dummy (COPY): - { - *(.stack*) - } > SRAM - - .heap (COPY): - { - . = ALIGN(4); - PROVIDE ( end = . ); - PROVIDE ( _end = . ); - *(.heap*) - __HeapLimit = ABSOLUTE(__StackLimit); - } > SRAM - - PROVIDE(__stack = __StackTop); - - /* Check if data + heap + stack exceeds RAM limit */ - ASSERT(__StackLimit >= _ebss, "region RAM overflowed with stack") -} diff --git a/hw/bsp/max32650/family.c b/hw/bsp/max32650/family.c deleted file mode 100644 index bb382cdd4..000000000 --- a/hw/bsp/max32650/family.c +++ /dev/null @@ -1,173 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2024 Brent Kowal (Analog Devices, Inc) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - * This file is part of the TinyUSB stack. - */ - -#ifdef __GNUC__ -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wstrict-prototypes" // _mxc_crit_get_state() -#endif - -#include "gpio.h" -#include "mxc_sys.h" -#include "mxc_device.h" -#include "uart.h" - -#ifdef __GNUC__ -#pragma GCC diagnostic pop -#endif - -#include "board.h" -#include "bsp/board_api.h" - - -//--------------------------------------------------------------------+ -// Forward USB interrupt events to TinyUSB IRQ Handler -//--------------------------------------------------------------------+ -void USB_IRQHandler(void) { - tud_int_handler(0); -} - -//--------------------------------------------------------------------+ -// MACRO TYPEDEF CONSTANT ENUM -//--------------------------------------------------------------------+ -mxc_uart_regs_t *ConsoleUart = MXC_UART_GET_UART(UART_NUM); - -void board_init(void) { -#if CFG_TUSB_OS == OPT_OS_NONE - // 1ms tick timer - SysTick_Config(SystemCoreClock / 1000); -#elif CFG_TUSB_OS == OPT_OS_FREERTOS - // If freeRTOS is used, IRQ priority is limit by max syscall ( smaller is higher ) - NVIC_SetPriority(USB_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY); -#endif - mxc_gpio_cfg_t gpioConfig; - - // LED - gpioConfig.drvstr = MXC_GPIO_DRVSTR_0; - gpioConfig.func = MXC_GPIO_FUNC_OUT; - gpioConfig.mask = LED_PIN; - gpioConfig.pad = MXC_GPIO_PAD_NONE; - gpioConfig.port = LED_PORT; - gpioConfig.vssel = LED_VDDIO; - MXC_GPIO_Config(&gpioConfig); - board_led_write(false); - - // Button - gpioConfig.drvstr = MXC_GPIO_DRVSTR_0; - gpioConfig.func = MXC_GPIO_FUNC_IN; - gpioConfig.mask = BUTTON_PIN; - gpioConfig.pad = BUTTON_PULL; - gpioConfig.port = BUTTON_PORT; - gpioConfig.vssel = MXC_GPIO_VSSEL_VDDIO; - MXC_GPIO_Config(&gpioConfig); - - // UART - MXC_UART_Init(ConsoleUart, CFG_BOARD_UART_BAUDRATE); - - //USB - // Startup the HIRC96M clock if it's not on already - if (!(MXC_GCR->clk_ctrl & MXC_F_GCR_CLK_CTRL_HIRC96_EN)) { - MXC_GCR->clk_ctrl |= MXC_F_GCR_CLK_CTRL_HIRC96_EN; - MXC_SYS_Clock_Timeout(MXC_F_GCR_CLK_CTRL_HIRC96_RDY); - } - - MXC_SYS_ClockEnable(MXC_SYS_PERIPH_CLOCK_USB); - MXC_SYS_Reset_Periph(MXC_SYS_RESET_USB); -} - -//--------------------------------------------------------------------+ -// Board porting API -//--------------------------------------------------------------------+ - -void board_led_write(bool state) { -#if LED_STATE_ON - state = !state; -#endif - if (state) { - MXC_GPIO_OutClr(LED_PORT, LED_PIN); - } else { - MXC_GPIO_OutSet(LED_PORT, LED_PIN); - } -} - -uint32_t board_button_read(void) { - uint32_t state = MXC_GPIO_InGet(BUTTON_PORT, BUTTON_PIN) ? 1 : 0; - return BUTTON_STATE_ACTIVE == state; -} - -size_t board_get_unique_id(uint8_t id[], size_t max_len) { - uint8_t hw_id[13];//USN Buffer - MXC_SYS_GetUSN(hw_id, 13); - - size_t act_len = TU_MIN(max_len, 13); - memcpy(id, hw_id, act_len); - return act_len; -} - -int board_uart_read(uint8_t *buf, int len) { - int uart_val; - int act_len = 0; - - while (act_len < len) { - if ((uart_val = MXC_UART_ReadCharacterRaw(ConsoleUart)) == E_UNDERFLOW) { - break; - } else { - *buf++ = (uint8_t) uart_val; - act_len++; - } - } - return act_len; -} - -int board_uart_write(void const *buf, int len) { - int act_len = 0; - const uint8_t *ch_ptr = (const uint8_t *) buf; - while (act_len < len) { - MXC_UART_WriteCharacter(ConsoleUart, *ch_ptr++); - act_len++; - } - return len; -} - -#if CFG_TUSB_OS == OPT_OS_NONE -volatile uint32_t system_ticks = 0; - -void SysTick_Handler(void) { - system_ticks++; -} - -uint32_t board_millis(void) { - return system_ticks; -} -#endif - -void HardFault_Handler(void) { - __asm("BKPT #0\n"); -} - -// Required by __libc_init_array in startup code if we are compiling using -// -nostdlib/-nostartfiles. -void _init(void) { -} diff --git a/hw/bsp/max32650/family.cmake b/hw/bsp/max32650/family.cmake deleted file mode 100644 index 48853b92c..000000000 --- a/hw/bsp/max32650/family.cmake +++ /dev/null @@ -1,169 +0,0 @@ -include_guard() - -set(MAX32_PERIPH ${TOP}/hw/mcu/analog/max32/Libraries/PeriphDrivers) -set(MAX32_CMSIS ${TOP}/hw/mcu/analog/max32/Libraries/CMSIS) -set(CMSIS_5 ${TOP}/lib/CMSIS_5) - -# include board specific information and functions -include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) - -# Get the linker file -set(LD_FILE_Clang ${LD_FILE_GNU}) - -# toolchain set up -set(CMAKE_SYSTEM_PROCESSOR cortex-m4 CACHE INTERNAL "System Processor") -set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) -set(JLINK_DEVICE max32650) -set(OPENOCD_OPTION "-f interface/cmsis-dap.cfg -f target/max32650.cfg") - -set(FAMILY_MCUS MAX32650 CACHE INTERNAL "") - -function(update_board TARGET) - target_compile_definitions(${TARGET} PUBLIC - TARGET=MAX32650 - TARGET_REV=0x4131 - MXC_ASSERT_ENABLE - MAX32650 - IAR_PRAGMAS=0 - CFG_TUSB_MCU=OPT_MCU_MAX32650 - BOARD_TUD_MAX_SPEED=OPT_MODE_HIGH_SPEED - ) - - # Run any board specific updates - update_board_extras(${TARGET}) -endfunction() - -#------------------------------------ -# BOARD_TARGET -#------------------------------------ -# only need to be built ONCE for all examples -function(add_board_target BOARD_TARGET) - if (TARGET ${BOARD_TARGET}) - return() - endif () - - # Startup & Linker script - set(STARTUP_FILE_GNU ${MAX32_CMSIS}/Device/Maxim/MAX32650/Source/GCC/startup_max32650.S) - set(STARTUP_FILE_Clang ${STARTUP_FILE_GNU}) - - set(PERIPH_SRC ${MAX32_PERIPH}/Source) - add_library(${BOARD_TARGET} STATIC - ${MAX32_CMSIS}/Device/Maxim/MAX32650/Source/heap.c - ${MAX32_CMSIS}/Device/Maxim/MAX32650/Source/header_MAX32650.c - ${MAX32_CMSIS}/Device/Maxim/MAX32650/Source/system_max32650.c - ${PERIPH_SRC}/SYS/mxc_assert.c - ${PERIPH_SRC}/SYS/mxc_delay.c - ${PERIPH_SRC}/SYS/mxc_lock.c - ${PERIPH_SRC}/SYS/nvic_table.c - ${PERIPH_SRC}/SYS/pins_me10.c - ${PERIPH_SRC}/SYS/sys_me10.c - ${PERIPH_SRC}/TPU/tpu_me10.c - ${PERIPH_SRC}/TPU/tpu_reva.c - ${PERIPH_SRC}/FLC/flc_common.c - ${PERIPH_SRC}/FLC/flc_me10.c - ${PERIPH_SRC}/FLC/flc_reva.c - ${PERIPH_SRC}/GPIO/gpio_common.c - ${PERIPH_SRC}/GPIO/gpio_me10.c - ${PERIPH_SRC}/GPIO/gpio_reva.c - ${PERIPH_SRC}/ICC/icc_me10.c - ${PERIPH_SRC}/ICC/icc_reva.c - ${PERIPH_SRC}/ICC/icc_common.c - ${PERIPH_SRC}/UART/uart_common.c - ${PERIPH_SRC}/UART/uart_me10.c - ${PERIPH_SRC}/UART/uart_reva.c - ${STARTUP_FILE_${CMAKE_C_COMPILER_ID}} - ) - target_include_directories(${BOARD_TARGET} PUBLIC - ${CMAKE_CURRENT_FUNCTION_LIST_DIR} - ${MAX32_CMSIS}/Include - ${MAX32_CMSIS}/Device/Maxim/MAX32650/Include - ${MAX32_PERIPH}/Include/MAX32650 - ${PERIPH_SRC}/SYS - ${PERIPH_SRC}/GPIO - ${PERIPH_SRC}/TPU - ${PERIPH_SRC}/ICC - ${PERIPH_SRC}/FLC - ${PERIPH_SRC}/UART - ) - - target_compile_options(${BOARD_TARGET} PRIVATE - -Wno-error=strict-prototypes - ) - update_board(${BOARD_TARGET}) - - if (CMAKE_C_COMPILER_ID STREQUAL "GNU") - target_link_options(${BOARD_TARGET} PUBLIC - "LINKER:--script=${LD_FILE_GNU}" - -nostartfiles - --specs=nosys.specs --specs=nano.specs - -u sb_header #Needed when linking libraries to not lose the Signing header - ) - elseif (CMAKE_C_COMPILER_ID STREQUAL "Clang") - target_link_options(${BOARD_TARGET} PUBLIC - "LINKER:--script=${LD_FILE_Clang}" - ) - endif () -endfunction() - - -#------------------------------------ -# Functions -#------------------------------------ -function(family_configure_example TARGET RTOS) - family_configure_common(${TARGET} ${RTOS}) - - # Board target - add_board_target(board_${BOARD}) - - #---------- Port Specific ---------- - # These files are built for each example since it depends on example's tusb_config.h - target_sources(${TARGET} PUBLIC - # BSP - ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/family.c - ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/../board.c - ) - target_include_directories(${TARGET} PUBLIC - # family, hw, board - ${CMAKE_CURRENT_FUNCTION_LIST_DIR} - ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/../../ - ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/boards/${BOARD} - ) - - # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_MAX32650 ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC - ${TOP}/src/portable/mentor/musb/dcd_musb.c - ) - target_compile_options(${TARGET} PRIVATE - -Wno-error=strict-prototypes - ) - - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) - target_compile_options(${TARGET}-tinyusb PRIVATE - -Wno-error=strict-prototypes - ) - - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) - - # Flashing - family_flash_jlink(${TARGET}) - family_flash_openocd_adi(${TARGET}) - - # Add the optional MSDK OpenOCD flashing - family_flash_msdk(${TARGET}) -endfunction() - -function(family_flash_msdk TARGET) - # Prepare the image (signed) if the board requires it - prepare_image(${TARGET}) - - set(MAXIM_PATH "$ENV{MAXIM_PATH}") - add_custom_target(${TARGET}-msdk - DEPENDS ${TARGET} - COMMAND ${MAXIM_PATH}/Tools/OpenOCD/openocd -s ${MAXIM_PATH}/Tools/OpenOCD/scripts - -f interface/cmsis-dap.cfg -f target/max32650.cfg - -c "program $ verify; init; reset; exit" - VERBATIM - ) -endfunction() diff --git a/hw/bsp/max32650/family.mk b/hw/bsp/max32650/family.mk deleted file mode 100644 index d2fc293e4..000000000 --- a/hw/bsp/max32650/family.mk +++ /dev/null @@ -1,140 +0,0 @@ -DEPS_SUBMODULES += lib/CMSIS_5 hw/mcu/analog/max32 - -# Important locations in the hw support for MCU -MAX32_CMSIS = hw/mcu/analog/max32/Libraries/CMSIS -MAX32_PERIPH = hw/mcu/analog/max32/Libraries/PeriphDrivers - -# Add any board specific make rules -include $(TOP)/$(BOARD_PATH)/board.mk - -CPU_CORE ?= cortex-m4 -PORT ?= 0 - -# GCC -SRC_S_GCC += $(MAX32_CMSIS)/Device/Maxim/MAX32650/Source/GCC/startup_max32650.S - -# -------------- -# Compiler Flags -# -------------- -# Flags for the MAX32650/1/2 SDK -CFLAGS += -DTARGET=MAX32650 \ - -DTARGET_REV=0x4131 \ - -DMXC_ASSERT_ENABLE \ - -DMAX32650 \ - -DIAR_PRAGMAS=0 - -# Flags for TUSB features -CFLAGS += \ - -DCFG_TUSB_MCU=OPT_MCU_MAX32650 \ - -DBOARD_TUD_MAX_SPEED=OPT_MODE_HIGH_SPEED - -# mcu driver cause following warnings -CFLAGS += -Wno-error=strict-prototypes \ - -Wno-error=unused-parameter \ - -Wno-error=cast-align \ - -Wno-error=cast-qual \ - -Wno-error=sign-compare - -LDFLAGS_GCC += -nostartfiles --specs=nosys.specs --specs=nano.specs - -# Configure the flash rule. By default, use JLink. -SIGNED_BUILD ?= 0 -DEFAULT_FLASH = flash-jlink - -# If the applications needs to be signed (for the MAX32651), sign it first and -# then need to use MSDK's OpenOCD to flash it -# Also need to include the __SLA_FWK__ define to enable the signed header into -# memory -ifeq ($(SIGNED_BUILD), 1) -# Extra definitions to build for the secure part -CFLAGS += -D__SLA_FWK__ -DEFAULT_FLASH := sign-build flash-msdk -endif - -# For flash-jlink target -JLINK_DEVICE = max32650 - -# Configure the flash rule -flash: $(DEFAULT_FLASH) - -# ----------------- -# Sources & Include -# ----------------- -PERIPH_SRC = $(TOP)/$(MAX32_PERIPH)/Source -SRC_C += \ - src/portable/mentor/musb/dcd_musb.c \ - $(MAX32_CMSIS)/Device/Maxim/MAX32650/Source/heap.c \ - $(MAX32_CMSIS)/Device/Maxim/MAX32650/Source/system_max32650.c \ - $(MAX32_CMSIS)/Device/Maxim/MAX32650/Source/header_MAX32650.c \ - $(PERIPH_SRC)/SYS/mxc_assert.c \ - $(PERIPH_SRC)/SYS/mxc_delay.c \ - $(PERIPH_SRC)/SYS/mxc_lock.c \ - $(PERIPH_SRC)/SYS/nvic_table.c \ - $(PERIPH_SRC)/SYS/pins_me10.c \ - $(PERIPH_SRC)/SYS/sys_me10.c \ - $(PERIPH_SRC)/FLC/flc_common.c \ - $(PERIPH_SRC)/FLC/flc_me10.c \ - $(PERIPH_SRC)/FLC/flc_reva.c \ - $(PERIPH_SRC)/GPIO/gpio_common.c \ - $(PERIPH_SRC)/GPIO/gpio_me10.c \ - $(PERIPH_SRC)/GPIO/gpio_reva.c \ - $(PERIPH_SRC)/ICC/icc_me10.c \ - $(PERIPH_SRC)/ICC/icc_reva.c \ - $(PERIPH_SRC)/ICC/icc_common.c \ - $(PERIPH_SRC)/TPU/tpu_me10.c \ - $(PERIPH_SRC)/TPU/tpu_reva.c \ - $(PERIPH_SRC)/UART/uart_common.c \ - $(PERIPH_SRC)/UART/uart_me10.c \ - $(PERIPH_SRC)/UART/uart_reva.c \ - -INC += \ - $(TOP)/$(BOARD_PATH) \ - $(TOP)/$(MAX32_CMSIS)/Include \ - $(TOP)/$(MAX32_CMSIS)/Device/Maxim/MAX32650/Include \ - $(TOP)/$(MAX32_PERIPH)/Include/MAX32650 \ - $(PERIPH_SRC)/SYS \ - $(PERIPH_SRC)/GPIO \ - $(PERIPH_SRC)/ICC \ - $(PERIPH_SRC)/FLC \ - $(PERIPH_SRC)/TPU \ - $(PERIPH_SRC)/UART - - -# The MAX32651EVKIT is pin for pin identical to the MAX32650EVKIT, however the -# MAX32651 has a secure bootloader which requires the image to be signed before -# loading into flash. All MAX32651EVKIT's have the same key for evaluation -# purposes, so create a special flash rule to sign the binary and flash using -# the MSDK. -MCU_PATH = $(TOP)/hw/mcu/analog/max32/ -# Assume no extension for sign utility -SIGN_EXE = sign_app -ifeq ($(OS), Windows_NT) -# Must use .exe extension on Windows, since the binaries -# for Linux may live in the same place. -SIGN_EXE := sign_app.exe -else -UNAME = $(shell uname -s) -ifneq ($(findstring MSYS_NT,$(UNAME)),) -# Must also use .exe extension for MSYS2 -SIGN_EXE := sign_app.exe -endif -endif - -# Rule to sign the build. This will in-place modify the existing .elf file -# an populate the .sig section with the signature value -sign-build: $(BUILD)/$(PROJECT).elf - $(OBJCOPY) $(BUILD)/$(PROJECT).elf -R .sig -O binary $(BUILD)/$(PROJECT).bin - $(MCU_PATH)/Tools/SBT/bin/$(SIGN_EXE) -c MAX32651 \ - key_file="$(MCU_PATH)/Tools/SBT/devices/MAX32651/keys/maximtestcrk.key" \ - ca=$(BUILD)/$(PROJECT).bin sca=$(BUILD)/$(PROJECT).sbin - $(OBJCOPY) $(BUILD)/$(PROJECT).elf --update-section .sig=$(BUILD)/$(PROJECT).sig - -# Optional flash option when running within an installed MSDK to use OpenOCD -# Mainline OpenOCD does not yet have the MAX32's flash algorithm integrated. -# If the MSDK is installed, flash-msdk can be run to utilize the the modified -# openocd with the algorithms -MAXIM_PATH := $(subst \,/,$(MAXIM_PATH)) -flash-msdk: $(BUILD)/$(PROJECT).elf - $(MAXIM_PATH)/Tools/OpenOCD/openocd -s $(MAXIM_PATH)/Tools/OpenOCD/scripts \ - -f interface/cmsis-dap.cfg -f target/max32650.cfg \ - -c "program $(BUILD)/$(PROJECT).elf verify; init; reset; exit" diff --git a/hw/bsp/max32666/README.md b/hw/bsp/max32666/README.md deleted file mode 100644 index 902d82e25..000000000 --- a/hw/bsp/max32666/README.md +++ /dev/null @@ -1,32 +0,0 @@ -# Analog Devices MAX32665/6 - -This BSP is for working with the Analog Devices -[MAX32665](https://www.analog.com/en/products/max32665.html) and -[MAX32666](https://www.analog.com/en/products/max32666.html) microcontrollers. -The following boards are supported: - * [MAX32666EVKIT](https://www.analog.com/en/resources/evaluation-hardware-and-software/evaluation-boards-kits/max32666evkit.html) - * [MAX32666FTHR](https://www.analog.com/en/resources/evaluation-hardware-and-software/evaluation-boards-kits/max32666fthr.html) - - -This part family leverages the Maxim Microcontrollers SDK (MSDK) for the device -interfaces and hardware abstraction layers. This source code package is fetched -as part of the get-deps script. - -The microcontrollers utilize the standard GNU ARM toolchain. If this toolchain -is not already available on your build machine, it can be installed by using the -bundled MSDK installation. Details on downloading and installing can be found -in the [User's Guide](https://analogdevicesinc.github.io/msdk//USERGUIDE/). - -## Flashing - -The default flashing behavior in this BSP is to utilize JLink. This can be done -by running the `flash` or `flash-jlink` rule for Makefiles, or the -`-jlink` target for CMake. - -Both the Evaluation Kit and Feather boards are shipped with a CMSIS-DAP -compatible debug probe. However, at the time of writing, the necessary flashing -algorithms for OpenOCD have not yet been incorporated into the OpenOCD master -branch. To utilize the provided debug probes, please install the bundled MSDK -package which includes the appropriate OpenOCD modifications. To leverage this -OpenOCD instance, run the `flash-msdk` Makefile rule, or `-msdk` CMake -target. diff --git a/hw/bsp/max32666/boards/max32666evkit/board.cmake b/hw/bsp/max32666/boards/max32666evkit/board.cmake deleted file mode 100644 index 9dc6962eb..000000000 --- a/hw/bsp/max32666/boards/max32666evkit/board.cmake +++ /dev/null @@ -1 +0,0 @@ -# Nothing to be done at the board level diff --git a/hw/bsp/max32666/boards/max32666evkit/board.mk b/hw/bsp/max32666/boards/max32666evkit/board.mk deleted file mode 100644 index a813a5327..000000000 --- a/hw/bsp/max32666/boards/max32666evkit/board.mk +++ /dev/null @@ -1 +0,0 @@ -# No specific build requirements for the board. diff --git a/hw/bsp/max32666/boards/max32666fthr/board.cmake b/hw/bsp/max32666/boards/max32666fthr/board.cmake deleted file mode 100644 index 9dc6962eb..000000000 --- a/hw/bsp/max32666/boards/max32666fthr/board.cmake +++ /dev/null @@ -1 +0,0 @@ -# Nothing to be done at the board level diff --git a/hw/bsp/max32666/boards/max32666fthr/board.mk b/hw/bsp/max32666/boards/max32666fthr/board.mk deleted file mode 100644 index a813a5327..000000000 --- a/hw/bsp/max32666/boards/max32666fthr/board.mk +++ /dev/null @@ -1 +0,0 @@ -# No specific build requirements for the board. diff --git a/hw/bsp/max32666/family.cmake b/hw/bsp/max32666/family.cmake deleted file mode 100644 index fb8c32295..000000000 --- a/hw/bsp/max32666/family.cmake +++ /dev/null @@ -1,147 +0,0 @@ -include_guard() - -set(MAX32_PERIPH ${TOP}/hw/mcu/analog/max32/Libraries/PeriphDrivers) -set(MAX32_CMSIS ${TOP}/hw/mcu/analog/max32/Libraries/CMSIS) -set(CMSIS_5 ${TOP}/lib/CMSIS_5) - -# include board specific -include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) - -# Get the linker file from current location (family) -set(LD_FILE_GNU ${CMAKE_CURRENT_LIST_DIR}/max32666.ld) -set(LD_FILE_Clang ${LD_FILE_GNU}) - -# toolchain set up -set(CMAKE_SYSTEM_PROCESSOR cortex-m4 CACHE INTERNAL "System Processor") -set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) -set(JLINK_DEVICE max32666) -set(OPENOCD_OPTION "-f interface/cmsis-dap.cfg -f target/max32665.cfg") - -set(FAMILY_MCUS MAX32666 CACHE INTERNAL "") - -function(update_board TARGET) - target_compile_definitions(${TARGET} PUBLIC - TARGET=MAX32665 - TARGET_REV=0x4131 - MXC_ASSERT_ENABLE - MAX32665 - IAR_PRAGMAS=0 - CFG_TUSB_MCU=OPT_MCU_MAX32666 - BOARD_TUD_MAX_SPEED=OPT_MODE_HIGH_SPEED - ) -endfunction() - -#------------------------------------ -# BOARD_TARGET -#------------------------------------ -# only need to be built ONCE for all examples -function(add_board_target BOARD_TARGET) - if (TARGET ${BOARD_TARGET}) - return() - endif () - - # Startup & Linker script - set(STARTUP_FILE_GNU ${MAX32_CMSIS}/Device/Maxim/MAX32665/Source/GCC/startup_max32665.S) - set(STARTUP_FILE_Clang ${STARTUP_FILE_GNU}) - - set(PERIPH_SRC ${MAX32_PERIPH}/Source) - add_library(${BOARD_TARGET} STATIC - ${MAX32_CMSIS}/Device/Maxim/MAX32665/Source/heap.c - ${MAX32_CMSIS}/Device/Maxim/MAX32665/Source/system_max32665.c - ${PERIPH_SRC}/SYS/mxc_assert.c - ${PERIPH_SRC}/SYS/mxc_delay.c - ${PERIPH_SRC}/SYS/mxc_lock.c - ${PERIPH_SRC}/SYS/nvic_table.c - ${PERIPH_SRC}/SYS/pins_me14.c - ${PERIPH_SRC}/SYS/sys_me14.c - ${PERIPH_SRC}/TPU/tpu_me14.c - ${PERIPH_SRC}/TPU/tpu_reva.c - ${PERIPH_SRC}/FLC/flc_common.c - ${PERIPH_SRC}/FLC/flc_me14.c - ${PERIPH_SRC}/FLC/flc_reva.c - ${PERIPH_SRC}/GPIO/gpio_common.c - ${PERIPH_SRC}/GPIO/gpio_me14.c - ${PERIPH_SRC}/GPIO/gpio_reva.c - ${PERIPH_SRC}/ICC/icc_me14.c - ${PERIPH_SRC}/ICC/icc_reva.c - ${PERIPH_SRC}/UART/uart_common.c - ${PERIPH_SRC}/UART/uart_me14.c - ${PERIPH_SRC}/UART/uart_reva.c - ${STARTUP_FILE_${CMAKE_C_COMPILER_ID}} - ) - target_include_directories(${BOARD_TARGET} PUBLIC - ${CMAKE_CURRENT_FUNCTION_LIST_DIR} - ${MAX32_CMSIS}/Include - ${MAX32_CMSIS}/Device/Maxim/MAX32665/Include - ${MAX32_PERIPH}/Include/MAX32665 - ${PERIPH_SRC}/SYS - ${PERIPH_SRC}/GPIO - ${PERIPH_SRC}/TPU - ${PERIPH_SRC}/ICC - ${PERIPH_SRC}/FLC - ${PERIPH_SRC}/UART - ) - - target_compile_options(${BOARD_TARGET} PRIVATE - -Wno-error=strict-prototypes - ) - update_board(${BOARD_TARGET}) - - if (CMAKE_C_COMPILER_ID STREQUAL "GNU") - target_link_options(${BOARD_TARGET} PUBLIC - "LINKER:--script=${LD_FILE_GNU}" - -nostartfiles - --specs=nosys.specs --specs=nano.specs - ) - elseif (CMAKE_C_COMPILER_ID STREQUAL "Clang") - target_link_options(${BOARD_TARGET} PUBLIC - "LINKER:--script=${LD_FILE_Clang}" - ) - endif () -endfunction() - - -#------------------------------------ -# Functions -#------------------------------------ -function(family_configure_example TARGET RTOS) - family_configure_common(${TARGET} ${RTOS}) - - # Board target - add_board_target(board_${BOARD}) - - #---------- Port Specific ---------- - # These files are built for each example since it depends on example's tusb_config.h - target_sources(${TARGET} PUBLIC - # BSP - ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/family.c - ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/../board.c - ) - target_include_directories(${TARGET} PUBLIC - # family, hw, board - ${CMAKE_CURRENT_FUNCTION_LIST_DIR} - ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/../../ - ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/boards/${BOARD} - ) - - # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_MAX32666 ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC - ${TOP}/src/portable/mentor/musb/dcd_musb.c - ) - target_compile_options(${TARGET} PRIVATE - -Wno-error=strict-prototypes - ) - - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) - target_compile_options(${TARGET}-tinyusb PRIVATE - -Wno-error=strict-prototypes - ) - - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) - - # Flashing - family_flash_jlink(${TARGET}) - family_flash_openocd_adi(${TARGET}) -endfunction() diff --git a/hw/bsp/max32666/family.mk b/hw/bsp/max32666/family.mk deleted file mode 100644 index b4f7d1e57..000000000 --- a/hw/bsp/max32666/family.mk +++ /dev/null @@ -1,93 +0,0 @@ -DEPS_SUBMODULES += lib/CMSIS_5 hw/mcu/analog/max32 - -# Important locations in the hw support for MCU -MAX32_CMSIS = hw/mcu/analog/max32/Libraries/CMSIS -MAX32_PERIPH = hw/mcu/analog/max32/Libraries/PeriphDrivers - -# Add any board specific make rules -include $(TOP)/$(BOARD_PATH)/board.mk - -CPU_CORE ?= cortex-m4 -PORT ?= 0 - -# GCC -SRC_S_GCC += $(MAX32_CMSIS)/Device/Maxim/MAX32665/Source/GCC/startup_max32665.S -LD_FILE = $(FAMILY_PATH)/max32666.ld - -# -------------- -# Compiler Flags -# -------------- -# Flags for the MAX32665/6 SDK -CFLAGS += -DTARGET=MAX32665 \ - -DTARGET_REV=0x4131 \ - -DMXC_ASSERT_ENABLE \ - -DMAX32665 \ - -DIAR_PRAGMAS=0 - -# Flags for TUSB features -CFLAGS += \ - -DCFG_TUSB_MCU=OPT_MCU_MAX32666 \ - -DBOARD_TUD_MAX_SPEED=OPT_MODE_HIGH_SPEED - -# mcu driver cause following warnings -CFLAGS += -Wno-error=strict-prototypes \ - -Wno-error=unused-parameter \ - -Wno-error=cast-align \ - -Wno-error=cast-qual -LDFLAGS_GCC += -nostartfiles --specs=nosys.specs --specs=nano.specs - -# For flash-jlink target -JLINK_DEVICE = max32666 - -# flash target using Jlink by default -flash: flash-jlink - -# Optional flash option when running within an installed MSDK to use OpenOCD -# Mainline OpenOCD does not yet have the MAX32's flash algorithm integrated. -# If the MSDK is installed, flash-msdk can be run to utilize the the modified -# openocd with the algorithms -MAXIM_PATH := $(subst \,/,$(MAXIM_PATH)) -flash-msdk: $(BUILD)/$(PROJECT).elf - $(MAXIM_PATH)/Tools/OpenOCD/openocd -s $(MAXIM_PATH)/Tools/OpenOCD/scripts \ - -f interface/cmsis-dap.cfg -f target/max32665.cfg \ - -c "program $(BUILD)/$(PROJECT).elf verify; init; reset; exit" - -# ----------------- -# Sources & Include -# ----------------- -PERIPH_SRC = $(TOP)/$(MAX32_PERIPH)/Source -SRC_C += \ - src/portable/mentor/musb/dcd_musb.c \ - $(MAX32_CMSIS)/Device/Maxim/MAX32665/Source/heap.c \ - $(MAX32_CMSIS)/Device/Maxim/MAX32665/Source/system_max32665.c \ - $(PERIPH_SRC)/SYS/mxc_assert.c \ - $(PERIPH_SRC)/SYS/mxc_delay.c \ - $(PERIPH_SRC)/SYS/mxc_lock.c \ - $(PERIPH_SRC)/SYS/nvic_table.c \ - $(PERIPH_SRC)/SYS/pins_me14.c \ - $(PERIPH_SRC)/SYS/sys_me14.c \ - $(PERIPH_SRC)/FLC/flc_common.c \ - $(PERIPH_SRC)/FLC/flc_me14.c \ - $(PERIPH_SRC)/FLC/flc_reva.c \ - $(PERIPH_SRC)/GPIO/gpio_common.c \ - $(PERIPH_SRC)/GPIO/gpio_me14.c \ - $(PERIPH_SRC)/GPIO/gpio_reva.c \ - $(PERIPH_SRC)/ICC/icc_me14.c \ - $(PERIPH_SRC)/ICC/icc_reva.c \ - $(PERIPH_SRC)/TPU/tpu_me14.c \ - $(PERIPH_SRC)/TPU/tpu_reva.c \ - $(PERIPH_SRC)/UART/uart_common.c \ - $(PERIPH_SRC)/UART/uart_me14.c \ - $(PERIPH_SRC)/UART/uart_reva.c \ - -INC += \ - $(TOP)/$(BOARD_PATH) \ - $(TOP)/$(MAX32_CMSIS)/Include \ - $(TOP)/$(MAX32_CMSIS)/Device/Maxim/MAX32665/Include \ - $(TOP)/$(MAX32_PERIPH)/Include/MAX32665 \ - $(PERIPH_SRC)/SYS \ - $(PERIPH_SRC)/GPIO \ - $(PERIPH_SRC)/ICC \ - $(PERIPH_SRC)/FLC \ - $(PERIPH_SRC)/TPU \ - $(PERIPH_SRC)/UART diff --git a/hw/bsp/max32690/README.md b/hw/bsp/max32690/README.md deleted file mode 100644 index 081ae0ad4..000000000 --- a/hw/bsp/max32690/README.md +++ /dev/null @@ -1,31 +0,0 @@ -# Analog Devices MAX32690 - -This BSP is for working with the Analog Devices -[MAX32690](https://www.analog.com/en/products/max32690.html) microcontroller. -The following boards are supported: - * [MAX32690EVKIT](https://www.analog.com/en/resources/evaluation-hardware-and-software/evaluation-boards-kits/max32690evkit.html) - * [AD-APARD32690-SL](https://www.analog.com/en/resources/evaluation-hardware-and-software/evaluation-boards-kits/ad-apard32690-sl.html) - - -This part family leverages the Maxim Microcontrollers SDK (MSDK) for the device -interfaces and hardware abstraction layers. This source code package is fetched -as part of the get-deps script. - -The microcontroller utilizes the standard GNU ARM toolchain. If this toolchain -is not already available on your build machine, it can be installed by using the -bundled MSDK installation. Details on downloading and installing can be found -in the [User's Guide](https://analogdevicesinc.github.io/msdk//USERGUIDE/). - -## Flashing - -The default flashing behavior in this BSP is to utilize JLink. This can be done -by running the `flash` or `flash-jlink` rule for Makefiles, or the -`-jlink` target for CMake. - -Both the Evaluation Kit and APARD boards are shipped with a CMSIS-DAP -compatible debug probe. However, at the time of writing, the necessary flashing -algorithms for OpenOCD have not yet been incorporated into the OpenOCD master -branch. To utilize the provided debug probes, please install the bundled MSDK -package which includes the appropriate OpenOCD modifications. To leverage this -OpenOCD instance, run the `flash-msdk` Makefile rule, or `-msdk` CMake -target. diff --git a/hw/bsp/max32690/boards/apard32690/board.cmake b/hw/bsp/max32690/boards/apard32690/board.cmake deleted file mode 100644 index 9dc6962eb..000000000 --- a/hw/bsp/max32690/boards/apard32690/board.cmake +++ /dev/null @@ -1 +0,0 @@ -# Nothing to be done at the board level diff --git a/hw/bsp/max32690/boards/apard32690/board.mk b/hw/bsp/max32690/boards/apard32690/board.mk deleted file mode 100644 index a813a5327..000000000 --- a/hw/bsp/max32690/boards/apard32690/board.mk +++ /dev/null @@ -1 +0,0 @@ -# No specific build requirements for the board. diff --git a/hw/bsp/max32690/boards/max32690evkit/board.cmake b/hw/bsp/max32690/boards/max32690evkit/board.cmake deleted file mode 100644 index 9dc6962eb..000000000 --- a/hw/bsp/max32690/boards/max32690evkit/board.cmake +++ /dev/null @@ -1 +0,0 @@ -# Nothing to be done at the board level diff --git a/hw/bsp/max32690/boards/max32690evkit/board.mk b/hw/bsp/max32690/boards/max32690evkit/board.mk deleted file mode 100644 index a813a5327..000000000 --- a/hw/bsp/max32690/boards/max32690evkit/board.mk +++ /dev/null @@ -1 +0,0 @@ -# No specific build requirements for the board. diff --git a/hw/bsp/max32690/family.c b/hw/bsp/max32690/family.c deleted file mode 100644 index 2418168d4..000000000 --- a/hw/bsp/max32690/family.c +++ /dev/null @@ -1,171 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2024 Brent Kowal (Analog Devices, Inc) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - * This file is part of the TinyUSB stack. - */ - -#ifdef __GNUC__ -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wstrict-prototypes" // _mxc_crit_get_state() -#endif - -#include "gpio.h" -#include "mxc_sys.h" -#include "mcr_regs.h" -#include "mxc_device.h" -#include "uart.h" - -#ifdef __GNUC__ -#pragma GCC diagnostic pop -#endif - -#include "board.h" -#include "bsp/board_api.h" - - -//--------------------------------------------------------------------+ -// Forward USB interrupt events to TinyUSB IRQ Handler -//--------------------------------------------------------------------+ -void USB_IRQHandler(void) { - tud_int_handler(0); -} - -//--------------------------------------------------------------------+ -// MACRO TYPEDEF CONSTANT ENUM -//--------------------------------------------------------------------+ -mxc_uart_regs_t *ConsoleUart = MXC_UART_GET_UART(UART_NUM); - -void board_init(void) { -#if CFG_TUSB_OS == OPT_OS_NONE - // 1ms tick timer - SysTick_Config(SystemCoreClock / 1000); -#elif CFG_TUSB_OS == OPT_OS_FREERTOS - // If freeRTOS is used, IRQ priority is limit by max syscall ( smaller is higher ) - NVIC_SetPriority(USB_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY); -#endif - mxc_gpio_cfg_t gpioConfig; - - // LED - gpioConfig.drvstr = MXC_GPIO_DRVSTR_0; - gpioConfig.func = MXC_GPIO_FUNC_OUT; - gpioConfig.mask = LED_PIN; - gpioConfig.pad = MXC_GPIO_PAD_NONE; - gpioConfig.port = LED_PORT; - gpioConfig.vssel = LED_VDDIO; - MXC_GPIO_Config(&gpioConfig); - board_led_write(false); - - // Button - gpioConfig.drvstr = MXC_GPIO_DRVSTR_0; - gpioConfig.func = MXC_GPIO_FUNC_IN; - gpioConfig.mask = BUTTON_PIN; - gpioConfig.pad = BUTTON_PULL; - gpioConfig.port = BUTTON_PORT; - gpioConfig.vssel = MXC_GPIO_VSSEL_VDDIO; - MXC_GPIO_Config(&gpioConfig); - - // UART - MXC_UART_Init(ConsoleUart, CFG_BOARD_UART_BAUDRATE, MXC_UART_IBRO_CLK); - - //USB - MXC_SYS_ClockSourceEnable(MXC_SYS_CLOCK_IPO); - MXC_MCR->ldoctrl |= MXC_F_MCR_LDOCTRL_0P9EN; - MXC_SYS_ClockEnable(MXC_SYS_PERIPH_CLOCK_USB); - MXC_SYS_Reset_Periph(MXC_SYS_RESET0_USB); -} - -//--------------------------------------------------------------------+ -// Board porting API -//--------------------------------------------------------------------+ - -void board_led_write(bool state) { -#if LED_STATE_ON - state = !state; -#endif - if (state) { - MXC_GPIO_OutClr(LED_PORT, LED_PIN); - } else { - MXC_GPIO_OutSet(LED_PORT, LED_PIN); - } -} - -uint32_t board_button_read(void) { - uint32_t state = MXC_GPIO_InGet(BUTTON_PORT, BUTTON_PIN) ? 1 : 0; - return BUTTON_STATE_ACTIVE == state; -} - -size_t board_get_unique_id(uint8_t id[], size_t max_len) { - uint8_t hw_id[MXC_SYS_USN_CHECKSUM_LEN];//USN Buffer - /* All other 2nd parameter is optional checksum buffer */ - MXC_SYS_GetUSN(hw_id, NULL); - - size_t act_len = TU_MIN(max_len, MXC_SYS_USN_LEN); - memcpy(id, hw_id, act_len); - return act_len; -} - -int board_uart_read(uint8_t *buf, int len) { - int uart_val; - int act_len = 0; - - while (act_len < len) { - if ((uart_val = MXC_UART_ReadCharacterRaw(ConsoleUart)) == E_UNDERFLOW) { - break; - } else { - *buf++ = (uint8_t) uart_val; - act_len++; - } - } - return act_len; -} - -int board_uart_write(void const *buf, int len) { - int act_len = 0; - const uint8_t *ch_ptr = (const uint8_t *) buf; - while (act_len < len) { - MXC_UART_WriteCharacter(ConsoleUart, *ch_ptr++); - act_len++; - } - return len; -} - -#if CFG_TUSB_OS == OPT_OS_NONE -volatile uint32_t system_ticks = 0; - -void SysTick_Handler(void) { - system_ticks++; -} - -uint32_t board_millis(void) { - return system_ticks; -} -#endif - -void HardFault_Handler(void) { - __asm("BKPT #0\n"); -} - -// Required by __libc_init_array in startup code if we are compiling using -// -nostdlib/-nostartfiles. -void _init(void) { -} diff --git a/hw/bsp/max32690/family.cmake b/hw/bsp/max32690/family.cmake deleted file mode 100644 index 96dcfedff..000000000 --- a/hw/bsp/max32690/family.cmake +++ /dev/null @@ -1,152 +0,0 @@ -include_guard() - -set(MAX32_PERIPH ${TOP}/hw/mcu/analog/max32/Libraries/PeriphDrivers) -set(MAX32_CMSIS ${TOP}/hw/mcu/analog/max32/Libraries/CMSIS) -set(CMSIS_5 ${TOP}/lib/CMSIS_5) - -# include board specific -include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) - -# Get the linker file from current location (family) -set(LD_FILE_GNU ${CMAKE_CURRENT_LIST_DIR}/max32690.ld) -set(LD_FILE_Clang ${LD_FILE_GNU}) - -# toolchain set up -set(CMAKE_SYSTEM_PROCESSOR cortex-m4 CACHE INTERNAL "System Processor") -set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) -set(JLINK_DEVICE max32690) -set(OPENOCD_OPTION "-f interface/cmsis-dap.cfg -f target/max32690.cfg") - -set(FAMILY_MCUS MAX32690 CACHE INTERNAL "") - -function(update_board TARGET) - target_compile_definitions(${TARGET} PUBLIC - TARGET=MAX32690 - TARGET_REV=0x4131 - MXC_ASSERT_ENABLE - MAX32690 - FLASH_ORIGIN=0x10000000 - FLASH_SIZE=0x340000 - SRAM_ORIGIN=0x20000000 - SRAM_SIZE=0x100000 - IAR_PRAGMAS=0 - CFG_TUSB_MCU=OPT_MCU_MAX32690 - BOARD_TUD_MAX_SPEED=OPT_MODE_HIGH_SPEED - ) -endfunction() - -#------------------------------------ -# BOARD_TARGET -#------------------------------------ -# only need to be built ONCE for all examples -function(add_board_target BOARD_TARGET) - if (TARGET ${BOARD_TARGET}) - return() - endif () - - # Startup & Linker script - set(STARTUP_FILE_GNU ${MAX32_CMSIS}/Device/Maxim/MAX32690/Source/GCC/startup_max32690.S) - set(STARTUP_FILE_Clang ${STARTUP_FILE_GNU}) - - set(PERIPH_SRC ${MAX32_PERIPH}/Source) - add_library(${BOARD_TARGET} STATIC - ${MAX32_CMSIS}/Device/Maxim/MAX32690/Source/heap.c - ${MAX32_CMSIS}/Device/Maxim/MAX32690/Source/system_max32690.c - ${PERIPH_SRC}/SYS/mxc_assert.c - ${PERIPH_SRC}/SYS/mxc_delay.c - ${PERIPH_SRC}/SYS/mxc_lock.c - ${PERIPH_SRC}/SYS/nvic_table.c - ${PERIPH_SRC}/SYS/pins_me18.c - ${PERIPH_SRC}/SYS/sys_me18.c - ${PERIPH_SRC}/CTB/ctb_me18.c - ${PERIPH_SRC}/CTB/ctb_reva.c - ${PERIPH_SRC}/CTB/ctb_common.c - ${PERIPH_SRC}/FLC/flc_common.c - ${PERIPH_SRC}/FLC/flc_me18.c - ${PERIPH_SRC}/FLC/flc_reva.c - ${PERIPH_SRC}/GPIO/gpio_common.c - ${PERIPH_SRC}/GPIO/gpio_me18.c - ${PERIPH_SRC}/GPIO/gpio_reva.c - ${PERIPH_SRC}/ICC/icc_me18.c - ${PERIPH_SRC}/ICC/icc_reva.c - ${PERIPH_SRC}/UART/uart_common.c - ${PERIPH_SRC}/UART/uart_me18.c - ${PERIPH_SRC}/UART/uart_revb.c - ${STARTUP_FILE_${CMAKE_C_COMPILER_ID}} - ) - target_include_directories(${BOARD_TARGET} PUBLIC - ${CMAKE_CURRENT_FUNCTION_LIST_DIR} - ${MAX32_CMSIS}/Include - ${MAX32_CMSIS}/Device/Maxim/MAX32690/Include - ${MAX32_PERIPH}/Include/MAX32690 - ${PERIPH_SRC}/SYS - ${PERIPH_SRC}/GPIO - ${PERIPH_SRC}/CTB - ${PERIPH_SRC}/ICC - ${PERIPH_SRC}/FLC - ${PERIPH_SRC}/UART - ) - - target_compile_options(${BOARD_TARGET} PRIVATE - -Wno-error=strict-prototypes - ) - update_board(${BOARD_TARGET}) - - if (CMAKE_C_COMPILER_ID STREQUAL "GNU") - target_link_options(${BOARD_TARGET} PUBLIC - "LINKER:--script=${LD_FILE_GNU}" - -nostartfiles - --specs=nosys.specs --specs=nano.specs - ) - elseif (CMAKE_C_COMPILER_ID STREQUAL "Clang") - target_link_options(${BOARD_TARGET} PUBLIC - "LINKER:--script=${LD_FILE_Clang}" - ) - endif () -endfunction() - - -#------------------------------------ -# Functions -#------------------------------------ -function(family_configure_example TARGET RTOS) - family_configure_common(${TARGET} ${RTOS}) - - # Board target - add_board_target(board_${BOARD}) - - #---------- Port Specific ---------- - # These files are built for each example since it depends on example's tusb_config.h - target_sources(${TARGET} PUBLIC - # BSP - ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/family.c - ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/../board.c - ) - target_include_directories(${TARGET} PUBLIC - # family, hw, board - ${CMAKE_CURRENT_FUNCTION_LIST_DIR} - ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/../../ - ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/boards/${BOARD} - ) - - # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_MAX32690 ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC - ${TOP}/src/portable/mentor/musb/dcd_musb.c - ) - target_compile_options(${TARGET} PRIVATE - -Wno-error=strict-prototypes - ) - - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) - target_compile_options(${TARGET}-tinyusb PRIVATE - -Wno-error=strict-prototypes - ) - - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) - - # Flashing - family_flash_jlink(${TARGET}) - family_flash_openocd_adi(${TARGET}) -endfunction() diff --git a/hw/bsp/max32690/family.mk b/hw/bsp/max32690/family.mk deleted file mode 100644 index d4df8ef2f..000000000 --- a/hw/bsp/max32690/family.mk +++ /dev/null @@ -1,101 +0,0 @@ -DEPS_SUBMODULES += lib/CMSIS_5 hw/mcu/analog/max32 - -# Important locations in the hw support for MCU -MAX32_CMSIS = hw/mcu/analog/max32/Libraries/CMSIS -MAX32_PERIPH = hw/mcu/analog/max32/Libraries/PeriphDrivers - -# Add any board specific make rules -include $(TOP)/$(BOARD_PATH)/board.mk - -CPU_CORE ?= cortex-m4 -PORT ?= 0 - -# GCC -SRC_S_GCC += $(MAX32_CMSIS)/Device/Maxim/MAX32690/Source/GCC/startup_max32690.S -LD_FILE = $(FAMILY_PATH)/max32690.ld - -# -------------- -# Compiler Flags -# -------------- -# Flags for the MAX32690 SDK -CFLAGS += -DTARGET=MAX32690 \ - -DTARGET_REV=0x4131 \ - -DMXC_ASSERT_ENABLE \ - -DMAX32690 \ - -DFLASH_ORIGIN=0x10000000 \ - -DFLASH_SIZE=0x340000 \ - -DSRAM_ORIGIN=0x20000000 \ - -DSRAM_SIZE=0x100000 \ - -DIAR_PRAGMAS=0 - -# Flags for TUSB features -CFLAGS += \ - -DCFG_TUSB_MCU=OPT_MCU_MAX32690 \ - -DBOARD_TUD_MAX_SPEED=OPT_MODE_HIGH_SPEED - -# mcu driver cause following warnings -CFLAGS += -Wno-error=unused-parameter \ - -Wno-error=strict-prototypes \ - -Wno-error=old-style-declaration \ - -Wno-error=sign-compare \ - -Wno-error=cast-qual \ - -Wno-lto-type-mismatch - -LDFLAGS_GCC += -nostartfiles --specs=nosys.specs --specs=nano.specs - -# For flash-jlink target -JLINK_DEVICE = max32690 - -# flash target using Jlink by default -flash: flash-jlink - -# Optional flash option when running within an installed MSDK to use OpenOCD -# Mainline OpenOCD does not yet have the MAX32's flash algorithm integrated. -# If the MSDK is installed, flash-msdk can be run to utilize the the modified -# openocd with the algorithms -MAXIM_PATH := $(subst \,/,$(MAXIM_PATH)) -flash-msdk: $(BUILD)/$(PROJECT).elf - $(MAXIM_PATH)/Tools/OpenOCD/openocd -s $(MAXIM_PATH)/Tools/OpenOCD/scripts \ - -f interface/cmsis-dap.cfg -f target/max32690.cfg \ - -c "program $(BUILD)/$(PROJECT).elf verify; init; reset; exit" - -# ----------------- -# Sources & Include -# ----------------- -PERIPH_SRC = $(TOP)/$(MAX32_PERIPH)/Source -SRC_C += \ - src/portable/mentor/musb/dcd_musb.c \ - $(MAX32_CMSIS)/Device/Maxim/MAX32690/Source/heap.c \ - $(MAX32_CMSIS)/Device/Maxim/MAX32690/Source/system_max32690.c \ - $(PERIPH_SRC)/SYS/mxc_assert.c \ - $(PERIPH_SRC)/SYS/mxc_delay.c \ - $(PERIPH_SRC)/SYS/mxc_lock.c \ - $(PERIPH_SRC)/SYS/nvic_table.c \ - $(PERIPH_SRC)/SYS/pins_me18.c \ - $(PERIPH_SRC)/SYS/sys_me18.c \ - $(PERIPH_SRC)/CTB/ctb_me18.c \ - $(PERIPH_SRC)/CTB/ctb_reva.c \ - $(PERIPH_SRC)/CTB/ctb_common.c \ - $(PERIPH_SRC)/FLC/flc_common.c \ - $(PERIPH_SRC)/FLC/flc_me18.c \ - $(PERIPH_SRC)/FLC/flc_reva.c \ - $(PERIPH_SRC)/GPIO/gpio_common.c \ - $(PERIPH_SRC)/GPIO/gpio_me18.c \ - $(PERIPH_SRC)/GPIO/gpio_reva.c \ - $(PERIPH_SRC)/ICC/icc_me18.c \ - $(PERIPH_SRC)/ICC/icc_reva.c \ - $(PERIPH_SRC)/UART/uart_common.c \ - $(PERIPH_SRC)/UART/uart_me18.c \ - $(PERIPH_SRC)/UART/uart_revb.c \ - -INC += \ - $(TOP)/$(BOARD_PATH) \ - $(TOP)/$(MAX32_CMSIS)/Include \ - $(TOP)/$(MAX32_CMSIS)/Device/Maxim/MAX32690/Include \ - $(TOP)/$(MAX32_PERIPH)/Include/MAX32690 \ - $(PERIPH_SRC)/SYS \ - $(PERIPH_SRC)/GPIO \ - $(PERIPH_SRC)/CTB \ - $(PERIPH_SRC)/ICC \ - $(PERIPH_SRC)/FLC \ - $(PERIPH_SRC)/UART diff --git a/hw/bsp/max78002/FreeRTOSConfig/FreeRTOSConfig.h b/hw/bsp/max78002/FreeRTOSConfig/FreeRTOSConfig.h deleted file mode 100644 index e5a76af85..000000000 --- a/hw/bsp/max78002/FreeRTOSConfig/FreeRTOSConfig.h +++ /dev/null @@ -1,149 +0,0 @@ -/* - * FreeRTOS Kernel V10.0.0 - * 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. If you wish to use our Amazon - * FreeRTOS name, please do so in a fair use way that does not cause confusion. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS - * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR - * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER - * IN AN ACTION 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. - *----------------------------------------------------------*/ - -// skip if included from IAR assembler -#ifndef __IASMARM__ - #include "mxc_device.h" -#endif - -/* Cortex M23/M33 port configuration. */ -#define configENABLE_MPU 0 -#define configENABLE_FPU 1 -#define configENABLE_TRUSTZONE 0 -#define configMINIMAL_SECURE_STACK_SIZE (1024) - -#define configUSE_PREEMPTION 1 -#define configUSE_PORT_OPTIMISED_TASK_SELECTION 0 -#define configCPU_CLOCK_HZ SystemCoreClock -#define configTICK_RATE_HZ ( 1000 ) -#define configMAX_PRIORITIES ( 5 ) -#define configMINIMAL_STACK_SIZE ( 128 ) -#define configTOTAL_HEAP_SIZE ( configSUPPORT_DYNAMIC_ALLOCATION*4*1024 ) -#define configMAX_TASK_NAME_LEN 16 -#define configUSE_16_BIT_TICKS 0 -#define configIDLE_SHOULD_YIELD 1 -#define configUSE_MUTEXES 1 -#define configUSE_RECURSIVE_MUTEXES 1 -#define configUSE_COUNTING_SEMAPHORES 1 -#define configQUEUE_REGISTRY_SIZE 4 -#define configUSE_QUEUE_SETS 0 -#define configUSE_TIME_SLICING 0 -#define configUSE_NEWLIB_REENTRANT 0 -#define configENABLE_BACKWARD_COMPATIBILITY 1 -#define configSTACK_ALLOCATION_FROM_SEPARATE_HEAP 0 - -#define configSUPPORT_STATIC_ALLOCATION 1 -#define configSUPPORT_DYNAMIC_ALLOCATION 0 - -/* Hook function related definitions. */ -#define configUSE_IDLE_HOOK 0 -#define configUSE_TICK_HOOK 0 -#define configUSE_MALLOC_FAILED_HOOK 0 // cause nested extern warning -#define configCHECK_FOR_STACK_OVERFLOW 2 -#define configCHECK_HANDLER_INSTALLATION 0 - -/* Run time and task stats gathering related definitions. */ -#define configGENERATE_RUN_TIME_STATS 0 -#define configRECORD_STACK_HIGH_ADDRESS 1 -#define configUSE_TRACE_FACILITY 1 // legacy trace -#define configUSE_STATS_FORMATTING_FUNCTIONS 0 - -/* Co-routine definitions. */ -#define configUSE_CO_ROUTINES 0 -#define configMAX_CO_ROUTINE_PRIORITIES 2 - -/* Software timer related definitions. */ -#define configUSE_TIMERS 1 -#define configTIMER_TASK_PRIORITY (configMAX_PRIORITIES-2) -#define configTIMER_QUEUE_LENGTH 32 -#define configTIMER_TASK_STACK_DEPTH configMINIMAL_STACK_SIZE - -/* Optional functions - most linkers will remove unused functions anyway. */ -#define INCLUDE_vTaskPrioritySet 0 -#define INCLUDE_uxTaskPriorityGet 0 -#define INCLUDE_vTaskDelete 0 -#define INCLUDE_vTaskSuspend 1 // required for queue, semaphore, mutex to be blocked indefinitely with portMAX_DELAY -#define INCLUDE_xResumeFromISR 0 -#define INCLUDE_vTaskDelayUntil 1 -#define INCLUDE_vTaskDelay 1 -#define INCLUDE_xTaskGetSchedulerState 0 -#define INCLUDE_xTaskGetCurrentTaskHandle 1 -#define INCLUDE_uxTaskGetStackHighWaterMark 0 -#define INCLUDE_xTaskGetIdleTaskHandle 0 -#define INCLUDE_xTimerGetTimerDaemonTaskHandle 0 -#define INCLUDE_pcTaskGetTaskName 0 -#define INCLUDE_eTaskGetState 0 -#define INCLUDE_xEventGroupSetBitFromISR 0 -#define INCLUDE_xTimerPendFunctionCall 0 - -/* FreeRTOS hooks to NVIC vectors */ -#define xPortPendSVHandler PendSV_Handler -#define xPortSysTickHandler SysTick_Handler -#define vPortSVCHandler SVC_Handler - -//--------------------------------------------------------------------+ -// Interrupt nesting behavior configuration. -//--------------------------------------------------------------------+ - -// For Cortex-M specific: __NVIC_PRIO_BITS is defined in mcu header -#define configPRIO_BITS __NVIC_PRIO_BITS - -/* The lowest interrupt priority that can be used in a call to a "set priority" function. */ -#define configLIBRARY_LOWEST_INTERRUPT_PRIORITY ((1<-jlink` target for CMake. - -The Evaluation Kit is shipped with a CMSIS-DAP compatible debug probe. However, -at the time of writing, the necessary flashing algorithms for OpenOCD have not -yet been incorporated into the OpenOCD master branch. To utilize the provided -debug probes, please install the bundled MSDK package which includes the -appropriate OpenOCD modifications. To leverage this OpenOCD instance, run the -`flash-msdk` Makefile rule, or `-msdk` CMake target. diff --git a/hw/bsp/max78002/boards/max78002evkit/board.cmake b/hw/bsp/max78002/boards/max78002evkit/board.cmake deleted file mode 100644 index 9dc6962eb..000000000 --- a/hw/bsp/max78002/boards/max78002evkit/board.cmake +++ /dev/null @@ -1 +0,0 @@ -# Nothing to be done at the board level diff --git a/hw/bsp/max78002/boards/max78002evkit/board.mk b/hw/bsp/max78002/boards/max78002evkit/board.mk deleted file mode 100644 index a813a5327..000000000 --- a/hw/bsp/max78002/boards/max78002evkit/board.mk +++ /dev/null @@ -1 +0,0 @@ -# No specific build requirements for the board. diff --git a/hw/bsp/max78002/family.c b/hw/bsp/max78002/family.c deleted file mode 100644 index 8d51f141c..000000000 --- a/hw/bsp/max78002/family.c +++ /dev/null @@ -1,169 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2024 Brent Kowal (Analog Devices, Inc) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - * This file is part of the TinyUSB stack. - */ - -#ifdef __GNUC__ -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wstrict-prototypes" // _mxc_crit_get_state() -#endif - -#include "gpio.h" -#include "mxc_sys.h" -#include "mcr_regs.h" -#include "mxc_device.h" -#include "uart.h" - -#ifdef __GNUC__ -#pragma GCC diagnostic pop -#endif - -#include "board.h" -#include "bsp/board_api.h" - -//--------------------------------------------------------------------+ -// Forward USB interrupt events to TinyUSB IRQ Handler -//--------------------------------------------------------------------+ -void USB_IRQHandler(void) { - tud_int_handler(0); -} - -//--------------------------------------------------------------------+ -// MACRO TYPEDEF CONSTANT ENUM -//--------------------------------------------------------------------+ -mxc_uart_regs_t *ConsoleUart = MXC_UART_GET_UART(UART_NUM); - -void board_init(void) { -#if CFG_TUSB_OS == OPT_OS_NONE - // 1ms tick timer - SysTick_Config(SystemCoreClock / 1000); -#elif CFG_TUSB_OS == OPT_OS_FREERTOS - // If freeRTOS is used, IRQ priority is limit by max syscall ( smaller is higher ) - NVIC_SetPriority(USB_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY); -#endif - mxc_gpio_cfg_t gpioConfig; - - // LED - gpioConfig.drvstr = MXC_GPIO_DRVSTR_0; - gpioConfig.func = MXC_GPIO_FUNC_OUT; - gpioConfig.mask = LED_PIN; - gpioConfig.pad = MXC_GPIO_PAD_NONE; - gpioConfig.port = LED_PORT; - gpioConfig.vssel = LED_VDDIO; - MXC_GPIO_Config(&gpioConfig); - board_led_write(false); - - // Button - gpioConfig.drvstr = MXC_GPIO_DRVSTR_0; - gpioConfig.func = MXC_GPIO_FUNC_IN; - gpioConfig.mask = BUTTON_PIN; - gpioConfig.pad = BUTTON_PULL; - gpioConfig.port = BUTTON_PORT; - gpioConfig.vssel = MXC_GPIO_VSSEL_VDDIO; - MXC_GPIO_Config(&gpioConfig); - - // UART - MXC_UART_Init(ConsoleUart, CFG_BOARD_UART_BAUDRATE, MXC_UART_IBRO_CLK); - UART_PORT->vssel |= UART_VDDIO_BITS; //Set necessary bits to 3.3V - - //USB - MXC_MCR->ldoctrl |= MXC_F_MCR_LDOCTRL_0P9EN; - MXC_SYS_ClockEnable(MXC_SYS_PERIPH_CLOCK_USB); -} - -//--------------------------------------------------------------------+ -// Board porting API -//--------------------------------------------------------------------+ - -void board_led_write(bool state) { -#if LED_STATE_ON - state = !state; -#endif - if (state) { - MXC_GPIO_OutClr(LED_PORT, LED_PIN); - } else { - MXC_GPIO_OutSet(LED_PORT, LED_PIN); - } -} - -uint32_t board_button_read(void) { - uint32_t state = MXC_GPIO_InGet(BUTTON_PORT, BUTTON_PIN) ? 1 : 0; - return BUTTON_STATE_ACTIVE == state; -} - -size_t board_get_unique_id(uint8_t id[], size_t max_len) { - uint8_t hw_id[MXC_SYS_USN_CHECKSUM_LEN];//USN Buffer - /* All other 2nd parameter is optional checksum buffer */ - MXC_SYS_GetUSN(hw_id, NULL); - - size_t act_len = TU_MIN(max_len, MXC_SYS_USN_LEN); - memcpy(id, hw_id, act_len); - return act_len; -} - -int board_uart_read(uint8_t *buf, int len) { - int uart_val; - int act_len = 0; - - while (act_len < len) { - if ((uart_val = MXC_UART_ReadCharacterRaw(ConsoleUart)) == E_UNDERFLOW) { - break; - } else { - *buf++ = (uint8_t) uart_val; - act_len++; - } - } - return act_len; -} - -int board_uart_write(void const *buf, int len) { - int act_len = 0; - const uint8_t *ch_ptr = (const uint8_t *) buf; - while (act_len < len) { - MXC_UART_WriteCharacter(ConsoleUart, *ch_ptr++); - act_len++; - } - return len; -} - -#if CFG_TUSB_OS == OPT_OS_NONE -volatile uint32_t system_ticks = 0; - -void SysTick_Handler(void) { - system_ticks++; -} - -uint32_t board_millis(void) { - return system_ticks; -} -#endif - -void HardFault_Handler(void) { - __asm("BKPT #0\n"); -} - -// Required by __libc_init_array in startup code if we are compiling using -// -nostdlib/-nostartfiles. -void _init(void) { -} diff --git a/hw/bsp/max78002/family.cmake b/hw/bsp/max78002/family.cmake deleted file mode 100644 index 446930bd8..000000000 --- a/hw/bsp/max78002/family.cmake +++ /dev/null @@ -1,166 +0,0 @@ -include_guard() - -set(MAX32_PERIPH ${TOP}/hw/mcu/analog/max32/Libraries/PeriphDrivers) -set(MAX32_CMSIS ${TOP}/hw/mcu/analog/max32/Libraries/CMSIS) -set(CMSIS_5 ${TOP}/lib/CMSIS_5) - -# include board specific -include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) - -# Get the linker file from current location (family) -set(LD_FILE_GNU ${CMAKE_CURRENT_LIST_DIR}/max78002.ld) -set(LD_FILE_Clang ${LD_FILE_GNU}) - -# toolchain set up -set(CMAKE_SYSTEM_PROCESSOR cortex-m4 CACHE INTERNAL "System Processor") -set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) -set(JLINK_DEVICE max78000) - -set(FAMILY_MCUS MAX78002 CACHE INTERNAL "") - -function(update_board TARGET) - target_compile_definitions(${TARGET} PUBLIC - TARGET=MAX78002 - TARGET_REV=0x4131 - MXC_ASSERT_ENABLE - MAX78002 - IAR_PRAGMAS=0 - CFG_TUSB_MCU=OPT_MCU_MAX78002 - BOARD_TUD_MAX_SPEED=OPT_MODE_HIGH_SPEED - ) -endfunction() - -#------------------------------------ -# BOARD_TARGET -#------------------------------------ -# only need to be built ONCE for all examples -function(add_board_target BOARD_TARGET) - if (TARGET ${BOARD_TARGET}) - return() - endif () - - # Startup & Linker script - set(STARTUP_FILE_GNU ${MAX32_CMSIS}/Device/Maxim/MAX78002/Source/GCC/startup_max78002.S) - set(STARTUP_FILE_Clang ${STARTUP_FILE_GNU}) - - set(PERIPH_SRC ${MAX32_PERIPH}/Source) - add_library(${BOARD_TARGET} STATIC - ${MAX32_CMSIS}/Device/Maxim/MAX78002/Source/heap.c - ${MAX32_CMSIS}/Device/Maxim/MAX78002/Source/system_max78002.c - ${PERIPH_SRC}/SYS/mxc_assert.c - ${PERIPH_SRC}/SYS/mxc_delay.c - ${PERIPH_SRC}/SYS/mxc_lock.c - ${PERIPH_SRC}/SYS/nvic_table.c - ${PERIPH_SRC}/SYS/pins_ai87.c - ${PERIPH_SRC}/SYS/sys_ai87.c - ${PERIPH_SRC}/AES/aes_ai87.c - ${PERIPH_SRC}/AES/aes_revb.c - ${PERIPH_SRC}/FLC/flc_common.c - ${PERIPH_SRC}/FLC/flc_ai87.c - ${PERIPH_SRC}/FLC/flc_reva.c - ${PERIPH_SRC}/GPIO/gpio_common.c - ${PERIPH_SRC}/GPIO/gpio_ai87.c - ${PERIPH_SRC}/GPIO/gpio_reva.c - ${PERIPH_SRC}/ICC/icc_ai87.c - ${PERIPH_SRC}/ICC/icc_reva.c - ${PERIPH_SRC}/TRNG/trng_ai87.c - ${PERIPH_SRC}/TRNG/trng_revb.c - ${PERIPH_SRC}/UART/uart_common.c - ${PERIPH_SRC}/UART/uart_ai87.c - ${PERIPH_SRC}/UART/uart_revb.c - ${STARTUP_FILE_${CMAKE_C_COMPILER_ID}} - ) - target_include_directories(${BOARD_TARGET} PUBLIC - ${CMAKE_CURRENT_FUNCTION_LIST_DIR} - ${MAX32_CMSIS}/Include - ${MAX32_CMSIS}/Device/Maxim/MAX78002/Include - ${MAX32_PERIPH}/Include/MAX78002 - ${PERIPH_SRC}/SYS - ${PERIPH_SRC}/GPIO - ${PERIPH_SRC}/AES - ${PERIPH_SRC}/TRNG - ${PERIPH_SRC}/ICC - ${PERIPH_SRC}/FLC - ${PERIPH_SRC}/UART - ) - - target_compile_options(${BOARD_TARGET} PRIVATE - -Wno-error=strict-prototypes - -Wno-error=redundant-decls - ) - update_board(${BOARD_TARGET}) - - if (CMAKE_C_COMPILER_ID STREQUAL "GNU") - target_link_options(${BOARD_TARGET} PUBLIC - "LINKER:--script=${LD_FILE_GNU}" - -nostartfiles - --specs=nosys.specs --specs=nano.specs - ) - elseif (CMAKE_C_COMPILER_ID STREQUAL "Clang") - target_link_options(${BOARD_TARGET} PUBLIC - "LINKER:--script=${LD_FILE_Clang}" - ) - endif () -endfunction() - - -#------------------------------------ -# Functions -#------------------------------------ -function(family_configure_example TARGET RTOS) - family_configure_common(${TARGET} ${RTOS}) - - # Board target - add_board_target(board_${BOARD}) - - #---------- Port Specific ---------- - # These files are built for each example since it depends on example's tusb_config.h - target_sources(${TARGET} PUBLIC - # BSP - ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/family.c - ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/../board.c - ) - target_include_directories(${TARGET} PUBLIC - # family, hw, board - ${CMAKE_CURRENT_FUNCTION_LIST_DIR} - ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/../../ - ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/boards/${BOARD} - ) - - target_compile_options(${TARGET} PRIVATE - -Wno-error=strict-prototypes - -Wno-error=redundant-decls - ) - - - # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_MAX78002 ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC - ${TOP}/src/portable/mentor/musb/dcd_musb.c - ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) - target_compile_options(${TARGET}-tinyusb PRIVATE - -Wno-error=strict-prototypes - -Wno-error=redundant-decls - ) - - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) - - # Flashing - family_flash_jlink(${TARGET}) - family_flash_msdk(${TARGET}) -endfunction() - -# Add flash msdk target -function(family_flash_msdk TARGET) - set(MAXIM_PATH "$ENV{MAXIM_PATH}") - - add_custom_target(${TARGET}-msdk - DEPENDS ${TARGET} - COMMAND ${MAXIM_PATH}/Tools/OpenOCD/openocd -s ${MAXIM_PATH}/Tools/OpenOCD/scripts - -f interface/cmsis-dap.cfg -f target/max78002.cfg - -c "program $ verify; init; reset; exit" - VERBATIM - ) -endfunction() diff --git a/hw/bsp/max78002/family.mk b/hw/bsp/max78002/family.mk deleted file mode 100644 index 997816261..000000000 --- a/hw/bsp/max78002/family.mk +++ /dev/null @@ -1,99 +0,0 @@ -DEPS_SUBMODULES += lib/CMSIS_5 hw/mcu/analog/max32 - -# Important locations in the hw support for MCU -MAX32_CMSIS = hw/mcu/analog/max32/Libraries/CMSIS -MAX32_PERIPH = hw/mcu/analog/max32/Libraries/PeriphDrivers - -# Add any board specific make rules -include $(TOP)/$(BOARD_PATH)/board.mk - -CPU_CORE ?= cortex-m4 -PORT ?= 0 - -# GCC -SRC_S_GCC += $(MAX32_CMSIS)/Device/Maxim/MAX78002/Source/GCC/startup_max78002.S -LD_FILE = $(FAMILY_PATH)/max78002.ld - -# -------------- -# Compiler Flags -# -------------- -# Flags for the MAX78002 SDK -CFLAGS += -DTARGET=MAX78002 \ - -DTARGET_REV=0x4131 \ - -DMXC_ASSERT_ENABLE \ - -DMAX78002 \ - -DIAR_PRAGMAS=0 - -# Flags for TUSB features -CFLAGS += \ - -DCFG_TUSB_MCU=OPT_MCU_MAX78002 \ - -DBOARD_TUD_MAX_SPEED=OPT_MODE_HIGH_SPEED - -# mcu driver cause following warnings -CFLAGS += -Wno-error=redundant-decls \ - -Wno-error=strict-prototypes \ - -Wno-error=unused-parameter \ - -Wno-error=enum-conversion \ - -Wno-error=sign-compare \ - -Wno-error=cast-qual - -LDFLAGS_GCC += -nostartfiles --specs=nosys.specs --specs=nano.specs - -# For flash-jlink target -JLINK_DEVICE = max78000 - -# flash target using Jlink by default -flash: flash-jlink - -# Optional flash option when running within an installed MSDK to use OpenOCD -# Mainline OpenOCD does not yet have the MAX32's flash algorithm integrated. -# If the MSDK is installed, flash-msdk can be run to utilize the the modified -# openocd with the algorithms -MAXIM_PATH := $(subst \,/,$(MAXIM_PATH)) -flash-msdk: $(BUILD)/$(PROJECT).elf - $(MAXIM_PATH)/Tools/OpenOCD/openocd -s $(MAXIM_PATH)/Tools/OpenOCD/scripts \ - -f interface/cmsis-dap.cfg -f target/max78002.cfg \ - -c "program $(BUILD)/$(PROJECT).elf verify; init; reset; exit" - -# ----------------- -# Sources & Include -# ----------------- -PERIPH_SRC = $(TOP)/$(MAX32_PERIPH)/Source -SRC_C += \ - src/portable/mentor/musb/dcd_musb.c \ - $(MAX32_CMSIS)/Device/Maxim/MAX78002/Source/heap.c \ - $(MAX32_CMSIS)/Device/Maxim/MAX78002/Source/system_max78002.c \ - $(PERIPH_SRC)/SYS/mxc_assert.c \ - $(PERIPH_SRC)/SYS/mxc_delay.c \ - $(PERIPH_SRC)/SYS/mxc_lock.c \ - $(PERIPH_SRC)/SYS/nvic_table.c \ - $(PERIPH_SRC)/SYS/pins_ai87.c \ - $(PERIPH_SRC)/SYS/sys_ai87.c \ - $(PERIPH_SRC)/AES/aes_ai87.c \ - $(PERIPH_SRC)/AES/aes_revb.c \ - $(PERIPH_SRC)/FLC/flc_common.c \ - $(PERIPH_SRC)/FLC/flc_ai87.c \ - $(PERIPH_SRC)/FLC/flc_reva.c \ - $(PERIPH_SRC)/GPIO/gpio_common.c \ - $(PERIPH_SRC)/GPIO/gpio_ai87.c \ - $(PERIPH_SRC)/GPIO/gpio_reva.c \ - $(PERIPH_SRC)/ICC/icc_ai87.c \ - $(PERIPH_SRC)/ICC/icc_reva.c \ - $(PERIPH_SRC)/TRNG/trng_ai87.c \ - $(PERIPH_SRC)/TRNG/trng_revb.c \ - $(PERIPH_SRC)/UART/uart_common.c \ - $(PERIPH_SRC)/UART/uart_ai87.c \ - $(PERIPH_SRC)/UART/uart_revb.c \ - -INC += \ - $(TOP)/$(BOARD_PATH) \ - $(TOP)/$(MAX32_CMSIS)/Include \ - $(TOP)/$(MAX32_CMSIS)/Device/Maxim/MAX78002/Include \ - $(TOP)/$(MAX32_PERIPH)/Include/MAX78002 \ - $(PERIPH_SRC)/SYS \ - $(PERIPH_SRC)/GPIO \ - $(PERIPH_SRC)/AES \ - $(PERIPH_SRC)/ICC \ - $(PERIPH_SRC)/FLC \ - $(PERIPH_SRC)/TRNG \ - $(PERIPH_SRC)/UART diff --git a/hw/bsp/max32650/FreeRTOSConfig/FreeRTOSConfig.h b/hw/bsp/maxim/FreeRTOSConfig/FreeRTOSConfig.h similarity index 100% rename from hw/bsp/max32650/FreeRTOSConfig/FreeRTOSConfig.h rename to hw/bsp/maxim/FreeRTOSConfig/FreeRTOSConfig.h diff --git a/hw/bsp/maxim/README.md b/hw/bsp/maxim/README.md new file mode 100644 index 000000000..e2983e899 --- /dev/null +++ b/hw/bsp/maxim/README.md @@ -0,0 +1,43 @@ +# Analog Devices MAXIM + +This BSP is for working with the Analog microcontrollers + - [MAX32650](https://www.analog.com/en/products/max32650.html), + - [MAX32651](https://www.analog.com/en/products/max32651.html) + - [MAX32652](https://www.analog.com/en/products/max32652.html) + - [MAX32665](https://www.analog.com/en/products/max32665.html) + - [MAX32666](https://www.analog.com/en/products/max32666.html) + - [MAX32690](https://www.analog.com/en/products/max32690.html) + - [MAX78002](https://www.analog.com/en/products/max78002.html) AI microcontroller. + +The following boards are supported: + * [MAX32650EVKIT](https://www.analog.com/en/resources/evaluation-hardware-and-software/evaluation-boards-kits/max32650-evkit.html) + * [MAX32650FTHR](https://www.analog.com/en/resources/evaluation-hardware-and-software/evaluation-boards-kits/max32650fthr.html) + * [MAX32651EVKIT](https://www.analog.com/en/resources/evaluation-hardware-and-software/evaluation-boards-kits/max32651-evkit.html) (Secure Bootloader) + * [MAX32666EVKIT](https://www.analog.com/en/resources/evaluation-hardware-and-software/evaluation-boards-kits/max32666evkit.html) + * [MAX32666FTHR](https://www.analog.com/en/resources/evaluation-hardware-and-software/evaluation-boards-kits/max32666fthr.html) + * [MAX32690EVKIT](https://www.analog.com/en/resources/evaluation-hardware-and-software/evaluation-boards-kits/max32690evkit.html) + * [AD-APARD32690-SL](https://www.analog.com/en/resources/evaluation-hardware-and-software/evaluation-boards-kits/ad-apard32690-sl.html) + * [MAX78002EVKIT](https://www.analog.com/en/resources/evaluation-hardware-and-software/evaluation-boards-kits/max78002evkit.html) + +This part family leverages the Maxim Microcontrollers SDK (MSDK) for the device +interfaces and hardware abstraction layers. This source code package is fetched +as part of the get-deps script. + +The microcontroller utilizes the standard GNU ARM toolchain. If this toolchain +is not already available on your build machine, it can be installed by using the +bundled MSDK installation. Details on downloading and installing can be found +in the [User's Guide](https://analogdevicesinc.github.io/msdk//USERGUIDE/). + +## Flashing + +The default flashing behavior in this BSP is to utilize JLink. This can be done +by running the `flash` or `flash-jlink` rule for Makefiles, or the +`-jlink` target for CMake. + +Most the Evaluation Kit and boards are shipped with a CMSIS-DAP +compatible debug probe. However, at the time of writing, the necessary flashing +algorithms for OpenOCD have not yet been incorporated into the OpenOCD master +branch. To utilize the provided debug probes, please install the bundled MSDK +package which includes the appropriate OpenOCD modifications. To leverage this +OpenOCD instance, run the `flash-msdk` Makefile rule, or `-openocd` CMake +target. diff --git a/hw/bsp/maxim/boards/apard32690/board.cmake b/hw/bsp/maxim/boards/apard32690/board.cmake new file mode 100644 index 000000000..a03d05f8d --- /dev/null +++ b/hw/bsp/maxim/boards/apard32690/board.cmake @@ -0,0 +1,4 @@ +set(MAX_DEVICE max32690) + +function(update_board TARGET) +endfunction() diff --git a/hw/bsp/max32690/boards/apard32690/board.h b/hw/bsp/maxim/boards/apard32690/board.h similarity index 90% rename from hw/bsp/max32690/boards/apard32690/board.h rename to hw/bsp/maxim/boards/apard32690/board.h index f94097ca9..19f74bf56 100644 --- a/hw/bsp/max32690/boards/apard32690/board.h +++ b/hw/bsp/maxim/boards/apard32690/board.h @@ -24,11 +24,15 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: APARD32690-SL + url: https://www.analog.com/en/resources/evaluation-hardware-and-software/evaluation-boards-kits/ad-apard32690-sl.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ -#include "gpio.h" -#include "mxc_sys.h" +#include "max32690.h" #ifdef __cplusplus extern "C" { diff --git a/hw/bsp/maxim/boards/apard32690/board.mk b/hw/bsp/maxim/boards/apard32690/board.mk new file mode 100644 index 000000000..d8a0c9cae --- /dev/null +++ b/hw/bsp/maxim/boards/apard32690/board.mk @@ -0,0 +1 @@ +MAX_DEVICE = max32690 diff --git a/hw/bsp/maxim/boards/max32650evkit/board.cmake b/hw/bsp/maxim/boards/max32650evkit/board.cmake new file mode 100644 index 000000000..59721e756 --- /dev/null +++ b/hw/bsp/maxim/boards/max32650evkit/board.cmake @@ -0,0 +1,8 @@ +set(MAX_DEVICE max32650) + +function(update_board TARGET) +endfunction() + +function(prepare_image TARGET_IN) + #No signing required +endfunction() diff --git a/hw/bsp/max32650/boards/max32651evkit/board.h b/hw/bsp/maxim/boards/max32650evkit/board.h similarity index 90% rename from hw/bsp/max32650/boards/max32651evkit/board.h rename to hw/bsp/maxim/boards/max32650evkit/board.h index 196abdaca..0dfc074fa 100644 --- a/hw/bsp/max32650/boards/max32651evkit/board.h +++ b/hw/bsp/maxim/boards/max32650evkit/board.h @@ -24,11 +24,15 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: MAX32650 EVKIT + url: https://www.analog.com/en/resources/evaluation-hardware-and-software/evaluation-boards-kits/max32650-evkit.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ -#include "gpio.h" -#include "mxc_sys.h" +#include "max32650.h" #ifdef __cplusplus extern "C" { diff --git a/hw/bsp/maxim/boards/max32650evkit/board.mk b/hw/bsp/maxim/boards/max32650evkit/board.mk new file mode 100644 index 000000000..3a4108005 --- /dev/null +++ b/hw/bsp/maxim/boards/max32650evkit/board.mk @@ -0,0 +1 @@ +MAX_DEVICE = max32650 diff --git a/hw/bsp/maxim/boards/max32650fthr/board.cmake b/hw/bsp/maxim/boards/max32650fthr/board.cmake new file mode 100644 index 000000000..59721e756 --- /dev/null +++ b/hw/bsp/maxim/boards/max32650fthr/board.cmake @@ -0,0 +1,8 @@ +set(MAX_DEVICE max32650) + +function(update_board TARGET) +endfunction() + +function(prepare_image TARGET_IN) + #No signing required +endfunction() diff --git a/hw/bsp/max32650/boards/max32650fthr/board.h b/hw/bsp/maxim/boards/max32650fthr/board.h similarity index 90% rename from hw/bsp/max32650/boards/max32650fthr/board.h rename to hw/bsp/maxim/boards/max32650fthr/board.h index d80a8fcae..af0fa1c39 100644 --- a/hw/bsp/max32650/boards/max32650fthr/board.h +++ b/hw/bsp/maxim/boards/max32650fthr/board.h @@ -24,11 +24,15 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: MAX32650 Feather + url: https://www.analog.com/en/resources/evaluation-hardware-and-software/evaluation-boards-kits/max32650fthr.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ -#include "gpio.h" -#include "mxc_sys.h" +#include "max32650.h" #ifdef __cplusplus extern "C" { diff --git a/hw/bsp/maxim/boards/max32650fthr/board.mk b/hw/bsp/maxim/boards/max32650fthr/board.mk new file mode 100644 index 000000000..3a4108005 --- /dev/null +++ b/hw/bsp/maxim/boards/max32650fthr/board.mk @@ -0,0 +1 @@ +MAX_DEVICE = max32650 diff --git a/hw/bsp/max32650/boards/max32651evkit/board.cmake b/hw/bsp/maxim/boards/max32651evkit/board.cmake similarity index 81% rename from hw/bsp/max32650/boards/max32651evkit/board.cmake rename to hw/bsp/maxim/boards/max32651evkit/board.cmake index bd8077a42..773989126 100644 --- a/hw/bsp/max32650/boards/max32651evkit/board.cmake +++ b/hw/bsp/maxim/boards/max32651evkit/board.cmake @@ -1,22 +1,23 @@ -# Use the secure linker file -set(LD_FILE_GNU ${CMAKE_CURRENT_LIST_DIR}/max32651.ld) +set(MAX_DEVICE max32650) -function(update_board_extras TARGET) +# Use the secure linker file +set(LD_FILE_GNU ${CMAKE_CURRENT_LIST_DIR}/../../linker/max32651.ld) + +function(update_board TARGET) # for the signed target, need to add the __SLA_FWK__ define target_compile_definitions(${TARGET} PUBLIC __SLA_FWK__ ) endfunction() -function(prepare_image TARGET_IN) - #For the signed target, set up a POST_BUILD command to sign the elf file once - #created +function(sign_image TARGET_IN) + #For the signed target, set up a POST_BUILD command to sign the elf file once created if((WIN32) OR (MINGW) OR (MSYS)) set(SIGN_EXE "sign_app.exe") else() set(SIGN_EXE "sign_app") endif() - set(MCU_PATH "${TOP}/hw/mcu/analog/max32/") + set(MCU_PATH "${TOP}/hw/mcu/analog/msdk/") # Custom POST_BUILD command add_custom_command( diff --git a/hw/bsp/max32650/boards/max32650evkit/board.h b/hw/bsp/maxim/boards/max32651evkit/board.h similarity index 90% rename from hw/bsp/max32650/boards/max32650evkit/board.h rename to hw/bsp/maxim/boards/max32651evkit/board.h index 196abdaca..dbf2a4b7c 100644 --- a/hw/bsp/max32650/boards/max32650evkit/board.h +++ b/hw/bsp/maxim/boards/max32651evkit/board.h @@ -24,11 +24,15 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: MAX32651 EVKIT + url: https://www.analog.com/en/resources/evaluation-hardware-and-software/evaluation-boards-kits/max32651-evkit.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ -#include "gpio.h" -#include "mxc_sys.h" +#include "max32650.h" #ifdef __cplusplus extern "C" { diff --git a/hw/bsp/max32650/boards/max32651evkit/board.mk b/hw/bsp/maxim/boards/max32651evkit/board.mk similarity index 61% rename from hw/bsp/max32650/boards/max32651evkit/board.mk rename to hw/bsp/maxim/boards/max32651evkit/board.mk index b609598c1..5d4971148 100644 --- a/hw/bsp/max32650/boards/max32651evkit/board.mk +++ b/hw/bsp/maxim/boards/max32651evkit/board.mk @@ -1,5 +1,7 @@ +MAX_DEVICE = max32650 + # Use the secure linker file -LD_FILE = $(BOARD_PATH)/max32651.ld +LD_FILE = $(FAMILY_PATH)/linker/max32651.ld # Let the family script know the build needs to be signed SIGNED_BUILD := 1 diff --git a/hw/bsp/maxim/boards/max32666evkit/board.cmake b/hw/bsp/maxim/boards/max32666evkit/board.cmake new file mode 100644 index 000000000..e7116b603 --- /dev/null +++ b/hw/bsp/maxim/boards/max32666evkit/board.cmake @@ -0,0 +1,4 @@ +set(MAX_DEVICE max32665) + +function(update_board TARGET) +endfunction() diff --git a/hw/bsp/max32666/boards/max32666evkit/board.h b/hw/bsp/maxim/boards/max32666evkit/board.h similarity index 90% rename from hw/bsp/max32666/boards/max32666evkit/board.h rename to hw/bsp/maxim/boards/max32666evkit/board.h index 0ab1483b8..42965d3c5 100644 --- a/hw/bsp/max32666/boards/max32666evkit/board.h +++ b/hw/bsp/maxim/boards/max32666evkit/board.h @@ -24,11 +24,15 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: MAX32666 EVKIT + url: https://www.analog.com/en/resources/evaluation-hardware-and-software/evaluation-boards-kits/max32666evkit.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ -#include "gpio.h" -#include "mxc_sys.h" +#include "max32665.h" #ifdef __cplusplus extern "C" { diff --git a/hw/bsp/maxim/boards/max32666evkit/board.mk b/hw/bsp/maxim/boards/max32666evkit/board.mk new file mode 100644 index 000000000..a1cf3045d --- /dev/null +++ b/hw/bsp/maxim/boards/max32666evkit/board.mk @@ -0,0 +1 @@ +MAX_DEVICE = max32665 diff --git a/hw/bsp/maxim/boards/max32666fthr/board.cmake b/hw/bsp/maxim/boards/max32666fthr/board.cmake new file mode 100644 index 000000000..e7116b603 --- /dev/null +++ b/hw/bsp/maxim/boards/max32666fthr/board.cmake @@ -0,0 +1,4 @@ +set(MAX_DEVICE max32665) + +function(update_board TARGET) +endfunction() diff --git a/hw/bsp/max32666/boards/max32666fthr/board.h b/hw/bsp/maxim/boards/max32666fthr/board.h similarity index 90% rename from hw/bsp/max32666/boards/max32666fthr/board.h rename to hw/bsp/maxim/boards/max32666fthr/board.h index c719b748a..fbb217949 100644 --- a/hw/bsp/max32666/boards/max32666fthr/board.h +++ b/hw/bsp/maxim/boards/max32666fthr/board.h @@ -24,11 +24,15 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: MAX32666 Feather + url: https://www.analog.com/en/resources/evaluation-hardware-and-software/evaluation-boards-kits/max32666fthr.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ -#include "gpio.h" -#include "mxc_sys.h" +#include "max32665.h" #ifdef __cplusplus extern "C" { diff --git a/hw/bsp/maxim/boards/max32666fthr/board.mk b/hw/bsp/maxim/boards/max32666fthr/board.mk new file mode 100644 index 000000000..a1cf3045d --- /dev/null +++ b/hw/bsp/maxim/boards/max32666fthr/board.mk @@ -0,0 +1 @@ +MAX_DEVICE = max32665 diff --git a/hw/bsp/maxim/boards/max32690evkit/board.cmake b/hw/bsp/maxim/boards/max32690evkit/board.cmake new file mode 100644 index 000000000..a03d05f8d --- /dev/null +++ b/hw/bsp/maxim/boards/max32690evkit/board.cmake @@ -0,0 +1,4 @@ +set(MAX_DEVICE max32690) + +function(update_board TARGET) +endfunction() diff --git a/hw/bsp/max32690/boards/max32690evkit/board.h b/hw/bsp/maxim/boards/max32690evkit/board.h similarity index 90% rename from hw/bsp/max32690/boards/max32690evkit/board.h rename to hw/bsp/maxim/boards/max32690evkit/board.h index 05d60f220..41c73621f 100644 --- a/hw/bsp/max32690/boards/max32690evkit/board.h +++ b/hw/bsp/maxim/boards/max32690evkit/board.h @@ -24,16 +24,20 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: MAX32690 EVKIT + url: https://www.analog.com/en/resources/evaluation-hardware-and-software/evaluation-boards-kits/max32690evkit.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ -#include "gpio.h" -#include "mxc_sys.h" - #ifdef __cplusplus extern "C" { #endif +#include "max32690.h" + // LED #define LED_PORT MXC_GPIO0 #define LED_PIN MXC_GPIO_PIN_14 diff --git a/hw/bsp/maxim/boards/max32690evkit/board.mk b/hw/bsp/maxim/boards/max32690evkit/board.mk new file mode 100644 index 000000000..d8a0c9cae --- /dev/null +++ b/hw/bsp/maxim/boards/max32690evkit/board.mk @@ -0,0 +1 @@ +MAX_DEVICE = max32690 diff --git a/hw/bsp/maxim/boards/max78002evkit/board.cmake b/hw/bsp/maxim/boards/max78002evkit/board.cmake new file mode 100644 index 000000000..dd4c3c215 --- /dev/null +++ b/hw/bsp/maxim/boards/max78002evkit/board.cmake @@ -0,0 +1,4 @@ +set(MAX_DEVICE max78002) + +function(update_board TARGET) +endfunction() diff --git a/hw/bsp/max78002/boards/max78002evkit/board.h b/hw/bsp/maxim/boards/max78002evkit/board.h similarity index 90% rename from hw/bsp/max78002/boards/max78002evkit/board.h rename to hw/bsp/maxim/boards/max78002evkit/board.h index f8102c394..8c1fc13d4 100644 --- a/hw/bsp/max78002/boards/max78002evkit/board.h +++ b/hw/bsp/maxim/boards/max78002evkit/board.h @@ -24,11 +24,15 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: MAX78002 EVKIT + url: https://www.analog.com/en/resources/evaluation-hardware-and-software/evaluation-boards-kits/max78002evkit.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ -#include "gpio.h" -#include "mxc_sys.h" +#include "max78002.h" #ifdef __cplusplus extern "C" { diff --git a/hw/bsp/maxim/boards/max78002evkit/board.mk b/hw/bsp/maxim/boards/max78002evkit/board.mk new file mode 100644 index 000000000..b19e95187 --- /dev/null +++ b/hw/bsp/maxim/boards/max78002evkit/board.mk @@ -0,0 +1 @@ +MAX_DEVICE = max78002 diff --git a/hw/bsp/max32666/family.c b/hw/bsp/maxim/family.c similarity index 76% rename from hw/bsp/max32666/family.c rename to hw/bsp/maxim/family.c index f96393fe1..0ef6b8c4d 100644 --- a/hw/bsp/max32666/family.c +++ b/hw/bsp/maxim/family.c @@ -24,6 +24,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: Analog Devices +*/ + #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstrict-prototypes" // _mxc_crit_get_state() @@ -31,7 +35,9 @@ #include "gpio.h" #include "mxc_sys.h" +#if __has_include("mcr_regs.h") #include "mcr_regs.h" +#endif #include "mxc_device.h" #include "uart.h" @@ -84,16 +90,45 @@ void board_init(void) { MXC_GPIO_Config(&gpioConfig); // UART +#if MAX_PERIPH_ID == 14 MXC_UART_Init(ConsoleUart, CFG_BOARD_UART_BAUDRATE, UART_MAP); +#elif MAX_PERIPH_ID == 18 || MAX_PERIPH_ID == 87 + MXC_UART_Init(ConsoleUart, CFG_BOARD_UART_BAUDRATE, MXC_UART_IBRO_CLK); + #if MAX_PERIPH_ID == 87 + UART_PORT->vssel |= UART_VDDIO_BITS; // Set necessary bits to 3.3V + #endif +#endif //USB +#if defined(MAX32650) // Startup the HIRC96M clock if it's not on already - if (!(MXC_GCR->clkcn & MXC_F_GCR_CLKCN_HIRC96M_EN)) { - MXC_GCR->clkcn |= MXC_F_GCR_CLKCN_HIRC96M_EN; + if (!(MXC_GCR->clk_ctrl & MXC_F_GCR_CLK_CTRL_HIRC96_EN)) { + MXC_GCR->clk_ctrl |= MXC_F_GCR_CLK_CTRL_HIRC96_EN; + MXC_SYS_Clock_Timeout(MXC_F_GCR_CLK_CTRL_HIRC96_RDY); } - MXC_SYS_ClockEnable(MXC_SYS_PERIPH_CLOCK_USB); MXC_SYS_Reset_Periph(MXC_SYS_RESET_USB); + +#elif defined(MAX32665) || defined(MAX32666) + // Startup the HIRC96M clock if it's not on already + if (!(MXC_GCR->clkcn & MXC_F_GCR_CLKCN_HIRC96M_EN)) { + MXC_GCR->clkcn |= MXC_F_GCR_CLKCN_HIRC96M_EN; + } + MXC_SYS_ClockEnable(MXC_SYS_PERIPH_CLOCK_USB); + MXC_SYS_Reset_Periph(MXC_SYS_RESET_USB); + +#elif defined(MAX32690) + MXC_SYS_ClockSourceEnable(MXC_SYS_CLOCK_IPO); + MXC_MCR->ldoctrl |= MXC_F_MCR_LDOCTRL_0P9EN; + MXC_SYS_ClockEnable(MXC_SYS_PERIPH_CLOCK_USB); + MXC_SYS_Reset_Periph(MXC_SYS_RESET0_USB); + +# elif defined(MAX78002) + MXC_MCR->ldoctrl |= MXC_F_MCR_LDOCTRL_0P9EN; + MXC_SYS_ClockEnable(MXC_SYS_PERIPH_CLOCK_USB); +#else + #error "Unsupported MAXIM MCU for board_dfu_init" +#endif } //--------------------------------------------------------------------+ @@ -117,13 +152,18 @@ uint32_t board_button_read(void) { } size_t board_get_unique_id(uint8_t id[], size_t max_len) { - uint8_t hw_id[MXC_SYS_USN_CHECKSUM_LEN];//USN Buffer - /* All other 2nd parameter is optional checksum buffer */ - MXC_SYS_GetUSN(hw_id, NULL); +#if defined(MAX32650) + // USN is 13 bytes on this device + MXC_SYS_GetUSN(id, 13); + return 13; +#else + uint8_t hw_id[MXC_SYS_USN_CHECKSUM_LEN]; //USN Buffer + MXC_SYS_GetUSN(hw_id, NULL); // 2nd parameter is optional checksum buffer size_t act_len = TU_MIN(max_len, MXC_SYS_USN_LEN); memcpy(id, hw_id, act_len); return act_len; +#endif } int board_uart_read(uint8_t *buf, int len) { diff --git a/hw/bsp/maxim/family.cmake b/hw/bsp/maxim/family.cmake new file mode 100644 index 000000000..75daec753 --- /dev/null +++ b/hw/bsp/maxim/family.cmake @@ -0,0 +1,196 @@ +include_guard() + +# stub: overridden by board.cmake if needed +function(sign_image TARGET_IN) +endfunction() + +set(MSDK_LIB ${TOP}/hw/mcu/analog/msdk/Libraries) + +# include board specific +include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) + +# toolchain set up +set(CMAKE_SYSTEM_CPU cortex-m4 CACHE INTERNAL "System Processor") +set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) + +string(TOUPPER ${MAX_DEVICE} MAX_DEVICE_UPPER) +cmake_print_variables(MAX_DEVICE MAX_DEVICE_UPPER) + +set(JLINK_DEVICE ${MAX_DEVICE}) +set(OPENOCD_OPTION "-f interface/cmsis-dap.cfg -f target/${MAX_DEVICE}.cfg") + +set(FAMILY_MCUS ${MAX_DEVICE_UPPER} CACHE INTERNAL "") + +if (${MAX_DEVICE} STREQUAL "max32650") + set(PERIPH_ID 10) + set(PERIPH_SUFFIX "me") +elseif (${MAX_DEVICE} STREQUAL "max32665" OR ${MAX_DEVICE} STREQUAL "max32666") + set(PERIPH_ID 14) + set(PERIPH_SUFFIX "me") +elseif (${MAX_DEVICE} STREQUAL "max32690") + set(PERIPH_ID 18) + set(PERIPH_SUFFIX "me") +elseif (${MAX_DEVICE} STREQUAL "max78002") + set(PERIPH_ID 87) + set(PERIPH_SUFFIX "ai") +else() + message(FATAL_ERROR "Unsupported MAX device: ${MAX_DEVICE}") +endif() + +#------------------------------------ +# BOARD_TARGET +#------------------------------------ +# only need to be built ONCE for all examples +function(add_board_target BOARD_TARGET) + if (TARGET ${BOARD_TARGET}) + return() + endif () + + # Startup & Linker script + set(STARTUP_FILE_GNU ${MSDK_LIB}/CMSIS/Device/Maxim/${MAX_DEVICE_UPPER}/Source/GCC/startup_${MAX_DEVICE}.S) + set(STARTUP_FILE_Clang ${STARTUP_FILE_GNU}) + + if (NOT DEFINED LD_FILE_GNU) + set(LD_FILE_GNU ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/linker/${MAX_DEVICE}.ld) + endif () + set(LD_FILE_Clang ${LD_FILE_GNU}) + + # Common + add_library(${BOARD_TARGET} STATIC + ${STARTUP_FILE_${CMAKE_C_COMPILER_ID}} + ${MSDK_LIB}/CMSIS/Device/Maxim/${MAX_DEVICE_UPPER}/Source/heap.c + ${MSDK_LIB}/CMSIS/Device/Maxim/${MAX_DEVICE_UPPER}/Source/system_${MAX_DEVICE}.c + ${MSDK_LIB}/PeriphDrivers/Source/SYS/mxc_assert.c + ${MSDK_LIB}/PeriphDrivers/Source/SYS/mxc_delay.c + ${MSDK_LIB}/PeriphDrivers/Source/SYS/mxc_lock.c + ${MSDK_LIB}/PeriphDrivers/Source/SYS/nvic_table.c + ${MSDK_LIB}/PeriphDrivers/Source/SYS/pins_${PERIPH_SUFFIX}${PERIPH_ID}.c + ${MSDK_LIB}/PeriphDrivers/Source/SYS/sys_${PERIPH_SUFFIX}${PERIPH_ID}.c + ${MSDK_LIB}/PeriphDrivers/Source/FLC/flc_common.c + ${MSDK_LIB}/PeriphDrivers/Source/FLC/flc_${PERIPH_SUFFIX}${PERIPH_ID}.c + ${MSDK_LIB}/PeriphDrivers/Source/FLC/flc_reva.c + ${MSDK_LIB}/PeriphDrivers/Source/GPIO/gpio_common.c + ${MSDK_LIB}/PeriphDrivers/Source/GPIO/gpio_${PERIPH_SUFFIX}${PERIPH_ID}.c + ${MSDK_LIB}/PeriphDrivers/Source/GPIO/gpio_reva.c + ${MSDK_LIB}/PeriphDrivers/Source/ICC/icc_${PERIPH_SUFFIX}${PERIPH_ID}.c + ${MSDK_LIB}/PeriphDrivers/Source/ICC/icc_reva.c + ${MSDK_LIB}/PeriphDrivers/Source/UART/uart_common.c + ${MSDK_LIB}/PeriphDrivers/Source/UART/uart_${PERIPH_SUFFIX}${PERIPH_ID}.c + ) + target_include_directories(${BOARD_TARGET} PUBLIC + ${MSDK_LIB}/CMSIS/5.9.0/Core/Include + ${MSDK_LIB}/CMSIS/Device/Maxim/${MAX_DEVICE_UPPER}/Include + ${MSDK_LIB}/PeriphDrivers/Include/${MAX_DEVICE_UPPER} + ${MSDK_LIB}/PeriphDrivers/Source/SYS + ${MSDK_LIB}/PeriphDrivers/Source/GPIO + ${MSDK_LIB}/PeriphDrivers/Source/ICC + ${MSDK_LIB}/PeriphDrivers/Source/FLC + ${MSDK_LIB}/PeriphDrivers/Source/UART + ) + + # device specific + if (${MAX_DEVICE} STREQUAL "max32650" OR + ${MAX_DEVICE} STREQUAL "max32665" OR ${MAX_DEVICE} STREQUAL "max32666") + target_sources(${BOARD_TARGET} PRIVATE + ${MSDK_LIB}/PeriphDrivers/Source/ICC/icc_common.c + ${MSDK_LIB}/PeriphDrivers/Source/TPU/tpu_${PERIPH_SUFFIX}${PERIPH_ID}.c + ${MSDK_LIB}/PeriphDrivers/Source/TPU/tpu_reva.c + ${MSDK_LIB}/PeriphDrivers/Source/UART/uart_reva.c + ) + target_include_directories(${BOARD_TARGET} PUBLIC + ${MSDK_LIB}/PeriphDrivers/Source/TPU + ) + elseif (${MAX_DEVICE} STREQUAL "max32690") + target_sources(${BOARD_TARGET} PRIVATE + ${MSDK_LIB}/PeriphDrivers/Source/CTB/ctb_${PERIPH_SUFFIX}${PERIPH_ID}.c + ${MSDK_LIB}/PeriphDrivers/Source/CTB/ctb_reva.c + ${MSDK_LIB}/PeriphDrivers/Source/CTB/ctb_common.c + ${MSDK_LIB}/PeriphDrivers/Source/UART/uart_revb.c + ) + target_include_directories(${BOARD_TARGET} PUBLIC + ${MSDK_LIB}/PeriphDrivers/Source/CTB + ) + elseif (${MAX_DEVICE} STREQUAL "max78002") + target_sources(${BOARD_TARGET} PRIVATE + ${MSDK_LIB}/PeriphDrivers/Source/AES/aes_${PERIPH_SUFFIX}${PERIPH_ID}.c + ${MSDK_LIB}/PeriphDrivers/Source/AES/aes_revb.c + ${MSDK_LIB}/PeriphDrivers/Source/TRNG/trng_${PERIPH_SUFFIX}${PERIPH_ID}.c + ${MSDK_LIB}/PeriphDrivers/Source/TRNG/trng_revb.c + ${MSDK_LIB}/PeriphDrivers/Source/UART/uart_revb.c + ) + target_include_directories(${BOARD_TARGET} PUBLIC + ${MSDK_LIB}/PeriphDrivers/Source/AES + ${MSDK_LIB}/PeriphDrivers/Source/TRNG + ) + else() + message(FATAL_ERROR "Unsupported MAX device: ${MAX_DEVICE}") + endif() + + target_compile_definitions(${BOARD_TARGET} PUBLIC + TARGET=${MAX_DEVICE_UPPER} + TARGET_REV=0x4131 + MXC_ASSERT_ENABLE + ${MAX_DEVICE_UPPER} + IAR_PRAGMAS=0 + MAX_PERIPH_ID=${PERIPH_ID} + BOARD_TUD_MAX_SPEED=OPT_MODE_HIGH_SPEED + ) + target_compile_options(${BOARD_TARGET} PRIVATE + -Wno-error=strict-prototypes + ) + update_board(${BOARD_TARGET}) + + if (CMAKE_C_COMPILER_ID STREQUAL "GNU") + target_link_options(${BOARD_TARGET} PUBLIC + "LINKER:--script=${LD_FILE_GNU}" + -nostartfiles + --specs=nosys.specs --specs=nano.specs + ) + elseif (CMAKE_C_COMPILER_ID STREQUAL "Clang") + target_link_options(${BOARD_TARGET} PUBLIC + "LINKER:--script=${LD_FILE_Clang}" + ) + endif () +endfunction() + + +#------------------------------------ +# Functions +#------------------------------------ +function(family_configure_example TARGET RTOS) + family_configure_common(${TARGET} ${RTOS}) + + # Board target + add_board_target(board_${BOARD}) + + #---------- Port Specific ---------- + # These files are built for each example since it depends on example's tusb_config.h + target_sources(${TARGET} PUBLIC + # BSP + ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/family.c + ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/../board.c + ) + target_include_directories(${TARGET} PUBLIC + # family, hw, board + ${CMAKE_CURRENT_FUNCTION_LIST_DIR} + ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/../../ + ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/boards/${BOARD} + ) + + # Add TinyUSB target and port source + family_add_tinyusb(${TARGET} OPT_MCU_${MAX_DEVICE_UPPER}) + target_sources(${TARGET} PUBLIC + ${TOP}/src/portable/mentor/musb/dcd_musb.c + ) + target_compile_options(${TARGET} PRIVATE + -Wno-error=strict-prototypes + ) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + + # Flashing + family_add_bin_hex(${TARGET}) + family_flash_jlink(${TARGET}) + + sign_image(${TARGET}) # for secured device such as max32651 + family_flash_openocd_adi(${TARGET}) +endfunction() diff --git a/hw/bsp/maxim/family.mk b/hw/bsp/maxim/family.mk new file mode 100644 index 000000000..3ddf8cf39 --- /dev/null +++ b/hw/bsp/maxim/family.mk @@ -0,0 +1,190 @@ +MSDK_LIB = hw/mcu/analog/msdk/Libraries + +# Add any board specific make rules +include $(TOP)/$(BOARD_PATH)/board.mk + +CPU_CORE ?= cortex-m4 +PORT ?= 0 +JLINK_DEVICE = ${MAX_DEVICE} +MAX_DEVICE_UPPER = $(call to_upper,${MAX_DEVICE}) + +ifeq ($(MAX_DEVICE),max32650) + PERIPH_ID = 10 + PERIPH_SUFFIX = me +endif + +ifneq ($(filter $(MAX_DEVICE),max32665 max32666),) + PERIPH_ID = 14 + PERIPH_SUFFIX = me +endif + +ifeq ($(MAX_DEVICE),max32690) + PERIPH_ID = 18 + PERIPH_SUFFIX = me +endif + +ifeq ($(MAX_DEVICE),max78002) + PERIPH_ID = 87 + PERIPH_SUFFIX = ai +endif + +ifndef PERIPH_ID + $(error Unsupported MAX device: ${MAX_DEVICE}) +endif + +# Configure the flash rule. By default, use JLink. +SIGNED_BUILD ?= 0 +DEFAULT_FLASH = flash-jlink + +# -------------- +# Compiler Flags +# -------------- +CFLAGS += \ + -DTARGET=${MAX_DEVICE_UPPER}\ + -DTARGET_REV=0x4131 \ + -DMXC_ASSERT_ENABLE \ + -D${MAX_DEVICE_UPPER} \ + -DIAR_PRAGMAS=0 \ + -DMAX_PERIPH_ID=${PERIPH_ID} \ + -DCFG_TUSB_MCU=OPT_MCU_${MAX_DEVICE_UPPER} \ + -DBOARD_TUD_MAX_SPEED=OPT_MODE_HIGH_SPEED + +# mcu driver cause following warnings +CFLAGS += \ + -Wno-error=old-style-declaration \ + -Wno-error=redundant-decls \ + -Wno-error=strict-prototypes \ + -Wno-error=unused-parameter \ + -Wno-error=cast-align \ + -Wno-error=cast-qual \ + -Wno-error=sign-compare \ + -Wno-error=enum-conversion \ + +LDFLAGS_GCC += -nostartfiles --specs=nosys.specs --specs=nano.specs +LD_FILE_GCC ?= $(FAMILY_PATH)/linker/${MAX_DEVICE}.ld + +# If the applications needs to be signed (for the MAX32651), sign it first and +# then need to use MSDK's OpenOCD to flash it +# Also need to include the __SLA_FWK__ define to enable the signed header into +# memory +ifeq ($(SIGNED_BUILD), 1) +# Extra definitions to build for the secure part +CFLAGS += -D__SLA_FWK__ +DEFAULT_FLASH := sign-build flash-msdk +endif + +# ----------------- +# Sources & Include +# ----------------- + +# common +SRC_C += \ + src/portable/mentor/musb/dcd_musb.c \ + ${MSDK_LIB}/CMSIS/Device/Maxim/${MAX_DEVICE_UPPER}/Source/heap.c \ + ${MSDK_LIB}/CMSIS/Device/Maxim/${MAX_DEVICE_UPPER}/Source/system_${MAX_DEVICE}.c \ + ${MSDK_LIB}/PeriphDrivers/Source/SYS/mxc_assert.c \ + ${MSDK_LIB}/PeriphDrivers/Source/SYS/mxc_delay.c \ + ${MSDK_LIB}/PeriphDrivers/Source/SYS/mxc_lock.c \ + ${MSDK_LIB}/PeriphDrivers/Source/SYS/nvic_table.c \ + ${MSDK_LIB}/PeriphDrivers/Source/SYS/pins_${PERIPH_SUFFIX}${PERIPH_ID}.c \ + ${MSDK_LIB}/PeriphDrivers/Source/SYS/sys_${PERIPH_SUFFIX}${PERIPH_ID}.c \ + ${MSDK_LIB}/PeriphDrivers/Source/FLC/flc_common.c \ + ${MSDK_LIB}/PeriphDrivers/Source/FLC/flc_${PERIPH_SUFFIX}${PERIPH_ID}.c \ + ${MSDK_LIB}/PeriphDrivers/Source/FLC/flc_reva.c \ + ${MSDK_LIB}/PeriphDrivers/Source/GPIO/gpio_common.c \ + ${MSDK_LIB}/PeriphDrivers/Source/GPIO/gpio_${PERIPH_SUFFIX}${PERIPH_ID}.c \ + ${MSDK_LIB}/PeriphDrivers/Source/GPIO/gpio_reva.c \ + ${MSDK_LIB}/PeriphDrivers/Source/ICC/icc_${PERIPH_SUFFIX}${PERIPH_ID}.c \ + ${MSDK_LIB}/PeriphDrivers/Source/ICC/icc_reva.c \ + ${MSDK_LIB}/PeriphDrivers/Source/UART/uart_common.c \ + ${MSDK_LIB}/PeriphDrivers/Source/UART/uart_${PERIPH_SUFFIX}${PERIPH_ID}.c \ + +SRC_S_GCC += ${MSDK_LIB}/CMSIS/Device/Maxim/${MAX_DEVICE_UPPER}/Source/GCC/startup_${MAX_DEVICE}.S + +INC += \ + $(TOP)/$(BOARD_PATH) \ + $(TOP)/${MSDK_LIB}/CMSIS/5.9.0/Core/Include \ + $(TOP)/${MSDK_LIB}/CMSIS/Device/Maxim/${MAX_DEVICE_UPPER}/Include \ + $(TOP)/${MSDK_LIB}/PeriphDrivers/Include/${MAX_DEVICE_UPPER} \ + $(TOP)/${MSDK_LIB}/PeriphDrivers/Source/SYS \ + $(TOP)/${MSDK_LIB}/PeriphDrivers/Source/GPIO \ + $(TOP)/${MSDK_LIB}/PeriphDrivers/Source/ICC \ + $(TOP)/${MSDK_LIB}/PeriphDrivers/Source/FLC \ + $(TOP)/${MSDK_LIB}/PeriphDrivers/Source/UART \ + +# device specific +ifneq ($(filter $(MAX_DEVICE),max32650 max32665 max32666),) + SRC_C += \ + ${MSDK_LIB}/PeriphDrivers/Source/ICC/icc_common.c \ + ${MSDK_LIB}/PeriphDrivers/Source/TPU/tpu_${PERIPH_SUFFIX}${PERIPH_ID}.c \ + ${MSDK_LIB}/PeriphDrivers/Source/TPU/tpu_reva.c \ + ${MSDK_LIB}/PeriphDrivers/Source/UART/uart_reva.c \ + + INC += $(TOP)/${MSDK_LIB}/PeriphDrivers/Source/TPU +endif + +ifeq (${MAX_DEVICE},max32690) + SRC_C += \ + ${MSDK_LIB}/PeriphDrivers/Source/CTB/ctb_${PERIPH_SUFFIX}${PERIPH_ID}.c \ + ${MSDK_LIB}/PeriphDrivers/Source/CTB/ctb_reva.c \ + ${MSDK_LIB}/PeriphDrivers/Source/CTB/ctb_common.c \ + ${MSDK_LIB}/PeriphDrivers/Source/UART/uart_revb.c \ + + INC += ${TOP}/${MSDK_LIB}/PeriphDrivers/Source/CTB +endif + +ifeq (${MAX_DEVICE},max78002) + SRC_C += \ + ${MSDK_LIB}/PeriphDrivers/Source/AES/aes_${PERIPH_SUFFIX}${PERIPH_ID}.c \ + ${MSDK_LIB}/PeriphDrivers/Source/AES/aes_revb.c \ + ${MSDK_LIB}/PeriphDrivers/Source/TRNG/trng_${PERIPH_SUFFIX}${PERIPH_ID}.c \ + ${MSDK_LIB}/PeriphDrivers/Source/TRNG/trng_revb.c \ + ${MSDK_LIB}/PeriphDrivers/Source/UART/uart_revb.c \ + + INC += \ + ${TOP}/${MSDK_LIB}/PeriphDrivers/Source/AES \ + ${TOP}/${MSDK_LIB}/PeriphDrivers/Source/TRNG +endif + + +# The MAX32651EVKIT is pin for pin identical to the MAX32650EVKIT, however the +# MAX32651 has a secure bootloader which requires the image to be signed before +# loading into flash. All MAX32651EVKIT's have the same key for evaluation +# purposes, so create a special flash rule to sign the binary and flash using +# the MSDK. +MCU_PATH = $(TOP)/hw/mcu/analog/msdk/ +# Assume no extension for sign utility +SIGN_EXE = sign_app +ifeq ($(OS), Windows_NT) +# Must use .exe extension on Windows, since the binaries +# for Linux may live in the same place. +SIGN_EXE := sign_app.exe +else +UNAME = $(shell uname -s) +ifneq ($(findstring MSYS_NT,$(UNAME)),) +# Must also use .exe extension for MSYS2 +SIGN_EXE := sign_app.exe +endif +endif + +# Rule to sign the build. This will in-place modify the existing .elf file +# an populate the .sig section with the signature value +sign-build: $(BUILD)/$(PROJECT).elf + $(OBJCOPY) $(BUILD)/$(PROJECT).elf -R .sig -O binary $(BUILD)/$(PROJECT).bin + $(MCU_PATH)/Tools/SBT/bin/$(SIGN_EXE) -c MAX32651 \ + key_file="$(MCU_PATH)/Tools/SBT/devices/MAX32651/keys/maximtestcrk.key" \ + ca=$(BUILD)/$(PROJECT).bin sca=$(BUILD)/$(PROJECT).sbin + $(OBJCOPY) $(BUILD)/$(PROJECT).elf --update-section .sig=$(BUILD)/$(PROJECT).sig + +# Optional flash option when running within an installed MSDK to use OpenOCD +# Mainline OpenOCD does not yet have the MAX32's flash algorithm integrated. +# If the MSDK is installed, flash-msdk can be run to utilize the the modified +# openocd with the algorithms +MAXIM_PATH := $(subst \,/,$(MAXIM_PATH)) +flash-msdk: $(BUILD)/$(PROJECT).elf + $(MAXIM_PATH)/Tools/OpenOCD/openocd -s $(MAXIM_PATH)/Tools/OpenOCD/scripts \ + -f interface/cmsis-dap.cfg -f target/max32650.cfg \ + -c "program $(BUILD)/$(PROJECT).elf verify; init; reset; exit" + +# Configure the flash rule +flash: $(DEFAULT_FLASH) diff --git a/hw/bsp/max32650/boards/max32650evkit/max32650.ld b/hw/bsp/maxim/linker/max32650.ld similarity index 100% rename from hw/bsp/max32650/boards/max32650evkit/max32650.ld rename to hw/bsp/maxim/linker/max32650.ld diff --git a/hw/bsp/max32650/boards/max32651evkit/max32651.ld b/hw/bsp/maxim/linker/max32651.ld similarity index 100% rename from hw/bsp/max32650/boards/max32651evkit/max32651.ld rename to hw/bsp/maxim/linker/max32651.ld diff --git a/hw/bsp/max32666/max32666.ld b/hw/bsp/maxim/linker/max32665.ld similarity index 100% rename from hw/bsp/max32666/max32666.ld rename to hw/bsp/maxim/linker/max32665.ld diff --git a/hw/bsp/max32690/max32690.ld b/hw/bsp/maxim/linker/max32690.ld similarity index 100% rename from hw/bsp/max32690/max32690.ld rename to hw/bsp/maxim/linker/max32690.ld diff --git a/hw/bsp/max78002/max78002.ld b/hw/bsp/maxim/linker/max78002.ld similarity index 100% rename from hw/bsp/max78002/max78002.ld rename to hw/bsp/maxim/linker/max78002.ld diff --git a/hw/bsp/mcx/boards/frdm_mcxa153/board.h b/hw/bsp/mcx/boards/frdm_mcxa153/board.h index e207d89d9..86f987de9 100644 --- a/hw/bsp/mcx/boards/frdm_mcxa153/board.h +++ b/hw/bsp/mcx/boards/frdm_mcxa153/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Freedom MCXA153 + url: https://www.nxp.com/design/design-center/development-boards-and-designs/FRDM-MCXA153 +*/ + #ifndef BOARD_H_ #define BOARD_H_ @@ -34,10 +39,10 @@ extern "C" { // LED #define LED_GPIO GPIO3 #define LED_CLK kCLOCK_GateGPIO3 -#define LED_PIN 12 // red +#define LED_PIN 12 //red #define LED_STATE_ON 0 -// ISP button (Dummy, use unused pin +// ISP button #define BUTTON_GPIO GPIO3 #define BUTTON_CLK kCLOCK_GateGPIO3 #define BUTTON_PIN 29 //sw2 diff --git a/hw/bsp/mcx/boards/frdm_mcxa153/clock_config.c b/hw/bsp/mcx/boards/frdm_mcxa153/clock_config.c index f16bc51f6..5a132dc67 100644 --- a/hw/bsp/mcx/boards/frdm_mcxa153/clock_config.c +++ b/hw/bsp/mcx/boards/frdm_mcxa153/clock_config.c @@ -45,14 +45,13 @@ processor_version: 0.13.0 * Variables ******************************************************************************/ /* System clock frequency. */ -//uint32_t SystemCoreClock; +//extern uint32_t SystemCoreClock; /******************************************************************************* ************************ BOARD_InitBootClocks function ************************ ******************************************************************************/ void BOARD_InitBootClocks(void) { - BOARD_BootClockFRO96M(); } /******************************************************************************* @@ -386,7 +385,6 @@ void BOARD_BootClockFRO64M(void) /* TEXT BELOW IS USED AS SETTING FOR TOOLS ************************************* !!Configuration name: BOARD_BootClockFRO96M -called_from_default_init: true outputs: - {id: CLK_1M_clock.outFreq, value: 1 MHz} - {id: CLK_48M_clock.outFreq, value: 48 MHz} diff --git a/hw/bsp/mcx/boards/frdm_mcxa153/pin_mux.c b/hw/bsp/mcx/boards/frdm_mcxa153/pin_mux.c index cc8f56e63..47709951b 100644 --- a/hw/bsp/mcx/boards/frdm_mcxa153/pin_mux.c +++ b/hw/bsp/mcx/boards/frdm_mcxa153/pin_mux.c @@ -4,7 +4,6 @@ * * SPDX-License-Identifier: BSD-3-Clause */ - /*********************************************************************************************************************** * This file was generated by the MCUXpresso Config Tools. Any manual edits made to this file * will be overwritten if the respective MCUXpresso Config Tools is used to update this file. @@ -18,16 +17,13 @@ product: Pins v14.0 processor: MCXA153 package_id: MCXA153VLH mcu_data: ksdk2_0 -processor_version: 0.14.3 -pin_labels: -- {pin_num: '38', pin_signal: P3_12/LPUART2_RTS_B/CT1_MAT2/PWM0_X0, label: LED_RED, identifier: LED_RED} +processor_version: 0.14.4 * BE CAREFUL MODIFYING THIS COMMENT - IT IS YAML SETTINGS FOR TOOLS *********** */ /* clang-format on */ #include "fsl_common.h" #include "fsl_port.h" -#include "fsl_gpio.h" #include "pin_mux.h" /* FUNCTION ************************************************************************************************************ @@ -47,8 +43,10 @@ void BOARD_InitBootPins(void) BOARD_InitPins: - options: {callFromInitBoot: 'true', coreID: cm33_core0, enableClock: 'true'} - pin_list: - - {pin_num: '38', peripheral: GPIO3, signal: 'GPIO, 12', pin_signal: P3_12/LPUART2_RTS_B/CT1_MAT2/PWM0_X0, direction: OUTPUT, gpio_init_state: 'false', slew_rate: fast, - open_drain: disable, drive_strength: low, pull_select: down, pull_enable: disable, input_buffer: enable, invert_input: normal} + - {pin_num: '51', peripheral: LPUART0, signal: RX, pin_signal: P0_2/TDO/SWO/LPUART0_RXD/LPSPI0_SCK/CT0_MAT0/UTICK_CAP0/I3C0_PUR, slew_rate: fast, open_drain: disable, + drive_strength: low, pull_select: up, pull_enable: enable, input_buffer: enable, invert_input: normal} + - {pin_num: '52', peripheral: LPUART0, signal: TX, pin_signal: P0_3/TDI/LPUART0_TXD/LPSPI0_SDO/CT0_MAT1/UTICK_CAP1/CMP0_OUT/CMP1_IN1, slew_rate: fast, open_drain: disable, + drive_strength: low, pull_select: up, pull_enable: enable, input_buffer: enable, invert_input: normal} * BE CAREFUL MODIFYING THIS COMMENT - IT IS YAML SETTINGS FOR TOOLS *********** */ /* clang-format on */ @@ -61,15 +59,6 @@ BOARD_InitPins: * END ****************************************************************************************************************/ void BOARD_InitPins(void) { - RESET_PeripheralReset(kLPUART0_RST_SHIFT_RSTn); - RESET_PeripheralReset(kPORT0_RST_SHIFT_RSTn); - CLOCK_SetClockDiv(kCLOCK_DivLPUART0, 1u); - CLOCK_AttachClk(kFRO12M_to_LPUART0); - - /* write to PORT0: Peripheral clock is enabled */ - CLOCK_EnableClock(kCLOCK_GatePORT0); - - /* Write to GPIO3: Peripheral clock is enabled */ CLOCK_EnableClock(kCLOCK_GateGPIO3); /* Write to PORT3: Peripheral clock is enabled */ CLOCK_EnableClock(kCLOCK_GatePORT3); @@ -78,30 +67,13 @@ void BOARD_InitPins(void) /* PORT3 peripheral is released from reset */ RESET_ReleasePeripheralReset(kPORT3_RST_SHIFT_RSTn); - const port_pin_config_t port3_12_pin38_config = {/* Internal pull-up/down resistor is disabled */ - kPORT_PullDisable, - /* Low internal pull resistor value is selected. */ - kPORT_LowPullResistor, - /* Fast slew rate is configured */ - kPORT_FastSlewRate, - /* Passive input filter is disabled */ - kPORT_PassiveFilterDisable, - /* Open drain output is disabled */ - kPORT_OpenDrainDisable, - /* Low drive strength is configured */ - kPORT_LowDriveStrength, - /* Normal drive strength is configured */ - kPORT_NormalDriveStrength, - /* Pin is configured as P3_12 */ - kPORT_MuxAlt0, - /* Digital input enabled */ - kPORT_InputBufferEnable, - /* Digital input is not inverted */ - kPORT_InputNormal, - /* Pin Control Register fields [15:0] are not locked */ - kPORT_UnlockRegister}; - /* PORT3_12 (pin 38) is configured as P3_12 */ - PORT_SetPinConfig(PORT3, 12U, &port3_12_pin38_config); + + /* Write to PORT0: Peripheral clock is enabled */ + CLOCK_EnableClock(kCLOCK_GatePORT0); + /* LPUART0 peripheral is released from reset */ + RESET_ReleasePeripheralReset(kLPUART0_RST_SHIFT_RSTn); + /* PORT0 peripheral is released from reset */ + RESET_ReleasePeripheralReset(kPORT0_RST_SHIFT_RSTn); const port_pin_config_t port0_2_pin51_config = {/* Internal pull-up resistor is enabled */ kPORT_PullUp, @@ -152,7 +124,6 @@ void BOARD_InitPins(void) kPORT_UnlockRegister}; /* PORT0_3 (pin 52) is configured as LPUART0_TXD */ PORT_SetPinConfig(PORT0, 3U, &port0_3_pin52_config); - } /*********************************************************************************************************************** * EOF diff --git a/hw/bsp/mcx/boards/frdm_mcxa153/pin_mux.h b/hw/bsp/mcx/boards/frdm_mcxa153/pin_mux.h index 06b6fdee9..2c0e617a5 100644 --- a/hw/bsp/mcx/boards/frdm_mcxa153/pin_mux.h +++ b/hw/bsp/mcx/boards/frdm_mcxa153/pin_mux.h @@ -1,9 +1,13 @@ /* - * Copyright 2022 NXP + * Copyright 2023 NXP * All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ +/*********************************************************************************************************************** + * This file was generated by the MCUXpresso Config Tools. Any manual edits made to this file + * will be overwritten if the respective MCUXpresso Config Tools is used to update this file. + **********************************************************************************************************************/ #ifndef _PIN_MUX_H_ #define _PIN_MUX_H_ diff --git a/hw/bsp/mcx/boards/frdm_mcxa156/board.cmake b/hw/bsp/mcx/boards/frdm_mcxa156/board.cmake new file mode 100644 index 000000000..a6aa6c2e4 --- /dev/null +++ b/hw/bsp/mcx/boards/frdm_mcxa156/board.cmake @@ -0,0 +1,21 @@ +set(MCU_VARIANT MCXA156) +set(MCU_CORE MCXA156) + +set(JLINK_DEVICE MCXA156_M33) +set(PYOCD_TARGET MCXA156) +set(NXPLINK_DEVICE MCXA156:MCXA156) + +set(PORT 0) + +function(update_board TARGET) + target_compile_definitions(${TARGET} PUBLIC + CPU_MCXA156VLH + BOARD_TUD_RHPORT=0 + BOARD_TUD_MAX_SPEED=OPT_MODE_FULL_SPEED + CFG_EXAMPLE_VIDEO_READONLY + ) + target_sources(${TARGET} PUBLIC + ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/clock_config.c + ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/pin_mux.c + ) +endfunction() diff --git a/hw/bsp/mcx/boards/frdm_mcxa156/board.h b/hw/bsp/mcx/boards/frdm_mcxa156/board.h new file mode 100644 index 000000000..6c19797c6 --- /dev/null +++ b/hw/bsp/mcx/boards/frdm_mcxa156/board.h @@ -0,0 +1,69 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2021, Ha Thach (tinyusb.org) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * This file is part of the TinyUSB stack. + */ + +/* metadata: + name: Freedom MCXA156 + url: https://www.nxp.com/design/design-center/development-boards-and-designs/FRDM-MCXA156 +*/ + +#ifndef BOARD_H_ +#define BOARD_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +// LED +#define LED_GPIO GPIO3 +#define LED_CLK kCLOCK_GateGPIO3 +#define LED_PIN 12 // red +#define LED_STATE_ON 0 + +// ISP button +#define BUTTON_GPIO GPIO0 +#define BUTTON_CLK kCLOCK_GateGPIO0 +#define BUTTON_PIN 6 //SW3 +#define BUTTON_STATE_ACTIVE 0 + +// UART +#define UART_DEV LPUART0 + +static inline void board_uart_init_clock(void) { + /* attach 12 MHz clock to LPUART0 (debug console) */ + CLOCK_SetClockDiv(kCLOCK_DivLPUART0, 1u); + CLOCK_AttachClk(kFRO12M_to_LPUART0); + + RESET_PeripheralReset(kLPUART0_RST_SHIFT_RSTn); +} + +// XTAL +#define XTAL0_CLK_HZ (24 * 1000 * 1000U) + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/hw/bsp/mcx/boards/frdm_mcxa156/board.mk b/hw/bsp/mcx/boards/frdm_mcxa156/board.mk new file mode 100644 index 000000000..d4a59b32a --- /dev/null +++ b/hw/bsp/mcx/boards/frdm_mcxa156/board.mk @@ -0,0 +1,14 @@ +MCU_VARIANT = MCXA156 +MCU_CORE = MCXA156 +PORT = 0 + +CPU_CORE = cortex-m33-nodsp-nofp +CFLAGS += \ + -DCPU_MCXA156VLH \ + -DCFG_TUSB_MCU=OPT_MCU_MCXA15 \ + +JLINK_DEVICE = MCXA156 +PYOCD_TARGET = MCXA156 + +# flash using pyocd +flash: flash-jlink diff --git a/hw/bsp/mcx/boards/frdm_mcxa156/clock_config.c b/hw/bsp/mcx/boards/frdm_mcxa156/clock_config.c new file mode 100644 index 000000000..f549af243 --- /dev/null +++ b/hw/bsp/mcx/boards/frdm_mcxa156/clock_config.c @@ -0,0 +1,482 @@ +/* + * Copyright 2024 NXP + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/*********************************************************************************************************************** + * This file was generated by the MCUXpresso Config Tools. Any manual edits made to this file + * will be overwritten if the respective MCUXpresso Config Tools is used to update this file. + **********************************************************************************************************************/ +/* + * How to setup clock using clock driver functions: + * + * 1. Setup clock sources. + * + * 2. Set up wait states of the flash. + * + * 3. Set up all dividers. + * + * 4. Set up all selectors to provide selected clocks. + * + */ + +/* clang-format off */ +/* TEXT BELOW IS USED AS SETTING FOR TOOLS ************************************* +!!GlobalInfo +product: Clocks v13.0 +processor: MCXA156 +package_id: MCXA156VLL +mcu_data: ksdk2_0 +processor_version: 0.15.0 + * BE CAREFUL MODIFYING THIS COMMENT - IT IS YAML SETTINGS FOR TOOLS **********/ +/* clang-format on */ + +#include "fsl_clock.h" +#include "clock_config.h" +#include "fsl_spc.h" + +/******************************************************************************* + * Definitions + ******************************************************************************/ + +/******************************************************************************* + * Variables + ******************************************************************************/ +/* System clock frequency. */ +//extern uint32_t SystemCoreClock; + +/******************************************************************************* + ************************ BOARD_InitBootClocks function ************************ + ******************************************************************************/ +void BOARD_InitBootClocks(void) +{ + BOARD_BootClockFRO96M(); +} + +/******************************************************************************* + ******************** Configuration BOARD_BootClockFRO12M ********************** + ******************************************************************************/ +/* clang-format off */ +/* TEXT BELOW IS USED AS SETTING FOR TOOLS ************************************* +!!Configuration +name: BOARD_BootClockFRO12M +outputs: +- {id: CLK_1M_clock.outFreq, value: 1 MHz} +- {id: CPU_clock.outFreq, value: 12 MHz} +- {id: FRO_12M_clock.outFreq, value: 12 MHz} +- {id: MAIN_clock.outFreq, value: 12 MHz} +- {id: Slow_clock.outFreq, value: 3 MHz} +- {id: System_clock.outFreq, value: 12 MHz} +- {id: UTICK_clock.outFreq, value: 1 MHz} +settings: +- {id: SCGMode, value: SIRC} +- {id: FRO_HF_PERIPHERALS_EN_CFG, value: Disabled} +- {id: MRCC.FREQMEREFCLKSEL.sel, value: MRCC.aoi0_out0} +- {id: MRCC.FREQMETARGETCLKSEL.sel, value: MRCC.aoi0_out0} +- {id: MRCC.OSTIMERCLKSEL.sel, value: VBAT.CLK16K_1} +- {id: SCG.SCSSEL.sel, value: SCG.SIRC} +- {id: SCG_FIRCCSR_FIRCEN_CFG, value: Disabled} + * BE CAREFUL MODIFYING THIS COMMENT - IT IS YAML SETTINGS FOR TOOLS **********/ +/* clang-format on */ + +/******************************************************************************* + * Variables for BOARD_BootClockFRO12M configuration + ******************************************************************************/ +/******************************************************************************* + * Code for BOARD_BootClockFRO12M configuration + ******************************************************************************/ +void BOARD_BootClockFRO12M(void) +{ + uint32_t coreFreq; + spc_active_mode_core_ldo_option_t ldoOption; + spc_sram_voltage_config_t sramOption; + + /* Get the CPU Core frequency */ + coreFreq = CLOCK_GetCoreSysClkFreq(); + + /* The flow of increasing voltage and frequency */ + if (coreFreq <= BOARD_BOOTCLOCKFRO12M_CORE_CLOCK) { + /* Set the LDO_CORE VDD regulator level */ + ldoOption.CoreLDOVoltage = kSPC_CoreLDO_MidDriveVoltage; + ldoOption.CoreLDODriveStrength = kSPC_CoreLDO_NormalDriveStrength; + (void)SPC_SetActiveModeCoreLDORegulatorConfig(SPC0, &ldoOption); + /* Configure Flash to support different voltage level and frequency */ + FMU0->FCTRL = (FMU0->FCTRL & ~((uint32_t)FMU_FCTRL_RWSC_MASK)) | (FMU_FCTRL_RWSC(0x0U)); + /* Specifies the operating voltage for the SRAM's read/write timing margin */ + sramOption.operateVoltage = kSPC_sramOperateAt1P0V; + sramOption.requestVoltageUpdate = true; + (void)SPC_SetSRAMOperateVoltage(SPC0, &sramOption); + } + + CLOCK_SetupFRO12MClocking(); /*!< Setup FRO12M clock */ + + CLOCK_AttachClk(kFRO12M_to_MAIN_CLK); /* !< Switch MAIN_CLK to FRO12M */ + + /* The flow of decreasing voltage and frequency */ + if (coreFreq > BOARD_BOOTCLOCKFRO12M_CORE_CLOCK) { + /* Configure Flash to support different voltage level and frequency */ + FMU0->FCTRL = (FMU0->FCTRL & ~((uint32_t)FMU_FCTRL_RWSC_MASK)) | (FMU_FCTRL_RWSC(0x0U)); + /* Specifies the operating voltage for the SRAM's read/write timing margin */ + sramOption.operateVoltage = kSPC_sramOperateAt1P0V; + sramOption.requestVoltageUpdate = true; + (void)SPC_SetSRAMOperateVoltage(SPC0, &sramOption); + /* Set the LDO_CORE VDD regulator level */ + ldoOption.CoreLDOVoltage = kSPC_CoreLDO_MidDriveVoltage; + ldoOption.CoreLDODriveStrength = kSPC_CoreLDO_NormalDriveStrength; + (void)SPC_SetActiveModeCoreLDORegulatorConfig(SPC0, &ldoOption); + } + + /*!< Set up clock selectors - Attach clocks to the peripheries */ + + /*!< Set up dividers */ + CLOCK_SetClockDiv(kCLOCK_DivAHBCLK, 1U); /* !< Set AHBCLKDIV divider to value 1 */ + + /* Set SystemCoreClock variable */ + SystemCoreClock = BOARD_BOOTCLOCKFRO12M_CORE_CLOCK; +} +/******************************************************************************* + ******************** Configuration BOARD_BootClockFRO24M ********************** + ******************************************************************************/ +/* clang-format off */ +/* TEXT BELOW IS USED AS SETTING FOR TOOLS ************************************* +!!Configuration +name: BOARD_BootClockFRO24M +outputs: +- {id: CLK_1M_clock.outFreq, value: 1 MHz} +- {id: CLK_48M_clock.outFreq, value: 48 MHz} +- {id: CPU_clock.outFreq, value: 24 MHz} +- {id: FRO_12M_clock.outFreq, value: 12 MHz} +- {id: FRO_HF_DIV_clock.outFreq, value: 48 MHz} +- {id: FRO_HF_clock.outFreq, value: 48 MHz} +- {id: MAIN_clock.outFreq, value: 48 MHz} +- {id: Slow_clock.outFreq, value: 6 MHz} +- {id: System_clock.outFreq, value: 24 MHz} +- {id: UTICK_clock.outFreq, value: 1 MHz} +settings: +- {id: MRCC.FREQMEREFCLKSEL.sel, value: MRCC.aoi0_out0} +- {id: MRCC.FREQMETARGETCLKSEL.sel, value: MRCC.aoi0_out0} +- {id: MRCC.OSTIMERCLKSEL.sel, value: VBAT.CLK16K_1} +- {id: SYSCON.AHBCLKDIV.scale, value: '2', locked: true} + * BE CAREFUL MODIFYING THIS COMMENT - IT IS YAML SETTINGS FOR TOOLS **********/ +/* clang-format on */ + +/******************************************************************************* + * Variables for BOARD_BootClockFRO24M configuration + ******************************************************************************/ +/******************************************************************************* + * Code for BOARD_BootClockFRO24M configuration + ******************************************************************************/ +void BOARD_BootClockFRO24M(void) +{ + uint32_t coreFreq; + spc_active_mode_core_ldo_option_t ldoOption; + spc_sram_voltage_config_t sramOption; + + /* Get the CPU Core frequency */ + coreFreq = CLOCK_GetCoreSysClkFreq(); + + /* The flow of increasing voltage and frequency */ + if (coreFreq <= BOARD_BOOTCLOCKFRO24M_CORE_CLOCK) { + /* Set the LDO_CORE VDD regulator level */ + ldoOption.CoreLDOVoltage = kSPC_CoreLDO_MidDriveVoltage; + ldoOption.CoreLDODriveStrength = kSPC_CoreLDO_NormalDriveStrength; + (void)SPC_SetActiveModeCoreLDORegulatorConfig(SPC0, &ldoOption); + /* Configure Flash to support different voltage level and frequency */ + FMU0->FCTRL = (FMU0->FCTRL & ~((uint32_t)FMU_FCTRL_RWSC_MASK)) | (FMU_FCTRL_RWSC(0x0U)); + /* Specifies the operating voltage for the SRAM's read/write timing margin */ + sramOption.operateVoltage = kSPC_sramOperateAt1P0V; + sramOption.requestVoltageUpdate = true; + (void)SPC_SetSRAMOperateVoltage(SPC0, &sramOption); + } + + CLOCK_SetupFROHFClocking(48000000U); /*!< Enable FRO HF(48MHz) output */ + + CLOCK_SetupFRO12MClocking(); /*!< Setup FRO12M clock */ + + CLOCK_AttachClk(kFRO_HF_to_MAIN_CLK); /* !< Switch MAIN_CLK to FRO_HF */ + + /* The flow of decreasing voltage and frequency */ + if (coreFreq > BOARD_BOOTCLOCKFRO24M_CORE_CLOCK) { + /* Configure Flash to support different voltage level and frequency */ + FMU0->FCTRL = (FMU0->FCTRL & ~((uint32_t)FMU_FCTRL_RWSC_MASK)) | (FMU_FCTRL_RWSC(0x0U)); + /* Specifies the operating voltage for the SRAM's read/write timing margin */ + sramOption.operateVoltage = kSPC_sramOperateAt1P0V; + sramOption.requestVoltageUpdate = true; + (void)SPC_SetSRAMOperateVoltage(SPC0, &sramOption); + /* Set the LDO_CORE VDD regulator level */ + ldoOption.CoreLDOVoltage = kSPC_CoreLDO_MidDriveVoltage; + ldoOption.CoreLDODriveStrength = kSPC_CoreLDO_NormalDriveStrength; + (void)SPC_SetActiveModeCoreLDORegulatorConfig(SPC0, &ldoOption); + } + + /*!< Set up clock selectors - Attach clocks to the peripheries */ + + /*!< Set up dividers */ + CLOCK_SetClockDiv(kCLOCK_DivAHBCLK, 2U); /* !< Set AHBCLKDIV divider to value 2 */ + CLOCK_SetClockDiv(kCLOCK_DivFRO_HF_DIV, 1U); /* !< Set FROHFDIV divider to value 1 */ + + /* Set SystemCoreClock variable */ + SystemCoreClock = BOARD_BOOTCLOCKFRO24M_CORE_CLOCK; +} +/******************************************************************************* + ******************** Configuration BOARD_BootClockFRO48M ********************** + ******************************************************************************/ +/* clang-format off */ +/* TEXT BELOW IS USED AS SETTING FOR TOOLS ************************************* +!!Configuration +name: BOARD_BootClockFRO48M +outputs: +- {id: CLK_1M_clock.outFreq, value: 1 MHz} +- {id: CLK_48M_clock.outFreq, value: 48 MHz} +- {id: CPU_clock.outFreq, value: 48 MHz} +- {id: FRO_12M_clock.outFreq, value: 12 MHz} +- {id: FRO_HF_DIV_clock.outFreq, value: 48 MHz} +- {id: FRO_HF_clock.outFreq, value: 48 MHz} +- {id: MAIN_clock.outFreq, value: 48 MHz} +- {id: Slow_clock.outFreq, value: 12 MHz} +- {id: System_clock.outFreq, value: 48 MHz} +- {id: UTICK_clock.outFreq, value: 1 MHz} +settings: +- {id: MRCC.FREQMEREFCLKSEL.sel, value: MRCC.aoi0_out0} +- {id: MRCC.FREQMETARGETCLKSEL.sel, value: MRCC.aoi0_out0} +- {id: MRCC.OSTIMERCLKSEL.sel, value: VBAT.CLK16K_1} + * BE CAREFUL MODIFYING THIS COMMENT - IT IS YAML SETTINGS FOR TOOLS **********/ +/* clang-format on */ + +/******************************************************************************* + * Variables for BOARD_BootClockFRO48M configuration + ******************************************************************************/ +/******************************************************************************* + * Code for BOARD_BootClockFRO48M configuration + ******************************************************************************/ +void BOARD_BootClockFRO48M(void) +{ + uint32_t coreFreq; + spc_active_mode_core_ldo_option_t ldoOption; + spc_sram_voltage_config_t sramOption; + + /* Get the CPU Core frequency */ + coreFreq = CLOCK_GetCoreSysClkFreq(); + + /* The flow of increasing voltage and frequency */ + if (coreFreq <= BOARD_BOOTCLOCKFRO48M_CORE_CLOCK) { + /* Set the LDO_CORE VDD regulator level */ + ldoOption.CoreLDOVoltage = kSPC_CoreLDO_MidDriveVoltage; + ldoOption.CoreLDODriveStrength = kSPC_CoreLDO_NormalDriveStrength; + (void)SPC_SetActiveModeCoreLDORegulatorConfig(SPC0, &ldoOption); + /* Configure Flash to support different voltage level and frequency */ + FMU0->FCTRL = (FMU0->FCTRL & ~((uint32_t)FMU_FCTRL_RWSC_MASK)) | (FMU_FCTRL_RWSC(0x1U)); + /* Specifies the operating voltage for the SRAM's read/write timing margin */ + sramOption.operateVoltage = kSPC_sramOperateAt1P0V; + sramOption.requestVoltageUpdate = true; + (void)SPC_SetSRAMOperateVoltage(SPC0, &sramOption); + } + + CLOCK_SetupFROHFClocking(48000000U); /*!< Enable FRO HF(48MHz) output */ + + CLOCK_SetupFRO12MClocking(); /*!< Setup FRO12M clock */ + + CLOCK_AttachClk(kFRO_HF_to_MAIN_CLK); /* !< Switch MAIN_CLK to FRO_HF */ + + /* The flow of decreasing voltage and frequency */ + if (coreFreq > BOARD_BOOTCLOCKFRO48M_CORE_CLOCK) { + /* Configure Flash to support different voltage level and frequency */ + FMU0->FCTRL = (FMU0->FCTRL & ~((uint32_t)FMU_FCTRL_RWSC_MASK)) | (FMU_FCTRL_RWSC(0x1U)); + /* Specifies the operating voltage for the SRAM's read/write timing margin */ + sramOption.operateVoltage = kSPC_sramOperateAt1P0V; + sramOption.requestVoltageUpdate = true; + (void)SPC_SetSRAMOperateVoltage(SPC0, &sramOption); + /* Set the LDO_CORE VDD regulator level */ + ldoOption.CoreLDOVoltage = kSPC_CoreLDO_MidDriveVoltage; + ldoOption.CoreLDODriveStrength = kSPC_CoreLDO_NormalDriveStrength; + (void)SPC_SetActiveModeCoreLDORegulatorConfig(SPC0, &ldoOption); + } + + /*!< Set up clock selectors - Attach clocks to the peripheries */ + + /*!< Set up dividers */ + CLOCK_SetClockDiv(kCLOCK_DivAHBCLK, 1U); /* !< Set AHBCLKDIV divider to value 1 */ + CLOCK_SetClockDiv(kCLOCK_DivFRO_HF_DIV, 1U); /* !< Set FROHFDIV divider to value 1 */ + + /* Set SystemCoreClock variable */ + SystemCoreClock = BOARD_BOOTCLOCKFRO48M_CORE_CLOCK; +} +/******************************************************************************* + ******************** Configuration BOARD_BootClockFRO64M ********************** + ******************************************************************************/ +/* clang-format off */ +/* TEXT BELOW IS USED AS SETTING FOR TOOLS ************************************* +!!Configuration +name: BOARD_BootClockFRO64M +outputs: +- {id: CLK_1M_clock.outFreq, value: 1 MHz} +- {id: CLK_48M_clock.outFreq, value: 48 MHz} +- {id: CPU_clock.outFreq, value: 64 MHz} +- {id: FRO_12M_clock.outFreq, value: 12 MHz} +- {id: FRO_HF_DIV_clock.outFreq, value: 64 MHz} +- {id: FRO_HF_clock.outFreq, value: 64 MHz} +- {id: MAIN_clock.outFreq, value: 64 MHz} +- {id: Slow_clock.outFreq, value: 16 MHz} +- {id: System_clock.outFreq, value: 64 MHz} +- {id: UTICK_clock.outFreq, value: 1 MHz} +settings: +- {id: VDD_CORE, value: voltage_1v1} +- {id: MRCC.FREQMEREFCLKSEL.sel, value: MRCC.aoi0_out0} +- {id: MRCC.FREQMETARGETCLKSEL.sel, value: MRCC.aoi0_out0} +- {id: MRCC.FROHFDIV.scale, value: '1', locked: true} +- {id: MRCC.OSTIMERCLKSEL.sel, value: VBAT.CLK16K_1} +- {id: SYSCON.AHBCLKDIV.scale, value: '1', locked: true} +sources: +- {id: SCG.FIRC.outFreq, value: 64 MHz} + * BE CAREFUL MODIFYING THIS COMMENT - IT IS YAML SETTINGS FOR TOOLS **********/ +/* clang-format on */ + +/******************************************************************************* + * Variables for BOARD_BootClockFRO64M configuration + ******************************************************************************/ +/******************************************************************************* + * Code for BOARD_BootClockFRO64M configuration + ******************************************************************************/ +void BOARD_BootClockFRO64M(void) +{ + uint32_t coreFreq; + spc_active_mode_core_ldo_option_t ldoOption; + spc_sram_voltage_config_t sramOption; + + /* Get the CPU Core frequency */ + coreFreq = CLOCK_GetCoreSysClkFreq(); + + /* The flow of increasing voltage and frequency */ + if (coreFreq <= BOARD_BOOTCLOCKFRO64M_CORE_CLOCK) { + /* Set the LDO_CORE VDD regulator level */ + ldoOption.CoreLDOVoltage = kSPC_CoreLDO_NormalVoltage; + ldoOption.CoreLDODriveStrength = kSPC_CoreLDO_NormalDriveStrength; + (void)SPC_SetActiveModeCoreLDORegulatorConfig(SPC0, &ldoOption); + /* Configure Flash to support different voltage level and frequency */ + FMU0->FCTRL = (FMU0->FCTRL & ~((uint32_t)FMU_FCTRL_RWSC_MASK)) | (FMU_FCTRL_RWSC(0x1U)); + /* Specifies the operating voltage for the SRAM's read/write timing margin */ + sramOption.operateVoltage = kSPC_sramOperateAt1P1V; + sramOption.requestVoltageUpdate = true; + (void)SPC_SetSRAMOperateVoltage(SPC0, &sramOption); + } + + CLOCK_SetupFROHFClocking(64000000U); /*!< Enable FRO HF(64MHz) output */ + + CLOCK_SetupFRO12MClocking(); /*!< Setup FRO12M clock */ + + CLOCK_AttachClk(kFRO_HF_to_MAIN_CLK); /* !< Switch MAIN_CLK to FRO_HF */ + + /* The flow of decreasing voltage and frequency */ + if (coreFreq > BOARD_BOOTCLOCKFRO64M_CORE_CLOCK) { + /* Configure Flash to support different voltage level and frequency */ + FMU0->FCTRL = (FMU0->FCTRL & ~((uint32_t)FMU_FCTRL_RWSC_MASK)) | (FMU_FCTRL_RWSC(0x1U)); + /* Specifies the operating voltage for the SRAM's read/write timing margin */ + sramOption.operateVoltage = kSPC_sramOperateAt1P1V; + sramOption.requestVoltageUpdate = true; + (void)SPC_SetSRAMOperateVoltage(SPC0, &sramOption); + /* Set the LDO_CORE VDD regulator level */ + ldoOption.CoreLDOVoltage = kSPC_CoreLDO_NormalVoltage; + ldoOption.CoreLDODriveStrength = kSPC_CoreLDO_NormalDriveStrength; + (void)SPC_SetActiveModeCoreLDORegulatorConfig(SPC0, &ldoOption); + } + + /*!< Set up clock selectors - Attach clocks to the peripheries */ + + /*!< Set up dividers */ + CLOCK_SetClockDiv(kCLOCK_DivAHBCLK, 1U); /* !< Set AHBCLKDIV divider to value 1 */ + CLOCK_SetClockDiv(kCLOCK_DivFRO_HF_DIV, 1U); /* !< Set FROHFDIV divider to value 1 */ + + /* Set SystemCoreClock variable */ + SystemCoreClock = BOARD_BOOTCLOCKFRO64M_CORE_CLOCK; +} +/******************************************************************************* + ******************** Configuration BOARD_BootClockFRO96M ********************** + ******************************************************************************/ +/* clang-format off */ +/* TEXT BELOW IS USED AS SETTING FOR TOOLS ************************************* +!!Configuration +name: BOARD_BootClockFRO96M +called_from_default_init: true +outputs: +- {id: CLK_1M_clock.outFreq, value: 1 MHz} +- {id: CLK_48M_clock.outFreq, value: 48 MHz} +- {id: CPU_clock.outFreq, value: 96 MHz} +- {id: FRO_12M_clock.outFreq, value: 12 MHz} +- {id: FRO_HF_DIV_clock.outFreq, value: 96 MHz} +- {id: FRO_HF_clock.outFreq, value: 96 MHz} +- {id: MAIN_clock.outFreq, value: 96 MHz} +- {id: Slow_clock.outFreq, value: 24 MHz} +- {id: System_clock.outFreq, value: 96 MHz} +- {id: UTICK_clock.outFreq, value: 1 MHz} +settings: +- {id: VDD_CORE, value: voltage_1v1} +- {id: CLKOUTDIV_HALT, value: Enable} +- {id: MRCC.FREQMEREFCLKSEL.sel, value: MRCC.aoi0_out0} +- {id: MRCC.FREQMETARGETCLKSEL.sel, value: MRCC.aoi0_out0} +- {id: MRCC.FROHFDIV.scale, value: '1', locked: true} +- {id: MRCC.OSTIMERCLKSEL.sel, value: VBAT.CLK16K_1} +- {id: SYSCON.AHBCLKDIV.scale, value: '1', locked: true} +sources: +- {id: SCG.FIRC.outFreq, value: 96 MHz} + * BE CAREFUL MODIFYING THIS COMMENT - IT IS YAML SETTINGS FOR TOOLS **********/ +/* clang-format on */ + +/******************************************************************************* + * Variables for BOARD_BootClockFRO96M configuration + ******************************************************************************/ +/******************************************************************************* + * Code for BOARD_BootClockFRO96M configuration + ******************************************************************************/ +void BOARD_BootClockFRO96M(void) +{ + uint32_t coreFreq; + spc_active_mode_core_ldo_option_t ldoOption; + spc_sram_voltage_config_t sramOption; + + /* Get the CPU Core frequency */ + coreFreq = CLOCK_GetCoreSysClkFreq(); + + /* The flow of increasing voltage and frequency */ + if (coreFreq <= BOARD_BOOTCLOCKFRO96M_CORE_CLOCK) { + /* Set the LDO_CORE VDD regulator level */ + ldoOption.CoreLDOVoltage = kSPC_CoreLDO_NormalVoltage; + ldoOption.CoreLDODriveStrength = kSPC_CoreLDO_NormalDriveStrength; + (void)SPC_SetActiveModeCoreLDORegulatorConfig(SPC0, &ldoOption); + /* Configure Flash to support different voltage level and frequency */ + FMU0->FCTRL = (FMU0->FCTRL & ~((uint32_t)FMU_FCTRL_RWSC_MASK)) | (FMU_FCTRL_RWSC(0x2U)); + /* Specifies the operating voltage for the SRAM's read/write timing margin */ + sramOption.operateVoltage = kSPC_sramOperateAt1P1V; + sramOption.requestVoltageUpdate = true; + (void)SPC_SetSRAMOperateVoltage(SPC0, &sramOption); + } + + CLOCK_SetupFROHFClocking(96000000U); /*!< Enable FRO HF(96MHz) output */ + + CLOCK_SetupFRO12MClocking(); /*!< Setup FRO12M clock */ + + CLOCK_AttachClk(kFRO_HF_to_MAIN_CLK); /* !< Switch MAIN_CLK to FRO_HF */ + + /* The flow of decreasing voltage and frequency */ + if (coreFreq > BOARD_BOOTCLOCKFRO96M_CORE_CLOCK) { + /* Configure Flash to support different voltage level and frequency */ + FMU0->FCTRL = (FMU0->FCTRL & ~((uint32_t)FMU_FCTRL_RWSC_MASK)) | (FMU_FCTRL_RWSC(0x2U)); + /* Specifies the operating voltage for the SRAM's read/write timing margin */ + sramOption.operateVoltage = kSPC_sramOperateAt1P1V; + sramOption.requestVoltageUpdate = true; + (void)SPC_SetSRAMOperateVoltage(SPC0, &sramOption); + /* Set the LDO_CORE VDD regulator level */ + ldoOption.CoreLDOVoltage = kSPC_CoreLDO_NormalVoltage; + ldoOption.CoreLDODriveStrength = kSPC_CoreLDO_NormalDriveStrength; + (void)SPC_SetActiveModeCoreLDORegulatorConfig(SPC0, &ldoOption); + } + + /*!< Set up clock selectors - Attach clocks to the peripheries */ + + /*!< Set up dividers */ + CLOCK_SetClockDiv(kCLOCK_DivAHBCLK, 1U); /* !< Set AHBCLKDIV divider to value 1 */ + CLOCK_SetClockDiv(kCLOCK_DivFRO_HF_DIV, 1U); /* !< Set FROHFDIV divider to value 1 */ + + /* Set SystemCoreClock variable */ + SystemCoreClock = BOARD_BOOTCLOCKFRO96M_CORE_CLOCK; +} diff --git a/hw/bsp/mcx/boards/frdm_mcxa156/clock_config.h b/hw/bsp/mcx/boards/frdm_mcxa156/clock_config.h new file mode 100644 index 000000000..3f5dfefda --- /dev/null +++ b/hw/bsp/mcx/boards/frdm_mcxa156/clock_config.h @@ -0,0 +1,169 @@ +/* + * Copyright 2024 NXP + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/*********************************************************************************************************************** + * This file was generated by the MCUXpresso Config Tools. Any manual edits made to this file + * will be overwritten if the respective MCUXpresso Config Tools is used to update this file. + **********************************************************************************************************************/ + +#ifndef _CLOCK_CONFIG_H_ +#define _CLOCK_CONFIG_H_ + +#include "fsl_common.h" + +/******************************************************************************* + * Definitions + ******************************************************************************/ + +/******************************************************************************* + ************************ BOARD_InitBootClocks function ************************ + ******************************************************************************/ + +#if defined(__cplusplus) +extern "C" { +#endif /* __cplusplus*/ + +/*! + * @brief This function executes default configuration of clocks. + * + */ +void BOARD_InitBootClocks(void); + +#if defined(__cplusplus) +} +#endif /* __cplusplus*/ + +/******************************************************************************* + ******************** Configuration BOARD_BootClockFRO12M ********************** + ******************************************************************************/ +/******************************************************************************* + * Definitions for BOARD_BootClockFRO12M configuration + ******************************************************************************/ +#define BOARD_BOOTCLOCKFRO12M_CORE_CLOCK 12000000U /*!< Core clock frequency: 12000000Hz */ + + +/******************************************************************************* + * API for BOARD_BootClockFRO12M configuration + ******************************************************************************/ +#if defined(__cplusplus) +extern "C" { +#endif /* __cplusplus*/ + +/*! + * @brief This function executes configuration of clocks. + * + */ +void BOARD_BootClockFRO12M(void); + +#if defined(__cplusplus) +} +#endif /* __cplusplus*/ + +/******************************************************************************* + ******************** Configuration BOARD_BootClockFRO24M ********************** + ******************************************************************************/ +/******************************************************************************* + * Definitions for BOARD_BootClockFRO24M configuration + ******************************************************************************/ +#define BOARD_BOOTCLOCKFRO24M_CORE_CLOCK 24000000U /*!< Core clock frequency: 24000000Hz */ + + +/******************************************************************************* + * API for BOARD_BootClockFRO24M configuration + ******************************************************************************/ +#if defined(__cplusplus) +extern "C" { +#endif /* __cplusplus*/ + +/*! + * @brief This function executes configuration of clocks. + * + */ +void BOARD_BootClockFRO24M(void); + +#if defined(__cplusplus) +} +#endif /* __cplusplus*/ + +/******************************************************************************* + ******************** Configuration BOARD_BootClockFRO48M ********************** + ******************************************************************************/ +/******************************************************************************* + * Definitions for BOARD_BootClockFRO48M configuration + ******************************************************************************/ +#define BOARD_BOOTCLOCKFRO48M_CORE_CLOCK 48000000U /*!< Core clock frequency: 48000000Hz */ + + +/******************************************************************************* + * API for BOARD_BootClockFRO48M configuration + ******************************************************************************/ +#if defined(__cplusplus) +extern "C" { +#endif /* __cplusplus*/ + +/*! + * @brief This function executes configuration of clocks. + * + */ +void BOARD_BootClockFRO48M(void); + +#if defined(__cplusplus) +} +#endif /* __cplusplus*/ + +/******************************************************************************* + ******************** Configuration BOARD_BootClockFRO64M ********************** + ******************************************************************************/ +/******************************************************************************* + * Definitions for BOARD_BootClockFRO64M configuration + ******************************************************************************/ +#define BOARD_BOOTCLOCKFRO64M_CORE_CLOCK 64000000U /*!< Core clock frequency: 64000000Hz */ + + +/******************************************************************************* + * API for BOARD_BootClockFRO64M configuration + ******************************************************************************/ +#if defined(__cplusplus) +extern "C" { +#endif /* __cplusplus*/ + +/*! + * @brief This function executes configuration of clocks. + * + */ +void BOARD_BootClockFRO64M(void); + +#if defined(__cplusplus) +} +#endif /* __cplusplus*/ + +/******************************************************************************* + ******************** Configuration BOARD_BootClockFRO96M ********************** + ******************************************************************************/ +/******************************************************************************* + * Definitions for BOARD_BootClockFRO96M configuration + ******************************************************************************/ +#define BOARD_BOOTCLOCKFRO96M_CORE_CLOCK 96000000U /*!< Core clock frequency: 96000000Hz */ + + +/******************************************************************************* + * API for BOARD_BootClockFRO96M configuration + ******************************************************************************/ +#if defined(__cplusplus) +extern "C" { +#endif /* __cplusplus*/ + +/*! + * @brief This function executes configuration of clocks. + * + */ +void BOARD_BootClockFRO96M(void); + +#if defined(__cplusplus) +} +#endif /* __cplusplus*/ + +#endif /* _CLOCK_CONFIG_H_ */ diff --git a/hw/bsp/mcx/boards/frdm_mcxa156/pin_mux.c b/hw/bsp/mcx/boards/frdm_mcxa156/pin_mux.c new file mode 100644 index 000000000..de35103a6 --- /dev/null +++ b/hw/bsp/mcx/boards/frdm_mcxa156/pin_mux.c @@ -0,0 +1,144 @@ +/* + * Copyright 2024 NXP + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/*********************************************************************************************************************** + * This file was generated by the MCUXpresso Config Tools. Any manual edits made to this file + * will be overwritten if the respective MCUXpresso Config Tools is used to update this file. + **********************************************************************************************************************/ + +/* clang-format off */ +/* + * TEXT BELOW IS USED AS SETTING FOR TOOLS ************************************* +!!GlobalInfo +product: Pins v15.0 +processor: MCXA156 +package_id: MCXA156VLL +mcu_data: ksdk2_0 +processor_version: 0.15.0 + * BE CAREFUL MODIFYING THIS COMMENT - IT IS YAML SETTINGS FOR TOOLS *********** + */ +/* clang-format on */ + +#include "fsl_common.h" +#include "fsl_port.h" +#include "pin_mux.h" + +/* FUNCTION ************************************************************************************************************ + * + * Function Name : BOARD_InitBootPins + * Description : Calls initialization functions. + * + * END ****************************************************************************************************************/ +void BOARD_InitBootPins(void) +{ + BOARD_InitPins(); +} + +/* clang-format off */ +/* + * TEXT BELOW IS USED AS SETTING FOR TOOLS ************************************* +BOARD_InitPins: +- options: {callFromInitBoot: 'true', coreID: cm33_core0, enableClock: 'true'} +- pin_list: + - {pin_num: '78', peripheral: LPUART0, signal: RX, pin_signal: P0_2/TDO/SWO/LPUART0_RXD/LPSPI0_SCK/CT0_MAT0/UTICK_CAP0/FLEXIO0_D2, slew_rate: fast, open_drain: disable, + drive_strength: low, pull_select: up, pull_enable: enable, input_buffer: enable, invert_input: normal} + - {pin_num: '79', peripheral: LPUART0, signal: TX, pin_signal: P0_3/TDI/LPUART0_TXD/LPSPI0_SDO/CT0_MAT1/UTICK_CAP1/FLEXIO0_D3/CMP0_OUT, slew_rate: fast, open_drain: disable, + drive_strength: low, pull_select: up, pull_enable: enable, input_buffer: enable, invert_input: normal} + * BE CAREFUL MODIFYING THIS COMMENT - IT IS YAML SETTINGS FOR TOOLS *********** + */ +/* clang-format on */ + +/* FUNCTION ************************************************************************************************************ + * + * Function Name : BOARD_InitPins + * Description : Configures pin routing and optionally pin electrical features. + * + * END ****************************************************************************************************************/ +void BOARD_InitPins(void) +{ + + RESET_PeripheralReset(kLPUART0_RST_SHIFT_RSTn); + CLOCK_SetClockDiv(kCLOCK_DivLPUART0, 1u); + CLOCK_AttachClk(kFRO12M_to_LPUART0); + + /* GPIO3: Peripheral clock is enabled */ + CLOCK_EnableClock(kCLOCK_GateGPIO3); + /* PORT3: Peripheral clock is enabled */ + CLOCK_EnableClock(kCLOCK_GatePORT3); + /* GPIO3 peripheral is released from reset */ + RESET_ReleasePeripheralReset(kGPIO3_RST_SHIFT_RSTn); + /* PORT3 peripheral is released from reset */ + RESET_ReleasePeripheralReset(kPORT3_RST_SHIFT_RSTn); + + /* GPIO3: Peripheral clock is enabled */ + CLOCK_EnableClock(kCLOCK_GateGPIO0); + /* PORT3: Peripheral clock is enabled */ + CLOCK_EnableClock(kCLOCK_GatePORT0); + /* GPIO3 peripheral is released from reset */ + RESET_ReleasePeripheralReset(kGPIO0_RST_SHIFT_RSTn); + /* PORT3 peripheral is released from reset */ + RESET_ReleasePeripheralReset(kPORT0_RST_SHIFT_RSTn); + + /* PORT0: Peripheral clock is enabled */ + CLOCK_EnableClock(kCLOCK_GatePORT0); + /* LPUART0 peripheral is released from reset */ + RESET_ReleasePeripheralReset(kLPUART0_RST_SHIFT_RSTn); + /* PORT0 peripheral is released from reset */ + RESET_ReleasePeripheralReset(kPORT0_RST_SHIFT_RSTn); + + const port_pin_config_t port0_2_pin78_config = {/* Internal pull-up resistor is enabled */ + kPORT_PullUp, + /* Low internal pull resistor value is selected. */ + kPORT_LowPullResistor, + /* Fast slew rate is configured */ + kPORT_FastSlewRate, + /* Passive input filter is disabled */ + kPORT_PassiveFilterDisable, + /* Open drain output is disabled */ + kPORT_OpenDrainDisable, + /* Low drive strength is configured */ + kPORT_LowDriveStrength, + /* Normal drive strength is configured */ + kPORT_NormalDriveStrength, + /* Pin is configured as LPUART0_RXD */ + kPORT_MuxAlt2, + /* Digital input enabled */ + kPORT_InputBufferEnable, + /* Digital input is not inverted */ + kPORT_InputNormal, + /* Pin Control Register fields [15:0] are not locked */ + kPORT_UnlockRegister}; + /* PORT0_2 (pin 78) is configured as LPUART0_RXD */ + PORT_SetPinConfig(PORT0, 2U, &port0_2_pin78_config); + + const port_pin_config_t port0_3_pin79_config = {/* Internal pull-up resistor is enabled */ + kPORT_PullUp, + /* Low internal pull resistor value is selected. */ + kPORT_LowPullResistor, + /* Fast slew rate is configured */ + kPORT_FastSlewRate, + /* Passive input filter is disabled */ + kPORT_PassiveFilterDisable, + /* Open drain output is disabled */ + kPORT_OpenDrainDisable, + /* Low drive strength is configured */ + kPORT_LowDriveStrength, + /* Normal drive strength is configured */ + kPORT_NormalDriveStrength, + /* Pin is configured as LPUART0_TXD */ + kPORT_MuxAlt2, + /* Digital input enabled */ + kPORT_InputBufferEnable, + /* Digital input is not inverted */ + kPORT_InputNormal, + /* Pin Control Register fields [15:0] are not locked */ + kPORT_UnlockRegister}; + /* PORT0_3 (pin 79) is configured as LPUART0_TXD */ + PORT_SetPinConfig(PORT0, 3U, &port0_3_pin79_config); +} +/*********************************************************************************************************************** + * EOF + **********************************************************************************************************************/ diff --git a/hw/bsp/mcx/boards/frdm_mcxa156/pin_mux.h b/hw/bsp/mcx/boards/frdm_mcxa156/pin_mux.h new file mode 100644 index 000000000..fb7d1fc04 --- /dev/null +++ b/hw/bsp/mcx/boards/frdm_mcxa156/pin_mux.h @@ -0,0 +1,51 @@ +/* + * Copyright 2024 NXP + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/*********************************************************************************************************************** + * This file was generated by the MCUXpresso Config Tools. Any manual edits made to this file + * will be overwritten if the respective MCUXpresso Config Tools is used to update this file. + **********************************************************************************************************************/ + +#ifndef _PIN_MUX_H_ +#define _PIN_MUX_H_ + +/*! + * @addtogroup pin_mux + * @{ + */ + +/*********************************************************************************************************************** + * API + **********************************************************************************************************************/ + +#if defined(__cplusplus) +extern "C" { +#endif + +/*! + * @brief Calls initialization functions. + * + */ +void BOARD_InitBootPins(void); + +/*! + * @brief Configures pin routing and optionally pin electrical features. + * + */ +void BOARD_InitPins(void); + +#if defined(__cplusplus) +} +#endif + +/*! + * @} + */ +#endif /* _PIN_MUX_H_ */ + +/*********************************************************************************************************************** + * EOF + **********************************************************************************************************************/ diff --git a/hw/bsp/mcx/boards/frdm_mcxn947/board.h b/hw/bsp/mcx/boards/frdm_mcxn947/board.h index acb73363f..bb15620ef 100644 --- a/hw/bsp/mcx/boards/frdm_mcxn947/board.h +++ b/hw/bsp/mcx/boards/frdm_mcxn947/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Freedom MCXN947 + url: https://www.nxp.com/design/design-center/development-boards-and-designs/FRDM-MCXN947 +*/ + #ifndef BOARD_H_ #define BOARD_H_ @@ -44,17 +49,22 @@ #define BUTTON_STATE_ACTIVE 0 // UART -#define UART_DEV LPUART4 +#define UART_DEV LPUART4 +#define LP_FLEXCOMM_INST 4 + +#include "fsl_lpflexcomm.h" static inline void board_uart_init_clock(void) { + /* attach FRO 12M to FLEXCOMM4 */ + + LP_FLEXCOMM_Init(LP_FLEXCOMM_INST, LP_FLEXCOMM_PERIPH_LPUART); + CLOCK_SetClkDiv(kCLOCK_DivFlexcom4Clk, 1u); CLOCK_AttachClk(kFRO12M_to_FLEXCOMM4); RESET_ClearPeripheralReset(kFC4_RST_SHIFT_RSTn); -} -//#define UART_RX_PINMUX 0, 24, IOCON_PIO_DIG_FUNC1_EN -//#define UART_TX_PINMUX 0, 25, IOCON_PIO_DIG_FUNC1_EN +} // XTAL #define XTAL0_CLK_HZ (24 * 1000 * 1000U) diff --git a/hw/bsp/mcx/boards/mcxn947brk/board.h b/hw/bsp/mcx/boards/mcxn947brk/board.h index eae98bfa7..eef281787 100644 --- a/hw/bsp/mcx/boards/mcxn947brk/board.h +++ b/hw/bsp/mcx/boards/mcxn947brk/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: MCXN947 Breakout + url: n/a +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/mcx/drivers/spc/fsl_spc.c b/hw/bsp/mcx/drivers/spc/fsl_spc.c new file mode 100644 index 000000000..b16ca5fc5 --- /dev/null +++ b/hw/bsp/mcx/drivers/spc/fsl_spc.c @@ -0,0 +1,1680 @@ +/* + * Copyright 2022-2024 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include "fsl_spc.h" + +/* Component ID definition, used by tools. */ +#ifndef FSL_COMPONENT_ID +#define FSL_COMPONENT_ID "platform.drivers.mcx_spc" +#endif + +/* + * $Coverage Justification Reference$ + * + * $Justification spc_c_ref_1$ + * The SPC busy status flag is too short to get coverage data. + */ + +/******************************************************************************* + * Definitions + ******************************************************************************/ + +/******************************************************************************* + * Prototypes + ******************************************************************************/ + +/******************************************************************************* + * Variables + ******************************************************************************/ + +/******************************************************************************* + * Code + ******************************************************************************/ + +/*! + * brief Gets selected power domain's requested low power mode. + * + * param base SPC peripheral base address. + * param powerDomainId Power Domain Id, please refer to spc_power_domain_id_t. + * + * return The selected power domain's requested low power mode, please refer to spc_power_domain_low_power_mode_t. + */ +spc_power_domain_low_power_mode_t SPC_GetPowerDomainLowPowerMode(SPC_Type *base, spc_power_domain_id_t powerDomainId) +{ + assert((uint8_t)powerDomainId < SPC_PD_STATUS_COUNT); + + uint32_t val; + + val = ((base->PD_STATUS[(uint8_t)powerDomainId] & SPC_PD_STATUS_LP_MODE_MASK) >> SPC_PD_STATUS_LP_MODE_SHIFT); + return (spc_power_domain_low_power_mode_t)val; +} + +/*! + * brief Gets Isolation status for each power domains. + * + * This function gets the status which indicates whether certain + * peripheral and the IO pads are in a latched state as a result + * of having been in POWERDOWN mode. + * + * param base SPC peripheral base address. + * return Current isolation status for each power domains. + */ +uint8_t SPC_GetPeriphIOIsolationStatus(SPC_Type *base) +{ + uint32_t reg; + + reg = base->SC; + return (uint8_t)((reg & SPC_SC_ISO_CLR_MASK) >> SPC_SC_ISO_CLR_SHIFT); +} + +/*! + * brief Configs Low power request output pin. + * + * This function configs the low power request output pin + * + * param base SPC peripheral base address. + * param config Pointer the spc_LowPower_Request_config_t structure. + */ +void SPC_SetLowPowerRequestConfig(SPC_Type *base, const spc_lowpower_request_config_t *config) +{ + assert(config != NULL); + + uint32_t reg; + + reg = base->LPREQ_CFG; + reg &= ~(SPC_LPREQ_CFG_LPREQOE_MASK | SPC_LPREQ_CFG_LPREQPOL_MASK | SPC_LPREQ_CFG_LPREQOV_MASK); + + if (config->enable) + { + reg |= SPC_LPREQ_CFG_LPREQOE_MASK | SPC_LPREQ_CFG_LPREQPOL((uint8_t)(config->polarity)) | + SPC_LPREQ_CFG_LPREQOV((uint8_t)(config->override)); + } + else + { + reg &= ~SPC_LPREQ_CFG_LPREQOE_MASK; + } + + base->LPREQ_CFG = reg; +} + +#if !(defined(FSL_FEATURE_MCX_SPC_HAS_NO_GLITCH_DETECT) && FSL_FEATURE_MCX_SPC_HAS_NO_GLITCH_DETECT) +/*! + * brief Configures VDD Core Glitch detector, including ripple counter selection, timeout value and so on. + * + * param base SPC peripheral base address. + * param config Pointer to the structure in type of spc_vdd_core_glitch_detector_config_t. + */ +void SPC_ConfigVddCoreGlitchDetector(SPC_Type *base, const spc_vdd_core_glitch_detector_config_t *config) +{ + assert(config != NULL); + + uint32_t reg; + + reg = (base->VDD_CORE_GLITCH_DETECT_SC) & + ~(SPC_VDD_CORE_GLITCH_DETECT_SC_CNT_SELECT_MASK | SPC_VDD_CORE_GLITCH_DETECT_SC_TIMEOUT_MASK | + SPC_VDD_CORE_GLITCH_DETECT_SC_RE_MASK | SPC_VDD_CORE_GLITCH_DETECT_SC_IE_MASK); + + reg |= SPC_VDD_CORE_GLITCH_DETECT_SC_CNT_SELECT(config->rippleCounterSelect) | + SPC_VDD_CORE_GLITCH_DETECT_SC_TIMEOUT(config->resetTimeoutValue) | + SPC_VDD_CORE_GLITCH_DETECT_SC_RE(config->enableReset) | + SPC_VDD_CORE_GLITCH_DETECT_SC_IE(config->enableInterrupt); + + base->VDD_CORE_GLITCH_DETECT_SC = reg; +} +#endif + +/*! + * brief Set SRAM operate voltage. + * + * param base SPC peripheral base address. + * param config The pointer to spc_sram_voltage_config_t, specifies the configuration of sram voltage. + */ +void SPC_SetSRAMOperateVoltage(SPC_Type *base, const spc_sram_voltage_config_t *config) +{ + assert(config != NULL); + + uint32_t reg = 0UL; + + reg |= SPC_SRAMCTL_VSM(config->operateVoltage); + + base->SRAMCTL = reg; + + if (config->requestVoltageUpdate) + { + base->SRAMCTL |= SPC_SRAMCTL_REQ_MASK; + while ((base->SRAMCTL & SPC_SRAMCTL_ACK_MASK) == 0UL) + { + /* Wait until acknowledged */ + ; + } + base->SRAMCTL &= ~SPC_SRAMCTL_REQ_MASK; + } +} + +/*! + * brief Configs Bandgap mode in Active mode. + * + * @note To disable bandgap in Active mode: + * 1. Disable all LVD's and HVD's in active mode; + * 2. Disable Glitch detect; + * 3. Configure LDO's and DCDC to low drive strength in active mode; + * 4. Invoke this function to disable bandgap in active mode; + * otherwise the error status will be reported. + * + * @note Some other system resources(such as PLL, CMP) require bandgap to be enabled, to disable bandgap please + * take care of other system resources. + * + * param base SPC peripheral base address. + * param mode The Bandgap mode be selected. + * + * retval kStatus_SPC_BandgapModeWrong The Bandgap can not be disabled in active mode. + * retval kStatus_Success Config Bandgap mode in Active power mode successful. + */ +status_t SPC_SetActiveModeBandgapModeConfig(SPC_Type *base, spc_bandgap_mode_t mode) +{ + uint32_t reg; + uint32_t state; + + reg = base->ACTIVE_CFG; + + if (mode == kSPC_BandgapDisabled) + { + state = SPC_GetActiveModeVoltageDetectStatus(base); + + /* If any of the LVD/HVDs are kept enabled, bandgap mode must be enabled with buffer disabled. */ + if (state != 0UL) + { + return kStatus_SPC_BandgapModeWrong; + } + + /* The bandgap mode must be enabled if any regulators' drive strength set as Normal. */ +#if (defined(FSL_FEATURE_MCX_SPC_HAS_SYS_LDO) && FSL_FEATURE_MCX_SPC_HAS_SYS_LDO) + if ((base->ACTIVE_CFG & SPC_ACTIVE_CFG_SYSLDO_VDD_DS_MASK) == + SPC_ACTIVE_CFG_SYSLDO_VDD_DS(kSPC_SysLDO_NormalDriveStrength)) + { + return kStatus_SPC_BandgapModeWrong; + } +#endif /* FSL_FEATURE_MCX_SPC_HAS_SYS_LDO */ + +#if (defined(FSL_FEATURE_MCX_SPC_HAS_DCDC) && FSL_FEATURE_MCX_SPC_HAS_DCDC) + if ((base->ACTIVE_CFG & SPC_ACTIVE_CFG_DCDC_VDD_DS_MASK) == SPC_ACTIVE_CFG_DCDC_VDD_DS(kSPC_DCDC_NormalVoltage)) + { + return kStatus_SPC_BandgapModeWrong; + } +#endif /* FSL_FEATURE_MCX_SPC_HAS_DCDC */ + +#if !(defined(FSL_FEATURE_MCX_SPC_HAS_NO_GLITCH_DETECT) && FSL_FEATURE_MCX_SPC_HAS_NO_GLITCH_DETECT) + /* state of GLITCH_DETECT_DISABLE will be ignored if bandgap is disabled. */ + if ((base->ACTIVE_CFG & SPC_ACTIVE_CFG_GLITCH_DETECT_DISABLE_MASK) == 0UL) + { + return kStatus_SPC_BandgapModeWrong; + } +#endif +#if defined(FSL_FEATURE_SPC_HAS_CORELDO_VDD_DS) && FSL_FEATURE_SPC_HAS_CORELDO_VDD_DS + if ((base->ACTIVE_CFG & SPC_ACTIVE_CFG_CORELDO_VDD_DS_MASK) == + SPC_ACTIVE_CFG_CORELDO_VDD_DS(kSPC_CoreLDO_NormalDriveStrength)) + { + return kStatus_SPC_BandgapModeWrong; + } +#endif /* FSL_FEATURE_SPC_HAS_CORELDO_VDD_DS */ + } + + reg &= ~SPC_ACTIVE_CFG_BGMODE_MASK; + reg |= SPC_ACTIVE_CFG_BGMODE(mode); + + base->ACTIVE_CFG = reg; + + return kStatus_Success; +} + +/*! + * brief Configs Bandgap mode in Low Power mode. + * + * @note To disable Bandgap in Low-power mode: + * 1. Disable all LVD's ad HVD's in low power mode; + * 2. Disable Glitch detect in low power mode; + * 3. Configure LDO's and DCDC to low drive strength in low power mode; + * 4. Disable bandgap in low power mode; + * Otherwise, the error status will be reported. + * + * @note Some other system resources(such as PLL, CMP) require bandgap to be enabled, to disable bandgap please + * take care of other system resources. + * + * param base SPC peripheral base address. + * param mode The Bandgap mode be selected. + * + * retval kStatus_SPC_BandgapModeWrong The bandgap mode setting in Low Power mode is wrong. + * retval kStatus_Success Config Bandgap mode in Low Power power mode successful. + */ +status_t SPC_SetLowPowerModeBandgapmodeConfig(SPC_Type *base, spc_bandgap_mode_t mode) +{ + uint32_t reg; + uint32_t state; + + reg = base->LP_CFG; + + if (mode == kSPC_BandgapDisabled) + { + state = (uint32_t)SPC_GetLowPowerModeVoltageDetectStatus(base); + + /* If any of the LVD/HVDs are kept enabled, bandgap mode must be enabled with buffer disabled. */ + if (state != 0UL) + { + return kStatus_SPC_BandgapModeWrong; + } + +#if (defined(FSL_FEATURE_MCX_SPC_HAS_DCDC) && FSL_FEATURE_MCX_SPC_HAS_DCDC) + if ((base->LP_CFG & SPC_LP_CFG_DCDC_VDD_DS_MASK) == SPC_LP_CFG_DCDC_VDD_DS(kSPC_DCDC_NormalDriveStrength)) + { + return kStatus_SPC_BandgapModeWrong; + } +#endif /* FSL_FEATURE_MCX_SPC_HAS_DCDC */ + +#if (defined(FSL_FEATURE_MCX_SPC_HAS_SYS_LDO) && FSL_FEATURE_MCX_SPC_HAS_SYS_LDO) + if ((base->LP_CFG & SPC_LP_CFG_SYSLDO_VDD_DS_MASK) == SPC_LP_CFG_SYSLDO_VDD_DS(kSPC_SysLDO_NormalDriveStrength)) + { + return kStatus_SPC_BandgapModeWrong; + } +#endif /* FSL_FEATURE_MCX_SPC_HAS_SYS_LDO */ + + if ((base->LP_CFG & SPC_LP_CFG_CORELDO_VDD_DS_MASK) == + SPC_LP_CFG_CORELDO_VDD_DS(kSPC_CoreLDO_NormalDriveStrength)) + { + return kStatus_SPC_BandgapModeWrong; + } + +#if !(defined(FSL_FEATURE_MCX_SPC_HAS_NO_GLITCH_DETECT) && FSL_FEATURE_MCX_SPC_HAS_NO_GLITCH_DETECT) + /* state of GLITCH_DETECT_DISABLE will be ignored if bandgap is disabled. */ + if ((base->LP_CFG & SPC_LP_CFG_GLITCH_DETECT_DISABLE_MASK) == 0UL) + { + return kStatus_SPC_BandgapModeWrong; + } +#endif + } + + reg &= ~SPC_LP_CFG_BGMODE_MASK; + reg |= SPC_LP_CFG_BGMODE(mode); + base->LP_CFG = reg; + + return kStatus_Success; +} + +/*! + * brief Configs CORE voltage detect options. + * + * This function configs CORE voltage detect options. + * Note: Setting both the voltage detect interrupt and reset + * enable will cause interrupt to be generated on exit from reset. + * If those conditioned is not desired, interrupt/reset only one is enabled. + * + * param base SPC peripheral base address. + * param config Pointer to spc_core_voltage_detect_config_t structure. + */ +void SPC_SetCoreVoltageDetectConfig(SPC_Type *base, const spc_core_voltage_detect_config_t *config) +{ + assert(config != NULL); + + uint32_t reg = 0UL; + +#if (defined(FSL_FEATURE_MCX_SPC_HAS_COREVDD_HVD) && FSL_FEATURE_MCX_SPC_HAS_COREVDD_HVD) + reg |= (config->option.HVDInterruptEnable) ? SPC_VD_CORE_CFG_HVDIE(1U) : SPC_VD_CORE_CFG_HVDIE(0U); + reg |= (config->option.HVDResetEnable) ? SPC_VD_CORE_CFG_HVDRE(1U) : SPC_VD_CORE_CFG_HVDRE(0U); +#endif /* FSL_FEATURE_MCX_SPC_HAS_COREVDD_HVD */ + reg |= (config->option.LVDInterruptEnable) ? SPC_VD_CORE_CFG_LVDIE(1U) : SPC_VD_CORE_CFG_LVDIE(0U); + reg |= (config->option.LVDResetEnable) ? SPC_VD_CORE_CFG_LVDRE(1U) : SPC_VD_CORE_CFG_LVDRE(0U); + + base->VD_CORE_CFG = reg; +} + +#if (defined(FSL_FEATURE_MCX_SPC_HAS_COREVDD_HVD) && FSL_FEATURE_MCX_SPC_HAS_COREVDD_HVD) +/*! + * brief Enables the Core High Voltage Detector in Active mode. + * + * note If the CORE_LDO high voltage detect is enabled in Active mode, please note that the bandgap must be enabled + * and the drive strength of each regulator must not set to low. + * + * param base SPC peripheral base address. + * param enable Enable/Disable Core HVD. + * true - Enable Core High voltage detector in active mode. + * false - Disable Core High voltage detector in active mode. + * + * retval kStatus_Success Enable Core High Voltage Detect successfully. + */ +status_t SPC_EnableActiveModeCoreHighVoltageDetect(SPC_Type *base, bool enable) +{ + status_t status = kStatus_Success; + + if (enable) + { + base->ACTIVE_CFG |= SPC_ACTIVE_CFG_CORE_HVDE_MASK; + } + else + { + base->ACTIVE_CFG &= ~SPC_ACTIVE_CFG_CORE_HVDE_MASK; + } + + return status; +} + +/*! + * brief Enables the Core High Voltage Detector in Low Power mode. + * + * note If the CORE_LDO high voltage detect is enabled in Low Power mode, + * please note that the bandgap must be enabled and the drive strength of each regulator + * must not set to low in low power mode. + * + * param base SPC peripheral base address. + * param enable Enable/Disable Core HVD. + * true - Enable Core High voltage detector in low power mode. + * false - Disable Core High voltage detector in low power mode. + * + * retval kStatus_Success Enable Core High Voltage Detect in low power mode successfully. + */ +status_t SPC_EnableLowPowerModeCoreHighVoltageDetect(SPC_Type *base, bool enable) +{ + status_t status = kStatus_Success; + + if (enable) + { + base->LP_CFG |= SPC_LP_CFG_CORE_HVDE_MASK; + } + else + { + base->LP_CFG &= ~SPC_LP_CFG_CORE_HVDE_MASK; + } + + return status; +} +#endif /* FSL_FEATURE_MCX_SPC_HAS_COREVDD_HVD */ + +/*! + * brief Enables the Core VDD Low Voltage Detector in Active mode. + * + * note If the Core VDD high voltage detect is enabled in Active mode, please note that the bandgap must be enabled + * and the drive strength of each regulator must not set to low. + * + * param base SPC peripheral base address. + * param enable Enable/Disable Core LVD. + * true - Enable Core Low voltage detector in active mode. + * false - Disable Core Low voltage detector in active mode. + * + * retval kStatus_Success Enable Core Low Voltage Detect successfully. + */ +status_t SPC_EnableActiveModeCoreLowVoltageDetect(SPC_Type *base, bool enable) +{ + status_t status = kStatus_Success; + + if (enable) + { + base->ACTIVE_CFG |= SPC_ACTIVE_CFG_CORE_LVDE_MASK; + } + else + { + base->ACTIVE_CFG &= ~SPC_ACTIVE_CFG_CORE_LVDE_MASK; + } + + return status; +} + +/*! + * brief Enables the Core Low Voltage Detector in Low Power mode. + * + * note If the Core VDD low voltage detect is enabled in Low Power mode, please note that the bandgap must be enabled + * and the drive strength of each regulator must not set to low in Low Power mode. + * + * param base SPC peripheral base address. + * param enable Enable/Disable Core HVD. + * true - Enable Core Low voltage detector in low power mode. + * false - Disable Core Low voltage detector in low power mode. + * + * retval kStatus_Success Enable Core Low Voltage Detect in low power mode successfully. + */ +status_t SPC_EnableLowPowerModeCoreLowVoltageDetect(SPC_Type *base, bool enable) +{ + status_t status = kStatus_Success; + + if (enable) + { + base->LP_CFG |= SPC_LP_CFG_CORE_LVDE_MASK; + } + else + { + base->LP_CFG &= ~SPC_LP_CFG_CORE_LVDE_MASK; + } + + return status; +} + +/*! + * brief Set system VDD Low-voltage level selection. + * + * This function selects the system VDD low-voltage level. Changing system VDD low-voltage level + * must be done after disabling the System VDD low voltage reset and interrupt. + * + * @deprecated In latest RM, reserved for all devices, will removed in next release. + * + * param base SPC peripheral base address. + * param level System VDD Low-Voltage level selection. See @ref spc_low_voltage_level_select_t for details. + */ +void SPC_SetSystemVDDLowVoltageLevel(SPC_Type *base, spc_low_voltage_level_select_t level) +{ + (void)level; + (void)base; + + /* + uint32_t reg; + + reg = base->VD_SYS_CFG; + + base->VD_SYS_CFG &= ~(SPC_VD_SYS_CFG_LVDRE_MASK | SPC_VD_SYS_CFG_LVDIE_MASK); + reg |= SPC_VD_SYS_CFG_LVSEL(level); + + base->VD_SYS_CFG = reg; */ +} + +/*! + * brief Configs SYS VDD voltage detect options. + * + * This function config SYS voltage detect options. + * Note: Setting both the voltage detect interrupt and reset + * enable will cause interrupt to be generated on exit from reset. + * If those conditioned is not desired, interrupt/reset only one is enabled. + * + * param base SPC peripheral base address. + * param config Pointer to spc_system_voltage_detect_config_t structure. + */ +void SPC_SetSystemVoltageDetectConfig(SPC_Type *base, const spc_system_voltage_detect_config_t *config) +{ + assert(config != NULL); + + uint32_t reg = 0UL; + + reg |= (config->option.HVDInterruptEnable) ? SPC_VD_SYS_CFG_HVDIE(1U) : SPC_VD_SYS_CFG_HVDIE(0U); + reg |= (config->option.LVDInterruptEnable) ? SPC_VD_SYS_CFG_LVDIE(1U) : SPC_VD_SYS_CFG_LVDIE(0U); + reg |= (config->option.HVDResetEnable) ? SPC_VD_SYS_CFG_HVDRE(1U) : SPC_VD_SYS_CFG_HVDRE(0U); + reg |= (config->option.LVDResetEnable) ? SPC_VD_SYS_CFG_LVDRE(1U) : SPC_VD_SYS_CFG_LVDRE(0U); + + base->VD_SYS_CFG = reg; + + (void)(config->level); + /* SPC_SetSystemVDDLowVoltageLevel(base, config->level); */ +} + +/*! + * brief Enables the System VDD High Voltage Detector in Active mode. + * + * note If the System_LDO high voltage detect is enabled in Active mode, + * please note that the bandgap must be enabled and the drive strength of + * each regulator must not set to low in Active mode. + * + * param base SPC peripheral base address. + * param enable Enable/Disable System HVD. + * true - Enable System High voltage detector in active mode. + * false - Disable System High voltage detector in active mode. + * + * retval kStatus_Success Enable System High Voltage Detect successfully. + */ +status_t SPC_EnableActiveModeSystemHighVoltageDetect(SPC_Type *base, bool enable) +{ + status_t status = kStatus_Success; + + if (enable) + { + base->ACTIVE_CFG |= SPC_ACTIVE_CFG_SYS_HVDE_MASK; + } + else + { + base->ACTIVE_CFG &= ~SPC_ACTIVE_CFG_SYS_HVDE_MASK; + } + + return status; +} + +/*! + * brief Enables the System VDD Low Voltage Detector in Active mode. + * + * note If the System_LDO low voltage detect is enabled in Active mode, + * please note that the bandgap must be enabled and the drive strength of each + * regulator must not set to low in Active mode. + * + * param base SPC peripheral base address. + * param enable Enable/Disable System LVD. + * true - Enable System Low voltage detector in active mode. + * false - Disable System Low voltage detector in active mode. + * + * retval kStatus_Success Enable the System Low Voltage Detect successfully. + */ +status_t SPC_EnableActiveModeSystemLowVoltageDetect(SPC_Type *base, bool enable) +{ + status_t status = kStatus_Success; + + if (enable) + { + base->ACTIVE_CFG |= SPC_ACTIVE_CFG_SYS_LVDE_MASK; + } + else + { + base->ACTIVE_CFG &= ~SPC_ACTIVE_CFG_SYS_LVDE_MASK; + } + + return status; +} + +/*! + * brief Enables the System VDD High Voltage Detector in Low Power mode. + * + * note If the System_LDO high voltage detect is enabled in low power mode, + * please note that the bandgap must be enabled and the drive strength of each + * regulator must not set to low in low power mode. + * + * param base SPC peripheral base address. + * param enable Enable/Disable System HVD. + * true - Enable System High voltage detector in low power mode. + * false - Disable System High voltage detector in low power mode. + * + * retval kStatus_Success Enable System High Voltage Detect in low power mode successfully. + */ +status_t SPC_EnableLowPowerModeSystemHighVoltageDetect(SPC_Type *base, bool enable) +{ + status_t status = kStatus_Success; + + if (enable) + { + base->LP_CFG |= SPC_LP_CFG_SYS_HVDE_MASK; + } + else + { + base->LP_CFG &= ~SPC_LP_CFG_SYS_HVDE_MASK; + } + + return status; +} + +/*! + * brief Enables the System VDD Low Voltage Detector in Low Power mode. + * + * note If the System_LDO low voltage detect is enabled in Low Power mode, + * please note that the bandgap must be enabled and the drive strength of each + * regulator must not set to low in Low Power mode. + * + * param base SPC peripheral base address. + * param enable Enable/Disable System HVD. + * true - Enable System Low voltage detector in low power mode. + * false - Disable System Low voltage detector in low power mode. + * + * retval kStatus_Success Enable System Low Voltage Detect in low power mode successfully. + */ +status_t SPC_EnableLowPowerModeSystemLowVoltageDetect(SPC_Type *base, bool enable) +{ + status_t status = kStatus_Success; + + if (enable) + { + base->LP_CFG |= SPC_LP_CFG_SYS_LVDE_MASK; + } + else + { + base->LP_CFG &= ~SPC_LP_CFG_SYS_LVDE_MASK; + } + + return status; +} + +#if (defined(FSL_FEATURE_MCX_SPC_HAS_IOVDD_VD) && FSL_FEATURE_MCX_SPC_HAS_IOVDD_VD) +/*! + * brief Set IO VDD Low-Voltage level selection. + * + * This function selects the IO VDD Low-voltage level. Changing IO VDD low-voltage level + * must be done after disabling the IO VDD low voltage reset and interrupt. + * + * param base SPC peripheral base address. + * param level IO VDD Low-voltage level selection. + */ +void SPC_SetIOVDDLowVoltageLevel(SPC_Type *base, spc_low_voltage_level_select_t level) +{ + uint32_t reg; + + reg = base->VD_IO_CFG; + + base->VD_IO_CFG &= ~(SPC_VD_IO_CFG_LVDRE_MASK | SPC_VD_IO_CFG_LVDIE_MASK | SPC_VD_IO_CFG_LVSEL_MASK); + reg |= SPC_VD_IO_CFG_LVSEL(level); + + base->VD_IO_CFG = reg; +} + +/*! + * brief Configs IO VDD voltage detect options. + * + * This function config IO voltage detect options. + * Note: Setting both the voltage detect interrupt and reset + * enable will cause interrupt to be generated on exit from reset. + * If those conditioned is not desired, interrupt/reset so only one is enabled. + * + * param base SPC peripheral base address. + * param config Pointer to spc_IO_voltage_detect_config_t structure. + */ +void SPC_SetIOVoltageDetectConfig(SPC_Type *base, const spc_io_voltage_detect_config_t *config) +{ + assert(config != NULL); + + uint32_t reg = 0UL; + + /* Set trip voltage level. */ + SPC_SetIOVDDLowVoltageLevel(base, config->level); + + reg = base->VD_IO_CFG; + reg &= ~(SPC_VD_IO_CFG_LVDRE_MASK | SPC_VD_IO_CFG_LVDIE_MASK | SPC_VD_IO_CFG_HVDRE_MASK | SPC_VD_IO_CFG_HVDIE_MASK); + + reg |= (config->option.HVDInterruptEnable) ? SPC_VD_IO_CFG_HVDIE(1U) : SPC_VD_IO_CFG_HVDIE(0U); + reg |= (config->option.LVDInterruptEnable) ? SPC_VD_IO_CFG_LVDIE(1U) : SPC_VD_IO_CFG_LVDIE(0U); + reg |= (config->option.HVDResetEnable) ? SPC_VD_IO_CFG_HVDRE(1U) : SPC_VD_IO_CFG_HVDRE(0U); + reg |= (config->option.LVDResetEnable) ? SPC_VD_IO_CFG_LVDRE(1U) : SPC_VD_IO_CFG_LVDRE(0U); + + base->VD_IO_CFG = reg; +} + +/*! + * brief Enables the IO VDD High Voltage Detector in Active mode. + * + * note If the IO high voltage detect is enabled in Active mode, + * please note that the bandgap must be enabled and the drive strength + * of each regulator must not set to low in Active mode. + * + * param base SPC peripheral base address. + * param enable Enable/Disable IO HVD. + * true - Enable IO High voltage detector in active mode. + * false - Disable IO High voltage detector in active mode. + * + * retval kStatus_Success Enable IO High Voltage Detect successfully. + */ +status_t SPC_EnableActiveModeIOHighVoltageDetect(SPC_Type *base, bool enable) +{ + status_t status = kStatus_Success; + + if (enable) + { + base->ACTIVE_CFG |= SPC_ACTIVE_CFG_IO_HVDE_MASK; + } + else + { + base->ACTIVE_CFG &= ~SPC_ACTIVE_CFG_IO_HVDE_MASK; + } + + return status; +} + +/*! + * brief Enables the IO VDD Low Voltage Detector in Active mode. + * + * note If the IO low voltage detect is enabled in Active mode, + * please note that the bandgap must be enabled and the drive strength + * of each regulator must not set to low in Active mode. + * + * param base SPC peripheral base address. + * param enable Enable/Disable IO LVD. + * true - Enable IO Low voltage detector in active mode. + * false - Disable IO Low voltage detector in active mode. + * + * retval kStatus_Success Enable IO Low Voltage Detect successfully. + */ +status_t SPC_EnableActiveModeIOLowVoltageDetect(SPC_Type *base, bool enable) +{ + status_t status = kStatus_Success; + + if (enable) + { + base->ACTIVE_CFG |= SPC_ACTIVE_CFG_IO_LVDE_MASK; + } + else + { + base->ACTIVE_CFG &= ~SPC_ACTIVE_CFG_IO_LVDE_MASK; + } + + return status; +} + +/*! + * brief Enables the IO VDD High Voltage Detector in Low Power mode. + * + * note If the IO high voltage detect is enabled in Low Power mode, please note that the bandgap must be enabled + * and the drive strength of each regulator must not set to low in Low Power mode. + * + * param base SPC peripheral base address. + * param enable Enable/Disable IO HVD. + * true - Enable IO High voltage detector in low power mode. + * false - Disable IO High voltage detector in low power mode. + * + * retval kStatus_Success Enable IO High Voltage Detect in low power mode successfully. + */ +status_t SPC_EnableLowPowerModeIOHighVoltageDetect(SPC_Type *base, bool enable) +{ + status_t status = kStatus_Success; + + if (enable) + { + base->LP_CFG |= SPC_LP_CFG_IO_HVDE_MASK; + } + else + { + base->LP_CFG &= ~SPC_LP_CFG_IO_HVDE_MASK; + } + + return status; +} + +/*! + * brief Enables the IO VDD Low Voltage Detector in Low Power mode. + * + * note If the IO low voltage detect is enabled in Low Power mode, please note that the bandgap must be enabled + * and the drive strength of each regulator must not set to low in Low Power mode. + * + * param base SPC peripheral base address. + * param enable Enable/Disable IO HVD. + * true - Enable IO Low voltage detector in low power mode. + * false - Disable IO Low voltage detector in low power mode. + * + * retval kStatus_Success Enable IO Low Voltage Detect in low power mode successfully. + */ +status_t SPC_EnableLowPowerModeIOLowVoltageDetect(SPC_Type *base, bool enable) +{ + status_t status = kStatus_Success; + + if (enable) + { + base->LP_CFG |= SPC_LP_CFG_IO_LVDE_MASK; + } + else + { + base->LP_CFG &= ~SPC_LP_CFG_IO_LVDE_MASK; + } + + return status; +} +#endif /* FSL_FEATURE_MCX_SPC_HAS_IOVDD_VD */ + +/*! + * brief Configs external voltage domains + * + * This function configs external voltage domains isolation. + * + * param base SPC peripheral base address. + * param lowPowerIsoMask The mask of external domains isolate enable during low power mode. + * param IsoMask The mask of external domains isolate. + */ +void SPC_SetExternalVoltageDomainsConfig(SPC_Type *base, uint8_t lowPowerIsoMask, uint8_t IsoMask) +{ + uint32_t reg = 0UL; + + reg |= SPC_EVD_CFG_REG_EVDISO(IsoMask) | SPC_EVD_CFG_REG_EVDLPISO(lowPowerIsoMask); + base->EVD_CFG = reg; +} + +/*! + * brief Configs Core LDO Regulator in Active mode. + * + * @note The bandgap must be enabled before invoking this function. + * @note To set Core LDO as low drive strength, all HVDs/LVDs must be disabled previously. + * + * param base SPC peripheral base address. + * param option Pointer to the spc_active_mode_Core_LDO_option_t structure. + * + * retval kStatus_Success Config Core LDO regulator in Active power mode successful. + * retval kStatus_SPC_Busy The SPC instance is busy to execute any type of power mode transition. + * retval kStatus_SPC_BandgapModeWrong Bandgap should be enabled before invoking this function. + * retval kStatus_SPC_CORELDOLowDriveStrengthIgnore To set Core LDO as low drive strength, + * all LVDs/HVDs must be disabled before invoking this function. + */ +status_t SPC_SetActiveModeCoreLDORegulatorConfig(SPC_Type *base, const spc_active_mode_core_ldo_option_t *option) +{ + assert(option != NULL); + + if ((base->SC & SPC_SC_BUSY_MASK) != 0UL) + { + return kStatus_SPC_Busy; + } + + /* Check input parameters. */ + /* 1. Bandgap must not be disabled. */ + if (SPC_GetActiveModeBandgapMode(base) == kSPC_BandgapDisabled) + { + return kStatus_SPC_BandgapModeWrong; + } + + /* 2. To set to low drive strength, all LVDs/HVDs must be disabled previously. */ + if ((SPC_GetActiveModeVoltageDetectStatus(base) != 0UL) && + (option->CoreLDODriveStrength == kSPC_CoreLDO_LowDriveStrength)) + { + return kStatus_SPC_CORELDOLowDriveStrengthIgnore; + } + + if ((uint8_t)SPC_GetActiveModeCoreLDOVDDVoltageLevel(base) != (uint8_t)(option->CoreLDOVoltage)) + { +#if defined(FSL_FEATURE_SPC_HAS_CORELDO_VDD_DS) && FSL_FEATURE_SPC_HAS_CORELDO_VDD_DS + (void)SPC_SetActiveModeCoreLDORegulatorDriveStrength(base, kSPC_CoreLDO_NormalDriveStrength); +#endif /* FSL_FEATURE_SPC_HAS_CORELDO_VDD_DS */ + (void)SPC_SetActiveModeCoreLDORegulatorVoltageLevel(base, option->CoreLDOVoltage); + } + +#if defined(FSL_FEATURE_SPC_HAS_CORELDO_VDD_DS) && FSL_FEATURE_SPC_HAS_CORELDO_VDD_DS + (void)SPC_SetActiveModeCoreLDORegulatorDriveStrength(base, option->CoreLDODriveStrength); +#endif /* FSL_FEATURE_SPC_HAS_CORELDO_VDD_DS */ + + return kStatus_Success; +} + +/*! + * brief Set Core LDO VDD Regulator Voltage level in Active mode. + * + * @note In active mode, the Core LDO voltage level should only be changed when the + * Core LDO is in normal drive strength. + * + * @note Update Core LDO voltage level will set Busy flag, + * this function return only when busy flag is cleared by hardware + * + * param base SPC peripheral base address. + * param voltageLevel Specify the voltage level of CORE LDO Regulator in Active mode, please + refer to @ref spc_core_ldo_voltage_level_t. + * + * retval kStatus_SPC_CORELDOVoltageSetFail Core LDO voltage level should only be + * changed when the CORE_LDO is in normal drive strength. + * retval kStatus_Success Set Core LDO regulator voltage level in Active power mode successful. + */ +status_t SPC_SetActiveModeCoreLDORegulatorVoltageLevel(SPC_Type *base, spc_core_ldo_voltage_level_t voltageLevel) +{ + if ((uint8_t)voltageLevel != (uint8_t)SPC_GetActiveModeCoreLDOVDDVoltageLevel(base)) + { +#if (defined(FSL_FEATURE_SPC_HAS_CORELDO_VDD_DS) && FSL_FEATURE_SPC_HAS_CORELDO_VDD_DS) + if (SPC_GetActiveModeCoreLDODriveStrength(base) != kSPC_CoreLDO_NormalDriveStrength) + { + return kStatus_SPC_CORELDOVoltageSetFail; + } +#endif /* FSL_FEATURE_SPC_HAS_CORELDO_VDD_DS */ + + base->ACTIVE_CFG = + ((base->ACTIVE_CFG & ~SPC_ACTIVE_CFG_CORELDO_VDD_LVL_MASK) | SPC_ACTIVE_CFG_CORELDO_VDD_LVL(voltageLevel)); + + /* + * $Branch Coverage Justification$ + * $ref spc_c_ref_1$. + */ + while ((base->SC & SPC_SC_BUSY_MASK) != 0UL) + { + } + } + return kStatus_Success; +} + +#if defined(FSL_FEATURE_SPC_HAS_CORELDO_VDD_DS) && FSL_FEATURE_SPC_HAS_CORELDO_VDD_DS +/*! + * brief Set Core LDO VDD Regulator Drive Strength in Active mode. + * + * param base SPC peripheral base address. + * param driveStrength Specify the drive strength of CORE LDO Regulator in Active mode, please + refer to @ref spc_core_ldo_drive_strength_t. + * + * retval #kStatus_Success Set Core LDO regulator drive strength in Active power mode successful. + * retval #kStatus_SPC_CORELDOLowDriveStrengthIgnore If any voltage detect enabled, + core_ldo's drive strength can not set to low. + * retval #kStatus_SPC_BandgapModeWrong The selected bandgap mode is not allowed. + */ +status_t SPC_SetActiveModeCoreLDORegulatorDriveStrength(SPC_Type *base, spc_core_ldo_drive_strength_t driveStrength) +{ + if (driveStrength == kSPC_CoreLDO_LowDriveStrength) + { + /* If any voltage detect feature is enabled in Active mode, then CORE_LDO's drive strength must not set to low. + */ + if (SPC_GetActiveModeVoltageDetectStatus(base) != 0UL) + { + return kStatus_SPC_CORELDOLowDriveStrengthIgnore; + } + } + + if (driveStrength == kSPC_CoreLDO_NormalDriveStrength) + { + /* If specify normal drive strength, bandgap must not be disabled. */ + if (SPC_GetActiveModeBandgapMode(base) == kSPC_BandgapDisabled) + { + return kStatus_SPC_BandgapModeWrong; + } + } + + base->ACTIVE_CFG = + ((base->ACTIVE_CFG & ~SPC_ACTIVE_CFG_CORELDO_VDD_DS_MASK) | SPC_ACTIVE_CFG_CORELDO_VDD_DS(driveStrength)); + + return kStatus_Success; +} +#endif /* FSL_FEATURE_SPC_HAS_CORELDO_VDD_DS */ + +/*! + * brief Configs CORE LDO Regulator in low power mode + * + * This function configs CORE LDO Regulator in Low Power mode. + * If CORE LDO VDD Drive Strength is set to Normal, the CORE LDO VDD regulator voltage + * level in Active mode must be equal to the voltage level in Low power mode. And the Bandgap + * must be programmed to select bandgap enabled. + * Core VDD voltage levels for the Core LDO low power regulator can only be changed when the CORE + * LDO Drive Strength is set as Normal. + * + * param base SPC peripheral base address. + * param option Pointer to the spc_lowpower_mode_Core_LDO_option_t structure. + * retval kStatus_Success Config Core LDO regulator in power mode successfully. + * retval kStatus_SPC_Busy The SPC instance is busy to execute any type of power mode transition. + * retval kStatus_SPC_CORELDOLowDriveStrengthIgnore HVDs/LVDs are not disabled before invoking this function. + * retval kStatus_SPC_BandgapModeWrong The bandgap is not enabled before invoking this function. + */ +status_t SPC_SetLowPowerModeCoreLDORegulatorConfig(SPC_Type *base, const spc_lowpower_mode_core_ldo_option_t *option) +{ + status_t status = kStatus_Success; + + if ((base->SC & SPC_SC_BUSY_MASK) != 0UL) + { + /* + * $Line Coverage Justification$ + * $ref spc_c_ref_1$. + */ + return kStatus_SPC_Busy; + } + + status = SPC_SetLowPowerModeCoreLDORegulatorDriveStrength(base, option->CoreLDODriveStrength); + if (status == kStatus_Success) + { + (void)SPC_SetLowPowerModeCoreLDORegulatorVoltageLevel(base, option->CoreLDOVoltage); + } + + return status; +} + +/*! + * brief Set Core LDO VDD Regulator Voltage level in Low power mode. + * + * @note If Core LDO's drive strengths are same in active and low power mode, the Core LDO's voltage must be set to the + * same value in active and low power mode. Application should take care of this limitation. + * + * @note Some devices require Core LDO and DCDC have the same voltage level even if Core LDO is off. Application should + * take care of this limitation. + * + * param base SPC peripheral base address. + * param voltageLevel Voltage level of CORE LDO Regulator in Low power mode, please + refer to @ref spc_core_ldo_voltage_level_t. + * + * retval #kStatus_SPC_Busy The SPC instance is busy to execute other operation. + * retval #kStatus_Success Set Core LDO regulator voltage level in Low power mode successful. + */ +status_t SPC_SetLowPowerModeCoreLDORegulatorVoltageLevel(SPC_Type *base, spc_core_ldo_voltage_level_t voltageLevel) +{ + if ((base->SC & SPC_SC_BUSY_MASK) != 0UL) + { + /* + * $Line Coverage Justification$ + * $ref spc_c_ref_1$. + */ + return kStatus_SPC_Busy; + } + + base->LP_CFG = ((base->LP_CFG & ~SPC_LP_CFG_CORELDO_VDD_LVL_MASK) | SPC_LP_CFG_CORELDO_VDD_LVL(voltageLevel)); + + /* + * $Branch Coverage Justification$ + * $ref spc_c_ref_1$. + */ + while ((base->SC & SPC_SC_BUSY_MASK) != 0UL) + { + } + + return kStatus_Success; +} + +/*! + * brief Set Core LDO VDD Regulator Drive Strength in Low power mode. + * + * param base SPC peripheral base address. + * param driveStrength Specify drive strength of CORE LDO in low power mode. + * + * retval #kStatus_SPC_CORELDOLowDriveStrengthIgnore Some voltage detect enabled, CORE LDO's drive strength can not set + * as low. + * retval #kStatus_Success Set Core LDO regulator drive strength in Low power mode successful. + * retval #kStatus_SPC_BandgapModeWrong Bandgap is disabled when attempt to set CORE LDO work as normal drive strength. + */ +status_t SPC_SetLowPowerModeCoreLDORegulatorDriveStrength(SPC_Type *base, spc_core_ldo_drive_strength_t driveStrength) +{ + if (driveStrength == kSPC_CoreLDO_LowDriveStrength) + { + /* If any voltage detect feature is enabled in Low Power mode, then CORE_LDO's drive strength must not set to + * low. + */ + if (SPC_GetLowPowerModeVoltageDetectStatus(base) != 0UL) + { + return kStatus_SPC_CORELDOLowDriveStrengthIgnore; + } + } + else + { + /* To specify normal drive strength, the bandgap must be enabled in low power mode. */ + if (SPC_GetLowPowerModeBandgapMode(base) == kSPC_BandgapDisabled) + { + return kStatus_SPC_BandgapModeWrong; + } + } + + base->LP_CFG = ((base->LP_CFG & ~SPC_LP_CFG_CORELDO_VDD_DS_MASK) | SPC_LP_CFG_CORELDO_VDD_DS(driveStrength)); + + return kStatus_Success; +} + +#if (defined(FSL_FEATURE_MCX_SPC_HAS_SYS_LDO) && FSL_FEATURE_MCX_SPC_HAS_SYS_LDO) +/*! + * brief Configs System LDO VDD Regulator in Active mode. + * + * This function configs System LDO VDD Regulator in Active mode. + * If System LDO VDD Drive Strength is set to Normal, the Bandgap mode in Active mode must be programmed + * to a value that enable the bandgap. + * If any voltage detects are kept enabled, configuration to set System LDO VDD drive strength to low will + * be ignored. + * If select System LDO VDD Regulator voltage level to Over Drive Voltage, the Drive Strength of System LDO VDD + * Regulator must be set to Normal otherwise the regulator Drive Strength will be forced to Normal. + * If select System LDO VDD Regulator voltage level to Over Drive Voltage, the High voltage detect must be disabled. + * Otherwise it will be fail to regulator to Over Drive Voltage. + * + * param base SPC peripheral base address. + * param option Pointer to the spc_active_mode_Sys_LDO_option_t structure. + * retval kStatus_Success Config System LDO regulator in Active power mode successful. + * retval kStatus_SPC_Busy The SPC instance is busy to execute any type of power mode transition. + * retval kStatus_SPC_BandgapModeWrong The bandgap is not enabled before invoking this function. + * retval kStatus_SPC_SYSLDOOverDriveVoltageFail HVD of System VDD is not disable before setting to Over Drive voltage. + * retval kStatus_SPC_SYSLDOLowDriveStrengthIgnore Set System LDO VDD regulator's driver strength to Low will be + * ignored. + */ +status_t SPC_SetActiveModeSystemLDORegulatorConfig(SPC_Type *base, const spc_active_mode_sys_ldo_option_t *option) +{ + assert(option != NULL); + + if ((base->SC & SPC_SC_BUSY_MASK) != 0UL) + { + /* + * $Line Coverage Justification$ + * $ref spc_c_ref_1$. + */ + return kStatus_SPC_Busy; + } + + /* Check input parameters before setting registers. */ + /* 1. To set to low DS, all LVDs/HVDs must be disabled previously. */ + if ((SPC_GetActiveModeVoltageDetectStatus(base) != 0UL) && + (option->SysLDODriveStrength == kSPC_SysLDO_LowDriveStrength)) + { + return kStatus_SPC_SYSLDOLowDriveStrengthIgnore; + } + /* 2. If specify normal drive strength, bandgap must not be disabled. */ + if ((SPC_GetActiveModeBandgapMode(base) == kSPC_BandgapDisabled) && + (option->SysLDODriveStrength == kSPC_SysLDO_NormalDriveStrength)) + { + return kStatus_SPC_BandgapModeWrong; + } + + /* 3. Must disable system LDO high voltage detector before specifying overdrive voltage. */ + if ((option->SysLDOVoltage == kSPC_SysLDO_OverDriveVoltage) && + ((SPC_GetActiveModeVoltageDetectStatus(base) & SPC_ACTIVE_CFG_SYS_HVDE_MASK) != 0UL)) + { + return kStatus_SPC_SYSLDOOverDriveVoltageFail; + } + + (void)SPC_SetActiveModeSystemLDORegulatorDriveStrength(base, option->SysLDODriveStrength); + (void)SPC_SetActiveModeSystemLDORegulatorVoltageLevel(base, option->SysLDOVoltage); + + return kStatus_Success; +} + +/*! + * brief Set System LDO Regulator voltage level in Active mode. + * + * @note The system LDO regulator can only operate at the overdrive voltage level for a limited amount of time for the + * life of chip. + * + * param base SPC peripheral base address. + * param voltageLevel Specify the voltage level of System LDO Regulator in Active mode. + * + * retval #kStatus_Success Set System LDO Regulator voltage level in Active mode successfully. + * retval #kStatus_SPC_SYSLDOOverDriveVoltageFail Must disable system LDO high voltage detector before specifying + * overdrive voltage. + */ +status_t SPC_SetActiveModeSystemLDORegulatorVoltageLevel(SPC_Type *base, spc_sys_ldo_voltage_level_t voltageLevel) +{ + if (voltageLevel == kSPC_SysLDO_OverDriveVoltage) + { + /* Must disable system LDO high voltage detector before specifying overdrive voltage. */ + if ((SPC_GetActiveModeVoltageDetectStatus(base) & SPC_ACTIVE_CFG_SYS_HVDE_MASK) != 0UL) + { + return kStatus_SPC_SYSLDOOverDriveVoltageFail; + } + } + + base->ACTIVE_CFG = + (base->ACTIVE_CFG & ~SPC_ACTIVE_CFG_SYSLDO_VDD_LVL_MASK) | SPC_ACTIVE_CFG_SYSLDO_VDD_LVL(voltageLevel); + + return kStatus_Success; +} + +/*! + * brief Set System LDO Regulator Drive Strength in Active mode. + * + * param base SPC peripheral base address. + * param driveStrength Specify the drive strength of System LDO Regulator in Active mode. + * + * retval #kStatus_Success Set System LDO Regulator drive strength in Active mode successfully. + * retval #kStatus_SPC_SYSLDOLowDriveStrengthIgnore Attempt to specify low drive strength is ignored due to any + voltage detect feature is enabled in active mode. + * retval #kStatus_SPC_BandgapModeWrong Bandgap mode in Active mode must be programmed to a value that enables + the bandgap if attempt to specify normal drive strength. + */ +status_t SPC_SetActiveModeSystemLDORegulatorDriveStrength(SPC_Type *base, spc_sys_ldo_drive_strength_t driveStrength) +{ + if (driveStrength == kSPC_SysLDO_LowDriveStrength) + { + /* If enabled any LVDs or HVDs, SPC will ignore the attempt to specify low drive strength. */ + if (SPC_GetActiveModeVoltageDetectStatus(base) != 0UL) + { + return kStatus_SPC_SYSLDOLowDriveStrengthIgnore; + } + } + + if (driveStrength == kSPC_SysLDO_NormalDriveStrength) + { + /* If specify normal drive strength, bandgap must not be disabled. */ + if (SPC_GetActiveModeBandgapMode(base) == kSPC_BandgapDisabled) + { + return kStatus_SPC_BandgapModeWrong; + } + } + + base->ACTIVE_CFG = + (base->ACTIVE_CFG & ~SPC_ACTIVE_CFG_SYSLDO_VDD_DS_MASK) | SPC_ACTIVE_CFG_SYSLDO_VDD_DS(driveStrength); + + return kStatus_Success; +} + +/*! + * brief Configs System LDO regulator in low power modes. + * + * This function configs System LDO regulator in low power modes. + * If System LDO VDD Regulator Drive strength is set to normal, bandgap mode in low power + * mode must be programmed to a value that enables the Bandgap. + * If any High voltage detectors or Low Voltage detectors are kept enabled, configuration + * to set System LDO Regulator drive strength as Low will be ignored. + * + * param base SPC peripheral base address. + * param option Pointer to spc_lowpower_mode_Sys_LDO_option_t structure. + * + * retval kStatus_Success Config System LDO regulator in Low Power Mode successfully. + * retval kStatus_SPC_Busy The SPC instance is busy to execute any type of power mode transition. + * retval kStatus_SPC_BandgapModeWrong The bandgap mode setting in Low Power Mode is wrong. + * retval kStatus_SPC_SYSLDOLowDriveStrengthIgnore Set driver strength to low will be ignored. + */ +status_t SPC_SetLowPowerModeSystemLDORegulatorConfig(SPC_Type *base, const spc_lowpower_mode_sys_ldo_option_t *option) +{ + status_t status; + + if ((base->SC & SPC_SC_BUSY_MASK) != 0UL) + { + /* + * $Line Coverage Justification$ + * $ref spc_c_ref_1$. + */ + return kStatus_SPC_Busy; + } + + status = SPC_SetLowPowerModeSystemLDORegulatorDriveStrength(base, option->SysLDODriveStrength); + + return status; +} + +/*! + * brief Set System LDO Regulator drive strength in Low Power Mode. + * + * param base SPC peripheral base address. + * param driveStrength Specify the drive strength of System LDO Regulator in Low Power Mode. + * + * retval #kStatus_Success Set System LDO Regulator drive strength in Low Power Mode successfully. + * retval #kStatus_SPC_SYSLDOLowDriveStrengthIgnore Attempt to specify low drive strength is ignored due to any + voltage detect feature is enabled in low power mode. + * retval #kStatus_SPC_BandgapModeWrong Bandgap mode in low power mode must be programmed to a value that enables + the bandgap if attempt to specify normal drive strength. + */ +status_t SPC_SetLowPowerModeSystemLDORegulatorDriveStrength(SPC_Type *base, spc_sys_ldo_drive_strength_t driveStrength) +{ + if (driveStrength == kSPC_SysLDO_LowDriveStrength) + { + /* If enabled any LVDs or HVDs, SPC will ignore the attempt to specify low drive strength. */ + if (SPC_GetLowPowerModeVoltageDetectStatus(base) != 0UL) + { + return kStatus_SPC_SYSLDOLowDriveStrengthIgnore; + } + } + else + { + /* If specify normal drive strength, bandgap must not be disabled. */ + if (SPC_GetLowPowerModeBandgapMode(base) == kSPC_BandgapDisabled) + { + return kStatus_SPC_BandgapModeWrong; + } + } + + base->LP_CFG = (base->LP_CFG & ~SPC_LP_CFG_SYSLDO_VDD_DS_MASK) | SPC_LP_CFG_SYSLDO_VDD_DS(driveStrength); + + return kStatus_Success; +} +#endif /* FSL_FEATURE_MCX_SPC_HAS_SYS_LDO */ + +#if (defined(FSL_FEATURE_MCX_SPC_HAS_DCDC) && FSL_FEATURE_MCX_SPC_HAS_DCDC) +/*! + * brief Configs DCDC VDD Regulator in Active mode. + * + * note When changing the DCDC output voltage level, take care to change the CORE LDO voltage level. + * + * param base SPC peripheral base address. + * param option Pointer to the spc_active_mode_DCDC_option_t structure. + * + * retval kStatus_Success Config DCDC regulator in Active power mode successful. + * retval kStatus_SPC_Busy The SPC instance is busy to execute any type of power mode transition. + * retval kStatus_SPC_BandgapModeWrong The bandgap mode setting in Active mode is wrong. + */ +status_t SPC_SetActiveModeDCDCRegulatorConfig(SPC_Type *base, const spc_active_mode_dcdc_option_t *option) +{ + assert(option != NULL); + status_t status = kStatus_Success; + + if ((base->SC & SPC_SC_BUSY_MASK) != 0UL) + { + /* + * $Line Coverage Justification$ + * $ref spc_c_ref_1$. + */ + return kStatus_SPC_Busy; + } + + status = SPC_SetActiveModeDCDCRegulatorDriveStrength(base, option->DCDCDriveStrength); + + if (status == kStatus_Success) + { + SPC_SetActiveModeDCDCRegulatorVoltageLevel(base, option->DCDCVoltage); + } + + /* + * $Branch Coverage Justification$ + * $ref spc_c_ref_1$. + */ + while ((base->SC & SPC_SC_BUSY_MASK) != 0UL) + { + } + + return status; +} + +/*! + * brief Set DCDC VDD Regulator drive strength in Active mode. + * + * note To set DCDC drive strength as Normal, the bandgap must be enabled. + * + * param base SPC peripheral base address. + * param driveStrength Specify the DCDC VDD regulator drive strength, please refer to @ref spc_dcdc_drive_strength_t. + * + * retval #kStatus_Success Set DCDC VDD Regulator drive strength in Active mode successfully. + * retval #kStatus_SPC_BandgapModeWrong Set DCDC VDD Regulator drive strength to Normal, the Bandgap must be enabled. + */ +status_t SPC_SetActiveModeDCDCRegulatorDriveStrength(SPC_Type *base, spc_dcdc_drive_strength_t driveStrength) +{ + if (driveStrength == kSPC_DCDC_NormalDriveStrength) + { + /* If specify normal drive strength, bandgap must not be disabled. */ + if (SPC_GetActiveModeBandgapMode(base) == kSPC_BandgapDisabled) + { + return kStatus_SPC_BandgapModeWrong; + } + } + + base->ACTIVE_CFG = + ((base->ACTIVE_CFG) & (~SPC_ACTIVE_CFG_DCDC_VDD_DS_MASK)) | SPC_ACTIVE_CFG_DCDC_VDD_DS(driveStrength); + + return kStatus_Success; +} + +/*! + * brief Configs DCDC VDD Regulator in Low power modes. + * + * If DCDC VDD Drive Strength is set to Normal, the Bandgap mode in Low Power mode must be programmed + * to a value that enables the Bandgap. + * In Deep Power Down mode, DCDC regulator is always turned off. + * + * param base SPC peripheral base address. + * param option Pointer to the spc_lowpower_mode_DCDC_option_t structure. + * + * retval kStatus_Success Config DCDC regulator in low power mode successfully. + * retval kStatus_SPC_Busy The SPC instance is busy to execute any type of power mode transition. + * retval kStatus_SPC_BandgapModeWrong The bandgap should be enabled before invoking this function. + */ +status_t SPC_SetLowPowerModeDCDCRegulatorConfig(SPC_Type *base, const spc_lowpower_mode_dcdc_option_t *option) +{ + if ((base->SC & SPC_SC_BUSY_MASK) != 0UL) + { + /* + * $Line Coverage Justification$ + * $ref spc_c_ref_1$. + */ + return kStatus_SPC_Busy; + } + + /* Check input parameter before setting registers. */ + if ((option->DCDCDriveStrength == kSPC_DCDC_NormalDriveStrength) && + (SPC_GetLowPowerModeBandgapMode(base) == kSPC_BandgapDisabled)) + { + return kStatus_SPC_BandgapModeWrong; + } + + /* + 1. Configure to desired voltage level. + 2. Change to low drive strength. + 3. Configure same voltage level in active mode. + */ + SPC_SetLowPowerModeDCDCRegulatorVoltageLevel(base, option->DCDCVoltage); + + /* Change to desired drive strength. */ + if (option->DCDCDriveStrength != kSPC_DCDC_LowDriveStrength) + { + (void)SPC_SetLowPowerModeDCDCRegulatorDriveStrength(base, option->DCDCDriveStrength); + } + + /* + * $Branch Coverage Justification$ + * $ref spc_c_ref_1$. + */ + while ((base->SC & SPC_SC_BUSY_MASK) != 0UL) + { + } + + return kStatus_Success; +} + +/*! + * brief Set DCDC VDD Regulator drive strength in Low power mode. + * + * param base SPC peripheral base address. + * param driveStrength Specify the DCDC VDD Regulator drive strength, please refer to @ref spc_dcdc_drive_strength_t. + * + * retval #kStatus_Success Set DCDC VDD Regulator drive strength in Low power mode successfully. + * retval #kStatus_SPC_BandgapModeWrong Set DCDC VDD Regulator drive strength to Normal, the Bandgap must be enabled. + */ +status_t SPC_SetLowPowerModeDCDCRegulatorDriveStrength(SPC_Type *base, spc_dcdc_drive_strength_t driveStrength) +{ + if (driveStrength == kSPC_DCDC_NormalDriveStrength) + { + /* If specify normal drive strength, bandgap must not be disabled. */ + if (SPC_GetLowPowerModeBandgapMode(base) == kSPC_BandgapDisabled) + { + return kStatus_SPC_BandgapModeWrong; + } + } + + base->LP_CFG = ((base->LP_CFG) & (~SPC_LP_CFG_DCDC_VDD_DS_MASK)) | SPC_LP_CFG_DCDC_VDD_DS(driveStrength); + + return kStatus_Success; +} + +/*! + * brief Config DCDC Burst options + * + * param base SPC peripheral base address. + * param config Pointer to spc_DCDC_burst_config_t structure. + */ +void SPC_SetDCDCBurstConfig(SPC_Type *base, spc_dcdc_burst_config_t *config) +{ + assert(config != NULL); + uint32_t reg; + reg = base->DCDC_CFG; + reg &= ~(SPC_DCDC_CFG_FREQ_CNTRL_MASK | SPC_DCDC_CFG_FREQ_CNTRL_ON_MASK); + reg |= SPC_DCDC_CFG_FREQ_CNTRL(config->freq); + reg |= config->stabilizeBurstFreq ? SPC_DCDC_CFG_FREQ_CNTRL_ON(1U) : SPC_DCDC_CFG_FREQ_CNTRL_ON(0U); + base->DCDC_CFG = reg; + + /* Blocking until previous DCDC burst completed. */ + while ((base->DCDC_BURST_CFG & SPC_DCDC_BURST_CFG_BURST_ACK_MASK) == 0UL) + { + } + + if ((config->sofwareBurstRequest) || (config->externalBurstRequest)) + { + /* Clear DCDC burst acknowledge flag. */ + base->DCDC_BURST_CFG |= SPC_DCDC_BURST_CFG_BURST_ACK_MASK; + } + base->DCDC_BURST_CFG |= SPC_DCDC_BURST_CFG_EXT_BURST_EN(config->externalBurstRequest); + + if (config->sofwareBurstRequest) + { + base->DCDC_BURST_CFG |= SPC_DCDC_BURST_CFG_BURST_REQ_MASK; + } +} + +/*! + * brief Set the count value of the reference clock. + * + * This function set the count value of the reference clock to control the frequency + * of dcdc refresh when dcdc is configured in Pulse Refresh mode. + * + * param base SPC peripheral base address. + * param count The count value, 16 bit width. + */ +void SPC_SetDCDCRefreshCount(SPC_Type *base, uint16_t count) +{ + uint32_t reg; + + reg = base->DCDC_BURST_CFG; + reg &= ~SPC_DCDC_BURST_CFG_PULSE_REFRESH_CNT_MASK; + reg |= SPC_DCDC_BURST_CFG_PULSE_REFRESH_CNT(count); + + base->DCDC_BURST_CFG = reg; +} +#endif /* FSL_FEATURE_MCX_SPC_HAS_DCDC */ + +/*! + * brief Configs all settings of regulators in Active mode at a time. + * + * @note This function is used to overwrite all settings of regulators(including bandgap mode, regulators' + * drive strength and voltage level) in active mode at a time. + * + * @note Enable/disable LVDs/HVDs before invoking this function. + * + * @note This function will check input parameters based on hardware restrictions before setting registers, if input + * parameters do not satisfy hardware restrictions the specific error will be reported. + * + * + * @note Some hardware restrictions not covered, application should be aware of this and follow this hardware + * restrictions otherwise some unknown issue may occur: + * 1. If Core LDO's drive strength are set to same value in both Active mode and low power mode, + * the voltage level should also set to same value. + * 2. When switching Core LDO's drive strength from low to normal, ensure the LDO_CORE high voltage level is set + * to same level that was set prior to switching to the LDO_CORE drive strength. Otherwise, if the LVDs are + * enabled, an unexpected LVD can occur. + * + * @note If this function can not satisfy some tricky settings, please invoke other low-level functions. + * + * param base SPC peripheral base address. + * param config Pointer to spc_active_mode_regulators_config_t structure. + * retval kStatus_Success Config regulators in Active power mode successful. + * retval kStatus_SPC_BandgapModeWrong The bandgap mode setting in Active mode is wrong. + * retval kStatus_SPC_Busy The SPC instance is busy to execute any type of power mode transition. + * retval kStatus_SPC_CORELDOVoltageWrong The selected voltage level in active mode is not allowed. + * retval kStatus_SPC_SYSLDOOverDriveVoltageFail Fail to regulator to Over Drive Voltage. + * retval kStatus_SPC_SYSLDOLowDriveStrengthIgnore Set driver strength to Low will be ignored. + * retval kStatus_SPC_DCDCLowDriveStrengthIgnore Set driver strength to Low will be ignored. + */ +status_t SPC_SetActiveModeRegulatorsConfig(SPC_Type *base, const spc_active_mode_regulators_config_t *config) +{ + assert(config != NULL); + + uint32_t activeModeVDValue = SPC_GetActiveModeVoltageDetectStatus(base); + + /* Check input parameters */ + /* 1. Bandgap should not be disabled if any of regulator in normal drive strength or + if any of LVDs/HVDs are enabled or if VDD CORE glitch detect are enabled. */ + if ((config->bandgapMode == kSPC_BandgapDisabled) && + ((activeModeVDValue != 0UL) +#if !(defined(FSL_FEATURE_MCX_SPC_HAS_NO_GLITCH_DETECT) && FSL_FEATURE_MCX_SPC_HAS_NO_GLITCH_DETECT) + || (SPC_CheckActiveModeVddCoreGlitchDetectEnabled(base) == true) +#endif /* FSL_FEATURE_MCX_SPC_HAS_NO_GLITCH_DETECT */ +#if (defined(FSL_FEATURE_MCX_SPC_HAS_DCDC) && FSL_FEATURE_MCX_SPC_HAS_DCDC) + || (config->DCDCOption.DCDCDriveStrength == kSPC_DCDC_NormalDriveStrength) +#endif /* FSL_FEATURE_MCX_SPC_HAS_DCDC */ +#if (defined(FSL_FEATURE_MCX_SPC_HAS_SYS_LDO) && FSL_FEATURE_MCX_SPC_HAS_SYS_LDO) + || (config->SysLDOOption.SysLDODriveStrength == kSPC_SysLDO_NormalDriveStrength) +#endif /* FSL_FEATURE_MCX_SPC_HAS_SYS_LDO */ +#if (defined(FSL_FEATURE_SPC_HAS_CORELDO_VDD_DS) && FSL_FEATURE_SPC_HAS_CORELDO_VDD_DS) + || (config->CoreLDOOption.CoreLDODriveStrength == kSPC_CoreLDO_NormalDriveStrength) +#endif /* FSL_FEATURE_SPC_HAS_CORELDO_VDD_DS */ + )) + { + return kStatus_SPC_BandgapModeWrong; + } + +#if (defined(FSL_FEATURE_MCX_SPC_HAS_SYS_LDO) && FSL_FEATURE_MCX_SPC_HAS_SYS_LDO) + /* 2. Must disable system LDO high voltage detector before specifying SysLDO to overdrive voltage */ + if (((activeModeVDValue & SPC_ACTIVE_CFG_SYS_HVDE_MASK) != 0UL) && + (config->SysLDOOption.SysLDOVoltage == kSPC_SysLDO_OverDriveVoltage)) + { + return kStatus_SPC_SYSLDOOverDriveVoltageFail; + } +#endif /* FSL_FEATURE_MCX_SPC_HAS_SYS_LDO */ + +#if (defined(FSL_FEATURE_MCX_SPC_HAS_SYS_LDO) && FSL_FEATURE_MCX_SPC_HAS_SYS_LDO) + /* 3. To set System LDO's drive strength to low, all LVDs and HVDs must be disabled. */ + if ((activeModeVDValue != 0UL) && (config->SysLDOOption.SysLDODriveStrength == kSPC_SysLDO_LowDriveStrength)) + { + return kStatus_SPC_SYSLDOLowDriveStrengthIgnore; + } +#endif /* FSL_FEATURE_MCX_SPC_HAS_SYS_LDO */ + +#if (defined(FSL_FEATURE_SPC_HAS_CORELDO_VDD_DS) && FSL_FEATURE_SPC_HAS_CORELDO_VDD_DS) + /* 4. To set Core LDO's drive strength to low, all LVDs and HVDs must be disabled. */ + if ((activeModeVDValue != 0UL) && (config->CoreLDOOption.CoreLDODriveStrength == kSPC_CoreLDO_LowDriveStrength)) + { + return kStatus_SPC_CORELDOLowDriveStrengthIgnore; + } +#endif /* FSL_FEATURE_SPC_HAS_CORELDO_VDD_DS */ + +#if (defined(FSL_FEATURE_MCX_SPC_HAS_DCDC) && FSL_FEATURE_MCX_SPC_HAS_DCDC) + /* 5. Core LDO and DCDC should have same voltage level. */ + if ((uint8_t)config->DCDCOption.DCDCVoltage != (uint8_t)config->CoreLDOOption.CoreLDOVoltage) + { + return kStatus_SPC_CORELDOVoltageWrong; + } +#endif /* FSL_FEATURE_MCX_SPC_HAS_DCDC */ + + if ((base->SC & SPC_SC_BUSY_MASK) != 0UL) + { + return kStatus_SPC_Busy; + } + + base->ACTIVE_CFG = + ((base->ACTIVE_CFG) & ~(SPC_ACTIVE_CFG_BGMODE_MASK)) | SPC_ACTIVE_CFG_BGMODE(config->bandgapMode); +#if (defined(FSL_FEATURE_MCX_SPC_HAS_LPBUFF_EN_BIT) && FSL_FEATURE_MCX_SPC_HAS_LPBUFF_EN_BIT) + SPC_EnableActiveModeCMPBandgapBuffer(base, config->lpBuff); +#endif /* FSL_FEATURE_MCX_SPC_HAS_LPBUFF_EN_BIT */ + +#if (defined(FSL_FEATURE_MCX_SPC_HAS_SYS_LDO) && FSL_FEATURE_MCX_SPC_HAS_SYS_LDO) + (void)SPC_SetActiveModeSystemLDORegulatorConfig(base, &config->SysLDOOption); +#endif /* FSL_FEATURE_MCX_SPC_HAS_SYS_LDO */ + +#if (defined(FSL_FEATURE_MCX_SPC_HAS_DCDC) && FSL_FEATURE_MCX_SPC_HAS_DCDC) + (void)SPC_SetActiveModeDCDCRegulatorConfig(base, &config->DCDCOption); +#endif /* FSL_FEATURE_MCX_SPC_HAS_DCDC */ + + (void)SPC_SetActiveModeCoreLDORegulatorConfig(base, &config->CoreLDOOption); + + return kStatus_Success; +} + +/*! + * brief Configs regulators in Low Power mode. + * + * This function provides the method to config all on-chip regulators in Low Power mode. + * + * param base SPC peripheral base address. + * param config Pointer to spc_lowpower_mode_regulators_config_t structure. + * retval #kStatus_Success Config regulators in Low power mode successful. + * retval #kStatus_SPC_BandgapModeWrong The bandgap should not be disabled based on input settings. + * retval #kStatus_SPC_CORELDOLowDriveStrengthIgnore Set driver strength to low will be ignored. + * retval #kStatus_SPC_SYSLDOLowDriveStrengthIgnore Set driver strength to low will be ignored. + * retval #kStatus_SPC_CORELDOVoltageWrong Core LDO and System LDO do not have same voltage level. + */ +status_t SPC_SetLowPowerModeRegulatorsConfig(SPC_Type *base, const spc_lowpower_mode_regulators_config_t *config) +{ + assert(config != NULL); + uint32_t lpModeVDValue = SPC_GetLowPowerModeVoltageDetectStatus(base); + + /* Check input parameters */ + /* 1. Bandgap should not be disabled if any of regulator in normal drive strength or + if any of LVDs/HVDs are enabled or if VDD CORE glitch detect are enabled. */ + if ((config->bandgapMode == kSPC_BandgapDisabled) && + ((lpModeVDValue != 0UL) +#if !(defined(FSL_FEATURE_MCX_SPC_HAS_NO_GLITCH_DETECT) && FSL_FEATURE_MCX_SPC_HAS_NO_GLITCH_DETECT) + || (SPC_CheckLowPowerModeVddCoreGlitchDetectEnabled(base) == true) +#endif /* FSL_FEATURE_MCX_SPC_HAS_NO_GLITCH_DETECT */ +#if (defined(FSL_FEATURE_MCX_SPC_HAS_DCDC) && FSL_FEATURE_MCX_SPC_HAS_DCDC) + || (config->DCDCOption.DCDCDriveStrength == kSPC_DCDC_NormalDriveStrength) +#endif /* FSL_FEATURE_MCX_SPC_HAS_DCDC */ +#if (defined(FSL_FEATURE_MCX_SPC_HAS_SYS_LDO) && FSL_FEATURE_MCX_SPC_HAS_SYS_LDO) + || (config->SysLDOOption.SysLDODriveStrength == kSPC_SysLDO_NormalDriveStrength) +#endif /* FSL_FEATURE_MCX_SPC_HAS_SYS_LDO */ +#if (defined(FSL_FEATURE_SPC_HAS_CORELDO_VDD_DS) && FSL_FEATURE_SPC_HAS_CORELDO_VDD_DS) + || (config->CoreLDOOption.CoreLDODriveStrength == kSPC_CoreLDO_NormalDriveStrength) +#endif /* FSL_FEATURE_SPC_HAS_CORELDO_VDD_DS */ + )) + { + return kStatus_SPC_BandgapModeWrong; + } + +#if (defined(FSL_FEATURE_MCX_SPC_HAS_SYS_LDO) && FSL_FEATURE_MCX_SPC_HAS_SYS_LDO) + /* 2. To set System LDO's drive strength to low, all LVDs and HVDs must be disabled. */ + if ((lpModeVDValue != 0UL) && (config->SysLDOOption.SysLDODriveStrength == kSPC_SysLDO_LowDriveStrength)) + { + return kStatus_SPC_SYSLDOLowDriveStrengthIgnore; + } +#endif /* FSL_FEATURE_MCX_SPC_HAS_SYS_LDO */ + +#if (defined(FSL_FEATURE_SPC_HAS_CORELDO_VDD_DS) && FSL_FEATURE_SPC_HAS_CORELDO_VDD_DS) + /* 3. To set Core LDO's drive strength to low, all LVDs and HVDs must be disabled. */ + if ((lpModeVDValue != 0UL) && (config->CoreLDOOption.CoreLDODriveStrength == kSPC_CoreLDO_LowDriveStrength)) + { + return kStatus_SPC_CORELDOLowDriveStrengthIgnore; + } +#endif /* FSL_FEATURE_SPC_HAS_CORELDO_VDD_DS */ + +#if (defined(FSL_FEATURE_MCX_SPC_HAS_DCDC) && FSL_FEATURE_MCX_SPC_HAS_DCDC) + /* 5. Core LDO and DCDC should have same voltage level. */ + if ((uint8_t)config->DCDCOption.DCDCVoltage != (uint8_t)config->CoreLDOOption.CoreLDOVoltage) + { + return kStatus_SPC_CORELDOVoltageWrong; + } +#endif /* FSL_FEATURE_MCX_SPC_HAS_DCDC */ + base->LP_CFG = ((base->LP_CFG) & ~(SPC_LP_CFG_BGMODE_MASK)) | SPC_LP_CFG_BGMODE(config->bandgapMode); +#if (defined(FSL_FEATURE_MCX_SPC_HAS_LPBUFF_EN_BIT) && FSL_FEATURE_MCX_SPC_HAS_LPBUFF_EN_BIT) + SPC_EnableLowPowerModeCMPBandgapBuffer(base, config->lpBuff); +#endif /* FSL_FEATURE_MCX_SPC_HAS_LPBUFF_EN_BIT */ +#if (defined(FSL_FEATURE_MCX_SPC_HAS_COREVDD_IVS_EN_BIT) && FSL_FEATURE_MCX_SPC_HAS_COREVDD_IVS_EN_BIT) + SPC_EnableLowPowerModeCoreVDDInternalVoltageScaling(base, config->CoreIVS); +#endif /* FSL_FEATURE_MCX_SPC_HAS_COREVDD_IVS_EN_BIT */ + SPC_EnableLowPowerModeLowPowerIREF(base, config->lpIREF); + +#if (defined(FSL_FEATURE_MCX_SPC_HAS_SYS_LDO) && FSL_FEATURE_MCX_SPC_HAS_SYS_LDO) + (void)SPC_SetLowPowerModeSystemLDORegulatorConfig(base, &config->SysLDOOption); +#endif /* FSL_FEATURE_MCX_SPC_HAS_SYS_LDO */ + +#if (defined(FSL_FEATURE_MCX_SPC_HAS_DCDC) && FSL_FEATURE_MCX_SPC_HAS_DCDC) + (void)SPC_SetLowPowerModeDCDCRegulatorConfig(base, &config->DCDCOption); +#endif /* FSL_FEATURE_MCX_SPC_HAS_DCDC */ + + (void)SPC_SetLowPowerModeCoreLDORegulatorConfig(base, &config->CoreLDOOption); + + return kStatus_Success; +} diff --git a/hw/bsp/mcx/drivers/spc/fsl_spc.h b/hw/bsp/mcx/drivers/spc/fsl_spc.h new file mode 100644 index 000000000..69a001098 --- /dev/null +++ b/hw/bsp/mcx/drivers/spc/fsl_spc.h @@ -0,0 +1,2433 @@ +/* + * Copyright 2022-2024 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef FSL_SPC_H_ +#define FSL_SPC_H_ +#include "fsl_common.h" + +/*! + * @addtogroup mcx_spc + * @{ + */ + +/******************************************************************************* + * Definitions + ******************************************************************************/ + +/*! @name Driver version */ +/*! @{ */ +/*! @brief SPC driver version 2.4.2. */ +#define FSL_SPC_DRIVER_VERSION (MAKE_VERSION(2, 4, 2)) +/*! @} */ + +#define SPC_EVD_CFG_REG_EVDISO_SHIFT 0UL +#define SPC_EVD_CFG_REG_EVDLPISO_SHIFT 8UL +#define SPC_EVD_CFG_REG_EVDSTAT_SHIFT 16UL + +#define SPC_EVD_CFG_REG_EVDISO(x) ((uint32_t)(x) << SPC_EVD_CFG_REG_EVDISO_SHIFT) +#define SPC_EVD_CFG_REG_EVDLPISO(x) ((uint32_t)(x) << SPC_EVD_CFG_REG_EVDLPISO_SHIFT) +#define SPC_EVD_CFG_REG_EVDSTAT(x) ((uint32_t)(x) << SPC_EVD_CFG_REG_EVDSTAT_SHIFT) + +#if (defined(SPC_GLITCH_DETECT_SC_CNT_SELECT_MASK)) +#define VDD_CORE_GLITCH_DETECT_SC GLITCH_DETECT_SC +#define SPC_VDD_CORE_GLITCH_DETECT_SC_GLITCH_DETECT_FLAG_MASK SPC_GLITCH_DETECT_SC_GLITCH_DETECT_FLAG_MASK +#define SPC_VDD_CORE_GLITCH_DETECT_SC_GLITCH_DETECT_FLAG SPC_GLITCH_DETECT_SC_GLITCH_DETECT_FLAG +#define SPC_VDD_CORE_GLITCH_DETECT_SC_LOCK_MASK SPC_GLITCH_DETECT_SC_LOCK_MASK +#define SPC_VDD_CORE_GLITCH_DETECT_SC_CNT_SELECT_MASK SPC_GLITCH_DETECT_SC_CNT_SELECT_MASK +#define SPC_VDD_CORE_GLITCH_DETECT_SC_CNT_SELECT SPC_GLITCH_DETECT_SC_CNT_SELECT +#define SPC_VDD_CORE_GLITCH_DETECT_SC_RE_MASK SPC_GLITCH_DETECT_SC_RE_MASK +#define SPC_VDD_CORE_GLITCH_DETECT_SC_RE SPC_GLITCH_DETECT_SC_RE +#define SPC_VDD_CORE_GLITCH_DETECT_SC_TIMEOUT_MASK SPC_GLITCH_DETECT_SC_TIMEOUT_MASK +#define SPC_VDD_CORE_GLITCH_DETECT_SC_TIMEOUT SPC_GLITCH_DETECT_SC_TIMEOUT +#define SPC_VDD_CORE_GLITCH_DETECT_SC_IE_MASK SPC_GLITCH_DETECT_SC_IE_MASK +#define SPC_VDD_CORE_GLITCH_DETECT_SC_IE SPC_GLITCH_DETECT_SC_IE +#endif + +/*! + * @brief SPC status enumeration. + * + * @note Some device(such as MCXA family) do not equip DCDC or System LDO, please refer to the reference manual + * to check. + */ +enum +{ + kStatus_SPC_Busy = MAKE_STATUS(kStatusGroup_SPC, 0U), /*!< The SPC instance is busy executing any + type of power mode transition. */ +#if (defined(FSL_FEATURE_MCX_SPC_HAS_DCDC) && FSL_FEATURE_MCX_SPC_HAS_DCDC) + kStatus_SPC_DCDCLowDriveStrengthIgnore = MAKE_STATUS(kStatusGroup_SPC, 1U), /*!< DCDC Low drive strength setting be + ignored for LVD/HVD enabled. */ + kStatus_SPC_DCDCPulseRefreshModeIgnore = MAKE_STATUS(kStatusGroup_SPC, 2U), /*!< DCDC Pulse Refresh Mode drive + strength setting be ignored for LVD/HVD enabled. */ +#endif /* FSL_FEATURE_MCX_SPC_HAS_DCDC */ +#if (defined(FSL_FEATURE_MCX_SPC_HAS_SYS_LDO) && FSL_FEATURE_MCX_SPC_HAS_SYS_LDO) + kStatus_SPC_SYSLDOOverDriveVoltageFail = MAKE_STATUS(kStatusGroup_SPC, 3U), /*!< SYS LDO regulate to Over drive + voltage failed for SYS LDO HVD must be disabled. */ + kStatus_SPC_SYSLDOLowDriveStrengthIgnore = MAKE_STATUS(kStatusGroup_SPC, 4U), /*!< SYS LDO Low driver strength + setting be ignored for LDO LVD/HVD enabled. */ +#endif /* FSL_FEATURE_MCX_SPC_HAS_SYS_LDO */ + kStatus_SPC_CORELDOLowDriveStrengthIgnore = MAKE_STATUS(kStatusGroup_SPC, 5U), /*!< CORE LDO Low driver strength + setting be ignored for LDO LVD/HVD enabled. */ + kStatus_SPC_CORELDOVoltageWrong = MAKE_STATUS(kStatusGroup_SPC, 7U), /*!< Core LDO voltage is wrong. */ + kStatus_SPC_CORELDOVoltageSetFail = MAKE_STATUS(kStatusGroup_SPC, 8U), /*!< Core LDO voltage set fail. */ + kStatus_SPC_BandgapModeWrong = MAKE_STATUS(kStatusGroup_SPC, 6U), /*!< Selected Bandgap Mode wrong. */ +}; + +/*! + * @brief Voltage Detect Status Flags. + */ +enum _spc_voltage_detect_flags +{ +#if (defined(FSL_FEATURE_MCX_SPC_HAS_IOVDD_VD) && FSL_FEATURE_MCX_SPC_HAS_IOVDD_VD) + kSPC_IOVDDHighVoltageDetectFlag = SPC_VD_STAT_IOVDD_HVDF_MASK, /*!< IO VDD High-Voltage detect flag. */ + kSPC_IOVDDLowVoltageDetectFlag = SPC_VD_STAT_IOVDD_LVDF_MASK, /*!< IO VDD Low-Voltage detect flag. */ +#endif /* FSL_FEATURE_MCX_SPC_HAS_IOVDD_VD */ + kSPC_SystemVDDHighVoltageDetectFlag = SPC_VD_STAT_SYSVDD_HVDF_MASK, /*!< System VDD High-Voltage detect flag. */ + kSPC_SystemVDDLowVoltageDetectFlag = SPC_VD_STAT_SYSVDD_LVDF_MASK, /*!< System VDD Low-Voltage detect flag. */ +#if (defined(FSL_FEATURE_MCX_SPC_HAS_COREVDD_HVD) && FSL_FEATURE_MCX_SPC_HAS_COREVDD_HVD) + kSPC_CoreVDDHighVoltageDetectFlag = SPC_VD_STAT_COREVDD_HVDF_MASK, /*!< Core VDD High-Voltage detect flag. */ +#endif /* FSL_FEATURE_MCX_SPC_HAS_COREVDD_HVD */ + kSPC_CoreVDDLowVoltageDetectFlag = SPC_VD_STAT_COREVDD_LVDF_MASK, /*!< Core VDD Low-Voltage detect flag. */ +}; + +/*! + * @brief SPC power domain isolation status. + * @note Some devices(such as MCXA family) do not contain WAKE Power Domain, please refer to the reference manual to + * check. + */ +enum _spc_power_domains +{ + kSPC_MAINPowerDomainRetain = 1UL << 16U, /*!< Peripherals and IO pads retain in MAIN Power Domain. */ + kSPC_WAKEPowerDomainRetain = 1UL << 17U, /*!< Peripherals and IO pads retain in WAKE Power Domain. */ +}; + +/*! + * @brief The enumeration of all analog module that can be controlled by SPC in active or low-power modes. + * @anchor spc_analog_module_control + */ +enum _spc_analog_module_control +{ + kSPC_controlVref = 1UL << 0UL, /*!< Enable/disable VREF in active or low-power modes. */ + kSPC_controlUsb3vDet = 1UL << 1UL, /*!< Enable/disable USB3V_Det in active or low-power modes. */ + kSPC_controlDac0 = 1UL << 4UL, /*!< Enable/disable DAC0 in active or low-power modes. */ + kSPC_controlDac1 = 1UL << 5UL, /*!< Enable/disable DAC1 in active or low-power modes. */ + kSPC_controlDac2 = 1UL << 6UL, /*!< Enable/disable DAC2 in active or low-power modes. */ + kSPC_controlOpamp0 = 1UL << 8UL, /*!< Enable/disable OPAMP0 in active or low-power modes. */ + kSPC_controlOpamp1 = 1UL << 9UL, /*!< Enable/disable OPAMP1 in active or low-power modes. */ + kSPC_controlOpamp2 = 1UL << 10UL, /*!< Enable/disable OPAMP2 in active or low-power modes. */ + kSPC_controlCmp0 = 1UL << 16UL, /*!< Enable/disable CMP0 in active or low-power modes. */ + kSPC_controlCmp1 = 1UL << 17UL, /*!< Enable/disable CMP1 in active or low-power modes. */ + kSPC_controlCmp2 = 1UL << 18UL, /*!< Enable/disable CMP2 in active or low-power modes. */ + kSPC_controlCmp0Dac = 1UL << 20UL, /*!< Enable/disable CMP0_DAC in active or low-power modes. */ + kSPC_controlCmp1Dac = 1UL << 21UL, /*!< Enable/disable CMP1_DAC in active or low-power modes. */ + kSPC_controlCmp2Dac = 1UL << 22UL, /*!< Enable/disable CMP2_DAC in active or low-power modes. */ + kSPC_controlAllModules = 0x770773UL, /*!< Enable/disable all modules in active or low-power modes. */ +}; + +/*! + * @brief The enumeration of spc power domain, the connected power domain is chip specific, please refer to chip's RM + * for details. + */ +typedef enum _spc_power_domain_id +{ + kSPC_PowerDomain0 = 0U, /*!< Power domain0, the connected power domain is chip specific. */ + kSPC_PowerDomain1 = 1U, /*!< Power domain1, the connected power domain is chip specific. */ +} spc_power_domain_id_t; + +/*! + * @brief The enumeration of Power domain's low power mode. + */ +typedef enum _spc_power_domain_low_power_mode +{ + kSPC_SleepWithSYSClockRunning = 0U, /*!< Power domain request SLEEP mode with SYS clock running. */ + kSPC_DeepSleepWithSysClockOff = 1U, /*!< Power domain request deep sleep mode with system clock off. */ + kSPC_PowerDownWithSysClockOff = 2U, /*!< Power domain request power down mode with system clock off. */ + kSPC_DeepPowerDownWithSysClockOff = 4U, /*!< Power domain request deep power down mode with system clock off. */ +} spc_power_domain_low_power_mode_t; + +/*! + * @brief SPC low power request output pin polarity. + */ +typedef enum _spc_lowPower_request_pin_polarity +{ + kSPC_HighTruePolarity = 0x0U, /*!< Control the High Polarity of the Low Power Request Pin. */ + kSPC_LowTruePolarity = 0x1U, /*!< Control the Low Polarity of the Low Power Request Pin. */ +} spc_lowpower_request_pin_polarity_t; + +/*! + * @brief SPC low power request output override. + */ +typedef enum _spc_lowPower_request_output_override +{ + kSPC_LowPowerRequestNotForced = 0x0U, /*!< Not Forced. */ + kSPC_LowPowerRequestReserved = 0x1U, /*!< Reserved. */ + kSPC_LowPowerRequestForcedLow = 0x2U, /*!< Forced Low (Ignore LowPower request output polarity setting.) */ + kSPC_LowPowerRequestForcedHigh = 0x3U, /*!< Forced High (Ignore LowPower request output polarity setting.) */ +} spc_lowpower_request_output_override_t; + +/*! + * @brief SPC Bandgap mode enumeration in Active mode or Low Power mode. + */ +typedef enum _spc_bandgap_mode +{ + kSPC_BandgapDisabled = 0x0U, /*!< Bandgap disabled. */ + kSPC_BandgapEnabledBufferDisabled = 0x1U, /*!< Bandgap enabled with Buffer disabled. */ + kSPC_BandgapEnabledBufferEnabled = 0x2U, /*!< Bandgap enabled with Buffer enabled. */ + kSPC_BandgapReserved = 0x3U, /*!< Reserved. */ +} spc_bandgap_mode_t; + +#if (defined(FSL_FEATURE_MCX_SPC_HAS_DCDC) && FSL_FEATURE_MCX_SPC_HAS_DCDC) +/*! + * @brief DCDC regulator voltage level enumeration in Active mode or Low Power Mode. + * + * @note #kSPC_DCDC_RetentionVoltage not supported for all power modes. + */ +typedef enum _spc_dcdc_voltage_level +{ + kSPC_DCDC_RetentionVoltage = 0x0U, /*!< DCDC_CORE Regulator regulate to retention + Voltage(Only supportedin low power modes) */ + kSPC_DCDC_MidVoltage = 0x1U, /*!< DCDC_CORE Regulator regulate to Mid Voltage(1.0V). */ + kSPC_DCDC_NormalVoltage = 0x2U, /*!< DCDC_CORE Regulator regulate to Normal Voltage(1.1V). */ + kSPC_DCDC_OverdriveVoltage = 0x3U, /*!< DCDC_CORE Regulator regulate to Safe-Mode Voltage(1.2V). */ +} spc_dcdc_voltage_level_t; + +/*! + * @brief DCDC regulator Drive Strength enumeration in Active mode or Low Power Mode. + * + * @note Different drive strength differ in these DCDC characteristics: + * Maximum load current + * Quiescent current + * Transient response. + */ +typedef enum _spc_dcdc_drive_strength +{ + kSPC_DCDC_PulseRefreshMode = 0x0U, /*!< DCDC_CORE Regulator Drive Strength set to Pulse Refresh Mode, + * This enum member is only useful for Low Power Mode config, please + * note that pulse refresh mode is invalid in SLEEP mode. + */ + kSPC_DCDC_LowDriveStrength = 0x1U, /*!< DCDC_CORE regulator Drive Strength set to low. */ + kSPC_DCDC_NormalDriveStrength = 0x2U, /*!< DCDC_CORE regulator Drive Strength set to Normal. */ +} spc_dcdc_drive_strength_t; +#endif /* FSL_FEATURE_MCX_SPC_HAS_DCDC */ + +#if (defined(FSL_FEATURE_MCX_SPC_HAS_SYS_LDO) && FSL_FEATURE_MCX_SPC_HAS_SYS_LDO) +/*! + * @brief SYS LDO regulator voltage level enumeration in Active mode. + */ +typedef enum _spc_sys_ldo_voltage_level +{ + kSPC_SysLDO_NormalVoltage = 0x0U, /*!< SYS LDO VDD Regulator regulate to Normal Voltage(1.8V). */ + kSPC_SysLDO_OverDriveVoltage = 0x1U, /*!< SYS LDO VDD Regulator regulate to Over Drive Voltage(2.5V). */ +} spc_sys_ldo_voltage_level_t; + +/*! + * @brief SYS LDO regulator Drive Strength enumeration in Active mode or Low Power mode. + */ +typedef enum _spc_sys_ldo_drive_strength +{ + kSPC_SysLDO_LowDriveStrength = 0x0U, /*!< SYS LDO VDD regulator Drive Strength set to low. */ + kSPC_SysLDO_NormalDriveStrength = 0x1U, /*!< SYS LDO VDD regulator Drive Strength set to Normal. */ +} spc_sys_ldo_drive_strength_t; +#endif /* FSL_FEATURE_MCX_SPC_HAS_SYS_LDO */ + +/*! + * @brief Core LDO regulator voltage level enumeration in Active mode or Low Power mode. + */ +typedef enum _spc_core_ldo_voltage_level +{ + kSPC_CoreLDO_UnderDriveVoltage = 0x0U, /*!< @deprecated, to align with description of latest RM, please use + #kSPC_Core_LDO_RetentionVoltage as instead. */ + kSPC_Core_LDO_RetentionVoltage = 0x0U, /*!< Core LDO VDD regulator regulate to retention voltage, please note that + only useful in low power modes and not all devices support this options + please refer to devices' RM for details. */ + kSPC_CoreLDO_MidDriveVoltage = 0x1U, /*!< Core LDO VDD regulator regulate to Mid Drive Voltage. */ + kSPC_CoreLDO_NormalVoltage = 0x2U, /*!< Core LDO VDD regulator regulate to Normal Voltage. */ + kSPC_CoreLDO_OverDriveVoltage = 0x3U, /*!< Core LDO VDD regulator regulate to overdrive Voltage. */ +} spc_core_ldo_voltage_level_t; + +/*! + * @brief CORE LDO VDD regulator Drive Strength enumeration in Low Power mode. + */ +typedef enum _spc_core_ldo_drive_strength +{ + kSPC_CoreLDO_LowDriveStrength = 0x0U, /*!< Core LDO VDD regulator Drive Strength set to low. */ + kSPC_CoreLDO_NormalDriveStrength = 0x1U, /*!< Core LDO VDD regulator Drive Strength set to Normal. */ +} spc_core_ldo_drive_strength_t; + +/*! + * @brief IO VDD Low-Voltage Level Select. + */ +typedef enum _spc_low_voltage_level_select +{ + kSPC_LowVoltageNormalLevel = 0x0U, /*!< @deprecated, please use kSPC_LowVoltageHighRange as instead. */ + kSPC_LowVoltageSafeLevel = 0x1U, /*!< @deprecated, please use kSPC_LowVoltageLowRange as instead. */ + + kSPC_LowVoltageHighRange = 0x0U, /*!< High range LVD threshold. */ + kSPC_LowVoltageLowRange = 0x1U, /*!< Low range LVD threshold. */ +} spc_low_voltage_level_select_t; + +#if !(defined(FSL_FEATURE_MCX_SPC_HAS_NO_GLITCH_DETECT) && FSL_FEATURE_MCX_SPC_HAS_NO_GLITCH_DETECT) +/*! + * @brief Used to select output of 4-bit ripple counter is used to monitor a glitch on VDD core. + */ +typedef enum _spc_vdd_core_glitch_ripple_counter_select +{ + kSPC_selectBit0Of4bitRippleCounter = 0x0U, /*!< Select bit-0 of 4-bit Ripple Counter + to detect glitch on VDD Core. */ + kSPC_selectBit1Of4bitRippleCounter = 0x1U, /*!< Select bit-1 of 4-bit Ripple Counter + to detect glitch on VDD Core. */ + kSPC_selectBit2Of4bitRippleCounter = 0x2U, /*!< Select bit-2 of 4-bit Ripple Counter + to detect glitch on VDD Core. */ + kSPC_selectBit3Of4bitRippleCounter = 0x3U, /*!< Select bit-3 of 4-bit Ripple Counter + to detect glitch on VDD Core. */ +} spc_vdd_core_glitch_ripple_counter_select_t; +#endif + +/*! + * @brief The list of the operating voltage for the SRAM's read/write timing margin. + */ +typedef enum _spc_sram_operate_voltage +{ + kSPC_sramOperateAt1P0V = 0x1U, /*!< SRAM configured for 1.0V operation. */ + kSPC_sramOperateAt1P1V = 0x2U, /*!< SRAM configured for 1.1V operation. */ + kSPC_sramOperateAt1P2V = 0x3U, /*!< SRAM configured for 1.2V operation. */ +} spc_sram_operate_voltage_t; + +#if !(defined(FSL_FEATURE_MCX_SPC_HAS_NO_GLITCH_DETECT) && FSL_FEATURE_MCX_SPC_HAS_NO_GLITCH_DETECT) +/*! + * @brief The configuration of VDD Core glitch detector. + */ +typedef struct _spc_vdd_core_glitch_detector_config +{ + spc_vdd_core_glitch_ripple_counter_select_t rippleCounterSelect; /*!< Used to set ripple counter. */ + uint8_t resetTimeoutValue; /*!< The timeout value used to reset glitch detect/compare logic after an initial + glitch is detected. */ + bool enableReset; /*!< Used to enable/disable POR/LVD reset that caused by CORE VDD glitch detect error. */ + bool enableInterrupt; /*!< Used to enable/disable hardware interrupt if CORE VDD glitch detect error. */ +} spc_vdd_core_glitch_detector_config_t; +#endif + +typedef struct _spc_sram_voltage_config +{ + spc_sram_operate_voltage_t operateVoltage; /*!< Specifies the operating voltage for the SRAM's + read/write timing margin. */ + bool requestVoltageUpdate; /*!< Used to control whether request an SRAM trim value change. */ +} spc_sram_voltage_config_t; + +/*! + * @brief Low Power Request output pin configuration. + */ +typedef struct _spc_lowpower_request_config +{ + bool enable; /*!< Low Power Request Output enable. */ + spc_lowpower_request_pin_polarity_t polarity; /*!< Low Power Request Output pin polarity select. */ + spc_lowpower_request_output_override_t override; /*!< Low Power Request Output Override. */ +} spc_lowpower_request_config_t; + +/*! + * @brief Core LDO regulator options in Active mode. + */ +typedef struct _spc_active_mode_core_ldo_option +{ + spc_core_ldo_voltage_level_t CoreLDOVoltage; /*!< Core LDO Regulator Voltage Level selection in Active mode. */ +#if defined(FSL_FEATURE_SPC_HAS_CORELDO_VDD_DS) && FSL_FEATURE_SPC_HAS_CORELDO_VDD_DS + spc_core_ldo_drive_strength_t CoreLDODriveStrength; /*!< Core LDO Regulator Drive Strength + selection in Active mode */ +#endif /* FSL_FEATURE_SPC_HAS_CORELDO_VDD_DS */ +} spc_active_mode_core_ldo_option_t; + +#if (defined(FSL_FEATURE_MCX_SPC_HAS_SYS_LDO) && FSL_FEATURE_MCX_SPC_HAS_SYS_LDO) +/*! + * @brief System LDO regulator options in Active mode. + */ +typedef struct _spc_active_mode_sys_ldo_option +{ + spc_sys_ldo_voltage_level_t SysLDOVoltage; /*!< System LDO Regulator Voltage Level selection in Active mode. */ + spc_sys_ldo_drive_strength_t SysLDODriveStrength; /*!< System LDO Regulator Drive Strength + selection in Active mode. */ +} spc_active_mode_sys_ldo_option_t; +#endif /* FSL_FEATURE_MCX_SPC_HAS_SYS_LDO */ + +#if (defined(FSL_FEATURE_MCX_SPC_HAS_DCDC) && FSL_FEATURE_MCX_SPC_HAS_DCDC) +/*! + * @brief DCDC regulator options in Active mode. + */ +typedef struct _spc_active_mode_dcdc_option +{ + spc_dcdc_voltage_level_t DCDCVoltage; /*!< DCDC Regulator Voltage Level selection in Active mode. */ + spc_dcdc_drive_strength_t DCDCDriveStrength; /*!< DCDC_CORE Regulator Drive Strength selection in Active mode. */ +} spc_active_mode_dcdc_option_t; +#endif /* FSL_FEATURE_MCX_SPC_HAS_DCDC */ + +/*! + * @brief Core LDO regulator options in Low Power mode. + */ +typedef struct _spc_lowpower_mode_core_ldo_option +{ + spc_core_ldo_voltage_level_t CoreLDOVoltage; /*!< Core LDO Regulator Voltage Level selection in Low Power mode. */ + spc_core_ldo_drive_strength_t CoreLDODriveStrength; /*!< Core LDO Regulator Drive Strength + selection in Low Power mode */ +} spc_lowpower_mode_core_ldo_option_t; + +#if (defined(FSL_FEATURE_MCX_SPC_HAS_SYS_LDO) && FSL_FEATURE_MCX_SPC_HAS_SYS_LDO) +/*! + * @brief System LDO regulator options in Low Power mode. + */ +typedef struct _spc_lowpower_mode_sys_ldo_option +{ + spc_sys_ldo_drive_strength_t SysLDODriveStrength; /*!< System LDO Regulator Drive Strength + selection in Low Power mode. */ +} spc_lowpower_mode_sys_ldo_option_t; +#endif /* FSL_FEATURE_MCX_SPC_HAS_SYS_LDO */ + +#if (defined(FSL_FEATURE_MCX_SPC_HAS_DCDC) && FSL_FEATURE_MCX_SPC_HAS_DCDC) +/*! + * @brief DCDC regulator options in Low Power mode. + */ +typedef struct _spc_lowpower_mode_dcdc_option +{ + spc_dcdc_voltage_level_t DCDCVoltage; /*!< DCDC Regulator Voltage Level selection in Low Power mode. */ + spc_dcdc_drive_strength_t DCDCDriveStrength; /*!< DCDC_CORE Regulator Drive Strength selection in Low Power mode. */ +} spc_lowpower_mode_dcdc_option_t; + +/*! + * @brief DCDC Burst configuration. + * @deprecated Do not recommend to use this structure. + */ +typedef struct _spc_dcdc_burst_config +{ + bool sofwareBurstRequest; /*!< Enable/Disable DCDC Software Burst Request. */ + bool externalBurstRequest; /*!< Enable/Disable DCDC External Burst Request. */ + bool stabilizeBurstFreq; /*!< Enable/Disable DCDC frequency stabilization. */ + uint8_t freq; /*!< The frequency of the current burst. */ +} spc_dcdc_burst_config_t; +#endif /* FSL_FEATURE_MCX_SPC_HAS_DCDC */ + +/*! + * @brief CORE/SYS/IO VDD Voltage Detect options. + */ +typedef struct _spc_voltage_detect_option +{ + bool HVDInterruptEnable; /*!< CORE/SYS/IO VDD High Voltage Detect interrupt enable. */ + bool HVDResetEnable; /*!< CORE/SYS/IO VDD High Voltage Detect reset enable. */ + bool LVDInterruptEnable; /*!< CORE/SYS/IO VDD Low Voltage Detect interrupt enable. */ + bool LVDResetEnable; /*!< CORE/SYS/IO VDD Low Voltage Detect reset enable. */ +} spc_voltage_detect_option_t; + +/*! + * @brief Core Voltage Detect configuration. + */ +typedef struct _spc_core_voltage_detect_config +{ + spc_voltage_detect_option_t option; /*!< Core VDD Voltage Detect option. */ +} spc_core_voltage_detect_config_t; + +/*! + * @brief System Voltage Detect Configuration. + */ +typedef struct _spc_system_voltage_detect_config +{ + spc_voltage_detect_option_t option; /*!< System VDD Voltage Detect option. */ + spc_low_voltage_level_select_t level; /*!< @deprecated, reserved for all devices, will removed in next release. */ +} spc_system_voltage_detect_config_t; + +#if (defined(FSL_FEATURE_MCX_SPC_HAS_IOVDD_VD) && FSL_FEATURE_MCX_SPC_HAS_IOVDD_VD) +/*! + * @brief IO Voltage Detect Configuration. + */ +typedef struct _spc_io_voltage_detect_config +{ + spc_voltage_detect_option_t option; /*!< IO VDD Voltage Detect option. */ + spc_low_voltage_level_select_t level; /*!< IO VDD Low-voltage level selection. */ +} spc_io_voltage_detect_config_t; +#endif /* FSL_FEATURE_MCX_SPC_HAS_IOVDD_VD */ + +/*! + * @brief Active mode configuration. + */ +typedef struct _spc_active_mode_regulators_config +{ + spc_bandgap_mode_t bandgapMode; /*!< Specify bandgap mode in active mode. */ + +#if (defined(FSL_FEATURE_MCX_SPC_HAS_LPBUFF_EN_BIT) && FSL_FEATURE_MCX_SPC_HAS_LPBUFF_EN_BIT) + bool lpBuff; /*!< Enable/disable CMP bandgap buffer. */ +#endif /* FSL_FEATURE_MCX_SPC_HAS_LPBUFF_EN_BIT */ + +#if (defined(FSL_FEATURE_MCX_SPC_HAS_DCDC) && FSL_FEATURE_MCX_SPC_HAS_DCDC) + spc_active_mode_dcdc_option_t DCDCOption; /*!< Specify DCDC configurations in active mode. */ +#endif /* FSL_FEATURE_MCX_SPC_HAS_DCDC */ + +#if (defined(FSL_FEATURE_MCX_SPC_HAS_SYS_LDO) && FSL_FEATURE_MCX_SPC_HAS_SYS_LDO) + spc_active_mode_sys_ldo_option_t SysLDOOption; /*!< Specify System LDO configurations in active mode. */ +#endif /* FSL_FEATURE_MCX_SPC_HAS_SYS_LDO */ + + spc_active_mode_core_ldo_option_t CoreLDOOption; /*!< Specify Core LDO configurations in active mode. */ +} spc_active_mode_regulators_config_t; + +/*! + * @brief Low Power Mode configuration. + */ +typedef struct _spc_lowpower_mode_regulators_config +{ + bool lpIREF; /*!< Enable/disable low power IREF in low power modes. */ + spc_bandgap_mode_t bandgapMode; /*!< Specify bandgap mode in low power modes. */ + +#if (defined(FSL_FEATURE_MCX_SPC_HAS_LPBUFF_EN_BIT) && FSL_FEATURE_MCX_SPC_HAS_LPBUFF_EN_BIT) + bool lpBuff; /*!< Enable/disable CMP bandgap buffer in low power modes. */ +#endif /* FSL_FEATURE_MCX_SPC_HAS_LPBUFF_EN_BIT */ + +#if (defined(FSL_FEATURE_MCX_SPC_HAS_COREVDD_IVS_EN_BIT) && FSL_FEATURE_MCX_SPC_HAS_COREVDD_IVS_EN_BIT) + bool CoreIVS; /*!< Enable/disable CORE VDD internal voltage scaling. */ +#endif /* FSL_FEATURE_MCX_SPC_HAS_COREVDD_IVS_EN_BIT */ + +#if (defined(FSL_FEATURE_MCX_SPC_HAS_DCDC) && FSL_FEATURE_MCX_SPC_HAS_DCDC) + spc_lowpower_mode_dcdc_option_t DCDCOption; /*!< Specify DCDC configurations in low power modes. */ +#endif /* FSL_FEATURE_MCX_SPC_HAS_DCDC */ + +#if (defined(FSL_FEATURE_MCX_SPC_HAS_SYS_LDO) && FSL_FEATURE_MCX_SPC_HAS_SYS_LDO) + spc_lowpower_mode_sys_ldo_option_t SysLDOOption; /*!< Specify system LDO configurations in low power modes. */ +#endif /* FSL_FEATURE_MCX_SPC_HAS_SYS_LDO */ + + spc_lowpower_mode_core_ldo_option_t CoreLDOOption; /*!< Specify core LDO configurations in low power modes. */ +} spc_lowpower_mode_regulators_config_t; + +/******************************************************************************* + * API + ******************************************************************************/ +#if defined(__cplusplus) +extern "C" { +#endif /* __cplusplus */ + +/*! + * @name SPC Status + * @{ + */ +/*! + * @brief Gets Isolation status for each power domains. + * + * This function gets the status which indicates whether certain + * peripheral and the IO pads are in a latched state as a result + * of having been in POWERDOWN mode. + * + * @param base SPC peripheral base address. + * @return Current isolation status for each power domains. See @ref _spc_power_domains for details. + */ +uint8_t SPC_GetPeriphIOIsolationStatus(SPC_Type *base); + +/*! + * @brief Clears peripherals and I/O pads isolation flags for each power domains. + * + * This function clears peripherals and I/O pads isolation flags for each power domains. + * After recovering from the POWERDOWN mode, user must invoke this function to release the + * I/O pads and certain peripherals to their normal run mode state. Before invoking this + * function, user must restore chip configuration in particular pin configuration for enabled + * WUU wakeup pins. + * + * @param base SPC peripheral base address. + */ +static inline void SPC_ClearPeriphIOIsolationFlag(SPC_Type *base) +{ + base->SC |= SPC_SC_ISO_CLR_MASK; +} + +/*! + * @brief Gets SPC busy status flag. + * + * This function gets SPC busy status flag. When SPC executing any type of power mode + * transition in ACTIVE mode or any of the SOC low power mode, the SPC busy status flag is set + * and this function returns true. When changing CORE LDO voltage level and DCDC voltage level + * in ACTIVE mode, the SPC busy status flag is set and this function return true. + * + * @param base SPC peripheral base address. + * @return Ack busy flag. + * true - SPC is busy. + * false - SPC is not busy. + */ +static inline bool SPC_GetBusyStatusFlag(SPC_Type *base) +{ + return ((base->SC & SPC_SC_BUSY_MASK) != 0UL); +} + +/*! + * @brief Checks system low power request. + * + * @note Only when all power domains request low power mode entry, the result of this function is true. That means when + * all power domains request low power mode entry, the SPC regulators will be controlled by LP_CFG register. + * + * @param base SPC peripheral base address. + * @return The system low power request check result. + * - \b true All power domains have requested low power mode and SPC has entered a low power state and power mode + * configuration are based on the LP_CFG configuration register. + * - \b false SPC in active mode and ACTIVE_CFG register control system power supply. + */ +static inline bool SPC_CheckLowPowerReqest(SPC_Type *base) +{ + return ((base->SC & SPC_SC_SPC_LP_REQ_MASK) == SPC_SC_SPC_LP_REQ_MASK); +} + +/*! + * @brief Clears system low power request, set SPC in active mode. + * + * @param base SPC peripheral base address. + */ +static inline void SPC_ClearLowPowerRequest(SPC_Type *base) +{ + base->SC |= SPC_SC_SPC_LP_REQ_MASK; +} + +#if (defined(FSL_FEATURE_MCX_SPC_HAS_SWITCH_STATE_BIT) && FSL_FEATURE_MCX_SPC_HAS_SWITCH_STATE_BIT) +/*! + * @brief Checks whether the power switch is on. + * + * @param base SPC peripheral base address. + * + * @retval true The power switch is on. + * @retval false The power switch is off. + */ +static inline bool SPC_CheckSwitchState(SPC_Type *base) +{ + return ((base->SC & SPC_SC_SWITCH_STATE_MASK) != 0UL); +} +#endif /* FSL_FEATURE_MCX_SPC_HAS_SWITCH_STATE_BIT */ + +/*! + * @brief Gets selected power domain's requested low power mode. + * + * @param base SPC peripheral base address. + * @param powerDomainId Power Domain Id, please refer to @ref spc_power_domain_id_t. + * + * @return The selected power domain's requested low power mode, please refer to @ref spc_power_domain_low_power_mode_t. + */ +spc_power_domain_low_power_mode_t SPC_GetPowerDomainLowPowerMode(SPC_Type *base, spc_power_domain_id_t powerDomainId); + +/*! + * @brief Checks power domain's low power request. + * + * @param base SPC peripheral base address. + * @param powerDomainId Power Domain Id, please refer to @ref spc_power_domain_id_t. + * @return The result of power domain's low power request. + * - \b true The selected power domain requests low power mode entry. + * - \b false The selected power domain does not request low power mode entry. + */ +static inline bool SPC_CheckPowerDomainLowPowerRequest(SPC_Type *base, spc_power_domain_id_t powerDomainId) +{ + assert((uint8_t)powerDomainId < SPC_PD_STATUS_COUNT); + return ((base->PD_STATUS[(uint8_t)powerDomainId] & SPC_PD_STATUS_PWR_REQ_STATUS_MASK) == + SPC_PD_STATUS_PWR_REQ_STATUS_MASK); +} + +/*! + * @brief Clears selected power domain's low power request flag. + * + * @param base SPC peripheral base address. + * @param powerDomainId Power Domain Id, please refer to @ref spc_power_domain_id_t. + */ +static inline void SPC_ClearPowerDomainLowPowerRequestFlag(SPC_Type *base, spc_power_domain_id_t powerDomainId) +{ + assert((uint8_t)powerDomainId < SPC_PD_STATUS_COUNT); + base->PD_STATUS[(uint8_t)powerDomainId] |= SPC_PD_STATUS_PD_LP_REQ_MASK; +} + +/*! @} */ + +#if (defined(FSL_FEATURE_MCX_SPC_HAS_SRAMRETLDO_REG) && FSL_FEATURE_MCX_SPC_HAS_SRAMRETLDO_REG) +/*! + * @name SRAM Retention LDO Control APIs + * @{ + */ + +/*! + * @brief Trims SRAM retention regulator reference voltage, trim step is 12 mV, range is around 0.48V to 0.85V. + * + * @param base SPC peripheral base address. + * @param trimValue Reference voltage trim value. + */ +static inline void SPC_TrimSRAMLdoRefVoltage(SPC_Type *base, uint8_t trimValue) +{ + base->SRAMRETLDO_REFTRIM = + ((base->SRAMRETLDO_REFTRIM & ~SPC_SRAMRETLDO_REFTRIM_REFTRIM_MASK) | SPC_SRAMRETLDO_REFTRIM_REFTRIM(trimValue)); +} + +/*! + * @brief Enables/disables SRAM retention LDO. + * + * @param base SPC peripheral base address. + * @param enable Used to enable/disable SRAM LDO : + * - \b true Enable SRAM LDO; + * - \b false Disable SRAM LDO. + */ +static inline void SPC_EnableSRAMLdo(SPC_Type *base, bool enable) +{ + if (enable) + { + base->SRAMRETLDO_CNTRL |= SPC_SRAMRETLDO_CNTRL_SRAMLDO_ON_MASK; + } + else + { + base->SRAMRETLDO_CNTRL &= ~SPC_SRAMRETLDO_CNTRL_SRAMLDO_ON_MASK; + } +} + +/*! + * @brief + * + * @todo Need to check. + * + * @param base SPC peripheral base address. + * @param mask The OR'ed value of SRAM Array. + */ +static inline void SPC_RetainSRAMArray(SPC_Type *base, uint8_t mask) +{ + base->SRAMRETLDO_CNTRL |= SPC_SRAMRETLDO_CNTRL_SRAM_RET_EN(mask); +} + +/*! @} */ +#endif /* FSL_FEATURE_MCX_SPC_HAS_SRAMRETLDO_REG */ + +/*! + * @name Low Power Request configuration + * @{ + */ +/*! + * @brief Configs Low power request output pin. + * + * This function config the low power request output pin + * + * @param base SPC peripheral base address. + * @param config Pointer the @ref spc_lowpower_request_config_t structure. + */ +void SPC_SetLowPowerRequestConfig(SPC_Type *base, const spc_lowpower_request_config_t *config); + +/*! @} */ + +#if (defined(FSL_FEATURE_MCX_SPC_HAS_CFG_REG) && FSL_FEATURE_MCX_SPC_HAS_CFG_REG) +/*! + * @name Integrated Power Switch Control APIs + * @{ + */ + +/*! + * @brief Enables/disables the integrated power switch manually. + * + * @param base SPC peripheral base address. + * @param enable Used to enable/disable the integrated power switch: + * - \b true Enable the integrated power switch; + * - \b false Disable the integrated power switch. + */ +static inline void SPC_EnableIntegratedPowerSwitchManually(SPC_Type *base, bool enable) +{ + if (enable) + { + base->CFG |= (SPC_CFG_INTG_PWSWTCH_SLEEP_ACTIVE_EN_MASK | SPC_CFG_INTG_PWSWTCH_WKUP_ACTIVE_EN_MASK); + } + else + { + base->CFG &= ~(SPC_CFG_INTG_PWSWTCH_SLEEP_ACTIVE_EN_MASK | SPC_CFG_INTG_PWSWTCH_WKUP_ACTIVE_EN_MASK); + } +} + +/*! + * @brief Enables/disables the integrated power switch automatically. + * + * To gate the integrated power switch when chip enter low power modes, and ungate the switch after wake-up from low + * power modes: + * @code + * SPC_EnableIntegratedPowerSwitchAutomatically(SPC, true, true); + * @endcode + * + * @param base SPC peripheral base address. + * @param sleepGate Enable the integrated power switch when chip enter low power modes: + * - \b true SPC asserts an output pin at low-power entry to power-gate the switch; + * - \b false SPC does not assert an output pin at low-power entry to power-gate the switch. + * @param wakeupUngate Enables the switch after wake-up from low power modes: + * - \b true SPC asserts an output pin at low-power exit to power-ungate the switch; + * - \b false SPC does not assert an output pin at low-power exit to power-ungate the switch. + */ +static inline void SPC_EnableIntegratedPowerSwitchAutomatically(SPC_Type *base, bool sleepGate, bool wakeupUngate) +{ + uint32_t tmp32 = ((base->CFG) & ~(SPC_CFG_INTG_PWSWTCH_SLEEP_EN_MASK | SPC_CFG_INTG_PWSWTCH_WKUP_EN_MASK)); + + tmp32 |= SPC_CFG_INTG_PWSWTCH_SLEEP_EN(sleepGate) | SPC_CFG_INTG_PWSWTCH_WKUP_EN(wakeupUngate); + + base->CFG = tmp32; +} + +/*! @} */ +#endif /* FSL_FEATURE_MCX_SPC_HAS_CFG_REG */ + +#if !(defined(FSL_FEATURE_MCX_SPC_HAS_NO_GLITCH_DETECT) && FSL_FEATURE_MCX_SPC_HAS_NO_GLITCH_DETECT) +/*! + * @name VDD Core Glitch Detector Control APIs + * @{ + */ + +/*! + * @brief Configures VDD Core Glitch detector, including ripple counter selection, timeout value and so on. + * + * @param base SPC peripheral base address. + * @param config Pointer to the structure in type of @ref spc_vdd_core_glitch_detector_config_t. + */ +void SPC_ConfigVddCoreGlitchDetector(SPC_Type *base, const spc_vdd_core_glitch_detector_config_t *config); + +/*! + * @brief Checks selected 4-bit glitch ripple counter's output. + * + * @param base SPC peripheral base address. + * @param rippleCounter The ripple counter to check, please refer to @ref spc_vdd_core_glitch_ripple_counter_select_t. + * + * @retval true The selected ripple counter output is 1, will generate interrupt or reset based on settings. + * @retval false The selected ripple counter output is 0. + */ + +static inline bool SPC_CheckGlitchRippleCounterOutput(SPC_Type *base, + spc_vdd_core_glitch_ripple_counter_select_t rippleCounter) +{ + return ((base->VDD_CORE_GLITCH_DETECT_SC & SPC_VDD_CORE_GLITCH_DETECT_SC_GLITCH_DETECT_FLAG_MASK) == + SPC_VDD_CORE_GLITCH_DETECT_SC_GLITCH_DETECT_FLAG(1UL << (uint32_t)(rippleCounter))); +} + +/*! + * @brief Clears output of selected glitch ripple counter. + * + * @param base SPC peripheral base address. + * @param rippleCounter The ripple counter to check, please refer to @ref spc_vdd_core_glitch_ripple_counter_select_t. + */ +static inline void SPC_ClearGlitchRippleCounterOutput(SPC_Type *base, + spc_vdd_core_glitch_ripple_counter_select_t rippleCounter) +{ + base->VDD_CORE_GLITCH_DETECT_SC |= + SPC_VDD_CORE_GLITCH_DETECT_SC_GLITCH_DETECT_FLAG(1UL << (uint32_t)(rippleCounter)); +} + +/*! + * @brief After invoking this function, writes to SPC_VDD_CORE_GLITCH_DETECT_SC[RE] register are ignored. + * + * @param base SPC peripheral base address. + */ +static inline void SPC_LockVddCoreVoltageGlitchDetectResetControl(SPC_Type *base) +{ + base->VDD_CORE_GLITCH_DETECT_SC |= SPC_VDD_CORE_GLITCH_DETECT_SC_LOCK_MASK; +} + +/*! + * @brief After invoking this function, writes to SPC_VDD_CORE_GLITCH_DETECT_SC[RE] register are allowed. + * + * @param base SPC peripheral base address. + */ +static inline void SPC_UnlockVddCoreVoltageGlitchDetectResetControl(SPC_Type *base) +{ + base->VDD_CORE_GLITCH_DETECT_SC &= ~SPC_VDD_CORE_GLITCH_DETECT_SC_LOCK_MASK; +} + +/*! + * @brief Checks if SPC_VDD_CORE_GLITCH_DETECT_SC[RE] register is writable. + * + * @param base SPC peripheral base address. + * + * @retval true SPC_VDD_CORE_GLITCH_DETECT_SC[RE] register is writable. + * @retval false SPC_VDD_CORE_GLITCH_DETECT_SC[RE] register is not writable. + */ +static inline bool SPC_CheckVddCoreVoltageGlitchResetControlState(SPC_Type *base) +{ + return ((base->VDD_CORE_GLITCH_DETECT_SC & SPC_VDD_CORE_GLITCH_DETECT_SC_LOCK_MASK) != 0UL); +} + +/*! @} */ +#endif + +/*! + * @name SRAM Control APIs + * @{ + */ + +/*! + * @brief Set SRAM operate voltage. + * + * @param base SPC peripheral base address. + * @param config The pointer to @ref spc_sram_voltage_config_t, specifies the configuration of sram voltage. + */ +void SPC_SetSRAMOperateVoltage(SPC_Type *base, const spc_sram_voltage_config_t *config); + +/*! @} */ + +/*! + * @name Active Mode configuration + * @{ + */ + +/*! + * @brief Gets the Bandgap mode in Active mode. + * + * @param base SPC peripheral base address. + * @return Bandgap mode in the type of @ref spc_bandgap_mode_t enumeration. + */ +static inline spc_bandgap_mode_t SPC_GetActiveModeBandgapMode(SPC_Type *base) +{ + return (spc_bandgap_mode_t)(uint32_t)((base->ACTIVE_CFG & SPC_ACTIVE_CFG_BGMODE_MASK) >> + SPC_ACTIVE_CFG_BGMODE_SHIFT); +} + +/*! + * @brief Gets all voltage detectors status in Active mode. + * + * @param base SPC peripheral base address. + * @return All voltage detectors status in Active mode. + */ +static inline uint32_t SPC_GetActiveModeVoltageDetectStatus(SPC_Type *base) +{ + uint32_t state; + state = base->ACTIVE_CFG & + ( +#if (defined(FSL_FEATURE_MCX_SPC_HAS_IOVDD_VD) && FSL_FEATURE_MCX_SPC_HAS_IOVDD_VD) + SPC_ACTIVE_CFG_IO_HVDE_MASK | SPC_ACTIVE_CFG_IO_LVDE_MASK | + +#endif /* FSL_FEATURE_MCX_SPC_HAS_IOVDD_VD */ + SPC_ACTIVE_CFG_SYS_HVDE_MASK | SPC_ACTIVE_CFG_SYS_LVDE_MASK | SPC_ACTIVE_CFG_CORE_LVDE_MASK + +#if (defined(FSL_FEATURE_MCX_SPC_HAS_COREVDD_HVD) && FSL_FEATURE_MCX_SPC_HAS_COREVDD_HVD) + | SPC_ACTIVE_CFG_CORE_HVDE_MASK + +#endif /* FSL_FEATURE_MCX_SPC_HAS_COREVDD_HVD */ + ); + return state; +} + +/*! + * @brief Configs Bandgap mode in Active mode. + * + * @note To disable bandgap in Active mode: + * 1. Disable all LVD's and HVD's in active mode; + * 2. Disable Glitch detect; + * 3. Configure LDO's and DCDC to low drive strength in active mode; + * 4. Invoke this function to disable bandgap in active mode; + * otherwise the error status will be reported. + * + * @note Some other system resources(such as PLL, CMP) require bandgap to be enabled, to disable bandgap please + * take care of other system resources. + * + * @param base SPC peripheral base address. + * @param mode The Bandgap mode be selected. + * + * @retval #kStatus_SPC_BandgapModeWrong The Bandgap can not be disabled in active mode. + * @retval #kStatus_Success Config Bandgap mode in Active power mode successful. + */ +status_t SPC_SetActiveModeBandgapModeConfig(SPC_Type *base, spc_bandgap_mode_t mode); + +#if (defined(FSL_FEATURE_MCX_SPC_HAS_LPBUFF_EN_BIT) && FSL_FEATURE_MCX_SPC_HAS_LPBUFF_EN_BIT) +/*! + * @brief Enables/Disable the CMP Bandgap Buffer in Active mode. + * + * @param base SPC peripheral base address. + * @param enable Enable/Disable CMP Bandgap buffer. + * true - Enable Buffer Stored Reference voltage to CMP. + * false - Disable Buffer Stored Reference voltage to CMP. + */ +static inline void SPC_EnableActiveModeCMPBandgapBuffer(SPC_Type *base, bool enable) +{ + if (enable) + { + base->ACTIVE_CFG |= SPC_ACTIVE_CFG_LPBUFF_EN_MASK; + } + else + { + base->ACTIVE_CFG &= ~SPC_ACTIVE_CFG_LPBUFF_EN_MASK; + } +} +#endif /* FSL_FEATURE_MCX_SPC_HAS_LPBUFF_EN_BIT */ + +/*! + * @brief Sets the delay when the regulators change voltage level in Active mode. + * + * @param base SPC peripheral base address. + * @param delay The number of SPC timer clock cycles. + */ +static inline void SPC_SetActiveModeVoltageTrimDelay(SPC_Type *base, uint16_t delay) +{ + base->ACTIVE_VDELAY = SPC_ACTIVE_VDELAY_ACTIVE_VDELAY(delay); +} + +/*! + * @brief Configs all settings of regulators in Active mode at a time. + * + * @note This function is used to overwrite all settings of regulators(including bandgap mode, regulators' + * drive strength and voltage level) in active mode at a time. + * + * @note Enable/disable LVDs/HVDs before invoking this function. + * + * @note This function will check input parameters based on hardware restrictions before setting registers, if input + * parameters do not satisfy hardware restrictions the specific error will be reported. + * + * + * @note Some hardware restrictions not covered, application should be aware of this and follow this hardware + * restrictions otherwise some unknown issue may occur: + * 1. If Core LDO's drive strength are set to same value in both Active mode and low power mode, + * the voltage level should also set to same value. + * 2. When switching Core LDO's drive strength from low to normal, ensure the LDO_CORE high voltage level is set + * to same level that was set prior to switching to the LDO_CORE drive strength. Otherwise, if the LVDs are + * enabled, an unexpected LVD can occur. + * + * @note If this function can not satisfy some tricky settings, please invoke other APIs in low-level function group. + * + * @param base SPC peripheral base address. + * @param config Pointer to spc_active_mode_regulators_config_t structure. + * + * @retval #kStatus_Success Config regulators in Active power mode successful. + * @retval #kStatus_SPC_BandgapModeWrong Based on input setting, bandgap can not be disabled. + * @retval #kStatus_SPC_Busy The SPC instance is busy to execute any type of power mode transition. + * @retval #kStatus_SPC_CORELDOLowDriveStrengthIgnore Any of LVDs/HVDs kept enabled before invoking this function. + * @retval #kStatus_SPC_SYSLDOOverDriveVoltageFail Fail to regulator to Over Drive Voltage due to + * System VDD HVD is not disabled. + * @retval #kStatus_SPC_SYSLDOLowDriveStrengthIgnore Any of LVDs/HVDs kept enabled before invoking this function. + * @retval #kStatus_SPC_CORELDOVoltageWrong Core LDO and System LDO do not have same voltage level. + */ +status_t SPC_SetActiveModeRegulatorsConfig(SPC_Type *base, const spc_active_mode_regulators_config_t *config); + +#if !(defined(FSL_FEATURE_MCX_SPC_HAS_NO_GLITCH_DETECT) && FSL_FEATURE_MCX_SPC_HAS_NO_GLITCH_DETECT) +/*! + * @brief Disables/Enables VDD Core Glitch Detect in Active mode. + * + * @note State of glitch detect disable feature will be ignored if bandgap is disabled and + * glitch detect hardware will be forced to OFF state. + * + * @param base SPC peripheral base address. + * @param disable Used to disable/enable VDD Core Glitch detect feature. + * - \b true Disable VDD Core Low Voltage detect; + * - \b false Enable VDD Core Low Voltage detect. + */ +static inline void SPC_DisableActiveModeVddCoreGlitchDetect(SPC_Type *base, bool disable) +{ + if (disable) + { + base->ACTIVE_CFG |= SPC_ACTIVE_CFG_GLITCH_DETECT_DISABLE_MASK; + } + else + { + base->ACTIVE_CFG &= ~SPC_ACTIVE_CFG_GLITCH_DETECT_DISABLE_MASK; + } +} + +/*! + * @brief Check if Glitch detect hardware is enabled in active mode. + * + * @param base SPC peripheral base address. + * @return Indicate if Glitch detector is enabled. + */ +static inline bool SPC_CheckActiveModeVddCoreGlitchDetectEnabled(SPC_Type *base) +{ + if ((base->ACTIVE_CFG & SPC_ACTIVE_CFG_GLITCH_DETECT_DISABLE_MASK) == 0UL) + { + return true; + } + else + { + return false; + } +} + +#endif /* FSL_FEATURE_MCX_SPC_HAS_NO_GLITCH_DETECT */ + +/*! + * @brief Enables analog modules in active mode. + * + * @param base SPC peripheral base address. + * @param maskValue The mask of analog modules to enable in active mode, should be the OR'ed value + * of @ref spc_analog_module_control. + */ +static inline void SPC_EnableActiveModeAnalogModules(SPC_Type *base, uint32_t maskValue) +{ + base->ACTIVE_CFG1 |= SPC_ACTIVE_CFG1_SOC_CNTRL(maskValue); +} + +/*! + * @brief Disables analog modules in active mode. + * + * @param base SPC peripheral base address. + * @param maskValue The mask of analog modules to disable in active mode, should be the OR'ed value + * of @ref spc_analog_module_control. + */ +static inline void SPC_DisableActiveModeAnalogModules(SPC_Type *base, uint32_t maskValue) +{ + base->ACTIVE_CFG1 &= ~SPC_ACTIVE_CFG1_SOC_CNTRL(maskValue); +} + +/*! + * @brief Gets enabled analog modules that enabled in active mode. + * + * @param base SPC peripheral base address. + * + * @return The mask of enabled analog modules that enabled in active mode. + */ +static inline uint32_t SPC_GetActiveModeEnabledAnalogModules(SPC_Type *base) +{ + return base->ACTIVE_CFG1; +} + +/*! @} */ + +/*! + * @name Low Power mode configuration + * @{ + */ + +/*! + * @brief Gets the Bandgap mode in Low Power mode. + * + * @param base SPC peripheral base address. + * @return Bandgap mode in the type of @ref spc_bandgap_mode_t enumeration. + */ +static inline spc_bandgap_mode_t SPC_GetLowPowerModeBandgapMode(SPC_Type *base) +{ + return (spc_bandgap_mode_t)(uint32_t)((base->LP_CFG & SPC_LP_CFG_BGMODE_MASK) >> SPC_LP_CFG_BGMODE_SHIFT); +} + +/*! + * @brief Gets the status of all voltage detectors in Low Power mode. + * + * @param base SPC peripheral base address. + * @return The status of all voltage detectors in low power mode. + */ +static inline uint32_t SPC_GetLowPowerModeVoltageDetectStatus(SPC_Type *base) +{ + uint32_t state; + state = base->LP_CFG & ( +#if (defined(FSL_FEATURE_MCX_SPC_HAS_IOVDD_VD) && FSL_FEATURE_MCX_SPC_HAS_IOVDD_VD) + SPC_LP_CFG_IO_HVDE_MASK | SPC_LP_CFG_IO_LVDE_MASK | + +#endif /* FSL_FEATURE_MCX_SPC_HAS_IOVDD_VD */ + SPC_LP_CFG_SYS_HVDE_MASK | SPC_LP_CFG_SYS_LVDE_MASK | SPC_LP_CFG_CORE_LVDE_MASK + +#if (defined(FSL_FEATURE_MCX_SPC_HAS_COREVDD_HVD) && FSL_FEATURE_MCX_SPC_HAS_COREVDD_HVD) + | SPC_LP_CFG_CORE_HVDE_MASK + +#endif /* FSL_FEATURE_MCX_SPC_HAS_COREVDD_HVD */ + ); + return state; +} + +/*! + * @brief Enables/Disables Low Power IREF in low power modes. + * + * This function enables/disables Low Power IREF. Low Power IREF can only get + * disabled in Deep power down mode. In other low power modes, the Low Power IREF + * is always enabled. + * + * @param base SPC peripheral base address. + * @param enable Enable/Disable Low Power IREF. + * true - Enable Low Power IREF for Low Power modes. + * false - Disable Low Power IREF for Deep Power Down mode. + */ +static inline void SPC_EnableLowPowerModeLowPowerIREF(SPC_Type *base, bool enable) +{ + if (enable) + { + base->LP_CFG |= SPC_LP_CFG_LP_IREFEN_MASK; + } + else + { + base->LP_CFG &= ~SPC_LP_CFG_LP_IREFEN_MASK; + } +} + +/*! + * @brief Configs Bandgap mode in Low Power mode. + * + * @note To disable Bandgap in Low-power mode: + * 1. Disable all LVD's ad HVD's in low power mode; + * 2. Disable Glitch detect in low power mode; + * 3. Configure LDO's and DCDC to low drive strength in low power mode; + * 4. Disable bandgap in low power mode; + * Otherwise, the error status will be reported. + * + * @note Some other system resources(such as PLL, CMP) require bandgap to be enabled, to disable bandgap please + * take care of other system resources. + * + * @param base SPC peripheral base address. + * @param mode The Bandgap mode be selected. + * + * @retval #kStatus_SPC_BandgapModeWrong The bandgap mode setting in Low Power mode is wrong. + * @retval #kStatus_Success Config Bandgap mode in Low Power power mode successful. + */ +status_t SPC_SetLowPowerModeBandgapmodeConfig(SPC_Type *base, spc_bandgap_mode_t mode); + +#if (defined(FSL_FEATURE_MCX_SPC_HAS_SRAMLDO_DPD_ON_BIT) && FSL_FEATURE_MCX_SPC_HAS_SRAMLDO_DPD_ON_BIT) +/*! + * @brief Enables/disables SRAM_LDO deep power low power IREF. + * + * @param base SPC peripheral base address. + * @param enable Used to enable/disable low power IREF : + * - \b true: Low Power IREF is enabled ; + * - \b false: Low Power IREF is disabled for power saving. + */ +static inline void SPC_EnableSRAMLdOLowPowerModeIREF(SPC_Type *base, bool enable) +{ + if (enable) + { + base->LP_CFG |= SPC_LP_CFG_SRAMLDO_DPD_ON_MASK; + } + else + { + base->LP_CFG &= ~SPC_LP_CFG_SRAMLDO_DPD_ON_MASK; + } +} +#endif /* FSL_FEATURE_MCX_SPC_HAS_SRAMLDO_DPD_ON_BIT */ + +#if (defined(FSL_FEATURE_MCX_SPC_HAS_LPBUFF_EN_BIT) && FSL_FEATURE_MCX_SPC_HAS_LPBUFF_EN_BIT) +/*! + * @brief Enables/Disables CMP Bandgap Buffer. + * + * This function gates CMP bandgap buffer. CMP bandgap buffer is automatically disabled and turned off + * in Deep Power Down mode. + * + * @deprecated No longer used, please use SPC_EnableLowPowerModeCMPBandgapBuffer as instead. + * + * @param base SPC peripheral base address. + * @param enable Enable/Disable CMP Bandgap buffer. + * true - Enable Buffer Stored Reference Voltage to CMP. + * false - Disable Buffer Stored Reference Voltage to CMP. + */ +static inline void SPC_EnableLowPowerModeCMPBandgapBufferMode(SPC_Type *base, bool enable) +{ + if (enable) + { + base->LP_CFG |= SPC_LP_CFG_LPBUFF_EN_MASK; + } + else + { + base->LP_CFG &= ~SPC_LP_CFG_LPBUFF_EN_MASK; + } +} + +/*! + * @brief Enables/Disables CMP Bandgap Buffer. + * + * This function gates CMP bandgap buffer. CMP bandgap buffer is automatically disabled and turned off + * in Deep Power Down mode. + * + * @deprecated No longer used. + * + * @param base SPC peripheral base address. + * @param enable Enable/Disable CMP Bandgap buffer. + * true - Enable Buffer Stored Reference Voltage to CMP. + * false - Disable Buffer Stored Reference Voltage to CMP. + */ +static inline void SPC_EnableLowPowerModeCMPBandgapBuffer(SPC_Type *base, bool enable) +{ + if (enable) + { + base->LP_CFG |= SPC_LP_CFG_LPBUFF_EN_MASK; + } + else + { + base->LP_CFG &= ~SPC_LP_CFG_LPBUFF_EN_MASK; + } +} +#endif /* FSL_FEATURE_MCX_SPC_HAS_LPBUFF_EN_BIT */ + +#if (defined(FSL_FEATURE_MCX_SPC_HAS_COREVDD_IVS_EN_BIT) && FSL_FEATURE_MCX_SPC_HAS_COREVDD_IVS_EN_BIT) +/*! + * @brief Enables/Disables CORE VDD IVS(Internal Voltage Scaling) in power down modes. + * + * This function gates CORE VDD IVS. When enabled, the IVS regulator will scale the + * external input CORE VDD to a lower voltage level to reduce internal leakage. + * IVS is invalid in Sleep or Deep power down mode. + * + * @param base SPC peripheral base address. + * @param enable Enable/Disable IVS. + * true - enable CORE VDD IVS in Power Down mode. + * false - disable CORE VDD IVS in Power Down mode. + */ +static inline void SPC_EnableLowPowerModeCoreVDDInternalVoltageScaling(SPC_Type *base, bool enable) +{ + if (enable) + { + base->LP_CFG |= SPC_LP_CFG_COREVDD_IVS_EN_MASK; + } + else + { + base->LP_CFG &= ~SPC_LP_CFG_COREVDD_IVS_EN_MASK; + } +} +#endif /* FSL_FEATURE_MCX_SPC_HAS_COREVDD_IVS_EN_BIT */ + +/*! + * @brief Sets the delay when exit the low power modes. + * + * @param base SPC peripheral base address. + * @param delay The number of SPC timer clock cycles that the SPC waits on exit from low power modes. + */ +static inline void SPC_SetLowPowerWakeUpDelay(SPC_Type *base, uint16_t delay) +{ + base->LPWKUP_DELAY = SPC_LPWKUP_DELAY_LPWKUP_DELAY(delay); +} + +/*! + * @brief Configs all settings of regulators in Low power mode at a time. + * + * @note This function is used to overwrite all settings of regulators(including bandgap mode, regulators' + * drive strength and voltage level) in low power mode at a time. + * + * @note Enable/disable LVDs/HVDs before invoking this function. + * + * @note This function will check input parameters based on hardware restrictions before setting registers, if input + * parameters do not satisfy hardware restrictions the specific error will be reported. + * + * @note Some hardware restrictions not covered, application should be aware of this and follow this hardware + * restrictions otherwise some unknown issue may occur: + * 1. If Core LDO's drive strength are set to same value in both Active mode and low power mode, + * the voltage level should also set to same value. + * 2. When switching Core LDO's drive strength from low to normal, ensure the LDO_CORE high voltage level is set + * to same level that was set prior to switching to the LDO_CORE drive strength. Otherwise, if the LVDs are + * enabled, an unexpected LVD can occur. + * + * @note If this function can not satisfy some tricky settings, please invoke other APIs in low-level function group. + * + * @param base SPC peripheral base address. + * @param config Pointer to spc_lowpower_mode_regulators_config_t structure. + * @retval #kStatus_Success Config regulators in Low power mode successful. + * @retval #kStatus_SPC_BandgapModeWrong The bandgap should not be disabled based on input settings. + * @retval #kStatus_SPC_CORELDOLowDriveStrengthIgnore Set driver strength to low will be ignored. + * @retval #kStatus_SPC_SYSLDOLowDriveStrengthIgnore Set driver strength to low will be ignored. + * @retval #kStatus_SPC_CORELDOVoltageWrong Core LDO and System LDO do not have same voltage level. + */ +status_t SPC_SetLowPowerModeRegulatorsConfig(SPC_Type *base, const spc_lowpower_mode_regulators_config_t *config); + +#if !(defined(FSL_FEATURE_MCX_SPC_HAS_NO_GLITCH_DETECT) && FSL_FEATURE_MCX_SPC_HAS_NO_GLITCH_DETECT) +/*! + * @brief Disable/Enable VDD Core Glitch Detect in low power mode. + * + * @note State of glitch detect disable feature will be ignored if bandgap is disabled and + * glitch detect hardware will be forced to OFF state. + * + * @param base SPC peripheral base address. + * @param disable Used to disable/enable VDD Core Glitch detect feature. + * - \b true Disable VDD Core Low Voltage detect; + * - \b false Enable VDD Core Low Voltage detect. + */ +static inline void SPC_DisableLowPowerModeVddCoreGlitchDetect(SPC_Type *base, bool disable) +{ + if (disable) + { + base->LP_CFG |= SPC_LP_CFG_GLITCH_DETECT_DISABLE_MASK; + } + else + { + base->LP_CFG &= ~SPC_LP_CFG_GLITCH_DETECT_DISABLE_MASK; + } +} + +/*! + * @brief Check if Glitch detect hardware is enabled in low power mode. + * + * @param base SPC peripheral base address. + * @return Indicate if Glitch detector is enabled. + */ +static inline bool SPC_CheckLowPowerModeVddCoreGlitchDetectEnabled(SPC_Type *base) +{ + if ((base->LP_CFG & SPC_LP_CFG_GLITCH_DETECT_DISABLE_MASK) == 0UL) + { + return true; + } + else + { + return false; + } +} +#endif + +/*! + * @brief Enables analog modules in low power modes. + * + * @param base SPC peripheral base address. + * @param maskValue The mask of analog modules to enable in low power modes, should be OR'ed value + of @ref spc_analog_module_control. + */ +static inline void SPC_EnableLowPowerModeAnalogModules(SPC_Type *base, uint32_t maskValue) +{ + base->LP_CFG1 |= SPC_LP_CFG1_SOC_CNTRL(maskValue); +} + +/*! + * @brief Disables analog modules in low power modes. + * + * @param base SPC peripheral base address. + * @param maskValue The mask of analog modules to disable in low power modes, should be OR'ed value + of @ref spc_analog_module_control. + */ +static inline void SPC_DisableLowPowerModeAnalogModules(SPC_Type *base, uint32_t maskValue) +{ + base->LP_CFG1 &= ~SPC_LP_CFG1_SOC_CNTRL(maskValue); +} + +/*! + * @brief Gets enabled analog modules that enabled in low power modes. + * + * @param base SPC peripheral base address. + * + * @return The mask of enabled analog modules that enabled in low power modes. + */ +static inline uint32_t SPC_GetLowPowerModeEnabledAnalogModules(SPC_Type *base) +{ + return base->LP_CFG1; +} + +/*! @} */ + +/*! + * @name Voltage Detect Status + * @{ + */ +/*! + * @brief Get Voltage Detect Status Flags. + * + * @param base SPC peripheral base address. + * @return Voltage Detect Status Flags. See @ref _spc_voltage_detect_flags for details. + */ +static inline uint8_t SPC_GetVoltageDetectStatusFlag(SPC_Type *base) +{ + return (uint8_t)(base->VD_STAT); +} + +/*! + * @brief Clear Voltage Detect Status Flags. + * + * @param base SPC peripheral base address. + * @param mask The mask of the voltage detect status flags. See @ref _spc_voltage_detect_flags for details. + */ +static inline void SPC_ClearVoltageDetectStatusFlag(SPC_Type *base, uint8_t mask) +{ + base->VD_STAT |= mask; +} + +/*! @} */ + +/*! + * @name Voltage Detect configuration for Core voltage domain. + * @{ + */ + +/*! + * @brief Configs CORE voltage detect options. + * + * @note: Setting both the voltage detect interrupt and reset + * enable will cause interrupt to be generated on exit from reset. + * If those conditioned is not desired, interrupt/reset so only one is enabled. + * + * @param base SPC peripheral base address. + * @param config Pointer to spc_core_voltage_detect_config_t structure. + */ +void SPC_SetCoreVoltageDetectConfig(SPC_Type *base, const spc_core_voltage_detect_config_t *config); + +/*! + * @brief Locks Core voltage detect reset setting. + * + * This function locks core voltage detect reset setting. After invoking this function + * any configuration of Core voltage detect reset will be ignored. + * + * @param base SPC peripheral base address. + */ +static inline void SPC_LockCoreVoltageDetectResetSetting(SPC_Type *base) +{ + base->VD_CORE_CFG |= SPC_VD_CORE_CFG_LOCK_MASK; +} + +/*! + * @brief Unlocks Core voltage detect reset setting. + * + * This function unlocks core voltage detect reset setting. If locks the Core + * voltage detect reset setting, invoking this function to unlock. + * + * @param base SPC peripheral base address. + */ +static inline void SPC_UnlockCoreVoltageDetectResetSetting(SPC_Type *base) +{ + base->VD_CORE_CFG &= ~SPC_VD_CORE_CFG_LOCK_MASK; +} + +/*! + * @brief Enables/Disables the Core Low Voltage Detector in Active mode. + * + * @note If the CORE_LDO low voltage detect is enabled in Active mode, please note that the bandgap must be enabled + * and the drive strength of each regulator must not set to low. + * + * @param base SPC peripheral base address. + * @param enable Enable/Disable Core LVD. + * true - Enable Core Low voltage detector in active mode. + * false - Disable Core Low voltage detector in active mode. + * + * @retval #kStatus_Success Enable/Disable Core Low Voltage Detect successfully. + */ +status_t SPC_EnableActiveModeCoreLowVoltageDetect(SPC_Type *base, bool enable); + +/*! + * @brief Enables/Disables the Core Low Voltage Detector in Low Power mode. + * + * This function enables/disables the Core Low Voltage Detector. + * If enabled the Core Low Voltage detector. The Bandgap mode in + * low power mode must be programmed so that Bandgap is enabled. + * + * @note If the CORE_LDO low voltage detect is enabled in Low Power mode, please note that the bandgap must be enabled + * and the drive strength of each regulator must not set to low in Low Power mode. + * + * @param base SPC peripheral base address. + * @param enable Enable/Disable Core HVD. + * true - Enable Core Low voltage detector in low power mode. + * false - Disable Core Low voltage detector in low power mode. + * + * @retval #kStatus_Success Enable/Disable Core Low Voltage Detect in low power mode successfully. + */ +status_t SPC_EnableLowPowerModeCoreLowVoltageDetect(SPC_Type *base, bool enable); + +#if (defined(FSL_FEATURE_MCX_SPC_HAS_COREVDD_HVD) && FSL_FEATURE_MCX_SPC_HAS_COREVDD_HVD) +/*! + * @brief Enables/Disables the Core High Voltage Detector in Active mode. + * + * @note If the CORE_LDO high voltage detect is enabled in Active mode, please note that the bandgap must be enabled + * and the drive strength of each regulator must not set to low. + * + * @param base SPC peripheral base address. + * @param enable Enable/Disable Core HVD. + * true - Enable Core High voltage detector in active mode. + * false - Disable Core High voltage detector in active mode. + * + * @retval #kStatus_Success Enable/Disable Core High Voltage Detect successfully. + */ +status_t SPC_EnableActiveModeCoreHighVoltageDetect(SPC_Type *base, bool enable); + +/*! + * @brief Enables/Disables the Core High Voltage Detector in Low Power mode. + * + * This function enables/disables the Core High Voltage Detector. + * If enabled the Core High Voltage detector. The Bandgap mode in + * low power mode must be programmed so that Bandgap is enabled. + * + * @note If the CORE_LDO high voltage detect is enabled in Low Power mode, please note that the bandgap must be enabled + * and the drive strength of each regulator must not set to low in low power mode. + * + * @param base SPC peripheral base address. + * @param enable Enable/Disable Core HVD. + * true - Enable Core High voltage detector in low power mode. + * false - Disable Core High voltage detector in low power mode. + * + * @retval #kStatus_Success Enable/Disable Core High Voltage Detect in low power mode successfully. + */ +status_t SPC_EnableLowPowerModeCoreHighVoltageDetect(SPC_Type *base, bool enable); +#endif /* FSL_FEATURE_MCX_SPC_HAS_COREVDD_HVD */ + +/*! @} */ + +/*! + * @name Voltage detect configuration for System Voltage domain + * @{ + */ +/*! + * @brief Set system VDD Low-voltage level selection. + * + * This function selects the system VDD low-voltage level. Changing system VDD low-voltage level + * must be done after disabling the System VDD low voltage reset and interrupt. + * + * @deprecated In latest RM, reserved for all devices, will removed in next release. + * + * @param base SPC peripheral base address. + * @param level System VDD Low-Voltage level selection. + */ +void SPC_SetSystemVDDLowVoltageLevel(SPC_Type *base, spc_low_voltage_level_select_t level); + +/*! + * @brief Configs SYS voltage detect options. + * + * This function config SYS voltage detect options. + * @note: Setting both the voltage detect interrupt and reset + * enable will cause interrupt to be generated on exit from reset. + * If those conditioned is not desired, interrupt/reset so only one is enabled. + * + * @param base SPC peripheral base address. + * @param config Pointer to spc_system_voltage_detect_config_t structure. + */ +void SPC_SetSystemVoltageDetectConfig(SPC_Type *base, const spc_system_voltage_detect_config_t *config); + +/*! + * @brief Lock System voltage detect reset setting. + * + * This function locks system voltage detect reset setting. After invoking this function + * any configuration of System Voltage detect reset will be ignored. + * + * @param base SPC peripheral base address. + */ +static inline void SPC_LockSystemVoltageDetectResetSetting(SPC_Type *base) +{ + base->VD_SYS_CFG |= SPC_VD_SYS_CFG_LOCK_MASK; +} + +/*! + * @brief Unlock System voltage detect reset setting. + * + * This function unlocks system voltage detect reset setting. If locks the System + * voltage detect reset setting, invoking this function to unlock. + * + * @param base SPC peripheral base address. + */ +static inline void SPC_UnlockSystemVoltageDetectResetSetting(SPC_Type *base) +{ + base->VD_SYS_CFG &= ~SPC_VD_SYS_CFG_LOCK_MASK; +} + +/*! + * @brief Enables/Disables the System High Voltage Detector in Active mode. + * + * @note If the System_LDO high voltage detect is enabled in Active mode, please note that the bandgap must be enabled + * and the drive strength of each regulator must not set to low in Active mode. + * + * @param base SPC peripheral base address. + * @param enable Enable/Disable System HVD. + * true - Enable System High voltage detector in active mode. + * false - Disable System High voltage detector in active mode. + * + * @retval #kStatus_Success Enable/Disable System High Voltage Detect successfully. + */ +status_t SPC_EnableActiveModeSystemHighVoltageDetect(SPC_Type *base, bool enable); + +/*! + * @brief Enables/Disable the System Low Voltage Detector in Active mode. + * + * @note If the System_LDO low voltage detect is enabled in Active mode, + * please note that the bandgap must be enabled and the drive strength of each + * regulator must not set to low in Active mode. + * + * @param base SPC peripheral base address. + * @param enable Enable/Disable System LVD. + * true - Enable System Low voltage detector in active mode. + * false - Disable System Low voltage detector in active mode. + * + * @retval #kStatus_Success Enable/Disable the System Low Voltage Detect successfully. + */ +status_t SPC_EnableActiveModeSystemLowVoltageDetect(SPC_Type *base, bool enable); + +/*! + * @brief Enables/Disables the System High Voltage Detector in Low Power mode. + * + * @note If the System_LDO high voltage detect is enabled in Low Power mode, please note + * that the bandgap must be enabled and the drive strength of each regulator must + * not set to low in Low Power mode. + * + * @param base SPC peripheral base address. + * @param enable Enable/Disable System HVD. + * true - Enable System High voltage detector in low power mode. + * false - Disable System High voltage detector in low power mode. + * + * @retval #kStatus_Success Enable/Disable System High Voltage Detect in low power mode successfully. + */ +status_t SPC_EnableLowPowerModeSystemHighVoltageDetect(SPC_Type *base, bool enable); + +/*! + * @brief Enables/Disables the System Low Voltage Detector in Low Power mode. + * + * @note If the System_LDO low voltage detect is enabled in Low Power mode, + * please note that the bandgap must be enabled and the drive strength of each + * regulator must not set to low in Low Power mode. + * + * @param base SPC peripheral base address. + * @param enable Enable/Disable System HVD. + * true - Enable System Low voltage detector in low power mode. + * false - Disable System Low voltage detector in low power mode. + * + * @retval #kStatus_Success Enables System Low Voltage Detect in low power mode successfully. + */ +status_t SPC_EnableLowPowerModeSystemLowVoltageDetect(SPC_Type *base, bool enable); + +/*! @} */ + +#if (defined(FSL_FEATURE_MCX_SPC_HAS_IOVDD_VD) && FSL_FEATURE_MCX_SPC_HAS_IOVDD_VD) +/*! + * @name Voltage detect configuration for IO voltage domain + * @{ + */ +/*! + * @brief Set IO VDD Low-Voltage level selection. + * + * This function selects the IO VDD Low-voltage level. Changing IO VDD low-voltage level + * must be done after disabling the IO VDD low voltage reset and interrupt. + * + * @param base SPC peripheral base address. + * @param level IO VDD Low-voltage level selection. + */ +void SPC_SetIOVDDLowVoltageLevel(SPC_Type *base, spc_low_voltage_level_select_t level); + +/*! + * @brief Configs IO voltage detect options. + * + * This function config IO voltage detect options. + * @note: Setting both the voltage detect interrupt and reset + * enable will cause interrupt to be generated on exit from reset. + * If those conditioned is not desired, interrupt/reset so only one is enabled. + * + * @param base SPC peripheral base address. + * @param config Pointer to spc_voltage_detect_config_t structure. + */ +void SPC_SetIOVoltageDetectConfig(SPC_Type *base, const spc_io_voltage_detect_config_t *config); + +/*! + * @brief Lock IO Voltage detect reset setting. + * + * This function locks IO voltage detect reset setting. After invoking this function + * any configuration of system voltage detect reset will be ignored. + * + * @param base SPC peripheral base address. + */ +static inline void SPC_LockIOVoltageDetectResetSetting(SPC_Type *base) +{ + base->VD_IO_CFG |= SPC_VD_IO_CFG_LOCK_MASK; +} + +/*! + * @brief Unlock IO voltage detect reset setting. + * + * This function unlocks IO voltage detect reset setting. If locks the IO + * voltage detect reset setting, invoking this function to unlock. + * + * @param base SPC peripheral base address. + */ +static inline void SPC_UnlockIOVoltageDetectResetSetting(SPC_Type *base) +{ + base->VD_IO_CFG &= ~SPC_VD_IO_CFG_LOCK_MASK; +} + +/*! + * @brief Enables/Disables the IO High Voltage Detector in Active mode. + * + * @note If the IO high voltage detect is enabled in Active mode, please note that the bandgap must be enabled + * and the drive strength of each regulator must not set to low in Active mode. + * + * @param base SPC peripheral base address. + * @param enable Enable/Disable IO HVD. + * true - Enable IO High voltage detector in active mode. + * false - Disable IO High voltage detector in active mode. + * + * @retval #kStatus_Success Enable/Disable IO High Voltage Detect successfully. + */ +status_t SPC_EnableActiveModeIOHighVoltageDetect(SPC_Type *base, bool enable); + +/*! + * @brief Enables/Disables the IO Low Voltage Detector in Active mode. + * + * @note If the IO low voltage detect is enabled in Active mode, please note that the bandgap must be enabled + * and the drive strength of each regulator must not set to low in Active mode. + * + * @param base SPC peripheral base address. + * @param enable Enable/Disable IO LVD. + * true - Enable IO Low voltage detector in active mode. + * false - Disable IO Low voltage detector in active mode. + * + * @retval #kStatus_Success Enable IO Low Voltage Detect successfully. + */ +status_t SPC_EnableActiveModeIOLowVoltageDetect(SPC_Type *base, bool enable); + +/*! + * @brief Enables/Disables the IO High Voltage Detector in Low Power mode. + * + * @note If the IO high voltage detect is enabled in Low Power mode, please note that the bandgap must be enabled + * and the drive strength of each regulator must not set to low in Low Power mode. + * + * @param base SPC peripheral base address. + * @param enable Enable/Disable IO HVD. + * true - Enable IO High voltage detector in low power mode. + * false - Disable IO High voltage detector in low power mode. + * + * @retval #kStatus_Success Enable IO High Voltage Detect in low power mode successfully. + */ +status_t SPC_EnableLowPowerModeIOHighVoltageDetect(SPC_Type *base, bool enable); + +/*! + * @brief Enables/Disables the IO Low Voltage Detector in Low Power mode. + * + * @note If the IO low voltage detect is enabled in Low Power mode, please note that the bandgap must be enabled + * and the drive strength of each regulator must not set to low in Low Power mode. + * + * @param base SPC peripheral base address. + * @param enable Enable/Disable IO LVD. + * true - Enable IO Low voltage detector in low power mode. + * false - Disable IO Low voltage detector in low power mode. + * + * @retval #kStatus_Success Enable/Disable IO Low Voltage Detect in low power mode successfully. + */ +status_t SPC_EnableLowPowerModeIOLowVoltageDetect(SPC_Type *base, bool enable); + +/*! @} */ + +#endif /* FSL_FEATURE_MCX_SPC_HAS_IOVDD_VD */ + +/*! + * @name External Voltage domains configuration + * @{ + */ +/*! + * @brief Configs external voltage domains + * + * This function configs external voltage domains isolation. + * + * @param base SPC peripheral base address. + * @param lowPowerIsoMask The mask of external domains isolate enable during low power mode. Please read the Reference + * Manual for the Bitmap. + * @param IsoMask The mask of external domains isolate. Please read the Reference Manual for the Bitmap. + */ +void SPC_SetExternalVoltageDomainsConfig(SPC_Type *base, uint8_t lowPowerIsoMask, uint8_t IsoMask); + +/*! + * @brief Gets External Domains status. + * + * @param base SPC peripheral base address. + * @return The status of each external domain. + */ +static inline uint8_t SPC_GetExternalDomainsStatus(SPC_Type *base) +{ + return (uint8_t)(base->EVD_CFG >> SPC_EVD_CFG_REG_EVDSTAT_SHIFT); +} + +/*! @} */ + +/*! + * @name Low Level APIs To Set CORE LDO Regulator + * @{ + */ + +#if (defined(FSL_FEATURE_MCX_SPC_HAS_CNTRL_REG) && FSL_FEATURE_MCX_SPC_HAS_CNTRL_REG) +/*! + * @brief Enable/Disable Core LDO regulator. + * + * @note The CORE LDO enable bit is write-once. + * + * @param base SPC peripheral base address. + * @param enable Enable/Disable CORE LDO Regulator. + * true - Enable CORE LDO Regulator. + * false - Disable CORE LDO Regulator. + */ +static inline void SPC_EnableCoreLDORegulator(SPC_Type *base, bool enable) +{ + if (enable) + { + base->CNTRL |= SPC_CNTRL_CORELDO_EN_MASK; + } + else + { + /* + * $Branch Coverage Justification$ + * If CORE_LDO is disabled, all RAMs data will powered off. + */ + base->CNTRL &= ~SPC_CNTRL_CORELDO_EN_MASK; + } +} +#endif /* FSL_FEATURE_MCX_SPC_HAS_CNTRL_REG */ + +#if (defined(FSL_FEATURE_MCX_SPC_HAS_DPDOWN_PULLDOWN_DISABLE_BIT) && \ + FSL_FEATURE_MCX_SPC_HAS_DPDOWN_PULLDOWN_DISABLE_BIT) +/*! + * @brief Enable/Disable the CORE LDO Regulator pull down in Deep Power Down. + * + * @note This function only useful when enabled the CORE LDO Regulator. + * + * @param base SPC peripheral base address. + * @param pulldown Enable/Disable CORE LDO pulldown in Deep Power Down mode. + * true - CORE LDO Regulator will discharge in Deep Power Down mode. + * false - CORE LDO Regulator will not discharge in Deep Power Down mode. + */ +static inline void SPC_PullDownCoreLDORegulator(SPC_Type *base, bool pulldown) +{ + if (pulldown) + { + base->CORELDO_CFG &= ~SPC_CORELDO_CFG_DPDOWN_PULLDOWN_DISABLE_MASK; + } + else + { + base->CORELDO_CFG |= SPC_CORELDO_CFG_DPDOWN_PULLDOWN_DISABLE_MASK; + } +} +#endif /* FSL_FEATURE_MCX_SPC_HAS_DPDOWN_PULLDOWN_DISABLE_BIT */ + +/*! + * @brief Configs Core LDO Regulator in Active mode. + * + * @note The bandgap must be enabled before invoking this function. + * @note To set Core LDO as low drive strength, all HVDs/LVDs must be disabled previously. + * + * @param base SPC peripheral base address. + * @param option Pointer to the spc_active_mode_core_ldo_option_t structure. + * + * @retval kStatus_Success Config Core LDO regulator in Active power mode successful. + * @retval kStatus_SPC_Busy The SPC instance is busy to execute any type of power mode transition. + * @retval kStatus_SPC_BandgapModeWrong Bandgap should be enabled before invoking this function. + * @retval kStatus_SPC_CORELDOLowDriveStrengthIgnore To set Core LDO as low drive strength, + * all LVDs/HVDs must be disabled before invoking this function. + */ +status_t SPC_SetActiveModeCoreLDORegulatorConfig(SPC_Type *base, const spc_active_mode_core_ldo_option_t *option); + +/*! + * @brief Set Core LDO Regulator Voltage level in Active mode. + * + * @param base SPC peripheral base address. + * @param voltageLevel Specify the voltage level of CORE LDO Regulator in Active mode, please + refer to @ref spc_core_ldo_voltage_level_t. + * + * @note In active mode, the Core LDO voltage level should only be changed when the + * Core LDO is in normal drive strength. + * + * @note Update Core LDO voltage level will set Busy flag, + * this function return only when busy flag is cleared by hardware + * + * @retval kStatus_SPC_CORELDOVoltageSetFail The drive strength of Core LDO is not normal. + * @retval kStatus_Success Set Core LDO regulator voltage level in Active power mode successful. + */ +status_t SPC_SetActiveModeCoreLDORegulatorVoltageLevel(SPC_Type *base, spc_core_ldo_voltage_level_t voltageLevel); + +/*! + * @brief Gets CORE LDO Regulator Voltage level. + * + * This function returns the voltage level of CORE LDO Regulator in Active mode. + * + * @param base SPC peripheral base address. + * @return Voltage level of CORE LDO in type of @ref spc_core_ldo_voltage_level_t enumeration. + */ +static inline spc_core_ldo_voltage_level_t SPC_GetActiveModeCoreLDOVDDVoltageLevel(SPC_Type *base) +{ + return (spc_core_ldo_voltage_level_t)(uint32_t)((base->ACTIVE_CFG & SPC_ACTIVE_CFG_CORELDO_VDD_LVL_MASK) >> + SPC_ACTIVE_CFG_CORELDO_VDD_LVL_SHIFT); +} + +#if (defined(FSL_FEATURE_SPC_HAS_CORELDO_VDD_DS) && FSL_FEATURE_SPC_HAS_CORELDO_VDD_DS) +/*! + * @brief Set Core LDO VDD Regulator Drive Strength in Active mode. + * + * @param base SPC peripheral base address. + * @param driveStrength Specify the drive strength of CORE LDO Regulator in Active mode, please + refer to @ref spc_core_ldo_drive_strength_t. + * + * @retval #kStatus_Success Set Core LDO regulator drive strength in Active power mode successful. + * @retval #kStatus_SPC_CORELDOLowDriveStrengthIgnore If any voltage detect enabled, + core_ldo's drive strength can not set to low. + * @retval #kStatus_SPC_BandgapModeWrong The selected bandgap mode is not allowed. + */ +status_t SPC_SetActiveModeCoreLDORegulatorDriveStrength(SPC_Type *base, spc_core_ldo_drive_strength_t driveStrength); + +/*! + * @brief Gets CORE LDO VDD Regulator Drive Strength in Active mode. + * + * @param base SPC peripheral base address. + * @return Drive Strength of CORE LDO regulator in Active mode, please refer to @ref spc_core_ldo_drive_strength_t. + */ +static inline spc_core_ldo_drive_strength_t SPC_GetActiveModeCoreLDODriveStrength(SPC_Type *base) +{ + return (spc_core_ldo_drive_strength_t)(uint32_t)((base->ACTIVE_CFG & SPC_ACTIVE_CFG_CORELDO_VDD_DS_MASK) >> + SPC_ACTIVE_CFG_CORELDO_VDD_DS_SHIFT); +} +#endif /* defined(FSL_FEATURE_SPC_HAS_CORELDO_VDD_DS) && FSL_FEATURE_SPC_HAS_CORELDO_VDD_DS */ + +/*! + * @brief Configs CORE LDO Regulator in low power mode + * + * This function configs CORE LDO Regulator in Low Power mode. + * If CORE LDO VDD Drive Strength is set to Normal, the CORE LDO VDD regulator voltage + * level in Active mode must be equal to the voltage level in Low power mode. And the Bandgap + * must be programmed to select bandgap enabled. + * Core VDD voltage levels for the Core LDO low power regulator can only be changed when the CORE + * LDO Drive Strength set as Normal. + * + * @param base SPC peripheral base address. + * @param option Pointer to the spc_lowpower_mode_core_ldo_option_t structure. + * + * @retval #kStatus_Success Config Core LDO regulator in power mode successfully. + * @retval #kStatus_SPC_Busy The SPC instance is busy to execute any type of power mode transition. + * @retval #kStatus_SPC_CORELDOLowDriveStrengthIgnore Set driver strength to low will be ignored. + * @retval #kStatus_SPC_CORELDOVoltageSetFail. Fail to change Core LDO voltage level. + */ +status_t SPC_SetLowPowerModeCoreLDORegulatorConfig(SPC_Type *base, const spc_lowpower_mode_core_ldo_option_t *option); + +/*! + * @brief Set Core LDO VDD Regulator Voltage level in Low power mode. + * + * @note If CORE LDO's drive strength is set to Normal, the CORE LDO VDD regulator voltage in active mode and low power + * mode must be same. + * @note Voltage level for the CORE LDO in low power mode can only be changed when the CORE LDO Drive Strength set as + * Normal. + * + * @param base SPC peripheral base address. + * @param voltageLevel Voltage level of CORE LDO Regulator in Low power mode, please + refer to @ref spc_core_ldo_voltage_level_t. + * + * @retval #kStatus_SPC_CORELDOVoltageWrong Voltage level in active mode and low power mode is not same. + * @retval #kStatus_Success Set Core LDO regulator voltage level in Low power mode successful. + * @retval #kStatus_SPC_CORELDOVoltageSetFail Fail to update voltage level because drive strength is incorrect. + */ +status_t SPC_SetLowPowerModeCoreLDORegulatorVoltageLevel(SPC_Type *base, spc_core_ldo_voltage_level_t voltageLevel); + +/*! + * @brief Gets the CORE LDO VDD Regulator Voltage Level for Low Power modes. + * + * @param base SPC peripheral base address. + * @return The CORE LDO VDD Regulator's voltage level. + */ +static inline spc_core_ldo_voltage_level_t SPC_GetLowPowerCoreLDOVDDVoltageLevel(SPC_Type *base) +{ + return ((spc_core_ldo_voltage_level_t)(uint32_t)((base->LP_CFG & SPC_LP_CFG_CORELDO_VDD_LVL_MASK) >> + SPC_LP_CFG_CORELDO_VDD_LVL_SHIFT)); +} + +/*! + * @brief Set Core LDO VDD Regulator Drive Strength in Low power mode. + * + * @param base SPC peripheral base address. + * @param driveStrength Specify drive strength of CORE LDO in low power mode. + * + * @retval #kStatus_SPC_CORELDOLowDriveStrengthIgnore Some voltage detect enabled, CORE LDO's drive strength can not set + * as low. + * @retval #kStatus_Success Set Core LDO regulator drive strength in Low power mode successful. + * @retval #kStatus_SPC_BandgapModeWrong Bandgap is disabled when attempt to set CORE LDO work as normal drive strength. + */ +status_t SPC_SetLowPowerModeCoreLDORegulatorDriveStrength(SPC_Type *base, spc_core_ldo_drive_strength_t driveStrength); + +/*! + * @brief Gets CORE LDO VDD Drive Strength for Low Power modes. + * + * @param base SPC peripheral base address. + * @return The CORE LDO's VDD Drive Strength. + */ +static inline spc_core_ldo_drive_strength_t SPC_GetLowPowerCoreLDOVDDDriveStrength(SPC_Type *base) +{ + return (spc_core_ldo_drive_strength_t)(uint32_t)((base->LP_CFG & SPC_LP_CFG_CORELDO_VDD_DS_MASK) >> + SPC_LP_CFG_CORELDO_VDD_DS_SHIFT); +} + +#if (defined(FSL_FEATURE_MCX_SPC_HAS_SYS_LDO) && FSL_FEATURE_MCX_SPC_HAS_SYS_LDO) +/*! + * @name Low Level APIs To Set System LDO Regulator + * @{ + */ + +/*! + * @brief Enable/Disable System LDO regulator. + * + * @note The SYSTEM LDO enable bit is write-once. + * + * @param base SPC peripheral base address. + * @param enable Enable/Disable System LDO Regulator. + * true - Enable System LDO Regulator. + * false - Disable System LDO Regulator. + */ +static inline void SPC_EnableSystemLDORegulator(SPC_Type *base, bool enable) +{ + if (enable) + { + base->CNTRL |= SPC_CNTRL_SYSLDO_EN_MASK; + } + else + { + /* + * $Branch Coverage Justification$ + * If SYSTEM_LDO is disabled, may cause some unexpected issues. + */ + base->CNTRL &= ~SPC_CNTRL_SYSLDO_EN_MASK; + } +} + +/*! + * @brief Enable/Disable current sink feature of System LDO Regulator. + * + * @param base SPC peripheral base address. + * @param sink Enable/Disable current sink feature. + * true - Enable current sink feature of System LDO Regulator. + * false - Disable current sink feature of System LDO Regulator. + */ +static inline void SPC_EnableSystemLDOSinkFeature(SPC_Type *base, bool sink) +{ + if (sink) + { + base->SYSLDO_CFG |= SPC_SYSLDO_CFG_ISINKEN_MASK; + } + else + { + base->SYSLDO_CFG &= ~SPC_SYSLDO_CFG_ISINKEN_MASK; + } +} + +/*! + * @brief Configs System LDO VDD Regulator in Active mode. + * + * @note If System LDO VDD Drive Strength is set to Normal, the Bandgap mode in Active mode must be programmed + * to a value that enables the bandgap. + * @note If any voltage detects are kept enabled, configuration to set System LDO VDD drive strength to low will + * be ignored. + * @note If select System LDO VDD Regulator voltage level to Over Drive Voltage, the Drive Strength of System LDO VDD + * Regulator must be set to Normal otherwise the regulator Drive Strength will be forced to Normal. + * @note If select System LDO VDD Regulator voltage level to Over Drive Voltage, the High voltage detect must be + * disabled. Otherwise it will be fail to regulator to Over Drive Voltage. + * + * @param base SPC peripheral base address. + * @param option Pointer to the spc_active_mode_sys_ldo_option_t structure. + * + * @retval #kStatus_Success Config System LDO regulator in Active power mode successful. + * @retval #kStatus_SPC_Busy The SPC instance is busy to execute any type of power mode transition. + * @retval #kStatus_SPC_BandgapModeWrong The bandgap is not enabled before invoking this function. + * @retval #kStatus_SPC_SYSLDOOverDriveVoltageFail HVD of System VDD is not disable before setting to Over Drive + * voltage. + * @retval kStatus_SPC_SYSLDOLowDriveStrengthIgnore Set System LDO VDD regulator's driver strength to Low will be + * ignored. + */ +status_t SPC_SetActiveModeSystemLDORegulatorConfig(SPC_Type *base, const spc_active_mode_sys_ldo_option_t *option); + +/*! + * @brief Set System LDO Regulator voltage level in Active mode. + * + * @note The system LDO regulator can only operate at the overdrive voltage level for a limited amount of time for the + * life of chip. + * + * @param base SPC peripheral base address. + * @param voltageLevel Specify the voltage level of System LDO Regulator in Active mode. + * + * @retval #kStatus_Success Set System LDO Regulator voltage level in Active mode successfully. + * @retval #kStatus_SPC_SYSLDOOverDriveVoltageFail Must disable system LDO high voltage detector before specifying + * overdrive voltage. + */ +status_t SPC_SetActiveModeSystemLDORegulatorVoltageLevel(SPC_Type *base, spc_sys_ldo_voltage_level_t voltageLevel); + +/*! + * @brief Get System LDO Regulator voltage level in Active mode. + * + * @param base SPC peripheral base address. + * @return System LDO Regulator voltage level in Active mode, please refer to @ref spc_sys_ldo_voltage_level_t. + */ +static inline spc_sys_ldo_voltage_level_t SPC_GetActiveModeSystemLDORegulatorVoltageLevel(SPC_Type *base) +{ + return (spc_sys_ldo_voltage_level_t)(uint32_t)((base->ACTIVE_CFG & SPC_ACTIVE_CFG_SYSLDO_VDD_LVL_MASK) >> + SPC_ACTIVE_CFG_SYSLDO_VDD_LVL_SHIFT); +} + +/*! + * @brief Set System LDO Regulator Drive Strength in Active mode. + * + * @param base SPC peripheral base address. + * @param driveStrength Specify the drive strength of System LDO Regulator in Active mode. + * + * @retval #kStatus_Success Set System LDO Regulator drive strength in Active mode successfully. + * @retval #kStatus_SPC_SYSLDOLowDriveStrengthIgnore Attempt to specify low drive strength is ignored due to any + voltage detect feature is enabled in active mode. + * @retval #kStatus_SPC_BandgapModeWrong Bandgap mode in Active mode must be programmed to a value that enables + the bandgap if attempt to specify normal drive strength. + */ +status_t SPC_SetActiveModeSystemLDORegulatorDriveStrength(SPC_Type *base, spc_sys_ldo_drive_strength_t driveStrength); + +/*! + * @brief Get System LDO Regulator Drive Strength in Active mode. + * + * @param base SPC peripheral base address. + * @return System LDO regulator drive strength in Active mode, please refer to @ref spc_sys_ldo_drive_strength_t. + */ +static inline spc_sys_ldo_drive_strength_t SPC_GetActiveModeSystemLDORegulatorDriveStrength(SPC_Type *base) +{ + return (spc_sys_ldo_drive_strength_t)(uint32_t)((base->ACTIVE_CFG & SPC_ACTIVE_CFG_SYSLDO_VDD_DS_MASK) >> + SPC_ACTIVE_CFG_SYSLDO_VDD_DS_SHIFT); +} + +/*! + * @brief Configs System LDO regulator in low power modes. + * + * This function configs System LDO regulator in low power modes. + * If System LDO VDD Regulator Drive strength is set to normal, bandgap mode in low power + * mode must be programmed to a value that enables the Bandgap. + * If any High voltage detectors or Low Voltage detectors are kept enabled, configuration + * to set System LDO Regulator drive strength as Low will be ignored. + * + * @param base SPC peripheral base address. + * @param option Pointer to spc_lowpower_mode_sys_ldo_option_t structure. + * + * @retval #kStatus_Success Config System LDO regulator in Low Power Mode successfully. + * @retval #kStatus_SPC_Busy The SPC instance is busy to execute any type of power mode transition. + * @retval #kStatus_SPC_SYSLDOLowDriveStrengthIgnore Set driver strength to low will be ignored. + */ +status_t SPC_SetLowPowerModeSystemLDORegulatorConfig(SPC_Type *base, const spc_lowpower_mode_sys_ldo_option_t *option); + +/*! + * @brief Set System LDO Regulator drive strength in Low Power Mode. + * + * @param base SPC peripheral base address. + * @param driveStrength Specify the drive strength of System LDO Regulator in Low Power Mode. + * + * @retval #kStatus_Success Set System LDO Regulator drive strength in Low Power Mode successfully. + * @retval #kStatus_SPC_SYSLDOLowDriveStrengthIgnore Attempt to specify low drive strength is ignored due to any + voltage detect feature is enabled in low power mode. + * @retval #kStatus_SPC_BandgapModeWrong Bandgap mode in low power mode must be programmed to a value that enables + the bandgap if attempt to specify normal drive strength. + */ +status_t SPC_SetLowPowerModeSystemLDORegulatorDriveStrength(SPC_Type *base, spc_sys_ldo_drive_strength_t driveStrength); + +/*! + * @brief Get System LDO Regulator drive strength in Low Power Mode. + * + * @param base SPC peripheral base address. + * @return System LDO regulator drive strength in Low Power Mode, please refer to @ref spc_sys_ldo_drive_strength_t. + */ +static inline spc_sys_ldo_drive_strength_t SPC_GetLowPowerModeSystemLDORegulatorDriveStrength(SPC_Type *base) +{ + return (spc_sys_ldo_drive_strength_t)(uint32_t)((base->LP_CFG & SPC_LP_CFG_SYSLDO_VDD_DS_MASK) >> + SPC_LP_CFG_SYSLDO_VDD_DS_SHIFT); +} +/*! @} */ +#endif /* FSL_FEATURE_MCX_SPC_HAS_SYS_LDO */ + +#if (defined(FSL_FEATURE_MCX_SPC_HAS_DCDC) && FSL_FEATURE_MCX_SPC_HAS_DCDC) +/*! + * @name Low Level APIs To Set DCDC Regulator + * @{ + */ + +/*! + * @brief Enable/Disable DCDC Regulator. + * + * @note The DCDC enable bit is write-once, settings only reset after a POR, LVD, or HVD event. + * + * @param base SPC peripheral base address. + * @param enable Enable/Disable DCDC Regulator. + * true - Enable DCDC Regulator. + * false - Disable DCDC Regulator. + */ +static inline void SPC_EnableDCDCRegulator(SPC_Type *base, bool enable) +{ + if (enable) + { + base->CNTRL |= SPC_CNTRL_DCDC_EN_MASK; + } + else + { + /* + * $Branch Coverage Justification$ + * If DCDC is disabled, all RAMs data will powered off. + */ + base->CNTRL &= ~SPC_CNTRL_DCDC_EN_MASK; + } +} + +/*! + * @brief Config DCDC Burst options + * + * @param base SPC peripheral base address. + * @param config Pointer to spc_dcdc_burst_config_t structure. + */ +void SPC_SetDCDCBurstConfig(SPC_Type *base, spc_dcdc_burst_config_t *config); + +/*! + * @brief Trigger a software burst request to DCDC. + * + * @param base SPC peripheral base address. + */ +static inline void SPC_TriggerDCDCBurstRequest(SPC_Type *base) +{ + /* Blocking until previous DCDC burst completed. */ + while ((base->DCDC_BURST_CFG & SPC_DCDC_BURST_CFG_BURST_ACK_MASK) == 0UL) + { + } + + base->DCDC_BURST_CFG |= SPC_DCDC_BURST_CFG_BURST_REQ_MASK; +} + +/*! + * @brief Check if burst acknowledge flag is asserted. + * + * @param base SPC peripheral base address. + * + * @retval false DCDC burst not complete. + * @retval true DCDC burst complete. + */ +static inline bool SPC_CheckDCDCBurstAck(SPC_Type *base) +{ + return ((base->DCDC_BURST_CFG & SPC_DCDC_BURST_CFG_BURST_ACK_MASK) != 0UL); +} + +/*! + * @brief Clear DCDC busrt acknowledge flag. + * + * @param base SPC periphral base address. + */ +static inline void SPC_ClearDCDCBurstAckFlag(SPC_Type *base) +{ + base->DCDC_BURST_CFG |= SPC_DCDC_BURST_CFG_BURST_ACK_MASK; +} + +/*! + * @brief Set the count value of the reference clock to configure the period of DCDC not active. + * + * @note This function is only useful when DCDC's drive strength is set as pulse refresh. + * @note The pulse duration(time between on and off) is: reference clock period * (count + 2). + * + * @param base SPC peripheral base address. + * @param count The count value, 16 bit width. + */ +void SPC_SetDCDCRefreshCount(SPC_Type *base, uint16_t count); + +#if (defined(FSL_FEATURE_MCX_SPC_HAS_DCDC_CFG_BLEED_EN) && FSL_FEATURE_MCX_SPC_HAS_DCDC_CFG_BLEED_EN) +/*! + * @brief Enable a bleed resistor to discharge DCDC output when DCDC is disabled. + * + * @param base SPC peripheral base address. + * @param enable Used to enable/disable bleed resistor. + */ +static inline void SPC_EnableDCDCBleedResistor(SPC_Type *base, bool enable) +{ + if (enable) + { + base->DCDC_CFG |= SPC_DCDC_CFG_BLEED_EN_MASK; + } + else + { + base->DCDC_CFG &= ~SPC_DCDC_CFG_BLEED_EN_MASK; + } +} +#endif /* FSL_FEATURE_MCX_SPC_HAS_DCDC_CFG_BLEED_EN */ + +/*! + * @brief Configs DCDC_CORE Regulator in Active mode. + * + * @note When changing the DCDC output voltage level, take care to change the CORE LDO voltage level. + * + * @param base SPC peripheral base address. + * @param option Pointer to the spc_active_mode_dcdc_option_t structure. + * + * @retval #kStatus_Success Config DCDC regulator in Active power mode successful. + * @retval #kStatus_SPC_Busy The SPC instance is busy to execute any type of power mode transition. + * @retval #kStatus_SPC_BandgapModeWrong Set DCDC_CORE Regulator drive strength to Normal, the Bandgap must be enabled. + */ +status_t SPC_SetActiveModeDCDCRegulatorConfig(SPC_Type *base, const spc_active_mode_dcdc_option_t *option); + +/*! + * @brief Set DCDC_CORE Regulator voltage level in Active mode. + * + * @note When changing the DCDC output voltage level, take care to change the CORE LDO voltage level. + * + * @param base SPC peripheral base address. + * @param voltageLevel Specify the DCDC_CORE Regulator voltage level, please refer to @ref spc_dcdc_voltage_level_t. + */ +static inline void SPC_SetActiveModeDCDCRegulatorVoltageLevel(SPC_Type *base, spc_dcdc_voltage_level_t voltageLevel) +{ + base->ACTIVE_CFG = + (base->ACTIVE_CFG & (~SPC_ACTIVE_CFG_DCDC_VDD_LVL_MASK)) | SPC_ACTIVE_CFG_DCDC_VDD_LVL(voltageLevel); +} + +/*! + * @brief Get DCDC_CORE Regulator voltage level in Active mode. + * + * @param base SPC peripheral base address. + * @return DCDC_CORE Regulator voltage level, please refer to @ref spc_dcdc_voltage_level_t. + */ +static inline spc_dcdc_voltage_level_t SPC_GetActiveModeDCDCRegulatorVoltageLevel(SPC_Type *base) +{ + return (spc_dcdc_voltage_level_t)((uint32_t)((base->ACTIVE_CFG & SPC_ACTIVE_CFG_DCDC_VDD_LVL_MASK) >> + SPC_ACTIVE_CFG_DCDC_VDD_LVL_SHIFT)); +} + +/*! + * @brief Set DCDC_CORE Regulator drive strength in Active mode. + * + * @note To set DCDC drive strength as Normal, the bandgap must be enabled. + * + * @param base SPC peripheral base address. + * @param driveStrength Specify the DCDC_CORE regulator drive strength, please refer to @ref spc_dcdc_drive_strength_t. + * + * @retval #kStatus_Success Set DCDC_CORE Regulator drive strength in Active mode successfully. + * @retval #kStatus_SPC_BandgapModeWrong Set DCDC_CORE Regulator drive strength to Normal, the Bandgap must be enabled. + */ +status_t SPC_SetActiveModeDCDCRegulatorDriveStrength(SPC_Type *base, spc_dcdc_drive_strength_t driveStrength); + +/*! + * @brief Get DCDC_CORE Regulator drive strength in Active mode. + * + * @param base SPC peripheral base address. + * @return DCDC_CORE Regulator drive strength, please refer to @ref spc_dcdc_drive_strength_t. + */ +static inline spc_dcdc_drive_strength_t SPC_GetActiveModeDCDCRegulatorDriveStrength(SPC_Type *base) +{ + return (spc_dcdc_drive_strength_t)((uint32_t)((base->ACTIVE_CFG & SPC_ACTIVE_CFG_DCDC_VDD_DS_MASK) >> + SPC_ACTIVE_CFG_DCDC_VDD_DS_SHIFT)); +} + +/*! + * @brief Configs DCDC_CORE Regulator in Low power modes. + * + * @note If DCDC_CORE Drive Strength is set to Normal, the Bandgap mode in Low Power mode must be programmed + * to a value that enables the Bandgap. + * @note In Deep Power Down mode, DCDC regulator is always turned off. + * + * @param base SPC peripheral base address. + * @param option Pointer to the spc_lowpower_mode_dcdc_option_t structure. + * + * @retval #kStatus_Success Config DCDC regulator in low power mode successfully. + * @retval #kStatus_SPC_Busy The SPC instance is busy to execute any type of power mode transition. + * @retval #kStatus_SPC_BandgapModeWrong The bandgap mode setting in Low Power mode is wrong. + */ +status_t SPC_SetLowPowerModeDCDCRegulatorConfig(SPC_Type *base, const spc_lowpower_mode_dcdc_option_t *option); + +/*! + * @brief Set DCDC_CORE Regulator drive strength in Low power mode. + * + * @note To set drive strength as normal, the bandgap must be enabled. + * + * @param base SPC peripheral base address. + * @param driveStrength Specify the DCDC_CORE Regulator drive strength, please refer to @ref spc_dcdc_drive_strength_t. + * + * @retval #kStatus_Success Set DCDC_CORE Regulator drive strength in Low power mode successfully. + * @retval #kStatus_SPC_BandgapModeWrong Set DCDC_CORE Regulator drive strength to Normal, the Bandgap must be enabled. + */ +status_t SPC_SetLowPowerModeDCDCRegulatorDriveStrength(SPC_Type *base, spc_dcdc_drive_strength_t driveStrength); + +/*! + * @brief Get DCDC_CORE Regulator drive strength in Low power mode. + * + * @param base SPC peripheral base address. + * @return DCDC_CORE Regulator drive strength, please refer to @ref spc_dcdc_drive_strength_t. + */ +static inline spc_dcdc_drive_strength_t SPC_GetLowPowerModeDCDCRegulatorDriveStrength(SPC_Type *base) +{ + return (spc_dcdc_drive_strength_t)((uint32_t)((base->LP_CFG & SPC_LP_CFG_DCDC_VDD_DS_MASK) >> + SPC_LP_CFG_DCDC_VDD_DS_SHIFT)); +} + +/*! + * @brief Set DCDC_CORE Regulator voltage level in Low power mode. + * + * @note To change DCDC level in Low-Power mode: + * 1. Configure LP_CFG[DCDC_VDD_LVL] to desired level; + * 2. Configure LP_CFG[DCDC_VDD_DS] to low driver strength; + * 3. Configure ACTIVE_CFG[DCDC_VDD_LVL] to same level programmed in #1. + * + * @note After invoking this function, the voltage level in active mode(wakeup from low power modes) also changed, + * if it is necessary, please invoke SPC_SetActiveModeDCDCRegulatorVoltageLevel() to change to desried voltage level. + * + * @param base SPC peripheral base address. + * @param voltageLevel Specify the DCDC_CORE Regulator voltage level, please refer to @ref spc_dcdc_voltage_level_t. + */ +static inline void SPC_SetLowPowerModeDCDCRegulatorVoltageLevel(SPC_Type *base, spc_dcdc_voltage_level_t voltageLevel) +{ + base->LP_CFG = (base->LP_CFG & (~SPC_LP_CFG_DCDC_VDD_LVL_MASK)) | SPC_LP_CFG_DCDC_VDD_LVL(voltageLevel); + (void)SPC_SetLowPowerModeDCDCRegulatorDriveStrength(base, kSPC_DCDC_LowDriveStrength); + SPC_SetActiveModeDCDCRegulatorVoltageLevel(base, voltageLevel); +} + +/*! + * @brief Get DCDC_CORE Regulator voltage level in Low power mode. + * + * @param base SPC peripheral base address. + * @return DCDC_CORE Regulator voltage level, please refer to @ref spc_dcdc_voltage_level_t. + */ +static inline spc_dcdc_voltage_level_t SPC_GetLowPowerModeDCDCRegulatorVoltageLevel(SPC_Type *base) +{ + return (spc_dcdc_voltage_level_t)((uint32_t)((base->LP_CFG & SPC_LP_CFG_DCDC_VDD_LVL_MASK) >> + SPC_LP_CFG_DCDC_VDD_LVL_SHIFT)); +} + +/*! @} */ +#endif /* FSL_FEATURE_MCX_SPC_HAS_DCDC */ + +#if defined(__cplusplus) +} +#endif /* __cplusplus */ + +/*! @} */ + +#endif /* FSL_SPC_H_ */ diff --git a/hw/bsp/mcx/family.c b/hw/bsp/mcx/family.c index ce54097fe..2dfefeb92 100644 --- a/hw/bsp/mcx/family.c +++ b/hw/bsp/mcx/family.c @@ -24,6 +24,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: NXP +*/ + #include "bsp/board_api.h" #include "fsl_device_registers.h" #include "fsl_gpio.h" @@ -56,9 +60,14 @@ void USB0_IRQHandler(void) { void board_init(void) { + BOARD_InitPins(); + BOARD_InitBootClocks(); + + #ifdef XTAL0_CLK_HZ CLOCK_SetupExtClocking(XTAL0_CLK_HZ); + #endif #if CFG_TUSB_OS == OPT_OS_NONE // 1ms tick timer @@ -80,15 +89,7 @@ void board_init(void) { board_led_write(0); #ifdef NEOPIXEL_PIN - // Neopixel - static uint32_t pixelData[NEOPIXEL_NUMBER]; - IOCON_PinMuxSet(IOCON, NEOPIXEL_PORT, NEOPIXEL_PIN, IOCON_PIO_DIG_FUNC4_EN); - - sctpix_init(NEOPIXEL_TYPE); - sctpix_addCh(NEOPIXEL_CH, pixelData, NEOPIXEL_NUMBER); - sctpix_setPixel(NEOPIXEL_CH, 0, 0x100010); - sctpix_setPixel(NEOPIXEL_CH, 1, 0x100010); - sctpix_show(); + // No neo pixel support yet #endif // Button @@ -99,9 +100,6 @@ void board_init(void) { #endif #ifdef UART_DEV - // UART -// IOCON_PinMuxSet(IOCON, UART_RX_PINMUX); -// IOCON_PinMuxSet(IOCON, UART_TX_PINMUX); // Enable UART when debug log is on board_uart_init_clock(); @@ -111,6 +109,7 @@ void board_init(void) { uart_config.baudRate_Bps = CFG_BOARD_UART_BAUDRATE; uart_config.enableTx = true; uart_config.enableRx = true; + LPUART_Init(UART_DEV, &uart_config, 12000000u); #endif @@ -192,17 +191,6 @@ void board_init(void) { void board_led_write(bool state) { GPIO_PinWrite(LED_GPIO, LED_PIN, state ? LED_STATE_ON : (1 - LED_STATE_ON)); - -#ifdef NEOPIXEL_PIN - if (state) { - sctpix_setPixel(NEOPIXEL_CH, 0, 0x100000); - sctpix_setPixel(NEOPIXEL_CH, 1, 0x101010); - } else { - sctpix_setPixel(NEOPIXEL_CH, 0, 0x001000); - sctpix_setPixel(NEOPIXEL_CH, 1, 0x000010); - } - sctpix_show(); -#endif } uint32_t board_button_read(void) { diff --git a/hw/bsp/mcx/family.cmake b/hw/bsp/mcx/family.cmake index 223afb9ec..f857ed31a 100644 --- a/hw/bsp/mcx/family.cmake +++ b/hw/bsp/mcx/family.cmake @@ -8,10 +8,13 @@ include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) # toolchain set up if (MCU_VARIANT STREQUAL "MCXA153") - set(CMAKE_SYSTEM_PROCESSOR cortex-m33-nodsp-nofp CACHE INTERNAL "System Processor") + set(CMAKE_SYSTEM_CPU cortex-m33-nodsp-nofp CACHE INTERNAL "System Processor") set(FAMILY_MCUS MCXA15 CACHE INTERNAL "") +elseif (MCU_VARIANT STREQUAL "MCXA156") + set(CMAKE_SYSTEM_CPU cortex-m33 CACHE INTERNAL "System Processor") + set(FAMILY_MCUS MCXA15 CACHE INTERNAL "") elseif (MCU_VARIANT STREQUAL "MCXN947") - set(CMAKE_SYSTEM_PROCESSOR cortex-m33 CACHE INTERNAL "System Processor") + set(CMAKE_SYSTEM_CPU cortex-m33 CACHE INTERNAL "System Processor") set(FAMILY_MCUS MCXN9 CACHE INTERNAL "") else() message(FATAL_ERROR "MCU_VARIANT not supported") @@ -38,12 +41,14 @@ function(add_board_target BOARD_TARGET) endif() set(STARTUP_FILE_Clang ${STARTUP_FILE_GNU}) + add_library(${BOARD_TARGET} STATIC ${STARTUP_FILE_${CMAKE_C_COMPILER_ID}} # driver - ${SDK_DIR}/devices/${MCU_VARIANT}/drivers/fsl_gpio.c - ${SDK_DIR}/devices/${MCU_VARIANT}/drivers/fsl_common_arm.c - ${SDK_DIR}/devices/${MCU_VARIANT}/drivers/fsl_lpuart.c + ${SDK_DIR}/drivers/gpio/fsl_gpio.c + ${SDK_DIR}/drivers/common/fsl_common_arm.c + ${SDK_DIR}/drivers/lpuart/fsl_lpuart.c + ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/drivers/spc/fsl_spc.c # mcu ${SDK_DIR}/devices/${MCU_VARIANT}/drivers/fsl_clock.c ${SDK_DIR}/devices/${MCU_VARIANT}/drivers/fsl_reset.c @@ -51,18 +56,27 @@ function(add_board_target BOARD_TARGET) ) target_include_directories(${BOARD_TARGET} PUBLIC ${CMSIS_DIR}/CMSIS/Core/Include + ${SDK_DIR}/drivers/gpio/ + ${SDK_DIR}/drivers/lpuart + ${SDK_DIR}/drivers/common + ${SDK_DIR}/drivers/port + ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/drivers/spc ${SDK_DIR}/devices/${MCU_VARIANT} ${SDK_DIR}/devices/${MCU_VARIANT}/drivers ) if (${FAMILY_MCUS} STREQUAL "MCXN9") + target_sources(${BOARD_TARGET} PRIVATE - ${SDK_DIR}/devices/${MCU_VARIANT}/drivers/fsl_lpflexcomm.c + ${SDK_DIR}/drivers/lpflexcomm/fsl_lpflexcomm.c + ) + + target_include_directories(${BOARD_TARGET} PUBLIC + ${SDK_DIR}/drivers/lpflexcomm ) elseif(${FAMILY_MCUS} STREQUAL "MCXA15") - target_sources(${BOARD_TARGET} PRIVATE - ${SDK_DIR}/devices/${MCU_VARIANT}/drivers/fsl_spc.c - ) + + endif() update_board(${BOARD_TARGET}) @@ -110,21 +124,21 @@ function(family_configure_example TARGET RTOS) # Add TinyUSB target and port source if (${FAMILY_MCUS} STREQUAL "MCXN9") - family_add_tinyusb(${TARGET} OPT_MCU_MCXN9 ${RTOS}) + family_add_tinyusb(${TARGET} OPT_MCU_MCXN9) elseif(${FAMILY_MCUS} STREQUAL "MCXA15") - family_add_tinyusb(${TARGET} OPT_MCU_MCXA15 ${RTOS}) + family_add_tinyusb(${TARGET} OPT_MCU_MCXA15) endif() - target_sources(${TARGET}-tinyusb PUBLIC + target_sources(${TARGET} PUBLIC # TinyUSB: Port0 is chipidea FS, Port1 is chipidea HS ${TOP}/src/portable/chipidea/$ ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) # Flashing + family_add_bin_hex(${TARGET}) family_flash_jlink(${TARGET}) #family_flash_nxplink(${TARGET}) #family_flash_pyocd(${TARGET}) diff --git a/hw/bsp/mcx/family.mk b/hw/bsp/mcx/family.mk index 58149fb8d..a16f4b6c0 100644 --- a/hw/bsp/mcx/family.mk +++ b/hw/bsp/mcx/family.mk @@ -1,8 +1,6 @@ UF2_FAMILY_ID = 0x2abc77ec SDK_DIR = hw/mcu/nxp/mcux-sdk -DEPS_SUBMODULES += $(SDK_DIR) lib/CMSIS_5 - include $(TOP)/$(BOARD_PATH)/board.mk # Default to Highspeed PORT1 @@ -35,18 +33,19 @@ SRC_C += \ $(SDK_DIR)/devices/$(MCU_VARIANT)/system_$(MCU_CORE).c \ $(SDK_DIR)/devices/$(MCU_VARIANT)/drivers/fsl_clock.c \ $(SDK_DIR)/devices/$(MCU_VARIANT)/drivers/fsl_reset.c \ - $(SDK_DIR)/devices/$(MCU_VARIANT)/drivers/fsl_gpio.c \ - $(SDK_DIR)/devices/$(MCU_VARIANT)/drivers/fsl_lpuart.c \ - $(SDK_DIR)/devices/$(MCU_VARIANT)/drivers/fsl_common_arm.c \ + ${SDK_DIR}/drivers/gpio/fsl_gpio.c \ + ${SDK_DIR}/drivers/lpuart/fsl_lpuart.c \ + ${SDK_DIR}/drivers/common/fsl_common_arm.c\ + hw/bsp/mcx/drivers/spc/fsl_spc.c # fsl_lpflexcomm for MCXN9 ifeq ($(MCU_VARIANT), MCXN947) - SRC_C += $(SDK_DIR)/devices/$(MCU_VARIANT)/drivers/fsl_lpflexcomm.c + SRC_C += ${SDK_DIR}/drivers/lpflexcomm/fsl_lpflexcomm.c endif # fsl_spc for MCXNA15 ifeq ($(MCU_VARIANT), MCXA153) - SRC_C += $(SDK_DIR)/devices/$(MCU_VARIANT)/drivers/fsl_spc.c + endif INC += \ @@ -54,5 +53,15 @@ INC += \ $(TOP)/lib/CMSIS_5/CMSIS/Core/Include \ $(TOP)/$(SDK_DIR)/devices/$(MCU_VARIANT) \ $(TOP)/$(SDK_DIR)/devices/$(MCU_VARIANT)/drivers \ + $(TOP)/$(SDK_DIR)/drivers/ \ + $(TOP)/$(SDK_DIR)/drivers/lpuart \ + $(TOP)/$(SDK_DIR)/drivers/lpflexcomm \ + $(TOP)/$(SDK_DIR)/drivers/common\ + $(TOP)/$(SDK_DIR)/drivers/gpio\ + $(TOP)/$(SDK_DIR)/drivers/port\ + $(TOP)/hw/bsp/mcx/drivers/spc + + + SRC_S += $(SDK_DIR)/devices/$(MCU_VARIANT)/gcc/startup_$(MCU_CORE).S diff --git a/hw/bsp/mm32/boards/mm32f327x_mb39/board.h b/hw/bsp/mm32/boards/mm32f327x_mb39/board.h index 3ac048cf1..ee0800030 100644 --- a/hw/bsp/mm32/boards/mm32f327x_mb39/board.h +++ b/hw/bsp/mm32/boards/mm32f327x_mb39/board.h @@ -1,3 +1,8 @@ +/* metadata: + name: MM32F3273G9P MB-039 + url: https://www.mindmotion.com.cn/support/development_tools/evaluation_boards/evboard/mm32f3273g9p/ +*/ + #ifndef BOARD_H #define BOARD_H diff --git a/hw/bsp/mm32/boards/mm32f327x_pitaya_lite/board.h b/hw/bsp/mm32/boards/mm32f327x_pitaya_lite/board.h index 2b3f54a60..522d494a8 100644 --- a/hw/bsp/mm32/boards/mm32f327x_pitaya_lite/board.h +++ b/hw/bsp/mm32/boards/mm32f327x_pitaya_lite/board.h @@ -1,3 +1,8 @@ +/* metadata: + name: DshanMCU Pitaya Lite with MM32F3273G8P + url: https://gitee.com/weidongshan/DshanMCU-Pitaya-c +*/ + #ifndef BOARD_H #define BOARD_H diff --git a/hw/bsp/mm32/family.c b/hw/bsp/mm32/family.c index f0fd6d334..979efb6ca 100644 --- a/hw/bsp/mm32/family.c +++ b/hw/bsp/mm32/family.c @@ -24,6 +24,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: MindMotion +*/ + #include "hal_conf.h" #include "mm32_device.h" diff --git a/hw/bsp/mm32/family.cmake b/hw/bsp/mm32/family.cmake index bf315acaa..0561a63a0 100644 --- a/hw/bsp/mm32/family.cmake +++ b/hw/bsp/mm32/family.cmake @@ -7,7 +7,7 @@ set(SDK_DIR ${TOP}/hw/mcu/mindmotion/mm32sdk/${MCU_VARIANT_UPPER}) set(CMSIS_5 ${TOP}/lib/CMSIS_5) # toolchain set up -set(CMAKE_SYSTEM_PROCESSOR cortex-m3 CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU cortex-m3 CACHE INTERNAL "System Processor") set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) set(FAMILY_MCUS MM32F327X CACHE INTERNAL "") @@ -87,15 +87,15 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_MM32F327X ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC + family_add_tinyusb(${TARGET} OPT_MCU_MM32F327X) + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/mindmotion/mm32/dcd_mm32f327x_otg.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) # Flashing + family_add_bin_hex(${TARGET}) family_flash_jlink(${TARGET}) endfunction() diff --git a/hw/bsp/msp430/boards/msp_exp430f5529lp/board.h b/hw/bsp/msp430/boards/msp_exp430f5529lp/board.h index ccfe321c2..8fbe5cc49 100644 --- a/hw/bsp/msp430/boards/msp_exp430f5529lp/board.h +++ b/hw/bsp/msp430/boards/msp_exp430f5529lp/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: MSP430F5529 LaunchPad + url: https://www.ti.com/tool/MSP-EXP430F5529LP +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/msp430/family.c b/hw/bsp/msp430/family.c index 5bb3d3866..a45bd5f93 100644 --- a/hw/bsp/msp430/family.c +++ b/hw/bsp/msp430/family.c @@ -24,6 +24,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: Texas Instruments +*/ + #include "bsp/board_api.h" #include "board.h" #include "msp430.h" diff --git a/hw/bsp/msp430/family.cmake b/hw/bsp/msp430/family.cmake index e0b4ed28a..d9b4bf770 100644 --- a/hw/bsp/msp430/family.cmake +++ b/hw/bsp/msp430/family.cmake @@ -6,41 +6,42 @@ set(SDK_DIR ${TOP}/hw/mcu/ti/msp430/msp430-gcc-support-files/include) include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) # toolchain set up -set(CMAKE_SYSTEM_PROCESSOR msp430 CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU msp430 CACHE INTERNAL "System Processor") set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/msp430_${TOOLCHAIN}.cmake) set(FAMILY_MCUS MSP430x5xx CACHE INTERNAL "") - #------------------------------------ # BOARD_TARGET #------------------------------------ # only need to be built ONCE for all examples function(add_board_target BOARD_TARGET) - if (NOT TARGET ${BOARD_TARGET}) - add_library(${BOARD_TARGET} INTERFACE) - target_compile_definitions(${BOARD_TARGET} INTERFACE - CFG_TUD_ENDPOINT0_SIZE=8 - CFG_EXAMPLE_VIDEO_READONLY - CFG_EXAMPLE_MSC_READONLY - ) - target_include_directories(${BOARD_TARGET} INTERFACE - ${CMAKE_CURRENT_FUNCTION_LIST_DIR} - ${SDK_DIR} - ) + if (TARGET ${BOARD_TARGET}) + return() + endif () - update_board(${BOARD_TARGET}) + add_library(${BOARD_TARGET} INTERFACE) + target_compile_definitions(${BOARD_TARGET} INTERFACE + CFG_TUD_ENDPOINT0_SIZE=8 + CFG_EXAMPLE_VIDEO_READONLY + CFG_EXAMPLE_MSC_READONLY + ) + target_include_directories(${BOARD_TARGET} INTERFACE + ${CMAKE_CURRENT_FUNCTION_LIST_DIR} + ${SDK_DIR} + ) - if (CMAKE_C_COMPILER_ID STREQUAL "GNU") - target_link_options(${BOARD_TARGET} INTERFACE - "LINKER:--script=${LD_FILE_GNU}" - -L${SDK_DIR} - ) - elseif (CMAKE_C_COMPILER_ID STREQUAL "IAR") - target_link_options(${BOARD_TARGET} INTERFACE - "LINKER:--config=${LD_FILE_IAR}" - ) - endif () + update_board(${BOARD_TARGET}) + + if (CMAKE_C_COMPILER_ID STREQUAL "GNU") + target_link_options(${BOARD_TARGET} INTERFACE + "LINKER:--script=${LD_FILE_GNU}" + -L${SDK_DIR} + ) + elseif (CMAKE_C_COMPILER_ID STREQUAL "IAR") + target_link_options(${BOARD_TARGET} INTERFACE + "LINKER:--config=${LD_FILE_IAR}" + ) endif () endfunction() @@ -69,14 +70,11 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_MSP430x5xx ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC + family_add_tinyusb(${TARGET} OPT_MCU_MSP430x5xx) + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/ti/msp430x5xx/dcd_msp430x5xx.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) - - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) # Flashing family_add_bin_hex(${TARGET}) diff --git a/hw/bsp/msp430/family.mk b/hw/bsp/msp430/family.mk index 06508ab2c..c973d9dcd 100644 --- a/hw/bsp/msp430/family.mk +++ b/hw/bsp/msp430/family.mk @@ -1,5 +1,4 @@ CROSS_COMPILE = msp430-elf- -DEPS_SUBMODULES += hw/mcu/ti SKIP_NANOLIB = 1 SDK_DIR = hw/mcu/ti/msp430/msp430-gcc-support-files/include diff --git a/hw/bsp/msp432e4/boards/msp_exp432e401y/board.h b/hw/bsp/msp432e4/boards/msp_exp432e401y/board.h index 3130d663b..6206bb247 100644 --- a/hw/bsp/msp432e4/boards/msp_exp432e401y/board.h +++ b/hw/bsp/msp432e4/boards/msp_exp432e401y/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: MSP432E401Y LaunchPad + url: https://www.ti.com/tool/MSP-EXP432E401Y +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/msp432e4/family.c b/hw/bsp/msp432e4/family.c index d5ef7f930..9a3b48b66 100644 --- a/hw/bsp/msp432e4/family.c +++ b/hw/bsp/msp432e4/family.c @@ -24,6 +24,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: Texas Instruments +*/ + #include "bsp/board_api.h" #include "board.h" #include "msp.h" diff --git a/hw/bsp/msp432e4/family.cmake b/hw/bsp/msp432e4/family.cmake index f06e0d4c9..f6939ecfe 100644 --- a/hw/bsp/msp432e4/family.cmake +++ b/hw/bsp/msp432e4/family.cmake @@ -7,7 +7,7 @@ set(CMSIS_DIR ${TOP}/lib/CMSIS_5) include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) # toolchain set up -set(CMAKE_SYSTEM_PROCESSOR cortex-m4 CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU cortex-m4 CACHE INTERNAL "System Processor") set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) set(FAMILY_MCUS MSP432E4 CACHE INTERNAL "") @@ -85,15 +85,14 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_MSP432E4 ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC + family_add_tinyusb(${TARGET} OPT_MCU_MSP432E4) + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/mentor/musb/dcd_musb.c ${TOP}/src/portable/mentor/musb/hcd_musb.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) # Flashing family_add_bin_hex(${TARGET}) diff --git a/hw/bsp/nrf/boards/adafruit_clue/board.h b/hw/bsp/nrf/boards/adafruit_clue/board.h index 8d6df786e..a5d90f608 100644 --- a/hw/bsp/nrf/boards/adafruit_clue/board.h +++ b/hw/bsp/nrf/boards/adafruit_clue/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Adafruit CLUE + url: https://www.adafruit.com/product/4500 +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/nrf/boards/arduino_nano33_ble/board.h b/hw/bsp/nrf/boards/arduino_nano33_ble/board.h index 00fa8d8ea..6e6a079ab 100644 --- a/hw/bsp/nrf/boards/arduino_nano33_ble/board.h +++ b/hw/bsp/nrf/boards/arduino_nano33_ble/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Arduino Nano 33 BLE + url: https://store.arduino.cc/arduino-nano-33-ble +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/nrf/boards/circuitplayground_bluefruit/board.h b/hw/bsp/nrf/boards/circuitplayground_bluefruit/board.h index 3dd354efa..4cdac5f9f 100644 --- a/hw/bsp/nrf/boards/circuitplayground_bluefruit/board.h +++ b/hw/bsp/nrf/boards/circuitplayground_bluefruit/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Adafruit Circuit Playground Bluefruit + url: https://www.adafruit.com/product/4333 +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/nrf/boards/feather_nrf52840_express/board.h b/hw/bsp/nrf/boards/feather_nrf52840_express/board.h index 3d59516d8..bfbb98677 100644 --- a/hw/bsp/nrf/boards/feather_nrf52840_express/board.h +++ b/hw/bsp/nrf/boards/feather_nrf52840_express/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Adafruit Feather nRF52840 Express + url: https://www.adafruit.com/product/4062 +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/nrf/boards/feather_nrf52840_sense/board.h b/hw/bsp/nrf/boards/feather_nrf52840_sense/board.h index 605deea24..288a1b52e 100644 --- a/hw/bsp/nrf/boards/feather_nrf52840_sense/board.h +++ b/hw/bsp/nrf/boards/feather_nrf52840_sense/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Adafruit Feather nRF52840 Sense + url: https://www.adafruit.com/product/4516 +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/nrf/boards/itsybitsy_nrf52840/board.h b/hw/bsp/nrf/boards/itsybitsy_nrf52840/board.h index 33c370f53..5f065eec0 100644 --- a/hw/bsp/nrf/boards/itsybitsy_nrf52840/board.h +++ b/hw/bsp/nrf/boards/itsybitsy_nrf52840/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Adafruit ItsyBitsy nRF52840 Express + url: https://www.adafruit.com/product/4481 +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/nrf/boards/pca10056/board.cmake b/hw/bsp/nrf/boards/pca10056/board.cmake index cc370aac8..85314f3bc 100644 --- a/hw/bsp/nrf/boards/pca10056/board.cmake +++ b/hw/bsp/nrf/boards/pca10056/board.cmake @@ -2,3 +2,9 @@ set(MCU_VARIANT nrf52840) function(update_board TARGET) endfunction() + +#board_runner_args(jlink "--device=nRF52840_xxAA" "--speed=4000") +#include(${ZEPHYR_BASE}/boards/common/nrfjprog.board.cmake) +#include(${ZEPHYR_BASE}/boards/common/nrfutil.board.cmake) +#include(${ZEPHYR_BASE}/boards/common/jlink.board.cmake) +#include(${ZEPHYR_BASE}/boards/common/openocd-nrf5.board.cmake) diff --git a/hw/bsp/nrf/boards/pca10056/board.h b/hw/bsp/nrf/boards/pca10056/board.h index 24d3faa65..ec632e769 100644 --- a/hw/bsp/nrf/boards/pca10056/board.h +++ b/hw/bsp/nrf/boards/pca10056/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Nordic nRF52840DK + url: https://www.nordicsemi.com/Software-and-Tools/Development-Kits/nRF52840-DK +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/nrf/boards/pca10059/board.h b/hw/bsp/nrf/boards/pca10059/board.h index ea3f4030d..3b95481ad 100644 --- a/hw/bsp/nrf/boards/pca10059/board.h +++ b/hw/bsp/nrf/boards/pca10059/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Nordic nRF52840 Dongle + url: https://www.nordicsemi.com/Software-and-Tools/Development-Kits/nRF52840-Dongle +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/nrf/boards/pca10095/board.cmake b/hw/bsp/nrf/boards/pca10095/board.cmake index 95dd30969..6d183dde6 100644 --- a/hw/bsp/nrf/boards/pca10095/board.cmake +++ b/hw/bsp/nrf/boards/pca10095/board.cmake @@ -2,6 +2,6 @@ set(MCU_VARIANT nrf5340_application) function(update_board TARGET) target_sources(${TARGET} PRIVATE - ${NRFX_DIR}/drivers/src/nrfx_usbreg.c + ${NRFX_PATH}/drivers/src/nrfx_usbreg.c ) endfunction() diff --git a/hw/bsp/nrf/boards/pca10095/board.h b/hw/bsp/nrf/boards/pca10095/board.h index 846c2ee5b..1c7981049 100644 --- a/hw/bsp/nrf/boards/pca10095/board.h +++ b/hw/bsp/nrf/boards/pca10095/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Nordic nRF5340 DK + url: https://www.nordicsemi.com/Software-and-Tools/Development-Kits/nRF5340-DK +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/nrf/boards/pca10100/board.h b/hw/bsp/nrf/boards/pca10100/board.h index 2b2579732..8aca6dce9 100644 --- a/hw/bsp/nrf/boards/pca10100/board.h +++ b/hw/bsp/nrf/boards/pca10100/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Nordic nRF52833 DK + url: https://www.nordicsemi.com/Software-and-Tools/Development-Kits/nRF52833-DK +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/nrf/family.c b/hw/bsp/nrf/family.c index 885910f9a..298ca2302 100644 --- a/hw/bsp/nrf/family.c +++ b/hw/bsp/nrf/family.c @@ -24,6 +24,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: Nordic Semiconductor +*/ + #include "bsp/board_api.h" #include "board.h" @@ -40,10 +44,10 @@ #include "nrfx.h" #include "hal/nrf_gpio.h" -#include "drivers/include/nrfx_gpiote.h" -#include "drivers/include/nrfx_power.h" -#include "drivers/include/nrfx_uarte.h" -#include "drivers/include/nrfx_spim.h" +#include "nrfx_gpiote.h" +#include "nrfx_power.h" +#include "nrfx_uarte.h" +#include "nrfx_spim.h" #ifdef SOFTDEVICE_PRESENT #include "nrf_sdm.h" @@ -133,8 +137,20 @@ void board_init(void) { // Button nrf_gpio_cfg_input(BUTTON_PIN, NRF_GPIO_PIN_PULLUP); +#if CFG_TUSB_OS == OPT_OS_NONE // 1ms tick timer SysTick_Config(SystemCoreClock / 1000); +#elif CFG_TUSB_OS == OPT_OS_ZEPHYR + #ifdef CONFIG_HAS_HW_NRF_USBREG + // IRQ_CONNECT(USBREGULATOR_IRQn, DT_IRQ(DT_INST(0, nordic_nrf_clock), priority), nrfx_isr, nrfx_usbreg_irq_handler, 0); + // irq_enable(USBREGULATOR_IRQn); + #endif + + /* USB device controller access from devicetree */ + #define DT_DRV_COMPAT nordic_nrf_usbd + IRQ_CONNECT(DT_INST_IRQN(0), DT_INST_IRQ(0, priority), nrfx_isr, USBD_IRQHandler, 0); + irq_enable(DT_INST_IRQN(0)); +#endif // UART #if NRFX_VER <= 2 @@ -167,7 +183,7 @@ void board_init(void) { }; #endif - nrfx_uarte_init(&_uart_id, &uart_cfg, NULL); //uart_handler); + nrfx_uarte_init(&_uart_id, &uart_cfg, NULL); //------------- USB -------------// #if CFG_TUD_ENABLED @@ -211,8 +227,12 @@ void board_init(void) { #endif } - if ( usb_reg & VBUSDETECT_Msk ) tusb_hal_nrf_power_event(USB_EVT_DETECTED); - if ( usb_reg & OUTPUTRDY_Msk ) tusb_hal_nrf_power_event(USB_EVT_READY); + if ( usb_reg & VBUSDETECT_Msk ) { + tusb_hal_nrf_power_event(USB_EVT_DETECTED); + } + if ( usb_reg & OUTPUTRDY_Msk ) { + tusb_hal_nrf_power_event(USB_EVT_READY); + } #endif #if CFG_TUH_ENABLED && defined(CFG_TUH_MAX3421) && CFG_TUH_MAX3421 @@ -224,7 +244,6 @@ void board_init(void) { //--------------------------------------------------------------------+ // Board porting API //--------------------------------------------------------------------+ - void board_led_write(bool state) { nrf_gpio_pin_write(LED_PIN, state ? LED_STATE_ON : (1 - LED_STATE_ON)); } diff --git a/hw/bsp/nrf/family.cmake b/hw/bsp/nrf/family.cmake index 9e86374dc..7d0a9f6de 100644 --- a/hw/bsp/nrf/family.cmake +++ b/hw/bsp/nrf/family.cmake @@ -1,17 +1,20 @@ include_guard() -set(NRFX_DIR ${TOP}/hw/mcu/nordic/nrfx) +set(NRFX_PATH ${TOP}/hw/mcu/nordic/nrfx) set(CMSIS_DIR ${TOP}/lib/CMSIS_5) -# include board specific -include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) +# include board specific, for zephyr BOARD_ALIAS may be used instead +include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake OPTIONAL RESULT_VARIABLE board_cmake_included) +if (NOT board_cmake_included) + include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD_ALIAS}/board.cmake) +endif () # toolchain set up if (MCU_VARIANT STREQUAL "nrf5340_application") - set(CMAKE_SYSTEM_PROCESSOR cortex-m33 CACHE INTERNAL "System Processor") + set(CMAKE_SYSTEM_CPU cortex-m33 CACHE INTERNAL "System Processor") set(JLINK_DEVICE nrf5340_xxaa_app) else () - set(CMAKE_SYSTEM_PROCESSOR cortex-m4 CACHE INTERNAL "System Processor") + set(CMAKE_SYSTEM_CPU cortex-m4 CACHE INTERNAL "System Processor") set(JLINK_DEVICE ${MCU_VARIANT}_xxaa) endif () @@ -19,7 +22,6 @@ set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOL set(FAMILY_MCUS NRF5X CACHE INTERNAL "") - #------------------------------------ # BOARD_TARGET #------------------------------------ @@ -40,18 +42,18 @@ function(add_board_target BOARD_TARGET) endif () if (NOT DEFINED STARTUP_FILE_${CMAKE_C_COMPILER_ID}) - set(STARTUP_FILE_GNU ${NRFX_DIR}/mdk/gcc_startup_${MCU_VARIANT}.S) + set(STARTUP_FILE_GNU ${NRFX_PATH}/mdk/gcc_startup_${MCU_VARIANT}.S) set(STARTUP_FILE_Clang ${STARTUP_FILE_GNU}) endif () add_library(${BOARD_TARGET} STATIC - ${NRFX_DIR}/helpers/nrfx_flag32_allocator.c - ${NRFX_DIR}/drivers/src/nrfx_gpiote.c - ${NRFX_DIR}/drivers/src/nrfx_power.c - ${NRFX_DIR}/drivers/src/nrfx_spim.c - ${NRFX_DIR}/drivers/src/nrfx_uarte.c - ${NRFX_DIR}/mdk/system_${MCU_VARIANT}.c - ${NRFX_DIR}/soc/nrfx_atomic.c + ${NRFX_PATH}/helpers/nrfx_flag32_allocator.c + ${NRFX_PATH}/drivers/src/nrfx_gpiote.c + ${NRFX_PATH}/drivers/src/nrfx_power.c + ${NRFX_PATH}/drivers/src/nrfx_spim.c + ${NRFX_PATH}/drivers/src/nrfx_uarte.c + ${NRFX_PATH}/mdk/system_${MCU_VARIANT}.c + ${NRFX_PATH}/soc/nrfx_atomic.c ${STARTUP_FILE_${CMAKE_C_COMPILER_ID}} ) string(TOUPPER "${MCU_VARIANT_XXAA}" MCU_VARIANT_XXAA_UPPER) @@ -67,12 +69,10 @@ function(add_board_target BOARD_TARGET) endif () target_include_directories(${BOARD_TARGET} PUBLIC - ${CMAKE_CURRENT_FUNCTION_LIST_DIR} - ${NRFX_DIR} - ${NRFX_DIR}/mdk - ${NRFX_DIR}/hal - ${NRFX_DIR}/drivers/include - ${NRFX_DIR}/drivers/src + ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/nrfx_config + ${NRFX_PATH} + ${NRFX_PATH}/mdk + ${NRFX_PATH}/drivers/include ${CMSIS_DIR}/CMSIS/Core/Include ) @@ -81,14 +81,14 @@ function(add_board_target BOARD_TARGET) if (CMAKE_C_COMPILER_ID STREQUAL "GNU") target_link_options(${BOARD_TARGET} PUBLIC "LINKER:--script=${LD_FILE_GNU}" - -L${NRFX_DIR}/mdk + -L${NRFX_PATH}/mdk --specs=nosys.specs --specs=nano.specs -nostartfiles ) elseif (CMAKE_C_COMPILER_ID STREQUAL "Clang") target_link_options(${BOARD_TARGET} PUBLIC "LINKER:--script=${LD_FILE_GNU}" - -L${NRFX_DIR}/mdk + -L${NRFX_PATH}/mdk ) elseif (CMAKE_C_COMPILER_ID STREQUAL "IAR") target_link_options(${BOARD_TARGET} PUBLIC @@ -111,14 +111,17 @@ endfunction() function(family_configure_example TARGET RTOS) - family_configure_common(${TARGET} ${RTOS}) - # Board target - add_board_target(board_${BOARD}) + if (NOT RTOS STREQUAL zephyr) + add_board_target(board_${BOARD}) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + endif () + + family_configure_common(${TARGET} ${RTOS}) #---------- Port Specific ---------- # These files are built for each example since it depends on example's tusb_config.h - target_sources(${TARGET} PUBLIC + target_sources(${TARGET} PRIVATE # BSP ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/family.c ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/../board.c @@ -129,18 +132,18 @@ function(family_configure_example TARGET RTOS) ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/../../ ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/boards/${BOARD} ) + if (RTOS STREQUAL zephyr AND DEFINED BOARD_ALIAS AND NOT BOARD STREQUAL BOARD_ALIAS) + target_include_directories(${TARGET} PUBLIC ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/boards/${BOARD_ALIAS}) + endif () # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_NRF5X ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC + family_add_tinyusb(${TARGET} OPT_MCU_NRF5X) + target_sources(${TARGET} PRIVATE ${TOP}/src/portable/nordic/nrf5x/dcd_nrf5x.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) - - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) # Flashing +# family_add_bin_hex(${TARGET}) family_flash_jlink(${TARGET}) # family_flash_adafruit_nrfutil(${TARGET}) endfunction() diff --git a/hw/bsp/nrf/family.mk b/hw/bsp/nrf/family.mk index b3c05e6db..a8acb1624 100644 --- a/hw/bsp/nrf/family.mk +++ b/hw/bsp/nrf/family.mk @@ -1,6 +1,6 @@ UF2_FAMILY_ID = 0xADA52840 -NRFX_DIR = hw/mcu/nordic/nrfx +NRFX_PATH = hw/mcu/nordic/nrfx include $(TOP)/$(BOARD_PATH)/board.mk @@ -28,31 +28,32 @@ CFLAGS_GCC += \ LDFLAGS_GCC += \ -nostartfiles \ --specs=nosys.specs --specs=nano.specs \ - -L$(TOP)/${NRFX_DIR}/mdk + -L$(TOP)/${NRFX_PATH}/mdk LDFLAGS_CLANG += \ - -L$(TOP)/${NRFX_DIR}/mdk \ + -L$(TOP)/${NRFX_PATH}/mdk \ SRC_C += \ src/portable/nordic/nrf5x/dcd_nrf5x.c \ - ${NRFX_DIR}/helpers/nrfx_flag32_allocator.c \ - ${NRFX_DIR}/drivers/src/nrfx_gpiote.c \ - ${NRFX_DIR}/drivers/src/nrfx_power.c \ - ${NRFX_DIR}/drivers/src/nrfx_spim.c \ - ${NRFX_DIR}/drivers/src/nrfx_uarte.c \ - ${NRFX_DIR}/mdk/system_$(MCU_VARIANT).c \ - ${NRFX_DIR}/soc/nrfx_atomic.c + ${NRFX_PATH}/helpers/nrfx_flag32_allocator.c \ + ${NRFX_PATH}/drivers/src/nrfx_gpiote.c \ + ${NRFX_PATH}/drivers/src/nrfx_power.c \ + ${NRFX_PATH}/drivers/src/nrfx_spim.c \ + ${NRFX_PATH}/drivers/src/nrfx_uarte.c \ + ${NRFX_PATH}/mdk/system_$(MCU_VARIANT).c \ + ${NRFX_PATH}/soc/nrfx_atomic.c INC += \ $(TOP)/$(BOARD_PATH) \ + $(TOP)/$(FAMILY_PATH)/nrfx_config \ $(TOP)/lib/CMSIS_5/CMSIS/Core/Include \ - $(TOP)/${NRFX_DIR} \ - $(TOP)/${NRFX_DIR}/mdk \ - $(TOP)/${NRFX_DIR}/hal \ - $(TOP)/${NRFX_DIR}/drivers/include \ - $(TOP)/${NRFX_DIR}/drivers/src \ + $(TOP)/${NRFX_PATH} \ + $(TOP)/${NRFX_PATH}/mdk \ + $(TOP)/${NRFX_PATH}/hal \ + $(TOP)/${NRFX_PATH}/drivers/include \ + $(TOP)/${NRFX_PATH}/drivers/src \ -SRC_S += ${NRFX_DIR}/mdk/gcc_startup_$(MCU_VARIANT).S +SRC_S += ${NRFX_PATH}/mdk/gcc_startup_$(MCU_VARIANT).S ASFLAGS += -D__HEAP_SIZE=0 diff --git a/hw/bsp/nrf/nrfx_config.h b/hw/bsp/nrf/nrfx_config/nrfx_config.h similarity index 100% rename from hw/bsp/nrf/nrfx_config.h rename to hw/bsp/nrf/nrfx_config/nrfx_config.h diff --git a/hw/bsp/nrf/nrfx_glue.h b/hw/bsp/nrf/nrfx_config/nrfx_glue.h similarity index 95% rename from hw/bsp/nrf/nrfx_glue.h rename to hw/bsp/nrf/nrfx_config/nrfx_glue.h index ef756c670..bc3b3689b 100644 --- a/hw/bsp/nrf/nrfx_glue.h +++ b/hw/bsp/nrf/nrfx_config/nrfx_glue.h @@ -1,7 +1,9 @@ /* - * Copyright (c) 2017 - 2018, Nordic Semiconductor ASA + * Copyright (c) 2017 - 2024, Nordic Semiconductor ASA * All rights reserved. * + * SPDX-License-Identifier: BSD-3-Clause + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * @@ -60,14 +62,14 @@ extern "C" { /** * @brief Macro for placing a runtime assertion. * - * @param expression Expression to evaluate. + * @param expression Expression to be evaluated. */ #define NRFX_ASSERT(expression) /** * @brief Macro for placing a compile time assertion. * - * @param expression Expression to evaluate. + * @param expression Expression to be evaluated. */ #define NRFX_STATIC_ASSERT(expression) @@ -76,8 +78,8 @@ extern "C" { /** * @brief Macro for setting the priority of a specific IRQ. * - * @param irq_number IRQ number. - * @param priority Priority to set. + * @param irq_number IRQ number. + * @param priority Priority to be set. */ #define NRFX_IRQ_PRIORITY_SET(irq_number, priority) _NRFX_IRQ_PRIORITY_SET(irq_number, priority) static inline void _NRFX_IRQ_PRIORITY_SET(IRQn_Type irq_number, @@ -158,14 +160,10 @@ static inline bool _NRFX_IRQ_IS_PENDING(IRQn_Type irq_number) return (NVIC_GetPendingIRQ(irq_number) == 1); } -/** - * @brief Macro for entering into a critical section. - */ +/** @brief Macro for entering into a critical section. */ #define NRFX_CRITICAL_SECTION_ENTER() -/** - * @brief Macro for exiting from a critical section. - */ +/** @brief Macro for exiting from a critical section. */ #define NRFX_CRITICAL_SECTION_EXIT() //------------------------------------------------------------------------------ diff --git a/hw/bsp/nrf/nrfx_log.h b/hw/bsp/nrf/nrfx_config/nrfx_log.h similarity index 100% rename from hw/bsp/nrf/nrfx_log.h rename to hw/bsp/nrf/nrfx_config/nrfx_log.h diff --git a/hw/bsp/nutiny_nuc121s/board.mk b/hw/bsp/nutiny_nuc121s/board.mk index 161ff9041..06c47d544 100644 --- a/hw/bsp/nutiny_nuc121s/board.mk +++ b/hw/bsp/nutiny_nuc121s/board.mk @@ -1,5 +1,3 @@ -DEPS_SUBMODULES += hw/mcu/nuvoton - CFLAGS += \ -flto \ -mthumb \ diff --git a/hw/bsp/nutiny_nuc125s/board.mk b/hw/bsp/nutiny_nuc125s/board.mk index 081764fd3..50b9d866a 100644 --- a/hw/bsp/nutiny_nuc125s/board.mk +++ b/hw/bsp/nutiny_nuc125s/board.mk @@ -1,5 +1,3 @@ -DEPS_SUBMODULES += hw/mcu/nuvoton - CFLAGS += \ -flto \ -mthumb \ diff --git a/hw/bsp/nutiny_nuc126v/board.mk b/hw/bsp/nutiny_nuc126v/board.mk index 2466b3a31..e87d1aad0 100644 --- a/hw/bsp/nutiny_nuc126v/board.mk +++ b/hw/bsp/nutiny_nuc126v/board.mk @@ -1,5 +1,3 @@ -DEPS_SUBMODULES += hw/mcu/nuvoton - CFLAGS += \ -flto \ -mthumb \ diff --git a/hw/bsp/nutiny_sdk_nuc120/board.mk b/hw/bsp/nutiny_sdk_nuc120/board.mk index b54895b58..d982bdc06 100644 --- a/hw/bsp/nutiny_sdk_nuc120/board.mk +++ b/hw/bsp/nutiny_sdk_nuc120/board.mk @@ -1,5 +1,3 @@ -DEPS_SUBMODULES += hw/mcu/nuvoton - CFLAGS += \ -flto \ -mthumb \ diff --git a/hw/bsp/nutiny_sdk_nuc505/board.mk b/hw/bsp/nutiny_sdk_nuc505/board.mk index f3b389354..1dc8b244e 100644 --- a/hw/bsp/nutiny_sdk_nuc505/board.mk +++ b/hw/bsp/nutiny_sdk_nuc505/board.mk @@ -1,5 +1,3 @@ -DEPS_SUBMODULES += hw/mcu/nuvoton - CFLAGS += \ -flto \ -mthumb \ diff --git a/hw/bsp/pic32mz/boards/olimex_emz64/board.h b/hw/bsp/pic32mz/boards/olimex_emz64/board.h new file mode 100644 index 000000000..7f42e024f --- /dev/null +++ b/hw/bsp/pic32mz/boards/olimex_emz64/board.h @@ -0,0 +1,43 @@ +/* +* The MIT License (MIT) + * + * Copyright (c) 2020, Ha Thach (tinyusb.org) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * This file is part of the TinyUSB stack. + */ + +/* metadata: + name: Olimex PIC32-EMZ64 + url: https://www.olimex.com/Products/PIC/Development/PIC32-EMZ64/open-source-hardware +*/ + +#ifndef BOARD_H_ +#define BOARD_H_ + +#ifdef __cplusplus + extern "C" { +#endif + +#ifdef __cplusplus + } +#endif + +#endif /* BOARD_H_ */ diff --git a/hw/bsp/pic32mz/boards/olimex_hmz144/board.h b/hw/bsp/pic32mz/boards/olimex_hmz144/board.h new file mode 100644 index 000000000..c9c07bf77 --- /dev/null +++ b/hw/bsp/pic32mz/boards/olimex_hmz144/board.h @@ -0,0 +1,43 @@ +/* +* The MIT License (MIT) + * + * Copyright (c) 2020, Ha Thach (tinyusb.org) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * This file is part of the TinyUSB stack. + */ + +/* metadata: + name: Olimex PIC32-HMZ144 + url: https://www.olimex.com/Products/PIC/Development/PIC32-HMZ144/open-source-hardware +*/ + +#ifndef BOARD_H_ +#define BOARD_H_ + +#ifdef __cplusplus + extern "C" { +#endif + +#ifdef __cplusplus + } +#endif + +#endif /* BOARD_H_ */ diff --git a/hw/bsp/pic32mz/family.c b/hw/bsp/pic32mz/family.c index 895e23899..da97f67a9 100644 --- a/hw/bsp/pic32mz/family.c +++ b/hw/bsp/pic32mz/family.c @@ -24,6 +24,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: Microchip +*/ + #include #include #include diff --git a/hw/bsp/ra/board_cfg.h b/hw/bsp/ra/board_cfg.h index baed46b5f..825f8cd32 100644 --- a/hw/bsp/ra/board_cfg.h +++ b/hw/bsp/ra/board_cfg.h @@ -1,45 +1,13 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2023 Ha Thach (tinyusb.org) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -#ifndef _BOARD_CFG_H -#define _BOARD_CFG_H - +/* generated configuration header file - do not edit */ +#ifndef BOARD_CFG_H_ +#define BOARD_CFG_H_ #ifdef __cplusplus -extern "C" { -#endif + extern "C" { + #endif -#if defined(BSP_MCU_GROUP_RA6M5) || defined(BSP_MCU_GROUP_RA6M3) || (BSP_CFG_MCU_PART_SERIES == 8) - #define BOARD_HAS_USB_HIGHSPEED -#endif + void bsp_init(void * p_args); -// for SystemInit() -void bsp_init(void * p_args); - - -#ifdef __cplusplus -} -#endif - -#endif + #ifdef __cplusplus + } + #endif +#endif /* BOARD_CFG_H_ */ diff --git a/hw/bsp/ra/boards/portenta_c33/board.cmake b/hw/bsp/ra/boards/portenta_c33/board.cmake index 1837d8450..a1545f070 100644 --- a/hw/bsp/ra/boards/portenta_c33/board.cmake +++ b/hw/bsp/ra/boards/portenta_c33/board.cmake @@ -1,25 +1,16 @@ -set(CMAKE_SYSTEM_PROCESSOR cortex-m33 CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU cortex-m33 CACHE INTERNAL "System Processor") set(MCU_VARIANT ra6m5) set(JLINK_DEVICE R7FA6M5BH) set(DFU_UTIL_VID_PID 2341:0368) -set(LD_FILE_GNU ${CMAKE_CURRENT_LIST_DIR}/${BOARD}.ld) - -# Device port default to PORT1 Highspeed -if (NOT DEFINED PORT) -set(PORT 1) +# device default to PORT 1 High Speed +if (NOT DEFINED RHPORT_DEVICE) + set(RHPORT_DEVICE 1) +endif() +if (NOT DEFINED RHPORT_HOST) + set(RHPORT_HOST 0) endif() -# Host port will be the other port -set(HOST_PORT $) - function(update_board TARGET) - target_compile_definitions(${TARGET} PUBLIC - BOARD_TUD_RHPORT=${PORT} - BOARD_TUH_RHPORT=${HOST_PORT} - # port 0 is fullspeed, port 1 is highspeed - BOARD_TUD_MAX_SPEED=$ - BOARD_TUH_MAX_SPEED=$ - ) endfunction() diff --git a/hw/bsp/ra/boards/portenta_c33/board.h b/hw/bsp/ra/boards/portenta_c33/board.h index 7841ec8b8..7853c2dbd 100644 --- a/hw/bsp/ra/boards/portenta_c33/board.h +++ b/hw/bsp/ra/boards/portenta_c33/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Arduino Portenta C33 + url: https://www.arduino.cc/pro/hardware-product-portenta-c33/ +*/ + #ifndef _BOARD_H_ #define _BOARD_H_ @@ -31,36 +36,9 @@ extern "C" { #endif -#define LED1 BSP_IO_PORT_01_PIN_07 // Red LED #define LED_STATE_ON 1 - -#define SW1 BSP_IO_PORT_04_PIN_08 // D12 #define BUTTON_STATE_ACTIVE 0 -static const ioport_pin_cfg_t board_pin_cfg[] = { - { .pin = LED1, .pin_cfg = IOPORT_CFG_PORT_DIRECTION_OUTPUT | IOPORT_CFG_PORT_OUTPUT_LOW }, - { .pin = SW1, .pin_cfg = IOPORT_CFG_PORT_DIRECTION_INPUT }, - - // USB FS - { .pin = BSP_IO_PORT_04_PIN_07, .pin_cfg = IOPORT_CFG_PERIPHERAL_PIN | IOPORT_PERIPHERAL_USB_FS | IOPORT_CFG_DRIVE_HIGH }, - { .pin = BSP_IO_PORT_05_PIN_00, .pin_cfg = IOPORT_CFG_PERIPHERAL_PIN | IOPORT_PERIPHERAL_USB_FS | IOPORT_CFG_DRIVE_HIGH}, - { .pin = BSP_IO_PORT_05_PIN_01, .pin_cfg = IOPORT_CFG_PERIPHERAL_PIN | IOPORT_PERIPHERAL_USB_FS | IOPORT_CFG_DRIVE_HIGH}, - - // USB HS - { .pin = BSP_IO_PORT_07_PIN_07, .pin_cfg = IOPORT_CFG_PERIPHERAL_PIN | IOPORT_PERIPHERAL_USB_HS }, - { .pin = BSP_IO_PORT_11_PIN_00, .pin_cfg = IOPORT_CFG_PERIPHERAL_PIN | IOPORT_PERIPHERAL_USB_HS | IOPORT_CFG_DRIVE_HIGH}, - { .pin = BSP_IO_PORT_11_PIN_01, .pin_cfg = IOPORT_CFG_PERIPHERAL_PIN | IOPORT_PERIPHERAL_USB_HS | IOPORT_CFG_DRIVE_HIGH}, - - // ETM Trace - #ifdef TRACE_ETM - { .pin = BSP_IO_PORT_02_PIN_08, .pin_cfg = IOPORT_CFG_PERIPHERAL_PIN | IOPORT_PERIPHERAL_TRACE | IOPORT_CFG_DRIVE_HS_HIGH }, - { .pin = BSP_IO_PORT_02_PIN_09, .pin_cfg = IOPORT_CFG_PERIPHERAL_PIN | IOPORT_PERIPHERAL_TRACE | IOPORT_CFG_DRIVE_HS_HIGH }, - { .pin = BSP_IO_PORT_02_PIN_10, .pin_cfg = IOPORT_CFG_PERIPHERAL_PIN | IOPORT_PERIPHERAL_TRACE | IOPORT_CFG_DRIVE_HS_HIGH }, - { .pin = BSP_IO_PORT_02_PIN_11, .pin_cfg = IOPORT_CFG_PERIPHERAL_PIN | IOPORT_PERIPHERAL_TRACE | IOPORT_CFG_DRIVE_HS_HIGH }, - { .pin = BSP_IO_PORT_02_PIN_14, .pin_cfg = IOPORT_CFG_PERIPHERAL_PIN | IOPORT_PERIPHERAL_TRACE | IOPORT_CFG_DRIVE_HS_HIGH }, - #endif -}; - #ifdef __cplusplus } #endif diff --git a/hw/bsp/ra/boards/portenta_c33/board.mk b/hw/bsp/ra/boards/portenta_c33/board.mk index 6a5c2ffce..ab814cda6 100644 --- a/hw/bsp/ra/boards/portenta_c33/board.mk +++ b/hw/bsp/ra/boards/portenta_c33/board.mk @@ -1,10 +1,9 @@ CPU_CORE = cortex-m33 MCU_VARIANT = ra6m5 -LD_FILE = ${BOARD_PATH}/${BOARD}.ld - # Port 1 is highspeed -PORT ?= 1 +RHPORT_DEVICE ?= 1 +RHPORT_HOST ?= 0 JLINK_DEVICE = R7FA6M5BH DFU_UTIL_OPTION = -d 2341:0368 -a 0 diff --git a/hw/bsp/ra/boards/portenta_c33/fsp_cfg/bsp/bsp_cfg.h b/hw/bsp/ra/boards/portenta_c33/fsp_cfg/bsp/bsp_cfg.h deleted file mode 100644 index 33d381850..000000000 --- a/hw/bsp/ra/boards/portenta_c33/fsp_cfg/bsp/bsp_cfg.h +++ /dev/null @@ -1,63 +0,0 @@ -/* generated configuration header file - do not edit */ -#ifndef BSP_CFG_H_ -#define BSP_CFG_H_ -#ifdef __cplusplus -extern "C" { -#endif - -#include "bsp_clock_cfg.h" -#include "bsp_mcu_family_cfg.h" -#include "board_cfg.h" - -#define RA_NOT_DEFINED 0 -#ifndef BSP_CFG_RTOS -#if (RA_NOT_DEFINED) != (2) -#define BSP_CFG_RTOS (2) -#elif (RA_NOT_DEFINED) != (RA_NOT_DEFINED) - #define BSP_CFG_RTOS (1) -#else - #define BSP_CFG_RTOS (0) -#endif -#endif -#ifndef BSP_CFG_RTC_USED -#define BSP_CFG_RTC_USED (RA_NOT_DEFINED) -#endif -#undef RA_NOT_DEFINED -#if defined(_RA_BOOT_IMAGE) - #define BSP_CFG_BOOT_IMAGE (1) -#endif -#define BSP_CFG_MCU_VCC_MV (3300) -#define BSP_CFG_STACK_MAIN_BYTES (0x1000) -#define BSP_CFG_HEAP_BYTES (0x1000) -#define BSP_CFG_PARAM_CHECKING_ENABLE (1) -#define BSP_CFG_ASSERT (0) -#define BSP_CFG_ERROR_LOG (0) - -#define BSP_CFG_PFS_PROTECT ((1)) - -#define BSP_CFG_C_RUNTIME_INIT ((1)) -#define BSP_CFG_EARLY_INIT ((0)) - -#define BSP_CFG_STARTUP_CLOCK_REG_NOT_RESET ((0)) - -#ifndef BSP_CLOCK_CFG_MAIN_OSC_POPULATED -#define BSP_CLOCK_CFG_MAIN_OSC_POPULATED (1) -#endif - -#ifndef BSP_CLOCK_CFG_MAIN_OSC_CLOCK_SOURCE -#define BSP_CLOCK_CFG_MAIN_OSC_CLOCK_SOURCE (0) -#endif -#ifndef BSP_CLOCK_CFG_SUBCLOCK_DRIVE -#define BSP_CLOCK_CFG_SUBCLOCK_DRIVE (0) -#endif -#ifndef BSP_CLOCK_CFG_SUBCLOCK_POPULATED -#define BSP_CLOCK_CFG_SUBCLOCK_POPULATED (1) -#endif -#ifndef BSP_CLOCK_CFG_SUBCLOCK_STABILIZATION_MS -#define BSP_CLOCK_CFG_SUBCLOCK_STABILIZATION_MS 1000 -#endif - -#ifdef __cplusplus -} -#endif -#endif /* BSP_CFG_H_ */ diff --git a/hw/bsp/ra/boards/portenta_c33/fsp_cfg/bsp/bsp_mcu_device_pn_cfg.h b/hw/bsp/ra/boards/portenta_c33/fsp_cfg/bsp/bsp_mcu_device_pn_cfg.h deleted file mode 100644 index 6845183db..000000000 --- a/hw/bsp/ra/boards/portenta_c33/fsp_cfg/bsp/bsp_mcu_device_pn_cfg.h +++ /dev/null @@ -1,11 +0,0 @@ -/* generated configuration header file - do not edit */ -#ifndef BSP_MCU_DEVICE_PN_CFG_H_ -#define BSP_MCU_DEVICE_PN_CFG_H_ -#define BSP_MCU_R7FA6M5BH3CFC -#define BSP_MCU_FEATURE_SET ('B') -#define BSP_ROM_SIZE_BYTES (2097152) -#define BSP_RAM_SIZE_BYTES (524288) -#define BSP_DATA_FLASH_SIZE_BYTES (8192) -#define BSP_PACKAGE_LQFP -#define BSP_PACKAGE_PINS (176) -#endif /* BSP_MCU_DEVICE_PN_CFG_H_ */ diff --git a/hw/bsp/ra/boards/portenta_c33/portenta_c33.ld b/hw/bsp/ra/boards/portenta_c33/portenta_c33.ld deleted file mode 100644 index ba15588e6..000000000 --- a/hw/bsp/ra/boards/portenta_c33/portenta_c33.ld +++ /dev/null @@ -1,25 +0,0 @@ -RAM_START = 0x20000000; -RAM_LENGTH = 0x80000; -FLASH_START = 0x00000000; -FLASH_LENGTH = 0x200000; -DATA_FLASH_START = 0x08000000; -DATA_FLASH_LENGTH = 0x2000; -OPTION_SETTING_START = 0x0100A100; -OPTION_SETTING_LENGTH = 0x100; -OPTION_SETTING_S_START = 0x0100A200; -OPTION_SETTING_S_LENGTH = 0x100; -ID_CODE_START = 0x00000000; -ID_CODE_LENGTH = 0x0; -SDRAM_START = 0x80010000; -SDRAM_LENGTH = 0x0; -QSPI_FLASH_START = 0x60000000; -QSPI_FLASH_LENGTH = 0x4000000; -OSPI_DEVICE_0_START = 0x68000000; -OSPI_DEVICE_0_LENGTH = 0x8000000; -OSPI_DEVICE_1_START = 0x70000000; -OSPI_DEVICE_1_LENGTH = 0x10000000; - -/* Board has bootloader */ -FLASH_IMAGE_START = 0x10000; - -INCLUDE fsp.ld diff --git a/hw/bsp/ra/boards/portenta_c33/ra_cfg/fsp_cfg/bsp/bsp_cfg.h b/hw/bsp/ra/boards/portenta_c33/ra_cfg/fsp_cfg/bsp/bsp_cfg.h new file mode 100644 index 000000000..90afbdef3 --- /dev/null +++ b/hw/bsp/ra/boards/portenta_c33/ra_cfg/fsp_cfg/bsp/bsp_cfg.h @@ -0,0 +1,62 @@ +/* generated configuration header file - do not edit */ +#ifndef BSP_CFG_H_ +#define BSP_CFG_H_ +#ifdef __cplusplus + extern "C" { + #endif + + #include "bsp_clock_cfg.h" + #include "bsp_mcu_family_cfg.h" + #include "board_cfg.h" + #define RA_NOT_DEFINED 0 + #ifndef BSP_CFG_RTOS + #if (RA_NOT_DEFINED) != (RA_NOT_DEFINED) + #define BSP_CFG_RTOS (2) + #elif (RA_NOT_DEFINED) != (RA_NOT_DEFINED) + #define BSP_CFG_RTOS (1) + #else + #define BSP_CFG_RTOS (0) + #endif + #endif + #ifndef BSP_CFG_RTC_USED + #define BSP_CFG_RTC_USED (RA_NOT_DEFINED) + #endif + #undef RA_NOT_DEFINED + #if defined(_RA_BOOT_IMAGE) + #define BSP_CFG_BOOT_IMAGE (1) + #endif + #define BSP_CFG_MCU_VCC_MV (3300) + #define BSP_CFG_STACK_MAIN_BYTES (0x1000) + #define BSP_CFG_HEAP_BYTES (0x1000) + #define BSP_CFG_PARAM_CHECKING_ENABLE (0) + #define BSP_CFG_ASSERT (0) + #define BSP_CFG_ERROR_LOG (0) + + #define BSP_CFG_PFS_PROTECT ((1)) + + #define BSP_CFG_C_RUNTIME_INIT ((1)) + #define BSP_CFG_EARLY_INIT ((0)) + + #define BSP_CFG_STARTUP_CLOCK_REG_NOT_RESET ((0)) + + #ifndef BSP_CLOCK_CFG_MAIN_OSC_POPULATED + #define BSP_CLOCK_CFG_MAIN_OSC_POPULATED (1) + #endif + + #ifndef BSP_CLOCK_CFG_MAIN_OSC_CLOCK_SOURCE + #define BSP_CLOCK_CFG_MAIN_OSC_CLOCK_SOURCE (0) + #endif + #ifndef BSP_CLOCK_CFG_SUBCLOCK_DRIVE + #define BSP_CLOCK_CFG_SUBCLOCK_DRIVE (0) + #endif + #ifndef BSP_CLOCK_CFG_SUBCLOCK_POPULATED + #define BSP_CLOCK_CFG_SUBCLOCK_POPULATED (1) + #endif + #ifndef BSP_CLOCK_CFG_SUBCLOCK_STABILIZATION_MS + #define BSP_CLOCK_CFG_SUBCLOCK_STABILIZATION_MS 1000 + #endif + + #ifdef __cplusplus + } + #endif +#endif /* BSP_CFG_H_ */ diff --git a/hw/bsp/ra/boards/portenta_c33/fsp_cfg/bsp/bsp_mcu_device_cfg.h b/hw/bsp/ra/boards/portenta_c33/ra_cfg/fsp_cfg/bsp/bsp_mcu_device_cfg.h similarity index 100% rename from hw/bsp/ra/boards/portenta_c33/fsp_cfg/bsp/bsp_mcu_device_cfg.h rename to hw/bsp/ra/boards/portenta_c33/ra_cfg/fsp_cfg/bsp/bsp_mcu_device_cfg.h diff --git a/hw/bsp/ra/boards/portenta_c33/ra_cfg/fsp_cfg/bsp/bsp_mcu_device_pn_cfg.h b/hw/bsp/ra/boards/portenta_c33/ra_cfg/fsp_cfg/bsp/bsp_mcu_device_pn_cfg.h new file mode 100644 index 000000000..e532478f8 --- /dev/null +++ b/hw/bsp/ra/boards/portenta_c33/ra_cfg/fsp_cfg/bsp/bsp_mcu_device_pn_cfg.h @@ -0,0 +1,11 @@ +/* generated configuration header file - do not edit */ +#ifndef BSP_MCU_DEVICE_PN_CFG_H_ +#define BSP_MCU_DEVICE_PN_CFG_H_ +#define BSP_MCU_R7FA6M5BH3CFC + #define BSP_MCU_FEATURE_SET ('B') + #define BSP_ROM_SIZE_BYTES (2097152) + #define BSP_RAM_SIZE_BYTES (524288) + #define BSP_DATA_FLASH_SIZE_BYTES (8192) + #define BSP_PACKAGE_LQFP + #define BSP_PACKAGE_PINS (176) +#endif /* BSP_MCU_DEVICE_PN_CFG_H_ */ diff --git a/hw/bsp/ra/boards/ra6m5_ek/fsp_cfg/bsp/bsp_mcu_family_cfg.h b/hw/bsp/ra/boards/portenta_c33/ra_cfg/fsp_cfg/bsp/bsp_mcu_family_cfg.h similarity index 56% rename from hw/bsp/ra/boards/ra6m5_ek/fsp_cfg/bsp/bsp_mcu_family_cfg.h rename to hw/bsp/ra/boards/portenta_c33/ra_cfg/fsp_cfg/bsp/bsp_mcu_family_cfg.h index d5428540f..c01219377 100644 --- a/hw/bsp/ra/boards/ra6m5_ek/fsp_cfg/bsp/bsp_mcu_family_cfg.h +++ b/hw/bsp/ra/boards/portenta_c33/ra_cfg/fsp_cfg/bsp/bsp_mcu_family_cfg.h @@ -5,80 +5,80 @@ extern "C" { #endif -#include "bsp_mcu_device_pn_cfg.h" -#include "bsp_mcu_device_cfg.h" -#include "../../../ra/fsp/src/bsp/mcu/ra6m5/bsp_mcu_info.h" -#include "bsp_clock_cfg.h" + #include "bsp_mcu_device_pn_cfg.h" + #include "bsp_mcu_device_cfg.h" + #include "../../../ra/fsp/src/bsp/mcu/ra6m5/bsp_mcu_info.h" + #include "bsp_clock_cfg.h" + #define BSP_MCU_GROUP_RA6M5 (1) + #define BSP_LOCO_HZ (32768) + #define BSP_MOCO_HZ (8000000) + #define BSP_SUB_CLOCK_HZ (32768) + #if BSP_CFG_HOCO_FREQUENCY == 0 + #define BSP_HOCO_HZ (16000000) + #elif BSP_CFG_HOCO_FREQUENCY == 1 + #define BSP_HOCO_HZ (18000000) + #elif BSP_CFG_HOCO_FREQUENCY == 2 + #define BSP_HOCO_HZ (20000000) + #else + #error "Invalid HOCO frequency chosen (BSP_CFG_HOCO_FREQUENCY) in bsp_clock_cfg.h" + #endif -#define BSP_MCU_GROUP_RA6M5 (1) -#define BSP_LOCO_HZ (32768) -#define BSP_MOCO_HZ (8000000) -#define BSP_SUB_CLOCK_HZ (32768) -#if BSP_CFG_HOCO_FREQUENCY == 0 -#define BSP_HOCO_HZ (16000000) -#elif BSP_CFG_HOCO_FREQUENCY == 1 - #define BSP_HOCO_HZ (18000000) -#elif BSP_CFG_HOCO_FREQUENCY == 2 - #define BSP_HOCO_HZ (20000000) -#else - #error "Invalid HOCO frequency chosen (BSP_CFG_HOCO_FREQUENCY) in bsp_clock_cfg.h" -#endif + #define BSP_CFG_FLL_ENABLE (0) -#define BSP_CFG_FLL_ENABLE (0) + #define BSP_CORTEX_VECTOR_TABLE_ENTRIES (16U) + #define BSP_VECTOR_TABLE_MAX_ENTRIES (112U) + #define BSP_CFG_INLINE_IRQ_FUNCTIONS (1) -#define BSP_CORTEX_VECTOR_TABLE_ENTRIES (16U) -#define BSP_VECTOR_TABLE_MAX_ENTRIES (112U) - -#if defined(_RA_TZ_SECURE) + #if defined(_RA_TZ_SECURE) #define BSP_TZ_SECURE_BUILD (1) #define BSP_TZ_NONSECURE_BUILD (0) #elif defined(_RA_TZ_NONSECURE) #define BSP_TZ_SECURE_BUILD (0) #define BSP_TZ_NONSECURE_BUILD (1) #else -#define BSP_TZ_SECURE_BUILD (0) -#define BSP_TZ_NONSECURE_BUILD (0) -#endif + #define BSP_TZ_SECURE_BUILD (0) + #define BSP_TZ_NONSECURE_BUILD (0) + #endif -/* TrustZone Settings */ -#define BSP_TZ_CFG_INIT_SECURE_ONLY (BSP_CFG_CLOCKS_SECURE || (!BSP_CFG_CLOCKS_OVERRIDE)) -#define BSP_TZ_CFG_SKIP_INIT (BSP_TZ_NONSECURE_BUILD && BSP_TZ_CFG_INIT_SECURE_ONLY) -#define BSP_TZ_CFG_EXCEPTION_RESPONSE (0) + /* TrustZone Settings */ + #define BSP_TZ_CFG_INIT_SECURE_ONLY (BSP_CFG_CLOCKS_SECURE || (!BSP_CFG_CLOCKS_OVERRIDE)) + #define BSP_TZ_CFG_SKIP_INIT (BSP_TZ_NONSECURE_BUILD && BSP_TZ_CFG_INIT_SECURE_ONLY) + #define BSP_TZ_CFG_EXCEPTION_RESPONSE (0) -/* CMSIS TrustZone Settings */ -#define SCB_CSR_AIRCR_INIT (1) -#define SCB_AIRCR_BFHFNMINS_VAL (0) -#define SCB_AIRCR_SYSRESETREQS_VAL (1) -#define SCB_AIRCR_PRIS_VAL (0) -#define TZ_FPU_NS_USAGE (1) + /* CMSIS TrustZone Settings */ + #define SCB_CSR_AIRCR_INIT (1) + #define SCB_AIRCR_BFHFNMINS_VAL (0) + #define SCB_AIRCR_SYSRESETREQS_VAL (1) + #define SCB_AIRCR_PRIS_VAL (0) + #define TZ_FPU_NS_USAGE (1) #ifndef SCB_NSACR_CP10_11_VAL -#define SCB_NSACR_CP10_11_VAL (3U) + #define SCB_NSACR_CP10_11_VAL (3U) #endif #ifndef FPU_FPCCR_TS_VAL -#define FPU_FPCCR_TS_VAL (1U) + #define FPU_FPCCR_TS_VAL (1U) #endif -#define FPU_FPCCR_CLRONRETS_VAL (1) + #define FPU_FPCCR_CLRONRETS_VAL (1) #ifndef FPU_FPCCR_CLRONRET_VAL -#define FPU_FPCCR_CLRONRET_VAL (1) + #define FPU_FPCCR_CLRONRET_VAL (1) #endif -/* The C-Cache line size that is configured during startup. */ + /* The C-Cache line size that is configured during startup. */ #ifndef BSP_CFG_C_CACHE_LINE_SIZE -#define BSP_CFG_C_CACHE_LINE_SIZE (1U) + #define BSP_CFG_C_CACHE_LINE_SIZE (1U) #endif -/* Type 1 Peripheral Security Attribution */ + /* Type 1 Peripheral Security Attribution */ -/* Peripheral Security Attribution Register (PSAR) Settings */ + /* Peripheral Security Attribution Register (PSAR) Settings */ #ifndef BSP_TZ_CFG_PSARB #define BSP_TZ_CFG_PSARB (\ (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 1) /* CAN1 */ | \ (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 2) /* CAN0 */ | \ (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 8) /* IIC1 */ | \ (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 9) /* IIC0 */ | \ - (((1 > 0) ? 0U : 1U) << 11) /* USBFS */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 11) /* USBFS */ | \ (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 18) /* SPI1 */ | \ (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 19) /* SPI0 */ | \ (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 22) /* SCI9 */ | \ @@ -146,19 +146,19 @@ extern "C" { 0xfffffffc) /* Unused */ #endif -/* Type 2 Peripheral Security Attribution */ + /* Type 2 Peripheral Security Attribution */ -/* Security attribution for Cache registers. */ + /* Security attribution for Cache registers. */ #ifndef BSP_TZ_CFG_CSAR #define BSP_TZ_CFG_CSAR (0xFFFFFFFFU) #endif -/* Security attribution for RSTSRn registers. */ + /* Security attribution for RSTSRn registers. */ #ifndef BSP_TZ_CFG_RSTSAR #define BSP_TZ_CFG_RSTSAR (0xFFFFFFFFU) #endif -/* Security attribution for registers of LVD channels. */ + /* Security attribution for registers of LVD channels. */ #ifndef BSP_TZ_CFG_LVDSAR #define BSP_TZ_CFG_LVDSAR (\ (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 0) | /* LVD Channel 1 */ \ @@ -166,16 +166,16 @@ extern "C" { 0xFFFFFFFCU) #endif -/* Security attribution for LPM registers. */ + /* Security attribution for LPM registers. */ #ifndef BSP_TZ_CFG_LPMSAR #define BSP_TZ_CFG_LPMSAR ((RA_NOT_DEFINED > 0) ? 0xFFFFFCEAU : 0xFFFFFFFFU) #endif -/* Deep Standby Interrupt Factor Security Attribution Register. */ + /* Deep Standby Interrupt Factor Security Attribution Register. */ #ifndef BSP_TZ_CFG_DPFSAR #define BSP_TZ_CFG_DPFSAR ((RA_NOT_DEFINED > 0) ? 0xF2E00000U : 0xFFFFFFFFU) #endif -/* Security attribution for CGC registers. */ + /* Security attribution for CGC registers. */ #ifndef BSP_TZ_CFG_CGFSAR #if BSP_CFG_CLOCKS_SECURE /* Protect all CGC registers from Non-secure write access. */ @@ -186,12 +186,12 @@ extern "C" { #endif #endif -/* Security attribution for Battery Backup registers. */ + /* Security attribution for Battery Backup registers. */ #ifndef BSP_TZ_CFG_BBFSAR #define BSP_TZ_CFG_BBFSAR (0x00FFFFFF) #endif -/* Security attribution for registers for IRQ channels. */ + /* Security attribution for registers for IRQ channels. */ #ifndef BSP_TZ_CFG_ICUSARA #define BSP_TZ_CFG_ICUSARA (\ (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 0U) /* External IRQ0 */ | \ @@ -213,12 +213,12 @@ extern "C" { 0xFFFF0000U) #endif -/* Security attribution for NMI registers. */ + /* Security attribution for NMI registers. */ #ifndef BSP_TZ_CFG_ICUSARB #define BSP_TZ_CFG_ICUSARB (0 | 0xFFFFFFFEU) /* Should match AIRCR.BFHFNMINS. */ #endif -/* Security attribution for registers for DMAC channels */ + /* Security attribution for registers for DMAC channels */ #ifndef BSP_TZ_CFG_ICUSARC #define BSP_TZ_CFG_ICUSARC (\ (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 0U) /* DMAC Channel 0 */ | \ @@ -232,29 +232,29 @@ extern "C" { 0xFFFFFF00U) #endif -/* Security attribution registers for SELSR0. */ + /* Security attribution registers for SELSR0. */ #ifndef BSP_TZ_CFG_ICUSARD #define BSP_TZ_CFG_ICUSARD ((RA_NOT_DEFINED > 0) ? 0xFFFFFFFEU : 0xFFFFFFFFU) #endif -/* Security attribution registers for WUPEN0. */ + /* Security attribution registers for WUPEN0. */ #ifndef BSP_TZ_CFG_ICUSARE #define BSP_TZ_CFG_ICUSARE ((RA_NOT_DEFINED > 0) ? 0x04F2FFFFU : 0xFFFFFFFFU) #endif -/* Security attribution registers for WUPEN1. */ + /* Security attribution registers for WUPEN1. */ #ifndef BSP_TZ_CFG_ICUSARF #define BSP_TZ_CFG_ICUSARF ((RA_NOT_DEFINED > 0) ? 0xFFFFFFF8U : 0xFFFFFFFFU) #endif -/* Set DTCSTSAR if the Secure program uses the DTC. */ + /* Set DTCSTSAR if the Secure program uses the DTC. */ #if RA_NOT_DEFINED == RA_NOT_DEFINED -#define BSP_TZ_CFG_DTC_USED (0U) + #define BSP_TZ_CFG_DTC_USED (0U) #else #define BSP_TZ_CFG_DTC_USED (1U) #endif -/* Security attribution of FLWT and FCKMHZ registers. */ + /* Security attribution of FLWT and FCKMHZ registers. */ #ifndef BSP_TZ_CFG_FSAR /* If the CGC registers are only accessible in Secure mode, than there is no * reason for nonsecure applications to access FLWT and FCKMHZ. */ @@ -267,118 +267,123 @@ extern "C" { #endif #endif -/* Security attribution for SRAM registers. */ + /* Security attribution for SRAM registers. */ #ifndef BSP_TZ_CFG_SRAMSAR /* If the CGC registers are only accessible in Secure mode, than there is no reason for Non Secure applications to access * SRAM0WTEN and therefore there is no reason to access PRCR2. */ -#define BSP_TZ_CFG_SRAMSAR (\ + #define BSP_TZ_CFG_SRAMSAR (\ 1 | \ ((BSP_CFG_CLOCKS_SECURE == 0) ? (1U << 1U) : 0U) | \ 4 | \ 0xFFFFFFF8U) #endif -/* Security attribution for Standby RAM registers. */ + /* Security attribution for Standby RAM registers. */ #ifndef BSP_TZ_CFG_STBRAMSAR -#define BSP_TZ_CFG_STBRAMSAR (0 | 0xFFFFFFF0U) + #define BSP_TZ_CFG_STBRAMSAR (0 | 0xFFFFFFF0U) #endif -/* Security attribution for the DMAC Bus Master MPU settings. */ + /* Security attribution for the DMAC Bus Master MPU settings. */ #ifndef BSP_TZ_CFG_MMPUSARA -/* The DMAC Bus Master MPU settings should align with the DMAC channel settings. */ -#define BSP_TZ_CFG_MMPUSARA (BSP_TZ_CFG_ICUSARC) + /* The DMAC Bus Master MPU settings should align with the DMAC channel settings. */ + #define BSP_TZ_CFG_MMPUSARA (BSP_TZ_CFG_ICUSARC) #endif -/* Security Attribution Register A for BUS Control registers. */ + /* Security Attribution Register A for BUS Control registers. */ #ifndef BSP_TZ_CFG_BUSSARA -#define BSP_TZ_CFG_BUSSARA (0xFFFFFFFFU) + #define BSP_TZ_CFG_BUSSARA (0xFFFFFFFFU) #endif -/* Security Attribution Register B for BUS Control registers. */ + /* Security Attribution Register B for BUS Control registers. */ #ifndef BSP_TZ_CFG_BUSSARB -#define BSP_TZ_CFG_BUSSARB (0xFFFFFFFFU) + #define BSP_TZ_CFG_BUSSARB (0xFFFFFFFFU) #endif -/* Enable Uninitialized Non-Secure Application Fallback. */ + /* Enable Uninitialized Non-Secure Application Fallback. */ #ifndef BSP_TZ_CFG_NON_SECURE_APPLICATION_FALLBACK -#define BSP_TZ_CFG_NON_SECURE_APPLICATION_FALLBACK (1U) + #define BSP_TZ_CFG_NON_SECURE_APPLICATION_FALLBACK (1U) #endif -#define OFS_SEQ1 0xA001A001 | (1 << 1) | (3 << 2) -#define OFS_SEQ2 (15 << 4) | (3 << 8) | (3 << 10) -#define OFS_SEQ3 (1 << 12) | (1 << 14) | (1 << 17) -#define OFS_SEQ4 (3 << 18) |(15 << 20) | (3 << 24) | (3 << 26) -#define OFS_SEQ5 (1 << 28) | (1 << 30) -#define BSP_CFG_ROM_REG_OFS0 (OFS_SEQ1 | OFS_SEQ2 | OFS_SEQ3 | OFS_SEQ4 | OFS_SEQ5) -/* Option Function Select Register 1 Security Attribution */ + #define OFS_SEQ1 0xA001A001 | (1 << 1) | (3 << 2) + #define OFS_SEQ2 (15 << 4) | (3 << 8) | (3 << 10) + #define OFS_SEQ3 (1 << 12) | (1 << 14) | (1 << 17) + #define OFS_SEQ4 (3 << 18) |(15 << 20) | (3 << 24) | (3 << 26) + #define OFS_SEQ5 (1 << 28) | (1 << 30) + #define BSP_CFG_ROM_REG_OFS0 (OFS_SEQ1 | OFS_SEQ2 | OFS_SEQ3 | OFS_SEQ4 | OFS_SEQ5) + + /* Option Function Select Register 1 Security Attribution */ #ifndef BSP_CFG_ROM_REG_OFS1_SEL #if defined(_RA_TZ_SECURE) || defined(_RA_TZ_NONSECURE) - #define BSP_CFG_ROM_REG_OFS1_SEL (0xFFFFF8F8U | ((BSP_CFG_CLOCKS_SECURE == 0) ? 0x700U : 0U) | ((RA_NOT_DEFINED > 0) ? 0U : 0x7U)) + #define BSP_CFG_ROM_REG_OFS1_SEL (0xFFFFF8F8U | ((0U << 0U)) | ((0U << 2U)) | ((BSP_CFG_CLOCKS_SECURE == 0) ? 0x700U : 0U)) #else -#define BSP_CFG_ROM_REG_OFS1_SEL (0xFFFFF8F8U) + #define BSP_CFG_ROM_REG_OFS1_SEL (0xFFFFF8F8U) #endif #endif -#define BSP_CFG_ROM_REG_OFS1 (0xFFFFFEF8 | (1 << 2) | (3) | (1 << 8)) + #define BSP_CFG_ROM_REG_OFS1 (0xFFFFFEF8 | (1 << 2) | (3) | (1 << 8)) -/* Used to create IELS values for the interrupt initialization table g_interrupt_event_link_select. */ -#define BSP_PRV_IELS_ENUM(vector) (ELC_ ## vector) + /* Used to create IELS values for the interrupt initialization table g_interrupt_event_link_select. */ + #define BSP_PRV_IELS_ENUM(vector) (ELC_ ## vector) -/* Dual Mode Select Register */ + /* Dual Mode Select Register */ #ifndef BSP_CFG_ROM_REG_DUALSEL -#define BSP_CFG_ROM_REG_DUALSEL (0xFFFFFFF8U | (0x7U)) + #define BSP_CFG_ROM_REG_DUALSEL (0xFFFFFFF8U | (0x7U)) #endif -/* Block Protection Register 0 */ + /* Block Protection Register 0 */ #ifndef BSP_CFG_ROM_REG_BPS0 -#define BSP_CFG_ROM_REG_BPS0 (~( 0U)) + #define BSP_CFG_ROM_REG_BPS0 (~( 0U)) #endif -/* Block Protection Register 1 */ + /* Block Protection Register 1 */ #ifndef BSP_CFG_ROM_REG_BPS1 -#define BSP_CFG_ROM_REG_BPS1 (~( 0U)) + #define BSP_CFG_ROM_REG_BPS1 (~( 0U)) #endif -/* Block Protection Register 2 */ + /* Block Protection Register 2 */ #ifndef BSP_CFG_ROM_REG_BPS2 -#define BSP_CFG_ROM_REG_BPS2 (~( 0U)) + #define BSP_CFG_ROM_REG_BPS2 (~( 0U)) #endif -/* Block Protection Register 3 */ + /* Block Protection Register 3 */ #ifndef BSP_CFG_ROM_REG_BPS3 -#define BSP_CFG_ROM_REG_BPS3 (0xFFFFFFFFU) + #define BSP_CFG_ROM_REG_BPS3 (0xFFFFFFFFU) #endif -/* Permanent Block Protection Register 0 */ + /* Permanent Block Protection Register 0 */ #ifndef BSP_CFG_ROM_REG_PBPS0 -#define BSP_CFG_ROM_REG_PBPS0 (~( 0U)) + #define BSP_CFG_ROM_REG_PBPS0 (~( 0U)) #endif -/* Permanent Block Protection Register 1 */ + /* Permanent Block Protection Register 1 */ #ifndef BSP_CFG_ROM_REG_PBPS1 -#define BSP_CFG_ROM_REG_PBPS1 (~( 0U)) + #define BSP_CFG_ROM_REG_PBPS1 (~( 0U)) #endif -/* Permanent Block Protection Register 2 */ + /* Permanent Block Protection Register 2 */ #ifndef BSP_CFG_ROM_REG_PBPS2 -#define BSP_CFG_ROM_REG_PBPS2 (~( 0U)) + #define BSP_CFG_ROM_REG_PBPS2 (~( 0U)) #endif -/* Permanent Block Protection Register 3 */ + /* Permanent Block Protection Register 3 */ #ifndef BSP_CFG_ROM_REG_PBPS3 -#define BSP_CFG_ROM_REG_PBPS3 (0xFFFFFFFFU) + #define BSP_CFG_ROM_REG_PBPS3 (0xFFFFFFFFU) #endif -/* Security Attribution for Block Protection Register 0 (If any blocks are marked as protected in the secure application, then mark them as secure) */ + /* Security Attribution for Block Protection Register 0 (If any blocks are marked as protected in the secure application, then mark them as secure) */ #ifndef BSP_CFG_ROM_REG_BPS_SEL0 -#define BSP_CFG_ROM_REG_BPS_SEL0 (BSP_CFG_ROM_REG_BPS0 & BSP_CFG_ROM_REG_PBPS0) + #define BSP_CFG_ROM_REG_BPS_SEL0 (BSP_CFG_ROM_REG_BPS0 & BSP_CFG_ROM_REG_PBPS0) #endif -/* Security Attribution for Block Protection Register 1 (If any blocks are marked as protected in the secure application, then mark them as secure) */ + /* Security Attribution for Block Protection Register 1 (If any blocks are marked as protected in the secure application, then mark them as secure) */ #ifndef BSP_CFG_ROM_REG_BPS_SEL1 -#define BSP_CFG_ROM_REG_BPS_SEL1 (BSP_CFG_ROM_REG_BPS1 & BSP_CFG_ROM_REG_PBPS1) + #define BSP_CFG_ROM_REG_BPS_SEL1 (BSP_CFG_ROM_REG_BPS1 & BSP_CFG_ROM_REG_PBPS1) #endif -/* Security Attribution for Block Protection Register 2 (If any blocks are marked as protected in the secure application, then mark them as secure) */ + /* Security Attribution for Block Protection Register 2 (If any blocks are marked as protected in the secure application, then mark them as secure) */ #ifndef BSP_CFG_ROM_REG_BPS_SEL2 -#define BSP_CFG_ROM_REG_BPS_SEL2 (BSP_CFG_ROM_REG_BPS2 & BSP_CFG_ROM_REG_PBPS2) + #define BSP_CFG_ROM_REG_BPS_SEL2 (BSP_CFG_ROM_REG_BPS2 & BSP_CFG_ROM_REG_PBPS2) #endif -/* Security Attribution for Block Protection Register 3 (If any blocks are marked as protected in the secure application, then mark them as secure) */ + /* Security Attribution for Block Protection Register 3 (If any blocks are marked as protected in the secure application, then mark them as secure) */ #ifndef BSP_CFG_ROM_REG_BPS_SEL3 -#define BSP_CFG_ROM_REG_BPS_SEL3 (BSP_CFG_ROM_REG_BPS3 & BSP_CFG_ROM_REG_PBPS3) + #define BSP_CFG_ROM_REG_BPS_SEL3 (BSP_CFG_ROM_REG_BPS3 & BSP_CFG_ROM_REG_PBPS3) +#endif + /* Security Attribution for Bank Select Register */ +#ifndef BSP_CFG_ROM_REG_BANKSEL_SEL + #define BSP_CFG_ROM_REG_BANKSEL_SEL (0xFFFFFFFFU) #endif #ifndef BSP_CLOCK_CFG_MAIN_OSC_WAIT -#define BSP_CLOCK_CFG_MAIN_OSC_WAIT (9) + #define BSP_CLOCK_CFG_MAIN_OSC_WAIT (9) #endif #ifdef __cplusplus diff --git a/hw/bsp/ra/boards/portenta_c33/ra_cfg/fsp_cfg/bsp/bsp_pin_cfg.h b/hw/bsp/ra/boards/portenta_c33/ra_cfg/fsp_cfg/bsp/bsp_pin_cfg.h new file mode 100644 index 000000000..c411386c1 --- /dev/null +++ b/hw/bsp/ra/boards/portenta_c33/ra_cfg/fsp_cfg/bsp/bsp_pin_cfg.h @@ -0,0 +1,17 @@ +/* generated configuration header file - do not edit */ +#ifndef BSP_PIN_CFG_H_ +#define BSP_PIN_CFG_H_ +#include "r_ioport.h" + +/* Common macro for FSP header files. There is also a corresponding FSP_FOOTER macro at the end of this file. */ +FSP_HEADER + +#define LED1 (BSP_IO_PORT_01_PIN_07) +#define SW1 (BSP_IO_PORT_04_PIN_08) +extern const ioport_cfg_t g_bsp_pin_cfg; /* R7FA6M5BH3CFC.pincfg */ + +void BSP_PinConfigSecurityInit(); + +/* Common macro for FSP header files. There is also a corresponding FSP_HEADER macro at the top of this file. */ +FSP_FOOTER +#endif /* BSP_PIN_CFG_H_ */ diff --git a/hw/bsp/ra/r_ioport_cfg.h b/hw/bsp/ra/boards/portenta_c33/ra_cfg/fsp_cfg/r_ioport_cfg.h similarity index 75% rename from hw/bsp/ra/r_ioport_cfg.h rename to hw/bsp/ra/boards/portenta_c33/ra_cfg/fsp_cfg/r_ioport_cfg.h index cb7c07932..d2688bf5b 100644 --- a/hw/bsp/ra/r_ioport_cfg.h +++ b/hw/bsp/ra/boards/portenta_c33/ra_cfg/fsp_cfg/r_ioport_cfg.h @@ -1,7 +1,13 @@ /* generated configuration header file - do not edit */ #ifndef R_IOPORT_CFG_H_ #define R_IOPORT_CFG_H_ +#ifdef __cplusplus +extern "C" { +#endif #define IOPORT_CFG_PARAM_CHECKING_ENABLE (BSP_CFG_PARAM_CHECKING_ENABLE) +#ifdef __cplusplus +} +#endif #endif /* R_IOPORT_CFG_H_ */ diff --git a/hw/bsp/ra/boards/portenta_c33/ra_gen/bsp_clock_cfg.h b/hw/bsp/ra/boards/portenta_c33/ra_gen/bsp_clock_cfg.h new file mode 100644 index 000000000..91b9de11e --- /dev/null +++ b/hw/bsp/ra/boards/portenta_c33/ra_gen/bsp_clock_cfg.h @@ -0,0 +1,35 @@ +/* generated configuration header file - do not edit */ +#ifndef BSP_CLOCK_CFG_H_ +#define BSP_CLOCK_CFG_H_ +#define BSP_CFG_CLOCKS_SECURE (0) +#define BSP_CFG_CLOCKS_OVERRIDE (0) +#define BSP_CFG_XTAL_HZ (24000000) /* XTAL 24000000Hz */ +#define BSP_CFG_HOCO_FREQUENCY (2) /* HOCO 20MHz */ +#define BSP_CFG_PLL_SOURCE (BSP_CLOCKS_SOURCE_CLOCK_MAIN_OSC) /* PLL Src: XTAL */ +#define BSP_CFG_PLL_DIV (BSP_CLOCKS_PLL_DIV_3) /* PLL Div /3 */ +#define BSP_CFG_PLL_MUL BSP_CLOCKS_PLL_MUL(25U,0U) /* PLL Mul x25.0 */ +#define BSP_CFG_PLL2_SOURCE (BSP_CLOCKS_SOURCE_CLOCK_MAIN_OSC) /* PLL2 Src: XTAL */ +#define BSP_CFG_PLL2_DIV (BSP_CLOCKS_PLL_DIV_2) /* PLL2 Div /2 */ +#define BSP_CFG_PLL2_MUL BSP_CLOCKS_PLL_MUL(20U,0U) /* PLL2 Mul x20.0 */ +#define BSP_CFG_CLOCK_SOURCE (BSP_CLOCKS_SOURCE_CLOCK_PLL) /* Clock Src: PLL */ +#define BSP_CFG_CLKOUT_SOURCE (BSP_CLOCKS_CLOCK_DISABLED) /* CLKOUT Disabled */ +#define BSP_CFG_UCK_SOURCE (BSP_CLOCKS_SOURCE_CLOCK_PLL2) /* UCLK Src: PLL2 */ +#define BSP_CFG_U60CK_SOURCE (BSP_CLOCKS_SOURCE_CLOCK_PLL2) /* U60CK Src: PLL2 */ +#define BSP_CFG_OCTA_SOURCE (BSP_CLOCKS_CLOCK_DISABLED) /* OCTASPICLK Disabled */ +#define BSP_CFG_CANFDCLK_SOURCE (BSP_CLOCKS_CLOCK_DISABLED) /* CANFDCLK Disabled */ +#define BSP_CFG_CECCLK_SOURCE (BSP_CLOCKS_CLOCK_DISABLED) /* CECCLK Disabled */ +#define BSP_CFG_ICLK_DIV (BSP_CLOCKS_SYS_CLOCK_DIV_1) /* ICLK Div /1 */ +#define BSP_CFG_PCLKA_DIV (BSP_CLOCKS_SYS_CLOCK_DIV_2) /* PCLKA Div /2 */ +#define BSP_CFG_PCLKB_DIV (BSP_CLOCKS_SYS_CLOCK_DIV_4) /* PCLKB Div /4 */ +#define BSP_CFG_PCLKC_DIV (BSP_CLOCKS_SYS_CLOCK_DIV_4) /* PCLKC Div /4 */ +#define BSP_CFG_PCLKD_DIV (BSP_CLOCKS_SYS_CLOCK_DIV_2) /* PCLKD Div /2 */ +#define BSP_CFG_BCLK_DIV (BSP_CLOCKS_SYS_CLOCK_DIV_2) /* BCLK Div /2 */ +#define BSP_CFG_BCLK_OUTPUT (2) /* EBCLK Div /2 */ +#define BSP_CFG_FCLK_DIV (BSP_CLOCKS_SYS_CLOCK_DIV_4) /* FCLK Div /4 */ +#define BSP_CFG_CLKOUT_DIV (BSP_CLOCKS_SYS_CLOCK_DIV_1) /* CLKOUT Div /1 */ +#define BSP_CFG_UCK_DIV (BSP_CLOCKS_USB_CLOCK_DIV_5) /* UCLK Div /5 */ +#define BSP_CFG_U60CK_DIV (BSP_CLOCKS_USB60_CLOCK_DIV_4) /* U60CK Div /4 */ +#define BSP_CFG_OCTA_DIV (BSP_CLOCKS_OCTA_CLOCK_DIV_1) /* OCTASPICLK Div /1 */ +#define BSP_CFG_CANFDCLK_DIV (BSP_CLOCKS_CANFD_CLOCK_DIV_1) /* CANFDCLK Div /1 */ +#define BSP_CFG_CECCLK_DIV (BSP_CLOCKS_CEC_CLOCK_DIV_1) /* CECCLK Div /1 */ +#endif /* BSP_CLOCK_CFG_H_ */ diff --git a/hw/bsp/ra/boards/portenta_c33/ra_gen/common_data.c b/hw/bsp/ra/boards/portenta_c33/ra_gen/common_data.c new file mode 100644 index 000000000..50036c0ad --- /dev/null +++ b/hw/bsp/ra/boards/portenta_c33/ra_gen/common_data.c @@ -0,0 +1,11 @@ +/* generated common source file - do not edit */ +#include "common_data.h" +ioport_instance_ctrl_t g_ioport_ctrl; +const ioport_instance_t g_ioport = + { + .p_api = &g_ioport_on_ioport, + .p_ctrl = &g_ioport_ctrl, + .p_cfg = &g_bsp_pin_cfg, + }; +void g_common_init(void) { +} diff --git a/hw/bsp/ra/boards/portenta_c33/ra_gen/common_data.h b/hw/bsp/ra/boards/portenta_c33/ra_gen/common_data.h new file mode 100644 index 000000000..6a08cbee0 --- /dev/null +++ b/hw/bsp/ra/boards/portenta_c33/ra_gen/common_data.h @@ -0,0 +1,20 @@ +/* generated common header file - do not edit */ +#ifndef COMMON_DATA_H_ +#define COMMON_DATA_H_ +#include +#include "bsp_api.h" +#include "r_ioport.h" +#include "bsp_pin_cfg.h" +FSP_HEADER +#define IOPORT_CFG_NAME g_bsp_pin_cfg +#define IOPORT_CFG_OPEN R_IOPORT_Open +#define IOPORT_CFG_CTRL g_ioport_ctrl + +/* IOPORT Instance */ +extern const ioport_instance_t g_ioport; + +/* IOPORT control structure. */ +extern ioport_instance_ctrl_t g_ioport_ctrl; +void g_common_init(void); +FSP_FOOTER +#endif /* COMMON_DATA_H_ */ diff --git a/hw/bsp/ra/boards/portenta_c33/ra_gen/pin_data.c b/hw/bsp/ra/boards/portenta_c33/ra_gen/pin_data.c new file mode 100644 index 000000000..fad79741a --- /dev/null +++ b/hw/bsp/ra/boards/portenta_c33/ra_gen/pin_data.c @@ -0,0 +1,71 @@ +/* generated pin source file - do not edit */ +#include "bsp_api.h" +#include "r_ioport.h" + + +const ioport_pin_cfg_t g_bsp_pin_cfg_data[] = { + { + .pin = BSP_IO_PORT_01_PIN_07, + .pin_cfg = ((uint32_t) IOPORT_CFG_PORT_DIRECTION_OUTPUT | (uint32_t) IOPORT_CFG_PORT_OUTPUT_LOW) + }, + { + .pin = BSP_IO_PORT_01_PIN_08, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_DEBUG) + }, + { + .pin = BSP_IO_PORT_03_PIN_00, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_DEBUG) + }, + { + .pin = BSP_IO_PORT_04_PIN_07, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_USB_FS) + }, + { + .pin = BSP_IO_PORT_04_PIN_08, + .pin_cfg = ((uint32_t) IOPORT_CFG_PORT_DIRECTION_INPUT | (uint32_t) IOPORT_CFG_PULLUP_ENABLE) + }, + { + .pin = BSP_IO_PORT_11_PIN_01, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_USB_HS) + }, +}; + +const ioport_cfg_t g_bsp_pin_cfg = { + .number_of_pins = sizeof(g_bsp_pin_cfg_data)/sizeof(ioport_pin_cfg_t), + .p_pin_cfg_data = &g_bsp_pin_cfg_data[0], +}; + +#if BSP_TZ_SECURE_BUILD + +void R_BSP_PinCfgSecurityInit(void); + +/* Initialize SAR registers for secure pins. */ +void R_BSP_PinCfgSecurityInit(void) +{ + #if (2U == BSP_FEATURE_IOPORT_VERSION) + uint32_t pmsar[BSP_FEATURE_BSP_NUM_PMSAR]; + #else + uint16_t pmsar[BSP_FEATURE_BSP_NUM_PMSAR]; + #endif + memset(pmsar, 0xFF, BSP_FEATURE_BSP_NUM_PMSAR * sizeof(R_PMISC->PMSAR[0])); + + + for(uint32_t i = 0; i < g_bsp_pin_cfg.number_of_pins; i++) + { + uint32_t port_pin = g_bsp_pin_cfg.p_pin_cfg_data[i].pin; + uint32_t port = port_pin >> 8U; + uint32_t pin = port_pin & 0xFFU; + pmsar[port] &= (uint16_t) ~(1U << pin); + } + + for(uint32_t i = 0; i < BSP_FEATURE_BSP_NUM_PMSAR; i++) + { + #if (2U == BSP_FEATURE_IOPORT_VERSION) + R_PMISC->PMSAR[i].PMSAR = (uint16_t) pmsar[i]; + #else + R_PMISC->PMSAR[i].PMSAR = pmsar[i]; + #endif + } + +} +#endif diff --git a/hw/bsp/ra/linker/gcc/fsp.ld b/hw/bsp/ra/boards/portenta_c33/script/fsp.ld similarity index 78% rename from hw/bsp/ra/linker/gcc/fsp.ld rename to hw/bsp/ra/boards/portenta_c33/script/fsp.ld index 453d46f24..605eef7d2 100644 --- a/hw/bsp/ra/linker/gcc/fsp.ld +++ b/hw/bsp/ra/boards/portenta_c33/script/fsp.ld @@ -1,3 +1,9 @@ +/* + Linker File for Renesas FSP +*/ + +INCLUDE memory_regions.ld + /* Uncomment and set XIP_SECONDARY_SLOT_IMAGE to 1 below for the secondary XIP application image.*/ /* XIP_SECONDARY_SLOT_IMAGE = 1; @@ -14,8 +20,6 @@ ITCM_START = DEFINED(ITCM_START)? ITCM_START : 0; ITCM_LENGTH = DEFINED(ITCM_LENGTH)? ITCM_LENGTH : 0; DTCM_START = DEFINED(DTCM_START)? DTCM_START : 0; DTCM_LENGTH = DEFINED(DTCM_LENGTH)? DTCM_LENGTH : 0; -NS_OFFSET_START = DEFINED(NS_OFFSET_START) ? NS_OFFSET_START : 0; -NS_IMAGE_OFFSET = DEFINED(PROJECT_NONSECURE) ? NS_OFFSET_START : 0; RAM_NS_BUFFER_BLOCK_LENGTH = DEFINED(RAM_NS_BUFFER_LENGTH) ? ALIGN(RAM_NS_BUFFER_LENGTH, 8192) : 0; RAM_NS_BUFFER_LENGTH = DEFINED(RAM_NS_BUFFER_LENGTH) ? RAM_NS_BUFFER_LENGTH : 0; RAM_NS_BUFFER_START = RAM_START + RAM_LENGTH - RAM_NS_BUFFER_LENGTH; @@ -32,20 +36,21 @@ PROJECT_SECURE_OR_FLAT = (!DEFINED(PROJECT_NONSECURE) || DEFINED(PROJECT_SECURE) USE_OPTION_SETTING_NS = DEFINED(PROJECT_NONSECURE) && !DEFINED(FSP_BOOTABLE_IMAGE); __bl_FLASH_IMAGE_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : - FLASH_APPLICATION_IMAGE_NUMBER == 1 ? FLASH_BOOTLOADER_LENGTH + FLASH_BOOTLOADER_HEADER_LENGTH : - FLASH_BOOTLOADER_LENGTH + FLASH_BOOTLOADER_SCRATCH_LENGTH + FLASH_APPLICATION_S_LENGTH + FLASH_BOOTLOADER_HEADER_LENGTH; + FLASH_APPLICATION_IMAGE_NUMBER == 1 ? FLASH_START + FLASH_BOOTLOADER_LENGTH + FLASH_BOOTLOADER_HEADER_LENGTH : + (DEFINED(BOOTLOADER_SECONDARY_USE_QSPI) || DEFINED(BOOTLOADER_SECONDARY_USE_OSPI_B)) ? FLASH_START + FLASH_BOOTLOADER_LENGTH + FLASH_BOOTLOADER_SCRATCH_LENGTH + FLASH_BOOTLOADER_HEADER_LENGTH : + FLASH_START + FLASH_BOOTLOADER_LENGTH + FLASH_BOOTLOADER_SCRATCH_LENGTH + FLASH_APPLICATION_S_LENGTH + FLASH_BOOTLOADER_HEADER_LENGTH; __bl_FLASH_IMAGE_LENGTH = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : FLASH_APPLICATION_S_LENGTH - FLASH_BOOTLOADER_HEADER_LENGTH; __bl_FLASH_IMAGE_END = __bl_FLASH_IMAGE_START + __bl_FLASH_IMAGE_LENGTH; __bl_XIP_SECONDARY_FLASH_IMAGE_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : - FLASH_BOOTLOADER_LENGTH + FLASH_APPLICATION_S_LENGTH + FLASH_BOOTLOADER_HEADER_LENGTH; + FLASH_START + FLASH_BOOTLOADER_LENGTH + FLASH_APPLICATION_S_LENGTH + FLASH_BOOTLOADER_HEADER_LENGTH; __bl_XIP_SECONDARY_FLASH_IMAGE_END = __bl_XIP_SECONDARY_FLASH_IMAGE_START + __bl_FLASH_IMAGE_LENGTH; __bl_FLASH_NS_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : FLASH_APPLICATION_NS_LENGTH == 0 ? __bl_FLASH_IMAGE_END : __bl_FLASH_IMAGE_START - FLASH_BOOTLOADER_HEADER_LENGTH + FLASH_APPLICATION_S_LENGTH; __bl_FLASH_NSC_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : FLASH_APPLICATION_NS_LENGTH == 0 ? __bl_FLASH_IMAGE_END : - __bl_FLASH_NS_START - FLASH_APPLICATION_NSC_LENGTH; + __bl_FLASH_IMAGE_END - FLASH_APPLICATION_NSC_LENGTH; __bl_RAM_NS_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : FLASH_APPLICATION_NS_LENGTH == 0 ? RAM_START + RAM_LENGTH : RAM_START + RAM_LENGTH - RAM_APPLICATION_NS_LENGTH; @@ -55,7 +60,7 @@ __bl_RAM_NSC_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : __bl_FLASH_NS_IMAGE_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : FLASH_APPLICATION_NS_LENGTH == 0 ? __bl_FLASH_IMAGE_END : __bl_FLASH_NS_START + FLASH_BOOTLOADER_HEADER_LENGTH_2; -__bln_FLASH_IMAGE_START = __bl_FLASH_NS_IMAGE_START; +__bln_FLASH_IMAGE_START = __bl_FLASH_NS_IMAGE_START | (!DEFINED (NS_OFFSET_START) ? 0 : NS_OFFSET_START); __bln_FLASH_IMAGE_LENGTH = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : FLASH_APPLICATION_NS_LENGTH == 0 ? __bl_FLASH_IMAGE_END : FLASH_APPLICATION_NS_LENGTH - FLASH_BOOTLOADER_HEADER_LENGTH_2; @@ -67,30 +72,34 @@ FLASH_ORIGIN = !DEFINED(FLASH_IMAGE_START) ? FLASH_START : LIMITED_FLASH_LENGTH = DEFINED(FLASH_IMAGE_LENGTH) ? FLASH_IMAGE_LENGTH : DEFINED(FLASH_BOOTLOADER_LENGTH) ? FLASH_BOOTLOADER_LENGTH : FLASH_LENGTH; +OPTION_SETTING_SAS_SIZE = 0x34; +OPTION_SETTING_SAS_LENGTH = !DEFINED(OPTION_SETTING_LENGTH) ? 0 : + OPTION_SETTING_LENGTH == 0 ? 0 : + OPTION_SETTING_LENGTH - OPTION_SETTING_SAS_SIZE; /* Define memory regions. */ MEMORY { - ITCM (rx) : ORIGIN = ITCM_START + NS_IMAGE_OFFSET, LENGTH = ITCM_LENGTH - DTCM (rwx) : ORIGIN = DTCM_START + NS_IMAGE_OFFSET, LENGTH = DTCM_LENGTH - FLASH (rx) : ORIGIN = FLASH_ORIGIN + NS_IMAGE_OFFSET, LENGTH = LIMITED_FLASH_LENGTH - RAM (rwx) : ORIGIN = RAM_START + NS_IMAGE_OFFSET, LENGTH = RAM_LENGTH - DATA_FLASH (rx) : ORIGIN = DATA_FLASH_START + NS_IMAGE_OFFSET, LENGTH = DATA_FLASH_LENGTH - QSPI_FLASH (rx) : ORIGIN = QSPI_FLASH_START, LENGTH = QSPI_FLASH_PRV_LENGTH - OSPI_DEVICE_0 (rx) : ORIGIN = OSPI_DEVICE_0_START, LENGTH = OSPI_DEVICE_0_PRV_LENGTH - OSPI_DEVICE_1 (rx) : ORIGIN = OSPI_DEVICE_1_START, LENGTH = OSPI_DEVICE_1_PRV_LENGTH - OSPI_DEVICE_0_RAM (rwx) : ORIGIN = OSPI_DEVICE_0_START, LENGTH = OSPI_DEVICE_0_PRV_LENGTH - OSPI_DEVICE_1_RAM (rwx) : ORIGIN = OSPI_DEVICE_1_START, LENGTH = OSPI_DEVICE_1_PRV_LENGTH - SDRAM (rwx) : ORIGIN = SDRAM_START, LENGTH = SDRAM_LENGTH - OPTION_SETTING (r) : ORIGIN = OPTION_SETTING_START + NS_IMAGE_OFFSET, LENGTH = OPTION_SETTING_LENGTH - OPTION_SETTING_OFS (r) : ORIGIN = OPTION_SETTING_START + NS_IMAGE_OFFSET, LENGTH = 0x18 - OPTION_SETTING_SAS (r) : ORIGIN = OPTION_SETTING_START + NS_IMAGE_OFFSET + 0x34, LENGTH = OPTION_SETTING_LENGTH - 0x34 - OPTION_SETTING_S (r) : ORIGIN = OPTION_SETTING_S_START + NS_IMAGE_OFFSET, LENGTH = OPTION_SETTING_S_LENGTH - ID_CODE (rx) : ORIGIN = ID_CODE_START, LENGTH = ID_CODE_LENGTH + ITCM (rx) : ORIGIN = ITCM_START, LENGTH = ITCM_LENGTH + DTCM (rwx) : ORIGIN = DTCM_START, LENGTH = DTCM_LENGTH + FLASH (rx) : ORIGIN = FLASH_ORIGIN, LENGTH = LIMITED_FLASH_LENGTH + RAM (rwx) : ORIGIN = RAM_START, LENGTH = RAM_LENGTH + DATA_FLASH (rx) : ORIGIN = DATA_FLASH_START, LENGTH = DATA_FLASH_LENGTH + QSPI_FLASH (rx) : ORIGIN = QSPI_FLASH_START, LENGTH = QSPI_FLASH_PRV_LENGTH + OSPI_DEVICE_0 (rx) : ORIGIN = OSPI_DEVICE_0_START, LENGTH = OSPI_DEVICE_0_PRV_LENGTH + OSPI_DEVICE_1 (rx) : ORIGIN = OSPI_DEVICE_1_START, LENGTH = OSPI_DEVICE_1_PRV_LENGTH + OSPI_DEVICE_0_RAM (rwx) : ORIGIN = OSPI_DEVICE_0_START, LENGTH = OSPI_DEVICE_0_PRV_LENGTH + OSPI_DEVICE_1_RAM (rwx) : ORIGIN = OSPI_DEVICE_1_START, LENGTH = OSPI_DEVICE_1_PRV_LENGTH + SDRAM (rwx) : ORIGIN = SDRAM_START, LENGTH = SDRAM_LENGTH + OPTION_SETTING (r) : ORIGIN = OPTION_SETTING_START, LENGTH = OPTION_SETTING_LENGTH + OPTION_SETTING_OFS (r) : ORIGIN = OPTION_SETTING_START, LENGTH = 0x18 + OPTION_SETTING_SAS (r) : ORIGIN = OPTION_SETTING_START + OPTION_SETTING_SAS_SIZE, LENGTH = OPTION_SETTING_SAS_LENGTH + OPTION_SETTING_S (r) : ORIGIN = OPTION_SETTING_S_START, LENGTH = OPTION_SETTING_S_LENGTH + ID_CODE (rx) : ORIGIN = ID_CODE_START, LENGTH = ID_CODE_LENGTH } /* Library configurations */ -GROUP(libgcc.a libc.a libm.a libnosys.a) +GROUP(libgcc.a libc.a libm.a) /* Linker script to place sections and symbol values. Should be used together * with other linker script that defines memory regions FLASH and RAM. @@ -144,27 +153,6 @@ ENTRY(Reset_Handler) SECTIONS { - /* Initialized ITCM data. */ - .itcm_data : - { - /* Start of ITCM Secure Trustzone region. */ - __tz_ITCM_S = ABSOLUTE(ITCM_START); - - /* All ITCM data start */ - __itcm_data_start__ = .; - - KEEP(*(.itcm_data*)) - - /* All ITCM data end */ - __itcm_data_end__ = .; - - /* - * Start of the ITCM Non-Secure Trustzone region. - * ITCM_NS_START can be used to set a fixed address for non-secure ITCM in secure projects or flat projects. - */ - __tz_ITCM_N = DEFINED(ITCM_NS_START) ? ABSOLUTE(ITCM_NS_START) : ALIGN(__itcm_data_end__, 8192); - } > ITCM - .text : { __tz_FLASH_S = ABSOLUTE(FLASH_START); @@ -177,6 +165,10 @@ SECTIONS KEEP(*(.application_vectors*)) __Vectors_End = .; + /* Some devices have a gap of code flash between the vector table and ROM Registers. + * The flash gap section allows applications to place code and data in this section. */ + *(.flash_gap*) + /* ROM Registers start at address 0x00000400 for devices that do not have the OPTION_SETTING region. */ . = OPTION_SETTING_LENGTH > 0 ? . : __ROM_Start + 0x400; KEEP(*(.rom_registers*)) @@ -187,7 +179,6 @@ SECTIONS /* Allocate flash write-boundary-aligned * space for sce9 wrapped public keys for mcuboot if the module is used. */ - . = ALIGN(128); KEEP(*(.mcuboot_sce9_key*)) *(.text*) @@ -233,16 +224,54 @@ SECTIONS __Vectors_Size = __Vectors_End - __Vectors; - .ARM.extab : + . = .; + __itcm_data_pre_location = .; + + /* Initialized ITCM data. */ + /* Aligned to FCACHE2 for RA8. */ + .itcm_data : ALIGN(16) { - *(.ARM.extab* .gnu.linkonce.armextab.*) - } > FLASH + /* Start of ITCM Secure Trustzone region. */ + __tz_ITCM_S = ABSOLUTE(ITCM_START); + + /* All ITCM data start */ + __itcm_data_start = .; + + KEEP(*(.itcm_data*)) + + /* Pad to eight byte alignment in case of ECC initialization. Fill zero. */ + . = ALIGN(8); + + /* All ITCM data end */ + __itcm_data_end = .; + + /* + * Start of the ITCM Non-Secure Trustzone region. + * ITCM_NS_START can be used to set a fixed address for non-secure ITCM in secure projects or flat projects. + */ + __tz_ITCM_N = DEFINED(ITCM_NS_START) ? ABSOLUTE(ITCM_NS_START) : ALIGN(__itcm_data_end, 8192); + } > ITCM AT > FLASH = 0x00 + + /* Addresses exported for ITCM initialization. */ + __itcm_data_init_start = LOADADDR(.itcm_data); + __itcm_data_init_end = LOADADDR(.itcm_data) + SIZEOF(.itcm_data); + + ASSERT(ORIGIN(ITCM) % 8 == 0, "ITCM memory region origin must be aligned to 8 bytes.") + ASSERT(LENGTH(ITCM) % 8 == 0, "ITCM memory region length must be a multiple of 8 bytes.") + ASSERT(LOADADDR(.itcm_data) % 16 == 0, ".itcm_data section must be aligned to 16 bytes.") + ASSERT(SIZEOF(.itcm_data) % 8 == 0, ".itcm_data section size must be a multiple of 8 bytes.") + + /* Restore location counter. */ + /* If ITCM is not present, this will be the address stored in '.' before ALIGN was attempted. */ + /* If ITCM is present, this will be the absolute address that follows the ITCM ROM location. */ + . = (SIZEOF(.itcm_data) > 0) ? __itcm_data_init_end : __itcm_data_pre_location; __exidx_start = .; - .ARM.exidx : + /DISCARD/ : { + *(.ARM.extab* .gnu.linkonce.armextab.*) *(.ARM.exidx* .gnu.linkonce.armexidx.*) - } > FLASH + } __exidx_end = .; /* To copy multiple ROM to RAM sections, @@ -337,50 +366,76 @@ SECTIONS } > RAM AT > FLASH - /* Start address of the initial values for .dtcm_data. */ - __dtcm_data_init_start = __etext + __data_end__ - __data_start__; + . = .; + __dtcm_data_pre_location = LOADADDR(.data) + SIZEOF(.data); /* Initialized DTCM data. */ - .dtcm_data : + /* Aligned to FCACHE2 for RA8. */ + .dtcm_data : ALIGN(16) { /* Start of DTCM Secure Trustzone region. */ __tz_DTCM_S = ABSOLUTE(DTCM_START); /* Initialized DTCM data start */ - __dtcm_data_start__ = .; + __dtcm_data_start = .; KEEP(*(.dtcm_data*)) - /* Initialized DTCM data end */ - __dtcm_data_end__ = .; - } > DTCM AT > FLASH + /* Pad to eight byte alignment in case of ECC initialization. Fill zero. */ + . = ALIGN(8); + /* Initialized DTCM data end */ + __dtcm_data_end = .; + } > DTCM AT > FLASH = 0x00 + + . = __dtcm_data_end; /* Uninitialized DTCM data. */ - .dtcm_noinit (NOLOAD): + /* ALIGN appears on the left side of the colon because it is being used to assign the VMA directly, as opposed to a right side appearance which would control the LMA. */ + .dtcm_bss ALIGN(8) (NOLOAD) : { /* Uninitialized DTCM data start */ - __dtcm_noinit_start = .; + __dtcm_bss_start = .; - KEEP(*(.dtcm_noinit*)) + KEEP(*(.dtcm_bss*)) + + /* Pad to eight byte alignment in case of ECC initialization. No fill because of NOLOAD. */ + . = ALIGN(8); /* Uninitialized DTCM data end */ - __dtcm_noinit_end = .; + __dtcm_bss_end = .; /* * Start of the DTCM Non-Secure Trustzone region. - * DTCM_NS_START can be used to set a fixed address for non-secure ITCM in secure projects or flat projects. + * DTCM_NS_START can be used to set a fixed address for non-secure DTCM in secure projects or flat projects. */ - __tz_DTCM_N = DEFINED(DTCM_NS_START) ? ABSOLUTE(DTCM_NS_START) : ALIGN(__dtcm_noinit_end, 8192); + __tz_DTCM_N = DEFINED(DTCM_NS_START) ? ABSOLUTE(DTCM_NS_START) : ALIGN(__dtcm_bss_end, 8192); } > DTCM - /* TrustZone Secure Gateway Stubs Section. */ + /* Addresses exported for DTCM initialization. */ + __dtcm_data_init_start = LOADADDR(.dtcm_data); + __dtcm_data_init_end = LOADADDR(.dtcm_data) + SIZEOF(.dtcm_data); - /* Some arithmetic is needed to eliminate unnecessary FILL for secure projects. */ - /* 1. Get the address to the next block after the .data section in FLASH. */ - DATA_END = LOADADDR(.data) + SIZEOF(.data); - /* 2. Determine the secure gateway stubs address either by the provided linker variable or the next 1024-byte block after .data */ - SGSTUBS_LOC = (DEFINED(PROJECT_SECURE) && DEFINED(FLASH_NSC_START)) ? ABSOLUTE(FLASH_NSC_START) : ALIGN(DATA_END, 1024); - /* 3. Manually specify the start location for .gnu.sgstubs */ + ASSERT(ORIGIN(DTCM) % 8 == 0, "DTCM memory region origin must be aligned to 8 bytes.") + ASSERT(LENGTH(DTCM) % 8 == 0, "DTCM memory region length must be a multiple of 8 bytes.") + ASSERT(LOADADDR(.dtcm_bss) == ADDR(.dtcm_bss), ".dtcm_bss has (VMA != LMA) but should be NOLOAD (VMA == LMA).") + ASSERT(LOADADDR(.dtcm_data) % 16 == 0, ".dtcm_data section must be aligned to 16 bytes.") + ASSERT(SIZEOF(.dtcm_data) % 8 == 0, ".dtcm_data section size must be a multiple of 8 bytes.") + ASSERT(LOADADDR(.dtcm_bss) % 8 == 0, ".dtcm_bss section must be aligned to 8 bytes.") + ASSERT(SIZEOF(.dtcm_bss) % 8 == 0, ".dtcm_bss section size must be a multiple of 8 bytes.") + ASSERT(__dtcm_bss_start == __dtcm_data_end, ".dtcm_bss section is not adjacent to .dtcm_data section.") + + /* Restore location counter. */ + /* If DTCM is not present, this will be the address stored in '.' before ALIGN was attempted. */ + /* If DTCM is present, this will be the absolute address that follows the DTCM ROM location. */ + . = (SIZEOF(.dtcm_data) > 0) ? __dtcm_data_init_end : __dtcm_data_pre_location; + + /* TrustZone Secure Gateway Stubs Section */ + + /* Store location counter for SPI non-retentive sections. */ + sgstubs_pre_location = .; + + /* Determine the secure gateway stubs address either by the provided linker variable or the next 1024-byte block. */ + SGSTUBS_LOC = (DEFINED(PROJECT_SECURE) && DEFINED(FLASH_NSC_START)) ? ABSOLUTE(FLASH_NSC_START) : ALIGN(1024); .gnu.sgstubs SGSTUBS_LOC : ALIGN(1024) { __tz_FLASH_C = DEFINED(FLASH_NSC_START) ? ABSOLUTE(FLASH_NSC_START) : __RESERVE_NS_RAM ? ABSOLUTE(FLASH_START + FLASH_LENGTH) : ALIGN(1024); @@ -407,8 +462,8 @@ SECTIONS __qspi_flash_code_size__ = __qspi_flash_end__ - __qspi_flash_start__; /* QSPI_FLASH non-retentive section, creates a copy in internal flash that can be copied to QSPI */ - __qspi_flash_code_addr__ = __etext + (__data_end__ - __data_start__); - .qspi_non_retentive : AT (__qspi_flash_code_addr__) + __qspi_flash_code_addr__ = sgstubs_pre_location; + .qspi_non_retentive : AT(__qspi_flash_code_addr__) { __qspi_non_retentive_start__ = .; KEEP(*(.qspi_non_retentive*)) @@ -456,8 +511,8 @@ SECTIONS __ospi_device_0_code_size__ = __ospi_device_0_end__ - __ospi_device_0_start__; /* OSPI_DEVICE_0 non-retentive section, creates a copy in internal flash that can be copied to OSPI */ - __ospi_device_0_code_addr__ = __etext + (__data_end__ - __data_start__); - .ospi_device_0_non_retentive : AT (__ospi_device_0_code_addr__) + __ospi_device_0_code_addr__ = sgstubs_pre_location + (SIZEOF(.qspi_non_retentive)); + .ospi_device_0_non_retentive : AT(__ospi_device_0_code_addr__) { __ospi_device_0_non_retentive_start__ = .; KEEP(*(.ospi_device_0_non_retentive*)) @@ -486,8 +541,8 @@ SECTIONS __ospi_device_1_code_size__ = __ospi_device_1_end__ - __ospi_device_1_start__; /* OSPI_DEVICE_1 non-retentive section, creates a copy in internal flash that can be copied to OSPI */ - __ospi_device_1_code_addr__ = __etext + (__data_end__ - __data_start__); - .ospi_device_1_non_retentive : AT (__ospi_device_1_code_addr__) + __ospi_device_1_code_addr__ = sgstubs_pre_location + (SIZEOF(.qspi_non_retentive) + SIZEOF(.ospi_device_0_non_retentive)); + .ospi_device_1_non_retentive : AT(__ospi_device_1_code_addr__) { __ospi_device_1_non_retentive_start__ = .; KEEP(*(.ospi_device_1_non_retentive*)) @@ -527,7 +582,6 @@ SECTIONS { . = ALIGN(8); __HeapBase = .; - PROVIDE(end = .); /* Place the STD heap here. */ KEEP(*(.heap)) __HeapLimit = .; @@ -615,7 +669,6 @@ SECTIONS __ID_Code_End = .; } > ID_CODE - /* Symbol required for RA Configuration tool. */ __tz_OPTION_SETTING_S = ORIGIN(OPTION_SETTING_OFS); diff --git a/hw/bsp/ra/boards/portenta_c33/script/memory_regions.ld b/hw/bsp/ra/boards/portenta_c33/script/memory_regions.ld new file mode 100644 index 000000000..74c648329 --- /dev/null +++ b/hw/bsp/ra/boards/portenta_c33/script/memory_regions.ld @@ -0,0 +1,25 @@ + + /* generated memory regions file - do not edit */ + RAM_START = 0x20000000; + RAM_LENGTH = 0x80000; + FLASH_START = 0x00000000; + FLASH_LENGTH = 0x200000; + DATA_FLASH_START = 0x08000000; + DATA_FLASH_LENGTH = 0x2000; + OPTION_SETTING_START = 0x0100A100; + OPTION_SETTING_LENGTH = 0x100; + OPTION_SETTING_S_START = 0x0100A200; + OPTION_SETTING_S_LENGTH = 0x100; + ID_CODE_START = 0x00000000; + ID_CODE_LENGTH = 0x0; + SDRAM_START = 0x80010000; + SDRAM_LENGTH = 0x0; + QSPI_FLASH_START = 0x60000000; + QSPI_FLASH_LENGTH = 0x4000000; + OSPI_DEVICE_0_START = 0x68000000; + OSPI_DEVICE_0_LENGTH = 0x8000000; + OSPI_DEVICE_1_START = 0x70000000; + OSPI_DEVICE_1_LENGTH = 0x10000000; + +/* Board has bootloader */ +FLASH_IMAGE_START = 0x10000; diff --git a/hw/bsp/ra/boards/portenta_c33/smart_configurator/configuration.xml b/hw/bsp/ra/boards/portenta_c33/smart_configurator/configuration.xml new file mode 100644 index 000000000..fcc9d711d --- /dev/null +++ b/hw/bsp/ra/boards/portenta_c33/smart_configurator/configuration.xml @@ -0,0 +1,240 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Board Support Package Common Files + Renesas.RA.5.6.0.pack + + + I/O Port + Renesas.RA.5.6.0.pack + + + Arm CMSIS Version 6 - Core (M) + Arm.CMSIS6.6.1.0+fsp.5.6.0.pack + + + Custom Board Support Files + Renesas.RA_board_custom.5.6.0.pack + + + Board support package for R7FA6M5BH3CFC + Renesas.RA_mcu_ra6m5.5.6.0.pack + + + Board support package for RA6M5 + Renesas.RA_mcu_ra6m5.5.6.0.pack + + + Board support package for RA6M5 - FSP Data + Renesas.RA_mcu_ra6m5.5.6.0.pack + + + Board support package for RA6M5 - Events + Renesas.RA_mcu_ra6m5.5.6.0.pack + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/hw/bsp/ra/boards/ra2a1_ek/board.cmake b/hw/bsp/ra/boards/ra2a1_ek/board.cmake index 4d083ca98..9c679c4b5 100644 --- a/hw/bsp/ra/boards/ra2a1_ek/board.cmake +++ b/hw/bsp/ra/boards/ra2a1_ek/board.cmake @@ -1,4 +1,4 @@ -set(CMAKE_SYSTEM_PROCESSOR cortex-m23 CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU cortex-m23 CACHE INTERNAL "System Processor") set(MCU_VARIANT ra2a1) set(JLINK_DEVICE R7FA2A1AB) diff --git a/hw/bsp/ra/boards/ra2a1_ek/board.h b/hw/bsp/ra/boards/ra2a1_ek/board.h index 1c2b666d2..d925fc551 100644 --- a/hw/bsp/ra/boards/ra2a1_ek/board.h +++ b/hw/bsp/ra/boards/ra2a1_ek/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: RA2A1 EK + url: https://www.renesas.com/en/products/microcontrollers-microprocessors/ra-cortex-m-mcus/ek-ra2a1-evaluation-kit-ra2a1-mcu-group +*/ + #ifndef _BOARD_H_ #define _BOARD_H_ @@ -31,21 +36,9 @@ extern "C" { #endif -#define LED1 BSP_IO_PORT_02_PIN_05 -#define LED_STATE_ON 1 - -#define SW1 BSP_IO_PORT_02_PIN_06 +#define LED_STATE_ON 1 #define BUTTON_STATE_ACTIVE 0 -static const ioport_pin_cfg_t board_pin_cfg[] = { - {.pin = LED1, .pin_cfg = IOPORT_CFG_PORT_DIRECTION_OUTPUT}, - {.pin = SW1, .pin_cfg = IOPORT_CFG_PORT_DIRECTION_INPUT}, - // USB FS D+, D-, VBus - {.pin = BSP_IO_PORT_04_PIN_07, .pin_cfg = IOPORT_CFG_PERIPHERAL_PIN | IOPORT_PERIPHERAL_USB_FS}, - {.pin = BSP_IO_PORT_09_PIN_14, .pin_cfg = IOPORT_CFG_PERIPHERAL_PIN | IOPORT_PERIPHERAL_USB_FS}, - {.pin = BSP_IO_PORT_09_PIN_15, .pin_cfg = IOPORT_CFG_PERIPHERAL_PIN | IOPORT_PERIPHERAL_USB_FS}, -}; - #ifdef __cplusplus } #endif diff --git a/hw/bsp/ra/boards/ra2a1_ek/fsp_cfg/bsp/bsp_cfg.h b/hw/bsp/ra/boards/ra2a1_ek/fsp_cfg/bsp/bsp_cfg.h deleted file mode 100644 index 30637c17b..000000000 --- a/hw/bsp/ra/boards/ra2a1_ek/fsp_cfg/bsp/bsp_cfg.h +++ /dev/null @@ -1,62 +0,0 @@ -/* generated configuration header file - do not edit */ -#ifndef BSP_CFG_H_ -#define BSP_CFG_H_ -#ifdef __cplusplus - extern "C" { - #endif - -#include "bsp_clock_cfg.h" -#include "bsp_mcu_family_cfg.h" -#include "board_cfg.h" -#define RA_NOT_DEFINED 0 -#ifndef BSP_CFG_RTOS -#if (RA_NOT_DEFINED) != (RA_NOT_DEFINED) - #define BSP_CFG_RTOS (2) - #elif (RA_NOT_DEFINED) != (RA_NOT_DEFINED) - #define BSP_CFG_RTOS (1) - #else -#define BSP_CFG_RTOS (0) -#endif -#endif -#ifndef BSP_CFG_RTC_USED -#define BSP_CFG_RTC_USED (RA_NOT_DEFINED) -#endif -#undef RA_NOT_DEFINED -#if defined(_RA_BOOT_IMAGE) - #define BSP_CFG_BOOT_IMAGE (1) - #endif -#define BSP_CFG_MCU_VCC_MV (3300) -#define BSP_CFG_STACK_MAIN_BYTES (0x400) -#define BSP_CFG_HEAP_BYTES (0x400) -#define BSP_CFG_PARAM_CHECKING_ENABLE (1) -#define BSP_CFG_ASSERT (0) -#define BSP_CFG_ERROR_LOG (0) - -#define BSP_CFG_PFS_PROTECT ((1)) - -#define BSP_CFG_C_RUNTIME_INIT ((1)) -#define BSP_CFG_EARLY_INIT ((0)) - -#define BSP_CFG_STARTUP_CLOCK_REG_NOT_RESET ((0)) - -#ifndef BSP_CLOCK_CFG_MAIN_OSC_POPULATED -#define BSP_CLOCK_CFG_MAIN_OSC_POPULATED (1) -#endif - -#ifndef BSP_CLOCK_CFG_MAIN_OSC_CLOCK_SOURCE -#define BSP_CLOCK_CFG_MAIN_OSC_CLOCK_SOURCE (0) -#endif -#ifndef BSP_CLOCK_CFG_SUBCLOCK_DRIVE -#define BSP_CLOCK_CFG_SUBCLOCK_DRIVE (0) -#endif -#ifndef BSP_CLOCK_CFG_SUBCLOCK_POPULATED -#define BSP_CLOCK_CFG_SUBCLOCK_POPULATED (1) -#endif -#ifndef BSP_CLOCK_CFG_SUBCLOCK_STABILIZATION_MS -#define BSP_CLOCK_CFG_SUBCLOCK_STABILIZATION_MS 1000 -#endif - -#ifdef __cplusplus - } - #endif -#endif /* BSP_CFG_H_ */ diff --git a/hw/bsp/ra/boards/ra2a1_ek/fsp_cfg/bsp/bsp_mcu_device_pn_cfg.h b/hw/bsp/ra/boards/ra2a1_ek/fsp_cfg/bsp/bsp_mcu_device_pn_cfg.h deleted file mode 100644 index 710e85b28..000000000 --- a/hw/bsp/ra/boards/ra2a1_ek/fsp_cfg/bsp/bsp_mcu_device_pn_cfg.h +++ /dev/null @@ -1,11 +0,0 @@ -/* generated configuration header file - do not edit */ -#ifndef BSP_MCU_DEVICE_PN_CFG_H_ -#define BSP_MCU_DEVICE_PN_CFG_H_ -#define BSP_MCU_R7FA2A1AB3CFM -#define BSP_MCU_FEATURE_SET ('A') -#define BSP_ROM_SIZE_BYTES (262144) -#define BSP_RAM_SIZE_BYTES (32768) -#define BSP_DATA_FLASH_SIZE_BYTES (8192) -#define BSP_PACKAGE_LQFP -#define BSP_PACKAGE_PINS (64) -#endif /* BSP_MCU_DEVICE_PN_CFG_H_ */ diff --git a/hw/bsp/ra/boards/ra2a1_ek/fsp_cfg/bsp/bsp_mcu_family_cfg.h b/hw/bsp/ra/boards/ra2a1_ek/fsp_cfg/bsp/bsp_mcu_family_cfg.h deleted file mode 100644 index 6caef62cc..000000000 --- a/hw/bsp/ra/boards/ra2a1_ek/fsp_cfg/bsp/bsp_mcu_family_cfg.h +++ /dev/null @@ -1,84 +0,0 @@ -/* generated configuration header file - do not edit */ -#ifndef BSP_MCU_FAMILY_CFG_H_ -#define BSP_MCU_FAMILY_CFG_H_ -#ifdef __cplusplus - extern "C" { - #endif - -#include "bsp_mcu_device_pn_cfg.h" -#include "bsp_mcu_device_cfg.h" -#include "../../../ra/fsp/src/bsp/mcu/ra2a1/bsp_mcu_info.h" -#include "bsp_clock_cfg.h" -#define BSP_MCU_GROUP_RA2A1 (1) -#define BSP_LOCO_HZ (32768) -#define BSP_MOCO_HZ (8000000) -#define BSP_SUB_CLOCK_HZ (32768) -#if BSP_CFG_HOCO_FREQUENCY == 0 -#define BSP_HOCO_HZ (24000000) -#elif BSP_CFG_HOCO_FREQUENCY == 2 - #define BSP_HOCO_HZ (32000000) - #elif BSP_CFG_HOCO_FREQUENCY == 4 - #define BSP_HOCO_HZ (48000000) - #elif BSP_CFG_HOCO_FREQUENCY == 5 - #define BSP_HOCO_HZ (64000000) - #else - #error "Invalid HOCO frequency chosen (BSP_CFG_HOCO_FREQUENCY) in bsp_clock_cfg.h" - #endif - -#define BSP_CORTEX_VECTOR_TABLE_ENTRIES (16U) -#define BSP_VECTOR_TABLE_MAX_ENTRIES (48U) - -#define OFS_SEQ1 0xA001A001 | (1 << 1) | (3 << 2) -#define OFS_SEQ2 (15 << 4) | (3 << 8) | (3 << 10) -#define OFS_SEQ3 (1 << 12) | (1 << 14) | (1 << 17) -#define OFS_SEQ4 (3 << 18) |(15 << 20) | (3 << 24) | (3 << 26) -#define OFS_SEQ5 (1 << 28) | (1 << 30) -#define BSP_CFG_USE_LOW_VOLTAGE_MODE ((0)) -#define BSP_CFG_ROM_REG_OFS0 (OFS_SEQ1 | OFS_SEQ2 | OFS_SEQ3 | OFS_SEQ4 | OFS_SEQ5) -#define BSP_CFG_ROM_REG_OFS1 (0xFFFFFEC3 | (1 << 2) | (3 << 3) | (0 << 8)) -#define BSP_CFG_ROM_REG_MPU_PC0_ENABLE (1) -#define BSP_CFG_ROM_REG_MPU_PC0_START (0x000FFFFC) -#define BSP_CFG_ROM_REG_MPU_PC0_END (0x000FFFFF) -#define BSP_CFG_ROM_REG_MPU_PC1_ENABLE (1) -#define BSP_CFG_ROM_REG_MPU_PC1_START (0x000FFFFC) -#define BSP_CFG_ROM_REG_MPU_PC1_END (0x000FFFFF) -#define BSP_CFG_ROM_REG_MPU_REGION0_ENABLE (1) -#define BSP_CFG_ROM_REG_MPU_REGION0_START (0x000FFFFC) -#define BSP_CFG_ROM_REG_MPU_REGION0_END (0x000FFFFF) -#define BSP_CFG_ROM_REG_MPU_REGION1_ENABLE (1) -#define BSP_CFG_ROM_REG_MPU_REGION1_START (0x200FFFFC) -#define BSP_CFG_ROM_REG_MPU_REGION1_END (0x200FFFFF) -#define BSP_CFG_ROM_REG_MPU_REGION2_ENABLE (1) -#define BSP_CFG_ROM_REG_MPU_REGION2_START (0x407FFFFC) -#define BSP_CFG_ROM_REG_MPU_REGION2_END (0x407FFFFF) -#define BSP_CFG_ROM_REG_MPU_REGION3_ENABLE (1) -#define BSP_CFG_ROM_REG_MPU_REGION3_START (0x400DFFFC) -#define BSP_CFG_ROM_REG_MPU_REGION3_END (0x400DFFFF) -#ifndef BSP_CLOCK_CFG_MAIN_OSC_WAIT -#define BSP_CLOCK_CFG_MAIN_OSC_WAIT (9) -#endif -/* Used to create IELS values for the interrupt initialization table g_interrupt_event_link_select. */ -#define BSP_PRV_IELS_ENUM(vector) (ELC_ ## vector) - -/* - ID Code - Note: To permanently lock and disable the debug interface define the BSP_ID_CODE_PERMANENTLY_LOCKED in the compiler settings. - WARNING: This will disable debug access to the part and cannot be reversed by a debug probe. - */ -#if defined(BSP_ID_CODE_PERMANENTLY_LOCKED) - #define BSP_CFG_ID_CODE_LONG_1 (0x00000000) - #define BSP_CFG_ID_CODE_LONG_2 (0x00000000) - #define BSP_CFG_ID_CODE_LONG_3 (0x00000000) - #define BSP_CFG_ID_CODE_LONG_4 (0x00000000) - #else -/* ID CODE: FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF */ -#define BSP_CFG_ID_CODE_LONG_1 (0xFFFFFFFF) -#define BSP_CFG_ID_CODE_LONG_2 (0xFFFFFFFF) -#define BSP_CFG_ID_CODE_LONG_3 (0xFFFFFFFF) -#define BSP_CFG_ID_CODE_LONG_4 (0xffFFFFFF) -#endif - -#ifdef __cplusplus - } - #endif -#endif /* BSP_MCU_FAMILY_CFG_H_ */ diff --git a/hw/bsp/ra/boards/ra2a1_ek/ra_cfg/fsp_cfg/bsp/bsp_cfg.h b/hw/bsp/ra/boards/ra2a1_ek/ra_cfg/fsp_cfg/bsp/bsp_cfg.h new file mode 100644 index 000000000..bf1fe0cc6 --- /dev/null +++ b/hw/bsp/ra/boards/ra2a1_ek/ra_cfg/fsp_cfg/bsp/bsp_cfg.h @@ -0,0 +1,62 @@ +/* generated configuration header file - do not edit */ +#ifndef BSP_CFG_H_ +#define BSP_CFG_H_ +#ifdef __cplusplus + extern "C" { + #endif + + #include "bsp_clock_cfg.h" + #include "bsp_mcu_family_cfg.h" + #include "board_cfg.h" + #define RA_NOT_DEFINED 0 + #ifndef BSP_CFG_RTOS + #if (RA_NOT_DEFINED) != (RA_NOT_DEFINED) + #define BSP_CFG_RTOS (2) + #elif (RA_NOT_DEFINED) != (RA_NOT_DEFINED) + #define BSP_CFG_RTOS (1) + #else + #define BSP_CFG_RTOS (0) + #endif + #endif + #ifndef BSP_CFG_RTC_USED + #define BSP_CFG_RTC_USED (RA_NOT_DEFINED) + #endif + #undef RA_NOT_DEFINED + #if defined(_RA_BOOT_IMAGE) + #define BSP_CFG_BOOT_IMAGE (1) + #endif + #define BSP_CFG_MCU_VCC_MV (3300) + #define BSP_CFG_STACK_MAIN_BYTES (0x400) + #define BSP_CFG_HEAP_BYTES (0x400) + #define BSP_CFG_PARAM_CHECKING_ENABLE (0) + #define BSP_CFG_ASSERT (0) + #define BSP_CFG_ERROR_LOG (0) + + #define BSP_CFG_PFS_PROTECT ((1)) + + #define BSP_CFG_C_RUNTIME_INIT ((1)) + #define BSP_CFG_EARLY_INIT ((0)) + + #define BSP_CFG_STARTUP_CLOCK_REG_NOT_RESET ((0)) + + #ifndef BSP_CLOCK_CFG_MAIN_OSC_POPULATED + #define BSP_CLOCK_CFG_MAIN_OSC_POPULATED (1) + #endif + + #ifndef BSP_CLOCK_CFG_MAIN_OSC_CLOCK_SOURCE + #define BSP_CLOCK_CFG_MAIN_OSC_CLOCK_SOURCE (0) + #endif + #ifndef BSP_CLOCK_CFG_SUBCLOCK_DRIVE + #define BSP_CLOCK_CFG_SUBCLOCK_DRIVE (0) + #endif + #ifndef BSP_CLOCK_CFG_SUBCLOCK_POPULATED + #define BSP_CLOCK_CFG_SUBCLOCK_POPULATED (1) + #endif + #ifndef BSP_CLOCK_CFG_SUBCLOCK_STABILIZATION_MS + #define BSP_CLOCK_CFG_SUBCLOCK_STABILIZATION_MS 1000 + #endif + + #ifdef __cplusplus + } + #endif +#endif /* BSP_CFG_H_ */ diff --git a/hw/bsp/ra/boards/ra2a1_ek/fsp_cfg/bsp/bsp_mcu_device_cfg.h b/hw/bsp/ra/boards/ra2a1_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_device_cfg.h similarity index 100% rename from hw/bsp/ra/boards/ra2a1_ek/fsp_cfg/bsp/bsp_mcu_device_cfg.h rename to hw/bsp/ra/boards/ra2a1_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_device_cfg.h diff --git a/hw/bsp/ra/boards/ra2a1_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_device_pn_cfg.h b/hw/bsp/ra/boards/ra2a1_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_device_pn_cfg.h new file mode 100644 index 000000000..6970e4c33 --- /dev/null +++ b/hw/bsp/ra/boards/ra2a1_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_device_pn_cfg.h @@ -0,0 +1,11 @@ +/* generated configuration header file - do not edit */ +#ifndef BSP_MCU_DEVICE_PN_CFG_H_ +#define BSP_MCU_DEVICE_PN_CFG_H_ +#define BSP_MCU_R7FA2A1AB3CFM + #define BSP_MCU_FEATURE_SET ('A') + #define BSP_ROM_SIZE_BYTES (262144) + #define BSP_RAM_SIZE_BYTES (32768) + #define BSP_DATA_FLASH_SIZE_BYTES (8192) + #define BSP_PACKAGE_LQFP + #define BSP_PACKAGE_PINS (64) +#endif /* BSP_MCU_DEVICE_PN_CFG_H_ */ diff --git a/hw/bsp/ra/boards/ra2a1_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_family_cfg.h b/hw/bsp/ra/boards/ra2a1_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_family_cfg.h new file mode 100644 index 000000000..24e3efaa2 --- /dev/null +++ b/hw/bsp/ra/boards/ra2a1_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_family_cfg.h @@ -0,0 +1,89 @@ +/* generated configuration header file - do not edit */ +#ifndef BSP_MCU_FAMILY_CFG_H_ +#define BSP_MCU_FAMILY_CFG_H_ +#ifdef __cplusplus + extern "C" { + #endif + + #include "bsp_mcu_device_pn_cfg.h" + #include "bsp_mcu_device_cfg.h" + #include "../../../ra/fsp/src/bsp/mcu/ra2a1/bsp_mcu_info.h" + #include "bsp_clock_cfg.h" + #define BSP_MCU_GROUP_RA2A1 (1) + #define BSP_LOCO_HZ (32768) + #define BSP_MOCO_HZ (8000000) + #define BSP_SUB_CLOCK_HZ (32768) + #if BSP_CFG_HOCO_FREQUENCY == 0 + #define BSP_HOCO_HZ (24000000) + #elif BSP_CFG_HOCO_FREQUENCY == 2 + #define BSP_HOCO_HZ (32000000) + #elif BSP_CFG_HOCO_FREQUENCY == 4 + #define BSP_HOCO_HZ (48000000) + #elif BSP_CFG_HOCO_FREQUENCY == 5 + #define BSP_HOCO_HZ (64000000) + #else + #error "Invalid HOCO frequency chosen (BSP_CFG_HOCO_FREQUENCY) in bsp_clock_cfg.h" + #endif + + #define BSP_CORTEX_VECTOR_TABLE_ENTRIES (16U) + #define BSP_VECTOR_TABLE_MAX_ENTRIES (48U) + #define BSP_CFG_INLINE_IRQ_FUNCTIONS (0) + + #define OFS_SEQ1 0xA001A001 | (1 << 1) | (3 << 2) + #define OFS_SEQ2 (15 << 4) | (3 << 8) | (3 << 10) + #define OFS_SEQ3 (1 << 12) | (1 << 14) | (1 << 17) + #define OFS_SEQ4 (3 << 18) |(15 << 20) | (3 << 24) | (3 << 26) + #define OFS_SEQ5 (1 << 28) | (1 << 30) + #define BSP_CFG_USE_LOW_VOLTAGE_MODE ((0)) + #define BSP_CFG_ROM_REG_OFS0 (OFS_SEQ1 | OFS_SEQ2 | OFS_SEQ3 | OFS_SEQ4 | OFS_SEQ5) + #define BSP_CFG_ROM_REG_OFS1 (0xFFFFFEC3 | (1 << 2) | (3 << 3) | (0 << 8)) + #define BSP_CFG_ROM_REG_MPU_PC0_ENABLE (1) + #define BSP_CFG_ROM_REG_MPU_PC0_START (0x000FFFFC) + #define BSP_CFG_ROM_REG_MPU_PC0_END (0x000FFFFF) + #define BSP_CFG_ROM_REG_MPU_PC1_ENABLE (1) + #define BSP_CFG_ROM_REG_MPU_PC1_START (0x000FFFFC) + #define BSP_CFG_ROM_REG_MPU_PC1_END (0x000FFFFF) + #define BSP_CFG_ROM_REG_MPU_REGION0_ENABLE (1) + #define BSP_CFG_ROM_REG_MPU_REGION0_START (0x000FFFFC) + #define BSP_CFG_ROM_REG_MPU_REGION0_END (0x000FFFFF) + #define BSP_CFG_ROM_REG_MPU_REGION1_ENABLE (1) + #define BSP_CFG_ROM_REG_MPU_REGION1_START (0x200FFFFC) + #define BSP_CFG_ROM_REG_MPU_REGION1_END (0x200FFFFF) + #define BSP_CFG_ROM_REG_MPU_REGION2_ENABLE (1) + #define BSP_CFG_ROM_REG_MPU_REGION2_START (0x407FFFFC) + #define BSP_CFG_ROM_REG_MPU_REGION2_END (0x407FFFFF) + #define BSP_CFG_ROM_REG_MPU_REGION3_ENABLE (1) + #define BSP_CFG_ROM_REG_MPU_REGION3_START (0x400DFFFC) + #define BSP_CFG_ROM_REG_MPU_REGION3_END (0x400DFFFF) + #ifndef BSP_CLOCK_CFG_MAIN_OSC_WAIT + #define BSP_CLOCK_CFG_MAIN_OSC_WAIT (9) + #endif + /* Used to create IELS values for the interrupt initialization table g_interrupt_event_link_select. */ + #define BSP_PRV_IELS_ENUM(vector) (ELC_ ## vector) + + /* + ID Code + Note: To lock and disable the debug interface define BSP_ID_CODE_LOCKED in compiler settings. + WARNING: This will disable debug access to the part. However, ALeRASE command will be accepted, which will clear (reset) the ID code. After clearing ID code, debug access will be enabled. + */ + #if defined(BSP_ID_CODE_LOCKED) + #define BSP_CFG_ID_CODE_LONG_1 (0x00000000) + #define BSP_CFG_ID_CODE_LONG_2 (0x00000000) + #define BSP_CFG_ID_CODE_LONG_3 (0x00000000) + #define BSP_CFG_ID_CODE_LONG_4 (0x00000000) + #else + /* ID CODE: FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF */ + #define BSP_CFG_ID_CODE_LONG_1 (0xFFFFFFFF) + #define BSP_CFG_ID_CODE_LONG_2 (0xFFFFFFFF) + #define BSP_CFG_ID_CODE_LONG_3 (0xFFFFFFFF) + #define BSP_CFG_ID_CODE_LONG_4 (0xffFFFFFF) + #endif + + #if (0) + #define BSP_SECTION_FLASH_GAP BSP_PLACE_IN_SECTION(".flash_gap") + #endif + + #ifdef __cplusplus + } + #endif +#endif /* BSP_MCU_FAMILY_CFG_H_ */ diff --git a/hw/bsp/ra/boards/ra2a1_ek/ra_cfg/fsp_cfg/bsp/bsp_pin_cfg.h b/hw/bsp/ra/boards/ra2a1_ek/ra_cfg/fsp_cfg/bsp/bsp_pin_cfg.h new file mode 100644 index 000000000..fc48a5809 --- /dev/null +++ b/hw/bsp/ra/boards/ra2a1_ek/ra_cfg/fsp_cfg/bsp/bsp_pin_cfg.h @@ -0,0 +1,17 @@ +/* generated configuration header file - do not edit */ +#ifndef BSP_PIN_CFG_H_ +#define BSP_PIN_CFG_H_ +#include "r_ioport.h" + +/* Common macro for FSP header files. There is also a corresponding FSP_FOOTER macro at the end of this file. */ +FSP_HEADER + +#define LED1 (BSP_IO_PORT_02_PIN_05) +#define SW1 (BSP_IO_PORT_02_PIN_06) +extern const ioport_cfg_t g_bsp_pin_cfg; /* RA2A1-EK.pincfg */ + +void BSP_PinConfigSecurityInit(); + +/* Common macro for FSP header files. There is also a corresponding FSP_HEADER macro at the top of this file. */ +FSP_FOOTER +#endif /* BSP_PIN_CFG_H_ */ diff --git a/hw/bsp/ra/boards/ra2a1_ek/ra_cfg/fsp_cfg/r_ioport_cfg.h b/hw/bsp/ra/boards/ra2a1_ek/ra_cfg/fsp_cfg/r_ioport_cfg.h new file mode 100644 index 000000000..d2688bf5b --- /dev/null +++ b/hw/bsp/ra/boards/ra2a1_ek/ra_cfg/fsp_cfg/r_ioport_cfg.h @@ -0,0 +1,13 @@ +/* generated configuration header file - do not edit */ +#ifndef R_IOPORT_CFG_H_ +#define R_IOPORT_CFG_H_ +#ifdef __cplusplus +extern "C" { +#endif + +#define IOPORT_CFG_PARAM_CHECKING_ENABLE (BSP_CFG_PARAM_CHECKING_ENABLE) + +#ifdef __cplusplus +} +#endif +#endif /* R_IOPORT_CFG_H_ */ diff --git a/hw/bsp/ra/boards/ra2a1_ek/fsp_cfg/bsp_clock_cfg.h b/hw/bsp/ra/boards/ra2a1_ek/ra_gen/bsp_clock_cfg.h similarity index 92% rename from hw/bsp/ra/boards/ra2a1_ek/fsp_cfg/bsp_clock_cfg.h rename to hw/bsp/ra/boards/ra2a1_ek/ra_gen/bsp_clock_cfg.h index cd9d135f7..6b41669d3 100644 --- a/hw/bsp/ra/boards/ra2a1_ek/fsp_cfg/bsp_clock_cfg.h +++ b/hw/bsp/ra/boards/ra2a1_ek/ra_gen/bsp_clock_cfg.h @@ -8,7 +8,7 @@ #define BSP_CFG_CLOCK_SOURCE (BSP_CLOCKS_SOURCE_CLOCK_HOCO) /* Clock Src: HOCO */ #define BSP_CFG_ICLK_DIV (BSP_CLOCKS_SYS_CLOCK_DIV_1) /* ICLK Div /1 */ #define BSP_CFG_PCLKB_DIV (BSP_CLOCKS_SYS_CLOCK_DIV_2) /* PCLKB Div /2 */ -#define BSP_CFG_PCLKD_DIV (BSP_CLOCKS_SYS_CLOCK_DIV_2) /* PCLKD Div /2 */ +#define BSP_CFG_PCLKD_DIV (BSP_CLOCKS_SYS_CLOCK_DIV_1) /* PCLKD Div /1 */ #define BSP_CFG_FCLK_DIV (BSP_CLOCKS_SYS_CLOCK_DIV_2) /* FCLK Div /2 */ #define BSP_CFG_SDADC_CLOCK_SOURCE (0) /* SDADCCLK Src: HOCO */ #define BSP_CFG_SDADCCLK_DIV (7) /* SDADCCLK Div /12 */ diff --git a/hw/bsp/ra/boards/ra2a1_ek/ra_gen/common_data.c b/hw/bsp/ra/boards/ra2a1_ek/ra_gen/common_data.c new file mode 100644 index 000000000..50036c0ad --- /dev/null +++ b/hw/bsp/ra/boards/ra2a1_ek/ra_gen/common_data.c @@ -0,0 +1,11 @@ +/* generated common source file - do not edit */ +#include "common_data.h" +ioport_instance_ctrl_t g_ioport_ctrl; +const ioport_instance_t g_ioport = + { + .p_api = &g_ioport_on_ioport, + .p_ctrl = &g_ioport_ctrl, + .p_cfg = &g_bsp_pin_cfg, + }; +void g_common_init(void) { +} diff --git a/hw/bsp/ra/boards/ra2a1_ek/ra_gen/common_data.h b/hw/bsp/ra/boards/ra2a1_ek/ra_gen/common_data.h new file mode 100644 index 000000000..6a08cbee0 --- /dev/null +++ b/hw/bsp/ra/boards/ra2a1_ek/ra_gen/common_data.h @@ -0,0 +1,20 @@ +/* generated common header file - do not edit */ +#ifndef COMMON_DATA_H_ +#define COMMON_DATA_H_ +#include +#include "bsp_api.h" +#include "r_ioport.h" +#include "bsp_pin_cfg.h" +FSP_HEADER +#define IOPORT_CFG_NAME g_bsp_pin_cfg +#define IOPORT_CFG_OPEN R_IOPORT_Open +#define IOPORT_CFG_CTRL g_ioport_ctrl + +/* IOPORT Instance */ +extern const ioport_instance_t g_ioport; + +/* IOPORT control structure. */ +extern ioport_instance_ctrl_t g_ioport_ctrl; +void g_common_init(void); +FSP_FOOTER +#endif /* COMMON_DATA_H_ */ diff --git a/hw/bsp/ra/boards/ra2a1_ek/ra_gen/pin_data.c b/hw/bsp/ra/boards/ra2a1_ek/ra_gen/pin_data.c new file mode 100644 index 000000000..7fed32687 --- /dev/null +++ b/hw/bsp/ra/boards/ra2a1_ek/ra_gen/pin_data.c @@ -0,0 +1,115 @@ +/* generated pin source file - do not edit */ +#include "bsp_api.h" +#include "r_ioport.h" + + +const ioport_pin_cfg_t g_bsp_pin_cfg_data[] = { + { + .pin = BSP_IO_PORT_00_PIN_01, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_CTSU) + }, + { + .pin = BSP_IO_PORT_00_PIN_03, + .pin_cfg = ((uint32_t) IOPORT_CFG_ANALOG_ENABLE) + }, + { + .pin = BSP_IO_PORT_01_PIN_08, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_DEBUG) + }, + { + .pin = BSP_IO_PORT_01_PIN_11, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SPI) + }, + { + .pin = BSP_IO_PORT_01_PIN_12, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SPI) + }, + { + .pin = BSP_IO_PORT_02_PIN_01, + .pin_cfg = ((uint32_t) IOPORT_CFG_PORT_DIRECTION_INPUT) + }, + { + .pin = BSP_IO_PORT_02_PIN_04, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SCI0_2_4_6_8) + }, + { + .pin = BSP_IO_PORT_02_PIN_05, + .pin_cfg = ((uint32_t) IOPORT_CFG_PORT_DIRECTION_OUTPUT | (uint32_t) IOPORT_CFG_PORT_OUTPUT_LOW) + }, + { + .pin = BSP_IO_PORT_02_PIN_06, + .pin_cfg = ((uint32_t) IOPORT_CFG_PORT_DIRECTION_INPUT | (uint32_t) IOPORT_CFG_PULLUP_ENABLE) + }, + { + .pin = BSP_IO_PORT_03_PIN_00, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_DEBUG) + }, + { + .pin = BSP_IO_PORT_03_PIN_03, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SPI) + }, + { + .pin = BSP_IO_PORT_03_PIN_04, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SPI) + }, + { + .pin = BSP_IO_PORT_04_PIN_07, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_USB_FS) + }, + { + .pin = BSP_IO_PORT_04_PIN_09, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_CTSU) + }, + { + .pin = BSP_IO_PORT_04_PIN_11, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SCI0_2_4_6_8) + }, + { + .pin = BSP_IO_PORT_09_PIN_14, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_USB_FS) + }, + { + .pin = BSP_IO_PORT_09_PIN_15, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_USB_FS) + }, +}; + +const ioport_cfg_t g_bsp_pin_cfg = { + .number_of_pins = sizeof(g_bsp_pin_cfg_data)/sizeof(ioport_pin_cfg_t), + .p_pin_cfg_data = &g_bsp_pin_cfg_data[0], +}; + +#if BSP_TZ_SECURE_BUILD + +void R_BSP_PinCfgSecurityInit(void); + +/* Initialize SAR registers for secure pins. */ +void R_BSP_PinCfgSecurityInit(void) +{ + #if (2U == BSP_FEATURE_IOPORT_VERSION) + uint32_t pmsar[BSP_FEATURE_BSP_NUM_PMSAR]; + #else + uint16_t pmsar[BSP_FEATURE_BSP_NUM_PMSAR]; + #endif + memset(pmsar, 0xFF, BSP_FEATURE_BSP_NUM_PMSAR * sizeof(R_PMISC->PMSAR[0])); + + + for(uint32_t i = 0; i < g_bsp_pin_cfg.number_of_pins; i++) + { + uint32_t port_pin = g_bsp_pin_cfg.p_pin_cfg_data[i].pin; + uint32_t port = port_pin >> 8U; + uint32_t pin = port_pin & 0xFFU; + pmsar[port] &= (uint16_t) ~(1U << pin); + } + + for(uint32_t i = 0; i < BSP_FEATURE_BSP_NUM_PMSAR; i++) + { + #if (2U == BSP_FEATURE_IOPORT_VERSION) + R_PMISC->PMSAR[i].PMSAR = (uint16_t) pmsar[i]; + #else + R_PMISC->PMSAR[i].PMSAR = pmsar[i]; + #endif + } + +} +#endif diff --git a/hw/bsp/ra/boards/ra2a1_ek/script/fsp.ld b/hw/bsp/ra/boards/ra2a1_ek/script/fsp.ld new file mode 100644 index 000000000..605eef7d2 --- /dev/null +++ b/hw/bsp/ra/boards/ra2a1_ek/script/fsp.ld @@ -0,0 +1,769 @@ +/* + Linker File for Renesas FSP +*/ + +INCLUDE memory_regions.ld + +/* Uncomment and set XIP_SECONDARY_SLOT_IMAGE to 1 below for the secondary XIP application image.*/ +/* + XIP_SECONDARY_SLOT_IMAGE = 1; +*/ + +QSPI_FLASH_PRV_LENGTH = DEFINED(QSPI_FLASH_SIZE) ? ABSOLUTE(QSPI_FLASH_SIZE) : ABSOLUTE(QSPI_FLASH_LENGTH); +OSPI_DEVICE_0_PRV_LENGTH = DEFINED(OSPI_DEVICE_0_SIZE) ? ABSOLUTE(OSPI_DEVICE_0_SIZE) : ABSOLUTE(OSPI_DEVICE_0_LENGTH); +OSPI_DEVICE_1_PRV_LENGTH = DEFINED(OSPI_DEVICE_1_SIZE) ? ABSOLUTE(OSPI_DEVICE_1_SIZE) : ABSOLUTE(OSPI_DEVICE_1_LENGTH); + +/* If a flat (secure) project has DEFINED RAM_NS_BUFFER_LENGTH, then emit IDAU symbols to allocate non-secure RAM. */ +__RESERVE_NS_RAM = !DEFINED(PROJECT_NONSECURE) && DEFINED(RAM_NS_BUFFER_LENGTH) && (OPTION_SETTING_S_LENGTH != 0); + +ITCM_START = DEFINED(ITCM_START)? ITCM_START : 0; +ITCM_LENGTH = DEFINED(ITCM_LENGTH)? ITCM_LENGTH : 0; +DTCM_START = DEFINED(DTCM_START)? DTCM_START : 0; +DTCM_LENGTH = DEFINED(DTCM_LENGTH)? DTCM_LENGTH : 0; +RAM_NS_BUFFER_BLOCK_LENGTH = DEFINED(RAM_NS_BUFFER_LENGTH) ? ALIGN(RAM_NS_BUFFER_LENGTH, 8192) : 0; +RAM_NS_BUFFER_LENGTH = DEFINED(RAM_NS_BUFFER_LENGTH) ? RAM_NS_BUFFER_LENGTH : 0; +RAM_NS_BUFFER_START = RAM_START + RAM_LENGTH - RAM_NS_BUFFER_LENGTH; +RAM_NS_BUFFER_BLOCK_START = RAM_START + RAM_LENGTH - RAM_NS_BUFFER_BLOCK_LENGTH; + +OPTION_SETTING_START_NS = DEFINED(PROJECT_NONSECURE) ? OPTION_SETTING_START : OPTION_SETTING_START + 0x80; + +/* This definition is used to avoid moving the counter in OPTION_SETTING regions for projects that should not configure option settings. + * Bootloader images do not configure option settings because they are owned by the bootloader. + * FSP_BOOTABLE_IMAGE is only defined in bootloader images. */ +__bl_FSP_BOOTABLE_IMAGE = 1; +__bln_FSP_BOOTABLE_IMAGE = 1; +PROJECT_SECURE_OR_FLAT = (!DEFINED(PROJECT_NONSECURE) || DEFINED(PROJECT_SECURE)) && OPTION_SETTING_LENGTH && !DEFINED(FSP_BOOTABLE_IMAGE); +USE_OPTION_SETTING_NS = DEFINED(PROJECT_NONSECURE) && !DEFINED(FSP_BOOTABLE_IMAGE); + +__bl_FLASH_IMAGE_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_IMAGE_NUMBER == 1 ? FLASH_START + FLASH_BOOTLOADER_LENGTH + FLASH_BOOTLOADER_HEADER_LENGTH : + (DEFINED(BOOTLOADER_SECONDARY_USE_QSPI) || DEFINED(BOOTLOADER_SECONDARY_USE_OSPI_B)) ? FLASH_START + FLASH_BOOTLOADER_LENGTH + FLASH_BOOTLOADER_SCRATCH_LENGTH + FLASH_BOOTLOADER_HEADER_LENGTH : + FLASH_START + FLASH_BOOTLOADER_LENGTH + FLASH_BOOTLOADER_SCRATCH_LENGTH + FLASH_APPLICATION_S_LENGTH + FLASH_BOOTLOADER_HEADER_LENGTH; +__bl_FLASH_IMAGE_LENGTH = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_S_LENGTH - FLASH_BOOTLOADER_HEADER_LENGTH; +__bl_FLASH_IMAGE_END = __bl_FLASH_IMAGE_START + __bl_FLASH_IMAGE_LENGTH; +__bl_XIP_SECONDARY_FLASH_IMAGE_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_START + FLASH_BOOTLOADER_LENGTH + FLASH_APPLICATION_S_LENGTH + FLASH_BOOTLOADER_HEADER_LENGTH; +__bl_XIP_SECONDARY_FLASH_IMAGE_END = __bl_XIP_SECONDARY_FLASH_IMAGE_START + __bl_FLASH_IMAGE_LENGTH; +__bl_FLASH_NS_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_NS_LENGTH == 0 ? __bl_FLASH_IMAGE_END : + __bl_FLASH_IMAGE_START - FLASH_BOOTLOADER_HEADER_LENGTH + FLASH_APPLICATION_S_LENGTH; +__bl_FLASH_NSC_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_NS_LENGTH == 0 ? __bl_FLASH_IMAGE_END : + __bl_FLASH_IMAGE_END - FLASH_APPLICATION_NSC_LENGTH; +__bl_RAM_NS_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_NS_LENGTH == 0 ? RAM_START + RAM_LENGTH : + RAM_START + RAM_LENGTH - RAM_APPLICATION_NS_LENGTH; +__bl_RAM_NSC_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_NS_LENGTH == 0 ? RAM_START + RAM_LENGTH : + __bl_RAM_NS_START - RAM_APPLICATION_NSC_LENGTH; +__bl_FLASH_NS_IMAGE_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_NS_LENGTH == 0 ? __bl_FLASH_IMAGE_END : + __bl_FLASH_NS_START + FLASH_BOOTLOADER_HEADER_LENGTH_2; +__bln_FLASH_IMAGE_START = __bl_FLASH_NS_IMAGE_START | (!DEFINED (NS_OFFSET_START) ? 0 : NS_OFFSET_START); +__bln_FLASH_IMAGE_LENGTH = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_NS_LENGTH == 0 ? __bl_FLASH_IMAGE_END : + FLASH_APPLICATION_NS_LENGTH - FLASH_BOOTLOADER_HEADER_LENGTH_2; + +XIP_SECONDARY_SLOT_IMAGE = DEFINED(XIP_SECONDARY_SLOT_IMAGE) ? XIP_SECONDARY_SLOT_IMAGE : 0; +FLASH_ORIGIN = !DEFINED(FLASH_IMAGE_START) ? FLASH_START : + XIP_SECONDARY_SLOT_IMAGE == 1 ? XIP_SECONDARY_FLASH_IMAGE_START : + FLASH_IMAGE_START; +LIMITED_FLASH_LENGTH = DEFINED(FLASH_IMAGE_LENGTH) ? FLASH_IMAGE_LENGTH : + DEFINED(FLASH_BOOTLOADER_LENGTH) ? FLASH_BOOTLOADER_LENGTH : + FLASH_LENGTH; +OPTION_SETTING_SAS_SIZE = 0x34; +OPTION_SETTING_SAS_LENGTH = !DEFINED(OPTION_SETTING_LENGTH) ? 0 : + OPTION_SETTING_LENGTH == 0 ? 0 : + OPTION_SETTING_LENGTH - OPTION_SETTING_SAS_SIZE; + +/* Define memory regions. */ +MEMORY +{ + ITCM (rx) : ORIGIN = ITCM_START, LENGTH = ITCM_LENGTH + DTCM (rwx) : ORIGIN = DTCM_START, LENGTH = DTCM_LENGTH + FLASH (rx) : ORIGIN = FLASH_ORIGIN, LENGTH = LIMITED_FLASH_LENGTH + RAM (rwx) : ORIGIN = RAM_START, LENGTH = RAM_LENGTH + DATA_FLASH (rx) : ORIGIN = DATA_FLASH_START, LENGTH = DATA_FLASH_LENGTH + QSPI_FLASH (rx) : ORIGIN = QSPI_FLASH_START, LENGTH = QSPI_FLASH_PRV_LENGTH + OSPI_DEVICE_0 (rx) : ORIGIN = OSPI_DEVICE_0_START, LENGTH = OSPI_DEVICE_0_PRV_LENGTH + OSPI_DEVICE_1 (rx) : ORIGIN = OSPI_DEVICE_1_START, LENGTH = OSPI_DEVICE_1_PRV_LENGTH + OSPI_DEVICE_0_RAM (rwx) : ORIGIN = OSPI_DEVICE_0_START, LENGTH = OSPI_DEVICE_0_PRV_LENGTH + OSPI_DEVICE_1_RAM (rwx) : ORIGIN = OSPI_DEVICE_1_START, LENGTH = OSPI_DEVICE_1_PRV_LENGTH + SDRAM (rwx) : ORIGIN = SDRAM_START, LENGTH = SDRAM_LENGTH + OPTION_SETTING (r) : ORIGIN = OPTION_SETTING_START, LENGTH = OPTION_SETTING_LENGTH + OPTION_SETTING_OFS (r) : ORIGIN = OPTION_SETTING_START, LENGTH = 0x18 + OPTION_SETTING_SAS (r) : ORIGIN = OPTION_SETTING_START + OPTION_SETTING_SAS_SIZE, LENGTH = OPTION_SETTING_SAS_LENGTH + OPTION_SETTING_S (r) : ORIGIN = OPTION_SETTING_S_START, LENGTH = OPTION_SETTING_S_LENGTH + ID_CODE (rx) : ORIGIN = ID_CODE_START, LENGTH = ID_CODE_LENGTH +} + +/* Library configurations */ +GROUP(libgcc.a libc.a libm.a) + +/* Linker script to place sections and symbol values. Should be used together + * with other linker script that defines memory regions FLASH and RAM. + * It references following symbols, which must be DEFINED in code: + * Reset_Handler : Entry of reset handler + * + * It defines following symbols, which code can use without definition: + * __exidx_start + * __exidx_end + * __copy_table_start__ + * __copy_table_end__ + * __zero_table_start__ + * __zero_table_end__ + * __etext + * __data_start__ + * __preinit_array_start + * __preinit_array_end + * __init_array_start + * __init_array_end + * __fini_array_start + * __fini_array_end + * __data_end__ + * __bss_start__ + * __bss_end__ + * __HeapLimit + * __StackLimit + * __StackTop + * __stack + * __Vectors_End + * __Vectors_Size + * __qspi_flash_start__ + * __qspi_flash_end__ + * __qspi_flash_code_size__ + * __qspi_region_max_size__ + * __qspi_region_start_address__ + * __qspi_region_end_address__ + * __ospi_device_0_start__ + * __ospi_device_0_end__ + * __ospi_device_0_code_size__ + * __ospi_device_0_region_max_size__ + * __ospi_device_0_region_start_address__ + * __ospi_device_0_region_end_address__ + * __ospi_device_1_start__ + * __ospi_device_1_end__ + * __ospi_device_1_code_size__ + * __ospi_device_1_region_max_size__ + * __ospi_device_1_region_start_address__ + * __ospi_device_1_region_end_address__ + */ +ENTRY(Reset_Handler) + +SECTIONS +{ + .text : + { + __tz_FLASH_S = ABSOLUTE(FLASH_START); + __ROM_Start = .; + + /* Even though the vector table is not 256 entries (1KB) long, we still allocate that much + * space because ROM registers are at address 0x400 and there is very little space + * in between. */ + KEEP(*(.fixed_vectors*)) + KEEP(*(.application_vectors*)) + __Vectors_End = .; + + /* Some devices have a gap of code flash between the vector table and ROM Registers. + * The flash gap section allows applications to place code and data in this section. */ + *(.flash_gap*) + + /* ROM Registers start at address 0x00000400 for devices that do not have the OPTION_SETTING region. */ + . = OPTION_SETTING_LENGTH > 0 ? . : __ROM_Start + 0x400; + KEEP(*(.rom_registers*)) + + /* Reserving 0x100 bytes of space for ROM registers. */ + . = OPTION_SETTING_LENGTH > 0 ? . : __ROM_Start + 0x500; + + /* Allocate flash write-boundary-aligned + * space for sce9 wrapped public keys for mcuboot if the module is used. + */ + KEEP(*(.mcuboot_sce9_key*)) + + *(.text*) + + KEEP(*(.version)) + KEEP(*(.init)) + KEEP(*(.fini)) + + /* .ctors */ + *crtbegin.o(.ctors) + *crtbegin?.o(.ctors) + *(EXCLUDE_FILE(*crtend?.o *crtend.o) .ctors) + *(SORT(.ctors.*)) + *(.ctors) + + /* .dtors */ + *crtbegin.o(.dtors) + *crtbegin?.o(.dtors) + *(EXCLUDE_FILE(*crtend?.o *crtend.o) .dtors) + *(SORT(.dtors.*)) + *(.dtors) + + *(.rodata*) + __usb_dev_descriptor_start_fs = .; + KEEP(*(.usb_device_desc_fs*)) + __usb_cfg_descriptor_start_fs = .; + KEEP(*(.usb_config_desc_fs*)) + __usb_interface_descriptor_start_fs = .; + KEEP(*(.usb_interface_desc_fs*)) + __usb_descriptor_end_fs = .; + __usb_dev_descriptor_start_hs = .; + KEEP(*(.usb_device_desc_hs*)) + __usb_cfg_descriptor_start_hs = .; + KEEP(*(.usb_config_desc_hs*)) + __usb_interface_descriptor_start_hs = .; + KEEP(*(.usb_interface_desc_hs*)) + __usb_descriptor_end_hs = .; + + KEEP(*(.eh_frame*)) + + __ROM_End = .; + } > FLASH = 0xFF + + __Vectors_Size = __Vectors_End - __Vectors; + + . = .; + __itcm_data_pre_location = .; + + /* Initialized ITCM data. */ + /* Aligned to FCACHE2 for RA8. */ + .itcm_data : ALIGN(16) + { + /* Start of ITCM Secure Trustzone region. */ + __tz_ITCM_S = ABSOLUTE(ITCM_START); + + /* All ITCM data start */ + __itcm_data_start = .; + + KEEP(*(.itcm_data*)) + + /* Pad to eight byte alignment in case of ECC initialization. Fill zero. */ + . = ALIGN(8); + + /* All ITCM data end */ + __itcm_data_end = .; + + /* + * Start of the ITCM Non-Secure Trustzone region. + * ITCM_NS_START can be used to set a fixed address for non-secure ITCM in secure projects or flat projects. + */ + __tz_ITCM_N = DEFINED(ITCM_NS_START) ? ABSOLUTE(ITCM_NS_START) : ALIGN(__itcm_data_end, 8192); + } > ITCM AT > FLASH = 0x00 + + /* Addresses exported for ITCM initialization. */ + __itcm_data_init_start = LOADADDR(.itcm_data); + __itcm_data_init_end = LOADADDR(.itcm_data) + SIZEOF(.itcm_data); + + ASSERT(ORIGIN(ITCM) % 8 == 0, "ITCM memory region origin must be aligned to 8 bytes.") + ASSERT(LENGTH(ITCM) % 8 == 0, "ITCM memory region length must be a multiple of 8 bytes.") + ASSERT(LOADADDR(.itcm_data) % 16 == 0, ".itcm_data section must be aligned to 16 bytes.") + ASSERT(SIZEOF(.itcm_data) % 8 == 0, ".itcm_data section size must be a multiple of 8 bytes.") + + /* Restore location counter. */ + /* If ITCM is not present, this will be the address stored in '.' before ALIGN was attempted. */ + /* If ITCM is present, this will be the absolute address that follows the ITCM ROM location. */ + . = (SIZEOF(.itcm_data) > 0) ? __itcm_data_init_end : __itcm_data_pre_location; + + __exidx_start = .; + /DISCARD/ : + { + *(.ARM.extab* .gnu.linkonce.armextab.*) + *(.ARM.exidx* .gnu.linkonce.armexidx.*) + } + __exidx_end = .; + + /* To copy multiple ROM to RAM sections, + * uncomment .copy.table section and, + * define __STARTUP_COPY_MULTIPLE in startup_ARMCMx.S */ + /* + .copy.table : + { + . = ALIGN(4); + __copy_table_start__ = .; + LONG (__etext) + LONG (__data_start__) + LONG (__data_end__ - __data_start__) + LONG (__etext2) + LONG (__data2_start__) + LONG (__data2_end__ - __data2_start__) + __copy_table_end__ = .; + } > FLASH + */ + + /* To clear multiple BSS sections, + * uncomment .zero.table section and, + * define __STARTUP_CLEAR_BSS_MULTIPLE in startup_ARMCMx.S */ + /* + .zero.table : + { + . = ALIGN(4); + __zero_table_start__ = .; + LONG (__bss_start__) + LONG (__bss_end__ - __bss_start__) + LONG (__bss2_start__) + LONG (__bss2_end__ - __bss2_start__) + __zero_table_end__ = .; + } > FLASH + */ + + __etext = .; + + __tz_RAM_S = ORIGIN(RAM); + + /* If DTC is used, put the DTC vector table at the start of SRAM. + This avoids memory holes due to 1K alignment required by it. */ + .fsp_dtc_vector_table (NOLOAD) : + { + . = ORIGIN(RAM); + *(.fsp_dtc_vector_table) + } > RAM + + /* Initialized data section. */ + .data : + { + __data_start__ = .; + . = ALIGN(4); + + __Code_In_RAM_Start = .; + + KEEP(*(.code_in_ram*)) + __Code_In_RAM_End = .; + + *(vtable) + /* Don't use *(.data*) because it will place data meant for .data_flash in this section. */ + *(.data.*) + *(.data) + + . = ALIGN(4); + /* preinit data */ + PROVIDE_HIDDEN (__preinit_array_start = .); + KEEP(*(.preinit_array)) + PROVIDE_HIDDEN (__preinit_array_end = .); + + . = ALIGN(4); + /* init data */ + PROVIDE_HIDDEN (__init_array_start = .); + KEEP(*(SORT(.init_array.*))) + KEEP(*(.init_array)) + PROVIDE_HIDDEN (__init_array_end = .); + + + . = ALIGN(4); + /* finit data */ + PROVIDE_HIDDEN (__fini_array_start = .); + KEEP(*(SORT(.fini_array.*))) + KEEP(*(.fini_array)) + PROVIDE_HIDDEN (__fini_array_end = .); + + KEEP(*(.jcr*)) + + . = ALIGN(4); + + /* All data end */ + __data_end__ = .; + + } > RAM AT > FLASH + + . = .; + __dtcm_data_pre_location = LOADADDR(.data) + SIZEOF(.data); + + /* Initialized DTCM data. */ + /* Aligned to FCACHE2 for RA8. */ + .dtcm_data : ALIGN(16) + { + /* Start of DTCM Secure Trustzone region. */ + __tz_DTCM_S = ABSOLUTE(DTCM_START); + + /* Initialized DTCM data start */ + __dtcm_data_start = .; + + KEEP(*(.dtcm_data*)) + + /* Pad to eight byte alignment in case of ECC initialization. Fill zero. */ + . = ALIGN(8); + + /* Initialized DTCM data end */ + __dtcm_data_end = .; + } > DTCM AT > FLASH = 0x00 + + . = __dtcm_data_end; + /* Uninitialized DTCM data. */ + /* ALIGN appears on the left side of the colon because it is being used to assign the VMA directly, as opposed to a right side appearance which would control the LMA. */ + .dtcm_bss ALIGN(8) (NOLOAD) : + { + /* Uninitialized DTCM data start */ + __dtcm_bss_start = .; + + KEEP(*(.dtcm_bss*)) + + /* Pad to eight byte alignment in case of ECC initialization. No fill because of NOLOAD. */ + . = ALIGN(8); + + /* Uninitialized DTCM data end */ + __dtcm_bss_end = .; + + /* + * Start of the DTCM Non-Secure Trustzone region. + * DTCM_NS_START can be used to set a fixed address for non-secure DTCM in secure projects or flat projects. + */ + __tz_DTCM_N = DEFINED(DTCM_NS_START) ? ABSOLUTE(DTCM_NS_START) : ALIGN(__dtcm_bss_end, 8192); + } > DTCM + + /* Addresses exported for DTCM initialization. */ + __dtcm_data_init_start = LOADADDR(.dtcm_data); + __dtcm_data_init_end = LOADADDR(.dtcm_data) + SIZEOF(.dtcm_data); + + ASSERT(ORIGIN(DTCM) % 8 == 0, "DTCM memory region origin must be aligned to 8 bytes.") + ASSERT(LENGTH(DTCM) % 8 == 0, "DTCM memory region length must be a multiple of 8 bytes.") + ASSERT(LOADADDR(.dtcm_bss) == ADDR(.dtcm_bss), ".dtcm_bss has (VMA != LMA) but should be NOLOAD (VMA == LMA).") + ASSERT(LOADADDR(.dtcm_data) % 16 == 0, ".dtcm_data section must be aligned to 16 bytes.") + ASSERT(SIZEOF(.dtcm_data) % 8 == 0, ".dtcm_data section size must be a multiple of 8 bytes.") + ASSERT(LOADADDR(.dtcm_bss) % 8 == 0, ".dtcm_bss section must be aligned to 8 bytes.") + ASSERT(SIZEOF(.dtcm_bss) % 8 == 0, ".dtcm_bss section size must be a multiple of 8 bytes.") + ASSERT(__dtcm_bss_start == __dtcm_data_end, ".dtcm_bss section is not adjacent to .dtcm_data section.") + + /* Restore location counter. */ + /* If DTCM is not present, this will be the address stored in '.' before ALIGN was attempted. */ + /* If DTCM is present, this will be the absolute address that follows the DTCM ROM location. */ + . = (SIZEOF(.dtcm_data) > 0) ? __dtcm_data_init_end : __dtcm_data_pre_location; + + /* TrustZone Secure Gateway Stubs Section */ + + /* Store location counter for SPI non-retentive sections. */ + sgstubs_pre_location = .; + + /* Determine the secure gateway stubs address either by the provided linker variable or the next 1024-byte block. */ + SGSTUBS_LOC = (DEFINED(PROJECT_SECURE) && DEFINED(FLASH_NSC_START)) ? ABSOLUTE(FLASH_NSC_START) : ALIGN(1024); + .gnu.sgstubs SGSTUBS_LOC : ALIGN(1024) + { + __tz_FLASH_C = DEFINED(FLASH_NSC_START) ? ABSOLUTE(FLASH_NSC_START) : __RESERVE_NS_RAM ? ABSOLUTE(FLASH_START + FLASH_LENGTH) : ALIGN(1024); + _start_sg = .; + *(.gnu.sgstubs*) + . = ALIGN(32); + _end_sg = .; + } > FLASH + + __tz_FLASH_N = DEFINED(FLASH_NS_START) ? ABSOLUTE(FLASH_NS_START) : __RESERVE_NS_RAM ? ABSOLUTE(FLASH_START + FLASH_LENGTH) : FLASH_LENGTH < 32768 ? FLASH_LENGTH : ALIGN(32768); + FLASH_NS_IMAGE_START = DEFINED(FLASH_NS_IMAGE_START) ? FLASH_NS_IMAGE_START : __tz_FLASH_N; + + /* Note: There are no secure/non-secure boundaries for QSPI. These symbols are provided for the RA configuration tool. */ + __tz_QSPI_FLASH_S = ORIGIN(QSPI_FLASH); + + /* QSPI_FLASH section to be downloaded via debugger */ + .qspi_flash : + { + __qspi_flash_start__ = .; + KEEP(*(.qspi_flash*)) + KEEP(*(.code_in_qspi*)) + __qspi_flash_end__ = .; + } > QSPI_FLASH + __qspi_flash_code_size__ = __qspi_flash_end__ - __qspi_flash_start__; + + /* QSPI_FLASH non-retentive section, creates a copy in internal flash that can be copied to QSPI */ + __qspi_flash_code_addr__ = sgstubs_pre_location; + .qspi_non_retentive : AT(__qspi_flash_code_addr__) + { + __qspi_non_retentive_start__ = .; + KEEP(*(.qspi_non_retentive*)) + __qspi_non_retentive_end__ = .; + } > QSPI_FLASH + __qspi_non_retentive_size__ = __qspi_non_retentive_end__ - __qspi_non_retentive_start__; + + __qspi_region_max_size__ = 0x4000000; /* Must be the same as defined in MEMORY above */ + __qspi_region_start_address__ = __qspi_flash_start__; + __qspi_region_end_address__ = __qspi_flash_start__ + __qspi_region_max_size__; + + /* Note: There are no secure/non-secure boundaries for QSPI. These symbols are provided for the RA configuration tool. */ + __tz_QSPI_FLASH_N = __qspi_non_retentive_end__; + + /* Support for OctaRAM */ + .OSPI_DEVICE_0_NO_LOAD (NOLOAD): + { + . = ALIGN(4); + __ospi_device_0_start__ = .; + *(.ospi_device_0_no_load*) + . = ALIGN(4); + __ospi_device_0_end__ = .; + } > OSPI_DEVICE_0_RAM + + .OSPI_DEVICE_1_NO_LOAD (NOLOAD): + { + . = ALIGN(4); + __ospi_device_1_start__ = .; + *(.ospi_device_1_no_load*) + . = ALIGN(4); + __ospi_device_1_end__ = .; + } > OSPI_DEVICE_1_RAM + + /* Note: There are no secure/non-secure boundaries for QSPI. These symbols are provided for the RA configuration tool. */ + __tz_OSPI_DEVICE_0_S = ORIGIN(OSPI_DEVICE_0); + + /* OSPI_DEVICE_0 section to be downloaded via debugger */ + .OSPI_DEVICE_0 : + { + __ospi_device_0_start__ = .; + KEEP(*(.ospi_device_0*)) + KEEP(*(.code_in_ospi_device_0*)) + __ospi_device_0_end__ = .; + } > OSPI_DEVICE_0 + __ospi_device_0_code_size__ = __ospi_device_0_end__ - __ospi_device_0_start__; + + /* OSPI_DEVICE_0 non-retentive section, creates a copy in internal flash that can be copied to OSPI */ + __ospi_device_0_code_addr__ = sgstubs_pre_location + (SIZEOF(.qspi_non_retentive)); + .ospi_device_0_non_retentive : AT(__ospi_device_0_code_addr__) + { + __ospi_device_0_non_retentive_start__ = .; + KEEP(*(.ospi_device_0_non_retentive*)) + __ospi_device_0_non_retentive_end__ = .; + } > OSPI_DEVICE_0 + __ospi_device_0_non_retentive_size__ = __ospi_device_0_non_retentive_end__ - __ospi_device_0_non_retentive_start__; + + __ospi_device_0_region_max_size__ = 0x8000000; /* Must be the same as defined in MEMORY above */ + __ospi_device_0_region_start_address__ = __ospi_device_0_start__; + __ospi_device_0_region_end_address__ = __ospi_device_0_start__ + __ospi_device_0_region_max_size__; + + /* Note: There are no secure/non-secure boundaries for OSPI. These symbols are provided for the RA configuration tool. */ + __tz_OSPI_DEVICE_0_N = __ospi_device_0_non_retentive_end__; + + /* Note: There are no secure/non-secure boundaries for OSPI. These symbols are provided for the RA configuration tool. */ + __tz_OSPI_DEVICE_1_S = ORIGIN(OSPI_DEVICE_1); + + /* OSPI_DEVICE_1 section to be downloaded via debugger */ + .OSPI_DEVICE_1 : + { + __ospi_device_1_start__ = .; + KEEP(*(.ospi_device_1*)) + KEEP(*(.code_in_ospi_device_1*)) + __ospi_device_1_end__ = .; + } > OSPI_DEVICE_1 + __ospi_device_1_code_size__ = __ospi_device_1_end__ - __ospi_device_1_start__; + + /* OSPI_DEVICE_1 non-retentive section, creates a copy in internal flash that can be copied to OSPI */ + __ospi_device_1_code_addr__ = sgstubs_pre_location + (SIZEOF(.qspi_non_retentive) + SIZEOF(.ospi_device_0_non_retentive)); + .ospi_device_1_non_retentive : AT(__ospi_device_1_code_addr__) + { + __ospi_device_1_non_retentive_start__ = .; + KEEP(*(.ospi_device_1_non_retentive*)) + __ospi_device_1_non_retentive_end__ = .; + } > OSPI_DEVICE_1 + __ospi_device_1_non_retentive_size__ = __ospi_device_1_non_retentive_end__ - __ospi_device_1_non_retentive_start__; + + __ospi_device_1_region_max_size__ = 0x10000000; /* Must be the same as defined in MEMORY above */ + __ospi_device_1_region_start_address__ = __ospi_device_1_start__; + __ospi_device_1_region_end_address__ = __ospi_device_1_start__ + __ospi_device_1_region_max_size__; + + /* Note: There are no secure/non-secure boundaries for OSPI. These symbols are provided for the RA configuration tool. */ + __tz_OSPI_DEVICE_1_N = __ospi_device_1_non_retentive_end__; + + .noinit (NOLOAD): + { + . = ALIGN(4); + __noinit_start = .; + KEEP(*(.noinit*)) + . = ALIGN(8); + /* Place the FreeRTOS heap here so that the __HeapLimit calculation does not include the freertos heap. */ + KEEP(*(.heap.*)) + __noinit_end = .; + } > RAM + + .bss : + { + . = ALIGN(4); + __bss_start__ = .; + *(.bss*) + *(COMMON) + . = ALIGN(4); + __bss_end__ = .; + } > RAM + + .heap (NOLOAD): + { + . = ALIGN(8); + __HeapBase = .; + /* Place the STD heap here. */ + KEEP(*(.heap)) + __HeapLimit = .; + } > RAM + + /* Stacks are stored in this section. */ + .stack_dummy (NOLOAD): + { + . = ALIGN(8); + __StackLimit = .; + /* Main stack */ + KEEP(*(.stack)) + __StackTop = .; + /* Thread stacks */ + KEEP(*(.stack*)) + __StackTopAll = .; + } > RAM + + PROVIDE(__stack = __StackTopAll); + + /* This symbol represents the end of user allocated RAM. The RAM after this symbol can be used + at run time for things such as ThreadX memory pool allocations. */ + __RAM_segment_used_end__ = ALIGN(__StackTopAll , 4); + + /* RAM_NSC_START can be used to set a fixed address for non-secure callable RAM in secure projects. + * If it is not specified, the address for NSC RAM is the end of RAM aligned to a 1K boundary. + * In flat projects that require non-secure RAM, this variable is set to the start of non-secure RAM. */ + __tz_RAM_C = DEFINED(RAM_NSC_START) ? ABSOLUTE(RAM_NSC_START - RAM_NS_BUFFER_BLOCK_LENGTH) : __RESERVE_NS_RAM ? ABSOLUTE(RAM_NS_BUFFER_BLOCK_START) : ALIGN(__RAM_segment_used_end__, 1024); + + /* RAM_NS_START can be used to set a fixed address for non-secure RAM in secure projects or flat projects. + * RAM_NS_BUFFER_BLOCK_LENGTH is used to allocate non-secure buffers in a flat project. If it is not + * specified, the address for NSC RAM is the end of RAM aligned to an 8K boundary. + * In flat projects that require non-secure RAM, this variable is set to the start of non-secure RAM. */ + __tz_RAM_N = DEFINED(RAM_NS_START) ? ABSOLUTE(RAM_NS_START - RAM_NS_BUFFER_BLOCK_LENGTH) : __RESERVE_NS_RAM ? ABSOLUTE(RAM_NS_BUFFER_BLOCK_START) : ALIGN(__tz_RAM_C, 8192); + + /* Non-secure buffers must be in non-secure RAM. This is primarily used for the EDMAC in flat projects. + * The EDMAC is a non-secure bus master and can only access non-secure RAM. */ + .ns_buffer (NOLOAD): + { + /* Allocate RAM on a 32-byte boundary to help with placement of Ethernet buffers. */ + . = __RESERVE_NS_RAM ? ABSOLUTE(RAM_NS_BUFFER_START & 0xFFFFFFE0) : .; + + KEEP(*(.ns_buffer*)) + } > RAM + + /* Data flash. */ + .data_flash : + { + . = ORIGIN(DATA_FLASH); + __tz_DATA_FLASH_S = .; + __Data_Flash_Start = .; + KEEP(*(.data_flash*)) + __Data_Flash_End = .; + + __tz_DATA_FLASH_N = DEFINED(DATA_FLASH_NS_START) ? ABSOLUTE(DATA_FLASH_NS_START) : __RESERVE_NS_RAM ? ABSOLUTE(DATA_FLASH_START + DATA_FLASH_LENGTH) : ALIGN(1024); + } > DATA_FLASH + + /* Note: There are no secure/non-secure boundaries for SDRAM. These symbols are provided for the RA configuration tool. */ + __tz_SDRAM_S = ORIGIN(SDRAM); + + /* SDRAM */ + .sdram (NOLOAD): + { + __SDRAM_Start = .; + KEEP(*(.sdram*)) + KEEP(*(.frame*)) + __SDRAM_End = .; + } > SDRAM + + /* Note: There are no secure/non-secure boundaries for SDRAM. These symbols are provided for the RA configuration tool. */ + __tz_SDRAM_N = __SDRAM_End; + + /* Note: There are no secure/non-secure boundaries for ID_CODE. These symbols are provided for the RA configuration tool. */ + __tz_ID_CODE_S = ORIGIN(ID_CODE); + + /* Note: There are no secure/non-secure boundaries for ID_CODE. These symbols are provided for the RA configuration tool. + * Set this symbol to the same value as __tz_ID_CODE_S so the RA configuration tool does not split the ID_CODE + * memory region between TrustZone projects. */ + __tz_ID_CODE_N = __tz_ID_CODE_S; + + .id_code : + { + __ID_Code_Start = .; + KEEP(*(.id_code*)) + __ID_Code_End = .; + } > ID_CODE + + /* Symbol required for RA Configuration tool. */ + __tz_OPTION_SETTING_S = ORIGIN(OPTION_SETTING_OFS); + + .option_setting_ofs : + { + __OPTION_SETTING_OFS_Start = .; + KEEP(*(.option_setting_ofs0)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_OFS_Start + 0x04 : __OPTION_SETTING_OFS_Start; + KEEP(*(.option_setting_ofs2)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_OFS_Start + 0x10 : __OPTION_SETTING_OFS_Start; + KEEP(*(.option_setting_dualsel)) + __OPTION_SETTING_OFS_End = .; + } > OPTION_SETTING_OFS = 0xFF + + .option_setting_sas : + { + __OPTION_SETTING_SAS_Start = .; + KEEP(*(.option_setting_sas)) + __OPTION_SETTING_SAS_End = .; + } > OPTION_SETTING_SAS = 0xFF + + /* Symbol required for RA Configuration tool. */ + __tz_OPTION_SETTING_N = ABSOLUTE(OPTION_SETTING_START_NS); + + .option_setting_ns : + { + __OPTION_SETTING_NS_Start = .; + KEEP(*(.option_setting_ofs1)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x04 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_ofs3)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x10 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_banksel)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x40 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_bps0)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x44 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_bps1)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x48 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_bps2)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x4C : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_bps3)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x60 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_pbps0)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x64 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_pbps1)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x68 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_pbps2)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x6C : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_pbps3)) + __OPTION_SETTING_NS_End = .; + } > OPTION_SETTING = 0xFF + + /* Symbol required for RA Configuration tool. */ + __tz_OPTION_SETTING_S_S = ORIGIN(OPTION_SETTING_S); + + .option_setting_s : + { + __OPTION_SETTING_S_Start = .; + KEEP(*(.option_setting_ofs1_sec)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x04 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_ofs3_sec)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x10 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_banksel_sec)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x40 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sec0)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x44 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sec1)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x48 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sec2)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x4C : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sec3)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x60 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_pbps_sec0)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x64 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_pbps_sec1)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x68 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_pbps_sec2)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x6C : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_pbps_sec3)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x80 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_ofs1_sel)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x84 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_ofs3_sel)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x90 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_banksel_sel)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0xC0 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sel0)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0xC4 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sel1)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0xC8 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sel2)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0xCC : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sel3)) + __OPTION_SETTING_S_End = .; + } > OPTION_SETTING_S = 0xFF + + /* Symbol required for RA Configuration tool. */ + __tz_OPTION_SETTING_S_N = __OPTION_SETTING_S_End; +} diff --git a/hw/bsp/ra/boards/ra2a1_ek/script/memory_regions.ld b/hw/bsp/ra/boards/ra2a1_ek/script/memory_regions.ld new file mode 100644 index 000000000..2d6992fed --- /dev/null +++ b/hw/bsp/ra/boards/ra2a1_ek/script/memory_regions.ld @@ -0,0 +1,22 @@ + + /* generated memory regions file - do not edit */ + RAM_START = 0x20000000; + RAM_LENGTH = 0x8000; + FLASH_START = 0x00000000; + FLASH_LENGTH = 0x40000; + DATA_FLASH_START = 0x40100000; + DATA_FLASH_LENGTH = 0x2000; + OPTION_SETTING_START = 0x00000000; + OPTION_SETTING_LENGTH = 0x0; + OPTION_SETTING_S_START = 0x80000000; + OPTION_SETTING_S_LENGTH = 0x0; + ID_CODE_START = 0x01010018; + ID_CODE_LENGTH = 0x20; + SDRAM_START = 0x80010000; + SDRAM_LENGTH = 0x0; + QSPI_FLASH_START = 0x60000000; + QSPI_FLASH_LENGTH = 0x0; + OSPI_DEVICE_0_START = 0x80020000; + OSPI_DEVICE_0_LENGTH = 0x0; + OSPI_DEVICE_1_START = 0x80030000; + OSPI_DEVICE_1_LENGTH = 0x0; diff --git a/hw/bsp/ra/boards/ra2a1_ek/smart_configurator/configuration.xml b/hw/bsp/ra/boards/ra2a1_ek/smart_configurator/configuration.xml new file mode 100644 index 000000000..beeeb67f2 --- /dev/null +++ b/hw/bsp/ra/boards/ra2a1_ek/smart_configurator/configuration.xml @@ -0,0 +1,258 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Simple application that blinks an LED. No RTOS included. + Renesas.RA_baremetal_blinky.5.6.0.pack + + + Board Support Package Common Files + Renesas.RA.5.6.0.pack + + + I/O Port + Renesas.RA.5.6.0.pack + + + Arm CMSIS Version 6 - Core (M) + Arm.CMSIS6.6.1.0+fsp.5.6.0.pack + + + RA2A1-EK Board Support Files + Renesas.RA_board_ra2a1_ek.5.6.0.pack + + + Board support package for R7FA2A1AB3CFM + Renesas.RA_mcu_ra2a1.5.6.0.pack + + + Board support package for RA2A1 + Renesas.RA_mcu_ra2a1.5.6.0.pack + + + Board support package for RA2A1 - FSP Data + Renesas.RA_mcu_ra2a1.5.6.0.pack + + + Board support package for RA2A1 - Events + Renesas.RA_mcu_ra2a1.5.6.0.pack + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/hw/bsp/ra/boards/ra4m1_ek/board.cmake b/hw/bsp/ra/boards/ra4m1_ek/board.cmake index 7bb48bf44..247dea619 100644 --- a/hw/bsp/ra/boards/ra4m1_ek/board.cmake +++ b/hw/bsp/ra/boards/ra4m1_ek/board.cmake @@ -1,4 +1,4 @@ -set(CMAKE_SYSTEM_PROCESSOR cortex-m4 CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU cortex-m4 CACHE INTERNAL "System Processor") set(MCU_VARIANT ra4m1) set(JLINK_DEVICE R7FA4M1AB) diff --git a/hw/bsp/ra/boards/ra4m1_ek/board.h b/hw/bsp/ra/boards/ra4m1_ek/board.h index c132387bc..e146261be 100644 --- a/hw/bsp/ra/boards/ra4m1_ek/board.h +++ b/hw/bsp/ra/boards/ra4m1_ek/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: RA4M1 EK + url: https://www.renesas.com/en/products/microcontrollers-microprocessors/ra-cortex-m-mcus/ek-ra4m1-evaluation-kit-ra4m1-mcu-group +*/ + #ifndef _BOARD_H_ #define _BOARD_H_ @@ -31,21 +36,9 @@ extern "C" { #endif -#define LED1 BSP_IO_PORT_01_PIN_06 -#define LED_STATE_ON 1 - -#define SW1 BSP_IO_PORT_01_PIN_05 +#define LED_STATE_ON 1 #define BUTTON_STATE_ACTIVE 0 -static const ioport_pin_cfg_t board_pin_cfg[] = { - {.pin = LED1, .pin_cfg = IOPORT_CFG_PORT_DIRECTION_OUTPUT}, - {.pin = SW1, .pin_cfg = IOPORT_CFG_PORT_DIRECTION_INPUT}, - // USB FS D+, D-, VBus - {.pin = BSP_IO_PORT_04_PIN_07, .pin_cfg = IOPORT_CFG_PERIPHERAL_PIN | IOPORT_PERIPHERAL_USB_FS}, - {.pin = BSP_IO_PORT_09_PIN_14, .pin_cfg = IOPORT_CFG_PERIPHERAL_PIN | IOPORT_PERIPHERAL_USB_FS}, - {.pin = BSP_IO_PORT_09_PIN_15, .pin_cfg = IOPORT_CFG_PERIPHERAL_PIN | IOPORT_PERIPHERAL_USB_FS}, -}; - #ifdef __cplusplus } #endif diff --git a/hw/bsp/ra/boards/ra4m1_ek/fsp_cfg/bsp/bsp_cfg.h b/hw/bsp/ra/boards/ra4m1_ek/fsp_cfg/bsp/bsp_cfg.h deleted file mode 100644 index 11d5795df..000000000 --- a/hw/bsp/ra/boards/ra4m1_ek/fsp_cfg/bsp/bsp_cfg.h +++ /dev/null @@ -1,35 +0,0 @@ -/* generated configuration header file - do not edit */ -#ifndef BSP_CFG_H_ -#define BSP_CFG_H_ - -#include "bsp_clock_cfg.h" -#include "bsp_mcu_family_cfg.h" -#include "board_cfg.h" - -#undef RA_NOT_DEFINED -#define BSP_CFG_RTOS (0) -#if defined(_RA_BOOT_IMAGE) -#define BSP_CFG_BOOT_IMAGE (1) -#endif -#define BSP_CFG_MCU_VCC_MV (3300) -#define BSP_CFG_STACK_MAIN_BYTES (0x800) -#define BSP_CFG_HEAP_BYTES (0x1000) -#define BSP_CFG_PARAM_CHECKING_ENABLE (1) -#define BSP_CFG_ASSERT (0) -#define BSP_CFG_ERROR_LOG (0) - -#define BSP_CFG_PFS_PROTECT ((1)) - -#define BSP_CFG_C_RUNTIME_INIT ((1)) -#define BSP_CFG_EARLY_INIT ((0)) - -#define BSP_CFG_STARTUP_CLOCK_REG_NOT_RESET ((0)) - -#define BSP_CLOCK_CFG_MAIN_OSC_POPULATED (1) - -#define BSP_CLOCK_CFG_MAIN_OSC_CLOCK_SOURCE (0) -#define BSP_CLOCK_CFG_SUBCLOCK_DRIVE (0) -#define BSP_CLOCK_CFG_SUBCLOCK_POPULATED (1) -#define BSP_CLOCK_CFG_SUBCLOCK_STABILIZATION_MS 1000 - -#endif /* BSP_CFG_H_ */ diff --git a/hw/bsp/ra/boards/ra4m1_ek/fsp_cfg/bsp/bsp_mcu_device_pn_cfg.h b/hw/bsp/ra/boards/ra4m1_ek/fsp_cfg/bsp/bsp_mcu_device_pn_cfg.h deleted file mode 100644 index d810dabb2..000000000 --- a/hw/bsp/ra/boards/ra4m1_ek/fsp_cfg/bsp/bsp_mcu_device_pn_cfg.h +++ /dev/null @@ -1,11 +0,0 @@ -/* generated configuration header file - do not edit */ -#ifndef BSP_MCU_DEVICE_PN_CFG_H_ -#define BSP_MCU_DEVICE_PN_CFG_H_ -#define BSP_MCU_R7FA4M1AB3CFP -#define BSP_MCU_FEATURE_SET ('A') -#define BSP_ROM_SIZE_BYTES (262144) -#define BSP_RAM_SIZE_BYTES (32768) -#define BSP_DATA_FLASH_SIZE_BYTES (8192) -#define BSP_PACKAGE_LQFP -#define BSP_PACKAGE_PINS (100) -#endif /* BSP_MCU_DEVICE_PN_CFG_H_ */ diff --git a/hw/bsp/ra/boards/ra4m1_ek/fsp_cfg/bsp/bsp_mcu_family_cfg.h b/hw/bsp/ra/boards/ra4m1_ek/fsp_cfg/bsp/bsp_mcu_family_cfg.h deleted file mode 100644 index 72cdb89e6..000000000 --- a/hw/bsp/ra/boards/ra4m1_ek/fsp_cfg/bsp/bsp_mcu_family_cfg.h +++ /dev/null @@ -1,78 +0,0 @@ -/* generated configuration header file through renesas e2 studio */ -#ifndef BSP_MCU_FAMILY_CFG_H_ -#define BSP_MCU_FAMILY_CFG_H_ - -#include "bsp_mcu_device_pn_cfg.h" -#include "bsp_mcu_device_cfg.h" -#include "bsp_mcu_info.h" -#include "bsp_clock_cfg.h" - -#define BSP_MCU_GROUP_RA4M1 (1) -#define BSP_LOCO_HZ (32768) -#define BSP_MOCO_HZ (8000000) -#define BSP_SUB_CLOCK_HZ (32768) -#if BSP_CFG_HOCO_FREQUENCY == 0 - #define BSP_HOCO_HZ (24000000) -#elif BSP_CFG_HOCO_FREQUENCY == 2 - #define BSP_HOCO_HZ (32000000) -#elif BSP_CFG_HOCO_FREQUENCY == 4 - #define BSP_HOCO_HZ (48000000) -#elif BSP_CFG_HOCO_FREQUENCY == 5 - #define BSP_HOCO_HZ (64000000) -#else - #error "Invalid HOCO frequency chosen (BSP_CFG_HOCO_FREQUENCY) in bsp_clock_cfg.h" -#endif -#define BSP_CORTEX_VECTOR_TABLE_ENTRIES (16U) -#define BSP_VECTOR_TABLE_MAX_ENTRIES (48U) - -#define OFS_SEQ1 0xA001A001 | (1 << 1) | (3 << 2) -#define OFS_SEQ2 (15 << 4) | (3 << 8) | (3 << 10) -#define OFS_SEQ3 (1 << 12) | (1 << 14) | (1 << 17) -#define OFS_SEQ4 (3 << 18) |(15 << 20) | (3 << 24) | (3 << 26) -#define OFS_SEQ5 (1 << 28) | (1 << 30) -#define BSP_CFG_ROM_REG_OFS0 (OFS_SEQ1 | OFS_SEQ2 | OFS_SEQ3 | OFS_SEQ4 | OFS_SEQ5) -#define BSP_CFG_ROM_REG_OFS1 (0xFFFFFEC3 | (1 << 2) | (3 << 3) | (0 << 8)) -#define BSP_CFG_USE_LOW_VOLTAGE_MODE ((0)) -#define BSP_CFG_ROM_REG_MPU_PC0_ENABLE (1) -#define BSP_CFG_ROM_REG_MPU_PC0_START (0x00FFFFFC) -#define BSP_CFG_ROM_REG_MPU_PC0_END (0x00FFFFFF) -#define BSP_CFG_ROM_REG_MPU_PC1_ENABLE (1) -#define BSP_CFG_ROM_REG_MPU_PC1_START (0x00FFFFFC) -#define BSP_CFG_ROM_REG_MPU_PC1_END (0x00FFFFFF) -#define BSP_CFG_ROM_REG_MPU_REGION0_ENABLE (1) -#define BSP_CFG_ROM_REG_MPU_REGION0_START (0x00FFFFFC) -#define BSP_CFG_ROM_REG_MPU_REGION0_END (0x00FFFFFF) -#define BSP_CFG_ROM_REG_MPU_REGION1_ENABLE (1) -#define BSP_CFG_ROM_REG_MPU_REGION1_START (0x200FFFFC) -#define BSP_CFG_ROM_REG_MPU_REGION1_END (0x200FFFFF) -#define BSP_CFG_ROM_REG_MPU_REGION2_ENABLE (1) -#define BSP_CFG_ROM_REG_MPU_REGION2_START (0x407FFFFC) -#define BSP_CFG_ROM_REG_MPU_REGION2_END (0x407FFFFF) -#define BSP_CFG_ROM_REG_MPU_REGION3_ENABLE (1) -#define BSP_CFG_ROM_REG_MPU_REGION3_START (0x400DFFFC) -#define BSP_CFG_ROM_REG_MPU_REGION3_END (0x400DFFFF) -#ifndef BSP_CLOCK_CFG_MAIN_OSC_WAIT -#define BSP_CLOCK_CFG_MAIN_OSC_WAIT (9) -#endif -/* Used to create IELS values for the interrupt initialization table g_interrupt_event_link_select. */ -#define BSP_PRV_IELS_ENUM(vector) (ELC_ ## vector) - -/* - ID Code - Note: To permanently lock and disable the debug interface define the BSP_ID_CODE_PERMANENTLY_LOCKED in the compiler settings. - WARNING: This will disable debug access to the part and cannot be reversed by a debug probe. - */ -#if defined(BSP_ID_CODE_PERMANENTLY_LOCKED) - #define BSP_CFG_ID_CODE_LONG_1 (0x00000000) - #define BSP_CFG_ID_CODE_LONG_2 (0x00000000) - #define BSP_CFG_ID_CODE_LONG_3 (0x00000000) - #define BSP_CFG_ID_CODE_LONG_4 (0x00000000) - #else -/* ID CODE: FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF */ -#define BSP_CFG_ID_CODE_LONG_1 (0xFFFFFFFF) -#define BSP_CFG_ID_CODE_LONG_2 (0xFFFFFFFF) -#define BSP_CFG_ID_CODE_LONG_3 (0xFFFFFFFF) -#define BSP_CFG_ID_CODE_LONG_4 (0xffFFFFFF) -#endif - -#endif /* BSP_MCU_FAMILY_CFG_H_ */ diff --git a/hw/bsp/ra/boards/ra4m1_ek/ra_cfg/fsp_cfg/bsp/bsp_cfg.h b/hw/bsp/ra/boards/ra4m1_ek/ra_cfg/fsp_cfg/bsp/bsp_cfg.h new file mode 100644 index 000000000..43b0f5b65 --- /dev/null +++ b/hw/bsp/ra/boards/ra4m1_ek/ra_cfg/fsp_cfg/bsp/bsp_cfg.h @@ -0,0 +1,62 @@ +/* generated configuration header file - do not edit */ +#ifndef BSP_CFG_H_ +#define BSP_CFG_H_ +#ifdef __cplusplus + extern "C" { + #endif + + #include "bsp_clock_cfg.h" + #include "bsp_mcu_family_cfg.h" + #include "board_cfg.h" + #define RA_NOT_DEFINED 0 + #ifndef BSP_CFG_RTOS + #if (RA_NOT_DEFINED) != (RA_NOT_DEFINED) + #define BSP_CFG_RTOS (2) + #elif (RA_NOT_DEFINED) != (RA_NOT_DEFINED) + #define BSP_CFG_RTOS (1) + #else + #define BSP_CFG_RTOS (0) + #endif + #endif + #ifndef BSP_CFG_RTC_USED + #define BSP_CFG_RTC_USED (RA_NOT_DEFINED) + #endif + #undef RA_NOT_DEFINED + #if defined(_RA_BOOT_IMAGE) + #define BSP_CFG_BOOT_IMAGE (1) + #endif + #define BSP_CFG_MCU_VCC_MV (3300) + #define BSP_CFG_STACK_MAIN_BYTES (0x800) + #define BSP_CFG_HEAP_BYTES (0x1000) + #define BSP_CFG_PARAM_CHECKING_ENABLE (0) + #define BSP_CFG_ASSERT (0) + #define BSP_CFG_ERROR_LOG (0) + + #define BSP_CFG_PFS_PROTECT ((1)) + + #define BSP_CFG_C_RUNTIME_INIT ((1)) + #define BSP_CFG_EARLY_INIT ((0)) + + #define BSP_CFG_STARTUP_CLOCK_REG_NOT_RESET ((0)) + + #ifndef BSP_CLOCK_CFG_MAIN_OSC_POPULATED + #define BSP_CLOCK_CFG_MAIN_OSC_POPULATED (1) + #endif + + #ifndef BSP_CLOCK_CFG_MAIN_OSC_CLOCK_SOURCE + #define BSP_CLOCK_CFG_MAIN_OSC_CLOCK_SOURCE (0) + #endif + #ifndef BSP_CLOCK_CFG_SUBCLOCK_DRIVE + #define BSP_CLOCK_CFG_SUBCLOCK_DRIVE (0) + #endif + #ifndef BSP_CLOCK_CFG_SUBCLOCK_POPULATED + #define BSP_CLOCK_CFG_SUBCLOCK_POPULATED (1) + #endif + #ifndef BSP_CLOCK_CFG_SUBCLOCK_STABILIZATION_MS + #define BSP_CLOCK_CFG_SUBCLOCK_STABILIZATION_MS 1000 + #endif + + #ifdef __cplusplus + } + #endif +#endif /* BSP_CFG_H_ */ diff --git a/hw/bsp/ra/boards/ra4m1_ek/fsp_cfg/bsp/bsp_mcu_device_cfg.h b/hw/bsp/ra/boards/ra4m1_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_device_cfg.h similarity index 100% rename from hw/bsp/ra/boards/ra4m1_ek/fsp_cfg/bsp/bsp_mcu_device_cfg.h rename to hw/bsp/ra/boards/ra4m1_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_device_cfg.h diff --git a/hw/bsp/ra/boards/ra4m1_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_device_pn_cfg.h b/hw/bsp/ra/boards/ra4m1_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_device_pn_cfg.h new file mode 100644 index 000000000..243fad9b6 --- /dev/null +++ b/hw/bsp/ra/boards/ra4m1_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_device_pn_cfg.h @@ -0,0 +1,11 @@ +/* generated configuration header file - do not edit */ +#ifndef BSP_MCU_DEVICE_PN_CFG_H_ +#define BSP_MCU_DEVICE_PN_CFG_H_ +#define BSP_MCU_R7FA4M1AB3CFP + #define BSP_MCU_FEATURE_SET ('A') + #define BSP_ROM_SIZE_BYTES (262144) + #define BSP_RAM_SIZE_BYTES (32768) + #define BSP_DATA_FLASH_SIZE_BYTES (8192) + #define BSP_PACKAGE_LQFP + #define BSP_PACKAGE_PINS (100) +#endif /* BSP_MCU_DEVICE_PN_CFG_H_ */ diff --git a/hw/bsp/ra/boards/ra4m1_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_family_cfg.h b/hw/bsp/ra/boards/ra4m1_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_family_cfg.h new file mode 100644 index 000000000..3d482b2b6 --- /dev/null +++ b/hw/bsp/ra/boards/ra4m1_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_family_cfg.h @@ -0,0 +1,84 @@ +/* generated configuration header file - do not edit */ +#ifndef BSP_MCU_FAMILY_CFG_H_ +#define BSP_MCU_FAMILY_CFG_H_ +#ifdef __cplusplus + extern "C" { + #endif + + #include "bsp_mcu_device_pn_cfg.h" + #include "bsp_mcu_device_cfg.h" + #include "../../../ra/fsp/src/bsp/mcu/ra4m1/bsp_mcu_info.h" + #include "bsp_clock_cfg.h" + #define BSP_MCU_GROUP_RA4M1 (1) + #define BSP_LOCO_HZ (32768) + #define BSP_MOCO_HZ (8000000) + #define BSP_SUB_CLOCK_HZ (32768) + #if BSP_CFG_HOCO_FREQUENCY == 0 + #define BSP_HOCO_HZ (24000000) + #elif BSP_CFG_HOCO_FREQUENCY == 2 + #define BSP_HOCO_HZ (32000000) + #elif BSP_CFG_HOCO_FREQUENCY == 4 + #define BSP_HOCO_HZ (48000000) + #elif BSP_CFG_HOCO_FREQUENCY == 5 + #define BSP_HOCO_HZ (64000000) + #else + #error "Invalid HOCO frequency chosen (BSP_CFG_HOCO_FREQUENCY) in bsp_clock_cfg.h" + #endif + #define BSP_CORTEX_VECTOR_TABLE_ENTRIES (16U) + #define BSP_VECTOR_TABLE_MAX_ENTRIES (48U) + #define BSP_CFG_INLINE_IRQ_FUNCTIONS (1) + + #define OFS_SEQ1 0xA001A001 | (1 << 1) | (3 << 2) + #define OFS_SEQ2 (15 << 4) | (3 << 8) | (3 << 10) + #define OFS_SEQ3 (1 << 12) | (1 << 14) | (1 << 17) + #define OFS_SEQ4 (3 << 18) |(15 << 20) | (3 << 24) | (3 << 26) + #define OFS_SEQ5 (1 << 28) | (1 << 30) + #define BSP_CFG_ROM_REG_OFS0 (OFS_SEQ1 | OFS_SEQ2 | OFS_SEQ3 | OFS_SEQ4 | OFS_SEQ5) + #define BSP_CFG_ROM_REG_OFS1 (0xFFFFFEC3 | (1 << 2) | (3 << 3) | (0 << 8)) + #define BSP_CFG_USE_LOW_VOLTAGE_MODE ((0)) + #define BSP_CFG_ROM_REG_MPU_PC0_ENABLE (1) + #define BSP_CFG_ROM_REG_MPU_PC0_START (0x00FFFFFC) + #define BSP_CFG_ROM_REG_MPU_PC0_END (0x00FFFFFF) + #define BSP_CFG_ROM_REG_MPU_PC1_ENABLE (1) + #define BSP_CFG_ROM_REG_MPU_PC1_START (0x00FFFFFC) + #define BSP_CFG_ROM_REG_MPU_PC1_END (0x00FFFFFF) + #define BSP_CFG_ROM_REG_MPU_REGION0_ENABLE (1) + #define BSP_CFG_ROM_REG_MPU_REGION0_START (0x00FFFFFC) + #define BSP_CFG_ROM_REG_MPU_REGION0_END (0x00FFFFFF) + #define BSP_CFG_ROM_REG_MPU_REGION1_ENABLE (1) + #define BSP_CFG_ROM_REG_MPU_REGION1_START (0x200FFFFC) + #define BSP_CFG_ROM_REG_MPU_REGION1_END (0x200FFFFF) + #define BSP_CFG_ROM_REG_MPU_REGION2_ENABLE (1) + #define BSP_CFG_ROM_REG_MPU_REGION2_START (0x407FFFFC) + #define BSP_CFG_ROM_REG_MPU_REGION2_END (0x407FFFFF) + #define BSP_CFG_ROM_REG_MPU_REGION3_ENABLE (1) + #define BSP_CFG_ROM_REG_MPU_REGION3_START (0x400DFFFC) + #define BSP_CFG_ROM_REG_MPU_REGION3_END (0x400DFFFF) + #ifndef BSP_CLOCK_CFG_MAIN_OSC_WAIT + #define BSP_CLOCK_CFG_MAIN_OSC_WAIT (9) + #endif + /* Used to create IELS values for the interrupt initialization table g_interrupt_event_link_select. */ + #define BSP_PRV_IELS_ENUM(vector) (ELC_ ## vector) + + /* + ID Code + Note: To permanently lock and disable the debug interface define the BSP_ID_CODE_PERMANENTLY_LOCKED in the compiler settings. + WARNING: This will disable debug access to the part and cannot be reversed by a debug probe. + */ + #if defined(BSP_ID_CODE_PERMANENTLY_LOCKED) + #define BSP_CFG_ID_CODE_LONG_1 (0x00000000) + #define BSP_CFG_ID_CODE_LONG_2 (0x00000000) + #define BSP_CFG_ID_CODE_LONG_3 (0x00000000) + #define BSP_CFG_ID_CODE_LONG_4 (0x00000000) + #else + /* ID CODE: FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF */ + #define BSP_CFG_ID_CODE_LONG_1 (0xFFFFFFFF) + #define BSP_CFG_ID_CODE_LONG_2 (0xFFFFFFFF) + #define BSP_CFG_ID_CODE_LONG_3 (0xFFFFFFFF) + #define BSP_CFG_ID_CODE_LONG_4 (0xffFFFFFF) + #endif + + #ifdef __cplusplus + } + #endif +#endif /* BSP_MCU_FAMILY_CFG_H_ */ diff --git a/hw/bsp/ra/boards/ra4m1_ek/ra_cfg/fsp_cfg/bsp/bsp_pin_cfg.h b/hw/bsp/ra/boards/ra4m1_ek/ra_cfg/fsp_cfg/bsp/bsp_pin_cfg.h new file mode 100644 index 000000000..f77a5bcec --- /dev/null +++ b/hw/bsp/ra/boards/ra4m1_ek/ra_cfg/fsp_cfg/bsp/bsp_pin_cfg.h @@ -0,0 +1,17 @@ +/* generated configuration header file - do not edit */ +#ifndef BSP_PIN_CFG_H_ +#define BSP_PIN_CFG_H_ +#include "r_ioport.h" + +/* Common macro for FSP header files. There is also a corresponding FSP_FOOTER macro at the end of this file. */ +FSP_HEADER + +#define SW1 (BSP_IO_PORT_01_PIN_05) +#define LED1 (BSP_IO_PORT_01_PIN_06) +extern const ioport_cfg_t g_bsp_pin_cfg; /* RA4M1-EK.pincfg */ + +void BSP_PinConfigSecurityInit(); + +/* Common macro for FSP header files. There is also a corresponding FSP_HEADER macro at the top of this file. */ +FSP_FOOTER +#endif /* BSP_PIN_CFG_H_ */ diff --git a/hw/bsp/ra/boards/ra4m1_ek/ra_cfg/fsp_cfg/r_ioport_cfg.h b/hw/bsp/ra/boards/ra4m1_ek/ra_cfg/fsp_cfg/r_ioport_cfg.h new file mode 100644 index 000000000..d2688bf5b --- /dev/null +++ b/hw/bsp/ra/boards/ra4m1_ek/ra_cfg/fsp_cfg/r_ioport_cfg.h @@ -0,0 +1,13 @@ +/* generated configuration header file - do not edit */ +#ifndef R_IOPORT_CFG_H_ +#define R_IOPORT_CFG_H_ +#ifdef __cplusplus +extern "C" { +#endif + +#define IOPORT_CFG_PARAM_CHECKING_ENABLE (BSP_CFG_PARAM_CHECKING_ENABLE) + +#ifdef __cplusplus +} +#endif +#endif /* R_IOPORT_CFG_H_ */ diff --git a/hw/bsp/ra/boards/ra4m1_ek/fsp_cfg/bsp_clock_cfg.h b/hw/bsp/ra/boards/ra4m1_ek/ra_gen/bsp_clock_cfg.h similarity index 94% rename from hw/bsp/ra/boards/ra4m1_ek/fsp_cfg/bsp_clock_cfg.h rename to hw/bsp/ra/boards/ra4m1_ek/ra_gen/bsp_clock_cfg.h index 554126523..81ac5dc11 100644 --- a/hw/bsp/ra/boards/ra4m1_ek/fsp_cfg/bsp_clock_cfg.h +++ b/hw/bsp/ra/boards/ra4m1_ek/ra_gen/bsp_clock_cfg.h @@ -7,7 +7,7 @@ #define BSP_CFG_PLL_SOURCE (BSP_CLOCKS_SOURCE_CLOCK_MAIN_OSC) /* PLL Src: XTAL */ #define BSP_CFG_HOCO_FREQUENCY (0) /* HOCO 24MHz */ #define BSP_CFG_PLL_DIV (BSP_CLOCKS_PLL_DIV_2) /* PLL Div /2 */ -#define BSP_CFG_PLL_MUL (BSP_CLOCKS_PLL_MUL(8u,0u)) /* PLL Mul x8 */ +#define BSP_CFG_PLL_MUL BSP_CLOCKS_PLL_MUL(8U,0U) /* PLL Mul x8 */ #define BSP_CFG_CLOCK_SOURCE (BSP_CLOCKS_SOURCE_CLOCK_PLL) /* Clock Src: PLL */ #define BSP_CFG_ICLK_DIV (BSP_CLOCKS_SYS_CLOCK_DIV_1) /* ICLK Div /1 */ #define BSP_CFG_PCLKA_DIV (BSP_CLOCKS_SYS_CLOCK_DIV_1) /* PCLKA Div /1 */ diff --git a/hw/bsp/ra/boards/ra4m1_ek/ra_gen/common_data.c b/hw/bsp/ra/boards/ra4m1_ek/ra_gen/common_data.c new file mode 100644 index 000000000..50036c0ad --- /dev/null +++ b/hw/bsp/ra/boards/ra4m1_ek/ra_gen/common_data.c @@ -0,0 +1,11 @@ +/* generated common source file - do not edit */ +#include "common_data.h" +ioport_instance_ctrl_t g_ioport_ctrl; +const ioport_instance_t g_ioport = + { + .p_api = &g_ioport_on_ioport, + .p_ctrl = &g_ioport_ctrl, + .p_cfg = &g_bsp_pin_cfg, + }; +void g_common_init(void) { +} diff --git a/hw/bsp/ra/boards/ra4m1_ek/ra_gen/common_data.h b/hw/bsp/ra/boards/ra4m1_ek/ra_gen/common_data.h new file mode 100644 index 000000000..6a08cbee0 --- /dev/null +++ b/hw/bsp/ra/boards/ra4m1_ek/ra_gen/common_data.h @@ -0,0 +1,20 @@ +/* generated common header file - do not edit */ +#ifndef COMMON_DATA_H_ +#define COMMON_DATA_H_ +#include +#include "bsp_api.h" +#include "r_ioport.h" +#include "bsp_pin_cfg.h" +FSP_HEADER +#define IOPORT_CFG_NAME g_bsp_pin_cfg +#define IOPORT_CFG_OPEN R_IOPORT_Open +#define IOPORT_CFG_CTRL g_ioport_ctrl + +/* IOPORT Instance */ +extern const ioport_instance_t g_ioport; + +/* IOPORT control structure. */ +extern ioport_instance_ctrl_t g_ioport_ctrl; +void g_common_init(void); +FSP_FOOTER +#endif /* COMMON_DATA_H_ */ diff --git a/hw/bsp/ra/boards/ra4m1_ek/ra_gen/pin_data.c b/hw/bsp/ra/boards/ra4m1_ek/ra_gen/pin_data.c new file mode 100644 index 000000000..baa713443 --- /dev/null +++ b/hw/bsp/ra/boards/ra4m1_ek/ra_gen/pin_data.c @@ -0,0 +1,119 @@ +/* generated pin source file - do not edit */ +#include "bsp_api.h" +#include "r_ioport.h" + + +const ioport_pin_cfg_t g_bsp_pin_cfg_data[] = { + { + .pin = BSP_IO_PORT_00_PIN_04, + .pin_cfg = ((uint32_t) IOPORT_CFG_ANALOG_ENABLE) + }, + { + .pin = BSP_IO_PORT_01_PIN_00, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SPI) + }, + { + .pin = BSP_IO_PORT_01_PIN_01, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SPI) + }, + { + .pin = BSP_IO_PORT_01_PIN_02, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SPI) + }, + { + .pin = BSP_IO_PORT_01_PIN_03, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SPI) + }, + { + .pin = BSP_IO_PORT_01_PIN_05, + .pin_cfg = ((uint32_t) IOPORT_CFG_PORT_DIRECTION_INPUT | (uint32_t) IOPORT_CFG_PULLUP_ENABLE) + }, + { + .pin = BSP_IO_PORT_01_PIN_06, + .pin_cfg = ((uint32_t) IOPORT_CFG_PORT_DIRECTION_OUTPUT | (uint32_t) IOPORT_CFG_PORT_OUTPUT_LOW) + }, + { + .pin = BSP_IO_PORT_01_PIN_08, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_DEBUG) + }, + { + .pin = BSP_IO_PORT_01_PIN_15, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_CTSU) + }, + { + .pin = BSP_IO_PORT_02_PIN_05, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_CTSU) + }, + { + .pin = BSP_IO_PORT_03_PIN_00, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_DEBUG) + }, + { + .pin = BSP_IO_PORT_04_PIN_00, + .pin_cfg = ((uint32_t) IOPORT_CFG_PORT_DIRECTION_OUTPUT | (uint32_t) IOPORT_CFG_PORT_OUTPUT_LOW) + }, + { + .pin = BSP_IO_PORT_04_PIN_01, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SCI1_3_5_7_9) + }, + { + .pin = BSP_IO_PORT_04_PIN_02, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SCI1_3_5_7_9) + }, + { + .pin = BSP_IO_PORT_04_PIN_03, + .pin_cfg = ((uint32_t) IOPORT_CFG_PORT_DIRECTION_OUTPUT | (uint32_t) IOPORT_CFG_PORT_OUTPUT_LOW) + }, + { + .pin = BSP_IO_PORT_04_PIN_07, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_USB_FS) + }, + { + .pin = BSP_IO_PORT_09_PIN_14, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_USB_FS) + }, + { + .pin = BSP_IO_PORT_09_PIN_15, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_USB_FS) + }, +}; + +const ioport_cfg_t g_bsp_pin_cfg = { + .number_of_pins = sizeof(g_bsp_pin_cfg_data)/sizeof(ioport_pin_cfg_t), + .p_pin_cfg_data = &g_bsp_pin_cfg_data[0], +}; + +#if BSP_TZ_SECURE_BUILD + +void R_BSP_PinCfgSecurityInit(void); + +/* Initialize SAR registers for secure pins. */ +void R_BSP_PinCfgSecurityInit(void) +{ + #if (2U == BSP_FEATURE_IOPORT_VERSION) + uint32_t pmsar[BSP_FEATURE_BSP_NUM_PMSAR]; + #else + uint16_t pmsar[BSP_FEATURE_BSP_NUM_PMSAR]; + #endif + memset(pmsar, 0xFF, BSP_FEATURE_BSP_NUM_PMSAR * sizeof(R_PMISC->PMSAR[0])); + + + for(uint32_t i = 0; i < g_bsp_pin_cfg.number_of_pins; i++) + { + uint32_t port_pin = g_bsp_pin_cfg.p_pin_cfg_data[i].pin; + uint32_t port = port_pin >> 8U; + uint32_t pin = port_pin & 0xFFU; + pmsar[port] &= (uint16_t) ~(1U << pin); + } + + for(uint32_t i = 0; i < BSP_FEATURE_BSP_NUM_PMSAR; i++) + { + #if (2U == BSP_FEATURE_IOPORT_VERSION) + R_PMISC->PMSAR[i].PMSAR = (uint16_t) pmsar[i]; + #else + R_PMISC->PMSAR[i].PMSAR = pmsar[i]; + #endif + } + +} +#endif diff --git a/hw/bsp/ra/boards/ra4m1_ek/script/fsp.ld b/hw/bsp/ra/boards/ra4m1_ek/script/fsp.ld new file mode 100644 index 000000000..605eef7d2 --- /dev/null +++ b/hw/bsp/ra/boards/ra4m1_ek/script/fsp.ld @@ -0,0 +1,769 @@ +/* + Linker File for Renesas FSP +*/ + +INCLUDE memory_regions.ld + +/* Uncomment and set XIP_SECONDARY_SLOT_IMAGE to 1 below for the secondary XIP application image.*/ +/* + XIP_SECONDARY_SLOT_IMAGE = 1; +*/ + +QSPI_FLASH_PRV_LENGTH = DEFINED(QSPI_FLASH_SIZE) ? ABSOLUTE(QSPI_FLASH_SIZE) : ABSOLUTE(QSPI_FLASH_LENGTH); +OSPI_DEVICE_0_PRV_LENGTH = DEFINED(OSPI_DEVICE_0_SIZE) ? ABSOLUTE(OSPI_DEVICE_0_SIZE) : ABSOLUTE(OSPI_DEVICE_0_LENGTH); +OSPI_DEVICE_1_PRV_LENGTH = DEFINED(OSPI_DEVICE_1_SIZE) ? ABSOLUTE(OSPI_DEVICE_1_SIZE) : ABSOLUTE(OSPI_DEVICE_1_LENGTH); + +/* If a flat (secure) project has DEFINED RAM_NS_BUFFER_LENGTH, then emit IDAU symbols to allocate non-secure RAM. */ +__RESERVE_NS_RAM = !DEFINED(PROJECT_NONSECURE) && DEFINED(RAM_NS_BUFFER_LENGTH) && (OPTION_SETTING_S_LENGTH != 0); + +ITCM_START = DEFINED(ITCM_START)? ITCM_START : 0; +ITCM_LENGTH = DEFINED(ITCM_LENGTH)? ITCM_LENGTH : 0; +DTCM_START = DEFINED(DTCM_START)? DTCM_START : 0; +DTCM_LENGTH = DEFINED(DTCM_LENGTH)? DTCM_LENGTH : 0; +RAM_NS_BUFFER_BLOCK_LENGTH = DEFINED(RAM_NS_BUFFER_LENGTH) ? ALIGN(RAM_NS_BUFFER_LENGTH, 8192) : 0; +RAM_NS_BUFFER_LENGTH = DEFINED(RAM_NS_BUFFER_LENGTH) ? RAM_NS_BUFFER_LENGTH : 0; +RAM_NS_BUFFER_START = RAM_START + RAM_LENGTH - RAM_NS_BUFFER_LENGTH; +RAM_NS_BUFFER_BLOCK_START = RAM_START + RAM_LENGTH - RAM_NS_BUFFER_BLOCK_LENGTH; + +OPTION_SETTING_START_NS = DEFINED(PROJECT_NONSECURE) ? OPTION_SETTING_START : OPTION_SETTING_START + 0x80; + +/* This definition is used to avoid moving the counter in OPTION_SETTING regions for projects that should not configure option settings. + * Bootloader images do not configure option settings because they are owned by the bootloader. + * FSP_BOOTABLE_IMAGE is only defined in bootloader images. */ +__bl_FSP_BOOTABLE_IMAGE = 1; +__bln_FSP_BOOTABLE_IMAGE = 1; +PROJECT_SECURE_OR_FLAT = (!DEFINED(PROJECT_NONSECURE) || DEFINED(PROJECT_SECURE)) && OPTION_SETTING_LENGTH && !DEFINED(FSP_BOOTABLE_IMAGE); +USE_OPTION_SETTING_NS = DEFINED(PROJECT_NONSECURE) && !DEFINED(FSP_BOOTABLE_IMAGE); + +__bl_FLASH_IMAGE_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_IMAGE_NUMBER == 1 ? FLASH_START + FLASH_BOOTLOADER_LENGTH + FLASH_BOOTLOADER_HEADER_LENGTH : + (DEFINED(BOOTLOADER_SECONDARY_USE_QSPI) || DEFINED(BOOTLOADER_SECONDARY_USE_OSPI_B)) ? FLASH_START + FLASH_BOOTLOADER_LENGTH + FLASH_BOOTLOADER_SCRATCH_LENGTH + FLASH_BOOTLOADER_HEADER_LENGTH : + FLASH_START + FLASH_BOOTLOADER_LENGTH + FLASH_BOOTLOADER_SCRATCH_LENGTH + FLASH_APPLICATION_S_LENGTH + FLASH_BOOTLOADER_HEADER_LENGTH; +__bl_FLASH_IMAGE_LENGTH = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_S_LENGTH - FLASH_BOOTLOADER_HEADER_LENGTH; +__bl_FLASH_IMAGE_END = __bl_FLASH_IMAGE_START + __bl_FLASH_IMAGE_LENGTH; +__bl_XIP_SECONDARY_FLASH_IMAGE_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_START + FLASH_BOOTLOADER_LENGTH + FLASH_APPLICATION_S_LENGTH + FLASH_BOOTLOADER_HEADER_LENGTH; +__bl_XIP_SECONDARY_FLASH_IMAGE_END = __bl_XIP_SECONDARY_FLASH_IMAGE_START + __bl_FLASH_IMAGE_LENGTH; +__bl_FLASH_NS_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_NS_LENGTH == 0 ? __bl_FLASH_IMAGE_END : + __bl_FLASH_IMAGE_START - FLASH_BOOTLOADER_HEADER_LENGTH + FLASH_APPLICATION_S_LENGTH; +__bl_FLASH_NSC_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_NS_LENGTH == 0 ? __bl_FLASH_IMAGE_END : + __bl_FLASH_IMAGE_END - FLASH_APPLICATION_NSC_LENGTH; +__bl_RAM_NS_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_NS_LENGTH == 0 ? RAM_START + RAM_LENGTH : + RAM_START + RAM_LENGTH - RAM_APPLICATION_NS_LENGTH; +__bl_RAM_NSC_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_NS_LENGTH == 0 ? RAM_START + RAM_LENGTH : + __bl_RAM_NS_START - RAM_APPLICATION_NSC_LENGTH; +__bl_FLASH_NS_IMAGE_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_NS_LENGTH == 0 ? __bl_FLASH_IMAGE_END : + __bl_FLASH_NS_START + FLASH_BOOTLOADER_HEADER_LENGTH_2; +__bln_FLASH_IMAGE_START = __bl_FLASH_NS_IMAGE_START | (!DEFINED (NS_OFFSET_START) ? 0 : NS_OFFSET_START); +__bln_FLASH_IMAGE_LENGTH = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_NS_LENGTH == 0 ? __bl_FLASH_IMAGE_END : + FLASH_APPLICATION_NS_LENGTH - FLASH_BOOTLOADER_HEADER_LENGTH_2; + +XIP_SECONDARY_SLOT_IMAGE = DEFINED(XIP_SECONDARY_SLOT_IMAGE) ? XIP_SECONDARY_SLOT_IMAGE : 0; +FLASH_ORIGIN = !DEFINED(FLASH_IMAGE_START) ? FLASH_START : + XIP_SECONDARY_SLOT_IMAGE == 1 ? XIP_SECONDARY_FLASH_IMAGE_START : + FLASH_IMAGE_START; +LIMITED_FLASH_LENGTH = DEFINED(FLASH_IMAGE_LENGTH) ? FLASH_IMAGE_LENGTH : + DEFINED(FLASH_BOOTLOADER_LENGTH) ? FLASH_BOOTLOADER_LENGTH : + FLASH_LENGTH; +OPTION_SETTING_SAS_SIZE = 0x34; +OPTION_SETTING_SAS_LENGTH = !DEFINED(OPTION_SETTING_LENGTH) ? 0 : + OPTION_SETTING_LENGTH == 0 ? 0 : + OPTION_SETTING_LENGTH - OPTION_SETTING_SAS_SIZE; + +/* Define memory regions. */ +MEMORY +{ + ITCM (rx) : ORIGIN = ITCM_START, LENGTH = ITCM_LENGTH + DTCM (rwx) : ORIGIN = DTCM_START, LENGTH = DTCM_LENGTH + FLASH (rx) : ORIGIN = FLASH_ORIGIN, LENGTH = LIMITED_FLASH_LENGTH + RAM (rwx) : ORIGIN = RAM_START, LENGTH = RAM_LENGTH + DATA_FLASH (rx) : ORIGIN = DATA_FLASH_START, LENGTH = DATA_FLASH_LENGTH + QSPI_FLASH (rx) : ORIGIN = QSPI_FLASH_START, LENGTH = QSPI_FLASH_PRV_LENGTH + OSPI_DEVICE_0 (rx) : ORIGIN = OSPI_DEVICE_0_START, LENGTH = OSPI_DEVICE_0_PRV_LENGTH + OSPI_DEVICE_1 (rx) : ORIGIN = OSPI_DEVICE_1_START, LENGTH = OSPI_DEVICE_1_PRV_LENGTH + OSPI_DEVICE_0_RAM (rwx) : ORIGIN = OSPI_DEVICE_0_START, LENGTH = OSPI_DEVICE_0_PRV_LENGTH + OSPI_DEVICE_1_RAM (rwx) : ORIGIN = OSPI_DEVICE_1_START, LENGTH = OSPI_DEVICE_1_PRV_LENGTH + SDRAM (rwx) : ORIGIN = SDRAM_START, LENGTH = SDRAM_LENGTH + OPTION_SETTING (r) : ORIGIN = OPTION_SETTING_START, LENGTH = OPTION_SETTING_LENGTH + OPTION_SETTING_OFS (r) : ORIGIN = OPTION_SETTING_START, LENGTH = 0x18 + OPTION_SETTING_SAS (r) : ORIGIN = OPTION_SETTING_START + OPTION_SETTING_SAS_SIZE, LENGTH = OPTION_SETTING_SAS_LENGTH + OPTION_SETTING_S (r) : ORIGIN = OPTION_SETTING_S_START, LENGTH = OPTION_SETTING_S_LENGTH + ID_CODE (rx) : ORIGIN = ID_CODE_START, LENGTH = ID_CODE_LENGTH +} + +/* Library configurations */ +GROUP(libgcc.a libc.a libm.a) + +/* Linker script to place sections and symbol values. Should be used together + * with other linker script that defines memory regions FLASH and RAM. + * It references following symbols, which must be DEFINED in code: + * Reset_Handler : Entry of reset handler + * + * It defines following symbols, which code can use without definition: + * __exidx_start + * __exidx_end + * __copy_table_start__ + * __copy_table_end__ + * __zero_table_start__ + * __zero_table_end__ + * __etext + * __data_start__ + * __preinit_array_start + * __preinit_array_end + * __init_array_start + * __init_array_end + * __fini_array_start + * __fini_array_end + * __data_end__ + * __bss_start__ + * __bss_end__ + * __HeapLimit + * __StackLimit + * __StackTop + * __stack + * __Vectors_End + * __Vectors_Size + * __qspi_flash_start__ + * __qspi_flash_end__ + * __qspi_flash_code_size__ + * __qspi_region_max_size__ + * __qspi_region_start_address__ + * __qspi_region_end_address__ + * __ospi_device_0_start__ + * __ospi_device_0_end__ + * __ospi_device_0_code_size__ + * __ospi_device_0_region_max_size__ + * __ospi_device_0_region_start_address__ + * __ospi_device_0_region_end_address__ + * __ospi_device_1_start__ + * __ospi_device_1_end__ + * __ospi_device_1_code_size__ + * __ospi_device_1_region_max_size__ + * __ospi_device_1_region_start_address__ + * __ospi_device_1_region_end_address__ + */ +ENTRY(Reset_Handler) + +SECTIONS +{ + .text : + { + __tz_FLASH_S = ABSOLUTE(FLASH_START); + __ROM_Start = .; + + /* Even though the vector table is not 256 entries (1KB) long, we still allocate that much + * space because ROM registers are at address 0x400 and there is very little space + * in between. */ + KEEP(*(.fixed_vectors*)) + KEEP(*(.application_vectors*)) + __Vectors_End = .; + + /* Some devices have a gap of code flash between the vector table and ROM Registers. + * The flash gap section allows applications to place code and data in this section. */ + *(.flash_gap*) + + /* ROM Registers start at address 0x00000400 for devices that do not have the OPTION_SETTING region. */ + . = OPTION_SETTING_LENGTH > 0 ? . : __ROM_Start + 0x400; + KEEP(*(.rom_registers*)) + + /* Reserving 0x100 bytes of space for ROM registers. */ + . = OPTION_SETTING_LENGTH > 0 ? . : __ROM_Start + 0x500; + + /* Allocate flash write-boundary-aligned + * space for sce9 wrapped public keys for mcuboot if the module is used. + */ + KEEP(*(.mcuboot_sce9_key*)) + + *(.text*) + + KEEP(*(.version)) + KEEP(*(.init)) + KEEP(*(.fini)) + + /* .ctors */ + *crtbegin.o(.ctors) + *crtbegin?.o(.ctors) + *(EXCLUDE_FILE(*crtend?.o *crtend.o) .ctors) + *(SORT(.ctors.*)) + *(.ctors) + + /* .dtors */ + *crtbegin.o(.dtors) + *crtbegin?.o(.dtors) + *(EXCLUDE_FILE(*crtend?.o *crtend.o) .dtors) + *(SORT(.dtors.*)) + *(.dtors) + + *(.rodata*) + __usb_dev_descriptor_start_fs = .; + KEEP(*(.usb_device_desc_fs*)) + __usb_cfg_descriptor_start_fs = .; + KEEP(*(.usb_config_desc_fs*)) + __usb_interface_descriptor_start_fs = .; + KEEP(*(.usb_interface_desc_fs*)) + __usb_descriptor_end_fs = .; + __usb_dev_descriptor_start_hs = .; + KEEP(*(.usb_device_desc_hs*)) + __usb_cfg_descriptor_start_hs = .; + KEEP(*(.usb_config_desc_hs*)) + __usb_interface_descriptor_start_hs = .; + KEEP(*(.usb_interface_desc_hs*)) + __usb_descriptor_end_hs = .; + + KEEP(*(.eh_frame*)) + + __ROM_End = .; + } > FLASH = 0xFF + + __Vectors_Size = __Vectors_End - __Vectors; + + . = .; + __itcm_data_pre_location = .; + + /* Initialized ITCM data. */ + /* Aligned to FCACHE2 for RA8. */ + .itcm_data : ALIGN(16) + { + /* Start of ITCM Secure Trustzone region. */ + __tz_ITCM_S = ABSOLUTE(ITCM_START); + + /* All ITCM data start */ + __itcm_data_start = .; + + KEEP(*(.itcm_data*)) + + /* Pad to eight byte alignment in case of ECC initialization. Fill zero. */ + . = ALIGN(8); + + /* All ITCM data end */ + __itcm_data_end = .; + + /* + * Start of the ITCM Non-Secure Trustzone region. + * ITCM_NS_START can be used to set a fixed address for non-secure ITCM in secure projects or flat projects. + */ + __tz_ITCM_N = DEFINED(ITCM_NS_START) ? ABSOLUTE(ITCM_NS_START) : ALIGN(__itcm_data_end, 8192); + } > ITCM AT > FLASH = 0x00 + + /* Addresses exported for ITCM initialization. */ + __itcm_data_init_start = LOADADDR(.itcm_data); + __itcm_data_init_end = LOADADDR(.itcm_data) + SIZEOF(.itcm_data); + + ASSERT(ORIGIN(ITCM) % 8 == 0, "ITCM memory region origin must be aligned to 8 bytes.") + ASSERT(LENGTH(ITCM) % 8 == 0, "ITCM memory region length must be a multiple of 8 bytes.") + ASSERT(LOADADDR(.itcm_data) % 16 == 0, ".itcm_data section must be aligned to 16 bytes.") + ASSERT(SIZEOF(.itcm_data) % 8 == 0, ".itcm_data section size must be a multiple of 8 bytes.") + + /* Restore location counter. */ + /* If ITCM is not present, this will be the address stored in '.' before ALIGN was attempted. */ + /* If ITCM is present, this will be the absolute address that follows the ITCM ROM location. */ + . = (SIZEOF(.itcm_data) > 0) ? __itcm_data_init_end : __itcm_data_pre_location; + + __exidx_start = .; + /DISCARD/ : + { + *(.ARM.extab* .gnu.linkonce.armextab.*) + *(.ARM.exidx* .gnu.linkonce.armexidx.*) + } + __exidx_end = .; + + /* To copy multiple ROM to RAM sections, + * uncomment .copy.table section and, + * define __STARTUP_COPY_MULTIPLE in startup_ARMCMx.S */ + /* + .copy.table : + { + . = ALIGN(4); + __copy_table_start__ = .; + LONG (__etext) + LONG (__data_start__) + LONG (__data_end__ - __data_start__) + LONG (__etext2) + LONG (__data2_start__) + LONG (__data2_end__ - __data2_start__) + __copy_table_end__ = .; + } > FLASH + */ + + /* To clear multiple BSS sections, + * uncomment .zero.table section and, + * define __STARTUP_CLEAR_BSS_MULTIPLE in startup_ARMCMx.S */ + /* + .zero.table : + { + . = ALIGN(4); + __zero_table_start__ = .; + LONG (__bss_start__) + LONG (__bss_end__ - __bss_start__) + LONG (__bss2_start__) + LONG (__bss2_end__ - __bss2_start__) + __zero_table_end__ = .; + } > FLASH + */ + + __etext = .; + + __tz_RAM_S = ORIGIN(RAM); + + /* If DTC is used, put the DTC vector table at the start of SRAM. + This avoids memory holes due to 1K alignment required by it. */ + .fsp_dtc_vector_table (NOLOAD) : + { + . = ORIGIN(RAM); + *(.fsp_dtc_vector_table) + } > RAM + + /* Initialized data section. */ + .data : + { + __data_start__ = .; + . = ALIGN(4); + + __Code_In_RAM_Start = .; + + KEEP(*(.code_in_ram*)) + __Code_In_RAM_End = .; + + *(vtable) + /* Don't use *(.data*) because it will place data meant for .data_flash in this section. */ + *(.data.*) + *(.data) + + . = ALIGN(4); + /* preinit data */ + PROVIDE_HIDDEN (__preinit_array_start = .); + KEEP(*(.preinit_array)) + PROVIDE_HIDDEN (__preinit_array_end = .); + + . = ALIGN(4); + /* init data */ + PROVIDE_HIDDEN (__init_array_start = .); + KEEP(*(SORT(.init_array.*))) + KEEP(*(.init_array)) + PROVIDE_HIDDEN (__init_array_end = .); + + + . = ALIGN(4); + /* finit data */ + PROVIDE_HIDDEN (__fini_array_start = .); + KEEP(*(SORT(.fini_array.*))) + KEEP(*(.fini_array)) + PROVIDE_HIDDEN (__fini_array_end = .); + + KEEP(*(.jcr*)) + + . = ALIGN(4); + + /* All data end */ + __data_end__ = .; + + } > RAM AT > FLASH + + . = .; + __dtcm_data_pre_location = LOADADDR(.data) + SIZEOF(.data); + + /* Initialized DTCM data. */ + /* Aligned to FCACHE2 for RA8. */ + .dtcm_data : ALIGN(16) + { + /* Start of DTCM Secure Trustzone region. */ + __tz_DTCM_S = ABSOLUTE(DTCM_START); + + /* Initialized DTCM data start */ + __dtcm_data_start = .; + + KEEP(*(.dtcm_data*)) + + /* Pad to eight byte alignment in case of ECC initialization. Fill zero. */ + . = ALIGN(8); + + /* Initialized DTCM data end */ + __dtcm_data_end = .; + } > DTCM AT > FLASH = 0x00 + + . = __dtcm_data_end; + /* Uninitialized DTCM data. */ + /* ALIGN appears on the left side of the colon because it is being used to assign the VMA directly, as opposed to a right side appearance which would control the LMA. */ + .dtcm_bss ALIGN(8) (NOLOAD) : + { + /* Uninitialized DTCM data start */ + __dtcm_bss_start = .; + + KEEP(*(.dtcm_bss*)) + + /* Pad to eight byte alignment in case of ECC initialization. No fill because of NOLOAD. */ + . = ALIGN(8); + + /* Uninitialized DTCM data end */ + __dtcm_bss_end = .; + + /* + * Start of the DTCM Non-Secure Trustzone region. + * DTCM_NS_START can be used to set a fixed address for non-secure DTCM in secure projects or flat projects. + */ + __tz_DTCM_N = DEFINED(DTCM_NS_START) ? ABSOLUTE(DTCM_NS_START) : ALIGN(__dtcm_bss_end, 8192); + } > DTCM + + /* Addresses exported for DTCM initialization. */ + __dtcm_data_init_start = LOADADDR(.dtcm_data); + __dtcm_data_init_end = LOADADDR(.dtcm_data) + SIZEOF(.dtcm_data); + + ASSERT(ORIGIN(DTCM) % 8 == 0, "DTCM memory region origin must be aligned to 8 bytes.") + ASSERT(LENGTH(DTCM) % 8 == 0, "DTCM memory region length must be a multiple of 8 bytes.") + ASSERT(LOADADDR(.dtcm_bss) == ADDR(.dtcm_bss), ".dtcm_bss has (VMA != LMA) but should be NOLOAD (VMA == LMA).") + ASSERT(LOADADDR(.dtcm_data) % 16 == 0, ".dtcm_data section must be aligned to 16 bytes.") + ASSERT(SIZEOF(.dtcm_data) % 8 == 0, ".dtcm_data section size must be a multiple of 8 bytes.") + ASSERT(LOADADDR(.dtcm_bss) % 8 == 0, ".dtcm_bss section must be aligned to 8 bytes.") + ASSERT(SIZEOF(.dtcm_bss) % 8 == 0, ".dtcm_bss section size must be a multiple of 8 bytes.") + ASSERT(__dtcm_bss_start == __dtcm_data_end, ".dtcm_bss section is not adjacent to .dtcm_data section.") + + /* Restore location counter. */ + /* If DTCM is not present, this will be the address stored in '.' before ALIGN was attempted. */ + /* If DTCM is present, this will be the absolute address that follows the DTCM ROM location. */ + . = (SIZEOF(.dtcm_data) > 0) ? __dtcm_data_init_end : __dtcm_data_pre_location; + + /* TrustZone Secure Gateway Stubs Section */ + + /* Store location counter for SPI non-retentive sections. */ + sgstubs_pre_location = .; + + /* Determine the secure gateway stubs address either by the provided linker variable or the next 1024-byte block. */ + SGSTUBS_LOC = (DEFINED(PROJECT_SECURE) && DEFINED(FLASH_NSC_START)) ? ABSOLUTE(FLASH_NSC_START) : ALIGN(1024); + .gnu.sgstubs SGSTUBS_LOC : ALIGN(1024) + { + __tz_FLASH_C = DEFINED(FLASH_NSC_START) ? ABSOLUTE(FLASH_NSC_START) : __RESERVE_NS_RAM ? ABSOLUTE(FLASH_START + FLASH_LENGTH) : ALIGN(1024); + _start_sg = .; + *(.gnu.sgstubs*) + . = ALIGN(32); + _end_sg = .; + } > FLASH + + __tz_FLASH_N = DEFINED(FLASH_NS_START) ? ABSOLUTE(FLASH_NS_START) : __RESERVE_NS_RAM ? ABSOLUTE(FLASH_START + FLASH_LENGTH) : FLASH_LENGTH < 32768 ? FLASH_LENGTH : ALIGN(32768); + FLASH_NS_IMAGE_START = DEFINED(FLASH_NS_IMAGE_START) ? FLASH_NS_IMAGE_START : __tz_FLASH_N; + + /* Note: There are no secure/non-secure boundaries for QSPI. These symbols are provided for the RA configuration tool. */ + __tz_QSPI_FLASH_S = ORIGIN(QSPI_FLASH); + + /* QSPI_FLASH section to be downloaded via debugger */ + .qspi_flash : + { + __qspi_flash_start__ = .; + KEEP(*(.qspi_flash*)) + KEEP(*(.code_in_qspi*)) + __qspi_flash_end__ = .; + } > QSPI_FLASH + __qspi_flash_code_size__ = __qspi_flash_end__ - __qspi_flash_start__; + + /* QSPI_FLASH non-retentive section, creates a copy in internal flash that can be copied to QSPI */ + __qspi_flash_code_addr__ = sgstubs_pre_location; + .qspi_non_retentive : AT(__qspi_flash_code_addr__) + { + __qspi_non_retentive_start__ = .; + KEEP(*(.qspi_non_retentive*)) + __qspi_non_retentive_end__ = .; + } > QSPI_FLASH + __qspi_non_retentive_size__ = __qspi_non_retentive_end__ - __qspi_non_retentive_start__; + + __qspi_region_max_size__ = 0x4000000; /* Must be the same as defined in MEMORY above */ + __qspi_region_start_address__ = __qspi_flash_start__; + __qspi_region_end_address__ = __qspi_flash_start__ + __qspi_region_max_size__; + + /* Note: There are no secure/non-secure boundaries for QSPI. These symbols are provided for the RA configuration tool. */ + __tz_QSPI_FLASH_N = __qspi_non_retentive_end__; + + /* Support for OctaRAM */ + .OSPI_DEVICE_0_NO_LOAD (NOLOAD): + { + . = ALIGN(4); + __ospi_device_0_start__ = .; + *(.ospi_device_0_no_load*) + . = ALIGN(4); + __ospi_device_0_end__ = .; + } > OSPI_DEVICE_0_RAM + + .OSPI_DEVICE_1_NO_LOAD (NOLOAD): + { + . = ALIGN(4); + __ospi_device_1_start__ = .; + *(.ospi_device_1_no_load*) + . = ALIGN(4); + __ospi_device_1_end__ = .; + } > OSPI_DEVICE_1_RAM + + /* Note: There are no secure/non-secure boundaries for QSPI. These symbols are provided for the RA configuration tool. */ + __tz_OSPI_DEVICE_0_S = ORIGIN(OSPI_DEVICE_0); + + /* OSPI_DEVICE_0 section to be downloaded via debugger */ + .OSPI_DEVICE_0 : + { + __ospi_device_0_start__ = .; + KEEP(*(.ospi_device_0*)) + KEEP(*(.code_in_ospi_device_0*)) + __ospi_device_0_end__ = .; + } > OSPI_DEVICE_0 + __ospi_device_0_code_size__ = __ospi_device_0_end__ - __ospi_device_0_start__; + + /* OSPI_DEVICE_0 non-retentive section, creates a copy in internal flash that can be copied to OSPI */ + __ospi_device_0_code_addr__ = sgstubs_pre_location + (SIZEOF(.qspi_non_retentive)); + .ospi_device_0_non_retentive : AT(__ospi_device_0_code_addr__) + { + __ospi_device_0_non_retentive_start__ = .; + KEEP(*(.ospi_device_0_non_retentive*)) + __ospi_device_0_non_retentive_end__ = .; + } > OSPI_DEVICE_0 + __ospi_device_0_non_retentive_size__ = __ospi_device_0_non_retentive_end__ - __ospi_device_0_non_retentive_start__; + + __ospi_device_0_region_max_size__ = 0x8000000; /* Must be the same as defined in MEMORY above */ + __ospi_device_0_region_start_address__ = __ospi_device_0_start__; + __ospi_device_0_region_end_address__ = __ospi_device_0_start__ + __ospi_device_0_region_max_size__; + + /* Note: There are no secure/non-secure boundaries for OSPI. These symbols are provided for the RA configuration tool. */ + __tz_OSPI_DEVICE_0_N = __ospi_device_0_non_retentive_end__; + + /* Note: There are no secure/non-secure boundaries for OSPI. These symbols are provided for the RA configuration tool. */ + __tz_OSPI_DEVICE_1_S = ORIGIN(OSPI_DEVICE_1); + + /* OSPI_DEVICE_1 section to be downloaded via debugger */ + .OSPI_DEVICE_1 : + { + __ospi_device_1_start__ = .; + KEEP(*(.ospi_device_1*)) + KEEP(*(.code_in_ospi_device_1*)) + __ospi_device_1_end__ = .; + } > OSPI_DEVICE_1 + __ospi_device_1_code_size__ = __ospi_device_1_end__ - __ospi_device_1_start__; + + /* OSPI_DEVICE_1 non-retentive section, creates a copy in internal flash that can be copied to OSPI */ + __ospi_device_1_code_addr__ = sgstubs_pre_location + (SIZEOF(.qspi_non_retentive) + SIZEOF(.ospi_device_0_non_retentive)); + .ospi_device_1_non_retentive : AT(__ospi_device_1_code_addr__) + { + __ospi_device_1_non_retentive_start__ = .; + KEEP(*(.ospi_device_1_non_retentive*)) + __ospi_device_1_non_retentive_end__ = .; + } > OSPI_DEVICE_1 + __ospi_device_1_non_retentive_size__ = __ospi_device_1_non_retentive_end__ - __ospi_device_1_non_retentive_start__; + + __ospi_device_1_region_max_size__ = 0x10000000; /* Must be the same as defined in MEMORY above */ + __ospi_device_1_region_start_address__ = __ospi_device_1_start__; + __ospi_device_1_region_end_address__ = __ospi_device_1_start__ + __ospi_device_1_region_max_size__; + + /* Note: There are no secure/non-secure boundaries for OSPI. These symbols are provided for the RA configuration tool. */ + __tz_OSPI_DEVICE_1_N = __ospi_device_1_non_retentive_end__; + + .noinit (NOLOAD): + { + . = ALIGN(4); + __noinit_start = .; + KEEP(*(.noinit*)) + . = ALIGN(8); + /* Place the FreeRTOS heap here so that the __HeapLimit calculation does not include the freertos heap. */ + KEEP(*(.heap.*)) + __noinit_end = .; + } > RAM + + .bss : + { + . = ALIGN(4); + __bss_start__ = .; + *(.bss*) + *(COMMON) + . = ALIGN(4); + __bss_end__ = .; + } > RAM + + .heap (NOLOAD): + { + . = ALIGN(8); + __HeapBase = .; + /* Place the STD heap here. */ + KEEP(*(.heap)) + __HeapLimit = .; + } > RAM + + /* Stacks are stored in this section. */ + .stack_dummy (NOLOAD): + { + . = ALIGN(8); + __StackLimit = .; + /* Main stack */ + KEEP(*(.stack)) + __StackTop = .; + /* Thread stacks */ + KEEP(*(.stack*)) + __StackTopAll = .; + } > RAM + + PROVIDE(__stack = __StackTopAll); + + /* This symbol represents the end of user allocated RAM. The RAM after this symbol can be used + at run time for things such as ThreadX memory pool allocations. */ + __RAM_segment_used_end__ = ALIGN(__StackTopAll , 4); + + /* RAM_NSC_START can be used to set a fixed address for non-secure callable RAM in secure projects. + * If it is not specified, the address for NSC RAM is the end of RAM aligned to a 1K boundary. + * In flat projects that require non-secure RAM, this variable is set to the start of non-secure RAM. */ + __tz_RAM_C = DEFINED(RAM_NSC_START) ? ABSOLUTE(RAM_NSC_START - RAM_NS_BUFFER_BLOCK_LENGTH) : __RESERVE_NS_RAM ? ABSOLUTE(RAM_NS_BUFFER_BLOCK_START) : ALIGN(__RAM_segment_used_end__, 1024); + + /* RAM_NS_START can be used to set a fixed address for non-secure RAM in secure projects or flat projects. + * RAM_NS_BUFFER_BLOCK_LENGTH is used to allocate non-secure buffers in a flat project. If it is not + * specified, the address for NSC RAM is the end of RAM aligned to an 8K boundary. + * In flat projects that require non-secure RAM, this variable is set to the start of non-secure RAM. */ + __tz_RAM_N = DEFINED(RAM_NS_START) ? ABSOLUTE(RAM_NS_START - RAM_NS_BUFFER_BLOCK_LENGTH) : __RESERVE_NS_RAM ? ABSOLUTE(RAM_NS_BUFFER_BLOCK_START) : ALIGN(__tz_RAM_C, 8192); + + /* Non-secure buffers must be in non-secure RAM. This is primarily used for the EDMAC in flat projects. + * The EDMAC is a non-secure bus master and can only access non-secure RAM. */ + .ns_buffer (NOLOAD): + { + /* Allocate RAM on a 32-byte boundary to help with placement of Ethernet buffers. */ + . = __RESERVE_NS_RAM ? ABSOLUTE(RAM_NS_BUFFER_START & 0xFFFFFFE0) : .; + + KEEP(*(.ns_buffer*)) + } > RAM + + /* Data flash. */ + .data_flash : + { + . = ORIGIN(DATA_FLASH); + __tz_DATA_FLASH_S = .; + __Data_Flash_Start = .; + KEEP(*(.data_flash*)) + __Data_Flash_End = .; + + __tz_DATA_FLASH_N = DEFINED(DATA_FLASH_NS_START) ? ABSOLUTE(DATA_FLASH_NS_START) : __RESERVE_NS_RAM ? ABSOLUTE(DATA_FLASH_START + DATA_FLASH_LENGTH) : ALIGN(1024); + } > DATA_FLASH + + /* Note: There are no secure/non-secure boundaries for SDRAM. These symbols are provided for the RA configuration tool. */ + __tz_SDRAM_S = ORIGIN(SDRAM); + + /* SDRAM */ + .sdram (NOLOAD): + { + __SDRAM_Start = .; + KEEP(*(.sdram*)) + KEEP(*(.frame*)) + __SDRAM_End = .; + } > SDRAM + + /* Note: There are no secure/non-secure boundaries for SDRAM. These symbols are provided for the RA configuration tool. */ + __tz_SDRAM_N = __SDRAM_End; + + /* Note: There are no secure/non-secure boundaries for ID_CODE. These symbols are provided for the RA configuration tool. */ + __tz_ID_CODE_S = ORIGIN(ID_CODE); + + /* Note: There are no secure/non-secure boundaries for ID_CODE. These symbols are provided for the RA configuration tool. + * Set this symbol to the same value as __tz_ID_CODE_S so the RA configuration tool does not split the ID_CODE + * memory region between TrustZone projects. */ + __tz_ID_CODE_N = __tz_ID_CODE_S; + + .id_code : + { + __ID_Code_Start = .; + KEEP(*(.id_code*)) + __ID_Code_End = .; + } > ID_CODE + + /* Symbol required for RA Configuration tool. */ + __tz_OPTION_SETTING_S = ORIGIN(OPTION_SETTING_OFS); + + .option_setting_ofs : + { + __OPTION_SETTING_OFS_Start = .; + KEEP(*(.option_setting_ofs0)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_OFS_Start + 0x04 : __OPTION_SETTING_OFS_Start; + KEEP(*(.option_setting_ofs2)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_OFS_Start + 0x10 : __OPTION_SETTING_OFS_Start; + KEEP(*(.option_setting_dualsel)) + __OPTION_SETTING_OFS_End = .; + } > OPTION_SETTING_OFS = 0xFF + + .option_setting_sas : + { + __OPTION_SETTING_SAS_Start = .; + KEEP(*(.option_setting_sas)) + __OPTION_SETTING_SAS_End = .; + } > OPTION_SETTING_SAS = 0xFF + + /* Symbol required for RA Configuration tool. */ + __tz_OPTION_SETTING_N = ABSOLUTE(OPTION_SETTING_START_NS); + + .option_setting_ns : + { + __OPTION_SETTING_NS_Start = .; + KEEP(*(.option_setting_ofs1)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x04 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_ofs3)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x10 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_banksel)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x40 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_bps0)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x44 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_bps1)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x48 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_bps2)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x4C : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_bps3)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x60 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_pbps0)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x64 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_pbps1)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x68 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_pbps2)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x6C : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_pbps3)) + __OPTION_SETTING_NS_End = .; + } > OPTION_SETTING = 0xFF + + /* Symbol required for RA Configuration tool. */ + __tz_OPTION_SETTING_S_S = ORIGIN(OPTION_SETTING_S); + + .option_setting_s : + { + __OPTION_SETTING_S_Start = .; + KEEP(*(.option_setting_ofs1_sec)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x04 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_ofs3_sec)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x10 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_banksel_sec)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x40 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sec0)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x44 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sec1)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x48 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sec2)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x4C : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sec3)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x60 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_pbps_sec0)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x64 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_pbps_sec1)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x68 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_pbps_sec2)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x6C : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_pbps_sec3)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x80 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_ofs1_sel)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x84 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_ofs3_sel)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x90 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_banksel_sel)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0xC0 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sel0)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0xC4 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sel1)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0xC8 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sel2)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0xCC : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sel3)) + __OPTION_SETTING_S_End = .; + } > OPTION_SETTING_S = 0xFF + + /* Symbol required for RA Configuration tool. */ + __tz_OPTION_SETTING_S_N = __OPTION_SETTING_S_End; +} diff --git a/hw/bsp/ra/boards/ra4m1_ek/script/memory_regions.ld b/hw/bsp/ra/boards/ra4m1_ek/script/memory_regions.ld new file mode 100644 index 000000000..2d6992fed --- /dev/null +++ b/hw/bsp/ra/boards/ra4m1_ek/script/memory_regions.ld @@ -0,0 +1,22 @@ + + /* generated memory regions file - do not edit */ + RAM_START = 0x20000000; + RAM_LENGTH = 0x8000; + FLASH_START = 0x00000000; + FLASH_LENGTH = 0x40000; + DATA_FLASH_START = 0x40100000; + DATA_FLASH_LENGTH = 0x2000; + OPTION_SETTING_START = 0x00000000; + OPTION_SETTING_LENGTH = 0x0; + OPTION_SETTING_S_START = 0x80000000; + OPTION_SETTING_S_LENGTH = 0x0; + ID_CODE_START = 0x01010018; + ID_CODE_LENGTH = 0x20; + SDRAM_START = 0x80010000; + SDRAM_LENGTH = 0x0; + QSPI_FLASH_START = 0x60000000; + QSPI_FLASH_LENGTH = 0x0; + OSPI_DEVICE_0_START = 0x80020000; + OSPI_DEVICE_0_LENGTH = 0x0; + OSPI_DEVICE_1_START = 0x80030000; + OSPI_DEVICE_1_LENGTH = 0x0; diff --git a/hw/bsp/ra/boards/ra4m1_ek/smart_configurator/configuration.xml b/hw/bsp/ra/boards/ra4m1_ek/smart_configurator/configuration.xml new file mode 100644 index 000000000..2ca7fe595 --- /dev/null +++ b/hw/bsp/ra/boards/ra4m1_ek/smart_configurator/configuration.xml @@ -0,0 +1,271 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Simple application that blinks an LED. No RTOS included. + Renesas.RA_baremetal_blinky.5.6.0.pack + + + Board Support Package Common Files + Renesas.RA.5.6.0.pack + + + I/O Port + Renesas.RA.5.6.0.pack + + + Arm CMSIS Version 6 - Core (M) + Arm.CMSIS6.6.1.0+fsp.5.6.0.pack + + + RA4M1-EK Board Support Files + Renesas.RA_board_ra4m1_ek.5.6.0.pack + + + Board support package for R7FA4M1AB3CFP + Renesas.RA_mcu_ra4m1.5.6.0.pack + + + Board support package for RA4M1 + Renesas.RA_mcu_ra4m1.5.6.0.pack + + + Board support package for RA4M1 - FSP Data + Renesas.RA_mcu_ra4m1.5.6.0.pack + + + Board support package for RA4M1 - Events + Renesas.RA_mcu_ra4m1.5.6.0.pack + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/hw/bsp/ra/boards/ra4m3_ek/board.cmake b/hw/bsp/ra/boards/ra4m3_ek/board.cmake index dfd5fc95a..b413abc36 100644 --- a/hw/bsp/ra/boards/ra4m3_ek/board.cmake +++ b/hw/bsp/ra/boards/ra4m3_ek/board.cmake @@ -1,4 +1,4 @@ -set(CMAKE_SYSTEM_PROCESSOR cortex-m33 CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU cortex-m33 CACHE INTERNAL "System Processor") set(MCU_VARIANT ra4m3) set(JLINK_DEVICE R7FA4M3AF) diff --git a/hw/bsp/ra/boards/ra4m3_ek/board.h b/hw/bsp/ra/boards/ra4m3_ek/board.h index 9dd2545a0..8b277f6f0 100644 --- a/hw/bsp/ra/boards/ra4m3_ek/board.h +++ b/hw/bsp/ra/boards/ra4m3_ek/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: RA4M3 EK + url: https://www.renesas.com/en/products/microcontrollers-microprocessors/ra-cortex-m-mcus/ek-ra4m3-evaluation-kit-ra4m3-mcu-group +*/ + #ifndef _BOARD_H_ #define _BOARD_H_ diff --git a/hw/bsp/ra/boards/ra4m3_ek/fsp_cfg/bsp/bsp_cfg.h b/hw/bsp/ra/boards/ra4m3_ek/fsp_cfg/bsp/bsp_cfg.h deleted file mode 100644 index 862ec25b7..000000000 --- a/hw/bsp/ra/boards/ra4m3_ek/fsp_cfg/bsp/bsp_cfg.h +++ /dev/null @@ -1,63 +0,0 @@ -/* generated configuration header file - do not edit */ -#ifndef BSP_CFG_H_ -#define BSP_CFG_H_ -#ifdef __cplusplus -extern "C" { -#endif - -#include "bsp_clock_cfg.h" -#include "bsp_mcu_family_cfg.h" -#include "board_cfg.h" - -#define RA_NOT_DEFINED 0 -#ifndef BSP_CFG_RTOS -#if (RA_NOT_DEFINED) != (RA_NOT_DEFINED) -#define BSP_CFG_RTOS (2) -#elif (RA_NOT_DEFINED) != (RA_NOT_DEFINED) -#define BSP_CFG_RTOS (1) -#else -#define BSP_CFG_RTOS (0) -#endif -#endif -#ifndef BSP_CFG_RTC_USED -#define BSP_CFG_RTC_USED (RA_NOT_DEFINED) -#endif -#undef RA_NOT_DEFINED -#if defined(_RA_BOOT_IMAGE) -#define BSP_CFG_BOOT_IMAGE (1) -#endif -#define BSP_CFG_MCU_VCC_MV (3300) -#define BSP_CFG_STACK_MAIN_BYTES (0x800) -#define BSP_CFG_HEAP_BYTES (0x800) -#define BSP_CFG_PARAM_CHECKING_ENABLE (1) -#define BSP_CFG_ASSERT (0) -#define BSP_CFG_ERROR_LOG (0) - -#define BSP_CFG_PFS_PROTECT ((1)) - -#define BSP_CFG_C_RUNTIME_INIT ((1)) -#define BSP_CFG_EARLY_INIT ((0)) - -#define BSP_CFG_STARTUP_CLOCK_REG_NOT_RESET ((0)) - -#ifndef BSP_CLOCK_CFG_MAIN_OSC_POPULATED -#define BSP_CLOCK_CFG_MAIN_OSC_POPULATED (1) -#endif - -#ifndef BSP_CLOCK_CFG_MAIN_OSC_CLOCK_SOURCE -#define BSP_CLOCK_CFG_MAIN_OSC_CLOCK_SOURCE (0) -#endif -#ifndef BSP_CLOCK_CFG_SUBCLOCK_DRIVE -#define BSP_CLOCK_CFG_SUBCLOCK_DRIVE (0) -#endif -#ifndef BSP_CLOCK_CFG_SUBCLOCK_POPULATED -#define BSP_CLOCK_CFG_SUBCLOCK_POPULATED (1) -#endif -#ifndef BSP_CLOCK_CFG_SUBCLOCK_STABILIZATION_MS -#define BSP_CLOCK_CFG_SUBCLOCK_STABILIZATION_MS 1000 -#endif - -#ifdef __cplusplus -} -#endif -#endif /* BSP_CFG_H_ */ diff --git a/hw/bsp/ra/boards/ra4m3_ek/fsp_cfg/bsp/bsp_mcu_device_pn_cfg.h b/hw/bsp/ra/boards/ra4m3_ek/fsp_cfg/bsp/bsp_mcu_device_pn_cfg.h deleted file mode 100644 index 1a0bc02e2..000000000 --- a/hw/bsp/ra/boards/ra4m3_ek/fsp_cfg/bsp/bsp_mcu_device_pn_cfg.h +++ /dev/null @@ -1,11 +0,0 @@ -/* generated configuration header file - do not edit */ -#ifndef BSP_MCU_DEVICE_PN_CFG_H_ -#define BSP_MCU_DEVICE_PN_CFG_H_ -#define BSP_MCU_R7FA4M3AF3CFB -#define BSP_MCU_FEATURE_SET ('A') -#define BSP_ROM_SIZE_BYTES (1048576) -#define BSP_RAM_SIZE_BYTES (131072) -#define BSP_DATA_FLASH_SIZE_BYTES (8192) -#define BSP_PACKAGE_LQFP -#define BSP_PACKAGE_PINS (144) -#endif /* BSP_MCU_DEVICE_PN_CFG_H_ */ diff --git a/hw/bsp/ra/boards/ra4m3_ek/ra_cfg/fsp_cfg/bsp/bsp_cfg.h b/hw/bsp/ra/boards/ra4m3_ek/ra_cfg/fsp_cfg/bsp/bsp_cfg.h new file mode 100644 index 000000000..96087fa0d --- /dev/null +++ b/hw/bsp/ra/boards/ra4m3_ek/ra_cfg/fsp_cfg/bsp/bsp_cfg.h @@ -0,0 +1,62 @@ +/* generated configuration header file - do not edit */ +#ifndef BSP_CFG_H_ +#define BSP_CFG_H_ +#ifdef __cplusplus + extern "C" { + #endif + + #include "bsp_clock_cfg.h" + #include "bsp_mcu_family_cfg.h" + #include "board_cfg.h" + #define RA_NOT_DEFINED 0 + #ifndef BSP_CFG_RTOS + #if (RA_NOT_DEFINED) != (RA_NOT_DEFINED) + #define BSP_CFG_RTOS (2) + #elif (RA_NOT_DEFINED) != (RA_NOT_DEFINED) + #define BSP_CFG_RTOS (1) + #else + #define BSP_CFG_RTOS (0) + #endif + #endif + #ifndef BSP_CFG_RTC_USED + #define BSP_CFG_RTC_USED (RA_NOT_DEFINED) + #endif + #undef RA_NOT_DEFINED + #if defined(_RA_BOOT_IMAGE) + #define BSP_CFG_BOOT_IMAGE (1) + #endif + #define BSP_CFG_MCU_VCC_MV (3300) + #define BSP_CFG_STACK_MAIN_BYTES (0x800) + #define BSP_CFG_HEAP_BYTES (0x800) + #define BSP_CFG_PARAM_CHECKING_ENABLE (0) + #define BSP_CFG_ASSERT (0) + #define BSP_CFG_ERROR_LOG (0) + + #define BSP_CFG_PFS_PROTECT ((1)) + + #define BSP_CFG_C_RUNTIME_INIT ((1)) + #define BSP_CFG_EARLY_INIT ((0)) + + #define BSP_CFG_STARTUP_CLOCK_REG_NOT_RESET ((0)) + + #ifndef BSP_CLOCK_CFG_MAIN_OSC_POPULATED + #define BSP_CLOCK_CFG_MAIN_OSC_POPULATED (1) + #endif + + #ifndef BSP_CLOCK_CFG_MAIN_OSC_CLOCK_SOURCE + #define BSP_CLOCK_CFG_MAIN_OSC_CLOCK_SOURCE (0) + #endif + #ifndef BSP_CLOCK_CFG_SUBCLOCK_DRIVE + #define BSP_CLOCK_CFG_SUBCLOCK_DRIVE (0) + #endif + #ifndef BSP_CLOCK_CFG_SUBCLOCK_POPULATED + #define BSP_CLOCK_CFG_SUBCLOCK_POPULATED (1) + #endif + #ifndef BSP_CLOCK_CFG_SUBCLOCK_STABILIZATION_MS + #define BSP_CLOCK_CFG_SUBCLOCK_STABILIZATION_MS 1000 + #endif + + #ifdef __cplusplus + } + #endif +#endif /* BSP_CFG_H_ */ diff --git a/hw/bsp/ra/boards/ra4m3_ek/fsp_cfg/bsp/bsp_mcu_device_cfg.h b/hw/bsp/ra/boards/ra4m3_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_device_cfg.h similarity index 100% rename from hw/bsp/ra/boards/ra4m3_ek/fsp_cfg/bsp/bsp_mcu_device_cfg.h rename to hw/bsp/ra/boards/ra4m3_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_device_cfg.h diff --git a/hw/bsp/ra/boards/ra4m3_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_device_pn_cfg.h b/hw/bsp/ra/boards/ra4m3_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_device_pn_cfg.h new file mode 100644 index 000000000..1aaa4be0a --- /dev/null +++ b/hw/bsp/ra/boards/ra4m3_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_device_pn_cfg.h @@ -0,0 +1,11 @@ +/* generated configuration header file - do not edit */ +#ifndef BSP_MCU_DEVICE_PN_CFG_H_ +#define BSP_MCU_DEVICE_PN_CFG_H_ +#define BSP_MCU_R7FA4M3AF3CFB + #define BSP_MCU_FEATURE_SET ('A') + #define BSP_ROM_SIZE_BYTES (1048576) + #define BSP_RAM_SIZE_BYTES (131072) + #define BSP_DATA_FLASH_SIZE_BYTES (8192) + #define BSP_PACKAGE_LQFP + #define BSP_PACKAGE_PINS (144) +#endif /* BSP_MCU_DEVICE_PN_CFG_H_ */ diff --git a/hw/bsp/ra/boards/portenta_c33/fsp_cfg/bsp/bsp_mcu_family_cfg.h b/hw/bsp/ra/boards/ra4m3_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_family_cfg.h similarity index 57% rename from hw/bsp/ra/boards/portenta_c33/fsp_cfg/bsp/bsp_mcu_family_cfg.h rename to hw/bsp/ra/boards/ra4m3_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_family_cfg.h index d5428540f..cb9429057 100644 --- a/hw/bsp/ra/boards/portenta_c33/fsp_cfg/bsp/bsp_mcu_family_cfg.h +++ b/hw/bsp/ra/boards/ra4m3_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_family_cfg.h @@ -5,80 +5,80 @@ extern "C" { #endif -#include "bsp_mcu_device_pn_cfg.h" -#include "bsp_mcu_device_cfg.h" -#include "../../../ra/fsp/src/bsp/mcu/ra6m5/bsp_mcu_info.h" -#include "bsp_clock_cfg.h" + #include "bsp_mcu_device_pn_cfg.h" + #include "bsp_mcu_device_cfg.h" + #include "../../../ra/fsp/src/bsp/mcu/ra4m3/bsp_mcu_info.h" + #include "bsp_clock_cfg.h" + #define BSP_MCU_GROUP_RA4M3 (1) + #define BSP_LOCO_HZ (32768) + #define BSP_MOCO_HZ (8000000) + #define BSP_SUB_CLOCK_HZ (32768) + #if BSP_CFG_HOCO_FREQUENCY == 0 + #define BSP_HOCO_HZ (16000000) + #elif BSP_CFG_HOCO_FREQUENCY == 1 + #define BSP_HOCO_HZ (18000000) + #elif BSP_CFG_HOCO_FREQUENCY == 2 + #define BSP_HOCO_HZ (20000000) + #else + #error "Invalid HOCO frequency chosen (BSP_CFG_HOCO_FREQUENCY) in bsp_clock_cfg.h" + #endif -#define BSP_MCU_GROUP_RA6M5 (1) -#define BSP_LOCO_HZ (32768) -#define BSP_MOCO_HZ (8000000) -#define BSP_SUB_CLOCK_HZ (32768) -#if BSP_CFG_HOCO_FREQUENCY == 0 -#define BSP_HOCO_HZ (16000000) -#elif BSP_CFG_HOCO_FREQUENCY == 1 - #define BSP_HOCO_HZ (18000000) -#elif BSP_CFG_HOCO_FREQUENCY == 2 - #define BSP_HOCO_HZ (20000000) -#else - #error "Invalid HOCO frequency chosen (BSP_CFG_HOCO_FREQUENCY) in bsp_clock_cfg.h" -#endif + #define BSP_CFG_FLL_ENABLE (0) -#define BSP_CFG_FLL_ENABLE (0) + #define BSP_CORTEX_VECTOR_TABLE_ENTRIES (16U) + #define BSP_VECTOR_TABLE_MAX_ENTRIES (112U) + #define BSP_CFG_INLINE_IRQ_FUNCTIONS (1) -#define BSP_CORTEX_VECTOR_TABLE_ENTRIES (16U) -#define BSP_VECTOR_TABLE_MAX_ENTRIES (112U) - -#if defined(_RA_TZ_SECURE) + #if defined(_RA_TZ_SECURE) #define BSP_TZ_SECURE_BUILD (1) #define BSP_TZ_NONSECURE_BUILD (0) #elif defined(_RA_TZ_NONSECURE) #define BSP_TZ_SECURE_BUILD (0) #define BSP_TZ_NONSECURE_BUILD (1) #else -#define BSP_TZ_SECURE_BUILD (0) -#define BSP_TZ_NONSECURE_BUILD (0) -#endif + #define BSP_TZ_SECURE_BUILD (0) + #define BSP_TZ_NONSECURE_BUILD (0) + #endif -/* TrustZone Settings */ -#define BSP_TZ_CFG_INIT_SECURE_ONLY (BSP_CFG_CLOCKS_SECURE || (!BSP_CFG_CLOCKS_OVERRIDE)) -#define BSP_TZ_CFG_SKIP_INIT (BSP_TZ_NONSECURE_BUILD && BSP_TZ_CFG_INIT_SECURE_ONLY) -#define BSP_TZ_CFG_EXCEPTION_RESPONSE (0) + /* TrustZone Settings */ + #define BSP_TZ_CFG_INIT_SECURE_ONLY (BSP_CFG_CLOCKS_SECURE || (!BSP_CFG_CLOCKS_OVERRIDE)) + #define BSP_TZ_CFG_SKIP_INIT (BSP_TZ_NONSECURE_BUILD && BSP_TZ_CFG_INIT_SECURE_ONLY) + #define BSP_TZ_CFG_EXCEPTION_RESPONSE (0) -/* CMSIS TrustZone Settings */ -#define SCB_CSR_AIRCR_INIT (1) -#define SCB_AIRCR_BFHFNMINS_VAL (0) -#define SCB_AIRCR_SYSRESETREQS_VAL (1) -#define SCB_AIRCR_PRIS_VAL (0) -#define TZ_FPU_NS_USAGE (1) + /* CMSIS TrustZone Settings */ + #define SCB_CSR_AIRCR_INIT (1) + #define SCB_AIRCR_BFHFNMINS_VAL (0) + #define SCB_AIRCR_SYSRESETREQS_VAL (1) + #define SCB_AIRCR_PRIS_VAL (0) + #define TZ_FPU_NS_USAGE (1) #ifndef SCB_NSACR_CP10_11_VAL -#define SCB_NSACR_CP10_11_VAL (3U) + #define SCB_NSACR_CP10_11_VAL (3U) #endif #ifndef FPU_FPCCR_TS_VAL -#define FPU_FPCCR_TS_VAL (1U) + #define FPU_FPCCR_TS_VAL (1U) #endif -#define FPU_FPCCR_CLRONRETS_VAL (1) + #define FPU_FPCCR_CLRONRETS_VAL (1) #ifndef FPU_FPCCR_CLRONRET_VAL -#define FPU_FPCCR_CLRONRET_VAL (1) + #define FPU_FPCCR_CLRONRET_VAL (1) #endif -/* The C-Cache line size that is configured during startup. */ + /* The C-Cache line size that is configured during startup. */ #ifndef BSP_CFG_C_CACHE_LINE_SIZE -#define BSP_CFG_C_CACHE_LINE_SIZE (1U) + #define BSP_CFG_C_CACHE_LINE_SIZE (1U) #endif -/* Type 1 Peripheral Security Attribution */ + /* Type 1 Peripheral Security Attribution */ -/* Peripheral Security Attribution Register (PSAR) Settings */ + /* Peripheral Security Attribution Register (PSAR) Settings */ #ifndef BSP_TZ_CFG_PSARB #define BSP_TZ_CFG_PSARB (\ (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 1) /* CAN1 */ | \ (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 2) /* CAN0 */ | \ (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 8) /* IIC1 */ | \ (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 9) /* IIC0 */ | \ - (((1 > 0) ? 0U : 1U) << 11) /* USBFS */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 11) /* USBFS */ | \ (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 18) /* SPI1 */ | \ (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 19) /* SPI0 */ | \ (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 22) /* SCI9 */ | \ @@ -146,19 +146,19 @@ extern "C" { 0xfffffffc) /* Unused */ #endif -/* Type 2 Peripheral Security Attribution */ + /* Type 2 Peripheral Security Attribution */ -/* Security attribution for Cache registers. */ + /* Security attribution for Cache registers. */ #ifndef BSP_TZ_CFG_CSAR #define BSP_TZ_CFG_CSAR (0xFFFFFFFFU) #endif -/* Security attribution for RSTSRn registers. */ + /* Security attribution for RSTSRn registers. */ #ifndef BSP_TZ_CFG_RSTSAR #define BSP_TZ_CFG_RSTSAR (0xFFFFFFFFU) #endif -/* Security attribution for registers of LVD channels. */ + /* Security attribution for registers of LVD channels. */ #ifndef BSP_TZ_CFG_LVDSAR #define BSP_TZ_CFG_LVDSAR (\ (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 0) | /* LVD Channel 1 */ \ @@ -166,16 +166,16 @@ extern "C" { 0xFFFFFFFCU) #endif -/* Security attribution for LPM registers. */ + /* Security attribution for LPM registers. */ #ifndef BSP_TZ_CFG_LPMSAR #define BSP_TZ_CFG_LPMSAR ((RA_NOT_DEFINED > 0) ? 0xFFFFFCEAU : 0xFFFFFFFFU) #endif -/* Deep Standby Interrupt Factor Security Attribution Register. */ + /* Deep Standby Interrupt Factor Security Attribution Register. */ #ifndef BSP_TZ_CFG_DPFSAR #define BSP_TZ_CFG_DPFSAR ((RA_NOT_DEFINED > 0) ? 0xF2E00000U : 0xFFFFFFFFU) #endif -/* Security attribution for CGC registers. */ + /* Security attribution for CGC registers. */ #ifndef BSP_TZ_CFG_CGFSAR #if BSP_CFG_CLOCKS_SECURE /* Protect all CGC registers from Non-secure write access. */ @@ -186,12 +186,12 @@ extern "C" { #endif #endif -/* Security attribution for Battery Backup registers. */ + /* Security attribution for Battery Backup registers. */ #ifndef BSP_TZ_CFG_BBFSAR #define BSP_TZ_CFG_BBFSAR (0x00FFFFFF) #endif -/* Security attribution for registers for IRQ channels. */ + /* Security attribution for registers for IRQ channels. */ #ifndef BSP_TZ_CFG_ICUSARA #define BSP_TZ_CFG_ICUSARA (\ (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 0U) /* External IRQ0 */ | \ @@ -213,12 +213,12 @@ extern "C" { 0xFFFF0000U) #endif -/* Security attribution for NMI registers. */ + /* Security attribution for NMI registers. */ #ifndef BSP_TZ_CFG_ICUSARB #define BSP_TZ_CFG_ICUSARB (0 | 0xFFFFFFFEU) /* Should match AIRCR.BFHFNMINS. */ #endif -/* Security attribution for registers for DMAC channels */ + /* Security attribution for registers for DMAC channels */ #ifndef BSP_TZ_CFG_ICUSARC #define BSP_TZ_CFG_ICUSARC (\ (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 0U) /* DMAC Channel 0 */ | \ @@ -232,29 +232,29 @@ extern "C" { 0xFFFFFF00U) #endif -/* Security attribution registers for SELSR0. */ + /* Security attribution registers for SELSR0. */ #ifndef BSP_TZ_CFG_ICUSARD #define BSP_TZ_CFG_ICUSARD ((RA_NOT_DEFINED > 0) ? 0xFFFFFFFEU : 0xFFFFFFFFU) #endif -/* Security attribution registers for WUPEN0. */ + /* Security attribution registers for WUPEN0. */ #ifndef BSP_TZ_CFG_ICUSARE #define BSP_TZ_CFG_ICUSARE ((RA_NOT_DEFINED > 0) ? 0x04F2FFFFU : 0xFFFFFFFFU) #endif -/* Security attribution registers for WUPEN1. */ + /* Security attribution registers for WUPEN1. */ #ifndef BSP_TZ_CFG_ICUSARF #define BSP_TZ_CFG_ICUSARF ((RA_NOT_DEFINED > 0) ? 0xFFFFFFF8U : 0xFFFFFFFFU) #endif -/* Set DTCSTSAR if the Secure program uses the DTC. */ + /* Set DTCSTSAR if the Secure program uses the DTC. */ #if RA_NOT_DEFINED == RA_NOT_DEFINED -#define BSP_TZ_CFG_DTC_USED (0U) + #define BSP_TZ_CFG_DTC_USED (0U) #else #define BSP_TZ_CFG_DTC_USED (1U) #endif -/* Security attribution of FLWT and FCKMHZ registers. */ + /* Security attribution of FLWT and FCKMHZ registers. */ #ifndef BSP_TZ_CFG_FSAR /* If the CGC registers are only accessible in Secure mode, than there is no * reason for nonsecure applications to access FLWT and FCKMHZ. */ @@ -267,118 +267,119 @@ extern "C" { #endif #endif -/* Security attribution for SRAM registers. */ + /* Security attribution for SRAM registers. */ #ifndef BSP_TZ_CFG_SRAMSAR /* If the CGC registers are only accessible in Secure mode, than there is no reason for Non Secure applications to access * SRAM0WTEN and therefore there is no reason to access PRCR2. */ -#define BSP_TZ_CFG_SRAMSAR (\ + #define BSP_TZ_CFG_SRAMSAR (\ 1 | \ ((BSP_CFG_CLOCKS_SECURE == 0) ? (1U << 1U) : 0U) | \ 4 | \ 0xFFFFFFF8U) #endif -/* Security attribution for Standby RAM registers. */ + /* Security attribution for Standby RAM registers. */ #ifndef BSP_TZ_CFG_STBRAMSAR -#define BSP_TZ_CFG_STBRAMSAR (0 | 0xFFFFFFF0U) + #define BSP_TZ_CFG_STBRAMSAR (0 | 0xFFFFFFF0U) #endif -/* Security attribution for the DMAC Bus Master MPU settings. */ + /* Security attribution for the DMAC Bus Master MPU settings. */ #ifndef BSP_TZ_CFG_MMPUSARA -/* The DMAC Bus Master MPU settings should align with the DMAC channel settings. */ -#define BSP_TZ_CFG_MMPUSARA (BSP_TZ_CFG_ICUSARC) + /* The DMAC Bus Master MPU settings should align with the DMAC channel settings. */ + #define BSP_TZ_CFG_MMPUSARA (BSP_TZ_CFG_ICUSARC) #endif -/* Security Attribution Register A for BUS Control registers. */ + /* Security Attribution Register A for BUS Control registers. */ #ifndef BSP_TZ_CFG_BUSSARA -#define BSP_TZ_CFG_BUSSARA (0xFFFFFFFFU) + #define BSP_TZ_CFG_BUSSARA (0xFFFFFFFFU) #endif -/* Security Attribution Register B for BUS Control registers. */ + /* Security Attribution Register B for BUS Control registers. */ #ifndef BSP_TZ_CFG_BUSSARB -#define BSP_TZ_CFG_BUSSARB (0xFFFFFFFFU) + #define BSP_TZ_CFG_BUSSARB (0xFFFFFFFFU) #endif -/* Enable Uninitialized Non-Secure Application Fallback. */ + /* Enable Uninitialized Non-Secure Application Fallback. */ #ifndef BSP_TZ_CFG_NON_SECURE_APPLICATION_FALLBACK -#define BSP_TZ_CFG_NON_SECURE_APPLICATION_FALLBACK (1U) + #define BSP_TZ_CFG_NON_SECURE_APPLICATION_FALLBACK (1U) #endif -#define OFS_SEQ1 0xA001A001 | (1 << 1) | (3 << 2) -#define OFS_SEQ2 (15 << 4) | (3 << 8) | (3 << 10) -#define OFS_SEQ3 (1 << 12) | (1 << 14) | (1 << 17) -#define OFS_SEQ4 (3 << 18) |(15 << 20) | (3 << 24) | (3 << 26) -#define OFS_SEQ5 (1 << 28) | (1 << 30) -#define BSP_CFG_ROM_REG_OFS0 (OFS_SEQ1 | OFS_SEQ2 | OFS_SEQ3 | OFS_SEQ4 | OFS_SEQ5) -/* Option Function Select Register 1 Security Attribution */ + #define OFS_SEQ1 0xA001A001 | (1 << 1) | (3 << 2) + #define OFS_SEQ2 (15 << 4) | (3 << 8) | (3 << 10) + #define OFS_SEQ3 (1 << 12) | (1 << 14) | (1 << 17) + #define OFS_SEQ4 (3 << 18) |(15 << 20) | (3 << 24) | (3 << 26) + #define OFS_SEQ5 (1 << 28) | (1 << 30) + #define BSP_CFG_ROM_REG_OFS0 (OFS_SEQ1 | OFS_SEQ2 | OFS_SEQ3 | OFS_SEQ4 | OFS_SEQ5) + + /* Option Function Select Register 1 Security Attribution */ #ifndef BSP_CFG_ROM_REG_OFS1_SEL #if defined(_RA_TZ_SECURE) || defined(_RA_TZ_NONSECURE) - #define BSP_CFG_ROM_REG_OFS1_SEL (0xFFFFF8F8U | ((BSP_CFG_CLOCKS_SECURE == 0) ? 0x700U : 0U) | ((RA_NOT_DEFINED > 0) ? 0U : 0x7U)) + #define BSP_CFG_ROM_REG_OFS1_SEL (0xFFFFF8F8U | ((0U << 0U)) | ((0U << 2U)) | ((BSP_CFG_CLOCKS_SECURE == 0) ? 0x700U : 0U)) #else -#define BSP_CFG_ROM_REG_OFS1_SEL (0xFFFFF8F8U) + #define BSP_CFG_ROM_REG_OFS1_SEL (0xFFFFF8F8U) #endif #endif -#define BSP_CFG_ROM_REG_OFS1 (0xFFFFFEF8 | (1 << 2) | (3) | (1 << 8)) + #define BSP_CFG_ROM_REG_OFS1 (0xFFFFFEF8 | (1 << 2) | (3) | (1 << 8)) -/* Used to create IELS values for the interrupt initialization table g_interrupt_event_link_select. */ -#define BSP_PRV_IELS_ENUM(vector) (ELC_ ## vector) + /* Used to create IELS values for the interrupt initialization table g_interrupt_event_link_select. */ + #define BSP_PRV_IELS_ENUM(vector) (ELC_ ## vector) -/* Dual Mode Select Register */ + /* Dual Mode Select Register */ #ifndef BSP_CFG_ROM_REG_DUALSEL -#define BSP_CFG_ROM_REG_DUALSEL (0xFFFFFFF8U | (0x7U)) + #define BSP_CFG_ROM_REG_DUALSEL (0xFFFFFFFFU) #endif -/* Block Protection Register 0 */ + /* Block Protection Register 0 */ #ifndef BSP_CFG_ROM_REG_BPS0 -#define BSP_CFG_ROM_REG_BPS0 (~( 0U)) + #define BSP_CFG_ROM_REG_BPS0 (~( 0U)) #endif -/* Block Protection Register 1 */ + /* Block Protection Register 1 */ #ifndef BSP_CFG_ROM_REG_BPS1 -#define BSP_CFG_ROM_REG_BPS1 (~( 0U)) + #define BSP_CFG_ROM_REG_BPS1 (~( 0U)) #endif -/* Block Protection Register 2 */ + /* Block Protection Register 2 */ #ifndef BSP_CFG_ROM_REG_BPS2 -#define BSP_CFG_ROM_REG_BPS2 (~( 0U)) + #define BSP_CFG_ROM_REG_BPS2 (0xFFFFFFFFU) #endif -/* Block Protection Register 3 */ + /* Block Protection Register 3 */ #ifndef BSP_CFG_ROM_REG_BPS3 -#define BSP_CFG_ROM_REG_BPS3 (0xFFFFFFFFU) + #define BSP_CFG_ROM_REG_BPS3 (0xFFFFFFFFU) #endif -/* Permanent Block Protection Register 0 */ + /* Permanent Block Protection Register 0 */ #ifndef BSP_CFG_ROM_REG_PBPS0 -#define BSP_CFG_ROM_REG_PBPS0 (~( 0U)) + #define BSP_CFG_ROM_REG_PBPS0 (~( 0U)) #endif -/* Permanent Block Protection Register 1 */ + /* Permanent Block Protection Register 1 */ #ifndef BSP_CFG_ROM_REG_PBPS1 -#define BSP_CFG_ROM_REG_PBPS1 (~( 0U)) + #define BSP_CFG_ROM_REG_PBPS1 (~( 0U)) #endif -/* Permanent Block Protection Register 2 */ + /* Permanent Block Protection Register 2 */ #ifndef BSP_CFG_ROM_REG_PBPS2 -#define BSP_CFG_ROM_REG_PBPS2 (~( 0U)) + #define BSP_CFG_ROM_REG_PBPS2 (0xFFFFFFFFU) #endif -/* Permanent Block Protection Register 3 */ + /* Permanent Block Protection Register 3 */ #ifndef BSP_CFG_ROM_REG_PBPS3 -#define BSP_CFG_ROM_REG_PBPS3 (0xFFFFFFFFU) + #define BSP_CFG_ROM_REG_PBPS3 (0xFFFFFFFFU) #endif -/* Security Attribution for Block Protection Register 0 (If any blocks are marked as protected in the secure application, then mark them as secure) */ + /* Security Attribution for Block Protection Register 0 (If any blocks are marked as protected in the secure application, then mark them as secure) */ #ifndef BSP_CFG_ROM_REG_BPS_SEL0 -#define BSP_CFG_ROM_REG_BPS_SEL0 (BSP_CFG_ROM_REG_BPS0 & BSP_CFG_ROM_REG_PBPS0) + #define BSP_CFG_ROM_REG_BPS_SEL0 (BSP_CFG_ROM_REG_BPS0 & BSP_CFG_ROM_REG_PBPS0) #endif -/* Security Attribution for Block Protection Register 1 (If any blocks are marked as protected in the secure application, then mark them as secure) */ + /* Security Attribution for Block Protection Register 1 (If any blocks are marked as protected in the secure application, then mark them as secure) */ #ifndef BSP_CFG_ROM_REG_BPS_SEL1 -#define BSP_CFG_ROM_REG_BPS_SEL1 (BSP_CFG_ROM_REG_BPS1 & BSP_CFG_ROM_REG_PBPS1) + #define BSP_CFG_ROM_REG_BPS_SEL1 (BSP_CFG_ROM_REG_BPS1 & BSP_CFG_ROM_REG_PBPS1) #endif -/* Security Attribution for Block Protection Register 2 (If any blocks are marked as protected in the secure application, then mark them as secure) */ + /* Security Attribution for Block Protection Register 2 (If any blocks are marked as protected in the secure application, then mark them as secure) */ #ifndef BSP_CFG_ROM_REG_BPS_SEL2 -#define BSP_CFG_ROM_REG_BPS_SEL2 (BSP_CFG_ROM_REG_BPS2 & BSP_CFG_ROM_REG_PBPS2) + #define BSP_CFG_ROM_REG_BPS_SEL2 (0xFFFFFFFFU) #endif -/* Security Attribution for Block Protection Register 3 (If any blocks are marked as protected in the secure application, then mark them as secure) */ + /* Security Attribution for Block Protection Register 3 (If any blocks are marked as protected in the secure application, then mark them as secure) */ #ifndef BSP_CFG_ROM_REG_BPS_SEL3 -#define BSP_CFG_ROM_REG_BPS_SEL3 (BSP_CFG_ROM_REG_BPS3 & BSP_CFG_ROM_REG_PBPS3) + #define BSP_CFG_ROM_REG_BPS_SEL3 (0xFFFFFFFFU) #endif #ifndef BSP_CLOCK_CFG_MAIN_OSC_WAIT -#define BSP_CLOCK_CFG_MAIN_OSC_WAIT (9) + #define BSP_CLOCK_CFG_MAIN_OSC_WAIT (9) #endif #ifdef __cplusplus diff --git a/hw/bsp/ra/boards/ra4m3_ek/ra_cfg/fsp_cfg/bsp/bsp_pin_cfg.h b/hw/bsp/ra/boards/ra4m3_ek/ra_cfg/fsp_cfg/bsp/bsp_pin_cfg.h new file mode 100644 index 000000000..8ed58a11b --- /dev/null +++ b/hw/bsp/ra/boards/ra4m3_ek/ra_cfg/fsp_cfg/bsp/bsp_pin_cfg.h @@ -0,0 +1,67 @@ +/* generated configuration header file - do not edit */ +#ifndef BSP_PIN_CFG_H_ +#define BSP_PIN_CFG_H_ +#include "r_ioport.h" + +/* Common macro for FSP header files. There is also a corresponding FSP_FOOTER macro at the end of this file. */ +FSP_HEADER + +#define ARDUINO_A0_MIKROBUS_AN (BSP_IO_PORT_00_PIN_00) +#define ARDUINO_A1 (BSP_IO_PORT_00_PIN_01) +#define ARDUINO_A2 (BSP_IO_PORT_00_PIN_03) +#define SW1 (BSP_IO_PORT_00_PIN_05) +#define SW2 (BSP_IO_PORT_00_PIN_06) +#define ARDUINO_A3 (BSP_IO_PORT_00_PIN_07) +#define PMOD1_INT (BSP_IO_PORT_00_PIN_08) +#define ARDUINO_A4 (BSP_IO_PORT_00_PIN_14) +#define ARDUINO_A5 (BSP_IO_PORT_00_PIN_15) +#define ARDUINO_RX_MIKROBUS_RX (BSP_IO_PORT_01_PIN_00) +#define ARDUINO_TX_MIKROBUS_TX (BSP_IO_PORT_01_PIN_01) +#define ARDUINO_D2 (BSP_IO_PORT_01_PIN_05) +#define ARDUINO_D3 (BSP_IO_PORT_01_PIN_11) +#define MIKROBUS_RST (BSP_IO_PORT_01_PIN_15) +#define ARDUINO_MISO_MIKROBUS_MISO_PMOD1_MISO (BSP_IO_PORT_02_PIN_02) +#define ARDUINO_MOSI_MIKROBUS_MOSI_PMOD1_MOSI (BSP_IO_PORT_02_PIN_03) +#define ARDUINO_CLK_MIKROBUS_CLK_PMOD1_CLK (BSP_IO_PORT_02_PIN_04) +#define ARDUINO_SS_MIKCRBUS_SS (BSP_IO_PORT_02_PIN_05) +#define PMOD1_SS1 (BSP_IO_PORT_02_PIN_06) +#define PMOD1_SS2 (BSP_IO_PORT_02_PIN_07) +#define PMOD1_SS3 (BSP_IO_PORT_03_PIN_02) +#define ARDUINO_D9 (BSP_IO_PORT_03_PIN_03) +#define ARDUINO_D7 (BSP_IO_PORT_03_PIN_04) +#define QSPI_CLK (BSP_IO_PORT_03_PIN_05) +#define QSPI_SSL (BSP_IO_PORT_03_PIN_06) +#define QSPI_IO0 (BSP_IO_PORT_03_PIN_07) +#define QSPI_IO1 (BSP_IO_PORT_03_PIN_08) +#define QSPI_IO2 (BSP_IO_PORT_03_PIN_09) +#define QSPI_IO3 (BSP_IO_PORT_03_PIN_10) +#define PMOD1_RST (BSP_IO_PORT_03_PIN_11) +#define LED3 (BSP_IO_PORT_04_PIN_00) +#define LED2 (BSP_IO_PORT_04_PIN_04) +#define USB_VBUS (BSP_IO_PORT_04_PIN_07) +#define ARDUINO_D6_MIKROBUS_PWM (BSP_IO_PORT_04_PIN_08) +#define MIKROBUS_INT (BSP_IO_PORT_04_PIN_09) +#define PMOD2_INT (BSP_IO_PORT_04_PIN_14) +#define LED1 (BSP_IO_PORT_04_PIN_15) +#define USB_VBUS_EN (BSP_IO_PORT_05_PIN_00) +#define USB_VBUS_OC (BSP_IO_PORT_05_PIN_01) +#define GROVE2_AN1 (BSP_IO_PORT_05_PIN_05) +#define GROVE2_AN2 (BSP_IO_PORT_05_PIN_06) +#define GROVE1_SDA_QWIIC_SDA (BSP_IO_PORT_05_PIN_11) +#define GROVE1_SCL_QWIIC_SCL (BSP_IO_PORT_05_PIN_12) +#define ARDUINO_SCL_MIKROBUS_SCL (BSP_IO_PORT_06_PIN_01) +#define ARDUINO_SDA_MIKROBUS_SDA (BSP_IO_PORT_06_PIN_02) +#define ARDUINO_D8 (BSP_IO_PORT_06_PIN_11) +#define ARDUINO_RST (BSP_IO_PORT_06_PIN_12) +#define PMOD2_RST (BSP_IO_PORT_07_PIN_08) +#define PMOD2_SS2 (BSP_IO_PORT_07_PIN_09) +#define PMOD2_SS3 (BSP_IO_PORT_07_PIN_10) +#define ARDUINO_D5 (BSP_IO_PORT_07_PIN_12) +#define ARDUINO_D4 (BSP_IO_PORT_07_PIN_13) +extern const ioport_cfg_t g_bsp_pin_cfg; /* RA4M3 EK */ + +void BSP_PinConfigSecurityInit(); + +/* Common macro for FSP header files. There is also a corresponding FSP_HEADER macro at the top of this file. */ +FSP_FOOTER +#endif /* BSP_PIN_CFG_H_ */ diff --git a/hw/bsp/ra/boards/ra4m3_ek/ra_cfg/fsp_cfg/r_ioport_cfg.h b/hw/bsp/ra/boards/ra4m3_ek/ra_cfg/fsp_cfg/r_ioport_cfg.h new file mode 100644 index 000000000..d2688bf5b --- /dev/null +++ b/hw/bsp/ra/boards/ra4m3_ek/ra_cfg/fsp_cfg/r_ioport_cfg.h @@ -0,0 +1,13 @@ +/* generated configuration header file - do not edit */ +#ifndef R_IOPORT_CFG_H_ +#define R_IOPORT_CFG_H_ +#ifdef __cplusplus +extern "C" { +#endif + +#define IOPORT_CFG_PARAM_CHECKING_ENABLE (BSP_CFG_PARAM_CHECKING_ENABLE) + +#ifdef __cplusplus +} +#endif +#endif /* R_IOPORT_CFG_H_ */ diff --git a/hw/bsp/ra/boards/ra4m3_ek/fsp_cfg/bsp_clock_cfg.h b/hw/bsp/ra/boards/ra4m3_ek/ra_gen/bsp_clock_cfg.h similarity index 82% rename from hw/bsp/ra/boards/ra4m3_ek/fsp_cfg/bsp_clock_cfg.h rename to hw/bsp/ra/boards/ra4m3_ek/ra_gen/bsp_clock_cfg.h index 80641945d..3eac2985e 100644 --- a/hw/bsp/ra/boards/ra4m3_ek/fsp_cfg/bsp_clock_cfg.h +++ b/hw/bsp/ra/boards/ra4m3_ek/ra_gen/bsp_clock_cfg.h @@ -7,10 +7,10 @@ #define BSP_CFG_HOCO_FREQUENCY (2) /* HOCO 20MHz */ #define BSP_CFG_PLL_SOURCE (BSP_CLOCKS_SOURCE_CLOCK_MAIN_OSC) /* PLL Src: XTAL */ #define BSP_CFG_PLL_DIV (BSP_CLOCKS_PLL_DIV_3) /* PLL Div /3 */ -#define BSP_CFG_PLL_MUL BSP_CLOCKS_PLL_MUL(24U,0U) /* PLL Mul x24.0 */ +#define BSP_CFG_PLL_MUL BSP_CLOCKS_PLL_MUL(25U,0U) /* PLL Mul x25.0 */ #define BSP_CFG_PLL2_SOURCE (BSP_CLOCKS_SOURCE_CLOCK_MAIN_OSC) /* PLL2 Src: XTAL */ -#define BSP_CFG_PLL2_DIV (BSP_CLOCKS_PLL_DIV_3) /* PLL2 Div /3 */ -#define BSP_CFG_PLL2_MUL BSP_CLOCKS_PLL_MUL(24U,0U) /* PLL2 Mul x24.0 */ +#define BSP_CFG_PLL2_DIV (BSP_CLOCKS_PLL_DIV_2) /* PLL2 Div /2 */ +#define BSP_CFG_PLL2_MUL BSP_CLOCKS_PLL_MUL(20U,0U) /* PLL2 Mul x20.0 */ #define BSP_CFG_CLOCK_SOURCE (BSP_CLOCKS_SOURCE_CLOCK_PLL) /* Clock Src: PLL */ #define BSP_CFG_CLKOUT_SOURCE (BSP_CLOCKS_CLOCK_DISABLED) /* CLKOUT Disabled */ #define BSP_CFG_UCK_SOURCE (BSP_CLOCKS_SOURCE_CLOCK_PLL2) /* UCLK Src: PLL2 */ @@ -21,5 +21,5 @@ #define BSP_CFG_PCLKD_DIV (BSP_CLOCKS_SYS_CLOCK_DIV_2) /* PCLKD Div /2 */ #define BSP_CFG_FCLK_DIV (BSP_CLOCKS_SYS_CLOCK_DIV_4) /* FCLK Div /4 */ #define BSP_CFG_CLKOUT_DIV (BSP_CLOCKS_SYS_CLOCK_DIV_1) /* CLKOUT Div /1 */ -#define BSP_CFG_UCK_DIV (BSP_CLOCKS_USB_CLOCK_DIV_4) /* UCLK Div /4 */ +#define BSP_CFG_UCK_DIV (BSP_CLOCKS_USB_CLOCK_DIV_5) /* UCLK Div /5 */ #endif /* BSP_CLOCK_CFG_H_ */ diff --git a/hw/bsp/ra/boards/ra4m3_ek/ra_gen/common_data.c b/hw/bsp/ra/boards/ra4m3_ek/ra_gen/common_data.c new file mode 100644 index 000000000..50036c0ad --- /dev/null +++ b/hw/bsp/ra/boards/ra4m3_ek/ra_gen/common_data.c @@ -0,0 +1,11 @@ +/* generated common source file - do not edit */ +#include "common_data.h" +ioport_instance_ctrl_t g_ioport_ctrl; +const ioport_instance_t g_ioport = + { + .p_api = &g_ioport_on_ioport, + .p_ctrl = &g_ioport_ctrl, + .p_cfg = &g_bsp_pin_cfg, + }; +void g_common_init(void) { +} diff --git a/hw/bsp/ra/boards/ra4m3_ek/ra_gen/common_data.h b/hw/bsp/ra/boards/ra4m3_ek/ra_gen/common_data.h new file mode 100644 index 000000000..6a08cbee0 --- /dev/null +++ b/hw/bsp/ra/boards/ra4m3_ek/ra_gen/common_data.h @@ -0,0 +1,20 @@ +/* generated common header file - do not edit */ +#ifndef COMMON_DATA_H_ +#define COMMON_DATA_H_ +#include +#include "bsp_api.h" +#include "r_ioport.h" +#include "bsp_pin_cfg.h" +FSP_HEADER +#define IOPORT_CFG_NAME g_bsp_pin_cfg +#define IOPORT_CFG_OPEN R_IOPORT_Open +#define IOPORT_CFG_CTRL g_ioport_ctrl + +/* IOPORT Instance */ +extern const ioport_instance_t g_ioport; + +/* IOPORT control structure. */ +extern ioport_instance_ctrl_t g_ioport_ctrl; +void g_common_init(void); +FSP_FOOTER +#endif /* COMMON_DATA_H_ */ diff --git a/hw/bsp/ra/boards/ra4m3_ek/ra_gen/pin_data.c b/hw/bsp/ra/boards/ra4m3_ek/ra_gen/pin_data.c new file mode 100644 index 000000000..bf30782cf --- /dev/null +++ b/hw/bsp/ra/boards/ra4m3_ek/ra_gen/pin_data.c @@ -0,0 +1,263 @@ +/* generated pin source file - do not edit */ +#include "bsp_api.h" +#include "r_ioport.h" + + +const ioport_pin_cfg_t g_bsp_pin_cfg_data[] = { + { + .pin = BSP_IO_PORT_00_PIN_00, + .pin_cfg = ((uint32_t) IOPORT_CFG_ANALOG_ENABLE) + }, + { + .pin = BSP_IO_PORT_00_PIN_01, + .pin_cfg = ((uint32_t) IOPORT_CFG_ANALOG_ENABLE) + }, + { + .pin = BSP_IO_PORT_00_PIN_03, + .pin_cfg = ((uint32_t) IOPORT_CFG_ANALOG_ENABLE) + }, + { + .pin = BSP_IO_PORT_00_PIN_05, + .pin_cfg = ((uint32_t) IOPORT_CFG_PORT_DIRECTION_INPUT) + }, + { + .pin = BSP_IO_PORT_00_PIN_06, + .pin_cfg = ((uint32_t) IOPORT_CFG_IRQ_ENABLE | (uint32_t) IOPORT_CFG_PORT_DIRECTION_INPUT) + }, + { + .pin = BSP_IO_PORT_00_PIN_07, + .pin_cfg = ((uint32_t) IOPORT_CFG_ANALOG_ENABLE) + }, + { + .pin = BSP_IO_PORT_00_PIN_08, + .pin_cfg = ((uint32_t) IOPORT_CFG_IRQ_ENABLE | (uint32_t) IOPORT_CFG_PORT_DIRECTION_INPUT | (uint32_t) IOPORT_CFG_PULLUP_ENABLE) + }, + { + .pin = BSP_IO_PORT_00_PIN_14, + .pin_cfg = ((uint32_t) IOPORT_CFG_ANALOG_ENABLE) + }, + { + .pin = BSP_IO_PORT_00_PIN_15, + .pin_cfg = ((uint32_t) IOPORT_CFG_ANALOG_ENABLE) + }, + { + .pin = BSP_IO_PORT_01_PIN_00, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SCI0_2_4_6_8) + }, + { + .pin = BSP_IO_PORT_01_PIN_01, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SCI0_2_4_6_8) + }, + { + .pin = BSP_IO_PORT_01_PIN_05, + .pin_cfg = ((uint32_t) IOPORT_CFG_PORT_DIRECTION_OUTPUT | (uint32_t) IOPORT_CFG_PORT_OUTPUT_LOW) + }, + { + .pin = BSP_IO_PORT_01_PIN_08, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_DEBUG) + }, + { + .pin = BSP_IO_PORT_01_PIN_11, + .pin_cfg = ((uint32_t) IOPORT_CFG_PORT_DIRECTION_OUTPUT | (uint32_t) IOPORT_CFG_PORT_OUTPUT_LOW) + }, + { + .pin = BSP_IO_PORT_01_PIN_15, + .pin_cfg = ((uint32_t) IOPORT_CFG_PORT_DIRECTION_OUTPUT | (uint32_t) IOPORT_CFG_PORT_OUTPUT_LOW) + }, + { + .pin = BSP_IO_PORT_02_PIN_02, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SPI) + }, + { + .pin = BSP_IO_PORT_02_PIN_03, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SPI) + }, + { + .pin = BSP_IO_PORT_02_PIN_04, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SPI) + }, + { + .pin = BSP_IO_PORT_02_PIN_05, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SPI) + }, + { + .pin = BSP_IO_PORT_02_PIN_06, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SPI) + }, + { + .pin = BSP_IO_PORT_02_PIN_07, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SPI) + }, + { + .pin = BSP_IO_PORT_03_PIN_00, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_DEBUG) + }, + { + .pin = BSP_IO_PORT_03_PIN_02, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SPI) + }, + { + .pin = BSP_IO_PORT_03_PIN_03, + .pin_cfg = ((uint32_t) IOPORT_CFG_PORT_DIRECTION_OUTPUT | (uint32_t) IOPORT_CFG_PORT_OUTPUT_LOW) + }, + { + .pin = BSP_IO_PORT_03_PIN_04, + .pin_cfg = ((uint32_t) IOPORT_CFG_PORT_DIRECTION_OUTPUT | (uint32_t) IOPORT_CFG_PORT_OUTPUT_LOW) + }, + { + .pin = BSP_IO_PORT_03_PIN_05, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_QSPI) + }, + { + .pin = BSP_IO_PORT_03_PIN_06, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_QSPI) + }, + { + .pin = BSP_IO_PORT_03_PIN_07, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_QSPI) + }, + { + .pin = BSP_IO_PORT_03_PIN_08, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_QSPI) + }, + { + .pin = BSP_IO_PORT_03_PIN_09, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_QSPI) + }, + { + .pin = BSP_IO_PORT_03_PIN_10, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_QSPI) + }, + { + .pin = BSP_IO_PORT_03_PIN_11, + .pin_cfg = ((uint32_t) IOPORT_CFG_PORT_DIRECTION_OUTPUT | (uint32_t) IOPORT_CFG_PORT_OUTPUT_LOW) + }, + { + .pin = BSP_IO_PORT_04_PIN_00, + .pin_cfg = ((uint32_t) IOPORT_CFG_PORT_DIRECTION_OUTPUT | (uint32_t) IOPORT_CFG_PORT_OUTPUT_LOW) + }, + { + .pin = BSP_IO_PORT_04_PIN_04, + .pin_cfg = ((uint32_t) IOPORT_CFG_PORT_DIRECTION_OUTPUT | (uint32_t) IOPORT_CFG_PORT_OUTPUT_LOW) + }, + { + .pin = BSP_IO_PORT_04_PIN_07, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_USB_FS) + }, + { + .pin = BSP_IO_PORT_04_PIN_08, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_GPT1) + }, + { + .pin = BSP_IO_PORT_04_PIN_09, + .pin_cfg = ((uint32_t) IOPORT_CFG_IRQ_ENABLE | (uint32_t) IOPORT_CFG_PORT_DIRECTION_INPUT | (uint32_t) IOPORT_CFG_PULLUP_ENABLE) + }, + { + .pin = BSP_IO_PORT_04_PIN_14, + .pin_cfg = ((uint32_t) IOPORT_CFG_IRQ_ENABLE | (uint32_t) IOPORT_CFG_PORT_DIRECTION_INPUT | (uint32_t) IOPORT_CFG_PULLUP_ENABLE) + }, + { + .pin = BSP_IO_PORT_04_PIN_15, + .pin_cfg = ((uint32_t) IOPORT_CFG_PORT_DIRECTION_OUTPUT | (uint32_t) IOPORT_CFG_PORT_OUTPUT_LOW) + }, + { + .pin = BSP_IO_PORT_05_PIN_00, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_USB_FS) + }, + { + .pin = BSP_IO_PORT_05_PIN_01, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_USB_FS) + }, + { + .pin = BSP_IO_PORT_05_PIN_05, + .pin_cfg = ((uint32_t) IOPORT_CFG_ANALOG_ENABLE) + }, + { + .pin = BSP_IO_PORT_05_PIN_06, + .pin_cfg = ((uint32_t) IOPORT_CFG_ANALOG_ENABLE) + }, + { + .pin = BSP_IO_PORT_05_PIN_11, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_IIC) + }, + { + .pin = BSP_IO_PORT_05_PIN_12, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_IIC) + }, + { + .pin = BSP_IO_PORT_06_PIN_01, + .pin_cfg = ((uint32_t) IOPORT_CFG_NMOS_ENABLE | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SCI1_3_5_7_9) + }, + { + .pin = BSP_IO_PORT_06_PIN_02, + .pin_cfg = ((uint32_t) IOPORT_CFG_NMOS_ENABLE | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SCI1_3_5_7_9) + }, + { + .pin = BSP_IO_PORT_06_PIN_11, + .pin_cfg = ((uint32_t) IOPORT_CFG_PORT_DIRECTION_OUTPUT | (uint32_t) IOPORT_CFG_PORT_OUTPUT_LOW) + }, + { + .pin = BSP_IO_PORT_06_PIN_12, + .pin_cfg = ((uint32_t) IOPORT_CFG_PORT_DIRECTION_OUTPUT | (uint32_t) IOPORT_CFG_PORT_OUTPUT_LOW) + }, + { + .pin = BSP_IO_PORT_07_PIN_08, + .pin_cfg = ((uint32_t) IOPORT_CFG_PORT_DIRECTION_OUTPUT | (uint32_t) IOPORT_CFG_PORT_OUTPUT_LOW) + }, + { + .pin = BSP_IO_PORT_07_PIN_09, + .pin_cfg = ((uint32_t) IOPORT_CFG_PORT_DIRECTION_OUTPUT | (uint32_t) IOPORT_CFG_PORT_OUTPUT_LOW) + }, + { + .pin = BSP_IO_PORT_07_PIN_10, + .pin_cfg = ((uint32_t) IOPORT_CFG_PORT_DIRECTION_OUTPUT | (uint32_t) IOPORT_CFG_PORT_OUTPUT_LOW) + }, + { + .pin = BSP_IO_PORT_07_PIN_12, + .pin_cfg = ((uint32_t) IOPORT_CFG_PORT_DIRECTION_OUTPUT | (uint32_t) IOPORT_CFG_PORT_OUTPUT_LOW) + }, + { + .pin = BSP_IO_PORT_07_PIN_13, + .pin_cfg = ((uint32_t) IOPORT_CFG_PORT_DIRECTION_OUTPUT | (uint32_t) IOPORT_CFG_PORT_OUTPUT_LOW) + }, +}; + +const ioport_cfg_t g_bsp_pin_cfg = { + .number_of_pins = sizeof(g_bsp_pin_cfg_data)/sizeof(ioport_pin_cfg_t), + .p_pin_cfg_data = &g_bsp_pin_cfg_data[0], +}; + +#if BSP_TZ_SECURE_BUILD + +void R_BSP_PinCfgSecurityInit(void); + +/* Initialize SAR registers for secure pins. */ +void R_BSP_PinCfgSecurityInit(void) +{ + #if (2U == BSP_FEATURE_IOPORT_VERSION) + uint32_t pmsar[BSP_FEATURE_BSP_NUM_PMSAR]; + #else + uint16_t pmsar[BSP_FEATURE_BSP_NUM_PMSAR]; + #endif + memset(pmsar, 0xFF, BSP_FEATURE_BSP_NUM_PMSAR * sizeof(R_PMISC->PMSAR[0])); + + + for(uint32_t i = 0; i < g_bsp_pin_cfg.number_of_pins; i++) + { + uint32_t port_pin = g_bsp_pin_cfg.p_pin_cfg_data[i].pin; + uint32_t port = port_pin >> 8U; + uint32_t pin = port_pin & 0xFFU; + pmsar[port] &= (uint16_t) ~(1U << pin); + } + + for(uint32_t i = 0; i < BSP_FEATURE_BSP_NUM_PMSAR; i++) + { + #if (2U == BSP_FEATURE_IOPORT_VERSION) + R_PMISC->PMSAR[i].PMSAR = (uint16_t) pmsar[i]; + #else + R_PMISC->PMSAR[i].PMSAR = pmsar[i]; + #endif + } + +} +#endif diff --git a/hw/bsp/ra/boards/ra4m3_ek/script/fsp.ld b/hw/bsp/ra/boards/ra4m3_ek/script/fsp.ld new file mode 100644 index 000000000..605eef7d2 --- /dev/null +++ b/hw/bsp/ra/boards/ra4m3_ek/script/fsp.ld @@ -0,0 +1,769 @@ +/* + Linker File for Renesas FSP +*/ + +INCLUDE memory_regions.ld + +/* Uncomment and set XIP_SECONDARY_SLOT_IMAGE to 1 below for the secondary XIP application image.*/ +/* + XIP_SECONDARY_SLOT_IMAGE = 1; +*/ + +QSPI_FLASH_PRV_LENGTH = DEFINED(QSPI_FLASH_SIZE) ? ABSOLUTE(QSPI_FLASH_SIZE) : ABSOLUTE(QSPI_FLASH_LENGTH); +OSPI_DEVICE_0_PRV_LENGTH = DEFINED(OSPI_DEVICE_0_SIZE) ? ABSOLUTE(OSPI_DEVICE_0_SIZE) : ABSOLUTE(OSPI_DEVICE_0_LENGTH); +OSPI_DEVICE_1_PRV_LENGTH = DEFINED(OSPI_DEVICE_1_SIZE) ? ABSOLUTE(OSPI_DEVICE_1_SIZE) : ABSOLUTE(OSPI_DEVICE_1_LENGTH); + +/* If a flat (secure) project has DEFINED RAM_NS_BUFFER_LENGTH, then emit IDAU symbols to allocate non-secure RAM. */ +__RESERVE_NS_RAM = !DEFINED(PROJECT_NONSECURE) && DEFINED(RAM_NS_BUFFER_LENGTH) && (OPTION_SETTING_S_LENGTH != 0); + +ITCM_START = DEFINED(ITCM_START)? ITCM_START : 0; +ITCM_LENGTH = DEFINED(ITCM_LENGTH)? ITCM_LENGTH : 0; +DTCM_START = DEFINED(DTCM_START)? DTCM_START : 0; +DTCM_LENGTH = DEFINED(DTCM_LENGTH)? DTCM_LENGTH : 0; +RAM_NS_BUFFER_BLOCK_LENGTH = DEFINED(RAM_NS_BUFFER_LENGTH) ? ALIGN(RAM_NS_BUFFER_LENGTH, 8192) : 0; +RAM_NS_BUFFER_LENGTH = DEFINED(RAM_NS_BUFFER_LENGTH) ? RAM_NS_BUFFER_LENGTH : 0; +RAM_NS_BUFFER_START = RAM_START + RAM_LENGTH - RAM_NS_BUFFER_LENGTH; +RAM_NS_BUFFER_BLOCK_START = RAM_START + RAM_LENGTH - RAM_NS_BUFFER_BLOCK_LENGTH; + +OPTION_SETTING_START_NS = DEFINED(PROJECT_NONSECURE) ? OPTION_SETTING_START : OPTION_SETTING_START + 0x80; + +/* This definition is used to avoid moving the counter in OPTION_SETTING regions for projects that should not configure option settings. + * Bootloader images do not configure option settings because they are owned by the bootloader. + * FSP_BOOTABLE_IMAGE is only defined in bootloader images. */ +__bl_FSP_BOOTABLE_IMAGE = 1; +__bln_FSP_BOOTABLE_IMAGE = 1; +PROJECT_SECURE_OR_FLAT = (!DEFINED(PROJECT_NONSECURE) || DEFINED(PROJECT_SECURE)) && OPTION_SETTING_LENGTH && !DEFINED(FSP_BOOTABLE_IMAGE); +USE_OPTION_SETTING_NS = DEFINED(PROJECT_NONSECURE) && !DEFINED(FSP_BOOTABLE_IMAGE); + +__bl_FLASH_IMAGE_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_IMAGE_NUMBER == 1 ? FLASH_START + FLASH_BOOTLOADER_LENGTH + FLASH_BOOTLOADER_HEADER_LENGTH : + (DEFINED(BOOTLOADER_SECONDARY_USE_QSPI) || DEFINED(BOOTLOADER_SECONDARY_USE_OSPI_B)) ? FLASH_START + FLASH_BOOTLOADER_LENGTH + FLASH_BOOTLOADER_SCRATCH_LENGTH + FLASH_BOOTLOADER_HEADER_LENGTH : + FLASH_START + FLASH_BOOTLOADER_LENGTH + FLASH_BOOTLOADER_SCRATCH_LENGTH + FLASH_APPLICATION_S_LENGTH + FLASH_BOOTLOADER_HEADER_LENGTH; +__bl_FLASH_IMAGE_LENGTH = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_S_LENGTH - FLASH_BOOTLOADER_HEADER_LENGTH; +__bl_FLASH_IMAGE_END = __bl_FLASH_IMAGE_START + __bl_FLASH_IMAGE_LENGTH; +__bl_XIP_SECONDARY_FLASH_IMAGE_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_START + FLASH_BOOTLOADER_LENGTH + FLASH_APPLICATION_S_LENGTH + FLASH_BOOTLOADER_HEADER_LENGTH; +__bl_XIP_SECONDARY_FLASH_IMAGE_END = __bl_XIP_SECONDARY_FLASH_IMAGE_START + __bl_FLASH_IMAGE_LENGTH; +__bl_FLASH_NS_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_NS_LENGTH == 0 ? __bl_FLASH_IMAGE_END : + __bl_FLASH_IMAGE_START - FLASH_BOOTLOADER_HEADER_LENGTH + FLASH_APPLICATION_S_LENGTH; +__bl_FLASH_NSC_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_NS_LENGTH == 0 ? __bl_FLASH_IMAGE_END : + __bl_FLASH_IMAGE_END - FLASH_APPLICATION_NSC_LENGTH; +__bl_RAM_NS_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_NS_LENGTH == 0 ? RAM_START + RAM_LENGTH : + RAM_START + RAM_LENGTH - RAM_APPLICATION_NS_LENGTH; +__bl_RAM_NSC_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_NS_LENGTH == 0 ? RAM_START + RAM_LENGTH : + __bl_RAM_NS_START - RAM_APPLICATION_NSC_LENGTH; +__bl_FLASH_NS_IMAGE_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_NS_LENGTH == 0 ? __bl_FLASH_IMAGE_END : + __bl_FLASH_NS_START + FLASH_BOOTLOADER_HEADER_LENGTH_2; +__bln_FLASH_IMAGE_START = __bl_FLASH_NS_IMAGE_START | (!DEFINED (NS_OFFSET_START) ? 0 : NS_OFFSET_START); +__bln_FLASH_IMAGE_LENGTH = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_NS_LENGTH == 0 ? __bl_FLASH_IMAGE_END : + FLASH_APPLICATION_NS_LENGTH - FLASH_BOOTLOADER_HEADER_LENGTH_2; + +XIP_SECONDARY_SLOT_IMAGE = DEFINED(XIP_SECONDARY_SLOT_IMAGE) ? XIP_SECONDARY_SLOT_IMAGE : 0; +FLASH_ORIGIN = !DEFINED(FLASH_IMAGE_START) ? FLASH_START : + XIP_SECONDARY_SLOT_IMAGE == 1 ? XIP_SECONDARY_FLASH_IMAGE_START : + FLASH_IMAGE_START; +LIMITED_FLASH_LENGTH = DEFINED(FLASH_IMAGE_LENGTH) ? FLASH_IMAGE_LENGTH : + DEFINED(FLASH_BOOTLOADER_LENGTH) ? FLASH_BOOTLOADER_LENGTH : + FLASH_LENGTH; +OPTION_SETTING_SAS_SIZE = 0x34; +OPTION_SETTING_SAS_LENGTH = !DEFINED(OPTION_SETTING_LENGTH) ? 0 : + OPTION_SETTING_LENGTH == 0 ? 0 : + OPTION_SETTING_LENGTH - OPTION_SETTING_SAS_SIZE; + +/* Define memory regions. */ +MEMORY +{ + ITCM (rx) : ORIGIN = ITCM_START, LENGTH = ITCM_LENGTH + DTCM (rwx) : ORIGIN = DTCM_START, LENGTH = DTCM_LENGTH + FLASH (rx) : ORIGIN = FLASH_ORIGIN, LENGTH = LIMITED_FLASH_LENGTH + RAM (rwx) : ORIGIN = RAM_START, LENGTH = RAM_LENGTH + DATA_FLASH (rx) : ORIGIN = DATA_FLASH_START, LENGTH = DATA_FLASH_LENGTH + QSPI_FLASH (rx) : ORIGIN = QSPI_FLASH_START, LENGTH = QSPI_FLASH_PRV_LENGTH + OSPI_DEVICE_0 (rx) : ORIGIN = OSPI_DEVICE_0_START, LENGTH = OSPI_DEVICE_0_PRV_LENGTH + OSPI_DEVICE_1 (rx) : ORIGIN = OSPI_DEVICE_1_START, LENGTH = OSPI_DEVICE_1_PRV_LENGTH + OSPI_DEVICE_0_RAM (rwx) : ORIGIN = OSPI_DEVICE_0_START, LENGTH = OSPI_DEVICE_0_PRV_LENGTH + OSPI_DEVICE_1_RAM (rwx) : ORIGIN = OSPI_DEVICE_1_START, LENGTH = OSPI_DEVICE_1_PRV_LENGTH + SDRAM (rwx) : ORIGIN = SDRAM_START, LENGTH = SDRAM_LENGTH + OPTION_SETTING (r) : ORIGIN = OPTION_SETTING_START, LENGTH = OPTION_SETTING_LENGTH + OPTION_SETTING_OFS (r) : ORIGIN = OPTION_SETTING_START, LENGTH = 0x18 + OPTION_SETTING_SAS (r) : ORIGIN = OPTION_SETTING_START + OPTION_SETTING_SAS_SIZE, LENGTH = OPTION_SETTING_SAS_LENGTH + OPTION_SETTING_S (r) : ORIGIN = OPTION_SETTING_S_START, LENGTH = OPTION_SETTING_S_LENGTH + ID_CODE (rx) : ORIGIN = ID_CODE_START, LENGTH = ID_CODE_LENGTH +} + +/* Library configurations */ +GROUP(libgcc.a libc.a libm.a) + +/* Linker script to place sections and symbol values. Should be used together + * with other linker script that defines memory regions FLASH and RAM. + * It references following symbols, which must be DEFINED in code: + * Reset_Handler : Entry of reset handler + * + * It defines following symbols, which code can use without definition: + * __exidx_start + * __exidx_end + * __copy_table_start__ + * __copy_table_end__ + * __zero_table_start__ + * __zero_table_end__ + * __etext + * __data_start__ + * __preinit_array_start + * __preinit_array_end + * __init_array_start + * __init_array_end + * __fini_array_start + * __fini_array_end + * __data_end__ + * __bss_start__ + * __bss_end__ + * __HeapLimit + * __StackLimit + * __StackTop + * __stack + * __Vectors_End + * __Vectors_Size + * __qspi_flash_start__ + * __qspi_flash_end__ + * __qspi_flash_code_size__ + * __qspi_region_max_size__ + * __qspi_region_start_address__ + * __qspi_region_end_address__ + * __ospi_device_0_start__ + * __ospi_device_0_end__ + * __ospi_device_0_code_size__ + * __ospi_device_0_region_max_size__ + * __ospi_device_0_region_start_address__ + * __ospi_device_0_region_end_address__ + * __ospi_device_1_start__ + * __ospi_device_1_end__ + * __ospi_device_1_code_size__ + * __ospi_device_1_region_max_size__ + * __ospi_device_1_region_start_address__ + * __ospi_device_1_region_end_address__ + */ +ENTRY(Reset_Handler) + +SECTIONS +{ + .text : + { + __tz_FLASH_S = ABSOLUTE(FLASH_START); + __ROM_Start = .; + + /* Even though the vector table is not 256 entries (1KB) long, we still allocate that much + * space because ROM registers are at address 0x400 and there is very little space + * in between. */ + KEEP(*(.fixed_vectors*)) + KEEP(*(.application_vectors*)) + __Vectors_End = .; + + /* Some devices have a gap of code flash between the vector table and ROM Registers. + * The flash gap section allows applications to place code and data in this section. */ + *(.flash_gap*) + + /* ROM Registers start at address 0x00000400 for devices that do not have the OPTION_SETTING region. */ + . = OPTION_SETTING_LENGTH > 0 ? . : __ROM_Start + 0x400; + KEEP(*(.rom_registers*)) + + /* Reserving 0x100 bytes of space for ROM registers. */ + . = OPTION_SETTING_LENGTH > 0 ? . : __ROM_Start + 0x500; + + /* Allocate flash write-boundary-aligned + * space for sce9 wrapped public keys for mcuboot if the module is used. + */ + KEEP(*(.mcuboot_sce9_key*)) + + *(.text*) + + KEEP(*(.version)) + KEEP(*(.init)) + KEEP(*(.fini)) + + /* .ctors */ + *crtbegin.o(.ctors) + *crtbegin?.o(.ctors) + *(EXCLUDE_FILE(*crtend?.o *crtend.o) .ctors) + *(SORT(.ctors.*)) + *(.ctors) + + /* .dtors */ + *crtbegin.o(.dtors) + *crtbegin?.o(.dtors) + *(EXCLUDE_FILE(*crtend?.o *crtend.o) .dtors) + *(SORT(.dtors.*)) + *(.dtors) + + *(.rodata*) + __usb_dev_descriptor_start_fs = .; + KEEP(*(.usb_device_desc_fs*)) + __usb_cfg_descriptor_start_fs = .; + KEEP(*(.usb_config_desc_fs*)) + __usb_interface_descriptor_start_fs = .; + KEEP(*(.usb_interface_desc_fs*)) + __usb_descriptor_end_fs = .; + __usb_dev_descriptor_start_hs = .; + KEEP(*(.usb_device_desc_hs*)) + __usb_cfg_descriptor_start_hs = .; + KEEP(*(.usb_config_desc_hs*)) + __usb_interface_descriptor_start_hs = .; + KEEP(*(.usb_interface_desc_hs*)) + __usb_descriptor_end_hs = .; + + KEEP(*(.eh_frame*)) + + __ROM_End = .; + } > FLASH = 0xFF + + __Vectors_Size = __Vectors_End - __Vectors; + + . = .; + __itcm_data_pre_location = .; + + /* Initialized ITCM data. */ + /* Aligned to FCACHE2 for RA8. */ + .itcm_data : ALIGN(16) + { + /* Start of ITCM Secure Trustzone region. */ + __tz_ITCM_S = ABSOLUTE(ITCM_START); + + /* All ITCM data start */ + __itcm_data_start = .; + + KEEP(*(.itcm_data*)) + + /* Pad to eight byte alignment in case of ECC initialization. Fill zero. */ + . = ALIGN(8); + + /* All ITCM data end */ + __itcm_data_end = .; + + /* + * Start of the ITCM Non-Secure Trustzone region. + * ITCM_NS_START can be used to set a fixed address for non-secure ITCM in secure projects or flat projects. + */ + __tz_ITCM_N = DEFINED(ITCM_NS_START) ? ABSOLUTE(ITCM_NS_START) : ALIGN(__itcm_data_end, 8192); + } > ITCM AT > FLASH = 0x00 + + /* Addresses exported for ITCM initialization. */ + __itcm_data_init_start = LOADADDR(.itcm_data); + __itcm_data_init_end = LOADADDR(.itcm_data) + SIZEOF(.itcm_data); + + ASSERT(ORIGIN(ITCM) % 8 == 0, "ITCM memory region origin must be aligned to 8 bytes.") + ASSERT(LENGTH(ITCM) % 8 == 0, "ITCM memory region length must be a multiple of 8 bytes.") + ASSERT(LOADADDR(.itcm_data) % 16 == 0, ".itcm_data section must be aligned to 16 bytes.") + ASSERT(SIZEOF(.itcm_data) % 8 == 0, ".itcm_data section size must be a multiple of 8 bytes.") + + /* Restore location counter. */ + /* If ITCM is not present, this will be the address stored in '.' before ALIGN was attempted. */ + /* If ITCM is present, this will be the absolute address that follows the ITCM ROM location. */ + . = (SIZEOF(.itcm_data) > 0) ? __itcm_data_init_end : __itcm_data_pre_location; + + __exidx_start = .; + /DISCARD/ : + { + *(.ARM.extab* .gnu.linkonce.armextab.*) + *(.ARM.exidx* .gnu.linkonce.armexidx.*) + } + __exidx_end = .; + + /* To copy multiple ROM to RAM sections, + * uncomment .copy.table section and, + * define __STARTUP_COPY_MULTIPLE in startup_ARMCMx.S */ + /* + .copy.table : + { + . = ALIGN(4); + __copy_table_start__ = .; + LONG (__etext) + LONG (__data_start__) + LONG (__data_end__ - __data_start__) + LONG (__etext2) + LONG (__data2_start__) + LONG (__data2_end__ - __data2_start__) + __copy_table_end__ = .; + } > FLASH + */ + + /* To clear multiple BSS sections, + * uncomment .zero.table section and, + * define __STARTUP_CLEAR_BSS_MULTIPLE in startup_ARMCMx.S */ + /* + .zero.table : + { + . = ALIGN(4); + __zero_table_start__ = .; + LONG (__bss_start__) + LONG (__bss_end__ - __bss_start__) + LONG (__bss2_start__) + LONG (__bss2_end__ - __bss2_start__) + __zero_table_end__ = .; + } > FLASH + */ + + __etext = .; + + __tz_RAM_S = ORIGIN(RAM); + + /* If DTC is used, put the DTC vector table at the start of SRAM. + This avoids memory holes due to 1K alignment required by it. */ + .fsp_dtc_vector_table (NOLOAD) : + { + . = ORIGIN(RAM); + *(.fsp_dtc_vector_table) + } > RAM + + /* Initialized data section. */ + .data : + { + __data_start__ = .; + . = ALIGN(4); + + __Code_In_RAM_Start = .; + + KEEP(*(.code_in_ram*)) + __Code_In_RAM_End = .; + + *(vtable) + /* Don't use *(.data*) because it will place data meant for .data_flash in this section. */ + *(.data.*) + *(.data) + + . = ALIGN(4); + /* preinit data */ + PROVIDE_HIDDEN (__preinit_array_start = .); + KEEP(*(.preinit_array)) + PROVIDE_HIDDEN (__preinit_array_end = .); + + . = ALIGN(4); + /* init data */ + PROVIDE_HIDDEN (__init_array_start = .); + KEEP(*(SORT(.init_array.*))) + KEEP(*(.init_array)) + PROVIDE_HIDDEN (__init_array_end = .); + + + . = ALIGN(4); + /* finit data */ + PROVIDE_HIDDEN (__fini_array_start = .); + KEEP(*(SORT(.fini_array.*))) + KEEP(*(.fini_array)) + PROVIDE_HIDDEN (__fini_array_end = .); + + KEEP(*(.jcr*)) + + . = ALIGN(4); + + /* All data end */ + __data_end__ = .; + + } > RAM AT > FLASH + + . = .; + __dtcm_data_pre_location = LOADADDR(.data) + SIZEOF(.data); + + /* Initialized DTCM data. */ + /* Aligned to FCACHE2 for RA8. */ + .dtcm_data : ALIGN(16) + { + /* Start of DTCM Secure Trustzone region. */ + __tz_DTCM_S = ABSOLUTE(DTCM_START); + + /* Initialized DTCM data start */ + __dtcm_data_start = .; + + KEEP(*(.dtcm_data*)) + + /* Pad to eight byte alignment in case of ECC initialization. Fill zero. */ + . = ALIGN(8); + + /* Initialized DTCM data end */ + __dtcm_data_end = .; + } > DTCM AT > FLASH = 0x00 + + . = __dtcm_data_end; + /* Uninitialized DTCM data. */ + /* ALIGN appears on the left side of the colon because it is being used to assign the VMA directly, as opposed to a right side appearance which would control the LMA. */ + .dtcm_bss ALIGN(8) (NOLOAD) : + { + /* Uninitialized DTCM data start */ + __dtcm_bss_start = .; + + KEEP(*(.dtcm_bss*)) + + /* Pad to eight byte alignment in case of ECC initialization. No fill because of NOLOAD. */ + . = ALIGN(8); + + /* Uninitialized DTCM data end */ + __dtcm_bss_end = .; + + /* + * Start of the DTCM Non-Secure Trustzone region. + * DTCM_NS_START can be used to set a fixed address for non-secure DTCM in secure projects or flat projects. + */ + __tz_DTCM_N = DEFINED(DTCM_NS_START) ? ABSOLUTE(DTCM_NS_START) : ALIGN(__dtcm_bss_end, 8192); + } > DTCM + + /* Addresses exported for DTCM initialization. */ + __dtcm_data_init_start = LOADADDR(.dtcm_data); + __dtcm_data_init_end = LOADADDR(.dtcm_data) + SIZEOF(.dtcm_data); + + ASSERT(ORIGIN(DTCM) % 8 == 0, "DTCM memory region origin must be aligned to 8 bytes.") + ASSERT(LENGTH(DTCM) % 8 == 0, "DTCM memory region length must be a multiple of 8 bytes.") + ASSERT(LOADADDR(.dtcm_bss) == ADDR(.dtcm_bss), ".dtcm_bss has (VMA != LMA) but should be NOLOAD (VMA == LMA).") + ASSERT(LOADADDR(.dtcm_data) % 16 == 0, ".dtcm_data section must be aligned to 16 bytes.") + ASSERT(SIZEOF(.dtcm_data) % 8 == 0, ".dtcm_data section size must be a multiple of 8 bytes.") + ASSERT(LOADADDR(.dtcm_bss) % 8 == 0, ".dtcm_bss section must be aligned to 8 bytes.") + ASSERT(SIZEOF(.dtcm_bss) % 8 == 0, ".dtcm_bss section size must be a multiple of 8 bytes.") + ASSERT(__dtcm_bss_start == __dtcm_data_end, ".dtcm_bss section is not adjacent to .dtcm_data section.") + + /* Restore location counter. */ + /* If DTCM is not present, this will be the address stored in '.' before ALIGN was attempted. */ + /* If DTCM is present, this will be the absolute address that follows the DTCM ROM location. */ + . = (SIZEOF(.dtcm_data) > 0) ? __dtcm_data_init_end : __dtcm_data_pre_location; + + /* TrustZone Secure Gateway Stubs Section */ + + /* Store location counter for SPI non-retentive sections. */ + sgstubs_pre_location = .; + + /* Determine the secure gateway stubs address either by the provided linker variable or the next 1024-byte block. */ + SGSTUBS_LOC = (DEFINED(PROJECT_SECURE) && DEFINED(FLASH_NSC_START)) ? ABSOLUTE(FLASH_NSC_START) : ALIGN(1024); + .gnu.sgstubs SGSTUBS_LOC : ALIGN(1024) + { + __tz_FLASH_C = DEFINED(FLASH_NSC_START) ? ABSOLUTE(FLASH_NSC_START) : __RESERVE_NS_RAM ? ABSOLUTE(FLASH_START + FLASH_LENGTH) : ALIGN(1024); + _start_sg = .; + *(.gnu.sgstubs*) + . = ALIGN(32); + _end_sg = .; + } > FLASH + + __tz_FLASH_N = DEFINED(FLASH_NS_START) ? ABSOLUTE(FLASH_NS_START) : __RESERVE_NS_RAM ? ABSOLUTE(FLASH_START + FLASH_LENGTH) : FLASH_LENGTH < 32768 ? FLASH_LENGTH : ALIGN(32768); + FLASH_NS_IMAGE_START = DEFINED(FLASH_NS_IMAGE_START) ? FLASH_NS_IMAGE_START : __tz_FLASH_N; + + /* Note: There are no secure/non-secure boundaries for QSPI. These symbols are provided for the RA configuration tool. */ + __tz_QSPI_FLASH_S = ORIGIN(QSPI_FLASH); + + /* QSPI_FLASH section to be downloaded via debugger */ + .qspi_flash : + { + __qspi_flash_start__ = .; + KEEP(*(.qspi_flash*)) + KEEP(*(.code_in_qspi*)) + __qspi_flash_end__ = .; + } > QSPI_FLASH + __qspi_flash_code_size__ = __qspi_flash_end__ - __qspi_flash_start__; + + /* QSPI_FLASH non-retentive section, creates a copy in internal flash that can be copied to QSPI */ + __qspi_flash_code_addr__ = sgstubs_pre_location; + .qspi_non_retentive : AT(__qspi_flash_code_addr__) + { + __qspi_non_retentive_start__ = .; + KEEP(*(.qspi_non_retentive*)) + __qspi_non_retentive_end__ = .; + } > QSPI_FLASH + __qspi_non_retentive_size__ = __qspi_non_retentive_end__ - __qspi_non_retentive_start__; + + __qspi_region_max_size__ = 0x4000000; /* Must be the same as defined in MEMORY above */ + __qspi_region_start_address__ = __qspi_flash_start__; + __qspi_region_end_address__ = __qspi_flash_start__ + __qspi_region_max_size__; + + /* Note: There are no secure/non-secure boundaries for QSPI. These symbols are provided for the RA configuration tool. */ + __tz_QSPI_FLASH_N = __qspi_non_retentive_end__; + + /* Support for OctaRAM */ + .OSPI_DEVICE_0_NO_LOAD (NOLOAD): + { + . = ALIGN(4); + __ospi_device_0_start__ = .; + *(.ospi_device_0_no_load*) + . = ALIGN(4); + __ospi_device_0_end__ = .; + } > OSPI_DEVICE_0_RAM + + .OSPI_DEVICE_1_NO_LOAD (NOLOAD): + { + . = ALIGN(4); + __ospi_device_1_start__ = .; + *(.ospi_device_1_no_load*) + . = ALIGN(4); + __ospi_device_1_end__ = .; + } > OSPI_DEVICE_1_RAM + + /* Note: There are no secure/non-secure boundaries for QSPI. These symbols are provided for the RA configuration tool. */ + __tz_OSPI_DEVICE_0_S = ORIGIN(OSPI_DEVICE_0); + + /* OSPI_DEVICE_0 section to be downloaded via debugger */ + .OSPI_DEVICE_0 : + { + __ospi_device_0_start__ = .; + KEEP(*(.ospi_device_0*)) + KEEP(*(.code_in_ospi_device_0*)) + __ospi_device_0_end__ = .; + } > OSPI_DEVICE_0 + __ospi_device_0_code_size__ = __ospi_device_0_end__ - __ospi_device_0_start__; + + /* OSPI_DEVICE_0 non-retentive section, creates a copy in internal flash that can be copied to OSPI */ + __ospi_device_0_code_addr__ = sgstubs_pre_location + (SIZEOF(.qspi_non_retentive)); + .ospi_device_0_non_retentive : AT(__ospi_device_0_code_addr__) + { + __ospi_device_0_non_retentive_start__ = .; + KEEP(*(.ospi_device_0_non_retentive*)) + __ospi_device_0_non_retentive_end__ = .; + } > OSPI_DEVICE_0 + __ospi_device_0_non_retentive_size__ = __ospi_device_0_non_retentive_end__ - __ospi_device_0_non_retentive_start__; + + __ospi_device_0_region_max_size__ = 0x8000000; /* Must be the same as defined in MEMORY above */ + __ospi_device_0_region_start_address__ = __ospi_device_0_start__; + __ospi_device_0_region_end_address__ = __ospi_device_0_start__ + __ospi_device_0_region_max_size__; + + /* Note: There are no secure/non-secure boundaries for OSPI. These symbols are provided for the RA configuration tool. */ + __tz_OSPI_DEVICE_0_N = __ospi_device_0_non_retentive_end__; + + /* Note: There are no secure/non-secure boundaries for OSPI. These symbols are provided for the RA configuration tool. */ + __tz_OSPI_DEVICE_1_S = ORIGIN(OSPI_DEVICE_1); + + /* OSPI_DEVICE_1 section to be downloaded via debugger */ + .OSPI_DEVICE_1 : + { + __ospi_device_1_start__ = .; + KEEP(*(.ospi_device_1*)) + KEEP(*(.code_in_ospi_device_1*)) + __ospi_device_1_end__ = .; + } > OSPI_DEVICE_1 + __ospi_device_1_code_size__ = __ospi_device_1_end__ - __ospi_device_1_start__; + + /* OSPI_DEVICE_1 non-retentive section, creates a copy in internal flash that can be copied to OSPI */ + __ospi_device_1_code_addr__ = sgstubs_pre_location + (SIZEOF(.qspi_non_retentive) + SIZEOF(.ospi_device_0_non_retentive)); + .ospi_device_1_non_retentive : AT(__ospi_device_1_code_addr__) + { + __ospi_device_1_non_retentive_start__ = .; + KEEP(*(.ospi_device_1_non_retentive*)) + __ospi_device_1_non_retentive_end__ = .; + } > OSPI_DEVICE_1 + __ospi_device_1_non_retentive_size__ = __ospi_device_1_non_retentive_end__ - __ospi_device_1_non_retentive_start__; + + __ospi_device_1_region_max_size__ = 0x10000000; /* Must be the same as defined in MEMORY above */ + __ospi_device_1_region_start_address__ = __ospi_device_1_start__; + __ospi_device_1_region_end_address__ = __ospi_device_1_start__ + __ospi_device_1_region_max_size__; + + /* Note: There are no secure/non-secure boundaries for OSPI. These symbols are provided for the RA configuration tool. */ + __tz_OSPI_DEVICE_1_N = __ospi_device_1_non_retentive_end__; + + .noinit (NOLOAD): + { + . = ALIGN(4); + __noinit_start = .; + KEEP(*(.noinit*)) + . = ALIGN(8); + /* Place the FreeRTOS heap here so that the __HeapLimit calculation does not include the freertos heap. */ + KEEP(*(.heap.*)) + __noinit_end = .; + } > RAM + + .bss : + { + . = ALIGN(4); + __bss_start__ = .; + *(.bss*) + *(COMMON) + . = ALIGN(4); + __bss_end__ = .; + } > RAM + + .heap (NOLOAD): + { + . = ALIGN(8); + __HeapBase = .; + /* Place the STD heap here. */ + KEEP(*(.heap)) + __HeapLimit = .; + } > RAM + + /* Stacks are stored in this section. */ + .stack_dummy (NOLOAD): + { + . = ALIGN(8); + __StackLimit = .; + /* Main stack */ + KEEP(*(.stack)) + __StackTop = .; + /* Thread stacks */ + KEEP(*(.stack*)) + __StackTopAll = .; + } > RAM + + PROVIDE(__stack = __StackTopAll); + + /* This symbol represents the end of user allocated RAM. The RAM after this symbol can be used + at run time for things such as ThreadX memory pool allocations. */ + __RAM_segment_used_end__ = ALIGN(__StackTopAll , 4); + + /* RAM_NSC_START can be used to set a fixed address for non-secure callable RAM in secure projects. + * If it is not specified, the address for NSC RAM is the end of RAM aligned to a 1K boundary. + * In flat projects that require non-secure RAM, this variable is set to the start of non-secure RAM. */ + __tz_RAM_C = DEFINED(RAM_NSC_START) ? ABSOLUTE(RAM_NSC_START - RAM_NS_BUFFER_BLOCK_LENGTH) : __RESERVE_NS_RAM ? ABSOLUTE(RAM_NS_BUFFER_BLOCK_START) : ALIGN(__RAM_segment_used_end__, 1024); + + /* RAM_NS_START can be used to set a fixed address for non-secure RAM in secure projects or flat projects. + * RAM_NS_BUFFER_BLOCK_LENGTH is used to allocate non-secure buffers in a flat project. If it is not + * specified, the address for NSC RAM is the end of RAM aligned to an 8K boundary. + * In flat projects that require non-secure RAM, this variable is set to the start of non-secure RAM. */ + __tz_RAM_N = DEFINED(RAM_NS_START) ? ABSOLUTE(RAM_NS_START - RAM_NS_BUFFER_BLOCK_LENGTH) : __RESERVE_NS_RAM ? ABSOLUTE(RAM_NS_BUFFER_BLOCK_START) : ALIGN(__tz_RAM_C, 8192); + + /* Non-secure buffers must be in non-secure RAM. This is primarily used for the EDMAC in flat projects. + * The EDMAC is a non-secure bus master and can only access non-secure RAM. */ + .ns_buffer (NOLOAD): + { + /* Allocate RAM on a 32-byte boundary to help with placement of Ethernet buffers. */ + . = __RESERVE_NS_RAM ? ABSOLUTE(RAM_NS_BUFFER_START & 0xFFFFFFE0) : .; + + KEEP(*(.ns_buffer*)) + } > RAM + + /* Data flash. */ + .data_flash : + { + . = ORIGIN(DATA_FLASH); + __tz_DATA_FLASH_S = .; + __Data_Flash_Start = .; + KEEP(*(.data_flash*)) + __Data_Flash_End = .; + + __tz_DATA_FLASH_N = DEFINED(DATA_FLASH_NS_START) ? ABSOLUTE(DATA_FLASH_NS_START) : __RESERVE_NS_RAM ? ABSOLUTE(DATA_FLASH_START + DATA_FLASH_LENGTH) : ALIGN(1024); + } > DATA_FLASH + + /* Note: There are no secure/non-secure boundaries for SDRAM. These symbols are provided for the RA configuration tool. */ + __tz_SDRAM_S = ORIGIN(SDRAM); + + /* SDRAM */ + .sdram (NOLOAD): + { + __SDRAM_Start = .; + KEEP(*(.sdram*)) + KEEP(*(.frame*)) + __SDRAM_End = .; + } > SDRAM + + /* Note: There are no secure/non-secure boundaries for SDRAM. These symbols are provided for the RA configuration tool. */ + __tz_SDRAM_N = __SDRAM_End; + + /* Note: There are no secure/non-secure boundaries for ID_CODE. These symbols are provided for the RA configuration tool. */ + __tz_ID_CODE_S = ORIGIN(ID_CODE); + + /* Note: There are no secure/non-secure boundaries for ID_CODE. These symbols are provided for the RA configuration tool. + * Set this symbol to the same value as __tz_ID_CODE_S so the RA configuration tool does not split the ID_CODE + * memory region between TrustZone projects. */ + __tz_ID_CODE_N = __tz_ID_CODE_S; + + .id_code : + { + __ID_Code_Start = .; + KEEP(*(.id_code*)) + __ID_Code_End = .; + } > ID_CODE + + /* Symbol required for RA Configuration tool. */ + __tz_OPTION_SETTING_S = ORIGIN(OPTION_SETTING_OFS); + + .option_setting_ofs : + { + __OPTION_SETTING_OFS_Start = .; + KEEP(*(.option_setting_ofs0)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_OFS_Start + 0x04 : __OPTION_SETTING_OFS_Start; + KEEP(*(.option_setting_ofs2)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_OFS_Start + 0x10 : __OPTION_SETTING_OFS_Start; + KEEP(*(.option_setting_dualsel)) + __OPTION_SETTING_OFS_End = .; + } > OPTION_SETTING_OFS = 0xFF + + .option_setting_sas : + { + __OPTION_SETTING_SAS_Start = .; + KEEP(*(.option_setting_sas)) + __OPTION_SETTING_SAS_End = .; + } > OPTION_SETTING_SAS = 0xFF + + /* Symbol required for RA Configuration tool. */ + __tz_OPTION_SETTING_N = ABSOLUTE(OPTION_SETTING_START_NS); + + .option_setting_ns : + { + __OPTION_SETTING_NS_Start = .; + KEEP(*(.option_setting_ofs1)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x04 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_ofs3)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x10 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_banksel)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x40 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_bps0)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x44 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_bps1)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x48 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_bps2)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x4C : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_bps3)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x60 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_pbps0)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x64 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_pbps1)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x68 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_pbps2)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x6C : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_pbps3)) + __OPTION_SETTING_NS_End = .; + } > OPTION_SETTING = 0xFF + + /* Symbol required for RA Configuration tool. */ + __tz_OPTION_SETTING_S_S = ORIGIN(OPTION_SETTING_S); + + .option_setting_s : + { + __OPTION_SETTING_S_Start = .; + KEEP(*(.option_setting_ofs1_sec)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x04 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_ofs3_sec)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x10 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_banksel_sec)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x40 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sec0)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x44 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sec1)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x48 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sec2)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x4C : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sec3)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x60 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_pbps_sec0)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x64 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_pbps_sec1)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x68 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_pbps_sec2)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x6C : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_pbps_sec3)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x80 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_ofs1_sel)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x84 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_ofs3_sel)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x90 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_banksel_sel)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0xC0 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sel0)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0xC4 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sel1)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0xC8 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sel2)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0xCC : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sel3)) + __OPTION_SETTING_S_End = .; + } > OPTION_SETTING_S = 0xFF + + /* Symbol required for RA Configuration tool. */ + __tz_OPTION_SETTING_S_N = __OPTION_SETTING_S_End; +} diff --git a/hw/bsp/ra/boards/ra4m3_ek/script/memory_regions.ld b/hw/bsp/ra/boards/ra4m3_ek/script/memory_regions.ld new file mode 100644 index 000000000..04d7de497 --- /dev/null +++ b/hw/bsp/ra/boards/ra4m3_ek/script/memory_regions.ld @@ -0,0 +1,22 @@ + + /* generated memory regions file - do not edit */ + RAM_START = 0x20000000; + RAM_LENGTH = 0x20000; + FLASH_START = 0x00000000; + FLASH_LENGTH = 0x100000; + DATA_FLASH_START = 0x08000000; + DATA_FLASH_LENGTH = 0x2000; + OPTION_SETTING_START = 0x0100A100; + OPTION_SETTING_LENGTH = 0x100; + OPTION_SETTING_S_START = 0x0100A200; + OPTION_SETTING_S_LENGTH = 0x100; + ID_CODE_START = 0x00000000; + ID_CODE_LENGTH = 0x0; + SDRAM_START = 0x80010000; + SDRAM_LENGTH = 0x0; + QSPI_FLASH_START = 0x60000000; + QSPI_FLASH_LENGTH = 0x4000000; + OSPI_DEVICE_0_START = 0x80020000; + OSPI_DEVICE_0_LENGTH = 0x0; + OSPI_DEVICE_1_START = 0x80030000; + OSPI_DEVICE_1_LENGTH = 0x0; diff --git a/hw/bsp/ra/boards/ra4m3_ek/smart_configurator/configuration.xml b/hw/bsp/ra/boards/ra4m3_ek/smart_configurator/configuration.xml new file mode 100644 index 000000000..1d75f1b72 --- /dev/null +++ b/hw/bsp/ra/boards/ra4m3_ek/smart_configurator/configuration.xml @@ -0,0 +1,432 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Simple application that blinks an LED. No RTOS included. + Renesas.RA_baremetal_blinky.5.6.0.pack + + + Board Support Package Common Files + Renesas.RA.5.6.0.pack + + + I/O Port + Renesas.RA.5.6.0.pack + + + Arm CMSIS Version 6 - Core (M) + Arm.CMSIS6.6.1.0+fsp.5.6.0.pack + + + Board support package for R7FA4M3AF3CFB + Renesas.RA_mcu_ra4m3.5.6.0.pack + + + Board support package for RA4M3 + Renesas.RA_mcu_ra4m3.5.6.0.pack + + + Board support package for RA4M3 - FSP Data + Renesas.RA_mcu_ra4m3.5.6.0.pack + + + Board support package for RA4M3 - Events + Renesas.RA_mcu_ra4m3.5.6.0.pack + + + RA4M3-EK Board Support Files + Renesas.RA_board_ra4m3_ek.5.6.0.pack + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/hw/bsp/ra/boards/ra6m1_ek/board.cmake b/hw/bsp/ra/boards/ra6m1_ek/board.cmake index b2f41a354..957e8394d 100644 --- a/hw/bsp/ra/boards/ra6m1_ek/board.cmake +++ b/hw/bsp/ra/boards/ra6m1_ek/board.cmake @@ -1,4 +1,4 @@ -set(CMAKE_SYSTEM_PROCESSOR cortex-m4 CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU cortex-m4 CACHE INTERNAL "System Processor") set(MCU_VARIANT ra6m1) set(JLINK_DEVICE R7FA6M1AD) diff --git a/hw/bsp/ra/boards/ra6m1_ek/board.h b/hw/bsp/ra/boards/ra6m1_ek/board.h index f73a08fc0..2024a0335 100644 --- a/hw/bsp/ra/boards/ra6m1_ek/board.h +++ b/hw/bsp/ra/boards/ra6m1_ek/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: RA6M1 EK + url: https://www.renesas.com/en/products/microcontrollers-microprocessors/ra-cortex-m-mcus/ek-ra6m1-evaluation-kit-ra6m1-mcu-group +*/ + #ifndef _BOARD_H_ #define _BOARD_H_ @@ -31,19 +36,9 @@ extern "C" { #endif -#define LED1 BSP_IO_PORT_01_PIN_12 -#define LED_STATE_ON 1 - -#define SW1 BSP_IO_PORT_04_PIN_15 +#define LED_STATE_ON 1 #define BUTTON_STATE_ACTIVE 0 -static const ioport_pin_cfg_t board_pin_cfg[] = { - { .pin = LED1, .pin_cfg = IOPORT_CFG_PORT_DIRECTION_OUTPUT }, - { .pin = SW1, .pin_cfg = IOPORT_CFG_PORT_DIRECTION_INPUT }, - // USB FS - { .pin = BSP_IO_PORT_04_PIN_07, .pin_cfg = IOPORT_CFG_PERIPHERAL_PIN | IOPORT_PERIPHERAL_USB_FS }, -}; - #ifdef __cplusplus } #endif diff --git a/hw/bsp/ra/boards/ra6m1_ek/fsp_cfg/bsp/bsp_cfg.h b/hw/bsp/ra/boards/ra6m1_ek/fsp_cfg/bsp/bsp_cfg.h deleted file mode 100644 index 772e5e5b1..000000000 --- a/hw/bsp/ra/boards/ra6m1_ek/fsp_cfg/bsp/bsp_cfg.h +++ /dev/null @@ -1,68 +0,0 @@ -/* generated configuration header file - do not edit */ -#ifndef BSP_CFG_H_ -#define BSP_CFG_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "bsp_clock_cfg.h" -#include "bsp_mcu_family_cfg.h" -#include "board_cfg.h" - -#define RA_NOT_DEFINED 0 -#ifndef BSP_CFG_RTOS -#if (RA_NOT_DEFINED) != (2) -#define BSP_CFG_RTOS (2) -#elif (RA_NOT_DEFINED) != (RA_NOT_DEFINED) - #define BSP_CFG_RTOS (1) -#else - #define BSP_CFG_RTOS (0) -#endif -#endif - -#ifndef BSP_CFG_RTC_USED -#define BSP_CFG_RTC_USED (RA_NOT_DEFINED) -#endif - -#undef RA_NOT_DEFINED -#if defined(_RA_BOOT_IMAGE) - #define BSP_CFG_BOOT_IMAGE (1) -#endif - -#define BSP_CFG_MCU_VCC_MV (3300) -#define BSP_CFG_STACK_MAIN_BYTES (0x1000) -#define BSP_CFG_HEAP_BYTES (0x1000) -#define BSP_CFG_PARAM_CHECKING_ENABLE (1) -#define BSP_CFG_ASSERT (0) -#define BSP_CFG_ERROR_LOG (0) - -#define BSP_CFG_PFS_PROTECT ((1)) - -#define BSP_CFG_C_RUNTIME_INIT ((1)) -#define BSP_CFG_EARLY_INIT ((0)) - -#define BSP_CFG_STARTUP_CLOCK_REG_NOT_RESET ((0)) - -#ifndef BSP_CLOCK_CFG_MAIN_OSC_POPULATED -#define BSP_CLOCK_CFG_MAIN_OSC_POPULATED (1) -#endif - -#ifndef BSP_CLOCK_CFG_MAIN_OSC_CLOCK_SOURCE -#define BSP_CLOCK_CFG_MAIN_OSC_CLOCK_SOURCE (0) -#endif -#ifndef BSP_CLOCK_CFG_SUBCLOCK_DRIVE -#define BSP_CLOCK_CFG_SUBCLOCK_DRIVE (0) -#endif -#ifndef BSP_CLOCK_CFG_SUBCLOCK_POPULATED -#define BSP_CLOCK_CFG_SUBCLOCK_POPULATED (1) -#endif -#ifndef BSP_CLOCK_CFG_SUBCLOCK_STABILIZATION_MS -#define BSP_CLOCK_CFG_SUBCLOCK_STABILIZATION_MS 1000 -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* BSP_CFG_H_ */ diff --git a/hw/bsp/ra/boards/ra6m1_ek/fsp_cfg/bsp/bsp_mcu_device_pn_cfg.h b/hw/bsp/ra/boards/ra6m1_ek/fsp_cfg/bsp/bsp_mcu_device_pn_cfg.h deleted file mode 100644 index 40bb3a3bf..000000000 --- a/hw/bsp/ra/boards/ra6m1_ek/fsp_cfg/bsp/bsp_mcu_device_pn_cfg.h +++ /dev/null @@ -1,11 +0,0 @@ -/* generated configuration header file - do not edit */ -#ifndef BSP_MCU_DEVICE_PN_CFG_H_ -#define BSP_MCU_DEVICE_PN_CFG_H_ -#define BSP_MCU_R7FA6M1AD3CFP -#define BSP_MCU_FEATURE_SET ('A') -#define BSP_ROM_SIZE_BYTES (524288) -#define BSP_RAM_SIZE_BYTES (262144) -#define BSP_DATA_FLASH_SIZE_BYTES (8192) -#define BSP_PACKAGE_LQFP -#define BSP_PACKAGE_PINS (100) -#endif /* BSP_MCU_DEVICE_PN_CFG_H_ */ diff --git a/hw/bsp/ra/boards/ra6m1_ek/fsp_cfg/bsp/bsp_mcu_family_cfg.h b/hw/bsp/ra/boards/ra6m1_ek/fsp_cfg/bsp/bsp_mcu_family_cfg.h deleted file mode 100644 index 5fedd754f..000000000 --- a/hw/bsp/ra/boards/ra6m1_ek/fsp_cfg/bsp/bsp_mcu_family_cfg.h +++ /dev/null @@ -1,84 +0,0 @@ -/* generated configuration header file - do not edit */ -#ifndef BSP_MCU_FAMILY_CFG_H_ -#define BSP_MCU_FAMILY_CFG_H_ -#ifdef __cplusplus -extern "C" { -#endif - -#include "bsp_mcu_device_pn_cfg.h" -#include "bsp_mcu_device_cfg.h" -#include "../../../ra/fsp/src/bsp/mcu/ra6m1/bsp_mcu_info.h" -#include "bsp_clock_cfg.h" - -#define BSP_MCU_GROUP_RA6M1 (1) -#define BSP_LOCO_HZ (32768) -#define BSP_MOCO_HZ (8000000) -#define BSP_SUB_CLOCK_HZ (32768) -#if BSP_CFG_HOCO_FREQUENCY == 0 -#define BSP_HOCO_HZ (16000000) -#elif BSP_CFG_HOCO_FREQUENCY == 1 - #define BSP_HOCO_HZ (18000000) -#elif BSP_CFG_HOCO_FREQUENCY == 2 - #define BSP_HOCO_HZ (20000000) -#else - #error "Invalid HOCO frequency chosen (BSP_CFG_HOCO_FREQUENCY) in bsp_clock_cfg.h" -#endif - -#define BSP_CFG_FLL_ENABLE (0) - -#define BSP_CORTEX_VECTOR_TABLE_ENTRIES (16U) -#define BSP_VECTOR_TABLE_MAX_ENTRIES (112U) - -#define OFS_SEQ1 0xA001A001 | (1 << 1) | (3 << 2) -#define OFS_SEQ2 (15 << 4) | (3 << 8) | (3 << 10) -#define OFS_SEQ3 (1 << 12) | (1 << 14) | (1 << 17) -#define OFS_SEQ4 (3 << 18) |(15 << 20) | (3 << 24) | (3 << 26) -#define OFS_SEQ5 (1 << 28) | (1 << 30) -#define BSP_CFG_ROM_REG_OFS0 (OFS_SEQ1 | OFS_SEQ2 | OFS_SEQ3 | OFS_SEQ4 | OFS_SEQ5) -#define BSP_CFG_ROM_REG_OFS1 (0xFFFFFEF8 | (1 << 2) | (3) | (1 << 8)) -#define BSP_CFG_ROM_REG_MPU_PC0_ENABLE (1) -#define BSP_CFG_ROM_REG_MPU_PC0_START (0xFFFFFFFC) -#define BSP_CFG_ROM_REG_MPU_PC0_END (0xFFFFFFFF) -#define BSP_CFG_ROM_REG_MPU_PC1_ENABLE (1) -#define BSP_CFG_ROM_REG_MPU_PC1_START (0xFFFFFFFC) -#define BSP_CFG_ROM_REG_MPU_PC1_END (0xFFFFFFFF) -#define BSP_CFG_ROM_REG_MPU_REGION0_ENABLE (1) -#define BSP_CFG_ROM_REG_MPU_REGION0_START (0x00FFFFFC) -#define BSP_CFG_ROM_REG_MPU_REGION0_END (0x00FFFFFF) -#define BSP_CFG_ROM_REG_MPU_REGION1_ENABLE (1) -#define BSP_CFG_ROM_REG_MPU_REGION1_START (0x200FFFFC) -#define BSP_CFG_ROM_REG_MPU_REGION1_END (0x200FFFFF) -#define BSP_CFG_ROM_REG_MPU_REGION2_ENABLE (1) -#define BSP_CFG_ROM_REG_MPU_REGION2_START (0x407FFFFC) -#define BSP_CFG_ROM_REG_MPU_REGION2_END (0x407FFFFF) -#define BSP_CFG_ROM_REG_MPU_REGION3_ENABLE (1) -#define BSP_CFG_ROM_REG_MPU_REGION3_START (0x400DFFFC) -#define BSP_CFG_ROM_REG_MPU_REGION3_END (0x400DFFFF) -#ifndef BSP_CLOCK_CFG_MAIN_OSC_WAIT -#define BSP_CLOCK_CFG_MAIN_OSC_WAIT (9) -#endif -/* Used to create IELS values for the interrupt initialization table g_interrupt_event_link_select. */ -#define BSP_PRV_IELS_ENUM(vector) (ELC_ ## vector) - -/* - ID Code - Note: To permanently lock and disable the debug interface define the BSP_ID_CODE_PERMANENTLY_LOCKED in the compiler settings. - WARNING: This will disable debug access to the part and cannot be reversed by a debug probe. - */ -#if defined(BSP_ID_CODE_PERMANENTLY_LOCKED) - #define BSP_CFG_ID_CODE_LONG_1 (0x00000000) - #define BSP_CFG_ID_CODE_LONG_2 (0x00000000) - #define BSP_CFG_ID_CODE_LONG_3 (0x00000000) - #define BSP_CFG_ID_CODE_LONG_4 (0x00000000) -#else - /* ID CODE: FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF */ - #define BSP_CFG_ID_CODE_LONG_1 (0xFFFFFFFF) - #define BSP_CFG_ID_CODE_LONG_2 (0xFFFFFFFF) - #define BSP_CFG_ID_CODE_LONG_3 (0xFFFFFFFF) - #define BSP_CFG_ID_CODE_LONG_4 (0xffFFFFFF) -#endif - -#ifdef __cplusplus -} -#endif -#endif /* BSP_MCU_FAMILY_CFG_H_ */ diff --git a/hw/bsp/ra/boards/ra6m1_ek/ra_cfg/fsp_cfg/bsp/bsp_cfg.h b/hw/bsp/ra/boards/ra6m1_ek/ra_cfg/fsp_cfg/bsp/bsp_cfg.h new file mode 100644 index 000000000..90afbdef3 --- /dev/null +++ b/hw/bsp/ra/boards/ra6m1_ek/ra_cfg/fsp_cfg/bsp/bsp_cfg.h @@ -0,0 +1,62 @@ +/* generated configuration header file - do not edit */ +#ifndef BSP_CFG_H_ +#define BSP_CFG_H_ +#ifdef __cplusplus + extern "C" { + #endif + + #include "bsp_clock_cfg.h" + #include "bsp_mcu_family_cfg.h" + #include "board_cfg.h" + #define RA_NOT_DEFINED 0 + #ifndef BSP_CFG_RTOS + #if (RA_NOT_DEFINED) != (RA_NOT_DEFINED) + #define BSP_CFG_RTOS (2) + #elif (RA_NOT_DEFINED) != (RA_NOT_DEFINED) + #define BSP_CFG_RTOS (1) + #else + #define BSP_CFG_RTOS (0) + #endif + #endif + #ifndef BSP_CFG_RTC_USED + #define BSP_CFG_RTC_USED (RA_NOT_DEFINED) + #endif + #undef RA_NOT_DEFINED + #if defined(_RA_BOOT_IMAGE) + #define BSP_CFG_BOOT_IMAGE (1) + #endif + #define BSP_CFG_MCU_VCC_MV (3300) + #define BSP_CFG_STACK_MAIN_BYTES (0x1000) + #define BSP_CFG_HEAP_BYTES (0x1000) + #define BSP_CFG_PARAM_CHECKING_ENABLE (0) + #define BSP_CFG_ASSERT (0) + #define BSP_CFG_ERROR_LOG (0) + + #define BSP_CFG_PFS_PROTECT ((1)) + + #define BSP_CFG_C_RUNTIME_INIT ((1)) + #define BSP_CFG_EARLY_INIT ((0)) + + #define BSP_CFG_STARTUP_CLOCK_REG_NOT_RESET ((0)) + + #ifndef BSP_CLOCK_CFG_MAIN_OSC_POPULATED + #define BSP_CLOCK_CFG_MAIN_OSC_POPULATED (1) + #endif + + #ifndef BSP_CLOCK_CFG_MAIN_OSC_CLOCK_SOURCE + #define BSP_CLOCK_CFG_MAIN_OSC_CLOCK_SOURCE (0) + #endif + #ifndef BSP_CLOCK_CFG_SUBCLOCK_DRIVE + #define BSP_CLOCK_CFG_SUBCLOCK_DRIVE (0) + #endif + #ifndef BSP_CLOCK_CFG_SUBCLOCK_POPULATED + #define BSP_CLOCK_CFG_SUBCLOCK_POPULATED (1) + #endif + #ifndef BSP_CLOCK_CFG_SUBCLOCK_STABILIZATION_MS + #define BSP_CLOCK_CFG_SUBCLOCK_STABILIZATION_MS 1000 + #endif + + #ifdef __cplusplus + } + #endif +#endif /* BSP_CFG_H_ */ diff --git a/hw/bsp/ra/boards/ra6m1_ek/fsp_cfg/bsp/bsp_mcu_device_cfg.h b/hw/bsp/ra/boards/ra6m1_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_device_cfg.h similarity index 100% rename from hw/bsp/ra/boards/ra6m1_ek/fsp_cfg/bsp/bsp_mcu_device_cfg.h rename to hw/bsp/ra/boards/ra6m1_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_device_cfg.h diff --git a/hw/bsp/ra/boards/ra6m1_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_device_pn_cfg.h b/hw/bsp/ra/boards/ra6m1_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_device_pn_cfg.h new file mode 100644 index 000000000..5e7841442 --- /dev/null +++ b/hw/bsp/ra/boards/ra6m1_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_device_pn_cfg.h @@ -0,0 +1,11 @@ +/* generated configuration header file - do not edit */ +#ifndef BSP_MCU_DEVICE_PN_CFG_H_ +#define BSP_MCU_DEVICE_PN_CFG_H_ +#define BSP_MCU_R7FA6M1AD3CFP + #define BSP_MCU_FEATURE_SET ('A') + #define BSP_ROM_SIZE_BYTES (524288) + #define BSP_RAM_SIZE_BYTES (262144) + #define BSP_DATA_FLASH_SIZE_BYTES (8192) + #define BSP_PACKAGE_LQFP + #define BSP_PACKAGE_PINS (100) +#endif /* BSP_MCU_DEVICE_PN_CFG_H_ */ diff --git a/hw/bsp/ra/boards/ra6m1_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_family_cfg.h b/hw/bsp/ra/boards/ra6m1_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_family_cfg.h new file mode 100644 index 000000000..16349b5ff --- /dev/null +++ b/hw/bsp/ra/boards/ra6m1_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_family_cfg.h @@ -0,0 +1,84 @@ +/* generated configuration header file - do not edit */ +#ifndef BSP_MCU_FAMILY_CFG_H_ +#define BSP_MCU_FAMILY_CFG_H_ +#ifdef __cplusplus + extern "C" { + #endif + + #include "bsp_mcu_device_pn_cfg.h" + #include "bsp_mcu_device_cfg.h" + #include "../../../ra/fsp/src/bsp/mcu/ra6m1/bsp_mcu_info.h" + #include "bsp_clock_cfg.h" + #define BSP_MCU_GROUP_RA6M1 (1) + #define BSP_LOCO_HZ (32768) + #define BSP_MOCO_HZ (8000000) + #define BSP_SUB_CLOCK_HZ (32768) + #if BSP_CFG_HOCO_FREQUENCY == 0 + #define BSP_HOCO_HZ (16000000) + #elif BSP_CFG_HOCO_FREQUENCY == 1 + #define BSP_HOCO_HZ (18000000) + #elif BSP_CFG_HOCO_FREQUENCY == 2 + #define BSP_HOCO_HZ (20000000) + #else + #error "Invalid HOCO frequency chosen (BSP_CFG_HOCO_FREQUENCY) in bsp_clock_cfg.h" + #endif + + #define BSP_CFG_FLL_ENABLE (0) + + #define BSP_CORTEX_VECTOR_TABLE_ENTRIES (16U) + #define BSP_VECTOR_TABLE_MAX_ENTRIES (112U) + #define BSP_CFG_INLINE_IRQ_FUNCTIONS (1) + + #define OFS_SEQ1 0xA001A001 | (1 << 1) | (3 << 2) + #define OFS_SEQ2 (15 << 4) | (3 << 8) | (3 << 10) + #define OFS_SEQ3 (1 << 12) | (1 << 14) | (1 << 17) + #define OFS_SEQ4 (3 << 18) |(15 << 20) | (3 << 24) | (3 << 26) + #define OFS_SEQ5 (1 << 28) | (1 << 30) + #define BSP_CFG_ROM_REG_OFS0 (OFS_SEQ1 | OFS_SEQ2 | OFS_SEQ3 | OFS_SEQ4 | OFS_SEQ5) + #define BSP_CFG_ROM_REG_OFS1 (0xFFFFFEF8 | (1 << 2) | (3) | (1 << 8)) + #define BSP_CFG_ROM_REG_MPU_PC0_ENABLE (1) + #define BSP_CFG_ROM_REG_MPU_PC0_START (0xFFFFFFFC) + #define BSP_CFG_ROM_REG_MPU_PC0_END (0xFFFFFFFF) + #define BSP_CFG_ROM_REG_MPU_PC1_ENABLE (1) + #define BSP_CFG_ROM_REG_MPU_PC1_START (0xFFFFFFFC) + #define BSP_CFG_ROM_REG_MPU_PC1_END (0xFFFFFFFF) + #define BSP_CFG_ROM_REG_MPU_REGION0_ENABLE (1) + #define BSP_CFG_ROM_REG_MPU_REGION0_START (0x00FFFFFC) + #define BSP_CFG_ROM_REG_MPU_REGION0_END (0x00FFFFFF) + #define BSP_CFG_ROM_REG_MPU_REGION1_ENABLE (1) + #define BSP_CFG_ROM_REG_MPU_REGION1_START (0x200FFFFC) + #define BSP_CFG_ROM_REG_MPU_REGION1_END (0x200FFFFF) + #define BSP_CFG_ROM_REG_MPU_REGION2_ENABLE (1) + #define BSP_CFG_ROM_REG_MPU_REGION2_START (0x407FFFFC) + #define BSP_CFG_ROM_REG_MPU_REGION2_END (0x407FFFFF) + #define BSP_CFG_ROM_REG_MPU_REGION3_ENABLE (1) + #define BSP_CFG_ROM_REG_MPU_REGION3_START (0x400DFFFC) + #define BSP_CFG_ROM_REG_MPU_REGION3_END (0x400DFFFF) + #ifndef BSP_CLOCK_CFG_MAIN_OSC_WAIT + #define BSP_CLOCK_CFG_MAIN_OSC_WAIT (9) + #endif + /* Used to create IELS values for the interrupt initialization table g_interrupt_event_link_select. */ + #define BSP_PRV_IELS_ENUM(vector) (ELC_ ## vector) + + /* + ID Code + Note: To lock and disable the debug interface define BSP_ID_CODE_LOCKED in compiler settings. + WARNING: This will disable debug access to the part. However, ALeRASE command will be accepted, which will clear (reset) the ID code. After clearing ID code, debug access will be enabled. + */ + #if defined(BSP_ID_CODE_LOCKED) + #define BSP_CFG_ID_CODE_LONG_1 (0x00000000) + #define BSP_CFG_ID_CODE_LONG_2 (0x00000000) + #define BSP_CFG_ID_CODE_LONG_3 (0x00000000) + #define BSP_CFG_ID_CODE_LONG_4 (0x00000000) + #else + /* ID CODE: FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF */ + #define BSP_CFG_ID_CODE_LONG_1 (0xFFFFFFFF) + #define BSP_CFG_ID_CODE_LONG_2 (0xFFFFFFFF) + #define BSP_CFG_ID_CODE_LONG_3 (0xFFFFFFFF) + #define BSP_CFG_ID_CODE_LONG_4 (0xffFFFFFF) + #endif + + #ifdef __cplusplus + } + #endif +#endif /* BSP_MCU_FAMILY_CFG_H_ */ diff --git a/hw/bsp/ra/boards/ra6m1_ek/ra_cfg/fsp_cfg/bsp/bsp_pin_cfg.h b/hw/bsp/ra/boards/ra6m1_ek/ra_cfg/fsp_cfg/bsp/bsp_pin_cfg.h new file mode 100644 index 000000000..8ba9aafba --- /dev/null +++ b/hw/bsp/ra/boards/ra6m1_ek/ra_cfg/fsp_cfg/bsp/bsp_pin_cfg.h @@ -0,0 +1,17 @@ +/* generated configuration header file - do not edit */ +#ifndef BSP_PIN_CFG_H_ +#define BSP_PIN_CFG_H_ +#include "r_ioport.h" + +/* Common macro for FSP header files. There is also a corresponding FSP_FOOTER macro at the end of this file. */ +FSP_HEADER + +#define LED1 (BSP_IO_PORT_01_PIN_12) +#define SW1 (BSP_IO_PORT_04_PIN_15) +extern const ioport_cfg_t g_bsp_pin_cfg; /* RA6M1-EK.pincfg */ + +void BSP_PinConfigSecurityInit(); + +/* Common macro for FSP header files. There is also a corresponding FSP_HEADER macro at the top of this file. */ +FSP_FOOTER +#endif /* BSP_PIN_CFG_H_ */ diff --git a/hw/bsp/ra/boards/ra6m1_ek/ra_cfg/fsp_cfg/r_ioport_cfg.h b/hw/bsp/ra/boards/ra6m1_ek/ra_cfg/fsp_cfg/r_ioport_cfg.h new file mode 100644 index 000000000..d2688bf5b --- /dev/null +++ b/hw/bsp/ra/boards/ra6m1_ek/ra_cfg/fsp_cfg/r_ioport_cfg.h @@ -0,0 +1,13 @@ +/* generated configuration header file - do not edit */ +#ifndef R_IOPORT_CFG_H_ +#define R_IOPORT_CFG_H_ +#ifdef __cplusplus +extern "C" { +#endif + +#define IOPORT_CFG_PARAM_CHECKING_ENABLE (BSP_CFG_PARAM_CHECKING_ENABLE) + +#ifdef __cplusplus +} +#endif +#endif /* R_IOPORT_CFG_H_ */ diff --git a/hw/bsp/ra/boards/ra6m1_ek/fsp_cfg/bsp_clock_cfg.h b/hw/bsp/ra/boards/ra6m1_ek/ra_gen/bsp_clock_cfg.h similarity index 100% rename from hw/bsp/ra/boards/ra6m1_ek/fsp_cfg/bsp_clock_cfg.h rename to hw/bsp/ra/boards/ra6m1_ek/ra_gen/bsp_clock_cfg.h diff --git a/hw/bsp/ra/boards/ra6m1_ek/ra_gen/common_data.c b/hw/bsp/ra/boards/ra6m1_ek/ra_gen/common_data.c new file mode 100644 index 000000000..50036c0ad --- /dev/null +++ b/hw/bsp/ra/boards/ra6m1_ek/ra_gen/common_data.c @@ -0,0 +1,11 @@ +/* generated common source file - do not edit */ +#include "common_data.h" +ioport_instance_ctrl_t g_ioport_ctrl; +const ioport_instance_t g_ioport = + { + .p_api = &g_ioport_on_ioport, + .p_ctrl = &g_ioport_ctrl, + .p_cfg = &g_bsp_pin_cfg, + }; +void g_common_init(void) { +} diff --git a/hw/bsp/ra/boards/ra6m1_ek/ra_gen/common_data.h b/hw/bsp/ra/boards/ra6m1_ek/ra_gen/common_data.h new file mode 100644 index 000000000..6a08cbee0 --- /dev/null +++ b/hw/bsp/ra/boards/ra6m1_ek/ra_gen/common_data.h @@ -0,0 +1,20 @@ +/* generated common header file - do not edit */ +#ifndef COMMON_DATA_H_ +#define COMMON_DATA_H_ +#include +#include "bsp_api.h" +#include "r_ioport.h" +#include "bsp_pin_cfg.h" +FSP_HEADER +#define IOPORT_CFG_NAME g_bsp_pin_cfg +#define IOPORT_CFG_OPEN R_IOPORT_Open +#define IOPORT_CFG_CTRL g_ioport_ctrl + +/* IOPORT Instance */ +extern const ioport_instance_t g_ioport; + +/* IOPORT control structure. */ +extern ioport_instance_ctrl_t g_ioport_ctrl; +void g_common_init(void); +FSP_FOOTER +#endif /* COMMON_DATA_H_ */ diff --git a/hw/bsp/ra/boards/ra6m1_ek/ra_gen/pin_data.c b/hw/bsp/ra/boards/ra6m1_ek/ra_gen/pin_data.c new file mode 100644 index 000000000..80774b0a5 --- /dev/null +++ b/hw/bsp/ra/boards/ra6m1_ek/ra_gen/pin_data.c @@ -0,0 +1,115 @@ +/* generated pin source file - do not edit */ +#include "bsp_api.h" +#include "r_ioport.h" + + +const ioport_pin_cfg_t g_bsp_pin_cfg_data[] = { + { + .pin = BSP_IO_PORT_00_PIN_04, + .pin_cfg = ((uint32_t) IOPORT_CFG_ANALOG_ENABLE) + }, + { + .pin = BSP_IO_PORT_01_PIN_00, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SPI) + }, + { + .pin = BSP_IO_PORT_01_PIN_01, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SPI) + }, + { + .pin = BSP_IO_PORT_01_PIN_02, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SPI) + }, + { + .pin = BSP_IO_PORT_01_PIN_03, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SPI) + }, + { + .pin = BSP_IO_PORT_01_PIN_04, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SCI0_2_4_6_8) + }, + { + .pin = BSP_IO_PORT_01_PIN_05, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SCI0_2_4_6_8) + }, + { + .pin = BSP_IO_PORT_01_PIN_06, + .pin_cfg = ((uint32_t) IOPORT_CFG_PORT_DIRECTION_OUTPUT | (uint32_t) IOPORT_CFG_PORT_OUTPUT_LOW) + }, + { + .pin = BSP_IO_PORT_01_PIN_07, + .pin_cfg = ((uint32_t) IOPORT_CFG_PORT_DIRECTION_OUTPUT | (uint32_t) IOPORT_CFG_PORT_OUTPUT_LOW) + }, + { + .pin = BSP_IO_PORT_01_PIN_08, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_DEBUG) + }, + { + .pin = BSP_IO_PORT_01_PIN_12, + .pin_cfg = ((uint32_t) IOPORT_CFG_PORT_DIRECTION_OUTPUT | (uint32_t) IOPORT_CFG_PORT_OUTPUT_LOW) + }, + { + .pin = BSP_IO_PORT_02_PIN_01, + .pin_cfg = ((uint32_t) IOPORT_CFG_PORT_DIRECTION_INPUT) + }, + { + .pin = BSP_IO_PORT_02_PIN_05, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_CTSU) + }, + { + .pin = BSP_IO_PORT_02_PIN_07, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_CTSU) + }, + { + .pin = BSP_IO_PORT_03_PIN_00, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_DEBUG) + }, + { + .pin = BSP_IO_PORT_04_PIN_07, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_USB_FS) + }, + { + .pin = BSP_IO_PORT_04_PIN_15, + .pin_cfg = ((uint32_t) IOPORT_CFG_PORT_DIRECTION_INPUT | (uint32_t) IOPORT_CFG_PULLUP_ENABLE) + }, +}; + +const ioport_cfg_t g_bsp_pin_cfg = { + .number_of_pins = sizeof(g_bsp_pin_cfg_data)/sizeof(ioport_pin_cfg_t), + .p_pin_cfg_data = &g_bsp_pin_cfg_data[0], +}; + +#if BSP_TZ_SECURE_BUILD + +void R_BSP_PinCfgSecurityInit(void); + +/* Initialize SAR registers for secure pins. */ +void R_BSP_PinCfgSecurityInit(void) +{ + #if (2U == BSP_FEATURE_IOPORT_VERSION) + uint32_t pmsar[BSP_FEATURE_BSP_NUM_PMSAR]; + #else + uint16_t pmsar[BSP_FEATURE_BSP_NUM_PMSAR]; + #endif + memset(pmsar, 0xFF, BSP_FEATURE_BSP_NUM_PMSAR * sizeof(R_PMISC->PMSAR[0])); + + + for(uint32_t i = 0; i < g_bsp_pin_cfg.number_of_pins; i++) + { + uint32_t port_pin = g_bsp_pin_cfg.p_pin_cfg_data[i].pin; + uint32_t port = port_pin >> 8U; + uint32_t pin = port_pin & 0xFFU; + pmsar[port] &= (uint16_t) ~(1U << pin); + } + + for(uint32_t i = 0; i < BSP_FEATURE_BSP_NUM_PMSAR; i++) + { + #if (2U == BSP_FEATURE_IOPORT_VERSION) + R_PMISC->PMSAR[i].PMSAR = (uint16_t) pmsar[i]; + #else + R_PMISC->PMSAR[i].PMSAR = pmsar[i]; + #endif + } + +} +#endif diff --git a/hw/bsp/ra/boards/ra6m1_ek/script/fsp.ld b/hw/bsp/ra/boards/ra6m1_ek/script/fsp.ld new file mode 100644 index 000000000..605eef7d2 --- /dev/null +++ b/hw/bsp/ra/boards/ra6m1_ek/script/fsp.ld @@ -0,0 +1,769 @@ +/* + Linker File for Renesas FSP +*/ + +INCLUDE memory_regions.ld + +/* Uncomment and set XIP_SECONDARY_SLOT_IMAGE to 1 below for the secondary XIP application image.*/ +/* + XIP_SECONDARY_SLOT_IMAGE = 1; +*/ + +QSPI_FLASH_PRV_LENGTH = DEFINED(QSPI_FLASH_SIZE) ? ABSOLUTE(QSPI_FLASH_SIZE) : ABSOLUTE(QSPI_FLASH_LENGTH); +OSPI_DEVICE_0_PRV_LENGTH = DEFINED(OSPI_DEVICE_0_SIZE) ? ABSOLUTE(OSPI_DEVICE_0_SIZE) : ABSOLUTE(OSPI_DEVICE_0_LENGTH); +OSPI_DEVICE_1_PRV_LENGTH = DEFINED(OSPI_DEVICE_1_SIZE) ? ABSOLUTE(OSPI_DEVICE_1_SIZE) : ABSOLUTE(OSPI_DEVICE_1_LENGTH); + +/* If a flat (secure) project has DEFINED RAM_NS_BUFFER_LENGTH, then emit IDAU symbols to allocate non-secure RAM. */ +__RESERVE_NS_RAM = !DEFINED(PROJECT_NONSECURE) && DEFINED(RAM_NS_BUFFER_LENGTH) && (OPTION_SETTING_S_LENGTH != 0); + +ITCM_START = DEFINED(ITCM_START)? ITCM_START : 0; +ITCM_LENGTH = DEFINED(ITCM_LENGTH)? ITCM_LENGTH : 0; +DTCM_START = DEFINED(DTCM_START)? DTCM_START : 0; +DTCM_LENGTH = DEFINED(DTCM_LENGTH)? DTCM_LENGTH : 0; +RAM_NS_BUFFER_BLOCK_LENGTH = DEFINED(RAM_NS_BUFFER_LENGTH) ? ALIGN(RAM_NS_BUFFER_LENGTH, 8192) : 0; +RAM_NS_BUFFER_LENGTH = DEFINED(RAM_NS_BUFFER_LENGTH) ? RAM_NS_BUFFER_LENGTH : 0; +RAM_NS_BUFFER_START = RAM_START + RAM_LENGTH - RAM_NS_BUFFER_LENGTH; +RAM_NS_BUFFER_BLOCK_START = RAM_START + RAM_LENGTH - RAM_NS_BUFFER_BLOCK_LENGTH; + +OPTION_SETTING_START_NS = DEFINED(PROJECT_NONSECURE) ? OPTION_SETTING_START : OPTION_SETTING_START + 0x80; + +/* This definition is used to avoid moving the counter in OPTION_SETTING regions for projects that should not configure option settings. + * Bootloader images do not configure option settings because they are owned by the bootloader. + * FSP_BOOTABLE_IMAGE is only defined in bootloader images. */ +__bl_FSP_BOOTABLE_IMAGE = 1; +__bln_FSP_BOOTABLE_IMAGE = 1; +PROJECT_SECURE_OR_FLAT = (!DEFINED(PROJECT_NONSECURE) || DEFINED(PROJECT_SECURE)) && OPTION_SETTING_LENGTH && !DEFINED(FSP_BOOTABLE_IMAGE); +USE_OPTION_SETTING_NS = DEFINED(PROJECT_NONSECURE) && !DEFINED(FSP_BOOTABLE_IMAGE); + +__bl_FLASH_IMAGE_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_IMAGE_NUMBER == 1 ? FLASH_START + FLASH_BOOTLOADER_LENGTH + FLASH_BOOTLOADER_HEADER_LENGTH : + (DEFINED(BOOTLOADER_SECONDARY_USE_QSPI) || DEFINED(BOOTLOADER_SECONDARY_USE_OSPI_B)) ? FLASH_START + FLASH_BOOTLOADER_LENGTH + FLASH_BOOTLOADER_SCRATCH_LENGTH + FLASH_BOOTLOADER_HEADER_LENGTH : + FLASH_START + FLASH_BOOTLOADER_LENGTH + FLASH_BOOTLOADER_SCRATCH_LENGTH + FLASH_APPLICATION_S_LENGTH + FLASH_BOOTLOADER_HEADER_LENGTH; +__bl_FLASH_IMAGE_LENGTH = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_S_LENGTH - FLASH_BOOTLOADER_HEADER_LENGTH; +__bl_FLASH_IMAGE_END = __bl_FLASH_IMAGE_START + __bl_FLASH_IMAGE_LENGTH; +__bl_XIP_SECONDARY_FLASH_IMAGE_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_START + FLASH_BOOTLOADER_LENGTH + FLASH_APPLICATION_S_LENGTH + FLASH_BOOTLOADER_HEADER_LENGTH; +__bl_XIP_SECONDARY_FLASH_IMAGE_END = __bl_XIP_SECONDARY_FLASH_IMAGE_START + __bl_FLASH_IMAGE_LENGTH; +__bl_FLASH_NS_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_NS_LENGTH == 0 ? __bl_FLASH_IMAGE_END : + __bl_FLASH_IMAGE_START - FLASH_BOOTLOADER_HEADER_LENGTH + FLASH_APPLICATION_S_LENGTH; +__bl_FLASH_NSC_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_NS_LENGTH == 0 ? __bl_FLASH_IMAGE_END : + __bl_FLASH_IMAGE_END - FLASH_APPLICATION_NSC_LENGTH; +__bl_RAM_NS_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_NS_LENGTH == 0 ? RAM_START + RAM_LENGTH : + RAM_START + RAM_LENGTH - RAM_APPLICATION_NS_LENGTH; +__bl_RAM_NSC_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_NS_LENGTH == 0 ? RAM_START + RAM_LENGTH : + __bl_RAM_NS_START - RAM_APPLICATION_NSC_LENGTH; +__bl_FLASH_NS_IMAGE_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_NS_LENGTH == 0 ? __bl_FLASH_IMAGE_END : + __bl_FLASH_NS_START + FLASH_BOOTLOADER_HEADER_LENGTH_2; +__bln_FLASH_IMAGE_START = __bl_FLASH_NS_IMAGE_START | (!DEFINED (NS_OFFSET_START) ? 0 : NS_OFFSET_START); +__bln_FLASH_IMAGE_LENGTH = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_NS_LENGTH == 0 ? __bl_FLASH_IMAGE_END : + FLASH_APPLICATION_NS_LENGTH - FLASH_BOOTLOADER_HEADER_LENGTH_2; + +XIP_SECONDARY_SLOT_IMAGE = DEFINED(XIP_SECONDARY_SLOT_IMAGE) ? XIP_SECONDARY_SLOT_IMAGE : 0; +FLASH_ORIGIN = !DEFINED(FLASH_IMAGE_START) ? FLASH_START : + XIP_SECONDARY_SLOT_IMAGE == 1 ? XIP_SECONDARY_FLASH_IMAGE_START : + FLASH_IMAGE_START; +LIMITED_FLASH_LENGTH = DEFINED(FLASH_IMAGE_LENGTH) ? FLASH_IMAGE_LENGTH : + DEFINED(FLASH_BOOTLOADER_LENGTH) ? FLASH_BOOTLOADER_LENGTH : + FLASH_LENGTH; +OPTION_SETTING_SAS_SIZE = 0x34; +OPTION_SETTING_SAS_LENGTH = !DEFINED(OPTION_SETTING_LENGTH) ? 0 : + OPTION_SETTING_LENGTH == 0 ? 0 : + OPTION_SETTING_LENGTH - OPTION_SETTING_SAS_SIZE; + +/* Define memory regions. */ +MEMORY +{ + ITCM (rx) : ORIGIN = ITCM_START, LENGTH = ITCM_LENGTH + DTCM (rwx) : ORIGIN = DTCM_START, LENGTH = DTCM_LENGTH + FLASH (rx) : ORIGIN = FLASH_ORIGIN, LENGTH = LIMITED_FLASH_LENGTH + RAM (rwx) : ORIGIN = RAM_START, LENGTH = RAM_LENGTH + DATA_FLASH (rx) : ORIGIN = DATA_FLASH_START, LENGTH = DATA_FLASH_LENGTH + QSPI_FLASH (rx) : ORIGIN = QSPI_FLASH_START, LENGTH = QSPI_FLASH_PRV_LENGTH + OSPI_DEVICE_0 (rx) : ORIGIN = OSPI_DEVICE_0_START, LENGTH = OSPI_DEVICE_0_PRV_LENGTH + OSPI_DEVICE_1 (rx) : ORIGIN = OSPI_DEVICE_1_START, LENGTH = OSPI_DEVICE_1_PRV_LENGTH + OSPI_DEVICE_0_RAM (rwx) : ORIGIN = OSPI_DEVICE_0_START, LENGTH = OSPI_DEVICE_0_PRV_LENGTH + OSPI_DEVICE_1_RAM (rwx) : ORIGIN = OSPI_DEVICE_1_START, LENGTH = OSPI_DEVICE_1_PRV_LENGTH + SDRAM (rwx) : ORIGIN = SDRAM_START, LENGTH = SDRAM_LENGTH + OPTION_SETTING (r) : ORIGIN = OPTION_SETTING_START, LENGTH = OPTION_SETTING_LENGTH + OPTION_SETTING_OFS (r) : ORIGIN = OPTION_SETTING_START, LENGTH = 0x18 + OPTION_SETTING_SAS (r) : ORIGIN = OPTION_SETTING_START + OPTION_SETTING_SAS_SIZE, LENGTH = OPTION_SETTING_SAS_LENGTH + OPTION_SETTING_S (r) : ORIGIN = OPTION_SETTING_S_START, LENGTH = OPTION_SETTING_S_LENGTH + ID_CODE (rx) : ORIGIN = ID_CODE_START, LENGTH = ID_CODE_LENGTH +} + +/* Library configurations */ +GROUP(libgcc.a libc.a libm.a) + +/* Linker script to place sections and symbol values. Should be used together + * with other linker script that defines memory regions FLASH and RAM. + * It references following symbols, which must be DEFINED in code: + * Reset_Handler : Entry of reset handler + * + * It defines following symbols, which code can use without definition: + * __exidx_start + * __exidx_end + * __copy_table_start__ + * __copy_table_end__ + * __zero_table_start__ + * __zero_table_end__ + * __etext + * __data_start__ + * __preinit_array_start + * __preinit_array_end + * __init_array_start + * __init_array_end + * __fini_array_start + * __fini_array_end + * __data_end__ + * __bss_start__ + * __bss_end__ + * __HeapLimit + * __StackLimit + * __StackTop + * __stack + * __Vectors_End + * __Vectors_Size + * __qspi_flash_start__ + * __qspi_flash_end__ + * __qspi_flash_code_size__ + * __qspi_region_max_size__ + * __qspi_region_start_address__ + * __qspi_region_end_address__ + * __ospi_device_0_start__ + * __ospi_device_0_end__ + * __ospi_device_0_code_size__ + * __ospi_device_0_region_max_size__ + * __ospi_device_0_region_start_address__ + * __ospi_device_0_region_end_address__ + * __ospi_device_1_start__ + * __ospi_device_1_end__ + * __ospi_device_1_code_size__ + * __ospi_device_1_region_max_size__ + * __ospi_device_1_region_start_address__ + * __ospi_device_1_region_end_address__ + */ +ENTRY(Reset_Handler) + +SECTIONS +{ + .text : + { + __tz_FLASH_S = ABSOLUTE(FLASH_START); + __ROM_Start = .; + + /* Even though the vector table is not 256 entries (1KB) long, we still allocate that much + * space because ROM registers are at address 0x400 and there is very little space + * in between. */ + KEEP(*(.fixed_vectors*)) + KEEP(*(.application_vectors*)) + __Vectors_End = .; + + /* Some devices have a gap of code flash between the vector table and ROM Registers. + * The flash gap section allows applications to place code and data in this section. */ + *(.flash_gap*) + + /* ROM Registers start at address 0x00000400 for devices that do not have the OPTION_SETTING region. */ + . = OPTION_SETTING_LENGTH > 0 ? . : __ROM_Start + 0x400; + KEEP(*(.rom_registers*)) + + /* Reserving 0x100 bytes of space for ROM registers. */ + . = OPTION_SETTING_LENGTH > 0 ? . : __ROM_Start + 0x500; + + /* Allocate flash write-boundary-aligned + * space for sce9 wrapped public keys for mcuboot if the module is used. + */ + KEEP(*(.mcuboot_sce9_key*)) + + *(.text*) + + KEEP(*(.version)) + KEEP(*(.init)) + KEEP(*(.fini)) + + /* .ctors */ + *crtbegin.o(.ctors) + *crtbegin?.o(.ctors) + *(EXCLUDE_FILE(*crtend?.o *crtend.o) .ctors) + *(SORT(.ctors.*)) + *(.ctors) + + /* .dtors */ + *crtbegin.o(.dtors) + *crtbegin?.o(.dtors) + *(EXCLUDE_FILE(*crtend?.o *crtend.o) .dtors) + *(SORT(.dtors.*)) + *(.dtors) + + *(.rodata*) + __usb_dev_descriptor_start_fs = .; + KEEP(*(.usb_device_desc_fs*)) + __usb_cfg_descriptor_start_fs = .; + KEEP(*(.usb_config_desc_fs*)) + __usb_interface_descriptor_start_fs = .; + KEEP(*(.usb_interface_desc_fs*)) + __usb_descriptor_end_fs = .; + __usb_dev_descriptor_start_hs = .; + KEEP(*(.usb_device_desc_hs*)) + __usb_cfg_descriptor_start_hs = .; + KEEP(*(.usb_config_desc_hs*)) + __usb_interface_descriptor_start_hs = .; + KEEP(*(.usb_interface_desc_hs*)) + __usb_descriptor_end_hs = .; + + KEEP(*(.eh_frame*)) + + __ROM_End = .; + } > FLASH = 0xFF + + __Vectors_Size = __Vectors_End - __Vectors; + + . = .; + __itcm_data_pre_location = .; + + /* Initialized ITCM data. */ + /* Aligned to FCACHE2 for RA8. */ + .itcm_data : ALIGN(16) + { + /* Start of ITCM Secure Trustzone region. */ + __tz_ITCM_S = ABSOLUTE(ITCM_START); + + /* All ITCM data start */ + __itcm_data_start = .; + + KEEP(*(.itcm_data*)) + + /* Pad to eight byte alignment in case of ECC initialization. Fill zero. */ + . = ALIGN(8); + + /* All ITCM data end */ + __itcm_data_end = .; + + /* + * Start of the ITCM Non-Secure Trustzone region. + * ITCM_NS_START can be used to set a fixed address for non-secure ITCM in secure projects or flat projects. + */ + __tz_ITCM_N = DEFINED(ITCM_NS_START) ? ABSOLUTE(ITCM_NS_START) : ALIGN(__itcm_data_end, 8192); + } > ITCM AT > FLASH = 0x00 + + /* Addresses exported for ITCM initialization. */ + __itcm_data_init_start = LOADADDR(.itcm_data); + __itcm_data_init_end = LOADADDR(.itcm_data) + SIZEOF(.itcm_data); + + ASSERT(ORIGIN(ITCM) % 8 == 0, "ITCM memory region origin must be aligned to 8 bytes.") + ASSERT(LENGTH(ITCM) % 8 == 0, "ITCM memory region length must be a multiple of 8 bytes.") + ASSERT(LOADADDR(.itcm_data) % 16 == 0, ".itcm_data section must be aligned to 16 bytes.") + ASSERT(SIZEOF(.itcm_data) % 8 == 0, ".itcm_data section size must be a multiple of 8 bytes.") + + /* Restore location counter. */ + /* If ITCM is not present, this will be the address stored in '.' before ALIGN was attempted. */ + /* If ITCM is present, this will be the absolute address that follows the ITCM ROM location. */ + . = (SIZEOF(.itcm_data) > 0) ? __itcm_data_init_end : __itcm_data_pre_location; + + __exidx_start = .; + /DISCARD/ : + { + *(.ARM.extab* .gnu.linkonce.armextab.*) + *(.ARM.exidx* .gnu.linkonce.armexidx.*) + } + __exidx_end = .; + + /* To copy multiple ROM to RAM sections, + * uncomment .copy.table section and, + * define __STARTUP_COPY_MULTIPLE in startup_ARMCMx.S */ + /* + .copy.table : + { + . = ALIGN(4); + __copy_table_start__ = .; + LONG (__etext) + LONG (__data_start__) + LONG (__data_end__ - __data_start__) + LONG (__etext2) + LONG (__data2_start__) + LONG (__data2_end__ - __data2_start__) + __copy_table_end__ = .; + } > FLASH + */ + + /* To clear multiple BSS sections, + * uncomment .zero.table section and, + * define __STARTUP_CLEAR_BSS_MULTIPLE in startup_ARMCMx.S */ + /* + .zero.table : + { + . = ALIGN(4); + __zero_table_start__ = .; + LONG (__bss_start__) + LONG (__bss_end__ - __bss_start__) + LONG (__bss2_start__) + LONG (__bss2_end__ - __bss2_start__) + __zero_table_end__ = .; + } > FLASH + */ + + __etext = .; + + __tz_RAM_S = ORIGIN(RAM); + + /* If DTC is used, put the DTC vector table at the start of SRAM. + This avoids memory holes due to 1K alignment required by it. */ + .fsp_dtc_vector_table (NOLOAD) : + { + . = ORIGIN(RAM); + *(.fsp_dtc_vector_table) + } > RAM + + /* Initialized data section. */ + .data : + { + __data_start__ = .; + . = ALIGN(4); + + __Code_In_RAM_Start = .; + + KEEP(*(.code_in_ram*)) + __Code_In_RAM_End = .; + + *(vtable) + /* Don't use *(.data*) because it will place data meant for .data_flash in this section. */ + *(.data.*) + *(.data) + + . = ALIGN(4); + /* preinit data */ + PROVIDE_HIDDEN (__preinit_array_start = .); + KEEP(*(.preinit_array)) + PROVIDE_HIDDEN (__preinit_array_end = .); + + . = ALIGN(4); + /* init data */ + PROVIDE_HIDDEN (__init_array_start = .); + KEEP(*(SORT(.init_array.*))) + KEEP(*(.init_array)) + PROVIDE_HIDDEN (__init_array_end = .); + + + . = ALIGN(4); + /* finit data */ + PROVIDE_HIDDEN (__fini_array_start = .); + KEEP(*(SORT(.fini_array.*))) + KEEP(*(.fini_array)) + PROVIDE_HIDDEN (__fini_array_end = .); + + KEEP(*(.jcr*)) + + . = ALIGN(4); + + /* All data end */ + __data_end__ = .; + + } > RAM AT > FLASH + + . = .; + __dtcm_data_pre_location = LOADADDR(.data) + SIZEOF(.data); + + /* Initialized DTCM data. */ + /* Aligned to FCACHE2 for RA8. */ + .dtcm_data : ALIGN(16) + { + /* Start of DTCM Secure Trustzone region. */ + __tz_DTCM_S = ABSOLUTE(DTCM_START); + + /* Initialized DTCM data start */ + __dtcm_data_start = .; + + KEEP(*(.dtcm_data*)) + + /* Pad to eight byte alignment in case of ECC initialization. Fill zero. */ + . = ALIGN(8); + + /* Initialized DTCM data end */ + __dtcm_data_end = .; + } > DTCM AT > FLASH = 0x00 + + . = __dtcm_data_end; + /* Uninitialized DTCM data. */ + /* ALIGN appears on the left side of the colon because it is being used to assign the VMA directly, as opposed to a right side appearance which would control the LMA. */ + .dtcm_bss ALIGN(8) (NOLOAD) : + { + /* Uninitialized DTCM data start */ + __dtcm_bss_start = .; + + KEEP(*(.dtcm_bss*)) + + /* Pad to eight byte alignment in case of ECC initialization. No fill because of NOLOAD. */ + . = ALIGN(8); + + /* Uninitialized DTCM data end */ + __dtcm_bss_end = .; + + /* + * Start of the DTCM Non-Secure Trustzone region. + * DTCM_NS_START can be used to set a fixed address for non-secure DTCM in secure projects or flat projects. + */ + __tz_DTCM_N = DEFINED(DTCM_NS_START) ? ABSOLUTE(DTCM_NS_START) : ALIGN(__dtcm_bss_end, 8192); + } > DTCM + + /* Addresses exported for DTCM initialization. */ + __dtcm_data_init_start = LOADADDR(.dtcm_data); + __dtcm_data_init_end = LOADADDR(.dtcm_data) + SIZEOF(.dtcm_data); + + ASSERT(ORIGIN(DTCM) % 8 == 0, "DTCM memory region origin must be aligned to 8 bytes.") + ASSERT(LENGTH(DTCM) % 8 == 0, "DTCM memory region length must be a multiple of 8 bytes.") + ASSERT(LOADADDR(.dtcm_bss) == ADDR(.dtcm_bss), ".dtcm_bss has (VMA != LMA) but should be NOLOAD (VMA == LMA).") + ASSERT(LOADADDR(.dtcm_data) % 16 == 0, ".dtcm_data section must be aligned to 16 bytes.") + ASSERT(SIZEOF(.dtcm_data) % 8 == 0, ".dtcm_data section size must be a multiple of 8 bytes.") + ASSERT(LOADADDR(.dtcm_bss) % 8 == 0, ".dtcm_bss section must be aligned to 8 bytes.") + ASSERT(SIZEOF(.dtcm_bss) % 8 == 0, ".dtcm_bss section size must be a multiple of 8 bytes.") + ASSERT(__dtcm_bss_start == __dtcm_data_end, ".dtcm_bss section is not adjacent to .dtcm_data section.") + + /* Restore location counter. */ + /* If DTCM is not present, this will be the address stored in '.' before ALIGN was attempted. */ + /* If DTCM is present, this will be the absolute address that follows the DTCM ROM location. */ + . = (SIZEOF(.dtcm_data) > 0) ? __dtcm_data_init_end : __dtcm_data_pre_location; + + /* TrustZone Secure Gateway Stubs Section */ + + /* Store location counter for SPI non-retentive sections. */ + sgstubs_pre_location = .; + + /* Determine the secure gateway stubs address either by the provided linker variable or the next 1024-byte block. */ + SGSTUBS_LOC = (DEFINED(PROJECT_SECURE) && DEFINED(FLASH_NSC_START)) ? ABSOLUTE(FLASH_NSC_START) : ALIGN(1024); + .gnu.sgstubs SGSTUBS_LOC : ALIGN(1024) + { + __tz_FLASH_C = DEFINED(FLASH_NSC_START) ? ABSOLUTE(FLASH_NSC_START) : __RESERVE_NS_RAM ? ABSOLUTE(FLASH_START + FLASH_LENGTH) : ALIGN(1024); + _start_sg = .; + *(.gnu.sgstubs*) + . = ALIGN(32); + _end_sg = .; + } > FLASH + + __tz_FLASH_N = DEFINED(FLASH_NS_START) ? ABSOLUTE(FLASH_NS_START) : __RESERVE_NS_RAM ? ABSOLUTE(FLASH_START + FLASH_LENGTH) : FLASH_LENGTH < 32768 ? FLASH_LENGTH : ALIGN(32768); + FLASH_NS_IMAGE_START = DEFINED(FLASH_NS_IMAGE_START) ? FLASH_NS_IMAGE_START : __tz_FLASH_N; + + /* Note: There are no secure/non-secure boundaries for QSPI. These symbols are provided for the RA configuration tool. */ + __tz_QSPI_FLASH_S = ORIGIN(QSPI_FLASH); + + /* QSPI_FLASH section to be downloaded via debugger */ + .qspi_flash : + { + __qspi_flash_start__ = .; + KEEP(*(.qspi_flash*)) + KEEP(*(.code_in_qspi*)) + __qspi_flash_end__ = .; + } > QSPI_FLASH + __qspi_flash_code_size__ = __qspi_flash_end__ - __qspi_flash_start__; + + /* QSPI_FLASH non-retentive section, creates a copy in internal flash that can be copied to QSPI */ + __qspi_flash_code_addr__ = sgstubs_pre_location; + .qspi_non_retentive : AT(__qspi_flash_code_addr__) + { + __qspi_non_retentive_start__ = .; + KEEP(*(.qspi_non_retentive*)) + __qspi_non_retentive_end__ = .; + } > QSPI_FLASH + __qspi_non_retentive_size__ = __qspi_non_retentive_end__ - __qspi_non_retentive_start__; + + __qspi_region_max_size__ = 0x4000000; /* Must be the same as defined in MEMORY above */ + __qspi_region_start_address__ = __qspi_flash_start__; + __qspi_region_end_address__ = __qspi_flash_start__ + __qspi_region_max_size__; + + /* Note: There are no secure/non-secure boundaries for QSPI. These symbols are provided for the RA configuration tool. */ + __tz_QSPI_FLASH_N = __qspi_non_retentive_end__; + + /* Support for OctaRAM */ + .OSPI_DEVICE_0_NO_LOAD (NOLOAD): + { + . = ALIGN(4); + __ospi_device_0_start__ = .; + *(.ospi_device_0_no_load*) + . = ALIGN(4); + __ospi_device_0_end__ = .; + } > OSPI_DEVICE_0_RAM + + .OSPI_DEVICE_1_NO_LOAD (NOLOAD): + { + . = ALIGN(4); + __ospi_device_1_start__ = .; + *(.ospi_device_1_no_load*) + . = ALIGN(4); + __ospi_device_1_end__ = .; + } > OSPI_DEVICE_1_RAM + + /* Note: There are no secure/non-secure boundaries for QSPI. These symbols are provided for the RA configuration tool. */ + __tz_OSPI_DEVICE_0_S = ORIGIN(OSPI_DEVICE_0); + + /* OSPI_DEVICE_0 section to be downloaded via debugger */ + .OSPI_DEVICE_0 : + { + __ospi_device_0_start__ = .; + KEEP(*(.ospi_device_0*)) + KEEP(*(.code_in_ospi_device_0*)) + __ospi_device_0_end__ = .; + } > OSPI_DEVICE_0 + __ospi_device_0_code_size__ = __ospi_device_0_end__ - __ospi_device_0_start__; + + /* OSPI_DEVICE_0 non-retentive section, creates a copy in internal flash that can be copied to OSPI */ + __ospi_device_0_code_addr__ = sgstubs_pre_location + (SIZEOF(.qspi_non_retentive)); + .ospi_device_0_non_retentive : AT(__ospi_device_0_code_addr__) + { + __ospi_device_0_non_retentive_start__ = .; + KEEP(*(.ospi_device_0_non_retentive*)) + __ospi_device_0_non_retentive_end__ = .; + } > OSPI_DEVICE_0 + __ospi_device_0_non_retentive_size__ = __ospi_device_0_non_retentive_end__ - __ospi_device_0_non_retentive_start__; + + __ospi_device_0_region_max_size__ = 0x8000000; /* Must be the same as defined in MEMORY above */ + __ospi_device_0_region_start_address__ = __ospi_device_0_start__; + __ospi_device_0_region_end_address__ = __ospi_device_0_start__ + __ospi_device_0_region_max_size__; + + /* Note: There are no secure/non-secure boundaries for OSPI. These symbols are provided for the RA configuration tool. */ + __tz_OSPI_DEVICE_0_N = __ospi_device_0_non_retentive_end__; + + /* Note: There are no secure/non-secure boundaries for OSPI. These symbols are provided for the RA configuration tool. */ + __tz_OSPI_DEVICE_1_S = ORIGIN(OSPI_DEVICE_1); + + /* OSPI_DEVICE_1 section to be downloaded via debugger */ + .OSPI_DEVICE_1 : + { + __ospi_device_1_start__ = .; + KEEP(*(.ospi_device_1*)) + KEEP(*(.code_in_ospi_device_1*)) + __ospi_device_1_end__ = .; + } > OSPI_DEVICE_1 + __ospi_device_1_code_size__ = __ospi_device_1_end__ - __ospi_device_1_start__; + + /* OSPI_DEVICE_1 non-retentive section, creates a copy in internal flash that can be copied to OSPI */ + __ospi_device_1_code_addr__ = sgstubs_pre_location + (SIZEOF(.qspi_non_retentive) + SIZEOF(.ospi_device_0_non_retentive)); + .ospi_device_1_non_retentive : AT(__ospi_device_1_code_addr__) + { + __ospi_device_1_non_retentive_start__ = .; + KEEP(*(.ospi_device_1_non_retentive*)) + __ospi_device_1_non_retentive_end__ = .; + } > OSPI_DEVICE_1 + __ospi_device_1_non_retentive_size__ = __ospi_device_1_non_retentive_end__ - __ospi_device_1_non_retentive_start__; + + __ospi_device_1_region_max_size__ = 0x10000000; /* Must be the same as defined in MEMORY above */ + __ospi_device_1_region_start_address__ = __ospi_device_1_start__; + __ospi_device_1_region_end_address__ = __ospi_device_1_start__ + __ospi_device_1_region_max_size__; + + /* Note: There are no secure/non-secure boundaries for OSPI. These symbols are provided for the RA configuration tool. */ + __tz_OSPI_DEVICE_1_N = __ospi_device_1_non_retentive_end__; + + .noinit (NOLOAD): + { + . = ALIGN(4); + __noinit_start = .; + KEEP(*(.noinit*)) + . = ALIGN(8); + /* Place the FreeRTOS heap here so that the __HeapLimit calculation does not include the freertos heap. */ + KEEP(*(.heap.*)) + __noinit_end = .; + } > RAM + + .bss : + { + . = ALIGN(4); + __bss_start__ = .; + *(.bss*) + *(COMMON) + . = ALIGN(4); + __bss_end__ = .; + } > RAM + + .heap (NOLOAD): + { + . = ALIGN(8); + __HeapBase = .; + /* Place the STD heap here. */ + KEEP(*(.heap)) + __HeapLimit = .; + } > RAM + + /* Stacks are stored in this section. */ + .stack_dummy (NOLOAD): + { + . = ALIGN(8); + __StackLimit = .; + /* Main stack */ + KEEP(*(.stack)) + __StackTop = .; + /* Thread stacks */ + KEEP(*(.stack*)) + __StackTopAll = .; + } > RAM + + PROVIDE(__stack = __StackTopAll); + + /* This symbol represents the end of user allocated RAM. The RAM after this symbol can be used + at run time for things such as ThreadX memory pool allocations. */ + __RAM_segment_used_end__ = ALIGN(__StackTopAll , 4); + + /* RAM_NSC_START can be used to set a fixed address for non-secure callable RAM in secure projects. + * If it is not specified, the address for NSC RAM is the end of RAM aligned to a 1K boundary. + * In flat projects that require non-secure RAM, this variable is set to the start of non-secure RAM. */ + __tz_RAM_C = DEFINED(RAM_NSC_START) ? ABSOLUTE(RAM_NSC_START - RAM_NS_BUFFER_BLOCK_LENGTH) : __RESERVE_NS_RAM ? ABSOLUTE(RAM_NS_BUFFER_BLOCK_START) : ALIGN(__RAM_segment_used_end__, 1024); + + /* RAM_NS_START can be used to set a fixed address for non-secure RAM in secure projects or flat projects. + * RAM_NS_BUFFER_BLOCK_LENGTH is used to allocate non-secure buffers in a flat project. If it is not + * specified, the address for NSC RAM is the end of RAM aligned to an 8K boundary. + * In flat projects that require non-secure RAM, this variable is set to the start of non-secure RAM. */ + __tz_RAM_N = DEFINED(RAM_NS_START) ? ABSOLUTE(RAM_NS_START - RAM_NS_BUFFER_BLOCK_LENGTH) : __RESERVE_NS_RAM ? ABSOLUTE(RAM_NS_BUFFER_BLOCK_START) : ALIGN(__tz_RAM_C, 8192); + + /* Non-secure buffers must be in non-secure RAM. This is primarily used for the EDMAC in flat projects. + * The EDMAC is a non-secure bus master and can only access non-secure RAM. */ + .ns_buffer (NOLOAD): + { + /* Allocate RAM on a 32-byte boundary to help with placement of Ethernet buffers. */ + . = __RESERVE_NS_RAM ? ABSOLUTE(RAM_NS_BUFFER_START & 0xFFFFFFE0) : .; + + KEEP(*(.ns_buffer*)) + } > RAM + + /* Data flash. */ + .data_flash : + { + . = ORIGIN(DATA_FLASH); + __tz_DATA_FLASH_S = .; + __Data_Flash_Start = .; + KEEP(*(.data_flash*)) + __Data_Flash_End = .; + + __tz_DATA_FLASH_N = DEFINED(DATA_FLASH_NS_START) ? ABSOLUTE(DATA_FLASH_NS_START) : __RESERVE_NS_RAM ? ABSOLUTE(DATA_FLASH_START + DATA_FLASH_LENGTH) : ALIGN(1024); + } > DATA_FLASH + + /* Note: There are no secure/non-secure boundaries for SDRAM. These symbols are provided for the RA configuration tool. */ + __tz_SDRAM_S = ORIGIN(SDRAM); + + /* SDRAM */ + .sdram (NOLOAD): + { + __SDRAM_Start = .; + KEEP(*(.sdram*)) + KEEP(*(.frame*)) + __SDRAM_End = .; + } > SDRAM + + /* Note: There are no secure/non-secure boundaries for SDRAM. These symbols are provided for the RA configuration tool. */ + __tz_SDRAM_N = __SDRAM_End; + + /* Note: There are no secure/non-secure boundaries for ID_CODE. These symbols are provided for the RA configuration tool. */ + __tz_ID_CODE_S = ORIGIN(ID_CODE); + + /* Note: There are no secure/non-secure boundaries for ID_CODE. These symbols are provided for the RA configuration tool. + * Set this symbol to the same value as __tz_ID_CODE_S so the RA configuration tool does not split the ID_CODE + * memory region between TrustZone projects. */ + __tz_ID_CODE_N = __tz_ID_CODE_S; + + .id_code : + { + __ID_Code_Start = .; + KEEP(*(.id_code*)) + __ID_Code_End = .; + } > ID_CODE + + /* Symbol required for RA Configuration tool. */ + __tz_OPTION_SETTING_S = ORIGIN(OPTION_SETTING_OFS); + + .option_setting_ofs : + { + __OPTION_SETTING_OFS_Start = .; + KEEP(*(.option_setting_ofs0)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_OFS_Start + 0x04 : __OPTION_SETTING_OFS_Start; + KEEP(*(.option_setting_ofs2)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_OFS_Start + 0x10 : __OPTION_SETTING_OFS_Start; + KEEP(*(.option_setting_dualsel)) + __OPTION_SETTING_OFS_End = .; + } > OPTION_SETTING_OFS = 0xFF + + .option_setting_sas : + { + __OPTION_SETTING_SAS_Start = .; + KEEP(*(.option_setting_sas)) + __OPTION_SETTING_SAS_End = .; + } > OPTION_SETTING_SAS = 0xFF + + /* Symbol required for RA Configuration tool. */ + __tz_OPTION_SETTING_N = ABSOLUTE(OPTION_SETTING_START_NS); + + .option_setting_ns : + { + __OPTION_SETTING_NS_Start = .; + KEEP(*(.option_setting_ofs1)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x04 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_ofs3)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x10 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_banksel)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x40 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_bps0)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x44 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_bps1)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x48 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_bps2)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x4C : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_bps3)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x60 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_pbps0)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x64 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_pbps1)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x68 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_pbps2)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x6C : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_pbps3)) + __OPTION_SETTING_NS_End = .; + } > OPTION_SETTING = 0xFF + + /* Symbol required for RA Configuration tool. */ + __tz_OPTION_SETTING_S_S = ORIGIN(OPTION_SETTING_S); + + .option_setting_s : + { + __OPTION_SETTING_S_Start = .; + KEEP(*(.option_setting_ofs1_sec)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x04 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_ofs3_sec)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x10 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_banksel_sec)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x40 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sec0)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x44 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sec1)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x48 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sec2)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x4C : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sec3)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x60 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_pbps_sec0)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x64 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_pbps_sec1)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x68 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_pbps_sec2)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x6C : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_pbps_sec3)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x80 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_ofs1_sel)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x84 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_ofs3_sel)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x90 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_banksel_sel)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0xC0 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sel0)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0xC4 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sel1)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0xC8 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sel2)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0xCC : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sel3)) + __OPTION_SETTING_S_End = .; + } > OPTION_SETTING_S = 0xFF + + /* Symbol required for RA Configuration tool. */ + __tz_OPTION_SETTING_S_N = __OPTION_SETTING_S_End; +} diff --git a/hw/bsp/ra/boards/ra6m1_ek/script/memory_regions.ld b/hw/bsp/ra/boards/ra6m1_ek/script/memory_regions.ld new file mode 100644 index 000000000..9d973c737 --- /dev/null +++ b/hw/bsp/ra/boards/ra6m1_ek/script/memory_regions.ld @@ -0,0 +1,22 @@ + + /* generated memory regions file - do not edit */ + RAM_START = 0x1FFE0000; + RAM_LENGTH = 0x40000; + FLASH_START = 0x00000000; + FLASH_LENGTH = 0x80000; + DATA_FLASH_START = 0x40100000; + DATA_FLASH_LENGTH = 0x2000; + OPTION_SETTING_START = 0x00000000; + OPTION_SETTING_LENGTH = 0x0; + OPTION_SETTING_S_START = 0x80000000; + OPTION_SETTING_S_LENGTH = 0x0; + ID_CODE_START = 0x0100A150; + ID_CODE_LENGTH = 0x10; + SDRAM_START = 0x80010000; + SDRAM_LENGTH = 0x0; + QSPI_FLASH_START = 0x60000000; + QSPI_FLASH_LENGTH = 0x4000000; + OSPI_DEVICE_0_START = 0x80020000; + OSPI_DEVICE_0_LENGTH = 0x0; + OSPI_DEVICE_1_START = 0x80030000; + OSPI_DEVICE_1_LENGTH = 0x0; diff --git a/hw/bsp/ra/boards/ra6m1_ek/smart_configurator/configuration.xml b/hw/bsp/ra/boards/ra6m1_ek/smart_configurator/configuration.xml new file mode 100644 index 000000000..4c5d77ed0 --- /dev/null +++ b/hw/bsp/ra/boards/ra6m1_ek/smart_configurator/configuration.xml @@ -0,0 +1,270 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Simple application that blinks an LED. No RTOS included. + Renesas.RA_baremetal_blinky.5.6.0.pack + + + Board Support Package Common Files + Renesas.RA.5.6.0.pack + + + I/O Port + Renesas.RA.5.6.0.pack + + + Arm CMSIS Version 6 - Core (M) + Arm.CMSIS6.6.1.0+fsp.5.6.0.pack + + + RA6M1-EK Board Support Files + Renesas.RA_board_ra6m1_ek.5.6.0.pack + + + Board support package for R7FA6M1AD3CFP + Renesas.RA_mcu_ra6m1.5.6.0.pack + + + Board support package for RA6M1 + Renesas.RA_mcu_ra6m1.5.6.0.pack + + + Board support package for RA6M1 - FSP Data + Renesas.RA_mcu_ra6m1.5.6.0.pack + + + Board support package for RA6M1 - Events + Renesas.RA_mcu_ra6m1.5.6.0.pack + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/hw/bsp/ra/boards/ra6m5_ek/board.cmake b/hw/bsp/ra/boards/ra6m5_ek/board.cmake index c91d48a32..bc99845a1 100644 --- a/hw/bsp/ra/boards/ra6m5_ek/board.cmake +++ b/hw/bsp/ra/boards/ra6m5_ek/board.cmake @@ -1,22 +1,16 @@ -set(CMAKE_SYSTEM_PROCESSOR cortex-m33 CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU cortex-m33 CACHE INTERNAL "System Processor") set(MCU_VARIANT ra6m5) set(JLINK_DEVICE R7FA6M5BH) +set(JLINK_OPTION "-USB 000831915224") -# Device port default to PORT1 Highspeed -if (NOT DEFINED PORT) -set(PORT 1) +# device default to PORT 1 High Speed +if (NOT DEFINED RHPORT_DEVICE) + set(RHPORT_DEVICE 1) +endif() +if (NOT DEFINED RHPORT_HOST) + set(RHPORT_HOST 0) endif() -# Host port will be the other port -set(HOST_PORT $) - function(update_board TARGET) - target_compile_definitions(${TARGET} PUBLIC - BOARD_TUD_RHPORT=${PORT} - BOARD_TUH_RHPORT=${HOST_PORT} - # port 0 is fullspeed, port 1 is highspeed - BOARD_TUD_MAX_SPEED=$ - BOARD_TUH_MAX_SPEED=$ - ) endfunction() diff --git a/hw/bsp/ra/boards/ra6m5_ek/board.h b/hw/bsp/ra/boards/ra6m5_ek/board.h index 779f71810..32ede3a97 100644 --- a/hw/bsp/ra/boards/ra6m5_ek/board.h +++ b/hw/bsp/ra/boards/ra6m5_ek/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: RA6M5 EK + url: https://www.renesas.com/en/products/microcontrollers-microprocessors/ra-cortex-m-mcus/ek-ra6m5-evaluation-kit-ra6m5-mcu-group +*/ + #ifndef _BOARD_H_ #define _BOARD_H_ @@ -31,35 +36,9 @@ extern "C" { #endif -#define LED1 BSP_IO_PORT_00_PIN_08 #define LED_STATE_ON 1 - -#define SW1 BSP_IO_PORT_00_PIN_05 #define BUTTON_STATE_ACTIVE 0 -static const ioport_pin_cfg_t board_pin_cfg[] = { - { .pin = LED1, .pin_cfg = IOPORT_CFG_PORT_DIRECTION_OUTPUT | IOPORT_CFG_PORT_OUTPUT_LOW }, - { .pin = SW1, .pin_cfg = IOPORT_CFG_PORT_DIRECTION_INPUT }, - - // USB FS - { .pin = BSP_IO_PORT_04_PIN_07, .pin_cfg = IOPORT_CFG_PERIPHERAL_PIN | IOPORT_PERIPHERAL_USB_FS | IOPORT_CFG_DRIVE_HIGH }, - { .pin = BSP_IO_PORT_05_PIN_00, .pin_cfg = IOPORT_CFG_PERIPHERAL_PIN | IOPORT_PERIPHERAL_USB_FS | IOPORT_CFG_DRIVE_HIGH}, - { .pin = BSP_IO_PORT_05_PIN_01, .pin_cfg = IOPORT_CFG_PERIPHERAL_PIN | IOPORT_PERIPHERAL_USB_FS | IOPORT_CFG_DRIVE_HIGH}, - - // USB HS - { .pin = BSP_IO_PORT_07_PIN_07, .pin_cfg = IOPORT_CFG_PERIPHERAL_PIN | IOPORT_PERIPHERAL_USB_HS }, - { .pin = BSP_IO_PORT_11_PIN_00, .pin_cfg = IOPORT_CFG_PERIPHERAL_PIN | IOPORT_PERIPHERAL_USB_HS | IOPORT_CFG_DRIVE_HIGH}, - { .pin = BSP_IO_PORT_11_PIN_01, .pin_cfg = IOPORT_CFG_PERIPHERAL_PIN | IOPORT_PERIPHERAL_USB_HS | IOPORT_CFG_DRIVE_HIGH}, - - // ETM Trace - #ifdef TRACE_ETM - { .pin = BSP_IO_PORT_02_PIN_08, .pin_cfg = IOPORT_CFG_PERIPHERAL_PIN | IOPORT_PERIPHERAL_TRACE | IOPORT_CFG_DRIVE_HS_HIGH }, - { .pin = BSP_IO_PORT_02_PIN_09, .pin_cfg = IOPORT_CFG_PERIPHERAL_PIN | IOPORT_PERIPHERAL_TRACE | IOPORT_CFG_DRIVE_HS_HIGH }, - { .pin = BSP_IO_PORT_02_PIN_10, .pin_cfg = IOPORT_CFG_PERIPHERAL_PIN | IOPORT_PERIPHERAL_TRACE | IOPORT_CFG_DRIVE_HS_HIGH }, - { .pin = BSP_IO_PORT_02_PIN_11, .pin_cfg = IOPORT_CFG_PERIPHERAL_PIN | IOPORT_PERIPHERAL_TRACE | IOPORT_CFG_DRIVE_HS_HIGH }, - { .pin = BSP_IO_PORT_02_PIN_14, .pin_cfg = IOPORT_CFG_PERIPHERAL_PIN | IOPORT_PERIPHERAL_TRACE | IOPORT_CFG_DRIVE_HS_HIGH }, - #endif -}; #ifdef __cplusplus } diff --git a/hw/bsp/ra/boards/ra6m5_ek/board.mk b/hw/bsp/ra/boards/ra6m5_ek/board.mk index a5c933764..5fcc1d0f1 100644 --- a/hw/bsp/ra/boards/ra6m5_ek/board.mk +++ b/hw/bsp/ra/boards/ra6m5_ek/board.mk @@ -5,6 +5,7 @@ MCU_VARIANT = ra6m5 JLINK_DEVICE = R7FA6M5BH # Port 1 is highspeed -PORT ?= 1 +RHPORT_DEVICE ?= 1 +RHPORT_HOST ?= 0 flash: flash-jlink diff --git a/hw/bsp/ra/boards/ra6m5_ek/fsp_cfg/bsp/bsp_cfg.h b/hw/bsp/ra/boards/ra6m5_ek/fsp_cfg/bsp/bsp_cfg.h deleted file mode 100644 index 33d381850..000000000 --- a/hw/bsp/ra/boards/ra6m5_ek/fsp_cfg/bsp/bsp_cfg.h +++ /dev/null @@ -1,63 +0,0 @@ -/* generated configuration header file - do not edit */ -#ifndef BSP_CFG_H_ -#define BSP_CFG_H_ -#ifdef __cplusplus -extern "C" { -#endif - -#include "bsp_clock_cfg.h" -#include "bsp_mcu_family_cfg.h" -#include "board_cfg.h" - -#define RA_NOT_DEFINED 0 -#ifndef BSP_CFG_RTOS -#if (RA_NOT_DEFINED) != (2) -#define BSP_CFG_RTOS (2) -#elif (RA_NOT_DEFINED) != (RA_NOT_DEFINED) - #define BSP_CFG_RTOS (1) -#else - #define BSP_CFG_RTOS (0) -#endif -#endif -#ifndef BSP_CFG_RTC_USED -#define BSP_CFG_RTC_USED (RA_NOT_DEFINED) -#endif -#undef RA_NOT_DEFINED -#if defined(_RA_BOOT_IMAGE) - #define BSP_CFG_BOOT_IMAGE (1) -#endif -#define BSP_CFG_MCU_VCC_MV (3300) -#define BSP_CFG_STACK_MAIN_BYTES (0x1000) -#define BSP_CFG_HEAP_BYTES (0x1000) -#define BSP_CFG_PARAM_CHECKING_ENABLE (1) -#define BSP_CFG_ASSERT (0) -#define BSP_CFG_ERROR_LOG (0) - -#define BSP_CFG_PFS_PROTECT ((1)) - -#define BSP_CFG_C_RUNTIME_INIT ((1)) -#define BSP_CFG_EARLY_INIT ((0)) - -#define BSP_CFG_STARTUP_CLOCK_REG_NOT_RESET ((0)) - -#ifndef BSP_CLOCK_CFG_MAIN_OSC_POPULATED -#define BSP_CLOCK_CFG_MAIN_OSC_POPULATED (1) -#endif - -#ifndef BSP_CLOCK_CFG_MAIN_OSC_CLOCK_SOURCE -#define BSP_CLOCK_CFG_MAIN_OSC_CLOCK_SOURCE (0) -#endif -#ifndef BSP_CLOCK_CFG_SUBCLOCK_DRIVE -#define BSP_CLOCK_CFG_SUBCLOCK_DRIVE (0) -#endif -#ifndef BSP_CLOCK_CFG_SUBCLOCK_POPULATED -#define BSP_CLOCK_CFG_SUBCLOCK_POPULATED (1) -#endif -#ifndef BSP_CLOCK_CFG_SUBCLOCK_STABILIZATION_MS -#define BSP_CLOCK_CFG_SUBCLOCK_STABILIZATION_MS 1000 -#endif - -#ifdef __cplusplus -} -#endif -#endif /* BSP_CFG_H_ */ diff --git a/hw/bsp/ra/boards/ra6m5_ek/fsp_cfg/bsp/bsp_mcu_device_pn_cfg.h b/hw/bsp/ra/boards/ra6m5_ek/fsp_cfg/bsp/bsp_mcu_device_pn_cfg.h deleted file mode 100644 index 6845183db..000000000 --- a/hw/bsp/ra/boards/ra6m5_ek/fsp_cfg/bsp/bsp_mcu_device_pn_cfg.h +++ /dev/null @@ -1,11 +0,0 @@ -/* generated configuration header file - do not edit */ -#ifndef BSP_MCU_DEVICE_PN_CFG_H_ -#define BSP_MCU_DEVICE_PN_CFG_H_ -#define BSP_MCU_R7FA6M5BH3CFC -#define BSP_MCU_FEATURE_SET ('B') -#define BSP_ROM_SIZE_BYTES (2097152) -#define BSP_RAM_SIZE_BYTES (524288) -#define BSP_DATA_FLASH_SIZE_BYTES (8192) -#define BSP_PACKAGE_LQFP -#define BSP_PACKAGE_PINS (176) -#endif /* BSP_MCU_DEVICE_PN_CFG_H_ */ diff --git a/hw/bsp/ra/boards/ra6m5_ek/fsp_cfg/bsp_clock_cfg.h b/hw/bsp/ra/boards/ra6m5_ek/fsp_cfg/bsp_clock_cfg.h deleted file mode 100644 index 0eb5e0516..000000000 --- a/hw/bsp/ra/boards/ra6m5_ek/fsp_cfg/bsp_clock_cfg.h +++ /dev/null @@ -1,37 +0,0 @@ -/* generated configuration header file - do not edit */ -#ifndef BSP_CLOCK_CFG_H_ -#define BSP_CLOCK_CFG_H_ - -#define BSP_CFG_CLOCKS_SECURE (0) -#define BSP_CFG_CLOCKS_OVERRIDE (0) -#define BSP_CFG_XTAL_HZ (24000000) /* XTAL 24000000Hz */ -#define BSP_CFG_HOCO_FREQUENCY (2) /* HOCO 20MHz */ -#define BSP_CFG_PLL_SOURCE (BSP_CLOCKS_SOURCE_CLOCK_MAIN_OSC) /* PLL Src: XTAL */ -#define BSP_CFG_PLL_DIV (BSP_CLOCKS_PLL_DIV_3) /* PLL Div /3 */ -#define BSP_CFG_PLL_MUL (BSP_CLOCKS_PLL_MUL(25U,0U)) /* PLL Mul x25.0 */ -#define BSP_CFG_PLL2_SOURCE (BSP_CLOCKS_SOURCE_CLOCK_MAIN_OSC) /* PLL2 Src: XTAL */ -#define BSP_CFG_PLL2_DIV (BSP_CLOCKS_PLL_DIV_2) /* PLL2 Div /2 */ -#define BSP_CFG_PLL2_MUL (BSP_CLOCKS_PLL_MUL(20U,0U)) /* PLL2 Mul x20.0 */ -#define BSP_CFG_CLOCK_SOURCE (BSP_CLOCKS_SOURCE_CLOCK_PLL) /* Clock Src: PLL */ -#define BSP_CFG_CLKOUT_SOURCE (BSP_CLOCKS_CLOCK_DISABLED) /* CLKOUT Disabled */ -#define BSP_CFG_UCK_SOURCE (BSP_CLOCKS_SOURCE_CLOCK_PLL2) /* UCLK Src: PLL2 */ -#define BSP_CFG_U60CK_SOURCE (BSP_CLOCKS_SOURCE_CLOCK_PLL2) /* U60CK Src: PLL2 */ -#define BSP_CFG_OCTA_SOURCE (BSP_CLOCKS_CLOCK_DISABLED) /* OCTASPICLK Disabled */ -#define BSP_CFG_CANFDCLK_SOURCE (BSP_CLOCKS_CLOCK_DISABLED) /* CANFDCLK Disabled */ -#define BSP_CFG_CECCLK_SOURCE (BSP_CLOCKS_CLOCK_DISABLED) /* CECCLK Disabled */ -#define BSP_CFG_ICLK_DIV (BSP_CLOCKS_SYS_CLOCK_DIV_1) /* ICLK Div /1 */ -#define BSP_CFG_PCLKA_DIV (BSP_CLOCKS_SYS_CLOCK_DIV_2) /* PCLKA Div /2 */ -#define BSP_CFG_PCLKB_DIV (BSP_CLOCKS_SYS_CLOCK_DIV_4) /* PCLKB Div /4 */ -#define BSP_CFG_PCLKC_DIV (BSP_CLOCKS_SYS_CLOCK_DIV_4) /* PCLKC Div /4 */ -#define BSP_CFG_PCLKD_DIV (BSP_CLOCKS_SYS_CLOCK_DIV_2) /* PCLKD Div /2 */ -#define BSP_CFG_BCLK_DIV (BSP_CLOCKS_SYS_CLOCK_DIV_2) /* BCLK Div /2 */ -#define BSP_CFG_BCLK_OUTPUT (2) /* EBCLK Div /2 */ -#define BSP_CFG_FCLK_DIV (BSP_CLOCKS_SYS_CLOCK_DIV_4) /* FCLK Div /4 */ -#define BSP_CFG_CLKOUT_DIV (BSP_CLOCKS_SYS_CLOCK_DIV_1) /* CLKOUT Div /1 */ -#define BSP_CFG_UCK_DIV (BSP_CLOCKS_USB_CLOCK_DIV_5) /* UCLK Div /5 */ -#define BSP_CFG_U60CK_DIV (BSP_CLOCKS_USB60_CLOCK_DIV_4) /* U60CK Div /4 */ -#define BSP_CFG_OCTA_DIV (BSP_CLOCKS_OCTA_CLOCK_DIV_1) /* OCTASPICLK Div /1 */ -#define BSP_CFG_CANFDCLK_DIV (BSP_CLOCKS_CANFD_CLOCK_DIV_1) /* CANFDCLK Div /1 */ -#define BSP_CFG_CECCLK_DIV (BSP_CLOCKS_CEC_CLOCK_DIV_1) /* CECCLK Div /1 */ - -#endif /* BSP_CLOCK_CFG_H_ */ diff --git a/hw/bsp/ra/boards/ra6m5_ek/ozone/ra6m5.jdebug b/hw/bsp/ra/boards/ra6m5_ek/ozone/ra6m5.jdebug index 7b8ee9c95..ca18fed7c 100644 --- a/hw/bsp/ra/boards/ra6m5_ek/ozone/ra6m5.jdebug +++ b/hw/bsp/ra/boards/ra6m5_ek/ozone/ra6m5.jdebug @@ -20,9 +20,7 @@ void OnProjectLoad (void) { Project.SetTraceSource ("Trace Pins"); Project.SetTracePortWidth (4); - //File.Open ("../../../../../../examples/device/cdc_msc/cmake-build-ra6m5/cdc_msc.elf"); - //File.Open ("../../../../../../examples/dual/cmake-build-ra6m5/host_hid_to_device_cdc/host_hid_to_device_cdc.elf"); - File.Open ("../../../../../../examples/cmake-build-ra6m5/host/cdc_msc_hid/cdc_msc_hid.elf"); + File.Open ("../../../../../../examples/cmake-build-ra6m5_ek/device/cdc_msc/cdc_msc.elf"); } /********************************************************************* * diff --git a/hw/bsp/ra/boards/ra6m5_ek/ra_cfg/fsp_cfg/bsp/bsp_cfg.h b/hw/bsp/ra/boards/ra6m5_ek/ra_cfg/fsp_cfg/bsp/bsp_cfg.h new file mode 100644 index 000000000..90afbdef3 --- /dev/null +++ b/hw/bsp/ra/boards/ra6m5_ek/ra_cfg/fsp_cfg/bsp/bsp_cfg.h @@ -0,0 +1,62 @@ +/* generated configuration header file - do not edit */ +#ifndef BSP_CFG_H_ +#define BSP_CFG_H_ +#ifdef __cplusplus + extern "C" { + #endif + + #include "bsp_clock_cfg.h" + #include "bsp_mcu_family_cfg.h" + #include "board_cfg.h" + #define RA_NOT_DEFINED 0 + #ifndef BSP_CFG_RTOS + #if (RA_NOT_DEFINED) != (RA_NOT_DEFINED) + #define BSP_CFG_RTOS (2) + #elif (RA_NOT_DEFINED) != (RA_NOT_DEFINED) + #define BSP_CFG_RTOS (1) + #else + #define BSP_CFG_RTOS (0) + #endif + #endif + #ifndef BSP_CFG_RTC_USED + #define BSP_CFG_RTC_USED (RA_NOT_DEFINED) + #endif + #undef RA_NOT_DEFINED + #if defined(_RA_BOOT_IMAGE) + #define BSP_CFG_BOOT_IMAGE (1) + #endif + #define BSP_CFG_MCU_VCC_MV (3300) + #define BSP_CFG_STACK_MAIN_BYTES (0x1000) + #define BSP_CFG_HEAP_BYTES (0x1000) + #define BSP_CFG_PARAM_CHECKING_ENABLE (0) + #define BSP_CFG_ASSERT (0) + #define BSP_CFG_ERROR_LOG (0) + + #define BSP_CFG_PFS_PROTECT ((1)) + + #define BSP_CFG_C_RUNTIME_INIT ((1)) + #define BSP_CFG_EARLY_INIT ((0)) + + #define BSP_CFG_STARTUP_CLOCK_REG_NOT_RESET ((0)) + + #ifndef BSP_CLOCK_CFG_MAIN_OSC_POPULATED + #define BSP_CLOCK_CFG_MAIN_OSC_POPULATED (1) + #endif + + #ifndef BSP_CLOCK_CFG_MAIN_OSC_CLOCK_SOURCE + #define BSP_CLOCK_CFG_MAIN_OSC_CLOCK_SOURCE (0) + #endif + #ifndef BSP_CLOCK_CFG_SUBCLOCK_DRIVE + #define BSP_CLOCK_CFG_SUBCLOCK_DRIVE (0) + #endif + #ifndef BSP_CLOCK_CFG_SUBCLOCK_POPULATED + #define BSP_CLOCK_CFG_SUBCLOCK_POPULATED (1) + #endif + #ifndef BSP_CLOCK_CFG_SUBCLOCK_STABILIZATION_MS + #define BSP_CLOCK_CFG_SUBCLOCK_STABILIZATION_MS 1000 + #endif + + #ifdef __cplusplus + } + #endif +#endif /* BSP_CFG_H_ */ diff --git a/hw/bsp/ra/boards/ra6m5_ek/fsp_cfg/bsp/bsp_mcu_device_cfg.h b/hw/bsp/ra/boards/ra6m5_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_device_cfg.h similarity index 100% rename from hw/bsp/ra/boards/ra6m5_ek/fsp_cfg/bsp/bsp_mcu_device_cfg.h rename to hw/bsp/ra/boards/ra6m5_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_device_cfg.h diff --git a/hw/bsp/ra/boards/ra6m5_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_device_pn_cfg.h b/hw/bsp/ra/boards/ra6m5_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_device_pn_cfg.h new file mode 100644 index 000000000..e532478f8 --- /dev/null +++ b/hw/bsp/ra/boards/ra6m5_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_device_pn_cfg.h @@ -0,0 +1,11 @@ +/* generated configuration header file - do not edit */ +#ifndef BSP_MCU_DEVICE_PN_CFG_H_ +#define BSP_MCU_DEVICE_PN_CFG_H_ +#define BSP_MCU_R7FA6M5BH3CFC + #define BSP_MCU_FEATURE_SET ('B') + #define BSP_ROM_SIZE_BYTES (2097152) + #define BSP_RAM_SIZE_BYTES (524288) + #define BSP_DATA_FLASH_SIZE_BYTES (8192) + #define BSP_PACKAGE_LQFP + #define BSP_PACKAGE_PINS (176) +#endif /* BSP_MCU_DEVICE_PN_CFG_H_ */ diff --git a/hw/bsp/ra/boards/ra4m3_ek/fsp_cfg/bsp/bsp_mcu_family_cfg.h b/hw/bsp/ra/boards/ra6m5_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_family_cfg.h similarity index 55% rename from hw/bsp/ra/boards/ra4m3_ek/fsp_cfg/bsp/bsp_mcu_family_cfg.h rename to hw/bsp/ra/boards/ra6m5_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_family_cfg.h index 26e184a94..c01219377 100644 --- a/hw/bsp/ra/boards/ra4m3_ek/fsp_cfg/bsp/bsp_mcu_family_cfg.h +++ b/hw/bsp/ra/boards/ra6m5_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_family_cfg.h @@ -5,17 +5,17 @@ extern "C" { #endif -#include "bsp_mcu_device_pn_cfg.h" -#include "bsp_mcu_device_cfg.h" -#include "../../../ra/fsp/src/bsp/mcu/ra4m3/bsp_mcu_info.h" -#include "bsp_clock_cfg.h" -#define BSP_MCU_GROUP_RA4M3 (1) -#define BSP_LOCO_HZ (32768) -#define BSP_MOCO_HZ (8000000) -#define BSP_SUB_CLOCK_HZ (32768) -#if BSP_CFG_HOCO_FREQUENCY == 0 -#define BSP_HOCO_HZ (16000000) -#elif BSP_CFG_HOCO_FREQUENCY == 1 + #include "bsp_mcu_device_pn_cfg.h" + #include "bsp_mcu_device_cfg.h" + #include "../../../ra/fsp/src/bsp/mcu/ra6m5/bsp_mcu_info.h" + #include "bsp_clock_cfg.h" + #define BSP_MCU_GROUP_RA6M5 (1) + #define BSP_LOCO_HZ (32768) + #define BSP_MOCO_HZ (8000000) + #define BSP_SUB_CLOCK_HZ (32768) + #if BSP_CFG_HOCO_FREQUENCY == 0 + #define BSP_HOCO_HZ (16000000) + #elif BSP_CFG_HOCO_FREQUENCY == 1 #define BSP_HOCO_HZ (18000000) #elif BSP_CFG_HOCO_FREQUENCY == 2 #define BSP_HOCO_HZ (20000000) @@ -23,61 +23,62 @@ extern "C" { #error "Invalid HOCO frequency chosen (BSP_CFG_HOCO_FREQUENCY) in bsp_clock_cfg.h" #endif -#define BSP_CFG_FLL_ENABLE (0) + #define BSP_CFG_FLL_ENABLE (0) -#define BSP_CORTEX_VECTOR_TABLE_ENTRIES (16U) -#define BSP_VECTOR_TABLE_MAX_ENTRIES (112U) + #define BSP_CORTEX_VECTOR_TABLE_ENTRIES (16U) + #define BSP_VECTOR_TABLE_MAX_ENTRIES (112U) + #define BSP_CFG_INLINE_IRQ_FUNCTIONS (1) -#if defined(_RA_TZ_SECURE) + #if defined(_RA_TZ_SECURE) #define BSP_TZ_SECURE_BUILD (1) #define BSP_TZ_NONSECURE_BUILD (0) #elif defined(_RA_TZ_NONSECURE) #define BSP_TZ_SECURE_BUILD (0) #define BSP_TZ_NONSECURE_BUILD (1) #else -#define BSP_TZ_SECURE_BUILD (0) -#define BSP_TZ_NONSECURE_BUILD (0) -#endif + #define BSP_TZ_SECURE_BUILD (0) + #define BSP_TZ_NONSECURE_BUILD (0) + #endif -/* TrustZone Settings */ -#define BSP_TZ_CFG_INIT_SECURE_ONLY (BSP_CFG_CLOCKS_SECURE || (!BSP_CFG_CLOCKS_OVERRIDE)) -#define BSP_TZ_CFG_SKIP_INIT (BSP_TZ_NONSECURE_BUILD && BSP_TZ_CFG_INIT_SECURE_ONLY) -#define BSP_TZ_CFG_EXCEPTION_RESPONSE (0) + /* TrustZone Settings */ + #define BSP_TZ_CFG_INIT_SECURE_ONLY (BSP_CFG_CLOCKS_SECURE || (!BSP_CFG_CLOCKS_OVERRIDE)) + #define BSP_TZ_CFG_SKIP_INIT (BSP_TZ_NONSECURE_BUILD && BSP_TZ_CFG_INIT_SECURE_ONLY) + #define BSP_TZ_CFG_EXCEPTION_RESPONSE (0) -/* CMSIS TrustZone Settings */ -#define SCB_CSR_AIRCR_INIT (1) -#define SCB_AIRCR_BFHFNMINS_VAL (0) -#define SCB_AIRCR_SYSRESETREQS_VAL (1) -#define SCB_AIRCR_PRIS_VAL (0) -#define TZ_FPU_NS_USAGE (1) + /* CMSIS TrustZone Settings */ + #define SCB_CSR_AIRCR_INIT (1) + #define SCB_AIRCR_BFHFNMINS_VAL (0) + #define SCB_AIRCR_SYSRESETREQS_VAL (1) + #define SCB_AIRCR_PRIS_VAL (0) + #define TZ_FPU_NS_USAGE (1) #ifndef SCB_NSACR_CP10_11_VAL -#define SCB_NSACR_CP10_11_VAL (3U) + #define SCB_NSACR_CP10_11_VAL (3U) #endif #ifndef FPU_FPCCR_TS_VAL -#define FPU_FPCCR_TS_VAL (1U) + #define FPU_FPCCR_TS_VAL (1U) #endif -#define FPU_FPCCR_CLRONRETS_VAL (1) + #define FPU_FPCCR_CLRONRETS_VAL (1) #ifndef FPU_FPCCR_CLRONRET_VAL -#define FPU_FPCCR_CLRONRET_VAL (1) + #define FPU_FPCCR_CLRONRET_VAL (1) #endif -/* The C-Cache line size that is configured during startup. */ + /* The C-Cache line size that is configured during startup. */ #ifndef BSP_CFG_C_CACHE_LINE_SIZE -#define BSP_CFG_C_CACHE_LINE_SIZE (1U) + #define BSP_CFG_C_CACHE_LINE_SIZE (1U) #endif -/* Type 1 Peripheral Security Attribution */ + /* Type 1 Peripheral Security Attribution */ -/* Peripheral Security Attribution Register (PSAR) Settings */ + /* Peripheral Security Attribution Register (PSAR) Settings */ #ifndef BSP_TZ_CFG_PSARB #define BSP_TZ_CFG_PSARB (\ (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 1) /* CAN1 */ | \ (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 2) /* CAN0 */ | \ (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 8) /* IIC1 */ | \ (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 9) /* IIC0 */ | \ - (((1 > 0) ? 0U : 1U) << 11) /* USBFS */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 11) /* USBFS */ | \ (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 18) /* SPI1 */ | \ (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 19) /* SPI0 */ | \ (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 22) /* SCI9 */ | \ @@ -114,7 +115,7 @@ extern "C" { (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 13) /* POEG1 */ | \ (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 14) /* POEG0 */ | \ (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 15) /* ADC1 */ | \ - (((1 > 0) ? 0U : 1U) << 16) /* ADC0 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 16) /* ADC0 */ | \ (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 20) /* DAC */ | \ (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 22) /* TSN */ | \ 0xffae07f0) /* Unused */ @@ -129,13 +130,13 @@ extern "C" { (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 22) /* GPT9 */ | \ (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 23) /* GPT8 */ | \ (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 24) /* GPT7 */ | \ - (((1 > 0) ? 0U : 1U) << 25) /* GPT6 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 25) /* GPT6 */ | \ (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 26) /* GPT5 */ | \ (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 27) /* GPT4 */ | \ - (((1 > 0) ? 0U : 1U) << 28) /* GPT3 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 28) /* GPT3 */ | \ (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 29) /* GPT2 */ | \ - (((1 > 0) ? 0U : 1U) << 30) /* GPT1 */ | \ - (((1 > 0) ? 0U : 1U) << 31) /* GPT0 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 30) /* GPT1 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 31) /* GPT0 */ | \ 0x3f3ff8) /* Unused */ #endif #ifndef BSP_TZ_CFG_MSSAR @@ -145,19 +146,19 @@ extern "C" { 0xfffffffc) /* Unused */ #endif -/* Type 2 Peripheral Security Attribution */ + /* Type 2 Peripheral Security Attribution */ -/* Security attribution for Cache registers. */ + /* Security attribution for Cache registers. */ #ifndef BSP_TZ_CFG_CSAR #define BSP_TZ_CFG_CSAR (0xFFFFFFFFU) #endif -/* Security attribution for RSTSRn registers. */ + /* Security attribution for RSTSRn registers. */ #ifndef BSP_TZ_CFG_RSTSAR #define BSP_TZ_CFG_RSTSAR (0xFFFFFFFFU) #endif -/* Security attribution for registers of LVD channels. */ + /* Security attribution for registers of LVD channels. */ #ifndef BSP_TZ_CFG_LVDSAR #define BSP_TZ_CFG_LVDSAR (\ (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 0) | /* LVD Channel 1 */ \ @@ -165,16 +166,16 @@ extern "C" { 0xFFFFFFFCU) #endif -/* Security attribution for LPM registers. */ + /* Security attribution for LPM registers. */ #ifndef BSP_TZ_CFG_LPMSAR #define BSP_TZ_CFG_LPMSAR ((RA_NOT_DEFINED > 0) ? 0xFFFFFCEAU : 0xFFFFFFFFU) #endif -/* Deep Standby Interrupt Factor Security Attribution Register. */ + /* Deep Standby Interrupt Factor Security Attribution Register. */ #ifndef BSP_TZ_CFG_DPFSAR #define BSP_TZ_CFG_DPFSAR ((RA_NOT_DEFINED > 0) ? 0xF2E00000U : 0xFFFFFFFFU) #endif -/* Security attribution for CGC registers. */ + /* Security attribution for CGC registers. */ #ifndef BSP_TZ_CFG_CGFSAR #if BSP_CFG_CLOCKS_SECURE /* Protect all CGC registers from Non-secure write access. */ @@ -185,12 +186,12 @@ extern "C" { #endif #endif -/* Security attribution for Battery Backup registers. */ + /* Security attribution for Battery Backup registers. */ #ifndef BSP_TZ_CFG_BBFSAR #define BSP_TZ_CFG_BBFSAR (0x00FFFFFF) #endif -/* Security attribution for registers for IRQ channels. */ + /* Security attribution for registers for IRQ channels. */ #ifndef BSP_TZ_CFG_ICUSARA #define BSP_TZ_CFG_ICUSARA (\ (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 0U) /* External IRQ0 */ | \ @@ -203,8 +204,8 @@ extern "C" { (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 7U) /* External IRQ7 */ | \ (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 8U) /* External IRQ8 */ | \ (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 9U) /* External IRQ9 */ | \ - (((1 > 0) ? 0U : 1U) << 10U) /* External IRQ10 */ | \ - (((1 > 0) ? 0U : 1U) << 11U) /* External IRQ11 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 10U) /* External IRQ10 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 11U) /* External IRQ11 */ | \ (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 12U) /* External IRQ12 */ | \ (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 13U) /* External IRQ13 */ | \ (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 14U) /* External IRQ14 */ | \ @@ -212,12 +213,12 @@ extern "C" { 0xFFFF0000U) #endif -/* Security attribution for NMI registers. */ + /* Security attribution for NMI registers. */ #ifndef BSP_TZ_CFG_ICUSARB #define BSP_TZ_CFG_ICUSARB (0 | 0xFFFFFFFEU) /* Should match AIRCR.BFHFNMINS. */ #endif -/* Security attribution for registers for DMAC channels */ + /* Security attribution for registers for DMAC channels */ #ifndef BSP_TZ_CFG_ICUSARC #define BSP_TZ_CFG_ICUSARC (\ (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 0U) /* DMAC Channel 0 */ | \ @@ -231,29 +232,29 @@ extern "C" { 0xFFFFFF00U) #endif -/* Security attribution registers for SELSR0. */ + /* Security attribution registers for SELSR0. */ #ifndef BSP_TZ_CFG_ICUSARD #define BSP_TZ_CFG_ICUSARD ((RA_NOT_DEFINED > 0) ? 0xFFFFFFFEU : 0xFFFFFFFFU) #endif -/* Security attribution registers for WUPEN0. */ + /* Security attribution registers for WUPEN0. */ #ifndef BSP_TZ_CFG_ICUSARE #define BSP_TZ_CFG_ICUSARE ((RA_NOT_DEFINED > 0) ? 0x04F2FFFFU : 0xFFFFFFFFU) #endif -/* Security attribution registers for WUPEN1. */ + /* Security attribution registers for WUPEN1. */ #ifndef BSP_TZ_CFG_ICUSARF #define BSP_TZ_CFG_ICUSARF ((RA_NOT_DEFINED > 0) ? 0xFFFFFFF8U : 0xFFFFFFFFU) #endif -/* Set DTCSTSAR if the Secure program uses the DTC. */ + /* Set DTCSTSAR if the Secure program uses the DTC. */ #if RA_NOT_DEFINED == RA_NOT_DEFINED -#define BSP_TZ_CFG_DTC_USED (0U) + #define BSP_TZ_CFG_DTC_USED (0U) #else #define BSP_TZ_CFG_DTC_USED (1U) #endif -/* Security attribution of FLWT and FCKMHZ registers. */ + /* Security attribution of FLWT and FCKMHZ registers. */ #ifndef BSP_TZ_CFG_FSAR /* If the CGC registers are only accessible in Secure mode, than there is no * reason for nonsecure applications to access FLWT and FCKMHZ. */ @@ -266,118 +267,123 @@ extern "C" { #endif #endif -/* Security attribution for SRAM registers. */ + /* Security attribution for SRAM registers. */ #ifndef BSP_TZ_CFG_SRAMSAR /* If the CGC registers are only accessible in Secure mode, than there is no reason for Non Secure applications to access * SRAM0WTEN and therefore there is no reason to access PRCR2. */ -#define BSP_TZ_CFG_SRAMSAR (\ + #define BSP_TZ_CFG_SRAMSAR (\ 1 | \ ((BSP_CFG_CLOCKS_SECURE == 0) ? (1U << 1U) : 0U) | \ 4 | \ 0xFFFFFFF8U) #endif -/* Security attribution for Standby RAM registers. */ + /* Security attribution for Standby RAM registers. */ #ifndef BSP_TZ_CFG_STBRAMSAR -#define BSP_TZ_CFG_STBRAMSAR (0 | 0xFFFFFFF0U) + #define BSP_TZ_CFG_STBRAMSAR (0 | 0xFFFFFFF0U) #endif -/* Security attribution for the DMAC Bus Master MPU settings. */ + /* Security attribution for the DMAC Bus Master MPU settings. */ #ifndef BSP_TZ_CFG_MMPUSARA -/* The DMAC Bus Master MPU settings should align with the DMAC channel settings. */ -#define BSP_TZ_CFG_MMPUSARA (BSP_TZ_CFG_ICUSARC) + /* The DMAC Bus Master MPU settings should align with the DMAC channel settings. */ + #define BSP_TZ_CFG_MMPUSARA (BSP_TZ_CFG_ICUSARC) #endif -/* Security Attribution Register A for BUS Control registers. */ + /* Security Attribution Register A for BUS Control registers. */ #ifndef BSP_TZ_CFG_BUSSARA -#define BSP_TZ_CFG_BUSSARA (0xFFFFFFFFU) + #define BSP_TZ_CFG_BUSSARA (0xFFFFFFFFU) #endif -/* Security Attribution Register B for BUS Control registers. */ + /* Security Attribution Register B for BUS Control registers. */ #ifndef BSP_TZ_CFG_BUSSARB -#define BSP_TZ_CFG_BUSSARB (0xFFFFFFFFU) + #define BSP_TZ_CFG_BUSSARB (0xFFFFFFFFU) #endif -/* Enable Uninitialized Non-Secure Application Fallback. */ + /* Enable Uninitialized Non-Secure Application Fallback. */ #ifndef BSP_TZ_CFG_NON_SECURE_APPLICATION_FALLBACK -#define BSP_TZ_CFG_NON_SECURE_APPLICATION_FALLBACK (1U) + #define BSP_TZ_CFG_NON_SECURE_APPLICATION_FALLBACK (1U) #endif -#define OFS_SEQ1 0xA001A001 | (1 << 1) | (3 << 2) -#define OFS_SEQ2 (15 << 4) | (3 << 8) | (3 << 10) -#define OFS_SEQ3 (1 << 12) | (1 << 14) | (1 << 17) -#define OFS_SEQ4 (3 << 18) |(15 << 20) | (3 << 24) | (3 << 26) -#define OFS_SEQ5 (1 << 28) | (1 << 30) -#define BSP_CFG_ROM_REG_OFS0 (OFS_SEQ1 | OFS_SEQ2 | OFS_SEQ3 | OFS_SEQ4 | OFS_SEQ5) -/* Option Function Select Register 1 Security Attribution */ + #define OFS_SEQ1 0xA001A001 | (1 << 1) | (3 << 2) + #define OFS_SEQ2 (15 << 4) | (3 << 8) | (3 << 10) + #define OFS_SEQ3 (1 << 12) | (1 << 14) | (1 << 17) + #define OFS_SEQ4 (3 << 18) |(15 << 20) | (3 << 24) | (3 << 26) + #define OFS_SEQ5 (1 << 28) | (1 << 30) + #define BSP_CFG_ROM_REG_OFS0 (OFS_SEQ1 | OFS_SEQ2 | OFS_SEQ3 | OFS_SEQ4 | OFS_SEQ5) + + /* Option Function Select Register 1 Security Attribution */ #ifndef BSP_CFG_ROM_REG_OFS1_SEL #if defined(_RA_TZ_SECURE) || defined(_RA_TZ_NONSECURE) - #define BSP_CFG_ROM_REG_OFS1_SEL (0xFFFFF8F8U | ((BSP_CFG_CLOCKS_SECURE == 0) ? 0x700U : 0U) | ((RA_NOT_DEFINED > 0) ? 0U : 0x7U)) + #define BSP_CFG_ROM_REG_OFS1_SEL (0xFFFFF8F8U | ((0U << 0U)) | ((0U << 2U)) | ((BSP_CFG_CLOCKS_SECURE == 0) ? 0x700U : 0U)) #else -#define BSP_CFG_ROM_REG_OFS1_SEL (0xFFFFF8F8U) + #define BSP_CFG_ROM_REG_OFS1_SEL (0xFFFFF8F8U) #endif #endif -#define BSP_CFG_ROM_REG_OFS1 (0xFFFFFEF8 | (1 << 2) | (3) | (1 << 8)) + #define BSP_CFG_ROM_REG_OFS1 (0xFFFFFEF8 | (1 << 2) | (3) | (1 << 8)) -/* Used to create IELS values for the interrupt initialization table g_interrupt_event_link_select. */ -#define BSP_PRV_IELS_ENUM(vector) (ELC_ ## vector) + /* Used to create IELS values for the interrupt initialization table g_interrupt_event_link_select. */ + #define BSP_PRV_IELS_ENUM(vector) (ELC_ ## vector) -/* Dual Mode Select Register */ + /* Dual Mode Select Register */ #ifndef BSP_CFG_ROM_REG_DUALSEL -#define BSP_CFG_ROM_REG_DUALSEL (0xFFFFFFFFU) + #define BSP_CFG_ROM_REG_DUALSEL (0xFFFFFFF8U | (0x7U)) #endif -/* Block Protection Register 0 */ + /* Block Protection Register 0 */ #ifndef BSP_CFG_ROM_REG_BPS0 -#define BSP_CFG_ROM_REG_BPS0 (~( 0U)) + #define BSP_CFG_ROM_REG_BPS0 (~( 0U)) #endif -/* Block Protection Register 1 */ + /* Block Protection Register 1 */ #ifndef BSP_CFG_ROM_REG_BPS1 -#define BSP_CFG_ROM_REG_BPS1 (~( 0U)) + #define BSP_CFG_ROM_REG_BPS1 (~( 0U)) #endif -/* Block Protection Register 2 */ + /* Block Protection Register 2 */ #ifndef BSP_CFG_ROM_REG_BPS2 -#define BSP_CFG_ROM_REG_BPS2 (0xFFFFFFFFU) + #define BSP_CFG_ROM_REG_BPS2 (~( 0U)) #endif -/* Block Protection Register 3 */ + /* Block Protection Register 3 */ #ifndef BSP_CFG_ROM_REG_BPS3 -#define BSP_CFG_ROM_REG_BPS3 (0xFFFFFFFFU) + #define BSP_CFG_ROM_REG_BPS3 (0xFFFFFFFFU) #endif -/* Permanent Block Protection Register 0 */ + /* Permanent Block Protection Register 0 */ #ifndef BSP_CFG_ROM_REG_PBPS0 -#define BSP_CFG_ROM_REG_PBPS0 (~( 0U)) + #define BSP_CFG_ROM_REG_PBPS0 (~( 0U)) #endif -/* Permanent Block Protection Register 1 */ + /* Permanent Block Protection Register 1 */ #ifndef BSP_CFG_ROM_REG_PBPS1 -#define BSP_CFG_ROM_REG_PBPS1 (~( 0U)) + #define BSP_CFG_ROM_REG_PBPS1 (~( 0U)) #endif -/* Permanent Block Protection Register 2 */ + /* Permanent Block Protection Register 2 */ #ifndef BSP_CFG_ROM_REG_PBPS2 -#define BSP_CFG_ROM_REG_PBPS2 (0xFFFFFFFFU) + #define BSP_CFG_ROM_REG_PBPS2 (~( 0U)) #endif -/* Permanent Block Protection Register 3 */ + /* Permanent Block Protection Register 3 */ #ifndef BSP_CFG_ROM_REG_PBPS3 -#define BSP_CFG_ROM_REG_PBPS3 (0xFFFFFFFFU) + #define BSP_CFG_ROM_REG_PBPS3 (0xFFFFFFFFU) #endif -/* Security Attribution for Block Protection Register 0 (If any blocks are marked as protected in the secure application, then mark them as secure) */ + /* Security Attribution for Block Protection Register 0 (If any blocks are marked as protected in the secure application, then mark them as secure) */ #ifndef BSP_CFG_ROM_REG_BPS_SEL0 -#define BSP_CFG_ROM_REG_BPS_SEL0 (BSP_CFG_ROM_REG_BPS0 & BSP_CFG_ROM_REG_PBPS0) + #define BSP_CFG_ROM_REG_BPS_SEL0 (BSP_CFG_ROM_REG_BPS0 & BSP_CFG_ROM_REG_PBPS0) #endif -/* Security Attribution for Block Protection Register 1 (If any blocks are marked as protected in the secure application, then mark them as secure) */ + /* Security Attribution for Block Protection Register 1 (If any blocks are marked as protected in the secure application, then mark them as secure) */ #ifndef BSP_CFG_ROM_REG_BPS_SEL1 -#define BSP_CFG_ROM_REG_BPS_SEL1 (BSP_CFG_ROM_REG_BPS1 & BSP_CFG_ROM_REG_PBPS1) + #define BSP_CFG_ROM_REG_BPS_SEL1 (BSP_CFG_ROM_REG_BPS1 & BSP_CFG_ROM_REG_PBPS1) #endif -/* Security Attribution for Block Protection Register 2 (If any blocks are marked as protected in the secure application, then mark them as secure) */ + /* Security Attribution for Block Protection Register 2 (If any blocks are marked as protected in the secure application, then mark them as secure) */ #ifndef BSP_CFG_ROM_REG_BPS_SEL2 -#define BSP_CFG_ROM_REG_BPS_SEL2 (0xFFFFFFFFU) + #define BSP_CFG_ROM_REG_BPS_SEL2 (BSP_CFG_ROM_REG_BPS2 & BSP_CFG_ROM_REG_PBPS2) #endif -/* Security Attribution for Block Protection Register 3 (If any blocks are marked as protected in the secure application, then mark them as secure) */ + /* Security Attribution for Block Protection Register 3 (If any blocks are marked as protected in the secure application, then mark them as secure) */ #ifndef BSP_CFG_ROM_REG_BPS_SEL3 -#define BSP_CFG_ROM_REG_BPS_SEL3 (0xFFFFFFFFU) + #define BSP_CFG_ROM_REG_BPS_SEL3 (BSP_CFG_ROM_REG_BPS3 & BSP_CFG_ROM_REG_PBPS3) +#endif + /* Security Attribution for Bank Select Register */ +#ifndef BSP_CFG_ROM_REG_BANKSEL_SEL + #define BSP_CFG_ROM_REG_BANKSEL_SEL (0xFFFFFFFFU) #endif #ifndef BSP_CLOCK_CFG_MAIN_OSC_WAIT -#define BSP_CLOCK_CFG_MAIN_OSC_WAIT (9) + #define BSP_CLOCK_CFG_MAIN_OSC_WAIT (9) #endif #ifdef __cplusplus diff --git a/hw/bsp/ra/boards/ra6m5_ek/ra_cfg/fsp_cfg/bsp/bsp_pin_cfg.h b/hw/bsp/ra/boards/ra6m5_ek/ra_cfg/fsp_cfg/bsp/bsp_pin_cfg.h new file mode 100644 index 000000000..d2eec08ae --- /dev/null +++ b/hw/bsp/ra/boards/ra6m5_ek/ra_cfg/fsp_cfg/bsp/bsp_pin_cfg.h @@ -0,0 +1,99 @@ +/* generated configuration header file - do not edit */ +#ifndef BSP_PIN_CFG_H_ +#define BSP_PIN_CFG_H_ +#include "r_ioport.h" + +/* Common macro for FSP header files. There is also a corresponding FSP_FOOTER macro at the end of this file. */ +FSP_HEADER + +#define MIKROBUS_AN_ARDUINO_A0 (BSP_IO_PORT_00_PIN_00) +#define ARDUINO_A1 (BSP_IO_PORT_00_PIN_01) +#define ARDUINO_A2 (BSP_IO_PORT_00_PIN_02) +#define ARDUINO_A3 (BSP_IO_PORT_00_PIN_03) +#define SW2 (BSP_IO_PORT_00_PIN_04) +#define SW1 (BSP_IO_PORT_00_PIN_05) +#define LED1 (BSP_IO_PORT_00_PIN_06) +#define LED2 (BSP_IO_PORT_00_PIN_07) +#define LED3 (BSP_IO_PORT_00_PIN_08) +#define ARDUINO_A4 (BSP_IO_PORT_00_PIN_14) +#define ARDUINO_A5 (BSP_IO_PORT_00_PIN_15) +#define OSPI_CLK (BSP_IO_PORT_01_PIN_00) +#define OSPI_SIO7 (BSP_IO_PORT_01_PIN_01) +#define OSPI_SIO1 (BSP_IO_PORT_01_PIN_02) +#define OSPI_SIO6 (BSP_IO_PORT_01_PIN_03) +#define OSPI_DQS (BSP_IO_PORT_01_PIN_04) +#define OSPI_SIO5 (BSP_IO_PORT_01_PIN_05) +#define OSPI_SIO0 (BSP_IO_PORT_01_PIN_06) +#define OSPI_SIO3 (BSP_IO_PORT_01_PIN_07) +#define MIKROBUS_PWM_ARDUINO_D3_PWM (BSP_IO_PORT_01_PIN_11) +#define ARDUINO_D4 (BSP_IO_PORT_01_PIN_12) +#define ARDUINO_D5 (BSP_IO_PORT_01_PIN_13) +#define ARDUINO_D6 (BSP_IO_PORT_01_PIN_14) +#define ARDUINO_D9 (BSP_IO_PORT_01_PIN_15) +#define MIKROBUS_MISO_ARDUINO_MISO_PMOD1_MISO (BSP_IO_PORT_02_PIN_02) +#define MIKROBUS_MOSI_ARDUINO_MOSI_PMOD1_MOSI (BSP_IO_PORT_02_PIN_03) +#define MIKROBUS_SCK_ARDUINO_SCK_PMOD1_SCK (BSP_IO_PORT_02_PIN_04) +#define MIKROBUS_SS_ARDUINO_SS (BSP_IO_PORT_02_PIN_05) +#define PMOD1_SS (BSP_IO_PORT_02_PIN_06) +#define ARDUINO_D8 (BSP_IO_PORT_02_PIN_07) +#define PMOD1_SS2 (BSP_IO_PORT_03_PIN_01) +#define PMOD1_SS3 (BSP_IO_PORT_03_PIN_02) +#define MIKROBUS_RESET_ARDUINO_RESET (BSP_IO_PORT_03_PIN_03) +#define QSPI_CLK (BSP_IO_PORT_03_PIN_05) +#define QSPI_CS (BSP_IO_PORT_03_PIN_06) +#define QSPI_IO0 (BSP_IO_PORT_03_PIN_07) +#define QSPI_IO1 (BSP_IO_PORT_03_PIN_08) +#define QSPI_IO2 (BSP_IO_PORT_03_PIN_09) +#define QSPI_IO3 (BSP_IO_PORT_03_PIN_10) +#define PMOD1_RST (BSP_IO_PORT_03_PIN_11) +#define PMOD2_INT (BSP_IO_PORT_04_PIN_00) +#define ETH_MDC (BSP_IO_PORT_04_PIN_01) +#define ETH_MDIO (BSP_IO_PORT_04_PIN_02) +#define ETH_RST (BSP_IO_PORT_04_PIN_03) +#define PMOD2_RST (BSP_IO_PORT_04_PIN_04) +#define ETH_TXEN (BSP_IO_PORT_04_PIN_05) +#define ETH_TXD1 (BSP_IO_PORT_04_PIN_06) +#define USBFS_VBUS (BSP_IO_PORT_04_PIN_07) +#define PMOD2_SS2 (BSP_IO_PORT_04_PIN_08) +#define MIKROBUS_INT_ARDUINO_INT0 (BSP_IO_PORT_04_PIN_09) +#define PMOD2_MISO (BSP_IO_PORT_04_PIN_10) +#define PMOD2_MOSI (BSP_IO_PORT_04_PIN_11) +#define PMOD2_SCK (BSP_IO_PORT_04_PIN_12) +#define PMOS2_SS (BSP_IO_PORT_04_PIN_13) +#define GROVE1_SDA_QWIIC_SDA (BSP_IO_PORT_04_PIN_14) +#define GROVE1_SCL_QWIIC_SCL (BSP_IO_PORT_04_PIN_15) +#define USBFS_VBUS_EN (BSP_IO_PORT_05_PIN_00) +#define USBFS_OVERCURA (BSP_IO_PORT_05_PIN_01) +#define GROVE2_SCL (BSP_IO_PORT_05_PIN_05) +#define GROVE2_SDA (BSP_IO_PORT_05_PIN_06) +#define MIKROBUS_SDA_ARDUINO_SDA (BSP_IO_PORT_05_PIN_11) +#define MIKROBUS_SCL_ARDUINO_SCL (BSP_IO_PORT_05_PIN_12) +#define OSPI_SIO4 (BSP_IO_PORT_06_PIN_00) +#define OSPI_SIO2 (BSP_IO_PORT_06_PIN_01) +#define OSPI_CS1 (BSP_IO_PORT_06_PIN_02) +#define ARDUINO_D7 (BSP_IO_PORT_06_PIN_08) +#define CAN_TXD (BSP_IO_PORT_06_PIN_09) +#define CAN_RDX (BSP_IO_PORT_06_PIN_10) +#define CAN_STBY (BSP_IO_PORT_06_PIN_11) +#define MIKROBUS_TX_ARDUINO_TX (BSP_IO_PORT_06_PIN_13) +#define MIKROBUS_RX_ARDUINO_RX (BSP_IO_PORT_06_PIN_14) +#define OSPI_RST (BSP_IO_PORT_06_PIN_15) +#define ETH_TXD0 (BSP_IO_PORT_07_PIN_00) +#define ETH_50REF (BSP_IO_PORT_07_PIN_01) +#define ETH_RXD0 (BSP_IO_PORT_07_PIN_02) +#define ETH_RXD1 (BSP_IO_PORT_07_PIN_03) +#define ETH_RXERR (BSP_IO_PORT_07_PIN_04) +#define ETH_CRSDV (BSP_IO_PORT_07_PIN_05) +#define ETH_INT (BSP_IO_PORT_07_PIN_06) +#define USBHS_OVERCURA (BSP_IO_PORT_07_PIN_07) +#define PMOD2_SS3 (BSP_IO_PORT_07_PIN_08) +#define PMOD1_INT (BSP_IO_PORT_09_PIN_05) +#define USBHS_VBUS_EN (BSP_IO_PORT_11_PIN_00) +#define USBHS_VBUS (BSP_IO_PORT_11_PIN_01) +extern const ioport_cfg_t g_bsp_pin_cfg; /* RA6M5 EK */ + +void BSP_PinConfigSecurityInit(); + +/* Common macro for FSP header files. There is also a corresponding FSP_HEADER macro at the top of this file. */ +FSP_FOOTER +#endif /* BSP_PIN_CFG_H_ */ diff --git a/hw/bsp/ra/boards/ra6m5_ek/ra_cfg/fsp_cfg/r_ioport_cfg.h b/hw/bsp/ra/boards/ra6m5_ek/ra_cfg/fsp_cfg/r_ioport_cfg.h new file mode 100644 index 000000000..d2688bf5b --- /dev/null +++ b/hw/bsp/ra/boards/ra6m5_ek/ra_cfg/fsp_cfg/r_ioport_cfg.h @@ -0,0 +1,13 @@ +/* generated configuration header file - do not edit */ +#ifndef R_IOPORT_CFG_H_ +#define R_IOPORT_CFG_H_ +#ifdef __cplusplus +extern "C" { +#endif + +#define IOPORT_CFG_PARAM_CHECKING_ENABLE (BSP_CFG_PARAM_CHECKING_ENABLE) + +#ifdef __cplusplus +} +#endif +#endif /* R_IOPORT_CFG_H_ */ diff --git a/hw/bsp/ra/boards/portenta_c33/fsp_cfg/bsp_clock_cfg.h b/hw/bsp/ra/boards/ra6m5_ek/ra_gen/bsp_clock_cfg.h similarity index 100% rename from hw/bsp/ra/boards/portenta_c33/fsp_cfg/bsp_clock_cfg.h rename to hw/bsp/ra/boards/ra6m5_ek/ra_gen/bsp_clock_cfg.h diff --git a/hw/bsp/ra/boards/ra6m5_ek/ra_gen/common_data.c b/hw/bsp/ra/boards/ra6m5_ek/ra_gen/common_data.c new file mode 100644 index 000000000..50036c0ad --- /dev/null +++ b/hw/bsp/ra/boards/ra6m5_ek/ra_gen/common_data.c @@ -0,0 +1,11 @@ +/* generated common source file - do not edit */ +#include "common_data.h" +ioport_instance_ctrl_t g_ioport_ctrl; +const ioport_instance_t g_ioport = + { + .p_api = &g_ioport_on_ioport, + .p_ctrl = &g_ioport_ctrl, + .p_cfg = &g_bsp_pin_cfg, + }; +void g_common_init(void) { +} diff --git a/hw/bsp/ra/boards/ra6m5_ek/ra_gen/common_data.h b/hw/bsp/ra/boards/ra6m5_ek/ra_gen/common_data.h new file mode 100644 index 000000000..6a08cbee0 --- /dev/null +++ b/hw/bsp/ra/boards/ra6m5_ek/ra_gen/common_data.h @@ -0,0 +1,20 @@ +/* generated common header file - do not edit */ +#ifndef COMMON_DATA_H_ +#define COMMON_DATA_H_ +#include +#include "bsp_api.h" +#include "r_ioport.h" +#include "bsp_pin_cfg.h" +FSP_HEADER +#define IOPORT_CFG_NAME g_bsp_pin_cfg +#define IOPORT_CFG_OPEN R_IOPORT_Open +#define IOPORT_CFG_CTRL g_ioport_ctrl + +/* IOPORT Instance */ +extern const ioport_instance_t g_ioport; + +/* IOPORT control structure. */ +extern ioport_instance_ctrl_t g_ioport_ctrl; +void g_common_init(void); +FSP_FOOTER +#endif /* COMMON_DATA_H_ */ diff --git a/hw/bsp/ra/boards/ra6m5_ek/ra_gen/pin_data.c b/hw/bsp/ra/boards/ra6m5_ek/ra_gen/pin_data.c new file mode 100644 index 000000000..6b814d74a --- /dev/null +++ b/hw/bsp/ra/boards/ra6m5_ek/ra_gen/pin_data.c @@ -0,0 +1,411 @@ +/* generated pin source file - do not edit */ +#include "bsp_api.h" +#include "r_ioport.h" + + +const ioport_pin_cfg_t g_bsp_pin_cfg_data[] = { + { + .pin = BSP_IO_PORT_00_PIN_00, + .pin_cfg = ((uint32_t) IOPORT_CFG_ANALOG_ENABLE) + }, + { + .pin = BSP_IO_PORT_00_PIN_01, + .pin_cfg = ((uint32_t) IOPORT_CFG_ANALOG_ENABLE) + }, + { + .pin = BSP_IO_PORT_00_PIN_02, + .pin_cfg = ((uint32_t) IOPORT_CFG_ANALOG_ENABLE) + }, + { + .pin = BSP_IO_PORT_00_PIN_03, + .pin_cfg = ((uint32_t) IOPORT_CFG_ANALOG_ENABLE) + }, + { + .pin = BSP_IO_PORT_00_PIN_04, + .pin_cfg = ((uint32_t) IOPORT_CFG_IRQ_ENABLE | (uint32_t) IOPORT_CFG_PORT_DIRECTION_INPUT) + }, + { + .pin = BSP_IO_PORT_00_PIN_05, + .pin_cfg = ((uint32_t) IOPORT_CFG_IRQ_ENABLE | (uint32_t) IOPORT_CFG_PORT_DIRECTION_INPUT) + }, + { + .pin = BSP_IO_PORT_00_PIN_06, + .pin_cfg = ((uint32_t) IOPORT_CFG_PORT_DIRECTION_OUTPUT | (uint32_t) IOPORT_CFG_PORT_OUTPUT_LOW) + }, + { + .pin = BSP_IO_PORT_00_PIN_07, + .pin_cfg = ((uint32_t) IOPORT_CFG_PORT_DIRECTION_OUTPUT | (uint32_t) IOPORT_CFG_PORT_OUTPUT_LOW) + }, + { + .pin = BSP_IO_PORT_00_PIN_08, + .pin_cfg = ((uint32_t) IOPORT_CFG_PORT_DIRECTION_OUTPUT | (uint32_t) IOPORT_CFG_PORT_OUTPUT_LOW) + }, + { + .pin = BSP_IO_PORT_00_PIN_14, + .pin_cfg = ((uint32_t) IOPORT_CFG_ANALOG_ENABLE) + }, + { + .pin = BSP_IO_PORT_00_PIN_15, + .pin_cfg = ((uint32_t) IOPORT_CFG_ANALOG_ENABLE) + }, + { + .pin = BSP_IO_PORT_01_PIN_00, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HS_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_OSPI) + }, + { + .pin = BSP_IO_PORT_01_PIN_01, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HS_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_OSPI) + }, + { + .pin = BSP_IO_PORT_01_PIN_02, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HS_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_OSPI) + }, + { + .pin = BSP_IO_PORT_01_PIN_03, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HS_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_OSPI) + }, + { + .pin = BSP_IO_PORT_01_PIN_04, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HS_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_OSPI) + }, + { + .pin = BSP_IO_PORT_01_PIN_05, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HS_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_OSPI) + }, + { + .pin = BSP_IO_PORT_01_PIN_06, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HS_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_OSPI) + }, + { + .pin = BSP_IO_PORT_01_PIN_07, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HS_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_OSPI) + }, + { + .pin = BSP_IO_PORT_01_PIN_08, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_DEBUG) + }, + { + .pin = BSP_IO_PORT_01_PIN_11, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_GPT1) + }, + { + .pin = BSP_IO_PORT_01_PIN_12, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PORT_DIRECTION_OUTPUT | (uint32_t) IOPORT_CFG_PORT_OUTPUT_LOW) + }, + { + .pin = BSP_IO_PORT_01_PIN_13, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PORT_DIRECTION_OUTPUT | (uint32_t) IOPORT_CFG_PORT_OUTPUT_LOW) + }, + { + .pin = BSP_IO_PORT_01_PIN_14, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PORT_DIRECTION_OUTPUT | (uint32_t) IOPORT_CFG_PORT_OUTPUT_LOW) + }, + { + .pin = BSP_IO_PORT_01_PIN_15, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PORT_DIRECTION_OUTPUT | (uint32_t) IOPORT_CFG_PORT_OUTPUT_LOW) + }, + { + .pin = BSP_IO_PORT_02_PIN_02, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SPI) + }, + { + .pin = BSP_IO_PORT_02_PIN_03, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SPI) + }, + { + .pin = BSP_IO_PORT_02_PIN_04, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SPI) + }, + { + .pin = BSP_IO_PORT_02_PIN_05, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SPI) + }, + { + .pin = BSP_IO_PORT_02_PIN_06, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SPI) + }, + { + .pin = BSP_IO_PORT_02_PIN_07, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PORT_DIRECTION_OUTPUT | (uint32_t) IOPORT_CFG_PORT_OUTPUT_LOW) + }, + { + .pin = BSP_IO_PORT_02_PIN_08, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_TRACE) + }, + { + .pin = BSP_IO_PORT_02_PIN_09, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_TRACE) + }, + { + .pin = BSP_IO_PORT_02_PIN_10, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_TRACE) + }, + { + .pin = BSP_IO_PORT_02_PIN_11, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_TRACE) + }, + { + .pin = BSP_IO_PORT_02_PIN_14, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_TRACE) + }, + { + .pin = BSP_IO_PORT_03_PIN_00, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_DEBUG) + }, + { + .pin = BSP_IO_PORT_03_PIN_01, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SPI) + }, + { + .pin = BSP_IO_PORT_03_PIN_02, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SPI) + }, + { + .pin = BSP_IO_PORT_03_PIN_03, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PORT_DIRECTION_OUTPUT | (uint32_t) IOPORT_CFG_PORT_OUTPUT_LOW) + }, + { + .pin = BSP_IO_PORT_03_PIN_05, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_QSPI) + }, + { + .pin = BSP_IO_PORT_03_PIN_06, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_QSPI) + }, + { + .pin = BSP_IO_PORT_03_PIN_07, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_QSPI) + }, + { + .pin = BSP_IO_PORT_03_PIN_08, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_QSPI) + }, + { + .pin = BSP_IO_PORT_03_PIN_09, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_QSPI) + }, + { + .pin = BSP_IO_PORT_03_PIN_10, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_QSPI) + }, + { + .pin = BSP_IO_PORT_03_PIN_11, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PORT_DIRECTION_OUTPUT | (uint32_t) IOPORT_CFG_PORT_OUTPUT_LOW) + }, + { + .pin = BSP_IO_PORT_04_PIN_00, + .pin_cfg = ((uint32_t) IOPORT_CFG_IRQ_ENABLE | (uint32_t) IOPORT_CFG_PORT_DIRECTION_INPUT | (uint32_t) IOPORT_CFG_PULLUP_ENABLE) + }, + { + .pin = BSP_IO_PORT_04_PIN_01, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_ETHER_RMII) + }, + { + .pin = BSP_IO_PORT_04_PIN_02, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_ETHER_RMII) + }, + { + .pin = BSP_IO_PORT_04_PIN_03, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PORT_DIRECTION_OUTPUT | (uint32_t) IOPORT_CFG_PORT_OUTPUT_HIGH) + }, + { + .pin = BSP_IO_PORT_04_PIN_04, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PORT_DIRECTION_OUTPUT | (uint32_t) IOPORT_CFG_PORT_OUTPUT_LOW) + }, + { + .pin = BSP_IO_PORT_04_PIN_05, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_ETHER_RMII) + }, + { + .pin = BSP_IO_PORT_04_PIN_06, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_ETHER_RMII) + }, + { + .pin = BSP_IO_PORT_04_PIN_07, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_USB_FS) + }, + { + .pin = BSP_IO_PORT_04_PIN_08, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PORT_DIRECTION_OUTPUT | (uint32_t) IOPORT_CFG_PORT_OUTPUT_LOW) + }, + { + .pin = BSP_IO_PORT_04_PIN_09, + .pin_cfg = ((uint32_t) IOPORT_CFG_IRQ_ENABLE | (uint32_t) IOPORT_CFG_PORT_DIRECTION_INPUT | (uint32_t) IOPORT_CFG_PULLUP_ENABLE) + }, + { + .pin = BSP_IO_PORT_04_PIN_10, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SPI) + }, + { + .pin = BSP_IO_PORT_04_PIN_11, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SPI) + }, + { + .pin = BSP_IO_PORT_04_PIN_12, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SPI) + }, + { + .pin = BSP_IO_PORT_04_PIN_13, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SPI) + }, + { + .pin = BSP_IO_PORT_04_PIN_14, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_IIC) + }, + { + .pin = BSP_IO_PORT_04_PIN_15, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_IIC) + }, + { + .pin = BSP_IO_PORT_05_PIN_00, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_USB_FS) + }, + { + .pin = BSP_IO_PORT_05_PIN_01, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_USB_FS) + }, + { + .pin = BSP_IO_PORT_05_PIN_05, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_NMOS_ENABLE | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SCI0_2_4_6_8) + }, + { + .pin = BSP_IO_PORT_05_PIN_06, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_NMOS_ENABLE | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SCI0_2_4_6_8) + }, + { + .pin = BSP_IO_PORT_05_PIN_11, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_IIC) + }, + { + .pin = BSP_IO_PORT_05_PIN_12, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_IIC) + }, + { + .pin = BSP_IO_PORT_06_PIN_00, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HS_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_OSPI) + }, + { + .pin = BSP_IO_PORT_06_PIN_01, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HS_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_OSPI) + }, + { + .pin = BSP_IO_PORT_06_PIN_02, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_OSPI) + }, + { + .pin = BSP_IO_PORT_06_PIN_08, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PORT_DIRECTION_OUTPUT | (uint32_t) IOPORT_CFG_PORT_OUTPUT_LOW) + }, + { + .pin = BSP_IO_PORT_06_PIN_09, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_CAN) + }, + { + .pin = BSP_IO_PORT_06_PIN_10, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_CAN) + }, + { + .pin = BSP_IO_PORT_06_PIN_11, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PORT_DIRECTION_OUTPUT | (uint32_t) IOPORT_CFG_PORT_OUTPUT_LOW) + }, + { + .pin = BSP_IO_PORT_06_PIN_13, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SCI1_3_5_7_9) + }, + { + .pin = BSP_IO_PORT_06_PIN_14, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SCI1_3_5_7_9) + }, + { + .pin = BSP_IO_PORT_06_PIN_15, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_MID | (uint32_t) IOPORT_CFG_PORT_DIRECTION_OUTPUT | (uint32_t) IOPORT_CFG_PORT_OUTPUT_HIGH) + }, + { + .pin = BSP_IO_PORT_07_PIN_00, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_ETHER_RMII) + }, + { + .pin = BSP_IO_PORT_07_PIN_01, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_ETHER_RMII) + }, + { + .pin = BSP_IO_PORT_07_PIN_02, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_ETHER_RMII) + }, + { + .pin = BSP_IO_PORT_07_PIN_03, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_ETHER_RMII) + }, + { + .pin = BSP_IO_PORT_07_PIN_04, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_ETHER_RMII) + }, + { + .pin = BSP_IO_PORT_07_PIN_05, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_ETHER_RMII) + }, + { + .pin = BSP_IO_PORT_07_PIN_06, + .pin_cfg = ((uint32_t) IOPORT_CFG_IRQ_ENABLE | (uint32_t) IOPORT_CFG_PORT_DIRECTION_INPUT) + }, + { + .pin = BSP_IO_PORT_07_PIN_07, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_USB_HS) + }, + { + .pin = BSP_IO_PORT_07_PIN_08, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SPI) + }, + { + .pin = BSP_IO_PORT_09_PIN_05, + .pin_cfg = ((uint32_t) IOPORT_CFG_IRQ_ENABLE | (uint32_t) IOPORT_CFG_PORT_DIRECTION_INPUT | (uint32_t) IOPORT_CFG_PULLUP_ENABLE) + }, + { + .pin = BSP_IO_PORT_11_PIN_00, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_USB_HS) + }, + { + .pin = BSP_IO_PORT_11_PIN_01, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_USB_HS) + }, +}; + +const ioport_cfg_t g_bsp_pin_cfg = { + .number_of_pins = sizeof(g_bsp_pin_cfg_data)/sizeof(ioport_pin_cfg_t), + .p_pin_cfg_data = &g_bsp_pin_cfg_data[0], +}; + +#if BSP_TZ_SECURE_BUILD + +void R_BSP_PinCfgSecurityInit(void); + +/* Initialize SAR registers for secure pins. */ +void R_BSP_PinCfgSecurityInit(void) +{ + #if (2U == BSP_FEATURE_IOPORT_VERSION) + uint32_t pmsar[BSP_FEATURE_BSP_NUM_PMSAR]; + #else + uint16_t pmsar[BSP_FEATURE_BSP_NUM_PMSAR]; + #endif + memset(pmsar, 0xFF, BSP_FEATURE_BSP_NUM_PMSAR * sizeof(R_PMISC->PMSAR[0])); + + + for(uint32_t i = 0; i < g_bsp_pin_cfg.number_of_pins; i++) + { + uint32_t port_pin = g_bsp_pin_cfg.p_pin_cfg_data[i].pin; + uint32_t port = port_pin >> 8U; + uint32_t pin = port_pin & 0xFFU; + pmsar[port] &= (uint16_t) ~(1U << pin); + } + + for(uint32_t i = 0; i < BSP_FEATURE_BSP_NUM_PMSAR; i++) + { + #if (2U == BSP_FEATURE_IOPORT_VERSION) + R_PMISC->PMSAR[i].PMSAR = (uint16_t) pmsar[i]; + #else + R_PMISC->PMSAR[i].PMSAR = pmsar[i]; + #endif + } + +} +#endif diff --git a/hw/bsp/ra/boards/ra6m5_ek/script/fsp.ld b/hw/bsp/ra/boards/ra6m5_ek/script/fsp.ld new file mode 100644 index 000000000..605eef7d2 --- /dev/null +++ b/hw/bsp/ra/boards/ra6m5_ek/script/fsp.ld @@ -0,0 +1,769 @@ +/* + Linker File for Renesas FSP +*/ + +INCLUDE memory_regions.ld + +/* Uncomment and set XIP_SECONDARY_SLOT_IMAGE to 1 below for the secondary XIP application image.*/ +/* + XIP_SECONDARY_SLOT_IMAGE = 1; +*/ + +QSPI_FLASH_PRV_LENGTH = DEFINED(QSPI_FLASH_SIZE) ? ABSOLUTE(QSPI_FLASH_SIZE) : ABSOLUTE(QSPI_FLASH_LENGTH); +OSPI_DEVICE_0_PRV_LENGTH = DEFINED(OSPI_DEVICE_0_SIZE) ? ABSOLUTE(OSPI_DEVICE_0_SIZE) : ABSOLUTE(OSPI_DEVICE_0_LENGTH); +OSPI_DEVICE_1_PRV_LENGTH = DEFINED(OSPI_DEVICE_1_SIZE) ? ABSOLUTE(OSPI_DEVICE_1_SIZE) : ABSOLUTE(OSPI_DEVICE_1_LENGTH); + +/* If a flat (secure) project has DEFINED RAM_NS_BUFFER_LENGTH, then emit IDAU symbols to allocate non-secure RAM. */ +__RESERVE_NS_RAM = !DEFINED(PROJECT_NONSECURE) && DEFINED(RAM_NS_BUFFER_LENGTH) && (OPTION_SETTING_S_LENGTH != 0); + +ITCM_START = DEFINED(ITCM_START)? ITCM_START : 0; +ITCM_LENGTH = DEFINED(ITCM_LENGTH)? ITCM_LENGTH : 0; +DTCM_START = DEFINED(DTCM_START)? DTCM_START : 0; +DTCM_LENGTH = DEFINED(DTCM_LENGTH)? DTCM_LENGTH : 0; +RAM_NS_BUFFER_BLOCK_LENGTH = DEFINED(RAM_NS_BUFFER_LENGTH) ? ALIGN(RAM_NS_BUFFER_LENGTH, 8192) : 0; +RAM_NS_BUFFER_LENGTH = DEFINED(RAM_NS_BUFFER_LENGTH) ? RAM_NS_BUFFER_LENGTH : 0; +RAM_NS_BUFFER_START = RAM_START + RAM_LENGTH - RAM_NS_BUFFER_LENGTH; +RAM_NS_BUFFER_BLOCK_START = RAM_START + RAM_LENGTH - RAM_NS_BUFFER_BLOCK_LENGTH; + +OPTION_SETTING_START_NS = DEFINED(PROJECT_NONSECURE) ? OPTION_SETTING_START : OPTION_SETTING_START + 0x80; + +/* This definition is used to avoid moving the counter in OPTION_SETTING regions for projects that should not configure option settings. + * Bootloader images do not configure option settings because they are owned by the bootloader. + * FSP_BOOTABLE_IMAGE is only defined in bootloader images. */ +__bl_FSP_BOOTABLE_IMAGE = 1; +__bln_FSP_BOOTABLE_IMAGE = 1; +PROJECT_SECURE_OR_FLAT = (!DEFINED(PROJECT_NONSECURE) || DEFINED(PROJECT_SECURE)) && OPTION_SETTING_LENGTH && !DEFINED(FSP_BOOTABLE_IMAGE); +USE_OPTION_SETTING_NS = DEFINED(PROJECT_NONSECURE) && !DEFINED(FSP_BOOTABLE_IMAGE); + +__bl_FLASH_IMAGE_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_IMAGE_NUMBER == 1 ? FLASH_START + FLASH_BOOTLOADER_LENGTH + FLASH_BOOTLOADER_HEADER_LENGTH : + (DEFINED(BOOTLOADER_SECONDARY_USE_QSPI) || DEFINED(BOOTLOADER_SECONDARY_USE_OSPI_B)) ? FLASH_START + FLASH_BOOTLOADER_LENGTH + FLASH_BOOTLOADER_SCRATCH_LENGTH + FLASH_BOOTLOADER_HEADER_LENGTH : + FLASH_START + FLASH_BOOTLOADER_LENGTH + FLASH_BOOTLOADER_SCRATCH_LENGTH + FLASH_APPLICATION_S_LENGTH + FLASH_BOOTLOADER_HEADER_LENGTH; +__bl_FLASH_IMAGE_LENGTH = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_S_LENGTH - FLASH_BOOTLOADER_HEADER_LENGTH; +__bl_FLASH_IMAGE_END = __bl_FLASH_IMAGE_START + __bl_FLASH_IMAGE_LENGTH; +__bl_XIP_SECONDARY_FLASH_IMAGE_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_START + FLASH_BOOTLOADER_LENGTH + FLASH_APPLICATION_S_LENGTH + FLASH_BOOTLOADER_HEADER_LENGTH; +__bl_XIP_SECONDARY_FLASH_IMAGE_END = __bl_XIP_SECONDARY_FLASH_IMAGE_START + __bl_FLASH_IMAGE_LENGTH; +__bl_FLASH_NS_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_NS_LENGTH == 0 ? __bl_FLASH_IMAGE_END : + __bl_FLASH_IMAGE_START - FLASH_BOOTLOADER_HEADER_LENGTH + FLASH_APPLICATION_S_LENGTH; +__bl_FLASH_NSC_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_NS_LENGTH == 0 ? __bl_FLASH_IMAGE_END : + __bl_FLASH_IMAGE_END - FLASH_APPLICATION_NSC_LENGTH; +__bl_RAM_NS_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_NS_LENGTH == 0 ? RAM_START + RAM_LENGTH : + RAM_START + RAM_LENGTH - RAM_APPLICATION_NS_LENGTH; +__bl_RAM_NSC_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_NS_LENGTH == 0 ? RAM_START + RAM_LENGTH : + __bl_RAM_NS_START - RAM_APPLICATION_NSC_LENGTH; +__bl_FLASH_NS_IMAGE_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_NS_LENGTH == 0 ? __bl_FLASH_IMAGE_END : + __bl_FLASH_NS_START + FLASH_BOOTLOADER_HEADER_LENGTH_2; +__bln_FLASH_IMAGE_START = __bl_FLASH_NS_IMAGE_START | (!DEFINED (NS_OFFSET_START) ? 0 : NS_OFFSET_START); +__bln_FLASH_IMAGE_LENGTH = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_NS_LENGTH == 0 ? __bl_FLASH_IMAGE_END : + FLASH_APPLICATION_NS_LENGTH - FLASH_BOOTLOADER_HEADER_LENGTH_2; + +XIP_SECONDARY_SLOT_IMAGE = DEFINED(XIP_SECONDARY_SLOT_IMAGE) ? XIP_SECONDARY_SLOT_IMAGE : 0; +FLASH_ORIGIN = !DEFINED(FLASH_IMAGE_START) ? FLASH_START : + XIP_SECONDARY_SLOT_IMAGE == 1 ? XIP_SECONDARY_FLASH_IMAGE_START : + FLASH_IMAGE_START; +LIMITED_FLASH_LENGTH = DEFINED(FLASH_IMAGE_LENGTH) ? FLASH_IMAGE_LENGTH : + DEFINED(FLASH_BOOTLOADER_LENGTH) ? FLASH_BOOTLOADER_LENGTH : + FLASH_LENGTH; +OPTION_SETTING_SAS_SIZE = 0x34; +OPTION_SETTING_SAS_LENGTH = !DEFINED(OPTION_SETTING_LENGTH) ? 0 : + OPTION_SETTING_LENGTH == 0 ? 0 : + OPTION_SETTING_LENGTH - OPTION_SETTING_SAS_SIZE; + +/* Define memory regions. */ +MEMORY +{ + ITCM (rx) : ORIGIN = ITCM_START, LENGTH = ITCM_LENGTH + DTCM (rwx) : ORIGIN = DTCM_START, LENGTH = DTCM_LENGTH + FLASH (rx) : ORIGIN = FLASH_ORIGIN, LENGTH = LIMITED_FLASH_LENGTH + RAM (rwx) : ORIGIN = RAM_START, LENGTH = RAM_LENGTH + DATA_FLASH (rx) : ORIGIN = DATA_FLASH_START, LENGTH = DATA_FLASH_LENGTH + QSPI_FLASH (rx) : ORIGIN = QSPI_FLASH_START, LENGTH = QSPI_FLASH_PRV_LENGTH + OSPI_DEVICE_0 (rx) : ORIGIN = OSPI_DEVICE_0_START, LENGTH = OSPI_DEVICE_0_PRV_LENGTH + OSPI_DEVICE_1 (rx) : ORIGIN = OSPI_DEVICE_1_START, LENGTH = OSPI_DEVICE_1_PRV_LENGTH + OSPI_DEVICE_0_RAM (rwx) : ORIGIN = OSPI_DEVICE_0_START, LENGTH = OSPI_DEVICE_0_PRV_LENGTH + OSPI_DEVICE_1_RAM (rwx) : ORIGIN = OSPI_DEVICE_1_START, LENGTH = OSPI_DEVICE_1_PRV_LENGTH + SDRAM (rwx) : ORIGIN = SDRAM_START, LENGTH = SDRAM_LENGTH + OPTION_SETTING (r) : ORIGIN = OPTION_SETTING_START, LENGTH = OPTION_SETTING_LENGTH + OPTION_SETTING_OFS (r) : ORIGIN = OPTION_SETTING_START, LENGTH = 0x18 + OPTION_SETTING_SAS (r) : ORIGIN = OPTION_SETTING_START + OPTION_SETTING_SAS_SIZE, LENGTH = OPTION_SETTING_SAS_LENGTH + OPTION_SETTING_S (r) : ORIGIN = OPTION_SETTING_S_START, LENGTH = OPTION_SETTING_S_LENGTH + ID_CODE (rx) : ORIGIN = ID_CODE_START, LENGTH = ID_CODE_LENGTH +} + +/* Library configurations */ +GROUP(libgcc.a libc.a libm.a) + +/* Linker script to place sections and symbol values. Should be used together + * with other linker script that defines memory regions FLASH and RAM. + * It references following symbols, which must be DEFINED in code: + * Reset_Handler : Entry of reset handler + * + * It defines following symbols, which code can use without definition: + * __exidx_start + * __exidx_end + * __copy_table_start__ + * __copy_table_end__ + * __zero_table_start__ + * __zero_table_end__ + * __etext + * __data_start__ + * __preinit_array_start + * __preinit_array_end + * __init_array_start + * __init_array_end + * __fini_array_start + * __fini_array_end + * __data_end__ + * __bss_start__ + * __bss_end__ + * __HeapLimit + * __StackLimit + * __StackTop + * __stack + * __Vectors_End + * __Vectors_Size + * __qspi_flash_start__ + * __qspi_flash_end__ + * __qspi_flash_code_size__ + * __qspi_region_max_size__ + * __qspi_region_start_address__ + * __qspi_region_end_address__ + * __ospi_device_0_start__ + * __ospi_device_0_end__ + * __ospi_device_0_code_size__ + * __ospi_device_0_region_max_size__ + * __ospi_device_0_region_start_address__ + * __ospi_device_0_region_end_address__ + * __ospi_device_1_start__ + * __ospi_device_1_end__ + * __ospi_device_1_code_size__ + * __ospi_device_1_region_max_size__ + * __ospi_device_1_region_start_address__ + * __ospi_device_1_region_end_address__ + */ +ENTRY(Reset_Handler) + +SECTIONS +{ + .text : + { + __tz_FLASH_S = ABSOLUTE(FLASH_START); + __ROM_Start = .; + + /* Even though the vector table is not 256 entries (1KB) long, we still allocate that much + * space because ROM registers are at address 0x400 and there is very little space + * in between. */ + KEEP(*(.fixed_vectors*)) + KEEP(*(.application_vectors*)) + __Vectors_End = .; + + /* Some devices have a gap of code flash between the vector table and ROM Registers. + * The flash gap section allows applications to place code and data in this section. */ + *(.flash_gap*) + + /* ROM Registers start at address 0x00000400 for devices that do not have the OPTION_SETTING region. */ + . = OPTION_SETTING_LENGTH > 0 ? . : __ROM_Start + 0x400; + KEEP(*(.rom_registers*)) + + /* Reserving 0x100 bytes of space for ROM registers. */ + . = OPTION_SETTING_LENGTH > 0 ? . : __ROM_Start + 0x500; + + /* Allocate flash write-boundary-aligned + * space for sce9 wrapped public keys for mcuboot if the module is used. + */ + KEEP(*(.mcuboot_sce9_key*)) + + *(.text*) + + KEEP(*(.version)) + KEEP(*(.init)) + KEEP(*(.fini)) + + /* .ctors */ + *crtbegin.o(.ctors) + *crtbegin?.o(.ctors) + *(EXCLUDE_FILE(*crtend?.o *crtend.o) .ctors) + *(SORT(.ctors.*)) + *(.ctors) + + /* .dtors */ + *crtbegin.o(.dtors) + *crtbegin?.o(.dtors) + *(EXCLUDE_FILE(*crtend?.o *crtend.o) .dtors) + *(SORT(.dtors.*)) + *(.dtors) + + *(.rodata*) + __usb_dev_descriptor_start_fs = .; + KEEP(*(.usb_device_desc_fs*)) + __usb_cfg_descriptor_start_fs = .; + KEEP(*(.usb_config_desc_fs*)) + __usb_interface_descriptor_start_fs = .; + KEEP(*(.usb_interface_desc_fs*)) + __usb_descriptor_end_fs = .; + __usb_dev_descriptor_start_hs = .; + KEEP(*(.usb_device_desc_hs*)) + __usb_cfg_descriptor_start_hs = .; + KEEP(*(.usb_config_desc_hs*)) + __usb_interface_descriptor_start_hs = .; + KEEP(*(.usb_interface_desc_hs*)) + __usb_descriptor_end_hs = .; + + KEEP(*(.eh_frame*)) + + __ROM_End = .; + } > FLASH = 0xFF + + __Vectors_Size = __Vectors_End - __Vectors; + + . = .; + __itcm_data_pre_location = .; + + /* Initialized ITCM data. */ + /* Aligned to FCACHE2 for RA8. */ + .itcm_data : ALIGN(16) + { + /* Start of ITCM Secure Trustzone region. */ + __tz_ITCM_S = ABSOLUTE(ITCM_START); + + /* All ITCM data start */ + __itcm_data_start = .; + + KEEP(*(.itcm_data*)) + + /* Pad to eight byte alignment in case of ECC initialization. Fill zero. */ + . = ALIGN(8); + + /* All ITCM data end */ + __itcm_data_end = .; + + /* + * Start of the ITCM Non-Secure Trustzone region. + * ITCM_NS_START can be used to set a fixed address for non-secure ITCM in secure projects or flat projects. + */ + __tz_ITCM_N = DEFINED(ITCM_NS_START) ? ABSOLUTE(ITCM_NS_START) : ALIGN(__itcm_data_end, 8192); + } > ITCM AT > FLASH = 0x00 + + /* Addresses exported for ITCM initialization. */ + __itcm_data_init_start = LOADADDR(.itcm_data); + __itcm_data_init_end = LOADADDR(.itcm_data) + SIZEOF(.itcm_data); + + ASSERT(ORIGIN(ITCM) % 8 == 0, "ITCM memory region origin must be aligned to 8 bytes.") + ASSERT(LENGTH(ITCM) % 8 == 0, "ITCM memory region length must be a multiple of 8 bytes.") + ASSERT(LOADADDR(.itcm_data) % 16 == 0, ".itcm_data section must be aligned to 16 bytes.") + ASSERT(SIZEOF(.itcm_data) % 8 == 0, ".itcm_data section size must be a multiple of 8 bytes.") + + /* Restore location counter. */ + /* If ITCM is not present, this will be the address stored in '.' before ALIGN was attempted. */ + /* If ITCM is present, this will be the absolute address that follows the ITCM ROM location. */ + . = (SIZEOF(.itcm_data) > 0) ? __itcm_data_init_end : __itcm_data_pre_location; + + __exidx_start = .; + /DISCARD/ : + { + *(.ARM.extab* .gnu.linkonce.armextab.*) + *(.ARM.exidx* .gnu.linkonce.armexidx.*) + } + __exidx_end = .; + + /* To copy multiple ROM to RAM sections, + * uncomment .copy.table section and, + * define __STARTUP_COPY_MULTIPLE in startup_ARMCMx.S */ + /* + .copy.table : + { + . = ALIGN(4); + __copy_table_start__ = .; + LONG (__etext) + LONG (__data_start__) + LONG (__data_end__ - __data_start__) + LONG (__etext2) + LONG (__data2_start__) + LONG (__data2_end__ - __data2_start__) + __copy_table_end__ = .; + } > FLASH + */ + + /* To clear multiple BSS sections, + * uncomment .zero.table section and, + * define __STARTUP_CLEAR_BSS_MULTIPLE in startup_ARMCMx.S */ + /* + .zero.table : + { + . = ALIGN(4); + __zero_table_start__ = .; + LONG (__bss_start__) + LONG (__bss_end__ - __bss_start__) + LONG (__bss2_start__) + LONG (__bss2_end__ - __bss2_start__) + __zero_table_end__ = .; + } > FLASH + */ + + __etext = .; + + __tz_RAM_S = ORIGIN(RAM); + + /* If DTC is used, put the DTC vector table at the start of SRAM. + This avoids memory holes due to 1K alignment required by it. */ + .fsp_dtc_vector_table (NOLOAD) : + { + . = ORIGIN(RAM); + *(.fsp_dtc_vector_table) + } > RAM + + /* Initialized data section. */ + .data : + { + __data_start__ = .; + . = ALIGN(4); + + __Code_In_RAM_Start = .; + + KEEP(*(.code_in_ram*)) + __Code_In_RAM_End = .; + + *(vtable) + /* Don't use *(.data*) because it will place data meant for .data_flash in this section. */ + *(.data.*) + *(.data) + + . = ALIGN(4); + /* preinit data */ + PROVIDE_HIDDEN (__preinit_array_start = .); + KEEP(*(.preinit_array)) + PROVIDE_HIDDEN (__preinit_array_end = .); + + . = ALIGN(4); + /* init data */ + PROVIDE_HIDDEN (__init_array_start = .); + KEEP(*(SORT(.init_array.*))) + KEEP(*(.init_array)) + PROVIDE_HIDDEN (__init_array_end = .); + + + . = ALIGN(4); + /* finit data */ + PROVIDE_HIDDEN (__fini_array_start = .); + KEEP(*(SORT(.fini_array.*))) + KEEP(*(.fini_array)) + PROVIDE_HIDDEN (__fini_array_end = .); + + KEEP(*(.jcr*)) + + . = ALIGN(4); + + /* All data end */ + __data_end__ = .; + + } > RAM AT > FLASH + + . = .; + __dtcm_data_pre_location = LOADADDR(.data) + SIZEOF(.data); + + /* Initialized DTCM data. */ + /* Aligned to FCACHE2 for RA8. */ + .dtcm_data : ALIGN(16) + { + /* Start of DTCM Secure Trustzone region. */ + __tz_DTCM_S = ABSOLUTE(DTCM_START); + + /* Initialized DTCM data start */ + __dtcm_data_start = .; + + KEEP(*(.dtcm_data*)) + + /* Pad to eight byte alignment in case of ECC initialization. Fill zero. */ + . = ALIGN(8); + + /* Initialized DTCM data end */ + __dtcm_data_end = .; + } > DTCM AT > FLASH = 0x00 + + . = __dtcm_data_end; + /* Uninitialized DTCM data. */ + /* ALIGN appears on the left side of the colon because it is being used to assign the VMA directly, as opposed to a right side appearance which would control the LMA. */ + .dtcm_bss ALIGN(8) (NOLOAD) : + { + /* Uninitialized DTCM data start */ + __dtcm_bss_start = .; + + KEEP(*(.dtcm_bss*)) + + /* Pad to eight byte alignment in case of ECC initialization. No fill because of NOLOAD. */ + . = ALIGN(8); + + /* Uninitialized DTCM data end */ + __dtcm_bss_end = .; + + /* + * Start of the DTCM Non-Secure Trustzone region. + * DTCM_NS_START can be used to set a fixed address for non-secure DTCM in secure projects or flat projects. + */ + __tz_DTCM_N = DEFINED(DTCM_NS_START) ? ABSOLUTE(DTCM_NS_START) : ALIGN(__dtcm_bss_end, 8192); + } > DTCM + + /* Addresses exported for DTCM initialization. */ + __dtcm_data_init_start = LOADADDR(.dtcm_data); + __dtcm_data_init_end = LOADADDR(.dtcm_data) + SIZEOF(.dtcm_data); + + ASSERT(ORIGIN(DTCM) % 8 == 0, "DTCM memory region origin must be aligned to 8 bytes.") + ASSERT(LENGTH(DTCM) % 8 == 0, "DTCM memory region length must be a multiple of 8 bytes.") + ASSERT(LOADADDR(.dtcm_bss) == ADDR(.dtcm_bss), ".dtcm_bss has (VMA != LMA) but should be NOLOAD (VMA == LMA).") + ASSERT(LOADADDR(.dtcm_data) % 16 == 0, ".dtcm_data section must be aligned to 16 bytes.") + ASSERT(SIZEOF(.dtcm_data) % 8 == 0, ".dtcm_data section size must be a multiple of 8 bytes.") + ASSERT(LOADADDR(.dtcm_bss) % 8 == 0, ".dtcm_bss section must be aligned to 8 bytes.") + ASSERT(SIZEOF(.dtcm_bss) % 8 == 0, ".dtcm_bss section size must be a multiple of 8 bytes.") + ASSERT(__dtcm_bss_start == __dtcm_data_end, ".dtcm_bss section is not adjacent to .dtcm_data section.") + + /* Restore location counter. */ + /* If DTCM is not present, this will be the address stored in '.' before ALIGN was attempted. */ + /* If DTCM is present, this will be the absolute address that follows the DTCM ROM location. */ + . = (SIZEOF(.dtcm_data) > 0) ? __dtcm_data_init_end : __dtcm_data_pre_location; + + /* TrustZone Secure Gateway Stubs Section */ + + /* Store location counter for SPI non-retentive sections. */ + sgstubs_pre_location = .; + + /* Determine the secure gateway stubs address either by the provided linker variable or the next 1024-byte block. */ + SGSTUBS_LOC = (DEFINED(PROJECT_SECURE) && DEFINED(FLASH_NSC_START)) ? ABSOLUTE(FLASH_NSC_START) : ALIGN(1024); + .gnu.sgstubs SGSTUBS_LOC : ALIGN(1024) + { + __tz_FLASH_C = DEFINED(FLASH_NSC_START) ? ABSOLUTE(FLASH_NSC_START) : __RESERVE_NS_RAM ? ABSOLUTE(FLASH_START + FLASH_LENGTH) : ALIGN(1024); + _start_sg = .; + *(.gnu.sgstubs*) + . = ALIGN(32); + _end_sg = .; + } > FLASH + + __tz_FLASH_N = DEFINED(FLASH_NS_START) ? ABSOLUTE(FLASH_NS_START) : __RESERVE_NS_RAM ? ABSOLUTE(FLASH_START + FLASH_LENGTH) : FLASH_LENGTH < 32768 ? FLASH_LENGTH : ALIGN(32768); + FLASH_NS_IMAGE_START = DEFINED(FLASH_NS_IMAGE_START) ? FLASH_NS_IMAGE_START : __tz_FLASH_N; + + /* Note: There are no secure/non-secure boundaries for QSPI. These symbols are provided for the RA configuration tool. */ + __tz_QSPI_FLASH_S = ORIGIN(QSPI_FLASH); + + /* QSPI_FLASH section to be downloaded via debugger */ + .qspi_flash : + { + __qspi_flash_start__ = .; + KEEP(*(.qspi_flash*)) + KEEP(*(.code_in_qspi*)) + __qspi_flash_end__ = .; + } > QSPI_FLASH + __qspi_flash_code_size__ = __qspi_flash_end__ - __qspi_flash_start__; + + /* QSPI_FLASH non-retentive section, creates a copy in internal flash that can be copied to QSPI */ + __qspi_flash_code_addr__ = sgstubs_pre_location; + .qspi_non_retentive : AT(__qspi_flash_code_addr__) + { + __qspi_non_retentive_start__ = .; + KEEP(*(.qspi_non_retentive*)) + __qspi_non_retentive_end__ = .; + } > QSPI_FLASH + __qspi_non_retentive_size__ = __qspi_non_retentive_end__ - __qspi_non_retentive_start__; + + __qspi_region_max_size__ = 0x4000000; /* Must be the same as defined in MEMORY above */ + __qspi_region_start_address__ = __qspi_flash_start__; + __qspi_region_end_address__ = __qspi_flash_start__ + __qspi_region_max_size__; + + /* Note: There are no secure/non-secure boundaries for QSPI. These symbols are provided for the RA configuration tool. */ + __tz_QSPI_FLASH_N = __qspi_non_retentive_end__; + + /* Support for OctaRAM */ + .OSPI_DEVICE_0_NO_LOAD (NOLOAD): + { + . = ALIGN(4); + __ospi_device_0_start__ = .; + *(.ospi_device_0_no_load*) + . = ALIGN(4); + __ospi_device_0_end__ = .; + } > OSPI_DEVICE_0_RAM + + .OSPI_DEVICE_1_NO_LOAD (NOLOAD): + { + . = ALIGN(4); + __ospi_device_1_start__ = .; + *(.ospi_device_1_no_load*) + . = ALIGN(4); + __ospi_device_1_end__ = .; + } > OSPI_DEVICE_1_RAM + + /* Note: There are no secure/non-secure boundaries for QSPI. These symbols are provided for the RA configuration tool. */ + __tz_OSPI_DEVICE_0_S = ORIGIN(OSPI_DEVICE_0); + + /* OSPI_DEVICE_0 section to be downloaded via debugger */ + .OSPI_DEVICE_0 : + { + __ospi_device_0_start__ = .; + KEEP(*(.ospi_device_0*)) + KEEP(*(.code_in_ospi_device_0*)) + __ospi_device_0_end__ = .; + } > OSPI_DEVICE_0 + __ospi_device_0_code_size__ = __ospi_device_0_end__ - __ospi_device_0_start__; + + /* OSPI_DEVICE_0 non-retentive section, creates a copy in internal flash that can be copied to OSPI */ + __ospi_device_0_code_addr__ = sgstubs_pre_location + (SIZEOF(.qspi_non_retentive)); + .ospi_device_0_non_retentive : AT(__ospi_device_0_code_addr__) + { + __ospi_device_0_non_retentive_start__ = .; + KEEP(*(.ospi_device_0_non_retentive*)) + __ospi_device_0_non_retentive_end__ = .; + } > OSPI_DEVICE_0 + __ospi_device_0_non_retentive_size__ = __ospi_device_0_non_retentive_end__ - __ospi_device_0_non_retentive_start__; + + __ospi_device_0_region_max_size__ = 0x8000000; /* Must be the same as defined in MEMORY above */ + __ospi_device_0_region_start_address__ = __ospi_device_0_start__; + __ospi_device_0_region_end_address__ = __ospi_device_0_start__ + __ospi_device_0_region_max_size__; + + /* Note: There are no secure/non-secure boundaries for OSPI. These symbols are provided for the RA configuration tool. */ + __tz_OSPI_DEVICE_0_N = __ospi_device_0_non_retentive_end__; + + /* Note: There are no secure/non-secure boundaries for OSPI. These symbols are provided for the RA configuration tool. */ + __tz_OSPI_DEVICE_1_S = ORIGIN(OSPI_DEVICE_1); + + /* OSPI_DEVICE_1 section to be downloaded via debugger */ + .OSPI_DEVICE_1 : + { + __ospi_device_1_start__ = .; + KEEP(*(.ospi_device_1*)) + KEEP(*(.code_in_ospi_device_1*)) + __ospi_device_1_end__ = .; + } > OSPI_DEVICE_1 + __ospi_device_1_code_size__ = __ospi_device_1_end__ - __ospi_device_1_start__; + + /* OSPI_DEVICE_1 non-retentive section, creates a copy in internal flash that can be copied to OSPI */ + __ospi_device_1_code_addr__ = sgstubs_pre_location + (SIZEOF(.qspi_non_retentive) + SIZEOF(.ospi_device_0_non_retentive)); + .ospi_device_1_non_retentive : AT(__ospi_device_1_code_addr__) + { + __ospi_device_1_non_retentive_start__ = .; + KEEP(*(.ospi_device_1_non_retentive*)) + __ospi_device_1_non_retentive_end__ = .; + } > OSPI_DEVICE_1 + __ospi_device_1_non_retentive_size__ = __ospi_device_1_non_retentive_end__ - __ospi_device_1_non_retentive_start__; + + __ospi_device_1_region_max_size__ = 0x10000000; /* Must be the same as defined in MEMORY above */ + __ospi_device_1_region_start_address__ = __ospi_device_1_start__; + __ospi_device_1_region_end_address__ = __ospi_device_1_start__ + __ospi_device_1_region_max_size__; + + /* Note: There are no secure/non-secure boundaries for OSPI. These symbols are provided for the RA configuration tool. */ + __tz_OSPI_DEVICE_1_N = __ospi_device_1_non_retentive_end__; + + .noinit (NOLOAD): + { + . = ALIGN(4); + __noinit_start = .; + KEEP(*(.noinit*)) + . = ALIGN(8); + /* Place the FreeRTOS heap here so that the __HeapLimit calculation does not include the freertos heap. */ + KEEP(*(.heap.*)) + __noinit_end = .; + } > RAM + + .bss : + { + . = ALIGN(4); + __bss_start__ = .; + *(.bss*) + *(COMMON) + . = ALIGN(4); + __bss_end__ = .; + } > RAM + + .heap (NOLOAD): + { + . = ALIGN(8); + __HeapBase = .; + /* Place the STD heap here. */ + KEEP(*(.heap)) + __HeapLimit = .; + } > RAM + + /* Stacks are stored in this section. */ + .stack_dummy (NOLOAD): + { + . = ALIGN(8); + __StackLimit = .; + /* Main stack */ + KEEP(*(.stack)) + __StackTop = .; + /* Thread stacks */ + KEEP(*(.stack*)) + __StackTopAll = .; + } > RAM + + PROVIDE(__stack = __StackTopAll); + + /* This symbol represents the end of user allocated RAM. The RAM after this symbol can be used + at run time for things such as ThreadX memory pool allocations. */ + __RAM_segment_used_end__ = ALIGN(__StackTopAll , 4); + + /* RAM_NSC_START can be used to set a fixed address for non-secure callable RAM in secure projects. + * If it is not specified, the address for NSC RAM is the end of RAM aligned to a 1K boundary. + * In flat projects that require non-secure RAM, this variable is set to the start of non-secure RAM. */ + __tz_RAM_C = DEFINED(RAM_NSC_START) ? ABSOLUTE(RAM_NSC_START - RAM_NS_BUFFER_BLOCK_LENGTH) : __RESERVE_NS_RAM ? ABSOLUTE(RAM_NS_BUFFER_BLOCK_START) : ALIGN(__RAM_segment_used_end__, 1024); + + /* RAM_NS_START can be used to set a fixed address for non-secure RAM in secure projects or flat projects. + * RAM_NS_BUFFER_BLOCK_LENGTH is used to allocate non-secure buffers in a flat project. If it is not + * specified, the address for NSC RAM is the end of RAM aligned to an 8K boundary. + * In flat projects that require non-secure RAM, this variable is set to the start of non-secure RAM. */ + __tz_RAM_N = DEFINED(RAM_NS_START) ? ABSOLUTE(RAM_NS_START - RAM_NS_BUFFER_BLOCK_LENGTH) : __RESERVE_NS_RAM ? ABSOLUTE(RAM_NS_BUFFER_BLOCK_START) : ALIGN(__tz_RAM_C, 8192); + + /* Non-secure buffers must be in non-secure RAM. This is primarily used for the EDMAC in flat projects. + * The EDMAC is a non-secure bus master and can only access non-secure RAM. */ + .ns_buffer (NOLOAD): + { + /* Allocate RAM on a 32-byte boundary to help with placement of Ethernet buffers. */ + . = __RESERVE_NS_RAM ? ABSOLUTE(RAM_NS_BUFFER_START & 0xFFFFFFE0) : .; + + KEEP(*(.ns_buffer*)) + } > RAM + + /* Data flash. */ + .data_flash : + { + . = ORIGIN(DATA_FLASH); + __tz_DATA_FLASH_S = .; + __Data_Flash_Start = .; + KEEP(*(.data_flash*)) + __Data_Flash_End = .; + + __tz_DATA_FLASH_N = DEFINED(DATA_FLASH_NS_START) ? ABSOLUTE(DATA_FLASH_NS_START) : __RESERVE_NS_RAM ? ABSOLUTE(DATA_FLASH_START + DATA_FLASH_LENGTH) : ALIGN(1024); + } > DATA_FLASH + + /* Note: There are no secure/non-secure boundaries for SDRAM. These symbols are provided for the RA configuration tool. */ + __tz_SDRAM_S = ORIGIN(SDRAM); + + /* SDRAM */ + .sdram (NOLOAD): + { + __SDRAM_Start = .; + KEEP(*(.sdram*)) + KEEP(*(.frame*)) + __SDRAM_End = .; + } > SDRAM + + /* Note: There are no secure/non-secure boundaries for SDRAM. These symbols are provided for the RA configuration tool. */ + __tz_SDRAM_N = __SDRAM_End; + + /* Note: There are no secure/non-secure boundaries for ID_CODE. These symbols are provided for the RA configuration tool. */ + __tz_ID_CODE_S = ORIGIN(ID_CODE); + + /* Note: There are no secure/non-secure boundaries for ID_CODE. These symbols are provided for the RA configuration tool. + * Set this symbol to the same value as __tz_ID_CODE_S so the RA configuration tool does not split the ID_CODE + * memory region between TrustZone projects. */ + __tz_ID_CODE_N = __tz_ID_CODE_S; + + .id_code : + { + __ID_Code_Start = .; + KEEP(*(.id_code*)) + __ID_Code_End = .; + } > ID_CODE + + /* Symbol required for RA Configuration tool. */ + __tz_OPTION_SETTING_S = ORIGIN(OPTION_SETTING_OFS); + + .option_setting_ofs : + { + __OPTION_SETTING_OFS_Start = .; + KEEP(*(.option_setting_ofs0)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_OFS_Start + 0x04 : __OPTION_SETTING_OFS_Start; + KEEP(*(.option_setting_ofs2)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_OFS_Start + 0x10 : __OPTION_SETTING_OFS_Start; + KEEP(*(.option_setting_dualsel)) + __OPTION_SETTING_OFS_End = .; + } > OPTION_SETTING_OFS = 0xFF + + .option_setting_sas : + { + __OPTION_SETTING_SAS_Start = .; + KEEP(*(.option_setting_sas)) + __OPTION_SETTING_SAS_End = .; + } > OPTION_SETTING_SAS = 0xFF + + /* Symbol required for RA Configuration tool. */ + __tz_OPTION_SETTING_N = ABSOLUTE(OPTION_SETTING_START_NS); + + .option_setting_ns : + { + __OPTION_SETTING_NS_Start = .; + KEEP(*(.option_setting_ofs1)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x04 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_ofs3)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x10 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_banksel)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x40 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_bps0)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x44 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_bps1)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x48 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_bps2)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x4C : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_bps3)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x60 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_pbps0)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x64 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_pbps1)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x68 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_pbps2)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x6C : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_pbps3)) + __OPTION_SETTING_NS_End = .; + } > OPTION_SETTING = 0xFF + + /* Symbol required for RA Configuration tool. */ + __tz_OPTION_SETTING_S_S = ORIGIN(OPTION_SETTING_S); + + .option_setting_s : + { + __OPTION_SETTING_S_Start = .; + KEEP(*(.option_setting_ofs1_sec)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x04 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_ofs3_sec)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x10 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_banksel_sec)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x40 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sec0)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x44 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sec1)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x48 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sec2)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x4C : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sec3)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x60 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_pbps_sec0)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x64 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_pbps_sec1)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x68 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_pbps_sec2)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x6C : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_pbps_sec3)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x80 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_ofs1_sel)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x84 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_ofs3_sel)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x90 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_banksel_sel)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0xC0 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sel0)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0xC4 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sel1)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0xC8 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sel2)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0xCC : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sel3)) + __OPTION_SETTING_S_End = .; + } > OPTION_SETTING_S = 0xFF + + /* Symbol required for RA Configuration tool. */ + __tz_OPTION_SETTING_S_N = __OPTION_SETTING_S_End; +} diff --git a/hw/bsp/ra/boards/ra6m5_ek/script/memory_regions.ld b/hw/bsp/ra/boards/ra6m5_ek/script/memory_regions.ld new file mode 100644 index 000000000..19864683f --- /dev/null +++ b/hw/bsp/ra/boards/ra6m5_ek/script/memory_regions.ld @@ -0,0 +1,22 @@ + + /* generated memory regions file - do not edit */ + RAM_START = 0x20000000; + RAM_LENGTH = 0x80000; + FLASH_START = 0x00000000; + FLASH_LENGTH = 0x200000; + DATA_FLASH_START = 0x08000000; + DATA_FLASH_LENGTH = 0x2000; + OPTION_SETTING_START = 0x0100A100; + OPTION_SETTING_LENGTH = 0x100; + OPTION_SETTING_S_START = 0x0100A200; + OPTION_SETTING_S_LENGTH = 0x100; + ID_CODE_START = 0x00000000; + ID_CODE_LENGTH = 0x0; + SDRAM_START = 0x80010000; + SDRAM_LENGTH = 0x0; + QSPI_FLASH_START = 0x60000000; + QSPI_FLASH_LENGTH = 0x4000000; + OSPI_DEVICE_0_START = 0x68000000; + OSPI_DEVICE_0_LENGTH = 0x8000000; + OSPI_DEVICE_1_START = 0x70000000; + OSPI_DEVICE_1_LENGTH = 0x10000000; diff --git a/hw/bsp/ra/boards/ra6m5_ek/smart_configurator/configuration.xml b/hw/bsp/ra/boards/ra6m5_ek/smart_configurator/configuration.xml new file mode 100644 index 000000000..4544d0f2a --- /dev/null +++ b/hw/bsp/ra/boards/ra6m5_ek/smart_configurator/configuration.xml @@ -0,0 +1,670 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Simple application that blinks an LED. No RTOS included. + Renesas.RA_baremetal_blinky.5.6.0.pack + + + Board Support Package Common Files + Renesas.RA.5.6.0.pack + + + I/O Port + Renesas.RA.5.6.0.pack + + + Arm CMSIS Version 6 - Core (M) + Arm.CMSIS6.6.1.0+fsp.5.6.0.pack + + + RA6M5-EK Board Support Files + Renesas.RA_board_ra6m5_ek.5.6.0.pack + + + Board support package for R7FA6M5BH3CFC + Renesas.RA_mcu_ra6m5.5.6.0.pack + + + Board support package for RA6M5 + Renesas.RA_mcu_ra6m5.5.6.0.pack + + + Board support package for RA6M5 - FSP Data + Renesas.RA_mcu_ra6m5.5.6.0.pack + + + Board support package for RA6M5 - Events + Renesas.RA_mcu_ra6m5.5.6.0.pack + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/hw/bsp/ra/boards/ra8m1_ek/board.cmake b/hw/bsp/ra/boards/ra8m1_ek/board.cmake new file mode 100644 index 000000000..c61166f38 --- /dev/null +++ b/hw/bsp/ra/boards/ra8m1_ek/board.cmake @@ -0,0 +1,16 @@ +set(CMAKE_SYSTEM_CPU cortex-m85 CACHE INTERNAL "System Processor") +set(MCU_VARIANT ra8m1) + +set(JLINK_DEVICE R7FA8M1AH) +#set(JLINK_OPTION "-USB 001083115236") + +# device default to PORT 1 High Speed +if (NOT DEFINED RHPORT_DEVICE) + set(RHPORT_DEVICE 1) +endif() +if (NOT DEFINED RHPORT_HOST) + set(RHPORT_HOST 0) +endif() + +function(update_board TARGET) +endfunction() diff --git a/hw/bsp/ra/boards/ra8m1_ek/board.h b/hw/bsp/ra/boards/ra8m1_ek/board.h new file mode 100644 index 000000000..54672452f --- /dev/null +++ b/hw/bsp/ra/boards/ra8m1_ek/board.h @@ -0,0 +1,47 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2023 Ha Thach (tinyusb.org) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * This file is part of the TinyUSB stack. + */ + +/* metadata: + name: RA8M1 EK + url: https://www.renesas.com/en/products/microcontrollers-microprocessors/ra-cortex-m-mcus/ek-ra8m1-evaluation-kit-ra8m1-mcu-group +*/ + +#ifndef _BOARD_H_ +#define _BOARD_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#define LED_STATE_ON 1 +#define BUTTON_STATE_ACTIVE 0 + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/hw/bsp/ra/boards/ra8m1_ek/board.mk b/hw/bsp/ra/boards/ra8m1_ek/board.mk new file mode 100644 index 000000000..2e56b3781 --- /dev/null +++ b/hw/bsp/ra/boards/ra8m1_ek/board.mk @@ -0,0 +1,11 @@ +CPU_CORE = cortex-m85 +MCU_VARIANT = ra8m1 + +# For flash-jlink target +JLINK_DEVICE = R7FA8M1AH + +# Port 1 is highspeed +RHPORT_DEVICE ?= 1 +RHPORT_HOST ?= 0 + +flash: flash-jlink diff --git a/hw/bsp/ra/boards/ra8m1_ek/ozone/Renesas_RA8_TracePins.pex b/hw/bsp/ra/boards/ra8m1_ek/ozone/Renesas_RA8_TracePins.pex new file mode 100644 index 000000000..70dd323ec Binary files /dev/null and b/hw/bsp/ra/boards/ra8m1_ek/ozone/Renesas_RA8_TracePins.pex differ diff --git a/hw/bsp/ra/boards/ra8m1_ek/ozone/ra8m1.jdebug b/hw/bsp/ra/boards/ra8m1_ek/ozone/ra8m1.jdebug new file mode 100644 index 000000000..242a15db9 --- /dev/null +++ b/hw/bsp/ra/boards/ra8m1_ek/ozone/ra8m1.jdebug @@ -0,0 +1,231 @@ + +/********************************************************************* +* +* OnProjectLoad +* +* Function description +* Project load routine. Required. +* +********************************************************************** +*/ +void OnProjectLoad (void) { + Project.SetTraceSource ("Trace Pins"); + Project.SetDevice ("R7FA8M1AH"); + Project.SetHostIF ("USB", ""); + Project.SetTargetIF ("SWD"); + Project.SetTIFSpeed ("50 MHz"); + + Project.AddSvdFile ("$(InstallDir)/Config/CPU/Cortex-M85F.svd"); + Project.AddSvdFile ("../../../../../../../cmsis-svd-data/data/Renesas/R7FA6M5BH.svd"); + + File.Open ("../../../../../../examples/cmake-build-ra8m1_ek/device/cdc_msc/cdc_msc.elf"); +} +/********************************************************************* +* +* BeforeTargetConnect +* +* Function description +* Event handler routine. Optional. +* +********************************************************************** +*/ +void BeforeTargetConnect (void) { + // Trace pin init is done by J-Link script file as J-Link script files are IDE independent + //Project.SetJLinkScript("../../../debug.jlinkscript"); + Project.SetJLinkScript ("$(ProjectDir)/Renesas_RA8_TracePins.pex"); +} + +/********************************************************************* +* +* AfterTargetConnect +* +* Function description +* Event handler routine. Optional. +* +********************************************************************** +*/ +//void AfterTargetConnect (void) { +//} + +/********************************************************************* +* +* TargetDownload +* +* Function description +* Replaces the default program download routine. Optional. +* +********************************************************************** +*/ +//void TargetDownload (void) { +//} + +/********************************************************************* +* +* BeforeTargetDownload +* +* Function description +* Event handler routine. Optional. +* +********************************************************************** +*/ +//void BeforeTargetDownload (void) { +//} + +/********************************************************************* +* +* AfterTargetDownload +* +* Function description +* Event handler routine. Optional. +* The default implementation initializes SP and PC to reset values. +* +********************************************************************** +*/ +void AfterTargetDownload (void) { + _SetupTarget(); +} + +/********************************************************************* +* +* BeforeTargetDisconnect +* +* Function description +* Event handler routine. Optional. +* +********************************************************************** +*/ +//void BeforeTargetDisconnect (void) { +//} + +/********************************************************************* +* +* AfterTargetDisconnect +* +* Function description +* Event handler routine. Optional. +* +********************************************************************** +*/ +//void AfterTargetDisconnect (void) { +//} + +/********************************************************************* +* +* AfterTargetHalt +* +* Function description +* Event handler routine. Optional. +* +********************************************************************** +*/ +//void AfterTargetHalt (void) { +//} + +/********************************************************************* +* +* BeforeTargetResume +* +* Function description +* Event handler routine. Optional. +* +********************************************************************** +*/ +//void BeforeTargetResume (void) { +//} + +/********************************************************************* +* +* OnSnapshotLoad +* +* Function description +* Called upon loading a snapshot. Optional. +* +* Additional information +* This function is used to restore the target state in cases +* where values cannot simply be written to the target. +* Typical use: GPIO clock needs to be enabled, before +* GPIO is configured. +* +********************************************************************** +*/ +//void OnSnapshotLoad (void) { +//} + +/********************************************************************* +* +* OnSnapshotSave +* +* Function description +* Called upon saving a snapshot. Optional. +* +* Additional information +* This function is usually used to save values of the target +* state which can either not be trivially read, +* or need to be restored in a specific way or order. +* Typically use: Memory Mapped Registers, +* such as PLL and GPIO configuration. +* +********************************************************************** +*/ +//void OnSnapshotSave (void) { +//} + +/********************************************************************* +* +* OnError +* +* Function description +* Called when an error occurred. Optional. +* +********************************************************************** +*/ +//void OnError (void) { +//} + +/********************************************************************* +* +* AfterProjectLoad +* +* Function description +* After Project load routine. Optional. +* +********************************************************************** +*/ +//void AfterProjectLoad (void) { +//} + +/********************************************************************* +* +* _SetupTarget +* +* Function description +* Setup the target. +* Called by AfterTargetReset() and AfterTargetDownload(). +* +* Auto-generated function. May be overridden by Ozone. +* +********************************************************************** +*/ +void _SetupTarget(void) { + unsigned int SP; + unsigned int PC; + unsigned int VectorTableAddr; + + VectorTableAddr = Elf.GetBaseAddr(); + // + // Set up initial stack pointer + // + SP = Target.ReadU32(VectorTableAddr); + if (SP != 0xFFFFFFFF) { + Target.SetReg("SP", SP); + } + // + // Set up entry point PC + // + PC = Elf.GetEntryPointPC(); + if (PC != 0xFFFFFFFF) { + Target.SetReg("PC", PC); + } else { + Util.Error("Project script error: failed to set up entry point PC", 1); + } +} diff --git a/hw/bsp/ra/boards/ra8m1_ek/ra_cfg/fsp_cfg/bsp/bsp_cfg.h b/hw/bsp/ra/boards/ra8m1_ek/ra_cfg/fsp_cfg/bsp/bsp_cfg.h new file mode 100644 index 000000000..90afbdef3 --- /dev/null +++ b/hw/bsp/ra/boards/ra8m1_ek/ra_cfg/fsp_cfg/bsp/bsp_cfg.h @@ -0,0 +1,62 @@ +/* generated configuration header file - do not edit */ +#ifndef BSP_CFG_H_ +#define BSP_CFG_H_ +#ifdef __cplusplus + extern "C" { + #endif + + #include "bsp_clock_cfg.h" + #include "bsp_mcu_family_cfg.h" + #include "board_cfg.h" + #define RA_NOT_DEFINED 0 + #ifndef BSP_CFG_RTOS + #if (RA_NOT_DEFINED) != (RA_NOT_DEFINED) + #define BSP_CFG_RTOS (2) + #elif (RA_NOT_DEFINED) != (RA_NOT_DEFINED) + #define BSP_CFG_RTOS (1) + #else + #define BSP_CFG_RTOS (0) + #endif + #endif + #ifndef BSP_CFG_RTC_USED + #define BSP_CFG_RTC_USED (RA_NOT_DEFINED) + #endif + #undef RA_NOT_DEFINED + #if defined(_RA_BOOT_IMAGE) + #define BSP_CFG_BOOT_IMAGE (1) + #endif + #define BSP_CFG_MCU_VCC_MV (3300) + #define BSP_CFG_STACK_MAIN_BYTES (0x1000) + #define BSP_CFG_HEAP_BYTES (0x1000) + #define BSP_CFG_PARAM_CHECKING_ENABLE (0) + #define BSP_CFG_ASSERT (0) + #define BSP_CFG_ERROR_LOG (0) + + #define BSP_CFG_PFS_PROTECT ((1)) + + #define BSP_CFG_C_RUNTIME_INIT ((1)) + #define BSP_CFG_EARLY_INIT ((0)) + + #define BSP_CFG_STARTUP_CLOCK_REG_NOT_RESET ((0)) + + #ifndef BSP_CLOCK_CFG_MAIN_OSC_POPULATED + #define BSP_CLOCK_CFG_MAIN_OSC_POPULATED (1) + #endif + + #ifndef BSP_CLOCK_CFG_MAIN_OSC_CLOCK_SOURCE + #define BSP_CLOCK_CFG_MAIN_OSC_CLOCK_SOURCE (0) + #endif + #ifndef BSP_CLOCK_CFG_SUBCLOCK_DRIVE + #define BSP_CLOCK_CFG_SUBCLOCK_DRIVE (0) + #endif + #ifndef BSP_CLOCK_CFG_SUBCLOCK_POPULATED + #define BSP_CLOCK_CFG_SUBCLOCK_POPULATED (1) + #endif + #ifndef BSP_CLOCK_CFG_SUBCLOCK_STABILIZATION_MS + #define BSP_CLOCK_CFG_SUBCLOCK_STABILIZATION_MS 1000 + #endif + + #ifdef __cplusplus + } + #endif +#endif /* BSP_CFG_H_ */ diff --git a/hw/bsp/ra/boards/ra8m1_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_device_cfg.h b/hw/bsp/ra/boards/ra8m1_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_device_cfg.h new file mode 100644 index 000000000..92e7ddcdb --- /dev/null +++ b/hw/bsp/ra/boards/ra8m1_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_device_cfg.h @@ -0,0 +1,5 @@ +/* generated configuration header file - do not edit */ +#ifndef BSP_MCU_DEVICE_CFG_H_ +#define BSP_MCU_DEVICE_CFG_H_ +#define BSP_CFG_MCU_PART_SERIES (8) +#endif /* BSP_MCU_DEVICE_CFG_H_ */ diff --git a/hw/bsp/ra/boards/ra8m1_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_device_pn_cfg.h b/hw/bsp/ra/boards/ra8m1_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_device_pn_cfg.h new file mode 100644 index 000000000..a22da075d --- /dev/null +++ b/hw/bsp/ra/boards/ra8m1_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_device_pn_cfg.h @@ -0,0 +1,11 @@ +/* generated configuration header file - do not edit */ +#ifndef BSP_MCU_DEVICE_PN_CFG_H_ +#define BSP_MCU_DEVICE_PN_CFG_H_ +#define BSP_MCU_R7FA8M1AHECBD + #define BSP_MCU_FEATURE_SET ('A') + #define BSP_ROM_SIZE_BYTES (2064384) + #define BSP_RAM_SIZE_BYTES (917504) + #define BSP_DATA_FLASH_SIZE_BYTES (12288) + #define BSP_PACKAGE_BGA + #define BSP_PACKAGE_PINS (224) +#endif /* BSP_MCU_DEVICE_PN_CFG_H_ */ diff --git a/hw/bsp/ra/boards/ra8m1_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_family_cfg.h b/hw/bsp/ra/boards/ra8m1_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_family_cfg.h new file mode 100644 index 000000000..94f09c61f --- /dev/null +++ b/hw/bsp/ra/boards/ra8m1_ek/ra_cfg/fsp_cfg/bsp/bsp_mcu_family_cfg.h @@ -0,0 +1,526 @@ +/* generated configuration header file - do not edit */ +#ifndef BSP_MCU_FAMILY_CFG_H_ +#define BSP_MCU_FAMILY_CFG_H_ +#include "bsp_mcu_device_pn_cfg.h" + #include "bsp_mcu_device_cfg.h" + #include "../../../ra/fsp/src/bsp/mcu/ra8m1/bsp_override.h" + #include "../../../ra/fsp/src/bsp/mcu/ra8m1/bsp_mcu_info.h" + #include "bsp_clock_cfg.h" + #define BSP_MCU_GROUP_RA8M1 (1) + #define BSP_LOCO_HZ (32768) + #define BSP_MOCO_HZ (8000000) + #define BSP_SUB_CLOCK_HZ (0) + #if BSP_CFG_HOCO_FREQUENCY == 0 + #define BSP_HOCO_HZ (16000000) + #elif BSP_CFG_HOCO_FREQUENCY == 1 + #define BSP_HOCO_HZ (18000000) + #elif BSP_CFG_HOCO_FREQUENCY == 2 + #define BSP_HOCO_HZ (20000000) + #elif BSP_CFG_HOCO_FREQUENCY == 4 + #define BSP_HOCO_HZ (32000000) + #elif BSP_CFG_HOCO_FREQUENCY == 7 + #define BSP_HOCO_HZ (48000000) + #else + #error "Invalid HOCO frequency chosen (BSP_CFG_HOCO_FREQUENCY) in bsp_clock_cfg.h" + #endif + + #define BSP_CFG_FLL_ENABLE (0) + + #define BSP_CFG_CLOCK_SETTLING_DELAY_ENABLE (1) + #define BSP_CFG_SLEEP_MODE_DELAY_ENABLE (1) + #define BSP_CFG_MSTP_CHANGE_DELAY_ENABLE (1) + #define BSP_CFG_RTOS_IDLE_SLEEP (0) + #define BSP_CFG_CLOCK_SETTLING_DELAY_US (150) + + #if defined(BSP_PACKAGE_LQFP) && (BSP_PACKAGE_PINS == 100) + #define BSP_MAX_CLOCK_CHANGE_THRESHOLD (180000000U) + #elif defined(BSP_PACKAGE_LQFP) + #define BSP_MAX_CLOCK_CHANGE_THRESHOLD (200000000U) + #else + #define BSP_MAX_CLOCK_CHANGE_THRESHOLD (240000000U) + #endif + + #define BSP_CORTEX_VECTOR_TABLE_ENTRIES (16U) + #define BSP_VECTOR_TABLE_MAX_ENTRIES (112U) + #define BSP_CFG_INLINE_IRQ_FUNCTIONS (1) + + #if defined(_RA_TZ_SECURE) + #define BSP_TZ_SECURE_BUILD (1) + #define BSP_TZ_NONSECURE_BUILD (0) + #elif defined(_RA_TZ_NONSECURE) + #define BSP_TZ_SECURE_BUILD (0) + #define BSP_TZ_NONSECURE_BUILD (1) + #else + #define BSP_TZ_SECURE_BUILD (0) + #define BSP_TZ_NONSECURE_BUILD (0) + #endif + + /* TrustZone Settings */ + #define BSP_TZ_CFG_INIT_SECURE_ONLY (BSP_CFG_CLOCKS_SECURE || (!BSP_CFG_CLOCKS_OVERRIDE)) + #define BSP_TZ_CFG_SKIP_INIT (BSP_TZ_NONSECURE_BUILD && BSP_TZ_CFG_INIT_SECURE_ONLY) + #define BSP_TZ_CFG_EXCEPTION_RESPONSE (0) + + /* CMSIS TrustZone Settings */ + #define SCB_CSR_AIRCR_INIT (1) + #define SCB_AIRCR_BFHFNMINS_VAL (0) + #define SCB_AIRCR_SYSRESETREQS_VAL (1) + #define SCB_AIRCR_PRIS_VAL (0) + #define TZ_FPU_NS_USAGE (1) +#ifndef SCB_NSACR_CP10_11_VAL + #define SCB_NSACR_CP10_11_VAL (3U) +#endif + +#ifndef FPU_FPCCR_TS_VAL + #define FPU_FPCCR_TS_VAL (1U) +#endif + #define FPU_FPCCR_CLRONRETS_VAL (1) + +#ifndef FPU_FPCCR_CLRONRET_VAL + #define FPU_FPCCR_CLRONRET_VAL (1) +#endif + + /* Type 1 Peripheral Security Attribution */ + + /* Peripheral Security Attribution Register (PSAR) Settings */ +#ifndef BSP_TZ_CFG_PSARB +#define BSP_TZ_CFG_PSARB (\ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 4) /* I3C */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 8) /* IIC1 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 9) /* IIC0 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 11) /* USBFS */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 12) /* USBHS */ | \ + (1 << 15) /* ETHERC/EDMAC */ | \ + (1 << 16) /* OSPI */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 18) /* SPI1 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 19) /* SPI0 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 22) /* SCI9 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 27) /* SCI4 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 28) /* SCI3 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 29) /* SCI2 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 30) /* SCI1 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 31) /* SCI0 */) +#endif +#ifndef BSP_TZ_CFG_PSARC +#define BSP_TZ_CFG_PSARC (\ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 0) /* CAC */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 1) /* CRC */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 7) /* SSIE1 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 8) /* SSIE0 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 11) /* SDHI1 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 12) /* SDHI0 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 13) /* DOC */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 16) /* CEU */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 26) /* CANFD1 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 27) /* CANFD0 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 31) /* RSIP-E51A */) +#endif +#ifndef BSP_TZ_CFG_PSARD +#define BSP_TZ_CFG_PSARD (\ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 4) /* AGT1 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 5) /* AGT0 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 11) /* POEG3 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 12) /* POEG2 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 13) /* POEG1 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 14) /* POEG0 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 15) /* ADC121 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 16) /* ADC120 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 20) /* DAC120 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 22) /* TSN */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 27) /* ACMPHS1 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 28) /* ACMPHS0 */) +#endif +#ifndef BSP_TZ_CFG_PSARE +#define BSP_TZ_CFG_PSARE (\ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 1) /* WDT */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 2) /* IWDT */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 3) /* RTC */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 8) /* ULPT1 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 9) /* ULPT0 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 18) /* GPT13 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 19) /* GPT12 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 20) /* GPT11 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 21) /* GPT10 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 22) /* GPT9 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 23) /* GPT8 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 24) /* GPT7 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 25) /* GPT6 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 26) /* GPT5 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 27) /* GPT4 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 28) /* GPT3 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 29) /* GPT2 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 30) /* GPT1 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 31) /* GPT0 */) +#endif +#ifndef BSP_TZ_CFG_MSSAR +#define BSP_TZ_CFG_MSSAR (\ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 22) /* DTC_DMAC */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 31) /* ELC */) +#endif + + /* Type 2 Peripheral Security Attribution */ + + /* Security attribution for RSTSRn registers. */ +#ifndef BSP_TZ_CFG_RSTSAR +#define BSP_TZ_CFG_RSTSAR (0x00000007U) +#endif + + /* Security attribution for registers of LVD channels. */ +#ifndef BSP_TZ_CFG_LVDSAR + /* The LVD driver needs to access both channels. This means that the security attribution for both channels must be the same. */ +#if (RA_NOT_DEFINED > 0) || (RA_NOT_DEFINED > 0) +#define BSP_TZ_CFG_LVDSAR (0U) +#else +#define BSP_TZ_CFG_LVDSAR (3U) +#endif +#endif + + /* Security attribution for LPM registers. + * - OPCCR based on clock security. + * - Set remaining registers based on LPM security. + */ +#ifndef BSP_TZ_CFG_LPMSAR +#define BSP_TZ_CFG_LPMSAR ((RA_NOT_DEFINED > 0) ? BSP_CFG_CLOCKS_SECURE == 0 : (\ + 0x002E0106U | \ + (BSP_CFG_CLOCKS_SECURE == 0))) +#endif + /* Deep Standby Interrupt Factor Security Attribution Register. */ +#ifndef BSP_TZ_CFG_DPFSAR +#define BSP_TZ_CFG_DPFSAR ((RA_NOT_DEFINED > 0) ? 0U : 0xAF1FFFFFU) +#endif + /* RAM Standby Control Security Attribution Register. */ +#ifndef BSP_TZ_CFG_RSCSAR +#define BSP_TZ_CFG_RSCSAR ((RA_NOT_DEFINED > 0) ? 0U : 0x00037FFFU) +#endif + + /* Security attribution for CGC registers. */ +#ifndef BSP_TZ_CFG_CGFSAR +#if BSP_CFG_CLOCKS_SECURE +/* Protect all CGC registers from Non-secure write access. */ +#define BSP_TZ_CFG_CGFSAR (0U) +#else +/* Allow Secure and Non-secure write access. */ +#define BSP_TZ_CFG_CGFSAR (0x047F3BFDU) +#endif +#endif + + /* Security attribution for Battery Backup registers. */ +#ifndef BSP_TZ_CFG_BBFSAR +#if 0 +#define BSP_TZ_CFG_BBFSAR (0U) +#else +#define BSP_TZ_CFG_BBFSAR (0x1FU) +#endif +#endif + + /* Security attribution for Battery Backup registers (VBTBKRn). */ +#ifndef BSP_TZ_CFG_VBRSABAR +#if 0 +#define BSP_TZ_CFG_VBRSABAR (0xFFE0) +#else +#define BSP_TZ_CFG_VBRSABAR (0xED00) +#endif +#endif + + /* Security attribution for registers for IRQ channels. */ +#ifndef BSP_TZ_CFG_ICUSARA +#define BSP_TZ_CFG_ICUSARA (\ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 0U) /* External IRQ0 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 1U) /* External IRQ1 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 2U) /* External IRQ2 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 3U) /* External IRQ3 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 4U) /* External IRQ4 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 5U) /* External IRQ5 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 6U) /* External IRQ6 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 7U) /* External IRQ7 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 8U) /* External IRQ8 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 9U) /* External IRQ9 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 10U) /* External IRQ10 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 11U) /* External IRQ11 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 12U) /* External IRQ12 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 13U) /* External IRQ13 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 14U) /* External IRQ14 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 15U) /* External IRQ15 */) +#endif + + /* Security attribution for NMI registers. */ +#ifndef BSP_TZ_CFG_ICUSARB +#define BSP_TZ_CFG_ICUSARB (0 | 0U) /* Should match AIRCR.BFHFNMINS. */ +#endif + + /* Security attribution for registers for DMAC channels */ +#ifndef BSP_TZ_CFG_DMACCHSAR +#define BSP_TZ_CFG_DMACCHSAR (\ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 0U) /* DMAC Channel 0 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 1U) /* DMAC Channel 1 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 2U) /* DMAC Channel 2 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 3U) /* DMAC Channel 3 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 4U) /* DMAC Channel 4 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 5U) /* DMAC Channel 5 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 6U) /* DMAC Channel 6 */ | \ + (((RA_NOT_DEFINED > 0) ? 0U : 1U) << 7U) /* DMAC Channel 7 */) +#endif + + /* Security attribution registers for WUPEN0. */ +#ifndef BSP_TZ_CFG_ICUSARE +#define BSP_TZ_CFG_ICUSARE ((RA_NOT_DEFINED > 0) ? 0U : 0xFF1D0000U) +#endif + + /* Security attribution registers for WUPEN1. */ +#ifndef BSP_TZ_CFG_ICUSARF +#define BSP_TZ_CFG_ICUSARF ((RA_NOT_DEFINED > 0) ? 0U : 0x00007F08U) +#endif + + /* Trusted Event Route Control Register for IELSR, DMAC.DELSR and ELC.ELSR. Note that currently Trusted Event Route Control is not supported. */ +#ifndef BSP_TZ_CFG_TEVTRCR +#define BSP_TZ_CFG_TEVTRCR (0) +#endif + + /* Security attribution register for ELCR, ELSEGR0, ELSEGR1 Security Attribution. */ +#ifndef BSP_TZ_CFG_ELCSARA + #define BSP_TZ_CFG_ELCSARA (0x00000007U) +#endif + + /* Set DTCSTSAR if the Secure program uses the DTC. */ +#if RA_NOT_DEFINED == RA_NOT_DEFINED + #define BSP_TZ_CFG_DTC_USED (0U) +#else + #define BSP_TZ_CFG_DTC_USED (1U) +#endif + + /* Security attribution of FLWT and FCKMHZ registers. */ +#ifndef BSP_TZ_CFG_FSAR +/* If the CGC registers are only accessible in Secure mode, than there is no + * reason for nonsecure applications to access FLWT and FCKMHZ. */ +#define BSP_TZ_CFG_FSAR (\ + ((BSP_CFG_CLOCKS_SECURE == 0) ? (1U << 0) : 0U) | /* FLWTSA */\ + ((RA_NOT_DEFINED) > 0 ? 0U: (1U << 1)) | /* FCACHESA */\ + ((BSP_CFG_CLOCKS_SECURE == 0) ? (1U << 8) : 0U) | /* FCKMHZSA */ \ + ((RA_NOT_DEFINED) > 0 ? 0U : (1U << 9U)) | /* FACICMISA */\ + ((RA_NOT_DEFINED) > 0 ? 0U: (1U << 10U)) /* FACICMRSA */) +#endif + + /* Security attribution for SRAM registers. */ +#ifndef BSP_TZ_CFG_SRAMSAR +/* If the CGC registers are only accessible in Secure mode, than there is no reason for Non Secure applications to access + * SRAM0WTEN and therefore there is no reason to access PRCR2. */ + #define BSP_TZ_CFG_SRAMSAR (\ + ((1U) << 0U) | /* SRAMSA0 */\ + ((1U) << 1U) | /* SRAMSA1 */\ + ((1U) << 7U) | /* STBRAMSA */\ + ((BSP_CFG_CLOCKS_SECURE == 0) ? (1U << 8U) : 0U) /* SRAMWTSA */) +#endif + + /* Security attribution for the DMAC Bus Master MPU settings. */ +#ifndef BSP_TZ_CFG_MMPUSARA + /* The DMAC Bus Master MPU settings should align with the DMAC channel settings. */ + #define BSP_TZ_CFG_MMPUSARA (BSP_TZ_CFG_DMACCHSAR) +#endif + + /* Security Attribution Register A for BUS Control registers. */ +#ifndef BSP_TZ_CFG_BUSSARA + #define BSP_TZ_CFG_BUSSARA (1U) +#endif + /* Security Attribution Register B for BUS Control registers. */ +#ifndef BSP_TZ_CFG_BUSSARB + #define BSP_TZ_CFG_BUSSARB (1U) +#endif + /* Security Attribution Register C for BUS Control registers. */ +#ifndef BSP_TZ_CFG_BUSSARC + #define BSP_TZ_CFG_BUSSARC (1U) +#endif + + /* Enable Uninitialized Non-Secure Application Fallback. */ +#ifndef BSP_TZ_CFG_NON_SECURE_APPLICATION_FALLBACK + #define BSP_TZ_CFG_NON_SECURE_APPLICATION_FALLBACK (1U) +#endif + + + #define OFS_SEQ1 0xA001A001 | (1 << 1) | (3 << 2) + #define OFS_SEQ2 (15 << 4) | (3 << 8) | (3 << 10) + #define OFS_SEQ3 (1 << 12) | (1 << 14) | (1 << 17) + #define OFS_SEQ4 (3 << 18) |(15 << 20) | (3 << 24) | (3 << 26) + #define OFS_SEQ5 (1 << 28) | (1 << 30) + #define BSP_CFG_ROM_REG_OFS0 (OFS_SEQ1 | OFS_SEQ2 | OFS_SEQ3 | OFS_SEQ4 | OFS_SEQ5) + + #define BSP_CFG_ROM_REG_OFS2 ((1 << 0) | 0xFFFFFFFEU) + + /* Option Function Select Register 1 Security Attribution */ +#ifndef BSP_CFG_ROM_REG_OFS1_SEL +#if defined(_RA_TZ_SECURE) || defined(_RA_TZ_NONSECURE) + #define BSP_CFG_ROM_REG_OFS1_SEL (0x00000000U | ((0U << 0U)) | ((0U << 3U)) | ((0U << 5U)) | ((BSP_CFG_CLOCKS_SECURE == 0) ? 0xF00U : 0U) | ((0U << 24U)) | ((0U << 25U))) +#else + #define BSP_CFG_ROM_REG_OFS1_SEL (0x00000000U) +#endif +#endif + #define BSP_CFG_ROM_REG_OFS1_INITECCEN (0 << 25) + #define BSP_CFG_ROM_REG_OFS1 (0xFCFFFED0 | (1 << 3) | (7) | (1 << 5) | (1 << 8) | (1 << 24) | (BSP_CFG_ROM_REG_OFS1_INITECCEN)) + + /* Used to create IELS values for the interrupt initialization table g_interrupt_event_link_select. */ + #define BSP_PRV_IELS_ENUM(vector) (ELC_ ## vector) + + /* Dual Mode Select Register */ +#ifndef BSP_CFG_ROM_REG_DUALSEL + #define BSP_CFG_ROM_REG_DUALSEL (0xFFFFFFF8U | (0x7U)) +#endif + + /* Block Protection Register 0 */ +#ifndef BSP_CFG_ROM_REG_BPS0 + #define BSP_CFG_ROM_REG_BPS0 (~( 0U)) +#endif + /* Block Protection Register 1 */ +#ifndef BSP_CFG_ROM_REG_BPS1 + #define BSP_CFG_ROM_REG_BPS1 (~( 0U)) +#endif + /* Block Protection Register 2 */ +#ifndef BSP_CFG_ROM_REG_BPS2 + #define BSP_CFG_ROM_REG_BPS2 (~( 0U)) +#endif + /* Block Protection Register 3 */ +#ifndef BSP_CFG_ROM_REG_BPS3 + #define BSP_CFG_ROM_REG_BPS3 (~( 0U)) +#endif + /* Permanent Block Protection Register 0 */ +#ifndef BSP_CFG_ROM_REG_PBPS0 + #define BSP_CFG_ROM_REG_PBPS0 (~( 0U)) +#endif + /* Permanent Block Protection Register 1 */ +#ifndef BSP_CFG_ROM_REG_PBPS1 + #define BSP_CFG_ROM_REG_PBPS1 (~( 0U)) +#endif + /* Permanent Block Protection Register 2 */ +#ifndef BSP_CFG_ROM_REG_PBPS2 + #define BSP_CFG_ROM_REG_PBPS2 (~( 0U)) +#endif + /* Permanent Block Protection Register 3 */ +#ifndef BSP_CFG_ROM_REG_PBPS3 + #define BSP_CFG_ROM_REG_PBPS3 (~( 0U)) +#endif + /* Security Attribution for Block Protection Register 0 (If any blocks are marked as protected in the secure application, then mark them as secure) */ +#ifndef BSP_CFG_ROM_REG_BPS_SEL0 + #define BSP_CFG_ROM_REG_BPS_SEL0 (BSP_CFG_ROM_REG_BPS0 & BSP_CFG_ROM_REG_PBPS0) +#endif + /* Security Attribution for Block Protection Register 1 (If any blocks are marked as protected in the secure application, then mark them as secure) */ +#ifndef BSP_CFG_ROM_REG_BPS_SEL1 + #define BSP_CFG_ROM_REG_BPS_SEL1 (BSP_CFG_ROM_REG_BPS1 & BSP_CFG_ROM_REG_PBPS1) +#endif + /* Security Attribution for Block Protection Register 2 (If any blocks are marked as protected in the secure application, then mark them as secure) */ +#ifndef BSP_CFG_ROM_REG_BPS_SEL2 + #define BSP_CFG_ROM_REG_BPS_SEL2 (BSP_CFG_ROM_REG_BPS2 & BSP_CFG_ROM_REG_PBPS2) +#endif + /* Security Attribution for Block Protection Register 3 (If any blocks are marked as protected in the secure application, then mark them as secure) */ +#ifndef BSP_CFG_ROM_REG_BPS_SEL3 + #define BSP_CFG_ROM_REG_BPS_SEL3 (BSP_CFG_ROM_REG_BPS3 & BSP_CFG_ROM_REG_PBPS3) +#endif + /* Security Attribution for Bank Select Register */ +#ifndef BSP_CFG_ROM_REG_BANKSEL_SEL + #define BSP_CFG_ROM_REG_BANKSEL_SEL (0xFFFFFFFFU) +#endif +#ifndef BSP_CLOCK_CFG_MAIN_OSC_WAIT + #define BSP_CLOCK_CFG_MAIN_OSC_WAIT (9) +#endif + + /* FSBL Control Register 0 */ +#ifndef BSP_CFG_ROM_REG_FSBLCTRL0 +#define BSP_CFG_ROM_REG_FSBLCTRL0 ( \ + (7 << R_OFS_DATAFLASH_FSBLCTRL0_FSBLEN_Pos) | \ + (7 << R_OFS_DATAFLASH_FSBLCTRL0_FSBLSKIPSW_Pos) | \ + (7 << R_OFS_DATAFLASH_FSBLCTRL0_FSBLSKIPDS_Pos) | \ + (7 << R_OFS_DATAFLASH_FSBLCTRL0_FSBLCLK_Pos) | \ + 0xFFFFF000) +#endif + + /* FSBL Control Register 1 */ +#ifndef BSP_CFG_ROM_REG_FSBLCTRL1 +#define BSP_CFG_ROM_REG_FSBLCTRL1 ( \ + (3 << R_OFS_DATAFLASH_FSBLCTRL1_FSBLEXMD_Pos) | \ + 0xFFFFFFFC) +#endif + + /* FSBL Control Register 2 */ +#ifndef BSP_CFG_ROM_REG_FSBLCTRL2 +#define BSP_CFG_ROM_REG_FSBLCTRL2 ( \ + (15 << R_OFS_DATAFLASH_FSBLCTRL2_PORTPN_Pos) | \ + (0x1F << R_OFS_DATAFLASH_FSBLCTRL2_PORTGN_Pos) | \ + 0xFFFFFE00) +#endif + + /* Start Address of Code Certificate Register 0 */ +#ifndef BSP_CFG_ROM_REG_SACC0 +#define BSP_CFG_ROM_REG_SACC0 (0xFFFFFFFF) +#endif + + /* Start Address of Code Certificate Register 1 */ +#ifndef BSP_CFG_ROM_REG_SACC1 +#define BSP_CFG_ROM_REG_SACC1 (0xFFFFFFFF) +#endif + + /* Start Address of Measurement Report Register */ +#ifndef BSP_CFG_ROM_REG_SAMR +#define BSP_CFG_ROM_REG_SAMR (0xFFFFFFFF) +#endif + +#ifndef BSP_CFG_DCACHE_ENABLED +#define BSP_CFG_DCACHE_ENABLED (0) +#endif + + +#ifndef BSP_CFG_SDRAM_ENABLED + #define BSP_CFG_SDRAM_ENABLED (0) +#endif + +#ifndef BSP_CFG_SDRAM_TRAS + #define BSP_CFG_SDRAM_TRAS (6) +#endif + +#ifndef BSP_CFG_SDRAM_TRCD + #define BSP_CFG_SDRAM_TRCD (3) +#endif + +#ifndef BSP_CFG_SDRAM_TRP + #define BSP_CFG_SDRAM_TRP (3) +#endif + +#ifndef BSP_CFG_SDRAM_TWR + #define BSP_CFG_SDRAM_TWR (2) +#endif + +#ifndef BSP_CFG_SDRAM_TCL + #define BSP_CFG_SDRAM_TCL (3) +#endif + +#ifndef BSP_CFG_SDRAM_TRFC + #define BSP_CFG_SDRAM_TRFC (937) +#endif + +#ifndef BSP_CFG_SDRAM_TREFW + #define BSP_CFG_SDRAM_TREFW (8) +#endif + +#ifndef BSP_CFG_SDRAM_INIT_ARFI + #define BSP_CFG_SDRAM_INIT_ARFI (10) +#endif + +#ifndef BSP_CFG_SDRAM_INIT_ARFC + #define BSP_CFG_SDRAM_INIT_ARFC (8) +#endif + +#ifndef BSP_CFG_SDRAM_INIT_PRC + #define BSP_CFG_SDRAM_INIT_PRC (3) +#endif + +#ifndef BSP_CFG_SDRAM_MULTIPLEX_ADDR_SHIFT + #define BSP_CFG_SDRAM_MULTIPLEX_ADDR_SHIFT (1) +#endif + +#ifndef BSP_CFG_SDRAM_ENDIAN_MODE + #define BSP_CFG_SDRAM_ENDIAN_MODE (0) +#endif + +#ifndef BSP_CFG_SDRAM_ACCESS_MODE + #define BSP_CFG_SDRAM_ACCESS_MODE (1) +#endif + +#ifndef BSP_CFG_SDRAM_BUS_WIDTH + #define BSP_CFG_SDRAM_BUS_WIDTH (0) +#endif +#endif /* BSP_MCU_FAMILY_CFG_H_ */ diff --git a/hw/bsp/ra/boards/ra8m1_ek/ra_cfg/fsp_cfg/bsp/bsp_pin_cfg.h b/hw/bsp/ra/boards/ra8m1_ek/ra_cfg/fsp_cfg/bsp/bsp_pin_cfg.h new file mode 100644 index 000000000..883363437 --- /dev/null +++ b/hw/bsp/ra/boards/ra8m1_ek/ra_cfg/fsp_cfg/bsp/bsp_pin_cfg.h @@ -0,0 +1,127 @@ +/* generated configuration header file - do not edit */ +#ifndef BSP_PIN_CFG_H_ +#define BSP_PIN_CFG_H_ +#include "r_ioport.h" + +/* Common macro for FSP header files. There is also a corresponding FSP_FOOTER macro at the end of this file. */ +FSP_HEADER + +#define ENET_RMII_INT (BSP_IO_PORT_00_PIN_00) +#define ARDUINO_A3 (BSP_IO_PORT_00_PIN_01) +#define GROVE2_AN102 (BSP_IO_PORT_00_PIN_02) +#define ARDUINO_A1 (BSP_IO_PORT_00_PIN_03) +#define ARDUINO_A0_MIKROBUS_AN000 (BSP_IO_PORT_00_PIN_04) +#define GROVE2_AN001 (BSP_IO_PORT_00_PIN_05) +#define PMOD1_IRQ11 (BSP_IO_PORT_00_PIN_06) +#define ARDUINO_A004 (BSP_IO_PORT_00_PIN_07) +#define USER_S2 (BSP_IO_PORT_00_PIN_08) +#define SW1 (BSP_IO_PORT_00_PIN_09) +#define MIKROBUS_IRQ14 (BSP_IO_PORT_00_PIN_10) +#define ARDUINO_A4 (BSP_IO_PORT_00_PIN_14) +#define ARDUINO_A5 (BSP_IO_PORT_00_PIN_15) +#define OSPI_DQ0 (BSP_IO_PORT_01_PIN_00) +#define OSPI_DQ3 (BSP_IO_PORT_01_PIN_01) +#define OSPI_DQ4 (BSP_IO_PORT_01_PIN_02) +#define OSPI_DQ2 (BSP_IO_PORT_01_PIN_03) +#define OSPI_CS (BSP_IO_PORT_01_PIN_04) +#define OSPI_INT (BSP_IO_PORT_01_PIN_05) +#define OSPI_RESET (BSP_IO_PORT_01_PIN_06) +#define LED3 (BSP_IO_PORT_01_PIN_07) +#define ETH_A_RMII_RMII_RXDV (BSP_IO_PORT_01_PIN_12) +#define ETH_A_LINKSTA (BSP_IO_PORT_01_PIN_14) +#define MPLX_CTRL (BSP_IO_PORT_01_PIN_15) +#define NMI (BSP_IO_PORT_02_PIN_00) +#define MD (BSP_IO_PORT_02_PIN_01) +#define CAN_STB (BSP_IO_PORT_02_PIN_07) +#define TDI (BSP_IO_PORT_02_PIN_08) +#define TDO (BSP_IO_PORT_02_PIN_09) +#define SWDIO (BSP_IO_PORT_02_PIN_10) +#define SWCLK (BSP_IO_PORT_02_PIN_11) +#define EXTAL (BSP_IO_PORT_02_PIN_12) +#define XTAL (BSP_IO_PORT_02_PIN_13) +#define ETH_A_RXER (BSP_IO_PORT_03_PIN_00) +#define ETH_A_RXD1 (BSP_IO_PORT_03_PIN_01) +#define ETH_A_RXD0 (BSP_IO_PORT_03_PIN_02) +#define ETH_A_REFCLK (BSP_IO_PORT_03_PIN_03) +#define ETH_A_TXD0 (BSP_IO_PORT_03_PIN_04) +#define ETH_A_TXD1 (BSP_IO_PORT_03_PIN_05) +#define ETH_A_TXEN (BSP_IO_PORT_03_PIN_06) +#define ETH_A_MDIO (BSP_IO_PORT_03_PIN_07) +#define ETH_A_MDC (BSP_IO_PORT_03_PIN_08) +#define ARDUINO_D0_MIKROBUS_RXD3 (BSP_IO_PORT_03_PIN_09) +#define ARDUINO_D1_MIKROBUS_TXD3 (BSP_IO_PORT_03_PIN_10) +#define CAN_RXD (BSP_IO_PORT_03_PIN_11) +#define CAN_TXD (BSP_IO_PORT_03_PIN_12) +#define I3C_SCL0_ARDUINO_MIKROBUS_PMOD1_3_qwiic (BSP_IO_PORT_04_PIN_00) +#define I3C_SDA0_ARDUINO_MIKROBUS_PMOD1_4_qwiic (BSP_IO_PORT_04_PIN_01) +#define ETH_B_MDIO (BSP_IO_PORT_04_PIN_02) +#define ETH_B_LINKSTA (BSP_IO_PORT_04_PIN_03) +#define ETH_B_RST_N (BSP_IO_PORT_04_PIN_04) +#define ETH_B_TXEN (BSP_IO_PORT_04_PIN_05) +#define ETH_B_TXD1 (BSP_IO_PORT_04_PIN_06) +#define USBFS_VBUS (BSP_IO_PORT_04_PIN_07) +#define USBHS_VBUSEN (BSP_IO_PORT_04_PIN_08) +#define USBHS_OVRCURA (BSP_IO_PORT_04_PIN_09) +#define MISOB_B_ARDUINO_MIKROBUS (BSP_IO_PORT_04_PIN_10) +#define MOSIB_B_ARDUINO_MIKROBUS (BSP_IO_PORT_04_PIN_11) +#define RSPCKB_B_ARDUINO_MIKROBUS (BSP_IO_PORT_04_PIN_12) +#define SSLB0_B_ARDUINO_D10_MIKROBUS (BSP_IO_PORT_04_PIN_13) +#define LED2 (BSP_IO_PORT_04_PIN_14) +#define USBFS_VBUS_EN (BSP_IO_PORT_05_PIN_00) +#define USBFS_OVERCURA (BSP_IO_PORT_05_PIN_01) +#define MIKROBUS_RESET (BSP_IO_PORT_05_PIN_02) +#define PMOD2_7_IRQ1 (BSP_IO_PORT_05_PIN_08) +#define GROVE2_IIC_SDA1 (BSP_IO_PORT_05_PIN_11) +#define GROVE2_IIC_SCL1 (BSP_IO_PORT_05_PIN_12) +#define LED1 (BSP_IO_PORT_06_PIN_00) +#define ARDUINO_D5 (BSP_IO_PORT_06_PIN_01) +#define ARDUINO_D6 (BSP_IO_PORT_06_PIN_02) +#define ARDUINO_D9 (BSP_IO_PORT_06_PIN_03) +#define PMOD1_3_MISO0_RXD0_SCL0 (BSP_IO_PORT_06_PIN_09) +#define PMOD1_2_MOSI0_TXD0 (BSP_IO_PORT_06_PIN_10) +#define PMOD1_4_SCK0 (BSP_IO_PORT_06_PIN_11) +#define PMOD1_1_SSL0_CTS_RTS (BSP_IO_PORT_06_PIN_12) +#define PMOD1_1_CTS0 (BSP_IO_PORT_06_PIN_13) +#define PMOD1_9_GPIO (BSP_IO_PORT_06_PIN_14) +#define PMOD1_10_GPIO (BSP_IO_PORT_06_PIN_15) +#define ETH_B_TXD0 (BSP_IO_PORT_07_PIN_00) +#define ETH_B_REFCLK (BSP_IO_PORT_07_PIN_01) +#define ETH_B_RXD0 (BSP_IO_PORT_07_PIN_02) +#define ETH_B_RXD1 (BSP_IO_PORT_07_PIN_03) +#define ETH_B_RXER (BSP_IO_PORT_07_PIN_04) +#define ETH_B_RMII_RXDV (BSP_IO_PORT_07_PIN_05) +#define I3C_SDA0_PULLUP (BSP_IO_PORT_07_PIN_11) +#define OSPI_DQ5 (BSP_IO_PORT_08_PIN_00) +#define OSPI_DS (BSP_IO_PORT_08_PIN_01) +#define OSPI_DQ6 (BSP_IO_PORT_08_PIN_02) +#define OSPI_DQ1 (BSP_IO_PORT_08_PIN_03) +#define OSPI_DQ7 (BSP_IO_PORT_08_PIN_04) +#define OSPI_CK (BSP_IO_PORT_08_PIN_08) +#define PMOD2_8_RESET (BSP_IO_PORT_08_PIN_09) +#define PMOD2_9_GPIO (BSP_IO_PORT_08_PIN_10) +#define PMOD2_10_GPIO (BSP_IO_PORT_08_PIN_11) +#define ARDUINO_RESET (BSP_IO_PORT_08_PIN_12) +#define USBFS_P (BSP_IO_PORT_08_PIN_14) +#define USBFS_N (BSP_IO_PORT_08_PIN_15) +#define ARDUINO_D4 (BSP_IO_PORT_09_PIN_05) +#define ARDUINO_D2 (BSP_IO_PORT_09_PIN_06) +#define ARDUINO_D3_MIKROBUS_GTIOC13A (BSP_IO_PORT_09_PIN_07) +#define ARDUINO_D7 (BSP_IO_PORT_09_PIN_08) +#define ARDUINO_D8 (BSP_IO_PORT_09_PIN_09) +#define PMOD2_3_MISO2_RXD2 (BSP_IO_PORT_10_PIN_02) +#define PMOD2_2_MOSI2_TXD2 (BSP_IO_PORT_10_PIN_03) +#define PMOD2_4_SCK2 (BSP_IO_PORT_10_PIN_04) +#define PMOD2_1_CTS_RTS_SSL2 (BSP_IO_PORT_10_PIN_05) +#define PMOD2_1_CTS2 (BSP_IO_PORT_10_PIN_06) +#define PMOD1_8_RESET (BSP_IO_PORT_10_PIN_08) +#define JLOB_COMS_TX (BSP_IO_PORT_10_PIN_14) +#define JLOB_COMS_RX (BSP_IO_PORT_10_PIN_15) +#define I3C_SCL0_PULLUP (BSP_IO_PORT_11_PIN_00) +#define USBHS_VBUS (BSP_IO_PORT_11_PIN_01) +extern const ioport_cfg_t g_bsp_pin_cfg; /* RA8M1 EK */ + +void BSP_PinConfigSecurityInit(); + +/* Common macro for FSP header files. There is also a corresponding FSP_HEADER macro at the top of this file. */ +FSP_FOOTER +#endif /* BSP_PIN_CFG_H_ */ diff --git a/hw/bsp/ra/boards/ra8m1_ek/ra_cfg/fsp_cfg/r_ioport_cfg.h b/hw/bsp/ra/boards/ra8m1_ek/ra_cfg/fsp_cfg/r_ioport_cfg.h new file mode 100644 index 000000000..d2688bf5b --- /dev/null +++ b/hw/bsp/ra/boards/ra8m1_ek/ra_cfg/fsp_cfg/r_ioport_cfg.h @@ -0,0 +1,13 @@ +/* generated configuration header file - do not edit */ +#ifndef R_IOPORT_CFG_H_ +#define R_IOPORT_CFG_H_ +#ifdef __cplusplus +extern "C" { +#endif + +#define IOPORT_CFG_PARAM_CHECKING_ENABLE (BSP_CFG_PARAM_CHECKING_ENABLE) + +#ifdef __cplusplus +} +#endif +#endif /* R_IOPORT_CFG_H_ */ diff --git a/hw/bsp/ra/boards/ra8m1_ek/ra_gen/bsp_clock_cfg.h b/hw/bsp/ra/boards/ra8m1_ek/ra_gen/bsp_clock_cfg.h new file mode 100644 index 000000000..f2f1ae0c9 --- /dev/null +++ b/hw/bsp/ra/boards/ra8m1_ek/ra_gen/bsp_clock_cfg.h @@ -0,0 +1,56 @@ +/* generated configuration header file - do not edit */ +#ifndef BSP_CLOCK_CFG_H_ +#define BSP_CLOCK_CFG_H_ +#define BSP_CFG_CLOCKS_SECURE (0) +#define BSP_CFG_CLOCKS_OVERRIDE (0) +#define BSP_CFG_XTAL_HZ (20000000) /* XTAL 20000000Hz */ +#define BSP_CFG_HOCO_FREQUENCY (7) /* HOCO 48MHz */ +#define BSP_CFG_PLL_SOURCE (BSP_CLOCKS_SOURCE_CLOCK_MAIN_OSC) /* PLL Src: XTAL */ +#define BSP_CFG_PLL_DIV (BSP_CLOCKS_PLL_DIV_2) /* PLL Div /2 */ +#define BSP_CFG_PLL_MUL BSP_CLOCKS_PLL_MUL(96,0) /* PLL Mul x80-99|Mul x96|PLL Mul x96.00 */ +#define BSP_CFG_PLL_FREQUENCY_HZ (960000000) /* PLL 960000000Hz */ +#define BSP_CFG_PLODIVP (BSP_CLOCKS_PLL_DIV_2) /* PLL1P Div /2 */ +#define BSP_CFG_PLL1P_FREQUENCY_HZ (480000000) /* PLL1P 480000000Hz */ +#define BSP_CFG_PLODIVQ (BSP_CLOCKS_PLL_DIV_4) /* PLL1Q Div /4 */ +#define BSP_CFG_PLL1Q_FREQUENCY_HZ (240000000) /* PLL1Q 240000000Hz */ +#define BSP_CFG_PLODIVR (BSP_CLOCKS_PLL_DIV_2) /* PLL1R Div /2 */ +#define BSP_CFG_PLL1R_FREQUENCY_HZ (480000000) /* PLL1R 480000000Hz */ +#define BSP_CFG_PLL2_SOURCE (BSP_CLOCKS_CLOCK_DISABLED) /* PLL2 Disabled */ +#define BSP_CFG_PLL2_DIV (BSP_CLOCKS_PLL_DIV_2) /* PLL2 Div /2 */ +#define BSP_CFG_PLL2_MUL BSP_CLOCKS_PLL_MUL(96,0) /* PLL2 Mul x80-99|Mul x96|PLL2 Mul x96.00 */ +#define BSP_CFG_PLL2_FREQUENCY_HZ (0) /* PLL2 0Hz */ +#define BSP_CFG_PL2ODIVP (BSP_CLOCKS_PLL_DIV_2) /* PLL2P Div /2 */ +#define BSP_CFG_PLL2P_FREQUENCY_HZ (0) /* PLL2P 0Hz */ +#define BSP_CFG_PL2ODIVQ (BSP_CLOCKS_PLL_DIV_2) /* PLL2Q Div /2 */ +#define BSP_CFG_PLL2Q_FREQUENCY_HZ (0) /* PLL2Q 0Hz */ +#define BSP_CFG_PL2ODIVR (BSP_CLOCKS_PLL_DIV_2) /* PLL2R Div /2 */ +#define BSP_CFG_PLL2R_FREQUENCY_HZ (0) /* PLL2R 0Hz */ +#define BSP_CFG_CLOCK_SOURCE (BSP_CLOCKS_SOURCE_CLOCK_PLL1P) /* Clock Src: PLL1P */ +#define BSP_CFG_CLKOUT_SOURCE (BSP_CLOCKS_CLOCK_DISABLED) /* CLKOUT Disabled */ +#define BSP_CFG_SCICLK_SOURCE (BSP_CLOCKS_CLOCK_DISABLED) /* SCICLK Disabled */ +#define BSP_CFG_SPICLK_SOURCE (BSP_CLOCKS_CLOCK_DISABLED) /* SPICLK Disabled */ +#define BSP_CFG_CANFDCLK_SOURCE (BSP_CLOCKS_CLOCK_DISABLED) /* CANFDCLK Disabled */ +#define BSP_CFG_I3CCLK_SOURCE (BSP_CLOCKS_CLOCK_DISABLED) /* I3CCLK Disabled */ +#define BSP_CFG_UCK_SOURCE (BSP_CLOCKS_SOURCE_CLOCK_PLL1Q) /* UCK Src: PLL1Q */ +#define BSP_CFG_U60CK_SOURCE (BSP_CLOCKS_SOURCE_CLOCK_PLL1P) /* U60CK Src: PLL1P */ +#define BSP_CFG_OCTA_SOURCE (BSP_CLOCKS_CLOCK_DISABLED) /* OCTASPICLK Disabled */ +#define BSP_CFG_CPUCLK_DIV (BSP_CLOCKS_SYS_CLOCK_DIV_1) /* CPUCLK Div /1 */ +#define BSP_CFG_ICLK_DIV (BSP_CLOCKS_SYS_CLOCK_DIV_2) /* ICLK Div /2 */ +#define BSP_CFG_PCLKA_DIV (BSP_CLOCKS_SYS_CLOCK_DIV_4) /* PCLKA Div /4 */ +#define BSP_CFG_PCLKB_DIV (BSP_CLOCKS_SYS_CLOCK_DIV_8) /* PCLKB Div /8 */ +#define BSP_CFG_PCLKC_DIV (BSP_CLOCKS_SYS_CLOCK_DIV_8) /* PCLKC Div /8 */ +#define BSP_CFG_PCLKD_DIV (BSP_CLOCKS_SYS_CLOCK_DIV_4) /* PCLKD Div /4 */ +#define BSP_CFG_PCLKE_DIV (BSP_CLOCKS_SYS_CLOCK_DIV_2) /* PCLKE Div /2 */ +#define BSP_CFG_SDCLK_OUTPUT (1) /* SDCLK Enabled */ +#define BSP_CFG_BCLK_DIV (BSP_CLOCKS_SYS_CLOCK_DIV_4) /* BCLK Div /4 */ +#define BSP_CFG_BCLK_OUTPUT (2) /* EBCLK Div /2 */ +#define BSP_CFG_FCLK_DIV (BSP_CLOCKS_SYS_CLOCK_DIV_8) /* FCLK Div /8 */ +#define BSP_CFG_CLKOUT_DIV (BSP_CLOCKS_SYS_CLOCK_DIV_1) /* CLKOUT Div /1 */ +#define BSP_CFG_SCICLK_DIV (BSP_CLOCKS_SCI_CLOCK_DIV_4) /* SCICLK Div /4 */ +#define BSP_CFG_SPICLK_DIV (BSP_CLOCKS_SPI_CLOCK_DIV_4) /* SPICLK Div /4 */ +#define BSP_CFG_CANFDCLK_DIV (BSP_CLOCKS_CANFD_CLOCK_DIV_8) /* CANFDCLK Div /8 */ +#define BSP_CFG_I3CCLK_DIV (BSP_CLOCKS_I3C_CLOCK_DIV_3) /* I3CCLK Div /3 */ +#define BSP_CFG_UCK_DIV (BSP_CLOCKS_USB_CLOCK_DIV_5) /* UCK Div /5 */ +#define BSP_CFG_U60CK_DIV (BSP_CLOCKS_USB_CLOCK_DIV_8) /* U60CK Div /8 */ +#define BSP_CFG_OCTA_DIV (BSP_CLOCKS_OCTA_CLOCK_DIV_4) /* OCTASPICLK Div /4 */ +#endif /* BSP_CLOCK_CFG_H_ */ diff --git a/hw/bsp/ra/boards/ra8m1_ek/ra_gen/common_data.c b/hw/bsp/ra/boards/ra8m1_ek/ra_gen/common_data.c new file mode 100644 index 000000000..50036c0ad --- /dev/null +++ b/hw/bsp/ra/boards/ra8m1_ek/ra_gen/common_data.c @@ -0,0 +1,11 @@ +/* generated common source file - do not edit */ +#include "common_data.h" +ioport_instance_ctrl_t g_ioport_ctrl; +const ioport_instance_t g_ioport = + { + .p_api = &g_ioport_on_ioport, + .p_ctrl = &g_ioport_ctrl, + .p_cfg = &g_bsp_pin_cfg, + }; +void g_common_init(void) { +} diff --git a/hw/bsp/ra/boards/ra8m1_ek/ra_gen/common_data.h b/hw/bsp/ra/boards/ra8m1_ek/ra_gen/common_data.h new file mode 100644 index 000000000..6a08cbee0 --- /dev/null +++ b/hw/bsp/ra/boards/ra8m1_ek/ra_gen/common_data.h @@ -0,0 +1,20 @@ +/* generated common header file - do not edit */ +#ifndef COMMON_DATA_H_ +#define COMMON_DATA_H_ +#include +#include "bsp_api.h" +#include "r_ioport.h" +#include "bsp_pin_cfg.h" +FSP_HEADER +#define IOPORT_CFG_NAME g_bsp_pin_cfg +#define IOPORT_CFG_OPEN R_IOPORT_Open +#define IOPORT_CFG_CTRL g_ioport_ctrl + +/* IOPORT Instance */ +extern const ioport_instance_t g_ioport; + +/* IOPORT control structure. */ +extern ioport_instance_ctrl_t g_ioport_ctrl; +void g_common_init(void); +FSP_FOOTER +#endif /* COMMON_DATA_H_ */ diff --git a/hw/bsp/ra/boards/ra8m1_ek/ra_gen/pin_data.c b/hw/bsp/ra/boards/ra8m1_ek/ra_gen/pin_data.c new file mode 100644 index 000000000..b92421739 --- /dev/null +++ b/hw/bsp/ra/boards/ra8m1_ek/ra_gen/pin_data.c @@ -0,0 +1,275 @@ +/* generated pin source file - do not edit */ +#include "bsp_api.h" +#include "r_ioport.h" + + +const ioport_pin_cfg_t g_bsp_pin_cfg_data[] = { + { + .pin = BSP_IO_PORT_00_PIN_00, + .pin_cfg = ((uint32_t) IOPORT_CFG_PORT_DIRECTION_INPUT) + }, + { + .pin = BSP_IO_PORT_00_PIN_02, + .pin_cfg = ((uint32_t) IOPORT_CFG_ANALOG_ENABLE) + }, + { + .pin = BSP_IO_PORT_00_PIN_03, + .pin_cfg = ((uint32_t) IOPORT_CFG_ANALOG_ENABLE) + }, + { + .pin = BSP_IO_PORT_00_PIN_04, + .pin_cfg = ((uint32_t) IOPORT_CFG_ANALOG_ENABLE) + }, + { + .pin = BSP_IO_PORT_00_PIN_05, + .pin_cfg = ((uint32_t) IOPORT_CFG_ANALOG_ENABLE) + }, + { + .pin = BSP_IO_PORT_00_PIN_07, + .pin_cfg = ((uint32_t) IOPORT_CFG_ANALOG_ENABLE) + }, + { + .pin = BSP_IO_PORT_00_PIN_08, + .pin_cfg = ((uint32_t) IOPORT_CFG_IRQ_ENABLE | (uint32_t) IOPORT_CFG_PORT_DIRECTION_INPUT) + }, + { + .pin = BSP_IO_PORT_00_PIN_09, + .pin_cfg = ((uint32_t) IOPORT_CFG_IRQ_ENABLE | (uint32_t) IOPORT_CFG_PORT_DIRECTION_INPUT) + }, + { + .pin = BSP_IO_PORT_00_PIN_11, + .pin_cfg = ((uint32_t) IOPORT_CFG_ANALOG_ENABLE) + }, + { + .pin = BSP_IO_PORT_00_PIN_14, + .pin_cfg = ((uint32_t) IOPORT_CFG_ANALOG_ENABLE) + }, + { + .pin = BSP_IO_PORT_00_PIN_15, + .pin_cfg = ((uint32_t) IOPORT_CFG_ANALOG_ENABLE) + }, + { + .pin = BSP_IO_PORT_01_PIN_00, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HS_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_OSPI) + }, + { + .pin = BSP_IO_PORT_01_PIN_01, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HS_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_OSPI) + }, + { + .pin = BSP_IO_PORT_01_PIN_02, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HS_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_OSPI) + }, + { + .pin = BSP_IO_PORT_01_PIN_03, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HS_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_OSPI) + }, + { + .pin = BSP_IO_PORT_01_PIN_04, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_OSPI) + }, + { + .pin = BSP_IO_PORT_01_PIN_05, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_OSPI) + }, + { + .pin = BSP_IO_PORT_01_PIN_06, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_OSPI) + }, + { + .pin = BSP_IO_PORT_01_PIN_07, + .pin_cfg = ((uint32_t) IOPORT_CFG_PORT_DIRECTION_OUTPUT | (uint32_t) IOPORT_CFG_PORT_OUTPUT_LOW) + }, + { + .pin = BSP_IO_PORT_02_PIN_09, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_TRACE) + }, + { + .pin = BSP_IO_PORT_02_PIN_10, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_DEBUG) + }, + { + .pin = BSP_IO_PORT_02_PIN_11, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_DEBUG) + }, + { + .pin = BSP_IO_PORT_03_PIN_04, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_TRACE) + }, + { + .pin = BSP_IO_PORT_03_PIN_05, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_TRACE) + }, + { + .pin = BSP_IO_PORT_03_PIN_06, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_TRACE) + }, + { + .pin = BSP_IO_PORT_03_PIN_07, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_TRACE) + }, + { + .pin = BSP_IO_PORT_03_PIN_08, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_TRACE) + }, + { + .pin = BSP_IO_PORT_04_PIN_07, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_USB_FS) + }, + { + .pin = BSP_IO_PORT_04_PIN_08, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_USB_HS) + }, + { + .pin = BSP_IO_PORT_04_PIN_09, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_USB_HS) + }, + { + .pin = BSP_IO_PORT_04_PIN_10, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SPI) + }, + { + .pin = BSP_IO_PORT_04_PIN_11, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SPI) + }, + { + .pin = BSP_IO_PORT_04_PIN_12, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SPI) + }, + { + .pin = BSP_IO_PORT_04_PIN_13, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SPI) + }, + { + .pin = BSP_IO_PORT_04_PIN_14, + .pin_cfg = ((uint32_t) IOPORT_CFG_PORT_DIRECTION_OUTPUT | (uint32_t) IOPORT_CFG_PORT_OUTPUT_LOW) + }, + { + .pin = BSP_IO_PORT_05_PIN_00, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_USB_FS) + }, + { + .pin = BSP_IO_PORT_05_PIN_01, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_USB_FS) + }, + { + .pin = BSP_IO_PORT_05_PIN_11, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_MID | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_IIC) + }, + { + .pin = BSP_IO_PORT_05_PIN_12, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_MID | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_IIC) + }, + { + .pin = BSP_IO_PORT_06_PIN_00, + .pin_cfg = ((uint32_t) IOPORT_CFG_PORT_DIRECTION_OUTPUT | (uint32_t) IOPORT_CFG_PORT_OUTPUT_LOW) + }, + { + .pin = BSP_IO_PORT_08_PIN_00, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HS_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_OSPI) + }, + { + .pin = BSP_IO_PORT_08_PIN_01, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HS_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_OSPI) + }, + { + .pin = BSP_IO_PORT_08_PIN_02, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HS_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_OSPI) + }, + { + .pin = BSP_IO_PORT_08_PIN_03, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HS_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_OSPI) + }, + { + .pin = BSP_IO_PORT_08_PIN_04, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HS_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_OSPI) + }, + { + .pin = BSP_IO_PORT_08_PIN_08, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HS_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_OSPI) + }, + { + .pin = BSP_IO_PORT_08_PIN_09, + .pin_cfg = ((uint32_t) IOPORT_CFG_PORT_DIRECTION_OUTPUT | (uint32_t) IOPORT_CFG_PORT_OUTPUT_LOW) + }, + { + .pin = BSP_IO_PORT_08_PIN_14, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_USB_FS) + }, + { + .pin = BSP_IO_PORT_08_PIN_15, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_USB_FS) + }, + { + .pin = BSP_IO_PORT_10_PIN_02, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SCI0_2_4_6_8) + }, + { + .pin = BSP_IO_PORT_10_PIN_03, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SCI0_2_4_6_8) + }, + { + .pin = BSP_IO_PORT_10_PIN_04, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SCI0_2_4_6_8) + }, + { + .pin = BSP_IO_PORT_10_PIN_05, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SCI0_2_4_6_8) + }, + { + .pin = BSP_IO_PORT_10_PIN_06, + .pin_cfg = ((uint32_t) IOPORT_CFG_PORT_DIRECTION_INPUT) + }, + { + .pin = BSP_IO_PORT_10_PIN_14, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SCI1_3_5_7_9) + }, + { + .pin = BSP_IO_PORT_10_PIN_15, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SCI1_3_5_7_9) + }, + { + .pin = BSP_IO_PORT_11_PIN_01, + .pin_cfg = ((uint32_t) IOPORT_CFG_DRIVE_HIGH | (uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_USB_HS) + }, +}; + +const ioport_cfg_t g_bsp_pin_cfg = { + .number_of_pins = sizeof(g_bsp_pin_cfg_data)/sizeof(ioport_pin_cfg_t), + .p_pin_cfg_data = &g_bsp_pin_cfg_data[0], +}; + +#if BSP_TZ_SECURE_BUILD + +void R_BSP_PinCfgSecurityInit(void); + +/* Initialize SAR registers for secure pins. */ +void R_BSP_PinCfgSecurityInit(void) +{ + #if (2U == BSP_FEATURE_IOPORT_VERSION) + uint32_t pmsar[BSP_FEATURE_BSP_NUM_PMSAR]; + #else + uint16_t pmsar[BSP_FEATURE_BSP_NUM_PMSAR]; + #endif + memset(pmsar, 0xFF, BSP_FEATURE_BSP_NUM_PMSAR * sizeof(R_PMISC->PMSAR[0])); + + + for(uint32_t i = 0; i < g_bsp_pin_cfg.number_of_pins; i++) + { + uint32_t port_pin = g_bsp_pin_cfg.p_pin_cfg_data[i].pin; + uint32_t port = port_pin >> 8U; + uint32_t pin = port_pin & 0xFFU; + pmsar[port] &= (uint16_t) ~(1U << pin); + } + + for(uint32_t i = 0; i < BSP_FEATURE_BSP_NUM_PMSAR; i++) + { + #if (2U == BSP_FEATURE_IOPORT_VERSION) + R_PMISC->PMSAR[i].PMSAR = (uint16_t) pmsar[i]; + #else + R_PMISC->PMSAR[i].PMSAR = pmsar[i]; + #endif + } + +} +#endif diff --git a/hw/bsp/ra/boards/ra8m1_ek/script/fsp.ld b/hw/bsp/ra/boards/ra8m1_ek/script/fsp.ld new file mode 100644 index 000000000..d7f78a915 --- /dev/null +++ b/hw/bsp/ra/boards/ra8m1_ek/script/fsp.ld @@ -0,0 +1,823 @@ +/* + Linker File for Renesas FSP +*/ + +INCLUDE memory_regions.ld + +/* Uncomment and set XIP_SECONDARY_SLOT_IMAGE to 1 below for the secondary XIP application image.*/ +/* + XIP_SECONDARY_SLOT_IMAGE = 1; +*/ + +QSPI_FLASH_PRV_LENGTH = DEFINED(QSPI_FLASH_SIZE) ? ABSOLUTE(QSPI_FLASH_SIZE) : ABSOLUTE(QSPI_FLASH_LENGTH); +OSPI_DEVICE_0_PRV_LENGTH = DEFINED(OSPI_DEVICE_0_SIZE) ? ABSOLUTE(OSPI_DEVICE_0_SIZE) : ABSOLUTE(OSPI_DEVICE_0_LENGTH); +OSPI_DEVICE_1_PRV_LENGTH = DEFINED(OSPI_DEVICE_1_SIZE) ? ABSOLUTE(OSPI_DEVICE_1_SIZE) : ABSOLUTE(OSPI_DEVICE_1_LENGTH); + +/* If a flat (secure) project has DEFINED RAM_NS_BUFFER_LENGTH, then emit IDAU symbols to allocate non-secure RAM. */ +__RESERVE_NS_RAM = !DEFINED(PROJECT_NONSECURE) && DEFINED(RAM_NS_BUFFER_LENGTH) && (OPTION_SETTING_S_LENGTH != 0); + +ITCM_START = DEFINED(ITCM_START)? ITCM_START : 0; +ITCM_LENGTH = DEFINED(ITCM_LENGTH)? ITCM_LENGTH : 0; +DTCM_START = DEFINED(DTCM_START)? DTCM_START : 0; +DTCM_LENGTH = DEFINED(DTCM_LENGTH)? DTCM_LENGTH : 0; +RAM_NS_BUFFER_BLOCK_LENGTH = DEFINED(RAM_NS_BUFFER_LENGTH) ? ALIGN(RAM_NS_BUFFER_LENGTH, 8192) : 0; +RAM_NS_BUFFER_LENGTH = DEFINED(RAM_NS_BUFFER_LENGTH) ? RAM_NS_BUFFER_LENGTH : 0; +RAM_NS_BUFFER_START = RAM_START + RAM_LENGTH - RAM_NS_BUFFER_LENGTH; +RAM_NS_BUFFER_BLOCK_START = RAM_START + RAM_LENGTH - RAM_NS_BUFFER_BLOCK_LENGTH; + +OPTION_SETTING_START_NS = DEFINED(PROJECT_NONSECURE) ? OPTION_SETTING_START : OPTION_SETTING_START + 0x80; +OPTION_SETTING_DATA_FLASH_S_START = DEFINED(OPTION_SETTING_DATA_FLASH_S_START) ? OPTION_SETTING_DATA_FLASH_S_START : 0; +OPTION_SETTING_DATA_FLASH_S_LENGTH = DEFINED(OPTION_SETTING_DATA_FLASH_S_LENGTH) ? OPTION_SETTING_DATA_FLASH_S_LENGTH : 0; + +/* This definition is used to avoid moving the counter in OPTION_SETTING regions for projects that should not configure option settings. + * Bootloader images do not configure option settings because they are owned by the bootloader. + * FSP_BOOTABLE_IMAGE is only defined in bootloader images. */ +__bl_FSP_BOOTABLE_IMAGE = 1; +__bln_FSP_BOOTABLE_IMAGE = 1; +PROJECT_SECURE_OR_FLAT = (!DEFINED(PROJECT_NONSECURE) || DEFINED(PROJECT_SECURE)) && OPTION_SETTING_LENGTH && !DEFINED(FSP_BOOTABLE_IMAGE); +USE_OPTION_SETTING_NS = DEFINED(PROJECT_NONSECURE) && !DEFINED(FSP_BOOTABLE_IMAGE); +USE_OPTION_SETTING_DATA_FLASH = PROJECT_SECURE_OR_FLAT && (OPTION_SETTING_DATA_FLASH_S_LENGTH != 0); + +__bl_FLASH_IMAGE_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_IMAGE_NUMBER == 1 ? FLASH_START + FLASH_BOOTLOADER_LENGTH + FLASH_BOOTLOADER_HEADER_LENGTH : + (DEFINED(BOOTLOADER_SECONDARY_USE_QSPI) || DEFINED(BOOTLOADER_SECONDARY_USE_OSPI_B)) ? FLASH_START + FLASH_BOOTLOADER_LENGTH + FLASH_BOOTLOADER_SCRATCH_LENGTH + FLASH_BOOTLOADER_HEADER_LENGTH : + FLASH_START + FLASH_BOOTLOADER_LENGTH + FLASH_BOOTLOADER_SCRATCH_LENGTH + FLASH_APPLICATION_S_LENGTH + FLASH_BOOTLOADER_HEADER_LENGTH; +__bl_FLASH_IMAGE_LENGTH = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_S_LENGTH - FLASH_BOOTLOADER_HEADER_LENGTH; +__bl_FLASH_IMAGE_END = __bl_FLASH_IMAGE_START + __bl_FLASH_IMAGE_LENGTH; +__bl_XIP_SECONDARY_FLASH_IMAGE_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_START + FLASH_BOOTLOADER_LENGTH + FLASH_APPLICATION_S_LENGTH + FLASH_BOOTLOADER_HEADER_LENGTH; +__bl_XIP_SECONDARY_FLASH_IMAGE_END = __bl_XIP_SECONDARY_FLASH_IMAGE_START + __bl_FLASH_IMAGE_LENGTH; +__bl_FLASH_NS_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_NS_LENGTH == 0 ? __bl_FLASH_IMAGE_END : + __bl_FLASH_IMAGE_START - FLASH_BOOTLOADER_HEADER_LENGTH + FLASH_APPLICATION_S_LENGTH; +__bl_FLASH_NSC_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_NS_LENGTH == 0 ? __bl_FLASH_IMAGE_END : + __bl_FLASH_IMAGE_END - FLASH_APPLICATION_NSC_LENGTH; +__bl_RAM_NS_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_NS_LENGTH == 0 ? RAM_START + RAM_LENGTH : + RAM_START + RAM_LENGTH - RAM_APPLICATION_NS_LENGTH; +__bl_RAM_NSC_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_NS_LENGTH == 0 ? RAM_START + RAM_LENGTH : + __bl_RAM_NS_START - RAM_APPLICATION_NSC_LENGTH; +__bl_FLASH_NS_IMAGE_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_NS_LENGTH == 0 ? __bl_FLASH_IMAGE_END : + __bl_FLASH_NS_START + FLASH_BOOTLOADER_HEADER_LENGTH_2; +__bln_FLASH_IMAGE_START = __bl_FLASH_NS_IMAGE_START | (!DEFINED (NS_OFFSET_START) ? 0 : NS_OFFSET_START); +__bln_FLASH_IMAGE_LENGTH = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_NS_LENGTH == 0 ? __bl_FLASH_IMAGE_END : + FLASH_APPLICATION_NS_LENGTH - FLASH_BOOTLOADER_HEADER_LENGTH_2; + +XIP_SECONDARY_SLOT_IMAGE = DEFINED(XIP_SECONDARY_SLOT_IMAGE) ? XIP_SECONDARY_SLOT_IMAGE : 0; +FLASH_ORIGIN = !DEFINED(FLASH_IMAGE_START) ? FLASH_START : + XIP_SECONDARY_SLOT_IMAGE == 1 ? XIP_SECONDARY_FLASH_IMAGE_START : + FLASH_IMAGE_START; +LIMITED_FLASH_LENGTH = DEFINED(FLASH_IMAGE_LENGTH) ? FLASH_IMAGE_LENGTH : + DEFINED(FLASH_BOOTLOADER_LENGTH) ? FLASH_BOOTLOADER_LENGTH : + FLASH_LENGTH; +OPTION_SETTING_SAS_SIZE = 0x34; +OPTION_SETTING_SAS_LENGTH = !DEFINED(OPTION_SETTING_LENGTH) ? 0 : + OPTION_SETTING_LENGTH == 0 ? 0 : + OPTION_SETTING_LENGTH - OPTION_SETTING_SAS_SIZE; + +/* Define memory regions. */ +MEMORY +{ + ITCM (rx) : ORIGIN = ITCM_START, LENGTH = ITCM_LENGTH + DTCM (rwx) : ORIGIN = DTCM_START, LENGTH = DTCM_LENGTH + FLASH (rx) : ORIGIN = FLASH_ORIGIN, LENGTH = LIMITED_FLASH_LENGTH + RAM (rwx) : ORIGIN = RAM_START, LENGTH = RAM_LENGTH + DATA_FLASH (rx) : ORIGIN = DATA_FLASH_START, LENGTH = DATA_FLASH_LENGTH + QSPI_FLASH (rx) : ORIGIN = QSPI_FLASH_START, LENGTH = QSPI_FLASH_PRV_LENGTH + OSPI_DEVICE_0 (rx) : ORIGIN = OSPI_DEVICE_0_START, LENGTH = OSPI_DEVICE_0_PRV_LENGTH + OSPI_DEVICE_1 (rx) : ORIGIN = OSPI_DEVICE_1_START, LENGTH = OSPI_DEVICE_1_PRV_LENGTH + OSPI_DEVICE_0_RAM (rwx) : ORIGIN = OSPI_DEVICE_0_START, LENGTH = OSPI_DEVICE_0_PRV_LENGTH + OSPI_DEVICE_1_RAM (rwx) : ORIGIN = OSPI_DEVICE_1_START, LENGTH = OSPI_DEVICE_1_PRV_LENGTH + SDRAM (rwx) : ORIGIN = SDRAM_START, LENGTH = SDRAM_LENGTH + OPTION_SETTING (r) : ORIGIN = OPTION_SETTING_START, LENGTH = OPTION_SETTING_LENGTH + OPTION_SETTING_OFS (r) : ORIGIN = OPTION_SETTING_START, LENGTH = 0x18 + OPTION_SETTING_SAS (r) : ORIGIN = OPTION_SETTING_START + OPTION_SETTING_SAS_SIZE, LENGTH = OPTION_SETTING_SAS_LENGTH + OPTION_SETTING_S (r) : ORIGIN = OPTION_SETTING_S_START, LENGTH = OPTION_SETTING_S_LENGTH + OPTION_SETTING_DATA_FLASH_S (r) : ORIGIN = OPTION_SETTING_DATA_FLASH_S_START, LENGTH = OPTION_SETTING_DATA_FLASH_S_LENGTH + ID_CODE (rx) : ORIGIN = ID_CODE_START, LENGTH = ID_CODE_LENGTH +} + +/* Library configurations */ +GROUP(libgcc.a libc.a libm.a) + +/* Linker script to place sections and symbol values. Should be used together + * with other linker script that defines memory regions FLASH and RAM. + * It references following symbols, which must be DEFINED in code: + * Reset_Handler : Entry of reset handler + * + * It defines following symbols, which code can use without definition: + * __exidx_start + * __exidx_end + * __copy_table_start__ + * __copy_table_end__ + * __zero_table_start__ + * __zero_table_end__ + * __etext + * __data_start__ + * __preinit_array_start + * __preinit_array_end + * __init_array_start + * __init_array_end + * __fini_array_start + * __fini_array_end + * __data_end__ + * __bss_start__ + * __bss_end__ + * __HeapLimit + * __StackLimit + * __StackTop + * __stack + * __Vectors_End + * __Vectors_Size + * __qspi_flash_start__ + * __qspi_flash_end__ + * __qspi_flash_code_size__ + * __qspi_region_max_size__ + * __qspi_region_start_address__ + * __qspi_region_end_address__ + * __ospi_device_0_start__ + * __ospi_device_0_end__ + * __ospi_device_0_code_size__ + * __ospi_device_0_region_max_size__ + * __ospi_device_0_region_start_address__ + * __ospi_device_0_region_end_address__ + * __ospi_device_1_start__ + * __ospi_device_1_end__ + * __ospi_device_1_code_size__ + * __ospi_device_1_region_max_size__ + * __ospi_device_1_region_start_address__ + * __ospi_device_1_region_end_address__ + */ +ENTRY(Reset_Handler) + +SECTIONS +{ + .text : + { + __tz_FLASH_S = ABSOLUTE(FLASH_START); + __ROM_Start = .; + + /* Even though the vector table is not 256 entries (1KB) long, we still allocate that much + * space because ROM registers are at address 0x400 and there is very little space + * in between. */ + KEEP(*(.fixed_vectors*)) + KEEP(*(.application_vectors*)) + __Vectors_End = .; + + /* Some devices have a gap of code flash between the vector table and ROM Registers. + * The flash gap section allows applications to place code and data in this section. */ + *(.flash_gap*) + + /* ROM Registers start at address 0x00000400 for devices that do not have the OPTION_SETTING region. */ + . = OPTION_SETTING_LENGTH > 0 ? . : __ROM_Start + 0x400; + KEEP(*(.rom_registers*)) + + /* Reserving 0x100 bytes of space for ROM registers. */ + . = OPTION_SETTING_LENGTH > 0 ? . : __ROM_Start + 0x500; + + /* Allocate flash write-boundary-aligned + * space for sce9 wrapped public keys for mcuboot if the module is used. + */ + KEEP(*(.mcuboot_sce9_key*)) + + *(.text*) + + KEEP(*(.version)) + KEEP(*(.init)) + KEEP(*(.fini)) + + /* .ctors */ + *crtbegin.o(.ctors) + *crtbegin?.o(.ctors) + *(EXCLUDE_FILE(*crtend?.o *crtend.o) .ctors) + *(SORT(.ctors.*)) + *(.ctors) + + /* .dtors */ + *crtbegin.o(.dtors) + *crtbegin?.o(.dtors) + *(EXCLUDE_FILE(*crtend?.o *crtend.o) .dtors) + *(SORT(.dtors.*)) + *(.dtors) + + *(.rodata*) + __usb_dev_descriptor_start_fs = .; + KEEP(*(.usb_device_desc_fs*)) + __usb_cfg_descriptor_start_fs = .; + KEEP(*(.usb_config_desc_fs*)) + __usb_interface_descriptor_start_fs = .; + KEEP(*(.usb_interface_desc_fs*)) + __usb_descriptor_end_fs = .; + __usb_dev_descriptor_start_hs = .; + KEEP(*(.usb_device_desc_hs*)) + __usb_cfg_descriptor_start_hs = .; + KEEP(*(.usb_config_desc_hs*)) + __usb_interface_descriptor_start_hs = .; + KEEP(*(.usb_interface_desc_hs*)) + __usb_descriptor_end_hs = .; + + KEEP(*(.eh_frame*)) + + __ROM_End = .; + } > FLASH = 0xFF + + __Vectors_Size = __Vectors_End - __Vectors; + + . = .; + __itcm_data_pre_location = .; + + /* Initialized ITCM data. */ + /* Aligned to FCACHE2 for RA8. */ + .itcm_data : ALIGN(16) + { + /* Start of ITCM Secure Trustzone region. */ + __tz_ITCM_S = ABSOLUTE(ITCM_START); + + /* All ITCM data start */ + __itcm_data_start = .; + + KEEP(*(.itcm_data*)) + + /* Pad to eight byte alignment in case of ECC initialization. Fill zero. */ + . = ALIGN(8); + + /* All ITCM data end */ + __itcm_data_end = .; + + /* + * Start of the ITCM Non-Secure Trustzone region. + * ITCM_NS_START can be used to set a fixed address for non-secure ITCM in secure projects or flat projects. + */ + __tz_ITCM_N = DEFINED(ITCM_NS_START) ? ABSOLUTE(ITCM_NS_START) : ALIGN(__itcm_data_end, 8192); + } > ITCM AT > FLASH = 0x00 + + /* Addresses exported for ITCM initialization. */ + __itcm_data_init_start = LOADADDR(.itcm_data); + __itcm_data_init_end = LOADADDR(.itcm_data) + SIZEOF(.itcm_data); + + ASSERT(ORIGIN(ITCM) % 8 == 0, "ITCM memory region origin must be aligned to 8 bytes.") + ASSERT(LENGTH(ITCM) % 8 == 0, "ITCM memory region length must be a multiple of 8 bytes.") + ASSERT(LOADADDR(.itcm_data) % 16 == 0, ".itcm_data section must be aligned to 16 bytes.") + ASSERT(SIZEOF(.itcm_data) % 8 == 0, ".itcm_data section size must be a multiple of 8 bytes.") + + /* Restore location counter. */ + /* If ITCM is not present, this will be the address stored in '.' before ALIGN was attempted. */ + /* If ITCM is present, this will be the absolute address that follows the ITCM ROM location. */ + . = (SIZEOF(.itcm_data) > 0) ? __itcm_data_init_end : __itcm_data_pre_location; + + __exidx_start = .; + /DISCARD/ : + { + *(.ARM.extab* .gnu.linkonce.armextab.*) + *(.ARM.exidx* .gnu.linkonce.armexidx.*) + } + __exidx_end = .; + + /* To copy multiple ROM to RAM sections, + * uncomment .copy.table section and, + * define __STARTUP_COPY_MULTIPLE in startup_ARMCMx.S */ + /* + .copy.table : + { + . = ALIGN(4); + __copy_table_start__ = .; + LONG (__etext) + LONG (__data_start__) + LONG (__data_end__ - __data_start__) + LONG (__etext2) + LONG (__data2_start__) + LONG (__data2_end__ - __data2_start__) + __copy_table_end__ = .; + } > FLASH + */ + + /* To clear multiple BSS sections, + * uncomment .zero.table section and, + * define __STARTUP_CLEAR_BSS_MULTIPLE in startup_ARMCMx.S */ + /* + .zero.table : + { + . = ALIGN(4); + __zero_table_start__ = .; + LONG (__bss_start__) + LONG (__bss_end__ - __bss_start__) + LONG (__bss2_start__) + LONG (__bss2_end__ - __bss2_start__) + __zero_table_end__ = .; + } > FLASH + */ + + __etext = .; + + __tz_RAM_S = ORIGIN(RAM); + + /* If DTC is used, put the DTC vector table at the start of SRAM. + This avoids memory holes due to 1K alignment required by it. */ + .fsp_dtc_vector_table (NOLOAD) : + { + . = ORIGIN(RAM); + *(.fsp_dtc_vector_table) + } > RAM + + /* Initialized data section. */ + .data : + { + __data_start__ = .; + . = ALIGN(4); + + __Code_In_RAM_Start = .; + + KEEP(*(.code_in_ram*)) + __Code_In_RAM_End = .; + + *(vtable) + /* Don't use *(.data*) because it will place data meant for .data_flash in this section. */ + *(.data.*) + *(.data) + + . = ALIGN(4); + /* preinit data */ + PROVIDE_HIDDEN (__preinit_array_start = .); + KEEP(*(.preinit_array)) + PROVIDE_HIDDEN (__preinit_array_end = .); + + . = ALIGN(4); + /* init data */ + PROVIDE_HIDDEN (__init_array_start = .); + KEEP(*(SORT(.init_array.*))) + KEEP(*(.init_array)) + PROVIDE_HIDDEN (__init_array_end = .); + + + . = ALIGN(4); + /* finit data */ + PROVIDE_HIDDEN (__fini_array_start = .); + KEEP(*(SORT(.fini_array.*))) + KEEP(*(.fini_array)) + PROVIDE_HIDDEN (__fini_array_end = .); + + KEEP(*(.jcr*)) + + . = ALIGN(4); + + /* All data end */ + __data_end__ = .; + + } > RAM AT > FLASH + + . = .; + __dtcm_data_pre_location = LOADADDR(.data) + SIZEOF(.data); + + /* Initialized DTCM data. */ + /* Aligned to FCACHE2 for RA8. */ + .dtcm_data : ALIGN(16) + { + /* Start of DTCM Secure Trustzone region. */ + __tz_DTCM_S = ABSOLUTE(DTCM_START); + + /* Initialized DTCM data start */ + __dtcm_data_start = .; + + KEEP(*(.dtcm_data*)) + + /* Pad to eight byte alignment in case of ECC initialization. Fill zero. */ + . = ALIGN(8); + + /* Initialized DTCM data end */ + __dtcm_data_end = .; + } > DTCM AT > FLASH = 0x00 + + . = __dtcm_data_end; + /* Uninitialized DTCM data. */ + /* ALIGN appears on the left side of the colon because it is being used to assign the VMA directly, as opposed to a right side appearance which would control the LMA. */ + .dtcm_bss ALIGN(8) (NOLOAD) : + { + /* Uninitialized DTCM data start */ + __dtcm_bss_start = .; + + KEEP(*(.dtcm_bss*)) + + /* Pad to eight byte alignment in case of ECC initialization. No fill because of NOLOAD. */ + . = ALIGN(8); + + /* Uninitialized DTCM data end */ + __dtcm_bss_end = .; + + /* + * Start of the DTCM Non-Secure Trustzone region. + * DTCM_NS_START can be used to set a fixed address for non-secure DTCM in secure projects or flat projects. + */ + __tz_DTCM_N = DEFINED(DTCM_NS_START) ? ABSOLUTE(DTCM_NS_START) : ALIGN(__dtcm_bss_end, 8192); + } > DTCM + + /* Addresses exported for DTCM initialization. */ + __dtcm_data_init_start = LOADADDR(.dtcm_data); + __dtcm_data_init_end = LOADADDR(.dtcm_data) + SIZEOF(.dtcm_data); + + ASSERT(ORIGIN(DTCM) % 8 == 0, "DTCM memory region origin must be aligned to 8 bytes.") + ASSERT(LENGTH(DTCM) % 8 == 0, "DTCM memory region length must be a multiple of 8 bytes.") + ASSERT(LOADADDR(.dtcm_bss) == ADDR(.dtcm_bss), ".dtcm_bss has (VMA != LMA) but should be NOLOAD (VMA == LMA).") + ASSERT(LOADADDR(.dtcm_data) % 16 == 0, ".dtcm_data section must be aligned to 16 bytes.") + ASSERT(SIZEOF(.dtcm_data) % 8 == 0, ".dtcm_data section size must be a multiple of 8 bytes.") + ASSERT(LOADADDR(.dtcm_bss) % 8 == 0, ".dtcm_bss section must be aligned to 8 bytes.") + ASSERT(SIZEOF(.dtcm_bss) % 8 == 0, ".dtcm_bss section size must be a multiple of 8 bytes.") + ASSERT(__dtcm_bss_start == __dtcm_data_end, ".dtcm_bss section is not adjacent to .dtcm_data section.") + + /* Restore location counter. */ + /* If DTCM is not present, this will be the address stored in '.' before ALIGN was attempted. */ + /* If DTCM is present, this will be the absolute address that follows the DTCM ROM location. */ + . = (SIZEOF(.dtcm_data) > 0) ? __dtcm_data_init_end : __dtcm_data_pre_location; + + /* TrustZone Secure Gateway Stubs Section */ + + /* Store location counter for SPI non-retentive sections. */ + sgstubs_pre_location = .; + + /* Determine the secure gateway stubs address either by the provided linker variable or the next 1024-byte block. */ + SGSTUBS_LOC = (DEFINED(PROJECT_SECURE) && DEFINED(FLASH_NSC_START)) ? ABSOLUTE(FLASH_NSC_START) : ALIGN(1024); + .gnu.sgstubs SGSTUBS_LOC : ALIGN(1024) + { + __FLASH_NSC_START = DEFINED(FLASH_NSC_START) ? ABSOLUTE(FLASH_NSC_START) : __RESERVE_NS_RAM ? ABSOLUTE(FLASH_START + FLASH_LENGTH) : ALIGN(1024); + _start_sg = .; + *(.gnu.sgstubs*) + . = ALIGN(32); + _end_sg = .; + } > FLASH + + __tz_FLASH_N = DEFINED(FLASH_NS_START) ? ABSOLUTE(FLASH_NS_START) : __RESERVE_NS_RAM ? ABSOLUTE(FLASH_START + FLASH_LENGTH) : FLASH_LENGTH < 32768 ? FLASH_LENGTH : ALIGN(32768); + FLASH_NS_IMAGE_START = DEFINED(FLASH_NS_IMAGE_START) ? FLASH_NS_IMAGE_START : __tz_FLASH_N; + + /* Note: There are no secure/non-secure boundaries for QSPI. These symbols are provided for the RA configuration tool. */ + __tz_QSPI_FLASH_S = ORIGIN(QSPI_FLASH); + + /* QSPI_FLASH section to be downloaded via debugger */ + .qspi_flash : + { + __qspi_flash_start__ = .; + KEEP(*(.qspi_flash*)) + KEEP(*(.code_in_qspi*)) + __qspi_flash_end__ = .; + } > QSPI_FLASH + __qspi_flash_code_size__ = __qspi_flash_end__ - __qspi_flash_start__; + + /* QSPI_FLASH non-retentive section, creates a copy in internal flash that can be copied to QSPI */ + __qspi_flash_code_addr__ = sgstubs_pre_location; + .qspi_non_retentive : AT(__qspi_flash_code_addr__) + { + __qspi_non_retentive_start__ = .; + KEEP(*(.qspi_non_retentive*)) + __qspi_non_retentive_end__ = .; + } > QSPI_FLASH + __qspi_non_retentive_size__ = __qspi_non_retentive_end__ - __qspi_non_retentive_start__; + + __qspi_region_max_size__ = 0x4000000; /* Must be the same as defined in MEMORY above */ + __qspi_region_start_address__ = __qspi_flash_start__; + __qspi_region_end_address__ = __qspi_flash_start__ + __qspi_region_max_size__; + + /* Note: There are no secure/non-secure boundaries for QSPI. These symbols are provided for the RA configuration tool. */ + __tz_QSPI_FLASH_N = __qspi_non_retentive_end__; + + /* Support for OctaRAM */ + .OSPI_DEVICE_0_NO_LOAD (NOLOAD): + { + . = ALIGN(4); + __ospi_device_0_start__ = .; + *(.ospi_device_0_no_load*) + . = ALIGN(4); + __ospi_device_0_end__ = .; + } > OSPI_DEVICE_0_RAM + + .OSPI_DEVICE_1_NO_LOAD (NOLOAD): + { + . = ALIGN(4); + __ospi_device_1_start__ = .; + *(.ospi_device_1_no_load*) + . = ALIGN(4); + __ospi_device_1_end__ = .; + } > OSPI_DEVICE_1_RAM + + /* Note: There are no secure/non-secure boundaries for QSPI. These symbols are provided for the RA configuration tool. */ + __tz_OSPI_DEVICE_0_S = ORIGIN(OSPI_DEVICE_0); + + /* OSPI_DEVICE_0 section to be downloaded via debugger */ + .OSPI_DEVICE_0 : + { + __ospi_device_0_start__ = .; + KEEP(*(.ospi_device_0*)) + KEEP(*(.code_in_ospi_device_0*)) + __ospi_device_0_end__ = .; + } > OSPI_DEVICE_0 + __ospi_device_0_code_size__ = __ospi_device_0_end__ - __ospi_device_0_start__; + + /* OSPI_DEVICE_0 non-retentive section, creates a copy in internal flash that can be copied to OSPI */ + __ospi_device_0_code_addr__ = sgstubs_pre_location + (SIZEOF(.qspi_non_retentive)); + .ospi_device_0_non_retentive : AT(__ospi_device_0_code_addr__) + { + __ospi_device_0_non_retentive_start__ = .; + KEEP(*(.ospi_device_0_non_retentive*)) + __ospi_device_0_non_retentive_end__ = .; + } > OSPI_DEVICE_0 + __ospi_device_0_non_retentive_size__ = __ospi_device_0_non_retentive_end__ - __ospi_device_0_non_retentive_start__; + + __ospi_device_0_region_max_size__ = 0x8000000; /* Must be the same as defined in MEMORY above */ + __ospi_device_0_region_start_address__ = __ospi_device_0_start__; + __ospi_device_0_region_end_address__ = __ospi_device_0_start__ + __ospi_device_0_region_max_size__; + + /* Note: There are no secure/non-secure boundaries for OSPI. These symbols are provided for the RA configuration tool. */ + __tz_OSPI_DEVICE_0_N = __ospi_device_0_non_retentive_end__; + + /* Note: There are no secure/non-secure boundaries for OSPI. These symbols are provided for the RA configuration tool. */ + __tz_OSPI_DEVICE_1_S = ORIGIN(OSPI_DEVICE_1); + + /* OSPI_DEVICE_1 section to be downloaded via debugger */ + .OSPI_DEVICE_1 : + { + __ospi_device_1_start__ = .; + KEEP(*(.ospi_device_1*)) + KEEP(*(.code_in_ospi_device_1*)) + __ospi_device_1_end__ = .; + } > OSPI_DEVICE_1 + __ospi_device_1_code_size__ = __ospi_device_1_end__ - __ospi_device_1_start__; + + /* OSPI_DEVICE_1 non-retentive section, creates a copy in internal flash that can be copied to OSPI */ + __ospi_device_1_code_addr__ = sgstubs_pre_location + (SIZEOF(.qspi_non_retentive) + SIZEOF(.ospi_device_0_non_retentive)); + .ospi_device_1_non_retentive : AT(__ospi_device_1_code_addr__) + { + __ospi_device_1_non_retentive_start__ = .; + KEEP(*(.ospi_device_1_non_retentive*)) + __ospi_device_1_non_retentive_end__ = .; + } > OSPI_DEVICE_1 + __ospi_device_1_non_retentive_size__ = __ospi_device_1_non_retentive_end__ - __ospi_device_1_non_retentive_start__; + + __ospi_device_1_region_max_size__ = 0x10000000; /* Must be the same as defined in MEMORY above */ + __ospi_device_1_region_start_address__ = __ospi_device_1_start__; + __ospi_device_1_region_end_address__ = __ospi_device_1_start__ + __ospi_device_1_region_max_size__; + + /* Note: There are no secure/non-secure boundaries for OSPI. These symbols are provided for the RA configuration tool. */ + __tz_OSPI_DEVICE_1_N = __ospi_device_1_non_retentive_end__; + + .noinit (NOLOAD): + { + . = ALIGN(4); + __noinit_start = .; + KEEP(*(.noinit*)) + . = ALIGN(8); + /* Place the FreeRTOS heap here so that the __HeapLimit calculation does not include the freertos heap. */ + KEEP(*(.heap.*)) + __noinit_end = .; + } > RAM + + . = .; + __nocache_pre_location = .; + .nocache ALIGN(32) (NOLOAD): + { + __nocache_start = .; + + KEEP(*(.nocache)) + + . = ALIGN(32); + __nocache_end = .; + } > RAM + . = (SIZEOF(.nocache) > 0) ? __nocache_end : __nocache_pre_location; + + .bss : + { + . = ALIGN(4); + __bss_start__ = .; + *(.bss*) + *(COMMON) + . = ALIGN(4); + __bss_end__ = .; + } > RAM + + .heap (NOLOAD): + { + . = ALIGN(8); + __HeapBase = .; + /* Place the STD heap here. */ + KEEP(*(.heap)) + __HeapLimit = .; + } > RAM + + /* Stacks are stored in this section. */ + .stack_dummy (NOLOAD): + { + . = ALIGN(8); + __StackLimit = .; + /* Main stack */ + KEEP(*(.stack)) + __StackTop = .; + /* Thread stacks */ + KEEP(*(.stack*)) + __StackTopAll = .; + } > RAM + + PROVIDE(__stack = __StackTopAll); + + /* This symbol represents the end of user allocated RAM. The RAM after this symbol can be used + at run time for things such as ThreadX memory pool allocations. */ + __RAM_segment_used_end__ = ALIGN(__StackTopAll , 4); + + /* RAM_NSC_START can be used to set a fixed address for non-secure callable RAM in secure projects. + * If it is not specified, the address for NSC RAM is the end of RAM aligned to a 1K boundary. + * In flat projects that require non-secure RAM, this variable is set to the start of non-secure RAM. */ + __RAM_NSC_START = DEFINED(RAM_NSC_START) ? ABSOLUTE(RAM_NSC_START - RAM_NS_BUFFER_BLOCK_LENGTH) : __RESERVE_NS_RAM ? ABSOLUTE(RAM_NS_BUFFER_BLOCK_START) : ALIGN(__RAM_segment_used_end__, 1024); + + /* RAM_NS_START can be used to set a fixed address for non-secure RAM in secure projects or flat projects. + * RAM_NS_BUFFER_BLOCK_LENGTH is used to allocate non-secure buffers in a flat project. If it is not + * specified, the address for NSC RAM is the end of RAM aligned to an 8K boundary. + * In flat projects that require non-secure RAM, this variable is set to the start of non-secure RAM. */ + __tz_RAM_N = DEFINED(FLASH_BOOTLOADER_LENGTH) ? (RAM_START + RAM_LENGTH - RAM_APPLICATION_NS_LENGTH) : DEFINED(RAM_NS_START) ? ABSOLUTE(RAM_NS_START - RAM_NS_BUFFER_BLOCK_LENGTH) : __RESERVE_NS_RAM ? ABSOLUTE(RAM_NS_BUFFER_BLOCK_START) : ALIGN(__RAM_NSC_START, 8192); + + /* Non-secure buffers must be in non-secure RAM. This is primarily used for the EDMAC in flat projects. + * The EDMAC is a non-secure bus master and can only access non-secure RAM. */ + .ns_buffer (NOLOAD): + { + /* Allocate RAM on a 32-byte boundary to help with placement of Ethernet buffers. */ + . = __RESERVE_NS_RAM ? ABSOLUTE(RAM_NS_BUFFER_START & 0xFFFFFFE0) : .; + + KEEP(*(.ns_buffer*)) + } > RAM + + /* Data flash. */ + .data_flash : + { + . = ORIGIN(DATA_FLASH); + __tz_DATA_FLASH_S = .; + __Data_Flash_Start = .; + KEEP(*(.data_flash*)) + __Data_Flash_End = .; + + __tz_DATA_FLASH_N = DEFINED(DATA_FLASH_NS_START) ? ABSOLUTE(DATA_FLASH_NS_START) : __RESERVE_NS_RAM ? ABSOLUTE(DATA_FLASH_START + DATA_FLASH_LENGTH) : ALIGN(1024); + } > DATA_FLASH + + /* Note: There are no secure/non-secure boundaries for SDRAM. These symbols are provided for the RA configuration tool. */ + __tz_SDRAM_S = ORIGIN(SDRAM); + + /* SDRAM */ + .sdram (NOLOAD): + { + __SDRAM_Start = .; + KEEP(*(.sdram*)) + KEEP(*(.frame*)) + __SDRAM_End = .; + } > SDRAM + + . = .; + __nocache_sdram_pre_location = .; + .nocache_sdram ALIGN(32) (NOLOAD): + { + __nocache_sdram_start = .; + + KEEP(*(.nocache_sdram)) + + . = ALIGN(32); + __nocache_sdram_end = .; + } > SDRAM + . = (SIZEOF(.nocache_sdram) > 0) ? __nocache_sdram_end : __nocache_sdram_pre_location; + + /* Note: There are no secure/non-secure boundaries for SDRAM. These symbols are provided for the RA configuration tool. */ + __tz_SDRAM_N = __SDRAM_End; + + /* Note: There are no secure/non-secure boundaries for ID_CODE. These symbols are provided for the RA configuration tool. */ + __tz_ID_CODE_S = ORIGIN(ID_CODE); + + /* Note: There are no secure/non-secure boundaries for ID_CODE. These symbols are provided for the RA configuration tool. + * Set this symbol to the same value as __tz_ID_CODE_S so the RA configuration tool does not split the ID_CODE + * memory region between TrustZone projects. */ + __tz_ID_CODE_N = __tz_ID_CODE_S; + + .id_code : + { + __ID_Code_Start = .; + KEEP(*(.id_code*)) + __ID_Code_End = .; + } > ID_CODE + + /* Symbol required for RA Configuration tool. */ + __tz_OPTION_SETTING_S = ORIGIN(OPTION_SETTING_OFS); + + .option_setting_ofs : + { + __OPTION_SETTING_OFS_Start = .; + KEEP(*(.option_setting_ofs0)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_OFS_Start + 0x04 : __OPTION_SETTING_OFS_Start; + KEEP(*(.option_setting_ofs2)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_OFS_Start + 0x10 : __OPTION_SETTING_OFS_Start; + KEEP(*(.option_setting_dualsel)) + __OPTION_SETTING_OFS_End = .; + } > OPTION_SETTING_OFS = 0xFF + + .option_setting_sas : + { + __OPTION_SETTING_SAS_Start = .; + KEEP(*(.option_setting_sas)) + __OPTION_SETTING_SAS_End = .; + } > OPTION_SETTING_SAS = 0xFF + + /* Symbol required for RA Configuration tool. */ + __tz_OPTION_SETTING_N = ABSOLUTE(OPTION_SETTING_START_NS); + + .option_setting_ns : + { + __OPTION_SETTING_NS_Start = .; + KEEP(*(.option_setting_ofs1)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x04 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_ofs3)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x10 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_banksel)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x40 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_bps0)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x44 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_bps1)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x48 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_bps2)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x4C : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_bps3)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x60 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_pbps0)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x64 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_pbps1)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x68 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_pbps2)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x6C : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_pbps3)) + __OPTION_SETTING_NS_End = .; + } > OPTION_SETTING = 0xFF + + /* Symbol required for RA Configuration tool. */ + __tz_OPTION_SETTING_S_S = ORIGIN(OPTION_SETTING_S); + + .option_setting_s : + { + __OPTION_SETTING_S_Start = .; + KEEP(*(.option_setting_ofs1_sec)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x04 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_ofs3_sec)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x10 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_banksel_sec)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x40 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sec0)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x44 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sec1)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x48 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sec2)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x4C : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sec3)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x60 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_pbps_sec0)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x64 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_pbps_sec1)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x68 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_pbps_sec2)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x6C : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_pbps_sec3)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x80 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_ofs1_sel)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x84 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_ofs3_sel)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x90 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_banksel_sel)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0xC0 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sel0)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0xC4 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sel1)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0xC8 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sel2)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0xCC : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sel3)) + __OPTION_SETTING_S_End = .; + } > OPTION_SETTING_S = 0xFF + + /* Symbol required for RA Configuration tool. */ + __tz_OPTION_SETTING_S_N = __OPTION_SETTING_S_End; + /* Symbol required for RA Configuration tool. */ + __tz_OPTION_SETTING_DATA_FLASH_S_S = ORIGIN(OPTION_SETTING_DATA_FLASH_S); + + .option_setting_data_flash_s : + { + __OPTION_SETTING_DATA_FLASH_S_Start = .; + KEEP(*(.option_setting_data_flash_fsblctrl0)) + . = USE_OPTION_SETTING_DATA_FLASH ? __OPTION_SETTING_DATA_FLASH_S_Start + 0x04 : __OPTION_SETTING_DATA_FLASH_S_Start; + KEEP(*(.option_setting_data_flash_fsblctrl1)) + . = USE_OPTION_SETTING_DATA_FLASH ? __OPTION_SETTING_DATA_FLASH_S_Start + 0x08 : __OPTION_SETTING_DATA_FLASH_S_Start; + KEEP(*(.option_setting_data_flash_fsblctrl2)) + . = USE_OPTION_SETTING_DATA_FLASH ? __OPTION_SETTING_DATA_FLASH_S_Start + 0x0C : __OPTION_SETTING_DATA_FLASH_S_Start; + KEEP(*(.option_setting_data_flash_sacc0)) + . = USE_OPTION_SETTING_DATA_FLASH ? __OPTION_SETTING_DATA_FLASH_S_Start + 0x10 : __OPTION_SETTING_DATA_FLASH_S_Start; + KEEP(*(.option_setting_data_flash_sacc1)) + . = USE_OPTION_SETTING_DATA_FLASH ? __OPTION_SETTING_DATA_FLASH_S_Start + 0x14 : __OPTION_SETTING_DATA_FLASH_S_Start; + KEEP(*(.option_setting_data_flash_samr)) + . = USE_OPTION_SETTING_DATA_FLASH ? __OPTION_SETTING_DATA_FLASH_S_Start + 0x2E0 : __OPTION_SETTING_DATA_FLASH_S_Start; + KEEP(*(.option_setting_data_flash_hoemrtpk)) + __OPTION_SETTING_DATA_FLASH_S_End = .; + } > OPTION_SETTING_DATA_FLASH_S = 0xFF + + /* Symbol required for RA Configuration tool. */ + __tz_OPTION_SETTING_DATA_FLASH_S_N = __OPTION_SETTING_DATA_FLASH_S_End; +} diff --git a/hw/bsp/ra/boards/ra8m1_ek/script/memory_regions.ld b/hw/bsp/ra/boards/ra8m1_ek/script/memory_regions.ld new file mode 100644 index 000000000..2bc162511 --- /dev/null +++ b/hw/bsp/ra/boards/ra8m1_ek/script/memory_regions.ld @@ -0,0 +1,30 @@ + + /* generated memory regions file - do not edit */ + RAM_START = 0x22000000; + RAM_LENGTH = 0xE0000; + FLASH_START = 0x02000000; + FLASH_LENGTH = 0x1F8000; + DATA_FLASH_START = 0x27000000; + DATA_FLASH_LENGTH = 0x3000; + OPTION_SETTING_START = 0x0300A100; + OPTION_SETTING_LENGTH = 0x100; + OPTION_SETTING_S_START = 0x0300A200; + OPTION_SETTING_S_LENGTH = 0x100; + OPTION_SETTING_DATA_FLASH_S_START = 0x27030080; + OPTION_SETTING_DATA_FLASH_S_LENGTH = 0x800; + ID_CODE_START = 0x00000000; + ID_CODE_LENGTH = 0x0; + SDRAM_START = 0x68000000; + SDRAM_LENGTH = 0x8000000; + QSPI_FLASH_START = 0x60000000; + QSPI_FLASH_LENGTH = 0x0; + OSPI_DEVICE_0_START = 0x80000000; + OSPI_DEVICE_0_LENGTH = 0x10000000; + OSPI_DEVICE_1_START = 0x90000000; + OSPI_DEVICE_1_LENGTH = 0x10000000; + ITCM_START = 0x00000000; + ITCM_LENGTH = 0x10000; + DTCM_START = 0x20000000; + DTCM_LENGTH = 0x10000; + NS_OFFSET_START = 0x10000000; + NS_OFFSET_LENGTH = 0x0; diff --git a/hw/bsp/ra/boards/ra8m1_ek/smart_configurator/configuration.xml b/hw/bsp/ra/boards/ra8m1_ek/smart_configurator/configuration.xml new file mode 100644 index 000000000..0f83b4a11 --- /dev/null +++ b/hw/bsp/ra/boards/ra8m1_ek/smart_configurator/configuration.xml @@ -0,0 +1,680 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Simple application that blinks an LED. No RTOS included. + Renesas.RA_baremetal_blinky.5.6.0.pack + + + Board Support Package Common Files + Renesas.RA.5.6.0.pack + + + I/O Port + Renesas.RA.5.6.0.pack + + + Arm CMSIS Version 6 - Core (M) + Arm.CMSIS6.6.1.0+fsp.5.6.0.pack + + + RA8M1-EK Board Support Files + Renesas.RA_board_ra8m1_ek.5.6.0.pack + + + Board support package for R7FA8M1AHECBD + Renesas.RA_mcu_ra8m1.5.6.0.pack + + + Board support package for RA8M1 + Renesas.RA_mcu_ra8m1.5.6.0.pack + + + Board support package for RA8M1 - FSP Data + Renesas.RA_mcu_ra8m1.5.6.0.pack + + + Board support package for RA8M1 - Events + Renesas.RA_mcu_ra8m1.5.6.0.pack + + + USB Basic + Renesas.RA.5.6.0.pack + + + USB Peripheral Communications Device Class + Renesas.RA.5.6.0.pack + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/hw/bsp/ra/boards/uno_r4/board.cmake b/hw/bsp/ra/boards/uno_r4/board.cmake index 9d59bc4f7..735a93035 100644 --- a/hw/bsp/ra/boards/uno_r4/board.cmake +++ b/hw/bsp/ra/boards/uno_r4/board.cmake @@ -1,13 +1,9 @@ -set(CMAKE_SYSTEM_PROCESSOR cortex-m4 CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU cortex-m4 CACHE INTERNAL "System Processor") set(MCU_VARIANT ra4m1) - set(JLINK_DEVICE R7FA4M1AB) -set(LD_FILE_GNU ${CMAKE_CURRENT_LIST_DIR}/${BOARD}.ld) function(update_board TARGET) target_compile_definitions(${TARGET} PUBLIC CFG_EXAMPLE_VIDEO_READONLY ) -# target_sources(${TARGET} PRIVATE) -# target_include_directories(${BOARD_TARGET} PUBLIC) endfunction() diff --git a/hw/bsp/ra/boards/uno_r4/board.h b/hw/bsp/ra/boards/uno_r4/board.h index 72abda27f..4e7ebb5ce 100644 --- a/hw/bsp/ra/boards/uno_r4/board.h +++ b/hw/bsp/ra/boards/uno_r4/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Arduino UNO R4 + url: https://store-usa.arduino.cc/pages/uno-r4 +*/ + #ifndef _BOARD_H_ #define _BOARD_H_ @@ -31,20 +36,8 @@ extern "C" { #endif -#define LED1 BSP_IO_PORT_01_PIN_11 // D13 -#define LED_STATE_ON 1 - -#define SW1 BSP_IO_PORT_01_PIN_10 // D12 -#define BUTTON_STATE_ACTIVE 0 - -static const ioport_pin_cfg_t board_pin_cfg[] = { - {.pin = LED1, .pin_cfg = IOPORT_CFG_PORT_DIRECTION_OUTPUT}, - {.pin = SW1, .pin_cfg = IOPORT_CFG_PORT_DIRECTION_INPUT}, - // USB FS D+, D-, VBus - {.pin = BSP_IO_PORT_04_PIN_07, .pin_cfg = IOPORT_CFG_PERIPHERAL_PIN | IOPORT_PERIPHERAL_USB_FS}, - {.pin = BSP_IO_PORT_09_PIN_14, .pin_cfg = IOPORT_CFG_PERIPHERAL_PIN | IOPORT_PERIPHERAL_USB_FS}, - {.pin = BSP_IO_PORT_09_PIN_15, .pin_cfg = IOPORT_CFG_PERIPHERAL_PIN | IOPORT_PERIPHERAL_USB_FS}, -}; +#define LED_STATE_ON 1 +#define BUTTON_STATE_ACTIVE 0 #ifdef __cplusplus } diff --git a/hw/bsp/ra/boards/uno_r4/board.mk b/hw/bsp/ra/boards/uno_r4/board.mk index b7075eec0..f257c0000 100644 --- a/hw/bsp/ra/boards/uno_r4/board.mk +++ b/hw/bsp/ra/boards/uno_r4/board.mk @@ -1,8 +1,6 @@ CPU_CORE = cortex-m4 MCU_VARIANT = ra4m1 -LD_FILE = ${BOARD_PATH}/${BOARD}.ld - # For flash-jlink target JLINK_DEVICE = R7FA4M1AB diff --git a/hw/bsp/ra/boards/uno_r4/fsp_cfg/bsp/bsp_cfg.h b/hw/bsp/ra/boards/uno_r4/fsp_cfg/bsp/bsp_cfg.h deleted file mode 100644 index c1d1022cc..000000000 --- a/hw/bsp/ra/boards/uno_r4/fsp_cfg/bsp/bsp_cfg.h +++ /dev/null @@ -1,35 +0,0 @@ -/* generated configuration header file - do not edit */ -#ifndef BSP_CFG_H_ -#define BSP_CFG_H_ - -#include "bsp_clock_cfg.h" -#include "bsp_mcu_family_cfg.h" -#include "board_cfg.h" - -#undef RA_NOT_DEFINED -#define BSP_CFG_RTOS (0) -#if defined(_RA_BOOT_IMAGE) -#define BSP_CFG_BOOT_IMAGE (1) -#endif -#define BSP_CFG_MCU_VCC_MV (3300) -#define BSP_CFG_STACK_MAIN_BYTES (0x800) -#define BSP_CFG_HEAP_BYTES (0x1000) -#define BSP_CFG_PARAM_CHECKING_ENABLE (1) -#define BSP_CFG_ASSERT (0) -#define BSP_CFG_ERROR_LOG (0) - -#define BSP_CFG_PFS_PROTECT ((1)) - -#define BSP_CFG_C_RUNTIME_INIT ((1)) -#define BSP_CFG_EARLY_INIT ((0)) - -#define BSP_CFG_STARTUP_CLOCK_REG_NOT_RESET ((0)) - -#define BSP_CLOCK_CFG_MAIN_OSC_POPULATED (0) - -#define BSP_CLOCK_CFG_MAIN_OSC_CLOCK_SOURCE (0) -#define BSP_CLOCK_CFG_SUBCLOCK_DRIVE (0) -#define BSP_CLOCK_CFG_SUBCLOCK_POPULATED (0) -#define BSP_CLOCK_CFG_SUBCLOCK_STABILIZATION_MS 1000 - -#endif /* BSP_CFG_H_ */ diff --git a/hw/bsp/ra/boards/uno_r4/fsp_cfg/bsp/bsp_mcu_device_pn_cfg.h b/hw/bsp/ra/boards/uno_r4/fsp_cfg/bsp/bsp_mcu_device_pn_cfg.h deleted file mode 100644 index 336918800..000000000 --- a/hw/bsp/ra/boards/uno_r4/fsp_cfg/bsp/bsp_mcu_device_pn_cfg.h +++ /dev/null @@ -1,11 +0,0 @@ -/* generated configuration header file - do not edit */ -#ifndef BSP_MCU_DEVICE_PN_CFG_H_ -#define BSP_MCU_DEVICE_PN_CFG_H_ -#define BSP_MCU_R7FA4M1AB3CNE -#define BSP_MCU_FEATURE_SET ('A') -#define BSP_ROM_SIZE_BYTES (262144) -#define BSP_RAM_SIZE_BYTES (32768) -#define BSP_DATA_FLASH_SIZE_BYTES (8192) -#define BSP_PACKAGE_QFN -#define BSP_PACKAGE_PINS (48) -#endif /* BSP_MCU_DEVICE_PN_CFG_H_ */ diff --git a/hw/bsp/ra/boards/uno_r4/fsp_cfg/bsp/bsp_mcu_family_cfg.h b/hw/bsp/ra/boards/uno_r4/fsp_cfg/bsp/bsp_mcu_family_cfg.h deleted file mode 100644 index fc604eb3b..000000000 --- a/hw/bsp/ra/boards/uno_r4/fsp_cfg/bsp/bsp_mcu_family_cfg.h +++ /dev/null @@ -1,87 +0,0 @@ -/* generated configuration header file through renesas e2 studio */ -#ifndef BSP_MCU_FAMILY_CFG_H_ -#define BSP_MCU_FAMILY_CFG_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "bsp_mcu_device_pn_cfg.h" -#include "bsp_mcu_device_cfg.h" -#include "bsp_mcu_info.h" -#include "bsp_clock_cfg.h" - -#define BSP_MCU_GROUP_RA4M1 (1) -#define BSP_LOCO_HZ (32768) -#define BSP_MOCO_HZ (8000000) -#define BSP_SUB_CLOCK_HZ (32768) -#if BSP_CFG_HOCO_FREQUENCY == 0 - #define BSP_HOCO_HZ (24000000) -#elif BSP_CFG_HOCO_FREQUENCY == 2 - #define BSP_HOCO_HZ (32000000) -#elif BSP_CFG_HOCO_FREQUENCY == 4 - #define BSP_HOCO_HZ (48000000) -#elif BSP_CFG_HOCO_FREQUENCY == 5 - #define BSP_HOCO_HZ (64000000) -#else - #error "Invalid HOCO frequency chosen (BSP_CFG_HOCO_FREQUENCY) in bsp_clock_cfg.h" -#endif -#define BSP_CORTEX_VECTOR_TABLE_ENTRIES (16U) -#define BSP_VECTOR_TABLE_MAX_ENTRIES (48U) -#define BSP_MCU_VBATT_SUPPORT (1) - -#define OFS_SEQ1 0xA001A001 | (1 << 1) | (3 << 2) -#define OFS_SEQ2 (15 << 4) | (3 << 8) | (3 << 10) -#define OFS_SEQ3 (1 << 12) | (1 << 14) | (1 << 17) -#define OFS_SEQ4 (3 << 18) |(15 << 20) | (3 << 24) | (3 << 26) -#define OFS_SEQ5 (1 << 28) | (1 << 30) -#define BSP_CFG_ROM_REG_OFS0 (OFS_SEQ1 | OFS_SEQ2 | OFS_SEQ3 | OFS_SEQ4 | OFS_SEQ5) -#define BSP_CFG_ROM_REG_OFS1 (0xFFFFFEC3 | (1 << 2) | (3 << 3) | (0 << 8)) -#define BSP_CFG_USE_LOW_VOLTAGE_MODE ((0)) -#define BSP_CFG_ROM_REG_MPU_PC0_ENABLE (1) -#define BSP_CFG_ROM_REG_MPU_PC0_START (0x00FFFFFC) -#define BSP_CFG_ROM_REG_MPU_PC0_END (0x00FFFFFF) -#define BSP_CFG_ROM_REG_MPU_PC1_ENABLE (1) -#define BSP_CFG_ROM_REG_MPU_PC1_START (0x00FFFFFC) -#define BSP_CFG_ROM_REG_MPU_PC1_END (0x00FFFFFF) -#define BSP_CFG_ROM_REG_MPU_REGION0_ENABLE (1) -#define BSP_CFG_ROM_REG_MPU_REGION0_START (0x00FFFFFC) -#define BSP_CFG_ROM_REG_MPU_REGION0_END (0x00FFFFFF) -#define BSP_CFG_ROM_REG_MPU_REGION1_ENABLE (1) -#define BSP_CFG_ROM_REG_MPU_REGION1_START (0x200FFFFC) -#define BSP_CFG_ROM_REG_MPU_REGION1_END (0x200FFFFF) -#define BSP_CFG_ROM_REG_MPU_REGION2_ENABLE (1) -#define BSP_CFG_ROM_REG_MPU_REGION2_START (0x407FFFFC) -#define BSP_CFG_ROM_REG_MPU_REGION2_END (0x407FFFFF) -#define BSP_CFG_ROM_REG_MPU_REGION3_ENABLE (1) -#define BSP_CFG_ROM_REG_MPU_REGION3_START (0x400DFFFC) -#define BSP_CFG_ROM_REG_MPU_REGION3_END (0x400DFFFF) -#ifndef BSP_CLOCK_CFG_MAIN_OSC_WAIT -#define BSP_CLOCK_CFG_MAIN_OSC_WAIT (9) -#endif -/* Used to create IELS values for the interrupt initialization table g_interrupt_event_link_select. */ -#define BSP_PRV_IELS_ENUM(vector) (ELC_ ## vector) - -/* - ID Code - Note: To permanently lock and disable the debug interface define the BSP_ID_CODE_PERMANENTLY_LOCKED in the compiler settings. - WARNING: This will disable debug access to the part and cannot be reversed by a debug probe. - */ -#if defined(BSP_ID_CODE_PERMANENTLY_LOCKED) - #define BSP_CFG_ID_CODE_LONG_1 (0x00000000) - #define BSP_CFG_ID_CODE_LONG_2 (0x00000000) - #define BSP_CFG_ID_CODE_LONG_3 (0x00000000) - #define BSP_CFG_ID_CODE_LONG_4 (0x00000000) - #else -/* ID CODE: FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF */ -#define BSP_CFG_ID_CODE_LONG_1 (0xFFFFFFFF) -#define BSP_CFG_ID_CODE_LONG_2 (0xFFFFFFFF) -#define BSP_CFG_ID_CODE_LONG_3 (0xFFFFFFFF) -#define BSP_CFG_ID_CODE_LONG_4 (0xffFFFFFF) -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* BSP_MCU_FAMILY_CFG_H_ */ diff --git a/hw/bsp/ra/boards/uno_r4/ra_cfg/fsp_cfg/bsp/bsp_cfg.h b/hw/bsp/ra/boards/uno_r4/ra_cfg/fsp_cfg/bsp/bsp_cfg.h new file mode 100644 index 000000000..4eef62a0e --- /dev/null +++ b/hw/bsp/ra/boards/uno_r4/ra_cfg/fsp_cfg/bsp/bsp_cfg.h @@ -0,0 +1,62 @@ +/* generated configuration header file - do not edit */ +#ifndef BSP_CFG_H_ +#define BSP_CFG_H_ +#ifdef __cplusplus + extern "C" { + #endif + + #include "bsp_clock_cfg.h" + #include "bsp_mcu_family_cfg.h" + #include "board_cfg.h" + #define RA_NOT_DEFINED 0 + #ifndef BSP_CFG_RTOS + #if (RA_NOT_DEFINED) != (RA_NOT_DEFINED) + #define BSP_CFG_RTOS (2) + #elif (RA_NOT_DEFINED) != (RA_NOT_DEFINED) + #define BSP_CFG_RTOS (1) + #else + #define BSP_CFG_RTOS (0) + #endif + #endif + #ifndef BSP_CFG_RTC_USED + #define BSP_CFG_RTC_USED (RA_NOT_DEFINED) + #endif + #undef RA_NOT_DEFINED + #if defined(_RA_BOOT_IMAGE) + #define BSP_CFG_BOOT_IMAGE (1) + #endif + #define BSP_CFG_MCU_VCC_MV (3300) + #define BSP_CFG_STACK_MAIN_BYTES (0x800) + #define BSP_CFG_HEAP_BYTES (0x1000) + #define BSP_CFG_PARAM_CHECKING_ENABLE (0) + #define BSP_CFG_ASSERT (0) + #define BSP_CFG_ERROR_LOG (0) + + #define BSP_CFG_PFS_PROTECT ((1)) + + #define BSP_CFG_C_RUNTIME_INIT ((1)) + #define BSP_CFG_EARLY_INIT ((0)) + + #define BSP_CFG_STARTUP_CLOCK_REG_NOT_RESET ((0)) + + #ifndef BSP_CLOCK_CFG_MAIN_OSC_POPULATED + #define BSP_CLOCK_CFG_MAIN_OSC_POPULATED (0) + #endif + + #ifndef BSP_CLOCK_CFG_MAIN_OSC_CLOCK_SOURCE + #define BSP_CLOCK_CFG_MAIN_OSC_CLOCK_SOURCE (0) + #endif + #ifndef BSP_CLOCK_CFG_SUBCLOCK_DRIVE + #define BSP_CLOCK_CFG_SUBCLOCK_DRIVE (0) + #endif + #ifndef BSP_CLOCK_CFG_SUBCLOCK_POPULATED + #define BSP_CLOCK_CFG_SUBCLOCK_POPULATED (0) + #endif + #ifndef BSP_CLOCK_CFG_SUBCLOCK_STABILIZATION_MS + #define BSP_CLOCK_CFG_SUBCLOCK_STABILIZATION_MS 1000 + #endif + + #ifdef __cplusplus + } + #endif +#endif /* BSP_CFG_H_ */ diff --git a/hw/bsp/ra/boards/uno_r4/fsp_cfg/bsp/bsp_mcu_device_cfg.h b/hw/bsp/ra/boards/uno_r4/ra_cfg/fsp_cfg/bsp/bsp_mcu_device_cfg.h similarity index 100% rename from hw/bsp/ra/boards/uno_r4/fsp_cfg/bsp/bsp_mcu_device_cfg.h rename to hw/bsp/ra/boards/uno_r4/ra_cfg/fsp_cfg/bsp/bsp_mcu_device_cfg.h diff --git a/hw/bsp/ra/boards/uno_r4/ra_cfg/fsp_cfg/bsp/bsp_mcu_device_pn_cfg.h b/hw/bsp/ra/boards/uno_r4/ra_cfg/fsp_cfg/bsp/bsp_mcu_device_pn_cfg.h new file mode 100644 index 000000000..3f1d02b0d --- /dev/null +++ b/hw/bsp/ra/boards/uno_r4/ra_cfg/fsp_cfg/bsp/bsp_mcu_device_pn_cfg.h @@ -0,0 +1,11 @@ +/* generated configuration header file - do not edit */ +#ifndef BSP_MCU_DEVICE_PN_CFG_H_ +#define BSP_MCU_DEVICE_PN_CFG_H_ +#define BSP_MCU_R7FA4M1AB3CNE + #define BSP_MCU_FEATURE_SET ('A') + #define BSP_ROM_SIZE_BYTES (262144) + #define BSP_RAM_SIZE_BYTES (32768) + #define BSP_DATA_FLASH_SIZE_BYTES (8192) + #define BSP_PACKAGE_QFN + #define BSP_PACKAGE_PINS (48) +#endif /* BSP_MCU_DEVICE_PN_CFG_H_ */ diff --git a/hw/bsp/ra/boards/uno_r4/ra_cfg/fsp_cfg/bsp/bsp_mcu_family_cfg.h b/hw/bsp/ra/boards/uno_r4/ra_cfg/fsp_cfg/bsp/bsp_mcu_family_cfg.h new file mode 100644 index 000000000..3d482b2b6 --- /dev/null +++ b/hw/bsp/ra/boards/uno_r4/ra_cfg/fsp_cfg/bsp/bsp_mcu_family_cfg.h @@ -0,0 +1,84 @@ +/* generated configuration header file - do not edit */ +#ifndef BSP_MCU_FAMILY_CFG_H_ +#define BSP_MCU_FAMILY_CFG_H_ +#ifdef __cplusplus + extern "C" { + #endif + + #include "bsp_mcu_device_pn_cfg.h" + #include "bsp_mcu_device_cfg.h" + #include "../../../ra/fsp/src/bsp/mcu/ra4m1/bsp_mcu_info.h" + #include "bsp_clock_cfg.h" + #define BSP_MCU_GROUP_RA4M1 (1) + #define BSP_LOCO_HZ (32768) + #define BSP_MOCO_HZ (8000000) + #define BSP_SUB_CLOCK_HZ (32768) + #if BSP_CFG_HOCO_FREQUENCY == 0 + #define BSP_HOCO_HZ (24000000) + #elif BSP_CFG_HOCO_FREQUENCY == 2 + #define BSP_HOCO_HZ (32000000) + #elif BSP_CFG_HOCO_FREQUENCY == 4 + #define BSP_HOCO_HZ (48000000) + #elif BSP_CFG_HOCO_FREQUENCY == 5 + #define BSP_HOCO_HZ (64000000) + #else + #error "Invalid HOCO frequency chosen (BSP_CFG_HOCO_FREQUENCY) in bsp_clock_cfg.h" + #endif + #define BSP_CORTEX_VECTOR_TABLE_ENTRIES (16U) + #define BSP_VECTOR_TABLE_MAX_ENTRIES (48U) + #define BSP_CFG_INLINE_IRQ_FUNCTIONS (1) + + #define OFS_SEQ1 0xA001A001 | (1 << 1) | (3 << 2) + #define OFS_SEQ2 (15 << 4) | (3 << 8) | (3 << 10) + #define OFS_SEQ3 (1 << 12) | (1 << 14) | (1 << 17) + #define OFS_SEQ4 (3 << 18) |(15 << 20) | (3 << 24) | (3 << 26) + #define OFS_SEQ5 (1 << 28) | (1 << 30) + #define BSP_CFG_ROM_REG_OFS0 (OFS_SEQ1 | OFS_SEQ2 | OFS_SEQ3 | OFS_SEQ4 | OFS_SEQ5) + #define BSP_CFG_ROM_REG_OFS1 (0xFFFFFEC3 | (1 << 2) | (3 << 3) | (0 << 8)) + #define BSP_CFG_USE_LOW_VOLTAGE_MODE ((0)) + #define BSP_CFG_ROM_REG_MPU_PC0_ENABLE (1) + #define BSP_CFG_ROM_REG_MPU_PC0_START (0x00FFFFFC) + #define BSP_CFG_ROM_REG_MPU_PC0_END (0x00FFFFFF) + #define BSP_CFG_ROM_REG_MPU_PC1_ENABLE (1) + #define BSP_CFG_ROM_REG_MPU_PC1_START (0x00FFFFFC) + #define BSP_CFG_ROM_REG_MPU_PC1_END (0x00FFFFFF) + #define BSP_CFG_ROM_REG_MPU_REGION0_ENABLE (1) + #define BSP_CFG_ROM_REG_MPU_REGION0_START (0x00FFFFFC) + #define BSP_CFG_ROM_REG_MPU_REGION0_END (0x00FFFFFF) + #define BSP_CFG_ROM_REG_MPU_REGION1_ENABLE (1) + #define BSP_CFG_ROM_REG_MPU_REGION1_START (0x200FFFFC) + #define BSP_CFG_ROM_REG_MPU_REGION1_END (0x200FFFFF) + #define BSP_CFG_ROM_REG_MPU_REGION2_ENABLE (1) + #define BSP_CFG_ROM_REG_MPU_REGION2_START (0x407FFFFC) + #define BSP_CFG_ROM_REG_MPU_REGION2_END (0x407FFFFF) + #define BSP_CFG_ROM_REG_MPU_REGION3_ENABLE (1) + #define BSP_CFG_ROM_REG_MPU_REGION3_START (0x400DFFFC) + #define BSP_CFG_ROM_REG_MPU_REGION3_END (0x400DFFFF) + #ifndef BSP_CLOCK_CFG_MAIN_OSC_WAIT + #define BSP_CLOCK_CFG_MAIN_OSC_WAIT (9) + #endif + /* Used to create IELS values for the interrupt initialization table g_interrupt_event_link_select. */ + #define BSP_PRV_IELS_ENUM(vector) (ELC_ ## vector) + + /* + ID Code + Note: To permanently lock and disable the debug interface define the BSP_ID_CODE_PERMANENTLY_LOCKED in the compiler settings. + WARNING: This will disable debug access to the part and cannot be reversed by a debug probe. + */ + #if defined(BSP_ID_CODE_PERMANENTLY_LOCKED) + #define BSP_CFG_ID_CODE_LONG_1 (0x00000000) + #define BSP_CFG_ID_CODE_LONG_2 (0x00000000) + #define BSP_CFG_ID_CODE_LONG_3 (0x00000000) + #define BSP_CFG_ID_CODE_LONG_4 (0x00000000) + #else + /* ID CODE: FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF */ + #define BSP_CFG_ID_CODE_LONG_1 (0xFFFFFFFF) + #define BSP_CFG_ID_CODE_LONG_2 (0xFFFFFFFF) + #define BSP_CFG_ID_CODE_LONG_3 (0xFFFFFFFF) + #define BSP_CFG_ID_CODE_LONG_4 (0xffFFFFFF) + #endif + + #ifdef __cplusplus + } + #endif +#endif /* BSP_MCU_FAMILY_CFG_H_ */ diff --git a/hw/bsp/ra/boards/uno_r4/ra_cfg/fsp_cfg/bsp/bsp_pin_cfg.h b/hw/bsp/ra/boards/uno_r4/ra_cfg/fsp_cfg/bsp/bsp_pin_cfg.h new file mode 100644 index 000000000..5440b293b --- /dev/null +++ b/hw/bsp/ra/boards/uno_r4/ra_cfg/fsp_cfg/bsp/bsp_pin_cfg.h @@ -0,0 +1,17 @@ +/* generated configuration header file - do not edit */ +#ifndef BSP_PIN_CFG_H_ +#define BSP_PIN_CFG_H_ +#include "r_ioport.h" + +/* Common macro for FSP header files. There is also a corresponding FSP_FOOTER macro at the end of this file. */ +FSP_HEADER + +#define SW1 (BSP_IO_PORT_01_PIN_10) /* active low */ +#define LED1 (BSP_IO_PORT_01_PIN_11) /* active high */ +extern const ioport_cfg_t g_bsp_pin_cfg; /* R7FA4M1AB3CNE.pincfg */ + +void BSP_PinConfigSecurityInit(); + +/* Common macro for FSP header files. There is also a corresponding FSP_HEADER macro at the top of this file. */ +FSP_FOOTER +#endif /* BSP_PIN_CFG_H_ */ diff --git a/hw/bsp/ra/boards/uno_r4/ra_cfg/fsp_cfg/r_ioport_cfg.h b/hw/bsp/ra/boards/uno_r4/ra_cfg/fsp_cfg/r_ioport_cfg.h new file mode 100644 index 000000000..d2688bf5b --- /dev/null +++ b/hw/bsp/ra/boards/uno_r4/ra_cfg/fsp_cfg/r_ioport_cfg.h @@ -0,0 +1,13 @@ +/* generated configuration header file - do not edit */ +#ifndef R_IOPORT_CFG_H_ +#define R_IOPORT_CFG_H_ +#ifdef __cplusplus +extern "C" { +#endif + +#define IOPORT_CFG_PARAM_CHECKING_ENABLE (BSP_CFG_PARAM_CHECKING_ENABLE) + +#ifdef __cplusplus +} +#endif +#endif /* R_IOPORT_CFG_H_ */ diff --git a/hw/bsp/ra/boards/uno_r4/fsp_cfg/bsp_clock_cfg.h b/hw/bsp/ra/boards/uno_r4/ra_gen/bsp_clock_cfg.h similarity index 92% rename from hw/bsp/ra/boards/uno_r4/fsp_cfg/bsp_clock_cfg.h rename to hw/bsp/ra/boards/uno_r4/ra_gen/bsp_clock_cfg.h index 63618ec4b..559000a7a 100644 --- a/hw/bsp/ra/boards/uno_r4/fsp_cfg/bsp_clock_cfg.h +++ b/hw/bsp/ra/boards/uno_r4/ra_gen/bsp_clock_cfg.h @@ -4,10 +4,10 @@ #define BSP_CFG_CLOCKS_SECURE (0) #define BSP_CFG_CLOCKS_OVERRIDE (0) #define BSP_CFG_XTAL_HZ (0) /* XTAL 0Hz */ -#define BSP_CFG_PLL_SOURCE (BSP_CLOCKS_CLOCK_DISABLED) /* PLL Src: XTAL */ +#define BSP_CFG_PLL_SOURCE (BSP_CLOCKS_CLOCK_DISABLED) /* PLL Src: Disabled */ #define BSP_CFG_HOCO_FREQUENCY (4) /* HOCO 48MHz */ #define BSP_CFG_PLL_DIV (BSP_CLOCKS_PLL_DIV_4) /* PLL Div /4 */ -#define BSP_CFG_PLL_MUL BSP_CLOCKS_PLL_MUL(12, 0) /* PLL Mul x12 */ +#define BSP_CFG_PLL_MUL BSP_CLOCKS_PLL_MUL(12U,0U) /* PLL Mul x12 */ #define BSP_CFG_CLOCK_SOURCE (BSP_CLOCKS_SOURCE_CLOCK_HOCO) /* Clock Src: HOCO */ #define BSP_CFG_ICLK_DIV (BSP_CLOCKS_SYS_CLOCK_DIV_1) /* ICLK Div /1 */ #define BSP_CFG_PCLKA_DIV (BSP_CLOCKS_SYS_CLOCK_DIV_1) /* PCLKA Div /1 */ @@ -15,7 +15,7 @@ #define BSP_CFG_PCLKC_DIV (BSP_CLOCKS_SYS_CLOCK_DIV_1) /* PCLKC Div /1 */ #define BSP_CFG_PCLKD_DIV (BSP_CLOCKS_SYS_CLOCK_DIV_1) /* PCLKD Div /1 */ #define BSP_CFG_FCLK_DIV (BSP_CLOCKS_SYS_CLOCK_DIV_2) /* FCLK Div /2 */ -#define BSP_CFG_CLKOUT_SOURCE (BSP_CLOCKS_CLOCK_DISABLED) /* CLKOUT Src: SUBCLK */ +#define BSP_CFG_CLKOUT_SOURCE (BSP_CLOCKS_CLOCK_DISABLED) /* CLKOUT Disabled */ #define BSP_CFG_CLKOUT_DIV (BSP_CLOCKS_SYS_CLOCK_DIV_1) /* CLKOUT Div /1 */ #define BSP_CFG_UCK_SOURCE (BSP_CLOCKS_SOURCE_CLOCK_HOCO) /* UCLK Src: HOCO */ #endif /* BSP_CLOCK_CFG_H_ */ diff --git a/hw/bsp/ra/boards/uno_r4/ra_gen/common_data.c b/hw/bsp/ra/boards/uno_r4/ra_gen/common_data.c new file mode 100644 index 000000000..50036c0ad --- /dev/null +++ b/hw/bsp/ra/boards/uno_r4/ra_gen/common_data.c @@ -0,0 +1,11 @@ +/* generated common source file - do not edit */ +#include "common_data.h" +ioport_instance_ctrl_t g_ioport_ctrl; +const ioport_instance_t g_ioport = + { + .p_api = &g_ioport_on_ioport, + .p_ctrl = &g_ioport_ctrl, + .p_cfg = &g_bsp_pin_cfg, + }; +void g_common_init(void) { +} diff --git a/hw/bsp/ra/boards/uno_r4/ra_gen/common_data.h b/hw/bsp/ra/boards/uno_r4/ra_gen/common_data.h new file mode 100644 index 000000000..6a08cbee0 --- /dev/null +++ b/hw/bsp/ra/boards/uno_r4/ra_gen/common_data.h @@ -0,0 +1,20 @@ +/* generated common header file - do not edit */ +#ifndef COMMON_DATA_H_ +#define COMMON_DATA_H_ +#include +#include "bsp_api.h" +#include "r_ioport.h" +#include "bsp_pin_cfg.h" +FSP_HEADER +#define IOPORT_CFG_NAME g_bsp_pin_cfg +#define IOPORT_CFG_OPEN R_IOPORT_Open +#define IOPORT_CFG_CTRL g_ioport_ctrl + +/* IOPORT Instance */ +extern const ioport_instance_t g_ioport; + +/* IOPORT control structure. */ +extern ioport_instance_ctrl_t g_ioport_ctrl; +void g_common_init(void); +FSP_FOOTER +#endif /* COMMON_DATA_H_ */ diff --git a/hw/bsp/ra/boards/uno_r4/ra_gen/pin_data.c b/hw/bsp/ra/boards/uno_r4/ra_gen/pin_data.c new file mode 100644 index 000000000..58262de8b --- /dev/null +++ b/hw/bsp/ra/boards/uno_r4/ra_gen/pin_data.c @@ -0,0 +1,75 @@ +/* generated pin source file - do not edit */ +#include "bsp_api.h" +#include "r_ioport.h" + + +const ioport_pin_cfg_t g_bsp_pin_cfg_data[] = { + { + .pin = BSP_IO_PORT_01_PIN_08, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_DEBUG) + }, + { + .pin = BSP_IO_PORT_01_PIN_10, + .pin_cfg = ((uint32_t) IOPORT_CFG_PORT_DIRECTION_INPUT | (uint32_t) IOPORT_CFG_PULLUP_ENABLE) + }, + { + .pin = BSP_IO_PORT_01_PIN_11, + .pin_cfg = ((uint32_t) IOPORT_CFG_PORT_DIRECTION_OUTPUT | (uint32_t) IOPORT_CFG_PORT_OUTPUT_LOW) + }, + { + .pin = BSP_IO_PORT_03_PIN_00, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_DEBUG) + }, + { + .pin = BSP_IO_PORT_04_PIN_07, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_USB_FS) + }, + { + .pin = BSP_IO_PORT_09_PIN_14, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_USB_FS) + }, + { + .pin = BSP_IO_PORT_09_PIN_15, + .pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_USB_FS) + }, +}; + +const ioport_cfg_t g_bsp_pin_cfg = { + .number_of_pins = sizeof(g_bsp_pin_cfg_data)/sizeof(ioport_pin_cfg_t), + .p_pin_cfg_data = &g_bsp_pin_cfg_data[0], +}; + +#if BSP_TZ_SECURE_BUILD + +void R_BSP_PinCfgSecurityInit(void); + +/* Initialize SAR registers for secure pins. */ +void R_BSP_PinCfgSecurityInit(void) +{ + #if (2U == BSP_FEATURE_IOPORT_VERSION) + uint32_t pmsar[BSP_FEATURE_BSP_NUM_PMSAR]; + #else + uint16_t pmsar[BSP_FEATURE_BSP_NUM_PMSAR]; + #endif + memset(pmsar, 0xFF, BSP_FEATURE_BSP_NUM_PMSAR * sizeof(R_PMISC->PMSAR[0])); + + + for(uint32_t i = 0; i < g_bsp_pin_cfg.number_of_pins; i++) + { + uint32_t port_pin = g_bsp_pin_cfg.p_pin_cfg_data[i].pin; + uint32_t port = port_pin >> 8U; + uint32_t pin = port_pin & 0xFFU; + pmsar[port] &= (uint16_t) ~(1U << pin); + } + + for(uint32_t i = 0; i < BSP_FEATURE_BSP_NUM_PMSAR; i++) + { + #if (2U == BSP_FEATURE_IOPORT_VERSION) + R_PMISC->PMSAR[i].PMSAR = (uint16_t) pmsar[i]; + #else + R_PMISC->PMSAR[i].PMSAR = pmsar[i]; + #endif + } + +} +#endif diff --git a/hw/bsp/ra/boards/uno_r4/script/fsp.ld b/hw/bsp/ra/boards/uno_r4/script/fsp.ld new file mode 100644 index 000000000..605eef7d2 --- /dev/null +++ b/hw/bsp/ra/boards/uno_r4/script/fsp.ld @@ -0,0 +1,769 @@ +/* + Linker File for Renesas FSP +*/ + +INCLUDE memory_regions.ld + +/* Uncomment and set XIP_SECONDARY_SLOT_IMAGE to 1 below for the secondary XIP application image.*/ +/* + XIP_SECONDARY_SLOT_IMAGE = 1; +*/ + +QSPI_FLASH_PRV_LENGTH = DEFINED(QSPI_FLASH_SIZE) ? ABSOLUTE(QSPI_FLASH_SIZE) : ABSOLUTE(QSPI_FLASH_LENGTH); +OSPI_DEVICE_0_PRV_LENGTH = DEFINED(OSPI_DEVICE_0_SIZE) ? ABSOLUTE(OSPI_DEVICE_0_SIZE) : ABSOLUTE(OSPI_DEVICE_0_LENGTH); +OSPI_DEVICE_1_PRV_LENGTH = DEFINED(OSPI_DEVICE_1_SIZE) ? ABSOLUTE(OSPI_DEVICE_1_SIZE) : ABSOLUTE(OSPI_DEVICE_1_LENGTH); + +/* If a flat (secure) project has DEFINED RAM_NS_BUFFER_LENGTH, then emit IDAU symbols to allocate non-secure RAM. */ +__RESERVE_NS_RAM = !DEFINED(PROJECT_NONSECURE) && DEFINED(RAM_NS_BUFFER_LENGTH) && (OPTION_SETTING_S_LENGTH != 0); + +ITCM_START = DEFINED(ITCM_START)? ITCM_START : 0; +ITCM_LENGTH = DEFINED(ITCM_LENGTH)? ITCM_LENGTH : 0; +DTCM_START = DEFINED(DTCM_START)? DTCM_START : 0; +DTCM_LENGTH = DEFINED(DTCM_LENGTH)? DTCM_LENGTH : 0; +RAM_NS_BUFFER_BLOCK_LENGTH = DEFINED(RAM_NS_BUFFER_LENGTH) ? ALIGN(RAM_NS_BUFFER_LENGTH, 8192) : 0; +RAM_NS_BUFFER_LENGTH = DEFINED(RAM_NS_BUFFER_LENGTH) ? RAM_NS_BUFFER_LENGTH : 0; +RAM_NS_BUFFER_START = RAM_START + RAM_LENGTH - RAM_NS_BUFFER_LENGTH; +RAM_NS_BUFFER_BLOCK_START = RAM_START + RAM_LENGTH - RAM_NS_BUFFER_BLOCK_LENGTH; + +OPTION_SETTING_START_NS = DEFINED(PROJECT_NONSECURE) ? OPTION_SETTING_START : OPTION_SETTING_START + 0x80; + +/* This definition is used to avoid moving the counter in OPTION_SETTING regions for projects that should not configure option settings. + * Bootloader images do not configure option settings because they are owned by the bootloader. + * FSP_BOOTABLE_IMAGE is only defined in bootloader images. */ +__bl_FSP_BOOTABLE_IMAGE = 1; +__bln_FSP_BOOTABLE_IMAGE = 1; +PROJECT_SECURE_OR_FLAT = (!DEFINED(PROJECT_NONSECURE) || DEFINED(PROJECT_SECURE)) && OPTION_SETTING_LENGTH && !DEFINED(FSP_BOOTABLE_IMAGE); +USE_OPTION_SETTING_NS = DEFINED(PROJECT_NONSECURE) && !DEFINED(FSP_BOOTABLE_IMAGE); + +__bl_FLASH_IMAGE_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_IMAGE_NUMBER == 1 ? FLASH_START + FLASH_BOOTLOADER_LENGTH + FLASH_BOOTLOADER_HEADER_LENGTH : + (DEFINED(BOOTLOADER_SECONDARY_USE_QSPI) || DEFINED(BOOTLOADER_SECONDARY_USE_OSPI_B)) ? FLASH_START + FLASH_BOOTLOADER_LENGTH + FLASH_BOOTLOADER_SCRATCH_LENGTH + FLASH_BOOTLOADER_HEADER_LENGTH : + FLASH_START + FLASH_BOOTLOADER_LENGTH + FLASH_BOOTLOADER_SCRATCH_LENGTH + FLASH_APPLICATION_S_LENGTH + FLASH_BOOTLOADER_HEADER_LENGTH; +__bl_FLASH_IMAGE_LENGTH = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_S_LENGTH - FLASH_BOOTLOADER_HEADER_LENGTH; +__bl_FLASH_IMAGE_END = __bl_FLASH_IMAGE_START + __bl_FLASH_IMAGE_LENGTH; +__bl_XIP_SECONDARY_FLASH_IMAGE_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_START + FLASH_BOOTLOADER_LENGTH + FLASH_APPLICATION_S_LENGTH + FLASH_BOOTLOADER_HEADER_LENGTH; +__bl_XIP_SECONDARY_FLASH_IMAGE_END = __bl_XIP_SECONDARY_FLASH_IMAGE_START + __bl_FLASH_IMAGE_LENGTH; +__bl_FLASH_NS_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_NS_LENGTH == 0 ? __bl_FLASH_IMAGE_END : + __bl_FLASH_IMAGE_START - FLASH_BOOTLOADER_HEADER_LENGTH + FLASH_APPLICATION_S_LENGTH; +__bl_FLASH_NSC_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_NS_LENGTH == 0 ? __bl_FLASH_IMAGE_END : + __bl_FLASH_IMAGE_END - FLASH_APPLICATION_NSC_LENGTH; +__bl_RAM_NS_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_NS_LENGTH == 0 ? RAM_START + RAM_LENGTH : + RAM_START + RAM_LENGTH - RAM_APPLICATION_NS_LENGTH; +__bl_RAM_NSC_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_NS_LENGTH == 0 ? RAM_START + RAM_LENGTH : + __bl_RAM_NS_START - RAM_APPLICATION_NSC_LENGTH; +__bl_FLASH_NS_IMAGE_START = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_NS_LENGTH == 0 ? __bl_FLASH_IMAGE_END : + __bl_FLASH_NS_START + FLASH_BOOTLOADER_HEADER_LENGTH_2; +__bln_FLASH_IMAGE_START = __bl_FLASH_NS_IMAGE_START | (!DEFINED (NS_OFFSET_START) ? 0 : NS_OFFSET_START); +__bln_FLASH_IMAGE_LENGTH = !DEFINED(FLASH_BOOTLOADER_LENGTH) ? 0 : + FLASH_APPLICATION_NS_LENGTH == 0 ? __bl_FLASH_IMAGE_END : + FLASH_APPLICATION_NS_LENGTH - FLASH_BOOTLOADER_HEADER_LENGTH_2; + +XIP_SECONDARY_SLOT_IMAGE = DEFINED(XIP_SECONDARY_SLOT_IMAGE) ? XIP_SECONDARY_SLOT_IMAGE : 0; +FLASH_ORIGIN = !DEFINED(FLASH_IMAGE_START) ? FLASH_START : + XIP_SECONDARY_SLOT_IMAGE == 1 ? XIP_SECONDARY_FLASH_IMAGE_START : + FLASH_IMAGE_START; +LIMITED_FLASH_LENGTH = DEFINED(FLASH_IMAGE_LENGTH) ? FLASH_IMAGE_LENGTH : + DEFINED(FLASH_BOOTLOADER_LENGTH) ? FLASH_BOOTLOADER_LENGTH : + FLASH_LENGTH; +OPTION_SETTING_SAS_SIZE = 0x34; +OPTION_SETTING_SAS_LENGTH = !DEFINED(OPTION_SETTING_LENGTH) ? 0 : + OPTION_SETTING_LENGTH == 0 ? 0 : + OPTION_SETTING_LENGTH - OPTION_SETTING_SAS_SIZE; + +/* Define memory regions. */ +MEMORY +{ + ITCM (rx) : ORIGIN = ITCM_START, LENGTH = ITCM_LENGTH + DTCM (rwx) : ORIGIN = DTCM_START, LENGTH = DTCM_LENGTH + FLASH (rx) : ORIGIN = FLASH_ORIGIN, LENGTH = LIMITED_FLASH_LENGTH + RAM (rwx) : ORIGIN = RAM_START, LENGTH = RAM_LENGTH + DATA_FLASH (rx) : ORIGIN = DATA_FLASH_START, LENGTH = DATA_FLASH_LENGTH + QSPI_FLASH (rx) : ORIGIN = QSPI_FLASH_START, LENGTH = QSPI_FLASH_PRV_LENGTH + OSPI_DEVICE_0 (rx) : ORIGIN = OSPI_DEVICE_0_START, LENGTH = OSPI_DEVICE_0_PRV_LENGTH + OSPI_DEVICE_1 (rx) : ORIGIN = OSPI_DEVICE_1_START, LENGTH = OSPI_DEVICE_1_PRV_LENGTH + OSPI_DEVICE_0_RAM (rwx) : ORIGIN = OSPI_DEVICE_0_START, LENGTH = OSPI_DEVICE_0_PRV_LENGTH + OSPI_DEVICE_1_RAM (rwx) : ORIGIN = OSPI_DEVICE_1_START, LENGTH = OSPI_DEVICE_1_PRV_LENGTH + SDRAM (rwx) : ORIGIN = SDRAM_START, LENGTH = SDRAM_LENGTH + OPTION_SETTING (r) : ORIGIN = OPTION_SETTING_START, LENGTH = OPTION_SETTING_LENGTH + OPTION_SETTING_OFS (r) : ORIGIN = OPTION_SETTING_START, LENGTH = 0x18 + OPTION_SETTING_SAS (r) : ORIGIN = OPTION_SETTING_START + OPTION_SETTING_SAS_SIZE, LENGTH = OPTION_SETTING_SAS_LENGTH + OPTION_SETTING_S (r) : ORIGIN = OPTION_SETTING_S_START, LENGTH = OPTION_SETTING_S_LENGTH + ID_CODE (rx) : ORIGIN = ID_CODE_START, LENGTH = ID_CODE_LENGTH +} + +/* Library configurations */ +GROUP(libgcc.a libc.a libm.a) + +/* Linker script to place sections and symbol values. Should be used together + * with other linker script that defines memory regions FLASH and RAM. + * It references following symbols, which must be DEFINED in code: + * Reset_Handler : Entry of reset handler + * + * It defines following symbols, which code can use without definition: + * __exidx_start + * __exidx_end + * __copy_table_start__ + * __copy_table_end__ + * __zero_table_start__ + * __zero_table_end__ + * __etext + * __data_start__ + * __preinit_array_start + * __preinit_array_end + * __init_array_start + * __init_array_end + * __fini_array_start + * __fini_array_end + * __data_end__ + * __bss_start__ + * __bss_end__ + * __HeapLimit + * __StackLimit + * __StackTop + * __stack + * __Vectors_End + * __Vectors_Size + * __qspi_flash_start__ + * __qspi_flash_end__ + * __qspi_flash_code_size__ + * __qspi_region_max_size__ + * __qspi_region_start_address__ + * __qspi_region_end_address__ + * __ospi_device_0_start__ + * __ospi_device_0_end__ + * __ospi_device_0_code_size__ + * __ospi_device_0_region_max_size__ + * __ospi_device_0_region_start_address__ + * __ospi_device_0_region_end_address__ + * __ospi_device_1_start__ + * __ospi_device_1_end__ + * __ospi_device_1_code_size__ + * __ospi_device_1_region_max_size__ + * __ospi_device_1_region_start_address__ + * __ospi_device_1_region_end_address__ + */ +ENTRY(Reset_Handler) + +SECTIONS +{ + .text : + { + __tz_FLASH_S = ABSOLUTE(FLASH_START); + __ROM_Start = .; + + /* Even though the vector table is not 256 entries (1KB) long, we still allocate that much + * space because ROM registers are at address 0x400 and there is very little space + * in between. */ + KEEP(*(.fixed_vectors*)) + KEEP(*(.application_vectors*)) + __Vectors_End = .; + + /* Some devices have a gap of code flash between the vector table and ROM Registers. + * The flash gap section allows applications to place code and data in this section. */ + *(.flash_gap*) + + /* ROM Registers start at address 0x00000400 for devices that do not have the OPTION_SETTING region. */ + . = OPTION_SETTING_LENGTH > 0 ? . : __ROM_Start + 0x400; + KEEP(*(.rom_registers*)) + + /* Reserving 0x100 bytes of space for ROM registers. */ + . = OPTION_SETTING_LENGTH > 0 ? . : __ROM_Start + 0x500; + + /* Allocate flash write-boundary-aligned + * space for sce9 wrapped public keys for mcuboot if the module is used. + */ + KEEP(*(.mcuboot_sce9_key*)) + + *(.text*) + + KEEP(*(.version)) + KEEP(*(.init)) + KEEP(*(.fini)) + + /* .ctors */ + *crtbegin.o(.ctors) + *crtbegin?.o(.ctors) + *(EXCLUDE_FILE(*crtend?.o *crtend.o) .ctors) + *(SORT(.ctors.*)) + *(.ctors) + + /* .dtors */ + *crtbegin.o(.dtors) + *crtbegin?.o(.dtors) + *(EXCLUDE_FILE(*crtend?.o *crtend.o) .dtors) + *(SORT(.dtors.*)) + *(.dtors) + + *(.rodata*) + __usb_dev_descriptor_start_fs = .; + KEEP(*(.usb_device_desc_fs*)) + __usb_cfg_descriptor_start_fs = .; + KEEP(*(.usb_config_desc_fs*)) + __usb_interface_descriptor_start_fs = .; + KEEP(*(.usb_interface_desc_fs*)) + __usb_descriptor_end_fs = .; + __usb_dev_descriptor_start_hs = .; + KEEP(*(.usb_device_desc_hs*)) + __usb_cfg_descriptor_start_hs = .; + KEEP(*(.usb_config_desc_hs*)) + __usb_interface_descriptor_start_hs = .; + KEEP(*(.usb_interface_desc_hs*)) + __usb_descriptor_end_hs = .; + + KEEP(*(.eh_frame*)) + + __ROM_End = .; + } > FLASH = 0xFF + + __Vectors_Size = __Vectors_End - __Vectors; + + . = .; + __itcm_data_pre_location = .; + + /* Initialized ITCM data. */ + /* Aligned to FCACHE2 for RA8. */ + .itcm_data : ALIGN(16) + { + /* Start of ITCM Secure Trustzone region. */ + __tz_ITCM_S = ABSOLUTE(ITCM_START); + + /* All ITCM data start */ + __itcm_data_start = .; + + KEEP(*(.itcm_data*)) + + /* Pad to eight byte alignment in case of ECC initialization. Fill zero. */ + . = ALIGN(8); + + /* All ITCM data end */ + __itcm_data_end = .; + + /* + * Start of the ITCM Non-Secure Trustzone region. + * ITCM_NS_START can be used to set a fixed address for non-secure ITCM in secure projects or flat projects. + */ + __tz_ITCM_N = DEFINED(ITCM_NS_START) ? ABSOLUTE(ITCM_NS_START) : ALIGN(__itcm_data_end, 8192); + } > ITCM AT > FLASH = 0x00 + + /* Addresses exported for ITCM initialization. */ + __itcm_data_init_start = LOADADDR(.itcm_data); + __itcm_data_init_end = LOADADDR(.itcm_data) + SIZEOF(.itcm_data); + + ASSERT(ORIGIN(ITCM) % 8 == 0, "ITCM memory region origin must be aligned to 8 bytes.") + ASSERT(LENGTH(ITCM) % 8 == 0, "ITCM memory region length must be a multiple of 8 bytes.") + ASSERT(LOADADDR(.itcm_data) % 16 == 0, ".itcm_data section must be aligned to 16 bytes.") + ASSERT(SIZEOF(.itcm_data) % 8 == 0, ".itcm_data section size must be a multiple of 8 bytes.") + + /* Restore location counter. */ + /* If ITCM is not present, this will be the address stored in '.' before ALIGN was attempted. */ + /* If ITCM is present, this will be the absolute address that follows the ITCM ROM location. */ + . = (SIZEOF(.itcm_data) > 0) ? __itcm_data_init_end : __itcm_data_pre_location; + + __exidx_start = .; + /DISCARD/ : + { + *(.ARM.extab* .gnu.linkonce.armextab.*) + *(.ARM.exidx* .gnu.linkonce.armexidx.*) + } + __exidx_end = .; + + /* To copy multiple ROM to RAM sections, + * uncomment .copy.table section and, + * define __STARTUP_COPY_MULTIPLE in startup_ARMCMx.S */ + /* + .copy.table : + { + . = ALIGN(4); + __copy_table_start__ = .; + LONG (__etext) + LONG (__data_start__) + LONG (__data_end__ - __data_start__) + LONG (__etext2) + LONG (__data2_start__) + LONG (__data2_end__ - __data2_start__) + __copy_table_end__ = .; + } > FLASH + */ + + /* To clear multiple BSS sections, + * uncomment .zero.table section and, + * define __STARTUP_CLEAR_BSS_MULTIPLE in startup_ARMCMx.S */ + /* + .zero.table : + { + . = ALIGN(4); + __zero_table_start__ = .; + LONG (__bss_start__) + LONG (__bss_end__ - __bss_start__) + LONG (__bss2_start__) + LONG (__bss2_end__ - __bss2_start__) + __zero_table_end__ = .; + } > FLASH + */ + + __etext = .; + + __tz_RAM_S = ORIGIN(RAM); + + /* If DTC is used, put the DTC vector table at the start of SRAM. + This avoids memory holes due to 1K alignment required by it. */ + .fsp_dtc_vector_table (NOLOAD) : + { + . = ORIGIN(RAM); + *(.fsp_dtc_vector_table) + } > RAM + + /* Initialized data section. */ + .data : + { + __data_start__ = .; + . = ALIGN(4); + + __Code_In_RAM_Start = .; + + KEEP(*(.code_in_ram*)) + __Code_In_RAM_End = .; + + *(vtable) + /* Don't use *(.data*) because it will place data meant for .data_flash in this section. */ + *(.data.*) + *(.data) + + . = ALIGN(4); + /* preinit data */ + PROVIDE_HIDDEN (__preinit_array_start = .); + KEEP(*(.preinit_array)) + PROVIDE_HIDDEN (__preinit_array_end = .); + + . = ALIGN(4); + /* init data */ + PROVIDE_HIDDEN (__init_array_start = .); + KEEP(*(SORT(.init_array.*))) + KEEP(*(.init_array)) + PROVIDE_HIDDEN (__init_array_end = .); + + + . = ALIGN(4); + /* finit data */ + PROVIDE_HIDDEN (__fini_array_start = .); + KEEP(*(SORT(.fini_array.*))) + KEEP(*(.fini_array)) + PROVIDE_HIDDEN (__fini_array_end = .); + + KEEP(*(.jcr*)) + + . = ALIGN(4); + + /* All data end */ + __data_end__ = .; + + } > RAM AT > FLASH + + . = .; + __dtcm_data_pre_location = LOADADDR(.data) + SIZEOF(.data); + + /* Initialized DTCM data. */ + /* Aligned to FCACHE2 for RA8. */ + .dtcm_data : ALIGN(16) + { + /* Start of DTCM Secure Trustzone region. */ + __tz_DTCM_S = ABSOLUTE(DTCM_START); + + /* Initialized DTCM data start */ + __dtcm_data_start = .; + + KEEP(*(.dtcm_data*)) + + /* Pad to eight byte alignment in case of ECC initialization. Fill zero. */ + . = ALIGN(8); + + /* Initialized DTCM data end */ + __dtcm_data_end = .; + } > DTCM AT > FLASH = 0x00 + + . = __dtcm_data_end; + /* Uninitialized DTCM data. */ + /* ALIGN appears on the left side of the colon because it is being used to assign the VMA directly, as opposed to a right side appearance which would control the LMA. */ + .dtcm_bss ALIGN(8) (NOLOAD) : + { + /* Uninitialized DTCM data start */ + __dtcm_bss_start = .; + + KEEP(*(.dtcm_bss*)) + + /* Pad to eight byte alignment in case of ECC initialization. No fill because of NOLOAD. */ + . = ALIGN(8); + + /* Uninitialized DTCM data end */ + __dtcm_bss_end = .; + + /* + * Start of the DTCM Non-Secure Trustzone region. + * DTCM_NS_START can be used to set a fixed address for non-secure DTCM in secure projects or flat projects. + */ + __tz_DTCM_N = DEFINED(DTCM_NS_START) ? ABSOLUTE(DTCM_NS_START) : ALIGN(__dtcm_bss_end, 8192); + } > DTCM + + /* Addresses exported for DTCM initialization. */ + __dtcm_data_init_start = LOADADDR(.dtcm_data); + __dtcm_data_init_end = LOADADDR(.dtcm_data) + SIZEOF(.dtcm_data); + + ASSERT(ORIGIN(DTCM) % 8 == 0, "DTCM memory region origin must be aligned to 8 bytes.") + ASSERT(LENGTH(DTCM) % 8 == 0, "DTCM memory region length must be a multiple of 8 bytes.") + ASSERT(LOADADDR(.dtcm_bss) == ADDR(.dtcm_bss), ".dtcm_bss has (VMA != LMA) but should be NOLOAD (VMA == LMA).") + ASSERT(LOADADDR(.dtcm_data) % 16 == 0, ".dtcm_data section must be aligned to 16 bytes.") + ASSERT(SIZEOF(.dtcm_data) % 8 == 0, ".dtcm_data section size must be a multiple of 8 bytes.") + ASSERT(LOADADDR(.dtcm_bss) % 8 == 0, ".dtcm_bss section must be aligned to 8 bytes.") + ASSERT(SIZEOF(.dtcm_bss) % 8 == 0, ".dtcm_bss section size must be a multiple of 8 bytes.") + ASSERT(__dtcm_bss_start == __dtcm_data_end, ".dtcm_bss section is not adjacent to .dtcm_data section.") + + /* Restore location counter. */ + /* If DTCM is not present, this will be the address stored in '.' before ALIGN was attempted. */ + /* If DTCM is present, this will be the absolute address that follows the DTCM ROM location. */ + . = (SIZEOF(.dtcm_data) > 0) ? __dtcm_data_init_end : __dtcm_data_pre_location; + + /* TrustZone Secure Gateway Stubs Section */ + + /* Store location counter for SPI non-retentive sections. */ + sgstubs_pre_location = .; + + /* Determine the secure gateway stubs address either by the provided linker variable or the next 1024-byte block. */ + SGSTUBS_LOC = (DEFINED(PROJECT_SECURE) && DEFINED(FLASH_NSC_START)) ? ABSOLUTE(FLASH_NSC_START) : ALIGN(1024); + .gnu.sgstubs SGSTUBS_LOC : ALIGN(1024) + { + __tz_FLASH_C = DEFINED(FLASH_NSC_START) ? ABSOLUTE(FLASH_NSC_START) : __RESERVE_NS_RAM ? ABSOLUTE(FLASH_START + FLASH_LENGTH) : ALIGN(1024); + _start_sg = .; + *(.gnu.sgstubs*) + . = ALIGN(32); + _end_sg = .; + } > FLASH + + __tz_FLASH_N = DEFINED(FLASH_NS_START) ? ABSOLUTE(FLASH_NS_START) : __RESERVE_NS_RAM ? ABSOLUTE(FLASH_START + FLASH_LENGTH) : FLASH_LENGTH < 32768 ? FLASH_LENGTH : ALIGN(32768); + FLASH_NS_IMAGE_START = DEFINED(FLASH_NS_IMAGE_START) ? FLASH_NS_IMAGE_START : __tz_FLASH_N; + + /* Note: There are no secure/non-secure boundaries for QSPI. These symbols are provided for the RA configuration tool. */ + __tz_QSPI_FLASH_S = ORIGIN(QSPI_FLASH); + + /* QSPI_FLASH section to be downloaded via debugger */ + .qspi_flash : + { + __qspi_flash_start__ = .; + KEEP(*(.qspi_flash*)) + KEEP(*(.code_in_qspi*)) + __qspi_flash_end__ = .; + } > QSPI_FLASH + __qspi_flash_code_size__ = __qspi_flash_end__ - __qspi_flash_start__; + + /* QSPI_FLASH non-retentive section, creates a copy in internal flash that can be copied to QSPI */ + __qspi_flash_code_addr__ = sgstubs_pre_location; + .qspi_non_retentive : AT(__qspi_flash_code_addr__) + { + __qspi_non_retentive_start__ = .; + KEEP(*(.qspi_non_retentive*)) + __qspi_non_retentive_end__ = .; + } > QSPI_FLASH + __qspi_non_retentive_size__ = __qspi_non_retentive_end__ - __qspi_non_retentive_start__; + + __qspi_region_max_size__ = 0x4000000; /* Must be the same as defined in MEMORY above */ + __qspi_region_start_address__ = __qspi_flash_start__; + __qspi_region_end_address__ = __qspi_flash_start__ + __qspi_region_max_size__; + + /* Note: There are no secure/non-secure boundaries for QSPI. These symbols are provided for the RA configuration tool. */ + __tz_QSPI_FLASH_N = __qspi_non_retentive_end__; + + /* Support for OctaRAM */ + .OSPI_DEVICE_0_NO_LOAD (NOLOAD): + { + . = ALIGN(4); + __ospi_device_0_start__ = .; + *(.ospi_device_0_no_load*) + . = ALIGN(4); + __ospi_device_0_end__ = .; + } > OSPI_DEVICE_0_RAM + + .OSPI_DEVICE_1_NO_LOAD (NOLOAD): + { + . = ALIGN(4); + __ospi_device_1_start__ = .; + *(.ospi_device_1_no_load*) + . = ALIGN(4); + __ospi_device_1_end__ = .; + } > OSPI_DEVICE_1_RAM + + /* Note: There are no secure/non-secure boundaries for QSPI. These symbols are provided for the RA configuration tool. */ + __tz_OSPI_DEVICE_0_S = ORIGIN(OSPI_DEVICE_0); + + /* OSPI_DEVICE_0 section to be downloaded via debugger */ + .OSPI_DEVICE_0 : + { + __ospi_device_0_start__ = .; + KEEP(*(.ospi_device_0*)) + KEEP(*(.code_in_ospi_device_0*)) + __ospi_device_0_end__ = .; + } > OSPI_DEVICE_0 + __ospi_device_0_code_size__ = __ospi_device_0_end__ - __ospi_device_0_start__; + + /* OSPI_DEVICE_0 non-retentive section, creates a copy in internal flash that can be copied to OSPI */ + __ospi_device_0_code_addr__ = sgstubs_pre_location + (SIZEOF(.qspi_non_retentive)); + .ospi_device_0_non_retentive : AT(__ospi_device_0_code_addr__) + { + __ospi_device_0_non_retentive_start__ = .; + KEEP(*(.ospi_device_0_non_retentive*)) + __ospi_device_0_non_retentive_end__ = .; + } > OSPI_DEVICE_0 + __ospi_device_0_non_retentive_size__ = __ospi_device_0_non_retentive_end__ - __ospi_device_0_non_retentive_start__; + + __ospi_device_0_region_max_size__ = 0x8000000; /* Must be the same as defined in MEMORY above */ + __ospi_device_0_region_start_address__ = __ospi_device_0_start__; + __ospi_device_0_region_end_address__ = __ospi_device_0_start__ + __ospi_device_0_region_max_size__; + + /* Note: There are no secure/non-secure boundaries for OSPI. These symbols are provided for the RA configuration tool. */ + __tz_OSPI_DEVICE_0_N = __ospi_device_0_non_retentive_end__; + + /* Note: There are no secure/non-secure boundaries for OSPI. These symbols are provided for the RA configuration tool. */ + __tz_OSPI_DEVICE_1_S = ORIGIN(OSPI_DEVICE_1); + + /* OSPI_DEVICE_1 section to be downloaded via debugger */ + .OSPI_DEVICE_1 : + { + __ospi_device_1_start__ = .; + KEEP(*(.ospi_device_1*)) + KEEP(*(.code_in_ospi_device_1*)) + __ospi_device_1_end__ = .; + } > OSPI_DEVICE_1 + __ospi_device_1_code_size__ = __ospi_device_1_end__ - __ospi_device_1_start__; + + /* OSPI_DEVICE_1 non-retentive section, creates a copy in internal flash that can be copied to OSPI */ + __ospi_device_1_code_addr__ = sgstubs_pre_location + (SIZEOF(.qspi_non_retentive) + SIZEOF(.ospi_device_0_non_retentive)); + .ospi_device_1_non_retentive : AT(__ospi_device_1_code_addr__) + { + __ospi_device_1_non_retentive_start__ = .; + KEEP(*(.ospi_device_1_non_retentive*)) + __ospi_device_1_non_retentive_end__ = .; + } > OSPI_DEVICE_1 + __ospi_device_1_non_retentive_size__ = __ospi_device_1_non_retentive_end__ - __ospi_device_1_non_retentive_start__; + + __ospi_device_1_region_max_size__ = 0x10000000; /* Must be the same as defined in MEMORY above */ + __ospi_device_1_region_start_address__ = __ospi_device_1_start__; + __ospi_device_1_region_end_address__ = __ospi_device_1_start__ + __ospi_device_1_region_max_size__; + + /* Note: There are no secure/non-secure boundaries for OSPI. These symbols are provided for the RA configuration tool. */ + __tz_OSPI_DEVICE_1_N = __ospi_device_1_non_retentive_end__; + + .noinit (NOLOAD): + { + . = ALIGN(4); + __noinit_start = .; + KEEP(*(.noinit*)) + . = ALIGN(8); + /* Place the FreeRTOS heap here so that the __HeapLimit calculation does not include the freertos heap. */ + KEEP(*(.heap.*)) + __noinit_end = .; + } > RAM + + .bss : + { + . = ALIGN(4); + __bss_start__ = .; + *(.bss*) + *(COMMON) + . = ALIGN(4); + __bss_end__ = .; + } > RAM + + .heap (NOLOAD): + { + . = ALIGN(8); + __HeapBase = .; + /* Place the STD heap here. */ + KEEP(*(.heap)) + __HeapLimit = .; + } > RAM + + /* Stacks are stored in this section. */ + .stack_dummy (NOLOAD): + { + . = ALIGN(8); + __StackLimit = .; + /* Main stack */ + KEEP(*(.stack)) + __StackTop = .; + /* Thread stacks */ + KEEP(*(.stack*)) + __StackTopAll = .; + } > RAM + + PROVIDE(__stack = __StackTopAll); + + /* This symbol represents the end of user allocated RAM. The RAM after this symbol can be used + at run time for things such as ThreadX memory pool allocations. */ + __RAM_segment_used_end__ = ALIGN(__StackTopAll , 4); + + /* RAM_NSC_START can be used to set a fixed address for non-secure callable RAM in secure projects. + * If it is not specified, the address for NSC RAM is the end of RAM aligned to a 1K boundary. + * In flat projects that require non-secure RAM, this variable is set to the start of non-secure RAM. */ + __tz_RAM_C = DEFINED(RAM_NSC_START) ? ABSOLUTE(RAM_NSC_START - RAM_NS_BUFFER_BLOCK_LENGTH) : __RESERVE_NS_RAM ? ABSOLUTE(RAM_NS_BUFFER_BLOCK_START) : ALIGN(__RAM_segment_used_end__, 1024); + + /* RAM_NS_START can be used to set a fixed address for non-secure RAM in secure projects or flat projects. + * RAM_NS_BUFFER_BLOCK_LENGTH is used to allocate non-secure buffers in a flat project. If it is not + * specified, the address for NSC RAM is the end of RAM aligned to an 8K boundary. + * In flat projects that require non-secure RAM, this variable is set to the start of non-secure RAM. */ + __tz_RAM_N = DEFINED(RAM_NS_START) ? ABSOLUTE(RAM_NS_START - RAM_NS_BUFFER_BLOCK_LENGTH) : __RESERVE_NS_RAM ? ABSOLUTE(RAM_NS_BUFFER_BLOCK_START) : ALIGN(__tz_RAM_C, 8192); + + /* Non-secure buffers must be in non-secure RAM. This is primarily used for the EDMAC in flat projects. + * The EDMAC is a non-secure bus master and can only access non-secure RAM. */ + .ns_buffer (NOLOAD): + { + /* Allocate RAM on a 32-byte boundary to help with placement of Ethernet buffers. */ + . = __RESERVE_NS_RAM ? ABSOLUTE(RAM_NS_BUFFER_START & 0xFFFFFFE0) : .; + + KEEP(*(.ns_buffer*)) + } > RAM + + /* Data flash. */ + .data_flash : + { + . = ORIGIN(DATA_FLASH); + __tz_DATA_FLASH_S = .; + __Data_Flash_Start = .; + KEEP(*(.data_flash*)) + __Data_Flash_End = .; + + __tz_DATA_FLASH_N = DEFINED(DATA_FLASH_NS_START) ? ABSOLUTE(DATA_FLASH_NS_START) : __RESERVE_NS_RAM ? ABSOLUTE(DATA_FLASH_START + DATA_FLASH_LENGTH) : ALIGN(1024); + } > DATA_FLASH + + /* Note: There are no secure/non-secure boundaries for SDRAM. These symbols are provided for the RA configuration tool. */ + __tz_SDRAM_S = ORIGIN(SDRAM); + + /* SDRAM */ + .sdram (NOLOAD): + { + __SDRAM_Start = .; + KEEP(*(.sdram*)) + KEEP(*(.frame*)) + __SDRAM_End = .; + } > SDRAM + + /* Note: There are no secure/non-secure boundaries for SDRAM. These symbols are provided for the RA configuration tool. */ + __tz_SDRAM_N = __SDRAM_End; + + /* Note: There are no secure/non-secure boundaries for ID_CODE. These symbols are provided for the RA configuration tool. */ + __tz_ID_CODE_S = ORIGIN(ID_CODE); + + /* Note: There are no secure/non-secure boundaries for ID_CODE. These symbols are provided for the RA configuration tool. + * Set this symbol to the same value as __tz_ID_CODE_S so the RA configuration tool does not split the ID_CODE + * memory region between TrustZone projects. */ + __tz_ID_CODE_N = __tz_ID_CODE_S; + + .id_code : + { + __ID_Code_Start = .; + KEEP(*(.id_code*)) + __ID_Code_End = .; + } > ID_CODE + + /* Symbol required for RA Configuration tool. */ + __tz_OPTION_SETTING_S = ORIGIN(OPTION_SETTING_OFS); + + .option_setting_ofs : + { + __OPTION_SETTING_OFS_Start = .; + KEEP(*(.option_setting_ofs0)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_OFS_Start + 0x04 : __OPTION_SETTING_OFS_Start; + KEEP(*(.option_setting_ofs2)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_OFS_Start + 0x10 : __OPTION_SETTING_OFS_Start; + KEEP(*(.option_setting_dualsel)) + __OPTION_SETTING_OFS_End = .; + } > OPTION_SETTING_OFS = 0xFF + + .option_setting_sas : + { + __OPTION_SETTING_SAS_Start = .; + KEEP(*(.option_setting_sas)) + __OPTION_SETTING_SAS_End = .; + } > OPTION_SETTING_SAS = 0xFF + + /* Symbol required for RA Configuration tool. */ + __tz_OPTION_SETTING_N = ABSOLUTE(OPTION_SETTING_START_NS); + + .option_setting_ns : + { + __OPTION_SETTING_NS_Start = .; + KEEP(*(.option_setting_ofs1)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x04 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_ofs3)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x10 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_banksel)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x40 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_bps0)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x44 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_bps1)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x48 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_bps2)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x4C : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_bps3)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x60 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_pbps0)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x64 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_pbps1)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x68 : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_pbps2)) + . = USE_OPTION_SETTING_NS ? __OPTION_SETTING_NS_Start + 0x6C : __OPTION_SETTING_NS_Start; + KEEP(*(.option_setting_pbps3)) + __OPTION_SETTING_NS_End = .; + } > OPTION_SETTING = 0xFF + + /* Symbol required for RA Configuration tool. */ + __tz_OPTION_SETTING_S_S = ORIGIN(OPTION_SETTING_S); + + .option_setting_s : + { + __OPTION_SETTING_S_Start = .; + KEEP(*(.option_setting_ofs1_sec)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x04 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_ofs3_sec)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x10 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_banksel_sec)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x40 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sec0)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x44 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sec1)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x48 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sec2)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x4C : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sec3)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x60 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_pbps_sec0)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x64 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_pbps_sec1)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x68 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_pbps_sec2)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x6C : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_pbps_sec3)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x80 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_ofs1_sel)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x84 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_ofs3_sel)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0x90 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_banksel_sel)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0xC0 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sel0)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0xC4 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sel1)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0xC8 : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sel2)) + . = PROJECT_SECURE_OR_FLAT ? __OPTION_SETTING_S_Start + 0xCC : __OPTION_SETTING_S_Start; + KEEP(*(.option_setting_bps_sel3)) + __OPTION_SETTING_S_End = .; + } > OPTION_SETTING_S = 0xFF + + /* Symbol required for RA Configuration tool. */ + __tz_OPTION_SETTING_S_N = __OPTION_SETTING_S_End; +} diff --git a/hw/bsp/ra/boards/uno_r4/script/memory_regions.ld b/hw/bsp/ra/boards/uno_r4/script/memory_regions.ld new file mode 100644 index 000000000..22775395c --- /dev/null +++ b/hw/bsp/ra/boards/uno_r4/script/memory_regions.ld @@ -0,0 +1,25 @@ + + /* generated memory regions file - do not edit */ + RAM_START = 0x20000000; + RAM_LENGTH = 0x8000; + FLASH_START = 0x00000000; + FLASH_LENGTH = 0x40000; + DATA_FLASH_START = 0x40100000; + DATA_FLASH_LENGTH = 0x2000; + OPTION_SETTING_START = 0x00000000; + OPTION_SETTING_LENGTH = 0x0; + OPTION_SETTING_S_START = 0x80000000; + OPTION_SETTING_S_LENGTH = 0x0; + ID_CODE_START = 0x01010018; + ID_CODE_LENGTH = 0x20; + SDRAM_START = 0x80010000; + SDRAM_LENGTH = 0x0; + QSPI_FLASH_START = 0x60000000; + QSPI_FLASH_LENGTH = 0x0; + OSPI_DEVICE_0_START = 0x80020000; + OSPI_DEVICE_0_LENGTH = 0x0; + OSPI_DEVICE_1_START = 0x80030000; + OSPI_DEVICE_1_LENGTH = 0x0; + +/* Uno R4 has bootloader */ +FLASH_IMAGE_START = 0x4000; diff --git a/hw/bsp/ra/boards/uno_r4/smart_configurator/configuration.xml b/hw/bsp/ra/boards/uno_r4/smart_configurator/configuration.xml new file mode 100644 index 000000000..b716c8ec9 --- /dev/null +++ b/hw/bsp/ra/boards/uno_r4/smart_configurator/configuration.xml @@ -0,0 +1,218 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Board Support Package Common Files + Renesas.RA.5.6.0.pack + + + I/O Port + Renesas.RA.5.6.0.pack + + + Arm CMSIS Version 6 - Core (M) + Arm.CMSIS6.6.1.0+fsp.5.6.0.pack + + + Custom Board Support Files + Renesas.RA_board_custom.5.6.0.pack + + + Board support package for R7FA4M1AB3CNE + Renesas.RA_mcu_ra4m1.5.6.0.pack + + + Board support package for RA4M1 + Renesas.RA_mcu_ra4m1.5.6.0.pack + + + Board support package for RA4M1 - FSP Data + Renesas.RA_mcu_ra4m1.5.6.0.pack + + + Board support package for RA4M1 - Events + Renesas.RA_mcu_ra4m1.5.6.0.pack + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/hw/bsp/ra/boards/uno_r4/uno_r4.ld b/hw/bsp/ra/boards/uno_r4/uno_r4.ld deleted file mode 100644 index 45f11dfb1..000000000 --- a/hw/bsp/ra/boards/uno_r4/uno_r4.ld +++ /dev/null @@ -1,25 +0,0 @@ -RAM_START = 0x20000000; -RAM_LENGTH = 0x8000; -FLASH_START = 0x00000000; -FLASH_LENGTH = 0x40000; -DATA_FLASH_START = 0x40100000; -DATA_FLASH_LENGTH = 0x2000; -OPTION_SETTING_START = 0x00000000; -OPTION_SETTING_LENGTH = 0x0; -OPTION_SETTING_S_START = 0x80000000; -OPTION_SETTING_S_LENGTH = 0x0; -ID_CODE_START = 0x01010018; -ID_CODE_LENGTH = 0x20; -SDRAM_START = 0x80010000; -SDRAM_LENGTH = 0x0; -QSPI_FLASH_START = 0x60000000; -QSPI_FLASH_LENGTH = 0x0; -OSPI_DEVICE_0_START = 0x80020000; -OSPI_DEVICE_0_LENGTH = 0x0; -OSPI_DEVICE_1_START = 0x80030000; -OSPI_DEVICE_1_LENGTH = 0x0; - -/* Uno R4 has bootloader */ -FLASH_IMAGE_START = 0x4000; - -INCLUDE fsp.ld diff --git a/hw/bsp/ra/family.c b/hw/bsp/ra/family.c index 87f7b4a22..0fd24e493 100644 --- a/hw/bsp/ra/family.c +++ b/hw/bsp/ra/family.c @@ -24,20 +24,19 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: Renesas +*/ + #include #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstrict-prototypes" #pragma GCC diagnostic ignored "-Wundef" - -// extra push due to https://github.com/renesas/fsp/pull/278 -#pragma GCC diagnostic push #endif -#include "bsp_api.h" -#include "r_ioport.h" -#include "r_ioport_api.h" +#include "common_data.h" #include "renesas.h" #ifdef __GNUC__ @@ -50,12 +49,6 @@ /* Key code for writing PRCR register. */ #define BSP_PRV_PRCR_KEY (0xA500U) -static const ioport_cfg_t family_pin_cfg = { - .number_of_pins = sizeof(board_pin_cfg) / sizeof(ioport_pin_cfg_t), - .p_pin_cfg_data = board_pin_cfg, -}; -static ioport_instance_ctrl_t port_ctrl; - //--------------------------------------------------------------------+ // Vector Data //--------------------------------------------------------------------+ @@ -103,7 +96,7 @@ void board_init(void) { __enable_irq(); /* Configure pins. */ - R_IOPORT_Open(&port_ctrl, &family_pin_cfg); + R_IOPORT_Open(&IOPORT_CFG_CTRL, &IOPORT_CFG_NAME); #ifdef TRACE_ETM // TRCKCR is protected by PRCR bit0 register @@ -138,12 +131,12 @@ void board_init_after_tusb(void) { } void board_led_write(bool state) { - R_IOPORT_PinWrite(&port_ctrl, LED1, state ? LED_STATE_ON : !LED_STATE_ON); + R_IOPORT_PinWrite(&IOPORT_CFG_CTRL, LED1, state ? LED_STATE_ON : !LED_STATE_ON); } uint32_t board_button_read(void) { bsp_io_level_t lvl = !BUTTON_STATE_ACTIVE; - R_IOPORT_PinRead(&port_ctrl, SW1, &lvl); + R_IOPORT_PinRead(&IOPORT_CFG_CTRL, SW1, &lvl); return lvl == BUTTON_STATE_ACTIVE; } @@ -211,7 +204,6 @@ void usbfs_d1fifo_handler(void) { //------------- USB1 HighSpeed -------------// #ifdef BOARD_HAS_USB_HIGHSPEED - void usbhs_interrupt_handler(void) { IRQn_Type irq = R_FSP_CurrentIrqGet(); R_BSP_IrqStatusClear(irq); @@ -230,7 +222,6 @@ void usbhs_d1fifo_handler(void) { R_BSP_IrqStatusClear(irq); // TODO not used yet } - #endif //--------------------------------------------------------------------+ diff --git a/hw/bsp/ra/family.cmake b/hw/bsp/ra/family.cmake index 426e1ca8f..42a32631c 100644 --- a/hw/bsp/ra/family.cmake +++ b/hw/bsp/ra/family.cmake @@ -4,7 +4,7 @@ if (NOT BOARD) message(FATAL_ERROR "BOARD not specified") endif () -set(CMSIS_DIR ${TOP}/lib/CMSIS_5) +set(CMSIS_DIR ${TOP}/lib/CMSIS_6) set(FSP_RA ${TOP}/hw/mcu/renesas/fsp/ra/fsp) # include board specific @@ -15,6 +15,28 @@ set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOL set(FAMILY_MCUS RAXXX ${MCU_VARIANT} CACHE INTERNAL "") +# ---------------------- +# Port & Speed Selection +# ---------------------- +if (NOT DEFINED RHPORT_DEVICE) + set(RHPORT_DEVICE 0) +endif () +if (NOT DEFINED RHPORT_HOST) + set(RHPORT_HOST 0) +endif () + +if (NOT DEFINED RHPORT_SPEED) + set(RHPORT_SPEED OPT_MODE_FULL_SPEED OPT_MODE_HIGH_SPEED) +endif () +if (NOT DEFINED RHPORT_DEVICE_SPEED) + list(GET RHPORT_SPEED ${RHPORT_DEVICE} RHPORT_DEVICE_SPEED) +endif () +if (NOT DEFINED RHPORT_HOST_SPEED) + list(GET RHPORT_SPEED ${RHPORT_HOST} RHPORT_HOST_SPEED) +endif () + +cmake_print_variables(RHPORT_DEVICE RHPORT_DEVICE_SPEED RHPORT_HOST RHPORT_HOST_SPEED) + #------------------------------------ # BOARD_TARGET #------------------------------------ @@ -32,10 +54,11 @@ function(add_board_target BOARD_TARGET) ${FSP_RA}/src/bsp/mcu/all/bsp_io.c ${FSP_RA}/src/bsp/mcu/all/bsp_irq.c ${FSP_RA}/src/bsp/mcu/all/bsp_register_protection.c - ${FSP_RA}/src/bsp/mcu/all/bsp_rom_registers.c ${FSP_RA}/src/bsp/mcu/all/bsp_sbrk.c ${FSP_RA}/src/bsp/mcu/all/bsp_security.c ${FSP_RA}/src/r_ioport/r_ioport.c + ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/boards/${BOARD}/ra_gen/common_data.c + ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/boards/${BOARD}/ra_gen/pin_data.c ) target_compile_options(${BOARD_TARGET} PUBLIC @@ -44,8 +67,9 @@ function(add_board_target BOARD_TARGET) target_include_directories(${BOARD_TARGET} PUBLIC ${CMAKE_CURRENT_FUNCTION_LIST_DIR} ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/boards/${BOARD} - ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/boards/${BOARD}/fsp_cfg - ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/boards/${BOARD}/fsp_cfg/bsp + ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/boards/${BOARD}/ra_cfg/fsp_cfg + ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/boards/${BOARD}/ra_cfg/fsp_cfg/bsp + ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/boards/${BOARD}/ra_gen ${CMSIS_DIR}/CMSIS/Core/Include ${FSP_RA}/inc ${FSP_RA}/inc/api @@ -54,22 +78,27 @@ function(add_board_target BOARD_TARGET) ${FSP_RA}/src/bsp/mcu/all ${FSP_RA}/src/bsp/mcu/${MCU_VARIANT} ) + target_compile_definitions(${BOARD_TARGET} PUBLIC + BOARD_TUD_RHPORT=${RHPORT_DEVICE} + BOARD_TUD_MAX_SPEED=${RHPORT_DEVICE_SPEED} + BOARD_TUH_RHPORT=${RHPORT_HOST} + BOARD_TUH_MAX_SPEED=${RHPORT_HOST_SPEED} + ) update_board(${BOARD_TARGET}) if (NOT DEFINED LD_FILE_${CMAKE_C_COMPILER_ID}) - set(LD_FILE_GNU ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/linker/gcc/${MCU_VARIANT}.ld) + set(LD_FILE_GNU ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/boards/${BOARD}/script/fsp.ld) endif () if (CMAKE_C_COMPILER_ID STREQUAL "GNU") target_link_options(${BOARD_TARGET} PUBLIC # linker file "LINKER:--script=${LD_FILE_GNU}" - -L${CMAKE_CURRENT_FUNCTION_LIST_DIR}/linker/gcc + -L${CMAKE_CURRENT_FUNCTION_LIST_DIR}/boards/${BOARD}/script + -Wl,--defsym=end=__bss_end__ -nostartfiles - # nanolib - --specs=nano.specs - --specs=nosys.specs + --specs=nano.specs --specs=nosys.specs ) elseif (CMAKE_C_COMPILER_ID STREQUAL "IAR") target_link_options(${BOARD_TARGET} PUBLIC @@ -95,12 +124,18 @@ function(family_configure_example TARGET RTOS) # BSP ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/family.c ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/../board.c + # Explicitly added bsp_rom_registers here, otherwise MCU can be bricked if g_bsp_rom_registers is dropped by linker + ${FSP_RA}/src/bsp/mcu/all/bsp_rom_registers.c ) target_include_directories(${TARGET} PUBLIC # family, hw, board ${CMAKE_CURRENT_FUNCTION_LIST_DIR} ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/../../ ) + target_compile_options(${TARGET} PUBLIC + -Wno-error=undef + -Wno-error=strict-prototypes + ) # # RA has custom freertos port # if (NOT TARGET freertos_kernel_port) @@ -112,22 +147,21 @@ function(family_configure_example TARGET RTOS) # endif () # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_RAXXX ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC + family_add_tinyusb(${TARGET} OPT_MCU_RAXXX) + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/renesas/rusb2/dcd_rusb2.c ${TOP}/src/portable/renesas/rusb2/hcd_rusb2.c ${TOP}/src/portable/renesas/rusb2/rusb2_common.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) # Flashing family_flash_jlink(${TARGET}) + family_add_bin_hex(${TARGET}) if (DEFINED DFU_UTIL_VID_PID) - family_add_bin_hex(${TARGET}) family_flash_dfu_util(${TARGET} ${DFU_UTIL_VID_PID}) endif () endfunction() diff --git a/hw/bsp/ra/family.mk b/hw/bsp/ra/family.mk index 4447e8499..6ac7c262f 100644 --- a/hw/bsp/ra/family.mk +++ b/hw/bsp/ra/family.mk @@ -1,42 +1,67 @@ -DEPS_SUBMODULES += hw/mcu/renesas/fsp lib/CMSIS_5 - FSP_RA = hw/mcu/renesas/fsp/ra/fsp include $(TOP)/$(BOARD_PATH)/board.mk # Don't include options setting in .bin file since it create unnecessary large file due to padding OBJCOPY_BIN_OPTION = --only-section .text --only-section .data --only-section .rodata --only-section .bss -# Default to port 0 fullspeed, board with port 1 highspeed should override this in board.mk -PORT ?= 0 +# ---------------------- +# Port & Speed Selection +# ---------------------- +RHPORT_SPEED ?= OPT_MODE_FULL_SPEED OPT_MODE_HIGH_SPEED +RHPORT_DEVICE ?= 0 +RHPORT_HOST ?= 0 +# Determine RHPORT_DEVICE_SPEED if not defined +ifndef RHPORT_DEVICE_SPEED +ifeq ($(RHPORT_DEVICE), 0) + RHPORT_DEVICE_SPEED = $(firstword $(RHPORT_SPEED)) +else + RHPORT_DEVICE_SPEED = $(lastword $(RHPORT_SPEED)) +endif +endif + +# Determine RHPORT_HOST_SPEED if not defined +ifndef RHPORT_HOST_SPEED +ifeq ($(RHPORT_HOST), 0) + RHPORT_HOST_SPEED = $(firstword $(RHPORT_SPEED)) +else + RHPORT_HOST_SPEED = $(lastword $(RHPORT_SPEED)) +endif +endif + +# -------------- +# Compiler Flags +# -------------- CFLAGS += \ - -flto \ -DCFG_TUSB_MCU=OPT_MCU_RAXXX \ - -DBOARD_TUD_RHPORT=$(PORT) \ + -DBOARD_TUD_RHPORT=${RHPORT_DEVICE} \ + -DBOARD_TUD_MAX_SPEED=${RHPORT_DEVICE_SPEED} \ + -DBOARD_TUH_RHPORT=${RHPORT_HOST} \ + -DBOARD_TUH_MAX_SPEED=${RHPORT_HOST_SPEED} + +CFLAGS_GCC += \ + -flto \ -Wno-error=undef \ -Wno-error=strict-prototypes \ -Wno-error=cast-align \ -Wno-error=cast-qual \ -Wno-error=unused-but-set-variable \ -Wno-error=unused-variable \ - -nostdlib \ - -nostartfiles \ -ffreestanding -ifeq ($(PORT), 1) - CFLAGS += -DBOARD_TUD_MAX_SPEED=OPT_MODE_HIGH_SPEED - $(info "Using PORT 1 HighSpeed") -else - CFLAGS += -DBOARD_TUD_MAX_SPEED=OPT_MODE_FULL_SPEED - $(info "Using PORT 0 FullSpeed") -endif - -LDFLAGS_GCC += -specs=nosys.specs -specs=nano.specs +LDFLAGS_GCC += \ + -nostartfiles -nostdlib \ + -specs=nosys.specs -specs=nano.specs +# ----------------- +# Sources & Include +# ----------------- SRC_C += \ src/portable/renesas/rusb2/dcd_rusb2.c \ src/portable/renesas/rusb2/hcd_rusb2.c \ src/portable/renesas/rusb2/rusb2_common.c \ + ${BOARD_PATH}/ra_gen/common_data.c \ + ${BOARD_PATH}/ra_gen/pin_data.c \ $(FSP_RA)/src/bsp/cmsis/Device/RENESAS/Source/startup.c \ $(FSP_RA)/src/bsp/cmsis/Device/RENESAS/Source/system.c \ $(FSP_RA)/src/bsp/mcu/all/bsp_clocks.c \ @@ -53,10 +78,11 @@ SRC_C += \ $(FSP_RA)/src/r_ioport/r_ioport.c \ INC += \ - $(TOP)/lib/CMSIS_5/CMSIS/Core/Include \ $(TOP)/$(BOARD_PATH) \ - $(TOP)/$(BOARD_PATH)/fsp_cfg \ - $(TOP)/$(BOARD_PATH)/fsp_cfg/bsp \ + $(TOP)/$(BOARD_PATH)/ra_cfg/fsp_cfg \ + $(TOP)/$(BOARD_PATH)/ra_cfg/fsp_cfg/bsp \ + $(TOP)/$(BOARD_PATH)/ra_gen \ + $(TOP)/lib/CMSIS_6/CMSIS/Core/Include \ $(TOP)/$(FSP_RA)/src/bsp/cmsis/Device/RENESAS/Include \ $(TOP)/$(FSP_RA)/inc \ $(TOP)/$(FSP_RA)/inc/api \ @@ -65,10 +91,11 @@ INC += \ $(TOP)/$(FSP_RA)/src/bsp/mcu/$(MCU_VARIANT) \ ifndef LD_FILE -LD_FILE = $(FAMILY_PATH)/linker/gcc/$(MCU_VARIANT).ld +LD_FILE = $(BOARD_PATH)/script/fsp.ld endif -LDFLAGS += -L$(TOP)/$(FAMILY_PATH)/linker/gcc +LDFLAGS += -L$(TOP)/$(BOARD_PATH)/script +LDFLAGS += -Wl,--defsym=end=__bss_end__ # For freeRTOS port source # hack to use the port provided by renesas diff --git a/hw/bsp/ra/linker/gcc/ra2a1.ld b/hw/bsp/ra/linker/gcc/ra2a1.ld deleted file mode 100644 index 218acbb2a..000000000 --- a/hw/bsp/ra/linker/gcc/ra2a1.ld +++ /dev/null @@ -1,22 +0,0 @@ -RAM_START = 0x20000000; -RAM_LENGTH = 0x8000; -FLASH_START = 0x00000000; -FLASH_LENGTH = 0x40000; -DATA_FLASH_START = 0x40100000; -DATA_FLASH_LENGTH = 0x2000; -OPTION_SETTING_START = 0x00000000; -OPTION_SETTING_LENGTH = 0x0; -OPTION_SETTING_S_START = 0x80000000; -OPTION_SETTING_S_LENGTH = 0x0; -ID_CODE_START = 0x01010018; -ID_CODE_LENGTH = 0x20; -SDRAM_START = 0x80010000; -SDRAM_LENGTH = 0x0; -QSPI_FLASH_START = 0x60000000; -QSPI_FLASH_LENGTH = 0x0; -OSPI_DEVICE_0_START = 0x80020000; -OSPI_DEVICE_0_LENGTH = 0x0; -OSPI_DEVICE_1_START = 0x80030000; -OSPI_DEVICE_1_LENGTH = 0x0; - -INCLUDE fsp.ld diff --git a/hw/bsp/ra/linker/gcc/ra4m1.ld b/hw/bsp/ra/linker/gcc/ra4m1.ld deleted file mode 100644 index 218acbb2a..000000000 --- a/hw/bsp/ra/linker/gcc/ra4m1.ld +++ /dev/null @@ -1,22 +0,0 @@ -RAM_START = 0x20000000; -RAM_LENGTH = 0x8000; -FLASH_START = 0x00000000; -FLASH_LENGTH = 0x40000; -DATA_FLASH_START = 0x40100000; -DATA_FLASH_LENGTH = 0x2000; -OPTION_SETTING_START = 0x00000000; -OPTION_SETTING_LENGTH = 0x0; -OPTION_SETTING_S_START = 0x80000000; -OPTION_SETTING_S_LENGTH = 0x0; -ID_CODE_START = 0x01010018; -ID_CODE_LENGTH = 0x20; -SDRAM_START = 0x80010000; -SDRAM_LENGTH = 0x0; -QSPI_FLASH_START = 0x60000000; -QSPI_FLASH_LENGTH = 0x0; -OSPI_DEVICE_0_START = 0x80020000; -OSPI_DEVICE_0_LENGTH = 0x0; -OSPI_DEVICE_1_START = 0x80030000; -OSPI_DEVICE_1_LENGTH = 0x0; - -INCLUDE fsp.ld diff --git a/hw/bsp/ra/linker/gcc/ra4m3.ld b/hw/bsp/ra/linker/gcc/ra4m3.ld deleted file mode 100644 index 7b3a63fbe..000000000 --- a/hw/bsp/ra/linker/gcc/ra4m3.ld +++ /dev/null @@ -1,22 +0,0 @@ -RAM_START = 0x20000000; -RAM_LENGTH = 0x20000; -FLASH_START = 0x00000000; -FLASH_LENGTH = 0x100000; -DATA_FLASH_START = 0x08000000; -DATA_FLASH_LENGTH = 0x2000; -OPTION_SETTING_START = 0x0100A100; -OPTION_SETTING_LENGTH = 0x100; -OPTION_SETTING_S_START = 0x0100A200; -OPTION_SETTING_S_LENGTH = 0x100; -ID_CODE_START = 0x00000000; -ID_CODE_LENGTH = 0x0; -SDRAM_START = 0x80010000; -SDRAM_LENGTH = 0x0; -QSPI_FLASH_START = 0x60000000; -QSPI_FLASH_LENGTH = 0x4000000; -OSPI_DEVICE_0_START = 0x80020000; -OSPI_DEVICE_0_LENGTH = 0x0; -OSPI_DEVICE_1_START = 0x80030000; -OSPI_DEVICE_1_LENGTH = 0x0; - -INCLUDE fsp.ld diff --git a/hw/bsp/ra/linker/gcc/ra6m1.ld b/hw/bsp/ra/linker/gcc/ra6m1.ld deleted file mode 100644 index 91d27f74c..000000000 --- a/hw/bsp/ra/linker/gcc/ra6m1.ld +++ /dev/null @@ -1,22 +0,0 @@ -RAM_START = 0x1FFE0000; -RAM_LENGTH = 0x40000; -FLASH_START = 0x00000000; -FLASH_LENGTH = 0x80000; -DATA_FLASH_START = 0x40100000; -DATA_FLASH_LENGTH = 0x2000; -OPTION_SETTING_START = 0x00000000; -OPTION_SETTING_LENGTH = 0x0; -OPTION_SETTING_S_START = 0x80000000; -OPTION_SETTING_S_LENGTH = 0x0; -ID_CODE_START = 0x0100A150; -ID_CODE_LENGTH = 0x10; -SDRAM_START = 0x80010000; -SDRAM_LENGTH = 0x0; -QSPI_FLASH_START = 0x60000000; -QSPI_FLASH_LENGTH = 0x4000000; -OSPI_DEVICE_0_START = 0x80020000; -OSPI_DEVICE_0_LENGTH = 0x0; -OSPI_DEVICE_1_START = 0x80030000; -OSPI_DEVICE_1_LENGTH = 0x0; - -INCLUDE fsp.ld diff --git a/hw/bsp/ra/linker/gcc/ra6m5.ld b/hw/bsp/ra/linker/gcc/ra6m5.ld deleted file mode 100644 index af747fd9b..000000000 --- a/hw/bsp/ra/linker/gcc/ra6m5.ld +++ /dev/null @@ -1,22 +0,0 @@ -RAM_START = 0x20000000; -RAM_LENGTH = 0x80000; -FLASH_START = 0x00000000; -FLASH_LENGTH = 0x200000; -DATA_FLASH_START = 0x08000000; -DATA_FLASH_LENGTH = 0x2000; -OPTION_SETTING_START = 0x0100A100; -OPTION_SETTING_LENGTH = 0x100; -OPTION_SETTING_S_START = 0x0100A200; -OPTION_SETTING_S_LENGTH = 0x100; -ID_CODE_START = 0x00000000; -ID_CODE_LENGTH = 0x0; -SDRAM_START = 0x80010000; -SDRAM_LENGTH = 0x0; -QSPI_FLASH_START = 0x60000000; -QSPI_FLASH_LENGTH = 0x4000000; -OSPI_DEVICE_0_START = 0x68000000; -OSPI_DEVICE_0_LENGTH = 0x8000000; -OSPI_DEVICE_1_START = 0x70000000; -OSPI_DEVICE_1_LENGTH = 0x10000000; - -INCLUDE fsp.ld diff --git a/hw/bsp/ra/vector_data.h b/hw/bsp/ra/vector_data.h index 2b3b7d837..a85d064bd 100644 --- a/hw/bsp/ra/vector_data.h +++ b/hw/bsp/ra/vector_data.h @@ -6,6 +6,10 @@ extern "C" { #endif +#if defined(BSP_MCU_GROUP_RA6M5) || defined(BSP_MCU_GROUP_RA6M3) || (BSP_CFG_MCU_PART_SERIES == 8) +#define BOARD_HAS_USB_HIGHSPEED +#endif + /* ISR prototypes */ void usbfs_interrupt_handler(void); void usbfs_resume_handler(void); diff --git a/hw/bsp/rp2040/boards/adafruit_feather_rp2040_usb_host/board.cmake b/hw/bsp/rp2040/boards/adafruit_feather_rp2040_usb_host/board.cmake new file mode 100644 index 000000000..41897f644 --- /dev/null +++ b/hw/bsp/rp2040/boards/adafruit_feather_rp2040_usb_host/board.cmake @@ -0,0 +1,2 @@ +set(PICO_PLATFORM rp2040) +set(PICO_BOARD adafruit_feather_rp2040_usb_host) diff --git a/hw/bsp/rp2040/board.h b/hw/bsp/rp2040/boards/adafruit_feather_rp2040_usb_host/board.h similarity index 64% rename from hw/bsp/rp2040/board.h rename to hw/bsp/rp2040/boards/adafruit_feather_rp2040_usb_host/board.h index 733e93797..d003ae828 100644 --- a/hw/bsp/rp2040/board.h +++ b/hw/bsp/rp2040/boards/adafruit_feather_rp2040_usb_host/board.h @@ -1,7 +1,7 @@ /* * The MIT License (MIT) * - * Copyright (c) 2021, Ha Thach (tinyusb.org) + * Copyright (c) 2025 Ha Thach (tinyusb.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -24,55 +24,27 @@ * This file is part of the TinyUSB stack. */ -#ifndef BOARD_H_ -#define BOARD_H_ +/* metadata: + name: Adafruit Feather RP2040 with USB Type A Host + url: https://www.adafruit.com/product/5723 +*/ + +#ifndef TUSB_BOARD_H +#define TUSB_BOARD_H #ifdef __cplusplus extern "C" { #endif -// LED -#ifdef PICO_DEFAULT_LED_PIN -#define LED_PIN PICO_DEFAULT_LED_PIN -#define LED_STATE_ON (!(PICO_DEFAULT_LED_PIN_INVERTED)) -#endif - -// Button pin is BOOTSEL which is flash CS pin -#define BUTTON_BOOTSEL -#define BUTTON_STATE_ACTIVE 0 - -// UART -#if defined(PICO_DEFAULT_UART_TX_PIN) && defined(PICO_DEFAULT_UART_RX_PIN) && \ - defined(PICO_DEFAULT_UART) && defined(LIB_PICO_STDIO_UART) -#define UART_DEV PICO_DEFAULT_UART -#define UART_TX_PIN PICO_DEFAULT_UART_TX_PIN -#define UART_RX_PIN PICO_DEFAULT_UART_RX_PIN -#endif +// UART and LED are already defined in pico-sdk board //--------------------------------------------------------------------+ // PIO_USB -// default to pin on Adafruit Feather rp2040 USB Host or Tester if defined //--------------------------------------------------------------------+ -// #define USE_ADAFRUIT_FEATHER_RP2040_USBHOST -#ifdef USE_ADAFRUIT_FEATHER_RP2040_USBHOST #define PICO_DEFAULT_PIO_USB_DP_PIN 16 #define PICO_DEFAULT_PIO_USB_VBUSEN_PIN 18 -#endif - -#ifndef PICO_DEFAULT_PIO_USB_DP_PIN -#define PICO_DEFAULT_PIO_USB_DP_PIN 20 -#endif - -// VBUS enable pin and its active state -#ifndef PICO_DEFAULT_PIO_USB_VBUSEN_PIN -#define PICO_DEFAULT_PIO_USB_VBUSEN_PIN 22 -#endif - -// VBUS enable state -#ifndef PICO_DEFAULT_PIO_USB_VBUSEN_STATE #define PICO_DEFAULT_PIO_USB_VBUSEN_STATE 1 -#endif //-------------------------------------------------------------------- // USB Host MAX3421E @@ -94,4 +66,4 @@ } #endif -#endif /* BOARD_H_ */ +#endif diff --git a/hw/bsp/rp2040/boards/adafruit_fruit_jam/adafruit_fruit_jam.h b/hw/bsp/rp2040/boards/adafruit_fruit_jam/adafruit_fruit_jam.h new file mode 100644 index 000000000..2d4c689de --- /dev/null +++ b/hw/bsp/rp2040/boards/adafruit_fruit_jam/adafruit_fruit_jam.h @@ -0,0 +1,113 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2025 Ha Thach (tinyusb.org) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * This file is part of the TinyUSB stack. + */ +#ifndef BOARDS_ADAFRUIT_FRUIT_JAM_H +#define BOARDS_ADAFRUIT_FRUIT_JAM_H + +// required for board that is not part of pico-sdk + +// ----------------------------------------------------- +// NOTE: THIS HEADER IS ALSO INCLUDED BY ASSEMBLER SO +// SHOULD ONLY CONSIST OF PREPROCESSOR DIRECTIVES +// ----------------------------------------------------- + +// pico_cmake_set PICO_PLATFORM=rp2350 + +// On some samples, the xosc can take longer to stabilize than is usual +#ifndef PICO_XOSC_STARTUP_DELAY_MULTIPLIER +#define PICO_XOSC_STARTUP_DELAY_MULTIPLIER 64 +#endif + +// For board detection +#define ADAFRUIT_FRUIT_JAM + +// --- RP2350 VARIANT --- +#define PICO_RP2350A 0 + +// --- UART --- +#ifndef PICO_DEFAULT_UART +#define PICO_DEFAULT_UART 1 +#endif +#ifndef PICO_DEFAULT_UART_TX_PIN +#define PICO_DEFAULT_UART_TX_PIN 8 +#endif +#ifndef PICO_DEFAULT_UART_RX_PIN +#define PICO_DEFAULT_UART_RX_PIN 9 +#endif + +// --- LED --- +#ifndef PICO_DEFAULT_LED_PIN +#define PICO_DEFAULT_LED_PIN 29 +#endif + +#ifndef PICO_DEFAULT_WS2812_PIN +#define PICO_DEFAULT_WS2812_PIN 32 +#endif + +// --- I2C --- +#ifndef PICO_DEFAULT_I2C +#define PICO_DEFAULT_I2C 0 +#endif +#ifndef PICO_DEFAULT_I2C_SDA_PIN +#define PICO_DEFAULT_I2C_SDA_PIN 20 +#endif +#ifndef PICO_DEFAULT_I2C_SCL_PIN +#define PICO_DEFAULT_I2C_SCL_PIN 21 +#endif + +// --- SPI --- +#ifndef PICO_DEFAULT_SPI +#define PICO_DEFAULT_SPI 1 +#endif +#ifndef PICO_DEFAULT_SPI_SCK_PIN +#define PICO_DEFAULT_SPI_SCK_PIN 30 +#endif +#ifndef PICO_DEFAULT_SPI_TX_PIN +#define PICO_DEFAULT_SPI_TX_PIN 31 +#endif +#ifndef PICO_DEFAULT_SPI_RX_PIN +#define PICO_DEFAULT_SPI_RX_PIN 28 +#endif + +// --- FLASH --- + +// FruitJam use w25q128 but sdk does not have .s for it, use q080 instead +#define PICO_BOOT_STAGE2_CHOOSE_W25Q080 1 + +#ifndef PICO_FLASH_SPI_CLKDIV +#define PICO_FLASH_SPI_CLKDIV 2 +#endif + +// pico_cmake_set_default PICO_FLASH_SIZE_BYTES = (8 * 1024 * 1024) +#ifndef PICO_FLASH_SIZE_BYTES +#define PICO_FLASH_SIZE_BYTES (8 * 1024 * 1024) +#endif + +// pico_cmake_set_default PICO_RP2350_A2_SUPPORTED = 1 +#ifndef PICO_RP2350_A2_SUPPORTED +#define PICO_RP2350_A2_SUPPORTED 1 +#endif + +#endif diff --git a/hw/bsp/rp2040/boards/adafruit_fruit_jam/board.cmake b/hw/bsp/rp2040/boards/adafruit_fruit_jam/board.cmake new file mode 100644 index 000000000..4ab8a5477 --- /dev/null +++ b/hw/bsp/rp2040/boards/adafruit_fruit_jam/board.cmake @@ -0,0 +1,4 @@ +set(PICO_PLATFORM rp2350-arm-s) +set(PICO_BOARD adafruit_fruit_jam) +set(PICO_BOARD_HEADER_DIRS ${CMAKE_CURRENT_LIST_DIR}) +#set(OPENOCD_SERIAL E6614103E78E8324) diff --git a/hw/bsp/rp2040/boards/adafruit_fruit_jam/board.h b/hw/bsp/rp2040/boards/adafruit_fruit_jam/board.h new file mode 100644 index 000000000..0f53fd96f --- /dev/null +++ b/hw/bsp/rp2040/boards/adafruit_fruit_jam/board.h @@ -0,0 +1,57 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2025 Ha Thach (tinyusb.org) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * This file is part of the TinyUSB stack. + */ + +/* metadata: + name: Adafruit Fruit Jam - Mini RP2350 + url: https://www.adafruit.com/product/6200 +*/ + +#ifndef TUSB_BOARD_H +#define TUSB_BOARD_H + +#ifdef __cplusplus + extern "C" { +#endif + +// UART and LED are already defined in pico-sdk board + +//--------------------------------------------------------------------+ +// PIO_USB +//--------------------------------------------------------------------+ +// default to pico brain tester +#define PICO_DEFAULT_PIO_USB_DP_PIN 1 +#define PICO_DEFAULT_PIO_USB_VBUSEN_PIN 11 +#define PICO_DEFAULT_PIO_USB_VBUSEN_STATE 1 + +//-------------------------------------------------------------------- +// USB Host MAX3421E +//-------------------------------------------------------------------- + +#ifdef __cplusplus + } +#endif + +#endif diff --git a/hw/bsp/rp2040/boards/adafruit_metro_rp2350/adafruit_metro_rp2350.h b/hw/bsp/rp2040/boards/adafruit_metro_rp2350/adafruit_metro_rp2350.h new file mode 100644 index 000000000..9fb9658a5 --- /dev/null +++ b/hw/bsp/rp2040/boards/adafruit_metro_rp2350/adafruit_metro_rp2350.h @@ -0,0 +1,113 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2025 Ha Thach (tinyusb.org) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * This file is part of the TinyUSB stack. + */ +#ifndef BOARDS_ADAFRUIT_METRO_RP2350_H +#define BOARDS_ADAFRUIT_METRO_RP2350_H + +// required for board that is not part of pico-sdk + +// ----------------------------------------------------- +// NOTE: THIS HEADER IS ALSO INCLUDED BY ASSEMBLER SO +// SHOULD ONLY CONSIST OF PREPROCESSOR DIRECTIVES +// ----------------------------------------------------- + +// pico_cmake_set PICO_PLATFORM=rp2350 + +// On some samples, the xosc can take longer to stabilize than is usual +#ifndef PICO_XOSC_STARTUP_DELAY_MULTIPLIER +#define PICO_XOSC_STARTUP_DELAY_MULTIPLIER 64 +#endif + +// For board detection +#define ADAFRUIT_METRO_RP2350 + +// --- RP2350 VARIANT --- +#define PICO_RP2350A 0 + +// --- UART --- +#ifndef PICO_DEFAULT_UART +#define PICO_DEFAULT_UART 0 +#endif +#ifndef PICO_DEFAULT_UART_TX_PIN +#define PICO_DEFAULT_UART_TX_PIN 0 +#endif +#ifndef PICO_DEFAULT_UART_RX_PIN +#define PICO_DEFAULT_UART_RX_PIN 1 +#endif + +// --- LED --- +#ifndef PICO_DEFAULT_LED_PIN +#define PICO_DEFAULT_LED_PIN 23 +#endif + +#ifndef PICO_DEFAULT_WS2812_PIN +#define PICO_DEFAULT_WS2812_PIN 25 +#endif + +// --- I2C --- +#ifndef PICO_DEFAULT_I2C +#define PICO_DEFAULT_I2C 0 +#endif +#ifndef PICO_DEFAULT_I2C_SDA_PIN +#define PICO_DEFAULT_I2C_SDA_PIN 20 +#endif +#ifndef PICO_DEFAULT_I2C_SCL_PIN +#define PICO_DEFAULT_I2C_SCL_PIN 21 +#endif + +// --- SPI --- +#ifndef PICO_DEFAULT_SPI +#define PICO_DEFAULT_SPI 1 +#endif +#ifndef PICO_DEFAULT_SPI_SCK_PIN +#define PICO_DEFAULT_SPI_SCK_PIN 30 +#endif +#ifndef PICO_DEFAULT_SPI_TX_PIN +#define PICO_DEFAULT_SPI_TX_PIN 31 +#endif +#ifndef PICO_DEFAULT_SPI_RX_PIN +#define PICO_DEFAULT_SPI_RX_PIN 28 +#endif + +// --- FLASH --- + +// FruitJam use w25q128 but sdk does not have .s for it, use q080 instead +#define PICO_BOOT_STAGE2_CHOOSE_W25Q080 1 + +#ifndef PICO_FLASH_SPI_CLKDIV +#define PICO_FLASH_SPI_CLKDIV 2 +#endif + +// pico_cmake_set_default PICO_FLASH_SIZE_BYTES = (8 * 1024 * 1024) +#ifndef PICO_FLASH_SIZE_BYTES +#define PICO_FLASH_SIZE_BYTES (8 * 1024 * 1024) +#endif + +// pico_cmake_set_default PICO_RP2350_A2_SUPPORTED = 1 +#ifndef PICO_RP2350_A2_SUPPORTED +#define PICO_RP2350_A2_SUPPORTED 1 +#endif + +#endif diff --git a/hw/bsp/rp2040/boards/adafruit_metro_rp2350/board.cmake b/hw/bsp/rp2040/boards/adafruit_metro_rp2350/board.cmake new file mode 100644 index 000000000..9a58821a5 --- /dev/null +++ b/hw/bsp/rp2040/boards/adafruit_metro_rp2350/board.cmake @@ -0,0 +1,4 @@ +set(PICO_PLATFORM rp2350-arm-s) +set(PICO_BOARD adafruit_metro_rp2350) +set(PICO_BOARD_HEADER_DIRS ${CMAKE_CURRENT_LIST_DIR}) +#set(OPENOCD_SERIAL E6614103E78E8324) diff --git a/hw/bsp/rp2040/boards/adafruit_metro_rp2350/board.h b/hw/bsp/rp2040/boards/adafruit_metro_rp2350/board.h new file mode 100644 index 000000000..0b8515d1f --- /dev/null +++ b/hw/bsp/rp2040/boards/adafruit_metro_rp2350/board.h @@ -0,0 +1,57 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2025 Ha Thach (tinyusb.org) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * This file is part of the TinyUSB stack. + */ + +/* metadata: + name: Adafruit Metro RP2350 + url: https://www.adafruit.com/product/6003 +*/ + +#ifndef TUSB_BOARD_H +#define TUSB_BOARD_H + +#ifdef __cplusplus + extern "C" { +#endif + +// UART and LED are already defined in pico-sdk board + +//--------------------------------------------------------------------+ +// PIO_USB +//--------------------------------------------------------------------+ +// default to pico brain tester +#define PICO_DEFAULT_PIO_USB_DP_PIN 32 +#define PICO_DEFAULT_PIO_USB_VBUSEN_PIN 29 +#define PICO_DEFAULT_PIO_USB_VBUSEN_STATE 1 + +//-------------------------------------------------------------------- +// USB Host MAX3421E +//-------------------------------------------------------------------- + +#ifdef __cplusplus + } +#endif + +#endif diff --git a/hw/bsp/rp2040/boards/feather_rp2040_max3421/board.h b/hw/bsp/rp2040/boards/feather_rp2040_max3421/board.h new file mode 100644 index 000000000..f36ca14c9 --- /dev/null +++ b/hw/bsp/rp2040/boards/feather_rp2040_max3421/board.h @@ -0,0 +1,64 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2025 Ha Thach (tinyusb.org) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * This file is part of the TinyUSB stack. + */ + +#ifndef TUSB_BOARD_H +#define TUSB_BOARD_H + +#ifdef __cplusplus + extern "C" { +#endif + +// UART and LED are already defined in pico-sdk board + +//--------------------------------------------------------------------+ +// PIO_USB +//--------------------------------------------------------------------+ + +#define PICO_DEFAULT_PIO_USB_DP_PIN 16 +#define PICO_DEFAULT_PIO_USB_VBUSEN_PIN 18 +#define PICO_DEFAULT_PIO_USB_VBUSEN_STATE 1 + +//-------------------------------------------------------------------- +// USB Host MAX3421E +//-------------------------------------------------------------------- + +#ifdef PICO_DEFAULT_SPI +#define MAX3421_SPI PICO_DEFAULT_SPI // sdk v2 +#else +#define MAX3421_SPI PICO_DEFAULT_SPI_INSTANCE // sdk v1 +#endif + +#define MAX3421_SCK_PIN PICO_DEFAULT_SPI_SCK_PIN +#define MAX3421_MOSI_PIN PICO_DEFAULT_SPI_TX_PIN +#define MAX3421_MISO_PIN PICO_DEFAULT_SPI_RX_PIN +#define MAX3421_CS_PIN 10 +#define MAX3421_INTR_PIN 9 + +#ifdef __cplusplus + } +#endif + +#endif diff --git a/hw/bsp/rp2040/boards/pico_sdk/board.h b/hw/bsp/rp2040/boards/pico_sdk/board.h new file mode 100644 index 000000000..284edac7d --- /dev/null +++ b/hw/bsp/rp2040/boards/pico_sdk/board.h @@ -0,0 +1,40 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2025 Ha Thach (tinyusb.org) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * This file is part of the TinyUSB stack. + */ + +#ifndef TUSB_BOARD_H +#define TUSB_BOARD_H + +#ifdef __cplusplus + extern "C" { +#endif + +// UART and LED are already defined in pico-sdk board + +#ifdef __cplusplus + } +#endif + +#endif diff --git a/hw/bsp/rp2040/boards/raspberry_pi_pico/board.cmake b/hw/bsp/rp2040/boards/raspberry_pi_pico/board.cmake index 804cdb50a..2d739291c 100644 --- a/hw/bsp/rp2040/boards/raspberry_pi_pico/board.cmake +++ b/hw/bsp/rp2040/boards/raspberry_pi_pico/board.cmake @@ -1,2 +1,3 @@ set(PICO_PLATFORM rp2040) set(PICO_BOARD pico) +#set(OPENOCD_SERIAL E6614103E719612F) diff --git a/hw/bsp/rp2040/boards/raspberry_pi_pico/board.h b/hw/bsp/rp2040/boards/raspberry_pi_pico/board.h new file mode 100644 index 000000000..88f8793f4 --- /dev/null +++ b/hw/bsp/rp2040/boards/raspberry_pi_pico/board.h @@ -0,0 +1,69 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2025 Ha Thach (tinyusb.org) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * This file is part of the TinyUSB stack. + */ + +/* metadata: + name: Pico + url: https://www.raspberrypi.com/products/raspberry-pi-pico/ +*/ + +#ifndef TUSB_BOARD_H +#define TUSB_BOARD_H + +#ifdef __cplusplus + extern "C" { +#endif + +// UART and LED are already defined in pico-sdk board + +//--------------------------------------------------------------------+ +// PIO_USB +//--------------------------------------------------------------------+ +// default to pico brain tester +#define PICO_DEFAULT_PIO_USB_DP_PIN 20 +#define PICO_DEFAULT_PIO_USB_VBUSEN_PIN 22 +#define PICO_DEFAULT_PIO_USB_VBUSEN_STATE 1 + +//-------------------------------------------------------------------- +// USB Host MAX3421E +//-------------------------------------------------------------------- + +#ifdef PICO_DEFAULT_SPI +#define MAX3421_SPI PICO_DEFAULT_SPI // sdk v2 +#else +#define MAX3421_SPI PICO_DEFAULT_SPI_INSTANCE // sdk v1 +#endif + +#define MAX3421_SCK_PIN PICO_DEFAULT_SPI_SCK_PIN +#define MAX3421_MOSI_PIN PICO_DEFAULT_SPI_TX_PIN +#define MAX3421_MISO_PIN PICO_DEFAULT_SPI_RX_PIN +#define MAX3421_CS_PIN 10 +#define MAX3421_INTR_PIN 9 + +#ifdef __cplusplus + } +#endif + +#endif diff --git a/hw/bsp/rp2040/boards/raspberry_pi_pico2/board.cmake b/hw/bsp/rp2040/boards/raspberry_pi_pico2/board.cmake index 3482e2674..0a7dd4d23 100644 --- a/hw/bsp/rp2040/boards/raspberry_pi_pico2/board.cmake +++ b/hw/bsp/rp2040/boards/raspberry_pi_pico2/board.cmake @@ -1,2 +1,3 @@ set(PICO_PLATFORM rp2350-arm-s) set(PICO_BOARD pico2) +#set(OPENOCD_SERIAL E6614103E77C5A24) diff --git a/hw/bsp/rp2040/boards/raspberry_pi_pico2/board.h b/hw/bsp/rp2040/boards/raspberry_pi_pico2/board.h new file mode 100644 index 000000000..b5ce8b7e1 --- /dev/null +++ b/hw/bsp/rp2040/boards/raspberry_pi_pico2/board.h @@ -0,0 +1,69 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2025 Ha Thach (tinyusb.org) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * This file is part of the TinyUSB stack. + */ + +/* metadata: + name: Pico2 + url: https://www.raspberrypi.com/products/raspberry-pi-pico-2/ +*/ + +#ifndef TUSB_BOARD_H +#define TUSB_BOARD_H + +#ifdef __cplusplus + extern "C" { +#endif + +// UART and LED are already defined in pico-sdk board + +//--------------------------------------------------------------------+ +// PIO_USB +//--------------------------------------------------------------------+ +// default to pico brain tester +#define PICO_DEFAULT_PIO_USB_DP_PIN 20 +#define PICO_DEFAULT_PIO_USB_VBUSEN_PIN 22 +#define PICO_DEFAULT_PIO_USB_VBUSEN_STATE 1 + +//-------------------------------------------------------------------- +// USB Host MAX3421E +//-------------------------------------------------------------------- + +#ifdef PICO_DEFAULT_SPI +#define MAX3421_SPI PICO_DEFAULT_SPI // sdk v2 +#else +#define MAX3421_SPI PICO_DEFAULT_SPI_INSTANCE // sdk v1 +#endif + +#define MAX3421_SCK_PIN PICO_DEFAULT_SPI_SCK_PIN +#define MAX3421_MOSI_PIN PICO_DEFAULT_SPI_TX_PIN +#define MAX3421_MISO_PIN PICO_DEFAULT_SPI_RX_PIN +#define MAX3421_CS_PIN 10 +#define MAX3421_INTR_PIN 9 + +#ifdef __cplusplus + } +#endif + +#endif diff --git a/hw/bsp/rp2040/boards/raspberry_pi_pico_w/board.cmake b/hw/bsp/rp2040/boards/raspberry_pi_pico_w/board.cmake new file mode 100644 index 000000000..97621d855 --- /dev/null +++ b/hw/bsp/rp2040/boards/raspberry_pi_pico_w/board.cmake @@ -0,0 +1,2 @@ +set(PICO_PLATFORM rp2040) +set(PICO_BOARD pico_w) diff --git a/hw/bsp/rp2040/boards/raspberry_pi_pico_w/board.h b/hw/bsp/rp2040/boards/raspberry_pi_pico_w/board.h new file mode 100644 index 000000000..8af32fc9e --- /dev/null +++ b/hw/bsp/rp2040/boards/raspberry_pi_pico_w/board.h @@ -0,0 +1,70 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2025 Ha Thach (tinyusb.org) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * This file is part of the TinyUSB stack. + */ + +/* metadata: + name: Pico + url: https://www.raspberrypi.com/products/raspberry-pi-pico/ +*/ + +#ifndef TUSB_BOARD_H +#define TUSB_BOARD_H + +#ifdef __cplusplus + extern "C" { +#endif + +// UART and LED are already defined in pico-sdk board + +//--------------------------------------------------------------------+ +// PIO_USB +//--------------------------------------------------------------------+ +// default to pico brain tester +#define PICO_DEFAULT_PIO_USB_DP_PIN 20 +#define PICO_DEFAULT_PIO_USB_VBUSEN_PIN 22 +#define PICO_DEFAULT_PIO_USB_VBUSEN_STATE 1 + +//-------------------------------------------------------------------- +// USB Host MAX3421E +//-------------------------------------------------------------------- + +#ifdef PICO_DEFAULT_SPI +#define MAX3421_SPI PICO_DEFAULT_SPI // sdk v2 +#else +#define MAX3421_SPI PICO_DEFAULT_SPI_INSTANCE // sdk v1 +#endif + +#define MAX3421_SCK_PIN PICO_DEFAULT_SPI_SCK_PIN +#define MAX3421_MOSI_PIN PICO_DEFAULT_SPI_TX_PIN +#define MAX3421_MISO_PIN PICO_DEFAULT_SPI_RX_PIN +#define MAX3421_CS_PIN 10 +#define MAX3421_INTR_PIN 9 + + +#ifdef __cplusplus + } +#endif + +#endif diff --git a/hw/bsp/rp2040/family.c b/hw/bsp/rp2040/family.c index 452a5568f..a22924131 100644 --- a/hw/bsp/rp2040/family.c +++ b/hw/bsp/rp2040/family.c @@ -25,6 +25,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: Raspberry Pi +*/ + #include "pico/stdlib.h" #include "pico/binary_info.h" #include "pico/unique_id.h" @@ -38,10 +42,6 @@ #include "bsp/board_api.h" #include "board.h" -#ifdef UART_DEV -static uart_inst_t *uart_inst; -#endif - #if (CFG_TUH_ENABLED && CFG_TUH_RPI_PIO_USB) || (CFG_TUD_ENABLED && CFG_TUD_RPI_PIO_USB) #include "pio_usb.h" #endif @@ -51,6 +51,36 @@ static uart_inst_t *uart_inst; static void max3421_init(void); #endif +//--------------------------------------------------------------------+ +// +//--------------------------------------------------------------------+ +// LED +#if !defined(LED_PIN) && defined(PICO_DEFAULT_LED_PIN) +#define LED_PIN PICO_DEFAULT_LED_PIN +#define LED_STATE_ON (!(PICO_DEFAULT_LED_PIN_INVERTED)) +#endif + +// Button, if not defined use BOOTSEL button +#ifndef BUTTON_PIN +#define BUTTON_BOOTSEL +#define BUTTON_STATE_ACTIVE 0 +#endif + +// UART +#if !defined(UART_DEV) && defined(PICO_DEFAULT_UART) && defined(LIB_PICO_STDIO_UART) && \ + defined(PICO_DEFAULT_UART_TX_PIN) && defined(PICO_DEFAULT_UART_RX_PIN) +#define UART_DEV PICO_DEFAULT_UART +#define UART_TX_PIN PICO_DEFAULT_UART_TX_PIN +#define UART_RX_PIN PICO_DEFAULT_UART_RX_PIN +#endif + +#ifdef UART_DEV +static uart_inst_t *uart_inst; +#endif + +//--------------------------------------------------------------------+ +// +//--------------------------------------------------------------------+ #ifdef BUTTON_BOOTSEL // This example blinks the Picoboard LED when the BOOTSEL button is pressed. // @@ -75,7 +105,7 @@ bool __no_inline_not_in_flash_func(get_bootsel_button)(void) { IO_QSPI_GPIO_QSPI_SS_CTRL_OEOVER_BITS); // Note we can't call into any sleep functions in flash right now - for (volatile int i = 0; i < 1000; ++i); + for (volatile int i = 0; i < 1000; ++i) {} // The HI GPIO registers in SIO can observe and control the 6 QSPI pins. // Note the button pulls the pin *low* when pressed. @@ -129,12 +159,15 @@ void stdio_rtt_init(void) { //--------------------------------------------------------------------+ // //--------------------------------------------------------------------+ - void board_init(void) { #if (CFG_TUH_ENABLED && CFG_TUH_RPI_PIO_USB) || (CFG_TUD_ENABLED && CFG_TUD_RPI_PIO_USB) - // Set the system clock to a multiple of 120mhz for bitbanging USB with pico-usb + // Set the system clock to a multiple of 12mhz for bit-banging USB with pico-usb set_sys_clock_khz(120000, true); + // set_sys_clock_khz(180000, true); + // set_sys_clock_khz(192000, true); + // set_sys_clock_khz(240000, true); + // set_sys_clock_khz(264000, true); #ifdef PICO_DEFAULT_PIO_USB_VBUSEN_PIN gpio_init(PICO_DEFAULT_PIO_USB_VBUSEN_PIN); @@ -189,7 +222,6 @@ void board_init(void) //--------------------------------------------------------------------+ // Board porting API //--------------------------------------------------------------------+ - void board_led_write(bool state) { (void) state; @@ -222,7 +254,7 @@ size_t board_get_unique_id(uint8_t id[], size_t max_len) { int board_uart_read(uint8_t *buf, int len) { #ifdef UART_DEV int count = 0; - while ( (count < len) && uart_is_readable(uart_inst) ) { + while ((count < len) && uart_is_readable(uart_inst)) { buf[count] = uart_getc(uart_inst); count++; } @@ -250,6 +282,10 @@ int board_getchar(void) { return getchar_timeout_us(0); } +void board_putchar(int c) { + stdio_putchar(c); +} + //--------------------------------------------------------------------+ // USB Interrupt Handler // rp2040 implementation will install appropriate handler when initializing @@ -262,7 +298,9 @@ int board_getchar(void) { #if CFG_TUH_ENABLED && defined(CFG_TUH_MAX3421) && CFG_TUH_MAX3421 void max3421_int_handler(uint gpio, uint32_t event_mask) { - if (!(gpio == MAX3421_INTR_PIN && event_mask & GPIO_IRQ_EDGE_FALL)) return; + if (!(gpio == MAX3421_INTR_PIN && event_mask & GPIO_IRQ_EDGE_FALL)) { + return; + } tuh_int_handler(BOARD_TUH_RHPORT, true); } diff --git a/hw/bsp/rp2040/family.cmake b/hw/bsp/rp2040/family.cmake index b2b01b1cf..2182e9ad1 100644 --- a/hw/bsp/rp2040/family.cmake +++ b/hw/bsp/rp2040/family.cmake @@ -31,7 +31,9 @@ elseif (PICO_PLATFORM STREQUAL "rp2350-riscv") set(OPENOCD_TARGET rp2350-riscv) endif() -set(OPENOCD_OPTION "-f interface/cmsis-dap.cfg -f target/${OPENOCD_TARGET}.cfg -c \"adapter speed 5000\"") +if (NOT OPENOCD_OPTION) + set(OPENOCD_OPTION "-f interface/cmsis-dap.cfg -f target/${OPENOCD_TARGET}.cfg -c \"adapter speed 5000\"") +endif() if (NOT PICO_TINYUSB_PATH) set(PICO_TINYUSB_PATH ${TOP}) @@ -111,6 +113,7 @@ target_sources(tinyusb_host_base INTERFACE ${TOP}/src/host/hub.c ${TOP}/src/class/cdc/cdc_host.c ${TOP}/src/class/hid/hid_host.c + ${TOP}/src/class/midi/midi_host.c ${TOP}/src/class/msc/msc_host.c ${TOP}/src/class/vendor/vendor_host.c ) @@ -143,6 +146,7 @@ target_sources(tinyusb_bsp INTERFACE ) target_include_directories(tinyusb_bsp INTERFACE ${TOP}/hw + ${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD} ) target_link_libraries(tinyusb_bsp INTERFACE pico_unique_id diff --git a/hw/bsp/rp2040/family.mk b/hw/bsp/rp2040/family.mk deleted file mode 100644 index 25d1ad9c5..000000000 --- a/hw/bsp/rp2040/family.mk +++ /dev/null @@ -1,18 +0,0 @@ -JLINK_DEVICE = rp2040_m0_0 -PYOCD_TARGET = rp2040 - -DEPS_SUBMODULES += hw/mcu/raspberry_pi/Pico-PIO-USB - -ifeq ($(DEBUG), 1) -CMAKE_DEFSYM += -DCMAKE_BUILD_TYPE=Debug -endif - -$(BUILD): - cmake -S . -B $(BUILD) -DFAMILY=$(FAMILY) -DBOARD=$(BOARD) -DPICO_BUILD_DOCS=0 $(CMAKE_DEFSYM) - -all: $(BUILD) - $(MAKE) -C $(BUILD) - -flash: flash-pyocd -flash-uf2: - @$(CP) $(BUILD)/$(PROJECT).uf2 /media/$(USER)/RPI-RP2 diff --git a/hw/bsp/rp2040/rp2350-openocd.cfg b/hw/bsp/rp2040/rp2350-openocd.cfg new file mode 100644 index 000000000..52c71cd99 --- /dev/null +++ b/hw/bsp/rp2040/rp2350-openocd.cfg @@ -0,0 +1,3 @@ +source [find interface/cmsis-dap.cfg] +adapter speed 5000 +source [find target/rp2350.cfg] diff --git a/hw/bsp/rp2040/skip_ci.txt b/hw/bsp/rp2040/skip_ci.txt new file mode 100644 index 000000000..fe99c9f65 --- /dev/null +++ b/hw/bsp/rp2040/skip_ci.txt @@ -0,0 +1,7 @@ +# boards in this files are skipped when running CI with this family +adafruit_feather_rp2040_usb_host +adafruit_fruit_jam +adafruit_metro_rp2350 +feather_rp2040_max3421 +pico_sdk +raspberry_pi_pico_w diff --git a/hw/bsp/rx/boards/gr_citrus/board.h b/hw/bsp/rx/boards/gr_citrus/board.h new file mode 100644 index 000000000..617d309c3 --- /dev/null +++ b/hw/bsp/rx/boards/gr_citrus/board.h @@ -0,0 +1,43 @@ +/* +* The MIT License (MIT) + * + * Copyright (c) 2020, Ha Thach (tinyusb.org) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * This file is part of the TinyUSB stack. + */ + +/* metadata: + name: GR Citrus + url: https://www.renesas.com/en/products/gadget-renesas/boards/gr-citrus +*/ + +#ifndef BOARD_H_ +#define BOARD_H_ + +#ifdef __cplusplus + extern "C" { +#endif + +#ifdef __cplusplus + } +#endif + +#endif /* BOARD_H_ */ diff --git a/hw/bsp/rx/boards/rx65n_target/board.h b/hw/bsp/rx/boards/rx65n_target/board.h new file mode 100644 index 000000000..8c8e7b95f --- /dev/null +++ b/hw/bsp/rx/boards/rx65n_target/board.h @@ -0,0 +1,43 @@ +/* +* The MIT License (MIT) + * + * Copyright (c) 2020, Ha Thach (tinyusb.org) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * This file is part of the TinyUSB stack. + */ + +/* metadata: + name: RX65N Target Board + url: https://www.renesas.com/en/products/microcontrollers-microprocessors/rx-32-bit-performance-efficiency-mcus/rtk5rx65n0c00000br-target-board-rx65n +*/ + +#ifndef BOARD_H_ +#define BOARD_H_ + +#ifdef __cplusplus + extern "C" { +#endif + +#ifdef __cplusplus + } +#endif + +#endif /* BOARD_H_ */ diff --git a/hw/bsp/rx/family.mk b/hw/bsp/rx/family.mk index 02ea0dfa4..4ecf80409 100644 --- a/hw/bsp/rx/family.mk +++ b/hw/bsp/rx/family.mk @@ -1,5 +1,3 @@ -DEPS_SUBMODULES += hw/mcu/renesas/rx - # Cross Compiler for RX CROSS_COMPILE = rx-elf- diff --git a/hw/bsp/samd11/boards/cynthion_d11/board.h b/hw/bsp/samd11/boards/cynthion_d11/board.h index b13c8eeea..8916e9b83 100644 --- a/hw/bsp/samd11/boards/cynthion_d11/board.h +++ b/hw/bsp/samd11/boards/cynthion_d11/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Great Scott Gadgets Cynthion + url: https://greatscottgadgets.com/cynthion/ +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/samd11/boards/samd11_xplained/board.h b/hw/bsp/samd11/boards/samd11_xplained/board.h index 2bbec4958..13045ac1d 100644 --- a/hw/bsp/samd11/boards/samd11_xplained/board.h +++ b/hw/bsp/samd11/boards/samd11_xplained/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: SAMD11 Xplained Pro + url: https://www.microchip.com/en-us/development-tool/ATSAMD11-XPRO +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/samd11/family.c b/hw/bsp/samd11/family.c index a6588805a..79ca9de02 100644 --- a/hw/bsp/samd11/family.c +++ b/hw/bsp/samd11/family.c @@ -24,6 +24,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: Microchip +*/ + #include "sam.h" // Suppress warning caused by mcu driver diff --git a/hw/bsp/samd11/family.cmake b/hw/bsp/samd11/family.cmake index c9ccc86f8..965b1cfb5 100644 --- a/hw/bsp/samd11/family.cmake +++ b/hw/bsp/samd11/family.cmake @@ -7,7 +7,7 @@ set(CMSIS_5 ${TOP}/lib/CMSIS_5) include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) # toolchain set up -set(CMAKE_SYSTEM_PROCESSOR cortex-m0plus CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU cortex-m0plus CACHE INTERNAL "System Processor") set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) set(FAMILY_MCUS SAMD11 CACHE INTERNAL "") @@ -100,14 +100,13 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_SAMD11 ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC + family_add_tinyusb(${TARGET} OPT_MCU_SAMD11) + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/microchip/samd/dcd_samd.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) # Flashing family_add_bin_hex(${TARGET}) diff --git a/hw/bsp/samd21/boards/atsamd21_xpro/board.h b/hw/bsp/samd21/boards/atsamd21_xpro/board.h index 315e40c78..6d2e40c56 100644 --- a/hw/bsp/samd21/boards/atsamd21_xpro/board.h +++ b/hw/bsp/samd21/boards/atsamd21_xpro/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: SAMD21 Xplained Pro + url: https://www.microchip.com/DevelopmentTools/ProductDetails/ATSAMD21-XPRO +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/samd21/boards/circuitplayground_express/board.h b/hw/bsp/samd21/boards/circuitplayground_express/board.h index 0037db00d..6a4ec32a9 100644 --- a/hw/bsp/samd21/boards/circuitplayground_express/board.h +++ b/hw/bsp/samd21/boards/circuitplayground_express/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Adafruit Circuit Playground Express + url: https://www.adafruit.com/product/3333 +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/samd21/boards/curiosity_nano/board.h b/hw/bsp/samd21/boards/curiosity_nano/board.h index 1a4a833a3..78d701ec9 100644 --- a/hw/bsp/samd21/boards/curiosity_nano/board.h +++ b/hw/bsp/samd21/boards/curiosity_nano/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: SAMD21 Curiosty Nano + url: https://www.microchip.com/en-us/development-tool/dm320119 +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/samd21/boards/cynthion_d21/board.h b/hw/bsp/samd21/boards/cynthion_d21/board.h index 776063636..6a2b8c5c6 100644 --- a/hw/bsp/samd21/boards/cynthion_d21/board.h +++ b/hw/bsp/samd21/boards/cynthion_d21/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Great Scott Gadgets Cynthion + url: https://greatscottgadgets.com/cynthion/ +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/samd21/boards/feather_m0_express/board.h b/hw/bsp/samd21/boards/feather_m0_express/board.h index 56ae3230d..a7f9122ee 100644 --- a/hw/bsp/samd21/boards/feather_m0_express/board.h +++ b/hw/bsp/samd21/boards/feather_m0_express/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Adafruit Feather M0 Express + url: https://www.adafruit.com/product/3403 +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/samd21/boards/itsybitsy_m0/board.h b/hw/bsp/samd21/boards/itsybitsy_m0/board.h index 6ee814da5..15a0afb15 100644 --- a/hw/bsp/samd21/boards/itsybitsy_m0/board.h +++ b/hw/bsp/samd21/boards/itsybitsy_m0/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Adafruit ItsyBitsy M0 + url: https://www.adafruit.com/product/3727 +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/samd21/boards/metro_m0_express/board.h b/hw/bsp/samd21/boards/metro_m0_express/board.h index 6dd53e901..405c92b02 100644 --- a/hw/bsp/samd21/boards/metro_m0_express/board.h +++ b/hw/bsp/samd21/boards/metro_m0_express/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Adafruit Metro M0 Express + url: https://www.adafruit.com/product/3505 +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/samd21/boards/qtpy/board.h b/hw/bsp/samd21/boards/qtpy/board.h index 9ba39e966..29a9f727f 100644 --- a/hw/bsp/samd21/boards/qtpy/board.h +++ b/hw/bsp/samd21/boards/qtpy/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Adafruit QT Py + url: https://www.adafruit.com/product/4600 +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/samd21/boards/seeeduino_xiao/board.h b/hw/bsp/samd21/boards/seeeduino_xiao/board.h index 1bd63d6d9..0a6d1fc7d 100644 --- a/hw/bsp/samd21/boards/seeeduino_xiao/board.h +++ b/hw/bsp/samd21/boards/seeeduino_xiao/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Seeeduino XIAO + url: https://wiki.seeedstudio.com/Seeeduino-XIAO/ +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/samd21/boards/sparkfun_samd21_mini_usb/board.h b/hw/bsp/samd21/boards/sparkfun_samd21_mini_usb/board.h index 60a86d743..85be34008 100644 --- a/hw/bsp/samd21/boards/sparkfun_samd21_mini_usb/board.h +++ b/hw/bsp/samd21/boards/sparkfun_samd21_mini_usb/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: SparkFun SAMD21 Mini + url: https://www.sparkfun.com/products/13664 +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/samd21/boards/trinket_m0/board.h b/hw/bsp/samd21/boards/trinket_m0/board.h index c94a3abb6..22e7cb77f 100644 --- a/hw/bsp/samd21/boards/trinket_m0/board.h +++ b/hw/bsp/samd21/boards/trinket_m0/board.h @@ -23,6 +23,11 @@ * */ +/* metadata: + name: Adafruit Trinket M0 + url: https://www.adafruit.com/product/3500 +*/ + #pragma once // LED diff --git a/hw/bsp/samd21/family.c b/hw/bsp/samd21/family.c index 7ca20c458..c360a4a5a 100644 --- a/hw/bsp/samd21/family.c +++ b/hw/bsp/samd21/family.c @@ -24,6 +24,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: Microchip +*/ + #include "sam.h" #include "bsp/board_api.h" #include "board.h" diff --git a/hw/bsp/samd21/family.cmake b/hw/bsp/samd21/family.cmake index c836b85d9..4a10d6224 100644 --- a/hw/bsp/samd21/family.cmake +++ b/hw/bsp/samd21/family.cmake @@ -6,7 +6,7 @@ set(SDK_DIR ${TOP}/hw/mcu/microchip/samd21) include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) # toolchain set up -set(CMAKE_SYSTEM_PROCESSOR cortex-m0plus CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU cortex-m0plus CACHE INTERNAL "System Processor") set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) set(FAMILY_MCUS SAMD21 CACHE INTERNAL "") @@ -96,14 +96,11 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_SAMD21 ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC + family_add_tinyusb(${TARGET} OPT_MCU_SAMD21) + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/microchip/samd/dcd_samd.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) - - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) # Flashing family_add_bin_hex(${TARGET}) diff --git a/hw/bsp/samd5x_e5x/boards/d5035_01/board.h b/hw/bsp/samd5x_e5x/boards/d5035_01/board.h index 2cf59f5d1..4eb4a4ebe 100644 --- a/hw/bsp/samd5x_e5x/boards/d5035_01/board.h +++ b/hw/bsp/samd5x_e5x/boards/d5035_01/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: D5035-01 + url: https://github.com/RudolphRiedel/USB_CAN-FD +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/samd5x_e5x/boards/feather_m4_express/board.h b/hw/bsp/samd5x_e5x/boards/feather_m4_express/board.h index 83de04266..edb965c9d 100644 --- a/hw/bsp/samd5x_e5x/boards/feather_m4_express/board.h +++ b/hw/bsp/samd5x_e5x/boards/feather_m4_express/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Adafruit Feather M4 Express + url: https://www.adafruit.com/product/3857 +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/samd5x_e5x/boards/itsybitsy_m4/board.h b/hw/bsp/samd5x_e5x/boards/itsybitsy_m4/board.h index 272315771..d41ca4ac3 100644 --- a/hw/bsp/samd5x_e5x/boards/itsybitsy_m4/board.h +++ b/hw/bsp/samd5x_e5x/boards/itsybitsy_m4/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Adafruit ItsyBitsy M4 + url: https://www.adafruit.com/product/3800 +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/samd5x_e5x/boards/metro_m4_express/board.h b/hw/bsp/samd5x_e5x/boards/metro_m4_express/board.h index b3b80db89..b2eaaa54d 100644 --- a/hw/bsp/samd5x_e5x/boards/metro_m4_express/board.h +++ b/hw/bsp/samd5x_e5x/boards/metro_m4_express/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Adafruit Metro M4 Express + url: https://www.adafruit.com/product/3382 +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/samd5x_e5x/boards/pybadge/board.h b/hw/bsp/samd5x_e5x/boards/pybadge/board.h index 4629643fd..a5d447db6 100644 --- a/hw/bsp/samd5x_e5x/boards/pybadge/board.h +++ b/hw/bsp/samd5x_e5x/boards/pybadge/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Adafruit PyBadge + url: https://www.adafruit.com/product/4200 +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/samd5x_e5x/boards/pyportal/board.h b/hw/bsp/samd5x_e5x/boards/pyportal/board.h index ff04c900b..e635e1375 100644 --- a/hw/bsp/samd5x_e5x/boards/pyportal/board.h +++ b/hw/bsp/samd5x_e5x/boards/pyportal/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Adafruit PyPortal + url: https://www.adafruit.com/product/4116 +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/samd5x_e5x/boards/same54_xplained/board.h b/hw/bsp/samd5x_e5x/boards/same54_xplained/board.h index faaa52b8e..6c252f9d0 100644 --- a/hw/bsp/samd5x_e5x/boards/same54_xplained/board.h +++ b/hw/bsp/samd5x_e5x/boards/same54_xplained/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: SAME54 Xplained Pro + url: https://www.microchip.com/DevelopmentTools/ProductDetails/ATSAME54-XPRO +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/samd5x_e5x/family.c b/hw/bsp/samd5x_e5x/family.c index abaee353b..8ceddb1be 100644 --- a/hw/bsp/samd5x_e5x/family.c +++ b/hw/bsp/samd5x_e5x/family.c @@ -24,6 +24,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: Microchip +*/ + #include "sam.h" #include "bsp/board_api.h" #include "board.h" diff --git a/hw/bsp/samd5x_e5x/family.cmake b/hw/bsp/samd5x_e5x/family.cmake index fd95ce10e..50e0ec66d 100644 --- a/hw/bsp/samd5x_e5x/family.cmake +++ b/hw/bsp/samd5x_e5x/family.cmake @@ -6,7 +6,7 @@ set(SDK_DIR ${TOP}/hw/mcu/microchip/${SAM_FAMILY}) set(CMSIS_5 ${TOP}/lib/CMSIS_5) # toolchain set up -set(CMAKE_SYSTEM_PROCESSOR cortex-m4 CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU cortex-m4 CACHE INTERNAL "System Processor") set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) set(FAMILY_MCUS SAMD51 SAME54 CACHE INTERNAL "") @@ -93,14 +93,11 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_SAMD51 ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC + family_add_tinyusb(${TARGET} OPT_MCU_SAMD51) + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/microchip/samd/dcd_samd.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) - - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) # Flashing family_add_bin_hex(${TARGET}) diff --git a/hw/bsp/same70_qmtech/board.mk b/hw/bsp/same70_qmtech/board.mk index 281a947f3..7e949e135 100644 --- a/hw/bsp/same70_qmtech/board.mk +++ b/hw/bsp/same70_qmtech/board.mk @@ -1,4 +1,3 @@ -DEPS_SUBMODULES += hw/mcu/microchip ASF_DIR = hw/mcu/microchip/same70 CFLAGS += \ diff --git a/hw/bsp/same70_xplained/board.mk b/hw/bsp/same70_xplained/board.mk index 3edc128a5..2d97ecdc1 100644 --- a/hw/bsp/same70_xplained/board.mk +++ b/hw/bsp/same70_xplained/board.mk @@ -1,4 +1,3 @@ -DEPS_SUBMODULES += hw/mcu/microchip ASF_DIR = hw/mcu/microchip/same70 CFLAGS += \ @@ -14,6 +13,14 @@ CFLAGS += \ # suppress following warnings from mcu driver CFLAGS += -Wno-error=unused-parameter -Wno-error=cast-align -Wno-error=redundant-decls +SPEED ?= high + +ifeq ($(SPEED), high) + CFLAGS += -DBOARD_TUD_MAX_SPEED=OPT_MODE_HIGH_SPEED +else + CFLAGS += -DBOARD_TUD_MAX_SPEED=OPT_MODE_FULL_SPEED +endif + # SAM driver is flooded with -Wcast-qual which slow down complication significantly CFLAGS_SKIP += -Wcast-qual diff --git a/hw/bsp/samg/boards/samg55_xplained/board.h b/hw/bsp/samg/boards/samg55_xplained/board.h index c94cda198..53c557ef0 100644 --- a/hw/bsp/samg/boards/samg55_xplained/board.h +++ b/hw/bsp/samg/boards/samg55_xplained/board.h @@ -1,3 +1,8 @@ +/* metadata: + name: SAMG55 Xplained Pro + url: https://www.microchip.com/DevelopmentTools/ProductDetails/ATSAMG55-XPRO +*/ + #ifndef BOARD_H #define BOARD_H diff --git a/hw/bsp/samg/family.c b/hw/bsp/samg/family.c index 63db5739d..8db429e79 100644 --- a/hw/bsp/samg/family.c +++ b/hw/bsp/samg/family.c @@ -23,6 +23,10 @@ * */ +/* metadata: + manufacturer: Microchip +*/ + #include "sam.h" // Suppress warning caused by mcu driver diff --git a/hw/bsp/samg/family.cmake b/hw/bsp/samg/family.cmake index 1cc715ce6..eb00c8c52 100644 --- a/hw/bsp/samg/family.cmake +++ b/hw/bsp/samg/family.cmake @@ -7,7 +7,7 @@ set(SDK_DIR ${TOP}/hw/mcu/microchip/samg55) include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) # toolchain set up -set(CMAKE_SYSTEM_PROCESSOR cortex-m4 CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU cortex-m4 CACHE INTERNAL "System Processor") set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) set(FAMILY_MCUS SAMG CACHE INTERNAL "") @@ -98,14 +98,13 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_SAMG ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC + family_add_tinyusb(${TARGET} OPT_MCU_SAMG) + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/microchip/samg/dcd_samg.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) # Flashing family_add_bin_hex(${TARGET}) diff --git a/hw/bsp/saml2x/boards/atsaml21_xpro/board.h b/hw/bsp/saml2x/boards/atsaml21_xpro/board.h index 315e40c78..b93b4e591 100644 --- a/hw/bsp/saml2x/boards/atsaml21_xpro/board.h +++ b/hw/bsp/saml2x/boards/atsaml21_xpro/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: SAML21 Xplained Pro + url: https://www.microchip.com/en-us/development-tool/atsaml21-xpro-b +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/saml2x/boards/saml22_feather/board.h b/hw/bsp/saml2x/boards/saml22_feather/board.h index 72e9897b6..f8660c3f8 100644 --- a/hw/bsp/saml2x/boards/saml22_feather/board.h +++ b/hw/bsp/saml2x/boards/saml22_feather/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: SAML22 Feather + url: https://github.com/joeycastillo/Feather-Projects/tree/main/SAML22%20Feather +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/saml2x/boards/sensorwatch_m0/board.h b/hw/bsp/saml2x/boards/sensorwatch_m0/board.h index 735f6afc8..502c799db 100644 --- a/hw/bsp/saml2x/boards/sensorwatch_m0/board.h +++ b/hw/bsp/saml2x/boards/sensorwatch_m0/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: SensorWatch + url: https://github.com/joeycastillo/Sensor-Watch +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/saml2x/family.c b/hw/bsp/saml2x/family.c index 11977b036..cdc65baf1 100644 --- a/hw/bsp/saml2x/family.c +++ b/hw/bsp/saml2x/family.c @@ -24,6 +24,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: Microchip +*/ + #include "sam.h" // Suppress warning caused by mcu driver diff --git a/hw/bsp/saml2x/family.cmake b/hw/bsp/saml2x/family.cmake index 2338d1916..49f2e3e75 100644 --- a/hw/bsp/saml2x/family.cmake +++ b/hw/bsp/saml2x/family.cmake @@ -7,7 +7,7 @@ set(SDK_DIR ${TOP}/hw/mcu/microchip/${SAM_FAMILY}) set(CMSIS_5 ${TOP}/lib/CMSIS_5) # toolchain set up -set(CMAKE_SYSTEM_PROCESSOR cortex-m0plus CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU cortex-m0plus CACHE INTERNAL "System Processor") set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) set(FAMILY_MCUS SAML21 SAML22 CACHE INTERNAL "") @@ -100,14 +100,13 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_SAML22 ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC + family_add_tinyusb(${TARGET} OPT_MCU_SAML22) + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/microchip/samd/dcd_samd.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) # Flashing family_add_bin_hex(${TARGET}) diff --git a/hw/bsp/sltb009a/board.mk b/hw/bsp/sltb009a/board.mk index 687761364..5dd7a158f 100644 --- a/hw/bsp/sltb009a/board.mk +++ b/hw/bsp/sltb009a/board.mk @@ -16,9 +16,6 @@ CFLAGS += \ SILABS_FAMILY = efm32gg12b SILABS_CMSIS = hw/mcu/silabs/cmsis-dfp-$(SILABS_FAMILY)/Device/SiliconLabs/$(shell echo $(SILABS_FAMILY) | tr a-z A-Z) -DEPS_SUBMODULES += hw/mcu/silabs/cmsis-dfp-$(SILABS_FAMILY) -DEPS_SUBMODULES += lib/CMSIS_5 - LDFLAGS_GCC += -specs=nosys.specs -specs=nano.specs # All source paths should be relative to the top level. diff --git a/hw/bsp/spresense/board.mk b/hw/bsp/spresense/board.mk index 15fa0ff20..24f39d2b6 100644 --- a/hw/bsp/spresense/board.mk +++ b/hw/bsp/spresense/board.mk @@ -1,5 +1,3 @@ -DEPS_SUBMODULES += hw/mcu/sony/cxd56/spresense-exported-sdk - # Platforms are: Linux, Darwin, MSYS, CYGWIN PLATFORM := $(firstword $(subst _, ,$(shell uname -s 2>/dev/null))) diff --git a/hw/bsp/stm32c0/boards/stm32c071nucleo/board.h b/hw/bsp/stm32c0/boards/stm32c071nucleo/board.h index f08762736..751df2251 100644 --- a/hw/bsp/stm32c0/boards/stm32c071nucleo/board.h +++ b/hw/bsp/stm32c0/boards/stm32c071nucleo/board.h @@ -25,6 +25,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: STM32C071 Nucleo + url: https://www.st.com/en/evaluation-tools/nucleo-g071rb.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ @@ -50,9 +55,45 @@ // Enable UART serial communication with the ST-Link #define UART_DEV USART2 +#define UART_CLK_EN __HAL_RCC_USART2_CLK_ENABLE #define UART_GPIO_PORT GPIOA #define UART_GPIO_AF GPIO_AF1_USART2 #define UART_TX_PIN GPIO_PIN_2 #define UART_RX_PIN GPIO_PIN_3 +static inline void board_clock_init(void) { + RCC_OscInitTypeDef RCC_OscInitStruct = {0}; + RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; + RCC_CRSInitTypeDef RCC_CRSInitStruct = {0}; + + /* -1- Enable HSIUSB48 Oscillator */ + RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI48; + RCC_OscInitStruct.HSI48State = RCC_HSI48_ON; + + HAL_RCC_OscConfig(&RCC_OscInitStruct); + + /* -2- Initializes the CPU, AHB and APB buses clocks */ + RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK + |RCC_CLOCKTYPE_PCLK1; + RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSIUSB48; + RCC_ClkInitStruct.SYSCLKDivider = RCC_SYSCLK_DIV1; + RCC_ClkInitStruct.AHBCLKDivider = RCC_HCLK_DIV1; + RCC_ClkInitStruct.APB1CLKDivider = RCC_APB1_DIV1; + + HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1); + + + __HAL_RCC_CRS_CLK_ENABLE(); + + // Configures CRS + RCC_CRSInitStruct.Prescaler = RCC_CRS_SYNC_DIV1; + RCC_CRSInitStruct.Source = RCC_CRS_SYNC_SOURCE_USB; + RCC_CRSInitStruct.Polarity = RCC_CRS_SYNC_POLARITY_RISING; + RCC_CRSInitStruct.ReloadValue = __HAL_RCC_CRS_RELOADVALUE_CALCULATE(48000000,1000); + RCC_CRSInitStruct.ErrorLimitValue = 34; + RCC_CRSInitStruct.HSI48CalibrationValue = 32; + + HAL_RCCEx_CRSConfig(&RCC_CRSInitStruct); +} + #endif /* BOARD_H_ */ diff --git a/hw/bsp/stm32c0/family.c b/hw/bsp/stm32c0/family.c index dba6a8af1..09704b527 100644 --- a/hw/bsp/stm32c0/family.c +++ b/hw/bsp/stm32c0/family.c @@ -25,6 +25,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: STMicroelectronics +*/ + #include "stm32c0xx_hal.h" #include "bsp/board_api.h" #include "board.h" @@ -49,31 +53,16 @@ UART_HandleTypeDef UartHandle; void board_init(void) { HAL_Init(); - - // Enable the HSIUSB48 48 MHz oscillator. - RCC->CR |= RCC_CR_HSIUSB48ON; - - // Wait for HSIUSB48 to be ready. - while (!(RCC->CR & RCC_CR_HSIUSB48RDY)) { } - - // Change the SYSCLK source to HSIUSB48. - RCC->CFGR = (RCC->CFGR & ~RCC_CFGR_SW) | RCC_SYSCLKSOURCE_HSIUSB48; - - // Wait for the SYSCLK source to change. - while ((RCC->CFGR & RCC_CFGR_SWS) >> RCC_CFGR_SWS_Pos != RCC_SYSCLKSOURCE_HSIUSB48) { } - - // Disable HSI48 to save power. - RCC->CR &= ~RCC_CR_HSION; + board_clock_init(); // Enable peripheral clocks. - RCC->APBENR1 = RCC_APBENR1_USBEN | RCC_APBENR1_CRSEN | RCC_APBENR1_USART2EN; - RCC->APBENR2 = RCC_APBENR2_USART1EN; - - // Enable all GPIO clocks. - RCC->IOPENR = 0x2F; - - // Turn on CRS to make the HSIUSB48 clock more precise when USB is connected. - CRS->CR |= CRS_CR_AUTOTRIMEN | CRS_CR_CEN; + __HAL_RCC_USB_CLK_ENABLE(); + __HAL_RCC_GPIOA_CLK_ENABLE(); + __HAL_RCC_GPIOB_CLK_ENABLE(); + __HAL_RCC_GPIOC_CLK_ENABLE(); + __HAL_RCC_GPIOD_CLK_ENABLE(); + __HAL_RCC_SYSCFG_CLK_ENABLE(); + __HAL_RCC_PWR_CLK_ENABLE(); #if CFG_TUSB_OS == OPT_OS_NONE // 1ms tick timer @@ -105,6 +94,7 @@ void board_init(void) { } #ifdef UART_DEV + UART_CLK_EN(); // UART { GPIO_InitTypeDef gpio_init = { 0 }; diff --git a/hw/bsp/stm32c0/family.cmake b/hw/bsp/stm32c0/family.cmake index ed237838d..c6a90fff6 100644 --- a/hw/bsp/stm32c0/family.cmake +++ b/hw/bsp/stm32c0/family.cmake @@ -11,7 +11,7 @@ set(CMSIS_5 ${TOP}/lib/CMSIS_5) include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) # toolchain set up -set(CMAKE_SYSTEM_PROCESSOR cortex-m0plus CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU cortex-m0plus CACHE INTERNAL "System Processor") set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) set(FAMILY_MCUS STM32C0 CACHE INTERNAL "") @@ -102,17 +102,17 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_STM32C0 ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC + family_add_tinyusb(${TARGET} OPT_MCU_STM32C0) + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c ${TOP}/src/portable/st/typec/typec_stm32.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) # Flashing + family_add_bin_hex(${TARGET}) family_flash_jlink(${TARGET}) family_flash_stlink(${TARGET}) #family_flash_openocd(${TARGET}) diff --git a/hw/bsp/stm32c0/family.mk b/hw/bsp/stm32c0/family.mk index 9ff3a2fdf..bdb34454e 100644 --- a/hw/bsp/stm32c0/family.mk +++ b/hw/bsp/stm32c0/family.mk @@ -1,6 +1,4 @@ ST_FAMILY = c0 -DEPS_SUBMODULES += lib/CMSIS_5 hw/mcu/st/cmsis_device_$(ST_FAMILY) hw/mcu/st/stm32$(ST_FAMILY)xx_hal_driver - ST_CMSIS = hw/mcu/st/cmsis_device_$(ST_FAMILY) ST_HAL_DRIVER = hw/mcu/st/stm32$(ST_FAMILY)xx_hal_driver diff --git a/hw/bsp/stm32f0/boards/stm32f070rbnucleo/board.h b/hw/bsp/stm32f0/boards/stm32f070rbnucleo/board.h index 9af81e63c..82ad309a3 100644 --- a/hw/bsp/stm32f0/boards/stm32f070rbnucleo/board.h +++ b/hw/bsp/stm32f0/boards/stm32f070rbnucleo/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: STM32 F070 Nucleo + url: https://www.st.com/en/evaluation-tools/nucleo-f070rb.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/stm32f0/boards/stm32f072disco/board.h b/hw/bsp/stm32f0/boards/stm32f072disco/board.h index 1febd01e8..3ca1b3641 100644 --- a/hw/bsp/stm32f0/boards/stm32f072disco/board.h +++ b/hw/bsp/stm32f0/boards/stm32f072disco/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: STM32 F072 Discovery + url: https://www.st.com/en/evaluation-tools/32f072bdiscovery.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/stm32f0/boards/stm32f072eval/board.h b/hw/bsp/stm32f0/boards/stm32f072eval/board.h index 7dcfa3e85..2828000b9 100644 --- a/hw/bsp/stm32f0/boards/stm32f072eval/board.h +++ b/hw/bsp/stm32f0/boards/stm32f072eval/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: STM32 F072 Eval + url: https://www.st.com/en/evaluation-tools/stm32072b-eval.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/stm32f0/family.c b/hw/bsp/stm32f0/family.c index 3079a1ed3..ea1373e6c 100644 --- a/hw/bsp/stm32f0/family.c +++ b/hw/bsp/stm32f0/family.c @@ -24,6 +24,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: STMicroelectronics +*/ + #include "stm32f0xx_hal.h" #include "bsp/board_api.h" #include "board.h" diff --git a/hw/bsp/stm32f0/family.cmake b/hw/bsp/stm32f0/family.cmake index 0af200dd5..12c7b592c 100644 --- a/hw/bsp/stm32f0/family.cmake +++ b/hw/bsp/stm32f0/family.cmake @@ -11,7 +11,7 @@ set(CMSIS_5 ${TOP}/lib/CMSIS_5) include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) # toolchain set up -set(CMAKE_SYSTEM_PROCESSOR cortex-m0 CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU cortex-m0 CACHE INTERNAL "System Processor") set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) set(FAMILY_MCUS STM32F0 CACHE INTERNAL "") @@ -100,16 +100,16 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_STM32F0 ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC + family_add_tinyusb(${TARGET} OPT_MCU_STM32F0) + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) # Flashing + family_add_bin_hex(${TARGET}) family_flash_stlink(${TARGET}) family_flash_jlink(${TARGET}) endfunction() diff --git a/hw/bsp/stm32f0/family.mk b/hw/bsp/stm32f0/family.mk index 431709de0..9b8305874 100644 --- a/hw/bsp/stm32f0/family.mk +++ b/hw/bsp/stm32f0/family.mk @@ -1,7 +1,5 @@ UF2_FAMILY_ID = 0x647824b6 ST_FAMILY = f0 -DEPS_SUBMODULES += lib/CMSIS_5 hw/mcu/st/cmsis_device_$(ST_FAMILY) hw/mcu/st/stm32$(ST_FAMILY)xx_hal_driver - ST_CMSIS = hw/mcu/st/cmsis_device_$(ST_FAMILY) ST_HAL_DRIVER = hw/mcu/st/stm32$(ST_FAMILY)xx_hal_driver diff --git a/hw/bsp/stm32f1/boards/stm32f103_bluepill/board.h b/hw/bsp/stm32f1/boards/stm32f103_bluepill/board.h index 2f30a09d4..c8a74337f 100644 --- a/hw/bsp/stm32f1/boards/stm32f103_bluepill/board.h +++ b/hw/bsp/stm32f1/boards/stm32f103_bluepill/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: STM32 F103 Bluepill + url: https://stm32-base.org/boards/STM32F103C8T6-Blue-Pill +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/stm32f1/boards/stm32f103_mini_2/board.h b/hw/bsp/stm32f1/boards/stm32f103_mini_2/board.h index c8dba4268..d4824686f 100644 --- a/hw/bsp/stm32f1/boards/stm32f103_mini_2/board.h +++ b/hw/bsp/stm32f1/boards/stm32f103_mini_2/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: STM32 F103 Mini v2 + url: https://stm32-base.org/boards/STM32F103RCT6-STM32-Mini-V2.0 +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/stm32f1/boards/stm32f103ze_iar/board.h b/hw/bsp/stm32f1/boards/stm32f103ze_iar/board.h index d31102d32..1253c5a48 100644 --- a/hw/bsp/stm32f1/boards/stm32f103ze_iar/board.h +++ b/hw/bsp/stm32f1/boards/stm32f103ze_iar/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: IAR STM32 F103ze starter kit + url: n/a +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/stm32f1/family.c b/hw/bsp/stm32f1/family.c index 600fc28c0..29785397f 100644 --- a/hw/bsp/stm32f1/family.c +++ b/hw/bsp/stm32f1/family.c @@ -24,6 +24,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: STMicroelectronics +*/ + #include "stm32f1xx_hal.h" #include "bsp/board_api.h" #include "board.h" diff --git a/hw/bsp/stm32f1/family.cmake b/hw/bsp/stm32f1/family.cmake index e8cc4db1f..cbb9c3568 100644 --- a/hw/bsp/stm32f1/family.cmake +++ b/hw/bsp/stm32f1/family.cmake @@ -11,7 +11,7 @@ set(CMSIS_5 ${TOP}/lib/CMSIS_5) include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) # toolchain set up -set(CMAKE_SYSTEM_PROCESSOR cortex-m3 CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU cortex-m3 CACHE INTERNAL "System Processor") set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) set(FAMILY_MCUS STM32F1 CACHE INTERNAL "") @@ -99,16 +99,16 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_STM32F1 ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC + family_add_tinyusb(${TARGET} OPT_MCU_STM32F1) + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) # Flashing + family_add_bin_hex(${TARGET}) family_flash_stlink(${TARGET}) family_flash_jlink(${TARGET}) endfunction() diff --git a/hw/bsp/stm32f1/family.mk b/hw/bsp/stm32f1/family.mk index 364616304..ca95f2315 100644 --- a/hw/bsp/stm32f1/family.mk +++ b/hw/bsp/stm32f1/family.mk @@ -1,6 +1,4 @@ ST_FAMILY = f1 -DEPS_SUBMODULES += lib/CMSIS_5 hw/mcu/st/cmsis_device_${ST_FAMILY} hw/mcu/st/stm32${ST_FAMILY}xx_hal_driver - ST_CMSIS = hw/mcu/st/cmsis_device_${ST_FAMILY} ST_HAL_DRIVER = hw/mcu/st/stm32${ST_FAMILY}xx_hal_driver diff --git a/hw/bsp/stm32f2/boards/stm32f207nucleo/board.h b/hw/bsp/stm32f2/boards/stm32f207nucleo/board.h index 3301ede27..8d8c52f60 100644 --- a/hw/bsp/stm32f2/boards/stm32f207nucleo/board.h +++ b/hw/bsp/stm32f2/boards/stm32f207nucleo/board.h @@ -1,3 +1,9 @@ + +/* metadata: + name: STM32 F207 Nucleo + url: https://www.st.com/en/evaluation-tools/nucleo-f207zg.html +*/ + #ifndef BOARD_H #define BOARD_H diff --git a/hw/bsp/stm32f2/boards/stm32f207nucleo/board.mk b/hw/bsp/stm32f2/boards/stm32f207nucleo/board.mk index ba185d199..6e681ef57 100644 --- a/hw/bsp/stm32f2/boards/stm32f207nucleo/board.mk +++ b/hw/bsp/stm32f2/boards/stm32f207nucleo/board.mk @@ -1,12 +1,9 @@ -CFLAGS += \ - -DSTM32F207xx \ +MCU_VARIANT = stm32f207xx +CFLAGS += -DSTM32F207xx # All source paths should be relative to the top level. LD_FILE = $(BOARD_PATH)/STM32F207ZGTx_FLASH.ld -SRC_S += \ - $(ST_CMSIS)/Source/Templates/gcc/startup_stm32f207xx.s - # For flash-jlink target JLINK_DEVICE = stm32f207zg diff --git a/hw/bsp/stm32f2/family.c b/hw/bsp/stm32f2/family.c index 62cca327b..c1333382a 100644 --- a/hw/bsp/stm32f2/family.c +++ b/hw/bsp/stm32f2/family.c @@ -24,6 +24,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: STMicroelectronics +*/ + #include "stm32f2xx_hal.h" #include "bsp/board_api.h" #include "board.h" diff --git a/hw/bsp/stm32f2/family.cmake b/hw/bsp/stm32f2/family.cmake index 538a6cd66..dc6bc2885 100644 --- a/hw/bsp/stm32f2/family.cmake +++ b/hw/bsp/stm32f2/family.cmake @@ -11,7 +11,7 @@ set(CMSIS_5 ${TOP}/lib/CMSIS_5) include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) # toolchain set up -set(CMAKE_SYSTEM_PROCESSOR cortex-m3 CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU cortex-m3 CACHE INTERNAL "System Processor") set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) set(FAMILY_MCUS STM32F2 CACHE INTERNAL "") @@ -99,18 +99,18 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_STM32F2 ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC + family_add_tinyusb(${TARGET} OPT_MCU_STM32F2) + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/synopsys/dwc2/dcd_dwc2.c ${TOP}/src/portable/synopsys/dwc2/hcd_dwc2.c ${TOP}/src/portable/synopsys/dwc2/dwc2_common.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) # Flashing + family_add_bin_hex(${TARGET}) family_flash_stlink(${TARGET}) family_flash_jlink(${TARGET}) endfunction() diff --git a/hw/bsp/stm32f2/family.mk b/hw/bsp/stm32f2/family.mk index 7af9a76a0..ef14a9d67 100644 --- a/hw/bsp/stm32f2/family.mk +++ b/hw/bsp/stm32f2/family.mk @@ -1,24 +1,17 @@ ST_FAMILY = f2 - ST_CMSIS = hw/mcu/st/cmsis_device_$(ST_FAMILY) ST_HAL_DRIVER = hw/mcu/st/stm32$(ST_FAMILY)xx_hal_driver -DEPS_SUBMODULES += \ - lib/CMSIS_5 \ - $(ST_CMSIS) \ - $(ST_HAL_DRIVER) - include $(TOP)/$(BOARD_PATH)/board.mk CPU_CORE ?= cortex-m3 CFLAGS += \ -DCFG_TUSB_MCU=OPT_MCU_STM32F2 +# mcu driver cause following warnings CFLAGS_GCC += \ -flto \ - -# mcu driver cause following warnings -CFLAGS_GCC += -Wno-error=sign-compare + -Wno-error=sign-compare LDFLAGS_GCC += \ -nostdlib -nostartfiles \ @@ -40,3 +33,10 @@ INC += \ $(TOP)/$(ST_CMSIS)/Include \ $(TOP)/$(ST_HAL_DRIVER)/Inc \ $(TOP)/$(BOARD_PATH) + +# Startup +SRC_S_GCC += $(ST_CMSIS)/Source/Templates/gcc/startup_${MCU_VARIANT}.s +SRC_S_IAR += $(ST_CMSIS)/Source/Templates/iar/startup_${MCU_VARIANT}.s + +# Linker +LD_FILE_IAR ?= $(ST_CMSIS)/Source/Templates/iar/linker/${MCU_VARIANT}_flash.icf diff --git a/hw/bsp/stm32f3/boards/stm32f303disco/board.h b/hw/bsp/stm32f3/boards/stm32f303disco/board.h index 706149b49..c79dea945 100644 --- a/hw/bsp/stm32f3/boards/stm32f303disco/board.h +++ b/hw/bsp/stm32f3/boards/stm32f303disco/board.h @@ -1,3 +1,9 @@ + +/* metadata: + name: STM32 F303 Discovery + url: https://www.st.com/en/evaluation-tools/stm32f3discovery.html +*/ + #ifndef BOARD_H #define BOARD_H diff --git a/hw/bsp/stm32f3/boards/stm32f303disco/board.mk b/hw/bsp/stm32f3/boards/stm32f303disco/board.mk index e387f2d54..6b9a3e283 100644 --- a/hw/bsp/stm32f3/boards/stm32f303disco/board.mk +++ b/hw/bsp/stm32f3/boards/stm32f303disco/board.mk @@ -1,12 +1,10 @@ +MCU_VARIANT = stm32f303xc CFLAGS += \ -DSTM32F303xC \ # All source paths should be relative to the top level. LD_FILE = $(BOARD_PATH)/STM32F303VCTx_FLASH.ld -SRC_S += \ - $(ST_CMSIS)/Source/Templates/gcc/startup_stm32f303xc.s - # For flash-jlink target JLINK_DEVICE = stm32f303vc diff --git a/hw/bsp/stm32f3/family.c b/hw/bsp/stm32f3/family.c index f94dd95cf..84612d416 100644 --- a/hw/bsp/stm32f3/family.c +++ b/hw/bsp/stm32f3/family.c @@ -24,6 +24,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: STMicroelectronics +*/ + #include "stm32f3xx_hal.h" #include "bsp/board_api.h" #include "board.h" diff --git a/hw/bsp/stm32f3/family.cmake b/hw/bsp/stm32f3/family.cmake index dbba1e658..0ba2920d5 100644 --- a/hw/bsp/stm32f3/family.cmake +++ b/hw/bsp/stm32f3/family.cmake @@ -11,7 +11,7 @@ set(CMSIS_5 ${TOP}/lib/CMSIS_5) include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) # toolchain set up -set(CMAKE_SYSTEM_PROCESSOR cortex-m3 CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU cortex-m3 CACHE INTERNAL "System Processor") set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) set(FAMILY_MCUS STM32F3 CACHE INTERNAL "") @@ -97,16 +97,16 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_STM32F3 ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC + family_add_tinyusb(${TARGET} OPT_MCU_STM32F3) + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) # Flashing + family_add_bin_hex(${TARGET}) family_flash_stlink(${TARGET}) family_flash_jlink(${TARGET}) endfunction() diff --git a/hw/bsp/stm32f3/family.mk b/hw/bsp/stm32f3/family.mk index 4fe3aa99d..13734583a 100644 --- a/hw/bsp/stm32f3/family.mk +++ b/hw/bsp/stm32f3/family.mk @@ -1,22 +1,17 @@ ST_FAMILY = f3 - ST_CMSIS = hw/mcu/st/cmsis_device_$(ST_FAMILY) ST_HAL_DRIVER = hw/mcu/st/stm32$(ST_FAMILY)xx_hal_driver -DEPS_SUBMODULES += \ - lib/CMSIS_5 \ - $(ST_CMSIS) \ - $(ST_HAL_DRIVER) - include $(TOP)/$(BOARD_PATH)/board.mk CPU_CORE ?= cortex-m4 CFLAGS += \ - -flto \ -DCFG_TUSB_MCU=OPT_MCU_STM32F3 # mcu driver cause following warnings -CFLAGS += -Wno-error=unused-parameter +CFLAGS_GCC += \ + -flto \ + -Wno-error=unused-parameter LDFLAGS_GCC += \ -nostdlib -nostartfiles \ @@ -36,3 +31,10 @@ INC += \ $(TOP)/$(ST_CMSIS)/Include \ $(TOP)/$(ST_HAL_DRIVER)/Inc \ $(TOP)/$(BOARD_PATH) + +# Startup +SRC_S_GCC += $(ST_CMSIS)/Source/Templates/gcc/startup_${MCU_VARIANT}.s +SRC_S_IAR += $(ST_CMSIS)/Source/Templates/iar/startup_${MCU_VARIANT}.s + +# Linker +LD_FILE_IAR ?= $(ST_CMSIS)/Source/Templates/iar/linker/${MCU_VARIANT}_flash.icf diff --git a/hw/bsp/stm32f4/boards/feather_stm32f405/board.h b/hw/bsp/stm32f4/boards/feather_stm32f405/board.h index 670ce8012..11e976a42 100644 --- a/hw/bsp/stm32f4/boards/feather_stm32f405/board.h +++ b/hw/bsp/stm32f4/boards/feather_stm32f405/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Adafruit Feather STM32F405 + url: https://www.adafruit.com/product/4382 +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/stm32f4/boards/pyboardv11/board.h b/hw/bsp/stm32f4/boards/pyboardv11/board.h index 077313518..9583a924b 100644 --- a/hw/bsp/stm32f4/boards/pyboardv11/board.h +++ b/hw/bsp/stm32f4/boards/pyboardv11/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Pyboard v1.1 + url: https://www.adafruit.com/product/2390 +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/stm32f4/boards/stm32f401blackpill/board.h b/hw/bsp/stm32f4/boards/stm32f401blackpill/board.h index ef40089c9..8a3fe8409 100644 --- a/hw/bsp/stm32f4/boards/stm32f401blackpill/board.h +++ b/hw/bsp/stm32f4/boards/stm32f401blackpill/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: STM32 F401 Blackpill + url: https://stm32-base.org/boards/STM32F401CCU6-WeAct-Black-Pill-V1.2 +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/stm32f4/boards/stm32f407blackvet/board.h b/hw/bsp/stm32f4/boards/stm32f407blackvet/board.h index 6879d066b..effbf2be8 100644 --- a/hw/bsp/stm32f4/boards/stm32f407blackvet/board.h +++ b/hw/bsp/stm32f4/boards/stm32f407blackvet/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: STM32 F407 Blackvet + url: https://stm32-base.org/boards/STM32F407VET6-STM32-F4VE-V2.0 +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/stm32f4/boards/stm32f407blackvet/board.mk b/hw/bsp/stm32f4/boards/stm32f407blackvet/board.mk index 2593978ec..c46a78f81 100644 --- a/hw/bsp/stm32f4/boards/stm32f407blackvet/board.mk +++ b/hw/bsp/stm32f4/boards/stm32f407blackvet/board.mk @@ -1,12 +1,12 @@ CFLAGS += -DSTM32F407xx # GCC -GCC_SRC_S += $(ST_CMSIS)/Source/Templates/gcc/startup_stm32f407xx.s -GCC_LD_FILE = $(BOARD_PATH)/STM32F407VETX_FLASH.ld +SRC_S_GCC += $(ST_CMSIS)/Source/Templates/gcc/startup_stm32f407xx.s +LD_FILE_GCC = $(BOARD_PATH)/STM32F407VETx_FLASH.ld # IAR -IAR_SRC_S += $(ST_CMSIS)/Source/Templates/iar/startup_stm32f407xx.s -IAR_LD_FILE = $(ST_CMSIS)/Source/Templates/iar/linker/stm32f407xx_flash.icf +SRC_S_IAR += $(ST_CMSIS)/Source/Templates/iar/startup_stm32f407xx.s +LD_FILE_IAR = $(ST_CMSIS)/Source/Templates/iar/linker/stm32f407xx_flash.icf # For flash-jlink target diff --git a/hw/bsp/stm32f4/boards/stm32f407disco/board.h b/hw/bsp/stm32f4/boards/stm32f407disco/board.h index 380f8e391..19a029768 100644 --- a/hw/bsp/stm32f4/boards/stm32f407disco/board.h +++ b/hw/bsp/stm32f4/boards/stm32f407disco/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: STM32 F407 Discovery + url: https://www.st.com/en/evaluation-tools/stm32f4discovery.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/stm32f4/boards/stm32f411blackpill/board.h b/hw/bsp/stm32f4/boards/stm32f411blackpill/board.h index efa618b72..61e5de70d 100644 --- a/hw/bsp/stm32f4/boards/stm32f411blackpill/board.h +++ b/hw/bsp/stm32f4/boards/stm32f411blackpill/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: STM32 F411 Blackpill + url: https://stm32-base.org/boards/STM32F411CEU6-WeAct-Black-Pill-V2.0 +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/stm32f4/boards/stm32f411disco/board.h b/hw/bsp/stm32f4/boards/stm32f411disco/board.h index d4bad8e40..d7b02e79d 100644 --- a/hw/bsp/stm32f4/boards/stm32f411disco/board.h +++ b/hw/bsp/stm32f4/boards/stm32f411disco/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: STM32 F411 Discovery + url: https://www.st.com/en/evaluation-tools/32f411ediscovery.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/stm32f4/boards/stm32f412disco/board.h b/hw/bsp/stm32f4/boards/stm32f412disco/board.h index 74e664418..d5146ae3c 100644 --- a/hw/bsp/stm32f4/boards/stm32f412disco/board.h +++ b/hw/bsp/stm32f4/boards/stm32f412disco/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: STM32 F412 Discovery + url: https://www.st.com/en/evaluation-tools/32f412gdiscovery.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/stm32f4/boards/stm32f412nucleo/board.h b/hw/bsp/stm32f4/boards/stm32f412nucleo/board.h index 8900a1e6b..f7026ce61 100644 --- a/hw/bsp/stm32f4/boards/stm32f412nucleo/board.h +++ b/hw/bsp/stm32f4/boards/stm32f412nucleo/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: STM32 F412 Nucleo + url: https://www.st.com/en/evaluation-tools/nucleo-f412zg.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/stm32f4/boards/stm32f439nucleo/board.h b/hw/bsp/stm32f4/boards/stm32f439nucleo/board.h index aa9de4073..9a348f33f 100644 --- a/hw/bsp/stm32f4/boards/stm32f439nucleo/board.h +++ b/hw/bsp/stm32f4/boards/stm32f439nucleo/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: STM32 F439 Nucleo + url: https://www.st.com/en/evaluation-tools/nucleo-f439zi.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/stm32f4/family.c b/hw/bsp/stm32f4/family.c index 866a09d6f..3a1507dbf 100644 --- a/hw/bsp/stm32f4/family.c +++ b/hw/bsp/stm32f4/family.c @@ -24,6 +24,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: STMicroelectronics +*/ + #include "stm32f4xx_hal.h" #include "bsp/board_api.h" diff --git a/hw/bsp/stm32f4/family.cmake b/hw/bsp/stm32f4/family.cmake index c0c9fe902..db5736192 100644 --- a/hw/bsp/stm32f4/family.cmake +++ b/hw/bsp/stm32f4/family.cmake @@ -11,7 +11,7 @@ set(CMSIS_5 ${TOP}/lib/CMSIS_5) include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) # toolchain set up -set(CMAKE_SYSTEM_PROCESSOR cortex-m4 CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU cortex-m4 CACHE INTERNAL "System Processor") set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) set(FAMILY_MCUS STM32F4 CACHE INTERNAL "") @@ -125,18 +125,18 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_STM32F4 ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC + family_add_tinyusb(${TARGET} OPT_MCU_STM32F4) + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/synopsys/dwc2/dcd_dwc2.c ${TOP}/src/portable/synopsys/dwc2/hcd_dwc2.c ${TOP}/src/portable/synopsys/dwc2/dwc2_common.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) # Flashing + family_add_bin_hex(${TARGET}) family_flash_stlink(${TARGET}) family_flash_jlink(${TARGET}) endfunction() diff --git a/hw/bsp/stm32f4/family.mk b/hw/bsp/stm32f4/family.mk index 51ff43a60..c3c41dc3f 100644 --- a/hw/bsp/stm32f4/family.mk +++ b/hw/bsp/stm32f4/family.mk @@ -1,6 +1,5 @@ UF2_FAMILY_ID = 0x57755a57 ST_FAMILY = f4 -DEPS_SUBMODULES += lib/CMSIS_5 hw/mcu/st/cmsis_device_$(ST_FAMILY) hw/mcu/st/stm32$(ST_FAMILY)xx_hal_driver ST_CMSIS = hw/mcu/st/cmsis_device_$(ST_FAMILY) ST_HAL_DRIVER = hw/mcu/st/stm32$(ST_FAMILY)xx_hal_driver diff --git a/hw/bsp/stm32f7/boards/stlinkv3mini/board.h b/hw/bsp/stm32f7/boards/stlinkv3mini/board.h index 632fd99ed..06adb79ad 100644 --- a/hw/bsp/stm32f7/boards/stlinkv3mini/board.h +++ b/hw/bsp/stm32f7/boards/stlinkv3mini/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Stlink-v3 mini + url: https://www.st.com/en/development-tools/stlink-v3mini.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/stm32f7/boards/stm32f723disco/board.h b/hw/bsp/stm32f7/boards/stm32f723disco/board.h index d45ceec5c..35102c1f2 100644 --- a/hw/bsp/stm32f7/boards/stm32f723disco/board.h +++ b/hw/bsp/stm32f7/boards/stm32f723disco/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: STM32 F723 Discovery + url: https://www.st.com/en/evaluation-tools/32f723ediscovery.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/stm32f7/boards/stm32f746disco/board.h b/hw/bsp/stm32f7/boards/stm32f746disco/board.h index d8e92931e..2964ebada 100644 --- a/hw/bsp/stm32f7/boards/stm32f746disco/board.h +++ b/hw/bsp/stm32f7/boards/stm32f746disco/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: STM32 F746 Discovery + url: https://www.st.com/en/evaluation-tools/32f746gdiscovery.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/stm32f7/boards/stm32f746nucleo/board.h b/hw/bsp/stm32f7/boards/stm32f746nucleo/board.h index 55e77fe5f..b039f5543 100644 --- a/hw/bsp/stm32f7/boards/stm32f746nucleo/board.h +++ b/hw/bsp/stm32f7/boards/stm32f746nucleo/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: STM32 F746 Nucleo + url: https://www.st.com/en/evaluation-tools/nucleo-f746zg.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/stm32f7/boards/stm32f767nucleo/board.h b/hw/bsp/stm32f7/boards/stm32f767nucleo/board.h index 81cb60aeb..b5b3841f1 100644 --- a/hw/bsp/stm32f7/boards/stm32f767nucleo/board.h +++ b/hw/bsp/stm32f7/boards/stm32f767nucleo/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: STM32 F767 Nucleo + url: https://www.st.com/en/evaluation-tools/nucleo-f767zi.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/stm32f7/boards/stm32f769disco/board.h b/hw/bsp/stm32f7/boards/stm32f769disco/board.h index 268919b61..8ac520619 100644 --- a/hw/bsp/stm32f7/boards/stm32f769disco/board.h +++ b/hw/bsp/stm32f7/boards/stm32f769disco/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: STM32 F769 Discovery + url: https://www.st.com/en/evaluation-tools/32f769idiscovery.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/stm32f7/family.c b/hw/bsp/stm32f7/family.c index 527fbfe5c..5f63834d0 100644 --- a/hw/bsp/stm32f7/family.c +++ b/hw/bsp/stm32f7/family.c @@ -26,6 +26,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: STMicroelectronics +*/ + #include "stm32f7xx_hal.h" #include "bsp/board_api.h" diff --git a/hw/bsp/stm32f7/family.cmake b/hw/bsp/stm32f7/family.cmake index dc134e9c0..1a3365332 100644 --- a/hw/bsp/stm32f7/family.cmake +++ b/hw/bsp/stm32f7/family.cmake @@ -11,7 +11,7 @@ set(CMSIS_5 ${TOP}/lib/CMSIS_5) include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) # toolchain set up -set(CMAKE_SYSTEM_PROCESSOR cortex-m7-fpsp CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU cortex-m7-fpsp CACHE INTERNAL "System Processor") set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) set(FAMILY_MCUS STM32F7 CACHE INTERNAL "") @@ -127,18 +127,18 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_STM32F7 ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC + family_add_tinyusb(${TARGET} OPT_MCU_STM32F7) + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/synopsys/dwc2/dcd_dwc2.c ${TOP}/src/portable/synopsys/dwc2/hcd_dwc2.c ${TOP}/src/portable/synopsys/dwc2/dwc2_common.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) # Flashing + family_add_bin_hex(${TARGET}) family_flash_stlink(${TARGET}) family_flash_jlink(${TARGET}) endfunction() diff --git a/hw/bsp/stm32f7/family.mk b/hw/bsp/stm32f7/family.mk index abeea784c..d3422e03c 100644 --- a/hw/bsp/stm32f7/family.mk +++ b/hw/bsp/stm32f7/family.mk @@ -1,6 +1,5 @@ UF2_FAMILY_ID = 0x53b80f00 ST_FAMILY = f7 -DEPS_SUBMODULES += lib/CMSIS_5 hw/mcu/st/cmsis_device_$(ST_FAMILY) hw/mcu/st/stm32$(ST_FAMILY)xx_hal_driver ST_CMSIS = hw/mcu/st/cmsis_device_$(ST_FAMILY) ST_HAL_DRIVER = hw/mcu/st/stm32$(ST_FAMILY)xx_hal_driver diff --git a/hw/bsp/stm32g0/boards/stm32g0b1nucleo/board.h b/hw/bsp/stm32g0/boards/stm32g0b1nucleo/board.h index 9ebaf73f0..14d309da1 100644 --- a/hw/bsp/stm32g0/boards/stm32g0b1nucleo/board.h +++ b/hw/bsp/stm32g0/boards/stm32g0b1nucleo/board.h @@ -25,6 +25,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: STM32 G0B1 Nucleo + url: https://www.st.com/en/evaluation-tools/nucleo-g0b1re.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/stm32g0/family.c b/hw/bsp/stm32g0/family.c index d1635be12..67b0b3f1c 100644 --- a/hw/bsp/stm32g0/family.c +++ b/hw/bsp/stm32g0/family.c @@ -25,6 +25,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: STMicroelectronics +*/ + #include "stm32g0xx_hal.h" #include "bsp/board_api.h" #include "board.h" @@ -39,7 +43,9 @@ void USB_UCPD1_2_IRQHandler(void) { //--------------------------------------------------------------------+ // MACRO TYPEDEF CONSTANT ENUM //--------------------------------------------------------------------+ +#ifdef UART_DEV UART_HandleTypeDef UartHandle; +#endif void board_init(void) { HAL_Init(); // required for HAL_RCC_Osc TODO check with freeRTOS @@ -55,8 +61,6 @@ void board_init(void) { __HAL_RCC_SYSCFG_CLK_ENABLE(); __HAL_RCC_PWR_CLK_ENABLE(); - UART_CLK_EN(); - #if CFG_TUSB_OS == OPT_OS_NONE // 1ms tick timer SysTick_Config(SystemCoreClock / 1000); @@ -87,6 +91,8 @@ void board_init(void) { HAL_GPIO_Init(BUTTON_PORT, &GPIO_InitStruct); #ifdef UART_DEV + UART_CLK_EN(); + // UART GPIO_InitStruct.Pin = UART_TX_PIN | UART_RX_PIN; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; @@ -163,7 +169,6 @@ int board_uart_write(void const *buf, int len) { #else (void) buf; (void) len; - (void) UartHandle; return 0; #endif } diff --git a/hw/bsp/stm32g0/family.cmake b/hw/bsp/stm32g0/family.cmake index 0dafa9c0a..4da26f27e 100644 --- a/hw/bsp/stm32g0/family.cmake +++ b/hw/bsp/stm32g0/family.cmake @@ -11,7 +11,7 @@ set(CMSIS_5 ${TOP}/lib/CMSIS_5) include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) # toolchain set up -set(CMAKE_SYSTEM_PROCESSOR cortex-m0plus CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU cortex-m0plus CACHE INTERNAL "System Processor") set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) set(FAMILY_MCUS STM32G0 CACHE INTERNAL "") @@ -101,17 +101,17 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_STM32G0 ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC + family_add_tinyusb(${TARGET} OPT_MCU_STM32G0) + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c ${TOP}/src/portable/st/typec/typec_stm32.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) # Flashing + family_add_bin_hex(${TARGET}) family_flash_jlink(${TARGET}) family_flash_stlink(${TARGET}) #family_flash_openocd(${TARGET}) diff --git a/hw/bsp/stm32g0/family.mk b/hw/bsp/stm32g0/family.mk index 95b8e537d..d735ca92d 100644 --- a/hw/bsp/stm32g0/family.mk +++ b/hw/bsp/stm32g0/family.mk @@ -1,5 +1,4 @@ ST_FAMILY = g0 -DEPS_SUBMODULES += lib/CMSIS_5 hw/mcu/st/cmsis_device_$(ST_FAMILY) hw/mcu/st/stm32$(ST_FAMILY)xx_hal_driver ST_CMSIS = hw/mcu/st/cmsis_device_$(ST_FAMILY) ST_HAL_DRIVER = hw/mcu/st/stm32$(ST_FAMILY)xx_hal_driver diff --git a/hw/bsp/stm32g4/boards/b_g474e_dpow1/board.h b/hw/bsp/stm32g4/boards/b_g474e_dpow1/board.h index e61b13170..d569783fc 100644 --- a/hw/bsp/stm32g4/boards/b_g474e_dpow1/board.h +++ b/hw/bsp/stm32g4/boards/b_g474e_dpow1/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: STM32 B-G474E-DPOW1 Discovery kit + url: https://www.st.com/en/evaluation-tools/b-g474e-dpow1.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/stm32g4/boards/stm32g474nucleo/board.h b/hw/bsp/stm32g4/boards/stm32g474nucleo/board.h index aa2bf20bb..cfef1c09f 100644 --- a/hw/bsp/stm32g4/boards/stm32g474nucleo/board.h +++ b/hw/bsp/stm32g4/boards/stm32g474nucleo/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: STM32 G474 Nucleo + url: https://www.st.com/en/evaluation-tools/nucleo-g474re.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/stm32g4/boards/stm32g491nucleo/board.h b/hw/bsp/stm32g4/boards/stm32g491nucleo/board.h index 7dd4ed9ae..be3d44645 100644 --- a/hw/bsp/stm32g4/boards/stm32g491nucleo/board.h +++ b/hw/bsp/stm32g4/boards/stm32g491nucleo/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: STM32 G491 Nucleo + url: https://www.st.com/en/evaluation-tools/nucleo-g491re.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/stm32g4/family.c b/hw/bsp/stm32g4/family.c index 2259cb9e2..49ef86db9 100644 --- a/hw/bsp/stm32g4/family.c +++ b/hw/bsp/stm32g4/family.c @@ -24,6 +24,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: STMicroelectronics +*/ + #include "stm32g4xx_hal.h" #include "stm32g4xx_ll_bus.h" @@ -53,7 +57,9 @@ void UCPD1_IRQHandler(void) { //--------------------------------------------------------------------+ // MACRO TYPEDEF CONSTANT ENUM //--------------------------------------------------------------------+ +#ifdef UART_DEV UART_HandleTypeDef UartHandle; +#endif void board_init(void) { HAL_Init(); @@ -67,8 +73,6 @@ void board_init(void) { __HAL_RCC_GPIOE_CLK_ENABLE(); __HAL_RCC_GPIOG_CLK_ENABLE(); - UART_CLK_EN(); - #if CFG_TUSB_OS == OPT_OS_NONE // 1ms tick timer SysTick_Config(SystemCoreClock / 1000); @@ -103,6 +107,8 @@ void board_init(void) { HAL_GPIO_Init(BUTTON_PORT, &GPIO_InitStruct); #ifdef UART_DEV + UART_CLK_EN(); + // UART memset(&GPIO_InitStruct, 0, sizeof(GPIO_InitStruct)); GPIO_InitStruct.Pin = UART_TX_PIN | UART_RX_PIN; @@ -193,7 +199,6 @@ int board_uart_write(void const *buf, int len) { #else (void) buf; (void) len; - (void) UartHandle; return 0; #endif } diff --git a/hw/bsp/stm32g4/family.cmake b/hw/bsp/stm32g4/family.cmake index 4217e4be6..5ec9926fe 100644 --- a/hw/bsp/stm32g4/family.cmake +++ b/hw/bsp/stm32g4/family.cmake @@ -11,7 +11,7 @@ set(CMSIS_5 ${TOP}/lib/CMSIS_5) include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) # toolchain set up -set(CMAKE_SYSTEM_PROCESSOR cortex-m4 CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU cortex-m4 CACHE INTERNAL "System Processor") set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) set(FAMILY_MCUS STM32G4 CACHE INTERNAL "") @@ -97,17 +97,17 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_STM32G4 ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC + family_add_tinyusb(${TARGET} OPT_MCU_STM32G4) + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c ${TOP}/src/portable/st/typec/typec_stm32.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) # Flashing + family_add_bin_hex(${TARGET}) family_flash_stlink(${TARGET}) family_flash_jlink(${TARGET}) endfunction() diff --git a/hw/bsp/stm32h5/boards/stm32h503nucleo/board.cmake b/hw/bsp/stm32h5/boards/stm32h503nucleo/board.cmake index f0fb1d809..1a44c3f1d 100644 --- a/hw/bsp/stm32h5/boards/stm32h503nucleo/board.cmake +++ b/hw/bsp/stm32h5/boards/stm32h503nucleo/board.cmake @@ -4,5 +4,6 @@ set(JLINK_DEVICE stm32h503rb) function(update_board TARGET) target_compile_definitions(${TARGET} PUBLIC STM32H503xx + HSE_VALUE=24000000 ) endfunction() diff --git a/hw/bsp/stm32h5/boards/stm32h503nucleo/board.h b/hw/bsp/stm32h5/boards/stm32h503nucleo/board.h index da20cfa3a..c8b5e31f5 100644 --- a/hw/bsp/stm32h5/boards/stm32h503nucleo/board.h +++ b/hw/bsp/stm32h5/boards/stm32h503nucleo/board.h @@ -25,6 +25,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: STM32 H503 Nucleo + url: https://www.st.com/en/evaluation-tools/nucleo-h503rb.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/stm32h5/boards/stm32h503nucleo/board.mk b/hw/bsp/stm32h5/boards/stm32h503nucleo/board.mk index cf60098af..0292353ae 100644 --- a/hw/bsp/stm32h5/boards/stm32h503nucleo/board.mk +++ b/hw/bsp/stm32h5/boards/stm32h503nucleo/board.mk @@ -1,7 +1,8 @@ MCU_VARIANT = stm32h503xx CFLAGS += \ - -DSTM32H503xx + -DSTM32H503xx \ + -DHSE_VALUE=24000000 \ # For flash-jlink target JLINK_DEVICE = stm32h503rb diff --git a/hw/bsp/stm32h5/boards/stm32h563nucleo/board.cmake b/hw/bsp/stm32h5/boards/stm32h563nucleo/board.cmake index 694ea41cd..0077bf235 100644 --- a/hw/bsp/stm32h5/boards/stm32h563nucleo/board.cmake +++ b/hw/bsp/stm32h5/boards/stm32h563nucleo/board.cmake @@ -4,5 +4,6 @@ set(JLINK_DEVICE stm32h563zi) function(update_board TARGET) target_compile_definitions(${TARGET} PUBLIC STM32H563xx + HSE_VALUE=8000000 ) endfunction() diff --git a/hw/bsp/stm32h5/boards/stm32h563nucleo/board.h b/hw/bsp/stm32h5/boards/stm32h563nucleo/board.h index 8e849f5c8..adc3d751a 100644 --- a/hw/bsp/stm32h5/boards/stm32h563nucleo/board.h +++ b/hw/bsp/stm32h5/boards/stm32h563nucleo/board.h @@ -25,6 +25,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: STM32 H563 Nucleo + url: https://www.st.com/en/evaluation-tools/nucleo-h563zi.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ @@ -67,9 +72,8 @@ static inline void SystemClock_Config(void) { /** Initializes the RCC Oscillators according to the specified parameters * in the RCC_OscInitTypeDef structure. */ - RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI48|RCC_OSCILLATORTYPE_HSE; - RCC_OscInitStruct.HSEState = RCC_HSE_BYPASS_DIGITAL; - RCC_OscInitStruct.HSI48State = RCC_HSI48_ON; + RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE; + RCC_OscInitStruct.HSEState = RCC_HSE_BYPASS; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLL1_SOURCE_HSE; RCC_OscInitStruct.PLL.PLLM = 4; @@ -88,8 +92,8 @@ static inline void SystemClock_Config(void) { /** Initializes the CPU, AHB and APB buses clocks */ RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK - |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2 - |RCC_CLOCKTYPE_PCLK3; + |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2 + |RCC_CLOCKTYPE_PCLK3; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1; @@ -101,25 +105,27 @@ static inline void SystemClock_Config(void) { Error_Handler(); } - // Configure CRS clock source - __HAL_RCC_CRS_CLK_ENABLE(); - RCC_CRSInitTypeDef RCC_CRSInitStruct = {0}; - RCC_CRSInitStruct.Prescaler = RCC_CRS_SYNC_DIV1; - RCC_CRSInitStruct.Source = RCC_CRS_SYNC_SOURCE_USB; - RCC_CRSInitStruct.Polarity = RCC_CRS_SYNC_POLARITY_RISING; - RCC_CRSInitStruct.ReloadValue = __HAL_RCC_CRS_RELOADVALUE_CALCULATE(48000000, 1000); - RCC_CRSInitStruct.ErrorLimitValue = 34; - RCC_CRSInitStruct.HSI48CalibrationValue = 32; - HAL_RCCEx_CRSConfig(&RCC_CRSInitStruct); + /** Configure the programming delay + */ + __HAL_FLASH_SET_PROGRAM_DELAY(FLASH_PROGRAMMING_DELAY_2); - /* Select HSI48 as USB clock source */ - RCC_PeriphCLKInitTypeDef usb_clk = {0 }; - usb_clk.PeriphClockSelection = RCC_PERIPHCLK_USB; - usb_clk.UsbClockSelection = RCC_USBCLKSOURCE_HSI48; - HAL_RCCEx_PeriphCLKConfig(&usb_clk); - - /* Peripheral clock enable */ - __HAL_RCC_USB_CLK_ENABLE(); + RCC_PeriphCLKInitTypeDef PeriphClkInitStruct = {0}; + PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_USB; + PeriphClkInitStruct.PLL3.PLL3Source = RCC_PLL3_SOURCE_HSE; + PeriphClkInitStruct.PLL3.PLL3M = 1; + PeriphClkInitStruct.PLL3.PLL3N = 18; + PeriphClkInitStruct.PLL3.PLL3P = 2; + PeriphClkInitStruct.PLL3.PLL3Q = 3; + PeriphClkInitStruct.PLL3.PLL3R = 2; + PeriphClkInitStruct.PLL3.PLL3RGE = RCC_PLL3_VCIRANGE_1; + PeriphClkInitStruct.PLL3.PLL3VCOSEL = RCC_PLL3_VCORANGE_WIDE; + PeriphClkInitStruct.PLL3.PLL3FRACN = 0.0; + PeriphClkInitStruct.PLL3.PLL3ClockOut = RCC_PLL3_DIVQ; + PeriphClkInitStruct.UsbClockSelection = RCC_USBCLKSOURCE_PLL3Q; + if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct) != HAL_OK) + { + Error_Handler(); + } } #ifdef __cplusplus diff --git a/hw/bsp/stm32h5/boards/stm32h563nucleo/board.mk b/hw/bsp/stm32h5/boards/stm32h563nucleo/board.mk index 091d1e5e3..a7ccbdf39 100644 --- a/hw/bsp/stm32h5/boards/stm32h563nucleo/board.mk +++ b/hw/bsp/stm32h5/boards/stm32h563nucleo/board.mk @@ -1,7 +1,8 @@ MCU_VARIANT = stm32h563xx CFLAGS += \ - -DSTM32H563xx + -DSTM32H563xx \ + -DHSE_VALUE=8000000 \ # For flash-jlink target JLINK_DEVICE = stm32h563zi diff --git a/hw/bsp/stm32h5/boards/stm32h563nucleo/cubemx/stm32h563nucleo.ioc b/hw/bsp/stm32h5/boards/stm32h563nucleo/cubemx/stm32h563nucleo.ioc index 3c83d136d..b9b9605c1 100644 --- a/hw/bsp/stm32h5/boards/stm32h563nucleo/cubemx/stm32h563nucleo.ioc +++ b/hw/bsp/stm32h5/boards/stm32h563nucleo/cubemx/stm32h563nucleo.ioc @@ -2,6 +2,7 @@ BOOTPATH.BootPathName=LEGACY BOOTPATH.IPParameters=BootPathName BOOTPATH.UserSelectedBootPath=LEGACY +BSP_IP_NAME=NUCLEO-H563ZI CAD.formats= CAD.pinconfig= CAD.provider= @@ -16,6 +17,7 @@ Mcu.ContextProject=TrustZoneDisabled Mcu.Family=STM32H5 Mcu.IP0=BOOTPATH Mcu.IP1=CORTEX_M33_NS +Mcu.IP10=NUCLEO-H563ZI Mcu.IP2=DEBUG Mcu.IP3=ICACHE Mcu.IP4=MEMORYMAP @@ -24,7 +26,7 @@ Mcu.IP6=PWR Mcu.IP7=RCC Mcu.IP8=SYS Mcu.IP9=USB -Mcu.IPNb=10 +Mcu.IPNb=11 Mcu.Name=STM32H563ZITx Mcu.Package=LQFP144 Mcu.Pin0=PE2 @@ -74,8 +76,8 @@ Mcu.PinsNb=43 Mcu.ThirdPartyNb=0 Mcu.UserConstants= Mcu.UserName=STM32H563ZITx -MxCube.Version=6.10.0 -MxDb.Version=DB.6.0.100 +MxCube.Version=6.12.1 +MxDb.Version=DB.6.0.121 NVIC.BusFault_IRQn=true\:0\:0\:false\:false\:true\:false\:false\:false NVIC.DebugMonitor_IRQn=true\:0\:0\:false\:false\:true\:false\:false\:false NVIC.EXTI13_IRQn=true\:0\:0\:false\:false\:true\:false\:true\:true @@ -267,7 +269,7 @@ ProjectManager.CustomerFirmwarePackage= ProjectManager.DefaultFWLocation=true ProjectManager.DeletePrevious=true ProjectManager.DeviceId=STM32H563ZITx -ProjectManager.FirmwarePackage=STM32Cube FW_H5 V1.1.1 +ProjectManager.FirmwarePackage=STM32Cube FW_H5 V1.3.0 ProjectManager.FreePins=false ProjectManager.HalAssertFull=false ProjectManager.HeapSize=0x200 @@ -317,7 +319,7 @@ RCC.I2C2Freq_Value=250000000 RCC.I2C3Freq_Value=250000000 RCC.I2C4Freq_Value=250000000 RCC.I3C1Freq_Value=250000000 -RCC.IPParameters=ADCFreq_Value,AHBFreq_Value,APB1Freq_Value,APB1TimFreq_Value,APB2Freq_Value,APB2TimFreq_Value,APB3Freq_Value,CECFreq_Value,CKPERFreq_Value,CRSFreq_Value,CSI_VALUE,CortexFreq_Value,DACFreq_Value,EPOD_VALUE,ETHFreq_Value,FCLKCortexFreq_Value,FDCANFreq_Value,FamilyName,HCLKFreq_Value,HSE_VALUE,HSI48_VALUE,HSIDiv,HSI_VALUE,I2C1Freq_Value,I2C2Freq_Value,I2C3Freq_Value,I2C4Freq_Value,I3C1Freq_Value,LPTIM1Freq_Value,LPTIM2Freq_Value,LPTIM3Freq_Value,LPTIM4Freq_Value,LPTIM5Freq_Value,LPTIM6Freq_Value,LPUART1Freq_Value,LSCOPinFreq_Value,LSIRC_VALUE,MCO1PinFreq_Value,MCO2PinFreq_Value,OCTOSPIMFreq_Value,PLL2PoutputFreq_Value,PLL2QoutputFreq_Value,PLL2RoutputFreq_Value,PLL3PoutputFreq_Value,PLL3QoutputFreq_Value,PLL3RoutputFreq_Value,PLLM,PLLN,PLLPoutputFreq_Value,PLLQoutputFreq_Value,PLLSourceVirtual,PWRFreq_Value,RNGFreq_Value,SAI1Freq_Value,SAI2Freq_Value,SDMMC1Freq_Value,SDMMC2Freq_Value,SPI1Freq_Value,SPI2Freq_Value,SPI3Freq_Value,SPI4Freq_Value,SPI5Freq_Value,SPI6Freq_Value,SYSCLKFreq_VALUE,SYSCLKSource,UART12Freq_Value,UART4Freq_Value,UART5Freq_Value,UART7Freq_Value,UART8Freq_Value,UART9Freq_Value,UCPD1outputFreq_Value,USART10Freq_Value,USART11Freq_Value,USART1Freq_Value,USART2Freq_Value,USART3Freq_Value,USART6Freq_Value,USBFreq_Value,VCOInput2Freq_Value,VCOInput3Freq_Value,VCOInputFreq_Value,VCOOutputFreq_Value,VCOPLL2OutputFreq_Value,VCOPLL3OutputFreq_Value +RCC.IPParameters=ADCFreq_Value,AHBFreq_Value,APB1Freq_Value,APB1TimFreq_Value,APB2Freq_Value,APB2TimFreq_Value,APB3Freq_Value,CECFreq_Value,CKPERFreq_Value,CRSFreq_Value,CSI_VALUE,CortexFreq_Value,DACFreq_Value,EPOD_VALUE,ETHFreq_Value,FCLKCortexFreq_Value,FDCANFreq_Value,FamilyName,HCLKFreq_Value,HSE_VALUE,HSI48_VALUE,HSIDiv,HSI_VALUE,I2C1Freq_Value,I2C2Freq_Value,I2C3Freq_Value,I2C4Freq_Value,I3C1Freq_Value,LPTIM1Freq_Value,LPTIM2Freq_Value,LPTIM3Freq_Value,LPTIM4Freq_Value,LPTIM5Freq_Value,LPTIM6Freq_Value,LPUART1Freq_Value,LSCOPinFreq_Value,LSIRC_VALUE,MCO1PinFreq_Value,MCO2PinFreq_Value,OCTOSPIMFreq_Value,PLL2PoutputFreq_Value,PLL2QoutputFreq_Value,PLL2RoutputFreq_Value,PLL2Source,PLL3FRACN,PLL3N,PLL3PoutputFreq_Value,PLL3Q,PLL3QoutputFreq_Value,PLL3RoutputFreq_Value,PLL3Source,PLLFRACN,PLLM,PLLN,PLLPoutputFreq_Value,PLLQoutputFreq_Value,PLLSourceVirtual,PWRFreq_Value,RNGFreq_Value,SAI1Freq_Value,SAI2Freq_Value,SDMMC1Freq_Value,SDMMC2Freq_Value,SPI1Freq_Value,SPI2Freq_Value,SPI3Freq_Value,SPI4Freq_Value,SPI5Freq_Value,SPI6Freq_Value,SYSCLKFreq_VALUE,SYSCLKSource,UART12Freq_Value,UART4Freq_Value,UART5Freq_Value,UART7Freq_Value,UART8Freq_Value,UART9Freq_Value,UCPD1outputFreq_Value,USART10Freq_Value,USART11Freq_Value,USART1Freq_Value,USART2Freq_Value,USART3Freq_Value,USART6Freq_Value,USBCLockSelection,USBFreq_Value,VCOInput2Freq_Value,VCOInput3Freq_Value,VCOInputFreq_Value,VCOOutputFreq_Value,VCOPLL2OutputFreq_Value,VCOPLL3OutputFreq_Value RCC.LPTIM1Freq_Value=250000000 RCC.LPTIM2Freq_Value=250000000 RCC.LPTIM3Freq_Value=250000000 @@ -330,12 +332,18 @@ RCC.LSIRC_VALUE=32000 RCC.MCO1PinFreq_Value=64000000 RCC.MCO2PinFreq_Value=250000000 RCC.OCTOSPIMFreq_Value=250000000 -RCC.PLL2PoutputFreq_Value=258000000 -RCC.PLL2QoutputFreq_Value=258000000 -RCC.PLL2RoutputFreq_Value=258000000 -RCC.PLL3PoutputFreq_Value=258000000 -RCC.PLL3QoutputFreq_Value=258000000 -RCC.PLL3RoutputFreq_Value=258000000 +RCC.PLL2PoutputFreq_Value=516000000 +RCC.PLL2QoutputFreq_Value=516000000 +RCC.PLL2RoutputFreq_Value=516000000 +RCC.PLL2Source=RCC_PLL2_SOURCE_HSE +RCC.PLL3FRACN=0 +RCC.PLL3N=18 +RCC.PLL3PoutputFreq_Value=72000000 +RCC.PLL3Q=3 +RCC.PLL3QoutputFreq_Value=48000000 +RCC.PLL3RoutputFreq_Value=72000000 +RCC.PLL3Source=RCC_PLL3_SOURCE_HSE +RCC.PLLFRACN=0 RCC.PLLM=4 RCC.PLLN=250 RCC.PLLPoutputFreq_Value=250000000 @@ -343,8 +351,8 @@ RCC.PLLQoutputFreq_Value=250000000 RCC.PLLSourceVirtual=RCC_PLL1_SOURCE_HSE RCC.PWRFreq_Value=250000000 RCC.RNGFreq_Value=48000000 -RCC.SAI1Freq_Value=258000000 -RCC.SAI2Freq_Value=258000000 +RCC.SAI1Freq_Value=516000000 +RCC.SAI2Freq_Value=516000000 RCC.SDMMC1Freq_Value=250000000 RCC.SDMMC2Freq_Value=250000000 RCC.SPI1Freq_Value=250000000 @@ -368,13 +376,14 @@ RCC.USART1Freq_Value=250000000 RCC.USART2Freq_Value=250000000 RCC.USART3Freq_Value=250000000 RCC.USART6Freq_Value=250000000 +RCC.USBCLockSelection=RCC_USBCLKSOURCE_PLL3Q RCC.USBFreq_Value=48000000 -RCC.VCOInput2Freq_Value=4000000 -RCC.VCOInput3Freq_Value=4000000 +RCC.VCOInput2Freq_Value=8000000 +RCC.VCOInput3Freq_Value=8000000 RCC.VCOInputFreq_Value=2000000 RCC.VCOOutputFreq_Value=500000000 -RCC.VCOPLL2OutputFreq_Value=516000000 -RCC.VCOPLL3OutputFreq_Value=516000000 +RCC.VCOPLL2OutputFreq_Value=1032000000 +RCC.VCOPLL3OutputFreq_Value=144000000 SH.ADCx_INP18.0=ADC1_INP18 SH.ADCx_INP18.ConfNb=1 SH.GPXTI13.0=GPIO_EXTI13 diff --git a/hw/bsp/stm32h5/boards/stm32h573i_dk/board.h b/hw/bsp/stm32h5/boards/stm32h573i_dk/board.h index 7baef6ca6..d75114397 100644 --- a/hw/bsp/stm32h5/boards/stm32h573i_dk/board.h +++ b/hw/bsp/stm32h5/boards/stm32h573i_dk/board.h @@ -25,6 +25,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: STM32 H573i Discovery + url: https://www.st.com/en/evaluation-tools/stm32h573i-dk.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/stm32h5/family.c b/hw/bsp/stm32h5/family.c index 02500db4e..26ba34ac3 100644 --- a/hw/bsp/stm32h5/family.c +++ b/hw/bsp/stm32h5/family.c @@ -25,6 +25,9 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: STMicroelectronics +*/ // Suppress warning caused by mcu driver #ifdef __GNUC__ @@ -55,7 +58,9 @@ void USB_DRD_FS_IRQHandler(void) { //--------------------------------------------------------------------+ // MACRO TYPEDEF CONSTANT ENUM //--------------------------------------------------------------------+ +#ifdef UART_DEV UART_HandleTypeDef UartHandle; +#endif void board_init(void) { HAL_Init(); // required for HAL_RCC_Osc TODO check with freeRTOS @@ -79,8 +84,6 @@ void board_init(void) { __HAL_RCC_GPIOI_CLK_ENABLE(); #endif - UART_CLK_EN(); - #if CFG_TUSB_OS == OPT_OS_NONE // 1ms tick timer SysTick_Config(SystemCoreClock / 1000); @@ -111,6 +114,8 @@ void board_init(void) { HAL_GPIO_Init(BUTTON_PORT, &GPIO_InitStruct); #ifdef UART_DEV + UART_CLK_EN(); + // UART GPIO_InitStruct.Pin = UART_TX_PIN | UART_RX_PIN; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; @@ -189,7 +194,6 @@ int board_uart_write(void const* buf, int len) { #else (void) buf; (void) len; - (void) UartHandle; return 0; #endif } diff --git a/hw/bsp/stm32h5/family.cmake b/hw/bsp/stm32h5/family.cmake index 94900f416..1df6bcb90 100644 --- a/hw/bsp/stm32h5/family.cmake +++ b/hw/bsp/stm32h5/family.cmake @@ -11,7 +11,7 @@ set(CMSIS_5 ${TOP}/lib/CMSIS_5) include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) # toolchain set up -set(CMAKE_SYSTEM_PROCESSOR cortex-m33 CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU cortex-m33 CACHE INTERNAL "System Processor") set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) set(FAMILY_MCUS STM32H5 CACHE INTERNAL "") @@ -101,17 +101,17 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_STM32H5 ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC + family_add_tinyusb(${TARGET} OPT_MCU_STM32H5) + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c ${TOP}/src/portable/st/typec/typec_stm32.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) # Flashing + family_add_bin_hex(${TARGET}) family_flash_stlink(${TARGET}) family_flash_jlink(${TARGET}) endfunction() diff --git a/hw/bsp/stm32h7/boards/daisyseed/board.h b/hw/bsp/stm32h7/boards/daisyseed/board.h index 2d681d640..300ecb8b2 100644 --- a/hw/bsp/stm32h7/boards/daisyseed/board.h +++ b/hw/bsp/stm32h7/boards/daisyseed/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Daisy Seed + url: https://electro-smith.com/products/daisy-seed +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/stm32h7/boards/stm32h723nucleo/board.h b/hw/bsp/stm32h7/boards/stm32h723nucleo/board.h index c5257901d..f623149bd 100644 --- a/hw/bsp/stm32h7/boards/stm32h723nucleo/board.h +++ b/hw/bsp/stm32h7/boards/stm32h723nucleo/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: STM32 H723 Nucleo + url: https://www.st.com/en/evaluation-tools/nucleo-h723zg.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/stm32h7/boards/stm32h743eval/board.h b/hw/bsp/stm32h7/boards/stm32h743eval/board.h index fa9721be3..7c3f6414a 100644 --- a/hw/bsp/stm32h7/boards/stm32h743eval/board.h +++ b/hw/bsp/stm32h7/boards/stm32h743eval/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: STM32 H743 Eval + url: https://www.st.com/en/evaluation-tools/stm32h743i-eval.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ @@ -179,7 +184,7 @@ static MFXSTM32L152_Object_t mfx_obj = { 0 }; static MFXSTM32L152_IO_Mode_t* mfx_io = NULL; static uint32_t mfx_vbus_pin[2] = { MFXSTM32L152_GPIO_PIN_7, MFXSTM32L152_GPIO_PIN_9 }; -int32_t board_i2c_init(void) { +static int32_t board_i2c_init(void) { __HAL_RCC_I2C1_CLK_ENABLE(); __HAL_RCC_I2C1_FORCE_RESET(); __HAL_RCC_I2C1_RELEASE_RESET(); @@ -195,16 +200,16 @@ int32_t board_i2c_init(void) { return 0; } -int32_t board_i2c_deinit(void) { +static int32_t board_i2c_deinit(void) { return 0; } -int32_t i2c_readreg(uint16_t DevAddr, uint16_t Reg, uint8_t *pData, uint16_t Length) { +static int32_t i2c_readreg(uint16_t DevAddr, uint16_t Reg, uint8_t *pData, uint16_t Length) { TU_ASSERT (HAL_OK == HAL_I2C_Mem_Read(&i2c_handle, DevAddr, Reg, I2C_MEMADD_SIZE_8BIT, pData, Length, 10000)); return 0; } -int32_t i2c_writereg(uint16_t DevAddr, uint16_t Reg, uint8_t *pData, uint16_t Length) { +static int32_t i2c_writereg(uint16_t DevAddr, uint16_t Reg, uint8_t *pData, uint16_t Length) { TU_ASSERT(HAL_OK == HAL_I2C_Mem_Write(&i2c_handle, DevAddr, Reg, I2C_MEMADD_SIZE_8BIT, pData, Length, 10000)); return 0; } @@ -244,7 +249,7 @@ static inline void board_init2(void) { } // VBUS1 is actually controlled by USB3320C PHY (using dwc2 drivebus signal) -void board_vbus_set(uint8_t rhport, bool state) { +static void TU_ATTR_UNUSED board_vbus_set(uint8_t rhport, bool state) { if (mfx_io) { mfx_io->IO_WritePin(&mfx_obj, mfx_vbus_pin[rhport], state); } diff --git a/hw/bsp/stm32h7/boards/stm32h743nucleo/board.h b/hw/bsp/stm32h7/boards/stm32h743nucleo/board.h index 0606f395a..0277d05c7 100644 --- a/hw/bsp/stm32h7/boards/stm32h743nucleo/board.h +++ b/hw/bsp/stm32h7/boards/stm32h743nucleo/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: STM32 H743 Nucleo + url: https://www.st.com/en/evaluation-tools/nucleo-h743zi.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/stm32h7/boards/stm32h745disco/board.h b/hw/bsp/stm32h7/boards/stm32h745disco/board.h index b9d9cdea4..ebdd5a17a 100644 --- a/hw/bsp/stm32h7/boards/stm32h745disco/board.h +++ b/hw/bsp/stm32h7/boards/stm32h745disco/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: STM32 H745 Discovery + url: https://www.st.com/en/evaluation-tools/stm32h745i-disco.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/stm32h7/boards/stm32h750_weact/board.h b/hw/bsp/stm32h7/boards/stm32h750_weact/board.h index f1c363082..e11a55103 100644 --- a/hw/bsp/stm32h7/boards/stm32h750_weact/board.h +++ b/hw/bsp/stm32h7/boards/stm32h750_weact/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: STM32 H750 WeAct + url: https://www.adafruit.com/product/5032 +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/stm32h7/boards/stm32h750bdk/board.h b/hw/bsp/stm32h7/boards/stm32h750bdk/board.h index 2895f0973..ac417601b 100644 --- a/hw/bsp/stm32h7/boards/stm32h750bdk/board.h +++ b/hw/bsp/stm32h7/boards/stm32h750bdk/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: STM32 H750b Discovery Kit + url: https://www.st.com/en/evaluation-tools/stm32h750b-dk.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/stm32h7/boards/waveshare_openh743i/board.h b/hw/bsp/stm32h7/boards/waveshare_openh743i/board.h index 625c6a137..bfaf42784 100644 --- a/hw/bsp/stm32h7/boards/waveshare_openh743i/board.h +++ b/hw/bsp/stm32h7/boards/waveshare_openh743i/board.h @@ -26,6 +26,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: Waveshare Open H743i + url: https://www.waveshare.com/openh743i-c-standard.htm +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/stm32h7/family.c b/hw/bsp/stm32h7/family.c index 0be18350c..f8723b0c7 100644 --- a/hw/bsp/stm32h7/family.c +++ b/hw/bsp/stm32h7/family.c @@ -27,6 +27,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: STMicroelectronics +*/ + #include "stm32h7xx_hal.h" #include "bsp/board_api.h" @@ -76,7 +80,7 @@ void OTG_HS_IRQHandler(void) { } #ifdef TRACE_ETM -void trace_etm_init(void) { +static void trace_etm_init(void) { // H7 trace pin is PE2 to PE6 GPIO_InitTypeDef gpio_init; gpio_init.Pin = GPIO_PIN_2 | GPIO_PIN_3 | GPIO_PIN_4 | GPIO_PIN_5 | GPIO_PIN_6; @@ -90,7 +94,7 @@ void trace_etm_init(void) { DBGMCU->CR |= DBGMCU_CR_DBG_TRACECKEN | DBGMCU_CR_DBG_CKD1EN | DBGMCU_CR_DBG_CKD3EN; } #else - #define trace_etm_init() +#define trace_etm_init() #endif void board_init(void) { diff --git a/hw/bsp/stm32h7/family.cmake b/hw/bsp/stm32h7/family.cmake index 3e246faed..b4f0bebbf 100644 --- a/hw/bsp/stm32h7/family.cmake +++ b/hw/bsp/stm32h7/family.cmake @@ -12,7 +12,7 @@ set(CMSIS_5 ${TOP}/lib/CMSIS_5) include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) # toolchain set up -set(CMAKE_SYSTEM_PROCESSOR cortex-m7 CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU cortex-m7 CACHE INTERNAL "System Processor") set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) set(FAMILY_MCUS STM32H7 CACHE INTERNAL "") @@ -132,18 +132,18 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_STM32H7 ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC + family_add_tinyusb(${TARGET} OPT_MCU_STM32H7) + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/synopsys/dwc2/dcd_dwc2.c ${TOP}/src/portable/synopsys/dwc2/hcd_dwc2.c ${TOP}/src/portable/synopsys/dwc2/dwc2_common.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) # Flashing + family_add_bin_hex(${TARGET}) family_flash_stlink(${TARGET}) family_flash_jlink(${TARGET}) endfunction() diff --git a/hw/bsp/stm32h7/family.mk b/hw/bsp/stm32h7/family.mk index 29b83cf7d..19a085424 100644 --- a/hw/bsp/stm32h7/family.mk +++ b/hw/bsp/stm32h7/family.mk @@ -45,11 +45,9 @@ CFLAGS += \ -DBOARD_TUH_MAX_SPEED=${RHPORT_HOST_SPEED} \ # GCC Flags -CFLAGS_GCC += \ - -flto \ - # suppress warning caused by vendor mcu driver CFLAGS_GCC += \ + -flto \ -Wno-error=cast-align \ -Wno-error=unused-parameter \ diff --git a/hw/bsp/max32666/FreeRTOSConfig/FreeRTOSConfig.h b/hw/bsp/stm32h7rs/FreeRTOSConfig/FreeRTOSConfig.h similarity index 98% rename from hw/bsp/max32666/FreeRTOSConfig/FreeRTOSConfig.h rename to hw/bsp/stm32h7rs/FreeRTOSConfig/FreeRTOSConfig.h index e5a76af85..9fd3f6c50 100644 --- a/hw/bsp/max32666/FreeRTOSConfig/FreeRTOSConfig.h +++ b/hw/bsp/stm32h7rs/FreeRTOSConfig/FreeRTOSConfig.h @@ -44,7 +44,7 @@ // skip if included from IAR assembler #ifndef __IASMARM__ - #include "mxc_device.h" + #include "stm32h7rsxx.h" #endif /* Cortex M23/M33 port configuration. */ @@ -59,7 +59,7 @@ #define configTICK_RATE_HZ ( 1000 ) #define configMAX_PRIORITIES ( 5 ) #define configMINIMAL_STACK_SIZE ( 128 ) -#define configTOTAL_HEAP_SIZE ( configSUPPORT_DYNAMIC_ALLOCATION*4*1024 ) +#define configTOTAL_HEAP_SIZE ( configSUPPORT_DYNAMIC_ALLOCATION*8*1024 ) #define configMAX_TASK_NAME_LEN 16 #define configUSE_16_BIT_TICKS 0 #define configIDLE_SHOULD_YIELD 1 @@ -127,7 +127,7 @@ //--------------------------------------------------------------------+ // For Cortex-M specific: __NVIC_PRIO_BITS is defined in mcu header -#define configPRIO_BITS __NVIC_PRIO_BITS +#define configPRIO_BITS 4 /* The lowest interrupt priority that can be used in a call to a "set priority" function. */ #define configLIBRARY_LOWEST_INTERRUPT_PRIORITY ((1<port, pindef->pin_init.Pin, GPIO_PIN_SET); + + __HAL_RCC_I2C3_CLK_ENABLE(); + __HAL_RCC_I2C3_FORCE_RESET(); + __HAL_RCC_I2C3_RELEASE_RESET(); + if (HAL_I2C_Init(&i2c_handle) != HAL_OK) { + return HAL_ERROR; + } + + NVIC_SetPriority(EXTI8_IRQn, 12); + NVIC_EnableIRQ(EXTI8_IRQn); + + return 0; +} + +int32_t board_tcpp0203_deinit(void) { + return 0; +} + +int32_t i2c_readreg(uint16_t DevAddr, uint16_t Reg, uint8_t *pData, uint16_t Length) { + TU_ASSERT (HAL_OK == HAL_I2C_Mem_Read(&i2c_handle, DevAddr, Reg, I2C_MEMADD_SIZE_8BIT, pData, Length, 10000)); + return 0; +} + +int32_t i2c_writereg(uint16_t DevAddr, uint16_t Reg, uint8_t *pData, uint16_t Length) { + TU_ASSERT(HAL_OK == HAL_I2C_Mem_Write(&i2c_handle, DevAddr, Reg, I2C_MEMADD_SIZE_8BIT, pData, Length, 10000)); + return 0; +} + +static inline void board_init2(void) { + TCPP0203_IO_t io_ctx; + + io_ctx.Address = TCPP0203_I2C_ADDRESS_X68; + io_ctx.Init = board_tcpp0203_init; + io_ctx.DeInit = board_tcpp0203_deinit; + io_ctx.ReadReg = i2c_readreg; + io_ctx.WriteReg = i2c_writereg; + + TU_ASSERT(TCPP0203_RegisterBusIO(&tcpp0203_obj, &io_ctx) == TCPP0203_OK, ); + + TU_ASSERT(TCPP0203_Init(&tcpp0203_obj) == TCPP0203_OK, ); + + TU_ASSERT(TCPP0203_SetPowerMode(&tcpp0203_obj, TCPP0203_POWER_MODE_NORMAL) == TCPP0203_OK, ); +} + +void board_vbus_set(uint8_t rhport, bool state) { + (void) state; + if (rhport == 1) { + TU_ASSERT(TCPP0203_SetGateDriverProvider(&tcpp0203_obj, TCPP0203_GD_PROVIDER_SWITCH_CLOSED) == TCPP0203_OK, ); + } +} + +void EXTI8_IRQHandler(void) { + __HAL_GPIO_EXTI_CLEAR_IT(GPIO_PIN_8); + if (tcpp0203_obj.IsInitialized) { + TU_ASSERT(TCPP0203_SetPowerMode(&tcpp0203_obj, TCPP0203_POWER_MODE_NORMAL) == TCPP0203_OK, ); + TU_ASSERT(TCPP0203_SetGateDriverProvider(&tcpp0203_obj, TCPP0203_GD_PROVIDER_SWITCH_CLOSED) == TCPP0203_OK, ); + } +} + +#ifdef __cplusplus + } +#endif + +#endif diff --git a/hw/bsp/stm32h7rs/boards/stm32h7s3nucleo/board.mk b/hw/bsp/stm32h7rs/boards/stm32h7s3nucleo/board.mk new file mode 100644 index 000000000..cf0c2ff54 --- /dev/null +++ b/hw/bsp/stm32h7rs/boards/stm32h7s3nucleo/board.mk @@ -0,0 +1,19 @@ +MCU_VARIANT = stm32h7s3xx +CFLAGS += -DSTM32H7S3xx + +# For flash-jlink target +JLINK_DEVICE = stm32h7s3xx + +# flash target using on-board stlink +flash: flash-stlink + +# Linker +LD_FILE_GCC = $(BOARD_PATH)/stm32h7s3xx_flash.ld +LD_FILE_IAR = $(BOARD_PATH)/stm32h7s3xx_flash.icf + +SRC_C += \ + $(ST_TCPP0203)/tcpp0203.c \ + $(ST_TCPP0203)/tcpp0203_reg.c \ + +INC += \ + $(TOP)/$(ST_TCPP0203) \ diff --git a/hw/bsp/stm32h7rs/boards/stm32h7s3nucleo/stm32h7s3xx_flash.icf b/hw/bsp/stm32h7rs/boards/stm32h7s3nucleo/stm32h7s3xx_flash.icf new file mode 100644 index 000000000..8ffaa74a7 --- /dev/null +++ b/hw/bsp/stm32h7rs/boards/stm32h7s3nucleo/stm32h7s3xx_flash.icf @@ -0,0 +1,55 @@ +/*###ICF### Section handled by ICF editor, don't touch! ****/ +/*-Editor annotation file-*/ +/* IcfEditorFile="$TOOLKIT_DIR$\config\ide\IcfEditor\cortex_v1_0.xml" */ +/*-Specials-*/ +define symbol __ICFEDIT_intvec_start__ = 0x08000000; +/*-Memory Regions-*/ +define symbol NONCACHEABLEBUFFER_size = 0x4000; +define symbol __ICFEDIT_region_ROM_start__ = 0x08000000; +define symbol __ICFEDIT_region_ROM_end__ = 0x0800FFFF; +define symbol __ICFEDIT_region_RAM_start__ = 0x24000000; +define symbol __ICFEDIT_region_RAM_end__ = 0x2404FFFF - NONCACHEABLEBUFFER_size; +define symbol NONCACHEABLEBUFFER_start = __ICFEDIT_region_RAM_end__ + 1; +define symbol NONCACHEABLEBUFFER_end = __ICFEDIT_region_RAM_end__ + NONCACHEABLEBUFFER_size; + + +/*-Sizes-*/ +define symbol __ICFEDIT_size_cstack__ = 0x800; +define symbol __ICFEDIT_size_heap__ = 0x200; +/**** End of ICF editor section. ###ICF###*/ + +define symbol __region_ITCM_start__ = 0x00000000; +define symbol __region_ITCM_end__ = 0x0000FFFF; +define symbol __region_DTCM_start__ = 0x20000000; +define symbol __region_DTCM_end__ = 0x2000FFFF; +define symbol __region_SRAMAHB_start__ = 0x30000000; +define symbol __region_SRAMAHB_end__ = 0x30007FFF; +define symbol __region_BKPSRAM_start__ = 0x38800000; +define symbol __region_BKPSRAM_end__ = 0x38800FFF; + +export symbol NONCACHEABLEBUFFER_start; +export symbol NONCACHEABLEBUFFER_size; + +export symbol __ICFEDIT_region_ROM_start__; +export symbol __ICFEDIT_region_ROM_end__; +define memory mem with size = 4G; +define region ROM_region = mem:[from __ICFEDIT_region_ROM_start__ to __ICFEDIT_region_ROM_end__]; +define region RAM_region = mem:[from __ICFEDIT_region_RAM_start__ to __ICFEDIT_region_RAM_end__]; +define region NONCACHEABLE_region = mem:[from NONCACHEABLEBUFFER_start to NONCACHEABLEBUFFER_end]; +define region ITCM_region = mem:[from __region_ITCM_start__ to __region_ITCM_end__]; +define region DTCM_region = mem:[from __region_DTCM_start__ to __region_DTCM_end__]; +define region SRAMAHB_region = mem:[from __region_SRAMAHB_start__ to __region_SRAMAHB_end__]; +define region BKPSRAM_region = mem:[from __region_BKPSRAM_start__ to __region_BKPSRAM_end__]; + +define block CSTACK with alignment = 8, size = __ICFEDIT_size_cstack__ { }; +define block HEAP with alignment = 8, size = __ICFEDIT_size_heap__ { }; + +initialize by copy { readwrite }; +do not initialize { section .noinit }; + +place at address mem:__ICFEDIT_intvec_start__ { readonly section .intvec }; + +place in ROM_region { readonly }; +place in RAM_region { readwrite }; +place in NONCACHEABLE_region { section noncacheable_buffer }; +place in DTCM_region { block CSTACK, block HEAP }; diff --git a/hw/bsp/stm32h7rs/boards/stm32h7s3nucleo/stm32h7s3xx_flash.ld b/hw/bsp/stm32h7rs/boards/stm32h7s3nucleo/stm32h7s3xx_flash.ld new file mode 100644 index 000000000..3bd7f0b89 --- /dev/null +++ b/hw/bsp/stm32h7rs/boards/stm32h7s3nucleo/stm32h7s3xx_flash.ld @@ -0,0 +1,208 @@ +/* +****************************************************************************** +** +** @file : LinkerScript.ld +** +** @author : Auto-generated by STM32CubeIDE +** +** @brief : Linker script for STM32H7S3xx Device from STM32H7RS series +** 64Kbytes FLASH +** 456Kbytes RAM +** +** Set heap size, stack size and stack location according +** to application requirements. +** +** Set memory bank area and size if external memory is used +** +** Target : STMicroelectronics STM32 +** +** Distribution: The file is distributed as is, without any warranty +** of any kind. +** +****************************************************************************** +** @attention +** +** Copyright (c) 2023 STMicroelectronics. +** All rights reserved. +** +** This software is licensed under terms that can be found in the LICENSE file +** in the root directory of this software component. +** If no LICENSE file comes with this software, it is provided AS-IS. +** +****************************************************************************** +*/ + +/* Entry Point */ +ENTRY(Reset_Handler) + +_Min_Heap_Size = 0x200; /* required amount of heap */ +_Min_Stack_Size = 0x400; /* required amount of stack */ + +__FLASH_BEGIN = 0x08000000; +__FLASH_SIZE = 0x00010000; + +__RAM_BEGIN = 0x24000000; +__RAM_SIZE = 0x4FC00; +__RAM_NONCACHEABLEBUFFER_SIZE = 0x4000; + +/* Memories definition */ +MEMORY +{ + RAM (xrw) : ORIGIN = __RAM_BEGIN, LENGTH = __RAM_SIZE + RAM_NONCACHEABLEBUFFER (xrw) : ORIGIN = __RAM_BEGIN + __RAM_SIZE, LENGTH = __RAM_NONCACHEABLEBUFFER_SIZE + + ITCM (xrw) : ORIGIN = 0x00000000, LENGTH = 0x00010000 + DTCM (rw) : ORIGIN = 0x20000000, LENGTH = 0x00010000 + SRAMAHB (rw) : ORIGIN = 0x30000000, LENGTH = 0x00008000 + BKPSRAM (rw) : ORIGIN = 0x38800000, LENGTH = 0x00001000 + + FLASH (xrw) : ORIGIN = __FLASH_BEGIN, LENGTH = __FLASH_SIZE +} + +/* Highest address of the user mode stack */ +_estack = ORIGIN(DTCM) + LENGTH(DTCM); /* end of "DTCM" Ram type memory */ + +/* Sections */ +SECTIONS +{ + /* The startup code into "FLASH" Rom type memory */ + .isr_vector : + { + . = ALIGN(4); + KEEP(*(.isr_vector)) /* Startup code */ + . = ALIGN(4); + } >FLASH + + /* The program code and other data into "FLASH" Rom type memory */ + .text : + { + . = ALIGN(4); + *(.text) /* .text sections (code) */ + *(.text*) /* .text* sections (code) */ + *(.glue_7) /* glue arm to thumb code */ + *(.glue_7t) /* glue thumb to arm code */ + *(.eh_frame) + + KEEP (*(.init)) + KEEP (*(.fini)) + + . = ALIGN(4); + _etext = .; /* define a global symbols at end of code */ + } >FLASH + + /* Constant data into "FLASH" Rom type memory */ + .rodata : + { + . = ALIGN(4); + *(.rodata) /* .rodata sections (constants, strings, etc.) */ + *(.rodata*) /* .rodata* sections (constants, strings, etc.) */ + . = ALIGN(4); + } >FLASH + + .ARM.extab : + { + . = ALIGN(4); + *(.ARM.extab* .gnu.linkonce.armextab.*) + . = ALIGN(4); + } >FLASH + + .ARM : + { + . = ALIGN(4); + __exidx_start = .; + *(.ARM.exidx*) + __exidx_end = .; + . = ALIGN(4); + } >FLASH + + .preinit_array : + { + . = ALIGN(4); + PROVIDE_HIDDEN (__preinit_array_start = .); + KEEP (*(.preinit_array*)) + PROVIDE_HIDDEN (__preinit_array_end = .); + . = ALIGN(4); + } >FLASH + + .init_array : + { + . = ALIGN(4); + PROVIDE_HIDDEN (__init_array_start = .); + KEEP (*(SORT(.init_array.*))) + KEEP (*(.init_array*)) + PROVIDE_HIDDEN (__init_array_end = .); + . = ALIGN(4); + } >FLASH + + .fini_array : + { + . = ALIGN(4); + PROVIDE_HIDDEN (__fini_array_start = .); + KEEP (*(SORT(.fini_array.*))) + KEEP (*(.fini_array*)) + PROVIDE_HIDDEN (__fini_array_end = .); + . = ALIGN(4); + } >FLASH + + /* Used by the startup to initialize data */ + _sidata = LOADADDR(.data); + + /* Initialized data sections into "RAM" Ram type memory */ + .data : + { + . = ALIGN(4); + _sdata = .; /* create a global symbol at data start */ + *(.data) /* .data sections */ + *(.data*) /* .data* sections */ + *(.RamFunc) /* .RamFunc sections */ + *(.RamFunc*) /* .RamFunc* sections */ + + . = ALIGN(4); + _edata = .; /* define a global symbol at data end */ + + } >RAM AT> FLASH + + /* Uninitialized data section into "RAM" Ram type memory */ + . = ALIGN(4); + .bss : + { + /* This is used by the startup in order to initialize the .bss section */ + _sbss = .; /* define a global symbol at bss start */ + __bss_start__ = _sbss; + *(.bss) + *(.bss*) + *(COMMON) + + . = ALIGN(4); + _ebss = .; /* define a global symbol at bss end */ + __bss_end__ = _ebss; + } >RAM + + RW_NONCACHEABLE : + { + __NONCACHEABLEBUFFER_BEGIN = .;/* create symbol for start of section */ + KEEP(*(noncacheable_buffer)) + __NONCACHEABLEBUFFER_END = .; /* create symbol for start of section */ + } > RAM_NONCACHEABLEBUFFER + + /* User_heap_stack section, used to check that there is enough "DTCM" Ram type memory left */ + ._user_heap_stack : + { + . = ALIGN(8); + PROVIDE ( end = . ); + PROVIDE ( _end = . ); + . = . + _Min_Heap_Size; + . = . + _Min_Stack_Size; + . = ALIGN(8); + } >DTCM + + /* Remove information from the compiler libraries */ + /DISCARD/ : + { + libc.a ( * ) + libm.a ( * ) + libgcc.a ( * ) + } + + .ARM.attributes 0 : { *(.ARM.attributes) } +} diff --git a/hw/bsp/stm32h7rs/family.c b/hw/bsp/stm32h7rs/family.c new file mode 100644 index 000000000..4b81deea0 --- /dev/null +++ b/hw/bsp/stm32h7rs/family.c @@ -0,0 +1,340 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 + * William D. Jones (thor0505@comcast.net), + * Ha Thach (tinyusb.org) + * Uwe Bonnes (bon@elektron.ikp.physik.tu-darmstadt.de + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * This file is part of the TinyUSB stack. + */ + +/* metadata: + manufacturer: STMicroelectronics +*/ + +#include "stm32h7rsxx_hal.h" +#include "bsp/board_api.h" + +TU_ATTR_UNUSED static void Error_Handler(void) { } + +typedef struct { + GPIO_TypeDef* port; + GPIO_InitTypeDef pin_init; + uint8_t active_state; +} board_pindef_t; + +#include "board.h" + +//--------------------------------------------------------------------+ +// MACRO TYPEDEF CONSTANT ENUM +//--------------------------------------------------------------------+ + +#ifdef UART_DEV +UART_HandleTypeDef UartHandle = { + .Instance = UART_DEV, + .Init = { + .BaudRate = CFG_BOARD_UART_BAUDRATE, + .WordLength = UART_WORDLENGTH_8B, + .StopBits = UART_STOPBITS_1, + .Parity = UART_PARITY_NONE, + .HwFlowCtl = UART_HWCONTROL_NONE, + .Mode = UART_MODE_TX_RX, + .OverSampling = UART_OVERSAMPLING_16, + } +}; +#endif + +#ifndef SWO_FREQ +#define SWO_FREQ 4000000 +#endif + +//--------------------------------------------------------------------+ +// Forward USB interrupt events to TinyUSB IRQ Handler +//--------------------------------------------------------------------+ + +// Despite being call USB2_OTG_FS on some MCUs +// OTG_FS is marked as RHPort0 by TinyUSB to be consistent across stm32 port +void OTG_FS_IRQHandler(void) { + tusb_int_handler(0, true); +} + +// Despite being call USB1_OTG_HS on some MCUs +// OTG_HS is marked as RHPort1 by TinyUSB to be consistent across stm32 port +void OTG_HS_IRQHandler(void) { + tusb_int_handler(1, true); +} + +#ifdef TRACE_ETM +void trace_etm_init(void) { + // H7 trace pin is PE2 to PE6 + GPIO_InitTypeDef gpio_init; + gpio_init.Pin = GPIO_PIN_2 | GPIO_PIN_3 | GPIO_PIN_4 | GPIO_PIN_5 | GPIO_PIN_6; + gpio_init.Mode = GPIO_MODE_AF_PP; + gpio_init.Pull = GPIO_PULLUP; + gpio_init.Speed = GPIO_SPEED_FREQ_VERY_HIGH; + gpio_init.Alternate = GPIO_AF0_TRACE; + HAL_GPIO_Init(GPIOE, &gpio_init); + + // Enable trace clk, also in D1 and D3 domain + DBGMCU->CR |= DBGMCU_CR_DBG_TRACECKEN | DBGMCU_CR_DBG_CKD1EN | DBGMCU_CR_DBG_CKD3EN; +} +#else + #define trace_etm_init() +#endif + +#ifdef LOGGER_SWO +void log_swo_init(void) +{ + //UNLOCK FUNNEL + *(volatile uint32_t*)(0x5C004FB0) = 0xC5ACCE55; // SWTF_LAR + *(volatile uint32_t*)(0x5C003FB0) = 0xC5ACCE55; // SWO_LAR + + //SWO current output divisor register + //To change it, you can use the following rule + // value = (CPU_Freq / 3 / SWO_Freq) - 1 + *(volatile uint32_t*)(0x5C003010) = ((SystemCoreClock / 3 / SWO_FREQ) - 1); // SWO_CODR + + //SWO selected pin protocol register + *(volatile uint32_t*)(0x5C0030F0) = 0x00000002; // SWO_SPPR + + //Enable ITM input of SWO trace funnel + *(volatile uint32_t*)(0x5C004000) |= 0x00000001; // SWFT_CTRL +} +#else + #define log_swo_init() +#endif + +void board_init(void) { + HAL_Init(); + + HAL_PWREx_ConfigSupply(PWR_LDO_SUPPLY); + // Implemented in board.h + SystemClock_Config(); + + // Enable All GPIOs clocks + __HAL_RCC_GPIOA_CLK_ENABLE(); + __HAL_RCC_GPIOB_CLK_ENABLE(); + __HAL_RCC_GPIOC_CLK_ENABLE(); + __HAL_RCC_GPIOD_CLK_ENABLE(); + __HAL_RCC_GPIOE_CLK_ENABLE(); + __HAL_RCC_GPIOF_CLK_ENABLE(); + __HAL_RCC_GPIOG_CLK_ENABLE(); + __HAL_RCC_GPIOM_CLK_ENABLE(); + __HAL_RCC_GPION_CLK_ENABLE(); + __HAL_RCC_GPIOO_CLK_ENABLE(); + __HAL_RCC_GPIOP_CLK_ENABLE(); + + log_swo_init(); + trace_etm_init(); + + for (uint8_t i = 0; i < TU_ARRAY_SIZE(board_pindef); i++) { + HAL_GPIO_Init(board_pindef[i].port, &board_pindef[i].pin_init); + } + +#if CFG_TUSB_OS == OPT_OS_NONE + // 1ms tick timer + SysTick_Config(SystemCoreClock / 1000); + +#elif CFG_TUSB_OS == OPT_OS_FREERTOS + // Explicitly disable systick to prevent its ISR runs before scheduler start + SysTick->CTRL &= ~1U; + + // If freeRTOS is used, IRQ priority is limit by max syscall ( smaller is higher ) + #ifdef USB_OTG_FS_PERIPH_BASE + NVIC_SetPriority(OTG_FS_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY ); + #endif + + NVIC_SetPriority(OTG_HS_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY ); +#endif + + + +#ifdef UART_DEV + UART_CLK_EN(); + HAL_UART_Init(&UartHandle); +#endif + + //------------- USB FS -------------// +#if (CFG_TUD_ENABLED && BOARD_TUD_RHPORT == 0) || (CFG_TUH_ENABLED && BOARD_TUH_RHPORT == 0) + // OTG_FS is marked as RHPort0 by TinyUSB to be consistent across stm32 port + + HAL_PWREx_EnableUSBVoltageDetector(); + HAL_PWREx_EnableUSBReg(); + + __HAL_RCC_USB2_OTG_FS_CLK_ENABLE(); + + // PM14 VUSB, PM10 ID, PM11 DM, PM12 DP + // Configure DM DP Pins + GPIO_InitTypeDef GPIO_InitStruct; + GPIO_InitStruct.Pin = GPIO_PIN_11 | GPIO_PIN_12; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Pull = GPIO_NOPULL; + GPIO_InitStruct.Alternate = GPIO_AF10_OTG_FS; + HAL_GPIO_Init(GPIOM, &GPIO_InitStruct); + + // This for ID line debug + GPIO_InitStruct.Pin = GPIO_PIN_10; + GPIO_InitStruct.Mode = GPIO_MODE_AF_OD; + GPIO_InitStruct.Pull = GPIO_PULLUP; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; + GPIO_InitStruct.Alternate = GPIO_AF10_OTG_FS; + HAL_GPIO_Init(GPIOM, &GPIO_InitStruct); + +#if OTG_FS_VBUS_SENSE + // Configure VBUS Pin + GPIO_InitStruct.Pin = GPIO_PIN_14; + GPIO_InitStruct.Mode = GPIO_MODE_INPUT; + GPIO_InitStruct.Pull = GPIO_NOPULL; + GPIO_InitStruct.Alternate = GPIO_AF10_OTG_FS; + HAL_GPIO_Init(GPIOM, &GPIO_InitStruct); + + // Enable VBUS sense (B device) via pin PM14 + USB_OTG_FS->GCCFG |= USB_OTG_GCCFG_VBDEN; +#else + // Disable VBUS sense (B device) + USB_OTG_FS->GCCFG &= ~USB_OTG_GCCFG_VBDEN; + + // B-peripheral session valid override enable + USB_OTG_FS->GOTGCTL |= USB_OTG_GOTGCTL_BVALOEN; + USB_OTG_FS->GOTGCTL |= USB_OTG_GOTGCTL_BVALOVAL; +#endif // vbus sense +#endif + + //------------- USB HS -------------// +#if (CFG_TUD_ENABLED && BOARD_TUD_RHPORT == 1) || (CFG_TUH_ENABLED && BOARD_TUH_RHPORT == 1) + + // Enable USB HS & ULPI Clocks + __HAL_RCC_USB_OTG_HS_CLK_ENABLE(); + __HAL_RCC_USBPHYC_CLK_ENABLE(); + + // Enable USB power + HAL_PWREx_EnableUSBVoltageDetector(); + HAL_PWREx_EnableUSBHSregulator(); + +#if OTG_HS_VBUS_SENSE + // Configure VBUS Pin + GPIO_InitStruct.Pin = GPIO_PIN_9; + GPIO_InitStruct.Mode = GPIO_MODE_INPUT; + GPIO_InitStruct.Pull = GPIO_NOPULL; + GPIO_InitStruct.Alternate = GPIO_AF10_OTG_HS; + HAL_GPIO_Init(GPIOM, &GPIO_InitStruct); + + // Enable VBUS sense (B device) via pin PM9 + USB_OTG_HS->GCCFG |= USB_OTG_GCCFG_VBDEN; +#else + // Disable VBUS sense (B device) + USB_OTG_HS->GCCFG &= ~USB_OTG_GCCFG_VBDEN; + +#if CFG_TUD_ENABLED && BOARD_TUD_RHPORT == 1 + // B-peripheral session valid override enable + USB_OTG_HS->GCCFG |= USB_OTG_GCCFG_VBVALEXTOEN; + USB_OTG_HS->GCCFG |= USB_OTG_GCCFG_VBVALOVAL; +#else + USB_OTG_HS->GCCFG |= USB_OTG_GCCFG_PULLDOWNEN; +#endif + +#endif +#endif + + board_init2(); + +#if CFG_TUH_ENABLED + board_vbus_set(BOARD_TUH_RHPORT, 1); +#endif +} + +//--------------------------------------------------------------------+ +// Board porting API +//--------------------------------------------------------------------+ + +void board_led_write(bool state) { +#ifdef PINID_LED + board_pindef_t* pindef = &board_pindef[PINID_LED]; + GPIO_PinState pin_state = state == pindef->active_state ? GPIO_PIN_SET : GPIO_PIN_RESET; + HAL_GPIO_WritePin(pindef->port, pindef->pin_init.Pin, pin_state); +#else + (void) state; +#endif +} + +uint32_t board_button_read(void) { +#ifdef PINID_BUTTON + board_pindef_t* pindef = &board_pindef[PINID_BUTTON]; + return pindef->active_state == HAL_GPIO_ReadPin(pindef->port, pindef->pin_init.Pin); +#else + return 0; +#endif +} + +size_t board_get_unique_id(uint8_t id[], size_t max_len) { + (void) max_len; + volatile uint32_t * stm32_uuid = (volatile uint32_t *) UID_BASE; + uint32_t* id32 = (uint32_t*) (uintptr_t) id; + uint8_t const len = 12; + + id32[0] = stm32_uuid[0]; + id32[1] = stm32_uuid[1]; + id32[2] = stm32_uuid[2]; + + return len; +} + +int board_uart_read(uint8_t *buf, int len) { + (void) buf; + (void) len; + return 0; +} + +int board_uart_write(void const *buf, int len) { +#ifdef UART_DEV + HAL_UART_Transmit(&UartHandle, (uint8_t * )(uintptr_t) + buf, len, 0xffff); + return len; +#else + (void) buf; (void) len; + return -1; +#endif +} + +#if CFG_TUSB_OS == OPT_OS_NONE +volatile uint32_t system_ticks = 0; + +void SysTick_Handler(void) { + HAL_IncTick(); + system_ticks++; +} + +uint32_t board_millis(void) { + return system_ticks; +} + +#endif + +void HardFault_Handler(void) { + __asm("BKPT #0\n"); +} + +// Required by __libc_init_array in startup code if we are compiling using +// -nostdlib/-nostartfiles. +void _init(void) { +} diff --git a/hw/bsp/stm32h7rs/family.cmake b/hw/bsp/stm32h7rs/family.cmake new file mode 100644 index 000000000..e5e98f914 --- /dev/null +++ b/hw/bsp/stm32h7rs/family.cmake @@ -0,0 +1,150 @@ +include_guard() + +set(ST_FAMILY h7rs) +set(ST_PREFIX stm32${ST_FAMILY}xx) + +set(ST_HAL_DRIVER ${TOP}/hw/mcu/st/stm32${ST_FAMILY}xx_hal_driver) +set(ST_CMSIS ${TOP}/hw/mcu/st/cmsis_device_${ST_FAMILY}) +set(ST_TCPP0203 ${TOP}/hw/mcu/st/stm32-tcpp0203) +set(CMSIS_5 ${TOP}/lib/CMSIS_5) + +# include board specific +include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) + +# toolchain set up +set(CMAKE_SYSTEM_CPU cortex-m7 CACHE INTERNAL "System Processor") +set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) + +set(FAMILY_MCUS STM32H7RS CACHE INTERNAL "") + +# ---------------------- +# Port & Speed Selection +# ---------------------- +if (NOT DEFINED RHPORT_DEVICE) + set(RHPORT_DEVICE 1) +endif () +if (NOT DEFINED RHPORT_HOST) + set(RHPORT_HOST 1) +endif () + +if (NOT DEFINED RHPORT_SPEED) + set(RHPORT_SPEED OPT_MODE_FULL_SPEED OPT_MODE_HIGH_SPEED) +endif () +if (NOT DEFINED RHPORT_DEVICE_SPEED) + list(GET RHPORT_SPEED ${RHPORT_DEVICE} RHPORT_DEVICE_SPEED) +endif () +if (NOT DEFINED RHPORT_HOST_SPEED) + list(GET RHPORT_SPEED ${RHPORT_HOST} RHPORT_HOST_SPEED) +endif () + +cmake_print_variables(RHPORT_DEVICE RHPORT_DEVICE_SPEED RHPORT_HOST RHPORT_HOST_SPEED) + +#------------------------------------ +# BOARD_TARGET +#------------------------------------ +# only need to be built ONCE for all examples +function(add_board_target BOARD_TARGET) + if (TARGET ${BOARD_TARGET}) + return() + endif() + + # Startup & Linker script + set(STARTUP_FILE_GNU ${ST_CMSIS}/Source/Templates/gcc/startup_${MCU_VARIANT}.s) + set(STARTUP_FILE_Clang ${STARTUP_FILE_GNU}) + set(STARTUP_FILE_IAR ${ST_CMSIS}/Source/Templates/iar/startup_${MCU_VARIANT}.s) + + if(NOT DEFINED LD_FILE_GNU) + set(LD_FILE_GNU ${ST_CMSIS}/Source/Templates/gcc/linker/${MCU_VARIANT}_flash.ld) + endif() + set(LD_FILE_Clang ${LD_FILE_GNU}) + if(NOT DEFINED LD_FILE_IAR) + set(LD_FILE_IAR ${ST_CMSIS}/Source/Templates/iar/linker/${MCU_VARIANT}_flash.icf) + endif() + + add_library(${BOARD_TARGET} STATIC + ${ST_CMSIS}/Source/Templates/system_${ST_PREFIX}.c + ${ST_HAL_DRIVER}/Src/${ST_PREFIX}_hal.c + ${ST_HAL_DRIVER}/Src/${ST_PREFIX}_hal_cortex.c + ${ST_HAL_DRIVER}/Src/${ST_PREFIX}_hal_dma.c + ${ST_HAL_DRIVER}/Src/${ST_PREFIX}_hal_gpio.c + ${ST_HAL_DRIVER}/Src/${ST_PREFIX}_hal_pwr.c + ${ST_HAL_DRIVER}/Src/${ST_PREFIX}_hal_i2c.c + ${ST_HAL_DRIVER}/Src/${ST_PREFIX}_hal_pwr_ex.c + ${ST_HAL_DRIVER}/Src/${ST_PREFIX}_hal_rcc.c + ${ST_HAL_DRIVER}/Src/${ST_PREFIX}_hal_rcc_ex.c + ${ST_HAL_DRIVER}/Src/${ST_PREFIX}_hal_uart.c + ${ST_HAL_DRIVER}/Src/${ST_PREFIX}_hal_uart_ex.c + ${STARTUP_FILE_${CMAKE_C_COMPILER_ID}} + ) + target_include_directories(${BOARD_TARGET} PUBLIC + ${CMAKE_CURRENT_FUNCTION_LIST_DIR} + ${CMSIS_5}/CMSIS/Core/Include + ${ST_CMSIS}/Include + ${ST_HAL_DRIVER}/Inc + ) + target_compile_definitions(${BOARD_TARGET} PUBLIC + BOARD_TUD_RHPORT=${RHPORT_DEVICE} + BOARD_TUD_MAX_SPEED=${RHPORT_DEVICE_SPEED} + BOARD_TUH_RHPORT=${RHPORT_HOST} + BOARD_TUH_MAX_SPEED=${RHPORT_HOST_SPEED} + SEGGER_RTT_SECTION="noncacheable_buffer" + BUFFER_SIZE_UP=0x3000 + ) + + update_board(${BOARD_TARGET}) + + if (CMAKE_C_COMPILER_ID STREQUAL "GNU") + target_link_options(${BOARD_TARGET} PUBLIC + "LINKER:--script=${LD_FILE_GNU}" + -nostartfiles + --specs=nosys.specs --specs=nano.specs + ) + elseif (CMAKE_C_COMPILER_ID STREQUAL "Clang") + target_link_options(${BOARD_TARGET} PUBLIC + "LINKER:--script=${LD_FILE_Clang}" + ) + elseif (CMAKE_C_COMPILER_ID STREQUAL "IAR") + target_link_options(${BOARD_TARGET} PUBLIC + "LINKER:--config=${LD_FILE_IAR}" + ) + endif () +endfunction() + + +#------------------------------------ +# Functions +#------------------------------------ +function(family_configure_example TARGET RTOS) + family_configure_common(${TARGET} ${RTOS}) + + # Board target + add_board_target(board_${BOARD}) + + #---------- Port Specific ---------- + # These files are built for each example since it depends on example's tusb_config.h + target_sources(${TARGET} PUBLIC + # BSP + ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/family.c + ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/../board.c + ) + target_include_directories(${TARGET} PUBLIC + # family, hw, board + ${CMAKE_CURRENT_FUNCTION_LIST_DIR} + ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/../../ + ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/boards/${BOARD} + ) + + # Add TinyUSB target and port source + family_add_tinyusb(${TARGET} OPT_MCU_STM32H7RS ${RTOS}) + target_sources(${TARGET} PUBLIC + ${TOP}/src/portable/synopsys/dwc2/dcd_dwc2.c + ${TOP}/src/portable/synopsys/dwc2/hcd_dwc2.c + ${TOP}/src/portable/synopsys/dwc2/dwc2_common.c + ) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + + # Flashing + family_add_bin_hex(${TARGET}) + family_flash_stlink(${TARGET}) + family_flash_jlink(${TARGET}) +endfunction() diff --git a/hw/bsp/stm32h7rs/family.mk b/hw/bsp/stm32h7rs/family.mk new file mode 100644 index 000000000..9970059f8 --- /dev/null +++ b/hw/bsp/stm32h7rs/family.mk @@ -0,0 +1,95 @@ +ST_FAMILY = h7rs +ST_PREFIX = stm32${ST_FAMILY}xx +ST_CMSIS = hw/mcu/st/cmsis_device_$(ST_FAMILY) +ST_HAL_DRIVER = hw/mcu/st/${ST_PREFIX}_hal_driver +ST_TCPP0203 = hw/mcu/st/stm32-tcpp0203 + +UF2_FAMILY_ID = 0x6db66083 + +include $(TOP)/$(BOARD_PATH)/board.mk +CPU_CORE ?= cortex-m7 + +# ---------------------- +# Port & Speed Selection +# ---------------------- +RHPORT_SPEED ?= OPT_MODE_FULL_SPEED OPT_MODE_HIGH_SPEED +RHPORT_DEVICE ?= 1 +RHPORT_HOST ?= 1 + +# Determine RHPORT_DEVICE_SPEED if not defined +ifndef RHPORT_DEVICE_SPEED +ifeq ($(RHPORT_DEVICE), 0) + RHPORT_DEVICE_SPEED = $(firstword $(RHPORT_SPEED)) +else + RHPORT_DEVICE_SPEED = $(lastword $(RHPORT_SPEED)) +endif +endif + +# Determine RHPORT_HOST_SPEED if not defined +ifndef RHPORT_HOST_SPEED +ifeq ($(RHPORT_HOST), 0) + RHPORT_HOST_SPEED = $(firstword $(RHPORT_SPEED)) +else + RHPORT_HOST_SPEED = $(lastword $(RHPORT_SPEED)) +endif +endif + +# -------------- +# Compiler Flags +# -------------- +CFLAGS += \ + -DCFG_TUSB_MCU=OPT_MCU_STM32H7RS \ + -DBOARD_TUD_RHPORT=${RHPORT_DEVICE} \ + -DBOARD_TUD_MAX_SPEED=${RHPORT_DEVICE_SPEED} \ + -DBOARD_TUH_RHPORT=${RHPORT_HOST} \ + -DBOARD_TUH_MAX_SPEED=${RHPORT_HOST_SPEED} \ + -DSEGGER_RTT_SECTION=\"noncacheable_buffer\" \ + -DBUFFER_SIZE_UP=0x3000 \ + +# GCC Flags +CFLAGS_GCC += \ + -flto \ + +# suppress warning caused by vendor mcu driver +CFLAGS_GCC += \ + -Wno-error=cast-align \ + -Wno-error=unused-parameter \ + +LDFLAGS_GCC += \ + -nostdlib -nostartfiles \ + --specs=nosys.specs --specs=nano.specs + +# ----------------- +# Sources & Include +# ----------------- + +SRC_C += \ + src/portable/synopsys/dwc2/dcd_dwc2.c \ + src/portable/synopsys/dwc2/hcd_dwc2.c \ + src/portable/synopsys/dwc2/dwc2_common.c \ + $(ST_CMSIS)/Source/Templates/system_${ST_PREFIX}.c \ + $(ST_HAL_DRIVER)/Src/${ST_PREFIX}_hal.c \ + $(ST_HAL_DRIVER)/Src/${ST_PREFIX}_hal_cortex.c \ + $(ST_HAL_DRIVER)/Src/${ST_PREFIX}_hal_dma.c \ + $(ST_HAL_DRIVER)/Src/${ST_PREFIX}_hal_gpio.c \ + $(ST_HAL_DRIVER)/Src/${ST_PREFIX}_hal_i2c.c \ + $(ST_HAL_DRIVER)/Src/${ST_PREFIX}_hal_pwr.c \ + $(ST_HAL_DRIVER)/Src/${ST_PREFIX}_hal_pwr_ex.c \ + $(ST_HAL_DRIVER)/Src/${ST_PREFIX}_hal_rcc.c \ + $(ST_HAL_DRIVER)/Src/${ST_PREFIX}_hal_rcc_ex.c \ + $(ST_HAL_DRIVER)/Src/${ST_PREFIX}_hal_uart.c \ + $(ST_HAL_DRIVER)/Src/${ST_PREFIX}_hal_uart_ex.c \ + +INC += \ + $(TOP)/$(BOARD_PATH) \ + $(TOP)/lib/CMSIS_5/CMSIS/Core/Include \ + $(TOP)/$(ST_CMSIS)/Include \ + $(TOP)/$(ST_HAL_DRIVER)/Inc + +# Startup +SRC_S_GCC += $(ST_CMSIS)/Source/Templates/gcc/startup_$(MCU_VARIANT).s +SRC_S_IAR += $(ST_CMSIS)/Source/Templates/iar/startup_$(MCU_VARIANT).s + +# Linker +LD_FILE_GCC ?= $(ST_CMSIS)/Source/Templates/gcc/linker/$(MCU_VARIANT)_flash.ld +LD_FILE_IAR ?= $(ST_CMSIS)/Source/Templates/iar/linker/$(MCU_VARIANT)_flash.icf diff --git a/hw/bsp/stm32h7rs/stm32h7rsxx_hal_conf.h b/hw/bsp/stm32h7rs/stm32h7rsxx_hal_conf.h new file mode 100644 index 000000000..6fd90abde --- /dev/null +++ b/hw/bsp/stm32h7rs/stm32h7rsxx_hal_conf.h @@ -0,0 +1,500 @@ +/* USER CODE BEGIN Header */ +/** + ****************************************************************************** + * @file stm32h7rsxx_hal_conf.h + * @author MCD Application Team + * @brief HAL configuration template file. + * This file should be copied to the application folder and renamed + * to stm32h7rsxx_hal_conf.h. + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2022 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ +/* USER CODE END Header */ +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef STM32H7RSxx_HAL_CONF_H +#define STM32H7RSxx_HAL_CONF_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ + +/* ########################## Module Selection ############################## */ +/** + * @brief This is the list of modules to be used in the HAL driver + */ +#define HAL_MODULE_ENABLED +/* #define HAL_ADC_MODULE_ENABLED */ +/* #define HAL_CEC_MODULE_ENABLED */ +/* #define HAL_CORDIC_MODULE_ENABLED */ +/* #define HAL_CRC_MODULE_ENABLED */ +/* #define HAL_CRYP_MODULE_ENABLED */ +/* #define HAL_DCMIPP_MODULE_ENABLED */ +/* #define HAL_DMA2D_MODULE_ENABLED */ +/* #define HAL_DTS_MODULE_ENABLED */ +/* #define HAL_ETH_MODULE_ENABLED */ +/* #define HAL_FDCAN_MODULE_ENABLED */ +/* #define HAL_GFXMMU_MODULE_ENABLED */ +/* #define HAL_GFXTIM_MODULE_ENABLED */ +/* #define HAL_GPU2D_MODULE_ENABLED */ +/* #define HAL_HASH_MODULE_ENABLED */ +/* #define HAL_HCD_MODULE_ENABLED */ +#define HAL_I2C_MODULE_ENABLED +/* #define HAL_I2S_MODULE_ENABLED */ +/* #define HAL_I3C_MODULE_ENABLED */ +/* #define HAL_ICACHE_MODULE_ENABLED */ +/* #define HAL_IRDA_MODULE_ENABLED */ +/* #define HAL_IWDG_MODULE_ENABLED */ +/* #define HAL_JPEG_MODULE_ENABLED */ +/* #define HAL_LPTIM_MODULE_ENABLED */ +/* #define HAL_LTDC_MODULE_ENABLED */ +/* #define HAL_MCE_MODULE_ENABLED */ +/* #define HAL_MDF_MODULE_ENABLED */ +/* #define HAL_MMC_MODULE_ENABLED */ +/* #define HAL_NAND_MODULE_ENABLED */ +/* #define HAL_NOR_MODULE_ENABLED */ +/* #define HAL_PCD_MODULE_ENABLED */ +/* #define HAL_PKA_MODULE_ENABLED */ +/* #define HAL_PSSI_MODULE_ENABLED */ +/* #define HAL_RAMECC_MODULE_ENABLED */ +/* #define HAL_RCC_MODULE_ENABLED */ +/* #define HAL_RNG_MODULE_ENABLED */ +/* #define HAL_RTC_MODULE_ENABLED */ +/* #define HAL_SAI_MODULE_ENABLED */ +/* #define HAL_SD_MODULE_ENABLED */ +/* #define HAL_SDRAM_MODULE_ENABLED */ +/* #define HAL_SMARTCARD_MODULE_ENABLED */ +/* #define HAL_SMBUS_MODULE_ENABLED */ +/* #define HAL_SPDIFRX_MODULE_ENABLED */ +/* #define HAL_SPI_MODULE_ENABLED */ +/* #define HAL_SRAM_MODULE_ENABLED */ +/* #define HAL_TIM_MODULE_ENABLED */ +#define HAL_UART_MODULE_ENABLED +/* #define HAL_USART_MODULE_ENABLED */ +/* #define HAL_WWDG_MODULE_ENABLED */ +#define HAL_XSPI_MODULE_ENABLED +#define HAL_GPIO_MODULE_ENABLED +#define HAL_PWR_MODULE_ENABLED +#define HAL_DMA_MODULE_ENABLED +#define HAL_RCC_MODULE_ENABLED +#define HAL_FLASH_MODULE_ENABLED +#define HAL_EXTI_MODULE_ENABLED +#define HAL_CORTEX_MODULE_ENABLED + +/* ########################## Oscillator Values adaptation ####################*/ +/** + * @brief Adjust the value of External High Speed oscillator (HSE) used in your application. + * This value is used by the RCC HAL module to compute the system frequency + * (when HSE is used as system clock source, directly or through the PLL). + */ +#if !defined (HSE_VALUE) +#define HSE_VALUE 24000000UL /*!< Value of the External oscillator in Hz */ +#endif /* HSE_VALUE */ + +#if !defined (HSE_STARTUP_TIMEOUT) +#define HSE_STARTUP_TIMEOUT 100UL /*!< Time out for HSE start up (in ms) */ +#endif /* HSE_STARTUP_TIMEOUT */ + +/** + * @brief Internal High Speed oscillator (HSI) value. + * This value is used by the RCC HAL module to compute the system frequency + * (when HSI is used as system clock source, directly or through the PLL). + */ +#if !defined (HSI_VALUE) +#define HSI_VALUE 64000000UL /*!< Value of the Internal oscillator in Hz */ +#endif /* HSI_VALUE */ + +/** + * @brief Internal Low-power oscillator (CSI) default value. + * This value is the default CSI range value after Reset. + */ +#if !defined (CSI_VALUE) +#define CSI_VALUE 4000000UL /*!< Value of the Internal oscillator in Hz */ +#endif /* CSI_VALUE */ + +/** + * @brief Internal High Speed oscillator (HSI48) value for USB OTG FS and RNG. + * This internal oscillator is mainly dedicated to provide a high precision clock to + * the USB peripheral by means of a special Clock Recovery System (CRS) circuitry. + * When the CRS is not used, the HSI48 RC oscillator runs on it default frequency + * which is subject to manufacturing process variations. + */ + #if !defined (HSI48_VALUE) + #define HSI48_VALUE 48000000UL /*!< Value of the Internal High Speed oscillator for USB OTG FS/RNG in Hz. + The real value my vary depending on manufacturing process variations. */ + #endif /* HSI48_VALUE */ + +/** +* @brief Internal Low Speed oscillator (LSI) value. + */ +#if !defined (LSI_VALUE) +#define LSI_VALUE 32000UL /*!< LSI Typical Value in Hz. + Value of the Internal Low Speed oscillator in Hz. + The real value may vary depending on the variations + in voltage and temperature.*/ +#endif /* LSI_VALUE */ + +/** +* @brief External Low Speed oscillator (LSE) value. +*/ +#if !defined (LSE_VALUE) +#define LSE_VALUE 32768UL /*!< Value of the External oscillator in Hz*/ +#endif /* LSE_VALUE */ + +#if !defined (LSE_STARTUP_TIMEOUT) +#define LSE_STARTUP_TIMEOUT 5000UL /*!< Time out for LSE start up (in ms) */ +#endif /* LSE_STARTUP_TIMEOUT */ + +/** + * @brief External clock source for digital audio interfaces: SPI/I2S, SAI and ADF + * This value is used by the RCC HAL module to provide the digital audio interfaces + * frequency. This clock source is inserted directly through I2S_CKIN pad. + */ +#if !defined (EXTERNAL_CLOCK_VALUE) +#define EXTERNAL_CLOCK_VALUE 48000UL /*!< Value of the external clock source in Hz */ +#endif /* EXTERNAL_CLOCK_VALUE */ + +/* Tip: To avoid modifying this file each time you need to use different HSE, + === you can define the HSE value in your toolchain compiler preprocessor. */ + +/* ########################### System Configuration ######################### */ +/** + * @brief This is the HAL system configuration section + */ +#define VDD_VALUE 3300UL /*!< Value of VDD in mv */ +#define TICK_INT_PRIORITY (15UL)/*!< tick interrupt priority (lowest by default) */ +#define USE_RTOS 0U + +/* ########################## Assert Selection ############################## */ +/** +* @brief Uncomment the line below to expanse the "assert_param" macro in the +* HAL drivers code +*/ +/* #define USE_FULL_ASSERT 1U */ + +/* ################## Register callback feature configuration ############### */ +/** +* @brief Set below the peripheral configuration to "1U" to add the support +* of HAL callback registration/unregistration feature for the HAL +* driver(s). This allows user application to provide specific callback +* functions thanks to HAL_PPP_RegisterCallback() rather than overwriting +* the default weak callback functions (see each stm32h7rsxx_hal_ppp.h file +* for possible callback identifiers defined in HAL_PPP_CallbackIDTypeDef +* for each PPP peripheral). +*/ +#define USE_HAL_ADC_REGISTER_CALLBACKS 0U +#define USE_HAL_CEC_REGISTER_CALLBACKS 0U +#define USE_HAL_CORDIC_REGISTER_CALLBACKS 0U +#define USE_HAL_CRYP_REGISTER_CALLBACKS 0U +#define USE_HAL_DCMIPP_REGISTER_CALLBACKS 0U +#define USE_HAL_FDCAN_REGISTER_CALLBACKS 0U +#define USE_HAL_GFXMMU_REGISTER_CALLBACKS 0U +#define USE_HAL_HASH_REGISTER_CALLBACKS 0U +#define USE_HAL_I2C_REGISTER_CALLBACKS 0U +#define USE_HAL_I2S_REGISTER_CALLBACKS 0U +#define USE_HAL_IRDA_REGISTER_CALLBACKS 0U +#define USE_HAL_JPEG_REGISTER_CALLBACKS 0U +#define USE_HAL_LPTIM_REGISTER_CALLBACKS 0U +#define USE_HAL_MDF_REGISTER_CALLBACKS 0U +#define USE_HAL_MMC_REGISTER_CALLBACKS 0U +#define USE_HAL_NAND_REGISTER_CALLBACKS 0U +#define USE_HAL_NOR_REGISTER_CALLBACKS 0U +#define USE_HAL_PCD_REGISTER_CALLBACKS 0U +#define USE_HAL_PKA_REGISTER_CALLBACKS 0U +#define USE_HAL_PSSI_REGISTER_CALLBACKS 0U +#define USE_HAL_RNG_REGISTER_CALLBACKS 0U +#define USE_HAL_RTC_REGISTER_CALLBACKS 0U +#define USE_HAL_SAI_REGISTER_CALLBACKS 0U +#define USE_HAL_SD_REGISTER_CALLBACKS 0U +#define USE_HAL_SDRAM_REGISTER_CALLBACKS 0U +#define USE_HAL_SMARTCARD_REGISTER_CALLBACKS 0U +#define USE_HAL_SMBUS_REGISTER_CALLBACKS 0U +#define USE_HAL_SPDIFRX_REGISTER_CALLBACKS 0U +#define USE_HAL_SPI_REGISTER_CALLBACKS 0U +#define USE_HAL_SRAM_REGISTER_CALLBACKS 0U +#define USE_HAL_TIM_REGISTER_CALLBACKS 0U +#define USE_HAL_UART_REGISTER_CALLBACKS 0U +#define USE_HAL_USART_REGISTER_CALLBACKS 0U +#define USE_HAL_WWDG_REGISTER_CALLBACKS 0U +#define USE_HAL_XSPI_REGISTER_CALLBACKS 0U + +/* ################## SPI peripheral configuration ########################## */ + +/* CRC FEATURE: Use to activate CRC feature inside HAL SPI Driver +* Activated: CRC code is present inside driver +* Deactivated: CRC code cleaned from driver +*/ + +#define USE_SPI_CRC 1U + +/* ################## CRYP peripheral configuration ########################## */ + +#define USE_HAL_CRYP_SUSPEND_RESUME 0U + +/* ################## HASH peripheral configuration ########################## */ + +#define USE_HAL_HASH_SUSPEND_RESUME 0U + +/* ################## SDMMC peripheral configuration ######################### */ + +#define USE_SD_TRANSCEIVER 0U + +/* Includes ------------------------------------------------------------------*/ +/** + * @brief Include module's header file + */ + +#ifdef HAL_RCC_MODULE_ENABLED + #include "stm32h7rsxx_hal_rcc.h" +#endif /* HAL_RCC_MODULE_ENABLED */ + +#ifdef HAL_GPIO_MODULE_ENABLED + #include "stm32h7rsxx_hal_gpio.h" +#endif /* HAL_GPIO_MODULE_ENABLED */ + +#ifdef HAL_DMA_MODULE_ENABLED + #include "stm32h7rsxx_hal_dma.h" +#endif /* HAL_DMA_MODULE_ENABLED */ + +#ifdef HAL_CORTEX_MODULE_ENABLED + #include "stm32h7rsxx_hal_cortex.h" +#endif /* HAL_CORTEX_MODULE_ENABLED */ + +#ifdef HAL_ADC_MODULE_ENABLED + #include "stm32h7rsxx_hal_adc.h" +#endif /* HAL_ADC_MODULE_ENABLED */ + +#ifdef HAL_CEC_MODULE_ENABLED + #include "stm32h7rsxx_hal_cec.h" +#endif /* HAL_CEC_MODULE_ENABLED */ + +#ifdef HAL_CORDIC_MODULE_ENABLED + #include "stm32h7rsxx_hal_cordic.h" +#endif /* HAL_CORDIC_MODULE_ENABLED */ + +#ifdef HAL_CRC_MODULE_ENABLED + #include "stm32h7rsxx_hal_crc.h" +#endif /* HAL_CRC_MODULE_ENABLED */ + +#ifdef HAL_CRYP_MODULE_ENABLED + #include "stm32h7rsxx_hal_cryp.h" +#endif /* HAL_CRYP_MODULE_ENABLED */ + +#ifdef HAL_DCMIPP_MODULE_ENABLED + #include "stm32h7rsxx_hal_dcmipp.h" +#endif /* HAL_DCMIPP_MODULE_ENABLED */ + +#ifdef HAL_DMA2D_MODULE_ENABLED + #include "stm32h7rsxx_hal_dma2d.h" +#endif /* HAL_DMA2D_MODULE_ENABLED */ + +#ifdef HAL_DTS_MODULE_ENABLED + #include "stm32h7rsxx_hal_dts.h" +#endif /* HAL_DTS_MODULE_ENABLED */ + +#ifdef HAL_ETH_MODULE_ENABLED + #include "stm32h7rsxx_hal_eth.h" +#endif /* HAL_ETH_MODULE_ENABLED */ + +#ifdef HAL_EXTI_MODULE_ENABLED + #include "stm32h7rsxx_hal_exti.h" +#endif /* HAL_EXTI_MODULE_ENABLED */ + +#ifdef HAL_FDCAN_MODULE_ENABLED + #include "stm32h7rsxx_hal_fdcan.h" +#endif /* HAL_FDCAN_MODULE_ENABLED */ + +#ifdef HAL_FLASH_MODULE_ENABLED + #include "stm32h7rsxx_hal_flash.h" +#endif /* HAL_FLASH_MODULE_ENABLED */ + +#ifdef HAL_GFXMMU_MODULE_ENABLED + #include "stm32h7rsxx_hal_gfxmmu.h" +#endif /* HAL_GFXMMU_MODULE_ENABLED */ + +#ifdef HAL_GFXTIM_MODULE_ENABLED + #include "stm32h7rsxx_hal_gfxtim.h" +#endif /* HAL_GFXTIM_MODULE_ENABLED */ + +#ifdef HAL_GPU2D_MODULE_ENABLED + #include "stm32h7rsxx_hal_gpu2d.h" +#endif /* HAL_GPU2D_MODULE_ENABLED */ + +#ifdef HAL_HASH_MODULE_ENABLED + #include "stm32h7rsxx_hal_hash.h" +#endif /* HAL_HASH_MODULE_ENABLED */ + +#ifdef HAL_HCD_MODULE_ENABLED + #include "stm32h7rsxx_hal_hcd.h" +#endif /* HAL_HCD_MODULE_ENABLED */ + +#ifdef HAL_I2C_MODULE_ENABLED + #include "stm32h7rsxx_hal_i2c.h" +#endif /* HAL_I2C_MODULE_ENABLED */ + +#ifdef HAL_I2S_MODULE_ENABLED + #include "stm32h7rsxx_hal_i2s.h" +#endif /* HAL_I2S_MODULE_ENABLED */ + +#ifdef HAL_I3C_MODULE_ENABLED + #include "stm32h7rsxx_hal_i3c.h" +#endif /* HAL_I3C_MODULE_ENABLED */ + +#ifdef HAL_ICACHE_MODULE_ENABLED + #include "stm32h7rsxx_hal_icache.h" +#endif /* HAL_ICACHE_MODULE_ENABLED */ + +#ifdef HAL_IRDA_MODULE_ENABLED + #include "stm32h7rsxx_hal_irda.h" +#endif /* HAL_IRDA_MODULE_ENABLED */ + +#ifdef HAL_IWDG_MODULE_ENABLED + #include "stm32h7rsxx_hal_iwdg.h" +#endif /* HAL_IWDG_MODULE_ENABLED */ + +#ifdef HAL_JPEG_MODULE_ENABLED + #include "stm32h7rsxx_hal_jpeg.h" +#endif /* HAL_JPEG_MODULE_ENABLED */ + +#ifdef HAL_LTDC_MODULE_ENABLED + #include "stm32h7rsxx_hal_ltdc.h" +#endif /* HAL_LTDC_MODULE_ENABLED */ + +#ifdef HAL_LPTIM_MODULE_ENABLED + #include "stm32h7rsxx_hal_lptim.h" +#endif /* HAL_LPTIM_MODULE_ENABLED */ + +#ifdef HAL_MCE_MODULE_ENABLED + #include "stm32h7rsxx_hal_mce.h" +#endif /* HAL_MCE_MODULE_ENABLED */ + +#ifdef HAL_MDF_MODULE_ENABLED + #include "stm32h7rsxx_hal_mdf.h" +#endif /* HAL_MDF_MODULE_ENABLED */ + +#ifdef HAL_MMC_MODULE_ENABLED + #include "stm32h7rsxx_hal_mmc.h" +#endif /* HAL_MMC_MODULE_ENABLED */ + +#ifdef HAL_NAND_MODULE_ENABLED + #include "stm32h7rsxx_hal_nand.h" +#endif /* HAL_NAND_MODULE_ENABLED */ + +#ifdef HAL_NOR_MODULE_ENABLED + #include "stm32h7rsxx_hal_nor.h" +#endif /* HAL_NOR_MODULE_ENABLED */ + +#ifdef HAL_PCD_MODULE_ENABLED + #include "stm32h7rsxx_hal_pcd.h" +#endif /* HAL_PCD_MODULE_ENABLED */ + +#ifdef HAL_PKA_MODULE_ENABLED + #include "stm32h7rsxx_hal_pka.h" +#endif /* HAL_PKA_MODULE_ENABLED */ + +#ifdef HAL_PSSI_MODULE_ENABLED + #include "stm32h7rsxx_hal_pssi.h" +#endif /* HAL_PSSI_MODULE_ENABLED */ + +#ifdef HAL_PWR_MODULE_ENABLED + #include "stm32h7rsxx_hal_pwr.h" +#endif /* HAL_PWR_MODULE_ENABLED */ + +#ifdef HAL_RAMECC_MODULE_ENABLED + #include "stm32h7rsxx_hal_ramecc.h" +#endif /* HAL_RAMECC_MODULE_ENABLED */ + +#ifdef HAL_RNG_MODULE_ENABLED + #include "stm32h7rsxx_hal_rng.h" +#endif /* HAL_RNG_MODULE_ENABLED */ + +#ifdef HAL_RTC_MODULE_ENABLED + #include "stm32h7rsxx_hal_rtc.h" +#endif /* HAL_RTC_MODULE_ENABLED */ + +#ifdef HAL_SAI_MODULE_ENABLED + #include "stm32h7rsxx_hal_sai.h" +#endif /* HAL_SAI_MODULE_ENABLED */ + +#ifdef HAL_SD_MODULE_ENABLED + #include "stm32h7rsxx_hal_sd.h" +#endif /* HAL_SD_MODULE_ENABLED */ + +#ifdef HAL_SDRAM_MODULE_ENABLED + #include "stm32h7rsxx_hal_sdram.h" +#endif /* HAL_SDRAM_MODULE_ENABLED */ + +#ifdef HAL_SMARTCARD_MODULE_ENABLED + #include "stm32h7rsxx_hal_smartcard.h" +#endif /* HAL_SMARTCARD_MODULE_ENABLED */ + +#ifdef HAL_SMBUS_MODULE_ENABLED + #include "stm32h7rsxx_hal_smbus.h" +#endif /* HAL_SMBUS_MODULE_ENABLED */ + +#ifdef HAL_SPDIFRX_MODULE_ENABLED + #include "stm32h7rsxx_hal_spdifrx.h" +#endif /* HAL_SPDIFRX_MODULE_ENABLED */ + +#ifdef HAL_SPI_MODULE_ENABLED + #include "stm32h7rsxx_hal_spi.h" +#endif /* HAL_SPI_MODULE_ENABLED */ + +#ifdef HAL_SRAM_MODULE_ENABLED + #include "stm32h7rsxx_hal_sram.h" +#endif /* HAL_SRAM_MODULE_ENABLED */ + +#ifdef HAL_TIM_MODULE_ENABLED + #include "stm32h7rsxx_hal_tim.h" +#endif /* HAL_TIM_MODULE_ENABLED */ + +#ifdef HAL_UART_MODULE_ENABLED + #include "stm32h7rsxx_hal_uart.h" +#endif /* HAL_UART_MODULE_ENABLED */ + +#ifdef HAL_USART_MODULE_ENABLED + #include "stm32h7rsxx_hal_usart.h" +#endif /* HAL_USART_MODULE_ENABLED */ + +#ifdef HAL_WWDG_MODULE_ENABLED + #include "stm32h7rsxx_hal_wwdg.h" +#endif /* HAL_WWDG_MODULE_ENABLED */ + +#ifdef HAL_XSPI_MODULE_ENABLED + #include "stm32h7rsxx_hal_xspi.h" +#endif /* HAL_XSPI_MODULE_ENABLED */ + +/* Exported macro ------------------------------------------------------------*/ +#ifdef USE_FULL_ASSERT +/** + * @brief The assert_param macro is used for function's parameters check. + * @param expr If expr is false, it calls assert_failed function + * which reports the name of the source file and the source + * line number of the call that failed. + * If expr is true, it returns no value. + * @retval None + */ + #define assert_param(expr) ((expr) ? (void)0U : assert_failed((uint8_t *)__FILE__, __LINE__)) +/* Exported functions ------------------------------------------------------- */ + void assert_failed(uint8_t *file, uint32_t line); +#else + #define assert_param(expr) ((void)0U) +#endif /* USE_FULL_ASSERT */ + +#ifdef __cplusplus +} +#endif + +#endif /* STM32H7RSxx_HAL_CONF_H */ diff --git a/hw/bsp/stm32l0/boards/stm32l052dap52/board.h b/hw/bsp/stm32l0/boards/stm32l052dap52/board.h index ee83bbcbc..50bbafadb 100644 --- a/hw/bsp/stm32l0/boards/stm32l052dap52/board.h +++ b/hw/bsp/stm32l0/boards/stm32l052dap52/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: STM32 L052 DAP + url: n/a +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/stm32l0/boards/stm32l052dap52/board.mk b/hw/bsp/stm32l0/boards/stm32l052dap52/board.mk index 0b1348474..e63b41f12 100644 --- a/hw/bsp/stm32l0/boards/stm32l052dap52/board.mk +++ b/hw/bsp/stm32l0/boards/stm32l052dap52/board.mk @@ -1,10 +1,9 @@ +MCU_VARIANT = stm32l052xx CFLAGS += \ -DSTM32L052xx LD_FILE = $(BOARD_PATH)/STM32L052K8Ux_FLASH.ld -SRC_S += $(ST_CMSIS)/Source/Templates/gcc/startup_stm32l052xx.s - # For flash-jlink target JLINK_DEVICE = stm32l052k8 diff --git a/hw/bsp/stm32l0/boards/stm32l0538disco/board.h b/hw/bsp/stm32l0/boards/stm32l0538disco/board.h index 5cda1c15a..29402f00a 100644 --- a/hw/bsp/stm32l0/boards/stm32l0538disco/board.h +++ b/hw/bsp/stm32l0/boards/stm32l0538disco/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: STM32 L0538 Discovery + url: https://www.st.com/en/evaluation-tools/32l0538discovery.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/stm32l0/boards/stm32l0538disco/board.mk b/hw/bsp/stm32l0/boards/stm32l0538disco/board.mk index deed519ba..f3e6978b0 100644 --- a/hw/bsp/stm32l0/boards/stm32l0538disco/board.mk +++ b/hw/bsp/stm32l0/boards/stm32l0538disco/board.mk @@ -1,12 +1,10 @@ +MCU_VARIANT = stm32l053xx CFLAGS += \ -DSTM32L053xx # All source paths should be relative to the top level. LD_FILE = $(BOARD_PATH)/STM32L053C8Tx_FLASH.ld -SRC_S += \ - $(ST_CMSIS)/Source/Templates/gcc/startup_stm32l053xx.s - # For flash-jlink target JLINK_DEVICE = STM32L053R8 diff --git a/hw/bsp/stm32l0/family.c b/hw/bsp/stm32l0/family.c index c8c88d687..b28903e00 100644 --- a/hw/bsp/stm32l0/family.c +++ b/hw/bsp/stm32l0/family.c @@ -24,6 +24,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: STMicroelectronics +*/ + #include "stm32l0xx_hal.h" #include "bsp/board_api.h" #include "board.h" diff --git a/hw/bsp/stm32l0/family.cmake b/hw/bsp/stm32l0/family.cmake index c04927585..954bdb158 100644 --- a/hw/bsp/stm32l0/family.cmake +++ b/hw/bsp/stm32l0/family.cmake @@ -11,7 +11,7 @@ set(CMSIS_5 ${TOP}/lib/CMSIS_5) include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) # toolchain set up -set(CMAKE_SYSTEM_PROCESSOR cortex-m0plus CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU cortex-m0plus CACHE INTERNAL "System Processor") set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) set(FAMILY_MCUS STM32L0 CACHE INTERNAL "") @@ -101,16 +101,16 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_STM32L0 ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC + family_add_tinyusb(${TARGET} OPT_MCU_STM32L0) + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) # Flashing + family_add_bin_hex(${TARGET}) family_flash_stlink(${TARGET}) family_flash_jlink(${TARGET}) endfunction() diff --git a/hw/bsp/stm32l0/family.mk b/hw/bsp/stm32l0/family.mk index fe7561fc2..921b1b413 100644 --- a/hw/bsp/stm32l0/family.mk +++ b/hw/bsp/stm32l0/family.mk @@ -1,9 +1,4 @@ ST_FAMILY = l0 -DEPS_SUBMODULES += \ - lib/CMSIS_5 \ - hw/mcu/st/cmsis_device_$(ST_FAMILY) \ - hw/mcu/st/stm32$(ST_FAMILY)xx_hal_driver - ST_CMSIS = hw/mcu/st/cmsis_device_$(ST_FAMILY) ST_HAL_DRIVER = hw/mcu/st/stm32$(ST_FAMILY)xx_hal_driver @@ -11,20 +6,17 @@ include $(TOP)/$(BOARD_PATH)/board.mk CPU_CORE ?= cortex-m0plus CFLAGS += \ - -flto \ -DCFG_EXAMPLE_MSC_READONLY \ -DCFG_EXAMPLE_VIDEO_READONLY \ -DCFG_TUSB_MCU=OPT_MCU_STM32L0 # mcu driver cause following warnings CFLAGS_GCC += \ + -flto \ -Wno-error=unused-parameter \ -Wno-error=redundant-decls \ -Wno-error=cast-align \ - -ifeq ($(TOOLCHAIN),gcc) -CFLAGS_GCC += -Wno-error=maybe-uninitialized -endif + -Wno-error=maybe-uninitialized \ CFLAGS_CLANG += \ -Wno-error=parentheses-equality @@ -48,3 +40,10 @@ INC += \ $(TOP)/lib/CMSIS_5/CMSIS/Core/Include \ $(TOP)/$(ST_CMSIS)/Include \ $(TOP)/$(ST_HAL_DRIVER)/Inc + +# Startup +SRC_S_GCC += $(ST_CMSIS)/Source/Templates/gcc/startup_${MCU_VARIANT}.s +SRC_S_IAR += $(ST_CMSIS)/Source/Templates/iar/startup_${MCU_VARIANT}.s + +# Linker +LD_FILE_IAR ?= $(ST_CMSIS)/Source/Templates/iar/linker/$(MCU_VARIANT)_flash.icf diff --git a/hw/bsp/stm32l4/boards/stm32l412nucleo/board.h b/hw/bsp/stm32l4/boards/stm32l412nucleo/board.h index 72d17b760..980e1e321 100644 --- a/hw/bsp/stm32l4/boards/stm32l412nucleo/board.h +++ b/hw/bsp/stm32l4/boards/stm32l412nucleo/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: STM32 L412 Nucleo + url: https://www.st.com/en/evaluation-tools/nucleo-l412kb.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/stm32l4/boards/stm32l476disco/board.h b/hw/bsp/stm32l4/boards/stm32l476disco/board.h index 9d4351b39..8c766d8ea 100644 --- a/hw/bsp/stm32l4/boards/stm32l476disco/board.h +++ b/hw/bsp/stm32l4/boards/stm32l476disco/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: STM32 L476 Disco + url: https://www.st.com/en/evaluation-tools/32l476gdiscovery.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/stm32l4/boards/stm32l4p5nucleo/board.h b/hw/bsp/stm32l4/boards/stm32l4p5nucleo/board.h index 47ada6bb9..f522e7522 100644 --- a/hw/bsp/stm32l4/boards/stm32l4p5nucleo/board.h +++ b/hw/bsp/stm32l4/boards/stm32l4p5nucleo/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: STM32 L4P5 Nucleo + url: https://www.st.com/en/evaluation-tools/nucleo-l4p5zg.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/stm32l4/boards/stm32l4r5nucleo/board.h b/hw/bsp/stm32l4/boards/stm32l4r5nucleo/board.h index 47ada6bb9..c181f5d4a 100644 --- a/hw/bsp/stm32l4/boards/stm32l4r5nucleo/board.h +++ b/hw/bsp/stm32l4/boards/stm32l4r5nucleo/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: STM32 L4R5 Nucleo + url: https://www.st.com/en/evaluation-tools/nucleo-l4r5zi.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/stm32l4/family.c b/hw/bsp/stm32l4/family.c index 965c4810a..2b555b5c2 100644 --- a/hw/bsp/stm32l4/family.c +++ b/hw/bsp/stm32l4/family.c @@ -26,6 +26,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: STMicroelectronics +*/ + #include "stm32l4xx_hal.h" #include "bsp/board_api.h" #include "board.h" diff --git a/hw/bsp/stm32l4/family.cmake b/hw/bsp/stm32l4/family.cmake index 77876cb8b..eebcff4f3 100644 --- a/hw/bsp/stm32l4/family.cmake +++ b/hw/bsp/stm32l4/family.cmake @@ -11,7 +11,7 @@ set(CMSIS_5 ${TOP}/lib/CMSIS_5) include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) # toolchain set up -set(CMAKE_SYSTEM_PROCESSOR cortex-m4 CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU cortex-m4 CACHE INTERNAL "System Processor") set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) set(FAMILY_MCUS STM32L4 CACHE INTERNAL "") @@ -101,19 +101,19 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_${FAMILY_MCUS} ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC + family_add_tinyusb(${TARGET} OPT_MCU_${FAMILY_MCUS}) + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/synopsys/dwc2/dcd_dwc2.c ${TOP}/src/portable/synopsys/dwc2/hcd_dwc2.c ${TOP}/src/portable/synopsys/dwc2/dwc2_common.c ${TOP}/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) # Flashing + family_add_bin_hex(${TARGET}) family_flash_stlink(${TARGET}) family_flash_jlink(${TARGET}) endfunction() diff --git a/hw/bsp/stm32l4/family.mk b/hw/bsp/stm32l4/family.mk index 950b6f9cb..01d059236 100644 --- a/hw/bsp/stm32l4/family.mk +++ b/hw/bsp/stm32l4/family.mk @@ -1,5 +1,4 @@ ST_FAMILY = l4 -DEPS_SUBMODULES += lib/CMSIS_5 hw/mcu/st/cmsis_device_$(ST_FAMILY) hw/mcu/st/stm32$(ST_FAMILY)xx_hal_driver ST_CMSIS = hw/mcu/st/cmsis_device_$(ST_FAMILY) ST_HAL_DRIVER = hw/mcu/st/stm32$(ST_FAMILY)xx_hal_driver diff --git a/hw/bsp/max32690/FreeRTOSConfig/FreeRTOSConfig.h b/hw/bsp/stm32n6/FreeRTOSConfig/FreeRTOSConfig.h similarity index 97% rename from hw/bsp/max32690/FreeRTOSConfig/FreeRTOSConfig.h rename to hw/bsp/stm32n6/FreeRTOSConfig/FreeRTOSConfig.h index e5a76af85..a1b83c802 100644 --- a/hw/bsp/max32690/FreeRTOSConfig/FreeRTOSConfig.h +++ b/hw/bsp/stm32n6/FreeRTOSConfig/FreeRTOSConfig.h @@ -44,10 +44,11 @@ // skip if included from IAR assembler #ifndef __IASMARM__ - #include "mxc_device.h" + #include "stm32n6xx.h" #endif -/* Cortex M23/M33 port configuration. */ +/* Cortex M55 port configuration. */ +#define configENABLE_MVE 0 #define configENABLE_MPU 0 #define configENABLE_FPU 1 #define configENABLE_TRUSTZONE 0 @@ -59,7 +60,7 @@ #define configTICK_RATE_HZ ( 1000 ) #define configMAX_PRIORITIES ( 5 ) #define configMINIMAL_STACK_SIZE ( 128 ) -#define configTOTAL_HEAP_SIZE ( configSUPPORT_DYNAMIC_ALLOCATION*4*1024 ) +#define configTOTAL_HEAP_SIZE ( configSUPPORT_DYNAMIC_ALLOCATION*8*1024 ) #define configMAX_TASK_NAME_LEN 16 #define configUSE_16_BIT_TICKS 0 #define configIDLE_SHOULD_YIELD 1 @@ -127,7 +128,7 @@ //--------------------------------------------------------------------+ // For Cortex-M specific: __NVIC_PRIO_BITS is defined in mcu header -#define configPRIO_BITS __NVIC_PRIO_BITS +#define configPRIO_BITS 4 /* The lowest interrupt priority that can be used in a call to a "set priority" function. */ #define configLIBRARY_LOWEST_INTERRUPT_PRIORITY ((1<ROM + + /* The program code and other data into "RAM" Ram type memory */ + .text : + { + . = ALIGN(4); + *(.text) /* .text sections (code) */ + *(.text*) /* .text* sections (code) */ + *(.glue_7) /* glue arm to thumb code */ + *(.glue_7t) /* glue thumb to arm code */ + *(.eh_frame) + *(.RamFunc) /* .RamFunc sections */ + *(.RamFunc*) /* .RamFunc* sections */ + + KEEP (*(.init)) + KEEP (*(.fini)) + + . = ALIGN(4); + _etext = .; /* define a global symbols at end of code */ + } >ROM + + /* Constant data into "RAM" Ram type memory */ + .rodata : + { + . = ALIGN(4); + *(.rodata) /* .rodata sections (constants, strings, etc.) */ + *(.rodata*) /* .rodata* sections (constants, strings, etc.) */ + . = ALIGN(4); + } >ROM + + .ARM.extab (READONLY) : /* The READONLY keyword is only supported in GCC11 and later, remove it if using GCC10 or earlier. */ + { + . = ALIGN(4); + *(.ARM.extab* .gnu.linkonce.armextab.*) + . = ALIGN(4); + } >ROM + + .ARM (READONLY) : /* The READONLY keyword is only supported in GCC11 and later, remove it if using GCC10 or earlier. */ + { + . = ALIGN(4); + __exidx_start = .; + *(.ARM.exidx*) + __exidx_end = .; + . = ALIGN(4); + } >ROM + + .preinit_array (READONLY) : /* The READONLY keyword is only supported in GCC11 and later, remove it if using GCC10 or earlier. */ + { + . = ALIGN(4); + PROVIDE_HIDDEN (__preinit_array_start = .); + KEEP (*(.preinit_array*)) + PROVIDE_HIDDEN (__preinit_array_end = .); + . = ALIGN(4); + } >ROM + + .init_array (READONLY) : /* The READONLY keyword is only supported in GCC11 and later, remove it if using GCC10 or earlier. */ + { + . = ALIGN(4); + PROVIDE_HIDDEN (__init_array_start = .); + KEEP (*(SORT(.init_array.*))) + KEEP (*(.init_array*)) + PROVIDE_HIDDEN (__init_array_end = .); + . = ALIGN(4); + } >ROM + + .fini_array (READONLY) : /* The READONLY keyword is only supported in GCC11 and later, remove it if using GCC10 or earlier. */ + { + . = ALIGN(4); + PROVIDE_HIDDEN (__fini_array_start = .); + KEEP (*(SORT(.fini_array.*))) + KEEP (*(.fini_array*)) + PROVIDE_HIDDEN (__fini_array_end = .); + . = ALIGN(4); + } >ROM + + /* Used by the startup to initialize data */ + _sidata = LOADADDR(.data); + + /* Initialized data sections into "RAM" Ram type memory */ + .data : + { + . = ALIGN(4); + _sdata = .; /* create a global symbol at data start */ + *(.data) /* .data sections */ + *(.data*) /* .data* sections */ + + . = ALIGN(4); + _edata = .; /* define a global symbol at data end */ + + } >RAM AT> ROM + + .noncacheable : + { + . = ALIGN(8); + __snoncacheable = .;/* create symbol for start of section */ + KEEP(*(.noncacheable)) + . = ALIGN(8); + __enoncacheable = .; /* create symbol for end of section */ + } > RAM + + + .gnu.sgstubs : + { + . = ALIGN(4); + *(.gnu.sgstubs*) /* Secure Gateway stubs */ + . = ALIGN(4); + } >ROM + /* Uninitialized data section into "RAM" Ram type memory */ + . = ALIGN(4); + .bss : + { + /* This is used by the startup in order to initialize the .bss section */ + _sbss = .; /* define a global symbol at bss start */ + __bss_start__ = _sbss; + *(.bss) + *(.bss*) + *(COMMON) + + . = ALIGN(4); + _ebss = .; /* define a global symbol at bss end */ + __bss_end__ = _ebss; + } >RAM + + /* User_heap_stack section, used to check that there is enough "RAM" Ram type memory left */ + ._user_heap_stack : + { + . = ALIGN(8); + PROVIDE ( end = . ); + PROVIDE ( _end = . ); + . = . + _Min_Heap_Size; + . = . + _Min_Stack_Size; + . = ALIGN(8); + } >RAM + + /* Remove information from the compiler libraries */ + /DISCARD/ : + { + libc.a ( * ) + libm.a ( * ) + libgcc.a ( * ) + } + + .ARM.attributes 0 : { *(.ARM.attributes) } +} diff --git a/hw/bsp/stm32n6/boards/stm32n657nucleo/board.cmake b/hw/bsp/stm32n6/boards/stm32n657nucleo/board.cmake new file mode 100644 index 000000000..e88efefb9 --- /dev/null +++ b/hw/bsp/stm32n6/boards/stm32n657nucleo/board.cmake @@ -0,0 +1,17 @@ +set(MCU_VARIANT stm32n657xx) +set(JLINK_DEVICE stm32n6xx) + +set(LD_FILE_GNU ${CMAKE_CURRENT_LIST_DIR}/STM32N657XX_AXISRAM2_fsbl.ld) + +function(update_board TARGET) + target_compile_definitions(${TARGET} PUBLIC + STM32N657xx + ) + target_sources(${TARGET} PUBLIC + ${ST_TCPP0203}/tcpp0203.c + ${ST_TCPP0203}/tcpp0203_reg.c + ) + target_include_directories(${TARGET} PUBLIC + ${ST_TCPP0203} + ) +endfunction() diff --git a/hw/bsp/stm32n6/boards/stm32n657nucleo/board.h b/hw/bsp/stm32n6/boards/stm32n657nucleo/board.h new file mode 100644 index 000000000..963ecad61 --- /dev/null +++ b/hw/bsp/stm32n6/boards/stm32n657nucleo/board.h @@ -0,0 +1,283 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2021, Ha Thach (tinyusb.org) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * This file is part of the TinyUSB stack. + */ + +/* metadata: + name: STM32 N657X0-Q Nucleo + url: https://www.st.com/en/evaluation-tools/nucleo-n657x0-q.html +*/ + +#ifndef BOARD_H_ +#define BOARD_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include "stm32n657xx.h" +#include "stm32n6xx_ll_exti.h" +#include "stm32n6xx_ll_system.h" +#include "tcpp0203.h" + +#define UART_DEV USART1 +#define UART_CLK_EN __HAL_RCC_USART1_CLK_ENABLE + +#define BOARD_TUD_RHPORT 1 + +// VBUS Sense detection +#define OTG_FS_VBUS_SENSE 1 +#define OTG_HS_VBUS_SENSE 1 + +#define PINID_LED 0 +#define PINID_BUTTON 1 +#define PINID_UART_TX 2 +#define PINID_UART_RX 3 +#define PINID_TCPP0203_EN 4 + +static board_pindef_t board_pindef[] = { + {// LED + .port = GPIOG, + .pin_init = {.Pin = GPIO_PIN_10, .Mode = GPIO_MODE_OUTPUT_PP, .Pull = GPIO_PULLDOWN, .Speed = GPIO_SPEED_FREQ_HIGH, .Alternate = 0}, + .active_state = 1}, + {// Button + .port = GPIOC, + .pin_init = {.Pin = GPIO_PIN_13, .Mode = GPIO_MODE_INPUT, .Pull = GPIO_PULLDOWN, .Speed = GPIO_SPEED_FREQ_HIGH, .Alternate = 0}, + .active_state = 1}, + {// UART TX + .port = GPIOE, + .pin_init = {.Pin = GPIO_PIN_5, .Mode = GPIO_MODE_AF_PP, .Pull = GPIO_NOPULL, .Speed = GPIO_SPEED_FREQ_LOW, .Alternate = GPIO_AF7_USART1}, + .active_state = 0}, + {// UART RX + .port = GPIOE, + .pin_init = {.Pin = GPIO_PIN_6, .Mode = GPIO_MODE_AF_PP, .Pull = GPIO_NOPULL, .Speed = GPIO_SPEED_FREQ_LOW, .Alternate = GPIO_AF7_USART1}, + .active_state = 0}, + {// VBUS input pin used for TCPP0203 EN + .port = GPIOA, + .pin_init = {.Pin = GPIO_PIN_7, .Mode = GPIO_MODE_OUTPUT_PP, .Pull = GPIO_PULLDOWN, .Speed = GPIO_SPEED_FREQ_HIGH, .Alternate = 0}, + .active_state = 0}, + { + // I2C SCL for TCPP0203 + .port = GPIOB, + .pin_init = {.Pin = GPIO_PIN_10, .Mode = GPIO_MODE_AF_OD, .Pull = GPIO_NOPULL, .Speed = GPIO_SPEED_FREQ_LOW, .Alternate = GPIO_AF4_I2C2}, + }, + { + // I2C SDA for TCPP0203 + .port = GPIOB, + .pin_init = {.Pin = GPIO_PIN_11, .Mode = GPIO_MODE_AF_OD, .Pull = GPIO_NOPULL, .Speed = GPIO_SPEED_FREQ_LOW, .Alternate = GPIO_AF4_I2C2}, + }, + { + // INT for TCPP0203 + .port = GPIOD, + .pin_init = {.Pin = GPIO_PIN_2, .Mode = GPIO_MODE_IT_FALLING, .Pull = GPIO_PULLUP, .Speed = GPIO_SPEED_FREQ_HIGH, .Alternate = 0}, + }, +}; + +//--------------------------------------------------------------------+ +// RCC Clock +//--------------------------------------------------------------------+ +void SystemClock_Config(void) { + RCC_OscInitTypeDef RCC_OscInitStruct = {0}; + RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; + /* Configure the power domain */ + if (HAL_PWREx_ConfigSupply(PWR_EXTERNAL_SOURCE_SUPPLY) != HAL_OK) { + Error_Handler(); + } + + /* Get current CPU/System buses clocks configuration */ + /* and if necessary switch to intermediate HSI clock */ + /* to ensure target clock can be set */ + HAL_RCC_GetClockConfig(&RCC_ClkInitStruct); + if ((RCC_ClkInitStruct.CPUCLKSource == RCC_CPUCLKSOURCE_IC1) || + (RCC_ClkInitStruct.SYSCLKSource == RCC_SYSCLKSOURCE_IC2_IC6_IC11)) { + RCC_ClkInitStruct.ClockType = (RCC_CLOCKTYPE_CPUCLK | RCC_CLOCKTYPE_SYSCLK); + RCC_ClkInitStruct.CPUCLKSource = RCC_CPUCLKSOURCE_HSI; + RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSI; + if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct) != HAL_OK) { + Error_Handler(); + } + } + + /* HSE selected as source (stable clock on Level 0 samples */ + /* PLL1 output = ((HSE/PLLM)*PLLN)/PLLP1/PLLP2 */ + /* = ((48000000/3)*75)/1/1 */ + /* = (16000000*75)/1/1 */ + /* = 1200000000 (1200 MHz) */ + /* PLL2 off */ + /* PLL3 off */ + /* PLL4 off */ + + /* Enable HSE && HSI */ + RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE; + RCC_OscInitStruct.HSIState = RCC_HSI_OFF; + RCC_OscInitStruct.HSIDiv = RCC_HSI_DIV1; + RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT; + RCC_OscInitStruct.HSEState = RCC_HSE_ON; /* 48 MHz */ + + RCC_OscInitStruct.PLL1.PLLState = RCC_PLL_ON; + RCC_OscInitStruct.PLL1.PLLSource = RCC_PLLSOURCE_HSE; + RCC_OscInitStruct.PLL1.PLLM = 3; + RCC_OscInitStruct.PLL1.PLLN = 75; /* PLL1 VCO = 48/3 * 75 = 1200MHz */ + RCC_OscInitStruct.PLL1.PLLP1 = 1; /* PLL output = PLL VCO frequency / (PLLP1 * PLLP2) */ + RCC_OscInitStruct.PLL1.PLLP2 = 1; /* PLL output = 1200 MHz */ + RCC_OscInitStruct.PLL1.PLLFractional = 0; + + if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { + /* Initialization error */ + Error_Handler(); + } + + /* Select PLL1 outputs as CPU and System bus clock source */ + /* CPUCLK = ic1_ck = PLL1 output/ic1_divider = 600 MHz */ + /* SYSCLK = ic2_ck = PLL1 output/ic2_divider = 400 MHz */ + /* Configure the HCLK clock divider */ + /* HCLK = PLL1 SYSCLK/HCLK divider = 200 MHz */ + /* PCLKx = HCLK / PCLKx divider = 200 MHz */ + RCC_ClkInitStruct.ClockType = (RCC_CLOCKTYPE_CPUCLK | RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | + RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2 | RCC_CLOCKTYPE_PCLK4 | RCC_CLOCKTYPE_PCLK5); + RCC_ClkInitStruct.CPUCLKSource = RCC_CPUCLKSOURCE_IC1; + RCC_ClkInitStruct.IC1Selection.ClockSelection = RCC_ICCLKSOURCE_PLL1; + RCC_ClkInitStruct.IC1Selection.ClockDivider = 2; + RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_IC2_IC6_IC11; + RCC_ClkInitStruct.IC2Selection.ClockSelection = RCC_ICCLKSOURCE_PLL1; + RCC_ClkInitStruct.IC2Selection.ClockDivider = 3; + RCC_ClkInitStruct.IC6Selection.ClockSelection = RCC_ICCLKSOURCE_PLL1; + RCC_ClkInitStruct.IC6Selection.ClockDivider = 3; + RCC_ClkInitStruct.IC11Selection.ClockSelection = RCC_ICCLKSOURCE_PLL1; + RCC_ClkInitStruct.IC11Selection.ClockDivider = 3; + RCC_ClkInitStruct.AHBCLKDivider = RCC_HCLK_DIV2; + RCC_ClkInitStruct.APB1CLKDivider = RCC_APB1_DIV1; + RCC_ClkInitStruct.APB2CLKDivider = RCC_APB2_DIV1; + RCC_ClkInitStruct.APB4CLKDivider = RCC_APB4_DIV1; + RCC_ClkInitStruct.APB5CLKDivider = RCC_APB5_DIV1; + if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct) != HAL_OK) { + /* Initialization Error */ + Error_Handler(); + } + + /** Initializes the peripherals clock + */ + RCC_PeriphCLKInitTypeDef PeriphClkInitStruct = {0}; + PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_USBOTGHS1; + PeriphClkInitStruct.UsbOtgHs1ClockSelection = RCC_USBPHY1REFCLKSOURCE_HSE_DIRECT; + + if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct) != HAL_OK) { + /* Initialization Error */ + Error_Handler(); + } + + /** Set USB OTG HS PHY1 Reference Clock Source */ + PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_USBPHY1; + PeriphClkInitStruct.UsbPhy1ClockSelection = RCC_USBPHY1REFCLKSOURCE_HSE_DIRECT; + + if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct) != HAL_OK) { + /* Initialization Error */ + Error_Handler(); + } +} + +//--------------------------------------------------------------------+ +// USB PD +//--------------------------------------------------------------------+ +static I2C_HandleTypeDef i2c_handle = { + .Instance = I2C2, + .Init = { + .Timing = 0x20C0EDFF, + .OwnAddress1 = 0, + .AddressingMode = I2C_ADDRESSINGMODE_7BIT, + .DualAddressMode = I2C_DUALADDRESS_DISABLE, + .OwnAddress2 = 0, + .OwnAddress2Masks = I2C_OA2_NOMASK, + .GeneralCallMode = I2C_GENERALCALL_DISABLE, + .NoStretchMode = I2C_NOSTRETCH_DISABLE, + }}; +static TCPP0203_Object_t tcpp0203_obj = {0}; + +int32_t board_tcpp0203_init(void) { + board_pindef_t *pindef = &board_pindef[PINID_TCPP0203_EN]; + HAL_GPIO_WritePin(pindef->port, pindef->pin_init.Pin, GPIO_PIN_SET); + + __HAL_RCC_I2C2_CLK_ENABLE(); + __HAL_RCC_I2C2_FORCE_RESET(); + __HAL_RCC_I2C2_RELEASE_RESET(); + if (HAL_I2C_Init(&i2c_handle) != HAL_OK) { + return HAL_ERROR; + } + + NVIC_SetPriority(EXTI8_IRQn, 12); + NVIC_EnableIRQ(EXTI8_IRQn); + + return 0; +} + +int32_t board_tcpp0203_deinit(void) { + return 0; +} + +int32_t i2c_readreg(uint16_t DevAddr, uint16_t Reg, uint8_t *pData, uint16_t Length) { + TU_ASSERT(HAL_OK == HAL_I2C_Mem_Read(&i2c_handle, DevAddr, Reg, I2C_MEMADD_SIZE_8BIT, pData, Length, 10000)); + return 0; +} + +int32_t i2c_writereg(uint16_t DevAddr, uint16_t Reg, uint8_t *pData, uint16_t Length) { + TU_ASSERT(HAL_OK == HAL_I2C_Mem_Write(&i2c_handle, DevAddr, Reg, I2C_MEMADD_SIZE_8BIT, pData, Length, 10000)); + return 0; +} + +static inline void board_init2(void) { + TCPP0203_IO_t io_ctx; + + io_ctx.Address = TCPP0203_I2C_ADDRESS_X68; + io_ctx.Init = board_tcpp0203_init; + io_ctx.DeInit = board_tcpp0203_deinit; + io_ctx.ReadReg = i2c_readreg; + io_ctx.WriteReg = i2c_writereg; + + TU_ASSERT(TCPP0203_RegisterBusIO(&tcpp0203_obj, &io_ctx) == TCPP0203_OK, ); + + TU_ASSERT(TCPP0203_Init(&tcpp0203_obj) == TCPP0203_OK, ); + + TU_ASSERT(TCPP0203_SetPowerMode(&tcpp0203_obj, TCPP0203_POWER_MODE_NORMAL) == TCPP0203_OK, ); +} + +void board_vbus_set(uint8_t rhport, bool state) { + (void) state; + if (rhport == 1) { + TU_ASSERT(TCPP0203_SetGateDriverProvider(&tcpp0203_obj, TCPP0203_GD_PROVIDER_SWITCH_CLOSED) == TCPP0203_OK, ); + } +} + +void EXTI8_IRQHandler(void) { + __HAL_GPIO_EXTI_CLEAR_IT(GPIO_PIN_8); + if (tcpp0203_obj.IsInitialized) { + TU_ASSERT(TCPP0203_SetPowerMode(&tcpp0203_obj, TCPP0203_POWER_MODE_NORMAL) == TCPP0203_OK, ); + TU_ASSERT(TCPP0203_SetGateDriverProvider(&tcpp0203_obj, TCPP0203_GD_PROVIDER_SWITCH_CLOSED) == TCPP0203_OK, ); + } +} + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/hw/bsp/stm32n6/boards/stm32n657nucleo/board.mk b/hw/bsp/stm32n6/boards/stm32n657nucleo/board.mk new file mode 100644 index 000000000..05717699c --- /dev/null +++ b/hw/bsp/stm32n6/boards/stm32n657nucleo/board.mk @@ -0,0 +1,17 @@ +MCU_VARIANT = stm32n657xx +CFLAGS += -DSTM32N657xx +JLINK_DEVICE = stm32n6xx + +LD_FILE_GCC = $(BOARD_PATH)/STM32N657XX_AXISRAM2_fsbl.ld + +# flash target using on-board stlink +flash: flash-stlink + +PORT = 1 + +SRC_C += \ + $(ST_TCPP0203)/tcpp0203.c \ + $(ST_TCPP0203)/tcpp0203_reg.c \ + +INC += \ + $(TOP)/$(ST_TCPP0203) \ diff --git a/hw/bsp/stm32n6/family.c b/hw/bsp/stm32n6/family.c new file mode 100644 index 000000000..1d0616d8e --- /dev/null +++ b/hw/bsp/stm32n6/family.c @@ -0,0 +1,280 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 + * William D. Jones (thor0505@comcast.net), + * Ha Thach (tinyusb.org) + * Uwe Bonnes (bon@elektron.ikp.physik.tu-darmstadt.de + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * This file is part of the TinyUSB stack. + */ + +/* metadata: + manufacturer: STMicroelectronics +*/ + +// Suppress warning caused by mcu driver +#ifdef __GNUC__ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wcast-align" +#endif + +#include "stm32n6xx_hal.h" + +#ifdef __GNUC__ +#pragma GCC diagnostic pop +#endif + +#include "bsp/board_api.h" + +TU_ATTR_UNUSED static void Error_Handler(void) { } + +void HardFault_Handler(void); + +typedef struct { + GPIO_TypeDef* port; + GPIO_InitTypeDef pin_init; + uint8_t active_state; +} board_pindef_t; + +#include "board.h" + +//--------------------------------------------------------------------+ +// MACRO TYPEDEF CONSTANT ENUM +//--------------------------------------------------------------------+ + +#ifdef UART_DEV +UART_HandleTypeDef UartHandle = { + .Instance = UART_DEV, + .Init = { + .BaudRate = CFG_BOARD_UART_BAUDRATE, + .WordLength = UART_WORDLENGTH_8B, + .StopBits = UART_STOPBITS_1, + .Parity = UART_PARITY_NONE, + .HwFlowCtl = UART_HWCONTROL_NONE, + .Mode = UART_MODE_TX_RX, + .OverSampling = UART_OVERSAMPLING_16, + } +}; +#endif + +#ifndef SWO_FREQ +#define SWO_FREQ 4000000 +#endif + +//--------------------------------------------------------------------+ +// Forward USB interrupt events to TinyUSB IRQ Handler +//--------------------------------------------------------------------+ + +// Despite being call USB2_OTG_FS on some MCUs +// OTG_FS is marked as RHPort0 by TinyUSB to be consistent across stm32 port +void USB2_OTG_HS_IRQHandler(void) { + tusb_int_handler(0, true); +} + +// Despite being call USB1_OTG_HS on some MCUs +// OTG_HS is marked as RHPort1 by TinyUSB to be consistent across stm32 port +void USB1_OTG_HS_IRQHandler(void) { + tusb_int_handler(1, true); +} + +void board_init(void) { + + /* Enable BusFault and SecureFault handlers (HardFault is default) */ + SCB->SHCSR |= (SCB_SHCSR_BUSFAULTENA_Msk | SCB_SHCSR_SECUREFAULTENA_Msk); + + HAL_PWREx_EnableVddA(); + HAL_PWREx_EnableVddIO2(); + HAL_PWREx_EnableVddIO3(); + HAL_PWREx_EnableVddIO4(); + HAL_PWREx_EnableVddIO5(); + + HAL_Init(); + + // Implemented in board.h + SystemClock_Config(); + + // Enable All GPIOs clocks + __HAL_RCC_GPIOA_CLK_ENABLE(); + __HAL_RCC_GPIOB_CLK_ENABLE(); + __HAL_RCC_GPIOC_CLK_ENABLE(); + __HAL_RCC_GPIOD_CLK_ENABLE(); + __HAL_RCC_GPIOE_CLK_ENABLE(); + __HAL_RCC_GPIOF_CLK_ENABLE(); + __HAL_RCC_GPIOG_CLK_ENABLE(); + __HAL_RCC_GPIOH_CLK_ENABLE(); + __HAL_RCC_GPION_CLK_ENABLE(); + __HAL_RCC_GPIOO_CLK_ENABLE(); + __HAL_RCC_GPIOP_CLK_ENABLE(); + __HAL_RCC_GPIOQ_CLK_ENABLE(); + + // HAL_ICACHE_Enable(); + + for (uint8_t i = 0; i < TU_ARRAY_SIZE(board_pindef); i++) { + HAL_GPIO_Init(board_pindef[i].port, &board_pindef[i].pin_init); + } + + NVIC_SetPriority(UCPD1_IRQn, NVIC_EncodePriority(NVIC_GetPriorityGrouping(),5, 0)); + NVIC_EnableIRQ(UCPD1_IRQn); + +#if CFG_TUSB_OS == OPT_OS_NONE + // 1ms tick timer + SysTick_Config(SystemCoreClock / 1000); + +#elif CFG_TUSB_OS == OPT_OS_FREERTOS + // Explicitly disable systick to prevent its ISR runs before scheduler start + SysTick->CTRL &= ~1U; + + // If freeRTOS is used, IRQ priority is limit by max syscall ( smaller is higher ) + + NVIC_SetPriority(USB1_OTG_HS_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY ); +#endif + + + +#ifdef UART_DEV + UART_CLK_EN(); + HAL_UART_Init(&UartHandle); +#endif + + + __HAL_RCC_USB1_OTG_HS_CLK_ENABLE(); + __HAL_RCC_PWR_CLK_ENABLE(); + HAL_PWREx_EnableVddUSBVMEN(); + while(__HAL_PWR_GET_FLAG(PWR_FLAG_USB33RDY)); + HAL_PWREx_EnableVddUSB(); + + LL_AHB5_GRP1_ForceReset(0x00800000); + __HAL_RCC_USB1_OTG_HS_FORCE_RESET(); + __HAL_RCC_USB1_OTG_HS_PHY_FORCE_RESET(); + + LL_RCC_HSE_SelectHSEDiv2AsDiv2Clock(); + LL_AHB5_GRP1_ReleaseReset(0x00800000); + + /* Peripheral clock enable */ + __HAL_RCC_USB1_OTG_HS_CLK_ENABLE(); + + /* Required few clock cycles before accessing USB PHY Controller Registers */ + for (volatile uint32_t i = 0; i < 10; i++) { + __NOP(); // No Operation instruction to create a delay + } + + USB1_HS_PHYC->USBPHYC_CR &= ~(0x7 << 0x4); + + USB1_HS_PHYC->USBPHYC_CR |= (0x1 << 16) | + (0x2 << 4) | + (0x1 << 2) | + 0x1U; + + __HAL_RCC_USB1_OTG_HS_PHY_RELEASE_RESET(); + + /* Required few clock cycles before Releasing Reset */ + for (volatile uint32_t i = 0; i < 10; i++) { + __NOP(); // No Operation instruction to create a delay + } + + __HAL_RCC_USB1_OTG_HS_RELEASE_RESET(); + + /* Peripheral PHY clock enable */ + __HAL_RCC_USB1_OTG_HS_PHY_CLK_ENABLE(); + + board_init2(); + +#if CFG_TUH_ENABLED + board_vbus_set(BOARD_TUH_RHPORT, 1); +#endif +} + +//--------------------------------------------------------------------+ +// Board porting API +//--------------------------------------------------------------------+ + +void board_led_write(bool state) { +#ifdef PINID_LED + board_pindef_t* pindef = &board_pindef[PINID_LED]; + GPIO_PinState pin_state = state == pindef->active_state ? GPIO_PIN_SET : GPIO_PIN_RESET; + HAL_GPIO_WritePin(pindef->port, pindef->pin_init.Pin, pin_state); +#else + (void) state; +#endif +} + +uint32_t board_button_read(void) { +#ifdef PINID_BUTTON + board_pindef_t* pindef = &board_pindef[PINID_BUTTON]; + return pindef->active_state == HAL_GPIO_ReadPin(pindef->port, pindef->pin_init.Pin); +#else + return 0; +#endif +} + +size_t board_get_unique_id(uint8_t id[], size_t max_len) { + (void) max_len; + volatile uint32_t * stm32_uuid = (volatile uint32_t *) UID_BASE; + uint32_t* id32 = (uint32_t*) (uintptr_t) id; + uint8_t const len = 12; + + id32[0] = stm32_uuid[0]; + id32[1] = stm32_uuid[1]; + id32[2] = stm32_uuid[2]; + + return len; +} + +int board_uart_read(uint8_t *buf, int len) { + (void) buf; + (void) len; + return 0; +} + +int board_uart_write(void const *buf, int len) { +#ifdef UART_DEV + HAL_UART_Transmit(&UartHandle, (uint8_t * )(uintptr_t) + buf, len, 0xffff); + return len; +#else + (void) buf; (void) len; + return -1; +#endif +} + +#if CFG_TUSB_OS == OPT_OS_NONE +volatile uint32_t system_ticks = 0; + +void SysTick_Handler(void) { + HAL_IncTick(); + system_ticks++; +} + +uint32_t board_millis(void) { + return system_ticks; +} + +#endif + +void HardFault_Handler(void) { + __asm("BKPT #0\n"); +} + +// Required by __libc_init_array in startup code if we are compiling using +// -nostdlib/-nostartfiles. +void _init(void) { +} diff --git a/hw/bsp/stm32n6/family.cmake b/hw/bsp/stm32n6/family.cmake new file mode 100644 index 000000000..76763937e --- /dev/null +++ b/hw/bsp/stm32n6/family.cmake @@ -0,0 +1,148 @@ +include_guard() + +set(ST_FAMILY n6) +set(ST_PREFIX stm32${ST_FAMILY}xx) + +set(ST_HAL_DRIVER ${TOP}/hw/mcu/st/stm32${ST_FAMILY}xx_hal_driver) +set(ST_CMSIS ${TOP}/hw/mcu/st/cmsis_device_${ST_FAMILY}) +set(CMSIS_5 ${TOP}/lib/CMSIS_5) +set(ST_TCPP0203 ${TOP}/hw/mcu/st/stm32-tcpp0203) + +# include board specific +include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) + +# toolchain set up +set(CMAKE_SYSTEM_CPU cortex-m55 CACHE INTERNAL "System Processor") +set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) + +set(FAMILY_MCUS STM32N6 CACHE INTERNAL "") + +# ---------------------- +# Port & Speed Selection +# ---------------------- +if (NOT DEFINED RHPORT_DEVICE) + set(RHPORT_DEVICE 1) +endif () +if (NOT DEFINED RHPORT_HOST) + set(RHPORT_HOST 1) +endif () + +# N6 are all high speed +if (NOT DEFINED RHPORT_DEVICE_SPEED) + set(RHPORT_DEVICE_SPEED OPT_MODE_HIGH_SPEED) +endif () +if (NOT DEFINED RHPORT_HOST_SPEED) + set(RHPORT_HOST_SPEED OPT_MODE_HIGH_SPEED) +endif () + +cmake_print_variables(RHPORT_DEVICE RHPORT_DEVICE_SPEED RHPORT_HOST RHPORT_HOST_SPEED) + +#------------------------------------ +# BOARD_TARGET +#------------------------------------ +# only need to be built ONCE for all examples +function(add_board_target BOARD_TARGET) + if (TARGET ${BOARD_TARGET}) + return() + endif() + + # Startup & Linker script + set(STARTUP_FILE_GNU ${ST_CMSIS}/Source/Templates/gcc/startup_${MCU_VARIANT}.s) + set(STARTUP_FILE_Clang ${STARTUP_FILE_GNU}) + set(STARTUP_FILE_IAR ${ST_CMSIS}/Source/Templates/iar/startup_${MCU_VARIANT}.s) + + if(NOT DEFINED LD_FILE_GNU) + set(LD_FILE_GNU ${ST_CMSIS}/Source/Templates/gcc/linker/${MCU_VARIANT}_flash.ld) + endif() + set(LD_FILE_Clang ${LD_FILE_GNU}) + if(NOT DEFINED LD_FILE_IAR) + set(LD_FILE_IAR ${ST_CMSIS}/Source/Templates/iar/linker/${MCU_VARIANT}_flash.icf) + endif() + + add_library(${BOARD_TARGET} STATIC + ${ST_CMSIS}/Source/Templates/system_${ST_PREFIX}_fsbl.c + ${ST_HAL_DRIVER}/Src/${ST_PREFIX}_hal.c + ${ST_HAL_DRIVER}/Src/${ST_PREFIX}_hal_cortex.c + ${ST_HAL_DRIVER}/Src/${ST_PREFIX}_hal_dma.c + ${ST_HAL_DRIVER}/Src/${ST_PREFIX}_hal_gpio.c + ${ST_HAL_DRIVER}/Src/${ST_PREFIX}_hal_pwr.c + ${ST_HAL_DRIVER}/Src/${ST_PREFIX}_hal_i2c.c + ${ST_HAL_DRIVER}/Src/${ST_PREFIX}_hal_pwr_ex.c + ${ST_HAL_DRIVER}/Src/${ST_PREFIX}_hal_rcc.c + ${ST_HAL_DRIVER}/Src/${ST_PREFIX}_hal_rcc_ex.c + ${ST_HAL_DRIVER}/Src/${ST_PREFIX}_hal_uart.c + ${ST_HAL_DRIVER}/Src/${ST_PREFIX}_hal_uart_ex.c + ${STARTUP_FILE_${CMAKE_C_COMPILER_ID}} + ) + target_include_directories(${BOARD_TARGET} PUBLIC + ${CMAKE_CURRENT_FUNCTION_LIST_DIR} + ${CMSIS_5}/CMSIS/Core/Include + ${ST_CMSIS}/Include + ${ST_HAL_DRIVER}/Inc + ) + target_compile_definitions(${BOARD_TARGET} PUBLIC + BOARD_TUD_RHPORT=${RHPORT_DEVICE} + BOARD_TUD_MAX_SPEED=${RHPORT_DEVICE_SPEED} + BOARD_TUH_RHPORT=${RHPORT_HOST} + BOARD_TUH_MAX_SPEED=${RHPORT_HOST_SPEED} + SEGGER_RTT_SECTION="noncacheable_buffer" + BUFFER_SIZE_UP=0x3000 + ) + + update_board(${BOARD_TARGET}) + + if (CMAKE_C_COMPILER_ID STREQUAL "GNU") + target_link_options(${BOARD_TARGET} PUBLIC + "LINKER:--script=${LD_FILE_GNU}" + -nostartfiles + --specs=nosys.specs --specs=nano.specs + ) + elseif (CMAKE_C_COMPILER_ID STREQUAL "Clang") + target_link_options(${BOARD_TARGET} PUBLIC + "LINKER:--script=${LD_FILE_Clang}" + ) + elseif (CMAKE_C_COMPILER_ID STREQUAL "IAR") + target_link_options(${BOARD_TARGET} PUBLIC + "LINKER:--config=${LD_FILE_IAR}" + ) + endif () +endfunction() + + +#------------------------------------ +# Functions +#------------------------------------ +function(family_configure_example TARGET RTOS) + family_configure_common(${TARGET} ${RTOS}) + + # Board target + add_board_target(board_${BOARD}) + + #---------- Port Specific ---------- + # These files are built for each example since it depends on example's tusb_config.h + target_sources(${TARGET} PUBLIC + # BSP + ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/family.c + ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/../board.c + ) + target_include_directories(${TARGET} PUBLIC + # family, hw, board + ${CMAKE_CURRENT_FUNCTION_LIST_DIR} + ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/../../ + ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/boards/${BOARD} + ) + + # Add TinyUSB target and port source + family_add_tinyusb(${TARGET} OPT_MCU_STM32N6 ${RTOS}) + target_sources(${TARGET} PUBLIC + ${TOP}/src/portable/synopsys/dwc2/dcd_dwc2.c + ${TOP}/src/portable/synopsys/dwc2/hcd_dwc2.c + ${TOP}/src/portable/synopsys/dwc2/dwc2_common.c + ) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + + # Flashing + family_add_bin_hex(${TARGET}) + family_flash_stlink(${TARGET}) + family_flash_jlink(${TARGET}) +endfunction() diff --git a/hw/bsp/stm32n6/family.mk b/hw/bsp/stm32n6/family.mk new file mode 100644 index 000000000..37087ed42 --- /dev/null +++ b/hw/bsp/stm32n6/family.mk @@ -0,0 +1,89 @@ +ST_FAMILY = n6 +ST_PREFIX = stm32${ST_FAMILY}xx +ST_CMSIS = hw/mcu/st/cmsis_device_$(ST_FAMILY) +ST_HAL_DRIVER = hw/mcu/st/${ST_PREFIX}_hal_driver +ST_TCPP0203 = hw/mcu/st/stm32-tcpp0203 + +UF2_FAMILY_ID = 0x6db66083 + +include $(TOP)/$(BOARD_PATH)/board.mk +CPU_CORE ?= cortex-m55 + +# ---------------------- +# Port & Speed Selection +# ---------------------- +RHPORT_DEVICE ?= 1 +RHPORT_HOST ?= 1 + +ifndef RHPORT_DEVICE_SPEED + RHPORT_DEVICE_SPEED = OPT_MODE_HIGH_SPEED +endif + +ifndef RHPORT_HOST_SPEED + RHPORT_HOST_SPEED = OPT_MODE_HIGH_SPEED +endif + +# -------------- +# Compiler Flags +# -------------- +CFLAGS += \ + -DCFG_TUSB_MCU=OPT_MCU_STM32N6 \ + -DBOARD_TUD_RHPORT=${RHPORT_DEVICE} \ + -DBOARD_TUD_MAX_SPEED=${RHPORT_DEVICE_SPEED} \ + -DBOARD_TUH_RHPORT=${RHPORT_HOST} \ + -DBOARD_TUH_MAX_SPEED=${RHPORT_HOST_SPEED} \ + -DSEGGER_RTT_SECTION=\"noncacheable_buffer\" \ + -DBUFFER_SIZE_UP=0x3000 \ + +# GCC Flags +CFLAGS_GCC += \ + -flto \ + +# suppress warning caused by vendor mcu driver +CFLAGS_GCC += \ + -Wno-error=cast-align \ + -Wno-error=unused-parameter \ + +LDFLAGS_GCC += \ + -nostdlib -nostartfiles \ + --specs=nosys.specs --specs=nano.specs + +# ----------------- +# Sources & Include +# ----------------- + +SRC_C += \ + src/portable/synopsys/dwc2/dcd_dwc2.c \ + src/portable/synopsys/dwc2/hcd_dwc2.c \ + src/portable/synopsys/dwc2/dwc2_common.c \ + $(ST_CMSIS)/Source/Templates/system_${ST_PREFIX}_fsbl.c \ + $(ST_HAL_DRIVER)/Src/${ST_PREFIX}_hal.c \ + $(ST_HAL_DRIVER)/Src/${ST_PREFIX}_hal_cortex.c \ + $(ST_HAL_DRIVER)/Src/${ST_PREFIX}_hal_dma.c \ + $(ST_HAL_DRIVER)/Src/${ST_PREFIX}_hal_gpio.c \ + $(ST_HAL_DRIVER)/Src/${ST_PREFIX}_hal_hcd.c \ + $(ST_HAL_DRIVER)/Src/${ST_PREFIX}_hal_i2c.c \ + $(ST_HAL_DRIVER)/Src/${ST_PREFIX}_hal_pcd.c \ + $(ST_HAL_DRIVER)/Src/${ST_PREFIX}_hal_pcd_ex.c \ + $(ST_HAL_DRIVER)/Src/${ST_PREFIX}_hal_pwr.c \ + $(ST_HAL_DRIVER)/Src/${ST_PREFIX}_hal_pwr_ex.c \ + $(ST_HAL_DRIVER)/Src/${ST_PREFIX}_hal_rcc.c \ + $(ST_HAL_DRIVER)/Src/${ST_PREFIX}_hal_rcc_ex.c \ + $(ST_HAL_DRIVER)/Src/${ST_PREFIX}_hal_rif.c \ + $(ST_HAL_DRIVER)/Src/${ST_PREFIX}_hal_uart.c \ + $(ST_HAL_DRIVER)/Src/${ST_PREFIX}_hal_uart_ex.c \ + $(ST_HAL_DRIVER)/Src/${ST_PREFIX}_ll_usb.c \ + +INC += \ + $(TOP)/$(BOARD_PATH) \ + $(TOP)/lib/CMSIS_5/CMSIS/Core/Include \ + $(TOP)/$(ST_CMSIS)/Include \ + $(TOP)/$(ST_HAL_DRIVER)/Inc + +# Startup +SRC_S_GCC += $(ST_CMSIS)/Source/Templates/gcc/startup_$(MCU_VARIANT)_fsbl.s +SRC_S_IAR += $(ST_CMSIS)/Source/Templates/iar/startup_$(MCU_VARIANT).s + +# Linker +LD_FILE_GCC ?= $(ST_CMSIS)/Source/Templates/gcc/linker/$(MCU_VARIANT)_flash.ld +LD_FILE_IAR ?= $(ST_CMSIS)/Source/Templates/iar/linker/$(MCU_VARIANT)_flash.icf diff --git a/hw/bsp/stm32n6/partition_stm32n657xx.h b/hw/bsp/stm32n6/partition_stm32n657xx.h new file mode 100644 index 000000000..4efdc5668 --- /dev/null +++ b/hw/bsp/stm32n6/partition_stm32n657xx.h @@ -0,0 +1,792 @@ +/** + ****************************************************************************** + * @file partition_stm32n657xx.h + * @author MCD Application Team + * @brief CMSIS STM32N657xx Device Initial Setup for Secure / Non-Secure Zones + * for ARMCM55 based on CMSIS CORE V5.3.1 partition_ARMCM33.h Template. + * + * This file contains: + * - Initialize Security Attribution Unit (SAU) CTRL register + * - Setup behavior of Sleep and Exception Handling + * - Setup behavior of Floating Point Unit + * - Setup Interrupt Target + * + ******************************************************************************/ +/* + * Copyright (c) 2009-2016 ARM Limited. All rights reserved. + * Portions Copyright (c) 2023 STMicroelectronics, all rights reserved + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PARTITION_STM32N657XX_H +#define PARTITION_STM32N657XX_H + +/* +//-------- <<< Use Configuration Wizard in Context Menu >>> ----------------- +*/ + +/* +// Initialize Security Attribution Unit (SAU) CTRL register +*/ +#define SAU_INIT_CTRL 0 + +/* +// Enable SAU +// Value for SAU->CTRL register bit ENABLE +*/ +#define SAU_INIT_CTRL_ENABLE 0 + +/* +// When SAU is disabled +// <0=> All Memory is Secure +// <1=> All Memory is Non-Secure +// Value for SAU->CTRL register bit ALLNS +// When all Memory is Non-Secure (ALLNS is 1), IDAU can override memory map configuration. +*/ +#define SAU_INIT_CTRL_ALLNS 0 + +/* +// +*/ + +/* +// Initialize Security Attribution Unit (SAU) Address Regions +// SAU configuration specifies regions to be one of: +// - Secure and Non-Secure Callable +// - Non-Secure +// Note: All memory regions not configured by SAU are Secure +*/ +#define SAU_REGIONS_MAX 8 /* Max. number of SAU regions */ + +/* +// Initialize SAU Region 0 +// Setup SAU Region 0 memory attributes +*/ +#define SAU_INIT_REGION0 0 + +/* +// Start Address <0-0xFFFFFFE0> +*/ +#define SAU_INIT_START0 0x00000000 /* start address of SAU region 0 */ + +/* +// End Address <0x1F-0xFFFFFFFF> +*/ +#define SAU_INIT_END0 0x00000000 /* end address of SAU region 0 */ + +/* +// Region is +// <0=>Non-Secure +// <1=>Secure, Non-Secure Callable +*/ +#define SAU_INIT_NSC0 0 +/* +// +*/ + +/* +// Initialize SAU Region 1 +// Setup SAU Region 1 memory attributes +*/ +#define SAU_INIT_REGION1 0 + +/* +// Start Address <0-0xFFFFFFE0> +*/ +#define SAU_INIT_START1 0x00000000 /* start address of SAU region 1 */ + +/* +// End Address <0x1F-0xFFFFFFFF> +*/ +#define SAU_INIT_END1 0x00000000 /* end address of SAU region 1 */ + +/* +// Region is +// <0=>Non-Secure +// <1=>Secure, Non-Secure Callable +*/ +#define SAU_INIT_NSC1 0 +/* +// +*/ + +/* +// Initialize SAU Region 2 +// Setup SAU Region 2 memory attributes +*/ +#define SAU_INIT_REGION2 0 + +/* +// Start Address <0-0xFFFFFFE0> +*/ +#define SAU_INIT_START2 0x00000000 /* start address of SAU region 2 */ + +/* +// End Address <0x1F-0xFFFFFFFF> +*/ +#define SAU_INIT_END2 0x00000000 /* end address of SAU region 2 */ + +/* +// Region is +// <0=>Non-Secure +// <1=>Secure, Non-Secure Callable +*/ +#define SAU_INIT_NSC2 0 +/* +// +*/ + +/* +// Initialize SAU Region 3 +// Setup SAU Region 3 memory attributes +*/ +#define SAU_INIT_REGION3 0 + +/* +// Start Address <0-0xFFFFFFE0> +*/ +#define SAU_INIT_START3 0x00000000 /* start address of SAU region 3 */ + +/* +// End Address <0x1F-0xFFFFFFFF> +*/ +#define SAU_INIT_END3 0x00000000 /* end address of SAU region 3 */ + +/* +// Region is +// <0=>Non-Secure +// <1=>Secure, Non-Secure Callable +*/ +#define SAU_INIT_NSC3 0 +/* +// +*/ + +/* +// Initialize SAU Region 4 +// Setup SAU Region 4 memory attributes +*/ +#define SAU_INIT_REGION4 0 + +/* +// Start Address <0-0xFFFFFFE0> +*/ +#define SAU_INIT_START4 0x00000000 /* start address of SAU region 4 */ + +/* +// End Address <0x1F-0xFFFFFFFF> +*/ +#define SAU_INIT_END4 0x00000000 /* end address of SAU region 4 */ + +/* +// Region is +// <0=>Non-Secure +// <1=>Secure, Non-Secure Callable +*/ +#define SAU_INIT_NSC4 0 +/* +// +*/ + +/* +// Initialize SAU Region 5 +// Setup SAU Region 5 memory attributes +*/ +#define SAU_INIT_REGION5 0 + +/* +// Start Address <0-0xFFFFFFE0> +*/ +#define SAU_INIT_START5 0x00000000 /* start address of SAU region 5 */ + +/* +// End Address <0x1F-0xFFFFFFFF> +*/ +#define SAU_INIT_END5 0x00000000 /* end address of SAU region 5 */ + +/* +// Region is +// <0=>Non-Secure +// <1=>Secure, Non-Secure Callable +*/ +#define SAU_INIT_NSC5 0 +/* +// +*/ + +/* +// Initialize SAU Region 6 +// Setup SAU Region 6 memory attributes +*/ +#define SAU_INIT_REGION6 0 + +/* +// Start Address <0-0xFFFFFFE0> +*/ +#define SAU_INIT_START6 0x00000000 /* start address of SAU region 6 */ + +/* +// End Address <0x1F-0xFFFFFFFF> +*/ +#define SAU_INIT_END6 0x00000000 /* end address of SAU region 6 */ + +/* +// Region is +// <0=>Non-Secure +// <1=>Secure, Non-Secure Callable +*/ +#define SAU_INIT_NSC6 0 +/* +// +*/ + +/* +// Initialize SAU Region 7 +// Setup SAU Region 7 memory attributes +*/ +#define SAU_INIT_REGION7 0 + +/* +// Start Address <0-0xFFFFFFE0> +*/ +#define SAU_INIT_START7 0x00000000 /* start address of SAU region 7 */ + +/* +// End Address <0x1F-0xFFFFFFFF> +*/ +#define SAU_INIT_END7 0x00000000 /* end address of SAU region 7 */ + +/* +// Region is +// <0=>Non-Secure +// <1=>Secure, Non-Secure Callable +*/ +#define SAU_INIT_NSC7 0 +/* +// +*/ + +/* +// +*/ + +/* +// Setup behaviour of Sleep and Exception Handling +*/ +#define SCB_CSR_AIRCR_INIT 0 + +/* +// Deep Sleep can be enabled by +// <0=>Secure and Non-Secure state +// <1=>Secure state only +// Value for SCB->CSR register bit DEEPSLEEPS +*/ +#define SCB_CSR_DEEPSLEEPS_VAL 0 + +/* +// System reset request accessible from +// <0=> Secure and Non-Secure state +// <1=> Secure state only +// Value for SCB->AIRCR register bit SYSRESETREQS +*/ +#define SCB_AIRCR_SYSRESETREQS_VAL 0 + +/* +// Priority of Non-Secure exceptions is +// <0=> Not altered +// <1=> Lowered to 0x04-0x07 +// Value for SCB->AIRCR register bit PRIS +*/ +#define SCB_AIRCR_PRIS_VAL 0 + +/* +// BusFault, HardFault, and NMI target +// <0=> Secure state +// <1=> Non-Secure state +// Value for SCB->AIRCR register bit BFHFNMINS +*/ +#define SCB_AIRCR_BFHFNMINS_VAL 0 + +/* +// +*/ + +/* +// Setup behaviour of Floating Point Unit +*/ +#define TZ_FPU_NS_USAGE 1 + +/* +// Floating Point Unit usage +// <0=> Secure state only +// <3=> Secure and Non-Secure state +// Value for SCB->NSACR register bits CP10, CP11 +*/ +#define SCB_NSACR_CP10_11_VAL 3 + +/* +// Treat floating-point registers as Secure +// <0=> Disabled +// <1=> Enabled +// Value for FPU->FPCCR register bit TS +*/ +#define FPU_FPCCR_TS_VAL 0 + +/* +// Clear on return (CLRONRET) accessibility +// <0=> Secure and Non-Secure state +// <1=> Secure state only +// Value for FPU->FPCCR register bit CLRONRETS +*/ +#define FPU_FPCCR_CLRONRETS_VAL 0 + +/* +// Clear floating-point caller saved registers on exception return +// <0=> Disabled +// <1=> Enabled +// Value for FPU->FPCCR register bit CLRONRET +*/ +#define FPU_FPCCR_CLRONRET_VAL 1 + +/* +// +*/ + +/* +// Setup Interrupt Target +*/ + +/* +// Initialize ITNS 0 (Interrupts 0..31) +*/ +#define NVIC_INIT_ITNS0 1 + +/* +// Interrupts 0..31 +// PVD_IRQn <0=> Secure state <1=> Non-Secure state +// Reserved <0=> Secure state <1=> Non-Secure state +// DTS_IRQn <0=> Secure state <1=> Non-Secure state +// RCC_IRQn <0=> Secure state <1=> Non-Secure state +// LOCKUP_IRQn <0=> Secure state <1=> Non-Secure state +// CACHE_ECC_IRQn <0=> Secure state <1=> Non-Secure state +// TCM_ECC_IRQn <0=> Secure state <1=> Non-Secure state +// BKP_ECC_IRQn <0=> Secure state <1=> Non-Secure state +// FPU_IRQn <0=> Secure state <1=> Non-Secure state +// Reserved <0=> Secure state <1=> Non-Secure state +// RTC_S_IRQn <0=> Secure state <1=> Non-Secure state +// TAMP_IRQn <0=> Secure state <1=> Non-Secure state +// RIFSC_TAMPER_IRQn <0=> Secure state <1=> Non-Secure state +// IAC_IRQn <0=> Secure state <1=> Non-Secure state +// RCC_S_IRQn <0=> Secure state <1=> Non-Secure state +// Reserved <0=> Secure state <1=> Non-Secure state +// RTC_IRQn <0=> Secure state <1=> Non-Secure state +// Reserved <0=> Secure state <1=> Non-Secure state +// IWDG_IRQn <0=> Secure state <1=> Non-Secure state +// WWDG_IRQn <0=> Secure state <1=> Non-Secure state +// EXTI0_IRQn <0=> Secure state <1=> Non-Secure state +// EXTI1_IRQn <0=> Secure state <1=> Non-Secure state +// EXTI2_IRQn <0=> Secure state <1=> Non-Secure state +// EXTI3_IRQn <0=> Secure state <1=> Non-Secure state +// EXTI4_IRQn <0=> Secure state <1=> Non-Secure state +// EXTI5_IRQn <0=> Secure state <1=> Non-Secure state +// EXTI6_IRQn <0=> Secure state <1=> Non-Secure state +// EXTI7_IRQn <0=> Secure state <1=> Non-Secure state +// EXTI8_IRQn <0=> Secure state <1=> Non-Secure state +// EXTI9_IRQn <0=> Secure state <1=> Non-Secure state +// EXTI10_IRQn <0=> Secure state <1=> Non-Secure state +// EXTI11_IRQn <0=> Secure state <1=> Non-Secure state +*/ +#define NVIC_INIT_ITNS0_VAL 0x00000000 + +/* +// +*/ + +/* +// Initialize ITNS 1 (Interrupts 32..63) +*/ +#define NVIC_INIT_ITNS1 1 + +/* +// Interrupts 32..63 +// EXTI12_IRQn <0=> Secure state <1=> Non-Secure state +// EXTI13_IRQn <0=> Secure state <1=> Non-Secure state +// EXTI14_IRQn <0=> Secure state <1=> Non-Secure state +// EXTI15_IRQn <0=> Secure state <1=> Non-Secure state +// SAES_IRQn <0=> Secure state <1=> Non-Secure state +// CRYP_IRQn <0=> Secure state <1=> Non-Secure state +// PKA_IRQn <0=> Secure state <1=> Non-Secure state +// HASH_IRQn <0=> Secure state <1=> Non-Secure state +// RNG_IRQn <0=> Secure state <1=> Non-Secure state +// Reserved <0=> Secure state <1=> Non-Secure state +// MCE1_IRQn <0=> Secure state <1=> Non-Secure state +// MCE2_IRQn <0=> Secure state <1=> Non-Secure state +// MCE3_IRQn <0=> Secure state <1=> Non-Secure state +// MCE4_IRQn <0=> Secure state <1=> Non-Secure state +// ADC1_2_IRQn <0=> Secure state <1=> Non-Secure state +// CSI_IRQn <0=> Secure state <1=> Non-Secure state +// DCMIPP_IRQn <0=> Secure state <1=> Non-Secure state +// Reserved <0=> Secure state <1=> Non-Secure state +// Reserved <0=> Secure state <1=> Non-Secure state +// Reserved <0=> Secure state <1=> Non-Secure state +// PAHB_ERR_IRQn <0=> Secure state <1=> Non-Secure state +// NPU0_IRQn <0=> Secure state <1=> Non-Secure state +// NPU1_IRQn <0=> Secure state <1=> Non-Secure state +// NPU2_IRQn <0=> Secure state <1=> Non-Secure state +// NPU3_IRQn <0=> Secure state <1=> Non-Secure state +// CACHEAXI_IRQn <0=> Secure state <1=> Non-Secure state +// LTDC_LO_IRQn <0=> Secure state <1=> Non-Secure state +// LTDC_LO_ERR_IRQn <0=> Secure state <1=> Non-Secure state +// DMA2D_IRQn <0=> Secure state <1=> Non-Secure state +// JPEG_IRQn <0=> Secure state <1=> Non-Secure state +// VENC_IRQn <0=> Secure state <1=> Non-Secure state +// GFXMMU_IRQn <0=> Secure state <1=> Non-Secure state +*/ +#define NVIC_INIT_ITNS1_VAL 0x00000000 + +/* +// +*/ + +/* +// Initialize ITNS 2 (Interrupts 64..95) +*/ +#define NVIC_INIT_ITNS2 1 + +/* +// Interrupts 64..95 +// GFXTIM_IRQn <0=> Secure state <1=> Non-Secure state +// GPU2D_IRQn <0=> Secure state <1=> Non-Secure state +// GPU2D_ER_IRQn <0=> Secure state <1=> Non-Secure state +// ICACHE_IRQn <0=> Secure state <1=> Non-Secure state +// HPDMA1_Channel0_IRQn <0=> Secure state <1=> Non-Secure state +// HPDMA1_Channel1_IRQn <0=> Secure state <1=> Non-Secure state +// HPDMA1_Channel2_IRQn <0=> Secure state <1=> Non-Secure state +// HPDMA1_Channel3_IRQn <0=> Secure state <1=> Non-Secure state +// HPDMA1_Channel4_IRQn <0=> Secure state <1=> Non-Secure state +// HPDMA1_Channel5_IRQn <0=> Secure state <1=> Non-Secure state +// HPDMA1_Channel6_IRQn <0=> Secure state <1=> Non-Secure state +// HPDMA1_Channel7_IRQn <0=> Secure state <1=> Non-Secure state +// HPDMA1_Channel8_IRQn <0=> Secure state <1=> Non-Secure state +// HPDMA1_Channel9_IRQn <0=> Secure state <1=> Non-Secure state +// HPDMA1_Channel10_IRQn <0=> Secure state <1=> Non-Secure state +// HPDMA1_Channel11_IRQn <0=> Secure state <1=> Non-Secure state +// HPDMA1_Channel12_IRQn <0=> Secure state <1=> Non-Secure state +// HPDMA1_Channel13_IRQn <0=> Secure state <1=> Non-Secure state +// HPDMA1_Channel14_IRQn <0=> Secure state <1=> Non-Secure state +// HPDMA1_Channel15_IRQn <0=> Secure state <1=> Non-Secure state +// GPDMA1_Channel0_IRQn <0=> Secure state <1=> Non-Secure state +// GPDMA1_Channel1_IRQn <0=> Secure state <1=> Non-Secure state +// GPDMA1_Channel2_IRQn <0=> Secure state <1=> Non-Secure state +// GPDMA1_Channel3_IRQn <0=> Secure state <1=> Non-Secure state +// GPDMA1_Channel4_IRQn <0=> Secure state <1=> Non-Secure state +// GPDMA1_Channel5_IRQn <0=> Secure state <1=> Non-Secure state +// GPDMA1_Channel6_IRQn <0=> Secure state <1=> Non-Secure state +// GPDMA1_Channel7_IRQn <0=> Secure state <1=> Non-Secure state +// GPDMA1_Channel8_IRQn <0=> Secure state <1=> Non-Secure state +// GPDMA1_Channel9_IRQn <0=> Secure state <1=> Non-Secure state +// GPDMA1_Channel10_IRQn <0=> Secure state <1=> Non-Secure state +// GPDMA1_Channel11_IRQn <0=> Secure state <1=> Non-Secure state +*/ +#define NVIC_INIT_ITNS2_VAL 0x00000000 + +/* +// +*/ + +/* +// Initialize ITNS 3 (Interrupts 96..127) +*/ +#define NVIC_INIT_ITNS3 1 + +/* +// Interrupts 96..127 +// GPDMA1_Channel12_IRQn <0=> Secure state <1=> Non-Secure state +// GPDMA1_Channel13_IRQn <0=> Secure state <1=> Non-Secure state +// GPDMA1_Channel14_IRQn <0=> Secure state <1=> Non-Secure state +// GPDMA1_Channel15_IRQn <0=> Secure state <1=> Non-Secure state +// I2C1_EV_IRQn <0=> Secure state <1=> Non-Secure state +// I2C1_ER_IRQn <0=> Secure state <1=> Non-Secure state +// I2C2_EV_IRQn <0=> Secure state <1=> Non-Secure state +// I2C2_ER_IRQn <0=> Secure state <1=> Non-Secure state +// I2C3_EV_IRQn <0=> Secure state <1=> Non-Secure state +// I2C3_ER_IRQn <0=> Secure state <1=> Non-Secure state +// I2C4_EV_IRQn <0=> Secure state <1=> Non-Secure state +// I2C4_ER_IRQn <0=> Secure state <1=> Non-Secure state +// I3C1_EV_IRQn <0=> Secure state <1=> Non-Secure state +// I3C1_ER_IRQn <0=> Secure state <1=> Non-Secure state +// I3C2_EV_IRQn <0=> Secure state <1=> Non-Secure state +// I3C2_ER_IRQn <0=> Secure state <1=> Non-Secure state +// TIM1_BRK_IRQn <0=> Secure state <1=> Non-Secure state +// TIM1_UP_IRQn <0=> Secure state <1=> Non-Secure state +// TIM1_TRG_COM_IRQn <0=> Secure state <1=> Non-Secure state +// TIM1_CC_IRQn <0=> Secure state <1=> Non-Secure state +// TIM2_IRQn <0=> Secure state <1=> Non-Secure state +// TIM3_IRQn <0=> Secure state <1=> Non-Secure state +// TIM4_IRQn <0=> Secure state <1=> Non-Secure state +// TIM5_IRQn <0=> Secure state <1=> Non-Secure state +// TIM6_IRQn <0=> Secure state <1=> Non-Secure state +// TIM7_IRQn <0=> Secure state <1=> Non-Secure state +// TIM8_BRK_IRQn <0=> Secure state <1=> Non-Secure state +// TIM8_UP_IRQn <0=> Secure state <1=> Non-Secure state +// TIM8_TRG_COM_IRQn <0=> Secure state <1=> Non-Secure state +// TIM8_CC_IRQn <0=> Secure state <1=> Non-Secure state +// TIM9_IRQn <0=> Secure state <1=> Non-Secure state +// TIM10_IRQn <0=> Secure state <1=> Non-Secure state + +*/ +#define NVIC_INIT_ITNS3_VAL 0x00000000 + +/* +// +*/ + +/* +// Initialize ITNS 4 (Interrupts 128..159) +*/ +#define NVIC_INIT_ITNS4 1 + +/* +// Interrupts 128..159 +// TIM11_IRQn <0=> Secure state <1=> Non-Secure state +// TIM12_IRQn <0=> Secure state <1=> Non-Secure state +// TIM13_IRQn <0=> Secure state <1=> Non-Secure state +// TIM14_IRQn <0=> Secure state <1=> Non-Secure state +// TIM15_IRQn <0=> Secure state <1=> Non-Secure state +// TIM16_IRQn <0=> Secure state <1=> Non-Secure state +// TIM17_IRQn <0=> Secure state <1=> Non-Secure state +// TIM18_IRQn <0=> Secure state <1=> Non-Secure state +// LPTIM1_IRQn <0=> Secure state <1=> Non-Secure state +// LPTIM2_IRQn <0=> Secure state <1=> Non-Secure state +// LPTIM3_IRQn <0=> Secure state <1=> Non-Secure state +// LPTIM4_IRQn <0=> Secure state <1=> Non-Secure state +// LPTIM5_IRQn <0=> Secure state <1=> Non-Secure state +// ADF1_FLT0_IRQn <0=> Secure state <1=> Non-Secure state +// MDF1_FLT0_IRQn <0=> Secure state <1=> Non-Secure state +// MDF1_FLT1_IRQn <0=> Secure state <1=> Non-Secure state +// MDF1_FLT2_IRQn <0=> Secure state <1=> Non-Secure state +// MDF1_FLT3_IRQn <0=> Secure state <1=> Non-Secure state +// MDF1_FLT4_IRQn <0=> Secure state <1=> Non-Secure state +// MDF1_FLT5_IRQn <0=> Secure state <1=> Non-Secure state +// SAI1_A_IRQn <0=> Secure state <1=> Non-Secure state +// SAI1_B_IRQn <0=> Secure state <1=> Non-Secure state +// SAI2_A_IRQn <0=> Secure state <1=> Non-Secure state +// SAI2_B_IRQn <0=> Secure state <1=> Non-Secure state +// SPDIFRX1_IRQn <0=> Secure state <1=> Non-Secure state +// SPI1_IRQn <0=> Secure state <1=> Non-Secure state +// SPI2_IRQn <0=> Secure state <1=> Non-Secure state +// SPI3_IRQn <0=> Secure state <1=> Non-Secure state +// SPI4_IRQn <0=> Secure state <1=> Non-Secure state +// SPI5_IRQn <0=> Secure state <1=> Non-Secure state +// SPI6_IRQn <0=> Secure state <1=> Non-Secure state +// USART1_IRQn <0=> Secure state <1=> Non-Secure state + +*/ +#define NVIC_INIT_ITNS4_VAL 0x00000000 + +/* +// +*/ + +/* +// Initialize ITNS 5 (Interrupts 160..191) +*/ +#define NVIC_INIT_ITNS5 1 + +/* +// Interrupts 160..191 +// USART2_IRQn <0=> Secure state <1=> Non-Secure state +// USART3_IRQn <0=> Secure state <1=> Non-Secure state +// UART4_IRQn <0=> Secure state <1=> Non-Secure state +// UART5_IRQn <0=> Secure state <1=> Non-Secure state +// USART6_IRQn <0=> Secure state <1=> Non-Secure state +// UART7_IRQn <0=> Secure state <1=> Non-Secure state +// UART8_IRQn <0=> Secure state <1=> Non-Secure state +// UART9_IRQn <0=> Secure state <1=> Non-Secure state +// USART10_IRQn <0=> Secure state <1=> Non-Secure state +// LPUART1_IRQn <0=> Secure state <1=> Non-Secure state +// XSPI1_IRQn <0=> Secure state <1=> Non-Secure state +// XSPI2_IRQn <0=> Secure state <1=> Non-Secure state +// XSPI3_IRQn <0=> Secure state <1=> Non-Secure state +// FMC_IRQn <0=> Secure state <1=> Non-Secure state +// SDMMC1_IRQn <0=> Secure state <1=> Non-Secure state +// SDMMC2_IRQn <0=> Secure state <1=> Non-Secure state +// UCPD1_IRQn <0=> Secure state <1=> Non-Secure state +// USB1_OTG_HS_IRQn <0=> Secure state <1=> Non-Secure state +// USB2_OTG_HS_IRQn <0=> Secure state <1=> Non-Secure state +// ETH1_IRQn <0=> Secure state <1=> Non-Secure state +// FDCAN1_IT0_IRQn <0=> Secure state <1=> Non-Secure state +// FDCAN1_IT1_IRQn <0=> Secure state <1=> Non-Secure state +// FDCAN2_IT0_IRQn <0=> Secure state <1=> Non-Secure state +// FDCAN2_IT1_IRQn <0=> Secure state <1=> Non-Secure state +// FDCAN3_IT0_IRQn <0=> Secure state <1=> Non-Secure state +// FDCAN3_IT1_IRQn <0=> Secure state <1=> Non-Secure state +// FDCAN_CU_IRQn <0=> Secure state <1=> Non-Secure state +// MDIOS_IRQn <0=> Secure state <1=> Non-Secure state +// DCMI_PSSI_IRQn <0=> Secure state <1=> Non-Secure state +// WAKEUP_PIN_IRQn <0=> Secure state <1=> Non-Secure state +// CTI_INT0_IRQn <0=> Secure state <1=> Non-Secure state +// CTI_INT1_IRQn <0=> Secure state <1=> Non-Secure state + +*/ +#define NVIC_INIT_ITNS5_VAL 0x00000000 + +/* +// +*/ + +/* +// Initialize ITNS 6 (Interrupts 192..223) +*/ +#define NVIC_INIT_ITNS6 1 + +/* +// Interrupts 192..223 +// Reserved <0=> Secure state <1=> Non-Secure state +// LTDC_UP_IRQn <0=> Secure state <1=> Non-Secure state +// LTDC_UP_ERR_IRQn <0=> Secure state <1=> Non-Secure state + +*/ +#define NVIC_INIT_ITNS6_VAL 0x00000000 + +/* +// +*/ + +/* +// +*/ + + + +/* + max 8 SAU regions. + SAU regions are defined in partition.h + */ + +#define SAU_INIT_REGION(n) \ + SAU->RNR = (n & SAU_RNR_REGION_Msk); \ + SAU->RBAR = (SAU_INIT_START##n & SAU_RBAR_BADDR_Msk); \ + SAU->RLAR = (SAU_INIT_END##n & SAU_RLAR_LADDR_Msk) | \ + ((SAU_INIT_NSC##n << SAU_RLAR_NSC_Pos) & SAU_RLAR_NSC_Msk) | 1U + +/** + \brief Setup a SAU Region + \details Writes the region information contained in SAU_Region to the + registers SAU_RNR, SAU_RBAR, and SAU_RLAR + */ +__STATIC_INLINE void TZ_SAU_Setup (void) +{ + +#if defined (__SAUREGION_PRESENT) && (__SAUREGION_PRESENT == 1U) + + #if defined (SAU_INIT_REGION0) && (SAU_INIT_REGION0 == 1U) + SAU_INIT_REGION(0); + #endif + + #if defined (SAU_INIT_REGION1) && (SAU_INIT_REGION1 == 1U) + SAU_INIT_REGION(1); + #endif + + #if defined (SAU_INIT_REGION2) && (SAU_INIT_REGION2 == 1U) + SAU_INIT_REGION(2); + #endif + + #if defined (SAU_INIT_REGION3) && (SAU_INIT_REGION3 == 1U) + SAU_INIT_REGION(3); + #endif + + #if defined (SAU_INIT_REGION4) && (SAU_INIT_REGION4 == 1U) + SAU_INIT_REGION(4); + #endif + + #if defined (SAU_INIT_REGION5) && (SAU_INIT_REGION5 == 1U) + SAU_INIT_REGION(5); + #endif + + #if defined (SAU_INIT_REGION6) && (SAU_INIT_REGION6 == 1U) + SAU_INIT_REGION(6); + #endif + + #if defined (SAU_INIT_REGION7) && (SAU_INIT_REGION7 == 1U) + SAU_INIT_REGION(7); + #endif + + /* repeat this for all possible SAU regions */ + +#endif /* defined (__SAUREGION_PRESENT) && (__SAUREGION_PRESENT == 1U) */ + + + #if defined (SAU_INIT_CTRL) && (SAU_INIT_CTRL == 1U) + SAU->CTRL = ((SAU_INIT_CTRL_ENABLE << SAU_CTRL_ENABLE_Pos) & SAU_CTRL_ENABLE_Msk) | + ((SAU_INIT_CTRL_ALLNS << SAU_CTRL_ALLNS_Pos) & SAU_CTRL_ALLNS_Msk) ; + #endif + + #if defined (SCB_CSR_AIRCR_INIT) && (SCB_CSR_AIRCR_INIT == 1U) + SCB->SCR = (SCB->SCR & ~(SCB_SCR_SLEEPDEEPS_Msk )) | + ((SCB_CSR_DEEPSLEEPS_VAL << SCB_SCR_SLEEPDEEPS_Pos) & SCB_SCR_SLEEPDEEPS_Msk); + + SCB->AIRCR = (SCB->AIRCR & ~(SCB_AIRCR_VECTKEY_Msk | SCB_AIRCR_SYSRESETREQS_Msk | + SCB_AIRCR_BFHFNMINS_Msk | SCB_AIRCR_PRIS_Msk) ) | + ((0x05FAU << SCB_AIRCR_VECTKEY_Pos) & SCB_AIRCR_VECTKEY_Msk) | + ((SCB_AIRCR_SYSRESETREQS_VAL << SCB_AIRCR_SYSRESETREQS_Pos) & SCB_AIRCR_SYSRESETREQS_Msk) | + ((SCB_AIRCR_PRIS_VAL << SCB_AIRCR_PRIS_Pos) & SCB_AIRCR_PRIS_Msk) | + ((SCB_AIRCR_BFHFNMINS_VAL << SCB_AIRCR_BFHFNMINS_Pos) & SCB_AIRCR_BFHFNMINS_Msk); + #endif /* defined (SCB_CSR_AIRCR_INIT) && (SCB_CSR_AIRCR_INIT == 1U) */ + + #if defined (__FPU_USED) && (__FPU_USED == 1U) && \ + defined (TZ_FPU_NS_USAGE) && (TZ_FPU_NS_USAGE == 1U) + + SCB->NSACR = (SCB->NSACR & ~(SCB_NSACR_CP10_Msk | SCB_NSACR_CP11_Msk)) | + ((SCB_NSACR_CP10_11_VAL << SCB_NSACR_CP10_Pos) & (SCB_NSACR_CP10_Msk | SCB_NSACR_CP11_Msk)); + + FPU->FPCCR = (FPU->FPCCR & ~(FPU_FPCCR_TS_Msk | FPU_FPCCR_CLRONRETS_Msk | FPU_FPCCR_CLRONRET_Msk)) | + ((FPU_FPCCR_TS_VAL << FPU_FPCCR_TS_Pos ) & FPU_FPCCR_TS_Msk ) | + ((FPU_FPCCR_CLRONRETS_VAL << FPU_FPCCR_CLRONRETS_Pos) & FPU_FPCCR_CLRONRETS_Msk) | + ((FPU_FPCCR_CLRONRET_VAL << FPU_FPCCR_CLRONRET_Pos ) & FPU_FPCCR_CLRONRET_Msk ); + #endif + + #if defined (NVIC_INIT_ITNS0) && (NVIC_INIT_ITNS0 == 1U) + NVIC->ITNS[0] = NVIC_INIT_ITNS0_VAL; + #endif + + #if defined (NVIC_INIT_ITNS1) && (NVIC_INIT_ITNS1 == 1U) + NVIC->ITNS[1] = NVIC_INIT_ITNS1_VAL; + #endif + + #if defined (NVIC_INIT_ITNS2) && (NVIC_INIT_ITNS2 == 1U) + NVIC->ITNS[2] = NVIC_INIT_ITNS2_VAL; + #endif + + #if defined (NVIC_INIT_ITNS3) && (NVIC_INIT_ITNS3 == 1U) + NVIC->ITNS[3] = NVIC_INIT_ITNS3_VAL; + #endif + + #if defined (NVIC_INIT_ITNS4) && (NVIC_INIT_ITNS4 == 1U) + NVIC->ITNS[4] = NVIC_INIT_ITNS4_VAL; + #endif + + #if defined (NVIC_INIT_ITNS5) && (NVIC_INIT_ITNS5 == 1U) + NVIC->ITNS[5] = NVIC_INIT_ITNS5_VAL; + #endif + + #if defined (NVIC_INIT_ITNS6) && (NVIC_INIT_ITNS6 == 1U) + NVIC->ITNS[6] = NVIC_INIT_ITNS6_VAL; + #endif + +} + +#endif /* PARTITION_STM32N657XX_H */ diff --git a/hw/bsp/stm32n6/stm32n6xx_hal_conf.h b/hw/bsp/stm32n6/stm32n6xx_hal_conf.h new file mode 100644 index 000000000..00cb31159 --- /dev/null +++ b/hw/bsp/stm32n6/stm32n6xx_hal_conf.h @@ -0,0 +1,504 @@ +/** + ****************************************************************************** + * @file stm32n6xx_hal_conf_template.h + * @author MCD Application Team + * @brief HAL configuration template file. + * This file should be copied to the application folder and renamed + * to stm32n6xx_hal_conf.h. + ****************************************************************************** + * @attention + * + * Copyright (c) 2023 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef STM32N6xx_HAL_CONF_H +#define STM32N6xx_HAL_CONF_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ + +/* ########################## Module Selection ############################## */ +/** + * @brief This is the list of modules to be used in the HAL driver + */ +#define HAL_MODULE_ENABLED +/*#define HAL_ADC_MODULE_ENABLED */ +/*#define HAL_BSEC_MODULE_ENABLED */ +/*#define HAL_CRC_MODULE_ENABLED */ +/*#define HAL_CRYP_MODULE_ENABLED */ +/*#define HAL_DCMI_MODULE_ENABLED */ +/*#define HAL_DCMIPP_MODULE_ENABLED */ +/*#define HAL_DMA2D_MODULE_ENABLED */ +/*#define HAL_DTS_MODULE_ENABLED */ +/*#define HAL_ETH_MODULE_ENABLED */ +/*#define HAL_EXTI_MODULE_ENABLED */ +/*#define HAL_FDCAN_MODULE_ENABLED */ +/*#define HAL_GFXMMU_MODULE_ENABLED */ +/*#define HAL_GFXTIM_MODULE_ENABLED */ +/*#define HAL_HASH_MODULE_ENABLED */ +/*#define HAL_HCD_MODULE_ENABLED */ +#define HAL_I2C_MODULE_ENABLED +/*#define HAL_I2S_MODULE_ENABLED */ +/*#define HAL_I3C_MODULE_ENABLED */ +/*#define HAL_ICACHE_MODULE_ENABLED */ +/*#define HAL_IRDA_MODULE_ENABLED */ +/*#define HAL_IWDG_MODULE_ENABLED */ +/*#define HAL_JPEG_MODULE_ENABLED */ +/*#define HAL_LPTIM_MODULE_ENABLED */ +/*#define HAL_LTDC_MODULE_ENABLED */ +/*#define HAL_MCE_MODULE_ENABLED */ +/*#define HAL_MDF_MODULE_ENABLED */ +/*#define HAL_MMC_MODULE_ENABLED */ +/*#define HAL_NAND_MODULE_ENABLED */ +/*#define HAL_NOR_MODULE_ENABLED */ +/*#define HAL_PCD_MODULE_ENABLED */ +/*#define HAL_PKA_MODULE_ENABLED */ +/*#define HAL_PSSI_MODULE_ENABLED */ +/*#define HAL_RAMCFG_MODULE_ENABLED */ +/*#define HAL_RIF_MODULE_ENABLED */ +/*#define HAL_RNG_MODULE_ENABLED */ +/*#define HAL_RTC_MODULE_ENABLED */ +/*#define HAL_SAI_MODULE_ENABLED */ +/*#define HAL_SD_MODULE_ENABLED */ +/*#define HAL_SDIO_MODULE_ENABLED */ +/*#define HAL_SDRAM_MODULE_ENABLED */ +/*#define HAL_SMARTCARD_MODULE_ENABLED*/ +/*#define HAL_SMBUS_MODULE_ENABLED */ +/*#define HAL_SPDIFRX_MODULE_ENABLED */ +/*#define HAL_SPI_MODULE_ENABLED */ +/*#define HAL_SRAM_MODULE_ENABLED */ +/*#define HAL_TIM_MODULE_ENABLED */ +#define HAL_UART_MODULE_ENABLED +/*#define HAL_USART_MODULE_ENABLED */ +/*#define HAL_WWDG_MODULE_ENABLED */ +/*#define HAL_XSPI_MODULE_ENABLED */ +/*#define HAL_CACHEAXI_MODULE_ENABLED */ +/*#define HAL_MDIOS_MODULE_ENABLED */ +/*#define HAL_GPU2D_MODULE_ENABLED */ +/*#define HAL_CACHEAXI_MODULE_ENABLED */ +#define HAL_GPIO_MODULE_ENABLED +#define HAL_EXTI_MODULE_ENABLED +#define HAL_DMA_MODULE_ENABLED +#define HAL_RCC_MODULE_ENABLED +#define HAL_PWR_MODULE_ENABLED +#define HAL_CORTEX_MODULE_ENABLED + +/* ########################## Oscillator Values adaptation ####################*/ +/** + * @brief Adjust the value of External High Speed oscillator (HSE) used in your application. + * This value is used by the RCC HAL module to compute the system frequency + * (when HSE is used as system clock source, directly or through the PLL). + */ +#if !defined (HSE_VALUE) +#define HSE_VALUE 48000000UL /*!< Value of the External oscillator in Hz */ +#endif /* HSE_VALUE */ + +#if !defined (HSE_STARTUP_TIMEOUT) +#define HSE_STARTUP_TIMEOUT 100UL /*!< Time out for HSE start up, in ms */ +#endif /* HSE_STARTUP_TIMEOUT */ + +/** + * @brief External Low Speed oscillator (LSE) value. + * This value is used by the UART, RTC HAL module to compute the system frequency + */ +#if !defined (LSE_VALUE) +#define LSE_VALUE 32768UL /*!< Value of the External oscillator in Hz */ +#endif /* LSE_VALUE */ + +#if !defined (LSE_STARTUP_TIMEOUT) +#define LSE_STARTUP_TIMEOUT 5000UL /*!< Time out for LSE start up, in ms */ +#endif /* LSE_STARTUP_TIMEOUT */ + +/** + * @brief Internal Multiple Speed oscillator (MSI) default value. + * This value is the default MSI range value after Reset. + */ +#if !defined (MSI_VALUE) +#define MSI_VALUE 4000000UL /*!< Value of the Internal oscillator in Hz */ +#endif /* MSI_VALUE */ + +/** + * @brief Internal High Speed oscillator (HSI) value. + * This value is used by the RCC HAL module to compute the system frequency + * (when HSI is used as system clock source, directly or through the PLL). + */ +#if !defined (HSI_VALUE) +#define HSI_VALUE 64000000UL /*!< Value of the Internal oscillator in Hz */ +#endif /* HSI_VALUE */ + +/** + * @brief Internal Low Speed oscillator (LSI) value. + */ +#if !defined (LSI_VALUE) +#define LSI_VALUE 32000UL /*!< LSI Typical Value in Hz */ +#endif /* LSI_VALUE */ /*!< Value of the Internal Low Speed oscillator in Hz */ +/* The real value may vary depending on the variations in voltage and temperature.*/ + +/* Tip: To avoid modifying this file each time you need to use different HSE, + === you can define the HSE value in your toolchain compiler preprocessor. */ + +/* ########################### System Configuration ######################### */ +/** + * @brief This is the HAL system configuration section + */ +#define VDD_VALUE 3300UL /*!< Value of VDD in mv */ +#define TICK_INT_PRIORITY 15U /*!< tick interrupt priority (lowest by default) */ +#define USE_RTOS 0U + +/* ########################## Assert Selection ############################## */ +/** + * @brief Uncomment the line below to expanse the "assert_param" macro in the + * HAL drivers code + */ +/* #define USE_FULL_ASSERT 1U */ + +/* ################## Register callback feature configuration ############### */ +/** + * @brief Set below the peripheral configuration to "1U" to add the support + * of HAL callback registration/unregistration feature for the HAL + * driver(s). This allows user application to provide specific callback + * functions thanks to HAL_PPP_RegisterCallback() rather than overwriting + * the default weak callback functions (see each stm32n6xx_hal_ppp.h file + * for possible callback identifiers defined in HAL_PPP_CallbackIDTypeDef + * for each PPP peripheral). + */ +#define USE_HAL_ADC_REGISTER_CALLBACKS 0U /* ADC register callback disabled */ +#define USE_HAL_CACHEAXI_REGISTER_CALLBACKS 0U /* CACHEAXI register callback disabled */ +#define USE_HAL_CRYP_REGISTER_CALLBACKS 0U /* CRYP register callback disabled */ +#define USE_HAL_DCMI_REGISTER_CALLBACKS 0U /* DCMI register callback disabled */ +#define USE_HAL_DCMIPP_REGISTER_CALLBACKS 0U /* DCMIPP register callback disabled */ +#define USE_HAL_DMA2D_REGISTER_CALLBACKS 0U /* DMA2D register callback disabled */ +#define USE_HAL_DTS_REGISTER_CALLBACKS 0U /* DTS register callback disabled */ +#define USE_HAL_ETH_REGISTER_CALLBACKS 0U /* ETH register callback disabled */ +#define USE_HAL_FDCAN_REGISTER_CALLBACKS 0U /* FDCAN register callback disabled */ +#define USE_HAL_GFXMMU_REGISTER_CALLBACKS 0U /* GFXMMU register callback disabled */ +#define USE_HAL_GFXTIM_REGISTER_CALLBACKS 0U /* GFXTIM register callback disabled */ +#define USE_HAL_HASH_REGISTER_CALLBACKS 0U /* HASH register callback disabled */ +#define USE_HAL_HCD_REGISTER_CALLBACKS 0U /* HCD register callback disabled */ +#define USE_HAL_I2C_REGISTER_CALLBACKS 0U /* I2C register callback disabled */ +#define USE_HAL_I2S_REGISTER_CALLBACKS 0U /* I2S register callback disabled */ +#define USE_HAL_I3C_REGISTER_CALLBACKS 0U /* I3C register callback disabled */ +#define USE_HAL_IWDG_REGISTER_CALLBACKS 0U /* IWDG register callback disabled */ +#define USE_HAL_IRDA_REGISTER_CALLBACKS 0U /* IRDA register callback disabled */ +#define USE_HAL_LPTIM_REGISTER_CALLBACKS 0U /* LPTIM register callback disabled */ +#define USE_HAL_LTDC_REGISTER_CALLBACKS 0U /* LTDC register callback disabled */ +#define USE_HAL_MCE_REGISTER_CALLBACKS 0U /* MCE register callback disabled */ +#define USE_HAL_MDF_REGISTER_CALLBACKS 0U /* MDF register callback disabled */ +#define USE_HAL_MMC_REGISTER_CALLBACKS 0U /* MMC register callback disabled */ +#define USE_HAL_NAND_REGISTER_CALLBACKS 0U /* NAND register callback disabled */ +#define USE_HAL_NOR_REGISTER_CALLBACKS 0U /* NOR register callback disabled */ +#define USE_HAL_PCD_REGISTER_CALLBACKS 0U /* PCD register callback disabled */ +#define USE_HAL_PKA_REGISTER_CALLBACKS 0U /* PKA register callback disabled */ +#define USE_HAL_PSSI_REGISTER_CALLBACKS 0U /* PSSI register callback disabled */ +#define USE_HAL_RAMCFG_REGISTER_CALLBACKS 0U /* RAMCFG register callback disabled */ +#define USE_HAL_RNG_REGISTER_CALLBACKS 0U /* RNG register callback disabled */ +#define USE_HAL_RTC_REGISTER_CALLBACKS 0U /* RTC register callback disabled */ +#define USE_HAL_SAI_REGISTER_CALLBACKS 0U /* SAI register callback disabled */ +#define USE_HAL_SD_REGISTER_CALLBACKS 0U /* SD register callback disabled */ +#define USE_HAL_SDIO_REGISTER_CALLBACKS 0U /* SDIO register callback disabled */ +#define USE_HAL_SDRAM_REGISTER_CALLBACKS 0U /* SDRAM register callback disabled */ +#define USE_HAL_SMARTCARD_REGISTER_CALLBACKS 0U /* SMARTCARD register callback disabled */ +#define USE_HAL_SMBUS_REGISTER_CALLBACKS 0U /* SMBUS register callback disabled */ +#define USE_HAL_SPDIFRX_REGISTER_CALLBACKS 0U /* SPDIFRX register callback disabled */ +#define USE_HAL_SPI_REGISTER_CALLBACKS 0U /* SPI register callback disabled */ +#define USE_HAL_SRAM_REGISTER_CALLBACKS 0U /* SRAM register callback disabled */ +#define USE_HAL_TIM_REGISTER_CALLBACKS 0U /* TIM register callback disabled */ +#define USE_HAL_UART_REGISTER_CALLBACKS 0U /* UART register callback disabled */ +#define USE_HAL_USART_REGISTER_CALLBACKS 0U /* USART register callback disabled */ +#define USE_HAL_WWDG_REGISTER_CALLBACKS 0U /* WWDG register callback disabled */ +#define USE_HAL_XSPI_REGISTER_CALLBACKS 0U /* XSPI register callback disabled */ + +/* ################## SPI peripheral configuration ########################## */ + +/* CRC FEATURE: Use to activate CRC feature inside HAL SPI Driver + * Activated: CRC code is present inside driver + * Deactivated: CRC code cleaned from driver + */ +#define USE_SPI_CRC 0U + +/* ################## SDMMC peripheral configuration ######################### */ + +#define USE_SD_TRANSCEIVER 0U + +/* ################## SDIO peripheral configuration ########################## */ +#define USE_SDIO_TRANSCEIVER 1U +#define SDIO_MAX_IO_NUMBER 7U /*!< SDIO device support maximum IO number */ + +/* Includes ------------------------------------------------------------------*/ +/** + * @brief Include module's header file + */ +#ifdef HAL_RCC_MODULE_ENABLED +#include "stm32n6xx_hal_rcc.h" +#endif /* HAL_RCC_MODULE_ENABLED */ + +#ifdef HAL_GPIO_MODULE_ENABLED +#include "stm32n6xx_hal_gpio.h" +#endif /* HAL_GPIO_MODULE_ENABLED */ + +#ifdef HAL_RIF_MODULE_ENABLED +#include "stm32n6xx_hal_rif.h" +#endif /* HAL_RIF_MODULE_ENABLED */ + +#ifdef HAL_DMA_MODULE_ENABLED +#include "stm32n6xx_hal_dma.h" +#endif /* HAL_DMA_MODULE_ENABLED */ + +#ifdef HAL_CACHEAXI_MODULE_ENABLED +#include "stm32n6xx_hal_cacheaxi.h" +#endif /* HAL_CACHEAXI_MODULE_ENABLED */ + +#ifdef HAL_CORTEX_MODULE_ENABLED +#include "stm32n6xx_hal_cortex.h" +#endif /* HAL_CORTEX_MODULE_ENABLED */ + +#ifdef HAL_ADC_MODULE_ENABLED +#include "stm32n6xx_hal_adc.h" +#endif /* HAL_ADC_MODULE_ENABLED */ + +#ifdef HAL_BSEC_MODULE_ENABLED +#include "stm32n6xx_hal_bsec.h" +#endif /* HAL_BSEC_MODULE_ENABLED */ + +#ifdef HAL_CRC_MODULE_ENABLED +#include "stm32n6xx_hal_crc.h" +#endif /* HAL_CRC_MODULE_ENABLED */ + +#ifdef HAL_CRYP_MODULE_ENABLED +#include "stm32n6xx_hal_cryp.h" +#endif /* HAL_CRYP_MODULE_ENABLED */ + +#ifdef HAL_DCMI_MODULE_ENABLED +#include "stm32n6xx_hal_dcmi.h" +#endif /* HAL_DCMI_MODULE_ENABLED */ + +#ifdef HAL_DCMIPP_MODULE_ENABLED +#include "stm32n6xx_hal_dcmipp.h" +#endif /* HAL_DCMIPP_MODULE_ENABLED */ + +#ifdef HAL_DMA2D_MODULE_ENABLED +#include "stm32n6xx_hal_dma2d.h" +#endif /* HAL_DMA2D_MODULE_ENABLED */ + +#ifdef HAL_DTS_MODULE_ENABLED +#include "stm32n6xx_hal_dts.h" +#endif /* HAL_DTS_MODULE_ENABLED */ + +#ifdef HAL_ETH_MODULE_ENABLED +#include "stm32n6xx_hal_eth.h" +#endif /* HAL_ETH_MODULE_ENABLED */ + +#ifdef HAL_EXTI_MODULE_ENABLED +#include "stm32n6xx_hal_exti.h" +#endif /* HAL_EXTI_MODULE_ENABLED */ + +#ifdef HAL_FDCAN_MODULE_ENABLED +#include "stm32n6xx_hal_fdcan.h" +#endif /* HAL_FDCAN_MODULE_ENABLED */ + +#ifdef HAL_GFXMMU_MODULE_ENABLED +#include "stm32n6xx_hal_gfxmmu.h" +#endif /* HAL_GFXMMU_MODULE_ENABLED */ + +#ifdef HAL_GFXTIM_MODULE_ENABLED +#include "stm32n6xx_hal_gfxtim.h" +#endif /* HAL_GFXTIM_MODULE_ENABLED */ + +#ifdef HAL_GPIO_MODULE_ENABLED +#include "stm32n6xx_hal_gpio.h" +#endif /* HAL_GPIO_MODULE_ENABLED */ + +#ifdef HAL_GPU2D_MODULE_ENABLED +#include "stm32n6xx_hal_gpu2d.h" +#endif /* HAL_GPU2D_MODULE_ENABLED */ + +#ifdef HAL_HASH_MODULE_ENABLED +#include "stm32n6xx_hal_hash.h" +#endif /* HAL_HASH_MODULE_ENABLED */ + +#ifdef HAL_HCD_MODULE_ENABLED +#include "stm32n6xx_hal_hcd.h" +#endif /* HAL_HCD_MODULE_ENABLED */ + +#ifdef HAL_I2C_MODULE_ENABLED +#include "stm32n6xx_hal_i2c.h" +#endif /* HAL_I2C_MODULE_ENABLED */ + +#ifdef HAL_I2S_MODULE_ENABLED + #include "stm32n6xx_hal_i2s.h" +#endif /* HAL_I2S_MODULE_ENABLED */ + +#ifdef HAL_I3C_MODULE_ENABLED +#include "stm32n6xx_hal_i3c.h" +#endif /* HAL_I3C_MODULE_ENABLED */ + +#ifdef HAL_ICACHE_MODULE_ENABLED +#include "stm32n6xx_hal_icache.h" +#endif /* HAL_ICACHE_MODULE_ENABLED */ + +#ifdef HAL_IRDA_MODULE_ENABLED +#include "stm32n6xx_hal_irda.h" +#endif /* HAL_IRDA_MODULE_ENABLED */ + +#ifdef HAL_IWDG_MODULE_ENABLED +#include "stm32n6xx_hal_iwdg.h" +#endif /* HAL_IWDG_MODULE_ENABLED */ + +#ifdef HAL_JPEG_MODULE_ENABLED +#include "stm32n6xx_hal_jpeg.h" +#endif /* HAL_JPEG_MODULE_ENABLED */ + +#ifdef HAL_LPTIM_MODULE_ENABLED +#include "stm32n6xx_hal_lptim.h" +#endif /* HAL_LPTIM_MODULE_ENABLED */ + +#ifdef HAL_LTDC_MODULE_ENABLED +#include "stm32n6xx_hal_ltdc.h" +#endif /* HAL_LTDC_MODULE_ENABLED */ + +#ifdef HAL_MCE_MODULE_ENABLED +#include "stm32n6xx_hal_mce.h" +#endif /* HAL_MCE_MODULE_ENABLED */ + +#ifdef HAL_MDF_MODULE_ENABLED +#include "stm32n6xx_hal_mdf.h" +#endif /* HAL_MDF_MODULE_ENABLED */ + +#ifdef HAL_MDIOS_MODULE_ENABLED +#include "stm32n6xx_hal_mdios.h" +#endif /* HAL_MDIOS_MODULE_ENABLED */ + +#ifdef HAL_MMC_MODULE_ENABLED +#include "stm32n6xx_hal_mmc.h" +#endif /* HAL_MMC_MODULE_ENABLED */ + +#ifdef HAL_NAND_MODULE_ENABLED +#include "stm32n6xx_hal_nand.h" +#endif /* HAL_NAND_MODULE_ENABLED */ + +#ifdef HAL_NOR_MODULE_ENABLED +#include "stm32n6xx_hal_nor.h" +#endif /* HAL_NOR_MODULE_ENABLED */ + +#ifdef HAL_NAND_MODULE_ENABLED +#include "stm32n6xx_hal_nand.h" +#endif /* HAL_NAND_MODULE_ENABLED */ + +#ifdef HAL_PCD_MODULE_ENABLED +#include "stm32n6xx_hal_pcd.h" +#endif /* HAL_PCD_MODULE_ENABLED */ + +#ifdef HAL_PKA_MODULE_ENABLED +#include "stm32n6xx_hal_pka.h" +#endif /* HAL_PKA_MODULE_ENABLED */ + +#ifdef HAL_PSSI_MODULE_ENABLED +#include "stm32n6xx_hal_pssi.h" +#endif /* HAL_PSSI_MODULE_ENABLED */ + +#ifdef HAL_PWR_MODULE_ENABLED +#include "stm32n6xx_hal_pwr.h" +#endif /* HAL_PWR_MODULE_ENABLED */ + +#ifdef HAL_RAMCFG_MODULE_ENABLED +#include "stm32n6xx_hal_ramcfg.h" +#endif /* HAL_RAMCFG_MODULE_ENABLED */ + +#ifdef HAL_RNG_MODULE_ENABLED +#include "stm32n6xx_hal_rng.h" +#endif /* HAL_RNG_MODULE_ENABLED */ + +#ifdef HAL_RTC_MODULE_ENABLED +#include "stm32n6xx_hal_rtc.h" +#endif /* HAL_RTC_MODULE_ENABLED */ + +#ifdef HAL_SAI_MODULE_ENABLED +#include "stm32n6xx_hal_sai.h" +#endif /* HAL_SAI_MODULE_ENABLED */ + +#ifdef HAL_SD_MODULE_ENABLED +#include "stm32n6xx_hal_sd.h" +#endif /* HAL_SD_MODULE_ENABLED */ + +#ifdef HAL_SDIO_MODULE_ENABLED +#include "stm32n6xx_hal_sdio.h" +#endif /* HAL_SDIO_MODULE_ENABLED */ + +#ifdef HAL_SDRAM_MODULE_ENABLED +#include "stm32n6xx_hal_sdram.h" +#endif /* HAL_SDRAM_MODULE_ENABLED */ + +#ifdef HAL_SMARTCARD_MODULE_ENABLED +#include "stm32n6xx_hal_smartcard.h" +#endif /* HAL_SMARTCARD_MODULE_ENABLED */ + +#ifdef HAL_SMBUS_MODULE_ENABLED +#include "stm32n6xx_hal_smbus.h" +#endif /* HAL_SMBUS_MODULE_ENABLED */ + +#ifdef HAL_SPDIFRX_MODULE_ENABLED +#include "stm32n6xx_hal_spdifrx.h" +#endif /* HAL_SPDIFRX_MODULE_ENABLED */ + +#ifdef HAL_SPI_MODULE_ENABLED +#include "stm32n6xx_hal_spi.h" +#endif /* HAL_SPI_MODULE_ENABLED */ + +#ifdef HAL_SRAM_MODULE_ENABLED +#include "stm32n6xx_hal_sram.h" +#endif /* HAL_SRAM_MODULE_ENABLED */ + +#ifdef HAL_TIM_MODULE_ENABLED +#include "stm32n6xx_hal_tim.h" +#endif /* HAL_TIM_MODULE_ENABLED */ + +#ifdef HAL_UART_MODULE_ENABLED +#include "stm32n6xx_hal_uart.h" +#endif /* HAL_UART_MODULE_ENABLED */ + +#ifdef HAL_USART_MODULE_ENABLED +#include "stm32n6xx_hal_usart.h" +#endif /* HAL_USART_MODULE_ENABLED */ + +#ifdef HAL_WWDG_MODULE_ENABLED +#include "stm32n6xx_hal_wwdg.h" +#endif /* HAL_WWDG_MODULE_ENABLED */ + +#ifdef HAL_XSPI_MODULE_ENABLED +#include "stm32n6xx_hal_xspi.h" +#endif /* HAL_XSPI_MODULE_ENABLED */ + +/* Exported macros -----------------------------------------------------------*/ +#ifdef USE_FULL_ASSERT +/** + * @brief The assert_param macro is used for function's parameters check. + * @param expr: If expr is false, it calls assert_failed function + * which reports the name of the source file and the source + * line number of the call that failed. + * If expr is true, it returns no value. + * @retval None + */ +#define assert_param(expr) ((expr) ? (void)0U : assert_failed((uint8_t *)__FILE__, __LINE__)) +/* Exported functions ------------------------------------------------------- */ +void assert_failed(uint8_t *file, uint32_t line); +#else +#define assert_param(expr) ((void)0U) +#endif /* USE_FULL_ASSERT */ + +#ifdef __cplusplus +} +#endif + +#endif /* STM32N6xx_HAL_CONF_H */ diff --git a/hw/bsp/stm32u5/boards/b_u585i_iot2a/board.h b/hw/bsp/stm32u5/boards/b_u585i_iot2a/board.h index 2f1c451db..cf3f63ea5 100644 --- a/hw/bsp/stm32u5/boards/b_u585i_iot2a/board.h +++ b/hw/bsp/stm32u5/boards/b_u585i_iot2a/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: STM32 B-U585i IOT2A Discovery kit + url: https://www.st.com/en/evaluation-tools/b-u585i-iot02a.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/stm32u5/boards/b_u585i_iot2a/board.mk b/hw/bsp/stm32u5/boards/b_u585i_iot2a/board.mk index ae63afef3..0a2c47030 100644 --- a/hw/bsp/stm32u5/boards/b_u585i_iot2a/board.mk +++ b/hw/bsp/stm32u5/boards/b_u585i_iot2a/board.mk @@ -1,11 +1,9 @@ +MCU_VARIANT = stm32u585xx CFLAGS += \ -DSTM32U585xx \ # All source paths should be relative to the top level. LD_FILE = ${FAMILY_PATH}/linker/STM32U575xx_FLASH.ld -SRC_S += $(ST_CMSIS)/Source/Templates/gcc/startup_stm32u575xx.s - -MCU_VARIANT = stm32u585xx # For flash-jlink target JLINK_DEVICE = stm32u585zi diff --git a/hw/bsp/stm32u5/boards/stm32u545nucleo/board.h b/hw/bsp/stm32u5/boards/stm32u545nucleo/board.h index 7f3bf462c..0c3439b2c 100644 --- a/hw/bsp/stm32u5/boards/stm32u545nucleo/board.h +++ b/hw/bsp/stm32u5/boards/stm32u545nucleo/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: STM32 U545 Nucleo + url: https://www.st.com/en/evaluation-tools/nucleo-u545re-q.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/stm32u5/boards/stm32u545nucleo/board.mk b/hw/bsp/stm32u5/boards/stm32u545nucleo/board.mk index 072c595fb..0aba57ce4 100644 --- a/hw/bsp/stm32u5/boards/stm32u545nucleo/board.mk +++ b/hw/bsp/stm32u5/boards/stm32u545nucleo/board.mk @@ -1,11 +1,9 @@ +MCU_VARIANT = stm32u545xx CFLAGS += \ -DSTM32U545xx \ # All source paths should be relative to the top level. LD_FILE = ${FAMILY_PATH}/linker/STM32U545xx_FLASH.ld -SRC_S += $(ST_CMSIS)/Source/Templates/gcc/startup_stm32u545xx.s - -MCU_VARIANT = stm32u545xx # For flash-jlink target JLINK_DEVICE = stm32u545re diff --git a/hw/bsp/stm32u5/boards/stm32u575eval/board.h b/hw/bsp/stm32u5/boards/stm32u575eval/board.h index bd91502af..b11f6a747 100644 --- a/hw/bsp/stm32u5/boards/stm32u575eval/board.h +++ b/hw/bsp/stm32u5/boards/stm32u575eval/board.h @@ -25,6 +25,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: STM32 U575 Eval + url: https://www.st.com/en/evaluation-tools/stm32u575i-ev.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/stm32u5/boards/stm32u575eval/board.mk b/hw/bsp/stm32u5/boards/stm32u575eval/board.mk index fee56f2ba..4bc9fea10 100644 --- a/hw/bsp/stm32u5/boards/stm32u575eval/board.mk +++ b/hw/bsp/stm32u5/boards/stm32u575eval/board.mk @@ -1,11 +1,9 @@ +MCU_VARIANT = stm32u575xx CFLAGS += \ -DSTM32U575xx \ # All source paths should be relative to the top level. LD_FILE = ${FAMILY_PATH}/linker/STM32U575xx_FLASH.ld -SRC_S += $(ST_CMSIS)/Source/Templates/gcc/startup_stm32u575xx.s - -MCU_VARIANT = stm32u575xx # For flash-jlink target JLINK_DEVICE = stm32u575ai diff --git a/hw/bsp/stm32u5/boards/stm32u575nucleo/board.h b/hw/bsp/stm32u5/boards/stm32u575nucleo/board.h index 6d244d418..be037b68a 100644 --- a/hw/bsp/stm32u5/boards/stm32u575nucleo/board.h +++ b/hw/bsp/stm32u5/boards/stm32u575nucleo/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: STM32 U575 Nucleo + url: https://www.st.com/en/evaluation-tools/nucleo-u575zi-q.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/stm32u5/boards/stm32u575nucleo/board.mk b/hw/bsp/stm32u5/boards/stm32u575nucleo/board.mk index c83ec3999..d09dc5c46 100644 --- a/hw/bsp/stm32u5/boards/stm32u575nucleo/board.mk +++ b/hw/bsp/stm32u5/boards/stm32u575nucleo/board.mk @@ -1,11 +1,9 @@ +MCU_VARIANT = stm32u575xx CFLAGS += \ -DSTM32U575xx \ # All source paths should be relative to the top level. LD_FILE = ${FAMILY_PATH}/linker/STM32U575xx_FLASH.ld -SRC_S += $(ST_CMSIS)/Source/Templates/gcc/startup_stm32u575xx.s - -MCU_VARIANT = stm32u575xx # For flash-jlink target JLINK_DEVICE = stm32u575zi diff --git a/hw/bsp/stm32u5/boards/stm32u5a5nucleo/board.h b/hw/bsp/stm32u5/boards/stm32u5a5nucleo/board.h index 062fb807f..0785fb36b 100644 --- a/hw/bsp/stm32u5/boards/stm32u5a5nucleo/board.h +++ b/hw/bsp/stm32u5/boards/stm32u5a5nucleo/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: STM32 U5a5 Nucleo + url: https://www.st.com/en/evaluation-tools/nucleo-u5a5zj-q.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/stm32u5/boards/stm32u5a5nucleo/board.mk b/hw/bsp/stm32u5/boards/stm32u5a5nucleo/board.mk index 4bebe3330..c9fdbac1a 100644 --- a/hw/bsp/stm32u5/boards/stm32u5a5nucleo/board.mk +++ b/hw/bsp/stm32u5/boards/stm32u5a5nucleo/board.mk @@ -1,3 +1,4 @@ +MCU_VARIANT = stm32u5a5xx CFLAGS += \ -DSTM32U5A5xx \ -DHSE_VALUE=16000000UL \ @@ -5,8 +6,5 @@ CFLAGS += \ # All source paths should be relative to the top level. LD_FILE = ${BOARD_PATH}/STM32U5A5ZJTXQ_FLASH.ld -SRC_S += $(ST_CMSIS)/Source/Templates/gcc/startup_stm32u5a5xx.s - -MCU_VARIANT = stm32u5a5xx # For flash-jlink target JLINK_DEVICE = stm32u575zi diff --git a/hw/bsp/stm32u5/family.c b/hw/bsp/stm32u5/family.c index 3cc7cc511..032c01f34 100644 --- a/hw/bsp/stm32u5/family.c +++ b/hw/bsp/stm32u5/family.c @@ -25,6 +25,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: STMicroelectronics +*/ + // Suppress warning caused by mcu driver #ifdef __GNUC__ #pragma GCC diagnostic push diff --git a/hw/bsp/stm32u5/family.cmake b/hw/bsp/stm32u5/family.cmake index 3ab7cdf8b..7a5935961 100644 --- a/hw/bsp/stm32u5/family.cmake +++ b/hw/bsp/stm32u5/family.cmake @@ -11,7 +11,7 @@ set(CMSIS_5 ${TOP}/lib/CMSIS_5) include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) # toolchain set up -set(CMAKE_SYSTEM_PROCESSOR cortex-m33 CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU cortex-m33 CACHE INTERNAL "System Processor") set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) set(FAMILY_MCUS STM32U5 CACHE INTERNAL "") @@ -101,20 +101,20 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_STM32U5 ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC + family_add_tinyusb(${TARGET} OPT_MCU_STM32U5) + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c ${TOP}/src/portable/synopsys/dwc2/dcd_dwc2.c ${TOP}/src/portable/synopsys/dwc2/hcd_dwc2.c ${TOP}/src/portable/synopsys/dwc2/dwc2_common.c #${TOP}/src/portable/st/typec/typec_stm32.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) # Flashing + family_add_bin_hex(${TARGET}) family_flash_stlink(${TARGET}) family_flash_jlink(${TARGET}) endfunction() diff --git a/hw/bsp/stm32u5/family.mk b/hw/bsp/stm32u5/family.mk index 05fe4608a..3694b1ca0 100644 --- a/hw/bsp/stm32u5/family.mk +++ b/hw/bsp/stm32u5/family.mk @@ -1,5 +1,4 @@ ST_FAMILY = u5 -DEPS_SUBMODULES += lib/CMSIS_5 hw/mcu/st/cmsis_device_$(ST_FAMILY) hw/mcu/st/stm32$(ST_FAMILY)xx_hal_driver ST_CMSIS = hw/mcu/st/cmsis_device_$(ST_FAMILY) ST_HAL_DRIVER = hw/mcu/st/stm32$(ST_FAMILY)xx_hal_driver @@ -57,5 +56,12 @@ INC += \ $(TOP)/$(ST_HAL_DRIVER)/Inc \ $(TOP)/$(BOARD_PATH) +# Startup +SRC_S_GCC += $(ST_CMSIS)/Source/Templates/gcc/startup_$(MCU_VARIANT).s +SRC_S_IAR += $(ST_CMSIS)/Source/Templates/iar/startup_$(MCU_VARIANT).s + +# Linker +LD_FILE_IAR ?= $(ST_CMSIS)/Source/Templates/iar/linker/$(MCU_VARIANT)_flash.icf + # flash target using on-board stlink flash: flash-stlink diff --git a/hw/bsp/stm32wb/boards/stm32wb55nucleo/board.h b/hw/bsp/stm32wb/boards/stm32wb55nucleo/board.h index ea975df03..704592506 100644 --- a/hw/bsp/stm32wb/boards/stm32wb55nucleo/board.h +++ b/hw/bsp/stm32wb/boards/stm32wb55nucleo/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: STM32 P-NUCLEO-WB55 + url: https://www.st.com/en/evaluation-tools/p-nucleo-wb55.html +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/stm32wb/boards/stm32wb55nucleo/stm32wb55xx_flash_cm4.ld b/hw/bsp/stm32wb/boards/stm32wb55nucleo/stm32wb55xx_flash_cm4.ld index 916f11866..c16235586 100644 --- a/hw/bsp/stm32wb/boards/stm32wb55nucleo/stm32wb55xx_flash_cm4.ld +++ b/hw/bsp/stm32wb/boards/stm32wb55nucleo/stm32wb55xx_flash_cm4.ld @@ -3,21 +3,26 @@ ** ** File : stm32wb55xx_flash_cm4.ld ** -** Abstract : System Workbench Minimal System calls file +** Author : STM32CubeIDE ** -** For more information about which c-functions -** need which of these lowlevel functions -** please consult the Newlib libc-manual +** Abstract : Linker script for STM32WB55xx Device +** 1024Kbytes FLASH +** 128Kbytes RAM ** -** Environment : System Workbench for MCU +** Set heap size, stack size and stack location according +** to application requirements. ** -** Distribution: The file is distributed “as is,” without any warranty +** Set memory bank area and size if external memory is used. +** +** Target : STMicroelectronics STM32 +** +** Distribution: The file is distributed as is without any warranty ** of any kind. ** ***************************************************************************** ** @attention ** -** Copyright (c) 2019 STMicroelectronics. +** Copyright (c) 2019-2022 STMicroelectronics. ** All rights reserved. ** ** This software is licensed under terms that can be found in the LICENSE file @@ -33,7 +38,7 @@ ENTRY(Reset_Handler) /* Highest address of the user mode stack */ _estack = 0x20030000; /* end of RAM */ /* Generate a link error if heap and stack don't fit into RAM */ -_Min_Heap_Size = 0x400; /* required amount of heap */ +_Min_Heap_Size = 0x400; /* required amount of heap */ _Min_Stack_Size = 0x1000; /* required amount of stack */ /* Specify the memory areas */ @@ -81,14 +86,17 @@ SECTIONS . = ALIGN(4); } >FLASH - .ARM.extab : { *(.ARM.extab* .gnu.linkonce.armextab.*) } >FLASH + .ARM.extab : + { + *(.ARM.extab* .gnu.linkonce.armextab.*) + } >FLASH .ARM : { __exidx_start = .; *(.ARM.exidx*) __exidx_end = .; } >FLASH - .preinit_array : + .preinit_array : { PROVIDE_HIDDEN (__preinit_array_start = .); KEEP (*(.preinit_array*)) @@ -124,7 +132,6 @@ SECTIONS _edata = .; /* define a global symbol at data end */ } >RAM1 AT> FLASH - /* Uninitialized data section */ . = ALIGN(4); .bss : @@ -152,8 +159,6 @@ SECTIONS . = ALIGN(8); } >RAM1 - - /* Remove information from the standard libraries */ /DISCARD/ : { @@ -163,7 +168,15 @@ SECTIONS } .ARM.attributes 0 : { *(.ARM.attributes) } - MAPPING_TABLE (NOLOAD) : { *(MAPPING_TABLE) } >RAM_SHARED - MB_MEM1 (NOLOAD) : { *(MB_MEM1) } >RAM_SHARED - MB_MEM2 (NOLOAD) : { _sMB_MEM2 = . ; *(MB_MEM2) ; _eMB_MEM2 = . ; } >RAM_SHARED + MAPPING_TABLE (NOLOAD) : { *(MAPPING_TABLE) } >RAM_SHARED + MB_MEM1 (NOLOAD) : { *(MB_MEM1) } >RAM_SHARED + + /* used by the startup to initialize .MB_MEM2 data */ + _siMB_MEM2 = LOADADDR(.MB_MEM2); + .MB_MEM2 : + { + _sMB_MEM2 = . ; + *(MB_MEM2) ; + _eMB_MEM2 = . ; + } >RAM_SHARED AT> FLASH } diff --git a/hw/bsp/stm32wb/family.c b/hw/bsp/stm32wb/family.c index 6051388a7..93aba02fa 100644 --- a/hw/bsp/stm32wb/family.c +++ b/hw/bsp/stm32wb/family.c @@ -24,6 +24,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: STMicroelectronics +*/ + #include "stm32wbxx_hal.h" #include "bsp/board_api.h" #include "board.h" @@ -42,7 +46,9 @@ void USB_LP_IRQHandler(void) { //--------------------------------------------------------------------+ // MACRO TYPEDEF CONSTANT ENUM //--------------------------------------------------------------------+ +#ifdef UART_DEV UART_HandleTypeDef UartHandle; +#endif void board_init(void) { board_clock_init(); @@ -54,8 +60,6 @@ void board_init(void) { __HAL_RCC_GPIOD_CLK_ENABLE(); __HAL_RCC_GPIOE_CLK_ENABLE(); - UART_CLK_EN(); - #if CFG_TUSB_OS == OPT_OS_NONE // 1ms tick timer SysTick_Config(SystemCoreClock / 1000); @@ -98,6 +102,8 @@ void board_init(void) { HAL_GPIO_Init(BUTTON_PORT, &GPIO_InitStruct); #ifdef UART_DEV + UART_CLK_EN(); + // UART GPIO_InitStruct.Pin = UART_TX_PIN | UART_RX_PIN; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; @@ -155,7 +161,7 @@ int board_uart_write(void const* buf, int len) { HAL_UART_Transmit(&UartHandle, (uint8_t*) (uintptr_t) buf, len, 0xffff); return len; #else - (void) buf; (void) len; (void) UartHandle; + (void) buf; (void) len; return 0; #endif } @@ -178,8 +184,7 @@ void HardFault_Handler(void) { asm("bkpt 1"); } -// Required by __libc_init_array in startup code if we are compiling using -// -nostdlib/-nostartfiles. +// Required by __libc_init_array in startup code if we are compiling using -nostdlib/-nostartfiles. +void _init(void); void _init(void) { - } diff --git a/hw/bsp/stm32wb/family.cmake b/hw/bsp/stm32wb/family.cmake index 071797c20..0ea937257 100644 --- a/hw/bsp/stm32wb/family.cmake +++ b/hw/bsp/stm32wb/family.cmake @@ -11,7 +11,7 @@ set(CMSIS_5 ${TOP}/lib/CMSIS_5) include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) # toolchain set up -set(CMAKE_SYSTEM_PROCESSOR cortex-m4 CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU cortex-m4 CACHE INTERNAL "System Processor") set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) set(FAMILY_MCUS STM32WB CACHE INTERNAL "") @@ -104,16 +104,16 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_${FAMILY_MCUS} ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC + family_add_tinyusb(${TARGET} OPT_MCU_${FAMILY_MCUS}) + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) # Flashing + family_add_bin_hex(${TARGET}) family_flash_stlink(${TARGET}) family_flash_jlink(${TARGET}) endfunction() diff --git a/hw/bsp/stm32wb/family.mk b/hw/bsp/stm32wb/family.mk index de8372eea..a80ff6f5b 100644 --- a/hw/bsp/stm32wb/family.mk +++ b/hw/bsp/stm32wb/family.mk @@ -9,14 +9,12 @@ include $(TOP)/$(BOARD_PATH)/board.mk CPU_CORE ?= cortex-m4 CFLAGS += \ - -flto \ - -nostdlib -nostartfiles \ -DCFG_TUSB_MCU=OPT_MCU_STM32WB -# suppress warning caused by vendor mcu driver -CFLAGS += -Wno-error=cast-align -Wno-unused-parameter - -LD_FILE ?= ${ST_CMSIS}/Source/Templates/gcc/linker/${MCU_VARIANT}_flash_cm4.ld +CFLAGS_GCC += \ + -flto \ + -nostdlib -nostartfiles \ + -Wno-error=cast-align -Wno-unused-parameter LDFLAGS_GCC += -specs=nosys.specs -specs=nano.specs @@ -25,19 +23,26 @@ SRC_C += \ $(ST_CMSIS)/Source/Templates/system_${ST_PREFIX}.c \ $(ST_HAL_DRIVER)/Src/${ST_PREFIX}_hal.c \ $(ST_HAL_DRIVER)/Src/${ST_PREFIX}_hal_cortex.c \ + $(ST_HAL_DRIVER)/Src/${ST_PREFIX}_hal_pwr.c \ $(ST_HAL_DRIVER)/Src/${ST_PREFIX}_hal_pwr_ex.c \ $(ST_HAL_DRIVER)/Src/${ST_PREFIX}_hal_rcc.c \ $(ST_HAL_DRIVER)/Src/${ST_PREFIX}_hal_rcc_ex.c \ $(ST_HAL_DRIVER)/Src/${ST_PREFIX}_hal_uart.c \ $(ST_HAL_DRIVER)/Src/${ST_PREFIX}_hal_gpio.c -SRC_S += $(ST_CMSIS)/Source/Templates/gcc/startup_${MCU_VARIANT}_cm4.s - INC += \ $(TOP)/$(BOARD_PATH) \ $(TOP)/lib/CMSIS_5/CMSIS/Core/Include \ $(TOP)/$(ST_CMSIS)/Include \ $(TOP)/$(ST_HAL_DRIVER)/Inc +# Startup +SRC_S_GCC += $(ST_CMSIS)/Source/Templates/gcc/startup_$(MCU_VARIANT)_cm4.s +SRC_S_IAR += $(ST_CMSIS)/Source/Templates/iar/startup_$(MCU_VARIANT)_cm4.s + +# Linker +LD_FILE_GCC ?= ${ST_CMSIS}/Source/Templates/gcc/linker/${MCU_VARIANT}_flash_cm4.ld +LD_FILE_IAR ?= $(ST_CMSIS)/Source/Templates/iar/linker/$(MCU_VARIANT)_flash_cm4.icf + # flash target using on-board stlink flash: flash-stlink diff --git a/hw/bsp/tm4c/boards/ek_tm4c123gxl/board.h b/hw/bsp/tm4c/boards/ek_tm4c123gxl/board.h index 5732056ae..c0ceb4cd8 100644 --- a/hw/bsp/tm4c/boards/ek_tm4c123gxl/board.h +++ b/hw/bsp/tm4c/boards/ek_tm4c123gxl/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: TM4C123G LaunchPad + url: https://www.ti.com/tool/EK-TM4C123GXL +*/ + #ifndef _BOARD_H_ #define _BOARD_H_ diff --git a/hw/bsp/tm4c/family.c b/hw/bsp/tm4c/family.c index 5e1f6d3ff..4e5491005 100644 --- a/hw/bsp/tm4c/family.c +++ b/hw/bsp/tm4c/family.c @@ -1,3 +1,7 @@ +/* metadata: + manufacturer: Texas Instruments +*/ + #include "TM4C123.h" #include "bsp/board_api.h" #include "board.h" diff --git a/hw/bsp/tm4c/family.cmake b/hw/bsp/tm4c/family.cmake index 9c083759b..e1cf94e96 100644 --- a/hw/bsp/tm4c/family.cmake +++ b/hw/bsp/tm4c/family.cmake @@ -9,7 +9,7 @@ set(SDK_DIR ${TOP}/hw/mcu/ti/${MCU_VARIANT}xx) set(CMSIS_DIR ${TOP}/lib/CMSIS_5) # toolchain set up -set(CMAKE_SYSTEM_PROCESSOR cortex-m4 CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU cortex-m4 CACHE INTERNAL "System Processor") set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) set(FAMILY_MCUS TM4C123 CACHE INTERNAL "") @@ -79,15 +79,14 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_TM4C123 ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC + family_add_tinyusb(${TARGET} OPT_MCU_TM4C123) + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/mentor/musb/dcd_musb.c ${TOP}/src/portable/mentor/musb/hcd_musb.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) # Flashing family_add_bin_hex(${TARGET}) diff --git a/hw/bsp/xmc4000/boards/xmc4500_relax/board.h b/hw/bsp/xmc4000/boards/xmc4500_relax/board.h index 2d4764f40..3d0e92b2c 100644 --- a/hw/bsp/xmc4000/boards/xmc4500_relax/board.h +++ b/hw/bsp/xmc4000/boards/xmc4500_relax/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: XMC4500 relax kit + url: https://www.infineon.com/cms/en/product/evaluation-boards/kit_xmc45_relax_v1/ +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/xmc4000/boards/xmc4700_relax/board.h b/hw/bsp/xmc4000/boards/xmc4700_relax/board.h index aa12fde3b..f3972980c 100644 --- a/hw/bsp/xmc4000/boards/xmc4700_relax/board.h +++ b/hw/bsp/xmc4000/boards/xmc4700_relax/board.h @@ -24,6 +24,11 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + name: XMC4700 relax kit + url: https://www.infineon.com/cms/en/product/evaluation-boards/kit_xmc47_relax_v1/ +*/ + #ifndef BOARD_H_ #define BOARD_H_ diff --git a/hw/bsp/xmc4000/family.c b/hw/bsp/xmc4000/family.c index c776cb58a..1acce024b 100644 --- a/hw/bsp/xmc4000/family.c +++ b/hw/bsp/xmc4000/family.c @@ -24,6 +24,10 @@ * This file is part of the TinyUSB stack. */ +/* metadata: + manufacturer: Infineon +*/ + #include "xmc_gpio.h" #include "xmc_scu.h" #include "xmc_uart.h" diff --git a/hw/bsp/xmc4000/family.cmake b/hw/bsp/xmc4000/family.cmake index 85444db28..6edd72caf 100644 --- a/hw/bsp/xmc4000/family.cmake +++ b/hw/bsp/xmc4000/family.cmake @@ -6,7 +6,7 @@ set(CMSIS_DIR ${TOP}/lib/CMSIS_5) include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) # toolchain set up -set(CMAKE_SYSTEM_PROCESSOR cortex-m4 CACHE INTERNAL "System Processor") +set(CMAKE_SYSTEM_CPU cortex-m4 CACHE INTERNAL "System Processor") set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake) set(FAMILY_MCUS XMC4000 CACHE INTERNAL "") @@ -83,17 +83,17 @@ function(family_configure_example TARGET RTOS) ) # Add TinyUSB target and port source - family_add_tinyusb(${TARGET} OPT_MCU_XMC4000 ${RTOS}) - target_sources(${TARGET}-tinyusb PUBLIC + family_add_tinyusb(${TARGET} OPT_MCU_XMC4000) + target_sources(${TARGET} PUBLIC ${TOP}/src/portable/synopsys/dwc2/dcd_dwc2.c ${TOP}/src/portable/synopsys/dwc2/hcd_dwc2.c ${TOP}/src/portable/synopsys/dwc2/dwc2_common.c ) - target_link_libraries(${TARGET}-tinyusb PUBLIC board_${BOARD}) + target_link_libraries(${TARGET} PUBLIC board_${BOARD}) + - # Link dependencies - target_link_libraries(${TARGET} PUBLIC board_${BOARD} ${TARGET}-tinyusb) # Flashing + family_add_bin_hex(${TARGET}) family_flash_jlink(${TARGET}) endfunction() diff --git a/hw/bsp/xmc4000/family.mk b/hw/bsp/xmc4000/family.mk index a1679a2f0..4eed7360a 100644 --- a/hw/bsp/xmc4000/family.mk +++ b/hw/bsp/xmc4000/family.mk @@ -1,8 +1,6 @@ UF2_FAMILY_ID = 0x00 SDK_DIR = hw/mcu/infineon/mtb-xmclib-cat3 -DEPS_SUBMODULES += ${SDK_DIR} - include $(TOP)/$(BOARD_PATH)/board.mk CPU_CORE ?= cortex-m4 diff --git a/hw/bsp/zephyr_board_aliases.cmake b/hw/bsp/zephyr_board_aliases.cmake new file mode 100644 index 000000000..b60e97ef4 --- /dev/null +++ b/hw/bsp/zephyr_board_aliases.cmake @@ -0,0 +1,2 @@ +set(pca10056_BOARD_ALIAS nrf52840dk/nrf52840) +set(stm32n657nucleo_BOARD_ALIAS nucleo_n657x0_q) diff --git a/library.json b/library.json index c945d4b52..f1bfd6387 100644 --- a/library.json +++ b/library.json @@ -1,6 +1,6 @@ { "name": "TinyUSB", - "version": "0.17.0", + "version": "0.18.0", "description": "TinyUSB is an open-source cross-platform USB Host/Device stack for embedded system, designed to be memory-safe with no dynamic allocation and thread-safe with all interrupt events are deferred then handled in the non-ISR task function.", "keywords": "usb, host, device", "repository": diff --git a/pkg.yml b/pkg.yml index 331445024..841307847 100644 --- a/pkg.yml +++ b/pkg.yml @@ -1,5 +1,5 @@ pkg.name: tinyusb -pkg.description: A silly USB stack for embedded +pkg.description: An open source cross-platform USB stack for embedded system pkg.author: "Ha Thach " pkg.homepage: "https://github.com/hathach/tinyusb" pkg.keywords: diff --git a/repository.yml b/repository.yml index df7895e84..31c9eddc5 100644 --- a/repository.yml +++ b/repository.yml @@ -15,5 +15,6 @@ repo.versions: "0.15.0": "0.15.0" "0.16.0": "0.16.0" "0.17.0": "0.17.0" - "0-latest": "0.17.0" + "0.18.0": "0.18.0" + "0-latest": "0.18.0" "0-dev": "0.0.0" diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index cf6878389..99d3059fc 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -1,11 +1,7 @@ -# TODO more docs and example on how to use this file -# Usage: requires target tinyusb_config which expose tusb_config.h file -# TINYUSB_TARGET_PREFIX and TINYUSB_TARGET_SUFFIX can be used to change the name of the target +cmake_minimum_required(VERSION 3.20) -cmake_minimum_required(VERSION 3.17) - -# Add tinyusb to a target, if user don't want to compile tinyusb as a library -function(add_tinyusb TARGET) +# Add tinyusb to a existing target, DCD and HCD drivers are not included +function(tinyusb_target_add TARGET) target_sources(${TARGET} PRIVATE # common ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/tusb.c @@ -30,6 +26,7 @@ function(add_tinyusb TARGET) ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/host/hub.c ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/class/cdc/cdc_host.c ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/class/hid/hid_host.c + ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/class/midi/midi_host.c ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/class/msc/msc_host.c ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/class/vendor/vendor_host.c # typec @@ -40,68 +37,4 @@ function(add_tinyusb TARGET) # TODO for net driver, should be removed/changed ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/../lib/networking ) - - if (CMAKE_C_COMPILER_ID STREQUAL "GNU" OR CMAKE_C_COMPILER_ID STREQUAL "Clang") - target_compile_options(${TARGET} PRIVATE - -Wall - -Wextra - -Werror - -Wfatal-errors - -Wdouble-promotion - -Wstrict-prototypes - -Wstrict-overflow - -Werror-implicit-function-declaration - -Wfloat-equal - -Wundef - -Wshadow - -Wwrite-strings - -Wsign-compare - -Wmissing-format-attribute - -Wunreachable-code - -Wcast-align - -Wcast-function-type - -Wcast-qual - -Wnull-dereference - -Wuninitialized - -Wunused - -Wunused-function - -Wreturn-type - -Wredundant-decls - -Wmissing-prototypes - ) - elseif (CMAKE_C_COMPILER_ID STREQUAL "IAR") - - endif () endfunction() - -#------------------------------------ -# TinyUSB as library target -#------------------------------------ -if (NOT DEFINED TINYUSB_TARGET) - set(TINYUSB_TARGET "tinyusb") -endif () - -set(TINYUSB_CONFIG_TARGET "${TINYUSB_TARGET}_config") - -if (DEFINED TINYUSB_TARGET_PREFIX) - set(TINYUSB_TARGET "${TINYUSB_TARGET_PREFIX}${TINYUSB_TARGET}") - set(TINYUSB_CONFIG_TARGET "${TINYUSB_TARGET_PREFIX}${TINYUSB_CONFIG_TARGET}") -endif () - -if (DEFINED TINYUSB_TARGET_SUFFIX) - set(TINYUSB_TARGET "${TINYUSB_TARGET}${TINYUSB_TARGET_SUFFIX}") - set(TINYUSB_CONFIG_TARGET "${TINYUSB_CONFIG_TARGET}${TINYUSB_TARGET_SUFFIX}") -endif () - -add_library(${TINYUSB_TARGET} STATIC) -add_tinyusb(${TINYUSB_TARGET}) - -# Check if tinyusb_config target is defined -if (NOT TARGET ${TINYUSB_CONFIG_TARGET}) - message(FATAL_ERROR "${TINYUSB_CONFIG_TARGET} target is not defined") -endif() - -# Link with tinyusb_config target -target_link_libraries(${TINYUSB_TARGET} PUBLIC - ${TINYUSB_CONFIG_TARGET} - ) diff --git a/src/class/audio/audio.h b/src/class/audio/audio.h index 2f97c0f23..0d1acadcc 100644 --- a/src/class/audio/audio.h +++ b/src/class/audio/audio.h @@ -661,6 +661,7 @@ typedef struct TU_ATTR_PACKED uint16_t wTotalLength ; ///< Total number of bytes returned for the class-specific AudioControl interface descriptor. Includes the combined length of this descriptor header and all Clock Source, Unit and Terminal descriptors. uint8_t bmControls ; ///< See: audio_cs_ac_interface_control_pos_t. } audio_desc_cs_ac_interface_t; +TU_VERIFY_STATIC(sizeof(audio_desc_cs_ac_interface_t) == 9, "size is not correct"); /// AUDIO Clock Source Descriptor (4.7.2.1) typedef struct TU_ATTR_PACKED diff --git a/src/class/audio/audio_device.c b/src/class/audio/audio_device.c index cd4183cc3..a877dc900 100644 --- a/src/class/audio/audio_device.c +++ b/src/class/audio/audio_device.c @@ -81,135 +81,140 @@ // Only STM32 and dcd_transdimension use non-linear buffer for now // dwc2 except esp32sx (since it may use dcd_esp32sx) +// Ring buffer is incompatible with dcache, since neither address nor size is aligned to cache line #if (defined(TUP_USBIP_DWC2) && !TU_CHECK_MCU(OPT_MCU_ESP32S2, OPT_MCU_ESP32S3)) || \ - defined(TUP_USBIP_FSDEV) || \ - CFG_TUSB_MCU == OPT_MCU_RX63X || \ - CFG_TUSB_MCU == OPT_MCU_RX65X || \ - CFG_TUSB_MCU == OPT_MCU_RX72N || \ - CFG_TUSB_MCU == OPT_MCU_LPC18XX || \ - CFG_TUSB_MCU == OPT_MCU_LPC43XX || \ - CFG_TUSB_MCU == OPT_MCU_MIMXRT1XXX || \ + defined(TUP_USBIP_FSDEV) || \ + CFG_TUSB_MCU == OPT_MCU_RX63X || \ + CFG_TUSB_MCU == OPT_MCU_RX65X || \ + CFG_TUSB_MCU == OPT_MCU_RX72N || \ + CFG_TUSB_MCU == OPT_MCU_LPC18XX || \ + CFG_TUSB_MCU == OPT_MCU_LPC43XX || \ + CFG_TUSB_MCU == OPT_MCU_MIMXRT1XXX || \ CFG_TUSB_MCU == OPT_MCU_MSP432E4 - #if TUD_AUDIO_PREFER_RING_BUFFER - #define USE_LINEAR_BUFFER 0 + #if TUD_AUDIO_PREFER_RING_BUFFER && !CFG_TUD_MEM_DCACHE_ENABLE + #define USE_LINEAR_BUFFER 0 #else - #define USE_LINEAR_BUFFER 1 + #define USE_LINEAR_BUFFER 1 #endif #else - #define USE_LINEAR_BUFFER 1 + #define USE_LINEAR_BUFFER 1 #endif // Declaration of buffers // Check for maximum supported numbers #if CFG_TUD_AUDIO > 3 -#error Maximum number of audio functions restricted to three! + #error Maximum number of audio functions restricted to three! #endif -// Put sw_buf in USB section only if necessary -#if USE_LINEAR_BUFFER || CFG_TUD_AUDIO_ENABLE_ENCODING -#define IN_SW_BUF_MEM_SECTION +// Put swap buffer in USB section only if necessary +#if USE_LINEAR_BUFFER + #define IN_SW_BUF_MEM_ATTR TU_ATTR_ALIGNED(4) #else -#define IN_SW_BUF_MEM_SECTION CFG_TUD_MEM_SECTION + #define IN_SW_BUF_MEM_ATTR CFG_TUD_MEM_SECTION CFG_TUD_MEM_ALIGN #endif -#if USE_LINEAR_BUFFER || CFG_TUD_AUDIO_ENABLE_DECODING -#define OUT_SW_BUF_MEM_SECTION +#if USE_LINEAR_BUFFER + #define OUT_SW_BUF_MEM_ATTR TU_ATTR_ALIGNED(4) #else -#define OUT_SW_BUF_MEM_SECTION CFG_TUD_MEM_SECTION + #define OUT_SW_BUF_MEM_ATTR CFG_TUD_MEM_SECTION CFG_TUD_MEM_ALIGN #endif // EP IN software buffers and mutexes -#if CFG_TUD_AUDIO_ENABLE_EP_IN && !CFG_TUD_AUDIO_ENABLE_ENCODING +#if CFG_TUD_AUDIO_ENABLE_EP_IN +tu_static IN_SW_BUF_MEM_ATTR struct { #if CFG_TUD_AUDIO_FUNC_1_EP_IN_SW_BUF_SZ > 0 - tu_static IN_SW_BUF_MEM_SECTION CFG_TUSB_MEM_ALIGN uint8_t audio_ep_in_sw_buf_1[CFG_TUD_AUDIO_FUNC_1_EP_IN_SW_BUF_SZ]; - #if CFG_FIFO_MUTEX - tu_static osal_mutex_def_t ep_in_ff_mutex_wr_1; // No need for read mutex as only USB driver reads from FIFO - #endif - #endif // CFG_TUD_AUDIO_FUNC_1_EP_IN_SW_BUF_SZ > 0 - + TUD_EPBUF_DEF(buf_1, CFG_TUD_AUDIO_FUNC_1_EP_IN_SW_BUF_SZ); + #endif #if CFG_TUD_AUDIO > 1 && CFG_TUD_AUDIO_FUNC_2_EP_IN_SW_BUF_SZ > 0 - tu_static IN_SW_BUF_MEM_SECTION CFG_TUSB_MEM_ALIGN uint8_t audio_ep_in_sw_buf_2[CFG_TUD_AUDIO_FUNC_2_EP_IN_SW_BUF_SZ]; - #if CFG_FIFO_MUTEX - tu_static osal_mutex_def_t ep_in_ff_mutex_wr_2; // No need for read mutex as only USB driver reads from FIFO - #endif - #endif // CFG_TUD_AUDIO > 1 && CFG_TUD_AUDIO_FUNC_2_EP_IN_SW_BUF_SZ > 0 - + TUD_EPBUF_DEF(buf_2, CFG_TUD_AUDIO_FUNC_2_EP_IN_SW_BUF_SZ); + #endif #if CFG_TUD_AUDIO > 2 && CFG_TUD_AUDIO_FUNC_3_EP_IN_SW_BUF_SZ > 0 - tu_static IN_SW_BUF_MEM_SECTION CFG_TUSB_MEM_ALIGN uint8_t audio_ep_in_sw_buf_3[CFG_TUD_AUDIO_FUNC_3_EP_IN_SW_BUF_SZ]; - #if CFG_FIFO_MUTEX - tu_static osal_mutex_def_t ep_in_ff_mutex_wr_3; // No need for read mutex as only USB driver reads from FIFO + TUD_EPBUF_DEF(buf_3, CFG_TUD_AUDIO_FUNC_3_EP_IN_SW_BUF_SZ); + #endif +} ep_in_sw_buf; + + #if CFG_FIFO_MUTEX + #if CFG_TUD_AUDIO_FUNC_1_EP_IN_SW_BUF_SZ > 0 + tu_static osal_mutex_def_t ep_in_ff_mutex_wr_1; #endif - #endif // CFG_TUD_AUDIO > 2 && CFG_TUD_AUDIO_FUNC_3_EP_IN_SW_BUF_SZ > 0 -#endif // CFG_TUD_AUDIO_ENABLE_EP_IN && !CFG_TUD_AUDIO_ENABLE_ENCODING + #if CFG_TUD_AUDIO > 1 && CFG_TUD_AUDIO_FUNC_2_EP_IN_SW_BUF_SZ > 0 + tu_static osal_mutex_def_t ep_in_ff_mutex_wr_2; + #endif + #if CFG_TUD_AUDIO > 2 && CFG_TUD_AUDIO_FUNC_3_EP_IN_SW_BUF_SZ > 0 + tu_static osal_mutex_def_t ep_in_ff_mutex_wr_3; + #endif + #endif +#endif// CFG_TUD_AUDIO_ENABLE_EP_IN // Linear buffer TX in case: // - target MCU is not capable of handling a ring buffer FIFO e.g. no hardware buffer is available or driver is would need to be changed dramatically OR -// - the software encoding is used - in this case the linear buffers serve as a target memory where logical channels are encoded into -#if CFG_TUD_AUDIO_ENABLE_EP_IN && (USE_LINEAR_BUFFER || CFG_TUD_AUDIO_ENABLE_ENCODING) +#if CFG_TUD_AUDIO_ENABLE_EP_IN && USE_LINEAR_BUFFER +tu_static CFG_TUD_MEM_SECTION struct { #if CFG_TUD_AUDIO_FUNC_1_EP_IN_SZ_MAX > 0 - tu_static CFG_TUD_MEM_SECTION CFG_TUSB_MEM_ALIGN uint8_t lin_buf_in_1[CFG_TUD_AUDIO_FUNC_1_EP_IN_SZ_MAX]; + TUD_EPBUF_DEF(buf_1, CFG_TUD_AUDIO_FUNC_1_EP_IN_SZ_MAX); #endif - #if CFG_TUD_AUDIO > 1 && CFG_TUD_AUDIO_FUNC_2_EP_IN_SZ_MAX > 0 - tu_static CFG_TUD_MEM_SECTION CFG_TUSB_MEM_ALIGN uint8_t lin_buf_in_2[CFG_TUD_AUDIO_FUNC_2_EP_IN_SZ_MAX]; + TUD_EPBUF_DEF(buf_2, CFG_TUD_AUDIO_FUNC_2_EP_IN_SZ_MAX); #endif - #if CFG_TUD_AUDIO > 2 && CFG_TUD_AUDIO_FUNC_3_EP_IN_SZ_MAX > 0 - tu_static CFG_TUD_MEM_SECTION CFG_TUSB_MEM_ALIGN uint8_t lin_buf_in_3[CFG_TUD_AUDIO_FUNC_3_EP_IN_SZ_MAX]; + TUD_EPBUF_DEF(buf_3, CFG_TUD_AUDIO_FUNC_3_EP_IN_SZ_MAX); #endif -#endif // CFG_TUD_AUDIO_ENABLE_EP_IN && (USE_LINEAR_BUFFER || CFG_TUD_AUDIO_ENABLE_DECODING) +} lin_buf_in; +#endif// CFG_TUD_AUDIO_ENABLE_EP_IN && USE_LINEAR_BUFFER // EP OUT software buffers and mutexes -#if CFG_TUD_AUDIO_ENABLE_EP_OUT && !CFG_TUD_AUDIO_ENABLE_DECODING +#if CFG_TUD_AUDIO_ENABLE_EP_OUT +tu_static OUT_SW_BUF_MEM_ATTR struct { #if CFG_TUD_AUDIO_FUNC_1_EP_OUT_SW_BUF_SZ > 0 - tu_static OUT_SW_BUF_MEM_SECTION CFG_TUSB_MEM_ALIGN uint8_t audio_ep_out_sw_buf_1[CFG_TUD_AUDIO_FUNC_1_EP_OUT_SW_BUF_SZ]; - #if CFG_FIFO_MUTEX - tu_static osal_mutex_def_t ep_out_ff_mutex_rd_1; // No need for write mutex as only USB driver writes into FIFO - #endif - #endif // CFG_TUD_AUDIO_FUNC_1_EP_OUT_SW_BUF_SZ > 0 - + TUD_EPBUF_DEF(buf_1, CFG_TUD_AUDIO_FUNC_1_EP_OUT_SW_BUF_SZ); + #endif #if CFG_TUD_AUDIO > 1 && CFG_TUD_AUDIO_FUNC_2_EP_OUT_SW_BUF_SZ > 0 - tu_static OUT_SW_BUF_MEM_SECTION CFG_TUSB_MEM_ALIGN uint8_t audio_ep_out_sw_buf_2[CFG_TUD_AUDIO_FUNC_2_EP_OUT_SW_BUF_SZ]; - #if CFG_FIFO_MUTEX - tu_static osal_mutex_def_t ep_out_ff_mutex_rd_2; // No need for write mutex as only USB driver writes into FIFO - #endif - #endif // CFG_TUD_AUDIO > 1 && CFG_TUD_AUDIO_FUNC_2_EP_OUT_SW_BUF_SZ > 0 - + TUD_EPBUF_DEF(buf_2, CFG_TUD_AUDIO_FUNC_2_EP_OUT_SW_BUF_SZ); + #endif #if CFG_TUD_AUDIO > 2 && CFG_TUD_AUDIO_FUNC_3_EP_OUT_SW_BUF_SZ > 0 - tu_static OUT_SW_BUF_MEM_SECTION CFG_TUSB_MEM_ALIGN uint8_t audio_ep_out_sw_buf_3[CFG_TUD_AUDIO_FUNC_3_EP_OUT_SW_BUF_SZ]; - #if CFG_FIFO_MUTEX - tu_static osal_mutex_def_t ep_out_ff_mutex_rd_3; // No need for write mutex as only USB driver writes into FIFO + TUD_EPBUF_DEF(buf_3, CFG_TUD_AUDIO_FUNC_3_EP_OUT_SW_BUF_SZ); + #endif +} ep_out_sw_buf; + + #if CFG_FIFO_MUTEX + #if CFG_TUD_AUDIO_FUNC_1_EP_OUT_SW_BUF_SZ > 0 + tu_static osal_mutex_def_t ep_out_ff_mutex_rd_1; #endif - #endif // CFG_TUD_AUDIO > 2 && CFG_TUD_AUDIO_FUNC_3_EP_OUT_SW_BUF_SZ > 0 -#endif // CFG_TUD_AUDIO_ENABLE_EP_OUT && !CFG_TUD_AUDIO_ENABLE_DECODING + #if CFG_TUD_AUDIO > 1 && CFG_TUD_AUDIO_FUNC_2_EP_OUT_SW_BUF_SZ > 0 + tu_static osal_mutex_def_t ep_out_ff_mutex_rd_2; + #endif + #if CFG_TUD_AUDIO > 2 && CFG_TUD_AUDIO_FUNC_3_EP_OUT_SW_BUF_SZ > 0 + tu_static osal_mutex_def_t ep_out_ff_mutex_rd_3; + #endif + #endif +#endif// CFG_TUD_AUDIO_ENABLE_EP_OUT // Linear buffer RX in case: // - target MCU is not capable of handling a ring buffer FIFO e.g. no hardware buffer is available or driver is would need to be changed dramatically OR -// - the software encoding is used - in this case the linear buffers serve as a target memory where logical channels are encoded into -#if CFG_TUD_AUDIO_ENABLE_EP_OUT && (USE_LINEAR_BUFFER || CFG_TUD_AUDIO_ENABLE_DECODING) +#if CFG_TUD_AUDIO_ENABLE_EP_OUT && USE_LINEAR_BUFFER +tu_static CFG_TUD_MEM_SECTION struct { #if CFG_TUD_AUDIO_FUNC_1_EP_OUT_SZ_MAX > 0 - tu_static CFG_TUD_MEM_SECTION CFG_TUSB_MEM_ALIGN uint8_t lin_buf_out_1[CFG_TUD_AUDIO_FUNC_1_EP_OUT_SZ_MAX]; + TUD_EPBUF_DEF(buf_1, CFG_TUD_AUDIO_FUNC_1_EP_OUT_SZ_MAX); #endif - #if CFG_TUD_AUDIO > 1 && CFG_TUD_AUDIO_FUNC_2_EP_OUT_SZ_MAX > 0 - tu_static CFG_TUD_MEM_SECTION CFG_TUSB_MEM_ALIGN uint8_t lin_buf_out_2[CFG_TUD_AUDIO_FUNC_2_EP_OUT_SZ_MAX]; + TUD_EPBUF_DEF(buf_2, CFG_TUD_AUDIO_FUNC_2_EP_OUT_SZ_MAX); #endif - #if CFG_TUD_AUDIO > 2 && CFG_TUD_AUDIO_FUNC_3_EP_OUT_SZ_MAX > 0 - tu_static CFG_TUD_MEM_SECTION CFG_TUSB_MEM_ALIGN uint8_t lin_buf_out_3[CFG_TUD_AUDIO_FUNC_3_EP_OUT_SZ_MAX]; + TUD_EPBUF_DEF(buf_3, CFG_TUD_AUDIO_FUNC_3_EP_OUT_SZ_MAX); #endif -#endif // CFG_TUD_AUDIO_ENABLE_EP_OUT && (USE_LINEAR_BUFFER || CFG_TUD_AUDIO_ENABLE_DECODING) +} lin_buf_out; +#endif// CFG_TUD_AUDIO_ENABLE_EP_OUT && USE_LINEAR_BUFFER // Control buffers -tu_static CFG_TUD_MEM_SECTION CFG_TUSB_MEM_ALIGN uint8_t ctrl_buf_1[CFG_TUD_AUDIO_FUNC_1_CTRL_BUF_SZ]; - -#if CFG_TUD_AUDIO > 1 -tu_static CFG_TUD_MEM_SECTION CFG_TUSB_MEM_ALIGN uint8_t ctrl_buf_2[CFG_TUD_AUDIO_FUNC_2_CTRL_BUF_SZ]; -#endif - -#if CFG_TUD_AUDIO > 2 -tu_static CFG_TUD_MEM_SECTION CFG_TUSB_MEM_ALIGN uint8_t ctrl_buf_3[CFG_TUD_AUDIO_FUNC_3_CTRL_BUF_SZ]; -#endif +tu_static CFG_TUD_MEM_SECTION struct { + TUD_EPBUF_DEF(buf1, CFG_TUD_AUDIO_FUNC_1_CTRL_BUF_SZ); + #if CFG_TUD_AUDIO > 1 + TUD_EPBUF_DEF(buf2, CFG_TUD_AUDIO_FUNC_2_CTRL_BUF_SZ); + #endif + #if CFG_TUD_AUDIO > 2 + TUD_EPBUF_DEF(buf3, CFG_TUD_AUDIO_FUNC_3_CTRL_BUF_SZ); + #endif +} ctrl_buf; // Active alternate setting of interfaces tu_static uint8_t alt_setting_1[CFG_TUD_AUDIO_FUNC_1_N_AS_INT]; @@ -222,131 +227,86 @@ tu_static uint8_t alt_setting_2[CFG_TUD_AUDIO_FUNC_2_N_AS_INT]; tu_static uint8_t alt_setting_3[CFG_TUD_AUDIO_FUNC_3_N_AS_INT]; #endif -// Software encoding/decoding support FIFOs -#if CFG_TUD_AUDIO_ENABLE_EP_IN && CFG_TUD_AUDIO_ENABLE_ENCODING - #if CFG_TUD_AUDIO_FUNC_1_TX_SUPP_SW_FIFO_SZ > 0 - tu_static CFG_TUSB_MEM_ALIGN uint8_t tx_supp_ff_buf_1[CFG_TUD_AUDIO_FUNC_1_N_TX_SUPP_SW_FIFO][CFG_TUD_AUDIO_FUNC_1_TX_SUPP_SW_FIFO_SZ]; - tu_static tu_fifo_t tx_supp_ff_1[CFG_TUD_AUDIO_FUNC_1_N_TX_SUPP_SW_FIFO]; - #if CFG_FIFO_MUTEX - tu_static osal_mutex_def_t tx_supp_ff_mutex_wr_1[CFG_TUD_AUDIO_FUNC_1_N_TX_SUPP_SW_FIFO]; // No need for read mutex as only USB driver reads from FIFO - #endif +// Aligned buffer for feedback EP +#if CFG_TUD_AUDIO_ENABLE_EP_OUT && CFG_TUD_AUDIO_ENABLE_FEEDBACK_EP +tu_static CFG_TUD_MEM_SECTION struct { + #if CFG_TUD_AUDIO_FUNC_1_EP_OUT_SZ_MAX > 0 + TUD_EPBUF_TYPE_DEF(uint32_t, buf_1); #endif - - #if CFG_TUD_AUDIO > 1 && CFG_TUD_AUDIO_FUNC_2_TX_SUPP_SW_FIFO_SZ > 0 - tu_static CFG_TUSB_MEM_ALIGN uint8_t tx_supp_ff_buf_2[CFG_TUD_AUDIO_FUNC_2_N_TX_SUPP_SW_FIFO][CFG_TUD_AUDIO_FUNC_2_TX_SUPP_SW_FIFO_SZ]; - tu_static tu_fifo_t tx_supp_ff_2[CFG_TUD_AUDIO_FUNC_2_N_TX_SUPP_SW_FIFO]; - #if CFG_FIFO_MUTEX - tu_static osal_mutex_def_t tx_supp_ff_mutex_wr_2[CFG_TUD_AUDIO_FUNC_2_N_TX_SUPP_SW_FIFO]; // No need for read mutex as only USB driver reads from FIFO - #endif + #if CFG_TUD_AUDIO > 1 && CFG_TUD_AUDIO_FUNC_2_EP_OUT_SZ_MAX > 0 + TUD_EPBUF_TYPE_DEF(uint32_t, buf_2); #endif - - #if CFG_TUD_AUDIO > 2 && CFG_TUD_AUDIO_FUNC_3_TX_SUPP_SW_FIFO_SZ > 0 - tu_static CFG_TUSB_MEM_ALIGN uint8_t tx_supp_ff_buf_3[CFG_TUD_AUDIO_FUNC_3_N_TX_SUPP_SW_FIFO][CFG_TUD_AUDIO_FUNC_3_TX_SUPP_SW_FIFO_SZ]; - tu_static tu_fifo_t tx_supp_ff_3[CFG_TUD_AUDIO_FUNC_3_N_TX_SUPP_SW_FIFO]; - #if CFG_FIFO_MUTEX - tu_static osal_mutex_def_t tx_supp_ff_mutex_wr_3[CFG_TUD_AUDIO_FUNC_3_N_TX_SUPP_SW_FIFO]; // No need for read mutex as only USB driver reads from FIFO - #endif + #if CFG_TUD_AUDIO > 2 && CFG_TUD_AUDIO_FUNC_3_EP_OUT_SZ_MAX > 0 + TUD_EPBUF_TYPE_DEF(uint32_t, buf_3); #endif +} fb_ep_buf; #endif -#if CFG_TUD_AUDIO_ENABLE_EP_OUT && CFG_TUD_AUDIO_ENABLE_DECODING - #if CFG_TUD_AUDIO_FUNC_1_RX_SUPP_SW_FIFO_SZ > 0 - tu_static CFG_TUSB_MEM_ALIGN uint8_t rx_supp_ff_buf_1[CFG_TUD_AUDIO_FUNC_1_N_RX_SUPP_SW_FIFO][CFG_TUD_AUDIO_FUNC_1_RX_SUPP_SW_FIFO_SZ]; - tu_static tu_fifo_t rx_supp_ff_1[CFG_TUD_AUDIO_FUNC_1_N_RX_SUPP_SW_FIFO]; - #if CFG_FIFO_MUTEX - tu_static osal_mutex_def_t rx_supp_ff_mutex_rd_1[CFG_TUD_AUDIO_FUNC_1_N_RX_SUPP_SW_FIFO]; // No need for write mutex as only USB driver writes into FIFO - #endif - #endif - - #if CFG_TUD_AUDIO > 1 && CFG_TUD_AUDIO_FUNC_2_RX_SUPP_SW_FIFO_SZ > 0 - tu_static CFG_TUSB_MEM_ALIGN uint8_t rx_supp_ff_buf_2[CFG_TUD_AUDIO_FUNC_2_N_RX_SUPP_SW_FIFO][CFG_TUD_AUDIO_FUNC_2_RX_SUPP_SW_FIFO_SZ]; - tu_static tu_fifo_t rx_supp_ff_2[CFG_TUD_AUDIO_FUNC_2_N_RX_SUPP_SW_FIFO]; - #if CFG_FIFO_MUTEX - tu_static osal_mutex_def_t rx_supp_ff_mutex_rd_2[CFG_TUD_AUDIO_FUNC_2_N_RX_SUPP_SW_FIFO]; // No need for write mutex as only USB driver writes into FIFO - #endif - #endif - - #if CFG_TUD_AUDIO > 2 && CFG_TUD_AUDIO_FUNC_3_RX_SUPP_SW_FIFO_SZ > 0 - tu_static CFG_TUSB_MEM_ALIGN uint8_t rx_supp_ff_buf_3[CFG_TUD_AUDIO_FUNC_3_N_RX_SUPP_SW_FIFO][CFG_TUD_AUDIO_FUNC_3_RX_SUPP_SW_FIFO_SZ]; - tu_static tu_fifo_t rx_supp_ff_3[CFG_TUD_AUDIO_FUNC_3_N_RX_SUPP_SW_FIFO]; - #if CFG_FIFO_MUTEX - tu_static osal_mutex_def_t rx_supp_ff_mutex_rd_3[CFG_TUD_AUDIO_FUNC_3_N_RX_SUPP_SW_FIFO]; // No need for write mutex as only USB driver writes into FIFO - #endif - #endif +// Aligned buffer for interrupt EP +#if CFG_TUD_AUDIO_ENABLE_INTERRUPT_EP +tu_static CFG_TUD_MEM_SECTION struct { + TUD_EPBUF_DEF(buf, CFG_TUD_AUDIO_INTERRUPT_EP_SZ); +} int_ep_buf[CFG_TUD_AUDIO]; #endif typedef struct { uint8_t rhport; - uint8_t const * p_desc; // Pointer pointing to Standard AC Interface Descriptor(4.7.1) - Audio Control descriptor defining audio function + uint8_t const *p_desc;// Pointer pointing to Standard AC Interface Descriptor(4.7.1) - Audio Control descriptor defining audio function #if CFG_TUD_AUDIO_ENABLE_EP_IN - uint8_t ep_in; // TX audio data EP. - uint16_t ep_in_sz; // Current size of TX EP - uint8_t ep_in_as_intf_num; // Corresponding Standard AS Interface Descriptor (4.9.1) belonging to output terminal to which this EP belongs - 0 is invalid (this fits to UAC2 specification since AS interfaces can not have interface number equal to zero) + uint8_t ep_in; // TX audio data EP. + uint16_t ep_in_sz; // Current size of TX EP + uint8_t ep_in_as_intf_num;// Corresponding Standard AS Interface Descriptor (4.9.1) belonging to output terminal to which this EP belongs - 0 is invalid (this fits to UAC2 specification since AS interfaces can not have interface number equal to zero) #endif #if CFG_TUD_AUDIO_ENABLE_EP_OUT - uint8_t ep_out; // Incoming (into uC) audio data EP. - uint16_t ep_out_sz; // Current size of RX EP - uint8_t ep_out_as_intf_num; // Corresponding Standard AS Interface Descriptor (4.9.1) belonging to input terminal to which this EP belongs - 0 is invalid (this fits to UAC2 specification since AS interfaces can not have interface number equal to zero) + uint8_t ep_out; // Incoming (into uC) audio data EP. + uint16_t ep_out_sz; // Current size of RX EP + uint8_t ep_out_as_intf_num;// Corresponding Standard AS Interface Descriptor (4.9.1) belonging to input terminal to which this EP belongs - 0 is invalid (this fits to UAC2 specification since AS interfaces can not have interface number equal to zero) -#if CFG_TUD_AUDIO_ENABLE_FEEDBACK_EP - uint8_t ep_fb; // Feedback EP. -#endif + #if CFG_TUD_AUDIO_ENABLE_FEEDBACK_EP + uint8_t ep_fb;// Feedback EP. + #endif #endif #if CFG_TUD_AUDIO_ENABLE_INTERRUPT_EP - uint8_t ep_int; // Audio control interrupt EP. + uint8_t ep_int;// Audio control interrupt EP. #endif - bool mounted; // Device opened + bool mounted;// Device opened - uint16_t desc_length; // Length of audio function descriptor + uint16_t desc_length;// Length of audio function descriptor #if CFG_TUD_AUDIO_ENABLE_FEEDBACK_EP struct { - CFG_TUSB_MEM_ALIGN uint32_t send_buf; - uint32_t value; // Feedback value for asynchronous mode (in 16.16 format). - uint32_t min_value; // min value according to UAC2 FMT-2.0 section 2.3.1.1. - uint32_t max_value; // max value according to UAC2 FMT-2.0 section 2.3.1.1. + uint32_t value; // Feedback value for asynchronous mode (in 16.16 format). + uint32_t min_value;// min value according to UAC2 FMT-2.0 section 2.3.1.1. + uint32_t max_value;// max value according to UAC2 FMT-2.0 section 2.3.1.1. - uint8_t frame_shift; // bInterval-1 in unit of frame (FS), micro-frame (HS) + uint8_t frame_shift;// bInterval-1 in unit of frame (FS), micro-frame (HS) uint8_t compute_method; bool format_correction; union { - uint8_t power_of_2; // pre-computed power of 2 shift - float float_const; // pre-computed float constant + uint8_t power_of_2;// pre-computed power of 2 shift + float float_const; // pre-computed float constant struct { uint32_t sample_freq; uint32_t mclk_freq; - }fixed; + } fixed; struct { - uint32_t nom_value; // In 16.16 format - uint32_t fifo_lvl_avg; // In 16.16 format - uint16_t fifo_lvl_thr; // fifo level threshold - uint16_t rate_const[2]; // pre-computed feedback/fifo_depth rate - }fifo_count; - }compute; + uint32_t nom_value; // In 16.16 format + uint32_t fifo_lvl_avg; // In 16.16 format + uint16_t fifo_lvl_thr; // fifo level threshold + uint16_t rate_const[2];// pre-computed feedback/fifo_depth rate + } fifo_count; + } compute; } feedback; -#endif // CFG_TUD_AUDIO_ENABLE_FEEDBACK_EP - - // Decoding parameters - parameters are set when alternate AS interface is set by host - // Coding is currently only supported for EP. Software coding corresponding to AS interfaces without EPs are not supported currently. -#if CFG_TUD_AUDIO_ENABLE_EP_OUT && CFG_TUD_AUDIO_ENABLE_DECODING - audio_format_type_t format_type_rx; - uint8_t n_channels_rx; - -#if CFG_TUD_AUDIO_ENABLE_TYPE_I_DECODING - audio_data_format_type_I_t format_type_I_rx; - uint8_t n_bytes_per_sample_rx; - uint8_t n_ff_used_rx; -#endif -#endif +#endif// CFG_TUD_AUDIO_ENABLE_FEEDBACK_EP #if CFG_TUD_AUDIO_ENABLE_EP_IN && CFG_TUD_AUDIO_EP_IN_FLOW_CONTROL uint32_t sample_rate_tx; @@ -355,82 +315,56 @@ typedef struct uint8_t interval_tx; #endif - // Encoding parameters - parameters are set when alternate AS interface is set by host -#if CFG_TUD_AUDIO_ENABLE_EP_IN && (CFG_TUD_AUDIO_ENABLE_ENCODING || CFG_TUD_AUDIO_EP_IN_FLOW_CONTROL) +// Encoding parameters - parameters are set when alternate AS interface is set by host +#if CFG_TUD_AUDIO_ENABLE_EP_IN && CFG_TUD_AUDIO_EP_IN_FLOW_CONTROL audio_format_type_t format_type_tx; uint8_t n_channels_tx; uint8_t n_bytes_per_sample_tx; - -#if CFG_TUD_AUDIO_ENABLE_TYPE_I_ENCODING - audio_data_format_type_I_t format_type_I_tx; - uint8_t n_ff_used_tx; -#endif #endif /*------------- From this point, data is not cleared by bus reset -------------*/ // Buffer for control requests - uint8_t * ctrl_buf; + uint8_t *ctrl_buf; uint8_t ctrl_buf_sz; // Current active alternate settings - uint8_t * alt_setting; // We need to save the current alternate setting this way, because it is possible that there are AS interfaces which do not have an EP! + uint8_t *alt_setting;// We need to save the current alternate setting this way, because it is possible that there are AS interfaces which do not have an EP! - // EP Transfer buffers and FIFOs -#if CFG_TUD_AUDIO_ENABLE_EP_OUT && !CFG_TUD_AUDIO_ENABLE_DECODING +// EP Transfer buffers and FIFOs +#if CFG_TUD_AUDIO_ENABLE_EP_OUT tu_fifo_t ep_out_ff; #endif -#if CFG_TUD_AUDIO_ENABLE_EP_IN && !CFG_TUD_AUDIO_ENABLE_ENCODING +#if CFG_TUD_AUDIO_ENABLE_EP_IN tu_fifo_t ep_in_ff; #endif - // Audio control interrupt buffer - no FIFO - 6 Bytes according to UAC 2 specification (p. 74) -#if CFG_TUD_AUDIO_ENABLE_INTERRUPT_EP - CFG_TUSB_MEM_ALIGN uint8_t ep_int_buf[6]; +// Linear buffer in case target MCU is not capable of handling a ring buffer FIFO e.g. no hardware buffer is available or driver is would need to be changed dramatically +#if CFG_TUD_AUDIO_ENABLE_EP_OUT && USE_LINEAR_BUFFER + uint8_t *lin_buf_out; + #define USE_LINEAR_BUFFER_RX 1 #endif - // Support FIFOs for software encoding and decoding -#if CFG_TUD_AUDIO_ENABLE_EP_OUT && CFG_TUD_AUDIO_ENABLE_DECODING - tu_fifo_t * rx_supp_ff; - uint8_t n_rx_supp_ff; - uint16_t rx_supp_ff_sz_max; -#if CFG_TUD_AUDIO_ENABLE_TYPE_I_DECODING - uint8_t n_channels_per_ff_rx; -#endif +#if CFG_TUD_AUDIO_ENABLE_EP_IN && USE_LINEAR_BUFFER + uint8_t *lin_buf_in; + #define USE_LINEAR_BUFFER_TX 1 #endif -#if CFG_TUD_AUDIO_ENABLE_EP_IN && CFG_TUD_AUDIO_ENABLE_ENCODING - tu_fifo_t * tx_supp_ff; - uint8_t n_tx_supp_ff; - uint16_t tx_supp_ff_sz_max; -#if CFG_TUD_AUDIO_ENABLE_TYPE_I_ENCODING - uint8_t n_channels_per_ff_tx; +#if CFG_TUD_AUDIO_ENABLE_FEEDBACK_EP + uint32_t *fb_buf; #endif -#endif - - // Linear buffer in case target MCU is not capable of handling a ring buffer FIFO e.g. no hardware buffer is available or driver is would need to be changed dramatically OR the support FIFOs are used -#if CFG_TUD_AUDIO_ENABLE_EP_OUT && (USE_LINEAR_BUFFER || CFG_TUD_AUDIO_ENABLE_DECODING) - uint8_t * lin_buf_out; -#define USE_LINEAR_BUFFER_RX 1 -#endif - -#if CFG_TUD_AUDIO_ENABLE_EP_IN && (USE_LINEAR_BUFFER || CFG_TUD_AUDIO_ENABLE_ENCODING) - uint8_t * lin_buf_in; -#define USE_LINEAR_BUFFER_TX 1 -#endif - } audiod_function_t; #ifndef USE_LINEAR_BUFFER_TX -#define USE_LINEAR_BUFFER_TX 0 + #define USE_LINEAR_BUFFER_TX 0 #endif #ifndef USE_LINEAR_BUFFER_RX -#define USE_LINEAR_BUFFER_RX 0 + #define USE_LINEAR_BUFFER_RX 0 #endif -#define ITF_MEM_RESET_SIZE offsetof(audiod_function_t, ctrl_buf) +#define ITF_MEM_RESET_SIZE offsetof(audiod_function_t, ctrl_buf) //--------------------------------------------------------------------+ // WEAK FUNCTION STUBS @@ -480,7 +414,7 @@ TU_ATTR_WEAK void tud_audio_fb_done_cb(uint8_t func_id) { (void) func_id; } -TU_ATTR_WEAK void tud_audio_feedback_params_cb(uint8_t func_id, uint8_t alt_itf, audio_feedback_params_t* feedback_param) { +TU_ATTR_WEAK void tud_audio_feedback_params_cb(uint8_t func_id, uint8_t alt_itf, audio_feedback_params_t *feedback_param) { (void) func_id; (void) alt_itf; feedback_param->method = AUDIO_FEEDBACK_METHOD_DISABLED; @@ -505,68 +439,68 @@ TU_ATTR_WEAK void tud_audio_int_done_cb(uint8_t rhport) { #endif // Invoked when audio set interface request received -TU_ATTR_WEAK bool tud_audio_set_itf_cb(uint8_t rhport, tusb_control_request_t const * p_request) { +TU_ATTR_WEAK bool tud_audio_set_itf_cb(uint8_t rhport, tusb_control_request_t const *p_request) { (void) rhport; (void) p_request; return true; } // Invoked when audio set interface request received which closes an EP -TU_ATTR_WEAK bool tud_audio_set_itf_close_EP_cb(uint8_t rhport, tusb_control_request_t const * p_request) { +TU_ATTR_WEAK bool tud_audio_set_itf_close_EP_cb(uint8_t rhport, tusb_control_request_t const *p_request) { (void) rhport; (void) p_request; return true; } // Invoked when audio class specific set request received for an EP -TU_ATTR_WEAK bool tud_audio_set_req_ep_cb(uint8_t rhport, tusb_control_request_t const * p_request, uint8_t *pBuff) { +TU_ATTR_WEAK bool tud_audio_set_req_ep_cb(uint8_t rhport, tusb_control_request_t const *p_request, uint8_t *pBuff) { (void) rhport; (void) p_request; (void) pBuff; TU_LOG2(" No EP set request callback available!\r\n"); - return false; // In case no callback function is present or request can not be conducted we stall it + return false;// In case no callback function is present or request can not be conducted we stall it } // Invoked when audio class specific set request received for an interface -TU_ATTR_WEAK bool tud_audio_set_req_itf_cb(uint8_t rhport, tusb_control_request_t const * p_request, uint8_t *pBuff) { +TU_ATTR_WEAK bool tud_audio_set_req_itf_cb(uint8_t rhport, tusb_control_request_t const *p_request, uint8_t *pBuff) { (void) rhport; (void) p_request; (void) pBuff; TU_LOG2(" No interface set request callback available!\r\n"); - return false; // In case no callback function is present or request can not be conducted we stall it + return false;// In case no callback function is present or request can not be conducted we stall it } // Invoked when audio class specific set request received for an entity -TU_ATTR_WEAK bool tud_audio_set_req_entity_cb(uint8_t rhport, tusb_control_request_t const * p_request, uint8_t *pBuff) { +TU_ATTR_WEAK bool tud_audio_set_req_entity_cb(uint8_t rhport, tusb_control_request_t const *p_request, uint8_t *pBuff) { (void) rhport; (void) p_request; (void) pBuff; TU_LOG2(" No entity set request callback available!\r\n"); - return false; // In case no callback function is present or request can not be conducted we stall it + return false;// In case no callback function is present or request can not be conducted we stall it } // Invoked when audio class specific get request received for an EP -TU_ATTR_WEAK bool tud_audio_get_req_ep_cb(uint8_t rhport, tusb_control_request_t const * p_request) { +TU_ATTR_WEAK bool tud_audio_get_req_ep_cb(uint8_t rhport, tusb_control_request_t const *p_request) { (void) rhport; (void) p_request; TU_LOG2(" No EP get request callback available!\r\n"); - return false; // Stall + return false;// Stall } // Invoked when audio class specific get request received for an interface -TU_ATTR_WEAK bool tud_audio_get_req_itf_cb(uint8_t rhport, tusb_control_request_t const * p_request) { +TU_ATTR_WEAK bool tud_audio_get_req_itf_cb(uint8_t rhport, tusb_control_request_t const *p_request) { (void) rhport; (void) p_request; TU_LOG2(" No interface get request callback available!\r\n"); - return false; // Stall + return false;// Stall } // Invoked when audio class specific get request received for an entity -TU_ATTR_WEAK bool tud_audio_get_req_entity_cb(uint8_t rhport, tusb_control_request_t const * p_request) { +TU_ATTR_WEAK bool tud_audio_get_req_entity_cb(uint8_t rhport, tusb_control_request_t const *p_request) { (void) rhport; (void) p_request; TU_LOG2(" No entity get request callback available!\r\n"); - return false; // Stall + return false;// Stall } //--------------------------------------------------------------------+ @@ -575,54 +509,37 @@ TU_ATTR_WEAK bool tud_audio_get_req_entity_cb(uint8_t rhport, tusb_control_reque tu_static CFG_TUD_MEM_SECTION audiod_function_t _audiod_fct[CFG_TUD_AUDIO]; #if CFG_TUD_AUDIO_ENABLE_EP_OUT -static bool audiod_rx_done_cb(uint8_t rhport, audiod_function_t* audio, uint16_t n_bytes_received); -#endif - -#if CFG_TUD_AUDIO_ENABLE_DECODING && CFG_TUD_AUDIO_ENABLE_EP_OUT -static bool audiod_decode_type_I_pcm(uint8_t rhport, audiod_function_t* audio, uint16_t n_bytes_received); +static bool audiod_rx_done_cb(uint8_t rhport, audiod_function_t *audio, uint16_t n_bytes_received); #endif #if CFG_TUD_AUDIO_ENABLE_EP_IN -static bool audiod_tx_done_cb(uint8_t rhport, audiod_function_t* audio); +static bool audiod_tx_done_cb(uint8_t rhport, audiod_function_t *audio); #endif -#if CFG_TUD_AUDIO_ENABLE_ENCODING && CFG_TUD_AUDIO_ENABLE_EP_IN -static uint16_t audiod_encode_type_I_pcm(uint8_t rhport, audiod_function_t* audio); -#endif - -static bool audiod_get_interface(uint8_t rhport, tusb_control_request_t const * p_request); -static bool audiod_set_interface(uint8_t rhport, tusb_control_request_t const * p_request); +static bool audiod_get_interface(uint8_t rhport, tusb_control_request_t const *p_request); +static bool audiod_set_interface(uint8_t rhport, tusb_control_request_t const *p_request); static bool audiod_get_AS_interface_index_global(uint8_t itf, uint8_t *func_id, uint8_t *idxItf, uint8_t const **pp_desc_int); -static bool audiod_get_AS_interface_index(uint8_t itf, audiod_function_t * audio, uint8_t *idxItf, uint8_t const **pp_desc_int); +static bool audiod_get_AS_interface_index(uint8_t itf, audiod_function_t *audio, uint8_t *idxItf, uint8_t const **pp_desc_int); static bool audiod_verify_entity_exists(uint8_t itf, uint8_t entityID, uint8_t *func_id); static bool audiod_verify_itf_exists(uint8_t itf, uint8_t *func_id); static bool audiod_verify_ep_exists(uint8_t ep, uint8_t *func_id); -static uint8_t audiod_get_audio_fct_idx(audiod_function_t * audio); - -#if (CFG_TUD_AUDIO_ENABLE_EP_IN && (CFG_TUD_AUDIO_EP_IN_FLOW_CONTROL || CFG_TUD_AUDIO_ENABLE_ENCODING)) || (CFG_TUD_AUDIO_ENABLE_EP_OUT && CFG_TUD_AUDIO_ENABLE_DECODING) -static void audiod_parse_for_AS_params(audiod_function_t* audio, uint8_t const * p_desc, uint8_t const * p_desc_end, uint8_t const as_itf); - -static inline uint8_t tu_desc_subtype(void const* desc) -{ - return ((uint8_t const*) desc)[2]; -} -#endif +static uint8_t audiod_get_audio_fct_idx(audiod_function_t *audio); #if CFG_TUD_AUDIO_ENABLE_EP_IN && CFG_TUD_AUDIO_EP_IN_FLOW_CONTROL -static bool audiod_calc_tx_packet_sz(audiod_function_t* audio); -static uint16_t audiod_tx_packet_size(const uint16_t* norminal_size, uint16_t data_count, uint16_t fifo_depth, uint16_t max_size); +static void audiod_parse_flow_control_params(audiod_function_t *audio, uint8_t const *p_desc); +static bool audiod_calc_tx_packet_sz(audiod_function_t *audio); +static uint16_t audiod_tx_packet_size(const uint16_t *norminal_size, uint16_t data_count, uint16_t fifo_depth, uint16_t max_size); #endif #if CFG_TUD_AUDIO_ENABLE_EP_OUT && CFG_TUD_AUDIO_ENABLE_FEEDBACK_EP -static bool audiod_set_fb_params_freq(audiod_function_t* audio, uint32_t sample_freq, uint32_t mclk_freq); -static void audiod_fb_fifo_count_update(audiod_function_t* audio, uint16_t lvl_new); +static bool audiod_set_fb_params_freq(audiod_function_t *audio, uint32_t sample_freq, uint32_t mclk_freq); +static void audiod_fb_fifo_count_update(audiod_function_t *audio, uint16_t lvl_new); #endif -bool tud_audio_n_mounted(uint8_t func_id) -{ +bool tud_audio_n_mounted(uint8_t func_id) { TU_VERIFY(func_id < CFG_TUD_AUDIO); - audiod_function_t* audio = &_audiod_fct[func_id]; + audiod_function_t *audio = &_audiod_fct[func_id]; return audio->mounted; } @@ -631,68 +548,30 @@ bool tud_audio_n_mounted(uint8_t func_id) // READ API //--------------------------------------------------------------------+ -#if CFG_TUD_AUDIO_ENABLE_EP_OUT && !CFG_TUD_AUDIO_ENABLE_DECODING +#if CFG_TUD_AUDIO_ENABLE_EP_OUT -uint16_t tud_audio_n_available(uint8_t func_id) -{ +uint16_t tud_audio_n_available(uint8_t func_id) { TU_VERIFY(func_id < CFG_TUD_AUDIO && _audiod_fct[func_id].p_desc != NULL); return tu_fifo_count(&_audiod_fct[func_id].ep_out_ff); } -uint16_t tud_audio_n_read(uint8_t func_id, void* buffer, uint16_t bufsize) -{ +uint16_t tud_audio_n_read(uint8_t func_id, void *buffer, uint16_t bufsize) { TU_VERIFY(func_id < CFG_TUD_AUDIO && _audiod_fct[func_id].p_desc != NULL); return tu_fifo_read_n(&_audiod_fct[func_id].ep_out_ff, buffer, bufsize); } -bool tud_audio_n_clear_ep_out_ff(uint8_t func_id) -{ +bool tud_audio_n_clear_ep_out_ff(uint8_t func_id) { TU_VERIFY(func_id < CFG_TUD_AUDIO && _audiod_fct[func_id].p_desc != NULL); return tu_fifo_clear(&_audiod_fct[func_id].ep_out_ff); } -tu_fifo_t* tud_audio_n_get_ep_out_ff(uint8_t func_id) -{ - if(func_id < CFG_TUD_AUDIO && _audiod_fct[func_id].p_desc != NULL) return &_audiod_fct[func_id].ep_out_ff; +tu_fifo_t *tud_audio_n_get_ep_out_ff(uint8_t func_id) { + if (func_id < CFG_TUD_AUDIO && _audiod_fct[func_id].p_desc != NULL) return &_audiod_fct[func_id].ep_out_ff; return NULL; } -#endif - -#if CFG_TUD_AUDIO_ENABLE_DECODING && CFG_TUD_AUDIO_ENABLE_EP_OUT -// Delete all content in the support RX FIFOs -bool tud_audio_n_clear_rx_support_ff(uint8_t func_id, uint8_t ff_idx) -{ - TU_VERIFY(func_id < CFG_TUD_AUDIO && _audiod_fct[func_id].p_desc != NULL && ff_idx < _audiod_fct[func_id].n_rx_supp_ff); - return tu_fifo_clear(&_audiod_fct[func_id].rx_supp_ff[ff_idx]); -} - -uint16_t tud_audio_n_available_support_ff(uint8_t func_id, uint8_t ff_idx) -{ - TU_VERIFY(func_id < CFG_TUD_AUDIO && _audiod_fct[func_id].p_desc != NULL && ff_idx < _audiod_fct[func_id].n_rx_supp_ff); - return tu_fifo_count(&_audiod_fct[func_id].rx_supp_ff[ff_idx]); -} - -uint16_t tud_audio_n_read_support_ff(uint8_t func_id, uint8_t ff_idx, void* buffer, uint16_t bufsize) -{ - TU_VERIFY(func_id < CFG_TUD_AUDIO && _audiod_fct[func_id].p_desc != NULL && ff_idx < _audiod_fct[func_id].n_rx_supp_ff); - return tu_fifo_read_n(&_audiod_fct[func_id].rx_supp_ff[ff_idx], buffer, bufsize); -} - -tu_fifo_t* tud_audio_n_get_rx_support_ff(uint8_t func_id, uint8_t ff_idx) -{ - if(func_id < CFG_TUD_AUDIO && _audiod_fct[func_id].p_desc != NULL && ff_idx < _audiod_fct[func_id].n_rx_supp_ff) return &_audiod_fct[func_id].rx_supp_ff[ff_idx]; - return NULL; -} -#endif - -// This function is called once an audio packet is received by the USB and is responsible for putting data from USB memory into EP_OUT_FIFO (or support FIFOs + decoding of received stream into audio channels). -// If you prefer your own (more efficient) implementation suiting your purpose set CFG_TUD_AUDIO_ENABLE_DECODING = 0. - -#if CFG_TUD_AUDIO_ENABLE_EP_OUT - -static bool audiod_rx_done_cb(uint8_t rhport, audiod_function_t* audio, uint16_t n_bytes_received) -{ +// This function is called once an audio packet is received by the USB and is responsible for putting data from USB memory into EP_OUT_FIFO. +static bool audiod_rx_done_cb(uint8_t rhport, audiod_function_t *audio, uint16_t n_bytes_received) { uint8_t idxItf = 0; uint8_t const *dummy2; uint8_t idx_audio_fct = 0; @@ -700,66 +579,25 @@ static bool audiod_rx_done_cb(uint8_t rhport, audiod_function_t* audio, uint16_t idx_audio_fct = audiod_get_audio_fct_idx(audio); TU_VERIFY(audiod_get_AS_interface_index(audio->ep_out_as_intf_num, audio, &idxItf, &dummy2)); - // Call a weak callback here - a possibility for user to get informed an audio packet was received and data gets now loaded into EP FIFO (or decoded into support RX software FIFO) + // Call a weak callback here - a possibility for user to get informed an audio packet was received and data gets now loaded into EP FIFO TU_VERIFY(tud_audio_rx_done_pre_read_cb(rhport, n_bytes_received, idx_audio_fct, audio->ep_out, audio->alt_setting[idxItf])); -#if CFG_TUD_AUDIO_ENABLE_DECODING - - switch (audio->format_type_rx) - { - case AUDIO_FORMAT_TYPE_UNDEFINED: - // INDIVIDUAL DECODING PROCEDURE REQUIRED HERE! - TU_LOG2(" Desired CFG_TUD_AUDIO_FORMAT encoding not implemented!\r\n"); - TU_BREAKPOINT(); - break; - - case AUDIO_FORMAT_TYPE_I: - - switch (audio->format_type_I_rx) - { - case AUDIO_DATA_FORMAT_TYPE_I_PCM: - TU_VERIFY(audiod_decode_type_I_pcm(rhport, audio, n_bytes_received)); - break; - - default: - // DESIRED CFG_TUD_AUDIO_FORMAT_TYPE_I_RX NOT IMPLEMENTED! - TU_LOG2(" Desired CFG_TUD_AUDIO_FORMAT_TYPE_I_RX encoding not implemented!\r\n"); - TU_BREAKPOINT(); - break; - } - break; - - default: - // Desired CFG_TUD_AUDIO_FORMAT_TYPE_RX not implemented! - TU_LOG2(" Desired CFG_TUD_AUDIO_FORMAT_TYPE_RX not implemented!\r\n"); - TU_BREAKPOINT(); - break; - } - - // Prepare for next transmission - TU_VERIFY(usbd_edpt_xfer(rhport, audio->ep_out, audio->lin_buf_out, audio->ep_out_sz), false); - -#else - -#if USE_LINEAR_BUFFER_RX + #if USE_LINEAR_BUFFER_RX // Data currently is in linear buffer, copy into EP OUT FIFO TU_VERIFY(tu_fifo_write_n(&audio->ep_out_ff, audio->lin_buf_out, n_bytes_received)); // Schedule for next receive TU_VERIFY(usbd_edpt_xfer(rhport, audio->ep_out, audio->lin_buf_out, audio->ep_out_sz), false); -#else + #else // Data is already placed in EP FIFO, schedule for next receive TU_VERIFY(usbd_edpt_xfer_fifo(rhport, audio->ep_out, &audio->ep_out_ff, audio->ep_out_sz), false); -#endif + #endif -#if CFG_TUD_AUDIO_ENABLE_FEEDBACK_EP - if(audio->feedback.compute_method == AUDIO_FEEDBACK_METHOD_FIFO_COUNT) - { + #if CFG_TUD_AUDIO_ENABLE_FEEDBACK_EP + if (audio->feedback.compute_method == AUDIO_FEEDBACK_METHOD_FIFO_COUNT) { audiod_fb_fifo_count_update(audio, tu_fifo_count(&audio->ep_out_ff)); } -#endif - -#endif + #endif // Call a weak callback here - a possibility for user to get informed decoding was completed TU_VERIFY(tud_audio_rx_done_post_read_cb(rhport, n_bytes_received, idx_audio_fct, audio->ep_out, audio->alt_setting[idxItf])); @@ -767,121 +605,13 @@ static bool audiod_rx_done_cb(uint8_t rhport, audiod_function_t* audio, uint16_t return true; } -#endif //CFG_TUD_AUDIO_ENABLE_EP_OUT - -// The following functions are used in case CFG_TUD_AUDIO_ENABLE_DECODING != 0 -#if CFG_TUD_AUDIO_ENABLE_DECODING && CFG_TUD_AUDIO_ENABLE_EP_OUT - -// Decoding according to 2.3.1.5 Audio Streams - -// Helper function -static inline void * audiod_interleaved_copy_bytes_fast_decode(uint16_t const nBytesPerSample, void * dst, const void * dst_end, void * src, uint8_t const n_ff_used) -{ - // Due to one FIFO contains 2 channels, data always aligned to (nBytesPerSample * 2) - uint16_t * dst16 = dst; - uint16_t * src16 = src; - const uint16_t * dst_end16 = dst_end; - uint32_t * dst32 = dst; - uint32_t * src32 = src; - const uint32_t * dst_end32 = dst_end; - - if (nBytesPerSample == 1) - { - while(dst16 < dst_end16) - { - *dst16++ = *src16++; - src16 += n_ff_used - 1; - } - return src16; - } - else if (nBytesPerSample == 2) - { - while(dst32 < dst_end32) - { - *dst32++ = *src32++; - src32 += n_ff_used - 1; - } - return src32; - } - else if (nBytesPerSample == 3) - { - while(dst16 < dst_end16) - { - *dst16++ = *src16++; - *dst16++ = *src16++; - *dst16++ = *src16++; - src16 += 3 * (n_ff_used - 1); - } - return src16; - } - else // nBytesPerSample == 4 - { - while(dst32 < dst_end32) - { - *dst32++ = *src32++; - *dst32++ = *src32++; - src32 += 2 * (n_ff_used - 1); - } - return src32; - } -} - -static bool audiod_decode_type_I_pcm(uint8_t rhport, audiod_function_t* audio, uint16_t n_bytes_received) -{ - (void) rhport; - - // Determine amount of samples - uint8_t const n_ff_used = audio->n_ff_used_rx; - uint16_t const nBytesPerFFToRead = n_bytes_received / n_ff_used; - uint8_t cnt_ff; - - // Decode - uint8_t * src; - uint8_t * dst_end; - - tu_fifo_buffer_info_t info; - - for (cnt_ff = 0; cnt_ff < n_ff_used; cnt_ff++) - { - tu_fifo_get_write_info(&audio->rx_supp_ff[cnt_ff], &info); - - if (info.len_lin != 0) - { - info.len_lin = tu_min16(nBytesPerFFToRead, info.len_lin); - src = &audio->lin_buf_out[cnt_ff*audio->n_channels_per_ff_rx * audio->n_bytes_per_sample_rx]; - dst_end = info.ptr_lin + info.len_lin; - src = audiod_interleaved_copy_bytes_fast_decode(audio->n_bytes_per_sample_rx, info.ptr_lin, dst_end, src, n_ff_used); - - // Handle wrapped part of FIFO - info.len_wrap = tu_min16(nBytesPerFFToRead - info.len_lin, info.len_wrap); - if (info.len_wrap != 0) - { - dst_end = info.ptr_wrap + info.len_wrap; - audiod_interleaved_copy_bytes_fast_decode(audio->n_bytes_per_sample_rx, info.ptr_wrap, dst_end, src, n_ff_used); - } - tu_fifo_advance_write_pointer(&audio->rx_supp_ff[cnt_ff], info.len_lin + info.len_wrap); - } - } - - // Number of bytes should be a multiple of CFG_TUD_AUDIO_N_BYTES_PER_SAMPLE_RX * CFG_TUD_AUDIO_N_CHANNELS_RX but checking makes no sense - no way to correct it - // TU_VERIFY(cnt != n_bytes); - -#if CFG_TUD_AUDIO_ENABLE_FEEDBACK_EP - if(audio->feedback.compute_method == AUDIO_FEEDBACK_METHOD_FIFO_COUNT) - { - audiod_fb_fifo_count_update(audio, tu_fifo_count(&audio->rx_supp_ff[0])); - } -#endif - - return true; -} -#endif //CFG_TUD_AUDIO_ENABLE_DECODING +#endif//CFG_TUD_AUDIO_ENABLE_EP_OUT //--------------------------------------------------------------------+ // WRITE API //--------------------------------------------------------------------+ -#if CFG_TUD_AUDIO_ENABLE_EP_IN && !CFG_TUD_AUDIO_ENABLE_ENCODING +#if CFG_TUD_AUDIO_ENABLE_EP_IN /** * \brief Write data to EP in buffer @@ -894,97 +624,25 @@ static bool audiod_decode_type_I_pcm(uint8_t rhport, audiod_function_t* audio, u * \param[in] len: # of array elements to copy * \return Number of bytes actually written */ -uint16_t tud_audio_n_write(uint8_t func_id, const void * data, uint16_t len) -{ +uint16_t tud_audio_n_write(uint8_t func_id, const void *data, uint16_t len) { TU_VERIFY(func_id < CFG_TUD_AUDIO && _audiod_fct[func_id].p_desc != NULL); return tu_fifo_write_n(&_audiod_fct[func_id].ep_in_ff, data, len); } -bool tud_audio_n_clear_ep_in_ff(uint8_t func_id) // Delete all content in the EP IN FIFO +bool tud_audio_n_clear_ep_in_ff(uint8_t func_id)// Delete all content in the EP IN FIFO { TU_VERIFY(func_id < CFG_TUD_AUDIO && _audiod_fct[func_id].p_desc != NULL); return tu_fifo_clear(&_audiod_fct[func_id].ep_in_ff); } -tu_fifo_t* tud_audio_n_get_ep_in_ff(uint8_t func_id) -{ - if(func_id < CFG_TUD_AUDIO && _audiod_fct[func_id].p_desc != NULL) return &_audiod_fct[func_id].ep_in_ff; +tu_fifo_t *tud_audio_n_get_ep_in_ff(uint8_t func_id) { + if (func_id < CFG_TUD_AUDIO && _audiod_fct[func_id].p_desc != NULL) return &_audiod_fct[func_id].ep_in_ff; return NULL; } -#endif - -#if CFG_TUD_AUDIO_ENABLE_ENCODING && CFG_TUD_AUDIO_ENABLE_EP_IN - -uint16_t tud_audio_n_flush_tx_support_ff(uint8_t func_id) // Force all content in the support TX FIFOs to be written into linear buffer and schedule a transmit -{ - TU_VERIFY(func_id < CFG_TUD_AUDIO && _audiod_fct[func_id].p_desc != NULL); - audiod_function_t* audio = &_audiod_fct[func_id]; - - uint16_t n_bytes_copied = tu_fifo_count(&audio->tx_supp_ff[0]); - - TU_VERIFY(audiod_tx_done_cb(audio->rhport, audio)); - - n_bytes_copied -= tu_fifo_count(&audio->tx_supp_ff[0]); - n_bytes_copied = n_bytes_copied*audio->tx_supp_ff[0].item_size; - - return n_bytes_copied; -} - -bool tud_audio_n_clear_tx_support_ff(uint8_t func_id, uint8_t ff_idx) -{ - TU_VERIFY(func_id < CFG_TUD_AUDIO && _audiod_fct[func_id].p_desc != NULL && ff_idx < _audiod_fct[func_id].n_tx_supp_ff); - return tu_fifo_clear(&_audiod_fct[func_id].tx_supp_ff[ff_idx]); -} - -uint16_t tud_audio_n_write_support_ff(uint8_t func_id, uint8_t ff_idx, const void * data, uint16_t len) -{ - TU_VERIFY(func_id < CFG_TUD_AUDIO && _audiod_fct[func_id].p_desc != NULL && ff_idx < _audiod_fct[func_id].n_tx_supp_ff); - return tu_fifo_write_n(&_audiod_fct[func_id].tx_supp_ff[ff_idx], data, len); -} - -tu_fifo_t* tud_audio_n_get_tx_support_ff(uint8_t func_id, uint8_t ff_idx) -{ - if(func_id < CFG_TUD_AUDIO && _audiod_fct[func_id].p_desc != NULL && ff_idx < _audiod_fct[func_id].n_tx_supp_ff) return &_audiod_fct[func_id].tx_supp_ff[ff_idx]; - return NULL; -} - -#endif - - -#if CFG_TUD_AUDIO_ENABLE_INTERRUPT_EP -// If no interrupt transmit is pending bytes get written into buffer and a transmit is scheduled - once transmit completed tud_audio_int_done_cb() is called in inform user -bool tud_audio_int_n_write(uint8_t func_id, const audio_interrupt_data_t * data) -{ - TU_VERIFY(func_id < CFG_TUD_AUDIO && _audiod_fct[func_id].p_desc != NULL); - - TU_VERIFY(_audiod_fct[func_id].ep_int != 0); - - // We write directly into the EP's buffer - abort if previous transfer not complete - TU_VERIFY(usbd_edpt_claim(_audiod_fct[func_id].rhport, _audiod_fct[func_id].ep_int)); - - // Check length - if (tu_memcpy_s(_audiod_fct[func_id].ep_int_buf, sizeof(_audiod_fct[func_id].ep_int_buf), data, sizeof(audio_interrupt_data_t)) == 0) - { - // Schedule transmit - TU_ASSERT(usbd_edpt_xfer(_audiod_fct[func_id].rhport, _audiod_fct[func_id].ep_int, _audiod_fct[func_id].ep_int_buf, sizeof(_audiod_fct[func_id].ep_int_buf)), 0); - } else - { - // Release endpoint since we don't make any transfer - usbd_edpt_release(_audiod_fct[func_id].rhport, _audiod_fct[func_id].ep_int); - } - - return true; -} -#endif - // This function is called once a transmit of an audio packet was successfully completed. Here, we encode samples and place it in IN EP's buffer for next transmission. -// If you prefer your own (more efficient) implementation suiting your purpose set CFG_TUD_AUDIO_ENABLE_ENCODING = 0 and use tud_audio_n_write. - // n_bytes_copied - Informs caller how many bytes were loaded. In case n_bytes_copied = 0, a ZLP is scheduled to inform host no data is available for current frame. -#if CFG_TUD_AUDIO_ENABLE_EP_IN -static bool audiod_tx_done_cb(uint8_t rhport, audiod_function_t * audio) -{ +static bool audiod_tx_done_cb(uint8_t rhport, audiod_function_t *audio) { uint8_t idxItf; uint8_t const *dummy2; @@ -1001,62 +659,19 @@ static bool audiod_tx_done_cb(uint8_t rhport, audiod_function_t * audio) // Send everything in ISO EP FIFO uint16_t n_bytes_tx; - // If support FIFOs are used, encode and schedule transmit -#if CFG_TUD_AUDIO_ENABLE_ENCODING && CFG_TUD_AUDIO_ENABLE_EP_IN - switch (audio->format_type_tx) - { - case AUDIO_FORMAT_TYPE_UNDEFINED: - // INDIVIDUAL ENCODING PROCEDURE REQUIRED HERE! - TU_LOG2(" Desired CFG_TUD_AUDIO_FORMAT encoding not implemented!\r\n"); - TU_BREAKPOINT(); - n_bytes_tx = 0; - break; - - case AUDIO_FORMAT_TYPE_I: - - switch (audio->format_type_I_tx) - { - case AUDIO_DATA_FORMAT_TYPE_I_PCM: - - n_bytes_tx = audiod_encode_type_I_pcm(rhport, audio); - break; - - default: - // YOUR ENCODING IS REQUIRED HERE! - TU_LOG2(" Desired CFG_TUD_AUDIO_FORMAT_TYPE_I_TX encoding not implemented!\r\n"); - TU_BREAKPOINT(); - n_bytes_tx = 0; - break; - } - break; - - default: - // Desired CFG_TUD_AUDIO_FORMAT_TYPE_TX not implemented! - TU_LOG2(" Desired CFG_TUD_AUDIO_FORMAT_TYPE_TX not implemented!\r\n"); - TU_BREAKPOINT(); - n_bytes_tx = 0; - break; - } - - TU_VERIFY(usbd_edpt_xfer(rhport, audio->ep_in, audio->lin_buf_in, n_bytes_tx)); - -#else - // No support FIFOs, if no linear buffer required schedule transmit, else put data into linear buffer and schedule -#if CFG_TUD_AUDIO_EP_IN_FLOW_CONTROL - // packet_sz_tx is based on total packet size, here we want size for each support buffer. + #if CFG_TUD_AUDIO_EP_IN_FLOW_CONTROL + // packet_sz_tx is based on total packet size n_bytes_tx = audiod_tx_packet_size(audio->packet_sz_tx, tu_fifo_count(&audio->ep_in_ff), audio->ep_in_ff.depth, audio->ep_in_sz); -#else - n_bytes_tx = tu_min16(tu_fifo_count(&audio->ep_in_ff), audio->ep_in_sz); // Limit up to max packet size, more can not be done for ISO -#endif -#if USE_LINEAR_BUFFER_TX + #else + n_bytes_tx = tu_min16(tu_fifo_count(&audio->ep_in_ff), audio->ep_in_sz);// Limit up to max packet size, more can not be done for ISO + #endif + #if USE_LINEAR_BUFFER_TX tu_fifo_read_n(&audio->ep_in_ff, audio->lin_buf_in, n_bytes_tx); TU_VERIFY(usbd_edpt_xfer(rhport, audio->ep_in, audio->lin_buf_in, n_bytes_tx)); -#else + #else // Send everything in ISO EP FIFO TU_VERIFY(usbd_edpt_xfer_fifo(rhport, audio->ep_in, &audio->ep_in_ff, n_bytes_tx)); -#endif - -#endif + #endif // Call a weak callback here - a possibility for user to get informed former TX was completed and how many bytes were loaded for the next frame TU_VERIFY(tud_audio_tx_done_post_load_cb(rhport, n_bytes_tx, idx_audio_fct, audio->ep_in, audio->alt_setting[idxItf])); @@ -1064,173 +679,46 @@ static bool audiod_tx_done_cb(uint8_t rhport, audiod_function_t * audio) return true; } -#endif //CFG_TUD_AUDIO_ENABLE_EP_IN - -#if CFG_TUD_AUDIO_ENABLE_ENCODING && CFG_TUD_AUDIO_ENABLE_EP_IN -// Take samples from the support buffer and encode them into the IN EP software FIFO -// Returns number of bytes written into linear buffer - -/* 2.3.1.7.1 PCM Format -The PCM (Pulse Coded Modulation) format is the most commonly used audio format to represent audio -data streams. The audio data is not compressed and uses a signed two’s-complement fixed point format. It -is left-justified (the sign bit is the Msb) and data is padded with trailing zeros to fill the remaining unused -bits of the subslot. The binary point is located to the right of the sign bit so that all values lie within the -range [-1, +1) - */ - -/* - * This function encodes channels saved within the support FIFOs into one stream by interleaving the PCM samples - * in the support FIFOs according to 2.3.1.5 Audio Streams. It does not control justification (left or right) and - * does not change the number of bytes per sample. - * */ - -// Helper function -static inline void * audiod_interleaved_copy_bytes_fast_encode(uint16_t const nBytesPerSample, void * src, const void * src_end, void * dst, uint8_t const n_ff_used) -{ - // Due to one FIFO contains 2 channels, data always aligned to (nBytesPerSample * 2) - uint16_t * dst16 = dst; - uint16_t * src16 = src; - const uint16_t * src_end16 = src_end; - uint32_t * dst32 = dst; - uint32_t * src32 = src; - const uint32_t * src_end32 = src_end; - - if (nBytesPerSample == 1) - { - while(src16 < src_end16) - { - *dst16++ = *src16++; - dst16 += n_ff_used - 1; - } - return dst16; - } - else if (nBytesPerSample == 2) - { - while(src32 < src_end32) - { - *dst32++ = *src32++; - dst32 += n_ff_used - 1; - } - return dst32; - } - else if (nBytesPerSample == 3) - { - while(src16 < src_end16) - { - *dst16++ = *src16++; - *dst16++ = *src16++; - *dst16++ = *src16++; - dst16 += 3 * (n_ff_used - 1); - } - return dst16; - } - else // nBytesPerSample == 4 - { - while(src32 < src_end32) - { - *dst32++ = *src32++; - *dst32++ = *src32++; - dst32 += 2 * (n_ff_used - 1); - } - return dst32; - } -} - -static uint16_t audiod_encode_type_I_pcm(uint8_t rhport, audiod_function_t* audio) -{ - // This function relies on the fact that the length of the support FIFOs was configured to be a multiple of the active sample size in bytes s.t. no sample is split within a wrap - // This is ensured within set_interface, where the FIFOs are reconfigured according to this size - - // We encode directly into IN EP's linear buffer - abort if previous transfer not complete - TU_VERIFY(!usbd_edpt_busy(rhport, audio->ep_in)); - - // Determine amount of samples - uint8_t const n_ff_used = audio->n_ff_used_tx; - uint16_t nBytesPerFFToSend = tu_fifo_count(&audio->tx_supp_ff[0]); - uint8_t cnt_ff; - - for (cnt_ff = 1; cnt_ff < n_ff_used; cnt_ff++) - { - uint16_t const count = tu_fifo_count(&audio->tx_supp_ff[cnt_ff]); - if (count < nBytesPerFFToSend) - { - nBytesPerFFToSend = count; - } - } - -#if CFG_TUD_AUDIO_EP_IN_FLOW_CONTROL - const uint16_t norm_packet_sz_tx[3] = {audio->packet_sz_tx[0] / n_ff_used, - audio->packet_sz_tx[1] / n_ff_used, - audio->packet_sz_tx[2] / n_ff_used}; - // packet_sz_tx is based on total packet size, here we want size for each support buffer. - nBytesPerFFToSend = audiod_tx_packet_size(norm_packet_sz_tx, nBytesPerFFToSend, audio->tx_supp_ff[0].depth, audio->ep_in_sz / n_ff_used); - // Check if there is enough data - if (nBytesPerFFToSend == 0) return 0; -#else - // Check if there is enough data - if (nBytesPerFFToSend == 0) return 0; - // Limit to maximum sample number - THIS IS A POSSIBLE ERROR SOURCE IF TOO MANY SAMPLE WOULD NEED TO BE SENT BUT CAN NOT! - nBytesPerFFToSend = tu_min16(nBytesPerFFToSend, audio->ep_in_sz / n_ff_used); - // Round to full number of samples (flooring) - uint16_t const nSlotSize = audio->n_channels_per_ff_tx * audio->n_bytes_per_sample_tx; - nBytesPerFFToSend = (nBytesPerFFToSend / nSlotSize) * nSlotSize; #endif - // Encode - uint8_t * dst; - uint8_t * src_end; +#if CFG_TUD_AUDIO_ENABLE_INTERRUPT_EP +// If no interrupt transmit is pending bytes get written into buffer and a transmit is scheduled - once transmit completed tud_audio_int_done_cb() is called in inform user +bool tud_audio_int_n_write(uint8_t func_id, const audio_interrupt_data_t *data) { + TU_VERIFY(func_id < CFG_TUD_AUDIO && _audiod_fct[func_id].p_desc != NULL); - tu_fifo_buffer_info_t info; + TU_VERIFY(_audiod_fct[func_id].ep_int != 0); - for (cnt_ff = 0; cnt_ff < n_ff_used; cnt_ff++) - { - dst = &audio->lin_buf_in[cnt_ff*audio->n_channels_per_ff_tx*audio->n_bytes_per_sample_tx]; + // We write directly into the EP's buffer - abort if previous transfer not complete + TU_VERIFY(usbd_edpt_claim(_audiod_fct[func_id].rhport, _audiod_fct[func_id].ep_int)); - tu_fifo_get_read_info(&audio->tx_supp_ff[cnt_ff], &info); - - if (info.len_lin != 0) - { - info.len_lin = tu_min16(nBytesPerFFToSend, info.len_lin); // Limit up to desired length - src_end = (uint8_t *)info.ptr_lin + info.len_lin; - dst = audiod_interleaved_copy_bytes_fast_encode(audio->n_bytes_per_sample_tx, info.ptr_lin, src_end, dst, n_ff_used); - - // Limit up to desired length - info.len_wrap = tu_min16(nBytesPerFFToSend - info.len_lin, info.len_wrap); - - // Handle wrapped part of FIFO - if (info.len_wrap != 0) - { - src_end = (uint8_t *)info.ptr_wrap + info.len_wrap; - audiod_interleaved_copy_bytes_fast_encode(audio->n_bytes_per_sample_tx, info.ptr_wrap, src_end, dst, n_ff_used); - } - - tu_fifo_advance_read_pointer(&audio->tx_supp_ff[cnt_ff], info.len_lin + info.len_wrap); - } + // Check length + if (tu_memcpy_s(int_ep_buf[func_id].buf, sizeof(int_ep_buf[func_id].buf), data, sizeof(audio_interrupt_data_t)) == 0) { + // Schedule transmit + TU_ASSERT(usbd_edpt_xfer(_audiod_fct[func_id].rhport, _audiod_fct[func_id].ep_int, int_ep_buf[func_id].buf, sizeof(int_ep_buf[func_id].buf)), 0); + } else { + // Release endpoint since we don't make any transfer + usbd_edpt_release(_audiod_fct[func_id].rhport, _audiod_fct[func_id].ep_int); } - return nBytesPerFFToSend * n_ff_used; + return true; } -#endif //CFG_TUD_AUDIO_ENABLE_ENCODING - -// This function is called once a transmit of a feedback packet was successfully completed. Here, we get the next feedback value to be sent +#endif #if CFG_TUD_AUDIO_ENABLE_EP_OUT && CFG_TUD_AUDIO_ENABLE_FEEDBACK_EP -static inline bool audiod_fb_send(audiod_function_t *audio) -{ +// This function is called once a transmit of a feedback packet was successfully completed. Here, we get the next feedback value to be sent +static inline bool audiod_fb_send(audiod_function_t *audio) { bool apply_correction = (TUSB_SPEED_FULL == tud_speed_get()) && audio->feedback.format_correction; // Format the feedback value - if (apply_correction) - { - uint8_t * fb = (uint8_t *) &audio->feedback.send_buf; + if (apply_correction) { + uint8_t *fb = (uint8_t *) audio->fb_buf; // For FS format is 10.14 *(fb++) = (audio->feedback.value >> 2) & 0xFF; *(fb++) = (audio->feedback.value >> 10) & 0xFF; *(fb++) = (audio->feedback.value >> 18) & 0xFF; *fb = 0; - } else - { - audio->feedback.send_buf = audio->feedback.value; + } else { + *audio->fb_buf = audio->feedback.value; } // About feedback format on FS @@ -1246,45 +734,41 @@ static inline bool audiod_fb_send(audiod_function_t *audio) // 10.14 3 3 Linux, OSX // // We send 3 bytes since sending packet larger than wMaxPacketSize is pretty ugly - return usbd_edpt_xfer(audio->rhport, audio->ep_fb, (uint8_t *) &audio->feedback.send_buf, apply_correction ? 3 : 4); + return usbd_edpt_xfer(audio->rhport, audio->ep_fb, (uint8_t *) audio->fb_buf, apply_correction ? 3 : 4); } #endif //--------------------------------------------------------------------+ // USBD Driver API //--------------------------------------------------------------------+ -void audiod_init(void) -{ +void audiod_init(void) { tu_memclr(_audiod_fct, sizeof(_audiod_fct)); - for(uint8_t i=0; ictrl_buf = ctrl_buf_1; + audio->ctrl_buf = ctrl_buf.buf1; audio->ctrl_buf_sz = CFG_TUD_AUDIO_FUNC_1_CTRL_BUF_SZ; break; #if CFG_TUD_AUDIO > 1 && CFG_TUD_AUDIO_FUNC_2_CTRL_BUF_SZ > 0 case 1: - audio->ctrl_buf = ctrl_buf_2; + audio->ctrl_buf = ctrl_buf.buf2; audio->ctrl_buf_sz = CFG_TUD_AUDIO_FUNC_2_CTRL_BUF_SZ; break; #endif #if CFG_TUD_AUDIO > 2 && CFG_TUD_AUDIO_FUNC_3_CTRL_BUF_SZ > 0 case 2: - audio->ctrl_buf = ctrl_buf_3; + audio->ctrl_buf = ctrl_buf.buf3; audio->ctrl_buf_sz = CFG_TUD_AUDIO_FUNC_3_CTRL_BUF_SZ; break; #endif } // Initialize active alternate interface buffers - switch (i) - { + switch (i) { #if CFG_TUD_AUDIO_FUNC_1_N_AS_INT > 0 case 0: audio->alt_setting = alt_setting_1; @@ -1302,321 +786,165 @@ void audiod_init(void) #endif } - // Initialize IN EP FIFO if required -#if CFG_TUD_AUDIO_ENABLE_EP_IN && !CFG_TUD_AUDIO_ENABLE_ENCODING + // Initialize IN EP FIFO if required +#if CFG_TUD_AUDIO_ENABLE_EP_IN - switch (i) - { -#if CFG_TUD_AUDIO_FUNC_1_EP_IN_SW_BUF_SZ > 0 + switch (i) { + #if CFG_TUD_AUDIO_FUNC_1_EP_IN_SW_BUF_SZ > 0 case 0: - tu_fifo_config(&audio->ep_in_ff, audio_ep_in_sw_buf_1, CFG_TUD_AUDIO_FUNC_1_EP_IN_SW_BUF_SZ, 1, true); -#if CFG_FIFO_MUTEX + tu_fifo_config(&audio->ep_in_ff, ep_in_sw_buf.buf_1, CFG_TUD_AUDIO_FUNC_1_EP_IN_SW_BUF_SZ, 1, true); + #if CFG_FIFO_MUTEX tu_fifo_config_mutex(&audio->ep_in_ff, osal_mutex_create(&ep_in_ff_mutex_wr_1), NULL); -#endif + #endif break; -#endif -#if CFG_TUD_AUDIO > 1 && CFG_TUD_AUDIO_FUNC_2_EP_IN_SW_BUF_SZ > 0 + #endif + #if CFG_TUD_AUDIO > 1 && CFG_TUD_AUDIO_FUNC_2_EP_IN_SW_BUF_SZ > 0 case 1: - tu_fifo_config(&audio->ep_in_ff, audio_ep_in_sw_buf_2, CFG_TUD_AUDIO_FUNC_2_EP_IN_SW_BUF_SZ, 1, true); -#if CFG_FIFO_MUTEX + tu_fifo_config(&audio->ep_in_ff, ep_in_sw_buf.buf_2, CFG_TUD_AUDIO_FUNC_2_EP_IN_SW_BUF_SZ, 1, true); + #if CFG_FIFO_MUTEX tu_fifo_config_mutex(&audio->ep_in_ff, osal_mutex_create(&ep_in_ff_mutex_wr_2), NULL); -#endif + #endif break; -#endif -#if CFG_TUD_AUDIO > 2 && CFG_TUD_AUDIO_FUNC_3_EP_IN_SW_BUF_SZ > 0 + #endif + #if CFG_TUD_AUDIO > 2 && CFG_TUD_AUDIO_FUNC_3_EP_IN_SW_BUF_SZ > 0 case 2: - tu_fifo_config(&audio->ep_in_ff, audio_ep_in_sw_buf_3, CFG_TUD_AUDIO_FUNC_3_EP_IN_SW_BUF_SZ, 1, true); -#if CFG_FIFO_MUTEX + tu_fifo_config(&audio->ep_in_ff, ep_in_sw_buf.buf_3, CFG_TUD_AUDIO_FUNC_3_EP_IN_SW_BUF_SZ, 1, true); + #if CFG_FIFO_MUTEX tu_fifo_config_mutex(&audio->ep_in_ff, osal_mutex_create(&ep_in_ff_mutex_wr_3), NULL); -#endif + #endif break; -#endif + #endif } -#endif // CFG_TUD_AUDIO_ENABLE_EP_IN && !CFG_TUD_AUDIO_ENABLE_ENCODING +#endif// CFG_TUD_AUDIO_ENABLE_EP_IN - // Initialize linear buffers + // Initialize linear buffers #if USE_LINEAR_BUFFER_TX - switch (i) - { -#if CFG_TUD_AUDIO_FUNC_1_EP_IN_SZ_MAX > 0 + switch (i) { + #if CFG_TUD_AUDIO_FUNC_1_EP_IN_SZ_MAX > 0 case 0: - audio->lin_buf_in = lin_buf_in_1; + audio->lin_buf_in = lin_buf_in.buf_1; break; -#endif -#if CFG_TUD_AUDIO > 1 && CFG_TUD_AUDIO_FUNC_2_EP_IN_SZ_MAX > 0 + #endif + #if CFG_TUD_AUDIO > 1 && CFG_TUD_AUDIO_FUNC_2_EP_IN_SZ_MAX > 0 case 1: - audio->lin_buf_in = lin_buf_in_2; + audio->lin_buf_in = lin_buf_in.buf_2; break; -#endif -#if CFG_TUD_AUDIO > 2 && CFG_TUD_AUDIO_FUNC_3_EP_IN_SZ_MAX > 0 + #endif + #if CFG_TUD_AUDIO > 2 && CFG_TUD_AUDIO_FUNC_3_EP_IN_SZ_MAX > 0 case 2: - audio->lin_buf_in = lin_buf_in_3; + audio->lin_buf_in = lin_buf_in.buf_3; break; -#endif + #endif } -#endif // USE_LINEAR_BUFFER_TX +#endif// USE_LINEAR_BUFFER_TX - // Initialize OUT EP FIFO if required -#if CFG_TUD_AUDIO_ENABLE_EP_OUT && !CFG_TUD_AUDIO_ENABLE_DECODING + // Initialize OUT EP FIFO if required +#if CFG_TUD_AUDIO_ENABLE_EP_OUT - switch (i) - { -#if CFG_TUD_AUDIO_FUNC_1_EP_OUT_SW_BUF_SZ > 0 + switch (i) { + #if CFG_TUD_AUDIO_FUNC_1_EP_OUT_SW_BUF_SZ > 0 case 0: - tu_fifo_config(&audio->ep_out_ff, audio_ep_out_sw_buf_1, CFG_TUD_AUDIO_FUNC_1_EP_OUT_SW_BUF_SZ, 1, true); -#if CFG_FIFO_MUTEX + tu_fifo_config(&audio->ep_out_ff, ep_out_sw_buf.buf_1, CFG_TUD_AUDIO_FUNC_1_EP_OUT_SW_BUF_SZ, 1, true); + #if CFG_FIFO_MUTEX tu_fifo_config_mutex(&audio->ep_out_ff, NULL, osal_mutex_create(&ep_out_ff_mutex_rd_1)); -#endif + #endif break; -#endif -#if CFG_TUD_AUDIO > 1 && CFG_TUD_AUDIO_FUNC_2_EP_OUT_SW_BUF_SZ > 0 + #endif + #if CFG_TUD_AUDIO > 1 && CFG_TUD_AUDIO_FUNC_2_EP_OUT_SW_BUF_SZ > 0 case 1: - tu_fifo_config(&audio->ep_out_ff, audio_ep_out_sw_buf_2, CFG_TUD_AUDIO_FUNC_2_EP_OUT_SW_BUF_SZ, 1, true); -#if CFG_FIFO_MUTEX + tu_fifo_config(&audio->ep_out_ff, ep_out_sw_buf.buf_2, CFG_TUD_AUDIO_FUNC_2_EP_OUT_SW_BUF_SZ, 1, true); + #if CFG_FIFO_MUTEX tu_fifo_config_mutex(&audio->ep_out_ff, NULL, osal_mutex_create(&ep_out_ff_mutex_rd_2)); -#endif + #endif break; -#endif -#if CFG_TUD_AUDIO > 2 && CFG_TUD_AUDIO_FUNC_3_EP_OUT_SW_BUF_SZ > 0 + #endif + #if CFG_TUD_AUDIO > 2 && CFG_TUD_AUDIO_FUNC_3_EP_OUT_SW_BUF_SZ > 0 case 2: - tu_fifo_config(&audio->ep_out_ff, audio_ep_out_sw_buf_3, CFG_TUD_AUDIO_FUNC_3_EP_OUT_SW_BUF_SZ, 1, true); -#if CFG_FIFO_MUTEX + tu_fifo_config(&audio->ep_out_ff, ep_out_sw_buf.buf_3, CFG_TUD_AUDIO_FUNC_3_EP_OUT_SW_BUF_SZ, 1, true); + #if CFG_FIFO_MUTEX tu_fifo_config_mutex(&audio->ep_out_ff, NULL, osal_mutex_create(&ep_out_ff_mutex_rd_3)); -#endif + #endif break; -#endif + #endif } -#endif // CFG_TUD_AUDIO_ENABLE_EP_OUT && !CFG_TUD_AUDIO_ENABLE_DECODING +#endif// CFG_TUD_AUDIO_ENABLE_EP_OUT - // Initialize linear buffers + // Initialize linear buffers #if USE_LINEAR_BUFFER_RX - switch (i) - { -#if CFG_TUD_AUDIO_FUNC_1_EP_OUT_SZ_MAX > 0 + switch (i) { + #if CFG_TUD_AUDIO_FUNC_1_EP_OUT_SZ_MAX > 0 case 0: - audio->lin_buf_out = lin_buf_out_1; + audio->lin_buf_out = lin_buf_out.buf_1; break; -#endif -#if CFG_TUD_AUDIO > 1 && CFG_TUD_AUDIO_FUNC_2_EP_OUT_SZ_MAX > 0 + #endif + #if CFG_TUD_AUDIO > 1 && CFG_TUD_AUDIO_FUNC_2_EP_OUT_SZ_MAX > 0 case 1: - audio->lin_buf_out = lin_buf_out_2; + audio->lin_buf_out = lin_buf_out.buf_2; break; -#endif -#if CFG_TUD_AUDIO > 2 && CFG_TUD_AUDIO_FUNC_3_EP_OUT_SZ_MAX > 0 + #endif + #if CFG_TUD_AUDIO > 2 && CFG_TUD_AUDIO_FUNC_3_EP_OUT_SZ_MAX > 0 case 2: - audio->lin_buf_out = lin_buf_out_3; + audio->lin_buf_out = lin_buf_out.buf_3; break; -#endif + #endif } -#endif // USE_LINEAR_BUFFER_TX +#endif// USE_LINEAR_BUFFER_RX - // Initialize TX support FIFOs if required -#if CFG_TUD_AUDIO_ENABLE_EP_IN && CFG_TUD_AUDIO_ENABLE_ENCODING - - switch (i) - { -#if CFG_TUD_AUDIO_FUNC_1_TX_SUPP_SW_FIFO_SZ > 0 +#if CFG_TUD_AUDIO_ENABLE_FEEDBACK_EP + switch (i) { + #if CFG_TUD_AUDIO_FUNC_1_EP_OUT_SZ_MAX > 0 case 0: - audio->tx_supp_ff = tx_supp_ff_1; - audio->n_tx_supp_ff = CFG_TUD_AUDIO_FUNC_1_N_TX_SUPP_SW_FIFO; - audio->tx_supp_ff_sz_max = CFG_TUD_AUDIO_FUNC_1_TX_SUPP_SW_FIFO_SZ; - for (uint8_t cnt = 0; cnt < CFG_TUD_AUDIO_FUNC_1_N_TX_SUPP_SW_FIFO; cnt++) - { - tu_fifo_config(&tx_supp_ff_1[cnt], tx_supp_ff_buf_1[cnt], CFG_TUD_AUDIO_FUNC_1_TX_SUPP_SW_FIFO_SZ, 1, true); -#if CFG_FIFO_MUTEX - tu_fifo_config_mutex(&tx_supp_ff_1[cnt], osal_mutex_create(&tx_supp_ff_mutex_wr_1[cnt]), NULL); -#endif - } - + audio->fb_buf = &fb_ep_buf.buf_1; break; -#endif // CFG_TUD_AUDIO_FUNC_1_TX_SUPP_SW_FIFO_SZ > 0 - -#if CFG_TUD_AUDIO > 1 && CFG_TUD_AUDIO_FUNC_2_TX_SUPP_SW_FIFO_SZ > 0 + #endif + #if CFG_TUD_AUDIO > 1 && CFG_TUD_AUDIO_FUNC_2_EP_OUT_SZ_MAX > 0 case 1: - audio->tx_supp_ff = tx_supp_ff_2; - audio->n_tx_supp_ff = CFG_TUD_AUDIO_FUNC_2_N_TX_SUPP_SW_FIFO; - audio->tx_supp_ff_sz_max = CFG_TUD_AUDIO_FUNC_2_TX_SUPP_SW_FIFO_SZ; - for (uint8_t cnt = 0; cnt < CFG_TUD_AUDIO_FUNC_2_N_TX_SUPP_SW_FIFO; cnt++) - { - tu_fifo_config(&tx_supp_ff_2[cnt], tx_supp_ff_buf_2[cnt], CFG_TUD_AUDIO_FUNC_2_TX_SUPP_SW_FIFO_SZ, 1, true); -#if CFG_FIFO_MUTEX - tu_fifo_config_mutex(&tx_supp_ff_2[cnt], osal_mutex_create(&tx_supp_ff_mutex_wr_2[cnt]), NULL); -#endif - } - + audio->fb_buf = &fb_ep_buf.buf_2; break; -#endif // CFG_TUD_AUDIO > 1 && CFG_TUD_AUDIO_FUNC_2_TX_SUPP_SW_FIFO_SZ > 0 - -#if CFG_TUD_AUDIO > 2 && CFG_TUD_AUDIO_FUNC_3_TX_SUPP_SW_FIFO_SZ > 0 + #endif + #if CFG_TUD_AUDIO > 2 && CFG_TUD_AUDIO_FUNC_3_EP_OUT_SZ_MAX > 0 case 2: - audio->tx_supp_ff = tx_supp_ff_3; - audio->n_tx_supp_ff = CFG_TUD_AUDIO_FUNC_3_N_TX_SUPP_SW_FIFO; - audio->tx_supp_ff_sz_max = CFG_TUD_AUDIO_FUNC_3_TX_SUPP_SW_FIFO_SZ; - for (uint8_t cnt = 0; cnt < CFG_TUD_AUDIO_FUNC_3_N_TX_SUPP_SW_FIFO; cnt++) - { - tu_fifo_config(&tx_supp_ff_3[cnt], tx_supp_ff_buf_3[cnt], CFG_TUD_AUDIO_FUNC_3_TX_SUPP_SW_FIFO_SZ, 1, true); -#if CFG_FIFO_MUTEX - tu_fifo_config_mutex(&tx_supp_ff_3[cnt], osal_mutex_create(&tx_supp_ff_mutex_wr_3[cnt]), NULL); -#endif - } - + audio->fb_buf = &fb_ep_buf.buf_3; break; -#endif // CFG_TUD_AUDIO > 1 && CFG_TUD_AUDIO_FUNC_2_TX_SUPP_SW_FIFO_SZ > 0 + #endif } -#endif // CFG_TUD_AUDIO_ENABLE_EP_IN && CFG_TUD_AUDIO_ENABLE_ENCODING - - // Set encoding parameters for Type_I formats -#if CFG_TUD_AUDIO_ENABLE_EP_IN && CFG_TUD_AUDIO_ENABLE_TYPE_I_ENCODING - switch (i) - { -#if CFG_TUD_AUDIO_FUNC_1_TX_SUPP_SW_FIFO_SZ > 0 - case 0: - audio->n_channels_per_ff_tx = CFG_TUD_AUDIO_FUNC_1_CHANNEL_PER_FIFO_TX; - break; -#endif -#if CFG_TUD_AUDIO > 1 && CFG_TUD_AUDIO_FUNC_2_TX_SUPP_SW_FIFO_SZ > 0 - case 1: - audio->n_channels_per_ff_tx = CFG_TUD_AUDIO_FUNC_2_CHANNEL_PER_FIFO_TX; - break; -#endif -#if CFG_TUD_AUDIO > 2 && CFG_TUD_AUDIO_FUNC_3_TX_SUPP_SW_FIFO_SZ > 0 - case 2: - audio->n_channels_per_ff_tx = CFG_TUD_AUDIO_FUNC_3_CHANNEL_PER_FIFO_TX; - break; -#endif - } -#endif // CFG_TUD_AUDIO_ENABLE_TYPE_I_ENCODING - - // Initialize RX support FIFOs if required -#if CFG_TUD_AUDIO_ENABLE_EP_OUT && CFG_TUD_AUDIO_ENABLE_DECODING - - switch (i) - { -#if CFG_TUD_AUDIO_FUNC_1_RX_SUPP_SW_FIFO_SZ > 0 - case 0: - audio->rx_supp_ff = rx_supp_ff_1; - audio->n_rx_supp_ff = CFG_TUD_AUDIO_FUNC_1_N_RX_SUPP_SW_FIFO; - audio->rx_supp_ff_sz_max = CFG_TUD_AUDIO_FUNC_1_RX_SUPP_SW_FIFO_SZ; - for (uint8_t cnt = 0; cnt < CFG_TUD_AUDIO_FUNC_1_N_RX_SUPP_SW_FIFO; cnt++) - { - tu_fifo_config(&rx_supp_ff_1[cnt], rx_supp_ff_buf_1[cnt], CFG_TUD_AUDIO_FUNC_1_RX_SUPP_SW_FIFO_SZ, 1, true); -#if CFG_FIFO_MUTEX - tu_fifo_config_mutex(&rx_supp_ff_1[cnt], osal_mutex_create(&rx_supp_ff_mutex_rd_1[cnt]), NULL); -#endif - } - - break; -#endif // CFG_TUD_AUDIO_FUNC_1_RX_SUPP_SW_FIFO_SZ > 0 - -#if CFG_TUD_AUDIO > 1 && CFG_TUD_AUDIO_FUNC_2_RX_SUPP_SW_FIFO_SZ > 0 - case 1: - audio->rx_supp_ff = rx_supp_ff_2; - audio->n_rx_supp_ff = CFG_TUD_AUDIO_FUNC_2_N_RX_SUPP_SW_FIFO; - audio->rx_supp_ff_sz_max = CFG_TUD_AUDIO_FUNC_2_RX_SUPP_SW_FIFO_SZ; - for (uint8_t cnt = 0; cnt < CFG_TUD_AUDIO_FUNC_2_N_RX_SUPP_SW_FIFO; cnt++) - { - tu_fifo_config(&rx_supp_ff_2[cnt], rx_supp_ff_buf_2[cnt], CFG_TUD_AUDIO_FUNC_2_RX_SUPP_SW_FIFO_SZ, 1, true); -#if CFG_FIFO_MUTEX - tu_fifo_config_mutex(&rx_supp_ff_2[cnt], osal_mutex_create(&rx_supp_ff_mutex_rd_2[cnt]), NULL); -#endif - } - - break; -#endif // CFG_TUD_AUDIO > 1 && CFG_TUD_AUDIO_FUNC_2_RX_SUPP_SW_FIFO_SZ > 0 - -#if CFG_TUD_AUDIO > 2 && CFG_TUD_AUDIO_FUNC_3_RX_SUPP_SW_FIFO_SZ > 0 - case 2: - audio->rx_supp_ff = rx_supp_ff_3; - audio->n_rx_supp_ff = CFG_TUD_AUDIO_FUNC_3_N_RX_SUPP_SW_FIFO; - audio->rx_supp_ff_sz_max = CFG_TUD_AUDIO_FUNC_3_RX_SUPP_SW_FIFO_SZ; - for (uint8_t cnt = 0; cnt < CFG_TUD_AUDIO_FUNC_3_N_RX_SUPP_SW_FIFO; cnt++) - { - tu_fifo_config(&rx_supp_ff_3[cnt], rx_supp_ff_buf_3[cnt], CFG_TUD_AUDIO_FUNC_3_RX_SUPP_SW_FIFO_SZ, 1, true); -#if CFG_FIFO_MUTEX - tu_fifo_config_mutex(&rx_supp_ff_3[cnt], osal_mutex_create(&rx_supp_ff_mutex_rd_3[cnt]), NULL); -#endif - } - - break; -#endif // CFG_TUD_AUDIO > 1 && CFG_TUD_AUDIO_FUNC_2_RX_SUPP_SW_FIFO_SZ > 0 - } -#endif // CFG_TUD_AUDIO_ENABLE_EP_IN && CFG_TUD_AUDIO_ENABLE_ENCODING - - // Set encoding parameters for Type_I formats -#if CFG_TUD_AUDIO_ENABLE_TYPE_I_DECODING - switch (i) - { -#if CFG_TUD_AUDIO_FUNC_1_RX_SUPP_SW_FIFO_SZ > 0 - case 0: - audio->n_channels_per_ff_rx = CFG_TUD_AUDIO_FUNC_1_CHANNEL_PER_FIFO_RX; - break; -#endif -#if CFG_TUD_AUDIO > 1 && CFG_TUD_AUDIO_FUNC_2_RX_SUPP_SW_FIFO_SZ > 0 - case 1: - audio->n_channels_per_ff_rx = CFG_TUD_AUDIO_FUNC_2_CHANNEL_PER_FIFO_RX; - break; -#endif -#if CFG_TUD_AUDIO > 2 && CFG_TUD_AUDIO_FUNC_3_RX_SUPP_SW_FIFO_SZ > 0 - case 2: - audio->n_channels_per_ff_rx = CFG_TUD_AUDIO_FUNC_3_CHANNEL_PER_FIFO_RX; - break; -#endif - } -#endif // CFG_TUD_AUDIO_ENABLE_TYPE_I_DECODING +#endif// CFG_TUD_AUDIO_ENABLE_FEEDBACK_EP } } bool audiod_deinit(void) { - return false; // TODO not implemented yet + return false;// TODO not implemented yet } -void audiod_reset(uint8_t rhport) -{ +void audiod_reset(uint8_t rhport) { (void) rhport; - for(uint8_t i=0; iep_in_ff); #endif -#if CFG_TUD_AUDIO_ENABLE_EP_OUT && !CFG_TUD_AUDIO_ENABLE_DECODING +#if CFG_TUD_AUDIO_ENABLE_EP_OUT tu_fifo_clear(&audio->ep_out_ff); #endif - -#if CFG_TUD_AUDIO_ENABLE_EP_IN && CFG_TUD_AUDIO_ENABLE_ENCODING - for (uint8_t cnt = 0; cnt < audio->n_tx_supp_ff; cnt++) - { - tu_fifo_clear(&audio->tx_supp_ff[cnt]); - } -#endif - -#if CFG_TUD_AUDIO_ENABLE_EP_OUT && CFG_TUD_AUDIO_ENABLE_DECODING - for (uint8_t cnt = 0; cnt < audio->n_rx_supp_ff; cnt++) - { - tu_fifo_clear(&audio->rx_supp_ff[cnt]); - } -#endif } } -uint16_t audiod_open(uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t max_len) -{ +uint16_t audiod_open(uint8_t rhport, tusb_desc_interface_t const *itf_desc, uint16_t max_len) { (void) max_len; - TU_VERIFY ( TUSB_CLASS_AUDIO == itf_desc->bInterfaceClass && - AUDIO_SUBCLASS_CONTROL == itf_desc->bInterfaceSubClass); + TU_VERIFY(TUSB_CLASS_AUDIO == itf_desc->bInterfaceClass && + AUDIO_SUBCLASS_CONTROL == itf_desc->bInterfaceSubClass); // Verify version is correct - this check can be omitted TU_VERIFY(itf_desc->bInterfaceProtocol == AUDIO_INT_PROTOCOL_CODE_V2); // Verify interrupt control EP is enabled if demanded by descriptor - TU_ASSERT(itf_desc->bNumEndpoints <= 1); // 0 or 1 EPs are allowed - if (itf_desc->bNumEndpoints == 1) - { + TU_ASSERT(itf_desc->bNumEndpoints <= 1);// 0 or 1 EPs are allowed + if (itf_desc->bNumEndpoints == 1) { TU_ASSERT(CFG_TUD_AUDIO_ENABLE_INTERRUPT_EP); } @@ -1625,16 +953,13 @@ uint16_t audiod_open(uint8_t rhport, tusb_desc_interface_t const * itf_desc, uin // Find available audio driver interface uint8_t i; - for (i = 0; i < CFG_TUD_AUDIO; i++) - { - if (!_audiod_fct[i].p_desc) - { - _audiod_fct[i].p_desc = (uint8_t const *)itf_desc; // Save pointer to AC descriptor which is by specification always the first one + for (i = 0; i < CFG_TUD_AUDIO; i++) { + if (!_audiod_fct[i].p_desc) { + _audiod_fct[i].p_desc = (uint8_t const *) itf_desc;// Save pointer to AC descriptor which is by specification always the first one _audiod_fct[i].rhport = rhport; // Setup descriptor lengths - switch (i) - { + switch (i) { case 0: _audiod_fct[i].desc_length = CFG_TUD_AUDIO_FUNC_1_DESC_LEN; break; @@ -1653,12 +978,12 @@ uint16_t audiod_open(uint8_t rhport, tusb_desc_interface_t const * itf_desc, uin #ifdef TUP_DCD_EDPT_ISO_ALLOC { #if CFG_TUD_AUDIO_ENABLE_EP_IN - uint8_t ep_in = 0; + uint8_t ep_in = 0; uint16_t ep_in_size = 0; #endif #if CFG_TUD_AUDIO_ENABLE_EP_OUT - uint8_t ep_out = 0; + uint8_t ep_out = 0; uint16_t ep_out_size = 0; #endif @@ -1668,38 +993,32 @@ uint16_t audiod_open(uint8_t rhport, tusb_desc_interface_t const * itf_desc, uin uint8_t const *p_desc = _audiod_fct[i].p_desc; uint8_t const *p_desc_end = p_desc + _audiod_fct[i].desc_length - TUD_AUDIO_DESC_IAD_LEN; // Condition modified from p_desc < p_desc_end to prevent gcc>=12 strict-overflow warning - while (p_desc_end - p_desc > 0) - { - if (tu_desc_type(p_desc) == TUSB_DESC_ENDPOINT) - { + while (p_desc_end - p_desc > 0) { + if (tu_desc_type(p_desc) == TUSB_DESC_ENDPOINT) { tusb_desc_endpoint_t const *desc_ep = (tusb_desc_endpoint_t const *) p_desc; - if (desc_ep->bmAttributes.xfer == TUSB_XFER_ISOCHRONOUS) - { + if (desc_ep->bmAttributes.xfer == TUSB_XFER_ISOCHRONOUS) { #if CFG_TUD_AUDIO_ENABLE_FEEDBACK_EP // Explicit feedback EP - if (desc_ep->bmAttributes.usage == 1) - { + if (desc_ep->bmAttributes.usage == 1) { ep_fb = desc_ep->bEndpointAddress; } #endif - // Data EP - if (desc_ep->bmAttributes.usage == 0) - { - if (tu_edpt_dir(desc_ep->bEndpointAddress) == TUSB_DIR_IN) - { #if CFG_TUD_AUDIO_ENABLE_EP_IN - ep_in = desc_ep->bEndpointAddress; - ep_in_size = TU_MAX(tu_edpt_packet_size(desc_ep), ep_in_size); - #endif - } else - { - #if CFG_TUD_AUDIO_ENABLE_EP_OUT - ep_out = desc_ep->bEndpointAddress; - ep_out_size = TU_MAX(tu_edpt_packet_size(desc_ep), ep_out_size); - #endif - } + // Data or data with implicit feedback IN EP + if (tu_edpt_dir(desc_ep->bEndpointAddress) == TUSB_DIR_IN + && (desc_ep->bmAttributes.usage == 0 || desc_ep->bmAttributes.usage == 2)) { + ep_in = desc_ep->bEndpointAddress; + ep_in_size = TU_MAX(tu_edpt_packet_size(desc_ep), ep_in_size); } - + #endif + #if CFG_TUD_AUDIO_ENABLE_EP_OUT + // Data OUT EP + if (tu_edpt_dir(desc_ep->bEndpointAddress) == TUSB_DIR_OUT + && desc_ep->bmAttributes.usage == 0) { + ep_out = desc_ep->bEndpointAddress; + ep_out_size = TU_MAX(tu_edpt_packet_size(desc_ep), ep_out_size); + } + #endif } } @@ -1707,76 +1026,62 @@ uint16_t audiod_open(uint8_t rhport, tusb_desc_interface_t const * itf_desc, uin } #if CFG_TUD_AUDIO_ENABLE_EP_IN - if (ep_in) - { + if (ep_in) { usbd_edpt_iso_alloc(rhport, ep_in, ep_in_size); } #endif #if CFG_TUD_AUDIO_ENABLE_EP_OUT - if (ep_out) - { + if (ep_out) { usbd_edpt_iso_alloc(rhport, ep_out, ep_out_size); } #endif #if CFG_TUD_AUDIO_ENABLE_FEEDBACK_EP - if (ep_fb) - { + if (ep_fb) { usbd_edpt_iso_alloc(rhport, ep_fb, 4); } #endif } -#endif // TUP_DCD_EDPT_ISO_ALLOC +#endif// TUP_DCD_EDPT_ISO_ALLOC #if CFG_TUD_AUDIO_ENABLE_EP_IN && CFG_TUD_AUDIO_EP_IN_FLOW_CONTROL { uint8_t const *p_desc = _audiod_fct[i].p_desc; uint8_t const *p_desc_end = p_desc + _audiod_fct[i].desc_length - TUD_AUDIO_DESC_IAD_LEN; // Condition modified from p_desc < p_desc_end to prevent gcc>=12 strict-overflow warning - while (p_desc_end - p_desc > 0) - { - if (tu_desc_type(p_desc) == TUSB_DESC_ENDPOINT) - { + while (p_desc_end - p_desc > 0) { + if (tu_desc_type(p_desc) == TUSB_DESC_ENDPOINT) { tusb_desc_endpoint_t const *desc_ep = (tusb_desc_endpoint_t const *) p_desc; - if (desc_ep->bmAttributes.xfer == TUSB_XFER_ISOCHRONOUS) - { - if (desc_ep->bmAttributes.usage == 0) - { - if (tu_edpt_dir(desc_ep->bEndpointAddress) == TUSB_DIR_IN) - { - _audiod_fct[i].interval_tx = desc_ep->bInterval; - } + if (desc_ep->bmAttributes.xfer == TUSB_XFER_ISOCHRONOUS) { + // For data or data with implicit feedback IN EP + if (tu_edpt_dir(desc_ep->bEndpointAddress) == TUSB_DIR_IN + && (desc_ep->bmAttributes.usage == 0 || desc_ep->bmAttributes.usage == 2)) { + _audiod_fct[i].interval_tx = desc_ep->bInterval; } } - } else - if (tu_desc_type(p_desc) == TUSB_DESC_CS_INTERFACE && tu_desc_subtype(p_desc) == AUDIO_CS_AC_INTERFACE_OUTPUT_TERMINAL) - { - if(tu_unaligned_read16(p_desc + 4) == AUDIO_TERM_TYPE_USB_STREAMING) - { - _audiod_fct[i].bclock_id_tx = p_desc[8]; + } else if (tu_desc_type(p_desc) == TUSB_DESC_CS_INTERFACE && tu_desc_subtype(p_desc) == AUDIO_CS_AC_INTERFACE_OUTPUT_TERMINAL) { + if (tu_unaligned_read16(p_desc + 4) == AUDIO_TERM_TYPE_USB_STREAMING) { + _audiod_fct[i].bclock_id_tx = p_desc[8]; } } p_desc = tu_desc_next(p_desc); } } -#endif // CFG_TUD_AUDIO_EP_IN_FLOW_CONTROL +#endif// CFG_TUD_AUDIO_EP_IN_FLOW_CONTROL #if CFG_TUD_AUDIO_ENABLE_INTERRUPT_EP { uint8_t const *p_desc = _audiod_fct[i].p_desc; uint8_t const *p_desc_end = p_desc + _audiod_fct[i].desc_length - TUD_AUDIO_DESC_IAD_LEN; // Condition modified from p_desc < p_desc_end to prevent gcc>=12 strict-overflow warning - while (p_desc_end - p_desc > 0) - { + while (p_desc_end - p_desc > 0) { // For each endpoint - if (tu_desc_type(p_desc) == TUSB_DESC_ENDPOINT) - { - tusb_desc_endpoint_t const* desc_ep = (tusb_desc_endpoint_t const *) p_desc; + if (tu_desc_type(p_desc) == TUSB_DESC_ENDPOINT) { + tusb_desc_endpoint_t const *desc_ep = (tusb_desc_endpoint_t const *) p_desc; uint8_t const ep_addr = desc_ep->bEndpointAddress; // If endpoint is input-direction and interrupt-type - if (tu_edpt_dir(ep_addr) == TUSB_DIR_IN && desc_ep->bmAttributes.xfer == TUSB_XFER_INTERRUPT) - { + if (tu_edpt_dir(ep_addr) == TUSB_DIR_IN && desc_ep->bmAttributes.xfer == TUSB_XFER_INTERRUPT) { // Store endpoint number and open endpoint _audiod_fct[i].ep_int = ep_addr; TU_ASSERT(usbd_edpt_open(_audiod_fct[i].rhport, desc_ep)); @@ -1793,16 +1098,15 @@ uint16_t audiod_open(uint8_t rhport, tusb_desc_interface_t const * itf_desc, uin } // Verify we found a free one - TU_ASSERT( i < CFG_TUD_AUDIO ); + TU_ASSERT(i < CFG_TUD_AUDIO); // This is all we need so far - the EPs are setup by a later set_interface request (as per UAC2 specification) - uint16_t drv_len = _audiod_fct[i].desc_length - TUD_AUDIO_DESC_IAD_LEN; // - TUD_AUDIO_DESC_IAD_LEN since tinyUSB already handles the IAD descriptor + uint16_t drv_len = _audiod_fct[i].desc_length - TUD_AUDIO_DESC_IAD_LEN;// - TUD_AUDIO_DESC_IAD_LEN since tinyUSB already handles the IAD descriptor return drv_len; } -static bool audiod_get_interface(uint8_t rhport, tusb_control_request_t const * p_request) -{ +static bool audiod_get_interface(uint8_t rhport, tusb_control_request_t const *p_request) { uint8_t const itf = tu_u16_low(p_request->wIndex); // Find index of audio streaming interface @@ -1810,16 +1114,14 @@ static bool audiod_get_interface(uint8_t rhport, tusb_control_request_t const * uint8_t const *dummy; TU_VERIFY(audiod_get_AS_interface_index_global(itf, &func_id, &idxItf, &dummy)); - _audiod_fct[func_id].ctrl_buf[0] = _audiod_fct[func_id].alt_setting[idxItf]; - TU_VERIFY(tud_control_xfer(rhport, p_request, _audiod_fct[func_id].ctrl_buf, 1)); + TU_VERIFY(tud_control_xfer(rhport, p_request, &_audiod_fct[func_id].alt_setting[idxItf], 1)); TU_LOG2(" Get itf: %u - current alt: %u\r\n", itf, _audiod_fct[func_id].alt_setting[idxItf]); return true; } -static bool audiod_set_interface(uint8_t rhport, tusb_control_request_t const * p_request) -{ +static bool audiod_set_interface(uint8_t rhport, tusb_control_request_t const *p_request) { (void) rhport; // Here we need to do the following: @@ -1843,31 +1145,23 @@ static bool audiod_set_interface(uint8_t rhport, tusb_control_request_t const * uint8_t const *p_desc; TU_VERIFY(audiod_get_AS_interface_index_global(itf, &func_id, &idxItf, &p_desc)); - audiod_function_t* audio = &_audiod_fct[func_id]; + audiod_function_t *audio = &_audiod_fct[func_id]; - // Look if there is an EP to be closed - for this driver, there are only 3 possible EPs which may be closed (only AS related EPs can be closed, AC EP (if present) is always open) +// Look if there is an EP to be closed - for this driver, there are only 3 possible EPs which may be closed (only AS related EPs can be closed, AC EP (if present) is always open) #if CFG_TUD_AUDIO_ENABLE_EP_IN - if (audio->ep_in_as_intf_num == itf) - { + if (audio->ep_in_as_intf_num == itf) { audio->ep_in_as_intf_num = 0; #ifndef TUP_DCD_EDPT_ISO_ALLOC usbd_edpt_close(rhport, audio->ep_in); #endif // Clear FIFOs, since data is no longer valid - #if !CFG_TUD_AUDIO_ENABLE_ENCODING tu_fifo_clear(&audio->ep_in_ff); - #else - for (uint8_t cnt = 0; cnt < audio->n_tx_supp_ff; cnt++) - { - tu_fifo_clear(&audio->tx_supp_ff[cnt]); - } - #endif // Invoke callback - can be used to stop data sampling TU_VERIFY(tud_audio_set_itf_close_EP_cb(rhport, p_request)); - audio->ep_in = 0; // Necessary? + audio->ep_in = 0;// Necessary? #if CFG_TUD_AUDIO_EP_IN_FLOW_CONTROL audio->packet_sz_tx[0] = 0; @@ -1875,30 +1169,22 @@ static bool audiod_set_interface(uint8_t rhport, tusb_control_request_t const * audio->packet_sz_tx[2] = 0; #endif } -#endif // CFG_TUD_AUDIO_ENABLE_EP_IN +#endif// CFG_TUD_AUDIO_ENABLE_EP_IN #if CFG_TUD_AUDIO_ENABLE_EP_OUT - if (audio->ep_out_as_intf_num == itf) - { + if (audio->ep_out_as_intf_num == itf) { audio->ep_out_as_intf_num = 0; #ifndef TUP_DCD_EDPT_ISO_ALLOC usbd_edpt_close(rhport, audio->ep_out); #endif // Clear FIFOs, since data is no longer valid - #if !CFG_TUD_AUDIO_ENABLE_DECODING tu_fifo_clear(&audio->ep_out_ff); - #else - for (uint8_t cnt = 0; cnt < audio->n_rx_supp_ff; cnt++) - { - tu_fifo_clear(&audio->rx_supp_ff[cnt]); - } - #endif // Invoke callback - can be used to stop data sampling TU_VERIFY(tud_audio_set_itf_close_EP_cb(rhport, p_request)); - audio->ep_out = 0; // Necessary? + audio->ep_out = 0;// Necessary? // Close corresponding feedback EP #if CFG_TUD_AUDIO_ENABLE_FEEDBACK_EP @@ -1909,7 +1195,7 @@ static bool audiod_set_interface(uint8_t rhport, tusb_control_request_t const * tu_memclr(&audio->feedback, sizeof(audio->feedback)); #endif } -#endif // CFG_TUD_AUDIO_ENABLE_EP_OUT +#endif// CFG_TUD_AUDIO_ENABLE_EP_OUT // Save current alternative interface setting audio->alt_setting[idxItf] = alt; @@ -1920,22 +1206,18 @@ static bool audiod_set_interface(uint8_t rhport, tusb_control_request_t const * // p_desc starts at required interface with alternate setting zero // Condition modified from p_desc < p_desc_end to prevent gcc>=12 strict-overflow warning - while (p_desc_end - p_desc > 0) - { + while (p_desc_end - p_desc > 0) { // Find correct interface - if (tu_desc_type(p_desc) == TUSB_DESC_INTERFACE && ((tusb_desc_interface_t const * )p_desc)->bInterfaceNumber == itf && ((tusb_desc_interface_t const * )p_desc)->bAlternateSetting == alt) - { -#if (CFG_TUD_AUDIO_ENABLE_EP_IN && (CFG_TUD_AUDIO_EP_IN_FLOW_CONTROL || CFG_TUD_AUDIO_ENABLE_ENCODING)) || (CFG_TUD_AUDIO_ENABLE_EP_OUT && CFG_TUD_AUDIO_ENABLE_DECODING) - uint8_t const * p_desc_parse_for_params = p_desc; + if (tu_desc_type(p_desc) == TUSB_DESC_INTERFACE && ((tusb_desc_interface_t const *) p_desc)->bInterfaceNumber == itf && ((tusb_desc_interface_t const *) p_desc)->bAlternateSetting == alt) { +#if CFG_TUD_AUDIO_ENABLE_EP_IN && CFG_TUD_AUDIO_EP_IN_FLOW_CONTROL + uint8_t const *p_desc_parse_for_params = p_desc; #endif // From this point forward follow the EP descriptors associated to the current alternate setting interface - Open EPs if necessary - uint8_t foundEPs = 0, nEps = ((tusb_desc_interface_t const * )p_desc)->bNumEndpoints; + uint8_t foundEPs = 0, nEps = ((tusb_desc_interface_t const *) p_desc)->bNumEndpoints; // Condition modified from p_desc < p_desc_end to prevent gcc>=12 strict-overflow warning - while (foundEPs < nEps && (p_desc_end - p_desc > 0)) - { - if (tu_desc_type(p_desc) == TUSB_DESC_ENDPOINT) - { - tusb_desc_endpoint_t const* desc_ep = (tusb_desc_endpoint_t const *) p_desc; + while (foundEPs < nEps && (p_desc_end - p_desc > 0)) { + if (tu_desc_type(p_desc) == TUSB_DESC_ENDPOINT) { + tusb_desc_endpoint_t const *desc_ep = (tusb_desc_endpoint_t const *) p_desc; #ifdef TUP_DCD_EDPT_ISO_ALLOC TU_ASSERT(usbd_edpt_iso_activate(rhport, desc_ep)); #else @@ -1947,60 +1229,32 @@ static bool audiod_set_interface(uint8_t rhport, tusb_control_request_t const * usbd_edpt_clear_stall(rhport, ep_addr); #if CFG_TUD_AUDIO_ENABLE_EP_IN - if (tu_edpt_dir(ep_addr) == TUSB_DIR_IN && desc_ep->bmAttributes.usage == 0x00) // Check if usage is data EP + // For data or data with implicit feedback IN EP + if (tu_edpt_dir(ep_addr) == TUSB_DIR_IN && (desc_ep->bmAttributes.usage == 0 || desc_ep->bmAttributes.usage == 2)) { // Save address audio->ep_in = ep_addr; audio->ep_in_as_intf_num = itf; audio->ep_in_sz = tu_edpt_packet_size(desc_ep); - // If software encoding is enabled, parse for the corresponding parameters - doing this here means only AS interfaces with EPs get scanned for parameters - #if CFG_TUD_AUDIO_ENABLE_ENCODING || CFG_TUD_AUDIO_EP_IN_FLOW_CONTROL - audiod_parse_for_AS_params(audio, p_desc_parse_for_params, p_desc_end, itf); - - // Reconfigure size of support FIFOs - this is necessary to avoid samples to get split in case of a wrap - #if CFG_TUD_AUDIO_ENABLE_ENCODING && CFG_TUD_AUDIO_ENABLE_TYPE_I_ENCODING - const uint16_t active_fifo_depth = (uint16_t) ((audio->tx_supp_ff_sz_max / (audio->n_channels_per_ff_tx * audio->n_bytes_per_sample_tx)) - * (audio->n_channels_per_ff_tx * audio->n_bytes_per_sample_tx)); - for (uint8_t cnt = 0; cnt < audio->n_tx_supp_ff; cnt++) - { - tu_fifo_config(&audio->tx_supp_ff[cnt], audio->tx_supp_ff[cnt].buffer, active_fifo_depth, 1, true); - } - audio->n_ff_used_tx = audio->n_channels_tx / audio->n_channels_per_ff_tx; - TU_ASSERT( audio->n_ff_used_tx <= audio->n_tx_supp_ff ); - #endif + // If flow control is enabled, parse for the corresponding parameters - doing this here means only AS interfaces with EPs get scanned for parameters + #if CFG_TUD_AUDIO_EP_IN_FLOW_CONTROL + audiod_parse_flow_control_params(audio, p_desc_parse_for_params); #endif - // Schedule first transmit if alternate interface is not zero i.e. streaming is disabled - in case no sample data is available a ZLP is loaded // It is necessary to trigger this here since the refill is done with an RX FIFO empty interrupt which can only trigger if something was in there TU_VERIFY(audiod_tx_done_cb(rhport, &_audiod_fct[func_id])); } -#endif // CFG_TUD_AUDIO_ENABLE_EP_IN +#endif// CFG_TUD_AUDIO_ENABLE_EP_IN #if CFG_TUD_AUDIO_ENABLE_EP_OUT - - if (tu_edpt_dir(ep_addr) == TUSB_DIR_OUT) // Checking usage not necessary + if (tu_edpt_dir(ep_addr) == TUSB_DIR_OUT)// Checking usage not necessary { // Save address audio->ep_out = ep_addr; audio->ep_out_as_intf_num = itf; audio->ep_out_sz = tu_edpt_packet_size(desc_ep); - #if CFG_TUD_AUDIO_ENABLE_DECODING - audiod_parse_for_AS_params(audio, p_desc_parse_for_params, p_desc_end, itf); - - // Reconfigure size of support FIFOs - this is necessary to avoid samples to get split in case of a wrap - #if CFG_TUD_AUDIO_ENABLE_TYPE_I_DECODING - const uint16_t active_fifo_depth = (audio->rx_supp_ff_sz_max / audio->n_bytes_per_sample_rx) * audio->n_bytes_per_sample_rx; - for (uint8_t cnt = 0; cnt < audio->n_rx_supp_ff; cnt++) - { - tu_fifo_config(&audio->rx_supp_ff[cnt], audio->rx_supp_ff[cnt].buffer, active_fifo_depth, 1, true); - } - audio->n_ff_used_rx = audio->n_channels_rx / audio->n_channels_per_ff_rx; - TU_ASSERT( audio->n_ff_used_rx <= audio->n_rx_supp_ff ); - #endif - #endif - // Prepare for incoming data #if USE_LINEAR_BUFFER_RX TU_VERIFY(usbd_edpt_xfer(rhport, audio->ep_out, audio->lin_buf_out, audio->ep_out_sz), false); @@ -2010,13 +1264,13 @@ static bool audiod_set_interface(uint8_t rhport, tusb_control_request_t const * } #if CFG_TUD_AUDIO_ENABLE_FEEDBACK_EP - if (tu_edpt_dir(ep_addr) == TUSB_DIR_IN && desc_ep->bmAttributes.usage == 1) // Check if usage is explicit data feedback + if (tu_edpt_dir(ep_addr) == TUSB_DIR_IN && desc_ep->bmAttributes.usage == 1)// Check if usage is explicit data feedback { audio->ep_fb = ep_addr; - audio->feedback.frame_shift = desc_ep->bInterval -1; + audio->feedback.frame_shift = desc_ep->bInterval - 1; } #endif -#endif // CFG_TUD_AUDIO_ENABLE_EP_OUT +#endif// CFG_TUD_AUDIO_ENABLE_EP_OUT foundEPs += 1; } @@ -2030,58 +1284,50 @@ static bool audiod_set_interface(uint8_t rhport, tusb_control_request_t const * #if CFG_TUD_AUDIO_ENABLE_FEEDBACK_EP // Prepare feedback computation if endpoint is available - if(audio->ep_fb != 0) - { + if (audio->ep_fb != 0) { audio_feedback_params_t fb_param; tud_audio_feedback_params_cb(func_id, alt, &fb_param); audio->feedback.compute_method = fb_param.method; - if(TUSB_SPEED_FULL == tud_speed_get()) + if (TUSB_SPEED_FULL == tud_speed_get()) audio->feedback.format_correction = tud_audio_feedback_format_correction_cb(func_id); // Minimal/Maximum value in 16.16 format for full speed (1ms per frame) or high speed (125 us per frame) - uint32_t const frame_div = (TUSB_SPEED_FULL == tud_speed_get()) ? 1000 : 8000; - audio->feedback.min_value = ((fb_param.sample_freq - 1)/frame_div) << 16; - audio->feedback.max_value = (fb_param.sample_freq/frame_div + 1) << 16; + uint32_t const frame_div = (TUSB_SPEED_FULL == tud_speed_get()) ? 1000 : 8000; + audio->feedback.min_value = ((fb_param.sample_freq - 1) / frame_div) << 16; + audio->feedback.max_value = (fb_param.sample_freq / frame_div + 1) << 16; - switch(fb_param.method) - { + switch (fb_param.method) { case AUDIO_FEEDBACK_METHOD_FREQUENCY_FIXED: case AUDIO_FEEDBACK_METHOD_FREQUENCY_FLOAT: case AUDIO_FEEDBACK_METHOD_FREQUENCY_POWER_OF_2: audiod_set_fb_params_freq(audio, fb_param.sample_freq, fb_param.frequency.mclk_freq); - break; + break; - case AUDIO_FEEDBACK_METHOD_FIFO_COUNT: - { + case AUDIO_FEEDBACK_METHOD_FIFO_COUNT: { // Initialize the threshold level to half filled - uint16_t fifo_lvl_thr; -#if CFG_TUD_AUDIO_ENABLE_DECODING - fifo_lvl_thr = tu_fifo_depth(&audio->rx_supp_ff[0]) / 2; -#else - fifo_lvl_thr = tu_fifo_depth(&audio->ep_out_ff) / 2; -#endif + uint16_t fifo_lvl_thr = tu_fifo_depth(&audio->ep_out_ff) / 2; audio->feedback.compute.fifo_count.fifo_lvl_thr = fifo_lvl_thr; - audio->feedback.compute.fifo_count.fifo_lvl_avg = ((uint32_t)fifo_lvl_thr) << 16; + audio->feedback.compute.fifo_count.fifo_lvl_avg = ((uint32_t) fifo_lvl_thr) << 16; // Avoid 64bit division uint32_t nominal = ((fb_param.sample_freq / 100) << 16) / (frame_div / 100); audio->feedback.compute.fifo_count.nom_value = nominal; audio->feedback.compute.fifo_count.rate_const[0] = (uint16_t) ((audio->feedback.max_value - nominal) / fifo_lvl_thr); audio->feedback.compute.fifo_count.rate_const[1] = (uint16_t) ((nominal - audio->feedback.min_value) / fifo_lvl_thr); // On HS feedback is more sensitive since packet size can vary every MSOF, could cause instability - if(tud_speed_get() == TUSB_SPEED_HIGH) { + if (tud_speed_get() == TUSB_SPEED_HIGH) { audio->feedback.compute.fifo_count.rate_const[0] /= 8; audio->feedback.compute.fifo_count.rate_const[1] /= 8; } - } - break; + } break; // nothing to do - default: break; + default: + break; } } -#endif // CFG_TUD_AUDIO_ENABLE_FEEDBACK_EP +#endif// CFG_TUD_AUDIO_ENABLE_FEEDBACK_EP // We are done - abort loop break; @@ -2094,13 +1340,11 @@ static bool audiod_set_interface(uint8_t rhport, tusb_control_request_t const * #if CFG_TUD_AUDIO_ENABLE_FEEDBACK_EP // Disable SOF interrupt if no driver has any enabled feedback EP bool enable_sof = false; - for(uint8_t i=0; i < CFG_TUD_AUDIO; i++) - { + for (uint8_t i = 0; i < CFG_TUD_AUDIO; i++) { if (_audiod_fct[i].ep_fb != 0 && - (_audiod_fct[i].feedback.compute_method == AUDIO_FEEDBACK_METHOD_FREQUENCY_FIXED || - _audiod_fct[i].feedback.compute_method == AUDIO_FEEDBACK_METHOD_FREQUENCY_FLOAT || - _audiod_fct[i].feedback.compute_method == AUDIO_FEEDBACK_METHOD_FREQUENCY_POWER_OF_2 )) - { + (_audiod_fct[i].feedback.compute_method == AUDIO_FEEDBACK_METHOD_FREQUENCY_FIXED || + _audiod_fct[i].feedback.compute_method == AUDIO_FEEDBACK_METHOD_FREQUENCY_FLOAT || + _audiod_fct[i].feedback.compute_method == AUDIO_FEEDBACK_METHOD_FREQUENCY_POWER_OF_2)) { enable_sof = true; break; } @@ -2119,22 +1363,17 @@ static bool audiod_set_interface(uint8_t rhport, tusb_control_request_t const * // Invoked when class request DATA stage is finished. // return false to stall control EP (e.g Host send non-sense DATA) -static bool audiod_control_complete(uint8_t rhport, tusb_control_request_t const * p_request) -{ +static bool audiod_control_complete(uint8_t rhport, tusb_control_request_t const *p_request) { // Handle audio class specific set requests - if(p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS && p_request->bmRequestType_bit.direction == TUSB_DIR_OUT) - { + if (p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS && p_request->bmRequestType_bit.direction == TUSB_DIR_OUT) { uint8_t func_id; - switch (p_request->bmRequestType_bit.recipient) - { - case TUSB_REQ_RCPT_INTERFACE: - { + switch (p_request->bmRequestType_bit.recipient) { + case TUSB_REQ_RCPT_INTERFACE: { uint8_t itf = TU_U16_LOW(p_request->wIndex); uint8_t entityID = TU_U16_HIGH(p_request->wIndex); - if (entityID != 0) - { + if (entityID != 0) { // Check if entity is present and get corresponding driver index TU_VERIFY(audiod_verify_entity_exists(itf, entityID, &func_id)); @@ -2147,20 +1386,16 @@ static bool audiod_control_complete(uint8_t rhport, tusb_control_request_t const // Invoke callback return tud_audio_set_req_entity_cb(rhport, p_request, _audiod_fct[func_id].ctrl_buf); - } - else - { + } else { // Find index of audio driver structure and verify interface really exists TU_VERIFY(audiod_verify_itf_exists(itf, &func_id)); // Invoke callback return tud_audio_set_req_itf_cb(rhport, p_request, _audiod_fct[func_id].ctrl_buf); } - } - break; + } break; - case TUSB_REQ_RCPT_ENDPOINT: - { + case TUSB_REQ_RCPT_ENDPOINT: { uint8_t ep = TU_U16_LOW(p_request->wIndex); // Check if entity is present and get corresponding driver index @@ -2168,10 +1403,11 @@ static bool audiod_control_complete(uint8_t rhport, tusb_control_request_t const // Invoke callback return tud_audio_set_req_ep_cb(rhport, p_request, _audiod_fct[func_id].ctrl_buf); - } - break; + } break; // Unknown/Unsupported recipient - default: TU_BREAKPOINT(); return false; + default: + TU_BREAKPOINT(); + return false; } } return true; @@ -2179,15 +1415,12 @@ static bool audiod_control_complete(uint8_t rhport, tusb_control_request_t const // Handle class control request // return false to stall control endpoint (e.g unsupported request) -static bool audiod_control_request(uint8_t rhport, tusb_control_request_t const * p_request) -{ +static bool audiod_control_request(uint8_t rhport, tusb_control_request_t const *p_request) { (void) rhport; // Handle standard requests - standard set requests usually have no data stage so we also handle set requests here - if (p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_STANDARD) - { - switch (p_request->bRequest) - { + if (p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_STANDARD) { + switch (p_request->bRequest) { case TUSB_REQ_GET_INTERFACE: return audiod_get_interface(rhport, p_request); @@ -2198,66 +1431,59 @@ static bool audiod_control_request(uint8_t rhport, tusb_control_request_t const return true; // Unknown/Unsupported request - default: TU_BREAKPOINT(); return false; + default: + TU_BREAKPOINT(); + return false; } } // Handle class requests - if (p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS) - { + if (p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS) { uint8_t itf = TU_U16_LOW(p_request->wIndex); uint8_t func_id; // Conduct checks which depend on the recipient - switch (p_request->bmRequestType_bit.recipient) - { - case TUSB_REQ_RCPT_INTERFACE: - { + switch (p_request->bmRequestType_bit.recipient) { + case TUSB_REQ_RCPT_INTERFACE: { uint8_t entityID = TU_U16_HIGH(p_request->wIndex); // Verify if entity is present - if (entityID != 0) - { + if (entityID != 0) { // Find index of audio driver structure and verify entity really exists TU_VERIFY(audiod_verify_entity_exists(itf, entityID, &func_id)); // In case we got a get request invoke callback - callback needs to answer as defined in UAC2 specification page 89 - 5. Requests - if (p_request->bmRequestType_bit.direction == TUSB_DIR_IN) - { + if (p_request->bmRequestType_bit.direction == TUSB_DIR_IN) { return tud_audio_get_req_entity_cb(rhport, p_request); } - } - else - { + } else { // Find index of audio driver structure and verify interface really exists TU_VERIFY(audiod_verify_itf_exists(itf, &func_id)); // In case we got a get request invoke callback - callback needs to answer as defined in UAC2 specification page 89 - 5. Requests - if (p_request->bmRequestType_bit.direction == TUSB_DIR_IN) - { + if (p_request->bmRequestType_bit.direction == TUSB_DIR_IN) { return tud_audio_get_req_itf_cb(rhport, p_request); } } - } - break; + } break; - case TUSB_REQ_RCPT_ENDPOINT: - { + case TUSB_REQ_RCPT_ENDPOINT: { uint8_t ep = TU_U16_LOW(p_request->wIndex); // Find index of audio driver structure and verify EP really exists TU_VERIFY(audiod_verify_ep_exists(ep, &func_id)); // In case we got a get request invoke callback - callback needs to answer as defined in UAC2 specification page 89 - 5. Requests - if (p_request->bmRequestType_bit.direction == TUSB_DIR_IN) - { + if (p_request->bmRequestType_bit.direction == TUSB_DIR_IN) { return tud_audio_get_req_ep_cb(rhport, p_request); } - } - break; + } break; // Unknown/Unsupported recipient - default: TU_LOG2(" Unsupported recipient: %d\r\n", p_request->bmRequestType_bit.recipient); TU_BREAKPOINT(); return false; + default: + TU_LOG2(" Unsupported recipient: %d\r\n", p_request->bmRequestType_bit.recipient); + TU_BREAKPOINT(); + return false; } // If we end here, the received request is a set request - we schedule a receive for the data stage and return true here. We handle the rest later in audiod_control_complete() once the data stage was finished @@ -2270,35 +1496,28 @@ static bool audiod_control_request(uint8_t rhport, tusb_control_request_t const return false; } -bool audiod_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb_control_request_t const * request) -{ - if ( stage == CONTROL_STAGE_SETUP ) - { +bool audiod_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb_control_request_t const *request) { + if (stage == CONTROL_STAGE_SETUP) { return audiod_control_request(rhport, request); - } - else if ( stage == CONTROL_STAGE_DATA ) - { + } else if (stage == CONTROL_STAGE_DATA) { return audiod_control_complete(rhport, request); } return true; } -bool audiod_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes) -{ +bool audiod_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes) { (void) result; (void) xferred_bytes; // Search for interface belonging to given end point address and proceed as required - for (uint8_t func_id = 0; func_id < CFG_TUD_AUDIO; func_id++) - { - audiod_function_t* audio = &_audiod_fct[func_id]; + for (uint8_t func_id = 0; func_id < CFG_TUD_AUDIO; func_id++) { + audiod_function_t *audio = &_audiod_fct[func_id]; #if CFG_TUD_AUDIO_ENABLE_INTERRUPT_EP // Data transmission of control interrupt finished - if (audio->ep_int == ep_addr) - { + if (audio->ep_int == ep_addr) { // According to USB2 specification, maximum payload of interrupt EP is 8 bytes on low speed, 64 bytes on full speed, and 1024 bytes on high speed (but only if an alternate interface other than 0 is used - see specification p. 49) // In case there is nothing to send we have to return a NAK - this is taken care of by PHY ??? // In case of an erroneous transmission a retransmission is conducted - this is taken care of by PHY ??? @@ -2315,8 +1534,7 @@ bool audiod_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint3 #if CFG_TUD_AUDIO_ENABLE_EP_IN // Data transmission of audio packet finished - if (audio->ep_in == ep_addr && audio->alt_setting != 0) - { + if (audio->ep_in == ep_addr && audio->alt_setting != 0) { // USB 2.0, section 5.6.4, third paragraph, states "An isochronous endpoint must specify its required bus access period. However, an isochronous endpoint must be prepared to handle poll rates faster than the one specified." // That paragraph goes on to say "An isochronous IN endpoint must return a zero-length packet whenever data is requested at a faster interval than the specified interval and data is not available." // This can only be solved reliably if we load a ZLP after every IN transmission since we can not say if the host requests samples earlier than we declared! Once all samples are collected we overwrite the loaded ZLP. @@ -2336,27 +1554,24 @@ bool audiod_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint3 #if CFG_TUD_AUDIO_ENABLE_EP_OUT // New audio packet received - if (audio->ep_out == ep_addr) - { + if (audio->ep_out == ep_addr) { TU_VERIFY(audiod_rx_done_cb(rhport, audio, (uint16_t) xferred_bytes)); return true; } -#if CFG_TUD_AUDIO_ENABLE_FEEDBACK_EP + #if CFG_TUD_AUDIO_ENABLE_FEEDBACK_EP // Transmission of feedback EP finished - if (audio->ep_fb == ep_addr) - { + if (audio->ep_fb == ep_addr) { tud_audio_fb_done_cb(func_id); // Schedule a transmit with the new value if EP is not busy - if (usbd_edpt_claim(rhport, audio->ep_fb)) - { + if (usbd_edpt_claim(rhport, audio->ep_fb)) { // Schedule next transmission - value is changed bytud_audio_n_fb_set() in the meantime or the old value gets sent return audiod_fb_send(audio); } } -#endif + #endif #endif } @@ -2365,8 +1580,7 @@ bool audiod_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint3 #if CFG_TUD_AUDIO_ENABLE_EP_OUT && CFG_TUD_AUDIO_ENABLE_FEEDBACK_EP -static bool audiod_set_fb_params_freq(audiod_function_t* audio, uint32_t sample_freq, uint32_t mclk_freq) -{ +static bool audiod_set_fb_params_freq(audiod_function_t *audio, uint32_t sample_freq, uint32_t mclk_freq) { // Check if frame interval is within sane limits // The interval value n_frames was taken from the descriptors within audiod_set_interface() @@ -2375,23 +1589,19 @@ static bool audiod_set_fb_params_freq(audiod_function_t* audio, uint32_t sample_ uint32_t const k = (TUSB_SPEED_FULL == tud_speed_get()) ? 10 : 13; uint32_t const n_frame = (1UL << audio->feedback.frame_shift); - if ( (((1UL << k) * sample_freq / mclk_freq) + 1) > n_frame ) - { - TU_LOG1(" UAC2 feedback interval too small\r\n"); TU_BREAKPOINT(); return false; + if ((((1UL << k) * sample_freq / mclk_freq) + 1) > n_frame) { + TU_LOG1(" UAC2 feedback interval too small\r\n"); + TU_BREAKPOINT(); + return false; } // Check if parameters really allow for a power of two division - if ((mclk_freq % sample_freq) == 0 && tu_is_power_of_two(mclk_freq / sample_freq)) - { - audio->feedback.compute_method = AUDIO_FEEDBACK_METHOD_FREQUENCY_POWER_OF_2; + if ((mclk_freq % sample_freq) == 0 && tu_is_power_of_two(mclk_freq / sample_freq)) { + audio->feedback.compute_method = AUDIO_FEEDBACK_METHOD_FREQUENCY_POWER_OF_2; audio->feedback.compute.power_of_2 = (uint8_t) (16 - (audio->feedback.frame_shift - 1) - tu_log2(mclk_freq / sample_freq)); - } - else if ( audio->feedback.compute_method == AUDIO_FEEDBACK_METHOD_FREQUENCY_FLOAT) - { - audio->feedback.compute.float_const = (float)sample_freq / (float) mclk_freq * (1UL << (16 - (audio->feedback.frame_shift - 1))); - } - else - { + } else if (audio->feedback.compute_method == AUDIO_FEEDBACK_METHOD_FREQUENCY_FLOAT) { + audio->feedback.compute.float_const = (float) sample_freq / (float) mclk_freq * (1UL << (16 - (audio->feedback.frame_shift - 1))); + } else { audio->feedback.compute.fixed.sample_freq = sample_freq; audio->feedback.compute.fixed.mclk_freq = mclk_freq; } @@ -2399,84 +1609,75 @@ static bool audiod_set_fb_params_freq(audiod_function_t* audio, uint32_t sample_ return true; } -static void audiod_fb_fifo_count_update(audiod_function_t* audio, uint16_t lvl_new) -{ +static void audiod_fb_fifo_count_update(audiod_function_t *audio, uint16_t lvl_new) { /* Low-pass (averaging) filter */ uint32_t lvl = audio->feedback.compute.fifo_count.fifo_lvl_avg; - lvl = (uint32_t)(((uint64_t)lvl * 63 + ((uint32_t)lvl_new << 16)) >> 6); + lvl = (uint32_t) (((uint64_t) lvl * 63 + ((uint32_t) lvl_new << 16)) >> 6); audio->feedback.compute.fifo_count.fifo_lvl_avg = lvl; uint32_t const ff_lvl = lvl >> 16; uint16_t const ff_thr = audio->feedback.compute.fifo_count.fifo_lvl_thr; - uint16_t const *rate = audio->feedback.compute.fifo_count.rate_const; + uint16_t const *rate = audio->feedback.compute.fifo_count.rate_const; uint32_t feedback; - if(ff_lvl < ff_thr) - { + if (ff_lvl < ff_thr) { feedback = audio->feedback.compute.fifo_count.nom_value + (ff_thr - ff_lvl) * rate[0]; - } else - { + } else { feedback = audio->feedback.compute.fifo_count.nom_value - (ff_lvl - ff_thr) * rate[1]; } - if ( feedback > audio->feedback.max_value ) feedback = audio->feedback.max_value; - if ( feedback < audio->feedback.min_value ) feedback = audio->feedback.min_value; + if (feedback > audio->feedback.max_value) feedback = audio->feedback.max_value; + if (feedback < audio->feedback.min_value) feedback = audio->feedback.min_value; audio->feedback.value = feedback; // Schedule a transmit with the new value if EP is not busy - this triggers repetitive scheduling of the feedback value - if (usbd_edpt_claim(audio->rhport, audio->ep_fb)) - { + if (usbd_edpt_claim(audio->rhport, audio->ep_fb)) { audiod_fb_send(audio); } } -uint32_t tud_audio_feedback_update(uint8_t func_id, uint32_t cycles) -{ - audiod_function_t* audio = &_audiod_fct[func_id]; +uint32_t tud_audio_feedback_update(uint8_t func_id, uint32_t cycles) { + audiod_function_t *audio = &_audiod_fct[func_id]; uint32_t feedback; - switch (audio->feedback.compute_method) - { + switch (audio->feedback.compute_method) { case AUDIO_FEEDBACK_METHOD_FREQUENCY_POWER_OF_2: feedback = (cycles << audio->feedback.compute.power_of_2); - break; + break; case AUDIO_FEEDBACK_METHOD_FREQUENCY_FLOAT: feedback = (uint32_t) ((float) cycles * audio->feedback.compute.float_const); - break; + break; - case AUDIO_FEEDBACK_METHOD_FREQUENCY_FIXED: - { + case AUDIO_FEEDBACK_METHOD_FREQUENCY_FIXED: { uint64_t fb64 = (((uint64_t) cycles) * audio->feedback.compute.fixed.sample_freq) << (16 - (audio->feedback.frame_shift - 1)); feedback = (uint32_t) (fb64 / audio->feedback.compute.fixed.mclk_freq); - } - break; + } break; - default: return 0; + default: + return 0; } // For Windows: https://docs.microsoft.com/en-us/windows-hardware/drivers/audio/usb-2-0-audio-drivers // The size of isochronous packets created by the device must be within the limits specified in FMT-2.0 section 2.3.1.1. // This means that the deviation of actual packet size from nominal size must not exceed +/- one audio slot // (audio slot = channel count samples). - if ( feedback > audio->feedback.max_value ) feedback = audio->feedback.max_value; - if ( feedback < audio->feedback.min_value ) feedback = audio->feedback.min_value; + if (feedback > audio->feedback.max_value) feedback = audio->feedback.max_value; + if (feedback < audio->feedback.min_value) feedback = audio->feedback.min_value; tud_audio_n_fb_set(func_id, feedback); return feedback; } -bool tud_audio_n_fb_set(uint8_t func_id, uint32_t feedback) -{ +bool tud_audio_n_fb_set(uint8_t func_id, uint32_t feedback) { TU_VERIFY(func_id < CFG_TUD_AUDIO && _audiod_fct[func_id].p_desc != NULL); _audiod_fct[func_id].feedback.value = feedback; // Schedule a transmit with the new value if EP is not busy - this triggers repetitive scheduling of the feedback value - if (usbd_edpt_claim(_audiod_fct[func_id].rhport, _audiod_fct[func_id].ep_fb)) - { + if (usbd_edpt_claim(_audiod_fct[func_id].rhport, _audiod_fct[func_id].ep_fb)) { return audiod_fb_send(&_audiod_fct[func_id]); } @@ -2484,8 +1685,7 @@ bool tud_audio_n_fb_set(uint8_t func_id, uint32_t feedback) } #endif -TU_ATTR_FAST_FUNC void audiod_sof_isr (uint8_t rhport, uint32_t frame_count) -{ +TU_ATTR_FAST_FUNC void audiod_sof_isr(uint8_t rhport, uint32_t frame_count) { (void) rhport; (void) frame_count; @@ -2497,26 +1697,22 @@ TU_ATTR_FAST_FUNC void audiod_sof_isr (uint8_t rhport, uint32_t frame_count) // feedback = n_cycles / n_frames * f_s / f_m in 16.16 format, where n_cycles are the number of main clock cycles within fb_n_frames // Iterate over audio functions and set feedback value - for(uint8_t i=0; i < CFG_TUD_AUDIO; i++) - { - audiod_function_t* audio = &_audiod_fct[i]; + for (uint8_t i = 0; i < CFG_TUD_AUDIO; i++) { + audiod_function_t *audio = &_audiod_fct[i]; - if (audio->ep_fb != 0) - { + if (audio->ep_fb != 0) { // HS shift need to be adjusted since SOF event is generated for frame only uint8_t const hs_adjust = (TUSB_SPEED_HIGH == tud_speed_get()) ? 3 : 0; uint32_t const interval = 1UL << (audio->feedback.frame_shift - hs_adjust); - if ( 0 == (frame_count & (interval-1)) ) - { + if (0 == (frame_count & (interval - 1))) { tud_audio_feedback_interval_isr(i, frame_count, audio->feedback.frame_shift); } } } -#endif // CFG_TUD_AUDIO_ENABLE_EP_OUT && CFG_TUD_AUDIO_ENABLE_FEEDBACK_EP +#endif// CFG_TUD_AUDIO_ENABLE_EP_OUT && CFG_TUD_AUDIO_ENABLE_FEEDBACK_EP } -bool tud_audio_buffer_and_schedule_control_xfer(uint8_t rhport, tusb_control_request_t const * p_request, void* data, uint16_t len) -{ +bool tud_audio_buffer_and_schedule_control_xfer(uint8_t rhport, tusb_control_request_t const *p_request, void *data, uint16_t len) { // Handles only sending of data not receiving if (p_request->bmRequestType_bit.direction == TUSB_DIR_OUT) return false; @@ -2525,85 +1721,73 @@ bool tud_audio_buffer_and_schedule_control_xfer(uint8_t rhport, tusb_control_req uint8_t itf = TU_U16_LOW(p_request->wIndex); // Conduct checks which depend on the recipient - switch (p_request->bmRequestType_bit.recipient) - { - case TUSB_REQ_RCPT_INTERFACE: - { + switch (p_request->bmRequestType_bit.recipient) { + case TUSB_REQ_RCPT_INTERFACE: { uint8_t entityID = TU_U16_HIGH(p_request->wIndex); // Verify if entity is present - if (entityID != 0) - { + if (entityID != 0) { // Find index of audio driver structure and verify entity really exists TU_VERIFY(audiod_verify_entity_exists(itf, entityID, &func_id)); - } - else - { + } else { // Find index of audio driver structure and verify interface really exists TU_VERIFY(audiod_verify_itf_exists(itf, &func_id)); } - } - break; + } break; - case TUSB_REQ_RCPT_ENDPOINT: - { + case TUSB_REQ_RCPT_ENDPOINT: { uint8_t ep = TU_U16_LOW(p_request->wIndex); // Find index of audio driver structure and verify EP really exists TU_VERIFY(audiod_verify_ep_exists(ep, &func_id)); - } - break; + } break; // Unknown/Unsupported recipient - default: TU_LOG2(" Unsupported recipient: %d\r\n", p_request->bmRequestType_bit.recipient); TU_BREAKPOINT(); return false; + default: + TU_LOG2(" Unsupported recipient: %d\r\n", p_request->bmRequestType_bit.recipient); + TU_BREAKPOINT(); + return false; } // Crop length if (len > _audiod_fct[func_id].ctrl_buf_sz) len = _audiod_fct[func_id].ctrl_buf_sz; // Copy into buffer - TU_VERIFY(0 == tu_memcpy_s(_audiod_fct[func_id].ctrl_buf, _audiod_fct[func_id].ctrl_buf_sz, data, (size_t)len)); + TU_VERIFY(0 == tu_memcpy_s(_audiod_fct[func_id].ctrl_buf, _audiod_fct[func_id].ctrl_buf_sz, data, (size_t) len)); #if CFG_TUD_AUDIO_ENABLE_EP_IN && CFG_TUD_AUDIO_EP_IN_FLOW_CONTROL // Find data for sampling_frequency_control - if (p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS && p_request->bmRequestType_bit.recipient == TUSB_REQ_RCPT_INTERFACE) - { + if (p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS && p_request->bmRequestType_bit.recipient == TUSB_REQ_RCPT_INTERFACE) { uint8_t entityID = TU_U16_HIGH(p_request->wIndex); uint8_t ctrlSel = TU_U16_HIGH(p_request->wValue); - if (_audiod_fct[func_id].bclock_id_tx == entityID && ctrlSel == AUDIO_CS_CTRL_SAM_FREQ && p_request->bRequest == AUDIO_CS_REQ_CUR) - { + if (_audiod_fct[func_id].bclock_id_tx == entityID && ctrlSel == AUDIO_CS_CTRL_SAM_FREQ && p_request->bRequest == AUDIO_CS_REQ_CUR) { _audiod_fct[func_id].sample_rate_tx = tu_unaligned_read32(_audiod_fct[func_id].ctrl_buf); } } #endif // Schedule transmit - return tud_control_xfer(rhport, p_request, (void*)_audiod_fct[func_id].ctrl_buf, len); + return tud_control_xfer(rhport, p_request, (void *) _audiod_fct[func_id].ctrl_buf, len); } // This helper function finds for a given audio function and AS interface number the index of the attached driver structure, the index of the interface in the audio function // (e.g. the std. AS interface with interface number 15 is the first AS interface for the given audio function and thus gets index zero), and // finally a pointer to the std. AS interface, where the pointer always points to the first alternate setting i.e. alternate interface zero. -static bool audiod_get_AS_interface_index(uint8_t itf, audiod_function_t * audio, uint8_t *idxItf, uint8_t const **pp_desc_int) -{ - if (audio->p_desc) - { +static bool audiod_get_AS_interface_index(uint8_t itf, audiod_function_t *audio, uint8_t *idxItf, uint8_t const **pp_desc_int) { + if (audio->p_desc) { // Get pointer at end uint8_t const *p_desc_end = audio->p_desc + audio->desc_length - TUD_AUDIO_DESC_IAD_LEN; // Advance past AC descriptors uint8_t const *p_desc = tu_desc_next(audio->p_desc); - p_desc += ((audio_desc_cs_ac_interface_t const *)p_desc)->wTotalLength; + p_desc += ((audio_desc_cs_ac_interface_t const *) p_desc)->wTotalLength; uint8_t tmp = 0; // Condition modified from p_desc < p_desc_end to prevent gcc>=12 strict-overflow warning - while (p_desc_end - p_desc > 0) - { + while (p_desc_end - p_desc > 0) { // We assume the number of alternate settings is increasing thus we return the index of alternate setting zero! - if (tu_desc_type(p_desc) == TUSB_DESC_INTERFACE && ((tusb_desc_interface_t const * )p_desc)->bAlternateSetting == 0) - { - if (((tusb_desc_interface_t const * )p_desc)->bInterfaceNumber == itf) - { + if (tu_desc_type(p_desc) == TUSB_DESC_INTERFACE && ((tusb_desc_interface_t const *) p_desc)->bAlternateSetting == 0) { + if (((tusb_desc_interface_t const *) p_desc)->bInterfaceNumber == itf) { *idxItf = tmp; *pp_desc_int = p_desc; return true; @@ -2620,14 +1804,11 @@ static bool audiod_get_AS_interface_index(uint8_t itf, audiod_function_t * audio // This helper function finds for a given AS interface number the index of the attached driver structure, the index of the interface in the audio function // (e.g. the std. AS interface with interface number 15 is the first AS interface for the given audio function and thus gets index zero), and // finally a pointer to the std. AS interface, where the pointer always points to the first alternate setting i.e. alternate interface zero. -static bool audiod_get_AS_interface_index_global(uint8_t itf, uint8_t *func_id, uint8_t *idxItf, uint8_t const **pp_desc_int) -{ +static bool audiod_get_AS_interface_index_global(uint8_t itf, uint8_t *func_id, uint8_t *idxItf, uint8_t const **pp_desc_int) { // Loop over audio driver interfaces uint8_t i; - for (i = 0; i < CFG_TUD_AUDIO; i++) - { - if (audiod_get_AS_interface_index(itf, &_audiod_fct[i], idxItf, pp_desc_int)) - { + for (i = 0; i < CFG_TUD_AUDIO; i++) { + if (audiod_get_AS_interface_index(itf, &_audiod_fct[i], idxItf, pp_desc_int)) { *func_id = i; return true; } @@ -2637,23 +1818,19 @@ static bool audiod_get_AS_interface_index_global(uint8_t itf, uint8_t *func_id, } // Verify an entity with the given ID exists and returns also the corresponding driver index -static bool audiod_verify_entity_exists(uint8_t itf, uint8_t entityID, uint8_t *func_id) -{ +static bool audiod_verify_entity_exists(uint8_t itf, uint8_t entityID, uint8_t *func_id) { uint8_t i; - for (i = 0; i < CFG_TUD_AUDIO; i++) - { + for (i = 0; i < CFG_TUD_AUDIO; i++) { // Look for the correct driver by checking if the unique standard AC interface number fits - if (_audiod_fct[i].p_desc && ((tusb_desc_interface_t const *)_audiod_fct[i].p_desc)->bInterfaceNumber == itf) - { + if (_audiod_fct[i].p_desc && ((tusb_desc_interface_t const *) _audiod_fct[i].p_desc)->bInterfaceNumber == itf) { // Get pointers after class specific AC descriptors and end of AC descriptors - entities are defined in between - uint8_t const *p_desc = tu_desc_next(_audiod_fct[i].p_desc); // Points to CS AC descriptor - uint8_t const *p_desc_end = ((audio_desc_cs_ac_interface_t const *)p_desc)->wTotalLength + p_desc; - p_desc = tu_desc_next(p_desc); // Get past CS AC descriptor + uint8_t const *p_desc = tu_desc_next(_audiod_fct[i].p_desc);// Points to CS AC descriptor + uint8_t const *p_desc_end = ((audio_desc_cs_ac_interface_t const *) p_desc)->wTotalLength + p_desc; + p_desc = tu_desc_next(p_desc);// Get past CS AC descriptor // Condition modified from p_desc < p_desc_end to prevent gcc>=12 strict-overflow warning - while (p_desc_end - p_desc > 0) - { - if (p_desc[3] == entityID) // Entity IDs are always at offset 3 + while (p_desc_end - p_desc > 0) { + if (p_desc[3] == entityID)// Entity IDs are always at offset 3 { *func_id = i; return true; @@ -2665,21 +1842,16 @@ static bool audiod_verify_entity_exists(uint8_t itf, uint8_t entityID, uint8_t * return false; } -static bool audiod_verify_itf_exists(uint8_t itf, uint8_t *func_id) -{ +static bool audiod_verify_itf_exists(uint8_t itf, uint8_t *func_id) { uint8_t i; - for (i = 0; i < CFG_TUD_AUDIO; i++) - { - if (_audiod_fct[i].p_desc) - { + for (i = 0; i < CFG_TUD_AUDIO; i++) { + if (_audiod_fct[i].p_desc) { // Get pointer at beginning and end uint8_t const *p_desc = _audiod_fct[i].p_desc; uint8_t const *p_desc_end = _audiod_fct[i].p_desc + _audiod_fct[i].desc_length - TUD_AUDIO_DESC_IAD_LEN; // Condition modified from p_desc < p_desc_end to prevent gcc>=12 strict-overflow warning - while (p_desc_end - p_desc > 0) - { - if (tu_desc_type(p_desc) == TUSB_DESC_INTERFACE && ((tusb_desc_interface_t const *)_audiod_fct[i].p_desc)->bInterfaceNumber == itf) - { + while (p_desc_end - p_desc > 0) { + if (tu_desc_type(p_desc) == TUSB_DESC_INTERFACE && ((tusb_desc_interface_t const *) _audiod_fct[i].p_desc)->bInterfaceNumber == itf) { *func_id = i; return true; } @@ -2690,25 +1862,20 @@ static bool audiod_verify_itf_exists(uint8_t itf, uint8_t *func_id) return false; } -static bool audiod_verify_ep_exists(uint8_t ep, uint8_t *func_id) -{ +static bool audiod_verify_ep_exists(uint8_t ep, uint8_t *func_id) { uint8_t i; - for (i = 0; i < CFG_TUD_AUDIO; i++) - { - if (_audiod_fct[i].p_desc) - { + for (i = 0; i < CFG_TUD_AUDIO; i++) { + if (_audiod_fct[i].p_desc) { // Get pointer at end uint8_t const *p_desc_end = _audiod_fct[i].p_desc + _audiod_fct[i].desc_length; // Advance past AC descriptors - EP we look for are streaming EPs uint8_t const *p_desc = tu_desc_next(_audiod_fct[i].p_desc); - p_desc += ((audio_desc_cs_ac_interface_t const *)p_desc)->wTotalLength; + p_desc += ((audio_desc_cs_ac_interface_t const *) p_desc)->wTotalLength; // Condition modified from p_desc < p_desc_end to prevent gcc>=12 strict-overflow warning - while (p_desc_end - p_desc > 0) - { - if (tu_desc_type(p_desc) == TUSB_DESC_ENDPOINT && ((tusb_desc_endpoint_t const * )p_desc)->bEndpointAddress == ep) - { + while (p_desc_end - p_desc > 0) { + if (tu_desc_type(p_desc) == TUSB_DESC_ENDPOINT && ((tusb_desc_endpoint_t const *) p_desc)->bEndpointAddress == ep) { *func_id = i; return true; } @@ -2719,97 +1886,24 @@ static bool audiod_verify_ep_exists(uint8_t ep, uint8_t *func_id) return false; } -#if (CFG_TUD_AUDIO_ENABLE_EP_IN && (CFG_TUD_AUDIO_EP_IN_FLOW_CONTROL || CFG_TUD_AUDIO_ENABLE_ENCODING)) || (CFG_TUD_AUDIO_ENABLE_EP_OUT && CFG_TUD_AUDIO_ENABLE_DECODING) -// p_desc points to the AS interface of alternate setting zero -// itf is the interface number of the corresponding interface - we check if the interface belongs to EP in or EP out to see if it is a TX or RX parameter -// Currently, only AS interfaces with an EP (in or out) are supposed to be parsed for! -static void audiod_parse_for_AS_params(audiod_function_t* audio, uint8_t const * p_desc, uint8_t const * p_desc_end, uint8_t const as_itf) -{ -#if CFG_TUD_AUDIO_ENABLE_EP_IN && CFG_TUD_AUDIO_ENABLE_EP_OUT - if (as_itf != audio->ep_in_as_intf_num && as_itf != audio->ep_out_as_intf_num) return; // Abort, this interface has no EP, this driver does not support this currently -#endif -#if CFG_TUD_AUDIO_ENABLE_EP_IN && !CFG_TUD_AUDIO_ENABLE_EP_OUT - if (as_itf != audio->ep_in_as_intf_num) return; -#endif -#if !CFG_TUD_AUDIO_ENABLE_EP_IN && CFG_TUD_AUDIO_ENABLE_EP_OUT - if (as_itf != audio->ep_out_as_intf_num) return; -#endif +#if CFG_TUD_AUDIO_ENABLE_EP_IN && CFG_TUD_AUDIO_EP_IN_FLOW_CONTROL +static void audiod_parse_flow_control_params(audiod_function_t *audio, uint8_t const *p_desc) { - p_desc = tu_desc_next(p_desc); // Exclude standard AS interface descriptor of current alternate interface descriptor - // Condition modified from p_desc < p_desc_end to prevent gcc>=12 strict-overflow warning - while (p_desc_end - p_desc > 0) - { - // Abort if follow up descriptor is a new standard interface descriptor - indicates the last AS descriptor was already finished - if (tu_desc_type(p_desc) == TUSB_DESC_INTERFACE) break; - - // Look for a Class-Specific AS Interface Descriptor(4.9.2) to verify format type and format and also to get number of physical channels - if (tu_desc_type(p_desc) == TUSB_DESC_CS_INTERFACE && tu_desc_subtype(p_desc) == AUDIO_CS_AS_INTERFACE_AS_GENERAL) - { -#if CFG_TUD_AUDIO_ENABLE_EP_IN - if (as_itf == audio->ep_in_as_intf_num) - { - audio->n_channels_tx = ((audio_desc_cs_as_interface_t const * )p_desc)->bNrChannels; - audio->format_type_tx = (audio_format_type_t)(((audio_desc_cs_as_interface_t const * )p_desc)->bFormatType); - -#if CFG_TUD_AUDIO_ENABLE_TYPE_I_ENCODING - audio->format_type_I_tx = (audio_data_format_type_I_t)(((audio_desc_cs_as_interface_t const * )p_desc)->bmFormats); -#endif - } -#endif - -#if CFG_TUD_AUDIO_ENABLE_EP_OUT && CFG_TUD_AUDIO_ENABLE_DECODING - if (as_itf == audio->ep_out_as_intf_num) - { - audio->n_channels_rx = ((audio_desc_cs_as_interface_t const * )p_desc)->bNrChannels; - audio->format_type_rx = ((audio_desc_cs_as_interface_t const * )p_desc)->bFormatType; -#if CFG_TUD_AUDIO_ENABLE_TYPE_I_DECODING - audio->format_type_I_rx = ((audio_desc_cs_as_interface_t const * )p_desc)->bmFormats; -#endif - } -#endif - } + p_desc = tu_desc_next(p_desc);// Exclude standard AS interface descriptor of current alternate interface descriptor + // Look for a Class-Specific AS Interface Descriptor(4.9.2) to verify format type and format and also to get number of physical channels + if (tu_desc_type(p_desc) == TUSB_DESC_CS_INTERFACE && tu_desc_subtype(p_desc) == AUDIO_CS_AS_INTERFACE_AS_GENERAL) { + audio->n_channels_tx = ((audio_desc_cs_as_interface_t const *) p_desc)->bNrChannels; + audio->format_type_tx = (audio_format_type_t) (((audio_desc_cs_as_interface_t const *) p_desc)->bFormatType); // Look for a Type I Format Type Descriptor(2.3.1.6 - Audio Formats) -#if CFG_TUD_AUDIO_ENABLE_TYPE_I_ENCODING || CFG_TUD_AUDIO_EP_IN_FLOW_CONTROL || CFG_TUD_AUDIO_ENABLE_TYPE_I_DECODING - if (tu_desc_type(p_desc) == TUSB_DESC_CS_INTERFACE && tu_desc_subtype(p_desc) == AUDIO_CS_AS_INTERFACE_FORMAT_TYPE && ((audio_desc_type_I_format_t const * )p_desc)->bFormatType == AUDIO_FORMAT_TYPE_I) - { -#if CFG_TUD_AUDIO_ENABLE_EP_IN && CFG_TUD_AUDIO_ENABLE_EP_OUT - if (as_itf != audio->ep_in_as_intf_num && as_itf != audio->ep_out_as_intf_num) break; // Abort loop, this interface has no EP, this driver does not support this currently -#endif -#if CFG_TUD_AUDIO_ENABLE_EP_IN && !CFG_TUD_AUDIO_ENABLE_EP_OUT - if (as_itf != audio->ep_in_as_intf_num) break; -#endif -#if !CFG_TUD_AUDIO_ENABLE_EP_IN && CFG_TUD_AUDIO_ENABLE_EP_OUT - if (as_itf != audio->ep_out_as_intf_num) break; -#endif - -#if CFG_TUD_AUDIO_ENABLE_EP_IN - if (as_itf == audio->ep_in_as_intf_num) - { - audio->n_bytes_per_sample_tx = ((audio_desc_type_I_format_t const * )p_desc)->bSubslotSize; - } -#endif - -#if CFG_TUD_AUDIO_ENABLE_EP_OUT && CFG_TUD_AUDIO_ENABLE_DECODING - if (as_itf == audio->ep_out_as_intf_num) - { - audio->n_bytes_per_sample_rx = ((audio_desc_type_I_format_t const * )p_desc)->bSubslotSize; - } -#endif - } -#endif - - // Other format types are not supported yet - p_desc = tu_desc_next(p_desc); + if (tu_desc_type(p_desc) == TUSB_DESC_CS_INTERFACE && tu_desc_subtype(p_desc) == AUDIO_CS_AS_INTERFACE_FORMAT_TYPE && ((audio_desc_type_I_format_t const *) p_desc)->bFormatType == AUDIO_FORMAT_TYPE_I) { + audio->n_bytes_per_sample_tx = ((audio_desc_type_I_format_t const *) p_desc)->bSubslotSize; + } } } -#endif -#if CFG_TUD_AUDIO_ENABLE_EP_IN && CFG_TUD_AUDIO_EP_IN_FLOW_CONTROL - -static bool audiod_calc_tx_packet_sz(audiod_function_t* audio) -{ +static bool audiod_calc_tx_packet_sz(audiod_function_t *audio) { TU_VERIFY(audio->format_type_tx == AUDIO_FORMAT_TYPE_I); TU_VERIFY(audio->n_channels_tx); TU_VERIFY(audio->n_bytes_per_sample_tx); @@ -2818,25 +1912,23 @@ static bool audiod_calc_tx_packet_sz(audiod_function_t* audio) const uint8_t interval = (tud_speed_get() == TUSB_SPEED_FULL) ? audio->interval_tx : 1 << (audio->interval_tx - 1); - const uint16_t sample_normimal = (uint16_t)(audio->sample_rate_tx * interval / ((tud_speed_get() == TUSB_SPEED_FULL) ? 1000 : 8000)); - const uint16_t sample_reminder = (uint16_t)(audio->sample_rate_tx * interval % ((tud_speed_get() == TUSB_SPEED_FULL) ? 1000 : 8000)); + const uint16_t sample_normimal = (uint16_t) (audio->sample_rate_tx * interval / ((tud_speed_get() == TUSB_SPEED_FULL) ? 1000 : 8000)); + const uint16_t sample_reminder = (uint16_t) (audio->sample_rate_tx * interval % ((tud_speed_get() == TUSB_SPEED_FULL) ? 1000 : 8000)); - const uint16_t packet_sz_tx_min = (uint16_t)((sample_normimal - 1) * audio->n_channels_tx * audio->n_bytes_per_sample_tx); - const uint16_t packet_sz_tx_norm = (uint16_t)(sample_normimal * audio->n_channels_tx * audio->n_bytes_per_sample_tx); - const uint16_t packet_sz_tx_max = (uint16_t)((sample_normimal + 1) * audio->n_channels_tx * audio->n_bytes_per_sample_tx); + const uint16_t packet_sz_tx_min = (uint16_t) ((sample_normimal - 1) * audio->n_channels_tx * audio->n_bytes_per_sample_tx); + const uint16_t packet_sz_tx_norm = (uint16_t) (sample_normimal * audio->n_channels_tx * audio->n_bytes_per_sample_tx); + const uint16_t packet_sz_tx_max = (uint16_t) ((sample_normimal + 1) * audio->n_channels_tx * audio->n_bytes_per_sample_tx); // Endpoint size must larger than packet size TU_ASSERT(packet_sz_tx_max <= audio->ep_in_sz); // Frmt20.pdf 2.3.1.1 USB Packets - if (sample_reminder) - { + if (sample_reminder) { // All virtual frame packets must either contain INT(nav) audio slots (small VFP) or INT(nav)+1 (large VFP) audio slots audio->packet_sz_tx[0] = packet_sz_tx_norm; audio->packet_sz_tx[1] = packet_sz_tx_norm; audio->packet_sz_tx[2] = packet_sz_tx_max; - } else - { + } else { // In the case where nav = INT(nav), ni may vary between INT(nav)-1 (small VFP), INT(nav) // (medium VFP) and INT(nav)+1 (large VFP). audio->packet_sz_tx[0] = packet_sz_tx_min; @@ -2847,49 +1939,37 @@ static bool audiod_calc_tx_packet_sz(audiod_function_t* audio) return true; } -static uint16_t audiod_tx_packet_size(const uint16_t* norminal_size, uint16_t data_count, uint16_t fifo_depth, uint16_t max_depth) -{ +static uint16_t audiod_tx_packet_size(const uint16_t *norminal_size, uint16_t data_count, uint16_t fifo_depth, uint16_t max_depth) { // Flow control need a FIFO size of at least 4*Navg - if(norminal_size[1] && norminal_size[1] <= fifo_depth * 4) - { + if (norminal_size[1] && norminal_size[1] <= fifo_depth * 4) { // Use blackout to prioritize normal size packet static int ctrl_blackout = 0; uint16_t packet_size; uint16_t slot_size = norminal_size[2] - norminal_size[1]; - if (data_count < norminal_size[0]) - { - // If you get here frequently, then your I2S clock deviation is too big ! - packet_size = 0; - } else - if (data_count < fifo_depth / 2 - slot_size && !ctrl_blackout) - { + if (data_count < norminal_size[0]) { + // If you get here frequently, then your I2S clock deviation is too big ! + packet_size = 0; + } else if (data_count < fifo_depth / 2 - slot_size && !ctrl_blackout) { packet_size = norminal_size[0]; ctrl_blackout = 10; - } else - if (data_count > fifo_depth / 2 + slot_size && !ctrl_blackout) - { + } else if (data_count > fifo_depth / 2 + slot_size && !ctrl_blackout) { packet_size = norminal_size[2]; - if(norminal_size[0] == norminal_size[1]) - { + if (norminal_size[0] == norminal_size[1]) { // nav > INT(nav), eg. 44.1k, 88.2k ctrl_blackout = 0; - } else - { + } else { // nav = INT(nav), eg. 48k, 96k ctrl_blackout = 10; } - } else - { + } else { packet_size = norminal_size[1]; - if (ctrl_blackout) - { + if (ctrl_blackout) { ctrl_blackout--; } } // Normally this cap is not necessary return tu_min16(packet_size, max_depth); - } else - { + } else { return tu_min16(data_count, max_depth); } } @@ -2897,13 +1977,11 @@ static uint16_t audiod_tx_packet_size(const uint16_t* norminal_size, uint16_t da #endif // No security checks here - internal function only which should always succeed -static uint8_t audiod_get_audio_fct_idx(audiod_function_t * audio) -{ - for (uint8_t cnt=0; cnt < CFG_TUD_AUDIO; cnt++) - { +static uint8_t audiod_get_audio_fct_idx(audiod_function_t *audio) { + for (uint8_t cnt = 0; cnt < CFG_TUD_AUDIO; cnt++) { if (&_audiod_fct[cnt] == audio) return cnt; } return 0; } -#endif //CFG_TUD_ENABLED && CFG_TUD_AUDIO +#endif // (CFG_TUD_ENABLED && CFG_TUD_AUDIO) diff --git a/src/class/audio/audio_device.h b/src/class/audio/audio_device.h index ae253f49d..603535b2a 100644 --- a/src/class/audio/audio_device.h +++ b/src/class/audio/audio_device.h @@ -203,152 +203,8 @@ #define CFG_TUD_AUDIO_ENABLE_INTERRUPT_EP 0 // Feedback - 0 or 1 #endif -// Use software encoding/decoding - -// The software coding feature of the driver is not mandatory. It is useful if, for instance, you have two I2S streams which need to be interleaved -// into a single PCM stream as SAMPLE_1 | SAMPLE_2 | SAMPLE_3 | SAMPLE_4. -// -// Currently, only PCM type I encoding/decoding is supported! -// -// If the coding feature is to be used, support FIFOs need to be configured. Their sizes and numbers are defined below. - -// Encoding/decoding is done in software and thus time consuming. If you can encode/decode your stream more efficiently do not use the -// support FIFOs but write/read directly into/from the EP_X_SW_BUFFER_FIFOs using -// - tud_audio_n_write() or -// - tud_audio_n_read(). -// To write/read to/from the support FIFOs use -// - tud_audio_n_write_support_ff() or -// - tud_audio_n_read_support_ff(). -// -// The encoding/decoding format type done is defined below. -// -// The encoding/decoding starts when the private callback functions -// - audio_tx_done_cb() -// - audio_rx_done_cb() -// are invoked. If support FIFOs are used, the corresponding encoding/decoding functions are called from there. -// Once encoding/decoding is done the result is put directly into the EP_X_SW_BUFFER_FIFOs. You can use the public callback functions -// - tud_audio_tx_done_pre_load_cb() or tud_audio_tx_done_post_load_cb() -// - tud_audio_rx_done_pre_read_cb() or tud_audio_rx_done_post_read_cb() -// if you want to get informed what happened. -// -// If you don't use the support FIFOs you may use the public callback functions -// - tud_audio_tx_done_pre_load_cb() or tud_audio_tx_done_post_load_cb() -// - tud_audio_rx_done_pre_read_cb() or tud_audio_rx_done_post_read_cb() -// to write/read from/into the EP_X_SW_BUFFER_FIFOs at the right time. -// -// If you need a different encoding which is not support so far implement it in the -// - audio_tx_done_cb() -// - audio_rx_done_cb() -// functions. - -// Enable encoding/decodings - for these to work, support FIFOs need to be setup in appropriate numbers and size -// The actual coding parameters of active AS alternate interface is parsed from the descriptors - -// The item size of the FIFO is always fixed to one i.e. bytes! Furthermore, the actively used FIFO depth is reconfigured such that the depth is a multiple -// of the current sample size in order to avoid samples to get split up in case of a wrap in the FIFO ring buffer (depth = (max_depth / sample_sz) * sample_sz)! -// This is important to remind in case you use DMAs! If the sample sizes changes, the DMA MUST BE RECONFIGURED just like the FIFOs for a different depth!!! - -// For PCM encoding/decoding - -#ifndef CFG_TUD_AUDIO_ENABLE_ENCODING -#define CFG_TUD_AUDIO_ENABLE_ENCODING 0 -#endif - -#ifndef CFG_TUD_AUDIO_ENABLE_DECODING -#define CFG_TUD_AUDIO_ENABLE_DECODING 0 -#endif - -// This enabling allows to save the current coding parameters e.g. # of bytes per sample etc. - TYPE_I includes common PCM encoding -#ifndef CFG_TUD_AUDIO_ENABLE_TYPE_I_ENCODING -#define CFG_TUD_AUDIO_ENABLE_TYPE_I_ENCODING 0 -#endif - -#ifndef CFG_TUD_AUDIO_ENABLE_TYPE_I_DECODING -#define CFG_TUD_AUDIO_ENABLE_TYPE_I_DECODING 0 -#endif - -// Type I Coding parameters not given within UAC2 descriptors -// It would be possible to allow for a more flexible setting and not fix this parameter as done below. However, this is most often not needed and kept for later if really necessary. The more flexible setting could be implemented within set_interface(), however, how the values are saved per alternate setting is to be determined! -#if CFG_TUD_AUDIO_ENABLE_EP_IN && CFG_TUD_AUDIO_ENABLE_ENCODING && CFG_TUD_AUDIO_ENABLE_TYPE_I_ENCODING -#ifndef CFG_TUD_AUDIO_FUNC_1_CHANNEL_PER_FIFO_TX -#error You must tell the driver the number of channels per FIFO for the interleaved encoding! E.g. for an I2S interface having two channels, CHANNEL_PER_FIFO = 2 as the I2S stream having two channels is usually saved within one FIFO -#endif -#if CFG_TUD_AUDIO > 1 -#ifndef CFG_TUD_AUDIO_FUNC_2_CHANNEL_PER_FIFO_TX -#error You must tell the driver the number of channels per FIFO for the interleaved encoding! E.g. for an I2S interface having two channels, CHANNEL_PER_FIFO = 2 as the I2S stream having two channels is usually saved within one FIFO -#endif -#endif -#if CFG_TUD_AUDIO > 2 -#ifndef CFG_TUD_AUDIO_FUNC_3_CHANNEL_PER_FIFO_TX -#error You must tell the driver the number of channels per FIFO for the interleaved encoding! E.g. for an I2S interface having two channels, CHANNEL_PER_FIFO = 2 as the I2S stream having two channels is usually saved within one FIFO -#endif -#endif -#endif - -#if CFG_TUD_AUDIO_ENABLE_EP_OUT && CFG_TUD_AUDIO_ENABLE_DECODING && CFG_TUD_AUDIO_ENABLE_TYPE_I_DECODING -#ifndef CFG_TUD_AUDIO_FUNC_1_CHANNEL_PER_FIFO_RX -#error You must tell the driver the number of channels per FIFO for the interleaved encoding! E.g. for an I2S interface having two channels, CHANNEL_PER_FIFO = 2 as the I2S stream having two channels is usually saved within one FIFO -#endif -#if CFG_TUD_AUDIO > 1 -#ifndef CFG_TUD_AUDIO_FUNC_2_CHANNEL_PER_FIFO_RX -#error You must tell the driver the number of channels per FIFO for the interleaved encoding! E.g. for an I2S interface having two channels, CHANNEL_PER_FIFO = 2 as the I2S stream having two channels is usually saved within one FIFO -#endif -#endif -#if CFG_TUD_AUDIO > 2 -#ifndef CFG_TUD_AUDIO_FUNC_3_CHANNEL_PER_FIFO_RX -#error You must tell the driver the number of channels per FIFO for the interleaved encoding! E.g. for an I2S interface having two channels, CHANNEL_PER_FIFO = 2 as the I2S stream having two channels is usually saved within one FIFO -#endif -#endif -#endif - -// Remaining types not support so far - -// Number of support FIFOs to set up - multiple channels can be handled by one FIFO - very common is two channels per FIFO stemming from one I2S interface -#ifndef CFG_TUD_AUDIO_FUNC_1_N_TX_SUPP_SW_FIFO -#define CFG_TUD_AUDIO_FUNC_1_N_TX_SUPP_SW_FIFO 0 -#endif -#ifndef CFG_TUD_AUDIO_FUNC_2_N_TX_SUPP_SW_FIFO -#define CFG_TUD_AUDIO_FUNC_2_N_TX_SUPP_SW_FIFO 0 -#endif -#ifndef CFG_TUD_AUDIO_FUNC_3_N_TX_SUPP_SW_FIFO -#define CFG_TUD_AUDIO_FUNC_3_N_TX_SUPP_SW_FIFO 0 -#endif - -#ifndef CFG_TUD_AUDIO_FUNC_1_N_RX_SUPP_SW_FIFO -#define CFG_TUD_AUDIO_FUNC_1_N_RX_SUPP_SW_FIFO 0 -#endif -#ifndef CFG_TUD_AUDIO_FUNC_2_N_RX_SUPP_SW_FIFO -#define CFG_TUD_AUDIO_FUNC_2_N_RX_SUPP_SW_FIFO 0 -#endif -#ifndef CFG_TUD_AUDIO_FUNC_3_N_RX_SUPP_SW_FIFO -#define CFG_TUD_AUDIO_FUNC_3_N_RX_SUPP_SW_FIFO 0 -#endif - -// Size of support FIFOs IN BYTES - if size > 0 there are as many FIFOs set up as CFG_TUD_AUDIO_FUNC_X_N_TX_SUPP_SW_FIFO and CFG_TUD_AUDIO_FUNC_X_N_RX_SUPP_SW_FIFO -#ifndef CFG_TUD_AUDIO_FUNC_1_TX_SUPP_SW_FIFO_SZ -#define CFG_TUD_AUDIO_FUNC_1_TX_SUPP_SW_FIFO_SZ 0 // FIFO size - minimum size: ceil(f_s/1000) * max(# of TX channels) / (# of TX support FIFOs) * max(# of bytes per sample) -#endif -#ifndef CFG_TUD_AUDIO_FUNC_2_TX_SUPP_SW_FIFO_SZ -#define CFG_TUD_AUDIO_FUNC_2_TX_SUPP_SW_FIFO_SZ 0 -#endif -#ifndef CFG_TUD_AUDIO_FUNC_3_TX_SUPP_SW_FIFO_SZ -#define CFG_TUD_AUDIO_FUNC_3_TX_SUPP_SW_FIFO_SZ 0 -#endif - -#ifndef CFG_TUD_AUDIO_FUNC_1_RX_SUPP_SW_FIFO_SZ -#define CFG_TUD_AUDIO_FUNC_1_RX_SUPP_SW_FIFO_SZ 0 // FIFO size - minimum size: ceil(f_s/1000) * max(# of RX channels) / (# of RX support FIFOs) * max(# of bytes per sample) -#endif -#ifndef CFG_TUD_AUDIO_FUNC_2_RX_SUPP_SW_FIFO_SZ -#define CFG_TUD_AUDIO_FUNC_2_RX_SUPP_SW_FIFO_SZ 0 -#endif -#ifndef CFG_TUD_AUDIO_FUNC_3_RX_SUPP_SW_FIFO_SZ -#define CFG_TUD_AUDIO_FUNC_3_RX_SUPP_SW_FIFO_SZ 0 -#endif - -//static_assert(sizeof(tud_audio_desc_lengths) != CFG_TUD_AUDIO, "Supply audio function descriptor pack length!"); - -// Supported types of this driver: -// AUDIO_DATA_FORMAT_TYPE_I_PCM - Required definitions: CFG_TUD_AUDIO_N_CHANNELS and CFG_TUD_AUDIO_BYTES_PER_CHANNEL +// Audio control interrupt EP - 6 Bytes according to UAC 2 specification (p. 74) +#define CFG_TUD_AUDIO_INTERRUPT_EP_SZ 6 #ifdef __cplusplus extern "C" { @@ -365,38 +221,23 @@ extern "C" { //--------------------------------------------------------------------+ bool tud_audio_n_mounted (uint8_t func_id); -#if CFG_TUD_AUDIO_ENABLE_EP_OUT && !CFG_TUD_AUDIO_ENABLE_DECODING +#if CFG_TUD_AUDIO_ENABLE_EP_OUT uint16_t tud_audio_n_available (uint8_t func_id); uint16_t tud_audio_n_read (uint8_t func_id, void* buffer, uint16_t bufsize); bool tud_audio_n_clear_ep_out_ff (uint8_t func_id); // Delete all content in the EP OUT FIFO tu_fifo_t* tud_audio_n_get_ep_out_ff (uint8_t func_id); #endif -#if CFG_TUD_AUDIO_ENABLE_EP_OUT && CFG_TUD_AUDIO_ENABLE_DECODING -bool tud_audio_n_clear_rx_support_ff (uint8_t func_id, uint8_t ff_idx); // Delete all content in the support RX FIFOs -uint16_t tud_audio_n_available_support_ff (uint8_t func_id, uint8_t ff_idx); -uint16_t tud_audio_n_read_support_ff (uint8_t func_id, uint8_t ff_idx, void* buffer, uint16_t bufsize); -tu_fifo_t* tud_audio_n_get_rx_support_ff (uint8_t func_id, uint8_t ff_idx); -#endif - -#if CFG_TUD_AUDIO_ENABLE_EP_IN && !CFG_TUD_AUDIO_ENABLE_ENCODING +#if CFG_TUD_AUDIO_ENABLE_EP_IN uint16_t tud_audio_n_write (uint8_t func_id, const void * data, uint16_t len); bool tud_audio_n_clear_ep_in_ff (uint8_t func_id); // Delete all content in the EP IN FIFO tu_fifo_t* tud_audio_n_get_ep_in_ff (uint8_t func_id); #endif -#if CFG_TUD_AUDIO_ENABLE_EP_IN && CFG_TUD_AUDIO_ENABLE_ENCODING -uint16_t tud_audio_n_flush_tx_support_ff (uint8_t func_id); // Force all content in the support TX FIFOs to be written into EP SW FIFO -bool tud_audio_n_clear_tx_support_ff (uint8_t func_id, uint8_t ff_idx); -uint16_t tud_audio_n_write_support_ff (uint8_t func_id, uint8_t ff_idx, const void * data, uint16_t len); -tu_fifo_t* tud_audio_n_get_tx_support_ff (uint8_t func_id, uint8_t ff_idx); -#endif - #if CFG_TUD_AUDIO_ENABLE_INTERRUPT_EP bool tud_audio_int_n_write (uint8_t func_id, const audio_interrupt_data_t * data); #endif - //--------------------------------------------------------------------+ // Application API (Interface0) //--------------------------------------------------------------------+ @@ -405,35 +246,21 @@ static inline bool tud_audio_mounted (void); // RX API -#if CFG_TUD_AUDIO_ENABLE_EP_OUT && !CFG_TUD_AUDIO_ENABLE_DECODING +#if CFG_TUD_AUDIO_ENABLE_EP_OUT static inline uint16_t tud_audio_available (void); static inline bool tud_audio_clear_ep_out_ff (void); // Delete all content in the EP OUT FIFO static inline uint16_t tud_audio_read (void* buffer, uint16_t bufsize); static inline tu_fifo_t* tud_audio_get_ep_out_ff (void); #endif -#if CFG_TUD_AUDIO_ENABLE_EP_OUT && CFG_TUD_AUDIO_ENABLE_DECODING -static inline bool tud_audio_clear_rx_support_ff (uint8_t ff_idx); -static inline uint16_t tud_audio_available_support_ff (uint8_t ff_idx); -static inline uint16_t tud_audio_read_support_ff (uint8_t ff_idx, void* buffer, uint16_t bufsize); -static inline tu_fifo_t* tud_audio_get_rx_support_ff (uint8_t ff_idx); -#endif - // TX API -#if CFG_TUD_AUDIO_ENABLE_EP_IN && !CFG_TUD_AUDIO_ENABLE_ENCODING +#if CFG_TUD_AUDIO_ENABLE_EP_IN static inline uint16_t tud_audio_write (const void * data, uint16_t len); static inline bool tud_audio_clear_ep_in_ff (void); static inline tu_fifo_t* tud_audio_get_ep_in_ff (void); #endif -#if CFG_TUD_AUDIO_ENABLE_EP_IN && CFG_TUD_AUDIO_ENABLE_ENCODING -static inline uint16_t tud_audio_flush_tx_support_ff (void); -static inline uint16_t tud_audio_clear_tx_support_ff (uint8_t ff_idx); -static inline uint16_t tud_audio_write_support_ff (uint8_t ff_idx, const void * data, uint16_t len); -static inline tu_fifo_t* tud_audio_get_tx_support_ff (uint8_t ff_idx); -#endif - // INT CTR API #if CFG_TUD_AUDIO_ENABLE_INTERRUPT_EP @@ -590,7 +417,7 @@ static inline bool tud_audio_mounted(void) // RX API -#if CFG_TUD_AUDIO_ENABLE_EP_OUT && !CFG_TUD_AUDIO_ENABLE_DECODING +#if CFG_TUD_AUDIO_ENABLE_EP_OUT static inline uint16_t tud_audio_available(void) { @@ -614,33 +441,9 @@ static inline tu_fifo_t* tud_audio_get_ep_out_ff(void) #endif -#if CFG_TUD_AUDIO_ENABLE_EP_OUT && CFG_TUD_AUDIO_ENABLE_DECODING - -static inline bool tud_audio_clear_rx_support_ff(uint8_t ff_idx) -{ - return tud_audio_n_clear_rx_support_ff(0, ff_idx); -} - -static inline uint16_t tud_audio_available_support_ff(uint8_t ff_idx) -{ - return tud_audio_n_available_support_ff(0, ff_idx); -} - -static inline uint16_t tud_audio_read_support_ff(uint8_t ff_idx, void* buffer, uint16_t bufsize) -{ - return tud_audio_n_read_support_ff(0, ff_idx, buffer, bufsize); -} - -static inline tu_fifo_t* tud_audio_get_rx_support_ff(uint8_t ff_idx) -{ - return tud_audio_n_get_rx_support_ff(0, ff_idx); -} - -#endif - // TX API -#if CFG_TUD_AUDIO_ENABLE_EP_IN && !CFG_TUD_AUDIO_ENABLE_ENCODING +#if CFG_TUD_AUDIO_ENABLE_EP_IN static inline uint16_t tud_audio_write(const void * data, uint16_t len) { @@ -659,30 +462,6 @@ static inline tu_fifo_t* tud_audio_get_ep_in_ff(void) #endif -#if CFG_TUD_AUDIO_ENABLE_EP_IN && CFG_TUD_AUDIO_ENABLE_ENCODING - -static inline uint16_t tud_audio_flush_tx_support_ff(void) -{ - return tud_audio_n_flush_tx_support_ff(0); -} - -static inline uint16_t tud_audio_clear_tx_support_ff(uint8_t ff_idx) -{ - return tud_audio_n_clear_tx_support_ff(0, ff_idx); -} - -static inline uint16_t tud_audio_write_support_ff(uint8_t ff_idx, const void * data, uint16_t len) -{ - return tud_audio_n_write_support_ff(0, ff_idx, data, len); -} - -static inline tu_fifo_t* tud_audio_get_tx_support_ff(uint8_t ff_idx) -{ - return tud_audio_n_get_tx_support_ff(0, ff_idx); -} - -#endif - #if CFG_TUD_AUDIO_ENABLE_INTERRUPT_EP static inline bool tud_audio_int_write(const audio_interrupt_data_t * data) { diff --git a/src/class/cdc/cdc.h b/src/class/cdc/cdc.h index f92ab9231..a403d77fa 100644 --- a/src/class/cdc/cdc.h +++ b/src/class/cdc/cdc.h @@ -192,6 +192,11 @@ typedef enum { CDC_LINE_CODING_STOP_BITS_2 = 2, // 2 bits } cdc_line_coding_stopbits_t; +#define CDC_LINE_CODING_STOP_BITS_TEXT(STOP_BITS) ( \ + STOP_BITS == CDC_LINE_CODING_STOP_BITS_1 ? "1" : \ + STOP_BITS == CDC_LINE_CODING_STOP_BITS_1_5 ? "1.5" : \ + STOP_BITS == CDC_LINE_CODING_STOP_BITS_2 ? "2" : "?" ) + // TODO Backward compatible for typos. Maybe removed in the future release #define CDC_LINE_CONDING_STOP_BITS_1 CDC_LINE_CODING_STOP_BITS_1 #define CDC_LINE_CONDING_STOP_BITS_1_5 CDC_LINE_CODING_STOP_BITS_1_5 @@ -205,6 +210,13 @@ typedef enum { CDC_LINE_CODING_PARITY_SPACE = 4, } cdc_line_coding_parity_t; +#define CDC_LINE_CODING_PARITY_CHAR(PARITY) ( \ + PARITY == CDC_LINE_CODING_PARITY_NONE ? 'N' : \ + PARITY == CDC_LINE_CODING_PARITY_ODD ? 'O' : \ + PARITY == CDC_LINE_CODING_PARITY_EVEN ? 'E' : \ + PARITY == CDC_LINE_CODING_PARITY_MARK ? 'M' : \ + PARITY == CDC_LINE_CODING_PARITY_SPACE ? 'S' : '?' ) + //--------------------------------------------------------------------+ // Management Element Notification (Notification Endpoint) //--------------------------------------------------------------------+ @@ -392,8 +404,7 @@ static inline uint8_t cdc_functional_desc_typeof(uint8_t const * p_desc) //--------------------------------------------------------------------+ // Requests //--------------------------------------------------------------------+ -typedef struct TU_ATTR_PACKED -{ +typedef struct TU_ATTR_PACKED { uint32_t bit_rate; uint8_t stop_bits; ///< 0: 1 stop bit - 1: 1.5 stop bits - 2: 2 stop bits uint8_t parity; ///< 0: None - 1: Odd - 2: Even - 3: Mark - 4: Space @@ -402,15 +413,16 @@ typedef struct TU_ATTR_PACKED TU_VERIFY_STATIC(sizeof(cdc_line_coding_t) == 7, "size is not correct"); -typedef struct TU_ATTR_PACKED -{ - uint16_t dtr : 1; - uint16_t rts : 1; - uint16_t : 6; - uint16_t : 8; +typedef union TU_ATTR_PACKED { + struct { + uint8_t dtr : 1; + uint8_t rts : 1; + uint8_t : 6; + }; + uint8_t value; } cdc_line_control_state_t; -TU_VERIFY_STATIC(sizeof(cdc_line_control_state_t) == 2, "size is not correct"); +TU_VERIFY_STATIC(sizeof(cdc_line_control_state_t) == 1, "size is not correct"); //--------------------------------------------------------------------+ // Notifications diff --git a/src/class/cdc/cdc_device.c b/src/class/cdc/cdc_device.c index 9fbe66b1a..786c3aa55 100644 --- a/src/class/cdc/cdc_device.c +++ b/src/class/cdc/cdc_device.c @@ -84,7 +84,7 @@ typedef struct { static cdcd_interface_t _cdcd_itf[CFG_TUD_CDC]; CFG_TUD_MEM_SECTION static cdcd_epbuf_t _cdcd_epbuf[CFG_TUD_CDC]; -static tud_cdc_configure_fifo_t _cdcd_fifo_cfg; +static tud_cdc_configure_t _cdcd_cfg = TUD_CDC_CONFIGURE_DEFAULT(); static bool _prep_out_transaction(uint8_t itf) { const uint8_t rhport = 0; @@ -121,9 +121,9 @@ static bool _prep_out_transaction(uint8_t itf) { // APPLICATION API //--------------------------------------------------------------------+ -bool tud_cdc_configure_fifo(const tud_cdc_configure_fifo_t* cfg) { - TU_VERIFY(cfg); - _cdcd_fifo_cfg = (*cfg); +bool tud_cdc_configure(const tud_cdc_configure_t* driver_cfg) { + TU_VERIFY(driver_cfg); + _cdcd_cfg = *driver_cfg; return true; } @@ -198,7 +198,7 @@ void tud_cdc_n_read_flush(uint8_t itf) { //--------------------------------------------------------------------+ uint32_t tud_cdc_n_write(uint8_t itf, const void* buffer, uint32_t bufsize) { cdcd_interface_t* p_cdc = &_cdcd_itf[itf]; - uint16_t ret = tu_fifo_write_n(&p_cdc->tx_ff, buffer, (uint16_t) TU_MIN(bufsize, UINT16_MAX)); + uint16_t wr_count = tu_fifo_write_n(&p_cdc->tx_ff, buffer, (uint16_t) TU_MIN(bufsize, UINT16_MAX)); // flush if queue more than packet size if (tu_fifo_count(&p_cdc->tx_ff) >= BULK_PACKET_SIZE @@ -209,7 +209,7 @@ uint32_t tud_cdc_n_write(uint8_t itf, const void* buffer, uint32_t bufsize) { tud_cdc_n_write_flush(itf); } - return ret; + return wr_count; } uint32_t tud_cdc_n_write_flush(uint8_t itf) { @@ -256,8 +256,6 @@ bool tud_cdc_n_write_clear(uint8_t itf) { //--------------------------------------------------------------------+ void cdcd_init(void) { tu_memclr(_cdcd_itf, sizeof(_cdcd_itf)); - tu_memclr(&_cdcd_fifo_cfg, sizeof(_cdcd_fifo_cfg)); - for (uint8_t i = 0; i < CFG_TUD_CDC; i++) { cdcd_interface_t* p_cdc = &_cdcd_itf[i]; @@ -272,10 +270,10 @@ void cdcd_init(void) { // Config RX fifo tu_fifo_config(&p_cdc->rx_ff, p_cdc->rx_ff_buf, TU_ARRAY_SIZE(p_cdc->rx_ff_buf), 1, false); - // Config TX fifo as overwritable at initialization and will be changed to non-overwritable - // if terminal supports DTR bit. Without DTR we do not know if data is actually polled by terminal. - // In this way, the most current data is prioritized. - tu_fifo_config(&p_cdc->tx_ff, p_cdc->tx_ff_buf, TU_ARRAY_SIZE(p_cdc->tx_ff_buf), 1, true); + // TX fifo can be configured to change to overwritable if not connected (DTR bit not set). Without DTR we do not + // know if data is actually polled by terminal. This way the most current data is prioritized. + // Default: is overwritable + tu_fifo_config(&p_cdc->tx_ff, p_cdc->tx_ff_buf, TU_ARRAY_SIZE(p_cdc->tx_ff_buf), 1, _cdcd_cfg.tx_overwritabe_if_not_connected); #if OSAL_MUTEX_REQUIRED osal_mutex_t mutex_rd = osal_mutex_create(&p_cdc->rx_ff_mutex); @@ -317,13 +315,13 @@ void cdcd_reset(uint8_t rhport) { cdcd_interface_t* p_cdc = &_cdcd_itf[i]; tu_memclr(p_cdc, ITF_MEM_RESET_SIZE); - if (!_cdcd_fifo_cfg.rx_persistent) { + if (!_cdcd_cfg.rx_persistent) { tu_fifo_clear(&p_cdc->rx_ff); } - if (!_cdcd_fifo_cfg.tx_persistent) { + if (!_cdcd_cfg.tx_persistent) { tu_fifo_clear(&p_cdc->tx_ff); } - tu_fifo_set_overwritable(&p_cdc->tx_ff, true); + tu_fifo_set_overwritable(&p_cdc->tx_ff, _cdcd_cfg.tx_overwritabe_if_not_connected); } } @@ -438,8 +436,12 @@ bool cdcd_control_xfer_cb(uint8_t rhport, uint8_t stage, const tusb_control_requ p_cdc->line_state = (uint8_t) request->wValue; - // Disable fifo overwriting if DTR bit is set - tu_fifo_set_overwritable(&p_cdc->tx_ff, !dtr); + // If enabled: fifo overwriting is disabled if DTR bit is set and vice versa + if (_cdcd_cfg.tx_overwritabe_if_not_connected) { + tu_fifo_set_overwritable(&p_cdc->tx_ff, !dtr); + } else { + tu_fifo_set_overwritable(&p_cdc->tx_ff, false); + } TU_LOG_DRV(" Set Control Line State: DTR = %d, RTS = %d\r\n", dtr, rts); @@ -520,7 +522,7 @@ bool cdcd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_ // xferred_bytes is multiple of EP Packet size and not zero if (!tu_fifo_count(&p_cdc->tx_ff) && xferred_bytes && (0 == (xferred_bytes & (BULK_PACKET_SIZE - 1)))) { if (usbd_edpt_claim(rhport, p_cdc->ep_in)) { - usbd_edpt_xfer(rhport, p_cdc->ep_in, NULL, 0); + TU_ASSERT(usbd_edpt_xfer(rhport, p_cdc->ep_in, NULL, 0)); } } } diff --git a/src/class/cdc/cdc_device.h b/src/class/cdc/cdc_device.h index 0f7dcc856..f6fa5abf8 100644 --- a/src/class/cdc/cdc_device.h +++ b/src/class/cdc/cdc_device.h @@ -48,14 +48,24 @@ //--------------------------------------------------------------------+ // Driver Configuration //--------------------------------------------------------------------+ - typedef struct TU_ATTR_PACKED { - uint8_t rx_persistent : 1; // keep rx fifo on bus reset or disconnect - uint8_t tx_persistent : 1; // keep tx fifo on bus reset or disconnect -} tud_cdc_configure_fifo_t; + uint8_t rx_persistent : 1; // keep rx fifo data even with bus reset or disconnect + uint8_t tx_persistent : 1; // keep tx fifo data even with reset or disconnect + uint8_t tx_overwritabe_if_not_connected : 1; // if not connected, tx fifo can be overwritten +} tud_cdc_configure_t; -// Configure CDC FIFOs behavior -bool tud_cdc_configure_fifo(tud_cdc_configure_fifo_t const* cfg); +#define TUD_CDC_CONFIGURE_DEFAULT() { \ + .rx_persistent = 0, \ + .tx_persistent = 0, \ + .tx_overwritabe_if_not_connected = 1, \ +} + +// Configure CDC driver behavior +bool tud_cdc_configure(const tud_cdc_configure_t* driver_cfg); + +// Backward compatible +#define tud_cdc_configure_fifo_t tud_cdc_configure_t +#define tud_cdc_configure_fifo tud_cdc_configure //--------------------------------------------------------------------+ // Application API (Multiple Ports) i.e. CFG_TUD_CDC > 1 diff --git a/src/class/cdc/cdc_host.c b/src/class/cdc/cdc_host.c index e817ebc7e..f4567fac4 100644 --- a/src/class/cdc/cdc_host.c +++ b/src/class/cdc/cdc_host.c @@ -24,7 +24,7 @@ * This file is part of the TinyUSB stack. * * Contribution - * - Heiko Kuester: CH34x support + * - Heiko Kuester: add support of CH34x & PL2303, improve support of FTDI & CP210x */ #include "tusb_option.h" @@ -35,13 +35,19 @@ #include "host/usbh_pvt.h" #include "cdc_host.h" +#include "serial/ftdi_sio.h" +#include "serial/cp210x.h" +#include "serial/ch34x.h" +#include "serial/pl2303.h" // Level where CFG_TUSB_DEBUG must be at least for this driver is logged #ifndef CFG_TUH_CDC_LOG_LEVEL - #define CFG_TUH_CDC_LOG_LEVEL CFG_TUH_LOG_LEVEL + #define CFG_TUH_CDC_LOG_LEVEL 2 #endif -#define TU_LOG_DRV(...) TU_LOG(CFG_TUH_CDC_LOG_LEVEL, __VA_ARGS__) +#define TU_LOG_DRV(...) TU_LOG(CFG_TUH_CDC_LOG_LEVEL, __VA_ARGS__) +#define TU_LOG_CDC(_cdc, _format, ...) TU_LOG_DRV("[:%u:%u] CDCh %s " _format "\r\n", _cdc->daddr, _cdc->bInterfaceNumber, \ + serial_drivers[_cdc->serial_drid].name, ##__VA_ARGS__) //--------------------------------------------------------------------+ // Host CDC Interface @@ -56,30 +62,40 @@ typedef struct { uint8_t ep_notif; uint8_t serial_drid; // Serial Driver ID bool mounted; // Enumeration is complete - cdc_acm_capability_t acm_capability; - TU_ATTR_ALIGNED(4) cdc_line_coding_t line_coding; // Baudrate, stop bits, parity, data width - uint8_t line_state; // DTR (bit0), RTS (bit1) + struct { + TU_ATTR_ALIGNED(4) cdc_line_coding_t coding; // Baudrate, stop bits, parity, data width + cdc_line_control_state_t control_state; // DTR, RTS + } line, requested_line; - #if CFG_TUH_CDC_FTDI || CFG_TUH_CDC_CP210X || CFG_TUH_CDC_CH34X - cdc_line_coding_t requested_line_coding; - // 1 byte padding - #endif + tuh_xfer_cb_t user_complete_cb; // required since we handle request internally first - tuh_xfer_cb_t user_control_cb; + union { + struct { + cdc_acm_capability_t capability; + } acm; + + #if CFG_TUH_CDC_FTDI + ftdi_private_t ftdi; + #endif + + #if CFG_TUH_CDC_PL2303 + pl2303_private_t pl2303; + #endif + }; struct { tu_edpt_stream_t tx; tu_edpt_stream_t rx; uint8_t tx_ff_buf[CFG_TUH_CDC_TX_BUFSIZE]; - uint8_t rx_ff_buf[CFG_TUH_CDC_TX_BUFSIZE]; + uint8_t rx_ff_buf[CFG_TUH_CDC_RX_BUFSIZE]; } stream; } cdch_interface_t; typedef struct { TUH_EPBUF_DEF(tx, CFG_TUH_CDC_TX_EPSIZE); - TUH_EPBUF_DEF(rx, CFG_TUH_CDC_TX_EPSIZE); + TUH_EPBUF_DEF(rx, CFG_TUH_CDC_RX_EPSIZE); } cdch_epbuf_t; static cdch_interface_t cdch_data[CFG_TUH_CDC]; @@ -89,58 +105,70 @@ CFG_TUH_MEM_SECTION static cdch_epbuf_t cdch_epbuf[CFG_TUH_CDC]; // Serial Driver //--------------------------------------------------------------------+ -//------------- ACM prototypes -------------// -static bool acm_open(uint8_t daddr, tusb_desc_interface_t const *itf_desc, uint16_t max_len); -static void acm_process_config(tuh_xfer_t* xfer); +// General driver +static void cdch_process_set_config(tuh_xfer_t *xfer); +static void cdch_process_line_state_on_enum(tuh_xfer_t *xfer); // invoked after set config is processed +static void cdch_internal_control_complete(tuh_xfer_t *xfer); +static void cdch_set_line_coding_stage1_baudrate_complete(tuh_xfer_t *xfer); +static void cdch_set_line_coding_stage2_data_format_complete(tuh_xfer_t *xfer); -static bool acm_set_baudrate(cdch_interface_t* p_cdc, uint32_t baudrate, tuh_xfer_cb_t complete_cb, uintptr_t user_data); -static bool acm_set_data_format(cdch_interface_t* p_cdc, uint8_t stop_bits, uint8_t parity, uint8_t data_bits, tuh_xfer_cb_t complete_cb, uintptr_t user_data); -static bool acm_set_line_coding(cdch_interface_t* p_cdc, cdc_line_coding_t const* line_coding, tuh_xfer_cb_t complete_cb, uintptr_t user_data); -static bool acm_set_control_line_state(cdch_interface_t* p_cdc, uint16_t line_state, tuh_xfer_cb_t complete_cb, uintptr_t user_data); +//------------- ACM prototypes -------------// +static bool acm_open(uint8_t daddr, tusb_desc_interface_t const * itf_desc, uint16_t max_len); +static bool acm_process_set_config(cdch_interface_t *p_cdc, tuh_xfer_t *xfer); +static void acm_internal_control_complete(cdch_interface_t *p_cdc, tuh_xfer_t *xfer); + +static bool acm_set_line_coding(cdch_interface_t * p_cdc, tuh_xfer_cb_t complete_cb, uintptr_t user_data); +static bool acm_set_control_line_state(cdch_interface_t * p_cdc, tuh_xfer_cb_t complete_cb, uintptr_t user_data); //------------- FTDI prototypes -------------// #if CFG_TUH_CDC_FTDI -#include "serial/ftdi_sio.h" - static uint16_t const ftdi_vid_pid_list[][2] = {CFG_TUH_CDC_FTDI_VID_PID_LIST}; +static bool ftdi_open(uint8_t daddr, const tusb_desc_interface_t * itf_desc, uint16_t max_len); +static bool ftdi_proccess_set_config(cdch_interface_t *p_cdc, tuh_xfer_t *xfer); +static void ftdi_internal_control_complete(cdch_interface_t* p_cdc, tuh_xfer_t *xfer); -static bool ftdi_open(uint8_t daddr, const tusb_desc_interface_t *itf_desc, uint16_t max_len); -static void ftdi_process_config(tuh_xfer_t* xfer); - -static bool ftdi_sio_set_baudrate(cdch_interface_t* p_cdc, uint32_t baudrate, tuh_xfer_cb_t complete_cb, uintptr_t user_data); -static bool ftdi_set_data_format(cdch_interface_t* p_cdc, uint8_t stop_bits, uint8_t parity, uint8_t data_bits, tuh_xfer_cb_t complete_cb, uintptr_t user_data); -static bool ftdi_set_line_coding(cdch_interface_t* p_cdc, cdc_line_coding_t const* line_coding, tuh_xfer_cb_t complete_cb, uintptr_t user_data); -static bool ftdi_sio_set_modem_ctrl(cdch_interface_t* p_cdc, uint16_t line_state, tuh_xfer_cb_t complete_cb, uintptr_t user_data); +static bool ftdi_set_baudrate(cdch_interface_t * p_cdc, tuh_xfer_cb_t complete_cb, uintptr_t user_data); +static bool ftdi_set_data_format(cdch_interface_t * p_cdc, tuh_xfer_cb_t complete_cb, uintptr_t user_data); +static bool ftdi_set_modem_ctrl(cdch_interface_t * p_cdc, tuh_xfer_cb_t complete_cb, uintptr_t user_data); #endif //------------- CP210X prototypes -------------// #if CFG_TUH_CDC_CP210X -#include "serial/cp210x.h" - static uint16_t const cp210x_vid_pid_list[][2] = {CFG_TUH_CDC_CP210X_VID_PID_LIST}; -static bool cp210x_open(uint8_t daddr, tusb_desc_interface_t const *itf_desc, uint16_t max_len); -static void cp210x_process_config(tuh_xfer_t* xfer); +static bool cp210x_open(uint8_t daddr, tusb_desc_interface_t const * itf_desc, uint16_t max_len); +static bool cp210x_process_set_config(cdch_interface_t *p_cdc, tuh_xfer_t *xfer); +static void cp210x_internal_control_complete(cdch_interface_t *p_cdc, tuh_xfer_t *xfer); -static bool cp210x_set_baudrate(cdch_interface_t* p_cdc, uint32_t baudrate, tuh_xfer_cb_t complete_cb, uintptr_t user_data); -static bool cp210x_set_data_format(cdch_interface_t* p_cdc, uint8_t stop_bits, uint8_t parity, uint8_t data_bits, tuh_xfer_cb_t complete_cb, uintptr_t user_data); -static bool cp210x_set_line_coding(cdch_interface_t* p_cdc, cdc_line_coding_t const* line_coding, tuh_xfer_cb_t complete_cb, uintptr_t user_data); -static bool cp210x_set_modem_ctrl(cdch_interface_t* p_cdc, uint16_t line_state, tuh_xfer_cb_t complete_cb, uintptr_t user_data); +static bool cp210x_set_baudrate(cdch_interface_t * p_cdc, tuh_xfer_cb_t complete_cb, uintptr_t user_data); +static bool cp210x_set_data_format(cdch_interface_t * p_cdc, tuh_xfer_cb_t complete_cb, uintptr_t user_data); +static bool cp210x_set_modem_ctrl(cdch_interface_t * p_cdc, tuh_xfer_cb_t complete_cb, uintptr_t user_data); #endif //------------- CH34x prototypes -------------// #if CFG_TUH_CDC_CH34X -#include "serial/ch34x.h" - static uint16_t const ch34x_vid_pid_list[][2] = {CFG_TUH_CDC_CH34X_VID_PID_LIST}; -static bool ch34x_open(uint8_t daddr, tusb_desc_interface_t const* itf_desc, uint16_t max_len); -static void ch34x_process_config(tuh_xfer_t* xfer); +static bool ch34x_open(uint8_t daddr, tusb_desc_interface_t const * itf_desc, uint16_t max_len); +static bool ch34x_process_set_config(cdch_interface_t *p_cdc, tuh_xfer_t *xfer); +static void ch34x_internal_control_complete(cdch_interface_t *p_cdc, tuh_xfer_t *xfer); -static bool ch34x_set_baudrate(cdch_interface_t* p_cdc, uint32_t baudrate, tuh_xfer_cb_t complete_cb, uintptr_t user_data); -static bool ch34x_set_data_format(cdch_interface_t* p_cdc, uint8_t stop_bits, uint8_t parity, uint8_t data_bits, tuh_xfer_cb_t complete_cb, uintptr_t user_data); -static bool ch34x_set_line_coding(cdch_interface_t* p_cdc, cdc_line_coding_t const* line_coding, tuh_xfer_cb_t complete_cb, uintptr_t user_data); -static bool ch34x_set_modem_ctrl(cdch_interface_t* p_cdc, uint16_t line_state, tuh_xfer_cb_t complete_cb, uintptr_t user_data); +static bool ch34x_set_baudrate(cdch_interface_t * p_cdc, tuh_xfer_cb_t complete_cb, uintptr_t user_data); +static bool ch34x_set_data_format(cdch_interface_t * p_cdc, tuh_xfer_cb_t complete_cb, uintptr_t user_data); +static bool ch34x_set_modem_ctrl(cdch_interface_t * p_cdc, tuh_xfer_cb_t complete_cb, uintptr_t user_data); +#endif + +//------------- PL2303 prototypes -------------// +#if CFG_TUH_CDC_PL2303 +static uint16_t const pl2303_vid_pid_list[][2] = {CFG_TUH_CDC_PL2303_VID_PID_LIST}; +static const pl2303_type_data_t pl2303_type_data[PL2303_TYPE_COUNT] = {PL2303_TYPE_DATA}; + +static bool pl2303_open(uint8_t daddr, tusb_desc_interface_t const * itf_desc, uint16_t max_len); +static bool pl2303_process_set_config(cdch_interface_t *p_cdc, tuh_xfer_t *xfer); +static void pl2303_internal_control_complete(cdch_interface_t *p_cdc, tuh_xfer_t *xfer); + +static bool pl2303_set_line_coding(cdch_interface_t * p_cdc, tuh_xfer_cb_t complete_cb, uintptr_t user_data); +static bool pl2303_set_modem_ctrl(cdch_interface_t * p_cdc, tuh_xfer_cb_t complete_cb, uintptr_t user_data); #endif //------------- Common -------------// @@ -159,31 +187,48 @@ enum { SERIAL_DRIVER_CH34X, #endif +#if CFG_TUH_CDC_PL2303 + SERIAL_DRIVER_PL2303, +#endif + SERIAL_DRIVER_COUNT }; +typedef bool (*serial_driver_func_t)(cdch_interface_t * p_cdc, tuh_xfer_cb_t complete_cb, uintptr_t user_data); + typedef struct { uint16_t const (*vid_pid_list)[2]; uint16_t const vid_pid_count; - bool (*const open)(uint8_t daddr, const tusb_desc_interface_t *itf_desc, uint16_t max_len); - void (*const process_set_config)(tuh_xfer_t* xfer); - bool (*const set_control_line_state)(cdch_interface_t* p_cdc, uint16_t line_state, tuh_xfer_cb_t complete_cb, uintptr_t user_data); - bool (*const set_baudrate)(cdch_interface_t* p_cdc, uint32_t baudrate, tuh_xfer_cb_t complete_cb, uintptr_t user_data); - bool (*const set_data_format)(cdch_interface_t* p_cdc, uint8_t stop_bits, uint8_t parity, uint8_t data_bits, tuh_xfer_cb_t complete_cb, uintptr_t user_data); - bool (*const set_line_coding)(cdch_interface_t* p_cdc, cdc_line_coding_t const* line_coding, tuh_xfer_cb_t complete_cb, uintptr_t user_data); + bool (*const open)(uint8_t daddr, const tusb_desc_interface_t * itf_desc, uint16_t max_len); + bool (*const process_set_config)(cdch_interface_t * p_cdc, tuh_xfer_t * xfer); + void (*const request_complete)(cdch_interface_t * p_cdc, tuh_xfer_t * xfer); // internal request complete handler to update line state + + serial_driver_func_t set_control_line_state, set_baudrate, set_data_format, set_line_coding; + + #if CFG_TUSB_DEBUG && CFG_TUSB_DEBUG >= CFG_TUH_CDC_LOG_LEVEL + const char * name; + #endif } cdch_serial_driver_t; +#if CFG_TUSB_DEBUG >= CFG_TUH_CDC_LOG_LEVEL + #define DRIVER_NAME_DECLARE(_str) .name = _str +#else + #define DRIVER_NAME_DECLARE(_str) +#endif + // Note driver list must be in the same order as SERIAL_DRIVER enum static const cdch_serial_driver_t serial_drivers[] = { { .vid_pid_list = NULL, .vid_pid_count = 0, .open = acm_open, - .process_set_config = acm_process_config, + .process_set_config = acm_process_set_config, + .request_complete = acm_internal_control_complete, .set_control_line_state = acm_set_control_line_state, - .set_baudrate = acm_set_baudrate, - .set_data_format = acm_set_data_format, - .set_line_coding = acm_set_line_coding + .set_baudrate = acm_set_line_coding, + .set_data_format = acm_set_line_coding, + .set_line_coding = acm_set_line_coding, + DRIVER_NAME_DECLARE("ACM") }, #if CFG_TUH_CDC_FTDI @@ -191,11 +236,13 @@ static const cdch_serial_driver_t serial_drivers[] = { .vid_pid_list = ftdi_vid_pid_list, .vid_pid_count = TU_ARRAY_SIZE(ftdi_vid_pid_list), .open = ftdi_open, - .process_set_config = ftdi_process_config, - .set_control_line_state = ftdi_sio_set_modem_ctrl, - .set_baudrate = ftdi_sio_set_baudrate, + .process_set_config = ftdi_proccess_set_config, + .request_complete = ftdi_internal_control_complete, + .set_control_line_state = ftdi_set_modem_ctrl, + .set_baudrate = ftdi_set_baudrate, .set_data_format = ftdi_set_data_format, - .set_line_coding = ftdi_set_line_coding + .set_line_coding = NULL, // 2 stage set line coding + DRIVER_NAME_DECLARE("FTDI") }, #endif @@ -204,11 +251,13 @@ static const cdch_serial_driver_t serial_drivers[] = { .vid_pid_list = cp210x_vid_pid_list, .vid_pid_count = TU_ARRAY_SIZE(cp210x_vid_pid_list), .open = cp210x_open, - .process_set_config = cp210x_process_config, + .process_set_config = cp210x_process_set_config, + .request_complete = cp210x_internal_control_complete, .set_control_line_state = cp210x_set_modem_ctrl, .set_baudrate = cp210x_set_baudrate, .set_data_format = cp210x_set_data_format, - .set_line_coding = cp210x_set_line_coding + .set_line_coding = NULL, // 2 stage set line coding + DRIVER_NAME_DECLARE("CP210x") }, #endif @@ -217,13 +266,31 @@ static const cdch_serial_driver_t serial_drivers[] = { .vid_pid_list = ch34x_vid_pid_list, .vid_pid_count = TU_ARRAY_SIZE(ch34x_vid_pid_list), .open = ch34x_open, - .process_set_config = ch34x_process_config, + .process_set_config = ch34x_process_set_config, + .request_complete = ch34x_internal_control_complete, + .set_control_line_state = ch34x_set_modem_ctrl, .set_baudrate = ch34x_set_baudrate, .set_data_format = ch34x_set_data_format, - .set_line_coding = ch34x_set_line_coding + .set_line_coding = NULL, // 2 stage set line coding + DRIVER_NAME_DECLARE("CH34x") }, #endif + + #if CFG_TUH_CDC_PL2303 + { + .vid_pid_list = pl2303_vid_pid_list, + .vid_pid_count = TU_ARRAY_SIZE(pl2303_vid_pid_list), + .open = pl2303_open, + .process_set_config = pl2303_process_set_config, + .request_complete = pl2303_internal_control_complete, + .set_control_line_state = pl2303_set_modem_ctrl, + .set_baudrate = pl2303_set_line_coding, + .set_data_format = pl2303_set_line_coding, + .set_line_coding = pl2303_set_line_coding, + DRIVER_NAME_DECLARE("PL2303") + } + #endif }; TU_VERIFY_STATIC(TU_ARRAY_SIZE(serial_drivers) == SERIAL_DRIVER_COUNT, "Serial driver count mismatch"); @@ -232,17 +299,20 @@ TU_VERIFY_STATIC(TU_ARRAY_SIZE(serial_drivers) == SERIAL_DRIVER_COUNT, "Serial d // INTERNAL OBJECT & FUNCTION DECLARATION //--------------------------------------------------------------------+ -static inline cdch_interface_t* get_itf(uint8_t idx) { +TU_ATTR_ALWAYS_INLINE static inline cdch_interface_t * get_itf(uint8_t idx) { TU_ASSERT(idx < CFG_TUH_CDC, NULL); - cdch_interface_t* p_cdc = &cdch_data[idx]; - + cdch_interface_t * p_cdc = &cdch_data[idx]; return (p_cdc->daddr != 0) ? p_cdc : NULL; } +TU_ATTR_ALWAYS_INLINE static inline uint8_t get_idx_by_ptr(cdch_interface_t* p_cdc) { + return (uint8_t) (p_cdc - cdch_data); +} + static inline uint8_t get_idx_by_ep_addr(uint8_t daddr, uint8_t ep_addr) { for(uint8_t i=0; idaddr == daddr) && + cdch_interface_t * p_cdc = &cdch_data[i]; + if ((p_cdc->daddr == daddr) && (ep_addr == p_cdc->ep_notif || ep_addr == p_cdc->stream.rx.ep_addr || ep_addr == p_cdc->stream.tx.ep_addr)) { return i; } @@ -251,15 +321,67 @@ static inline uint8_t get_idx_by_ep_addr(uint8_t daddr, uint8_t ep_addr) { return TUSB_INDEX_INVALID_8; } -static cdch_interface_t* make_new_itf(uint8_t daddr, tusb_desc_interface_t const *itf_desc) { +// determine the interface from the completed transfer +static cdch_interface_t* get_itf_by_xfer(const tuh_xfer_t * xfer) { + TU_VERIFY(xfer->daddr != 0, NULL); + for(uint8_t i=0; idaddr == xfer->daddr) { + switch (p_cdc->serial_drid) { + #if CFG_TUH_CDC_CP210X + case SERIAL_DRIVER_CP210X: + #endif + case SERIAL_DRIVER_ACM: { + // Driver use wIndex for bInterfaceNumber + const uint8_t itf_num = (uint8_t) tu_le16toh(xfer->setup->wIndex); + if (p_cdc->bInterfaceNumber == itf_num) { + return p_cdc; + } + break; + } + + #if CFG_TUH_CDC_FTDI + case SERIAL_DRIVER_FTDI: { + // FTDI uses wIndex for channel number, if channel is 0 then it is the default channel + const uint8_t channel = (uint8_t) tu_le16toh(xfer->setup->wIndex); + if (p_cdc->ftdi.channel == 0 || p_cdc->ftdi.channel == channel) { + return p_cdc; + } + break; + } + #endif + + #if CFG_TUH_CDC_CH34X + case SERIAL_DRIVER_CH34X: + // ch34x has only one interface + return p_cdc; + #endif + + #if CFG_TUH_CDC_PL2303 + case SERIAL_DRIVER_PL2303: + // pl2303 has only one interface + return p_cdc; + #endif + + default: + break; + } + } + } + + return NULL; +} + +static cdch_interface_t * make_new_itf(uint8_t daddr, tusb_desc_interface_t const * itf_desc) { for(uint8_t i=0; idaddr = daddr; p_cdc->bInterfaceNumber = itf_desc->bInterfaceNumber; p_cdc->bInterfaceSubClass = itf_desc->bInterfaceSubClass; p_cdc->bInterfaceProtocol = itf_desc->bInterfaceProtocol; - p_cdc->line_state = 0; + p_cdc->line.coding = (cdc_line_coding_t) { 0, 0, 0, 0 }; + p_cdc->line.control_state.value = 0; return p_cdc; } } @@ -267,9 +389,7 @@ static cdch_interface_t* make_new_itf(uint8_t daddr, tusb_desc_interface_t const return NULL; } -static bool open_ep_stream_pair(cdch_interface_t* p_cdc , tusb_desc_endpoint_t const *desc_ep); -static void set_config_complete(cdch_interface_t * p_cdc, uint8_t idx, uint8_t itf_num); -static void cdch_internal_control_complete(tuh_xfer_t* xfer); +static bool open_ep_stream_pair(cdch_interface_t * p_cdc , tusb_desc_endpoint_t const *desc_ep); //--------------------------------------------------------------------+ // APPLICATION API @@ -277,21 +397,20 @@ static void cdch_internal_control_complete(tuh_xfer_t* xfer); uint8_t tuh_cdc_itf_get_index(uint8_t daddr, uint8_t itf_num) { for (uint8_t i = 0; i < CFG_TUH_CDC; i++) { - const cdch_interface_t* p_cdc = &cdch_data[i]; - if (p_cdc->daddr == daddr && p_cdc->bInterfaceNumber == itf_num) return i; + const cdch_interface_t * p_cdc = &cdch_data[i]; + if (p_cdc->daddr == daddr && p_cdc->bInterfaceNumber == itf_num) { return i; } } - return TUSB_INDEX_INVALID_8; } -bool tuh_cdc_itf_get_info(uint8_t idx, tuh_itf_info_t* info) { - cdch_interface_t* p_cdc = get_itf(idx); +bool tuh_cdc_itf_get_info(uint8_t idx, tuh_itf_info_t * info) { + cdch_interface_t * p_cdc = get_itf(idx); TU_VERIFY(p_cdc && info); info->daddr = p_cdc->daddr; - // re-construct descriptor - tusb_desc_interface_t* desc = &info->desc; + // re-construct interface descriptor + tusb_desc_interface_t * desc = &info->desc; desc->bLength = sizeof(tusb_desc_interface_t); desc->bDescriptorType = TUSB_DESC_INTERFACE; @@ -307,31 +426,22 @@ bool tuh_cdc_itf_get_info(uint8_t idx, tuh_itf_info_t* info) { } bool tuh_cdc_mounted(uint8_t idx) { - cdch_interface_t* p_cdc = get_itf(idx); + cdch_interface_t * p_cdc = get_itf(idx); TU_VERIFY(p_cdc); return p_cdc->mounted; } -bool tuh_cdc_get_dtr(uint8_t idx) { - cdch_interface_t* p_cdc = get_itf(idx); +bool tuh_cdc_get_control_line_state_local(uint8_t idx, uint16_t* line_state) { + cdch_interface_t * p_cdc = get_itf(idx); TU_VERIFY(p_cdc); - - return (p_cdc->line_state & CDC_CONTROL_LINE_STATE_DTR) ? true : false; + *line_state = p_cdc->line.control_state.value; + return true; } -bool tuh_cdc_get_rts(uint8_t idx) { - cdch_interface_t* p_cdc = get_itf(idx); +bool tuh_cdc_get_line_coding_local(uint8_t idx, cdc_line_coding_t * line_coding) { + cdch_interface_t * p_cdc = get_itf(idx); TU_VERIFY(p_cdc); - - return (p_cdc->line_state & CDC_CONTROL_LINE_STATE_RTS) ? true : false; -} - -bool tuh_cdc_get_local_line_coding(uint8_t idx, cdc_line_coding_t* line_coding) { - cdch_interface_t* p_cdc = get_itf(idx); - TU_VERIFY(p_cdc); - - *line_coding = p_cdc->line_coding; - + *line_coding = p_cdc->line.coding; return true; } @@ -339,31 +449,27 @@ bool tuh_cdc_get_local_line_coding(uint8_t idx, cdc_line_coding_t* line_coding) // Write //--------------------------------------------------------------------+ -uint32_t tuh_cdc_write(uint8_t idx, void const* buffer, uint32_t bufsize) { - cdch_interface_t* p_cdc = get_itf(idx); +uint32_t tuh_cdc_write(uint8_t idx, void const * buffer, uint32_t bufsize) { + cdch_interface_t * p_cdc = get_itf(idx); TU_VERIFY(p_cdc); - return tu_edpt_stream_write(p_cdc->daddr, &p_cdc->stream.tx, buffer, bufsize); } uint32_t tuh_cdc_write_flush(uint8_t idx) { - cdch_interface_t* p_cdc = get_itf(idx); + cdch_interface_t * p_cdc = get_itf(idx); TU_VERIFY(p_cdc); - return tu_edpt_stream_write_xfer(p_cdc->daddr, &p_cdc->stream.tx); } bool tuh_cdc_write_clear(uint8_t idx) { - cdch_interface_t* p_cdc = get_itf(idx); + cdch_interface_t * p_cdc = get_itf(idx); TU_VERIFY(p_cdc); - return tu_edpt_stream_clear(&p_cdc->stream.tx); } uint32_t tuh_cdc_write_available(uint8_t idx) { - cdch_interface_t* p_cdc = get_itf(idx); + cdch_interface_t * p_cdc = get_itf(idx); TU_VERIFY(p_cdc); - return tu_edpt_stream_write_available(p_cdc->daddr, &p_cdc->stream.tx); } @@ -371,29 +477,26 @@ uint32_t tuh_cdc_write_available(uint8_t idx) { // Read //--------------------------------------------------------------------+ -uint32_t tuh_cdc_read (uint8_t idx, void* buffer, uint32_t bufsize) { - cdch_interface_t* p_cdc = get_itf(idx); +uint32_t tuh_cdc_read (uint8_t idx, void * buffer, uint32_t bufsize) { + cdch_interface_t * p_cdc = get_itf(idx); TU_VERIFY(p_cdc); - return tu_edpt_stream_read(p_cdc->daddr, &p_cdc->stream.rx, buffer, bufsize); } uint32_t tuh_cdc_read_available(uint8_t idx) { - cdch_interface_t* p_cdc = get_itf(idx); + cdch_interface_t * p_cdc = get_itf(idx); TU_VERIFY(p_cdc); - return tu_edpt_stream_read_available(&p_cdc->stream.rx); } -bool tuh_cdc_peek(uint8_t idx, uint8_t* ch) { - cdch_interface_t* p_cdc = get_itf(idx); +bool tuh_cdc_peek(uint8_t idx, uint8_t * ch) { + cdch_interface_t * p_cdc = get_itf(idx); TU_VERIFY(p_cdc); - return tu_edpt_stream_peek(&p_cdc->stream.rx, ch); } bool tuh_cdc_read_clear (uint8_t idx) { - cdch_interface_t* p_cdc = get_itf(idx); + cdch_interface_t * p_cdc = get_itf(idx); TU_VERIFY(p_cdc); bool ret = tu_edpt_stream_clear(&p_cdc->stream.rx); @@ -405,218 +508,115 @@ bool tuh_cdc_read_clear (uint8_t idx) { // Control Endpoint API //--------------------------------------------------------------------+ -static void process_internal_control_complete(tuh_xfer_t* xfer, uint8_t itf_num) { - uint8_t idx = tuh_cdc_itf_get_index(xfer->daddr, itf_num); - cdch_interface_t* p_cdc = get_itf(idx); - TU_ASSERT(p_cdc, ); - uint16_t const value = tu_le16toh(xfer->setup->wValue); - - if (xfer->result == XFER_RESULT_SUCCESS) { - switch (p_cdc->serial_drid) { - case SERIAL_DRIVER_ACM: - switch (xfer->setup->bRequest) { - case CDC_REQUEST_SET_CONTROL_LINE_STATE: - p_cdc->line_state = (uint8_t) value; - break; - - case CDC_REQUEST_SET_LINE_CODING: { - uint16_t const len = tu_min16(sizeof(cdc_line_coding_t), tu_le16toh(xfer->setup->wLength)); - memcpy(&p_cdc->line_coding, xfer->buffer, len); - break; - } - - default: break; - } - break; - - #if CFG_TUH_CDC_FTDI - case SERIAL_DRIVER_FTDI: - switch (xfer->setup->bRequest) { - case FTDI_SIO_MODEM_CTRL: - p_cdc->line_state = (uint8_t) value; - break; - - case FTDI_SIO_SET_BAUD_RATE: - p_cdc->line_coding.bit_rate = p_cdc->requested_line_coding.bit_rate; - break; - - default: break; - } - break; - #endif - - #if CFG_TUH_CDC_CP210X - case SERIAL_DRIVER_CP210X: - switch(xfer->setup->bRequest) { - case CP210X_SET_MHS: - p_cdc->line_state = (uint8_t) value; - break; - - case CP210X_SET_BAUDRATE: { - uint32_t baudrate; - memcpy(&baudrate, xfer->buffer, sizeof(uint32_t)); - p_cdc->line_coding.bit_rate = tu_le32toh(baudrate); - break; - } - - default: break; - } - break; - #endif - - #if CFG_TUH_CDC_CH34X - case SERIAL_DRIVER_CH34X: - switch (xfer->setup->bRequest) { - case CH34X_REQ_WRITE_REG: - // register write request - switch (value) { - case CH34X_REG16_DIVISOR_PRESCALER: - // baudrate - p_cdc->line_coding.bit_rate = p_cdc->requested_line_coding.bit_rate; - break; - - case CH32X_REG16_LCR2_LCR: - // data format - p_cdc->line_coding.stop_bits = p_cdc->requested_line_coding.stop_bits; - p_cdc->line_coding.parity = p_cdc->requested_line_coding.parity; - p_cdc->line_coding.data_bits = p_cdc->requested_line_coding.data_bits; - break; - - default: break; - } - break; - - case CH34X_REQ_MODEM_CTRL: { - // set modem controls RTS/DTR request. Note: signals are inverted - uint16_t const modem_signal = ~value; - if (modem_signal & CH34X_BIT_RTS) { - p_cdc->line_state |= CDC_CONTROL_LINE_STATE_RTS; - } else { - p_cdc->line_state &= (uint8_t) ~CDC_CONTROL_LINE_STATE_RTS; - } - - if (modem_signal & CH34X_BIT_DTR) { - p_cdc->line_state |= CDC_CONTROL_LINE_STATE_DTR; - } else { - p_cdc->line_state &= (uint8_t) ~CDC_CONTROL_LINE_STATE_DTR; - } - break; - } - - default: break; - } - break; - #endif - - default: break; - } - } - - xfer->complete_cb = p_cdc->user_control_cb; - if (xfer->complete_cb) { - xfer->complete_cb(xfer); - } -} - -// internal control complete to update state such as line state, encoding -static void cdch_internal_control_complete(tuh_xfer_t* xfer) { - uint8_t const itf_num = (uint8_t) tu_le16toh(xfer->setup->wIndex); - process_internal_control_complete(xfer, itf_num); -} - bool tuh_cdc_set_control_line_state(uint8_t idx, uint16_t line_state, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { - cdch_interface_t* p_cdc = get_itf(idx); + cdch_interface_t * p_cdc = get_itf(idx); TU_VERIFY(p_cdc && p_cdc->serial_drid < SERIAL_DRIVER_COUNT); - cdch_serial_driver_t const* driver = &serial_drivers[p_cdc->serial_drid]; + TU_LOG_CDC(p_cdc, "set control line state dtr = %u rts = %u", p_cdc->requested_line.control_state.dtr, p_cdc->requested_line.control_state.rts); + const cdch_serial_driver_t * driver = &serial_drivers[p_cdc->serial_drid]; - if (complete_cb) { - return driver->set_control_line_state(p_cdc, line_state, complete_cb, user_data); - } else { - // blocking - xfer_result_t result = XFER_RESULT_INVALID; - bool ret = driver->set_control_line_state(p_cdc, line_state, complete_cb, (uintptr_t) &result); + p_cdc->requested_line.control_state.value = (uint8_t) line_state; + p_cdc->user_complete_cb = complete_cb; + TU_VERIFY(driver->set_control_line_state(p_cdc, complete_cb ? cdch_internal_control_complete : NULL, user_data)); - if (user_data) { - // user_data is not NULL, return result via user_data - *((xfer_result_t*) user_data) = result; - } - - TU_VERIFY(ret && result == XFER_RESULT_SUCCESS); - p_cdc->line_state = (uint8_t) line_state; - return true; + if (!complete_cb) { + // blocking, update line state if request was successful + p_cdc->line.control_state.value = (uint8_t) line_state; } + + return true; } bool tuh_cdc_set_baudrate(uint8_t idx, uint32_t baudrate, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { - cdch_interface_t* p_cdc = get_itf(idx); + cdch_interface_t *p_cdc = get_itf(idx); TU_VERIFY(p_cdc && p_cdc->serial_drid < SERIAL_DRIVER_COUNT); - cdch_serial_driver_t const* driver = &serial_drivers[p_cdc->serial_drid]; + TU_LOG_CDC(p_cdc, "set baudrate %lu", baudrate); + const cdch_serial_driver_t *driver = &serial_drivers[p_cdc->serial_drid]; - if (complete_cb) { - return driver->set_baudrate(p_cdc, baudrate, complete_cb, user_data); - } else { - // blocking - xfer_result_t result = XFER_RESULT_INVALID; - bool ret = driver->set_baudrate(p_cdc, baudrate, complete_cb, (uintptr_t) &result); + p_cdc->requested_line = p_cdc->line; // keep current line coding + p_cdc->requested_line.coding.bit_rate = baudrate; + p_cdc->user_complete_cb = complete_cb; + TU_VERIFY(driver->set_baudrate(p_cdc, complete_cb ? cdch_internal_control_complete : NULL, user_data)); - if (user_data) { - // user_data is not NULL, return result via user_data - *((xfer_result_t*) user_data) = result; - } - - TU_VERIFY(ret && result == XFER_RESULT_SUCCESS); - p_cdc->line_coding.bit_rate = baudrate; - return true; + if (!complete_cb) { + p_cdc->line.coding.bit_rate = baudrate; } + + return true; } bool tuh_cdc_set_data_format(uint8_t idx, uint8_t stop_bits, uint8_t parity, uint8_t data_bits, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { - cdch_interface_t* p_cdc = get_itf(idx); + cdch_interface_t *p_cdc = get_itf(idx); TU_VERIFY(p_cdc && p_cdc->serial_drid < SERIAL_DRIVER_COUNT); - cdch_serial_driver_t const* driver = &serial_drivers[p_cdc->serial_drid]; + TU_LOG_CDC(p_cdc, "set data format %u%c%s", + data_bits, CDC_LINE_CODING_PARITY_CHAR(parity), + CDC_LINE_CODING_STOP_BITS_TEXT(stop_bits)); + const cdch_serial_driver_t *driver = &serial_drivers[p_cdc->serial_drid]; - if (complete_cb) { - return driver->set_data_format(p_cdc, stop_bits, parity, data_bits, complete_cb, user_data); - } else { + p_cdc->requested_line = p_cdc->line; // keep current line coding + p_cdc->requested_line.coding.stop_bits = stop_bits; + p_cdc->requested_line.coding.parity = parity; + p_cdc->requested_line.coding.data_bits = data_bits; + + p_cdc->user_complete_cb = complete_cb; + TU_VERIFY(driver->set_data_format(p_cdc, complete_cb ? cdch_internal_control_complete : NULL, user_data)); + + if (!complete_cb) { // blocking - xfer_result_t result = XFER_RESULT_INVALID; - bool ret = driver->set_data_format(p_cdc, stop_bits, parity, data_bits, complete_cb, (uintptr_t) &result); - - if (user_data) { - // user_data is not NULL, return result via user_data - *((xfer_result_t*) user_data) = result; - } - - TU_VERIFY(ret && result == XFER_RESULT_SUCCESS); - p_cdc->line_coding.stop_bits = stop_bits; - p_cdc->line_coding.parity = parity; - p_cdc->line_coding.data_bits = data_bits; - return true; + p_cdc->line.coding.stop_bits = stop_bits; + p_cdc->line.coding.parity = parity; + p_cdc->line.coding.data_bits = data_bits; } + + return true; } -bool tuh_cdc_set_line_coding(uint8_t idx, cdc_line_coding_t const* line_coding, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { - cdch_interface_t* p_cdc = get_itf(idx); +bool tuh_cdc_set_line_coding(uint8_t idx, cdc_line_coding_t const *line_coding, + tuh_xfer_cb_t complete_cb, uintptr_t user_data) { + cdch_interface_t *p_cdc = get_itf(idx); TU_VERIFY(p_cdc && p_cdc->serial_drid < SERIAL_DRIVER_COUNT); - cdch_serial_driver_t const* driver = &serial_drivers[p_cdc->serial_drid]; + TU_LOG_CDC(p_cdc, "set line coding %lu %u%c%s", + line_coding->bit_rate, line_coding->data_bits, + CDC_LINE_CODING_PARITY_CHAR(line_coding->parity), + CDC_LINE_CODING_STOP_BITS_TEXT(line_coding->stop_bits)); + cdch_serial_driver_t const *driver = &serial_drivers[p_cdc->serial_drid]; + p_cdc->requested_line.coding = *line_coding; + p_cdc->user_complete_cb = complete_cb; - if ( complete_cb ) { - return driver->set_line_coding(p_cdc, line_coding, complete_cb, user_data); - } else { - // blocking - xfer_result_t result = XFER_RESULT_INVALID; - bool ret = driver->set_line_coding(p_cdc, line_coding, complete_cb, (uintptr_t) &result); + if (driver->set_line_coding) { + // driver support set_line_coding request + TU_VERIFY(driver->set_line_coding(p_cdc, complete_cb ? cdch_internal_control_complete : NULL, user_data)); - if (user_data) { - // user_data is not NULL, return result via user_data - *((xfer_result_t*) user_data) = result; + if (!complete_cb) { + p_cdc->line.coding = *line_coding; } + } else { + // driver does not support set_line_coding and need 2 stage to set baudrate and data format separately + if (complete_cb) { + // non-blocking + TU_VERIFY(driver->set_baudrate(p_cdc, cdch_set_line_coding_stage1_baudrate_complete, user_data)); + } else { + // blocking + xfer_result_t result = XFER_RESULT_INVALID; - TU_VERIFY(ret && result == XFER_RESULT_SUCCESS); - p_cdc->line_coding = *line_coding; - return true; + TU_VERIFY(driver->set_baudrate(p_cdc, NULL, (uintptr_t) &result)); + if (user_data) { + *((xfer_result_t *) user_data) = result; + } + TU_VERIFY(result == XFER_RESULT_SUCCESS); + p_cdc->line.coding.bit_rate = p_cdc->requested_line.coding.bit_rate; // update baudrate + + result = XFER_RESULT_INVALID; + TU_VERIFY(driver->set_data_format(p_cdc, NULL, (uintptr_t) &result)); + if (user_data) { + *((xfer_result_t *) user_data) = result; + } + TU_VERIFY(result == XFER_RESULT_SUCCESS); + p_cdc->line.coding = p_cdc->requested_line.coding; // update data format + } } + + return true; } //--------------------------------------------------------------------+ @@ -627,8 +627,8 @@ bool cdch_init(void) { TU_LOG_DRV("sizeof(cdch_interface_t) = %u\r\n", sizeof(cdch_interface_t)); tu_memclr(cdch_data, sizeof(cdch_data)); for (size_t i = 0; i < CFG_TUH_CDC; i++) { - cdch_interface_t* p_cdc = &cdch_data[i]; - cdch_epbuf_t* epbuf = &cdch_epbuf[i]; + cdch_interface_t *p_cdc = &cdch_data[i]; + cdch_epbuf_t *epbuf = &cdch_epbuf[i]; tu_edpt_stream_init(&p_cdc->stream.tx, true, true, false, p_cdc->stream.tx_ff_buf, CFG_TUH_CDC_TX_BUFSIZE, epbuf->tx, CFG_TUH_CDC_TX_EPSIZE); @@ -643,7 +643,7 @@ bool cdch_init(void) { bool cdch_deinit(void) { for (size_t i = 0; i < CFG_TUH_CDC; i++) { - cdch_interface_t* p_cdc = &cdch_data[i]; + cdch_interface_t *p_cdc = &cdch_data[i]; tu_edpt_stream_deinit(&p_cdc->stream.tx); tu_edpt_stream_deinit(&p_cdc->stream.rx); } @@ -652,9 +652,9 @@ bool cdch_deinit(void) { void cdch_close(uint8_t daddr) { for (uint8_t idx = 0; idx < CFG_TUH_CDC; idx++) { - cdch_interface_t* p_cdc = &cdch_data[idx]; + cdch_interface_t *p_cdc = &cdch_data[idx]; if (p_cdc->daddr == daddr) { - TU_LOG_DRV(" CDCh close addr = %u index = %u\r\n", daddr, idx); + TU_LOG_CDC(p_cdc, "close"); // Invoke application callback if (tuh_cdc_umount_cb) { @@ -672,45 +672,50 @@ void cdch_close(uint8_t daddr) { bool cdch_xfer_cb(uint8_t daddr, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes) { // TODO handle stall response, retry failed transfer ... - TU_ASSERT(event == XFER_RESULT_SUCCESS); + TU_VERIFY(event == XFER_RESULT_SUCCESS); uint8_t const idx = get_idx_by_ep_addr(daddr, ep_addr); - cdch_interface_t * p_cdc = get_itf(idx); + cdch_interface_t *p_cdc = get_itf(idx); TU_ASSERT(p_cdc); - if ( ep_addr == p_cdc->stream.tx.ep_addr ) { + if (ep_addr == p_cdc->stream.tx.ep_addr) { // invoke tx complete callback to possibly refill tx fifo if (tuh_cdc_tx_complete_cb) { tuh_cdc_tx_complete_cb(idx); } - if ( 0 == tu_edpt_stream_write_xfer(daddr, &p_cdc->stream.tx) ) { + if (0 == tu_edpt_stream_write_xfer(daddr, &p_cdc->stream.tx)) { // If there is no data left, a ZLP should be sent if: // - xferred_bytes is multiple of EP Packet size and not zero tu_edpt_stream_write_zlp_if_needed(daddr, &p_cdc->stream.tx, xferred_bytes); } - } else if ( ep_addr == p_cdc->stream.rx.ep_addr ) { + } else if (ep_addr == p_cdc->stream.rx.ep_addr) { #if CFG_TUH_CDC_FTDI if (p_cdc->serial_drid == SERIAL_DRIVER_FTDI) { // FTDI reserve 2 bytes for status // uint8_t status[2] = {p_cdc->stream.rx.ep_buf[0], p_cdc->stream.rx.ep_buf[1]}; - tu_edpt_stream_read_xfer_complete_offset(&p_cdc->stream.rx, xferred_bytes, 2); - }else + if (xferred_bytes > 2) { + tu_edpt_stream_read_xfer_complete_with_buf(&p_cdc->stream.rx, p_cdc->stream.rx.ep_buf + 2, xferred_bytes - 2); + + if (tuh_cdc_rx_cb) { + tuh_cdc_rx_cb(idx); // invoke receive callback + } + } + } else #endif { tu_edpt_stream_read_xfer_complete(&p_cdc->stream.rx, xferred_bytes); - } - // invoke receive callback - if (tuh_cdc_rx_cb) { - tuh_cdc_rx_cb(idx); + if (tuh_cdc_rx_cb) { + tuh_cdc_rx_cb(idx); // invoke receive callback + } } // prepare for next transfer if needed tu_edpt_stream_read_xfer(daddr, &p_cdc->stream.rx); - }else if ( ep_addr == p_cdc->ep_notif ) { + } else if (ep_addr == p_cdc->ep_notif) { // TODO handle notification endpoint - }else { + } else { TU_ASSERT(false); } @@ -721,7 +726,7 @@ bool cdch_xfer_cb(uint8_t daddr, uint8_t ep_addr, xfer_result_t event, uint32_t // Enumeration //--------------------------------------------------------------------+ -static bool open_ep_stream_pair(cdch_interface_t* p_cdc, tusb_desc_endpoint_t const* desc_ep) { +static bool open_ep_stream_pair(cdch_interface_t *p_cdc, tusb_desc_endpoint_t const *desc_ep) { for (size_t i = 0; i < 2; i++) { TU_ASSERT(TUSB_DESC_ENDPOINT == desc_ep->bDescriptorType && TUSB_XFER_BULK == desc_ep->bmAttributes.xfer); @@ -733,7 +738,7 @@ static bool open_ep_stream_pair(cdch_interface_t* p_cdc, tusb_desc_endpoint_t co tu_edpt_stream_open(&p_cdc->stream.tx, desc_ep); } - desc_ep = (tusb_desc_endpoint_t const*) tu_desc_next(desc_ep); + desc_ep = (tusb_desc_endpoint_t const *) tu_desc_next(desc_ep); } return true; @@ -741,10 +746,9 @@ static bool open_ep_stream_pair(cdch_interface_t* p_cdc, tusb_desc_endpoint_t co bool cdch_open(uint8_t rhport, uint8_t daddr, tusb_desc_interface_t const *itf_desc, uint16_t max_len) { (void) rhport; - // For CDC: only support ACM subclass // Note: Protocol 0xFF can be RNDIS device - if (TUSB_CLASS_CDC == itf_desc->bInterfaceClass && + if (TUSB_CLASS_CDC == itf_desc->bInterfaceClass && CDC_COMM_SUBCLASS_ABSTRACT_CONTROL_MODEL == itf_desc->bInterfaceSubClass) { return acm_open(daddr, itf_desc, max_len); } else if (SERIAL_DRIVER_COUNT > 1 && @@ -753,10 +757,12 @@ bool cdch_open(uint8_t rhport, uint8_t daddr, tusb_desc_interface_t const *itf_d TU_VERIFY(tuh_vid_pid_get(daddr, &vid, &pid)); for (size_t dr = 1; dr < SERIAL_DRIVER_COUNT; dr++) { - cdch_serial_driver_t const* driver = &serial_drivers[dr]; + const cdch_serial_driver_t *driver = &serial_drivers[dr]; for (size_t i = 0; i < driver->vid_pid_count; i++) { if (driver->vid_pid_list[i][0] == vid && driver->vid_pid_list[i][1] == pid) { - return driver->open(daddr, itf_desc, max_len); + const bool ret = driver->open(daddr, itf_desc, max_len); + TU_LOG_DRV("[:%u:%u] CDCh %s open %s\r\n", daddr, itf_desc->bInterfaceNumber, driver->name, ret ? "OK" : "FAILED"); + return ret; } } } @@ -765,123 +771,170 @@ bool cdch_open(uint8_t rhport, uint8_t daddr, tusb_desc_interface_t const *itf_d return false; } -static void set_config_complete(cdch_interface_t * p_cdc, uint8_t idx, uint8_t itf_num) { - TU_LOG_DRV("CDCh Set Configure complete\r\n"); - p_cdc->mounted = true; - if (tuh_cdc_mount_cb) { - tuh_cdc_mount_cb(idx); - } - - // Prepare for incoming data - tu_edpt_stream_read_xfer(p_cdc->daddr, &p_cdc->stream.rx); - - // notify usbh that driver enumeration is complete - usbh_driver_set_config_complete(p_cdc->daddr, itf_num); -} - bool cdch_set_config(uint8_t daddr, uint8_t itf_num) { tusb_control_request_t request; request.wIndex = tu_htole16((uint16_t) itf_num); - - // fake transfer to kick-off process - tuh_xfer_t xfer; - xfer.daddr = daddr; - xfer.result = XFER_RESULT_SUCCESS; - xfer.setup = &request; - xfer.user_data = 0; // initial state - uint8_t const idx = tuh_cdc_itf_get_index(daddr, itf_num); - cdch_interface_t * p_cdc = get_itf(idx); + cdch_interface_t *p_cdc = get_itf(idx); TU_ASSERT(p_cdc && p_cdc->serial_drid < SERIAL_DRIVER_COUNT); + TU_LOG_CDC(p_cdc, "set config"); + + // fake transfer to kick-off process_set_config() + tuh_xfer_t xfer; + xfer.daddr = daddr; + xfer.result = XFER_RESULT_SUCCESS; + xfer.setup = &request; + xfer.user_data = 0; // initial state 0 + cdch_process_set_config(&xfer); - serial_drivers[p_cdc->serial_drid].process_set_config(&xfer); return true; } +static void set_config_complete(cdch_interface_t *p_cdc, bool success) { + if (success) { + const uint8_t idx = get_idx_by_ptr(p_cdc); + p_cdc->mounted = true; + if (tuh_cdc_mount_cb) { + tuh_cdc_mount_cb(idx); + } + // Prepare for incoming data + tu_edpt_stream_read_xfer(p_cdc->daddr, &p_cdc->stream.rx); + } else { + // clear the interface entry + p_cdc->daddr = 0; + p_cdc->bInterfaceNumber = 0; + } + + // notify usbh that driver enumeration is complete + const uint8_t itf_offset = (p_cdc->serial_drid == SERIAL_DRIVER_ACM) ? 1 : 0; + usbh_driver_set_config_complete(p_cdc->daddr, p_cdc->bInterfaceNumber + itf_offset); +} + +static void cdch_process_set_config(tuh_xfer_t *xfer) { + cdch_interface_t *p_cdc = get_itf_by_xfer(xfer); + TU_ASSERT(p_cdc && p_cdc->serial_drid < SERIAL_DRIVER_COUNT,); + TU_LOG_DRV(" state = %u\r\n", xfer->user_data); + const cdch_serial_driver_t *driver = &serial_drivers[p_cdc->serial_drid]; + + if (!driver->process_set_config(p_cdc, xfer)) { + set_config_complete(p_cdc, false); + } +} + +static bool set_line_state_on_enum(cdch_interface_t *p_cdc, tuh_xfer_t *xfer) { + enum { + ENUM_SET_LINE_CODING = 0, + ENUM_SET_LINE_CONTROL, + ENUM_SET_LINE_COMPLETE, + }; + const uint8_t idx = get_idx_by_ptr(p_cdc); + const uintptr_t state = xfer->user_data; + + switch (state) { + case ENUM_SET_LINE_CODING: { + #ifdef CFG_TUH_CDC_LINE_CODING_ON_ENUM + // ch34x already set line coding in serial init + if (p_cdc->serial_drid != SERIAL_DRIVER_CH34X) { + const cdc_line_coding_t line_coding = (cdc_line_coding_t) CFG_TUH_CDC_LINE_CODING_ON_ENUM; + TU_ASSERT(tuh_cdc_set_line_coding(idx, &line_coding, + cdch_process_line_state_on_enum, ENUM_SET_LINE_CONTROL)); + break; + } + #endif + TU_ATTR_FALLTHROUGH; + } + + case ENUM_SET_LINE_CONTROL: + #ifdef CFG_TUH_CDC_LINE_CONTROL_ON_ENUM + TU_ASSERT(tuh_cdc_set_control_line_state(idx, CFG_TUH_CDC_LINE_CONTROL_ON_ENUM, + cdch_process_line_state_on_enum, ENUM_SET_LINE_COMPLETE)); + break; + #else + TU_ATTR_FALLTHROUGH; + #endif + + case ENUM_SET_LINE_COMPLETE: + set_config_complete(p_cdc, true); + break; + + default: + return false; + } + + return true; +} + +static void cdch_process_line_state_on_enum(tuh_xfer_t *xfer) { + cdch_interface_t *p_cdc = get_itf_by_xfer(xfer); + TU_ASSERT(p_cdc && p_cdc->serial_drid < SERIAL_DRIVER_COUNT,); + if (xfer->result != XFER_RESULT_SUCCESS || !set_line_state_on_enum(p_cdc, xfer)) { + set_config_complete(p_cdc, false); + } +} + + +static void cdch_internal_control_complete(tuh_xfer_t *xfer) { + cdch_interface_t *p_cdc = get_itf_by_xfer(xfer); + TU_ASSERT(p_cdc && p_cdc->serial_drid < SERIAL_DRIVER_COUNT,); + TU_LOG_DRV(" request result = %u\r\n", xfer->result); + const cdch_serial_driver_t *driver = &serial_drivers[p_cdc->serial_drid]; + driver->request_complete(p_cdc, xfer); + + // Invoke application callback + xfer->complete_cb = p_cdc->user_complete_cb; + if (xfer->complete_cb) { + xfer->complete_cb(xfer); + } +} + +static void cdch_set_line_coding_stage1_baudrate_complete(tuh_xfer_t *xfer) { + cdch_interface_t *p_cdc = get_itf_by_xfer(xfer); + TU_ASSERT(p_cdc && p_cdc->serial_drid < SERIAL_DRIVER_COUNT,); + TU_LOG_DRV(" stage1 set baudrate result = %u\r\n", xfer->result); + const cdch_serial_driver_t *driver = &serial_drivers[p_cdc->serial_drid]; + + if (xfer->result == XFER_RESULT_SUCCESS) { + p_cdc->line.coding.bit_rate = p_cdc->requested_line.coding.bit_rate; // update baudrate + TU_ASSERT(driver->set_data_format(p_cdc, cdch_set_line_coding_stage2_data_format_complete, xfer->user_data),); + } else { + xfer->complete_cb = p_cdc->user_complete_cb; + if (xfer->complete_cb) { + xfer->complete_cb(xfer); + } + } +} + +static void cdch_set_line_coding_stage2_data_format_complete(tuh_xfer_t *xfer) { + cdch_interface_t *p_cdc = get_itf_by_xfer(xfer); + TU_ASSERT(p_cdc && p_cdc->serial_drid < SERIAL_DRIVER_COUNT,); + TU_LOG_DRV(" stage2 set data format result = %u\r\n", xfer->result); + + if (xfer->result == XFER_RESULT_SUCCESS) { + p_cdc->line.coding = p_cdc->requested_line.coding; // update data format + } + + xfer->complete_cb = p_cdc->user_complete_cb; + if (xfer->complete_cb) { + xfer->complete_cb(xfer); + } +} + //--------------------------------------------------------------------+ // ACM //--------------------------------------------------------------------+ -enum { - CONFIG_ACM_SET_CONTROL_LINE_STATE = 0, - CONFIG_ACM_SET_LINE_CODING, - CONFIG_ACM_COMPLETE, -}; +// internal control complete to update state such as line state, encoding +static void acm_internal_control_complete(cdch_interface_t *p_cdc, tuh_xfer_t *xfer) { + TU_VERIFY (xfer->result == XFER_RESULT_SUCCESS,); + const tusb_control_request_t * setup = xfer->setup; -static bool acm_open(uint8_t daddr, tusb_desc_interface_t const* itf_desc, uint16_t max_len) { - uint8_t const* p_desc_end = ((uint8_t const*) itf_desc) + max_len; + switch (setup->bRequest) { + case CDC_REQUEST_SET_CONTROL_LINE_STATE: + p_cdc->line.control_state = p_cdc->requested_line.control_state; + break; - cdch_interface_t* p_cdc = make_new_itf(daddr, itf_desc); - TU_VERIFY(p_cdc); - p_cdc->serial_drid = SERIAL_DRIVER_ACM; - - //------------- Control Interface -------------// - uint8_t const* p_desc = tu_desc_next(itf_desc); - - // Communication Functional Descriptors - while ((p_desc < p_desc_end) && (TUSB_DESC_CS_INTERFACE == tu_desc_type(p_desc))) { - if (CDC_FUNC_DESC_ABSTRACT_CONTROL_MANAGEMENT == cdc_functional_desc_typeof(p_desc)) { - // save ACM bmCapabilities - p_cdc->acm_capability = ((cdc_desc_func_acm_t const*) p_desc)->bmCapabilities; - } - - p_desc = tu_desc_next(p_desc); - } - - // Open notification endpoint of control interface if any - if (itf_desc->bNumEndpoints == 1) { - TU_ASSERT(TUSB_DESC_ENDPOINT == tu_desc_type(p_desc)); - tusb_desc_endpoint_t const* desc_ep = (tusb_desc_endpoint_t const*) p_desc; - - TU_ASSERT(tuh_edpt_open(daddr, desc_ep)); - p_cdc->ep_notif = desc_ep->bEndpointAddress; - - p_desc = tu_desc_next(p_desc); - } - - //------------- Data Interface (if any) -------------// - if ((TUSB_DESC_INTERFACE == tu_desc_type(p_desc)) && - (TUSB_CLASS_CDC_DATA == ((tusb_desc_interface_t const*) p_desc)->bInterfaceClass)) { - // next to endpoint descriptor - p_desc = tu_desc_next(p_desc); - - // data endpoints expected to be in pairs - TU_ASSERT(open_ep_stream_pair(p_cdc, (tusb_desc_endpoint_t const*) p_desc)); - } - - return true; -} - -static void acm_process_config(tuh_xfer_t* xfer) { - uintptr_t const state = xfer->user_data; - uint8_t const itf_num = (uint8_t) tu_le16toh(xfer->setup->wIndex); - uint8_t const idx = tuh_cdc_itf_get_index(xfer->daddr, itf_num); - cdch_interface_t* p_cdc = get_itf(idx); - TU_ASSERT(p_cdc,); - - switch (state) { - case CONFIG_ACM_SET_CONTROL_LINE_STATE: - #if CFG_TUH_CDC_LINE_CONTROL_ON_ENUM - if (p_cdc->acm_capability.support_line_request) { - TU_ASSERT(acm_set_control_line_state(p_cdc, CFG_TUH_CDC_LINE_CONTROL_ON_ENUM, acm_process_config, CONFIG_ACM_SET_LINE_CODING),); - break; - } - #endif - TU_ATTR_FALLTHROUGH; - - case CONFIG_ACM_SET_LINE_CODING: - #ifdef CFG_TUH_CDC_LINE_CODING_ON_ENUM - if (p_cdc->acm_capability.support_line_request) { - cdc_line_coding_t line_coding = CFG_TUH_CDC_LINE_CODING_ON_ENUM; - TU_ASSERT(acm_set_line_coding(p_cdc, &line_coding, acm_process_config, CONFIG_ACM_COMPLETE),); - break; - } - #endif - TU_ATTR_FALLTHROUGH; - - case CONFIG_ACM_COMPLETE: - // itf_num+1 to account for data interface as well - set_config_complete(p_cdc, idx, itf_num + 1); + case CDC_REQUEST_SET_LINE_CODING: + p_cdc->line.coding = p_cdc->requested_line.coding; break; default: @@ -889,135 +942,21 @@ static void acm_process_config(tuh_xfer_t* xfer) { } } -static bool acm_set_control_line_state(cdch_interface_t* p_cdc, uint16_t line_state, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { - TU_VERIFY(p_cdc->acm_capability.support_line_request); - TU_LOG_DRV("CDC ACM Set Control Line State\r\n"); +static bool acm_set_control_line_state(cdch_interface_t *p_cdc, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { + TU_VERIFY(p_cdc->acm.capability.support_line_request); - tusb_control_request_t const request = { + const tusb_control_request_t request = { .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_INTERFACE, .type = TUSB_REQ_TYPE_CLASS, .direction = TUSB_DIR_OUT }, .bRequest = CDC_REQUEST_SET_CONTROL_LINE_STATE, - .wValue = tu_htole16(line_state), + .wValue = tu_htole16((uint16_t) p_cdc->requested_line.control_state.value), .wIndex = tu_htole16((uint16_t) p_cdc->bInterfaceNumber), .wLength = 0 }; - p_cdc->user_control_cb = complete_cb; - - tuh_xfer_t xfer = { - .daddr = p_cdc->daddr, - .ep_addr = 0, - .setup = &request, - .buffer = NULL, - .complete_cb = complete_cb ? cdch_internal_control_complete : NULL, // complete_cb is NULL for sync call - .user_data = user_data - }; - - TU_ASSERT(tuh_control_xfer(&xfer)); - return true; -} - -static bool acm_set_line_coding(cdch_interface_t* p_cdc, cdc_line_coding_t const* line_coding, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { - TU_LOG_DRV("CDC ACM Set Line Conding\r\n"); - - tusb_control_request_t const request = { - .bmRequestType_bit = { - .recipient = TUSB_REQ_RCPT_INTERFACE, - .type = TUSB_REQ_TYPE_CLASS, - .direction = TUSB_DIR_OUT - }, - .bRequest = CDC_REQUEST_SET_LINE_CODING, - .wValue = 0, - .wIndex = tu_htole16(p_cdc->bInterfaceNumber), - .wLength = tu_htole16(sizeof(cdc_line_coding_t)) - }; - - // use usbh enum buf to hold line coding since user line_coding variable does not live long enough - uint8_t* enum_buf = usbh_get_enum_buf(); - memcpy(enum_buf, line_coding, sizeof(cdc_line_coding_t)); - - p_cdc->user_control_cb = complete_cb; - tuh_xfer_t xfer = { - .daddr = p_cdc->daddr, - .ep_addr = 0, - .setup = &request, - .buffer = enum_buf, - .complete_cb = complete_cb ? cdch_internal_control_complete : NULL, // complete_cb is NULL for sync call - .user_data = user_data - }; - - TU_ASSERT(tuh_control_xfer(&xfer)); - return true; -} - -static bool acm_set_data_format(cdch_interface_t* p_cdc, uint8_t stop_bits, uint8_t parity, uint8_t data_bits, - tuh_xfer_cb_t complete_cb, uintptr_t user_data) { - TU_LOG_DRV("CDC ACM Set Data Format\r\n"); - - cdc_line_coding_t line_coding; - line_coding.bit_rate = p_cdc->line_coding.bit_rate; - line_coding.stop_bits = stop_bits; - line_coding.parity = parity; - line_coding.data_bits = data_bits; - - return acm_set_line_coding(p_cdc, &line_coding, complete_cb, user_data); -} - -static bool acm_set_baudrate(cdch_interface_t* p_cdc, uint32_t baudrate, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { - TU_VERIFY(p_cdc->acm_capability.support_line_request); - cdc_line_coding_t line_coding = p_cdc->line_coding; - line_coding.bit_rate = baudrate; - return acm_set_line_coding(p_cdc, &line_coding, complete_cb, user_data); -} - -//--------------------------------------------------------------------+ -// FTDI -//--------------------------------------------------------------------+ -#if CFG_TUH_CDC_FTDI - -enum { - CONFIG_FTDI_RESET = 0, - CONFIG_FTDI_MODEM_CTRL, - CONFIG_FTDI_SET_BAUDRATE, - CONFIG_FTDI_SET_DATA, - CONFIG_FTDI_COMPLETE -}; - -static bool ftdi_open(uint8_t daddr, const tusb_desc_interface_t *itf_desc, uint16_t max_len) { - // FTDI Interface includes 1 vendor interface + 2 bulk endpoints - TU_VERIFY(itf_desc->bInterfaceSubClass == 0xff && itf_desc->bInterfaceProtocol == 0xff && itf_desc->bNumEndpoints == 2); - TU_VERIFY(sizeof(tusb_desc_interface_t) + 2*sizeof(tusb_desc_endpoint_t) <= max_len); - - cdch_interface_t * p_cdc = make_new_itf(daddr, itf_desc); - TU_VERIFY(p_cdc); - - TU_LOG_DRV("FTDI opened\r\n"); - p_cdc->serial_drid = SERIAL_DRIVER_FTDI; - - // endpoint pair - tusb_desc_endpoint_t const * desc_ep = (tusb_desc_endpoint_t const *) tu_desc_next(itf_desc); - - // data endpoints expected to be in pairs - return open_ep_stream_pair(p_cdc, desc_ep); -} - -// set request without data -static bool ftdi_sio_set_request(cdch_interface_t* p_cdc, uint8_t command, uint16_t value, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { - tusb_control_request_t const request = { - .bmRequestType_bit = { - .recipient = TUSB_REQ_RCPT_DEVICE, - .type = TUSB_REQ_TYPE_VENDOR, - .direction = TUSB_DIR_OUT - }, - .bRequest = command, - .wValue = tu_htole16(value), - .wIndex = 0, - .wLength = 0 - }; - tuh_xfer_t xfer = { .daddr = p_cdc->daddr, .ep_addr = 0, @@ -1030,125 +969,502 @@ static bool ftdi_sio_set_request(cdch_interface_t* p_cdc, uint8_t command, uint1 return tuh_control_xfer(&xfer); } -static bool ftdi_sio_reset(cdch_interface_t* p_cdc, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { - return ftdi_sio_set_request(p_cdc, FTDI_SIO_RESET, FTDI_SIO_RESET_SIO, complete_cb, user_data); +static bool acm_set_line_coding(cdch_interface_t *p_cdc, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { + TU_VERIFY(p_cdc->acm.capability.support_line_request); + TU_VERIFY((p_cdc->requested_line.coding.data_bits >= 5 && p_cdc->requested_line.coding.data_bits <= 8) || + p_cdc->requested_line.coding.data_bits == 16); + + tusb_control_request_t const request = { + .bmRequestType_bit = { + .recipient = TUSB_REQ_RCPT_INTERFACE, + .type = TUSB_REQ_TYPE_CLASS, + .direction = TUSB_DIR_OUT + }, + .bRequest = CDC_REQUEST_SET_LINE_CODING, + .wValue = 0, + .wIndex = tu_htole16((uint16_t) p_cdc->bInterfaceNumber), + .wLength = tu_htole16((uint16_t) sizeof(cdc_line_coding_t)) + }; + + // use usbh enum buf to hold line coding since user line_coding variable does not live long enough + uint8_t *enum_buf = usbh_get_enum_buf(); + memcpy(enum_buf, &p_cdc->requested_line.coding, sizeof(cdc_line_coding_t)); + + tuh_xfer_t xfer = { + .daddr = p_cdc->daddr, + .ep_addr = 0, + .setup = &request, + .buffer = enum_buf, + .complete_cb = complete_cb, + .user_data = user_data + }; + + return tuh_control_xfer(&xfer); } -static bool ftdi_set_data_format(cdch_interface_t* p_cdc, uint8_t stop_bits, uint8_t parity, uint8_t data_bits, - tuh_xfer_cb_t complete_cb, uintptr_t user_data) { - (void) p_cdc; - (void) stop_bits; - (void) parity; - (void) data_bits; - (void) complete_cb; - (void) user_data; - // TODO not implemented yet - return false; -} +//------------- Enumeration -------------// +enum { + CONFIG_ACM_COMPLETE = 0 +}; -static bool ftdi_set_line_coding(cdch_interface_t* p_cdc, cdc_line_coding_t const* line_coding, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { - (void) p_cdc; - (void) line_coding; - (void) complete_cb; - (void) user_data; - // TODO not implemented yet - return false; -} +static bool acm_open(uint8_t daddr, tusb_desc_interface_t const *itf_desc, uint16_t max_len) { + uint8_t const *p_desc_end = ((uint8_t const *) itf_desc) + max_len; + + cdch_interface_t *p_cdc = make_new_itf(daddr, itf_desc); + TU_VERIFY(p_cdc); + + p_cdc->serial_drid = SERIAL_DRIVER_ACM; + + //------------- Control Interface -------------// + uint8_t const *p_desc = tu_desc_next(itf_desc); + + // Communication Functional Descriptors + while ((p_desc < p_desc_end) && (TUSB_DESC_CS_INTERFACE == tu_desc_type(p_desc))) { + if (CDC_FUNC_DESC_ABSTRACT_CONTROL_MANAGEMENT == cdc_functional_desc_typeof(p_desc)) { + // save ACM bmCapabilities + p_cdc->acm.capability = ((cdc_desc_func_acm_t const *) p_desc)->bmCapabilities; + } + + p_desc = tu_desc_next(p_desc); + } + + // Open notification endpoint of control interface if any + if (itf_desc->bNumEndpoints == 1) { + TU_ASSERT(TUSB_DESC_ENDPOINT == tu_desc_type(p_desc)); + tusb_desc_endpoint_t const *desc_ep = (tusb_desc_endpoint_t const *) p_desc; + + TU_ASSERT(tuh_edpt_open(daddr, desc_ep)); + p_cdc->ep_notif = desc_ep->bEndpointAddress; + + p_desc = tu_desc_next(p_desc); + } + + //------------- Data Interface (if any) -------------// + if ((TUSB_DESC_INTERFACE == tu_desc_type(p_desc)) && + (TUSB_CLASS_CDC_DATA == ((tusb_desc_interface_t const *) p_desc)->bInterfaceClass)) { + // next to endpoint descriptor + p_desc = tu_desc_next(p_desc); + + // data endpoints expected to be in pairs + TU_ASSERT(open_ep_stream_pair(p_cdc, (tusb_desc_endpoint_t const *) p_desc)); + } -static bool ftdi_sio_set_modem_ctrl(cdch_interface_t* p_cdc, uint16_t line_state, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { - TU_LOG_DRV("CDC FTDI Set Control Line State\r\n"); - p_cdc->user_control_cb = complete_cb; - TU_ASSERT(ftdi_sio_set_request(p_cdc, FTDI_SIO_MODEM_CTRL, 0x0300 | line_state, - complete_cb ? cdch_internal_control_complete : NULL, user_data)); return true; } -static uint32_t ftdi_232bm_baud_base_to_divisor(uint32_t baud, uint32_t base) { - const uint8_t divfrac[8] = { 0, 3, 2, 4, 1, 5, 6, 7 }; - uint32_t divisor; +static bool acm_process_set_config(cdch_interface_t *p_cdc, tuh_xfer_t *xfer) { + TU_ASSERT(xfer->result == XFER_RESULT_SUCCESS); + (void) p_cdc; + const uintptr_t state = xfer->user_data; - /* divisor shifted 3 bits to the left */ - uint32_t divisor3 = base / (2 * baud); - divisor = (divisor3 >> 3); - divisor |= (uint32_t) divfrac[divisor3 & 0x7] << 14; + switch (state) { + case CONFIG_ACM_COMPLETE: { + xfer->user_data = 0; // kick-off set line state on enum + cdch_process_line_state_on_enum(xfer); + break; + } - /* Deal with special cases for highest baud rates. */ - if (divisor == 1) { /* 1.0 */ - divisor = 0; + default: + return false; // invalid state } - else if (divisor == 0x4001) { /* 1.5 */ + + return true; +} + +//--------------------------------------------------------------------+ +// FTDI +//--------------------------------------------------------------------+ +#if CFG_TUH_CDC_FTDI + +static bool ftdi_determine_type(cdch_interface_t *p_cdc); +static uint32_t ftdi_get_divisor(cdch_interface_t *p_cdc); + +//------------- Control Request -------------// + +// set request without data +static bool ftdi_set_request(cdch_interface_t *p_cdc, uint8_t request, uint8_t requesttype, + uint16_t value, uint16_t index, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { + tusb_control_request_t const request_setup = { + .bmRequestType = requesttype, + .bRequest = request, + .wValue = tu_htole16(value), + .wIndex = tu_htole16(index), + .wLength = 0 + }; + + tuh_xfer_t xfer = { + .daddr = p_cdc->daddr, + .ep_addr = 0, + .setup = &request_setup, + .buffer = NULL, + .complete_cb = complete_cb, + .user_data = user_data + }; + + return tuh_control_xfer(&xfer); +} + +#ifdef CFG_TUH_CDC_FTDI_LATENCY +static int8_t ftdi_write_latency_timer(cdch_interface_t * p_cdc, uint16_t latency, + tuh_xfer_cb_t complete_cb, uintptr_t user_data) { + if (p_cdc->ftdi.chip_type == FTDI_SIO /* || p_cdc->ftdi.chip_type == FT232A */ ) + return FTDI_NOT_POSSIBLE; + return ftdi_set_request(p_cdc, FTDI_SIO_SET_LATENCY_TIMER_REQUEST, FTDI_SIO_SET_LATENCY_TIMER_REQUEST_TYPE, + latency, p_cdc->ftdi.channel, complete_cb, user_data) ? FTDI_REQUESTED : FTDI_FAIL; +} +#endif + +static inline bool ftdi_sio_reset(cdch_interface_t *p_cdc, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { + return ftdi_set_request(p_cdc, FTDI_SIO_RESET_REQUEST, FTDI_SIO_RESET_REQUEST_TYPE, FTDI_SIO_RESET_SIO, + p_cdc->ftdi.channel, complete_cb, user_data); +} + + +//------------- Driver API -------------// + +// internal control complete to update state such as line state, line_coding +static void ftdi_internal_control_complete(cdch_interface_t* p_cdc, tuh_xfer_t *xfer) { + TU_VERIFY(xfer->result == XFER_RESULT_SUCCESS,); + const tusb_control_request_t * setup = xfer->setup; + if (xfer->result == XFER_RESULT_SUCCESS) { + if (setup->bRequest == FTDI_SIO_SET_MODEM_CTRL_REQUEST && + setup->bmRequestType == FTDI_SIO_SET_MODEM_CTRL_REQUEST_TYPE ) { + p_cdc->line.control_state = p_cdc->requested_line.control_state; + } + if (setup->bRequest == FTDI_SIO_SET_DATA_REQUEST && + setup->bmRequestType == FTDI_SIO_SET_DATA_REQUEST_TYPE ) { + p_cdc->line.coding.stop_bits = p_cdc->requested_line.coding.stop_bits; + p_cdc->line.coding.parity = p_cdc->requested_line.coding.parity; + p_cdc->line.coding.data_bits = p_cdc->requested_line.coding.data_bits; + } + if (setup->bRequest == FTDI_SIO_SET_BAUDRATE_REQUEST && + setup->bmRequestType == FTDI_SIO_SET_BAUDRATE_REQUEST_TYPE ) { + p_cdc->line.coding.bit_rate = p_cdc->requested_line.coding.bit_rate; + } + } +} + +static bool ftdi_set_data_format(cdch_interface_t *p_cdc, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { + TU_VERIFY(p_cdc->requested_line.coding.data_bits >= 7 && p_cdc->requested_line.coding.data_bits <= 8, 0); + uint16_t value = (uint16_t) ((p_cdc->requested_line.coding.data_bits & 0xfUL) | // data bit quantity is stored in bits 0-3 + (p_cdc->requested_line.coding.parity & 0x7UL) << 8 | // parity is stored in bits 8-10, same coding + (p_cdc->requested_line.coding.stop_bits & 0x3UL) << 11); // stop bits quantity is stored in bits 11-12, same coding + // not each FTDI supports 1.5 stop bits + return ftdi_set_request(p_cdc, FTDI_SIO_SET_DATA_REQUEST, FTDI_SIO_SET_DATA_REQUEST_TYPE, + value, p_cdc->ftdi.channel, complete_cb, user_data); +} + +static bool ftdi_set_baudrate(cdch_interface_t *p_cdc, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { + uint32_t index_value = ftdi_get_divisor(p_cdc); + TU_VERIFY(index_value); + uint16_t value = (uint16_t) index_value; + uint16_t index = (uint16_t) (index_value >> 16); + if (p_cdc->ftdi.channel) { + index = (uint16_t) ((index << 8) | p_cdc->ftdi.channel); + } + + return ftdi_set_request(p_cdc, FTDI_SIO_SET_BAUDRATE_REQUEST, FTDI_SIO_SET_BAUDRATE_REQUEST_TYPE, + value, index, complete_cb, user_data); +} + +static bool ftdi_set_modem_ctrl(cdch_interface_t *p_cdc, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { + uint16_t line_state = (uint16_t) ((p_cdc->requested_line.control_state.dtr ? FTDI_SIO_SET_DTR_HIGH : FTDI_SIO_SET_DTR_LOW) | + (p_cdc->requested_line.control_state.rts ? FTDI_SIO_SET_RTS_HIGH : FTDI_SIO_SET_RTS_LOW)); + return ftdi_set_request(p_cdc, FTDI_SIO_SET_MODEM_CTRL_REQUEST, FTDI_SIO_SET_MODEM_CTRL_REQUEST_TYPE, + line_state, p_cdc->ftdi.channel, complete_cb ? cdch_internal_control_complete : NULL, user_data); +} + +//------------- Enumeration -------------// +enum { + CONFIG_FTDI_DETERMINE_TYPE = 0, + CONFIG_FTDI_WRITE_LATENCY, + CONFIG_FTDI_SIO_RESET, + CONFIG_FTDI_FLOW_CONTROL, + CONFIG_FTDI_COMPLETE +}; + +static bool ftdi_open(uint8_t daddr, const tusb_desc_interface_t *itf_desc, uint16_t max_len) { + // FTDI Interface includes 1 vendor interface + 2 bulk endpoints + TU_VERIFY(itf_desc->bInterfaceSubClass == 0xff && itf_desc->bInterfaceProtocol == 0xff && + itf_desc->bNumEndpoints == 2); + TU_VERIFY(sizeof(tusb_desc_interface_t) + 2 * sizeof(tusb_desc_endpoint_t) <= max_len); + + cdch_interface_t *p_cdc = make_new_itf(daddr, itf_desc); + TU_VERIFY(p_cdc); + + p_cdc->serial_drid = SERIAL_DRIVER_FTDI; + + // endpoint pair + tusb_desc_endpoint_t const *desc_ep = (tusb_desc_endpoint_t const *) tu_desc_next(itf_desc); + + /* + * NOTE: Some customers have programmed FT232R/FT245R devices + * with an endpoint size of 0 - not good. + */ + TU_ASSERT(desc_ep->wMaxPacketSize != 0); + + // data endpoints expected to be in pairs + return open_ep_stream_pair(p_cdc, desc_ep); +} + +static bool ftdi_proccess_set_config(cdch_interface_t *p_cdc, tuh_xfer_t *xfer) { + TU_ASSERT(xfer->result == XFER_RESULT_SUCCESS); + const uintptr_t state = xfer->user_data; + switch (state) { + // from here sequence overtaken from Linux Kernel function ftdi_port_probe() + case CONFIG_FTDI_DETERMINE_TYPE: + // determine type + if (p_cdc->bInterfaceNumber == 0) { + TU_ASSERT(ftdi_determine_type(p_cdc)); + } else { + // other interfaces have same type as interface 0 + uint8_t const idx_itf0 = tuh_cdc_itf_get_index(xfer->daddr, 0); + cdch_interface_t const *p_cdc_itf0 = get_itf(idx_itf0); + TU_ASSERT(p_cdc_itf0); + p_cdc->ftdi.chip_type = p_cdc_itf0->ftdi.chip_type; + } + TU_ATTR_FALLTHROUGH; + + case CONFIG_FTDI_WRITE_LATENCY: + #ifdef CFG_TUH_CDC_FTDI_LATENCY + int8_t result = ftdi_write_latency_timer(p_cdc, CFG_TUH_CDC_FTDI_LATENCY, ftdi_process_config, + CONFIG_FTDI_SIO_RESET); + TU_ASSERT(result != FTDI_FAIL); + if (result == FTDI_REQUESTED) { + break; + }// else FTDI_NOT_POSSIBLE => continue directly with next state + #endif + TU_ATTR_FALLTHROUGH; + + // from here sequence overtaken from Linux Kernel function ftdi_open() + case CONFIG_FTDI_SIO_RESET: + TU_ASSERT(ftdi_sio_reset(p_cdc, cdch_process_set_config, CONFIG_FTDI_FLOW_CONTROL)); + break; + + case CONFIG_FTDI_FLOW_CONTROL: + // disable flow control + TU_ASSERT(ftdi_set_request(p_cdc, FTDI_SIO_SET_FLOW_CTRL_REQUEST, FTDI_SIO_SET_FLOW_CTRL_REQUEST_TYPE, FTDI_SIO_DISABLE_FLOW_CTRL, + p_cdc->ftdi.channel, cdch_process_set_config, CONFIG_FTDI_COMPLETE)); + break; + + case CONFIG_FTDI_COMPLETE: { + xfer->user_data = 0; // kick-off set line state on enum + cdch_process_line_state_on_enum(xfer); + break; + } + + default: + return false; + } + + return true; +} + +//------------- Helper -------------// + +static bool ftdi_determine_type(cdch_interface_t *p_cdc) { + tusb_desc_device_t desc_dev; + TU_VERIFY(tuh_descriptor_get_device_local(p_cdc->daddr, &desc_dev)); + uint16_t const version = desc_dev.bcdDevice; + uint8_t const itf_num = p_cdc->bInterfaceNumber; + + p_cdc->ftdi.chip_type = FTDI_UNKNOWN; + + /* Assume Hi-Speed type */ + p_cdc->ftdi.channel = CHANNEL_A + itf_num; + + switch (version) { + case 0x200: + // FT232A not supported to keep it simple (no extra _read_latency_timer()) not testable + // p_cdc->ftdi.chip_type = FT232A; + // p_cdc->ftdi.baud_base = 48000000 / 2; + // p_cdc->ftdi.channel = 0; + // /* + // * FT232B devices have a bug where bcdDevice gets set to 0x200 + // * when iSerialNumber is 0. Assume it is an FT232B in case the + // * latency timer is readable. + // */ + // if (desc->iSerialNumber == 0 && + // _read_latency_timer(port) >= 0) { + // p_cdc->ftdi.chip_type = FTDI_FT232B; + // } + break; + + case 0x400 : p_cdc->ftdi.chip_type = FTDI_FT232B; p_cdc->ftdi.channel = 0; break; + case 0x500 : p_cdc->ftdi.chip_type = FTDI_FT2232C; break; + case 0x600 : p_cdc->ftdi.chip_type = FTDI_FT232R; p_cdc->ftdi.channel = 0; break; + case 0x700 : p_cdc->ftdi.chip_type = FTDI_FT2232H; break; + case 0x800 : p_cdc->ftdi.chip_type = FTDI_FT4232H; break; + case 0x900 : p_cdc->ftdi.chip_type = FTDI_FT232H; break; + case 0x1000: p_cdc->ftdi.chip_type = FTDI_FTX; break; + case 0x2800: p_cdc->ftdi.chip_type = FTDI_FT2233HP; break; + case 0x2900: p_cdc->ftdi.chip_type = FTDI_FT4233HP; break; + case 0x3000: p_cdc->ftdi.chip_type = FTDI_FT2232HP; break; + case 0x3100: p_cdc->ftdi.chip_type = FTDI_FT4232HP; break; + case 0x3200: p_cdc->ftdi.chip_type = FTDI_FT233HP; break; + case 0x3300: p_cdc->ftdi.chip_type = FTDI_FT232HP; break; + case 0x3600: p_cdc->ftdi.chip_type = FTDI_FT4232HA; break; + + default: + if (version < 0x200) { + p_cdc->ftdi.chip_type = FTDI_SIO; + p_cdc->ftdi.channel = 0; + } + break; + } + + #if CFG_TUSB_DEBUG >= CFG_TUH_CDC_LOG_LEVEL + const char * ftdi_chip_name[] = { FTDI_CHIP_NAMES }; + TU_LOG_CDC(p_cdc, "%s detected (bcdDevice = 0x%04x)", + ftdi_chip_name[p_cdc->ftdi.chip_type], version); + #endif + + return (p_cdc->ftdi.chip_type != FTDI_UNKNOWN); +} + +// FT232A not supported +//static uint32_t ftdi_232am_baud_base_to_divisor(uint32_t baud, uint32_t base) +//{ +// uint32_t divisor; +// /* divisor shifted 3 bits to the left */ +// uint32_t divisor3 = DIV_ROUND_CLOSEST(base, 2 * baud); +// if ((divisor3 & 0x7) == 7) +// divisor3++; /* round x.7/8 up to x+1 */ +// divisor = divisor3 >> 3; +// divisor3 &= 0x7; +// if (divisor3 == 1) +// divisor |= 0xc000; /* +0.125 */ +// else if (divisor3 >= 4) +// divisor |= 0x4000; /* +0.5 */ +// else if (divisor3 != 0) +// divisor |= 0x8000; /* +0.25 */ +// else if (divisor == 1) +// divisor = 0; /* special case for maximum baud rate */ +// return divisor; +//} + +// FT232A not supported +//static inline uint32_t ftdi_232am_baud_to_divisor(uint32_t baud) +//{ +// return ftdi_232am_baud_base_to_divisor(baud, (uint32_t) 48000000); +//} + +static uint32_t ftdi_232bm_baud_base_to_divisor(uint32_t baud, uint32_t base) { + uint8_t divfrac[8] = {0, 3, 2, 4, 1, 5, 6, 7}; + uint32_t divisor; + /* divisor shifted 3 bits to the left */ + uint32_t divisor3 = DIV_ROUND_CLOSEST(base, 2 * baud); + divisor = divisor3 >> 3; + divisor |= (uint32_t) divfrac[divisor3 & 0x7] << 14; + /* Deal with special cases for highest baud rates. */ + if (divisor == 1) /* 1.0 */ { + divisor = 0; + } else if (divisor == 0x4001) /* 1.5 */ { divisor = 1; } - return divisor; } -static uint32_t ftdi_232bm_baud_to_divisor(uint32_t baud) { - return ftdi_232bm_baud_base_to_divisor(baud, 48000000u); +static inline uint32_t ftdi_232bm_baud_to_divisor(uint32_t baud) { + return ftdi_232bm_baud_base_to_divisor(baud, 48000000); } -static bool ftdi_sio_set_baudrate(cdch_interface_t* p_cdc, uint32_t baudrate, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { - uint16_t const divisor = (uint16_t) ftdi_232bm_baud_to_divisor(baudrate); - TU_LOG_DRV("CDC FTDI Set BaudRate = %" PRIu32 ", divisor = 0x%04x\r\n", baudrate, divisor); +static uint32_t ftdi_2232h_baud_base_to_divisor(uint32_t baud, uint32_t base) { + static const unsigned char divfrac[8] = {0, 3, 2, 4, 1, 5, 6, 7}; + uint32_t divisor; + uint32_t divisor3; - p_cdc->user_control_cb = complete_cb; - p_cdc->requested_line_coding.bit_rate = baudrate; - TU_ASSERT(ftdi_sio_set_request(p_cdc, FTDI_SIO_SET_BAUD_RATE, divisor, - complete_cb ? cdch_internal_control_complete : NULL, user_data)); + /* hi-speed baud rate is 10-bit sampling instead of 16-bit */ + divisor3 = DIV_ROUND_CLOSEST(8 * base, 10 * baud); - return true; + divisor = divisor3 >> 3; + divisor |= (uint32_t) divfrac[divisor3 & 0x7] << 14; + /* Deal with special cases for highest baud rates. */ + if (divisor == 1) /* 1.0 */ { + divisor = 0; + } else if (divisor == 0x4001) /* 1.5 */ { + divisor = 1; + } + /* + * Set this bit to turn off a divide by 2.5 on baud rate generator + * This enables baud rates up to 12Mbaud but cannot reach below 1200 + * baud with this bit set + */ + divisor |= 0x00020000; + return divisor; } -static void ftdi_process_config(tuh_xfer_t* xfer) { - uintptr_t const state = xfer->user_data; - uint8_t const itf_num = (uint8_t) tu_le16toh(xfer->setup->wIndex); - uint8_t const idx = tuh_cdc_itf_get_index(xfer->daddr, itf_num); - cdch_interface_t * p_cdc = get_itf(idx); - TU_ASSERT(p_cdc, ); +static inline uint32_t ftdi_2232h_baud_to_divisor(uint32_t baud) { + return ftdi_2232h_baud_base_to_divisor(baud, (uint32_t) 120000000); +} - switch(state) { - // Note may need to read FTDI eeprom - case CONFIG_FTDI_RESET: - TU_ASSERT(ftdi_sio_reset(p_cdc, ftdi_process_config, CONFIG_FTDI_MODEM_CTRL),); +static inline uint32_t ftdi_get_divisor(cdch_interface_t *p_cdc) { + uint32_t baud = p_cdc->requested_line.coding.bit_rate; + uint32_t div_value = 0; + TU_VERIFY(baud); + + switch (p_cdc->ftdi.chip_type) { + case FTDI_UNKNOWN: + return 0; + case FTDI_SIO: + switch (baud) { + case 300: div_value = ftdi_sio_b300; break; + case 600: div_value = ftdi_sio_b600; break; + case 1200: div_value = ftdi_sio_b1200; break; + case 2400: div_value = ftdi_sio_b2400; break; + case 4800: div_value = ftdi_sio_b4800; break; + case 9600: div_value = ftdi_sio_b9600; break; + case 19200: div_value = ftdi_sio_b19200; break; + case 38400: div_value = ftdi_sio_b38400; break; + case 57600: div_value = ftdi_sio_b57600; break; + case 115200: div_value = ftdi_sio_b115200; break; + default: + // Baudrate not supported + return 0; + break; + } break; - - case CONFIG_FTDI_MODEM_CTRL: - #if CFG_TUH_CDC_LINE_CONTROL_ON_ENUM - TU_ASSERT(ftdi_sio_set_modem_ctrl(p_cdc, CFG_TUH_CDC_LINE_CONTROL_ON_ENUM, ftdi_process_config, CONFIG_FTDI_SET_BAUDRATE),); + // FT232A not supported + // case FT232A: + // if (baud <= 3000000) { + // div_value = ftdi_232am_baud_to_divisor(baud); + // } else { + // // Baud rate too high! + // baud = 9600; + // div_value = ftdi_232am_baud_to_divisor(9600); + // div_okay = false; + // } + // break; + case FTDI_FT232B: + case FTDI_FT2232C: + case FTDI_FT232R: + case FTDI_FTX: + TU_VERIFY(baud <= 3000000); // else Baud rate too high! + div_value = ftdi_232bm_baud_to_divisor(baud); break; - #else - TU_ATTR_FALLTHROUGH; - #endif - - case CONFIG_FTDI_SET_BAUDRATE: { - #ifdef CFG_TUH_CDC_LINE_CODING_ON_ENUM - cdc_line_coding_t line_coding = CFG_TUH_CDC_LINE_CODING_ON_ENUM; - TU_ASSERT(ftdi_sio_set_baudrate(p_cdc, line_coding.bit_rate, ftdi_process_config, CONFIG_FTDI_SET_DATA),); - break; - #else - TU_ATTR_FALLTHROUGH; - #endif - } - - case CONFIG_FTDI_SET_DATA: { - #if 0 // TODO set data format - #ifdef CFG_TUH_CDC_LINE_CODING_ON_ENUM - cdc_line_coding_t line_coding = CFG_TUH_CDC_LINE_CODING_ON_ENUM; - TU_ASSERT(ftdi_sio_set_data(p_cdc, process_ftdi_config, CONFIG_FTDI_COMPLETE),); - break; - #endif - #endif - - TU_ATTR_FALLTHROUGH; - } - - case CONFIG_FTDI_COMPLETE: - set_config_complete(p_cdc, idx, itf_num); - break; - + case FTDI_FT232H: + case FTDI_FT2232H: + case FTDI_FT4232H: + case FTDI_FT4232HA: + case FTDI_FT232HP: + case FTDI_FT233HP: + case FTDI_FT2232HP: + case FTDI_FT2233HP: + case FTDI_FT4232HP: + case FTDI_FT4233HP: default: + TU_VERIFY(baud <= 12000000); // else Baud rate too high! + if (baud >= 1200) { + div_value = ftdi_2232h_baud_to_divisor(baud); + } else { + div_value = ftdi_232bm_baud_to_divisor(baud); + } break; } + + TU_LOG_CDC(p_cdc, "Baudrate divisor = 0x%lu", div_value); + + return div_value; } #endif @@ -1156,36 +1472,12 @@ static void ftdi_process_config(tuh_xfer_t* xfer) { //--------------------------------------------------------------------+ // CP210x //--------------------------------------------------------------------+ - #if CFG_TUH_CDC_CP210X -enum { - CONFIG_CP210X_IFC_ENABLE = 0, - CONFIG_CP210X_SET_BAUDRATE, - CONFIG_CP210X_SET_LINE_CTL, - CONFIG_CP210X_SET_DTR_RTS, - CONFIG_CP210X_COMPLETE -}; +//------------- Control Request -------------// -static bool cp210x_open(uint8_t daddr, tusb_desc_interface_t const *itf_desc, uint16_t max_len) { - // CP210x Interface includes 1 vendor interface + 2 bulk endpoints - TU_VERIFY(itf_desc->bInterfaceSubClass == 0 && itf_desc->bInterfaceProtocol == 0 && itf_desc->bNumEndpoints == 2); - TU_VERIFY(sizeof(tusb_desc_interface_t) + 2*sizeof(tusb_desc_endpoint_t) <= max_len); - - cdch_interface_t * p_cdc = make_new_itf(daddr, itf_desc); - TU_VERIFY(p_cdc); - - TU_LOG_DRV("CP210x opened\r\n"); - p_cdc->serial_drid = SERIAL_DRIVER_CP210X; - - // endpoint pair - tusb_desc_endpoint_t const * desc_ep = (tusb_desc_endpoint_t const *) tu_desc_next(itf_desc); - - // data endpoints expected to be in pairs - return open_ep_stream_pair(p_cdc, desc_ep); -} - -static bool cp210x_set_request(cdch_interface_t* p_cdc, uint8_t command, uint16_t value, uint8_t* buffer, uint16_t length, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { +static bool cp210x_set_request(cdch_interface_t * p_cdc, uint8_t command, uint16_t value, + uint8_t * buffer, uint16_t length, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { tusb_control_request_t const request = { .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_INTERFACE, @@ -1194,12 +1486,12 @@ static bool cp210x_set_request(cdch_interface_t* p_cdc, uint8_t command, uint16_ }, .bRequest = command, .wValue = tu_htole16(value), - .wIndex = p_cdc->bInterfaceNumber, + .wIndex = tu_htole16((uint16_t) p_cdc->bInterfaceNumber), .wLength = tu_htole16(length) }; // use usbh enum buf since application variable does not live long enough - uint8_t* enum_buf = NULL; + uint8_t * enum_buf = NULL; if (buffer && length > 0) { enum_buf = usbh_get_enum_buf(); @@ -1218,93 +1510,105 @@ static bool cp210x_set_request(cdch_interface_t* p_cdc, uint8_t command, uint16_ return tuh_control_xfer(&xfer); } -static bool cp210x_ifc_enable(cdch_interface_t* p_cdc, uint16_t enabled, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { +TU_ATTR_ALWAYS_INLINE static inline bool cp210x_ifc_enable(cdch_interface_t *p_cdc, uint16_t enabled, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { return cp210x_set_request(p_cdc, CP210X_IFC_ENABLE, enabled, NULL, 0, complete_cb, user_data); } -static bool cp210x_set_line_coding(cdch_interface_t* p_cdc, cdc_line_coding_t const* line_coding, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { - // TODO implement later - (void) p_cdc; - (void) line_coding; - (void) complete_cb; - (void) user_data; - return false; +TU_ATTR_ALWAYS_INLINE static inline bool cp210x_set_mhs(cdch_interface_t *p_cdc, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { + // CP210x has the same bit coding + return cp210x_set_request(p_cdc, CP210X_SET_MHS, + (uint16_t) (CP210X_CONTROL_WRITE_DTR | CP210X_CONTROL_WRITE_RTS | p_cdc->requested_line.control_state.value), + NULL, 0, complete_cb, user_data); } -static bool cp210x_set_baudrate(cdch_interface_t* p_cdc, uint32_t baudrate, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { - TU_LOG_DRV("CDC CP210x Set BaudRate = %" PRIu32 "\r\n", baudrate); - uint32_t baud_le = tu_htole32(baudrate); - p_cdc->user_control_cb = complete_cb; - return cp210x_set_request(p_cdc, CP210X_SET_BAUDRATE, 0, (uint8_t *) &baud_le, 4, - complete_cb ? cdch_internal_control_complete : NULL, user_data); -} +//------------- Driver API -------------// -static bool cp210x_set_data_format(cdch_interface_t* p_cdc, uint8_t stop_bits, uint8_t parity, uint8_t data_bits, - tuh_xfer_cb_t complete_cb, uintptr_t user_data) { - (void) p_cdc; - (void) stop_bits; - (void) parity; - (void) data_bits; - (void) complete_cb; - (void) user_data; - // TODO not implemented yet - return false; -} - -static bool cp210x_set_modem_ctrl(cdch_interface_t* p_cdc, uint16_t line_state, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { - TU_LOG_DRV("CDC CP210x Set Control Line State\r\n"); - p_cdc->user_control_cb = complete_cb; - return cp210x_set_request(p_cdc, CP210X_SET_MHS, 0x0300 | line_state, NULL, 0, - complete_cb ? cdch_internal_control_complete : NULL, user_data); -} - -static void cp210x_process_config(tuh_xfer_t* xfer) { - uintptr_t const state = xfer->user_data; - uint8_t const itf_num = (uint8_t) tu_le16toh(xfer->setup->wIndex); - uint8_t const idx = tuh_cdc_itf_get_index(xfer->daddr, itf_num); - cdch_interface_t *p_cdc = get_itf(idx); - TU_ASSERT(p_cdc,); - - switch (state) { - case CONFIG_CP210X_IFC_ENABLE: - TU_ASSERT(cp210x_ifc_enable(p_cdc, 1, cp210x_process_config, CONFIG_CP210X_SET_BAUDRATE),); +// internal control complete to update state such as line state, encoding +static void cp210x_internal_control_complete(cdch_interface_t *p_cdc, tuh_xfer_t *xfer) { + TU_VERIFY(xfer->result == XFER_RESULT_SUCCESS,); + switch (xfer->setup->bRequest) { + case CP210X_SET_MHS: + p_cdc->line.control_state = p_cdc->requested_line.control_state; break; - case CONFIG_CP210X_SET_BAUDRATE: { - #ifdef CFG_TUH_CDC_LINE_CODING_ON_ENUM - cdc_line_coding_t line_coding = CFG_TUH_CDC_LINE_CODING_ON_ENUM; - TU_ASSERT(cp210x_set_baudrate(p_cdc, line_coding.bit_rate, cp210x_process_config, CONFIG_CP210X_SET_LINE_CTL),); + case CP210X_SET_LINE_CTL: + p_cdc->line.coding.stop_bits = p_cdc->requested_line.coding.stop_bits; + p_cdc->line.coding.parity = p_cdc->requested_line.coding.parity; + p_cdc->line.coding.data_bits = p_cdc->requested_line.coding.data_bits; break; - #else - TU_ATTR_FALLTHROUGH; - #endif - } - case CONFIG_CP210X_SET_LINE_CTL: { - #if defined(CFG_TUH_CDC_LINE_CODING_ON_ENUM) && 0 // skip for now - cdc_line_coding_t line_coding = CFG_TUH_CDC_LINE_CODING_ON_ENUM; - break; - #else - TU_ATTR_FALLTHROUGH; - #endif - } - - case CONFIG_CP210X_SET_DTR_RTS: - #if CFG_TUH_CDC_LINE_CONTROL_ON_ENUM - TU_ASSERT(cp210x_set_modem_ctrl(p_cdc, CFG_TUH_CDC_LINE_CONTROL_ON_ENUM, cp210x_process_config, CONFIG_CP210X_COMPLETE),); - break; - #else - TU_ATTR_FALLTHROUGH; - #endif - - case CONFIG_CP210X_COMPLETE: - set_config_complete(p_cdc, idx, itf_num); + case CP210X_SET_BAUDRATE: + p_cdc->line.coding.bit_rate = p_cdc->requested_line.coding.bit_rate; break; default: break; } } +static bool cp210x_set_baudrate(cdch_interface_t *p_cdc, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { + // Not every baud rate is supported. See datasheets and AN205 "CP210x Baud Rate Support" + uint32_t baud_le = tu_htole32(p_cdc->requested_line.coding.bit_rate); + return cp210x_set_request(p_cdc, CP210X_SET_BAUDRATE, 0, (uint8_t *) &baud_le, 4, complete_cb, user_data); +} + +static bool cp210x_set_data_format(cdch_interface_t *p_cdc, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { + TU_VERIFY(p_cdc->requested_line.coding.data_bits >= 5 && p_cdc->requested_line.coding.data_bits <= 8, 0); + uint16_t lcr = (uint16_t) ((p_cdc->requested_line.coding.data_bits & 0xfUL) << 8 | // data bit quantity is stored in bits 8-11 + (p_cdc->requested_line.coding.parity & 0xfUL) << 4 | // parity is stored in bits 4-7, same coding + (p_cdc->requested_line.coding.stop_bits & 0xfUL)); // parity is stored in bits 0-3, same coding + + return cp210x_set_request(p_cdc, CP210X_SET_LINE_CTL, lcr, NULL, 0, complete_cb, user_data); +} + +static bool cp210x_set_modem_ctrl(cdch_interface_t *p_cdc, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { + return cp210x_set_mhs(p_cdc, complete_cb, user_data); +} + +//------------- Enumeration -------------// + +enum { + CONFIG_CP210X_IFC_ENABLE = 0, + CONFIG_CP210X_COMPLETE +}; + +static bool cp210x_open(uint8_t daddr, tusb_desc_interface_t const *itf_desc, uint16_t max_len) { + // CP210x Interface includes 1 vendor interface + 2 bulk endpoints + TU_VERIFY(itf_desc->bInterfaceSubClass == 0 && itf_desc->bInterfaceProtocol == 0 && itf_desc->bNumEndpoints == 2); + TU_VERIFY(sizeof(tusb_desc_interface_t) + 2 * sizeof(tusb_desc_endpoint_t) <= max_len); + + cdch_interface_t *p_cdc = make_new_itf(daddr, itf_desc); + TU_VERIFY(p_cdc); + + p_cdc->serial_drid = SERIAL_DRIVER_CP210X; + + // endpoint pair + tusb_desc_endpoint_t const *desc_ep = (tusb_desc_endpoint_t const *) tu_desc_next(itf_desc); + + // data endpoints expected to be in pairs + return open_ep_stream_pair(p_cdc, desc_ep); +} + +static bool cp210x_process_set_config(cdch_interface_t *p_cdc, tuh_xfer_t *xfer) { + TU_ASSERT(xfer->result == XFER_RESULT_SUCCESS); + const uintptr_t state = xfer->user_data; + + switch (state) { + case CONFIG_CP210X_IFC_ENABLE: + TU_ASSERT(cp210x_ifc_enable(p_cdc, CP210X_UART_ENABLE, cdch_process_set_config, CONFIG_CP210X_COMPLETE)); + break; + + case CONFIG_CP210X_COMPLETE: + xfer->user_data = 0;// kick-off set line state on enum + cdch_process_line_state_on_enum(xfer); + break; + + default: + return false; + } + + return true; +} + #endif //--------------------------------------------------------------------+ @@ -1313,13 +1617,14 @@ static void cp210x_process_config(tuh_xfer_t* xfer) { #if CFG_TUH_CDC_CH34X -static uint8_t ch34x_get_lcr(uint8_t stop_bits, uint8_t parity, uint8_t data_bits); -static uint16_t ch34x_get_divisor_prescaler(uint32_t baval); +static uint8_t ch34x_get_lcr(cdch_interface_t *p_cdc); +static uint16_t ch34x_get_divisor_prescaler(cdch_interface_t *p_cdc); -//------------- control request -------------// +//------------- Control Request -------------// -static bool ch34x_set_request(cdch_interface_t* p_cdc, uint8_t direction, uint8_t request, uint16_t value, - uint16_t index, uint8_t* buffer, uint16_t length, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { +static bool ch34x_set_request(cdch_interface_t *p_cdc, uint8_t direction, uint8_t request, + uint16_t value, uint16_t index, uint8_t *buffer, uint16_t length, + tuh_xfer_cb_t complete_cb, uintptr_t user_data) { tusb_control_request_t const request_setup = { .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_DEVICE, @@ -1327,13 +1632,13 @@ static bool ch34x_set_request(cdch_interface_t* p_cdc, uint8_t direction, uint8_ .direction = direction & 0x01u }, .bRequest = request, - .wValue = tu_htole16 (value), - .wIndex = tu_htole16 (index), - .wLength = tu_htole16 (length) + .wValue = tu_htole16(value), + .wIndex = tu_htole16(index), + .wLength = tu_htole16(length) }; // use usbh enum buf since application variable does not live long enough - uint8_t* enum_buf = NULL; + uint8_t *enum_buf = NULL; if (buffer && length > 0) { enum_buf = usbh_get_enum_buf(); @@ -1354,164 +1659,101 @@ static bool ch34x_set_request(cdch_interface_t* p_cdc, uint8_t direction, uint8_ return tuh_control_xfer(&xfer); } -static inline bool ch34x_control_out(cdch_interface_t* p_cdc, uint8_t request, uint16_t value, uint16_t index, - tuh_xfer_cb_t complete_cb, uintptr_t user_data) { +TU_ATTR_ALWAYS_INLINE static inline bool ch34x_control_out(cdch_interface_t *p_cdc, uint8_t request, uint16_t value, uint16_t index, + tuh_xfer_cb_t complete_cb, uintptr_t user_data) { return ch34x_set_request(p_cdc, TUSB_DIR_OUT, request, value, index, NULL, 0, complete_cb, user_data); } -static inline bool ch34x_control_in(cdch_interface_t* p_cdc, uint8_t request, uint16_t value, uint16_t index, - uint8_t* buffer, uint16_t buffersize, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { +TU_ATTR_ALWAYS_INLINE static inline bool ch34x_control_in(cdch_interface_t *p_cdc, uint8_t request, uint16_t value, uint16_t index, + uint8_t *buffer, uint16_t buffersize, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { return ch34x_set_request(p_cdc, TUSB_DIR_IN, request, value, index, buffer, buffersize, complete_cb, user_data); } -static inline bool ch34x_write_reg(cdch_interface_t* p_cdc, uint16_t reg, uint16_t reg_value, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { +TU_ATTR_ALWAYS_INLINE static inline bool ch34x_write_reg(cdch_interface_t *p_cdc, uint16_t reg, uint16_t reg_value, + tuh_xfer_cb_t complete_cb, uintptr_t user_data) { return ch34x_control_out(p_cdc, CH34X_REQ_WRITE_REG, reg, reg_value, complete_cb, user_data); } -//static bool ch34x_read_reg_request ( cdch_interface_t* p_cdc, uint16_t reg, +//static bool ch34x_read_reg_request ( cdch_interface_t * p_cdc, uint16_t reg, // uint8_t *buffer, uint16_t buffersize, tuh_xfer_cb_t complete_cb, uintptr_t user_data ) //{ // return ch34x_control_in ( p_cdc, CH34X_REQ_READ_REG, reg, 0, buffer, buffersize, complete_cb, user_data ); //} -static bool ch34x_write_reg_baudrate(cdch_interface_t* p_cdc, uint32_t baudrate, - tuh_xfer_cb_t complete_cb, uintptr_t user_data) { - uint16_t const div_ps = ch34x_get_divisor_prescaler(baudrate); - TU_VERIFY(div_ps); - TU_ASSERT(ch34x_write_reg(p_cdc, CH34X_REG16_DIVISOR_PRESCALER, div_ps, - complete_cb, user_data)); - return true; -} - //------------- Driver API -------------// // internal control complete to update state such as line state, encoding -static void ch34x_control_complete(tuh_xfer_t* xfer) { - // CH34x only has 1 interface and use wIndex as payload and not for bInterfaceNumber - process_internal_control_complete(xfer, 0); +static void ch34x_internal_control_complete(cdch_interface_t *p_cdc, tuh_xfer_t *xfer) { + TU_VERIFY(xfer->result == XFER_RESULT_SUCCESS,); + switch (xfer->setup->bRequest) { + case CH34X_REQ_WRITE_REG: + // register write request + switch (tu_le16toh(xfer->setup->wValue)) { + case CH34X_REG16_DIVISOR_PRESCALER: + // baudrate + p_cdc->line.coding.bit_rate = p_cdc->requested_line.coding.bit_rate; + break; + + case CH32X_REG16_LCR2_LCR: + // data format + p_cdc->line.coding.stop_bits = p_cdc->requested_line.coding.stop_bits; + p_cdc->line.coding.parity = p_cdc->requested_line.coding.parity; + p_cdc->line.coding.data_bits = p_cdc->requested_line.coding.data_bits; + break; + + default: break; + } + break; + + case CH34X_REQ_MODEM_CTRL: + p_cdc->line.control_state = p_cdc->requested_line.control_state; + break; + + default: break; + } } -static bool ch34x_set_data_format(cdch_interface_t* p_cdc, uint8_t stop_bits, uint8_t parity, uint8_t data_bits, - tuh_xfer_cb_t complete_cb, uintptr_t user_data) { - p_cdc->requested_line_coding.stop_bits = stop_bits; - p_cdc->requested_line_coding.parity = parity; - p_cdc->requested_line_coding.data_bits = data_bits; - - uint8_t const lcr = ch34x_get_lcr(stop_bits, parity, data_bits); +static bool ch34x_set_data_format(cdch_interface_t *p_cdc, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { + const uint8_t lcr = ch34x_get_lcr(p_cdc); TU_VERIFY(lcr); - TU_ASSERT (ch34x_control_out(p_cdc, CH34X_REQ_WRITE_REG, CH32X_REG16_LCR2_LCR, lcr, - complete_cb ? ch34x_control_complete : NULL, user_data)); - return true; + return ch34x_write_reg(p_cdc, CH32X_REG16_LCR2_LCR, lcr, complete_cb, user_data); } -static bool ch34x_set_baudrate(cdch_interface_t* p_cdc, uint32_t baudrate, - tuh_xfer_cb_t complete_cb, uintptr_t user_data) { - p_cdc->requested_line_coding.bit_rate = baudrate; - p_cdc->user_control_cb = complete_cb; - TU_ASSERT(ch34x_write_reg_baudrate(p_cdc, baudrate, - complete_cb ? ch34x_control_complete : NULL, user_data)); - return true; +static bool ch34x_set_baudrate(cdch_interface_t *p_cdc, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { + const uint16_t div_ps = ch34x_get_divisor_prescaler(p_cdc); + TU_VERIFY(div_ps); + return ch34x_write_reg(p_cdc, CH34X_REG16_DIVISOR_PRESCALER, div_ps, complete_cb, user_data); } -static void ch34x_set_line_coding_stage1_complete(tuh_xfer_t* xfer) { - // CH34x only has 1 interface and use wIndex as payload and not for bInterfaceNumber - uint8_t const itf_num = 0; - uint8_t const idx = tuh_cdc_itf_get_index(xfer->daddr, itf_num); - cdch_interface_t* p_cdc = get_itf(idx); - TU_ASSERT(p_cdc, ); - - if (xfer->result == XFER_RESULT_SUCCESS) { - // stage 1 success, continue to stage 2 - p_cdc->line_coding.bit_rate = p_cdc->requested_line_coding.bit_rate; - TU_ASSERT(ch34x_set_data_format(p_cdc, p_cdc->requested_line_coding.stop_bits, p_cdc->requested_line_coding.parity, - p_cdc->requested_line_coding.data_bits, ch34x_control_complete, xfer->user_data), ); - } else { - // stage 1 failed, notify user - xfer->complete_cb = p_cdc->user_control_cb; - if (xfer->complete_cb) { - xfer->complete_cb(xfer); - } - } -} - -// 2 stages: set baudrate (stage1) + set data format (stage2) -static bool ch34x_set_line_coding(cdch_interface_t* p_cdc, cdc_line_coding_t const* line_coding, - tuh_xfer_cb_t complete_cb, uintptr_t user_data) { - p_cdc->requested_line_coding = *line_coding; - p_cdc->user_control_cb = complete_cb; - - if (complete_cb) { - // stage 1 set baudrate - TU_ASSERT(ch34x_write_reg_baudrate(p_cdc, line_coding->bit_rate, - ch34x_set_line_coding_stage1_complete, user_data)); - } else { - // sync call - xfer_result_t result; - - // stage 1 set baudrate - TU_ASSERT(ch34x_write_reg_baudrate(p_cdc, line_coding->bit_rate, NULL, (uintptr_t) &result)); - TU_VERIFY(result == XFER_RESULT_SUCCESS); - p_cdc->line_coding.bit_rate = line_coding->bit_rate; - - // stage 2 set data format - TU_ASSERT(ch34x_set_data_format(p_cdc, line_coding->stop_bits, line_coding->parity, line_coding->data_bits, - NULL, (uintptr_t) &result)); - TU_VERIFY(result == XFER_RESULT_SUCCESS); - p_cdc->line_coding.stop_bits = line_coding->stop_bits; - p_cdc->line_coding.parity = line_coding->parity; - p_cdc->line_coding.data_bits = line_coding->data_bits; - - // update transfer result, user_data is expected to point to xfer_result_t - if (user_data) { - *((xfer_result_t*) user_data) = result; - } - } - - return true; -} - -static bool ch34x_set_modem_ctrl(cdch_interface_t* p_cdc, uint16_t line_state, - tuh_xfer_cb_t complete_cb, uintptr_t user_data) { - uint8_t control = 0; - if (line_state & CDC_CONTROL_LINE_STATE_RTS) { - control |= CH34X_BIT_RTS; - } - if (line_state & CDC_CONTROL_LINE_STATE_DTR) { - control |= CH34X_BIT_DTR; - } - +static bool ch34x_set_modem_ctrl(cdch_interface_t * p_cdc, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { // CH34x signals are inverted - control = ~control; - - p_cdc->user_control_cb = complete_cb; - TU_ASSERT (ch34x_control_out(p_cdc, CH34X_REQ_MODEM_CTRL, control, 0, - complete_cb ? ch34x_control_complete : NULL, user_data)); - return true; + uint8_t control = ~((p_cdc->requested_line.control_state.rts ? CH34X_BIT_RTS : 0) | + (p_cdc->requested_line.control_state.dtr ? CH34X_BIT_DTR : 0)); + return ch34x_control_out(p_cdc, CH34X_REQ_MODEM_CTRL, control, 0, complete_cb, user_data); } //------------- Enumeration -------------// + enum { CONFIG_CH34X_READ_VERSION = 0, CONFIG_CH34X_SERIAL_INIT, CONFIG_CH34X_SPECIAL_REG_WRITE, CONFIG_CH34X_FLOW_CONTROL, - CONFIG_CH34X_MODEM_CONTROL, CONFIG_CH34X_COMPLETE }; -static bool ch34x_open(uint8_t daddr, tusb_desc_interface_t const* itf_desc, uint16_t max_len) { +static bool ch34x_open(uint8_t daddr, tusb_desc_interface_t const * itf_desc, uint16_t max_len) { // CH34x Interface includes 1 vendor interface + 2 bulk + 1 interrupt endpoints - TU_VERIFY (itf_desc->bNumEndpoints == 3); - TU_VERIFY (sizeof(tusb_desc_interface_t) + 3 * sizeof(tusb_desc_endpoint_t) <= max_len); + TU_VERIFY(itf_desc->bNumEndpoints == 3); + TU_VERIFY(sizeof(tusb_desc_interface_t) + 3 * sizeof(tusb_desc_endpoint_t) <= max_len); - cdch_interface_t* p_cdc = make_new_itf(daddr, itf_desc); - TU_VERIFY (p_cdc); + cdch_interface_t * p_cdc = make_new_itf(daddr, itf_desc); + TU_VERIFY(p_cdc); - TU_LOG_DRV ("CH34x opened\r\n"); p_cdc->serial_drid = SERIAL_DRIVER_CH34X; - tusb_desc_endpoint_t const* desc_ep = (tusb_desc_endpoint_t const*) tu_desc_next(itf_desc); + tusb_desc_endpoint_t const * desc_ep = (tusb_desc_endpoint_t const *) tu_desc_next(itf_desc); // data endpoints expected to be in pairs TU_ASSERT(open_ep_stream_pair(p_cdc, desc_ep)); @@ -1526,69 +1768,66 @@ static bool ch34x_open(uint8_t daddr, tusb_desc_interface_t const* itf_desc, uin return true; } -static void ch34x_process_config(tuh_xfer_t* xfer) { - // CH34x only has 1 interface and use wIndex as payload and not for bInterfaceNumber - uint8_t const itf_num = 0; - uint8_t const idx = tuh_cdc_itf_get_index(xfer->daddr, itf_num); - cdch_interface_t* p_cdc = get_itf(idx); - uintptr_t const state = xfer->user_data; - uint8_t buffer[2]; // TODO remove - TU_ASSERT (p_cdc,); - TU_ASSERT (xfer->result == XFER_RESULT_SUCCESS,); +static bool ch34x_process_set_config(cdch_interface_t *p_cdc, tuh_xfer_t *xfer) { + TU_ASSERT(xfer->result == XFER_RESULT_SUCCESS); + const uintptr_t state = xfer->user_data; switch (state) { - case CONFIG_CH34X_READ_VERSION: - TU_LOG_DRV("[%u] CDCh CH34x attempt to read Chip Version\r\n", p_cdc->daddr); - TU_ASSERT (ch34x_control_in(p_cdc, CH34X_REQ_READ_VERSION, 0, 0, buffer, 2, ch34x_process_config, CONFIG_CH34X_SERIAL_INIT),); + case CONFIG_CH34X_READ_VERSION: { + uint8_t* enum_buf = usbh_get_enum_buf(); + TU_ASSERT(ch34x_control_in(p_cdc, CH34X_REQ_READ_VERSION, 0, 0, enum_buf, 2, + cdch_process_set_config, CONFIG_CH34X_SERIAL_INIT)); break; + } case CONFIG_CH34X_SERIAL_INIT: { // handle version read data, set CH34x line coding (incl. baudrate) uint8_t const version = xfer->buffer[0]; - TU_LOG_DRV("[%u] CDCh CH34x Chip Version = %02x\r\n", p_cdc->daddr, version); - // only versions >= 0x30 are tested, below 0x30 seems having other programming, see drivers from WCH vendor, Linux kernel and FreeBSD - TU_ASSERT (version >= 0x30,); - // init CH34x with line coding - cdc_line_coding_t const line_coding = CFG_TUH_CDC_LINE_CODING_ON_ENUM_CH34X; - uint16_t const div_ps = ch34x_get_divisor_prescaler(line_coding.bit_rate); - TU_ASSERT(div_ps, ); - uint8_t const lcr = ch34x_get_lcr(line_coding.stop_bits, line_coding.parity, line_coding.data_bits); - TU_ASSERT(lcr, ); - TU_ASSERT (ch34x_control_out(p_cdc, CH34X_REQ_SERIAL_INIT, tu_u16(lcr, 0x9c), div_ps, - ch34x_process_config, CONFIG_CH34X_SPECIAL_REG_WRITE),); + TU_LOG_CDC(p_cdc, "Chip Version = 0x%02x", version); + // only versions >= 0x30 are tested, below 0x30 seems having other programming + // see drivers from WCH vendor, Linux kernel and FreeBSD + if (version >= 0x30) { + // init CH34x with line coding + p_cdc->requested_line.coding = (cdc_line_coding_t) CFG_TUH_CDC_LINE_CODING_ON_ENUM_CH34X; + uint16_t const div_ps = ch34x_get_divisor_prescaler(p_cdc); + uint8_t const lcr = ch34x_get_lcr(p_cdc); + TU_ASSERT(div_ps != 0 && lcr != 0); + TU_ASSERT(ch34x_control_out(p_cdc, CH34X_REQ_SERIAL_INIT, tu_u16(lcr, 0x9c), div_ps, + cdch_process_set_config, CONFIG_CH34X_SPECIAL_REG_WRITE)); + } break; } case CONFIG_CH34X_SPECIAL_REG_WRITE: // overtake line coding and do special reg write, purpose unknown, overtaken from WCH driver - p_cdc->line_coding = ((cdc_line_coding_t) CFG_TUH_CDC_LINE_CODING_ON_ENUM_CH34X); - TU_ASSERT (ch34x_write_reg(p_cdc, TU_U16(CH341_REG_0x0F, CH341_REG_0x2C), 0x0007, ch34x_process_config, CONFIG_CH34X_FLOW_CONTROL),); + p_cdc->line.coding = (cdc_line_coding_t) CFG_TUH_CDC_LINE_CODING_ON_ENUM_CH34X; + TU_ASSERT(ch34x_write_reg(p_cdc, TU_U16(CH341_REG_0x0F, CH341_REG_0x2C), 0x0007, + cdch_process_set_config, CONFIG_CH34X_FLOW_CONTROL)); break; case CONFIG_CH34X_FLOW_CONTROL: // no hardware flow control - TU_ASSERT (ch34x_write_reg(p_cdc, TU_U16(CH341_REG_0x27, CH341_REG_0x27), 0x0000, ch34x_process_config, CONFIG_CH34X_MODEM_CONTROL),); - break; - - case CONFIG_CH34X_MODEM_CONTROL: - // !always! set modem controls RTS/DTR (CH34x has no reset state after CH34X_REQ_SERIAL_INIT) - TU_ASSERT (ch34x_set_modem_ctrl(p_cdc, CFG_TUH_CDC_LINE_CONTROL_ON_ENUM, ch34x_process_config, CONFIG_CH34X_COMPLETE),); + TU_ASSERT(ch34x_write_reg(p_cdc, TU_U16(CH341_REG_0x27, CH341_REG_0x27), 0x0000, + cdch_process_set_config, CONFIG_CH34X_COMPLETE)); break; case CONFIG_CH34X_COMPLETE: - set_config_complete(p_cdc, idx, itf_num); + xfer->user_data = 0; // kick-off set line state on enum + cdch_process_line_state_on_enum(xfer); break; default: - TU_ASSERT (false,); - break; + return false; } + + return true; } -//------------- CH34x helper -------------// +//------------- Helper -------------// // calculate divisor and prescaler for baudrate, return it as 16-bit combined value -static uint16_t ch34x_get_divisor_prescaler(uint32_t baval) { +static uint16_t ch34x_get_divisor_prescaler(cdch_interface_t *p_cdc) { + uint32_t const baval = p_cdc->requested_line.coding.bit_rate; uint8_t a; uint8_t b; uint32_t c; @@ -1633,16 +1872,20 @@ static uint16_t ch34x_get_divisor_prescaler(uint32_t baval) { // reg divisor = a, reg prescaler = b // According to linux code we need to set bit 7 of UCHCOM_REG_BPS_PRE, // otherwise the chip will buffer data. - return (uint16_t) ((uint16_t)a << 8 | 0x80 | b); + return (uint16_t) ((uint16_t) a << 8 | 0x80 | b); } // calculate lcr value from data coding -static uint8_t ch34x_get_lcr(uint8_t stop_bits, uint8_t parity, uint8_t data_bits) { +static uint8_t ch34x_get_lcr(cdch_interface_t *p_cdc) { + uint8_t const stop_bits = p_cdc->requested_line.coding.stop_bits; + uint8_t const parity = p_cdc->requested_line.coding.parity; + uint8_t const data_bits = p_cdc->requested_line.coding.data_bits; + uint8_t lcr = CH34X_LCR_ENABLE_RX | CH34X_LCR_ENABLE_TX; - TU_VERIFY(data_bits >= 5 && data_bits <= 8, 0); + TU_VERIFY(data_bits >= 5 && data_bits <= 8); lcr |= (uint8_t) (data_bits - 5); - switch(parity) { + switch (parity) { case CDC_LINE_CODING_PARITY_NONE: break; @@ -1666,7 +1909,7 @@ static uint8_t ch34x_get_lcr(uint8_t stop_bits, uint8_t parity, uint8_t data_bit } // 1.5 stop bits not supported - TU_VERIFY(stop_bits != CDC_LINE_CODING_STOP_BITS_1_5, 0); + TU_VERIFY(stop_bits != CDC_LINE_CODING_STOP_BITS_1_5); if (stop_bits == CDC_LINE_CODING_STOP_BITS_2) { lcr |= CH34X_LCR_STOP_BITS_2; } @@ -1674,7 +1917,612 @@ static uint8_t ch34x_get_lcr(uint8_t stop_bits, uint8_t parity, uint8_t data_bit return lcr; } - #endif // CFG_TUH_CDC_CH34X +//--------------------------------------------------------------------+ +// PL2303 +//--------------------------------------------------------------------+ +#if CFG_TUH_CDC_PL2303 + +static pl2303_type_t pl2303_detect_type(cdch_interface_t *p_cdc, uint8_t step); +static bool pl2303_encode_baud_rate(cdch_interface_t *p_cdc, uint8_t buf[PL2303_LINE_CODING_BAUDRATE_BUFSIZE]); + +//------------- Control Request -------------// +static bool pl2303_set_request(cdch_interface_t *p_cdc, uint8_t request, uint8_t requesttype, + uint16_t value, uint16_t index, uint8_t *buffer, uint16_t length, + tuh_xfer_cb_t complete_cb, uintptr_t user_data) { + tusb_control_request_t const request_setup = { + .bmRequestType = requesttype, + .bRequest = request, + .wValue = tu_htole16(value), + .wIndex = tu_htole16(index), + .wLength = tu_htole16(length) + }; + + // use usbh enum buf since application variable does not live long enough + uint8_t *enum_buf = NULL; + + if (buffer && length > 0) { + enum_buf = usbh_get_enum_buf(); + if (request_setup.bmRequestType_bit.direction == TUSB_DIR_OUT) { + tu_memcpy_s(enum_buf, CFG_TUH_ENUMERATION_BUFSIZE, buffer, length); + } + } + + tuh_xfer_t xfer = { + .daddr = p_cdc->daddr, + .ep_addr = 0, + .setup = &request_setup, + .buffer = enum_buf, + .complete_cb = complete_cb, + .user_data = user_data + }; + + return tuh_control_xfer(&xfer); +} + +static bool pl2303_vendor_read(cdch_interface_t *p_cdc, uint16_t value, uint8_t *buf, + tuh_xfer_cb_t complete_cb, uintptr_t user_data) { + uint8_t request = p_cdc->pl2303.type == PL2303_TYPE_HXN ? PL2303_VENDOR_READ_NREQUEST : PL2303_VENDOR_READ_REQUEST; + return pl2303_set_request(p_cdc, request, PL2303_VENDOR_READ_REQUEST_TYPE, value, 0, buf, 1, complete_cb, user_data); +} + +static bool pl2303_vendor_write(cdch_interface_t *p_cdc, uint16_t value, uint16_t index, + tuh_xfer_cb_t complete_cb, uintptr_t user_data) { + uint8_t request = p_cdc->pl2303.type == PL2303_TYPE_HXN ? PL2303_VENDOR_WRITE_NREQUEST : PL2303_VENDOR_WRITE_REQUEST; + return pl2303_set_request(p_cdc, request, PL2303_VENDOR_WRITE_REQUEST_TYPE, value, index, NULL, 0, complete_cb, user_data); +} + +static inline bool pl2303_supports_hx_status(cdch_interface_t *p_cdc, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { + uint8_t buf = 0; + return pl2303_set_request(p_cdc, PL2303_VENDOR_READ_REQUEST, PL2303_VENDOR_READ_REQUEST_TYPE, PL2303_READ_TYPE_HX_STATUS, 0, + &buf, 1, complete_cb, user_data); +} + +//static bool pl2303_get_line_request(cdch_interface_t * p_cdc, uint8_t buf[PL2303_LINE_CODING_BUFSIZE]) { +// return pl2303_set_request(p_cdc, PL2303_GET_LINE_REQUEST, PL2303_GET_LINE_REQUEST_TYPE, 0, 0, buf, PL2303_LINE_CODING_BUFSIZE); +//} + +//static bool pl2303_set_break(cdch_interface_t * p_cdc, bool enable) { +// uint16_t state = enable ? PL2303_BREAK_ON : PL2303_BREAK_OFF; +// return pl2303_set_request(p_cdc, PL2303_BREAK_REQUEST, PL2303_BREAK_REQUEST_TYPE, state, 0, NULL, 0); +//} + +static inline int pl2303_clear_halt(cdch_interface_t *p_cdc, uint8_t endp, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { + /* we don't care if it wasn't halted first. in fact some devices + * (like some ibmcam model 1 units) seem to expect hosts to make + * this request for iso endpoints, which can't halt! + */ + return pl2303_set_request(p_cdc, TUSB_REQ_CLEAR_FEATURE, PL2303_CLEAR_HALT_REQUEST_TYPE, TUSB_REQ_FEATURE_EDPT_HALT, endp, + NULL, 0, complete_cb, user_data); +} + +//------------- Driver API -------------// + +// internal control complete to update state such as line state, encoding +static void pl2303_internal_control_complete(cdch_interface_t *p_cdc, tuh_xfer_t *xfer) { + TU_VERIFY(xfer->result == XFER_RESULT_SUCCESS,); + if (xfer->setup->bRequest == PL2303_SET_LINE_REQUEST && + xfer->setup->bmRequestType == PL2303_SET_LINE_REQUEST_TYPE) { + p_cdc->line.coding = p_cdc->requested_line.coding; + } + if (xfer->setup->bRequest == PL2303_SET_CONTROL_REQUEST && + xfer->setup->bmRequestType == PL2303_SET_CONTROL_REQUEST_TYPE) { + p_cdc->line.control_state = p_cdc->requested_line.control_state; + } +} + +static bool pl2303_set_line_coding(cdch_interface_t *p_cdc, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { + // the caller has to precheck, that the new line coding different than the current, else false returned + uint8_t buf[PL2303_LINE_CODING_BUFSIZE]; + /* + * Some PL2303 are known to lose bytes if you change serial settings + * even to the same values as before. Thus we actually need to filter + * in this specific case. + */ + TU_VERIFY(p_cdc->requested_line.coding.data_bits != p_cdc->line.coding.data_bits || + p_cdc->requested_line.coding.stop_bits != p_cdc->line.coding.stop_bits || + p_cdc->requested_line.coding.parity != p_cdc->line.coding.parity || + p_cdc->requested_line.coding.bit_rate != p_cdc->line.coding.bit_rate ); + + /* For reference buf[6] data bits value */ + TU_VERIFY(p_cdc->requested_line.coding.data_bits >= 5 && p_cdc->requested_line.coding.data_bits <= 8, 0); + buf[6] = p_cdc->requested_line.coding.data_bits; + + /* For reference buf[0]:buf[3] baud rate value */ + TU_VERIFY(pl2303_encode_baud_rate(p_cdc, &buf[0])); + + /* For reference buf[4]=0 is 1 stop bits */ + /* For reference buf[4]=1 is 1.5 stop bits */ + /* For reference buf[4]=2 is 2 stop bits */ + buf[4] = p_cdc->requested_line.coding.stop_bits; // PL2303 has the same coding + + /* For reference buf[5]=0 is none parity */ + /* For reference buf[5]=1 is odd parity */ + /* For reference buf[5]=2 is even parity */ + /* For reference buf[5]=3 is mark parity */ + /* For reference buf[5]=4 is space parity */ + buf[5] = p_cdc->requested_line.coding.parity; // PL2303 has the same coding + + return pl2303_set_request(p_cdc, PL2303_SET_LINE_REQUEST, PL2303_SET_LINE_REQUEST_TYPE, 0, 0, + buf, PL2303_LINE_CODING_BUFSIZE, complete_cb, user_data); +} + +static bool pl2303_set_modem_ctrl(cdch_interface_t *p_cdc, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { + // PL2303 has the same bit coding + return pl2303_set_request(p_cdc, PL2303_SET_CONTROL_REQUEST, PL2303_SET_CONTROL_REQUEST_TYPE, + p_cdc->requested_line.control_state.value, 0, NULL, 0, complete_cb, user_data); +} + +//------------- Enumeration -------------// + +enum { + CONFIG_PL2303_DETECT_TYPE = 0, + CONFIG_PL2303_READ1, + CONFIG_PL2303_WRITE1, + CONFIG_PL2303_READ2, + CONFIG_PL2303_READ3, + CONFIG_PL2303_READ4, + CONFIG_PL2303_WRITE2, + CONFIG_PL2303_READ5, + CONFIG_PL2303_READ6, + CONFIG_PL2303_WRITE3, + CONFIG_PL2303_WRITE4, + CONFIG_PL2303_WRITE5, + CONFIG_PL2303_RESET_ENDP1, + CONFIG_PL2303_RESET_ENDP2, +// CONFIG_PL2303_FLOW_CTRL_READ, +// CONFIG_PL2303_FLOW_CTRL_WRITE, + CONFIG_PL2303_COMPLETE +}; + +static bool pl2303_open(uint8_t daddr, tusb_desc_interface_t const *itf_desc, uint16_t max_len) { + // PL2303 Interface includes 1 vendor interface + 1 interrupt endpoints + 2 bulk + TU_VERIFY(itf_desc->bNumEndpoints == 3); + TU_VERIFY(sizeof(tusb_desc_interface_t) + 3 * sizeof(tusb_desc_endpoint_t) <= max_len); + + cdch_interface_t *p_cdc = make_new_itf(daddr, itf_desc); + TU_VERIFY(p_cdc); + + p_cdc->serial_drid = SERIAL_DRIVER_PL2303; + p_cdc->pl2303.quirks = 0; + p_cdc->pl2303.supports_hx_status = false; + + tusb_desc_endpoint_t const *desc_ep = (tusb_desc_endpoint_t const *) tu_desc_next(itf_desc); + + // Interrupt endpoint: not used for now + TU_ASSERT(TUSB_DESC_ENDPOINT == tu_desc_type(desc_ep) && + TUSB_XFER_INTERRUPT == desc_ep->bmAttributes.xfer); + TU_ASSERT(tuh_edpt_open(daddr, desc_ep)); + p_cdc->ep_notif = desc_ep->bEndpointAddress; + desc_ep += 1; + + // data endpoints expected to be in pairs + TU_ASSERT(open_ep_stream_pair(p_cdc, desc_ep)); + + return true; +} + +static bool pl2303_process_set_config(cdch_interface_t *p_cdc, tuh_xfer_t *xfer) { + // state CONFIG_PL2303_READ1 may have no success due to expected stall by pl2303_supports_hx_status() + const uintptr_t state = xfer->user_data; + TU_ASSERT(xfer->result == XFER_RESULT_SUCCESS || state == CONFIG_PL2303_READ1); + uint8_t* enum_buf = usbh_get_enum_buf(); + pl2303_type_t type; + + switch (state) { + // from here sequence overtaken from Linux Kernel function pl2303_startup() + case CONFIG_PL2303_DETECT_TYPE: + // get type and quirks (step 1) + type = pl2303_detect_type(p_cdc, 1); + TU_ASSERT(type != PL2303_TYPE_UNKNOWN); + if (type == PL2303_TYPE_NEED_SUPPORTS_HX_STATUS) { + TU_ASSERT(pl2303_supports_hx_status(p_cdc, cdch_process_set_config, CONFIG_PL2303_READ1)); + break; + } else { + // no transfer triggered and continue with CONFIG_PL2303_READ1 + TU_ATTR_FALLTHROUGH; + } + + case CONFIG_PL2303_READ1: + // get supports_hx_status, type and quirks (step 2), do special read + // will not be true, if coming directly from previous case + if (xfer->user_data == CONFIG_PL2303_READ1 && xfer->result == XFER_RESULT_SUCCESS) { + p_cdc->pl2303.supports_hx_status = true; + } + type = pl2303_detect_type(p_cdc, 2); // step 2 now with supports_hx_status + TU_ASSERT(type != PL2303_TYPE_UNKNOWN); + TU_LOG_DRV(" PL2303 type detected: %u\r\n", type); + + p_cdc->pl2303.type = type; + p_cdc->pl2303.quirks |= pl2303_type_data[type].quirks; + + // purpose unknown, overtaken from Linux Kernel driver + if (p_cdc->pl2303.type != PL2303_TYPE_HXN) { + TU_ASSERT(pl2303_vendor_read(p_cdc, 0x8484, enum_buf, cdch_process_set_config, CONFIG_PL2303_WRITE1)); + break; + }// else: continue with next step + TU_ATTR_FALLTHROUGH; + + case CONFIG_PL2303_WRITE1: + // purpose unknown, overtaken from Linux Kernel driver + if (p_cdc->pl2303.type != PL2303_TYPE_HXN) { + TU_ASSERT(pl2303_vendor_write(p_cdc, 0x0404, 0, cdch_process_set_config, CONFIG_PL2303_READ2)); + break; + }// else: continue with next step + TU_ATTR_FALLTHROUGH; + + case CONFIG_PL2303_READ2: + // purpose unknown, overtaken from Linux Kernel driver + if (p_cdc->pl2303.type != PL2303_TYPE_HXN) { + TU_ASSERT(pl2303_vendor_read(p_cdc, 0x8484, enum_buf, cdch_process_set_config, CONFIG_PL2303_READ3)); + break; + }// else: continue with next step + TU_ATTR_FALLTHROUGH; + + case CONFIG_PL2303_READ3: + // purpose unknown, overtaken from Linux Kernel driver + if (p_cdc->pl2303.type != PL2303_TYPE_HXN) { + TU_ASSERT(pl2303_vendor_read(p_cdc, 0x8383, enum_buf, cdch_process_set_config, CONFIG_PL2303_READ4)); + break; + }// else: continue with next step + TU_ATTR_FALLTHROUGH; + + case CONFIG_PL2303_READ4: + // purpose unknown, overtaken from Linux Kernel driver + if (p_cdc->pl2303.type != PL2303_TYPE_HXN) { + TU_ASSERT(pl2303_vendor_read(p_cdc, 0x8484, enum_buf, cdch_process_set_config, CONFIG_PL2303_WRITE2)); + break; + }// else: continue with next step + TU_ATTR_FALLTHROUGH; + + case CONFIG_PL2303_WRITE2: + // purpose unknown, overtaken from Linux Kernel driver + if (p_cdc->pl2303.type != PL2303_TYPE_HXN) { + TU_ASSERT(pl2303_vendor_write(p_cdc, 0x0404, 1, cdch_process_set_config, CONFIG_PL2303_READ5)); + break; + }// else: continue with next step + TU_ATTR_FALLTHROUGH; + + case CONFIG_PL2303_READ5: + // purpose unknown, overtaken from Linux Kernel driver + if (p_cdc->pl2303.type != PL2303_TYPE_HXN) { + TU_ASSERT(pl2303_vendor_read(p_cdc, 0x8484, enum_buf, cdch_process_set_config, CONFIG_PL2303_READ6)); + break; + }// else: continue with next step + TU_ATTR_FALLTHROUGH; + + case CONFIG_PL2303_READ6: + // purpose unknown, overtaken from Linux Kernel driver + if (p_cdc->pl2303.type != PL2303_TYPE_HXN) { + TU_ASSERT(pl2303_vendor_read(p_cdc, 0x8383, enum_buf, cdch_process_set_config, CONFIG_PL2303_WRITE3)); + break; + }// else: continue with next step + TU_ATTR_FALLTHROUGH; + + case CONFIG_PL2303_WRITE3: + // purpose unknown, overtaken from Linux Kernel driver + if (p_cdc->pl2303.type != PL2303_TYPE_HXN) { + TU_ASSERT(pl2303_vendor_write(p_cdc, 0, 1, cdch_process_set_config, CONFIG_PL2303_WRITE4)); + break; + }// else: continue with next step + TU_ATTR_FALLTHROUGH; + + case CONFIG_PL2303_WRITE4: + // purpose unknown, overtaken from Linux Kernel driver + if (p_cdc->pl2303.type != PL2303_TYPE_HXN) { + TU_ASSERT(pl2303_vendor_write(p_cdc, 1, 0, cdch_process_set_config, CONFIG_PL2303_WRITE5)); + break; + }// else: continue with next step + TU_ATTR_FALLTHROUGH; + + case CONFIG_PL2303_WRITE5: + // purpose unknown, overtaken from Linux Kernel driver + if (p_cdc->pl2303.type != PL2303_TYPE_HXN) { + uint16_t const windex = (p_cdc->pl2303.quirks & PL2303_QUIRK_LEGACY) ? 0x24 : 0x44; + TU_ASSERT(pl2303_vendor_write(p_cdc, 2, windex, cdch_process_set_config, CONFIG_PL2303_RESET_ENDP1)); + break; + }// else: continue with next step + TU_ATTR_FALLTHROUGH; + + // from here sequence overtaken from Linux Kernel function pl2303_open() + case CONFIG_PL2303_RESET_ENDP1: + // step 1 + if (p_cdc->pl2303.quirks & PL2303_QUIRK_LEGACY) { + TU_ASSERT(pl2303_clear_halt(p_cdc, PL2303_OUT_EP, cdch_process_set_config, CONFIG_PL2303_RESET_ENDP2)); + } else { + /* reset upstream data pipes */ + if (p_cdc->pl2303.type == PL2303_TYPE_HXN) { + TU_ASSERT(pl2303_vendor_write(p_cdc, PL2303_HXN_RESET_REG,// skip CONFIG_PL2303_RESET_ENDP2, no 2nd step + PL2303_HXN_RESET_UPSTREAM_PIPE | PL2303_HXN_RESET_DOWNSTREAM_PIPE, + cdch_process_set_config, CONFIG_PL2303_COMPLETE)); + } else { + pl2303_vendor_write(p_cdc, 8, 0, cdch_process_set_config, CONFIG_PL2303_RESET_ENDP2); + } + } + break; + + case CONFIG_PL2303_RESET_ENDP2: + // step 2 + if (p_cdc->pl2303.quirks & PL2303_QUIRK_LEGACY) { + TU_ASSERT(pl2303_clear_halt(p_cdc, PL2303_IN_EP, cdch_process_set_config, CONFIG_PL2303_COMPLETE)); + } else { + /* reset upstream data pipes */ + if (p_cdc->pl2303.type == PL2303_TYPE_HXN) { + // here nothing to do, only structure of previous step overtaken for better reading and comparison + } else { + TU_ASSERT(pl2303_vendor_write(p_cdc, 9, 0, cdch_process_set_config, CONFIG_PL2303_COMPLETE)); + } + } + break; + + // skipped, because it's not working with each PL230x. flow control can be also set by PL2303 EEPROM Writer Program + // case CONFIG_PL2303_FLOW_CTRL_READ: + // // read flow control register for modify & write back in next step + // if (p_cdc->pl2303.type == PL2303_TYPE_HXN) { + // TU_LOG_P_CDC ( "1\r\n" ); + // TU_ASSERT(pl2303_vendor_read(p_cdc, PL2303_HXN_FLOWCTRL_REG, &buf, + // cdch_process_set_config, CONFIG_PL2303_FLOW_CTRL_WRITE)); + // } else { + // TU_LOG_P_CDC ( "2\r\n" ); + // TU_ASSERT(pl2303_vendor_read(p_cdc, 0, &buf, cdch_process_set_config, CONFIG_PL2303_FLOW_CTRL_WRITE)); + // } + // break; + // + // case CONFIG_PL2303_FLOW_CTRL_WRITE: + // // no flow control + // buf = xfer->buffer[0]; + // if (p_cdc->pl2303.type == PL2303_TYPE_HXN) { + // buf &= (uint8_t) ~PL2303_HXN_FLOWCTRL_MASK; + // buf |= PL2303_HXN_FLOWCTRL_NONE; + // TU_ASSERT(pl2303_vendor_write(p_cdc, PL2303_HXN_FLOWCTRL_REG, buf, + // cdch_process_set_config, CONFIG_PL2303_COMPLETE)); + // } else { + // buf &= (uint8_t) ~PL2303_FLOWCTRL_MASK; + // TU_ASSERT(pl2303_vendor_write(p_cdc, 0, buf, + // cdch_process_set_config, CONFIG_PL2303_COMPLETE)); + // } + // break; + + case CONFIG_PL2303_COMPLETE: + xfer->user_data = 0; // kick-off set line state on enum + cdch_process_line_state_on_enum(xfer); + break; + + default: + return false; + } + + return true; +} + +//------------- Helper -------------// + +static pl2303_type_t pl2303_detect_type(cdch_interface_t *p_cdc, uint8_t step) { + tusb_desc_device_t desc_dev; + TU_VERIFY(tuh_descriptor_get_device_local(p_cdc->daddr, &desc_dev), PL2303_TYPE_UNKNOWN); + + // Legacy PL2303H, variants 0 and 1 (difference unknown). + if (desc_dev.bDeviceClass == 0x02) { + return PL2303_TYPE_H; /* variant 0 */ + } + + if (desc_dev.bMaxPacketSize0 != 0x40) { + if (desc_dev.bDeviceClass == 0x00 || desc_dev.bDeviceClass == 0xff) { + return PL2303_TYPE_H; /* variant 1 */ + } + return PL2303_TYPE_H; /* variant 0 */ + } + + switch (desc_dev.bcdUSB) { + case 0x101: + /* USB 1.0.1? Let's assume they meant 1.1... */ + TU_ATTR_FALLTHROUGH; + case 0x110: + switch (desc_dev.bcdDevice) { + case 0x300: return PL2303_TYPE_HX; + case 0x400: return PL2303_TYPE_HXD; + default: return PL2303_TYPE_HX; + } + break; + + case 0x200: + switch (desc_dev.bcdDevice) { + case 0x100: /* GC */ + case 0x105: + return PL2303_TYPE_HXN; + + case 0x300: /* GT / TA */ + if (step == 1) { + // step 1 trigger pl2303_supports_hx_status() request + return PL2303_TYPE_NEED_SUPPORTS_HX_STATUS; + } else { + // step 2 use supports_hx_status + if (p_cdc->pl2303.supports_hx_status) { + return PL2303_TYPE_TA; + } + } + TU_ATTR_FALLTHROUGH; + case 0x305: + case 0x400: /* GL */ + case 0x405: + return PL2303_TYPE_HXN; + + case 0x500: /* GE / TB */ + if (step == 1) { + // step 1 trigger pl2303_supports_hx_status() request + return PL2303_TYPE_NEED_SUPPORTS_HX_STATUS; + } else { + // step 2 use supports_hx_status + if (p_cdc->pl2303.supports_hx_status) { + return PL2303_TYPE_TB; + } + } + TU_ATTR_FALLTHROUGH; + case 0x505: + case 0x600: /* GS */ + case 0x605: + case 0x700: /* GR */ + case 0x705: + return PL2303_TYPE_HXN; + + default: + break; + } + break; + default: break; + } + + TU_LOG_CDC(p_cdc, "unknown device type bcdUSB = 0x%04x", desc_dev.bcdUSB); + return PL2303_TYPE_UNKNOWN; +} + +/* + * Returns the nearest supported baud rate that can be set directly without + * using divisors. + */ +static uint32_t pl2303_get_supported_baud_rate(uint32_t baud) { + static const uint32_t baud_sup[] = { + 75, 150, 300, 600, 1200, 1800, 2400, 3600, 4800, 7200, 9600, + 14400, 19200, 28800, 38400, 57600, 115200, 230400, 460800, + 614400, 921600, 1228800, 2457600, 3000000, 6000000 + }; + + uint8_t i; + for (i = 0; i < TU_ARRAY_SIZE(baud_sup); ++i) { + if (baud_sup[i] > baud) { + break; + } + } + + if (i == TU_ARRAY_SIZE(baud_sup)) { + baud = baud_sup[i - 1]; + } else if (i > 0 && (baud_sup[i] - baud) > (baud - baud_sup[i - 1])) { + baud = baud_sup[i - 1]; + } else { + baud = baud_sup[i]; + } + + return baud; +} + +/* + * NOTE: If unsupported baud rates are set directly, the PL2303 seems to + * use 9600 baud. + */ +static uint32_t pl2303_encode_baud_rate_direct(uint8_t buf[PL2303_LINE_CODING_BAUDRATE_BUFSIZE], uint32_t baud) { + uint32_t baud_le = tu_htole32(baud); + buf[0] = (uint8_t) ( baud_le & 0xff); + buf[1] = (uint8_t) ((baud_le >> 8) & 0xff); + buf[2] = (uint8_t) ((baud_le >> 16) & 0xff); + buf[3] = (uint8_t) ((baud_le >> 24) & 0xff); + + return baud; +} + +static uint32_t pl2303_encode_baud_rate_divisor(uint8_t buf[PL2303_LINE_CODING_BAUDRATE_BUFSIZE], uint32_t baud) { + uint32_t baseline, mantissa, exponent; + + /* + * Apparently the formula is: + * baudrate = 12M * 32 / (mantissa * 4^exponent) + * where + * mantissa = buf[8:0] + * exponent = buf[11:9] + */ + baseline = 12000000 * 32; + mantissa = baseline / baud; + if (mantissa == 0) + mantissa = 1; /* Avoid dividing by zero if baud > 32 * 12M. */ + exponent = 0; + while (mantissa >= 512) { + if (exponent < 7) { + mantissa >>= 2; /* divide by 4 */ + exponent++; + } else { + /* Exponent is maxed. Trim mantissa and leave. */ + mantissa = 511; + break; + } + } + + buf[3] = 0x80; + buf[2] = 0; + buf[1] = (uint8_t) ((exponent << 1 | mantissa >> 8) & 0xff); + buf[0] = (uint8_t) (mantissa & 0xff); + + /* Calculate and return the exact baud rate. */ + baud = (baseline / mantissa) >> (exponent << 1); + + return baud; +} + +static uint32_t pl2303_encode_baud_rate_divisor_alt(uint8_t buf[PL2303_LINE_CODING_BAUDRATE_BUFSIZE], uint32_t baud) { + uint32_t baseline, mantissa, exponent; + + /* + * Apparently, for the TA version the formula is: + * baudrate = 12M * 32 / (mantissa * 2^exponent) + * where + * mantissa = buf[10:0] + * exponent = buf[15:13 16] + */ + baseline = 12000000 * 32; + mantissa = baseline / baud; + if (mantissa == 0) { + mantissa = 1; /* Avoid dividing by zero if baud > 32 * 12M. */ + } + exponent = 0; + while (mantissa >= 2048) { + if (exponent < 15) { + mantissa >>= 1; /* divide by 2 */ + exponent++; + } else { + /* Exponent is maxed. Trim mantissa and leave. */ + mantissa = 2047; + break; + } + } + + buf[3] = 0x80; + buf[2] = (uint8_t) (exponent & 0x01); + buf[1] = (uint8_t) (((exponent & (uint32_t) ~0x01) << 4 | mantissa >> 8) & 0xff); + buf[0] = (uint8_t) (mantissa & 0xff); + + /* Calculate and return the exact baud rate. */ + baud = (baseline / mantissa) >> exponent; + + return baud; +} + +static bool pl2303_encode_baud_rate(cdch_interface_t *p_cdc, uint8_t buf[PL2303_LINE_CODING_BAUDRATE_BUFSIZE]) { + uint32_t baud = p_cdc->requested_line.coding.bit_rate; + uint32_t baud_sup; + const pl2303_type_data_t* type_data = &pl2303_type_data[p_cdc->pl2303.type]; + + TU_VERIFY(baud && baud <= type_data->max_baud_rate); + /* + * Use direct method for supported baud rates, otherwise use divisors. + * Newer chip types do not support divisor encoding. + */ + if (type_data->no_divisors) { + baud_sup = baud; + } else { + baud_sup = pl2303_get_supported_baud_rate(baud); + } + + if (baud == baud_sup) { + baud = pl2303_encode_baud_rate_direct(buf, baud); + } else if (type_data->alt_divisors) { + baud = pl2303_encode_baud_rate_divisor_alt(buf, baud); + } else { + baud = pl2303_encode_baud_rate_divisor(buf, baud); + } + TU_LOG_CDC(p_cdc, "real baudrate %lu", baud); + + return true; +} + +#endif // CFG_TUH_CDC_PL2303 + #endif diff --git a/src/class/cdc/cdc_host.h b/src/class/cdc/cdc_host.h index df975b2f0..37bfca270 100644 --- a/src/class/cdc/cdc_host.h +++ b/src/class/cdc/cdc_host.h @@ -37,34 +37,24 @@ // Class Driver Configuration //--------------------------------------------------------------------+ -// Set Line Control state on enumeration/mounted: DTR ( bit 0), RTS (bit 1) -#ifndef CFG_TUH_CDC_LINE_CONTROL_ON_ENUM -#define CFG_TUH_CDC_LINE_CONTROL_ON_ENUM 0 -#endif - -// Set Line Coding on enumeration/mounted, value for cdc_line_coding_t -//#ifndef CFG_TUH_CDC_LINE_CODING_ON_ENUM -//#define CFG_TUH_CDC_LINE_CODING_ON_ENUM { 115200, CDC_LINE_CODING_STOP_BITS_1, CDC_LINE_CODING_PARITY_NONE, 8 } -//#endif - // RX FIFO size #ifndef CFG_TUH_CDC_RX_BUFSIZE -#define CFG_TUH_CDC_RX_BUFSIZE USBH_EPSIZE_BULK_MAX +#define CFG_TUH_CDC_RX_BUFSIZE TUH_EPSIZE_BULK_MPS #endif // RX Endpoint size #ifndef CFG_TUH_CDC_RX_EPSIZE -#define CFG_TUH_CDC_RX_EPSIZE USBH_EPSIZE_BULK_MAX +#define CFG_TUH_CDC_RX_EPSIZE TUH_EPSIZE_BULK_MPS #endif // TX FIFO size #ifndef CFG_TUH_CDC_TX_BUFSIZE -#define CFG_TUH_CDC_TX_BUFSIZE USBH_EPSIZE_BULK_MAX +#define CFG_TUH_CDC_TX_BUFSIZE TUH_EPSIZE_BULK_MPS #endif // TX Endpoint size #ifndef CFG_TUH_CDC_TX_EPSIZE -#define CFG_TUH_CDC_TX_EPSIZE USBH_EPSIZE_BULK_MAX +#define CFG_TUH_CDC_TX_EPSIZE TUH_EPSIZE_BULK_MPS #endif //--------------------------------------------------------------------+ @@ -79,14 +69,27 @@ uint8_t tuh_cdc_itf_get_index(uint8_t daddr, uint8_t itf_num); // return true if index is correct and interface is currently mounted bool tuh_cdc_itf_get_info(uint8_t idx, tuh_itf_info_t* info); -// Check if a interface is mounted +// Check if an interface is mounted bool tuh_cdc_mounted(uint8_t idx); +// Get local (cached) line state +// This function should return correct values if tuh_cdc_set_control_line_state() / tuh_cdc_get_control_line_state() +// are invoked previously or CFG_TUH_CDC_LINE_STATE_ON_ENUM is defined. +bool tuh_cdc_get_control_line_state_local(uint8_t idx, uint16_t* line_state); + // Get current DTR status -bool tuh_cdc_get_dtr(uint8_t idx); +TU_ATTR_ALWAYS_INLINE static inline bool tuh_cdc_get_dtr(uint8_t idx) { + uint16_t line_state; + TU_VERIFY(tuh_cdc_get_control_line_state_local(idx, &line_state)); + return (line_state & CDC_CONTROL_LINE_STATE_DTR) != 0; +} // Get current RTS status -bool tuh_cdc_get_rts(uint8_t idx); +TU_ATTR_ALWAYS_INLINE static inline bool tuh_cdc_get_rts(uint8_t idx) { + uint16_t line_state; + TU_VERIFY(tuh_cdc_get_control_line_state_local(idx, &line_state)); + return (line_state & CDC_CONTROL_LINE_STATE_RTS) != 0; +} // Check if interface is connected (DTR active) TU_ATTR_ALWAYS_INLINE static inline bool tuh_cdc_connected(uint8_t idx) { @@ -97,7 +100,9 @@ TU_ATTR_ALWAYS_INLINE static inline bool tuh_cdc_connected(uint8_t idx) { // This function should return correct values if tuh_cdc_set_line_coding() / tuh_cdc_get_line_coding() // are invoked previously or CFG_TUH_CDC_LINE_CODING_ON_ENUM is defined. // NOTE: This function does not make any USB transfer request to device. -bool tuh_cdc_get_local_line_coding(uint8_t idx, cdc_line_coding_t* line_coding); +bool tuh_cdc_get_line_coding_local(uint8_t idx, cdc_line_coding_t* line_coding); + +#define tuh_cdc_get_local_line_coding tuh_cdc_get_line_coding_local // backward compatibility //--------------------------------------------------------------------+ // Write API @@ -132,18 +137,31 @@ bool tuh_cdc_peek(uint8_t idx, uint8_t* ch); bool tuh_cdc_read_clear (uint8_t idx); //--------------------------------------------------------------------+ -// Control Endpoint (Request) API +// Control Request API // Each Function will make a USB control transfer request to/from device // - If complete_cb is provided, the function will return immediately and invoke // the callback when request is complete. // - If complete_cb is NULL, the function will block until request is complete. -// - In this case, user_data should be pointed to xfer_result_t to hold the transfer result. -// - The function will return true if transfer is successful, false otherwise. +// In this case, user_data should be usb_xfer_result_t* to hold the transfer result. //--------------------------------------------------------------------+ // Request to Set Control Line State: DTR (bit 0), RTS (bit 1) bool tuh_cdc_set_control_line_state(uint8_t idx, uint16_t line_state, tuh_xfer_cb_t complete_cb, uintptr_t user_data); +// Request to Set DTR +TU_ATTR_ALWAYS_INLINE static inline bool tuh_cdc_set_dtr(uint8_t idx, bool dtr_state, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { + cdc_line_control_state_t line_state = { .dtr = dtr_state }; + line_state.rts = tuh_cdc_get_rts(idx); + return tuh_cdc_set_control_line_state(idx, line_state.value, complete_cb, user_data); +} + +// Request to Set RTS +TU_ATTR_ALWAYS_INLINE static inline bool tuh_cdc_set_rts(uint8_t idx, bool rts_state, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { + cdc_line_control_state_t line_state = { .rts = rts_state }; + line_state.dtr = tuh_cdc_get_dtr(idx); + return tuh_cdc_set_control_line_state(idx, line_state.value, complete_cb, user_data); +} + // Request to set baudrate bool tuh_cdc_set_baudrate(uint8_t idx, uint32_t baudrate, tuh_xfer_cb_t complete_cb, uintptr_t user_data); @@ -160,17 +178,52 @@ bool tuh_cdc_set_line_coding(uint8_t idx, cdc_line_coding_t const* line_coding, // bool tuh_cdc_get_line_coding(uint8_t idx, cdc_line_coding_t* coding); // Connect by set both DTR, RTS -TU_ATTR_ALWAYS_INLINE static inline -bool tuh_cdc_connect(uint8_t idx, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { +TU_ATTR_ALWAYS_INLINE static inline bool tuh_cdc_connect(uint8_t idx, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { return tuh_cdc_set_control_line_state(idx, CDC_CONTROL_LINE_STATE_DTR | CDC_CONTROL_LINE_STATE_RTS, complete_cb, user_data); } // Disconnect by clear both DTR, RTS -TU_ATTR_ALWAYS_INLINE static inline -bool tuh_cdc_disconnect(uint8_t idx, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { +TU_ATTR_ALWAYS_INLINE static inline bool tuh_cdc_disconnect(uint8_t idx, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { return tuh_cdc_set_control_line_state(idx, 0x00, complete_cb, user_data); } +//--------------------------------------------------------------------+ +// Control Request Sync API +// Each Function will make a USB control transfer request to/from device the function will block until request is +// complete. The function will return the transfer request result +//--------------------------------------------------------------------+ +TU_ATTR_ALWAYS_INLINE static inline tusb_xfer_result_t tuh_cdc_set_control_line_state_sync(uint8_t idx, uint16_t line_state) { + TU_API_SYNC(tuh_cdc_set_control_line_state, idx, line_state); +} + +TU_ATTR_ALWAYS_INLINE static inline tusb_xfer_result_t tuh_cdc_set_dtr_sync(uint8_t idx, bool dtr_state) { + TU_API_SYNC(tuh_cdc_set_dtr, idx, dtr_state); +} + +TU_ATTR_ALWAYS_INLINE static inline tusb_xfer_result_t tuh_cdc_set_rts_sync(uint8_t idx, bool rts_state) { + TU_API_SYNC(tuh_cdc_set_rts, idx, rts_state); +} + +TU_ATTR_ALWAYS_INLINE static inline tusb_xfer_result_t tuh_cdc_set_baudrate_sync(uint8_t idx, uint32_t baudrate) { + TU_API_SYNC(tuh_cdc_set_baudrate, idx, baudrate); +} + +TU_ATTR_ALWAYS_INLINE static inline tusb_xfer_result_t tuh_cdc_set_data_format_sync(uint8_t idx, uint8_t stop_bits, uint8_t parity, uint8_t data_bits) { + TU_API_SYNC(tuh_cdc_set_data_format, idx, stop_bits, parity, data_bits); +} + +TU_ATTR_ALWAYS_INLINE static inline tusb_xfer_result_t tuh_cdc_set_line_coding_sync(uint8_t idx, cdc_line_coding_t const* line_coding) { + TU_API_SYNC(tuh_cdc_set_line_coding, idx, line_coding); +} + +TU_ATTR_ALWAYS_INLINE static inline tusb_xfer_result_t tuh_cdc_connect_sync(uint8_t idx) { + TU_API_SYNC(tuh_cdc_connect, idx); +} + +TU_ATTR_ALWAYS_INLINE static inline tusb_xfer_result_t tuh_cdc_disconnect_sync(uint8_t idx) { + TU_API_SYNC(tuh_cdc_disconnect, idx); +} + //--------------------------------------------------------------------+ // CDC APPLICATION CALLBACKS //--------------------------------------------------------------------+ diff --git a/src/class/cdc/serial/ch34x.h b/src/class/cdc/serial/ch34x.h index c18066f57..0e08b0acd 100644 --- a/src/class/cdc/serial/ch34x.h +++ b/src/class/cdc/serial/ch34x.h @@ -24,8 +24,8 @@ * This file is part of the TinyUSB stack. */ -#ifndef _CH34X_H_ -#define _CH34X_H_ +#ifndef TUSB_CH34X_H +#define TUSB_CH34X_H // There is no official documentation for the CH34x (CH340, CH341) chips. Reference can be found // - https://github.com/WCHSoftGroup/ch341ser_linux @@ -34,51 +34,51 @@ // set line_coding @ enumeration #ifdef CFG_TUH_CDC_LINE_CODING_ON_ENUM -#define CFG_TUH_CDC_LINE_CODING_ON_ENUM_CH34X CFG_TUH_CDC_LINE_CODING_ON_ENUM + #define CFG_TUH_CDC_LINE_CODING_ON_ENUM_CH34X CFG_TUH_CDC_LINE_CODING_ON_ENUM #else // this default is necessary to work properly -#define CFG_TUH_CDC_LINE_CODING_ON_ENUM_CH34X { 9600, CDC_LINE_CONDING_STOP_BITS_1, CDC_LINE_CODING_PARITY_NONE, 8 } + #define CFG_TUH_CDC_LINE_CODING_ON_ENUM_CH34X { 9600, CDC_LINE_CONDING_STOP_BITS_1, CDC_LINE_CODING_PARITY_NONE, 8 } #endif // USB requests -#define CH34X_REQ_READ_VERSION 0x5F // dec 95 -#define CH34X_REQ_WRITE_REG 0x9A // dec 154 -#define CH34X_REQ_READ_REG 0x95 // dec 149 -#define CH34X_REQ_SERIAL_INIT 0xA1 // dec 161 -#define CH34X_REQ_MODEM_CTRL 0xA4 // dev 164 +#define CH34X_REQ_READ_VERSION 0x5F // dec 95 +#define CH34X_REQ_WRITE_REG 0x9A // dec 154 +#define CH34X_REQ_READ_REG 0x95 // dec 149 +#define CH34X_REQ_SERIAL_INIT 0xA1 // dec 161 +#define CH34X_REQ_MODEM_CTRL 0xA4 // dev 164 // registers -#define CH34X_REG_BREAK 0x05 -#define CH34X_REG_PRESCALER 0x12 -#define CH34X_REG_DIVISOR 0x13 -#define CH34X_REG_LCR 0x18 -#define CH34X_REG_LCR2 0x25 -#define CH34X_REG_MCR_MSR 0x06 -#define CH34X_REG_MCR_MSR2 0x07 -#define CH34X_NBREAK_BITS 0x01 +#define CH34X_REG_BREAK 0x05 +#define CH34X_REG_PRESCALER 0x12 +#define CH34X_REG_DIVISOR 0x13 +#define CH34X_REG_LCR 0x18 +#define CH34X_REG_LCR2 0x25 +#define CH34X_REG_MCR_MSR 0x06 +#define CH34X_REG_MCR_MSR2 0x07 +#define CH34X_NBREAK_BITS 0x01 -#define CH341_REG_0x0F 0x0F // undocumented register -#define CH341_REG_0x2C 0x2C // undocumented register -#define CH341_REG_0x27 0x27 // hardware flow control (cts/rts) +#define CH341_REG_0x0F 0x0F // undocumented register +#define CH341_REG_0x2C 0x2C // undocumented register +#define CH341_REG_0x27 0x27 // hardware flow control (cts/rts) -#define CH34X_REG16_DIVISOR_PRESCALER TU_U16(CH34X_REG_DIVISOR, CH34X_REG_PRESCALER) -#define CH32X_REG16_LCR2_LCR TU_U16(CH34X_REG_LCR2, CH34X_REG_LCR) +#define CH34X_REG16_DIVISOR_PRESCALER TU_U16(CH34X_REG_DIVISOR, CH34X_REG_PRESCALER) +#define CH32X_REG16_LCR2_LCR TU_U16(CH34X_REG_LCR2, CH34X_REG_LCR) // modem control bits -#define CH34X_BIT_RTS ( 1 << 6 ) -#define CH34X_BIT_DTR ( 1 << 5 ) +#define CH34X_BIT_RTS (1 << 6) +#define CH34X_BIT_DTR (1 << 5) // line control bits -#define CH34X_LCR_ENABLE_RX 0x80 -#define CH34X_LCR_ENABLE_TX 0x40 -#define CH34X_LCR_MARK_SPACE 0x20 -#define CH34X_LCR_PAR_EVEN 0x10 -#define CH34X_LCR_ENABLE_PAR 0x08 -#define CH34X_LCR_PAR_MASK 0x38 // all parity bits -#define CH34X_LCR_STOP_BITS_2 0x04 -#define CH34X_LCR_CS8 0x03 -#define CH34X_LCR_CS7 0x02 -#define CH34X_LCR_CS6 0x01 -#define CH34X_LCR_CS5 0x00 -#define CH34X_LCR_CS_MASK 0x03 // all CSx bits +#define CH34X_LCR_ENABLE_RX 0x80 +#define CH34X_LCR_ENABLE_TX 0x40 +#define CH34X_LCR_MARK_SPACE 0x20 +#define CH34X_LCR_PAR_EVEN 0x10 +#define CH34X_LCR_ENABLE_PAR 0x08 +#define CH34X_LCR_PAR_MASK 0x38 // all parity bits +#define CH34X_LCR_STOP_BITS_2 0x04 +#define CH34X_LCR_CS8 0x03 +#define CH34X_LCR_CS7 0x02 +#define CH34X_LCR_CS6 0x01 +#define CH34X_LCR_CS5 0x00 +#define CH34X_LCR_CS_MASK 0x03 // all CSx bits -#endif /* _CH34X_H_ */ +#endif // TUSB_CH34X_H diff --git a/src/class/cdc/serial/cp210x.h b/src/class/cdc/serial/cp210x.h index 2c749f522..a0eff9e40 100644 --- a/src/class/cdc/serial/cp210x.h +++ b/src/class/cdc/serial/cp210x.h @@ -28,9 +28,10 @@ // Protocol details can be found at AN571: CP210x Virtual COM Port Interface // https://www.silabs.com/documents/public/application-notes/AN571.pdf -#define TU_CP210X_VID 0x10C4 +// parts are overtaken from vendors driver +// https://www.silabs.com/documents/public/software/cp210x-3.1.0.tar.gz -/* Config request codes */ +// Config request codes #define CP210X_IFC_ENABLE 0x00 #define CP210X_SET_BAUDDIV 0x01 #define CP210X_GET_BAUDDIV 0x02 @@ -59,4 +60,55 @@ #define CP210X_SET_BAUDRATE 0x1E #define CP210X_VENDOR_SPECIFIC 0xFF // GPIO, Recipient must be Device +// SILABSER_IFC_ENABLE_REQUEST_CODE +#define CP210X_UART_ENABLE 0x0001 +#define CP210X_UART_DISABLE 0x0000 + +// SILABSER_SET_BAUDDIV_REQUEST_CODE +#define CP210X_BAUD_RATE_GEN_FREQ 0x384000 + +// SILABSER_SET_LINE_CTL_REQUEST_CODE +#define CP210X_BITS_DATA_MASK 0x0f00 +#define CP210X_BITS_DATA_5 0x0500 +#define CP210X_BITS_DATA_6 0x0600 +#define CP210X_BITS_DATA_7 0x0700 +#define CP210X_BITS_DATA_8 0x0800 +#define CP210X_BITS_DATA_9 0x0900 + +#define CP210X_BITS_PARITY_MASK 0x00f0 +#define CP210X_BITS_PARITY_NONE 0x0000 +#define CP210X_BITS_PARITY_ODD 0x0010 +#define CP210X_BITS_PARITY_EVEN 0x0020 +#define CP210X_BITS_PARITY_MARK 0x0030 +#define CP210X_BITS_PARITY_SPACE 0x0040 + +#define CP210X_BITS_STOP_MASK 0x000f +#define CP210X_BITS_STOP_1 0x0000 +#define CP210X_BITS_STOP_1_5 0x0001 +#define CP210X_BITS_STOP_2 0x0002 + +// SILABSER_SET_BREAK_REQUEST_CODE +#define CP210X_BREAK_ON 0x0001 +#define CP210X_BREAK_OFF 0x0000 + +// SILABSER_SET_MHS_REQUEST_CODE +#define CP210X_MCR_DTR 0x0001 +#define CP210X_MCR_RTS 0x0002 +#define CP210X_MCR_ALL 0x0003 +#define CP210X_MSR_CTS 0x0010 +#define CP210X_MSR_DSR 0x0020 +#define CP210X_MSR_RING 0x0040 +#define CP210X_MSR_DCD 0x0080 +#define CP210X_MSR_ALL 0x00F0 + +#define CP210X_CONTROL_WRITE_DTR 0x0100UL +#define CP210X_CONTROL_WRITE_RTS 0x0200UL + +#define CP210X_LSR_BREAK 0x0001 +#define CP210X_LSR_FRAMING_ERROR 0x0002 +#define CP210X_LSR_HW_OVERRUN 0x0004 +#define CP210X_LSR_QUEUE_OVERRUN 0x0008 +#define CP210X_LSR_PARITY_ERROR 0x0010 +#define CP210X_LSR_ALL 0x001F + #endif //TUSB_CP210X_H diff --git a/src/class/cdc/serial/ftdi_sio.h b/src/class/cdc/serial/ftdi_sio.h index 0825f0719..8abf74f11 100644 --- a/src/class/cdc/serial/ftdi_sio.h +++ b/src/class/cdc/serial/ftdi_sio.h @@ -25,222 +25,207 @@ #ifndef TUSB_FTDI_SIO_H #define TUSB_FTDI_SIO_H -// VID for matching FTDI devices -#define TU_FTDI_VID 0x0403 +#include // Commands -#define FTDI_SIO_RESET 0 /* Reset the port */ -#define FTDI_SIO_MODEM_CTRL 1 /* Set the modem control register */ -#define FTDI_SIO_SET_FLOW_CTRL 2 /* Set flow control register */ -#define FTDI_SIO_SET_BAUD_RATE 3 /* Set baud rate */ -#define FTDI_SIO_SET_DATA 4 /* Set the data characteristics of the port */ -#define FTDI_SIO_GET_MODEM_STATUS 5 /* Retrieve current value of modem status register */ -#define FTDI_SIO_SET_EVENT_CHAR 6 /* Set the event character */ -#define FTDI_SIO_SET_ERROR_CHAR 7 /* Set the error character */ -#define FTDI_SIO_SET_LATENCY_TIMER 9 /* Set the latency timer */ -#define FTDI_SIO_GET_LATENCY_TIMER 0x0a /* Get the latency timer */ -#define FTDI_SIO_SET_BITMODE 0x0b /* Set bitbang mode */ -#define FTDI_SIO_READ_PINS 0x0c /* Read immediate value of pins */ -#define FTDI_SIO_READ_EEPROM 0x90 /* Read EEPROM */ +#define FTDI_SIO_RESET 0 // Reset the port +#define FTDI_SIO_MODEM_CTRL 1 // Set the modem control register +#define FTDI_SIO_SET_FLOW_CTRL 2 // Set flow control register +#define FTDI_SIO_SET_BAUD_RATE 3 // Set baud rate +#define FTDI_SIO_SET_DATA 4 // Set the data characteristics of the port +#define FTDI_SIO_GET_MODEM_STATUS 5 // Retrieve current value of modem status register +#define FTDI_SIO_SET_EVENT_CHAR 6 // Set the event character +#define FTDI_SIO_SET_ERROR_CHAR 7 // Set the error character +#define FTDI_SIO_SET_LATENCY_TIMER 9 // Set the latency timer +#define FTDI_SIO_GET_LATENCY_TIMER 10 // Get the latency timer +#define FTDI_SIO_SET_BITMODE 11 // Set bitbang mode +#define FTDI_SIO_READ_PINS 12 // Read immediate value of pins +#define FTDI_SIO_READ_EEPROM 0x90 // Read EEPROM -/* FTDI_SIO_RESET */ -#define FTDI_SIO_RESET_SIO 0 -#define FTDI_SIO_RESET_PURGE_RX 1 -#define FTDI_SIO_RESET_PURGE_TX 2 +// Channel indices for FT2232, FT2232H and FT4232H devices +#define CHANNEL_A 1 +#define CHANNEL_B 2 +#define CHANNEL_C 3 +#define CHANNEL_D 4 -/* - * BmRequestType: 0100 0000B - * bRequest: FTDI_SIO_RESET - * wValue: Control Value - * 0 = Reset SIO - * 1 = Purge RX buffer - * 2 = Purge TX buffer - * wIndex: Port - * wLength: 0 - * Data: None - * - * The Reset SIO command has this effect: - * - * Sets flow control set to 'none' - * Event char = $0D - * Event trigger = disabled - * Purge RX buffer - * Purge TX buffer - * Clear DTR - * Clear RTS - * baud and data format not reset - * - * The Purge RX and TX buffer commands affect nothing except the buffers - * - */ +// Port Identifier Table +#define PIT_DEFAULT 0 // SIOA +#define PIT_SIOA 1 // SIOA +// The device this driver is tested with one has only one port +#define PIT_SIOB 2 // SIOB +#define PIT_PARALLEL 3 // Parallel -/* FTDI_SIO_MODEM_CTRL */ -/* - * BmRequestType: 0100 0000B - * bRequest: FTDI_SIO_MODEM_CTRL - * wValue: ControlValue (see below) - * wIndex: Port - * wLength: 0 - * Data: None - * - * NOTE: If the device is in RTS/CTS flow control, the RTS set by this - * command will be IGNORED without an error being returned - * Also - you can not set DTR and RTS with one control message - */ +// FTDI_SIO_RESET +#define FTDI_SIO_RESET_REQUEST FTDI_SIO_RESET +#define FTDI_SIO_RESET_REQUEST_TYPE 0x40 +#define FTDI_SIO_RESET_SIO 0 +#define FTDI_SIO_RESET_PURGE_RX 1 +#define FTDI_SIO_RESET_PURGE_TX 2 -#define FTDI_SIO_SET_DTR_MASK 0x1 -#define FTDI_SIO_SET_DTR_HIGH ((FTDI_SIO_SET_DTR_MASK << 8) | 1) -#define FTDI_SIO_SET_DTR_LOW ((FTDI_SIO_SET_DTR_MASK << 8) | 0) -#define FTDI_SIO_SET_RTS_MASK 0x2 -#define FTDI_SIO_SET_RTS_HIGH ((FTDI_SIO_SET_RTS_MASK << 8) | 2) -#define FTDI_SIO_SET_RTS_LOW ((FTDI_SIO_SET_RTS_MASK << 8) | 0) +// FTDI_SIO_SET_BAUDRATE +#define FTDI_SIO_SET_BAUDRATE_REQUEST_TYPE 0x40 +#define FTDI_SIO_SET_BAUDRATE_REQUEST 3 -/* - * ControlValue - * B0 DTR state - * 0 = reset - * 1 = set - * B1 RTS state - * 0 = reset - * 1 = set - * B2..7 Reserved - * B8 DTR state enable - * 0 = ignore - * 1 = use DTR state - * B9 RTS state enable - * 0 = ignore - * 1 = use RTS state - * B10..15 Reserved - */ +enum ftdi_sio_baudrate { + ftdi_sio_b300 = 0, + ftdi_sio_b600 = 1, + ftdi_sio_b1200 = 2, + ftdi_sio_b2400 = 3, + ftdi_sio_b4800 = 4, + ftdi_sio_b9600 = 5, + ftdi_sio_b19200 = 6, + ftdi_sio_b38400 = 7, + ftdi_sio_b57600 = 8, + ftdi_sio_b115200 = 9 +}; -/* FTDI_SIO_SET_FLOW_CTRL */ -#define FTDI_SIO_DISABLE_FLOW_CTRL 0x0 -#define FTDI_SIO_RTS_CTS_HS (0x1 << 8) -#define FTDI_SIO_DTR_DSR_HS (0x2 << 8) -#define FTDI_SIO_XON_XOFF_HS (0x4 << 8) +// FTDI_SIO_SET_DATA +#define FTDI_SIO_SET_DATA_REQUEST FTDI_SIO_SET_DATA +#define FTDI_SIO_SET_DATA_REQUEST_TYPE 0x40 +#define FTDI_SIO_SET_DATA_PARITY_NONE (0x0 << 8) +#define FTDI_SIO_SET_DATA_PARITY_ODD (0x1 << 8) +#define FTDI_SIO_SET_DATA_PARITY_EVEN (0x2 << 8) +#define FTDI_SIO_SET_DATA_PARITY_MARK (0x3 << 8) +#define FTDI_SIO_SET_DATA_PARITY_SPACE (0x4 << 8) +#define FTDI_SIO_SET_DATA_STOP_BITS_1 (0x0 << 11) // same coding as ACM +#define FTDI_SIO_SET_DATA_STOP_BITS_15 (0x1 << 11) // 1.5 not supported, for future use? +#define FTDI_SIO_SET_DATA_STOP_BITS_2 (0x2 << 11) +#define FTDI_SIO_SET_BREAK (0x1 << 14) -/* - * BmRequestType: 0100 0000b - * bRequest: FTDI_SIO_SET_FLOW_CTRL - * wValue: Xoff/Xon - * wIndex: Protocol/Port - hIndex is protocol / lIndex is port - * wLength: 0 - * Data: None - * - * hIndex protocol is: - * B0 Output handshaking using RTS/CTS - * 0 = disabled - * 1 = enabled - * B1 Output handshaking using DTR/DSR - * 0 = disabled - * 1 = enabled - * B2 Xon/Xoff handshaking - * 0 = disabled - * 1 = enabled - * - * A value of zero in the hIndex field disables handshaking - * - * If Xon/Xoff handshaking is specified, the hValue field should contain the - * XOFF character and the lValue field contains the XON character. - */ +// FTDI_SIO_MODEM_CTRL +#define FTDI_SIO_SET_MODEM_CTRL_REQUEST_TYPE 0x40 +#define FTDI_SIO_SET_MODEM_CTRL_REQUEST FTDI_SIO_MODEM_CTRL -/* FTDI_SIO_SET_BAUD_RATE */ -/* - * BmRequestType: 0100 0000B - * bRequest: FTDI_SIO_SET_BAUDRATE - * wValue: BaudDivisor value - see below - * wIndex: Port - * wLength: 0 - * Data: None - * The BaudDivisor values are calculated as follows (too complicated): - */ +#define FTDI_SIO_SET_DTR_MASK 0x1UL +#define FTDI_SIO_SET_DTR_HIGH ((FTDI_SIO_SET_DTR_MASK << 8) | 1UL) +#define FTDI_SIO_SET_DTR_LOW ((FTDI_SIO_SET_DTR_MASK << 8) | 0UL) +#define FTDI_SIO_SET_RTS_MASK 0x2UL +#define FTDI_SIO_SET_RTS_HIGH ((FTDI_SIO_SET_RTS_MASK << 8) | 2UL) +#define FTDI_SIO_SET_RTS_LOW ((FTDI_SIO_SET_RTS_MASK << 8) | 0UL) -/* FTDI_SIO_SET_DATA */ -#define FTDI_SIO_SET_DATA_PARITY_NONE (0x0 << 8) -#define FTDI_SIO_SET_DATA_PARITY_ODD (0x1 << 8) -#define FTDI_SIO_SET_DATA_PARITY_EVEN (0x2 << 8) -#define FTDI_SIO_SET_DATA_PARITY_MARK (0x3 << 8) -#define FTDI_SIO_SET_DATA_PARITY_SPACE (0x4 << 8) -#define FTDI_SIO_SET_DATA_STOP_BITS_1 (0x0 << 11) -#define FTDI_SIO_SET_DATA_STOP_BITS_15 (0x1 << 11) -#define FTDI_SIO_SET_DATA_STOP_BITS_2 (0x2 << 11) -#define FTDI_SIO_SET_BREAK (0x1 << 14) +// FTDI_SIO_SET_FLOW_CTRL +#define FTDI_SIO_SET_FLOW_CTRL_REQUEST_TYPE 0x40 +#define FTDI_SIO_SET_FLOW_CTRL_REQUEST FTDI_SIO_SET_FLOW_CTRL +#define FTDI_SIO_DISABLE_FLOW_CTRL 0x0 +#define FTDI_SIO_RTS_CTS_HS (0x1 << 8) +#define FTDI_SIO_DTR_DSR_HS (0x2 << 8) +#define FTDI_SIO_XON_XOFF_HS (0x4 << 8) -/* - * BmRequestType: 0100 0000B - * bRequest: FTDI_SIO_SET_DATA - * wValue: Data characteristics (see below) - * wIndex: Port - * wLength: 0 - * Data: No - * - * Data characteristics - * - * B0..7 Number of data bits - * B8..10 Parity - * 0 = None - * 1 = Odd - * 2 = Even - * 3 = Mark - * 4 = Space - * B11..13 Stop Bits - * 0 = 1 - * 1 = 1.5 - * 2 = 2 - * B14 - * 1 = TX ON (break) - * 0 = TX OFF (normal state) - * B15 Reserved - * - */ +// FTDI_SIO_GET_LATENCY_TIMER +#define FTDI_SIO_GET_LATENCY_TIMER_REQUEST FTDI_SIO_GET_LATENCY_TIMER +#define FTDI_SIO_GET_LATENCY_TIMER_REQUEST_TYPE 0xC0 -/* -* DATA FORMAT -* -* IN Endpoint -* -* The device reserves the first two bytes of data on this endpoint to contain -* the current values of the modem and line status registers. In the absence of -* data, the device generates a message consisting of these two status bytes - * every 40 ms - * - * Byte 0: Modem Status -* -* Offset Description -* B0 Reserved - must be 1 -* B1 Reserved - must be 0 -* B2 Reserved - must be 0 -* B3 Reserved - must be 0 -* B4 Clear to Send (CTS) -* B5 Data Set Ready (DSR) -* B6 Ring Indicator (RI) -* B7 Receive Line Signal Detect (RLSD) -* -* Byte 1: Line Status -* -* Offset Description -* B0 Data Ready (DR) -* B1 Overrun Error (OE) -* B2 Parity Error (PE) -* B3 Framing Error (FE) -* B4 Break Interrupt (BI) -* B5 Transmitter Holding Register (THRE) -* B6 Transmitter Empty (TEMT) -* B7 Error in RCVR FIFO -* -*/ -#define FTDI_RS0_CTS (1 << 4) -#define FTDI_RS0_DSR (1 << 5) -#define FTDI_RS0_RI (1 << 6) -#define FTDI_RS0_RLSD (1 << 7) +// FTDI_SIO_SET_LATENCY_TIMER +#define FTDI_SIO_SET_LATENCY_TIMER_REQUEST FTDI_SIO_SET_LATENCY_TIMER +#define FTDI_SIO_SET_LATENCY_TIMER_REQUEST_TYPE 0x40 -#define FTDI_RS_DR 1 -#define FTDI_RS_OE (1<<1) -#define FTDI_RS_PE (1<<2) -#define FTDI_RS_FE (1<<3) -#define FTDI_RS_BI (1<<4) -#define FTDI_RS_THRE (1<<5) -#define FTDI_RS_TEMT (1<<6) -#define FTDI_RS_FIFO (1<<7) +// FTDI_SIO_SET_EVENT_CHAR +#define FTDI_SIO_SET_EVENT_CHAR_REQUEST FTDI_SIO_SET_EVENT_CHAR +#define FTDI_SIO_SET_EVENT_CHAR_REQUEST_TYPE 0x40 + +// FTDI_SIO_GET_MODEM_STATUS +#define FTDI_SIO_GET_MODEM_STATUS_REQUEST_TYPE 0xc0 +#define FTDI_SIO_GET_MODEM_STATUS_REQUEST FTDI_SIO_GET_MODEM_STATUS +#define FTDI_SIO_CTS_MASK 0x10 +#define FTDI_SIO_DSR_MASK 0x20 +#define FTDI_SIO_RI_MASK 0x40 +#define FTDI_SIO_RLSD_MASK 0x80 + +// FTDI_SIO_SET_BITMODE +#define FTDI_SIO_SET_BITMODE_REQUEST_TYPE 0x40 +#define FTDI_SIO_SET_BITMODE_REQUEST FTDI_SIO_SET_BITMODE + +// Possible bitmodes for FTDI_SIO_SET_BITMODE_REQUEST +#define FTDI_SIO_BITMODE_RESET 0x00 +#define FTDI_SIO_BITMODE_CBUS 0x20 + +// FTDI_SIO_READ_PINS +#define FTDI_SIO_READ_PINS_REQUEST_TYPE 0xc0 +#define FTDI_SIO_READ_PINS_REQUEST FTDI_SIO_READ_PINS + +// FTDI_SIO_READ_EEPROM +#define FTDI_SIO_READ_EEPROM_REQUEST_TYPE 0xc0 +#define FTDI_SIO_READ_EEPROM_REQUEST FTDI_SIO_READ_EEPROM + +#define FTDI_FTX_CBUS_MUX_GPIO 0x8 +#define FTDI_FT232R_CBUS_MUX_GPIO 0xa + +#define FTDI_RS0_CTS (1 << 4) +#define FTDI_RS0_DSR (1 << 5) +#define FTDI_RS0_RI (1 << 6) +#define FTDI_RS0_RLSD (1 << 7) + +#define FTDI_RS_DR 1 +#define FTDI_RS_OE (1 << 1) +#define FTDI_RS_PE (1 << 2) +#define FTDI_RS_FE (1 << 3) +#define FTDI_RS_BI (1 << 4) +#define FTDI_RS_THRE (1 << 5) +#define FTDI_RS_TEMT (1 << 6) +#define FTDI_RS_FIFO (1 << 7) + +// chip types and names +typedef enum ftdi_chip_type { + FTDI_SIO = 0, +// FTDI_FT232A, + FTDI_FT232B, + FTDI_FT2232C, + FTDI_FT232R, + FTDI_FT232H, + FTDI_FT2232H, + FTDI_FT4232H, + FTDI_FT4232HA, + FTDI_FT232HP, + FTDI_FT233HP, + FTDI_FT2232HP, + FTDI_FT2233HP, + FTDI_FT4232HP, + FTDI_FT4233HP, + FTDI_FTX, + FTDI_UNKNOWN +} ftdi_chip_type_t; + +#define FTDI_CHIP_NAMES \ + [FTDI_SIO] = "SIO", /* the serial part of FT8U100AX */ \ +/* [FTDI_FT232A] = "FT232A", */ \ + [FTDI_FT232B] = "FT232B", \ + [FTDI_FT2232C] = "FT2232C/D", \ + [FTDI_FT232R] = "FT232R", \ + [FTDI_FT232H] = "FT232H", \ + [FTDI_FT2232H] = "FTDI_FT2232H", \ + [FTDI_FT4232H] = "FT4232H", \ + [FTDI_FT4232HA] = "FT4232HA", \ + [FTDI_FT232HP] = "FT232HP", \ + [FTDI_FT233HP] = "FT233HP", \ + [FTDI_FT2232HP] = "FT2232HP", \ + [FTDI_FT2233HP] = "FT2233HP", \ + [FTDI_FT4232HP] = "FT4232HP", \ + [FTDI_FT4233HP] = "FT4233HP", \ + [FTDI_FTX] = "FT-X", \ + [FTDI_UNKNOWN] = "UNKNOWN" + +// private interface data +typedef struct ftdi_private { + ftdi_chip_type_t chip_type; + uint8_t channel; // channel index, or 0 for legacy types +} ftdi_private_t; + +#define FTDI_OK true +#define FTDI_FAIL false +#define FTDI_NOT_POSSIBLE -1 +#define FTDI_REQUESTED -2 + +// division and round function overtaken from math.h +#define DIV_ROUND_CLOSEST(x, divisor)( \ +{ \ + typeof(x) __x = x; \ + typeof(divisor) __d = divisor; \ + (((typeof(x))-1) > 0 || \ + ((typeof(divisor))-1) > 0 || \ + (((__x) > 0) == ((__d) > 0))) ? \ + (((__x) + ((__d) / 2)) / (__d)) : \ + (((__x) - ((__d) / 2)) / (__d)); \ +} \ +) #endif //TUSB_FTDI_SIO_H diff --git a/src/class/cdc/serial/pl2303.h b/src/class/cdc/serial/pl2303.h new file mode 100644 index 000000000..63910c7bb --- /dev/null +++ b/src/class/cdc/serial/pl2303.h @@ -0,0 +1,159 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2024 Heiko Kuester + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * This file is part of the TinyUSB stack. + */ + +#ifndef TUSB_PL2303_H +#define TUSB_PL2303_H + +#include +#include + +// There is no official documentation for the PL2303 chips. +// Reference can be found +// - https://github.com/torvalds/linux/blob/master/drivers/usb/serial/pl2303.h and +// https://github.com/torvalds/linux/blob/master/drivers/usb/serial/pl2303.c +// - https://github.com/freebsd/freebsd-src/blob/main/sys/dev/usb/serial/uplcom.c + +// quirks +#define PL2303_QUIRK_UART_STATE_IDX0 1 +#define PL2303_QUIRK_LEGACY 2 +#define PL2303_QUIRK_ENDPOINT_HACK 4 + +// requests and bits +#define PL2303_SET_LINE_REQUEST_TYPE 0x21 // class request host to device interface +#define PL2303_SET_LINE_REQUEST 0x20 // dec 32 + +#define PL2303_SET_CONTROL_REQUEST_TYPE 0x21 // class request host to device interface +#define PL2303_SET_CONTROL_REQUEST 0x22 // dec 34 +#define PL2303_CONTROL_DTR 0x01 // dec 1 +#define PL2303_CONTROL_RTS 0x02 // dec 2 + +#define PL2303_BREAK_REQUEST_TYPE 0x21 // class request host to device interface +#define PL2303_BREAK_REQUEST 0x23 // dec 35 +#define PL2303_BREAK_ON 0xffff +#define PL2303_BREAK_OFF 0x0000 + +#define PL2303_GET_LINE_REQUEST_TYPE 0xa1 // class request device to host interface +#define PL2303_GET_LINE_REQUEST 0x21 // dec 33 + +#define PL2303_VENDOR_WRITE_REQUEST_TYPE 0x40 // vendor request host to device interface +#define PL2303_VENDOR_WRITE_REQUEST 0x01 // dec 1 +#define PL2303_VENDOR_WRITE_NREQUEST 0x80 // dec 128 + +#define PL2303_VENDOR_READ_REQUEST_TYPE 0xc0 // vendor request device to host interface +#define PL2303_VENDOR_READ_REQUEST 0x01 // dec 1 +#define PL2303_VENDOR_READ_NREQUEST 0x81 // dec 129 + +#define PL2303_UART_STATE_INDEX 8 +#define PL2303_UART_STATE_MSR_MASK 0x8b +#define PL2303_UART_STATE_TRANSIENT_MASK 0x74 +#define PL2303_UART_DCD 0x01 +#define PL2303_UART_DSR 0x02 +#define PL2303_UART_BREAK_ERROR 0x04 +#define PL2303_UART_RING 0x08 +#define PL2303_UART_FRAME_ERROR 0x10 +#define PL2303_UART_PARITY_ERROR 0x20 +#define PL2303_UART_OVERRUN_ERROR 0x40 +#define PL2303_UART_CTS 0x80 + +#define PL2303_FLOWCTRL_MASK 0xf0 + +#define PL2303_CLEAR_HALT_REQUEST_TYPE 0x02 // standard request host to device endpoint + +// registers via vendor read/write requests +#define PL2303_READ_TYPE_HX_STATUS 0x8080 + +#define PL2303_HXN_RESET_REG 0x07 +#define PL2303_HXN_RESET_UPSTREAM_PIPE 0x02 +#define PL2303_HXN_RESET_DOWNSTREAM_PIPE 0x01 + +#define PL2303_HXN_FLOWCTRL_REG 0x0a +#define PL2303_HXN_FLOWCTRL_MASK 0x1c +#define PL2303_HXN_FLOWCTRL_NONE 0x1c +#define PL2303_HXN_FLOWCTRL_RTS_CTS 0x18 +#define PL2303_HXN_FLOWCTRL_XON_XOFF 0x0c + +// type data +typedef enum pl2303_type { + PL2303_TYPE_H = 0, // 0 + PL2303_TYPE_HX, // 1 + PL2303_TYPE_TA, // 2 + PL2303_TYPE_TB, // 3 + PL2303_TYPE_HXD, // 4 + PL2303_TYPE_HXN, // 5 + PL2303_TYPE_COUNT, + PL2303_TYPE_NEED_SUPPORTS_HX_STATUS, + PL2303_TYPE_UNKNOWN, +} pl2303_type_t; + +typedef struct pl2303_type_data { + uint32_t max_baud_rate; + uint8_t quirks; + uint8_t no_autoxonxoff : 1; + uint8_t no_divisors : 1; + uint8_t alt_divisors : 1; +} pl2303_type_data_t; + +#define PL2303_TYPE_DATA \ + [PL2303_TYPE_H] = { \ + .max_baud_rate = 1228800, .quirks = PL2303_QUIRK_LEGACY, \ + .no_autoxonxoff = 1, .no_divisors = 0, .alt_divisors = 0 \ + }, \ + [PL2303_TYPE_HX] = { \ + .max_baud_rate = 6000000, .quirks = 0, \ + .no_autoxonxoff = 0, .no_divisors = 0, .alt_divisors = 0 \ + }, \ + [PL2303_TYPE_TA] = { \ + .max_baud_rate = 6000000, .quirks = 0, \ + .no_autoxonxoff = 0, .no_divisors = 0, .alt_divisors = 1 \ + }, \ + [PL2303_TYPE_TB] = { \ + .max_baud_rate = 12000000, .quirks = 0, \ + .no_autoxonxoff = 0, .no_divisors = 0, .alt_divisors = 1 \ + }, \ + [PL2303_TYPE_HXD] = { \ + .max_baud_rate = 12000000, .quirks = 0, \ + .no_autoxonxoff = 0, .no_divisors = 0, .alt_divisors = 0 \ + }, \ + [PL2303_TYPE_HXN] = { \ + .max_baud_rate = 12000000, .quirks = 0, \ + .no_autoxonxoff = 0, .no_divisors = 1, .alt_divisors = 0 \ + } + +typedef struct TU_ATTR_PACKED { + pl2303_type_t type; + uint8_t quirks; + bool supports_hx_status; +} pl2303_private_t; + +// buffer sizes for line coding data +#define PL2303_LINE_CODING_BUFSIZE 7 +#define PL2303_LINE_CODING_BAUDRATE_BUFSIZE 4 + +// bulk endpoints +#define PL2303_OUT_EP 0x02 +#define PL2303_IN_EP 0x83 + +#endif // TUSB_PL2303_H diff --git a/src/class/hid/hid.h b/src/class/hid/hid.h index c2b5a8a48..c2434c20d 100644 --- a/src/class/hid/hid.h +++ b/src/class/hid/hid.h @@ -325,6 +325,29 @@ typedef enum /// @} +//--------------------------------------------------------------------+ +// Digitizer Stylus Pen +//--------------------------------------------------------------------+ +/** \addtogroup ClassDriver_HID_Stylus Stylus + * @{ */ + +// Standard Stylus Pen Report. +typedef struct TU_ATTR_PACKED +{ + uint8_t attr; /**< Attribute mask for describing current status of the stylus pen. */ + uint16_t x; /**< Current x position of the mouse. */ + uint16_t y; /**< Current y position of the mouse. */ +} hid_stylus_report_t; + +// Standard Stylus Pen Attributes Bitmap. +typedef enum +{ + STYLUS_ATTR_TIP_SWITCH = TU_BIT(0), ///< Tip switch + STYLUS_ATTR_IN_RANGE = TU_BIT(1), ///< In-range bit. +} hid_stylus_attr_bm_t; + +/// @} + //--------------------------------------------------------------------+ // Keyboard //--------------------------------------------------------------------+ @@ -740,6 +763,21 @@ enum { //--------------------------------------------------------------------+ // Usage Table +/* Usage Types Data + Sel Selector Array + SV Static Value Constant, Variable, Absolute + SF Static Flag Constant, Variable, Absolute + DV Dynamic Value Constant, Variable, Absolute + DF Dynamic Flag Constant, Variable, Absolute +*/ +/* Usage Types Collection + NAry Named Array Logical + CA Collection Application Application + CL Collection Logical Logical + CP Collection Physical Physical + US Usage Switch Logical + UM Usage Modifier Logical +*/ //--------------------------------------------------------------------+ /// HID Usage Table - Table 1: Usage Page Summary @@ -759,8 +797,14 @@ enum { HID_USAGE_PAGE_DIGITIZER = 0x0d, HID_USAGE_PAGE_PID = 0x0f, HID_USAGE_PAGE_UNICODE = 0x10, - HID_USAGE_PAGE_ALPHA_DISPLAY = 0x14, - HID_USAGE_PAGE_MEDICAL = 0x40, + HID_USAGE_PAGE_SOC = 0x11, + HID_USAGE_PAGE_EYE_AND_HEAD_TRACKERS = 0x12, + // 0x13 is reserved + HID_USAGE_PAGE_AUXILIARY_DISPLAY = 0x14, + // 0x15 - 0x1f is reserved + HID_USAGE_PAGE_SENSORS = 0x20, + // 0x21 - 0x3f is reserved + HID_USAGE_PAGE_MEDICAL_INSTRUMENT = 0x40, HID_USAGE_PAGE_LIGHTING_AND_ILLUMINATION = 0x59, HID_USAGE_PAGE_MONITOR = 0x80, // 0x80 - 0x83 HID_USAGE_PAGE_POWER = 0x84, // 0x084 - 0x87 @@ -846,7 +890,6 @@ enum { HID_USAGE_DESKTOP_SYSTEM_DISPLAY_LCD_AUTOSCALE = 0xB7 }; - /// HID Usage Table: Consumer Page (0x0C) /// Only contains controls that supported by Windows (whole list is too long) enum { @@ -905,6 +948,237 @@ enum { HID_USAGE_CONSUMER_AC_PAN = 0x0238, }; +/// HID Usage Table: Digitizer Page (0x0D) +enum { + HID_USAGE_DIGITIZER_UNDEFINED = 0x00, + HID_USAGE_DIGITIZER_DIGITIZER = 0x01, // CA + HID_USAGE_DIGITIZER_PEN = 0x02, // CA + HID_USAGE_DIGITIZER_LIGHT_PEN = 0x03, // CA + HID_USAGE_DIGITIZER_TOUCH_SCREEN = 0x04, // CA + HID_USAGE_DIGITIZER_TOUCH_PAD = 0x05, // CA + HID_USAGE_DIGITIZER_WHITEBOARD = 0x06, // CA + HID_USAGE_DIGITIZER_COORDINATE_MEASURING_MACHINE = 0x07, // CA + HID_USAGE_DIGITIZER_3D_DIGITIZER = 0x08, // CA + HID_USAGE_DIGITIZER_STEREO_PLOTTER = 0x09, // CA + HID_USAGE_DIGITIZER_ARTICULATED_ARM = 0x0A, // CA + HID_USAGE_DIGITIZER_ARMATURE = 0x0B, // CA + HID_USAGE_DIGITIZER_MULTIPLE_POINT_DIGITIZER = 0x0C, // CA + HID_USAGE_DIGITIZER_FREE_SPACE_WAND = 0x0D, // CA + HID_USAGE_DIGITIZER_DEVICE_CONFIGURATION = 0x0E, // CA + HID_USAGE_DIGITIZER_CAPACITIVE_HEAT_MAP_DIGITIZER = 0x0F, // CA + // Reserved (0x10 - 0x1F) + HID_USAGE_DIGITIZER_STYLUS = 0x20, // CA/CL + HID_USAGE_DIGITIZER_PUCK = 0x21, // CL + HID_USAGE_DIGITIZER_FINGER = 0x22, // CL + HID_USAGE_DIGITIZER_DEVICE_SETTINGS = 0x23, // CL + HID_USAGE_DIGITIZER_CHARACTER_GESTURE = 0x24, // CL + // Reserved (0x25 - 0x2F) + HID_USAGE_DIGITIZER_TIP_PRESSURE = 0x30, // DV + HID_USAGE_DIGITIZER_BARREL_PRESSURE = 0x31, // DV + HID_USAGE_DIGITIZER_IN_RANGE = 0x32, // MC + HID_USAGE_DIGITIZER_TOUCH = 0x33, // MC + HID_USAGE_DIGITIZER_UNTOUCH = 0x34, // OSC + HID_USAGE_DIGITIZER_TAP = 0x35, // OSC + HID_USAGE_DIGITIZER_QUALITY = 0x36, // DV + HID_USAGE_DIGITIZER_DATA_VALID = 0x37, // MC + HID_USAGE_DIGITIZER_TRANSDUCER_INDEX = 0x38, // DV + HID_USAGE_DIGITIZER_TABLET_FUNCTION_KEYS = 0x39, // CL + HID_USAGE_DIGITIZER_PROGRAM_CHANGE_KEYS = 0x3A, // CL + HID_USAGE_DIGITIZER_BATTERY_STRENGTH = 0x3B, // DV + HID_USAGE_DIGITIZER_INVERT = 0x3C, // MC + HID_USAGE_DIGITIZER_X_TILT = 0x3D, // DV + HID_USAGE_DIGITIZER_Y_TILT = 0x3E, // DV + HID_USAGE_DIGITIZER_AZIMUTH = 0x3F, // DV + HID_USAGE_DIGITIZER_ALTITUDE = 0x40, // DV + HID_USAGE_DIGITIZER_TWIST = 0x41, // DV + HID_USAGE_DIGITIZER_TIP_SWITCH = 0x42, // MC + HID_USAGE_DIGITIZER_SECONDARY_TIP_SWITCH = 0x43, // MC + HID_USAGE_DIGITIZER_BARREL_SWITCH = 0x44, // MC + HID_USAGE_DIGITIZER_ERASER = 0x45, // MC + HID_USAGE_DIGITIZER_TABLET_PICK = 0x46, // MC + HID_USAGE_DIGITIZER_TOUCH_VALID = 0x47, // MC + HID_USAGE_DIGITIZER_WIDTH = 0x48, // DV + HID_USAGE_DIGITIZER_HEIGHT = 0x49, // DV + // Reserved (0x4A - 0x50) + HID_USAGE_DIGITIZER_CONTACT_IDENTIFIER = 0x51, // DV + HID_USAGE_DIGITIZER_DEVICE_MODE = 0x52, // DV + HID_USAGE_DIGITIZER_DEVICE_IDENTIFIER = 0x53, // DV/SV + HID_USAGE_DIGITIZER_CONTACT_COUNT = 0x54, // DV + HID_USAGE_DIGITIZER_CONTACT_COUNT_MAXIMUM = 0x55, // SV + HID_USAGE_DIGITIZER_SCAN_TIME = 0x56, // DV + HID_USAGE_DIGITIZER_SURFACE_SWITCH = 0x57, // DF + HID_USAGE_DIGITIZER_BUTTON_SWITCH = 0x58, // DF + HID_USAGE_DIGITIZER_PAD_TYPE = 0x59, // SF + HID_USAGE_DIGITIZER_TRANSDUCER_SERIAL_NUMBER = 0x5B, // SV + HID_USAGE_DIGITIZER_PREFERRED_COLOR = 0x5C, // DV + HID_USAGE_DIGITIZER_PREFERRED_COLOR_LOCKED = 0x5D, // MC + HID_USAGE_DIGITIZER_PREFERRED_LINE_WIDTH = 0x5E, // DV + HID_USAGE_DIGITIZER_PREFERRED_LINE_WIDTH_LOCKED = 0x5F, // MC + HID_USAGE_DIGITIZER_LATENCY_MODE = 0x60, // DF + HID_USAGE_DIGITIZER_GESTURE_CHARACTER_QUALITY = 0x61, // DV + HID_USAGE_DIGITIZER_CHARACTER_GESTURE_DATA_LENGTH = 0x62, // DV + HID_USAGE_DIGITIZER_CHARACTER_GESTURE_DATA = 0x63, // DV + HID_USAGE_DIGITIZER_GESTURE_CHARACTER_ENCODING = 0x64, // NAry + HID_USAGE_DIGITIZER_UTF8_CHARACTER_GESTURE_ENCODING = 0x65, // Sel + HID_USAGE_DIGITIZER_UTF16_LE_CHARACTER_GESTURE_ENCODING = 0x66, // Sel + HID_USAGE_DIGITIZER_UTF16_BE_CHARACTER_GESTURE_ENCODING = 0x67, // Sel + HID_USAGE_DIGITIZER_UTF32_LE_CHARACTER_GESTURE_ENCODING = 0x68, // Sel + HID_USAGE_DIGITIZER_UTF32_BE_CHARACTER_GESTURE_ENCODING = 0x69, // Sel + HID_USAGE_DIGITIZER_CAPACITIVE_HEAT_MAP_VENDOR_ID = 0x6A, // SV + HID_USAGE_DIGITIZER_CAPACITIVE_HEAT_MAP_VERSION = 0x6B, // SV + HID_USAGE_DIGITIZER_CAPACITIVE_HEAT_MAP_FRAME_DATA = 0x6C, // DV + HID_USAGE_DIGITIZER_GESTURE_CHARACTER_ENABLE = 0x6D, // DF + HID_USAGE_DIGITIZER_TRANSDUCER_SERIAL_NUMBER_PART2 = 0x6E, // SV + HID_USAGE_DIGITIZER_NO_PREFERRED_COLOR = 0x6F, // DF + HID_USAGE_DIGITIZER_PREFERRED_LINE_STYLE = 0x70, // NAry + HID_USAGE_DIGITIZER_PREFERRED_LINE_STYLE_LOCKED = 0x71, // MC + HID_USAGE_DIGITIZER_INK = 0x72, // Sel + HID_USAGE_DIGITIZER_PENCIL = 0x73, // Sel + HID_USAGE_DIGITIZER_HIGHLIGHTER = 0x74, // Sel + HID_USAGE_DIGITIZER_CHISEL_MARKER = 0x75, // Sel + HID_USAGE_DIGITIZER_BRUSH = 0x76, // Sel + HID_USAGE_DIGITIZER_NO_PREFERENCE = 0x77, // Sel + // Reserved (0x78 - 0x7F) + HID_USAGE_DIGITIZER_DIGITIZER_DIAGNOSTIC = 0x80, // CL + HID_USAGE_DIGITIZER_DIGITIZER_ERROR = 0x81, // NAry + HID_USAGE_DIGITIZER_ERR_NORMAL_STATUS = 0x82, // Sel + HID_USAGE_DIGITIZER_ERR_TRANSDUCERS_EXCEEDED = 0x83, // Sel + HID_USAGE_DIGITIZER_ERR_FULL_TRANS_FEATURES_UNAVAILABLE = 0x84, // Sel + HID_USAGE_DIGITIZER_ERR_CHARGE_LOW = 0x85, // Sel + // Reserved (0x86 - 0x8F) + HID_USAGE_DIGITIZER_TRANSDUCER_SOFTWARE_INFO = 0x90, // CL + HID_USAGE_DIGITIZER_TRANSDUCER_VENDOR_ID = 0x91, // SV + HID_USAGE_DIGITIZER_TRANSDUCER_PRODUCT_ID = 0x92, // SV + HID_USAGE_DIGITIZER_DEVICE_SUPPORTED_PROTOCOLS = 0x93, // NAry/CL + HID_USAGE_DIGITIZER_TRANSDUCER_SUPPORTED_PROTOCOLS = 0x94, // NAry/CL + HID_USAGE_DIGITIZER_NO_PROTOCOL = 0x95, // Sel + HID_USAGE_DIGITIZER_WACOM_AES_PROTOCOL = 0x96, // Sel + HID_USAGE_DIGITIZER_USI_PROTOCOL = 0x97, // Sel + HID_USAGE_DIGITIZER_MICROSOFT_PEN_PROTOCOL = 0x98, // Sel + // Reserved (0x99 - 0x9F) + HID_USAGE_DIGITIZER_SUPPORTED_REPORT_RATES = 0xA0, // SV/CL + HID_USAGE_DIGITIZER_REPORT_RATE = 0xA1, // DV + HID_USAGE_DIGITIZER_TRANSDUCER_CONNECTED = 0xA2, // SF + HID_USAGE_DIGITIZER_SWITCH_DISABLED = 0xA3, // Sel + HID_USAGE_DIGITIZER_SWITCH_UNIMPLEMENTED = 0xA4, // Sel + HID_USAGE_DIGITIZER_TRANSDUCER_SWITCHES = 0xA5, // CL + HID_USAGE_DIGITIZER_TRANSDUCER_INDEX_SELECTOR = 0xA6, // DV + // Reserved (0xA7 - 0xAF) + HID_USAGE_DIGITIZER_BUTTON_PRESS_THRESHOLD = 0xB0, // DV + + // Reserved (0xB1 - 0xFFFF) +}; + +/// HID Usage Table: Physical Input Device Page (0x0F) +enum { + HID_USAGE_PID_UNDEFINED = 0x00, + HID_USAGE_PID_PHYSICAL_INPUT_DEVICE = 0x01, + HID_USAGE_PID_NORMAL = 0x20, + HID_USAGE_PID_SET_EFFECT_REPORT = 0x21, + HID_USAGE_PID_EFFECT_PARAMETER_BLOCK_INDEX = 0x22, + HID_USAGE_PID_PARAMETER_BLOCK_OFFSET = 0x23, + HID_USAGE_PID_ROM_FLAG = 0x24, + HID_USAGE_PID_EFFECT_TYPE = 0x25, + HID_USAGE_PID_ET_CONSTANTFORCE = 0x26, + HID_USAGE_PID_ET_RAMP = 0x27, + HID_USAGE_PID_ET_CUSTOMFORCE = 0x28, + HID_USAGE_PID_ET_SQUARE = 0x30, + HID_USAGE_PID_ET_SINE = 0x31, + HID_USAGE_PID_ET_TRIANGLE = 0x32, + HID_USAGE_PID_ET_SAWTOOTH_UP = 0x33, + HID_USAGE_PID_ET_SAWTOOTH_DOWN = 0x34, + HID_USAGE_PID_ET_SPRING = 0x40, + HID_USAGE_PID_ET_DAMPER = 0x41, + HID_USAGE_PID_ET_INERTIA = 0x42, + HID_USAGE_PID_ET_FRICTION = 0x43, + HID_USAGE_PID_DURATION = 0x50, + HID_USAGE_PID_SAMPLE_PERIOD = 0x51, + HID_USAGE_PID_GAIN = 0x52, + HID_USAGE_PID_TRIGGER_BUTTON = 0x53, + HID_USAGE_PID_TRIGGER_REPEAT_INTERVAL = 0x54, + HID_USAGE_PID_AXES_ENABLE = 0x55, + HID_USAGE_PID_DIRECTION_ENABLE = 0x56, + HID_USAGE_PID_DIRECTION = 0x57, + HID_USAGE_PID_TYPE_SPECIFIC_BLOCK_OFFSET = 0x58, + HID_USAGE_PID_BLOCK_TYPE = 0x59, + HID_USAGE_PID_SET_ENVELOPE_REPORT = 0x5a, + HID_USAGE_PID_ATTACK_LEVEL = 0x5b, + HID_USAGE_PID_ATTACK_TIME = 0x5c, + HID_USAGE_PID_FADE_LEVEL = 0x5d, + HID_USAGE_PID_FADE_TIME = 0x5e, + HID_USAGE_PID_SET_CONDITION_REPORT = 0x5f, + HID_USAGE_PID_CENTERPOINT_OFFSET = 0x60, + HID_USAGE_PID_POSITIVE_COEFFICIENT = 0x61, + HID_USAGE_PID_NEGATIVE_COEFFICIENT = 0x62, + HID_USAGE_PID_POSITIVE_SATURATION = 0x63, + HID_USAGE_PID_NEGATIVE_SATURATION = 0x64, + HID_USAGE_PID_DEAD_BAND = 0x65, + HID_USAGE_PID_DOWNLOAD_FORCE_SAMPLE = 0x66, + HID_USAGE_PID_ISOCH_CUSTOMFORCE_ENABLE = 0x67, + HID_USAGE_PID_CUSTOMFORCE_DATA_REPORT = 0x68, + HID_USAGE_PID_CUSTOMFORCE_DATA = 0x69, + HID_USAGE_PID_CUSTOMFORCE_VENDOR_DEFINED_DATA = 0x6a, + HID_USAGE_PID_SET_CUSTOMFORCE_REPORT = 0x6b, + HID_USAGE_PID_CUSTOMFORCE_DATA_OFFSET = 0x6c, + HID_USAGE_PID_SAMPLE_COUNT = 0x6d, + HID_USAGE_PID_SET_PERIODIC_REPORT = 0x6e, + HID_USAGE_PID_OFFSET = 0x6f, + HID_USAGE_PID_MAGNITUDE = 0x70, + HID_USAGE_PID_PHASE = 0x71, + HID_USAGE_PID_PERIOD = 0x72, + HID_USAGE_PID_SET_CONSTANTFORCE_REPORT = 0x73, + HID_USAGE_PID_SET_RAMPFORCE_REPORT = 0x74, + HID_USAGE_PID_RAMP_START = 0x75, + HID_USAGE_PID_RAMP_END = 0x76, + HID_USAGE_PID_EFFECT_OPERATION_REPORT = 0x77, + HID_USAGE_PID_EFFECT_OPERATION = 0x78, + HID_USAGE_PID_OP_EFFECT_START = 0x79, + HID_USAGE_PID_OP_EFFECT_START_SOLO = 0x7a, + HID_USAGE_PID_OP_EFFECT_STOP = 0x7b, + HID_USAGE_PID_LOOP_COUNT = 0x7c, + HID_USAGE_PID_DEVICE_GAIN_REPORT = 0x7d, + HID_USAGE_PID_DEVICE_GAIN = 0x7e, + HID_USAGE_PID_PARAMETER_BLOCK_POOLS_REPORT = 0x7f, + HID_USAGE_PID_RAM_POOL_SIZE = 0x80, + HID_USAGE_PID_ROM_POOL_SIZE = 0x81, + HID_USAGE_PID_ROM_EFFECT_BLOCK_COUNT = 0x82, + HID_USAGE_PID_SIMULTANEOUS_EFFECTS_MAX = 0x83, + HID_USAGE_PID_POOL_ALIGNMENT = 0x84, + HID_USAGE_PID_PARAMETER_BLOCK_MOVE_REPORT = 0x85, + HID_USAGE_PID_MOVE_SOURCE = 0x86, + HID_USAGE_PID_MOVE_DESTINATION = 0x87, + HID_USAGE_PID_MOVE_LENGTH = 0x88, + HID_USAGE_PID_EFFECT_PARAMETER_BLOCK_LOAD_REPORT = 0x89, + HID_USAGE_PID_EFFECT_PARAMETER_BLOCK_LOAD_STATUS = 0x8b, + HID_USAGE_PID_BLOCK_LOAD_SUCCESS = 0x8c, + HID_USAGE_PID_BLOCK_LOAD_FULL = 0x8d, + HID_USAGE_PID_BLOCK_LOAD_ERROR = 0x8e, + HID_USAGE_PID_BLOCK_HANDLE = 0x8f, + HID_USAGE_PID_EFFECT_PARAMETER_BLOCK_FREE_REPORT = 0x90, + HID_USAGE_PID_TYPE_SPECIFIC_BLOCK_HANDLE = 0x91, + HID_USAGE_PID_PID_STATE_REPORT = 0x92, + HID_USAGE_PID_EFFECT_PLAYING = 0x94, + HID_USAGE_PID_PID_DEVICE_CONTROL_REPORT = 0x95, + HID_USAGE_PID_PID_DEVICE_CONTROL = 0x96, + HID_USAGE_PID_DC_ENABLE_ACTUATORS = 0x97, + HID_USAGE_PID_DC_DISABLE_ACTUATORS = 0x98, + HID_USAGE_PID_DC_STOP_ALL_EFFECTS = 0x99, + HID_USAGE_PID_DC_RESET = 0x9a, + HID_USAGE_PID_DC_PAUSE = 0x9b, + HID_USAGE_PID_DC_CONTINUE = 0x9c, + HID_USAGE_PID_DEVICE_PAUSED = 0x9f, + HID_USAGE_PID_ACTUATORS_ENABLED = 0xa0, + HID_USAGE_PID_SAFETY_SWITCH = 0xa4, + HID_USAGE_PID_ACTUATOR_OVERRIDE_SWITCH = 0xa5, + HID_USAGE_PID_ACTUATOR_POWER = 0xa6, + HID_USAGE_PID_START_DELAY = 0xa7, + HID_USAGE_PID_PARAMETER_BLOCK_SIZE = 0xa8, + HID_USAGE_PID_DEVICEMANAGED_POOL = 0xa9, + HID_USAGE_PID_SHARED_PARAMETER_BLOCKS = 0xaa, + HID_USAGE_PID_CREATE_NEW_EFFECT_PARAMETER_BLOCK_REPORT = 0xab, + HID_USAGE_PID_RAM_POOL_AVAILABLE = 0xac, +}; + /// HID Usage Table - Lighting And Illumination Page (0x59) enum { HID_USAGE_LIGHTING_LAMP_ARRAY = 0x01, diff --git a/src/class/hid/hid_device.c b/src/class/hid/hid_device.c index eedcba984..b4f24902b 100644 --- a/src/class/hid/hid_device.c +++ b/src/class/hid/hid_device.c @@ -194,6 +194,16 @@ bool tud_hid_n_gamepad_report(uint8_t instance, uint8_t report_id, return tud_hid_n_report(instance, report_id, &report, sizeof(report)); } +bool tud_hid_n_stylus_report(uint8_t instance, uint8_t report_id, uint8_t attrs, uint16_t x, uint16_t y) { + hid_stylus_report_t report = { + .attr = attrs, + .x = x, + .y = y, + }; + + return tud_hid_n_report(instance, report_id, &report, sizeof(report)); +} + //--------------------------------------------------------------------+ // USBD-CLASS API //--------------------------------------------------------------------+ diff --git a/src/class/hid/hid_device.h b/src/class/hid/hid_device.h index ab2e27373..fc1dbcbd8 100644 --- a/src/class/hid/hid_device.h +++ b/src/class/hid/hid_device.h @@ -79,6 +79,9 @@ bool tud_hid_n_abs_mouse_report(uint8_t instance, uint8_t report_id, uint8_t but // use template layout report TUD_HID_REPORT_DESC_GAMEPAD bool tud_hid_n_gamepad_report(uint8_t instance, uint8_t report_id, int8_t x, int8_t y, int8_t z, int8_t rz, int8_t rx, int8_t ry, uint8_t hat, uint32_t buttons); +// STYLUS PEN: convenient helper to send absolute stylus pen report if application +bool tud_hid_n_stylus_report(uint8_t instance, uint8_t report_id, uint8_t attrs, uint16_t x, uint16_t y); + //--------------------------------------------------------------------+ // Application API (Single Port) //--------------------------------------------------------------------+ @@ -114,6 +117,10 @@ TU_ATTR_ALWAYS_INLINE static inline bool tud_hid_gamepad_report(uint8_t report_i return tud_hid_n_gamepad_report(0, report_id, x, y, z, rz, rx, ry, hat, buttons); } +TU_ATTR_ALWAYS_INLINE static inline bool tud_hid_stylus_report(uint8_t report_id, uint8_t attrs, uint16_t x, uint16_t y) { + return tud_hid_n_stylus_report(0, report_id, attrs, x, y); +} + //--------------------------------------------------------------------+ // Application Callbacks //--------------------------------------------------------------------+ @@ -257,6 +264,41 @@ void tud_hid_report_failed_cb(uint8_t instance, hid_report_type_t report_type, u HID_COLLECTION_END , \ HID_COLLECTION_END \ +// Stylus Pen Report Descriptor Template +#define TUD_HID_REPORT_DESC_STYLUS_PEN(...) \ + HID_USAGE_PAGE ( HID_USAGE_PAGE_DIGITIZER ) , \ + HID_USAGE ( HID_USAGE_DIGITIZER_TOUCH_SCREEN ) , \ + HID_COLLECTION ( HID_COLLECTION_APPLICATION ) , \ + /* Report ID if any */\ + __VA_ARGS__ \ + HID_USAGE ( HID_USAGE_DIGITIZER_STYLUS ) , \ + HID_COLLECTION ( HID_COLLECTION_PHYSICAL ) , \ + HID_USAGE_PAGE ( HID_USAGE_DIGITIZER_TIP_SWITCH ) , \ + HID_USAGE_PAGE ( HID_USAGE_DIGITIZER_IN_RANGE ) , \ + HID_LOGICAL_MIN ( 0 ), \ + HID_LOGICAL_MAX ( 1 ), \ + HID_REPORT_SIZE ( 1 ), \ + HID_REPORT_COUNT( 2 ), \ + HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ), \ + HID_REPORT_SIZE ( 1 ), \ + HID_REPORT_COUNT( 6 ), \ + HID_INPUT ( HID_CONSTANT | HID_ARRAY | HID_ABSOLUTE), \ + HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ), \ + HID_PHYSICAL_MAX_N( 0x7fff, 2 ), \ + HID_LOGICAL_MAX_N ( 0x7fff, 2 ), \ + HID_REPORT_SIZE ( 16 ), \ + HID_REPORT_COUNT( 1 ), \ + HID_UNIT_EXPONENT( 0x0f ), \ + HID_UNIT ( HID_VARIABLE | HID_NONLINEAR ), \ + HID_PHYSICAL_MIN( 0 ), \ + HID_PHYSICAL_MAX( 0 ), \ + HID_USAGE ( HID_USAGE_DESKTOP_X ), \ + HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ), \ + HID_USAGE ( HID_USAGE_DESKTOP_Y ), \ + HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ), \ + HID_COLLECTION_END , \ + HID_COLLECTION_END \ + // Absolute Mouse Report Descriptor Template #define TUD_HID_REPORT_DESC_ABSMOUSE(...) \ HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\ diff --git a/src/class/hid/hid_host.c b/src/class/hid/hid_host.c index eef584d74..57e437196 100644 --- a/src/class/hid/hid_host.c +++ b/src/class/hid/hid_host.c @@ -410,7 +410,7 @@ bool tuh_hid_send_report(uint8_t daddr, uint8_t idx, uint8_t report_id, const vo ++len; // 1 more byte for report_id } - TU_LOG3_MEM(p_hid->epout_buf, len, 2); + TU_LOG3_MEM(epbuf->epout, len, 2); if (!usbh_edpt_xfer(daddr, p_hid->ep_out, epbuf->epout, len)) { usbh_edpt_release(daddr, p_hid->ep_out); @@ -444,8 +444,8 @@ bool hidh_xfer_cb(uint8_t daddr, uint8_t ep_addr, xfer_result_t result, uint32_t hidh_epbuf_t* epbuf = get_hid_epbuf(idx); if (dir == TUSB_DIR_IN) { - TU_LOG_DRV(" Get Report callback (%u, %u)\r\n", daddr, idx); - TU_LOG3_MEM(p_hid->epin_buf, xferred_bytes, 2); + TU_LOG_DRV(" [idx=%u] Get Report callback\r\n", idx); + TU_LOG3_MEM(epbuf->epin, xferred_bytes, 2); tuh_hid_report_received_cb(daddr, idx, epbuf->epin, (uint16_t) xferred_bytes); } else { if (tuh_hid_report_sent_cb) { @@ -461,7 +461,9 @@ void hidh_close(uint8_t daddr) { hidh_interface_t* p_hid = &_hidh_itf[i]; if (p_hid->daddr == daddr) { TU_LOG_DRV(" HIDh close addr = %u index = %u\r\n", daddr, i); - if (tuh_hid_umount_cb) tuh_hid_umount_cb(daddr, i); + if (tuh_hid_umount_cb) { + tuh_hid_umount_cb(daddr, i); + } tu_memclr(p_hid, sizeof(hidh_interface_t)); } } diff --git a/src/class/midi/README_midi_host.md b/src/class/midi/README_midi_host.md new file mode 100644 index 000000000..efaf7a13d --- /dev/null +++ b/src/class/midi/README_midi_host.md @@ -0,0 +1,111 @@ +# MIDI HOST DRIVER +This README file contains the design notes and limitations of the +MIDI host driver. + +# MAXIMUM NUMBER OF MIDI DEVICES ATTACHED TO HOST +In this version of the driver, only one MIDI device is supported. This +constraint may change in the future. + +# MAXIMUM NUMBER OF ENDPOINTS +Although the USB MIDI 1.0 Class specification allows an arbitrary number +of endpoints, this driver supports at most one USB BULK DATA IN endpoint +and one USB BULK DATA OUT endpoint. Each endpoint can support up to 16 +virtual cables. If a device has multiple IN endpoints or multiple OUT +endpoints, it will fail to enumerate. + +Most USB MIDI devices contain both an IN endpoint and an OUT endpoint, +but not all do. For example, some USB pedals only support an OUT endpoint. +This driver allows that. + +# PUBLIC API +Applications interact with this driver via 8-bit buffers of MIDI messages +formed using the rules for sending bytes on a 5-pin DIN cable per the +original MIDI 1.0 specification. + +To send a message to a device, the Host application composes a sequence +of status and data bytes in a byte array and calls the API function. +The arguments of the function are a pointer to the byte array, the number +of bytes in the array, and the target virtual cable number 0-15. + +When the host driver receives a message from the device, the host driver +will call a callback function that the host application registers. This +callback function contains a pointer to a message buffer, a message length, +and the virtual cable number of the message buffer. One complete bulk IN +endpoint transfer might contain multiple messages targeted to different +virtual cables. + +# SUBCLASS AUDIO CONTROL +A MIDI device does not absolutely need to have an Audio Control Interface, +unless it adheres to the USB Audio Class 2 spec, but many devices +have them even if the devices do not have an audio streaming interface. +Because this driver does not support audio streaming, the descriptor parser +will skip past any audio control interface and audio streaming interface +and open only the MIDI interface. + +An audio streaming host driver can use this driver by passing a pointer +to the MIDI interface descriptor that is found after the audio streaming +interface to the midih_open() function. That is, an audio streaming host +driver would parse the audio control interface descriptor and then the +audio streaming interface and endpoint descriptors. When the next descriptor +pointer points to a MIDI interface descriptor, call midih_open() with that +descriptor pointer. + +# CLASS SPECIFIC INTERFACE AND REQUESTS +The host driver does not make use of the information in the class specific +interface descriptors. In the future, a public API could be created to +retrieve the string descriptors for the names of each ELEMENT, +IN JACK and OUT JACK, and how the device describes the connections. + +This driver also does not support class specific requests to control +ELEMENT items, nor does it support non-MIDI Streaming bulk endpoints. + +# MIDI CLASS SPECIFIC DESCRIPTOR TOTAL LENGTH FIELD IGNORED +I have observed at least one keyboard by a leading manufacturer that +sets the wTotalLength field of the Class-Specific MS Interface Header +Descriptor to include the length of the MIDIStreaming Endpoint +Descriptors. This is wrong per my reading of the specification. + +# MESSAGE BUFFER DETAILS +Messages buffers composed from USB data received on the IN endpoint will never contain +running status because USB MIDI 1.0 class does not support that. Messages +buffers to be sent to the device on the OUT endpoint may contain running status +(the message might come from a UART data stream from a 5-pin DIN MIDI IN +cable on the host, for example). The driver may in the future correctly compose +4-byte USB MIDI Class packets using the running status if need be. However, +it does not currently do that. Also, use of running status is not a good idea +overall because a single byte error can really mess up the data stream with no +way to recover until the next non-real time status byte is in the message buffer. + +Message buffers to be sent to the device may contain Real time messages +such as MIDI clock. Real time messages may be inserted in the message +byte stream between status and data bytes of another message without disrupting +the running status. However, because MIDI 1.0 class messages are sent +as four byte packets, a real-time message so inserted will be re-ordered +to be sent to the device in a new 4-byte packet immediately before the +interrupted data stream. + +Real time messages the device sends to the host can only appear between +the status byte and data bytes of the message in System Exclusive messages +that are longer than 3 bytes. + +# POORLY FORMED USB MIDI DATA PACKETS FROM THE DEVICE +Some devices do not properly encode the code index number (CIN) for the +MIDI message status byte even though the 3-byte data payload correctly encodes +the MIDI message. This driver looks to the byte after the CIN byte to decide +how many bytes to place in the message buffer. + +Some devices do not properly encode the virtual cable number. If the virtual +cable number in the CIN data byte of the packet is not less than bNumEmbMIDIJack +for that endpoint, then the host driver assumes virtual cable 0 and does not +report an error. + +Some MIDI devices will always send back exactly wMaxPacketSize bytes on +every endpoint even if only one 4-byte packet is required (e.g., NOTE ON). +These devices send packets with 4 packet bytes 0. This driver ignores all +zero packets without reporting an error. + +# ENUMERATION FAILURES +The host may fail to enumerate a device if it has too many endpoints, if it has +if it has a Standard MS Transfer Bulk Data Endpoint Descriptor (not supported), +if it has a poorly formed descriptor, or if the descriptor is too long for +the host to read the whole thing. diff --git a/src/class/midi/midi.h b/src/class/midi/midi.h index 8ddcdfda2..cd67640e4 100644 --- a/src/class/midi/midi.h +++ b/src/class/midi/midi.h @@ -24,13 +24,8 @@ * This file is part of the TinyUSB stack. */ -/** \ingroup group_class - * \defgroup ClassDriver_CDC Communication Device Class (CDC) - * Currently only Abstract Control Model subclass is supported - * @{ */ - -#ifndef _TUSB_MIDI_H__ -#define _TUSB_MIDI_H__ +#ifndef TUSB_MIDI_H_ +#define TUSB_MIDI_H_ #include "common/tusb_common.h" @@ -39,30 +34,31 @@ #endif //--------------------------------------------------------------------+ -// Class Specific Descriptor +// Constants //--------------------------------------------------------------------+ +enum { + MIDI_VERSION_1_0 = 0x0100, + MIDI_VERSION_2_0 = 0x0200, +}; -typedef enum -{ +typedef enum { MIDI_CS_INTERFACE_HEADER = 0x01, MIDI_CS_INTERFACE_IN_JACK = 0x02, MIDI_CS_INTERFACE_OUT_JACK = 0x03, MIDI_CS_INTERFACE_ELEMENT = 0x04, } midi_cs_interface_subtype_t; -typedef enum -{ - MIDI_CS_ENDPOINT_GENERAL = 0x01 +typedef enum { + MIDI_CS_ENDPOINT_GENERAL = 0x01, + MIDI_CS_ENDPOINT_GENERAL_2_0 = 0x02, } midi_cs_endpoint_subtype_t; -typedef enum -{ +typedef enum { MIDI_JACK_EMBEDDED = 0x01, MIDI_JACK_EXTERNAL = 0x02 } midi_jack_type_t; -typedef enum -{ +typedef enum { MIDI_CIN_MISC = 0, MIDI_CIN_CABLE_EVENT = 1, MIDI_CIN_SYSCOM_2BYTE = 2, // 2 byte system common message e.g MTC, SongSelect @@ -82,8 +78,7 @@ typedef enum } midi_code_index_number_t; // MIDI 1.0 status byte -enum -{ +enum { //------------- System Exclusive -------------// MIDI_STATUS_SYSEX_START = 0xF0, MIDI_STATUS_SYSEX_END = 0xF7, @@ -106,80 +101,54 @@ enum MIDI_STATUS_SYSREAL_SYSTEM_RESET = 0xFF, }; +enum { + MIDI_MAX_DATA_VAL = 0x7F, +}; + +//--------------------------------------------------------------------+ +// Class Specific Descriptor +//--------------------------------------------------------------------+ + /// MIDI Interface Header Descriptor -typedef struct TU_ATTR_PACKED -{ - uint8_t bLength ; ///< Size of this descriptor in bytes. - uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific - uint8_t bDescriptorSubType ; ///< Descriptor SubType - uint16_t bcdMSC ; ///< MidiStreaming SubClass release number in Binary-Coded Decimal - uint16_t wTotalLength ; +typedef struct TU_ATTR_PACKED { + uint8_t bLength; ///< Size of this descriptor in bytes. + uint8_t bDescriptorType; ///< must be TUSB_DESC_CS_INTERFACE + uint8_t bDescriptorSubType;///< Descriptor SubType + uint16_t bcdMSC; ///< MidiStreaming SubClass release number in Binary-Coded Decimal + uint16_t wTotalLength; } midi_desc_header_t; +TU_VERIFY_STATIC(sizeof(midi_desc_header_t) == 7, "size is not correct"); /// MIDI In Jack Descriptor -typedef struct TU_ATTR_PACKED -{ - uint8_t bLength ; ///< Size of this descriptor in bytes. - uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific - uint8_t bDescriptorSubType ; ///< Descriptor SubType - uint8_t bJackType ; ///< Embedded or External - uint8_t bJackID ; ///< Unique ID for MIDI IN Jack - uint8_t iJack ; ///< string descriptor +typedef struct TU_ATTR_PACKED { + uint8_t bLength; ///< Size of this descriptor in bytes. + uint8_t bDescriptorType; ///< Descriptor Type, must be Class-Specific + uint8_t bDescriptorSubType;///< Descriptor SubType + uint8_t bJackType; ///< Embedded or External + uint8_t bJackID; ///< Unique ID for MIDI IN Jack + uint8_t iJack; ///< string descriptor } midi_desc_in_jack_t; +TU_VERIFY_STATIC(sizeof(midi_desc_in_jack_t) == 6, "size is not correct"); - -/// MIDI Out Jack Descriptor with single pin -typedef struct TU_ATTR_PACKED -{ - uint8_t bLength ; ///< Size of this descriptor in bytes. - uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific - uint8_t bDescriptorSubType ; ///< Descriptor SubType - uint8_t bJackType ; ///< Embedded or External - uint8_t bJackID ; ///< Unique ID for MIDI IN Jack - uint8_t bNrInputPins; - - uint8_t baSourceID; - uint8_t baSourcePin; - - uint8_t iJack ; ///< string descriptor -} midi_desc_out_jack_t ; - -/// MIDI Out Jack Descriptor with multiple pins +/// MIDI Out Jack Descriptor with multiple input pins #define midi_desc_out_jack_n_t(input_num) \ - struct TU_ATTR_PACKED { \ - uint8_t bLength ; \ - uint8_t bDescriptorType ; \ - uint8_t bDescriptorSubType ; \ - uint8_t bJackType ; \ - uint8_t bJackID ; \ - uint8_t bNrInputPins ; \ - struct TU_ATTR_PACKED { \ - uint8_t baSourceID; \ - uint8_t baSourcePin; \ - } pins[input_num]; \ - uint8_t iJack ; \ + struct TU_ATTR_PACKED { \ + uint8_t bLength; \ + uint8_t bDescriptorType; \ + uint8_t bDescriptorSubType; \ + uint8_t bJackType; \ + uint8_t bJackID; \ + uint8_t bNrInputPins; \ + struct TU_ATTR_PACKED { \ + uint8_t baSourceID; \ + uint8_t baSourcePin; \ + } input[input_num]; \ + uint8_t iJack; \ } -/// MIDI Element Descriptor -typedef struct TU_ATTR_PACKED -{ - uint8_t bLength ; ///< Size of this descriptor in bytes. - uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific - uint8_t bDescriptorSubType ; ///< Descriptor SubType - uint8_t bElementID; - - uint8_t bNrInputPins; - uint8_t baSourceID; - uint8_t baSourcePin; - - uint8_t bNrOutputPins; - uint8_t bInTerminalLink; - uint8_t bOutTerminalLink; - uint8_t bElCapsSize; - - uint16_t bmElementCaps; - uint8_t iElement; -} midi_desc_element_t; +typedef midi_desc_out_jack_n_t(1) midi_desc_out_jack_1in_t; // 1 input +typedef midi_desc_out_jack_1in_t midi_desc_out_jack_t; // backward compatible +TU_VERIFY_STATIC(sizeof(midi_desc_out_jack_1in_t) == 7 + 2 * 1, "size is not correct"); /// MIDI Element Descriptor with multiple pins #define midi_desc_element_n_t(input_num) \ @@ -201,12 +170,32 @@ typedef struct TU_ATTR_PACKED uint8_t iElement; \ } -/** @} */ +// This descriptor follows the standard bulk data endpoint descriptor +#define midi_desc_cs_endpoint_n_t(jack_num) \ + struct TU_ATTR_PACKED { \ + uint8_t bLength; \ + uint8_t bDescriptorType; \ + uint8_t bDescriptorSubType; \ + uint8_t bNumEmbMIDIJack; \ + uint8_t baAssocJackID[jack_num]; \ + } + +typedef midi_desc_cs_endpoint_n_t() midi_desc_cs_endpoint_t; // empty/flexible jack list +typedef midi_desc_cs_endpoint_n_t(1) midi_desc_cs_endpoint_1jack_t; + +TU_VERIFY_STATIC(sizeof(midi_desc_cs_endpoint_1jack_t) == 4+1, "size is not correct"); + +//--------------------------------------------------------------------+ +// For Internal Driver Use +//--------------------------------------------------------------------+ +typedef struct { + uint8_t buffer[4]; + uint8_t index; + uint8_t total; +} midi_driver_stream_t; #ifdef __cplusplus } #endif #endif - -/** @} */ diff --git a/src/class/midi/midi_device.c b/src/class/midi/midi_device.c index c545f8287..0bbb3caf4 100644 --- a/src/class/midi/midi_device.c +++ b/src/class/midi/midi_device.c @@ -39,13 +39,6 @@ //--------------------------------------------------------------------+ // MACRO CONSTANT TYPEDEF //--------------------------------------------------------------------+ - -typedef struct { - uint8_t buffer[4]; - uint8_t index; - uint8_t total; -} midid_stream_t; - typedef struct { uint8_t itf_num; uint8_t ep_in; @@ -54,8 +47,8 @@ typedef struct { // For Stream read()/write() API // Messages are always 4 bytes long, queue them for reading and writing so the // callers can use the Stream interface with single-byte read/write calls. - midid_stream_t stream_write; - midid_stream_t stream_read; + midi_driver_stream_t stream_write; + midi_driver_stream_t stream_read; /*------------- From this point, data is not cleared by bus reset -------------*/ // FIFO @@ -122,7 +115,7 @@ uint32_t tud_midi_n_available(uint8_t itf, uint8_t cable_num) (void) cable_num; midid_interface_t* midi = &_midid_itf[itf]; - const midid_stream_t* stream = &midi->stream_read; + const midi_driver_stream_t* stream = &midi->stream_read; // when using with packet API stream total & index are both zero return tu_fifo_count(&midi->rx_ff) + (uint8_t) (stream->total - stream->index); @@ -136,7 +129,7 @@ uint32_t tud_midi_n_stream_read(uint8_t itf, uint8_t cable_num, void* buffer, ui uint8_t* buf8 = (uint8_t*) buffer; midid_interface_t* midi = &_midid_itf[itf]; - midid_stream_t* stream = &midi->stream_read; + midi_driver_stream_t* stream = &midi->stream_read; uint32_t total_read = 0; while( bufsize ) @@ -241,7 +234,7 @@ uint32_t tud_midi_n_stream_write(uint8_t itf, uint8_t cable_num, const uint8_t* midid_interface_t* midi = &_midid_itf[itf]; TU_VERIFY(midi->ep_in, 0); - midid_stream_t* stream = &midi->stream_write; + midi_driver_stream_t* stream = &midi->stream_write; uint32_t i = 0; while ( (i < bufsize) && (tu_fifo_remaining(&midi->tx_ff) >= 4) ) @@ -429,21 +422,21 @@ void midid_reset(uint8_t rhport) } } -uint16_t midid_open(uint8_t rhport, const tusb_desc_interface_t* desc_itf, uint16_t max_len) -{ - // 1st Interface is Audio Control v1 - TU_VERIFY(TUSB_CLASS_AUDIO == desc_itf->bInterfaceClass && - AUDIO_SUBCLASS_CONTROL == desc_itf->bInterfaceSubClass && - AUDIO_FUNC_PROTOCOL_CODE_UNDEF == desc_itf->bInterfaceProtocol, 0); +uint16_t midid_open(uint8_t rhport, const tusb_desc_interface_t* desc_itf, uint16_t max_len) { + uint16_t drv_len = 0; + uint8_t const * p_desc = (uint8_t const *)desc_itf; - uint16_t drv_len = tu_desc_len(desc_itf); - const uint8_t* p_desc = tu_desc_next(desc_itf); - - // Skip Class Specific descriptors - while ( TUSB_DESC_CS_INTERFACE == tu_desc_type(p_desc) && drv_len <= max_len ) - { - drv_len += tu_desc_len(p_desc); - p_desc = tu_desc_next(p_desc); + // 1st Interface is Audio Control v1 (optional) + if (TUSB_CLASS_AUDIO == desc_itf->bInterfaceClass && + AUDIO_SUBCLASS_CONTROL == desc_itf->bInterfaceSubClass && + AUDIO_FUNC_PROTOCOL_CODE_UNDEF == desc_itf->bInterfaceProtocol) { + drv_len = tu_desc_len(desc_itf); + p_desc = tu_desc_next(desc_itf); + // Skip Class Specific descriptors + while (TUSB_DESC_CS_INTERFACE == tu_desc_type(p_desc) && drv_len <= max_len) { + drv_len += tu_desc_len(p_desc); + p_desc = tu_desc_next(p_desc); + } } // 2nd Interface is MIDI Streaming diff --git a/src/class/midi/midi_host.c b/src/class/midi/midi_host.c new file mode 100644 index 000000000..cd6e115ee --- /dev/null +++ b/src/class/midi/midi_host.c @@ -0,0 +1,622 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * This file is part of the TinyUSB stack. + */ + +#include "tusb_option.h" + +#if (CFG_TUH_ENABLED && CFG_TUH_MIDI) + +#include "host/usbh.h" +#include "host/usbh_pvt.h" + +#include "midi_host.h" + +// Level where CFG_TUSB_DEBUG must be at least for this driver is logged +#ifndef CFG_TUH_MIDI_LOG_LEVEL + #define CFG_TUH_MIDI_LOG_LEVEL CFG_TUH_LOG_LEVEL +#endif + +#define TU_LOG_DRV(...) TU_LOG(CFG_TUH_MIDI_LOG_LEVEL, __VA_ARGS__) + +//--------------------------------------------------------------------+ +// Weak stubs: invoked if no strong implementation is available +//--------------------------------------------------------------------+ +TU_ATTR_WEAK void tuh_midi_descriptor_cb(uint8_t idx, const tuh_midi_descriptor_cb_t * desc_cb_data) { (void) idx; (void) desc_cb_data; } +TU_ATTR_WEAK void tuh_midi_mount_cb(uint8_t idx, const tuh_midi_mount_cb_t* mount_cb_data) { (void) idx; (void) mount_cb_data; } +TU_ATTR_WEAK void tuh_midi_umount_cb(uint8_t idx) { (void) idx; } +TU_ATTR_WEAK void tuh_midi_rx_cb(uint8_t idx, uint32_t xferred_bytes) { (void) idx; (void) xferred_bytes; } +TU_ATTR_WEAK void tuh_midi_tx_cb(uint8_t idx, uint32_t xferred_bytes) { (void) idx; (void) xferred_bytes; } + +//--------------------------------------------------------------------+ +// MACRO CONSTANT TYPEDEF +//--------------------------------------------------------------------+ + +typedef struct { + uint8_t daddr; + uint8_t bInterfaceNumber; // interface number of MIDI streaming + uint8_t iInterface; + uint8_t itf_count; // number of interface including Audio Control + MIDI streaming + + uint8_t ep_in; // IN endpoint address + uint8_t ep_out; // OUT endpoint address + + uint8_t rx_cable_count; // IN endpoint CS descriptor bNumEmbMIDIJack value + uint8_t tx_cable_count; // OUT endpoint CS descriptor bNumEmbMIDIJack value + + #if CFG_TUH_MIDI_STREAM_API + // For Stream read()/write() API + // Messages are always 4 bytes long, queue them for reading and writing so the + // callers can use the Stream interface with single-byte read/write calls. + midi_driver_stream_t stream_write; + midi_driver_stream_t stream_read; + #endif + + // Endpoint stream + struct { + tu_edpt_stream_t tx; + tu_edpt_stream_t rx; + + uint8_t rx_ff_buf[CFG_TUH_MIDI_RX_BUFSIZE]; + uint8_t tx_ff_buf[CFG_TUH_MIDI_TX_BUFSIZE]; + } ep_stream; + + bool mounted; +}midih_interface_t; + +typedef struct { + TUH_EPBUF_DEF(tx, TUH_EPSIZE_BULK_MPS); + TUH_EPBUF_DEF(rx, TUH_EPSIZE_BULK_MPS); +} midih_epbuf_t; + +static midih_interface_t _midi_host[CFG_TUH_MIDI]; +CFG_TUH_MEM_SECTION static midih_epbuf_t _midi_epbuf[CFG_TUH_MIDI]; + +//--------------------------------------------------------------------+ +// Helper +//--------------------------------------------------------------------+ +TU_ATTR_ALWAYS_INLINE static inline uint8_t find_new_midi_index(void) { + for (uint8_t idx = 0; idx < CFG_TUH_MIDI; idx++) { + if (_midi_host[idx].daddr == 0) { + return idx; + } + } + return TUSB_INDEX_INVALID_8; +} + +static inline uint8_t get_idx_by_ep_addr(uint8_t daddr, uint8_t ep_addr) { + for (uint8_t idx = 0; idx < CFG_TUH_MIDI; idx++) { + const midih_interface_t *p_midi = &_midi_host[idx]; + if ((p_midi->daddr == daddr) && + (ep_addr == p_midi->ep_stream.rx.ep_addr || ep_addr == p_midi->ep_stream.tx.ep_addr)) { + return idx; + } + } + return TUSB_INDEX_INVALID_8; +} + +//--------------------------------------------------------------------+ +// USBH API +//--------------------------------------------------------------------+ +bool midih_init(void) { + tu_memclr(&_midi_host, sizeof(_midi_host)); + for (int inst = 0; inst < CFG_TUH_MIDI; inst++) { + midih_interface_t *p_midi_host = &_midi_host[inst]; + tu_edpt_stream_init(&p_midi_host->ep_stream.rx, true, false, false, + p_midi_host->ep_stream.rx_ff_buf, CFG_TUH_MIDI_RX_BUFSIZE, _midi_epbuf->rx, TUH_EPSIZE_BULK_MPS); + tu_edpt_stream_init(&p_midi_host->ep_stream.tx, true, true, false, + p_midi_host->ep_stream.tx_ff_buf, CFG_TUH_MIDI_TX_BUFSIZE, _midi_epbuf->tx, TUH_EPSIZE_BULK_MPS); + } + return true; +} + +bool midih_deinit(void) { + for (size_t i = 0; i < CFG_TUH_MIDI; i++) { + midih_interface_t* p_midi = &_midi_host[i]; + tu_edpt_stream_deinit(&p_midi->ep_stream.rx); + tu_edpt_stream_deinit(&p_midi->ep_stream.tx); + } + return true; +} + +void midih_close(uint8_t daddr) { + for (uint8_t idx = 0; idx < CFG_TUH_MIDI; idx++) { + midih_interface_t* p_midi = &_midi_host[idx]; + if (p_midi->daddr == daddr) { + TU_LOG_DRV(" MIDI close addr = %u index = %u\r\n", daddr, idx); + tuh_midi_umount_cb(idx); + + p_midi->ep_in = 0; + p_midi->ep_out = 0; + p_midi->bInterfaceNumber = 0; + p_midi->rx_cable_count = 0; + p_midi->tx_cable_count = 0; + p_midi->daddr = 0; + p_midi->mounted = false; +#if CFG_TUH_MIDI_STREAM_API + tu_memclr(&p_midi->stream_read, sizeof(p_midi->stream_read)); + tu_memclr(&p_midi->stream_write, sizeof(p_midi->stream_write)); +#endif + tu_edpt_stream_close(&p_midi->ep_stream.rx); + tu_edpt_stream_close(&p_midi->ep_stream.tx); + } + } +} + +bool midih_xfer_cb(uint8_t dev_addr, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes) { + (void) result; + const uint8_t idx = get_idx_by_ep_addr(dev_addr, ep_addr); + TU_VERIFY(idx < CFG_TUH_MIDI); + midih_interface_t *p_midi = &_midi_host[idx]; + + if (ep_addr == p_midi->ep_stream.rx.ep_addr) { + // receive new data, put it into FIFO and invoke callback if available + // Note: some devices send back all zero packets even if there is no data ready + if (xferred_bytes && !tu_mem_is_zero(p_midi->ep_stream.rx.ep_buf, xferred_bytes)) { + tu_edpt_stream_read_xfer_complete(&p_midi->ep_stream.rx, xferred_bytes); + tuh_midi_rx_cb(idx, xferred_bytes); + } + + tu_edpt_stream_read_xfer(dev_addr, &p_midi->ep_stream.rx); // prepare for next transfer + } else if (ep_addr == p_midi->ep_stream.tx.ep_addr) { + tuh_midi_tx_cb(idx, xferred_bytes); + + if (0 == tu_edpt_stream_write_xfer(dev_addr, &p_midi->ep_stream.tx)) { + // If there is no data left, a ZLP should be sent if + // xferred_bytes is multiple of EP size and not zero + tu_edpt_stream_write_zlp_if_needed(dev_addr, &p_midi->ep_stream.tx, xferred_bytes); + } + } + + return true; +} + +//--------------------------------------------------------------------+ +// Enumeration +//--------------------------------------------------------------------+ +bool midih_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const *desc_itf, uint16_t max_len) { + (void) rhport; + + TU_VERIFY(TUSB_CLASS_AUDIO == desc_itf->bInterfaceClass); + const uint8_t *p_end = ((const uint8_t *) desc_itf) + max_len; + const uint8_t *p_desc = (const uint8_t *) desc_itf; + + const uint8_t idx = find_new_midi_index(); + TU_VERIFY(idx < CFG_TUH_MIDI); + midih_interface_t *p_midi = &_midi_host[idx]; + p_midi->itf_count = 0; + + tuh_midi_descriptor_cb_t desc_cb = { 0 }; + desc_cb.jack_num = 0; + + // There can be just a MIDI or an Audio + MIDI interface + // If there is Audio Control Interface + Audio Header descriptor, skip it + if (AUDIO_SUBCLASS_CONTROL == desc_itf->bInterfaceSubClass) { + TU_VERIFY(max_len > 2*sizeof(tusb_desc_interface_t) + sizeof(audio_desc_cs_ac_interface_t)); + + p_desc = tu_desc_next(p_desc); + TU_VERIFY(tu_desc_type(p_desc) == TUSB_DESC_CS_INTERFACE && + tu_desc_subtype(p_desc) == AUDIO_CS_AC_INTERFACE_HEADER); + desc_cb.desc_audio_control = desc_itf; + + p_desc = tu_desc_next(p_desc); + desc_itf = (const tusb_desc_interface_t *)p_desc; + TU_VERIFY(TUSB_CLASS_AUDIO == desc_itf->bInterfaceClass); + p_midi->itf_count = 1; + } + TU_VERIFY(AUDIO_SUBCLASS_MIDI_STREAMING == desc_itf->bInterfaceSubClass); + + TU_LOG_DRV("MIDI opening Interface %u (addr = %u)\r\n", desc_itf->bInterfaceNumber, dev_addr); + p_midi->bInterfaceNumber = desc_itf->bInterfaceNumber; + p_midi->iInterface = desc_itf->iInterface; + p_midi->itf_count++; + desc_cb.desc_midi = desc_itf; + + p_desc = tu_desc_next(p_desc); // next to CS Header + + bool found_new_interface = false; + while ((p_desc < p_end) && (tu_desc_next(p_desc) <= p_end) && !found_new_interface) { + switch (tu_desc_type(p_desc)) { + case TUSB_DESC_INTERFACE: + found_new_interface = true; + break; + + case TUSB_DESC_CS_INTERFACE: + switch (tu_desc_subtype(p_desc)) { + case MIDI_CS_INTERFACE_HEADER: + TU_LOG_DRV(" Interface Header descriptor\r\n"); + desc_cb.desc_header = p_desc; + break; + + case MIDI_CS_INTERFACE_IN_JACK: + case MIDI_CS_INTERFACE_OUT_JACK: { + TU_LOG_DRV(" Jack %s %s descriptor \r\n", + tu_desc_subtype(p_desc) == MIDI_CS_INTERFACE_IN_JACK ? "IN" : "OUT", + p_desc[3] == MIDI_JACK_EXTERNAL ? "External" : "Embedded"); + if (desc_cb.jack_num < TU_ARRAY_SIZE(desc_cb.desc_jack)) { + desc_cb.desc_jack[desc_cb.jack_num++] = p_desc; + } + break; + } + + case MIDI_CS_INTERFACE_ELEMENT: + TU_LOG_DRV(" Element descriptor\r\n"); + desc_cb.desc_element = p_desc; + break; + + default: + TU_LOG_DRV(" Unknown CS Interface sub-type %u\r\n", tu_desc_subtype(p_desc)); + break; + } + break; + + case TUSB_DESC_ENDPOINT: { + const tusb_desc_endpoint_t *p_ep = (const tusb_desc_endpoint_t *) p_desc; + p_desc = tu_desc_next(p_desc); // next to CS endpoint + TU_VERIFY(p_desc < p_end && tu_desc_next(p_desc) <= p_end); + const midi_desc_cs_endpoint_t *p_csep = (const midi_desc_cs_endpoint_t *) p_desc; + + TU_LOG_DRV(" Endpoint and CS_Endpoint descriptor %02x\r\n", p_ep->bEndpointAddress); + if (tu_edpt_dir(p_ep->bEndpointAddress) == TUSB_DIR_OUT) { + p_midi->ep_out = p_ep->bEndpointAddress; + p_midi->tx_cable_count = p_csep->bNumEmbMIDIJack; + desc_cb.desc_epout = p_ep; + + TU_ASSERT(tuh_edpt_open(dev_addr, p_ep)); + tu_edpt_stream_open(&p_midi->ep_stream.tx, p_ep); + } else { + p_midi->ep_in = p_ep->bEndpointAddress; + p_midi->rx_cable_count = p_csep->bNumEmbMIDIJack; + desc_cb.desc_epin = p_ep; + + TU_ASSERT(tuh_edpt_open(dev_addr, p_ep)); + tu_edpt_stream_open(&p_midi->ep_stream.rx, p_ep); + } + break; + } + + default: break; // skip unknown descriptor + } + p_desc = tu_desc_next(p_desc); + } + desc_cb.desc_midi_total_len = (uint16_t) ((uintptr_t)p_desc - (uintptr_t) desc_itf); + + p_midi->daddr = dev_addr; + tuh_midi_descriptor_cb(idx, &desc_cb); + + return true; +} + +bool midih_set_config(uint8_t dev_addr, uint8_t itf_num) { + uint8_t idx = tuh_midi_itf_get_index(dev_addr, itf_num); + TU_ASSERT(idx < CFG_TUH_MIDI); + midih_interface_t *p_midi = &_midi_host[idx]; + p_midi->mounted = true; + + const tuh_midi_mount_cb_t mount_cb_data = { + .daddr = dev_addr, + .bInterfaceNumber = itf_num, + .rx_cable_count = p_midi->rx_cable_count, + .tx_cable_count = p_midi->tx_cable_count, + }; + tuh_midi_mount_cb(idx, &mount_cb_data); + + tu_edpt_stream_read_xfer(dev_addr, &p_midi->ep_stream.rx); // prepare for incoming data + + // No special config things to do for MIDI + usbh_driver_set_config_complete(dev_addr, p_midi->bInterfaceNumber); + return true; +} + +//--------------------------------------------------------------------+ +// API +//--------------------------------------------------------------------+ +bool tuh_midi_mounted(uint8_t idx) { + TU_VERIFY(idx < CFG_TUH_MIDI); + midih_interface_t *p_midi = &_midi_host[idx]; + return p_midi->mounted; +} + +uint8_t tuh_midi_itf_get_index(uint8_t daddr, uint8_t itf_num) { + for (uint8_t idx = 0; idx < CFG_TUH_MIDI; idx++) { + const midih_interface_t *p_midi = &_midi_host[idx]; + if (p_midi->daddr == daddr && + (p_midi->bInterfaceNumber == itf_num || + p_midi->bInterfaceNumber == (uint8_t) (itf_num + p_midi->itf_count - 1))) { + return idx; + } + } + return TUSB_INDEX_INVALID_8; +} + +bool tuh_midi_itf_get_info(uint8_t idx, tuh_itf_info_t* info) { + midih_interface_t* p_midi = &_midi_host[idx]; + TU_VERIFY(p_midi && info); + + info->daddr = p_midi->daddr; + + // re-construct descriptor + tusb_desc_interface_t* desc = &info->desc; + desc->bLength = sizeof(tusb_desc_interface_t); + desc->bDescriptorType = TUSB_DESC_INTERFACE; + + desc->bInterfaceNumber = p_midi->bInterfaceNumber; + desc->bAlternateSetting = 0; + desc->bNumEndpoints = (uint8_t)((p_midi->ep_in != 0 ? 1:0) + (p_midi->ep_out != 0 ? 1:0)); + desc->bInterfaceClass = TUSB_CLASS_AUDIO; + desc->bInterfaceSubClass = AUDIO_SUBCLASS_MIDI_STREAMING; + desc->bInterfaceProtocol = 0; + desc->iInterface = p_midi->iInterface; + + return true; +} + +uint8_t tuh_midi_get_tx_cable_count (uint8_t idx) { + TU_VERIFY(idx < CFG_TUH_MIDI); + midih_interface_t *p_midi = &_midi_host[idx]; + TU_VERIFY(p_midi->ep_stream.tx.ep_addr != 0, 0); + return p_midi->tx_cable_count; +} + +uint8_t tuh_midi_get_rx_cable_count (uint8_t idx) { + TU_VERIFY(idx < CFG_TUH_MIDI); + midih_interface_t *p_midi = &_midi_host[idx]; + TU_VERIFY(p_midi->ep_stream.rx.ep_addr != 0, 0); + return p_midi->rx_cable_count; +} + +uint32_t tuh_midi_read_available(uint8_t idx) { + TU_VERIFY(idx < CFG_TUH_MIDI); + midih_interface_t *p_midi = &_midi_host[idx]; + return tu_edpt_stream_read_available(&p_midi->ep_stream.rx); +} + +uint32_t tuh_midi_write_flush(uint8_t idx) { + TU_VERIFY(idx < CFG_TUH_MIDI); + midih_interface_t *p_midi = &_midi_host[idx]; + return tu_edpt_stream_write_xfer(p_midi->daddr, &p_midi->ep_stream.tx); +} + +//--------------------------------------------------------------------+ +// Packet API +//--------------------------------------------------------------------+ +uint32_t tuh_midi_packet_read_n(uint8_t idx, uint8_t* buffer, uint32_t bufsize) { + TU_VERIFY(idx < CFG_TUH_MIDI && buffer && bufsize > 0, 0); + midih_interface_t *p_midi = &_midi_host[idx]; + + uint32_t count4 = tu_min32(bufsize, tu_edpt_stream_read_available(&p_midi->ep_stream.rx)); + count4 = tu_align4(count4); // round down to multiple of 4 + TU_VERIFY(count4 > 0, 0); + return tu_edpt_stream_read(p_midi->daddr, &p_midi->ep_stream.rx, buffer, count4); +} + +uint32_t tuh_midi_packet_write_n(uint8_t idx, const uint8_t* buffer, uint32_t bufsize) { + TU_VERIFY(idx < CFG_TUH_MIDI && buffer && bufsize > 0, 0); + midih_interface_t *p_midi = &_midi_host[idx]; + + const uint32_t bufsize4 = tu_align4(bufsize); + TU_VERIFY(bufsize4 > 0, 0); + return tu_edpt_stream_write(p_midi->daddr, &p_midi->ep_stream.tx, buffer, bufsize4); +} + +//--------------------------------------------------------------------+ +// Stream API +//--------------------------------------------------------------------+ +#if CFG_TUH_MIDI_STREAM_API +uint32_t tuh_midi_stream_write(uint8_t idx, uint8_t cable_num, uint8_t const *buffer, uint32_t bufsize) { + TU_VERIFY(idx < CFG_TUH_MIDI && buffer && bufsize > 0); + midih_interface_t *p_midi = &_midi_host[idx]; + TU_VERIFY(cable_num < p_midi->tx_cable_count); + midi_driver_stream_t *stream = &p_midi->stream_write; + + uint32_t byte_count = 0; + while ((byte_count < bufsize) && (tu_edpt_stream_write_available(p_midi->daddr, &p_midi->ep_stream.tx) >= 4)) { + uint8_t const data = buffer[byte_count]; + byte_count++; + if (data >= MIDI_STATUS_SYSREAL_TIMING_CLOCK) { + // real-time messages need to be sent right away + midi_driver_stream_t streamrt; + streamrt.buffer[0] = MIDI_CIN_SYSEX_END_1BYTE; + streamrt.buffer[1] = data; + streamrt.index = 2; + streamrt.total = 2; + uint32_t const count = tu_edpt_stream_write(p_midi->daddr, &p_midi->ep_stream.tx, streamrt.buffer, 4); + TU_ASSERT(count == 4, byte_count); // Check FIFO overflown, since we already check fifo remaining. It is probably race condition + } else if (stream->index == 0) { + //------------- New event packet -------------// + + uint8_t const msg = data >> 4; + + stream->index = 2; + stream->buffer[1] = data; + + // Check to see if we're still in a SysEx transmit. + if (stream->buffer[0] == MIDI_CIN_SYSEX_START) { + if (data == MIDI_STATUS_SYSEX_END) { + stream->buffer[0] = MIDI_CIN_SYSEX_END_1BYTE; + stream->total = 2; + } else { + stream->total = 4; + } + } else if ((msg >= 0x8 && msg <= 0xB) || msg == 0xE) { + // Channel Voice Messages + stream->buffer[0] = (uint8_t) ((cable_num << 4) | msg); + stream->total = 4; + } else if (msg == 0xC || msg == 0xD) { + // Channel Voice Messages, two-byte variants (Program Change and Channel Pressure) + stream->buffer[0] = (uint8_t) ((cable_num << 4) | msg); + stream->total = 3; + } else if (msg == 0xf) { + // System message + if (data == MIDI_STATUS_SYSEX_START) { + stream->buffer[0] = MIDI_CIN_SYSEX_START; + stream->total = 4; + } else if (data == MIDI_STATUS_SYSCOM_TIME_CODE_QUARTER_FRAME || data == MIDI_STATUS_SYSCOM_SONG_SELECT) { + stream->buffer[0] = MIDI_CIN_SYSCOM_2BYTE; + stream->total = 3; + } else if (data == MIDI_STATUS_SYSCOM_SONG_POSITION_POINTER) { + stream->buffer[0] = MIDI_CIN_SYSCOM_3BYTE; + stream->total = 4; + } else { + stream->buffer[0] = MIDI_CIN_SYSEX_END_1BYTE; + stream->total = 2; + } + } else { + // Pack individual bytes if we don't support packing them into words. + stream->buffer[0] = (uint8_t) (cable_num << 4 | 0xf); + stream->buffer[2] = 0; + stream->buffer[3] = 0; + stream->index = 2; + stream->total = 2; + } + } else { + //------------- On-going (buffering) packet -------------// + TU_ASSERT(stream->index < 4, byte_count); + stream->buffer[stream->index] = data; + stream->index++; + // See if this byte ends a SysEx. + if (stream->buffer[0] == MIDI_CIN_SYSEX_START && data == MIDI_STATUS_SYSEX_END) { + stream->buffer[0] = MIDI_CIN_SYSEX_START + (stream->index - 1); + stream->total = stream->index; + } + } + + // Send out packet + if (stream->index >= 2 && stream->index == stream->total) { + // zeroes unused bytes + for (uint8_t i = stream->total; i < 4; i++) { + stream->buffer[i] = 0; + } + TU_LOG3_MEM(stream->buffer, 4, 2); + + const uint32_t count = tu_edpt_stream_write(p_midi->daddr, &p_midi->ep_stream.tx, stream->buffer, 4); + + // complete current event packet, reset stream + stream->index = 0; + stream->total = 0; + + // FIFO overflown, since we already check fifo remaining. It is probably race condition + TU_ASSERT(count == 4, byte_count); + } + } + return byte_count; +} + +uint32_t tuh_midi_stream_read(uint8_t idx, uint8_t *p_cable_num, uint8_t *p_buffer, uint16_t bufsize) { + TU_VERIFY(idx < CFG_TUH_MIDI && p_cable_num && p_buffer && bufsize > 0); + midih_interface_t *p_midi = &_midi_host[idx]; + uint32_t bytes_buffered = 0; + uint8_t one_byte; + if (!tu_edpt_stream_peek(&p_midi->ep_stream.rx, &one_byte)) { + return 0; + } + *p_cable_num = (one_byte >> 4) & 0xf; + uint32_t nread = tu_edpt_stream_read(p_midi->daddr, &p_midi->ep_stream.rx, p_midi->stream_read.buffer, 4); + static uint16_t cable_sysex_in_progress;// bit i is set if received MIDI_STATUS_SYSEX_START but not MIDI_STATUS_SYSEX_END + while (nread == 4 && bytes_buffered < bufsize) { + *p_cable_num = (p_midi->stream_read.buffer[0] >> 4) & 0x0f; + uint8_t bytes_to_add_to_stream = 0; + if (*p_cable_num < p_midi->rx_cable_count) { + // ignore the CIN field; too many devices out there encode this wrong + uint8_t status = p_midi->stream_read.buffer[1]; + uint16_t cable_mask = (uint16_t) (1 << *p_cable_num); + if (status <= MIDI_MAX_DATA_VAL || status == MIDI_STATUS_SYSEX_START) { + if (status == MIDI_STATUS_SYSEX_START) { + cable_sysex_in_progress |= cable_mask; + } + // only add the packet if a sysex message is in progress + if (cable_sysex_in_progress & cable_mask) { + ++bytes_to_add_to_stream; + for (uint8_t i = 2; i < 4; i++) { + if (p_midi->stream_read.buffer[i] <= MIDI_MAX_DATA_VAL) { + ++bytes_to_add_to_stream; + } else if (p_midi->stream_read.buffer[i] == MIDI_STATUS_SYSEX_END) { + ++bytes_to_add_to_stream; + cable_sysex_in_progress &= (uint16_t) ~cable_mask; + i = 4;// force the loop to exit; I hate break statements in loops + } + } + } + } else if (status < MIDI_STATUS_SYSEX_START) { + // then it is a channel message either three bytes or two + uint8_t fake_cin = (status & 0xf0) >> 4; + switch (fake_cin) { + case MIDI_CIN_NOTE_OFF: + case MIDI_CIN_NOTE_ON: + case MIDI_CIN_POLY_KEYPRESS: + case MIDI_CIN_CONTROL_CHANGE: + case MIDI_CIN_PITCH_BEND_CHANGE: + bytes_to_add_to_stream = 3; + break; + case MIDI_CIN_PROGRAM_CHANGE: + case MIDI_CIN_CHANNEL_PRESSURE: + bytes_to_add_to_stream = 2; + break; + default: + break;// Should not get this + } + cable_sysex_in_progress &= (uint16_t) ~cable_mask; + } else if (status < MIDI_STATUS_SYSREAL_TIMING_CLOCK) { + switch (status) { + case MIDI_STATUS_SYSCOM_TIME_CODE_QUARTER_FRAME: + case MIDI_STATUS_SYSCOM_SONG_SELECT: + bytes_to_add_to_stream = 2; + break; + case MIDI_STATUS_SYSCOM_SONG_POSITION_POINTER: + bytes_to_add_to_stream = 3; + break; + case MIDI_STATUS_SYSCOM_TUNE_REQUEST: + case MIDI_STATUS_SYSEX_END: + bytes_to_add_to_stream = 1; + break; + default: + break; + } + cable_sysex_in_progress &= (uint16_t) ~cable_mask; + } else { + // Real-time message: can be inserted into a sysex message, + // so do don't clear cable_sysex_in_progress bit + bytes_to_add_to_stream = 1; + } + } + + for (uint8_t i = 1; i <= bytes_to_add_to_stream; i++) { + *p_buffer++ = p_midi->stream_read.buffer[i]; + } + bytes_buffered += bytes_to_add_to_stream; + nread = 0; + if (tu_edpt_stream_peek(&p_midi->ep_stream.rx, &one_byte)) { + uint8_t new_cable = (one_byte >> 4) & 0xf; + if (new_cable == *p_cable_num) { + // still on the same cable. Continue reading the stream + nread = tu_edpt_stream_read(p_midi->daddr, &p_midi->ep_stream.rx, p_midi->stream_read.buffer, 4); + } + } + } + + return bytes_buffered; +} +#endif + +#endif diff --git a/src/class/midi/midi_host.h b/src/class/midi/midi_host.h new file mode 100644 index 000000000..06554a03d --- /dev/null +++ b/src/class/midi/midi_host.h @@ -0,0 +1,193 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * This file is part of the TinyUSB stack. + */ + +#ifndef TUSB_MIDI_HOST_H_ +#define TUSB_MIDI_HOST_H_ + +#include "class/audio/audio.h" +#include "midi.h" + +#ifdef __cplusplus + extern "C" { +#endif + +//--------------------------------------------------------------------+ +// Class Driver Configuration +//--------------------------------------------------------------------+ +#ifndef CFG_TUH_MIDI_RX_BUFSIZE +#define CFG_TUH_MIDI_RX_BUFSIZE TUH_EPSIZE_BULK_MPS +#endif + +#ifndef CFG_TUH_MIDI_TX_BUFSIZE +#define CFG_TUH_MIDI_TX_BUFSIZE TUH_EPSIZE_BULK_MPS +#endif + +#ifndef CFG_TUH_MIDI_EP_BUFSIZE +#define CFG_TUH_MIDI_EP_BUFSIZE TUH_EPSIZE_BULK_MPS +#endif + +// Enable the MIDI stream read/write API. Some library can work with raw USB MIDI packet +// Disable this can save driver footprint. +#ifndef CFG_TUH_MIDI_STREAM_API +#define CFG_TUH_MIDI_STREAM_API 1 +#endif + +//--------------------------------------------------------------------+ +// Application Types +//--------------------------------------------------------------------+ +typedef struct { + const tusb_desc_interface_t* desc_audio_control; + const tusb_desc_interface_t* desc_midi; // start of whole midi interface descriptor + uint16_t desc_midi_total_len; + + const uint8_t* desc_header; + const uint8_t* desc_element; + const tusb_desc_endpoint_t* desc_epin; // endpoint IN descriptor, CS_ENDPOINT is right after + const tusb_desc_endpoint_t* desc_epout; // endpoint OUT descriptor, CS_ENDPOINT is right after + + uint8_t jack_num; + const uint8_t* desc_jack[32]; // list of jack descriptors (embedded + external) +} tuh_midi_descriptor_cb_t; + +typedef struct { + uint8_t daddr; + uint8_t bInterfaceNumber; // interface number of MIDI streaming + uint8_t rx_cable_count; + uint8_t tx_cable_count; +} tuh_midi_mount_cb_t; + +//--------------------------------------------------------------------+ +// Application API +//--------------------------------------------------------------------+ + +// Check if MIDI interface is mounted +bool tuh_midi_mounted(uint8_t idx); + +// Get Interface index from device address + interface number +// return TUSB_INDEX_INVALID_8 (0xFF) if not found +uint8_t tuh_midi_itf_get_index(uint8_t daddr, uint8_t itf_num); + +// Get Interface information +// return true if index is correct and interface is currently mounted +bool tuh_midi_itf_get_info(uint8_t idx, tuh_itf_info_t* info); + +// return the number of virtual midi cables on the device's IN endpoint +uint8_t tuh_midi_get_rx_cable_count(uint8_t idx); + +// return the number of virtual midi cables on the device's OUT endpoint +uint8_t tuh_midi_get_tx_cable_count(uint8_t idx); + +// return the raw number of bytes available. +// Note: this is related but not the same as number of stream bytes available. +uint32_t tuh_midi_read_available(uint8_t idx); + +// Send any queued packets to the device if the host hardware is able to do it +// Returns the number of bytes flushed to the host hardware or 0 if +// the host hardware is busy or there is nothing in queue to send. +uint32_t tuh_midi_write_flush(uint8_t idx); + +//--------------------------------------------------------------------+ +// Packet API +//--------------------------------------------------------------------+ + +// Read all available MIDI packets from the connected device +// Return number of bytes read (always multiple of 4) +uint32_t tuh_midi_packet_read_n(uint8_t idx, uint8_t* buffer, uint32_t bufsize); + +// Read a raw MIDI packet from the connected device +// Return true if a packet was returned +TU_ATTR_ALWAYS_INLINE static inline +bool tuh_midi_packet_read (uint8_t idx, uint8_t packet[4]) { + return 4 == tuh_midi_packet_read_n(idx, packet, 4); +} + +// Write all 4-byte packets, data is locally buffered and only transferred when buffered bytes +// reach the endpoint packet size or tuh_midi_write_flush() is called +uint32_t tuh_midi_packet_write_n(uint8_t idx, const uint8_t* buffer, uint32_t bufsize); + +// Write a 4-bytes packet to the device. +// Returns true if the packet was successfully queued. +TU_ATTR_ALWAYS_INLINE static inline +bool tuh_midi_packet_write (uint8_t idx, uint8_t const packet[4]) { + return 4 == tuh_midi_packet_write_n(idx, packet, 4); +} + +//--------------------------------------------------------------------+ +// Stream API +//--------------------------------------------------------------------+ +#if CFG_TUH_MIDI_STREAM_API + +// Queue a message to the device using stream API. data is locally buffered and only transferred when buffered bytes +// reach the endpoint packet size or tuh_midi_write_flush() is called +// Returns number of bytes was successfully queued. +uint32_t tuh_midi_stream_write(uint8_t idx, uint8_t cable_num, uint8_t const *p_buffer, uint32_t bufsize); + +// Get the MIDI stream from the device. Set the value pointed +// to by p_cable_num to the MIDI cable number intended to receive it. +// The MIDI stream will be stored in the buffer pointed to by p_buffer. +// Return the number of bytes added to the buffer. +// Note that this function ignores the CIN field of the MIDI packet +// because a number of commercial devices out there do not encode +// it properly. +uint32_t tuh_midi_stream_read(uint8_t idx, uint8_t *p_cable_num, uint8_t *p_buffer, uint16_t bufsize); + +#endif + +//--------------------------------------------------------------------+ +// Callbacks (Weak is optional) +//--------------------------------------------------------------------+ + +// Invoked when MIDI interface is detected in enumeration. Application can copy/parse descriptor if needed. +// Note: may be fired before tuh_midi_mount_cb(), therefore midi interface is not mounted/ready. +void tuh_midi_descriptor_cb(uint8_t idx, const tuh_midi_descriptor_cb_t * desc_cb_data); + +// Invoked when device with MIDI interface is mounted. +void tuh_midi_mount_cb(uint8_t idx, const tuh_midi_mount_cb_t* mount_cb_data); + +// Invoked when device with MIDI interface is un-mounted +void tuh_midi_umount_cb(uint8_t idx); + +// Invoked when received new data +void tuh_midi_rx_cb(uint8_t idx, uint32_t xferred_bytes); + +// Invoked when a TX is complete and therefore space becomes available in TX buffer +void tuh_midi_tx_cb(uint8_t idx, uint32_t xferred_bytes); + +//--------------------------------------------------------------------+ +// Internal Class Driver API +//--------------------------------------------------------------------+ +bool midih_init (void); +bool midih_deinit (void); +bool midih_open (uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const *desc_itf, uint16_t max_len); +bool midih_set_config (uint8_t dev_addr, uint8_t itf_num); +bool midih_xfer_cb (uint8_t dev_addr, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes); +void midih_close (uint8_t daddr); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/class/msc/msc_device.c b/src/class/msc/msc_device.c index dd66bfb6f..747ad03ed 100644 --- a/src/class/msc/msc_device.c +++ b/src/class/msc/msc_device.c @@ -53,23 +53,26 @@ enum { }; typedef struct { - TU_ATTR_ALIGNED(4) msc_cbw_t cbw; - TU_ATTR_ALIGNED(4) msc_csw_t csw; + TU_ATTR_ALIGNED(4) msc_cbw_t cbw; // 31 bytes + uint8_t rhport; + TU_ATTR_ALIGNED(4) msc_csw_t csw; // 13 bytes uint8_t itf_num; uint8_t ep_in; uint8_t ep_out; - // Bulk Only Transfer (BOT) Protocol - uint8_t stage; - uint32_t total_len; // byte to be transferred, can be smaller than total_bytes in cbw uint32_t xferred_len; // numbered of bytes transferred so far in the Data Stage - // Sense Response Data + // Bulk Only Transfer (BOT) Protocol + uint8_t stage; + + // SCSI Sense Response Data uint8_t sense_key; uint8_t add_sense_code; uint8_t add_sense_qualifier; + + uint8_t pending_io; // pending async IO }mscd_interface_t; static mscd_interface_t _mscd_itf; @@ -82,31 +85,36 @@ CFG_TUD_MEM_SECTION static struct { // INTERNAL OBJECT & FUNCTION DECLARATION //--------------------------------------------------------------------+ static int32_t proc_builtin_scsi(uint8_t lun, uint8_t const scsi_cmd[16], uint8_t* buffer, uint32_t bufsize); -static void proc_read10_cmd(uint8_t rhport, mscd_interface_t* p_msc); - -static void proc_write10_cmd(uint8_t rhport, mscd_interface_t* p_msc); -static void proc_write10_new_data(uint8_t rhport, mscd_interface_t* p_msc, uint32_t xferred_bytes); +static void proc_read10_cmd(mscd_interface_t* p_msc); +static void proc_read_io_data(mscd_interface_t* p_msc, int32_t nbytes); +static void proc_write10_cmd(mscd_interface_t* p_msc); +static void proc_write10_host_data(mscd_interface_t* p_msc, uint32_t xferred_bytes); +static void proc_write_io_data(mscd_interface_t* p_msc, uint32_t xferred_bytes, int32_t nbytes); +static bool proc_stage_status(mscd_interface_t* p_msc); TU_ATTR_ALWAYS_INLINE static inline bool is_data_in(uint8_t dir) { return tu_bit_test(dir, 7); } -static inline bool send_csw(uint8_t rhport, mscd_interface_t* p_msc) { +static inline bool send_csw(mscd_interface_t* p_msc) { // Data residue is always = host expect - actual transferred + uint8_t rhport = p_msc->rhport; p_msc->csw.data_residue = p_msc->cbw.total_bytes - p_msc->xferred_len; p_msc->stage = MSC_STAGE_STATUS_SENT; memcpy(_mscd_epbuf.buf, &p_msc->csw, sizeof(msc_csw_t)); return usbd_edpt_xfer(rhport, p_msc->ep_in , _mscd_epbuf.buf, sizeof(msc_csw_t)); } -static inline bool prepare_cbw(uint8_t rhport, mscd_interface_t* p_msc) { +static inline bool prepare_cbw(mscd_interface_t* p_msc) { + uint8_t rhport = p_msc->rhport; p_msc->stage = MSC_STAGE_CMD; return usbd_edpt_xfer(rhport, p_msc->ep_out, _mscd_epbuf.buf, sizeof(msc_cbw_t)); } -static void fail_scsi_op(uint8_t rhport, mscd_interface_t* p_msc, uint8_t status) { +static void fail_scsi_op(mscd_interface_t* p_msc, uint8_t status) { msc_cbw_t const * p_cbw = &p_msc->cbw; msc_csw_t * p_csw = &p_msc->csw; + uint8_t rhport = p_msc->rhport; p_csw->status = status; p_csw->data_residue = p_msc->cbw.total_bytes - p_msc->xferred_len; @@ -177,6 +185,33 @@ static uint8_t rdwr10_validate_cmd(msc_cbw_t const* cbw) { return status; } +static bool proc_stage_status(mscd_interface_t *p_msc) { + uint8_t rhport = p_msc->rhport; + msc_cbw_t const *p_cbw = &p_msc->cbw; + + // skip status if epin is currently stalled, will do it when received Clear Stall request + if (!usbd_edpt_stalled(rhport, p_msc->ep_in)) { + if ((p_cbw->total_bytes > p_msc->xferred_len) && is_data_in(p_cbw->dir)) { + // 6.7 The 13 Cases: case 5 (Hi > Di): STALL before status + // TU_LOG_DRV(" SCSI case 5 (Hi > Di): %lu > %lu\r\n", p_cbw->total_bytes, p_msc->xferred_len); + usbd_edpt_stall(rhport, p_msc->ep_in); + } else { + TU_ASSERT(send_csw(p_msc)); + } + } + + #if TU_CHECK_MCU(OPT_MCU_CXD56) + // WORKAROUND: cxd56 has its own nuttx usb stack which does not forward Set/ClearFeature(Endpoint) to DCD. + // There is no way for us to know when EP is un-stall, therefore we will unconditionally un-stall here and + // hope everything will work + if (usbd_edpt_stalled(rhport, p_msc->ep_in)) { + usbd_edpt_clear_stall(rhport, p_msc->ep_in); + send_csw(p_msc); + } + #endif + return true; +} + //--------------------------------------------------------------------+ // Debug //--------------------------------------------------------------------+ @@ -214,15 +249,51 @@ bool tud_msc_set_sense(uint8_t lun, uint8_t sense_key, uint8_t add_sense_code, u return true; } -static inline void set_sense_medium_not_present(uint8_t lun) { +TU_ATTR_ALWAYS_INLINE static inline void set_sense_medium_not_present(uint8_t lun) { // default sense is NOT READY, MEDIUM NOT PRESENT tud_msc_set_sense(lun, SCSI_SENSE_NOT_READY, 0x3A, 0x00); } +static void proc_async_io_done(void *bytes_io) { + mscd_interface_t *p_msc = &_mscd_itf; + TU_VERIFY(p_msc->pending_io, ); + const int32_t nbytes = (int32_t) (intptr_t) bytes_io; + const uint8_t cmd = p_msc->cbw.command[0]; + + p_msc->pending_io = 0; + switch (cmd) { + case SCSI_CMD_READ_10: + proc_read_io_data(p_msc, nbytes); + break; + + case SCSI_CMD_WRITE_10: + proc_write_io_data(p_msc, (uint32_t) nbytes, nbytes); + break; + + default: break; + } + + // send status if stage is transitioned to STATUS + if (p_msc->stage == MSC_STAGE_STATUS) { + proc_stage_status(p_msc); + } +} + +bool tud_msc_async_io_done(int32_t bytes_io, bool in_isr) { + // Precheck to avoid queueing multiple RW done callback + TU_VERIFY(_mscd_itf.pending_io); + if (bytes_io == 0) { + bytes_io = TUD_MSC_RET_ERROR; // 0 is treated as error, no reason to call this with BUSY here + } + usbd_defer_func(proc_async_io_done, (void *) (intptr_t) bytes_io, in_isr); + return true; +} + //--------------------------------------------------------------------+ // USBD Driver API //--------------------------------------------------------------------+ void mscd_init(void) { + TU_LOG_INT(CFG_TUD_MSC_LOG_LEVEL, sizeof(mscd_interface_t)); tu_memclr(&_mscd_itf, sizeof(mscd_interface_t)); } @@ -245,12 +316,13 @@ uint16_t mscd_open(uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint1 mscd_interface_t * p_msc = &_mscd_itf; p_msc->itf_num = itf_desc->bInterfaceNumber; + p_msc->rhport = rhport; // Open endpoint pair TU_ASSERT(usbd_open_edpt_pair(rhport, tu_desc_next(itf_desc), 2, TUSB_XFER_BULK, &p_msc->ep_out, &p_msc->ep_in), 0); // Prepare for Command Block Wrapper - TU_ASSERT(prepare_cbw(rhport, p_msc), drv_len); + TU_ASSERT(prepare_cbw(p_msc), drv_len); return drv_len; } @@ -289,14 +361,14 @@ bool mscd_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb_control_request_t if (ep_addr == p_msc->ep_in) { if (p_msc->stage == MSC_STAGE_STATUS) { // resume sending SCSI status if we are in this stage previously before stalled - TU_ASSERT(send_csw(rhport, p_msc)); + TU_ASSERT(send_csw(p_msc)); } } else if (ep_addr == p_msc->ep_out) { if (p_msc->stage == MSC_STAGE_CMD) { // part of reset recovery (probably due to invalid CBW) -> prepare for new command // Note: skip if already queued previously if (usbd_edpt_ready(rhport, p_msc->ep_out)) { - TU_ASSERT(prepare_cbw(rhport, p_msc)); + TU_ASSERT(prepare_cbw(p_msc)); } } } @@ -344,7 +416,7 @@ bool mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t msc_csw_t * p_csw = &p_msc->csw; switch (p_msc->stage) { - case MSC_STAGE_CMD: + case MSC_STAGE_CMD: { //------------- new CBW received -------------// // Complete IN while waiting for CMD is usually Status of previous SCSI op, ignore it if (ep_addr != p_msc->ep_out) { @@ -365,7 +437,7 @@ bool mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t memcpy(p_cbw, _mscd_epbuf.buf, sizeof(msc_cbw_t)); TU_LOG_DRV(" SCSI Command [Lun%u]: %s\r\n", p_cbw->lun, tu_lookup_find(&_msc_scsi_cmd_table, p_cbw->command[0])); - //TU_LOG_MEM(MSC_DEBUG, p_cbw, xferred_bytes, 2); + // TU_LOG_MEM(CFG_TUD_MSC_LOG_LEVEL, p_cbw, xferred_bytes, 2); p_csw->signature = MSC_CSW_SIGNATURE; p_csw->tag = p_cbw->tag; @@ -382,12 +454,12 @@ bool mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t uint8_t const status = rdwr10_validate_cmd(p_cbw); if (status != MSC_CSW_STATUS_PASSED) { - fail_scsi_op(rhport, p_msc, status); + fail_scsi_op(p_msc, status); } else if (p_cbw->total_bytes) { if (SCSI_CMD_READ_10 == p_cbw->command[0]) { - proc_read10_cmd(rhport, p_msc); + proc_read10_cmd(p_msc); } else { - proc_write10_cmd(rhport, p_msc); + proc_write10_cmd(p_msc); } } else { // no data transfer, only exist in complaint test suite @@ -400,7 +472,7 @@ bool mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t if ((p_cbw->total_bytes > 0) && !is_data_in(p_cbw->dir)) { if (p_cbw->total_bytes > CFG_TUD_MSC_EP_BUFSIZE) { TU_LOG_DRV(" SCSI reject non READ10/WRITE10 with large data\r\n"); - fail_scsi_op(rhport, p_msc, MSC_CSW_STATUS_FAILED); + fail_scsi_op(p_msc, MSC_CSW_STATUS_FAILED); } else { // Didn't check for case 9 (Ho > Dn), which requires examining scsi command first // but it is OK to just receive data then responded with failed status @@ -418,12 +490,12 @@ bool mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t if (resplen < 0) { // unsupported command TU_LOG_DRV(" SCSI unsupported or failed command\r\n"); - fail_scsi_op(rhport, p_msc, MSC_CSW_STATUS_FAILED); + fail_scsi_op(p_msc, MSC_CSW_STATUS_FAILED); } else if (resplen == 0) { if (p_cbw->total_bytes) { // 6.7 The 13 Cases: case 4 (Hi > Dn) - // TU_LOG(MSC_DEBUG, " SCSI case 4 (Hi > Dn): %lu\r\n", p_cbw->total_bytes); - fail_scsi_op(rhport, p_msc, MSC_CSW_STATUS_FAILED); + // TU_LOG_DRV(" SCSI case 4 (Hi > Dn): %lu\r\n", p_cbw->total_bytes); + fail_scsi_op(p_msc, MSC_CSW_STATUS_FAILED); } else { // case 1 Hn = Dn: all good p_msc->stage = MSC_STAGE_STATUS; @@ -431,8 +503,8 @@ bool mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t } else { if (p_cbw->total_bytes == 0) { // 6.7 The 13 Cases: case 2 (Hn < Di) - // TU_LOG(MSC_DEBUG, " SCSI case 2 (Hn < Di): %lu\r\n", p_cbw->total_bytes); - fail_scsi_op(rhport, p_msc, MSC_CSW_STATUS_FAILED); + // TU_LOG_DRV(" SCSI case 2 (Hn < Di): %lu\r\n", p_cbw->total_bytes); + fail_scsi_op(p_msc, MSC_CSW_STATUS_FAILED); } else { // cannot return more than host expect p_msc->total_len = tu_min32((uint32_t)resplen, p_cbw->total_bytes); @@ -441,11 +513,13 @@ bool mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t } } } - break; + break; + } case MSC_STAGE_DATA: TU_LOG_DRV(" SCSI Data [Lun%u]\r\n", p_cbw->lun); - //TU_LOG_MEM(MSC_DEBUG, _mscd_epbuf.buf, xferred_bytes, 2); + TU_ASSERT(xferred_bytes <= CFG_TUD_MSC_EP_BUFSIZE); // sanity check to avoid buffer overflow + // TU_LOG_MEM(CFG_TUD_MSC_LOG_LEVEL, _mscd_epbuf.buf, xferred_bytes, 2); if (SCSI_CMD_READ_10 == p_cbw->command[0]) { p_msc->xferred_len += xferred_bytes; @@ -454,10 +528,10 @@ bool mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t // Data Stage is complete p_msc->stage = MSC_STAGE_STATUS; }else { - proc_read10_cmd(rhport, p_msc); + proc_read10_cmd(p_msc); } } else if (SCSI_CMD_WRITE_10 == p_cbw->command[0]) { - proc_write10_new_data(rhport, p_msc, xferred_bytes); + proc_write10_host_data(p_msc, xferred_bytes); } else { p_msc->xferred_len += xferred_bytes; @@ -468,7 +542,7 @@ bool mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t if ( cb_result < 0 ) { // unsupported command TU_LOG_DRV(" SCSI unsupported command\r\n"); - fail_scsi_op(rhport, p_msc, MSC_CSW_STATUS_FAILED); + fail_scsi_op(p_msc, MSC_CSW_STATUS_FAILED); }else { // TODO haven't implement this scenario any further yet } @@ -489,10 +563,10 @@ bool mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t break; case MSC_STAGE_STATUS_SENT: - // Wait for the Status phase to complete + // Status phase is complete if ((ep_addr == p_msc->ep_in) && (xferred_bytes == sizeof(msc_csw_t))) { TU_LOG_DRV(" SCSI Status [Lun%u] = %u\r\n", p_cbw->lun, p_csw->status); - // TU_LOG_MEM(MSC_DEBUG, p_csw, xferred_bytes, 2); + // TU_LOG_MEM(CFG_TUD_MSC_LOG_LEVEL, p_csw, xferred_bytes, 2); // Invoke complete callback if defined // Note: There is racing issue with samd51 + qspi flash testing with arduino @@ -517,9 +591,9 @@ bool mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t break; } - TU_ASSERT(prepare_cbw(rhport, p_msc)); + TU_ASSERT(prepare_cbw(p_msc)); } else { - // Any xfer ended here is consider unknown error, ignore it + // Any xfer ended here is considered unknown error, ignore it TU_LOG1(" Warning expect SCSI Status but received unknown data\r\n"); } break; @@ -528,26 +602,7 @@ bool mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t } if (p_msc->stage == MSC_STAGE_STATUS) { - // skip status if epin is currently stalled, will do it when received Clear Stall request - if (!usbd_edpt_stalled(rhport, p_msc->ep_in)) { - if ((p_cbw->total_bytes > p_msc->xferred_len) && is_data_in(p_cbw->dir)) { - // 6.7 The 13 Cases: case 5 (Hi > Di): STALL before status - // TU_LOG(MSC_DEBUG, " SCSI case 5 (Hi > Di): %lu > %lu\r\n", p_cbw->total_bytes, p_msc->xferred_len); - usbd_edpt_stall(rhport, p_msc->ep_in); - } else { - TU_ASSERT(send_csw(rhport, p_msc)); - } - } - - #if TU_CHECK_MCU(OPT_MCU_CXD56) - // WORKAROUND: cxd56 has its own nuttx usb stack which does not forward Set/ClearFeature(Endpoint) to DCD. - // There is no way for us to know when EP is un-stall, therefore we will unconditionally un-stall here and - // hope everything will work - if ( usbd_edpt_stalled(rhport, p_msc->ep_in) ) { - usbd_edpt_clear_stall(rhport, p_msc->ep_in); - send_csw(rhport, p_msc); - } - #endif + TU_ASSERT(proc_stage_status(p_msc)); } return true; @@ -644,8 +699,7 @@ static int32_t proc_builtin_scsi(uint8_t lun, uint8_t const scsi_cmd[16], uint8_ break; case SCSI_CMD_READ_FORMAT_CAPACITY: { - scsi_read_format_capacity_data_t read_fmt_capa = - { + scsi_read_format_capacity_data_t read_fmt_capa = { .list_length = 8, .block_num = 0, .descriptor_type = 2, // formatted media @@ -677,8 +731,7 @@ static int32_t proc_builtin_scsi(uint8_t lun, uint8_t const scsi_cmd[16], uint8_ break; case SCSI_CMD_INQUIRY: { - scsi_inquiry_resp_t inquiry_rsp = - { + scsi_inquiry_resp_t inquiry_rsp = { .is_removable = 1, .version = 2, .response_data_format = 2, @@ -698,8 +751,7 @@ static int32_t proc_builtin_scsi(uint8_t lun, uint8_t const scsi_cmd[16], uint8_ break; case SCSI_CMD_MODE_SENSE_6: { - scsi_mode_sense6_resp_t mode_resp = - { + scsi_mode_sense6_resp_t mode_resp = { .data_len = 3, .medium_type = 0, .write_protected = false, @@ -720,8 +772,7 @@ static int32_t proc_builtin_scsi(uint8_t lun, uint8_t const scsi_cmd[16], uint8_ break; case SCSI_CMD_REQUEST_SENSE: { - scsi_sense_fixed_resp_t sense_rsp = - { + scsi_sense_fixed_resp_t sense_rsp = { .response_code = 0x70, // current, fixed format .valid = 1 }; @@ -751,39 +802,49 @@ static int32_t proc_builtin_scsi(uint8_t lun, uint8_t const scsi_cmd[16], uint8_ return resplen; } -static void proc_read10_cmd(uint8_t rhport, mscd_interface_t* p_msc) { +static void proc_read10_cmd(mscd_interface_t* p_msc) { msc_cbw_t const* p_cbw = &p_msc->cbw; - - // block size already verified not zero - uint16_t const block_sz = rdwr10_get_blocksize(p_cbw); - - // Adjust lba with transferred bytes + uint16_t const block_sz = rdwr10_get_blocksize(p_cbw); // already verified non-zero + // Adjust lba & offset with transferred bytes uint32_t const lba = rdwr10_get_lba(p_cbw->command) + (p_msc->xferred_len / block_sz); + uint32_t const offset = p_msc->xferred_len % block_sz; // remaining bytes capped at class buffer int32_t nbytes = (int32_t)tu_min32(CFG_TUD_MSC_EP_BUFSIZE, p_cbw->total_bytes - p_msc->xferred_len); - // Application can consume smaller bytes - uint32_t const offset = p_msc->xferred_len % block_sz; + p_msc->pending_io = 1; nbytes = tud_msc_read10_cb(p_cbw->lun, lba, offset, _mscd_epbuf.buf, (uint32_t)nbytes); - - if (nbytes < 0) { - // negative means error -> endpoint is stalled & status in CSW set to failed - TU_LOG_DRV(" tud_msc_read10_cb() return -1\r\n"); - - // set sense - set_sense_medium_not_present(p_cbw->lun); - - fail_scsi_op(rhport, p_msc, MSC_CSW_STATUS_FAILED); - } else if (nbytes == 0) { - // zero means not ready -> simulate an transfer complete so that this driver callback will fired again - dcd_event_xfer_complete(rhport, p_msc->ep_in, 0, XFER_RESULT_SUCCESS, false); - } else { - TU_ASSERT(usbd_edpt_xfer(rhport, p_msc->ep_in, _mscd_epbuf.buf, (uint16_t) nbytes),); + if (nbytes != TUD_MSC_RET_ASYNC) { + p_msc->pending_io = 0; + proc_read_io_data(p_msc, nbytes); } } -static void proc_write10_cmd(uint8_t rhport, mscd_interface_t* p_msc) { +static void proc_read_io_data(mscd_interface_t* p_msc, int32_t nbytes) { + const uint8_t rhport = p_msc->rhport; + if (nbytes > 0) { + TU_ASSERT(usbd_edpt_xfer(rhport, p_msc->ep_in, _mscd_epbuf.buf, (uint16_t) nbytes),); + } else { + // nbytes is status + switch (nbytes) { + case TUD_MSC_RET_ERROR: + // error -> endpoint is stalled & status in CSW set to failed + TU_LOG_DRV(" IO read() failed\r\n"); + set_sense_medium_not_present(p_msc->cbw.lun); + fail_scsi_op(p_msc, MSC_CSW_STATUS_FAILED); + break; + + case TUD_MSC_RET_BUSY: + // not ready yet -> fake a transfer complete so that this driver callback will fire again + dcd_event_xfer_complete(rhport, p_msc->ep_in, 0, XFER_RESULT_SUCCESS, false); + break; + + default: break; + } + } +} + +static void proc_write10_cmd(mscd_interface_t* p_msc) { msc_cbw_t const* p_cbw = &p_msc->cbw; bool writable = true; @@ -795,53 +856,56 @@ static void proc_write10_cmd(uint8_t rhport, mscd_interface_t* p_msc) { // Not writable, complete this SCSI op with error // Sense = Write protected tud_msc_set_sense(p_cbw->lun, SCSI_SENSE_DATA_PROTECT, 0x27, 0x00); - fail_scsi_op(rhport, p_msc, MSC_CSW_STATUS_FAILED); + fail_scsi_op(p_msc, MSC_CSW_STATUS_FAILED); return; } // remaining bytes capped at class buffer uint16_t nbytes = (uint16_t)tu_min32(CFG_TUD_MSC_EP_BUFSIZE, p_cbw->total_bytes - p_msc->xferred_len); - // Write10 callback will be called later when usb transfer complete - TU_ASSERT(usbd_edpt_xfer(rhport, p_msc->ep_out, _mscd_epbuf.buf, nbytes),); + TU_ASSERT(usbd_edpt_xfer(p_msc->rhport, p_msc->ep_out, _mscd_epbuf.buf, nbytes),); } // process new data arrived from WRITE10 -static void proc_write10_new_data(uint8_t rhport, mscd_interface_t* p_msc, uint32_t xferred_bytes) { +static void proc_write10_host_data(mscd_interface_t* p_msc, uint32_t xferred_bytes) { msc_cbw_t const* p_cbw = &p_msc->cbw; + uint16_t const block_sz = rdwr10_get_blocksize(p_cbw); // already verified non-zero - // block size already verified not zero - uint16_t const block_sz = rdwr10_get_blocksize(p_cbw); - - // Adjust lba with transferred bytes + // Adjust lba & offset with transferred bytes uint32_t const lba = rdwr10_get_lba(p_cbw->command) + (p_msc->xferred_len / block_sz); - - // Invoke callback to consume new data uint32_t const offset = p_msc->xferred_len % block_sz; - int32_t nbytes = tud_msc_write10_cb(p_cbw->lun, lba, offset, _mscd_epbuf.buf, xferred_bytes); + p_msc->pending_io = 1; + int32_t nbytes = tud_msc_write10_cb(p_cbw->lun, lba, offset, _mscd_epbuf.buf, xferred_bytes); + if (nbytes != TUD_MSC_RET_ASYNC) { + p_msc->pending_io = 0; + proc_write_io_data(p_msc, xferred_bytes, nbytes); + } +} + +static void proc_write_io_data(mscd_interface_t* p_msc, uint32_t xferred_bytes, int32_t nbytes) { if (nbytes < 0) { - // negative means error -> failed this scsi op - TU_LOG_DRV(" tud_msc_write10_cb() return -1\r\n"); + // nbytes is status + switch (nbytes) { + case TUD_MSC_RET_ERROR: + // IO error -> failed this scsi op + TU_LOG_DRV(" IO write() failed\r\n"); + set_sense_medium_not_present(p_msc->cbw.lun); + fail_scsi_op(p_msc, MSC_CSW_STATUS_FAILED); + break; - // update actual byte before failed - p_msc->xferred_len += xferred_bytes; - - // Set sense - set_sense_medium_not_present(p_cbw->lun); - - fail_scsi_op(rhport, p_msc, MSC_CSW_STATUS_FAILED); + default: break; + } } else { - // Application consume less than what we got (including zero) if ((uint32_t)nbytes < xferred_bytes) { - uint32_t const left_over = xferred_bytes - (uint32_t)nbytes; + // Application consume less than what we got including TUD_MSC_RET_BUSY (0) + const uint32_t left_over = xferred_bytes - (uint32_t)nbytes; if (nbytes > 0) { - p_msc->xferred_len += (uint16_t)nbytes; memmove(_mscd_epbuf.buf, _mscd_epbuf.buf + nbytes, left_over); } - // simulate an transfer complete with adjusted parameters --> callback will be invoked with adjusted parameter - dcd_event_xfer_complete(rhport, p_msc->ep_out, left_over, XFER_RESULT_SUCCESS, false); + // fake a transfer complete with adjusted parameters --> callback will be invoked with adjusted parameters + dcd_event_xfer_complete(p_msc->rhport, p_msc->ep_out, left_over, XFER_RESULT_SUCCESS, false); } else { // Application consume all bytes in our buffer p_msc->xferred_len += xferred_bytes; @@ -851,7 +915,7 @@ static void proc_write10_new_data(uint8_t rhport, mscd_interface_t* p_msc, uint3 p_msc->stage = MSC_STAGE_STATUS; } else { // prepare to receive more data from host - proc_write10_cmd(rhport, p_msc); + proc_write10_cmd(p_msc); } } } diff --git a/src/class/msc/msc_device.h b/src/class/msc/msc_device.h index 29acd280a..f2ea256b4 100644 --- a/src/class/msc/msc_device.h +++ b/src/class/msc/msc_device.h @@ -48,6 +48,13 @@ #error CFG_TUD_MSC_EP_BUFSIZE must be defined, value of a block size should work well, the more the better #endif +// Return value of callback functions +enum { + TUD_MSC_RET_BUSY = 0, // Busy, e.g disk I/O is not ready + TUD_MSC_RET_ERROR = -1, + TUD_MSC_RET_ASYNC = -2, // Asynchronous IO +}; + TU_VERIFY_STATIC(CFG_TUD_MSC_EP_BUFSIZE < UINT16_MAX, "Size is not correct"); //--------------------------------------------------------------------+ @@ -57,38 +64,30 @@ TU_VERIFY_STATIC(CFG_TUD_MSC_EP_BUFSIZE < UINT16_MAX, "Size is not correct"); // Set SCSI sense response bool tud_msc_set_sense(uint8_t lun, uint8_t sense_key, uint8_t add_sense_code, uint8_t add_sense_qualifier); +// Called by Application once asynchronous I/O operation is done +// bytes_io is number of bytes in I/O op, typically the bufsize in read/write_cb() or +// TUD_MSC_RET_ERROR (-1) for error. Note TUD_MSC_RET_BUSY (0) will be treated as error as well. +bool tud_msc_async_io_done(int32_t bytes_io, bool in_isr); + //--------------------------------------------------------------------+ // Application Callbacks (WEAK is optional) //--------------------------------------------------------------------+ -// Invoked when received SCSI READ10 command -// - Address = lba * BLOCK_SIZE + offset -// - offset is only needed if CFG_TUD_MSC_EP_BUFSIZE is smaller than BLOCK_SIZE. -// -// - Application fill the buffer (up to bufsize) with address contents and return number of read byte. If -// - read < bufsize : These bytes are transferred first and callback invoked again for remaining data. -// -// - read == 0 : Indicate application is not ready yet e.g disk I/O busy. -// Callback invoked again with the same parameters later on. -// -// - read < 0 : Indicate application error e.g invalid address. This request will be STALLed -// and return failed status in command status wrapper phase. +/* + Invoked when received SCSI READ10/WRITE10 command + - Address = lba * BLOCK_SIZE + offset + - offset is only needed if CFG_TUD_MSC_EP_BUFSIZE is smaller than BLOCK_SIZE. + - Application fill the buffer (up to bufsize) with address contents and return number of bytes read or status. + - 0 < ret < bufsize: These bytes are transferred first and callback will be invoked again for remaining data. + - TUD_MSC_RET_BUSY + Application is buys e.g disk I/O not ready. Callback will be invoked again with the same parameters later on. + - TUD_MSC_RET_ERROR + error such as invalid address. This request will be STALLed and scsi command will be failed + - TUD_MSC_RET_ASYNC + Data I/O will be done asynchronously in a background task. Application should return immediately. + tud_msc_async_io_done() must be called once IO/ is done to signal completion. +*/ int32_t tud_msc_read10_cb (uint8_t lun, uint32_t lba, uint32_t offset, void* buffer, uint32_t bufsize); - -// Invoked when received SCSI WRITE10 command -// - Address = lba * BLOCK_SIZE + offset -// - offset is only needed if CFG_TUD_MSC_EP_BUFSIZE is smaller than BLOCK_SIZE. -// -// - Application write data from buffer to address contents (up to bufsize) and return number of written byte. If -// - write < bufsize : callback invoked again with remaining data later on. -// -// - write == 0 : Indicate application is not ready yet e.g disk I/O busy. -// Callback invoked again with the same parameters later on. -// -// - write < 0 : Indicate application error e.g invalid address. This request will be STALLed -// and return failed status in command status wrapper phase. -// -// TODO change buffer to const uint8_t* int32_t tud_msc_write10_cb (uint8_t lun, uint32_t lba, uint32_t offset, uint8_t* buffer, uint32_t bufsize); // Invoked when received SCSI_CMD_INQUIRY diff --git a/src/class/net/ecm_rndis_device.c b/src/class/net/ecm_rndis_device.c index a54e6d662..299eb97c8 100644 --- a/src/class/net/ecm_rndis_device.c +++ b/src/class/net/ecm_rndis_device.c @@ -81,6 +81,7 @@ typedef struct { static netd_interface_t _netd_itf; CFG_TUD_MEM_SECTION static netd_epbuf_t _netd_epbuf; static bool can_xmit; +static bool ecm_link_is_up = true; // Store link state for ECM mode void tud_network_recv_renew(void) { usbd_edpt_xfer(0, _netd_itf.ep_out, _netd_epbuf.rx, NETD_PACKET_SIZE); @@ -95,7 +96,11 @@ void netd_report(uint8_t *buf, uint16_t len) { const uint8_t rhport = 0; len = tu_min16(len, sizeof(ecm_notify_t)); - TU_VERIFY(usbd_edpt_claim(rhport, _netd_itf.ep_notif), ); + if (!usbd_edpt_claim(rhport, _netd_itf.ep_notif)) { + TU_LOG1("ECM: Failed to claim notification endpoint\n"); + return; + } + memcpy(_netd_epbuf.notify, buf, len); usbd_edpt_xfer(rhport, _netd_itf.ep_notif, _netd_epbuf.notify, len); } @@ -181,8 +186,6 @@ uint16_t netd_open(uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint1 // Open endpoint pair for RNDIS TU_ASSERT(usbd_open_edpt_pair(rhport, p_desc, 2, TUSB_XFER_BULK, &_netd_itf.ep_out, &_netd_itf.ep_in), 0); - tud_network_init_cb(); - // we are ready to transmit a packet can_xmit = true; @@ -196,11 +199,11 @@ uint16_t netd_open(uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint1 } static void ecm_report(bool nc) { - const ecm_notify_t ecm_notify_nc = { + ecm_notify_t ecm_notify_nc = { .header = { .bmRequestType = 0xA1, .bRequest = 0, /* NETWORK_CONNECTION aka NetworkConnection */ - .wValue = 1, /* Connected */ + .wValue = ecm_link_is_up ? 1 : 0, /* Use current link state */ .wLength = 0, }, }; @@ -259,7 +262,6 @@ bool netd_control_xfer_cb (uint8_t rhport, uint8_t stage, tusb_control_request_t // TODO should be merge with RNDIS's after endpoint opened // Also should have opposite callback for application to disable network !! - tud_network_init_cb(); can_xmit = true; // we are ready to transmit a packet tud_network_recv_renew(); // prepare for incoming packets } @@ -286,7 +288,10 @@ bool netd_control_xfer_cb (uint8_t rhport, uint8_t stage, tusb_control_request_t /* the only required CDC-ECM Management Element Request is SetEthernetPacketFilter */ if (0x43 /* SET_ETHERNET_PACKET_FILTER */ == request->bRequest) { tud_control_xfer(rhport, request, NULL, 0); - ecm_report(true); + // Only send connection notification if link is up + if (ecm_link_is_up) { + ecm_report(true); + } } } else { if (request->bmRequestType_bit.direction == TUSB_DIR_IN) { @@ -363,9 +368,8 @@ bool netd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_ } if (_netd_itf.ecm_mode && (ep_addr == _netd_itf.ep_notif)) { - if (sizeof(tusb_control_request_t) == xferred_bytes) { - ecm_report(false); - } + // Notification transfer complete - endpoint is now free + // Don't automatically send speed change notification after link state changes } return true; @@ -398,4 +402,31 @@ void tud_network_xmit(void *ref, uint16_t arg) { do_in_xfer(_netd_epbuf.tx, len); } +// Set the network link state (up/down) and notify the host +void tud_network_link_state(uint8_t rhport, bool is_up) { + (void)rhport; + + if (_netd_itf.ecm_mode) { + ecm_link_is_up = is_up; + + // For ECM mode, send network connection notification only + // Don't trigger speed change notification for link state changes + ecm_notify_t notify = { + .header = { + .bmRequestType = 0xA1, + .bRequest = 0, /* NETWORK_CONNECTION */ + .wValue = is_up ? 1 : 0, /* 0 = disconnected, 1 = connected */ + .wLength = 0, + }, + }; + notify.header.wIndex = _netd_itf.itf_num; + netd_report((uint8_t *)¬ify, sizeof(notify.header)); + } else { + // For RNDIS mode, we would need to implement RNDIS status indication + // This is more complex and requires RNDIS_INDICATE_STATUS_MSG + // For now, RNDIS doesn't support dynamic link state changes + (void)is_up; + } +} + #endif diff --git a/src/class/net/ncm_device.c b/src/class/net/ncm_device.c index 4e6088340..02833c5f1 100644 --- a/src/class/net/ncm_device.c +++ b/src/class/net/ncm_device.c @@ -110,6 +110,7 @@ typedef struct { NOTIFICATION_DONE } notification_xmit_state; // state of notification transmission bool notification_xmit_is_running; // notification is currently transmitted + bool link_is_up; // current link state // misc bool tud_network_recv_renew_active; // tud_network_recv_renew() is active (avoid recursive invocations) @@ -218,7 +219,7 @@ static void notification_xmit(uint8_t rhport, bool force_next) { .direction = TUSB_DIR_IN }, .bRequest = CDC_NOTIF_NETWORK_CONNECTION, - .wValue = 1 /* Connected */, + .wValue = ncm_interface.link_is_up ? 1 : 0, /* Dynamic link state */ .wIndex = ncm_interface.itf_num, .wLength = 0, }, @@ -232,6 +233,7 @@ static void notification_xmit(uint8_t rhport, bool force_next) { ncm_interface.notification_xmit_is_running = true; } else { TU_LOG_DRV(" NOTIFICATION_FINISHED\n"); + ncm_interface.notification_xmit_is_running = false; } } // notification_xmit @@ -390,7 +392,7 @@ static bool xmit_requested_datagram_fits_into_current_ntb(uint16_t datagram_size if (ncm_interface.xmit_glue_ntb_datagram_ndx >= CFG_TUD_NCM_IN_MAX_DATAGRAMS_PER_NTB) { return false; } - if (ncm_interface.xmit_glue_ntb->nth.wBlockLength + datagram_size + XMIT_ALIGN_OFFSET(datagram_size) > CFG_TUD_NCM_OUT_NTB_MAX_SIZE) { + if (ncm_interface.xmit_glue_ntb->nth.wBlockLength + datagram_size + XMIT_ALIGN_OFFSET(datagram_size) > CFG_TUD_NCM_IN_NTB_MAX_SIZE) { return false; } return true; @@ -674,7 +676,7 @@ static void recv_transfer_datagram_to_glue_logic(void) { bool tud_network_can_xmit(uint16_t size) { TU_LOG_DRV("tud_network_can_xmit(%d)\n", size); - TU_ASSERT(size <= CFG_TUD_NCM_OUT_NTB_MAX_SIZE - (sizeof(nth16_t) + sizeof(ndp16_t) + 2 * sizeof(ndp16_datagram_t)), false); + TU_ASSERT(size <= CFG_TUD_NCM_IN_NTB_MAX_SIZE - (sizeof(nth16_t) + sizeof(ndp16_t) + 2 * sizeof(ndp16_datagram_t)), false); if (xmit_requested_datagram_fits_into_current_ntb(size) || xmit_setup_next_glue_ntb()) { // -> everything is fine @@ -709,7 +711,7 @@ void tud_network_xmit(void *ref, uint16_t arg) { ntb->nth.wBlockLength += (uint16_t) (size + XMIT_ALIGN_OFFSET(size)); - if (ntb->nth.wBlockLength > CFG_TUD_NCM_OUT_NTB_MAX_SIZE) { + if (ntb->nth.wBlockLength > CFG_TUD_NCM_IN_NTB_MAX_SIZE) { TU_LOG_DRV("(EE) tud_network_xmit: buffer overflow\n"); // must not happen (really) return; } @@ -755,6 +757,32 @@ static void tud_network_recv_renew_r(uint8_t rhport) { tud_network_recv_renew(); } // tud_network_recv_renew +/** + * Set the link state and send notification to host + */ +void tud_network_link_state(uint8_t rhport, bool is_up) { + TU_LOG_DRV("tud_network_link_state(%d, %d)\n", rhport, is_up); + + if (ncm_interface.link_is_up == is_up) { + // No change in link state + return; + } + + ncm_interface.link_is_up = is_up; + + // Only send notification if we have an active data interface + if (ncm_interface.itf_data_alt != 1) { + TU_LOG_DRV(" link state notification skipped (interface not active)\n"); + return; + } + + // Reset notification state to send link state update + ncm_interface.notification_xmit_state = NOTIFICATION_CONNECTED; + + // Trigger notification transmission + notification_xmit(rhport, false); +} + //----------------------------------------------------------------------------- // // all the netd_*() stuff (interface TinyUSB -> driver) @@ -774,6 +802,12 @@ void netd_init(void) { for (int i = 0; i < RECV_NTB_N; ++i) { ncm_interface.recv_free_ntb[i] = &ncm_epbuf.recv[i].ntb; } + // Default link state - can be configured via CFG_TUD_NCM_DEFAULT_LINK_UP + #ifdef CFG_TUD_NCM_DEFAULT_LINK_UP + ncm_interface.link_is_up = CFG_TUD_NCM_DEFAULT_LINK_UP; + #else + ncm_interface.link_is_up = true; // Default to link up if not set. + #endif } // netd_init /** @@ -857,7 +891,8 @@ bool netd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_ // - if there is a free receive buffer, initiate reception if (!recv_validate_datagram(ncm_interface.recv_tinyusb_ntb, xferred_bytes)) { // verification failed: ignore NTB and return it to free - TU_LOG_DRV("(EE) VALIDATION FAILED. WHAT CAN WE DO IN THIS CASE?\n"); + TU_LOG_DRV("Invalid datatagram. Ignoring NTB\n"); + recv_put_ntb_into_free_list(ncm_interface.recv_tinyusb_ntb); } else { // packet ok -> put it into ready list recv_put_ntb_into_ready_list(ncm_interface.recv_tinyusb_ntb); diff --git a/src/class/net/net_device.h b/src/class/net/net_device.h index 4c9a92f2d..fff2623b7 100644 --- a/src/class/net/net_device.h +++ b/src/class/net/net_device.h @@ -87,6 +87,11 @@ void tud_network_init_cb(void); // TODO removed later since it is not part of tinyusb stack extern uint8_t tud_network_mac_address[6]; +//------------- NCM -------------// + +// Set the network link state (up/down) and notify the host +void tud_network_link_state(uint8_t rhport, bool is_up); + //--------------------------------------------------------------------+ // INTERNAL USBD-CLASS DRIVER API //--------------------------------------------------------------------+ diff --git a/src/class/vendor/vendor_device.c b/src/class/vendor/vendor_device.c index 6f9b4853f..7f1fd8c41 100644 --- a/src/class/vendor/vendor_device.c +++ b/src/class/vendor/vendor_device.c @@ -196,8 +196,8 @@ void vendord_reset(uint8_t rhport) { uint16_t vendord_open(uint8_t rhport, const tusb_desc_interface_t* desc_itf, uint16_t max_len) { TU_VERIFY(TUSB_CLASS_VENDOR_SPECIFIC == desc_itf->bInterfaceClass, 0); + const uint8_t* desc_end = (const uint8_t*)desc_itf + max_len; const uint8_t* p_desc = tu_desc_next(desc_itf); - const uint8_t* desc_end = p_desc + max_len; // Find available interface vendord_interface_t* p_vendor = NULL; @@ -210,26 +210,26 @@ uint16_t vendord_open(uint8_t rhport, const tusb_desc_interface_t* desc_itf, uin TU_VERIFY(p_vendor, 0); p_vendor->itf_num = desc_itf->bInterfaceNumber; - uint8_t found_ep = 0; - while (found_ep < desc_itf->bNumEndpoints) { - // skip non-endpoint descriptors - while ( (TUSB_DESC_ENDPOINT != tu_desc_type(p_desc)) && (p_desc < desc_end) ) { - p_desc = tu_desc_next(p_desc); - } - if (p_desc >= desc_end) { - break; - } + while (tu_desc_is_valid(p_desc, desc_end)) { + const uint8_t desc_type = tu_desc_type(p_desc); + if (desc_type == TUSB_DESC_INTERFACE || desc_type == TUSB_DESC_INTERFACE_ASSOCIATION) { + break; // end of this interface + } else if (desc_type == TUSB_DESC_ENDPOINT) { + const tusb_desc_endpoint_t* desc_ep = (const tusb_desc_endpoint_t*) p_desc; + TU_ASSERT(usbd_edpt_open(rhport, desc_ep)); - const tusb_desc_endpoint_t* desc_ep = (const tusb_desc_endpoint_t*) p_desc; - TU_ASSERT(usbd_edpt_open(rhport, desc_ep)); - found_ep++; - - if (tu_edpt_dir(desc_ep->bEndpointAddress) == TUSB_DIR_IN) { - tu_edpt_stream_open(&p_vendor->tx.stream, desc_ep); - tud_vendor_n_write_flush((uint8_t)(p_vendor - _vendord_itf)); - } else { - tu_edpt_stream_open(&p_vendor->rx.stream, desc_ep); - TU_ASSERT(tu_edpt_stream_read_xfer(rhport, &p_vendor->rx.stream) > 0, 0); // prepare for incoming data + // open endpoint stream, skip if already opened + if (tu_edpt_dir(desc_ep->bEndpointAddress) == TUSB_DIR_IN) { + if (p_vendor->tx.stream.ep_addr == 0) { + tu_edpt_stream_open(&p_vendor->tx.stream, desc_ep); + tud_vendor_n_write_flush((uint8_t)(p_vendor - _vendord_itf)); + } + } else { + if (p_vendor->rx.stream.ep_addr == 0) { + tu_edpt_stream_open(&p_vendor->rx.stream, desc_ep); + TU_ASSERT(tu_edpt_stream_read_xfer(rhport, &p_vendor->rx.stream) > 0, 0); // prepare for incoming data + } + } } p_desc = tu_desc_next(p_desc); diff --git a/src/class/video/video.h b/src/class/video/video.h index b8a9b6369..f348e187b 100644 --- a/src/class/video/video.h +++ b/src/class/video/video.h @@ -540,28 +540,32 @@ typedef struct TU_ATTR_PACKED { TU_VERIFY_STATIC( sizeof(video_probe_and_commit_control_t) == 48, "size is not correct"); -#define TUD_VIDEO_DESC_IAD_LEN 8 -#define TUD_VIDEO_DESC_STD_VC_LEN 9 -#define TUD_VIDEO_DESC_CS_VC_LEN 12 -#define TUD_VIDEO_DESC_INPUT_TERM_LEN 8 -#define TUD_VIDEO_DESC_OUTPUT_TERM_LEN 9 -#define TUD_VIDEO_DESC_CAMERA_TERM_LEN 18 -#define TUD_VIDEO_DESC_STD_VS_LEN 9 -#define TUD_VIDEO_DESC_CS_VS_IN_LEN 13 -#define TUD_VIDEO_DESC_CS_VS_OUT_LEN 9 -#define TUD_VIDEO_DESC_CS_VS_FMT_UNCOMPR_LEN 27 -#define TUD_VIDEO_DESC_CS_VS_FMT_MJPEG_LEN 11 -#define TUD_VIDEO_DESC_CS_VS_FRM_UNCOMPR_CONT_LEN 38 -#define TUD_VIDEO_DESC_CS_VS_FRM_UNCOMPR_DISC_LEN 26 -#define TUD_VIDEO_DESC_CS_VS_FRM_MJPEG_CONT_LEN 38 -#define TUD_VIDEO_DESC_CS_VS_FRM_MJPEG_DISC_LEN 26 -#define TUD_VIDEO_DESC_CS_VS_COLOR_MATCHING_LEN 6 +#define TUD_VIDEO_DESC_IAD_LEN 8 +#define TUD_VIDEO_DESC_STD_VC_LEN 9 +#define TUD_VIDEO_DESC_CS_VC_LEN 12 +#define TUD_VIDEO_DESC_INPUT_TERM_LEN 8 +#define TUD_VIDEO_DESC_OUTPUT_TERM_LEN 9 +#define TUD_VIDEO_DESC_CAMERA_TERM_LEN 18 +#define TUD_VIDEO_DESC_STD_VS_LEN 9 +#define TUD_VIDEO_DESC_CS_VS_IN_LEN 13 +#define TUD_VIDEO_DESC_CS_VS_OUT_LEN 9 +#define TUD_VIDEO_DESC_CS_VS_FMT_UNCOMPR_LEN 27 +#define TUD_VIDEO_DESC_CS_VS_FMT_MJPEG_LEN 11 +#define TUD_VIDEO_DESC_CS_VS_FMT_FRAME_BASED_LEN 28 +#define TUD_VIDEO_DESC_CS_VS_FRM_UNCOMPR_CONT_LEN 38 +#define TUD_VIDEO_DESC_CS_VS_FRM_UNCOMPR_DISC_LEN 26 +#define TUD_VIDEO_DESC_CS_VS_FRM_MJPEG_CONT_LEN 38 +#define TUD_VIDEO_DESC_CS_VS_FRM_MJPEG_DISC_LEN 26 +#define TUD_VIDEO_DESC_CS_VS_FRM_FRAME_BASED_CONT_LEN 38 +#define TUD_VIDEO_DESC_CS_VS_FRM_FRAME_BASED_DISC_LEN 26 +#define TUD_VIDEO_DESC_CS_VS_COLOR_MATCHING_LEN 6 /* 2.2 compression formats */ #define TUD_VIDEO_GUID_YUY2 0x59,0x55,0x59,0x32,0x00,0x00,0x10,0x00,0x80,0x00,0x00,0xAA,0x00,0x38,0x9B,0x71 #define TUD_VIDEO_GUID_NV12 0x4E,0x56,0x31,0x32,0x00,0x00,0x10,0x00,0x80,0x00,0x00,0xAA,0x00,0x38,0x9B,0x71 #define TUD_VIDEO_GUID_M420 0x4D,0x34,0x32,0x30,0x00,0x00,0x10,0x00,0x80,0x00,0x00,0xAA,0x00,0x38,0x9B,0x71 #define TUD_VIDEO_GUID_I420 0x49,0x34,0x32,0x30,0x00,0x00,0x10,0x00,0x80,0x00,0x00,0xAA,0x00,0x38,0x9B,0x71 +#define TUD_VIDEO_GUID_H264 0x48,0x32,0x36,0x34,0x00,0x00,0x10,0x00,0x80,0x00,0x00,0xAA,0x00,0x38,0x9B,0x71 #define TUD_VIDEO_DESC_IAD(_firstitf, _nitfs, _stridx) \ TUD_VIDEO_DESC_IAD_LEN, TUSB_DESC_INTERFACE_ASSOCIATION, \ @@ -656,6 +660,25 @@ TU_VERIFY_STATIC( sizeof(video_probe_and_commit_control_t) == 48, "size is not c _frmidx, _cap, U16_TO_U8S_LE(_width), U16_TO_U8S_LE(_height), U32_TO_U8S_LE(_minbr), U32_TO_U8S_LE(_maxbr), \ U32_TO_U8S_LE(_maxfrmbufsz), U32_TO_U8S_LE(_frminterval), (TU_ARGS_NUM(__VA_ARGS__)), __VA_ARGS__ +/* Motion-Frame-Based 3.1.1 Table 3-1 */ +#define TUD_VIDEO_DESC_CS_VS_FMT_FRAME_BASED(_fmtidx, _numfrmdesc, _guid, _bitsperpix, _frmidx, _asrx, _asry, _interlace, _cp, _variablesize) \ + TUD_VIDEO_DESC_CS_VS_FMT_FRAME_BASED_LEN, TUSB_DESC_CS_INTERFACE, VIDEO_CS_ITF_VS_FORMAT_FRAME_BASED, \ + _fmtidx, _numfrmdesc, TUD_VIDEO_GUID(_guid), _bitsperpix, _frmidx, _asrx, _asry, _interlace, _cp, _variablesize + +/* Motion-Frame-Based 3.1.1 Table 3-2 and 3-3 */ +#define TUD_VIDEO_DESC_CS_VS_FRM_FRAME_BASED_CONT(_frmidx, _cap, _width, _height, _minbr, _maxbr, _frminterval, _bytesperline, _minfrminterval, _maxfrminterval, _frmintervalstep) \ + TUD_VIDEO_DESC_CS_VS_FRM_FRAME_BASED_CONT_LEN, TUSB_DESC_CS_INTERFACE, VIDEO_CS_ITF_VS_FRAME_FRAME_BASED, \ + _frmidx, _cap, U16_TO_U8S_LE(_width), U16_TO_U8S_LE(_height), U32_TO_U8S_LE(_minbr), U32_TO_U8S_LE(_maxbr), \ + U32_TO_U8S_LE(_frminterval), 0, U32_TO_U8S_LE(_bytesperline), \ + U32_TO_U8S_LE(_minfrminterval), U32_TO_U8S_LE(_maxfrminterval), U32_TO_U8S_LE(_frmintervalstep) + +/* Motion-Frame-Based 3.1.1 Table 3-2 and 3-4 */ +#define TUD_VIDEO_DESC_CS_VS_FRM_FRAME_BASED_DISC(_frmidx, _cap, _width, _height, _minbr, _maxbr, _frminterval, _bytesperline, ...) \ + TUD_VIDEO_DESC_CS_VS_FRM_FRAME_BASED_DISC_LEN + (TU_ARGS_NUM(__VA_ARGS__)) * 4, \ + TUSB_DESC_CS_INTERFACE, VIDEO_CS_ITF_VS_FRAME_FRAME_BASED, \ + _frmidx, _cap, U16_TO_U8S_LE(_width), U16_TO_U8S_LE(_height), U32_TO_U8S_LE(_minbr), U32_TO_U8S_LE(_maxbr), \ +U32_TO_U8S_LE(_frminterval), U32_TO_U8S_LE(_bytesperline), (TU_ARGS_NUM(__VA_ARGS__)), __VA_ARGS__ + /* 3.9.2.6 */ #define TUD_VIDEO_DESC_CS_VS_COLOR_MATCHING(_color, _trns, _mat) \ TUD_VIDEO_DESC_CS_VS_COLOR_MATCHING_LEN, \ diff --git a/src/class/video/video_device.c b/src/class/video/video_device.c index 86513ddf0..3124d5596 100644 --- a/src/class/video/video_device.c +++ b/src/class/video/video_device.c @@ -462,6 +462,9 @@ static bool _update_streaming_parameters(videod_streaming_interface_t const *stm case VIDEO_CS_ITF_VS_FORMAT_MJPEG: break; + case VIDEO_CS_ITF_VS_FORMAT_FRAME_BASED: + break; + default: return false; } @@ -487,6 +490,10 @@ static bool _update_streaming_parameters(videod_streaming_interface_t const *stm frame_size = (uint_fast32_t)frm->wWidth * frm->wHeight * 16 / 8; /* YUV422 */ break; + case VIDEO_CS_ITF_VS_FORMAT_FRAME_BASED: + frame_size = (uint_fast32_t)frm->wWidth * frm->wHeight * 16 / 8; /* YUV422 */ + break; + default: break; } param->dwMaxVideoFrameSize = frame_size; @@ -576,6 +583,10 @@ static bool _negotiate_streaming_parameters(videod_streaming_interface_t const * frmnum = fmt->mjpeg.bDefaultFrameIndex; break; + case VIDEO_CS_ITF_VS_FORMAT_FRAME_BASED: + frmnum = fmt->frame_based.bDefaultFrameIndex; + break; + default: return false; } break; @@ -594,6 +605,10 @@ static bool _negotiate_streaming_parameters(videod_streaming_interface_t const * frame_size = (uint_fast32_t)frm->wWidth * frm->wHeight * 16 / 8; /* YUV422 */ break; + case VIDEO_CS_ITF_VS_FORMAT_FRAME_BASED: + frame_size = (uint_fast32_t)frm->wWidth * frm->wHeight * 16 / 8; /* YUV422 */ + break; + default: return false; } param->dwMaxVideoFrameSize = frame_size; diff --git a/src/common/tusb_common.h b/src/common/tusb_common.h index 74cac965d..0351a3d8f 100644 --- a/src/common/tusb_common.h +++ b/src/common/tusb_common.h @@ -120,6 +120,22 @@ TU_ATTR_ALWAYS_INLINE static inline int tu_memcpy_s(void *dest, size_t destsz, c return 0; } +TU_ATTR_ALWAYS_INLINE static inline bool tu_mem_is_zero(const void *buffer, size_t size) { + const uint8_t* buf8 = (const uint8_t*) buffer; + for (size_t i = 0; i < size; i++) { + if (buf8[i] != 0) { return false; } + } + return true; +} + +TU_ATTR_ALWAYS_INLINE static inline bool tu_mem_is_ff(const void *buffer, size_t size) { + const uint8_t* buf8 = (const uint8_t*) buffer; + for (size_t i = 0; i < size; i++) { + if (buf8[i] != 0xff) { return false; } + } + return true; +} + //------------- Bytes -------------// TU_ATTR_ALWAYS_INLINE static inline uint32_t tu_u32(uint8_t b3, uint8_t b2, uint8_t b1, uint8_t b0) { @@ -181,8 +197,7 @@ TU_ATTR_ALWAYS_INLINE static inline uint32_t tu_round_up(uint32_t v, uint32_t f) // log2 of a value is its MSB's position // TODO use clz TODO remove -static inline uint8_t tu_log2(uint32_t value) -{ +TU_ATTR_ALWAYS_INLINE static inline uint8_t tu_log2(uint32_t value) { uint8_t result = 0; while (value >>= 1) { result++; } return result; @@ -193,8 +208,7 @@ static inline uint8_t tu_log2(uint32_t value) // return sizeof(uint32_t) * CHAR_BIT - __builtin_clz(x) - 1; //} -static inline bool tu_is_power_of_two(uint32_t value) -{ +TU_ATTR_ALWAYS_INLINE static inline bool tu_is_power_of_two(uint32_t value) { return (value != 0) && ((value & (value - 1)) == 0); } @@ -205,27 +219,23 @@ static inline bool tu_is_power_of_two(uint32_t value) typedef struct { uint16_t val; } TU_ATTR_PACKED tu_unaligned_uint16_t; typedef struct { uint32_t val; } TU_ATTR_PACKED tu_unaligned_uint32_t; -TU_ATTR_ALWAYS_INLINE static inline uint32_t tu_unaligned_read32(const void* mem) -{ - tu_unaligned_uint32_t const* ua32 = (tu_unaligned_uint32_t const*) mem; +TU_ATTR_ALWAYS_INLINE static inline uint32_t tu_unaligned_read32(const void *mem) { + tu_unaligned_uint32_t const *ua32 = (tu_unaligned_uint32_t const *) mem; return ua32->val; } -TU_ATTR_ALWAYS_INLINE static inline void tu_unaligned_write32(void* mem, uint32_t value) -{ - tu_unaligned_uint32_t* ua32 = (tu_unaligned_uint32_t*) mem; +TU_ATTR_ALWAYS_INLINE static inline void tu_unaligned_write32(void *mem, uint32_t value) { + tu_unaligned_uint32_t *ua32 = (tu_unaligned_uint32_t *) mem; ua32->val = value; } -TU_ATTR_ALWAYS_INLINE static inline uint16_t tu_unaligned_read16(const void* mem) -{ - tu_unaligned_uint16_t const* ua16 = (tu_unaligned_uint16_t const*) mem; +TU_ATTR_ALWAYS_INLINE static inline uint16_t tu_unaligned_read16(const void *mem) { + tu_unaligned_uint16_t const *ua16 = (tu_unaligned_uint16_t const *) mem; return ua16->val; } -TU_ATTR_ALWAYS_INLINE static inline void tu_unaligned_write16(void* mem, uint16_t value) -{ - tu_unaligned_uint16_t* ua16 = (tu_unaligned_uint16_t*) mem; +TU_ATTR_ALWAYS_INLINE static inline void tu_unaligned_write16(void *mem, uint16_t value) { + tu_unaligned_uint16_t *ua16 = (tu_unaligned_uint16_t *) mem; ua16->val = value; } diff --git a/src/common/tusb_debug.h b/src/common/tusb_debug.h index 2e9f1d9cd..1d0c6f1ad 100644 --- a/src/common/tusb_debug.h +++ b/src/common/tusb_debug.h @@ -108,15 +108,13 @@ typedef struct { } tu_lookup_table_t; static inline const char* tu_lookup_find(tu_lookup_table_t const* p_table, uint32_t key) { - tu_static char not_found[11]; - for(uint16_t i=0; icount; i++) { - if (p_table->items[i].key == key) return p_table->items[i].data; + if (p_table->items[i].key == key) { return p_table->items[i].data; } } // not found return the key value in hex + static char not_found[11]; snprintf(not_found, sizeof(not_found), "0x%08lX", (unsigned long) key); - return not_found; } diff --git a/src/common/tusb_fifo.c b/src/common/tusb_fifo.c index 5f2dcabad..ecf002b09 100644 --- a/src/common/tusb_fifo.c +++ b/src/common/tusb_fifo.c @@ -916,8 +916,11 @@ bool tu_fifo_clear(tu_fifo_t *f) Overwritable mode the fifo is set to */ /******************************************************************************/ -bool tu_fifo_set_overwritable(tu_fifo_t *f, bool overwritable) -{ +bool tu_fifo_set_overwritable(tu_fifo_t *f, bool overwritable) { + if (f->overwritable == overwritable) { + return true; + } + _ff_lock(f->mutex_wr); _ff_lock(f->mutex_rd); diff --git a/src/common/tusb_mcu.h b/src/common/tusb_mcu.h index d282c890d..2ee2132bf 100644 --- a/src/common/tusb_mcu.h +++ b/src/common/tusb_mcu.h @@ -108,12 +108,20 @@ #define TUP_DCD_ENDPOINT_MAX 16 #elif TU_CHECK_MCU(OPT_MCU_MIMXRT1XXX) + #include "fsl_device_registers.h" + #define TUP_USBIP_CHIPIDEA_HS #define TUP_USBIP_EHCI #define TUP_DCD_ENDPOINT_MAX 8 #define TUP_RHPORT_HIGHSPEED 1 + #if __CORTEX_M == 7 + #define CFG_TUD_MEM_DCACHE_ENABLE_DEFAULT 1 + #define CFG_TUH_MEM_DCACHE_ENABLE_DEFAULT 1 + #define CFG_TUSB_MEM_DCACHE_LINE_SIZE 32 + #endif + #elif TU_CHECK_MCU(OPT_MCU_KINETIS_KL, OPT_MCU_KINETIS_K32L, OPT_MCU_KINETIS_K) #define TUP_USBIP_CHIPIDEA_FS #define TUP_USBIP_CHIPIDEA_FS_KINETIS @@ -304,7 +312,7 @@ #define TUP_USBIP_FSDEV_STM32 #define TUP_DCD_ENDPOINT_MAX 8 -#elif TU_CHECK_MCU(OPT_MCU_STM32H7RS) +#elif TU_CHECK_MCU(OPT_MCU_STM32H7RS, OPT_MCU_STM32N6) #define TUP_USBIP_DWC2 #define TUP_USBIP_DWC2_STM32 @@ -361,6 +369,10 @@ #define TUP_DCD_ENDPOINT_MAX 7 // only 5 TX FIFO for endpoint IN #define CFG_TUSB_OS_INC_PATH_DEFAULT freertos/ + #if CFG_TUSB_MCU == OPT_MCU_ESP32S3 + #define TUP_MCU_MULTIPLE_CORE 1 + #endif + // Disable slave if DMA is enabled #define CFG_TUD_DWC2_SLAVE_ENABLE_DEFAULT !CFG_TUD_DWC2_DMA_ENABLE #define CFG_TUH_DWC2_SLAVE_ENABLE_DEFAULT !CFG_TUH_DWC2_DMA_ENABLE @@ -373,6 +385,8 @@ #define CFG_TUSB_OS_INC_PATH_DEFAULT freertos/ + #define TUP_MCU_MULTIPLE_CORE 1 + // Disable slave if DMA is enabled #define CFG_TUD_DWC2_SLAVE_ENABLE_DEFAULT !CFG_TUD_DWC2_DMA_ENABLE #define CFG_TUH_DWC2_SLAVE_ENABLE_DEFAULT !CFG_TUH_DWC2_DMA_ENABLE @@ -402,6 +416,7 @@ #elif TU_CHECK_MCU(OPT_MCU_RP2040) #define TUP_DCD_EDPT_ISO_ALLOC #define TUP_DCD_ENDPOINT_MAX 16 + #define TUP_MCU_MULTIPLE_CORE 1 #define TU_ATTR_FAST_FUNC __attribute__((section(".time_critical.tinyusb"))) diff --git a/src/common/tusb_private.h b/src/common/tusb_private.h index c71775abb..31aca8a31 100644 --- a/src/common/tusb_private.h +++ b/src/common/tusb_private.h @@ -67,7 +67,7 @@ typedef struct { //--------------------------------------------------------------------+ // Check if endpoint descriptor is valid per USB specs -bool tu_edpt_validate(tusb_desc_endpoint_t const * desc_ep, tusb_speed_t speed); +bool tu_edpt_validate(tusb_desc_endpoint_t const * desc_ep, tusb_speed_t speed, bool is_host); // Bind all endpoint of a interface descriptor to class driver void tu_edpt_bind_driver(uint8_t ep2drv[][2], tusb_desc_interface_t const* p_desc, uint16_t desc_len, uint8_t driver_id); @@ -138,7 +138,7 @@ uint32_t tu_edpt_stream_read(uint8_t hwid, tu_edpt_stream_t* s, void* buffer, ui // Start an usb transfer if endpoint is not busy uint32_t tu_edpt_stream_read_xfer(uint8_t hwid, tu_edpt_stream_t* s); -// Must be called in the transfer complete callback +// Complete read transfer by writing EP -> FIFO. Must be called in the transfer complete callback TU_ATTR_ALWAYS_INLINE static inline void tu_edpt_stream_read_xfer_complete(tu_edpt_stream_t* s, uint32_t xferred_bytes) { if (tu_fifo_depth(&s->ff)) { @@ -146,11 +146,11 @@ void tu_edpt_stream_read_xfer_complete(tu_edpt_stream_t* s, uint32_t xferred_byt } } -// Same as tu_edpt_stream_read_xfer_complete but skip the first n bytes +// Complete read transfer with provided buffer TU_ATTR_ALWAYS_INLINE static inline -void tu_edpt_stream_read_xfer_complete_offset(tu_edpt_stream_t* s, uint32_t xferred_bytes, uint32_t skip_offset) { - if (tu_fifo_depth(&s->ff) && (skip_offset < xferred_bytes)) { - tu_fifo_write_n(&s->ff, s->ep_buf + skip_offset, (uint16_t) (xferred_bytes - skip_offset)); +void tu_edpt_stream_read_xfer_complete_with_buf(tu_edpt_stream_t* s, const void * buf, uint32_t xferred_bytes) { + if (tu_fifo_depth(&s->ff)) { + tu_fifo_write_n(&s->ff, buf, (uint16_t) xferred_bytes); } } diff --git a/src/common/tusb_types.h b/src/common/tusb_types.h index 9e4d9380c..ec7aad796 100644 --- a/src/common/tusb_types.h +++ b/src/common/tusb_types.h @@ -278,10 +278,13 @@ typedef enum { XFER_RESULT_INVALID } xfer_result_t; +#define tusb_xfer_result_t xfer_result_t + // TODO remove enum { DESC_OFFSET_LEN = 0, - DESC_OFFSET_TYPE = 1 + DESC_OFFSET_TYPE = 1, + DESC_OFFSET_SUBTYPE = 2 }; enum { @@ -302,9 +305,9 @@ typedef enum { enum { CONTROL_STAGE_IDLE = 0, - CONTROL_STAGE_SETUP, - CONTROL_STAGE_DATA, - CONTROL_STAGE_ACK + CONTROL_STAGE_SETUP, // 1 + CONTROL_STAGE_DATA, // 2 + CONTROL_STAGE_ACK // 3 }; enum { @@ -344,7 +347,6 @@ typedef struct TU_ATTR_PACKED { uint8_t iManufacturer ; ///< Index of string descriptor describing manufacturer. uint8_t iProduct ; ///< Index of string descriptor describing product. uint8_t iSerialNumber ; ///< Index of string descriptor describing the device's serial number. - uint8_t bNumConfigurations ; ///< Number of possible configurations. } tusb_desc_device_t; @@ -462,7 +464,7 @@ TU_VERIFY_STATIC( sizeof(tusb_desc_interface_assoc_t) == 8, "size is not correct typedef struct TU_ATTR_PACKED { uint8_t bLength ; ///< Size of this descriptor in bytes uint8_t bDescriptorType ; ///< Descriptor Type - uint16_t unicode_string[]; + uint16_t utf16le[]; } tusb_desc_string_t; // USB Binary Device Object Store (BOS) @@ -570,16 +572,27 @@ TU_ATTR_ALWAYS_INLINE static inline uint8_t const * tu_desc_next(void const* des return desc8 + desc8[DESC_OFFSET_LEN]; } +// get descriptor length +TU_ATTR_ALWAYS_INLINE static inline uint8_t tu_desc_len(void const* desc) { + return ((uint8_t const*) desc)[DESC_OFFSET_LEN]; +} + // get descriptor type TU_ATTR_ALWAYS_INLINE static inline uint8_t tu_desc_type(void const* desc) { return ((uint8_t const*) desc)[DESC_OFFSET_TYPE]; } -// get descriptor length -TU_ATTR_ALWAYS_INLINE static inline uint8_t tu_desc_len(void const* desc) { - return ((uint8_t const*) desc)[DESC_OFFSET_LEN]; +// get descriptor subtype +TU_ATTR_ALWAYS_INLINE static inline uint8_t tu_desc_subtype(void const* desc) { + return ((uint8_t const*) desc)[DESC_OFFSET_SUBTYPE]; } +TU_ATTR_ALWAYS_INLINE static inline uint8_t tu_desc_is_valid(void const* desc, uint8_t const* desc_end) { + const uint8_t* desc8 = (uint8_t const*) desc; + return (desc8 < desc_end) && (tu_desc_next(desc) <= desc_end); +} + + // find descriptor that match byte1 (type) uint8_t const * tu_desc_find(uint8_t const* desc, uint8_t const* end, uint8_t byte1); diff --git a/src/device/usbd.c b/src/device/usbd.c index 2a6081673..ba8dd669b 100644 --- a/src/device/usbd.c +++ b/src/device/usbd.c @@ -340,15 +340,16 @@ TU_ATTR_ALWAYS_INLINE static inline usbd_class_driver_t const * get_driver(uint8 enum { RHPORT_INVALID = 0xFFu }; tu_static uint8_t _usbd_rhport = RHPORT_INVALID; -// Event queue -// usbd_int_set() is used as mutex in OS NONE config +static OSAL_SPINLOCK_DEF(_usbd_spin, usbd_int_set); + +// Event queue: usbd_int_set() is used as mutex in OS NONE config OSAL_QUEUE_DEF(usbd_int_set, _usbd_qdef, CFG_TUD_TASK_QUEUE_SZ, dcd_event_t); -tu_static osal_queue_t _usbd_q; +static osal_queue_t _usbd_q; // Mutex for claiming endpoint #if OSAL_MUTEX_REQUIRED - tu_static osal_mutex_def_t _ubsd_mutexdef; - tu_static osal_mutex_t _usbd_mutex; + static osal_mutex_def_t _ubsd_mutexdef; + static osal_mutex_t _usbd_mutex; #else #define _usbd_mutex NULL #endif @@ -464,17 +465,36 @@ bool tud_rhport_init(uint8_t rhport, const tusb_rhport_init_t* rh_init) { return true; // skip if already initialized } TU_ASSERT(rh_init); - - TU_LOG_USBD("USBD init on controller %u, speed = %s\r\n", rhport, - rh_init->speed == TUSB_SPEED_HIGH ? "High" : "Full"); +#if CFG_TUSB_DEBUG >= CFG_TUD_LOG_LEVEL + char const* speed_str = 0; + switch (rh_init->speed) { + case TUSB_SPEED_HIGH: + speed_str = "High"; + break; + case TUSB_SPEED_FULL: + speed_str = "Full"; + break; + case TUSB_SPEED_LOW: + speed_str = "Low"; + break; + case TUSB_SPEED_AUTO: + speed_str = "Auto"; + break; + default: + break; + } + TU_LOG_USBD("USBD init on controller %u, speed = %s\r\n", rhport, speed_str); TU_LOG_INT(CFG_TUD_LOG_LEVEL, sizeof(usbd_device_t)); TU_LOG_INT(CFG_TUD_LOG_LEVEL, sizeof(dcd_event_t)); TU_LOG_INT(CFG_TUD_LOG_LEVEL, sizeof(tu_fifo_t)); TU_LOG_INT(CFG_TUD_LOG_LEVEL, sizeof(tu_edpt_stream_t)); +#endif tu_varclr(&_usbd_dev); _usbd_queued_setup = 0; + osal_spin_init(&_usbd_spin); + #if OSAL_MUTEX_REQUIRED // Init device mutex _usbd_mutex = osal_mutex_create(&_ubsd_mutexdef); @@ -561,8 +581,7 @@ static void usbd_reset(uint8_t rhport) { } bool tud_task_event_ready(void) { - // Skip if stack is not initialized - if (!tud_inited()) return false; + TU_VERIFY(tud_inited()); // Skip if stack is not initialized return !osal_queue_empty(_usbd_q); } @@ -684,7 +703,9 @@ void tud_task_ext(uint32_t timeout_ms, bool in_isr) { case USBD_EVENT_FUNC_CALL: TU_LOG_USBD("\r\n"); - if (event.func_call.func) event.func_call.func(event.func_call.param); + if (event.func_call.func) { + event.func_call.func(event.func_call.param); + } break; case DCD_EVENT_SOF: @@ -701,7 +722,7 @@ void tud_task_ext(uint32_t timeout_ms, bool in_isr) { #if CFG_TUSB_OS != OPT_OS_NONE && CFG_TUSB_OS != OPT_OS_PICO // return if there is no more events, for application to run other background - if (osal_queue_empty(_usbd_q)) return; + if (osal_queue_empty(_usbd_q)) { return; } #endif } } @@ -1032,7 +1053,14 @@ static bool process_set_config(uint8_t rhport, uint8_t cfg_num) #endif #if CFG_TUD_MIDI - if ( driver->open == midid_open ) assoc_itf_count = 2; + if (driver->open == midid_open) { + // If there is a class-compliant Audio Control Class, then 2 interfaces. Otherwise, only one + if (TUSB_CLASS_AUDIO == desc_itf->bInterfaceClass && + AUDIO_SUBCLASS_CONTROL == desc_itf->bInterfaceSubClass && + AUDIO_FUNC_PROTOCOL_CODE_UNDEF == desc_itf->bInterfaceProtocol) { + assoc_itf_count = 2; + } + } #endif #if CFG_TUD_BTH && CFG_TUD_BTH_ISO_ALT_COUNT @@ -1234,17 +1262,21 @@ TU_ATTR_FAST_FUNC void dcd_event_handler(dcd_event_t const* event, bool in_isr) // USBD API For Class Driver //--------------------------------------------------------------------+ -void usbd_int_set(bool enabled) -{ - if (enabled) - { +void usbd_int_set(bool enabled) { + if (enabled) { dcd_int_enable(_usbd_rhport); - }else - { + } else { dcd_int_disable(_usbd_rhport); } } +void usbd_spin_lock(bool in_isr) { + osal_spin_lock(&_usbd_spin, in_isr); +} +void usbd_spin_unlock(bool in_isr) { + osal_spin_unlock(&_usbd_spin, in_isr); +} + // Parse consecutive endpoint descriptors (IN & OUT) bool usbd_open_edpt_pair(uint8_t rhport, uint8_t const* p_desc, uint8_t ep_count, uint8_t xfer_type, uint8_t* ep_out, uint8_t* ep_in) { @@ -1289,7 +1321,7 @@ bool usbd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const* desc_ep) { rhport = _usbd_rhport; TU_ASSERT(tu_edpt_number(desc_ep->bEndpointAddress) < CFG_TUD_ENDPPOINT_MAX); - TU_ASSERT(tu_edpt_validate(desc_ep, (tusb_speed_t) _usbd_dev.speed)); + TU_ASSERT(tu_edpt_validate(desc_ep, (tusb_speed_t) _usbd_dev.speed, false)); return dcd_edpt_open(rhport, desc_ep); } @@ -1490,7 +1522,7 @@ bool usbd_edpt_iso_activate(uint8_t rhport, tusb_desc_endpoint_t const* desc_ep) uint8_t const dir = tu_edpt_dir(desc_ep->bEndpointAddress); TU_ASSERT(epnum < CFG_TUD_ENDPPOINT_MAX); - TU_ASSERT(tu_edpt_validate(desc_ep, (tusb_speed_t) _usbd_dev.speed)); + TU_ASSERT(tu_edpt_validate(desc_ep, (tusb_speed_t) _usbd_dev.speed, false)); _usbd_dev.ep_status[epnum][dir].stalled = 0; _usbd_dev.ep_status[epnum][dir].busy = 0; diff --git a/src/device/usbd_control.c b/src/device/usbd_control.c index d964a75d0..c9700fd9d 100644 --- a/src/device/usbd_control.c +++ b/src/device/usbd_control.c @@ -44,10 +44,6 @@ TU_ATTR_WEAK void dcd_edpt0_status_complete(uint8_t rhport, const tusb_control_r // MACRO CONSTANT TYPEDEF //--------------------------------------------------------------------+ -#if CFG_TUSB_DEBUG >= CFG_TUD_LOG_LEVEL -extern void usbd_driver_print_control_complete_name(usbd_control_xfer_cb_t callback); -#endif - enum { EDPT_CTRL_OUT = 0x00, EDPT_CTRL_IN = 0x80 diff --git a/src/device/usbd_pvt.h b/src/device/usbd_pvt.h index 90f37db3e..5c6f9dbee 100644 --- a/src/device/usbd_pvt.h +++ b/src/device/usbd_pvt.h @@ -68,6 +68,8 @@ usbd_class_driver_t const* usbd_app_driver_get_cb(uint8_t* driver_count) TU_ATTR typedef bool (*usbd_control_xfer_cb_t)(uint8_t rhport, uint8_t stage, tusb_control_request_t const * request); void usbd_int_set(bool enabled); +void usbd_spin_lock(bool in_isr); +void usbd_spin_unlock(bool in_isr); //--------------------------------------------------------------------+ // USBD Endpoint API @@ -127,6 +129,11 @@ void usbd_sof_enable(uint8_t rhport, sof_consumer_t consumer, bool en); bool usbd_open_edpt_pair(uint8_t rhport, uint8_t const* p_desc, uint8_t ep_count, uint8_t xfer_type, uint8_t* ep_out, uint8_t* ep_in); void usbd_defer_func(osal_task_func_t func, void *param, bool in_isr); + +#if CFG_TUSB_DEBUG >= CFG_TUD_LOG_LEVEL +void usbd_driver_print_control_complete_name(usbd_control_xfer_cb_t callback); +#endif + #ifdef __cplusplus } #endif diff --git a/src/host/hcd.h b/src/host/hcd.h index 56b6fdb5d..d3551bf5b 100644 --- a/src/host/hcd.h +++ b/src/host/hcd.h @@ -90,13 +90,6 @@ typedef struct { }; } hcd_event_t; -typedef struct { - uint8_t rhport; - uint8_t hub_addr; - uint8_t hub_port; - uint8_t speed; -} hcd_devtree_info_t; - //--------------------------------------------------------------------+ // Memory API //--------------------------------------------------------------------+ @@ -163,8 +156,12 @@ void hcd_device_close(uint8_t rhport, uint8_t dev_addr); //--------------------------------------------------------------------+ // Open an endpoint +// return true if successfully opened or endpoint is currently opened bool hcd_edpt_open(uint8_t rhport, uint8_t daddr, tusb_desc_endpoint_t const * ep_desc); +// Close an endpoint +bool hcd_edpt_close(uint8_t rhport, uint8_t daddr, uint8_t ep_addr); + // Submit a transfer, when complete hcd_event_xfer_complete() must be invoked bool hcd_edpt_xfer(uint8_t rhport, uint8_t daddr, uint8_t ep_addr, uint8_t * buffer, uint16_t buflen); @@ -182,13 +179,6 @@ bool hcd_edpt_clear_stall(uint8_t rhport, uint8_t dev_addr, uint8_t ep_addr); // USBH implemented API //--------------------------------------------------------------------+ -// Get device tree information of a device -// USB device tree can be complicated and manged by USBH, this help HCD to retrieve -// needed topology info to carry out its work -extern void hcd_devtree_get_info(uint8_t dev_addr, hcd_devtree_info_t* devtree_info); - -//------------- Event API -------------// - // Called by HCD to notify stack extern void hcd_event_handler(hcd_event_t const* event, bool in_isr); @@ -235,4 +225,4 @@ void hcd_event_xfer_complete(uint8_t dev_addr, uint8_t ep_addr, uint32_t xferred } #endif -#endif /* _TUSB_HCD_H_ */ +#endif diff --git a/src/host/hub.c b/src/host/hub.c index e97014443..0b172a596 100644 --- a/src/host/hub.c +++ b/src/host/hub.c @@ -40,29 +40,38 @@ //--------------------------------------------------------------------+ // MACRO CONSTANT TYPEDEF //--------------------------------------------------------------------+ -typedef struct -{ +typedef struct { uint8_t itf_num; uint8_t ep_in; - uint8_t port_count; - CFG_TUH_MEM_ALIGN uint8_t status_change; - CFG_TUH_MEM_ALIGN hub_port_status_response_t port_status; - CFG_TUH_MEM_ALIGN hub_status_response_t hub_status; + // from hub descriptor + uint8_t bNbrPorts; + uint8_t bPwrOn2PwrGood_2ms; // port power on to good, in 2ms unit + // uint16_t wHubCharacteristics; + + hub_port_status_response_t port_status; } hub_interface_t; -CFG_TUH_MEM_SECTION static hub_interface_t hub_data[CFG_TUH_HUB]; -CFG_TUH_MEM_SECTION CFG_TUH_MEM_ALIGN static uint8_t _hub_buffer[sizeof(descriptor_hub_desc_t)]; +typedef struct { + TUH_EPBUF_DEF(status_change, 4); // interrupt endpoint + TUH_EPBUF_DEF(ctrl_buf, CFG_TUH_HUB_BUFSIZE); +} hub_epbuf_t; -TU_ATTR_ALWAYS_INLINE -static inline hub_interface_t* get_itf(uint8_t dev_addr) -{ - return &hub_data[dev_addr-1-CFG_TUH_DEVICE_MAX]; +static tuh_xfer_cb_t user_complete_cb = NULL; +static hub_interface_t hub_itfs[CFG_TUH_HUB]; +CFG_TUH_MEM_SECTION static hub_epbuf_t hub_epbufs[CFG_TUH_HUB]; + + +TU_ATTR_ALWAYS_INLINE static inline hub_interface_t* get_hub_itf(uint8_t daddr) { + return &hub_itfs[daddr-1-CFG_TUH_DEVICE_MAX]; } -#if CFG_TUSB_DEBUG >= 2 -static char const* const _hub_feature_str[] = -{ +TU_ATTR_ALWAYS_INLINE static inline hub_epbuf_t* get_hub_epbuf(uint8_t daddr) { + return &hub_epbufs[daddr-1-CFG_TUH_DEVICE_MAX]; +} + +#if CFG_TUSB_DEBUG >= HUB_DEBUG +static char const* const _hub_feature_str[] = { [HUB_FEATURE_PORT_CONNECTION ] = "PORT_CONNECTION", [HUB_FEATURE_PORT_ENABLE ] = "PORT_ENABLE", [HUB_FEATURE_PORT_SUSPEND ] = "PORT_SUSPEND", @@ -84,12 +93,9 @@ static char const* const _hub_feature_str[] = // HUB //--------------------------------------------------------------------+ bool hub_port_clear_feature(uint8_t hub_addr, uint8_t hub_port, uint8_t feature, - tuh_xfer_cb_t complete_cb, uintptr_t user_data) -{ - tusb_control_request_t const request = - { - .bmRequestType_bit = - { + tuh_xfer_cb_t complete_cb, uintptr_t user_data) { + tusb_control_request_t const request = { + .bmRequestType_bit = { .recipient = (hub_port == 0) ? TUSB_REQ_RCPT_DEVICE : TUSB_REQ_RCPT_OTHER, .type = TUSB_REQ_TYPE_CLASS, .direction = TUSB_DIR_OUT @@ -100,8 +106,7 @@ bool hub_port_clear_feature(uint8_t hub_addr, uint8_t hub_port, uint8_t feature, .wLength = 0 }; - tuh_xfer_t xfer = - { + tuh_xfer_t xfer = { .daddr = hub_addr, .ep_addr = 0, .setup = &request, @@ -110,18 +115,15 @@ bool hub_port_clear_feature(uint8_t hub_addr, uint8_t hub_port, uint8_t feature, .user_data = user_data }; - TU_LOG2("HUB Clear Feature: %s, addr = %u port = %u\r\n", _hub_feature_str[feature], hub_addr, hub_port); - TU_ASSERT( tuh_control_xfer(&xfer) ); + TU_LOG_DRV("HUB Clear Feature: %s, addr = %u port = %u\r\n", _hub_feature_str[feature], hub_addr, hub_port); + TU_ASSERT(tuh_control_xfer(&xfer)); return true; } bool hub_port_set_feature(uint8_t hub_addr, uint8_t hub_port, uint8_t feature, - tuh_xfer_cb_t complete_cb, uintptr_t user_data) -{ - tusb_control_request_t const request = - { - .bmRequestType_bit = - { + tuh_xfer_cb_t complete_cb, uintptr_t user_data) { + tusb_control_request_t const request = { + .bmRequestType_bit = { .recipient = (hub_port == 0) ? TUSB_REQ_RCPT_DEVICE : TUSB_REQ_RCPT_OTHER, .type = TUSB_REQ_TYPE_CLASS, .direction = TUSB_DIR_OUT @@ -132,8 +134,7 @@ bool hub_port_set_feature(uint8_t hub_addr, uint8_t hub_port, uint8_t feature, .wLength = 0 }; - tuh_xfer_t xfer = - { + tuh_xfer_t xfer = { .daddr = hub_addr, .ep_addr = 0, .setup = &request, @@ -142,18 +143,28 @@ bool hub_port_set_feature(uint8_t hub_addr, uint8_t hub_port, uint8_t feature, .user_data = user_data }; - TU_LOG2("HUB Set Feature: %s, addr = %u port = %u\r\n", _hub_feature_str[feature], hub_addr, hub_port); - TU_ASSERT( tuh_control_xfer(&xfer) ); + TU_LOG_DRV("HUB Set Feature: %s, addr = %u port = %u\r\n", _hub_feature_str[feature], hub_addr, hub_port); + TU_ASSERT(tuh_control_xfer(&xfer)); return true; } +static void port_get_status_complete (tuh_xfer_t* xfer) { + if (xfer->result == XFER_RESULT_SUCCESS) { + hub_interface_t* p_hub = get_hub_itf(xfer->daddr); + p_hub->port_status = *((const hub_port_status_response_t *) (uintptr_t) xfer->buffer); + } + + xfer->complete_cb = user_complete_cb; + user_complete_cb = NULL; + if (xfer->complete_cb) { + xfer->complete_cb(xfer); + } +} + bool hub_port_get_status(uint8_t hub_addr, uint8_t hub_port, void* resp, - tuh_xfer_cb_t complete_cb, uintptr_t user_data) -{ - tusb_control_request_t const request = - { - .bmRequestType_bit = - { + tuh_xfer_cb_t complete_cb, uintptr_t user_data) { + tusb_control_request_t const request = { + .bmRequestType_bit = { .recipient = (hub_port == 0) ? TUSB_REQ_RCPT_DEVICE : TUSB_REQ_RCPT_OTHER, .type = TUSB_REQ_TYPE_CLASS, .direction = TUSB_DIR_IN @@ -161,11 +172,10 @@ bool hub_port_get_status(uint8_t hub_addr, uint8_t hub_port, void* resp, .bRequest = HUB_REQUEST_GET_STATUS, .wValue = 0, .wIndex = hub_port, - .wLength = 4 + .wLength = tu_htole16(4) }; - tuh_xfer_t xfer = - { + tuh_xfer_t xfer = { .daddr = hub_addr, .ep_addr = 0, .setup = &request, @@ -174,8 +184,25 @@ bool hub_port_get_status(uint8_t hub_addr, uint8_t hub_port, void* resp, .user_data = user_data }; - TU_LOG2("HUB Get Port Status: addr = %u port = %u\r\n", hub_addr, hub_port); - TU_VERIFY( tuh_control_xfer(&xfer) ); + if (hub_port != 0) { + // intercept complete callback to save port status, ignore resp + hub_epbuf_t* p_epbuf = get_hub_epbuf(hub_addr); + xfer.complete_cb = port_get_status_complete; + xfer.buffer = p_epbuf->ctrl_buf; + user_complete_cb = complete_cb; + } else { + user_complete_cb = NULL; + } + + TU_LOG_DRV("HUB Get Port Status: addr = %u port = %u\r\n", hub_addr, hub_port); + TU_VERIFY(tuh_control_xfer(&xfer)); + return true; +} + +bool hub_port_get_status_local(uint8_t hub_addr, uint8_t hub_port, hub_port_status_response_t* resp) { + (void) hub_port; + hub_interface_t* p_hub = get_hub_itf(hub_addr); + *resp = p_hub->port_status; return true; } @@ -183,7 +210,7 @@ bool hub_port_get_status(uint8_t hub_addr, uint8_t hub_port, void* resp, // CLASS-USBH API (don't require to verify parameters) //--------------------------------------------------------------------+ bool hub_init(void) { - tu_memclr(hub_data, sizeof(hub_data)); + tu_memclr(hub_itfs, sizeof(hub_itfs)); return true; } @@ -191,40 +218,32 @@ bool hub_deinit(void) { return true; } -bool hub_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const *itf_desc, uint16_t max_len) -{ +bool hub_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const *itf_desc, uint16_t max_len) { (void) rhport; TU_VERIFY(TUSB_CLASS_HUB == itf_desc->bInterfaceClass && 0 == itf_desc->bInterfaceSubClass); + TU_VERIFY(itf_desc->bInterfaceProtocol <= 1); // not support multiple TT yet - // hub driver does not support multiple TT yet - TU_VERIFY(itf_desc->bInterfaceProtocol <= 1); - - // msc driver length is fixed uint16_t const drv_len = sizeof(tusb_desc_interface_t) + sizeof(tusb_desc_endpoint_t); TU_ASSERT(drv_len <= max_len); - //------------- Interrupt Status endpoint -------------// + // Interrupt Status endpoint tusb_desc_endpoint_t const *desc_ep = (tusb_desc_endpoint_t const *) tu_desc_next(itf_desc); - TU_ASSERT(TUSB_DESC_ENDPOINT == desc_ep->bDescriptorType && TUSB_XFER_INTERRUPT == desc_ep->bmAttributes.xfer, 0); - TU_ASSERT(tuh_edpt_open(dev_addr, desc_ep)); - hub_interface_t* p_hub = get_itf(dev_addr); - + hub_interface_t* p_hub = get_hub_itf(dev_addr); p_hub->itf_num = itf_desc->bInterfaceNumber; p_hub->ep_in = desc_ep->bEndpointAddress; return true; } -void hub_close(uint8_t dev_addr) -{ +void hub_close(uint8_t dev_addr) { TU_VERIFY(dev_addr > CFG_TUH_DEVICE_MAX, ); - hub_interface_t* p_hub = get_itf(dev_addr); + hub_interface_t* p_hub = get_hub_itf(dev_addr); if (p_hub->ep_in) { TU_LOG_DRV(" HUB close addr = %d\r\n", dev_addr); @@ -232,30 +251,33 @@ void hub_close(uint8_t dev_addr) } } -bool hub_edpt_status_xfer(uint8_t dev_addr) -{ - hub_interface_t* hub_itf = get_itf(dev_addr); - return usbh_edpt_xfer(dev_addr, hub_itf->ep_in, &hub_itf->status_change, 1); -} +bool hub_edpt_status_xfer(uint8_t daddr) { + hub_interface_t* p_hub = get_hub_itf(daddr); + hub_epbuf_t* p_epbuf = get_hub_epbuf(daddr); + TU_VERIFY(usbh_edpt_claim(daddr, p_hub->ep_in)); + if (!usbh_edpt_xfer(daddr, p_hub->ep_in, p_epbuf->status_change, 1)) { + usbh_edpt_release(daddr, p_hub->ep_in); + return false; + } + + return true; +} //--------------------------------------------------------------------+ // Set Configure //--------------------------------------------------------------------+ - static void config_set_port_power (tuh_xfer_t* xfer); static void config_port_power_complete (tuh_xfer_t* xfer); -bool hub_set_config(uint8_t dev_addr, uint8_t itf_num) -{ - hub_interface_t* p_hub = get_itf(dev_addr); +bool hub_set_config(uint8_t daddr, uint8_t itf_num) { + hub_interface_t* p_hub = get_hub_itf(daddr); TU_ASSERT(itf_num == p_hub->itf_num); + hub_epbuf_t* p_epbuf = get_hub_epbuf(daddr); // Get Hub Descriptor - tusb_control_request_t const request = - { - .bmRequestType_bit = - { + tusb_control_request_t const request = { + .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_DEVICE, .type = TUSB_REQ_TYPE_CLASS, .direction = TUSB_DIR_IN @@ -263,34 +285,33 @@ bool hub_set_config(uint8_t dev_addr, uint8_t itf_num) .bRequest = HUB_REQUEST_GET_DESCRIPTOR, .wValue = 0, .wIndex = 0, - .wLength = sizeof(descriptor_hub_desc_t) + .wLength = sizeof(hub_desc_cs_t) }; - tuh_xfer_t xfer = - { - .daddr = dev_addr, + tuh_xfer_t xfer = { + .daddr = daddr, .ep_addr = 0, .setup = &request, - .buffer = _hub_buffer, + .buffer = p_epbuf->ctrl_buf, .complete_cb = config_set_port_power, .user_data = 0 }; - TU_ASSERT( tuh_control_xfer(&xfer) ); - + TU_ASSERT(tuh_control_xfer(&xfer)); return true; } -static void config_set_port_power (tuh_xfer_t* xfer) -{ +static void config_set_port_power (tuh_xfer_t* xfer) { TU_ASSERT(XFER_RESULT_SUCCESS == xfer->result, ); uint8_t const daddr = xfer->daddr; - hub_interface_t* p_hub = get_itf(daddr); + hub_interface_t* p_hub = get_hub_itf(daddr); + hub_epbuf_t* p_epbuf = get_hub_epbuf(daddr); // only use number of ports in hub descriptor - descriptor_hub_desc_t const* desc_hub = (descriptor_hub_desc_t const*) _hub_buffer; - p_hub->port_count = desc_hub->bNbrPorts; + hub_desc_cs_t const* desc_hub = (hub_desc_cs_t const*) p_epbuf->ctrl_buf; + p_hub->bNbrPorts = desc_hub->bNbrPorts; + p_hub->bPwrOn2PwrGood_2ms = desc_hub->bPwrOn2PwrGood; // May need to GET_STATUS @@ -299,22 +320,21 @@ static void config_set_port_power (tuh_xfer_t* xfer) hub_port_set_feature(daddr, hub_port, HUB_FEATURE_PORT_POWER, config_port_power_complete, 0); } -static void config_port_power_complete (tuh_xfer_t* xfer) -{ +static void config_port_power_complete (tuh_xfer_t* xfer) { TU_ASSERT(XFER_RESULT_SUCCESS == xfer->result, ); uint8_t const daddr = xfer->daddr; - hub_interface_t* p_hub = get_itf(daddr); + hub_interface_t* p_hub = get_hub_itf(daddr); - if (xfer->setup->wIndex == p_hub->port_count) - { + if (xfer->setup->wIndex == p_hub->bNbrPorts) { // All ports are power -> queue notification status endpoint and // complete the SET CONFIGURATION - TU_ASSERT( usbh_edpt_xfer(daddr, p_hub->ep_in, &p_hub->status_change, 1), ); - + if (!hub_edpt_status_xfer(daddr)) { + TU_MESS_FAILED(); + TU_BREAKPOINT(); + } usbh_driver_set_config_complete(daddr, p_hub->itf_num); - }else - { + } else { // power next port uint8_t const hub_port = (uint8_t) (xfer->setup->wIndex + 1); hub_port_set_feature(daddr, hub_port, HUB_FEATURE_PORT_POWER, config_port_power_complete, 0); @@ -324,181 +344,135 @@ static void config_port_power_complete (tuh_xfer_t* xfer) //--------------------------------------------------------------------+ // Connection Changes //--------------------------------------------------------------------+ +enum { + STATE_IDLE = 0, + STATE_HUB_STATUS, + STATE_CLEAR_CHANGE, + STATE_CHECK_CONN, + STATE_COMPLETE +}; -static void hub_port_get_status_complete (tuh_xfer_t* xfer); -static void hub_get_status_complete (tuh_xfer_t* xfer); -static void connection_clear_conn_change_complete (tuh_xfer_t* xfer); -static void connection_port_reset_complete (tuh_xfer_t* xfer); +static void process_new_status(tuh_xfer_t* xfer); // callback as response of interrupt endpoint polling -bool hub_xfer_cb(uint8_t dev_addr, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes) { - (void) xferred_bytes; // TODO can be more than 1 for hub with lots of ports +bool hub_xfer_cb(uint8_t daddr, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes) { + (void) xferred_bytes; (void) ep_addr; - TU_VERIFY(result == XFER_RESULT_SUCCESS); - hub_interface_t* p_hub = get_itf(dev_addr); + bool processed = false; // true if new status is processed - uint8_t const status_change = p_hub->status_change; - TU_LOG2(" Hub Status Change = 0x%02X\r\n", status_change); + if (result == XFER_RESULT_SUCCESS) { + hub_interface_t* p_hub = get_hub_itf(daddr); + hub_epbuf_t *p_epbuf = get_hub_epbuf(daddr); + const uint8_t status_change = p_epbuf->status_change[0]; + TU_LOG_DRV(" Hub Status Change = 0x%02X\r\n", status_change); - if ( status_change == 0 ) { - // The status change event was neither for the hub, nor for any of its ports. - // This shouldn't happen, but it does with some devices. - // Initiate the next interrupt poll here. - return hub_edpt_status_xfer(dev_addr); - } - - if (tu_bit_test(status_change, 0)) { - // Hub bit 0 is for the hub device events - if (hub_port_get_status(dev_addr, 0, &p_hub->hub_status, hub_get_status_complete, 0) == false) { - //Hub status control transfer failed, retry - hub_edpt_status_xfer(dev_addr); - } - } - else { - // Hub bits 1 to n are hub port events - for (uint8_t port=1; port <= p_hub->port_count; port++) { - if ( tu_bit_test(status_change, port) ) { - if (hub_port_get_status(dev_addr, port, &p_hub->port_status, hub_port_get_status_complete, 0) == false) { - //Hub status control transfer failed, retry - hub_edpt_status_xfer(dev_addr); + if (status_change == 0) { + // The status change event was neither for the hub, nor for any of its ports. + // This shouldn't happen, but it does with some devices. Re-Initiate the interrupt poll. + processed = false; + } else if (tu_bit_test(status_change, 0)) { + // Hub bit 0 is for the hub device events + processed = hub_get_status(daddr, p_epbuf->ctrl_buf, process_new_status, STATE_HUB_STATUS); + } else { + // Hub bits 1 to n are hub port events + for (uint8_t port=1; port <= p_hub->bNbrPorts; port++) { + if (tu_bit_test(status_change, port)) { + processed = hub_port_get_status(daddr, port, NULL, process_new_status, STATE_CLEAR_CHANGE); + break; // after completely processed one port, we will re-queue the status poll and handle next one } - break; } } } - // NOTE: next status transfer is queued by usbh.c after handling this request + // If new status event is processed: next status pool is queued by usbh.c after handled this request + // Otherwise re-queue the status poll here + if (!processed) { + TU_ASSERT(hub_edpt_status_xfer(daddr)); + } + return true; } -static void hub_clear_feature_complete_stub(tuh_xfer_t* xfer) -{ - TU_ASSERT(xfer->result == XFER_RESULT_SUCCESS, ); - hub_edpt_status_xfer(xfer->daddr); -} +static void process_new_status(tuh_xfer_t* xfer) { + const uint8_t daddr = xfer->daddr; -static void hub_get_status_complete (tuh_xfer_t* xfer) -{ - TU_ASSERT(xfer->result == XFER_RESULT_SUCCESS, ); - - uint8_t const daddr = xfer->daddr; - hub_interface_t* p_hub = get_itf(daddr); - uint8_t const port_num = (uint8_t) tu_le16toh(xfer->setup->wIndex); - TU_ASSERT(port_num == 0 , ); - - TU_LOG2("HUB Got hub status, addr = %u, status = %04x\r\n", daddr, p_hub->hub_status.change.value); - - if (p_hub->hub_status.change.local_power_source) - { - TU_LOG2("HUB Local Power Change, addr = %u\r\n", daddr); - hub_port_clear_feature(daddr, port_num, HUB_FEATURE_HUB_LOCAL_POWER_CHANGE, hub_clear_feature_complete_stub, 0); + if (xfer->result != XFER_RESULT_SUCCESS) { + TU_ASSERT(hub_edpt_status_xfer(daddr),); + return; } - else if (p_hub->hub_status.change.over_current) - { - TU_LOG1("HUB Over Current, addr = %u\r\n", daddr); - hub_port_clear_feature(daddr, port_num, HUB_FEATURE_HUB_OVER_CURRENT_CHANGE, hub_clear_feature_complete_stub, 0); + + const uint8_t port_num = (uint8_t) tu_le16toh(xfer->setup->wIndex); + hub_interface_t *p_hub = get_hub_itf(daddr); + const uintptr_t state = xfer->user_data; + bool processed = false; // true if new status is processed + + switch (state) { + case STATE_HUB_STATUS: { + hub_status_response_t hub_status = *((const hub_status_response_t *) (uintptr_t) xfer->buffer); + TU_LOG_DRV("HUB Got hub status, addr = %u, status = %04x\r\n", daddr, hub_status.change.value); + if (hub_status.change.local_power_source) { + TU_LOG_DRV(" Local Power Change\r\n"); + processed = hub_clear_feature(daddr, HUB_FEATURE_HUB_LOCAL_POWER_CHANGE, + process_new_status, STATE_COMPLETE); + } else if (hub_status.change.over_current) { + TU_LOG_DRV(" Over Current\r\n"); + processed = hub_clear_feature(daddr, HUB_FEATURE_HUB_OVER_CURRENT_CHANGE, + process_new_status, STATE_COMPLETE); + } + break; + } + + case STATE_CLEAR_CHANGE: + // Get port status complete --> clear change + if (p_hub->port_status.change.connection) { + // Connection change + // Port is powered and enabled + //TU_VERIFY(port_status.status_current.port_power && port_status.status_current.port_enable, ); + + // Acknowledge Port Connection Change + processed = hub_port_clear_feature(daddr, port_num, HUB_FEATURE_PORT_CONNECTION_CHANGE, + process_new_status, STATE_CHECK_CONN); + } else if (p_hub->port_status.change.port_enable) { + processed = hub_port_clear_feature(daddr, port_num, HUB_FEATURE_PORT_ENABLE_CHANGE, + process_new_status, STATE_COMPLETE); + } else if (p_hub->port_status.change.suspend) { + processed = hub_port_clear_feature(daddr, port_num, HUB_FEATURE_PORT_SUSPEND_CHANGE, + process_new_status, STATE_COMPLETE); + } else if (p_hub->port_status.change.over_current) { + processed = hub_port_clear_feature(daddr, port_num, HUB_FEATURE_PORT_OVER_CURRENT_CHANGE, + process_new_status, STATE_COMPLETE); + } else if (p_hub->port_status.change.reset) { + processed = hub_port_clear_feature(daddr, port_num, HUB_FEATURE_PORT_RESET_CHANGE, + process_new_status, STATE_COMPLETE); + } + break; + + case STATE_CHECK_CONN: { + const hcd_event_t event = { + .rhport = usbh_get_rhport(daddr), + .event_id = p_hub->port_status.status.connection ? HCD_EVENT_DEVICE_ATTACH : HCD_EVENT_DEVICE_REMOVE, + .connection = { + .hub_addr = daddr, + .hub_port = port_num + } + }; + hcd_event_handler(&event, false); + // skip status for attach event, usbh will do it after handled this enumeration + processed = (event.event_id == HCD_EVENT_DEVICE_ATTACH); + break; + } + + case STATE_COMPLETE: + default: + processed = false; // complete this status, queue next status + break; + } -} -static void hub_port_get_status_complete (tuh_xfer_t* xfer) -{ - TU_ASSERT(xfer->result == XFER_RESULT_SUCCESS, ); - - uint8_t const daddr = xfer->daddr; - hub_interface_t* p_hub = get_itf(daddr); - uint8_t const port_num = (uint8_t) tu_le16toh(xfer->setup->wIndex); - - // Connection change - if (p_hub->port_status.change.connection) - { - // Port is powered and enabled - //TU_VERIFY(port_status.status_current.port_power && port_status.status_current.port_enable, ); - - // Acknowledge Port Connection Change - hub_port_clear_feature(daddr, port_num, HUB_FEATURE_PORT_CONNECTION_CHANGE, connection_clear_conn_change_complete, 0); - }else - { - // Clear other port status change interrupts. TODO Not currently handled - just cleared. - if (p_hub->port_status.change.port_enable) - { - hub_port_clear_feature(daddr, port_num, HUB_FEATURE_PORT_ENABLE_CHANGE, hub_clear_feature_complete_stub, 0); - } - else if (p_hub->port_status.change.suspend) - { - hub_port_clear_feature(daddr, port_num, HUB_FEATURE_PORT_SUSPEND_CHANGE, hub_clear_feature_complete_stub, 0); - } - else if (p_hub->port_status.change.over_current) - { - hub_port_clear_feature(daddr, port_num, HUB_FEATURE_PORT_OVER_CURRENT_CHANGE, hub_clear_feature_complete_stub, 0); - } - else if (p_hub->port_status.change.reset) - { - hub_port_clear_feature(daddr, port_num, HUB_FEATURE_PORT_RESET_CHANGE, hub_clear_feature_complete_stub, 0); - } - // Other changes are: L1 state - // TODO clear change - - else - { - // prepare for next hub status - // TODO continue with status_change, or maybe we can do it again with status - hub_edpt_status_xfer(daddr); - } + if (!processed) { + TU_ASSERT(hub_edpt_status_xfer(daddr),); } } -static void connection_clear_conn_change_complete (tuh_xfer_t* xfer) -{ - TU_ASSERT(xfer->result == XFER_RESULT_SUCCESS, ); - - uint8_t const daddr = xfer->daddr; - hub_interface_t* p_hub = get_itf(daddr); - uint8_t const port_num = (uint8_t) tu_le16toh(xfer->setup->wIndex); - - if ( p_hub->port_status.status.connection ) - { - // Reset port if attach event - hub_port_reset(daddr, port_num, connection_port_reset_complete, 0); - }else - { - // submit detach event - hcd_event_t event = - { - .rhport = usbh_get_rhport(daddr), - .event_id = HCD_EVENT_DEVICE_REMOVE, - .connection = - { - .hub_addr = daddr, - .hub_port = port_num - } - }; - - hcd_event_handler(&event, false); - } -} - -static void connection_port_reset_complete (tuh_xfer_t* xfer) -{ - TU_ASSERT(xfer->result == XFER_RESULT_SUCCESS, ); - - uint8_t const daddr = xfer->daddr; - // hub_interface_t* p_hub = get_itf(daddr); - uint8_t const port_num = (uint8_t) tu_le16toh(xfer->setup->wIndex); - - // submit attach event - hcd_event_t event = - { - .rhport = usbh_get_rhport(daddr), - .event_id = HCD_EVENT_DEVICE_ATTACH, - .connection = - { - .hub_addr = daddr, - .hub_port = port_num - } - }; - - hcd_event_handler(&event, false); -} - #endif diff --git a/src/host/hub.h b/src/host/hub.h index 385efe6b2..3587f0ee3 100644 --- a/src/host/hub.h +++ b/src/host/hub.h @@ -24,17 +24,8 @@ * This file is part of the TinyUSB stack. */ -/** \ingroup group_class - * \defgroup ClassDriver_Hub Hub (Host only) - * \details Like most PC's OS, Hub support is completely hidden from Application. In fact, application cannot determine whether - * a device is mounted directly via roothub or via a hub's port. All Hub-related procedures are performed and managed - * by tinyusb stack. Unless you are trying to develop the stack itself, there are nothing else can be used by Application. - * \note Due to my laziness, only 1-level of Hub is supported. In other way, the stack cannot mount a hub via another hub. - * @{ - */ - -#ifndef _TUSB_HUB_H_ -#define _TUSB_HUB_H_ +#ifndef TUSB_HUB_H_ +#define TUSB_HUB_H_ #include "common/tusb_common.h" @@ -42,63 +33,23 @@ extern "C" { #endif -//D1...D0: Logical Power Switching Mode -//00: Ganged power switching (all ports’power at -//once) -//01: Individual port power switching -//1X: Reserved. Used only on 1.0 compliant hubs -//that implement no power switching -//D2: Identifies a Compound Device -//0: Hub is not part of a compound device. -//1: Hub is part of a compound device. -//D4...D3: Over-current Protection Mode -//00: Global Over-current Protection. The hub -//reports over-current as a summation of all -//ports’current draw, without a breakdown of -//individual port over-current status. -//01: Individual Port Over-current Protection. The -//hub reports over-current on a per-port basis. -//Each port has an over-current status. -//1X: No Over-current Protection. This option is -//allowed only for bus-powered hubs that do not -//implement over-current protection. +//--------------------------------------------------------------------+ +// Configuration +//--------------------------------------------------------------------+ + +#ifndef CFG_TUH_HUB_BUFSIZE + #define CFG_TUH_HUB_BUFSIZE 12 +#endif + +//--------------------------------------------------------------------+ // -//D6...D5: TT Think TIme -//00: TT requires at most 8 FS bit times of inter -//transaction gap on a full-/low-speed -//downstream bus. -//01: TT requires at most 16 FS bit times. -//10: TT requires at most 24 FS bit times. -//11: TT requires at most 32 FS bit times. -//D7: Port Indicators Supported -//0: Port Indicators are not supported on its -//downstream facing ports and the -//PORT_INDICATOR request has no effect. -//1: Port Indicators are supported on its -//downstream facing ports and the -//PORT_INDICATOR request controls the -//indicators. See Section 11.5.3. -//D15...D8: Reserved - -typedef struct TU_ATTR_PACKED{ - uint8_t bLength ; ///< Size of descriptor - uint8_t bDescriptorType ; ///< Other_speed_Configuration Type - uint8_t bNbrPorts; - uint16_t wHubCharacteristics; - uint8_t bPwrOn2PwrGood; - uint8_t bHubContrCurrent; - uint8_t DeviceRemovable; // bitmap each bit for a port (from bit1) - uint8_t PortPwrCtrlMask; // just for compatibility, should be 0xff -} descriptor_hub_desc_t; - -TU_VERIFY_STATIC( sizeof(descriptor_hub_desc_t) == 9, "size is not correct"); - +//--------------------------------------------------------------------+ enum { HUB_REQUEST_GET_STATUS = 0 , HUB_REQUEST_CLEAR_FEATURE = 1 , - + // 2 is reserved HUB_REQUEST_SET_FEATURE = 3 , - + // 4-5 are reserved HUB_REQUEST_GET_DESCRIPTOR = 6 , HUB_REQUEST_SET_DESCRIPTOR = 7 , HUB_REQUEST_CLEAR_TT_BUFFER = 8 , @@ -118,10 +69,10 @@ enum{ HUB_FEATURE_PORT_SUSPEND = 2, HUB_FEATURE_PORT_OVER_CURRENT = 3, HUB_FEATURE_PORT_RESET = 4, - + // 5-7 are reserved HUB_FEATURE_PORT_POWER = 8, HUB_FEATURE_PORT_LOW_SPEED = 9, - + // 10-15 are reserved HUB_FEATURE_PORT_CONNECTION_CHANGE = 16, HUB_FEATURE_PORT_ENABLE_CHANGE = 17, HUB_FEATURE_PORT_SUSPEND_CHANGE = 18, @@ -131,6 +82,41 @@ enum{ HUB_FEATURE_PORT_INDICATOR = 22 }; +enum { + HUB_CHARS_POWER_GANGED_SWITCHING = 0, + HUB_CHARS_POWER_INDIVIDUAL_SWITCHING = 1, +}; + +enum { + HUB_CHARS_OVER_CURRENT_GLOBAL = 0, + HUB_CHARS_OVER_CURRENT_INDIVIDUAL = 1, +}; + +typedef struct TU_ATTR_PACKED{ + uint8_t bLength ; ///< Size of descriptor + uint8_t bDescriptorType ; ///< Other_speed_Configuration Type + uint8_t bNbrPorts; + uint16_t wHubCharacteristics; + uint8_t bPwrOn2PwrGood; + uint8_t bHubContrCurrent; + uint8_t DeviceRemovable; // bitmap each bit for a port (from bit1) + uint8_t PortPwrCtrlMask; // just for compatibility, should be 0xff +} hub_desc_cs_t; +TU_VERIFY_STATIC(sizeof(hub_desc_cs_t) == 9, "size is not correct"); +TU_VERIFY_STATIC(CFG_TUH_HUB_BUFSIZE >= sizeof(hub_desc_cs_t), "buffer is not big enough"); + +typedef struct TU_ATTR_PACKED { + struct TU_ATTR_PACKED { + uint8_t logical_power_switching_mode : 2; // [0..1] gannged or individual power switching + uint8_t compound_device : 1; // [2] hub is part of compound device + uint8_t over_current_protect_mode : 2; // [3..4] global or individual port over-current protection + uint8_t tt_think_time : 2; // [5..6] TT think time + uint8_t port_indicator_supported : 1; // [7] port indicator supported + }; + uint8_t rsv1; +} hub_characteristics_t; +TU_VERIFY_STATIC(sizeof(hub_characteristics_t) == 2, "size is not correct"); + // data in response of HUB_REQUEST_GET_STATUS, wIndex = 0 (hub) typedef struct { union{ @@ -143,48 +129,56 @@ typedef struct { uint16_t value; } status, change; } hub_status_response_t; - TU_VERIFY_STATIC( sizeof(hub_status_response_t) == 4, "size is not correct"); // data in response of HUB_REQUEST_GET_STATUS, wIndex = Port num typedef struct { - union { + union TU_ATTR_PACKED { struct TU_ATTR_PACKED { - uint16_t connection : 1; - uint16_t port_enable : 1; - uint16_t suspend : 1; - uint16_t over_current : 1; - uint16_t reset : 1; + // Bit 0-4 are for change & status + uint16_t connection : 1; // [0] 0 = no device, 1 = device connected + uint16_t port_enable : 1; // [1] port is enabled + uint16_t suspend : 1; // [2] + uint16_t over_current : 1; // [3] over-current exists + uint16_t reset : 1; // [4] 0 = no reset, 1 = resetting - uint16_t : 3; - uint16_t port_power : 1; - uint16_t low_speed : 1; - uint16_t high_speed : 1; - uint16_t port_test_mode : 1; - uint16_t port_indicator_control : 1; - uint16_t TU_RESERVED : 3; + // From Bit 5 are for status only + uint16_t rsv5_7 : 3; // [5..7] reserved + uint16_t port_power : 1; // [8] 0 = port is off, 1 = port is on + uint16_t low_speed : 1; // [9] low speed device attached + uint16_t high_speed : 1; // [10] high speed device attached + uint16_t port_test_mode : 1; // [11] port in test mode + uint16_t port_indicator_control : 1; // [12] 0: default color, 1: indicator is software controlled + uint16_t TU_RESERVED : 3; // [13..15] reserved }; uint16_t value; } status, change; } hub_port_status_response_t; - TU_VERIFY_STATIC( sizeof(hub_port_status_response_t) == 4, "size is not correct"); -// Clear feature -bool hub_port_clear_feature (uint8_t hub_addr, uint8_t hub_port, uint8_t feature, - tuh_xfer_cb_t complete_cb, uintptr_t user_data); +//--------------------------------------------------------------------+ +// HUB API +//--------------------------------------------------------------------+ -// Set feature -bool hub_port_set_feature (uint8_t hub_addr, uint8_t hub_port, uint8_t feature, - tuh_xfer_cb_t complete_cb, uintptr_t user_data); +// Clear port feature +bool hub_port_clear_feature(uint8_t hub_addr, uint8_t hub_port, uint8_t feature, + tuh_xfer_cb_t complete_cb, uintptr_t user_data); + +// Set port feature +bool hub_port_set_feature(uint8_t hub_addr, uint8_t hub_port, uint8_t feature, + tuh_xfer_cb_t complete_cb, uintptr_t user_data); // Get port status -bool hub_port_get_status (uint8_t hub_addr, uint8_t hub_port, void* resp, - tuh_xfer_cb_t complete_cb, uintptr_t user_data); +// If hub_port != 0, resp is ignored. hub_port_get_status_local() can be used to retrieve the status +bool hub_port_get_status(uint8_t hub_addr, uint8_t hub_port, void *resp, + tuh_xfer_cb_t complete_cb, uintptr_t user_data); + +// Get port status from local cache. This does not send a request to the device +bool hub_port_get_status_local(uint8_t hub_addr, uint8_t hub_port, hub_port_status_response_t* resp); // Get status from Interrupt endpoint -bool hub_edpt_status_xfer(uint8_t dev_addr); +bool hub_edpt_status_xfer(uint8_t daddr); // Reset a port TU_ATTR_ALWAYS_INLINE static inline @@ -192,27 +186,35 @@ bool hub_port_reset(uint8_t hub_addr, uint8_t hub_port, tuh_xfer_cb_t complete_c return hub_port_set_feature(hub_addr, hub_port, HUB_FEATURE_PORT_RESET, complete_cb, user_data); } -// Clear Reset Change +// Clear Port Reset Change TU_ATTR_ALWAYS_INLINE static inline bool hub_port_clear_reset_change(uint8_t hub_addr, uint8_t hub_port, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { return hub_port_clear_feature(hub_addr, hub_port, HUB_FEATURE_PORT_RESET_CHANGE, complete_cb, user_data); } +// Get Hub status (port = 0) +TU_ATTR_ALWAYS_INLINE static inline +bool hub_get_status(uint8_t hub_addr, void* resp, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { + return hub_port_get_status(hub_addr, 0, resp, complete_cb, user_data); +} +// Clear Hub feature +TU_ATTR_ALWAYS_INLINE static inline +bool hub_clear_feature(uint8_t hub_addr, uint8_t feature, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { + return hub_port_clear_feature(hub_addr, 0, feature, complete_cb, user_data); +} //--------------------------------------------------------------------+ // Internal Class Driver API //--------------------------------------------------------------------+ bool hub_init (void); bool hub_deinit (void); bool hub_open (uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const *itf_desc, uint16_t max_len); -bool hub_set_config (uint8_t dev_addr, uint8_t itf_num); -bool hub_xfer_cb (uint8_t dev_addr, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes); +bool hub_set_config (uint8_t daddr, uint8_t itf_num); +bool hub_xfer_cb (uint8_t daddr, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes); void hub_close (uint8_t dev_addr); #ifdef __cplusplus } #endif -#endif /* _TUSB_HUB_H_ */ - -/** @} */ +#endif diff --git a/src/host/usbh.c b/src/host/usbh.c index a2994cde7..ce83977c5 100644 --- a/src/host/usbh.c +++ b/src/host/usbh.c @@ -28,13 +28,13 @@ #if CFG_TUH_ENABLED -#include "host/hcd.h" +#include "hcd.h" #include "tusb.h" -#include "host/usbh_pvt.h" +#include "usbh_pvt.h" #include "hub.h" //--------------------------------------------------------------------+ -// USBH Configuration +// Configuration //--------------------------------------------------------------------+ #ifndef CFG_TUH_TASK_QUEUE_SZ #define CFG_TUH_TASK_QUEUE_SZ 16 @@ -44,25 +44,33 @@ #define CFG_TUH_INTERFACE_MAX 8 #endif +enum { + USBH_CONTROL_RETRY_MAX = 3, +}; + //--------------------------------------------------------------------+ // Weak stubs: invoked if no strong implementation is available //--------------------------------------------------------------------+ TU_ATTR_WEAK bool hcd_deinit(uint8_t rhport) { - (void) rhport; - return false; + (void) rhport; return false; } TU_ATTR_WEAK bool hcd_configure(uint8_t rhport, uint32_t cfg_id, const void* cfg_param) { - (void) rhport; - (void) cfg_id; - (void) cfg_param; + (void) rhport; (void) cfg_id; (void) cfg_param; return false; } +TU_ATTR_WEAK void tuh_enum_descriptor_device_cb(uint8_t daddr, const tusb_desc_device_t *desc_device) { + (void) daddr; (void) desc_device; +} + +TU_ATTR_WEAK bool tuh_enum_descriptor_configuration_cb(uint8_t daddr, uint8_t cfg_index, const tusb_desc_configuration_t *desc_config) { + (void) daddr; (void) cfg_index; (void) desc_config; + return true; +} + TU_ATTR_WEAK void tuh_event_hook_cb(uint8_t rhport, uint32_t eventid, bool in_isr) { - (void) rhport; - (void) eventid; - (void) in_isr; + (void) rhport; (void) eventid; (void) in_isr; } TU_ATTR_WEAK bool hcd_dcache_clean(const void* addr, uint32_t data_size) { @@ -81,27 +89,24 @@ TU_ATTR_WEAK bool hcd_dcache_clean_invalidate(const void* addr, uint32_t data_si } //--------------------------------------------------------------------+ -// USBH-HCD common data structure +// Data Structure //--------------------------------------------------------------------+ typedef struct { - // port - uint8_t rhport; - uint8_t hub_addr; - uint8_t hub_port; + tuh_bus_info_t bus_info; - struct TU_ATTR_PACKED { - uint8_t speed : 4; // packed speed to save footprint - volatile uint8_t enumerating : 1; // enumeration is in progress, false if not connected or all interfaces are configured - uint8_t TU_RESERVED : 3; - }; -} usbh_dev0_t; - -typedef struct { - // port, must be same layout as usbh_dev0_t - uint8_t rhport; - uint8_t hub_addr; - uint8_t hub_port; - uint8_t speed; + // Device Descriptor + uint16_t bcdUSB; + uint8_t bDeviceClass; + uint8_t bDeviceSubClass; + uint8_t bDeviceProtocol; + uint8_t bMaxPacketSize0; + uint16_t idVendor; + uint16_t idProduct; + uint16_t bcdDevice; + uint8_t iManufacturer; + uint8_t iProduct; + uint8_t iSerialNumber; + uint8_t bNumConfigurations; // Device State struct TU_ATTR_PACKED { @@ -109,23 +114,9 @@ typedef struct { volatile uint8_t addressed : 1; // After SET_ADDR volatile uint8_t configured : 1; // After SET_CONFIG and all drivers are configured volatile uint8_t suspended : 1; // Bus suspended - // volatile uint8_t removing : 1; // Physically disconnected, waiting to be processed by usbh }; - // Device Descriptor - uint8_t ep0_size; - - uint16_t vid; - uint16_t pid; - - uint8_t i_manufacturer; - uint8_t i_product; - uint8_t i_serial; - - // Configuration Descriptor - // uint8_t interface_count; // bNumInterfaces alias - // Endpoint & Interface uint8_t itf2drv[CFG_TUH_INTERFACE_MAX]; // map interface number to driver (0xff is invalid) uint8_t ep2drv[CFG_TUH_ENDPOINT_MAX][2]; // map endpoint to driver ( 0xff is invalid ), can use only 4-bit each @@ -142,8 +133,63 @@ typedef struct { } usbh_device_t; +// sum of end device + hub +#define TOTAL_DEVICES (CFG_TUH_DEVICE_MAX + CFG_TUH_HUB) + +// all devices excluding zero-address +// hub address start from CFG_TUH_DEVICE_MAX+1 +// TODO: hub can has its own simpler struct to save memory +static usbh_device_t _usbh_devices[TOTAL_DEVICES]; + +// Mutex for claiming endpoint +#if OSAL_MUTEX_REQUIRED +static osal_mutex_def_t _usbh_mutexdef; +static osal_mutex_t _usbh_mutex; +#else +#define _usbh_mutex NULL +#endif + +// Spinlock for interrupt handler +static OSAL_SPINLOCK_DEF(_usbh_spin, usbh_int_set); + +// Event queue: usbh_int_set() is used as mutex in OS NONE config +OSAL_QUEUE_DEF(usbh_int_set, _usbh_qdef, CFG_TUH_TASK_QUEUE_SZ, hcd_event_t); +static osal_queue_t _usbh_q; + +// Control transfers: since most controllers do not support multiple control transfers +// on multiple devices concurrently and control transfers are not used much except for +// enumeration, we will only execute control transfers one at a time. +typedef struct { + uint8_t* buffer; + tuh_xfer_cb_t complete_cb; + uintptr_t user_data; + + volatile uint8_t stage; + uint8_t daddr; + volatile uint16_t actual_len; + uint8_t failed_count; +} usbh_ctrl_xfer_info_t; + +typedef struct { + uint8_t controller_id; // controller ID + uint8_t enumerating_daddr; // device address of the device being enumerated + uint8_t attach_debouncing_bm; // bitmask for roothub port attach debouncing + tuh_bus_info_t dev0_bus; // bus info for dev0 in enumeration + usbh_ctrl_xfer_info_t ctrl_xfer_info; // control transfer +} usbh_data_t; + +static usbh_data_t _usbh_data = { + .controller_id = TUSB_INDEX_INVALID_8, +}; + +typedef struct { + TUH_EPBUF_TYPE_DEF(tusb_control_request_t, request); + TUH_EPBUF_DEF(ctrl, CFG_TUH_ENUMERATION_BUFSIZE); +} usbh_epbuf_t; +CFG_TUH_MEM_SECTION static usbh_epbuf_t _usbh_epbuf; + //--------------------------------------------------------------------+ -// MACRO CONSTANT TYPEDEF +// Class Driver //--------------------------------------------------------------------+ #if CFG_TUSB_DEBUG >= CFG_TUH_LOG_LEVEL #define DRIVER_NAME(_name) _name @@ -188,6 +234,18 @@ static usbh_class_driver_t const usbh_class_drivers[] = { }, #endif + #if CFG_TUH_MIDI + { + .name = DRIVER_NAME("MIDI"), + .init = midih_init, + .deinit = midih_deinit, + .open = midih_open, + .set_config = midih_set_config, + .xfer_cb = midih_xfer_cb, + .close = midih_close + }, + #endif + #if CFG_TUH_HUB { .name = DRIVER_NAME("HUB"), @@ -214,11 +272,10 @@ static usbh_class_driver_t const usbh_class_drivers[] = { }; enum { BUILTIN_DRIVER_COUNT = TU_ARRAY_SIZE(usbh_class_drivers) }; -enum { CONFIG_NUM = 1 }; // default to use configuration 1 // Additional class drivers implemented by application -tu_static usbh_class_driver_t const * _app_driver = NULL; -tu_static uint8_t _app_driver_count = 0; +static usbh_class_driver_t const * _app_driver = NULL; +static uint8_t _app_driver_count = 0; #define TOTAL_DRIVER_COUNT (_app_driver_count + BUILTIN_DRIVER_COUNT) @@ -235,66 +292,21 @@ static inline usbh_class_driver_t const *get_driver(uint8_t drv_id) { } //--------------------------------------------------------------------+ -// INTERNAL OBJECT & FUNCTION DECLARATION +// Function Inline and Prototypes //--------------------------------------------------------------------+ - -// sum of end device + hub -#define TOTAL_DEVICES (CFG_TUH_DEVICE_MAX + CFG_TUH_HUB) - -static uint8_t _usbh_controller = TUSB_INDEX_INVALID_8; - -// Device with address = 0 for enumeration -static usbh_dev0_t _dev0; - -// all devices excluding zero-address -// hub address start from CFG_TUH_DEVICE_MAX+1 -// TODO: hub can has its own simpler struct to save memory -static usbh_device_t _usbh_devices[TOTAL_DEVICES]; - -// Mutex for claiming endpoint -#if OSAL_MUTEX_REQUIRED - static osal_mutex_def_t _usbh_mutexdef; - static osal_mutex_t _usbh_mutex; -#else - #define _usbh_mutex NULL -#endif - -// Event queue -// usbh_int_set is used as mutex in OS NONE config -OSAL_QUEUE_DEF(usbh_int_set, _usbh_qdef, CFG_TUH_TASK_QUEUE_SZ, hcd_event_t); -static osal_queue_t _usbh_q; - -// Control transfers: since most controllers do not support multiple control transfers -// on multiple devices concurrently and control transfers are not used much except for -// enumeration, we will only execute control transfers one at a time. -static struct { - uint8_t* buffer; - tuh_xfer_cb_t complete_cb; - uintptr_t user_data; - - uint8_t daddr; - volatile uint8_t stage; - volatile uint16_t actual_len; -} _ctrl_xfer; - -typedef struct { - TUH_EPBUF_TYPE_DEF(tusb_control_request_t, request); - TUH_EPBUF_DEF(ctrl, CFG_TUH_ENUMERATION_BUFSIZE); -} usbh_epbuf_t; - -CFG_TUH_MEM_SECTION static usbh_epbuf_t _usbh_epbuf; - -//------------- Helper Function -------------// +static bool enum_new_device(hcd_event_t* event); +static void process_removed_device(uint8_t rhport, uint8_t hub_addr, uint8_t hub_port); +static bool usbh_edpt_control_open(uint8_t dev_addr, uint8_t max_packet_size); +static bool usbh_control_xfer_cb (uint8_t daddr, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes); TU_ATTR_ALWAYS_INLINE static inline usbh_device_t* get_device(uint8_t dev_addr) { TU_VERIFY(dev_addr > 0 && dev_addr <= TOTAL_DEVICES, NULL); return &_usbh_devices[dev_addr-1]; } -static bool enum_new_device(hcd_event_t* event); -static void process_removing_device(uint8_t rhport, uint8_t hub_addr, uint8_t hub_port); -static bool usbh_edpt_control_open(uint8_t dev_addr, uint8_t max_packet_size); -static bool usbh_control_xfer_cb (uint8_t daddr, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes); +TU_ATTR_ALWAYS_INLINE static inline bool is_hub_addr(uint8_t daddr) { + return (CFG_TUH_HUB > 0) && (daddr > CFG_TUH_DEVICE_MAX); +} TU_ATTR_ALWAYS_INLINE static inline bool queue_event(hcd_event_t const * event, bool in_isr) { TU_ASSERT(osal_queue_send(_usbh_q, event, in_isr)); @@ -302,40 +314,102 @@ TU_ATTR_ALWAYS_INLINE static inline bool queue_event(hcd_event_t const * event, return true; } +TU_ATTR_ALWAYS_INLINE static inline void _control_set_xfer_stage(uint8_t stage) { + if (_usbh_data.ctrl_xfer_info.stage != stage) { + (void) osal_mutex_lock(_usbh_mutex, OSAL_TIMEOUT_WAIT_FOREVER); + _usbh_data.ctrl_xfer_info.stage = stage; + (void) osal_mutex_unlock(_usbh_mutex); + } +} + +TU_ATTR_ALWAYS_INLINE static inline bool usbh_setup_send(uint8_t daddr, const uint8_t setup_packet[8]) { + const uint8_t rhport = usbh_get_rhport(daddr); + const bool ret = hcd_setup_send(rhport, daddr, setup_packet); + if (!ret) { + _control_set_xfer_stage(CONTROL_STAGE_IDLE); + } + return ret; +} + +TU_ATTR_ALWAYS_INLINE static inline void usbh_device_close(uint8_t rhport, uint8_t daddr) { + hcd_device_close(rhport, daddr); + + // abort any ongoing control transfer + if (daddr == _usbh_data.ctrl_xfer_info.daddr) { + _control_set_xfer_stage(CONTROL_STAGE_IDLE); + } + + // invalidate if enumerating + if (daddr == _usbh_data.enumerating_daddr) { + _usbh_data.enumerating_daddr = TUSB_INDEX_INVALID_8; + } +} + //--------------------------------------------------------------------+ // Device API //--------------------------------------------------------------------+ - bool tuh_mounted(uint8_t dev_addr) { usbh_device_t *dev = get_device(dev_addr); TU_VERIFY(dev); return dev->configured; } +bool tuh_connected(uint8_t daddr) { + if (daddr == 0) { + return _usbh_data.enumerating_daddr == 0; + } else { + const usbh_device_t* dev = get_device(daddr); + return dev && dev->connected; + } +} + bool tuh_vid_pid_get(uint8_t dev_addr, uint16_t *vid, uint16_t *pid) { *vid = *pid = 0; usbh_device_t const *dev = get_device(dev_addr); - TU_VERIFY(dev && dev->addressed && dev->vid != 0); + TU_VERIFY(dev && dev->addressed && dev->idVendor != 0); - *vid = dev->vid; - *pid = dev->pid; + *vid = dev->idVendor; + *pid = dev->idProduct; return true; } -tusb_speed_t tuh_speed_get(uint8_t dev_addr) { - usbh_device_t *dev = get_device(dev_addr); - return (tusb_speed_t) (dev ? get_device(dev_addr)->speed : _dev0.speed); +bool tuh_descriptor_get_device_local(uint8_t daddr, tusb_desc_device_t* desc_device) { + usbh_device_t *dev = get_device(daddr); + TU_VERIFY(dev && desc_device); + + desc_device->bLength = sizeof(tusb_desc_device_t); + desc_device->bDescriptorType = TUSB_DESC_DEVICE; + desc_device->bcdUSB = dev->bcdUSB; + desc_device->bDeviceClass = dev->bDeviceClass; + desc_device->bDeviceSubClass = dev->bDeviceSubClass; + desc_device->bDeviceProtocol = dev->bDeviceProtocol; + desc_device->bMaxPacketSize0 = dev->bMaxPacketSize0; + desc_device->idVendor = dev->idVendor; + desc_device->idProduct = dev->idProduct; + desc_device->bcdDevice = dev->bcdDevice; + desc_device->iManufacturer = dev->iManufacturer; + desc_device->iProduct = dev->iProduct; + desc_device->iSerialNumber = dev->iSerialNumber; + desc_device->bNumConfigurations = dev->bNumConfigurations; + + return true; +} + +tusb_speed_t tuh_speed_get(uint8_t daddr) { + tuh_bus_info_t bus_info; + tuh_bus_info_get(daddr, &bus_info); + return bus_info.speed; } bool tuh_rhport_is_active(uint8_t rhport) { - return _usbh_controller == rhport; + return _usbh_data.controller_id == rhport; } bool tuh_rhport_reset_bus(uint8_t rhport, bool active) { TU_VERIFY(tuh_rhport_is_active(rhport)); - if ( active ) { + if (active) { hcd_port_reset(rhport); } else { hcd_port_reset_end(rhport); @@ -346,7 +420,6 @@ bool tuh_rhport_reset_bus(uint8_t rhport, bool active) { //--------------------------------------------------------------------+ // PUBLIC API (Parameter Verification is required) //--------------------------------------------------------------------+ - bool tuh_configure(uint8_t rhport, uint32_t cfg_id, const void *cfg_param) { return hcd_configure(rhport, cfg_id, cfg_param); } @@ -358,26 +431,45 @@ static void clear_device(usbh_device_t* dev) { } bool tuh_inited(void) { - return _usbh_controller != TUSB_INDEX_INVALID_8; + return _usbh_data.controller_id != TUSB_INDEX_INVALID_8; } bool tuh_rhport_init(uint8_t rhport, const tusb_rhport_init_t* rh_init) { if (tuh_rhport_is_active(rhport)) { return true; // skip if already initialized } - - TU_LOG_USBH("USBH init on controller %u, speed = %s\r\n", rhport, - rh_init->speed == TUSB_SPEED_HIGH ? "High" : "Full"); +#if CFG_TUSB_DEBUG >= CFG_TUH_LOG_LEVEL + char const* speed_str = 0; + switch (rh_init->speed) { + case TUSB_SPEED_HIGH: + speed_str = "High"; + break; + case TUSB_SPEED_FULL: + speed_str = "Full"; + break; + case TUSB_SPEED_LOW: + speed_str = "Low"; + break; + case TUSB_SPEED_AUTO: + speed_str = "Auto"; + break; + default: + break; + } + TU_LOG_USBH("USBH init on controller %u, speed = %s\r\n", rhport, speed_str); +#endif // Init host stack if not already if (!tuh_inited()) { + TU_LOG_INT_USBH(sizeof(usbh_data_t)); TU_LOG_INT_USBH(sizeof(usbh_device_t)); TU_LOG_INT_USBH(sizeof(hcd_event_t)); - TU_LOG_INT_USBH(sizeof(_ctrl_xfer)); TU_LOG_INT_USBH(sizeof(tuh_xfer_t)); TU_LOG_INT_USBH(sizeof(tu_fifo_t)); TU_LOG_INT_USBH(sizeof(tu_edpt_stream_t)); + osal_spin_init(&_usbh_spin); + // Event queue _usbh_q = osal_queue_create(&_usbh_qdef); TU_ASSERT(_usbh_q != NULL); @@ -394,9 +486,11 @@ bool tuh_rhport_init(uint8_t rhport, const tusb_rhport_init_t* rh_init) { } // Device - tu_memclr(&_dev0, sizeof(_dev0)); tu_memclr(_usbh_devices, sizeof(_usbh_devices)); - tu_memclr(&_ctrl_xfer, sizeof(_ctrl_xfer)); + tu_memclr(&_usbh_data, sizeof(_usbh_data)); + + _usbh_data.controller_id = TUSB_INDEX_INVALID_8; + _usbh_data.enumerating_daddr = TUSB_INDEX_INVALID_8; for (uint8_t i = 0; i < TOTAL_DEVICES; i++) { clear_device(&_usbh_devices[i]); @@ -413,7 +507,7 @@ bool tuh_rhport_init(uint8_t rhport, const tusb_rhport_init_t* rh_init) { } // Init host controller - _usbh_controller = rhport; + _usbh_data.controller_id = rhport; TU_ASSERT(hcd_init(rhport, rh_init)); hcd_int_enable(rhport); @@ -421,15 +515,17 @@ bool tuh_rhport_init(uint8_t rhport, const tusb_rhport_init_t* rh_init) { } bool tuh_deinit(uint8_t rhport) { - if (!tuh_rhport_is_active(rhport)) return true; + if (!tuh_rhport_is_active(rhport)) { + return true; + } // deinit host controller hcd_int_disable(rhport); hcd_deinit(rhport); - _usbh_controller = TUSB_INDEX_INVALID_8; + _usbh_data.controller_id = TUSB_INDEX_INVALID_8; // "unplug" all devices on this rhport (hub_addr = 0, hub_port = 0) - process_removing_device(rhport, 0, 0); + process_removed_device(rhport, 0, 0); // deinit host stack if no controller is active if (!tuh_inited()) { @@ -467,13 +563,11 @@ bool tuh_task_event_ready(void) { * This should be called periodically within the mainloop or rtos thread. * @code - int main(void) - { + int main(void) { application_init(); tusb_init(0, TUSB_ROLE_HOST); - while(1) // the mainloop - { + while(1) { // the mainloop application_code(); tuh_task(); // tinyusb host task } @@ -484,55 +578,46 @@ void tuh_task_ext(uint32_t timeout_ms, bool in_isr) { (void) in_isr; // not implemented yet // Skip if stack is not initialized - if (!tuh_inited()) return; + if (!tuh_inited()) { + return; + } // Loop until there is no more events in the queue while (1) { hcd_event_t event; - if (!osal_queue_receive(_usbh_q, &event, timeout_ms)) return; + if (!osal_queue_receive(_usbh_q, &event, timeout_ms)) { return; } switch (event.event_id) { case HCD_EVENT_DEVICE_ATTACH: - // due to the shared control buffer, we must complete enumerating one device before enumerating another one. + // due to the shared control buffer, we must fully complete enumerating one device first. // TODO better to have an separated queue for newly attached devices - if (_dev0.enumerating) { - // Some device can cause multiple duplicated attach events - // drop current enumerating and start over for a proper port reset - if (event.rhport == _dev0.rhport && event.connection.hub_addr == _dev0.hub_addr && - event.connection.hub_port == _dev0.hub_port) { - // abort/cancel current enumeration and start new one - TU_LOG1("[%u:] USBH Device Attach (duplicated)\r\n", event.rhport); - tuh_edpt_abort_xfer(0, 0); - enum_new_device(&event); - } else { - TU_LOG_USBH("[%u:] USBH Defer Attach until current enumeration complete\r\n", event.rhport); - - bool is_empty = osal_queue_empty(_usbh_q); - queue_event(&event, in_isr); - - if (is_empty) { - // Exit if this is the only event in the queue, otherwise we may loop forever - return; - } - } - } else { - TU_LOG1("[%u:] USBH Device Attach\r\n", event.rhport); - _dev0.enumerating = 1; + if (_usbh_data.enumerating_daddr == TUSB_INDEX_INVALID_8) { + // New device attached and we are ready + TU_LOG_USBH("[%u:] USBH Device Attach\r\n", event.rhport); + _usbh_data.enumerating_daddr = 0; // enumerate new device with address 0 enum_new_device(&event); + } else { + // currently enumerating another device + TU_LOG_USBH("[%u:] USBH Defer Attach until current enumeration complete\r\n", event.rhport); + const bool is_empty = osal_queue_empty(_usbh_q); + queue_event(&event, in_isr); + if (is_empty) { + return; // Exit if this is the only event in the queue, otherwise we loop forever + } } break; case HCD_EVENT_DEVICE_REMOVE: TU_LOG_USBH("[%u:%u:%u] USBH DEVICE REMOVED\r\n", event.rhport, event.connection.hub_addr, event.connection.hub_port); - process_removing_device(event.rhport, event.connection.hub_addr, event.connection.hub_port); - - #if CFG_TUH_HUB - // TODO remove - if (event.connection.hub_addr != 0 && event.connection.hub_port != 0) { - // done with hub, waiting for next data on status pipe - (void) hub_edpt_status_xfer(event.connection.hub_addr); + if (_usbh_data.enumerating_daddr == 0 && + event.rhport == _usbh_data.dev0_bus.rhport && + event.connection.hub_addr == _usbh_data.dev0_bus.hub_addr && + event.connection.hub_port == _usbh_data.dev0_bus.hub_port) { + // dev0 is unplugged while enumerating (not yet assigned an address) + usbh_device_close(_usbh_data.dev0_bus.rhport, 0); + } else { + process_removed_device(event.rhport, event.connection.hub_addr, event.connection.hub_port); } - #endif break; case HCD_EVENT_XFER_COMPLETE: { @@ -540,7 +625,8 @@ void tuh_task_ext(uint32_t timeout_ms, bool in_isr) { uint8_t const epnum = tu_edpt_number(ep_addr); uint8_t const ep_dir = (uint8_t) tu_edpt_dir(ep_addr); - TU_LOG_USBH("on EP %02X with %u bytes: %s\r\n", ep_addr, (unsigned int) event.xfer_complete.len, tu_str_xfer_result[event.xfer_complete.result]); + TU_LOG_USBH("[:%u] on EP %02X with %u bytes: %s\r\n", + event.dev_addr, ep_addr, (unsigned int) event.xfer_complete.len, tu_str_xfer_result[event.xfer_complete.result]); if (event.dev_addr == 0) { // device 0 only has control endpoint @@ -579,7 +665,7 @@ void tuh_task_ext(uint32_t timeout_ms, bool in_isr) { uint8_t drv_id = dev->ep2drv[epnum][ep_dir]; usbh_class_driver_t const* driver = get_driver(drv_id); if (driver) { - TU_LOG_USBH("%s xfer callback\r\n", driver->name); + TU_LOG_USBH(" %s xfer callback\r\n", driver->name); driver->xfer_cb(event.dev_addr, ep_addr, (xfer_result_t) event.xfer_complete.result, event.xfer_complete.len); } else { @@ -618,56 +704,46 @@ static void _control_blocking_complete_cb(tuh_xfer_t* xfer) { // TODO timeout_ms is not supported yet bool tuh_control_xfer (tuh_xfer_t* xfer) { - // EP0 with setup packet - TU_VERIFY(xfer->ep_addr == 0 && xfer->setup); - - // Check if device is still connected (enumerating for dev0) + TU_VERIFY(xfer->ep_addr == 0 && xfer->setup); // EP0 with setup packet const uint8_t daddr = xfer->daddr; - if (daddr == 0) { - TU_VERIFY(_dev0.enumerating); - } else { - const usbh_device_t* dev = get_device(daddr); - TU_VERIFY(dev && dev->connected); - } + TU_VERIFY(tuh_connected(daddr)); - // pre-check to help reducing mutex lock - TU_VERIFY(_ctrl_xfer.stage == CONTROL_STAGE_IDLE); + usbh_ctrl_xfer_info_t* ctrl_info = &_usbh_data.ctrl_xfer_info; + + TU_VERIFY(ctrl_info->stage == CONTROL_STAGE_IDLE); // pre-check to help reducing mutex lock (void) osal_mutex_lock(_usbh_mutex, OSAL_TIMEOUT_WAIT_FOREVER); - - bool const is_idle = (_ctrl_xfer.stage == CONTROL_STAGE_IDLE); + bool const is_idle = (ctrl_info->stage == CONTROL_STAGE_IDLE); if (is_idle) { - _ctrl_xfer.stage = CONTROL_STAGE_SETUP; - _ctrl_xfer.daddr = daddr; - _ctrl_xfer.actual_len = 0; + ctrl_info->stage = CONTROL_STAGE_SETUP; + ctrl_info->daddr = daddr; + ctrl_info->actual_len = 0; + ctrl_info->failed_count = 0; - _ctrl_xfer.buffer = xfer->buffer; - _ctrl_xfer.complete_cb = xfer->complete_cb; - _ctrl_xfer.user_data = xfer->user_data; - _usbh_epbuf.request = (*xfer->setup); + ctrl_info->buffer = xfer->buffer; + ctrl_info->complete_cb = xfer->complete_cb; + ctrl_info->user_data = xfer->user_data; + _usbh_epbuf.request = (*xfer->setup); } - (void) osal_mutex_unlock(_usbh_mutex); TU_VERIFY(is_idle); - const uint8_t rhport = usbh_get_rhport(daddr); - - TU_LOG_USBH("[%u:%u] %s: ", rhport, daddr, + TU_LOG_USBH("[%u:%u] %s: ", usbh_get_rhport(daddr), daddr, (xfer->setup->bmRequestType_bit.type == TUSB_REQ_TYPE_STANDARD && xfer->setup->bRequest <= TUSB_REQ_SYNCH_FRAME) ? tu_str_std_request[xfer->setup->bRequest] : "Class Request"); TU_LOG_BUF_USBH(xfer->setup, 8); if (xfer->complete_cb) { - TU_ASSERT( hcd_setup_send(rhport, daddr, (uint8_t const*) &_usbh_epbuf.request) ); + TU_ASSERT(usbh_setup_send(daddr, (uint8_t const *) &_usbh_epbuf.request)); }else { // blocking if complete callback is not provided // change callback to internal blocking, and result as user argument volatile xfer_result_t result = XFER_RESULT_INVALID; // use user_data to point to xfer_result_t - _ctrl_xfer.user_data = (uintptr_t) &result; - _ctrl_xfer.complete_cb = _control_blocking_complete_cb; + ctrl_info->user_data = (uintptr_t) &result; + ctrl_info->complete_cb = _control_blocking_complete_cb; - TU_ASSERT( hcd_setup_send(rhport, daddr, (uint8_t*) &_usbh_epbuf.request) ); + TU_ASSERT(usbh_setup_send(daddr, (uint8_t const *) &_usbh_epbuf.request)); while (result == XFER_RESULT_INVALID) { // Note: this can be called within an callback ie. part of tuh_task() @@ -683,20 +759,15 @@ bool tuh_control_xfer (tuh_xfer_t* xfer) { *((xfer_result_t*) xfer->user_data) = result; } xfer->result = result; - xfer->actual_len = _ctrl_xfer.actual_len; + xfer->actual_len = ctrl_info->actual_len; } return true; } -TU_ATTR_ALWAYS_INLINE static inline void _set_control_xfer_stage(uint8_t stage) { - (void) osal_mutex_lock(_usbh_mutex, OSAL_TIMEOUT_WAIT_FOREVER); - _ctrl_xfer.stage = stage; - (void) osal_mutex_unlock(_usbh_mutex); -} - static void _control_xfer_complete(uint8_t daddr, xfer_result_t result) { TU_LOG_USBH("\r\n"); + usbh_ctrl_xfer_info_t* ctrl_info = &_usbh_data.ctrl_xfer_info; // duplicate xfer since user can execute control transfer within callback tusb_control_request_t const request = _usbh_epbuf.request; @@ -705,13 +776,13 @@ static void _control_xfer_complete(uint8_t daddr, xfer_result_t result) { .ep_addr = 0, .result = result, .setup = &request, - .actual_len = (uint32_t) _ctrl_xfer.actual_len, - .buffer = _ctrl_xfer.buffer, - .complete_cb = _ctrl_xfer.complete_cb, - .user_data = _ctrl_xfer.user_data + .actual_len = (uint32_t) ctrl_info->actual_len, + .buffer = ctrl_info->buffer, + .complete_cb = ctrl_info->complete_cb, + .user_data = ctrl_info->user_data }; - _set_control_xfer_stage(CONTROL_STAGE_IDLE); + _control_set_xfer_stage(CONTROL_STAGE_IDLE); if (xfer_temp.complete_cb) { xfer_temp.complete_cb(&xfer_temp); @@ -723,54 +794,77 @@ static bool usbh_control_xfer_cb (uint8_t daddr, uint8_t ep_addr, xfer_result_t const uint8_t rhport = usbh_get_rhport(daddr); tusb_control_request_t const * request = &_usbh_epbuf.request; + usbh_ctrl_xfer_info_t* ctrl_info = &_usbh_data.ctrl_xfer_info; - if (XFER_RESULT_SUCCESS != result) { - TU_LOG_USBH("[%u:%u] Control %s, xferred_bytes = %" PRIu32 "\r\n", rhport, daddr, result == XFER_RESULT_STALLED ? "STALLED" : "FAILED", xferred_bytes); - TU_LOG_BUF_USBH(request, 8); + switch (result) { + case XFER_RESULT_STALLED: + TU_LOG_USBH("[%u:%u] Control STALLED, xferred_bytes = %" PRIu32 "\r\n", rhport, daddr, xferred_bytes); + TU_LOG_BUF_USBH(request, 8); + _control_xfer_complete(daddr, result); + break; - // terminate transfer if any stage failed - _control_xfer_complete(daddr, result); - }else { - switch(_ctrl_xfer.stage) { - case CONTROL_STAGE_SETUP: - if (request->wLength) { - // DATA stage: initial data toggle is always 1 - _set_control_xfer_stage(CONTROL_STAGE_DATA); - TU_ASSERT( hcd_edpt_xfer(rhport, daddr, tu_edpt_addr(0, request->bmRequestType_bit.direction), _ctrl_xfer.buffer, request->wLength) ); - return true; - } - TU_ATTR_FALLTHROUGH; + case XFER_RESULT_FAILED: + if (tuh_connected(daddr) && ctrl_info->failed_count < USBH_CONTROL_RETRY_MAX) { + TU_LOG_USBH("[%u:%u] Control FAILED %u/%u, retrying\r\n", rhport, daddr, ctrl_info->failed_count+1, USBH_CONTROL_RETRY_MAX); + (void) osal_mutex_lock(_usbh_mutex, OSAL_TIMEOUT_WAIT_FOREVER); + ctrl_info->stage = CONTROL_STAGE_SETUP; + ctrl_info->failed_count++; + ctrl_info->actual_len = 0; // reset actual_len + (void) osal_mutex_unlock(_usbh_mutex); - case CONTROL_STAGE_DATA: - if (request->wLength) { - TU_LOG_USBH("[%u:%u] Control data:\r\n", rhport, daddr); - TU_LOG_MEM_USBH(_ctrl_xfer.buffer, xferred_bytes, 2); - } + TU_ASSERT(usbh_setup_send(daddr, (uint8_t const *) request)); + } else { + TU_LOG_USBH("[%u:%u] Control FAILED, xferred_bytes = %" PRIu32 "\r\n", rhport, daddr, xferred_bytes); + TU_LOG_BUF_USBH(request, 8); + _control_xfer_complete(daddr, result); + } + break; - _ctrl_xfer.actual_len = (uint16_t) xferred_bytes; + case XFER_RESULT_SUCCESS: + switch(ctrl_info->stage) { + case CONTROL_STAGE_SETUP: + if (request->wLength) { + // DATA stage: initial data toggle is always 1 + _control_set_xfer_stage(CONTROL_STAGE_DATA); + const uint8_t ep_data = tu_edpt_addr(0, request->bmRequestType_bit.direction); + TU_ASSERT(hcd_edpt_xfer(rhport, daddr, ep_data, ctrl_info->buffer, request->wLength)); + return true; + } + TU_ATTR_FALLTHROUGH; - // ACK stage: toggle is always 1 - _set_control_xfer_stage(CONTROL_STAGE_ACK); - TU_ASSERT( hcd_edpt_xfer(rhport, daddr, tu_edpt_addr(0, 1 - request->bmRequestType_bit.direction), NULL, 0) ); - break; + case CONTROL_STAGE_DATA: + if (request->wLength) { + TU_LOG_USBH("[%u:%u] Control data:\r\n", rhport, daddr); + TU_LOG_MEM_USBH(ctrl_info->buffer, xferred_bytes, 2); + } + ctrl_info->actual_len = (uint16_t) xferred_bytes; - case CONTROL_STAGE_ACK: { - // Abort all pending transfers if SET_CONFIGURATION request - // NOTE: should we force closing all non-control endpoints in the future? - if (request->bRequest == TUSB_REQ_SET_CONFIGURATION && request->bmRequestType == 0x00) { - for(uint8_t epnum=1; epnumbmRequestType_bit.direction); + TU_ASSERT(hcd_edpt_xfer(rhport, daddr, ep_status, NULL, 0)); + break; + + case CONTROL_STAGE_ACK: { + // Abort all pending transfers if SET_CONFIGURATION request + // NOTE: should we force closing all non-control endpoints in the future? + if (request->bRequest == TUSB_REQ_SET_CONFIGURATION && request->bmRequestType == 0x00) { + for(uint8_t epnum=1; epnumdaddr && ctrl_info->stage != CONTROL_STAGE_IDLE); hcd_edpt_abort_xfer(rhport, daddr, ep_addr); - _set_control_xfer_stage(CONTROL_STAGE_IDLE); // reset control transfer state to idle + _control_set_xfer_stage(CONTROL_STAGE_IDLE); // reset control transfer state to idle } else { usbh_device_t* dev = get_device(daddr); TU_VERIFY(dev); TU_VERIFY(dev->ep_status[epnum][dir].busy); // non-control skip if not busy - hcd_edpt_abort_xfer(dev->rhport, daddr, ep_addr); - - // mark as ready and release endpoint if transfer is aborted + // abort then mark as ready and release endpoint + hcd_edpt_abort_xfer(dev->bus_info.rhport, daddr, ep_addr); dev->ep_status[epnum][dir].busy = false; tu_edpt_release(&dev->ep_status[epnum][dir], _usbh_mutex); } @@ -829,9 +922,10 @@ bool tuh_edpt_abort_xfer(uint8_t daddr, uint8_t ep_addr) { // USBH API For Class Driver //--------------------------------------------------------------------+ -uint8_t usbh_get_rhport(uint8_t dev_addr) { - usbh_device_t *dev = get_device(dev_addr); - return dev ? dev->rhport : _dev0.rhport; +uint8_t usbh_get_rhport(uint8_t daddr) { + tuh_bus_info_t bus_info; + tuh_bus_info_get(daddr, &bus_info); + return bus_info.rhport; } uint8_t *usbh_get_enum_buf(void) { @@ -841,18 +935,25 @@ uint8_t *usbh_get_enum_buf(void) { void usbh_int_set(bool enabled) { // TODO all host controller if multiple are used since they shared the same event queue if (enabled) { - hcd_int_enable(_usbh_controller); + hcd_int_enable(_usbh_data.controller_id); } else { - hcd_int_disable(_usbh_controller); + hcd_int_disable(_usbh_data.controller_id); } } +void usbh_spin_lock(bool in_isr) { + osal_spin_lock(&_usbh_spin, in_isr); +} + +void usbh_spin_unlock(bool in_isr) { + osal_spin_unlock(&_usbh_spin, in_isr); +} + void usbh_defer_func(osal_task_func_t func, void *param, bool in_isr) { hcd_event_t event = { 0 }; event.event_id = USBH_EVENT_FUNC_CALL; event.func_call.func = func; event.func_call.param = param; - queue_event(&event, in_isr); } @@ -891,7 +992,6 @@ bool usbh_edpt_release(uint8_t dev_addr, uint8_t ep_addr) { } // Submit an transfer -// TODO call usbh_edpt_release if failed bool usbh_edpt_xfer_with_callback(uint8_t dev_addr, uint8_t ep_addr, uint8_t* buffer, uint16_t total_bytes, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { (void) complete_cb; @@ -918,7 +1018,7 @@ bool usbh_edpt_xfer_with_callback(uint8_t dev_addr, uint8_t ep_addr, uint8_t* bu dev->ep_callback[epnum][dir].user_data = user_data; #endif - if (hcd_edpt_xfer(dev->rhport, dev_addr, ep_addr, buffer, total_bytes)) { + if (hcd_edpt_xfer(dev->bus_info.rhport, dev_addr, ep_addr, buffer, total_bytes)) { TU_LOG_USBH("OK\r\n"); return true; } else { @@ -946,10 +1046,16 @@ static bool usbh_edpt_control_open(uint8_t dev_addr, uint8_t max_packet_size) { } bool tuh_edpt_open(uint8_t dev_addr, tusb_desc_endpoint_t const* desc_ep) { - TU_ASSERT(tu_edpt_validate(desc_ep, tuh_speed_get(dev_addr))); + TU_ASSERT(tu_edpt_validate(desc_ep, tuh_speed_get(dev_addr), true)); return hcd_edpt_open(usbh_get_rhport(dev_addr), dev_addr, desc_ep); } +bool tuh_edpt_close(uint8_t daddr, uint8_t ep_addr) { + TU_VERIFY(0 != tu_edpt_number(ep_addr)); // cannot close EP0 + tuh_edpt_abort_xfer(daddr, ep_addr); // abort any pending transfer + return hcd_edpt_close(usbh_get_rhport(daddr), daddr, ep_addr); +} + bool usbh_edpt_busy(uint8_t dev_addr, uint8_t ep_addr) { usbh_device_t* dev = get_device(dev_addr); TU_VERIFY(dev); @@ -964,31 +1070,30 @@ bool usbh_edpt_busy(uint8_t dev_addr, uint8_t ep_addr) { // HCD Event Handler //--------------------------------------------------------------------+ -void hcd_devtree_get_info(uint8_t dev_addr, hcd_devtree_info_t* devtree_info) { - usbh_device_t const* dev = get_device(dev_addr); +bool tuh_bus_info_get(uint8_t daddr, tuh_bus_info_t* bus_info) { + usbh_device_t const* dev = get_device(daddr); if (dev) { - devtree_info->rhport = dev->rhport; - devtree_info->hub_addr = dev->hub_addr; - devtree_info->hub_port = dev->hub_port; - devtree_info->speed = dev->speed; + *bus_info = dev->bus_info; } else { - devtree_info->rhport = _dev0.rhport; - devtree_info->hub_addr = _dev0.hub_addr; - devtree_info->hub_port = _dev0.hub_port; - devtree_info->speed = _dev0.speed; + *bus_info = _usbh_data.dev0_bus; } + return true; } TU_ATTR_FAST_FUNC void hcd_event_handler(hcd_event_t const* event, bool in_isr) { switch (event->event_id) { + case HCD_EVENT_DEVICE_ATTACH: case HCD_EVENT_DEVICE_REMOVE: - // FIXME device remove from a hub need an HCD API for hcd to free up endpoint - // mark device as removing to prevent further xfer before the event is processed in usbh task + // Attach debouncing on roothub: skip attach/remove while debouncing delay + if (event->connection.hub_addr == 0) { + if (tu_bit_test(_usbh_data.attach_debouncing_bm, event->rhport)) { + return; + } - // Check if dev0 is removed - if ((event->rhport == _dev0.rhport) && (event->connection.hub_addr == _dev0.hub_addr) && - (event->connection.hub_port == _dev0.hub_port)) { - _dev0.enumerating = 0; + if (event->event_id == HCD_EVENT_DEVICE_ATTACH) { + // No debouncing, set flag if attach event + _usbh_data.attach_debouncing_bm |= TU_BIT(event->rhport); + } } break; @@ -1004,8 +1109,9 @@ TU_ATTR_FAST_FUNC void hcd_event_handler(hcd_event_t const* event, bool in_isr) // generic helper to get a descriptor // if blocking, user_data is pointed to xfer_result -static bool _get_descriptor(uint8_t daddr, uint8_t type, uint8_t index, uint16_t language_id, void* buffer, uint16_t len, - tuh_xfer_cb_t complete_cb, uintptr_t user_data) { +TU_ATTR_ALWAYS_INLINE static inline +bool _get_descriptor(uint8_t daddr, uint8_t type, uint8_t index, uint16_t language_id, void* buffer, uint16_t len, + tuh_xfer_cb_t complete_cb, uintptr_t user_data) { tusb_control_request_t const request = { .bmRequestType_bit = { .recipient = TUSB_REQ_RCPT_DEVICE, @@ -1046,7 +1152,6 @@ bool tuh_descriptor_get_configuration(uint8_t daddr, uint8_t index, void* buffer } //------------- String Descriptor -------------// - bool tuh_descriptor_get_string(uint8_t daddr, uint8_t index, uint16_t language_id, void* buffer, uint16_t len, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { return _get_descriptor(daddr, TUSB_DESC_STRING, index, language_id, buffer, len, complete_cb, user_data); @@ -1057,24 +1162,24 @@ bool tuh_descriptor_get_manufacturer_string(uint8_t daddr, uint16_t language_id, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { usbh_device_t const* dev = get_device(daddr); - TU_VERIFY(dev && dev->i_manufacturer); - return tuh_descriptor_get_string(daddr, dev->i_manufacturer, language_id, buffer, len, complete_cb, user_data); + TU_VERIFY(dev && dev->iManufacturer); + return tuh_descriptor_get_string(daddr, dev->iManufacturer, language_id, buffer, len, complete_cb, user_data); } // Get product string descriptor bool tuh_descriptor_get_product_string(uint8_t daddr, uint16_t language_id, void* buffer, uint16_t len, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { usbh_device_t const* dev = get_device(daddr); - TU_VERIFY(dev && dev->i_product); - return tuh_descriptor_get_string(daddr, dev->i_product, language_id, buffer, len, complete_cb, user_data); + TU_VERIFY(dev && dev->iProduct); + return tuh_descriptor_get_string(daddr, dev->iProduct, language_id, buffer, len, complete_cb, user_data); } // Get serial string descriptor bool tuh_descriptor_get_serial_string(uint8_t daddr, uint16_t language_id, void* buffer, uint16_t len, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { usbh_device_t const* dev = get_device(daddr); - TU_VERIFY(dev && dev->i_serial); - return tuh_descriptor_get_string(daddr, dev->i_serial, language_id, buffer, len, complete_cb, user_data); + TU_VERIFY(dev && dev->iSerialNumber); + return tuh_descriptor_get_string(daddr, dev->iSerialNumber, language_id, buffer, len, complete_cb, user_data); } // Get HID report descriptor @@ -1105,6 +1210,33 @@ bool tuh_descriptor_get_hid_report(uint8_t daddr, uint8_t itf_num, uint8_t desc_ return tuh_control_xfer(&xfer); } +bool tuh_address_set(uint8_t daddr, uint8_t new_addr, + tuh_xfer_cb_t complete_cb, uintptr_t user_data) { + TU_LOG_USBH("Set Address = %d\r\n", new_addr); + const tusb_control_request_t request = { + .bmRequestType_bit = { + .recipient = TUSB_REQ_RCPT_DEVICE, + .type = TUSB_REQ_TYPE_STANDARD, + .direction = TUSB_DIR_OUT + }, + .bRequest = TUSB_REQ_SET_ADDRESS, + .wValue = tu_htole16(new_addr), + .wIndex = 0, + .wLength = 0 + }; + tuh_xfer_t xfer = { + .daddr = daddr, + .ep_addr = 0, + .setup = &request, + .buffer = NULL, + .complete_cb = complete_cb, + .user_data = user_data + }; + + TU_ASSERT(tuh_control_xfer(&xfer)); + return true; +} + bool tuh_configuration_set(uint8_t daddr, uint8_t config_num, tuh_xfer_cb_t complete_cb, uintptr_t user_data) { TU_LOG_USBH("Set Configuration = %d\r\n", config_num); @@ -1157,128 +1289,63 @@ bool tuh_interface_set(uint8_t daddr, uint8_t itf_num, uint8_t itf_alt, return tuh_control_xfer(&xfer); } -//--------------------------------------------------------------------+ -// Descriptor Sync -//--------------------------------------------------------------------+ - -#define _CONTROL_SYNC_API(_async_func, ...) \ - xfer_result_t result = XFER_RESULT_INVALID;\ - TU_VERIFY(_async_func(__VA_ARGS__, NULL, (uintptr_t) &result), XFER_RESULT_TIMEOUT); \ - return (uint8_t) result - -uint8_t tuh_descriptor_get_sync(uint8_t daddr, uint8_t type, uint8_t index, - void* buffer, uint16_t len) { - _CONTROL_SYNC_API(tuh_descriptor_get, daddr, type, index, buffer, len); -} - -uint8_t tuh_descriptor_get_device_sync(uint8_t daddr, void* buffer, uint16_t len) { - _CONTROL_SYNC_API(tuh_descriptor_get_device, daddr, buffer, len); -} - -uint8_t tuh_descriptor_get_configuration_sync(uint8_t daddr, uint8_t index, - void* buffer, uint16_t len) { - _CONTROL_SYNC_API(tuh_descriptor_get_configuration, daddr, index, buffer, len); -} - -uint8_t tuh_descriptor_get_hid_report_sync(uint8_t daddr, uint8_t itf_num, uint8_t desc_type, uint8_t index, - void* buffer, uint16_t len) { - _CONTROL_SYNC_API(tuh_descriptor_get_hid_report, daddr, itf_num, desc_type, index, buffer, len); -} - -uint8_t tuh_descriptor_get_string_sync(uint8_t daddr, uint8_t index, uint16_t language_id, - void* buffer, uint16_t len) { - _CONTROL_SYNC_API(tuh_descriptor_get_string, daddr, index, language_id, buffer, len); -} - -uint8_t tuh_descriptor_get_manufacturer_string_sync(uint8_t daddr, uint16_t language_id, - void* buffer, uint16_t len) { - _CONTROL_SYNC_API(tuh_descriptor_get_manufacturer_string, daddr, language_id, buffer, len); -} - -uint8_t tuh_descriptor_get_product_string_sync(uint8_t daddr, uint16_t language_id, - void* buffer, uint16_t len) { - _CONTROL_SYNC_API(tuh_descriptor_get_product_string, daddr, language_id, buffer, len); -} - -uint8_t tuh_descriptor_get_serial_string_sync(uint8_t daddr, uint16_t language_id, - void* buffer, uint16_t len) { - _CONTROL_SYNC_API(tuh_descriptor_get_serial_string, daddr, language_id, buffer, len); -} - //--------------------------------------------------------------------+ // Detaching //--------------------------------------------------------------------+ - -TU_ATTR_ALWAYS_INLINE static inline bool is_hub_addr(uint8_t daddr) { - return (CFG_TUH_HUB > 0) && (daddr > CFG_TUH_DEVICE_MAX); -} - -//static void mark_removing_device_isr(uint8_t rhport, uint8_t hub_addr, uint8_t hub_port) { -// for (uint8_t dev_id = 0; dev_id < TOTAL_DEVICES; dev_id++) { -// usbh_device_t *dev = &_usbh_devices[dev_id]; -// uint8_t const daddr = dev_id + 1; -// -// // hub_addr = 0 means roothub, hub_port = 0 means all devices of downstream hub -// if (dev->rhport == rhport && dev->connected && -// (hub_addr == 0 || dev->hub_addr == hub_addr) && -// (hub_port == 0 || dev->hub_port == hub_port)) { -// if (is_hub_addr(daddr)) { -// // If the device itself is a usb hub, mark all downstream devices. -// // FIXME recursive calls -// mark_removing_device_isr(rhport, daddr, 0); -// } -// -// dev->removing = 1; -// } -// } -//} - // a device unplugged from rhport:hub_addr:hub_port -static void process_removing_device(uint8_t rhport, uint8_t hub_addr, uint8_t hub_port) { - //------------- find the all devices (star-network) under port that is unplugged -------------// - // TODO mark as disconnected in ISR, also handle dev0 - uint32_t removing_hubs = 0; +static void process_removed_device(uint8_t rhport, uint8_t hub_addr, uint8_t hub_port) { + // Find the all devices (star-network) under port that is unplugged + #if CFG_TUH_HUB + uint8_t removing_hubs[CFG_TUH_HUB] = { 0 }; + #endif + do { for (uint8_t dev_id = 0; dev_id < TOTAL_DEVICES; dev_id++) { usbh_device_t* dev = &_usbh_devices[dev_id]; uint8_t const daddr = dev_id + 1; // hub_addr = 0 means roothub, hub_port = 0 means all devices of downstream hub - if (dev->rhport == rhport && dev->connected && - (hub_addr == 0 || dev->hub_addr == hub_addr) && - (hub_port == 0 || dev->hub_port == hub_port)) { + if (dev->bus_info.rhport == rhport && dev->connected && + (hub_addr == 0 || dev->bus_info.hub_addr == hub_addr) && + (hub_port == 0 || dev->bus_info.hub_port == hub_port)) { TU_LOG_USBH("[%u:%u:%u] unplugged address = %u\r\n", rhport, hub_addr, hub_port, daddr); + #if CFG_TUH_HUB if (is_hub_addr(daddr)) { TU_LOG_USBH(" is a HUB device %u\r\n", daddr); - removing_hubs |= TU_BIT(dev_id - CFG_TUH_DEVICE_MAX); - } else { + removing_hubs[dev_id - CFG_TUH_DEVICE_MAX] = 1; + } else + #endif + { // Invoke callback before closing driver (maybe call it later ?) - if (tuh_umount_cb) tuh_umount_cb(daddr); + if (tuh_umount_cb) { + tuh_umount_cb(daddr); + } } // Close class driver for (uint8_t drv_id = 0; drv_id < TOTAL_DRIVER_COUNT; drv_id++) { usbh_class_driver_t const* driver = get_driver(drv_id); - if (driver) driver->close(daddr); + if (driver) { + driver->close(daddr); + } } - hcd_device_close(rhport, daddr); + usbh_device_close(rhport, daddr); clear_device(dev); - - // abort on-going control xfer on this device if any - if (_ctrl_xfer.daddr == daddr) _set_control_xfer_stage(CONTROL_STAGE_IDLE); } } - // if removing a hub, we need to remove its downstream devices - #if CFG_TUH_HUB - if (removing_hubs == 0) break; +#if CFG_TUH_HUB + // if a hub is removed, we need to remove all of its downstream devices + if (tu_mem_is_zero(removing_hubs, CFG_TUH_HUB)) { + break; + } // find a marked hub to process for (uint8_t h_id = 0; h_id < CFG_TUH_HUB; h_id++) { - if (tu_bit_test(removing_hubs, h_id)) { - removing_hubs &= ~TU_BIT(h_id); + if (removing_hubs[h_id]) { + removing_hubs[h_id] = 0; // update hub_addr and hub_port for next loop hub_addr = h_id + 1 + CFG_TUH_DEVICE_MAX; @@ -1286,200 +1353,366 @@ static void process_removing_device(uint8_t rhport, uint8_t hub_addr, uint8_t hu break; } } - #else - (void) removing_hubs; +#else break; - #endif +#endif + } while(1); } //--------------------------------------------------------------------+ // Enumeration Process -// is a lengthy process with a series of control transfer to configure -// newly attached device. +// is a lengthy process with a series of control transfer to configure newly attached device. // NOTE: due to the shared control buffer, we must complete enumerating // one device before enumerating another one. //--------------------------------------------------------------------+ - -enum { - ENUM_RESET_DELAY_MS = 50, // USB specs: 10 to 50ms - ENUM_DEBOUNCING_DELAY_MS = 450, // when plug/unplug a device, physical connection can be bouncing and may - // generate a series of attach/detach event. This delay wait for stable connection +enum { // USB 2.0 specs 7.1.7 for timing + ENUM_DEBOUNCING_DELAY_MS = 150, // T(ATTDB) minimum 100 ms for stable connection + ENUM_RESET_ROOT_DELAY_MS = 50, // T(DRSTr) minimum 50 ms for reset from root port + ENUM_RESET_HUB_DELAY_MS = 20, // T(DRST) 10-20 ms for hub reset + ENUM_RESET_RECOVERY_DELAY_MS = 10, // T(RSTRCY) minimum 10 ms for reset recovery + ENUM_SET_ADDRESS_RECOVERY_DELAY_MS = 2, // USB 2.0 Spec 9.2.6.3 min is 2 ms }; enum { ENUM_IDLE, - ENUM_RESET_1, // 1st reset when attached - //ENUM_HUB_GET_STATUS_1, - ENUM_HUB_CLEAR_RESET_1, - ENUM_ADDR0_DEVICE_DESC, - ENUM_RESET_2, // 2nd reset before set address (not used) - ENUM_HUB_GET_STATUS_2, - ENUM_HUB_CLEAR_RESET_2, - ENUM_SET_ADDR, + ENUM_HUB_RERSET, + ENUM_HUB_GET_STATUS_AFTER_RESET, + ENUM_HUB_CLEAR_RESET, + ENUM_HUB_CLEAR_RESET_COMPLETE, + ENUM_ADDR0_DEVICE_DESC, + ENUM_SET_ADDR, ENUM_GET_DEVICE_DESC, + ENUM_GET_STRING_LANGUAGE_ID_LEN, + ENUM_GET_STRING_LANGUAGE_ID, + ENUM_GET_STRING_MANUFACTURER_LEN, + ENUM_GET_STRING_MANUFACTURER, + ENUM_GET_STRING_PRODUCT_LEN, + ENUM_GET_STRING_PRODUCT, + ENUM_GET_STRING_SERIAL_LEN, + ENUM_GET_STRING_SERIAL, ENUM_GET_9BYTE_CONFIG_DESC, ENUM_GET_FULL_CONFIG_DESC, ENUM_SET_CONFIG, ENUM_CONFIG_DRIVER }; -static bool enum_request_set_addr(void); -static bool _parse_configuration_descriptor (uint8_t dev_addr, tusb_desc_configuration_t const* desc_cfg); +static uint8_t enum_get_new_address(bool is_hub); +static bool enum_parse_configuration_desc (uint8_t dev_addr, tusb_desc_configuration_t const* desc_cfg); static void enum_full_complete(void); +static void process_enumeration(tuh_xfer_t* xfer); + +// start a new enumeration process +static bool enum_new_device(hcd_event_t* event) { + tuh_bus_info_t* dev0_bus = &_usbh_data.dev0_bus; + dev0_bus->rhport = event->rhport; + dev0_bus->hub_addr = event->connection.hub_addr; + dev0_bus->hub_port = event->connection.hub_port; + + // wait until device connection is stable TODO non blocking + tusb_time_delay_ms_api(ENUM_DEBOUNCING_DELAY_MS); + + // clear roothub debouncing delay + if (dev0_bus->hub_addr == 0) { + _usbh_data.attach_debouncing_bm &= (uint8_t) ~TU_BIT(dev0_bus->rhport); + } + + if (dev0_bus->hub_addr == 0) { + // connected directly to roothub + // USB bus not active and frame number is not available yet. + // need to depend on tusb_time_millis_api() TODO non blocking + + if (!hcd_port_connect_status(dev0_bus->rhport)) { + TU_LOG_USBH("Device unplugged while debouncing\r\n"); + enum_full_complete(); + return true; + } + + // reset device + hcd_port_reset(dev0_bus->rhport); + tusb_time_delay_ms_api(ENUM_RESET_ROOT_DELAY_MS); + hcd_port_reset_end(dev0_bus->rhport); + + if (!hcd_port_connect_status(dev0_bus->rhport)) { + // device unplugged while delaying + enum_full_complete(); + return true; + } + + dev0_bus->speed = hcd_port_speed_get(dev0_bus->rhport); + TU_LOG_USBH("%s Speed\r\n", tu_str_speed[dev0_bus->speed]); + + // fake transfer to kick-off the enumeration process + tuh_xfer_t xfer; + xfer.daddr = 0; + xfer.result = XFER_RESULT_SUCCESS; + xfer.user_data = ENUM_ADDR0_DEVICE_DESC; + process_enumeration(&xfer); + } + #if CFG_TUH_HUB + else { + // connected via hub + TU_VERIFY(dev0_bus->hub_port != 0); + TU_ASSERT(hub_port_get_status(dev0_bus->hub_addr, dev0_bus->hub_port, NULL, + process_enumeration, ENUM_HUB_RERSET)); + } + #endif // hub + + return true; +} // process device enumeration static void process_enumeration(tuh_xfer_t* xfer) { - // Retry a few times with transfers in enumeration since device can be unstable when starting up - enum { - ATTEMPT_COUNT_MAX = 3, - ATTEMPT_DELAY_MS = 100 - }; + // Retry a few times while enumerating since device can be unstable when starting up static uint8_t failed_count = 0; + if (XFER_RESULT_FAILED == xfer->result) { + enum { + ATTEMPT_COUNT_MAX = 3, + ATTEMPT_DELAY_MS = 100 + }; - if (XFER_RESULT_SUCCESS != xfer->result) { // retry if not reaching max attempt - bool retry = _dev0.enumerating && (failed_count < ATTEMPT_COUNT_MAX); - if ( retry ) { - failed_count++; + failed_count++; + bool retry = (_usbh_data.enumerating_daddr != TUSB_INDEX_INVALID_8) && (failed_count < ATTEMPT_COUNT_MAX); + if (retry) { tusb_time_delay_ms_api(ATTEMPT_DELAY_MS); // delay a bit - TU_LOG1("Enumeration attempt %u\r\n", failed_count); + TU_LOG_USBH("Enumeration attempt %u/%u\r\n", failed_count+1, ATTEMPT_COUNT_MAX); retry = tuh_control_xfer(xfer); } if (!retry) { - enum_full_complete(); + enum_full_complete(); // complete as failed } - return; } failed_count = 0; uint8_t const daddr = xfer->daddr; uintptr_t const state = xfer->user_data; + usbh_device_t* dev = get_device(daddr); + tuh_bus_info_t* dev0_bus = &_usbh_data.dev0_bus; + if (daddr > 0) { + TU_ASSERT(dev,); + } + uint16_t langid = 0x0409; // default is English switch (state) { #if CFG_TUH_HUB - //case ENUM_HUB_GET_STATUS_1: break; - - case ENUM_HUB_CLEAR_RESET_1: { + case ENUM_HUB_RERSET: { hub_port_status_response_t port_status; - memcpy(&port_status, _usbh_epbuf.ctrl, sizeof(hub_port_status_response_t)); + hub_port_get_status_local(dev0_bus->hub_addr, dev0_bus->hub_port, &port_status); if (!port_status.status.connection) { - // device unplugged while delaying, nothing else to do + TU_LOG_USBH("Device unplugged from hub while debouncing\r\n"); enum_full_complete(); return; } - _dev0.speed = (port_status.status.high_speed) ? TUSB_SPEED_HIGH : - (port_status.status.low_speed) ? TUSB_SPEED_LOW : TUSB_SPEED_FULL; - - // Acknowledge Port Reset Change - if (port_status.change.reset) { - hub_port_clear_reset_change(_dev0.hub_addr, _dev0.hub_port, - process_enumeration, ENUM_ADDR0_DEVICE_DESC); - } + TU_ASSERT(hub_port_reset(dev0_bus->hub_addr, dev0_bus->hub_port, process_enumeration, ENUM_HUB_GET_STATUS_AFTER_RESET),); break; } - case ENUM_HUB_GET_STATUS_2: - tusb_time_delay_ms_api(ENUM_RESET_DELAY_MS); - TU_ASSERT(hub_port_get_status(_dev0.hub_addr, _dev0.hub_port, _usbh_epbuf.ctrl, - process_enumeration, ENUM_HUB_CLEAR_RESET_2),); - break; + case ENUM_HUB_GET_STATUS_AFTER_RESET: { + tusb_time_delay_ms_api(ENUM_RESET_HUB_DELAY_MS); // wait for reset to take effect - case ENUM_HUB_CLEAR_RESET_2: { + // get status to check for reset change + TU_ASSERT(hub_port_get_status(dev0_bus->hub_addr, dev0_bus->hub_port, NULL, process_enumeration, ENUM_HUB_CLEAR_RESET),); + break; + } + + case ENUM_HUB_CLEAR_RESET: { hub_port_status_response_t port_status; - memcpy(&port_status, _usbh_epbuf.ctrl, sizeof(hub_port_status_response_t)); + hub_port_get_status_local(dev0_bus->hub_addr, dev0_bus->hub_port, &port_status); - // Acknowledge Port Reset Change if Reset Successful if (port_status.change.reset) { - TU_ASSERT(hub_port_clear_reset_change(_dev0.hub_addr, _dev0.hub_port, - process_enumeration, ENUM_SET_ADDR),); + // Acknowledge Port Reset Change + TU_ASSERT(hub_port_clear_reset_change(dev0_bus->hub_addr, dev0_bus->hub_port, process_enumeration, ENUM_HUB_CLEAR_RESET_COMPLETE),); + } else { + // maybe retry if reset change not set but we need timeout to prevent infinite loop + // TU_ASSERT(hub_port_get_status(dev0_bus->hub_addr, dev0_bus->hub_port, NULL, process_enumeration, ENUM_HUB_CLEAR_RESET_COMPLETE),); } + break; } + + case ENUM_HUB_CLEAR_RESET_COMPLETE: { + hub_port_status_response_t port_status; + hub_port_get_status_local(dev0_bus->hub_addr, dev0_bus->hub_port, &port_status); + + if (!port_status.status.connection) { + TU_LOG_USBH("Device unplugged from hub (not addressed yet)\r\n"); + enum_full_complete(); + return; + } + + dev0_bus->speed = (port_status.status.high_speed) ? TUSB_SPEED_HIGH : + (port_status.status.low_speed) ? TUSB_SPEED_LOW : TUSB_SPEED_FULL; + + TU_ATTR_FALLTHROUGH; + } #endif case ENUM_ADDR0_DEVICE_DESC: { + tusb_time_delay_ms_api(ENUM_RESET_RECOVERY_DELAY_MS); // reset recovery + // TODO probably doesn't need to open/close each enumeration uint8_t const addr0 = 0; TU_ASSERT(usbh_edpt_control_open(addr0, 8),); - // Get first 8 bytes of device descriptor for Control Endpoint size + // Get first 8 bytes of device descriptor for control endpoint size TU_LOG_USBH("Get 8 byte of Device Descriptor\r\n"); TU_ASSERT(tuh_descriptor_get_device(addr0, _usbh_epbuf.ctrl, 8, process_enumeration, ENUM_SET_ADDR),); break; } -#if 0 - case ENUM_RESET_2: - // TODO not used by now, but may be needed for some devices !? - // Reset device again before Set Address - TU_LOG_USBH("Port reset2 \r\n"); - if (_dev0.hub_addr == 0) { - // connected directly to roothub - hcd_port_reset( _dev0.rhport ); - tusb_time_delay_ms_api(RESET_DELAY); // TODO may not work for no-OS on MCU that require reset_end() since - // sof of controller may not running while resetting - hcd_port_reset_end(_dev0.rhport); - // TODO: fall through to SET ADDRESS, refactor later - } -#if CFG_TUH_HUB - else { - // after RESET_DELAY the hub_port_reset() already complete - TU_ASSERT( hub_port_reset(_dev0.hub_addr, _dev0.hub_port, - process_enumeration, ENUM_HUB_GET_STATUS_2), ); - break; - } -#endif - TU_ATTR_FALLTHROUGH; -#endif + case ENUM_SET_ADDR: { + // Due to physical debouncing, some devices can cause multiple attaches (actually reset) without detach event + // Force remove currently mounted with the same bus info (rhport, hub addr, hub port) if exists + process_removed_device(dev0_bus->rhport, dev0_bus->hub_addr, dev0_bus->hub_port); - case ENUM_SET_ADDR: - enum_request_set_addr(); - break; - - case ENUM_GET_DEVICE_DESC: { - // Allow 2ms for address recovery time, Ref USB Spec 9.2.6.3 - tusb_time_delay_ms_api(2); - - const uint8_t new_addr = (uint8_t) tu_le16toh(xfer->setup->wValue); + const tusb_desc_device_t *desc_device = (const tusb_desc_device_t *) _usbh_epbuf.ctrl; + const uint8_t new_addr = enum_get_new_address(desc_device->bDeviceClass == TUSB_CLASS_HUB); + TU_ASSERT(new_addr != 0,); usbh_device_t* new_dev = get_device(new_addr); - TU_ASSERT(new_dev,); - new_dev->addressed = 1; + new_dev->bus_info = *dev0_bus; + new_dev->connected = 1; + new_dev->bMaxPacketSize0 = desc_device->bMaxPacketSize0; - // Close device 0 - hcd_device_close(_dev0.rhport, 0); - - // open control pipe for new address - TU_ASSERT(usbh_edpt_control_open(new_addr, new_dev->ep0_size),); - - // Get full device descriptor - TU_LOG_USBH("Get Device Descriptor\r\n"); - TU_ASSERT(tuh_descriptor_get_device(new_addr, _usbh_epbuf.ctrl, sizeof(tusb_desc_device_t), - process_enumeration, ENUM_GET_9BYTE_CONFIG_DESC),); + TU_ASSERT(tuh_address_set(0, new_addr, process_enumeration, ENUM_GET_DEVICE_DESC),); break; } + case ENUM_GET_DEVICE_DESC: { + tusb_time_delay_ms_api(ENUM_SET_ADDRESS_RECOVERY_DELAY_MS); // set address recovery + + const uint8_t new_addr = (uint8_t) tu_le16toh(xfer->setup->wValue); + usbh_device_t* new_dev = get_device(new_addr); + TU_ASSERT(new_dev,); + new_dev->addressed = 1; + _usbh_data.enumerating_daddr = new_addr; + + usbh_device_close(dev0_bus->rhport, 0); // close dev0 + + TU_ASSERT(usbh_edpt_control_open(new_addr, new_dev->bMaxPacketSize0),); // open new control endpoint + + TU_LOG_USBH("Get Device Descriptor\r\n"); + TU_ASSERT(tuh_descriptor_get_device(new_addr, _usbh_epbuf.ctrl, sizeof(tusb_desc_device_t), + process_enumeration, ENUM_GET_STRING_LANGUAGE_ID_LEN),); + break; + } + + // For string descriptor (langid, manufacturer, product, serila): always get the first 2 bytes + // to determine the length first. otherwise, some device may have buffer overflow. + case ENUM_GET_STRING_LANGUAGE_ID_LEN: { + // save the received device descriptor + tusb_desc_device_t const *desc_device = (tusb_desc_device_t const *) _usbh_epbuf.ctrl; + dev->bcdUSB = desc_device->bcdUSB; + dev->bDeviceClass = desc_device->bDeviceClass; + dev->bDeviceSubClass = desc_device->bDeviceSubClass; + dev->bDeviceProtocol = desc_device->bDeviceProtocol; + dev->bMaxPacketSize0 = desc_device->bMaxPacketSize0; + dev->idVendor = desc_device->idVendor; + dev->idProduct = desc_device->idProduct; + dev->bcdDevice = desc_device->bcdDevice; + dev->iManufacturer = desc_device->iManufacturer; + dev->iProduct = desc_device->iProduct; + dev->iSerialNumber = desc_device->iSerialNumber; + dev->bNumConfigurations = desc_device->bNumConfigurations; + + tuh_enum_descriptor_device_cb(daddr, desc_device); // callback + tuh_descriptor_get_string_langid(daddr, _usbh_epbuf.ctrl, 2, + process_enumeration, ENUM_GET_STRING_LANGUAGE_ID); + break; + } + + case ENUM_GET_STRING_LANGUAGE_ID: { + const uint8_t str_len = xfer->buffer[0]; + tuh_descriptor_get_string_langid(daddr, _usbh_epbuf.ctrl, str_len, + process_enumeration, ENUM_GET_STRING_MANUFACTURER_LEN); + break; + } + + case ENUM_GET_STRING_MANUFACTURER_LEN: { + const tusb_desc_string_t* desc_langid = (const tusb_desc_string_t *) _usbh_epbuf.ctrl; + if (desc_langid->bLength >= 4) { + langid = tu_le16toh(desc_langid->utf16le[0]); // previous request is langid + } + if (dev->iManufacturer != 0) { + tuh_descriptor_get_string(daddr, dev->iManufacturer, langid, _usbh_epbuf.ctrl, 2, + process_enumeration, ENUM_GET_STRING_MANUFACTURER); + break; + }else { + TU_ATTR_FALLTHROUGH; + } + } + + case ENUM_GET_STRING_MANUFACTURER: { + if (dev->iManufacturer != 0) { + langid = tu_le16toh(xfer->setup->wIndex); // langid from length's request + const uint8_t str_len = xfer->buffer[0]; + tuh_descriptor_get_string(daddr, dev->iManufacturer, langid, _usbh_epbuf.ctrl, str_len, + process_enumeration, ENUM_GET_STRING_PRODUCT_LEN); + break; + } else { + TU_ATTR_FALLTHROUGH; + } + } + + case ENUM_GET_STRING_PRODUCT_LEN: + if (dev->iProduct != 0) { + if (state == ENUM_GET_STRING_PRODUCT_LEN) { + langid = tu_le16toh(xfer->setup->wIndex); // get langid from previous setup packet if not fall through + } + tuh_descriptor_get_string(daddr, dev->iProduct, langid, _usbh_epbuf.ctrl, 2, + process_enumeration, ENUM_GET_STRING_PRODUCT); + break; + } else { + TU_ATTR_FALLTHROUGH; + } + + case ENUM_GET_STRING_PRODUCT: { + if (dev->iProduct != 0) { + langid = tu_le16toh(xfer->setup->wIndex); // langid from length's request + const uint8_t str_len = xfer->buffer[0]; + tuh_descriptor_get_string(daddr, dev->iProduct, langid, _usbh_epbuf.ctrl, str_len, + process_enumeration, ENUM_GET_STRING_SERIAL_LEN); + break; + } else { + TU_ATTR_FALLTHROUGH; + } + } + + case ENUM_GET_STRING_SERIAL_LEN: + if (dev->iSerialNumber != 0) { + if (state == ENUM_GET_STRING_SERIAL_LEN) { + langid = tu_le16toh(xfer->setup->wIndex); // get langid from previous setup packet if not fall through + } + tuh_descriptor_get_string(daddr, dev->iSerialNumber, langid, _usbh_epbuf.ctrl, 2, + process_enumeration, ENUM_GET_STRING_SERIAL); + break; + } else { + TU_ATTR_FALLTHROUGH; + } + + case ENUM_GET_STRING_SERIAL: { + if (dev->iSerialNumber != 0) { + langid = tu_le16toh(xfer->setup->wIndex); // langid from length's request + const uint8_t str_len = xfer->buffer[0]; + tuh_descriptor_get_string(daddr, dev->iSerialNumber, langid, _usbh_epbuf.ctrl, str_len, + process_enumeration, ENUM_GET_9BYTE_CONFIG_DESC); + break; + } else { + TU_ATTR_FALLTHROUGH; + } + } + case ENUM_GET_9BYTE_CONFIG_DESC: { - tusb_desc_device_t const* desc_device = (tusb_desc_device_t const*) _usbh_epbuf.ctrl; - usbh_device_t* dev = get_device(daddr); - TU_ASSERT(dev,); - - dev->vid = desc_device->idVendor; - dev->pid = desc_device->idProduct; - dev->i_manufacturer = desc_device->iManufacturer; - dev->i_product = desc_device->iProduct; - dev->i_serial = desc_device->iSerialNumber; - // Get 9-byte for total length - uint8_t const config_idx = CONFIG_NUM - 1; - TU_LOG_USBH("Get Configuration[0] Descriptor (9 bytes)\r\n"); + uint8_t const config_idx = 0; + TU_LOG_USBH("Get Configuration[%u] Descriptor (9 bytes)\r\n", config_idx); TU_ASSERT(tuh_descriptor_get_configuration(daddr, config_idx, _usbh_epbuf.ctrl, 9, process_enumeration, ENUM_GET_FULL_CONFIG_DESC),); break; @@ -1489,34 +1722,40 @@ static void process_enumeration(tuh_xfer_t* xfer) { uint8_t const* desc_config = _usbh_epbuf.ctrl; // Use offsetof to avoid pointer to the odd/misaligned address - uint16_t const total_len = tu_le16toh( - tu_unaligned_read16(desc_config + offsetof(tusb_desc_configuration_t, wTotalLength))); + uint16_t const total_len = tu_le16toh(tu_unaligned_read16(desc_config + offsetof(tusb_desc_configuration_t, wTotalLength))); // TODO not enough buffer to hold configuration descriptor TU_ASSERT(total_len <= CFG_TUH_ENUMERATION_BUFSIZE,); // Get full configuration descriptor - uint8_t const config_idx = CONFIG_NUM - 1; - TU_LOG_USBH("Get Configuration[0] Descriptor\r\n"); + uint8_t const config_idx = (uint8_t) tu_le16toh(xfer->setup->wIndex); + TU_LOG_USBH("Get Configuration[%u] Descriptor\r\n", config_idx); TU_ASSERT(tuh_descriptor_get_configuration(daddr, config_idx, _usbh_epbuf.ctrl, total_len, process_enumeration, ENUM_SET_CONFIG),); break; } - case ENUM_SET_CONFIG: - TU_ASSERT(tuh_configuration_set(daddr, CONFIG_NUM, process_enumeration, ENUM_CONFIG_DRIVER),); + case ENUM_SET_CONFIG: { + uint8_t config_idx = (uint8_t) tu_le16toh(xfer->setup->wIndex); + if (tuh_enum_descriptor_configuration_cb(daddr, config_idx, (const tusb_desc_configuration_t*) _usbh_epbuf.ctrl)) { + TU_ASSERT(tuh_configuration_set(daddr, config_idx+1, process_enumeration, ENUM_CONFIG_DRIVER),); + } else { + config_idx++; + TU_ASSERT(config_idx < dev->bNumConfigurations,); + TU_LOG_USBH("Get Configuration[%u] Descriptor (9 bytes)\r\n", config_idx); + TU_ASSERT(tuh_descriptor_get_configuration(daddr, config_idx, _usbh_epbuf.ctrl, 9, + process_enumeration, ENUM_GET_FULL_CONFIG_DESC),); + } break; + } case ENUM_CONFIG_DRIVER: { TU_LOG_USBH("Device configured\r\n"); - usbh_device_t* dev = get_device(daddr); - TU_ASSERT(dev,); - dev->configured = 1; // Parse configuration & set up drivers // driver_open() must not make any usb transfer - TU_ASSERT(_parse_configuration_descriptor(daddr, (tusb_desc_configuration_t*) _usbh_epbuf.ctrl),); + TU_ASSERT(enum_parse_configuration_desc(daddr, (tusb_desc_configuration_t*) _usbh_epbuf.ctrl),); // Start the Set Configuration process for interfaces (itf = TUSB_INDEX_INVALID_8) // Since driver can perform control transfer within its set_config, this is done asynchronously. @@ -1527,65 +1766,12 @@ static void process_enumeration(tuh_xfer_t* xfer) { } default: - // stop enumeration if unknown state - enum_full_complete(); + enum_full_complete(); // stop enumeration if unknown state break; } } - - -static bool enum_new_device(hcd_event_t* event) { - _dev0.rhport = event->rhport; - _dev0.hub_addr = event->connection.hub_addr; - _dev0.hub_port = event->connection.hub_port; - - if (_dev0.hub_addr == 0) { - // connected directly to roothub - hcd_port_reset(_dev0.rhport); - - // Since we are in middle of rhport reset, frame number is not available yet. - // need to depend on tusb_time_millis_api() - tusb_time_delay_ms_api(ENUM_RESET_DELAY_MS); - - hcd_port_reset_end(_dev0.rhport); - - // wait until device connection is stable TODO non blocking - tusb_time_delay_ms_api(ENUM_DEBOUNCING_DELAY_MS); - - // device unplugged while delaying - if (!hcd_port_connect_status(_dev0.rhport)) { - enum_full_complete(); - return true; - } - - _dev0.speed = hcd_port_speed_get(_dev0.rhport); - TU_LOG_USBH("%s Speed\r\n", tu_str_speed[_dev0.speed]); - - // fake transfer to kick-off the enumeration process - tuh_xfer_t xfer; - xfer.daddr = 0; - xfer.result = XFER_RESULT_SUCCESS; - xfer.user_data = ENUM_ADDR0_DEVICE_DESC; - - process_enumeration(&xfer); - } -#if CFG_TUH_HUB - else { - // connected via external hub - // wait until device connection is stable TODO non blocking - tusb_time_delay_ms_api(ENUM_DEBOUNCING_DELAY_MS); - - // ENUM_HUB_GET_STATUS - TU_ASSERT(hub_port_get_status(_dev0.hub_addr, _dev0.hub_port, _usbh_epbuf.ctrl, - process_enumeration, ENUM_HUB_CLEAR_RESET_1)); - } -#endif // hub - - return true; -} - -static uint8_t get_new_address(bool is_hub) { +static uint8_t enum_get_new_address(bool is_hub) { uint8_t start; uint8_t end; @@ -1598,53 +1784,15 @@ static uint8_t get_new_address(bool is_hub) { } for (uint8_t idx = start; idx < end; idx++) { - if (!_usbh_devices[idx].connected) return (idx+1); + if (!_usbh_devices[idx].connected) { + return (idx + 1); + } } return 0; // invalid address } -static bool enum_request_set_addr(void) { - tusb_desc_device_t const* desc_device = (tusb_desc_device_t const*) _usbh_epbuf.ctrl; - - // Get new address - uint8_t const new_addr = get_new_address(desc_device->bDeviceClass == TUSB_CLASS_HUB); - TU_ASSERT(new_addr != 0); - TU_LOG_USBH("Set Address = %d\r\n", new_addr); - - usbh_device_t* new_dev = get_device(new_addr); - new_dev->rhport = _dev0.rhport; - new_dev->hub_addr = _dev0.hub_addr; - new_dev->hub_port = _dev0.hub_port; - new_dev->speed = _dev0.speed; - new_dev->connected = 1; - new_dev->ep0_size = desc_device->bMaxPacketSize0; - - tusb_control_request_t const request = { - .bmRequestType_bit = { - .recipient = TUSB_REQ_RCPT_DEVICE, - .type = TUSB_REQ_TYPE_STANDARD, - .direction = TUSB_DIR_OUT - }, - .bRequest = TUSB_REQ_SET_ADDRESS, - .wValue = tu_htole16(new_addr), - .wIndex = 0, - .wLength = 0 - }; - tuh_xfer_t xfer = { - .daddr = 0, // dev0 - .ep_addr = 0, - .setup = &request, - .buffer = NULL, - .complete_cb = process_enumeration, - .user_data = ENUM_GET_DEVICE_DESC - }; - - TU_ASSERT(tuh_control_xfer(&xfer)); - return true; -} - -static bool _parse_configuration_descriptor(uint8_t dev_addr, tusb_desc_configuration_t const* desc_cfg) { +static bool enum_parse_configuration_desc(uint8_t dev_addr, tusb_desc_configuration_t const* desc_cfg) { usbh_device_t* dev = get_device(dev_addr); uint16_t const total_len = tu_le16toh(desc_cfg->wTotalLength); uint8_t const* desc_end = ((uint8_t const*) desc_cfg) + total_len; @@ -1657,7 +1805,7 @@ static bool _parse_configuration_descriptor(uint8_t dev_addr, tusb_desc_configur if ( 0 == tu_desc_len(p_desc) ) { // A zero length descriptor indicates that the device is off spec (e.g. wrong wTotalLength). // Parsed interfaces should still be usable - TU_LOG_USBH("Encountered a zero-length descriptor after %u bytes\r\n", (uint32_t)p_desc - (uint32_t)desc_cfg); + TU_LOG_USBH("Encountered a zero-length descriptor after %" PRIu32 " bytes\r\n", (uint32_t)p_desc - (uint32_t)desc_cfg); break; } @@ -1705,7 +1853,7 @@ static bool _parse_configuration_descriptor(uint8_t dev_addr, tusb_desc_configur // Find driver for this interface for (uint8_t drv_id = 0; drv_id < TOTAL_DRIVER_COUNT; drv_id++) { usbh_class_driver_t const * driver = get_driver(drv_id); - if (driver && driver->open(dev->rhport, dev_addr, desc_itf, drv_len) ) { + if (driver && driver->open(dev->bus_info.rhport, dev_addr, desc_itf, drv_len) ) { // open successfully TU_LOG_USBH(" %s opened\r\n", driver->name); @@ -1724,9 +1872,9 @@ static bool _parse_configuration_descriptor(uint8_t dev_addr, tusb_desc_configur break; // exit driver find loop } - if ( drv_id == TOTAL_DRIVER_COUNT - 1 ) { + if (drv_id == TOTAL_DRIVER_COUNT - 1) { TU_LOG_USBH("[%u:%u] Interface %u: class = %u subclass = %u protocol = %u is not supported\r\n", - dev->rhport, dev_addr, desc_itf->bInterfaceNumber, desc_itf->bInterfaceClass, desc_itf->bInterfaceSubClass, desc_itf->bInterfaceProtocol); + dev->bus_info.rhport, dev_addr, desc_itf->bInterfaceNumber, desc_itf->bInterfaceClass, desc_itf->bInterfaceSubClass, desc_itf->bInterfaceProtocol); } } @@ -1761,18 +1909,21 @@ void usbh_driver_set_config_complete(uint8_t dev_addr, uint8_t itf_num) { TU_LOG_USBH("HUB address = %u is mounted\r\n", dev_addr); }else { // Invoke callback if available - if (tuh_mount_cb) tuh_mount_cb(dev_addr); + if (tuh_mount_cb) { + tuh_mount_cb(dev_addr); + } } } } static void enum_full_complete(void) { // mark enumeration as complete - _dev0.enumerating = 0; + _usbh_data.enumerating_daddr = TUSB_INDEX_INVALID_8; #if CFG_TUH_HUB - // get next hub status - if (_dev0.hub_addr) hub_edpt_status_xfer(_dev0.hub_addr); + if (_usbh_data.dev0_bus.hub_addr != 0) { + hub_edpt_status_xfer(_usbh_data.dev0_bus.hub_addr); // get next hub status + } #endif } diff --git a/src/host/usbh.h b/src/host/usbh.h index 72c237573..1e9bb26bc 100644 --- a/src/host/usbh.h +++ b/src/host/usbh.h @@ -33,14 +33,20 @@ #include "common/tusb_common.h" +#if CFG_TUH_MAX3421 +#include "portable/analog/max3421/hcd_max3421.h" +#endif + //--------------------------------------------------------------------+ // MACRO CONSTANT TYPEDEF //--------------------------------------------------------------------+ +// Endpoint Bulk size depending on host mx speed +#define TUH_EPSIZE_BULK_MPS (TUH_OPT_HIGH_SPEED ? TUSB_EPSIZE_BULK_HS : TUSB_EPSIZE_BULK_FS) + // forward declaration struct tuh_xfer_s; typedef struct tuh_xfer_s tuh_xfer_t; - typedef void (*tuh_xfer_cb_t)(tuh_xfer_t* xfer); // Note1: layout and order of this will be changed in near future @@ -73,6 +79,17 @@ typedef struct { tusb_desc_interface_t desc; } tuh_itf_info_t; +typedef struct { + uint8_t rhport; + uint8_t hub_addr; + uint8_t hub_port; + uint8_t speed; +} tuh_bus_info_t; + +// backward compatibility for hcd_devtree_info_t, maybe removed in the future +#define hcd_devtree_info_t tuh_bus_info_t +#define hcd_devtree_get_info(_daddr, _bus_info) tuh_bus_info_get(_daddr, _bus_info) + // ConfigID for tuh_configure() enum { TUH_CFGID_INVALID = 0, @@ -96,6 +113,15 @@ typedef union { // APPLICATION CALLBACK //--------------------------------------------------------------------+ +// Invoked when enumeration get device descriptor +// Device is not ready to communicate yet, application can copy the descriptor if needed +void tuh_enum_descriptor_device_cb(uint8_t daddr, const tusb_desc_device_t *desc_device); + +// Invoked when enumeration get configuration descriptor +// For multi-configuration device return false to skip, true to proceed with this configuration (may not be implemented yet) +// Device is not ready to communicate yet, application can copy the descriptor if needed +bool tuh_enum_descriptor_configuration_cb(uint8_t daddr, uint8_t cfg_index, const tusb_desc_configuration_t *desc_config); + // Invoked when a device is mounted (configured) TU_ATTR_WEAK void tuh_mount_cb (uint8_t daddr); @@ -146,8 +172,7 @@ bool tuh_inited(void); void tuh_task_ext(uint32_t timeout_ms, bool in_isr); // Task function should be called in main/rtos loop -TU_ATTR_ALWAYS_INLINE static inline -void tuh_task(void) { +TU_ATTR_ALWAYS_INLINE static inline void tuh_task(void) { tuh_task_ext(UINT32_MAX, false); } @@ -162,6 +187,8 @@ extern void hcd_int_handler(uint8_t rhport, bool in_isr); #define _tuh_int_handler_arg0() TU_VERIFY_STATIC(false, "tuh_int_handler() must have 1 or 2 arguments") #define _tuh_int_handler_arg1(_rhport) hcd_int_handler(_rhport, true) #define _tuh_int_handler_arg2(_rhport, _in_isr) hcd_int_handler(_rhport, _in_isr) + +// 1st argument is rhport (mandatory), 2nd argument in_isr (optional) #define tuh_int_handler(...) TU_FUNC_OPTIONAL_ARG(_tuh_int_handler, __VA_ARGS__) // Check if roothub port is initialized and active as a host @@ -177,30 +204,48 @@ bool tuh_rhport_reset_bus(uint8_t rhport, bool active); // Get VID/PID of device bool tuh_vid_pid_get(uint8_t daddr, uint16_t* vid, uint16_t* pid); +// Get local (cached) device descriptor once device is enumerated +bool tuh_descriptor_get_device_local(uint8_t daddr, tusb_desc_device_t* desc_device); + // Get speed of device tusb_speed_t tuh_speed_get(uint8_t daddr); // Check if device is connected and configured bool tuh_mounted(uint8_t daddr); +// Check if device is connected which mean device has at least 1 successful transfer +// Note: It may not be addressed/configured/mounted yet +bool tuh_connected(uint8_t daddr); + // Check if device is suspended -TU_ATTR_ALWAYS_INLINE static inline -bool tuh_suspended(uint8_t daddr) { +TU_ATTR_ALWAYS_INLINE static inline bool tuh_suspended(uint8_t daddr) { // TODO implement suspend & resume on host (void) daddr; return false; } // Check if device is ready to communicate with -TU_ATTR_ALWAYS_INLINE static inline -bool tuh_ready(uint8_t daddr) { +TU_ATTR_ALWAYS_INLINE static inline bool tuh_ready(uint8_t daddr) { return tuh_mounted(daddr) && !tuh_suspended(daddr); } +// Get bus information of device +bool tuh_bus_info_get(uint8_t daddr, tuh_bus_info_t* bus_info); + //--------------------------------------------------------------------+ // Transfer API +// Each Function will make a USB transfer request to device. If +// - complete_cb != NULL, the function will return immediately and invoke the callback when request is complete. +// - complete_cb == NULL, the function will block until request is complete. +// In this case, user_data should be tusb_xfer_result_t* to hold the transfer result. //--------------------------------------------------------------------+ +// Helper to make Sync API from async one +#define TU_API_SYNC(_async_api, ...) \ + xfer_result_t result = XFER_RESULT_INVALID;\ + TU_VERIFY(_async_api(__VA_ARGS__, NULL, (uintptr_t) &result), XFER_RESULT_TIMEOUT); \ + return result + // Submit a control transfer // - async: complete callback invoked when finished. // - sync : blocking if complete callback is NULL. @@ -214,10 +259,17 @@ bool tuh_edpt_xfer(tuh_xfer_t* xfer); // Open a non-control endpoint bool tuh_edpt_open(uint8_t daddr, tusb_desc_endpoint_t const * desc_ep); +// Close a non-control endpoint, it will abort any pending transfer +bool tuh_edpt_close(uint8_t daddr, uint8_t ep_addr); + // Abort a queued transfer. Note: it can only abort transfer that has not been started // Return true if a queued transfer is aborted, false if there is no transfer to abort bool tuh_edpt_abort_xfer(uint8_t daddr, uint8_t ep_addr); +// Set Address (control transfer) +bool tuh_address_set(uint8_t daddr, uint8_t new_addr, + tuh_xfer_cb_t complete_cb, uintptr_t user_data); + // Set Configuration (control transfer) // config_num = 0 will un-configure device. Note: config_num = config_descriptor_index + 1 // true on success, false if there is on-going control transfer or incorrect parameters @@ -261,6 +313,13 @@ bool tuh_descriptor_get_hid_report(uint8_t daddr, uint8_t itf_num, uint8_t desc_ bool tuh_descriptor_get_string(uint8_t daddr, uint8_t index, uint16_t language_id, void* buffer, uint16_t len, tuh_xfer_cb_t complete_cb, uintptr_t user_data); +// Get language id string descriptor (control transfer) +TU_ATTR_ALWAYS_INLINE static inline +bool tuh_descriptor_get_string_langid(uint8_t daddr, void* buffer, uint16_t len, + tuh_xfer_cb_t complete_cb, uintptr_t user_data) { + return tuh_descriptor_get_string(daddr, 0, 0, buffer, len, complete_cb, user_data); +} + // Get manufacturer string descriptor (control transfer) // true on success, false if there is on-going control transfer or incorrect parameters bool tuh_descriptor_get_manufacturer_string(uint8_t daddr, uint16_t language_id, void* buffer, uint16_t len, @@ -278,39 +337,54 @@ bool tuh_descriptor_get_serial_string(uint8_t daddr, uint16_t language_id, void* //--------------------------------------------------------------------+ // Descriptors Synchronous (blocking) +// Sync API which is blocking until transfer is complete. +// return transfer result //--------------------------------------------------------------------+ -// Sync (blocking) version of tuh_descriptor_get() -// return transfer result -uint8_t tuh_descriptor_get_sync(uint8_t daddr, uint8_t type, uint8_t index, void* buffer, uint16_t len); +// Sync version of tuh_descriptor_get() +TU_ATTR_ALWAYS_INLINE static inline tusb_xfer_result_t tuh_descriptor_get_sync(uint8_t daddr, uint8_t type, uint8_t index, void* buffer, uint16_t len) { + TU_API_SYNC(tuh_descriptor_get, daddr, type, index, buffer, len); +} -// Sync (blocking) version of tuh_descriptor_get_device() -// return transfer result -uint8_t tuh_descriptor_get_device_sync(uint8_t daddr, void* buffer, uint16_t len); +// Sync version of tuh_descriptor_get_device() +TU_ATTR_ALWAYS_INLINE static inline tusb_xfer_result_t tuh_descriptor_get_device_sync(uint8_t daddr, void* buffer, uint16_t len) { + TU_API_SYNC(tuh_descriptor_get_device, daddr, buffer, len); +} -// Sync (blocking) version of tuh_descriptor_get_configuration() -// return transfer result -uint8_t tuh_descriptor_get_configuration_sync(uint8_t daddr, uint8_t index, void* buffer, uint16_t len); +// Sync version of tuh_descriptor_get_configuration() +TU_ATTR_ALWAYS_INLINE static inline tusb_xfer_result_t tuh_descriptor_get_configuration_sync(uint8_t daddr, uint8_t index, void* buffer, uint16_t len) { + TU_API_SYNC(tuh_descriptor_get_configuration, daddr, index, buffer, len); +} -// Sync (blocking) version of tuh_descriptor_get_hid_report() -// return transfer result -uint8_t tuh_descriptor_get_hid_report_sync(uint8_t daddr, uint8_t itf_num, uint8_t desc_type, uint8_t index, void* buffer, uint16_t len); +// Sync version of tuh_descriptor_get_hid_report() +TU_ATTR_ALWAYS_INLINE static inline tusb_xfer_result_t tuh_descriptor_get_hid_report_sync(uint8_t daddr, uint8_t itf_num, uint8_t desc_type, uint8_t index, void* buffer, uint16_t len) { + TU_API_SYNC(tuh_descriptor_get_hid_report, daddr, itf_num, desc_type, index, buffer, len); +} -// Sync (blocking) version of tuh_descriptor_get_string() -// return transfer result -uint8_t tuh_descriptor_get_string_sync(uint8_t daddr, uint8_t index, uint16_t language_id, void* buffer, uint16_t len); +// Sync version of tuh_descriptor_get_string() +TU_ATTR_ALWAYS_INLINE static inline tusb_xfer_result_t tuh_descriptor_get_string_sync(uint8_t daddr, uint8_t index, uint16_t language_id, void* buffer, uint16_t len) { + TU_API_SYNC(tuh_descriptor_get_string, daddr, index, language_id, buffer, len); +} -// Sync (blocking) version of tuh_descriptor_get_manufacturer_string() -// return transfer result -uint8_t tuh_descriptor_get_manufacturer_string_sync(uint8_t daddr, uint16_t language_id, void* buffer, uint16_t len); +// Sync version of tuh_descriptor_get_string_langid() +TU_ATTR_ALWAYS_INLINE static inline tusb_xfer_result_t tuh_descriptor_get_string_langid_sync(uint8_t daddr, void* buffer, uint16_t len) { + return tuh_descriptor_get_string_sync(daddr, 0, 0, buffer, len); +} -// Sync (blocking) version of tuh_descriptor_get_product_string() -// return transfer result -uint8_t tuh_descriptor_get_product_string_sync(uint8_t daddr, uint16_t language_id, void* buffer, uint16_t len); +// Sync version of tuh_descriptor_get_manufacturer_string() +TU_ATTR_ALWAYS_INLINE static inline tusb_xfer_result_t tuh_descriptor_get_manufacturer_string_sync(uint8_t daddr, uint16_t language_id, void* buffer, uint16_t len) { + TU_API_SYNC(tuh_descriptor_get_manufacturer_string, daddr, language_id, buffer, len); +} -// Sync (blocking) version of tuh_descriptor_get_serial_string() -// return transfer result -uint8_t tuh_descriptor_get_serial_string_sync(uint8_t daddr, uint16_t language_id, void* buffer, uint16_t len); +// Sync version of tuh_descriptor_get_product_string() +TU_ATTR_ALWAYS_INLINE static inline tusb_xfer_result_t tuh_descriptor_get_product_string_sync(uint8_t daddr, uint16_t language_id, void* buffer, uint16_t len) { + TU_API_SYNC(tuh_descriptor_get_product_string, daddr, language_id, buffer, len); +} + +// Sync version of tuh_descriptor_get_serial_string() +TU_ATTR_ALWAYS_INLINE static inline tusb_xfer_result_t tuh_descriptor_get_serial_string_sync(uint8_t daddr, uint16_t language_id, void* buffer, uint16_t len) { + TU_API_SYNC(tuh_descriptor_get_serial_string, daddr, language_id, buffer, len); +} #ifdef __cplusplus } diff --git a/src/host/usbh_pvt.h b/src/host/usbh_pvt.h index 95de915e9..cb092e5f3 100644 --- a/src/host/usbh_pvt.h +++ b/src/host/usbh_pvt.h @@ -41,10 +41,6 @@ #define TU_LOG_INT_USBH(...) TU_LOG_INT(CFG_TUH_LOG_LEVEL, __VA_ARGS__) #define TU_LOG_HEX_USBH(...) TU_LOG_HEX(CFG_TUH_LOG_LEVEL, __VA_ARGS__) -enum { - USBH_EPSIZE_BULK_MAX = (TUH_OPT_HIGH_SPEED ? TUSB_EPSIZE_BULK_HS : TUSB_EPSIZE_BULK_FS) -}; - //--------------------------------------------------------------------+ // Class Driver API //--------------------------------------------------------------------+ @@ -67,7 +63,7 @@ usbh_class_driver_t const* usbh_app_driver_get_cb(uint8_t* driver_count) TU_ATTR // Call by class driver to tell USBH that it has complete the enumeration void usbh_driver_set_config_complete(uint8_t dev_addr, uint8_t itf_num); -uint8_t usbh_get_rhport(uint8_t dev_addr); +uint8_t usbh_get_rhport(uint8_t daddr); uint8_t* usbh_get_enum_buf(void); @@ -75,6 +71,9 @@ void usbh_int_set(bool enabled); void usbh_defer_func(osal_task_func_t func, void *param, bool in_isr); +void usbh_spin_lock(bool in_isr); +void usbh_spin_unlock(bool in_isr); + //--------------------------------------------------------------------+ // USBH Endpoint API //--------------------------------------------------------------------+ @@ -83,8 +82,8 @@ void usbh_defer_func(osal_task_func_t func, void *param, bool in_isr); bool usbh_edpt_xfer_with_callback(uint8_t dev_addr, uint8_t ep_addr, uint8_t * buffer, uint16_t total_bytes, tuh_xfer_cb_t complete_cb, uintptr_t user_data); -TU_ATTR_ALWAYS_INLINE -static inline bool usbh_edpt_xfer(uint8_t dev_addr, uint8_t ep_addr, uint8_t * buffer, uint16_t total_bytes) { +TU_ATTR_ALWAYS_INLINE static inline +bool usbh_edpt_xfer(uint8_t dev_addr, uint8_t ep_addr, uint8_t * buffer, uint16_t total_bytes) { return usbh_edpt_xfer_with_callback(dev_addr, ep_addr, buffer, total_bytes, NULL, 0); } diff --git a/src/osal/osal.h b/src/osal/osal.h index 8f45ea5c1..a33280425 100644 --- a/src/osal/osal.h +++ b/src/osal/osal.h @@ -63,6 +63,8 @@ typedef void (*osal_task_func_t)( void * ); #include "osal_rtthread.h" #elif CFG_TUSB_OS == OPT_OS_RTX4 #include "osal_rtx4.h" +#elif CFG_TUSB_OS == OPT_OS_ZEPHYR + #include "osal_zephyr.h" #elif CFG_TUSB_OS == OPT_OS_CUSTOM #include "tusb_os_custom.h" // implemented by application #else @@ -73,6 +75,10 @@ typedef void (*osal_task_func_t)( void * ); // OSAL Porting API // Should be implemented as static inline function in osal_port.h header /* + void osal_spin_init(osal_spinlock_t *ctx); + void osal_spin_lock(osal_spinlock_t *ctx, bool in_isr) + void osal_spin_unlock(osal_spinlock_t *ctx, bool in_isr); + osal_semaphore_t osal_semaphore_create(osal_semaphore_def_t* semdef); bool osal_semaphore_delete(osal_semaphore_t semd_hdl); bool osal_semaphore_post(osal_semaphore_t sem_hdl, bool in_isr); diff --git a/src/osal/osal_freertos.h b/src/osal/osal_freertos.h index a3a0f3a3f..bde5ec010 100644 --- a/src/osal/osal_freertos.h +++ b/src/osal/osal_freertos.h @@ -42,20 +42,20 @@ extern "C" { //--------------------------------------------------------------------+ #if configSUPPORT_STATIC_ALLOCATION - typedef StaticSemaphore_t osal_semaphore_def_t; - typedef StaticSemaphore_t osal_mutex_def_t; +typedef StaticSemaphore_t osal_semaphore_def_t; +typedef StaticSemaphore_t osal_mutex_def_t; #else - // not used therefore defined to smallest possible type to save space - typedef uint8_t osal_semaphore_def_t; - typedef uint8_t osal_mutex_def_t; + +// not used therefore defined to the smallest possible type to save space +typedef uint8_t osal_semaphore_def_t; +typedef uint8_t osal_mutex_def_t; #endif typedef SemaphoreHandle_t osal_semaphore_t; typedef SemaphoreHandle_t osal_mutex_t; typedef QueueHandle_t osal_queue_t; -typedef struct -{ +typedef struct { uint16_t depth; uint16_t item_sz; void* buf; @@ -83,16 +83,14 @@ typedef struct //--------------------------------------------------------------------+ // TASK API //--------------------------------------------------------------------+ - TU_ATTR_ALWAYS_INLINE static inline uint32_t _osal_ms2tick(uint32_t msec) { - if ( msec == OSAL_TIMEOUT_WAIT_FOREVER ) return portMAX_DELAY; - if ( msec == 0 ) return 0; + if (msec == OSAL_TIMEOUT_WAIT_FOREVER) { return portMAX_DELAY; } + if (msec == 0) { return 0; } uint32_t ticks = pdMS_TO_TICKS(msec); - // configTICK_RATE_HZ is less than 1000 and 1 tick > 1 ms - // we still need to delay at least 1 tick - if ( ticks == 0 ) ticks = 1; + // If configTICK_RATE_HZ is less than 1000 and 1 tick > 1 ms, we still need to delay at least 1 tick + if (ticks == 0) { ticks = 1; } return ticks; } @@ -101,10 +99,71 @@ TU_ATTR_ALWAYS_INLINE static inline void osal_task_delay(uint32_t msec) { vTaskDelay(pdMS_TO_TICKS(msec)); } +//--------------------------------------------------------------------+ +// Spinlock API +//--------------------------------------------------------------------+ +#define OSAL_SPINLOCK_DEF(_name, _int_set) \ + osal_spinlock_t _name + +#if TUSB_MCU_VENDOR_ESPRESSIF +// Espressif critical take spinlock as argument and does not use in_isr +typedef portMUX_TYPE osal_spinlock_t; + +TU_ATTR_ALWAYS_INLINE static inline void osal_spin_init(osal_spinlock_t *ctx) { + spinlock_initialize(ctx); +} + +TU_ATTR_ALWAYS_INLINE static inline void osal_spin_lock(osal_spinlock_t *ctx, bool in_isr) { + if (!TUP_MCU_MULTIPLE_CORE && in_isr) { + return; // single core MCU does not need to lock in ISR + } + portENTER_CRITICAL(ctx); +} + +TU_ATTR_ALWAYS_INLINE static inline void osal_spin_unlock(osal_spinlock_t *ctx, bool in_isr) { + if (!TUP_MCU_MULTIPLE_CORE && in_isr) { + return; // single core MCU does not need to lock in ISR + } + portEXIT_CRITICAL(ctx); +} + +#else + +typedef UBaseType_t osal_spinlock_t; + +TU_ATTR_ALWAYS_INLINE static inline void osal_spin_init(osal_spinlock_t *ctx) { + (void) ctx; +} + +TU_ATTR_ALWAYS_INLINE static inline void osal_spin_lock(osal_spinlock_t *ctx, bool in_isr) { + if (in_isr) { + if (!TUP_MCU_MULTIPLE_CORE) { + (void) ctx; + return; // single core MCU does not need to lock in ISR + } + *ctx = taskENTER_CRITICAL_FROM_ISR(); + } else { + taskENTER_CRITICAL(); + } +} + +TU_ATTR_ALWAYS_INLINE static inline void osal_spin_unlock(osal_spinlock_t *ctx, bool in_isr) { + if (in_isr) { + if (!TUP_MCU_MULTIPLE_CORE) { + (void) ctx; + return; // single core MCU does not need to lock in ISR + } + taskEXIT_CRITICAL_FROM_ISR(*ctx); + } else { + taskEXIT_CRITICAL(); + } +} + +#endif + //--------------------------------------------------------------------+ // Semaphore API //--------------------------------------------------------------------+ - TU_ATTR_ALWAYS_INLINE static inline osal_semaphore_t osal_semaphore_create(osal_semaphore_def_t *semdef) { #if configSUPPORT_STATIC_ALLOCATION return xSemaphoreCreateBinaryStatic(semdef); @@ -120,19 +179,12 @@ TU_ATTR_ALWAYS_INLINE static inline bool osal_semaphore_delete(osal_semaphore_t } TU_ATTR_ALWAYS_INLINE static inline bool osal_semaphore_post(osal_semaphore_t sem_hdl, bool in_isr) { - if ( !in_isr ) { + if (!in_isr) { return xSemaphoreGive(sem_hdl) != 0; } else { BaseType_t xHigherPriorityTaskWoken = pdFALSE; BaseType_t res = xSemaphoreGiveFromISR(sem_hdl, &xHigherPriorityTaskWoken); - -#if CFG_TUSB_MCU == OPT_MCU_ESP32S2 || CFG_TUSB_MCU == OPT_MCU_ESP32S3 - // not needed after https://github.com/espressif/esp-idf/commit/c5fd79547ac9b7bae06fa660e9f814d18d3390b7 - if ( xHigherPriorityTaskWoken ) portYIELD_FROM_ISR(); -#else portYIELD_FROM_ISR(xHigherPriorityTaskWoken); -#endif - return res != 0; } } @@ -148,7 +200,6 @@ TU_ATTR_ALWAYS_INLINE static inline void osal_semaphore_reset(osal_semaphore_t c //--------------------------------------------------------------------+ // MUTEX API (priority inheritance) //--------------------------------------------------------------------+ - TU_ATTR_ALWAYS_INLINE static inline osal_mutex_t osal_mutex_create(osal_mutex_def_t *mdef) { #if configSUPPORT_STATIC_ALLOCATION return xSemaphoreCreateMutexStatic(mdef); @@ -174,7 +225,6 @@ TU_ATTR_ALWAYS_INLINE static inline bool osal_mutex_unlock(osal_mutex_t mutex_hd //--------------------------------------------------------------------+ // QUEUE API //--------------------------------------------------------------------+ - TU_ATTR_ALWAYS_INLINE static inline osal_queue_t osal_queue_create(osal_queue_def_t* qdef) { osal_queue_t q; @@ -201,19 +251,12 @@ TU_ATTR_ALWAYS_INLINE static inline bool osal_queue_receive(osal_queue_t qhdl, v } TU_ATTR_ALWAYS_INLINE static inline bool osal_queue_send(osal_queue_t qhdl, void const *data, bool in_isr) { - if ( !in_isr ) { + if (!in_isr) { return xQueueSendToBack(qhdl, data, OSAL_TIMEOUT_WAIT_FOREVER) != 0; } else { BaseType_t xHigherPriorityTaskWoken = pdFALSE; BaseType_t res = xQueueSendToBackFromISR(qhdl, data, &xHigherPriorityTaskWoken); - -#if CFG_TUSB_MCU == OPT_MCU_ESP32S2 || CFG_TUSB_MCU == OPT_MCU_ESP32S3 - // not needed after https://github.com/espressif/esp-idf/commit/c5fd79547ac9b7bae06fa660e9f814d18d3390b7 (IDF v5) - if ( xHigherPriorityTaskWoken ) portYIELD_FROM_ISR(); -#else portYIELD_FROM_ISR(xHigherPriorityTaskWoken); -#endif - return res != 0; } } diff --git a/src/osal/osal_mynewt.h b/src/osal/osal_mynewt.h index 16def0d2a..ee95e684f 100644 --- a/src/osal/osal_mynewt.h +++ b/src/osal/osal_mynewt.h @@ -40,6 +40,32 @@ TU_ATTR_ALWAYS_INLINE static inline void osal_task_delay(uint32_t msec) { os_time_delay( os_time_ms_to_ticks32(msec) ); } +//--------------------------------------------------------------------+ +// Spinlock API +//--------------------------------------------------------------------+ +typedef os_sr_t osal_spinlock_t; + +#define OSAL_SPINLOCK_DEF(_name, _int_set) \ + osal_spinlock_t _name + +TU_ATTR_ALWAYS_INLINE static inline void osal_spin_init(osal_spinlock_t *ctx) { + (void) ctx; +} + +TU_ATTR_ALWAYS_INLINE static inline void osal_spin_lock(osal_spinlock_t *ctx, bool in_isr) { + if (!TUP_MCU_MULTIPLE_CORE && in_isr) { + return; // single core MCU does not need to lock in ISR + } + OS_ENTER_CRITICAL(*ctx); +} + +TU_ATTR_ALWAYS_INLINE static inline void osal_spin_unlock(osal_spinlock_t *ctx, bool in_isr) { + if (!TUP_MCU_MULTIPLE_CORE && in_isr) { + return; // single core MCU does not need to lock in ISR + } + OS_ENTER_CRITICAL(*ctx); +} + //--------------------------------------------------------------------+ // Semaphore API //--------------------------------------------------------------------+ diff --git a/src/osal/osal_none.h b/src/osal/osal_none.h index c93f7a86c..a8eb1042b 100644 --- a/src/osal/osal_none.h +++ b/src/osal/osal_none.h @@ -40,6 +40,33 @@ extern "C" { TU_ATTR_WEAK void osal_task_delay(uint32_t msec); #endif +//--------------------------------------------------------------------+ +// Spinlock API +//--------------------------------------------------------------------+ +typedef struct { + void (* interrupt_set)(bool); +} osal_spinlock_t; + +// For SMP, spinlock must be locked by hardware, cannot just use interrupt +#define OSAL_SPINLOCK_DEF(_name, _int_set) \ + osal_spinlock_t _name = { .interrupt_set = _int_set } + +TU_ATTR_ALWAYS_INLINE static inline void osal_spin_init(osal_spinlock_t *ctx) { + (void) ctx; +} + +TU_ATTR_ALWAYS_INLINE static inline void osal_spin_lock(osal_spinlock_t *ctx, bool in_isr) { + if (!in_isr) { + ctx->interrupt_set(false); + } +} + +TU_ATTR_ALWAYS_INLINE static inline void osal_spin_unlock(osal_spinlock_t *ctx, bool in_isr) { + if (!in_isr) { + ctx->interrupt_set(true); + } +} + //--------------------------------------------------------------------+ // Binary Semaphore API //--------------------------------------------------------------------+ @@ -137,18 +164,6 @@ typedef osal_queue_def_t* osal_queue_t; .ff = TU_FIFO_INIT(_name##_buf, _depth, _type, false) \ } -// lock queue by disable USB interrupt -TU_ATTR_ALWAYS_INLINE static inline void _osal_q_lock(osal_queue_t qhdl) { - // disable dcd/hcd interrupt - qhdl->interrupt_set(false); -} - -// unlock queue -TU_ATTR_ALWAYS_INLINE static inline void _osal_q_unlock(osal_queue_t qhdl) { - // enable dcd/hcd interrupt - qhdl->interrupt_set(true); -} - TU_ATTR_ALWAYS_INLINE static inline osal_queue_t osal_queue_create(osal_queue_def_t* qdef) { tu_fifo_clear(&qdef->ff); return (osal_queue_t) qdef; @@ -162,22 +177,22 @@ TU_ATTR_ALWAYS_INLINE static inline bool osal_queue_delete(osal_queue_t qhdl) { TU_ATTR_ALWAYS_INLINE static inline bool osal_queue_receive(osal_queue_t qhdl, void* data, uint32_t msec) { (void) msec; // not used, always behave as msec = 0 - _osal_q_lock(qhdl); - bool success = tu_fifo_read(&qhdl->ff, data); - _osal_q_unlock(qhdl); + qhdl->interrupt_set(false); + const bool success = tu_fifo_read(&qhdl->ff, data); + qhdl->interrupt_set(true); return success; } TU_ATTR_ALWAYS_INLINE static inline bool osal_queue_send(osal_queue_t qhdl, void const* data, bool in_isr) { if (!in_isr) { - _osal_q_lock(qhdl); + qhdl->interrupt_set(false); } - bool success = tu_fifo_write(&qhdl->ff, data); + const bool success = tu_fifo_write(&qhdl->ff, data); if (!in_isr) { - _osal_q_unlock(qhdl); + qhdl->interrupt_set(true); } return success; diff --git a/src/osal/osal_pico.h b/src/osal/osal_pico.h index 315de0950..ace5907d7 100644 --- a/src/osal/osal_pico.h +++ b/src/osal/osal_pico.h @@ -43,6 +43,27 @@ TU_ATTR_ALWAYS_INLINE static inline void osal_task_delay(uint32_t msec) { sleep_ms(msec); } +//--------------------------------------------------------------------+ +// Spinlock API +//--------------------------------------------------------------------+ +typedef critical_section_t osal_spinlock_t; // pico implement critical section with spinlock +#define OSAL_SPINLOCK_DEF(_name, _int_set) \ + osal_spinlock_t _name + +TU_ATTR_ALWAYS_INLINE static inline void osal_spin_init(osal_spinlock_t *ctx) { + critical_section_init(ctx); +} + +TU_ATTR_ALWAYS_INLINE static inline void osal_spin_lock(osal_spinlock_t *ctx, bool in_isr) { + (void) in_isr; + critical_section_enter_blocking(ctx); +} + +TU_ATTR_ALWAYS_INLINE static inline void osal_spin_unlock(osal_spinlock_t *ctx, bool in_isr) { + (void) in_isr; + critical_section_exit(ctx); +} + //--------------------------------------------------------------------+ // Binary Semaphore API //--------------------------------------------------------------------+ diff --git a/src/osal/osal_rtthread.h b/src/osal/osal_rtthread.h index c27814835..a778f5425 100644 --- a/src/osal/osal_rtthread.h +++ b/src/osal/osal_rtthread.h @@ -42,6 +42,32 @@ TU_ATTR_ALWAYS_INLINE static inline void osal_task_delay(uint32_t msec) { rt_thread_mdelay(msec); } +//--------------------------------------------------------------------+ +// Spinlock API +//--------------------------------------------------------------------+ +typedef struct rt_spinlock osal_spinlock_t; + +#define OSAL_SPINLOCK_DEF(_name, _int_set) \ + osal_spinlock_t _name + +TU_ATTR_ALWAYS_INLINE static inline void osal_spin_init(osal_spinlock_t *ctx) { + rt_spin_lock_init(ctx); +} + +TU_ATTR_ALWAYS_INLINE static inline void osal_spin_lock(osal_spinlock_t *ctx, bool in_isr) { + if (!TUP_MCU_MULTIPLE_CORE && in_isr) { + return; // single core MCU does not need to lock in ISR + } + rt_spin_lock(ctx); +} + +TU_ATTR_ALWAYS_INLINE static inline void osal_spin_unlock(osal_spinlock_t *ctx, bool in_isr) { + if (!TUP_MCU_MULTIPLE_CORE && in_isr) { + return; // single core MCU does not need to lock in ISR + } + rt_spin_unlock(ctx); +} + //--------------------------------------------------------------------+ // Semaphore API //--------------------------------------------------------------------+ diff --git a/src/osal/osal_rtx4.h b/src/osal/osal_rtx4.h index 35909e4d6..35860ddd5 100644 --- a/src/osal/osal_rtx4.h +++ b/src/osal/osal_rtx4.h @@ -56,6 +56,25 @@ TU_ATTR_ALWAYS_INLINE static inline uint16_t msec2wait(uint32_t msec) { } } +//--------------------------------------------------------------------+ +// Spinlock API, stub not implemented +//--------------------------------------------------------------------+ +typedef uint8_t osal_spinlock_t; +#define OSAL_SPINLOCK_DEF(_name, _int_set) \ + osal_spinlock_t _name + +TU_ATTR_ALWAYS_INLINE static inline void osal_spin_init(osal_spinlock_t *ctx) { + (void) ctx; +} + +TU_ATTR_ALWAYS_INLINE static inline void osal_spin_lock(osal_spinlock_t *ctx, bool in_isr) { + (void) ctx; (void) in_isr; +} + +TU_ATTR_ALWAYS_INLINE static inline void osal_spin_unlock(osal_spinlock_t *ctx, bool in_isr) { + (void) ctx; (void) in_isr; +} + //--------------------------------------------------------------------+ // Semaphore API //--------------------------------------------------------------------+ diff --git a/src/osal/osal_zephyr.h b/src/osal/osal_zephyr.h new file mode 100644 index 000000000..91f225f79 --- /dev/null +++ b/src/osal/osal_zephyr.h @@ -0,0 +1,152 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2025 Ha Thach (tinyusb.org) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * This file is part of the TinyUSB stack. + */ +#ifndef TUSB_OSAL_ZEPHYR_H +#define TUSB_OSAL_ZEPHYR_H + +#include + +//--------------------------------------------------------------------+ +// TASK API +//--------------------------------------------------------------------+ +TU_ATTR_ALWAYS_INLINE static inline void osal_task_delay(uint32_t msec) { + k_msleep(msec); +} + +//--------------------------------------------------------------------+ +// Spinlock API +//--------------------------------------------------------------------+ +typedef struct { + struct k_spinlock lock; + k_spinlock_key_t key; +} osal_spinlock_t; + +#define OSAL_SPINLOCK_DEF(_name, _int_set) \ + osal_spinlock_t _name + +TU_ATTR_ALWAYS_INLINE static inline void osal_spin_init(osal_spinlock_t *ctx) { + (void) ctx; +} + +TU_ATTR_ALWAYS_INLINE static inline void osal_spin_lock(osal_spinlock_t *ctx, bool in_isr) { + if (!TUP_MCU_MULTIPLE_CORE && in_isr) { + return; // single core MCU does not need to lock in ISR + } + ctx->key = k_spin_lock(&ctx->lock); +} + +TU_ATTR_ALWAYS_INLINE static inline void osal_spin_unlock(osal_spinlock_t *ctx, bool in_isr) { + if (!TUP_MCU_MULTIPLE_CORE && in_isr) { + return; // single core MCU does not need to lock in ISR + } + k_spin_unlock(&ctx->lock, ctx->key); +} + +//--------------------------------------------------------------------+ +// Binary Semaphore API +//--------------------------------------------------------------------+ +typedef struct k_sem osal_semaphore_def_t, * osal_semaphore_t; + +TU_ATTR_ALWAYS_INLINE static inline osal_semaphore_t osal_semaphore_create(osal_semaphore_def_t* semdef) { + k_sem_init(semdef, 0, 255); + return semdef; +} + +TU_ATTR_ALWAYS_INLINE static inline bool osal_semaphore_delete(osal_semaphore_t semd_hdl) { + (void) semd_hdl; + return true; // nothing to do +} + +TU_ATTR_ALWAYS_INLINE static inline bool osal_semaphore_post(osal_semaphore_t sem_hdl, bool in_isr) { + (void) in_isr; + k_sem_give(sem_hdl); + return true; +} + +TU_ATTR_ALWAYS_INLINE static inline bool osal_semaphore_wait(osal_semaphore_t sem_hdl, uint32_t msec) { + return 0 == k_sem_take(sem_hdl, K_MSEC(msec)); +} + +TU_ATTR_ALWAYS_INLINE static inline void osal_semaphore_reset(osal_semaphore_t sem_hdl) { + k_sem_reset(sem_hdl); +} + +//--------------------------------------------------------------------+ +// MUTEX API +//--------------------------------------------------------------------+ +typedef struct k_mutex osal_mutex_def_t, *osal_mutex_t; + +TU_ATTR_ALWAYS_INLINE static inline osal_mutex_t osal_mutex_create(osal_mutex_def_t* mdef) { + if ( 0 == k_mutex_init(mdef) ) { + return mdef; + } else { + return NULL; + } +} + +TU_ATTR_ALWAYS_INLINE static inline bool osal_mutex_delete(osal_mutex_t mutex_hdl) { + (void) mutex_hdl; + return true; // nothing to do +} + +TU_ATTR_ALWAYS_INLINE static inline bool osal_mutex_lock(osal_mutex_t mutex_hdl, uint32_t msec) { + return 0 == k_mutex_lock(mutex_hdl, K_MSEC(msec)); +} + +TU_ATTR_ALWAYS_INLINE static inline bool osal_mutex_unlock(osal_mutex_t mutex_hdl) { + return 0 == k_mutex_unlock(mutex_hdl); +} + +//--------------------------------------------------------------------+ +// QUEUE API +//--------------------------------------------------------------------+ +typedef struct k_msgq osal_queue_def_t, * osal_queue_t; + +// role device/host is used by OS NONE for mutex (disable usb isr) only +#define OSAL_QUEUE_DEF(_int_set, _name, _depth, _type) K_MSGQ_DEFINE(_name, sizeof(_type), _depth, 4) + +TU_ATTR_ALWAYS_INLINE static inline osal_queue_t osal_queue_create(osal_queue_def_t* qdef) { + // K_MSGQ_DEFINE already initializes the queue + return (osal_queue_t) qdef; +} + +TU_ATTR_ALWAYS_INLINE static inline bool osal_queue_delete(osal_queue_t qhdl) { + (void) qhdl; + return true; +} + +TU_ATTR_ALWAYS_INLINE static inline bool osal_queue_receive(osal_queue_t qhdl, void* data, uint32_t msec) { + return 0 == k_msgq_get(qhdl, data, K_MSEC(msec)); +} + +TU_ATTR_ALWAYS_INLINE static inline bool osal_queue_send(osal_queue_t qhdl, void const* data, bool in_isr) { + return 0 == k_msgq_put(qhdl, data, in_isr ? K_NO_WAIT : K_FOREVER); +} + +TU_ATTR_ALWAYS_INLINE static inline bool osal_queue_empty(osal_queue_t qhdl) { + return 0 == k_msgq_num_used_get(qhdl); +} + +#endif diff --git a/src/portable/analog/max3421/hcd_max3421.c b/src/portable/analog/max3421/hcd_max3421.c index c5e924266..971dbd62e 100644 --- a/src/portable/analog/max3421/hcd_max3421.c +++ b/src/portable/analog/max3421/hcd_max3421.c @@ -28,9 +28,9 @@ #if CFG_TUH_ENABLED && defined(CFG_TUH_MAX3421) && CFG_TUH_MAX3421 -#include #include "host/hcd.h" #include "host/usbh.h" +#include "host/usbh_pvt.h" //--------------------------------------------------------------------+ // @@ -233,7 +233,7 @@ typedef struct { uint8_t hxfr; }sndfifo_owner; - atomic_flag busy; // busy transferring + bool busy_lock; // busy transferring #if OSAL_MUTEX_REQUIRED OSAL_MUTEX_DEF(spi_mutexdef); @@ -252,28 +252,6 @@ static tuh_configure_max3421_t _tuh_cfg = { .pinctl = 0, // default: negative edge interrupt }; -//--------------------------------------------------------------------+ -// API: SPI transfer with MAX3421E -// - spi_cs_api(), spi_xfer_api(), int_api(): must be implemented by application -// - reg_read(), reg_write(): is implemented by this driver, can be used by application -//--------------------------------------------------------------------+ - -// API to control MAX3421 SPI CS -extern void tuh_max3421_spi_cs_api(uint8_t rhport, bool active); - -// API to transfer data with MAX3421 SPI -// Either tx_buf or rx_buf can be NULL, which means transfer is write or read only -extern bool tuh_max3421_spi_xfer_api(uint8_t rhport, uint8_t const* tx_buf, uint8_t* rx_buf, size_t xfer_bytes); - -// API to enable/disable MAX3421 INTR pin interrupt -extern void tuh_max3421_int_api(uint8_t rhport, bool enabled); - -// API to read MAX3421's register. Implemented by TinyUSB -uint8_t tuh_max3421_reg_read(uint8_t rhport, uint8_t reg, bool in_isr); - -// API to write MAX3421's register. Implemented by TinyUSB -bool tuh_max3421_reg_write(uint8_t rhport, uint8_t reg, uint8_t data, bool in_isr); - //--------------------------------------------------------------------+ // SPI Commands and Helper //--------------------------------------------------------------------+ @@ -349,7 +327,9 @@ TU_ATTR_ALWAYS_INLINE static inline void mode_write(uint8_t rhport, uint8_t data } TU_ATTR_ALWAYS_INLINE static inline void peraddr_write(uint8_t rhport, uint8_t data, bool in_isr) { - if ( _hcd_data.peraddr == data ) return; // no need to change address + if (_hcd_data.peraddr == data) { + return; // no need to change address + } _hcd_data.peraddr = data; reg_write(rhport, PERADDR_ADDR, data, in_isr); @@ -395,7 +375,7 @@ TU_ATTR_ALWAYS_INLINE static inline void hwfifo_setup(uint8_t rhport, const uint static void hwfifo_receive(uint8_t rhport, uint8_t * buffer, uint16_t len, bool in_isr) { uint8_t hirq; - uint8_t const reg = RCVVFIFO_ADDR; + const uint8_t reg = RCVVFIFO_ADDR; max3421_spi_lock(rhport, in_isr); @@ -411,7 +391,7 @@ static void hwfifo_receive(uint8_t rhport, uint8_t * buffer, uint16_t len, bool //--------------------------------------------------------------------+ static max3421_ep_t* find_ep_not_addr0(uint8_t daddr, uint8_t ep_num, uint8_t ep_dir) { - uint8_t const is_out = 1-ep_dir; + const uint8_t is_out = 1-ep_dir; for(size_t i=1; idaddr = daddr; @@ -645,6 +628,21 @@ bool hcd_edpt_open(uint8_t rhport, uint8_t daddr, tusb_desc_endpoint_t const * e return true; } +bool hcd_edpt_close(uint8_t rhport, uint8_t daddr, uint8_t ep_addr) { + (void) rhport; + uint8_t const ep_num = tu_edpt_number(ep_addr); + tusb_dir_t const ep_dir = tu_edpt_dir(ep_addr); + max3421_ep_t * ep = find_ep_not_addr0(daddr, ep_num, ep_dir); + + if (!ep) { + return false; // not opened + } + + tu_memclr(ep, sizeof(max3421_ep_t)); + + return true; +} + /* The microcontroller repeatedly writes the SNDFIFO register R2 to load the FIFO with up to 64 data bytes. * Then the microcontroller writes the SNDBC register, which this does three things: * 1. Tells the MAX3421E SIE (Serial Interface Engine) how many bytes in the FIFO to send. @@ -731,8 +729,8 @@ static void xact_generic(uint8_t rhport, max3421_ep_t *ep, bool switch_ep, bool // Submit a transfer, when complete hcd_event_xfer_complete() must be invoked bool hcd_edpt_xfer(uint8_t rhport, uint8_t daddr, uint8_t ep_addr, uint8_t * buffer, uint16_t buflen) { - uint8_t const ep_num = tu_edpt_number(ep_addr); - uint8_t const ep_dir = (uint8_t) tu_edpt_dir(ep_addr); + const uint8_t ep_num = tu_edpt_number(ep_addr); + const uint8_t ep_dir = (uint8_t) tu_edpt_dir(ep_addr); max3421_ep_t* ep = find_opened_ep(daddr, ep_num, ep_dir); TU_VERIFY(ep); @@ -748,8 +746,17 @@ bool hcd_edpt_xfer(uint8_t rhport, uint8_t daddr, uint8_t ep_addr, uint8_t * buf ep->xferred_len = 0; ep->state = EP_STATE_ATTEMPT_1; + bool has_xfer = false; + + usbh_spin_lock(false); + if (!_hcd_data.busy_lock) { + _hcd_data.busy_lock = true; + has_xfer = true; + } + usbh_spin_unlock(false); + // carry out transfer if not busy - if (!atomic_flag_test_and_set(&_hcd_data.busy)) { + if (has_xfer) { xact_generic(rhport, ep, true, false); } @@ -785,8 +792,17 @@ bool hcd_setup_send(uint8_t rhport, uint8_t daddr, uint8_t const setup_packet[8] ep->xferred_len = 0; ep->state = EP_STATE_ATTEMPT_1; + bool has_xfer = false; + + usbh_spin_lock(false); + if (!_hcd_data.busy_lock) { + _hcd_data.busy_lock = true; + has_xfer = true; + } + usbh_spin_unlock(false); + // carry out transfer if not busy - if (!atomic_flag_test_and_set(&_hcd_data.busy)) { + if (has_xfer) { xact_setup(rhport, ep, false); } @@ -852,8 +868,8 @@ static void handle_connect_irq(uint8_t rhport, bool in_isr) { } static void xfer_complete_isr(uint8_t rhport, max3421_ep_t *ep, xfer_result_t result, uint8_t hrsl, bool in_isr) { - uint8_t const ep_dir = 1-ep->hxfr_bm.is_out; - uint8_t const ep_addr = tu_edpt_addr(ep->hxfr_bm.ep_num, ep_dir); + const uint8_t ep_dir = 1 - ep->hxfr_bm.is_out; + const uint8_t ep_addr = tu_edpt_addr(ep->hxfr_bm.ep_num, ep_dir); // save data toggle if (ep_dir) { @@ -871,7 +887,9 @@ static void xfer_complete_isr(uint8_t rhport, max3421_ep_t *ep, xfer_result_t re xact_generic(rhport, next_ep, true, in_isr); }else { // no more pending - atomic_flag_clear(&_hcd_data.busy); + usbh_spin_lock(in_isr); + _hcd_data.busy_lock = false; + usbh_spin_unlock(in_isr); } } @@ -910,7 +928,9 @@ static void handle_xfer_done(uint8_t rhport, bool in_isr) { xact_generic(rhport, next_ep, true, in_isr); } else { // no more pending in this frame -> clear busy - atomic_flag_clear(&_hcd_data.busy); + usbh_spin_lock(in_isr); + _hcd_data.busy_lock = false; + usbh_spin_unlock(in_isr); } return; @@ -1001,8 +1021,8 @@ void print_hirq(uint8_t hirq) { // Interrupt handler void hcd_int_handler(uint8_t rhport, bool in_isr) { uint8_t hirq = reg_read(rhport, HIRQ_ADDR, in_isr) & _hcd_data.hien; - if (!hirq) return; -// print_hirq(hirq); + if (!hirq) { return; } + // print_hirq(hirq); if (hirq & HIRQ_FRAME_IRQ) { _hcd_data.frame_count++; @@ -1021,8 +1041,19 @@ void hcd_int_handler(uint8_t rhport, bool in_isr) { } // start usb transfer if not busy - if (ep_retry != NULL && !atomic_flag_test_and_set(&_hcd_data.busy)) { - xact_generic(rhport, ep_retry, true, in_isr); + if (ep_retry != NULL) { + bool has_xfer = false; + + usbh_spin_lock(in_isr); + if (!_hcd_data.busy_lock) { + _hcd_data.busy_lock = true; + has_xfer = true; + } + usbh_spin_unlock(in_isr); + + if (has_xfer) { + xact_generic(rhport, ep_retry, true, in_isr); + } } } diff --git a/src/portable/analog/max3421/hcd_max3421.h b/src/portable/analog/max3421/hcd_max3421.h new file mode 100644 index 000000000..4631fa21a --- /dev/null +++ b/src/portable/analog/max3421/hcd_max3421.h @@ -0,0 +1,63 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2025 Ha Thach (tinyusb.org) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * This file is part of the TinyUSB stack. + */ +#ifndef TUSB_HCD_MAX3421_H +#define TUSB_HCD_MAX3421_H + +#ifdef __cplusplus + extern "C" { +#endif + +//--------------------------------------------------------------------+ +// SPI transfer API with MAX3421E are implemented by application +// - spi_cs_api(), spi_xfer_api(), int_api() +//--------------------------------------------------------------------+ + +// API to control MAX3421 SPI CS +extern void tuh_max3421_spi_cs_api(uint8_t rhport, bool active); + +// API to transfer data with MAX3421 SPI +// Either tx_buf or rx_buf can be NULL, which means transfer is write or read only +extern bool tuh_max3421_spi_xfer_api(uint8_t rhport, uint8_t const* tx_buf, uint8_t* rx_buf, size_t xfer_bytes); + +// API to enable/disable MAX3421 INTR pin interrupt +extern void tuh_max3421_int_api(uint8_t rhport, bool enabled); + +//--------------------------------------------------------------------+ +// API for read/write MAX3421 registers +// are implemented by this driver, can be used by application +//--------------------------------------------------------------------+ + +// API to read MAX3421's register. Implemented by TinyUSB +uint8_t tuh_max3421_reg_read(uint8_t rhport, uint8_t reg, bool in_isr); + +// API to write MAX3421's register. Implemented by TinyUSB +bool tuh_max3421_reg_write(uint8_t rhport, uint8_t reg, uint8_t data, bool in_isr); + +#ifdef __cplusplus + } +#endif + +#endif diff --git a/src/portable/chipidea/ci_hs/ci_hs_imxrt.h b/src/portable/chipidea/ci_hs/ci_hs_imxrt.h index c59c107ff..75d1d55b8 100644 --- a/src/portable/chipidea/ci_hs/ci_hs_imxrt.h +++ b/src/portable/chipidea/ci_hs/ci_hs_imxrt.h @@ -56,14 +56,23 @@ static const ci_hs_controller_t _ci_controller[] = #define CI_HS_REG(_port) ((ci_hs_regs_t*) _ci_controller[_port].reg_base) //------------- DCD -------------// -#define CI_DCD_INT_ENABLE(_p) NVIC_EnableIRQ (_ci_controller[_p].irqnum) -#define CI_DCD_INT_DISABLE(_p) NVIC_DisableIRQ(_ci_controller[_p].irqnum) +#define CI_DCD_INT_ENABLE(_p) NVIC_EnableIRQ ((IRQn_Type)_ci_controller[_p].irqnum) +#define CI_DCD_INT_DISABLE(_p) NVIC_DisableIRQ((IRQn_Type)_ci_controller[_p].irqnum) //------------- HCD -------------// -#define CI_HCD_INT_ENABLE(_p) NVIC_EnableIRQ (_ci_controller[_p].irqnum) -#define CI_HCD_INT_DISABLE(_p) NVIC_DisableIRQ(_ci_controller[_p].irqnum) +#define CI_HCD_INT_ENABLE(_p) NVIC_EnableIRQ ((IRQn_Type)_ci_controller[_p].irqnum) +#define CI_HCD_INT_DISABLE(_p) NVIC_DisableIRQ((IRQn_Type)_ci_controller[_p].irqnum) //------------- DCache -------------// +#if CFG_TUD_MEM_DCACHE_ENABLE || CFG_TUH_MEM_DCACHE_ENABLE +#if __CORTEX_M == 7 +TU_ATTR_ALWAYS_INLINE static inline uint32_t round_up_to_cache_line_size(uint32_t size) { + if (size & (CFG_TUD_MEM_DCACHE_LINE_SIZE-1)) { + size = (size & ~(CFG_TUD_MEM_DCACHE_LINE_SIZE-1)) + CFG_TUD_MEM_DCACHE_LINE_SIZE; + } + return size; +} + TU_ATTR_ALWAYS_INLINE static inline bool imxrt_is_cache_mem(uintptr_t addr) { return !(0x20000000 <= addr && addr < 0x20100000); } @@ -72,6 +81,7 @@ TU_ATTR_ALWAYS_INLINE static inline bool imxrt_dcache_clean(void const* addr, ui const uintptr_t addr32 = (uintptr_t) addr; if (imxrt_is_cache_mem(addr32)) { TU_ASSERT(tu_is_aligned32(addr32)); + data_size = round_up_to_cache_line_size(data_size); SCB_CleanDCache_by_Addr((uint32_t *) addr32, (int32_t) data_size); } return true; @@ -84,6 +94,7 @@ TU_ATTR_ALWAYS_INLINE static inline bool imxrt_dcache_invalidate(void const* add // *very* careful when we do it. If we're not aligned, then we risk resetting // values back to their RAM state. TU_ASSERT(tu_is_aligned32(addr32)); + data_size = round_up_to_cache_line_size(data_size); SCB_InvalidateDCache_by_Addr((void*) addr32, (int32_t) data_size); } return true; @@ -93,9 +104,15 @@ TU_ATTR_ALWAYS_INLINE static inline bool imxrt_dcache_clean_invalidate(void cons const uintptr_t addr32 = (uintptr_t) addr; if (imxrt_is_cache_mem(addr32)) { TU_ASSERT(tu_is_aligned32(addr32)); + data_size = round_up_to_cache_line_size(data_size); SCB_CleanInvalidateDCache_by_Addr((uint32_t *) addr32, (int32_t) data_size); } return true; } +#elif __CORTEX_M == 4 +#error "Secondary M4 core's cache controller is not supported yet." +#endif +#endif + #endif diff --git a/src/portable/chipidea/ci_hs/dcd_ci_hs.c b/src/portable/chipidea/ci_hs/dcd_ci_hs.c index d9f7ca8ea..244f5a2d4 100644 --- a/src/portable/chipidea/ci_hs/dcd_ci_hs.c +++ b/src/portable/chipidea/ci_hs/dcd_ci_hs.c @@ -34,17 +34,19 @@ #if CFG_TUSB_MCU == OPT_MCU_MIMXRT1XXX #include "ci_hs_imxrt.h" - bool dcd_dcache_clean(void const* addr, uint32_t data_size) { - return imxrt_dcache_clean(addr, data_size); - } +#if CFG_TUD_MEM_DCACHE_ENABLE +bool dcd_dcache_clean(void const* addr, uint32_t data_size) { + return imxrt_dcache_clean(addr, data_size); +} - bool dcd_dcache_invalidate(void const* addr, uint32_t data_size) { - return imxrt_dcache_invalidate(addr, data_size); - } +bool dcd_dcache_invalidate(void const* addr, uint32_t data_size) { + return imxrt_dcache_invalidate(addr, data_size); +} - bool dcd_dcache_clean_invalidate(void const* addr, uint32_t data_size) { - return imxrt_dcache_clean_invalidate(addr, data_size); - } +bool dcd_dcache_clean_invalidate(void const* addr, uint32_t data_size) { + return imxrt_dcache_clean_invalidate(addr, data_size); +} +#endif #elif TU_CHECK_MCU(OPT_MCU_LPC18XX, OPT_MCU_LPC43XX) #include "ci_hs_lpc18_43.h" @@ -237,7 +239,11 @@ bool dcd_init(uint8_t rhport, const tusb_rhport_init_t* rh_init) { usbmode |= USBMODE_CM_DEVICE; dcd_reg->USBMODE = usbmode; +#ifdef CFG_TUD_CI_HS_VBUS_CHARGE + dcd_reg->OTGSC = OTGSC_VBUS_CHARGE | OTGSC_OTG_TERMINATION; +#else dcd_reg->OTGSC = OTGSC_VBUS_DISCHARGE | OTGSC_OTG_TERMINATION; +#endif #if !TUD_OPT_HIGH_SPEED dcd_reg->PORTSC1 = PORTSC1_FORCE_FULL_SPEED; @@ -311,9 +317,7 @@ void dcd_sof_enable(uint8_t rhport, bool en) static void qtd_init(dcd_qtd_t* p_qtd, void * data_ptr, uint16_t total_bytes) { - // Force the CPU to flush the buffer. We increase the size by 31 because the call aligns the - // address to 32-byte boundaries. Buffer must be word aligned - dcd_dcache_clean_invalidate((uint32_t*) tu_align((uint32_t) data_ptr, 4), total_bytes + 31); + dcd_dcache_clean_invalidate((uint32_t*) tu_align((uint32_t) data_ptr, 4), total_bytes); tu_memclr(p_qtd, sizeof(dcd_qtd_t)); @@ -479,7 +483,9 @@ bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t t return true; } +#if !CFG_TUD_MEM_DCACHE_ENABLE // fifo has to be aligned to 4k boundary +// It's incompatible with dcache enabled transfer, since neither address nor size is aligned to cache line bool dcd_edpt_xfer_fifo (uint8_t rhport, uint8_t ep_addr, tu_fifo_t * ff, uint16_t total_bytes) { uint8_t const epnum = tu_edpt_number(ep_addr); @@ -525,8 +531,6 @@ bool dcd_edpt_xfer_fifo (uint8_t rhport, uint8_t ep_addr, tu_fifo_t * ff, uint16 page++; } } - - dcd_dcache_clean_invalidate((uint32_t*) tu_align((uint32_t) fifo_info.ptr_wrap, 4), total_bytes - fifo_info.len_wrap + 31); } else { @@ -541,6 +545,7 @@ bool dcd_edpt_xfer_fifo (uint8_t rhport, uint8_t ep_addr, tu_fifo_t * ff, uint16 return true; } +#endif //--------------------------------------------------------------------+ // ISR diff --git a/src/portable/chipidea/ci_hs/hcd_ci_hs.c b/src/portable/chipidea/ci_hs/hcd_ci_hs.c index 14f8acb45..b5324a754 100644 --- a/src/portable/chipidea/ci_hs/hcd_ci_hs.c +++ b/src/portable/chipidea/ci_hs/hcd_ci_hs.c @@ -35,6 +35,7 @@ //--------------------------------------------------------------------+ #include "common/tusb_common.h" #include "host/hcd.h" +#include "host/usbh.h" #include "portable/ehci/ehci_api.h" #include "ci_hs_type.h" @@ -42,6 +43,7 @@ #include "ci_hs_imxrt.h" +#if CFG_TUH_MEM_DCACHE_ENABLE bool hcd_dcache_clean(void const* addr, uint32_t data_size) { return imxrt_dcache_clean(addr, data_size); } @@ -53,6 +55,7 @@ bool hcd_dcache_invalidate(void const* addr, uint32_t data_size) { bool hcd_dcache_clean_invalidate(void const* addr, uint32_t data_size) { return imxrt_dcache_clean_invalidate(addr, data_size); } +#endif #elif TU_CHECK_MCU(OPT_MCU_LPC18XX, OPT_MCU_LPC43XX) @@ -90,12 +93,6 @@ bool hcd_init(uint8_t rhport, const tusb_rhport_init_t* rh_init) { hcd_reg->USBMODE = USBMODE_CM_HOST; #endif - // FIXME force full speed, still have issue with Highspeed enumeration - // probably due to physical connection bouncing when plug/unplug - // 1. Have issue when plug/unplug devices, maybe the port is not reset properly - // 2. Also does not seems to detect disconnection - hcd_reg->PORTSC1 |= PORTSC1_FORCE_FULL_SPEED; - return ehci_init(rhport, (uint32_t) &hcd_reg->CAPLENGTH, (uint32_t) &hcd_reg->USBCMD); } diff --git a/src/portable/ehci/ehci.c b/src/portable/ehci/ehci.c index 01bbf62bf..da9f49d29 100644 --- a/src/portable/ehci/ehci.c +++ b/src/portable/ehci/ehci.c @@ -34,6 +34,7 @@ #include "osal/osal.h" #include "host/hcd.h" +#include "host/usbh.h" #include "ehci_api.h" #include "ehci.h" @@ -62,8 +63,7 @@ #define QHD_MAX (CFG_TUH_DEVICE_MAX*CFG_TUH_ENDPOINT_MAX + CFG_TUH_HUB) #define QTD_MAX QHD_MAX -typedef struct -{ +typedef struct { ehci_link_t period_framelist[FRAMELIST_SIZE]; // TODO only implement 1 ms & 2 ms & 4 ms, 8 ms (framelist) @@ -139,6 +139,12 @@ static ehci_qhd_t* qhd_get_from_addr (uint8_t dev_addr, uint8_t ep_addr); static void qhd_init(ehci_qhd_t *p_qhd, uint8_t dev_addr, tusb_desc_endpoint_t const * ep_desc); static void qhd_attach_qtd(ehci_qhd_t *qhd, ehci_qtd_t *qtd); static void qhd_remove_qtd(ehci_qhd_t *qhd); +TU_ATTR_ALWAYS_INLINE static inline bool qhd_is_periodic(ehci_qhd_t const *qhd) { + return qhd->int_smask != 0; +} +TU_ATTR_ALWAYS_INLINE static inline uint8_t qhd_ep_addr(ehci_qhd_t const *qhd) { + return tu_edpt_addr(qhd->ep_number, qhd->pid); +} TU_ATTR_ALWAYS_INLINE static inline ehci_qtd_t* qtd_control(uint8_t dev_addr); TU_ATTR_ALWAYS_INLINE static inline ehci_qtd_t* qtd_find_free (void); @@ -146,9 +152,10 @@ static void qtd_init (ehci_qtd_t* qtd, void const* buffer, uint16_t total_bytes) TU_ATTR_ALWAYS_INLINE static inline ehci_link_t* list_get_period_head(uint8_t rhport, uint32_t interval_ms); TU_ATTR_ALWAYS_INLINE static inline ehci_qhd_t* list_get_async_head(uint8_t rhport); -TU_ATTR_ALWAYS_INLINE static inline void list_insert (ehci_link_t *current, ehci_link_t *new, uint8_t new_type); TU_ATTR_ALWAYS_INLINE static inline ehci_link_t* list_next (ehci_link_t const *p_link); -static void list_remove_qhd_by_daddr(ehci_link_t* list_head, uint8_t dev_addr); +TU_ATTR_ALWAYS_INLINE static inline void list_insert (ehci_link_t *current, ehci_link_t *entry, uint8_t type); +TU_ATTR_ALWAYS_INLINE static inline void list_remove(ehci_link_t* head, ehci_link_t* prev, ehci_qhd_t* qhd); +static void list_remove_qhd_by_addr(ehci_link_t *list_head, uint8_t dev_addr, uint8_t ep_addr); static void ehci_disable_schedule(ehci_registers_t* regs, bool is_period) { // maybe have a timeout for status @@ -175,15 +182,12 @@ static void ehci_enable_schedule(ehci_registers_t* regs, bool is_period) { //--------------------------------------------------------------------+ // HCD API //--------------------------------------------------------------------+ - -uint32_t hcd_frame_number(uint8_t rhport) -{ +uint32_t hcd_frame_number(uint8_t rhport) { (void) rhport; return (ehci_data.uframe_number + ehci_data.regs->frame_index) >> 3; } -void hcd_port_reset(uint8_t rhport) -{ +void hcd_port_reset(uint8_t rhport) { (void) rhport; ehci_registers_t* regs = ehci_data.regs; @@ -204,8 +208,7 @@ void hcd_port_reset(uint8_t rhport) regs->portsc = portsc; } -void hcd_port_reset_end(uint8_t rhport) -{ +void hcd_port_reset_end(uint8_t rhport) { (void) rhport; ehci_registers_t* regs = ehci_data.regs; @@ -221,32 +224,29 @@ void hcd_port_reset_end(uint8_t rhport) regs->portsc = portsc; } -bool hcd_port_connect_status(uint8_t rhport) -{ +bool hcd_port_connect_status(uint8_t rhport) { (void) rhport; return ehci_data.regs->portsc_bm.current_connect_status; } -tusb_speed_t hcd_port_speed_get(uint8_t rhport) -{ +tusb_speed_t hcd_port_speed_get(uint8_t rhport) { (void) rhport; return (tusb_speed_t) ehci_data.regs->portsc_bm.nxp_port_speed; // NXP specific port speed } // Close all opened endpoint belong to this device -void hcd_device_close(uint8_t rhport, uint8_t daddr) -{ +void hcd_device_close(uint8_t rhport, uint8_t daddr) { // skip dev0 if (daddr == 0) { return; } - // Remove from async list - list_remove_qhd_by_daddr((ehci_link_t *) list_get_async_head(rhport), daddr); + // Remove from async list all endpoints of this device + list_remove_qhd_by_addr((ehci_link_t *) list_get_async_head(rhport), daddr, TUSB_INDEX_INVALID_8); - // Remove from all interval period list - for(uint8_t i = 0; i < TU_ARRAY_SIZE(ehci_data.period_head_arr); i++) { - list_remove_qhd_by_daddr((ehci_link_t *) &ehci_data.period_head_arr[i], daddr); + // Remove from all interval period list of this device + for (uint8_t i = 0; i < TU_ARRAY_SIZE(ehci_data.period_head_arr); i++) { + list_remove_qhd_by_addr((ehci_link_t *) &ehci_data.period_head_arr[i], daddr, TUSB_INDEX_INVALID_8); } // Async doorbell (EHCI 4.8.2 for operational details) @@ -358,12 +358,10 @@ bool ehci_init(uint8_t rhport, uint32_t capability_reg, uint32_t operatial_reg) } #if 0 -static void ehci_stop(uint8_t rhport) -{ +static void ehci_stop(uint8_t rhport) { (void) rhport; ehci_registers_t* regs = ehci_data.regs; - regs->command_bm.run_stop = 0; // USB Spec: controller has to stop within 16 uframe = 2 frames @@ -375,41 +373,46 @@ static void ehci_stop(uint8_t rhport) // Endpoint API //--------------------------------------------------------------------+ -bool hcd_edpt_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_endpoint_t const * ep_desc) -{ - (void) rhport; - +bool hcd_edpt_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_endpoint_t const * ep_desc) { // TODO not support ISO yet TU_ASSERT (ep_desc->bmAttributes.xfer != TUSB_XFER_ISOCHRONOUS); //------------- Prepare Queue Head -------------// - ehci_qhd_t *p_qhd = (ep_desc->bEndpointAddress == 0) ? qhd_control(dev_addr) : qhd_find_free(); + ehci_qhd_t *p_qhd; + if (ep_desc->bEndpointAddress == 0) { + p_qhd = qhd_control(dev_addr); + } else { + if (NULL != qhd_get_from_addr(dev_addr, ep_desc->bEndpointAddress)) { + return true; // already opened + } + p_qhd = qhd_find_free(); + } TU_ASSERT(p_qhd); - qhd_init(p_qhd, dev_addr, ep_desc); - // control of dev0 is always present as async head - if ( dev_addr == 0 ) return true; + // control of dev0 always exists as async head + if (dev_addr == 0) { + return true; + } // Insert to list ehci_link_t * list_head = NULL; - - switch (ep_desc->bmAttributes.xfer) - { + switch (ep_desc->bmAttributes.xfer) { case TUSB_XFER_CONTROL: case TUSB_XFER_BULK: - list_head = (ehci_link_t*) list_get_async_head(rhport); - break; + list_head = (ehci_link_t *) list_get_async_head(rhport); + break; case TUSB_XFER_INTERRUPT: list_head = list_get_period_head(rhport, p_qhd->interval_ms); - break; + break; case TUSB_XFER_ISOCHRONOUS: // TODO iso is not supported - break; + break; - default: break; + default: + break; } TU_ASSERT(list_head); @@ -421,8 +424,23 @@ bool hcd_edpt_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_endpoint_t const return true; } -bool hcd_setup_send(uint8_t rhport, uint8_t dev_addr, uint8_t const setup_packet[8]) -{ +bool hcd_edpt_close(uint8_t rhport, uint8_t daddr, uint8_t ep_addr) { + ehci_qhd_t* qhd = qhd_get_from_addr(daddr, ep_addr); + TU_VERIFY(qhd != NULL); + + ehci_link_t * list_head; + if (qhd_is_periodic(qhd)) { + // interrupt endpoint + list_head = list_get_period_head(rhport, qhd->interval_ms);; + } else { + list_head = (ehci_link_t *) list_get_async_head(rhport); + } + + list_remove_qhd_by_addr(list_head, daddr, ep_addr); + return true; +} + +bool hcd_setup_send(uint8_t rhport, uint8_t dev_addr, uint8_t const setup_packet[8]) { (void) rhport; ehci_qhd_t* qhd = &ehci_data.control[dev_addr].qhd; @@ -444,14 +462,14 @@ bool hcd_setup_send(uint8_t rhport, uint8_t dev_addr, uint8_t const setup_packet return true; } -bool hcd_edpt_xfer(uint8_t rhport, uint8_t dev_addr, uint8_t ep_addr, uint8_t * buffer, uint16_t buflen) -{ +bool hcd_edpt_xfer(uint8_t rhport, uint8_t dev_addr, uint8_t ep_addr, uint8_t * buffer, uint16_t buflen) { (void) rhport; uint8_t const epnum = tu_edpt_number(ep_addr); uint8_t const dir = tu_edpt_dir(ep_addr); ehci_qhd_t* qhd = qhd_get_from_addr(dev_addr, ep_addr); + TU_VERIFY(qhd != NULL); ehci_qtd_t* qtd; if (epnum == 0) { @@ -540,8 +558,7 @@ bool hcd_edpt_clear_stall(uint8_t rhport, uint8_t daddr, uint8_t ep_addr) { // This isr mean it is safe to modify previously removed queue head from async list. // In tinyusb, queue head is only removed when device is unplugged. TU_ATTR_ALWAYS_INLINE static inline -void async_advance_isr(uint8_t rhport) -{ +void async_advance_isr(uint8_t rhport) { (void) rhport; ehci_qhd_t *qhd_pool = ehci_data.qhd_pool; @@ -612,8 +629,7 @@ void qhd_xfer_complete_isr(ehci_qhd_t * qhd) { } TU_ATTR_ALWAYS_INLINE static inline -void proccess_async_xfer_isr(ehci_qhd_t * const list_head) -{ +void proccess_async_xfer_isr(ehci_qhd_t * const list_head) { ehci_qhd_t *qhd = list_head; do { @@ -623,8 +639,7 @@ void proccess_async_xfer_isr(ehci_qhd_t * const list_head) } TU_ATTR_ALWAYS_INLINE static inline -void process_period_xfer_isr(uint8_t rhport, uint32_t interval_ms) -{ +void process_period_xfer_isr(uint8_t rhport, uint32_t interval_ms) { uint32_t const period_1ms_addr = (uint32_t) list_get_period_head(rhport, 1u); ehci_link_t next_link = *list_get_period_head(rhport, interval_ms); @@ -726,51 +741,55 @@ TU_ATTR_ALWAYS_INLINE static inline ehci_link_t* list_next(ehci_link_t const *p_ return (ehci_link_t*) tu_align32(p_link->address); } -TU_ATTR_ALWAYS_INLINE static inline void list_insert(ehci_link_t *current, ehci_link_t *new, uint8_t new_type) -{ - new->address = current->address; - current->address = ((uint32_t) new) | (new_type << 1); +TU_ATTR_ALWAYS_INLINE static inline void list_insert(ehci_link_t *current, ehci_link_t *entry, uint8_t type) { + entry->address = current->address; + current->address = ((uint32_t) entry) | (type << 1); } -// Remove all queue head belong to this device address -static void list_remove_qhd_by_daddr(ehci_link_t* list_head, uint8_t dev_addr) { - ehci_link_t* prev = list_head; +// Remove a queue head from the list. +// Per EHCI 4.8.2 the removed qhd's next is linked to list head (which always reachable by Host Controller) +// TODO support iTD/siTD +TU_ATTR_ALWAYS_INLINE static inline void list_remove(ehci_link_t* head, ehci_link_t* prev, ehci_qhd_t* qhd) { + // TODO deactivate all TD, wait for QHD to inactive before removal + prev->address = qhd->next.address; + + // link the removed qhd's next to list head + qhd->next.address = ((uint32_t) head) | (EHCI_QTYPE_QHD << 1); + + if (qhd_is_periodic(qhd)) { + // period list queue element is guarantee to be free in the next frame (1 ms) + qhd->used = 0; + } else { + // async list use async advance handshake. Mark as removing, will completely re-usable when async advance isr occurs + qhd->removing = 1; + } + + hcd_dcache_clean(qhd, sizeof(ehci_qhd_t)); + hcd_dcache_clean(prev, sizeof(ehci_qhd_t)); +} + +// Remove queue head belong to this device address +static void list_remove_qhd_by_addr(ehci_link_t *list_head, uint8_t dev_addr, uint8_t ep_addr) { + ehci_link_t *prev = list_head; while (prev && !prev->terminate) { - ehci_qhd_t* qhd = (ehci_qhd_t*) (uintptr_t) list_next(prev); + ehci_qhd_t *qhd = (ehci_qhd_t *) (uintptr_t) list_next(prev); // done if loop back to head - if ( (uintptr_t) qhd == (uintptr_t) list_head) { + if ((uintptr_t) qhd == (uintptr_t) list_head) { break; } - if ( qhd->dev_addr == dev_addr ) { - // TODO deactivate all TD, wait for QHD to inactive before removal - prev->address = qhd->next.address; - - // EHCI 4.8.2 link the removed qhd's next to async head (which always reachable by Host Controller) - qhd->next.address = ((uint32_t) list_head) | (EHCI_QTYPE_QHD << 1); - - if ( qhd->int_smask ) - { - // period list queue element is guarantee to be free in the next frame (1 ms) - qhd->used = 0; - }else - { - // async list use async advance handshake - // mark as removing, will completely re-usable when async advance isr occurs - qhd->removing = 1; - } - - hcd_dcache_clean(qhd, sizeof(ehci_qhd_t)); - hcd_dcache_clean(prev, sizeof(ehci_qhd_t)); - }else { + // ep_addr is 0xff means all endpoints of this device address + if (qhd->dev_addr == dev_addr && + (ep_addr == TUSB_INDEX_INVALID_8 || qhd_ep_addr(qhd) == ep_addr)) { + list_remove(list_head, prev, qhd); + } else { prev = list_next(prev); } } } - //--------------------------------------------------------------------+ // Queue Header helper //--------------------------------------------------------------------+ @@ -782,8 +801,10 @@ TU_ATTR_ALWAYS_INLINE static inline ehci_qhd_t* qhd_control(uint8_t dev_addr) { // Find a free queue head TU_ATTR_ALWAYS_INLINE static inline ehci_qhd_t *qhd_find_free(void) { - for ( uint32_t i = 0; i < QHD_MAX; i++ ) { - if ( !ehci_data.qhd_pool[i].used ) return &ehci_data.qhd_pool[i]; + for (uint32_t i = 0; i < QHD_MAX; i++) { + if (!ehci_data.qhd_pool[i].used) { + return &ehci_data.qhd_pool[i]; + } } return NULL; } @@ -800,10 +821,9 @@ static ehci_qhd_t *qhd_get_from_addr(uint8_t dev_addr, uint8_t ep_addr) { } ehci_qhd_t *qhd_pool = ehci_data.qhd_pool; - - for ( uint32_t i = 0; i < QHD_MAX; i++ ) { - if ( (qhd_pool[i].dev_addr == dev_addr) && - ep_addr == tu_edpt_addr(qhd_pool[i].ep_number, qhd_pool[i].pid) ) { + for (uint32_t i = 0; i < QHD_MAX; i++) { + if ((qhd_pool[i].dev_addr == dev_addr) && + ep_addr == qhd_ep_addr(&qhd_pool[i])) { return &qhd_pool[i]; } } @@ -812,15 +832,14 @@ static ehci_qhd_t *qhd_get_from_addr(uint8_t dev_addr, uint8_t ep_addr) { } // Init queue head with endpoint descriptor -static void qhd_init(ehci_qhd_t *p_qhd, uint8_t dev_addr, tusb_desc_endpoint_t const * ep_desc) -{ +static void qhd_init(ehci_qhd_t *p_qhd, uint8_t dev_addr, tusb_desc_endpoint_t const * ep_desc) { // address 0 is used as async head, which always on the list --> cannot be cleared (ehci halted otherwise) if (dev_addr != 0) { tu_memclr(p_qhd, sizeof(ehci_qhd_t)); } - hcd_devtree_info_t devtree_info; - hcd_devtree_get_info(dev_addr, &devtree_info); + tuh_bus_info_t bus_info; + tuh_bus_info_get(dev_addr, &bus_info); uint8_t const xfer_type = ep_desc->bmAttributes.xfer; uint8_t const interval = ep_desc->bInterval; @@ -828,45 +847,49 @@ static void qhd_init(ehci_qhd_t *p_qhd, uint8_t dev_addr, tusb_desc_endpoint_t c p_qhd->dev_addr = dev_addr; p_qhd->fl_inactive_next_xact = 0; p_qhd->ep_number = tu_edpt_number(ep_desc->bEndpointAddress); - p_qhd->ep_speed = devtree_info.speed; + p_qhd->ep_speed = bus_info.speed; p_qhd->data_toggle_control= (xfer_type == TUSB_XFER_CONTROL) ? 1 : 0; - p_qhd->head_list_flag = (dev_addr == 0) ? 1 : 0; // addr0's endpoint is the static asyn list head + p_qhd->head_list_flag = (dev_addr == 0) ? 1 : 0; // addr0's endpoint is the static async list head p_qhd->max_packet_size = tu_edpt_packet_size(ep_desc); p_qhd->fl_ctrl_ep_flag = ((xfer_type == TUSB_XFER_CONTROL) && (p_qhd->ep_speed != TUSB_SPEED_HIGH)) ? 1 : 0; p_qhd->nak_reload = 0; - // Bulk/Control -> smask = cmask = 0 - // TODO Isochronous - if (TUSB_XFER_INTERRUPT == xfer_type) - { - if (TUSB_SPEED_HIGH == p_qhd->ep_speed) - { - TU_ASSERT( interval <= 16, ); - if ( interval < 4) // sub millisecond interval - { - p_qhd->interval_ms = 0; - p_qhd->int_smask = (interval == 1) ? TU_BIN8(11111111) : - (interval == 2) ? TU_BIN8(10101010) : TU_BIN8(01000100); - }else - { - p_qhd->interval_ms = (uint8_t) tu_min16( 1 << (interval-4), 255 ); - p_qhd->int_smask = TU_BIT(interval % 8); + switch (xfer_type) { + case TUSB_XFER_CONTROL: + case TUSB_XFER_BULK: + p_qhd->int_smask = p_qhd->fl_int_cmask = 0; + break; + + case TUSB_XFER_INTERRUPT: + if (TUSB_SPEED_HIGH == p_qhd->ep_speed) { + TU_ASSERT(interval <= 16, ); + if (interval < 4) { + // sub millisecond interval + p_qhd->interval_ms = 0; + p_qhd->int_smask = (interval == 1) ? TU_BIN8(11111111) : + (interval == 2) ? TU_BIN8(10101010): TU_BIN8(01000100); + } else { + p_qhd->interval_ms = (uint8_t) tu_min16(1 << (interval - 4), 255); + p_qhd->int_smask = TU_BIT(interval % 8); + } + } else { + TU_ASSERT(0 != interval, ); + // Full/Low: 4.12.2.1 (EHCI) case 1 schedule start split at 1 us & complete split at 2,3,4 uframes + p_qhd->int_smask = 0x01; + p_qhd->fl_int_cmask = TU_BIN8(11100); + p_qhd->interval_ms = interval; } - }else - { - TU_ASSERT( 0 != interval, ); - // Full/Low: 4.12.2.1 (EHCI) case 1 schedule start split at 1 us & complete split at 2,3,4 uframes - p_qhd->int_smask = 0x01; - p_qhd->fl_int_cmask = TU_BIN8(11100); - p_qhd->interval_ms = interval; - } - }else - { - p_qhd->int_smask = p_qhd->fl_int_cmask = 0; + break; + + case TUSB_XFER_ISOCHRONOUS: + // TODO not support ISO yet + break; + + default: break; } - p_qhd->fl_hub_addr = devtree_info.hub_addr; - p_qhd->fl_hub_port = devtree_info.hub_port; + p_qhd->fl_hub_addr = bus_info.hub_addr; + p_qhd->fl_hub_port = bus_info.hub_port; p_qhd->mult = 1; // TODO not use high bandwidth/park mode yet //------------- HCD Management Data -------------// @@ -880,8 +903,7 @@ static void qhd_init(ehci_qhd_t *p_qhd, uint8_t dev_addr, tusb_desc_endpoint_t c p_qhd->qtd_overlay.next.terminate = 1; p_qhd->qtd_overlay.alternate.terminate = 1; - if (TUSB_XFER_BULK == xfer_type && p_qhd->ep_speed == TUSB_SPEED_HIGH && p_qhd->pid == EHCI_PID_OUT) - { + if (TUSB_XFER_BULK == xfer_type && p_qhd->ep_speed == TUSB_SPEED_HIGH && p_qhd->pid == EHCI_PID_OUT) { p_qhd->qtd_overlay.ping_err = 1; // do PING for Highspeed Bulk OUT, EHCI section 4.11 } } diff --git a/src/portable/ehci/ehci.h b/src/portable/ehci/ehci.h index 457adc1d3..87659701b 100644 --- a/src/portable/ehci/ehci.h +++ b/src/portable/ehci/ehci.h @@ -49,15 +49,14 @@ // TODO merge OHCI with EHCI enum { - EHCI_MAX_ITD = 4, + EHCI_MAX_ITD = 4, EHCI_MAX_SITD = 16 }; //--------------------------------------------------------------------+ // EHCI Data Structure //--------------------------------------------------------------------+ -enum -{ +enum { EHCI_QTYPE_ITD = 0 , EHCI_QTYPE_QHD , EHCI_QTYPE_SITD , @@ -65,8 +64,7 @@ enum }; /// EHCI PID -enum -{ +enum { EHCI_PID_OUT = 0 , EHCI_PID_IN , EHCI_PID_SETUP @@ -74,187 +72,182 @@ enum /// Link pointer typedef union { - uint32_t address; - struct { - uint32_t terminate : 1; - uint32_t type : 2; - }; -}ehci_link_t; + uint32_t address; + struct { + uint32_t terminate : 1; + uint32_t type : 2; + }; +} ehci_link_t; TU_VERIFY_STATIC( sizeof(ehci_link_t) == 4, "size is not correct" ); /// Queue Element Transfer Descriptor /// Qtd is used to declare overlay in ehci_qhd_t -> cannot be declared with TU_ATTR_ALIGNED(32) -typedef struct -{ - // Word 0: Next QTD Pointer - ehci_link_t next; +typedef struct { + // Word 0 Next QTD Pointer + ehci_link_t next; - // Word 1: Alternate Next QTD Pointer (not used) - union{ - ehci_link_t alternate; - struct { - uint32_t : 5; - uint32_t used : 1; - uint32_t : 10; - uint32_t expected_bytes : 16; - }; - }; + // Word 1 Alternate Next QTD Pointer (not used) + union { + ehci_link_t alternate; + struct { + uint32_t : 5; + uint32_t used : 1; + uint32_t : 10; + uint32_t expected_bytes : 16; + }; + }; - // Word 2: qTQ Token - volatile uint32_t ping_err : 1 ; ///< For Highspeed: 0 Out, 1 Ping. Full/Slow used as error indicator - volatile uint32_t non_hs_split_state : 1 ; ///< Used by HC to track the state of split transaction - volatile uint32_t non_hs_missed_uframe : 1 ; ///< HC misses a complete split transaction - volatile uint32_t xact_err : 1 ; ///< Error (Timeout, CRC, Bad PID ... ) - volatile uint32_t babble_err : 1 ; ///< Babble detected, also set Halted bit to 1 - volatile uint32_t buffer_err : 1 ; ///< Data overrun/underrun error - volatile uint32_t halted : 1 ; ///< Serious error or STALL received - volatile uint32_t active : 1 ; ///< Start transfer, clear by HC when complete + // Word 2 qTQ Token + volatile uint32_t ping_err : 1; // For Highspeed: 0 Out, 1 Ping. Full/Slow used as error indicator + volatile uint32_t non_hs_split_state : 1; // Used by HC to track the state of split transaction + volatile uint32_t non_hs_missed_uframe : 1; // HC misses a complete split transaction + volatile uint32_t xact_err : 1; // Error (Timeout, CRC, Bad PID ... ) + volatile uint32_t babble_err : 1; // Babble detected, also set Halted bit to 1 + volatile uint32_t buffer_err : 1; // Data overrun/underrun error + volatile uint32_t halted : 1; // Serious error or STALL received + volatile uint32_t active : 1; // Start transfer, clear by HC when complete - uint32_t pid : 2 ; ///< 0: OUT, 1: IN, 2 Setup - volatile uint32_t err_count : 2 ; ///< Error Counter of consecutive errors - volatile uint32_t current_page : 3 ; ///< Index into the qTD buffer pointer list - uint32_t int_on_complete : 1 ; ///< Interrupt on complete - volatile uint32_t total_bytes : 15 ; ///< Transfer bytes, decreased during transaction - volatile uint32_t data_toggle : 1 ; ///< Data Toggle bit + uint32_t pid : 2; // 0: OUT, 1: IN, 2 Setup + volatile uint32_t err_count : 2; // Error Counter of consecutive errors + volatile uint32_t current_page : 3; // Index into the qTD buffer pointer list + uint32_t int_on_complete : 1; // Interrupt on complete + volatile uint32_t total_bytes : 15; // Transfer bytes, decreased during transaction + volatile uint32_t data_toggle : 1; // Data Toggle bit - - /// Buffer Page Pointer List, Each element in the list is a 4K page aligned, physical memory address. The lower 12 bits in each pointer are reserved (except for the first one) as each memory pointer must reference the start of a 4K page - uint32_t buffer[5]; + // Buffer Page Pointer List, Each element in the list is a 4K page aligned, physical memory address. + // The lower 12 bits in each pointer are reserved (except for the first one) as each memory pointer must reference the start of a 4K page + uint32_t buffer[5]; } ehci_qtd_t; TU_VERIFY_STATIC( sizeof(ehci_qtd_t) == 32, "size is not correct" ); /// Queue Head -typedef struct TU_ATTR_ALIGNED(32) -{ - // Word 0: Next QHD - ehci_link_t next; +typedef struct TU_ATTR_ALIGNED(32) { + // Word 0 Next QHD + ehci_link_t next; - // Word 1: Endpoint Characteristics - uint32_t dev_addr : 7 ; ///< device address - uint32_t fl_inactive_next_xact : 1 ; ///< Only valid for Periodic with Full/Slow speed - uint32_t ep_number : 4 ; ///< EP number - uint32_t ep_speed : 2 ; ///< 0: Full, 1: Low, 2: High - uint32_t data_toggle_control : 1 ; ///< 0: use DT in qHD, 1: use DT in qTD - uint32_t head_list_flag : 1 ; ///< Head of the queue - uint32_t max_packet_size : 11 ; ///< Max packet size - uint32_t fl_ctrl_ep_flag : 1 ; ///< 1 if is Full/Low speed control endpoint - uint32_t nak_reload : 4 ; ///< Used by HC + // Word 1 Endpoint Characteristics + uint32_t dev_addr : 7; // device address + uint32_t fl_inactive_next_xact : 1; // Only valid for Periodic with Full/Slow speed + uint32_t ep_number : 4; // EP number + uint32_t ep_speed : 2; // Full (0), Low (1), High (2) + uint32_t data_toggle_control : 1; // 0 use DT in qHD, 1 use DT in qTD + uint32_t head_list_flag : 1; // Head of the queue + uint32_t max_packet_size : 11; // Max packet size + uint32_t fl_ctrl_ep_flag : 1; // 1 if is Full/Low speed control endpoint + uint32_t nak_reload : 4; // Used by HC - // Word 2: Endpoint Capabilities - uint32_t int_smask : 8 ; ///< Interrupt Schedule Mask - uint32_t fl_int_cmask : 8 ; ///< Split Completion Mask for Full/Slow speed - uint32_t fl_hub_addr : 7 ; ///< Hub Address for Full/Slow speed - uint32_t fl_hub_port : 7 ; ///< Hub Port for Full/Slow speed - uint32_t mult : 2 ; ///< Transaction per micro frame + // Word 2 Endpoint Capabilities + uint32_t int_smask : 8; // Interrupt Schedule Mask + uint32_t fl_int_cmask : 8; // Split Completion Mask for Full/Slow speed + uint32_t fl_hub_addr : 7; // Hub Address for Full/Slow speed + uint32_t fl_hub_port : 7; // Hub Port for Full/Slow speed + uint32_t mult : 2; // Transaction per micro frame - // Word 3: Current qTD Pointer - volatile uint32_t qtd_addr; + // Word 3 Current qTD Pointer + volatile uint32_t qtd_addr; - // Word 4-11: Transfer Overlay - volatile ehci_qtd_t qtd_overlay; + // Word 4-11 Transfer Overlay + volatile ehci_qtd_t qtd_overlay; - //--------------------------------------------------------------------+ - /// Due to the fact QHD is 32 bytes aligned but occupies only 48 bytes - /// thus there are 16 bytes padding free that we can make use of. //--------------------------------------------------------------------+ - uint8_t used; - uint8_t removing; // removed from asyn list, waiting for async advance - uint8_t pid; - uint8_t interval_ms; // polling interval in frames (or millisecond) + /// Due to the fact QHD is 32 bytes aligned but occupies only 48 bytes + /// thus there are 16 bytes padding free that we can make use of. + //--------------------------------------------------------------------+ + uint8_t used; + uint8_t removing;// removed from asyn list, waiting for async advance + uint8_t pid; + uint8_t interval_ms;// polling interval in frames (or millisecond) - uint8_t TU_RESERVED[4]; + uint8_t TU_RESERVED[4]; // Attached TD management, note usbh will only queue 1 TD per QHD. // buffer for dcache invalidate since td's buffer is modified by HC and finding initial buffer address is not trivial uint32_t attached_buffer; - ehci_qtd_t * volatile attached_qtd; + ehci_qtd_t *volatile attached_qtd; } ehci_qhd_t; - TU_VERIFY_STATIC( sizeof(ehci_qhd_t) == 64, "size is not correct" ); /// Highspeed Isochronous Transfer Descriptor (section 3.3) typedef struct TU_ATTR_ALIGNED(32) { - // Word 0: Next Link Pointer - ehci_link_t next; + // Word 0: Next Link Pointer + ehci_link_t next; - // Word 1-8: iTD Transaction Status and Control List - struct { - // iTD Control - volatile uint32_t offset : 12 ; ///< This field is a value that is an offset, expressed in bytes, from the beginning of a buffer. - volatile uint32_t page_select : 3 ; ///< These bits are set by software to indicate which of the buffer page pointers the offset field in this slot should be concatenated to produce the starting memory address for this transaction. The valid range of values for this field is 0 to 6 - uint32_t int_on_complete : 1 ; ///< If this bit is set to a one, it specifies that when this transaction completes, the Host Controller should issue an interrupt at the next interrupt threshold - volatile uint32_t length : 12 ; ///< For an OUT, this field is the number of data bytes the host controller will send during the transaction. The host controller is not required to update this field to reflect the actual number of bytes transferred during the transfer - ///< For an IN, the initial value of the field is the number of bytes the host expects the endpoint to deliver. During the status update, the host controller writes back the number of bytes successfully received. The value in this register is the actual byte count - // iTD Status - volatile uint32_t error : 1 ; ///< Set to a one by the Host Controller during status update in the case where the host did not receive a valid response from the device (Timeout, CRC, Bad PID, etc.). This bit may only be set for isochronous IN transactions. - volatile uint32_t babble_err : 1 ; ///< Set to a 1 by the Host Controller during status update when a babble is detected during the transaction - volatile uint32_t buffer_err : 1 ; ///< Set to a 1 by the Host Controller during status update to indicate that the Host Controller is unable to keep up with the reception of incoming data (overrun) or is unable to supply data fast enough during transmission (underrun). - volatile uint32_t active : 1 ; ///< Set to 1 by software to enable the execution of an isochronous transaction by the Host Controller - } xact[8]; + // Word 1-8: iTD Transaction Status and Control List + struct { + // iTD Control + volatile uint32_t offset : 12; // offset in bytes, from the beginning of a buffer. + volatile uint32_t page_select : 3; // buffer page pointers the offset field in this slot should be concatenated to produce the starting memory address for this transaction. The valid range of values for this field is 0 to 6 + uint32_t int_on_complete : 1; // If this bit is set to a one, it specifies that when this transaction completes, the Host Controller should issue an interrupt at the next interrupt threshold + volatile uint32_t length : 12; // For an OUT, this field is the number of data bytes the host controller will send during the transaction. The host controller is not required to update this field to reflect the actual number of bytes transferred during the transfer + // For an IN, the initial value of the field is the number of bytes the host expects the endpoint to deliver. During the status update, the host controller writes back the number of bytes successfully received. The value in this register is the actual byte count + // iTD Status + volatile uint32_t error : 1; // Set to a one by the Host Controller during status update in the case where the host did not receive a valid response from the device (Timeout, CRC, Bad PID, etc.). This bit may only be set for isochronous IN transactions. + volatile uint32_t babble_err : 1; // Set to a 1 by the Host Controller during status update when a babble is detected during the transaction + volatile uint32_t buffer_err : 1; // Set to a 1 by the Host Controller during status update to indicate that the Host Controller is unable to keep up with the reception of incoming data (overrun) or is unable to supply data fast enough during transmission (underrun). + volatile uint32_t active : 1; // Set to 1 by software to enable the execution of an isochronous transaction by the Host Controller + } xact[8]; - // Word 9-15 Buffer Page Pointer List (Plus) - uint32_t BufferPointer[7]; + // Word 9-15 Buffer Page Pointer List (Plus) + uint32_t BufferPointer[7]; -// // FIXME: Store meta data into buffer pointer reserved for saving memory -// /*---------- HCD Area ----------*/ -// uint32_t used; -// uint32_t IhdIdx; -// uint32_t reserved[6]; + // FIXME: Store meta data into buffer pointer reserved for saving memory + //---------- HCD Area ---------- + // uint32_t used; + // uint32_t IhdIdx; + // uint32_t reserved[6]; } ehci_itd_t; - TU_VERIFY_STATIC( sizeof(ehci_itd_t) == 64, "size is not correct" ); /// Split (Full-Speed) Isochronous Transfer Descriptor -typedef struct TU_ATTR_ALIGNED(32) -{ +typedef struct TU_ATTR_ALIGNED(32) { // Word 0: Next Link Pointer - ehci_link_t next; + ehci_link_t next; - // Word 1: siTD Endpoint Characteristics - uint32_t dev_addr : 7; ///< This field selects the specific device serving as the data source or sink. - uint32_t : 1; ///< reserved - uint32_t ep_number : 4; ///< This 4-bit field selects the particular endpoint number on the device serving as the data source or sink. - uint32_t : 4; ///< This field is reserved and should be set to zero. - uint32_t hub_addr : 7; ///< This field holds the device address of the transaction translators’ hub. - uint32_t : 1; ///< reserved - uint32_t port_number : 7; ///< This field is the port number of the recipient transaction translator. - uint32_t direction : 1; ///< 0 = OUT; 1 = IN. This field encodes whether the full-speed transaction should be an IN or OUT. + // Word 1: siTD Endpoint Characteristics + uint32_t dev_addr : 7; ///< This field selects the specific device serving as the data source or sink. + uint32_t : 1; ///< reserved + uint32_t ep_number : 4; ///< This 4-bit field selects the particular endpoint number on the device serving as the data source or sink. + uint32_t : 4; ///< This field is reserved and should be set to zero. + uint32_t hub_addr : 7; ///< This field holds the device address of the transaction translators’ hub. + uint32_t : 1; ///< reserved + uint32_t port_number : 7; ///< This field is the port number of the recipient transaction translator. + uint32_t direction : 1; ///< 0 = OUT; 1 = IN. This field encodes whether the full-speed transaction should be an IN or OUT. - // Word 2: Micro-frame Schedule Control - uint8_t int_smask ; ///< This field (along with the Activeand SplitX-statefields in the Statusbyte) are used to determine during which micro-frames the host controller should execute complete-split transactions - uint8_t fl_int_cmask; ///< This field (along with the Activeand SplitX-statefields in the Statusbyte) are used to determine during which micro-frames the host controller should execute start-split transactions. - uint16_t reserved ; ///< reserved + // Word 2: Micro-frame Schedule Control + uint8_t int_smask ; ///< This field (along with the Activeand SplitX-statefields in the Statusbyte) are used to determine during which micro-frames the host controller should execute complete-split transactions + uint8_t fl_int_cmask; ///< This field (along with the Activeand SplitX-statefields in the Statusbyte) are used to determine during which micro-frames the host controller should execute start-split transactions. + uint16_t reserved ; ///< reserved - // Word 3: siTD Transfer Status and Control - // Status [7:0] TODO identical to qTD Token'status --> refactor later - volatile uint32_t : 1 ; // reserved - volatile uint32_t split_state : 1 ; - volatile uint32_t missed_uframe : 1 ; - volatile uint32_t xact_err : 1 ; - volatile uint32_t babble_err : 1 ; - volatile uint32_t buffer_err : 1 ; - volatile uint32_t error : 1 ; - volatile uint32_t active : 1 ; - // Micro-frame Schedule Control - volatile uint32_t cmask_progress : 8 ; ///< This field is used by the host controller to record which split-completes have been executed. See Section 4.12.3.3.2 for behavioral requirements. - volatile uint32_t total_bytes : 10 ; ///< This field is initialized by software to the total number of bytes expected in this transfer. Maximum value is 1023 - volatile uint32_t : 4 ; ///< reserved - volatile uint32_t page_select : 1 ; ///< Used to indicate which data page pointer should be concatenated with the CurrentOffsetfield to construct a data buffer pointer - uint32_t int_on_complete : 1 ; ///< Do not interrupt when transaction is complete. 1 = Do interrupt when transaction is complete - uint32_t : 0 ; // padding to the end of current storage unit + // Word 3: siTD Transfer Status and Control + // Status [7:0] TODO identical to qTD Token'status --> refactor later + volatile uint32_t : 1 ; // reserved + volatile uint32_t split_state : 1 ; + volatile uint32_t missed_uframe : 1 ; + volatile uint32_t xact_err : 1 ; + volatile uint32_t babble_err : 1 ; + volatile uint32_t buffer_err : 1 ; + volatile uint32_t error : 1 ; + volatile uint32_t active : 1 ; + // Micro-frame Schedule Control + volatile uint32_t cmask_progress : 8 ; ///< This field is used by the host controller to record which split-completes have been executed. See Section 4.12.3.3.2 for behavioral requirements. + volatile uint32_t total_bytes : 10 ; ///< This field is initialized by software to the total number of bytes expected in this transfer. Maximum value is 1023 + volatile uint32_t : 4 ; ///< reserved + volatile uint32_t page_select : 1 ; ///< Used to indicate which data page pointer should be concatenated with the CurrentOffsetfield to construct a data buffer pointer + uint32_t int_on_complete : 1 ; ///< Do not interrupt when transaction is complete. 1 = Do interrupt when transaction is complete + uint32_t : 0 ; // padding to the end of current storage unit - /// Word 4-5: Buffer Pointer List - uint32_t buffer[2]; // buffer[1] TP: Transaction Position - T-Count: Transaction Count + /// Word 4-5: Buffer Pointer List + uint32_t buffer[2]; // buffer[1] TP: Transaction Position - T-Count: Transaction Count - /*---------- Word 6 ----------*/ - ehci_link_t back; + /*---------- Word 6 ----------*/ + ehci_link_t back; - /// SITD is 32-byte aligned but occupies only 28 --> 4 bytes for storing extra data - uint8_t used; - uint8_t ihd_idx; - uint8_t reserved2[2]; + /// SITD is 32-byte aligned but occupies only 28 --> 4 bytes for storing extra data + uint8_t used; + uint8_t ihd_idx; + uint8_t reserved2[2]; } ehci_sitd_t; TU_VERIFY_STATIC( sizeof(ehci_sitd_t) == 32, "size is not correct" ); @@ -315,8 +308,7 @@ enum { EHCI_PORTSC_MASK_OVER_CURRENT_CHANGE }; -typedef volatile struct -{ +typedef volatile struct { union { uint32_t command; // 0x00 diff --git a/src/portable/mentor/musb/hcd_musb.c b/src/portable/mentor/musb/hcd_musb.c index 1c0740193..dcc023e0b 100644 --- a/src/portable/mentor/musb/hcd_musb.c +++ b/src/portable/mentor/musb/hcd_musb.c @@ -36,6 +36,7 @@ _Pragma("GCC diagnostic ignored \"-Waddress-of-packed-member\""); #endif #include "host/hcd.h" +#include "host/usbh.h" #include "musb_type.h" @@ -695,16 +696,16 @@ bool hcd_setup_send(uint8_t rhport, uint8_t dev_addr, uint8_t const setup_packet _hcd.pipe0.length = 8; _hcd.pipe0.remaining = 0; - hcd_devtree_info_t devtree; - hcd_devtree_get_info(dev_addr, &devtree); - switch (devtree.speed) { + tuh_bus_info_t bus_info; + tuh_bus_info_get(dev_addr, &bus_info); + switch (bus_info.speed) { default: return false; case TUSB_SPEED_LOW: USB0->TYPE0 = USB_TYPE0_SPEED_LOW; break; case TUSB_SPEED_FULL: USB0->TYPE0 = USB_TYPE0_SPEED_FULL; break; case TUSB_SPEED_HIGH: USB0->TYPE0 = USB_TYPE0_SPEED_HIGH; break; } - USB0->TXHUBADDR0 = devtree.hub_addr; - USB0->TXHUBPORT0 = devtree.hub_port; + USB0->TXHUBADDR0 = bus_info.hub_addr; + USB0->TXHUBPORT0 = bus_info.hub_port; USB0->TXFUNCADDR0 = dev_addr; USB0->CSRL0 = USB_CSRL0_TXRDY | USB_CSRL0_SETUP; return true; @@ -744,9 +745,9 @@ bool hcd_edpt_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_endpoint_t const pipe->remaining = 0; uint8_t pipe_type = 0; - hcd_devtree_info_t devtree; - hcd_devtree_get_info(dev_addr, &devtree); - switch (devtree.speed) { + tuh_bus_info_t bus_info; + tuh_bus_info_get(dev_addr, &bus_info); + switch (bus_info.speed) { default: return false; case TUSB_SPEED_LOW: pipe_type |= USB_TXTYPE1_SPEED_LOW; break; case TUSB_SPEED_FULL: pipe_type |= USB_TXTYPE1_SPEED_FULL; break; @@ -763,8 +764,8 @@ bool hcd_edpt_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_endpoint_t const hw_endpoint_t volatile *regs = edpt_regs(pipenum - 1); if (dir_tx) { fadr->TXFUNCADDR = dev_addr; - fadr->TXHUBADDR = devtree.hub_addr; - fadr->TXHUBPORT = devtree.hub_port; + fadr->TXHUBADDR = bus_info.hub_addr; + fadr->TXHUBPORT = bus_info.hub_port; regs->TXMAXP = mps; regs->TXTYPE = pipe_type | epn; regs->TXINTERVAL = ep_desc->bInterval; @@ -775,8 +776,8 @@ bool hcd_edpt_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_endpoint_t const USB0->TXIE |= TU_BIT(pipenum); } else { fadr->RXFUNCADDR = dev_addr; - fadr->RXHUBADDR = devtree.hub_addr; - fadr->RXHUBPORT = devtree.hub_port; + fadr->RXHUBADDR = bus_info.hub_addr; + fadr->RXHUBPORT = bus_info.hub_port; regs->RXMAXP = mps; regs->RXTYPE = pipe_type | epn; regs->RXINTERVAL = ep_desc->bInterval; @@ -804,6 +805,11 @@ bool hcd_edpt_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_endpoint_t const return true; } +bool hcd_edpt_close(uint8_t rhport, uint8_t daddr, uint8_t ep_addr) { + (void) rhport; (void) daddr; (void) ep_addr; + return false; // TODO not implemented yet +} + bool hcd_edpt_xfer(uint8_t rhport, uint8_t dev_addr, uint8_t ep_addr, uint8_t *buffer, uint16_t buflen) { (void)rhport; diff --git a/src/portable/microchip/pic/README.md b/src/portable/microchip/pic/README.md new file mode 100644 index 000000000..7ba6a4a96 --- /dev/null +++ b/src/portable/microchip/pic/README.md @@ -0,0 +1,51 @@ +# Microchip PIC Chipidea FS Driver + +This driver adds support for Microchip PIC microcontrollers with full-speed Chipidea USB peripheral to the TinyUSB stack. It supports the following families: + +- PIC32MX (untested) +- PIC32MM +- PIC32MK (untested) +- PIC24FJ +- PIC24EP (untested) +- dsPIC33EP (untested) + +Currently only the device mode is supported. + + +## Important Notes + +### Handling of shared VBUS & GPIO pin + +Some PICs have the USB VBUS pin bonded with a GPIO pin in the chip package. This driver does **NOT** handle the potential conflict between the VBUS and GPIO functionalities. + +Developers must ensure that the GPIO pin is tristated when the VBUS pin is managed by the USB peripheral in order to prevent damaging the chip. + +This design choice allows developers the flexibility to use the GPIO functionality for controlling VBUS in device mode if desired. + + +## TODO + +### Handle USB remote wakeup timing correctly + +The Chipidea FS IP doesn't handle the RESUME signal automatically and it must be managed in software. It needs to be asserted for exactly 10ms, and this is impossible to do without per-device support due to BSP differences. For now, a simple for-based loop is used. + +### 8-bit PIC support + +The 8-bit PICs also uses the Chipidea FS IP. Technically it's possible to support them as well. + +Possible difficulties: +- Memory size constraints (1KB/8KB ballpark) +- A third BDT layout (now we have two) +- Different compiler-specific directives +- Compiler bugs if you use SDCC + + +## Author +[ReimuNotMoe](https://github.com/ReimuNotMoe) at SudoMaker, Ltd. + + +## Credits + +This driver is based on: +- Microchip's USB driver (usb_device.c) +- TinyUSB's NXP KHCI driver (dcd_khci.c) diff --git a/src/portable/microchip/pic/dcd_pic.c b/src/portable/microchip/pic/dcd_pic.c index d40c4794a..b4a698199 100644 --- a/src/portable/microchip/pic/dcd_pic.c +++ b/src/portable/microchip/pic/dcd_pic.c @@ -1,8 +1,11 @@ /* * The MIT License (MIT) * - * Copyright (c) 2020 Koji Kitayama - * Copyright (c) 2022 Reimu NotMoe + * Copyright (c) 2022-2024 SudoMaker, Ltd. + * Author: Mike Yang (Reimu NotMoe) + * + * Based on usb_device.c - Copyright (c) 2015 Microchip Technology Inc. + * Based on dcd_khci.c - Copyright (c) 2020 Koji Kitayama * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -313,12 +316,23 @@ static void prepare_next_setup_packet(uint8_t rhport) { const unsigned out_odd = _dcd.endpoint[0][0].odd; const unsigned in_odd = _dcd.endpoint[0][1].odd; - TU_ASSERT(0 == _dcd.bdt[0][0][out_odd].own, ); + + // Abandon any previous control transfers that might have been using EP0. + // Ordinarily, nothing actually needs abandoning, since the previous control + // transfer would have completed successfully prior to the host sending the + // next SETUP packet. However, in a timeout error case, or after an EP0 + // STALL event, one or more UOWN bits might still be set. If so, we should + // clear the UOWN bits, so the EP0 IN/OUT endpoints are in a known inactive + // state, ready for re-arming by the `dcd_edpt_xfer' function that will be + // called next. _dcd.bdt[0][0][out_odd].data = 0; + _dcd.bdt[0][0][out_odd].own = 0; _dcd.bdt[0][0][out_odd ^ 1].data = 1; _dcd.bdt[0][1][in_odd].data = 1; + _dcd.bdt[0][1][in_odd].own = 0; _dcd.bdt[0][1][in_odd ^ 1].data = 0; + _dcd.bdt[0][1][in_odd ^ 1].own = 0; dcd_edpt_xfer(rhport, tu_edpt_addr(0, TUSB_DIR_OUT), _dcd.setup_packet, sizeof(_dcd.setup_packet)); } @@ -475,13 +489,12 @@ bool dcd_init(uint8_t rhport, const tusb_rhport_init_t* rh_init) { intr_disable(rhport); intr_clear(rhport); -#if CFG_TUSB_MCU == OPT_MCU_PIC32MM - TRISBbits.TRISB6 = 1; -#endif - tu_memclr(&_dcd, sizeof(_dcd)); #if TU_PIC_INT_SIZE == 4 + // The USBBUSY bit is present on PIC32s and we're required to check it + // prior to powering on the USB peripheral (see DS61126F page 27) + while (U1PWRCbits.USBBUSY); U1PWRCSET = _U1PWRC_USBPWR_MASK; #else U1PWRCbits.USBPWR = 1; @@ -505,6 +518,19 @@ bool dcd_init(uint8_t rhport, const tusb_rhport_init_t* rh_init) { return true; } +bool dcd_deinit(uint8_t rhport) +{ + U1CON = 0; + U1IE = 0; + U1OTGIE = 0; +#if TU_PIC_INT_SIZE == 4 + U1PWRCCLR = _U1PWRC_USUSPEND_MASK | _U1PWRC_USBPWR_MASK; +#else + U1PWRC &= ~(_U1PWRC_USUSPEND_MASK | _U1PWRC_USBPWR_MASK); +#endif + return true; +} + void dcd_int_enable(uint8_t rhport) { intr_enable(rhport); @@ -529,8 +555,25 @@ void dcd_remote_wakeup(uint8_t rhport) #else U1CONbits.RESUME = 1; #endif - unsigned cnt = 25000000 / 1000; + + // FIXME: Assert RESUME signal correctly, requires device-specific handling + // For now we use a hardcoded cycle-based delay which attempts to delay 10ms + // at the most common CPU frequencies. On PIC32s we assume the loop body + // takes 3 cycles. On 16-bit PICs we assume the XC16 compiler is in use and + // use its `__delay_ms' function. + +#if CFG_TUSB_MCU == OPT_MCU_PIC32MM + uint32_t cnt = 24000000 / 1000 / 3; while (cnt--) asm volatile("nop"); +#elif CFG_TUSB_MCU == OPT_MCU_PIC32MX + uint32_t cnt = 40000000 / 1000 / 3; + while (cnt--) asm volatile("nop"); +#elif CFG_TUSB_MCU == OPT_MCU_PIC32MK + uint32_t cnt = 120000000 / 1000 / 3; + while (cnt--) asm volatile("nop"); +#else + __delay_ms(10); +#endif #if TU_PIC_INT_SIZE == 4 U1CONCLR = _U1CON_RESUME_MASK; @@ -738,8 +781,11 @@ void dcd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr) //--------------------------------------------------------------------+ void dcd_int_handler(uint8_t rhport) { - uint32_t is = U1IR; - uint32_t msk = U1IE; + uint32_t is, msk; + + // Part 1 - "USB interrupts" + is = U1IR; + msk = U1IE; U1IR = is & ~msk; is &= msk; @@ -747,7 +793,7 @@ void dcd_int_handler(uint8_t rhport) if (is & _U1IR_UERRIF_MASK) { uint32_t es = U1EIR; U1EIR = es; - U1IR = is; /* discard any pending events */ + U1IR = is; /* discard any pending events */ } if (is & _U1IR_URSTIF_MASK) { @@ -758,29 +804,66 @@ void dcd_int_handler(uint8_t rhport) if (is & _U1IR_IDLEIF_MASK) { // Note Host usually has extra delay after bus reset (without SOF), which could falsely // detected as Sleep event. Though usbd has debouncing logic so we are good + + /* + * NOTE: Do not clear U1OTGIRbits.ACTVIF here! + * Reason: + * ACTVIF is only generated once an IDLEIF has been generated. + * This is a 1:1 ratio interrupt generation. + * For every IDLEIF, there will be only one ACTVIF regardless of + * the number of subsequent bus transitions. + * + * If the ACTIF is cleared here, a problem could occur when: + * [ IDLE ][bus activity -> + * <--- 3 ms -----> ^ + * ^ ACTVIF=1 + * IDLEIF=1 + * # # # # (#=Program polling flags) + * ^ + * This polling loop will see both + * IDLEIF=1 and ACTVIF=1. + * However, the program services IDLEIF first + * because ACTIVIE=0. + * If this routine clears the only ACTIVIF, + * then it can never get out of the suspend + * mode. + */ + U1OTGIESET = _U1OTGIE_ACTVIE_MASK; U1IR = _U1IR_IDLEIF_MASK; process_bus_sleep(rhport); } - if (is & _U1IR_RESUMEIF_MASK) { - U1IR = _U1IR_RESUMEIF_MASK; - process_bus_resume(rhport); - } - if (is & _U1IR_SOFIF_MASK) { U1IR = _U1IR_SOFIF_MASK; dcd_event_bus_signal(rhport, DCD_EVENT_SOF, true); } if (is & _U1IR_STALLIF_MASK) { - U1IR = _U1IR_STALLIF_MASK; process_stall(rhport); + U1IR = _U1IR_STALLIF_MASK; } if (is & _U1IR_TRNIF_MASK) { process_tokdne(rhport); } + // Part 2 - "USB OTG interrupts" + is = U1OTGIR; + msk = U1OTGIE; + + U1OTGIR = is & ~msk; + is &= msk; + + if (is & _U1OTGIR_ACTVIF_MASK) { +#if TU_PIC_INT_SIZE == 4 + U1OTGIECLR = _U1OTGIE_ACTVIE_MASK; +#else + U1OTGIE &= ~_U1OTGIE_ACTVIE_MASK; +#endif + U1OTGIR = _U1OTGIR_ACTVIF_MASK; + process_bus_resume(rhport); + } + intr_clear(rhport); } diff --git a/src/portable/nordic/nrf5x/dcd_nrf5x.c b/src/portable/nordic/nrf5x/dcd_nrf5x.c index 5bfedae17..9e5f5117f 100644 --- a/src/portable/nordic/nrf5x/dcd_nrf5x.c +++ b/src/portable/nordic/nrf5x/dcd_nrf5x.c @@ -39,8 +39,8 @@ #endif #include "nrf.h" -#include "nrf_clock.h" -#include "nrfx_usbd_errata.h" +#include "nrfx_clock.h" +#include "nrf_erratas.h" #ifdef __GNUC__ #pragma GCC diagnostic pop @@ -926,7 +926,7 @@ void tusb_hal_nrf_power_event(uint32_t event) { #ifdef NRF52_SERIES // NRF53 does not need this errata // ERRATA 171, 187, 166 - if (nrfx_usbd_errata_187()) { + if (nrf52_errata_187()) { // CRITICAL_REGION_ENTER(); if (*((volatile uint32_t*) (0x4006EC00)) == 0x00000000) { *((volatile uint32_t*) (0x4006EC00)) = 0x00009375; @@ -938,7 +938,7 @@ void tusb_hal_nrf_power_event(uint32_t event) { // CRITICAL_REGION_EXIT(); } - if (nrfx_usbd_errata_171()) { + if (nrf52_errata_171()) { // CRITICAL_REGION_ENTER(); if (*((volatile uint32_t*) (0x4006EC00)) == 0x00000000) { *((volatile uint32_t*) (0x4006EC00)) = 0x00009375; @@ -974,7 +974,7 @@ void tusb_hal_nrf_power_event(uint32_t event) { __DSB(); // for sync #ifdef NRF52_SERIES - if (nrfx_usbd_errata_171()) { + if (nrf52_errata_171()) { // CRITICAL_REGION_ENTER(); if (*((volatile uint32_t*) (0x4006EC00)) == 0x00000000) { *((volatile uint32_t*) (0x4006EC00)) = 0x00009375; @@ -987,7 +987,7 @@ void tusb_hal_nrf_power_event(uint32_t event) { // CRITICAL_REGION_EXIT(); } - if (nrfx_usbd_errata_187()) { + if (nrf52_errata_187()) { // CRITICAL_REGION_ENTER(); if (*((volatile uint32_t*) (0x4006EC00)) == 0x00000000) { *((volatile uint32_t*) (0x4006EC00)) = 0x00009375; @@ -999,7 +999,7 @@ void tusb_hal_nrf_power_event(uint32_t event) { // CRITICAL_REGION_EXIT(); } - if (nrfx_usbd_errata_166()) { + if (nrf52_errata_166()) { *((volatile uint32_t*) (NRF_USBD_BASE + 0x800)) = 0x7E3; *((volatile uint32_t*) (NRF_USBD_BASE + 0x804)) = 0x40; diff --git a/src/portable/nxp/khci/dcd_khci.c b/src/portable/nxp/khci/dcd_khci.c index 8398b09bf..3d5e195a9 100644 --- a/src/portable/nxp/khci/dcd_khci.c +++ b/src/portable/nxp/khci/dcd_khci.c @@ -565,7 +565,7 @@ void dcd_int_handler(uint8_t rhport) if (is & USB_ISTAT_SOFTOK_MASK) { KHCI->ISTAT = USB_ISTAT_SOFTOK_MASK; - dcd_event_bus_signal(rhport, DCD_EVENT_SOF, true); + dcd_event_sof(rhport, tu_u16(KHCI->FRMNUMH, KHCI->FRMNUML), true); } if (is & USB_ISTAT_STALL_MASK) { diff --git a/src/portable/nxp/khci/hcd_khci.c b/src/portable/nxp/khci/hcd_khci.c index 056dbf40b..45732a866 100644 --- a/src/portable/nxp/khci/hcd_khci.c +++ b/src/portable/nxp/khci/hcd_khci.c @@ -36,6 +36,7 @@ #endif #include "host/hcd.h" +#include "host/usbh.h" //--------------------------------------------------------------------+ // MACRO TYPEDEF CONSTANT ENUM DECLARATION @@ -541,6 +542,11 @@ bool hcd_edpt_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_endpoint_t const return true; } +bool hcd_edpt_close(uint8_t rhport, uint8_t daddr, uint8_t ep_addr) { + (void) rhport; (void) daddr; (void) ep_addr; + return false; // TODO not implemented yet +} + /* The address of buffer must be aligned to 4 byte boundary. And it must be at least 4 bytes long. * DMA writes data in 4 byte unit */ bool hcd_edpt_xfer(uint8_t rhport, uint8_t dev_addr, uint8_t ep_addr, uint8_t * buffer, uint16_t buflen) diff --git a/src/portable/nxp/lpc17_40/hcd_lpc17_40.c b/src/portable/nxp/lpc17_40/hcd_lpc17_40.c index 090d1ba69..fea3e2a66 100644 --- a/src/portable/nxp/lpc17_40/hcd_lpc17_40.c +++ b/src/portable/nxp/lpc17_40/hcd_lpc17_40.c @@ -31,6 +31,7 @@ #include "chip.h" #include "host/hcd.h" +#include "host/usbh.h" void hcd_int_enable(uint8_t rhport) { diff --git a/src/portable/nxp/lpc_ip3511/dcd_lpc_ip3511.c b/src/portable/nxp/lpc_ip3511/dcd_lpc_ip3511.c index 7d5cfb5b0..7c637ce0c 100644 --- a/src/portable/nxp/lpc_ip3511/dcd_lpc_ip3511.c +++ b/src/portable/nxp/lpc_ip3511/dcd_lpc_ip3511.c @@ -297,7 +297,7 @@ bool dcd_init(uint8_t rhport, const tusb_rhport_init_t* rh_init) { dcd_reg->EPLISTSTART = (uint32_t) _dcd.ep; dcd_reg->DATABUFSTART = tu_align((uint32_t) &_dcd, TU_BIT(22)); // 22-bit alignment - dcd_reg->INTSTAT |= dcd_reg->INTSTAT; // clear all pending interrupt + dcd_reg->INTSTAT = dcd_reg->INTSTAT; // clear all pending interrupt dcd_reg->INTEN = INT_DEVICE_STATUS_MASK; dcd_reg->DEVCMDSTAT |= DEVCMDSTAT_DEVICE_ENABLE_MASK | DEVCMDSTAT_DEVICE_CONNECT_MASK | DEVCMDSTAT_RESET_CHANGE_MASK | DEVCMDSTAT_CONNECT_CHANGE_MASK | DEVCMDSTAT_SUSPEND_CHANGE_MASK; @@ -563,7 +563,8 @@ void dcd_int_handler(uint8_t rhport) uint32_t const cmd_stat = dcd_reg->DEVCMDSTAT; - uint32_t int_status = dcd_reg->INTSTAT & dcd_reg->INTEN; + uint32_t int_status = dcd_reg->INTSTAT; + int_status &= dcd_reg->INTEN; dcd_reg->INTSTAT = int_status; // Acknowledge handled interrupt if (int_status == 0) return; diff --git a/src/portable/ohci/ohci.c b/src/portable/ohci/ohci.c index ce35eab70..81091c9a7 100644 --- a/src/portable/ohci/ohci.c +++ b/src/portable/ohci/ohci.c @@ -38,6 +38,7 @@ #include "osal/osal.h" #include "host/hcd.h" +#include "host/usbh.h" #include "ohci.h" // TODO remove @@ -328,13 +329,13 @@ static void ed_init(ohci_ed_t *p_ed, uint8_t dev_addr, uint16_t ep_size, uint8_t tu_memclr(p_ed, sizeof(ohci_ed_t)); } - hcd_devtree_info_t devtree_info; - hcd_devtree_get_info(dev_addr, &devtree_info); + tuh_bus_info_t bus_info; + tuh_bus_info_get(dev_addr, &bus_info); p_ed->dev_addr = dev_addr; p_ed->ep_number = ep_addr & 0x0F; p_ed->pid = (xfer_type == TUSB_XFER_CONTROL) ? PID_FROM_TD : (tu_edpt_dir(ep_addr) ? PID_IN : PID_OUT); - p_ed->speed = devtree_info.speed; + p_ed->speed = bus_info.speed; p_ed->is_iso = (xfer_type == TUSB_XFER_ISOCHRONOUS) ? 1 : 0; p_ed->max_packet_size = ep_size; @@ -451,7 +452,6 @@ static void td_insert_to_ed(ohci_ed_t* p_ed, ohci_gtd_t * p_gtd) //--------------------------------------------------------------------+ // Endpoint API //--------------------------------------------------------------------+ - bool hcd_edpt_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_endpoint_t const * ep_desc) { (void) rhport; @@ -486,6 +486,11 @@ bool hcd_edpt_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_endpoint_t const return true; } +bool hcd_edpt_close(uint8_t rhport, uint8_t daddr, uint8_t ep_addr) { + (void) rhport; (void) daddr; (void) ep_addr; + return false; // TODO not implemented yet +} + bool hcd_setup_send(uint8_t rhport, uint8_t dev_addr, uint8_t const setup_packet[8]) { (void) rhport; diff --git a/src/portable/raspberrypi/pio_usb/hcd_pio_usb.c b/src/portable/raspberrypi/pio_usb/hcd_pio_usb.c index 6422afff1..d59a2b4ee 100644 --- a/src/portable/raspberrypi/pio_usb/hcd_pio_usb.c +++ b/src/portable/raspberrypi/pio_usb/hcd_pio_usb.c @@ -114,14 +114,19 @@ void hcd_int_disable(uint8_t rhport) { //--------------------------------------------------------------------+ bool hcd_edpt_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_endpoint_t const *desc_ep) { - hcd_devtree_info_t dev_tree; - hcd_devtree_get_info(dev_addr, &dev_tree); - bool const need_pre = (dev_tree.hub_addr && dev_tree.speed == TUSB_SPEED_LOW); + tuh_bus_info_t bus_info; + tuh_bus_info_get(dev_addr, &bus_info); + bool const need_pre = (bus_info.hub_addr && bus_info.speed == TUSB_SPEED_LOW); uint8_t const pio_rhport = RHPORT_PIO(rhport); return pio_usb_host_endpoint_open(pio_rhport, dev_addr, (uint8_t const *) desc_ep, need_pre); } +bool hcd_edpt_close(uint8_t rhport, uint8_t daddr, uint8_t ep_addr) { + uint8_t const pio_rhport = RHPORT_PIO(rhport); + return pio_usb_host_endpoint_close(pio_rhport, daddr, ep_addr); +} + bool hcd_edpt_xfer(uint8_t rhport, uint8_t dev_addr, uint8_t ep_addr, uint8_t *buffer, uint16_t buflen) { uint8_t const pio_rhport = RHPORT_PIO(rhport); return pio_usb_host_endpoint_transfer(pio_rhport, dev_addr, ep_addr, buffer, buflen); diff --git a/src/portable/raspberrypi/rp2040/dcd_rp2040.c b/src/portable/raspberrypi/rp2040/dcd_rp2040.c index af08b549d..358ce84bc 100644 --- a/src/portable/raspberrypi/rp2040/dcd_rp2040.c +++ b/src/portable/raspberrypi/rp2040/dcd_rp2040.c @@ -148,6 +148,32 @@ static void hw_endpoint_xfer(uint8_t ep_addr, uint8_t* buffer, uint16_t total_by hw_endpoint_xfer_start(ep, buffer, total_bytes); } +static void hw_endpoint_abort_xfer(struct hw_endpoint* ep) { + // Abort any pending transfer + // Due to Errata RP2040-E2: ABORT flag is only applicable for B2 and later (unusable for B0, B1). + // Which means we are not guaranteed to safely abort pending transfer on B0 and B1. + const uint8_t dir = tu_edpt_dir(ep->ep_addr); + const uint8_t epnum = tu_edpt_number(ep->ep_addr); + const uint32_t abort_mask = TU_BIT((epnum << 1) | (dir ? 0 : 1)); + if (rp2040_chip_version() >= 2) { + usb_hw_set->abort = abort_mask; + while ((usb_hw->abort_done & abort_mask) != abort_mask) {} + } + + uint32_t buf_ctrl = USB_BUF_CTRL_SEL; // reset to buffer 0 + if (ep->next_pid) { + buf_ctrl |= USB_BUF_CTRL_DATA1_PID; + } + + _hw_endpoint_buffer_control_set_value32(ep, buf_ctrl); + hw_endpoint_reset_transfer(ep); + + if (rp2040_chip_version() >= 2) { + usb_hw_clear->abort_done = abort_mask; + usb_hw_clear->abort = abort_mask; + } +} + static void __tusb_irq_path_func(hw_handle_buff_status)(void) { uint32_t remaining_buffers = usb_hw->buf_status; pico_trace("buf_status = 0x%08lx\r\n", remaining_buffers); @@ -178,25 +204,10 @@ TU_ATTR_ALWAYS_INLINE static inline void reset_ep0(void) { // setup transfer. Also clear a stall in case for (uint8_t dir = 0; dir < 2; dir++) { struct hw_endpoint* ep = hw_endpoint_get_by_num(0, dir); - if (ep->active) { - // Abort any pending transfer from a prior control transfer per USB specs - // Due to Errata RP2040-E2: ABORT flag is only applicable for B2 and later (unusable for B0, B1). - // Which means we are not guaranteed to safely abort pending transfer on B0 and B1. - uint32_t const abort_mask = (dir ? USB_EP_ABORT_EP0_IN_BITS : USB_EP_ABORT_EP0_OUT_BITS); - if (rp2040_chip_version() >= 2) { - usb_hw_set->abort = abort_mask; - while ((usb_hw->abort_done & abort_mask) != abort_mask) {} - } - - _hw_endpoint_buffer_control_set_value32(ep, USB_BUF_CTRL_DATA1_PID | USB_BUF_CTRL_SEL); - hw_endpoint_reset_transfer(ep); - - if (rp2040_chip_version() >= 2) { - usb_hw_clear->abort_done = abort_mask; - usb_hw_clear->abort = abort_mask; - } - } ep->next_pid = 1u; + if (ep->active) { + hw_endpoint_abort_xfer(ep); // Abort any pending transfer per USB specs + } } } @@ -495,12 +506,14 @@ bool dcd_edpt_iso_alloc(uint8_t rhport, uint8_t ep_addr, uint16_t largest_packet // New API: Configure and enable an ISO endpoint according to descriptor bool dcd_edpt_iso_activate(uint8_t rhport, tusb_desc_endpoint_t const * ep_desc) { (void) rhport; - const uint8_t ep_addr = ep_desc->bEndpointAddress; - // Fill in endpoint control register with buffer offset - struct hw_endpoint* ep = hw_endpoint_get_by_addr(ep_addr); - TU_ASSERT(ep->hw_data_buf != NULL); // must be inited and buffer allocated - ep->wMaxPacketSize = ep_desc->wMaxPacketSize; + struct hw_endpoint* ep = hw_endpoint_get_by_addr(ep_desc->bEndpointAddress); + TU_ASSERT(ep->hw_data_buf != NULL); // must be inited and allocated previously + if (ep->active) { + hw_endpoint_abort_xfer(ep); // abort any pending transfer + } + + ep->wMaxPacketSize = ep_desc->wMaxPacketSize; hw_endpoint_enable(ep); return true; } diff --git a/src/portable/raspberrypi/rp2040/hcd_rp2040.c b/src/portable/raspberrypi/rp2040/hcd_rp2040.c index 2c0a3fd49..cd8c905d5 100644 --- a/src/portable/raspberrypi/rp2040/hcd_rp2040.c +++ b/src/portable/raspberrypi/rp2040/hcd_rp2040.c @@ -459,28 +459,33 @@ tusb_speed_t hcd_port_speed_get(uint8_t rhport) } // Close all opened endpoint belong to this device -void hcd_device_close(uint8_t rhport, uint8_t dev_addr) -{ +void hcd_device_close(uint8_t rhport, uint8_t dev_addr) { pico_trace("hcd_device_close %d\n", dev_addr); (void) rhport; - if (dev_addr == 0) return; + // reset epx if it is currently active with unplugged device + if (epx.configured && epx.active && epx.dev_addr == dev_addr) { + epx.configured = false; + *epx.endpoint_control = 0; + *epx.buffer_control = 0; + hw_endpoint_reset_transfer(&epx); + } - for (size_t i = 1; i < TU_ARRAY_SIZE(ep_pool); i++) - { - hw_endpoint_t* ep = &ep_pool[i]; + // dev0 only has ep0 + if (dev_addr != 0) { + for (size_t i = 1; i < TU_ARRAY_SIZE(ep_pool); i++) { + hw_endpoint_t *ep = &ep_pool[i]; + if (ep->dev_addr == dev_addr && ep->configured) { + // in case it is an interrupt endpoint, disable it + usb_hw_clear->int_ep_ctrl = (1 << (ep->interrupt_num + 1)); + usb_hw->int_ep_addr_ctrl[ep->interrupt_num] = 0; - if (ep->dev_addr == dev_addr && ep->configured) - { - // in case it is an interrupt endpoint, disable it - usb_hw_clear->int_ep_ctrl = (1 << (ep->interrupt_num + 1)); - usb_hw->int_ep_addr_ctrl[ep->interrupt_num] = 0; - - // unconfigure the endpoint - ep->configured = false; - *ep->endpoint_control = 0; - *ep->buffer_control = 0; - hw_endpoint_reset_transfer(ep); + // unconfigure the endpoint + ep->configured = false; + *ep->endpoint_control = 0; + *ep->buffer_control = 0; + hw_endpoint_reset_transfer(ep); + } } } } @@ -509,7 +514,6 @@ void hcd_int_disable(uint8_t rhport) //--------------------------------------------------------------------+ // Endpoint API //--------------------------------------------------------------------+ - bool hcd_edpt_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_endpoint_t const * ep_desc) { (void) rhport; @@ -530,6 +534,11 @@ bool hcd_edpt_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_endpoint_t const return true; } +bool hcd_edpt_close(uint8_t rhport, uint8_t daddr, uint8_t ep_addr) { + (void) rhport; (void) daddr; (void) ep_addr; + return false; // TODO not implemented yet +} + bool hcd_edpt_xfer(uint8_t rhport, uint8_t dev_addr, uint8_t ep_addr, uint8_t * buffer, uint16_t buflen) { (void) rhport; @@ -557,7 +566,7 @@ bool hcd_edpt_xfer(uint8_t rhport, uint8_t dev_addr, uint8_t ep_addr, uint8_t * } // If a normal transfer (non-interrupt) then initiate using - // sie ctrl registers. Otherwise interrupt ep registers should + // sie ctrl registers. Otherwise, interrupt ep registers should // already be configured if ( ep == &epx ) { @@ -597,13 +606,12 @@ bool hcd_setup_send(uint8_t rhport, uint8_t dev_addr, uint8_t const setup_packet (void) rhport; // Copy data into setup packet buffer - for ( uint8_t i = 0; i < 8; i++ ) - { + for (uint8_t i = 0; i < 8; i++) { usbh_dpram->setup_packet[i] = setup_packet[i]; } // Configure EP0 struct with setup info for the trans complete - struct hw_endpoint * ep = _hw_endpoint_allocate(0); + struct hw_endpoint * ep = _hw_endpoint_allocate( (uint8_t) TUSB_XFER_CONTROL); TU_ASSERT(ep); // EPX should be inactive diff --git a/src/portable/raspberrypi/rp2040/rp2040_usb.c b/src/portable/raspberrypi/rp2040/rp2040_usb.c index 43f48da39..9d0bd762d 100644 --- a/src/portable/raspberrypi/rp2040/rp2040_usb.c +++ b/src/portable/raspberrypi/rp2040/rp2040_usb.c @@ -110,7 +110,7 @@ void __tusb_irq_path_func(_hw_endpoint_buffer_control_update32)(struct hw_endpoi *ep->buffer_control = value & ~USB_BUF_CTRL_AVAIL; // 4.1.2.5.1 Con-current access: 12 cycles (should be good for 48*12Mhz = 576Mhz) after write to buffer control // Don't need delay in host mode as host is in charge - if ( !is_host_mode()) { + if (!is_host_mode()) { busy_wait_at_least_cycles(12); } } diff --git a/src/portable/renesas/rusb2/hcd_rusb2.c b/src/portable/renesas/rusb2/hcd_rusb2.c index 4c81b05be..6f6d27d0e 100644 --- a/src/portable/renesas/rusb2/hcd_rusb2.c +++ b/src/portable/renesas/rusb2/hcd_rusb2.c @@ -30,6 +30,7 @@ #if CFG_TUH_ENABLED && defined(TUP_USBIP_RUSB2) #include "host/hcd.h" +#include "host/usbh.h" #include "rusb2_type.h" #if TU_CHECK_MCU(OPT_MCU_RX63X, OPT_MCU_RX65X, OPT_MCU_RX72N) @@ -662,13 +663,13 @@ bool hcd_edpt_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_endpoint_t const if (0 == epn) { rusb->DCPCTR = RUSB2_PIPE_CTR_PID_NAK; - hcd_devtree_info_t devtree; - hcd_devtree_get_info(dev_addr, &devtree); + tuh_bus_info_t bus_info; + tuh_bus_info_get(dev_addr, &bus_info); uint16_t volatile *devadd = (uint16_t volatile *)(uintptr_t) &rusb->DEVADD[0]; devadd += dev_addr; while (rusb->DCPCTR_b.PBUSY) {} rusb->DCPMAXP = (dev_addr << 12) | mps; - *devadd = (TUSB_SPEED_FULL == devtree.speed) ? RUSB2_DEVADD_USBSPD_FS : RUSB2_DEVADD_USBSPD_LS; + *devadd = (TUSB_SPEED_FULL == bus_info.speed) ? RUSB2_DEVADD_USBSPD_FS : RUSB2_DEVADD_USBSPD_LS; _hcd.ctl_mps[dev_addr] = mps; return true; } @@ -718,6 +719,11 @@ bool hcd_edpt_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_endpoint_t const return true; } +bool hcd_edpt_close(uint8_t rhport, uint8_t daddr, uint8_t ep_addr) { + (void) rhport; (void) daddr; (void) ep_addr; + return false; // TODO not implemented yet +} + bool hcd_edpt_xfer(uint8_t rhport, uint8_t dev_addr, uint8_t ep_addr, uint8_t *buffer, uint16_t buflen) { bool r; diff --git a/src/portable/synopsys/dwc2/dcd_dwc2.c b/src/portable/synopsys/dwc2/dcd_dwc2.c index bde48ef57..5f86d6b76 100644 --- a/src/portable/synopsys/dwc2/dcd_dwc2.c +++ b/src/portable/synopsys/dwc2/dcd_dwc2.c @@ -39,14 +39,9 @@ #define DWC2_DEBUG 2 #include "device/dcd.h" +#include "device/usbd_pvt.h" #include "dwc2_common.h" -#if TU_CHECK_MCU(OPT_MCU_GD32VF103) - #define DWC2_EP_COUNT(_dwc2) DWC2_EP_MAX -#else - #define DWC2_EP_COUNT(_dwc2) ((_dwc2)->ghwcfg2_bm.num_dev_ep) -#endif - //--------------------------------------------------------------------+ // MACRO TYPEDEF CONSTANT ENUM //--------------------------------------------------------------------+ @@ -58,6 +53,7 @@ typedef struct { uint8_t interval; } xfer_ctl_t; +// This variable is modified from ISR context, so it must be protected by critical section static xfer_ctl_t xfer_status[DWC2_EP_MAX][2]; #define XFER_CTL_BASE(_ep, _dir) (&xfer_status[_ep][_dir]) @@ -79,6 +75,16 @@ CFG_TUD_MEM_SECTION static struct { TUD_EPBUF_DEF(setup_packet, 8); } _dcd_usbbuf; +TU_ATTR_ALWAYS_INLINE static inline uint8_t dwc2_ep_count(const dwc2_regs_t* dwc2) { + #if TU_CHECK_MCU(OPT_MCU_GD32VF103) + return DWC2_EP_MAX; + #else + const dwc2_ghwcfg2_t ghwcfg2 = {.value = dwc2->ghwcfg2}; + return ghwcfg2.num_dev_ep + 1; + #endif +} + + //-------------------------------------------------------------------- // DMA //-------------------------------------------------------------------- @@ -102,7 +108,8 @@ bool dcd_dcache_clean_invalidate(const void* addr, uint32_t data_size) { TU_ATTR_ALWAYS_INLINE static inline bool dma_device_enabled(const dwc2_regs_t* dwc2) { (void) dwc2; // Internal DMA only - return CFG_TUD_DWC2_DMA_ENABLE && dwc2->ghwcfg2_bm.arch == GHWCFG2_ARCH_INTERNAL_DMA; + const dwc2_ghwcfg2_t ghwcfg2 = {.value = dwc2->ghwcfg2}; + return CFG_TUD_DWC2_DMA_ENABLE && ghwcfg2.arch == GHWCFG2_ARCH_INTERNAL_DMA; } static void dma_setup_prepare(uint8_t rhport) { @@ -250,20 +257,15 @@ static void edpt_activate(uint8_t rhport, const tusb_desc_endpoint_t* p_endpoint xfer->interval = p_endpoint_desc->bInterval; // Endpoint control - union { - uint32_t value; - dwc2_depctl_t bm; - } depctl; - depctl.value = 0; - - depctl.bm.mps = xfer->max_size; - depctl.bm.active = 1; - depctl.bm.type = p_endpoint_desc->bmAttributes.xfer; + dwc2_depctl_t depctl = {.value = 0}; + depctl.mps = xfer->max_size; + depctl.active = 1; + depctl.type = p_endpoint_desc->bmAttributes.xfer; if (p_endpoint_desc->bmAttributes.xfer != TUSB_XFER_ISOCHRONOUS) { - depctl.bm.set_data0_iso_even = 1; + depctl.set_data0_iso_even = 1; } if (dir == TUSB_DIR_IN) { - depctl.bm.tx_fifo_num = epnum; + depctl.tx_fifo_num = epnum; } dwc2_dep_t* dep = &dwc2->ep[dir == TUSB_DIR_IN ? 0 : 1][epnum]; @@ -321,6 +323,9 @@ static void edpt_disable(uint8_t rhport, uint8_t ep_addr, bool stall) { } } +// Since this function returns void, it is not possible to return a boolean success message +// We must make sure that this function is not called when the EP is disabled +// Must be called from critical section static void edpt_schedule_packets(uint8_t rhport, const uint8_t epnum, const uint8_t dir) { dwc2_regs_t* dwc2 = DWC2_REG(rhport); xfer_ctl_t* const xfer = XFER_CTL_BASE(epnum, dir); @@ -343,31 +348,22 @@ static void edpt_schedule_packets(uint8_t rhport, const uint8_t epnum, const uin } // transfer size: A full OUT transfer (multiple packets, possibly) triggers XFRC. - union { - uint32_t value; - dwc2_ep_tsize_t bm; - } deptsiz; - deptsiz.value = 0; - deptsiz.bm.xfer_size = total_bytes; - deptsiz.bm.packet_count = num_packets; - + dwc2_ep_tsize_t deptsiz = {.value = 0}; + deptsiz.xfer_size = total_bytes; + deptsiz.packet_count = num_packets; dep->tsiz = deptsiz.value; // control - union { - dwc2_depctl_t bm; - uint32_t value; - } depctl; - depctl.value = dep->ctl; - - depctl.bm.clear_nak = 1; - depctl.bm.enable = 1; - if (depctl.bm.type == DEPCTL_EPTYPE_ISOCHRONOUS && xfer->interval == 1) { - const uint32_t odd_now = (dwc2->dsts_bm.frame_number & 1u); + dwc2_depctl_t depctl = {.value = dep->ctl}; + depctl.clear_nak = 1; + depctl.enable = 1; + if (depctl.type == DEPCTL_EPTYPE_ISOCHRONOUS && xfer->interval == 1) { + const dwc2_dsts_t dsts = {.value = dwc2->dsts}; + const uint32_t odd_now = dsts.frame_number & 1u; if (odd_now) { - depctl.bm.set_data0_iso_even = 1; + depctl.set_data0_iso_even = 1; } else { - depctl.bm.set_data1_iso_odd = 1; + depctl.set_data1_iso_odd = 1; } } @@ -410,7 +406,8 @@ bool dcd_init(uint8_t rhport, const tusb_rhport_init_t* rh_init) { // XCVRDLY: transceiver delay between xcvr_sel and txvalid during device chirp is required // when using with some PHYs such as USB334x (USB3341, USB3343, USB3346, USB3347) - if (dwc2->ghwcfg2_bm.hs_phy_type == GHWCFG2_HSPHY_ULPI) { + const dwc2_ghwcfg2_t ghwcfg2 = {.value = dwc2->ghwcfg2}; + if (ghwcfg2.hs_phy_type == GHWCFG2_HSPHY_ULPI) { dcfg |= DCFG_XCVRDLY; } } else { @@ -428,6 +425,11 @@ bool dcd_init(uint8_t rhport, const tusb_rhport_init_t* rh_init) { // Clear A override, force B Valid dwc2->gotgctl = (dwc2->gotgctl & ~GOTGCTL_AVALOEN) | GOTGCTL_BVALOEN | GOTGCTL_BVALOVAL; +#if CFG_TUSB_MCU == OPT_MCU_STM32N6 + // No hardware detection of Vbus B-session is available on the STM32N6 + dwc2->stm32_gccfg |= STM32_GCCFG_VBVALOVAL; +#endif + // Enable required interrupts dwc2->gintmsk |= GINTMSK_OTGINT | GINTMSK_USBSUSPM | GINTMSK_USBRST | GINTMSK_ENUMDNEM | GINTMSK_WUIM; @@ -539,6 +541,8 @@ void dcd_edpt_close_all(uint8_t rhport) { dwc2_regs_t* dwc2 = DWC2_REG(rhport); uint8_t const ep_count = _dwc2_controller[rhport].ep_count; + usbd_spin_lock(false); + _dcd_data.allocated_epin_count = 0; // Disable non-control interrupt @@ -556,8 +560,9 @@ void dcd_edpt_close_all(uint8_t rhport) { dfifo_flush_tx(dwc2, 0x10); // all tx fifo dfifo_flush_rx(dwc2); - dfifo_device_init(rhport); // re-init dfifo + + usbd_spin_unlock(false); } bool dcd_edpt_iso_alloc(uint8_t rhport, uint8_t ep_addr, uint16_t largest_packet_size) { @@ -575,21 +580,31 @@ bool dcd_edpt_iso_activate(uint8_t rhport, tusb_desc_endpoint_t const * p_endpo bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t* buffer, uint16_t total_bytes) { uint8_t const epnum = tu_edpt_number(ep_addr); uint8_t const dir = tu_edpt_dir(ep_addr); - xfer_ctl_t* xfer = XFER_CTL_BASE(epnum, dir); - xfer->buffer = buffer; - xfer->ff = NULL; - xfer->total_len = total_bytes; + bool ret; - // EP0 can only handle one packet - if (epnum == 0) { - _dcd_data.ep0_pending[dir] = total_bytes; + usbd_spin_lock(false); + + if (xfer->max_size == 0) { + ret = false; // Endpoint is closed + } else { + xfer->buffer = buffer; + xfer->ff = NULL; + xfer->total_len = total_bytes; + + // EP0 can only handle one packet + if (epnum == 0) { + _dcd_data.ep0_pending[dir] = total_bytes; + } + + // Schedule packets to be sent within interrupt + edpt_schedule_packets(rhport, epnum, dir); + ret = true; } - // Schedule packets to be sent within interrupt - edpt_schedule_packets(rhport, epnum, dir); + usbd_spin_unlock(false); - return true; + return ret; } // The number of bytes has to be given explicitly to allow more flexible control of how many @@ -602,17 +617,27 @@ bool dcd_edpt_xfer_fifo(uint8_t rhport, uint8_t ep_addr, tu_fifo_t* ff, uint16_t uint8_t const epnum = tu_edpt_number(ep_addr); uint8_t const dir = tu_edpt_dir(ep_addr); - xfer_ctl_t* xfer = XFER_CTL_BASE(epnum, dir); - xfer->buffer = NULL; - xfer->ff = ff; - xfer->total_len = total_bytes; + bool ret; - // Schedule packets to be sent within interrupt - // TODO xfer fifo may only available for slave mode - edpt_schedule_packets(rhport, epnum, dir); + usbd_spin_lock(false); - return true; + if (xfer->max_size == 0) { + ret = false; // Endpoint is closed + } else { + xfer->buffer = NULL; + xfer->ff = ff; + xfer->total_len = total_bytes; + + // Schedule packets to be sent within interrupt + // TODO xfer fifo may only available for slave mode + edpt_schedule_packets(rhport, epnum, dir); + ret = true; + } + + usbd_spin_unlock(false); + + return ret; } void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr) { @@ -639,9 +664,10 @@ void dcd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr) { //-------------------------------------------------------------------- // 7.4.1 Initialization on USB Reset +// Must be called from critical section static void handle_bus_reset(uint8_t rhport) { dwc2_regs_t *dwc2 = DWC2_REG(rhport); - const uint8_t ep_count = DWC2_EP_COUNT(dwc2); + const uint8_t ep_count = dwc2_ep_count(dwc2); tu_memclr(xfer_status, sizeof(xfer_status)); @@ -671,7 +697,9 @@ static void handle_bus_reset(uint8_t rhport) { dfifo_device_init(rhport); // 5. Reset device address - dwc2->dcfg_bm.address = 0; + dwc2_dcfg_t dcfg = {.value = dwc2->dcfg}; + dcfg.address = 0; + dwc2->dcfg = dcfg.value; // Fixed both control EP0 size to 64 bytes dwc2->epin[0].ctl &= ~(0x03 << DIEPCTL_MPSIZ_Pos); @@ -691,8 +719,9 @@ static void handle_bus_reset(uint8_t rhport) { static void handle_enum_done(uint8_t rhport) { dwc2_regs_t *dwc2 = DWC2_REG(rhport); + const dwc2_dsts_t dsts = {.value = dwc2->dsts}; tusb_speed_t speed; - switch (dwc2->dsts_bm.enum_speed) { + switch (dsts.enum_speed) { case DCFG_SPEED_HIGH: speed = TUSB_SPEED_HIGH; break; @@ -737,12 +766,12 @@ static void handle_rxflvl_irq(uint8_t rhport) { const volatile uint32_t* rx_fifo = dwc2->fifo[0]; // Pop control word off FIFO - const dwc2_grxstsp_t grxstsp_bm = dwc2->grxstsp_bm; - const uint8_t epnum = grxstsp_bm.ep_ch_num; + const dwc2_grxstsp_t grxstsp = {.value = dwc2->grxstsp}; + const uint8_t epnum = grxstsp.ep_ch_num; dwc2_dep_t* epout = &dwc2->epout[epnum]; - switch (grxstsp_bm.packet_status) { + switch (grxstsp.packet_status) { case GRXSTS_PKTSTS_GLOBAL_OUT_NAK: // Global OUT NAK: do nothing break; @@ -764,7 +793,7 @@ static void handle_rxflvl_irq(uint8_t rhport) { case GRXSTS_PKTSTS_RX_DATA: { // Out packet received - const uint16_t byte_count = grxstsp_bm.byte_count; + const uint16_t byte_count = grxstsp.byte_count; xfer_ctl_t* xfer = XFER_CTL_BASE(epnum, TUSB_DIR_OUT); if (byte_count) { @@ -778,7 +807,8 @@ static void handle_rxflvl_irq(uint8_t rhport) { // short packet, minus remaining bytes (xfer_size) if (byte_count < xfer->max_size) { - xfer->total_len -= epout->tsiz_bm.xfer_size; + const dwc2_ep_tsize_t tsiz = {.value = epout->tsiz}; + xfer->total_len -= tsiz.xfer_size; if (epnum == 0) { xfer->total_len -= _dcd_data.ep0_pending[TUSB_DIR_OUT]; _dcd_data.ep0_pending[TUSB_DIR_OUT] = 0; @@ -840,11 +870,13 @@ static void handle_epin_slave(uint8_t rhport, uint8_t epnum, dwc2_diepint_t diep // - 64 bytes or // - Half/Empty of TX FIFO size (configured by GAHBCFG.TXFELVL) if (diepint_bm.txfifo_empty && (dwc2->diepempmsk & (1 << epnum))) { - const uint16_t remain_packets = epin->tsiz_bm.packet_count; + dwc2_ep_tsize_t tsiz = {.value = epin->tsiz}; + const uint16_t remain_packets = tsiz.packet_count; // Process every single packet (only whole packets can be written to fifo) for (uint16_t i = 0; i < remain_packets; i++) { - const uint16_t remain_bytes = (uint16_t) epin->tsiz_bm.xfer_size; + tsiz.value = epin->tsiz; + const uint16_t remain_bytes = (uint16_t) tsiz.xfer_size; const uint16_t xact_bytes = tu_min16(remain_bytes, xfer->max_size); // Check if dtxfsts has enough space available @@ -863,7 +895,8 @@ static void handle_epin_slave(uint8_t rhport, uint8_t epnum, dwc2_diepint_t diep } // Turn off TXFE if all bytes are written. - if (epin->tsiz_bm.xfer_size == 0) { + tsiz.value = epin->tsiz; + if (tsiz.xfer_size == 0) { dwc2->diepempmsk &= ~(1 << epnum); } } @@ -894,7 +927,8 @@ static void handle_epout_dma(uint8_t rhport, uint8_t epnum, dwc2_doepint_t doepi xfer_ctl_t* xfer = XFER_CTL_BASE(epnum, TUSB_DIR_OUT); // determine actual received bytes - const uint16_t remain = epout->tsiz_bm.xfer_size; + const dwc2_ep_tsize_t tsiz = {.value = epout->tsiz}; + const uint16_t remain = tsiz.xfer_size; xfer->total_len -= remain; // this is ZLP, so prepare EP0 for next setup @@ -930,7 +964,7 @@ static void handle_epin_dma(uint8_t rhport, uint8_t epnum, dwc2_diepint_t diepin static void handle_ep_irq(uint8_t rhport, uint8_t dir) { dwc2_regs_t* dwc2 = DWC2_REG(rhport); const bool is_dma = dma_device_enabled(dwc2); - const uint8_t ep_count = DWC2_EP_COUNT(dwc2); + const uint8_t ep_count = dwc2_ep_count(dwc2); const uint8_t daint_offset = (dir == TUSB_DIR_IN) ? DAINT_IEPINT_Pos : DAINT_OEPINT_Pos; dwc2_dep_t* ep_base = &dwc2->ep[dir == TUSB_DIR_IN ? 0 : 1][0]; @@ -983,14 +1017,16 @@ static void handle_ep_irq(uint8_t rhport, uint8_t dir) { */ void dcd_int_handler(uint8_t rhport) { dwc2_regs_t* dwc2 = DWC2_REG(rhport); - const uint32_t gintmask = dwc2->gintmsk; const uint32_t gintsts = dwc2->gintsts & gintmask; if (gintsts & GINTSTS_USBRST) { // USBRST is start of reset. dwc2->gintsts = GINTSTS_USBRST; + + usbd_spin_lock(true); handle_bus_reset(rhport); + usbd_spin_unlock(true); } if (gintsts & GINTSTS_ENUMDNE) { diff --git a/src/portable/synopsys/dwc2/dwc2_common.c b/src/portable/synopsys/dwc2/dwc2_common.c index f80ae9acb..e1e7d5c1a 100644 --- a/src/portable/synopsys/dwc2/dwc2_common.c +++ b/src/portable/synopsys/dwc2/dwc2_common.c @@ -36,6 +36,7 @@ #if CFG_TUH_ENABLED #include "host/hcd.h" +#include "host/usbh.h" #endif #include "dwc2_common.h" @@ -88,11 +89,13 @@ static void phy_fs_init(dwc2_regs_t* dwc2) { static void phy_hs_init(dwc2_regs_t* dwc2) { uint32_t gusbcfg = dwc2->gusbcfg; + const dwc2_ghwcfg2_t ghwcfg2 = {.value = dwc2->ghwcfg2}; + const dwc2_ghwcfg4_t ghwcfg4 = {.value = dwc2->ghwcfg4}; // De-select FS PHY gusbcfg &= ~GUSBCFG_PHYSEL; - if (dwc2->ghwcfg2_bm.hs_phy_type == GHWCFG2_HSPHY_ULPI) { + if (ghwcfg2.hs_phy_type == GHWCFG2_HSPHY_ULPI) { TU_LOG(DWC2_COMMON_DEBUG, "Highspeed ULPI PHY init\r\n"); // Select ULPI PHY (external) @@ -116,7 +119,7 @@ static void phy_hs_init(dwc2_regs_t* dwc2) { gusbcfg &= ~GUSBCFG_ULPI_UTMI_SEL; // Set 16-bit interface if supported - if (dwc2->ghwcfg4_bm.phy_data_width) { + if (ghwcfg4.phy_data_width) { gusbcfg |= GUSBCFG_PHYIF16; // 16 bit } else { gusbcfg &= ~GUSBCFG_PHYIF16; // 8 bit @@ -127,7 +130,7 @@ static void phy_hs_init(dwc2_regs_t* dwc2) { dwc2->gusbcfg = gusbcfg; // mcu specific phy init - dwc2_phy_init(dwc2, dwc2->ghwcfg2_bm.hs_phy_type); + dwc2_phy_init(dwc2, ghwcfg2.hs_phy_type); // Reset core after selecting PHY reset_core(dwc2); @@ -136,11 +139,11 @@ static void phy_hs_init(dwc2_regs_t* dwc2) { // - 9 if using 8-bit PHY interface // - 5 if using 16-bit PHY interface gusbcfg &= ~GUSBCFG_TRDT_Msk; - gusbcfg |= (dwc2->ghwcfg4_bm.phy_data_width ? 5u : 9u) << GUSBCFG_TRDT_Pos; + gusbcfg |= (ghwcfg4.phy_data_width ? 5u : 9u) << GUSBCFG_TRDT_Pos; dwc2->gusbcfg = gusbcfg; // MCU specific PHY update post reset - dwc2_phy_update(dwc2, dwc2->ghwcfg2_bm.hs_phy_type); + dwc2_phy_update(dwc2, ghwcfg2.hs_phy_type); } static bool check_dwc2(dwc2_regs_t* dwc2) { @@ -171,7 +174,6 @@ static bool check_dwc2(dwc2_regs_t* dwc2) { //-------------------------------------------------------------------- bool dwc2_core_is_highspeed(dwc2_regs_t* dwc2, tusb_role_t role) { (void)dwc2; - #if CFG_TUD_ENABLED if (role == TUSB_ROLE_DEVICE && !TUD_OPT_HIGH_SPEED) { return false; @@ -183,7 +185,8 @@ bool dwc2_core_is_highspeed(dwc2_regs_t* dwc2, tusb_role_t role) { } #endif - return dwc2->ghwcfg2_bm.hs_phy_type != GHWCFG2_HSPHY_NOT_SUPPORTED; + const dwc2_ghwcfg2_t ghwcfg2 = {.value = dwc2->ghwcfg2}; + return ghwcfg2.hs_phy_type != GHWCFG2_HSPHY_NOT_SUPPORTED; } /* dwc2 has several PHYs option diff --git a/src/portable/synopsys/dwc2/dwc2_esp32.h b/src/portable/synopsys/dwc2/dwc2_esp32.h index ddbfd0d10..49b8c54cb 100644 --- a/src/portable/synopsys/dwc2/dwc2_esp32.h +++ b/src/portable/synopsys/dwc2/dwc2_esp32.h @@ -55,8 +55,8 @@ static const dwc2_controller_t _dwc2_controller[] = { // On ESP32 for consistency we associate // - Port0 to OTG_FS, and Port1 to OTG_HS static const dwc2_controller_t _dwc2_controller[] = { -{ .reg_base = DWC2_FS_REG_BASE, .irqnum = ETS_USB_OTG11_CH0_INTR_SOURCE, .ep_count = 7, .ep_in_count = 5, .ep_fifo_size = 1024 }, -{ .reg_base = DWC2_HS_REG_BASE, .irqnum = ETS_USB_OTG_INTR_SOURCE, .ep_count = 16, .ep_in_count = 8, .ep_fifo_size = 4096 } + { .reg_base = DWC2_FS_REG_BASE, .irqnum = ETS_USB_OTG11_CH0_INTR_SOURCE, .ep_count = 7, .ep_in_count = 5, .ep_fifo_size = 1024 }, + { .reg_base = DWC2_HS_REG_BASE, .irqnum = ETS_USB_OTG_INTR_SOURCE, .ep_count = 16, .ep_in_count = 8, .ep_fifo_size = 4096 } }; #endif @@ -73,7 +73,7 @@ static void dwc2_int_handler_wrap(void* arg) { dcd_int_handler(rhport); } #endif -#if CFG_TUH_ENABLED +#if CFG_TUH_ENABLED && !CFG_TUH_MAX3421 if (role == TUSB_ROLE_HOST) { hcd_int_handler(rhport, true); } diff --git a/src/portable/synopsys/dwc2/dwc2_info.md b/src/portable/synopsys/dwc2/dwc2_info.md index dec021f59..595c89b75 100644 --- a/src/portable/synopsys/dwc2/dwc2_info.md +++ b/src/portable/synopsys/dwc2/dwc2_info.md @@ -1,58 +1,58 @@ -| | BCM2711 (Pi4) | EFM32GG | ESP32-S2/S3 | ESP32-P4 | ST F207/F407/411/429 FS | ST F407/429 HS | ST F412/76x FS | ST F723/L4P5 FS | ST F723 HS | ST F76x HS | ST H743/H750 | ST L476 FS | ST U5A5 HS | XMC4500 | GD32VF103 | -|:---------------------------|:----------------|:-------------|:--------------|:-------------|:--------------------------|:-----------------|:-----------------|:------------------|:-------------|:-------------|:---------------|:-------------|:-------------|:-------------|:------------| -| GUID | 0x2708A000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00001200 | 0x00001100 | 0x00002000 | 0x00003000 | 0x00003100 | 0x00002100 | 0x00002300 | 0x00002000 | 0x00005000 | 0x00AEC000 | 0x00001000 | -| GSNPSID | 0x4F54280A | 0x4F54330A | 0x4F54400A | 0x4F54400A | 0x4F54281A | 0x4F54281A | 0x4F54320A | 0x4F54330A | 0x4F54330A | 0x4F54320A | 0x4F54330A | 0x4F54310A | 0x4F54411A | 0x4F54292A | 0x00000000 | -| - specs version | 2.80a | 3.30a | 4.00a | 4.00a | 2.81a | 2.81a | 3.20a | 3.30a | 3.30a | 3.20a | 3.30a | 3.10a | 4.11a | 2.92a | 0.00W | -| GHWCFG1 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00000000 | -| GHWCFG2 | 0x228DDD50 | 0x228F5910 | 0x224DD930 | 0x215FFFD0 | 0x229DCD20 | 0x229ED590 | 0x229ED520 | 0x229ED520 | 0x229FE1D0 | 0x229FE190 | 0x229FE190 | 0x229ED520 | 0x228FE052 | 0x228F5930 | 0x00000000 | -| - op_mode | HNP SRP | HNP SRP | HNP SRP | HNP SRP | HNP SRP | HNP SRP | HNP SRP | HNP SRP | HNP SRP | HNP SRP | HNP SRP | HNP SRP | noHNP noSRP | HNP SRP | HNP SRP | -| - arch | DMA internal | DMA internal | DMA internal | DMA internal | Slave only | DMA internal | Slave only | Slave only | DMA internal | DMA internal | DMA internal | Slave only | DMA internal | DMA internal | Slave only | -| - single_point | hub | hub | n/a | hub | n/a | hub | n/a | n/a | hub | hub | hub | n/a | hub | n/a | hub | -| - hs_phy_type | UTMI+ | n/a | n/a | UTMI+/ULPI | n/a | ULPI | n/a | n/a | UTMI+/ULPI | ULPI | ULPI | n/a | UTMI+ | n/a | n/a | -| - fs_phy_type | Dedicated | Dedicated | Dedicated | Shared ULPI | Dedicated | Dedicated | Dedicated | Dedicated | Dedicated | Dedicated | Dedicated | Dedicated | n/a | Dedicated | n/a | -| - num_dev_ep | 7 | 6 | 6 | 15 | 3 | 5 | 5 | 5 | 8 | 8 | 8 | 5 | 8 | 6 | 0 | -| - num_host_ch | 7 | 13 | 7 | 15 | 7 | 11 | 11 | 11 | 15 | 15 | 15 | 11 | 15 | 13 | 0 | -| - period_channel_support | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | -| - enable_dynamic_fifo | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | -| - mul_proc_intrpt | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | -| - reserved21 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | -| - nptx_q_depth | 8 | 8 | 4 | 4 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 2 | -| - ptx_q_depth | 8 | 8 | 8 | 4 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 2 | -| - token_q_depth | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 0 | -| - otg_enable_ic_usb | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | -| GHWCFG3 | 0x0FF000E8 | 0x01F204E8 | 0x00C804B5 | 0x03805EB5 | 0x020001E8 | 0x03F403E8 | 0x0200D1E8 | 0x0200D1E8 | 0x03EED2E8 | 0x03EED2E8 | 0x03B8D2E8 | 0x0200D1E8 | 0x03B882E8 | 0x027A01E5 | 0x00000000 | -| - xfer_size_width | 8 | 8 | 5 | 5 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 5 | 0 | -| - packet_size_width | 6 | 6 | 3 | 3 | 6 | 6 | 6 | 6 | 6 | 6 | 6 | 6 | 6 | 6 | 0 | -| - otg_enable | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | -| - i2c_enable | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | -| - vendor_ctrl_itf | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 1 | 1 | 1 | 0 | 1 | 0 | 0 | -| - optional_feature_removed | 0 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | -| - synch_reset | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | -| - otg_adp_support | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | -| - otg_enable_hsic | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | -| - battery_charger_support | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | -| - lpm_mode | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | -| - dfifo_depth | 4080 | 498 | 200 | 896 | 512 | 1012 | 512 | 512 | 1006 | 1006 | 952 | 512 | 952 | 634 | 0 | -| GHWCFG4 | 0x1FF00020 | 0x1BF08030 | 0xD3F0A030 | 0xDFF1A030 | 0x0FF08030 | 0x17F00030 | 0x17F08030 | 0x17F08030 | 0x23F00030 | 0x23F00030 | 0xE3F00030 | 0x17F08030 | 0xE2103E30 | 0xDBF08030 | 0x00000000 | -| - num_dev_period_in_ep | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | -| - partial_powerdown | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | -| - ahb_freq_min | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | -| - hibernation | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | -| - extended_hibernation | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | -| - reserved8 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | -| - enhanced_lpm_support1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | -| - service_interval_flow | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | -| - ipg_isoc_support | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | -| - acg_support | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | -| - enhanced_lpm_support | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | -| - phy_data_width | 8 bit | 8/16 bit | 8/16 bit | 8/16 bit | 8/16 bit | 8 bit | 8/16 bit | 8/16 bit | 8 bit | 8 bit | 8 bit | 8/16 bit | 8 bit | 8/16 bit | 8 bit | -| - ctrl_ep_num | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | -| - iddg_filter | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | -| - vbus_valid_filter | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 1 | 0 | -| - a_valid_filter | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 1 | 0 | -| - b_valid_filter | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 1 | 0 | -| - session_end_filter | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 1 | 0 | -| - dedicated_fifos | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | -| - num_dev_in_eps | 7 | 6 | 4 | 7 | 3 | 5 | 5 | 5 | 8 | 8 | 8 | 5 | 8 | 6 | 0 | -| - dma_desc_enable | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 0 | -| - dma_desc_dynamic | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 0 | +| | BCM2711 (Pi4) | EFM32GG | ESP32-S2/S3 | ESP32-P4 | ST F207/F407/411/429 FS | ST F407/429 HS | ST F412/76x FS | ST F723/L4P5 FS | ST F723 HS | ST F76x HS | ST H743/H750 | ST L476 FS | ST U5A5/H7RS/N6 HS | XMC4500 | GD32VF103 | +|:---------------------------|:----------------|:-------------|:--------------|:-------------|:--------------------------|:-----------------|:-----------------|:------------------|:-------------|:-------------|:---------------|:-------------|:---------------------|:-------------|:------------| +| GUID | 0x2708A000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00001200 | 0x00001100 | 0x00002000 | 0x00003000 | 0x00003100 | 0x00002100 | 0x00002300 | 0x00002000 | 0x00005000 | 0x00AEC000 | 0x00001000 | +| GSNPSID | 0x4F54280A | 0x4F54330A | 0x4F54400A | 0x4F54400A | 0x4F54281A | 0x4F54281A | 0x4F54320A | 0x4F54330A | 0x4F54330A | 0x4F54320A | 0x4F54330A | 0x4F54310A | 0x4F54411A | 0x4F54292A | 0x00000000 | +| - specs version | 2.80a | 3.30a | 4.00a | 4.00a | 2.81a | 2.81a | 3.20a | 3.30a | 3.30a | 3.20a | 3.30a | 3.10a | 4.11a | 2.92a | 0.00W | +| GHWCFG1 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00000000 | +| GHWCFG2 | 0x228DDD50 | 0x228F5910 | 0x224DD930 | 0x215FFFD0 | 0x229DCD20 | 0x229ED590 | 0x229ED520 | 0x229ED520 | 0x229FE1D0 | 0x229FE190 | 0x229FE190 | 0x229ED520 | 0x228FE052 | 0x228F5930 | 0x00000000 | +| - op_mode | HNP SRP | HNP SRP | HNP SRP | HNP SRP | HNP SRP | HNP SRP | HNP SRP | HNP SRP | HNP SRP | HNP SRP | HNP SRP | HNP SRP | noHNP noSRP | HNP SRP | HNP SRP | +| - arch | DMA internal | DMA internal | DMA internal | DMA internal | Slave only | DMA internal | Slave only | Slave only | DMA internal | DMA internal | DMA internal | Slave only | DMA internal | DMA internal | Slave only | +| - single_point | hub | hub | n/a | hub | n/a | hub | n/a | n/a | hub | hub | hub | n/a | hub | n/a | hub | +| - hs_phy_type | UTMI+ | n/a | n/a | UTMI+/ULPI | n/a | ULPI | n/a | n/a | UTMI+/ULPI | ULPI | ULPI | n/a | UTMI+ | n/a | n/a | +| - fs_phy_type | Dedicated | Dedicated | Dedicated | Shared ULPI | Dedicated | Dedicated | Dedicated | Dedicated | Dedicated | Dedicated | Dedicated | Dedicated | n/a | Dedicated | n/a | +| - num_dev_ep | 7 | 6 | 6 | 15 | 3 | 5 | 5 | 5 | 8 | 8 | 8 | 5 | 8 | 6 | 0 | +| - num_host_ch | 7 | 13 | 7 | 15 | 7 | 11 | 11 | 11 | 15 | 15 | 15 | 11 | 15 | 13 | 0 | +| - period_channel_support | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | +| - enable_dynamic_fifo | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | +| - mul_proc_intrpt | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | +| - reserved21 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| - nptx_q_depth | 8 | 8 | 4 | 4 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 2 | +| - ptx_q_depth | 8 | 8 | 8 | 4 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 2 | +| - token_q_depth | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 0 | +| - otg_enable_ic_usb | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| GHWCFG3 | 0x0FF000E8 | 0x01F204E8 | 0x00C804B5 | 0x03805EB5 | 0x020001E8 | 0x03F403E8 | 0x0200D1E8 | 0x0200D1E8 | 0x03EED2E8 | 0x03EED2E8 | 0x03B8D2E8 | 0x0200D1E8 | 0x03B882E8 | 0x027A01E5 | 0x00000000 | +| - xfer_size_width | 8 | 8 | 5 | 5 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 5 | 0 | +| - packet_size_width | 6 | 6 | 3 | 3 | 6 | 6 | 6 | 6 | 6 | 6 | 6 | 6 | 6 | 6 | 0 | +| - otg_enable | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | +| - i2c_enable | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | +| - vendor_ctrl_itf | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 1 | 1 | 1 | 0 | 1 | 0 | 0 | +| - optional_feature_removed | 0 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| - synch_reset | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| - otg_adp_support | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | +| - otg_enable_hsic | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| - battery_charger_support | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | +| - lpm_mode | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | +| - dfifo_depth | 4080 | 498 | 200 | 896 | 512 | 1012 | 512 | 512 | 1006 | 1006 | 952 | 512 | 952 | 634 | 0 | +| GHWCFG4 | 0x1FF00020 | 0x1BF08030 | 0xD3F0A030 | 0xDFF1A030 | 0x0FF08030 | 0x17F00030 | 0x17F08030 | 0x17F08030 | 0x23F00030 | 0x23F00030 | 0xE3F00030 | 0x17F08030 | 0xE2103E30 | 0xDBF08030 | 0x00000000 | +| - num_dev_period_in_ep | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| - partial_powerdown | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | +| - ahb_freq_min | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | +| - hibernation | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| - extended_hibernation | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| - reserved8 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| - enhanced_lpm_support1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| - service_interval_flow | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| - ipg_isoc_support | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| - acg_support | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| - enhanced_lpm_support | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| - phy_data_width | 8 bit | 8/16 bit | 8/16 bit | 8/16 bit | 8/16 bit | 8 bit | 8/16 bit | 8/16 bit | 8 bit | 8 bit | 8 bit | 8/16 bit | 8 bit | 8/16 bit | 8 bit | +| - ctrl_ep_num | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| - iddg_filter | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | +| - vbus_valid_filter | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 1 | 0 | +| - a_valid_filter | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 1 | 0 | +| - b_valid_filter | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 1 | 0 | +| - session_end_filter | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 1 | 0 | +| - dedicated_fifos | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | +| - num_dev_in_eps | 7 | 6 | 4 | 7 | 3 | 5 | 5 | 5 | 8 | 8 | 8 | 5 | 8 | 6 | 0 | +| - dma_desc_enable | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 0 | +| - dma_desc_dynamic | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 0 | diff --git a/src/portable/synopsys/dwc2/dwc2_info.py b/src/portable/synopsys/dwc2/dwc2_info.py index 25edcf22d..3b1993cc5 100755 --- a/src/portable/synopsys/dwc2/dwc2_info.py +++ b/src/portable/synopsys/dwc2/dwc2_info.py @@ -21,7 +21,7 @@ dwc2_reg_value = { 'ST F76x HS': [0x2100, 0x4F54320A, 0, 0x229FE190, 0x03EED2E8, 0x23F00030], 'ST H743/H750': [0x2300, 0x4F54330A, 0, 0x229FE190, 0x03B8D2E8, 0xE3F00030], 'ST L476 FS': [0x2000, 0x4F54310A, 0, 0x229ED520, 0x0200D1E8, 0x17F08030], - 'ST U5A5 HS': [0x5000, 0x4F54411A, 0, 0x228FE052, 0x03B882E8, 0xE2103E30], + 'ST U5A5/H7RS/N6 HS': [0x5000, 0x4F54411A, 0, 0x228FE052, 0x03B882E8, 0xE2103E30], 'XMC4500': [0xAEC000, 0x4F54292A, 0, 0x228F5930, 0x027A01E5, 0xDBF08030], 'GD32VF103': [0x1000, 0, 0, 0, 0, 0], } diff --git a/src/portable/synopsys/dwc2/dwc2_stm32.h b/src/portable/synopsys/dwc2/dwc2_stm32.h index c11c1eb05..dc4251c29 100644 --- a/src/portable/synopsys/dwc2/dwc2_stm32.h +++ b/src/portable/synopsys/dwc2/dwc2_stm32.h @@ -77,6 +77,17 @@ extern "C" { #define EP_MAX_HS 9 #define EP_FIFO_SIZE_HS 4096 +#elif CFG_TUSB_MCU == OPT_MCU_STM32N6 + #include "stm32n6xx.h" + #define EP_MAX_FS 9 + #define EP_FIFO_SIZE_FS 4096 + + #define EP_MAX_HS 9 + #define EP_FIFO_SIZE_HS 4096 + + #define USB_OTG_HS_PERIPH_BASE USB1_OTG_HS_BASE + #define OTG_HS_IRQn USB1_OTG_HS_IRQn + #elif CFG_TUSB_MCU == OPT_MCU_STM32F7 #include "stm32f7xx.h" #define EP_MAX_FS 6 diff --git a/src/portable/synopsys/dwc2/dwc2_type.h b/src/portable/synopsys/dwc2/dwc2_type.h index 812096759..0a8dacf5f 100644 --- a/src/portable/synopsys/dwc2/dwc2_type.h +++ b/src/portable/synopsys/dwc2/dwc2_type.h @@ -184,415 +184,470 @@ enum { //-------------------------------------------------------------------- // Common Register Bitfield //-------------------------------------------------------------------- -typedef struct TU_ATTR_PACKED { - uint32_t ses_req_scs : 1; // 0 Session request success - uint32_t ses_req : 1; // 1 Session request - uint32_t vbval_ov_en : 1; // 2 VBUS valid override enable - uint32_t vbval_ov_val : 1; // 3 VBUS valid override value - uint32_t aval_ov_en : 1; // 4 A-peripheral session valid override enable - uint32_t aval_ov_al : 1; // 5 A-peripheral session valid override value - uint32_t bval_ov_en : 1; // 6 B-peripheral session valid override enable - uint32_t bval_ov_val : 1; // 7 B-peripheral session valid override value - uint32_t hng_scs : 1; // 8 Host negotiation success - uint32_t hnp_rq : 1; // 9 HNP (host negotiation protocol) request - uint32_t host_set_hnp_en : 1; // 10 Host set HNP enable - uint32_t dev_hnp_en : 1; // 11 Device HNP enabled - uint32_t embedded_host_en : 1; // 12 Embedded host enable - uint32_t rsv13_14 : 2; // 13.14 Reserved - uint32_t dbnc_filter_bypass : 1; // 15 Debounce filter bypass - uint32_t cid_status : 1; // 16 Connector ID status - uint32_t dbnc_done : 1; // 17 Debounce done - uint32_t ases_valid : 1; // 18 A-session valid - uint32_t bses_valid : 1; // 19 B-session valid - uint32_t otg_ver : 1; // 20 OTG version 0: v1.3, 1: v2.0 - uint32_t current_mode : 1; // 21 Current mode of operation. Only from v3.00a - uint32_t mult_val_id_bc : 5; // 22..26 Multi-valued input pin ID battery charger - uint32_t chirp_en : 1; // 27 Chirp detection enable - uint32_t rsv28_30 : 3; // 28.30: Reserved - uint32_t test_mode_corr_eusb2 : 1; // 31 Test mode control for eUSB2 PHY +typedef union { + uint32_t value; + struct TU_ATTR_PACKED { + uint32_t ses_req_scs : 1; // 0 Session request success + uint32_t ses_req : 1; // 1 Session request + uint32_t vbval_ov_en : 1; // 2 VBUS valid override enable + uint32_t vbval_ov_val : 1; // 3 VBUS valid override value + uint32_t aval_ov_en : 1; // 4 A-peripheral session valid override enable + uint32_t aval_ov_al : 1; // 5 A-peripheral session valid override value + uint32_t bval_ov_en : 1; // 6 B-peripheral session valid override enable + uint32_t bval_ov_val : 1; // 7 B-peripheral session valid override value + uint32_t hng_scs : 1; // 8 Host negotiation success + uint32_t hnp_rq : 1; // 9 HNP (host negotiation protocol) request + uint32_t host_set_hnp_en : 1; // 10 Host set HNP enable + uint32_t dev_hnp_en : 1; // 11 Device HNP enabled + uint32_t embedded_host_en : 1; // 12 Embedded host enable + uint32_t rsv13_14 : 2; // 13.14 Reserved + uint32_t dbnc_filter_bypass : 1; // 15 Debounce filter bypass + uint32_t cid_status : 1; // 16 Connector ID status + uint32_t dbnc_done : 1; // 17 Debounce done + uint32_t ases_valid : 1; // 18 A-session valid + uint32_t bses_valid : 1; // 19 B-session valid + uint32_t otg_ver : 1; // 20 OTG version 0: v1.3, 1: v2.0 + uint32_t current_mode : 1; // 21 Current mode of operation. Only from v3.00a + uint32_t mult_val_id_bc : 5; // 22..26 Multi-valued input pin ID battery charger + uint32_t chirp_en : 1; // 27 Chirp detection enable + uint32_t rsv28_30 : 3; // 28.30: Reserved + uint32_t test_mode_corr_eusb2 : 1; // 31 Test mode control for eUSB2 PHY + }; } dwc2_gotgctl_t; TU_VERIFY_STATIC(sizeof(dwc2_gotgctl_t) == 4, "incorrect size"); -typedef struct TU_ATTR_PACKED { - uint32_t rsv0_1 : 2; // 0..1 Reserved - uint32_t ses_end_det : 1; // 2 Session end detected - uint32_t rsv3_7 : 5; // 3..7 Reserved - uint32_t srs_status_change : 1; // 8 Session request success status change - uint32_t hns_status_change : 1; // 9 Host negotiation success status change - uint32_t rsv10_16 : 7; // 10..16 Reserved - uint32_t hng_det : 1; // 17 Host negotiation detected - uint32_t adev_timeout_change : 1; // 18 A-device timeout change - uint32_t dbnc_done : 1; // 19 Debounce done - uint32_t mult_val_lp_change : 1; // 20 Multi-valued input pin change - uint32_t rsv21_31 :11; // 21..31 Reserved +typedef union { + uint32_t value; + struct TU_ATTR_PACKED { + uint32_t rsv0_1 : 2; // 0..1 Reserved + uint32_t ses_end_det : 1; // 2 Session end detected + uint32_t rsv3_7 : 5; // 3..7 Reserved + uint32_t srs_status_change : 1; // 8 Session request success status change + uint32_t hns_status_change : 1; // 9 Host negotiation success status change + uint32_t rsv10_16 : 7; // 10..16 Reserved + uint32_t hng_det : 1; // 17 Host negotiation detected + uint32_t adev_timeout_change : 1; // 18 A-device timeout change + uint32_t dbnc_done : 1; // 19 Debounce done + uint32_t mult_val_lp_change : 1; // 20 Multi-valued input pin change + uint32_t rsv21_31 :11; // 21..31 Reserved + }; } dwc2_gotgint_t; TU_VERIFY_STATIC(sizeof(dwc2_gotgint_t) == 4, "incorrect size"); -typedef struct TU_ATTR_PACKED { - uint32_t gintmask : 1; // 0 Global interrupt mask - uint32_t hbst_len : 4; // 1..4 Burst length/type - uint32_t dma_en : 1; // 5 DMA enable - uint32_t rsv6 : 1; // 6 Reserved - uint32_t nptxf_empty_lvl : 1; // 7 Non-periodic Tx FIFO empty level - uint32_t ptxf_empty_lvl : 1; // 8 Periodic Tx FIFO empty level - uint32_t rsv9_20 : 12; // 9.20: Reserved - uint32_t remote_mem_support : 1; // 21 Remote memory support - uint32_t notify_all_dma_write : 1; // 22 Notify all DMA writes - uint32_t ahb_single : 1; // 23 AHB single - uint32_t inv_desc_endian : 1; // 24 Inverse descriptor endian - uint32_t rsv25_31 : 7; // 25..31 Reserved +typedef union { + uint32_t value; + struct TU_ATTR_PACKED { + uint32_t gintmask : 1; // 0 Global interrupt mask + uint32_t hbst_len : 4; // 1..4 Burst length/type + uint32_t dma_en : 1; // 5 DMA enable + uint32_t rsv6 : 1; // 6 Reserved + uint32_t nptxf_empty_lvl : 1; // 7 Non-periodic Tx FIFO empty level + uint32_t ptxf_empty_lvl : 1; // 8 Periodic Tx FIFO empty level + uint32_t rsv9_20 : 12; // 9.20: Reserved + uint32_t remote_mem_support : 1; // 21 Remote memory support + uint32_t notify_all_dma_write : 1; // 22 Notify all DMA writes + uint32_t ahb_single : 1; // 23 AHB single + uint32_t inv_desc_endian : 1; // 24 Inverse descriptor endian + uint32_t rsv25_31 : 7; // 25..31 Reserved + }; } dwc2_gahbcfg_t; TU_VERIFY_STATIC(sizeof(dwc2_gahbcfg_t) == 4, "incorrect size"); -typedef struct TU_ATTR_PACKED { - uint32_t timeout_cal : 3; /* 0..2 Timeout calibration. - The USB standard timeout value for high-speed operation is 736 to 816 (inclusive) bit times. The USB standard - timeout value for full- speed operation is 16 to 18 (inclusive) bit times. The application must program this field - based on the speed of enumeration. The number of bit times added per PHY clock are as follows: - - High-speed: PHY clock One 30-MHz = 16 bit times, One 60-MHz = 8 bit times - - Full-speed: PHY clock One 30-MHz = 0.4 bit times, One 60-MHz = 0.2 bit times, One 48-MHz = 0.25 bit times */ - uint32_t phy_if16 : 1; // 3 PHY interface. 0: 8 bits, 1: 16 bits - uint32_t ulpi_utmi_sel : 1; // 4 ULPI/UTMI select. 0: UTMI+, 1: ULPI - uint32_t fs_intf_sel : 1; // 5 Fullspeed serial interface select. 0: 6-pin, 1: 3-pin - uint32_t phy_sel : 1; // 6 HS/FS PHY selection. 0: HS UTMI+ or ULPI, 1: FS serial transceiver - uint32_t ddr_sel : 1; // 7 ULPI DDR select. 0: Single data rate 8-bit, 1: Double data rate 4-bit - uint32_t srp_capable : 1; // 8 SRP-capable - uint32_t hnp_capable : 1; // 9 HNP-capable - uint32_t turnaround_time : 4; // 10..13 Turnaround time. 9: 8-bit UTMI+, 5: 16-bit UTMI+ - uint32_t rsv14 : 1; // 14 Reserved - uint32_t phy_low_power_clk_sel : 1; /* 15 PHY low-power clock select either 480-MHz or 48-MHz (low-power) PHY mode. - In FS/LS modes, the PHY can usually operate on a 48-MHz clock to save power. This bit is valid only for UTMI+ PHYs. - - 0: 480 Mhz internal PLL: the UTMI interface operates at either 60 MHz (8 bit) or 30 MHz (16-bit) - - 1 48 Mhz external clock: the UTMI interface operates at 48 MHz in FS mode and at either 48 or 6 MHz in LS mode */ - uint32_t otg_i2c_sel : 1; // 16 OTG I2C interface select. 0: UTMI-FS, 1: I2C for OTG signals - uint32_t ulpi_fsls : 1; /* 17 ULPI FS/LS select. 0: ULPI, 1: ULPI FS/LS. - valid only when the FS serial transceiver is selected on the ULPI PHY. */ - uint32_t ulpi_auto_resume : 1; // 18 ULPI Auto-resume - uint32_t ulpi_clk_sus_m : 1; // 19 ULPI Clock SuspendM - uint32_t ulpi_ext_vbus_drv : 1; // 20 ULPI External VBUS Drive - uint32_t ulpi_int_vbus_indicator : 1; // 21 ULPI Internal VBUS Indicator - uint32_t term_sel_dl_pulse : 1; // 22 TermSel DLine pulsing - uint32_t indicator_complement : 1; // 23 Indicator complement - uint32_t indicator_pass_through : 1; // 24 Indicator pass through - uint32_t ulpi_if_protect_disable : 1; // 25 ULPI interface protect disable - uint32_t ic_usb_capable : 1; // 26 IC_USB Capable - uint32_t ic_usb_traf_ctl : 1; // 27 IC_USB Traffic Control - uint32_t tx_end_delay : 1; // 28 TX end delay - uint32_t force_host_mode : 1; // 29 Force host mode - uint32_t force_dev_mode : 1; // 30 Force device mode - uint32_t corrupt_tx_pkt : 1; // 31 Corrupt Tx packet. 0: normal, 1: debug +typedef union { + uint32_t value; + struct TU_ATTR_PACKED { + uint32_t timeout_cal : 3; /* 0..2 Timeout calibration. + The USB standard timeout value for high-speed operation is 736 to 816 (inclusive) bit times. The USB standard + timeout value for full- speed operation is 16 to 18 (inclusive) bit times. The application must program this field + based on the speed of enumeration. The number of bit times added per PHY clock are as follows: + - High-speed: PHY clock One 30-MHz = 16 bit times, One 60-MHz = 8 bit times + - Full-speed: PHY clock One 30-MHz = 0.4 bit times, One 60-MHz = 0.2 bit times, One 48-MHz = 0.25 bit times */ + uint32_t phy_if16 : 1; // 3 PHY interface. 0: 8 bits, 1: 16 bits + uint32_t ulpi_utmi_sel : 1; // 4 ULPI/UTMI select. 0: UTMI+, 1: ULPI + uint32_t fs_intf_sel : 1; // 5 Fullspeed serial interface select. 0: 6-pin, 1: 3-pin + uint32_t phy_sel : 1; // 6 HS/FS PHY selection. 0: HS UTMI+ or ULPI, 1: FS serial transceiver + uint32_t ddr_sel : 1; // 7 ULPI DDR select. 0: Single data rate 8-bit, 1: Double data rate 4-bit + uint32_t srp_capable : 1; // 8 SRP-capable + uint32_t hnp_capable : 1; // 9 HNP-capable + uint32_t turnaround_time : 4; // 10..13 Turnaround time. 9: 8-bit UTMI+, 5: 16-bit UTMI+ + uint32_t rsv14 : 1; // 14 Reserved + uint32_t phy_low_power_clk_sel : 1; /* 15 PHY low-power clock select either 480-MHz or 48-MHz (low-power) PHY mode. + In FS/LS modes, the PHY can usually operate on a 48-MHz clock to save power. This bit is valid only for UTMI+ PHYs. + - 0: 480 Mhz internal PLL: the UTMI interface operates at either 60 MHz (8 bit) or 30 MHz (16-bit) + - 1 48 Mhz external clock: the UTMI interface operates at 48 MHz in FS mode and at either 48 or 6 MHz in LS mode */ + uint32_t otg_i2c_sel : 1; // 16 OTG I2C interface select. 0: UTMI-FS, 1: I2C for OTG signals + uint32_t ulpi_fsls : 1; /* 17 ULPI FS/LS select. 0: ULPI, 1: ULPI FS/LS. + valid only when the FS serial transceiver is selected on the ULPI PHY. */ + uint32_t ulpi_auto_resume : 1; // 18 ULPI Auto-resume + uint32_t ulpi_clk_sus_m : 1; // 19 ULPI Clock SuspendM + uint32_t ulpi_ext_vbus_drv : 1; // 20 ULPI External VBUS Drive + uint32_t ulpi_int_vbus_indicator : 1; // 21 ULPI Internal VBUS Indicator + uint32_t term_sel_dl_pulse : 1; // 22 TermSel DLine pulsing + uint32_t indicator_complement : 1; // 23 Indicator complement + uint32_t indicator_pass_through : 1; // 24 Indicator pass through + uint32_t ulpi_if_protect_disable : 1; // 25 ULPI interface protect disable + uint32_t ic_usb_capable : 1; // 26 IC_USB Capable + uint32_t ic_usb_traf_ctl : 1; // 27 IC_USB Traffic Control + uint32_t tx_end_delay : 1; // 28 TX end delay + uint32_t force_host_mode : 1; // 29 Force host mode + uint32_t force_dev_mode : 1; // 30 Force device mode + uint32_t corrupt_tx_pkt : 1; // 31 Corrupt Tx packet. 0: normal, 1: debug + }; } dwc2_gusbcfg_t; TU_VERIFY_STATIC(sizeof(dwc2_gusbcfg_t) == 4, "incorrect size"); -typedef struct TU_ATTR_PACKED { - uint32_t core_soft_rst : 1; // 0 Core Soft Reset - uint32_t piufs_soft_rst : 1; // 1 PIU FS Dedicated Controller Soft Reset - uint32_t frame_counter_rst : 1; // 2 Frame Counter Reset (host) - uint32_t intoken_q_flush : 1; // 3 IN Token Queue Flush - uint32_t rx_fifo_flush : 1; // 4 RX FIFO Flush - uint32_t tx_fifo_flush : 1; // 5 TX FIFO Flush - uint32_t tx_fifo_num : 5; // 6..10 TX FIFO Number - uint32_t rsv11_28 :18; // 11..28 Reserved - uint32_t core_soft_rst_done : 1; // 29 Core Soft Reset Done, from v4.20a - uint32_t dma_req : 1; // 30 DMA Request - uint32_t ahb_idle : 1; // 31 AHB Idle +typedef union { + uint32_t value; + struct TU_ATTR_PACKED { + uint32_t core_soft_rst : 1; // 0 Core Soft Reset + uint32_t piufs_soft_rst : 1; // 1 PIU FS Dedicated Controller Soft Reset + uint32_t frame_counter_rst : 1; // 2 Frame Counter Reset (host) + uint32_t intoken_q_flush : 1; // 3 IN Token Queue Flush + uint32_t rx_fifo_flush : 1; // 4 RX FIFO Flush + uint32_t tx_fifo_flush : 1; // 5 TX FIFO Flush + uint32_t tx_fifo_num : 5; // 6..10 TX FIFO Number + uint32_t rsv11_28 :18; // 11..28 Reserved + uint32_t core_soft_rst_done : 1; // 29 Core Soft Reset Done, from v4.20a + uint32_t dma_req : 1; // 30 DMA Request + uint32_t ahb_idle : 1; // 31 AHB Idle + }; } dwc2_grstctl_t; TU_VERIFY_STATIC(sizeof(dwc2_grstctl_t) == 4, "incorrect size"); -typedef struct TU_ATTR_PACKED { - uint32_t ep_ch_num : 4; // 0..3 Endpoint/Channel Number - uint32_t byte_count :11; // 4..14 Byte Count - uint32_t dpid : 2; // 15..16 Data PID - uint32_t packet_status : 4; // 17..20 Packet Status - uint32_t frame_number : 4; // 21..24 Frame Number - uint32_t rsv25_31 : 7; // 25..31 Reserved +typedef union { + uint32_t value; + struct TU_ATTR_PACKED { + uint32_t ep_ch_num : 4; // 0..3 Endpoint/Channel Number + uint32_t byte_count :11; // 4..14 Byte Count + uint32_t dpid : 2; // 15..16 Data PID + uint32_t packet_status : 4; // 17..20 Packet Status + uint32_t frame_number : 4; // 21..24 Frame Number + uint32_t rsv25_31 : 7; // 25..31 Reserved + }; } dwc2_grxstsp_t; TU_VERIFY_STATIC(sizeof(dwc2_grxstsp_t) == 4, "incorrect size"); -// Hardware Configuration -typedef struct TU_ATTR_PACKED { - uint32_t op_mode : 3; // 0..2 HNP/SRP Host/Device/OTG mode - uint32_t arch : 2; // 3..4 Slave/External/Internal DMA - uint32_t single_point : 1; // 5 0: support hub and split | 1: no hub, no split - uint32_t hs_phy_type : 2; // 6..7 0: not supported | 1: UTMI+ | 2: ULPI | 3: UTMI+ and ULPI - uint32_t fs_phy_type : 2; // 8..9 0: not supported | 1: dedicated | 2: UTMI+ | 3: ULPI - uint32_t num_dev_ep : 4; // 10..13 Number of device endpoints (excluding EP0) - uint32_t num_host_ch : 4; // 14..17 Number of host channel (excluding control) - uint32_t period_channel_support : 1; // 18 Support Periodic OUT Host Channel - uint32_t enable_dynamic_fifo : 1; // 19 Dynamic FIFO Sizing Enabled - uint32_t mul_proc_intrpt : 1; // 20 Multi-Processor Interrupt enabled (OTG_MULTI_PROC_INTRPT) - uint32_t reserved21 : 1; // 21 reserved - uint32_t nptx_q_depth : 2; // 22..23 Non-periodic request queue depth: 0 = 2. 1 = 4, 2 = 8 - uint32_t ptx_q_depth : 2; // 24..25 Host periodic request queue depth: 0 = 2. 1 = 4, 2 = 8 - uint32_t token_q_depth : 5; // 26..30 Device IN token sequence learning queue depth: 0-30 - uint32_t otg_enable_ic_usb : 1; // 31 IC_USB mode specified for mode of operation +typedef union { + uint32_t value; + struct TU_ATTR_PACKED { + uint32_t op_mode : 3; // 0..2 HNP/SRP Host/Device/OTG mode + uint32_t arch : 2; // 3..4 Slave/External/Internal DMA + uint32_t single_point : 1; // 5 0: support hub and split | 1: no hub, no split + uint32_t hs_phy_type : 2; // 6..7 0: not supported | 1: UTMI+ | 2: ULPI | 3: UTMI+ and ULPI + uint32_t fs_phy_type : 2; // 8..9 0: not supported | 1: dedicated | 2: UTMI+ | 3: ULPI + uint32_t num_dev_ep : 4; // 10..13 Number of device endpoints (excluding EP0) + uint32_t num_host_ch : 4; // 14..17 Number of host channel (excluding control) + uint32_t period_channel_support : 1; // 18 Support Periodic OUT Host Channel + uint32_t enable_dynamic_fifo : 1; // 19 Dynamic FIFO Sizing Enabled + uint32_t mul_proc_intrpt : 1; // 20 Multi-Processor Interrupt enabled (OTG_MULTI_PROC_INTRPT) + uint32_t reserved21 : 1; // 21 reserved + uint32_t nptx_q_depth : 2; // 22..23 Non-periodic request queue depth: 0 = 2. 1 = 4, 2 = 8 + uint32_t ptx_q_depth : 2; // 24..25 Host periodic request queue depth: 0 = 2. 1 = 4, 2 = 8 + uint32_t token_q_depth : 5; // 26..30 Device IN token sequence learning queue depth: 0-30 + uint32_t otg_enable_ic_usb : 1; // 31 IC_USB mode specified for mode of operation + }; } dwc2_ghwcfg2_t; TU_VERIFY_STATIC(sizeof(dwc2_ghwcfg2_t) == 4, "incorrect size"); -typedef struct TU_ATTR_PACKED { - uint32_t xfer_size_width : 4; // 0..3 Transfer size counter in bits = 11 + n (max 19 bits) - uint32_t packet_size_width : 3; // 4..6 Packet size counter in bits = 4 + n (max 10 bits) - uint32_t otg_enable : 1; // 7 OTG capable - uint32_t i2c_enable : 1; // 8 I2C interface is available - uint32_t vendor_ctrl_itf : 1; // 9 Vendor control interface is available - uint32_t optional_feature_removed : 1; // 10 remove User ID, GPIO, SOF toggle & counter to save gate count - uint32_t synch_reset : 1; // 11 0: async reset | 1: synch reset - uint32_t otg_adp_support : 1; // 12 ADP logic is present along with HSOTG controller - uint32_t otg_enable_hsic : 1; // 13 1: HSIC-capable with shared UTMI PHY interface | 0: non-HSIC - uint32_t battery_charger_support : 1; // s14 upport battery charger - uint32_t lpm_mode : 1; // 15 LPM mode - uint32_t dfifo_depth : 16; // DFIFO depth - EP_LOC_CNT in terms of 32-bit words -}dwc2_ghwcfg3_t; +typedef union { + uint32_t value; + struct TU_ATTR_PACKED { + uint32_t xfer_size_width : 4; // 0..3 Transfer size counter in bits = 11 + n (max 19 bits) + uint32_t packet_size_width : 3; // 4..6 Packet size counter in bits = 4 + n (max 10 bits) + uint32_t otg_enable : 1; // 7 OTG capable + uint32_t i2c_enable : 1; // 8 I2C interface is available + uint32_t vendor_ctrl_itf : 1; // 9 Vendor control interface is available + uint32_t optional_feature_removed : 1; // 10 remove User ID, GPIO, SOF toggle & counter to save gate count + uint32_t synch_reset : 1; // 11 0: async reset | 1: synch reset + uint32_t otg_adp_support : 1; // 12 ADP logic is present along with HSOTG controller + uint32_t otg_enable_hsic : 1; // 13 1: HSIC-capable with shared UTMI PHY interface | 0: non-HSIC + uint32_t battery_charger_support : 1; // s14 upport battery charger + uint32_t lpm_mode : 1; // 15 LPM mode + uint32_t dfifo_depth : 16; // DFIFO depth - EP_LOC_CNT in terms of 32-bit words + }; +} dwc2_ghwcfg3_t; TU_VERIFY_STATIC(sizeof(dwc2_ghwcfg3_t) == 4, "incorrect size"); -typedef struct TU_ATTR_PACKED { - uint32_t num_dev_period_in_ep : 4; // 0..3 Number of Device Periodic IN Endpoints - uint32_t partial_powerdown : 1; // 4 Partial Power Down Enabled - uint32_t ahb_freq_min : 1; // 5 1: minimum of AHB frequency is less than 60 MHz - uint32_t hibernation : 1; // 6 Hibernation feature is enabled - uint32_t extended_hibernation : 1; // 7 Extended Hibernation feature is enabled - uint32_t reserved8 : 1; // 8 Reserved - uint32_t enhanced_lpm_support1 : 1; // 9 Enhanced LPM Support1 - uint32_t service_interval_flow : 1; // 10 Service Interval flow is supported - uint32_t ipg_isoc_support : 1; // 11 Interpacket GAP ISO OUT worst-case is supported - uint32_t acg_support : 1; // 12 Active clock gating is supported - uint32_t enhanced_lpm_support : 1; // 13 Enhanced LPM Support - uint32_t phy_data_width : 2; // 14..15 0: 8 bits | 1: 16 bits | 2: 8/16 software selectable - uint32_t ctrl_ep_num : 4; // 16..19 Number of Device control endpoints in addition to EP0 - uint32_t iddg_filter : 1; // 20 IDDG Filter Enabled - uint32_t vbus_valid_filter : 1; // 21 VBUS Valid Filter Enabled - uint32_t a_valid_filter : 1; // 22 A Valid Filter Enabled - uint32_t b_valid_filter : 1; // 23 B Valid Filter Enabled - uint32_t session_end_filter : 1; // 24 Session End Filter Enabled - uint32_t dedicated_fifos : 1; // 25 Dedicated tx fifo for device IN Endpoint - uint32_t num_dev_in_eps : 4; // 26..29 Number of Device IN Endpoints including EP0 - uint32_t dma_desc_enabled : 1; // scatter/gather DMA configuration enabled - uint32_t dma_desc_dynamic : 1; // Dynamic scatter/gather DMA -}dwc2_ghwcfg4_t; +typedef union { + uint32_t value; + struct TU_ATTR_PACKED { + uint32_t num_dev_period_in_ep : 4; // 0..3 Number of Device Periodic IN Endpoints + uint32_t partial_powerdown : 1; // 4 Partial Power Down Enabled + uint32_t ahb_freq_min : 1; // 5 1: minimum of AHB frequency is less than 60 MHz + uint32_t hibernation : 1; // 6 Hibernation feature is enabled + uint32_t extended_hibernation : 1; // 7 Extended Hibernation feature is enabled + uint32_t reserved8 : 1; // 8 Reserved + uint32_t enhanced_lpm_support1 : 1; // 9 Enhanced LPM Support1 + uint32_t service_interval_flow : 1; // 10 Service Interval flow is supported + uint32_t ipg_isoc_support : 1; // 11 Interpacket GAP ISO OUT worst-case is supported + uint32_t acg_support : 1; // 12 Active clock gating is supported + uint32_t enhanced_lpm_support : 1; // 13 Enhanced LPM Support + uint32_t phy_data_width : 2; // 14..15 0: 8 bits | 1: 16 bits | 2: 8/16 software selectable + uint32_t ctrl_ep_num : 4; // 16..19 Number of Device control endpoints in addition to EP0 + uint32_t iddg_filter : 1; // 20 IDDG Filter Enabled + uint32_t vbus_valid_filter : 1; // 21 VBUS Valid Filter Enabled + uint32_t a_valid_filter : 1; // 22 A Valid Filter Enabled + uint32_t b_valid_filter : 1; // 23 B Valid Filter Enabled + uint32_t session_end_filter : 1; // 24 Session End Filter Enabled + uint32_t dedicated_fifos : 1; // 25 Dedicated tx fifo for device IN Endpoint + uint32_t num_dev_in_eps : 4; // 26..29 Number of Device IN Endpoints including EP0 + uint32_t dma_desc_enabled : 1; // scatter/gather DMA configuration enabled + uint32_t dma_desc_dynamic : 1; // Dynamic scatter/gather DMA + }; +} dwc2_ghwcfg4_t; TU_VERIFY_STATIC(sizeof(dwc2_ghwcfg4_t) == 4, "incorrect size"); -//-------------------------------------------------------------------- -// Host Register Bitfield -//-------------------------------------------------------------------- - -typedef struct TU_ATTR_PACKED { - uint32_t fifo_available : 16; // 0..15 Number of words available in the Tx FIFO - uint32_t req_queue_available : 8; // 16..23 Number of spaces available in the NPT transmit request queue for both IN and OU - // 24..31 is top entry in the request queue that is currently being processed by the MAC - uint32_t qtop_terminate : 1; // 24 Last entry for selected channel - uint32_t qtop_type : 2; // 25..26 Token (0) In/Out (1) ZLP, (2) Ping/cspit, (3) Channel halt command - uint32_t qtop_ch_num : 4; // 27..30 Channel number +typedef union { + uint32_t value; + struct TU_ATTR_PACKED { + uint32_t fifo_available : 16; // 0..15 Number of words available in the Tx FIFO + uint32_t req_queue_available : 8; // 16..23 Number of spaces available in the NPT transmit request queue for both IN and OU + // 24..31 is top entry in the request queue that is currently being processed by the MAC + uint32_t qtop_terminate : 1; // 24 Last entry for selected channel + uint32_t qtop_type : 2; // 25..26 Token (0) In/Out (1) ZLP, (2) Ping/cspit, (3) Channel halt command + uint32_t qtop_ch_num : 4; // 27..30 Channel number + }; } dwc2_hnptxsts_t; TU_VERIFY_STATIC(sizeof(dwc2_hnptxsts_t) == 4, "incorrect size"); -typedef struct TU_ATTR_PACKED { - uint32_t fifo_available : 16; // 0..15 Number of words available in the Tx FIFO - uint32_t req_queue_available : 7; // 16..22 Number of spaces available in the PTX transmit request queue - uint32_t qtop_terminate : 1; // 23 Last entry for selected channel - uint32_t qtop_last_period : 1; // 24 Last entry for selected channel is a periodic entry - uint32_t qtop_type : 2; // 25..26 Token (0) In/Out (1) ZLP, (2) Ping/cspit, (3) Channel halt command - uint32_t qtop_ch_num : 4; // 27..30 Channel number - uint32_t qtop_odd_frame : 1; // 31 Send in odd frame +typedef union { + uint32_t value; + struct TU_ATTR_PACKED { + uint32_t fifo_available :16; // 0..15 Number of words available in the Tx FIFO + uint32_t req_queue_available : 7; // 16..22 Number of spaces available in the PTX transmit request queue + uint32_t qtop_terminate : 1; // 23 Last entry for selected channel + uint32_t qtop_last_period : 1; // 24 Last entry for selected channel is a periodic entry + uint32_t qtop_type : 2; // 25..26 Token (0) In/Out (1) ZLP, (2) Ping/cspit, (3) Channel halt command + uint32_t qtop_ch_num : 4; // 27..30 Channel number + uint32_t qtop_odd_frame : 1; // 31 Send in odd frame + }; } dwc2_hptxsts_t; TU_VERIFY_STATIC(sizeof(dwc2_hptxsts_t) == 4, "incorrect size"); -typedef struct TU_ATTR_PACKED { - uint32_t conn_status : 1; // 0 Port connect status - uint32_t conn_detected : 1; // 1 Port connect detected - uint32_t enable : 1; // 2 Port enable status - uint32_t enable_change : 1; // 3 Port enable change - uint32_t over_current_active : 1; // 4 Port Over-current active - uint32_t over_current_change : 1; // 5 Port Over-current change - uint32_t resume : 1; // 6 Port resume - uint32_t suspend : 1; // 7 Port suspend - uint32_t reset : 1; // 8 Port reset - uint32_t rsv9 : 1; // 9 Reserved - uint32_t line_status : 2; // 10..11 Line status - uint32_t power : 1; // 12 Port power - uint32_t test_control : 4; // 13..16 Port Test control - uint32_t speed : 2; // 17..18 Port speed - uint32_t rsv19_31 :13; // 19..31 Reserved -}dwc2_hprt_t; +typedef union { + uint32_t value; + struct TU_ATTR_PACKED { + uint32_t conn_status : 1; // 0 Port connect status + uint32_t conn_detected : 1; // 1 Port connect detected + uint32_t enable : 1; // 2 Port enable status + uint32_t enable_change : 1; // 3 Port enable change + uint32_t over_current_active : 1; // 4 Port Over-current active + uint32_t over_current_change : 1; // 5 Port Over-current change + uint32_t resume : 1; // 6 Port resume + uint32_t suspend : 1; // 7 Port suspend + uint32_t reset : 1; // 8 Port reset + uint32_t rsv9 : 1; // 9 Reserved + uint32_t line_status : 2; // 10..11 Line status + uint32_t power : 1; // 12 Port power + uint32_t test_control : 4; // 13..16 Port Test control + uint32_t speed : 2; // 17..18 Port speed + uint32_t rsv19_31 :13; // 19..31 Reserved + }; +} dwc2_hprt_t; TU_VERIFY_STATIC(sizeof(dwc2_hprt_t) == 4, "incorrect size"); -typedef struct TU_ATTR_PACKED { - uint32_t ep_size : 11; // 0..10 Maximum packet size - uint32_t ep_num : 4; // 11..14 Endpoint number - uint32_t ep_dir : 1; // 15 Endpoint direction - uint32_t rsv16 : 1; // 16 Reserved - uint32_t low_speed_dev : 1; // 17 Low-speed device - uint32_t ep_type : 2; // 18..19 Endpoint type - uint32_t err_multi_count : 2; // 20..21 Error (splitEn = 1) / Multi (SplitEn = 0) count - uint32_t dev_addr : 7; // 22..28 Device address - uint32_t odd_frame : 1; // 29 Odd frame - uint32_t disable : 1; // 30 Channel disable - uint32_t enable : 1; // 31 Channel enable +typedef union { + uint32_t value; + struct TU_ATTR_PACKED { + uint32_t ep_size : 11; // 0..10 Maximum packet size + uint32_t ep_num : 4; // 11..14 Endpoint number + uint32_t ep_dir : 1; // 15 Endpoint direction + uint32_t rsv16 : 1; // 16 Reserved + uint32_t low_speed_dev : 1; // 17 Low-speed device + uint32_t ep_type : 2; // 18..19 Endpoint type + uint32_t err_multi_count : 2; // 20..21 Error (splitEn = 1) / Multi (SplitEn = 0) count + uint32_t dev_addr : 7; // 22..28 Device address + uint32_t odd_frame : 1; // 29 Odd frame + uint32_t disable : 1; // 30 Channel disable + uint32_t enable : 1; // 31 Channel enable + }; } dwc2_channel_char_t; TU_VERIFY_STATIC(sizeof(dwc2_channel_char_t) == 4, "incorrect size"); -typedef struct TU_ATTR_PACKED { - uint32_t hub_port : 7; // 0..6 Hub port number - uint32_t hub_addr : 7; // 7..13 Hub address - uint32_t xact_pos : 2; // 14..15 Transaction position - uint32_t split_compl : 1; // 16 Split completion - uint32_t rsv17_30 : 14; // 17..30 Reserved - uint32_t split_en : 1; // 31 Split enable +typedef union { + uint32_t value; + struct TU_ATTR_PACKED { + uint32_t hub_port : 7; // 0..6 Hub port number + uint32_t hub_addr : 7; // 7..13 Hub address + uint32_t xact_pos : 2; // 14..15 Transaction position + uint32_t split_compl : 1; // 16 Split completion + uint32_t rsv17_30 : 14; // 17..30 Reserved + uint32_t split_en : 1; // 31 Split enable + }; } dwc2_channel_split_t; TU_VERIFY_STATIC(sizeof(dwc2_channel_split_t) == 4, "incorrect size"); -typedef struct TU_ATTR_PACKED { - uint32_t xfer_size : 19; // 0..18 Transfer size in bytes - uint32_t packet_count : 10; // 19..28 Number of packets - uint32_t pid : 2; // 29..30 Packet ID - uint32_t do_ping : 1; // 31 Do PING +typedef union { + uint32_t value; + struct TU_ATTR_PACKED { + uint32_t xfer_size : 19; // 0..18 Transfer size in bytes + uint32_t packet_count : 10; // 19..28 Number of packets + uint32_t pid : 2; // 29..30 Packet ID + uint32_t do_ping : 1; // 31 Do PING + }; } dwc2_channel_tsize_t; TU_VERIFY_STATIC(sizeof(dwc2_channel_tsize_t) == 4, "incorrect size"); -typedef struct TU_ATTR_PACKED { - uint32_t num : 16; // 0..15 Frame number - uint32_t remainning : 16; // 16..31 Frame remaining +typedef union { + uint32_t value; + struct TU_ATTR_PACKED { + uint32_t num : 16; // 0..15 Frame number + uint32_t remainning : 16; // 16..31 Frame remaining + }; } dwc2_hfnum_t; TU_VERIFY_STATIC(sizeof(dwc2_hfnum_t) == 4, "incorrect size"); // Host Channel typedef struct { - union { - volatile uint32_t hcchar; // 500 + 20*ch Host Channel Characteristics - volatile dwc2_channel_char_t hcchar_bm; - }; - union { - volatile uint32_t hcsplt; // 504 + 20*ch Host Channel Split Control - volatile dwc2_channel_split_t hcsplt_bm; - }; - volatile uint32_t hcint; // 508 + 20*ch Host Channel Interrupt - volatile uint32_t hcintmsk; // 50C + 20*ch Host Channel Interrupt Mask - union { - volatile uint32_t hctsiz; // 510 + 20*ch Host Channel Transfer Size - volatile dwc2_channel_tsize_t hctsiz_bm; - }; - volatile uint32_t hcdma; // 514 + 20*ch Host Channel DMA Address - uint32_t reserved518; // 518 + 20*ch - volatile uint32_t hcdmab; // 51C + 20*ch Host Channel DMA Address + volatile uint32_t hcchar; // 500 + 20*ch Host Channel Characteristics + volatile uint32_t hcsplt; // 504 + 20*ch Host Channel Split Control + volatile uint32_t hcint; // 508 + 20*ch Host Channel Interrupt + volatile uint32_t hcintmsk; // 50C + 20*ch Host Channel Interrupt Mask + volatile uint32_t hctsiz; // 510 + 20*ch Host Channel Transfer Size + volatile uint32_t hcdma; // 514 + 20*ch Host Channel DMA Address + uint32_t reserved518; // 518 + 20*ch + volatile uint32_t hcdmab; // 51C + 20*ch Host Channel DMA Address } dwc2_channel_t; //-------------------------------------------------------------------- // Device Register Bitfield //-------------------------------------------------------------------- -typedef struct TU_ATTR_PACKED { - uint32_t speed : 2; // 0..1 Speed - uint32_t nzsts_out_handshake : 1; // 2 Non-zero-length status OUT handshake - uint32_t en_32khz_suspsend : 1; // 3 Enable 32-kHz SUSPEND mode - uint32_t address : 7; // 4..10 Device address - uint32_t period_frame_interval : 2; // 11..12 Periodic frame interval - uint32_t en_out_nak : 1; // 13 Enable Device OUT NAK - uint32_t xcvr_delay : 1; // 14 Transceiver delay - uint32_t erratic_int_mask : 1; // 15 Erratic interrupt mask - uint32_t rsv16 : 1; // 16 Reserved - uint32_t ipg_iso_support : 1; // 17 Interpacket gap ISO support - uint32_t epin_mismatch_count : 5; // 18..22 EP IN mismatch count - uint32_t dma_desc : 1; // 23 Enable scatter/gatter DMA descriptor - uint32_t period_schedule_interval : 2; // 24..25 Periodic schedule interval for scatter/gatter DMA - uint32_t resume_valid : 6; // 26..31 Resume valid period +typedef union { + uint32_t value; + struct TU_ATTR_PACKED { + uint32_t speed : 2; // 0..1 Speed + uint32_t nzsts_out_handshake : 1; // 2 Non-zero-length status OUT handshake + uint32_t en_32khz_suspsend : 1; // 3 Enable 32-kHz SUSPEND mode + uint32_t address : 7; // 4..10 Device address + uint32_t period_frame_interval : 2; // 11..12 Periodic frame interval + uint32_t en_out_nak : 1; // 13 Enable Device OUT NAK + uint32_t xcvr_delay : 1; // 14 Transceiver delay + uint32_t erratic_int_mask : 1; // 15 Erratic interrupt mask + uint32_t rsv16 : 1; // 16 Reserved + uint32_t ipg_iso_support : 1; // 17 Interpacket gap ISO support + uint32_t epin_mismatch_count : 5; // 18..22 EP IN mismatch count + uint32_t dma_desc : 1; // 23 Enable scatter/gather DMA descriptor + uint32_t period_schedule_interval : 2; // 24..25 Periodic schedule interval for scatter/gather DMA + uint32_t resume_valid : 6; // 26..31 Resume valid period + }; } dwc2_dcfg_t; TU_VERIFY_STATIC(sizeof(dwc2_dcfg_t) == 4, "incorrect size"); -typedef struct TU_ATTR_PACKED { - uint32_t remote_wakeup_signal : 1; // 0 Remote wakeup signal - uint32_t soft_disconnet : 1; // 1 Soft disconnect - uint32_t gnp_in_nak_status : 1; // 2 Global non-periodic NAK IN status - uint32_t gout_nak_status : 1; // 3 Global OUT NAK status - uint32_t test_control : 3; // 4..6 Test control - uint32_t set_gnp_in_nak : 1; // 7 Set global non-periodic IN NAK - uint32_t clear_gnp_in_nak : 1; // 8 Clear global non-periodic IN NAK - uint32_t set_gout_nak : 1; // 9 Set global OUT NAK - uint32_t clear_gout_nak : 1; // 10 Clear global OUT NAK - uint32_t poweron_prog_done : 1; // 11 Power-on programming done - uint32_t rsv12 : 1; // 12 Reserved - uint32_t global_multi_count : 2; // 13..14 Global multi-count - uint32_t ignore_frame_number : 1; // 15 Ignore frame number - uint32_t nak_on_babble : 1; // 16 NAK on babble - uint32_t en_cont_on_bna : 1; // 17 Enable continue on BNA - uint32_t deep_sleep_besl_reject : 1; // 18 Deep sleep BESL reject - uint32_t service_interval : 1; // 19 Service interval for ISO IN endpoint - uint32_t rsv20_31 :12; // 20..31 Reserved +typedef union { + uint32_t value; + struct TU_ATTR_PACKED { + uint32_t remote_wakeup_signal : 1; // 0 Remote wakeup signal + uint32_t soft_disconnet : 1; // 1 Soft disconnect + uint32_t gnp_in_nak_status : 1; // 2 Global non-periodic NAK IN status + uint32_t gout_nak_status : 1; // 3 Global OUT NAK status + uint32_t test_control : 3; // 4..6 Test control + uint32_t set_gnp_in_nak : 1; // 7 Set global non-periodic IN NAK + uint32_t clear_gnp_in_nak : 1; // 8 Clear global non-periodic IN NAK + uint32_t set_gout_nak : 1; // 9 Set global OUT NAK + uint32_t clear_gout_nak : 1; // 10 Clear global OUT NAK + uint32_t poweron_prog_done : 1; // 11 Power-on programming done + uint32_t rsv12 : 1; // 12 Reserved + uint32_t global_multi_count : 2; // 13..14 Global multi-count + uint32_t ignore_frame_number : 1; // 15 Ignore frame number + uint32_t nak_on_babble : 1; // 16 NAK on babble + uint32_t en_cont_on_bna : 1; // 17 Enable continue on BNA + uint32_t deep_sleep_besl_reject : 1; // 18 Deep sleep BESL reject + uint32_t service_interval : 1; // 19 Service interval for ISO IN endpoint + uint32_t rsv20_31 :12; // 20..31 Reserved + }; } dwc2_dctl_t; TU_VERIFY_STATIC(sizeof(dwc2_dctl_t) == 4, "incorrect size"); -typedef struct TU_ATTR_PACKED { - uint32_t suspend_status : 1; // 0 Suspend status - uint32_t enum_speed : 2; // 1..2 Enumerated speed - uint32_t erratic_err : 1; // 3 Erratic error - uint32_t rsv4_7 : 4; // 4..7 Reserved - uint32_t frame_number : 14; // 8..21 Frame/MicroFrame number - uint32_t line_status : 2; // 22..23 Line status - uint32_t rsv24_31 : 8; // 24..31 Reserved +typedef union { + uint32_t value; + struct TU_ATTR_PACKED { + uint32_t suspend_status : 1; // 0 Suspend status + uint32_t enum_speed : 2; // 1..2 Enumerated speed + uint32_t erratic_err : 1; // 3 Erratic error + uint32_t rsv4_7 : 4; // 4..7 Reserved + uint32_t frame_number :14; // 8..21 Frame/MicroFrame number + uint32_t line_status : 2; // 22..23 Line status + uint32_t rsv24_31 : 8; // 24..31 Reserved + }; } dwc2_dsts_t; TU_VERIFY_STATIC(sizeof(dwc2_dsts_t) == 4, "incorrect size"); -typedef struct TU_ATTR_PACKED { - uint32_t xfer_complete : 1; // 0 Transfer complete - uint32_t disabled : 1; // 1 Endpoint disabled - uint32_t ahb_err : 1; // 2 AHB error - uint32_t timeout : 1; // 3 Timeout - uint32_t in_rx_txfe : 1; // 4 IN token received when TxFIFO is empty - uint32_t in_rx_ep_mismatch : 1; // 5 IN token received with EP mismatch - uint32_t in_ep_nak_effective : 1; // 6 IN endpoint NAK effective - uint32_t txfifo_empty : 1; // 7 TX FIFO empty - uint32_t txfifo_underrun : 1; // 8 Tx FIFO under run - uint32_t bna : 1; // 9 Buffer not available - uint32_t rsv10 : 1; // 10 Reserved - uint32_t iso_packet_drop : 1; // 11 Isochronous OUT packet drop status - uint32_t babble_err : 1; // 12 Babble error - uint32_t nak : 1; // 13 NAK - uint32_t nyet : 1; // 14 NYET - uint32_t rsv14_31 :17; // 15..31 Reserved +typedef union { + uint32_t value; + struct TU_ATTR_PACKED { + uint32_t xfer_complete : 1; // 0 Transfer complete + uint32_t disabled : 1; // 1 Endpoint disabled + uint32_t ahb_err : 1; // 2 AHB error + uint32_t timeout : 1; // 3 Timeout + uint32_t in_rx_txfe : 1; // 4 IN token received when TxFIFO is empty + uint32_t in_rx_ep_mismatch : 1; // 5 IN token received with EP mismatch + uint32_t in_ep_nak_effective : 1; // 6 IN endpoint NAK effective + uint32_t txfifo_empty : 1; // 7 TX FIFO empty + uint32_t txfifo_underrun : 1; // 8 Tx FIFO under run + uint32_t bna : 1; // 9 Buffer not available + uint32_t rsv10 : 1; // 10 Reserved + uint32_t iso_packet_drop : 1; // 11 Isochronous OUT packet drop status + uint32_t babble_err : 1; // 12 Babble error + uint32_t nak : 1; // 13 NAK + uint32_t nyet : 1; // 14 NYET + uint32_t rsv14_31 :17; // 15..31 Reserved + }; } dwc2_diepint_t; TU_VERIFY_STATIC(sizeof(dwc2_diepint_t) == 4, "incorrect size"); -typedef struct TU_ATTR_PACKED { - uint32_t mps : 11; // 0..10 Maximum packet size, EP0 only use 2 bit - uint32_t next_ep : 4; // 11..14 Next endpoint number - uint32_t active : 1; // 15 Active - const uint32_t dpid_iso_odd : 1; // 16 DATA0/DATA1 for bulk/interrupt, odd frame for isochronous - const uint32_t nak_status : 1; // 17 NAK status - uint32_t type : 2; // 18..19 Endpoint type - uint32_t rsv20 : 1; // 20 Reserved - uint32_t stall : 1; // 21 Stall - uint32_t tx_fifo_num : 4; // 22..25 Tx FIFO number (IN) - uint32_t clear_nak : 1; // 26 Clear NAK - uint32_t set_nak : 1; // 27 Set NAK - uint32_t set_data0_iso_even : 1; // 28 Set DATA0 if bulk/interrupt, even frame for isochronous - uint32_t set_data1_iso_odd : 1; // 29 Set DATA1 if bulk/interrupt, odd frame for isochronous - uint32_t disable : 1; // 30 Disable - uint32_t enable : 1; // 31 Enable +typedef union { + uint32_t value; + struct TU_ATTR_PACKED { + uint32_t mps : 11; // 0..10 Maximum packet size, EP0 only use 2 bits + uint32_t next_ep : 4; // 11..14 Next endpoint number + uint32_t active : 1; // 15 Active + uint32_t dpid_iso_odd : 1; // 16 DATA0/DATA1 for bulk/interrupt, odd frame for isochronous + uint32_t nak_status : 1; // 17 NAK status + uint32_t type : 2; // 18..19 Endpoint type + uint32_t rsv20 : 1; // 20 Reserved + uint32_t stall : 1; // 21 Stall + uint32_t tx_fifo_num : 4; // 22..25 Tx FIFO number (IN) + uint32_t clear_nak : 1; // 26 Clear NAK + uint32_t set_nak : 1; // 27 Set NAK + uint32_t set_data0_iso_even : 1; // 28 Set DATA0 if bulk/interrupt, even frame for isochronous + uint32_t set_data1_iso_odd : 1; // 29 Set DATA1 if bulk/interrupt, odd frame for isochronous + uint32_t disable : 1; // 30 Disable + uint32_t enable : 1; // 31 Enable + }; } dwc2_depctl_t; TU_VERIFY_STATIC(sizeof(dwc2_depctl_t) == 4, "incorrect size"); -typedef struct TU_ATTR_PACKED { - uint32_t xfer_complete : 1; // 0 Transfer complete - uint32_t disabled : 1; // 1 Endpoint disabled - uint32_t ahb_err : 1; // 2 AHB error - uint32_t setup_phase_done : 1; // 3 Setup phase done - uint32_t out_rx_ep_disabled : 1; // 4 OUT token received when endpoint disabled - uint32_t status_phase_rx : 1; // 5 Status phase received - uint32_t setup_b2b : 1; // 6 Setup packet back-to-back - uint32_t rsv7 : 1; // 7 Reserved - uint32_t out_packet_err : 1; // 8 OUT packet error - uint32_t bna : 1; // 9 Buffer not available - uint32_t rsv10 : 1; // 10 Reserved - uint32_t iso_packet_drop : 1; // 11 Isochronous OUT packet drop status - uint32_t babble_err : 1; // 12 Babble error - uint32_t nak : 1; // 13 NAK - uint32_t nyet : 1; // 14 NYET - uint32_t setup_packet_rx : 1; // 15 Setup packet received (Buffer DMA Mode only) - uint32_t rsv16_31 :16; // 16..31 Reserved +typedef union { + uint32_t value; + struct TU_ATTR_PACKED { + uint32_t xfer_complete : 1; // 0 Transfer complete + uint32_t disabled : 1; // 1 Endpoint disabled + uint32_t ahb_err : 1; // 2 AHB error + uint32_t setup_phase_done : 1; // 3 Setup phase done + uint32_t out_rx_ep_disabled : 1; // 4 OUT token received when endpoint disabled + uint32_t status_phase_rx : 1; // 5 Status phase received + uint32_t setup_b2b : 1; // 6 Setup packet back-to-back + uint32_t rsv7 : 1; // 7 Reserved + uint32_t out_packet_err : 1; // 8 OUT packet error + uint32_t bna : 1; // 9 Buffer not available + uint32_t rsv10 : 1; // 10 Reserved + uint32_t iso_packet_drop : 1; // 11 Isochronous OUT packet drop status + uint32_t babble_err : 1; // 12 Babble error + uint32_t nak : 1; // 13 NAK + uint32_t nyet : 1; // 14 NYET + uint32_t setup_packet_rx : 1; // 15 Setup packet received (Buffer DMA Mode only) + uint32_t rsv16_31 :16; // 16..31 Reserved + }; } dwc2_doepint_t; TU_VERIFY_STATIC(sizeof(dwc2_doepint_t) == 4, "incorrect size"); -typedef struct TU_ATTR_PACKED { - uint32_t xfer_size : 19; // 0..18 Transfer size in bytes - uint32_t packet_count : 10; // 19..28 Number of packets - uint32_t mc_pid : 2; // 29..30 IN: Multi Count, OUT: PID +typedef union { + uint32_t value; + struct TU_ATTR_PACKED { + uint32_t xfer_size : 19; // 0..18 Transfer size in bytes + uint32_t packet_count : 10; // 19..28 Number of packets + uint32_t mc_pid : 2; // 29..30 IN: Multi Count, OUT: PID + }; } dwc2_ep_tsize_t; TU_VERIFY_STATIC(sizeof(dwc2_ep_tsize_t) == 4, "incorrect size"); @@ -601,26 +656,19 @@ typedef struct { union { volatile uint32_t diepctl; volatile uint32_t doepctl; - volatile uint32_t ctl; - volatile dwc2_depctl_t ctl_bm; }; uint32_t rsv04; union { volatile uint32_t intr; - volatile uint32_t diepint; - volatile dwc2_diepint_t diepint_bm; - volatile uint32_t doepint; - volatile dwc2_doepint_t doepint_bm; }; uint32_t rsv0c; union { volatile uint32_t dieptsiz; volatile uint32_t doeptsiz; volatile uint32_t tsiz; - volatile dwc2_ep_tsize_t tsiz_bm; }; union { volatile uint32_t diepdma; @@ -628,7 +676,7 @@ typedef struct { }; volatile uint32_t dtxfsts; uint32_t rsv1c; -}dwc2_dep_t; +} dwc2_dep_t; TU_VERIFY_STATIC(sizeof(dwc2_dep_t) == 0x20, "incorrect size"); @@ -636,157 +684,108 @@ TU_VERIFY_STATIC(sizeof(dwc2_dep_t) == 0x20, "incorrect size"); // CSR Register Map //-------------------------------------------------------------------- typedef struct { - //------------- Core Global -------------// - union { - volatile uint32_t gotgctl; // 000 OTG Control and Status - volatile dwc2_gotgctl_t gotgctl_bm; - }; - union { - volatile uint32_t gotgint; // 004 OTG Interrupt - volatile dwc2_gotgint_t gotgint_bm; - }; - union { - volatile uint32_t gahbcfg; // 008 AHB Configuration - volatile dwc2_gahbcfg_t gahbcfg_bm; - }; - union { - volatile uint32_t gusbcfg; // 00c USB Configuration - volatile dwc2_gusbcfg_t gusbcfg_bm; - }; - union { - volatile uint32_t grstctl; // 010 Reset - volatile dwc2_grstctl_t grstctl_bm; - }; - volatile uint32_t gintsts; // 014 Interrupt - volatile uint32_t gintmsk; // 018 Interrupt Mask - volatile uint32_t grxstsr; // 01c Receive Status Debug Read - union { - volatile uint32_t grxstsp; // 020 Receive Status Read/Pop - volatile dwc2_grxstsp_t grxstsp_bm; - }; - volatile uint32_t grxfsiz; // 024 Receive FIFO Size + //------------- Core Global ------------- + volatile uint32_t gotgctl; // 000 OTG Control and Status + volatile uint32_t gotgint; // 004 OTG Interrupt + volatile uint32_t gahbcfg; // 008 AHB Configuration + volatile uint32_t gusbcfg; // 00c USB Configuration + volatile uint32_t grstctl; // 010 Reset + volatile uint32_t gintsts; // 014 Interrupt + volatile uint32_t gintmsk; // 018 Interrupt Mask + volatile uint32_t grxstsr; // 01c Receive Status Debug Read + volatile uint32_t grxstsp; // 020 Receive Status Read/Pop + volatile uint32_t grxfsiz; // 024 Receive FIFO Size union { volatile uint32_t dieptxf0; // 028 EP0 Tx FIFO Size volatile uint32_t gnptxfsiz; // 028 Non-periodic Transmit FIFO Size }; union { volatile uint32_t hnptxsts; // 02c Non-periodic Transmit FIFO/Queue Status - volatile dwc2_hnptxsts_t hnptxsts_bm; volatile uint32_t gnptxsts; }; - volatile uint32_t gi2cctl; // 030 I2C Address - volatile uint32_t gpvndctl; // 034 PHY Vendor Control + volatile uint32_t gi2cctl; // 030 I2C Address + volatile uint32_t gpvndctl; // 034 PHY Vendor Control union { volatile uint32_t ggpio; // 038 General Purpose IO volatile uint32_t stm32_gccfg; // 038 STM32 General Core Configuration }; - volatile uint32_t guid; // 03C User (Application programmable) ID - volatile uint32_t gsnpsid; // 040 Synopsys ID + Release version - volatile uint32_t ghwcfg1; // 044 User Hardware Configuration1: endpoint dir (2 bit per ep) - union { - volatile uint32_t ghwcfg2; // 048 User Hardware Configuration2 - volatile dwc2_ghwcfg2_t ghwcfg2_bm; - }; - union { - volatile uint32_t ghwcfg3; // 04C User Hardware Configuration3 - volatile dwc2_ghwcfg3_t ghwcfg3_bm; - }; + volatile uint32_t guid; // 03C User (Application programmable) ID + volatile uint32_t gsnpsid; // 040 Synopsys ID + Release version + volatile uint32_t ghwcfg1; // 044 User Hardware Configuration1: endpoint dir (2 bit per ep) + volatile uint32_t ghwcfg2; // 048 User Hardware Configuration2 + volatile uint32_t ghwcfg3; // 04C User Hardware Configuration3 union { volatile uint32_t ghwcfg4; // 050 User Hardware Configuration4 volatile dwc2_ghwcfg4_t ghwcfg4_bm; }; - volatile uint32_t glpmcfg; // 054 Core LPM Configuration - volatile uint32_t gpwrdn; // 058 Power Down - volatile uint32_t gdfifocfg; // 05C DFIFO Software Configuration - volatile uint32_t gadpctl; // 060 ADP Timer, Control and Status - uint32_t reserved64[39]; // 064..0FF - volatile uint32_t hptxfsiz; // 100 Host Periodic Tx FIFO Size - volatile uint32_t dieptxf[15]; // 104..13C Device Periodic Transmit FIFO Size - uint32_t reserved140[176]; // 140..3FF + volatile uint32_t glpmcfg; // 054 Core LPM Configuration + volatile uint32_t gpwrdn; // 058 Power Down + volatile uint32_t gdfifocfg; // 05C DFIFO Software Configuration + volatile uint32_t gadpctl; // 060 ADP Timer, Control and Status + uint32_t reserved64[39]; // 064..0FF + volatile uint32_t hptxfsiz; // 100 Host Periodic Tx FIFO Size + volatile uint32_t dieptxf[15]; // 104..13C Device Periodic Transmit FIFO Size + uint32_t reserved140[176]; // 140..3FF - //------------ Host -------------// - volatile uint32_t hcfg; // 400 Host Configuration - volatile uint32_t hfir; // 404 Host Frame Interval - union { - volatile uint32_t hfnum; // 408 Host Frame Number / Frame Remaining - volatile dwc2_hfnum_t hfnum_bm; - }; - uint32_t reserved40c; // 40C - union { - volatile uint32_t hptxsts; // 410 Host Periodic TX FIFO / Queue Status - volatile dwc2_hptxsts_t hptxsts_bm; - }; - volatile uint32_t haint; // 414 Host All Channels Interrupt - volatile uint32_t haintmsk; // 418 Host All Channels Interrupt Mask - volatile uint32_t hflbaddr; // 41C Host Frame List Base Address - uint32_t reserved420[8]; // 420..43F - union { - volatile uint32_t hprt; // 440 Host Port Control and Status - volatile dwc2_hprt_t hprt_bm; - }; - uint32_t reserved444[47]; // 444..4FF + //------------ Host ------------- + volatile uint32_t hcfg; // 400 Host Configuration + volatile uint32_t hfir; // 404 Host Frame Interval + volatile uint32_t hfnum; // 408 Host Frame Number / Frame Remaining + uint32_t reserved40c; // 40C + volatile uint32_t hptxsts; // 410 Host Periodic TX FIFO / Queue Status + volatile uint32_t haint; // 414 Host All Channels Interrupt + volatile uint32_t haintmsk; // 418 Host All Channels Interrupt Mask + volatile uint32_t hflbaddr; // 41C Host Frame List Base Address + uint32_t reserved420[8]; // 420..43F + volatile uint32_t hprt; // 440 Host Port Control and Status + uint32_t reserved444[47]; // 444..4FF - //------------- Host Channel -------------// - dwc2_channel_t channel[16]; // 500..6FF Host Channels 0-15 - uint32_t reserved700[64]; // 700..7FF + //------------- Host Channel -------- + dwc2_channel_t channel[16]; // 500..6FF Host Channels 0-15 + uint32_t reserved700[64]; // 700..7FF - //------------- Device -----------// - union { - volatile uint32_t dcfg; // 800 Device Configuration - volatile dwc2_dcfg_t dcfg_bm; - }; - union { - volatile uint32_t dctl; // 804 Device Control - volatile dwc2_dctl_t dctl_bm; - }; - union { - volatile uint32_t dsts; // 808 Device Status (RO) - volatile dwc2_dsts_t dsts_bm; - }; - uint32_t reserved80c; // 80C - union { - volatile uint32_t diepmsk; // 810 Device IN Endpoint Interrupt Mask - volatile dwc2_diepint_t diepmsk_bm; - }; - union { - volatile uint32_t doepmsk; // 814 Device OUT Endpoint Interrupt Mask - volatile dwc2_doepint_t doepmsk_bm; - }; - volatile uint32_t daint; // 818 Device All Endpoints Interrupt - volatile uint32_t daintmsk; // 81C Device All Endpoints Interrupt Mask - volatile uint32_t dtknqr1; // 820 Device IN token sequence learning queue read1 - volatile uint32_t dtknqr2; // 824 Device IN token sequence learning queue read2 - volatile uint32_t dvbusdis; // 828 Device VBUS Discharge Time - volatile uint32_t dvbuspulse; // 82C Device VBUS Pulsing Time - volatile uint32_t dthrctl; // 830 Device threshold Control - volatile uint32_t diepempmsk; // 834 Device IN Endpoint FIFO Empty Interrupt Mask + //------------- Device ----------- + volatile uint32_t dcfg; // 800 Device Configuration + volatile uint32_t dctl; // 804 Device Control + volatile uint32_t dsts; // 808 Device Status (RO) + uint32_t reserved80c; // 80C + volatile uint32_t diepmsk; // 810 Device IN Endpoint Interrupt Mask + volatile uint32_t doepmsk; // 814 Device OUT Endpoint Interrupt Mask + volatile uint32_t daint; // 818 Device All Endpoints Interrupt + volatile uint32_t daintmsk; // 81C Device All Endpoints Interrupt Mask + volatile uint32_t dtknqr1; // 820 Device IN token sequence learning queue read1 + volatile uint32_t dtknqr2; // 824 Device IN token sequence learning queue read2 + volatile uint32_t dvbusdis; // 828 Device VBUS Discharge Time + volatile uint32_t dvbuspulse; // 82C Device VBUS Pulsing Time + volatile uint32_t dthrctl; // 830 Device threshold Control + volatile uint32_t diepempmsk; // 834 Device IN Endpoint FIFO Empty Interrupt Mask - // Device Each Endpoint (IN/OUT) Interrupt/Mask for generating dedicated EP interrupt line - // require OTG_MULTI_PROC_INTRPT=1 - volatile uint32_t deachint; // 838 Device Each Endpoint Interrupt - volatile uint32_t deachmsk; // 83C Device Each Endpoint Interrupt mask - volatile uint32_t diepeachmsk[16]; // 840..87C Device Each IN Endpoint mask - volatile uint32_t doepeachmsk[16]; // 880..8BF Device Each OUT Endpoint mask - uint32_t reserved8c0[16]; // 8C0..8FF + // Device Each Endpoint (IN/OUT) Interrupt/Mask for generating dedicated EP interrupt line require + // OTG_MULTI_PROC_INTRPT=1 + volatile uint32_t deachint; // 838 Device Each Endpoint Interrupt + volatile uint32_t deachmsk; // 83C Device Each Endpoint Interrupt mask + volatile uint32_t diepeachmsk[16]; // 840..87C Device Each IN Endpoint mask + volatile uint32_t doepeachmsk[16]; // 880..8BF Device Each OUT Endpoint mask + uint32_t reserved8c0[16]; // 8C0..8FF - //------------- Device Endpoint -------------// - union { - dwc2_dep_t ep[2][16]; // 0: IN, 1 OUT - struct { - dwc2_dep_t epin[16]; // 900..AFF IN Endpoints - dwc2_dep_t epout[16]; // B00..CFF OUT Endpoints - }; + //------------- Device Endpoint ----- + union { + dwc2_dep_t ep[2][16]; // 0: IN, 1 OUT + struct { + dwc2_dep_t epin[16]; // 900..AFF IN Endpoints + dwc2_dep_t epout[16]; // B00..CFF OUT Endpoints }; - uint32_t reservedd00[64]; // D00..DFF + }; + uint32_t reservedd00[64]; // D00..DFF - //------------- Power Clock -------------// - volatile uint32_t pcgcctl; // E00 Power and Clock Gating Characteristic Control - volatile uint32_t pcgcctl1; // E04 Power and Clock Gating Characteristic Control 1 - uint32_t reservede08[126]; // E08..FFF + //------------- Power Clock --------- + volatile uint32_t pcgcctl; // E00 Power and Clock Gating Characteristic Control + volatile uint32_t pcgcctl1; // E04 Power and Clock Gating Characteristic Control 1 + uint32_t reservede08[126]; // E08..FFF - //------------- FIFOs -------------// - // Word-accessed only using first pointer since it auto shift - volatile uint32_t fifo[16][0x400]; // 1000..FFFF Endpoint FIFO + //------------- FIFOs ------------- + // Word-accessed only using first pointer since it auto shift + volatile uint32_t fifo[16][0x400]; // 1000..FFFF Endpoint FIFO } dwc2_regs_t; TU_VERIFY_STATIC(offsetof(dwc2_regs_t, hcfg ) == 0x0400, "incorrect size"); @@ -2089,9 +2088,9 @@ TU_VERIFY_STATIC(offsetof(dwc2_regs_t, fifo ) == 0x1000, "incorrect size"); #define HCTSIZ_DOPING_Pos (31U) #define HCTSIZ_DOPING_Msk (0x1UL << HCTSIZ_DOPING_Pos) // 0x80000000 #define HCTSIZ_DOPING HCTSIZ_DOPING_Msk // Do PING -#define HCTSIZ_PID_Pos (29U) -#define HCTSIZ_PID_Msk (0x3UL << HCTSIZ_PID_Pos) // 0x60000000 -#define HCTSIZ_PID HCTSIZ_PID_Msk // Data PID +#define HCTSIZ_PID_Pos (29U) +#define HCTSIZ_PID_Msk (0x3UL << HCTSIZ_PID_Pos) // 0x60000000 +#define HCTSIZ_PID HCTSIZ_PID_Msk // Data PID /******************** Bit definition for DIEPDMA register ********************/ #define DIEPDMA_DMAADDR_Pos (0U) diff --git a/src/portable/synopsys/dwc2/hcd_dwc2.c b/src/portable/synopsys/dwc2/hcd_dwc2.c index ebbb6200a..257fa2833 100644 --- a/src/portable/synopsys/dwc2/hcd_dwc2.c +++ b/src/portable/synopsys/dwc2/hcd_dwc2.c @@ -26,7 +26,7 @@ #include "tusb_option.h" -#if CFG_TUH_ENABLED && defined(TUP_USBIP_DWC2) +#if CFG_TUH_ENABLED && defined(TUP_USBIP_DWC2) && !CFG_TUH_MAX3421 #if !(CFG_TUH_DWC2_SLAVE_ENABLE || CFG_TUH_DWC2_DMA_ENABLE) #error DWC2 require either CFG_TUH_DWC2_SLAVE_ENABLE or CFG_TUH_DWC2_DMA_ENABLE to be enabled @@ -36,6 +36,7 @@ #define DWC2_DEBUG 2 #include "host/hcd.h" +#include "host/usbh.h" #include "dwc2_common.h" // Max number of endpoints application can open, can be larger than DWC2_CHANNEL_COUNT_MAX @@ -44,8 +45,6 @@ #endif #define DWC2_CHANNEL_COUNT_MAX 16 // absolute max channel count -#define DWC2_CHANNEL_COUNT(_dwc2) tu_min8((_dwc2)->ghwcfg2_bm.num_host_ch + 1, DWC2_CHANNEL_COUNT_MAX) - TU_VERIFY_STATIC(CFG_TUH_DWC2_ENDPOINT_MAX <= 255, "currently only use 8-bit for index"); enum { @@ -77,9 +76,9 @@ typedef struct { struct TU_ATTR_PACKED { uint32_t uframe_interval : 18; // micro-frame interval - uint32_t speed : 2; - uint32_t next_pid : 2; - uint32_t do_ping : 1; + uint32_t speed : 2; + uint32_t next_pid : 2; // PID for next transfer + uint32_t next_do_ping : 1; // Do PING for next transfer if possible (highspeed OUT) // uint32_t : 9; }; @@ -97,7 +96,6 @@ typedef struct { uint8_t err_count : 3; uint8_t period_split_nyet_count : 3; uint8_t halted_nyet : 1; - uint8_t halted_sof_schedule : 1; }; uint8_t result; @@ -116,9 +114,15 @@ hcd_data_t _hcd_data; //-------------------------------------------------------------------- // //-------------------------------------------------------------------- +TU_ATTR_ALWAYS_INLINE static inline uint8_t dwc2_channel_count(const dwc2_regs_t* dwc2) { + const dwc2_ghwcfg2_t ghwcfg2 = {.value = dwc2->ghwcfg2}; + return tu_min8(ghwcfg2.num_host_ch + 1, DWC2_CHANNEL_COUNT_MAX); +} + TU_ATTR_ALWAYS_INLINE static inline tusb_speed_t hprt_speed_get(dwc2_regs_t* dwc2) { tusb_speed_t speed; - switch(dwc2->hprt_bm.speed) { + const dwc2_hprt_t hprt = {.value = dwc2->hprt}; + switch(hprt.speed) { case HPRT_SPEED_HIGH: speed = TUSB_SPEED_HIGH; break; case HPRT_SPEED_FULL: speed = TUSB_SPEED_FULL; break; case HPRT_SPEED_LOW : speed = TUSB_SPEED_LOW ; break; @@ -133,7 +137,8 @@ TU_ATTR_ALWAYS_INLINE static inline tusb_speed_t hprt_speed_get(dwc2_regs_t* dwc TU_ATTR_ALWAYS_INLINE static inline bool dma_host_enabled(const dwc2_regs_t* dwc2) { (void) dwc2; // Internal DMA only - return CFG_TUH_DWC2_DMA_ENABLE && dwc2->ghwcfg2_bm.arch == GHWCFG2_ARCH_INTERNAL_DMA; + const dwc2_ghwcfg2_t ghwcfg2 = {.value = dwc2->ghwcfg2}; + return CFG_TUH_DWC2_DMA_ENABLE && ghwcfg2.arch == GHWCFG2_ARCH_INTERNAL_DMA; } #if CFG_TUH_MEM_DCACHE_ENABLE @@ -155,7 +160,7 @@ bool hcd_dcache_clean_invalidate(const void* addr, uint32_t data_size) { // Allocate a channel for new transfer TU_ATTR_ALWAYS_INLINE static inline uint8_t channel_alloc(dwc2_regs_t* dwc2) { - const uint8_t max_channel = DWC2_CHANNEL_COUNT(dwc2); + const uint8_t max_channel = dwc2_channel_count(dwc2); for (uint8_t ch_id = 0; ch_id < max_channel; ch_id++) { hcd_xfer_t* xfer = &_hcd_data.xfer[ch_id]; if (!xfer->allocated) { @@ -168,15 +173,18 @@ TU_ATTR_ALWAYS_INLINE static inline uint8_t channel_alloc(dwc2_regs_t* dwc2) { } // Check if is periodic (interrupt/isochronous) -TU_ATTR_ALWAYS_INLINE static inline bool edpt_is_periodic(uint8_t ep_type) { - return ep_type == HCCHAR_EPTYPE_INTERRUPT || ep_type == HCCHAR_EPTYPE_ISOCHRONOUS; +TU_ATTR_ALWAYS_INLINE static inline bool channel_is_periodic(uint32_t hcchar) { + const dwc2_channel_char_t hcchar_bm = {.value = hcchar}; + return hcchar_bm.ep_type == HCCHAR_EPTYPE_INTERRUPT || hcchar_bm.ep_type == HCCHAR_EPTYPE_ISOCHRONOUS; } TU_ATTR_ALWAYS_INLINE static inline uint8_t req_queue_avail(const dwc2_regs_t* dwc2, bool is_period) { if (is_period) { - return dwc2->hptxsts_bm.req_queue_available; + const dwc2_hptxsts_t hptxsts = {.value = dwc2->hptxsts}; + return hptxsts.req_queue_available; } else { - return dwc2->hnptxsts_bm.req_queue_available; + const dwc2_hnptxsts_t hnptxsts = {.value = dwc2->hnptxsts}; + return hnptxsts.req_queue_available; } } @@ -188,7 +196,7 @@ TU_ATTR_ALWAYS_INLINE static inline void channel_dealloc(dwc2_regs_t* dwc2, uint TU_ATTR_ALWAYS_INLINE static inline bool channel_disable(const dwc2_regs_t* dwc2, dwc2_channel_t* channel) { // disable also require request queue - TU_ASSERT(req_queue_avail(dwc2, edpt_is_periodic(channel->hcchar_bm.ep_type))); + TU_ASSERT(req_queue_avail(dwc2, channel_is_periodic(channel->hcchar))); channel->hcintmsk |= HCINT_HALTED; channel->hcchar |= HCCHAR_CHDIS | HCCHAR_CHENA; // must set both CHDIS and CHENA return true; @@ -196,18 +204,18 @@ TU_ATTR_ALWAYS_INLINE static inline bool channel_disable(const dwc2_regs_t* dwc2 // attempt to send IN token to receive data TU_ATTR_ALWAYS_INLINE static inline bool channel_send_in_token(const dwc2_regs_t* dwc2, dwc2_channel_t* channel) { - TU_ASSERT(req_queue_avail(dwc2, edpt_is_periodic(channel->hcchar_bm.ep_type))); + TU_ASSERT(req_queue_avail(dwc2, channel_is_periodic(channel->hcchar))); channel->hcchar |= HCCHAR_CHENA; return true; } // Find currently enabled channel. Note: EP0 is bidirectional TU_ATTR_ALWAYS_INLINE static inline uint8_t channel_find_enabled(dwc2_regs_t* dwc2, uint8_t dev_addr, uint8_t ep_num, uint8_t ep_dir) { - const uint8_t max_channel = DWC2_CHANNEL_COUNT(dwc2); + const uint8_t max_channel = dwc2_channel_count(dwc2); for (uint8_t ch_id = 0; ch_id < max_channel; ch_id++) { if (_hcd_data.xfer[ch_id].allocated) { - const dwc2_channel_char_t hcchar_bm = dwc2->channel[ch_id].hcchar_bm; - if (hcchar_bm.dev_addr == dev_addr && hcchar_bm.ep_num == ep_num && (ep_num == 0 || hcchar_bm.ep_dir == ep_dir)) { + const dwc2_channel_char_t hcchar = {.value = dwc2->channel[ch_id].hcchar}; + if (hcchar.dev_addr == dev_addr && hcchar.ep_num == ep_num && (ep_num == 0 || hcchar.ep_dir == ep_dir)) { return ch_id; } } @@ -304,12 +312,13 @@ TU_ATTR_ALWAYS_INLINE static inline uint8_t cal_next_pid(uint8_t pid, uint8_t pa static void dfifo_host_init(uint8_t rhport) { const dwc2_controller_t* dwc2_controller = &_dwc2_controller[rhport]; dwc2_regs_t* dwc2 = DWC2_REG(rhport); + const dwc2_ghwcfg2_t ghwcfg2 = {.value = dwc2->ghwcfg2}; // Scatter/Gather DMA mode is not yet supported. Buffer DMA only need 1 words per channel const bool is_dma = dma_host_enabled(dwc2); uint16_t dfifo_top = dwc2_controller->ep_fifo_size/4; if (is_dma) { - dfifo_top -= dwc2->ghwcfg2_bm.num_host_ch; + dfifo_top -= ghwcfg2.num_host_ch; } // fixed allocation for now, improve later: @@ -319,7 +328,7 @@ static void dfifo_host_init(uint8_t rhport) { uint32_t ptx_largest = is_highspeed ? TUSB_EPSIZE_ISO_HS_MAX/4 : 256/4; uint16_t nptxfsiz = 2 * nptx_largest; - uint16_t rxfsiz = 2 * (ptx_largest + 2) + dwc2->ghwcfg2_bm.num_host_ch; + uint16_t rxfsiz = 2 * (ptx_largest + 2) + ghwcfg2.num_host_ch; TU_ASSERT(dfifo_top >= (nptxfsiz + rxfsiz),); uint16_t ptxfsiz = dfifo_top - (nptxfsiz + rxfsiz); @@ -372,6 +381,10 @@ bool hcd_init(uint8_t rhport, const tusb_rhport_init_t* rh_init) { // force host mode and wait for mode switch dwc2->gusbcfg = (dwc2->gusbcfg & ~GUSBCFG_FDMOD) | GUSBCFG_FHMOD; +#if CFG_TUSB_MCU == OPT_MCU_STM32N6 + // No hardware detection of Vbus B-session is available on the STM32N6 + dwc2->stm32_gccfg &= ~STM32_GCCFG_VBVALOVAL; +#endif while ((dwc2->gintsts & GINTSTS_CMOD) != GINTSTS_CMODE_HOST) {} // configure fixed-allocated fifo scheme @@ -381,7 +394,7 @@ bool hcd_init(uint8_t rhport, const tusb_rhport_init_t* rh_init) { dwc2->hprt = HPRT_POWER; // turn on VBUS // Enable required interrupts - dwc2->gintmsk |= GINTSTS_OTGINT | GINTSTS_CONIDSTSCHNG | GINTSTS_HPRTINT | GINTSTS_HCINT; + dwc2->gintmsk |= GINTSTS_OTGINT | GINTSTS_CONIDSTSCHNG | GINTSTS_HPRTINT | GINTSTS_HCINT | GINTSTS_DISCINT; // NPTX can hold at least 2 packet, change interrupt level to half-empty uint32_t gahbcfg = dwc2->gahbcfg & ~GAHBCFG_TX_FIFO_EPMTY_LVL; @@ -461,8 +474,8 @@ bool hcd_edpt_open(uint8_t rhport, uint8_t dev_addr, const tusb_desc_endpoint_t* dwc2_regs_t* dwc2 = DWC2_REG(rhport); const tusb_speed_t rh_speed = hprt_speed_get(dwc2); - hcd_devtree_info_t devtree_info; - hcd_devtree_get_info(dev_addr, &devtree_info); + tuh_bus_info_t bus_info; + tuh_bus_info_get(dev_addr, &bus_info); // find a free endpoint const uint8_t ep_id = edpt_alloc(); @@ -473,7 +486,7 @@ bool hcd_edpt_open(uint8_t rhport, uint8_t dev_addr, const tusb_desc_endpoint_t* hcchar_bm->ep_size = tu_edpt_packet_size(desc_ep); hcchar_bm->ep_num = tu_edpt_number(desc_ep->bEndpointAddress); hcchar_bm->ep_dir = tu_edpt_dir(desc_ep->bEndpointAddress); - hcchar_bm->low_speed_dev = (devtree_info.speed == TUSB_SPEED_LOW) ? 1 : 0; + hcchar_bm->low_speed_dev = (bus_info.speed == TUSB_SPEED_LOW) ? 1 : 0; hcchar_bm->ep_type = desc_ep->bmAttributes.xfer; // ep_type matches TUSB_XFER_* hcchar_bm->err_multi_count = 0; hcchar_bm->dev_addr = dev_addr; @@ -482,21 +495,21 @@ bool hcd_edpt_open(uint8_t rhport, uint8_t dev_addr, const tusb_desc_endpoint_t* hcchar_bm->enable = 1; dwc2_channel_split_t* hcsplt_bm = &edpt->hcsplt_bm; - hcsplt_bm->hub_port = devtree_info.hub_port; - hcsplt_bm->hub_addr = devtree_info.hub_addr; + hcsplt_bm->hub_port = bus_info.hub_port; + hcsplt_bm->hub_addr = bus_info.hub_addr; hcsplt_bm->xact_pos = 0; hcsplt_bm->split_compl = 0; - hcsplt_bm->split_en = (rh_speed == TUSB_SPEED_HIGH && devtree_info.speed != TUSB_SPEED_HIGH) ? 1 : 0; + hcsplt_bm->split_en = (rh_speed == TUSB_SPEED_HIGH && bus_info.speed != TUSB_SPEED_HIGH) ? 1 : 0; - edpt->speed = devtree_info.speed; + edpt->speed = bus_info.speed; edpt->next_pid = HCTSIZ_PID_DATA0; if (desc_ep->bmAttributes.xfer == TUSB_XFER_ISOCHRONOUS) { edpt->uframe_interval = 1 << (desc_ep->bInterval - 1); - if (devtree_info.speed == TUSB_SPEED_FULL) { + if (bus_info.speed == TUSB_SPEED_FULL) { edpt->uframe_interval <<= 3; } } else if (desc_ep->bmAttributes.xfer == TUSB_XFER_INTERRUPT) { - if (devtree_info.speed == TUSB_SPEED_HIGH) { + if (bus_info.speed == TUSB_SPEED_HIGH) { edpt->uframe_interval = 1 << (desc_ep->bInterval - 1); } else { edpt->uframe_interval = desc_ep->bInterval << 3; @@ -506,13 +519,19 @@ bool hcd_edpt_open(uint8_t rhport, uint8_t dev_addr, const tusb_desc_endpoint_t* return true; } +bool hcd_edpt_close(uint8_t rhport, uint8_t daddr, uint8_t ep_addr) { + (void) rhport; (void) daddr; (void) ep_addr; + return false; // TODO not implemented yet +} + // clean up channel after part of transfer is done but the whole urb is not complete static void channel_xfer_out_wrapup(dwc2_regs_t* dwc2, uint8_t ch_id) { hcd_xfer_t* xfer = &_hcd_data.xfer[ch_id]; - dwc2_channel_t* channel = &dwc2->channel[ch_id]; + const dwc2_channel_t* channel = &dwc2->channel[ch_id]; hcd_endpoint_t* edpt = &_hcd_data.edpt[xfer->ep_id]; - edpt->next_pid = channel->hctsiz_bm.pid; // save PID + const dwc2_channel_tsize_t hctsiz = {.value = channel->hctsiz}; + edpt->next_pid = hctsiz.pid; // save PID /* Since hctsiz.xfersize field reflects the number of bytes transferred via the AHB, not the USB) * For IN: we can use hctsiz.xfersize as remaining bytes. @@ -520,9 +539,10 @@ static void channel_xfer_out_wrapup(dwc2_regs_t* dwc2, uint8_t ch_id) { * number of packets that have been transferred via the USB. This is always an integral number of packets if the * transfer was halted before its normal completion. */ - const uint16_t remain_packets = channel->hctsiz_bm.packet_count; - const uint16_t total_packets = cal_packet_count(edpt->buflen, channel->hcchar_bm.ep_size); - const uint16_t actual_bytes = (total_packets - remain_packets) * channel->hcchar_bm.ep_size; + const uint16_t remain_packets = hctsiz.packet_count; + const dwc2_channel_char_t hcchar = {.value = channel->hcchar}; + const uint16_t total_packets = cal_packet_count(edpt->buflen, hcchar.ep_size); + const uint16_t actual_bytes = (total_packets - remain_packets) * hcchar.ep_size; xfer->fifo_bytes = 0; xfer->xferred_bytes += actual_bytes; @@ -535,7 +555,7 @@ static bool channel_xfer_start(dwc2_regs_t* dwc2, uint8_t ch_id) { hcd_endpoint_t* edpt = &_hcd_data.edpt[xfer->ep_id]; dwc2_channel_char_t* hcchar_bm = &edpt->hcchar_bm; dwc2_channel_t* channel = &dwc2->channel[ch_id]; - bool const is_period = edpt_is_periodic(hcchar_bm->ep_type); + bool const is_period = channel_is_periodic(edpt->hcchar); // clear previous state xfer->fifo_bytes = 0; @@ -548,13 +568,16 @@ static bool channel_xfer_start(dwc2_regs_t* dwc2, uint8_t ch_id) { // hctsiz: zero length packet still count as 1 const uint16_t packet_count = cal_packet_count(edpt->buflen, hcchar_bm->ep_size); - uint32_t hctsiz = (edpt->next_pid << HCTSIZ_PID_Pos) | (packet_count << HCTSIZ_PKTCNT_Pos) | edpt->buflen; - if (edpt->do_ping && edpt->speed == TUSB_SPEED_HIGH && + dwc2_channel_tsize_t hctsiz = {.value = 0}; + hctsiz.pid = edpt->next_pid; // next PID is set in transfer complete interrupt + hctsiz.packet_count = packet_count; + hctsiz.xfer_size = edpt->buflen; + if (edpt->next_do_ping && edpt->speed == TUSB_SPEED_HIGH && edpt->next_pid != HCTSIZ_PID_SETUP && hcchar_bm->ep_dir == TUSB_DIR_OUT) { - hctsiz |= HCTSIZ_DOPING; + hctsiz.do_ping = 1; } - channel->hctsiz = hctsiz; - edpt->do_ping = 0; + channel->hctsiz = hctsiz.value; + edpt->next_do_ping = 0; // pre-calculate next PID based on packet count, adjusted in transfer complete interrupt if short packet if (hcchar_bm->ep_num == 0) { @@ -585,7 +608,7 @@ static bool channel_xfer_start(dwc2_regs_t* dwc2, uint8_t ch_id) { hcintmsk |= HCINT_BABBLE_ERR | HCINT_DATATOGGLE_ERR | HCINT_ACK; } else { hcintmsk |= HCINT_NYET; - if (edpt->hcsplt_bm.split_en) { + if (edpt->hcsplt_bm.split_en || hctsiz.do_ping) { hcintmsk |= HCINT_ACK; } } @@ -694,18 +717,23 @@ bool hcd_edpt_clear_stall(uint8_t rhport, uint8_t dev_addr, uint8_t ep_addr) { //-------------------------------------------------------------------- // HCD Event Handler //-------------------------------------------------------------------- + +// retry an IN transfer, channel must be halted static void channel_xfer_in_retry(dwc2_regs_t* dwc2, uint8_t ch_id, uint32_t hcint) { hcd_xfer_t* xfer = &_hcd_data.xfer[ch_id]; - dwc2_channel_t* channel = &dwc2->channel[ch_id]; hcd_endpoint_t* edpt = &_hcd_data.edpt[xfer->ep_id]; + dwc2_channel_t* channel = &dwc2->channel[ch_id]; + dwc2_channel_char_t hcchar = {.value = channel->hcchar}; - if (edpt_is_periodic(channel->hcchar_bm.ep_type)){ + if (channel_is_periodic(hcchar.value)){ + const dwc2_channel_split_t hcsplt = {.value = channel->hcsplt}; // retry immediately for periodic split NYET if we haven't reach max retry - if (channel->hcsplt_bm.split_en && channel->hcsplt_bm.split_compl && (hcint & HCINT_NYET || xfer->halted_nyet)) { + if (hcsplt.split_en && hcsplt.split_compl && (hcint & HCINT_NYET || xfer->halted_nyet)) { xfer->period_split_nyet_count++; xfer->halted_nyet = 0; if (xfer->period_split_nyet_count < HCD_XFER_PERIOD_SPLIT_NYET_MAX) { - channel->hcchar_bm.odd_frame = 1 - (dwc2->hfnum & 1); // transfer on next frame + hcchar.odd_frame = 1 - (dwc2->hfnum & 1); // transfer on next frame + channel->hcchar = hcchar.value; channel_send_in_token(dwc2, channel); return; } else { @@ -714,18 +742,24 @@ static void channel_xfer_in_retry(dwc2_regs_t* dwc2, uint8_t ch_id, uint32_t hci } } - // for periodic, de-allocate channel, enable SOF set frame counter for later transfer - edpt->next_pid = channel->hctsiz_bm.pid; // save PID - edpt->uframe_countdown = edpt->uframe_interval; - dwc2->gintmsk |= GINTSTS_SOF; - - if (hcint & HCINT_HALTED) { + const uint32_t ucount = (hprt_speed_get(dwc2) == TUSB_SPEED_HIGH ? 1 : 8); + if (edpt->uframe_interval == ucount) { + // retry on next frame if bInterval is 1 + hcchar.odd_frame = 1 - (dwc2->hfnum & 1); + channel->hcchar = hcchar.value; + channel_send_in_token(dwc2, channel); + } else { + // otherwise, de-allocate channel, enable SOF set frame counter for later transfer + const dwc2_channel_tsize_t hctsiz = {.value = channel->hctsiz}; + edpt->next_pid = hctsiz.pid; // save PID + edpt->uframe_countdown = edpt->uframe_interval - ucount; + // enable SOF interrupt if not already enabled + if (!(dwc2->gintmsk & GINTMSK_SOFM)) { + dwc2->gintsts = GINTSTS_SOF; + dwc2->gintmsk |= GINTMSK_SOFM; + } // already halted, de-allocate channel (called from DMA isr) channel_dealloc(dwc2, ch_id); - } else { - // disable channel first if not halted (called slave isr) - xfer->halted_sof_schedule = 1; - channel_disable(dwc2, channel); } } else { // for control/bulk: retry immediately @@ -756,13 +790,13 @@ static void handle_rxflvl_irq(uint8_t rhport) { dwc2_regs_t* dwc2 = DWC2_REG(rhport); // Pop control word off FIFO - const dwc2_grxstsp_t grxstsp_bm = dwc2->grxstsp_bm; - const uint8_t ch_id = grxstsp_bm.ep_ch_num; + const dwc2_grxstsp_t grxstsp = {.value= dwc2->grxstsp}; + const uint8_t ch_id = grxstsp.ep_ch_num; - switch (grxstsp_bm.packet_status) { + switch (grxstsp.packet_status) { case GRXSTS_PKTSTS_RX_DATA: { // In packet received, pop this entry --> ACK interrupt - const uint16_t byte_count = grxstsp_bm.byte_count; + const uint16_t byte_count = grxstsp.byte_count; hcd_xfer_t* xfer = &_hcd_data.xfer[ch_id]; TU_ASSERT(xfer->ep_id < CFG_TUH_DWC2_ENDPOINT_MAX,); hcd_endpoint_t* edpt = &_hcd_data.edpt[xfer->ep_id]; @@ -796,25 +830,26 @@ static void handle_rxflvl_irq(uint8_t rhport) { // return true if there is still pending data and need more ISR static bool handle_txfifo_empty(dwc2_regs_t* dwc2, bool is_periodic) { // Use period txsts for both p/np to get request queue space available (1-bit difference, it is small enough) - volatile dwc2_hptxsts_t* txsts_bm = (volatile dwc2_hptxsts_t*) (is_periodic ? &dwc2->hptxsts : &dwc2->hnptxsts); + const dwc2_hptxsts_t txsts = {.value = (is_periodic ? dwc2->hptxsts : dwc2->hnptxsts)}; - const uint8_t max_channel = DWC2_CHANNEL_COUNT(dwc2); + const uint8_t max_channel = dwc2_channel_count(dwc2); for (uint8_t ch_id = 0; ch_id < max_channel; ch_id++) { dwc2_channel_t* channel = &dwc2->channel[ch_id]; + const dwc2_channel_char_t hcchar = {.value = channel->hcchar}; // skip writing to FIFO if channel is expecting halted. - if (!(channel->hcintmsk & HCINT_HALTED) && (channel->hcchar_bm.ep_dir == TUSB_DIR_OUT)) { + if (!(channel->hcintmsk & HCINT_HALTED) && (hcchar.ep_dir == TUSB_DIR_OUT)) { hcd_xfer_t* xfer = &_hcd_data.xfer[ch_id]; TU_ASSERT(xfer->ep_id < CFG_TUH_DWC2_ENDPOINT_MAX); hcd_endpoint_t* edpt = &_hcd_data.edpt[xfer->ep_id]; - - const uint16_t remain_packets = channel->hctsiz_bm.packet_count; + const dwc2_channel_tsize_t hctsiz = {.value = channel->hctsiz}; + const uint16_t remain_packets = hctsiz.packet_count; for (uint16_t i = 0; i < remain_packets; i++) { const uint16_t remain_bytes = edpt->buflen - xfer->fifo_bytes; - const uint16_t xact_bytes = tu_min16(remain_bytes, channel->hcchar_bm.ep_size); + const uint16_t xact_bytes = tu_min16(remain_bytes, hcchar.ep_size); // skip if there is not enough space in FIFO and RequestQueue. // Packet's last word written to FIFO will trigger a request queue - if ((xact_bytes > (txsts_bm->fifo_available << 2)) || (txsts_bm->req_queue_available == 0)) { + if ((xact_bytes > (txsts.fifo_available << 2)) || (txsts.req_queue_available == 0)) { return true; } @@ -831,23 +866,26 @@ static bool handle_channel_in_slave(dwc2_regs_t* dwc2, uint8_t ch_id, uint32_t h hcd_xfer_t* xfer = &_hcd_data.xfer[ch_id]; dwc2_channel_t* channel = &dwc2->channel[ch_id]; hcd_endpoint_t* edpt = &_hcd_data.edpt[xfer->ep_id]; + dwc2_channel_split_t hcsplt = {.value = channel->hcsplt}; + const dwc2_channel_tsize_t hctsiz = {.value = channel->hctsiz}; bool is_done = false; - // if (channel->hcsplt_bm.split_en) { + // if (hcsplt.split_en) { // if (edpt->hcchar_bm.ep_num == 1) { - // TU_LOG1("Frame %u, ch %u: ep %u, hcint 0x%04lX ", dwc2->hfnum_bm.num, ch_id, channel->hcchar_bm.ep_num, hcint); + // TU_LOG1("Frame %u, ch %u: ep %u, hcint 0x%04lX ", dwc2->hfnum_bm.num, ch_id, hcsplt.ep_num, hcint); // print_hcint(hcint); // } if (hcint & HCINT_XFER_COMPLETE) { if (edpt->hcchar_bm.ep_num != 0) { - edpt->next_pid = channel->hctsiz_bm.pid; // save pid (already toggled) + edpt->next_pid = hctsiz.pid; // save pid (already toggled) } - const uint16_t remain_packets = channel->hctsiz_bm.packet_count; - if (channel->hcsplt_bm.split_en && remain_packets && xfer->fifo_bytes == edpt->hcchar_bm.ep_size) { + const uint16_t remain_packets = hctsiz.packet_count; + if (hcsplt.split_en && remain_packets && xfer->fifo_bytes == edpt->hcchar_bm.ep_size) { // Split can only complete 1 transaction (up to 1 packet) at a time, schedule more - channel->hcsplt_bm.split_compl = 0; + hcsplt.split_compl = 0; + channel->hcsplt = hcsplt.value; } else { xfer->result = XFER_RESULT_SUCCESS; } @@ -866,43 +904,44 @@ static bool handle_channel_in_slave(dwc2_regs_t* dwc2, uint8_t ch_id, uint32_t h channel_disable(dwc2, channel); } else if (hcint & HCINT_NYET) { // restart complete split - channel->hcsplt_bm.split_compl = 1; + hcsplt.split_compl = 1; + channel->hcsplt = hcsplt.value; xfer->halted_nyet = 1; channel_disable(dwc2, channel); } else if (hcint & HCINT_NAK) { - // NAK received, re-enable channel if request queue is available - if (channel->hcsplt_bm.split_en) { - channel->hcsplt_bm.split_compl = 0; // restart with start-split + // NAK received, disable channel to flush all posted request and try again + if (hcsplt.split_en) { + hcsplt.split_compl = 0; // restart with start-split + channel->hcsplt = hcsplt.value; } channel_disable(dwc2, channel); } else if (hcint & HCINT_ACK) { xfer->err_count = 0; - if (channel->hcsplt_bm.split_en) { - if (!channel->hcsplt_bm.split_compl) { + if (hcsplt.split_en) { + if (!hcsplt.split_compl) { // start split is ACK --> do complete split channel->hcintmsk |= HCINT_NYET; - channel->hcsplt_bm.split_compl = 1; + hcsplt.split_compl = 1; + channel->hcsplt = hcsplt.value; channel_send_in_token(dwc2, channel); } else { // do nothing for complete split with DATA, this will trigger XferComplete and handled there } } else { // ACK with data - const uint16_t remain_packets = channel->hctsiz_bm.packet_count; + const uint16_t remain_packets = hctsiz.packet_count; if (remain_packets) { // still more packet to receive, also reset to start split - channel->hcsplt_bm.split_compl = 0; + hcsplt.split_compl = 0; + channel->hcsplt = hcsplt.value; channel_send_in_token(dwc2, channel); } } } else if (hcint & HCINT_HALTED) { channel->hcintmsk &= ~HCINT_HALTED; - if (xfer->halted_sof_schedule) { - // de-allocate channel but does not complete xfer, we schedule it in the SOF interrupt - channel_dealloc(dwc2, ch_id); - } else if (xfer->result != XFER_RESULT_INVALID) { + if (xfer->result != XFER_RESULT_INVALID) { is_done = true; } else if (xfer->err_count == HCD_XFER_ERROR_MAX) { xfer->result = XFER_RESULT_FAILED; @@ -922,23 +961,29 @@ static bool handle_channel_out_slave(dwc2_regs_t* dwc2, uint8_t ch_id, uint32_t hcd_xfer_t* xfer = &_hcd_data.xfer[ch_id]; dwc2_channel_t* channel = &dwc2->channel[ch_id]; hcd_endpoint_t* edpt = &_hcd_data.edpt[xfer->ep_id]; + dwc2_channel_split_t hcsplt = {.value = channel->hcsplt}; bool is_done = false; if (hcint & HCINT_XFER_COMPLETE) { is_done = true; xfer->result = XFER_RESULT_SUCCESS; channel->hcintmsk &= ~HCINT_ACK; + if (hcint & HCINT_NYET) { + // complete transfer with NYET, do ping next time + edpt->next_do_ping = 1; + } } else if (hcint & HCINT_STALL) { xfer->result = XFER_RESULT_STALLED; channel_disable(dwc2, channel); } else if (hcint & HCINT_NYET) { xfer->err_count = 0; - if (channel->hcsplt_bm.split_en) { + if (hcsplt.split_en) { // retry complete split - channel->hcsplt_bm.split_compl = 1; + hcsplt.split_compl = 1; + channel->hcsplt = hcsplt.value; channel->hcchar |= HCCHAR_CHENA; } else { - edpt->do_ping = 1; + edpt->next_do_ping = 1; channel_xfer_out_wrapup(dwc2, ch_id); channel_disable(dwc2, channel); } @@ -951,7 +996,7 @@ static bool handle_channel_out_slave(dwc2_regs_t* dwc2, uint8_t ch_id, uint32_t channel->hcintmsk |= HCINT_ACK; } else { // NAK disable channel to flush all posted request and try again - edpt->do_ping = 1; + edpt->next_do_ping = 1; xfer->err_count = 0; } } else if (hcint & HCINT_HALTED) { @@ -968,9 +1013,17 @@ static bool handle_channel_out_slave(dwc2_regs_t* dwc2, uint8_t ch_id, uint32_t } else if (hcint & HCINT_ACK) { xfer->err_count = 0; channel->hcintmsk &= ~HCINT_ACK; - if (channel->hcsplt_bm.split_en && !channel->hcsplt_bm.split_compl) { - // start split is ACK --> do complete split - channel->hcsplt_bm.split_compl = 1; + if (hcsplt.split_en) { + if (!hcsplt.split_compl) { + // ACK for start split --> do complete split + hcsplt.split_compl = 1; + channel->hcsplt = hcsplt.value; + channel->hcchar |= HCCHAR_CHENA; + } + } else { + // ACK interrupt is only enabled for Split and PING + // ACK for PING, which mean device is ready to receive data + channel->hctsiz &= ~HCTSIZ_DOPING; // HC already cleared PING bit, but we clear anyway channel->hcchar |= HCCHAR_CHENA; } } @@ -989,6 +1042,9 @@ static bool handle_channel_in_dma(dwc2_regs_t* dwc2, uint8_t ch_id, uint32_t hci hcd_xfer_t* xfer = &_hcd_data.xfer[ch_id]; dwc2_channel_t* channel = &dwc2->channel[ch_id]; hcd_endpoint_t* edpt = &_hcd_data.edpt[xfer->ep_id]; + dwc2_channel_char_t hcchar = {.value = channel->hcchar}; + dwc2_channel_split_t hcsplt = {.value = channel->hcsplt}; + const dwc2_channel_tsize_t hctsiz = {.value = channel->hctsiz}; bool is_done = false; @@ -996,8 +1052,8 @@ static bool handle_channel_in_dma(dwc2_regs_t* dwc2, uint8_t ch_id, uint32_t hci if (hcint & HCINT_HALTED) { if (hcint & (HCINT_XFER_COMPLETE | HCINT_STALL | HCINT_BABBLE_ERR)) { - const uint16_t remain_bytes = (uint16_t) channel->hctsiz_bm.xfer_size; - const uint16_t remain_packets = channel->hctsiz_bm.packet_count; + const uint16_t remain_bytes = (uint16_t) hctsiz.xfer_size; + const uint16_t remain_packets = hctsiz.packet_count; const uint16_t actual_len = edpt->buflen - remain_bytes; xfer->xferred_bytes += actual_len; @@ -1007,13 +1063,14 @@ static bool handle_channel_in_dma(dwc2_regs_t* dwc2, uint8_t ch_id, uint32_t hci xfer->result = XFER_RESULT_STALLED; } else if (hcint & HCINT_BABBLE_ERR) { xfer->result = XFER_RESULT_FAILED; - } else if (channel->hcsplt_bm.split_en && remain_packets && actual_len == edpt->hcchar_bm.ep_size) { + } else if (hcsplt.split_en && remain_packets && actual_len == hcchar.ep_size) { // Split can only complete 1 transaction (up to 1 packet) at a time, schedule more is_done = false; edpt->buffer += actual_len; edpt->buflen -= actual_len; - channel->hcsplt_bm.split_compl = 0; + hcsplt.split_compl = 0; + channel->hcsplt = hcsplt.value; channel_xfer_in_retry(dwc2, ch_id, hcint); } else { xfer->result = XFER_RESULT_SUCCESS; @@ -1028,33 +1085,38 @@ static bool handle_channel_in_dma(dwc2_regs_t* dwc2, uint8_t ch_id, uint32_t hci xfer->result = XFER_RESULT_FAILED; } else { channel->hcintmsk |= HCINT_ACK | HCINT_NAK | HCINT_DATATOGGLE_ERR; - channel->hcsplt_bm.split_compl = 0; + hcsplt.split_compl = 0; + channel->hcsplt = hcsplt.value; channel_xfer_in_retry(dwc2, ch_id, hcint); } } else if (hcint & HCINT_NYET) { // Must handle nyet before nak or ack. Could get a nyet at the same time as either of those on a BULK/CONTROL // OUT that started with a PING. The nyet takes precedence. - if (channel->hcsplt_bm.split_en) { + if (hcsplt.split_en) { // split not yet mean hub has no data, retry complete split - channel->hcsplt_bm.split_compl = 1; + hcsplt.split_compl = 1; + channel->hcsplt = hcsplt.value; channel_xfer_in_retry(dwc2, ch_id, hcint); } } else if (hcint & HCINT_ACK) { xfer->err_count = 0; channel->hcintmsk &= ~HCINT_ACK; - if (channel->hcsplt_bm.split_en) { + if (hcsplt.split_en) { // start split is ACK --> do complete split // TODO: for ISO must use xact_pos to plan complete split based on microframe (up to 187.5 bytes/uframe) - channel->hcsplt_bm.split_compl = 1; - if (edpt_is_periodic(channel->hcchar_bm.ep_type)) { - channel->hcchar_bm.odd_frame = 1 - (dwc2->hfnum & 1); // transfer on next frame + hcsplt.split_compl = 1; + channel->hcsplt = hcsplt.value; + if (channel_is_periodic(channel->hcchar)) { + hcchar.odd_frame = 1 - (dwc2->hfnum & 1); // transfer on next frame + channel->hcchar = hcchar.value; } channel_send_in_token(dwc2, channel); } } else if (hcint & (HCINT_NAK | HCINT_DATATOGGLE_ERR)) { xfer->err_count = 0; channel->hcintmsk &= ~(HCINT_NAK | HCINT_DATATOGGLE_ERR); - channel->hcsplt_bm.split_compl = 0; // restart with start-split + hcsplt.split_compl = 0; // restart with start-split + channel->hcsplt = hcsplt.value; channel_xfer_in_retry(dwc2, ch_id, hcint); } else if (hcint & HCINT_FARME_OVERRUN) { // retry start-split in next binterval @@ -1069,6 +1131,8 @@ static bool handle_channel_out_dma(dwc2_regs_t* dwc2, uint8_t ch_id, uint32_t hc hcd_xfer_t* xfer = &_hcd_data.xfer[ch_id]; dwc2_channel_t* channel = &dwc2->channel[ch_id]; hcd_endpoint_t* edpt = &_hcd_data.edpt[xfer->ep_id]; + const dwc2_channel_char_t hcchar = {.value = channel->hcchar}; + dwc2_channel_split_t hcsplt = {.value = channel->hcsplt}; bool is_done = false; @@ -1104,16 +1168,18 @@ static bool handle_channel_out_dma(dwc2_regs_t* dwc2, uint8_t ch_id, uint32_t hc } } } else if (hcint & HCINT_NYET) { - if (channel->hcsplt_bm.split_en && channel->hcsplt_bm.split_compl) { + if (hcsplt.split_en && hcsplt.split_compl) { // split not yet mean hub has no data, retry complete split - channel->hcsplt_bm.split_compl = 1; + hcsplt.split_compl = 1; + channel->hcsplt = hcsplt.value; channel->hcchar |= HCCHAR_CHENA; } } else if (hcint & HCINT_ACK) { xfer->err_count = 0; - if (channel->hcsplt_bm.split_en && !channel->hcsplt_bm.split_compl) { + if (hcsplt.split_en && !hcsplt.split_compl) { // start split is ACK --> do complete split - channel->hcsplt_bm.split_compl = 1; + hcsplt.split_compl = 1; + channel->hcsplt = hcsplt.value; channel->hcchar |= HCCHAR_CHENA; } } @@ -1129,14 +1195,14 @@ static bool handle_channel_out_dma(dwc2_regs_t* dwc2, uint8_t ch_id, uint32_t hc static void handle_channel_irq(uint8_t rhport, bool in_isr) { dwc2_regs_t* dwc2 = DWC2_REG(rhport); const bool is_dma = dma_host_enabled(dwc2); - const uint8_t max_channel = DWC2_CHANNEL_COUNT(dwc2); + const uint8_t max_channel = dwc2_channel_count(dwc2); for (uint8_t ch_id = 0; ch_id < max_channel; ch_id++) { if (tu_bit_test(dwc2->haint, ch_id)) { dwc2_channel_t* channel = &dwc2->channel[ch_id]; hcd_xfer_t* xfer = &_hcd_data.xfer[ch_id]; TU_ASSERT(xfer->ep_id < CFG_TUH_DWC2_ENDPOINT_MAX,); - dwc2_channel_char_t hcchar_bm = channel->hcchar_bm; + dwc2_channel_char_t hcchar = {.value = channel->hcchar}; const uint32_t hcint = channel->hcint; channel->hcint = hcint; // clear interrupt @@ -1144,7 +1210,7 @@ static void handle_channel_irq(uint8_t rhport, bool in_isr) { bool is_done = false; if (is_dma) { #if CFG_TUH_DWC2_DMA_ENABLE - if (hcchar_bm.ep_dir == TUSB_DIR_OUT) { + if (hcchar.ep_dir == TUSB_DIR_OUT) { is_done = handle_channel_out_dma(dwc2, ch_id, hcint); } else { is_done = handle_channel_in_dma(dwc2, ch_id, hcint); @@ -1156,7 +1222,7 @@ static void handle_channel_irq(uint8_t rhport, bool in_isr) { #endif } else { #if CFG_TUH_DWC2_SLAVE_ENABLE - if (hcchar_bm.ep_dir == TUSB_DIR_OUT) { + if (hcchar.ep_dir == TUSB_DIR_OUT) { is_done = handle_channel_out_slave(dwc2, ch_id, hcint); } else { is_done = handle_channel_in_slave(dwc2, ch_id, hcint); @@ -1165,8 +1231,8 @@ static void handle_channel_irq(uint8_t rhport, bool in_isr) { } if (is_done) { - const uint8_t ep_addr = tu_edpt_addr(hcchar_bm.ep_num, hcchar_bm.ep_dir); - hcd_event_xfer_complete(hcchar_bm.dev_addr, ep_addr, xfer->xferred_bytes, xfer->result, in_isr); + const uint8_t ep_addr = tu_edpt_addr(hcchar.ep_num, hcchar.ep_dir); + hcd_event_xfer_complete(hcchar.dev_addr, ep_addr, xfer->xferred_bytes, (xfer_result_t)xfer->result, in_isr); channel_dealloc(dwc2, ch_id); } } @@ -1177,6 +1243,7 @@ static void handle_channel_irq(uint8_t rhport, bool in_isr) { static bool handle_sof_irq(uint8_t rhport, bool in_isr) { (void) in_isr; dwc2_regs_t* dwc2 = DWC2_REG(rhport); + dwc2->gintsts = GINTSTS_SOF; // Clear the SOF interrupt flag bool more_isr = false; @@ -1185,7 +1252,7 @@ static bool handle_sof_irq(uint8_t rhport, bool in_isr) { for(uint8_t ep_id = 0; ep_id < CFG_TUH_DWC2_ENDPOINT_MAX; ep_id++) { hcd_endpoint_t* edpt = &_hcd_data.edpt[ep_id]; - if (edpt->hcchar_bm.enable && edpt_is_periodic(edpt->hcchar_bm.ep_type) && edpt->uframe_countdown > 0) { + if (edpt->hcchar_bm.enable && channel_is_periodic(edpt->hcchar) && edpt->uframe_countdown > 0) { edpt->uframe_countdown -= tu_min32(ucount, edpt->uframe_countdown); if (edpt->uframe_countdown == 0) { if (!edpt_xfer_kickoff(dwc2, ep_id)) { @@ -1204,10 +1271,10 @@ static bool handle_sof_irq(uint8_t rhport, bool in_isr) { static void port0_enable(dwc2_regs_t* dwc2, tusb_speed_t speed) { uint32_t hcfg = dwc2->hcfg & ~HCFG_FSLS_PHYCLK_SEL; - const dwc2_gusbcfg_t gusbcfg_bm = dwc2->gusbcfg_bm; + const dwc2_gusbcfg_t gusbcfg = {.value = dwc2->gusbcfg}; uint32_t phy_clock; - if (gusbcfg_bm.phy_sel) { + if (gusbcfg.phy_sel) { phy_clock = 48; // dedicated FS is 48Mhz if (speed == TUSB_SPEED_LOW) { hcfg |= HCFG_FSLS_PHYCLK_SEL_6MHZ; @@ -1215,11 +1282,11 @@ static void port0_enable(dwc2_regs_t* dwc2, tusb_speed_t speed) { hcfg |= HCFG_FSLS_PHYCLK_SEL_48MHZ; } } else { - if (gusbcfg_bm.ulpi_utmi_sel) { + if (gusbcfg.ulpi_utmi_sel) { phy_clock = 60; // ULPI 8-bit is 60Mhz } else { // UTMI+ 16-bit is 30Mhz, 8-bit is 60Mhz - phy_clock = gusbcfg_bm.phy_if16 ? 30 : 60; + phy_clock = gusbcfg.phy_if16 ? 30 : 60; // Enable UTMI+ low power mode 48Mhz external clock if not highspeed if (speed == TUSB_SPEED_HIGH) { @@ -1236,9 +1303,9 @@ static void port0_enable(dwc2_regs_t* dwc2, tusb_speed_t speed) { uint32_t hfir = dwc2->hfir & ~HFIR_FRIVL_Msk; if (speed == TUSB_SPEED_HIGH) { - hfir |= 125*phy_clock; + hfir |= 125*phy_clock - 1; // The "- 1" is the correct value. The Synopsys databook was corrected in 3.30a } else { - hfir |= 1000*phy_clock; + hfir |= 1000*phy_clock - 1; } dwc2->hfir = hfir; @@ -1251,21 +1318,19 @@ static void port0_enable(dwc2_regs_t* dwc2, tusb_speed_t speed) { */ static void handle_hprt_irq(uint8_t rhport, bool in_isr) { dwc2_regs_t* dwc2 = DWC2_REG(rhport); - uint32_t hprt = dwc2->hprt & ~HPRT_W1_MASK; - const dwc2_hprt_t hprt_bm = dwc2->hprt_bm; + const dwc2_hprt_t hprt_bm = {.value = dwc2->hprt}; + uint32_t hprt = hprt_bm.value & ~HPRT_W1_MASK; - if (dwc2->hprt & HPRT_CONN_DETECT) { + if (hprt_bm.conn_detected) { // Port Connect Detect hprt |= HPRT_CONN_DETECT; if (hprt_bm.conn_status) { hcd_event_device_attach(rhport, in_isr); - } else { - hcd_event_device_remove(rhport, in_isr); } } - if (dwc2->hprt & HPRT_ENABLE_CHANGE) { + if (hprt_bm.enable_change) { // Port enable change hprt |= HPRT_ENABLE_CHANGE; @@ -1324,6 +1389,15 @@ void hcd_int_handler(uint8_t rhport, bool in_isr) { handle_channel_irq(rhport, in_isr); } + if (gintsts & GINTSTS_DISCINT) { + // Device disconnected + dwc2->gintsts = GINTSTS_DISCINT; + + if (!(dwc2->hprt & HPRT_CONN_STATUS)) { + hcd_event_device_remove(rhport, in_isr); + } + } + #if CFG_TUH_DWC2_SLAVE_ENABLE // RxFIFO non-empty interrupt handling if (gintsts & GINTSTS_RXFLVL) { diff --git a/src/portable/template/hcd_template.c b/src/portable/template/hcd_template.c index d8bca196f..d2f304407 100644 --- a/src/portable/template/hcd_template.c +++ b/src/portable/template/hcd_template.c @@ -29,6 +29,7 @@ #if CFG_TUH_ENABLED && CFG_TUSB_MCU == OPT_MCU_NONE #include "host/hcd.h" +#include "host/usbh.h" //--------------------------------------------------------------------+ // Controller API @@ -36,24 +37,19 @@ // optional hcd configuration, called by tuh_configure() bool hcd_configure(uint8_t rhport, uint32_t cfg_id, const void* cfg_param) { - (void) rhport; - (void) cfg_id; - (void) cfg_param; - + (void) rhport; (void) cfg_id; (void) cfg_param; return false; } // Initialize controller to host mode bool hcd_init(uint8_t rhport, const tusb_rhport_init_t* rh_init) { - (void) rhport; - (void) rh_init; + (void) rhport; (void) rh_init; return false; } // Interrupt Handler void hcd_int_handler(uint8_t rhport, bool in_isr) { - (void) rhport; - (void) in_isr; + (void) rhport; (void) in_isr; } // Enable USB interrupt @@ -69,7 +65,6 @@ void hcd_int_disable(uint8_t rhport) { // Get frame number (1ms) uint32_t hcd_frame_number(uint8_t rhport) { (void) rhport; - return 0; } @@ -80,7 +75,6 @@ uint32_t hcd_frame_number(uint8_t rhport) { // Get the current connect status of roothub port bool hcd_port_connect_status(uint8_t rhport) { (void) rhport; - return false; } @@ -98,14 +92,12 @@ void hcd_port_reset_end(uint8_t rhport) { // Get port link speed tusb_speed_t hcd_port_speed_get(uint8_t rhport) { (void) rhport; - return TUSB_SPEED_FULL; } // HCD closes all opened endpoints belong to this device void hcd_device_close(uint8_t rhport, uint8_t dev_addr) { - (void) rhport; - (void) dev_addr; + (void) rhport; (void) dev_addr; } //--------------------------------------------------------------------+ @@ -114,49 +106,42 @@ void hcd_device_close(uint8_t rhport, uint8_t dev_addr) { // Open an endpoint bool hcd_edpt_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_endpoint_t const * ep_desc) { - (void) rhport; - (void) dev_addr; - (void) ep_desc; + (void) rhport; (void) dev_addr; (void) ep_desc; + + // NOTE: ep_desc is allocated on the stack when called from usbh_edpt_control_open() + // You need to copy the data into a local variable who maintains the state of the endpoint and transfer. + // Check _hcd_data in hcd_dwc2.c for example. return false; } +bool hcd_edpt_close(uint8_t rhport, uint8_t daddr, uint8_t ep_addr) { + (void) rhport; (void) daddr; (void) ep_addr; + return false; // TODO not implemented yet +} + // Submit a transfer, when complete hcd_event_xfer_complete() must be invoked bool hcd_edpt_xfer(uint8_t rhport, uint8_t dev_addr, uint8_t ep_addr, uint8_t * buffer, uint16_t buflen) { - (void) rhport; - (void) dev_addr; - (void) ep_addr; - (void) buffer; - (void) buflen; - + (void) rhport; (void) dev_addr; (void) ep_addr; (void) buffer; (void) buflen; return false; } // Abort a queued transfer. Note: it can only abort transfer that has not been started // Return true if a queued transfer is aborted, false if there is no transfer to abort bool hcd_edpt_abort_xfer(uint8_t rhport, uint8_t dev_addr, uint8_t ep_addr) { - (void) rhport; - (void) dev_addr; - (void) ep_addr; - + (void) rhport; (void) dev_addr; (void) ep_addr; return false; } // Submit a special transfer to send 8-byte Setup Packet, when complete hcd_event_xfer_complete() must be invoked bool hcd_setup_send(uint8_t rhport, uint8_t dev_addr, uint8_t const setup_packet[8]) { - (void) rhport; - (void) dev_addr; - (void) setup_packet; - + (void) rhport; (void) dev_addr; (void) setup_packet; return false; } // clear stall, data toggle is also reset to DATA0 bool hcd_edpt_clear_stall(uint8_t rhport, uint8_t dev_addr, uint8_t ep_addr) { - (void) rhport; - (void) dev_addr; - (void) ep_addr; - + (void) rhport; (void) dev_addr; (void) ep_addr; return false; } diff --git a/src/portable/wch/dcd_ch32_usbfs.c b/src/portable/wch/dcd_ch32_usbfs.c index 4e8e25a00..c248ba14e 100644 --- a/src/portable/wch/dcd_ch32_usbfs.c +++ b/src/portable/wch/dcd_ch32_usbfs.c @@ -192,7 +192,8 @@ void dcd_int_handler(uint8_t rhport) { data.xfer[0][TUSB_DIR_OUT].max_size = 64; data.xfer[0][TUSB_DIR_IN].max_size = 64; - dcd_event_bus_signal(rhport, DCD_EVENT_BUS_RESET, true); + //dcd_event_bus_reset(rhport, (USBOTG_FS->BASE_CTRL & USBFS_CTRL_LOW_SPEED) ? TUSB_SPEED_LOW : TUSB_SPEED_FULL, true); + dcd_event_bus_reset(rhport, (USBOTG_FS->UDEV_CTRL & USBFS_UDEV_CTRL_LOW_SPEED) ? TUSB_SPEED_LOW : TUSB_SPEED_FULL, true); USBOTG_FS->DEV_ADDR = 0x00; EP_RX_CTRL(0) = USBFS_EP_R_RES_ACK; diff --git a/src/tinyusb.mk b/src/tinyusb.mk index 89ea0212c..a9f623c24 100644 --- a/src/tinyusb.mk +++ b/src/tinyusb.mk @@ -21,6 +21,7 @@ TINYUSB_SRC_C += \ src/host/hub.c \ src/class/cdc/cdc_host.c \ src/class/hid/hid_host.c \ + src/class/midi/midi_host.c \ src/class/msc/msc_host.c \ src/class/vendor/vendor_host.c \ src/typec/usbc.c \ diff --git a/src/tusb.c b/src/tusb.c index 85ab1d6ae..13b89997c 100644 --- a/src/tusb.c +++ b/src/tusb.c @@ -142,7 +142,9 @@ void tusb_int_handler(uint8_t rhport, bool in_isr) { uint8_t const* tu_desc_find(uint8_t const* desc, uint8_t const* end, uint8_t byte1) { while (desc + 1 < end) { - if (desc[1] == byte1) return desc; + if (desc[1] == byte1) { + return desc; + } desc += desc[DESC_OFFSET_LEN]; } return NULL; @@ -150,7 +152,9 @@ uint8_t const* tu_desc_find(uint8_t const* desc, uint8_t const* end, uint8_t byt uint8_t const* tu_desc_find2(uint8_t const* desc, uint8_t const* end, uint8_t byte1, uint8_t byte2) { while (desc + 2 < end) { - if (desc[1] == byte1 && desc[2] == byte2) return desc; + if (desc[1] == byte1 && desc[2] == byte2) { + return desc; + } desc += desc[DESC_OFFSET_LEN]; } return NULL; @@ -158,7 +162,9 @@ uint8_t const* tu_desc_find2(uint8_t const* desc, uint8_t const* end, uint8_t by uint8_t const* tu_desc_find3(uint8_t const* desc, uint8_t const* end, uint8_t byte1, uint8_t byte2, uint8_t byte3) { while (desc + 3 < end) { - if (desc[1] == byte1 && desc[2] == byte2 && desc[3] == byte3) return desc; + if (desc[1] == byte1 && desc[2] == byte2 && desc[3] == byte3) { + return desc; + } desc += desc[DESC_OFFSET_LEN]; } return NULL; @@ -199,7 +205,7 @@ bool tu_edpt_release(tu_edpt_state_t* ep_state, osal_mutex_t mutex) { return ret; } -bool tu_edpt_validate(tusb_desc_endpoint_t const* desc_ep, tusb_speed_t speed) { +bool tu_edpt_validate(tusb_desc_endpoint_t const* desc_ep, tusb_speed_t speed, bool is_host) { uint16_t const max_packet_size = tu_edpt_packet_size(desc_ep); TU_LOG2(" Open EP %02X with Size = %u\r\n", desc_ep->bEndpointAddress, max_packet_size); @@ -215,8 +221,17 @@ bool tu_edpt_validate(tusb_desc_endpoint_t const* desc_ep, tusb_speed_t speed) { // Bulk highspeed must be EXACTLY 512 TU_ASSERT(max_packet_size == 512); } else { - // TODO Bulk fullspeed can only be 8, 16, 32, 64 - TU_ASSERT(max_packet_size <= 64); + // Bulk fullspeed can only be 8, 16, 32, 64 + if (is_host && max_packet_size == 512) { + // HACK: while in host mode, some device incorrectly always report 512 regardless of link speed + // overwrite descriptor to force 64 + TU_LOG1(" WARN: EP max packet size is 512 in fullspeed, force to 64\r\n"); + tusb_desc_endpoint_t* hacked_ep = (tusb_desc_endpoint_t*) (uintptr_t) desc_ep; + hacked_ep->wMaxPacketSize = tu_htole16(64); + } else { + TU_ASSERT(max_packet_size == 8 || max_packet_size == 16 || + max_packet_size == 32 || max_packet_size == 64); + } } break; diff --git a/src/tusb.h b/src/tusb.h index cb6021b33..dfba21ddf 100644 --- a/src/tusb.h +++ b/src/tusb.h @@ -59,6 +59,10 @@ #include "class/cdc/cdc_host.h" #endif + #if CFG_TUH_MIDI + #include "class/midi/midi_host.h" + #endif + #if CFG_TUH_VENDOR #include "class/vendor/vendor_host.h" #endif diff --git a/src/tusb_option.h b/src/tusb_option.h index dca1e4109..867babc33 100644 --- a/src/tusb_option.h +++ b/src/tusb_option.h @@ -31,11 +31,11 @@ // Version is release as major.minor.revision eg 1.0.0 #define TUSB_VERSION_MAJOR 0 -#define TUSB_VERSION_MINOR 17 +#define TUSB_VERSION_MINOR 18 #define TUSB_VERSION_REVISION 0 #define TUSB_VERSION_NUMBER (TUSB_VERSION_MAJOR * 10000 + TUSB_VERSION_MINOR * 100 + TUSB_VERSION_REVISION) -#define TUSB_VERSION_STRING TU_STRING(TUSB_VERSION_MAJOR) "." TU_STRING(TUSB_VERSION_MINOR) "." TU_STRING(TUSB_VERSION_REVISION) +#define TUSB_VERSION_STRING TU_XSTRING(TUSB_VERSION_MAJOR) "." TU_XSTRING(TUSB_VERSION_MINOR) "." TU_XSTRING(TUSB_VERSION_REVISION) //--------------------------------------------------------------------+ // Supported MCUs @@ -94,6 +94,7 @@ #define OPT_MCU_STM32U0 316 ///< ST U0 #define OPT_MCU_STM32H7RS 317 ///< ST F7RS #define OPT_MCU_STM32C0 318 ///< ST C0 +#define OPT_MCU_STM32N6 319 ///< ST N6 // Sony #define OPT_MCU_CXD56 400 ///< SONY CXD56 @@ -152,7 +153,7 @@ #define OPT_MCU_RX63X 1400 ///< Renesas RX63N/631 #define OPT_MCU_RX65X 1401 ///< Renesas RX65N/RX651 #define OPT_MCU_RX72N 1402 ///< Renesas RX72N -#define OPT_MCU_RAXXX 1403 ///< Renesas RAxxx families +#define OPT_MCU_RAXXX 1403 ///< Renesas RA generic // Mind Motion #define OPT_MCU_MM32F327X 1500 ///< Mind Motion MM32F327 @@ -195,6 +196,7 @@ // Analog Devices #define OPT_MCU_MAX32690 2400 ///< ADI MAX32690 +#define OPT_MCU_MAX32665 2401 ///< ADI MAX32666/5 #define OPT_MCU_MAX32666 2401 ///< ADI MAX32666/5 #define OPT_MCU_MAX32650 2402 ///< ADI MAX32650/1/2 #define OPT_MCU_MAX78002 2403 ///< ADI MAX78002 @@ -215,6 +217,7 @@ #define OPT_OS_PICO 5 ///< Raspberry Pi Pico SDK #define OPT_OS_RTTHREAD 6 ///< RT-Thread #define OPT_OS_RTX4 7 ///< Keil RTX 4 +#define OPT_OS_ZEPHYR 8 ///< Zephyr //--------------------------------------------------------------------+ // Mode and Speed @@ -266,6 +269,15 @@ #define CFG_TUD_DWC2_DMA_ENABLE CFG_TUD_DWC2_DMA_ENABLE_DEFAULT #endif +// Enable CI_HS VBUS Charge. Set this to 1 if the USB_VBUS pin is not connected to 5V VBUS (note: 3.3V is insufficient). +#ifndef CFG_TUD_CI_HS_VBUS_CHARGE + #ifndef CFG_TUD_CI_HS_VBUS_CHARGE_DEFAULT + #define CFG_TUD_CI_HS_VBUS_CHARGE_DEFAULT 0 + #endif + + #define CFG_TUD_CI_HS_VBUS_CHARGE CFG_TUD_CI_HS_VBUS_CHARGE_DEFAULT +#endif + // Enable DWC2 Slave mode for host #ifndef CFG_TUH_DWC2_SLAVE_ENABLE #ifndef CFG_TUH_DWC2_SLAVE_ENABLE_DEFAULT @@ -590,9 +602,22 @@ // List of product IDs that can use the FTDI CDC driver. 0x0403 is FTDI's VID #ifndef CFG_TUH_CDC_FTDI_VID_PID_LIST #define CFG_TUH_CDC_FTDI_VID_PID_LIST \ - {0x0403, 0x6001}, {0x0403, 0x6006}, {0x0403, 0x6010}, {0x0403, 0x6011}, \ - {0x0403, 0x6014}, {0x0403, 0x6015}, {0x0403, 0x8372}, {0x0403, 0xFBFA}, \ - {0x0403, 0xCD18} + {0x0403, 0x6001}, /* Similar device to SIO above */ \ + {0x0403, 0x6006}, /* FTDI's alternate PID for above */ \ + {0x0403, 0x6010}, /* Dual channel device */ \ + {0x0403, 0x6011}, /* Quad channel hi-speed device */ \ + {0x0403, 0x6014}, /* Single channel hi-speed device */ \ + {0x0403, 0x6015}, /* FT-X series (FT201X, FT230X, FT231X, etc) */ \ + {0x0403, 0x6040}, /* Dual channel hi-speed device with PD */ \ + {0x0403, 0x6041}, /* Quad channel hi-speed device with PD */ \ + {0x0403, 0x6042}, /* Dual channel hi-speed device with PD */ \ + {0x0403, 0x6043}, /* Quad channel hi-speed device with PD */ \ + {0x0403, 0x6044}, /* Dual channel hi-speed device with PD */ \ + {0x0403, 0x6045}, /* Dual channel hi-speed device with PD */ \ + {0x0403, 0x6048}, /* Quad channel automotive grade hi-speed device */ \ + {0x0403, 0x8372}, /* Product Id SIO application of 8U100AX */ \ + {0x0403, 0xFBFA}, /* Product ID for FT232RL */ \ + {0x0403, 0xCD18}, /* ??? */ #endif // CP210X is not part of CDC class, only to re-use CDC driver API @@ -603,7 +628,9 @@ // List of product IDs that can use the CP210X CDC driver. 0x10C4 is Silicon Labs' VID #ifndef CFG_TUH_CDC_CP210X_VID_PID_LIST #define CFG_TUH_CDC_CP210X_VID_PID_LIST \ - {0x10C4, 0xEA60}, {0x10C4, 0xEA70} + { 0x10C4, 0xEA60 }, /* Silicon Labs factory default */ \ + { 0x10C4, 0xEA61 }, /* Silicon Labs factory default */ \ + { 0x10C4, 0xEA70 } /* Silicon Labs Dual Port factory default */ #endif #ifndef CFG_TUH_CDC_CH34X @@ -623,6 +650,24 @@ { 0x9986, 0x7523 } /* overtaken from Linux Kernel driver /drivers/usb/serial/ch341.c */ #endif +#ifndef CFG_TUH_CDC_PL2303 + // PL2303 is not part of CDC class, only to re-use CDC driver API + #define CFG_TUH_CDC_PL2303 0 +#endif + +#ifndef CFG_TUH_CDC_PL2303_VID_PID_QUIRKS_LIST + // List of product IDs that can use the PL2303 CDC driver + #define CFG_TUH_CDC_PL2303_VID_PID_LIST \ + { 0x067b, 0x2303 }, /* initial 2303 */ \ + { 0x067b, 0x2304 }, /* TB */ \ + { 0x067b, 0x23a3 }, /* GC */ \ + { 0x067b, 0x23b3 }, /* GB */ \ + { 0x067b, 0x23c3 }, /* GT */ \ + { 0x067b, 0x23d3 }, /* GL */ \ + { 0x067b, 0x23e3 }, /* GE */ \ + { 0x067b, 0x23f3 } /* GS */ +#endif + #ifndef CFG_TUH_HID #define CFG_TUH_HID 0 #endif diff --git a/test/fuzz/device/net/Makefile b/test/fuzz/device/net/Makefile index 4e99604ad..2161ad3f1 100644 --- a/test/fuzz/device/net/Makefile +++ b/test/fuzz/device/net/Makefile @@ -1,5 +1,3 @@ -DEPS_SUBMODULES += lib/lwip - include ../../make.mk # suppress warning caused by lwip diff --git a/test/fuzz/make.mk b/test/fuzz/make.mk index b7b6d6a75..e9aa80bf1 100644 --- a/test/fuzz/make.mk +++ b/test/fuzz/make.mk @@ -124,11 +124,5 @@ endif # Log level is mapped to TUSB DEBUG option ifneq ($(LOG),) - CMAKE_DEFSYM += -DLOG=$(LOG) CFLAGS += -DCFG_TUSB_DEBUG=$(LOG) endif - -# Logger: default is uart, can be set to rtt or swo -ifneq ($(LOGGER),) - CMAKE_DEFSYM += -DLOGGER=$(LOGGER) -endif diff --git a/test/fuzz/rules.mk b/test/fuzz/rules.mk index ee91c706d..562969663 100644 --- a/test/fuzz/rules.mk +++ b/test/fuzz/rules.mk @@ -142,7 +142,7 @@ endif # get depenecies .PHONY: get-deps get-deps: - $(PYTHON) $(TOP)/tools/get_deps.py $(DEPS_SUBMODULES) + $(PYTHON) $(TOP)/tools/get_deps.py $(FAMILY) size: $(BUILD)/$(PROJECT) -@echo '' diff --git a/test/hil/hil_test.py b/test/hil/hil_test.py index a9f5dc1e1..f292bca15 100755 --- a/test/hil/hil_test.py +++ b/test/hil/hil_test.py @@ -81,7 +81,7 @@ def get_serial_dev(id, vendor_str, product_str, ifnum): return f'/dev/serial/by-id/usb-{vendor_str}_{product_str}_{id}-if{ifnum:02d}' else: # just use id: mostly for cp210x/ftdi flasher - pattern = f'/dev/serial/by-id/usb-*_{id}-if{ifnum:02d}*' + pattern = f'/dev/serial/by-id/usb-*_{id}-if*' port_list = glob.glob(pattern) return port_list[0] @@ -98,20 +98,18 @@ def get_hid_dev(id, vendor_str, product_str, event): def open_serial_dev(port): timeout = ENUM_TIMEOUT ser = None - while timeout: + while timeout > 0: if os.path.exists(port): try: - # slight delay since kernel may occupy the port briefly - time.sleep(0.5) - timeout = timeout - 0.5 ser = serial.Serial(port, baudrate=115200, timeout=5) break except serial.SerialException: + print(f'serial {port} not reaady {timeout} sec') pass - time.sleep(0.5) - timeout = timeout - 0.5 + time.sleep(0.1) + timeout -= 0.1 - assert timeout, f'Cannot open port f{port}' if os.path.exists(port) else f'Port {port} not existed' + assert timeout > 0, f'Cannot open port f{port}' if os.path.exists(port) else f'Port {port} not existed' return ser @@ -119,7 +117,7 @@ def read_disk_file(uid, lun, fname): # open_fs("fat://{dev}) require 'pip install pyfatfs' dev = get_disk_dev(uid, 'TinyUSB', lun) timeout = ENUM_TIMEOUT - while timeout: + while timeout > 0: if os.path.exists(dev): fat = fs.open_fs(f'fat://{dev}?read_only=true') try: @@ -132,7 +130,7 @@ def read_disk_file(uid, lun, fname): time.sleep(1) timeout -= 1 - assert timeout, f'Storage {dev} not existed' + assert timeout > 0, f'Storage {dev} not existed' return None @@ -202,14 +200,14 @@ def reset_stflash(board): def flash_openocd(board, firmware): flasher = board['flasher'] ret = run_cmd(f'openocd -c "tcl_port disabled" -c "gdb_port disabled" -c "adapter serial {flasher["uid"]}" ' - f'{flasher["args"]} -c init -c halt -c "program {firmware}.elf verify" -c reset -c exit') + f'{flasher["args"]} -c "init; halt; program {firmware}.elf verify; reset; exit"') return ret def reset_openocd(board): flasher = board['flasher'] ret = run_cmd(f'openocd -c "tcl_port disabled" -c "gdb_port disabled" -c "adapter serial {flasher["uid"]}" ' - f'{flasher["args"]} -c "reset exit"') + f'{flasher["args"]} -c "init; reset run; exit"') return ret @@ -304,11 +302,11 @@ def test_dual_host_info_to_device_cdc(board): ser = open_serial_dev(port) # read from cdc, first line should contain vid/pid and serial - data = ser.read(1000) + data = ser.read(10000) ser.close() if len(data) == 0: assert False, 'No data from device' - lines = data.decode('utf-8').splitlines() + lines = data.decode('utf-8', errors='ignore').splitlines() enum_dev_sn = [] for l in lines: @@ -319,6 +317,7 @@ def test_dual_host_info_to_device_cdc(board): if set(declared_devs) != set(enum_dev_sn): failed_msg = f'Expected {declared_devs}, Enumerated {enum_dev_sn}' + print('\n'.join(lines)) assert False, failed_msg return 0 @@ -337,12 +336,12 @@ def test_host_device_info(board): ret = globals()[f'reset_{flasher["name"].lower()}'](board) assert ret.returncode == 0, 'Failed to reset device' - data = ser.read(1000) + data = ser.read(10000) ser.close() if len(data) == 0: assert False, 'No data from device' + lines = data.decode('utf-8', errors='ignore').splitlines() - lines = data.decode('utf-8').splitlines() enum_dev_sn = [] for l in lines: vid_pid_sn = re.search(r'ID ([0-9a-fA-F]+):([0-9a-fA-F]+) SN (\w+)', l) @@ -352,8 +351,8 @@ def test_host_device_info(board): if set(declared_devs) != set(enum_dev_sn): failed_msg = f'Expected {declared_devs}, Enumerated {enum_dev_sn}' + print('\n'.join(lines)) assert False, failed_msg - return 0 @@ -419,7 +418,7 @@ def test_device_dfu(board): # Wait device enum timeout = ENUM_TIMEOUT - while timeout: + while timeout > 0: ret = run_cmd(f'dfu-util -l') stdout = ret.stdout.decode() if f'serial="{uid}"' in stdout and 'Found DFU: [cafe:4000]' in stdout: @@ -427,7 +426,7 @@ def test_device_dfu(board): time.sleep(1) timeout = timeout - 1 - assert timeout, 'Device not available' + assert timeout > 0, 'Device not available' f_dfu0 = f'dfu0_{uid}' f_dfu1 = f'dfu1_{uid}' @@ -460,7 +459,7 @@ def test_device_dfu_runtime(board): # Wait device enum timeout = ENUM_TIMEOUT - while timeout: + while timeout > 0: ret = run_cmd(f'dfu-util -l') stdout = ret.stdout.decode() if f'serial="{uid}"' in stdout and 'Found Runtime: [cafe:4000]' in stdout: @@ -468,7 +467,7 @@ def test_device_dfu_runtime(board): time.sleep(1) timeout = timeout - 1 - assert timeout, 'Device not available' + assert timeout > 0, 'Device not available' def test_device_hid_boot_interface(board): @@ -478,13 +477,13 @@ def test_device_hid_boot_interface(board): mouse2 = get_hid_dev(uid, 'TinyUSB', 'TinyUSB_Device', 'if01-mouse') # Wait device enum timeout = ENUM_TIMEOUT - while timeout: + while timeout > 0: if os.path.exists(kbd) and os.path.exists(mouse1) and os.path.exists(mouse2): break time.sleep(1) timeout = timeout - 1 - assert timeout, 'HID device not available' + assert timeout > 0, 'HID device not available' def test_device_hid_composite_freertos(id): @@ -515,6 +514,63 @@ host_test = [ ] +def test_example(board, f1, example): + """ + Test example firmware + :param board: board dict + :param f1: flags on + :param example: example name + :return: 0 if success/skip, 1 if failed + """ + name = board['name'] + err_count = 0 + + f1_str = "" + if f1 != "": + f1_str = '-f1_' + f1.replace(' ', '_') + + fw_dir = f'{TINYUSB_ROOT}/cmake-build/cmake-build-{name}{f1_str}/{example}' + if not os.path.exists(fw_dir): + fw_dir = f'{TINYUSB_ROOT}/examples/cmake-build-{name}{f1_str}/{example}' + fw_name = f'{fw_dir}/{os.path.basename(example)}' + print(f'{name+f1_str:40} {example:30} ... ', end='') + + if not os.path.exists(fw_dir) or not (os.path.exists(f'{fw_name}.elf') or os.path.exists(f'{fw_name}.bin')): + print('Skip (no binary)') + return 0 + + if verbose: + print(f'Flashing {fw_name}.elf') + + # flash firmware. It may fail randomly, retry a few times + max_rety = 3 + for i in range(max_rety): + ret = globals()[f'flash_{board["flasher"]["name"].lower()}'](board, fw_name) + if ret.returncode == 0: + try: + globals()[f'test_{example.replace("/", "_")}'](board) + print('OK') + break + except Exception as e: + if i == max_rety - 1: + err_count += 1 + print(STATUS_FAILED) + print(f' {e}') + else: + print() + print(f' Test failed: {e}, retry {i+2}/{max_rety}') + time.sleep(1) + else: + print(f'Flashing failed, retry {i+2}/{max_rety}') + time.sleep(1) + + if ret.returncode != 0: + err_count += 1 + print(f'Flash {STATUS_FAILED}') + + return err_count + + def test_board(board): name = board['name'] flasher = board['flasher'] @@ -538,54 +594,17 @@ def test_board(board): test_list.remove(skip) print(f'{name:25} {skip:30} ... Skip') - # board_test is added last to disable board's usb - test_list.append('device/board_test') - err_count = 0 flags_on_list = [""] if 'build' in board and 'flags_on' in board['build']: flags_on_list = board['build']['flags_on'] for f1 in flags_on_list: - f1_str = "" - if f1 != "": - f1_str = '-f1_' + f1.replace(' ', '_') for test in test_list: - fw_dir = f'{TINYUSB_ROOT}/cmake-build/cmake-build-{name}{f1_str}/{test}' - if not os.path.exists(fw_dir): - fw_dir = f'{TINYUSB_ROOT}/examples/cmake-build-{name}{f1_str}/{test}' - fw_name = f'{fw_dir}/{os.path.basename(test)}' - print(f'{name+f1_str:40} {test:30} ... ', end='') + err_count += test_example(board, f1, test) - if not os.path.exists(fw_dir) or not (os.path.exists(f'{fw_name}.elf') or os.path.exists(f'{fw_name}.bin')): - print('Skip (no binary)') - continue - - # flash firmware. It may fail randomly, retry a few times - max_rety = 2 - for i in range(max_rety): - ret = globals()[f'flash_{flasher["name"].lower()}'](board, fw_name) - if ret.returncode == 0: - try: - globals()[f'test_{test.replace("/", "_")}'](board) - print('OK') - break - except Exception as e: - if i == max_rety - 1: - err_count += 1 - print(STATUS_FAILED) - print(f' {e}') - else: - print() - print(f' Test failed: {e}, retry {i+1}') - time.sleep(1) - else: - print(f'Flashing failed, retry {i+1}') - time.sleep(1) - - if ret.returncode != 0: - err_count += 1 - print(f'Flash {STATUS_FAILED}') + # flash board_test last to disable board's usb + test_example(board, flags_on_list[0], 'device/board_test') return err_count diff --git a/test/hil/tinyusb.json b/test/hil/tinyusb.json index 7393226eb..11b118cea 100644 --- a/test/hil/tinyusb.json +++ b/test/hil/tinyusb.json @@ -21,16 +21,18 @@ "name": "espressif_s3_devkitm", "uid": "84F703C084E4", "build" : { - "flags_on": ["", "CFG_TUD_DWC2_DMA_ENABLE"] + "flags_on": ["", "CFG_TUD_DWC2_DMA_ENABLE CFG_TUH_DWC2_DMA_ENABLE"] }, "tests": { - "only": ["device/cdc_msc_freertos", "device/hid_composite_freertos"] + "only": ["device/cdc_msc_freertos", "device/hid_composite_freertos", "host/device_info"], + "dev_attached": [{"vid_pid": "1a86_55d4", "serial": "52D2005402"}] }, "flasher": { "name": "esptool", "uid": "3ea619acd1cdeb11a0a0b806e93fd3f1", "args": "-b 1500000" - } + }, + "comment": "Use TS3USB30 mux to test both device and host" }, { "name": "feather_nrf52840_express", @@ -44,23 +46,11 @@ "args": "-device nrf52840_xxaa" } }, - { - "name": "max32666fthr", - "uid": "0C81464124010B20FF0A08CC2C", - "tests": { - "device": true, "host": false, "dual": false - }, - "flasher": { - "name": "openocd_adi", - "uid": "E6614C311B597D32", - "args": "-f interface/cmsis-dap.cfg -f target/max32665.cfg" - } - }, { "name": "metro_m4_express", "uid": "9995AD485337433231202020FF100A34", "tests": { - "device": true, "host": false, "dual": false, + "device": true, "host": false, "dual": true, "dev_attached": [{"vid_pid": "1a86_55d4", "serial": "52D2002130"}] }, "flasher": { @@ -69,6 +59,19 @@ "args": "-device ATSAMD51J19" } }, + { + "name": "mimxrt1064_evk", + "uid": "BAE96FB95AFA6DBB8F00005002001200", + "tests": { + "device": true, "host": true, "dual": true, + "dev_attached": [{"vid_pid": "1a86_55d4", "serial": "52D2023299"}] + }, + "flasher": { + "name": "jlink", + "uid": "000725299165", + "args": "-device MIMXRT1064xxx6A" + } + }, { "name": "lpcxpresso11u37", "uid": "17121919", @@ -98,8 +101,11 @@ { "name": "raspberry_pi_pico", "uid": "E6614C311B764A37", + "build" : { + "flags_on": ["CFG_TUH_RPI_PIO_USB"] + }, "tests": { - "device": true, "host": false, "dual": false, + "device": true, "host": true, "dual": true, "dev_attached": [{"vid_pid": "1a86_55d4", "serial": "52D2002470"}] }, "flasher": { @@ -108,11 +114,28 @@ "args": "-f interface/cmsis-dap.cfg -f target/rp2040.cfg -c \"adapter speed 5000\"" } }, + { + "name": "raspberry_pi_pico_w", + "uid": "E6614C311B764A37", + "tests": { + "device": false, "host": true, "dual": false, + "dev_attached": [{"vid_pid": "1a86_55d4", "serial": "52D2023934"}] + }, + "flasher": { + "name": "openocd", + "uid": "E6633861A3819D38", + "args": "-f interface/cmsis-dap.cfg -f target/rp2040.cfg -c \"adapter speed 5000\"" + }, + "comment": "Test native host" + }, { "name": "raspberry_pi_pico2", "uid": "560AE75E1C7152C9", + "build" : { + "flags_on": ["CFG_TUH_RPI_PIO_USB"] + }, "tests": { - "device": true, "host": false, "dual": false, + "device": true, "host": true, "dual": true, "dev_attached": [{"vid_pid": "1a86_55d4", "serial": "533D004242"}] }, "flasher": { @@ -157,9 +180,9 @@ "device": true, "host": false, "dual": false }, "flasher": { - "name": "stlink", + "name": "openocd", "uid": "004C00343137510F39383538", - "args": "" + "args": "-f interface/stlink.cfg -f target/stm32h7x.cfg" } }, { @@ -176,6 +199,18 @@ } ], "boards-skip": [ + { + "name": "max32666fthr", + "uid": "0C81464124010B20FF0A08CC2C", + "tests": { + "device": true, "host": false, "dual": false + }, + "flasher": { + "name": "openocd_adi", + "uid": "E6614C311B597D32", + "args": "-f interface/cmsis-dap.cfg -f target/max32665.cfg" + } + }, { "name": "stm32f769disco", "uid": "21002F000F51363531383437", diff --git a/test/unit-test/project.yml b/test/unit-test/project.yml index 7fbbabfe6..6c86b0205 100644 --- a/test/unit-test/project.yml +++ b/test/unit-test/project.yml @@ -1,102 +1,226 @@ +# ========================================================================= +# Ceedling - Test-Centered Build System for C +# ThrowTheSwitch.org +# Copyright (c) 2010-25 Mike Karlesky, Mark VanderVoord, & Greg Williams +# SPDX-License-Identifier: MIT +# ========================================================================= + --- - -# Notes: -# Sample project C code is not presently written to produce a release artifact. -# As such, release build options are disabled. -# This sample, therefore, only demonstrates running a collection of unit tests. - :project: - :use_exceptions: TRUE + # how to use ceedling. If you're not sure, leave this as `gem` and `?` + :which_ceedling: gem + :ceedling_version: 1.0.0 + :verbosity: 3 + + # optional features. If you don't need them, keep them turned off for performance :use_mocks: TRUE - :use_test_preprocessor: TRUE - :use_auxiliary_dependencies: TRUE - :use_deep_dependencies: TRUE + :use_test_preprocessor: :mocks # options are :none, :mocks, :tests, or :all + :use_deep_dependencies: :all # options are :none, :mocks, :tests, or :all + :use_backtrace: :simple # options are :none, :simple, or :gdb + :use_decorators: :auto # decorate Ceedling's output text. options are :auto, :all, or :none + + # tweak the way ceedling handles automatic tasks :build_root: _build -# :release_build: TRUE :test_file_prefix: test_ - :which_ceedling: vendor/ceedling - :ceedling_version: 0.31.1 :default_tasks: - test:all -#:test_build: -# :use_assembly: TRUE + # performance options. If your tools start giving mysterious errors, consider + # dropping this to 1 to force single-tasking + :test_threads: 8 + :compile_threads: 8 -#:release_build: -# :output: MyApp.out -# :use_assembly: FALSE + # enable release build (more details in release_build section below) + :release_build: FALSE -:environment: +# Specify where to find mixins and any that should be enabled automatically +:mixins: + :enabled: [] + :load_paths: [] +# further details to configure the way Ceedling handles test code +:test_build: + :use_assembly: FALSE + +:test_runner: + # Insert additional #include statements in a generated runner + :includes: + - osal.h + +# further details to configure the way Ceedling handles release code +:release_build: + :output: MyApp.out + :use_assembly: FALSE + :artifacts: [] + +# Plugins are optional Ceedling features which can be enabled. Ceedling supports +# a variety of plugins which may effect the way things are compiled, reported, +# or may provide new command options. Refer to the readme in each plugin for +# details on how to use it. +:plugins: + :load_paths: [] + :enabled: + #- beep # beeps when finished, so you don't waste time waiting for ceedling + - module_generator # handy for quickly creating source, header, and test templates + #- gcov # test coverage using gcov. Requires gcc, gcov, and a coverage analyzer like gcovr + #- bullseye # test coverage using bullseye. Requires bullseye for your platform + #- command_hooks # write custom actions to be called at different points during the build process + #- compile_commands_json_db # generate a compile_commands.json file + #- dependencies # automatically fetch 3rd party libraries, etc. + #- subprojects # managing builds and test for static libraries + #- fake_function_framework # use FFF instead of CMock + + # Report options (You'll want to choose one stdout option, but may choose multiple stored options if desired) + #- report_build_warnings_log + #- report_tests_gtestlike_stdout + #- report_tests_ide_stdout + #- report_tests_log_factory + - report_tests_pretty_stdout + #- report_tests_raw_output_log + #- report_tests_teamcity_stdout + +# Specify which reports you'd like from the log factory +:report_tests_log_factory: + :reports: + - json + - junit + - cppunit + - html + +# override the default extensions for your system and toolchain :extension: + #:header: .h + #:source: .c + #:assembly: .s + #:dependencies: .d + #:object: .o :executable: .out + #:testpass: .pass + #:testfail: .fail + #:subprojects: .a +# This is where Ceedling should look for your source and test files. +# see documentation for the many options for specifying this. :paths: :test: - +:test/** - -:test/support :source: - ../../src/** + :include: + - ../../src/** :support: - test/support + :libraries: [] +# You can even specify specific files to add or remove from your test +# and release collections. Usually it's better to use paths and let +# Ceedling do the work for you! +:files: + :test: [] + :source: [] + +# Compilation symbols to be injected into builds +# See documentation for advanced options: +# - Test name matchers for different symbols per test executable build +# - Referencing symbols in multiple lists using advanced YAML +# - Specifying symbols used during test preprocessing :defines: - # in order to add common defines: - # 1) remove the trailing [] from the :common: section - # 2) add entries to the :common: section (e.g. :test: has TEST defined) - :common: &common_defines [] :test: - _UNITY_TEST_ - #- *common_defines - :test_preprocess: - - _UNITY_TEST_ - #- *common_defines + :release: [] + # Enable to inject name of a test as a unique compilation symbol into its respective executable build. + :use_test_definition: FALSE + +# Configure additional command line flags provided to tools used in each build step +# :flags: +# :release: +# :compile: # Add '-Wall' and '--02' to compilation of all files in release target +# - -Wall +# - --O2 +# :test: +# :compile: +# '(_|-)special': # Add '-pedantic' to compilation of all files in all test executables with '_special' or '-special' in their names +# - -pedantic +# '*': # Add '-foo' to compilation of all files in all test executables +# - -foo + +# Configuration Options specific to CMock. See CMock docs for details :cmock: - :mock_prefix: mock_ - :when_no_prototypes: :warn - :enforce_strict_ordering: TRUE - :plugins: + # Core configuration + :plugins: # What plugins should be used by CMock? - :ignore - :ignore_arg - :return_thru_ptr - :callback - :array - :treat_as: + :verbosity: 2 # the options being 0 errors only, 1 warnings and errors, 2 normal info, 3 verbose + :when_no_prototypes: :warn # the options being :ignore, :warn, or :error + + # File configuration + :skeleton_path: '' # Subdirectory to store stubs when generated (default: '') + :mock_prefix: 'mock_' # Prefix to append to filenames for mocks + :mock_suffix: '' # Suffix to append to filenames for mocks + + # Parser configuration + :strippables: ['(?:__attribute__\s*\([ (]*.*?[ )]*\)+)'] + :attributes: + - __ramfunc + - __irq + - __fiq + - register + - extern + :c_calling_conventions: + - __stdcall + - __cdecl + - __fastcall + :treat_externs: :exclude # the options being :include or :exclud + :treat_inlines: :exclude # the options being :include or :exclud + + # Type handling configuration + #:unity_helper_path: '' # specify a string of where to find a unity_helper.h file to discover custom type assertions + :treat_as: # optionally add additional types to map custom types uint8: HEX8 uint16: HEX16 uint32: UINT32 int8: INT8 bool: UINT8 + #:treat_as_array: {} # hint to cmock that these types are pointers to something + #:treat_as_void: [] # hint to cmock that these types are actually aliases of void + :memcmp_if_unknown: true # allow cmock to use the memory comparison assertions for unknown types + :when_ptr: :compare_data # hint to cmock how to handle pointers in general, the options being :compare_ptr, :compare_data, or :smart -# Add -gcov to the plugins list to make sure of the gcov plugin -# You will need to have gcov and gcovr both installed to make it work. -# For more information on these options, see docs in plugins/gcov -:gcov: - :html_report: TRUE - :html_report_type: detailed - :html_medium_threshold: 75 - :html_high_threshold: 90 - :xml_report: FALSE + # Mock generation configuration + :weak: '' # Symbol to use to declare weak functions + :enforce_strict_ordering: true # Do we want cmock to enforce ordering of all function calls? + :fail_on_unexpected_calls: true # Do we want cmock to fail when it encounters a function call that wasn't expected? + :callback_include_count: true # Do we want cmock to include the number of calls to this callback, when using callbacks? + :callback_after_arg_check: false # Do we want cmock to enforce an argument check first when using a callback? + #:includes: [] # You can add additional includes here, or specify the location with the options below + #:includes_h_pre_orig_header: [] + #:includes_h_post_orig_header: [] + #:includes_c_pre_header: [] + #:includes_c_post_header: [] + #:array_size_type: [] # Specify a type or types that should be used for array lengths + #:array_size_name: 'size|len' # Specify a name or names that CMock might automatically recognize as the length of an array + :exclude_setjmp_h: false # Don't use setjmp when running CMock. Note that this might result in late reporting or out-of-order failures. -:tools: - :test_compiler: - :executable: gcc - :name: 'gcc compiler' - :arguments: - - -I"$": COLLECTION_PATHS_TEST_TOOLCHAIN_INCLUDE #expands to -I search paths - - -I"$": COLLECTION_PATHS_TEST_SUPPORT_SOURCE_INCLUDE_VENDOR #expands to -I search paths - - -D$: COLLECTION_DEFINES_TEST_AND_VENDOR #expands to all -D defined symbols - #- -fsanitize=address - - -c ${1} #source code input file (Ruby method call param list sub) - - -o ${2} #object file output (Ruby method call param list sub) - :test_linker: - :executable: gcc - :name: 'gcc linker' - :arguments: - #- -fsanitize=address - - ${1} #list of object files to link (Ruby method call param list sub) - - -o ${2} #executable file output (Ruby method call param list sub) +# Configuration options specific to Unity. +:unity: + :defines: + - UNITY_EXCLUDE_FLOAT + +# You can optionally have ceedling create environment variables for you before +# performing the rest of its tasks. +:environment: [] +# :environment: +# # List enforces order allowing later to reference earlier with inline Ruby substitution +# - :var1: value +# - :var2: another value +# - :path: # Special PATH handling with platform-specific path separators +# - #{ENV['PATH']} # Environment variables can use inline Ruby substitution +# - /another/path/to/include # LIBRARIES # These libraries are automatically injected into the build process. Those specified as @@ -104,19 +228,210 @@ # tests or releases. These options are MERGED with the options in supplemental yaml files. :libraries: :placement: :end - :flag: "${1}" # or "-L ${1}" for example - :common: &common_libraries [] - :test: - #- *common_libraries - :release: - #- *common_libraries + :flag: "-l${1}" + :path_flag: "-L ${1}" + :system: [] # for example, you might list 'm' to grab the math library + :test: [] + :release: [] -:plugins: - :load_paths: - - vendor/ceedling/plugins - :enabled: - - stdout_pretty_tests_report - - module_generator - - raw_output_report - - colour_report +################################################################ +# PLUGIN CONFIGURATION +################################################################ + +# Add -gcov to the plugins list to make sure of the gcov plugin +# You will need to have gcov and gcovr both installed to make it work. +# For more information on these options, see docs in plugins/gcov +:gcov: + :summaries: TRUE # Enable simple coverage summaries to console after tests + :report_task: FALSE # Disabled dedicated report generation task (this enables automatic report generation) + :utilities: + - gcovr # Use gcovr to create the specified reports (default). + #- ReportGenerator # Use ReportGenerator to create the specified reports. + :reports: # Specify one or more reports to generate. + # Make an HTML summary report. + - HtmlBasic + # - HtmlDetailed + # - Text + # - Cobertura + # - SonarQube + # - JSON + # - HtmlInline + # - HtmlInlineAzure + # - HtmlInlineAzureDark + # - HtmlChart + # - MHtml + # - Badges + # - CsvSummary + # - Latex + # - LatexSummary + # - PngChart + # - TeamCitySummary + # - lcov + # - Xml + # - XmlSummary + :gcovr: + # :html_artifact_filename: TestCoverageReport.html + # :html_title: Test Coverage Report + :html_medium_threshold: 75 + :html_high_threshold: 90 + # :html_absolute_paths: TRUE + # :html_encoding: UTF-8 + +# :module_generator: +# :project_root: ./ +# :source_root: source/ +# :inc_root: includes/ +# :test_root: tests/ +# :naming: :snake #options: :bumpy, :camel, :caps, or :snake +# :includes: +# :tst: [] +# :src: [] +# :boilerplates: +# :src: "" +# :inc: "" +# :tst: "" + +# :dependencies: +# :libraries: +# - :name: WolfSSL +# :source_path: third_party/wolfssl/source +# :build_path: third_party/wolfssl/build +# :artifact_path: third_party/wolfssl/install +# :fetch: +# :method: :zip +# :source: \\shared_drive\third_party_libs\wolfssl\wolfssl-4.2.0.zip +# :environment: +# - CFLAGS+=-DWOLFSSL_DTLS_ALLOW_FUTURE +# :build: +# - "autoreconf -i" +# - "./configure --enable-tls13 --enable-singlethreaded" +# - make +# - make install +# :artifacts: +# :static_libraries: +# - lib/wolfssl.a +# :dynamic_libraries: +# - lib/wolfssl.so +# :includes: +# - include/** + +# :subprojects: +# :paths: +# - :name: libprojectA +# :source: +# - ./subprojectA/source +# :include: +# - ./subprojectA/include +# :build_root: ./subprojectA/build +# :defines: [] + +# :command_hooks: +# :pre_mock_preprocess: +# :post_mock_preprocess: +# :pre_test_preprocess: +# :post_test_preprocess: +# :pre_mock_generate: +# :post_mock_generate: +# :pre_runner_generate: +# :post_runner_generate: +# :pre_compile_execute: +# :post_compile_execute: +# :pre_link_execute: +# :post_link_execute: +# :pre_test_fixture_execute: +# :post_test_fixture_execute: +# :pre_test: +# :post_test: +# :pre_release: +# :post_release: +# :pre_build: +# :post_build: +# :post_error: + +################################################################ +# TOOLCHAIN CONFIGURATION +################################################################ + +#:tools: +# Ceedling defaults to using gcc for compiling, linking, etc. +# As [:tools] is blank, gcc will be used (so long as it's in your system path) +# See documentation to configure a given toolchain for use +#:tools: +# :test_compiler: +# :executable: gcc +# :name: 'gcc compiler' +# :arguments: +# - -I"$": COLLECTION_PATHS_TEST_TOOLCHAIN_INCLUDE #expands to -I search paths +# - -I"$": COLLECTION_PATHS_TEST_SUPPORT_SOURCE_INCLUDE_VENDOR #expands to -I search paths +# - -D$: COLLECTION_DEFINES_TEST_AND_VENDOR #expands to all -D defined symbols +# #- -fsanitize=address +# - -c ${1} #source code input file (Ruby method call param list sub) +# - -o ${2} #object file output (Ruby method call param list sub) +# :test_linker: +# :executable: gcc +# :name: 'gcc linker' +# :arguments: +# #- -fsanitize=address +# - ${1} #list of object files to link (Ruby method call param list sub) +# - -o ${2} #executable file output (Ruby method call param list sub) +# :test_compiler: +# :executable: +# :arguments: [] +# :name: +# :optional: FALSE +# :test_linker: +# :executable: +# :arguments: [] +# :name: +# :optional: FALSE +# :test_assembler: +# :executable: +# :arguments: [] +# :name: +# :optional: FALSE +# :test_fixture: +# :executable: +# :arguments: [] +# :name: +# :optional: FALSE +# :test_includes_preprocessor: +# :executable: +# :arguments: [] +# :name: +# :optional: FALSE +# :test_file_preprocessor: +# :executable: +# :arguments: [] +# :name: +# :optional: FALSE +# :test_file_preprocessor_directives: +# :executable: +# :arguments: [] +# :name: +# :optional: FALSE +# :test_dependencies_generator: +# :executable: +# :arguments: [] +# :name: +# :optional: FALSE +# :release_compiler: +# :executable: +# :arguments: [] +# :name: +# :optional: FALSE +# :release_linker: +# :executable: +# :arguments: [] +# :name: +# :optional: FALSE +# :release_assembler: +# :executable: +# :arguments: [] +# :name: +# :optional: FALSE +# :release_dependencies_generator: +# :executable: +# :arguments: [] +# :name: +# :optional: FALSE ... diff --git a/test/unit-test/test/device/msc/test_msc_device.c b/test/unit-test/test/device/msc/test_msc_device.c index 55b690313..3ab46b0f9 100644 --- a/test/unit-test/test/device/msc/test_msc_device.c +++ b/test/unit-test/test/device/msc/test_msc_device.c @@ -32,8 +32,8 @@ #include "tusb_fifo.h" #include "tusb.h" #include "usbd.h" -TEST_FILE("usbd_control.c") -TEST_FILE("msc_device.c") +TEST_SOURCE_FILE("usbd_control.c") +TEST_SOURCE_FILE("msc_device.c") // Mock File #include "mock_dcd.h" diff --git a/test/unit-test/test/device/usbd/test_usbd.c b/test/unit-test/test/device/usbd/test_usbd.c index e7c6a8578..f0153da3f 100644 --- a/test/unit-test/test/device/usbd/test_usbd.c +++ b/test/unit-test/test/device/usbd/test_usbd.c @@ -29,7 +29,7 @@ #include "tusb_fifo.h" #include "tusb.h" #include "usbd.h" -TEST_FILE("usbd_control.c") +TEST_SOURCE_FILE("usbd_control.c") // Mock File #include "mock_dcd.h" diff --git a/test/unit-test/vendor/ceedling/bin/ceedling b/test/unit-test/vendor/ceedling/bin/ceedling deleted file mode 100644 index b317db2f1..000000000 --- a/test/unit-test/vendor/ceedling/bin/ceedling +++ /dev/null @@ -1,350 +0,0 @@ -#!/usr/bin/env ruby - -#these are always used -require 'rubygems' -require 'fileutils' - -# Check for the main project file (either the one defined in the ENV or the default) -main_filepath = ENV['CEEDLING_MAIN_PROJECT_FILE'] -project_found = (!main_filepath.nil? && File.exists?(main_filepath)) -if (!project_found) - main_filepath = "project.yml" - project_found = File.exists?(main_filepath) -end - -def is_windows? - return ((RbConfig::CONFIG['host_os'] =~ /mswin|mingw/) ? true : false) if defined?(RbConfig) - return ((Config::CONFIG['host_os'] =~ /mswin|mingw/) ? true : false) -end - -unless (project_found) -#===================================== We Do Not Have A Project ================================================ - - puts "Welcome to Ceedling!" - require 'thor' - - def here - File.dirname(__FILE__) + "/.." - end - - class CeedlingTasks < Thor - include Thor::Actions - - desc "new PROJECT_NAME", "create a new ceedling project" - method_option :docs, :type => :boolean, :default => false, :desc => "Add docs in project vendor directory" - method_option :local, :type => :boolean, :default => false, :desc => "Create a copy of Ceedling in the project vendor directory" - method_option :gitignore, :type => :boolean, :default => false, :desc => "Create a gitignore file for ignoring ceedling generated files" - method_option :no_configs, :type => :boolean, :default => false, :desc => "Don't install starter configuration files" - method_option :noconfigs, :type => :boolean, :default => false - - #deprecated: - method_option :no_docs, :type => :boolean, :default => false - method_option :nodocs, :type => :boolean, :default => false - method_option :as_gem, :type => :boolean, :default => false - method_option :asgem, :type => :boolean, :default => false - method_option :with_ignore, :type => :boolean, :default => false - method_option :withignore, :type => :boolean, :default => false - def new(name, silent = false) - copy_assets_and_create_structure(name, silent, false, options) - end - - desc "upgrade PROJECT_NAME", "upgrade ceedling for a project (not req'd if gem used)" - def upgrade(name, silent = false) - as_local = true - begin - require "yaml" - as_local = (YAML.load_file(File.join(name, "project.yml"))[:project][:which_ceedling] != 'gem') - rescue - raise "ERROR: Could not find valid project file '#{yaml_path}'" - end - found_docs = File.exists?( File.join(name, "docs", "CeedlingPacket.md") ) - copy_assets_and_create_structure(name, silent, true, {:upgrade => true, :no_configs => true, :local => as_local, :docs => found_docs}) - end - - no_commands do - def copy_assets_and_create_structure(name, silent=false, force=false, options = {}) - - puts "WARNING: --no_docs deprecated. It is now the default. Specify -docs if you want docs installed." if (options[:no_docs] || options[:nodocs]) - puts "WARNING: --as_gem deprecated. It is now the default. Specify -local if you want ceedling installed to this project." if (options[:as_gem] || options[:asgem]) - puts "WARNING: --with_ignore deprecated. It is now called -gitignore" if (options[:with_ignore] || options[:with_ignore]) - - use_docs = options[:docs] || false - use_configs = !(options[:no_configs] || options[:noconfigs] || false) - use_gem = !(options[:local]) - use_ignore = options[:gitignore] || false - is_upgrade = options[:upgrade] || false - - ceedling_path = File.join(name, 'vendor', 'ceedling') - source_path = File.join(name, 'src') - test_path = File.join(name, 'test') - test_support_path = File.join(name, 'test/support') - - # If it's not an upgrade, make sure we have the paths we expect - if (!is_upgrade) - [source_path, test_path, test_support_path].each do |d| - FileUtils.mkdir_p d - end - end - - # Generate gitkeep in test support path - FileUtils.touch(File.join(test_support_path, '.gitkeep')) - - # If documentation requested, create a place to dump them and do so - doc_path = "" - if use_docs - doc_path = use_gem ? File.join(name, 'docs') : File.join(ceedling_path, 'docs') - FileUtils.mkdir_p doc_path - - in_doc_path = lambda {|f| File.join(doc_path, f)} - - # Add documentation from main projects to list - doc_files = {} - ['docs','vendor/unity/docs','vendor/cmock/docs','vendor/cexception/docs'].each do |p| - Dir[ File.expand_path(File.join(here, p, '*.md')) ].each do |f| - doc_files[ File.basename(f) ] = f unless(doc_files.include? f) - end - end - - # Add documentation from plugins to list - Dir[ File.join(here, 'plugins/**/README.md') ].each do |plugin_path| - k = "plugin_" + plugin_path.split(/\\|\//)[-2] + ".md" - doc_files[ k ] = File.expand_path(plugin_path) - end - - # Copy all documentation - doc_files.each_pair do |k, v| - copy_file(v, in_doc_path.call(k), :force => force) - end - end - - # If installed locally to project, copy ceedling, unity, cmock, & supports to vendor - unless use_gem - FileUtils.mkdir_p ceedling_path - - #copy full folders from ceedling gem into project - %w{plugins lib bin}.map do |f| - {:src => f, :dst => File.join(ceedling_path, f)} - end.each do |f| - directory(f[:src], f[:dst], :force => force) - end - - # mark ceedling as an executable - File.chmod(0755, File.join(ceedling_path, 'bin', 'ceedling')) unless is_windows? - - #copy necessary subcomponents from ceedling gem into project - sub_components = [ - {:src => 'vendor/c_exception/lib/', :dst => 'vendor/c_exception/lib'}, - {:src => 'vendor/cmock/config/', :dst => 'vendor/cmock/config'}, - {:src => 'vendor/cmock/lib/', :dst => 'vendor/cmock/lib'}, - {:src => 'vendor/cmock/src/', :dst => 'vendor/cmock/src'}, - {:src => 'vendor/diy/lib', :dst => 'vendor/diy/lib'}, - {:src => 'vendor/unity/auto/', :dst => 'vendor/unity/auto'}, - {:src => 'vendor/unity/src/', :dst => 'vendor/unity/src'}, - ] - - sub_components.each do |c| - directory(c[:src], File.join(ceedling_path, c[:dst]), :force => force) - end - end - - # We're copying in a configuration file if we haven't said not to - if (use_configs) - dst_yaml = File.join(name, 'project.yml') - src_yaml = if use_gem - File.join(here, 'assets', 'project_as_gem.yml') - else - if is_windows? - copy_file(File.join('assets', 'ceedling.cmd'), File.join(name, 'ceedling.cmd'), :force => force) - else - copy_file(File.join('assets', 'ceedling'), File.join(name, 'ceedling'), :force => force) - File.chmod(0755, File.join(name, 'ceedling')) - end - File.join(here, 'assets', 'project_with_guts.yml') - end - - # Perform the actual clone of the config file, while updating the version - File.open(dst_yaml,'w') do |dst| - require File.expand_path(File.join(File.dirname(__FILE__),"..","lib","ceedling","version.rb")) - dst << File.read(src_yaml).gsub(":ceedling_version: '?'",":ceedling_version: #{Ceedling::Version::CEEDLING}") - puts " create #{dst_yaml}" - end - end - - # Copy the gitignore file if requested - if (use_ignore) - copy_file(File.join('assets', 'default_gitignore'), File.join(name, '.gitignore'), :force => force) - end - - unless silent - puts "\n" - puts "Project '#{name}' #{force ? "upgraded" : "created"}!" - puts " - Tool documentation is located in #{doc_path}" if use_docs - puts " - Execute 'ceedling help' from #{name} to view available test & build tasks" - puts '' - end - end - end - - desc "examples", "list available example projects" - def examples() - puts "Available sample projects:" - FileUtils.cd(File.join(here, "examples")) do - Dir["*"].each {|proj| puts " #{proj}"} - end - end - - desc "example PROJ_NAME [DEST]", "new specified example project (in DEST, if specified)" - def example(proj_name, dest=nil) - if dest.nil? then dest = proj_name end - - copy_assets_and_create_structure(dest, true, false, {:local=>true, :docs=>true}) - - dest_src = File.join(dest,'src') - dest_test = File.join(dest,'test') - dest_project = File.join(dest,'project.yml') - - directory "examples/#{proj_name}/src", dest_src - directory "examples/#{proj_name}/test", dest_test - remove_file dest_project - copy_file "examples/#{proj_name}/project.yml", dest_project - - puts "\n" - puts "Example project '#{proj_name}' created!" - puts " - Tool documentation is located in vendor/ceedling/docs" - puts " - Execute 'ceedling help' to view available test & build tasks" - puts '' - end - - desc "version", "return the version of the tools installed" - def version() - require File.expand_path(File.join(File.dirname(__FILE__),"..","lib","ceedling","version.rb")) - puts " Ceedling:: #{Ceedling::Version::CEEDLING}" - puts " CMock:: #{Ceedling::Version::CMOCK}" - puts " Unity:: #{Ceedling::Version::UNITY}" - puts " CException:: #{Ceedling::Version::CEXCEPTION}" - end - end - - if (ARGV[0] =~ /^\-T$/) - puts "\n(No Project Detected, Therefore Showing Options to Create Projects)" - CeedlingTasks.tasks.each_pair do |k,v| - puts v.usage.ljust(25,' ') + v.description - end - puts "\n" - else - CeedlingTasks.source_root here - CeedlingTasks.start - end - -#===================================== We Have A Project Already ================================================ -else - require 'yaml' - require 'rbconfig' - - #determine platform - platform = begin - case(RbConfig::CONFIG['host_os']) - when /mswin|mingw|cygwin/i - :mswin - when /darwin/ - :osx - else - :linux - end - rescue - :linux - end - - #create our default meta-runner option set - options = { - :pretest => nil, - :args => [], - :add_path => [], - :path_connector => (platform == :mswin) ? ";" : ":", - :graceful_fail => false, - :which_ceedling => (Dir.exists?("vendor/ceedling") ? "vendor/ceedling" : 'gem'), - :default_tasks => [ 'test:all' ], - :list_tasks => false - } - - #guess that we need a special script file first if it exists - if (platform == :mswin) - options[:pretest] = File.exists?("#{ platform.to_s }_setup.bat") ? "#{ platform.to_s }_setup.bat" : nil - else - options[:pretest] = File.exists?("#{ platform.to_s }_setup.sh") ? "source #{ platform.to_s }_setup.sh" : nil - end - - #merge in project settings if they can be found here - yaml_options = YAML.load_file(main_filepath) - if (yaml_options[:paths]) - options[:add_path] = yaml_options[:paths][:tools] || [] - else - options[:add_path] = [] - end - options[:graceful_fail] = yaml_options[:graceful_fail] if yaml_options[:graceful_fail] - options[:which_ceedling] = yaml_options[:project][:which_ceedling] if (yaml_options[:project] && yaml_options[:project][:which_ceedling]) - options[:default_tasks] = yaml_options[:default_tasks] if yaml_options[:default_tasks] - - #sort through command line options - ARGV.each do |v| - case(v) - when /^(?:new|examples?|templates?)$/ - puts "\nOops. You called ceedling with argument '#{v}'.\n" + - " This is an operation that will create a new project... \n" + - " but it looks like you're already in a project. If you really \n" + - " want to do this, try moving to an empty folder.\n\n" - abort - when /^help$/ - options[:list_tasks] = true - when /^-T$/ - options[:list_tasks] = true - when /^--tasks$/ - options[:list_tasks] = true - when /^project:(\w+)/ - ENV['CEEDLING_USER_PROJECT_FILE'] = "#{$1}.yml" - else - options[:args].push(v) - end - end - - #add to the path - if (options[:add_path] && !options[:add_path].empty?) - path = ENV["PATH"] - options[:add_path].each do |p| - f = File.expand_path(File.dirname(__FILE__),p) - path = (f + options[:path_connector] + path) unless path.include? f - end - ENV["PATH"] = path - end - - # Load Ceedling (either through the rakefile OR directly) - if (File.exists?("rakefile.rb")) - load 'rakefile.rb' - else - if (options[:which_ceedling] == 'gem') - require 'ceedling' - else - load "#{options[:which_ceedling]}/lib/ceedling.rb" - end - Ceedling.load_project - end - - Rake.application.standard_exception_handling do - if options[:list_tasks] - # Display helpful task list when requested. This required us to dig into Rake internals a bit - Rake.application.define_singleton_method(:name=) {|n| @name = n} - Rake.application.name = 'ceedling' - Rake.application.options.show_tasks = :tasks - Rake.application.options.show_task_pattern = /^(?!.*build).*$/ - Rake.application.display_tasks_and_comments() - else - task :default => options[:default_tasks] - - # Run our Tasks! - Rake.application.collect_command_line_tasks(options[:args]) - Rake.application.top_level - end - end - true -#=================================================================================================================== -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling.rb b/test/unit-test/vendor/ceedling/lib/ceedling.rb deleted file mode 100644 index 063cfddd5..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling.rb +++ /dev/null @@ -1,98 +0,0 @@ -## -# This module defines the interface for interacting with and loading a project -# with Ceedling. -module Ceedling - ## - # Returns the location where the gem is installed. - # === Return - # _String_ - The location where the gem lives. - def self.location - File.join( File.dirname(__FILE__), '..') - end - - ## - # Return the path to the "built-in" plugins. - # === Return - # _String_ - The path where the default plugins live. - def self.load_path - File.join( self.location, 'plugins') - end - - ## - # Return the path to the Ceedling Rakefile - # === Return - # _String_ - def self.rakefile - File.join( self.location, 'lib', 'ceedling', 'rakefile.rb' ) - end - - ## - # This method selects the project file that Ceedling will use by setting the - # CEEDLING_MAIN_PROJECT_FILE environment variable before loading the ceedling - # rakefile. A path supplied as an argument to this method will override the - # current value of the environment variable. If no path is supplied as an - # argument then the existing value of the environment variable is used. If - # the environment variable has not been set and no argument has been supplied - # then a default path of './project.yml' will be used. - # - # === Arguments - # +options+ _Hash_:: - # A hash containing the options for ceedling. Currently the following - # options are supported: - # * +config+ - The path to the project YAML configuration file. - # * +root+ - The root of the project directory. - # * +prefix+ - A prefix to prepend to plugin names in order to determine the - # corresponding gem name. - # * +plugins+ - The list of ceedling plugins to load - def self.load_project(options = {}) - # Make sure our path to the yaml file is setup - if options.has_key? :config - ENV['CEEDLING_MAIN_PROJECT_FILE'] = options[:config] - elsif ENV['CEEDLING_MAIN_PROJECT_FILE'].nil? - ENV['CEEDLING_MAIN_PROJECT_FILE'] = './project.yml' - end - - # Register the plugins - if options.has_key? :plugins - options[:plugins].each do |plugin| - register_plugin( plugin, options[:prefix] ) - end - end - - # Define the root of the project if specified - Object.const_set('PROJECT_ROOT', options[:root]) if options.has_key? :root - - # Load ceedling - load "#{self.rakefile}" - end - - ## - # Register a plugin for ceedling to use when a project is loaded. This method - # *must* be called prior to calling the _load_project_ method. - # - # This method is intended to be used for loading plugins distributed via the - # RubyGems mechanism. As such, the following gem structure is assumed for - # plugins. - # - # * The gem name must be prefixed with 'ceedling-' followed by the plugin - # name (ex. 'ceedling-bullseye') - # - # * The contents of the plugin must be installed into a subdirectory of - # the gem with the same name as the plugin (ex. 'bullseye/') - # - # === Arguments - # +name+ _String_:: The name of the plugin to load. - # +prefix+ _String_:: - # (optional, default = nil) The prefix to use for the full gem name. - def self.register_plugin(name, prefix=nil) - # Figure out the full name of the gem and location - prefix ||= 'ceedling-' - gem_name = prefix + name - gem_dir = Gem::Specification.find_by_name(gem_name).gem_dir() - - # Register the plugin with Ceedling - require 'ceedling/defaults' - DEFAULT_CEEDLING_CONFIG[:plugins][:enabled] << name - DEFAULT_CEEDLING_CONFIG[:plugins][:load_paths] << gem_dir - end -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/build_invoker_utils.rb b/test/unit-test/vendor/ceedling/lib/ceedling/build_invoker_utils.rb deleted file mode 100644 index 31abe6d99..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/build_invoker_utils.rb +++ /dev/null @@ -1,39 +0,0 @@ -require 'ceedling/constants' - -## -# Utilities for raiser and reporting errors during building. -class BuildInvokerUtils - - constructor :configurator, :streaminator - - ## - # Processes exceptions and tries to display a useful message for the user. - # - # ==== Attributes - # - # * _exception_: The exception given by a rescue statement. - # * _context_: A symbol representing where in the build the exception - # occurs. - # * _test_build_: A bool to signify if the exception occurred while building - # from test or source. - # - def process_exception(exception, context, test_build=true) - if (exception.message =~ /Don't know how to build task '(.+)'/i) - error_header = "ERROR: Rake could not find file referenced in source" - error_header += " or test" if (test_build) - error_header += ": '#{$1}'. Possible stale dependency." - - @streaminator.stderr_puts( error_header ) - - if (@configurator.project_use_deep_dependencies) - help_message = "Try fixing #include statements or adding missing file. Then run '#{REFRESH_TASK_ROOT}#{context.to_s}' task and try again." - @streaminator.stderr_puts( help_message ) - end - - raise '' - else - raise exception - end - end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/cacheinator.rb b/test/unit-test/vendor/ceedling/lib/ceedling/cacheinator.rb deleted file mode 100644 index fd7451fa7..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/cacheinator.rb +++ /dev/null @@ -1,47 +0,0 @@ - -class Cacheinator - - constructor :cacheinator_helper, :file_path_utils, :file_wrapper, :yaml_wrapper - - def cache_test_config(hash) - @yaml_wrapper.dump( @file_path_utils.form_test_build_cache_path( INPUT_CONFIGURATION_CACHE_FILE), hash ) - end - - def cache_release_config(hash) - @yaml_wrapper.dump( @file_path_utils.form_release_build_cache_path( INPUT_CONFIGURATION_CACHE_FILE ), hash ) - end - - - def diff_cached_test_file( filepath ) - cached_filepath = @file_path_utils.form_test_build_cache_path( filepath ) - - if (@file_wrapper.exist?( cached_filepath ) and (!@file_wrapper.compare( filepath, cached_filepath ))) - @file_wrapper.cp(filepath, cached_filepath, {:preserve => false}) - return filepath - elsif (!@file_wrapper.exist?( cached_filepath )) - @file_wrapper.cp(filepath, cached_filepath, {:preserve => false}) - return filepath - end - - return cached_filepath - end - - def diff_cached_test_config?(hash) - cached_filepath = @file_path_utils.form_test_build_cache_path(INPUT_CONFIGURATION_CACHE_FILE) - - return @cacheinator_helper.diff_cached_config?( cached_filepath, hash ) - end - - def diff_cached_test_defines?(files) - cached_filepath = @file_path_utils.form_test_build_cache_path(DEFINES_DEPENDENCY_CACHE_FILE) - - return @cacheinator_helper.diff_cached_defines?( cached_filepath, files ) - end - - def diff_cached_release_config?(hash) - cached_filepath = @file_path_utils.form_release_build_cache_path(INPUT_CONFIGURATION_CACHE_FILE) - - return @cacheinator_helper.diff_cached_config?( cached_filepath, hash ) - end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/cacheinator_helper.rb b/test/unit-test/vendor/ceedling/lib/ceedling/cacheinator_helper.rb deleted file mode 100644 index b7fa5863f..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/cacheinator_helper.rb +++ /dev/null @@ -1,35 +0,0 @@ - -class CacheinatorHelper - - constructor :file_wrapper, :yaml_wrapper - - def diff_cached_config?(cached_filepath, hash) - return false if ( not @file_wrapper.exist?(cached_filepath) ) - return true if (@yaml_wrapper.load(cached_filepath) != hash) - return false - end - - def diff_cached_defines?(cached_filepath, files) - changed_defines = false - current_defines = COLLECTION_DEFINES_TEST_AND_VENDOR.reject(&:empty?) - - current_dependencies = Hash[files.collect { |source| [source, current_defines.dup] }] - if not @file_wrapper.exist?(cached_filepath) - @yaml_wrapper.dump(cached_filepath, current_dependencies) - return changed_defines - end - - dependencies = @yaml_wrapper.load(cached_filepath) - common_dependencies = current_dependencies.select { |file, defines| dependencies.has_key?(file) } - - if dependencies.values_at(*common_dependencies.keys) != common_dependencies.values - changed_defines = true - end - - dependencies.merge!(current_dependencies) - @yaml_wrapper.dump(cached_filepath, dependencies) - - return changed_defines - end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/cmock_builder.rb b/test/unit-test/vendor/ceedling/lib/ceedling/cmock_builder.rb deleted file mode 100644 index 82ef96135..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/cmock_builder.rb +++ /dev/null @@ -1,15 +0,0 @@ -require 'cmock' - -class CmockBuilder - - attr_accessor :cmock - - def setup - @cmock = nil - end - - def manufacture(cmock_config) - @cmock = CMock.new(cmock_config) - end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/configurator.rb b/test/unit-test/vendor/ceedling/lib/ceedling/configurator.rb deleted file mode 100644 index 8dc11aa5a..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/configurator.rb +++ /dev/null @@ -1,381 +0,0 @@ -require 'ceedling/defaults' -require 'ceedling/constants' -require 'ceedling/file_path_utils' -require 'deep_merge' - - - -class Configurator - - attr_reader :project_config_hash, :script_plugins, :rake_plugins - attr_accessor :project_logging, :project_debug, :project_verbosity, :sanity_checks - - constructor(:configurator_setup, :configurator_builder, :configurator_plugins, :cmock_builder, :yaml_wrapper, :system_wrapper) do - @project_logging = false - @project_debug = false - @project_verbosity = Verbosity::NORMAL - @sanity_checks = TestResultsSanityChecks::NORMAL - end - - def setup - # special copy of cmock config to provide to cmock for construction - @cmock_config_hash = {} - - # note: project_config_hash is an instance variable so constants and accessors created - # in eval() statements in build() have something of proper scope and persistence to reference - @project_config_hash = {} - @project_config_hash_backup = {} - - @script_plugins = [] - @rake_plugins = [] - end - - - def replace_flattened_config(config) - @project_config_hash.merge!(config) - @configurator_setup.build_constants_and_accessors(@project_config_hash, binding()) - end - - - def store_config - @project_config_hash_backup = @project_config_hash.clone - end - - - def restore_config - @project_config_hash = @project_config_hash_backup - @configurator_setup.build_constants_and_accessors(@project_config_hash, binding()) - end - - - def reset_defaults(config) - [:test_compiler, - :test_linker, - :test_fixture, - :test_includes_preprocessor, - :test_file_preprocessor, - :test_file_preprocessor_directives, - :test_dependencies_generator, - :release_compiler, - :release_assembler, - :release_linker, - :release_dependencies_generator].each do |tool| - config[:tools].delete(tool) if (not (config[:tools][tool].nil?)) - end - end - - - # The default values defined in defaults.rb (eg. DEFAULT_TOOLS_TEST) are populated - # into @param config - def populate_defaults(config) - new_config = DEFAULT_CEEDLING_CONFIG.deep_clone - new_config.deep_merge!(config) - config.replace(new_config) - - @configurator_builder.populate_defaults( config, DEFAULT_TOOLS_TEST ) - @configurator_builder.populate_defaults( config, DEFAULT_TOOLS_TEST_PREPROCESSORS ) if (config[:project][:use_test_preprocessor]) - @configurator_builder.populate_defaults( config, DEFAULT_TOOLS_TEST_DEPENDENCIES ) if (config[:project][:use_deep_dependencies]) - - @configurator_builder.populate_defaults( config, DEFAULT_TOOLS_RELEASE ) if (config[:project][:release_build]) - @configurator_builder.populate_defaults( config, DEFAULT_TOOLS_RELEASE_ASSEMBLER ) if (config[:project][:release_build] and config[:release_build][:use_assembly]) - @configurator_builder.populate_defaults( config, DEFAULT_TOOLS_RELEASE_DEPENDENCIES ) if (config[:project][:release_build] and config[:project][:use_deep_dependencies]) - end - - - def populate_unity_defaults(config) - unity = config[:unity] || {} - @runner_config = unity.merge(@runner_config || config[:test_runner] || {}) - end - - def populate_cmock_defaults(config) - # cmock has its own internal defaults handling, but we need to set these specific values - # so they're present for the build environment to access; - # note: these need to end up in the hash given to initialize cmock for this to be successful - cmock = config[:cmock] || {} - - # yes, we're duplicating the default mock_prefix in cmock, but it's because we need CMOCK_MOCK_PREFIX always available in Ceedling's environment - cmock[:mock_prefix] = 'Mock' if (cmock[:mock_prefix].nil?) - - # just because strict ordering is the way to go - cmock[:enforce_strict_ordering] = true if (cmock[:enforce_strict_ordering].nil?) - - cmock[:mock_path] = File.join(config[:project][:build_root], TESTS_BASE_PATH, 'mocks') if (cmock[:mock_path].nil?) - cmock[:verbosity] = @project_verbosity if (cmock[:verbosity].nil?) - - cmock[:plugins] = [] if (cmock[:plugins].nil?) - cmock[:plugins].map! { |plugin| plugin.to_sym } - cmock[:plugins] << (:cexception) if (!cmock[:plugins].include?(:cexception) and (config[:project][:use_exceptions])) - cmock[:plugins].uniq! - - cmock[:unity_helper] = false if (cmock[:unity_helper].nil?) - - if (cmock[:unity_helper]) - cmock[:unity_helper] = [cmock[:unity_helper]] if cmock[:unity_helper].is_a? String - cmock[:includes] += cmock[:unity_helper].map{|helper| File.basename(helper) } - cmock[:includes].uniq! - end - - @runner_config = cmock.merge(@runner_config || config[:test_runner] || {}) - - @cmock_builder.manufacture(cmock) - end - - - def get_runner_config - @runner_config - end - - - # grab tool names from yaml and insert into tool structures so available for error messages - # set up default values - def tools_setup(config) - config[:tools].each_key do |name| - tool = config[:tools][name] - - # populate name if not given - tool[:name] = name.to_s if (tool[:name].nil?) - - # handle inline ruby string substitution in executable - if (tool[:executable] =~ RUBY_STRING_REPLACEMENT_PATTERN) - tool[:executable].replace(@system_wrapper.module_eval(tool[:executable])) - end - - # populate stderr redirect option - tool[:stderr_redirect] = StdErrRedirect::NONE if (tool[:stderr_redirect].nil?) - - # populate background execution option - tool[:background_exec] = BackgroundExec::NONE if (tool[:background_exec].nil?) - - # populate optional option to control verification of executable in search paths - tool[:optional] = false if (tool[:optional].nil?) - end - end - - - def tools_supplement_arguments(config) - tools_name_prefix = 'tools_' - config[:tools].each_key do |name| - tool = @project_config_hash[(tools_name_prefix + name.to_s).to_sym] - - # smoosh in extra arguments if specified at top-level of config (useful for plugins & default gcc tools) - # arguments are squirted in at _end_ of list - top_level_tool = (tools_name_prefix + name.to_s).to_sym - if (not config[top_level_tool].nil?) - # adding and flattening is not a good idea: might over-flatten if there's array nesting in tool args - tool[:arguments].concat config[top_level_tool][:arguments] - end - end - end - - - def find_and_merge_plugins(config) - # plugins must be loaded before generic path evaluation & magic that happen later; - # perform path magic here as discrete step - config[:plugins][:load_paths].each do |path| - path.replace(@system_wrapper.module_eval(path)) if (path =~ RUBY_STRING_REPLACEMENT_PATTERN) - FilePathUtils::standardize(path) - end - - config[:plugins][:load_paths] << FilePathUtils::standardize(Ceedling.load_path) - config[:plugins][:load_paths].uniq! - - paths_hash = @configurator_plugins.add_load_paths(config) - - @rake_plugins = @configurator_plugins.find_rake_plugins(config, paths_hash) - @script_plugins = @configurator_plugins.find_script_plugins(config, paths_hash) - config_plugins = @configurator_plugins.find_config_plugins(config, paths_hash) - plugin_yml_defaults = @configurator_plugins.find_plugin_yml_defaults(config, paths_hash) - plugin_hash_defaults = @configurator_plugins.find_plugin_hash_defaults(config, paths_hash) - - config_plugins.each do |plugin| - plugin_config = @yaml_wrapper.load(plugin) - config.deep_merge(plugin_config) - end - - plugin_yml_defaults.each do |defaults| - @configurator_builder.populate_defaults( config, @yaml_wrapper.load(defaults) ) - end - - plugin_hash_defaults.each do |defaults| - @configurator_builder.populate_defaults( config, defaults ) - end - - # special plugin setting for results printing - config[:plugins][:display_raw_test_results] = true if (config[:plugins][:display_raw_test_results].nil?) - - paths_hash.each_pair { |name, path| config[:plugins][name] = path } - end - - - def merge_imports(config) - if config[:import] - if config[:import].is_a? Array - until config[:import].empty? - path = config[:import].shift - path = @system_wrapper.module_eval(path) if (path =~ RUBY_STRING_REPLACEMENT_PATTERN) - config.deep_merge!(@yaml_wrapper.load(path)) - end - else - config[:import].each_value do |path| - if !path.nil? - path = @system_wrapper.module_eval(path) if (path =~ RUBY_STRING_REPLACEMENT_PATTERN) - config.deep_merge!(@yaml_wrapper.load(path)) - end - end - end - end - config.delete(:import) - end - - - def eval_environment_variables(config) - config[:environment].each do |hash| - key = hash.keys[0] - value = hash[key] - items = [] - - interstitial = ((key == :path) ? File::PATH_SEPARATOR : '') - items = ((value.class == Array) ? hash[key] : [value]) - - items.each do |item| - if item.is_a? String and item =~ RUBY_STRING_REPLACEMENT_PATTERN - item.replace( @system_wrapper.module_eval( item ) ) - end - end - hash[key] = items.join( interstitial ) - - @system_wrapper.env_set( key.to_s.upcase, hash[key] ) - end - end - - - def eval_paths(config) - # [:plugins]:[load_paths] already handled - - paths = [ # individual paths that don't follow convention processed below - config[:project][:build_root], - config[:release_build][:artifacts]] - - eval_path_list( paths ) - - config[:paths].each_pair { |collection, paths| eval_path_list( paths ) } - - config[:files].each_pair { |collection, files| eval_path_list( files ) } - - # all other paths at secondary hash key level processed by convention: - # ex. [:toplevel][:foo_path] & [:toplevel][:bar_paths] are evaluated - config.each_pair { |parent, child| eval_path_list( collect_path_list( child ) ) } - end - - - def standardize_paths(config) - # [:plugins]:[load_paths] already handled - - paths = [ # individual paths that don't follow convention processed below - config[:project][:build_root], - config[:release_build][:artifacts]] # cmock path in case it was explicitly set in config - - paths.flatten.each { |path| FilePathUtils::standardize( path ) } - - config[:paths].each_pair do |collection, paths| - # ensure that list is an array (i.e. handle case of list being a single string, - # or a multidimensional array) - config[:paths][collection] = [paths].flatten.map{|path| FilePathUtils::standardize( path )} - end - - config[:files].each_pair { |collection, files| files.each{ |path| FilePathUtils::standardize( path ) } } - - config[:tools].each_pair { |tool, config| FilePathUtils::standardize( config[:executable] ) if (config.include? :executable) } - - # all other paths at secondary hash key level processed by convention: - # ex. [:toplevel][:foo_path] & [:toplevel][:bar_paths] are standardized - config.each_pair do |parent, child| - collect_path_list( child ).each { |path| FilePathUtils::standardize( path ) } - end - end - - - def validate(config) - # collect felonies and go straight to jail - raise if (not @configurator_setup.validate_required_sections( config )) - - # collect all misdemeanors, everybody on probation - blotter = [] - blotter << @configurator_setup.validate_required_section_values( config ) - blotter << @configurator_setup.validate_paths( config ) - blotter << @configurator_setup.validate_tools( config ) - blotter << @configurator_setup.validate_plugins( config ) - - raise if (blotter.include?( false )) - end - - - # create constants and accessors (attached to this object) from given hash - def build(config, *keys) - # create flattened & expanded configuration hash - built_config = @configurator_setup.build_project_config( config, @configurator_builder.flattenify( config ) ) - - @project_config_hash = built_config.clone - store_config() - - @configurator_setup.build_constants_and_accessors(built_config, binding()) - - # top-level keys disappear when we flatten, so create global constants & accessors to any specified keys - keys.each do |key| - hash = { key => config[key] } - @configurator_setup.build_constants_and_accessors(hash, binding()) - end - end - - - # add to constants and accessors as post build step - def build_supplement(config_base, config_more) - # merge in our post-build additions to base configuration hash - config_base.deep_merge!( config_more ) - - # flatten our addition hash - config_more_flattened = @configurator_builder.flattenify( config_more ) - - # merge our flattened hash with built hash from previous build - @project_config_hash.deep_merge!( config_more_flattened ) - store_config() - - # create more constants and accessors - @configurator_setup.build_constants_and_accessors(config_more_flattened, binding()) - - # recreate constants & update accessors with new merged, base values - config_more.keys.each do |key| - hash = { key => config_base[key] } - @configurator_setup.build_constants_and_accessors(hash, binding()) - end - end - - - def insert_rake_plugins(plugins) - plugins.each do |plugin| - @project_config_hash[:project_rakefile_component_files] << plugin - end - end - - ### private ### - - private - - def collect_path_list( container ) - paths = [] - container.each_key { |key| paths << container[key] if (key.to_s =~ /_path(s)?$/) } if (container.class == Hash) - return paths.flatten - end - - def eval_path_list( paths ) - if paths.kind_of?(Array) - paths = Array.new(paths) - end - - paths.flatten.each do |path| - path.replace( @system_wrapper.module_eval( path ) ) if (path =~ RUBY_STRING_REPLACEMENT_PATTERN) - end - end - - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/configurator_builder.rb b/test/unit-test/vendor/ceedling/lib/ceedling/configurator_builder.rb deleted file mode 100644 index f202d8a65..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/configurator_builder.rb +++ /dev/null @@ -1,475 +0,0 @@ -require 'rubygems' -require 'rake' # for ext() method -require 'ceedling/file_path_utils' # for class methods -require 'ceedling/defaults' -require 'ceedling/constants' # for Verbosity constants class & base file paths - - - -class ConfiguratorBuilder - - constructor :file_system_utils, :file_wrapper, :system_wrapper - - - def build_global_constants(config) - config.each_pair do |key, value| - formatted_key = key.to_s.upcase - # undefine global constant if it already exists - Object.send(:remove_const, formatted_key.to_sym) if @system_wrapper.constants_include?(formatted_key) - # create global constant - Object.module_eval("#{formatted_key} = value") - end - end - - - def build_accessor_methods(config, context) - config.each_pair do |key, value| - # fill configurator object with accessor methods - eval("def #{key.to_s.downcase}() return @project_config_hash[:#{key.to_s}] end", context) - end - end - - - # create a flattened hash from the original configuration structure - def flattenify(config) - new_hash = {} - - config.each_key do | parent | - - # gracefully handle empty top-level entries - next if (config[parent].nil?) - - case config[parent] - when Array - config[parent].each do |hash| - key = "#{parent.to_s.downcase}_#{hash.keys[0].to_s.downcase}".to_sym - new_hash[key] = hash[hash.keys[0]] - end - when Hash - config[parent].each_pair do | child, value | - key = "#{parent.to_s.downcase}_#{child.to_s.downcase}".to_sym - new_hash[key] = value - end - # handle entries with no children, only values - else - new_hash["#{parent.to_s.downcase}".to_sym] = config[parent] - end - - end - - return new_hash - end - - - def populate_defaults(config, defaults) - defaults.keys.sort.each do |section| - defaults[section].keys.sort.each do |entry| - config[section] = {} if config[section].nil? - config[section][entry] = defaults[section][entry].deep_clone if (config[section][entry].nil?) - end - end - end - - - def clean(in_hash) - # ensure that include files inserted into test runners have file extensions & proper ones at that - in_hash[:test_runner_includes].map!{|include| include.ext(in_hash[:extension_header])} - end - - - def set_build_paths(in_hash) - out_hash = {} - - project_build_artifacts_root = File.join(in_hash[:project_build_root], 'artifacts') - project_build_tests_root = File.join(in_hash[:project_build_root], TESTS_BASE_PATH) - project_build_release_root = File.join(in_hash[:project_build_root], RELEASE_BASE_PATH) - - paths = [ - [:project_build_artifacts_root, project_build_artifacts_root, true ], - [:project_build_tests_root, project_build_tests_root, true ], - [:project_build_release_root, project_build_release_root, in_hash[:project_release_build] ], - - [:project_test_artifacts_path, File.join(project_build_artifacts_root, TESTS_BASE_PATH), true ], - [:project_test_runners_path, File.join(project_build_tests_root, 'runners'), true ], - [:project_test_results_path, File.join(project_build_tests_root, 'results'), true ], - [:project_test_build_output_path, File.join(project_build_tests_root, 'out'), true ], - [:project_test_build_output_asm_path, File.join(project_build_tests_root, 'out', 'asm'), true ], - [:project_test_build_output_c_path, File.join(project_build_tests_root, 'out', 'c'), true ], - [:project_test_build_cache_path, File.join(project_build_tests_root, 'cache'), true ], - [:project_test_dependencies_path, File.join(project_build_tests_root, 'dependencies'), true ], - - [:project_release_artifacts_path, File.join(project_build_artifacts_root, RELEASE_BASE_PATH), in_hash[:project_release_build] ], - [:project_release_build_cache_path, File.join(project_build_release_root, 'cache'), in_hash[:project_release_build] ], - [:project_release_build_output_path, File.join(project_build_release_root, 'out'), in_hash[:project_release_build] ], - [:project_release_build_output_asm_path, File.join(project_build_release_root, 'out', 'asm'), in_hash[:project_release_build] ], - [:project_release_build_output_c_path, File.join(project_build_release_root, 'out', 'c'), in_hash[:project_release_build] ], - [:project_release_dependencies_path, File.join(project_build_release_root, 'dependencies'), in_hash[:project_release_build] ], - - [:project_log_path, File.join(in_hash[:project_build_root], 'logs'), true ], - [:project_temp_path, File.join(in_hash[:project_build_root], 'temp'), true ], - - [:project_test_preprocess_includes_path, File.join(project_build_tests_root, 'preprocess/includes'), in_hash[:project_use_test_preprocessor] ], - [:project_test_preprocess_files_path, File.join(project_build_tests_root, 'preprocess/files'), in_hash[:project_use_test_preprocessor] ], - ] - - out_hash[:project_build_paths] = [] - - # fetch already set mock path - out_hash[:project_build_paths] << in_hash[:cmock_mock_path] if (in_hash[:project_use_mocks]) - - paths.each do |path| - build_path_name = path[0] - build_path = path[1] - build_path_add_condition = path[2] - - # insert path into build paths if associated with true condition - out_hash[:project_build_paths] << build_path if build_path_add_condition - # set path symbol name and path for each entry in paths array - out_hash[build_path_name] = build_path - end - - return out_hash - end - - - def set_force_build_filepaths(in_hash) - out_hash = {} - - out_hash[:project_test_force_rebuild_filepath] = File.join( in_hash[:project_test_dependencies_path], 'force_build' ) - out_hash[:project_release_force_rebuild_filepath] = File.join( in_hash[:project_release_dependencies_path], 'force_build' ) if (in_hash[:project_release_build]) - - return out_hash - end - - - def set_rakefile_components(in_hash) - out_hash = { - :project_rakefile_component_files => - [File.join(CEEDLING_LIB, 'ceedling', 'tasks_base.rake'), - File.join(CEEDLING_LIB, 'ceedling', 'tasks_filesystem.rake'), - File.join(CEEDLING_LIB, 'ceedling', 'tasks_tests.rake'), - File.join(CEEDLING_LIB, 'ceedling', 'tasks_vendor.rake'), - File.join(CEEDLING_LIB, 'ceedling', 'rules_tests.rake')]} - - out_hash[:project_rakefile_component_files] << File.join(CEEDLING_LIB, 'ceedling', 'rules_cmock.rake') if (in_hash[:project_use_mocks]) - out_hash[:project_rakefile_component_files] << File.join(CEEDLING_LIB, 'ceedling', 'rules_preprocess.rake') if (in_hash[:project_use_test_preprocessor]) - out_hash[:project_rakefile_component_files] << File.join(CEEDLING_LIB, 'ceedling', 'rules_tests_deep_dependencies.rake') if (in_hash[:project_use_deep_dependencies]) - out_hash[:project_rakefile_component_files] << File.join(CEEDLING_LIB, 'ceedling', 'tasks_tests_deep_dependencies.rake') if (in_hash[:project_use_deep_dependencies]) - - out_hash[:project_rakefile_component_files] << File.join(CEEDLING_LIB, 'ceedling', 'rules_release_deep_dependencies.rake') if (in_hash[:project_release_build] and in_hash[:project_use_deep_dependencies]) - out_hash[:project_rakefile_component_files] << File.join(CEEDLING_LIB, 'ceedling', 'rules_release.rake') if (in_hash[:project_release_build]) - out_hash[:project_rakefile_component_files] << File.join(CEEDLING_LIB, 'ceedling', 'tasks_release_deep_dependencies.rake') if (in_hash[:project_release_build] and in_hash[:project_use_deep_dependencies]) - out_hash[:project_rakefile_component_files] << File.join(CEEDLING_LIB, 'ceedling', 'tasks_release.rake') if (in_hash[:project_release_build]) - - return out_hash - end - - - def set_release_target(in_hash) - return {} if (not in_hash[:project_release_build]) - - release_target_file = ((in_hash[:release_build_output].nil?) ? (DEFAULT_RELEASE_TARGET_NAME.ext(in_hash[:extension_executable])) : in_hash[:release_build_output]) - release_map_file = ((in_hash[:release_build_output].nil?) ? (DEFAULT_RELEASE_TARGET_NAME.ext(in_hash[:extension_map])) : in_hash[:release_build_output].ext(in_hash[:extension_map])) - - return { - # tempted to make a helper method in file_path_utils? stop right there, pal. you'll introduce a cyclical dependency - :project_release_build_target => File.join(in_hash[:project_build_release_root], release_target_file), - :project_release_build_map => File.join(in_hash[:project_build_release_root], release_map_file) - } - end - - - def collect_project_options(in_hash) - options = [] - - in_hash[:project_options_paths].each do |path| - options << @file_wrapper.directory_listing( File.join(path, '*.yml') ) - end - - return { - :collection_project_options => options.flatten - } - end - - - def expand_all_path_globs(in_hash) - out_hash = {} - path_keys = [] - - in_hash.each_key do |key| - next if (not key.to_s[0..4] == 'paths') - path_keys << key - end - - # sorted to provide assured order of traversal in test calls on mocks - path_keys.sort.each do |key| - out_hash["collection_#{key.to_s}".to_sym] = @file_system_utils.collect_paths( in_hash[key] ) - end - - return out_hash - end - - - def collect_source_and_include_paths(in_hash) - return { - :collection_paths_source_and_include => - ( in_hash[:collection_paths_source] + - in_hash[:collection_paths_include] ).select {|x| File.directory?(x)} - } - end - - - def collect_source_include_vendor_paths(in_hash) - extra_paths = [] - extra_paths << File.join(in_hash[:cexception_vendor_path], CEXCEPTION_LIB_PATH) if (in_hash[:project_use_exceptions]) - - return { - :collection_paths_source_include_vendor => - in_hash[:collection_paths_source_and_include] + - extra_paths - } - end - - - def collect_test_support_source_include_paths(in_hash) - return { - :collection_paths_test_support_source_include => - (in_hash[:collection_paths_test] + - in_hash[:collection_paths_support] + - in_hash[:collection_paths_source] + - in_hash[:collection_paths_include] ).select {|x| File.directory?(x)} - } - end - - - def collect_vendor_paths(in_hash) - return {:collection_paths_vendor => get_vendor_paths(in_hash)} - end - - - def collect_test_support_source_include_vendor_paths(in_hash) - return { - :collection_paths_test_support_source_include_vendor => - get_vendor_paths(in_hash) + - in_hash[:collection_paths_test_support_source_include] - } - end - - - def collect_tests(in_hash) - all_tests = @file_wrapper.instantiate_file_list - - in_hash[:collection_paths_test].each do |path| - all_tests.include( File.join(path, "#{in_hash[:project_test_file_prefix]}*#{in_hash[:extension_source]}") ) - end - - @file_system_utils.revise_file_list( all_tests, in_hash[:files_test] ) - - return {:collection_all_tests => all_tests} - end - - - def collect_assembly(in_hash) - all_assembly = @file_wrapper.instantiate_file_list - - return {:collection_all_assembly => all_assembly} if ((not in_hash[:release_build_use_assembly]) && (not in_hash[:test_build_use_assembly])) - - # Sprinkle in all assembly files we can find in the source folders - in_hash[:collection_paths_source].each do |path| - all_assembly.include( File.join(path, "*#{in_hash[:extension_assembly]}") ) - end - - # Also add all assembly files we can find in the support folders - in_hash[:collection_paths_support].each do |path| - all_assembly.include( File.join(path, "*#{in_hash[:extension_assembly]}") ) - end - - # Also add files that we are explicitly adding via :files:assembly: section - @file_system_utils.revise_file_list( all_assembly, in_hash[:files_assembly] ) - - return {:collection_all_assembly => all_assembly} - end - - - def collect_source(in_hash) - all_source = @file_wrapper.instantiate_file_list - in_hash[:collection_paths_source].each do |path| - if File.exists?(path) and not File.directory?(path) - all_source.include( path ) - else - all_source.include( File.join(path, "*#{in_hash[:extension_source]}") ) - end - end - @file_system_utils.revise_file_list( all_source, in_hash[:files_source] ) - - return {:collection_all_source => all_source} - end - - - def collect_headers(in_hash) - all_headers = @file_wrapper.instantiate_file_list - - paths = - in_hash[:collection_paths_test] + - in_hash[:collection_paths_support] + - in_hash[:collection_paths_source] + - in_hash[:collection_paths_include] - - paths.each do |path| - all_headers.include( File.join(path, "*#{in_hash[:extension_header]}") ) - end - - @file_system_utils.revise_file_list( all_headers, in_hash[:files_include] ) - - return {:collection_all_headers => all_headers} - end - - - def collect_release_existing_compilation_input(in_hash) - release_input = @file_wrapper.instantiate_file_list - - paths = - in_hash[:collection_paths_source] + - in_hash[:collection_paths_include] - - paths << File.join(in_hash[:cexception_vendor_path], CEXCEPTION_LIB_PATH) if (in_hash[:project_use_exceptions]) - - paths.each do |path| - release_input.include( File.join(path, "*#{in_hash[:extension_header]}") ) - if File.exists?(path) and not File.directory?(path) - release_input.include( path ) - else - release_input.include( File.join(path, "*#{in_hash[:extension_source]}") ) - end - end - - @file_system_utils.revise_file_list( release_input, in_hash[:files_source] ) - @file_system_utils.revise_file_list( release_input, in_hash[:files_include] ) - # finding assembly files handled explicitly through other means - - return {:collection_release_existing_compilation_input => release_input} - end - - - def collect_all_existing_compilation_input(in_hash) - all_input = @file_wrapper.instantiate_file_list - - paths = - in_hash[:collection_paths_test] + - in_hash[:collection_paths_support] + - in_hash[:collection_paths_source] + - in_hash[:collection_paths_include] + - [File.join(in_hash[:unity_vendor_path], UNITY_LIB_PATH)] - - paths << File.join(in_hash[:cexception_vendor_path], CEXCEPTION_LIB_PATH) if (in_hash[:project_use_exceptions]) - paths << File.join(in_hash[:cmock_vendor_path], CMOCK_LIB_PATH) if (in_hash[:project_use_mocks]) - - paths.each do |path| - all_input.include( File.join(path, "*#{in_hash[:extension_header]}") ) - if File.exists?(path) and not File.directory?(path) - all_input.include( path ) - else - all_input.include( File.join(path, "*#{in_hash[:extension_source]}") ) - all_input.include( File.join(path, "*#{in_hash[:extension_assembly]}") ) if (defined?(TEST_BUILD_USE_ASSEMBLY) && TEST_BUILD_USE_ASSEMBLY) - end - end - - @file_system_utils.revise_file_list( all_input, in_hash[:files_test] ) - @file_system_utils.revise_file_list( all_input, in_hash[:files_support] ) - @file_system_utils.revise_file_list( all_input, in_hash[:files_source] ) - @file_system_utils.revise_file_list( all_input, in_hash[:files_include] ) - # finding assembly files handled explicitly through other means - - return {:collection_all_existing_compilation_input => all_input} - end - - - def get_vendor_defines(in_hash) - defines = in_hash[:unity_defines].clone - defines.concat(in_hash[:cmock_defines]) if (in_hash[:project_use_mocks]) - defines.concat(in_hash[:cexception_defines]) if (in_hash[:project_use_exceptions]) - - return defines - end - - - def collect_vendor_defines(in_hash) - return {:collection_defines_vendor => get_vendor_defines(in_hash)} - end - - - def collect_test_and_vendor_defines(in_hash) - defines = in_hash[:defines_test].clone - vendor_defines = get_vendor_defines(in_hash) - defines.concat(vendor_defines) if vendor_defines - - return {:collection_defines_test_and_vendor => defines} - end - - - def collect_release_and_vendor_defines(in_hash) - release_defines = in_hash[:defines_release].clone - - release_defines.concat(in_hash[:cexception_defines]) if (in_hash[:project_use_exceptions]) - - return {:collection_defines_release_and_vendor => release_defines} - end - - - def collect_release_artifact_extra_link_objects(in_hash) - objects = [] - - # no build paths here so plugins can remap if necessary (i.e. path mapping happens at runtime) - objects << CEXCEPTION_C_FILE.ext( in_hash[:extension_object] ) if (in_hash[:project_use_exceptions]) - - return {:collection_release_artifact_extra_link_objects => objects} - end - - - def collect_test_fixture_extra_link_objects(in_hash) - # Note: Symbols passed to compiler at command line can change Unity and CException behavior / configuration; - # we also handle those dependencies elsewhere in compilation dependencies - - sources = [UNITY_C_FILE] - - in_hash[:files_support].each { |file| sources << file } - - # we don't include paths here because use of plugins or mixing different compilers may require different build paths - sources << CEXCEPTION_C_FILE if (in_hash[:project_use_exceptions]) - sources << CMOCK_C_FILE if (in_hash[:project_use_mocks]) - - # if we're using mocks & a unity helper is defined & that unity helper includes a source file component (not only a header of macros), - # then link in the unity_helper object file too - if ( in_hash[:project_use_mocks] and in_hash[:cmock_unity_helper] ) - in_hash[:cmock_unity_helper].each do |helper| - if @file_wrapper.exist?(helper.ext(in_hash[:extension_source])) - sources << helper - end - end - end - - # create object files from all the sources - objects = sources.map { |file| File.basename(file) } - - # no build paths here so plugins can remap if necessary (i.e. path mapping happens at runtime) - objects.map! { |object| object.ext(in_hash[:extension_object]) } - - return { :collection_all_support => sources, - :collection_test_fixture_extra_link_objects => objects - } - end - - - private - - def get_vendor_paths(in_hash) - vendor_paths = [] - vendor_paths << File.join(in_hash[:unity_vendor_path], UNITY_LIB_PATH) - vendor_paths << File.join(in_hash[:cexception_vendor_path], CEXCEPTION_LIB_PATH) if (in_hash[:project_use_exceptions]) - vendor_paths << File.join(in_hash[:cmock_vendor_path], CMOCK_LIB_PATH) if (in_hash[:project_use_mocks]) - vendor_paths << in_hash[:cmock_mock_path] if (in_hash[:project_use_mocks]) - - return vendor_paths - end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/configurator_plugins.rb b/test/unit-test/vendor/ceedling/lib/ceedling/configurator_plugins.rb deleted file mode 100644 index c2e198597..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/configurator_plugins.rb +++ /dev/null @@ -1,131 +0,0 @@ -require 'ceedling/constants' - -class ConfiguratorPlugins - - constructor :stream_wrapper, :file_wrapper, :system_wrapper - attr_reader :rake_plugins, :script_plugins - - def setup - @rake_plugins = [] - @script_plugins = [] - end - - - def add_load_paths(config) - plugin_paths = {} - - config[:plugins][:enabled].each do |plugin| - config[:plugins][:load_paths].each do |root| - path = File.join(root, plugin) - - is_script_plugin = ( not @file_wrapper.directory_listing( File.join( path, 'lib', '*.rb' ) ).empty? ) - is_rake_plugin = ( not @file_wrapper.directory_listing( File.join( path, '*.rake' ) ).empty? ) - - if is_script_plugin or is_rake_plugin - plugin_paths[(plugin + '_path').to_sym] = path - - if is_script_plugin - @system_wrapper.add_load_path( File.join( path, 'lib') ) - @system_wrapper.add_load_path( File.join( path, 'config') ) - end - break - end - end - end - - return plugin_paths - end - - - # gather up and return .rake filepaths that exist on-disk - def find_rake_plugins(config, plugin_paths) - @rake_plugins = [] - plugins_with_path = [] - - config[:plugins][:enabled].each do |plugin| - if path = plugin_paths[(plugin + '_path').to_sym] - rake_plugin_path = File.join(path, "#{plugin}.rake") - if (@file_wrapper.exist?(rake_plugin_path)) - plugins_with_path << rake_plugin_path - @rake_plugins << plugin - end - end - end - - return plugins_with_path - end - - - # gather up and return just names of .rb classes that exist on-disk - def find_script_plugins(config, plugin_paths) - @script_plugins = [] - - config[:plugins][:enabled].each do |plugin| - if path = plugin_paths[(plugin + '_path').to_sym] - script_plugin_path = File.join(path, "lib", "#{plugin}.rb") - - if @file_wrapper.exist?(script_plugin_path) - @script_plugins << plugin - end - end - end - - return @script_plugins - end - - - # gather up and return configuration .yml filepaths that exist on-disk - def find_config_plugins(config, plugin_paths) - plugins_with_path = [] - - config[:plugins][:enabled].each do |plugin| - if path = plugin_paths[(plugin + '_path').to_sym] - config_plugin_path = File.join(path, "config", "#{plugin}.yml") - - if @file_wrapper.exist?(config_plugin_path) - plugins_with_path << config_plugin_path - end - end - end - - return plugins_with_path - end - - - # gather up and return default .yml filepaths that exist on-disk - def find_plugin_yml_defaults(config, plugin_paths) - defaults_with_path = [] - - config[:plugins][:enabled].each do |plugin| - if path = plugin_paths[(plugin + '_path').to_sym] - default_path = File.join(path, 'config', 'defaults.yml') - - if @file_wrapper.exist?(default_path) - defaults_with_path << default_path - end - end - end - - return defaults_with_path - end - - # gather up and return - def find_plugin_hash_defaults(config, plugin_paths) - defaults_hash= [] - - config[:plugins][:enabled].each do |plugin| - if path = plugin_paths[(plugin + '_path').to_sym] - default_path = File.join(path, "config", "defaults_#{plugin}.rb") - if @file_wrapper.exist?(default_path) - @system_wrapper.require_file( "defaults_#{plugin}.rb") - - object = eval("get_default_config()") - defaults_hash << object - end - end - end - - return defaults_hash - end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/configurator_setup.rb b/test/unit-test/vendor/ceedling/lib/ceedling/configurator_setup.rb deleted file mode 100644 index cba88df3c..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/configurator_setup.rb +++ /dev/null @@ -1,128 +0,0 @@ - -# add sort-ability to symbol so we can order keys array in hash for test-ability -class Symbol - include Comparable - - def <=>(other) - self.to_s <=> other.to_s - end -end - - -class ConfiguratorSetup - - constructor :configurator_builder, :configurator_validator, :configurator_plugins, :stream_wrapper - - - def build_project_config(config, flattened_config) - ### flesh out config - @configurator_builder.clean(flattened_config) - - ### add to hash values we build up from configuration & file system contents - flattened_config.merge!(@configurator_builder.set_build_paths(flattened_config)) - flattened_config.merge!(@configurator_builder.set_force_build_filepaths(flattened_config)) - flattened_config.merge!(@configurator_builder.set_rakefile_components(flattened_config)) - flattened_config.merge!(@configurator_builder.set_release_target(flattened_config)) - flattened_config.merge!(@configurator_builder.collect_project_options(flattened_config)) - - ### iterate through all entries in paths section and expand any & all globs to actual paths - flattened_config.merge!(@configurator_builder.expand_all_path_globs(flattened_config)) - - flattened_config.merge!(@configurator_builder.collect_vendor_paths(flattened_config)) - flattened_config.merge!(@configurator_builder.collect_source_and_include_paths(flattened_config)) - flattened_config.merge!(@configurator_builder.collect_source_include_vendor_paths(flattened_config)) - flattened_config.merge!(@configurator_builder.collect_test_support_source_include_paths(flattened_config)) - flattened_config.merge!(@configurator_builder.collect_test_support_source_include_vendor_paths(flattened_config)) - flattened_config.merge!(@configurator_builder.collect_tests(flattened_config)) - flattened_config.merge!(@configurator_builder.collect_assembly(flattened_config)) - flattened_config.merge!(@configurator_builder.collect_source(flattened_config)) - flattened_config.merge!(@configurator_builder.collect_headers(flattened_config)) - flattened_config.merge!(@configurator_builder.collect_release_existing_compilation_input(flattened_config)) - flattened_config.merge!(@configurator_builder.collect_all_existing_compilation_input(flattened_config)) - flattened_config.merge!(@configurator_builder.collect_vendor_defines(flattened_config)) - flattened_config.merge!(@configurator_builder.collect_test_and_vendor_defines(flattened_config)) - flattened_config.merge!(@configurator_builder.collect_release_and_vendor_defines(flattened_config)) - flattened_config.merge!(@configurator_builder.collect_release_artifact_extra_link_objects(flattened_config)) - flattened_config.merge!(@configurator_builder.collect_test_fixture_extra_link_objects(flattened_config)) - - return flattened_config - end - - - def build_constants_and_accessors(config, context) - @configurator_builder.build_global_constants(config) - @configurator_builder.build_accessor_methods(config, context) - end - - - def validate_required_sections(config) - validation = [] - validation << @configurator_validator.exists?(config, :project) - validation << @configurator_validator.exists?(config, :paths) - - return false if (validation.include?(false)) - return true - end - - def validate_required_section_values(config) - validation = [] - validation << @configurator_validator.exists?(config, :project, :build_root) - validation << @configurator_validator.exists?(config, :paths, :test) - validation << @configurator_validator.exists?(config, :paths, :source) - - return false if (validation.include?(false)) - return true - end - - def validate_paths(config) - validation = [] - - if config[:cmock][:unity_helper] - config[:cmock][:unity_helper].each do |path| - validation << @configurator_validator.validate_filepath_simple( path, :cmock, :unity_helper ) - end - end - - config[:project][:options_paths].each do |path| - validation << @configurator_validator.validate_filepath_simple( path, :project, :options_paths ) - end - - config[:plugins][:load_paths].each do |path| - validation << @configurator_validator.validate_filepath_simple( path, :plugins, :load_paths ) - end - - config[:paths].keys.sort.each do |key| - validation << @configurator_validator.validate_path_list(config, :paths, key) - end - - return false if (validation.include?(false)) - return true - end - - def validate_tools(config) - validation = [] - - config[:tools].keys.sort.each do |key| - validation << @configurator_validator.exists?(config, :tools, key, :executable) - validation << @configurator_validator.validate_executable_filepath(config, :tools, key, :executable) if (not config[:tools][key][:optional]) - validation << @configurator_validator.validate_tool_stderr_redirect(config, :tools, key) - end - - return false if (validation.include?(false)) - return true - end - - def validate_plugins(config) - missing_plugins = - Set.new( config[:plugins][:enabled] ) - - Set.new( @configurator_plugins.rake_plugins ) - - Set.new( @configurator_plugins.script_plugins ) - - missing_plugins.each do |plugin| - @stream_wrapper.stderr_puts("ERROR: Ceedling plugin '#{plugin}' contains no rake or ruby class entry point. (Misspelled or missing files?)") - end - - return ( (missing_plugins.size > 0) ? false : true ) - end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/configurator_validator.rb b/test/unit-test/vendor/ceedling/lib/ceedling/configurator_validator.rb deleted file mode 100644 index fc2950e0b..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/configurator_validator.rb +++ /dev/null @@ -1,193 +0,0 @@ -require 'rubygems' -require 'rake' # for ext() -require 'ceedling/constants' -require 'ceedling/tool_executor' # for argument replacement pattern -require 'ceedling/file_path_utils' # for glob handling class methods - - -class ConfiguratorValidator - - constructor :file_wrapper, :stream_wrapper, :system_wrapper - - # walk into config hash verify existence of data at key depth - def exists?(config, *keys) - hash = retrieve_value(config, keys) - exist = !hash[:value].nil? - - if (not exist) - # no verbosity checking since this is lowest level anyhow & verbosity checking depends on configurator - @stream_wrapper.stderr_puts("ERROR: Required config file entry #{format_key_sequence(keys, hash[:depth])} does not exist.") - end - - return exist - end - - - # walk into config hash. verify directory path(s) at given key depth - def validate_path_list(config, *keys) - hash = retrieve_value(config, keys) - list = hash[:value] - - # return early if we couldn't walk into hash and find a value - return false if (list.nil?) - - path_list = [] - exist = true - - case list - when String then path_list << list - when Array then path_list = list - end - - path_list.each do |path| - base_path = FilePathUtils::extract_path(path) # lop off add/subtract notation & glob specifiers - - if (not @file_wrapper.exist?(base_path)) - # no verbosity checking since this is lowest level anyhow & verbosity checking depends on configurator - @stream_wrapper.stderr_puts("ERROR: Config path #{format_key_sequence(keys, hash[:depth])}['#{base_path}'] does not exist on disk.") - exist = false - end - end - - return exist - end - - - # simple path verification - def validate_filepath_simple(path, *keys) - validate_path = path - - if (not @file_wrapper.exist?(validate_path)) - # no verbosity checking since this is lowest level anyhow & verbosity checking depends on configurator - @stream_wrapper.stderr_puts("ERROR: Config path '#{validate_path}' associated with #{format_key_sequence(keys, keys.size)} does not exist on disk.") - return false - end - - return true - end - - # walk into config hash. verify specified file exists. - def validate_filepath(config, *keys) - hash = retrieve_value(config, keys) - filepath = hash[:value] - - # return early if we couldn't walk into hash and find a value - return false if (filepath.nil?) - - # skip everything if we've got an argument replacement pattern - return true if (filepath =~ TOOL_EXECUTOR_ARGUMENT_REPLACEMENT_PATTERN) - - if (not @file_wrapper.exist?(filepath)) - - # See if we can deal with it internally. - if GENERATED_DIR_PATH.include?(filepath) - # we already made this directory before let's make it again. - FileUtils.mkdir_p File.join(File.dirname(__FILE__), filepath) - @stream_wrapper.stderr_puts("WARNING: Generated filepath #{format_key_sequence(keys, hash[:depth])}['#{filepath}'] does not exist on disk. Recreating") - - else - # no verbosity checking since this is lowest level anyhow & verbosity checking depends on configurator - @stream_wrapper.stderr_puts("ERROR: Config filepath #{format_key_sequence(keys, hash[:depth])}['#{filepath}'] does not exist on disk.") - return false - end - end - - return true - end - - # walk into config hash. verify specified file exists. - def validate_executable_filepath(config, *keys) - exe_extension = config[:extension][:executable] - hash = retrieve_value(config, keys) - filepath = hash[:value] - - # return early if we couldn't walk into hash and find a value - return false if (filepath.nil?) - - # skip everything if we've got an argument replacement pattern - return true if (filepath =~ TOOL_EXECUTOR_ARGUMENT_REPLACEMENT_PATTERN) - - # if there's no path included, verify file exists somewhere in system search paths - if (not filepath.include?('/')) - exists = false - - @system_wrapper.search_paths.each do |path| - if (@file_wrapper.exist?( File.join(path, filepath)) ) - exists = true - break - end - - if (@file_wrapper.exist?( (File.join(path, filepath)).ext( exe_extension ) )) - exists = true - break - elsif (@system_wrapper.windows? and @file_wrapper.exist?( (File.join(path, filepath)).ext( EXTENSION_WIN_EXE ) )) - exists = true - break - end - end - - if (not exists) - # no verbosity checking since this is lowest level anyhow & verbosity checking depends on configurator - @stream_wrapper.stderr_puts("ERROR: Config filepath #{format_key_sequence(keys, hash[:depth])}['#{filepath}'] does not exist in system search paths.") - return false - end - - # if there is a path included, check that explicit filepath exists - else - if (not @file_wrapper.exist?(filepath)) - # no verbosity checking since this is lowest level anyhow & verbosity checking depends on configurator - @stream_wrapper.stderr_puts("ERROR: Config filepath #{format_key_sequence(keys, hash[:depth])}['#{filepath}'] does not exist on disk.") - return false - end - end - - return true - end - - def validate_tool_stderr_redirect(config, tools, tool) - redirect = config[tools][tool][:stderr_redirect] - if (redirect.class == Symbol) - # map constants and force to array of strings for runtime universality across ruby versions - if (not StdErrRedirect.constants.map{|constant| constant.to_s}.include?(redirect.to_s.upcase)) - error = "ERROR: [:#{tools}][:#{tool}][:stderr_redirect][:#{redirect}] is not a recognized option " + - "{#{StdErrRedirect.constants.map{|constant| ':' + constant.to_s.downcase}.join(', ')}}." - @stream_wrapper.stderr_puts(error) - return false - end - end - - return true - end - - private ######################################### - - - def retrieve_value(config, keys) - value = nil - hash = config - depth = 0 - - # walk into hash & extract value at requested key sequence - keys.each do |symbol| - depth += 1 - if (not hash[symbol].nil?) - hash = hash[symbol] - value = hash - else - value = nil - break - end - end - - return {:value => value, :depth => depth} - end - - - def format_key_sequence(keys, depth) - walked_keys = keys.slice(0, depth) - formatted_keys = walked_keys.map{|key| "[:#{key.to_s}]"} - - return formatted_keys.join - end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/constants.rb b/test/unit-test/vendor/ceedling/lib/ceedling/constants.rb deleted file mode 100644 index 19484f063..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/constants.rb +++ /dev/null @@ -1,99 +0,0 @@ - -class Verbosity - SILENT = 0 # as silent as possible (though there are some messages that must be spit out) - ERRORS = 1 # only errors - COMPLAIN = 2 # spit out errors and warnings/notices - NORMAL = 3 # errors, warnings/notices, standard status messages - OBNOXIOUS = 4 # all messages including extra verbose output (used for lite debugging / verification) - DEBUG = 5 # special extra verbose output for hardcore debugging -end - - -class TestResultsSanityChecks - NONE = 0 # no sanity checking of test results - NORMAL = 1 # perform non-problematic checks - THOROUGH = 2 # perform checks that require inside knowledge of system workings -end - - -class StdErrRedirect - NONE = :none - AUTO = :auto - WIN = :win - UNIX = :unix - TCSH = :tcsh -end - - -class BackgroundExec - NONE = :none - AUTO = :auto - WIN = :win - UNIX = :unix -end - -unless defined?(PROJECT_ROOT) - PROJECT_ROOT = Dir.pwd() -end - -GENERATED_DIR_PATH = [['vendor', 'ceedling'], 'src', "test", ['test', 'support'], 'build'].each{|p| File.join(*p)} - -EXTENSION_WIN_EXE = '.exe' -EXTENSION_NONWIN_EXE = '.out' - - -CEXCEPTION_ROOT_PATH = 'c_exception' -CEXCEPTION_LIB_PATH = "#{CEXCEPTION_ROOT_PATH}/lib" -CEXCEPTION_C_FILE = 'CException.c' -CEXCEPTION_H_FILE = 'CException.h' - -UNITY_ROOT_PATH = 'unity' -UNITY_LIB_PATH = "#{UNITY_ROOT_PATH}/src" -UNITY_C_FILE = 'unity.c' -UNITY_H_FILE = 'unity.h' -UNITY_INTERNALS_H_FILE = 'unity_internals.h' - -CMOCK_ROOT_PATH = 'cmock' -CMOCK_LIB_PATH = "#{CMOCK_ROOT_PATH}/src" -CMOCK_C_FILE = 'cmock.c' -CMOCK_H_FILE = 'cmock.h' - - -DEFAULT_CEEDLING_MAIN_PROJECT_FILE = 'project.yml' unless defined?(DEFAULT_CEEDLING_MAIN_PROJECT_FILE) # main project file -DEFAULT_CEEDLING_USER_PROJECT_FILE = 'user.yml' unless defined?(DEFAULT_CEEDLING_USER_PROJECT_FILE) # supplemental user config file - -INPUT_CONFIGURATION_CACHE_FILE = 'input.yml' unless defined?(INPUT_CONFIGURATION_CACHE_FILE) # input configuration file dump -DEFINES_DEPENDENCY_CACHE_FILE = 'defines_dependency.yml' unless defined?(DEFINES_DEPENDENCY_CACHE_FILE) # preprocessor definitions for files - -TEST_ROOT_NAME = 'test' unless defined?(TEST_ROOT_NAME) -TEST_TASK_ROOT = TEST_ROOT_NAME + ':' unless defined?(TEST_TASK_ROOT) -TEST_SYM = TEST_ROOT_NAME.to_sym unless defined?(TEST_SYM) - -RELEASE_ROOT_NAME = 'release' unless defined?(RELEASE_ROOT_NAME) -RELEASE_TASK_ROOT = RELEASE_ROOT_NAME + ':' unless defined?(RELEASE_TASK_ROOT) -RELEASE_SYM = RELEASE_ROOT_NAME.to_sym unless defined?(RELEASE_SYM) - -REFRESH_ROOT_NAME = 'refresh' unless defined?(REFRESH_ROOT_NAME) -REFRESH_TASK_ROOT = REFRESH_ROOT_NAME + ':' unless defined?(REFRESH_TASK_ROOT) -REFRESH_SYM = REFRESH_ROOT_NAME.to_sym unless defined?(REFRESH_SYM) - -UTILS_ROOT_NAME = 'utils' unless defined?(UTILS_ROOT_NAME) -UTILS_TASK_ROOT = UTILS_ROOT_NAME + ':' unless defined?(UTILS_TASK_ROOT) -UTILS_SYM = UTILS_ROOT_NAME.to_sym unless defined?(UTILS_SYM) - -OPERATION_COMPILE_SYM = :compile unless defined?(OPERATION_COMPILE_SYM) -OPERATION_ASSEMBLE_SYM = :assemble unless defined?(OPERATION_ASSEMBLE_SYM) -OPERATION_LINK_SYM = :link unless defined?(OPERATION_LINK_SYM) - - -RUBY_STRING_REPLACEMENT_PATTERN = /#\{.+\}/ -RUBY_EVAL_REPLACEMENT_PATTERN = /^\{(.+)\}$/ -TOOL_EXECUTOR_ARGUMENT_REPLACEMENT_PATTERN = /(\$\{(\d+)\})/ -TEST_STDOUT_STATISTICS_PATTERN = /\n-+\s*(\d+)\s+Tests\s+(\d+)\s+Failures\s+(\d+)\s+Ignored\s+(OK|FAIL)\s*/i - -NULL_FILE_PATH = '/dev/null' - -TESTS_BASE_PATH = TEST_ROOT_NAME -RELEASE_BASE_PATH = RELEASE_ROOT_NAME - -VENDORS_FILES = %w(unity UnityHelper cmock CException).freeze diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/defaults.rb b/test/unit-test/vendor/ceedling/lib/ceedling/defaults.rb deleted file mode 100644 index 1300a1aab..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/defaults.rb +++ /dev/null @@ -1,471 +0,0 @@ -require 'ceedling/constants' -require 'ceedling/system_wrapper' -require 'ceedling/file_path_utils' - -#this should be defined already, but not always during system specs -CEEDLING_VENDOR = File.expand_path(File.dirname(__FILE__) + '/../../vendor') unless defined? CEEDLING_VENDOR -CEEDLING_PLUGINS = [] unless defined? CEEDLING_PLUGINS - -DEFAULT_TEST_COMPILER_TOOL = { - :executable => ENV['CC'].nil? ? FilePathUtils.os_executable_ext('gcc').freeze : ENV['CC'].split[0], - :name => 'default_test_compiler'.freeze, - :stderr_redirect => StdErrRedirect::NONE.freeze, - :background_exec => BackgroundExec::NONE.freeze, - :optional => false.freeze, - :arguments => [ - ENV['CC'].nil? ? "" : ENV['CC'].split[1..-1], - ENV['CPPFLAGS'].nil? ? "" : ENV['CPPFLAGS'].split, - {"-I\"$\"" => 'COLLECTION_PATHS_TEST_SUPPORT_SOURCE_INCLUDE_VENDOR'}.freeze, - {"-I\"$\"" => 'COLLECTION_PATHS_TEST_TOOLCHAIN_INCLUDE'}.freeze, - {"-D$" => 'COLLECTION_DEFINES_TEST_AND_VENDOR'}.freeze, - "-DGNU_COMPILER".freeze, - "-g".freeze, - ENV['CFLAGS'].nil? ? "" : ENV['CFLAGS'].split, - "-c \"${1}\"".freeze, - "-o \"${2}\"".freeze, - # gcc's list file output options are complex; no use of ${3} parameter in default config - "-MMD".freeze, - "-MF \"${4}\"".freeze, - ].freeze - } - -DEFAULT_TEST_LINKER_TOOL = { - :executable => ENV['CCLD'].nil? ? FilePathUtils.os_executable_ext('gcc').freeze : ENV['CCLD'].split[0], - :name => 'default_test_linker'.freeze, - :stderr_redirect => StdErrRedirect::NONE.freeze, - :background_exec => BackgroundExec::NONE.freeze, - :optional => false.freeze, - :arguments => [ - ENV['CCLD'].nil? ? "" : ENV['CCLD'].split[1..-1], - ENV['CFLAGS'].nil? ? "" : ENV['CFLAGS'].split, - ENV['LDFLAGS'].nil? ? "" : ENV['LDFLAGS'].split, - "\"${1}\"".freeze, - "${5}".freeze, - "-o \"${2}\"".freeze, - "".freeze, - "${4}".freeze, - ENV['LDLIBS'].nil? ? "" : ENV['LDLIBS'].split - ].freeze - } - -DEFAULT_TEST_FIXTURE_TOOL = { - :executable => '${1}'.freeze, - :name => 'default_test_fixture'.freeze, - :stderr_redirect => StdErrRedirect::AUTO.freeze, - :background_exec => BackgroundExec::NONE.freeze, - :optional => false.freeze, - :arguments => [].freeze - } - -DEFAULT_TEST_INCLUDES_PREPROCESSOR_TOOL = { - :executable => ENV['CC'].nil? ? FilePathUtils.os_executable_ext('gcc').freeze : ENV['CC'].split[0], - :name => 'default_test_includes_preprocessor'.freeze, - :stderr_redirect => StdErrRedirect::NONE.freeze, - :background_exec => BackgroundExec::NONE.freeze, - :optional => false.freeze, - :arguments => [ - ENV['CC'].nil? ? "" : ENV['CC'].split[1..-1], - ENV['CPPFLAGS'].nil? ? "" : ENV['CPPFLAGS'].split, - '-E'.freeze, # OSX clang - '-MM'.freeze, - '-MG'.freeze, - # avoid some possibility of deep system lib header file complications by omitting vendor paths - # if cpp is run on *nix system, escape spaces in paths; if cpp on windows just use the paths collection as is - # {"-I\"$\"" => "{SystemWrapper.windows? ? COLLECTION_PATHS_TEST_SUPPORT_SOURCE_INCLUDE : COLLECTION_PATHS_TEST_SUPPORT_SOURCE_INCLUDE.map{|path| path.gsub(\/ \/, \'\\\\ \') }}"}.freeze, - {"-I\"$\"" => 'COLLECTION_PATHS_TEST_SUPPORT_SOURCE_INCLUDE_VENDOR'}.freeze, - {"-I\"$\"" => 'COLLECTION_PATHS_TEST_TOOLCHAIN_INCLUDE'}.freeze, - {"-D$" => 'COLLECTION_DEFINES_TEST_AND_VENDOR'}.freeze, - {"-D$" => 'DEFINES_TEST_PREPROCESS'}.freeze, - "-DGNU_COMPILER".freeze, # OSX clang - # '-nostdinc'.freeze, # disabled temporarily due to stdio access violations on OSX - "\"${1}\"".freeze - ].freeze - } - -DEFAULT_TEST_FILE_PREPROCESSOR_TOOL = { - :executable => ENV['CC'].nil? ? FilePathUtils.os_executable_ext('gcc').freeze : ENV['CC'].split[0], - :name => 'default_test_file_preprocessor'.freeze, - :stderr_redirect => StdErrRedirect::NONE.freeze, - :background_exec => BackgroundExec::NONE.freeze, - :optional => false.freeze, - :arguments => [ - ENV['CC'].nil? ? "" : ENV['CC'].split[1..-1], - ENV['CPPFLAGS'].nil? ? "" : ENV['CPPFLAGS'].split, - '-E'.freeze, - {"-I\"$\"" => 'COLLECTION_PATHS_TEST_SUPPORT_SOURCE_INCLUDE_VENDOR'}.freeze, - {"-I\"$\"" => 'COLLECTION_PATHS_TEST_TOOLCHAIN_INCLUDE'}.freeze, - {"-D$" => 'COLLECTION_DEFINES_TEST_AND_VENDOR'}.freeze, - {"-D$" => 'DEFINES_TEST_PREPROCESS'}.freeze, - "-DGNU_COMPILER".freeze, - # '-nostdinc'.freeze, # disabled temporarily due to stdio access violations on OSX - "\"${1}\"".freeze, - "-o \"${2}\"".freeze - ].freeze - } - -DEFAULT_TEST_FILE_PREPROCESSOR_DIRECTIVES_TOOL = { - :executable => FilePathUtils.os_executable_ext('gcc').freeze, - :name => 'default_test_file_preprocessor_directives'.freeze, - :stderr_redirect => StdErrRedirect::NONE.freeze, - :background_exec => BackgroundExec::NONE.freeze, - :optional => false.freeze, - :arguments => [ - '-E'.freeze, - {"-I\"$\"" => 'COLLECTION_PATHS_TEST_SUPPORT_SOURCE_INCLUDE_VENDOR'}.freeze, - {"-I\"$\"" => 'COLLECTION_PATHS_TEST_TOOLCHAIN_INCLUDE'}.freeze, - {"-D$" => 'COLLECTION_DEFINES_TEST_AND_VENDOR'}.freeze, - {"-D$" => 'DEFINES_TEST_PREPROCESS'}.freeze, - "-DGNU_COMPILER".freeze, - '-fdirectives-only'.freeze, - # '-nostdinc'.freeze, # disabled temporarily due to stdio access violations on OSX - "\"${1}\"".freeze, - "-o \"${2}\"".freeze - ].freeze - } - -# Disable the -MD flag for OSX LLVM Clang, since unsupported -if RUBY_PLATFORM =~ /darwin/ && `gcc --version 2> /dev/null` =~ /Apple LLVM version .* \(clang/m # OSX w/LLVM Clang - MD_FLAG = '' # Clang doesn't support the -MD flag -else - MD_FLAG = '-MD' -end - -DEFAULT_TEST_DEPENDENCIES_GENERATOR_TOOL = { - :executable => ENV['CC'].nil? ? FilePathUtils.os_executable_ext('gcc').freeze : ENV['CC'].split[0], - :name => 'default_test_dependencies_generator'.freeze, - :stderr_redirect => StdErrRedirect::NONE.freeze, - :background_exec => BackgroundExec::NONE.freeze, - :optional => false.freeze, - :arguments => [ - ENV['CC'].nil? ? "" : ENV['CC'].split[1..-1], - ENV['CPPFLAGS'].nil? ? "" : ENV['CPPFLAGS'].split, - '-E'.freeze, - {"-I\"$\"" => 'COLLECTION_PATHS_TEST_SUPPORT_SOURCE_INCLUDE_VENDOR'}.freeze, - {"-I\"$\"" => 'COLLECTION_PATHS_TEST_TOOLCHAIN_INCLUDE'}.freeze, - {"-D$" => 'COLLECTION_DEFINES_TEST_AND_VENDOR'}.freeze, - {"-D$" => 'DEFINES_TEST_PREPROCESS'}.freeze, - "-DGNU_COMPILER".freeze, - "-MT \"${3}\"".freeze, - '-MM'.freeze, - MD_FLAG.freeze, - '-MG'.freeze, - "-MF \"${2}\"".freeze, - "-c \"${1}\"".freeze, - # '-nostdinc'.freeze, - ].freeze - } - -DEFAULT_RELEASE_DEPENDENCIES_GENERATOR_TOOL = { - :executable => ENV['CC'].nil? ? FilePathUtils.os_executable_ext('gcc').freeze : ENV['CC'].split[0], - :name => 'default_release_dependencies_generator'.freeze, - :stderr_redirect => StdErrRedirect::NONE.freeze, - :background_exec => BackgroundExec::NONE.freeze, - :optional => false.freeze, - :arguments => [ - ENV['CC'].nil? ? "" : ENV['CC'].split[1..-1], - ENV['CPPFLAGS'].nil? ? "" : ENV['CPPFLAGS'].split, - '-E'.freeze, - {"-I\"$\"" => 'COLLECTION_PATHS_SOURCE_INCLUDE_VENDOR'}.freeze, - {"-I\"$\"" => 'COLLECTION_PATHS_RELEASE_TOOLCHAIN_INCLUDE'}.freeze, - {"-D$" => 'COLLECTION_DEFINES_RELEASE_AND_VENDOR'}.freeze, - {"-D$" => 'DEFINES_RELEASE_PREPROCESS'}.freeze, - "-DGNU_COMPILER".freeze, - "-MT \"${3}\"".freeze, - '-MM'.freeze, - MD_FLAG.freeze, - '-MG'.freeze, - "-MF \"${2}\"".freeze, - "-c \"${1}\"".freeze, - # '-nostdinc'.freeze, - ].freeze - } - - -DEFAULT_RELEASE_COMPILER_TOOL = { - :executable => ENV['CC'].nil? ? FilePathUtils.os_executable_ext('gcc').freeze : ENV['CC'].split[0], - :name => 'default_release_compiler'.freeze, - :stderr_redirect => StdErrRedirect::NONE.freeze, - :background_exec => BackgroundExec::NONE.freeze, - :optional => false.freeze, - :arguments => [ - ENV['CC'].nil? ? "" : ENV['CC'].split[1..-1], - ENV['CPPFLAGS'].nil? ? "" : ENV['CPPFLAGS'].split, - {"-I\"$\"" => 'COLLECTION_PATHS_SOURCE_INCLUDE_VENDOR'}.freeze, - {"-I\"$\"" => 'COLLECTION_PATHS_RELEASE_TOOLCHAIN_INCLUDE'}.freeze, - {"-D$" => 'COLLECTION_DEFINES_RELEASE_AND_VENDOR'}.freeze, - "-DGNU_COMPILER".freeze, - ENV['CFLAGS'].nil? ? "" : ENV['CFLAGS'].split, - "-c \"${1}\"".freeze, - "-o \"${2}\"".freeze, - # gcc's list file output options are complex; no use of ${3} parameter in default config - "-MMD".freeze, - "-MF \"${4}\"".freeze, - ].freeze - } - -DEFAULT_RELEASE_ASSEMBLER_TOOL = { - :executable => ENV['AS'].nil? ? FilePathUtils.os_executable_ext('as').freeze : ENV['AS'].split[0], - :name => 'default_release_assembler'.freeze, - :stderr_redirect => StdErrRedirect::NONE.freeze, - :background_exec => BackgroundExec::NONE.freeze, - :optional => false.freeze, - :arguments => [ - ENV['AS'].nil? ? "" : ENV['AS'].split[1..-1], - ENV['ASFLAGS'].nil? ? "" : ENV['ASFLAGS'].split, - {"-I\"$\"" => 'COLLECTION_PATHS_SOURCE_AND_INCLUDE'}.freeze, - "\"${1}\"".freeze, - "-o \"${2}\"".freeze, - ].freeze - } - -DEFAULT_RELEASE_LINKER_TOOL = { - :executable => ENV['CCLD'].nil? ? FilePathUtils.os_executable_ext('gcc').freeze : ENV['CCLD'].split[0], - :name => 'default_release_linker'.freeze, - :stderr_redirect => StdErrRedirect::NONE.freeze, - :background_exec => BackgroundExec::NONE.freeze, - :optional => false.freeze, - :arguments => [ - ENV['CCLD'].nil? ? "" : ENV['CCLD'].split[1..-1], - ENV['CFLAGS'].nil? ? "" : ENV['CFLAGS'].split, - ENV['LDFLAGS'].nil? ? "" : ENV['LDFLAGS'].split, - "\"${1}\"".freeze, - "${5}".freeze, - "-o \"${2}\"".freeze, - "".freeze, - "${4}".freeze, - ENV['LDLIBS'].nil? ? "" : ENV['LDLIBS'].split - ].freeze - } - - -DEFAULT_TOOLS_TEST = { - :tools => { - :test_compiler => DEFAULT_TEST_COMPILER_TOOL, - :test_linker => DEFAULT_TEST_LINKER_TOOL, - :test_fixture => DEFAULT_TEST_FIXTURE_TOOL, - } - } - -DEFAULT_TOOLS_TEST_PREPROCESSORS = { - :tools => { - :test_includes_preprocessor => DEFAULT_TEST_INCLUDES_PREPROCESSOR_TOOL, - :test_file_preprocessor => DEFAULT_TEST_FILE_PREPROCESSOR_TOOL, - :test_file_preprocessor_directives => DEFAULT_TEST_FILE_PREPROCESSOR_DIRECTIVES_TOOL, - } - } - -DEFAULT_TOOLS_TEST_DEPENDENCIES = { - :tools => { - :test_dependencies_generator => DEFAULT_TEST_DEPENDENCIES_GENERATOR_TOOL, - } - } - - -DEFAULT_TOOLS_RELEASE = { - :tools => { - :release_compiler => DEFAULT_RELEASE_COMPILER_TOOL, - :release_linker => DEFAULT_RELEASE_LINKER_TOOL, - } - } - -DEFAULT_TOOLS_RELEASE_ASSEMBLER = { - :tools => { - :release_assembler => DEFAULT_RELEASE_ASSEMBLER_TOOL, - } - } - -DEFAULT_TOOLS_RELEASE_DEPENDENCIES = { - :tools => { - :release_dependencies_generator => DEFAULT_RELEASE_DEPENDENCIES_GENERATOR_TOOL, - } - } - - -DEFAULT_RELEASE_TARGET_NAME = 'project' - -DEFAULT_CEEDLING_CONFIG = { - :project => { - # :build_root must be set by user - :use_exceptions => true, - :use_mocks => true, - :compile_threads => 1, - :test_threads => 1, - :use_test_preprocessor => false, - :use_preprocessor_directives => false, - :use_deep_dependencies => false, - :generate_deep_dependencies => true, # only applicable if use_deep_dependencies is true - :auto_link_deep_dependencies => false, - :test_file_prefix => 'test_', - :options_paths => [], - :release_build => false, - }, - - :release_build => { - # :output is set while building configuration -- allows smart default system-dependent file extension handling - :use_assembly => false, - :artifacts => [], - }, - - :paths => { - :test => [], # must be populated by user - :source => [], # must be populated by user - :support => [], - :include => [], - :libraries => [], - :test_toolchain_include => [], - :release_toolchain_include => [], - }, - - :files => { - :test => [], - :source => [], - :assembly => [], - :support => [], - :include => [], - }, - - # unlike other top-level entries, environment's value is an array to preserve order - :environment => [ - # when evaluated, this provides wider text field for rake task comments - {:rake_columns => '120'}, - ], - - :defines => { - :test => [], - :test_preprocess => [], - :release => [], - :release_preprocess => [], - :use_test_definition => false, - }, - - :libraries => { - :flag => '-l${1}', - :path_flag => '-L ${1}', - :test => [], - :test_preprocess => [], - :release => [], - :release_preprocess => [], - }, - - :flags => {}, - - :extension => { - :header => '.h', - :source => '.c', - :assembly => '.s', - :object => '.o', - :libraries => ['.a','.so'], - :executable => ( SystemWrapper.windows? ? EXTENSION_WIN_EXE : EXTENSION_NONWIN_EXE ), - :map => '.map', - :list => '.lst', - :testpass => '.pass', - :testfail => '.fail', - :dependencies => '.d', - }, - - :unity => { - :vendor_path => CEEDLING_VENDOR, - :defines => [] - }, - - :cmock => { - :vendor_path => CEEDLING_VENDOR, - :defines => [], - :includes => [] - }, - - :cexception => { - :vendor_path => CEEDLING_VENDOR, - :defines => [] - }, - - :test_runner => { - :includes => [], - :file_suffix => '_runner', - }, - - # all tools populated while building up config structure - :tools => {}, - - # empty argument lists for default tools - # (these can be overridden in project file to add arguments to tools without totally redefining tools) - :test_compiler => { :arguments => [] }, - :test_linker => { :arguments => [] }, - :test_fixture => { - :arguments => [], - :link_objects => [], # compiled object files to always be linked in (e.g. cmock.o if using mocks) - }, - :test_includes_preprocessor => { :arguments => [] }, - :test_file_preprocessor => { :arguments => [] }, - :test_file_preprocessor_directives => { :arguments => [] }, - :test_dependencies_generator => { :arguments => [] }, - :release_compiler => { :arguments => [] }, - :release_linker => { :arguments => [] }, - :release_assembler => { :arguments => [] }, - :release_dependencies_generator => { :arguments => [] }, - - :plugins => { - :load_paths => CEEDLING_PLUGINS, - :enabled => [], - } - }.freeze - - -DEFAULT_TESTS_RESULTS_REPORT_TEMPLATE = %q{ -% ignored = hash[:results][:counts][:ignored] -% failed = hash[:results][:counts][:failed] -% stdout_count = hash[:results][:counts][:stdout] -% header_prepend = ((hash[:header].length > 0) ? "#{hash[:header]}: " : '') -% banner_width = 25 + header_prepend.length # widest message - -% if (stdout_count > 0) -<%=@ceedling[:plugin_reportinator].generate_banner(header_prepend + 'TEST OUTPUT')%> -% hash[:results][:stdout].each do |string| -% string[:collection].each do |item| -<%=string[:source][:path]%><%=File::SEPARATOR%><%=string[:source][:file]%>: "<%=item%>" -% end -% end - -% end -% if (ignored > 0) -<%=@ceedling[:plugin_reportinator].generate_banner(header_prepend + 'IGNORED TEST SUMMARY')%> -% hash[:results][:ignores].each do |ignore| -% ignore[:collection].each do |item| -<%=ignore[:source][:path]%><%=File::SEPARATOR%><%=ignore[:source][:file]%>:<%=item[:line]%>:<%=item[:test]%> -% if (item[:message].length > 0) -: "<%=item[:message]%>" -% else -<%="\n"%> -% end -% end -% end - -% end -% if (failed > 0) -<%=@ceedling[:plugin_reportinator].generate_banner(header_prepend + 'FAILED TEST SUMMARY')%> -% hash[:results][:failures].each do |failure| -% failure[:collection].each do |item| -<%=failure[:source][:path]%><%=File::SEPARATOR%><%=failure[:source][:file]%>:<%=item[:line]%>:<%=item[:test]%> -% if (item[:message].length > 0) -: "<%=item[:message]%>" -% else -<%="\n"%> -% end -% end -% end - -% end -% total_string = hash[:results][:counts][:total].to_s -% format_string = "%#{total_string.length}i" -<%=@ceedling[:plugin_reportinator].generate_banner(header_prepend + 'OVERALL TEST SUMMARY')%> -% if (hash[:results][:counts][:total] > 0) -TESTED: <%=hash[:results][:counts][:total].to_s%> -PASSED: <%=sprintf(format_string, hash[:results][:counts][:passed])%> -FAILED: <%=sprintf(format_string, failed)%> -IGNORED: <%=sprintf(format_string, ignored)%> -% else - -No tests executed. -% end - -} diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/dependinator.rb b/test/unit-test/vendor/ceedling/lib/ceedling/dependinator.rb deleted file mode 100644 index accfe80c9..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/dependinator.rb +++ /dev/null @@ -1,97 +0,0 @@ - -class Dependinator - - constructor :configurator, :project_config_manager, :test_includes_extractor, :file_path_utils, :rake_wrapper, :file_wrapper - - def touch_force_rebuild_files - @file_wrapper.touch( @configurator.project_test_force_rebuild_filepath ) - @file_wrapper.touch( @configurator.project_release_force_rebuild_filepath ) if (@configurator.project_release_build) - end - - - - def load_release_object_deep_dependencies(dependencies_list) - dependencies_list.each do |dependencies_file| - if File.exists?(dependencies_file) - @rake_wrapper.load_dependencies( dependencies_file ) - end - end - end - - - def enhance_release_file_dependencies(files) - files.each do |filepath| - @rake_wrapper[filepath].enhance( [@configurator.project_release_force_rebuild_filepath] ) if (@project_config_manager.release_config_changed) - end - end - - - - def load_test_object_deep_dependencies(files_list) - dependencies_list = @file_path_utils.form_test_dependencies_filelist(files_list) - dependencies_list.each do |dependencies_file| - if File.exists?(dependencies_file) - @rake_wrapper.load_dependencies(dependencies_file) - end - end - end - - - def enhance_runner_dependencies(runner_filepath) - @rake_wrapper[runner_filepath].enhance( [@configurator.project_test_force_rebuild_filepath] ) if (@project_config_manager.test_config_changed || - @project_config_manager.test_defines_changed) - end - - - def enhance_shallow_include_lists_dependencies(include_lists) - include_lists.each do |include_list_filepath| - @rake_wrapper[include_list_filepath].enhance( [@configurator.project_test_force_rebuild_filepath] ) if (@project_config_manager.test_config_changed || - @project_config_manager.test_defines_changed) - end - end - - - def enhance_preprocesed_file_dependencies(files) - files.each do |filepath| - @rake_wrapper[filepath].enhance( [@configurator.project_test_force_rebuild_filepath] ) if (@project_config_manager.test_config_changed || - @project_config_manager.test_defines_changed) - end - end - - - def enhance_mock_dependencies(mocks_list) - # if input configuration or ceedling changes, make sure these guys get rebuilt - mocks_list.each do |mock_filepath| - @rake_wrapper[mock_filepath].enhance( [@configurator.project_test_force_rebuild_filepath] ) if (@project_config_manager.test_config_changed || - @project_config_manager.test_defines_changed) - @rake_wrapper[mock_filepath].enhance( @configurator.cmock_unity_helper ) if (@configurator.cmock_unity_helper) - end - end - - - def enhance_dependencies_dependencies(dependencies) - dependencies.each do |dependencies_filepath| - @rake_wrapper[dependencies_filepath].enhance( [@configurator.project_test_force_rebuild_filepath] ) if (@project_config_manager.test_config_changed || - @project_config_manager.test_defines_changed) - end - end - - - def enhance_test_build_object_dependencies(objects) - objects.each do |object_filepath| - @rake_wrapper[object_filepath].enhance( [@configurator.project_test_force_rebuild_filepath] ) if (@project_config_manager.test_config_changed || - @project_config_manager.test_defines_changed) - end - end - - - def enhance_results_dependencies(result_filepath) - @rake_wrapper[result_filepath].enhance( [@configurator.project_test_force_rebuild_filepath] ) if @project_config_manager.test_config_changed - end - - - def enhance_test_executable_dependencies(test, objects) - @rake_wrapper[ @file_path_utils.form_test_executable_filepath(test) ].enhance( objects ) - end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/erb_wrapper.rb b/test/unit-test/vendor/ceedling/lib/ceedling/erb_wrapper.rb deleted file mode 100644 index dab8d736b..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/erb_wrapper.rb +++ /dev/null @@ -1,9 +0,0 @@ -require 'erb' - -class ErbWrapper - def generate_file(template, data, output_file) - File.open(output_file, "w") do |f| - f << ERB.new(template, 0, "<>").result(binding) - end - end -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/file_finder.rb b/test/unit-test/vendor/ceedling/lib/ceedling/file_finder.rb deleted file mode 100644 index 4a1064c52..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/file_finder.rb +++ /dev/null @@ -1,148 +0,0 @@ -require 'rubygems' -require 'rake' # for adding ext() method to string -require 'thread' - - -class FileFinder - SEMAPHORE = Mutex.new - - constructor :configurator, :file_finder_helper, :cacheinator, :file_path_utils, :file_wrapper, :yaml_wrapper - - def prepare_search_sources - @all_test_source_and_header_file_collection = - @configurator.collection_all_tests + - @configurator.collection_all_source + - @configurator.collection_all_headers - end - - - def find_header_file(mock_file) - header = File.basename(mock_file).sub(/#{@configurator.cmock_mock_prefix}/, '').ext(@configurator.extension_header) - - found_path = @file_finder_helper.find_file_in_collection(header, @configurator.collection_all_headers, :error) - - return found_path - end - - - def find_header_input_for_mock_file(mock_file) - found_path = find_header_file(mock_file) - mock_input = found_path - - if (@configurator.project_use_test_preprocessor) - mock_input = @cacheinator.diff_cached_test_file( @file_path_utils.form_preprocessed_file_filepath( found_path ) ) - end - - return mock_input - end - - - def find_source_from_test(test, complain) - test_prefix = @configurator.project_test_file_prefix - source_paths = @configurator.collection_all_source - - source = File.basename(test).sub(/#{test_prefix}/, '') - - # we don't blow up if a test file has no corresponding source file - return @file_finder_helper.find_file_in_collection(source, source_paths, complain) - end - - - def find_test_from_runner_path(runner_path) - extension_source = @configurator.extension_source - - test_file = File.basename(runner_path).sub(/#{@configurator.test_runner_file_suffix}#{'\\'+extension_source}/, extension_source) - - found_path = @file_finder_helper.find_file_in_collection(test_file, @configurator.collection_all_tests, :error) - - return found_path - end - - - def find_test_input_for_runner_file(runner_path) - found_path = find_test_from_runner_path(runner_path) - runner_input = found_path - - if (@configurator.project_use_test_preprocessor) - runner_input = @cacheinator.diff_cached_test_file( @file_path_utils.form_preprocessed_file_filepath( found_path ) ) - end - - return runner_input - end - - - def find_test_from_file_path(file_path) - test_file = File.basename(file_path).ext(@configurator.extension_source) - - found_path = @file_finder_helper.find_file_in_collection(test_file, @configurator.collection_all_tests, :error) - - return found_path - end - - - def find_test_or_source_or_header_file(file_path) - file = File.basename(file_path) - return @file_finder_helper.find_file_in_collection(file, @all_test_source_and_header_file_collection, :error) - end - - - def find_compilation_input_file(file_path, complain=:error, release=false) - found_file = nil - - source_file = File.basename(file_path).ext(@configurator.extension_source) - - # We only collect files that already exist when we start up. - # FileLists can produce undesired results for dynamically generated files depending on when they're accessed. - # So collect mocks and runners separately and right now. - - SEMAPHORE.synchronize { - - if (source_file =~ /#{@configurator.test_runner_file_suffix}/) - found_file = - @file_finder_helper.find_file_in_collection( - source_file, - @file_wrapper.directory_listing( File.join(@configurator.project_test_runners_path, '*') ), - complain) - - elsif (@configurator.project_use_mocks and (source_file =~ /#{@configurator.cmock_mock_prefix}/)) - found_file = - @file_finder_helper.find_file_in_collection( - source_file, - @file_wrapper.directory_listing( File.join(@configurator.cmock_mock_path, '*') ), - complain) - - elsif release - found_file = - @file_finder_helper.find_file_in_collection( - source_file, - @configurator.collection_release_existing_compilation_input, - complain) - else - temp_complain = (defined?(TEST_BUILD_USE_ASSEMBLY) && TEST_BUILD_USE_ASSEMBLY) ? :ignore : complain - found_file = - @file_finder_helper.find_file_in_collection( - source_file, - @configurator.collection_all_existing_compilation_input, - temp_complain) - found_file ||= find_assembly_file(file_path, false) if (defined?(TEST_BUILD_USE_ASSEMBLY) && TEST_BUILD_USE_ASSEMBLY) - end - } - return found_file - end - - - def find_source_file(file_path, complain) - source_file = File.basename(file_path).ext(@configurator.extension_source) - return @file_finder_helper.find_file_in_collection(source_file, @configurator.collection_all_source, complain) - end - - - def find_assembly_file(file_path, complain = :error) - assembly_file = File.basename(file_path).ext(@configurator.extension_assembly) - return @file_finder_helper.find_file_in_collection(assembly_file, @configurator.collection_all_assembly, complain) - end - - def find_file_from_list(file_path, file_list, complain) - return @file_finder_helper.find_file_in_collection(file_path, file_list, complain) - end -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/file_finder_helper.rb b/test/unit-test/vendor/ceedling/lib/ceedling/file_finder_helper.rb deleted file mode 100644 index f2d6a5e91..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/file_finder_helper.rb +++ /dev/null @@ -1,54 +0,0 @@ -require 'fileutils' -require 'ceedling/constants' # for Verbosity enumeration - -class FileFinderHelper - - constructor :streaminator - - - def find_file_in_collection(file_name, file_list, complain, extra_message="") - file_to_find = nil - - file_list.each do |item| - base_file = File.basename(item) - - # case insensitive comparison - if (base_file.casecmp(file_name) == 0) - # case sensitive check - if (base_file == file_name) - file_to_find = item - break - else - blow_up(file_name, "However, a filename having different capitalization was found: '#{item}'.") - end - end - - end - - if file_to_find.nil? - case (complain) - when :error then blow_up(file_name, extra_message) - when :warn then gripe(file_name, extra_message) - #when :ignore then - end - end - - return file_to_find - end - - private - - def blow_up(file_name, extra_message="") - error = "ERROR: Found no file '#{file_name}' in search paths." - error += ' ' if (extra_message.length > 0) - @streaminator.stderr_puts(error + extra_message, Verbosity::ERRORS) - raise - end - - def gripe(file_name, extra_message="") - warning = "WARNING: Found no file '#{file_name}' in search paths." - warning += ' ' if (extra_message.length > 0) - @streaminator.stderr_puts(warning + extra_message, Verbosity::COMPLAIN) - end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/file_path_utils.rb b/test/unit-test/vendor/ceedling/lib/ceedling/file_path_utils.rb deleted file mode 100644 index 89a28ba7f..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/file_path_utils.rb +++ /dev/null @@ -1,202 +0,0 @@ -require 'rubygems' -require 'rake' # for ext() -require 'fileutils' -require 'ceedling/system_wrapper' - -# global utility methods (for plugins, project files, etc.) -def ceedling_form_filepath(destination_path, original_filepath, new_extension=nil) - filename = File.basename(original_filepath) - filename.replace(filename.ext(new_extension)) if (!new_extension.nil?) - return File.join( destination_path.gsub(/\\/, '/'), filename ) -end - -class FilePathUtils - - GLOB_MATCHER = /[\*\?\{\}\[\]]/ - - constructor :configurator, :file_wrapper - - - ######### class methods ########## - - # standardize path to use '/' path separator & have no trailing path separator - def self.standardize(path) - if path.is_a? String - path.strip! - path.gsub!(/\\/, '/') - path.chomp!('/') - end - return path - end - - def self.os_executable_ext(executable) - return executable.ext('.exe') if SystemWrapper.windows? - return executable - end - - # extract directory path from between optional add/subtract aggregation modifiers and up to glob specifiers - # note: slightly different than File.dirname in that /files/foo remains /files/foo and does not become /files - def self.extract_path(path) - path = path.sub(/^(\+|-):/, '') - - # find first occurrence of path separator followed by directory glob specifier: *, ?, {, }, [, ] - find_index = (path =~ GLOB_MATCHER) - - # no changes needed (lop off final path separator) - return path.chomp('/') if (find_index.nil?) - - # extract up to first glob specifier - path = path[0..(find_index-1)] - - # lop off everything up to and including final path separator - find_index = path.rindex('/') - return path[0..(find_index-1)] if (not find_index.nil?) - - # return string up to first glob specifier if no path separator found - return path - end - - # return whether the given path is to be aggregated (no aggregation modifier defaults to same as +:) - def self.add_path?(path) - return (path =~ /^-:/).nil? - end - - # get path (and glob) lopping off optional +: / -: prefixed aggregation modifiers - def self.extract_path_no_aggregation_operators(path) - return path.sub(/^(\+|-):/, '') - end - - # all the globs that may be in a path string work fine with one exception; - # to recurse through all subdirectories, the glob is dir/**/** but our paths use - # convention of only dir/** - def self.reform_glob(path) - return path if (path =~ /\/\*\*$/).nil? - return path + '/**' - end - - ######### instance methods ########## - - def form_temp_path(filepath, prefix='') - return File.join( @configurator.project_temp_path, prefix + File.basename(filepath) ) - end - - ### release ### - def form_release_build_cache_path(filepath) - return File.join( @configurator.project_release_build_cache_path, File.basename(filepath) ) - end - - def form_release_dependencies_filepath(filepath) - return File.join( @configurator.project_release_dependencies_path, File.basename(filepath).ext(@configurator.extension_dependencies) ) - end - - def form_release_build_c_object_filepath(filepath) - return File.join( @configurator.project_release_build_output_c_path, File.basename(filepath).ext(@configurator.extension_object) ) - end - - def form_release_build_asm_object_filepath(filepath) - return File.join( @configurator.project_release_build_output_asm_path, File.basename(filepath).ext(@configurator.extension_object) ) - end - - def form_release_build_c_objects_filelist(files) - return (@file_wrapper.instantiate_file_list(files)).pathmap("#{@configurator.project_release_build_output_c_path}/%n#{@configurator.extension_object}") - end - - def form_release_build_asm_objects_filelist(files) - return (@file_wrapper.instantiate_file_list(files)).pathmap("#{@configurator.project_release_build_output_asm_path}/%n#{@configurator.extension_object}") - end - - def form_release_build_c_list_filepath(filepath) - return File.join( @configurator.project_release_build_output_c_path, File.basename(filepath).ext(@configurator.extension_list) ) - end - - def form_release_dependencies_filelist(files) - return (@file_wrapper.instantiate_file_list(files)).pathmap("#{@configurator.project_release_dependencies_path}/%n#{@configurator.extension_dependencies}") - end - - ### tests ### - def form_test_build_cache_path(filepath) - return File.join( @configurator.project_test_build_cache_path, File.basename(filepath) ) - end - - def form_test_dependencies_filepath(filepath) - return File.join( @configurator.project_test_dependencies_path, File.basename(filepath).ext(@configurator.extension_dependencies) ) - end - - def form_pass_results_filepath(filepath) - return File.join( @configurator.project_test_results_path, File.basename(filepath).ext(@configurator.extension_testpass) ) - end - - def form_fail_results_filepath(filepath) - return File.join( @configurator.project_test_results_path, File.basename(filepath).ext(@configurator.extension_testfail) ) - end - - def form_runner_filepath_from_test(filepath) - return File.join( @configurator.project_test_runners_path, File.basename(filepath, @configurator.extension_source)) + @configurator.test_runner_file_suffix + @configurator.extension_source - end - - def form_test_filepath_from_runner(filepath) - return filepath.sub(/#{TEST_RUNNER_FILE_SUFFIX}/, '') - end - - def form_runner_object_filepath_from_test(filepath) - return (form_test_build_c_object_filepath(filepath)).sub(/(#{@configurator.extension_object})$/, "#{@configurator.test_runner_file_suffix}\\1") - end - - def form_test_build_c_object_filepath(filepath) - return File.join( @configurator.project_test_build_output_c_path, File.basename(filepath).ext(@configurator.extension_object) ) - end - - def form_test_build_asm_object_filepath(filepath) - return File.join( @configurator.project_test_build_output_asm_path, File.basename(filepath).ext(@configurator.extension_object) ) - end - - def form_test_executable_filepath(filepath) - return File.join( @configurator.project_test_build_output_path, File.basename(filepath).ext(@configurator.extension_executable) ) - end - - def form_test_build_map_filepath(filepath) - return File.join( @configurator.project_test_build_output_path, File.basename(filepath).ext(@configurator.extension_map) ) - end - - def form_test_build_list_filepath(filepath) - return File.join( @configurator.project_test_build_output_path, File.basename(filepath).ext(@configurator.extension_list) ) - end - - def form_preprocessed_file_filepath(filepath) - return File.join( @configurator.project_test_preprocess_files_path, File.basename(filepath) ) - end - - def form_preprocessed_includes_list_filepath(filepath) - return File.join( @configurator.project_test_preprocess_includes_path, File.basename(filepath) ) - end - - def form_test_build_objects_filelist(sources) - return (@file_wrapper.instantiate_file_list(sources)).pathmap("#{@configurator.project_test_build_output_c_path}/%n#{@configurator.extension_object}") - end - - def form_preprocessed_mockable_headers_filelist(mocks) - list = @file_wrapper.instantiate_file_list(mocks) - headers = list.map do |file| - module_name = File.basename(file).sub(/^#{@configurator.cmock_mock_prefix}/, '').sub(/\.[a-zA-Z]+$/,'') - "#{@configurator.project_test_preprocess_files_path}/#{module_name}#{@configurator.extension_header}" - end - return headers - end - - def form_mocks_source_filelist(mocks) - list = (@file_wrapper.instantiate_file_list(mocks)) - sources = list.map{|file| "#{@configurator.cmock_mock_path}/#{file}#{@configurator.extension_source}"} - return sources - end - - def form_test_dependencies_filelist(files) - list = @file_wrapper.instantiate_file_list(files) - return list.pathmap("#{@configurator.project_test_dependencies_path}/%n#{@configurator.extension_dependencies}") - end - - def form_pass_results_filelist(path, files) - list = @file_wrapper.instantiate_file_list(files) - return list.pathmap("#{path}/%n#{@configurator.extension_testpass}") - end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/file_system_utils.rb b/test/unit-test/vendor/ceedling/lib/ceedling/file_system_utils.rb deleted file mode 100644 index 245d8f826..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/file_system_utils.rb +++ /dev/null @@ -1,69 +0,0 @@ -require 'rubygems' -require 'rake' -require 'set' -require 'fileutils' -require 'ceedling/file_path_utils' - - -class FileSystemUtils - - constructor :file_wrapper - - # build up path list from input of one or more strings or arrays of (+/-) paths & globs - def collect_paths(*paths) - raw = [] # all paths and globs - plus = Set.new # all paths to expand and add - minus = Set.new # all paths to remove from plus set - - # assemble all globs and simple paths, reforming our glob notation to ruby globs - paths.each do |paths_container| - case (paths_container) - when String then raw << (FilePathUtils::reform_glob(paths_container)) - when Array then paths_container.each {|path| raw << (FilePathUtils::reform_glob(path))} - else raise "Don't know how to handle #{paths_container.class}" - end - end - - # iterate through each path and glob - raw.each do |path| - - dirs = [] # container for only (expanded) paths - - # if a glob, expand it and slurp up all non-file paths - if path.include?('*') - # grab base directory only if globs are snug up to final path separator - if (path =~ /\/\*+$/) - dirs << FilePathUtils.extract_path(path) - end - - # grab expanded sub-directory globs - expanded = @file_wrapper.directory_listing( FilePathUtils.extract_path_no_aggregation_operators(path) ) - expanded.each do |entry| - dirs << entry if @file_wrapper.directory?(entry) - end - - # else just grab simple path - # note: we could just run this through glob expansion but such an - # approach doesn't handle a path not yet on disk) - else - dirs << FilePathUtils.extract_path_no_aggregation_operators(path) - end - - # add dirs to the appropriate set based on path aggregation modifier if present - FilePathUtils.add_path?(path) ? plus.merge(dirs) : minus.merge(dirs) - end - - return (plus - minus).to_a.uniq - end - - - # given a file list, add to it or remove from it - def revise_file_list(list, revisions) - revisions.each do |revision| - # include or exclude file or glob to file list - file = FilePathUtils.extract_path_no_aggregation_operators( revision ) - FilePathUtils.add_path?(revision) ? list.include(file) : list.exclude(file) - end - end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/file_system_wrapper.rb b/test/unit-test/vendor/ceedling/lib/ceedling/file_system_wrapper.rb deleted file mode 100644 index 1bb2883ee..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/file_system_wrapper.rb +++ /dev/null @@ -1,10 +0,0 @@ - -class FileSystemWrapper - - def cd(path) - FileUtils.cd path do - yield - end - end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/file_wrapper.rb b/test/unit-test/vendor/ceedling/lib/ceedling/file_wrapper.rb deleted file mode 100644 index 9e5a909b4..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/file_wrapper.rb +++ /dev/null @@ -1,83 +0,0 @@ -require 'rubygems' -require 'rake' # for FileList -require 'fileutils' -require 'ceedling/constants' - - -class FileWrapper - - def get_expanded_path(path) - return File.expand_path(path) - end - - def basename(path, extension=nil) - return File.basename(path, extension) if extension - return File.basename(path) - end - - def exist?(filepath) - return true if (filepath == NULL_FILE_PATH) - return File.exist?(filepath) - end - - def directory?(path) - return File.directory?(path) - end - - def dirname(path) - return File.dirname(path) - end - - def directory_listing(glob) - return Dir.glob(glob, File::FNM_PATHNAME) - end - - def rm_f(filepath, options={}) - FileUtils.rm_f(filepath, **options) - end - - def rm_r(filepath, options={}) - FileUtils.rm_r(filepath, **options={}) - end - - def cp(source, destination, options={}) - FileUtils.cp(source, destination, **options) - end - - def compare(from, to) - return FileUtils.compare_file(from, to) - end - - def open(filepath, flags) - File.open(filepath, flags) do |file| - yield(file) - end - end - - def read(filepath) - return File.read(filepath) - end - - def touch(filepath, options={}) - FileUtils.touch(filepath, **options) - end - - def write(filepath, contents, flags='w') - File.open(filepath, flags) do |file| - file.write(contents) - end - end - - def readlines(filepath) - return File.readlines(filepath) - end - - def instantiate_file_list(files=[]) - return FileList.new(files) - end - - def mkdir(folder) - return FileUtils.mkdir_p(folder) - end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/flaginator.rb b/test/unit-test/vendor/ceedling/lib/ceedling/flaginator.rb deleted file mode 100644 index 175b3c5ac..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/flaginator.rb +++ /dev/null @@ -1,74 +0,0 @@ -require 'rubygems' -require 'rake' # for ext() -require 'fileutils' -require 'ceedling/constants' - - -# :flags: -# :release: -# :compile: -# :'test_.+' -# - -pedantic # add '-pedantic' to every test file -# :*: # add '-foo' to compilation of all files not main.c -# - -foo -# :main: # add '-Wall' to compilation of main.c -# - -Wall -# :test: -# :link: -# :test_main: # add '--bar --baz' to linking of test_main.exe -# - --bar -# - --baz - -def partition(hash, &predicate) - hash.partition(&predicate).map(&:to_h) -end - -class Flaginator - - constructor :configurator - - def get_flag(hash, file_name) - file_key = file_name.to_sym - - # 1. try literals - literals, magic = partition(hash) { |k, v| k.to_s =~ /^\w+$/ } - return literals[file_key] if literals.include?(file_key) - - any, regex = partition(magic) { |k, v| (k == :'*') || (k == :'.*') } # glob or regex wild card - - # 2. try regexes - find_res = regex.find { |k, v| file_name =~ /^#{k.to_s}$/ } - return find_res[1] if find_res - - # 3. try anything - find_res = any.find { |k, v| file_name =~ /.*/ } - return find_res[1] if find_res - - # 4. well, we've tried - return [] - end - - def flag_down( operation, context, file ) - # create configurator accessor method - accessor = ('flags_' + context.to_s).to_sym - - # create simple filename key from whatever filename provided - file_name = File.basename( file ).ext('') - file_key = File.basename( file ).ext('').to_sym - - # if no entry in configuration for flags for this context, bail out - return [] if not @configurator.respond_to?( accessor ) - - # get flags sub hash associated with this context - flags = @configurator.send( accessor ) - - # if operation not represented in flags hash, bail out - return [] if not flags.include?( operation ) - - # redefine flags to sub hash associated with the operation - flags = flags[operation] - - return get_flag(flags, file_name) - end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/generator.rb b/test/unit-test/vendor/ceedling/lib/ceedling/generator.rb deleted file mode 100644 index 0b8902475..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/generator.rb +++ /dev/null @@ -1,186 +0,0 @@ -require 'ceedling/constants' - -class Generator - - constructor :configurator, - :generator_helper, - :preprocessinator, - :cmock_builder, - :generator_test_runner, - :generator_test_results, - :flaginator, - :test_includes_extractor, - :tool_executor, - :file_finder, - :file_path_utils, - :streaminator, - :plugin_manager, - :file_wrapper - - - def generate_shallow_includes_list(context, file) - @streaminator.stdout_puts("Generating include list for #{File.basename(file)}...", Verbosity::NORMAL) - @preprocessinator.preprocess_shallow_includes(file) - end - - def generate_preprocessed_file(context, file) - @streaminator.stdout_puts("Preprocessing #{File.basename(file)}...", Verbosity::NORMAL) - @preprocessinator.preprocess_file(file) - end - - def generate_dependencies_file(tool, context, source, object, dependencies) - @streaminator.stdout_puts("Generating dependencies for #{File.basename(source)}...", Verbosity::NORMAL) - - command = - @tool_executor.build_command_line( - tool, - [], # extra per-file command line parameters - source, - dependencies, - object) - - @tool_executor.exec( command[:line], command[:options] ) - end - - def generate_mock(context, header_filepath) - arg_hash = {:header_file => header_filepath, :context => context} - @plugin_manager.pre_mock_generate( arg_hash ) - - begin - @cmock_builder.cmock.setup_mocks( arg_hash[:header_file] ) - rescue - raise - ensure - @plugin_manager.post_mock_generate( arg_hash ) - end - end - - # test_filepath may be either preprocessed test file or original test file - def generate_test_runner(context, test_filepath, runner_filepath) - arg_hash = {:context => context, :test_file => test_filepath, :runner_file => runner_filepath} - @plugin_manager.pre_runner_generate(arg_hash) - - # collect info we need - module_name = File.basename(arg_hash[:test_file]) - test_cases = @generator_test_runner.find_test_cases( @file_finder.find_test_from_runner_path(runner_filepath) ) - mock_list = @test_includes_extractor.lookup_raw_mock_list(arg_hash[:test_file]) - - @streaminator.stdout_puts("Generating runner for #{module_name}...", Verbosity::NORMAL) - - test_file_includes = [] # Empty list for now, since apparently unused - - # build runner file - begin - @generator_test_runner.generate(module_name, runner_filepath, test_cases, mock_list, test_file_includes) - rescue - raise - ensure - @plugin_manager.post_runner_generate(arg_hash) - end - end - - def generate_object_file(tool, operation, context, source, object, list='', dependencies='') - shell_result = {} - arg_hash = {:tool => tool, :operation => operation, :context => context, :source => source, :object => object, :list => list, :dependencies => dependencies} - @plugin_manager.pre_compile_execute(arg_hash) - - @streaminator.stdout_puts("Compiling #{File.basename(arg_hash[:source])}...", Verbosity::NORMAL) - command = - @tool_executor.build_command_line( arg_hash[:tool], - @flaginator.flag_down( operation, context, source ), - arg_hash[:source], - arg_hash[:object], - arg_hash[:list], - arg_hash[:dependencies]) - - @streaminator.stdout_puts("Command: #{command}", Verbosity::DEBUG) - - begin - shell_result = @tool_executor.exec( command[:line], command[:options] ) - rescue ShellExecutionException => ex - shell_result = ex.shell_result - raise ex - ensure - arg_hash[:shell_command] = command[:line] - arg_hash[:shell_result] = shell_result - @plugin_manager.post_compile_execute(arg_hash) - end - end - - def generate_executable_file(tool, context, objects, executable, map='', libraries=[], libpaths=[]) - shell_result = {} - arg_hash = { :tool => tool, - :context => context, - :objects => objects, - :executable => executable, - :map => map, - :libraries => libraries, - :libpaths => libpaths - } - - @plugin_manager.pre_link_execute(arg_hash) - - @streaminator.stdout_puts("Linking #{File.basename(arg_hash[:executable])}...", Verbosity::NORMAL) - command = - @tool_executor.build_command_line( arg_hash[:tool], - @flaginator.flag_down( OPERATION_LINK_SYM, context, executable ), - arg_hash[:objects], - arg_hash[:executable], - arg_hash[:map], - arg_hash[:libraries], - arg_hash[:libpaths] - ) - @streaminator.stdout_puts("Command: #{command}", Verbosity::DEBUG) - - begin - shell_result = @tool_executor.exec( command[:line], command[:options] ) - rescue ShellExecutionException => ex - notice = "\n" + - "NOTICE: If the linker reports missing symbols, the following may be to blame:\n" + - " 1. Test lacks #include statements corresponding to needed source files.\n" + - " 2. Project search paths do not contain source files corresponding to #include statements in the test.\n" - - if (@configurator.project_use_mocks) - notice += " 3. Test does not #include needed mocks.\n\n" - else - notice += "\n" - end - - @streaminator.stderr_puts(notice, Verbosity::COMPLAIN) - shell_result = ex.shell_result - raise '' - ensure - arg_hash[:shell_result] = shell_result - @plugin_manager.post_link_execute(arg_hash) - end - end - - def generate_test_results(tool, context, executable, result) - arg_hash = {:tool => tool, :context => context, :executable => executable, :result_file => result} - @plugin_manager.pre_test_fixture_execute(arg_hash) - - @streaminator.stdout_puts("Running #{File.basename(arg_hash[:executable])}...", Verbosity::NORMAL) - - # Unity's exit code is equivalent to the number of failed tests, so we tell @tool_executor not to fail out if there are failures - # so that we can run all tests and collect all results - command = @tool_executor.build_command_line(arg_hash[:tool], [], arg_hash[:executable]) - @streaminator.stdout_puts("Command: #{command}", Verbosity::DEBUG) - command[:options][:boom] = false - shell_result = @tool_executor.exec( command[:line], command[:options] ) - - #Don't Let The Failure Count Make Us Believe Things Aren't Working - shell_result[:exit_code] = 0 - @generator_helper.test_results_error_handler(executable, shell_result) - - processed = @generator_test_results.process_and_write_results( shell_result, - arg_hash[:result_file], - @file_finder.find_test_from_file_path(arg_hash[:executable]) ) - - arg_hash[:result_file] = processed[:result_file] - arg_hash[:results] = processed[:results] - arg_hash[:shell_result] = shell_result # for raw output display if no plugins for formatted display - - @plugin_manager.post_test_fixture_execute(arg_hash) - end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/generator_helper.rb b/test/unit-test/vendor/ceedling/lib/ceedling/generator_helper.rb deleted file mode 100644 index a6682c275..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/generator_helper.rb +++ /dev/null @@ -1,40 +0,0 @@ -require 'ceedling/constants' - - -class GeneratorHelper - - constructor :streaminator - - - def test_results_error_handler(executable, shell_result) - notice = '' - error = false - - if (shell_result[:output].nil? or shell_result[:output].strip.empty?) - error = true - # mirror style of generic tool_executor failure output - notice = "\n" + - "ERROR: Test executable \"#{File.basename(executable)}\" failed.\n" + - "> Produced no output to $stdout.\n" - elsif ((shell_result[:output] =~ TEST_STDOUT_STATISTICS_PATTERN).nil?) - error = true - # mirror style of generic tool_executor failure output - notice = "\n" + - "ERROR: Test executable \"#{File.basename(executable)}\" failed.\n" + - "> Produced no final test result counts in $stdout:\n" + - "#{shell_result[:output].strip}\n" - end - - if (error) - # since we told the tool executor to ignore the exit code, handle it explicitly here - notice += "> And exited with status: [#{shell_result[:exit_code]}] (count of failed tests).\n" if (shell_result[:exit_code] != nil) - notice += "> And then likely crashed.\n" if (shell_result[:exit_code] == nil) - - notice += "> This is often a symptom of a bad memory access in source or test code.\n\n" - - @streaminator.stderr_puts(notice, Verbosity::COMPLAIN) - raise - end - end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/generator_test_results.rb b/test/unit-test/vendor/ceedling/lib/ceedling/generator_test_results.rb deleted file mode 100644 index 2cd96478c..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/generator_test_results.rb +++ /dev/null @@ -1,100 +0,0 @@ -require 'rubygems' -require 'rake' # for .ext() -require 'ceedling/constants' - -class GeneratorTestResults - - constructor :configurator, :generator_test_results_sanity_checker, :yaml_wrapper - - def process_and_write_results(unity_shell_result, results_file, test_file) - output_file = results_file - - results = get_results_structure - - results[:source][:path] = File.dirname(test_file) - results[:source][:file] = File.basename(test_file) - results[:time] = unity_shell_result[:time] unless unity_shell_result[:time].nil? - - # process test statistics - if (unity_shell_result[:output] =~ TEST_STDOUT_STATISTICS_PATTERN) - results[:counts][:total] = $1.to_i - results[:counts][:failed] = $2.to_i - results[:counts][:ignored] = $3.to_i - results[:counts][:passed] = (results[:counts][:total] - results[:counts][:failed] - results[:counts][:ignored]) - end - - # remove test statistics lines - output_string = unity_shell_result[:output].sub(TEST_STDOUT_STATISTICS_PATTERN, '') - - output_string.lines do |line| - # process unity output - case line - when /(:IGNORE)/ - elements = extract_line_elements(line, results[:source][:file]) - results[:ignores] << elements[0] - results[:stdout] << elements[1] if (!elements[1].nil?) - when /(:PASS$)/ - elements = extract_line_elements(line, results[:source][:file]) - results[:successes] << elements[0] - results[:stdout] << elements[1] if (!elements[1].nil?) - when /(:PASS \(.* ms\)$)/ - elements = extract_line_elements(line, results[:source][:file]) - results[:successes] << elements[0] - results[:stdout] << elements[1] if (!elements[1].nil?) - when /(:FAIL)/ - elements = extract_line_elements(line, results[:source][:file]) - results[:failures] << elements[0] - results[:stdout] << elements[1] if (!elements[1].nil?) - else # collect up all other - results[:stdout] << line.chomp - end - end - - @generator_test_results_sanity_checker.verify(results, unity_shell_result[:exit_code]) - - output_file = results_file.ext(@configurator.extension_testfail) if (results[:counts][:failed] > 0) - - @yaml_wrapper.dump(output_file, results) - - return { :result_file => output_file, :result => results } - end - - private - - def get_results_structure - return { - :source => {:path => '', :file => ''}, - :successes => [], - :failures => [], - :ignores => [], - :counts => {:total => 0, :passed => 0, :failed => 0, :ignored => 0}, - :stdout => [], - :time => 0.0 - } - end - - def extract_line_elements(line, filename) - # handle anything preceding filename in line as extra output to be collected - stdout = nil - stdout_regex = /(.+)#{Regexp.escape(filename)}.+/i - unity_test_time = 0 - - if (line =~ stdout_regex) - stdout = $1.clone - line.sub!(/#{Regexp.escape(stdout)}/, '') - end - - # collect up test results minus and extra output - elements = (line.strip.split(':'))[1..-1] - - # find timestamp if available - if (elements[-1] =~ / \((\d*(?:\.\d*)?) ms\)/) - unity_test_time = $1.to_f / 1000 - elements[-1].sub!(/ \((\d*(?:\.\d*)?) ms\)/, '') - end - - return {:test => elements[1], :line => elements[0].to_i, :message => (elements[3..-1].join(':')).strip, :unity_test_time => unity_test_time}, stdout if elements.size >= 3 - return {:test => '???', :line => -1, :message => nil, :unity_test_time => unity_test_time} #fallback safe option. TODO better handling - end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/generator_test_results_sanity_checker.rb b/test/unit-test/vendor/ceedling/lib/ceedling/generator_test_results_sanity_checker.rb deleted file mode 100644 index 1d193c844..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/generator_test_results_sanity_checker.rb +++ /dev/null @@ -1,65 +0,0 @@ -require 'rubygems' -require 'rake' # for ext() method -require 'ceedling/constants' - - -class GeneratorTestResultsSanityChecker - - constructor :configurator, :streaminator - - def verify(results, unity_exit_code) - - # do no sanity checking if it's disabled - return if (@configurator.sanity_checks == TestResultsSanityChecks::NONE) - raise "results nil or empty" if results.nil? || results.empty? - - ceedling_ignores_count = results[:ignores].size - ceedling_failures_count = results[:failures].size - ceedling_tests_summation = (ceedling_ignores_count + ceedling_failures_count + results[:successes].size) - - # Exit code handling is not a sanity check that can always be performed because - # command line simulators may or may not pass through Unity's exit code - if (@configurator.sanity_checks >= TestResultsSanityChecks::THOROUGH) - # many platforms limit exit codes to a maximum of 255 - if ((ceedling_failures_count != unity_exit_code) and (unity_exit_code < 255)) - sanity_check_warning(results[:source][:file], "Unity's exit code (#{unity_exit_code}) does not match Ceedling's summation of failed test cases (#{ceedling_failures_count}).") - end - - if ((ceedling_failures_count < 255) and (unity_exit_code == 255)) - sanity_check_warning(results[:source][:file], "Ceedling's summation of failed test cases (#{ceedling_failures_count}) is less than Unity's exit code (255 or more).") - end - end - - if (ceedling_ignores_count != results[:counts][:ignored]) - sanity_check_warning(results[:source][:file], "Unity's final ignore count (#{results[:counts][:ignored]}) does not match Ceedling's summation of ignored test cases (#{ceedling_ignores_count}).") - end - - if (ceedling_failures_count != results[:counts][:failed]) - sanity_check_warning(results[:source][:file], "Unity's final fail count (#{results[:counts][:failed]}) does not match Ceedling's summation of failed test cases (#{ceedling_failures_count}).") - end - - if (ceedling_tests_summation != results[:counts][:total]) - sanity_check_warning(results[:source][:file], "Unity's final test count (#{results[:counts][:total]}) does not match Ceedling's summation of all test cases (#{ceedling_tests_summation}).") - end - - end - - private - - def sanity_check_warning(file, message) - unless defined?(CEEDLING_IGNORE_SANITY_CHECK) - notice = "\n" + - "ERROR: Internal sanity check for test fixture '#{file.ext(@configurator.extension_executable)}' finds that #{message}\n" + - " Possible causes:\n" + - " 1. Your test + source dereferenced a null pointer.\n" + - " 2. Your test + source indexed past the end of a buffer.\n" + - " 3. Your test + source committed a memory access violation.\n" + - " 4. Your test fixture produced an exit code of 0 despite execution ending prematurely.\n" + - " Sanity check failures of test results are usually a symptom of interrupted test execution.\n\n" - - @streaminator.stderr_puts( notice ) - raise - end - end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/generator_test_runner.rb b/test/unit-test/vendor/ceedling/lib/ceedling/generator_test_runner.rb deleted file mode 100644 index 79ed7140f..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/generator_test_runner.rb +++ /dev/null @@ -1,58 +0,0 @@ - -class GeneratorTestRunner - - constructor :configurator, :file_path_utils, :file_wrapper - - def find_test_cases(test_file) - - #Pull in Unity's Test Runner Generator - require 'generate_test_runner.rb' - @test_runner_generator ||= UnityTestRunnerGenerator.new( @configurator.get_runner_config ) - - if (@configurator.project_use_test_preprocessor) - - #redirect to use the preprocessor file if we're doing that sort of thing - pre_test_file = @file_path_utils.form_preprocessed_file_filepath(test_file) - - #actually look for the tests using Unity's test runner generator - contents = @file_wrapper.read(pre_test_file) - tests_and_line_numbers = @test_runner_generator.find_tests(contents) - @test_runner_generator.find_setup_and_teardown(contents) - - #look up the line numbers in the original file - source_lines = @file_wrapper.read(test_file).split("\n") - source_index = 0; - tests_and_line_numbers.size.times do |i| - source_lines[source_index..-1].each_with_index do |line, index| - if (line =~ /#{tests_and_line_numbers[i][:test]}/) - source_index += index - tests_and_line_numbers[i][:line_number] = source_index + 1 - break - end - end - end - else - #Just look for the tests using Unity's test runner generator - contents = @file_wrapper.read(test_file) - tests_and_line_numbers = @test_runner_generator.find_tests(contents) - @test_runner_generator.find_setup_and_teardown(contents) - end - - return tests_and_line_numbers - end - - def generate(module_name, runner_filepath, test_cases, mock_list, test_file_includes=[]) - require 'generate_test_runner.rb' - - header_extension = @configurator.extension_header - - #actually build the test runner using Unity's test runner generator - #(there is no need to use preprocessor here because we've already looked up test cases and are passing them in here) - @test_runner_generator ||= UnityTestRunnerGenerator.new( @configurator.get_runner_config ) - @test_runner_generator.generate( module_name, - runner_filepath, - test_cases, - mock_list.map{|f| File.basename(f,'.*')+header_extension}, - test_file_includes.map{|f| File.basename(f,'.*')+header_extension}) - end -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/loginator.rb b/test/unit-test/vendor/ceedling/lib/ceedling/loginator.rb deleted file mode 100644 index 38147b322..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/loginator.rb +++ /dev/null @@ -1,31 +0,0 @@ - -class Loginator - - constructor :configurator, :project_file_loader, :project_config_manager, :file_wrapper, :system_wrapper - - - def setup_log_filepath - config_files = [] - config_files << @project_file_loader.main_file - config_files << @project_file_loader.user_file - config_files.concat( @project_config_manager.options_files ) - config_files.compact! - config_files.map! { |file| file.ext('') } - - log_name = config_files.join( '_' ) - - @project_log_filepath = File.join( @configurator.project_log_path, log_name.ext('.log') ) - end - - - def log(string, heading=nil) - return if (not @configurator.project_logging) - - output = "\n[#{@system_wrapper.time_now}]" - output += " :: #{heading}" if (not heading.nil?) - output += "\n#{string.strip}\n" - - @file_wrapper.write(@project_log_filepath, output, 'a') - end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/makefile.rb b/test/unit-test/vendor/ceedling/lib/ceedling/makefile.rb deleted file mode 100644 index 9ad894ea0..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/makefile.rb +++ /dev/null @@ -1,46 +0,0 @@ - -# modified version of Rake's provided make-style dependency loader -# customizations: -# (1) handles windows drives in paths -- colons don't confuse task demarcation -# (2) handles spaces in directory paths - -module Rake - - # Makefile loader to be used with the import file loader. - class MakefileLoader - - # Load the makefile dependencies in +fn+. - def load(fn) - open(fn) do |mf| - lines = mf.read - lines.gsub!(/#[^\n]*\n/m, "") # remove comments - lines.gsub!(/\\\n/, ' ') # string together line continuations into single line - lines.split("\n").each do |line| - process_line(line) - end - end - end - - private - - # Process one logical line of makefile data. - def process_line(line) - # split on presence of task demaractor followed by space (i.e don't get confused by a colon in a win path) - file_tasks, args = line.split(/:\s/) - - return if args.nil? - - # split at non-escaped space boundary between files (i.e. escaped spaces in paths are left alone) - dependents = args.split(/\b\s+/) - # replace escaped spaces and clean up any extra whitespace - dependents.map! { |path| path.gsub(/\\ /, ' ').strip } - - file_tasks.strip.split.each do |file_task| - file file_task => dependents - end - end - end - - # Install the handler - Rake.application.add_loader('mf', MakefileLoader.new) -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/objects.yml b/test/unit-test/vendor/ceedling/lib/ceedling/objects.yml deleted file mode 100644 index d73987f7c..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/objects.yml +++ /dev/null @@ -1,313 +0,0 @@ - -file_wrapper: - -file_system_wrapper: - -stream_wrapper: - -rake_wrapper: - -yaml_wrapper: - -system_wrapper: - -cmock_builder: - -reportinator: - -rake_utils: - compose: - - rake_wrapper - -system_utils: - compose: - - system_wrapper - -file_path_utils: - compose: - - configurator - - file_wrapper - -file_system_utils: - compose: file_wrapper - -project_file_loader: - compose: - - yaml_wrapper - - stream_wrapper - - system_wrapper - - file_wrapper - -project_config_manager: - compose: - - cacheinator - - configurator - - yaml_wrapper - - file_wrapper - -cacheinator: - compose: - - cacheinator_helper - - file_path_utils - - file_wrapper - - yaml_wrapper - -cacheinator_helper: - compose: - - file_wrapper - - yaml_wrapper - -tool_executor: - compose: - - configurator - - tool_executor_helper - - streaminator - - system_wrapper - -tool_executor_helper: - compose: - - streaminator - - system_utils - - system_wrapper - -configurator: - compose: - - configurator_setup - - configurator_plugins - - configurator_builder - - cmock_builder - - yaml_wrapper - - system_wrapper - -configurator_setup: - compose: - - configurator_builder - - configurator_validator - - configurator_plugins - - stream_wrapper - -configurator_plugins: - compose: - - stream_wrapper - - file_wrapper - - system_wrapper - -configurator_validator: - compose: - - file_wrapper - - stream_wrapper - - system_wrapper - -configurator_builder: - compose: - - file_system_utils - - file_wrapper - - system_wrapper - -loginator: - compose: - - configurator - - project_file_loader - - project_config_manager - - file_wrapper - - system_wrapper - -streaminator: - compose: - - streaminator_helper - - verbosinator - - loginator - - stream_wrapper - -streaminator_helper: - -setupinator: - -plugin_builder: - -plugin_manager: - compose: - - configurator - - plugin_manager_helper - - streaminator - - reportinator - - system_wrapper - -plugin_manager_helper: - -plugin_reportinator: - compose: - - plugin_reportinator_helper - - plugin_manager - - reportinator - -plugin_reportinator_helper: - compose: - - configurator - - streaminator - - yaml_wrapper - - file_wrapper - -verbosinator: - compose: configurator - -file_finder: - compose: - - configurator - - file_finder_helper - - cacheinator - - file_path_utils - - file_wrapper - - yaml_wrapper - -file_finder_helper: - compose: streaminator - -test_includes_extractor: - compose: - - configurator - - yaml_wrapper - - file_wrapper - -task_invoker: - compose: - - dependinator - - rake_utils - - rake_wrapper - - project_config_manager - -flaginator: - compose: - - configurator - -generator: - compose: - - configurator - - generator_helper - - preprocessinator - - cmock_builder - - generator_test_runner - - generator_test_results - - flaginator - - test_includes_extractor - - tool_executor - - file_finder - - file_path_utils - - streaminator - - plugin_manager - - file_wrapper - -generator_helper: - compose: - - streaminator - -generator_test_results: - compose: - - configurator - - generator_test_results_sanity_checker - - yaml_wrapper - -generator_test_results_sanity_checker: - compose: - - configurator - - streaminator - -generator_test_runner: - compose: - - configurator - - file_path_utils - - file_wrapper - -dependinator: - compose: - - configurator - - project_config_manager - - test_includes_extractor - - file_path_utils - - rake_wrapper - - file_wrapper - -preprocessinator: - compose: - - preprocessinator_helper - - preprocessinator_includes_handler - - preprocessinator_file_handler - - task_invoker - - file_path_utils - - yaml_wrapper - - project_config_manager - - configurator - -preprocessinator_helper: - compose: - - configurator - - test_includes_extractor - - task_invoker - - file_finder - - file_path_utils - -preprocessinator_includes_handler: - compose: - - configurator - - tool_executor - - task_invoker - - file_path_utils - - yaml_wrapper - - file_wrapper - - file_finder - -preprocessinator_file_handler: - compose: - - preprocessinator_extractor - - configurator - - tool_executor - - file_path_utils - - file_wrapper - -preprocessinator_extractor: - -test_invoker: - compose: - - configurator - - test_invoker_helper - - plugin_manager - - streaminator - - preprocessinator - - task_invoker - - dependinator - - project_config_manager - - build_invoker_utils - - file_path_utils - - file_wrapper - -test_invoker_helper: - compose: - - configurator - - task_invoker - - test_includes_extractor - - file_finder - - file_path_utils - - file_wrapper - -release_invoker: - compose: - - configurator - - release_invoker_helper - - build_invoker_utils - - dependinator - - task_invoker - - file_path_utils - - file_wrapper - -release_invoker_helper: - compose: - - configurator - - dependinator - - task_invoker - -build_invoker_utils: - compose: - - configurator - - streaminator - -erb_wrapper: diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/par_map.rb b/test/unit-test/vendor/ceedling/lib/ceedling/par_map.rb deleted file mode 100644 index 250b5ad30..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/par_map.rb +++ /dev/null @@ -1,18 +0,0 @@ - - -def par_map(n, things, &block) - queue = Queue.new - things.each { |thing| queue << thing } - threads = (1..n).collect do - Thread.new do - begin - while true - yield queue.pop(true) - end - rescue ThreadError - - end - end - end - threads.each { |t| t.join } -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/plugin.rb b/test/unit-test/vendor/ceedling/lib/ceedling/plugin.rb deleted file mode 100644 index 835c08c52..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/plugin.rb +++ /dev/null @@ -1,80 +0,0 @@ - -class String - # reformat a multiline string to have given number of whitespace columns; - # helpful for formatting heredocs - def left_margin(margin=0) - non_whitespace_column = 0 - new_lines = [] - - # find first line with non-whitespace and count left columns of whitespace - self.each_line do |line| - if (line =~ /^\s*\S/) - non_whitespace_column = $&.length - 1 - break - end - end - - # iterate through each line, chopping off leftmost whitespace columns and add back the desired whitespace margin - self.each_line do |line| - columns = [] - margin.times{columns << ' '} - # handle special case of line being narrower than width to be lopped off - if (non_whitespace_column < line.length) - new_lines << "#{columns.join}#{line[non_whitespace_column..-1]}" - else - new_lines << "\n" - end - end - - return new_lines.join - end -end - -class Plugin - attr_reader :name, :environment - attr_accessor :plugin_objects - - def initialize(system_objects, name) - @environment = [] - @ceedling = system_objects - @name = name - self.setup - end - - def setup; end - - # mock generation - def pre_mock_generate(arg_hash); end - def post_mock_generate(arg_hash); end - - # test runner generation - def pre_runner_generate(arg_hash); end - def post_runner_generate(arg_hash); end - - # compilation (test or source) - def pre_compile_execute(arg_hash); end - def post_compile_execute(arg_hash); end - - # linking (test or source) - def pre_link_execute(arg_hash); end - def post_link_execute(arg_hash); end - - # test fixture execution - def pre_test_fixture_execute(arg_hash); end - def post_test_fixture_execute(arg_hash); end - - # test task - def pre_test(test); end - def post_test(test); end - - # release task - def pre_release; end - def post_release; end - - # whole shebang (any use of Ceedling) - def pre_build; end - def post_build; end - - def summary; end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/plugin_builder.rb b/test/unit-test/vendor/ceedling/lib/ceedling/plugin_builder.rb deleted file mode 100644 index a010e1d0f..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/plugin_builder.rb +++ /dev/null @@ -1,53 +0,0 @@ -require 'ceedling/plugin' - -class PluginBuilder - - attr_accessor :plugin_objects - - def construct_plugin(plugin_name, object_map_yaml, system_objects) - # @streaminator.stdout_puts("Constructing plugin #{plugin_name}...", Verbosity::OBNOXIOUS) - object_map = {} - @plugin_objects = {} - @system_objects = system_objects - - if object_map_yaml - @object_map = YAML.load(object_map_yaml) - @object_map.each_key do |obj| - construct_object(obj) - end - else - raise "Invalid object map for plugin #{plugin_name}!" - end - - return @plugin_objects - end - - private - - def camelize(underscored_name) - return underscored_name.gsub(/(_|^)([a-z0-9])/) {$2.upcase} - end - - def construct_object(obj) - if @plugin_objects[obj].nil? - if @object_map[obj] && @object_map[obj]['compose'] - @object_map[obj]['compose'].each do |dep| - construct_object(dep) - end - end - build_object(obj) - end - end - - def build_object(new_object) - if @plugin_objects[new_object.to_sym].nil? - # @streaminator.stdout_puts("Building plugin object #{new_object}", Verbosity::OBNOXIOUS) - require new_object - class_name = camelize(new_object) - new_instance = eval("#{class_name}.new(@system_objects, class_name.to_s)") - new_instance.plugin_objects = @plugin_objects - @plugin_objects[new_object.to_sym] = new_instance - end - end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/plugin_manager.rb b/test/unit-test/vendor/ceedling/lib/ceedling/plugin_manager.rb deleted file mode 100644 index 0468f2fc4..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/plugin_manager.rb +++ /dev/null @@ -1,107 +0,0 @@ -require 'ceedling/constants' - -class PluginManager - - constructor :configurator, :plugin_manager_helper, :streaminator, :reportinator, :system_wrapper - - def setup - @build_fail_registry = [] - @plugin_objects = [] # so we can preserve order - end - - def load_plugin_scripts(script_plugins, system_objects) - environment = [] - - script_plugins.each do |plugin| - # protect against instantiating object multiple times due to processing config multiple times (option files, etc) - next if (@plugin_manager_helper.include?(@plugin_objects, plugin)) - begin - @system_wrapper.require_file( "#{plugin}.rb" ) - object = @plugin_manager_helper.instantiate_plugin_script( camelize(plugin), system_objects, plugin ) - @plugin_objects << object - environment += object.environment - - # add plugins to hash of all system objects - system_objects[plugin.downcase.to_sym] = object - rescue - puts "Exception raised while trying to load plugin: #{plugin}" - raise - end - end - - yield( { :environment => environment } ) if (environment.size > 0) - end - - def plugins_failed? - return (@build_fail_registry.size > 0) - end - - def print_plugin_failures - if (@build_fail_registry.size > 0) - report = @reportinator.generate_banner('BUILD FAILURE SUMMARY') - - @build_fail_registry.each do |failure| - report += "#{' - ' if (@build_fail_registry.size > 1)}#{failure}\n" - end - - report += "\n" - - @streaminator.stderr_puts(report, Verbosity::ERRORS) - end - end - - def register_build_failure(message) - @build_fail_registry << message if (message and not message.empty?) - end - - #### execute all plugin methods #### - - def pre_mock_generate(arg_hash); execute_plugins(:pre_mock_generate, arg_hash); end - def post_mock_generate(arg_hash); execute_plugins(:post_mock_generate, arg_hash); end - - def pre_runner_generate(arg_hash); execute_plugins(:pre_runner_generate, arg_hash); end - def post_runner_generate(arg_hash); execute_plugins(:post_runner_generate, arg_hash); end - - def pre_compile_execute(arg_hash); execute_plugins(:pre_compile_execute, arg_hash); end - def post_compile_execute(arg_hash); execute_plugins(:post_compile_execute, arg_hash); end - - def pre_link_execute(arg_hash); execute_plugins(:pre_link_execute, arg_hash); end - def post_link_execute(arg_hash); execute_plugins(:post_link_execute, arg_hash); end - - def pre_test_fixture_execute(arg_hash); execute_plugins(:pre_test_fixture_execute, arg_hash); end - def post_test_fixture_execute(arg_hash) - # special arbitration: raw test results are printed or taken over by plugins handling the job - @streaminator.stdout_puts(arg_hash[:shell_result][:output]) if (@configurator.plugins_display_raw_test_results) - execute_plugins(:post_test_fixture_execute, arg_hash) - end - - def pre_test(test); execute_plugins(:pre_test, test); end - def post_test(test); execute_plugins(:post_test, test); end - - def pre_release; execute_plugins(:pre_release); end - def post_release; execute_plugins(:post_release); end - - def pre_build; execute_plugins(:pre_build); end - def post_build; execute_plugins(:post_build); end - def post_error; execute_plugins(:post_error); end - - def summary; execute_plugins(:summary); end - - private #################################### - - def camelize(underscored_name) - return underscored_name.gsub(/(_|^)([a-z0-9])/) {$2.upcase} - end - - def execute_plugins(method, *args) - @plugin_objects.each do |plugin| - begin - plugin.send(method, *args) if plugin.respond_to?(method) - rescue - puts "Exception raised in plugin: #{plugin.name}, in method #{method}" - raise - end - end - end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/plugin_manager_helper.rb b/test/unit-test/vendor/ceedling/lib/ceedling/plugin_manager_helper.rb deleted file mode 100644 index b18248a65..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/plugin_manager_helper.rb +++ /dev/null @@ -1,19 +0,0 @@ - -class PluginManagerHelper - - def include?(plugins, name) - include = false - plugins.each do |plugin| - if (plugin.name == name) - include = true - break - end - end - return include - end - - def instantiate_plugin_script(plugin, system_objects, name) - return eval("#{plugin}.new(system_objects, name)") - end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/plugin_reportinator.rb b/test/unit-test/vendor/ceedling/lib/ceedling/plugin_reportinator.rb deleted file mode 100644 index afc54494b..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/plugin_reportinator.rb +++ /dev/null @@ -1,76 +0,0 @@ -require 'ceedling/constants' -require 'ceedling/defaults' - -class PluginReportinator - - constructor :plugin_reportinator_helper, :plugin_manager, :reportinator - - def setup - @test_results_template = nil - end - - - def set_system_objects(system_objects) - @plugin_reportinator_helper.ceedling = system_objects - end - - - def fetch_results(results_path, test, options={:boom => false}) - return @plugin_reportinator_helper.fetch_results( File.join(results_path, test), options ) - end - - - def generate_banner(message) - return @reportinator.generate_banner(message) - end - - - def assemble_test_results(results_list, options={:boom => false}) - aggregated_results = get_results_structure - - results_list.each do |result_path| - results = @plugin_reportinator_helper.fetch_results( result_path, options ) - @plugin_reportinator_helper.process_results(aggregated_results, results) - end - - return aggregated_results - end - - - def register_test_results_template(template) - @test_results_template = template if (@test_results_template.nil?) - end - - - def run_test_results_report(hash, verbosity=Verbosity::NORMAL, &block) - run_report( $stdout, - ((@test_results_template.nil?) ? DEFAULT_TESTS_RESULTS_REPORT_TEMPLATE : @test_results_template), - hash, - verbosity, - &block ) - end - - - def run_report(stream, template, hash=nil, verbosity=Verbosity::NORMAL) - failure = nil - failure = yield() if block_given? - - @plugin_manager.register_build_failure( failure ) - - @plugin_reportinator_helper.run_report( stream, template, hash, verbosity ) - end - - private ############################### - - def get_results_structure - return { - :successes => [], - :failures => [], - :ignores => [], - :stdout => [], - :counts => {:total => 0, :passed => 0, :failed => 0, :ignored => 0, :stdout => 0}, - :time => 0.0 - } - end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/plugin_reportinator_helper.rb b/test/unit-test/vendor/ceedling/lib/ceedling/plugin_reportinator_helper.rb deleted file mode 100644 index 783158797..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/plugin_reportinator_helper.rb +++ /dev/null @@ -1,51 +0,0 @@ -require 'erb' -require 'rubygems' -require 'rake' # for ext() -require 'ceedling/constants' - -class PluginReportinatorHelper - - attr_writer :ceedling - - constructor :configurator, :streaminator, :yaml_wrapper, :file_wrapper - - def fetch_results(results_path, options) - pass_path = File.join(results_path.ext( @configurator.extension_testpass )) - fail_path = File.join(results_path.ext( @configurator.extension_testfail )) - - if (@file_wrapper.exist?(fail_path)) - return @yaml_wrapper.load(fail_path) - elsif (@file_wrapper.exist?(pass_path)) - return @yaml_wrapper.load(pass_path) - else - if (options[:boom]) - @streaminator.stderr_puts("Could find no test results for '#{File.basename(results_path).ext(@configurator.extension_source)}'", Verbosity::ERRORS) - raise - end - end - - return {} - end - - - def process_results(aggregate_results, results) - return if (results.empty?) - aggregate_results[:successes] << { :source => results[:source].clone, :collection => results[:successes].clone } if (results[:successes].size > 0) - aggregate_results[:failures] << { :source => results[:source].clone, :collection => results[:failures].clone } if (results[:failures].size > 0) - aggregate_results[:ignores] << { :source => results[:source].clone, :collection => results[:ignores].clone } if (results[:ignores].size > 0) - aggregate_results[:stdout] << { :source => results[:source].clone, :collection => results[:stdout].clone } if (results[:stdout].size > 0) - aggregate_results[:counts][:total] += results[:counts][:total] - aggregate_results[:counts][:passed] += results[:counts][:passed] - aggregate_results[:counts][:failed] += results[:counts][:failed] - aggregate_results[:counts][:ignored] += results[:counts][:ignored] - aggregate_results[:counts][:stdout] += results[:stdout].size - aggregate_results[:time] += results[:time] - end - - - def run_report(stream, template, hash, verbosity) - output = ERB.new(template, 0, "%<>") - @streaminator.stream_puts(stream, output.result(binding()), verbosity) - end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/preprocessinator.rb b/test/unit-test/vendor/ceedling/lib/ceedling/preprocessinator.rb deleted file mode 100644 index 52d82ca29..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/preprocessinator.rb +++ /dev/null @@ -1,56 +0,0 @@ - -class Preprocessinator - - constructor :preprocessinator_helper, :preprocessinator_includes_handler, :preprocessinator_file_handler, :task_invoker, :file_path_utils, :yaml_wrapper, :project_config_manager, :configurator - - - def setup - # fashion ourselves callbacks @preprocessinator_helper can use - @preprocess_includes_proc = Proc.new { |filepath| self.preprocess_shallow_includes(filepath) } - @preprocess_mock_file_proc = Proc.new { |filepath| self.preprocess_file(filepath) } - @preprocess_test_file_directives_proc = Proc.new { |filepath| self.preprocess_file_directives(filepath) } - @preprocess_test_file_proc = Proc.new { |filepath| self.preprocess_file(filepath) } - end - - def preprocess_shallow_source_includes(test) - @preprocessinator_helper.preprocess_source_includes(test) - end - - def preprocess_test_and_invoke_test_mocks(test) - @preprocessinator_helper.preprocess_includes(test, @preprocess_includes_proc) - - mocks_list = @preprocessinator_helper.assemble_mocks_list(test) - - @project_config_manager.process_test_defines_change(mocks_list) - - @preprocessinator_helper.preprocess_mockable_headers(mocks_list, @preprocess_mock_file_proc) - - @task_invoker.invoke_test_mocks(mocks_list) - - if (@configurator.project_use_preprocessor_directives) - @preprocessinator_helper.preprocess_test_file(test, @preprocess_test_file_directives_proc) - else - @preprocessinator_helper.preprocess_test_file(test, @preprocess_test_file_proc) - end - - return mocks_list - end - - def preprocess_shallow_includes(filepath) - includes = @preprocessinator_includes_handler.extract_includes(filepath) - - @preprocessinator_includes_handler.write_shallow_includes_list( - @file_path_utils.form_preprocessed_includes_list_filepath(filepath), includes) - end - - def preprocess_file(filepath) - @preprocessinator_includes_handler.invoke_shallow_includes_list(filepath) - @preprocessinator_file_handler.preprocess_file( filepath, @yaml_wrapper.load(@file_path_utils.form_preprocessed_includes_list_filepath(filepath)) ) - end - - def preprocess_file_directives(filepath) - @preprocessinator_includes_handler.invoke_shallow_includes_list( filepath ) - @preprocessinator_file_handler.preprocess_file_directives( filepath, - @yaml_wrapper.load( @file_path_utils.form_preprocessed_includes_list_filepath( filepath ) ) ) - end -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/preprocessinator_extractor.rb b/test/unit-test/vendor/ceedling/lib/ceedling/preprocessinator_extractor.rb deleted file mode 100644 index 62026e15a..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/preprocessinator_extractor.rb +++ /dev/null @@ -1,55 +0,0 @@ -class PreprocessinatorExtractor - def extract_base_file_from_preprocessed_expansion(filepath) - # preprocessing by way of toolchain preprocessor expands macros, eliminates - # comments, strips out #ifdef code, etc. however, it also expands in place - # each #include'd file. so, we must extract only the lines of the file - # that belong to the file originally preprocessed - - # iterate through all lines and alternate between extract and ignore modes - # all lines between a '#'line containing file name of our filepath and the - # next '#'line should be extracted - - base_name = File.basename(filepath) - not_pragma = /^#(?!pragma\b)/ # preprocessor directive that's not a #pragma - pattern = /^#.*(\s|\/|\\|\")#{Regexp.escape(base_name)}/ - found_file = false # have we found the file we care about? - - lines = [] - File.readlines(filepath).each do |line| - line.encode!('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: '') - if found_file and not line =~ not_pragma - lines << line - else - found_file = false - end - - found_file = true if line =~ pattern - end - - return lines - end - - def extract_base_file_from_preprocessed_directives(filepath) - # preprocessing by way of toolchain preprocessor eliminates directives only - # like #ifdef's and leave other code - - # iterate through all lines and only get last chunk of file after a last - # '#'line containing file name of our filepath - - base_name = File.basename(filepath) - pattern = /^#.*(\s|\/|\\|\")#{Regexp.escape(base_name)}/ - found_file = false # have we found the file we care about? - - lines = [] - File.readlines(filepath).each do |line| - line.encode!('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: '') - lines << line - - if line =~ pattern - lines = [] - end - end - - return lines - end -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/preprocessinator_file_handler.rb b/test/unit-test/vendor/ceedling/lib/ceedling/preprocessinator_file_handler.rb deleted file mode 100644 index 978fa0d05..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/preprocessinator_file_handler.rb +++ /dev/null @@ -1,34 +0,0 @@ - - -class PreprocessinatorFileHandler - - constructor :preprocessinator_extractor, :configurator, :tool_executor, :file_path_utils, :file_wrapper - - - def preprocess_file(filepath, includes) - preprocessed_filepath = @file_path_utils.form_preprocessed_file_filepath(filepath) - - command = @tool_executor.build_command_line(@configurator.tools_test_file_preprocessor, [], filepath, preprocessed_filepath) - @tool_executor.exec(command[:line], command[:options]) - - contents = @preprocessinator_extractor.extract_base_file_from_preprocessed_expansion(preprocessed_filepath) - - includes.each{|include| contents.unshift("#include \"#{include}\"")} - - @file_wrapper.write(preprocessed_filepath, contents.join("\n")) - end - - def preprocess_file_directives(filepath, includes) - preprocessed_filepath = @file_path_utils.form_preprocessed_file_filepath(filepath) - - command = @tool_executor.build_command_line(@configurator.tools_test_file_preprocessor_directives, [], filepath, preprocessed_filepath) - @tool_executor.exec(command[:line], command[:options]) - - contents = @preprocessinator_extractor.extract_base_file_from_preprocessed_directives(preprocessed_filepath) - - includes.each{|include| contents.unshift("#include \"#{include}\"")} - - @file_wrapper.write(preprocessed_filepath, contents.join("\n")) - end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/preprocessinator_helper.rb b/test/unit-test/vendor/ceedling/lib/ceedling/preprocessinator_helper.rb deleted file mode 100644 index 4bbda67fc..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/preprocessinator_helper.rb +++ /dev/null @@ -1,50 +0,0 @@ - - -class PreprocessinatorHelper - - constructor :configurator, :test_includes_extractor, :task_invoker, :file_finder, :file_path_utils - - - def preprocess_includes(test, preprocess_includes_proc) - if (@configurator.project_use_test_preprocessor) - preprocessed_includes_list = @file_path_utils.form_preprocessed_includes_list_filepath(test) - preprocess_includes_proc.call( @file_finder.find_test_from_file_path(preprocessed_includes_list) ) - @test_includes_extractor.parse_includes_list(preprocessed_includes_list) - else - @test_includes_extractor.parse_test_file(test) - end - end - - def preprocess_source_includes(test) - @test_includes_extractor.parse_test_file_source_include(test) - end - - def assemble_mocks_list(test) - return @file_path_utils.form_mocks_source_filelist( @test_includes_extractor.lookup_raw_mock_list(test) ) - end - - def preprocess_mockable_headers(mock_list, preprocess_file_proc) - if (@configurator.project_use_test_preprocessor) - preprocess_files_smartly( - @file_path_utils.form_preprocessed_mockable_headers_filelist(mock_list), - preprocess_file_proc ) { |file| @file_finder.find_header_file(file) } - end - end - - def preprocess_test_file(test, preprocess_file_proc) - return if (!@configurator.project_use_test_preprocessor) - - preprocess_file_proc.call(test) - end - - private ############################ - - def preprocess_files_smartly(file_list, preprocess_file_proc) - if (@configurator.project_use_deep_dependencies) - @task_invoker.invoke_test_preprocessed_files(file_list) - else - file_list.each { |file| preprocess_file_proc.call( yield(file) ) } - end - end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/preprocessinator_includes_handler.rb b/test/unit-test/vendor/ceedling/lib/ceedling/preprocessinator_includes_handler.rb deleted file mode 100644 index 9e5ae1fbf..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/preprocessinator_includes_handler.rb +++ /dev/null @@ -1,189 +0,0 @@ - - -class PreprocessinatorIncludesHandler - - constructor :configurator, :tool_executor, :task_invoker, :file_path_utils, :yaml_wrapper, :file_wrapper, :file_finder - @@makefile_cache = {} - - # shallow includes: only those headers a source file explicitly includes - - def invoke_shallow_includes_list(filepath) - @task_invoker.invoke_test_shallow_include_lists( [@file_path_utils.form_preprocessed_includes_list_filepath(filepath)] ) - end - - ## - # Ask the preprocessor for a make-style dependency rule of only the headers - # the source file immediately includes. - # - # === Arguments - # +filepath+ _String_:: Path to the test file to process. - # - # === Return - # _String_:: The text of the dependency rule generated by the preprocessor. - def form_shallow_dependencies_rule(filepath) - if @@makefile_cache.has_key?(filepath) - return @@makefile_cache[filepath] - end - # change filename (prefix of '_') to prevent preprocessor from finding - # include files in temp directory containing file it's scanning - temp_filepath = @file_path_utils.form_temp_path(filepath, '_') - - # read the file and replace all include statements with a decorated version - # (decorating the names creates file names that don't exist, thus preventing - # the preprocessor from snaking out and discovering the entire include path - # that winds through the code). The decorated filenames indicate files that - # are included directly by the test file. - contents = @file_wrapper.read(filepath) - - if !contents.valid_encoding? - contents = contents.encode("UTF-16be", :invalid=>:replace, :replace=>"?").encode('UTF-8') - end - - contents.gsub!( /^\s*#include\s+[\"<]\s*(\S+)\s*[\">]/, "#include \"\\1\"\n#include \"@@@@\\1\"" ) - contents.gsub!( /^\s*TEST_FILE\(\s*\"\s*(\S+)\s*\"\s*\)/, "#include \"\\1\"\n#include \"@@@@\\1\"") - @file_wrapper.write( temp_filepath, contents ) - - # extract the make-style dependency rule telling the preprocessor to - # ignore the fact that it can't find the included files - command = @tool_executor.build_command_line(@configurator.tools_test_includes_preprocessor, [], temp_filepath) - shell_result = @tool_executor.exec(command[:line], command[:options]) - - @@makefile_cache[filepath] = shell_result[:output] - return shell_result[:output] - end - - ## - # Extract the headers that are directly included by a source file using the - # provided, annotated Make dependency rule. - # - # === Arguments - # +filepath+ _String_:: C source or header file to extract includes for. - # - # === Return - # _Array_ of _String_:: Array of the direct dependencies for the source file. - def extract_includes(filepath) - to_process = [filepath] - ignore_list = [] - list = [] - all_mocks = [] - - include_paths = @configurator.project_config_hash[:collection_paths_include] - include_paths = [] if include_paths.nil? - include_paths.map! {|path| File.expand_path(path)} - - while to_process.length > 0 - target = to_process.shift() - ignore_list << target - new_deps, new_to_process, all_mocks = extract_includes_helper(target, include_paths, ignore_list, all_mocks) - list += new_deps - to_process += new_to_process - if !@configurator.project_config_hash[:project_auto_link_deep_dependencies] - break - else - list = list.uniq() - to_process = to_process.uniq() - end - end - - return list - end - - def extract_includes_helper(filepath, include_paths, ignore_list, mocks) - # Extract the dependencies from the make rule - make_rule = self.form_shallow_dependencies_rule(filepath) - target_file = make_rule.split[0].gsub(':', '').gsub('\\','/') - base = File.basename(target_file, File.extname(target_file)) - make_rule_dependencies = make_rule.gsub(/.*\b#{Regexp.escape(base)}\S*/, '').gsub(/\\$/, '') - - # Extract the headers dependencies from the make rule - hdr_ext = @configurator.extension_header - headers_dependencies = make_rule_dependencies.split.find_all {|path| path.end_with?(hdr_ext) }.uniq - headers_dependencies.map! {|hdr| hdr.gsub('\\','/') } - full_path_headers_dependencies = extract_full_path_dependencies(headers_dependencies) - - # Extract the sources dependencies from the make rule - src_ext = @configurator.extension_source - sources_dependencies = make_rule_dependencies.split.find_all {|path| path.end_with?(src_ext) }.uniq - sources_dependencies.map! {|src| src.gsub('\\','/') } - full_path_sources_dependencies = extract_full_path_dependencies(sources_dependencies) - - list = full_path_headers_dependencies + full_path_sources_dependencies - - mock_prefix = @configurator.project_config_hash[:cmock_mock_prefix] - # Creating list of mocks - mocks += full_path_headers_dependencies.find_all do |header| - File.basename(header) =~ /^#{mock_prefix}.*$/ - end.compact - - # ignore real file when both mock and real file exist - mocks.each do |mock| - list.each do |filename| - if File.basename(filename) == File.basename(mock).sub(mock_prefix, '') - ignore_list << filename - end - end - end.compact - - # Filtering list of final includes to only include mocks and anything that is NOT in the ignore_list - list = list.select do |item| - mocks.include? item or !(ignore_list.any? { |ignore_item| !item.match(/^(.*\/)?#{Regexp.escape(ignore_item)}$/).nil? }) - end - - to_process = [] - - if @configurator.project_config_hash[:project_auto_link_deep_dependencies] - # Creating list of headers that should be recursively pre-processed - # Skipping mocks and vendor headers - headers_to_deep_link = full_path_headers_dependencies.select do |hdr| - !(mocks.include? hdr) and (hdr.match(/^(.*\/)(#{VENDORS_FILES.join('|')}) + #{Regexp.escape(hdr_ext)}$/).nil?) - end - headers_to_deep_link.map! {|hdr| File.expand_path(hdr) } - headers_to_deep_link.compact! - - headers_to_deep_link.each do |hdr| - if (ignore_list.none? {|ignore_header| hdr.match(/^(.*\/)?#{Regexp.escape(ignore_header)}$/)} and - include_paths.none? {|include_path| hdr =~ /^#{include_path}\.*/}) - if File.exist?(hdr) - to_process << hdr - src = @file_finder.find_compilation_input_file(hdr, :ignore) - to_process << src if src - end - end - end - end - - return list, to_process, mocks - - end - - def write_shallow_includes_list(filepath, list) - @yaml_wrapper.dump(filepath, list) - end - - private - - def extract_full_path_dependencies(dependencies) - # Separate the real files form the annotated ones and remove the '@@@@' - annotated_files, real_files = dependencies.partition {|file| file =~ /^@@@@/} - annotated_files.map! {|file| file.gsub('@@@@','') } - # Matching annotated_files values against real_files to ensure that - # annotated_files contain full path entries (as returned by make rule) - annotated_files.map! {|file| real_files.find {|real| !real.match(/^(.*\/)?#{Regexp.escape(file)}$/).nil?}} - annotated_files = annotated_files.compact - - # Find which of our annotated files are "real" dependencies. This is - # intended to weed out dependencies that have been removed due to build - # options defined in the project yaml and/or in the files themselves. - return annotated_files.find_all do |annotated_file| - # find the index of the "real" file that matches the annotated one. - idx = real_files.find_index do |real_file| - real_file =~ /^(.*\/)?#{Regexp.escape(annotated_file)}$/ - end - # If we found a real file, delete it from the array and return it, - # otherwise return nil. Since nil is falsy this has the effect of making - # find_all return only the annotated files for which a real file was - # found/deleted - idx ? real_files.delete_at(idx) : nil - end.compact - end -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/project_config_manager.rb b/test/unit-test/vendor/ceedling/lib/ceedling/project_config_manager.rb deleted file mode 100644 index b1d455127..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/project_config_manager.rb +++ /dev/null @@ -1,52 +0,0 @@ -require 'ceedling/constants' - - -class ProjectConfigManager - - attr_reader :options_files, :release_config_changed, :test_config_changed, :test_defines_changed - attr_accessor :config_hash - - constructor :cacheinator, :configurator, :yaml_wrapper, :file_wrapper - - - def setup - @options_files = [] - @release_config_changed = false - @test_config_changed = false - @test_defines_changed = false - end - - - def merge_options(config_hash, option_filepath) - @options_files << File.basename( option_filepath ) - config_hash.deep_merge!( @yaml_wrapper.load( option_filepath ) ) - end - - - def filter_internal_sources(sources) - filtered_sources = sources.clone - filtered_sources.delete_if { |item| item =~ /#{CMOCK_MOCK_PREFIX}.+#{Regexp.escape(EXTENSION_SOURCE)}$/ } - filtered_sources.delete_if { |item| item =~ /#{VENDORS_FILES.map{|source| '\b' + Regexp.escape(source.ext(EXTENSION_SOURCE)) + '\b'}.join('|')}$/ } - return filtered_sources - end - - def process_release_config_change - # has project configuration changed since last release build - @release_config_changed = @cacheinator.diff_cached_release_config?( @config_hash ) - end - - - def process_test_config_change - # has project configuration changed since last test build - @test_config_changed = @cacheinator.diff_cached_test_config?( @config_hash ) - end - - def process_test_defines_change(files) - # has definitions changed since last test build - @test_defines_changed = @cacheinator.diff_cached_test_defines?( files ) - if @test_defines_changed - # update timestamp for rake task prerequisites - @file_wrapper.touch( @configurator.project_test_force_rebuild_filepath, :mtime => Time.now + 10 ) - end - end -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/project_file_loader.rb b/test/unit-test/vendor/ceedling/lib/ceedling/project_file_loader.rb deleted file mode 100644 index bf5dcd41d..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/project_file_loader.rb +++ /dev/null @@ -1,99 +0,0 @@ -require 'ceedling/constants' - - -class ProjectFileLoader - - attr_reader :main_file, :user_file - - constructor :yaml_wrapper, :stream_wrapper, :system_wrapper, :file_wrapper - - def setup - @main_file = nil - @mixin_files = [] - @user_file = nil - - @main_project_filepath = '' - @mixin_project_filepaths = [] - @user_project_filepath = '' - end - - - def find_project_files - # first go hunting for optional user project file by looking for environment variable and then default location on disk - user_filepath = @system_wrapper.env_get('CEEDLING_USER_PROJECT_FILE') - - if ( not user_filepath.nil? and @file_wrapper.exist?(user_filepath) ) - @user_project_filepath = user_filepath - elsif (@file_wrapper.exist?(DEFAULT_CEEDLING_USER_PROJECT_FILE)) - @user_project_filepath = DEFAULT_CEEDLING_USER_PROJECT_FILE - end - - # next check for mixin project files by looking for environment variable - mixin_filepaths = @system_wrapper.env_get('CEEDLING_MIXIN_PROJECT_FILES') - if ( not mixin_filepaths.nil? ) - mixin_filepaths.split(File::PATH_SEPARATOR).each do |filepath| - if ( @file_wrapper.exist?(filepath) ) - @mixin_project_filepaths.push(filepath) - end - end - end - - # next check for main project file by looking for environment variable and then default location on disk; - # blow up if we don't find this guy -- like, he's so totally important - main_filepath = @system_wrapper.env_get('CEEDLING_MAIN_PROJECT_FILE') - - if ( not main_filepath.nil? and @file_wrapper.exist?(main_filepath) ) - @main_project_filepath = main_filepath - elsif (@file_wrapper.exist?(DEFAULT_CEEDLING_MAIN_PROJECT_FILE)) - @main_project_filepath = DEFAULT_CEEDLING_MAIN_PROJECT_FILE - else - # no verbosity checking since this is lowest level reporting anyhow & - # verbosity checking depends on configurator which in turns needs this class (circular dependency) - @stream_wrapper.stderr_puts('Found no Ceedling project file (*.yml)') - raise - end - - @main_file = File.basename( @main_project_filepath ) - @mixin_project_filepaths.each do |filepath| - @mixin_files.push(File.basename( filepath )) - end - @user_file = File.basename( @user_project_filepath ) if ( not @user_project_filepath.empty? ) - end - - def yaml_merger(y1, y2) - o1 = y1 - y2.each_pair do |k,v| - if o1[k].nil? - o1[k] = v - else - if (o1[k].instance_of? Hash) - o1[k] = yaml_merger(o1[k], v) - elsif (o1[k].instance_of? Array) - o1[k] += v - else - o1[k] = v - end - end - end - return o1 - end - - def load_project_config - config_hash = @yaml_wrapper.load(@main_project_filepath) - - # if there are mixin project files, then use them - @mixin_project_filepaths.each do |filepath| - mixin = @yaml_wrapper.load(filepath) - config_hash = yaml_merger( config_hash, mixin ) - end - - # if there's a user project file, then use it - if ( not @user_project_filepath.empty? ) - user_hash = @yaml_wrapper.load(@user_project_filepath) - config_hash = yaml_merger( config_hash, user_hash ) - end - - return config_hash - end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/rake_utils.rb b/test/unit-test/vendor/ceedling/lib/ceedling/rake_utils.rb deleted file mode 100644 index b13749738..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/rake_utils.rb +++ /dev/null @@ -1,17 +0,0 @@ - -class RakeUtils - - constructor :rake_wrapper - - def task_invoked?(task_regex) - task_invoked = false - @rake_wrapper.task_list.each do |task| - if ((task.already_invoked) and (task.to_s =~ task_regex)) - task_invoked = true - break - end - end - return task_invoked - end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/rake_wrapper.rb b/test/unit-test/vendor/ceedling/lib/ceedling/rake_wrapper.rb deleted file mode 100644 index 15e479611..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/rake_wrapper.rb +++ /dev/null @@ -1,33 +0,0 @@ -require 'rubygems' -require 'rake' -require 'ceedling/makefile' # our replacement for rake's make-style dependency loader - -include Rake::DSL if defined?(Rake::DSL) - -class Rake::Task - attr_reader :already_invoked -end - -class RakeWrapper - - def initialize - @makefile_loader = Rake::MakefileLoader.new # use our custom replacement noted above - end - - def [](task) - return Rake::Task[task] - end - - def task_list - return Rake::Task.tasks - end - - def create_file_task(file_task, dependencies) - file(file_task => dependencies) - end - - def load_dependencies(dependencies_path) - @makefile_loader.load(dependencies_path) - end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/rakefile.rb b/test/unit-test/vendor/ceedling/lib/ceedling/rakefile.rb deleted file mode 100644 index 1bcb82491..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/rakefile.rb +++ /dev/null @@ -1,85 +0,0 @@ -require 'fileutils' - -# get directory containing this here file, back up one directory, and expand to full path -CEEDLING_ROOT = File.expand_path(File.dirname(__FILE__) + '/../..') -CEEDLING_LIB = File.join(CEEDLING_ROOT, 'lib') -CEEDLING_VENDOR = File.join(CEEDLING_ROOT, 'vendor') -CEEDLING_RELEASE = File.join(CEEDLING_ROOT, 'release') - -$LOAD_PATH.unshift( CEEDLING_LIB ) -$LOAD_PATH.unshift( File.join(CEEDLING_VENDOR, 'unity/auto') ) -$LOAD_PATH.unshift( File.join(CEEDLING_VENDOR, 'diy/lib') ) -$LOAD_PATH.unshift( File.join(CEEDLING_VENDOR, 'cmock/lib') ) - -require 'rake' - -#Let's make sure we remember the task descriptions in case we need them -Rake::TaskManager.record_task_metadata = true - -require 'diy' -require 'constructor' - -require 'ceedling/constants' -require 'ceedling/target_loader' - - -# construct all our objects -# ensure load path contains all libraries needed first -lib_ceedling_load_path_temp = File.join(CEEDLING_LIB, 'ceedling') -$LOAD_PATH.unshift( lib_ceedling_load_path_temp ) -@ceedling = DIY::Context.from_yaml( File.read( File.join(lib_ceedling_load_path_temp, 'objects.yml') ) ) -@ceedling.build_everything -# now that all objects are built, delete 'lib/ceedling' from load path -$LOAD_PATH.delete(lib_ceedling_load_path_temp) -# one-stop shopping for all our setup and such after construction -@ceedling[:setupinator].ceedling = @ceedling - -project_config = - begin - cfg = @ceedling[:setupinator].load_project_files - TargetLoader.inspect(cfg, ENV['TARGET']) - rescue TargetLoader::NoTargets - cfg - rescue TargetLoader::RequestReload - @ceedling[:setupinator].load_project_files - end - -@ceedling[:setupinator].do_setup( project_config ) - - -# tell all our plugins we're about to do something -@ceedling[:plugin_manager].pre_build - -# load rakefile component files (*.rake) -PROJECT_RAKEFILE_COMPONENT_FILES.each { |component| load(component) } - -# tell rake to shut up by default (overridden in verbosity / debug tasks as appropriate) -verbose(false) - - -# end block always executed following rake run -END { - $stdout.flush unless $stdout.nil? - $stderr.flush unless $stderr.nil? - - # cache our input configurations to use in comparison upon next execution - @ceedling[:cacheinator].cache_test_config( @ceedling[:setupinator].config_hash ) if (@ceedling[:task_invoker].test_invoked?) - @ceedling[:cacheinator].cache_release_config( @ceedling[:setupinator].config_hash ) if (@ceedling[:task_invoker].release_invoked?) - - # delete all temp files unless we're in debug mode - if (not @ceedling[:configurator].project_debug) - @ceedling[:file_wrapper].rm_f( @ceedling[:file_wrapper].directory_listing( File.join(@ceedling[:configurator].project_temp_path, '*') )) - end - - # only perform these final steps if we got here without runtime exceptions or errors - if (@ceedling[:system_wrapper].ruby_success) - - # tell all our plugins the build is done and process results - @ceedling[:plugin_manager].post_build - @ceedling[:plugin_manager].print_plugin_failures - exit(1) if (@ceedling[:plugin_manager].plugins_failed? && !@ceedling[:setupinator].config_hash[:graceful_fail]) - else - puts "ERROR: Ceedling Failed" - @ceedling[:plugin_manager].post_error - end -} diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/release_invoker.rb b/test/unit-test/vendor/ceedling/lib/ceedling/release_invoker.rb deleted file mode 100644 index 19bbca727..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/release_invoker.rb +++ /dev/null @@ -1,98 +0,0 @@ -require 'ceedling/constants' - - -class ReleaseInvoker - - constructor :configurator, :release_invoker_helper, :build_invoker_utils, :dependinator, :task_invoker, :file_path_utils, :file_wrapper - - - def setup_and_invoke_c_objects( c_files ) - objects = @file_path_utils.form_release_build_c_objects_filelist( c_files ) - - begin - @release_invoker_helper.process_deep_dependencies( @file_path_utils.form_release_dependencies_filelist( c_files ) ) - - @dependinator.enhance_release_file_dependencies( objects ) - @task_invoker.invoke_release_objects( objects ) - rescue => e - @build_invoker_utils.process_exception( e, RELEASE_SYM, false ) - end - - return objects - end - - - def setup_and_invoke_asm_objects( asm_files ) - objects = @file_path_utils.form_release_build_asm_objects_filelist( asm_files ) - - begin - @dependinator.enhance_release_file_dependencies( objects ) - @task_invoker.invoke_release_objects( objects ) - rescue => e - @build_invoker_utils.process_exception( e, RELEASE_SYM, false ) - end - - return objects - end - - - def refresh_c_deep_dependencies - return if (not @configurator.project_use_deep_dependencies) - - @file_wrapper.rm_f( - @file_wrapper.directory_listing( - File.join( @configurator.project_release_dependencies_path, '*' + @configurator.extension_dependencies ) ) ) - - @release_invoker_helper.process_deep_dependencies( - @file_path_utils.form_release_dependencies_filelist( - @configurator.collection_all_source ) ) - end - - - def artifactinate( *files ) - files.flatten.each do |file| - @file_wrapper.cp( file, @configurator.project_release_artifacts_path ) if @file_wrapper.exist?( file ) - end - end - - def convert_libraries_to_arguments(libraries) - args = ((libraries || []) + ((defined? LIBRARIES_SYSTEM) ? LIBRARIES_SYSTEM : [])).flatten - if (defined? LIBRARIES_FLAG) - args.map! {|v| LIBRARIES_FLAG.gsub(/\$\{1\}/, v) } - end - return args - end - - def get_library_paths_to_arguments() - paths = (defined? PATHS_LIBRARIES) ? (PATHS_LIBRARIES || []).clone : [] - if (defined? LIBRARIES_PATH_FLAG) - paths.map! {|v| LIBRARIES_PATH_FLAG.gsub(/\$\{1\}/, v) } - end - return paths - end - - def sort_objects_and_libraries(both) - extension = if ((defined? EXTENSION_SUBPROJECTS) && (defined? EXTENSION_LIBRARIES)) - extension_libraries = if (EXTENSION_LIBRARIES.class == Array) - EXTENSION_LIBRARIES.join(")|(?:\\") - else - EXTENSION_LIBRARIES - end - "(?:\\#{EXTENSION_SUBPROJECTS})|(?:\\#{extension_libraries})" - elsif (defined? EXTENSION_SUBPROJECTS) - "\\#{EXTENSION_SUBPROJECTS}" - elsif (defined? EXTENSION_LIBRARIES) - if (EXTENSION_LIBRARIES.class == Array) - "(?:\\#{EXTENSION_LIBRARIES.join(")|(?:\\")})" - else - "\\#{EXTENSION_LIBRARIES}" - end - else - "\\.LIBRARY" - end - sorted_objects = both.group_by {|v| v.match(/.+#{extension}$/) ? :libraries : :objects } - libraries = sorted_objects[:libraries] || [] - objects = sorted_objects[:objects] || [] - return objects, libraries - end -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/release_invoker_helper.rb b/test/unit-test/vendor/ceedling/lib/ceedling/release_invoker_helper.rb deleted file mode 100644 index f83a2a53a..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/release_invoker_helper.rb +++ /dev/null @@ -1,19 +0,0 @@ - - -class ReleaseInvokerHelper - - constructor :configurator, :dependinator, :task_invoker - - - def process_deep_dependencies(dependencies_list) - return if (not @configurator.project_use_deep_dependencies) - - if @configurator.project_generate_deep_dependencies - @dependinator.enhance_release_file_dependencies( dependencies_list ) - @task_invoker.invoke_release_dependencies_files( dependencies_list ) - end - - @dependinator.load_release_object_deep_dependencies( dependencies_list ) - end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/reportinator.rb b/test/unit-test/vendor/ceedling/lib/ceedling/reportinator.rb deleted file mode 100644 index fcb5286b9..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/reportinator.rb +++ /dev/null @@ -1,26 +0,0 @@ -## -# Pretifies reports -class Reportinator - - ## - # Generates a banner for a message based on the length of the message or a - # given width. - # ==== Attributes - # - # * _message_: The message to put. - # * _width_: The width of the message. If nil the size of the banner is - # determined by the length of the message. - # - # ==== Examples - # - # rp = Reportinator.new - # rp.generate_banner("Hello world!") => "------------\nHello world!\n------------\n" - # rp.generate_banner("Hello world!", 3) => "---\nHello world!\n---\n" - # - # - def generate_banner(message, width=nil) - dash_count = ((width.nil?) ? message.strip.length : width) - return "#{'-' * dash_count}\n#{message}\n#{'-' * dash_count}\n" - end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/rules_cmock.rake b/test/unit-test/vendor/ceedling/lib/ceedling/rules_cmock.rake deleted file mode 100644 index 51485d3a8..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/rules_cmock.rake +++ /dev/null @@ -1,9 +0,0 @@ - - -rule(/#{CMOCK_MOCK_PREFIX}[^\/\\]+#{'\\'+EXTENSION_SOURCE}$/ => [ - proc do |task_name| - @ceedling[:file_finder].find_header_input_for_mock_file(task_name) - end - ]) do |mock| - @ceedling[:generator].generate_mock(TEST_SYM, mock.source) -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/rules_preprocess.rake b/test/unit-test/vendor/ceedling/lib/ceedling/rules_preprocess.rake deleted file mode 100644 index d599421c0..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/rules_preprocess.rake +++ /dev/null @@ -1,25 +0,0 @@ - - -# invocations against this rule should only happen when enhanced dependencies are enabled; -# otherwise, dependency tracking will be too shallow and preprocessed files could intermittently -# fail to be updated when they actually need to be. -rule(/#{PROJECT_TEST_PREPROCESS_FILES_PATH}\/.+/ => [ - proc do |task_name| - @ceedling[:file_finder].find_test_or_source_or_header_file(task_name) - end - ]) do |file| - if (not @ceedling[:configurator].project_use_deep_dependencies) - raise 'ERROR: Ceedling preprocessing rule invoked though necessary auxiliary dependency support not enabled.' - end - @ceedling[:generator].generate_preprocessed_file(TEST_SYM, file.source) -end - - -# invocations against this rule can always happen as there are no deeper dependencies to consider -rule(/#{PROJECT_TEST_PREPROCESS_INCLUDES_PATH}\/.+/ => [ - proc do |task_name| - @ceedling[:file_finder].find_test_or_source_or_header_file(task_name) - end - ]) do |file| - @ceedling[:generator].generate_shallow_includes_list(TEST_SYM, file.source) -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/rules_release.rake b/test/unit-test/vendor/ceedling/lib/ceedling/rules_release.rake deleted file mode 100644 index 47eec858f..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/rules_release.rake +++ /dev/null @@ -1,98 +0,0 @@ - -RELEASE_COMPILE_TASK_ROOT = RELEASE_TASK_ROOT + 'compile:' unless defined?(RELEASE_COMPILE_TASK_ROOT) -RELEASE_ASSEMBLE_TASK_ROOT = RELEASE_TASK_ROOT + 'assemble:' unless defined?(RELEASE_ASSEMBLE_TASK_ROOT) - -# If GCC and Releasing a Library, Update Tools to Automatically Have Necessary Tags -if (TOOLS_RELEASE_COMPILER[:executable] == DEFAULT_RELEASE_COMPILER_TOOL[:executable]) - if (File.extname(PROJECT_RELEASE_BUILD_TARGET) == '.so') - TOOLS_RELEASE_COMPILER[:arguments] << "-fPIC" unless TOOLS_RELEASE_COMPILER[:arguments].include?("-fPIC") - TOOLS_RELEASE_LINKER[:arguments] << "-shared" unless TOOLS_RELEASE_LINKER[:arguments].include?("-shared") - elsif (File.extname(PROJECT_RELEASE_BUILD_TARGET) == '.a') - TOOLS_RELEASE_COMPILER[:arguments] << "-fPIC" unless TOOLS_RELEASE_COMPILER[:arguments].include?("-fPIC") - TOOLS_RELEASE_LINKER[:executable] = 'ar' - TOOLS_RELEASE_LINKER[:arguments] = ['rcs', '${2}', '${1}'].compact - end -end - -if (RELEASE_BUILD_USE_ASSEMBLY) -rule(/#{PROJECT_RELEASE_BUILD_OUTPUT_ASM_PATH}\/#{'.+\\'+EXTENSION_OBJECT}$/ => [ - proc do |task_name| - @ceedling[:file_finder].find_assembly_file(task_name) - end - ]) do |object| - @ceedling[:generator].generate_object_file( - TOOLS_RELEASE_ASSEMBLER, - OPERATION_ASSEMBLE_SYM, - RELEASE_SYM, - object.source, - object.name ) -end -end - - -rule(/#{PROJECT_RELEASE_BUILD_OUTPUT_C_PATH}\/#{'.+\\'+EXTENSION_OBJECT}$/ => [ - proc do |task_name| - @ceedling[:file_finder].find_compilation_input_file(task_name, :error, true) - end - ]) do |object| - @ceedling[:generator].generate_object_file( - TOOLS_RELEASE_COMPILER, - OPERATION_COMPILE_SYM, - RELEASE_SYM, - object.source, - object.name, - @ceedling[:file_path_utils].form_release_build_c_list_filepath( object.name ), - @ceedling[:file_path_utils].form_release_dependencies_filepath( object.name ) ) -end - - -rule(/#{PROJECT_RELEASE_BUILD_TARGET}/) do |bin_file| - objects, libraries = @ceedling[:release_invoker].sort_objects_and_libraries(bin_file.prerequisites) - tool = TOOLS_RELEASE_LINKER.clone - lib_args = @ceedling[:release_invoker].convert_libraries_to_arguments(libraries) - lib_paths = @ceedling[:release_invoker].get_library_paths_to_arguments() - map_file = @ceedling[:configurator].project_release_build_map - @ceedling[:generator].generate_executable_file( - tool, - RELEASE_SYM, - objects, - bin_file.name, - map_file, - lib_args, - lib_paths ) - @ceedling[:release_invoker].artifactinate( bin_file.name, map_file, @ceedling[:configurator].release_build_artifacts ) -end - - -namespace RELEASE_SYM do - # use rules to increase efficiency for large projects (instead of iterating through all sources and creating defined tasks) - - namespace :compile do - rule(/^#{RELEASE_COMPILE_TASK_ROOT}\S+#{'\\'+EXTENSION_SOURCE}$/ => [ # compile task names by regex - proc do |task_name| - source = task_name.sub(/#{RELEASE_COMPILE_TASK_ROOT}/, '') - @ceedling[:file_finder].find_source_file(source, :error) - end - ]) do |compile| - @ceedling[:rake_wrapper][:directories].invoke - @ceedling[:project_config_manager].process_release_config_change - @ceedling[:release_invoker].setup_and_invoke_c_objects( [compile.source] ) - end - end - - if (RELEASE_BUILD_USE_ASSEMBLY) - namespace :assemble do - rule(/^#{RELEASE_ASSEMBLE_TASK_ROOT}\S+#{'\\'+EXTENSION_ASSEMBLY}$/ => [ # assemble task names by regex - proc do |task_name| - source = task_name.sub(/#{RELEASE_ASSEMBLE_TASK_ROOT}/, '') - @ceedling[:file_finder].find_assembly_file(source) - end - ]) do |assemble| - @ceedling[:rake_wrapper][:directories].invoke - @ceedling[:project_config_manager].process_release_config_change - @ceedling[:release_invoker].setup_and_invoke_asm_objects( [assemble.source] ) - end - end - end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/rules_release_deep_dependencies.rake b/test/unit-test/vendor/ceedling/lib/ceedling/rules_release_deep_dependencies.rake deleted file mode 100644 index bf944de25..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/rules_release_deep_dependencies.rake +++ /dev/null @@ -1,14 +0,0 @@ - - -rule(/#{PROJECT_RELEASE_DEPENDENCIES_PATH}\/#{'.+\\'+EXTENSION_DEPENDENCIES}$/ => [ - proc do |task_name| - @ceedling[:file_finder].find_compilation_input_file(task_name, :error, true) - end - ]) do |dep| - @ceedling[:generator].generate_dependencies_file( - TOOLS_RELEASE_DEPENDENCIES_GENERATOR, - RELEASE_SYM, - dep.source, - @ceedling[:file_path_utils].form_release_build_c_object_filepath(dep.source), - dep.name) -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/rules_tests.rake b/test/unit-test/vendor/ceedling/lib/ceedling/rules_tests.rake deleted file mode 100644 index 3ab80f3a9..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/rules_tests.rake +++ /dev/null @@ -1,72 +0,0 @@ - - -rule(/#{PROJECT_TEST_FILE_PREFIX}#{'.+'+TEST_RUNNER_FILE_SUFFIX}#{'\\'+EXTENSION_SOURCE}$/ => [ - proc do |task_name| - @ceedling[:file_finder].find_test_input_for_runner_file(task_name) - end - ]) do |runner| - @ceedling[:generator].generate_test_runner(TEST_SYM, runner.source, runner.name) -end - -rule(/#{PROJECT_TEST_BUILD_OUTPUT_C_PATH}\/#{'.+\\'+EXTENSION_OBJECT}$/ => [ - proc do |task_name| - @ceedling[:file_finder].find_compilation_input_file(task_name) - end - ]) do |object| - if (File.basename(object.source) =~ /#{EXTENSION_SOURCE}$/) - @ceedling[:generator].generate_object_file( - TOOLS_TEST_COMPILER, - OPERATION_COMPILE_SYM, - TEST_SYM, - object.source, - object.name, - @ceedling[:file_path_utils].form_test_build_list_filepath( object.name ), - @ceedling[:file_path_utils].form_test_dependencies_filepath( object.name )) - elsif (defined?(TEST_BUILD_USE_ASSEMBLY) && TEST_BUILD_USE_ASSEMBLY) - @ceedling[:generator].generate_object_file( - TOOLS_TEST_ASSEMBLER, - OPERATION_ASSEMBLE_SYM, - TEST_SYM, - object.source, - object.name ) - end -end - - -rule(/#{PROJECT_TEST_BUILD_OUTPUT_PATH}\/#{'.+\\'+EXTENSION_EXECUTABLE}$/) do |bin_file| - lib_args = @ceedling[:test_invoker].convert_libraries_to_arguments() - lib_paths = @ceedling[:test_invoker].get_library_paths_to_arguments() - @ceedling[:generator].generate_executable_file( - TOOLS_TEST_LINKER, - TEST_SYM, - bin_file.prerequisites, - bin_file.name, - @ceedling[:file_path_utils].form_test_build_map_filepath( bin_file.name ), - lib_args, - lib_paths ) -end - - -rule(/#{PROJECT_TEST_RESULTS_PATH}\/#{'.+\\'+EXTENSION_TESTPASS}$/ => [ - proc do |task_name| - @ceedling[:file_path_utils].form_test_executable_filepath(task_name) - end - ]) do |test_result| - @ceedling[:generator].generate_test_results(TOOLS_TEST_FIXTURE, TEST_SYM, test_result.source, test_result.name) -end - - -namespace TEST_SYM do - # use rules to increase efficiency for large projects (instead of iterating through all sources and creating defined tasks) - - rule(/^#{TEST_TASK_ROOT}\S+$/ => [ # test task names by regex - proc do |task_name| - test = task_name.sub(/#{TEST_TASK_ROOT}/, '') - test = "#{PROJECT_TEST_FILE_PREFIX}#{test}" if not (test.start_with?(PROJECT_TEST_FILE_PREFIX)) - @ceedling[:file_finder].find_test_from_file_path(test) - end - ]) do |test| - @ceedling[:rake_wrapper][:test_deps].invoke - @ceedling[:test_invoker].setup_and_invoke([test.source]) - end -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/rules_tests_deep_dependencies.rake b/test/unit-test/vendor/ceedling/lib/ceedling/rules_tests_deep_dependencies.rake deleted file mode 100644 index a8dfd296e..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/rules_tests_deep_dependencies.rake +++ /dev/null @@ -1,14 +0,0 @@ - - -rule(/#{PROJECT_TEST_DEPENDENCIES_PATH}\/#{'.+\\'+EXTENSION_DEPENDENCIES}$/ => [ - proc do |task_name| - @ceedling[:file_finder].find_compilation_input_file(task_name) - end - ]) do |dep| - @ceedling[:generator].generate_dependencies_file( - TOOLS_TEST_DEPENDENCIES_GENERATOR, - TEST_SYM, - dep.source, - @ceedling[:file_path_utils].form_test_build_c_object_filepath(dep.source), - dep.name) -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/setupinator.rb b/test/unit-test/vendor/ceedling/lib/ceedling/setupinator.rb deleted file mode 100644 index cf9922f07..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/setupinator.rb +++ /dev/null @@ -1,53 +0,0 @@ - -class Setupinator - - attr_reader :config_hash - attr_writer :ceedling - - def setup - @ceedling = {} - @config_hash = {} - end - - def load_project_files - @ceedling[:project_file_loader].find_project_files - return @ceedling[:project_file_loader].load_project_config - end - - def do_setup(config_hash) - @config_hash = config_hash - - # load up all the constants and accessors our rake files, objects, & external scripts will need; - # note: configurator modifies the cmock section of the hash with a couple defaults to tie - # project together - the modified hash is used to build cmock object - @ceedling[:configurator].populate_defaults( config_hash ) - @ceedling[:configurator].populate_unity_defaults( config_hash ) - @ceedling[:configurator].populate_cmock_defaults( config_hash ) - @ceedling[:configurator].find_and_merge_plugins( config_hash ) - @ceedling[:configurator].merge_imports( config_hash ) - @ceedling[:configurator].eval_environment_variables( config_hash ) - @ceedling[:configurator].tools_setup( config_hash ) - @ceedling[:configurator].eval_paths( config_hash ) - @ceedling[:configurator].standardize_paths( config_hash ) - @ceedling[:configurator].validate( config_hash ) - @ceedling[:configurator].build( config_hash, :environment ) - - @ceedling[:configurator].insert_rake_plugins( @ceedling[:configurator].rake_plugins ) - @ceedling[:configurator].tools_supplement_arguments( config_hash ) - - # merge in any environment variables plugins specify, after the main build - @ceedling[:plugin_manager].load_plugin_scripts( @ceedling[:configurator].script_plugins, @ceedling ) do |env| - @ceedling[:configurator].eval_environment_variables( env ) - @ceedling[:configurator].build_supplement( config_hash, env ) - end - - @ceedling[:plugin_reportinator].set_system_objects( @ceedling ) - @ceedling[:file_finder].prepare_search_sources - @ceedling[:loginator].setup_log_filepath - @ceedling[:project_config_manager].config_hash = config_hash - end - - def reset_defaults(config_hash) - @ceedling[:configurator].reset_defaults( config_hash ) - end -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/stream_wrapper.rb b/test/unit-test/vendor/ceedling/lib/ceedling/stream_wrapper.rb deleted file mode 100644 index 2cee58d3e..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/stream_wrapper.rb +++ /dev/null @@ -1,28 +0,0 @@ - -class StreamWrapper - - def stdout_override(&fnc) - @stdout_overide_fnc = fnc - end - - def stdout_puts(string) - if @stdout_overide_fnc - @stdout_overide_fnc.call(string) - else - $stdout.puts(string) - end - end - - def stdout_flush - $stdout.flush - end - - def stderr_puts(string) - $stderr.puts(string) - end - - def stderr_flush - $stderr.flush - end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/streaminator.rb b/test/unit-test/vendor/ceedling/lib/ceedling/streaminator.rb deleted file mode 100644 index e30440c7d..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/streaminator.rb +++ /dev/null @@ -1,40 +0,0 @@ -require 'ceedling/constants' - -class Streaminator - - constructor :streaminator_helper, :verbosinator, :loginator, :stream_wrapper - - # for those objects for whom the configurator has already been instantiated, - # Streaminator is a convenience object for handling verbosity and writing to the std streams - - def stdout_puts(string, verbosity=Verbosity::NORMAL) - if (@verbosinator.should_output?(verbosity)) - @stream_wrapper.stdout_puts(string) - @stream_wrapper.stdout_flush - end - - # write to log as though Verbosity::OBNOXIOUS - @loginator.log( string, @streaminator_helper.extract_name($stdout) ) - end - - def stderr_puts(string, verbosity=Verbosity::NORMAL) - if (@verbosinator.should_output?(verbosity)) - @stream_wrapper.stderr_puts(string) - @stream_wrapper.stderr_flush - end - - # write to log as though Verbosity::OBNOXIOUS - @loginator.log( string, @streaminator_helper.extract_name($stderr) ) - end - - def stream_puts(stream, string, verbosity=Verbosity::NORMAL) - if (@verbosinator.should_output?(verbosity)) - stream.puts(string) - stream.flush - end - - # write to log as though Verbosity::OBNOXIOUS - @loginator.log( string, @streaminator_helper.extract_name(stream) ) - end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/streaminator_helper.rb b/test/unit-test/vendor/ceedling/lib/ceedling/streaminator_helper.rb deleted file mode 100644 index cbaef7c92..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/streaminator_helper.rb +++ /dev/null @@ -1,15 +0,0 @@ - -class StreaminatorHelper - - def extract_name(stream) - name = case (stream.fileno) - when 0 then '#' - when 1 then '#' - when 2 then '#' - else stream.inspect - end - - return name - end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/system_utils.rb b/test/unit-test/vendor/ceedling/lib/ceedling/system_utils.rb deleted file mode 100644 index 7d232a7fb..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/system_utils.rb +++ /dev/null @@ -1,37 +0,0 @@ - -class Object - def deep_clone - Marshal::load(Marshal.dump(self)) - end -end - - -## -# Class containing system utility functions. -class SystemUtils - - constructor :system_wrapper - - ## - # Sets up the class. - def setup - @tcsh_shell = nil - end - - ## - # Checks the system shell to see if it a tcsh shell. - def tcsh_shell? - # once run a single time, return state determined at that execution - return @tcsh_shell if not @tcsh_shell.nil? - - result = @system_wrapper.shell_backticks('echo $version') - - if ((result[:exit_code] == 0) and (result[:output].strip =~ /^tcsh/)) - @tcsh_shell = true - else - @tcsh_shell = false - end - - return @tcsh_shell - end -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/system_wrapper.rb b/test/unit-test/vendor/ceedling/lib/ceedling/system_wrapper.rb deleted file mode 100644 index 2b0f1edda..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/system_wrapper.rb +++ /dev/null @@ -1,80 +0,0 @@ -require 'rbconfig' - -class SystemWrapper - - # static method for use in defaults - def self.windows? - return ((RbConfig::CONFIG['host_os'] =~ /mswin|mingw/) ? true : false) if defined?(RbConfig) - return ((Config::CONFIG['host_os'] =~ /mswin|mingw/) ? true : false) - end - - # class method so as to be mockable for tests - def windows? - return SystemWrapper.windows? - end - - def module_eval(string) - return Object.module_eval("\"" + string + "\"") - end - - def eval(string) - return eval(string) - end - - def search_paths - return ENV['PATH'].split(File::PATH_SEPARATOR) - end - - def cmdline_args - return ARGV - end - - def env_set(name, value) - ENV[name] = value - end - - def env_get(name) - return ENV[name] - end - - def time_now - return Time.now.asctime - end - - def shell_backticks(command, boom = true) - retval = `#{command}`.freeze - $exit_code = ($?.exitstatus).freeze if boom - return { - :output => retval.freeze, - :exit_code => ($?.exitstatus).freeze - } - end - - def shell_system(command, boom = true) - system( command ) - $exit_code = ($?.exitstatus).freeze if boom - return { - :output => "".freeze, - :exit_code => ($?.exitstatus).freeze - } - end - - def add_load_path(path) - $LOAD_PATH.unshift(path) - end - - def require_file(path) - require(path) - end - - def ruby_success - # We are successful if we've never had an exit code that went boom (either because it's empty or it was 0) - return ($exit_code.nil? || ($exit_code == 0)) && ($!.nil? || $!.is_a?(SystemExit) && $!.success?) - end - - def constants_include?(item) - # forcing to strings provides consistency across Ruby versions - return Object.constants.map{|constant| constant.to_s}.include?(item.to_s) - end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/target_loader.rb b/test/unit-test/vendor/ceedling/lib/ceedling/target_loader.rb deleted file mode 100644 index 7fbc09591..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/target_loader.rb +++ /dev/null @@ -1,38 +0,0 @@ -module TargetLoader - class NoTargets < Exception; end - class NoDirectory < Exception; end - class NoDefault < Exception; end - class NoSuchTarget < Exception; end - - class RequestReload < Exception; end - - def self.inspect(config, target_name=nil) - unless config[:targets] - raise NoTargets - end - - targets = config[:targets] - unless targets[:targets_directory] - raise NoDirectory.new("No targets directory specified.") - end - unless targets[:default_target] - raise NoDefault.new("No default target specified.") - end - - target_path = lambda {|name| File.join(targets[:targets_directory], name + ".yml")} - - target = if target_name - target_path.call(target_name) - else - target_path.call(targets[:default_target]) - end - - unless File.exists? target - raise NoSuchTarget.new("No such target: #{target}") - end - - ENV['CEEDLING_MAIN_PROJECT_FILE'] = target - - raise RequestReload - end -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/task_invoker.rb b/test/unit-test/vendor/ceedling/lib/ceedling/task_invoker.rb deleted file mode 100644 index 35f92ae03..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/task_invoker.rb +++ /dev/null @@ -1,122 +0,0 @@ -require 'ceedling/par_map' - -class TaskInvoker - - attr_accessor :first_run - - constructor :dependinator, :rake_utils, :rake_wrapper, :project_config_manager - - def setup - @test_regexs = [/^#{TEST_ROOT_NAME}:/] - @release_regexs = [/^#{RELEASE_ROOT_NAME}(:|$)/] - @first_run = true - end - - def add_test_task_regex(regex) - @test_regexs << regex - end - - def add_release_task_regex(regex) - @release_regexs << regex - end - - def test_invoked? - invoked = false - - @test_regexs.each do |regex| - invoked = true if (@rake_utils.task_invoked?(regex)) - break if invoked - end - - return invoked - end - - def release_invoked? - invoked = false - - @release_regexs.each do |regex| - invoked = true if (@rake_utils.task_invoked?(regex)) - break if invoked - end - - return invoked - end - - def invoked?(regex) - return @rake_utils.task_invoked?(regex) - end - - def reset_rake_task_for_changed_defines(file) - if !(file =~ /#{VENDORS_FILES.map{|ignore| '\b' + ignore.ext(File.extname(file)) + '\b'}.join('|')}$/) - @rake_wrapper[file].clear_actions if @first_run == false && @project_config_manager.test_defines_changed - @rake_wrapper[file].reenable if @first_run == false && @project_config_manager.test_defines_changed - end - end - - def invoke_test_mocks(mocks) - @dependinator.enhance_mock_dependencies( mocks ) - mocks.each { |mock| - reset_rake_task_for_changed_defines( mock ) - @rake_wrapper[mock].invoke - } - end - - def invoke_test_runner(runner) - @dependinator.enhance_runner_dependencies( runner ) - reset_rake_task_for_changed_defines( runner ) - @rake_wrapper[runner].invoke - end - - def invoke_test_shallow_include_lists(files) - @dependinator.enhance_shallow_include_lists_dependencies( files ) - par_map(PROJECT_COMPILE_THREADS, files) do |file| - reset_rake_task_for_changed_defines( file ) - @rake_wrapper[file].invoke - end - end - - def invoke_test_preprocessed_files(files) - @dependinator.enhance_preprocesed_file_dependencies( files ) - par_map(PROJECT_COMPILE_THREADS, files) do |file| - reset_rake_task_for_changed_defines( file ) - @rake_wrapper[file].invoke - end - end - - def invoke_test_dependencies_files(files) - @dependinator.enhance_dependencies_dependencies( files ) - par_map(PROJECT_COMPILE_THREADS, files) do |file| - reset_rake_task_for_changed_defines( file ) - @rake_wrapper[file].invoke - end - end - - def invoke_test_objects(objects) - par_map(PROJECT_COMPILE_THREADS, objects) do |object| - reset_rake_task_for_changed_defines( object ) - @rake_wrapper[object].invoke - end - end - - def invoke_test_executable(file) - @rake_wrapper[file].invoke - end - - def invoke_test_results(result) - @dependinator.enhance_results_dependencies( result ) - @rake_wrapper[result].invoke - end - - def invoke_release_dependencies_files(files) - par_map(PROJECT_COMPILE_THREADS, files) do |file| - @rake_wrapper[file].invoke - end - end - - def invoke_release_objects(objects) - par_map(PROJECT_COMPILE_THREADS, objects) do |object| - @rake_wrapper[object].invoke - end - end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/tasks_base.rake b/test/unit-test/vendor/ceedling/lib/ceedling/tasks_base.rake deleted file mode 100644 index 67a3b503a..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/tasks_base.rake +++ /dev/null @@ -1,115 +0,0 @@ -require 'ceedling/constants' -require 'ceedling/file_path_utils' -require 'ceedling/version' - -desc "Display build environment version info." -task :version do - puts " Ceedling:: #{Ceedling::Version::CEEDLING}" - puts " Unity:: #{Ceedling::Version::UNITY}" - puts " CMock:: #{Ceedling::Version::CMOCK}" - puts " CException:: #{Ceedling::Version::CEXCEPTION}" -end - -desc "Set verbose output (silent:[#{Verbosity::SILENT}] - obnoxious:[#{Verbosity::OBNOXIOUS}])." -task :verbosity, :level do |t, args| - verbosity_level = args.level.to_i - - if (PROJECT_USE_MOCKS) - # don't store verbosity level in setupinator's config hash, use a copy; - # otherwise, the input configuration will change and trigger entire project rebuilds - hash = @ceedling[:setupinator].config_hash[:cmock].clone - hash[:verbosity] = verbosity_level - - @ceedling[:cmock_builder].manufacture( hash ) - end - - @ceedling[:configurator].project_verbosity = verbosity_level - - # control rake's verbosity with new setting - verbose( ((verbosity_level >= Verbosity::OBNOXIOUS) ? true : false) ) -end - -desc "Enable logging" -task :logging do - @ceedling[:configurator].project_logging = true -end - -# non advertised debug task -task :debug do - Rake::Task[:verbosity].invoke(Verbosity::DEBUG) - Rake.application.options.trace = true - @ceedling[:configurator].project_debug = true -end - -# non advertised sanity checking task -task :sanity_checks, :level do |t, args| - check_level = args.level.to_i - @ceedling[:configurator].sanity_checks = check_level -end - -# non advertised catch for calling upgrade in the wrong place -task :upgrade do - puts "WARNING: You're currently IN your project directory. Take a step out and try" - puts "again if you'd like to perform an upgrade." -end - -# list expanded environment variables -if (not ENVIRONMENT.empty?) -desc "List all configured environment variables." -task :environment do - env_list = [] - ENVIRONMENT.each do |env| - env.each_key do |key| - name = key.to_s.upcase - env_list.push(" - #{name}: \"#{env[key]}\"") - end - end - env_list.sort.each do |env_line| - puts env_line - end -end -end - -namespace :options do - - COLLECTION_PROJECT_OPTIONS.each do |option_path| - option = File.basename(option_path, '.yml') - - desc "Merge #{option} project options." - task option.to_sym do - hash = @ceedling[:project_config_manager].merge_options( @ceedling[:setupinator].config_hash, option_path ) - @ceedling[:setupinator].do_setup( hash ) - if @ceedling[:configurator].project_release_build - load(File.join(CEEDLING_LIB, 'ceedling', 'rules_release.rake')) - end - end - end - - # This is to give nice errors when typing options - rule /^options:.*/ do |t, args| - filename = t.to_s.split(':')[-1] + '.yml' - filelist = COLLECTION_PROJECT_OPTIONS.map{|s| File.basename(s) } - @ceedling[:file_finder].find_file_from_list(filename, filelist, :error) - end - - # This will output the fully-merged tools options to their own project.yml file - desc "Export tools options to a new project file" - task :export, :filename do |t, args| - outfile = args.filename || 'tools.yml' - toolcfg = {} - @ceedling[:configurator].project_config_hash.each_pair do |k,v| - toolcfg[k] = v if (k.to_s[0..5] == 'tools_') - end - File.open(outfile,'w') {|f| f << toolcfg.to_yaml({:indentation => 2})} - end -end - - -# do not present task if there's no plugins -if (not PLUGINS_ENABLED.empty?) -desc "Execute plugin result summaries (no build triggering)." -task :summary do - @ceedling[:plugin_manager].summary - puts "\nNOTE: Summaries may be out of date with project sources.\n\n" -end -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/tasks_filesystem.rake b/test/unit-test/vendor/ceedling/lib/ceedling/tasks_filesystem.rake deleted file mode 100644 index 8263955fa..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/tasks_filesystem.rake +++ /dev/null @@ -1,111 +0,0 @@ - -# rather than require 'rake/clean' & try to override, we replicate for finer control -CLEAN = Rake::FileList["**/*~", "**/*.bak"] -CLOBBER = Rake::FileList.new - -CLEAN.clear_exclude.exclude { |fn| fn.pathmap("%f") == 'core' && File.directory?(fn) } - -CLEAN.include(File.join(PROJECT_TEST_BUILD_OUTPUT_PATH, '*')) -CLEAN.include(File.join(PROJECT_TEST_RESULTS_PATH, '*')) -CLEAN.include(File.join(PROJECT_TEST_DEPENDENCIES_PATH, '*')) -CLEAN.include(File.join(PROJECT_BUILD_RELEASE_ROOT, '*.*')) -CLEAN.include(File.join(PROJECT_RELEASE_BUILD_OUTPUT_PATH, '*')) -CLEAN.include(File.join(PROJECT_RELEASE_DEPENDENCIES_PATH, '*')) - -CLOBBER.include(File.join(PROJECT_BUILD_ARTIFACTS_ROOT, '**/*')) -CLOBBER.include(File.join(PROJECT_BUILD_TESTS_ROOT, '**/*')) -CLOBBER.include(File.join(PROJECT_BUILD_RELEASE_ROOT, '**/*')) -CLOBBER.include(File.join(PROJECT_LOG_PATH, '**/*')) -CLOBBER.include(File.join(PROJECT_TEMP_PATH, '**/*')) - -# just in case they're using git, let's make sure we allow them to preserved the build directory if desired. -CLOBBER.exclude(File.join(TESTS_BASE_PATH), '**/.gitkeep') - -# because of cmock config, mock path can optionally exist apart from standard test build paths -CLOBBER.include(File.join(CMOCK_MOCK_PATH, '*')) - -REMOVE_FILE_PROC = Proc.new { |fn| rm_r fn rescue nil } - -# redefine clean so we can override how it advertises itself -desc "Delete all build artifacts and temporary products." -task(:clean) do - # because :clean is a prerequisite for :clobber, intelligently display the progress message - if (not @ceedling[:task_invoker].invoked?(/^clobber$/)) - @ceedling[:streaminator].stdout_puts("\nCleaning build artifacts...\n(For large projects, this task may take a long time to complete)\n\n") - end - begin - CLEAN.each { |fn| REMOVE_FILE_PROC.call(fn) } - rescue - end -end - -# redefine clobber so we can override how it advertises itself -desc "Delete all generated files (and build artifacts)." -task(:clobber => [:clean]) do - @ceedling[:streaminator].stdout_puts("\nClobbering all generated files...\n(For large projects, this task may take a long time to complete)\n\n") - begin - CLOBBER.each { |fn| REMOVE_FILE_PROC.call(fn) } - @ceedling[:rake_wrapper][:directories].invoke - @ceedling[:dependinator].touch_force_rebuild_files - rescue - end -end - -# create a directory task for each of the paths, so we know how to build them -PROJECT_BUILD_PATHS.each { |path| directory(path) } - -# create a single directory task which verifies all the others get built -task :directories => PROJECT_BUILD_PATHS - -# when the force file doesn't exist, it probably means we clobbered or are on a fresh -# install. In either case, stuff was deleted, so assume we want to rebuild it all -file @ceedling[:configurator].project_test_force_rebuild_filepath do - unless File.exists?(@ceedling[:configurator].project_test_force_rebuild_filepath) - @ceedling[:dependinator].touch_force_rebuild_files - end -end - -# list paths discovered at load time -namespace :paths do - standard_paths = ['test','source','include'] - paths = @ceedling[:setupinator].config_hash[:paths].keys.map{|n| n.to_s.downcase} - paths = (paths + standard_paths).uniq - paths.each do |name| - path_list = Object.const_get("COLLECTION_PATHS_#{name.upcase}") - - if (path_list.size != 0) || (standard_paths.include?(name)) - desc "List all collected #{name} paths." - task(name.to_sym) { puts "#{name} paths:"; path_list.sort.each {|path| puts " - #{path}" } } - end - end - -end - - -# list files & file counts discovered at load time -namespace :files do - - categories = [ - ['test', COLLECTION_ALL_TESTS], - ['source', COLLECTION_ALL_SOURCE], - ['include', COLLECTION_ALL_HEADERS], - ['support', COLLECTION_ALL_SUPPORT] - ] - - using_assembly = (defined?(TEST_BUILD_USE_ASSEMBLY) && TEST_BUILD_USE_ASSEMBLY) || - (defined?(RELEASE_BUILD_USE_ASSEMBLY) && RELEASE_BUILD_USE_ASSEMBLY) - categories << ['assembly', COLLECTION_ALL_ASSEMBLY] if using_assembly - - categories.each do |category| - name = category[0] - collection = category[1] - - desc "List all collected #{name} files." - task(name.to_sym) do - puts "#{name} files:" - collection.sort.each { |filepath| puts " - #{filepath}" } - puts "file count: #{collection.size}" - end - end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/tasks_release.rake b/test/unit-test/vendor/ceedling/lib/ceedling/tasks_release.rake deleted file mode 100644 index 9d3a59c53..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/tasks_release.rake +++ /dev/null @@ -1,29 +0,0 @@ -require 'ceedling/constants' -require 'ceedling/file_path_utils' - - -desc "Build release target." -task RELEASE_SYM => [:directories] do - header = "Release build '#{File.basename(PROJECT_RELEASE_BUILD_TARGET)}'" - @ceedling[:streaminator].stdout_puts("\n\n#{header}\n#{'-' * header.length}") - - begin - @ceedling[:plugin_manager].pre_release - - core_objects = [] - extra_objects = @ceedling[:file_path_utils].form_release_build_c_objects_filelist( COLLECTION_RELEASE_ARTIFACT_EXTRA_LINK_OBJECTS ) - - @ceedling[:project_config_manager].process_release_config_change - core_objects.concat( @ceedling[:release_invoker].setup_and_invoke_c_objects( COLLECTION_ALL_SOURCE ) ) - - # if assembler use isn't enabled, COLLECTION_ALL_ASSEMBLY is empty array & nothing happens - core_objects.concat( @ceedling[:release_invoker].setup_and_invoke_asm_objects( COLLECTION_ALL_ASSEMBLY ) ) - - # if we're using libraries, we need to add those to our collection as well - library_objects = (defined? LIBRARIES_RELEASE && !LIBRARIES_RELEASE.empty?) ? LIBRARIES_RELEASE.flatten.compact : [] - file( PROJECT_RELEASE_BUILD_TARGET => (core_objects + extra_objects + library_objects) ) - Rake::Task[PROJECT_RELEASE_BUILD_TARGET].invoke - ensure - @ceedling[:plugin_manager].post_release - end -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/tasks_release_deep_dependencies.rake b/test/unit-test/vendor/ceedling/lib/ceedling/tasks_release_deep_dependencies.rake deleted file mode 100644 index db2be5f34..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/tasks_release_deep_dependencies.rake +++ /dev/null @@ -1,9 +0,0 @@ -require 'ceedling/constants' - -namespace REFRESH_SYM do - - task RELEASE_SYM do - @ceedling[:release_invoker].refresh_c_deep_dependencies - end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/tasks_tests.rake b/test/unit-test/vendor/ceedling/lib/ceedling/tasks_tests.rake deleted file mode 100644 index 5c1006b36..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/tasks_tests.rake +++ /dev/null @@ -1,61 +0,0 @@ -require 'ceedling/constants' - -task :test_deps => [:directories] - -task :test => [:test_deps] do - Rake.application['test:all'].invoke -end - -namespace TEST_SYM do - - desc "Run all unit tests (also just 'test' works)." - task :all => [:test_deps] do - @ceedling[:test_invoker].setup_and_invoke(COLLECTION_ALL_TESTS) - end - - desc "Run single test ([*] real test or source file name, no path)." - task :* do - message = "\nOops! '#{TEST_ROOT_NAME}:*' isn't a real task. " + - "Use a real test or source file name (no path) in place of the wildcard.\n" + - "Example: rake #{TEST_ROOT_NAME}:foo.c\n\n" - - @ceedling[:streaminator].stdout_puts( message ) - end - - desc "Run tests for changed files." - task :delta => [:test_deps] do - @ceedling[:test_invoker].setup_and_invoke(COLLECTION_ALL_TESTS, TEST_SYM, {:force_run => false}) - end - - desc "Just build tests without running." - task :build_only => [:test_deps] do - @ceedling[:test_invoker].setup_and_invoke(COLLECTION_ALL_TESTS, TEST_SYM, {:build_only => true}) - end - - desc "Run tests by matching regular expression pattern." - task :pattern, [:regex] => [:test_deps] do |t, args| - matches = [] - - COLLECTION_ALL_TESTS.each { |test| matches << test if (test =~ /#{args.regex}/) } - - if (matches.size > 0) - @ceedling[:test_invoker].setup_and_invoke(matches, TEST_SYM, {:force_run => false}) - else - @ceedling[:streaminator].stdout_puts("\nFound no tests matching pattern /#{args.regex}/.") - end - end - - desc "Run tests whose test path contains [dir] or [dir] substring." - task :path, [:dir] => [:test_deps] do |t, args| - matches = [] - - COLLECTION_ALL_TESTS.each { |test| matches << test if File.dirname(test).include?(args.dir.gsub(/\\/, '/')) } - - if (matches.size > 0) - @ceedling[:test_invoker].setup_and_invoke(matches, TEST_SYM, {:force_run => false}) - else - @ceedling[:streaminator].stdout_puts("\nFound no tests including the given path or path component.") - end - end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/tasks_tests_deep_dependencies.rake b/test/unit-test/vendor/ceedling/lib/ceedling/tasks_tests_deep_dependencies.rake deleted file mode 100644 index f89940716..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/tasks_tests_deep_dependencies.rake +++ /dev/null @@ -1,9 +0,0 @@ -require 'ceedling/constants' - -namespace REFRESH_SYM do - - task TEST_SYM do - @ceedling[:test_invoker].refresh_deep_dependencies - end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/tasks_vendor.rake b/test/unit-test/vendor/ceedling/lib/ceedling/tasks_vendor.rake deleted file mode 100644 index 63c2ca55b..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/tasks_vendor.rake +++ /dev/null @@ -1,35 +0,0 @@ -require 'ceedling/constants' -require 'ceedling/file_path_utils' - -# create file dependencies to ensure C-based components of vendor tools are recompiled when they are updated with new versions -# forming these explicitly rather than depend on auxiliary dependencies so all scenarios are explicitly covered - -file( @ceedling[:file_path_utils].form_test_build_c_object_filepath( UNITY_C_FILE ) => [ - File.join( UNITY_VENDOR_PATH, UNITY_LIB_PATH, UNITY_C_FILE ), - File.join( UNITY_VENDOR_PATH, UNITY_LIB_PATH, UNITY_H_FILE ), - File.join( UNITY_VENDOR_PATH, UNITY_LIB_PATH, UNITY_INTERNALS_H_FILE ) ] - ) - - -if (PROJECT_USE_MOCKS) -file( @ceedling[:file_path_utils].form_test_build_c_object_filepath( CMOCK_C_FILE ) => [ - File.join( CMOCK_VENDOR_PATH, CMOCK_LIB_PATH, CMOCK_C_FILE ), - File.join( CMOCK_VENDOR_PATH, CMOCK_LIB_PATH, CMOCK_H_FILE ) ] - ) -end - - -if (PROJECT_USE_EXCEPTIONS) -file( @ceedling[:file_path_utils].form_test_build_c_object_filepath( CEXCEPTION_C_FILE ) => [ - File.join( CEXCEPTION_VENDOR_PATH, CEXCEPTION_LIB_PATH, CEXCEPTION_C_FILE ), - File.join( CEXCEPTION_VENDOR_PATH, CEXCEPTION_LIB_PATH, CEXCEPTION_H_FILE ) ] - ) -end - - -if (PROJECT_USE_EXCEPTIONS and PROJECT_RELEASE_BUILD) -file( @ceedling[:file_path_utils].form_release_build_c_object_filepath( CEXCEPTION_C_FILE ) => [ - File.join( CEXCEPTION_VENDOR_PATH, CEXCEPTION_LIB_PATH, CEXCEPTION_C_FILE ), - File.join( CEXCEPTION_VENDOR_PATH, CEXCEPTION_LIB_PATH, CEXCEPTION_H_FILE ) ] - ) -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/test_includes_extractor.rb b/test/unit-test/vendor/ceedling/lib/ceedling/test_includes_extractor.rb deleted file mode 100644 index 393b0be8b..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/test_includes_extractor.rb +++ /dev/null @@ -1,111 +0,0 @@ - -class TestIncludesExtractor - - constructor :configurator, :yaml_wrapper, :file_wrapper - - def setup - @includes = {} - @mocks = {} - end - - - # for includes_list file, slurp up array from yaml file and sort & store includes - def parse_includes_list(includes_list) - gather_and_store_includes( includes_list, @yaml_wrapper.load(includes_list) ) - end - - # open, scan for, and sort & store includes of test file - def parse_test_file(test) - gather_and_store_includes( test, extract_from_file(test) ) - end - - # open, scan for, and sort & store includes of test file - def parse_test_file_source_include(test) - return extract_source_include_from_file(test) - end - - # mocks with no file extension - def lookup_raw_mock_list(test) - file_key = form_file_key(test) - return [] if @mocks[file_key].nil? - return @mocks[file_key] - end - - # includes with file extension - def lookup_includes_list(file) - file_key = form_file_key(file) - return [] if (@includes[file_key]).nil? - return @includes[file_key] - end - - private ################################# - - def form_file_key(filepath) - return File.basename(filepath).to_sym - end - - def extract_from_file(file) - includes = [] - header_extension = @configurator.extension_header - - contents = @file_wrapper.read(file) - - # remove line comments - contents = contents.gsub(/\/\/.*$/, '') - # remove block comments - contents = contents.gsub(/\/\*.*?\*\//m, '') - - contents.split("\n").each do |line| - # look for include statement - scan_results = line.scan(/#include\s+\"\s*(.+#{'\\'+header_extension})\s*\"/) - - includes << scan_results[0][0] if (scan_results.size > 0) - - # look for TEST_FILE statement - scan_results = line.scan(/TEST_FILE\(\s*\"\s*(.+\.\w+)\s*\"\s*\)/) - - includes << scan_results[0][0] if (scan_results.size > 0) - end - - return includes.uniq - end - - def extract_source_include_from_file(file) - source_includes = [] - source_extension = @configurator.extension_source - - contents = @file_wrapper.read(file) - - # remove line comments - contents = contents.gsub(/\/\/.*$/, '') - # remove block comments - contents = contents.gsub(/\/\*.*?\*\//m, '') - - contents.split("\n").each do |line| - # look for include statement - scan_results = line.scan(/#include\s+\"\s*(.+#{'\\'+source_extension})\s*\"/) - - source_includes << scan_results[0][0] if (scan_results.size > 0) - end - - return source_includes.uniq - end - - def gather_and_store_includes(file, includes) - mock_prefix = @configurator.cmock_mock_prefix - header_extension = @configurator.extension_header - file_key = form_file_key(file) - @mocks[file_key] = [] - - # add includes to lookup hash - @includes[file_key] = includes - - includes.each do |include_file| - # check if include is a mock - scan_results = include_file.scan(/(#{mock_prefix}.+)#{'\\'+header_extension}/) - # add mock to lookup hash - @mocks[file_key] << scan_results[0][0] if (scan_results.size > 0) - end - end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/test_invoker.rb b/test/unit-test/vendor/ceedling/lib/ceedling/test_invoker.rb deleted file mode 100644 index ae686a110..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/test_invoker.rb +++ /dev/null @@ -1,165 +0,0 @@ -require 'ceedling/constants' - - -class TestInvoker - - attr_reader :sources, :tests, :mocks - - constructor :configurator, - :test_invoker_helper, - :plugin_manager, - :streaminator, - :preprocessinator, - :task_invoker, - :dependinator, - :project_config_manager, - :build_invoker_utils, - :file_path_utils, - :file_wrapper - - def setup - @sources = [] - @tests = [] - @mocks = [] - end - - - # Convert libraries configuration form YAML configuration - # into a string that can be given to the compiler. - def convert_libraries_to_arguments() - args = ((@configurator.project_config_hash[:libraries_test] || []) + ((defined? LIBRARIES_SYSTEM) ? LIBRARIES_SYSTEM : [])).flatten - if (defined? LIBRARIES_FLAG) - args.map! {|v| LIBRARIES_FLAG.gsub(/\$\{1\}/, v) } - end - return args - end - - def get_library_paths_to_arguments() - paths = (defined? PATHS_LIBRARIES) ? (PATHS_LIBRARIES || []).clone : [] - if (defined? LIBRARIES_PATH_FLAG) - paths.map! {|v| LIBRARIES_PATH_FLAG.gsub(/\$\{1\}/, v) } - end - return paths - end - - def setup_and_invoke(tests, context=TEST_SYM, options={:force_run => true, :build_only => false}) - - @tests = tests - - @project_config_manager.process_test_config_change - - @tests.each do |test| - # announce beginning of test run - header = "Test '#{File.basename(test)}'" - @streaminator.stdout_puts("\n\n#{header}\n#{'-' * header.length}") - - begin - @plugin_manager.pre_test( test ) - test_name ="#{File.basename(test)}".chomp('.c') - def_test_key="defines_#{test_name.downcase}" - - if @configurator.project_config_hash.has_key?(def_test_key.to_sym) || @configurator.defines_use_test_definition - defs_bkp = Array.new(COLLECTION_DEFINES_TEST_AND_VENDOR) - tst_defs_cfg = Array.new(defs_bkp) - if @configurator.project_config_hash.has_key?(def_test_key.to_sym) - tst_defs_cfg.replace(@configurator.project_config_hash[def_test_key.to_sym]) - tst_defs_cfg .concat(COLLECTION_DEFINES_VENDOR) if COLLECTION_DEFINES_VENDOR - end - if @configurator.defines_use_test_definition - tst_defs_cfg << File.basename(test, ".*").strip.upcase.sub(/@.*$/, "") - end - COLLECTION_DEFINES_TEST_AND_VENDOR.replace(tst_defs_cfg) - end - - # redefine the project out path and preprocessor defines - if @configurator.project_config_hash.has_key?(def_test_key.to_sym) - @streaminator.stdout_puts("Updating test definitions for #{test_name}", Verbosity::NORMAL) - orig_path = @configurator.project_test_build_output_path - @configurator.project_config_hash[:project_test_build_output_path] = File.join(@configurator.project_test_build_output_path, test_name) - @file_wrapper.mkdir(@configurator.project_test_build_output_path) - end - - # collect up test fixture pieces & parts - runner = @file_path_utils.form_runner_filepath_from_test( test ) - mock_list = @preprocessinator.preprocess_test_and_invoke_test_mocks( test ) - sources = @test_invoker_helper.extract_sources( test ) - extras = @configurator.collection_test_fixture_extra_link_objects - core = [test] + mock_list + sources - objects = @file_path_utils.form_test_build_objects_filelist( [runner] + core + extras ).uniq - results_pass = @file_path_utils.form_pass_results_filepath( test ) - results_fail = @file_path_utils.form_fail_results_filepath( test ) - - # identify all the objects shall not be linked and then remove them from objects list. - no_link_objects = @file_path_utils.form_test_build_objects_filelist(@preprocessinator.preprocess_shallow_source_includes( test )) - objects = objects.uniq - no_link_objects - - @project_config_manager.process_test_defines_change(@project_config_manager.filter_internal_sources(sources)) - - # clean results files so we have a missing file with which to kick off rake's dependency rules - @test_invoker_helper.clean_results( {:pass => results_pass, :fail => results_fail}, options ) - - # load up auxiliary dependencies so deep changes cause rebuilding appropriately - @test_invoker_helper.process_deep_dependencies( core ) do |dependencies_list| - @dependinator.load_test_object_deep_dependencies( dependencies_list ) - end - - # tell rake to create test runner if needed - @task_invoker.invoke_test_runner( runner ) - - # enhance object file dependencies to capture externalities influencing regeneration - @dependinator.enhance_test_build_object_dependencies( objects ) - - # associate object files with executable - @dependinator.enhance_test_executable_dependencies( test, objects ) - - # build test objects - @task_invoker.invoke_test_objects( objects ) - - # if the option build_only has been specified, build only the executable - # but don't run the test - if (options[:build_only]) - executable = @file_path_utils.form_test_executable_filepath( test ) - @task_invoker.invoke_test_executable( executable ) - else - # 3, 2, 1... launch - @task_invoker.invoke_test_results( results_pass ) - end - rescue => e - @build_invoker_utils.process_exception( e, context ) - ensure - @plugin_manager.post_test( test ) - # restore the project test defines - if @configurator.project_config_hash.has_key?(def_test_key.to_sym) || @configurator.defines_use_test_definition - COLLECTION_DEFINES_TEST_AND_VENDOR.replace(defs_bkp) - if @configurator.project_config_hash.has_key?(def_test_key.to_sym) - @configurator.project_config_hash[:project_test_build_output_path] = orig_path - @streaminator.stdout_puts("Restored defines and build path to standard", Verbosity::NORMAL) - end - end - end - - # store away what's been processed - @mocks.concat( mock_list ) - @sources.concat( sources ) - - @task_invoker.first_run = false - end - - # post-process collected mock list - @mocks.uniq! - - # post-process collected sources list - @sources.uniq! - end - - - def refresh_deep_dependencies - @file_wrapper.rm_f( - @file_wrapper.directory_listing( - File.join( @configurator.project_test_dependencies_path, '*' + @configurator.extension_dependencies ) ) ) - - @test_invoker_helper.process_deep_dependencies( - @configurator.collection_all_tests + @configurator.collection_all_source ) - end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/test_invoker_helper.rb b/test/unit-test/vendor/ceedling/lib/ceedling/test_invoker_helper.rb deleted file mode 100644 index a48edf9f9..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/test_invoker_helper.rb +++ /dev/null @@ -1,32 +0,0 @@ - -class TestInvokerHelper - - constructor :configurator, :task_invoker, :test_includes_extractor, :file_finder, :file_path_utils, :file_wrapper - - def clean_results(results, options) - @file_wrapper.rm_f( results[:fail] ) - @file_wrapper.rm_f( results[:pass] ) if (options[:force_run]) - end - - def process_deep_dependencies(files) - return if (not @configurator.project_use_deep_dependencies) - - dependencies_list = @file_path_utils.form_test_dependencies_filelist( files ).uniq - - if @configurator.project_generate_deep_dependencies - @task_invoker.invoke_test_dependencies_files( dependencies_list ) - end - - yield( dependencies_list ) if block_given? - end - - def extract_sources(test) - sources = [] - includes = @test_includes_extractor.lookup_includes_list(test) - - includes.each { |include| sources << @file_finder.find_compilation_input_file(include, :ignore) } - - return sources.compact - end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/tool_executor.rb b/test/unit-test/vendor/ceedling/lib/ceedling/tool_executor.rb deleted file mode 100644 index 0ab5ddcac..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/tool_executor.rb +++ /dev/null @@ -1,229 +0,0 @@ -require 'ceedling/constants' -require 'benchmark' - -class ShellExecutionException < RuntimeError - attr_reader :shell_result - def initialize(shell_result) - @shell_result = shell_result - end -end - -class ToolExecutor - - constructor :configurator, :tool_executor_helper, :streaminator, :system_wrapper - - def setup - @tool_name = '' - @executable = '' - end - - # build up a command line from yaml provided config - - # @param extra_params is an array of parameters to append to executable - def build_command_line(tool_config, extra_params, *args) - @tool_name = tool_config[:name] - @executable = tool_config[:executable] - - command = {} - - # basic premise is to iterate top to bottom through arguments using '$' as - # a string replacement indicator to expand globals or inline yaml arrays - # into command line arguments via substitution strings - # executable must be quoted if it includes spaces (common on windows) - executable = @tool_executor_helper.osify_path_separators( expandify_element(@executable, *args) ) - executable = "\"#{executable}\"" if executable.include?(' ') - command[:line] = [ - executable, - extra_params.join(' ').strip, - build_arguments(tool_config[:arguments], *args), - ].reject{|s| s.nil? || s.empty?}.join(' ').strip - - command[:options] = { - :stderr_redirect => @tool_executor_helper.stderr_redirection(tool_config, @configurator.project_logging), - :background_exec => tool_config[:background_exec] - } - - return command - end - - - # shell out, execute command, and return response - def exec(command, options={}, args=[]) - options[:boom] = true if (options[:boom].nil?) - options[:stderr_redirect] = StdErrRedirect::NONE if (options[:stderr_redirect].nil?) - options[:background_exec] = BackgroundExec::NONE if (options[:background_exec].nil?) - # build command line - command_line = [ - @tool_executor_helper.background_exec_cmdline_prepend( options ), - command.strip, - args, - @tool_executor_helper.stderr_redirect_cmdline_append( options ), - @tool_executor_helper.background_exec_cmdline_append( options ), - ].flatten.compact.join(' ') - - @streaminator.stderr_puts("Verbose: #{__method__.to_s}(): #{command_line}", Verbosity::DEBUG) - - shell_result = {} - - # depending on background exec option, we shell out differently - time = Benchmark.realtime do - if (options[:background_exec] != BackgroundExec::NONE) - shell_result = @system_wrapper.shell_system( command_line, options[:boom] ) - else - shell_result = @system_wrapper.shell_backticks( command_line, options[:boom] ) - end - end - shell_result[:time] = time - - #scrub the string for illegal output - unless shell_result[:output].nil? - shell_result[:output] = shell_result[:output].scrub if "".respond_to?(:scrub) - shell_result[:output].gsub!(/\033\[\d\dm/,'') - end - - @tool_executor_helper.print_happy_results( command_line, shell_result, options[:boom] ) - @tool_executor_helper.print_error_results( command_line, shell_result, options[:boom] ) - - # go boom if exit code isn't 0 (but in some cases we don't want a non-0 exit code to raise) - raise ShellExecutionException.new(shell_result) if ((shell_result[:exit_code] != 0) and options[:boom]) - - return shell_result - end - - - private ############################# - - - def build_arguments(config, *args) - build_string = '' - - return nil if (config.nil?) - - # iterate through each argument - - # the yaml blob array needs to be flattened so that yaml substitution - # is handled correctly, since it creates a nested array when an anchor is - # dereferenced - config.flatten.each do |element| - argument = '' - - case(element) - # if we find a simple string then look for string replacement operators - # and expand with the parameters in this method's argument list - when String then argument = expandify_element(element, *args) - # if we find a hash, then we grab the key as a substitution string and expand the - # hash's value(s) within that substitution string - when Hash then argument = dehashify_argument_elements(element) - end - - build_string.concat("#{argument} ") if (argument.length > 0) - end - - build_string.strip! - return build_string if (build_string.length > 0) - return nil - end - - - # handle simple text string argument & argument array string replacement operators - def expandify_element(element, *args) - match = // - to_process = nil - args_index = 0 - - # handle ${#} input replacement - if (element =~ TOOL_EXECUTOR_ARGUMENT_REPLACEMENT_PATTERN) - args_index = ($2.to_i - 1) - - if (args.nil? or args[args_index].nil?) - @streaminator.stderr_puts("ERROR: Tool '#{@tool_name}' expected valid argument data to accompany replacement operator #{$1}.", Verbosity::ERRORS) - raise - end - - match = /#{Regexp.escape($1)}/ - to_process = args[args_index] - end - - # simple string argument: replace escaped '\$' and strip - element.sub!(/\\\$/, '$') - element.strip! - - # handle inline ruby execution - if (element =~ RUBY_EVAL_REPLACEMENT_PATTERN) - element.replace(eval($1)) - end - - build_string = '' - - # handle array or anything else passed into method to be expanded in place of replacement operators - case (to_process) - when Array then to_process.each {|value| build_string.concat( "#{element.sub(match, value.to_s)} " ) } if (to_process.size > 0) - else build_string.concat( element.sub(match, to_process.to_s) ) - end - - # handle inline ruby string substitution - if (build_string =~ RUBY_STRING_REPLACEMENT_PATTERN) - build_string.replace(@system_wrapper.module_eval(build_string)) - end - - return build_string.strip - end - - - # handle argument hash: keys are substitution strings, values are data to be expanded within substitution strings - def dehashify_argument_elements(hash) - build_string = '' - elements = [] - - # grab the substitution string (hash key) - substitution = hash.keys[0].to_s - # grab the string(s) to squirt into the substitution string (hash value) - expand = hash[hash.keys[0]] - - if (expand.nil?) - @streaminator.stderr_puts("ERROR: Tool '#{@tool_name}' could not expand nil elements for substitution string '#{substitution}'.", Verbosity::ERRORS) - raise - end - - # array-ify expansion input if only a single string - expansion = ((expand.class == String) ? [expand] : expand) - - expansion.each do |item| - # code eval substitution - if (item =~ RUBY_EVAL_REPLACEMENT_PATTERN) - elements << eval($1) - # string eval substitution - elsif (item =~ RUBY_STRING_REPLACEMENT_PATTERN) - elements << @system_wrapper.module_eval(item) - # global constants - elsif (@system_wrapper.constants_include?(item)) - const = Object.const_get(item) - if (const.nil?) - @streaminator.stderr_puts("ERROR: Tool '#{@tool_name}' found constant '#{item}' to be nil.", Verbosity::ERRORS) - raise - else - elements << const - end - elsif (item.class == Array) - elements << item - elsif (item.class == String) - @streaminator.stderr_puts("ERROR: Tool '#{@tool_name}' cannot expand nonexistent value '#{item}' for substitution string '#{substitution}'.", Verbosity::ERRORS) - raise - else - @streaminator.stderr_puts("ERROR: Tool '#{@tool_name}' cannot expand value having type '#{item.class}' for substitution string '#{substitution}'.", Verbosity::ERRORS) - raise - end - end - - # expand elements (whether string or array) into substitution string & replace escaped '\$' - elements.flatten! - elements.each do |element| - build_string.concat( substitution.sub(/([^\\]*)\$/, "\\1#{element}") ) # don't replace escaped '\$' but allow us to replace just a lonesome '$' - build_string.gsub!(/\\\$/, '$') - build_string.concat(' ') - end - - return build_string.strip - end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/tool_executor_helper.rb b/test/unit-test/vendor/ceedling/lib/ceedling/tool_executor_helper.rb deleted file mode 100644 index de4cafe46..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/tool_executor_helper.rb +++ /dev/null @@ -1,164 +0,0 @@ -require 'ceedling/constants' # for Verbosity enumeration & $stderr redirect enumeration - -## -# Helper functions for the tool executor -class ToolExecutorHelper - - constructor :streaminator, :system_utils, :system_wrapper - - ## - # Returns the stderr redirection based on the config and logging. - # ==== Attributes - # - # * _tool_config_: A hash containing config information. - # * _logging_: A boolean representing if logging is enabled or not. - # - def stderr_redirection(tool_config, logging) - # if there's no logging enabled, return :stderr_redirect unmodified - return tool_config[:stderr_redirect] if (not logging) - - # if there is logging enabled but the redirect is a custom value (not enum), return the custom string - return tool_config[:stderr_redirect] if (tool_config[:stderr_redirect].class == String) - - # if logging is enabled but there's no custom string, return the AUTO enumeration so $stderr goes into the log - return StdErrRedirect::AUTO - end - - - ## - # Returns the background execution prepend based on the config. - # ==== Attributes - # - # * _tool_config_: A hash containing config information. - # - def background_exec_cmdline_prepend(tool_config) - return nil if (tool_config.nil? || tool_config[:background_exec].nil?) - - config_exec = tool_config[:background_exec] - - if ((config_exec == BackgroundExec::AUTO) and (@system_wrapper.windows?)) - return 'start' - end - - if (config_exec == BackgroundExec::WIN) - return 'start' - end - - return nil - end - - - ## - # Modifies an executables path based on platform. - # ==== Attributes - # - # * _executable_: The executable's path. - # - def osify_path_separators(executable) - return executable.gsub(/\//, '\\') if (@system_wrapper.windows?) - return executable - end - - ## - # Returns the stderr redirect append based on the config. - # ==== Attributes - # - # * _tool_config_: A hash containing config information. - # - def stderr_redirect_cmdline_append(tool_config) - return nil if (tool_config.nil? || tool_config[:stderr_redirect].nil?) - - config_redirect = tool_config[:stderr_redirect] - redirect = StdErrRedirect::NONE - - if (config_redirect == StdErrRedirect::AUTO) - if (@system_wrapper.windows?) - redirect = StdErrRedirect::WIN - elsif (@system_utils.tcsh_shell?) - redirect = StdErrRedirect::TCSH - else - redirect = StdErrRedirect::UNIX - end - end - - case redirect - # we may need more complicated processing after some learning with various environments - when StdErrRedirect::NONE then nil - when StdErrRedirect::WIN then '2>&1' - when StdErrRedirect::UNIX then '2>&1' - when StdErrRedirect::TCSH then '|&' - else redirect.to_s - end - end - - ## - # Returns the background execution append based on the config. - # ==== Attributes - # - # * _tool_config_: A hash containing config information. - # - def background_exec_cmdline_append(tool_config) - return nil if (tool_config.nil? || tool_config[:background_exec].nil?) - - config_exec = tool_config[:background_exec] - - # if :auto & windows, then we already prepended 'start' and should append nothing - return nil if ((config_exec == BackgroundExec::AUTO) and (@system_wrapper.windows?)) - - # if :auto & not windows, then we append standard '&' - return '&' if ((config_exec == BackgroundExec::AUTO) and (not @system_wrapper.windows?)) - - # if explicitly Unix, then append '&' - return '&' if (config_exec == BackgroundExec::UNIX) - - # * _command_str_: A hash containing config information. - # all other cases, including :none, :win, & anything unrecognized, append nothing - return nil - end - - ## - # Outputs success results if command succeeded and we have verbosity cranked up. - # ==== Attributes - # - # * _command_str_: The command ran. - # * _shell_results_: The outputs of the command including exit code and - # output. - # * _boom_: A boolean representing if a non zero result is erroneous. - # - def print_happy_results(command_str, shell_result, boom=true) - if ((shell_result[:exit_code] == 0) or ((shell_result[:exit_code] != 0) and not boom)) - output = "> Shell executed command:\n" - output += "'#{command_str}'\n" - output += "> Produced output:\n" if (not shell_result[:output].empty?) - output += "#{shell_result[:output].strip}\n" if (not shell_result[:output].empty?) - output += "> And exited with status: [#{shell_result[:exit_code]}].\n" if (shell_result[:exit_code] != 0) - output += "\n" - - @streaminator.stdout_puts(output, Verbosity::OBNOXIOUS) - end - end - - ## - # Outputs failures results if command failed and we have verbosity set to minimum error level. - # ==== Attributes - # - # * _command_str_: The command ran. - # * _shell_results_: The outputs of the command including exit code and - # output. - # * _boom_: A boolean representing if a non zero result is erroneous. - # - def print_error_results(command_str, shell_result, boom=true) - if ((shell_result[:exit_code] != 0) and boom) - output = "ERROR: Shell command failed.\n" - output += "> Shell executed command:\n" - output += "'#{command_str}'\n" - output += "> Produced output:\n" if (not shell_result[:output].empty?) - output += "#{shell_result[:output].strip}\n" if (not shell_result[:output].empty?) - output += "> And exited with status: [#{shell_result[:exit_code]}].\n" if (shell_result[:exit_code] != nil) - output += "> And then likely crashed.\n" if (shell_result[:exit_code] == nil) - output += "\n" - - @streaminator.stderr_puts(output, Verbosity::ERRORS) - end - end -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/verbosinator.rb b/test/unit-test/vendor/ceedling/lib/ceedling/verbosinator.rb deleted file mode 100644 index e8ed38d78..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/verbosinator.rb +++ /dev/null @@ -1,10 +0,0 @@ - -class Verbosinator - - constructor :configurator - - def should_output?(level) - return (level <= @configurator.project_verbosity) - end - -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/version.rb b/test/unit-test/vendor/ceedling/lib/ceedling/version.rb deleted file mode 100644 index ebda10b78..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/version.rb +++ /dev/null @@ -1,54 +0,0 @@ - -# @private -module Ceedling - module Version - { "UNITY" => File.join("unity","src","unity.h"), - "CMOCK" => File.join("cmock","src","cmock.h"), - "CEXCEPTION" => File.join("c_exception","lib","CException.h") - }.each_pair do |name, path| - # Check for local or global version of vendor directory in order to look up versions - path1 = File.expand_path( File.join("..","..","vendor",path) ) - path2 = File.expand_path( File.join(File.dirname(__FILE__),"..","..","vendor",path) ) - filename = if (File.exists?(path1)) - path1 - elsif (File.exists?(path2)) - path2 - elsif File.exists?(CEEDLING_VENDOR) - path3 = File.expand_path( File.join(CEEDLING_VENDOR,path) ) - if (File.exists?(path3)) - path3 - else - basepath = File.join( CEEDLING_VENDOR, path.split(/\\\//)[0], 'release') - begin - [ @ceedling[:file_wrapper].read( File.join(base_path, 'release', 'version.info') ).strip, - @ceedling[:file_wrapper].read( File.join(base_path, 'release', 'build.info') ).strip ].join('.') - rescue - "#{name}" - end - end - else - module_eval("#{name} = 'unknown'") - continue - end - - # Actually look up the versions - a = [0,0,0] - begin - File.readlines(filename).each do |line| - ["VERSION_MAJOR", "VERSION_MINOR", "VERSION_BUILD"].each_with_index do |field, i| - m = line.match(/#{name}_#{field}\s+(\d+)/) - a[i] = m[1] unless (m.nil?) - end - end - rescue - abort("Can't collect data for vendor component: \"#{filename}\" . \nPlease check your setup.") - end - - # splat it to return the final value - eval("#{name} = '#{a.join(".")}'") - end - - GEM = "0.31.1" - CEEDLING = GEM - end -end diff --git a/test/unit-test/vendor/ceedling/lib/ceedling/yaml_wrapper.rb b/test/unit-test/vendor/ceedling/lib/ceedling/yaml_wrapper.rb deleted file mode 100644 index 00ece5141..000000000 --- a/test/unit-test/vendor/ceedling/lib/ceedling/yaml_wrapper.rb +++ /dev/null @@ -1,17 +0,0 @@ -require 'yaml' -require 'erb' - - -class YamlWrapper - - def load(filepath) - return YAML.load(ERB.new(File.read(filepath)).result) - end - - def dump(filepath, structure) - File.open(filepath, 'w') do |output| - YAML.dump(structure, output) - end - end - -end diff --git a/test/unit-test/vendor/ceedling/plugins/beep/README.md b/test/unit-test/vendor/ceedling/plugins/beep/README.md deleted file mode 100644 index e59d881b3..000000000 --- a/test/unit-test/vendor/ceedling/plugins/beep/README.md +++ /dev/null @@ -1,22 +0,0 @@ -ceedling-beep -============= - -This is a simple plugin that just beeps at the end of a build and/or test sequence. Are you getting too distracted surfing -the internet, chatting with coworkers, or swordfighting while it's building or testing? The friendly beep will let you know -it's time to pay attention again. - -This plugin has very few configuration options. At this time it can beep on completion of a task and/or on an error condition. -For each of these, you can configure the method that it should beep. - -``` -:tools: - :beep_on_done: :bell - :beep_on_error: :bell -``` - -Each of these have the following options: - - - :bell - this option uses the ASCII bell character out stdout - - :speaker_test - this uses the linux speaker-test command if installed - -Very likely, we'll be adding to this list if people find this to be useful. diff --git a/test/unit-test/vendor/ceedling/plugins/beep/lib/beep.rb b/test/unit-test/vendor/ceedling/plugins/beep/lib/beep.rb deleted file mode 100644 index cbc5e3e38..000000000 --- a/test/unit-test/vendor/ceedling/plugins/beep/lib/beep.rb +++ /dev/null @@ -1,39 +0,0 @@ -require 'ceedling/plugin' -require 'ceedling/constants' - -class Beep < Plugin - - attr_reader :config - - def setup - @config = { - :on_done => ((defined? TOOLS_BEEP_ON_DONE) ? TOOLS_BEEP_ON_DONE : :bell ), - :on_error => ((defined? TOOLS_BEEP_ON_ERROR) ? TOOLS_BEEP_ON_ERROR : :bell ), - } - end - - def post_build - beep @config[:on_done] - end - - def post_error - beep @config[:on_error] - end - - private - - def beep(method = :none) - case method - when :bell - if (SystemWrapper.windows?) - puts "echo '\007'" - else - puts "echo -ne '\007'" - end - when :speaker_test - `speaker-test -t sine -f 1000 -l 1` - else - #do nothing with illegal or :none - end - end -end diff --git a/test/unit-test/vendor/ceedling/plugins/bullseye/README.md b/test/unit-test/vendor/ceedling/plugins/bullseye/README.md deleted file mode 100644 index aad449204..000000000 --- a/test/unit-test/vendor/ceedling/plugins/bullseye/README.md +++ /dev/null @@ -1,76 +0,0 @@ -ceedling-bullseye -================= - -# Plugin Overview - -Plugin for integrating Bullseye code coverage tool into Ceedling projects. -This plugin requires a working license to Bullseye code coverage tools. The tools -must be within the path or the path should be added to the environment in the -`project.yml file`. - -## Configuration - -The bullseye plugin supports configuration options via your `project.yml` provided -by Ceedling. The following is a typical configuration example: - -``` -:bullseye: - :auto_license: TRUE -:plugins: - :bullseye_lib_path: [] -:paths: - :bullseye_toolchain_include: [] - -:tools: - :bullseye_instrumentation: - :executable: covc - :arguments: - - '--file $': ENVIRONMENT_COVFILE - - -q - - ${1} - :bullseye_compiler: - :executable: gcc - :arguments: - - -g - - -I"$": COLLECTION_PATHS_TEST_SUPPORT_SOURCE_INCLUDE_VENDOR - - -I"$": COLLECTION_PATHS_BULLSEYE_TOOLCHAIN_INCLUDE - - -D$: COLLECTION_DEFINES_TEST_AND_VENDOR - - -DBULLSEYE_COMPILER - - -c "${1}" - - -o "${2}" - :bullseye_linker: - :executable: gcc - :arguments: - - ${1} - - -o ${2} - - -L$: PLUGINS_BULLSEYE_LIB_PATH - - -lcov - :bullseye_fixture: - :executable: ${1} - :bullseye_report_covsrc: - :executable: covsrc - :arguments: - - '--file $': ENVIRONMENT_COVFILE - - -q - - -w140 - :bullseye_report_covfn: - :executable: covfn - :stderr_redirect: :auto - :arguments: - - '--file $': ENVIRONMENT_COVFILE - - --width 120 - - --no-source - - '"${1}"' - :bullseye_browser: - :executable: CoverageBrowser - :background_exec: :auto - :optional: TRUE - :arguments: - - '"$"': ENVIRONMENT_COVFILE -``` - -## Example Usage - -```sh -ceedling bullseye:all utils:bullseye -``` diff --git a/test/unit-test/vendor/ceedling/plugins/bullseye/assets/template.erb b/test/unit-test/vendor/ceedling/plugins/bullseye/assets/template.erb deleted file mode 100644 index e1ef9874b..000000000 --- a/test/unit-test/vendor/ceedling/plugins/bullseye/assets/template.erb +++ /dev/null @@ -1,14 +0,0 @@ -% function_string = hash[:coverage][:functions].to_s -% branch_string = hash[:coverage][:branches].to_s -% format_string = "%#{[function_string.length, branch_string.length].max}i" -<%=@ceedling[:plugin_reportinator].generate_banner("#{hash[:header]}: CODE COVERAGE SUMMARY")%> -% if (!hash[:coverage][:functions].nil?) -FUNCTIONS: <%=sprintf(format_string, hash[:coverage][:functions])%>% -% else -FUNCTIONS: none -% end -% if (!hash[:coverage][:branches].nil?) -BRANCHES: <%=sprintf(format_string, hash[:coverage][:branches])%>% -% else -BRANCHES: none -% end diff --git a/test/unit-test/vendor/ceedling/plugins/bullseye/bullseye.rake b/test/unit-test/vendor/ceedling/plugins/bullseye/bullseye.rake deleted file mode 100644 index 11073e786..000000000 --- a/test/unit-test/vendor/ceedling/plugins/bullseye/bullseye.rake +++ /dev/null @@ -1,173 +0,0 @@ -directory(BULLSEYE_BUILD_OUTPUT_PATH) -directory(BULLSEYE_RESULTS_PATH) -directory(BULLSEYE_ARTIFACTS_PATH) -directory(BULLSEYE_DEPENDENCIES_PATH) - -CLEAN.include(File.join(BULLSEYE_BUILD_OUTPUT_PATH, '*')) -CLEAN.include(File.join(BULLSEYE_RESULTS_PATH, '*')) -CLEAN.include(File.join(BULLSEYE_DEPENDENCIES_PATH, '*')) - -CLOBBER.include(File.join(BULLSEYE_BUILD_PATH, '**/*')) -PLUGINS_BULLSEYE_LIB_PATH = 'C:\\tools\\BullseyeCoverage\\lib' if not defined?(PLUGINS_BULLSEYE_LIB_PATH) - -rule(/#{BULLSEYE_BUILD_OUTPUT_PATH}\/#{'.+\\'+EXTENSION_OBJECT}$/ => [ - proc do |task_name| - @ceedling[:file_finder].find_compilation_input_file(task_name) - end - ]) do |object| - - if File.basename(object.source) =~ /^(#{PROJECT_TEST_FILE_PREFIX}|#{CMOCK_MOCK_PREFIX}|#{BULLSEYE_IGNORE_SOURCES.join('|')})/i - @ceedling[:generator].generate_object_file( - TOOLS_BULLSEYE_COMPILER, - OPERATION_COMPILE_SYM, - BULLSEYE_SYM, - object.source, - object.name, - @ceedling[:file_path_utils].form_test_build_list_filepath(object.name) - ) - else - @ceedling[BULLSEYE_SYM].generate_coverage_object_file(object.source, object.name) - end - -end - -rule(/#{BULLSEYE_BUILD_OUTPUT_PATH}\/#{'.+\\'+EXTENSION_EXECUTABLE}$/) do |bin_file| - lib_args = @ceedling[:test_invoker].convert_libraries_to_arguments() - lib_paths = @ceedling[:test_invoker].get_library_paths_to_arguments() - @ceedling[:generator].generate_executable_file( - TOOLS_BULLSEYE_LINKER, - BULLSEYE_SYM, - bin_file.prerequisites, - bin_file.name, - @ceedling[:file_path_utils].form_test_build_map_filepath(bin_file.name), - lib_args, - lib_paths - ) -end - -rule(/#{BULLSEYE_RESULTS_PATH}\/#{'.+\\'+EXTENSION_TESTPASS}$/ => [ - proc do |task_name| - @ceedling[:file_path_utils].form_test_executable_filepath(task_name) - end - ]) do |test_result| - @ceedling[:generator].generate_test_results(TOOLS_BULLSEYE_FIXTURE, BULLSEYE_SYM, test_result.source, test_result.name) -end - -rule(/#{BULLSEYE_DEPENDENCIES_PATH}\/#{'.+\\'+EXTENSION_DEPENDENCIES}$/ => [ - proc do |task_name| - @ceedling[:file_finder].find_compilation_input_file(task_name) - end - ]) do |dep| - @ceedling[:generator].generate_dependencies_file( - TOOLS_TEST_DEPENDENCIES_GENERATOR, - BULLSEYE_SYM, - dep.source, - File.join(BULLSEYE_BUILD_OUTPUT_PATH, File.basename(dep.source).ext(EXTENSION_OBJECT) ), - dep.name - ) -end - -task :directories => [BULLSEYE_BUILD_OUTPUT_PATH, BULLSEYE_RESULTS_PATH, BULLSEYE_DEPENDENCIES_PATH, BULLSEYE_ARTIFACTS_PATH] - -namespace BULLSEYE_SYM do - task source_coverage: COLLECTION_ALL_SOURCE.pathmap("#{BULLSEYE_BUILD_OUTPUT_PATH}/%n#{@ceedling[:configurator].extension_object}") - - desc 'Run code coverage for all tests' - task all: [:test_deps] do - @ceedling[:configurator].replace_flattened_config(@ceedling[BULLSEYE_SYM].config) - @ceedling[BULLSEYE_SYM].enableBullseye(true) - @ceedling[:test_invoker].setup_and_invoke(COLLECTION_ALL_TESTS, BULLSEYE_SYM) - @ceedling[:configurator].restore_config - end - - desc "Run single test w/ coverage ([*] real test or source file name, no path)." - task :* do - message = "\nOops! '#{BULLSEYE_ROOT_NAME}:*' isn't a real task. " + - "Use a real test or source file name (no path) in place of the wildcard.\n" + - "Example: rake #{BULLSEYE_ROOT_NAME}:foo.c\n\n" - - @ceedling[:streaminator].stdout_puts( message ) - end - - desc 'Run tests by matching regular expression pattern.' - task :pattern, [:regex] => [:test_deps] do |_t, args| - matches = [] - - COLLECTION_ALL_TESTS.each do |test| - matches << test if test =~ /#{args.regex}/ - end - - if !matches.empty? - @ceedling[:configurator].replace_flattened_config(@ceedling[BULLSEYE_SYM].config) - @ceedling[BULLSEYE_SYM].enableBullseye(true) - @ceedling[:test_invoker].setup_and_invoke(matches, BULLSEYE_SYM, force_run: false) - @ceedling[:configurator].restore_config - else - @ceedling[:streaminator].stdout_puts("\nFound no tests matching pattern /#{args.regex}/.") - end - end - - desc 'Run tests whose test path contains [dir] or [dir] substring.' - task :path, [:dir] => [:test_deps] do |_t, args| - matches = [] - - COLLECTION_ALL_TESTS.each do |test| - matches << test if File.dirname(test).include?(args.dir.tr('\\', '/')) - end - - if !matches.empty? - @ceedling[:configurator].replace_flattened_config(@ceedling[BULLSEYE_SYM].config) - @ceedling[BULLSEYE_SYM].enableBullseye(true) - @ceedling[:test_invoker].setup_and_invoke(matches, BULLSEYE_SYM, force_run: false) - @ceedling[:configurator].restore_config - else - @ceedling[:streaminator].stdout_puts("\nFound no tests including the given path or path component.") - end - end - - desc 'Run code coverage for changed files' - task delta: [:test_deps] do - @ceedling[:configurator].replace_flattened_config(@ceedling[BULLSEYE_SYM].config) - @ceedling[BULLSEYE_SYM].enableBullseye(true) - @ceedling[:test_invoker].setup_and_invoke(COLLECTION_ALL_TESTS, BULLSEYE_SYM, {:force_run => false}) - @ceedling[:configurator].restore_config - end - - # use a rule to increase efficiency for large projects - # bullseye test tasks by regex - rule(/^#{BULLSEYE_TASK_ROOT}\S+$/ => [ - proc do |task_name| - test = task_name.sub(/#{BULLSEYE_TASK_ROOT}/, '') - test = "#{PROJECT_TEST_FILE_PREFIX}#{test}" unless test.start_with?(PROJECT_TEST_FILE_PREFIX) - @ceedling[:file_finder].find_test_from_file_path(test) - end - ]) do |test| - @ceedling[:rake_wrapper][:test_deps].invoke - @ceedling[:configurator].replace_flattened_config(@ceedling[BULLSEYE_SYM].config) - @ceedling[BULLSEYE_SYM].enableBullseye(true) - @ceedling[:test_invoker].setup_and_invoke([test.source], BULLSEYE_SYM) - @ceedling[:configurator].restore_config - end - -end - -if PROJECT_USE_DEEP_DEPENDENCIES -namespace REFRESH_SYM do - task BULLSEYE_SYM do - @ceedling[:configurator].replace_flattened_config(@ceedling[BULLSEYE_SYM].config) - @ceedling[BULLSEYE_SYM].enableBullseye(true) - @ceedling[:test_invoker].refresh_deep_dependencies - @ceedling[:configurator].restore_config - end -end -end - -namespace UTILS_SYM do - - desc "Open Bullseye code coverage browser" - task BULLSEYE_SYM do - command = @ceedling[:tool_executor].build_command_line(TOOLS_BULLSEYE_BROWSER, []) - @ceedling[:tool_executor].exec(command[:line], command[:options]) - end - -end diff --git a/test/unit-test/vendor/ceedling/plugins/bullseye/config/defaults.yml b/test/unit-test/vendor/ceedling/plugins/bullseye/config/defaults.yml deleted file mode 100644 index ed261d8e5..000000000 --- a/test/unit-test/vendor/ceedling/plugins/bullseye/config/defaults.yml +++ /dev/null @@ -1,57 +0,0 @@ ---- - -:bullseye: - :auto_license: TRUE -:plugins: - :bullseye_lib_path: [] -:paths: - :bullseye_toolchain_include: [] - -:tools: - :bullseye_instrumentation: - :executable: covc - :arguments: - - '--file $': ENVIRONMENT_COVFILE - - -q - - ${1} - :bullseye_compiler: - :executable: gcc - :arguments: - - -g - - -I"$": COLLECTION_PATHS_TEST_SUPPORT_SOURCE_INCLUDE_VENDOR - - -I"$": COLLECTION_PATHS_BULLSEYE_TOOLCHAIN_INCLUDE - - -D$: COLLECTION_DEFINES_TEST_AND_VENDOR - - -DBULLSEYE_COMPILER - - -c "${1}" - - -o "${2}" - :bullseye_linker: - :executable: gcc - :arguments: - - ${1} - - -o ${2} - - -L$: PLUGINS_BULLSEYE_LIB_PATH - - -lcov - :bullseye_fixture: - :executable: ${1} - :bullseye_report_covsrc: - :executable: covsrc - :arguments: - - '--file $': ENVIRONMENT_COVFILE - - -q - - -w140 - :bullseye_report_covfn: - :executable: covfn - :stderr_redirect: :auto - :arguments: - - '--file $': ENVIRONMENT_COVFILE - - --width 120 - - --no-source - - '"${1}"' - :bullseye_browser: - :executable: CoverageBrowser - :background_exec: :auto - :optional: TRUE - :arguments: - - '"$"': ENVIRONMENT_COVFILE - -... diff --git a/test/unit-test/vendor/ceedling/plugins/bullseye/lib/bullseye.rb b/test/unit-test/vendor/ceedling/plugins/bullseye/lib/bullseye.rb deleted file mode 100644 index 3e7622006..000000000 --- a/test/unit-test/vendor/ceedling/plugins/bullseye/lib/bullseye.rb +++ /dev/null @@ -1,194 +0,0 @@ -require 'ceedling/plugin' -require 'ceedling/constants' - -BULLSEYE_ROOT_NAME = 'bullseye' -BULLSEYE_TASK_ROOT = BULLSEYE_ROOT_NAME + ':' -BULLSEYE_SYM = BULLSEYE_ROOT_NAME.to_sym - -BULLSEYE_BUILD_PATH = "#{PROJECT_BUILD_ROOT}/#{BULLSEYE_ROOT_NAME}" -BULLSEYE_BUILD_OUTPUT_PATH = "#{BULLSEYE_BUILD_PATH}/out" -BULLSEYE_RESULTS_PATH = "#{BULLSEYE_BUILD_PATH}/results" -BULLSEYE_DEPENDENCIES_PATH = "#{BULLSEYE_BUILD_PATH}/dependencies" -BULLSEYE_ARTIFACTS_PATH = "#{PROJECT_BUILD_ARTIFACTS_ROOT}/#{BULLSEYE_ROOT_NAME}" - -BULLSEYE_IGNORE_SOURCES = ['unity', 'cmock', 'cexception'] - - -class Bullseye < Plugin - - def setup - @result_list = [] - @environment = [ {:covfile => File.join( BULLSEYE_ARTIFACTS_PATH, 'test.cov' )} ] - @plugin_root = File.expand_path(File.join(File.dirname(__FILE__), '..')) - @coverage_template_all = @ceedling[:file_wrapper].read(File.join(@plugin_root, 'assets/template.erb')) - end - - def config - { - :project_test_build_output_path => BULLSEYE_BUILD_OUTPUT_PATH, - :project_test_results_path => BULLSEYE_RESULTS_PATH, - :project_test_dependencies_path => BULLSEYE_DEPENDENCIES_PATH, - :defines_test => DEFINES_TEST + ['CODE_COVERAGE'], - :collection_defines_test_and_vendor => COLLECTION_DEFINES_TEST_AND_VENDOR + ['CODE_COVERAGE'] - } - end - - def generate_coverage_object_file(source, object) - arg_hash = {:tool => TOOLS_BULLSEYE_INSTRUMENTATION, :context => BULLSEYE_SYM, :source => source, :object => object} - @ceedling[:plugin_manager].pre_compile_execute(arg_hash) - - @ceedling[:streaminator].stdout_puts("Compiling #{File.basename(source)} with coverage...") - compile_command = - @ceedling[:tool_executor].build_command_line( - TOOLS_BULLSEYE_COMPILER, - @ceedling[:flaginator].flag_down( OPERATION_COMPILE_SYM, BULLSEYE_SYM, source ), - source, - object, - @ceedling[:file_path_utils].form_test_build_list_filepath( object ) ) - coverage_command = @ceedling[:tool_executor].build_command_line(TOOLS_BULLSEYE_INSTRUMENTATION, [], compile_command[:line] ) - - shell_result = @ceedling[:tool_executor].exec( coverage_command[:line], coverage_command[:options] ) - - arg_hash[:shell_result] = shell_result - @ceedling[:plugin_manager].post_compile_execute(arg_hash) - end - - def post_test_fixture_execute(arg_hash) - result_file = arg_hash[:result_file] - - if ((result_file =~ /#{BULLSEYE_RESULTS_PATH}/) and (not @result_list.include?(result_file))) - @result_list << arg_hash[:result_file] - end - end - - def post_build - return if (not @ceedling[:task_invoker].invoked?(/^#{BULLSEYE_TASK_ROOT}/)) - - # test results - results = @ceedling[:plugin_reportinator].assemble_test_results(@result_list) - hash = { - :header => BULLSEYE_ROOT_NAME.upcase, - :results => results - } - - @ceedling[:plugin_reportinator].run_test_results_report(hash) do - message = '' - message = 'Unit test failures.' if (results[:counts][:failed] > 0) - message - end - - # coverage results - return if (verify_coverage_file() == false) - if (@ceedling[:task_invoker].invoked?(/^#{BULLSEYE_TASK_ROOT}(all|delta)/)) - command = @ceedling[:tool_executor].build_command_line(TOOLS_BULLSEYE_REPORT_COVSRC, []) - shell_result = @ceedling[:tool_executor].exec(command[:line], command[:options]) - report_coverage_results_all(shell_result[:output]) - else - report_per_function_coverage_results(@ceedling[:test_invoker].sources) - end - end - - def summary - return if (verify_coverage_file() == false) - result_list = @ceedling[:file_path_utils].form_pass_results_filelist( BULLSEYE_RESULTS_PATH, COLLECTION_ALL_TESTS ) - - # test results - # get test results for only those tests in our configuration and of those only tests with results on disk - hash = { - :header => BULLSEYE_ROOT_NAME.upcase, - :results => @ceedling[:plugin_reportinator].assemble_test_results(result_list, {:boom => false}) - } - - @ceedling[:plugin_reportinator].run_test_results_report(hash) - - # coverage results - command = @ceedling[:tool_executor].build_command_line(TOOLS_BULLSEYE_REPORT_COVSRC) - shell_result = @ceedling[:tool_executor].exec(command[:line], command[:options]) - report_coverage_results_all(shell_result[:output]) - end - - def enableBullseye(enable) - if BULLSEYE_AUTO_LICENSE - if (enable) - args = ['push', 'on'] - @ceedling[:streaminator].stdout_puts("Enabling Bullseye") - else - args = ['pop'] - @ceedling[:streaminator].stdout_puts("Reverting Bullseye to previous state") - end - - args.each do |arg| - command = @ceedling[:tool_executor].build_command_line(TOOLS_BULLSEYE_BUILD_ENABLE_DISABLE, [], arg) - shell_result = @ceedling[:tool_executor].exec(command[:line], command[:options]) - end - - end - end - - private ################################### - - def report_coverage_results_all(coverage) - results = { - :header => BULLSEYE_ROOT_NAME.upcase, - :coverage => { - :functions => nil, - :branches => nil - } - } - - if (coverage =~ /^Total.*?=\s+([0-9]+)\%/) - results[:coverage][:functions] = $1.to_i - end - - if (coverage =~ /^Total.*=\s+([0-9]+)\%\s*$/) - results[:coverage][:branches] = $1.to_i - end - - @ceedling[:plugin_reportinator].run_report($stdout, @coverage_template_all, results) - end - - def report_per_function_coverage_results(sources) - banner = @ceedling[:plugin_reportinator].generate_banner( "#{BULLSEYE_ROOT_NAME.upcase}: CODE COVERAGE SUMMARY" ) - @ceedling[:streaminator].stdout_puts "\n" + banner - - coverage_sources = sources.clone - coverage_sources.delete_if {|item| item =~ /#{CMOCK_MOCK_PREFIX}.+#{EXTENSION_SOURCE}$/} - coverage_sources.delete_if {|item| item =~ /#{BULLSEYE_IGNORE_SOURCES.join('|')}#{EXTENSION_SOURCE}$/} - - coverage_sources.each do |source| - command = @ceedling[:tool_executor].build_command_line(TOOLS_BULLSEYE_REPORT_COVFN, [], source) - shell_results = @ceedling[:tool_executor].exec(command[:line], command[:options]) - coverage_results = shell_results[:output].deep_clone - coverage_results.sub!(/.*\n.*\n/,'') # Remove the Bullseye tool banner - if (coverage_results =~ /warning cov814: report is empty/) - coverage_results = "WARNING: #{source} contains no coverage data!\n\n" - @ceedling[:streaminator].stdout_puts(coverage_results, Verbosity::COMPLAIN) - else - coverage_results += "\n" - @ceedling[:streaminator].stdout_puts(coverage_results) - end - end - end - - def verify_coverage_file - exist = @ceedling[:file_wrapper].exist?( ENVIRONMENT_COVFILE ) - - if (!exist) - banner = @ceedling[:plugin_reportinator].generate_banner( "#{BULLSEYE_ROOT_NAME.upcase}: CODE COVERAGE SUMMARY" ) - @ceedling[:streaminator].stdout_puts "\n" + banner + "\nNo coverage file.\n\n" - end - - return exist - end - -end - - -# end blocks always executed following rake run -END { - # cache our input configurations to use in comparison upon next execution - if (@ceedling[:task_invoker].invoked?(/^#{BULLSEYE_TASK_ROOT}/)) - @ceedling[:cacheinator].cache_test_config( @ceedling[:setupinator].config_hash ) - @ceedling[BULLSEYE_SYM].enableBullseye(false) - end -} diff --git a/test/unit-test/vendor/ceedling/plugins/colour_report/README.md b/test/unit-test/vendor/ceedling/plugins/colour_report/README.md deleted file mode 100644 index 5f4ff77b1..000000000 --- a/test/unit-test/vendor/ceedling/plugins/colour_report/README.md +++ /dev/null @@ -1,20 +0,0 @@ -ceedling-colour-report -====================== - -## Overview - -The colour_report replaces the normal ceedling "pretty" output with -a colorized variant, in order to make the results easier to read from -a standard command line. This is very useful on developer machines, but -can occasionally cause problems with parsing on CI servers. - -## Setup - -Enable the plugin in your project.yml by adding `colour_report` -to the list of enabled plugins. - -``` YAML -:plugins: - :enabled: - - colour_report -``` diff --git a/test/unit-test/vendor/ceedling/plugins/colour_report/lib/colour_report.rb b/test/unit-test/vendor/ceedling/plugins/colour_report/lib/colour_report.rb deleted file mode 100644 index 1211eab4d..000000000 --- a/test/unit-test/vendor/ceedling/plugins/colour_report/lib/colour_report.rb +++ /dev/null @@ -1,16 +0,0 @@ -require 'ceedling/plugin' -require 'ceedling/streaminator' -require 'ceedling/constants' - -class ColourReport < Plugin - - def setup - @ceedling[:stream_wrapper].stdout_override(&ColourReport.method(:colour_stdout)) - end - - def self.colour_stdout(string) - require 'colour_reporter.rb' - report string - end - -end diff --git a/test/unit-test/vendor/ceedling/plugins/command_hooks/README.md b/test/unit-test/vendor/ceedling/plugins/command_hooks/README.md deleted file mode 100644 index 8ac64afce..000000000 --- a/test/unit-test/vendor/ceedling/plugins/command_hooks/README.md +++ /dev/null @@ -1,53 +0,0 @@ -ceedling-command-hooks -====================== - -Plugin for easily calling command line tools at various points in the build process - -Define any of these sections in :tools: to provide additional hooks to be called on demand: - -``` - :pre_mock_generate - :post_mock_generate - :pre_runner_generate - :post_runner_generate - :pre_compile_execute - :post_compile_execute - :pre_link_execute - :post_link_execute - :pre_test_fixture_execute - :pre_test - :post_test - :pre_release - :post_release - :pre_build - :post_build -``` - -Each of these tools can support an :executable string and an :arguments list, like so: - -``` -:tools: - :post_link_execute: - :executable: objcopy.exe - :arguments: - - ${1} #This is replaced with the executable name - - output.srec - - --strip-all -``` - -You may also specify an array of executables to be called in a particular place, like so: - -``` -:tools: - :post_test: - - :executable: echo - :arguments: "${1} was glorious!" - - :executable: echo - :arguments: - - it kinda made me cry a little. - - you? -``` - -Please note that it varies which arguments are being parsed down to the -hooks. For now see `command_hooks.rb` to figure out which suits you best. -Happy Tweaking! diff --git a/test/unit-test/vendor/ceedling/plugins/command_hooks/lib/command_hooks.rb b/test/unit-test/vendor/ceedling/plugins/command_hooks/lib/command_hooks.rb deleted file mode 100644 index 67e94f935..000000000 --- a/test/unit-test/vendor/ceedling/plugins/command_hooks/lib/command_hooks.rb +++ /dev/null @@ -1,91 +0,0 @@ -require 'ceedling/plugin' -require 'ceedling/constants' -class CommandHooks < Plugin - - attr_reader :config - - def setup - @config = { - :pre_mock_generate => ((defined? TOOLS_PRE_MOCK_GENERATE) ? TOOLS_PRE_MOCK_GENERATE : nil ), - :post_mock_generate => ((defined? TOOLS_POST_MOCK_GENERATE) ? TOOLS_POST_MOCK_GENERATE : nil ), - :pre_runner_generate => ((defined? TOOLS_PRE_RUNNER_GENERATE) ? TOOLS_PRE_RUNNER_GENERATE : nil ), - :post_runner_generate => ((defined? TOOLS_POST_RUNNER_GENERATE) ? TOOLS_POST_RUNNER_GENERATE : nil ), - :pre_compile_execute => ((defined? TOOLS_PRE_COMPILE_EXECUTE) ? TOOLS_PRE_COMPILE_EXECUTE : nil ), - :post_compile_execute => ((defined? TOOLS_POST_COMPILE_EXECUTE) ? TOOLS_POST_COMPILE_EXECUTE : nil ), - :pre_link_execute => ((defined? TOOLS_PRE_LINK_EXECUTE) ? TOOLS_PRE_LINK_EXECUTE : nil ), - :post_link_execute => ((defined? TOOLS_POST_LINK_EXECUTE) ? TOOLS_POST_LINK_EXECUTE : nil ), - :pre_test_fixture_execute => ((defined? TOOLS_PRE_TEST_FIXTURE_EXECUTE) ? TOOLS_PRE_TEST_FIXTURE_EXECUTE : nil ), - :post_test_fixture_execute => ((defined? TOOLS_POST_TEST_FIXTURE_EXECUTE) ? TOOLS_POST_TEST_FIXTURE_EXECUTE : nil ), - :pre_test => ((defined? TOOLS_PRE_TEST) ? TOOLS_PRE_TEST : nil ), - :post_test => ((defined? TOOLS_POST_TEST) ? TOOLS_POST_TEST : nil ), - :pre_release => ((defined? TOOLS_PRE_RELEASE) ? TOOLS_PRE_RELEASE : nil ), - :post_release => ((defined? TOOLS_POST_RELEASE) ? TOOLS_POST_RELEASE : nil ), - :pre_build => ((defined? TOOLS_PRE_BUILD) ? TOOLS_PRE_BUILD : nil ), - :post_build => ((defined? TOOLS_POST_BUILD) ? TOOLS_POST_BUILD : nil ), - :post_error => ((defined? TOOLS_POST_ERROR) ? TOOLS_POST_ERROR : nil ), - } - @plugin_root = File.expand_path(File.join(File.dirname(__FILE__), '..')) - end - - def pre_mock_generate(arg_hash); run_hook(:pre_mock_generate, arg_hash[:header_file] ); end - def post_mock_generate(arg_hash); run_hook(:post_mock_generate, arg_hash[:header_file] ); end - def pre_runner_generate(arg_hash); run_hook(:pre_runner_generate, arg_hash[:source ] ); end - def post_runner_generate(arg_hash); run_hook(:post_runner_generate, arg_hash[:runner_file] ); end - def pre_compile_execute(arg_hash); run_hook(:pre_compile_execute, arg_hash[:source_file] ); end - def post_compile_execute(arg_hash); run_hook(:post_compile_execute, arg_hash[:object_file] ); end - def pre_link_execute(arg_hash); run_hook(:pre_link_execute, arg_hash[:executable] ); end - def post_link_execute(arg_hash); run_hook(:post_link_execute, arg_hash[:executable] ); end - def pre_test_fixture_execute(arg_hash); run_hook(:pre_test_fixture_execute, arg_hash[:executable] ); end - def post_test_fixture_execute(arg_hash); run_hook(:post_test_fixture_execute, arg_hash[:executable] ); end - def pre_test(test); run_hook(:pre_test, test ); end - def post_test(test); run_hook(:post_test, test ); end - def pre_release; run_hook(:pre_release ); end - def post_release; run_hook(:post_release ); end - def pre_build; run_hook(:pre_build ); end - def post_build; run_hook(:post_build ); end - def post_error; run_hook(:post_error ); end - - private - - ## - # Run a hook if its available. - # - # :args: - # - hook: Name of the hook to run - # - name: Name of file (default: "") - # - # :return: - # shell_result. - # - def run_hook_step(hook, name="") - if (hook[:executable]) - # Handle argument replacemant ({$1}), and get commandline - cmd = @ceedling[:tool_executor].build_command_line( hook, [], name ) - shell_result = @ceedling[:tool_executor].exec(cmd[:line], cmd[:options]) - end - end - - ## - # Run a hook if its available. - # - # If __which_hook__ is an array, run each of them sequentially. - # - # :args: - # - which_hook: Name of the hook to run - # - name: Name of file - # - def run_hook(which_hook, name="") - if (@config[which_hook]) - @ceedling[:streaminator].stdout_puts("Running Hook #{which_hook}...", Verbosity::NORMAL) - if (@config[which_hook].is_a? Array) - @config[which_hook].each do |hook| - run_hook_step(hook, name) - end - elsif (@config[which_hook].is_a? Hash) - run_hook_step( @config[which_hook], name ) - else - @ceedling[:streaminator].stdout_puts("Hook #{which_hook} was poorly formed", Verbosity::COMPLAINT) - end - end - end -end diff --git a/test/unit-test/vendor/ceedling/plugins/compile_commands_json/README.md b/test/unit-test/vendor/ceedling/plugins/compile_commands_json/README.md deleted file mode 100644 index 7e3846e56..000000000 --- a/test/unit-test/vendor/ceedling/plugins/compile_commands_json/README.md +++ /dev/null @@ -1,29 +0,0 @@ -compile_commands_json -===================== - -## Overview - -Syntax highlighting and code completion are hard. Historically each editor or IDE has implemented their own and then competed amongst themselves to offer the best experience for developers. Often developers would still to an IDE that felt cumbersome and slow just because it had the best syntax highlighting on the market. If doing it for one language is hard (and it is) imagine doing it for dozens of them. Imagine a full stack developer who has to work with CSS, HTML, JavaScript and some Ruby - they need excellent support in all those languages which just made things even harder. - -In June of 2016, Microsoft with Red Hat and Codenvy got together to create a standard called the Language Server Protocol (LSP). The idea was simple, by standardising on one protocol, all the IDEs and editors out there would only have to support LSP, and not have custom plugins for each language. In turn, the backend code that actually does the highlighting can be written once and used by any IDE that supports LSP. Many editors already support it such as Sublime Text, vim and emacs. This means that if you're using a crufty old IDE or worse, you're using a shiny new editor without code completion, then this could be just the upgrade you're looking for! - -For C and C++ projects, many people use the `clangd` backend. So that it can do things like "go to definition", `clangd` needs to know how to build the project so that it can figure out all the pieces to the puzzle. There are manual tools such as `bear` which can be run with `gcc` or `clang` to extract this information it has a big limitation in that if run with `ceedling release` you won't get any auto completion for Unity and you'll also get error messages reported by your IDE because of what it perceives as missing headers. If you do the same with `ceedling test` now you get Unity but you might miss things that are only seen in the release build. - -This plugin resolves that issue. As it is run by Ceedling, it has access to all the build information it needs to create the perfect `compile_commands.json`. Once enabled, this plugin will generate that file and place it in `./build/artifacts/compile_commands.json`. `clangd` will search your project for this file, but it is easier to symlink it into the root directory (for example `ln -s ./build/artifacts/compile_commands.json`. - -For more information on LSP and to find out if your editor supports it, check out https://langserver.org/ - -## Setup - -Enable the plugin in your project.yml by adding `compile_commands_json` to the list -of enabled plugins. - -``` YAML -:plugins: - :enabled: - - compile_commands_json -``` - -## Configuration - -There is no additional configuration necessary to run this plugin. diff --git a/test/unit-test/vendor/ceedling/plugins/compile_commands_json/lib/compile_commands_json.rb b/test/unit-test/vendor/ceedling/plugins/compile_commands_json/lib/compile_commands_json.rb deleted file mode 100644 index 269cea4de..000000000 --- a/test/unit-test/vendor/ceedling/plugins/compile_commands_json/lib/compile_commands_json.rb +++ /dev/null @@ -1,35 +0,0 @@ -require 'ceedling/plugin' -require 'ceedling/constants' -require 'json' - -class CompileCommandsJson < Plugin - def setup - @fullpath = File.join(PROJECT_BUILD_ARTIFACTS_ROOT, "compile_commands.json") - @database = if (File.exists?(@fullpath)) - JSON.parse( File.read(@fullpath) ) - else - [] - end - end - - def post_compile_execute(arg_hash) - - # Create the new Entry - value = { - "directory" => Dir.pwd, - "command" => arg_hash[:shell_command], - "file" => arg_hash[:source] - } - - # Determine if we're updating an existing file description or adding a new one - index = @database.index {|h| h["file"] == arg_hash[:source]} - if index - @database[index] = value - else - @database << value - end - - # Update the Actual compile_commands.json file - File.open(@fullpath,'w') {|f| f << JSON.pretty_generate(@database)} - end -end diff --git a/test/unit-test/vendor/ceedling/plugins/dependencies/README.md b/test/unit-test/vendor/ceedling/plugins/dependencies/README.md deleted file mode 100644 index 256467dfa..000000000 --- a/test/unit-test/vendor/ceedling/plugins/dependencies/README.md +++ /dev/null @@ -1,254 +0,0 @@ -ceedling-dependencies -===================== - -Plugin for supporting release dependencies. It's rare for an embedded project to -be built completely free of other libraries and modules. Some of these may be -standard internal libraries. Some of these may be 3rd party libraries. In either -case, they become part of the project's ecosystem. - -This plugin is intended to make that relationship easier. It allows you to specify -a source for dependencies. If required, it will automatically grab the appropriate -version of that dependency. - -Most 3rd party libraries have a method of building already in place. While we'd -love to convert the world to a place where everything downloads with a test suite -in Ceedling, that's not likely to happen anytime soon. Until then, this plugin -will allow the developer to specify what calls Ceedling should make to oversee -the build process of those third party utilities. Are they using Make? CMake? A -custom series of scripts that only a mad scientist could possibly understand? No -matter. Ceedling has you covered. Just specify what should be called, and Ceedling -will make it happen whenever it notices that the output artifacts are missing. - -Output artifacts? Sure! Things like static and dynamic libraries, or folders -containing header files that might want to be included by your release project. - -So how does all this magic work? - -First, you need to add the `:dependencies` plugin to your list. Then, we'll add a new -section called :dependencies. There, you can list as many dependencies as you desire. Each -has a series of fields which help Ceedling to understand your needs. Many of them are -optional. If you don't need that feature, just don't include it! In the end, it'll look -something like this: - -``` -:dependencies: - :libraries: - - :name: WolfSSL - :source_path: third_party/wolfssl/source - :build_path: third_party/wolfssl/build - :artifact_path: third_party/wolfssl/install - :fetch: - :method: :zip - :source: \\shared_drive\third_party_libs\wolfssl\wolfssl-4.2.0.zip - :environment: - - CFLAGS+=-DWOLFSSL_DTLS_ALLOW_FUTURE - :build: - - "autoreconf -i" - - "./configure --enable-tls13 --enable-singlethreaded" - - make - - make install - :artifacts: - :static_libraries: - - lib/wolfssl.a - :dynamic_libraries: - - lib/wolfssl.so - :includes: - - include/** -``` - -Let's take a deeper look at each of these features. - -The Starting Dash & Name ------------------------- - -Yes, that opening dash tells the dependencies plugin that the rest of these fields -belong to our first dependency. If we had a second dependency, we'd have another -dash, lined up with the first, and followed by all the fields indented again. - -By convention, we use the `:name` field as the first field for each tool. Ceedling -honestly doesn't care which order the fields are given... but as humans, it makes -it easier for us to see the name of each dependency with starting dash. - -The name field is only used to print progress while we're running Ceedling. You may -call the name of the field whatever you wish. - -Working Folders ---------------- - -The `:source_path` field allows us to specify where the source code for each of our -dependencies is stored. If fetching the dependency from elsewhere, it will be fetched -to this location. All commands to build this dependency will be executed from -this location (override this by specifying a `:build_path`). Finally, the output -artifacts will be referenced to this location (override this by specifying a `:artifact_path`) - -If unspecified, the `:source_path` will be `dependencies\dep_name` where `dep_name` -is the name specified in `:name` above (with special characters removed). It's best, -though, if you specify exactly where you want your dependencies to live. - -If the dependency is directly included in your project (you've specified `:none` as the -`:method` for fetching), then `:source_path` should be where your Ceedling can find the -source for your dependency in you repo. - -All artifacts are relative to the `:artifact_path` (which defaults to be the same as -`:source_path`) - -Fetching Dependencies ---------------------- - -The `:dependencies` plugin supports the ability to automatically fetch your dependencies -for you... using some common methods of fetching source. This section contains only a -couple of fields: - -- `:method` -- This is the method that this dependency is fetched. - - `:none` -- This tells Ceedling that the code is already included in the project. - - `:zip` -- This tells Ceedling that we want to unpack a zip file to our source path. - - `:git` -- This tells Ceedling that we want to clone a git repo to our source path. - - `:svn` -- This tells Ceedling that we want to checkout a subversion repo to our source path. - - `:custom` -- This tells Ceedling that we want to use a custom command or commands to fetch the code. -- `:source` -- This is the path or url to fetch code when using the zip or git method. -- `:tag`/`:branch` -- This is the specific tag or branch that you wish to retrieve (git only. optional). -- `:hash` -- This is the specific SHA1 hash you want to fetch (git only. optional, requires a deep clone). -- `:revision` -- This is the specific revision you want to fetch (svn only. optional). -- `:executable` -- This is a list of commands to execute when using the `:custom` method - - -Environment Variables ---------------------- - -Many build systems support customization through environment variables. By specifying -an array of environment variables, Ceedling will customize the shell environment before -calling the build process. - -Environment variables may be specified in three ways. Let's look at one of each: - -``` - :environment: - - ARCHITECTURE=ARM9 - - CFLAGS+=-DADD_AWESOMENESS - - CFLAGS-=-DWASTE -``` - -In the first example, you see the most straightforward method. The environment variable -`ARCHITECTURE` is set to the value `ARM9`. That's it. Simple. - -The next two options modify an existing symbol. In the first one, we use `+=`, which tells -Ceedling to add the define `ADD_AWESOMENESS` to the environment variable `CFLAGS`. The second -tells Ceedling to remove the define `WASTE` from the same environment variable. - -There are a couple of things to note here. - -First, when adding to a variable, Ceedling has no way of knowing -what delimiter you are expecting. In this example you can see we manually added some whitespace. -If we had been modifying `PATH` instead, we might have had to use a `:` on a unux or `;` on -Windows. - -Second, removing an argument will have no effect on the argument if that argument isn't found -precisely. It's case sensitive and the entire string must match. If symbol doesn't already exist, -it WILL after executing this command... however it will be assigned to nothing. - -Building Dependencies ---------------------- - -The heart of the `:dependencies` plugin is the ability for you, the developer, to specify the -build process for each of your dependencies. You will need to have any required tools installed -before using this feature. - -The steps are specified as an array of strings. Ceedling will execute those steps in the order -specified, moving from step to step unless an error is encountered. By the end of the process, -the artifacts should have been created by your process... otherwise an error will be produced. - -Artifacts ---------- - -These are the outputs of the build process. There are there types of artifacts. Any dependency -may have none or some of these. Calling out these files tells Ceedling that they are important. -Your dependency's build process may produce many other files... but these are the files that -Ceedling understands it needs to act on. - -### `static_libraries` - -Specifying one or more static libraries will tell Ceedling where it should find static libraries -output by your build process. These libraries are automatically added to the list of dependencies -and will be linked with the rest of your code to produce the final release. - -If any of these libraries don't exist, Ceedling will trigger your build process in order for it -to produce them. - -### `dynamic_libraries` - -Specifying one or more dynamic libraries will tell Ceedling where it should find dynamic libraries -output by your build process. These libraries are automatically copied to the same folder as your -final release binary. - -If any of these libraries don't exist, Ceedling will trigger your build process in order for it -to produce them. - -### `includes` - -Often when libraries are built, the same process will output a collection of includes so that -your release code knows how to interact with that library. It's the public API for that library. -By specifying the directories that will contain these includes (don't specify the files themselves, -Ceedling only needs the directories), Ceedling is able to automatically add these to its internal -include list. This allows these files to be used while building your release code, as well we making -them mockable during unit testing. - -### `source` - -It's possible that your external dependency will just produce additional C files as its output. -In this case, Ceedling is able to automatically add these to its internal source list. This allows -these files to be used while building your release code. - -Tasks ------ - -Once configured correctly, the `:dependencies` plugin should integrate seamlessly into your -workflow and you shouldn't have to think about it. In the real world, that doesn't always happen. -Here are a number of tasks that are added or modified by this plugin. - -### `ceedling dependencies:clean` - -This can be issued in order to completely remove the dependency from its source path. On the -next build, it will be refetched and rebuilt from scratch. This can also apply to a particular -dependency. For example, by specifying `dependencies:clean:DepName`. - -### `ceedling dependencies:fetch` - -This can be issued in order to fetch each dependency from its origin. This will have no effect on -dependencies that don't have fetch instructions specified. This can also apply to a particular -dependency. For example, by specifying `dependencies:fetch:DepName`. - -### `ceedling dependencies:make` - -This will force the dependencies to all build. This should happen automatically when a release -has been triggered... but if you're just getting your dependency configured at this moment, you -may want to just use this feature instead. A single dependency can also be built by specifying its -name, like `dependencies:make:MyTunaBoat`. - -### `ceedling dependencies:deploy` - -This will force any dynamic libraries produced by your dependencies to be copied to your release -build directory... just in case you clobbered them. - -### `paths:include` - -Maybe you want to verify that all the include paths are correct. If you query Ceedling with this -request, it will list all the header file paths that it's found, including those produced by -dependencies. - -### `files:include` - -Maybe you want to take that query further and actually get a list of ALL the header files -Ceedling has found, including those belonging to your dependencies. - -Testing -======= - -Hopefully all your dependencies are fully tested... but we can't always depend on that. -In the event that they are tested with Ceedling, you'll probably want to consider using -the `:subprojects` plugin instead of this one. The purpose of this plugin is to pull in -third party code for release... and to provide a mockable interface for Ceedling to use -during its tests of other modules. - -If that's what you're after... you've found the right plugin! - -Happy Testing! diff --git a/test/unit-test/vendor/ceedling/plugins/dependencies/config/defaults.yml b/test/unit-test/vendor/ceedling/plugins/dependencies/config/defaults.yml deleted file mode 100644 index 0415f8ea1..000000000 --- a/test/unit-test/vendor/ceedling/plugins/dependencies/config/defaults.yml +++ /dev/null @@ -1,5 +0,0 @@ ---- -:dependencies: - :libraries: [] - -... diff --git a/test/unit-test/vendor/ceedling/plugins/dependencies/dependencies.rake b/test/unit-test/vendor/ceedling/plugins/dependencies/dependencies.rake deleted file mode 100644 index 4b9409bed..000000000 --- a/test/unit-test/vendor/ceedling/plugins/dependencies/dependencies.rake +++ /dev/null @@ -1,147 +0,0 @@ - -DEPENDENCIES_LIBRARIES.each do |deplib| - - # Look up the name of this dependency library - deplib_name = @ceedling[DEPENDENCIES_SYM].get_name(deplib) - - # Make sure the required working directories exists - # (don't worry about the subdirectories. That's the job of the dep's build tool) - paths = @ceedling[DEPENDENCIES_SYM].get_working_paths(deplib) - paths.each {|path| directory(path) } - task :directories => paths - - all_deps = @ceedling[DEPENDENCIES_SYM].get_static_libraries_for_dependency(deplib) + - @ceedling[DEPENDENCIES_SYM].get_dynamic_libraries_for_dependency(deplib) + - @ceedling[DEPENDENCIES_SYM].get_include_directories_for_dependency(deplib) + - @ceedling[DEPENDENCIES_SYM].get_source_files_for_dependency(deplib) - - # Add a rule for building the actual libraries from dependency list - (@ceedling[DEPENDENCIES_SYM].get_static_libraries_for_dependency(deplib) + - @ceedling[DEPENDENCIES_SYM].get_dynamic_libraries_for_dependency(deplib) - ).each do |libpath| - file libpath do |filetask| - path = filetask.name - - # We double-check that it doesn't already exist, because this process sometimes - # produces multiple files, but they may have already been flagged as invoked - unless (File.exists?(path)) - - # Set Environment Variables, Fetch, and Build - @ceedling[DEPENDENCIES_SYM].set_env_if_required(path) - @ceedling[DEPENDENCIES_SYM].fetch_if_required(path) - @ceedling[DEPENDENCIES_SYM].build_if_required(path) - end - end - end - - # Add a rule for building the source and includes from dependency list - (@ceedling[DEPENDENCIES_SYM].get_include_directories_for_dependency(deplib) + - @ceedling[DEPENDENCIES_SYM].get_source_files_for_dependency(deplib) - ).each do |libpath| - task libpath do |filetask| - path = filetask.name - - unless (File.file?(path) || File.directory?(path)) - - # Set Environment Variables, Fetch, and Build - @ceedling[DEPENDENCIES_SYM].set_env_if_required(path) - @ceedling[DEPENDENCIES_SYM].fetch_if_required(path) - @ceedling[DEPENDENCIES_SYM].build_if_required(path) - end - end - end - - # Give ourselves a way to trigger individual dependencies - namespace DEPENDENCIES_SYM do - namespace :deploy do - # Add task to directly just build this dependency - task(deplib_name => @ceedling[DEPENDENCIES_SYM].get_dynamic_libraries_for_dependency(deplib)) do |t,args| - @ceedling[DEPENDENCIES_SYM].deploy_if_required(deplib_name) - end - end - - namespace :make do - # Add task to directly just build this dependency - task(deplib_name => all_deps) - end - - namespace :clean do - # Add task to directly clobber this dependency - task(deplib_name) do - @ceedling[DEPENDENCIES_SYM].clean_if_required(deplib_name) - end - end - - namespace :fetch do - # Add task to directly clobber this dependency - task(deplib_name) do - @ceedling[DEPENDENCIES_SYM].fetch_if_required(deplib_name) - end - end - end - - # Add source files to our list of things to build during release - source_files = @ceedling[DEPENDENCIES_SYM].get_source_files_for_dependency(deplib) - task PROJECT_RELEASE_BUILD_TARGET => source_files - - # Finally, add the static libraries to our RELEASE build dependency list - static_libs = @ceedling[DEPENDENCIES_SYM].get_static_libraries_for_dependency(deplib) - task RELEASE_SYM => static_libs - - # Add the dynamic libraries to our RELEASE task dependency list so that they will be copied automatically - dynamic_libs = @ceedling[DEPENDENCIES_SYM].get_dynamic_libraries_for_dependency(deplib) - task RELEASE_SYM => dynamic_libs - - # Add the include dirs / files to our list of dependencies for release - headers = @ceedling[DEPENDENCIES_SYM].get_include_directories_for_dependency(deplib) - task RELEASE_SYM => headers - - # Paths to Libraries need to be Added to the Lib Path List - all_libs = static_libs + dynamic_libs - PATHS_LIBRARIES ||= [] - all_libs.each {|lib| PATHS_LIBRARIES << File.dirname(lib) } - PATHS_LIBRARIES.uniq! - PATHS_LIBRARIES.reject!{|s| s.empty?} - - # Libraries Need to be Added to the Library List - LIBRARIES_SYSTEM ||= [] - all_libs.each {|lib| LIBRARIES_SYSTEM << File.basename(lib,'.*').sub(/^lib/,'') } - LIBRARIES_SYSTEM.uniq! - LIBRARIES_SYSTEM.reject!{|s| s.empty?} -end - -# Add any artifact:include or :source folders to our release & test includes paths so linking and mocking work. -@ceedling[DEPENDENCIES_SYM].add_headers_and_sources() - -# Add tasks for building or cleaning ALL dependencies -namespace DEPENDENCIES_SYM do - desc "Deploy missing dependencies." - task :deploy => DEPENDENCIES_LIBRARIES.map{|deplib| "#{DEPENDENCIES_SYM}:deploy:#{@ceedling[DEPENDENCIES_SYM].get_name(deplib)}"} - - desc "Build any missing dependencies." - task :make => DEPENDENCIES_LIBRARIES.map{|deplib| "#{DEPENDENCIES_SYM}:make:#{@ceedling[DEPENDENCIES_SYM].get_name(deplib)}"} - - desc "Clean all dependencies." - task :clean => DEPENDENCIES_LIBRARIES.map{|deplib| "#{DEPENDENCIES_SYM}:clean:#{@ceedling[DEPENDENCIES_SYM].get_name(deplib)}"} - - desc "Fetch all dependencies." - task :fetch => DEPENDENCIES_LIBRARIES.map{|deplib| "#{DEPENDENCIES_SYM}:fetch:#{@ceedling[DEPENDENCIES_SYM].get_name(deplib)}"} -end - -namespace :files do - desc "List all collected dependency libraries." - task :dependencies do - puts "dependency files:" - deps = [] - DEPENDENCIES_LIBRARIES.each do |deplib| - deps << @ceedling[DEPENDENCIES_SYM].get_static_libraries_for_dependency(deplib) - deps << @ceedling[DEPENDENCIES_SYM].get_dynamic_libraries_for_dependency(deplib) - end - deps.flatten! - deps.sort.each {|dep| puts " - #{dep}"} - puts "file count: #{deps.size}" - end -end - -# Make sure that we build dependencies before attempting to tackle any of the unit tests -Rake::Task[:test_deps].enhance ['dependencies:make'] diff --git a/test/unit-test/vendor/ceedling/plugins/dependencies/lib/dependencies.rb b/test/unit-test/vendor/ceedling/plugins/dependencies/lib/dependencies.rb deleted file mode 100644 index fc8ae9968..000000000 --- a/test/unit-test/vendor/ceedling/plugins/dependencies/lib/dependencies.rb +++ /dev/null @@ -1,237 +0,0 @@ -require 'ceedling/plugin' -require 'ceedling/constants' - -DEPENDENCIES_ROOT_NAME = 'dependencies' -DEPENDENCIES_TASK_ROOT = DEPENDENCIES_ROOT_NAME + ':' -DEPENDENCIES_SYM = DEPENDENCIES_ROOT_NAME.to_sym - -class Dependencies < Plugin - - def setup - @plugin_root = File.expand_path(File.join(File.dirname(__FILE__), '..')) - - # Set up a fast way to look up dependencies by name or static lib path - @dependencies = {} - @dynamic_libraries = [] - DEPENDENCIES_LIBRARIES.each do |deplib| - - @dependencies[ deplib[:name] ] = deplib.clone - all_deps = get_static_libraries_for_dependency(deplib) + - get_dynamic_libraries_for_dependency(deplib) + - get_include_directories_for_dependency(deplib) + - get_source_files_for_dependency(deplib) - all_deps.each do |key| - @dependencies[key] = @dependencies[ deplib[:name] ] - end - - @dynamic_libraries += get_dynamic_libraries_for_dependency(deplib) - end - end - - def config - updates = { - :collection_paths_include => COLLECTION_PATHS_INCLUDE, - :collection_all_headers => COLLECTION_ALL_HEADERS, - } - - @ceedling[DEPENDENCIES_SYM].get_include_directories_for_dependency(deplib).each do |incpath| - updates[:collection_paths_include] << incpath - Dir[ File.join(incpath, "*#{EXTENSION_HEADER}") ].each do |f| - updates[:collection_all_headers] << f - end - end - - return updates - end - - def get_name(deplib) - raise "Each dependency must have a name!" if deplib[:name].nil? - return deplib[:name].gsub(/\W*/,'') - end - - def get_source_path(deplib) - return deplib[:source_path] || File.join('dependencies', get_name(deplib)) - end - - def get_build_path(deplib) - return deplib[:build_path] || deplib[:source_path] || File.join('dependencies', get_name(deplib)) - end - - def get_artifact_path(deplib) - return deplib[:artifact_path] || deplib[:source_path] || File.join('dependencies', get_name(deplib)) - end - - def get_working_paths(deplib) - paths = [deplib[:source_path], deplib[:build_path], deplib[:artifact_paths]].compact.uniq - paths = [ File.join('dependencies', get_name(deplib)) ] if (paths.empty?) - return paths - end - - def get_static_libraries_for_dependency(deplib) - (deplib[:artifacts][:static_libraries] || []).map {|path| File.join(get_artifact_path(deplib), path)} - end - - def get_dynamic_libraries_for_dependency(deplib) - (deplib[:artifacts][:dynamic_libraries] || []).map {|path| File.join(get_artifact_path(deplib), path)} - end - - def get_source_files_for_dependency(deplib) - (deplib[:artifacts][:source] || []).map {|path| File.join(get_artifact_path(deplib), path)} - end - - def get_include_directories_for_dependency(deplib) - paths = (deplib[:artifacts][:includes] || []).map {|path| File.join(get_artifact_path(deplib), path)} - @ceedling[:file_system_utils].collect_paths(paths) - end - - def set_env_if_required(lib_path) - blob = @dependencies[lib_path] - raise "Could not find dependency '#{lib_path}'" if blob.nil? - return if (blob[:environment].nil?) - return if (blob[:environment].empty?) - - blob[:environment].each do |e| - m = e.match(/^(\w+)\s*(\+?\-?=)\s*(.*)$/) - unless m.nil? - case m[2] - when "+=" - ENV[m[1]] = (ENV[m[1]] || "") + m[3] - when "-=" - ENV[m[1]] = (ENV[m[1]] || "").gsub(m[3],'') - else - ENV[m[1]] = m[3] - end - end - end - end - - def fetch_if_required(lib_path) - blob = @dependencies[lib_path] - raise "Could not find dependency '#{lib_path}'" if blob.nil? - return if (blob[:fetch].nil?) - return if (blob[:fetch][:method].nil?) - return if (directory(blob[:source_path]) && !Dir.empty?(blob[:source_path])) - - steps = case blob[:fetch][:method] - when :none - return - when :zip - [ "gzip -d #{blob[:fetch][:source]}" ] - when :git - branch = blob[:fetch][:tag] || blob[:fetch][:branch] || '' - branch = ("-b " + branch) unless branch.empty? - unless blob[:fetch][:hash].nil? - # Do a deep clone to ensure the commit we want is available - retval = [ "git clone #{branch} #{blob[:fetch][:source]} ." ] - # Checkout the specified commit - retval << "git checkout #{blob[:fetch][:hash]}" - else - # Do a thin clone - retval = [ "git clone #{branch} --depth 1 #{blob[:fetch][:source]} ." ] - end - when :svn - revision = blob[:fetch][:revision] || '' - revision = ("--revision " + branch) unless branch.empty? - retval = [ "svn checkout #{revision} #{blob[:fetch][:source]} ." ] - retval - when :custom - blob[:fetch][:executable] - else - raise "Unknown fetch method '#{blob[:fetch][:method].to_s}' for dependency '#{blob[:name]}'" - end - - # Perform the actual fetching - @ceedling[:streaminator].stdout_puts("Fetching dependency #{blob[:name]}...", Verbosity::NORMAL) - Dir.chdir(get_source_path(blob)) do - steps.each do |step| - @ceedling[:tool_executor].exec( step ) - end - end - end - - def build_if_required(lib_path) - blob = @dependencies[lib_path] - raise "Could not find dependency '#{lib_path}'" if blob.nil? - - # We don't clean anything unless we know how to fetch a new copy - if (blob[:build].nil? || blob[:build].empty?) - @ceedling[:streaminator].stdout_puts("Nothing to build for dependency #{blob[:name]}", Verbosity::NORMAL) - return - end - - # Perform the build - @ceedling[:streaminator].stdout_puts("Building dependency #{blob[:name]}...", Verbosity::NORMAL) - Dir.chdir(get_build_path(blob)) do - blob[:build].each do |step| - @ceedling[:tool_executor].exec( step ) - end - end - end - - def clean_if_required(lib_path) - blob = @dependencies[lib_path] - raise "Could not find dependency '#{lib_path}'" if blob.nil? - - # We don't clean anything unless we know how to fetch a new copy - if (blob[:fetch].nil? || blob[:fetch][:method].nil? || (blob[:fetch][:method] == :none)) - @ceedling[:streaminator].stdout_puts("Nothing to clean for dependency #{blob[:name]}", Verbosity::NORMAL) - return - end - - # Perform the actual Cleaning - @ceedling[:streaminator].stdout_puts("Cleaning dependency #{blob[:name]}...", Verbosity::NORMAL) - get_working_paths(blob).each do |path| - FileUtils.rm_rf(path) if File.directory?(path) - end - end - - def deploy_if_required(lib_path) - blob = @dependencies[lib_path] - raise "Could not find dependency '#{lib_path}'" if blob.nil? - - # We don't need to deploy anything if there isn't anything to deploy - if (blob[:artifacts].nil? || blob[:artifacts][:dynamic_libraries].nil? || blob[:artifacts][:dynamic_libraries].empty?) - @ceedling[:streaminator].stdout_puts("Nothing to deploy for dependency #{blob[:name]}", Verbosity::NORMAL) - return - end - - # Perform the actual Deploying - @ceedling[:streaminator].stdout_puts("Deploying dependency #{blob[:name]}...", Verbosity::NORMAL) - FileUtils.cp( lib_path, File.dirname(PROJECT_RELEASE_BUILD_TARGET) ) - end - - def add_headers_and_sources() - # Search for header file paths and files to add to our collections - DEPENDENCIES_LIBRARIES.each do |deplib| - get_include_directories_for_dependency(deplib).each do |header| - cfg = @ceedling[:configurator].project_config_hash - cfg[:collection_paths_include] << header - cfg[:collection_paths_source_and_include] << header - cfg[:collection_paths_test_support_source_include] << header - cfg[:collection_paths_test_support_source_include_vendor] << header - cfg[:collection_paths_release_toolchain_include] << header - Dir[ File.join(header, "*#{EXTENSION_HEADER}") ].each do |f| - cfg[:collection_all_headers] << f - end - end - - get_source_files_for_dependency(deplib).each do |source| - cfg = @ceedling[:configurator].project_config_hash - cfg[:collection_paths_source_and_include] << source - cfg[:collection_paths_test_support_source_include] << source - cfg[:collection_paths_test_support_source_include_vendor] << source - cfg[:collection_paths_release_toolchain_include] << source - Dir[ File.join(source, "*#{EXTENSION_SOURCE}") ].each do |f| - cfg[:collection_all_source] << f - end - end - end - - # Make all these updated files findable by Ceedling - @ceedling[:file_finder].prepare_search_sources() - end -end - -# end blocks always executed following rake run -END { -} diff --git a/test/unit-test/vendor/ceedling/plugins/fake_function_framework/README.md b/test/unit-test/vendor/ceedling/plugins/fake_function_framework/README.md deleted file mode 100644 index c99a95196..000000000 --- a/test/unit-test/vendor/ceedling/plugins/fake_function_framework/README.md +++ /dev/null @@ -1,250 +0,0 @@ -# A Fake Function Framework Plug-in for Ceedling - -This is a plug-in for [Ceedling](https://github.com/ThrowTheSwitch/Ceedling) to use the [Fake Function Framework](https://github.com/meekrosoft/fff) for mocking instead of CMock. - -Using fff provides less strict mocking than CMock, and allows for more loosely-coupled tests. -And, when tests fail -- since you get the actual line number of the failure -- it's a lot easier to figure out what went wrong. - -## Installing the plug-in - -To use the plugin you need to 1) get the contents of this repo and 2) configure your project to use it. - -### Get the source - -The easiest way to get the source is to just clone this repo into the Ceedling plugin folder for your existing Ceedling project. -(Don't have a Ceedling project already? [Here are instructions to create one.](http://www.electronvector.com/blog/try-embedded-test-driven-development-right-now-with-ceedling)) -From within `/vendor/ceedling/plugins`, run: - -`git clone https://github.com/ElectronVector/fake_function_framework.git` - -This will create a new folder named `fake_function_framework` in the plugins folder. - -### Enable the plug-in. - -The plug-in is enabled from within your project.yml file. - -In the `:plugins` configuration, add `fake_function_framework` to the list of enabled plugins: - -```yaml -:plugins: - :load_paths: - - vendor/ceedling/plugins - :enabled: - - stdout_pretty_tests_report - - module_generator - - fake_function_framework -``` -*Note that you could put the plugin source in some other location. -In that case you'd need to add a new path the `:load_paths`.* - -## How to use it - -You use fff with Ceedling the same way you used to use CMock. -Modules can still be generated with the default module generator: `rake module:create[my_module]`. -If you want to "mock" `some_module.h` in your tests, just `#include "mock_some_module.h"`. -This creates a fake function for each of the functions defined in `some_module.h`. - -The name of each fake is the original function name with an appended `_fake`. -For example, if we're generating fakes for a stack module with `push` and `pop` functions, we would have the fakes `push_fake` and `pop_fake`. -These fakes are linked into our test executable so that any time our unit under test calls `push` or `pop` our fakes are called instead. - -Each of these fakes is actually a structure containing information about how the function was called, and what it might return. -We can use Unity to inspect these fakes in our tests, and verify the interactions of our units. -There is also a global structure named `fff` which we can use to check the sequence of calls. - -The fakes can also be configured to return particular values, so you can exercise the unit under test however you want. - -The examples below explain how to use fff to test a variety of module interactions. -Each example uses fakes for a "display" module, created from a display.h file with `#include "mock_display.h"`. The `display.h` file must exist and must contain the prototypes for the functions to be faked. - -### Test that a function was called once - -```c -void -test_whenTheDeviceIsReset_thenTheStatusLedIsTurnedOff() -{ - // When - event_deviceReset(); - - // Then - TEST_ASSERT_EQUAL(1, display_turnOffStatusLed_fake.call_count); -} -``` - -### Test that a function was NOT called - -```c -void -test_whenThePowerReadingIsLessThan5_thenTheStatusLedIsNotTurnedOn(void) -{ - // When - event_powerReadingUpdate(4); - - // Then - TEST_ASSERT_EQUAL(0, display_turnOnStatusLed_fake.call_count); -} -``` - -## Test that a single function was called with the correct argument - -```c -void -test_whenTheVolumeKnobIsMaxed_thenVolumeDisplayIsSetTo11(void) -{ - // When - event_volumeKnobMaxed(); - - // Then - TEST_ASSERT_EQUAL(1, display_setVolume_fake.call_count); - TEST_ASSERT_EQUAL(11, display_setVolume_fake.arg0_val); -} -``` - -## Test that calls are made in a particular sequence - -```c -void -test_whenTheModeSelectButtonIsPressed_thenTheDisplayModeIsCycled(void) -{ - // When - event_modeSelectButtonPressed(); - event_modeSelectButtonPressed(); - event_modeSelectButtonPressed(); - - // Then - TEST_ASSERT_EQUAL_PTR((void*)display_setModeToMinimum, fff.call_history[0]); - TEST_ASSERT_EQUAL_PTR((void*)display_setModeToMaximum, fff.call_history[1]); - TEST_ASSERT_EQUAL_PTR((void*)display_setModeToAverage, fff.call_history[2]); -} -``` - -## Fake a return value from a function - -```c -void -test_givenTheDisplayHasAnError_whenTheDeviceIsPoweredOn_thenTheDisplayIsPoweredDown(void) -{ - // Given - display_isError_fake.return_val = true; - - // When - event_devicePoweredOn(); - - // Then - TEST_ASSERT_EQUAL(1, display_powerDown_fake.call_count); -} -``` - -## Fake a function with a value returned by reference - -```c -void -test_givenTheUserHasTypedSleep_whenItIsTimeToCheckTheKeyboard_theDisplayIsPoweredDown(void) -{ - // Given - char mockedEntry[] = "sleep"; - void return_mock_value(char * entry, int length) - { - if (length > strlen(mockedEntry)) - { - strncpy(entry, mockedEntry, length); - } - } - display_getKeyboardEntry_fake.custom_fake = return_mock_value; - - // When - event_keyboardCheckTimerExpired(); - - // Then - TEST_ASSERT_EQUAL(1, display_powerDown_fake.call_count); -} -``` - -## Fake a function with a function pointer parameter - -``` -void -test_givenNewDataIsAvailable_whenTheDisplayHasUpdated_thenTheEventIsComplete(void) -{ - // A mock function for capturing the callback handler function pointer. - void(*registeredCallback)(void) = 0; - void mock_display_updateData(int data, void(*callback)(void)) - { - //Save the callback function. - registeredCallback = callback; - } - display_updateData_fake.custom_fake = mock_display_updateData; - - // Given - event_newDataAvailable(10); - - // When - if (registeredCallback != 0) - { - registeredCallback(); - } - - // Then - TEST_ASSERT_EQUAL(true, eventProcessor_isLastEventComplete()); -} -``` - -## Helper macros - -For convenience, there are also some helper macros that create new Unity-style asserts: - -- `TEST_ASSERT_CALLED(function)`: Asserts that a function was called once. -- `TEST_ASSERT_NOT_CALLED(function)`: Asserts that a function was never called. -- `TEST_ASSERT_CALLED_TIMES(times, function)`: Asserts that a function was called a particular number of times. -- `TEST_ASSERT_CALLED_IN_ORDER(order, function)`: Asserts that a function was called in a particular order. - -Here's how you might use one of these instead of simply checking the call_count value: - -```c -void -test_whenTheDeviceIsReset_thenTheStatusLedIsTurnedOff() -{ - // When - event_deviceReset(); - - // Then - // This how to directly use fff... - TEST_ASSERT_EQUAL(1, display_turnOffStatusLed_fake.call_count); - // ...and this is how to use the helper macro. - TEST_ASSERT_CALLED(display_turnOffStatusLed); -} -``` - -## Test setup - -All of the fake functions, and any fff global state are all reset automatically between each test. - -## CMock configuration - -Use still use some of the CMock configuration options for setting things like the mock prefix, and for including additional header files in the mock files. - -```yaml -:cmock: - :mock_prefix: mock_ - :includes: - - - :includes_h_pre_orig_header: - - - :includes_h_post_orig_header: - - - :includes_c_pre_header: - - - :includes_c_post_header: -``` - -## Running the tests - -There are unit and integration tests for the plug-in itself. -These are run with the default `rake` task. -The integration test runs the tests for the example project in examples/fff_example. -For the integration tests to succeed, this repository must be placed in a Ceedling tree in the plugins folder. - -## More examples - -There is an example project in examples/fff_example. -It shows how to use the plug-in with some full-size examples. diff --git a/test/unit-test/vendor/ceedling/plugins/fake_function_framework/Rakefile b/test/unit-test/vendor/ceedling/plugins/fake_function_framework/Rakefile deleted file mode 100644 index 2fd9f859f..000000000 --- a/test/unit-test/vendor/ceedling/plugins/fake_function_framework/Rakefile +++ /dev/null @@ -1,19 +0,0 @@ -require 'rake' -require 'rspec/core/rake_task' - -desc "Run all rspecs" -RSpec::Core::RakeTask.new(:spec) do |t| - t.pattern = Dir.glob('spec/**/*_spec.rb') - t.rspec_opts = '--format documentation' - # t.rspec_opts << ' more options' -end - -desc "Run integration test on example" -task :integration_test do - chdir("./examples/fff_example") do - sh "rake clobber" - sh "rake test:all" - end -end - -task :default => [:spec, :integration_test] diff --git a/test/unit-test/vendor/ceedling/plugins/fake_function_framework/examples/fff_example/project.yml b/test/unit-test/vendor/ceedling/plugins/fake_function_framework/examples/fff_example/project.yml deleted file mode 100644 index 3253acf69..000000000 --- a/test/unit-test/vendor/ceedling/plugins/fake_function_framework/examples/fff_example/project.yml +++ /dev/null @@ -1,71 +0,0 @@ ---- - -# Notes: -# Sample project C code is not presently written to produce a release artifact. -# As such, release build options are disabled. -# This sample, therefore, only demonstrates running a collection of unit tests. - -:project: - :use_exceptions: FALSE - :use_test_preprocessor: TRUE - :use_auxiliary_dependencies: TRUE - :build_root: build -# :release_build: TRUE - :test_file_prefix: test_ - -#:release_build: -# :output: MyApp.out -# :use_assembly: FALSE - -:environment: - -:extension: - :executable: .out - -:paths: - :test: - - +:test/** - :source: - - src/** - :support: - -:defines: - # in order to add common defines: - # 1) remove the trailing [] from the :common: section - # 2) add entries to the :common: section (e.g. :test: has TEST defined) - :common: &common_defines [] - :test: - - *common_defines - - TEST - :test_preprocess: - - *common_defines - - TEST - -:cmock: - :mock_prefix: mock_ - :when_no_prototypes: :warn - :enforce_strict_ordering: TRUE - :plugins: - - :ignore - - :callback - :treat_as: - uint8: HEX8 - uint16: HEX16 - uint32: UINT32 - int8: INT8 - bool: UINT8 - -#:tools: -# Ceedling defaults to using gcc for compiling, linking, etc. -# As [:tools] is blank, gcc will be used (so long as it's in your system path) -# See documentation to configure a given toolchain for use - -:plugins: - :load_paths: - # This change from the default is for running Ceedling out of another folder. - - ../../../../plugins - :enabled: - - stdout_pretty_tests_report - - module_generator - - fake_function_framework -... diff --git a/test/unit-test/vendor/ceedling/plugins/fake_function_framework/examples/fff_example/rakefile.rb b/test/unit-test/vendor/ceedling/plugins/fake_function_framework/examples/fff_example/rakefile.rb deleted file mode 100644 index e484d5fb7..000000000 --- a/test/unit-test/vendor/ceedling/plugins/fake_function_framework/examples/fff_example/rakefile.rb +++ /dev/null @@ -1,7 +0,0 @@ -# This change from the default is for running Ceedling out of another folder. -PROJECT_CEEDLING_ROOT = "../../../.." -load "#{PROJECT_CEEDLING_ROOT}/lib/ceedling.rb" - -Ceedling.load_project - -task :default => %w[ test:all release ] diff --git a/test/unit-test/vendor/ceedling/plugins/fake_function_framework/examples/fff_example/src/bar.c b/test/unit-test/vendor/ceedling/plugins/fake_function_framework/examples/fff_example/src/bar.c deleted file mode 100644 index 6a403234f..000000000 --- a/test/unit-test/vendor/ceedling/plugins/fake_function_framework/examples/fff_example/src/bar.c +++ /dev/null @@ -1 +0,0 @@ -#include "bar.h" diff --git a/test/unit-test/vendor/ceedling/plugins/fake_function_framework/examples/fff_example/src/bar.h b/test/unit-test/vendor/ceedling/plugins/fake_function_framework/examples/fff_example/src/bar.h deleted file mode 100644 index febc58653..000000000 --- a/test/unit-test/vendor/ceedling/plugins/fake_function_framework/examples/fff_example/src/bar.h +++ /dev/null @@ -1,14 +0,0 @@ -#ifndef bar_H -#define bar_H - -#include "custom_types.h" - -void bar_turn_on(void); -void bar_print_message(const char * message); -void bar_print_message_formatted(const char * format, ...); -void bar_numbers(int one, int two, char three); -void bar_const_test(const char * a, char * const b, const int c); -custom_t bar_needs_custom_type(void); -const char * bar_return_const_ptr(int one); - -#endif // bar_H diff --git a/test/unit-test/vendor/ceedling/plugins/fake_function_framework/examples/fff_example/src/custom_types.h b/test/unit-test/vendor/ceedling/plugins/fake_function_framework/examples/fff_example/src/custom_types.h deleted file mode 100644 index b426b32ca..000000000 --- a/test/unit-test/vendor/ceedling/plugins/fake_function_framework/examples/fff_example/src/custom_types.h +++ /dev/null @@ -1,6 +0,0 @@ -#ifndef custom_types_H -#define custom_types_H - -typedef int custom_t; - -#endif diff --git a/test/unit-test/vendor/ceedling/plugins/fake_function_framework/examples/fff_example/src/display.c b/test/unit-test/vendor/ceedling/plugins/fake_function_framework/examples/fff_example/src/display.c deleted file mode 100644 index 797d46878..000000000 --- a/test/unit-test/vendor/ceedling/plugins/fake_function_framework/examples/fff_example/src/display.c +++ /dev/null @@ -1,7 +0,0 @@ -#include -#include "display.h" - -void display_turnOffStatusLed(void) -{ - printf("Display: Status LED off"); -} diff --git a/test/unit-test/vendor/ceedling/plugins/fake_function_framework/examples/fff_example/src/display.h b/test/unit-test/vendor/ceedling/plugins/fake_function_framework/examples/fff_example/src/display.h deleted file mode 100644 index def29960c..000000000 --- a/test/unit-test/vendor/ceedling/plugins/fake_function_framework/examples/fff_example/src/display.h +++ /dev/null @@ -1,16 +0,0 @@ -#include - -void display_turnOffStatusLed(void); -void display_turnOnStatusLed(void); -void display_setVolume(int level); -void display_setModeToMinimum(void); -void display_setModeToMaximum(void); -void display_setModeToAverage(void); -bool display_isError(void); -void display_powerDown(void); -void display_updateData(int data, void(*updateCompleteCallback)(void)); - -/* - The entry is returned (up to `length` bytes) in the provided `entry` buffer. -*/ -void display_getKeyboardEntry(char * entry, int length); diff --git a/test/unit-test/vendor/ceedling/plugins/fake_function_framework/examples/fff_example/src/event_processor.c b/test/unit-test/vendor/ceedling/plugins/fake_function_framework/examples/fff_example/src/event_processor.c deleted file mode 100644 index 916a92360..000000000 --- a/test/unit-test/vendor/ceedling/plugins/fake_function_framework/examples/fff_example/src/event_processor.c +++ /dev/null @@ -1,93 +0,0 @@ -/* - This module implements some business logic to test. - - Signal events by calling the functions on the module. -*/ - -#include -#include -#include "event_processor.h" -#include "display.h" - -void event_deviceReset(void) -{ - //printf ("Device reset\n"); - display_turnOffStatusLed(); -} - -void event_volumeKnobMaxed(void) -{ - display_setVolume(11); -} - -void event_powerReadingUpdate(int powerReading) -{ - if (powerReading >= 5) - { - display_turnOnStatusLed(); - } -} - -void event_modeSelectButtonPressed(void) -{ - static int mode = 0; - - if (mode == 0) - { - display_setModeToMinimum(); - mode++; - } - else if (mode == 1) - { - display_setModeToMaximum(); - mode++; - } - else if (mode == 2) - { - display_setModeToAverage(); - mode++; - } - else - { - mode = 0; - } -} - -void event_devicePoweredOn(void) -{ - if (display_isError()) - { - display_powerDown(); - } -} - -void event_keyboardCheckTimerExpired(void) -{ - char userEntry[100]; - - display_getKeyboardEntry(userEntry, 100); - - if (strcmp(userEntry, "sleep") == 0) - { - display_powerDown(); - } -} - -static bool event_lastComplete = false; - -/* Function called when the display update is complete. */ -static void displayUpdateComplete(void) -{ - event_lastComplete = true; -} - -void event_newDataAvailable(int data) -{ - event_lastComplete = false; - display_updateData(data, displayUpdateComplete); -} - -bool eventProcessor_isLastEventComplete(void) -{ - return event_lastComplete; -} diff --git a/test/unit-test/vendor/ceedling/plugins/fake_function_framework/examples/fff_example/src/event_processor.h b/test/unit-test/vendor/ceedling/plugins/fake_function_framework/examples/fff_example/src/event_processor.h deleted file mode 100644 index a79e68c56..000000000 --- a/test/unit-test/vendor/ceedling/plugins/fake_function_framework/examples/fff_example/src/event_processor.h +++ /dev/null @@ -1,11 +0,0 @@ -#include - -void event_deviceReset(void); -void event_volumeKnobMaxed(void); -void event_powerReadingUpdate(int powerReading); -void event_modeSelectButtonPressed(void); -void event_devicePoweredOn(void); -void event_keyboardCheckTimerExpired(void); -void event_newDataAvailable(int data); - -bool eventProcessor_isLastEventComplete(void); diff --git a/test/unit-test/vendor/ceedling/plugins/fake_function_framework/examples/fff_example/src/foo.c b/test/unit-test/vendor/ceedling/plugins/fake_function_framework/examples/fff_example/src/foo.c deleted file mode 100644 index c05b1154e..000000000 --- a/test/unit-test/vendor/ceedling/plugins/fake_function_framework/examples/fff_example/src/foo.c +++ /dev/null @@ -1,16 +0,0 @@ -#include "foo.h" -#include "bar.h" -#include "subfolder/zzz.h" - -void foo_turn_on(void) { - bar_turn_on(); - zzz_sleep(1, "sleepy"); -} - -void foo_print_message(const char * message) { - bar_print_message(message); -} - -void foo_print_special_message(void) { - bar_print_message_formatted("The numbers are %d, %d and %d", 1, 2, 3); -} diff --git a/test/unit-test/vendor/ceedling/plugins/fake_function_framework/examples/fff_example/src/foo.h b/test/unit-test/vendor/ceedling/plugins/fake_function_framework/examples/fff_example/src/foo.h deleted file mode 100644 index 3fea69940..000000000 --- a/test/unit-test/vendor/ceedling/plugins/fake_function_framework/examples/fff_example/src/foo.h +++ /dev/null @@ -1,8 +0,0 @@ -#ifndef foo_H -#define foo_H - -void foo_turn_on(void); -void foo_print_message(const char * message); -void foo_print_special_message(void); - -#endif // foo_H diff --git a/test/unit-test/vendor/ceedling/plugins/fake_function_framework/examples/fff_example/src/subfolder/zzz.c b/test/unit-test/vendor/ceedling/plugins/fake_function_framework/examples/fff_example/src/subfolder/zzz.c deleted file mode 100644 index 85f370e12..000000000 --- a/test/unit-test/vendor/ceedling/plugins/fake_function_framework/examples/fff_example/src/subfolder/zzz.c +++ /dev/null @@ -1 +0,0 @@ -#include "zzz.h" diff --git a/test/unit-test/vendor/ceedling/plugins/fake_function_framework/examples/fff_example/src/subfolder/zzz.h b/test/unit-test/vendor/ceedling/plugins/fake_function_framework/examples/fff_example/src/subfolder/zzz.h deleted file mode 100644 index 32c52940d..000000000 --- a/test/unit-test/vendor/ceedling/plugins/fake_function_framework/examples/fff_example/src/subfolder/zzz.h +++ /dev/null @@ -1,6 +0,0 @@ -#ifndef zzz_H -#define zzz_H - -int zzz_sleep(int time, char * name); - -#endif // zzz_H diff --git a/test/unit-test/vendor/ceedling/plugins/fake_function_framework/examples/fff_example/test/test_event_processor.c b/test/unit-test/vendor/ceedling/plugins/fake_function_framework/examples/fff_example/test/test_event_processor.c deleted file mode 100644 index ea59cd3e6..000000000 --- a/test/unit-test/vendor/ceedling/plugins/fake_function_framework/examples/fff_example/test/test_event_processor.c +++ /dev/null @@ -1,155 +0,0 @@ -#include "unity.h" -#include "event_processor.h" -#include "mock_display.h" -#include - -void setUp (void) -{ -} - -void tearDown (void) -{ -} -/* - Test that a single function was called. -*/ -void -test_whenTheDeviceIsReset_thenTheStatusLedIsTurnedOff() -{ - // When - event_deviceReset(); - - // Then - TEST_ASSERT_EQUAL(1, display_turnOffStatusLed_fake.call_count); - // or use the helper macro... - TEST_ASSERT_CALLED(display_turnOffStatusLed); -} - -/* - Test that a single function is NOT called. -*/ -void -test_whenThePowerReadingIsLessThan5_thenTheStatusLedIsNotTurnedOn(void) -{ - // When - event_powerReadingUpdate(4); - - // Then - TEST_ASSERT_EQUAL(0, display_turnOnStatusLed_fake.call_count); - // or use the helper macro... - TEST_ASSERT_NOT_CALLED(display_turnOffStatusLed); -} - -/* - Test that a single function was called with the correct argument. -*/ -void -test_whenTheVolumeKnobIsMaxed_thenVolumeDisplayIsSetTo11(void) -{ - // When - event_volumeKnobMaxed(); - - // Then - TEST_ASSERT_EQUAL(1, display_setVolume_fake.call_count); - // or use the helper macro... - TEST_ASSERT_CALLED(display_setVolume); - TEST_ASSERT_EQUAL(11, display_setVolume_fake.arg0_val); -} - -/* - Test a sequence of calls. -*/ - -void -test_whenTheModeSelectButtonIsPressed_thenTheDisplayModeIsCycled(void) -{ - // When - event_modeSelectButtonPressed(); - event_modeSelectButtonPressed(); - event_modeSelectButtonPressed(); - - // Then - TEST_ASSERT_EQUAL_PTR((void *)display_setModeToMinimum, fff.call_history[0]); - TEST_ASSERT_EQUAL_PTR((void *)display_setModeToMaximum, fff.call_history[1]); - TEST_ASSERT_EQUAL_PTR((void *)display_setModeToAverage, fff.call_history[2]); - // or use the helper macros... - TEST_ASSERT_CALLED_IN_ORDER(0, display_setModeToMinimum); - TEST_ASSERT_CALLED_IN_ORDER(1, display_setModeToMaximum); - TEST_ASSERT_CALLED_IN_ORDER(2, display_setModeToAverage); -} - -/* - Mock a return value from a function. -*/ -void -test_givenTheDisplayHasAnError_whenTheDeviceIsPoweredOn_thenTheDisplayIsPoweredDown(void) -{ - // Given - display_isError_fake.return_val = true; - - // When - event_devicePoweredOn(); - - // Then - TEST_ASSERT_EQUAL(1, display_powerDown_fake.call_count); - // or use the helper macro... - TEST_ASSERT_CALLED(display_powerDown); -} - -/* - Mock a sequence of calls with return values. -*/ - -/* - Mocking a function with a value returned by reference. -*/ -void -test_givenTheUserHasTypedSleep_whenItIsTimeToCheckTheKeyboard_theDisplayIsPoweredDown(void) -{ - // Given - char mockedEntry[] = "sleep"; - void return_mock_value(char * entry, int length) - { - if (length > strlen(mockedEntry)) - { - strncpy(entry, mockedEntry, length); - } - } - display_getKeyboardEntry_fake.custom_fake = return_mock_value; - - // When - event_keyboardCheckTimerExpired(); - - // Then - TEST_ASSERT_EQUAL(1, display_powerDown_fake.call_count); - // or use the helper macro... - TEST_ASSERT_CALLED(display_powerDown); -} - -/* - Mock a function with a function pointer parameter. -*/ -void -test_givenNewDataIsAvailable_whenTheDisplayHasUpdated_thenTheEventIsComplete(void) -{ - // A mock function for capturing the callback handler function pointer. - void(*registeredCallback)(void) = 0; - void mock_display_updateData(int data, void(*callback)(void)) - { - //Save the callback function. - registeredCallback = callback; - } - display_updateData_fake.custom_fake = mock_display_updateData; - - // Given - event_newDataAvailable(10); - - // When - if (registeredCallback != 0) - { - registeredCallback(); - } - - // Then - TEST_ASSERT_EQUAL(true, eventProcessor_isLastEventComplete()); -} diff --git a/test/unit-test/vendor/ceedling/plugins/fake_function_framework/examples/fff_example/test/test_foo.c b/test/unit-test/vendor/ceedling/plugins/fake_function_framework/examples/fff_example/test/test_foo.c deleted file mode 100644 index 12dd61a10..000000000 --- a/test/unit-test/vendor/ceedling/plugins/fake_function_framework/examples/fff_example/test/test_foo.c +++ /dev/null @@ -1,47 +0,0 @@ -#include "unity.h" -#include "foo.h" -#include "mock_bar.h" -#include "mock_zzz.h" - -void setUp(void) -{ -} - -void tearDown(void) -{ -} - -void test_foo(void) -{ - //When - foo_turn_on(); - - //Then - TEST_ASSERT_EQUAL(1, bar_turn_on_fake.call_count); - TEST_ASSERT_EQUAL(1, zzz_sleep_fake.call_count); - TEST_ASSERT_EQUAL_STRING("sleepy", zzz_sleep_fake.arg1_val); -} - -void test_foo_again(void) -{ - //When - foo_turn_on(); - - //Then - TEST_ASSERT_EQUAL(1, bar_turn_on_fake.call_count); -} - -void test_foo_mock_with_const(void) -{ - foo_print_message("123"); - - TEST_ASSERT_EQUAL(1, bar_print_message_fake.call_count); - TEST_ASSERT_EQUAL_STRING("123", bar_print_message_fake.arg0_val); -} - -void test_foo_mock_with_variable_args(void) -{ - foo_print_special_message(); - TEST_ASSERT_EQUAL(1, bar_print_message_formatted_fake.call_count); - TEST_ASSERT_EQUAL_STRING("The numbers are %d, %d and %d", bar_print_message_formatted_fake.arg0_val); -} diff --git a/test/unit-test/vendor/ceedling/plugins/fake_function_framework/lib/fake_function_framework.rb b/test/unit-test/vendor/ceedling/plugins/fake_function_framework/lib/fake_function_framework.rb deleted file mode 100644 index 8fbb1e9b5..000000000 --- a/test/unit-test/vendor/ceedling/plugins/fake_function_framework/lib/fake_function_framework.rb +++ /dev/null @@ -1,87 +0,0 @@ -require 'ceedling/plugin' -require 'fff_mock_generator' - -class FakeFunctionFramework < Plugin - - # Set up Ceedling to use this plugin. - def setup - # Get the location of this plugin. - @plugin_root = File.expand_path(File.join(File.dirname(__FILE__), '..')) - puts "Using fake function framework (fff)..." - - # Switch out the cmock_builder with our own. - @ceedling[:cmock_builder].cmock = FffMockGeneratorForCMock.new(@ceedling[:setupinator].config_hash[:cmock]) - - # Add the path to fff.h to the include paths. - COLLECTION_PATHS_TEST_SUPPORT_SOURCE_INCLUDE_VENDOR << "#{@plugin_root}/vendor/fff" - COLLECTION_PATHS_TEST_SUPPORT_SOURCE_INCLUDE_VENDOR << "#{@plugin_root}/src" - end - - def post_runner_generate(arg_hash) - # After the test runner file has been created, append the FFF globals - # definition to the end of the test runner. These globals will be shared by - # all mocks linked into the test. - File.open(arg_hash[:runner_file], 'a') do |f| - f.puts - f.puts "//=======Definitions of FFF variables=====" - f.puts %{#include "fff.h"} - f.puts "DEFINE_FFF_GLOBALS;" - end - end - -end # class FakeFunctionFramework - -class FffMockGeneratorForCMock - - def initialize(options=nil) - @cm_config = CMockConfig.new(options) - @cm_parser = CMockHeaderParser.new(@cm_config) - @silent = (@cm_config.verbosity < 2) - - # These are the additional files to include in the mock files. - @includes_h_pre_orig_header = (@cm_config.includes || @cm_config.includes_h_pre_orig_header || []).map{|h| h =~ /" - output.puts %{#include "fff.h"} - output.puts %{#include "#{mock_name}.h"} - end - - def self.write_function_definitions(parsed_header, output) - write_function_macros("DEFINE", parsed_header, output) - end - - def self.write_control_function_definitions(mock_name, parsed_header, output) - output.puts "void #{mock_name}_Init(void)" - output.puts "{" - # In the init function, reset the FFF globals. These are used for things - # like the call history. - output.puts " FFF_RESET_HISTORY();" - - # Also, reset all of the fakes. - if parsed_header[:functions] - parsed_header[:functions].each do |function| - output.puts " RESET_FAKE(#{function[:name]})" - end - end - output.puts "}" - output.puts "void #{mock_name}_Verify(void)" - output.puts "{" - output.puts "}" - output.puts "void #{mock_name}_Destroy(void)" - output.puts "{" - output.puts "}" - end - -# Shared functions. - - def self.write_extra_includes(includes, output) - if includes - includes.each {|inc| output.puts "#include #{inc}\n"} - end - end - - def self.write_function_macros(macro_type, parsed_header, output) - return unless parsed_header.key?(:functions) - parsed_header[:functions].each do |function| - name = function[:name] - return_type = function[:return][:type] - if function.has_key? :modifier - # Prepend any modifier. If there isn't one, trim any leading whitespace. - return_type = "#{function[:modifier]} #{return_type}".lstrip - end - arg_count = function[:args].size - - # Check for variable arguments. - var_arg_suffix = "" - if function[:var_arg] - # If there are are variable arguments, then we need to add this argument - # to the count, update the suffix that will get added to the macro. - arg_count += 1 - var_arg_suffix = "_VARARG" - end - - # Generate the correct macro. - if return_type == 'void' - output.print "#{macro_type}_FAKE_VOID_FUNC#{arg_count}#{var_arg_suffix}(#{name}" - else - output.print "#{macro_type}_FAKE_VALUE_FUNC#{arg_count}#{var_arg_suffix}(#{return_type}, #{name}" - end - - # Append each argument type. - function[:args].each do |arg| - output.print ", " - if arg[:const?] - output.print "const " - end - output.print "#{arg[:type]}" - end - - # If this argument list ends with a variable argument, add it here at the end. - if function[:var_arg] - output.print ", ..." - end - - # Close the declaration. - output.puts ");" - end - end - -end diff --git a/test/unit-test/vendor/ceedling/plugins/fake_function_framework/spec/fff_mock_header_generator_spec.rb b/test/unit-test/vendor/ceedling/plugins/fake_function_framework/spec/fff_mock_header_generator_spec.rb deleted file mode 100644 index 09d317551..000000000 --- a/test/unit-test/vendor/ceedling/plugins/fake_function_framework/spec/fff_mock_header_generator_spec.rb +++ /dev/null @@ -1,304 +0,0 @@ -require 'stringio' -require 'fff_mock_generator.rb' -require 'header_generator.rb' - -# Test the contents of the .h file created for the mock. -describe "FffMockGenerator.create_mock_header" do - - context "when there is nothing to mock," do - let(:mock_header) { - parsed_header = {} - FffMockGenerator.create_mock_header("display", "mock_display", parsed_header) - } - it "then the generated header file starts with an opening include guard" do - expect(mock_header).to start_with( - "#ifndef mock_display_H\n" + - "#define mock_display_H") - end - it "then the generated file ends with a closing include guard" do - expect(mock_header).to end_with( - "#endif // mock_display_H\n") - end - it "then the generated file includes the fff header" do - expect(mock_header).to include( - %{#include "fff.h"\n}) - end - it "then the generated file has a prototype for the init function" do - expect(mock_header).to include( - "void mock_display_Init(void);") - end - it "then the generated file has a prototype for the verify function" do - expect(mock_header).to include( - "void mock_display_Verify(void);") - end - it "then the generated file has a prototype for the destroy function" do - expect(mock_header).to include( - "void mock_display_Destroy(void);") - end - end - - context "when there is a function with no args and a void return," do - let(:mock_header) { - parsed_header = create_cmock_style_parsed_header( - [{:name => 'display_turnOffStatusLed', :return_type => 'void'}]) - FffMockGenerator.create_mock_header("display", "mock_display", parsed_header) - } - it "then the generated header file starts with an opening include guard" do - expect(mock_header).to start_with( - "#ifndef mock_display_H\n" + - "#define mock_display_H") - end - it "then the generated header file contains a fake function declaration" do - expect(mock_header).to include( - "DECLARE_FAKE_VOID_FUNC0(display_turnOffStatusLed);" - ) - end - it "then the generated file ends with a closing include guard" do - expect(mock_header).to end_with( - "#endif // mock_display_H\n") - end - end - - context "when there is a function with no args and a bool return," do - let(:mock_header) { - parsed_header = create_cmock_style_parsed_header( - [{:name => 'display_isError', :return_type => 'bool'}]) - FffMockGenerator.create_mock_header("display", "mock_display", parsed_header) - } - it "then the generated file contains the fake function declaration" do - expect(mock_header).to include( - "DECLARE_FAKE_VALUE_FUNC0(bool, display_isError);" - ) - end - end - - context "when there is a function with no args and an int return," do - let(:mock_header) { - parsed_header = create_cmock_style_parsed_header( - [{:name => 'display_isError', :return_type => 'int'}]) - FffMockGenerator.create_mock_header("display", "mock_display", parsed_header) - } - it "then the generated file contains the fake function declaration" do - expect(mock_header).to include( - "DECLARE_FAKE_VALUE_FUNC0(int, display_isError);" - ) - end - end - - context "when there is a function with args and a void return," do - let(:mock_header) { - parsed_header = create_cmock_style_parsed_header( - [{:name => 'display_setVolume', :return_type => 'void', :args => ['int']}]) - FffMockGenerator.create_mock_header("display", "mock_display", parsed_header) - } - it "then the generated file contains the fake function declaration" do - expect(mock_header).to include( - "DECLARE_FAKE_VOID_FUNC1(display_setVolume, int);" - ) - end - end - - context "when there is a function with args and a value return," do - let(:mock_header) { - parsed_header = create_cmock_style_parsed_header( - [{:name => 'a_function', :return_type => 'int', :args => ['char *']}]) - FffMockGenerator.create_mock_header("display", "mock_display", parsed_header) - } - it "then the generated file contains the fake function declaration" do - expect(mock_header).to include( - "FAKE_VALUE_FUNC1(int, a_function, char *);" - ) - end - end - - context "when there is a function with many args and a void return," do - let(:mock_header) { - parsed_header = create_cmock_style_parsed_header( - [{:name => 'a_function', :return_type => 'void', - :args => ['int', 'char *', 'int', 'int', 'bool', 'applesauce']}]) - FffMockGenerator.create_mock_header("display", "mock_display", parsed_header) - } - it "then the generated file contains the fake function declaration" do - expect(mock_header).to include( - "DECLARE_FAKE_VOID_FUNC6(a_function, int, char *, int, int, bool, applesauce);" - ) - end - end - - context "when there are multiple functions," do - let(:mock_header) { - parsed_header = create_cmock_style_parsed_header( - [ {:name => 'a_function', :return_type => 'int', :args => ['char *']}, - {:name => 'another_function', :return_type => 'void'}, - {:name => 'three', :return_type => 'bool', :args => ['float', 'int']} - ]) - FffMockGenerator.create_mock_header("display", "mock_display", parsed_header) - } - it "then the generated file contains the first fake function declaration" do - expect(mock_header).to include( - "DECLARE_FAKE_VALUE_FUNC1(int, a_function, char *);" - ) - end - it "then the generated file contains the second fake function declaration" do - expect(mock_header).to include( - "DECLARE_FAKE_VOID_FUNC0(another_function);" - ) - end - it "then the generated file contains the third fake function declaration" do - expect(mock_header).to include( - "DECLARE_FAKE_VALUE_FUNC2(bool, three, float, int);" - ) - end - end - - context "when there is a typedef," do - let(:mock_header) { - parsed_header = create_cmock_style_parsed_header( - nil, ["typedef void (*displayCompleteCallback) (void);"]) - FffMockGenerator.create_mock_header("display", "mock_display", parsed_header) - } - it "then the generated file contains the typedef" do - expect(mock_header).to include( - "typedef void (*displayCompleteCallback) (void);" - ) - end - end - - context "when there is a void function with variable arguments" do - let(:mock_header){ - parsed_header = {} - parsed_header[:functions] = [{ - :name => "function_with_var_args", - :return => {:type => "void"}, - :var_arg => "...", - :args => [{:type => 'char *'}] - }] - FffMockGenerator.create_mock_header("display", "mock_display", parsed_header) - } - it "then the generated file contains the vararg declaration" do - expect(mock_header).to include( - "DECLARE_FAKE_VOID_FUNC2_VARARG(function_with_var_args, char *, ...)" - ) - end - end - - context "when there is a function with a return value and variable arguments" do - let(:mock_header){ - parsed_header = {} - parsed_header[:functions] = [{ - :name => "function_with_var_args", - :return => {:type => "int"}, - :var_arg => "...", - :args => [{:type => 'char *'}] - }] - FffMockGenerator.create_mock_header("display", "mock_display", parsed_header) - } - it "then the generated file contains the vararg declaration" do - expect(mock_header).to include( - "DECLARE_FAKE_VALUE_FUNC2_VARARG(int, function_with_var_args, char *, ...)" - ) - end - end - - context "when there is a void function with variable arguments and " + - "additional arguments" do - let(:mock_header){ - parsed_header = {} - parsed_header[:functions] = [{ - :name => "function_with_var_args", - :return => {:type => "void"}, - :var_arg => "...", - :args => [{:type => 'char *'}, {:type => 'int'}] - }] - FffMockGenerator.create_mock_header("display", "mock_display", parsed_header) - } - it "then the generated file contains the vararg declaration" do - expect(mock_header).to include( - "DECLARE_FAKE_VOID_FUNC3_VARARG(function_with_var_args, char *, int, ...)" - ) - end - end - - context "when there is a function with a pointer to a const value" do - let(:mock_header){ - parsed_header = {} - parsed_header[:functions] = [{ - :name => "const_test_function", - :return => {:type => "void"}, - :args => [{:type => "char *", :name => "a", :ptr? => false, :const? => true}, - {:type => "char *", :name => "b", :ptr? => false, :const? => false}] - }] - FffMockGenerator.create_mock_header("display", "mock_display", parsed_header) - } - it "then the generated file contains the correct const argument in the declaration" do - expect(mock_header).to include( - "DECLARE_FAKE_VOID_FUNC2(const_test_function, const char *, char *)" - ) - end - end - - context "when there is a function that returns a const pointer" do - let(:mock_header){ - parsed_header = {} - parsed_header[:functions] = [{ - :name => "return_const_pointer_test_function", - :modifier => "const", - :return => {:type => "char *" }, - :args => [{:type => "int", :name => "a"}] - }] - FffMockGenerator.create_mock_header("display", "mock_display", parsed_header) - } - it "then the generated file contains the correct const return value in the declaration" do - expect(mock_header).to include( - "DECLARE_FAKE_VALUE_FUNC1(const char *, return_const_pointer_test_function, int)" - ) - end - end - - context "when there is a function that returns a const int" do - let(:mock_header){ - parsed_header = {} - parsed_header[:functions] = [{ - :name => "return_const_int_test_function", - :modifier => "const", - :return => {:type => "int" }, - :args => [] - }] - FffMockGenerator.create_mock_header("display", "mock_display", parsed_header) - } - it "then the generated file contains the correct const return value in the declaration" do - expect(mock_header).to include( - "DECLARE_FAKE_VALUE_FUNC0(const int, return_const_int_test_function)" - ) - end - end - - context "when there are pre-includes" do - let(:mock_header) { - parsed_header = {} - FffMockGenerator.create_mock_header("display", "mock_display", parsed_header, - [%{"another_header.h"}]) - } - it "then they are included before the other files" do - expect(mock_header).to include( - %{#include "another_header.h"\n} + - %{#include "fff.h"} - ) - end - end - - context "when there are post-includes" do - let(:mock_header) { - parsed_header = {} - FffMockGenerator.create_mock_header("display", "mock_display", parsed_header, - nil, [%{"another_header.h"}]) - } - it "then they are included after the other files" do - expect(mock_header).to include( - %{#include "display.h"\n} + - %{#include "another_header.h"\n} - ) - end - end - -end diff --git a/test/unit-test/vendor/ceedling/plugins/fake_function_framework/spec/fff_mock_source_generator_spec.rb b/test/unit-test/vendor/ceedling/plugins/fake_function_framework/spec/fff_mock_source_generator_spec.rb deleted file mode 100644 index 7b7f04f58..000000000 --- a/test/unit-test/vendor/ceedling/plugins/fake_function_framework/spec/fff_mock_source_generator_spec.rb +++ /dev/null @@ -1,149 +0,0 @@ -require 'stringio' -require 'fff_mock_generator.rb' - -# Test the contents of the .c file created for the mock. -describe "FffMockGenerator.create_mock_source" do - - context "when there is nothing to mock," do - let(:mock_source) { - parsed_header = {} - FffMockGenerator.create_mock_source("mock_my_module", parsed_header) - } - it "then the generated file includes the fff header" do - expect(mock_source).to include( - # fff.h also requires including string.h - %{#include \n} + - %{#include "fff.h"} - ) - end - it "then the generated file includes the mock header" do - expect(mock_source).to include( - %{#include "mock_my_module.h"\n} - ) - end - it "then the generated file defines the init function" do - expect(mock_source).to include( - "void mock_my_module_Init(void)\n" + - "{\n" + - " FFF_RESET_HISTORY();\n" + - "}" - ) - end - it "then the generated file defines the verify function" do - expect(mock_source).to include( - "void mock_my_module_Verify(void)\n" + - "{\n" + - "}" - ) - end - it "then the generated file defines the destroy function" do - expect(mock_source).to include( - "void mock_my_module_Destroy(void)\n" + - "{\n" + - "}" - ) - end - end - - context "when there are multiple functions," do - let(:mock_source) { - parsed_header = create_cmock_style_parsed_header( - [ {:name => 'a_function', :return_type => 'int', :args => ['char *']}, - {:name => 'another_function', :return_type => 'void'}, - {:name => 'three', :return_type => 'bool', :args => ['float', 'int']} - ]) - FffMockGenerator.create_mock_source("mock_display", parsed_header) - } - it "then the generated file contains the first fake function definition" do - expect(mock_source).to include( - "DEFINE_FAKE_VALUE_FUNC1(int, a_function, char *);" - ) - end - it "then the generated file contains the second fake function definition" do - expect(mock_source).to include( - "DEFINE_FAKE_VOID_FUNC0(another_function);" - ) - end - it "then the generated file contains the third fake function definition" do - expect(mock_source).to include( - "DEFINE_FAKE_VALUE_FUNC2(bool, three, float, int);" - ) - end - it "then the init function resets all of the fakes" do - expect(mock_source).to include( - "void mock_display_Init(void)\n" + - "{\n" + - " FFF_RESET_HISTORY();\n" + - " RESET_FAKE(a_function)\n" + - " RESET_FAKE(another_function)\n" + - " RESET_FAKE(three)\n" + - "}" - ) - end - end - - context "when there is a void function with variable arguments and " + - "additional arguments" do - let(:mock_source){ - parsed_header = {} - parsed_header[:functions] = [{ - :name => "function_with_var_args", - :return => {:type => "void"}, - :var_arg => "...", - :args => [{:type => 'char *'}, {:type => 'int'}] - }] - FffMockGenerator.create_mock_source("mock_display", parsed_header) - } - it "then the generated file contains the vararg definition" do - expect(mock_source).to include( - "DEFINE_FAKE_VOID_FUNC3_VARARG(function_with_var_args, char *, int, ...)" - ) - end - end - - context "when there is a function with a pointer to a const value" do - let(:mock_source){ - parsed_header = {} - parsed_header[:functions] = [{ - :name => "const_test_function", - :return => {:type => "void"}, - :args => [{:type => "char *", :name => "a", :ptr? => false, :const? => true}, - {:type => "char *", :name => "b", :ptr? => false, :const? => false}] - }] - FffMockGenerator.create_mock_source("mock_display", parsed_header) - } - it "then the generated file contains the correct const argument in the declaration" do - expect(mock_source).to include( - "DEFINE_FAKE_VOID_FUNC2(const_test_function, const char *, char *)" - ) - end - end - - context "when there are pre-includes" do - let(:mock_source) { - parsed_source = {} - FffMockGenerator.create_mock_source("mock_display", parsed_source, - [%{"another_header.h"}]) - } - it "then they are included before the other files" do - expect(mock_source).to include( - %{#include "another_header.h"\n} + - %{#include } - ) - end - end - - context "when there are post-includes" do - let(:mock_source) { - parsed_source = {} - FffMockGenerator.create_mock_source("mock_display", parsed_source, - nil, [%{"another_header.h"}]) - } - it "then they are included before the other files" do - expect(mock_source).to include( - %{#include "mock_display.h"\n} + - %{#include "another_header.h"\n} - ) - end - end -end diff --git a/test/unit-test/vendor/ceedling/plugins/fake_function_framework/spec/header_generator.rb b/test/unit-test/vendor/ceedling/plugins/fake_function_framework/spec/header_generator.rb deleted file mode 100644 index 3b6fa7120..000000000 --- a/test/unit-test/vendor/ceedling/plugins/fake_function_framework/spec/header_generator.rb +++ /dev/null @@ -1,51 +0,0 @@ -# Create a CMock-style parsed header hash. This the type of hash created by -# CMock when parsing header files for automock generation. It contains all of -# includes, typedefs and functions (with return types and arguments) parsed from -# the header file. -def create_cmock_style_parsed_header(functions, typedefs = nil) - parsed_header = { - :includes => nil, - :functions => [], - :typedefs => [] - } - - # Add the typedefs. - if typedefs - typedefs.each do |typedef| - parsed_header[:typedefs] << typedef - end - end - - # Add the functions. - if functions - functions.each do |function| - # Build the array of arguments. - args = [] - if function.key?(:args) - function[:args].each do |arg| - args << { - :type => arg - } - end - end - parsed_header[:functions] << { - :name => function[:name], - :modifier => "", - :return => { - :type => function[:return_type], - :name => "cmock_to_return", - :ptr? => false, - :const? => false, - :str => "void cmock_to_return", - :void? => true - }, - :var_arg => nil, - :args_string => "void", - :args => args, - :args_call => "", - :contains_ptr? => false - } - end - end - parsed_header -end diff --git a/test/unit-test/vendor/ceedling/plugins/fake_function_framework/spec/spec_helper.rb b/test/unit-test/vendor/ceedling/plugins/fake_function_framework/spec/spec_helper.rb deleted file mode 100644 index 25dc80ace..000000000 --- a/test/unit-test/vendor/ceedling/plugins/fake_function_framework/spec/spec_helper.rb +++ /dev/null @@ -1,96 +0,0 @@ -# This file was generated by the `rspec --init` command. Conventionally, all -# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. -# The generated `.rspec` file contains `--require spec_helper` which will cause -# this file to always be loaded, without a need to explicitly require it in any -# files. -# -# Given that it is always loaded, you are encouraged to keep this file as -# light-weight as possible. Requiring heavyweight dependencies from this file -# will add to the boot time of your test suite on EVERY test run, even for an -# individual file that may not need all of that loaded. Instead, consider making -# a separate helper file that requires the additional dependencies and performs -# the additional setup, and require it from the spec files that actually need -# it. -# -# The `.rspec` file also contains a few flags that are not defaults but that -# users commonly want. -# -# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration -RSpec.configure do |config| - # rspec-expectations config goes here. You can use an alternate - # assertion/expectation library such as wrong or the stdlib/minitest - # assertions if you prefer. - config.expect_with :rspec do |expectations| - # This option will default to `true` in RSpec 4. It makes the `description` - # and `failure_message` of custom matchers include text for helper methods - # defined using `chain`, e.g.: - # be_bigger_than(2).and_smaller_than(4).description - # # => "be bigger than 2 and smaller than 4" - # ...rather than: - # # => "be bigger than 2" - expectations.include_chain_clauses_in_custom_matcher_descriptions = true - end - - # rspec-mocks config goes here. You can use an alternate test double - # library (such as bogus or mocha) by changing the `mock_with` option here. - config.mock_with :rspec do |mocks| - # Prevents you from mocking or stubbing a method that does not exist on - # a real object. This is generally recommended, and will default to - # `true` in RSpec 4. - mocks.verify_partial_doubles = true - end - -# The settings below are suggested to provide a good initial experience -# with RSpec, but feel free to customize to your heart's content. -=begin - # These two settings work together to allow you to limit a spec run - # to individual examples or groups you care about by tagging them with - # `:focus` metadata. When nothing is tagged with `:focus`, all examples - # get run. - config.filter_run :focus - config.run_all_when_everything_filtered = true - - # Allows RSpec to persist some state between runs in order to support - # the `--only-failures` and `--next-failure` CLI options. We recommend - # you configure your source control system to ignore this file. - config.example_status_persistence_file_path = "spec/examples.txt" - - # Limits the available syntax to the non-monkey patched syntax that is - # recommended. For more details, see: - # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/ - # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ - # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode - config.disable_monkey_patching! - - # This setting enables warnings. It's recommended, but in some cases may - # be too noisy due to issues in dependencies. - config.warnings = true - - # Many RSpec users commonly either run the entire suite or an individual - # file, and it's useful to allow more verbose output when running an - # individual spec file. - if config.files_to_run.one? - # Use the documentation formatter for detailed output, - # unless a formatter has already been configured - # (e.g. via a command-line flag). - config.default_formatter = 'doc' - end - - # Print the 10 slowest examples and example groups at the - # end of the spec run, to help surface which specs are running - # particularly slow. - config.profile_examples = 10 - - # Run specs in random order to surface order dependencies. If you find an - # order dependency and want to debug it, you can fix the order by providing - # the seed, which is printed after each run. - # --seed 1234 - config.order = :random - - # Seed global randomization in this process using the `--seed` CLI option. - # Setting this allows you to use `--seed` to deterministically reproduce - # test failures related to randomization by passing the same `--seed` value - # as the one that triggered the failure. - Kernel.srand config.seed -=end -end diff --git a/test/unit-test/vendor/ceedling/plugins/fake_function_framework/src/fff_unity_helper.h b/test/unit-test/vendor/ceedling/plugins/fake_function_framework/src/fff_unity_helper.h deleted file mode 100644 index 970ecbb35..000000000 --- a/test/unit-test/vendor/ceedling/plugins/fake_function_framework/src/fff_unity_helper.h +++ /dev/null @@ -1,33 +0,0 @@ -#ifndef fff_unity_helper_H -#define fff_unity_helper_H - -/* - FFF helper macros for Unity. -*/ - -/* - Fail if the function was not called the expected number of times. -*/ -#define TEST_ASSERT_CALLED_TIMES(times_, function_) \ - TEST_ASSERT_EQUAL_MESSAGE(times_, \ - function_ ## _fake.call_count, \ - "Function " #function_ " called the incorrect number of times.") -/* - Fail if the function was not called exactly once. -*/ -#define TEST_ASSERT_CALLED(function_) TEST_ASSERT_CALLED_TIMES(1, function_) - -/* - Fail if the function was called 1 or more times. -*/ -#define TEST_ASSERT_NOT_CALLED(function_) TEST_ASSERT_CALLED_TIMES(0, function_) - -/* - Fail if the function was not called in this particular order. -*/ -#define TEST_ASSERT_CALLED_IN_ORDER(order_, function_) \ - TEST_ASSERT_EQUAL_PTR_MESSAGE((void *) function_, \ - fff.call_history[order_], \ - "Function " #function_ " not called in order " #order_ ) - -#endif diff --git a/test/unit-test/vendor/ceedling/plugins/gcov/README.md b/test/unit-test/vendor/ceedling/plugins/gcov/README.md deleted file mode 100644 index b144e3b74..000000000 --- a/test/unit-test/vendor/ceedling/plugins/gcov/README.md +++ /dev/null @@ -1,433 +0,0 @@ -ceedling-gcov -============= - -# Plugin Overview - -Plugin for integrating GNU GCov code coverage tool into Ceedling projects. -Currently only designed for the gcov command (like LCOV for example). In the -future we could configure this to work with other code coverage tools. - -This plugin currently uses [gcovr](https://www.gcovr.com/) and / or -[ReportGenerator](https://danielpalme.github.io/ReportGenerator/) -as utilities to generate HTML, XML, JSON, or Text reports. The normal gcov -plugin _must_ be run first for these reports to generate. - -## Installation - -gcovr can be installed via pip like so: - -```sh -pip install gcovr -``` - -ReportGenerator can be installed via .NET Core like so: - -```sh -dotnet tool install -g dotnet-reportgenerator-globaltool -``` - -It is not required to install both `gcovr` and `ReportGenerator`. Either utility -may be installed to create reports. - -## Configuration - -The gcov plugin supports configuration options via your `project.yml` provided -by Ceedling. - -### Utilities - -Gcovr and / or ReportGenerator may be enabled to create coverage reports. - -```yaml -:gcov: - :utilities: - - gcovr # Use gcovr to create the specified reports (default). - - ReportGenerator # Use ReportGenerator to create the specified reports. -``` - -### Reports - -Various reports are available and may be enabled with the following -configuration item. See the specific report sections in this README -for additional options and information. All generated reports will be found in `build/artifacts/gcov`. - -```yaml -:gcov: - # Specify one or more reports to generate. - # Defaults to HtmlBasic. - :reports: - # Make an HTML summary report. - # Supported utilities: gcovr, ReportGenerator - - HtmlBasic - - # Make an HTML report with line by line coverage of each source file. - # Supported utilities: gcovr, ReportGenerator - - HtmlDetailed - - # Make a Text report, which may be output to the console with gcovr or a file in both gcovr and ReportGenerator. - # Supported utilities: gcovr, ReportGenerator - - Text - - # Make a Cobertura XML report. - # Supported utilities: gcovr, ReportGenerator - - Cobertura - - # Make a SonarQube XML report. - # Supported utilities: gcovr, ReportGenerator - - SonarQube - - # Make a JSON report. - # Supported utilities: gcovr - - JSON - - # Make a detailed HTML report with CSS and JavaScript included in every HTML page. Useful for build servers. - # Supported utilities: ReportGenerator - - HtmlInline - - # Make a detailed HTML report with a light theme and CSS and JavaScript included in every HTML page for Azure DevOps. - # Supported utilities: ReportGenerator - - HtmlInlineAzure - - # Make a detailed HTML report with a dark theme and CSS and JavaScript included in every HTML page for Azure DevOps. - # Supported utilities: ReportGenerator - - HtmlInlineAzureDark - - # Make a single HTML file containing a chart with historic coverage information. - # Supported utilities: ReportGenerator - - HtmlChart - - # Make a detailed HTML report in a single file. - # Supported utilities: ReportGenerator - - MHtml - - # Make SVG and PNG files that show line and / or branch coverage information. - # Supported utilities: ReportGenerator - - Badges - - # Make a single CSV file containing coverage information per file. - # Supported utilities: ReportGenerator - - CsvSummary - - # Make a single TEX file containing a summary for all files and detailed reports for each files. - # Supported utilities: ReportGenerator - - Latex - - # Make a single TEX file containing a summary for all files. - # Supported utilities: ReportGenerator - - LatexSummary - - # Make a single PNG file containing a chart with historic coverage information. - # Supported utilities: ReportGenerator - - PngChart - - # Command line output interpreted by TeamCity. - # Supported utilities: ReportGenerator - - TeamCitySummary - - # Make a text file in lcov format. - # Supported utilities: ReportGenerator - - lcov - - # Make a XML file containing a summary for all classes and detailed reports for each class. - # Supported utilities: ReportGenerator - - Xml - - # Make a single XML file containing a summary for all files. - # Supported utilities: ReportGenerator - - XmlSummary -``` - -### Gcovr HTML Reports - -Generation of Gcovr HTML reports may be modified with the following configuration items. - -```yaml -:gcov: - # Set to 'true' to enable HTML reports or set to 'false' to disable. - # Defaults to enabled. (gcovr --html) - # Deprecated - See the :reports: configuration option. - :html_report: [true|false] - - # Gcovr supports generating two types of HTML reports. Use 'basic' to create - # an HTML report with only the overall file information. Use 'detailed' to create - # an HTML report with line by line coverage of each source file. - # Defaults to 'basic'. Set to 'detailed' for (gcovr --html-details). - # Deprecated - See the :reports: configuration option. - :html_report_type: [basic|detailed] - - - :gcovr: - # HTML report filename. - :html_artifact_filename: - - # Use 'title' as title for the HTML report. - # Default is 'Head'. (gcovr --html-title) - :html_title: - - # If the coverage is below MEDIUM, the value is marked as low coverage in the HTML report. - # MEDIUM has to be lower than or equal to value of html_high_threshold. - # If MEDIUM is equal to value of html_high_threshold the report has only high and low coverage. - # Default is 75.0. (gcovr --html-medium-threshold) - :html_medium_threshold: 75 - - # If the coverage is below HIGH, the value is marked as medium coverage in the HTML report. - # HIGH has to be greater than or equal to value of html_medium_threshold. - # If HIGH is equal to value of html_medium_threshold the report has only high and low coverage. - # Default is 90.0. (gcovr -html-high-threshold) - :html_high_threshold: 90 - - # Set to 'true' to use absolute paths to link the 'detailed' reports. - # Defaults to relative links. (gcovr --html-absolute-paths) - :html_absolute_paths: [true|false] - - # Override the declared HTML report encoding. Defaults to UTF-8. (gcovr --html-encoding) - :html_encoding: <html_encoding> -``` - -### Cobertura XML Reports - -Generation of Cobertura XML reports may be modified with the following configuration items. - -```yaml -:gcov: - # Set to 'true' to enable Cobertura XML reports or set to 'false' to disable. - # Defaults to disabled. (gcovr --xml) - # Deprecated - See the :reports: configuration option. - :xml_report: [true|false] - - - :gcovr: - # Set to 'true' to pretty-print the Cobertura XML report, otherwise set to 'false'. - # Defaults to disabled. (gcovr --xml-pretty) - :xml_pretty: [true|false] - :cobertura_pretty: [true|false] - - # Cobertura XML report filename. - :xml_artifact_filename: <output> - :cobertura_artifact_filename: <output> -``` - -### SonarQube XML Reports - -Generation of SonarQube XML reports may be modified with the following configuration items. - -```yaml -:gcov: - :gcovr: - # SonarQube XML report filename. - :sonarqube_artifact_filename: <output> -``` - -### JSON Reports - -Generation of JSON reports may be modified with the following configuration items. - -```yaml -:gcov: - :gcovr: - # Set to 'true' to pretty-print the JSON report, otherwise set 'false'. - # Defaults to disabled. (gcovr --json-pretty) - :json_pretty: [true|false] - - # JSON report filename. - :json_artifact_filename: <output> -``` - -### Text Reports - -Generation of text reports may be modified with the following configuration items. -Text reports may be printed to the console or output to a file. - -```yaml -:gcov: - :gcovr: - # Text report filename. - # The text report is printed to the console when no filename is provided. - :text_artifact_filename: <output> -``` - -### Common Report Options - -There are a number of options to control which files are considered part of -the coverage report. Most often, we only care about coverage on our source code, and not -on tests or automatically generated mocks, runners, etc. However, there are times -where this isn't true... or there are times where we've moved ceedling's directory -structure so that the project file isn't at the root of the project anymore. In these -cases, you may need to tweak `report_include`, `report_exclude`, and `exclude_directories`. - -One important note about `report_root`: gcovr will take only a single root folder, unlike -Ceedling's ability to take as many as you like. So you will need to choose a folder which is -a superset of ALL the folders you want, and then use the include or exclude options to set up -patterns of files to pay attention to or ignore. It's not ideal, but it works. - -Finally, there are a number of settings which can be specified to adjust the -default behaviors of gcovr: - -```yaml -:gcov: - :gcovr: - # The root directory of your source files. Defaults to ".", the current directory. - # File names are reported relative to this root. The report_root is the default report_include. - :report_root: "." - - # Load the specified configuration file. - # Defaults to gcovr.cfg in the report_root directory. (gcovr --config) - :config_file: <config_file> - - # Exit with a status of 2 if the total line coverage is less than MIN. - # Can be ORed with exit status of 'fail_under_branch' option. (gcovr --fail-under-line) - :fail_under_line: 30 - - # Exit with a status of 4 if the total branch coverage is less than MIN. - # Can be ORed with exit status of 'fail_under_line' option. (gcovr --fail-under-branch) - :fail_under_branch: 30 - - # Select the source file encoding. - # Defaults to the system default encoding (UTF-8). (gcovr --source-encoding) - :source_encoding: <source_encoding> - - # Report the branch coverage instead of the line coverage. For text report only. (gcovr --branches). - :branches: [true|false] - - # Sort entries by increasing number of uncovered lines. - # For text and HTML report. (gcovr --sort-uncovered) - :sort_uncovered: [true|false] - - # Sort entries by increasing percentage of uncovered lines. - # For text and HTML report. (gcovr --sort-percentage) - :sort_percentage: [true|false] - - # Print a small report to stdout with line & branch percentage coverage. - # This is in addition to other reports. (gcovr --print-summary). - :print_summary: [true|false] - - # Keep only source files that match this filter. (gcovr --filter). - :report_include: "^src" - - # Exclude source files that match this filter. (gcovr --exclude). - :report_exclude: "^vendor.*|^build.*|^test.*|^lib.*" - - # Keep only gcov data files that match this filter. (gcovr --gcov-filter). - :gcov_filter: <gcov_filter> - - # Exclude gcov data files that match this filter. (gcovr --gcov-exclude). - :gcov_exclude: <gcov_exclude> - - # Exclude directories that match this regex while searching - # raw coverage files. (gcovr --exclude-directories). - :exclude_directories: <exclude_dirs> - - # Use a particular gcov executable. (gcovr --gcov-executable). - :gcov_executable: <gcov_cmd> - - # Exclude branch coverage from lines without useful - # source code. (gcovr --exclude-unreachable-branches). - :exclude_unreachable_branches: [true|false] - - # For branch coverage, exclude branches that the compiler - # generates for exception handling. (gcovr --exclude-throw-branches). - :exclude_throw_branches: [true|false] - - # Use existing gcov files for analysis. Default: False. (gcovr --use-gcov-files) - :use_gcov_files: [true|false] - - # Skip lines with parse errors in GCOV files instead of - # exiting with an error. (gcovr --gcov-ignore-parse-errors). - :gcov_ignore_parse_errors: [true|false] - - # Override normal working directory detection. (gcovr --object-directory) - :object_directory: <objdir> - - # Keep gcov files after processing. (gcovr --keep). - :keep: [true|false] - - # Delete gcda files after processing. (gcovr --delete). - :delete: [true|false] - - # Set the number of threads to use in parallel. (gcovr -j). - :num_parallel_threads: <num_threads> - - # When scanning the code coverage, if any files are found that do not have - # associated coverage data, the command will abort with an error message. - :abort_on_uncovered: true - - # When using the ``abort_on_uncovered`` option, the files in this list will not - # trigger a failure. - # Ceedling globs described in the Ceedling packet ``Path`` section can be used - # when directories are placed on the list. Globs are limited to matching directories - # and not files. - :uncovered_ignore_list: [] -``` - -### ReportGenerator Configuration - -The ReportGenerator utility may be configured with the following configuration items. -All generated reports may be found in `build/artifacts/gcov/ReportGenerator`. - -```yaml -:gcov: - :report_generator: - # Optional directory for storing persistent coverage information. - # Can be used in future reports to show coverage evolution. - :history_directory: <history_directory> - - # Optional plugin files for custom reports or custom history storage (separated by semicolon). - :plugins: CustomReports.dll - - # Optional list of assemblies that should be included or excluded in the report (separated by semicolon).. - # Exclusion filters take precedence over inclusion filters. - # Wildcards are allowed, but not regular expressions. - :assembly_filters: "+Included;-Excluded" - - # Optional list of classes that should be included or excluded in the report (separated by semicolon).. - # Exclusion filters take precedence over inclusion filters. - # Wildcards are allowed, but not regular expressions. - :class_filters: "+Included;-Excluded" - - # Optional list of files that should be included or excluded in the report (separated by semicolon).. - # Exclusion filters take precedence over inclusion filters. - # Wildcards are allowed, but not regular expressions. - :file_filters: "-./vendor/*;-./build/*;-./test/*;-./lib/*;+./src/*" - - # The verbosity level of the log messages. - # Values: Verbose, Info, Warning, Error, Off - :verbosity: Warning - - # Optional tag or build version. - :tag: <tag> - - # Optional list of one or more regular expressions to exclude gcov notes files that match these filters. - :gcov_exclude: - - <exclude_regex1> - - <exclude_regex2> - - # Optionally use a particular gcov executable. Defaults to gcov. - :gcov_executable: <gcov_cmd> - - # Optionally set the number of threads to use in parallel. Defaults to 1. - :num_parallel_threads: <num_threads> - - # Optional list of one or more command line arguments to pass to Report Generator. - # Useful for configuring Risk Hotspots and Other Settings. - # https://github.com/danielpalme/ReportGenerator/wiki/Settings - :custom_args: - - <custom_arg1> - - <custom_arg2> -``` - -## Example Usage - -```sh -ceedling gcov:all utils:gcov -``` - -## To-Do list - -- Generate overall report (combined statistics from all files with coverage) - -## Citations - -Most of the comment text which describes the options was taken from the -[Gcovr User Guide](https://www.gcovr.com/en/stable/guide.html) and the -[ReportGenerator Wiki](https://github.com/danielpalme/ReportGenerator/wiki). -The text is repeated here to provide the most accurate option functionality. diff --git a/test/unit-test/vendor/ceedling/plugins/gcov/assets/template.erb b/test/unit-test/vendor/ceedling/plugins/gcov/assets/template.erb deleted file mode 100644 index 266750497..000000000 --- a/test/unit-test/vendor/ceedling/plugins/gcov/assets/template.erb +++ /dev/null @@ -1,14 +0,0 @@ -% function_string = hash[:coverage][:functions].to_s -% branch_string = hash[:coverage][:branches].to_s -% format_string = "%#{[function_string.length, branch_string.length].max}i" -<%=@ceedling[:plugin_reportinator].generate_banner("#{GCOV_ROOT_NAME.upcase}: CODE COVERAGE SUMMARY")%> -% if (!hash[:coverage][:functions].nil?) -FUNCTIONS: <%=sprintf(format_string, hash[:coverage][:functions])%>% -% else -FUNCTIONS: none -% end -% if (!hash[:coverage][:branches].nil?) -BRANCHES: <%=sprintf(format_string, hash[:coverage][:branches])%>% -% else -BRANCHES: none -% end diff --git a/test/unit-test/vendor/ceedling/plugins/gcov/config/defaults_gcov.rb b/test/unit-test/vendor/ceedling/plugins/gcov/config/defaults_gcov.rb deleted file mode 100644 index e3ce340dd..000000000 --- a/test/unit-test/vendor/ceedling/plugins/gcov/config/defaults_gcov.rb +++ /dev/null @@ -1,118 +0,0 @@ - -DEFAULT_GCOV_COMPILER_TOOL = { - :executable => ENV['CC'].nil? ? FilePathUtils.os_executable_ext('gcc').freeze : ENV['CC'].split[0], - :name => 'default_gcov_compiler'.freeze, - :stderr_redirect => StdErrRedirect::NONE.freeze, - :background_exec => BackgroundExec::NONE.freeze, - :optional => false.freeze, - :arguments => [ - "-g".freeze, - "-fprofile-arcs".freeze, - "-ftest-coverage".freeze, - ENV['CC'].nil? ? "" : ENV['CC'].split[1..-1], - ENV['CPPFLAGS'].nil? ? "" : ENV['CPPFLAGS'].split, - {"-I\"$\"" => 'COLLECTION_PATHS_TEST_SUPPORT_SOURCE_INCLUDE_VENDOR'}.freeze, - {"-I\"$\"" => 'COLLECTION_PATHS_TEST_TOOLCHAIN_INCLUDE'}.freeze, - {"-D$" => 'COLLECTION_DEFINES_TEST_AND_VENDOR'}.freeze, - "-DGCOV_COMPILER".freeze, - "-DCODE_COVERAGE".freeze, - ENV['CFLAGS'].nil? ? "" : ENV['CFLAGS'].split, - "-c \"${1}\"".freeze, - "-o \"${2}\"".freeze - ].freeze - } - - -DEFAULT_GCOV_LINKER_TOOL = { - :executable => ENV['CCLD'].nil? ? FilePathUtils.os_executable_ext('gcc').freeze : ENV['CCLD'].split[0], - :name => 'default_gcov_linker'.freeze, - :stderr_redirect => StdErrRedirect::NONE.freeze, - :background_exec => BackgroundExec::NONE.freeze, - :optional => false.freeze, - :arguments => [ - "-g".freeze, - "-fprofile-arcs".freeze, - "-ftest-coverage".freeze, - ENV['CCLD'].nil? ? "" : ENV['CCLD'].split[1..-1], - ENV['CFLAGS'].nil? ? "" : ENV['CFLAGS'].split, - ENV['LDFLAGS'].nil? ? "" : ENV['LDFLAGS'].split, - "\"${1}\"".freeze, - "-o \"${2}\"".freeze, - "${4}".freeze, - "${5}".freeze, - ENV['LDLIBS'].nil? ? "" : ENV['LDLIBS'].split - ].freeze - } - -DEFAULT_GCOV_FIXTURE_TOOL = { - :executable => '${1}'.freeze, - :name => 'default_gcov_fixture'.freeze, - :stderr_redirect => StdErrRedirect::NONE.freeze, - :background_exec => BackgroundExec::NONE.freeze, - :optional => false.freeze, - :arguments => [].freeze - } - -DEFAULT_GCOV_REPORT_TOOL = { - :executable => ENV['GCOV'].nil? ? FilePathUtils.os_executable_ext('gcov').freeze : ENV['GCOV'].split[0], - :name => 'default_gcov_report'.freeze, - :stderr_redirect => StdErrRedirect::NONE.freeze, - :background_exec => BackgroundExec::NONE.freeze, - :optional => false.freeze, - :arguments => [ - "-n".freeze, - "-p".freeze, - "-b".freeze, - {"-o \"$\"" => 'GCOV_BUILD_OUTPUT_PATH'}.freeze, - "\"${1}\"".freeze - ].freeze - } - -DEFAULT_GCOV_GCOV_POST_REPORT_TOOL = { - :executable => ENV['GCOV'].nil? ? FilePathUtils.os_executable_ext('gcov').freeze : ENV['GCOV'].split[0], - :name => 'default_gcov_gcov_post_report'.freeze, - :stderr_redirect => StdErrRedirect::NONE.freeze, - :background_exec => BackgroundExec::NONE.freeze, - :optional => true.freeze, - :arguments => [ - "-b".freeze, - "-c".freeze, - "-r".freeze, - "-x".freeze, - "${1}".freeze - ].freeze - } - -DEFAULT_GCOV_GCOVR_POST_REPORT_TOOL = { - :executable => 'gcovr'.freeze, - :name => 'default_gcov_gcovr_post_report'.freeze, - :stderr_redirect => StdErrRedirect::NONE.freeze, - :background_exec => BackgroundExec::NONE.freeze, - :optional => true.freeze, - :arguments => [ - "${1}".freeze - ].freeze - } - -DEFAULT_GCOV_REPORTGENERATOR_POST_REPORT = { - :executable => 'reportgenerator'.freeze, - :name => 'default_gcov_reportgenerator_post_report'.freeze, - :stderr_redirect => StdErrRedirect::NONE.freeze, - :background_exec => BackgroundExec::NONE.freeze, - :optional => true.freeze, - :arguments => [ - "${1}".freeze - ].freeze - } - -def get_default_config - return :tools => { - :gcov_compiler => DEFAULT_GCOV_COMPILER_TOOL, - :gcov_linker => DEFAULT_GCOV_LINKER_TOOL, - :gcov_fixture => DEFAULT_GCOV_FIXTURE_TOOL, - :gcov_report => DEFAULT_GCOV_REPORT_TOOL, - :gcov_gcov_post_report => DEFAULT_GCOV_GCOV_POST_REPORT_TOOL, - :gcov_gcovr_post_report => DEFAULT_GCOV_GCOVR_POST_REPORT_TOOL, - :gcov_reportgenerator_post_report => DEFAULT_GCOV_REPORTGENERATOR_POST_REPORT - } -end diff --git a/test/unit-test/vendor/ceedling/plugins/gcov/gcov.rake b/test/unit-test/vendor/ceedling/plugins/gcov/gcov.rake deleted file mode 100644 index 1467564a8..000000000 --- a/test/unit-test/vendor/ceedling/plugins/gcov/gcov.rake +++ /dev/null @@ -1,209 +0,0 @@ -require 'reportgenerator_reportinator' -require 'gcovr_reportinator' - -directory(GCOV_BUILD_OUTPUT_PATH) -directory(GCOV_RESULTS_PATH) -directory(GCOV_ARTIFACTS_PATH) -directory(GCOV_DEPENDENCIES_PATH) - -CLEAN.include(File.join(GCOV_BUILD_OUTPUT_PATH, '*')) -CLEAN.include(File.join(GCOV_RESULTS_PATH, '*')) -CLEAN.include(File.join(GCOV_ARTIFACTS_PATH, '*')) -CLEAN.include(File.join(GCOV_DEPENDENCIES_PATH, '*')) - -CLOBBER.include(File.join(GCOV_BUILD_PATH, '**/*')) - -rule(/#{GCOV_BUILD_OUTPUT_PATH}\/#{'.+\\' + EXTENSION_OBJECT}$/ => [ - proc do |task_name| - @ceedling[:file_finder].find_compilation_input_file(task_name) - end - ]) do |object| - - if File.basename(object.source) =~ /^(#{PROJECT_TEST_FILE_PREFIX}|#{CMOCK_MOCK_PREFIX})|(#{VENDORS_FILES.map{|source| '\b' + source + '\b'}.join('|')})/ - @ceedling[:generator].generate_object_file( - TOOLS_GCOV_COMPILER, - OPERATION_COMPILE_SYM, - GCOV_SYM, - object.source, - object.name, - @ceedling[:file_path_utils].form_test_build_list_filepath(object.name) - ) - else - @ceedling[GCOV_SYM].generate_coverage_object_file(object.source, object.name) - end -end - -rule(/#{GCOV_BUILD_OUTPUT_PATH}\/#{'.+\\' + EXTENSION_EXECUTABLE}$/) do |bin_file| - lib_args = @ceedling[:test_invoker].convert_libraries_to_arguments() - lib_paths = @ceedling[:test_invoker].get_library_paths_to_arguments() - @ceedling[:generator].generate_executable_file( - TOOLS_GCOV_LINKER, - GCOV_SYM, - bin_file.prerequisites, - bin_file.name, - @ceedling[:file_path_utils].form_test_build_map_filepath(bin_file.name), - lib_args, - lib_paths - ) -end - -rule(/#{GCOV_RESULTS_PATH}\/#{'.+\\' + EXTENSION_TESTPASS}$/ => [ - proc do |task_name| - @ceedling[:file_path_utils].form_test_executable_filepath(task_name) - end - ]) do |test_result| - @ceedling[:generator].generate_test_results(TOOLS_GCOV_FIXTURE, GCOV_SYM, test_result.source, test_result.name) -end - -rule(/#{GCOV_DEPENDENCIES_PATH}\/#{'.+\\' + EXTENSION_DEPENDENCIES}$/ => [ - proc do |task_name| - @ceedling[:file_finder].find_compilation_input_file(task_name) - end - ]) do |dep| - @ceedling[:generator].generate_dependencies_file( - TOOLS_TEST_DEPENDENCIES_GENERATOR, - GCOV_SYM, - dep.source, - File.join(GCOV_BUILD_OUTPUT_PATH, File.basename(dep.source).ext(EXTENSION_OBJECT)), - dep.name - ) -end - -task directories: [GCOV_BUILD_OUTPUT_PATH, GCOV_RESULTS_PATH, GCOV_DEPENDENCIES_PATH, GCOV_ARTIFACTS_PATH] - -namespace GCOV_SYM do - task source_coverage: COLLECTION_ALL_SOURCE.pathmap("#{GCOV_BUILD_OUTPUT_PATH}/%n#{@ceedling[:configurator].extension_object}") - - desc 'Run code coverage for all tests' - task all: [:test_deps] do - @ceedling[:configurator].replace_flattened_config(@ceedling[GCOV_SYM].config) - @ceedling[:test_invoker].setup_and_invoke(COLLECTION_ALL_TESTS, GCOV_SYM) - @ceedling[:configurator].restore_config - end - - desc 'Run single test w/ coverage ([*] real test or source file name, no path).' - task :* do - message = "\nOops! '#{GCOV_ROOT_NAME}:*' isn't a real task. " \ - "Use a real test or source file name (no path) in place of the wildcard.\n" \ - "Example: rake #{GCOV_ROOT_NAME}:foo.c\n\n" - - @ceedling[:streaminator].stdout_puts(message) - end - - desc 'Run tests by matching regular expression pattern.' - task :pattern, [:regex] => [:test_deps] do |_t, args| - matches = [] - - COLLECTION_ALL_TESTS.each do |test| - matches << test if test =~ /#{args.regex}/ - end - - if !matches.empty? - @ceedling[:configurator].replace_flattened_config(@ceedling[GCOV_SYM].config) - @ceedling[:test_invoker].setup_and_invoke(matches, GCOV_SYM, force_run: false) - @ceedling[:configurator].restore_config - else - @ceedling[:streaminator].stdout_puts("\nFound no tests matching pattern /#{args.regex}/.") - end - end - - desc 'Run tests whose test path contains [dir] or [dir] substring.' - task :path, [:dir] => [:test_deps] do |_t, args| - matches = [] - - COLLECTION_ALL_TESTS.each do |test| - matches << test if File.dirname(test).include?(args.dir.tr('\\', '/')) - end - - if !matches.empty? - @ceedling[:configurator].replace_flattened_config(@ceedling[GCOV_SYM].config) - @ceedling[:test_invoker].setup_and_invoke(matches, GCOV_SYM, force_run: false) - @ceedling[:configurator].restore_config - else - @ceedling[:streaminator].stdout_puts("\nFound no tests including the given path or path component.") - end - end - - desc 'Run code coverage for changed files' - task delta: [:test_deps] do - @ceedling[:configurator].replace_flattened_config(@ceedling[GCOV_SYM].config) - @ceedling[:test_invoker].setup_and_invoke(COLLECTION_ALL_TESTS, GCOV_SYM, force_run: false) - @ceedling[:configurator].restore_config - end - - # use a rule to increase efficiency for large projects - # gcov test tasks by regex - rule(/^#{GCOV_TASK_ROOT}\S+$/ => [ - proc do |task_name| - test = task_name.sub(/#{GCOV_TASK_ROOT}/, '') - test = "#{PROJECT_TEST_FILE_PREFIX}#{test}" unless test.start_with?(PROJECT_TEST_FILE_PREFIX) - @ceedling[:file_finder].find_test_from_file_path(test) - end - ]) do |test| - @ceedling[:rake_wrapper][:test_deps].invoke - @ceedling[:configurator].replace_flattened_config(@ceedling[GCOV_SYM].config) - @ceedling[:test_invoker].setup_and_invoke([test.source], GCOV_SYM) - @ceedling[:configurator].restore_config - end -end - -if PROJECT_USE_DEEP_DEPENDENCIES - namespace REFRESH_SYM do - task GCOV_SYM do - @ceedling[:configurator].replace_flattened_config(@ceedling[GCOV_SYM].config) - @ceedling[:test_invoker].refresh_deep_dependencies - @ceedling[:configurator].restore_config - end - end -end - -namespace UTILS_SYM do - # Report Creation Utilities - UTILITY_NAME_GCOVR = "gcovr" - UTILITY_NAME_REPORT_GENERATOR = "ReportGenerator" - UTILITY_NAMES = [UTILITY_NAME_GCOVR, UTILITY_NAME_REPORT_GENERATOR] - - # Returns true is the given utility is enabled, otherwise returns false. - def is_utility_enabled(opts, utility_name) - return !(opts.nil?) && !(opts[:gcov_utilities].nil?) && (opts[:gcov_utilities].map(&:upcase).include? utility_name.upcase) - end - - - desc "Create gcov code coverage html/xml/json/text report(s). (Note: Must run 'ceedling gcov' first)." - task GCOV_SYM do - # Get the gcov options from project.yml. - opts = @ceedling[:configurator].project_config_hash - - # Create the artifacts output directory. - if !File.directory? GCOV_ARTIFACTS_PATH - FileUtils.mkdir_p GCOV_ARTIFACTS_PATH - end - - # Remove unsupported reporting utilities. - if !(opts[:gcov_utilities].nil?) - opts[:gcov_utilities].reject! { |item| !(UTILITY_NAMES.map(&:upcase).include? item.upcase) } - end - - # Default to gcovr when no reporting utilities are specified. - if opts[:gcov_utilities].nil? || opts[:gcov_utilities].empty? - opts[:gcov_utilities] = [UTILITY_NAME_GCOVR] - end - - if opts[:gcov_reports].nil? - opts[:gcov_reports] = [] - end - - gcovr_reportinator = GcovrReportinator.new(@ceedling) - gcovr_reportinator.support_deprecated_options(opts) - - if is_utility_enabled(opts, UTILITY_NAME_GCOVR) - gcovr_reportinator.make_reports(opts) - end - - if is_utility_enabled(opts, UTILITY_NAME_REPORT_GENERATOR) - reportgenerator_reportinator = ReportGeneratorReportinator.new(@ceedling) - reportgenerator_reportinator.make_reports(opts) - end - - end -end diff --git a/test/unit-test/vendor/ceedling/plugins/gcov/lib/gcov.rb b/test/unit-test/vendor/ceedling/plugins/gcov/lib/gcov.rb deleted file mode 100644 index 30c6326b8..000000000 --- a/test/unit-test/vendor/ceedling/plugins/gcov/lib/gcov.rb +++ /dev/null @@ -1,136 +0,0 @@ -require 'ceedling/plugin' -require 'ceedling/constants' -require 'gcov_constants' - -class Gcov < Plugin - attr_reader :config - - def setup - @result_list = [] - - @config = { - project_test_build_output_path: GCOV_BUILD_OUTPUT_PATH, - project_test_build_output_c_path: GCOV_BUILD_OUTPUT_PATH, - project_test_results_path: GCOV_RESULTS_PATH, - project_test_dependencies_path: GCOV_DEPENDENCIES_PATH, - defines_test: DEFINES_TEST + ['CODE_COVERAGE'], - gcov_html_report_filter: GCOV_FILTER_EXCLUDE - } - - @plugin_root = File.expand_path(File.join(File.dirname(__FILE__), '..')) - @coverage_template_all = @ceedling[:file_wrapper].read(File.join(@plugin_root, 'assets/template.erb')) - end - - def generate_coverage_object_file(source, object) - lib_args = @ceedling[:test_invoker].convert_libraries_to_arguments() - compile_command = - @ceedling[:tool_executor].build_command_line( - TOOLS_GCOV_COMPILER, - @ceedling[:flaginator].flag_down(OPERATION_COMPILE_SYM, GCOV_SYM, source), - source, - object, - @ceedling[:file_path_utils].form_test_build_list_filepath(object), - lib_args - ) - @ceedling[:streaminator].stdout_puts("Compiling #{File.basename(source)} with coverage...") - @ceedling[:tool_executor].exec(compile_command[:line], compile_command[:options]) - end - - def post_test_fixture_execute(arg_hash) - result_file = arg_hash[:result_file] - - if (result_file =~ /#{GCOV_RESULTS_PATH}/) && !@result_list.include?(result_file) - @result_list << arg_hash[:result_file] - end - end - - def post_build - return unless @ceedling[:task_invoker].invoked?(/^#{GCOV_TASK_ROOT}/) - - # test results - results = @ceedling[:plugin_reportinator].assemble_test_results(@result_list) - hash = { - header: GCOV_ROOT_NAME.upcase, - results: results - } - - @ceedling[:plugin_reportinator].run_test_results_report(hash) do - message = '' - message = 'Unit test failures.' if results[:counts][:failed] > 0 - message - end - - report_per_file_coverage_results(@ceedling[:test_invoker].sources) - end - - def summary - result_list = @ceedling[:file_path_utils].form_pass_results_filelist(GCOV_RESULTS_PATH, COLLECTION_ALL_TESTS) - - # test results - # get test results for only those tests in our configuration and of those only tests with results on disk - hash = { - header: GCOV_ROOT_NAME.upcase, - results: @ceedling[:plugin_reportinator].assemble_test_results(result_list, boom: false) - } - - @ceedling[:plugin_reportinator].run_test_results_report(hash) - end - - private ################################### - - def report_per_file_coverage_results(sources) - banner = @ceedling[:plugin_reportinator].generate_banner "#{GCOV_ROOT_NAME.upcase}: CODE COVERAGE SUMMARY" - @ceedling[:streaminator].stdout_puts "\n" + banner - - coverage_sources = @ceedling[:project_config_manager].filter_internal_sources(sources) - coverage_sources.each do |source| - basename = File.basename(source) - command = @ceedling[:tool_executor].build_command_line(TOOLS_GCOV_REPORT, [], [basename]) - shell_results = @ceedling[:tool_executor].exec(command[:line], command[:options]) - coverage_results = shell_results[:output] - - if coverage_results.strip =~ /(File\s+'#{Regexp.escape(source)}'.+$)/m - report = Regexp.last_match(1).lines.to_a[1..-1].map { |line| basename + ' ' + line }.join('') - @ceedling[:streaminator].stdout_puts(report + "\n\n") - end - end - - ignore_path_list = @ceedling[:file_system_utils].collect_paths(@ceedling[:configurator].project_config_hash[:gcov_uncovered_ignore_list] || []) - ignore_uncovered_list = @ceedling[:file_wrapper].instantiate_file_list - ignore_path_list.each do |path| - if File.exists?(path) and not File.directory?(path) - ignore_uncovered_list.include(path) - else - ignore_uncovered_list.include(File.join(path, "*#{EXTENSION_SOURCE}")) - end - end - - found_uncovered = false - COLLECTION_ALL_SOURCE.each do |source| - unless coverage_sources.include?(source) - v = Verbosity::DEBUG - msg = "Could not find coverage results for " + source - if ignore_uncovered_list.include?(source) - msg += " [IGNORED]" - else - found_uncovered = true - v = Verbosity::NORMAL - end - msg += "\n" - @ceedling[:streaminator].stdout_puts(msg, v) - end - end - if found_uncovered - if @ceedling[:configurator].project_config_hash[:gcov_abort_on_uncovered] - @ceedling[:streaminator].stderr_puts("There were files with no coverage results: aborting.\n") - exit(-1) - end - end - end -end - -# end blocks always executed following rake run -END { - # cache our input configurations to use in comparison upon next execution - @ceedling[:cacheinator].cache_test_config(@ceedling[:setupinator].config_hash) if @ceedling[:task_invoker].invoked?(/^#{GCOV_TASK_ROOT}/) -} diff --git a/test/unit-test/vendor/ceedling/plugins/gcov/lib/gcov_constants.rb b/test/unit-test/vendor/ceedling/plugins/gcov/lib/gcov_constants.rb deleted file mode 100644 index 74c9bbda8..000000000 --- a/test/unit-test/vendor/ceedling/plugins/gcov/lib/gcov_constants.rb +++ /dev/null @@ -1,48 +0,0 @@ - -GCOV_ROOT_NAME = 'gcov'.freeze -GCOV_TASK_ROOT = GCOV_ROOT_NAME + ':' -GCOV_SYM = GCOV_ROOT_NAME.to_sym - -GCOV_BUILD_PATH = File.join(PROJECT_BUILD_ROOT, GCOV_ROOT_NAME) -GCOV_BUILD_OUTPUT_PATH = File.join(GCOV_BUILD_PATH, "out") -GCOV_RESULTS_PATH = File.join(GCOV_BUILD_PATH, "results") -GCOV_DEPENDENCIES_PATH = File.join(GCOV_BUILD_PATH, "dependencies") -GCOV_ARTIFACTS_PATH = File.join(PROJECT_BUILD_ARTIFACTS_ROOT, GCOV_ROOT_NAME) -GCOV_REPORT_GENERATOR_PATH = File.join(GCOV_ARTIFACTS_PATH, "ReportGenerator") - -GCOV_ARTIFACTS_FILE_HTML = File.join(GCOV_ARTIFACTS_PATH, "GcovCoverageResults.html") -GCOV_ARTIFACTS_FILE_COBERTURA = File.join(GCOV_ARTIFACTS_PATH, "GcovCoverageCobertura.xml") -GCOV_ARTIFACTS_FILE_SONARQUBE = File.join(GCOV_ARTIFACTS_PATH, "GcovCoverageSonarQube.xml") -GCOV_ARTIFACTS_FILE_JSON = File.join(GCOV_ARTIFACTS_PATH, "GcovCoverage.json") - -GCOV_FILTER_EXCLUDE_PATHS = ['vendor', 'build', 'test', 'lib'] - -# gcovr supports regular expressions. -GCOV_FILTER_EXCLUDE = GCOV_FILTER_EXCLUDE_PATHS.map{|path| '^'.concat(*path).concat('.*')}.join('|') - -# ReportGenerator supports text with wildcard characters. -GCOV_REPORT_GENERATOR_FILE_FILTERS = GCOV_FILTER_EXCLUDE_PATHS.map{|path| File.join('-.', *path, '*')}.join(';') - -# Report Types -class ReportTypes - HTML_BASIC = "HtmlBasic" - HTML_DETAILED = "HtmlDetailed" - HTML_CHART = "HtmlChart" - HTML_INLINE = "HtmlInline" - HTML_INLINE_AZURE = "HtmlInlineAzure" - HTML_INLINE_AZURE_DARK = "HtmlInlineAzureDark" - MHTML = "MHtml" - TEXT = "Text" - COBERTURA = "Cobertura" - SONARQUBE = "SonarQube" - JSON = "JSON" - BADGES = "Badges" - CSV_SUMMARY = "CsvSummary" - LATEX = "Latex" - LATEX_SUMMARY = "LatexSummary" - PNG_CHART = "PngChart" - TEAM_CITY_SUMMARY = "TeamCitySummary" - LCOV = "lcov" - XML = "Xml" - XML_SUMMARY = "XmlSummary" -end diff --git a/test/unit-test/vendor/ceedling/plugins/gcov/lib/gcovr_reportinator.rb b/test/unit-test/vendor/ceedling/plugins/gcov/lib/gcovr_reportinator.rb deleted file mode 100644 index 5317c5d24..000000000 --- a/test/unit-test/vendor/ceedling/plugins/gcov/lib/gcovr_reportinator.rb +++ /dev/null @@ -1,331 +0,0 @@ -require 'reportinator_helper' - -class GcovrReportinator - - def initialize(system_objects) - @ceedling = system_objects - @reportinator_helper = ReportinatorHelper.new - end - - - # Generate the gcovr report(s) specified in the options. - def make_reports(opts) - # Get the gcovr version number. - gcovr_version_info = get_gcovr_version() - - # Build the common gcovr arguments. - args_common = args_builder_common(opts) - - if ((gcovr_version_info[0] == 4) && (gcovr_version_info[1] >= 2)) || (gcovr_version_info[0] > 4) - # gcovr version 4.2 and later supports generating multiple reports with a single call. - args = args_common - args += args_builder_cobertura(opts, false) - args += args_builder_sonarqube(opts, false) - args += args_builder_json(opts, true) - # As of gcovr version 4.2, the --html argument must appear last. - args += args_builder_html(opts, false) - - print "Creating gcov results report(s) in '#{GCOV_ARTIFACTS_PATH}'... " - STDOUT.flush - - # Generate the report(s). - run(args) - else - # gcovr version 4.1 and earlier supports HTML and Cobertura XML reports. - # It does not support SonarQube and JSON reports. - # Reports must also be generated separately. - args_cobertura = args_builder_cobertura(opts, true) - args_html = args_builder_html(opts, true) - - if args_html.length > 0 - print "Creating a gcov HTML report in '#{GCOV_ARTIFACTS_PATH}'... " - STDOUT.flush - - # Generate the HTML report. - run(args_common + args_html) - end - - if args_cobertura.length > 0 - print "Creating a gcov XML report in '#{GCOV_ARTIFACTS_PATH}'... " - STDOUT.flush - - # Generate the Cobertura XML report. - run(args_common + args_cobertura) - end - end - - # Determine if the gcovr text report is enabled. Defaults to disabled. - if is_report_enabled(opts, ReportTypes::TEXT) - make_text_report(opts, args_common) - end - end - - - def support_deprecated_options(opts) - # Support deprecated :html_report: and ":html_report_type: basic" options. - if !is_report_enabled(opts, ReportTypes::HTML_BASIC) && (opts[:gcov_html_report] || (opts[:gcov_html_report_type].is_a? String) && (opts[:gcov_html_report_type].casecmp("basic") == 0)) - opts[:gcov_reports].push(ReportTypes::HTML_BASIC) - end - - # Support deprecated ":html_report_type: detailed" option. - if !is_report_enabled(opts, ReportTypes::HTML_DETAILED) && (opts[:gcov_html_report_type].is_a? String) && (opts[:gcov_html_report_type].casecmp("detailed") == 0) - opts[:gcov_reports].push(ReportTypes::HTML_DETAILED) - end - - # Support deprecated :xml_report: option. - if opts[:gcov_xml_report] - opts[:gcov_reports].push(ReportTypes::COBERTURA) - end - - # Default to HTML basic report when no report types are defined. - if opts[:gcov_reports].empty? && opts[:gcov_html_report_type].nil? && opts[:gcov_xml_report].nil? - opts[:gcov_reports] = [ReportTypes::HTML_BASIC] - - puts "In your project.yml, define one or more of the" - puts "following to specify which reports to generate." - puts "For now, creating only an #{ReportTypes::HTML_BASIC} report." - puts "" - puts ":gcov:" - puts " :reports:" - puts " - #{ReportTypes::HTML_BASIC}" - puts " - #{ReportTypes::HTML_DETAILED}" - puts " - #{ReportTypes::TEXT}" - puts " - #{ReportTypes::COBERTURA}" - puts " - #{ReportTypes::SONARQUBE}" - puts " - #{ReportTypes::JSON}" - puts "" - end - end - - - private - - GCOVR_SETTING_PREFIX = "gcov_gcovr" - - # Build the gcovr report generation common arguments. - def args_builder_common(opts) - gcovr_opts = get_opts(opts) - - args = "" - args += "--root \"#{gcovr_opts[:report_root] || '.'}\" " - args += "--config \"#{gcovr_opts[:config_file]}\" " unless gcovr_opts[:config_file].nil? - args += "--filter \"#{gcovr_opts[:report_include]}\" " unless gcovr_opts[:report_include].nil? - args += "--exclude \"#{gcovr_opts[:report_exclude] || GCOV_FILTER_EXCLUDE}\" " - args += "--gcov-filter \"#{gcovr_opts[:gcov_filter]}\" " unless gcovr_opts[:gcov_filter].nil? - args += "--gcov-exclude \"#{gcovr_opts[:gcov_exclude]}\" " unless gcovr_opts[:gcov_exclude].nil? - args += "--exclude-directories \"#{gcovr_opts[:exclude_directories]}\" " unless gcovr_opts[:exclude_directories].nil? - args += "--branches " if gcovr_opts[:branches].nil? || gcovr_opts[:branches] # Defaults to enabled. - args += "--sort-uncovered " if gcovr_opts[:sort_uncovered] - args += "--sort-percentage " if gcovr_opts[:sort_percentage].nil? || gcovr_opts[:sort_percentage] # Defaults to enabled. - args += "--print-summary " if gcovr_opts[:print_summary] - args += "--gcov-executable \"#{gcovr_opts[:gcov_executable]}\" " unless gcovr_opts[:gcov_executable].nil? - args += "--exclude-unreachable-branches " if gcovr_opts[:exclude_unreachable_branches] - args += "--exclude-throw-branches " if gcovr_opts[:exclude_throw_branches] - args += "--use-gcov-files " if gcovr_opts[:use_gcov_files] - args += "--gcov-ignore-parse-errors " if gcovr_opts[:gcov_ignore_parse_errors] - args += "--keep " if gcovr_opts[:keep] - args += "--delete " if gcovr_opts[:delete] - args += "-j #{gcovr_opts[:num_parallel_threads]} " if !(gcovr_opts[:num_parallel_threads].nil?) && (gcovr_opts[:num_parallel_threads].is_a? Integer) - - [:fail_under_line, :fail_under_branch, :source_encoding, :object_directory].each do |opt| - unless gcovr_opts[opt].nil? - - value = gcovr_opts[opt] - if (opt == :fail_under_line) || (opt == :fail_under_branch) - if not value.is_a? Integer - puts "Option value #{opt} has to be an integer" - value = nil - elsif (value < 0) || (value > 100) - puts "Option value #{opt} has to be a percentage from 0 to 100" - value = nil - end - end - args += "--#{opt.to_s.gsub('_','-')} #{value} " unless value.nil? - end - end - - return args - end - - - # Build the gcovr Cobertura XML report generation arguments. - def args_builder_cobertura(opts, use_output_option=false) - gcovr_opts = get_opts(opts) - args = "" - - # Determine if the Cobertura XML report is enabled. Defaults to disabled. - if is_report_enabled(opts, ReportTypes::COBERTURA) - # Determine the Cobertura XML report file name. - artifacts_file_cobertura = GCOV_ARTIFACTS_FILE_COBERTURA - if !(gcovr_opts[:cobertura_artifact_filename].nil?) - artifacts_file_cobertura = File.join(GCOV_ARTIFACTS_PATH, gcovr_opts[:cobertura_artifact_filename]) - elsif !(gcovr_opts[:xml_artifact_filename].nil?) - artifacts_file_cobertura = File.join(GCOV_ARTIFACTS_PATH, gcovr_opts[:xml_artifact_filename]) - end - - args += "--xml-pretty " if gcovr_opts[:xml_pretty] || gcovr_opts[:cobertura_pretty] - args += "--xml #{use_output_option ? "--output " : ""} \"#{artifacts_file_cobertura}\" " - end - - return args - end - - - # Build the gcovr SonarQube report generation arguments. - def args_builder_sonarqube(opts, use_output_option=false) - gcovr_opts = get_opts(opts) - args = "" - - # Determine if the gcovr SonarQube XML report is enabled. Defaults to disabled. - if is_report_enabled(opts, ReportTypes::SONARQUBE) - # Determine the SonarQube XML report file name. - artifacts_file_sonarqube = GCOV_ARTIFACTS_FILE_SONARQUBE - if !(gcovr_opts[:sonarqube_artifact_filename].nil?) - artifacts_file_sonarqube = File.join(GCOV_ARTIFACTS_PATH, gcovr_opts[:sonarqube_artifact_filename]) - end - - args += "--sonarqube #{use_output_option ? "--output " : ""} \"#{artifacts_file_sonarqube}\" " - end - - return args - end - - - # Build the gcovr JSON report generation arguments. - def args_builder_json(opts, use_output_option=false) - gcovr_opts = get_opts(opts) - args = "" - - # Determine if the gcovr JSON report is enabled. Defaults to disabled. - if is_report_enabled(opts, ReportTypes::JSON) - # Determine the JSON report file name. - artifacts_file_json = GCOV_ARTIFACTS_FILE_JSON - if !(gcovr_opts[:json_artifact_filename].nil?) - artifacts_file_json = File.join(GCOV_ARTIFACTS_PATH, gcovr_opts[:json_artifact_filename]) - end - - args += "--json-pretty " if gcovr_opts[:json_pretty] - # Note: In gcovr 4.2, the JSON report is output only when the --output option is specified. - # Hopefully we can remove --output after a future gcovr release. - args += "--json #{use_output_option ? "--output " : ""} \"#{artifacts_file_json}\" " - end - - return args - end - - - # Build the gcovr HTML report generation arguments. - def args_builder_html(opts, use_output_option=false) - gcovr_opts = get_opts(opts) - args = "" - - # Determine if the gcovr HTML report is enabled. Defaults to enabled. - html_enabled = (opts[:gcov_html_report].nil? && opts[:gcov_reports].empty?) || - is_report_enabled(opts, ReportTypes::HTML_BASIC) || - is_report_enabled(opts, ReportTypes::HTML_DETAILED) - - if html_enabled - # Determine the HTML report file name. - artifacts_file_html = GCOV_ARTIFACTS_FILE_HTML - if !(gcovr_opts[:html_artifact_filename].nil?) - artifacts_file_html = File.join(GCOV_ARTIFACTS_PATH, gcovr_opts[:html_artifact_filename]) - end - - is_html_report_type_detailed = (opts[:gcov_html_report_type].is_a? String) && (opts[:gcov_html_report_type].casecmp("detailed") == 0) - - args += "--html-details " if is_html_report_type_detailed || is_report_enabled(opts, ReportTypes::HTML_DETAILED) - args += "--html-title \"#{gcovr_opts[:html_title]}\" " unless gcovr_opts[:html_title].nil? - args += "--html-absolute-paths " if !(gcovr_opts[:html_absolute_paths].nil?) && gcovr_opts[:html_absolute_paths] - args += "--html-encoding \"#{gcovr_opts[:html_encoding]}\" " unless gcovr_opts[:html_encoding].nil? - - [:html_medium_threshold, :html_high_threshold].each do |opt| - args += "--#{opt.to_s.gsub('_','-')} #{gcovr_opts[opt]} " unless gcovr_opts[opt].nil? - end - - # The following option must be appended last for gcovr version <= 4.2 to properly work. - args += "--html #{use_output_option ? "--output " : ""} \"#{artifacts_file_html}\" " - end - - return args - end - - - # Generate a gcovr text report. - def make_text_report(opts, args_common) - gcovr_opts = get_opts(opts) - args_text = "" - message_text = "Creating a gcov text report" - - if !(gcovr_opts[:text_artifact_filename].nil?) - artifacts_file_txt = File.join(GCOV_ARTIFACTS_PATH, gcovr_opts[:text_artifact_filename]) - args_text += "--output \"#{artifacts_file_txt}\" " - message_text += " in '#{GCOV_ARTIFACTS_PATH}'... " - else - message_text += "... " - end - - print message_text - STDOUT.flush - - # Generate the text report. - run(args_common + args_text) - end - - - # Get the gcovr options from the project options. - def get_opts(opts) - return opts[GCOVR_SETTING_PREFIX.to_sym] || {} - end - - - # Run gcovr with the given arguments. - def run(args) - begin - command = @ceedling[:tool_executor].build_command_line(TOOLS_GCOV_GCOVR_POST_REPORT, [], args) - shell_result = @ceedling[:tool_executor].exec(command[:line], command[:options]) - @reportinator_helper.print_shell_result(shell_result) - rescue - # handle any unforeseen issues with called tool - exitcode = $?.exitstatus - show_gcovr_message(exitcode) - exit(exitcode) - end - end - - - # Get the gcovr version number as components. - # Returns [major, minor]. - def get_gcovr_version() - version_number_major = 0 - version_number_minor = 0 - - command = @ceedling[:tool_executor].build_command_line(TOOLS_GCOV_GCOVR_POST_REPORT, [], "--version") - shell_result = @ceedling[:tool_executor].exec(command[:line], command[:options]) - version_number_match_data = shell_result[:output].match(/gcovr ([0-9]+)\.([0-9]+)/) - - if !(version_number_match_data.nil?) && !(version_number_match_data[1].nil?) && !(version_number_match_data[2].nil?) - version_number_major = version_number_match_data[1].to_i - version_number_minor = version_number_match_data[2].to_i - end - - return version_number_major, version_number_minor - end - - - # Show a more human-friendly message on gcovr return code - def show_gcovr_message(exitcode) - if ((exitcode & 2) == 2) - puts "The line coverage is less than the minimum" - end - if ((exitcode & 4) == 4) - puts "The branch coverage is less than the minimum" - end - end - - - # Returns true if the given report type is enabled, otherwise returns false. - def is_report_enabled(opts, report_type) - return !(opts.nil?) && !(opts[:gcov_reports].nil?) && (opts[:gcov_reports].map(&:upcase).include? report_type.upcase) - end - -end diff --git a/test/unit-test/vendor/ceedling/plugins/gcov/lib/reportgenerator_reportinator.rb b/test/unit-test/vendor/ceedling/plugins/gcov/lib/reportgenerator_reportinator.rb deleted file mode 100644 index 96cf89163..000000000 --- a/test/unit-test/vendor/ceedling/plugins/gcov/lib/reportgenerator_reportinator.rb +++ /dev/null @@ -1,195 +0,0 @@ -require 'benchmark' -require 'reportinator_helper' - -class ReportGeneratorReportinator - - def initialize(system_objects) - @ceedling = system_objects - @reportinator_helper = ReportinatorHelper.new - end - - - # Generate the ReportGenerator report(s) specified in the options. - def make_reports(opts) - shell_result = nil - total_time = Benchmark.realtime do - rg_opts = get_opts(opts) - - print "Creating gcov results report(s) with ReportGenerator in '#{GCOV_REPORT_GENERATOR_PATH}'... " - STDOUT.flush - - # Cleanup any existing .gcov files to avoid reporting old coverage results. - for gcov_file in Dir.glob("*.gcov") - File.delete(gcov_file) - end - - # Use a custom gcov executable, if specified. - GCOV_TOOL_CONFIG[:executable] = rg_opts[:gcov_executable] unless rg_opts[:gcov_executable].nil? - - # Avoid running gcov on the mock, test, unity, and cexception gcov notes files to save time. - gcno_exclude_str = "#{opts[:cmock_mock_prefix]}.*" - gcno_exclude_str += "|#{opts[:project_test_file_prefix]}.*" - gcno_exclude_str += "|#{VENDORS_FILES.join('|')}" - - # Avoid running gcov on custom specified .gcno files. - if !(rg_opts.nil?) && !(rg_opts[:gcov_exclude].nil?) && !(rg_opts[:gcov_exclude].empty?) - for gcno_exclude_expression in rg_opts[:gcov_exclude] - if !(gcno_exclude_expression.nil?) && !(gcno_exclude_expression.empty?) - # We want to filter .gcno files, not .gcov files. - # We will generate .gcov files from .gcno files. - gcno_exclude_expression = gcno_exclude_expression.chomp("\\.gcov") - gcno_exclude_expression = gcno_exclude_expression.chomp(".gcov") - # The .gcno extension will be added later as we create the regex. - gcno_exclude_expression = gcno_exclude_expression.chomp("\\.gcno") - gcno_exclude_expression = gcno_exclude_expression.chomp(".gcno") - # Append the custom expression. - gcno_exclude_str += "|#{gcno_exclude_expression}" - end - end - end - - gcno_exclude_regex = /(\/|\\)(#{gcno_exclude_str})\.gcno/ - - # Generate .gcov files by running gcov on gcov notes files (*.gcno). - for gcno_filepath in Dir.glob(File.join(GCOV_BUILD_PATH, "**", "*.gcno")) - match_data = gcno_filepath.match(gcno_exclude_regex) - if match_data.nil? || (match_data[1].nil? && match_data[1].nil?) - # Ensure there is a matching gcov data file. - if File.file?(gcno_filepath.gsub(".gcno", ".gcda")) - run_gcov("\"#{gcno_filepath}\"") - end - end - end - - if Dir.glob("*.gcov").length > 0 - # Build the command line arguments. - args = args_builder(opts) - - # Generate the report(s). - shell_result = run(args) - else - puts "\nWarning: No matching .gcno coverage files found." - end - - # Cleanup .gcov files. - for gcov_file in Dir.glob("*.gcov") - File.delete(gcov_file) - end - end - - if shell_result - shell_result[:time] = total_time - @reportinator_helper.print_shell_result(shell_result) - end - end - - - private - - # A dictionary of report types defined in this plugin to ReportGenerator report types. - REPORT_TYPE_TO_REPORT_GENERATOR_REPORT_NAME = { - ReportTypes::HTML_BASIC.upcase => "HtmlSummary", - ReportTypes::HTML_DETAILED.upcase => "Html", - ReportTypes::HTML_CHART.upcase => "HtmlChart", - ReportTypes::HTML_INLINE.upcase => "HtmlInline", - ReportTypes::HTML_INLINE_AZURE.upcase => "HtmlInline_AzurePipelines", - ReportTypes::HTML_INLINE_AZURE_DARK.upcase => "HtmlInline_AzurePipelines_Dark", - ReportTypes::MHTML.upcase => "MHtml", - ReportTypes::TEXT.upcase => "TextSummary", - ReportTypes::COBERTURA.upcase => "Cobertura", - ReportTypes::SONARQUBE.upcase => "SonarQube", - ReportTypes::BADGES.upcase => "Badges", - ReportTypes::CSV_SUMMARY.upcase => "CsvSummary", - ReportTypes::LATEX.upcase => "Latex", - ReportTypes::LATEX_SUMMARY.upcase => "LatexSummary", - ReportTypes::PNG_CHART.upcase => "PngChart", - ReportTypes::TEAM_CITY_SUMMARY.upcase => "TeamCitySummary", - ReportTypes::LCOV.upcase => "lcov", - ReportTypes::XML.upcase => "Xml", - ReportTypes::XML_SUMMARY.upcase => "XmlSummary", - } - - REPORT_GENERATOR_SETTING_PREFIX = "gcov_report_generator" - - # Deep clone the gcov tool config, so we can modify it locally if specified via options. - GCOV_TOOL_CONFIG = Marshal.load(Marshal.dump(TOOLS_GCOV_GCOV_POST_REPORT)) - - # Build the ReportGenerator arguments. - def args_builder(opts) - rg_opts = get_opts(opts) - report_type_count = 0 - - args = "" - args += "\"-reports:*.gcov\" " - args += "\"-targetdir:\"#{GCOV_REPORT_GENERATOR_PATH}\"\" " - - # Build the report types argument. - if !(opts.nil?) && !(opts[:gcov_reports].nil?) && !(opts[:gcov_reports].empty?) - args += "\"-reporttypes:" - - for report_type in opts[:gcov_reports] - rg_report_type = REPORT_TYPE_TO_REPORT_GENERATOR_REPORT_NAME[report_type.upcase] - if !(rg_report_type.nil?) - args += rg_report_type + ";" - report_type_count = report_type_count + 1 - end - end - - # Removing trailing ';' after the last report type. - args = args.chomp(";") - - # Append a space separator after the report type. - args += "\" " - end - - # Build the source directories argument. - args += "\"-sourcedirs:.;" - if !(opts[:collection_paths_source].nil?) - args += opts[:collection_paths_source].join(';') - end - args = args.chomp(";") - args += "\" " - - args += "\"-historydir:#{rg_opts[:history_directory]}\" " unless rg_opts[:history_directory].nil? - args += "\"-plugins:#{rg_opts[:plugins]}\" " unless rg_opts[:plugins].nil? - args += "\"-assemblyfilters:#{rg_opts[:assembly_filters]}\" " unless rg_opts[:assembly_filters].nil? - args += "\"-classfilters:#{rg_opts[:class_filters]}\" " unless rg_opts[:class_filters].nil? - file_filters = rg_opts[:file_filters] || @ceedling[:tool_executor_helper].osify_path_separators(GCOV_REPORT_GENERATOR_FILE_FILTERS) - args += "\"-filefilters:#{file_filters}\" " - args += "\"-verbosity:#{rg_opts[:verbosity] || "Warning"}\" " - args += "\"-tag:#{rg_opts[:tag]}\" " unless rg_opts[:tag].nil? - args += "\"settings:createSubdirectoryForAllReportTypes=true\" " unless report_type_count <= 1 - args += "\"settings:numberOfReportsParsedInParallel=#{rg_opts[:num_parallel_threads]}\" " unless rg_opts[:num_parallel_threads].nil? - args += "\"settings:numberOfReportsMergedInParallel=#{rg_opts[:num_parallel_threads]}\" " unless rg_opts[:num_parallel_threads].nil? - - # Append custom arguments. - if !(rg_opts[:custom_args].nil?) && !(rg_opts[:custom_args].empty?) - for custom_arg in rg_opts[:custom_args] - args += "\"#{custom_arg}\" " unless custom_arg.nil? || custom_arg.empty? - end - end - - return args - end - - - # Get the ReportGenerator options from the project options. - def get_opts(opts) - return opts[REPORT_GENERATOR_SETTING_PREFIX.to_sym] || {} - end - - - # Run ReportGenerator with the given arguments. - def run(args) - command = @ceedling[:tool_executor].build_command_line(TOOLS_GCOV_REPORTGENERATOR_POST_REPORT, [], args) - return @ceedling[:tool_executor].exec(command[:line], command[:options]) - end - - - # Run gcov with the given arguments. - def run_gcov(args) - command = @ceedling[:tool_executor].build_command_line(GCOV_TOOL_CONFIG, [], args) - return @ceedling[:tool_executor].exec(command[:line], command[:options]) - end - -end diff --git a/test/unit-test/vendor/ceedling/plugins/gcov/lib/reportinator_helper.rb b/test/unit-test/vendor/ceedling/plugins/gcov/lib/reportinator_helper.rb deleted file mode 100644 index 10a0a6c5c..000000000 --- a/test/unit-test/vendor/ceedling/plugins/gcov/lib/reportinator_helper.rb +++ /dev/null @@ -1,15 +0,0 @@ - -class ReportinatorHelper - - # Output the shell result to the console. - def print_shell_result(shell_result) - if !(shell_result.nil?) - puts "Done in %.3f seconds." % shell_result[:time] - - if !(shell_result[:output].nil?) && (shell_result[:output].length > 0) - puts shell_result[:output] - end - end - end - -end diff --git a/test/unit-test/vendor/ceedling/plugins/json_tests_report/README.md b/test/unit-test/vendor/ceedling/plugins/json_tests_report/README.md deleted file mode 100644 index b383492e2..000000000 --- a/test/unit-test/vendor/ceedling/plugins/json_tests_report/README.md +++ /dev/null @@ -1,36 +0,0 @@ -json_tests_report -================= - -## Overview - -The json_tests_report plugin creates a JSON file of test results, which is -handy for Continuous Integration build servers or as input into other -reporting tools. The JSON file is output to the appropriate -`<build_root>/artifacts/` directory (e.g. `artifacts/test/` for test tasks, -`artifacts/gcov/` for gcov, or `artifacts/bullseye/` for bullseye runs). - -## Setup - -Enable the plugin in your project.yml by adding `json_tests_report` to the list -of enabled plugins. - -``` YAML -:plugins: - :enabled: - - json_tests_report -``` - -## Configuration - -Optionally configure the output / artifact filename in your project.yml with -the `artifact_filename` configuration option. The default filename is -`report.json`. - -You can also configure the path that this artifact is stored. This can be done -by setting `path`. The default is that it will be placed in a subfolder under -the `build` directory. - -``` YAML -:json_tests_report: - :artifact_filename: report_spectuluarly.json -``` diff --git a/test/unit-test/vendor/ceedling/plugins/json_tests_report/lib/json_tests_report.rb b/test/unit-test/vendor/ceedling/plugins/json_tests_report/lib/json_tests_report.rb deleted file mode 100644 index f09339ee2..000000000 --- a/test/unit-test/vendor/ceedling/plugins/json_tests_report/lib/json_tests_report.rb +++ /dev/null @@ -1,83 +0,0 @@ -require 'ceedling/plugin' -require 'ceedling/constants' -require 'json' - -class JsonTestsReport < Plugin - def setup - @results_list = {} - @test_counter = 0 - end - - def post_test_fixture_execute(arg_hash) - context = arg_hash[:context] - - @results_list[context] = [] if @results_list[context].nil? - - @results_list[context] << arg_hash[:result_file] - end - - def post_build - @results_list.each_key do |context| - results = @ceedling[:plugin_reportinator].assemble_test_results(@results_list[context]) - - artifact_filename = @ceedling[:configurator].project_config_hash[:json_tests_report_artifact_filename] || 'report.json' - artifact_fullpath = @ceedling[:configurator].project_config_hash[:json_tests_report_path] || File.join(PROJECT_BUILD_ARTIFACTS_ROOT, context.to_s) - file_path = File.join(artifact_fullpath, artifact_filename) - - @ceedling[:file_wrapper].open(file_path, 'w') do |f| - @test_counter = 1 - - json = { - "FailedTests" => write_failures(results[:failures]), - "PassedTests" => write_tests(results[:successes]), - "IgnoredTests" => write_tests(results[:ignores]), - "Summary" => write_statistics(results[:counts]) - } - - f << JSON.pretty_generate(json) - end - end - end - - private - - def write_failures(results) - retval = [] - results.each do |result| - result[:collection].each do |item| - @test_counter += 1 - retval << { - "file" => File.join(result[:source][:path], result[:source][:file]), - "test" => item[:test], - "line" => item[:line], - "message" => item[:message] - } - end - end - return retval.uniq - end - - def write_tests(results) - retval = [] - results.each do |result| - result[:collection].each do |item| - @test_counter += 1 - retval << { - "file" => File.join(result[:source][:path], result[:source][:file]), - "test" => item[:test] - } - end - end - return retval - end - - def write_statistics(counts) - return { - "total_tests" => counts[:total], - "passed" => (counts[:total] - counts[:ignored] - counts[:failed]), - "ignored" => counts[:ignored], - "failures" => counts[:failed] - } - end - -end diff --git a/test/unit-test/vendor/ceedling/plugins/junit_tests_report/README.md b/test/unit-test/vendor/ceedling/plugins/junit_tests_report/README.md deleted file mode 100644 index 1259fd668..000000000 --- a/test/unit-test/vendor/ceedling/plugins/junit_tests_report/README.md +++ /dev/null @@ -1,36 +0,0 @@ -junit_tests_report -==================== - -## Overview - -The junit_tests_report plugin creates an XML file of test results in JUnit -format, which is handy for Continuous Integration build servers or as input -into other reporting tools. The XML file is output to the appropriate -`<build_root>/artifacts/` directory (e.g. `artifacts/test/` for test tasks, -`artifacts/gcov/` for gcov, or `artifacts/bullseye/` for bullseye runs). - -## Setup - -Enable the plugin in your project.yml by adding `junit_tests_report` -to the list of enabled plugins. - -``` YAML -:plugins: - :enabled: - - junit_tests_report -``` - -## Configuration - -Optionally configure the output / artifact filename in your project.yml with -the `artifact_filename` configuration option. The default filename is -`report.xml`. - -You can also configure the path that this artifact is stored. This can be done -by setting `path`. The default is that it will be placed in a subfolder under -the `build` directory. - -``` YAML -:junit_tests_report: - :artifact_filename: report_junit.xml -``` diff --git a/test/unit-test/vendor/ceedling/plugins/junit_tests_report/lib/junit_tests_report.rb b/test/unit-test/vendor/ceedling/plugins/junit_tests_report/lib/junit_tests_report.rb deleted file mode 100644 index 310439380..000000000 --- a/test/unit-test/vendor/ceedling/plugins/junit_tests_report/lib/junit_tests_report.rb +++ /dev/null @@ -1,134 +0,0 @@ -require 'ceedling/plugin' -require 'ceedling/constants' - -class JunitTestsReport < Plugin - - def setup - @results_list = {} - @test_counter = 0 - @time_result = [] - end - - def post_test_fixture_execute(arg_hash) - context = arg_hash[:context] - - @results_list[context] = [] if (@results_list[context].nil?) - - @results_list[context] << arg_hash[:result_file] - @time_result << arg_hash[:shell_result][:time] - - end - - def post_build - @results_list.each_key do |context| - results = @ceedling[:plugin_reportinator].assemble_test_results(@results_list[context]) - - artifact_filename = @ceedling[:configurator].project_config_hash[:junit_tests_report_artifact_filename] || 'report.xml' - artifact_fullpath = @ceedling[:configurator].project_config_hash[:junit_tests_report_path] || File.join(PROJECT_BUILD_ARTIFACTS_ROOT, context.to_s) - file_path = File.join(artifact_fullpath, artifact_filename) - - @ceedling[:file_wrapper].open( file_path, 'w' ) do |f| - @testsuite_counter = 0 - @testcase_counter = 0 - suites = reorganise_results( results ) - - write_header( results, f ) - suites.each{|suite| write_suite( suite, f ) } - write_footer( f ) - end - end - end - - private - - def write_header( results, stream ) - results[:counts][:time] = @time_result.reduce(0, :+) - stream.puts '<?xml version="1.0" encoding="utf-8" ?>' - stream.puts('<testsuites tests="%<total>d" failures="%<failed>d" time="%<time>.3f">' % results[:counts]) - end - - def write_footer( stream ) - stream.puts '</testsuites>' - end - - def reorganise_results( results ) - # Reorganise the output by test suite instead of by result - suites = Hash.new{ |h,k| h[k] = {collection: [], total: 0, success: 0, failed: 0, ignored: 0, errors: 0, stdout: []} } - results[:successes].each do |result| - source = result[:source] - name = source[:file].sub(/\..{1,4}$/, "") - suites[name][:collection] += result[:collection].map{|test| test.merge(result: :success)} - suites[name][:total] += result[:collection].length - suites[name][:success] += result[:collection].length - end - results[:failures].each do |result| - source = result[:source] - name = source[:file].sub(/\..{1,4}$/, "") - suites[name][:collection] += result[:collection].map{|test| test.merge(result: :failed)} - suites[name][:total] += result[:collection].length - suites[name][:failed] += result[:collection].length - end - results[:ignores].each do |result| - source = result[:source] - name = source[:file].sub(/\..{1,4}$/, "") - suites[name][:collection] += result[:collection].map{|test| test.merge(result: :ignored)} - suites[name][:total] += result[:collection].length - suites[name][:ignored] += result[:collection].length - end - results[:stdout].each do |result| - source = result[:source] - name = source[:file].sub(/\..{1,4}$/, "") - suites[name][:stdout] += result[:collection] - end - suites.map{|name, data| data.merge(name: name) } - end - - def write_suite( suite, stream ) - suite[:time] = @time_result.shift - stream.puts(' <testsuite name="%<name>s" tests="%<total>d" failures="%<failed>d" skipped="%<ignored>d" errors="%<errors>d" time="%<time>.3f">' % suite) - - suite[:collection].each do |test| - write_test( test, stream ) - end - - unless suite[:stdout].empty? - stream.puts(' <system-out>') - suite[:stdout].each do |line| - line.gsub!(/&/, '&') - line.gsub!(/</, '<') - line.gsub!(/>/, '>') - line.gsub!(/"/, '"') - line.gsub!(/'/, ''') - stream.puts(line) - end - stream.puts(' </system-out>') - end - - stream.puts(' </testsuite>') - end - - def write_test( test, stream ) - test[:test].gsub!(/&/, '&') - test[:test].gsub!(/</, '<') - test[:test].gsub!(/>/, '>') - test[:test].gsub!(/"/, '"') - test[:test].gsub!(/'/, ''') - - case test[:result] - when :success - stream.puts(' <testcase name="%<test>s" time="%<unity_test_time>.3f"/>' % test) - when :failed - stream.puts(' <testcase name="%<test>s" time="%<unity_test_time>.3f">' % test) - if test[:message].empty? - stream.puts(' <failure />') - else - stream.puts(' <failure message="%s" />' % test[:message]) - end - stream.puts(' </testcase>') - when :ignored - stream.puts(' <testcase name="%<test>s" time="%<unity_test_time>.3f">' % test) - stream.puts(' <skipped />') - stream.puts(' </testcase>') - end - end -end diff --git a/test/unit-test/vendor/ceedling/plugins/module_generator/README.md b/test/unit-test/vendor/ceedling/plugins/module_generator/README.md deleted file mode 100644 index c7e982352..000000000 --- a/test/unit-test/vendor/ceedling/plugins/module_generator/README.md +++ /dev/null @@ -1,117 +0,0 @@ -ceedling-module-generator -========================= - -## Overview - -The module_generator plugin adds a pair of new commands to Ceedling, allowing -you to make or remove modules according to predefined templates. WIth a single call, -Ceedling can generate a source, header, and test file for a new module. If given a -pattern, it can even create a series of submodules to support specific design patterns. -Finally, it can just as easily remove related modules, avoiding the need to delete -each individually. - -Let's say, for example, that you want to create a single module named `MadScience`. - -``` -ceedling module:create[MadScience] -``` - -It says we're speaking to the module plugin, and we want to create a new module. The -name of that module is between the brackets. It will keep this case, unless you have -specified a different default (see configuration). It will create three files: -`MadScience.c`, `MadScience.h`, and `TestMadScience.c`. *NOTE* that it is important that -there are no spaces between the brackets. We know, it's annoying... but it's the rules. - -You can also create an entire pattern of files. To do that, just add a second argument -to the pattern ID. Something like this: - -``` -ceedling module:create[SecretLair,mch] -``` - -In this example, we'd create 9 files total: 3 headers, 3 source files, and 3 test files. These -files would be named `SecretLairModel`, `SecretLairConductor`, and `SecretLairHardware`. Isn't -that nice? - -Similarly, you can create stubs for all functions in a header file just by making a single call -to your handy `stub` feature, like this: - -``` -ceedling module:stub[SecretLair] -``` - -This call will look in SecretLair.h and will generate a file SecretLair.c that contains a stub -for each function declared in the header! Even better, if SecretLair.c already exists, it will -add only new functions, leaving your existing calls alone so that it doesn't cause any problems. - -## Configuration - -Enable the plugin in your project.yml by adding `module_generator` -to the list of enabled plugins. - -Then, like much of Ceedling, you can just run as-is with the defaults, or you can override those -defaults for your own needs. For example, new source and header files will be automatically -placed in the `src/` folder while tests will go in the `test/` folder. That's great if your project -follows the default ceedling structure... but what if you have a different structure? - -``` -:module_generator: - :project_root: ./ - :source_root: source/ - :inc_root: includes/ - :test_root: tests/ -``` - -Now I've redirected the location where modules are going to be generated. - -### Includes - -You can make it so that all of your files are generated with a standard include list. This is done -by adding to the `:includes` array. For example: - -``` -:module_generator: - :includes: - :tst: - - defs.h - - board.h - :src: - - board.h -``` - -### Boilerplates - -You can specify the actual boilerplate used for each of your files. This is the handy place to -put that corporate copyright notice (or maybe a copyleft notice, if that's your preference?) - -``` -:module_generator: - :boilerplates: | - /*************************** - * This file is Awesome. * - * That is All. * - ***************************/ -``` - -### Test Defines - -You can specify the "#ifdef TEST" at the top of the test files with a custom define. -This example will put a "#ifdef CEEDLING_TEST" at the top of the test files. - -``` -:module_generator: - :test_define: CEEDLING_TEST -``` - -### Naming Convention - -Finally, you can force a particular naming convention. Even if someone calls the generator -with something like `MyNewModule`, if they have the naming convention set to `:caps`, it will -generate files like `MY_NEW_MODULE.c`. This keeps everyone on your team behaving the same way. - -Your options are as follows: - - - `:bumpy` - BumpyFilesLooksLikeSo - - `:camel` - camelFilesAreSimilarButStartLow - - `:snake` - snake_case_is_all_lower_and_uses_underscores - - `:caps` - CAPS_FEELS_LIKE_YOU_ARE_SCREAMING diff --git a/test/unit-test/vendor/ceedling/plugins/module_generator/config/module_generator.yml b/test/unit-test/vendor/ceedling/plugins/module_generator/config/module_generator.yml deleted file mode 100644 index b90afd0ff..000000000 --- a/test/unit-test/vendor/ceedling/plugins/module_generator/config/module_generator.yml +++ /dev/null @@ -1,4 +0,0 @@ -:module_generator: - :project_root: ./ - :source_root: src/ - :test_root: test/ diff --git a/test/unit-test/vendor/ceedling/plugins/module_generator/lib/module_generator.rb b/test/unit-test/vendor/ceedling/plugins/module_generator/lib/module_generator.rb deleted file mode 100644 index d14288c36..000000000 --- a/test/unit-test/vendor/ceedling/plugins/module_generator/lib/module_generator.rb +++ /dev/null @@ -1,80 +0,0 @@ -require 'ceedling/plugin' -require 'ceedling/constants' -require 'erb' -require 'fileutils' - -class ModuleGenerator < Plugin - - attr_reader :config - - def create(module_name, optz={}) - - require "generate_module.rb" #From Unity Scripts - - if ((!optz.nil?) && (optz[:destroy])) - UnityModuleGenerator.new( divine_options(optz) ).destroy(module_name) - else - UnityModuleGenerator.new( divine_options(optz) ).generate(module_name) - end - end - - def stub_from_header(module_name, optz={}) - require "cmock.rb" #From CMock - stuboptz = divine_options(optz) - pathname = optz[:path_inc] || optz[:path_src] || "src" - filename = File.expand_path(optz[:module_root_path], File.join(pathname, module_name + ".h")) - CMock.new(stuboptz).setup_skeletons(filename) - end - - private - - def divine_options(optz={}) - unity_generator_options = - { - :path_src => ((defined? MODULE_GENERATOR_SOURCE_ROOT ) ? MODULE_GENERATOR_SOURCE_ROOT.gsub('\\', '/').sub(/^\//, '').sub(/\/$/, '') : "src" ), - :path_inc => ((defined? MODULE_GENERATOR_INC_ROOT ) ? - MODULE_GENERATOR_INC_ROOT.gsub('\\', '/').sub(/^\//, '').sub(/\/$/, '') - : (defined? MODULE_GENERATOR_SOURCE_ROOT ) ? - MODULE_GENERATOR_SOURCE_ROOT.gsub('\\', '/').sub(/^\//, '').sub(/\/$/, '') - : "src" ), - :path_tst => ((defined? MODULE_GENERATOR_TEST_ROOT ) ? MODULE_GENERATOR_TEST_ROOT.gsub( '\\', '/').sub(/^\//, '').sub(/\/$/, '') : "test" ), - :pattern => optz[:pattern], - :test_prefix => ((defined? PROJECT_TEST_FILE_PREFIX ) ? PROJECT_TEST_FILE_PREFIX : "Test" ), - :mock_prefix => ((defined? CMOCK_MOCK_PREFIX ) ? CMOCK_MOCK_PREFIX : "Mock" ), - :includes => ((defined? MODULE_GENERATOR_INCLUDES ) ? MODULE_GENERATOR_INCLUDES : {} ), - :boilerplates => ((defined? MODULE_GENERATOR_BOILERPLATES) ? MODULE_GENERATOR_BOILERPLATES : {} ), - :naming => ((defined? MODULE_GENERATOR_NAMING ) ? MODULE_GENERATOR_NAMING : nil ), - :update_svn => ((defined? MODULE_GENERATOR_UPDATE_SVN ) ? MODULE_GENERATOR_UPDATE_SVN : false ), - :skeleton_path=> ((defined? MODULE_GENERATOR_SOURCE_ROOT ) ? MODULE_GENERATOR_SOURCE_ROOT.gsub('\\', '/').sub(/^\//, '').sub(/\/$/, '') : "src" ), - :test_define => ((defined? MODULE_GENERATOR_TEST_DEFINE ) ? MODULE_GENERATOR_TEST_DEFINE : "TEST" ), - } - - # Read Boilerplate template file. - if (defined? MODULE_GENERATOR_BOILERPLATE_FILES) - - bf = MODULE_GENERATOR_BOILERPLATE_FILES - - if !bf[:src].nil? && File.exists?(bf[:src]) - unity_generator_options[:boilerplates][:src] = File.read(bf[:src]) - end - - if !bf[:inc].nil? && File.exists?(bf[:inc]) - unity_generator_options[:boilerplates][:inc] = File.read(bf[:inc]) - end - - if !bf[:tst].nil? && File.exists?(bf[:tst]) - unity_generator_options[:boilerplates][:tst] = File.read(bf[:tst]) - end - end - - # If using "create[<module_root>:<module_name>]" option from command line. - unless optz[:module_root_path].to_s.empty? - unity_generator_options[:path_src] = File.join(optz[:module_root_path], unity_generator_options[:path_src]) - unity_generator_options[:path_inc] = File.join(optz[:module_root_path], unity_generator_options[:path_inc]) - unity_generator_options[:path_tst] = File.join(optz[:module_root_path], unity_generator_options[:path_tst]) - end - - return unity_generator_options - end - -end diff --git a/test/unit-test/vendor/ceedling/plugins/module_generator/module_generator.rake b/test/unit-test/vendor/ceedling/plugins/module_generator/module_generator.rake deleted file mode 100644 index f4ed9f113..000000000 --- a/test/unit-test/vendor/ceedling/plugins/module_generator/module_generator.rake +++ /dev/null @@ -1,62 +0,0 @@ - -namespace :module do - module_root_separator = ":" - - desc "Generate module (source, header and test files)" - task :create, :module_path do |t, args| - files = [args[:module_path]] + (args.extras || []) - optz = { :module_root_path => "" } - ["dh", "dih", "mch", "mvp", "src", "test"].each do |pat| - p = files.delete(pat) - optz[:pattern] = p unless p.nil? - end - files.each do |v| - module_root_path, module_name = v.split(module_root_separator, 2) - if module_name - optz[:module_root_path] = module_root_path - v = module_name - end - if (v =~ /^test_?/i) - # If the name of the file starts with test, automatically treat it as one - @ceedling[:module_generator].create(v.sub(/^test_?/i,''), optz.merge({:pattern => 'test'})) - else - # Otherwise, go through the normal procedure - @ceedling[:module_generator].create(v, optz) - end - end - end - - desc "Generate module stubs from header" - task :stub, :module_path do |t, args| - files = [args[:module_path]] + (args.extras || []) - optz = { :module_root_path => "" } - files.each do |v| - module_root_path, module_name = v.split(module_root_separator, 2) - if module_name - optz[:module_root_path] = module_root_path - v = module_name - end - # Otherwise, go through the normal procedure - @ceedling[:module_generator].stub_from_header(v, optz) - end - end - - desc "Destroy module (source, header and test files)" - task :destroy, :module_path do |t, args| - files = [args[:module_path]] + (args.extras || []) - optz = { :destroy => true, :module_root_path => "" } - ["dh", "dih", "mch", "mvp", "src", "test"].each do |pat| - p = files.delete(pat) - optz[:pattern] = p unless p.nil? - end - files.each do |v| - module_root_path, module_name = v.split(module_root_separator, 2) - if module_name - optz[:module_root_path] = module_root_path - v = module_name - end - @ceedling[:module_generator].create(v, optz) - end - end - -end diff --git a/test/unit-test/vendor/ceedling/plugins/raw_output_report/README.md b/test/unit-test/vendor/ceedling/plugins/raw_output_report/README.md deleted file mode 100644 index 330e87d39..000000000 --- a/test/unit-test/vendor/ceedling/plugins/raw_output_report/README.md +++ /dev/null @@ -1,19 +0,0 @@ -ceedling-raw-output-report -========================== - -## Overview - -The raw-output-report allows you to capture all the output from the called -tools in a single document, so you can trace back through it later. This is -useful for debugging... but can eat through memory quickly if left running. - -## Setup - -Enable the plugin in your project.yml by adding `raw_output_report` -to the list of enabled plugins. - -``` YAML -:plugins: - :enabled: - - raw_output_report -``` diff --git a/test/unit-test/vendor/ceedling/plugins/raw_output_report/lib/raw_output_report.rb b/test/unit-test/vendor/ceedling/plugins/raw_output_report/lib/raw_output_report.rb deleted file mode 100644 index 014e67714..000000000 --- a/test/unit-test/vendor/ceedling/plugins/raw_output_report/lib/raw_output_report.rb +++ /dev/null @@ -1,41 +0,0 @@ -require 'ceedling/plugin' -require 'ceedling/constants' - -class RawOutputReport < Plugin - def setup - @log_paths = {} - end - - def post_test_fixture_execute(arg_hash) - output = strip_output(arg_hash[:shell_result][:output]) - write_raw_output_log(arg_hash, output) - end - - private - - def strip_output(raw_output) - output = "" - raw_output.each_line do |line| - next if line =~ /^\n$/ - next if line =~ /^.*:\d+:.*:(IGNORE|PASS|FAIL)/ - return output if line =~/^-----------------------\n$/ - output << line - end - end - def write_raw_output_log(arg_hash, output) - logging = generate_log_path(arg_hash) - @ceedling[:file_wrapper].write(logging[:path], output , logging[:flags]) unless logging.nil? - end - - def generate_log_path(arg_hash) - f_name = File.basename(arg_hash[:result_file], '.pass') - base_path = File.join(PROJECT_BUILD_ARTIFACTS_ROOT, arg_hash[:context].to_s) - file_path = File.join(base_path, f_name + '.log') - - if @ceedling[:file_wrapper].exist?(base_path) - return { path: file_path, flags: 'w' } - end - - nil - end -end diff --git a/test/unit-test/vendor/ceedling/plugins/stdout_gtestlike_tests_report/README.md b/test/unit-test/vendor/ceedling/plugins/stdout_gtestlike_tests_report/README.md deleted file mode 100644 index e95106ed1..000000000 --- a/test/unit-test/vendor/ceedling/plugins/stdout_gtestlike_tests_report/README.md +++ /dev/null @@ -1,19 +0,0 @@ -ceedling-stdout-gtestlike-tests-report -====================== - -## Overview - -The stdout_gtestlike_tests_report replaces the normal ceedling "pretty" output with -a variant that resembles the output of gtest. This is most helpful when trying to -integrate into an IDE or CI that is meant to work with google test. - -## Setup - -Enable the plugin in your project.yml by adding `stdout_gtestlike_tests_report` -to the list of enabled plugins. - -``` YAML -:plugins: - :enabled: - - stdout_gtestlike_tests_report -``` diff --git a/test/unit-test/vendor/ceedling/plugins/stdout_gtestlike_tests_report/assets/template.erb b/test/unit-test/vendor/ceedling/plugins/stdout_gtestlike_tests_report/assets/template.erb deleted file mode 100644 index fb8e3b13a..000000000 --- a/test/unit-test/vendor/ceedling/plugins/stdout_gtestlike_tests_report/assets/template.erb +++ /dev/null @@ -1,84 +0,0 @@ -% ignored = hash[:results][:counts][:ignored] -% failed = hash[:results][:counts][:failed] -% stdout_count = hash[:results][:counts][:stdout] -% header_prepend = ((hash[:header].length > 0) ? "#{hash[:header]}: " : '') -% banner_width = 25 + header_prepend.length # widest message -% results = {} -% hash[:results][:successes].each do |testresult| -% results[ testresult[:source][:file] ] = testresult[:collection] -% results[ testresult[:source][:file] ].length.times do |i| -% results[ testresult[:source][:file] ][i][:pass] = true -% end -% end -% hash[:results][:ignores].each do |testresult| -% if (results[ testresult[:source][:file] ].nil?) -% results[ testresult[:source][:file] ] = testresult[:collection] -% else -% results[ testresult[:source][:file] ] += testresult[:collection] -% end -% results[ testresult[:source][:file] ].length.times do |i| -% results[ testresult[:source][:file] ][i][:pass] = true -% end -% end -% hash[:results][:failures].each do |testresult| -% if (results[ testresult[:source][:file] ].nil?) -% results[ testresult[:source][:file] ] = testresult[:collection] -% else -% results[ testresult[:source][:file] ] += testresult[:collection] -% end -% end - - -[==========] Running <%=hash[:results][:counts][:total].to_s%> tests from <%=results.length.to_s%> test cases. -[----------] Global test environment set-up. -% results.each_pair do |modulename, moduledetails| -[----------] <%=moduledetails.length.to_s%> tests from <%=modulename%> -% moduledetails.each do |item| -[ RUN ] <%=modulename%>.<%=item[:test]%> -% if (not item[:pass]) -% if (not item[:message].empty?) -<%=modulename%>(<%=item[:line]%>): error: <%=item[:message]%> - -% m = item[:message].match(/Expected\s+(.*)\s+Was\s+([^\.]*)\./) -% if m.nil? - Actual: FALSE - Expected: TRUE -% else - Actual: <%=m[2]%> - Expected: <%=m[1]%> -% end -% else -<%=modulename%>(<%=item[:line]%>): fail: <%=item[:message]%> - Actual: FALSE - Expected: TRUE -% end -[ FAILED ] <%=modulename%>.<%=item[:test]%> (0 ms) -% else -[ OK ] <%=modulename%>.<%=item[:test]%> (0 ms) -% end -% end -[----------] <%=moduledetails.length.to_s%> tests from <%=modulename%> (0 ms total) -% end - -% if (hash[:results][:counts][:total] > 0) -[----------] Global test environment tear-down. -[==========] <%=hash[:results][:counts][:total].to_s%> tests from <%=hash[:results][:stdout].length.to_s%> test cases ran. -[ PASSED ] <%=hash[:results][:counts][:passed].to_s%> tests. -% if (failed == 0) -[ FAILED ] 0 tests. - - 0 FAILED TESTS -% else -[ FAILED ] <%=failed.to_s%> tests, listed below: -% hash[:results][:failures].each do |failure| -% failure[:collection].each do |item| -[ FAILED ] <%=failure[:source][:file]%>.<%=item[:test]%> -% end -% end -% end - - <%=failed.to_s%> FAILED TESTS -% else - -No tests executed. -% end diff --git a/test/unit-test/vendor/ceedling/plugins/stdout_gtestlike_tests_report/assets/template.erb copy b/test/unit-test/vendor/ceedling/plugins/stdout_gtestlike_tests_report/assets/template.erb copy deleted file mode 100644 index a90f495e2..000000000 --- a/test/unit-test/vendor/ceedling/plugins/stdout_gtestlike_tests_report/assets/template.erb copy +++ /dev/null @@ -1,59 +0,0 @@ -% ignored = hash[:results][:counts][:ignored] -% failed = hash[:results][:counts][:failed] -% stdout_count = hash[:results][:counts][:stdout] -% header_prepend = ((hash[:header].length > 0) ? "#{hash[:header]}: " : '') -% banner_width = 25 + header_prepend.length # widest message - - -% if (stdout_count > 0) -[==========] Running <%=hash[:results][:counts][:total].to_s%> tests from <%=hash[:results][:stdout].length.to_s%> test cases. -[----------] Global test environment set-up. -% end -% if (failed > 0) -% hash[:results][:failures].each do |failure| -[----------] <%=failure[:collection].length.to_s%> tests from <%=failure[:source][:file]%> -% failure[:collection].each do |item| -[ RUN ] <%=failure[:source][:file]%>.<%=item[:test]%> -% if (not item[:message].empty?) -<%=failure[:source][:file]%>(<%=item[:line]%>): error: <%=item[:message]%> - -% m = item[:message].match(/Expected\s+(.*)\s+Was\s+([^\.]*)\./) -% if m.nil? - Actual: FALSE - Expected: TRUE -% else - Actual: <%=m[2]%> - Expected: <%=m[1]%> -% end -% else -<%=failure[:source][:file]%>(<%=item[:line]%>): fail: <%=item[:message]%> - Actual: FALSE - Expected: TRUE -% end -[ FAILED ] <%=failure[:source][:file]%>.<%=item[:test]%> (0 ms) -% end -[----------] <%=failure[:collection].length.to_s%> tests from <%=failure[:source][:file]%> (0 ms total) -% end -% end -% if (hash[:results][:counts][:total] > 0) -[----------] Global test environment tear-down. -[==========] <%=hash[:results][:counts][:total].to_s%> tests from <%=hash[:results][:stdout].length.to_s%> test cases ran. -[ PASSED ] <%=hash[:results][:counts][:passed].to_s%> tests. -% if (failed == 0) -[ FAILED ] 0 tests. - - 0 FAILED TESTS -% else -[ FAILED ] <%=failed.to_s%> tests, listed below: -% hash[:results][:failures].each do |failure| -% failure[:collection].each do |item| -[ FAILED ] <%=failure[:source][:file]%>.<%=item[:test]%> -% end -% end - - <%=failed.to_s%> FAILED TESTS -% end -% else - -No tests executed. -% end diff --git a/test/unit-test/vendor/ceedling/plugins/stdout_gtestlike_tests_report/config/stdout_gtestlike_tests_report.yml b/test/unit-test/vendor/ceedling/plugins/stdout_gtestlike_tests_report/config/stdout_gtestlike_tests_report.yml deleted file mode 100644 index c25acf511..000000000 --- a/test/unit-test/vendor/ceedling/plugins/stdout_gtestlike_tests_report/config/stdout_gtestlike_tests_report.yml +++ /dev/null @@ -1,4 +0,0 @@ ---- -:plugins: - # tell Ceedling we got results display taken care of - :display_raw_test_results: FALSE diff --git a/test/unit-test/vendor/ceedling/plugins/stdout_gtestlike_tests_report/lib/stdout_gtestlike_tests_report.rb b/test/unit-test/vendor/ceedling/plugins/stdout_gtestlike_tests_report/lib/stdout_gtestlike_tests_report.rb deleted file mode 100644 index a51438a38..000000000 --- a/test/unit-test/vendor/ceedling/plugins/stdout_gtestlike_tests_report/lib/stdout_gtestlike_tests_report.rb +++ /dev/null @@ -1,43 +0,0 @@ -require 'ceedling/plugin' -require 'ceedling/defaults' - -class StdoutGtestlikeTestsReport < Plugin - - def setup - @result_list = [] - @plugin_root = File.expand_path(File.join(File.dirname(__FILE__), '..')) - template = @ceedling[:file_wrapper].read(File.join(@plugin_root, 'assets/template.erb')) - @ceedling[:plugin_reportinator].register_test_results_template( template ) - end - - def post_test_fixture_execute(arg_hash) - return if not (arg_hash[:context] == TEST_SYM) - - @result_list << arg_hash[:result_file] - end - - def post_build - return if not (@ceedling[:task_invoker].test_invoked?) - - results = @ceedling[:plugin_reportinator].assemble_test_results(@result_list) - hash = { - :header => '', - :results => results - } - - @ceedling[:plugin_reportinator].run_test_results_report(hash) - end - - def summary - result_list = @ceedling[:file_path_utils].form_pass_results_filelist( PROJECT_TEST_RESULTS_PATH, COLLECTION_ALL_TESTS ) - - # get test results for only those tests in our configuration and of those only tests with results on disk - hash = { - :header => '', - :results => @ceedling[:plugin_reportinator].assemble_test_results(result_list, {:boom => false}) - } - - @ceedling[:plugin_reportinator].run_test_results_report(hash) - end - -end diff --git a/test/unit-test/vendor/ceedling/plugins/stdout_ide_tests_report/README.md b/test/unit-test/vendor/ceedling/plugins/stdout_ide_tests_report/README.md deleted file mode 100644 index da04d1c14..000000000 --- a/test/unit-test/vendor/ceedling/plugins/stdout_ide_tests_report/README.md +++ /dev/null @@ -1,18 +0,0 @@ -ceedling-stdout-ide-tests-report -================================ - -## Overview - -The stdout_ide_tests_report replaces the normal ceedling "pretty" output with -a simplified variant intended to be easily parseable. - -## Setup - -Enable the plugin in your project.yml by adding `stdout_ide_tests_report` -to the list of enabled plugins. - -``` YAML -:plugins: - :enabled: - - stdout_ide_tests_report -``` diff --git a/test/unit-test/vendor/ceedling/plugins/stdout_ide_tests_report/config/stdout_ide_tests_report.yml b/test/unit-test/vendor/ceedling/plugins/stdout_ide_tests_report/config/stdout_ide_tests_report.yml deleted file mode 100644 index c25acf511..000000000 --- a/test/unit-test/vendor/ceedling/plugins/stdout_ide_tests_report/config/stdout_ide_tests_report.yml +++ /dev/null @@ -1,4 +0,0 @@ ---- -:plugins: - # tell Ceedling we got results display taken care of - :display_raw_test_results: FALSE diff --git a/test/unit-test/vendor/ceedling/plugins/stdout_ide_tests_report/lib/stdout_ide_tests_report.rb b/test/unit-test/vendor/ceedling/plugins/stdout_ide_tests_report/lib/stdout_ide_tests_report.rb deleted file mode 100644 index 48b3e819c..000000000 --- a/test/unit-test/vendor/ceedling/plugins/stdout_ide_tests_report/lib/stdout_ide_tests_report.rb +++ /dev/null @@ -1,44 +0,0 @@ -require 'ceedling/plugin' -require 'ceedling/defaults' - -class StdoutIdeTestsReport < Plugin - - def setup - @result_list = [] - end - - def post_test_fixture_execute(arg_hash) - return if not (arg_hash[:context] == TEST_SYM) - - @result_list << arg_hash[:result_file] - end - - def post_build - return if (not @ceedling[:task_invoker].test_invoked?) - - results = @ceedling[:plugin_reportinator].assemble_test_results(@result_list) - hash = { - :header => '', - :results => results - } - - @ceedling[:plugin_reportinator].run_test_results_report(hash) do - message = '' - message = 'Unit test failures.' if (hash[:results][:counts][:failed] > 0) - message - end - end - - def summary - result_list = @ceedling[:file_path_utils].form_pass_results_filelist( PROJECT_TEST_RESULTS_PATH, COLLECTION_ALL_TESTS ) - - # get test results for only those tests in our configuration and of those only tests with results on disk - hash = { - :header => '', - :results => @ceedling[:plugin_reportinator].assemble_test_results(result_list, {:boom => false}) - } - - @ceedling[:plugin_reportinator].run_test_results_report(hash) - end - -end diff --git a/test/unit-test/vendor/ceedling/plugins/stdout_pretty_tests_report/README.md b/test/unit-test/vendor/ceedling/plugins/stdout_pretty_tests_report/README.md deleted file mode 100644 index 358aa93ab..000000000 --- a/test/unit-test/vendor/ceedling/plugins/stdout_pretty_tests_report/README.md +++ /dev/null @@ -1,20 +0,0 @@ -ceedling-pretty-tests-report -============================ - -## Overview - -The stdout_pretty_tests_report is the default output of ceedling. Instead of -showing most of the raw output of CMock, Ceedling, etc., it shows a simplified -view. It also creates a nice summary at the end of execution which groups the -results into ignored and failed tests. - -## Setup - -Enable the plugin in your project.yml by adding `stdout_pretty_tests_report` -to the list of enabled plugins. - -``` YAML -:plugins: - :enabled: - - stdout_pretty_tests_report -``` diff --git a/test/unit-test/vendor/ceedling/plugins/stdout_pretty_tests_report/assets/template.erb b/test/unit-test/vendor/ceedling/plugins/stdout_pretty_tests_report/assets/template.erb deleted file mode 100644 index 1c025bf1b..000000000 --- a/test/unit-test/vendor/ceedling/plugins/stdout_pretty_tests_report/assets/template.erb +++ /dev/null @@ -1,58 +0,0 @@ -% ignored = hash[:results][:counts][:ignored] -% failed = hash[:results][:counts][:failed] -% stdout_count = hash[:results][:counts][:stdout] -% header_prepend = ((hash[:header].length > 0) ? "#{hash[:header]}: " : '') -% banner_width = 25 + header_prepend.length # widest message - -% if (stdout_count > 0) -<%=@ceedling[:plugin_reportinator].generate_banner(header_prepend + 'TEST OUTPUT')%> -% hash[:results][:stdout].each do |string| -[<%=string[:source][:file]%>] -% string[:collection].each do |item| - - "<%=item%>" -% end - -% end -% end -% if (ignored > 0) -<%=@ceedling[:plugin_reportinator].generate_banner(header_prepend + 'IGNORED TEST SUMMARY')%> -% hash[:results][:ignores].each do |ignore| -[<%=ignore[:source][:file]%>] -% ignore[:collection].each do |item| - Test: <%=item[:test]%> -% if (not item[:message].empty?) - At line (<%=item[:line]%>): "<%=item[:message]%>" -% else - At line (<%=item[:line]%>) -% end - -% end -% end -% end -% if (failed > 0) -<%=@ceedling[:plugin_reportinator].generate_banner(header_prepend + 'FAILED TEST SUMMARY')%> -% hash[:results][:failures].each do |failure| -[<%=failure[:source][:file]%>] -% failure[:collection].each do |item| - Test: <%=item[:test]%> -% if (not item[:message].empty?) - At line (<%=item[:line]%>): "<%=item[:message]%>" -% else - At line (<%=item[:line]%>) -% end - -% end -% end -% end -% total_string = hash[:results][:counts][:total].to_s -% format_string = "%#{total_string.length}i" -<%=@ceedling[:plugin_reportinator].generate_banner(header_prepend + 'OVERALL TEST SUMMARY')%> -% if (hash[:results][:counts][:total] > 0) -TESTED: <%=hash[:results][:counts][:total].to_s%> -PASSED: <%=sprintf(format_string, hash[:results][:counts][:passed])%> -FAILED: <%=sprintf(format_string, failed)%> -IGNORED: <%=sprintf(format_string, ignored)%> -% else - -No tests executed. -% end diff --git a/test/unit-test/vendor/ceedling/plugins/stdout_pretty_tests_report/config/stdout_pretty_tests_report.yml b/test/unit-test/vendor/ceedling/plugins/stdout_pretty_tests_report/config/stdout_pretty_tests_report.yml deleted file mode 100644 index c25acf511..000000000 --- a/test/unit-test/vendor/ceedling/plugins/stdout_pretty_tests_report/config/stdout_pretty_tests_report.yml +++ /dev/null @@ -1,4 +0,0 @@ ---- -:plugins: - # tell Ceedling we got results display taken care of - :display_raw_test_results: FALSE diff --git a/test/unit-test/vendor/ceedling/plugins/stdout_pretty_tests_report/lib/stdout_pretty_tests_report.rb b/test/unit-test/vendor/ceedling/plugins/stdout_pretty_tests_report/lib/stdout_pretty_tests_report.rb deleted file mode 100644 index fd9589183..000000000 --- a/test/unit-test/vendor/ceedling/plugins/stdout_pretty_tests_report/lib/stdout_pretty_tests_report.rb +++ /dev/null @@ -1,47 +0,0 @@ -require 'ceedling/plugin' -require 'ceedling/defaults' - -class StdoutPrettyTestsReport < Plugin - - def setup - @result_list = [] - @plugin_root = File.expand_path(File.join(File.dirname(__FILE__), '..')) - template = @ceedling[:file_wrapper].read(File.join(@plugin_root, 'assets/template.erb')) - @ceedling[:plugin_reportinator].register_test_results_template( template ) - end - - def post_test_fixture_execute(arg_hash) - return if not (arg_hash[:context] == TEST_SYM) - - @result_list << arg_hash[:result_file] - end - - def post_build - return if not (@ceedling[:task_invoker].test_invoked?) - - results = @ceedling[:plugin_reportinator].assemble_test_results(@result_list) - hash = { - :header => '', - :results => results - } - - @ceedling[:plugin_reportinator].run_test_results_report(hash) do - message = '' - message = 'Unit test failures.' if (results[:counts][:failed] > 0) - message - end - end - - def summary - result_list = @ceedling[:file_path_utils].form_pass_results_filelist( PROJECT_TEST_RESULTS_PATH, COLLECTION_ALL_TESTS ) - - # get test results for only those tests in our configuration and of those only tests with results on disk - hash = { - :header => '', - :results => @ceedling[:plugin_reportinator].assemble_test_results(result_list, {:boom => false}) - } - - @ceedling[:plugin_reportinator].run_test_results_report(hash) - end - -end diff --git a/test/unit-test/vendor/ceedling/plugins/subprojects/README.md b/test/unit-test/vendor/ceedling/plugins/subprojects/README.md deleted file mode 100644 index ef4caa57b..000000000 --- a/test/unit-test/vendor/ceedling/plugins/subprojects/README.md +++ /dev/null @@ -1,63 +0,0 @@ -ceedling-subprojects -==================== - -Plugin for supporting subprojects that are built as static libraries. It continues to support -dependency tracking, without getting confused between your main project files and your -subproject files. It accepts different compiler flags and linker flags, allowing you to -optimize for your situation. - -First, you're going to want to add the extension to your list of known extensions: - -``` -:extension: - :subprojects: '.a' -``` - -Define a new section called :subprojects. There, you can list as many subprojects -as you may need under the :paths key. For each, you specify a unique place to build -and a unique name. - -``` -:subprojects: - :paths: - - :name: libprojectA - :source: - - ./subprojectA/first/dir - - ./subprojectA/second/dir - :include: - - ./subprojectA/include/dir - :build_root: ./subprojectA/build/dir - :defines: - - DEFINE_JUST_FOR_THIS_FILE - - AND_ANOTHER - - :name: libprojectB - :source: - - ./subprojectB/only/dir - :include: - - ./subprojectB/first/include/dir - - ./subprojectB/second/include/dir - :build_root: ./subprojectB/build/dir - :defines: [] #none for this one -``` - -You can specify the compiler and linker, just as you would a release build: - -``` -:tools: - :subprojects_compiler: - :executable: gcc - :arguments: - - -g - - -I"$": COLLECTION_PATHS_SUBPROJECTS - - -D$: COLLECTION_DEFINES_SUBPROJECTS - - -c "${1}" - - -o "${2}" - :subprojects_linker: - :executable: ar - :arguments: - - rcs - - ${2} - - ${1} -``` - -That's all there is to it! Happy Hacking! diff --git a/test/unit-test/vendor/ceedling/plugins/subprojects/config/defaults.yml b/test/unit-test/vendor/ceedling/plugins/subprojects/config/defaults.yml deleted file mode 100644 index 1045a595f..000000000 --- a/test/unit-test/vendor/ceedling/plugins/subprojects/config/defaults.yml +++ /dev/null @@ -1,33 +0,0 @@ ---- -#:extension: -# :subprojects: '.a' - -:subprojects: - :paths: [] -# - :name: subprojectA -# :source: -# - ./first/subproject/dir -# - ./second/subproject/dir -# :include: -# - ./first/include/dir -# :build_root: ./subproject/build/dir -# :defines: -# - FIRST_DEFINE - -:tools: - :subprojects_compiler: - :executable: gcc - :arguments: - - -g - - -I"$": COLLECTION_PATHS_SUBPROJECTS - - -D$: COLLECTION_DEFINES_SUBPROJECTS - - -c "${1}" - - -o "${2}" - :subprojects_linker: - :executable: ar - :arguments: - - rcs - - ${2} - - ${1} - -... diff --git a/test/unit-test/vendor/ceedling/plugins/subprojects/lib/subprojects.rb b/test/unit-test/vendor/ceedling/plugins/subprojects/lib/subprojects.rb deleted file mode 100644 index 559251ed8..000000000 --- a/test/unit-test/vendor/ceedling/plugins/subprojects/lib/subprojects.rb +++ /dev/null @@ -1,92 +0,0 @@ -require 'ceedling/plugin' -require 'ceedling/constants' - -SUBPROJECTS_ROOT_NAME = 'subprojects' -SUBPROJECTS_TASK_ROOT = SUBPROJECTS_ROOT_NAME + ':' -SUBPROJECTS_SYM = SUBPROJECTS_ROOT_NAME.to_sym - -class Subprojects < Plugin - - def setup - @plugin_root = File.expand_path(File.join(File.dirname(__FILE__), '..')) - - # Add to the test paths - SUBPROJECTS_PATHS.each do |subproj| - subproj[:source].each do |path| - COLLECTION_PATHS_TEST_SUPPORT_SOURCE_INCLUDE_VENDOR << path - end - subproj[:include].each do |path| - COLLECTION_PATHS_TEST_SUPPORT_SOURCE_INCLUDE_VENDOR << path - end - end - - # Gather information about the subprojects - @subprojects = {} - @subproject_lookup_by_path = {} - SUBPROJECTS_PATHS.each do |subproj| - @subprojects[ subproj[:name] ] = subproj.clone - @subprojects[ subproj[:name] ][:c] = [] - @subprojects[ subproj[:name] ][:asm] = [] - subproj[:source].each do |path| - search_path = "#{path[-1].match(/\\|\//) ? path : "#{path}/"}*#{EXTENSION_SOURCE}" - @subprojects[ subproj[:name] ][:c] += Dir[search_path] - if (EXTENSION_ASSEMBLY && !EXTENSION_ASSEMBLY.empty?) - search_path = "#{path[-1].match(/\\|\//) ? path : "#{path}/"}*#{EXTENSION_ASSEMBLY}" - @subprojects[ subproj[:name] ][:asm] += Dir[search_path] - end - end - @subproject_lookup_by_path[ subproj[:build_root] ] = subproj[:name] - end - end - - def find_my_project( c_file, file_type = :c ) - @subprojects.each_pair do |subprojname, subproj| - return subprojname if (subproj[file_type].include?(c_file)) - end - end - - def find_my_paths( c_file, file_type = :c ) - @subprojects.each_pair do |subprojname, subproj| - return (subproj[:source] + (subproj[:include] || [])) if (subproj[file_type].include?(c_file)) - end - return [] - end - - def find_my_defines( c_file, file_type = :c ) - @subprojects.each_pair do |subprojname, subproj| - return (subproj[:defines] || []) if (subproj[file_type].include?(c_file)) - end - return [] - end - - def list_all_object_files_for_subproject( lib_name ) - subproj = File.basename(lib_name, EXTENSION_SUBPROJECTS) - objpath = "#{@subprojects[subproj][:build_root]}/out/c" - bbb = @subprojects[subproj][:c].map{|f| "#{objpath}/#{File.basename(f,EXTENSION_SOURCE)}#{EXTENSION_OBJECT}" } - bbb - end - - def find_library_source_file_for_object( obj_name ) - cname = "#{File.basename(obj_name, EXTENSION_OBJECT)}#{EXTENSION_SOURCE}" - dname = File.dirname(obj_name)[0..-7] - pname = @subproject_lookup_by_path[dname] - return @ceedling[:file_finder].find_file_from_list(cname, @subprojects[pname][:c], :error) - end - - def find_library_assembly_file_for_object( obj_name ) - cname = "#{File.basename(obj_name, EXTENSION_OBJECT)}#{EXTENSION_ASEMBLY}" - dname = File.dirname(obj_name)[0..-7] - pname = @subproject_lookup_by_path[dname] - return @ceedling[:file_finder].find_file_from_list(cname, @subprojects[pname][:asm], :error) - end - - def replace_constant(constant, new_value) - Object.send(:remove_const, constant.to_sym) if (Object.const_defined? constant) - Object.const_set(constant, new_value) - end - -end - -# end blocks always executed following rake run -END { -} diff --git a/test/unit-test/vendor/ceedling/plugins/subprojects/subprojects.rake b/test/unit-test/vendor/ceedling/plugins/subprojects/subprojects.rake deleted file mode 100644 index f80c812f3..000000000 --- a/test/unit-test/vendor/ceedling/plugins/subprojects/subprojects.rake +++ /dev/null @@ -1,77 +0,0 @@ - - -SUBPROJECTS_PATHS.each do |subproj| - - subproj_source = subproj[:source] - subproj_include = subproj[:include] - subproj_name = subproj[:name] - subproj_build_root = subproj[:build_root] - subproj_build_out = "#{subproj[:build_root]}/out" - subproj_build_c = "#{subproj[:build_root]}/out/c" - subproj_build_asm = "#{subproj[:build_root]}/out/asm" - subproj_directories = [ subproj_build_root, subproj_build_out, subproj_build_c, subproj_build_asm ] - - subproj_directories.each do |subdir| - directory(subdir) - end - - CLEAN.include(File.join(subproj_build_root, '*')) - CLEAN.include(File.join(subproj_build_out, '*')) - - CLOBBER.include(File.join(subproj_build_root, '**/*')) - - # Add a rule for building the actual static library from our object files - rule(/#{subproj_build_root}#{'.+\\'+EXTENSION_SUBPROJECTS}$/ => [ - proc do |task_name| - @ceedling[SUBPROJECTS_SYM].list_all_object_files_for_subproject(task_name) - end - ]) do |bin_file| - @ceedling[:generator].generate_executable_file( - TOOLS_SUBPROJECTS_LINKER, - SUBPROJECTS_SYM, - bin_file.prerequisites, - bin_file.name, - @ceedling[:file_path_utils].form_test_build_map_filepath(bin_file.name)) - end - - # Add a rule for building object files from assembly files to link into a library - if (RELEASE_BUILD_USE_ASSEMBLY) - rule(/#{subproj_build_asm}#{'.+\\'+EXTENSION_OBJECT}$/ => [ - proc do |task_name| - @ceedling[SUBPROJECTS_SYM].find_library_assembly_file_for_object(task_name) - end - ]) do |object| - @ceedling[SUBPROJECTS_SYM].replace_constant(:COLLECTION_PATHS_SUBPROJECTS, @ceedling[SUBPROJECTS_SYM].find_my_paths(object.source, :asm)) - @ceedling[SUBPROJECTS_SYM].replace_constant(:COLLECTION_DEFINES_SUBPROJECTS, @ceedling[SUBPROJECTS_SYM].find_my_defines(object.source, :asm)) - @ceedling[:generator].generate_object_file( - TOOLS_SUBPROJECTS_ASSEMBLER, - OPERATION_ASSEMBLE_SYM, - SUBPROJECTS_SYM, - object.source, - object.name ) - end - end - - # Add a rule for building object files from C files to link into a library - rule(/#{subproj_build_c}#{'.+\\'+EXTENSION_OBJECT}$/ => [ - proc do |task_name| - @ceedling[SUBPROJECTS_SYM].find_library_source_file_for_object(task_name) - end - ]) do |object| - @ceedling[SUBPROJECTS_SYM].replace_constant(:COLLECTION_PATHS_SUBPROJECTS, @ceedling[SUBPROJECTS_SYM].find_my_paths(object.source, :c)) - @ceedling[SUBPROJECTS_SYM].replace_constant(:COLLECTION_DEFINES_SUBPROJECTS, @ceedling[SUBPROJECTS_SYM].find_my_defines(object.source, :c)) - @ceedling[:generator].generate_object_file( - TOOLS_SUBPROJECTS_COMPILER, - OPERATION_COMPILE_SYM, - SUBPROJECTS_SYM, - object.source, - object.name, - @ceedling[:file_path_utils].form_release_build_c_list_filepath( object.name ) ) - end - - # Add the subdirectories involved to our list of those that should be autogenerated - task :directories => subproj_directories.clone - - # Finally, add the static library to our RELEASE build dependency list - task RELEASE_SYM => ["#{subproj_build_root}/#{subproj_name}#{EXTENSION_SUBPROJECTS}"] -end diff --git a/test/unit-test/vendor/ceedling/plugins/teamcity_tests_report/README.md b/test/unit-test/vendor/ceedling/plugins/teamcity_tests_report/README.md deleted file mode 100644 index 2467ebe99..000000000 --- a/test/unit-test/vendor/ceedling/plugins/teamcity_tests_report/README.md +++ /dev/null @@ -1,18 +0,0 @@ -ceedling-teamcity-tests-report -============================== - -## Overview - -The teamcity_tests_report replaces the normal ceedling "pretty" output with -a version that has results tagged to be consumed with the teamcity CI server. - -## Setup - -Enable the plugin in your project.yml by adding `teamcity_tests_report` -to the list of enabled plugins. - -``` YAML -:plugins: - :enabled: - - teamcity_tests_report -``` diff --git a/test/unit-test/vendor/ceedling/plugins/teamcity_tests_report/config/teamcity_tests_report.yml b/test/unit-test/vendor/ceedling/plugins/teamcity_tests_report/config/teamcity_tests_report.yml deleted file mode 100644 index c25acf511..000000000 --- a/test/unit-test/vendor/ceedling/plugins/teamcity_tests_report/config/teamcity_tests_report.yml +++ /dev/null @@ -1,4 +0,0 @@ ---- -:plugins: - # tell Ceedling we got results display taken care of - :display_raw_test_results: FALSE diff --git a/test/unit-test/vendor/ceedling/plugins/teamcity_tests_report/lib/teamcity_tests_report.rb b/test/unit-test/vendor/ceedling/plugins/teamcity_tests_report/lib/teamcity_tests_report.rb deleted file mode 100644 index 33d8548f3..000000000 --- a/test/unit-test/vendor/ceedling/plugins/teamcity_tests_report/lib/teamcity_tests_report.rb +++ /dev/null @@ -1,57 +0,0 @@ -require 'ceedling/plugin' -require 'ceedling/defaults' - -class TeamcityTestsReport < Plugin - - def setup - @suite_started = nil - @output_enabled = !defined?(TEAMCITY_BUILD) || TEAMCITY_BUILD - end - - def escape(string) - string.gsub(/['|\[\]]/, '|\0').gsub('\r', '|r').gsub('\n', '|n') - end - - def pre_test(test) - teamcity_message "testSuiteStarted name='#{File.basename(test, '.c')}'" - @suite_started = Time.now - end - - def post_test(test) - teamcity_message "testSuiteFinished name='#{File.basename(test, '.c')}'" - end - - def post_test_fixture_execute(arg_hash) - duration = (Time.now - @suite_started) * 1000 - results = @ceedling[:plugin_reportinator].assemble_test_results([arg_hash[:result_file]]) - avg_duration = (duration / [1, results[:counts][:passed] + results[:counts][:failed]].max).round - - results[:successes].each do |success| - success[:collection].each do |test| - teamcity_message "testStarted name='#{test[:test]}'" - teamcity_message "testFinished name='#{test[:test]}' duration='#{avg_duration}'" - end - end - - results[:failures].each do |failure| - failure[:collection].each do |test| - teamcity_message "testStarted name='#{test[:test]}'" - teamcity_message "testFailed name='#{test[:test]}' message='#{escape(test[:message])}' details='File: #{failure[:source][:path]}/#{failure[:source][:file]} Line: #{test[:line]}'" - teamcity_message "testFinished name='#{test[:test]}' duration='#{avg_duration}'" - end - end - - results[:ignores].each do |failure| - failure[:collection].each do |test| - teamcity_message "testIgnored name='#{test[:test]}' message='#{escape(test[:message])}'" - end - end - - # We ignore stdout - end - - def teamcity_message(content) - puts "##teamcity[#{content}]" unless !@output_enabled - end - -end diff --git a/test/unit-test/vendor/ceedling/plugins/warnings_report/README.md b/test/unit-test/vendor/ceedling/plugins/warnings_report/README.md deleted file mode 100644 index fd7fae5d9..000000000 --- a/test/unit-test/vendor/ceedling/plugins/warnings_report/README.md +++ /dev/null @@ -1,19 +0,0 @@ -warnings-report -=============== - -## Overview - -The warnings_report captures all warnings throughout the build process -and collects them into a single report at the end of execution. It places all -of this into a warnings file in the output artifact directory. - -## Setup - -Enable the plugin in your project.yml by adding `warnings_report` -to the list of enabled plugins. - -``` YAML -:plugins: - :enabled: - - warnings_report -``` diff --git a/test/unit-test/vendor/ceedling/plugins/warnings_report/lib/warnings_report.rb b/test/unit-test/vendor/ceedling/plugins/warnings_report/lib/warnings_report.rb deleted file mode 100644 index d4f43fb57..000000000 --- a/test/unit-test/vendor/ceedling/plugins/warnings_report/lib/warnings_report.rb +++ /dev/null @@ -1,69 +0,0 @@ -require 'ceedling/plugin' -require 'ceedling/constants' - -class WarningsReport < Plugin - def setup - @stderr_redirect = nil - @log_paths = {} - end - - def pre_compile_execute(arg_hash) - # at beginning of compile, override tool's stderr_redirect so we can parse $stderr + $stdout - set_stderr_redirect(arg_hash) - end - - def post_compile_execute(arg_hash) - # after compilation, grab output for parsing/logging, restore stderr_redirect, log warning if it exists - output = arg_hash[:shell_result][:output] - restore_stderr_redirect(arg_hash) - write_warning_log(arg_hash[:context], output) - end - - def pre_link_execute(arg_hash) - # at beginning of link, override tool's stderr_redirect so we can parse $stderr + $stdout - set_stderr_redirect(arg_hash) - end - - def post_link_execute(arg_hash) - # after linking, grab output for parsing/logging, restore stderr_redirect, log warning if it exists - output = arg_hash[:shell_result][:output] - restore_stderr_redirect(arg_hash) - write_warning_log(arg_hash[:context], output) - end - - private - - def set_stderr_redirect(hash) - @stderr_redirect = hash[:tool][:stderr_redirect] - hash[:tool][:stderr_redirect] = StdErrRedirect::AUTO - end - - def restore_stderr_redirect(hash) - hash[:tool][:stderr_redirect] = @stderr_redirect - end - - def write_warning_log(context, output) - # if $stderr/$stdout contain "warning", log it - if output =~ /warning/i - # generate a log path & file io write flags - logging = generate_log_path(context) - @ceedling[:file_wrapper].write(logging[:path], output + "\n", logging[:flags]) unless logging.nil? - end - end - - def generate_log_path(context) - # if path has already been generated, return it & 'append' file io flags (append to log) - return { path: @log_paths[context], flags: 'a' } unless @log_paths[context].nil? - - # first time through, generate path & 'write' file io flags (create new log) - base_path = File.join(PROJECT_BUILD_ARTIFACTS_ROOT, context.to_s) - file_path = File.join(base_path, 'warnings.log') - - if @ceedling[:file_wrapper].exist?(base_path) - @log_paths[context] = file_path - return { path: file_path, flags: 'w' } - end - - nil - end -end diff --git a/test/unit-test/vendor/ceedling/plugins/xml_tests_report/README.md b/test/unit-test/vendor/ceedling/plugins/xml_tests_report/README.md deleted file mode 100644 index 6200c7dea..000000000 --- a/test/unit-test/vendor/ceedling/plugins/xml_tests_report/README.md +++ /dev/null @@ -1,36 +0,0 @@ -xml_tests_report -================ - -## Overview - -The xml_tests_report plugin creates an XML file of test results in xUnit -format, which is handy for Continuous Integration build servers or as input -into other reporting tools. The XML file is output to the appropriate -`<build_root>/artifacts/` directory (e.g. `artifacts/test/` for test tasks, -`artifacts/gcov/` for gcov, or `artifacts/bullseye/` for bullseye runs). - -## Setup - -Enable the plugin in your project.yml by adding `xml_tests_report` to the list -of enabled plugins. - -``` YAML -:plugins: - :enabled: - - xml_tests_report -``` - -## Configuration - -Optionally configure the output / artifact filename in your project.yml with -the `artifact_filename` configuration option. The default filename is -`report.xml`. - -You can also configure the path that this artifact is stored. This can be done -by setting `path`. The default is that it will be placed in a subfolder under -the `build` directory. - -``` YAML -:xml_tests_report: - :artifact_filename: report_xunit.xml -``` diff --git a/test/unit-test/vendor/ceedling/plugins/xml_tests_report/lib/xml_tests_report.rb b/test/unit-test/vendor/ceedling/plugins/xml_tests_report/lib/xml_tests_report.rb deleted file mode 100644 index ed4e99603..000000000 --- a/test/unit-test/vendor/ceedling/plugins/xml_tests_report/lib/xml_tests_report.rb +++ /dev/null @@ -1,110 +0,0 @@ -require 'ceedling/plugin' -require 'ceedling/constants' - -class XmlTestsReport < Plugin - def setup - @results_list = {} - @test_counter = 0 - end - - def post_test_fixture_execute(arg_hash) - context = arg_hash[:context] - - @results_list[context] = [] if @results_list[context].nil? - - @results_list[context] << arg_hash[:result_file] - end - - def post_build - @results_list.each_key do |context| - results = @ceedling[:plugin_reportinator].assemble_test_results(@results_list[context]) - - artifact_filename = @ceedling[:configurator].project_config_hash[:xml_tests_report_artifact_filename] || 'report.xml' - artifact_fullpath = @ceedling[:configurator].project_config_hash[:xml_tests_report_path] || File.join(PROJECT_BUILD_ARTIFACTS_ROOT, context.to_s) - file_path = File.join(artifact_fullpath, artifact_filename) - - @ceedling[:file_wrapper].open(file_path, 'w') do |f| - @test_counter = 1 - write_results(results, f) - end - end - end - - private - - def write_results(results, stream) - write_header(stream) - write_failures(results[:failures], stream) - write_tests(results[:successes], stream, 'SuccessfulTests') - write_tests(results[:ignores], stream, 'IgnoredTests') - write_statistics(results[:counts], stream) - write_footer(stream) - end - - def write_header(stream) - stream.puts "<?xml version='1.0' encoding='utf-8' ?>" - stream.puts '<TestRun>' - end - - def write_failures(results, stream) - if results.size.zero? - stream.puts "\t<FailedTests/>" - return - end - - stream.puts "\t<FailedTests>" - - results.each do |result| - result[:collection].each do |item| - filename = File.join(result[:source][:path], result[:source][:file]) - - stream.puts "\t\t<Test id=\"#{@test_counter}\">" - stream.puts "\t\t\t<Name>#{filename}::#{item[:test]}</Name>" - stream.puts "\t\t\t<FailureType>Assertion</FailureType>" - stream.puts "\t\t\t<Location>" - stream.puts "\t\t\t\t<File>#{filename}</File>" - stream.puts "\t\t\t\t<Line>#{item[:line]}</Line>" - stream.puts "\t\t\t</Location>" - stream.puts "\t\t\t<Message>#{item[:message]}</Message>" - stream.puts "\t\t</Test>" - @test_counter += 1 - end - end - - stream.puts "\t</FailedTests>" - end - - def write_tests(results, stream, tag) - if results.size.zero? - stream.puts "\t<#{tag}/>" - return - end - - stream.puts "\t<#{tag}>" - - results.each do |result| - result[:collection].each do |item| - stream.puts "\t\t<Test id=\"#{@test_counter}\">" - stream.puts "\t\t\t<Name>#{File.join(result[:source][:path], result[:source][:file])}::#{item[:test]}</Name>" - stream.puts "\t\t</Test>" - @test_counter += 1 - end - end - - stream.puts "\t</#{tag}>" - end - - def write_statistics(counts, stream) - stream.puts "\t<Statistics>" - stream.puts "\t\t<Tests>#{counts[:total]}</Tests>" - stream.puts "\t\t<Ignores>#{counts[:ignored]}</Ignores>" - stream.puts "\t\t<FailuresTotal>#{counts[:failed]}</FailuresTotal>" - stream.puts "\t\t<Errors>0</Errors>" - stream.puts "\t\t<Failures>#{counts[:failed]}</Failures>" - stream.puts "\t</Statistics>" - end - - def write_footer(stream) - stream.puts '</TestRun>' - end -end diff --git a/test/unit-test/vendor/ceedling/vendor/c_exception/lib/CException.c b/test/unit-test/vendor/ceedling/vendor/c_exception/lib/CException.c deleted file mode 100644 index 24b3b09e8..000000000 --- a/test/unit-test/vendor/ceedling/vendor/c_exception/lib/CException.c +++ /dev/null @@ -1,45 +0,0 @@ -#include "CException.h" - -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wmissing-field-initializers" -volatile CEXCEPTION_FRAME_T CExceptionFrames[CEXCEPTION_NUM_ID] = {{ 0 }}; -#pragma GCC diagnostic pop - -//------------------------------------------------------------------------------------------ -// Throw -//------------------------------------------------------------------------------------------ -void Throw(CEXCEPTION_T ExceptionID) -{ - unsigned int MY_ID = CEXCEPTION_GET_ID; - CExceptionFrames[MY_ID].Exception = ExceptionID; - if (CExceptionFrames[MY_ID].pFrame) - { - longjmp(*CExceptionFrames[MY_ID].pFrame, 1); - } - CEXCEPTION_NO_CATCH_HANDLER(ExceptionID); -} - -//------------------------------------------------------------------------------------------ -// Explanation of what it's all for: -//------------------------------------------------------------------------------------------ -/* -#define Try - { <- give us some local scope. most compilers are happy with this - jmp_buf *PrevFrame, NewFrame; <- prev frame points to the last try block's frame. new frame gets created on stack for this Try block - unsigned int MY_ID = CEXCEPTION_GET_ID; <- look up this task's id for use in frame array. always 0 if single-tasking - PrevFrame = CExceptionFrames[CEXCEPTION_GET_ID].pFrame; <- set pointer to point at old frame (which array is currently pointing at) - CExceptionFrames[MY_ID].pFrame = &NewFrame; <- set array to point at my new frame instead, now - CExceptionFrames[MY_ID].Exception = CEXCEPTION_NONE; <- initialize my exception id to be NONE - if (setjmp(NewFrame) == 0) { <- do setjmp. it returns 1 if longjump called, otherwise 0 - if (&PrevFrame) <- this is here to force proper scoping. it requires braces or a single line to be but after Try, otherwise won't compile. This is always true at this point. - -#define Catch(e) - else { } <- this also forces proper scoping. Without this they could stick their own 'else' in and it would get ugly - CExceptionFrames[MY_ID].Exception = CEXCEPTION_NONE; <- no errors happened, so just set the exception id to NONE (in case it was corrupted) - } - else <- an exception occurred - { e = CExceptionFrames[MY_ID].Exception; e=e;} <- assign the caught exception id to the variable passed in. - CExceptionFrames[MY_ID].pFrame = PrevFrame; <- make the pointer in the array point at the previous frame again, as if NewFrame never existed. - } <- finish off that local scope we created to have our own variables - if (CExceptionFrames[CEXCEPTION_GET_ID].Exception != CEXCEPTION_NONE) <- start the actual 'catch' processing if we have an exception id saved away - */ diff --git a/test/unit-test/vendor/ceedling/vendor/c_exception/lib/CException.h b/test/unit-test/vendor/ceedling/vendor/c_exception/lib/CException.h deleted file mode 100644 index be9e18695..000000000 --- a/test/unit-test/vendor/ceedling/vendor/c_exception/lib/CException.h +++ /dev/null @@ -1,115 +0,0 @@ -#ifndef _CEXCEPTION_H -#define _CEXCEPTION_H - -#include <setjmp.h> - -#ifdef __cplusplus -extern "C" -{ -#endif - - -#define CEXCEPTION_VERSION_MAJOR 1 -#define CEXCEPTION_VERSION_MINOR 3 -#define CEXCEPTION_VERSION_BUILD 3 -#define CEXCEPTION_VERSION ((CEXCEPTION_VERSION_MAJOR << 16) | (CEXCEPTION_VERSION_MINOR << 8) | CEXCEPTION_VERSION_BUILD) - -//To Use CException, you have a number of options: -//1. Just include it and run with the defaults -//2. Define any of the following symbols at the command line to override them -//3. Include a header file before CException.h everywhere which defines any of these -//4. Create an Exception.h in your path, and just define EXCEPTION_USE_CONFIG_FILE first - -#ifdef CEXCEPTION_USE_CONFIG_FILE -#include "CExceptionConfig.h" -#endif - -//This is the value to assign when there isn't an exception -#ifndef CEXCEPTION_NONE -#define CEXCEPTION_NONE (0x5A5A5A5A) -#endif - -//This is number of exception stacks to keep track of (one per task) -#ifndef CEXCEPTION_NUM_ID -#define CEXCEPTION_NUM_ID (1) //there is only the one stack by default -#endif - -//This is the method of getting the current exception stack index (0 if only one stack) -#ifndef CEXCEPTION_GET_ID -#define CEXCEPTION_GET_ID (0) //use the first index always because there is only one anyway -#endif - -//The type to use to store the exception values. -#ifndef CEXCEPTION_T -#define CEXCEPTION_T unsigned int -#endif - -//This is an optional special handler for when there is no global Catch -#ifndef CEXCEPTION_NO_CATCH_HANDLER -#define CEXCEPTION_NO_CATCH_HANDLER(id) -#endif - -//These hooks allow you to inject custom code into places, particularly useful for saving and restoring additional state -#ifndef CEXCEPTION_HOOK_START_TRY -#define CEXCEPTION_HOOK_START_TRY -#endif -#ifndef CEXCEPTION_HOOK_HAPPY_TRY -#define CEXCEPTION_HOOK_HAPPY_TRY -#endif -#ifndef CEXCEPTION_HOOK_AFTER_TRY -#define CEXCEPTION_HOOK_AFTER_TRY -#endif -#ifndef CEXCEPTION_HOOK_START_CATCH -#define CEXCEPTION_HOOK_START_CATCH -#endif - -//exception frame structures -typedef struct { - jmp_buf* pFrame; - CEXCEPTION_T volatile Exception; -} CEXCEPTION_FRAME_T; - -//actual root frame storage (only one if single-tasking) -extern volatile CEXCEPTION_FRAME_T CExceptionFrames[]; - -//Try (see C file for explanation) -#define Try \ - { \ - jmp_buf *PrevFrame, NewFrame; \ - unsigned int MY_ID = CEXCEPTION_GET_ID; \ - PrevFrame = CExceptionFrames[MY_ID].pFrame; \ - CExceptionFrames[MY_ID].pFrame = (jmp_buf*)(&NewFrame); \ - CExceptionFrames[MY_ID].Exception = CEXCEPTION_NONE; \ - CEXCEPTION_HOOK_START_TRY; \ - if (setjmp(NewFrame) == 0) { \ - if (1) - -//Catch (see C file for explanation) -#define Catch(e) \ - else { } \ - CExceptionFrames[MY_ID].Exception = CEXCEPTION_NONE; \ - CEXCEPTION_HOOK_HAPPY_TRY; \ - } \ - else \ - { \ - e = CExceptionFrames[MY_ID].Exception; \ - (void)e; \ - CEXCEPTION_HOOK_START_CATCH; \ - } \ - CExceptionFrames[MY_ID].pFrame = PrevFrame; \ - CEXCEPTION_HOOK_AFTER_TRY; \ - } \ - if (CExceptionFrames[CEXCEPTION_GET_ID].Exception != CEXCEPTION_NONE) - -//Throw an Error -void Throw(CEXCEPTION_T ExceptionID); - -//Just exit the Try block and skip the Catch. -#define ExitTry() Throw(CEXCEPTION_NONE) - -#ifdef __cplusplus -} // extern "C" -#endif - - -#endif // _CEXCEPTION_H diff --git a/test/unit-test/vendor/ceedling/vendor/c_exception/lib/meson.build b/test/unit-test/vendor/ceedling/vendor/c_exception/lib/meson.build deleted file mode 100644 index 9694e51c7..000000000 --- a/test/unit-test/vendor/ceedling/vendor/c_exception/lib/meson.build +++ /dev/null @@ -1,11 +0,0 @@ -# -# build script written by : Michael Brockus. -# github repo author: Mark VanderVoord. -# -# license: MIT -# -cexception_dir = include_directories('.') - -cexception_lib = static_library(meson.project_name(), - files('CException.c'), - include_directories : cexception_dir) diff --git a/test/unit-test/vendor/ceedling/vendor/cmock/config/production_environment.rb b/test/unit-test/vendor/ceedling/vendor/cmock/config/production_environment.rb deleted file mode 100644 index 082b63fde..000000000 --- a/test/unit-test/vendor/ceedling/vendor/cmock/config/production_environment.rb +++ /dev/null @@ -1,12 +0,0 @@ -# ========================================== -# CMock Project - Automatic Mock Generation for C -# Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams -# [Released under MIT License. Please refer to license.txt for details] -# ========================================== - -# Setup our load path: -[ - 'lib' -].each do |dir| - $:.unshift(File.join(__dir__ + '/../', dir)) -end diff --git a/test/unit-test/vendor/ceedling/vendor/cmock/config/test_environment.rb b/test/unit-test/vendor/ceedling/vendor/cmock/config/test_environment.rb deleted file mode 100644 index aeae3a342..000000000 --- a/test/unit-test/vendor/ceedling/vendor/cmock/config/test_environment.rb +++ /dev/null @@ -1,16 +0,0 @@ -# ========================================== -# CMock Project - Automatic Mock Generation for C -# Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams -# [Released under MIT License. Please refer to license.txt for details] -# ========================================== - -# Setup our load path: -[ - './lib', - './vendor/behaviors/lib', - './vendor/hardmock/lib', - './vendor/unity/auto/', - './test/system/' -].each do |dir| - $:.unshift(File.join(File.expand_path(File.dirname(__FILE__) + '/../'), dir)) -end diff --git a/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock.rb b/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock.rb deleted file mode 100644 index 72f864189..000000000 --- a/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock.rb +++ /dev/null @@ -1,111 +0,0 @@ -# ========================================== -# CMock Project - Automatic Mock Generation for C -# Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams -# [Released under MIT License. Please refer to license.txt for details] -# ========================================== - -['../config/production_environment', - 'cmock_header_parser', - 'cmock_generator', - 'cmock_file_writer', - 'cmock_config', - 'cmock_plugin_manager', - 'cmock_generator_utils', - 'cmock_unityhelper_parser'].each { |req| require "#{__dir__}/#{req}" } - -class CMock - def initialize(options = nil) - cm_config = CMockConfig.new(options) - cm_unityhelper = CMockUnityHelperParser.new(cm_config) - cm_writer = CMockFileWriter.new(cm_config) - cm_gen_utils = CMockGeneratorUtils.new(cm_config, - :unity_helper => cm_unityhelper) - cm_gen_plugins = CMockPluginManager.new(cm_config, cm_gen_utils) - @cm_parser = CMockHeaderParser.new(cm_config) - @cm_generator = CMockGenerator.new(cm_config, cm_writer, cm_gen_utils, - cm_gen_plugins) - @silent = (cm_config.verbosity < 2) - end - - def setup_mocks(files, folder = nil) - [files].flatten.each do |src| - generate_mock(src, folder) - end - end - - def setup_skeletons(files) - [files].flatten.each do |src| - generate_skeleton src - end - end - - private ############################### - - def generate_mock(src, folder) - name = File.basename(src, '.*') - ext = File.extname(src) - puts "Creating mock for #{name}..." unless @silent - @cm_generator.create_mock(name, @cm_parser.parse(name, File.read(src)), ext, folder) - end - - def generate_skeleton(src) - name = File.basename(src, '.*') - puts "Creating skeleton for #{name}..." unless @silent - @cm_generator.create_skeleton(name, @cm_parser.parse(name, File.read(src))) - end -end - -def option_maker(options, key, val) - options ||= {} - options[key.to_sym] = - if val.chr == ':' - val[1..-1].to_sym - elsif val.include? ';' - val.split(';') - elsif val == 'true' - true - elsif val == 'false' - false - elsif val =~ /^\d+$/ - val.to_i - else - val - end - options -end - -# Command Line Support ############################### - -if $0 == __FILE__ - usage = "usage: ruby #{__FILE__} (-oOptionsFile) File(s)ToMock" - - unless ARGV[0] - puts usage - exit 1 - end - - options = {} - filelist = [] - ARGV.each do |arg| - if arg =~ /^-o\"?([a-zA-Z0-9@._\\\/:\s]+)\"?/ - options.merge! CMockConfig.load_config_file_from_yaml(arg.gsub(/^-o/, '')) - elsif arg == '--skeleton' - options[:skeleton] = true - elsif arg =~ /^--strippables=\"?(.*)\"?/ - # --strippables are dealt with separately since the user is allowed to - # enter any valid regular expression as argument - options = option_maker(options, 'strippables', Regexp.last_match(1)) - elsif arg =~ /^--([a-zA-Z0-9._\\\/:\s]+)=\"?([a-zA-Z0-9._\-\\\/:\s\;]*)\"?/x - options = option_maker(options, Regexp.last_match(1), - Regexp.last_match(2)) - else - filelist << arg - end - end - - if options[:skeleton] - CMock.new(options).setup_skeletons(filelist) - else - CMock.new(options).setup_mocks(filelist) - end -end diff --git a/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_config.rb b/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_config.rb deleted file mode 100644 index 716a0c55e..000000000 --- a/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_config.rb +++ /dev/null @@ -1,174 +0,0 @@ -# ========================================== -# CMock Project - Automatic Mock Generation for C -# Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams -# [Released under MIT License. Please refer to license.txt for details] -# ========================================== - -class CMockConfig - CMOCK_DEFAULT_OPTIONS = - { - :framework => :unity, - :mock_path => 'mocks', - :mock_prefix => 'Mock', - :mock_suffix => '', - :skeleton_path => '', - :weak => '', - :subdir => nil, - :plugins => [], - :strippables => ['(?:__attribute__\s*\(+.*?\)+)'], - :attributes => %w[__ramfunc __irq __fiq register extern], - :c_calling_conventions => %w[__stdcall __cdecl __fastcall], - :enforce_strict_ordering => false, - :fail_on_unexpected_calls => true, - :unity_helper_path => false, - :treat_as => {}, - :treat_as_array => {}, - :treat_as_void => [], - :memcmp_if_unknown => true, - :when_no_prototypes => :warn, # the options being :ignore, :warn, or :error - :when_ptr => :compare_data, # the options being :compare_ptr, :compare_data, or :smart - :verbosity => 2, # the options being 0 errors only, 1 warnings and errors, 2 normal info, 3 verbose - :treat_externs => :exclude, # the options being :include or :exclude - :treat_inlines => :exclude, # the options being :include or :exclude - :callback_include_count => true, - :callback_after_arg_check => false, - :includes => nil, - :includes_h_pre_orig_header => nil, - :includes_h_post_orig_header => nil, - :includes_c_pre_header => nil, - :includes_c_post_header => nil, - :orig_header_include_fmt => '#include "%s"', - :array_size_type => [], - :array_size_name => 'size|len', - :skeleton => false, - :exclude_setjmp_h => false, - - # Format to look for inline functions. - # This is a combination of "static" and "inline" keywords ("static inline", "inline static", "inline", "static") - # There are several possibilities: - # - sometimes they appear together, sometimes individually, - # - The keywords can appear before or after the return type (this is a compiler warning but people do weird stuff), - # so we check for word boundaries when searching for them - # - We first remove "static inline" combinations and boil down to single inline or static statements - :inline_function_patterns => ['(static\s+inline|inline\s+static)\s*', '(\bstatic\b|\binline\b)\s*'] # Last part (\s*) is just to remove whitespaces (only to prettify the output) - }.freeze - - def initialize(options = nil) - case options - when NilClass then options = CMOCK_DEFAULT_OPTIONS.dup - when String then options = CMOCK_DEFAULT_OPTIONS.dup.merge(load_config_file_from_yaml(options)) - when Hash then options = CMOCK_DEFAULT_OPTIONS.dup.merge(options) - else raise 'If you specify arguments, it should be a filename or a hash of options' - end - - # do some quick type verification - %i[plugins attributes treat_as_void].each do |opt| - unless options[opt].class == Array - options[opt] = [] - puts "WARNING: :#{opt} should be an array." unless options[:verbosity] < 1 - end - end - %i[includes includes_h_pre_orig_header includes_h_post_orig_header includes_c_pre_header includes_c_post_header].each do |opt| - unless options[opt].nil? || (options[opt].class == Array) - options[opt] = [] - puts "WARNING: :#{opt} should be an array." unless options[:verbosity] < 1 - end - end - options[:unity_helper_path] ||= options[:unity_helper] - options[:unity_helper_path] = [options[:unity_helper_path]] if options[:unity_helper_path].is_a? String - - if options[:unity_helper_path] - require 'pathname' - includes1 = options[:includes_c_post_header] || [] - includes2 = options[:unity_helper_path].map do |path| - Pathname(path).relative_path_from(Pathname(options[:mock_path])).to_s - end - options[:includes_c_post_header] = (includes1 + includes2).uniq - end - - options[:plugins].compact! - options[:plugins].map!(&:to_sym) - @options = options - - treat_as_map = standard_treat_as_map # .clone - treat_as_map.merge!(@options[:treat_as]) - @options[:treat_as] = treat_as_map - - @options.each_key do |key| - unless methods.include?(key) - eval("def #{key}() return @options[:#{key}] end") - end - end - end - - def load_config_file_from_yaml(yaml_filename) - self.class.load_config_file_from_yaml yaml_filename - end - - def self.load_config_file_from_yaml(yaml_filename) - require 'yaml' - require 'fileutils' - YAML.load_file(yaml_filename)[:cmock] - end - - def path(new_path) - @src_path = new_path - end - - def load_unity_helper - return nil unless @options[:unity_helper_path] - - @options[:unity_helper_path].inject('') do |unity_helper, filename| - unity_helper + "\n" + File.new(filename).read - end - end - - def standard_treat_as_map - { - 'int' => 'INT', - 'char' => 'INT8', - 'short' => 'INT16', - 'long' => 'INT', - 'int8' => 'INT8', - 'int16' => 'INT16', - 'int32' => 'INT', - 'int8_t' => 'INT8', - 'int16_t' => 'INT16', - 'int32_t' => 'INT', - 'INT8_T' => 'INT8', - 'INT16_T' => 'INT16', - 'INT32_T' => 'INT', - 'bool' => 'INT', - 'bool_t' => 'INT', - 'BOOL' => 'INT', - 'BOOL_T' => 'INT', - 'unsigned int' => 'HEX32', - 'unsigned long' => 'HEX32', - 'uint32' => 'HEX32', - 'uint32_t' => 'HEX32', - 'UINT32' => 'HEX32', - 'UINT32_T' => 'HEX32', - 'void*' => 'HEX8_ARRAY', - 'void const*' => 'HEX8_ARRAY', - 'const void*' => 'HEX8_ARRAY', - 'unsigned short' => 'HEX16', - 'uint16' => 'HEX16', - 'uint16_t' => 'HEX16', - 'UINT16' => 'HEX16', - 'UINT16_T' => 'HEX16', - 'unsigned char' => 'HEX8', - 'uint8' => 'HEX8', - 'uint8_t' => 'HEX8', - 'UINT8' => 'HEX8', - 'UINT8_T' => 'HEX8', - 'char*' => 'STRING', - 'char const*' => 'STRING', - 'const char*' => 'STRING', - 'pCHAR' => 'STRING', - 'cstring' => 'STRING', - 'CSTRING' => 'STRING', - 'float' => 'FLOAT', - 'double' => 'FLOAT' - } - end -end diff --git a/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_file_writer.rb b/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_file_writer.rb deleted file mode 100644 index f30c44b24..000000000 --- a/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_file_writer.rb +++ /dev/null @@ -1,47 +0,0 @@ -# ========================================== -# CMock Project - Automatic Mock Generation for C -# Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams -# [Released under MIT License. Please refer to license.txt for details] -# ========================================== - -class CMockFileWriter - attr_reader :config - - def initialize(config) - @config = config - end - - def create_subdir(subdir) - require 'fileutils' - FileUtils.mkdir_p "#{@config.mock_path}/" unless Dir.exist?("#{@config.mock_path}/") - FileUtils.mkdir_p "#{@config.mock_path}/#{subdir + '/' if subdir}" if subdir && !Dir.exist?("#{@config.mock_path}/#{subdir + '/' if subdir}") - end - - def create_file(filename, subdir) - raise "Where's the block of data to create?" unless block_given? - - full_file_name_temp = "#{@config.mock_path}/#{subdir + '/' if subdir}#{filename}.new" - full_file_name_done = "#{@config.mock_path}/#{subdir + '/' if subdir}#{filename}" - File.open(full_file_name_temp, 'w') do |file| - yield(file, filename) - end - update_file(full_file_name_done, full_file_name_temp) - end - - def append_file(filename, subdir) - raise "Where's the block of data to create?" unless block_given? - - full_file_name = "#{@config.skeleton_path}/#{subdir + '/' if subdir}#{filename}" - File.open(full_file_name, 'a') do |file| - yield(file, filename) - end - end - - private ################################### - - def update_file(dest, src) - require 'fileutils' - FileUtils.rm(dest, :force => true) - FileUtils.mv(src, dest) - end -end diff --git a/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_generator.rb b/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_generator.rb deleted file mode 100644 index 6ed51109f..000000000 --- a/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_generator.rb +++ /dev/null @@ -1,368 +0,0 @@ -# ========================================== -# CMock Project - Automatic Mock Generation for C -# Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams -# [Released under MIT License. Please refer to license.txt for details] -# ========================================== - -class CMockGenerator - attr_accessor :config, :file_writer, :module_name, :module_ext, :clean_mock_name, :mock_name, :utils, :plugins, :weak, :ordered - - def initialize(config, file_writer, utils, plugins) - @file_writer = file_writer - @utils = utils - @plugins = plugins - @config = config - @prefix = @config.mock_prefix - @suffix = @config.mock_suffix - @weak = @config.weak - @include_inline = @config.treat_inlines - @ordered = @config.enforce_strict_ordering - @framework = @config.framework.to_s - @fail_on_unexpected_calls = @config.fail_on_unexpected_calls - @exclude_setjmp_h = @config.exclude_setjmp_h - @subdir = @config.subdir - - @includes_h_pre_orig_header = (@config.includes || @config.includes_h_pre_orig_header || []).map { |h| h =~ /</ ? h : "\"#{h}\"" } - @includes_h_post_orig_header = (@config.includes_h_post_orig_header || []).map { |h| h =~ /</ ? h : "\"#{h}\"" } - @includes_c_pre_header = (@config.includes_c_pre_header || []).map { |h| h =~ /</ ? h : "\"#{h}\"" } - @includes_c_post_header = (@config.includes_c_post_header || []).map { |h| h =~ /</ ? h : "\"#{h}\"" } - - here = File.dirname __FILE__ - unity_path_in_ceedling = "#{here}/../../unity" # path to Unity from within Ceedling - unity_path_in_cmock = "#{here}/../vendor/unity" # path to Unity from within CMock - # path to Unity as specified by env var - unity_path_in_env = ENV.key?('UNITY_DIR') ? File.expand_path(ENV.fetch('UNITY_DIR')) : nil - - if unity_path_in_env && File.exist?(unity_path_in_env) - require "#{unity_path_in_env}/auto/type_sanitizer" - elsif File.exist? unity_path_in_ceedling - require "#{unity_path_in_ceedling}/auto/type_sanitizer" - elsif File.exist? unity_path_in_cmock - require "#{unity_path_in_cmock}/auto/type_sanitizer" - else - raise 'Failed to find an instance of Unity to pull in type_sanitizer module!' - end - end - - def create_mock(module_name, parsed_stuff, module_ext = nil, folder = nil) - # determine the name for our new mock - mock_name = @prefix + module_name + @suffix - - # determine the folder our mock will reside - mock_folder = if folder && @subdir - File.join(@subdir, folder) - elsif @subdir - @subdir - else - folder - end - - # adds a trailing slash to the folder output - mock_folder = File.join(mock_folder, '') if mock_folder - - # create out mock project from incoming data - mock_project = { - :module_name => module_name, - :module_ext => (module_ext || '.h'), - :mock_name => mock_name, - :clean_name => TypeSanitizer.sanitize_c_identifier(mock_name), - :folder => mock_folder, - :parsed_stuff => parsed_stuff, - :skeleton => false - } - - create_mock_subdir(mock_project) - create_mock_header_file(mock_project) - create_mock_source_file(mock_project) - end - - def create_skeleton(module_name, parsed_stuff) - mock_project = { - :module_name => module_name, - :module_ext => '.h', - :parsed_stuff => parsed_stuff, - :skeleton => true - } - - create_skeleton_source_file(mock_project) - end - - private if $ThisIsOnlyATest.nil? ############################## - - def create_mock_subdir(mock_project) - @file_writer.create_subdir(mock_project[:folder]) - end - - def create_using_statement(file, function) - file << "using namespace #{function[:namespace].join('::')};\n" unless function[:namespace].empty? - end - - def create_mock_header_file(mock_project) - if @include_inline == :include - @file_writer.create_file(mock_project[:module_name] + (mock_project[:module_ext]), mock_project[:folder]) do |file, _filename| - file << mock_project[:parsed_stuff][:normalized_source] - end - end - - @file_writer.create_file(mock_project[:mock_name] + mock_project[:module_ext], mock_project[:folder]) do |file, filename| - create_mock_header_header(file, filename, mock_project) - create_mock_header_service_call_declarations(file, mock_project) - create_typedefs(file, mock_project) - mock_project[:parsed_stuff][:functions].each do |function| - create_using_statement(file, function) - file << @plugins.run(:mock_function_declarations, function) - end - create_mock_header_footer(file) - end - end - - def create_mock_source_file(mock_project) - @file_writer.create_file(mock_project[:mock_name] + '.c', mock_project[:folder]) do |file, filename| - create_source_header_section(file, filename, mock_project) - create_instance_structure(file, mock_project) - create_extern_declarations(file) - create_mock_verify_function(file, mock_project) - create_mock_init_function(file, mock_project) - create_mock_destroy_function(file, mock_project) - mock_project[:parsed_stuff][:functions].each do |function| - create_mock_implementation(file, function) - create_mock_interfaces(file, function) - end - end - end - - def create_skeleton_source_file(mock_project) - filename = "#{@config.mock_path}/#{@subdir + '/' if @subdir}#{mock_project[:module_name]}.c" - existing = File.exist?(filename) ? File.read(filename) : '' - @file_writer.append_file(mock_project[:module_name] + '.c', @subdir) do |file, fullname| - blank_project = mock_project.clone - blank_project[:parsed_stuff] = { :functions => [] } - create_source_header_section(file, fullname, blank_project) if existing.empty? - mock_project[:parsed_stuff][:functions].each do |function| - create_function_skeleton(file, function, existing) - end - end - end - - def create_mock_header_header(file, _filename, mock_project) - define_name = mock_project[:clean_name].upcase - orig_filename = (mock_project[:folder] || '') + mock_project[:module_name] + mock_project[:module_ext] - file << "/* AUTOGENERATED FILE. DO NOT EDIT. */\n" - file << "#ifndef _#{define_name}_H\n" - file << "#define _#{define_name}_H\n\n" - file << "#include \"#{@framework}.h\"\n" - @includes_h_pre_orig_header.each { |inc| file << "#include #{inc}\n" } - file << @config.orig_header_include_fmt.gsub(/%s/, orig_filename.to_s) + "\n" - @includes_h_post_orig_header.each { |inc| file << "#include #{inc}\n" } - plugin_includes = @plugins.run(:include_files) - file << plugin_includes unless plugin_includes.empty? - file << "\n" - file << "/* Ignore the following warnings, since we are copying code */\n" - file << "#if defined(__GNUC__) && !defined(__ICC) && !defined(__TMS470__)\n" - file << "#if __GNUC__ > 4 || (__GNUC__ == 4 && (__GNUC_MINOR__ > 6 || (__GNUC_MINOR__ == 6 && __GNUC_PATCHLEVEL__ > 0)))\n" - file << "#pragma GCC diagnostic push\n" - file << "#endif\n" - file << "#if !defined(__clang__)\n" - file << "#pragma GCC diagnostic ignored \"-Wpragmas\"\n" - file << "#endif\n" - file << "#pragma GCC diagnostic ignored \"-Wunknown-pragmas\"\n" - file << "#pragma GCC diagnostic ignored \"-Wduplicate-decl-specifier\"\n" - file << "#endif\n" - file << "\n" - end - - def create_typedefs(file, mock_project) - file << "\n" - mock_project[:parsed_stuff][:typedefs].each { |typedef| file << "#{typedef}\n" } - file << "\n\n" - end - - def create_mock_header_service_call_declarations(file, mock_project) - file << "void #{mock_project[:clean_name]}_Init(void);\n" - file << "void #{mock_project[:clean_name]}_Destroy(void);\n" - file << "void #{mock_project[:clean_name]}_Verify(void);\n\n" - end - - def create_mock_header_footer(header) - header << "\n" - header << "#if defined(__GNUC__) && !defined(__ICC) && !defined(__TMS470__)\n" - header << "#if __GNUC__ > 4 || (__GNUC__ == 4 && (__GNUC_MINOR__ > 6 || (__GNUC_MINOR__ == 6 && __GNUC_PATCHLEVEL__ > 0)))\n" - header << "#pragma GCC diagnostic pop\n" - header << "#endif\n" - header << "#endif\n" - header << "\n" - header << "#endif\n" - end - - def create_source_header_section(file, filename, mock_project) - header_file = (mock_project[:folder] || '') + filename.gsub('.c', mock_project[:module_ext]) - file << "/* AUTOGENERATED FILE. DO NOT EDIT. */\n" unless mock_project[:parsed_stuff][:functions].empty? - file << "#include <string.h>\n" - file << "#include <stdlib.h>\n" - unless @exclude_setjmp_h - file << "#include <setjmp.h>\n" - end - file << "#include \"cmock.h\"\n" - @includes_c_pre_header.each { |inc| file << "#include #{inc}\n" } - file << "#include \"#{header_file}\"\n" - @includes_c_post_header.each { |inc| file << "#include #{inc}\n" } - file << "\n" - strs = [] - mock_project[:parsed_stuff][:functions].each do |func| - strs << func[:name] - func[:args].each { |arg| strs << arg[:name] } - end - strs.uniq.sort.each do |str| - file << "static const char* CMockString_#{str} = \"#{str}\";\n" - end - file << "\n" - end - - def create_instance_structure(file, mock_project) - functions = mock_project[:parsed_stuff][:functions] - functions.each do |function| - file << "typedef struct _CMOCK_#{function[:name]}_CALL_INSTANCE\n{\n" - file << " UNITY_LINE_TYPE LineNumber;\n" - file << @plugins.run(:instance_typedefs, function) - file << "\n} CMOCK_#{function[:name]}_CALL_INSTANCE;\n\n" - end - file << "static struct #{mock_project[:clean_name]}Instance\n{\n" - if functions.empty? - file << " unsigned char placeHolder;\n" - end - functions.each do |function| - file << @plugins.run(:instance_structure, function) - file << " CMOCK_MEM_INDEX_TYPE #{function[:name]}_CallInstance;\n" - end - file << "} Mock;\n\n" - end - - def create_extern_declarations(file) - unless @exclude_setjmp_h - file << "extern jmp_buf AbortFrame;\n" - end - if @ordered - file << "extern int GlobalExpectCount;\n" - file << "extern int GlobalVerifyOrder;\n" - end - file << "\n" - end - - def create_mock_verify_function(file, mock_project) - file << "void #{mock_project[:clean_name]}_Verify(void)\n{\n" - verifications = mock_project[:parsed_stuff][:functions].collect do |function| - v = @plugins.run(:mock_verify, function) - v.empty? ? v : [" call_instance = Mock.#{function[:name]}_CallInstance;\n", v] - end.join - unless verifications.empty? - file << " UNITY_LINE_TYPE cmock_line = TEST_LINE_NUM;\n" - file << " CMOCK_MEM_INDEX_TYPE call_instance;\n" - file << verifications - end - file << "}\n\n" - end - - def create_mock_init_function(file, mock_project) - file << "void #{mock_project[:clean_name]}_Init(void)\n{\n" - file << " #{mock_project[:clean_name]}_Destroy();\n" - file << "}\n\n" - end - - def create_mock_destroy_function(file, mock_project) - file << "void #{mock_project[:clean_name]}_Destroy(void)\n{\n" - file << " CMock_Guts_MemFreeAll();\n" - file << " memset(&Mock, 0, sizeof(Mock));\n" - file << mock_project[:parsed_stuff][:functions].collect { |function| @plugins.run(:mock_destroy, function) }.join - - unless @fail_on_unexpected_calls - file << mock_project[:parsed_stuff][:functions].collect { |function| @plugins.run(:mock_ignore, function) }.join - end - - if @ordered - file << " GlobalExpectCount = 0;\n" - file << " GlobalVerifyOrder = 0;\n" - end - file << "}\n\n" - end - - def create_mock_implementation(file, function) - # prepare return value and arguments - function_mod_and_rettype = (function[:modifier].empty? ? '' : "#{function[:modifier]} ") + - (function[:return][:type]) + - (function[:c_calling_convention] ? " #{function[:c_calling_convention]}" : '') - args_string = function[:args_string] - args_string += (', ' + function[:var_arg]) unless function[:var_arg].nil? - - # Encapsulate in namespace(s) if applicable - function[:namespace].each do |ns| - file << "namespace #{ns} {\n" - end - - # Determine class prefix (if any) - cls_pre = '' - unless function[:class].nil? - cls_pre = "#{function[:class]}::" - end - - # Create mock function - unless @weak.empty? - file << "#if defined (__IAR_SYSTEMS_ICC__)\n" - file << "#pragma weak #{function[:unscoped_name]}\n" - file << "#else\n" - file << "#{function_mod_and_rettype} #{function[:unscoped_name]}(#{args_string}) #{weak};\n" - file << "#endif\n\n" - end - file << "#{function_mod_and_rettype} #{cls_pre}#{function[:unscoped_name]}(#{args_string})\n" - file << "{\n" - file << " UNITY_LINE_TYPE cmock_line = TEST_LINE_NUM;\n" - file << " CMOCK_#{function[:name]}_CALL_INSTANCE* cmock_call_instance;\n" - file << " UNITY_SET_DETAIL(CMockString_#{function[:name]});\n" - file << " cmock_call_instance = (CMOCK_#{function[:name]}_CALL_INSTANCE*)CMock_Guts_GetAddressFor(Mock.#{function[:name]}_CallInstance);\n" - file << " Mock.#{function[:name]}_CallInstance = CMock_Guts_MemNext(Mock.#{function[:name]}_CallInstance);\n" - file << @plugins.run(:mock_implementation_precheck, function) - file << " UNITY_TEST_ASSERT_NOT_NULL(cmock_call_instance, cmock_line, CMockStringCalledMore);\n" - file << " cmock_line = cmock_call_instance->LineNumber;\n" - if @ordered - file << " if (cmock_call_instance->CallOrder > ++GlobalVerifyOrder)\n" - file << " UNITY_TEST_FAIL(cmock_line, CMockStringCalledEarly);\n" - file << " if (cmock_call_instance->CallOrder < GlobalVerifyOrder)\n" - file << " UNITY_TEST_FAIL(cmock_line, CMockStringCalledLate);\n" - end - file << @plugins.run(:mock_implementation, function) - file << " UNITY_CLR_DETAILS();\n" - file << " return cmock_call_instance->ReturnVal;\n" unless function[:return][:void?] - file << "}\n" - - # Close any namespace(s) opened above - function[:namespace].each do - file << "}\n" - end - - file << "\n" - end - - def create_mock_interfaces(file, function) - file << @utils.code_add_argument_loader(function) - file << @plugins.run(:mock_interfaces, function) - end - - def create_function_skeleton(file, function, existing) - # prepare return value and arguments - function_mod_and_rettype = (function[:modifier].empty? ? '' : "#{function[:modifier]} ") + - (function[:return][:type]) + - (function[:c_calling_convention] ? " #{function[:c_calling_convention]}" : '') - args_string = function[:args_string] - args_string += (', ' + function[:var_arg]) unless function[:var_arg].nil? - - decl = "#{function_mod_and_rettype} #{function[:name]}(#{args_string})" - - return if existing.include?(decl) - - file << "#{decl}\n" - file << "{\n" - file << " /*TODO: Implement Me!*/\n" - function[:args].each { |arg| file << " (void)#{arg[:name]};\n" } - file << " return (#{(function[:return][:type])})0;\n" unless function[:return][:void?] - file << "}\n\n" - end -end diff --git a/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_generator_plugin_array.rb b/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_generator_plugin_array.rb deleted file mode 100644 index a9864ab74..000000000 --- a/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_generator_plugin_array.rb +++ /dev/null @@ -1,63 +0,0 @@ -# ========================================== -# CMock Project - Automatic Mock Generation for C -# Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams -# [Released under MIT License. Please refer to license.txt for details] -# ========================================== - -class CMockGeneratorPluginArray - attr_reader :priority - attr_accessor :config, :utils, :unity_helper, :ordered - def initialize(config, utils) - @config = config - @ptr_handling = @config.when_ptr - @ordered = @config.enforce_strict_ordering - @utils = utils - @unity_helper = @utils.helpers[:unity_helper] - @priority = 8 - end - - def instance_typedefs(function) - function[:args].inject('') do |all, arg| - arg[:ptr?] ? all + " int Expected_#{arg[:name]}_Depth;\n" : all - end - end - - def mock_function_declarations(function) - return nil unless function[:contains_ptr?] - - args_call = function[:args].map { |m| m[:ptr?] ? "#{m[:name]}, #{m[:name]}_Depth" : (m[:name]).to_s }.join(', ') - args_string = function[:args].map do |m| - type = @utils.arg_type_with_const(m) - m[:ptr?] ? "#{type} #{m[:name]}, int #{m[:name]}_Depth" : "#{type} #{m[:name]}" - end.join(', ') - if function[:return][:void?] - return "#define #{function[:name]}_ExpectWithArray(#{args_call}) #{function[:name]}_CMockExpectWithArray(__LINE__, #{args_call})\n" \ - "void #{function[:name]}_CMockExpectWithArray(UNITY_LINE_TYPE cmock_line, #{args_string});\n" - else - return "#define #{function[:name]}_ExpectWithArrayAndReturn(#{args_call}, cmock_retval) #{function[:name]}_CMockExpectWithArrayAndReturn(__LINE__, #{args_call}, cmock_retval)\n" \ - "void #{function[:name]}_CMockExpectWithArrayAndReturn(UNITY_LINE_TYPE cmock_line, #{args_string}, #{function[:return][:str]});\n" - end - end - - def mock_interfaces(function) - return nil unless function[:contains_ptr?] - - lines = [] - func_name = function[:name] - args_string = function[:args].map do |m| - type = @utils.arg_type_with_const(m) - m[:ptr?] ? "#{type} #{m[:name]}, int #{m[:name]}_Depth" : "#{type} #{m[:name]}" - end.join(', ') - call_string = function[:args].map { |m| m[:ptr?] ? "#{m[:name]}, #{m[:name]}_Depth" : m[:name] }.join(', ') - lines << if function[:return][:void?] - "void #{func_name}_CMockExpectWithArray(UNITY_LINE_TYPE cmock_line, #{args_string})\n" - else - "void #{func_name}_CMockExpectWithArrayAndReturn(UNITY_LINE_TYPE cmock_line, #{args_string}, #{function[:return][:str]})\n" - end - lines << "{\n" - lines << @utils.code_add_base_expectation(func_name) - lines << " CMockExpectParameters_#{func_name}(cmock_call_instance, #{call_string});\n" - lines << " cmock_call_instance->ReturnVal = cmock_to_return;\n" unless function[:return][:void?] - lines << "}\n\n" - end -end diff --git a/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_generator_plugin_callback.rb b/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_generator_plugin_callback.rb deleted file mode 100644 index 6ba8e9bd9..000000000 --- a/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_generator_plugin_callback.rb +++ /dev/null @@ -1,88 +0,0 @@ -# ========================================== -# CMock Project - Automatic Mock Generation for C -# Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams -# [Released under MIT License. Please refer to license.txt for details] -# ========================================== - -class CMockGeneratorPluginCallback - attr_accessor :include_count - attr_reader :priority - attr_reader :config, :utils - - def initialize(config, utils) - @config = config - @utils = utils - @priority = 6 - - @include_count = @config.callback_include_count - end - - def instance_structure(function) - func_name = function[:name] - " char #{func_name}_CallbackBool;\n" \ - " CMOCK_#{func_name}_CALLBACK #{func_name}_CallbackFunctionPointer;\n" \ - " int #{func_name}_CallbackCalls;\n" - end - - def mock_function_declarations(function) - func_name = function[:name] - return_type = function[:return][:type] - action = @config.callback_after_arg_check ? 'AddCallback' : 'Stub' - style = (@include_count ? 1 : 0) | (function[:args].empty? ? 0 : 2) - styles = ['void', 'int cmock_num_calls', function[:args_string], "#{function[:args_string]}, int cmock_num_calls"] - "typedef #{return_type} (* CMOCK_#{func_name}_CALLBACK)(#{styles[style]});\n" \ - "void #{func_name}_AddCallback(CMOCK_#{func_name}_CALLBACK Callback);\n" \ - "void #{func_name}_Stub(CMOCK_#{func_name}_CALLBACK Callback);\n" \ - "#define #{func_name}_StubWithCallback #{func_name}_#{action}\n" - end - - def generate_call(function) - args = function[:args].map { |m| m[:name] } - args << "Mock.#{function[:name]}_CallbackCalls++" if @include_count - "Mock.#{function[:name]}_CallbackFunctionPointer(#{args.join(', ')})" - end - - def mock_implementation(function) - " if (Mock.#{function[:name]}_CallbackFunctionPointer != NULL)\n {\n" + - if function[:return][:void?] - " #{generate_call(function)};\n }\n" - else - " cmock_call_instance->ReturnVal = #{generate_call(function)};\n }\n" - end - end - - def mock_implementation_precheck(function) - " if (!Mock.#{function[:name]}_CallbackBool &&\n" \ - " Mock.#{function[:name]}_CallbackFunctionPointer != NULL)\n {\n" + - if function[:return][:void?] - " #{generate_call(function)};\n" \ - " UNITY_CLR_DETAILS();\n" \ - " return;\n }\n" - else - " #{function[:return][:type]} cmock_cb_ret = #{generate_call(function)};\n" \ - " UNITY_CLR_DETAILS();\n" \ - " return cmock_cb_ret;\n }\n" - end - end - - def mock_interfaces(function) - func_name = function[:name] - has_ignore = @config.plugins.include? :ignore - lines = '' - lines << "void #{func_name}_AddCallback(CMOCK_#{func_name}_CALLBACK Callback)\n{\n" - lines << " Mock.#{func_name}_IgnoreBool = (char)0;\n" if has_ignore - lines << " Mock.#{func_name}_CallbackBool = (char)1;\n" - lines << " Mock.#{func_name}_CallbackFunctionPointer = Callback;\n}\n\n" - lines << "void #{func_name}_Stub(CMOCK_#{func_name}_CALLBACK Callback)\n{\n" - lines << " Mock.#{func_name}_IgnoreBool = (char)0;\n" if has_ignore - lines << " Mock.#{func_name}_CallbackBool = (char)0;\n" - lines << " Mock.#{func_name}_CallbackFunctionPointer = Callback;\n}\n\n" - end - - def mock_verify(function) - func_name = function[:name] - " if (Mock.#{func_name}_CallbackFunctionPointer != NULL)\n {\n" \ - " call_instance = CMOCK_GUTS_NONE;\n" \ - " (void)call_instance;\n }\n" - end -end diff --git a/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_generator_plugin_cexception.rb b/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_generator_plugin_cexception.rb deleted file mode 100644 index 7e2d7b628..000000000 --- a/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_generator_plugin_cexception.rb +++ /dev/null @@ -1,50 +0,0 @@ -# ========================================== -# CMock Project - Automatic Mock Generation for C -# Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams -# [Released under MIT License. Please refer to license.txt for details] -# ========================================== - -class CMockGeneratorPluginCexception - attr_reader :priority - attr_reader :config, :utils - - def initialize(config, utils) - @config = config - @utils = utils - @priority = 7 - raise 'Error: cexception is not supported without setjmp support' if @config.exclude_setjmp_h - end - - def include_files - "#include \"CException.h\"\n" - end - - def instance_typedefs(_function) - " CEXCEPTION_T ExceptionToThrow;\n" - end - - def mock_function_declarations(function) - if function[:args_string] == 'void' - "#define #{function[:name]}_ExpectAndThrow(cmock_to_throw) #{function[:name]}_CMockExpectAndThrow(__LINE__, cmock_to_throw)\n" \ - "void #{function[:name]}_CMockExpectAndThrow(UNITY_LINE_TYPE cmock_line, CEXCEPTION_T cmock_to_throw);\n" - else - "#define #{function[:name]}_ExpectAndThrow(#{function[:args_call]}, cmock_to_throw) #{function[:name]}_CMockExpectAndThrow(__LINE__, #{function[:args_call]}, cmock_to_throw)\n" \ - "void #{function[:name]}_CMockExpectAndThrow(UNITY_LINE_TYPE cmock_line, #{function[:args_string]}, CEXCEPTION_T cmock_to_throw);\n" - end - end - - def mock_implementation(_function) - " if (cmock_call_instance->ExceptionToThrow != CEXCEPTION_NONE)\n {\n" \ - " UNITY_CLR_DETAILS();\n" \ - " Throw(cmock_call_instance->ExceptionToThrow);\n }\n" - end - - def mock_interfaces(function) - arg_insert = function[:args_string] == 'void' ? '' : "#{function[:args_string]}, " - ["void #{function[:name]}_CMockExpectAndThrow(UNITY_LINE_TYPE cmock_line, #{arg_insert}CEXCEPTION_T cmock_to_throw)\n{\n", - @utils.code_add_base_expectation(function[:name]), - @utils.code_call_argument_loader(function), - " cmock_call_instance->ExceptionToThrow = cmock_to_throw;\n", - "}\n\n"].join - end -end diff --git a/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_generator_plugin_expect.rb b/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_generator_plugin_expect.rb deleted file mode 100644 index 3a79c1a4d..000000000 --- a/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_generator_plugin_expect.rb +++ /dev/null @@ -1,100 +0,0 @@ -# ========================================== -# CMock Project - Automatic Mock Generation for C -# Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams -# [Released under MIT License. Please refer to license.txt for details] -# ========================================== - -class CMockGeneratorPluginExpect - attr_reader :priority - attr_accessor :config, :utils, :unity_helper, :ordered - - def initialize(config, utils) - @config = config - @ptr_handling = @config.when_ptr - @ordered = @config.enforce_strict_ordering - @utils = utils - @unity_helper = @utils.helpers[:unity_helper] - @priority = 5 - - if @config.plugins.include? :expect_any_args - alias :mock_implementation :mock_implementation_might_check_args - else - alias :mock_implementation :mock_implementation_always_check_args - end - end - - def instance_typedefs(function) - lines = '' - lines << " #{function[:return][:type]} ReturnVal;\n" unless function[:return][:void?] - lines << " int CallOrder;\n" if @ordered - function[:args].each do |arg| - lines << " #{arg[:type]} Expected_#{arg[:name]};\n" - end - lines - end - - def mock_function_declarations(function) - if function[:args].empty? - if function[:return][:void?] - "#define #{function[:name]}_Expect() #{function[:name]}_CMockExpect(__LINE__)\n" \ - "void #{function[:name]}_CMockExpect(UNITY_LINE_TYPE cmock_line);\n" - else - "#define #{function[:name]}_ExpectAndReturn(cmock_retval) #{function[:name]}_CMockExpectAndReturn(__LINE__, cmock_retval)\n" \ - "void #{function[:name]}_CMockExpectAndReturn(UNITY_LINE_TYPE cmock_line, #{function[:return][:str]});\n" - end - elsif function[:return][:void?] - "#define #{function[:name]}_Expect(#{function[:args_call]}) #{function[:name]}_CMockExpect(__LINE__, #{function[:args_call]})\n" \ - "void #{function[:name]}_CMockExpect(UNITY_LINE_TYPE cmock_line, #{function[:args_string]});\n" - else - "#define #{function[:name]}_ExpectAndReturn(#{function[:args_call]}, cmock_retval) #{function[:name]}_CMockExpectAndReturn(__LINE__, #{function[:args_call]}, cmock_retval)\n" \ - "void #{function[:name]}_CMockExpectAndReturn(UNITY_LINE_TYPE cmock_line, #{function[:args_string]}, #{function[:return][:str]});\n" - end - end - - def mock_implementation_always_check_args(function) - lines = '' - function[:args].each do |arg| - lines << @utils.code_verify_an_arg_expectation(function, arg) - end - lines - end - - def mock_implementation_might_check_args(function) - return '' if function[:args].empty? - - lines = " if (!cmock_call_instance->ExpectAnyArgsBool)\n {\n" - function[:args].each do |arg| - lines << @utils.code_verify_an_arg_expectation(function, arg) - end - lines << " }\n" - lines - end - - def mock_interfaces(function) - lines = '' - func_name = function[:name] - lines << if function[:return][:void?] - if function[:args_string] == 'void' - "void #{func_name}_CMockExpect(UNITY_LINE_TYPE cmock_line)\n{\n" - else - "void #{func_name}_CMockExpect(UNITY_LINE_TYPE cmock_line, #{function[:args_string]})\n{\n" - end - elsif function[:args_string] == 'void' - "void #{func_name}_CMockExpectAndReturn(UNITY_LINE_TYPE cmock_line, #{function[:return][:str]})\n{\n" - else - "void #{func_name}_CMockExpectAndReturn(UNITY_LINE_TYPE cmock_line, #{function[:args_string]}, #{function[:return][:str]})\n{\n" - end - lines << @utils.code_add_base_expectation(func_name) - lines << @utils.code_call_argument_loader(function) - lines << @utils.code_assign_argument_quickly('cmock_call_instance->ReturnVal', function[:return]) unless function[:return][:void?] - lines << "}\n\n" - end - - def mock_verify(function) - " if (CMOCK_GUTS_NONE != call_instance)\n" \ - " {\n" \ - " UNITY_SET_DETAIL(CMockString_#{function[:name]});\n" \ - " UNITY_TEST_FAIL(cmock_line, CMockStringCalledLess);\n" \ - " }\n" - end -end diff --git a/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_generator_plugin_expect_any_args.rb b/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_generator_plugin_expect_any_args.rb deleted file mode 100644 index 0fc88e124..000000000 --- a/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_generator_plugin_expect_any_args.rb +++ /dev/null @@ -1,50 +0,0 @@ -# ========================================== -# CMock Project - Automatic Mock Generation for C -# Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams -# [Released under MIT License. Please refer to license.txt for details] -# ========================================== - -class CMockGeneratorPluginExpectAnyArgs - attr_reader :priority - attr_reader :config, :utils - - def initialize(config, utils) - @config = config - @utils = utils - @priority = 3 - end - - def instance_typedefs(_function) - " char ExpectAnyArgsBool;\n" - end - - def mock_function_declarations(function) - if function[:args].empty? - '' - elsif function[:return][:void?] - "#define #{function[:name]}_ExpectAnyArgs() #{function[:name]}_CMockExpectAnyArgs(__LINE__)\n" \ - "void #{function[:name]}_CMockExpectAnyArgs(UNITY_LINE_TYPE cmock_line);\n" - else - "#define #{function[:name]}_ExpectAnyArgsAndReturn(cmock_retval) #{function[:name]}_CMockExpectAnyArgsAndReturn(__LINE__, cmock_retval)\n" \ - "void #{function[:name]}_CMockExpectAnyArgsAndReturn(UNITY_LINE_TYPE cmock_line, #{function[:return][:str]});\n" - end - end - - def mock_interfaces(function) - lines = '' - unless function[:args].empty? - lines << if function[:return][:void?] - "void #{function[:name]}_CMockExpectAnyArgs(UNITY_LINE_TYPE cmock_line)\n{\n" - else - "void #{function[:name]}_CMockExpectAnyArgsAndReturn(UNITY_LINE_TYPE cmock_line, #{function[:return][:str]})\n{\n" - end - lines << @utils.code_add_base_expectation(function[:name], true) - unless function[:return][:void?] - lines << " cmock_call_instance->ReturnVal = cmock_to_return;\n" - end - lines << " cmock_call_instance->ExpectAnyArgsBool = (char)1;\n" - lines << "}\n\n" - end - lines - end -end diff --git a/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_generator_plugin_ignore.rb b/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_generator_plugin_ignore.rb deleted file mode 100644 index b292f3d4f..000000000 --- a/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_generator_plugin_ignore.rb +++ /dev/null @@ -1,88 +0,0 @@ -# ========================================== -# CMock Project - Automatic Mock Generation for C -# Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams -# [Released under MIT License. Please refer to license.txt for details] -# ========================================== - -class CMockGeneratorPluginIgnore - attr_reader :priority - attr_reader :config, :utils - - def initialize(config, utils) - @config = config - @utils = utils - @priority = 2 - end - - def instance_structure(function) - if function[:return][:void?] - " char #{function[:name]}_IgnoreBool;\n" - else - " char #{function[:name]}_IgnoreBool;\n #{function[:return][:type]} #{function[:name]}_FinalReturn;\n" - end - end - - def mock_function_declarations(function) - lines = if function[:return][:void?] - "#define #{function[:name]}_Ignore() #{function[:name]}_CMockIgnore()\n" \ - "void #{function[:name]}_CMockIgnore(void);\n" - else - "#define #{function[:name]}_IgnoreAndReturn(cmock_retval) #{function[:name]}_CMockIgnoreAndReturn(__LINE__, cmock_retval)\n" \ - "void #{function[:name]}_CMockIgnoreAndReturn(UNITY_LINE_TYPE cmock_line, #{function[:return][:str]});\n" - end - - # Add stop ignore function. it does not matter if there are any args - lines << "#define #{function[:name]}_StopIgnore() #{function[:name]}_CMockStopIgnore()\n" \ - "void #{function[:name]}_CMockStopIgnore(void);\n" - lines - end - - def mock_implementation_precheck(function) - lines = " if (Mock.#{function[:name]}_IgnoreBool)\n {\n" - lines << " UNITY_CLR_DETAILS();\n" - if function[:return][:void?] - lines << " return;\n }\n" - else - retval = function[:return].merge(:name => 'cmock_call_instance->ReturnVal') - lines << " if (cmock_call_instance == NULL)\n return Mock.#{function[:name]}_FinalReturn;\n" - lines << ' ' + @utils.code_assign_argument_quickly("Mock.#{function[:name]}_FinalReturn", retval) unless retval[:void?] - lines << " return cmock_call_instance->ReturnVal;\n }\n" - end - lines - end - - def mock_interfaces(function) - lines = '' - lines << if function[:return][:void?] - "void #{function[:name]}_CMockIgnore(void)\n{\n" - else - "void #{function[:name]}_CMockIgnoreAndReturn(UNITY_LINE_TYPE cmock_line, #{function[:return][:str]})\n{\n" - end - unless function[:return][:void?] - lines << @utils.code_add_base_expectation(function[:name], false) - end - unless function[:return][:void?] - lines << " cmock_call_instance->ReturnVal = cmock_to_return;\n" - end - lines << " Mock.#{function[:name]}_IgnoreBool = (char)1;\n" - lines << "}\n\n" - - # Add stop ignore function. it does not matter if there are any args - lines << "void #{function[:name]}_CMockStopIgnore(void)\n{\n" - unless function[:return][:void?] - lines << " if(Mock.#{function[:name]}_IgnoreBool)\n" - lines << " Mock.#{function[:name]}_CallInstance = CMock_Guts_MemNext(Mock.#{function[:name]}_CallInstance);\n" - end - lines << " Mock.#{function[:name]}_IgnoreBool = (char)0;\n" - lines << "}\n\n" - end - - def mock_ignore(function) - " Mock.#{function[:name]}_IgnoreBool = (char) 1;\n" - end - - def mock_verify(function) - func_name = function[:name] - " if (Mock.#{func_name}_IgnoreBool)\n call_instance = CMOCK_GUTS_NONE;\n" - end -end diff --git a/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_generator_plugin_ignore_arg.rb b/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_generator_plugin_ignore_arg.rb deleted file mode 100644 index d55e84c25..000000000 --- a/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_generator_plugin_ignore_arg.rb +++ /dev/null @@ -1,42 +0,0 @@ -class CMockGeneratorPluginIgnoreArg - attr_reader :priority - attr_accessor :utils - - def initialize(_config, utils) - @utils = utils - @priority = 10 - end - - def instance_typedefs(function) - lines = '' - function[:args].each do |arg| - lines << " char IgnoreArg_#{arg[:name]};\n" - end - lines - end - - def mock_function_declarations(function) - lines = '' - function[:args].each do |arg| - lines << "#define #{function[:name]}_IgnoreArg_#{arg[:name]}()" - lines << " #{function[:name]}_CMockIgnoreArg_#{arg[:name]}(__LINE__)\n" - lines << "void #{function[:name]}_CMockIgnoreArg_#{arg[:name]}(UNITY_LINE_TYPE cmock_line);\n" - end - lines - end - - def mock_interfaces(function) - lines = [] - func_name = function[:name] - function[:args].each do |arg| - lines << "void #{func_name}_CMockIgnoreArg_#{arg[:name]}(UNITY_LINE_TYPE cmock_line)\n" - lines << "{\n" - lines << " CMOCK_#{func_name}_CALL_INSTANCE* cmock_call_instance = " \ - "(CMOCK_#{func_name}_CALL_INSTANCE*)CMock_Guts_GetAddressFor(CMock_Guts_MemEndOfChain(Mock.#{func_name}_CallInstance));\n" - lines << " UNITY_TEST_ASSERT_NOT_NULL(cmock_call_instance, cmock_line, CMockStringIgnPreExp);\n" - lines << " cmock_call_instance->IgnoreArg_#{arg[:name]} = 1;\n" - lines << "}\n\n" - end - lines - end -end diff --git a/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_generator_plugin_ignore_stateless.rb b/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_generator_plugin_ignore_stateless.rb deleted file mode 100644 index 9196edea4..000000000 --- a/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_generator_plugin_ignore_stateless.rb +++ /dev/null @@ -1,85 +0,0 @@ -# ========================================== -# CMock Project - Automatic Mock Generation for C -# Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams -# [Released under MIT License. Please refer to license.txt for details] -# ========================================== - -class CMockGeneratorPluginIgnoreStateless - attr_reader :priority - attr_reader :config, :utils - - def initialize(config, utils) - @config = config - @utils = utils - @priority = 2 - end - - def instance_structure(function) - if function[:return][:void?] - " char #{function[:name]}_IgnoreBool;\n" - else - " char #{function[:name]}_IgnoreBool;\n #{function[:return][:type]} #{function[:name]}_FinalReturn;\n" - end - end - - def mock_function_declarations(function) - lines = if function[:return][:void?] - "#define #{function[:name]}_Ignore() #{function[:name]}_CMockIgnore()\n" \ - "void #{function[:name]}_CMockIgnore(void);\n" - else - "#define #{function[:name]}_IgnoreAndReturn(cmock_retval) #{function[:name]}_CMockIgnoreAndReturn(cmock_retval)\n" \ - "void #{function[:name]}_CMockIgnoreAndReturn(#{function[:return][:str]});\n" - end - - # Add stop ignore function. it does not matter if there are any args - lines << "#define #{function[:name]}_StopIgnore() #{function[:name]}_CMockStopIgnore()\n" \ - "void #{function[:name]}_CMockStopIgnore(void);\n" - lines - end - - def mock_implementation_precheck(function) - lines = " if (Mock.#{function[:name]}_IgnoreBool)\n {\n" - lines << " UNITY_CLR_DETAILS();\n" - if function[:return][:void?] - lines << " return;\n }\n" - else - retval = function[:return].merge(:name => 'cmock_call_instance->ReturnVal') - lines << " if (cmock_call_instance == NULL)\n return Mock.#{function[:name]}_FinalReturn;\n" - lines << ' ' + @utils.code_assign_argument_quickly("Mock.#{function[:name]}_FinalReturn", retval) unless retval[:void?] - lines << " return cmock_call_instance->ReturnVal;\n }\n" - end - lines - end - - # this function is adjusted - def mock_interfaces(function) - lines = '' - lines << if function[:return][:void?] - "void #{function[:name]}_CMockIgnore(void)\n{\n" - else - "void #{function[:name]}_CMockIgnoreAndReturn(#{function[:return][:str]})\n{\n" - end - unless function[:return][:void?] - lines << " Mock.#{function[:name]}_CallInstance = CMOCK_GUTS_NONE;\n" - lines << " Mock.#{function[:name]}_FinalReturn = cmock_to_return;\n" - end - lines << " Mock.#{function[:name]}_IgnoreBool = (char)1;\n" - lines << "}\n\n" - - # Add stop ignore function. it does not matter if there are any args - lines << "void #{function[:name]}_CMockStopIgnore(void)\n{\n" - lines << " Mock.#{function[:name]}_IgnoreBool = (char)0;\n" - lines << "}\n\n" - - lines - end - - def mock_ignore(function) - " Mock.#{function[:name]}_IgnoreBool = (char)1;\n" - end - - def mock_verify(function) - func_name = function[:name] - " if (Mock.#{func_name}_IgnoreBool)\n call_instance = CMOCK_GUTS_NONE;\n" - end -end diff --git a/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_generator_plugin_return_thru_ptr.rb b/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_generator_plugin_return_thru_ptr.rb deleted file mode 100644 index 96b20035e..000000000 --- a/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_generator_plugin_return_thru_ptr.rb +++ /dev/null @@ -1,79 +0,0 @@ -class CMockGeneratorPluginReturnThruPtr - attr_reader :priority - attr_accessor :utils - - def initialize(_config, utils) - @utils = utils - @priority = 9 - end - - def instance_typedefs(function) - lines = '' - function[:args].each do |arg| - next unless @utils.ptr_or_str?(arg[:type]) && !(arg[:const?]) - - lines << " char ReturnThruPtr_#{arg[:name]}_Used;\n" - lines << " #{arg[:type]} ReturnThruPtr_#{arg[:name]}_Val;\n" - lines << " size_t ReturnThruPtr_#{arg[:name]}_Size;\n" - end - lines - end - - def mock_function_declarations(function) - lines = '' - function[:args].each do |arg| - next unless @utils.ptr_or_str?(arg[:type]) && !(arg[:const?]) - - lines << "#define #{function[:name]}_ReturnThruPtr_#{arg[:name]}(#{arg[:name]})" - # If the pointer type actually contains an asterisk, we can do sizeof the type (super safe), otherwise - # we need to do a sizeof the dereferenced pointer (which could be a problem if give the wrong size - lines << if arg[:type][-1] == '*' - " #{function[:name]}_CMockReturnMemThruPtr_#{arg[:name]}(__LINE__, #{arg[:name]}, sizeof(#{arg[:type][0..-2]}))\n" - else - " #{function[:name]}_CMockReturnMemThruPtr_#{arg[:name]}(__LINE__, #{arg[:name]}, sizeof(*#{arg[:name]}))\n" - end - lines << "#define #{function[:name]}_ReturnArrayThruPtr_#{arg[:name]}(#{arg[:name]}, cmock_len)" - lines << " #{function[:name]}_CMockReturnMemThruPtr_#{arg[:name]}(__LINE__, #{arg[:name]}, cmock_len * sizeof(*#{arg[:name]}))\n" - lines << "#define #{function[:name]}_ReturnMemThruPtr_#{arg[:name]}(#{arg[:name]}, cmock_size)" - lines << " #{function[:name]}_CMockReturnMemThruPtr_#{arg[:name]}(__LINE__, #{arg[:name]}, cmock_size)\n" - lines << "void #{function[:name]}_CMockReturnMemThruPtr_#{arg[:name]}(UNITY_LINE_TYPE cmock_line, #{arg[:type]} #{arg[:name]}, size_t cmock_size);\n" - end - lines - end - - def mock_interfaces(function) - lines = [] - func_name = function[:name] - function[:args].each do |arg| - arg_name = arg[:name] - next unless @utils.ptr_or_str?(arg[:type]) && !(arg[:const?]) - - lines << "void #{func_name}_CMockReturnMemThruPtr_#{arg_name}(UNITY_LINE_TYPE cmock_line, #{arg[:type]} #{arg_name}, size_t cmock_size)\n" - lines << "{\n" - lines << " CMOCK_#{func_name}_CALL_INSTANCE* cmock_call_instance = " \ - "(CMOCK_#{func_name}_CALL_INSTANCE*)CMock_Guts_GetAddressFor(CMock_Guts_MemEndOfChain(Mock.#{func_name}_CallInstance));\n" - lines << " UNITY_TEST_ASSERT_NOT_NULL(cmock_call_instance, cmock_line, CMockStringPtrPreExp);\n" - lines << " cmock_call_instance->ReturnThruPtr_#{arg_name}_Used = 1;\n" - lines << " cmock_call_instance->ReturnThruPtr_#{arg_name}_Val = #{arg_name};\n" - lines << " cmock_call_instance->ReturnThruPtr_#{arg_name}_Size = cmock_size;\n" - lines << "}\n\n" - end - lines - end - - def mock_implementation(function) - lines = [] - function[:args].each do |arg| - arg_name = arg[:name] - next unless @utils.ptr_or_str?(arg[:type]) && !(arg[:const?]) - - lines << " if (cmock_call_instance->ReturnThruPtr_#{arg_name}_Used)\n" - lines << " {\n" - lines << " UNITY_TEST_ASSERT_NOT_NULL(#{arg_name}, cmock_line, CMockStringPtrIsNULL);\n" - lines << " memcpy((void*)#{arg_name}, (void*)cmock_call_instance->ReturnThruPtr_#{arg_name}_Val,\n" - lines << " cmock_call_instance->ReturnThruPtr_#{arg_name}_Size);\n" - lines << " }\n" - end - lines - end -end diff --git a/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_generator_utils.rb b/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_generator_utils.rb deleted file mode 100644 index ecbc37e51..000000000 --- a/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_generator_utils.rb +++ /dev/null @@ -1,250 +0,0 @@ -# ========================================== -# CMock Project - Automatic Mock Generation for C -# Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams -# [Released under MIT License. Please refer to license.txt for details] -# ========================================== - -class CMockGeneratorUtils - attr_accessor :config, :helpers, :ordered, :ptr_handling, :arrays, :cexception - - def initialize(config, helpers = {}) - @config = config - @ptr_handling = @config.when_ptr - @ordered = @config.enforce_strict_ordering - @arrays = @config.plugins.include? :array - @cexception = @config.plugins.include? :cexception - @expect_any = @config.plugins.include? :expect_any_args - @return_thru_ptr = @config.plugins.include? :return_thru_ptr - @ignore_arg = @config.plugins.include? :ignore_arg - @ignore = @config.plugins.include? :ignore - @ignore_stateless = @config.plugins.include? :ignore_stateless - @treat_as = @config.treat_as - @helpers = helpers - end - - def self.arg_type_with_const(arg) - # Restore any "const" that was removed in header parsing - if arg[:type].include?('*') - arg[:const_ptr?] ? "#{arg[:type]} const" : arg[:type] - else - arg[:const?] ? "const #{arg[:type]}" : arg[:type] - end - end - - def arg_type_with_const(arg) - self.class.arg_type_with_const(arg) - end - - def code_verify_an_arg_expectation(function, arg) - if @arrays - case @ptr_handling - when :smart then code_verify_an_arg_expectation_with_smart_arrays(function, arg) - when :compare_data then code_verify_an_arg_expectation_with_normal_arrays(function, arg) - when :compare_ptr then raise "ERROR: the array plugin doesn't enjoy working with :compare_ptr only. Disable one option." - end - else - code_verify_an_arg_expectation_with_no_arrays(function, arg) - end - end - - def code_add_base_expectation(func_name, global_ordering_supported = true) - lines = " CMOCK_MEM_INDEX_TYPE cmock_guts_index = CMock_Guts_MemNew(sizeof(CMOCK_#{func_name}_CALL_INSTANCE));\n" - lines << " CMOCK_#{func_name}_CALL_INSTANCE* cmock_call_instance = (CMOCK_#{func_name}_CALL_INSTANCE*)CMock_Guts_GetAddressFor(cmock_guts_index);\n" - lines << " UNITY_TEST_ASSERT_NOT_NULL(cmock_call_instance, cmock_line, CMockStringOutOfMemory);\n" - lines << " memset(cmock_call_instance, 0, sizeof(*cmock_call_instance));\n" - lines << " Mock.#{func_name}_CallInstance = CMock_Guts_MemChain(Mock.#{func_name}_CallInstance, cmock_guts_index);\n" - lines << " Mock.#{func_name}_IgnoreBool = (char)0;\n" if @ignore || @ignore_stateless - lines << " cmock_call_instance->LineNumber = cmock_line;\n" - lines << " cmock_call_instance->CallOrder = ++GlobalExpectCount;\n" if @ordered && global_ordering_supported - lines << " cmock_call_instance->ExceptionToThrow = CEXCEPTION_NONE;\n" if @cexception - lines << " cmock_call_instance->ExpectAnyArgsBool = (char)0;\n" if @expect_any - lines - end - - def code_add_an_arg_expectation(arg, depth = 1) - lines = code_assign_argument_quickly("cmock_call_instance->Expected_#{arg[:name]}", arg) - lines << " cmock_call_instance->Expected_#{arg[:name]}_Depth = #{arg[:name]}_Depth;\n" if @arrays && (depth.class == String) - lines << " cmock_call_instance->IgnoreArg_#{arg[:name]} = 0;\n" if @ignore_arg - lines << " cmock_call_instance->ReturnThruPtr_#{arg[:name]}_Used = 0;\n" if @return_thru_ptr && ptr_or_str?(arg[:type]) && !(arg[:const?]) - lines - end - - def code_assign_argument_quickly(dest, arg) - if arg[:ptr?] || @treat_as.include?(arg[:type]) - " #{dest} = #{arg[:name]};\n" - else - assert_expr = "sizeof(#{arg[:name]}) == sizeof(#{arg[:type]}) ? 1 : -1" - comment = "/* add #{arg[:type]} to :treat_as_array if this causes an error */" - " memcpy((void*)(&#{dest}), (void*)(&#{arg[:name]}),\n" \ - " sizeof(#{arg[:type]}[#{assert_expr}])); #{comment}\n" - end - end - - def code_add_argument_loader(function) - if function[:args_string] != 'void' - if @arrays - args_string = function[:args].map do |m| - type = arg_type_with_const(m) - m[:ptr?] ? "#{type} #{m[:name]}, int #{m[:name]}_Depth" : "#{type} #{m[:name]}" - end.join(', ') - "void CMockExpectParameters_#{function[:name]}(CMOCK_#{function[:name]}_CALL_INSTANCE* cmock_call_instance, #{args_string});\n" \ - "void CMockExpectParameters_#{function[:name]}(CMOCK_#{function[:name]}_CALL_INSTANCE* cmock_call_instance, #{args_string})\n{\n" + - function[:args].inject('') { |all, arg| all + code_add_an_arg_expectation(arg, (arg[:ptr?] ? "#{arg[:name]}_Depth" : 1)) } + - "}\n\n" - else - "void CMockExpectParameters_#{function[:name]}(CMOCK_#{function[:name]}_CALL_INSTANCE* cmock_call_instance, #{function[:args_string]});\n" \ - "void CMockExpectParameters_#{function[:name]}(CMOCK_#{function[:name]}_CALL_INSTANCE* cmock_call_instance, #{function[:args_string]})\n{\n" + - function[:args].inject('') { |all, arg| all + code_add_an_arg_expectation(arg) } + - "}\n\n" - end - else - '' - end - end - - def code_call_argument_loader(function) - if function[:args_string] != 'void' - args = function[:args].map do |m| - if @arrays && m[:ptr?] && !(m[:array_data?]) - "#{m[:name]}, 1" - elsif @arrays && m[:array_size?] - "#{m[:name]}, #{m[:name]}" - else - m[:name] - end - end - " CMockExpectParameters_#{function[:name]}(cmock_call_instance, #{args.join(', ')});\n" - else - '' - end - end - - def ptr_or_str?(arg_type) - (arg_type.include?('*') || - @treat_as.fetch(arg_type, '').include?('*')) - end - - # private ###################### - - def lookup_expect_type(_function, arg) - c_type = arg[:type] - arg_name = arg[:name] - expected = "cmock_call_instance->Expected_#{arg_name}" - ignore = "cmock_call_instance->IgnoreArg_#{arg_name}" - unity_func = if (arg[:ptr?]) && ((c_type =~ /\*\*/) || (@ptr_handling == :compare_ptr)) - ['UNITY_TEST_ASSERT_EQUAL_PTR', ''] - else - @helpers.nil? || @helpers[:unity_helper].nil? ? ['UNITY_TEST_ASSERT_EQUAL', ''] : @helpers[:unity_helper].get_helper(c_type) - end - [c_type, arg_name, expected, ignore, unity_func[0], unity_func[1]] - end - - def code_verify_an_arg_expectation_with_no_arrays(function, arg) - c_type, arg_name, expected, ignore, unity_func, pre = lookup_expect_type(function, arg) - lines = '' - lines << " if (!#{ignore})\n" if @ignore_arg - lines << " {\n" - lines << " UNITY_SET_DETAILS(CMockString_#{function[:name]},CMockString_#{arg_name});\n" - case unity_func - when 'UNITY_TEST_ASSERT_EQUAL_MEMORY' - c_type_local = c_type.gsub(/\*$/, '') - lines << " UNITY_TEST_ASSERT_EQUAL_MEMORY((void*)(#{pre}#{expected}), (void*)(#{pre}#{arg_name}), sizeof(#{c_type_local}), cmock_line, CMockStringMismatch);\n" - when 'UNITY_TEST_ASSERT_EQUAL_MEMORY_ARRAY' - if pre == '&' - lines << " UNITY_TEST_ASSERT_EQUAL_MEMORY((void*)(#{pre}#{expected}), (void*)(#{pre}#{arg_name}), sizeof(#{c_type.sub('*', '')}), cmock_line, CMockStringMismatch);\n" - else - lines << " if (#{pre}#{expected} == NULL)\n" - lines << " { UNITY_TEST_ASSERT_NULL(#{pre}#{arg_name}, cmock_line, CMockStringExpNULL); }\n" - lines << " else\n" - lines << " { UNITY_TEST_ASSERT_EQUAL_MEMORY((void*)(#{pre}#{expected}), (void*)(#{pre}#{arg_name}), sizeof(#{c_type.sub('*', '')}), cmock_line, CMockStringMismatch); }\n" - end - when /_ARRAY/ - if pre == '&' - lines << " #{unity_func}(#{pre}#{expected}, #{pre}#{arg_name}, 1, cmock_line, CMockStringMismatch);\n" - else - lines << " if (#{pre}#{expected} == NULL)\n" - lines << " { UNITY_TEST_ASSERT_NULL(#{pre}#{arg_name}, cmock_line, CMockStringExpNULL); }\n" - lines << " else\n" - lines << " { #{unity_func}(#{pre}#{expected}, #{pre}#{arg_name}, 1, cmock_line, CMockStringMismatch); }\n" - end - else - lines << " #{unity_func}(#{pre}#{expected}, #{pre}#{arg_name}, cmock_line, CMockStringMismatch);\n" - end - lines << " }\n" - lines - end - - def code_verify_an_arg_expectation_with_normal_arrays(function, arg) - c_type, arg_name, expected, ignore, unity_func, pre = lookup_expect_type(function, arg) - depth_name = arg[:ptr?] ? "cmock_call_instance->Expected_#{arg_name}_Depth" : 1 - lines = '' - lines << " if (!#{ignore})\n" if @ignore_arg - lines << " {\n" - lines << " UNITY_SET_DETAILS(CMockString_#{function[:name]},CMockString_#{arg_name});\n" - case unity_func - when 'UNITY_TEST_ASSERT_EQUAL_MEMORY' - c_type_local = c_type.gsub(/\*$/, '') - lines << " UNITY_TEST_ASSERT_EQUAL_MEMORY((void*)(#{pre}#{expected}), (void*)(#{pre}#{arg_name}), sizeof(#{c_type_local}), cmock_line, CMockStringMismatch);\n" - when 'UNITY_TEST_ASSERT_EQUAL_MEMORY_ARRAY' - if pre == '&' - lines << " UNITY_TEST_ASSERT_EQUAL_MEMORY((void*)(#{pre}#{expected}), (void*)(#{pre}#{arg_name}), sizeof(#{c_type.sub('*', '')}), cmock_line, CMockStringMismatch);\n" - else - lines << " if (#{pre}#{expected} == NULL)\n" - lines << " { UNITY_TEST_ASSERT_NULL(#{pre}#{arg_name}, cmock_line, CMockStringExpNULL); }\n" - lines << " else\n" - lines << " { UNITY_TEST_ASSERT_EQUAL_MEMORY_ARRAY((void*)(#{pre}#{expected}), (void*)(#{pre}#{arg_name}), sizeof(#{c_type.sub('*', '')}), #{depth_name}, cmock_line, CMockStringMismatch); }\n" - end - when /_ARRAY/ - if pre == '&' - lines << " #{unity_func}(#{pre}#{expected}, #{pre}#{arg_name}, #{depth_name}, cmock_line, CMockStringMismatch);\n" - else - lines << " if (#{pre}#{expected} == NULL)\n" - lines << " { UNITY_TEST_ASSERT_NULL(#{pre}#{arg_name}, cmock_line, CMockStringExpNULL); }\n" - lines << " else\n" - lines << " { #{unity_func}(#{pre}#{expected}, #{pre}#{arg_name}, #{depth_name}, cmock_line, CMockStringMismatch); }\n" - end - else - lines << " #{unity_func}(#{pre}#{expected}, #{pre}#{arg_name}, cmock_line, CMockStringMismatch);\n" - end - lines << " }\n" - lines - end - - def code_verify_an_arg_expectation_with_smart_arrays(function, arg) - c_type, arg_name, expected, ignore, unity_func, pre = lookup_expect_type(function, arg) - depth_name = arg[:ptr?] ? "cmock_call_instance->Expected_#{arg_name}_Depth" : 1 - lines = '' - lines << " if (!#{ignore})\n" if @ignore_arg - lines << " {\n" - lines << " UNITY_SET_DETAILS(CMockString_#{function[:name]},CMockString_#{arg_name});\n" - case unity_func - when 'UNITY_TEST_ASSERT_EQUAL_MEMORY' - c_type_local = c_type.gsub(/\*$/, '') - lines << " UNITY_TEST_ASSERT_EQUAL_MEMORY((void*)(#{pre}#{expected}), (void*)(#{pre}#{arg_name}), sizeof(#{c_type_local}), cmock_line, CMockStringMismatch);\n" - when 'UNITY_TEST_ASSERT_EQUAL_MEMORY_ARRAY' - if pre == '&' - lines << " UNITY_TEST_ASSERT_EQUAL_MEMORY_ARRAY((void*)(#{pre}#{expected}), (void*)(#{pre}#{arg_name}), sizeof(#{c_type.sub('*', '')}), #{depth_name}, cmock_line, CMockStringMismatch);\n" - else - lines << " if (#{pre}#{expected} == NULL)\n" - lines << " { UNITY_TEST_ASSERT_NULL(#{arg_name}, cmock_line, CMockStringExpNULL); }\n" - lines << (depth_name != 1 ? " else if (#{depth_name} == 0)\n { UNITY_TEST_ASSERT_EQUAL_PTR(#{pre}#{expected}, #{pre}#{arg_name}, cmock_line, CMockStringMismatch); }\n" : '') - lines << " else\n" - lines << " { UNITY_TEST_ASSERT_EQUAL_MEMORY_ARRAY((void*)(#{pre}#{expected}), (void*)(#{pre}#{arg_name}), sizeof(#{c_type.sub('*', '')}), #{depth_name}, cmock_line, CMockStringMismatch); }\n" - end - when /_ARRAY/ - if pre == '&' - lines << " #{unity_func}(#{pre}#{expected}, #{pre}#{arg_name}, #{depth_name}, cmock_line, CMockStringMismatch);\n" - else - lines << " if (#{pre}#{expected} == NULL)\n" - lines << " { UNITY_TEST_ASSERT_NULL(#{pre}#{arg_name}, cmock_line, CMockStringExpNULL); }\n" - lines << (depth_name != 1 ? " else if (#{depth_name} == 0)\n { UNITY_TEST_ASSERT_EQUAL_PTR(#{pre}#{expected}, #{pre}#{arg_name}, cmock_line, CMockStringMismatch); }\n" : '') - lines << " else\n" - lines << " { #{unity_func}(#{pre}#{expected}, #{pre}#{arg_name}, #{depth_name}, cmock_line, CMockStringMismatch); }\n" - end - else - lines << " #{unity_func}(#{pre}#{expected}, #{pre}#{arg_name}, cmock_line, CMockStringMismatch);\n" - end - lines << " }\n" - lines - end -end diff --git a/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_header_parser.rb b/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_header_parser.rb deleted file mode 100644 index b008dc149..000000000 --- a/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_header_parser.rb +++ /dev/null @@ -1,623 +0,0 @@ -# ========================================== -# CMock Project - Automatic Mock Generation for C -# Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams -# [Released under MIT License. Please refer to license.txt for details] -# ========================================== - -class CMockHeaderParser - attr_accessor :funcs, :c_attr_noconst, :c_attributes, :treat_as_void, :treat_externs, :treat_inlines, :inline_function_patterns - - def initialize(cfg) - @c_strippables = cfg.strippables - @c_attr_noconst = cfg.attributes.uniq - ['const'] - @c_attributes = ['const'] + c_attr_noconst - @c_calling_conventions = cfg.c_calling_conventions.uniq - @treat_as_array = cfg.treat_as_array - @treat_as_void = (['void'] + cfg.treat_as_void).uniq - @function_declaration_parse_base_match = '([\w\s\*\(\),\[\]]+??)\(([\w\s\*\(\),\.\[\]+\-\/]*)\)' - @declaration_parse_matcher = /#{@function_declaration_parse_base_match}$/m - @standards = (%w[int short char long unsigned signed] + cfg.treat_as.keys).uniq - @array_size_name = cfg.array_size_name - @array_size_type = (%w[int size_t] + cfg.array_size_type).uniq - @when_no_prototypes = cfg.when_no_prototypes - @local_as_void = @treat_as_void - @verbosity = cfg.verbosity - @treat_externs = cfg.treat_externs - @treat_inlines = cfg.treat_inlines - @inline_function_patterns = cfg.inline_function_patterns - @c_strippables += ['extern'] if @treat_externs == :include # we'll need to remove the attribute if we're allowing externs - @c_strippables += ['inline'] if @treat_inlines == :include # we'll need to remove the attribute if we're allowing inlines - end - - def parse(name, source) - parse_project = { - :module_name => name.gsub(/\W/, ''), - :typedefs => [], - :functions => [], - :normalized_source => nil - } - - function_names = [] - - all_funcs = parse_functions(import_source(source, parse_project)).map { |item| [item] } - all_funcs += parse_cpp_functions(import_source(source, parse_project, true)) - all_funcs.map do |decl| - func = parse_declaration(parse_project, *decl) - unless function_names.include? func[:name] - parse_project[:functions] << func - function_names << func[:name] - end - end - - parse_project[:normalized_source] = if @treat_inlines == :include - transform_inline_functions(source) - else - '' - end - - { :includes => nil, - :functions => parse_project[:functions], - :typedefs => parse_project[:typedefs], - :normalized_source => parse_project[:normalized_source] } - end - - private if $ThisIsOnlyATest.nil? ################ - - # Remove C/C++ comments from a string - # +source+:: String which will have the comments removed - def remove_comments_from_source(source) - # remove comments (block and line, in three steps to ensure correct precedence) - source.gsub!(/(?<!\*)\/\/(?:.+\/\*|\*(?:$|[^\/])).*$/, '') # remove line comments that comment out the start of blocks - source.gsub!(/\/\*.*?\*\//m, '') # remove block comments - source.gsub!(/\/\/.*$/, '') # remove line comments (all that remain) - end - - def remove_nested_pairs_of_braces(source) - # remove nested pairs of braces because no function declarations will be inside of them (leave outer pair for function definition detection) - if RUBY_VERSION.split('.')[0].to_i > 1 - # we assign a string first because (no joke) if Ruby 1.9.3 sees this line as a regex, it will crash. - r = '\\{([^\\{\\}]*|\\g<0>)*\\}' - source.gsub!(/#{r}/m, '{ }') - else - while source.gsub!(/\{[^\{\}]*\{[^\{\}]*\}[^\{\}]*\}/m, '{ }') - end - end - - source - end - - # Return the number of pairs of braces/square brackets in the function provided by the user - # +source+:: String containing the function to be processed - def count_number_of_pairs_of_braces_in_function(source) - is_function_start_found = false - curr_level = 0 - total_pairs = 0 - - source.each_char do |c| - if c == '{' - curr_level += 1 - total_pairs += 1 - is_function_start_found = true - elsif c == '}' - curr_level -= 1 - end - - break if is_function_start_found && curr_level == 0 # We reached the end of the inline function body - end - - if curr_level != 0 - total_pairs = 0 # Something is fishy about this source, not enough closing braces? - end - - total_pairs - end - - # Transform inline functions to regular functions in the source by the user - # +source+:: String containing the source to be processed - def transform_inline_functions(source) - inline_function_regex_formats = [] - square_bracket_pair_regex_format = /\{[^\{\}]*\}/ # Regex to match one whole block enclosed by two square brackets - - # Convert user provided string patterns to regex - # Use word boundaries before and after the user regex to limit matching to actual word iso part of a word - @inline_function_patterns.each do |user_format_string| - user_regex = Regexp.new(user_format_string) - word_boundary_before_user_regex = /\b/ - cleanup_spaces_after_user_regex = /[ ]*\b/ - inline_function_regex_formats << Regexp.new(word_boundary_before_user_regex.source + user_regex.source + cleanup_spaces_after_user_regex.source) - end - - # let's clean up the encoding in case they've done anything weird with the characters we might find - source = source.force_encoding('ISO-8859-1').encode('utf-8', :replace => nil) - - # Comments can contain words that will trigger the parser (static|inline|<user_defined_static_keyword>) - remove_comments_from_source(source) - - # smush multiline macros into single line (checking for continuation character at end of line '\') - # If the user uses a macro to declare an inline function, - # smushing the macros makes it easier to recognize them as a macro and if required, - # remove them later on in this function - source.gsub!(/\s*\\\s*/m, ' ') - - # Just looking for static|inline in the gsub is a bit too aggressive (functions that are named like this, ...), so we try to be a bit smarter - # Instead, look for an inline pattern (f.e. "static inline") and parse it. - # Below is a small explanation on how the general mechanism works: - # - Everything before the match should just be copied, we don't want - # to touch anything but the inline functions. - # - Remove the implementation of the inline function (this is enclosed - # in square brackets) and replace it with ";" to complete the - # transformation to normal/non-inline function. - # To ensure proper removal of the function body, we count the number of square-bracket pairs - # and remove the pairs one-by-one. - # - Copy everything after the inline function implementation and start the parsing of the next inline function - # There are ofcourse some special cases (inline macro declarations, inline function declarations, ...) which are handled and explained below - inline_function_regex_formats.each do |format| - inspected_source = '' - regex_matched = false - loop do - inline_function_match = source.match(/#{format}/) # Search for inline function declaration - - if inline_function_match.nil? # No inline functions so nothing to do - # Join pre and post match stripped parts for the next inline function detection regex - source = inspected_source + source if regex_matched == true - break - end - - regex_matched = true - # 1. Determine if we are dealing with a user defined macro to declare inline functions - # If the end of the pre-match string is a macro-declaration-like string, - # we are dealing with a user defined macro to declare inline functions - if /(#define\s*)\z/ =~ inline_function_match.pre_match - # Remove the macro from the source - stripped_pre_match = inline_function_match.pre_match.sub(/(#define\s*)\z/, '') - stripped_post_match = inline_function_match.post_match.sub(/\A(.*[\n]?)/, '') - inspected_source += stripped_pre_match - source = stripped_post_match - next - end - - # 2. Determine if we are dealing with an inline function declaration iso function definition - # If the start of the post-match string is a function-declaration-like string (something ending with semicolon after the function arguments), - # we are dealing with a inline function declaration - if /\A#{@function_declaration_parse_base_match}\s*;/m =~ inline_function_match.post_match - # Only remove the inline part from the function declaration, leaving the function declaration won't do any harm - inspected_source += inline_function_match.pre_match - source = inline_function_match.post_match - next - end - - # 3. If we get here, we found an inline function declaration AND inline function body. - # Remove the function body to transform it into a 'normal' function declaration. - if /\A#{@function_declaration_parse_base_match}\s*\{/m =~ inline_function_match.post_match - total_pairs_to_remove = count_number_of_pairs_of_braces_in_function(inline_function_match.post_match) - - break if total_pairs_to_remove == 0 # Bad source? - - inline_function_stripped = inline_function_match.post_match - - total_pairs_to_remove.times do - inline_function_stripped.sub!(/\s*#{square_bracket_pair_regex_format}/, ';') # Remove inline implementation (+ some whitespace because it's prettier) - end - inspected_source += inline_function_match.pre_match - source = inline_function_stripped - next - end - - # 4. If we get here, it means the regex match, but it is not related to the function (ex. static variable in header) - # Leave this code as it is. - inspected_source += inline_function_match.pre_match + inline_function_match[0] - source = inline_function_match.post_match - end - end - - source - end - - def import_source(source, parse_project, cpp = false) - # let's clean up the encoding in case they've done anything weird with the characters we might find - source = source.force_encoding('ISO-8859-1').encode('utf-8', :replace => nil) - - # void must be void for cmock _ExpectAndReturn calls to process properly, not some weird typedef which equates to void - # to a certain extent, this action assumes we're chewing on pre-processed header files, otherwise we'll most likely just get stuff from @treat_as_void - @local_as_void = @treat_as_void - void_types = source.scan(/typedef\s+(?:\(\s*)?void(?:\s*\))?\s+([\w]+)\s*;/) - if void_types - @local_as_void += void_types.flatten.uniq.compact - end - - # If user wants to mock inline functions, - # remove the (user specific) inline keywords before removing anything else to avoid missing an inline function - if @treat_inlines == :include - @inline_function_patterns.each do |user_format_string| - source.gsub!(/#{user_format_string}/, '') # remove user defined inline function patterns - end - end - - # smush multiline macros into single line (checking for continuation character at end of line '\') - source.gsub!(/\s*\\\s*/m, ' ') - - remove_comments_from_source(source) - - # remove assembler pragma sections - source.gsub!(/^\s*#\s*pragma\s+asm\s+.*?#\s*pragma\s+endasm/m, '') - - # remove gcc's __attribute__ tags - source.gsub!(/__attribute(?:__)?\s*\(\(+.*\)\)+/, '') - - # remove preprocessor statements and extern "C" - source.gsub!(/^\s*#.*/, '') - source.gsub!(/extern\s+\"C\"\s*\{/, '') - - # enums, unions, structs, and typedefs can all contain things (e.g. function pointers) that parse like function prototypes, so yank them - # forward declared structs are removed before struct definitions so they don't mess up real thing later. we leave structs keywords in function prototypes - source.gsub!(/^[\w\s]*struct[^;\{\}\(\)]+;/m, '') # remove forward declared structs - source.gsub!(/^[\w\s]*(enum|union|struct|typedef)[\w\s]*\{[^\}]+\}[\w\s\*\,]*;/m, '') # remove struct, union, and enum definitions and typedefs with braces - # remove problem keywords - source.gsub!(/(\W)(?:register|auto|restrict)(\W)/, '\1\2') - source.gsub!(/(\W)(?:static)(\W)/, '\1\2') unless cpp - - source.gsub!(/\s*=\s*['"a-zA-Z0-9_\.]+\s*/, '') # remove default value statements from argument lists - source.gsub!(/^(?:[\w\s]*\W)?typedef\W[^;]*/m, '') # remove typedef statements - source.gsub!(/\)(\w)/, ') \1') # add space between parentheses and alphanumeric - source.gsub!(/(^|\W+)(?:#{@c_strippables.join('|')})(?=$|\W+)/, '\1') unless @c_strippables.empty? # remove known attributes slated to be stripped - - # scan standalone function pointers and remove them, because they can just be ignored - source.gsub!(/\w+\s*\(\s*\*\s*\w+\s*\)\s*\([^)]*\)\s*;/, ';') - - # scan for functions which return function pointers, because they are a pain - source.gsub!(/([\w\s\*]+)\(*\(\s*\*([\w\s\*]+)\s*\(([\w\s\*,]*)\)\)\s*\(([\w\s\*,]*)\)\)*/) do |_m| - functype = "cmock_#{parse_project[:module_name]}_func_ptr#{parse_project[:typedefs].size + 1}" - unless cpp # only collect once - parse_project[:typedefs] << "typedef #{Regexp.last_match(1).strip}(*#{functype})(#{Regexp.last_match(4)});" - "#{functype} #{Regexp.last_match(2).strip}(#{Regexp.last_match(3)});" - end - end - - source = remove_nested_pairs_of_braces(source) unless cpp - - if @treat_inlines == :include - # Functions having "{ }" at this point are/were inline functions, - # User wants them in so 'disguise' them as normal functions with the ";" - source.gsub!('{ }', ';') - end - - # remove function definitions by stripping off the arguments right now - source.gsub!(/\([^\)]*\)\s*\{[^\}]*\}/m, ';') - - # drop extra white space to make the rest go faster - source.gsub!(/^\s+/, '') # remove extra white space from beginning of line - source.gsub!(/\s+$/, '') # remove extra white space from end of line - source.gsub!(/\s*\(\s*/, '(') # remove extra white space from before left parens - source.gsub!(/\s*\)\s*/, ')') # remove extra white space from before right parens - source.gsub!(/\s+/, ' ') # remove remaining extra white space - - # split lines on semicolons and remove things that are obviously not what we are looking for - src_lines = source.split(/\s*;\s*/) - src_lines = src_lines.uniq unless cpp # must retain closing braces for class/namespace - src_lines.delete_if { |line| line.strip.empty? } # remove blank lines - src_lines.delete_if { |line| !(line =~ /[\w\s\*]+\(+\s*\*[\*\s]*[\w\s]+(?:\[[\w\s]*\]\s*)+\)+\s*\((?:[\w\s\*]*,?)*\s*\)/).nil? } # remove function pointer arrays - - unless @treat_externs == :include - src_lines.delete_if { |line| !(line =~ /(?:^|\s+)(?:extern)\s+/).nil? } # remove extern functions - end - - unless @treat_inlines == :include - src_lines.delete_if { |line| !(line =~ /(?:^|\s+)(?:inline)\s+/).nil? } # remove inline functions - end - - src_lines.delete_if(&:empty?) # drop empty lines - end - - # Rudimentary C++ parser - does not handle all situations - e.g.: - # * A namespace function appears after a class with private members (should be parsed) - # * Anonymous namespace (shouldn't parse anything - no matter how nested - within it) - # * A class nested within another class - def parse_cpp_functions(source) - funcs = [] - - ns = [] - pub = false - source.each do |line| - # Search for namespace, class, opening and closing braces - line.scan(/(?:(?:\b(?:namespace|class)\s+(?:\S+)\s*)?{)|}/).each do |item| - if item == '}' - ns.pop - else - token = item.strip.sub(/\s+/, ' ') - ns << token - - pub = false if token.start_with? 'class' - pub = true if token.start_with? 'namespace' - end - end - - pub = true if line =~ /public:/ - pub = false if line =~ /private:/ || line =~ /protected:/ - - # ignore non-public and non-static - next unless pub - next unless line =~ /\bstatic\b/ - - line.sub!(/^.*static/, '') - next unless line =~ @declaration_parse_matcher - - tmp = ns.reject { |item| item == '{' } - - # Identify class name, if any - cls = nil - if tmp[-1].start_with? 'class ' - cls = tmp.pop.sub(/class (\S+) {/, '\1') - end - - # Assemble list of namespaces - tmp.each { |item| item.sub!(/(?:namespace|class) (\S+) {/, '\1') } - - funcs << [line.strip.gsub(/\s+/, ' '), tmp, cls] - end - funcs - end - - def parse_functions(source) - funcs = [] - source.each { |line| funcs << line.strip.gsub(/\s+/, ' ') if line =~ @declaration_parse_matcher } - if funcs.empty? - case @when_no_prototypes - when :error - raise 'ERROR: No function prototypes found!' - when :warn - puts 'WARNING: No function prototypes found!' unless @verbosity < 1 - end - end - funcs - end - - def parse_type_and_name(arg) - # Split up words and remove known attributes. For pointer types, make sure - # to remove 'const' only when it applies to the pointer itself, not when it - # applies to the type pointed to. For non-pointer types, remove any - # occurrence of 'const'. - arg.gsub!(/(\w)\*/, '\1 *') # pull asterisks away from preceding word - arg.gsub!(/\*(\w)/, '* \1') # pull asterisks away from following word - arg_array = arg.split - arg_info = divine_ptr_and_const(arg) - arg_info[:name] = arg_array[-1] - - attributes = arg.include?('*') ? @c_attr_noconst : @c_attributes - attr_array = [] - type_array = [] - - arg_array[0..-2].each do |word| - if attributes.include?(word) - attr_array << word - elsif @c_calling_conventions.include?(word) - arg_info[:c_calling_convention] = word - else - type_array << word - end - end - - if arg_info[:const_ptr?] - attr_array << 'const' - type_array.delete_at(type_array.rindex('const')) - end - - arg_info[:modifier] = attr_array.join(' ') - arg_info[:type] = type_array.join(' ').gsub(/\s+\*/, '*') # remove space before asterisks - arg_info - end - - def parse_args(arg_list) - args = [] - arg_list.split(',').each do |arg| - arg.strip! - return args if arg =~ /^\s*((\.\.\.)|(void))\s*$/ # we're done if we reach void by itself or ... - - arg_info = parse_type_and_name(arg) - arg_info.delete(:modifier) # don't care about this - arg_info.delete(:c_calling_convention) # don't care about this - - # in C, array arguments implicitly degrade to pointers - # make the translation explicit here to simplify later logic - if @treat_as_array[arg_info[:type]] && !(arg_info[:ptr?]) - arg_info[:type] = "#{@treat_as_array[arg_info[:type]]}*" - arg_info[:type] = "const #{arg_info[:type]}" if arg_info[:const?] - arg_info[:ptr?] = true - end - - args << arg_info - end - - # Try to find array pair in parameters following this pattern : <type> * <name>, <@array_size_type> <@array_size_name> - args.each_with_index do |val, index| - next_index = index + 1 - next unless args.length > next_index - - if (val[:ptr?] == true) && args[next_index][:name].match(@array_size_name) && @array_size_type.include?(args[next_index][:type]) - val[:array_data?] = true - args[next_index][:array_size?] = true - end - end - - args - end - - def divine_ptr(arg) - return false unless arg.include? '*' - # treat "const char *" and similar as a string, not a pointer - return false if /(^|\s)(const\s+)?char(\s+const)?\s*\*(?!.*\*)/ =~ arg - - true - end - - def divine_const(arg) - # a non-pointer arg containing "const" is a constant - # an arg containing "const" before the last * is a pointer to a constant - if arg.include?('*') ? (/(^|\s|\*)const(\s(\w|\s)*)?\*(?!.*\*)/ =~ arg) : (/(^|\s)const(\s|$)/ =~ arg) - true - else - false - end - end - - def divine_ptr_and_const(arg) - divination = {} - - divination[:ptr?] = divine_ptr(arg) - divination[:const?] = divine_const(arg) - - # an arg containing "const" after the last * is a constant pointer - divination[:const_ptr?] = /\*(?!.*\*)\s*const(\s|$)/ =~ arg ? true : false - - divination - end - - def clean_args(arg_list, parse_project) - if @local_as_void.include?(arg_list.strip) || arg_list.empty? - 'void' - else - c = 0 - # magically turn brackets into asterisks, also match for parentheses that come from macros - arg_list.gsub!(/(\w+)(?:\s*\[[^\[\]]*\])+/, '*\1') - # remove space to place asterisks with type (where they belong) - arg_list.gsub!(/\s+\*/, '*') - # pull asterisks away from arg to place asterisks with type (where they belong) - arg_list.gsub!(/\*(\w)/, '* \1') - - # scan argument list for function pointers and replace them with custom types - arg_list.gsub!(/([\w\s\*]+)\(+\s*\*[\*\s]*([\w\s]*)\s*\)+\s*\(((?:[\w\s\*]*,?)*)\s*\)*/) do |_m| - functype = "cmock_#{parse_project[:module_name]}_func_ptr#{parse_project[:typedefs].size + 1}" - funcret = Regexp.last_match(1).strip - funcname = Regexp.last_match(2).strip - funcargs = Regexp.last_match(3).strip - funconst = '' - if funcname.include? 'const' - funcname.gsub!('const', '').strip! - funconst = 'const ' - end - parse_project[:typedefs] << "typedef #{funcret}(*#{functype})(#{funcargs});" - funcname = "cmock_arg#{c += 1}" if funcname.empty? - "#{functype} #{funconst}#{funcname}" - end - - # scan argument list for function pointers with shorthand notation and replace them with custom types - arg_list.gsub!(/([\w\s\*]+)+\s+(\w+)\s*\(((?:[\w\s\*]*,?)*)\s*\)*/) do |_m| - functype = "cmock_#{parse_project[:module_name]}_func_ptr#{parse_project[:typedefs].size + 1}" - funcret = Regexp.last_match(1).strip - funcname = Regexp.last_match(2).strip - funcargs = Regexp.last_match(3).strip - funconst = '' - if funcname.include? 'const' - funcname.gsub!('const', '').strip! - funconst = 'const ' - end - parse_project[:typedefs] << "typedef #{funcret}(*#{functype})(#{funcargs});" - funcname = "cmock_arg#{c += 1}" if funcname.empty? - "#{functype} #{funconst}#{funcname}" - end - - # automatically name unnamed arguments (those that only had a type) - arg_list.split(/\s*,\s*/).map do |arg| - parts = (arg.split - ['struct', 'union', 'enum', 'const', 'const*']) - if (parts.size < 2) || (parts[-1][-1].chr == '*') || @standards.include?(parts[-1]) - "#{arg} cmock_arg#{c += 1}" - else - arg - end - end.join(', ') - end - end - - def parse_declaration(parse_project, declaration, namespace = [], classname = nil) - decl = {} - decl[:namespace] = namespace - decl[:class] = classname - - regex_match = @declaration_parse_matcher.match(declaration) - raise "Failed parsing function declaration: '#{declaration}'" if regex_match.nil? - - # grab argument list - args = regex_match[2].strip - - # process function attributes, return type, and name - parsed = parse_type_and_name(regex_match[1]) - - # Record original name without scope prefix - decl[:unscoped_name] = parsed[:name] - - # Prefix name with namespace scope (if any) and then class - decl[:name] = namespace.join('_') - unless classname.nil? - decl[:name] << '_' unless decl[:name].empty? - decl[:name] << classname - end - # Add original name to complete fully scoped name - decl[:name] << '_' unless decl[:name].empty? - decl[:name] << decl[:unscoped_name] - - decl[:modifier] = parsed[:modifier] - unless parsed[:c_calling_convention].nil? - decl[:c_calling_convention] = parsed[:c_calling_convention] - end - - rettype = parsed[:type] - rettype = 'void' if @local_as_void.include?(rettype.strip) - decl[:return] = { :type => rettype, - :name => 'cmock_to_return', - :str => "#{rettype} cmock_to_return", - :void? => (rettype == 'void'), - :ptr? => parsed[:ptr?] || false, - :const? => parsed[:const?] || false, - :const_ptr? => parsed[:const_ptr?] || false } - - # remove default argument statements from mock definitions - args.gsub!(/=\s*[a-zA-Z0-9_\.]+\s*/, ' ') - - # check for var args - if args =~ /\.\.\./ - decl[:var_arg] = args.match(/[\w\s]*\.\.\./).to_s.strip - args = if args =~ /\,[\w\s]*\.\.\./ - args.gsub!(/\,[\w\s]*\.\.\./, '') - else - 'void' - end - else - decl[:var_arg] = nil - end - args = clean_args(args, parse_project) - decl[:args_string] = args - decl[:args] = parse_args(args) - decl[:args_call] = decl[:args].map { |a| a[:name] }.join(', ') - decl[:contains_ptr?] = decl[:args].inject(false) { |ptr, arg| arg[:ptr?] ? true : ptr } - - if decl[:return][:type].nil? || decl[:name].nil? || decl[:args].nil? || - decl[:return][:type].empty? || decl[:name].empty? - raise "Failed Parsing Declaration Prototype!\n" \ - " declaration: '#{declaration}'\n" \ - " modifier: '#{decl[:modifier]}'\n" \ - " return: #{prototype_inspect_hash(decl[:return])}\n" \ - " function: '#{decl[:name]}'\n" \ - " args: #{prototype_inspect_array_of_hashes(decl[:args])}\n" - end - - decl - end - - def prototype_inspect_hash(hash) - pairs = [] - hash.each_pair { |name, value| pairs << ":#{name} => #{"'" if value.class == String}#{value}#{"'" if value.class == String}" } - "{#{pairs.join(', ')}}" - end - - def prototype_inspect_array_of_hashes(array) - hashes = [] - array.each { |hash| hashes << prototype_inspect_hash(hash) } - case array.size - when 0 - return '[]' - when 1 - return "[#{hashes[0]}]" - else - return "[\n #{hashes.join("\n ")}\n ]\n" - end - end -end diff --git a/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_plugin_manager.rb b/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_plugin_manager.rb deleted file mode 100644 index 342014e22..000000000 --- a/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_plugin_manager.rb +++ /dev/null @@ -1,50 +0,0 @@ -# ========================================== -# CMock Project - Automatic Mock Generation for C -# Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams -# [Released under MIT License. Please refer to license.txt for details] -# ========================================== - -class CMockPluginManager - attr_accessor :plugins - - def initialize(config, utils) - @plugins = [] - plugins_to_load = [:expect, config.plugins].flatten.uniq.compact - plugins_to_load.each do |plugin| - plugin_name = plugin.to_s - object_name = 'CMockGeneratorPlugin' + camelize(plugin_name) - self.class.mutex.synchronize { load_plugin(plugin_name, object_name, config, utils) } - end - @plugins.sort! { |a, b| a.priority <=> b.priority } - end - - def run(method, args = nil) - if args.nil? - @plugins.collect { |plugin| plugin.send(method) if plugin.respond_to?(method) }.flatten.join - else - @plugins.collect { |plugin| plugin.send(method, args) if plugin.respond_to?(method) }.flatten.join - end - end - - def camelize(lower_case_and_underscored_word) - lower_case_and_underscored_word.gsub(/\/(.?)/) { '::' + Regexp.last_match(1).upcase }.gsub(/(^|_)(.)/) { Regexp.last_match(2).upcase } - end - - def self.mutex - @mutex ||= Mutex.new - end - - private - - def load_plugin(plugin_name, object_name, config, utils) - unless Object.const_defined? object_name - file_name = "#{__dir__}/cmock_generator_plugin_#{plugin_name.downcase}.rb" - require file_name - end - class_name = Object.const_get(object_name) - @plugins << class_name.new(config, utils) - rescue StandardError - file_name = "#{__dir__}/cmock_generator_plugin_#{plugin_name.downcase}.rb" - raise "ERROR: CMock unable to load plugin '#{plugin_name}' '#{object_name}' #{file_name}" - end -end diff --git a/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_unityhelper_parser.rb b/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_unityhelper_parser.rb deleted file mode 100644 index 9f4beb770..000000000 --- a/test/unit-test/vendor/ceedling/vendor/cmock/lib/cmock_unityhelper_parser.rb +++ /dev/null @@ -1,77 +0,0 @@ -# ========================================== -# CMock Project - Automatic Mock Generation for C -# Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams -# [Released under MIT License. Please refer to license.txt for details] -# ========================================== - -class CMockUnityHelperParser - attr_accessor :c_types - - def initialize(config) - @config = config - @fallback = @config.plugins.include?(:array) ? 'UNITY_TEST_ASSERT_EQUAL_MEMORY_ARRAY' : 'UNITY_TEST_ASSERT_EQUAL_MEMORY' - @c_types = map_c_types.merge(import_source) - end - - def get_helper(ctype) - lookup = ctype.gsub(/(?:^|(\S?)(\s*)|(\W))const(?:$|(\s*)(\S)|(\W))/, '\1\3\5\6').strip.gsub(/\s+/, '_') - return [@c_types[lookup], ''] if @c_types[lookup] - - if lookup =~ /\*$/ - lookup = lookup.gsub(/\*$/, '') - return [@c_types[lookup], '*'] if @c_types[lookup] - else - lookup += '*' - return [@c_types[lookup], '&'] if @c_types[lookup] - end - return ['UNITY_TEST_ASSERT_EQUAL_PTR', ''] if ctype =~ /cmock_\w+_ptr\d+/ - raise("Don't know how to test #{ctype} and memory tests are disabled!") unless @config.memcmp_if_unknown - - lookup =~ /\*$/ ? [@fallback, '&'] : [@fallback, ''] - end - - private ########################### - - def map_c_types - c_types = {} - @config.treat_as.each_pair do |ctype, expecttype| - c_type = ctype.gsub(/\s+/, '_') - if expecttype =~ /\*/ - c_types[c_type] = "UNITY_TEST_ASSERT_EQUAL_#{expecttype.delete('*')}_ARRAY" - else - c_types[c_type] = "UNITY_TEST_ASSERT_EQUAL_#{expecttype}" - c_types[c_type + '*'] ||= "UNITY_TEST_ASSERT_EQUAL_#{expecttype}_ARRAY" - end - end - c_types - end - - def import_source - source = @config.load_unity_helper - return {} if source.nil? - - c_types = {} - source = source.gsub(/\/\/.*$/, '') # remove line comments - source = source.gsub(/\/\*.*?\*\//m, '') # remove block comments - - # scan for comparison helpers - match_regex = Regexp.new('^\s*#define\s+(UNITY_TEST_ASSERT_EQUAL_(\w+))\s*\(' + Array.new(4, '\s*\w+\s*').join(',') + '\)') - pairs = source.scan(match_regex).flatten.compact - (pairs.size / 2).times do |i| - expect = pairs[i * 2] - ctype = pairs[(i * 2) + 1] - c_types[ctype] = expect unless expect.include?('_ARRAY') - end - - # scan for array variants of those helpers - match_regex = Regexp.new('^\s*#define\s+(UNITY_TEST_ASSERT_EQUAL_(\w+_ARRAY))\s*\(' + Array.new(5, '\s*\w+\s*').join(',') + '\)') - pairs = source.scan(match_regex).flatten.compact - (pairs.size / 2).times do |i| - expect = pairs[i * 2] - ctype = pairs[(i * 2) + 1] - c_types[ctype.gsub('_ARRAY', '*')] = expect - end - - c_types - end -end diff --git a/test/unit-test/vendor/ceedling/vendor/cmock/src/cmock.c b/test/unit-test/vendor/ceedling/vendor/cmock/src/cmock.c deleted file mode 100644 index d8bdb1369..000000000 --- a/test/unit-test/vendor/ceedling/vendor/cmock/src/cmock.c +++ /dev/null @@ -1,215 +0,0 @@ -/* ========================================== - CMock Project - Automatic Mock Generation for C - Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams - [Released under MIT License. Please refer to license.txt for details] -========================================== */ - -#include "cmock.h" - -/* public constants to be used by mocks */ -const char* CMockStringOutOfMemory = "CMock has run out of memory. Please allocate more."; -const char* CMockStringCalledMore = "Called more times than expected."; -const char* CMockStringCalledLess = "Called fewer times than expected."; -const char* CMockStringCalledEarly = "Called earlier than expected."; -const char* CMockStringCalledLate = "Called later than expected."; -const char* CMockStringCallOrder = "Called out of order."; -const char* CMockStringIgnPreExp = "IgnoreArg called before Expect."; -const char* CMockStringPtrPreExp = "ReturnThruPtr called before Expect."; -const char* CMockStringPtrIsNULL = "Pointer is NULL."; -const char* CMockStringExpNULL = "Expected NULL."; -const char* CMockStringMismatch = "Function called with unexpected argument value."; - -/* private variables */ -#ifdef CMOCK_MEM_DYNAMIC -static unsigned char* CMock_Guts_Buffer = NULL; -static CMOCK_MEM_INDEX_TYPE CMock_Guts_BufferSize = CMOCK_MEM_ALIGN_SIZE; -static CMOCK_MEM_INDEX_TYPE CMock_Guts_FreePtr = CMOCK_MEM_ALIGN_SIZE; -#else -static unsigned char CMock_Guts_Buffer[CMOCK_MEM_SIZE + CMOCK_MEM_ALIGN_SIZE]; -static CMOCK_MEM_INDEX_TYPE CMock_Guts_BufferSize = CMOCK_MEM_SIZE + CMOCK_MEM_ALIGN_SIZE; -static CMOCK_MEM_INDEX_TYPE CMock_Guts_FreePtr = CMOCK_MEM_ALIGN_SIZE; -#endif - -/*------------------------------------------------------- - * CMock_Guts_MemNew - *-------------------------------------------------------*/ -CMOCK_MEM_INDEX_TYPE CMock_Guts_MemNew(CMOCK_MEM_INDEX_TYPE size) -{ - CMOCK_MEM_INDEX_TYPE index; - - /* verify arguments valid (we must be allocating space for at least 1 byte, and the existing chain must be in memory somewhere) */ - if (size < 1) - return CMOCK_GUTS_NONE; - - /* verify we have enough room */ - size = size + CMOCK_MEM_INDEX_SIZE; - if (size & CMOCK_MEM_ALIGN_MASK) - size = (size + CMOCK_MEM_ALIGN_MASK) & ~CMOCK_MEM_ALIGN_MASK; - if ((CMock_Guts_BufferSize - CMock_Guts_FreePtr) < size) - { -#ifndef CMOCK_MEM_DYNAMIC - return CMOCK_GUTS_NONE; /* nothing we can do; our static buffer is out of memory */ -#else - /* our dynamic buffer does not have enough room; request more via realloc() */ - CMOCK_MEM_INDEX_TYPE new_buffersize = CMock_Guts_BufferSize + CMOCK_MEM_SIZE + size; - unsigned char* new_buffer = realloc(CMock_Guts_Buffer, (size_t)new_buffersize); - if (new_buffer == NULL) - return CMOCK_GUTS_NONE; /* realloc() failed; out of memory */ - CMock_Guts_Buffer = new_buffer; - CMock_Guts_BufferSize = new_buffersize; -#endif - } - - /* determine where we're putting this new block, and init its pointer to be the end of the line */ - index = CMock_Guts_FreePtr + CMOCK_MEM_INDEX_SIZE; - *(CMOCK_MEM_INDEX_TYPE*)(&CMock_Guts_Buffer[CMock_Guts_FreePtr]) = CMOCK_GUTS_NONE; - CMock_Guts_FreePtr += size; - - return index; -} - -/*------------------------------------------------------- - * CMock_Guts_MemChain - *-------------------------------------------------------*/ -CMOCK_MEM_INDEX_TYPE CMock_Guts_MemChain(CMOCK_MEM_INDEX_TYPE root_index, CMOCK_MEM_INDEX_TYPE obj_index) -{ - CMOCK_MEM_INDEX_TYPE index; - void* root; - void* obj; - void* next; - - if (root_index == CMOCK_GUTS_NONE) - { - /* if there is no root currently, we return this object as the root of the chain */ - return obj_index; - } - else - { - /* reject illegal nodes */ - if ((root_index < CMOCK_MEM_ALIGN_SIZE) || (root_index >= CMock_Guts_FreePtr)) - { - return CMOCK_GUTS_NONE; - } - if ((obj_index < CMOCK_MEM_ALIGN_SIZE) || (obj_index >= CMock_Guts_FreePtr)) - { - return CMOCK_GUTS_NONE; - } - - root = (void*)(&CMock_Guts_Buffer[root_index]); - obj = (void*)(&CMock_Guts_Buffer[obj_index]); - - /* find the end of the existing chain and add us */ - next = root; - do { - index = *(CMOCK_MEM_INDEX_TYPE*)((CMOCK_MEM_PTR_AS_INT)next - CMOCK_MEM_INDEX_SIZE); - if (index >= CMock_Guts_FreePtr) - return CMOCK_GUTS_NONE; - if (index > 0) - next = (void*)(&CMock_Guts_Buffer[index]); - } while (index > 0); - *(CMOCK_MEM_INDEX_TYPE*)((CMOCK_MEM_PTR_AS_INT)next - CMOCK_MEM_INDEX_SIZE) = (CMOCK_MEM_INDEX_TYPE)((CMOCK_MEM_PTR_AS_INT)obj - (CMOCK_MEM_PTR_AS_INT)CMock_Guts_Buffer); - return root_index; - } -} - -/*------------------------------------------------------- - * CMock_Guts_MemNext - *-------------------------------------------------------*/ -CMOCK_MEM_INDEX_TYPE CMock_Guts_MemNext(CMOCK_MEM_INDEX_TYPE previous_item_index) -{ - CMOCK_MEM_INDEX_TYPE index; - void* previous_item; - - /* There is nothing "next" if the pointer isn't from our buffer */ - if ((previous_item_index < CMOCK_MEM_ALIGN_SIZE) || (previous_item_index >= CMock_Guts_FreePtr)) - return CMOCK_GUTS_NONE; - previous_item = (void*)(&CMock_Guts_Buffer[previous_item_index]); - - /* if the pointer is good, then use it to look up the next index - * (we know the first element always goes in zero, so NEXT must always be > 1) */ - index = *(CMOCK_MEM_INDEX_TYPE*)((CMOCK_MEM_PTR_AS_INT)previous_item - CMOCK_MEM_INDEX_SIZE); - if ((index > 1) && (index < CMock_Guts_FreePtr)) - return index; - else - return CMOCK_GUTS_NONE; -} - -/*------------------------------------------------------- - * CMock_Guts_MemEndOfChain - *-------------------------------------------------------*/ -CMOCK_MEM_INDEX_TYPE CMock_Guts_MemEndOfChain(CMOCK_MEM_INDEX_TYPE root_index) -{ - CMOCK_MEM_INDEX_TYPE index = root_index; - CMOCK_MEM_INDEX_TYPE next_index; - - for (next_index = root_index; - next_index != CMOCK_GUTS_NONE; - next_index = CMock_Guts_MemNext(index)) - { - index = next_index; - } - - return index; -} - -/*------------------------------------------------------- - * CMock_GetAddressFor - *-------------------------------------------------------*/ -void* CMock_Guts_GetAddressFor(CMOCK_MEM_INDEX_TYPE index) -{ - if ((index >= CMOCK_MEM_ALIGN_SIZE) && (index < CMock_Guts_FreePtr)) - { - return (void*)(&CMock_Guts_Buffer[index]); - } - else - { - return NULL; - } -} - -/*------------------------------------------------------- - * CMock_Guts_MemBytesCapacity - *-------------------------------------------------------*/ -CMOCK_MEM_INDEX_TYPE CMock_Guts_MemBytesCapacity(void) -{ - return (sizeof(CMock_Guts_Buffer) - CMOCK_MEM_ALIGN_SIZE); -} - -/*------------------------------------------------------- - * CMock_Guts_MemBytesFree - *-------------------------------------------------------*/ -CMOCK_MEM_INDEX_TYPE CMock_Guts_MemBytesFree(void) -{ - return CMock_Guts_BufferSize - CMock_Guts_FreePtr; -} - -/*------------------------------------------------------- - * CMock_Guts_MemBytesUsed - *-------------------------------------------------------*/ -CMOCK_MEM_INDEX_TYPE CMock_Guts_MemBytesUsed(void) -{ - return CMock_Guts_FreePtr - CMOCK_MEM_ALIGN_SIZE; -} - -/*------------------------------------------------------- - * CMock_Guts_MemFreeAll - *-------------------------------------------------------*/ -void CMock_Guts_MemFreeAll(void) -{ - CMock_Guts_FreePtr = CMOCK_MEM_ALIGN_SIZE; /* skip the very beginning */ -} - -/*------------------------------------------------------- - * CMock_Guts_MemFreeFinal - *-------------------------------------------------------*/ -void CMock_Guts_MemFreeFinal(void) -{ - CMock_Guts_FreePtr = CMOCK_MEM_ALIGN_SIZE; -#ifdef CMOCK_MEM_DYNAMIC - if (CMock_Guts_Buffer) - { - free(CMock_Guts_Buffer); - CMock_Guts_Buffer = NULL; - } -#endif -} diff --git a/test/unit-test/vendor/ceedling/vendor/cmock/src/cmock.h b/test/unit-test/vendor/ceedling/vendor/cmock/src/cmock.h deleted file mode 100644 index 45bab1829..000000000 --- a/test/unit-test/vendor/ceedling/vendor/cmock/src/cmock.h +++ /dev/null @@ -1,47 +0,0 @@ -/* ========================================== - CMock Project - Automatic Mock Generation for C - Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams - [Released under MIT License. Please refer to license.txt for details] -========================================== */ - -#ifndef CMOCK_FRAMEWORK_H -#define CMOCK_FRAMEWORK_H - -#include "cmock_internals.h" - -#define CMOCK_VERSION_MAJOR 2 -#define CMOCK_VERSION_MINOR 5 -#define CMOCK_VERSION_BUILD 4 -#define CMOCK_VERSION ((CMOCK_VERSION_MAJOR << 16) | (CMOCK_VERSION_MINOR << 8) | CMOCK_VERSION_BUILD) - -/* should be big enough to index full range of CMOCK_MEM_MAX */ -#ifndef CMOCK_MEM_INDEX_TYPE -#include <stddef.h> -#define CMOCK_MEM_INDEX_TYPE size_t -#endif - -#define CMOCK_GUTS_NONE (0) - -#if defined __GNUC__ -# define CMOCK_FUNCTION_ATTR(a) __attribute__((a)) -#else -# define CMOCK_FUNCTION_ATTR(a) /* ignore */ -#endif - -/*------------------------------------------------------- - * Memory API - *-------------------------------------------------------*/ -CMOCK_MEM_INDEX_TYPE CMock_Guts_MemNew(CMOCK_MEM_INDEX_TYPE size); -CMOCK_MEM_INDEX_TYPE CMock_Guts_MemChain(CMOCK_MEM_INDEX_TYPE root_index, CMOCK_MEM_INDEX_TYPE obj_index); -CMOCK_MEM_INDEX_TYPE CMock_Guts_MemNext(CMOCK_MEM_INDEX_TYPE previous_item_index) CMOCK_FUNCTION_ATTR(pure); -CMOCK_MEM_INDEX_TYPE CMock_Guts_MemEndOfChain(CMOCK_MEM_INDEX_TYPE root_index) CMOCK_FUNCTION_ATTR(pure); - -void* CMock_Guts_GetAddressFor(CMOCK_MEM_INDEX_TYPE index) CMOCK_FUNCTION_ATTR(pure); - -CMOCK_MEM_INDEX_TYPE CMock_Guts_MemBytesCapacity(void) CMOCK_FUNCTION_ATTR(const); -CMOCK_MEM_INDEX_TYPE CMock_Guts_MemBytesFree(void) CMOCK_FUNCTION_ATTR(pure); -CMOCK_MEM_INDEX_TYPE CMock_Guts_MemBytesUsed(void) CMOCK_FUNCTION_ATTR(pure); -void CMock_Guts_MemFreeAll(void); -void CMock_Guts_MemFreeFinal(void); - -#endif /* end of CMOCK_FRAMEWORK_H */ diff --git a/test/unit-test/vendor/ceedling/vendor/cmock/src/cmock_internals.h b/test/unit-test/vendor/ceedling/vendor/cmock/src/cmock_internals.h deleted file mode 100644 index 56fb33b1a..000000000 --- a/test/unit-test/vendor/ceedling/vendor/cmock/src/cmock_internals.h +++ /dev/null @@ -1,91 +0,0 @@ -/* ========================================== - CMock Project - Automatic Mock Generation for C - Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams - [Released under MIT License. Please refer to license.txt for details] -========================================== */ - -#ifndef CMOCK_FRAMEWORK_INTERNALS_H -#define CMOCK_FRAMEWORK_INTERNALS_H - -#include "unity.h" - -/* These are constants that the generated mocks have access to */ -extern const char* CMockStringOutOfMemory; -extern const char* CMockStringCalledMore; -extern const char* CMockStringCalledLess; -extern const char* CMockStringCalledEarly; -extern const char* CMockStringCalledLate; -extern const char* CMockStringCallOrder; -extern const char* CMockStringIgnPreExp; -extern const char* CMockStringPtrPreExp; -extern const char* CMockStringPtrIsNULL; -extern const char* CMockStringExpNULL; -extern const char* CMockStringMismatch; - -/* define CMOCK_MEM_DYNAMIC to grab memory as needed with malloc - * when you do that, CMOCK_MEM_SIZE is used for incremental size instead of total */ -#ifdef CMOCK_MEM_STATIC -#undef CMOCK_MEM_DYNAMIC -#endif - -#ifdef CMOCK_MEM_DYNAMIC -#include <stdlib.h> -#endif - -/* this is used internally during pointer arithmetic. make sure this type is the same size as the target's pointer type */ -#ifndef CMOCK_MEM_PTR_AS_INT -#ifdef UNITY_POINTER_WIDTH -#ifdef UNITY_INT_WIDTH -#if UNITY_POINTER_WIDTH == UNITY_INT_WIDTH -#define CMOCK_MEM_PTR_AS_INT unsigned int -#endif -#endif -#endif -#endif - -#ifndef CMOCK_MEM_PTR_AS_INT -#ifdef UNITY_POINTER_WIDTH -#ifdef UNITY_LONG_WIDTH -#if UNITY_POINTER_WIDTH == UNITY_LONG_WIDTH -#define CMOCK_MEM_PTR_AS_INT unsigned long -#endif -#if UNITY_POINTER_WIDTH > UNITY_LONG_WIDTH -#define CMOCK_MEM_PTR_AS_INT unsigned long long -#endif -#endif -#endif -#endif - -#ifndef CMOCK_MEM_PTR_AS_INT -#define CMOCK_MEM_PTR_AS_INT unsigned long -#endif - -/* 0 for no alignment, 1 for 16-bit, 2 for 32-bit, 3 for 64-bit */ -#ifndef CMOCK_MEM_ALIGN - #ifdef UNITY_LONG_WIDTH - #if (UNITY_LONG_WIDTH == 16) - #define CMOCK_MEM_ALIGN (1) - #elif (UNITY_LONG_WIDTH == 32) - #define CMOCK_MEM_ALIGN (2) - #elif (UNITY_LONG_WIDTH == 64) - #define CMOCK_MEM_ALIGN (3) - #else - #define CMOCK_MEM_ALIGN (2) - #endif - #else - #define CMOCK_MEM_ALIGN (2) - #endif -#endif - -/* amount of memory to allow cmock to use in its internal heap */ -#ifndef CMOCK_MEM_SIZE -#define CMOCK_MEM_SIZE (32768) -#endif - -/* automatically calculated defs for easier reading */ -#define CMOCK_MEM_ALIGN_SIZE (CMOCK_MEM_INDEX_TYPE)(1u << CMOCK_MEM_ALIGN) -#define CMOCK_MEM_ALIGN_MASK (CMOCK_MEM_INDEX_TYPE)(CMOCK_MEM_ALIGN_SIZE - 1) -#define CMOCK_MEM_INDEX_SIZE (CMOCK_MEM_INDEX_TYPE)(CMOCK_MEM_PTR_AS_INT)((sizeof(CMOCK_MEM_INDEX_TYPE) > CMOCK_MEM_ALIGN_SIZE) ? sizeof(CMOCK_MEM_INDEX_TYPE) : CMOCK_MEM_ALIGN_SIZE) - - -#endif /* end of CMOCK_FRAMEWORK_INTERNALS_H */ diff --git a/test/unit-test/vendor/ceedling/vendor/cmock/src/meson.build b/test/unit-test/vendor/ceedling/vendor/cmock/src/meson.build deleted file mode 100644 index b3145c02e..000000000 --- a/test/unit-test/vendor/ceedling/vendor/cmock/src/meson.build +++ /dev/null @@ -1,12 +0,0 @@ -# -# build script written by : Michael Brockus. -# github repo author: Mike Karlesky, Mark VanderVoord, Greg Williams. -# -# license: MIT -# -cmock_dir = include_directories('.') - -cmock_lib = static_library(meson.project_name(), - files('cmock.c'), - dependencies: [unity_dep], - include_directories: cmock_dir) diff --git a/test/unit-test/vendor/ceedling/vendor/diy/lib/diy.rb b/test/unit-test/vendor/ceedling/vendor/diy/lib/diy.rb deleted file mode 100644 index cbeb8267a..000000000 --- a/test/unit-test/vendor/ceedling/vendor/diy/lib/diy.rb +++ /dev/null @@ -1,403 +0,0 @@ -require 'diy/factory.rb' -require 'yaml' -require 'set' - -module DIY #:nodoc:# - VERSION = '1.1.2' - class Context - - class << self - # Enable / disable automatic requiring of libraries. Default: true - attr_accessor :auto_require - end - @auto_require = true - - # Accepts a Hash defining the object context (usually loaded from objects.yml), and an additional - # Hash containing objects to inject into the context. - def initialize(context_hash, extra_inputs={}) - raise "Nil context hash" unless context_hash - raise "Need a hash" unless context_hash.kind_of?(Hash) - [ "[]", "keys" ].each do |mname| - unless extra_inputs.respond_to?(mname) - raise "Extra inputs must respond to hash-like [] operator and methods #keys and #each" - end - end - - # store extra inputs - if extra_inputs.kind_of?(Hash) - @extra_inputs= {} - extra_inputs.each { |k,v| @extra_inputs[k.to_s] = v } # smooth out the names - else - @extra_inputs = extra_inputs - end - - collect_object_and_subcontext_defs context_hash - - # init the cache - @cache = {} - @cache['this_context'] = self - end - - - # Convenience: create a new DIY::Context by loading from a String (or open file handle.) - def self.from_yaml(io_or_string, extra_inputs={}) - raise "nil input to YAML" unless io_or_string - Context.new(YAML.load(io_or_string), extra_inputs) - end - - # Convenience: create a new DIY::Context by loading from the named file. - def self.from_file(fname, extra_inputs={}) - raise "nil file name" unless fname - self.from_yaml(File.read(fname), extra_inputs) - end - - # Return a reference to the object named. If necessary, the object will - # be instantiated on first use. If the object is non-singleton, a new - # object will be produced each time. - def get_object(obj_name) - key = obj_name.to_s - obj = @cache[key] - unless obj - if extra_inputs_has(key) - obj = @extra_inputs[key] - else - case @defs[key] - when MethodDef - obj = construct_method(key) - when FactoryDef - obj = construct_factory(key) - @cache[key] = obj - else - obj = construct_object(key) - @cache[key] = obj if @defs[key].singleton? - end - end - end - obj - end - alias :[] :get_object - - # Inject a named object into the Context. This must be done before the Context has instantiated the - # object in question. - def set_object(obj_name,obj) - key = obj_name.to_s - raise "object '#{key}' already exists in context" if @cache.keys.include?(key) - @cache[key] = obj - end - alias :[]= :set_object - - # Provide a listing of object names - def keys - (@defs.keys.to_set + @extra_inputs.keys.to_set).to_a - end - - # Instantiate and yield the named subcontext - def within(sub_context_name) - # Find the subcontext definitaion: - context_def = @sub_context_defs[sub_context_name.to_s] - raise "No sub-context named #{sub_context_name}" unless context_def - # Instantiate a new context using self as parent: - context = Context.new( context_def, self ) - - yield context - end - - # Returns true if the context contains an object with the given name - def contains_object(obj_name) - key = obj_name.to_s - @defs.keys.member?(key) or extra_inputs_has(key) - end - - # Every top level object in the Context is instantiated. This is especially useful for - # systems that have "floating observers"... objects that are never directly accessed, who - # would thus never be instantiated by coincedence. This does not build any subcontexts - # that may exist. - def build_everything - @defs.keys.each { |k| self[k] } - end - alias :build_all :build_everything - alias :preinstantiate_singletons :build_everything - - private - - def collect_object_and_subcontext_defs(context_hash) - @defs = {} - @sub_context_defs = {} - get_defs_from context_hash - end - - def get_defs_from(hash, namespace=nil) - hash.each do |name,info| - # we modify the info hash below so it's important to have a new - # instance to play with - info = info.dup if info - - # see if we are building a factory - if info and info.has_key?('builds') - unless info.has_key?('auto_require') - info['auto_require'] = self.class.auto_require - end - - if namespace - info['builds'] = namespace.build_classname(info['builds']) - end - @defs[name] = FactoryDef.new({:name => name, - :target => info['builds'], - :library => info['library'], - :auto_require => info['auto_require']}) - next - end - - name = name.to_s - case name - when /^\+/ - # subcontext - @sub_context_defs[name.gsub(/^\+/,'')] = info - - when /^using_namespace/ - # namespace: use a module(s) prefix for the classname of contained object defs - # NOTE: namespacing is NOT scope... it's just a convenient way to setup class names for a group of objects. - get_defs_from info, parse_namespace(name) - when /^method\s/ - key_name = name.gsub(/^method\s/, "") - @defs[key_name] = MethodDef.new(:name => key_name, - :object => info['object'], - :method => info['method'], - :attach => info['attach']) - else - # Normal object def - info ||= {} - if extra_inputs_has(name) - raise ConstructionError.new(name, "Object definition conflicts with parent context") - end - unless info.has_key?('auto_require') - info['auto_require'] = self.class.auto_require - end - if namespace - if info['class'] - info['class'] = namespace.build_classname(info['class']) - else - info['class'] = namespace.build_classname(name) - end - end - - @defs[name] = ObjectDef.new(:name => name, :info => info) - - end - end - end - - def construct_method(key) - method_definition = @defs[key] - object = get_object(method_definition.object) - method = object.method(method_definition.method) - - unless method_definition.attach.nil? - instance_var_name = "@__diy_#{method_definition.object}" - - method_definition.attach.each do |object_key| - get_object(object_key).instance_eval do - instance_variable_set(instance_var_name, object) - eval %|def #{key}(*args) - #{instance_var_name}.#{method_definition.method}(*args) - end| - end - end - end - - return method - rescue Exception => oops - build_and_raise_construction_error(key, oops) - end - - def construct_object(key) - # Find the object definition - obj_def = @defs[key] - raise "No object definition for '#{key}'" unless obj_def - # If object def mentions a library, load it - require obj_def.library if obj_def.library - - # Resolve all components for the object - arg_hash = {} - obj_def.components.each do |name,value| - case value - when Lookup - arg_hash[name.to_sym] = get_object(value.name) - when StringValue - arg_hash[name.to_sym] = value.literal_value - else - raise "Cannot cope with component definition '#{value.inspect}'" - end - end - # Get a reference to the class for the object - big_c = get_class_for_name_with_module_delimeters(obj_def.class_name) - # Make and return the instance - if obj_def.use_class_directly? - return big_c - elsif arg_hash.keys.size > 0 - return big_c.new(arg_hash) - else - return big_c.new - end - rescue Exception => oops - build_and_raise_construction_error(key, oops) - end - - def build_and_raise_construction_error(key, oops) - cerr = ConstructionError.new(key,oops) - cerr.set_backtrace(oops.backtrace) - raise cerr - end - - def get_class_for_name_with_module_delimeters(class_name) - class_name.split(/::/).inject(Object) do |mod,const_name| mod.const_get(const_name) end - end - - def extra_inputs_has(key) - if key.nil? or key.strip == '' - raise ArgumentError.new("Cannot lookup objects with nil keys") - end - @extra_inputs.keys.member?(key) or @extra_inputs.keys.member?(key.to_sym) - end - - def parse_namespace(str) - Namespace.new(str) - end - end - - class Namespace #:nodoc:# - def initialize(str) - # 'using_namespace Animal Reptile' - parts = str.split(/\s+/) - raise "Namespace definitions must begin with 'using_namespace'" unless parts[0] == 'using_namespace' - parts.shift - - if parts.length > 0 and parts[0] =~ /::/ - parts = parts[0].split(/::/) - end - - raise NamespaceError, "Namespace needs to indicate a module" if parts.empty? - - @module_nest = parts - end - - def build_classname(name) - [ @module_nest, Infl.camelize(name) ].flatten.join("::") - end - end - - class Lookup #:nodoc: - attr_reader :name - def initialize(obj_name) - @name = obj_name - end - end - - class MethodDef #:nodoc: - attr_accessor :name, :object, :method, :attach - - def initialize(opts) - @name, @object, @method, @attach = opts[:name], opts[:object], opts[:method], opts[:attach] - end - end - - class ObjectDef #:nodoc: - attr_accessor :name, :class_name, :library, :components - def initialize(opts) - name = opts[:name] - raise "Can't make an ObjectDef without a name" if name.nil? - - info = opts[:info] || {} - info = info.clone - - @components = {} - - # Object name - @name = name - - # Class name - @class_name = info.delete 'class' - @class_name ||= info.delete 'type' - @class_name ||= Infl.camelize(@name) - - # Auto Require - @auto_require = info.delete 'auto_require' - - # Library - @library = info.delete 'library' - @library ||= info.delete 'lib' - @library ||= Infl.underscore(@class_name) if @auto_require - - # Use Class Directly - @use_class_directly = info.delete 'use_class_directly' - - # Auto-compose - compose = info.delete 'compose' - if compose - case compose - when Array - auto_names = compose.map { |x| x.to_s } - when String - auto_names = compose.split(',').map { |x| x.to_s.strip } - when Symbol - auto_names = [ compose.to_s ] - else - raise "Cannot auto compose object #{@name}, bad 'compose' format: #{compose.inspect}" - end - end - auto_names ||= [] - auto_names.each do |cname| - @components[cname] = Lookup.new(cname) - end - - # Singleton status - if info['singleton'].nil? - @singleton = true - else - @singleton = info['singleton'] - end - info.delete 'singleton' - - # Remaining keys - info.each do |key,val| - @components[key.to_s] = Lookup.new(val.to_s) - end - - end - - def singleton? - @singleton - end - - def use_class_directly? - @use_class_directly == true - end - - end - - class ConstructionError < RuntimeError #:nodoc:# - def initialize(object_name, cause=nil) - object_name = object_name - cause = cause - m = "Failed to construct '#{object_name}'" - if cause - m << "\n ...caused by:\n >>> #{cause}" - end - super m - end - end - - class NamespaceError < RuntimeError #:nodoc:# - end - - module Infl #:nodoc:# - # Ganked this from Inflector: - def self.camelize(lower_case_and_underscored_word) - lower_case_and_underscored_word.to_s.gsub(/\/(.?)/) { "::" + $1.upcase }.gsub(/(^|_)(.)/) { $2.upcase } - end - # Ganked this from Inflector: - def self.underscore(camel_cased_word) - camel_cased_word.to_s.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z])/,'\1_\2').gsub(/([a-z\d])([A-Z])/,'\1_\2').downcase - end - end -end diff --git a/test/unit-test/vendor/ceedling/vendor/diy/lib/diy/factory.rb b/test/unit-test/vendor/ceedling/vendor/diy/lib/diy/factory.rb deleted file mode 100644 index 8f00e5e45..000000000 --- a/test/unit-test/vendor/ceedling/vendor/diy/lib/diy/factory.rb +++ /dev/null @@ -1,35 +0,0 @@ -module DIY #:nodoc:# - class FactoryDef #:nodoc: - attr_accessor :name, :target, :class_name, :library - - def initialize(opts) - @name, @target, @library, @auto_require = - opts[:name], opts[:target], opts[:library], opts[:auto_require] - - @class_name = Infl.camelize(@target) - @library ||= Infl.underscore(@class_name) if @auto_require - end - end - - class Context - def construct_factory(key) - factory_def = @defs[key] -# puts "requiring #{factory_def.library}" - require factory_def.library if factory_def.library - - big_c = get_class_for_name_with_module_delimeters(factory_def.class_name) - - FactoryFactory.new(big_c) - end - end - - class FactoryFactory - def initialize(clazz) - @class_to_create = clazz - end - - def create(*args) - @class_to_create.new(*args) - end - end -end diff --git a/test/unit-test/vendor/ceedling/vendor/unity/auto/colour_prompt.rb b/test/unit-test/vendor/ceedling/vendor/unity/auto/colour_prompt.rb deleted file mode 100644 index 85cbfd80c..000000000 --- a/test/unit-test/vendor/ceedling/vendor/unity/auto/colour_prompt.rb +++ /dev/null @@ -1,119 +0,0 @@ -# ========================================== -# Unity Project - A Test Framework for C -# Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams -# [Released under MIT License. Please refer to license.txt for details] -# ========================================== - -if RUBY_PLATFORM =~ /(win|w)32$/ - begin - require 'Win32API' - rescue LoadError - puts 'ERROR! "Win32API" library not found' - puts '"Win32API" is required for colour on a windows machine' - puts ' try => "gem install Win32API" on the command line' - puts - end - # puts - # puts 'Windows Environment Detected...' - # puts 'Win32API Library Found.' - # puts -end - -class ColourCommandLine - def initialize - return unless RUBY_PLATFORM =~ /(win|w)32$/ - - get_std_handle = Win32API.new('kernel32', 'GetStdHandle', ['L'], 'L') - @set_console_txt_attrb = - Win32API.new('kernel32', 'SetConsoleTextAttribute', %w[L N], 'I') - @hout = get_std_handle.call(-11) - end - - def change_to(new_colour) - if RUBY_PLATFORM =~ /(win|w)32$/ - @set_console_txt_attrb.call(@hout, win32_colour(new_colour)) - else - "\033[30;#{posix_colour(new_colour)};22m" - end - end - - def win32_colour(colour) - case colour - when :black then 0 - when :dark_blue then 1 - when :dark_green then 2 - when :dark_cyan then 3 - when :dark_red then 4 - when :dark_purple then 5 - when :dark_yellow, :narrative then 6 - when :default_white, :default, :dark_white then 7 - when :silver then 8 - when :blue then 9 - when :green, :success then 10 - when :cyan, :output then 11 - when :red, :failure then 12 - when :purple then 13 - when :yellow then 14 - when :white then 15 - else - 0 - end - end - - def posix_colour(colour) - # ANSI Escape Codes - Foreground colors - # | Code | Color | - # | 39 | Default foreground color | - # | 30 | Black | - # | 31 | Red | - # | 32 | Green | - # | 33 | Yellow | - # | 34 | Blue | - # | 35 | Magenta | - # | 36 | Cyan | - # | 37 | Light gray | - # | 90 | Dark gray | - # | 91 | Light red | - # | 92 | Light green | - # | 93 | Light yellow | - # | 94 | Light blue | - # | 95 | Light magenta | - # | 96 | Light cyan | - # | 97 | White | - - case colour - when :black then 30 - when :red, :failure then 31 - when :green, :success then 32 - when :yellow then 33 - when :blue, :narrative then 34 - when :purple, :magenta then 35 - when :cyan, :output then 36 - when :white, :default_white then 37 - when :default then 39 - else - 39 - end - end - - def out_c(mode, colour, str) - case RUBY_PLATFORM - when /(win|w)32$/ - change_to(colour) - $stdout.puts str if mode == :puts - $stdout.print str if mode == :print - change_to(:default_white) - else - $stdout.puts("#{change_to(colour)}#{str}\033[0m") if mode == :puts - $stdout.print("#{change_to(colour)}#{str}\033[0m") if mode == :print - end - end -end - -def colour_puts(role, str) - ColourCommandLine.new.out_c(:puts, role, str) -end - -def colour_print(role, str) - ColourCommandLine.new.out_c(:print, role, str) -end diff --git a/test/unit-test/vendor/ceedling/vendor/unity/auto/colour_reporter.rb b/test/unit-test/vendor/ceedling/vendor/unity/auto/colour_reporter.rb deleted file mode 100644 index 1c3bc2162..000000000 --- a/test/unit-test/vendor/ceedling/vendor/unity/auto/colour_reporter.rb +++ /dev/null @@ -1,39 +0,0 @@ -# ========================================== -# Unity Project - A Test Framework for C -# Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams -# [Released under MIT License. Please refer to license.txt for details] -# ========================================== - -require_relative 'colour_prompt' - -$colour_output = true - -def report(message) - if !$colour_output - $stdout.puts(message) - else - message = message.join('\n') if message.class == Array - message.each_line do |line| - line.chomp! - colour = case line - when /(?:total\s+)?tests:?\s+(\d+)\s+(?:total\s+)?failures:?\s+\d+\s+Ignored:?/i - Regexp.last_match(1).to_i.zero? ? :green : :red - when /PASS/ - :green - when /^OK$/ - :green - when /(?:FAIL|ERROR)/ - :red - when /IGNORE/ - :yellow - when /^(?:Creating|Compiling|Linking)/ - :white - else - :silver - end - colour_puts(colour, line) - end - end - $stdout.flush - $stderr.flush -end diff --git a/test/unit-test/vendor/ceedling/vendor/unity/auto/generate_config.yml b/test/unit-test/vendor/ceedling/vendor/unity/auto/generate_config.yml deleted file mode 100644 index c7679aefc..000000000 --- a/test/unit-test/vendor/ceedling/vendor/unity/auto/generate_config.yml +++ /dev/null @@ -1,36 +0,0 @@ -#this is a sample configuration file for generate_module -#you would use it by calling generate_module with the -ygenerate_config.yml option -#files like this are useful for customizing generate_module to your environment -:generate_module: - :defaults: - #these defaults are used in place of any missing options at the command line - :path_src: ../src/ - :path_inc: ../src/ - :path_tst: ../test/ - :update_svn: true - :includes: - #use [] for no additional includes, otherwise list the includes on separate lines - :src: - - Defs.h - - Board.h - :inc: [] - :tst: - - Defs.h - - Board.h - - Exception.h - :boilerplates: - #these are inserted at the top of generated files. - #just comment out or remove if not desired. - #use %1$s where you would like the file name to appear (path/extension not included) - :src: | - //------------------------------------------- - // %1$s.c - //------------------------------------------- - :inc: | - //------------------------------------------- - // %1$s.h - //------------------------------------------- - :tst: | - //------------------------------------------- - // Test%1$s.c : Units tests for %1$s.c - //------------------------------------------- diff --git a/test/unit-test/vendor/ceedling/vendor/unity/auto/generate_module.rb b/test/unit-test/vendor/ceedling/vendor/unity/auto/generate_module.rb deleted file mode 100644 index 0a88becc9..000000000 --- a/test/unit-test/vendor/ceedling/vendor/unity/auto/generate_module.rb +++ /dev/null @@ -1,313 +0,0 @@ -# ========================================== -# Unity Project - A Test Framework for C -# Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams -# [Released under MIT License. Please refer to license.txt for details] -# ========================================== - -# This script creates all the files with start code necessary for a new module. -# A simple module only requires a source file, header file, and test file. -# Triad modules require a source, header, and test file for each triad type (like model, conductor, and hardware). - -require 'rubygems' -require 'fileutils' -require 'pathname' - -# TEMPLATE_TST -TEMPLATE_TST ||= '#ifdef TEST - -#include "unity.h" - -%2$s#include "%1$s.h" - -void setUp(void) -{ -} - -void tearDown(void) -{ -} - -void test_%4$s_NeedToImplement(void) -{ - TEST_IGNORE_MESSAGE("Need to Implement %1$s"); -} - -#endif // TEST -'.freeze - -# TEMPLATE_SRC -TEMPLATE_SRC ||= '%2$s#include "%1$s.h" -'.freeze - -# TEMPLATE_INC -TEMPLATE_INC ||= '#ifndef %3$s_H -#define %3$s_H -%2$s - -#endif // %3$s_H -'.freeze - -class UnityModuleGenerator - ############################ - def initialize(options = nil) - @options = UnityModuleGenerator.default_options - case options - when NilClass then @options - when String then @options.merge!(UnityModuleGenerator.grab_config(options)) - when Hash then @options.merge!(options) - else raise 'If you specify arguments, it should be a filename or a hash of options' - end - - # Create default file paths if none were provided - @options[:path_src] = "#{__dir__}/../src/" if @options[:path_src].nil? - @options[:path_inc] = @options[:path_src] if @options[:path_inc].nil? - @options[:path_tst] = "#{__dir__}/../test/" if @options[:path_tst].nil? - @options[:path_src] += '/' unless @options[:path_src][-1] == 47 - @options[:path_inc] += '/' unless @options[:path_inc][-1] == 47 - @options[:path_tst] += '/' unless @options[:path_tst][-1] == 47 - - # Built in patterns - @patterns = { - 'src' => { - '' => { inc: [] } - }, - 'test' => { - '' => { inc: [] } - }, - 'dh' => { - 'Driver' => { inc: [create_filename('%1$s', 'Hardware.h')] }, - 'Hardware' => { inc: [] } - }, - 'dih' => { - 'Driver' => { inc: [create_filename('%1$s', 'Hardware.h'), create_filename('%1$s', 'Interrupt.h')] }, - 'Interrupt' => { inc: [create_filename('%1$s', 'Hardware.h')] }, - 'Hardware' => { inc: [] } - }, - 'mch' => { - 'Model' => { inc: [] }, - 'Conductor' => { inc: [create_filename('%1$s', 'Model.h'), create_filename('%1$s', 'Hardware.h')] }, - 'Hardware' => { inc: [] } - }, - 'mvp' => { - 'Model' => { inc: [] }, - 'Presenter' => { inc: [create_filename('%1$s', 'Model.h'), create_filename('%1$s', 'View.h')] }, - 'View' => { inc: [] } - } - } - end - - ############################ - def self.default_options - { - pattern: 'src', - includes: { - src: [], - inc: [], - tst: [] - }, - update_svn: false, - boilerplates: {}, - test_prefix: 'Test', - mock_prefix: 'Mock' - } - end - - ############################ - def self.grab_config(config_file) - options = default_options - unless config_file.nil? || config_file.empty? - require 'yaml' - yaml_guts = YAML.load_file(config_file) - options.merge!(yaml_guts[:unity] || yaml_guts[:cmock]) - raise "No :unity or :cmock section found in #{config_file}" unless options - end - options - end - - ############################ - def files_to_operate_on(module_name, pattern = nil) - # strip any leading path information from the module name and save for later - subfolder = File.dirname(module_name) - module_name = File.basename(module_name) - - # create triad definition - prefix = @options[:test_prefix] || 'Test' - triad = [{ ext: '.c', path: @options[:path_src], prefix: '', template: TEMPLATE_SRC, inc: :src, boilerplate: @options[:boilerplates][:src] }, - { ext: '.h', path: @options[:path_inc], prefix: '', template: TEMPLATE_INC, inc: :inc, boilerplate: @options[:boilerplates][:inc] }, - { ext: '.c', path: @options[:path_tst], prefix: prefix, template: TEMPLATE_TST, inc: :tst, boilerplate: @options[:boilerplates][:tst] }] - - # prepare the pattern for use - pattern = (pattern || @options[:pattern] || 'src').downcase - patterns = @patterns[pattern] - raise "ERROR: The design pattern '#{pattern}' specified isn't one that I recognize!" if patterns.nil? - - # single file patterns (currently just 'test') can reject the other parts of the triad - triad.select! { |v| v[:inc] == :tst } if pattern == 'test' - - # Assemble the path/names of the files we need to work with. - files = [] - triad.each do |cfg| - patterns.each_pair do |pattern_file, pattern_traits| - submodule_name = create_filename(module_name, pattern_file) - filename = cfg[:prefix] + submodule_name + cfg[:ext] - files << { - path: (Pathname.new("#{cfg[:path]}#{subfolder}") + filename).cleanpath, - name: submodule_name, - template: cfg[:template], - boilerplate: cfg[:boilerplate], - includes: case (cfg[:inc]) - when :src then (@options[:includes][:src] || []) | (pattern_traits[:inc].map { |f| format(f, module_name) }) - when :inc then (@options[:includes][:inc] || []) - when :tst then (@options[:includes][:tst] || []) | (pattern_traits[:inc].map { |f| format("#{@options[:mock_prefix]}#{f}", module_name) }) - end - } - end - end - - files - end - - ############################ - def neutralize_filename(name, start_cap = true) - return name if name.empty? - name = name.split(/(?:\s+|_|(?=[A-Z][a-z]))|(?<=[a-z])(?=[A-Z])/).map { |v| v.capitalize }.join('_') - name = name[0].downcase + name[1..-1] unless start_cap - return name - end - - ############################ - def create_filename(part1, part2 = '') - name = part2.empty? ? part1 : part1 + '_' + part2 - case (@options[:naming]) - when 'bumpy' then neutralize_filename(name,false).delete('_') - when 'camel' then neutralize_filename(name).delete('_') - when 'snake' then neutralize_filename(name).downcase - when 'caps' then neutralize_filename(name).upcase - else name - end - end - - ############################ - def generate(module_name, pattern = nil) - files = files_to_operate_on(module_name, pattern) - - # Abort if all of the module files already exist - all_files_exist = true - files.each do |file| - all_files_exist = false unless File.exist?(file[:path]) - end - raise "ERROR: File #{files[0][:name]} already exists. Exiting." if all_files_exist - - # Create Source Modules - files.each_with_index do |file, _i| - # If this file already exists, don't overwrite it. - if File.exist?(file[:path]) - puts "File #{file[:path]} already exists!" - next - end - # Create the path first if necessary. - FileUtils.mkdir_p(File.dirname(file[:path]), verbose: false) - File.open(file[:path], 'w') do |f| - f.write("#{file[:boilerplate]}\n" % [file[:name]]) unless file[:boilerplate].nil? - f.write(file[:template] % [file[:name], - file[:includes].map { |ff| "#include \"#{ff}\"\n" }.join, - file[:name].upcase.gsub(/-/, '_'), - file[:name].gsub(/-/, '_')]) - end - if @options[:update_svn] - `svn add \"#{file[:path]}\"` - if $!.exitstatus.zero? - puts "File #{file[:path]} created and added to source control" - else - puts "File #{file[:path]} created but FAILED adding to source control!" - end - else - puts "File #{file[:path]} created" - end - end - puts 'Generate Complete' - end - - ############################ - def destroy(module_name, pattern = nil) - files_to_operate_on(module_name, pattern).each do |filespec| - file = filespec[:path] - if File.exist?(file) - if @options[:update_svn] - `svn delete \"#{file}\" --force` - puts "File #{file} deleted and removed from source control" - else - FileUtils.remove(file) - puts "File #{file} deleted" - end - else - puts "File #{file} does not exist so cannot be removed." - end - end - puts 'Destroy Complete' - end -end - -############################ -# Handle As Command Line If Called That Way -if $0 == __FILE__ - destroy = false - options = {} - module_name = nil - - # Parse the command line parameters. - ARGV.each do |arg| - case arg - when /^-d/ then destroy = true - when /^-u/ then options[:update_svn] = true - when /^-p\"?(\w+)\"?/ then options[:pattern] = Regexp.last_match(1) - when /^-s\"?(.+)\"?/ then options[:path_src] = Regexp.last_match(1) - when /^-i\"?(.+)\"?/ then options[:path_inc] = Regexp.last_match(1) - when /^-t\"?(.+)\"?/ then options[:path_tst] = Regexp.last_match(1) - when /^-n\"?(.+)\"?/ then options[:naming] = Regexp.last_match(1) - when /^-y\"?(.+)\"?/ then options = UnityModuleGenerator.grab_config(Regexp.last_match(1)) - when /^(\w+)/ - raise "ERROR: You can't have more than one Module name specified!" unless module_name.nil? - - module_name = arg - when /^-(h|-help)/ - ARGV = [].freeze - else - raise "ERROR: Unknown option specified '#{arg}'" - end - end - - unless ARGV[0] - puts ["\nGENERATE MODULE\n-------- ------", - "\nUsage: ruby generate_module [options] module_name", - " -i\"include\" sets the path to output headers to 'include' (DEFAULT ../src)", - " -s\"../src\" sets the path to output source to '../src' (DEFAULT ../src)", - " -t\"C:/test\" sets the path to output source to 'C:/test' (DEFAULT ../test)", - ' -p"MCH" sets the output pattern to MCH.', - ' dh - driver hardware.', - ' dih - driver interrupt hardware.', - ' mch - model conductor hardware.', - ' mvp - model view presenter.', - ' src - just a source module, header and test. (DEFAULT)', - ' test - just a test file.', - ' -d destroy module instead of creating it.', - ' -n"camel" sets the file naming convention.', - ' bumpy - BumpyCaseFilenames.', - ' camel - camelCaseFilenames.', - ' snake - snake_case_filenames.', - ' caps - CAPS_CASE_FILENAMES.', - ' -u update subversion too (requires subversion command line)', - ' -y"my.yml" selects a different yaml config file for module generation', - ''].join("\n") - exit - end - - raise 'ERROR: You must have a Module name specified! (use option -h for help)' if module_name.nil? - - if destroy - UnityModuleGenerator.new(options).destroy(module_name) - else - UnityModuleGenerator.new(options).generate(module_name) - end - -end diff --git a/test/unit-test/vendor/ceedling/vendor/unity/auto/generate_test_runner.rb b/test/unit-test/vendor/ceedling/vendor/unity/auto/generate_test_runner.rb deleted file mode 100644 index 6821bdc60..000000000 --- a/test/unit-test/vendor/ceedling/vendor/unity/auto/generate_test_runner.rb +++ /dev/null @@ -1,511 +0,0 @@ -# ========================================== -# Unity Project - A Test Framework for C -# Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams -# [Released under MIT License. Please refer to license.txt for details] -# ========================================== - -class UnityTestRunnerGenerator - def initialize(options = nil) - @options = UnityTestRunnerGenerator.default_options - case options - when NilClass - @options - when String - @options.merge!(UnityTestRunnerGenerator.grab_config(options)) - when Hash - # Check if some of these have been specified - @options[:has_setup] = !options[:setup_name].nil? - @options[:has_teardown] = !options[:teardown_name].nil? - @options[:has_suite_setup] = !options[:suite_setup].nil? - @options[:has_suite_teardown] = !options[:suite_teardown].nil? - @options.merge!(options) - else - raise 'If you specify arguments, it should be a filename or a hash of options' - end - require_relative 'type_sanitizer' - end - - def self.default_options - { - includes: [], - defines: [], - plugins: [], - framework: :unity, - test_prefix: 'test|spec|should', - mock_prefix: 'Mock', - mock_suffix: '', - setup_name: 'setUp', - teardown_name: 'tearDown', - test_reset_name: 'resetTest', - test_verify_name: 'verifyTest', - main_name: 'main', # set to :auto to automatically generate each time - main_export_decl: '', - cmdline_args: false, - omit_begin_end: false, - use_param_tests: false, - include_extensions: '(?:hpp|hh|H|h)', - source_extensions: '(?:cpp|cc|ino|C|c)' - } - end - - def self.grab_config(config_file) - options = default_options - unless config_file.nil? || config_file.empty? - require 'yaml' - yaml_guts = YAML.load_file(config_file) - options.merge!(yaml_guts[:unity] || yaml_guts[:cmock]) - raise "No :unity or :cmock section found in #{config_file}" unless options - end - options - end - - def run(input_file, output_file, options = nil) - @options.merge!(options) unless options.nil? - - # pull required data from source file - source = File.read(input_file) - source = source.force_encoding('ISO-8859-1').encode('utf-8', replace: nil) - tests = find_tests(source) - headers = find_includes(source) - testfile_includes = (headers[:local] + headers[:system]) - used_mocks = find_mocks(testfile_includes) - testfile_includes = (testfile_includes - used_mocks) - testfile_includes.delete_if { |inc| inc =~ /(unity|cmock)/ } - find_setup_and_teardown(source) - - # build runner file - generate(input_file, output_file, tests, used_mocks, testfile_includes) - - # determine which files were used to return them - all_files_used = [input_file, output_file] - all_files_used += testfile_includes.map { |filename| filename + '.c' } unless testfile_includes.empty? - all_files_used += @options[:includes] unless @options[:includes].empty? - all_files_used += headers[:linkonly] unless headers[:linkonly].empty? - all_files_used.uniq - end - - def generate(input_file, output_file, tests, used_mocks, testfile_includes) - File.open(output_file, 'w') do |output| - create_header(output, used_mocks, testfile_includes) - create_externs(output, tests, used_mocks) - create_mock_management(output, used_mocks) - create_setup(output) - create_teardown(output) - create_suite_setup(output) - create_suite_teardown(output) - create_reset(output) - create_run_test(output) unless tests.empty? - create_args_wrappers(output, tests) - create_main(output, input_file, tests, used_mocks) - end - - return unless @options[:header_file] && !@options[:header_file].empty? - - File.open(@options[:header_file], 'w') do |output| - create_h_file(output, @options[:header_file], tests, testfile_includes, used_mocks) - end - end - - def find_tests(source) - tests_and_line_numbers = [] - - # contains characters which will be substituted from within strings, doing - # this prevents these characters from interfering with scrubbers - # @ is not a valid C character, so there should be no clashes with files genuinely containing these markers - substring_subs = { '{' => '@co@', '}' => '@cc@', ';' => '@ss@', '/' => '@fs@' } - substring_re = Regexp.union(substring_subs.keys) - substring_unsubs = substring_subs.invert # the inverse map will be used to fix the strings afterwards - substring_unsubs['@quote@'] = '\\"' - substring_unsubs['@apos@'] = '\\\'' - substring_unre = Regexp.union(substring_unsubs.keys) - source_scrubbed = source.clone - source_scrubbed = source_scrubbed.gsub(/\\"/, '@quote@') # hide escaped quotes to allow capture of the full string/char - source_scrubbed = source_scrubbed.gsub(/\\'/, '@apos@') # hide escaped apostrophes to allow capture of the full string/char - source_scrubbed = source_scrubbed.gsub(/("[^"\n]*")|('[^'\n]*')/) { |s| s.gsub(substring_re, substring_subs) } # temporarily hide problematic characters within strings - source_scrubbed = source_scrubbed.gsub(/\/\/(?:.+\/\*|\*(?:$|[^\/])).*$/, '') # remove line comments that comment out the start of blocks - source_scrubbed = source_scrubbed.gsub(/\/\*.*?\*\//m, '') # remove block comments - source_scrubbed = source_scrubbed.gsub(/\/\/.*$/, '') # remove line comments (all that remain) - lines = source_scrubbed.split(/(^\s*\#.*$) | (;|\{|\}) /x) # Treat preprocessor directives as a logical line. Match ;, {, and } as end of lines - .map { |line| line.gsub(substring_unre, substring_unsubs) } # unhide the problematic characters previously removed - - lines.each_with_index do |line, _index| - # find tests - next unless line =~ /^((?:\s*(?:TEST_CASE|TEST_RANGE)\s*\(.*?\)\s*)*)\s*void\s+((?:#{@options[:test_prefix]}).*)\s*\(\s*(.*)\s*\)/m - - arguments = Regexp.last_match(1) - name = Regexp.last_match(2) - call = Regexp.last_match(3) - params = Regexp.last_match(4) - args = nil - - if @options[:use_param_tests] && !arguments.empty? - args = [] - arguments.scan(/\s*TEST_CASE\s*\((.*)\)\s*$/) { |a| args << a[0] } - - arguments.scan(/\s*TEST_RANGE\s*\((.*)\)\s*$/).flatten.each do |range_str| - args += range_str.scan(/\[\s*(-?\d+.?\d*),\s*(-?\d+.?\d*),\s*(-?\d+.?\d*)\s*\]/).map do |arg_values_str| - arg_values_str.map do |arg_value_str| - arg_value_str.include?('.') ? arg_value_str.to_f : arg_value_str.to_i - end - end.map do |arg_values| - (arg_values[0]..arg_values[1]).step(arg_values[2]).to_a - end.reduce do |result, arg_range_expanded| - result.product(arg_range_expanded) - end.map do |arg_combinations| - arg_combinations.flatten.join(', ') - end - end - end - - tests_and_line_numbers << { test: name, args: args, call: call, params: params, line_number: 0 } - end - - tests_and_line_numbers.uniq! { |v| v[:test] } - - # determine line numbers and create tests to run - source_lines = source.split("\n") - source_index = 0 - tests_and_line_numbers.size.times do |i| - source_lines[source_index..-1].each_with_index do |line, index| - next unless line =~ /\s+#{tests_and_line_numbers[i][:test]}(?:\s|\()/ - - source_index += index - tests_and_line_numbers[i][:line_number] = source_index + 1 - break - end - end - - tests_and_line_numbers - end - - def find_includes(source) - # remove comments (block and line, in three steps to ensure correct precedence) - source.gsub!(/\/\/(?:.+\/\*|\*(?:$|[^\/])).*$/, '') # remove line comments that comment out the start of blocks - source.gsub!(/\/\*.*?\*\//m, '') # remove block comments - source.gsub!(/\/\/.*$/, '') # remove line comments (all that remain) - - # parse out includes - includes = { - local: source.scan(/^\s*#include\s+\"\s*(.+\.#{@options[:include_extensions]})\s*\"/).flatten, - system: source.scan(/^\s*#include\s+<\s*(.+)\s*>/).flatten.map { |inc| "<#{inc}>" }, - linkonly: source.scan(/^TEST_FILE\(\s*\"\s*(.+\.#{@options[:source_extensions]})\s*\"/).flatten - } - includes - end - - def find_mocks(includes) - mock_headers = [] - includes.each do |include_path| - include_file = File.basename(include_path) - mock_headers << include_path if include_file =~ /^#{@options[:mock_prefix]}.*#{@options[:mock_suffix]}\.h$/i - end - mock_headers - end - - def find_setup_and_teardown(source) - @options[:has_setup] = source =~ /void\s+#{@options[:setup_name]}\s*\(/ - @options[:has_teardown] = source =~ /void\s+#{@options[:teardown_name]}\s*\(/ - @options[:has_suite_setup] ||= (source =~ /void\s+suiteSetUp\s*\(/) - @options[:has_suite_teardown] ||= (source =~ /int\s+suiteTearDown\s*\(int\s+([a-zA-Z0-9_])+\s*\)/) - end - - def create_header(output, mocks, testfile_includes = []) - output.puts('/* AUTOGENERATED FILE. DO NOT EDIT. */') - output.puts("\n/*=======Automagically Detected Files To Include=====*/") - output.puts("#include \"#{@options[:framework]}.h\"") - output.puts('#include "cmock.h"') unless mocks.empty? - if @options[:defines] && !@options[:defines].empty? - @options[:defines].each { |d| output.puts("#ifndef #{d}\n#define #{d}\n#endif /* #{d} */") } - end - if @options[:header_file] && !@options[:header_file].empty? - output.puts("#include \"#{File.basename(@options[:header_file])}\"") - else - @options[:includes].flatten.uniq.compact.each do |inc| - output.puts("#include #{inc.include?('<') ? inc : "\"#{inc}\""}") - end - testfile_includes.each do |inc| - output.puts("#include #{inc.include?('<') ? inc : "\"#{inc}\""}") - end - end - mocks.each do |mock| - output.puts("#include \"#{mock}\"") - end - output.puts('#include "CException.h"') if @options[:plugins].include?(:cexception) - - return unless @options[:enforce_strict_ordering] - - output.puts('') - output.puts('int GlobalExpectCount;') - output.puts('int GlobalVerifyOrder;') - output.puts('char* GlobalOrderError;') - end - - def create_externs(output, tests, _mocks) - output.puts("\n/*=======External Functions This Runner Calls=====*/") - output.puts("extern void #{@options[:setup_name]}(void);") - output.puts("extern void #{@options[:teardown_name]}(void);") - output.puts("\n#ifdef __cplusplus\nextern \"C\"\n{\n#endif") if @options[:externc] - tests.each do |test| - output.puts("extern void #{test[:test]}(#{test[:call] || 'void'});") - end - output.puts("#ifdef __cplusplus\n}\n#endif") if @options[:externc] - output.puts('') - end - - def create_mock_management(output, mock_headers) - output.puts("\n/*=======Mock Management=====*/") - output.puts('static void CMock_Init(void)') - output.puts('{') - - if @options[:enforce_strict_ordering] - output.puts(' GlobalExpectCount = 0;') - output.puts(' GlobalVerifyOrder = 0;') - output.puts(' GlobalOrderError = NULL;') - end - - mocks = mock_headers.map { |mock| File.basename(mock, '.*') } - mocks.each do |mock| - mock_clean = TypeSanitizer.sanitize_c_identifier(mock) - output.puts(" #{mock_clean}_Init();") - end - output.puts("}\n") - - output.puts('static void CMock_Verify(void)') - output.puts('{') - mocks.each do |mock| - mock_clean = TypeSanitizer.sanitize_c_identifier(mock) - output.puts(" #{mock_clean}_Verify();") - end - output.puts("}\n") - - output.puts('static void CMock_Destroy(void)') - output.puts('{') - mocks.each do |mock| - mock_clean = TypeSanitizer.sanitize_c_identifier(mock) - output.puts(" #{mock_clean}_Destroy();") - end - output.puts("}\n") - end - - def create_setup(output) - return if @options[:has_setup] - - output.puts("\n/*=======Setup (stub)=====*/") - output.puts("void #{@options[:setup_name]}(void) {}") - end - - def create_teardown(output) - return if @options[:has_teardown] - - output.puts("\n/*=======Teardown (stub)=====*/") - output.puts("void #{@options[:teardown_name]}(void) {}") - end - - def create_suite_setup(output) - return if @options[:suite_setup].nil? - - output.puts("\n/*=======Suite Setup=====*/") - output.puts('void suiteSetUp(void)') - output.puts('{') - output.puts(@options[:suite_setup]) - output.puts('}') - end - - def create_suite_teardown(output) - return if @options[:suite_teardown].nil? - - output.puts("\n/*=======Suite Teardown=====*/") - output.puts('int suiteTearDown(int num_failures)') - output.puts('{') - output.puts(@options[:suite_teardown]) - output.puts('}') - end - - def create_reset(output) - output.puts("\n/*=======Test Reset Options=====*/") - output.puts("void #{@options[:test_reset_name]}(void);") - output.puts("void #{@options[:test_reset_name]}(void)") - output.puts('{') - output.puts(" #{@options[:teardown_name]}();") - output.puts(' CMock_Verify();') - output.puts(' CMock_Destroy();') - output.puts(' CMock_Init();') - output.puts(" #{@options[:setup_name]}();") - output.puts('}') - output.puts("void #{@options[:test_verify_name]}(void);") - output.puts("void #{@options[:test_verify_name]}(void)") - output.puts('{') - output.puts(' CMock_Verify();') - output.puts('}') - end - - def create_run_test(output) - require 'erb' - template = ERB.new(File.read(File.join(__dir__, 'run_test.erb')), nil, '<>') - output.puts("\n" + template.result(binding)) - end - - def create_args_wrappers(output, tests) - return unless @options[:use_param_tests] - - output.puts("\n/*=======Parameterized Test Wrappers=====*/") - tests.each do |test| - next if test[:args].nil? || test[:args].empty? - - test[:args].each.with_index(1) do |args, idx| - output.puts("static void runner_args#{idx}_#{test[:test]}(void)") - output.puts('{') - output.puts(" #{test[:test]}(#{args});") - output.puts("}\n") - end - end - end - - def create_main(output, filename, tests, used_mocks) - output.puts("\n/*=======MAIN=====*/") - main_name = @options[:main_name].to_sym == :auto ? "main_#{filename.gsub('.c', '')}" : (@options[:main_name]).to_s - if @options[:cmdline_args] - if main_name != 'main' - output.puts("#{@options[:main_export_decl]} int #{main_name}(int argc, char** argv);") - end - output.puts("#{@options[:main_export_decl]} int #{main_name}(int argc, char** argv)") - output.puts('{') - output.puts(' int parse_status = UnityParseOptions(argc, argv);') - output.puts(' if (parse_status != 0)') - output.puts(' {') - output.puts(' if (parse_status < 0)') - output.puts(' {') - output.puts(" UnityPrint(\"#{filename.gsub('.c', '')}.\");") - output.puts(' UNITY_PRINT_EOL();') - tests.each do |test| - if (!@options[:use_param_tests]) || test[:args].nil? || test[:args].empty? - output.puts(" UnityPrint(\" #{test[:test]}\");") - output.puts(' UNITY_PRINT_EOL();') - else - test[:args].each do |args| - output.puts(" UnityPrint(\" #{test[:test]}(#{args})\");") - output.puts(' UNITY_PRINT_EOL();') - end - end - end - output.puts(' return 0;') - output.puts(' }') - output.puts(' return parse_status;') - output.puts(' }') - else - main_return = @options[:omit_begin_end] ? 'void' : 'int' - if main_name != 'main' - output.puts("#{@options[:main_export_decl]} #{main_return} #{main_name}(void);") - end - output.puts("#{main_return} #{main_name}(void)") - output.puts('{') - end - output.puts(' suiteSetUp();') if @options[:has_suite_setup] - if @options[:omit_begin_end] - output.puts(" UnitySetTestFile(\"#{filename.gsub(/\\/, '\\\\\\')}\");") - else - output.puts(" UnityBegin(\"#{filename.gsub(/\\/, '\\\\\\')}\");") - end - tests.each do |test| - if (!@options[:use_param_tests]) || test[:args].nil? || test[:args].empty? - output.puts(" run_test(#{test[:test]}, \"#{test[:test]}\", #{test[:line_number]});") - else - test[:args].each.with_index(1) do |args, idx| - wrapper = "runner_args#{idx}_#{test[:test]}" - testname = "#{test[:test]}(#{args})".dump - output.puts(" run_test(#{wrapper}, #{testname}, #{test[:line_number]});") - end - end - end - output.puts - output.puts(' CMock_Guts_MemFreeFinal();') unless used_mocks.empty? - if @options[:has_suite_teardown] - if @options[:omit_begin_end] - output.puts(' (void) suite_teardown(0);') - else - output.puts(' return suiteTearDown(UnityEnd());') - end - else - output.puts(' return UnityEnd();') unless @options[:omit_begin_end] - end - output.puts('}') - end - - def create_h_file(output, filename, tests, testfile_includes, used_mocks) - filename = File.basename(filename).gsub(/[-\/\\\.\,\s]/, '_').upcase - output.puts('/* AUTOGENERATED FILE. DO NOT EDIT. */') - output.puts("#ifndef _#{filename}") - output.puts("#define _#{filename}\n\n") - output.puts("#include \"#{@options[:framework]}.h\"") - output.puts('#include "cmock.h"') unless used_mocks.empty? - @options[:includes].flatten.uniq.compact.each do |inc| - output.puts("#include #{inc.include?('<') ? inc : "\"#{inc}\""}") - end - testfile_includes.each do |inc| - output.puts("#include #{inc.include?('<') ? inc : "\"#{inc}\""}") - end - output.puts "\n" - tests.each do |test| - if test[:params].nil? || test[:params].empty? - output.puts("void #{test[:test]}(void);") - else - output.puts("void #{test[:test]}(#{test[:params]});") - end - end - output.puts("#endif\n\n") - end -end - -if $0 == __FILE__ - options = { includes: [] } - - # parse out all the options first (these will all be removed as we go) - ARGV.reject! do |arg| - case arg - when '-cexception' - options[:plugins] = [:cexception] - true - when /\.*\.ya?ml$/ - options = UnityTestRunnerGenerator.grab_config(arg) - true - when /--(\w+)=\"?(.*)\"?/ - options[Regexp.last_match(1).to_sym] = Regexp.last_match(2) - true - when /\.*\.(?:hpp|hh|H|h)$/ - options[:includes] << arg - true - else false - end - end - - # make sure there is at least one parameter left (the input file) - unless ARGV[0] - puts ["\nusage: ruby #{__FILE__} (files) (options) input_test_file (output)", - "\n input_test_file - this is the C file you want to create a runner for", - ' output - this is the name of the runner file to generate', - ' defaults to (input_test_file)_Runner', - ' files:', - ' *.yml / *.yaml - loads configuration from here in :unity or :cmock', - ' *.h - header files are added as #includes in runner', - ' options:', - ' -cexception - include cexception support', - ' -externc - add extern "C" for cpp support', - ' --setup_name="" - redefine setUp func name to something else', - ' --teardown_name="" - redefine tearDown func name to something else', - ' --main_name="" - redefine main func name to something else', - ' --test_prefix="" - redefine test prefix from default test|spec|should', - ' --test_reset_name="" - redefine resetTest func name to something else', - ' --test_verify_name="" - redefine verifyTest func name to something else', - ' --suite_setup="" - code to execute for setup of entire suite', - ' --suite_teardown="" - code to execute for teardown of entire suite', - ' --use_param_tests=1 - enable parameterized tests (disabled by default)', - ' --omit_begin_end=1 - omit calls to UnityBegin and UnityEnd (disabled by default)', - ' --header_file="" - path/name of test header file to generate too'].join("\n") - exit 1 - end - - # create the default test runner name if not specified - ARGV[1] = ARGV[0].gsub('.c', '_Runner.c') unless ARGV[1] - - UnityTestRunnerGenerator.new(options).run(ARGV[0], ARGV[1]) -end diff --git a/test/unit-test/vendor/ceedling/vendor/unity/auto/parse_output.rb b/test/unit-test/vendor/ceedling/vendor/unity/auto/parse_output.rb deleted file mode 100644 index d72c6e8b2..000000000 --- a/test/unit-test/vendor/ceedling/vendor/unity/auto/parse_output.rb +++ /dev/null @@ -1,322 +0,0 @@ -#============================================================ -# Author: John Theofanopoulos -# A simple parser. Takes the output files generated during the -# build process and extracts information relating to the tests. -# -# Notes: -# To capture an output file under VS builds use the following: -# devenv [build instructions] > Output.txt & type Output.txt -# -# To capture an output file under Linux builds use the following: -# make | tee Output.txt -# -# This script can handle the following output formats: -# - normal output (raw unity) -# - fixture output (unity_fixture.h/.c) -# - fixture output with verbose flag set ("-v") -# -# To use this parser use the following command -# ruby parseOutput.rb [options] [file] -# options: -xml : produce a JUnit compatible XML file -# file: file to scan for results -#============================================================ - -# Parser class for handling the input file -class ParseOutput - def initialize - # internal data - @class_name_idx = 0 - @path_delim = nil - - # xml output related - @xml_out = false - @array_list = false - - # current suite name and statistics - @test_suite = nil - @total_tests = 0 - @test_passed = 0 - @test_failed = 0 - @test_ignored = 0 - end - - # Set the flag to indicate if there will be an XML output file or not - def set_xml_output - @xml_out = true - end - - # If write our output to XML - def write_xml_output - output = File.open('report.xml', 'w') - output << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" - @array_list.each do |item| - output << item << "\n" - end - end - - # Pushes the suite info as xml to the array list, which will be written later - def push_xml_output_suite_info - # Insert opening tag at front - heading = '<testsuite name="Unity" tests="' + @total_tests.to_s + '" failures="' + @test_failed.to_s + '"' + ' skips="' + @test_ignored.to_s + '">' - @array_list.insert(0, heading) - # Push back the closing tag - @array_list.push '</testsuite>' - end - - # Pushes xml output data to the array list, which will be written later - def push_xml_output_passed(test_name) - @array_list.push ' <testcase classname="' + @test_suite + '" name="' + test_name + '"/>' - end - - # Pushes xml output data to the array list, which will be written later - def push_xml_output_failed(test_name, reason) - @array_list.push ' <testcase classname="' + @test_suite + '" name="' + test_name + '">' - @array_list.push ' <failure type="ASSERT FAILED">' + reason + '</failure>' - @array_list.push ' </testcase>' - end - - # Pushes xml output data to the array list, which will be written later - def push_xml_output_ignored(test_name, reason) - @array_list.push ' <testcase classname="' + @test_suite + '" name="' + test_name + '">' - @array_list.push ' <skipped type="TEST IGNORED">' + reason + '</skipped>' - @array_list.push ' </testcase>' - end - - # This function will try and determine when the suite is changed. This is - # is the name that gets added to the classname parameter. - def test_suite_verify(test_suite_name) - # Split the path name - test_name = test_suite_name.split(@path_delim) - - # Remove the extension and extract the base_name - base_name = test_name[test_name.size - 1].split('.')[0] - - # Return if the test suite hasn't changed - return unless base_name.to_s != @test_suite.to_s - - @test_suite = base_name - printf "New Test: %s\n", @test_suite - end - - # Prepares the line for verbose fixture output ("-v") - def prepare_fixture_line(line) - line = line.sub('IGNORE_TEST(', '') - line = line.sub('TEST(', '') - line = line.sub(')', ',') - line = line.chomp - array = line.split(',') - array.map { |x| x.to_s.lstrip.chomp } - end - - # Test was flagged as having passed so format the output. - # This is using the Unity fixture output and not the original Unity output. - def test_passed_unity_fixture(array) - class_name = array[0] - test_name = array[1] - test_suite_verify(class_name) - printf "%-40s PASS\n", test_name - - push_xml_output_passed(test_name) if @xml_out - end - - # Test was flagged as having failed so format the output. - # This is using the Unity fixture output and not the original Unity output. - def test_failed_unity_fixture(array) - class_name = array[0] - test_name = array[1] - test_suite_verify(class_name) - reason_array = array[2].split(':') - reason = reason_array[-1].lstrip.chomp + ' at line: ' + reason_array[-4] - - printf "%-40s FAILED\n", test_name - - push_xml_output_failed(test_name, reason) if @xml_out - end - - # Test was flagged as being ignored so format the output. - # This is using the Unity fixture output and not the original Unity output. - def test_ignored_unity_fixture(array) - class_name = array[0] - test_name = array[1] - reason = 'No reason given' - if array.size > 2 - reason_array = array[2].split(':') - tmp_reason = reason_array[-1].lstrip.chomp - reason = tmp_reason == 'IGNORE' ? 'No reason given' : tmp_reason - end - test_suite_verify(class_name) - printf "%-40s IGNORED\n", test_name - - push_xml_output_ignored(test_name, reason) if @xml_out - end - - # Test was flagged as having passed so format the output - def test_passed(array) - last_item = array.length - 1 - test_name = array[last_item - 1] - test_suite_verify(array[@class_name_idx]) - printf "%-40s PASS\n", test_name - - return unless @xml_out - - push_xml_output_passed(test_name) if @xml_out - end - - # Test was flagged as having failed so format the line - def test_failed(array) - last_item = array.length - 1 - test_name = array[last_item - 2] - reason = array[last_item].chomp.lstrip + ' at line: ' + array[last_item - 3] - class_name = array[@class_name_idx] - - if test_name.start_with? 'TEST(' - array2 = test_name.split(' ') - - test_suite = array2[0].sub('TEST(', '') - test_suite = test_suite.sub(',', '') - class_name = test_suite - - test_name = array2[1].sub(')', '') - end - - test_suite_verify(class_name) - printf "%-40s FAILED\n", test_name - - push_xml_output_failed(test_name, reason) if @xml_out - end - - # Test was flagged as being ignored so format the output - def test_ignored(array) - last_item = array.length - 1 - test_name = array[last_item - 2] - reason = array[last_item].chomp.lstrip - class_name = array[@class_name_idx] - - if test_name.start_with? 'TEST(' - array2 = test_name.split(' ') - - test_suite = array2[0].sub('TEST(', '') - test_suite = test_suite.sub(',', '') - class_name = test_suite - - test_name = array2[1].sub(')', '') - end - - test_suite_verify(class_name) - printf "%-40s IGNORED\n", test_name - - push_xml_output_ignored(test_name, reason) if @xml_out - end - - # Adjusts the os specific members according to the current path style - # (Windows or Unix based) - def detect_os_specifics(line) - if line.include? '\\' - # Windows X:\Y\Z - @class_name_idx = 1 - @path_delim = '\\' - else - # Unix Based /X/Y/Z - @class_name_idx = 0 - @path_delim = '/' - end - end - - # Main function used to parse the file that was captured. - def process(file_name) - @array_list = [] - - puts 'Parsing file: ' + file_name - - @test_passed = 0 - @test_failed = 0 - @test_ignored = 0 - puts '' - puts '=================== RESULTS =====================' - puts '' - File.open(file_name).each do |line| - # Typical test lines look like these: - # ---------------------------------------------------- - # 1. normal output: - # <path>/<test_file>.c:36:test_tc1000_opsys:FAIL: Expected 1 Was 0 - # <path>/<test_file>.c:112:test_tc5004_initCanChannel:IGNORE: Not Yet Implemented - # <path>/<test_file>.c:115:test_tc5100_initCanVoidPtrs:PASS - # - # 2. fixture output - # <path>/<test_file>.c:63:TEST(<test_group>, <test_function>):FAIL: Expected 0x00001234 Was 0x00005A5A - # <path>/<test_file>.c:36:TEST(<test_group>, <test_function>):IGNORE - # Note: "PASS" information won't be generated in this mode - # - # 3. fixture output with verbose information ("-v") - # TEST(<test_group, <test_file>)<path>/<test_file>:168::FAIL: Expected 0x8D Was 0x8C - # TEST(<test_group>, <test_file>)<path>/<test_file>:22::IGNORE: This Test Was Ignored On Purpose - # IGNORE_TEST(<test_group, <test_file>) - # TEST(<test_group, <test_file>) PASS - # - # Note: Where path is different on Unix vs Windows devices (Windows leads with a drive letter)! - detect_os_specifics(line) - line_array = line.split(':') - - # If we were able to split the line then we can look to see if any of our target words - # were found. Case is important. - next unless (line_array.size >= 4) || (line.start_with? 'TEST(') || (line.start_with? 'IGNORE_TEST(') - - # check if the output is fixture output (with verbose flag "-v") - if (line.start_with? 'TEST(') || (line.start_with? 'IGNORE_TEST(') - line_array = prepare_fixture_line(line) - if line.include? ' PASS' - test_passed_unity_fixture(line_array) - @test_passed += 1 - elsif line.include? 'FAIL' - test_failed_unity_fixture(line_array) - @test_failed += 1 - elsif line.include? 'IGNORE' - test_ignored_unity_fixture(line_array) - @test_ignored += 1 - end - # normal output / fixture output (without verbose "-v") - elsif line.include? ':PASS' - test_passed(line_array) - @test_passed += 1 - elsif line.include? ':FAIL' - test_failed(line_array) - @test_failed += 1 - elsif line.include? ':IGNORE:' - test_ignored(line_array) - @test_ignored += 1 - elsif line.include? ':IGNORE' - line_array.push('No reason given') - test_ignored(line_array) - @test_ignored += 1 - end - @total_tests = @test_passed + @test_failed + @test_ignored - end - puts '' - puts '=================== SUMMARY =====================' - puts '' - puts 'Tests Passed : ' + @test_passed.to_s - puts 'Tests Failed : ' + @test_failed.to_s - puts 'Tests Ignored : ' + @test_ignored.to_s - - return unless @xml_out - - # push information about the suite - push_xml_output_suite_info - # write xml output file - write_xml_output - end -end - -# If the command line has no values in, used a default value of Output.txt -parse_my_file = ParseOutput.new - -if ARGV.size >= 1 - ARGV.each do |arg| - if arg == '-xml' - parse_my_file.set_xml_output - else - parse_my_file.process(arg) - break - end - end -end diff --git a/test/unit-test/vendor/ceedling/vendor/unity/auto/run_test.erb b/test/unit-test/vendor/ceedling/vendor/unity/auto/run_test.erb deleted file mode 100644 index f91b56691..000000000 --- a/test/unit-test/vendor/ceedling/vendor/unity/auto/run_test.erb +++ /dev/null @@ -1,37 +0,0 @@ -/*=======Test Runner Used To Run Each Test=====*/ -static void run_test(UnityTestFunction func, const char* name, UNITY_LINE_TYPE line_num) -{ - Unity.CurrentTestName = name; - Unity.CurrentTestLineNumber = line_num; -#ifdef UNITY_USE_COMMAND_LINE_ARGS - if (!UnityTestMatches()) - return; -#endif - Unity.NumberOfTests++; - UNITY_CLR_DETAILS(); - UNITY_EXEC_TIME_START(); - CMock_Init(); - if (TEST_PROTECT()) - { -<% if @options[:plugins].include?(:cexception) %> - CEXCEPTION_T e; - Try { - <%= @options[:setup_name] %>(); - func(); - } Catch(e) { - TEST_ASSERT_EQUAL_HEX32_MESSAGE(CEXCEPTION_NONE, e, "Unhandled Exception!"); - } -<% else %> - <%= @options[:setup_name] %>(); - func(); -<% end %> - } - if (TEST_PROTECT()) - { - <%= @options[:teardown_name] %>(); - CMock_Verify(); - } - CMock_Destroy(); - UNITY_EXEC_TIME_STOP(); - UnityConcludeTest(); -} diff --git a/test/unit-test/vendor/ceedling/vendor/unity/auto/stylize_as_junit.rb b/test/unit-test/vendor/ceedling/vendor/unity/auto/stylize_as_junit.rb deleted file mode 100644 index e01f7912a..000000000 --- a/test/unit-test/vendor/ceedling/vendor/unity/auto/stylize_as_junit.rb +++ /dev/null @@ -1,251 +0,0 @@ -#!/usr/bin/ruby -# -# unity_to_junit.rb -# -require 'fileutils' -require 'optparse' -require 'ostruct' -require 'set' - -require 'pp' - -VERSION = 1.0 - -class ArgvParser - # - # Return a structure describing the options. - # - def self.parse(args) - # The options specified on the command line will be collected in *options*. - # We set default values here. - options = OpenStruct.new - options.results_dir = '.' - options.root_path = '.' - options.out_file = 'results.xml' - - opts = OptionParser.new do |o| - o.banner = 'Usage: unity_to_junit.rb [options]' - - o.separator '' - o.separator 'Specific options:' - - o.on('-r', '--results <dir>', 'Look for Unity Results files here.') do |results| - # puts "results #{results}" - options.results_dir = results - end - - o.on('-p', '--root_path <path>', 'Prepend this path to files in results.') do |root_path| - options.root_path = root_path - end - - o.on('-o', '--output <filename>', 'XML file to generate.') do |out_file| - # puts "out_file: #{out_file}" - options.out_file = out_file - end - - o.separator '' - o.separator 'Common options:' - - # No argument, shows at tail. This will print an options summary. - o.on_tail('-h', '--help', 'Show this message') do - puts o - exit - end - - # Another typical switch to print the version. - o.on_tail('--version', 'Show version') do - puts "unity_to_junit.rb version #{VERSION}" - exit - end - end - - opts.parse!(args) - options - end -end - -class UnityToJUnit - include FileUtils::Verbose - attr_reader :report, :total_tests, :failures, :ignored - attr_writer :targets, :root, :out_file - - def initialize - @report = '' - @unit_name = '' - end - - def run - # Clean up result file names - results = @targets.map { |target| target.tr('\\', '/') } - # puts "Output File: #{@out_file}" - f = File.new(@out_file, 'w') - write_xml_header(f) - write_suites_header(f) - results.each do |result_file| - lines = File.readlines(result_file).map(&:chomp) - - raise "Empty test result file: #{result_file}" if lines.empty? - - result_output = get_details(result_file, lines) - tests, failures, ignored = parse_test_summary(lines) - result_output[:counts][:total] = tests - result_output[:counts][:failed] = failures - result_output[:counts][:ignored] = ignored - result_output[:counts][:passed] = (result_output[:counts][:total] - result_output[:counts][:failed] - result_output[:counts][:ignored]) - - # use line[0] from the test output to get the test_file path and name - test_file_str = lines[0].tr('\\', '/') - test_file_str = test_file_str.split(':') - test_file = if test_file_str.length < 2 - result_file - else - test_file_str[0] + ':' + test_file_str[1] - end - result_output[:source][:path] = File.dirname(test_file) - result_output[:source][:file] = File.basename(test_file) - - # save result_output - @unit_name = File.basename(test_file, '.*') - - write_suite_header(result_output[:counts], f) - write_failures(result_output, f) - write_tests(result_output, f) - write_ignored(result_output, f) - write_suite_footer(f) - end - write_suites_footer(f) - f.close - end - - def usage(err_msg = nil) - puts "\nERROR: " - puts err_msg if err_msg - puts 'Usage: unity_to_junit.rb [options]' - puts '' - puts 'Specific options:' - puts ' -r, --results <dir> Look for Unity Results files here.' - puts ' -p, --root_path <path> Prepend this path to files in results.' - puts ' -o, --output <filename> XML file to generate.' - puts '' - puts 'Common options:' - puts ' -h, --help Show this message' - puts ' --version Show version' - - exit 1 - end - - protected - - def get_details(_result_file, lines) - results = results_structure - lines.each do |line| - line = line.tr('\\', '/') - _src_file, src_line, test_name, status, msg = line.split(/:/) - case status - when 'IGNORE' then results[:ignores] << { test: test_name, line: src_line, message: msg } - when 'FAIL' then results[:failures] << { test: test_name, line: src_line, message: msg } - when 'PASS' then results[:successes] << { test: test_name, line: src_line, message: msg } - end - end - results - end - - def parse_test_summary(summary) - raise "Couldn't parse test results: #{summary}" unless summary.find { |v| v =~ /(\d+) Tests (\d+) Failures (\d+) Ignored/ } - - [Regexp.last_match(1).to_i, Regexp.last_match(2).to_i, Regexp.last_match(3).to_i] - end - - private - - def results_structure - { - source: { path: '', file: '' }, - successes: [], - failures: [], - ignores: [], - counts: { total: 0, passed: 0, failed: 0, ignored: 0 }, - stdout: [] - } - end - - def write_xml_header(stream) - stream.puts "<?xml version='1.0' encoding='utf-8' ?>" - end - - def write_suites_header(stream) - stream.puts '<testsuites>' - end - - def write_suite_header(counts, stream) - stream.puts "\t<testsuite errors=\"0\" skipped=\"#{counts[:ignored]}\" failures=\"#{counts[:failed]}\" tests=\"#{counts[:total]}\" name=\"unity\">" - end - - def write_failures(results, stream) - result = results[:failures] - result.each do |item| - filename = File.join(results[:source][:path], File.basename(results[:source][:file], '.*')) - stream.puts "\t\t<testcase classname=\"#{@unit_name}\" name=\"#{item[:test]}\" time=\"0\">" - stream.puts "\t\t\t<failure message=\"#{item[:message]}\" type=\"Assertion\"/>" - stream.puts "\t\t\t<system-err> [File] #{filename} [Line] #{item[:line]} </system-err>" - stream.puts "\t\t</testcase>" - end - end - - def write_tests(results, stream) - result = results[:successes] - result.each do |item| - stream.puts "\t\t<testcase classname=\"#{@unit_name}\" name=\"#{item[:test]}\" time=\"0\" />" - end - end - - def write_ignored(results, stream) - result = results[:ignores] - result.each do |item| - filename = File.join(results[:source][:path], File.basename(results[:source][:file], '.*')) - puts "Writing ignored tests for test harness: #{filename}" - stream.puts "\t\t<testcase classname=\"#{@unit_name}\" name=\"#{item[:test]}\" time=\"0\">" - stream.puts "\t\t\t<skipped message=\"#{item[:message]}\" type=\"Assertion\"/>" - stream.puts "\t\t\t<system-err> [File] #{filename} [Line] #{item[:line]} </system-err>" - stream.puts "\t\t</testcase>" - end - end - - def write_suite_footer(stream) - stream.puts "\t</testsuite>" - end - - def write_suites_footer(stream) - stream.puts '</testsuites>' - end -end - -if $0 == __FILE__ - # parse out the command options - options = ArgvParser.parse(ARGV) - - # create an instance to work with - utj = UnityToJUnit.new - begin - # look in the specified or current directory for result files - targets = "#{options.results_dir.tr('\\', '/')}**/*.test*" - - results = Dir[targets] - - raise "No *.testpass, *.testfail, or *.testresults files found in '#{targets}'" if results.empty? - - utj.targets = results - - # set the root path - utj.root = options.root_path - - # set the output XML file name - # puts "Output File from options: #{options.out_file}" - utj.out_file = options.out_file - - # run the summarizer - puts utj.run - rescue StandardError => e - utj.usage e.message - end -end diff --git a/test/unit-test/vendor/ceedling/vendor/unity/auto/test_file_filter.rb b/test/unit-test/vendor/ceedling/vendor/unity/auto/test_file_filter.rb deleted file mode 100644 index 5c3a79fc6..000000000 --- a/test/unit-test/vendor/ceedling/vendor/unity/auto/test_file_filter.rb +++ /dev/null @@ -1,25 +0,0 @@ -# ========================================== -# Unity Project - A Test Framework for C -# Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams -# [Released under MIT License. Please refer to license.txt for details] -# ========================================== - -require'yaml' - -module RakefileHelpers - class TestFileFilter - def initialize(all_files = false) - @all_files = all_files - - return unless @all_files - return unless File.exist?('test_file_filter.yml') - - filters = YAML.load_file('test_file_filter.yml') - @all_files = filters[:all_files] - @only_files = filters[:only_files] - @exclude_files = filters[:exclude_files] - end - - attr_accessor :all_files, :only_files, :exclude_files - end -end diff --git a/test/unit-test/vendor/ceedling/vendor/unity/auto/type_sanitizer.rb b/test/unit-test/vendor/ceedling/vendor/unity/auto/type_sanitizer.rb deleted file mode 100644 index dafb8826e..000000000 --- a/test/unit-test/vendor/ceedling/vendor/unity/auto/type_sanitizer.rb +++ /dev/null @@ -1,6 +0,0 @@ -module TypeSanitizer - def self.sanitize_c_identifier(unsanitized) - # convert filename to valid C identifier by replacing invalid chars with '_' - unsanitized.gsub(/[-\/\\\.\,\s]/, '_') - end -end diff --git a/test/unit-test/vendor/ceedling/vendor/unity/auto/unity_test_summary.py b/test/unit-test/vendor/ceedling/vendor/unity/auto/unity_test_summary.py deleted file mode 100755 index a8e5b2726..000000000 --- a/test/unit-test/vendor/ceedling/vendor/unity/auto/unity_test_summary.py +++ /dev/null @@ -1,139 +0,0 @@ -#!/usr/bin/env python3 -# ========================================== -# Unity Project - A Test Framework for C -# Copyright (c) 2015 Alexander Mueller / XelaRellum@web.de -# [Released under MIT License. Please refer to license.txt for details] -# Based on the ruby script by Mike Karlesky, Mark VanderVoord, Greg Williams -# ========================================== -import sys -import os -import re -from glob import glob - -class UnityTestSummary: - def __init__(self): - self.report = '' - self.total_tests = 0 - self.failures = 0 - self.ignored = 0 - - def run(self): - # Clean up result file names - results = [] - for target in self.targets: - results.append(target.replace('\\', '/')) - - # Dig through each result file, looking for details on pass/fail: - failure_output = [] - ignore_output = [] - - for result_file in results: - lines = list(map(lambda line: line.rstrip(), open(result_file, "r").read().split('\n'))) - if len(lines) == 0: - raise Exception("Empty test result file: %s" % result_file) - - details = self.get_details(result_file, lines) - failures = details['failures'] - ignores = details['ignores'] - if len(failures) > 0: failure_output.append('\n'.join(failures)) - if len(ignores) > 0: ignore_output.append('n'.join(ignores)) - tests,failures,ignored = self.parse_test_summary('\n'.join(lines)) - self.total_tests += tests - self.failures += failures - self.ignored += ignored - - if self.ignored > 0: - self.report += "\n" - self.report += "--------------------------\n" - self.report += "UNITY IGNORED TEST SUMMARY\n" - self.report += "--------------------------\n" - self.report += "\n".join(ignore_output) - - if self.failures > 0: - self.report += "\n" - self.report += "--------------------------\n" - self.report += "UNITY FAILED TEST SUMMARY\n" - self.report += "--------------------------\n" - self.report += '\n'.join(failure_output) - - self.report += "\n" - self.report += "--------------------------\n" - self.report += "OVERALL UNITY TEST SUMMARY\n" - self.report += "--------------------------\n" - self.report += "{total_tests} TOTAL TESTS {failures} TOTAL FAILURES {ignored} IGNORED\n".format(total_tests = self.total_tests, failures=self.failures, ignored=self.ignored) - self.report += "\n" - - return self.report - - def set_targets(self, target_array): - self.targets = target_array - - def set_root_path(self, path): - self.root = path - - def usage(self, err_msg=None): - print("\nERROR: ") - if err_msg: - print(err_msg) - print("\nUsage: unity_test_summary.py result_file_directory/ root_path/") - print(" result_file_directory - The location of your results files.") - print(" Defaults to current directory if not specified.") - print(" Should end in / if specified.") - print(" root_path - Helpful for producing more verbose output if using relative paths.") - sys.exit(1) - - def get_details(self, result_file, lines): - results = { 'failures': [], 'ignores': [], 'successes': [] } - for line in lines: - parts = line.split(':') - if len(parts) == 5: - src_file,src_line,test_name,status,msg = parts - elif len(parts) == 4: - src_file,src_line,test_name,status = parts - msg = '' - else: - continue - if len(self.root) > 0: - line_out = "%s%s" % (self.root, line) - else: - line_out = line - if status == 'IGNORE': - results['ignores'].append(line_out) - elif status == 'FAIL': - results['failures'].append(line_out) - elif status == 'PASS': - results['successes'].append(line_out) - return results - - def parse_test_summary(self, summary): - m = re.search(r"([0-9]+) Tests ([0-9]+) Failures ([0-9]+) Ignored", summary) - if not m: - raise Exception("Couldn't parse test results: %s" % summary) - - return int(m.group(1)), int(m.group(2)), int(m.group(3)) - - -if __name__ == '__main__': - uts = UnityTestSummary() - try: - #look in the specified or current directory for result files - if len(sys.argv) > 1: - targets_dir = sys.argv[1] - else: - targets_dir = './' - targets = list(map(lambda x: x.replace('\\', '/'), glob(targets_dir + '**/*.test*', recursive=True))) - if len(targets) == 0: - raise Exception("No *.testpass or *.testfail files found in '%s'" % targets_dir) - uts.set_targets(targets) - - #set the root path - if len(sys.argv) > 2: - root_path = sys.argv[2] - else: - root_path = os.path.split(__file__)[0] - uts.set_root_path(root_path) - - #run the summarizer - print(uts.run()) - except Exception as e: - uts.usage(e) diff --git a/test/unit-test/vendor/ceedling/vendor/unity/auto/unity_test_summary.rb b/test/unit-test/vendor/ceedling/vendor/unity/auto/unity_test_summary.rb deleted file mode 100644 index b3fe8a699..000000000 --- a/test/unit-test/vendor/ceedling/vendor/unity/auto/unity_test_summary.rb +++ /dev/null @@ -1,135 +0,0 @@ -# ========================================== -# Unity Project - A Test Framework for C -# Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams -# [Released under MIT License. Please refer to license.txt for details] -# ========================================== - -# !/usr/bin/ruby -# -# unity_test_summary.rb -# -require 'fileutils' -require 'set' - -class UnityTestSummary - include FileUtils::Verbose - - attr_reader :report, :total_tests, :failures, :ignored - attr_writer :targets, :root - - def initialize(_opts = {}) - @report = '' - @total_tests = 0 - @failures = 0 - @ignored = 0 - end - - def run - # Clean up result file names - results = @targets.map { |target| target.tr('\\', '/') } - - # Dig through each result file, looking for details on pass/fail: - failure_output = [] - ignore_output = [] - - results.each do |result_file| - lines = File.readlines(result_file).map(&:chomp) - - raise "Empty test result file: #{result_file}" if lines.empty? - - output = get_details(result_file, lines) - failure_output << output[:failures] unless output[:failures].empty? - ignore_output << output[:ignores] unless output[:ignores].empty? - tests, failures, ignored = parse_test_summary(lines) - @total_tests += tests - @failures += failures - @ignored += ignored - end - - if @ignored > 0 - @report += "\n" - @report += "--------------------------\n" - @report += "UNITY IGNORED TEST SUMMARY\n" - @report += "--------------------------\n" - @report += ignore_output.flatten.join("\n") - end - - if @failures > 0 - @report += "\n" - @report += "--------------------------\n" - @report += "UNITY FAILED TEST SUMMARY\n" - @report += "--------------------------\n" - @report += failure_output.flatten.join("\n") - end - - @report += "\n" - @report += "--------------------------\n" - @report += "OVERALL UNITY TEST SUMMARY\n" - @report += "--------------------------\n" - @report += "#{@total_tests} TOTAL TESTS #{@failures} TOTAL FAILURES #{@ignored} IGNORED\n" - @report += "\n" - end - - def usage(err_msg = nil) - puts "\nERROR: " - puts err_msg if err_msg - puts "\nUsage: unity_test_summary.rb result_file_directory/ root_path/" - puts ' result_file_directory - The location of your results files.' - puts ' Defaults to current directory if not specified.' - puts ' Should end in / if specified.' - puts ' root_path - Helpful for producing more verbose output if using relative paths.' - exit 1 - end - - protected - - def get_details(_result_file, lines) - results = { failures: [], ignores: [], successes: [] } - lines.each do |line| - _src_file, _src_line, _test_name, status, _msg = line.split(/:/) - line_out = (@root && (@root != 0) ? "#{@root}#{line}" : line).gsub(/\//, '\\') - case status - when 'IGNORE' then results[:ignores] << line_out - when 'FAIL' then results[:failures] << line_out - when 'PASS' then results[:successes] << line_out - end - end - results - end - - def parse_test_summary(summary) - raise "Couldn't parse test results: #{summary}" unless summary.find { |v| v =~ /(\d+) Tests (\d+) Failures (\d+) Ignored/ } - - [Regexp.last_match(1).to_i, Regexp.last_match(2).to_i, Regexp.last_match(3).to_i] - end -end - -if $0 == __FILE__ - - # parse out the command options - opts, args = ARGV.partition { |v| v =~ /^--\w+/ } - opts.map! { |v| v[2..-1].to_sym } - - # create an instance to work with - uts = UnityTestSummary.new(opts) - - begin - # look in the specified or current directory for result files - args[0] ||= './' - targets = "#{ARGV[0].tr('\\', '/')}**/*.test*" - results = Dir[targets] - - raise "No *.testpass, *.testfail, or *.testresults files found in '#{targets}'" if results.empty? - - uts.targets = results - - # set the root path - args[1] ||= Dir.pwd + '/' - uts.root = ARGV[1] - - # run the summarizer - puts uts.run - rescue StandardError => e - uts.usage e.message - end -end diff --git a/test/unit-test/vendor/ceedling/vendor/unity/auto/unity_to_junit.py b/test/unit-test/vendor/ceedling/vendor/unity/auto/unity_to_junit.py deleted file mode 100755 index 2379ad49a..000000000 --- a/test/unit-test/vendor/ceedling/vendor/unity/auto/unity_to_junit.py +++ /dev/null @@ -1,147 +0,0 @@ -#!/usr/bin/env python3 -import sys -import os -from glob import glob - -from pyparsing import * -from junit_xml import TestSuite, TestCase - - -class UnityTestSummary: - def __init__(self): - self.report = '' - self.total_tests = 0 - self.failures = 0 - self.ignored = 0 - self.targets = 0 - self.root = None - self.test_suites = dict() - - def run(self): - # Clean up result file names - results = [] - for target in self.targets: - results.append(target.replace('\\', '/')) - - # Dig through each result file, looking for details on pass/fail: - for result_file in results: - lines = list(map(lambda line: line.rstrip(), open(result_file, "r").read().split('\n'))) - if len(lines) == 0: - raise Exception("Empty test result file: %s" % result_file) - - # define an expression for your file reference - entry_one = Combine( - oneOf(list(alphas)) + ':/' + - Word(alphanums + '_-./')) - - entry_two = Word(printables + ' ', excludeChars=':') - entry = entry_one | entry_two - - delimiter = Literal(':').suppress() - tc_result_line = Group(entry.setResultsName('tc_file_name') + delimiter + entry.setResultsName( - 'tc_line_nr') + delimiter + entry.setResultsName('tc_name') + delimiter + entry.setResultsName( - 'tc_status') + Optional( - delimiter + entry.setResultsName('tc_msg'))).setResultsName("tc_line") - - eol = LineEnd().suppress() - sol = LineStart().suppress() - blank_line = sol + eol - - tc_summary_line = Group(Word(nums).setResultsName("num_of_tests") + "Tests" + Word(nums).setResultsName( - "num_of_fail") + "Failures" + Word(nums).setResultsName("num_of_ignore") + "Ignored").setResultsName( - "tc_summary") - tc_end_line = Or(Literal("FAIL"), Literal('Ok')).setResultsName("tc_result") - - # run it and see... - pp1 = tc_result_line | Optional(tc_summary_line | tc_end_line) - pp1.ignore(blank_line | OneOrMore("-")) - - result = list() - for l in lines: - result.append((pp1.parseString(l)).asDict()) - # delete empty results - result = filter(None, result) - - tc_list = list() - for r in result: - if 'tc_line' in r: - tmp_tc_line = r['tc_line'] - - # get only the file name which will be used as the classname - file_name = tmp_tc_line['tc_file_name'].split('\\').pop().split('/').pop().rsplit('.', 1)[0] - tmp_tc = TestCase(name=tmp_tc_line['tc_name'], classname=file_name) - if 'tc_status' in tmp_tc_line: - if str(tmp_tc_line['tc_status']) == 'IGNORE': - if 'tc_msg' in tmp_tc_line: - tmp_tc.add_skipped_info(message=tmp_tc_line['tc_msg'], - output=r'[File]={0}, [Line]={1}'.format( - tmp_tc_line['tc_file_name'], tmp_tc_line['tc_line_nr'])) - else: - tmp_tc.add_skipped_info(message=" ") - elif str(tmp_tc_line['tc_status']) == 'FAIL': - if 'tc_msg' in tmp_tc_line: - tmp_tc.add_failure_info(message=tmp_tc_line['tc_msg'], - output=r'[File]={0}, [Line]={1}'.format( - tmp_tc_line['tc_file_name'], tmp_tc_line['tc_line_nr'])) - else: - tmp_tc.add_failure_info(message=" ") - - tc_list.append((str(result_file), tmp_tc)) - - for k, v in tc_list: - try: - self.test_suites[k].append(v) - except KeyError: - self.test_suites[k] = [v] - ts = [] - for suite_name in self.test_suites: - ts.append(TestSuite(suite_name, self.test_suites[suite_name])) - - with open('result.xml', 'w') as f: - TestSuite.to_file(f, ts, prettyprint='True', encoding='utf-8') - - return self.report - - def set_targets(self, target_array): - self.targets = target_array - - def set_root_path(self, path): - self.root = path - - @staticmethod - def usage(err_msg=None): - print("\nERROR: ") - if err_msg: - print(err_msg) - print("\nUsage: unity_test_summary.py result_file_directory/ root_path/") - print(" result_file_directory - The location of your results files.") - print(" Defaults to current directory if not specified.") - print(" Should end in / if specified.") - print(" root_path - Helpful for producing more verbose output if using relative paths.") - sys.exit(1) - - -if __name__ == '__main__': - uts = UnityTestSummary() - try: - # look in the specified or current directory for result files - if len(sys.argv) > 1: - targets_dir = sys.argv[1] - else: - targets_dir = './' - targets = list(map(lambda x: x.replace('\\', '/'), glob(targets_dir + '*.test*'))) - if len(targets) == 0: - raise Exception("No *.testpass or *.testfail files found in '%s'" % targets_dir) - uts.set_targets(targets) - - # set the root path - if len(sys.argv) > 2: - root_path = sys.argv[2] - else: - root_path = os.path.split(__file__)[0] - uts.set_root_path(root_path) - - # run the summarizer - print(uts.run()) - except Exception as e: - UnityTestSummary.usage(e) diff --git a/test/unit-test/vendor/ceedling/vendor/unity/src/meson.build b/test/unit-test/vendor/ceedling/vendor/unity/src/meson.build deleted file mode 100644 index 5acd51a9b..000000000 --- a/test/unit-test/vendor/ceedling/vendor/unity/src/meson.build +++ /dev/null @@ -1,11 +0,0 @@ -# -# build script written by : Michael Brockus. -# github repo author: Mike Karlesky, Mark VanderVoord, Greg Williams. -# -# license: MIT -# -unity_dir = include_directories('.') - -unity_lib = static_library(meson.project_name(), - files('unity.c'), - include_directories: unity_dir) diff --git a/test/unit-test/vendor/ceedling/vendor/unity/src/unity.c b/test/unit-test/vendor/ceedling/vendor/unity/src/unity.c deleted file mode 100644 index ae5afa856..000000000 --- a/test/unit-test/vendor/ceedling/vendor/unity/src/unity.c +++ /dev/null @@ -1,2110 +0,0 @@ -/* ========================================================================= - Unity Project - A Test Framework for C - Copyright (c) 2007-21 Mike Karlesky, Mark VanderVoord, Greg Williams - [Released under MIT License. Please refer to license.txt for details] -============================================================================ */ - -#include "unity.h" -#include <stddef.h> - -#ifdef AVR -#include <avr/pgmspace.h> -#else -#define PROGMEM -#endif - -/* If omitted from header, declare overridable prototypes here so they're ready for use */ -#ifdef UNITY_OMIT_OUTPUT_CHAR_HEADER_DECLARATION -void UNITY_OUTPUT_CHAR(int); -#endif - -/* Helpful macros for us to use here in Assert functions */ -#define UNITY_FAIL_AND_BAIL { Unity.CurrentTestFailed = 1; UNITY_OUTPUT_FLUSH(); TEST_ABORT(); } -#define UNITY_IGNORE_AND_BAIL { Unity.CurrentTestIgnored = 1; UNITY_OUTPUT_FLUSH(); TEST_ABORT(); } -#define RETURN_IF_FAIL_OR_IGNORE if (Unity.CurrentTestFailed || Unity.CurrentTestIgnored) TEST_ABORT() - -struct UNITY_STORAGE_T Unity; - -#ifdef UNITY_OUTPUT_COLOR -const char PROGMEM UnityStrOk[] = "\033[42mOK\033[00m"; -const char PROGMEM UnityStrPass[] = "\033[42mPASS\033[00m"; -const char PROGMEM UnityStrFail[] = "\033[41mFAIL\033[00m"; -const char PROGMEM UnityStrIgnore[] = "\033[43mIGNORE\033[00m"; -#else -const char PROGMEM UnityStrOk[] = "OK"; -const char PROGMEM UnityStrPass[] = "PASS"; -const char PROGMEM UnityStrFail[] = "FAIL"; -const char PROGMEM UnityStrIgnore[] = "IGNORE"; -#endif -static const char PROGMEM UnityStrNull[] = "NULL"; -static const char PROGMEM UnityStrSpacer[] = ". "; -static const char PROGMEM UnityStrExpected[] = " Expected "; -static const char PROGMEM UnityStrWas[] = " Was "; -static const char PROGMEM UnityStrGt[] = " to be greater than "; -static const char PROGMEM UnityStrLt[] = " to be less than "; -static const char PROGMEM UnityStrOrEqual[] = "or equal to "; -static const char PROGMEM UnityStrNotEqual[] = " to be not equal to "; -static const char PROGMEM UnityStrElement[] = " Element "; -static const char PROGMEM UnityStrByte[] = " Byte "; -static const char PROGMEM UnityStrMemory[] = " Memory Mismatch."; -static const char PROGMEM UnityStrDelta[] = " Values Not Within Delta "; -static const char PROGMEM UnityStrPointless[] = " You Asked Me To Compare Nothing, Which Was Pointless."; -static const char PROGMEM UnityStrNullPointerForExpected[] = " Expected pointer to be NULL"; -static const char PROGMEM UnityStrNullPointerForActual[] = " Actual pointer was NULL"; -#ifndef UNITY_EXCLUDE_FLOAT -static const char PROGMEM UnityStrNot[] = "Not "; -static const char PROGMEM UnityStrInf[] = "Infinity"; -static const char PROGMEM UnityStrNegInf[] = "Negative Infinity"; -static const char PROGMEM UnityStrNaN[] = "NaN"; -static const char PROGMEM UnityStrDet[] = "Determinate"; -static const char PROGMEM UnityStrInvalidFloatTrait[] = "Invalid Float Trait"; -#endif -const char PROGMEM UnityStrErrShorthand[] = "Unity Shorthand Support Disabled"; -const char PROGMEM UnityStrErrFloat[] = "Unity Floating Point Disabled"; -const char PROGMEM UnityStrErrDouble[] = "Unity Double Precision Disabled"; -const char PROGMEM UnityStrErr64[] = "Unity 64-bit Support Disabled"; -static const char PROGMEM UnityStrBreaker[] = "-----------------------"; -static const char PROGMEM UnityStrResultsTests[] = " Tests "; -static const char PROGMEM UnityStrResultsFailures[] = " Failures "; -static const char PROGMEM UnityStrResultsIgnored[] = " Ignored "; -#ifndef UNITY_EXCLUDE_DETAILS -static const char PROGMEM UnityStrDetail1Name[] = UNITY_DETAIL1_NAME " "; -static const char PROGMEM UnityStrDetail2Name[] = " " UNITY_DETAIL2_NAME " "; -#endif -/*----------------------------------------------- - * Pretty Printers & Test Result Output Handlers - *-----------------------------------------------*/ - -/*-----------------------------------------------*/ -/* Local helper function to print characters. */ -static void UnityPrintChar(const char* pch) -{ - /* printable characters plus CR & LF are printed */ - if ((*pch <= 126) && (*pch >= 32)) - { - UNITY_OUTPUT_CHAR(*pch); - } - /* write escaped carriage returns */ - else if (*pch == 13) - { - UNITY_OUTPUT_CHAR('\\'); - UNITY_OUTPUT_CHAR('r'); - } - /* write escaped line feeds */ - else if (*pch == 10) - { - UNITY_OUTPUT_CHAR('\\'); - UNITY_OUTPUT_CHAR('n'); - } - /* unprintable characters are shown as codes */ - else - { - UNITY_OUTPUT_CHAR('\\'); - UNITY_OUTPUT_CHAR('x'); - UnityPrintNumberHex((UNITY_UINT)*pch, 2); - } -} - -/*-----------------------------------------------*/ -/* Local helper function to print ANSI escape strings e.g. "\033[42m". */ -#ifdef UNITY_OUTPUT_COLOR -static UNITY_UINT UnityPrintAnsiEscapeString(const char* string) -{ - const char* pch = string; - UNITY_UINT count = 0; - - while (*pch && (*pch != 'm')) - { - UNITY_OUTPUT_CHAR(*pch); - pch++; - count++; - } - UNITY_OUTPUT_CHAR('m'); - count++; - - return count; -} -#endif - -/*-----------------------------------------------*/ -void UnityPrint(const char* string) -{ - const char* pch = string; - - if (pch != NULL) - { - while (*pch) - { -#ifdef UNITY_OUTPUT_COLOR - /* print ANSI escape code */ - if ((*pch == 27) && (*(pch + 1) == '[')) - { - pch += UnityPrintAnsiEscapeString(pch); - continue; - } -#endif - UnityPrintChar(pch); - pch++; - } - } -} -/*-----------------------------------------------*/ -void UnityPrintLen(const char* string, const UNITY_UINT32 length) -{ - const char* pch = string; - - if (pch != NULL) - { - while (*pch && ((UNITY_UINT32)(pch - string) < length)) - { - /* printable characters plus CR & LF are printed */ - if ((*pch <= 126) && (*pch >= 32)) - { - UNITY_OUTPUT_CHAR(*pch); - } - /* write escaped carriage returns */ - else if (*pch == 13) - { - UNITY_OUTPUT_CHAR('\\'); - UNITY_OUTPUT_CHAR('r'); - } - /* write escaped line feeds */ - else if (*pch == 10) - { - UNITY_OUTPUT_CHAR('\\'); - UNITY_OUTPUT_CHAR('n'); - } - /* unprintable characters are shown as codes */ - else - { - UNITY_OUTPUT_CHAR('\\'); - UNITY_OUTPUT_CHAR('x'); - UnityPrintNumberHex((UNITY_UINT)*pch, 2); - } - pch++; - } - } -} - -/*-----------------------------------------------*/ -void UnityPrintNumberByStyle(const UNITY_INT number, const UNITY_DISPLAY_STYLE_T style) -{ - if ((style & UNITY_DISPLAY_RANGE_INT) == UNITY_DISPLAY_RANGE_INT) - { - if (style == UNITY_DISPLAY_STYLE_CHAR) - { - /* printable characters plus CR & LF are printed */ - UNITY_OUTPUT_CHAR('\''); - if ((number <= 126) && (number >= 32)) - { - UNITY_OUTPUT_CHAR((int)number); - } - /* write escaped carriage returns */ - else if (number == 13) - { - UNITY_OUTPUT_CHAR('\\'); - UNITY_OUTPUT_CHAR('r'); - } - /* write escaped line feeds */ - else if (number == 10) - { - UNITY_OUTPUT_CHAR('\\'); - UNITY_OUTPUT_CHAR('n'); - } - /* unprintable characters are shown as codes */ - else - { - UNITY_OUTPUT_CHAR('\\'); - UNITY_OUTPUT_CHAR('x'); - UnityPrintNumberHex((UNITY_UINT)number, 2); - } - UNITY_OUTPUT_CHAR('\''); - } - else - { - UnityPrintNumber(number); - } - } - else if ((style & UNITY_DISPLAY_RANGE_UINT) == UNITY_DISPLAY_RANGE_UINT) - { - UnityPrintNumberUnsigned((UNITY_UINT)number); - } - else - { - UNITY_OUTPUT_CHAR('0'); - UNITY_OUTPUT_CHAR('x'); - UnityPrintNumberHex((UNITY_UINT)number, (char)((style & 0xF) * 2)); - } -} - -/*-----------------------------------------------*/ -void UnityPrintNumber(const UNITY_INT number_to_print) -{ - UNITY_UINT number = (UNITY_UINT)number_to_print; - - if (number_to_print < 0) - { - /* A negative number, including MIN negative */ - UNITY_OUTPUT_CHAR('-'); - number = (~number) + 1; - } - UnityPrintNumberUnsigned(number); -} - -/*----------------------------------------------- - * basically do an itoa using as little ram as possible */ -void UnityPrintNumberUnsigned(const UNITY_UINT number) -{ - UNITY_UINT divisor = 1; - - /* figure out initial divisor */ - while (number / divisor > 9) - { - divisor *= 10; - } - - /* now mod and print, then divide divisor */ - do - { - UNITY_OUTPUT_CHAR((char)('0' + (number / divisor % 10))); - divisor /= 10; - } while (divisor > 0); -} - -/*-----------------------------------------------*/ -void UnityPrintNumberHex(const UNITY_UINT number, const char nibbles_to_print) -{ - int nibble; - char nibbles = nibbles_to_print; - - if ((unsigned)nibbles > UNITY_MAX_NIBBLES) - { - nibbles = UNITY_MAX_NIBBLES; - } - - while (nibbles > 0) - { - nibbles--; - nibble = (int)(number >> (nibbles * 4)) & 0x0F; - if (nibble <= 9) - { - UNITY_OUTPUT_CHAR((char)('0' + nibble)); - } - else - { - UNITY_OUTPUT_CHAR((char)('A' - 10 + nibble)); - } - } -} - -/*-----------------------------------------------*/ -void UnityPrintMask(const UNITY_UINT mask, const UNITY_UINT number) -{ - UNITY_UINT current_bit = (UNITY_UINT)1 << (UNITY_INT_WIDTH - 1); - UNITY_INT32 i; - - for (i = 0; i < UNITY_INT_WIDTH; i++) - { - if (current_bit & mask) - { - if (current_bit & number) - { - UNITY_OUTPUT_CHAR('1'); - } - else - { - UNITY_OUTPUT_CHAR('0'); - } - } - else - { - UNITY_OUTPUT_CHAR('X'); - } - current_bit = current_bit >> 1; - } -} - -/*-----------------------------------------------*/ -#ifndef UNITY_EXCLUDE_FLOAT_PRINT -/* - * This function prints a floating-point value in a format similar to - * printf("%.7g") on a single-precision machine or printf("%.9g") on a - * double-precision machine. The 7th digit won't always be totally correct - * in single-precision operation (for that level of accuracy, a more - * complicated algorithm would be needed). - */ -void UnityPrintFloat(const UNITY_DOUBLE input_number) -{ -#ifdef UNITY_INCLUDE_DOUBLE - static const int sig_digits = 9; - static const UNITY_INT32 min_scaled = 100000000; - static const UNITY_INT32 max_scaled = 1000000000; -#else - static const int sig_digits = 7; - static const UNITY_INT32 min_scaled = 1000000; - static const UNITY_INT32 max_scaled = 10000000; -#endif - - UNITY_DOUBLE number = input_number; - - /* print minus sign (does not handle negative zero) */ - if (number < 0.0f) - { - UNITY_OUTPUT_CHAR('-'); - number = -number; - } - - /* handle zero, NaN, and +/- infinity */ - if (number == 0.0f) - { - UnityPrint("0"); - } - else if (isnan(number)) - { - UnityPrint("nan"); - } - else if (isinf(number)) - { - UnityPrint("inf"); - } - else - { - UNITY_INT32 n_int = 0, n; - int exponent = 0; - int decimals, digits; - char buf[16] = {0}; - - /* - * Scale up or down by powers of 10. To minimize rounding error, - * start with a factor/divisor of 10^10, which is the largest - * power of 10 that can be represented exactly. Finally, compute - * (exactly) the remaining power of 10 and perform one more - * multiplication or division. - */ - if (number < 1.0f) - { - UNITY_DOUBLE factor = 1.0f; - - while (number < (UNITY_DOUBLE)max_scaled / 1e10f) { number *= 1e10f; exponent -= 10; } - while (number * factor < (UNITY_DOUBLE)min_scaled) { factor *= 10.0f; exponent--; } - - number *= factor; - } - else if (number > (UNITY_DOUBLE)max_scaled) - { - UNITY_DOUBLE divisor = 1.0f; - - while (number > (UNITY_DOUBLE)min_scaled * 1e10f) { number /= 1e10f; exponent += 10; } - while (number / divisor > (UNITY_DOUBLE)max_scaled) { divisor *= 10.0f; exponent++; } - - number /= divisor; - } - else - { - /* - * In this range, we can split off the integer part before - * doing any multiplications. This reduces rounding error by - * freeing up significant bits in the fractional part. - */ - UNITY_DOUBLE factor = 1.0f; - n_int = (UNITY_INT32)number; - number -= (UNITY_DOUBLE)n_int; - - while (n_int < min_scaled) { n_int *= 10; factor *= 10.0f; exponent--; } - - number *= factor; - } - - /* round to nearest integer */ - n = ((UNITY_INT32)(number + number) + 1) / 2; - -#ifndef UNITY_ROUND_TIES_AWAY_FROM_ZERO - /* round to even if exactly between two integers */ - if ((n & 1) && (((UNITY_DOUBLE)n - number) == 0.5f)) - n--; -#endif - - n += n_int; - - if (n >= max_scaled) - { - n = min_scaled; - exponent++; - } - - /* determine where to place decimal point */ - decimals = ((exponent <= 0) && (exponent >= -(sig_digits + 3))) ? (-exponent) : (sig_digits - 1); - exponent += decimals; - - /* truncate trailing zeroes after decimal point */ - while ((decimals > 0) && ((n % 10) == 0)) - { - n /= 10; - decimals--; - } - - /* build up buffer in reverse order */ - digits = 0; - while ((n != 0) || (digits <= decimals)) - { - buf[digits++] = (char)('0' + n % 10); - n /= 10; - } - while (digits > 0) - { - if (digits == decimals) { UNITY_OUTPUT_CHAR('.'); } - UNITY_OUTPUT_CHAR(buf[--digits]); - } - - /* print exponent if needed */ - if (exponent != 0) - { - UNITY_OUTPUT_CHAR('e'); - - if (exponent < 0) - { - UNITY_OUTPUT_CHAR('-'); - exponent = -exponent; - } - else - { - UNITY_OUTPUT_CHAR('+'); - } - - digits = 0; - while ((exponent != 0) || (digits < 2)) - { - buf[digits++] = (char)('0' + exponent % 10); - exponent /= 10; - } - while (digits > 0) - { - UNITY_OUTPUT_CHAR(buf[--digits]); - } - } - } -} -#endif /* ! UNITY_EXCLUDE_FLOAT_PRINT */ - -/*-----------------------------------------------*/ -static void UnityTestResultsBegin(const char* file, const UNITY_LINE_TYPE line) -{ -#ifdef UNITY_OUTPUT_FOR_ECLIPSE - UNITY_OUTPUT_CHAR('('); - UnityPrint(file); - UNITY_OUTPUT_CHAR(':'); - UnityPrintNumber((UNITY_INT)line); - UNITY_OUTPUT_CHAR(')'); - UNITY_OUTPUT_CHAR(' '); - UnityPrint(Unity.CurrentTestName); - UNITY_OUTPUT_CHAR(':'); -#else -#ifdef UNITY_OUTPUT_FOR_IAR_WORKBENCH - UnityPrint("<SRCREF line="); - UnityPrintNumber((UNITY_INT)line); - UnityPrint(" file=\""); - UnityPrint(file); - UNITY_OUTPUT_CHAR('"'); - UNITY_OUTPUT_CHAR('>'); - UnityPrint(Unity.CurrentTestName); - UnityPrint("</SRCREF> "); -#else -#ifdef UNITY_OUTPUT_FOR_QT_CREATOR - UnityPrint("file://"); - UnityPrint(file); - UNITY_OUTPUT_CHAR(':'); - UnityPrintNumber((UNITY_INT)line); - UNITY_OUTPUT_CHAR(' '); - UnityPrint(Unity.CurrentTestName); - UNITY_OUTPUT_CHAR(':'); -#else - UnityPrint(file); - UNITY_OUTPUT_CHAR(':'); - UnityPrintNumber((UNITY_INT)line); - UNITY_OUTPUT_CHAR(':'); - UnityPrint(Unity.CurrentTestName); - UNITY_OUTPUT_CHAR(':'); -#endif -#endif -#endif -} - -/*-----------------------------------------------*/ -static void UnityTestResultsFailBegin(const UNITY_LINE_TYPE line) -{ - UnityTestResultsBegin(Unity.TestFile, line); - UnityPrint(UnityStrFail); - UNITY_OUTPUT_CHAR(':'); -} - -/*-----------------------------------------------*/ -void UnityConcludeTest(void) -{ - if (Unity.CurrentTestIgnored) - { - Unity.TestIgnores++; - } - else if (!Unity.CurrentTestFailed) - { - UnityTestResultsBegin(Unity.TestFile, Unity.CurrentTestLineNumber); - UnityPrint(UnityStrPass); - } - else - { - Unity.TestFailures++; - } - - Unity.CurrentTestFailed = 0; - Unity.CurrentTestIgnored = 0; - UNITY_PRINT_EXEC_TIME(); - UNITY_PRINT_EOL(); - UNITY_FLUSH_CALL(); -} - -/*-----------------------------------------------*/ -static void UnityAddMsgIfSpecified(const char* msg) -{ - if (msg) - { - UnityPrint(UnityStrSpacer); - -#ifdef UNITY_PRINT_TEST_CONTEXT - UNITY_PRINT_TEST_CONTEXT(); -#endif -#ifndef UNITY_EXCLUDE_DETAILS - if (Unity.CurrentDetail1) - { - UnityPrint(UnityStrDetail1Name); - UnityPrint(Unity.CurrentDetail1); - if (Unity.CurrentDetail2) - { - UnityPrint(UnityStrDetail2Name); - UnityPrint(Unity.CurrentDetail2); - } - UnityPrint(UnityStrSpacer); - } -#endif - UnityPrint(msg); - } -} - -/*-----------------------------------------------*/ -static void UnityPrintExpectedAndActualStrings(const char* expected, const char* actual) -{ - UnityPrint(UnityStrExpected); - if (expected != NULL) - { - UNITY_OUTPUT_CHAR('\''); - UnityPrint(expected); - UNITY_OUTPUT_CHAR('\''); - } - else - { - UnityPrint(UnityStrNull); - } - UnityPrint(UnityStrWas); - if (actual != NULL) - { - UNITY_OUTPUT_CHAR('\''); - UnityPrint(actual); - UNITY_OUTPUT_CHAR('\''); - } - else - { - UnityPrint(UnityStrNull); - } -} - -/*-----------------------------------------------*/ -static void UnityPrintExpectedAndActualStringsLen(const char* expected, - const char* actual, - const UNITY_UINT32 length) -{ - UnityPrint(UnityStrExpected); - if (expected != NULL) - { - UNITY_OUTPUT_CHAR('\''); - UnityPrintLen(expected, length); - UNITY_OUTPUT_CHAR('\''); - } - else - { - UnityPrint(UnityStrNull); - } - UnityPrint(UnityStrWas); - if (actual != NULL) - { - UNITY_OUTPUT_CHAR('\''); - UnityPrintLen(actual, length); - UNITY_OUTPUT_CHAR('\''); - } - else - { - UnityPrint(UnityStrNull); - } -} - -/*----------------------------------------------- - * Assertion & Control Helpers - *-----------------------------------------------*/ - -/*-----------------------------------------------*/ -static int UnityIsOneArrayNull(UNITY_INTERNAL_PTR expected, - UNITY_INTERNAL_PTR actual, - const UNITY_LINE_TYPE lineNumber, - const char* msg) -{ - /* Both are NULL or same pointer */ - if (expected == actual) { return 0; } - - /* print and return true if just expected is NULL */ - if (expected == NULL) - { - UnityTestResultsFailBegin(lineNumber); - UnityPrint(UnityStrNullPointerForExpected); - UnityAddMsgIfSpecified(msg); - return 1; - } - - /* print and return true if just actual is NULL */ - if (actual == NULL) - { - UnityTestResultsFailBegin(lineNumber); - UnityPrint(UnityStrNullPointerForActual); - UnityAddMsgIfSpecified(msg); - return 1; - } - - return 0; /* return false if neither is NULL */ -} - -/*----------------------------------------------- - * Assertion Functions - *-----------------------------------------------*/ - -/*-----------------------------------------------*/ -void UnityAssertBits(const UNITY_INT mask, - const UNITY_INT expected, - const UNITY_INT actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber) -{ - RETURN_IF_FAIL_OR_IGNORE; - - if ((mask & expected) != (mask & actual)) - { - UnityTestResultsFailBegin(lineNumber); - UnityPrint(UnityStrExpected); - UnityPrintMask((UNITY_UINT)mask, (UNITY_UINT)expected); - UnityPrint(UnityStrWas); - UnityPrintMask((UNITY_UINT)mask, (UNITY_UINT)actual); - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } -} - -/*-----------------------------------------------*/ -void UnityAssertEqualNumber(const UNITY_INT expected, - const UNITY_INT actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_DISPLAY_STYLE_T style) -{ - RETURN_IF_FAIL_OR_IGNORE; - - if (expected != actual) - { - UnityTestResultsFailBegin(lineNumber); - UnityPrint(UnityStrExpected); - UnityPrintNumberByStyle(expected, style); - UnityPrint(UnityStrWas); - UnityPrintNumberByStyle(actual, style); - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } -} - -/*-----------------------------------------------*/ -void UnityAssertGreaterOrLessOrEqualNumber(const UNITY_INT threshold, - const UNITY_INT actual, - const UNITY_COMPARISON_T compare, - const char *msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_DISPLAY_STYLE_T style) -{ - int failed = 0; - RETURN_IF_FAIL_OR_IGNORE; - - if ((threshold == actual) && (compare & UNITY_EQUAL_TO)) { return; } - if ((threshold == actual)) { failed = 1; } - - if ((style & UNITY_DISPLAY_RANGE_INT) == UNITY_DISPLAY_RANGE_INT) - { - if ((actual > threshold) && (compare & UNITY_SMALLER_THAN)) { failed = 1; } - if ((actual < threshold) && (compare & UNITY_GREATER_THAN)) { failed = 1; } - } - else /* UINT or HEX */ - { - if (((UNITY_UINT)actual > (UNITY_UINT)threshold) && (compare & UNITY_SMALLER_THAN)) { failed = 1; } - if (((UNITY_UINT)actual < (UNITY_UINT)threshold) && (compare & UNITY_GREATER_THAN)) { failed = 1; } - } - - if (failed) - { - UnityTestResultsFailBegin(lineNumber); - UnityPrint(UnityStrExpected); - UnityPrintNumberByStyle(actual, style); - if (compare & UNITY_GREATER_THAN) { UnityPrint(UnityStrGt); } - if (compare & UNITY_SMALLER_THAN) { UnityPrint(UnityStrLt); } - if (compare & UNITY_EQUAL_TO) { UnityPrint(UnityStrOrEqual); } - if (compare == UNITY_NOT_EQUAL) { UnityPrint(UnityStrNotEqual); } - UnityPrintNumberByStyle(threshold, style); - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } -} - -#define UnityPrintPointlessAndBail() \ -{ \ - UnityTestResultsFailBegin(lineNumber); \ - UnityPrint(UnityStrPointless); \ - UnityAddMsgIfSpecified(msg); \ - UNITY_FAIL_AND_BAIL; } - -/*-----------------------------------------------*/ -void UnityAssertEqualIntArray(UNITY_INTERNAL_PTR expected, - UNITY_INTERNAL_PTR actual, - const UNITY_UINT32 num_elements, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_DISPLAY_STYLE_T style, - const UNITY_FLAGS_T flags) -{ - UNITY_UINT32 elements = num_elements; - unsigned int length = style & 0xF; - unsigned int increment = 0; - - RETURN_IF_FAIL_OR_IGNORE; - - if (num_elements == 0) - { - UnityPrintPointlessAndBail(); - } - - if (expected == actual) - { - return; /* Both are NULL or same pointer */ - } - - if (UnityIsOneArrayNull(expected, actual, lineNumber, msg)) - { - UNITY_FAIL_AND_BAIL; - } - - while ((elements > 0) && (elements--)) - { - UNITY_INT expect_val; - UNITY_INT actual_val; - - switch (length) - { - case 1: - expect_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT8*)expected; - actual_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT8*)actual; - increment = sizeof(UNITY_INT8); - break; - - case 2: - expect_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT16*)expected; - actual_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT16*)actual; - increment = sizeof(UNITY_INT16); - break; - -#ifdef UNITY_SUPPORT_64 - case 8: - expect_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT64*)expected; - actual_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT64*)actual; - increment = sizeof(UNITY_INT64); - break; -#endif - - default: /* default is length 4 bytes */ - case 4: - expect_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT32*)expected; - actual_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT32*)actual; - increment = sizeof(UNITY_INT32); - length = 4; - break; - } - - if (expect_val != actual_val) - { - if ((style & UNITY_DISPLAY_RANGE_UINT) && (length < (UNITY_INT_WIDTH / 8))) - { /* For UINT, remove sign extension (padding 1's) from signed type casts above */ - UNITY_INT mask = 1; - mask = (mask << 8 * length) - 1; - expect_val &= mask; - actual_val &= mask; - } - UnityTestResultsFailBegin(lineNumber); - UnityPrint(UnityStrElement); - UnityPrintNumberUnsigned(num_elements - elements - 1); - UnityPrint(UnityStrExpected); - UnityPrintNumberByStyle(expect_val, style); - UnityPrint(UnityStrWas); - UnityPrintNumberByStyle(actual_val, style); - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } - /* Walk through array by incrementing the pointers */ - if (flags == UNITY_ARRAY_TO_ARRAY) - { - expected = (UNITY_INTERNAL_PTR)((const char*)expected + increment); - } - actual = (UNITY_INTERNAL_PTR)((const char*)actual + increment); - } -} - -/*-----------------------------------------------*/ -#ifndef UNITY_EXCLUDE_FLOAT -/* Wrap this define in a function with variable types as float or double */ -#define UNITY_FLOAT_OR_DOUBLE_WITHIN(delta, expected, actual, diff) \ - if (isinf(expected) && isinf(actual) && (((expected) < 0) == ((actual) < 0))) return 1; \ - if (UNITY_NAN_CHECK) return 1; \ - (diff) = (actual) - (expected); \ - if ((diff) < 0) (diff) = -(diff); \ - if ((delta) < 0) (delta) = -(delta); \ - return !(isnan(diff) || isinf(diff) || ((diff) > (delta))) - /* This first part of this condition will catch any NaN or Infinite values */ -#ifndef UNITY_NAN_NOT_EQUAL_NAN - #define UNITY_NAN_CHECK isnan(expected) && isnan(actual) -#else - #define UNITY_NAN_CHECK 0 -#endif - -#ifndef UNITY_EXCLUDE_FLOAT_PRINT - #define UNITY_PRINT_EXPECTED_AND_ACTUAL_FLOAT(expected, actual) \ - { \ - UnityPrint(UnityStrExpected); \ - UnityPrintFloat(expected); \ - UnityPrint(UnityStrWas); \ - UnityPrintFloat(actual); } -#else - #define UNITY_PRINT_EXPECTED_AND_ACTUAL_FLOAT(expected, actual) \ - UnityPrint(UnityStrDelta) -#endif /* UNITY_EXCLUDE_FLOAT_PRINT */ - -/*-----------------------------------------------*/ -static int UnityFloatsWithin(UNITY_FLOAT delta, UNITY_FLOAT expected, UNITY_FLOAT actual) -{ - UNITY_FLOAT diff; - UNITY_FLOAT_OR_DOUBLE_WITHIN(delta, expected, actual, diff); -} - -/*-----------------------------------------------*/ -void UnityAssertEqualFloatArray(UNITY_PTR_ATTRIBUTE const UNITY_FLOAT* expected, - UNITY_PTR_ATTRIBUTE const UNITY_FLOAT* actual, - const UNITY_UINT32 num_elements, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_FLAGS_T flags) -{ - UNITY_UINT32 elements = num_elements; - UNITY_PTR_ATTRIBUTE const UNITY_FLOAT* ptr_expected = expected; - UNITY_PTR_ATTRIBUTE const UNITY_FLOAT* ptr_actual = actual; - - RETURN_IF_FAIL_OR_IGNORE; - - if (elements == 0) - { - UnityPrintPointlessAndBail(); - } - - if (expected == actual) - { - return; /* Both are NULL or same pointer */ - } - - if (UnityIsOneArrayNull((UNITY_INTERNAL_PTR)expected, (UNITY_INTERNAL_PTR)actual, lineNumber, msg)) - { - UNITY_FAIL_AND_BAIL; - } - - while (elements--) - { - if (!UnityFloatsWithin(*ptr_expected * UNITY_FLOAT_PRECISION, *ptr_expected, *ptr_actual)) - { - UnityTestResultsFailBegin(lineNumber); - UnityPrint(UnityStrElement); - UnityPrintNumberUnsigned(num_elements - elements - 1); - UNITY_PRINT_EXPECTED_AND_ACTUAL_FLOAT((UNITY_DOUBLE)*ptr_expected, (UNITY_DOUBLE)*ptr_actual); - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } - if (flags == UNITY_ARRAY_TO_ARRAY) - { - ptr_expected++; - } - ptr_actual++; - } -} - -/*-----------------------------------------------*/ -void UnityAssertFloatsWithin(const UNITY_FLOAT delta, - const UNITY_FLOAT expected, - const UNITY_FLOAT actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber) -{ - RETURN_IF_FAIL_OR_IGNORE; - - - if (!UnityFloatsWithin(delta, expected, actual)) - { - UnityTestResultsFailBegin(lineNumber); - UNITY_PRINT_EXPECTED_AND_ACTUAL_FLOAT((UNITY_DOUBLE)expected, (UNITY_DOUBLE)actual); - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } -} - -/*-----------------------------------------------*/ -void UnityAssertFloatSpecial(const UNITY_FLOAT actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_FLOAT_TRAIT_T style) -{ - const char* trait_names[] = {UnityStrInf, UnityStrNegInf, UnityStrNaN, UnityStrDet}; - UNITY_INT should_be_trait = ((UNITY_INT)style & 1); - UNITY_INT is_trait = !should_be_trait; - UNITY_INT trait_index = (UNITY_INT)(style >> 1); - - RETURN_IF_FAIL_OR_IGNORE; - - switch (style) - { - case UNITY_FLOAT_IS_INF: - case UNITY_FLOAT_IS_NOT_INF: - is_trait = isinf(actual) && (actual > 0); - break; - case UNITY_FLOAT_IS_NEG_INF: - case UNITY_FLOAT_IS_NOT_NEG_INF: - is_trait = isinf(actual) && (actual < 0); - break; - - case UNITY_FLOAT_IS_NAN: - case UNITY_FLOAT_IS_NOT_NAN: - is_trait = isnan(actual) ? 1 : 0; - break; - - case UNITY_FLOAT_IS_DET: /* A determinate number is non infinite and not NaN. */ - case UNITY_FLOAT_IS_NOT_DET: - is_trait = !isinf(actual) && !isnan(actual); - break; - - default: /* including UNITY_FLOAT_INVALID_TRAIT */ - trait_index = 0; - trait_names[0] = UnityStrInvalidFloatTrait; - break; - } - - if (is_trait != should_be_trait) - { - UnityTestResultsFailBegin(lineNumber); - UnityPrint(UnityStrExpected); - if (!should_be_trait) - { - UnityPrint(UnityStrNot); - } - UnityPrint(trait_names[trait_index]); - UnityPrint(UnityStrWas); -#ifndef UNITY_EXCLUDE_FLOAT_PRINT - UnityPrintFloat((UNITY_DOUBLE)actual); -#else - if (should_be_trait) - { - UnityPrint(UnityStrNot); - } - UnityPrint(trait_names[trait_index]); -#endif - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } -} - -#endif /* not UNITY_EXCLUDE_FLOAT */ - -/*-----------------------------------------------*/ -#ifndef UNITY_EXCLUDE_DOUBLE -static int UnityDoublesWithin(UNITY_DOUBLE delta, UNITY_DOUBLE expected, UNITY_DOUBLE actual) -{ - UNITY_DOUBLE diff; - UNITY_FLOAT_OR_DOUBLE_WITHIN(delta, expected, actual, diff); -} - -/*-----------------------------------------------*/ -void UnityAssertEqualDoubleArray(UNITY_PTR_ATTRIBUTE const UNITY_DOUBLE* expected, - UNITY_PTR_ATTRIBUTE const UNITY_DOUBLE* actual, - const UNITY_UINT32 num_elements, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_FLAGS_T flags) -{ - UNITY_UINT32 elements = num_elements; - UNITY_PTR_ATTRIBUTE const UNITY_DOUBLE* ptr_expected = expected; - UNITY_PTR_ATTRIBUTE const UNITY_DOUBLE* ptr_actual = actual; - - RETURN_IF_FAIL_OR_IGNORE; - - if (elements == 0) - { - UnityPrintPointlessAndBail(); - } - - if (expected == actual) - { - return; /* Both are NULL or same pointer */ - } - - if (UnityIsOneArrayNull((UNITY_INTERNAL_PTR)expected, (UNITY_INTERNAL_PTR)actual, lineNumber, msg)) - { - UNITY_FAIL_AND_BAIL; - } - - while (elements--) - { - if (!UnityDoublesWithin(*ptr_expected * UNITY_DOUBLE_PRECISION, *ptr_expected, *ptr_actual)) - { - UnityTestResultsFailBegin(lineNumber); - UnityPrint(UnityStrElement); - UnityPrintNumberUnsigned(num_elements - elements - 1); - UNITY_PRINT_EXPECTED_AND_ACTUAL_FLOAT(*ptr_expected, *ptr_actual); - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } - if (flags == UNITY_ARRAY_TO_ARRAY) - { - ptr_expected++; - } - ptr_actual++; - } -} - -/*-----------------------------------------------*/ -void UnityAssertDoublesWithin(const UNITY_DOUBLE delta, - const UNITY_DOUBLE expected, - const UNITY_DOUBLE actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber) -{ - RETURN_IF_FAIL_OR_IGNORE; - - if (!UnityDoublesWithin(delta, expected, actual)) - { - UnityTestResultsFailBegin(lineNumber); - UNITY_PRINT_EXPECTED_AND_ACTUAL_FLOAT(expected, actual); - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } -} - -/*-----------------------------------------------*/ -void UnityAssertDoubleSpecial(const UNITY_DOUBLE actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_FLOAT_TRAIT_T style) -{ - const char* trait_names[] = {UnityStrInf, UnityStrNegInf, UnityStrNaN, UnityStrDet}; - UNITY_INT should_be_trait = ((UNITY_INT)style & 1); - UNITY_INT is_trait = !should_be_trait; - UNITY_INT trait_index = (UNITY_INT)(style >> 1); - - RETURN_IF_FAIL_OR_IGNORE; - - switch (style) - { - case UNITY_FLOAT_IS_INF: - case UNITY_FLOAT_IS_NOT_INF: - is_trait = isinf(actual) && (actual > 0); - break; - case UNITY_FLOAT_IS_NEG_INF: - case UNITY_FLOAT_IS_NOT_NEG_INF: - is_trait = isinf(actual) && (actual < 0); - break; - - case UNITY_FLOAT_IS_NAN: - case UNITY_FLOAT_IS_NOT_NAN: - is_trait = isnan(actual) ? 1 : 0; - break; - - case UNITY_FLOAT_IS_DET: /* A determinate number is non infinite and not NaN. */ - case UNITY_FLOAT_IS_NOT_DET: - is_trait = !isinf(actual) && !isnan(actual); - break; - - default: /* including UNITY_FLOAT_INVALID_TRAIT */ - trait_index = 0; - trait_names[0] = UnityStrInvalidFloatTrait; - break; - } - - if (is_trait != should_be_trait) - { - UnityTestResultsFailBegin(lineNumber); - UnityPrint(UnityStrExpected); - if (!should_be_trait) - { - UnityPrint(UnityStrNot); - } - UnityPrint(trait_names[trait_index]); - UnityPrint(UnityStrWas); -#ifndef UNITY_EXCLUDE_FLOAT_PRINT - UnityPrintFloat(actual); -#else - if (should_be_trait) - { - UnityPrint(UnityStrNot); - } - UnityPrint(trait_names[trait_index]); -#endif - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } -} - -#endif /* not UNITY_EXCLUDE_DOUBLE */ - -/*-----------------------------------------------*/ -void UnityAssertNumbersWithin(const UNITY_UINT delta, - const UNITY_INT expected, - const UNITY_INT actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_DISPLAY_STYLE_T style) -{ - RETURN_IF_FAIL_OR_IGNORE; - - if ((style & UNITY_DISPLAY_RANGE_INT) == UNITY_DISPLAY_RANGE_INT) - { - if (actual > expected) - { - Unity.CurrentTestFailed = (((UNITY_UINT)actual - (UNITY_UINT)expected) > delta); - } - else - { - Unity.CurrentTestFailed = (((UNITY_UINT)expected - (UNITY_UINT)actual) > delta); - } - } - else - { - if ((UNITY_UINT)actual > (UNITY_UINT)expected) - { - Unity.CurrentTestFailed = (((UNITY_UINT)actual - (UNITY_UINT)expected) > delta); - } - else - { - Unity.CurrentTestFailed = (((UNITY_UINT)expected - (UNITY_UINT)actual) > delta); - } - } - - if (Unity.CurrentTestFailed) - { - UnityTestResultsFailBegin(lineNumber); - UnityPrint(UnityStrDelta); - UnityPrintNumberByStyle((UNITY_INT)delta, style); - UnityPrint(UnityStrExpected); - UnityPrintNumberByStyle(expected, style); - UnityPrint(UnityStrWas); - UnityPrintNumberByStyle(actual, style); - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } -} - -/*-----------------------------------------------*/ -void UnityAssertNumbersArrayWithin(const UNITY_UINT delta, - UNITY_INTERNAL_PTR expected, - UNITY_INTERNAL_PTR actual, - const UNITY_UINT32 num_elements, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_DISPLAY_STYLE_T style, - const UNITY_FLAGS_T flags) -{ - UNITY_UINT32 elements = num_elements; - unsigned int length = style & 0xF; - unsigned int increment = 0; - - RETURN_IF_FAIL_OR_IGNORE; - - if (num_elements == 0) - { - UnityPrintPointlessAndBail(); - } - - if (expected == actual) - { - return; /* Both are NULL or same pointer */ - } - - if (UnityIsOneArrayNull(expected, actual, lineNumber, msg)) - { - UNITY_FAIL_AND_BAIL; - } - - while ((elements > 0) && (elements--)) - { - UNITY_INT expect_val; - UNITY_INT actual_val; - - switch (length) - { - case 1: - expect_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT8*)expected; - actual_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT8*)actual; - increment = sizeof(UNITY_INT8); - break; - - case 2: - expect_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT16*)expected; - actual_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT16*)actual; - increment = sizeof(UNITY_INT16); - break; - -#ifdef UNITY_SUPPORT_64 - case 8: - expect_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT64*)expected; - actual_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT64*)actual; - increment = sizeof(UNITY_INT64); - break; -#endif - - default: /* default is length 4 bytes */ - case 4: - expect_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT32*)expected; - actual_val = *(UNITY_PTR_ATTRIBUTE const UNITY_INT32*)actual; - increment = sizeof(UNITY_INT32); - length = 4; - break; - } - - if ((style & UNITY_DISPLAY_RANGE_INT) == UNITY_DISPLAY_RANGE_INT) - { - if (actual_val > expect_val) - { - Unity.CurrentTestFailed = (((UNITY_UINT)actual_val - (UNITY_UINT)expect_val) > delta); - } - else - { - Unity.CurrentTestFailed = (((UNITY_UINT)expect_val - (UNITY_UINT)actual_val) > delta); - } - } - else - { - if ((UNITY_UINT)actual_val > (UNITY_UINT)expect_val) - { - Unity.CurrentTestFailed = (((UNITY_UINT)actual_val - (UNITY_UINT)expect_val) > delta); - } - else - { - Unity.CurrentTestFailed = (((UNITY_UINT)expect_val - (UNITY_UINT)actual_val) > delta); - } - } - - if (Unity.CurrentTestFailed) - { - if ((style & UNITY_DISPLAY_RANGE_UINT) && (length < (UNITY_INT_WIDTH / 8))) - { /* For UINT, remove sign extension (padding 1's) from signed type casts above */ - UNITY_INT mask = 1; - mask = (mask << 8 * length) - 1; - expect_val &= mask; - actual_val &= mask; - } - UnityTestResultsFailBegin(lineNumber); - UnityPrint(UnityStrDelta); - UnityPrintNumberByStyle((UNITY_INT)delta, style); - UnityPrint(UnityStrElement); - UnityPrintNumberUnsigned(num_elements - elements - 1); - UnityPrint(UnityStrExpected); - UnityPrintNumberByStyle(expect_val, style); - UnityPrint(UnityStrWas); - UnityPrintNumberByStyle(actual_val, style); - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } - /* Walk through array by incrementing the pointers */ - if (flags == UNITY_ARRAY_TO_ARRAY) - { - expected = (UNITY_INTERNAL_PTR)((const char*)expected + increment); - } - actual = (UNITY_INTERNAL_PTR)((const char*)actual + increment); - } -} - -/*-----------------------------------------------*/ -void UnityAssertEqualString(const char* expected, - const char* actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber) -{ - UNITY_UINT32 i; - - RETURN_IF_FAIL_OR_IGNORE; - - /* if both pointers not null compare the strings */ - if (expected && actual) - { - for (i = 0; expected[i] || actual[i]; i++) - { - if (expected[i] != actual[i]) - { - Unity.CurrentTestFailed = 1; - break; - } - } - } - else - { /* handle case of one pointers being null (if both null, test should pass) */ - if (expected != actual) - { - Unity.CurrentTestFailed = 1; - } - } - - if (Unity.CurrentTestFailed) - { - UnityTestResultsFailBegin(lineNumber); - UnityPrintExpectedAndActualStrings(expected, actual); - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } -} - -/*-----------------------------------------------*/ -void UnityAssertEqualStringLen(const char* expected, - const char* actual, - const UNITY_UINT32 length, - const char* msg, - const UNITY_LINE_TYPE lineNumber) -{ - UNITY_UINT32 i; - - RETURN_IF_FAIL_OR_IGNORE; - - /* if both pointers not null compare the strings */ - if (expected && actual) - { - for (i = 0; (i < length) && (expected[i] || actual[i]); i++) - { - if (expected[i] != actual[i]) - { - Unity.CurrentTestFailed = 1; - break; - } - } - } - else - { /* handle case of one pointers being null (if both null, test should pass) */ - if (expected != actual) - { - Unity.CurrentTestFailed = 1; - } - } - - if (Unity.CurrentTestFailed) - { - UnityTestResultsFailBegin(lineNumber); - UnityPrintExpectedAndActualStringsLen(expected, actual, length); - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } -} - -/*-----------------------------------------------*/ -void UnityAssertEqualStringArray(UNITY_INTERNAL_PTR expected, - const char** actual, - const UNITY_UINT32 num_elements, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_FLAGS_T flags) -{ - UNITY_UINT32 i = 0; - UNITY_UINT32 j = 0; - const char* expd = NULL; - const char* act = NULL; - - RETURN_IF_FAIL_OR_IGNORE; - - /* if no elements, it's an error */ - if (num_elements == 0) - { - UnityPrintPointlessAndBail(); - } - - if ((const void*)expected == (const void*)actual) - { - return; /* Both are NULL or same pointer */ - } - - if (UnityIsOneArrayNull((UNITY_INTERNAL_PTR)expected, (UNITY_INTERNAL_PTR)actual, lineNumber, msg)) - { - UNITY_FAIL_AND_BAIL; - } - - if (flags != UNITY_ARRAY_TO_ARRAY) - { - expd = (const char*)expected; - } - - do - { - act = actual[j]; - if (flags == UNITY_ARRAY_TO_ARRAY) - { - expd = ((const char* const*)expected)[j]; - } - - /* if both pointers not null compare the strings */ - if (expd && act) - { - for (i = 0; expd[i] || act[i]; i++) - { - if (expd[i] != act[i]) - { - Unity.CurrentTestFailed = 1; - break; - } - } - } - else - { /* handle case of one pointers being null (if both null, test should pass) */ - if (expd != act) - { - Unity.CurrentTestFailed = 1; - } - } - - if (Unity.CurrentTestFailed) - { - UnityTestResultsFailBegin(lineNumber); - if (num_elements > 1) - { - UnityPrint(UnityStrElement); - UnityPrintNumberUnsigned(j); - } - UnityPrintExpectedAndActualStrings(expd, act); - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } - } while (++j < num_elements); -} - -/*-----------------------------------------------*/ -void UnityAssertEqualMemory(UNITY_INTERNAL_PTR expected, - UNITY_INTERNAL_PTR actual, - const UNITY_UINT32 length, - const UNITY_UINT32 num_elements, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_FLAGS_T flags) -{ - UNITY_PTR_ATTRIBUTE const unsigned char* ptr_exp = (UNITY_PTR_ATTRIBUTE const unsigned char*)expected; - UNITY_PTR_ATTRIBUTE const unsigned char* ptr_act = (UNITY_PTR_ATTRIBUTE const unsigned char*)actual; - UNITY_UINT32 elements = num_elements; - UNITY_UINT32 bytes; - - RETURN_IF_FAIL_OR_IGNORE; - - if ((elements == 0) || (length == 0)) - { - UnityPrintPointlessAndBail(); - } - - if (expected == actual) - { - return; /* Both are NULL or same pointer */ - } - - if (UnityIsOneArrayNull(expected, actual, lineNumber, msg)) - { - UNITY_FAIL_AND_BAIL; - } - - while (elements--) - { - bytes = length; - while (bytes--) - { - if (*ptr_exp != *ptr_act) - { - UnityTestResultsFailBegin(lineNumber); - UnityPrint(UnityStrMemory); - if (num_elements > 1) - { - UnityPrint(UnityStrElement); - UnityPrintNumberUnsigned(num_elements - elements - 1); - } - UnityPrint(UnityStrByte); - UnityPrintNumberUnsigned(length - bytes - 1); - UnityPrint(UnityStrExpected); - UnityPrintNumberByStyle(*ptr_exp, UNITY_DISPLAY_STYLE_HEX8); - UnityPrint(UnityStrWas); - UnityPrintNumberByStyle(*ptr_act, UNITY_DISPLAY_STYLE_HEX8); - UnityAddMsgIfSpecified(msg); - UNITY_FAIL_AND_BAIL; - } - ptr_exp++; - ptr_act++; - } - if (flags == UNITY_ARRAY_TO_VAL) - { - ptr_exp = (UNITY_PTR_ATTRIBUTE const unsigned char*)expected; - } - } -} - -/*-----------------------------------------------*/ - -static union -{ - UNITY_INT8 i8; - UNITY_INT16 i16; - UNITY_INT32 i32; -#ifdef UNITY_SUPPORT_64 - UNITY_INT64 i64; -#endif -#ifndef UNITY_EXCLUDE_FLOAT - float f; -#endif -#ifndef UNITY_EXCLUDE_DOUBLE - double d; -#endif -} UnityQuickCompare; - -UNITY_INTERNAL_PTR UnityNumToPtr(const UNITY_INT num, const UNITY_UINT8 size) -{ - switch(size) - { - case 1: - UnityQuickCompare.i8 = (UNITY_INT8)num; - return (UNITY_INTERNAL_PTR)(&UnityQuickCompare.i8); - - case 2: - UnityQuickCompare.i16 = (UNITY_INT16)num; - return (UNITY_INTERNAL_PTR)(&UnityQuickCompare.i16); - -#ifdef UNITY_SUPPORT_64 - case 8: - UnityQuickCompare.i64 = (UNITY_INT64)num; - return (UNITY_INTERNAL_PTR)(&UnityQuickCompare.i64); -#endif - - default: /* 4 bytes */ - UnityQuickCompare.i32 = (UNITY_INT32)num; - return (UNITY_INTERNAL_PTR)(&UnityQuickCompare.i32); - } -} - -#ifndef UNITY_EXCLUDE_FLOAT -/*-----------------------------------------------*/ -UNITY_INTERNAL_PTR UnityFloatToPtr(const float num) -{ - UnityQuickCompare.f = num; - return (UNITY_INTERNAL_PTR)(&UnityQuickCompare.f); -} -#endif - -#ifndef UNITY_EXCLUDE_DOUBLE -/*-----------------------------------------------*/ -UNITY_INTERNAL_PTR UnityDoubleToPtr(const double num) -{ - UnityQuickCompare.d = num; - return (UNITY_INTERNAL_PTR)(&UnityQuickCompare.d); -} -#endif - -/*----------------------------------------------- - * printf helper function - *-----------------------------------------------*/ -#ifdef UNITY_INCLUDE_PRINT_FORMATTED -static void UnityPrintFVA(const char* format, va_list va) -{ - const char* pch = format; - if (pch != NULL) - { - while (*pch) - { - /* format identification character */ - if (*pch == '%') - { - pch++; - - if (pch != NULL) - { - switch (*pch) - { - case 'd': - case 'i': - { - const int number = va_arg(va, int); - UnityPrintNumber((UNITY_INT)number); - break; - } -#ifndef UNITY_EXCLUDE_FLOAT_PRINT - case 'f': - case 'g': - { - const double number = va_arg(va, double); - UnityPrintFloat((UNITY_DOUBLE)number); - break; - } -#endif - case 'u': - { - const unsigned int number = va_arg(va, unsigned int); - UnityPrintNumberUnsigned((UNITY_UINT)number); - break; - } - case 'b': - { - const unsigned int number = va_arg(va, unsigned int); - const UNITY_UINT mask = (UNITY_UINT)0 - (UNITY_UINT)1; - UNITY_OUTPUT_CHAR('0'); - UNITY_OUTPUT_CHAR('b'); - UnityPrintMask(mask, (UNITY_UINT)number); - break; - } - case 'x': - case 'X': - case 'p': - { - const unsigned int number = va_arg(va, unsigned int); - UNITY_OUTPUT_CHAR('0'); - UNITY_OUTPUT_CHAR('x'); - UnityPrintNumberHex((UNITY_UINT)number, 8); - break; - } - case 'c': - { - const int ch = va_arg(va, int); - UnityPrintChar((const char *)&ch); - break; - } - case 's': - { - const char * string = va_arg(va, const char *); - UnityPrint(string); - break; - } - case '%': - { - UnityPrintChar(pch); - break; - } - default: - { - /* print the unknown format character */ - UNITY_OUTPUT_CHAR('%'); - UnityPrintChar(pch); - break; - } - } - } - } -#ifdef UNITY_OUTPUT_COLOR - /* print ANSI escape code */ - else if ((*pch == 27) && (*(pch + 1) == '[')) - { - pch += UnityPrintAnsiEscapeString(pch); - continue; - } -#endif - else if (*pch == '\n') - { - UNITY_PRINT_EOL(); - } - else - { - UnityPrintChar(pch); - } - - pch++; - } - } -} - -void UnityPrintF(const UNITY_LINE_TYPE line, const char* format, ...) -{ - UnityTestResultsBegin(Unity.TestFile, line); - UnityPrint("INFO"); - if(format != NULL) - { - UnityPrint(": "); - va_list va; - va_start(va, format); - UnityPrintFVA(format, va); - va_end(va); - } - UNITY_PRINT_EOL(); -} -#endif /* ! UNITY_INCLUDE_PRINT_FORMATTED */ - - -/*----------------------------------------------- - * Control Functions - *-----------------------------------------------*/ - -/*-----------------------------------------------*/ -void UnityFail(const char* msg, const UNITY_LINE_TYPE line) -{ - RETURN_IF_FAIL_OR_IGNORE; - - UnityTestResultsBegin(Unity.TestFile, line); - UnityPrint(UnityStrFail); - if (msg != NULL) - { - UNITY_OUTPUT_CHAR(':'); - -#ifdef UNITY_PRINT_TEST_CONTEXT - UNITY_PRINT_TEST_CONTEXT(); -#endif -#ifndef UNITY_EXCLUDE_DETAILS - if (Unity.CurrentDetail1) - { - UnityPrint(UnityStrDetail1Name); - UnityPrint(Unity.CurrentDetail1); - if (Unity.CurrentDetail2) - { - UnityPrint(UnityStrDetail2Name); - UnityPrint(Unity.CurrentDetail2); - } - UnityPrint(UnityStrSpacer); - } -#endif - if (msg[0] != ' ') - { - UNITY_OUTPUT_CHAR(' '); - } - UnityPrint(msg); - } - - UNITY_FAIL_AND_BAIL; -} - -/*-----------------------------------------------*/ -void UnityIgnore(const char* msg, const UNITY_LINE_TYPE line) -{ - RETURN_IF_FAIL_OR_IGNORE; - - UnityTestResultsBegin(Unity.TestFile, line); - UnityPrint(UnityStrIgnore); - if (msg != NULL) - { - UNITY_OUTPUT_CHAR(':'); - UNITY_OUTPUT_CHAR(' '); - UnityPrint(msg); - } - UNITY_IGNORE_AND_BAIL; -} - -/*-----------------------------------------------*/ -void UnityMessage(const char* msg, const UNITY_LINE_TYPE line) -{ - UnityTestResultsBegin(Unity.TestFile, line); - UnityPrint("INFO"); - if (msg != NULL) - { - UNITY_OUTPUT_CHAR(':'); - UNITY_OUTPUT_CHAR(' '); - UnityPrint(msg); - } - UNITY_PRINT_EOL(); -} - -/*-----------------------------------------------*/ -/* If we have not defined our own test runner, then include our default test runner to make life easier */ -#ifndef UNITY_SKIP_DEFAULT_RUNNER -void UnityDefaultTestRun(UnityTestFunction Func, const char* FuncName, const int FuncLineNum) -{ - Unity.CurrentTestName = FuncName; - Unity.CurrentTestLineNumber = (UNITY_LINE_TYPE)FuncLineNum; - Unity.NumberOfTests++; - UNITY_CLR_DETAILS(); - UNITY_EXEC_TIME_START(); - if (TEST_PROTECT()) - { - setUp(); - Func(); - } - if (TEST_PROTECT()) - { - tearDown(); - } - UNITY_EXEC_TIME_STOP(); - UnityConcludeTest(); -} -#endif - -/*-----------------------------------------------*/ -void UnitySetTestFile(const char* filename) -{ - Unity.TestFile = filename; -} - -/*-----------------------------------------------*/ -void UnityBegin(const char* filename) -{ - Unity.TestFile = filename; - Unity.CurrentTestName = NULL; - Unity.CurrentTestLineNumber = 0; - Unity.NumberOfTests = 0; - Unity.TestFailures = 0; - Unity.TestIgnores = 0; - Unity.CurrentTestFailed = 0; - Unity.CurrentTestIgnored = 0; - - UNITY_CLR_DETAILS(); - UNITY_OUTPUT_START(); -} - -/*-----------------------------------------------*/ -int UnityEnd(void) -{ - UNITY_PRINT_EOL(); - UnityPrint(UnityStrBreaker); - UNITY_PRINT_EOL(); - UnityPrintNumber((UNITY_INT)(Unity.NumberOfTests)); - UnityPrint(UnityStrResultsTests); - UnityPrintNumber((UNITY_INT)(Unity.TestFailures)); - UnityPrint(UnityStrResultsFailures); - UnityPrintNumber((UNITY_INT)(Unity.TestIgnores)); - UnityPrint(UnityStrResultsIgnored); - UNITY_PRINT_EOL(); - if (Unity.TestFailures == 0U) - { - UnityPrint(UnityStrOk); - } - else - { - UnityPrint(UnityStrFail); -#ifdef UNITY_DIFFERENTIATE_FINAL_FAIL - UNITY_OUTPUT_CHAR('E'); UNITY_OUTPUT_CHAR('D'); -#endif - } - UNITY_PRINT_EOL(); - UNITY_FLUSH_CALL(); - UNITY_OUTPUT_COMPLETE(); - return (int)(Unity.TestFailures); -} - -/*----------------------------------------------- - * Command Line Argument Support - *-----------------------------------------------*/ -#ifdef UNITY_USE_COMMAND_LINE_ARGS - -char* UnityOptionIncludeNamed = NULL; -char* UnityOptionExcludeNamed = NULL; -int UnityVerbosity = 1; - -/*-----------------------------------------------*/ -int UnityParseOptions(int argc, char** argv) -{ - int i; - UnityOptionIncludeNamed = NULL; - UnityOptionExcludeNamed = NULL; - - for (i = 1; i < argc; i++) - { - if (argv[i][0] == '-') - { - switch (argv[i][1]) - { - case 'l': /* list tests */ - return -1; - case 'n': /* include tests with name including this string */ - case 'f': /* an alias for -n */ - if (argv[i][2] == '=') - { - UnityOptionIncludeNamed = &argv[i][3]; - } - else if (++i < argc) - { - UnityOptionIncludeNamed = argv[i]; - } - else - { - UnityPrint("ERROR: No Test String to Include Matches For"); - UNITY_PRINT_EOL(); - return 1; - } - break; - case 'q': /* quiet */ - UnityVerbosity = 0; - break; - case 'v': /* verbose */ - UnityVerbosity = 2; - break; - case 'x': /* exclude tests with name including this string */ - if (argv[i][2] == '=') - { - UnityOptionExcludeNamed = &argv[i][3]; - } - else if (++i < argc) - { - UnityOptionExcludeNamed = argv[i]; - } - else - { - UnityPrint("ERROR: No Test String to Exclude Matches For"); - UNITY_PRINT_EOL(); - return 1; - } - break; - default: - UnityPrint("ERROR: Unknown Option "); - UNITY_OUTPUT_CHAR(argv[i][1]); - UNITY_PRINT_EOL(); - return 1; - } - } - } - - return 0; -} - -/*-----------------------------------------------*/ -int IsStringInBiggerString(const char* longstring, const char* shortstring) -{ - const char* lptr = longstring; - const char* sptr = shortstring; - const char* lnext = lptr; - - if (*sptr == '*') - { - return 1; - } - - while (*lptr) - { - lnext = lptr + 1; - - /* If they current bytes match, go on to the next bytes */ - while (*lptr && *sptr && (*lptr == *sptr)) - { - lptr++; - sptr++; - - /* We're done if we match the entire string or up to a wildcard */ - if (*sptr == '*') - return 1; - if (*sptr == ',') - return 1; - if (*sptr == '"') - return 1; - if (*sptr == '\'') - return 1; - if (*sptr == ':') - return 2; - if (*sptr == 0) - return 1; - } - - /* Otherwise we start in the long pointer 1 character further and try again */ - lptr = lnext; - sptr = shortstring; - } - - return 0; -} - -/*-----------------------------------------------*/ -int UnityStringArgumentMatches(const char* str) -{ - int retval; - const char* ptr1; - const char* ptr2; - const char* ptrf; - - /* Go through the options and get the substrings for matching one at a time */ - ptr1 = str; - while (ptr1[0] != 0) - { - if ((ptr1[0] == '"') || (ptr1[0] == '\'')) - { - ptr1++; - } - - /* look for the start of the next partial */ - ptr2 = ptr1; - ptrf = 0; - do - { - ptr2++; - if ((ptr2[0] == ':') && (ptr2[1] != 0) && (ptr2[0] != '\'') && (ptr2[0] != '"') && (ptr2[0] != ',')) - { - ptrf = &ptr2[1]; - } - } while ((ptr2[0] != 0) && (ptr2[0] != '\'') && (ptr2[0] != '"') && (ptr2[0] != ',')); - - while ((ptr2[0] != 0) && ((ptr2[0] == ':') || (ptr2[0] == '\'') || (ptr2[0] == '"') || (ptr2[0] == ','))) - { - ptr2++; - } - - /* done if complete filename match */ - retval = IsStringInBiggerString(Unity.TestFile, ptr1); - if (retval == 1) - { - return retval; - } - - /* done if testname match after filename partial match */ - if ((retval == 2) && (ptrf != 0)) - { - if (IsStringInBiggerString(Unity.CurrentTestName, ptrf)) - { - return 1; - } - } - - /* done if complete testname match */ - if (IsStringInBiggerString(Unity.CurrentTestName, ptr1) == 1) - { - return 1; - } - - ptr1 = ptr2; - } - - /* we couldn't find a match for any substrings */ - return 0; -} - -/*-----------------------------------------------*/ -int UnityTestMatches(void) -{ - /* Check if this test name matches the included test pattern */ - int retval; - if (UnityOptionIncludeNamed) - { - retval = UnityStringArgumentMatches(UnityOptionIncludeNamed); - } - else - { - retval = 1; - } - - /* Check if this test name matches the excluded test pattern */ - if (UnityOptionExcludeNamed) - { - if (UnityStringArgumentMatches(UnityOptionExcludeNamed)) - { - retval = 0; - } - } - - return retval; -} - -#endif /* UNITY_USE_COMMAND_LINE_ARGS */ -/*-----------------------------------------------*/ diff --git a/test/unit-test/vendor/ceedling/vendor/unity/src/unity.h b/test/unit-test/vendor/ceedling/vendor/unity/src/unity.h deleted file mode 100644 index 338df0b55..000000000 --- a/test/unit-test/vendor/ceedling/vendor/unity/src/unity.h +++ /dev/null @@ -1,661 +0,0 @@ -/* ========================================== - Unity Project - A Test Framework for C - Copyright (c) 2007-21 Mike Karlesky, Mark VanderVoord, Greg Williams - [Released under MIT License. Please refer to license.txt for details] -========================================== */ - -#ifndef UNITY_FRAMEWORK_H -#define UNITY_FRAMEWORK_H -#define UNITY - -#define UNITY_VERSION_MAJOR 2 -#define UNITY_VERSION_MINOR 5 -#define UNITY_VERSION_BUILD 4 -#define UNITY_VERSION ((UNITY_VERSION_MAJOR << 16) | (UNITY_VERSION_MINOR << 8) | UNITY_VERSION_BUILD) - -#ifdef __cplusplus -extern "C" -{ -#endif - -#include "unity_internals.h" - -/*------------------------------------------------------- - * Test Setup / Teardown - *-------------------------------------------------------*/ - -/* These functions are intended to be called before and after each test. - * If using unity directly, these will need to be provided for each test - * executable built. If you are using the test runner generator and/or - * Ceedling, these are optional. */ -void setUp(void); -void tearDown(void); - -/* These functions are intended to be called at the beginning and end of an - * entire test suite. suiteTearDown() is passed the number of tests that - * failed, and its return value becomes the exit code of main(). If using - * Unity directly, you're in charge of calling these if they are desired. - * If using Ceedling or the test runner generator, these will be called - * automatically if they exist. */ -void suiteSetUp(void); -int suiteTearDown(int num_failures); - -/*------------------------------------------------------- - * Test Reset and Verify - *-------------------------------------------------------*/ - -/* These functions are intended to be called before during tests in order - * to support complex test loops, etc. Both are NOT built into Unity. Instead - * the test runner generator will create them. resetTest will run teardown and - * setup again, verifying any end-of-test needs between. verifyTest will only - * run the verification. */ -void resetTest(void); -void verifyTest(void); - -/*------------------------------------------------------- - * Configuration Options - *------------------------------------------------------- - * All options described below should be passed as a compiler flag to all files using Unity. If you must add #defines, place them BEFORE the #include above. - - * Integers/longs/pointers - * - Unity attempts to automatically discover your integer sizes - * - define UNITY_EXCLUDE_STDINT_H to stop attempting to look in <stdint.h> - * - define UNITY_EXCLUDE_LIMITS_H to stop attempting to look in <limits.h> - * - If you cannot use the automatic methods above, you can force Unity by using these options: - * - define UNITY_SUPPORT_64 - * - set UNITY_INT_WIDTH - * - set UNITY_LONG_WIDTH - * - set UNITY_POINTER_WIDTH - - * Floats - * - define UNITY_EXCLUDE_FLOAT to disallow floating point comparisons - * - define UNITY_FLOAT_PRECISION to specify the precision to use when doing TEST_ASSERT_EQUAL_FLOAT - * - define UNITY_FLOAT_TYPE to specify doubles instead of single precision floats - * - define UNITY_INCLUDE_DOUBLE to allow double floating point comparisons - * - define UNITY_EXCLUDE_DOUBLE to disallow double floating point comparisons (default) - * - define UNITY_DOUBLE_PRECISION to specify the precision to use when doing TEST_ASSERT_EQUAL_DOUBLE - * - define UNITY_DOUBLE_TYPE to specify something other than double - * - define UNITY_EXCLUDE_FLOAT_PRINT to trim binary size, won't print floating point values in errors - - * Output - * - by default, Unity prints to standard out with putchar. define UNITY_OUTPUT_CHAR(a) with a different function if desired - * - define UNITY_DIFFERENTIATE_FINAL_FAIL to print FAILED (vs. FAIL) at test end summary - for automated search for failure - - * Optimization - * - by default, line numbers are stored in unsigned shorts. Define UNITY_LINE_TYPE with a different type if your files are huge - * - by default, test and failure counters are unsigned shorts. Define UNITY_COUNTER_TYPE with a different type if you want to save space or have more than 65535 Tests. - - * Test Cases - * - define UNITY_SUPPORT_TEST_CASES to include the TEST_CASE macro, though really it's mostly about the runner generator script - - * Parameterized Tests - * - you'll want to create a define of TEST_CASE(...) which basically evaluates to nothing - - * Tests with Arguments - * - you'll want to define UNITY_USE_COMMAND_LINE_ARGS if you have the test runner passing arguments to Unity - - *------------------------------------------------------- - * Basic Fail and Ignore - *-------------------------------------------------------*/ - -#define TEST_FAIL_MESSAGE(message) UNITY_TEST_FAIL(__LINE__, (message)) -#define TEST_FAIL() UNITY_TEST_FAIL(__LINE__, NULL) -#define TEST_IGNORE_MESSAGE(message) UNITY_TEST_IGNORE(__LINE__, (message)) -#define TEST_IGNORE() UNITY_TEST_IGNORE(__LINE__, NULL) -#define TEST_MESSAGE(message) UnityMessage((message), __LINE__) -#define TEST_ONLY() -#ifdef UNITY_INCLUDE_PRINT_FORMATTED -#define TEST_PRINTF(message, ...) UnityPrintF(__LINE__, (message), __VA_ARGS__) -#endif - -/* It is not necessary for you to call PASS. A PASS condition is assumed if nothing fails. - * This method allows you to abort a test immediately with a PASS state, ignoring the remainder of the test. */ -#define TEST_PASS() TEST_ABORT() -#define TEST_PASS_MESSAGE(message) do { UnityMessage((message), __LINE__); TEST_ABORT(); } while(0) - -/* This macro does nothing, but it is useful for build tools (like Ceedling) to make use of this to figure out - * which files should be linked to in order to perform a test. Use it like TEST_FILE("sandwiches.c") */ -#define TEST_FILE(a) - -/*------------------------------------------------------- - * Test Asserts (simple) - *-------------------------------------------------------*/ - -/* Boolean */ -#define TEST_ASSERT(condition) UNITY_TEST_ASSERT( (condition), __LINE__, " Expression Evaluated To FALSE") -#define TEST_ASSERT_TRUE(condition) UNITY_TEST_ASSERT( (condition), __LINE__, " Expected TRUE Was FALSE") -#define TEST_ASSERT_UNLESS(condition) UNITY_TEST_ASSERT( !(condition), __LINE__, " Expression Evaluated To TRUE") -#define TEST_ASSERT_FALSE(condition) UNITY_TEST_ASSERT( !(condition), __LINE__, " Expected FALSE Was TRUE") -#define TEST_ASSERT_NULL(pointer) UNITY_TEST_ASSERT_NULL( (pointer), __LINE__, " Expected NULL") -#define TEST_ASSERT_NOT_NULL(pointer) UNITY_TEST_ASSERT_NOT_NULL((pointer), __LINE__, " Expected Non-NULL") -#define TEST_ASSERT_EMPTY(pointer) UNITY_TEST_ASSERT_EMPTY( (pointer), __LINE__, " Expected Empty") -#define TEST_ASSERT_NOT_EMPTY(pointer) UNITY_TEST_ASSERT_NOT_EMPTY((pointer), __LINE__, " Expected Non-Empty") - -/* Integers (of all sizes) */ -#define TEST_ASSERT_EQUAL_INT(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_INT8(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT8((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_INT16(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT16((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_INT32(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT32((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_INT64(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT64((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_UINT(expected, actual) UNITY_TEST_ASSERT_EQUAL_UINT( (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_UINT8(expected, actual) UNITY_TEST_ASSERT_EQUAL_UINT8( (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_UINT16(expected, actual) UNITY_TEST_ASSERT_EQUAL_UINT16( (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_UINT32(expected, actual) UNITY_TEST_ASSERT_EQUAL_UINT32( (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_UINT64(expected, actual) UNITY_TEST_ASSERT_EQUAL_UINT64( (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_size_t(expected, actual) UNITY_TEST_ASSERT_EQUAL_UINT((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_HEX(expected, actual) UNITY_TEST_ASSERT_EQUAL_HEX32((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_HEX8(expected, actual) UNITY_TEST_ASSERT_EQUAL_HEX8( (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_HEX16(expected, actual) UNITY_TEST_ASSERT_EQUAL_HEX16((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_HEX32(expected, actual) UNITY_TEST_ASSERT_EQUAL_HEX32((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_HEX64(expected, actual) UNITY_TEST_ASSERT_EQUAL_HEX64((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_CHAR(expected, actual) UNITY_TEST_ASSERT_EQUAL_CHAR((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_BITS(mask, expected, actual) UNITY_TEST_ASSERT_BITS((mask), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_BITS_HIGH(mask, actual) UNITY_TEST_ASSERT_BITS((mask), (UNITY_UINT)(-1), (actual), __LINE__, NULL) -#define TEST_ASSERT_BITS_LOW(mask, actual) UNITY_TEST_ASSERT_BITS((mask), (UNITY_UINT)(0), (actual), __LINE__, NULL) -#define TEST_ASSERT_BIT_HIGH(bit, actual) UNITY_TEST_ASSERT_BITS(((UNITY_UINT)1 << (bit)), (UNITY_UINT)(-1), (actual), __LINE__, NULL) -#define TEST_ASSERT_BIT_LOW(bit, actual) UNITY_TEST_ASSERT_BITS(((UNITY_UINT)1 << (bit)), (UNITY_UINT)(0), (actual), __LINE__, NULL) - -/* Integer Not Equal To (of all sizes) */ -#define TEST_ASSERT_NOT_EQUAL_INT(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_INT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL_INT8(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_INT8((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL_INT16(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_INT16((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL_INT32(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_INT32((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL_INT64(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_INT64((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL_UINT(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_UINT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL_UINT8(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_UINT8((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL_UINT16(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_UINT16((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL_UINT32(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_UINT32((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL_UINT64(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_UINT64((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL_size_t(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_UINT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL_HEX8(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_HEX8((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL_HEX16(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_HEX16((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL_HEX32(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_HEX32((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL_HEX64(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_HEX64((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL_CHAR(threshold, actual) UNITY_TEST_ASSERT_NOT_EQUAL_CHAR((threshold), (actual), __LINE__, NULL) - -/* Integer Greater Than/ Less Than (of all sizes) */ -#define TEST_ASSERT_GREATER_THAN(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_INT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_INT(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_INT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_INT8(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_INT8((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_INT16(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_INT16((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_INT32(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_INT32((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_INT64(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_INT64((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_UINT(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_UINT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_UINT8(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_UINT8((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_UINT16(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_UINT16((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_UINT32(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_UINT32((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_UINT64(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_UINT64((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_size_t(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_UINT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_HEX8(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_HEX8((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_HEX16(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_HEX16((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_HEX32(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_HEX32((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_HEX64(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_HEX64((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_THAN_CHAR(threshold, actual) UNITY_TEST_ASSERT_GREATER_THAN_CHAR((threshold), (actual), __LINE__, NULL) - -#define TEST_ASSERT_LESS_THAN(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_INT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_INT(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_INT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_INT8(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_INT8((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_INT16(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_INT16((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_INT32(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_INT32((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_INT64(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_INT64((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_UINT(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_UINT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_UINT8(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_UINT8((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_UINT16(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_UINT16((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_UINT32(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_UINT32((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_UINT64(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_UINT64((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_size_t(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_UINT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_HEX8(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_HEX8((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_HEX16(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_HEX16((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_HEX32(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_HEX32((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_HEX64(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_HEX64((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_THAN_CHAR(threshold, actual) UNITY_TEST_ASSERT_SMALLER_THAN_CHAR((threshold), (actual), __LINE__, NULL) - -#define TEST_ASSERT_GREATER_OR_EQUAL(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_INT(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_INT8(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT8((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_INT16(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT16((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_INT32(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT32((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_INT64(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT64((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_UINT(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_UINT8(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT8((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_UINT16(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT16((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_UINT32(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT32((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_UINT64(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT64((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_size_t(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_HEX8(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX8((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_HEX16(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX16((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_HEX32(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX32((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_HEX64(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX64((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_GREATER_OR_EQUAL_CHAR(threshold, actual) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_CHAR((threshold), (actual), __LINE__, NULL) - -#define TEST_ASSERT_LESS_OR_EQUAL(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_INT(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_INT8(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT8((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_INT16(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT16((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_INT32(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT32((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_INT64(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT64((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_UINT(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_UINT8(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT8((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_UINT16(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT16((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_UINT32(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT32((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_UINT64(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT64((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_size_t(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_HEX8(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX8((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_HEX16(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX16((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_HEX32(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX32((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_HEX64(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX64((threshold), (actual), __LINE__, NULL) -#define TEST_ASSERT_LESS_OR_EQUAL_CHAR(threshold, actual) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_CHAR((threshold), (actual), __LINE__, NULL) - -/* Integer Ranges (of all sizes) */ -#define TEST_ASSERT_INT_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_INT_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_INT8_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_INT8_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_INT16_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_INT16_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_INT32_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_INT32_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_INT64_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_INT64_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_UINT_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_UINT_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_UINT8_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_UINT8_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_UINT16_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_UINT16_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_UINT32_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_UINT32_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_UINT64_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_UINT64_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_size_t_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_UINT_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_HEX_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_HEX32_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_HEX8_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_HEX8_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_HEX16_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_HEX16_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_HEX32_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_HEX32_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_HEX64_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_HEX64_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_CHAR_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_CHAR_WITHIN((delta), (expected), (actual), __LINE__, NULL) - -/* Integer Array Ranges (of all sizes) */ -#define TEST_ASSERT_INT_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_INT_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_INT8_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_INT8_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_INT16_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_INT16_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_INT32_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_INT32_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_INT64_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_INT64_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_UINT_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_UINT_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_UINT8_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_UINT8_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_UINT16_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_UINT16_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_UINT32_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_UINT32_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_UINT64_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_UINT64_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_size_t_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_UINT_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_HEX_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_HEX32_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_HEX8_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_HEX8_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_HEX16_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_HEX16_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_HEX32_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_HEX32_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_HEX64_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_HEX64_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) -#define TEST_ASSERT_CHAR_ARRAY_WITHIN(delta, expected, actual, num_elements) UNITY_TEST_ASSERT_CHAR_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, NULL) - - -/* Structs and Strings */ -#define TEST_ASSERT_EQUAL_PTR(expected, actual) UNITY_TEST_ASSERT_EQUAL_PTR((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_STRING(expected, actual) UNITY_TEST_ASSERT_EQUAL_STRING((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_STRING_LEN(expected, actual, len) UNITY_TEST_ASSERT_EQUAL_STRING_LEN((expected), (actual), (len), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_MEMORY(expected, actual, len) UNITY_TEST_ASSERT_EQUAL_MEMORY((expected), (actual), (len), __LINE__, NULL) - -/* Arrays */ -#define TEST_ASSERT_EQUAL_INT_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_INT_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_INT8_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_INT8_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_INT16_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_INT16_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_INT32_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_INT32_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_INT64_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_INT64_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_UINT_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_UINT_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_UINT8_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_UINT8_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_UINT16_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_UINT16_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_UINT32_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_UINT32_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_UINT64_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_UINT64_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_size_t_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_UINT_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_HEX_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_HEX32_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_HEX8_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_HEX8_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_HEX16_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_HEX16_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_HEX32_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_HEX32_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_HEX64_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_HEX64_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_PTR_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_PTR_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_STRING_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_STRING_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_MEMORY_ARRAY(expected, actual, len, num_elements) UNITY_TEST_ASSERT_EQUAL_MEMORY_ARRAY((expected), (actual), (len), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_CHAR_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_CHAR_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) - -/* Arrays Compared To Single Value */ -#define TEST_ASSERT_EACH_EQUAL_INT(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_INT((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_INT8(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_INT8((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_INT16(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_INT16((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_INT32(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_INT32((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_INT64(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_INT64((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_UINT(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_UINT((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_UINT8(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_UINT8((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_UINT16(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_UINT16((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_UINT32(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_UINT32((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_UINT64(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_UINT64((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_size_t(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_UINT((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_HEX(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_HEX32((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_HEX8(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_HEX8((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_HEX16(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_HEX16((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_HEX32(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_HEX32((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_HEX64(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_HEX64((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_PTR(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_PTR((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_STRING(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_STRING((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_MEMORY(expected, actual, len, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_MEMORY((expected), (actual), (len), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_CHAR(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_CHAR((expected), (actual), (num_elements), __LINE__, NULL) - -/* Floating Point (If Enabled) */ -#define TEST_ASSERT_FLOAT_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_FLOAT_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_FLOAT(expected, actual) UNITY_TEST_ASSERT_EQUAL_FLOAT((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_FLOAT_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_FLOAT_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_FLOAT(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_FLOAT((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_FLOAT_IS_INF(actual) UNITY_TEST_ASSERT_FLOAT_IS_INF((actual), __LINE__, NULL) -#define TEST_ASSERT_FLOAT_IS_NEG_INF(actual) UNITY_TEST_ASSERT_FLOAT_IS_NEG_INF((actual), __LINE__, NULL) -#define TEST_ASSERT_FLOAT_IS_NAN(actual) UNITY_TEST_ASSERT_FLOAT_IS_NAN((actual), __LINE__, NULL) -#define TEST_ASSERT_FLOAT_IS_DETERMINATE(actual) UNITY_TEST_ASSERT_FLOAT_IS_DETERMINATE((actual), __LINE__, NULL) -#define TEST_ASSERT_FLOAT_IS_NOT_INF(actual) UNITY_TEST_ASSERT_FLOAT_IS_NOT_INF((actual), __LINE__, NULL) -#define TEST_ASSERT_FLOAT_IS_NOT_NEG_INF(actual) UNITY_TEST_ASSERT_FLOAT_IS_NOT_NEG_INF((actual), __LINE__, NULL) -#define TEST_ASSERT_FLOAT_IS_NOT_NAN(actual) UNITY_TEST_ASSERT_FLOAT_IS_NOT_NAN((actual), __LINE__, NULL) -#define TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE(actual) UNITY_TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE((actual), __LINE__, NULL) - -/* Double (If Enabled) */ -#define TEST_ASSERT_DOUBLE_WITHIN(delta, expected, actual) UNITY_TEST_ASSERT_DOUBLE_WITHIN((delta), (expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_DOUBLE(expected, actual) UNITY_TEST_ASSERT_EQUAL_DOUBLE((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_EQUAL_DOUBLE_ARRAY(expected, actual, num_elements) UNITY_TEST_ASSERT_EQUAL_DOUBLE_ARRAY((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_EACH_EQUAL_DOUBLE(expected, actual, num_elements) UNITY_TEST_ASSERT_EACH_EQUAL_DOUBLE((expected), (actual), (num_elements), __LINE__, NULL) -#define TEST_ASSERT_DOUBLE_IS_INF(actual) UNITY_TEST_ASSERT_DOUBLE_IS_INF((actual), __LINE__, NULL) -#define TEST_ASSERT_DOUBLE_IS_NEG_INF(actual) UNITY_TEST_ASSERT_DOUBLE_IS_NEG_INF((actual), __LINE__, NULL) -#define TEST_ASSERT_DOUBLE_IS_NAN(actual) UNITY_TEST_ASSERT_DOUBLE_IS_NAN((actual), __LINE__, NULL) -#define TEST_ASSERT_DOUBLE_IS_DETERMINATE(actual) UNITY_TEST_ASSERT_DOUBLE_IS_DETERMINATE((actual), __LINE__, NULL) -#define TEST_ASSERT_DOUBLE_IS_NOT_INF(actual) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_INF((actual), __LINE__, NULL) -#define TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF(actual) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF((actual), __LINE__, NULL) -#define TEST_ASSERT_DOUBLE_IS_NOT_NAN(actual) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NAN((actual), __LINE__, NULL) -#define TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE(actual) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE((actual), __LINE__, NULL) - -/* Shorthand */ -#ifdef UNITY_SHORTHAND_AS_OLD -#define TEST_ASSERT_EQUAL(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL(expected, actual) UNITY_TEST_ASSERT(((expected) != (actual)), __LINE__, " Expected Not-Equal") -#endif -#ifdef UNITY_SHORTHAND_AS_INT -#define TEST_ASSERT_EQUAL(expected, actual) UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL(expected, actual) UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand) -#endif -#ifdef UNITY_SHORTHAND_AS_MEM -#define TEST_ASSERT_EQUAL(expected, actual) UNITY_TEST_ASSERT_EQUAL_MEMORY((&expected), (&actual), sizeof(expected), __LINE__, NULL) -#define TEST_ASSERT_NOT_EQUAL(expected, actual) UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand) -#endif -#ifdef UNITY_SHORTHAND_AS_RAW -#define TEST_ASSERT_EQUAL(expected, actual) UNITY_TEST_ASSERT(((expected) == (actual)), __LINE__, " Expected Equal") -#define TEST_ASSERT_NOT_EQUAL(expected, actual) UNITY_TEST_ASSERT(((expected) != (actual)), __LINE__, " Expected Not-Equal") -#endif -#ifdef UNITY_SHORTHAND_AS_NONE -#define TEST_ASSERT_EQUAL(expected, actual) UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand) -#define TEST_ASSERT_NOT_EQUAL(expected, actual) UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand) -#endif - -/*------------------------------------------------------- - * Test Asserts (with additional messages) - *-------------------------------------------------------*/ - -/* Boolean */ -#define TEST_ASSERT_MESSAGE(condition, message) UNITY_TEST_ASSERT( (condition), __LINE__, (message)) -#define TEST_ASSERT_TRUE_MESSAGE(condition, message) UNITY_TEST_ASSERT( (condition), __LINE__, (message)) -#define TEST_ASSERT_UNLESS_MESSAGE(condition, message) UNITY_TEST_ASSERT( !(condition), __LINE__, (message)) -#define TEST_ASSERT_FALSE_MESSAGE(condition, message) UNITY_TEST_ASSERT( !(condition), __LINE__, (message)) -#define TEST_ASSERT_NULL_MESSAGE(pointer, message) UNITY_TEST_ASSERT_NULL( (pointer), __LINE__, (message)) -#define TEST_ASSERT_NOT_NULL_MESSAGE(pointer, message) UNITY_TEST_ASSERT_NOT_NULL((pointer), __LINE__, (message)) -#define TEST_ASSERT_EMPTY_MESSAGE(pointer, message) UNITY_TEST_ASSERT_EMPTY( (pointer), __LINE__, (message)) -#define TEST_ASSERT_NOT_EMPTY_MESSAGE(pointer, message) UNITY_TEST_ASSERT_NOT_EMPTY((pointer), __LINE__, (message)) - -/* Integers (of all sizes) */ -#define TEST_ASSERT_EQUAL_INT_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_INT8_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT8((expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_INT16_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT16((expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_INT32_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT32((expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_INT64_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT64((expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_UINT_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_UINT( (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_UINT8_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_UINT8( (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_UINT16_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_UINT16( (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_UINT32_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_UINT32( (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_UINT64_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_UINT64( (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_size_t_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_UINT( (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_HEX_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_HEX32((expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_HEX8_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_HEX8( (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_HEX16_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_HEX16((expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_HEX32_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_HEX32((expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_HEX64_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_HEX64((expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_BITS_MESSAGE(mask, expected, actual, message) UNITY_TEST_ASSERT_BITS((mask), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_BITS_HIGH_MESSAGE(mask, actual, message) UNITY_TEST_ASSERT_BITS((mask), (UNITY_UINT32)(-1), (actual), __LINE__, (message)) -#define TEST_ASSERT_BITS_LOW_MESSAGE(mask, actual, message) UNITY_TEST_ASSERT_BITS((mask), (UNITY_UINT32)(0), (actual), __LINE__, (message)) -#define TEST_ASSERT_BIT_HIGH_MESSAGE(bit, actual, message) UNITY_TEST_ASSERT_BITS(((UNITY_UINT32)1 << (bit)), (UNITY_UINT32)(-1), (actual), __LINE__, (message)) -#define TEST_ASSERT_BIT_LOW_MESSAGE(bit, actual, message) UNITY_TEST_ASSERT_BITS(((UNITY_UINT32)1 << (bit)), (UNITY_UINT32)(0), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_CHAR_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_CHAR((expected), (actual), __LINE__, (message)) - -/* Integer Not Equal To (of all sizes) */ -#define TEST_ASSERT_NOT_EQUAL_INT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_INT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_INT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_INT8((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_INT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_INT16((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_INT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_INT32((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_INT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_INT64((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_UINT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_UINT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_UINT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_UINT8((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_UINT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_UINT16((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_UINT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_UINT32((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_UINT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_UINT64((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_size_t_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_UINT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_HEX8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_HEX8((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_HEX16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_HEX16((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_HEX32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_HEX32((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_HEX64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_HEX64((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_CHAR_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_NOT_EQUAL_CHAR((threshold), (actual), __LINE__, (message)) - - -/* Integer Greater Than/ Less Than (of all sizes) */ -#define TEST_ASSERT_GREATER_THAN_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_INT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_INT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_INT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_INT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_INT8((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_INT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_INT16((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_INT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_INT32((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_INT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_INT64((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_UINT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_UINT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_UINT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_UINT8((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_UINT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_UINT16((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_UINT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_UINT32((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_UINT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_UINT64((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_size_t_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_UINT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_HEX8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_HEX8((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_HEX16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_HEX16((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_HEX32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_HEX32((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_HEX64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_HEX64((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_THAN_CHAR_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_THAN_CHAR((threshold), (actual), __LINE__, (message)) - -#define TEST_ASSERT_LESS_THAN_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_INT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_INT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_INT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_INT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_INT8((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_INT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_INT16((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_INT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_INT32((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_INT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_INT64((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_UINT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_UINT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_UINT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_UINT8((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_UINT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_UINT16((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_UINT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_UINT32((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_UINT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_UINT64((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_size_t_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_UINT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_HEX8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_HEX8((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_HEX16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_HEX16((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_HEX32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_HEX32((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_HEX64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_HEX64((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_THAN_CHAR_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_THAN_CHAR((threshold), (actual), __LINE__, (message)) - -#define TEST_ASSERT_GREATER_OR_EQUAL_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_INT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_INT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT8((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_INT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT16((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_INT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT32((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_INT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT64((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_UINT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_UINT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT8((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_UINT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT16((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_UINT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT32((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_UINT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT64((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_size_t_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_HEX8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX8((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_HEX16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX16((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_HEX32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX32((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_HEX64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX64((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_GREATER_OR_EQUAL_CHAR_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_GREATER_OR_EQUAL_CHAR((threshold), (actual), __LINE__, (message)) - -#define TEST_ASSERT_LESS_OR_EQUAL_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_INT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_INT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT8((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_INT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT16((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_INT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT32((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_INT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT64((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_UINT_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_UINT8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT8((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_UINT16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT16((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_UINT32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT32((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_UINT64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT64((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_size_t_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_HEX8_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX8((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_HEX16_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX16((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_HEX32_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX32((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_HEX64_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX64((threshold), (actual), __LINE__, (message)) -#define TEST_ASSERT_LESS_OR_EQUAL_CHAR_MESSAGE(threshold, actual, message) UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_CHAR((threshold), (actual), __LINE__, (message)) - -/* Integer Ranges (of all sizes) */ -#define TEST_ASSERT_INT_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_INT_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_INT8_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_INT8_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_INT16_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_INT16_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_INT32_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_INT32_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_INT64_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_INT64_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_UINT_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_UINT_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_UINT8_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_UINT8_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_UINT16_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_UINT16_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_UINT32_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_UINT32_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_UINT64_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_UINT64_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_size_t_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_UINT_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_HEX_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_HEX32_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_HEX8_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_HEX8_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_HEX16_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_HEX16_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_HEX32_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_HEX32_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_HEX64_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_HEX64_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_CHAR_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_CHAR_WITHIN((delta), (expected), (actual), __LINE__, (message)) - -/* Integer Array Ranges (of all sizes) */ -#define TEST_ASSERT_INT_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_INT_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_INT8_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_INT8_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_INT16_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_INT16_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_INT32_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_INT32_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_INT64_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_INT64_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_UINT_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_UINT_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_UINT8_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_UINT8_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_UINT16_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_UINT16_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_UINT32_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_UINT32_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_UINT64_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_UINT64_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_size_t_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_UINT_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_HEX_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_HEX32_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_HEX8_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_HEX8_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_HEX16_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_HEX16_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_HEX32_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_HEX32_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_HEX64_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_HEX64_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) -#define TEST_ASSERT_CHAR_ARRAY_WITHIN_MESSAGE(delta, expected, actual, num_elements, message) UNITY_TEST_ASSERT_CHAR_ARRAY_WITHIN((delta), (expected), (actual), num_elements, __LINE__, (message)) - - -/* Structs and Strings */ -#define TEST_ASSERT_EQUAL_PTR_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_PTR((expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_STRING_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_STRING((expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_STRING_LEN_MESSAGE(expected, actual, len, message) UNITY_TEST_ASSERT_EQUAL_STRING_LEN((expected), (actual), (len), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_MEMORY_MESSAGE(expected, actual, len, message) UNITY_TEST_ASSERT_EQUAL_MEMORY((expected), (actual), (len), __LINE__, (message)) - -/* Arrays */ -#define TEST_ASSERT_EQUAL_INT_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_INT_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_INT8_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_INT8_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_INT16_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_INT16_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_INT32_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_INT32_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_INT64_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_INT64_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_UINT_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_UINT_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_UINT8_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_UINT8_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_UINT16_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_UINT16_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_UINT32_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_UINT32_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_UINT64_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_UINT64_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_size_t_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_UINT_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_HEX_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_HEX32_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_HEX8_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_HEX8_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_HEX16_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_HEX16_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_HEX32_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_HEX32_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_HEX64_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_HEX64_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_PTR_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_PTR_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_STRING_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_STRING_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_MEMORY_ARRAY_MESSAGE(expected, actual, len, num_elements, message) UNITY_TEST_ASSERT_EQUAL_MEMORY_ARRAY((expected), (actual), (len), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_CHAR_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_CHAR_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) - -/* Arrays Compared To Single Value*/ -#define TEST_ASSERT_EACH_EQUAL_INT_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_INT((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_INT8_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_INT8((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_INT16_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_INT16((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_INT32_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_INT32((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_INT64_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_INT64((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_UINT_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_UINT((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_UINT8_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_UINT8((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_UINT16_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_UINT16((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_UINT32_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_UINT32((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_UINT64_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_UINT64((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_size_t_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_UINT((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_HEX_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_HEX32((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_HEX8_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_HEX8((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_HEX16_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_HEX16((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_HEX32_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_HEX32((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_HEX64_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_HEX64((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_PTR_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_PTR((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_STRING_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_STRING((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_MEMORY_MESSAGE(expected, actual, len, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_MEMORY((expected), (actual), (len), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_CHAR_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_CHAR((expected), (actual), (num_elements), __LINE__, (message)) - -/* Floating Point (If Enabled) */ -#define TEST_ASSERT_FLOAT_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_FLOAT_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_FLOAT_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_FLOAT((expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_FLOAT_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_FLOAT_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_FLOAT_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_FLOAT((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_FLOAT_IS_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_INF((actual), __LINE__, (message)) -#define TEST_ASSERT_FLOAT_IS_NEG_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_NEG_INF((actual), __LINE__, (message)) -#define TEST_ASSERT_FLOAT_IS_NAN_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_NAN((actual), __LINE__, (message)) -#define TEST_ASSERT_FLOAT_IS_DETERMINATE_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_DETERMINATE((actual), __LINE__, (message)) -#define TEST_ASSERT_FLOAT_IS_NOT_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_NOT_INF((actual), __LINE__, (message)) -#define TEST_ASSERT_FLOAT_IS_NOT_NEG_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_NOT_NEG_INF((actual), __LINE__, (message)) -#define TEST_ASSERT_FLOAT_IS_NOT_NAN_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_NOT_NAN((actual), __LINE__, (message)) -#define TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE_MESSAGE(actual, message) UNITY_TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE((actual), __LINE__, (message)) - -/* Double (If Enabled) */ -#define TEST_ASSERT_DOUBLE_WITHIN_MESSAGE(delta, expected, actual, message) UNITY_TEST_ASSERT_DOUBLE_WITHIN((delta), (expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_DOUBLE_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_DOUBLE((expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_EQUAL_DOUBLE_ARRAY_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EQUAL_DOUBLE_ARRAY((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_EACH_EQUAL_DOUBLE_MESSAGE(expected, actual, num_elements, message) UNITY_TEST_ASSERT_EACH_EQUAL_DOUBLE((expected), (actual), (num_elements), __LINE__, (message)) -#define TEST_ASSERT_DOUBLE_IS_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_INF((actual), __LINE__, (message)) -#define TEST_ASSERT_DOUBLE_IS_NEG_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_NEG_INF((actual), __LINE__, (message)) -#define TEST_ASSERT_DOUBLE_IS_NAN_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_NAN((actual), __LINE__, (message)) -#define TEST_ASSERT_DOUBLE_IS_DETERMINATE_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_DETERMINATE((actual), __LINE__, (message)) -#define TEST_ASSERT_DOUBLE_IS_NOT_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_INF((actual), __LINE__, (message)) -#define TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF((actual), __LINE__, (message)) -#define TEST_ASSERT_DOUBLE_IS_NOT_NAN_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NAN((actual), __LINE__, (message)) -#define TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE_MESSAGE(actual, message) UNITY_TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE((actual), __LINE__, (message)) - -/* Shorthand */ -#ifdef UNITY_SHORTHAND_AS_OLD -#define TEST_ASSERT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, (message)) -#define TEST_ASSERT_NOT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT(((expected) != (actual)), __LINE__, (message)) -#endif -#ifdef UNITY_SHORTHAND_AS_INT -#define TEST_ASSERT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_INT((expected), (actual), __LINE__, message) -#define TEST_ASSERT_NOT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand) -#endif -#ifdef UNITY_SHORTHAND_AS_MEM -#define TEST_ASSERT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT_EQUAL_MEMORY((&expected), (&actual), sizeof(expected), __LINE__, message) -#define TEST_ASSERT_NOT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand) -#endif -#ifdef UNITY_SHORTHAND_AS_RAW -#define TEST_ASSERT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT(((expected) == (actual)), __LINE__, message) -#define TEST_ASSERT_NOT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_ASSERT(((expected) != (actual)), __LINE__, message) -#endif -#ifdef UNITY_SHORTHAND_AS_NONE -#define TEST_ASSERT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand) -#define TEST_ASSERT_NOT_EQUAL_MESSAGE(expected, actual, message) UNITY_TEST_FAIL(__LINE__, UnityStrErrShorthand) -#endif - -/* end of UNITY_FRAMEWORK_H */ -#ifdef __cplusplus -} -#endif -#endif diff --git a/test/unit-test/vendor/ceedling/vendor/unity/src/unity_internals.h b/test/unit-test/vendor/ceedling/vendor/unity/src/unity_internals.h deleted file mode 100644 index d66309f96..000000000 --- a/test/unit-test/vendor/ceedling/vendor/unity/src/unity_internals.h +++ /dev/null @@ -1,1053 +0,0 @@ -/* ========================================== - Unity Project - A Test Framework for C - Copyright (c) 2007-21 Mike Karlesky, Mark VanderVoord, Greg Williams - [Released under MIT License. Please refer to license.txt for details] -========================================== */ - -#ifndef UNITY_INTERNALS_H -#define UNITY_INTERNALS_H - -#ifdef UNITY_INCLUDE_CONFIG_H -#include "unity_config.h" -#endif - -#ifndef UNITY_EXCLUDE_SETJMP_H -#include <setjmp.h> -#endif - -#ifndef UNITY_EXCLUDE_MATH_H -#include <math.h> -#endif - -#ifndef UNITY_EXCLUDE_STDDEF_H -#include <stddef.h> -#endif - -#ifdef UNITY_INCLUDE_PRINT_FORMATTED -#include <stdarg.h> -#endif - -/* Unity Attempts to Auto-Detect Integer Types - * Attempt 1: UINT_MAX, ULONG_MAX in <limits.h>, or default to 32 bits - * Attempt 2: UINTPTR_MAX in <stdint.h>, or default to same size as long - * The user may override any of these derived constants: - * UNITY_INT_WIDTH, UNITY_LONG_WIDTH, UNITY_POINTER_WIDTH */ -#ifndef UNITY_EXCLUDE_STDINT_H -#include <stdint.h> -#endif - -#ifndef UNITY_EXCLUDE_LIMITS_H -#include <limits.h> -#endif - -#if defined(__GNUC__) || defined(__clang__) - #define UNITY_FUNCTION_ATTR(a) __attribute__((a)) -#else - #define UNITY_FUNCTION_ATTR(a) /* ignore */ -#endif - -#ifndef UNITY_NORETURN - #if defined(__cplusplus) - #if __cplusplus >= 201103L - #define UNITY_NORETURN [[ noreturn ]] - #endif - #elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L - #include <stdnoreturn.h> - #define UNITY_NORETURN noreturn - #endif -#endif -#ifndef UNITY_NORETURN - #define UNITY_NORETURN UNITY_FUNCTION_ATTR(noreturn) -#endif - -/*------------------------------------------------------- - * Guess Widths If Not Specified - *-------------------------------------------------------*/ - -/* Determine the size of an int, if not already specified. - * We cannot use sizeof(int), because it is not yet defined - * at this stage in the translation of the C program. - * Also sizeof(int) does return the size in addressable units on all platforms, - * which may not necessarily be the size in bytes. - * Therefore, infer it from UINT_MAX if possible. */ -#ifndef UNITY_INT_WIDTH - #ifdef UINT_MAX - #if (UINT_MAX == 0xFFFF) - #define UNITY_INT_WIDTH (16) - #elif (UINT_MAX == 0xFFFFFFFF) - #define UNITY_INT_WIDTH (32) - #elif (UINT_MAX == 0xFFFFFFFFFFFFFFFF) - #define UNITY_INT_WIDTH (64) - #endif - #else /* Set to default */ - #define UNITY_INT_WIDTH (32) - #endif /* UINT_MAX */ -#endif - -/* Determine the size of a long, if not already specified. */ -#ifndef UNITY_LONG_WIDTH - #ifdef ULONG_MAX - #if (ULONG_MAX == 0xFFFF) - #define UNITY_LONG_WIDTH (16) - #elif (ULONG_MAX == 0xFFFFFFFF) - #define UNITY_LONG_WIDTH (32) - #elif (ULONG_MAX == 0xFFFFFFFFFFFFFFFF) - #define UNITY_LONG_WIDTH (64) - #endif - #else /* Set to default */ - #define UNITY_LONG_WIDTH (32) - #endif /* ULONG_MAX */ -#endif - -/* Determine the size of a pointer, if not already specified. */ -#ifndef UNITY_POINTER_WIDTH - #ifdef UINTPTR_MAX - #if (UINTPTR_MAX <= 0xFFFF) - #define UNITY_POINTER_WIDTH (16) - #elif (UINTPTR_MAX <= 0xFFFFFFFF) - #define UNITY_POINTER_WIDTH (32) - #elif (UINTPTR_MAX <= 0xFFFFFFFFFFFFFFFF) - #define UNITY_POINTER_WIDTH (64) - #endif - #else /* Set to default */ - #define UNITY_POINTER_WIDTH UNITY_LONG_WIDTH - #endif /* UINTPTR_MAX */ -#endif - -/*------------------------------------------------------- - * Int Support (Define types based on detected sizes) - *-------------------------------------------------------*/ - -#if (UNITY_INT_WIDTH == 32) - typedef unsigned char UNITY_UINT8; - typedef unsigned short UNITY_UINT16; - typedef unsigned int UNITY_UINT32; - typedef signed char UNITY_INT8; - typedef signed short UNITY_INT16; - typedef signed int UNITY_INT32; -#elif (UNITY_INT_WIDTH == 16) - typedef unsigned char UNITY_UINT8; - typedef unsigned int UNITY_UINT16; - typedef unsigned long UNITY_UINT32; - typedef signed char UNITY_INT8; - typedef signed int UNITY_INT16; - typedef signed long UNITY_INT32; -#else - #error Invalid UNITY_INT_WIDTH specified! (16 or 32 are supported) -#endif - -/*------------------------------------------------------- - * 64-bit Support - *-------------------------------------------------------*/ - -/* Auto-detect 64 Bit Support */ -#ifndef UNITY_SUPPORT_64 - #if UNITY_LONG_WIDTH == 64 || UNITY_POINTER_WIDTH == 64 - #define UNITY_SUPPORT_64 - #endif -#endif - -/* 64-Bit Support Dependent Configuration */ -#ifndef UNITY_SUPPORT_64 - /* No 64-bit Support */ - typedef UNITY_UINT32 UNITY_UINT; - typedef UNITY_INT32 UNITY_INT; - #define UNITY_MAX_NIBBLES (8) /* Maximum number of nibbles in a UNITY_(U)INT */ -#else - /* 64-bit Support */ - #if (UNITY_LONG_WIDTH == 32) - typedef unsigned long long UNITY_UINT64; - typedef signed long long UNITY_INT64; - #elif (UNITY_LONG_WIDTH == 64) - typedef unsigned long UNITY_UINT64; - typedef signed long UNITY_INT64; - #else - #error Invalid UNITY_LONG_WIDTH specified! (32 or 64 are supported) - #endif - typedef UNITY_UINT64 UNITY_UINT; - typedef UNITY_INT64 UNITY_INT; - #define UNITY_MAX_NIBBLES (16) /* Maximum number of nibbles in a UNITY_(U)INT */ -#endif - -/*------------------------------------------------------- - * Pointer Support - *-------------------------------------------------------*/ - -#if (UNITY_POINTER_WIDTH == 32) - #define UNITY_PTR_TO_INT UNITY_INT32 - #define UNITY_DISPLAY_STYLE_POINTER UNITY_DISPLAY_STYLE_HEX32 -#elif (UNITY_POINTER_WIDTH == 64) - #define UNITY_PTR_TO_INT UNITY_INT64 - #define UNITY_DISPLAY_STYLE_POINTER UNITY_DISPLAY_STYLE_HEX64 -#elif (UNITY_POINTER_WIDTH == 16) - #define UNITY_PTR_TO_INT UNITY_INT16 - #define UNITY_DISPLAY_STYLE_POINTER UNITY_DISPLAY_STYLE_HEX16 -#else - #error Invalid UNITY_POINTER_WIDTH specified! (16, 32 or 64 are supported) -#endif - -#ifndef UNITY_PTR_ATTRIBUTE - #define UNITY_PTR_ATTRIBUTE -#endif - -#ifndef UNITY_INTERNAL_PTR - #define UNITY_INTERNAL_PTR UNITY_PTR_ATTRIBUTE const void* -#endif - -/*------------------------------------------------------- - * Float Support - *-------------------------------------------------------*/ - -#ifdef UNITY_EXCLUDE_FLOAT - -/* No Floating Point Support */ -#ifndef UNITY_EXCLUDE_DOUBLE -#define UNITY_EXCLUDE_DOUBLE /* Remove double when excluding float support */ -#endif -#ifndef UNITY_EXCLUDE_FLOAT_PRINT -#define UNITY_EXCLUDE_FLOAT_PRINT -#endif - -#else - -/* Floating Point Support */ -#ifndef UNITY_FLOAT_PRECISION -#define UNITY_FLOAT_PRECISION (0.00001f) -#endif -#ifndef UNITY_FLOAT_TYPE -#define UNITY_FLOAT_TYPE float -#endif -typedef UNITY_FLOAT_TYPE UNITY_FLOAT; - -/* isinf & isnan macros should be provided by math.h */ -#ifndef isinf -/* The value of Inf - Inf is NaN */ -#define isinf(n) (isnan((n) - (n)) && !isnan(n)) -#endif - -#ifndef isnan -/* NaN is the only floating point value that does NOT equal itself. - * Therefore if n != n, then it is NaN. */ -#define isnan(n) ((n != n) ? 1 : 0) -#endif - -#endif - -/*------------------------------------------------------- - * Double Float Support - *-------------------------------------------------------*/ - -/* unlike float, we DON'T include by default */ -#if defined(UNITY_EXCLUDE_DOUBLE) || !defined(UNITY_INCLUDE_DOUBLE) - - /* No Floating Point Support */ - #ifndef UNITY_EXCLUDE_DOUBLE - #define UNITY_EXCLUDE_DOUBLE - #else - #undef UNITY_INCLUDE_DOUBLE - #endif - - #ifndef UNITY_EXCLUDE_FLOAT - #ifndef UNITY_DOUBLE_TYPE - #define UNITY_DOUBLE_TYPE double - #endif - typedef UNITY_FLOAT UNITY_DOUBLE; - /* For parameter in UnityPrintFloat(UNITY_DOUBLE), which aliases to double or float */ - #endif - -#else - - /* Double Floating Point Support */ - #ifndef UNITY_DOUBLE_PRECISION - #define UNITY_DOUBLE_PRECISION (1e-12) - #endif - - #ifndef UNITY_DOUBLE_TYPE - #define UNITY_DOUBLE_TYPE double - #endif - typedef UNITY_DOUBLE_TYPE UNITY_DOUBLE; - -#endif - -/*------------------------------------------------------- - * Output Method: stdout (DEFAULT) - *-------------------------------------------------------*/ -#ifndef UNITY_OUTPUT_CHAR - /* Default to using putchar, which is defined in stdio.h */ - #include <stdio.h> - #define UNITY_OUTPUT_CHAR(a) (void)putchar(a) -#else - /* If defined as something else, make sure we declare it here so it's ready for use */ - #ifdef UNITY_OUTPUT_CHAR_HEADER_DECLARATION - extern void UNITY_OUTPUT_CHAR_HEADER_DECLARATION; - #endif -#endif - -#ifndef UNITY_OUTPUT_FLUSH - #ifdef UNITY_USE_FLUSH_STDOUT - /* We want to use the stdout flush utility */ - #include <stdio.h> - #define UNITY_OUTPUT_FLUSH() (void)fflush(stdout) - #else - /* We've specified nothing, therefore flush should just be ignored */ - #define UNITY_OUTPUT_FLUSH() - #endif -#else - /* If defined as something else, make sure we declare it here so it's ready for use */ - #ifdef UNITY_OUTPUT_FLUSH_HEADER_DECLARATION - extern void UNITY_OUTPUT_FLUSH_HEADER_DECLARATION; - #endif -#endif - -#ifndef UNITY_OUTPUT_FLUSH -#define UNITY_FLUSH_CALL() -#else -#define UNITY_FLUSH_CALL() UNITY_OUTPUT_FLUSH() -#endif - -#ifndef UNITY_PRINT_EOL -#define UNITY_PRINT_EOL() UNITY_OUTPUT_CHAR('\n') -#endif - -#ifndef UNITY_OUTPUT_START -#define UNITY_OUTPUT_START() -#endif - -#ifndef UNITY_OUTPUT_COMPLETE -#define UNITY_OUTPUT_COMPLETE() -#endif - -#ifdef UNITY_INCLUDE_EXEC_TIME - #if !defined(UNITY_EXEC_TIME_START) && \ - !defined(UNITY_EXEC_TIME_STOP) && \ - !defined(UNITY_PRINT_EXEC_TIME) && \ - !defined(UNITY_TIME_TYPE) - /* If none any of these macros are defined then try to provide a default implementation */ - - #if defined(UNITY_CLOCK_MS) - /* This is a simple way to get a default implementation on platforms that support getting a millisecond counter */ - #define UNITY_TIME_TYPE UNITY_UINT - #define UNITY_EXEC_TIME_START() Unity.CurrentTestStartTime = UNITY_CLOCK_MS() - #define UNITY_EXEC_TIME_STOP() Unity.CurrentTestStopTime = UNITY_CLOCK_MS() - #define UNITY_PRINT_EXEC_TIME() { \ - UNITY_UINT execTimeMs = (Unity.CurrentTestStopTime - Unity.CurrentTestStartTime); \ - UnityPrint(" ("); \ - UnityPrintNumberUnsigned(execTimeMs); \ - UnityPrint(" ms)"); \ - } - #elif defined(_WIN32) - #include <time.h> - #define UNITY_TIME_TYPE clock_t - #define UNITY_GET_TIME(t) t = (clock_t)((clock() * 1000) / CLOCKS_PER_SEC) - #define UNITY_EXEC_TIME_START() UNITY_GET_TIME(Unity.CurrentTestStartTime) - #define UNITY_EXEC_TIME_STOP() UNITY_GET_TIME(Unity.CurrentTestStopTime) - #define UNITY_PRINT_EXEC_TIME() { \ - UNITY_UINT execTimeMs = (Unity.CurrentTestStopTime - Unity.CurrentTestStartTime); \ - UnityPrint(" ("); \ - UnityPrintNumberUnsigned(execTimeMs); \ - UnityPrint(" ms)"); \ - } - #elif defined(__unix__) || defined(__APPLE__) - #include <time.h> - #define UNITY_TIME_TYPE struct timespec - #define UNITY_GET_TIME(t) clock_gettime(CLOCK_MONOTONIC, &t) - #define UNITY_EXEC_TIME_START() UNITY_GET_TIME(Unity.CurrentTestStartTime) - #define UNITY_EXEC_TIME_STOP() UNITY_GET_TIME(Unity.CurrentTestStopTime) - #define UNITY_PRINT_EXEC_TIME() { \ - UNITY_UINT execTimeMs = ((Unity.CurrentTestStopTime.tv_sec - Unity.CurrentTestStartTime.tv_sec) * 1000L); \ - execTimeMs += ((Unity.CurrentTestStopTime.tv_nsec - Unity.CurrentTestStartTime.tv_nsec) / 1000000L); \ - UnityPrint(" ("); \ - UnityPrintNumberUnsigned(execTimeMs); \ - UnityPrint(" ms)"); \ - } - #endif - #endif -#endif - -#ifndef UNITY_EXEC_TIME_START -#define UNITY_EXEC_TIME_START() do{}while(0) -#endif - -#ifndef UNITY_EXEC_TIME_STOP -#define UNITY_EXEC_TIME_STOP() do{}while(0) -#endif - -#ifndef UNITY_TIME_TYPE -#define UNITY_TIME_TYPE UNITY_UINT -#endif - -#ifndef UNITY_PRINT_EXEC_TIME -#define UNITY_PRINT_EXEC_TIME() do{}while(0) -#endif - -/*------------------------------------------------------- - * Footprint - *-------------------------------------------------------*/ - -#ifndef UNITY_LINE_TYPE -#define UNITY_LINE_TYPE UNITY_UINT -#endif - -#ifndef UNITY_COUNTER_TYPE -#define UNITY_COUNTER_TYPE UNITY_UINT -#endif - -/*------------------------------------------------------- - * Internal Structs Needed - *-------------------------------------------------------*/ - -typedef void (*UnityTestFunction)(void); - -#define UNITY_DISPLAY_RANGE_INT (0x10) -#define UNITY_DISPLAY_RANGE_UINT (0x20) -#define UNITY_DISPLAY_RANGE_HEX (0x40) -#define UNITY_DISPLAY_RANGE_CHAR (0x80) - -typedef enum -{ - UNITY_DISPLAY_STYLE_INT = (UNITY_INT_WIDTH / 8) + UNITY_DISPLAY_RANGE_INT, - UNITY_DISPLAY_STYLE_INT8 = 1 + UNITY_DISPLAY_RANGE_INT, - UNITY_DISPLAY_STYLE_INT16 = 2 + UNITY_DISPLAY_RANGE_INT, - UNITY_DISPLAY_STYLE_INT32 = 4 + UNITY_DISPLAY_RANGE_INT, -#ifdef UNITY_SUPPORT_64 - UNITY_DISPLAY_STYLE_INT64 = 8 + UNITY_DISPLAY_RANGE_INT, -#endif - - UNITY_DISPLAY_STYLE_UINT = (UNITY_INT_WIDTH / 8) + UNITY_DISPLAY_RANGE_UINT, - UNITY_DISPLAY_STYLE_UINT8 = 1 + UNITY_DISPLAY_RANGE_UINT, - UNITY_DISPLAY_STYLE_UINT16 = 2 + UNITY_DISPLAY_RANGE_UINT, - UNITY_DISPLAY_STYLE_UINT32 = 4 + UNITY_DISPLAY_RANGE_UINT, -#ifdef UNITY_SUPPORT_64 - UNITY_DISPLAY_STYLE_UINT64 = 8 + UNITY_DISPLAY_RANGE_UINT, -#endif - - UNITY_DISPLAY_STYLE_HEX8 = 1 + UNITY_DISPLAY_RANGE_HEX, - UNITY_DISPLAY_STYLE_HEX16 = 2 + UNITY_DISPLAY_RANGE_HEX, - UNITY_DISPLAY_STYLE_HEX32 = 4 + UNITY_DISPLAY_RANGE_HEX, -#ifdef UNITY_SUPPORT_64 - UNITY_DISPLAY_STYLE_HEX64 = 8 + UNITY_DISPLAY_RANGE_HEX, -#endif - - UNITY_DISPLAY_STYLE_CHAR = 1 + UNITY_DISPLAY_RANGE_CHAR + UNITY_DISPLAY_RANGE_INT, - - UNITY_DISPLAY_STYLE_UNKNOWN -} UNITY_DISPLAY_STYLE_T; - -typedef enum -{ - UNITY_WITHIN = 0x0, - UNITY_EQUAL_TO = 0x1, - UNITY_GREATER_THAN = 0x2, - UNITY_GREATER_OR_EQUAL = 0x2 + UNITY_EQUAL_TO, - UNITY_SMALLER_THAN = 0x4, - UNITY_SMALLER_OR_EQUAL = 0x4 + UNITY_EQUAL_TO, - UNITY_NOT_EQUAL = 0x0, - UNITY_UNKNOWN -} UNITY_COMPARISON_T; - -#ifndef UNITY_EXCLUDE_FLOAT -typedef enum UNITY_FLOAT_TRAIT -{ - UNITY_FLOAT_IS_NOT_INF = 0, - UNITY_FLOAT_IS_INF, - UNITY_FLOAT_IS_NOT_NEG_INF, - UNITY_FLOAT_IS_NEG_INF, - UNITY_FLOAT_IS_NOT_NAN, - UNITY_FLOAT_IS_NAN, - UNITY_FLOAT_IS_NOT_DET, - UNITY_FLOAT_IS_DET, - UNITY_FLOAT_INVALID_TRAIT -} UNITY_FLOAT_TRAIT_T; -#endif - -typedef enum -{ - UNITY_ARRAY_TO_VAL = 0, - UNITY_ARRAY_TO_ARRAY, - UNITY_ARRAY_UNKNOWN -} UNITY_FLAGS_T; - -struct UNITY_STORAGE_T -{ - const char* TestFile; - const char* CurrentTestName; -#ifndef UNITY_EXCLUDE_DETAILS - const char* CurrentDetail1; - const char* CurrentDetail2; -#endif - UNITY_LINE_TYPE CurrentTestLineNumber; - UNITY_COUNTER_TYPE NumberOfTests; - UNITY_COUNTER_TYPE TestFailures; - UNITY_COUNTER_TYPE TestIgnores; - UNITY_COUNTER_TYPE CurrentTestFailed; - UNITY_COUNTER_TYPE CurrentTestIgnored; -#ifdef UNITY_INCLUDE_EXEC_TIME - UNITY_TIME_TYPE CurrentTestStartTime; - UNITY_TIME_TYPE CurrentTestStopTime; -#endif -#ifndef UNITY_EXCLUDE_SETJMP_H - jmp_buf AbortFrame; -#endif -}; - -extern struct UNITY_STORAGE_T Unity; - -/*------------------------------------------------------- - * Test Suite Management - *-------------------------------------------------------*/ - -void UnityBegin(const char* filename); -int UnityEnd(void); -void UnitySetTestFile(const char* filename); -void UnityConcludeTest(void); - -#ifndef RUN_TEST -void UnityDefaultTestRun(UnityTestFunction Func, const char* FuncName, const int FuncLineNum); -#else -#define UNITY_SKIP_DEFAULT_RUNNER -#endif - -/*------------------------------------------------------- - * Details Support - *-------------------------------------------------------*/ - -#ifdef UNITY_EXCLUDE_DETAILS -#define UNITY_CLR_DETAILS() -#define UNITY_SET_DETAIL(d1) -#define UNITY_SET_DETAILS(d1,d2) -#else -#define UNITY_CLR_DETAILS() { Unity.CurrentDetail1 = 0; Unity.CurrentDetail2 = 0; } -#define UNITY_SET_DETAIL(d1) { Unity.CurrentDetail1 = (d1); Unity.CurrentDetail2 = 0; } -#define UNITY_SET_DETAILS(d1,d2) { Unity.CurrentDetail1 = (d1); Unity.CurrentDetail2 = (d2); } - -#ifndef UNITY_DETAIL1_NAME -#define UNITY_DETAIL1_NAME "Function" -#endif - -#ifndef UNITY_DETAIL2_NAME -#define UNITY_DETAIL2_NAME "Argument" -#endif -#endif - -#ifdef UNITY_PRINT_TEST_CONTEXT -void UNITY_PRINT_TEST_CONTEXT(void); -#endif - -/*------------------------------------------------------- - * Test Output - *-------------------------------------------------------*/ - -void UnityPrint(const char* string); - -#ifdef UNITY_INCLUDE_PRINT_FORMATTED -void UnityPrintF(const UNITY_LINE_TYPE line, const char* format, ...); -#endif - -void UnityPrintLen(const char* string, const UNITY_UINT32 length); -void UnityPrintMask(const UNITY_UINT mask, const UNITY_UINT number); -void UnityPrintNumberByStyle(const UNITY_INT number, const UNITY_DISPLAY_STYLE_T style); -void UnityPrintNumber(const UNITY_INT number_to_print); -void UnityPrintNumberUnsigned(const UNITY_UINT number); -void UnityPrintNumberHex(const UNITY_UINT number, const char nibbles_to_print); - -#ifndef UNITY_EXCLUDE_FLOAT_PRINT -void UnityPrintFloat(const UNITY_DOUBLE input_number); -#endif - -/*------------------------------------------------------- - * Test Assertion Functions - *------------------------------------------------------- - * Use the macros below this section instead of calling - * these directly. The macros have a consistent naming - * convention and will pull in file and line information - * for you. */ - -void UnityAssertEqualNumber(const UNITY_INT expected, - const UNITY_INT actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_DISPLAY_STYLE_T style); - -void UnityAssertGreaterOrLessOrEqualNumber(const UNITY_INT threshold, - const UNITY_INT actual, - const UNITY_COMPARISON_T compare, - const char *msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_DISPLAY_STYLE_T style); - -void UnityAssertEqualIntArray(UNITY_INTERNAL_PTR expected, - UNITY_INTERNAL_PTR actual, - const UNITY_UINT32 num_elements, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_DISPLAY_STYLE_T style, - const UNITY_FLAGS_T flags); - -void UnityAssertBits(const UNITY_INT mask, - const UNITY_INT expected, - const UNITY_INT actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber); - -void UnityAssertEqualString(const char* expected, - const char* actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber); - -void UnityAssertEqualStringLen(const char* expected, - const char* actual, - const UNITY_UINT32 length, - const char* msg, - const UNITY_LINE_TYPE lineNumber); - -void UnityAssertEqualStringArray( UNITY_INTERNAL_PTR expected, - const char** actual, - const UNITY_UINT32 num_elements, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_FLAGS_T flags); - -void UnityAssertEqualMemory( UNITY_INTERNAL_PTR expected, - UNITY_INTERNAL_PTR actual, - const UNITY_UINT32 length, - const UNITY_UINT32 num_elements, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_FLAGS_T flags); - -void UnityAssertNumbersWithin(const UNITY_UINT delta, - const UNITY_INT expected, - const UNITY_INT actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_DISPLAY_STYLE_T style); - -void UnityAssertNumbersArrayWithin(const UNITY_UINT delta, - UNITY_INTERNAL_PTR expected, - UNITY_INTERNAL_PTR actual, - const UNITY_UINT32 num_elements, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_DISPLAY_STYLE_T style, - const UNITY_FLAGS_T flags); - -#ifndef UNITY_EXCLUDE_SETJMP_H -UNITY_NORETURN void UnityFail(const char* msg, const UNITY_LINE_TYPE line); -UNITY_NORETURN void UnityIgnore(const char* msg, const UNITY_LINE_TYPE line); -#else -void UnityFail(const char* msg, const UNITY_LINE_TYPE line); -void UnityIgnore(const char* msg, const UNITY_LINE_TYPE line); -#endif - -void UnityMessage(const char* msg, const UNITY_LINE_TYPE line); - -#ifndef UNITY_EXCLUDE_FLOAT -void UnityAssertFloatsWithin(const UNITY_FLOAT delta, - const UNITY_FLOAT expected, - const UNITY_FLOAT actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber); - -void UnityAssertEqualFloatArray(UNITY_PTR_ATTRIBUTE const UNITY_FLOAT* expected, - UNITY_PTR_ATTRIBUTE const UNITY_FLOAT* actual, - const UNITY_UINT32 num_elements, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_FLAGS_T flags); - -void UnityAssertFloatSpecial(const UNITY_FLOAT actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_FLOAT_TRAIT_T style); -#endif - -#ifndef UNITY_EXCLUDE_DOUBLE -void UnityAssertDoublesWithin(const UNITY_DOUBLE delta, - const UNITY_DOUBLE expected, - const UNITY_DOUBLE actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber); - -void UnityAssertEqualDoubleArray(UNITY_PTR_ATTRIBUTE const UNITY_DOUBLE* expected, - UNITY_PTR_ATTRIBUTE const UNITY_DOUBLE* actual, - const UNITY_UINT32 num_elements, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_FLAGS_T flags); - -void UnityAssertDoubleSpecial(const UNITY_DOUBLE actual, - const char* msg, - const UNITY_LINE_TYPE lineNumber, - const UNITY_FLOAT_TRAIT_T style); -#endif - -/*------------------------------------------------------- - * Helpers - *-------------------------------------------------------*/ - -UNITY_INTERNAL_PTR UnityNumToPtr(const UNITY_INT num, const UNITY_UINT8 size); -#ifndef UNITY_EXCLUDE_FLOAT -UNITY_INTERNAL_PTR UnityFloatToPtr(const float num); -#endif -#ifndef UNITY_EXCLUDE_DOUBLE -UNITY_INTERNAL_PTR UnityDoubleToPtr(const double num); -#endif - -/*------------------------------------------------------- - * Error Strings We Might Need - *-------------------------------------------------------*/ - -extern const char UnityStrOk[]; -extern const char UnityStrPass[]; -extern const char UnityStrFail[]; -extern const char UnityStrIgnore[]; - -extern const char UnityStrErrFloat[]; -extern const char UnityStrErrDouble[]; -extern const char UnityStrErr64[]; -extern const char UnityStrErrShorthand[]; - -/*------------------------------------------------------- - * Test Running Macros - *-------------------------------------------------------*/ - -#ifndef UNITY_EXCLUDE_SETJMP_H -#define TEST_PROTECT() (setjmp(Unity.AbortFrame) == 0) -#define TEST_ABORT() longjmp(Unity.AbortFrame, 1) -#else -#define TEST_PROTECT() 1 -#define TEST_ABORT() return -#endif - -/* This tricky series of macros gives us an optional line argument to treat it as RUN_TEST(func, num=__LINE__) */ -#ifndef RUN_TEST -#ifdef __STDC_VERSION__ -#if __STDC_VERSION__ >= 199901L -#define UNITY_SUPPORT_VARIADIC_MACROS -#endif -#endif -#ifdef UNITY_SUPPORT_VARIADIC_MACROS -#define RUN_TEST(...) RUN_TEST_AT_LINE(__VA_ARGS__, __LINE__, throwaway) -#define RUN_TEST_AT_LINE(func, line, ...) UnityDefaultTestRun(func, #func, line) -#endif -#endif - -/* If we can't do the tricky version, we'll just have to require them to always include the line number */ -#ifndef RUN_TEST -#ifdef CMOCK -#define RUN_TEST(func, num) UnityDefaultTestRun(func, #func, num) -#else -#define RUN_TEST(func) UnityDefaultTestRun(func, #func, __LINE__) -#endif -#endif - -#define TEST_LINE_NUM (Unity.CurrentTestLineNumber) -#define TEST_IS_IGNORED (Unity.CurrentTestIgnored) -#define UNITY_NEW_TEST(a) \ - Unity.CurrentTestName = (a); \ - Unity.CurrentTestLineNumber = (UNITY_LINE_TYPE)(__LINE__); \ - Unity.NumberOfTests++; - -#ifndef UNITY_BEGIN -#define UNITY_BEGIN() UnityBegin(__FILE__) -#endif - -#ifndef UNITY_END -#define UNITY_END() UnityEnd() -#endif - -#ifndef UNITY_SHORTHAND_AS_INT -#ifndef UNITY_SHORTHAND_AS_MEM -#ifndef UNITY_SHORTHAND_AS_NONE -#ifndef UNITY_SHORTHAND_AS_RAW -#define UNITY_SHORTHAND_AS_OLD -#endif -#endif -#endif -#endif - -/*----------------------------------------------- - * Command Line Argument Support - *-----------------------------------------------*/ - -#ifdef UNITY_USE_COMMAND_LINE_ARGS -int UnityParseOptions(int argc, char** argv); -int UnityTestMatches(void); -#endif - -/*------------------------------------------------------- - * Basic Fail and Ignore - *-------------------------------------------------------*/ - -#define UNITY_TEST_FAIL(line, message) UnityFail( (message), (UNITY_LINE_TYPE)(line)) -#define UNITY_TEST_IGNORE(line, message) UnityIgnore( (message), (UNITY_LINE_TYPE)(line)) - -/*------------------------------------------------------- - * Test Asserts - *-------------------------------------------------------*/ - -#define UNITY_TEST_ASSERT(condition, line, message) do {if (condition) {} else {UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), (message));}} while(0) -#define UNITY_TEST_ASSERT_NULL(pointer, line, message) UNITY_TEST_ASSERT(((pointer) == NULL), (UNITY_LINE_TYPE)(line), (message)) -#define UNITY_TEST_ASSERT_NOT_NULL(pointer, line, message) UNITY_TEST_ASSERT(((pointer) != NULL), (UNITY_LINE_TYPE)(line), (message)) -#define UNITY_TEST_ASSERT_EMPTY(pointer, line, message) UNITY_TEST_ASSERT(((pointer[0]) == 0), (UNITY_LINE_TYPE)(line), (message)) -#define UNITY_TEST_ASSERT_NOT_EMPTY(pointer, line, message) UNITY_TEST_ASSERT(((pointer[0]) != 0), (UNITY_LINE_TYPE)(line), (message)) - -#define UNITY_TEST_ASSERT_EQUAL_INT(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) -#define UNITY_TEST_ASSERT_EQUAL_INT8(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT8 )(expected), (UNITY_INT)(UNITY_INT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) -#define UNITY_TEST_ASSERT_EQUAL_INT16(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT16)(expected), (UNITY_INT)(UNITY_INT16)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) -#define UNITY_TEST_ASSERT_EQUAL_INT32(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT32)(expected), (UNITY_INT)(UNITY_INT32)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) -#define UNITY_TEST_ASSERT_EQUAL_UINT(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) -#define UNITY_TEST_ASSERT_EQUAL_UINT8(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_UINT8 )(expected), (UNITY_INT)(UNITY_UINT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) -#define UNITY_TEST_ASSERT_EQUAL_UINT16(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_UINT16)(expected), (UNITY_INT)(UNITY_UINT16)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) -#define UNITY_TEST_ASSERT_EQUAL_UINT32(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_UINT32)(expected), (UNITY_INT)(UNITY_UINT32)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) -#define UNITY_TEST_ASSERT_EQUAL_HEX8(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT8 )(expected), (UNITY_INT)(UNITY_INT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) -#define UNITY_TEST_ASSERT_EQUAL_HEX16(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT16)(expected), (UNITY_INT)(UNITY_INT16)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) -#define UNITY_TEST_ASSERT_EQUAL_HEX32(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT32)(expected), (UNITY_INT)(UNITY_INT32)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) -#define UNITY_TEST_ASSERT_EQUAL_CHAR(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(UNITY_INT8 )(expected), (UNITY_INT)(UNITY_INT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR) -#define UNITY_TEST_ASSERT_BITS(mask, expected, actual, line, message) UnityAssertBits((UNITY_INT)(mask), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line)) - -#define UNITY_TEST_ASSERT_NOT_EQUAL_INT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) -#define UNITY_TEST_ASSERT_NOT_EQUAL_INT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 )(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) -#define UNITY_TEST_ASSERT_NOT_EQUAL_INT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT16)(threshold), (UNITY_INT)(UNITY_INT16)(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) -#define UNITY_TEST_ASSERT_NOT_EQUAL_INT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT32)(threshold), (UNITY_INT)(UNITY_INT32)(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) -#define UNITY_TEST_ASSERT_NOT_EQUAL_UINT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) -#define UNITY_TEST_ASSERT_NOT_EQUAL_UINT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) -#define UNITY_TEST_ASSERT_NOT_EQUAL_UINT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) -#define UNITY_TEST_ASSERT_NOT_EQUAL_UINT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) -#define UNITY_TEST_ASSERT_NOT_EQUAL_HEX8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) -#define UNITY_TEST_ASSERT_NOT_EQUAL_HEX16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) -#define UNITY_TEST_ASSERT_NOT_EQUAL_HEX32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) -#define UNITY_TEST_ASSERT_NOT_EQUAL_CHAR(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 )(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR) - -#define UNITY_TEST_ASSERT_GREATER_THAN_INT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) -#define UNITY_TEST_ASSERT_GREATER_THAN_INT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 )(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) -#define UNITY_TEST_ASSERT_GREATER_THAN_INT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT16)(threshold), (UNITY_INT)(UNITY_INT16)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) -#define UNITY_TEST_ASSERT_GREATER_THAN_INT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT32)(threshold), (UNITY_INT)(UNITY_INT32)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) -#define UNITY_TEST_ASSERT_GREATER_THAN_UINT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) -#define UNITY_TEST_ASSERT_GREATER_THAN_UINT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) -#define UNITY_TEST_ASSERT_GREATER_THAN_UINT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) -#define UNITY_TEST_ASSERT_GREATER_THAN_UINT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) -#define UNITY_TEST_ASSERT_GREATER_THAN_HEX8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) -#define UNITY_TEST_ASSERT_GREATER_THAN_HEX16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) -#define UNITY_TEST_ASSERT_GREATER_THAN_HEX32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) -#define UNITY_TEST_ASSERT_GREATER_THAN_CHAR(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 )(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR) - -#define UNITY_TEST_ASSERT_SMALLER_THAN_INT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) -#define UNITY_TEST_ASSERT_SMALLER_THAN_INT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 )(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) -#define UNITY_TEST_ASSERT_SMALLER_THAN_INT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT16)(threshold), (UNITY_INT)(UNITY_INT16)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) -#define UNITY_TEST_ASSERT_SMALLER_THAN_INT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT32)(threshold), (UNITY_INT)(UNITY_INT32)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) -#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) -#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) -#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) -#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) -#define UNITY_TEST_ASSERT_SMALLER_THAN_HEX8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) -#define UNITY_TEST_ASSERT_SMALLER_THAN_HEX16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) -#define UNITY_TEST_ASSERT_SMALLER_THAN_HEX32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) -#define UNITY_TEST_ASSERT_SMALLER_THAN_CHAR(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 )(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR) - -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT) (threshold), (UNITY_INT) (actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 ) (threshold), (UNITY_INT)(UNITY_INT8 ) (actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT16) (threshold), (UNITY_INT)(UNITY_INT16) (actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT32) (threshold), (UNITY_INT)(UNITY_INT32) (actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT) (threshold), (UNITY_INT) (actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_CHAR(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 ) (threshold), (UNITY_INT)(UNITY_INT8 ) (actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR) - -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT) (threshold), (UNITY_INT) (actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 ) (actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT16)(threshold), (UNITY_INT)(UNITY_INT16) (actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT32)(threshold), (UNITY_INT)(UNITY_INT32) (actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT) (threshold), (UNITY_INT) (actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX8(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT8 )(threshold), (UNITY_INT)(UNITY_UINT8 )(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX16(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT16)(threshold), (UNITY_INT)(UNITY_UINT16)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX32(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_UINT32)(threshold), (UNITY_INT)(UNITY_UINT32)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_CHAR(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(UNITY_INT8 )(threshold), (UNITY_INT)(UNITY_INT8 ) (actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR) - -#define UNITY_TEST_ASSERT_INT_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin( (delta), (UNITY_INT) (expected), (UNITY_INT) (actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT) -#define UNITY_TEST_ASSERT_INT8_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT8 )(delta), (UNITY_INT)(UNITY_INT8 ) (expected), (UNITY_INT)(UNITY_INT8 ) (actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8) -#define UNITY_TEST_ASSERT_INT16_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT16)(delta), (UNITY_INT)(UNITY_INT16) (expected), (UNITY_INT)(UNITY_INT16) (actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16) -#define UNITY_TEST_ASSERT_INT32_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT32)(delta), (UNITY_INT)(UNITY_INT32) (expected), (UNITY_INT)(UNITY_INT32) (actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32) -#define UNITY_TEST_ASSERT_UINT_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin( (delta), (UNITY_INT) (expected), (UNITY_INT) (actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT) -#define UNITY_TEST_ASSERT_UINT8_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT8 )(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT8 )(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8) -#define UNITY_TEST_ASSERT_UINT16_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT16)(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT16)(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT16)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16) -#define UNITY_TEST_ASSERT_UINT32_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT32)(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT32)(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT32)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32) -#define UNITY_TEST_ASSERT_HEX8_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT8 )(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT8 )(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT8 )(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8) -#define UNITY_TEST_ASSERT_HEX16_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT16)(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT16)(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT16)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16) -#define UNITY_TEST_ASSERT_HEX32_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT32)(delta), (UNITY_INT)(UNITY_UINT)(UNITY_UINT32)(expected), (UNITY_INT)(UNITY_UINT)(UNITY_UINT32)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32) -#define UNITY_TEST_ASSERT_CHAR_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((UNITY_UINT8 )(delta), (UNITY_INT)(UNITY_INT8 ) (expected), (UNITY_INT)(UNITY_INT8 ) (actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR) - -#define UNITY_TEST_ASSERT_INT_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin( (delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_INT8_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT8 )(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_INT16_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT16)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_INT32_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT32)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_UINT_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin( (delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_UINT8_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT16)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_UINT16_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT16)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_UINT32_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT32)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_HEX8_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT8 )(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_HEX16_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT16)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_HEX32_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT32)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_CHAR_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT8 )(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), ((UNITY_UINT32)(num_elements)), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR, UNITY_ARRAY_TO_ARRAY) - - -#define UNITY_TEST_ASSERT_EQUAL_PTR(expected, actual, line, message) UnityAssertEqualNumber((UNITY_PTR_TO_INT)(expected), (UNITY_PTR_TO_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_POINTER) -#define UNITY_TEST_ASSERT_EQUAL_STRING(expected, actual, line, message) UnityAssertEqualString((const char*)(expected), (const char*)(actual), (message), (UNITY_LINE_TYPE)(line)) -#define UNITY_TEST_ASSERT_EQUAL_STRING_LEN(expected, actual, len, line, message) UnityAssertEqualStringLen((const char*)(expected), (const char*)(actual), (UNITY_UINT32)(len), (message), (UNITY_LINE_TYPE)(line)) -#define UNITY_TEST_ASSERT_EQUAL_MEMORY(expected, actual, len, line, message) UnityAssertEqualMemory((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(len), 1, (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_ARRAY) - -#define UNITY_TEST_ASSERT_EQUAL_INT_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_INT8_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_INT16_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_INT32_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_UINT_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_UINT8_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_UINT16_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_UINT32_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_HEX8_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_HEX16_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_HEX32_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_PTR_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_POINTER, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_STRING_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualStringArray((UNITY_INTERNAL_PTR)(expected), (const char**)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_MEMORY_ARRAY(expected, actual, len, num_elements, line, message) UnityAssertEqualMemory((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(len), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_CHAR_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR, UNITY_ARRAY_TO_ARRAY) - -#define UNITY_TEST_ASSERT_EACH_EQUAL_INT(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT) (expected), (UNITY_INT_WIDTH / 8)), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_INT8(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT8 )(expected), 1), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT8, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_INT16(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT16 )(expected), 2), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT16, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_INT32(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT32 )(expected), 4), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT32, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT) (expected), (UNITY_INT_WIDTH / 8)), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT8(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_UINT8 )(expected), 1), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT8, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT16(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_UINT16)(expected), 2), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT16, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT32(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_UINT32)(expected), 4), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT32, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_HEX8(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT8 )(expected), 1), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX8, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_HEX16(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT16 )(expected), 2), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX16, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_HEX32(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT32 )(expected), 4), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX32, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_PTR(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_PTR_TO_INT) (expected), (UNITY_POINTER_WIDTH / 8)), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_POINTER, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_STRING(expected, actual, num_elements, line, message) UnityAssertEqualStringArray((UNITY_INTERNAL_PTR)(expected), (const char**)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_MEMORY(expected, actual, len, num_elements, line, message) UnityAssertEqualMemory((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(len), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_CHAR(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT8 )(expected), 1), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_CHAR, UNITY_ARRAY_TO_VAL) - -#ifdef UNITY_SUPPORT_64 -#define UNITY_TEST_ASSERT_EQUAL_INT64(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64) -#define UNITY_TEST_ASSERT_EQUAL_UINT64(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64) -#define UNITY_TEST_ASSERT_EQUAL_HEX64(expected, actual, line, message) UnityAssertEqualNumber((UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64) -#define UNITY_TEST_ASSERT_EQUAL_INT64_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_UINT64_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EQUAL_HEX64_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualIntArray((UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EACH_EQUAL_INT64(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT64)(expected), 8), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_UINT64(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_UINT64)(expected), 8), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_EACH_EQUAL_HEX64(expected, actual, num_elements, line, message) UnityAssertEqualIntArray(UnityNumToPtr((UNITY_INT)(UNITY_INT64)(expected), 8), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64, UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_INT64_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((delta), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64) -#define UNITY_TEST_ASSERT_UINT64_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((delta), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64) -#define UNITY_TEST_ASSERT_HEX64_WITHIN(delta, expected, actual, line, message) UnityAssertNumbersWithin((delta), (UNITY_INT)(expected), (UNITY_INT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64) -#define UNITY_TEST_ASSERT_NOT_EQUAL_INT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64) -#define UNITY_TEST_ASSERT_NOT_EQUAL_UINT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64) -#define UNITY_TEST_ASSERT_NOT_EQUAL_HEX64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_NOT_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64) -#define UNITY_TEST_ASSERT_GREATER_THAN_INT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64) -#define UNITY_TEST_ASSERT_GREATER_THAN_UINT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64) -#define UNITY_TEST_ASSERT_GREATER_THAN_HEX64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_GREATER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64) -#define UNITY_TEST_ASSERT_SMALLER_THAN_INT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64) -#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64) -#define UNITY_TEST_ASSERT_SMALLER_THAN_HEX64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_THAN, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX64(threshold, actual, line, message) UnityAssertGreaterOrLessOrEqualNumber((UNITY_INT)(threshold), (UNITY_INT)(actual), UNITY_SMALLER_OR_EQUAL, (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64) -#define UNITY_TEST_ASSERT_INT64_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT64)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_INT64, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_UINT64_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT64)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_UINT64, UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_HEX64_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UnityAssertNumbersArrayWithin((UNITY_UINT64)(delta), (UNITY_INTERNAL_PTR)(expected), (UNITY_INTERNAL_PTR)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_DISPLAY_STYLE_HEX64, UNITY_ARRAY_TO_ARRAY) -#else -#define UNITY_TEST_ASSERT_EQUAL_INT64(expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_EQUAL_UINT64(expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_EQUAL_HEX64(expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_EQUAL_INT64_ARRAY(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_EQUAL_UINT64_ARRAY(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_EQUAL_HEX64_ARRAY(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_INT64_WITHIN(delta, expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_UINT64_WITHIN(delta, expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_HEX64_WITHIN(delta, expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_GREATER_THAN_INT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_GREATER_THAN_UINT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_GREATER_THAN_HEX64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_INT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_UINT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_GREATER_OR_EQUAL_HEX64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_SMALLER_THAN_INT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_SMALLER_THAN_UINT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_SMALLER_THAN_HEX64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_INT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_UINT64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_SMALLER_OR_EQUAL_HEX64(threshold, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_INT64_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_UINT64_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#define UNITY_TEST_ASSERT_HEX64_ARRAY_WITHIN(delta, expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErr64) -#endif - -#ifdef UNITY_EXCLUDE_FLOAT -#define UNITY_TEST_ASSERT_FLOAT_WITHIN(delta, expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) -#define UNITY_TEST_ASSERT_EQUAL_FLOAT(expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) -#define UNITY_TEST_ASSERT_EQUAL_FLOAT_ARRAY(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) -#define UNITY_TEST_ASSERT_EACH_EQUAL_FLOAT(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) -#define UNITY_TEST_ASSERT_FLOAT_IS_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) -#define UNITY_TEST_ASSERT_FLOAT_IS_NEG_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) -#define UNITY_TEST_ASSERT_FLOAT_IS_NAN(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) -#define UNITY_TEST_ASSERT_FLOAT_IS_DETERMINATE(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) -#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) -#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_NEG_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) -#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_NAN(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) -#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrFloat) -#else -#define UNITY_TEST_ASSERT_FLOAT_WITHIN(delta, expected, actual, line, message) UnityAssertFloatsWithin((UNITY_FLOAT)(delta), (UNITY_FLOAT)(expected), (UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line)) -#define UNITY_TEST_ASSERT_EQUAL_FLOAT(expected, actual, line, message) UNITY_TEST_ASSERT_FLOAT_WITHIN((UNITY_FLOAT)(expected) * (UNITY_FLOAT)UNITY_FLOAT_PRECISION, (UNITY_FLOAT)(expected), (UNITY_FLOAT)(actual), (UNITY_LINE_TYPE)(line), (message)) -#define UNITY_TEST_ASSERT_EQUAL_FLOAT_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualFloatArray((UNITY_FLOAT*)(expected), (UNITY_FLOAT*)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EACH_EQUAL_FLOAT(expected, actual, num_elements, line, message) UnityAssertEqualFloatArray(UnityFloatToPtr(expected), (UNITY_FLOAT*)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_FLOAT_IS_INF(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_INF) -#define UNITY_TEST_ASSERT_FLOAT_IS_NEG_INF(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NEG_INF) -#define UNITY_TEST_ASSERT_FLOAT_IS_NAN(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NAN) -#define UNITY_TEST_ASSERT_FLOAT_IS_DETERMINATE(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_DET) -#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_INF(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_INF) -#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_NEG_INF(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_NEG_INF) -#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_NAN(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_NAN) -#define UNITY_TEST_ASSERT_FLOAT_IS_NOT_DETERMINATE(actual, line, message) UnityAssertFloatSpecial((UNITY_FLOAT)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_DET) -#endif - -#ifdef UNITY_EXCLUDE_DOUBLE -#define UNITY_TEST_ASSERT_DOUBLE_WITHIN(delta, expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) -#define UNITY_TEST_ASSERT_EQUAL_DOUBLE(expected, actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) -#define UNITY_TEST_ASSERT_EQUAL_DOUBLE_ARRAY(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) -#define UNITY_TEST_ASSERT_EACH_EQUAL_DOUBLE(expected, actual, num_elements, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) -#define UNITY_TEST_ASSERT_DOUBLE_IS_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) -#define UNITY_TEST_ASSERT_DOUBLE_IS_NEG_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) -#define UNITY_TEST_ASSERT_DOUBLE_IS_NAN(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) -#define UNITY_TEST_ASSERT_DOUBLE_IS_DETERMINATE(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) -#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) -#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) -#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NAN(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) -#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE(actual, line, message) UNITY_TEST_FAIL((UNITY_LINE_TYPE)(line), UnityStrErrDouble) -#else -#define UNITY_TEST_ASSERT_DOUBLE_WITHIN(delta, expected, actual, line, message) UnityAssertDoublesWithin((UNITY_DOUBLE)(delta), (UNITY_DOUBLE)(expected), (UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line)) -#define UNITY_TEST_ASSERT_EQUAL_DOUBLE(expected, actual, line, message) UNITY_TEST_ASSERT_DOUBLE_WITHIN((UNITY_DOUBLE)(expected) * (UNITY_DOUBLE)UNITY_DOUBLE_PRECISION, (UNITY_DOUBLE)(expected), (UNITY_DOUBLE)(actual), (UNITY_LINE_TYPE)(line), (message)) -#define UNITY_TEST_ASSERT_EQUAL_DOUBLE_ARRAY(expected, actual, num_elements, line, message) UnityAssertEqualDoubleArray((UNITY_DOUBLE*)(expected), (UNITY_DOUBLE*)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_ARRAY) -#define UNITY_TEST_ASSERT_EACH_EQUAL_DOUBLE(expected, actual, num_elements, line, message) UnityAssertEqualDoubleArray(UnityDoubleToPtr(expected), (UNITY_DOUBLE*)(actual), (UNITY_UINT32)(num_elements), (message), (UNITY_LINE_TYPE)(line), UNITY_ARRAY_TO_VAL) -#define UNITY_TEST_ASSERT_DOUBLE_IS_INF(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_INF) -#define UNITY_TEST_ASSERT_DOUBLE_IS_NEG_INF(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NEG_INF) -#define UNITY_TEST_ASSERT_DOUBLE_IS_NAN(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NAN) -#define UNITY_TEST_ASSERT_DOUBLE_IS_DETERMINATE(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_DET) -#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_INF(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_INF) -#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NEG_INF(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_NEG_INF) -#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_NAN(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_NAN) -#define UNITY_TEST_ASSERT_DOUBLE_IS_NOT_DETERMINATE(actual, line, message) UnityAssertDoubleSpecial((UNITY_DOUBLE)(actual), (message), (UNITY_LINE_TYPE)(line), UNITY_FLOAT_IS_NOT_DET) -#endif - -/* End of UNITY_INTERNALS_H */ -#endif diff --git a/tools/build.py b/tools/build.py index 3a9239bc2..f639fba81 100755 --- a/tools/build.py +++ b/tools/build.py @@ -23,6 +23,7 @@ build_separator = '-' * 95 build_status = [STATUS_OK, STATUS_FAILED, STATUS_SKIPPED] verbose = False +parallel_jobs = os.cpu_count() # ----------------------------- # Helper @@ -100,16 +101,26 @@ def cmake_board(board, toolchain, build_flags_on): if build_utils.skip_example(example, board): ret[2] += 1 else: - rcmd = run_cmd(f'cmake examples/{example} -B {build_dir}/{example} -G "Ninja" ' - f'-DBOARD={board} {build_flags}') - if rcmd.returncode == 0: - rcmd = run_cmd(f'cmake --build {build_dir}/{example}') + rcmd = run_cmd(f'idf.py -C examples/{example} -B {build_dir}/{example} -G Ninja ' + f'-DBOARD={board} {build_flags} build') ret[0 if rcmd.returncode == 0 else 1] += 1 else: - rcmd = run_cmd(f'cmake examples -B {build_dir} -G "Ninja" -DBOARD={board} -DCMAKE_BUILD_TYPE=MinSizeRel ' + rcmd = run_cmd(f'cmake examples -B {build_dir} -G Ninja -DBOARD={board} -DCMAKE_BUILD_TYPE=MinSizeRel ' f'-DTOOLCHAIN={toolchain} {build_flags}') if rcmd.returncode == 0: - rcmd = run_cmd(f"cmake --build {build_dir}") + cmd = f"cmake --build {build_dir}" + njobs = parallel_jobs + + # circleci docker return $nproc as 36 core, limit parallel according to resource class. + # Required for IAR, also prevent crashed/killed by docker + if os.getenv('CIRCLECI'): + resource_class = { 'small': 1, 'medium': 2, 'medium+': 3, 'large': 4 } + for rc in resource_class: + if rc in os.getenv('CIRCLE_JOB'): + njobs = resource_class[rc] + break + cmd += f' --parallel {njobs}' + rcmd = run_cmd(cmd) ret[0 if rcmd.returncode == 0 else 1] += 1 example = 'all' @@ -143,16 +154,21 @@ def make_one_example(example, board, make_option): def make_board(board, toolchain): print(build_separator) - all_examples = get_examples(find_family(board)) + family = find_family(board); + all_examples = get_examples(family) start_time = time.monotonic() ret = [0, 0, 0] - with Pool(processes=os.cpu_count()) as pool: - pool_args = list((map(lambda e, b=board, o=f"TOOLCHAIN={toolchain}": [e, b, o], all_examples))) - r = pool.starmap(make_one_example, pool_args) - # sum all element of same index (column sum) - ret = list(map(sum, list(zip(*r)))) - example = 'all' - print_build_result(board, example, 0 if ret[1] == 0 else 1, time.monotonic() - start_time) + if family == 'espressif' or family == 'rp2040': + # espressif and rp2040 do not support make, use cmake instead + final_status = 2 + else: + with Pool(processes=os.cpu_count()) as pool: + pool_args = list((map(lambda e, b=board, o=f"TOOLCHAIN={toolchain}": [e, b, o], all_examples))) + r = pool.starmap(make_one_example, pool_args) + # sum all element of same index (column sum) + ret = list(map(sum, list(zip(*r)))) + final_status = 0 if ret[1] == 0 else 1 + print_build_result(board, 'all', final_status, time.monotonic() - start_time) return ret @@ -174,9 +190,14 @@ def build_boards_list(boards, toolchain, build_system, build_flags_on): def build_family(family, toolchain, build_system, build_flags_on, one_per_family, boards): + skip_ci = ['pico_sdk'] + if os.getenv('GITHUB_ACTIONS') or os.getenv('CIRCLECI'): + skip_ci_file = Path(f"hw/bsp/{family}/skip_ci.txt") + if skip_ci_file.exists(): + skip_ci = skip_ci_file.read_text().split() all_boards = [] for entry in os.scandir(f"hw/bsp/{family}/boards"): - if entry.is_dir() and entry.name != 'pico_sdk': + if entry.is_dir() and not entry.name in skip_ci: all_boards.append(entry.name) all_boards.sort() @@ -198,6 +219,7 @@ def build_family(family, toolchain, build_system, build_flags_on, one_per_family # ----------------------------- def main(): global verbose + global parallel_jobs parser = argparse.ArgumentParser() parser.add_argument('families', nargs='*', default=[], help='Families to build') @@ -206,6 +228,7 @@ def main(): parser.add_argument('-s', '--build-system', default='cmake', help='Build system to use, default is cmake') parser.add_argument('-f1', '--build-flags-on', action='append', default=[], help='Build flag to pass to build system') parser.add_argument('-1', '--one-per-family', action='store_true', default=False, help='Build only one random board inside a family') + parser.add_argument('-j', '--jobs', type=int, default=os.cpu_count(), help='Number of jobs to run in parallel') parser.add_argument('-v', '--verbose', action='store_true', help='Verbose output') args = parser.parse_args() @@ -216,6 +239,7 @@ def main(): build_flags_on = args.build_flags_on one_per_family = args.one_per_family verbose = args.verbose + parallel_jobs = args.jobs if len(families) == 0 and len(boards) == 0: print("Please specify families or board to build") diff --git a/tools/build_utils.py b/tools/build_utils.py index 2998f940d..d80ceea7c 100755 --- a/tools/build_utils.py +++ b/tools/build_utils.py @@ -26,6 +26,8 @@ def skip_example(example, board): # family.mk family_mk = family_dir / "family.mk" + if not family_mk.exists(): + family_mk = family_dir / "family.cmake" mk_contents = family_mk.read_text() # Find the mcu, first in family mk then board mk diff --git a/tools/gen_doc.py b/tools/gen_doc.py index c69f3ff29..ab07bc116 100755 --- a/tools/gen_doc.py +++ b/tools/gen_doc.py @@ -1,4 +1,5 @@ #!/usr/bin/env python3 +import re import pandas as pd from tabulate import tabulate from pathlib import Path @@ -11,7 +12,6 @@ TOP = Path(__file__).parent.parent.resolve() # ----------------------------------------- # Dependencies # ----------------------------------------- - def gen_deps_doc(): deps_rst = Path(TOP) / "docs/reference/dependencies.rst" df = pd.DataFrame.from_dict(deps_all, orient='index', columns=['Repo', 'Commit', 'Required by']) @@ -32,5 +32,86 @@ MCU low-level peripheral driver and external libraries for building TinyUSB exam f.write(outstr) +# ----------------------------------------- +# Dependencies +# ----------------------------------------- +def extract_metadata(file_path): + metadata = {} + try: + with open(file_path, 'r') as file: + content = file.read() + # Match metadata block + match = re.search(r'/\*\s*metadata:(.*?)\*/', content, re.DOTALL) + if match: + block = match.group(1) + # Extract key-value pairs + for line in block.splitlines(): + key_value = re.match(r'\s*(\w+):\s*(.+)', line) + if key_value: + key, value = key_value.groups() + metadata[key] = value.strip() + except FileNotFoundError: + pass + return metadata + + +def gen_boards_doc(): + # 'Manufacturer' : { 'Board' } + vendor_data = {} + # 'Board' : [ 'Name', 'Family', 'url', 'note' ] + all_boards = {} + # extract metadata from family.c + for family_dir in sorted((Path(TOP) / "hw/bsp").iterdir()): + if family_dir.is_dir(): + family_c = family_dir / "family.c" + if not family_c.exists(): + family_c = family_dir / "boards/family.c" + f_meta = extract_metadata(family_c) + if not f_meta: + continue + manuf = f_meta.get('manufacturer', '') + if manuf not in vendor_data: + vendor_data[manuf] = {} + # extract metadata from board.h + for board_dir in sorted((family_dir / "boards").iterdir()): + if board_dir.is_dir(): + b_meta = extract_metadata(board_dir / "board.h") + if not b_meta: + continue + b_entry = [ + b_meta.get('name', ''), + family_dir.name, + b_meta.get('url', ''), + b_meta.get('note', '') + ] + vendor_data[manuf][board_dir.name] = b_entry + boards_rst = Path(TOP) / "docs/reference/boards.rst" + with boards_rst.open('w') as f: + title = f"""\ +**************** +Supported Boards +**************** + +The board support code is only used for self-contained examples and testing. It is not used when TinyUSB is part of a larger project. +It is responsible for getting the MCU started and the USB peripheral clocked with minimal of on-board devices + +- One LED : for status +- One Button : to get input from user +- One UART : needed for logging with LOGGER=uart, maybe required for host/dual examples + +Following boards are supported""" + f.write(title) + for manuf, boards in sorted(vendor_data.items()): + f.write(f"\n\n{manuf}\n") + f.write(f"{'-' * len(manuf)}\n\n") + df = pd.DataFrame.from_dict(boards, orient='index', columns=['Name', 'Family', 'URL', 'Note']) + df = df.rename_axis("Board") + f.write(tabulate(df, headers="keys", tablefmt='rst')) + + +# ----------------------------------------- +# Main +# ----------------------------------------- if __name__ == "__main__": gen_deps_doc() + gen_boards_doc() diff --git a/tools/gen_presets.py b/tools/gen_presets.py new file mode 100755 index 000000000..94b8d16b0 --- /dev/null +++ b/tools/gen_presets.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python3 +import os +import json +from pathlib import Path + +def main(): + board_list = [] + + # Find all board.cmake files + for root, dirs, files in os.walk("hw/bsp"): + for file in files: + if file == "board.cmake": + board_list.append(os.path.basename(root)) + + print('Generating presets for the following boards:') + print(board_list) + + # Generate the presets + presets = {} + presets['version'] = 6 + + # Configure presets + presets['configurePresets'] = [ + {"name": "default", + "hidden": True, + "description": r"Configure preset for the ${presetName} board", + "generator": "Ninja Multi-Config", + "binaryDir": r"${sourceDir}/build/${presetName}", + "cacheVariables": { + "CMAKE_DEFAULT_BUILD_TYPE": "RelWithDebInfo", + "BOARD": r"${presetName}" + }}] + + presets['configurePresets'].extend( + sorted( + [ + { + 'name': board, + 'inherits': 'default' + } + for board in board_list + ], key=lambda x: x['name'] + ) + ) + + # Build presets + # no inheritance since 'name' doesn't support macro expansion + presets['buildPresets'] = sorted( + [ + { + 'name': board, + 'description': "Build preset for the " + board + " board", + 'configurePreset': board + } + for board in board_list + ], key=lambda x: x['name'] + ) + + # Workflow presets + presets['workflowPresets'] = sorted( + [ + { + "name": board, + "steps": [ + { + "type": "configure", + "name": board + }, + { + "type": "build", + "name": board + } + ] + } + for board in board_list + ], key=lambda x: x['name'] + ) + + path_boardpresets = "hw/bsp/BoardPresets.json" + with open(path_boardpresets, "w") as f: + f.write('{}\n'.format(json.dumps(presets, indent=2))) + + # Generate presets for examples + presets = { + "version": 6, + "include": [ + ] + } + + example_list = [] + for root, dirs, files in os.walk("examples"): + for file in files: + # Filter out ESP-IDF CMakeLists.txt in src folder + if file == "CMakeLists.txt" and os.path.basename(root) != 'src': + presets['include'] = [os.path.relpath(path_boardpresets, root).replace(os.sep, '/')] + with open(os.path.join(root, 'CMakePresets.json'), 'w') as f: + f.write('{}\n'.format(json.dumps(presets, indent=2))) + example_list.append(os.path.basename(root)) + + print('Generating presets for the following examples:') + print(example_list) + + +if __name__ == "__main__": + main() diff --git a/tools/get_deps.py b/tools/get_deps.py index 58709414c..6a36ef35d 100755 --- a/tools/get_deps.py +++ b/tools/get_deps.py @@ -25,9 +25,9 @@ deps_optional = { 'hw/mcu/allwinner': ['https://github.com/hathach/allwinner_driver.git', '8e5e89e8e132c0fd90e72d5422e5d3d68232b756', 'fc100s'], - 'hw/mcu/analog/max32' : ['https://github.com/analogdevicesinc/msdk.git', + 'hw/mcu/analog/msdk' : ['https://github.com/analogdevicesinc/msdk.git', 'b20b398d3e5e2007594e54a74ba3d2a2e50ddd75', - 'max32650 max32666 max32690 max78002'], + 'maxim'], 'hw/mcu/bridgetek/ft9xx/ft90x-sdk': ['https://github.com/BRTSG-FOSS/ft90x-sdk.git', '91060164afe239fcb394122e8bf9eb24d3194eb1', 'brtmm90x'], @@ -55,14 +55,14 @@ deps_optional = { 'hw/mcu/nxp/lpcopen': ['https://github.com/hathach/nxp_lpcopen.git', 'b41cf930e65c734d8ec6de04f1d57d46787c76ae', 'lpc11 lpc13 lpc15 lpc17 lpc18 lpc40 lpc43'], - 'hw/mcu/nxp/mcux-sdk': ['https://github.com/hathach/mcux-sdk.git', - '144f1eb7ea8c06512e12f12b27383601c0272410', + 'hw/mcu/nxp/mcux-sdk': ['https://github.com/nxp-mcuxpresso/mcux-sdk', + 'a1bdae309a14ec95a4f64a96d3315a4f89c397c6', 'kinetis_k kinetis_k32l2 kinetis_kl lpc51 lpc54 lpc55 mcx imxrt'], 'hw/mcu/raspberry_pi/Pico-PIO-USB': ['https://github.com/sekigon-gonnoc/Pico-PIO-USB.git', - 'fe9133fc513b82cc3dc62c67cb51f2339cf29ef7', + '3c1eec341a5232640e4c00628b889b641af34b28', 'rp2040'], 'hw/mcu/renesas/fsp': ['https://github.com/renesas/fsp.git', - 'd52e5a6a59b7c638da860c2bb309b6e78e752ff8', + 'edcc97d684b6f716728a60d7a6fea049d9870bd6', 'ra'], 'hw/mcu/renesas/rx': ['https://github.com/kkitayam/rx_device.git', '706b4e0cf485605c32351e2f90f5698267996023', @@ -103,6 +103,9 @@ deps_optional = { 'hw/mcu/st/cmsis_device_h7': ['https://github.com/STMicroelectronics/cmsis_device_h7.git', '60dc2c913203dc8629dc233d4384dcc41c91e77f', 'stm32h7'], + 'hw/mcu/st/cmsis_device_h7rs': ['https://github.com/STMicroelectronics/cmsis_device_h7rs.git', + '832649d1fd09bd901e9f68e979522e5c209ebf20', + 'stm32h7rs'], 'hw/mcu/st/cmsis_device_h5': ['https://github.com/STMicroelectronics/cmsis_device_h5.git', 'cd2d1d579743de57b88ccaf61a968b9c05848ffc', 'stm32h5'], @@ -118,15 +121,21 @@ deps_optional = { 'hw/mcu/st/cmsis_device_l5': ['https://github.com/STMicroelectronics/cmsis_device_l5.git', 'd922865fc0326a102c26211c44b8e42f52c1e53d', 'stm32l5'], + 'hw/mcu/st/cmsis_device_n6': ['https://github.com/STMicroelectronics/cmsis-device-n6.git', + 'f818b00f775444e8d19ef6cad822534c345e054f', + 'stm32n6'], 'hw/mcu/st/cmsis_device_u5': ['https://github.com/STMicroelectronics/cmsis_device_u5.git', '5ad9797c54ec3e55eff770fc9b3cd4a1aefc1309', 'stm32u5'], 'hw/mcu/st/cmsis_device_wb': ['https://github.com/STMicroelectronics/cmsis_device_wb.git', - '9c5d1920dd9fabbe2548e10561d63db829bb744f', + 'd6a7fa2e7de084f5e5e47f2ab88b022fe9b50e5a', 'stm32wb'], 'hw/mcu/st/stm32-mfxstm32l152': ['https://github.com/STMicroelectronics/stm32-mfxstm32l152.git', '7f4389efee9c6a655b55e5df3fceef5586b35f9b', 'stm32h7'], + 'hw/mcu/st/stm32-tcpp0203': ['https://github.com/STMicroelectronics/stm32-tcpp0203.git', + '9918655bff176ac3046ccf378b5c7bbbc6a38d15', + 'stm32h7rs stm32n6'], 'hw/mcu/st/stm32c0xx_hal_driver': ['https://github.com/STMicroelectronics/stm32c0xx_hal_driver.git', '41253e2f1d7ae4a4d0c379cf63f5bcf71fcf8eb3', 'stm32c0'], @@ -157,6 +166,9 @@ deps_optional = { 'hw/mcu/st/stm32h7xx_hal_driver': ['https://github.com/STMicroelectronics/stm32h7xx_hal_driver.git', 'd8461b980b59b1625207d8c4f2ce0a9c2a7a3b04', 'stm32h7'], + 'hw/mcu/st/stm32h7rsxx_hal_driver': ['https://github.com/STMicroelectronics/stm32h7rsxx-hal-driver.git', + '7ca2e07ca21bc66b53654e845b4c85c884343b60', + 'stm32h7rs'], 'hw/mcu/st/stm32h5xx_hal_driver': ['https://github.com/STMicroelectronics/stm32h5xx_hal_driver.git', '2cf77de584196d619cec1b4586c3b9e2820a254e', 'stm32h5'], @@ -172,6 +184,9 @@ deps_optional = { 'hw/mcu/st/stm32l5xx_hal_driver': ['https://github.com/STMicroelectronics/stm32l5xx_hal_driver.git', '675c32a75df37f39d50d61f51cb0dcf53f07e1cb', 'stm32l5'], + 'hw/mcu/st/stm32n6xx_hal_driver': ['https://github.com/STMicroelectronics/stm32n6xx-hal-driver.git', + '49f9989d10cf6817d4b07ac01848956b46bd0fd6', + 'stm32n6'], 'hw/mcu/st/stm32u5xx_hal_driver': ['https://github.com/STMicroelectronics/stm32u5xx_hal_driver.git', '4d93097a67928e9377e655ddd14622adc31b9770', 'stm32u5'], @@ -194,13 +209,16 @@ deps_optional = { '77c4095087e5ed2c548ec9058e655d0b8757663b', 'ch32f20x'], 'lib/CMSIS_5': ['https://github.com/ARM-software/CMSIS_5.git', - '20285262657d1b482d132d20d755c8c330d55c1f', - 'imxrt kinetis_k32l2 kinetis_kl lpc51 lpc54 lpc55 mcx mm32 msp432e4 nrf ra saml2x ' + '2b7495b8535bdcb306dac29b9ded4cfb679d7e5c', + 'imxrt kinetis_k32l2 kinetis_kl lpc51 lpc54 lpc55 mcx mm32 msp432e4 nrf saml2x ' 'lpc11 lpc13 lpc15 lpc17 lpc18 lpc40 lpc43 ' 'stm32c0 stm32f0 stm32f1 stm32f2 stm32f3 stm32f4 stm32f7 stm32g0 stm32g4 stm32h5 ' - 'stm32h7 stm32l0 stm32l1 stm32l4 stm32l5 stm32u5 stm32wb ' + 'stm32h7 stm32h7rs stm32l0 stm32l1 stm32l4 stm32l5 stm32n6 stm32u5 stm32wb ' 'sam3x samd11 samd21 samd51 samd5x_e5x same5x same7x saml2x samg ' 'tm4c '], + 'lib/CMSIS_6': ['https://github.com/ARM-software/CMSIS_6.git', + 'b0bbb0423b278ca632cfe1474eb227961d835fd2', + 'ra'], 'lib/sct_neopixel': ['https://github.com/gsteiert/sct_neopixel.git', 'e73e04ca63495672d955f9268e003cffe168fcd8', 'lpc55'], @@ -214,7 +232,12 @@ TOP = Path(__file__).parent.parent.resolve() def run_cmd(cmd): - return subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + r = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + title = f'Command Error: {cmd}' + if r.returncode != 0: + print(title) + print(r.stdout.decode("utf-8")) + return r def get_a_dep(d): @@ -235,11 +258,13 @@ def get_a_dep(d): p.mkdir(parents=True) run_cmd(f"{git_cmd} init") run_cmd(f"{git_cmd} remote add origin {url}") + head = None + else: + # Check if commit is already fetched + result = run_cmd(f"{git_cmd} rev-parse HEAD") + head = result.stdout.decode("utf-8").splitlines()[0] + run_cmd(f"{git_cmd} reset --hard") - # Check if commit is already fetched - result = run_cmd(f"{git_cmd} rev-parse HEAD") - head = result.stdout.decode("utf-8").splitlines()[0] - run_cmd(f"{git_cmd} reset --hard") if commit != head: run_cmd(f"{git_cmd} fetch --depth 1 origin {commit}") run_cmd(f"{git_cmd} checkout FETCH_HEAD") diff --git a/tools/make_release.py b/tools/make_release.py index 92c75baf9..c1caf3300 100755 --- a/tools/make_release.py +++ b/tools/make_release.py @@ -2,7 +2,7 @@ import re import gen_doc -version = '0.17.0' +version = '0.18.0' print('version {}'.format(version)) ver_id = version.split('.')