diff options
| author | HiFiPhile <[email protected]> | 2026-02-27 11:47:58 +0100 |
|---|---|---|
| committer | HiFiPhile <[email protected]> | 2026-02-27 11:47:58 +0100 |
| commit | ecc0e12dd5ab58cffafb03a8d1800dc68bed1c6f (patch) | |
| tree | 6ced64f1cca39af4aaf77a3861785f5b21f71b1b | |
| parent | a3fd3071c17bdc7392db1361f3a97019351af337 (diff) | |
| parent | bd1e79bc6cefbbbe981691c3a55e24cf25537301 (diff) | |
Merge remote-tracking branch 'tinyusb/master' into dwc2_deinit
Signed-off-by: HiFiPhile <[email protected]>
155 files changed, 4881 insertions, 1519 deletions
diff --git a/.circleci/config2.yml b/.circleci/config2.yml index 352d0f4fa..a31b0a818 100644 --- a/.circleci/config2.yml +++ b/.circleci/config2.yml @@ -110,7 +110,7 @@ commands: no_output_timeout: 20m command: | if [ << parameters.toolchain >> == esp-idf ]; then - docker run --rm -v $PWD:/project -w /project espressif/idf:v5.3.2 python tools/build.py << parameters.build-args >> << parameters.family >> + docker run --rm -v $PWD:/project -w /project espressif/idf:v5.3.2 python tools/build.py << parameters.build-args >> --target all << parameters.family >> else # Toolchain option default is gcc if [ << parameters.toolchain >> == arm-clang ]; then @@ -124,7 +124,11 @@ commands: # circleci docker return $nproc as 36 core, limit parallel to 4 (resource-class = large) # Required for IAR, also prevent crashed/killed by docker - python tools/build.py -s << parameters.build-system >> $TOOLCHAIN_OPTION -j 4 << parameters.build-args >> << parameters.family >> + BUILD_PY_ARGS="-s << parameters.build-system >> $TOOLCHAIN_OPTION -j 4 << parameters.build-args >> --target all" + if [ << parameters.build-system >> == "cmake" ]; then + BUILD_PY_ARGS="$BUILD_PY_ARGS --target tinyusb_metrics" + fi + python tools/build.py $BUILD_PY_ARGS << parameters.family >> fi # Only collect and persist metrics for cmake builds (excluding esp-idf and --one-random) diff --git a/.github/actions/get_deps/action.yml b/.github/actions/get_deps/action.yml index a84db893b..bbe94f0fa 100644 --- a/.github/actions/get_deps/action.yml +++ b/.github/actions/get_deps/action.yml @@ -22,6 +22,7 @@ runs: NINJA_URL=https://github.com/ninja-build/ninja/releases/download/v1.13.1/ninja-linux.zip wget $NINJA_URL -O ninja-linux.zip unzip ninja-linux.zip -d ninja-bin + pip install membrowse echo >> $GITHUB_PATH "${{ github.workspace }}/ninja-bin" shell: bash diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md deleted file mode 100644 index aa148eb79..000000000 --- a/.github/pull_request_template.md +++ /dev/null @@ -1,5 +0,0 @@ -**Describe the PR** -A clear and concise description of what this PR solve. - -**Additional context** -If applicable, add any other context about the PR and/or screenshots here. diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 781d3b002..9d8b90f5a 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -3,32 +3,11 @@ name: Build on: workflow_dispatch: push: - paths: - - 'src/**' - - 'examples/**' - - 'lib/**' - - 'hw/**' - - 'tools/build.py' - - 'tools/get_deps.py' - - '.github/actions/**' - - '.github/workflows/build.yml' - - '.github/workflows/build_util.yml' - - '.github/workflows/ci_set_matrix.py' + branches: [master] pull_request: - paths: - - 'src/**' - - 'examples/**' - - 'lib/**' - - 'hw/**' - - 'test/hil/**' - - 'tools/build.py' - - 'tools/get_deps.py' - - '.github/actions/**' - - '.github/workflows/build.yml' - - '.github/workflows/build_util.yml' - - '.github/workflows/ci_set_matrix.py' release: types: [ published ] + concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true @@ -37,6 +16,36 @@ env: HIL_JSON: test/hil/tinyusb.json jobs: + # Check if the code changes and we need to run ci build + # Cannot use paths filter in the on-event since we want this workflow to run even when there are no code changes, to register the commit chain + check-paths: + runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: read + outputs: + code_changed: ${{ steps.filter.outputs.code }} + steps: + - uses: actions/checkout@v6 + with: + fetch-depth: 2 # Needed for push commit comparison + - uses: dorny/paths-filter@v3 + id: filter + with: + filters: | + code: + - 'src/**' + - 'examples/**' + - 'lib/**' + - 'hw/**' + - 'test/hil/**' + - 'tools/build.py' + - 'tools/get_deps.py' + - '.github/actions/**' + - '.github/workflows/build.yml' + - '.github/workflows/build_util.yml' + - '.github/workflows/ci_set_matrix.py' + set-matrix: runs-on: ubuntu-latest outputs: @@ -64,7 +73,7 @@ jobs: # For Make and IAR build: will be done on CircleCI only (one random per family as well) # ------------------------------------------------------------------------------ cmake: - needs: set-matrix + needs: [ check-paths, set-matrix ] uses: ./.github/workflows/build_util.yml strategy: fail-fast: false @@ -82,9 +91,14 @@ jobs: build-args: ${{ toJSON(fromJSON(needs.set-matrix.outputs.json)[matrix.toolchain]) }} build-options: '--one-first' upload-metrics: true + upload-artifacts: false + upload-membrowse: true + code-changed: ${{ needs.check-paths.outputs.code_changed == 'true' }} + secrets: inherit code-metrics: - needs: cmake + needs: [ check-paths, cmake ] + if: needs.check-paths.outputs.code_changed == 'true' runs-on: ubuntu-latest permissions: pull-requests: write @@ -181,24 +195,29 @@ jobs: # Build Make/CMake on Windows/MacOS # --------------------------------------- build-os: - if: github.event_name == 'pull_request' + needs: [ check-paths ] + if: needs.check-paths.outputs.code_changed == 'true' uses: ./.github/workflows/build_util.yml strategy: fail-fast: false matrix: os: [ windows-latest, macos-latest ] + build-system: [ 'make', 'cmake' ] with: os: ${{ matrix.os }} - build-system: 'cmake-make' + build-system: ${{ matrix.build-system }} toolchain: 'arm-gcc-${{ matrix.os }}' - build-args: '["stm32h7"]' + build-args: '["stm32h7rs"]' build-options: '--one-random' # --------------------------------------- # Zephyr # --------------------------------------- zephyr: - if: github.event_name == 'push' + needs: [ check-paths ] + # skip zephyr build due to failed build, fix later + if: false + #if: needs.check-paths.outputs.code_changed == 'true' runs-on: ubuntu-latest steps: - name: Checkout TinyUSB @@ -220,10 +239,8 @@ jobs: # 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 + needs: [ check-paths, set-matrix ] + if: needs.check-paths.outputs.code_changed == 'true' && github.repository_owner == 'hathach' uses: ./.github/workflows/build_util.yml strategy: fail-fast: false @@ -242,7 +259,6 @@ jobs: # self-hosted on local VM, for attached hardware checkout HIL_JSON # --------------------------------------- hil-tinyusb: - if: github.repository_owner == 'hathach' && github.event_name != 'push' needs: hil-build runs-on: [ self-hosted, X64, hathach, hardware-in-the-loop ] steps: @@ -283,10 +299,11 @@ jobs: # Since IAR Token secret is not passed to forked PR, only build non-forked PR # --------------------------------------- hil-hfp: + needs: [ check-paths ] if: | + needs.check-paths.outputs.code_changed == 'true' && github.repository_owner == 'hathach' && - github.event.pull_request.head.repo.fork == false && - github.event_name != 'push' + !(github.event_name == 'pull_request' && github.event.pull_request.head.repo.fork == true) runs-on: [ self-hosted, Linux, X64, hifiphile ] env: IAR_LMS_BEARER_TOKEN: ${{ secrets.IAR_LMS_BEARER_TOKEN }} @@ -315,7 +332,7 @@ jobs: run: python3 tools/get_deps.py $BUILD_ARGS - name: Build - run: python3 tools/build.py -j 4 --toolchain iar $BUILD_ARGS + run: python3 tools/build.py --toolchain iar $BUILD_ARGS - name: Test on actual hardware (hardware in the loop) run: python3 test/hil/hil_test.py hfp.json diff --git a/.github/workflows/build_util.yml b/.github/workflows/build_util.yml index 540ee8b47..d03c9af81 100644 --- a/.github/workflows/build_util.yml +++ b/.github/workflows/build_util.yml @@ -3,6 +3,10 @@ name: Reusable build util on: workflow_call: inputs: + os: + required: false + type: string + default: 'ubuntu-latest' build-system: required: true type: string @@ -24,10 +28,14 @@ on: required: false default: false type: boolean - os: + upload-membrowse: required: false - type: string - default: 'ubuntu-latest' + default: false + type: boolean + code-changed: + required: false + default: true + type: boolean jobs: family: @@ -39,6 +47,8 @@ jobs: steps: - name: Checkout TinyUSB uses: actions/checkout@v6 + with: + fetch-depth: ${{ !inputs.upload-membrowse && 1 || 0 }} - name: Setup Toolchain id: setup-toolchain @@ -52,29 +62,40 @@ jobs: arg: ${{ matrix.arg }} - name: Build + if: ${{ inputs.code-changed }} env: IAR_LMS_BEARER_TOKEN: ${{ secrets.IAR_LMS_BEARER_TOKEN }} - TOOLCHAIN: ${{ inputs.toolchain }} run: | - if [ "$TOOLCHAIN" == "esp-idf" ]; then - docker run --rm -v $PWD:/project -w /project espressif/idf:tinyusb python tools/build.py ${{ matrix.arg }} - elif [ "${{ inputs.build-system }}" == "cmake-make" ] || [ "${{ inputs.build-system }}" == "make-cmake" ]; then - python tools/build.py -s make ${{ steps.setup-toolchain.outputs.build_option }} ${{ inputs.build-options }} ${{ matrix.arg }} - python tools/build.py -s cmake ${{ steps.setup-toolchain.outputs.build_option }} ${{ inputs.build-options }} ${{ matrix.arg }} + if [ "${{ inputs.toolchain }}" == "esp-idf" ]; then + docker run --rm -e MEMBROWSE_API_KEY="$MEMBROWSE_API_KEY" -v $PWD:/project -w /project espressif/idf:tinyusb python tools/build.py --target all ${{ matrix.arg }} else - python tools/build.py -s ${{ inputs.build-system }} ${{ steps.setup-toolchain.outputs.build_option }} ${{ inputs.build-options }} ${{ matrix.arg }} + BUILD_PY_ARGS="-s ${{ inputs.build-system }} ${{ steps.setup-toolchain.outputs.build_option }} ${{ inputs.build-options }} --target all" + if [ "${{ inputs.upload-metrics }}" = "true" ]; then + BUILD_PY_ARGS="$BUILD_PY_ARGS --target tinyusb_metrics" + fi + python tools/build.py $BUILD_PY_ARGS ${{ matrix.arg }} fi shell: bash + - name: Membrowse Upload + if: inputs.toolchain != 'esp-idf' && inputs.upload-membrowse == true + env: + MEMBROWSE_API_KEY: ${{ secrets.MEMBROWSE_API_KEY }} + run: | + # if code-changed is false --> there is no elf -> membrowse target upload with --identical flag + BUILD_PY_ARGS="-s ${{ inputs.build-system }} ${{ steps.setup-toolchain.outputs.build_option }} ${{ inputs.build-options }}" + python tools/build.py $BUILD_PY_ARGS --target examples-membrowse-upload -j 1 ${{ matrix.arg }} + shell: bash + - name: Upload Artifacts for Metrics - if: ${{ inputs.upload-metrics }} + if: inputs.upload-metrics == true && inputs.code-changed == true uses: actions/upload-artifact@v5 with: name: metrics-${{ matrix.arg }} path: cmake-build/cmake-build-*/metrics.json - name: Upload Artifacts for Hardware Testing - if: ${{ inputs.upload-artifacts }} + if: inputs.upload-artifacts == true && inputs.code-changed == true uses: actions/upload-artifact@v5 with: name: binaries-${{ matrix.arg }} @@ -86,3 +107,4 @@ jobs: cmake-build/cmake-build-*/*/*/partition_table/partition-table.bin cmake-build/cmake-build-*/*/*/config.env cmake-build/cmake-build-*/*/*/flash_args + cmake-build/hw/mcu/**/*.ld diff --git a/.github/workflows/ci_set_matrix.py b/.github/workflows/ci_set_matrix.py index c276d5253..cd7dfa76b 100755 --- a/.github/workflows/ci_set_matrix.py +++ b/.github/workflows/ci_set_matrix.py @@ -15,30 +15,76 @@ toolchain_list = [ # family: [supported toolchain] family_list = { - "at32f402_405 at32f403a_407 at32f413 at32f415 at32f423 at32f425 at32f435_437 broadcom_32bit da1469x": ["arm-gcc"], + "at32f402_405": ["arm-gcc"], + "at32f403a_407": ["arm-gcc"], + "at32f413": ["arm-gcc"], + "at32f415": ["arm-gcc"], + "at32f423": ["arm-gcc"], + "at32f425": ["arm-gcc"], + "at32f435_437": ["arm-gcc"], + "at32f45x": ["arm-gcc"], + "broadcom_32bit": ["arm-gcc"], "broadcom_64bit": ["aarch64-gcc"], - "ch32v10x ch32v20x ch32v30x fomu gd32vf103 hpmicro": ["riscv-gcc"], + "ch32v10x": ["riscv-gcc"], + "ch32v20x": ["riscv-gcc"], + "ch32v30x": ["riscv-gcc"], + "da1469x": ["arm-gcc"], + "fomu": ["riscv-gcc"], + "gd32vf103": ["riscv-gcc"], + "hpmicro": ["riscv-gcc"], "imxrt": ["arm-gcc", "arm-clang"], - "kinetis_k kinetis_kl kinetis_k32l2": ["arm-gcc", "arm-clang"], - "lpc11 lpc13 lpc15 lpc17 lpc18 lpc40 lpc43": ["arm-gcc", "arm-clang"], - "lpc51 lpc54 lpc55": ["arm-gcc", "arm-clang"], - "maxim mcx mm32 msp432e4 rw61x tm4c": ["arm-gcc"], + "kinetis_k": ["arm-gcc", "arm-clang"], + "kinetis_k32l2": ["arm-gcc", "arm-clang"], + "kinetis_kl": ["arm-gcc", "arm-clang"], + "lpc11": ["arm-gcc", "arm-clang"], + "lpc13": ["arm-gcc", "arm-clang"], + "lpc15": ["arm-gcc", "arm-clang"], + "lpc17": ["arm-gcc", "arm-clang"], + "lpc18": ["arm-gcc", "arm-clang"], + "lpc40": ["arm-gcc", "arm-clang"], + "lpc43": ["arm-gcc", "arm-clang"], + "lpc51": ["arm-gcc", "arm-clang"], + "lpc54": ["arm-gcc", "arm-clang"], + "lpc55": ["arm-gcc", "arm-clang"], + "maxim": ["arm-gcc"], + "mcx": ["arm-gcc"], + "mm32": ["arm-gcc"], "msp430": ["msp430-gcc"], + "msp432e4": ["arm-gcc"], "nrf": ["arm-gcc", "arm-clang"], - "nuc100_120 nuc121_125 nuc126 nuc505 xmc4000": ["arm-gcc"], + "nuc100_120": ["arm-gcc"], + "nuc121_125": ["arm-gcc"], + "nuc126": ["arm-gcc"], + "nuc505": ["arm-gcc"], "ra": ["arm-gcc"], "rp2040": ["arm-gcc"], + "rw61x": ["arm-gcc"], "rx": ["rx-gcc"], - "samd11 samd2x_l2x samd5x_e5x samg": ["arm-gcc", "arm-clang"], - "stm32c0 stm32f0 stm32f1 stm32f2 stm32f3": ["arm-gcc", "arm-clang", "arm-iar"], + "samd11": ["arm-gcc", "arm-clang"], + "samd2x_l2x": ["arm-gcc", "arm-clang"], + "samd5x_e5x": ["arm-gcc", "arm-clang"], + "samg": ["arm-gcc", "arm-clang"], + "stm32c0": ["arm-gcc", "arm-clang", "arm-iar"], + "stm32f0": ["arm-gcc", "arm-clang", "arm-iar"], + "stm32f1": ["arm-gcc", "arm-clang", "arm-iar"], + "stm32f2": ["arm-gcc", "arm-clang", "arm-iar"], + "stm32f3": ["arm-gcc", "arm-clang", "arm-iar"], "stm32f4": ["arm-gcc", "arm-clang", "arm-iar"], "stm32f7": ["arm-gcc", "arm-clang", "arm-iar"], - "stm32g0 stm32g4 stm32h5": ["arm-gcc", "arm-clang", "arm-iar"], + "stm32g0": ["arm-gcc", "arm-clang", "arm-iar"], + "stm32g4": ["arm-gcc", "arm-clang", "arm-iar"], + "stm32h5": ["arm-gcc", "arm-clang", "arm-iar"], "stm32h7": ["arm-gcc", "arm-clang", "arm-iar"], - "stm32h7rs stm32l0 stm32l4": ["arm-gcc", "arm-clang", "arm-iar"], + "stm32h7rs": ["arm-gcc", "arm-clang", "arm-iar"], + "stm32l0": ["arm-gcc", "arm-clang", "arm-iar"], + "stm32l4": ["arm-gcc", "arm-clang", "arm-iar"], "stm32n6": ["arm-gcc"], - "stm32u0 stm32u5 stm32wb stm32wba": ["arm-gcc", "arm-clang", "arm-iar"], - "-bespressif_s2_devkitc": ["esp-idf"], + "stm32u0": ["arm-gcc", "arm-clang", "arm-iar"], + "stm32u5": ["arm-gcc", "arm-clang", "arm-iar"], + "stm32wb": ["arm-gcc", "arm-clang", "arm-iar"], + "stm32wba": ["arm-gcc", "arm-clang", "arm-iar"], + "tm4c": ["arm-gcc"], + "xmc4000": ["arm-gcc"], # S3, P4 will be built by hil test # "-bespressif_s3_devkitm": ["esp-idf"], # "-bespressif_p4_function_ev": ["esp-idf"], diff --git a/.github/workflows/membrowse-comment.yml b/.github/workflows/membrowse-comment.yml new file mode 100644 index 000000000..a99c9db51 --- /dev/null +++ b/.github/workflows/membrowse-comment.yml @@ -0,0 +1,38 @@ +name: Membrowse Comment + +on: + workflow_run: + workflows: ["Build"] + types: + - completed + +jobs: + post-comment: + runs-on: ubuntu-latest + if: > + github.event.workflow_run.event == 'pull_request' && + github.event.workflow_run.conclusion != 'cancelled' + permissions: + actions: read + pull-requests: write + steps: + - name: Checkout repository + uses: actions/checkout@v6 + + - name: Download Artifacts + id: download + uses: actions/download-artifact@v5 + with: + run-id: ${{ github.event.workflow_run.id }} + github-token: ${{ secrets.GITHUB_TOKEN }} + name: membrowse-comment + path: reports + continue-on-error: true + + - name: Post Membrowse PR comment + if: steps.download.outcome == 'success' + uses: membrowse/membrowse-action/comment-action@v1 + with: + json_files: 'reports/*.json' + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/membrowse-onboard.yml b/.github/workflows/membrowse-onboard.yml new file mode 100644 index 000000000..aa7204ffa --- /dev/null +++ b/.github/workflows/membrowse-onboard.yml @@ -0,0 +1,62 @@ +name: Onboard to Membrowse + +on: + workflow_dispatch: + inputs: + num_commits: + description: 'Number of commits to process' + required: true + default: '10' + type: string + +jobs: + load-targets: + runs-on: ubuntu-22.04 + outputs: + targets: ${{ steps.load.outputs.targets }} + toolchains: ${{ steps.load.outputs.toolchains }} + steps: + - name: Checkout repository + uses: actions/checkout@v5 + + - name: Load target matrix + id: load + run: | + echo "targets=$(jq -c '.targets' .github/membrowse-targets.json)" >> $GITHUB_OUTPUT + echo "toolchains=$(jq -c '.toolchains' .github/membrowse-targets.json)" >> $GITHUB_OUTPUT + + onboard: + needs: load-targets + runs-on: ubuntu-22.04 + strategy: + fail-fast: false + matrix: + include: ${{ fromJson(needs.load-targets.outputs.targets) }} + + steps: + - name: Checkout repository + uses: actions/checkout@v5 + with: + fetch-depth: 0 + submodules: recursive + + - name: Install packages + run: | + ${{ fromJson(needs.load-targets.outputs.toolchains)[matrix.toolchain].setup_cmd }} && python3 tools/get_deps.py ${{ matrix.get_deps || matrix.port }} + + - name: Setup ccache + uses: hendrikmuhs/[email protected] + with: + key: ${{ matrix.port }}-${{ matrix.board }} + + - name: Run Membrowse Onboard Action + uses: membrowse/membrowse-action/onboard-action@v1 + with: + target_name: ${{ matrix.port }}-${{ matrix.board }}-${{ matrix.example }} + num_commits: ${{ github.event.inputs.num_commits }} + build_script: python3 tools/build.py -s cmake -b ${{ matrix.board }} + elf: cmake-build/cmake-build-${{ matrix.board }}/device/${{ matrix.example }}/${{ matrix.example }}.elf + ld: ${{ matrix.ld }} + linker_vars: ${{ matrix.linker_vars || '' }} + api_key: ${{ secrets.MEMBROWSE_API_KEY }} + api_url: ${{ vars.MEMBROWSE_API_URL }} diff --git a/.idea/cmake.xml b/.idea/cmake.xml index 0754253ad..822a70236 100644 --- a/.idea/cmake.xml +++ b/.idea/cmake.xml @@ -103,6 +103,8 @@ <configuration PROFILE_NAME="metro m7 1011 sd" ENABLED="false" CONFIG_NAME="Debug" GENERATION_OPTIONS="-DBOARD=metro_m7_1011_sd -DLOG=1 -DLOGGER=RTT -DTRACE_ETM=1" /> <configuration PROFILE_NAME="metro_m7_1011" ENABLED="false" CONFIG_NAME="Debug" GENERATION_OPTIONS="-DBOARD=metro_m7_1011 -DLOG=1 -DLOGGER=RTT" /> <configuration PROFILE_NAME="rt1010 evk" ENABLED="false" CONFIG_NAME="Debug" GENERATION_OPTIONS="-DBOARD=mimxrt1010_evk -DLOG=1 -DLOGGER=RTT" /> + <configuration PROFILE_NAME="rt1024 evk" ENABLED="false" CONFIG_NAME="Debug" GENERATION_OPTIONS="-DBOARD=mimxrt1024_evk -DLOG=1 -DLOGGER=RTT" /> + <configuration PROFILE_NAME="rt1050 evk" ENABLED="false" CONFIG_NAME="Debug" GENERATION_OPTIONS="-DBOARD=mimxrt1050_evkb -DLOG=1 -DLOGGER=RTT" /> <configuration PROFILE_NAME="mimxrt1060_evk" ENABLED="false" CONFIG_NAME="Debug" GENERATION_OPTIONS="-DBOARD=mimxrt1060_evk -DLOG=1" /> <configuration PROFILE_NAME="mimxrt1064_evk" ENABLED="false" CONFIG_NAME="Debug" GENERATION_OPTIONS="-DBOARD=mimxrt1064_evk" /> <configuration PROFILE_NAME="rt1170 evkb" ENABLED="false" CONFIG_NAME="Debug" GENERATION_OPTIONS="-DBOARD=mimxrt1170_evkb -DLOG=1 -DLOGGER=RTT -DTRACE_ETM=1" /> @@ -126,8 +128,10 @@ <configuration PROFILE_NAME="stm32h743eval_host1" ENABLED="false" CONFIG_NAME="Debug" GENERATION_OPTIONS="-DBOARD=stm32h743eval -DRHPORT_HOST=1 -DLOG=1 -DLOGGER=RTT -DTRACE_ETM=1" /> <configuration PROFILE_NAME="stm32h743eval IAR" ENABLED="false" CONFIG_NAME="Debug" TOOLCHAIN_NAME="iccarm" GENERATION_OPTIONS="-DBOARD=stm32h743eval -DLOG=1 -DLOGGER=RTT -DTRACE_ETM=1 -DIAR_CSTAT=1" /> <configuration PROFILE_NAME="stm32h743nucleo" ENABLED="false" CONFIG_NAME="Debug" GENERATION_OPTIONS="-DBOARD=stm32h743nucleo -DLOG=1" /> + <configuration PROFILE_NAME="stm32h7s3nucleo" ENABLED="false" CONFIG_NAME="Debug" GENERATION_OPTIONS="-DBOARD=stm32h7s3nucleo -DLOG=1" /> <configuration PROFILE_NAME="stm32l0538disco" ENABLED="false" CONFIG_NAME="Debug" GENERATION_OPTIONS="-DBOARD=stm32l0538disco -DLOG=0 -DLOGGER=RTT" /> <configuration PROFILE_NAME="stm32l476disco" ENABLED="false" CONFIG_NAME="Debug" GENERATION_OPTIONS="-DBOARD=stm32l476disco -DLOG=1 -DLOGGER=RTT" /> + <configuration PROFILE_NAME="stm32u083cdk" ENABLED="false" CONFIG_NAME="Debug" GENERATION_OPTIONS="-DBOARD=stm32u083cdk -DLOG=1 -DLOGGER=RTT" /> <configuration PROFILE_NAME="stm32u575nucleo" ENABLED="false" CONFIG_NAME="Debug" GENERATION_OPTIONS="-DBOARD=stm32u575nucleo -DLOG=1 -DLOGGER=RTT" /> <configuration PROFILE_NAME="stm32u5a5nucleo" ENABLED="false" CONFIG_NAME="Debug" GENERATION_OPTIONS="-DBOARD=stm32u5a5nucleo -DLOG=1 -DLOGGER=RTT" /> <configuration PROFILE_NAME="stm32wb55nucleo" ENABLED="false" GENERATION_OPTIONS="-DBOARD=stm32wb55nucleo" /> @@ -167,6 +171,7 @@ <configuration PROFILE_NAME="mm32f327x_mb39" ENABLED="false" GENERATION_OPTIONS="-DBOARD=mm32f327x_mb39" /> <configuration PROFILE_NAME="fomu" ENABLED="false" GENERATION_OPTIONS="-DBOARD=fomu" /> <configuration PROFILE_NAME="sipeed_longan_nano" ENABLED="false" GENERATION_OPTIONS="-DBOARD=sipeed_longan_nano" /> + <configuration PROFILE_NAME="ch32v103r_r1_1v0" ENABLED="false" CONFIG_NAME="Debug" GENERATION_OPTIONS="-DBOARD=ch32v103r_r1_1v0" /> <configuration PROFILE_NAME="nanoch32v203" ENABLED="false" CONFIG_NAME="Debug" GENERATION_OPTIONS="-DBOARD=nanoch32v203" /> <configuration PROFILE_NAME="ch32v203c_r0_1v0" ENABLED="false" CONFIG_NAME="Debug" GENERATION_OPTIONS="-DBOARD=ch32v203c_r0_1v0 -DLOG=0" /> <configuration PROFILE_NAME="ch32v203c_r0_1v0 USBFS" ENABLED="false" CONFIG_NAME="Debug" GENERATION_OPTIONS="-DBOARD=ch32v203c_r0_1v0 -DPORT=1" /> diff --git a/.idea/debugServers/ST_LINK.xml b/.idea/debugServers/ST_LINK.xml index 7c21d3879..c4dadd5bb 100644 --- a/.idea/debugServers/ST_LINK.xml +++ b/.idea/debugServers/ST_LINK.xml @@ -1,10 +1,10 @@ <component name="DebugServers"> - <stlink-debug-target name="ST-LINK" uniqueID="300d1a6f-85c0-4eb3-9753-f033d01e2eff"> + <stlink-debug-target name="ST-LINK" uniqueID="cf98f5f4-9c5b-4340-ab06-16ddd7f07062"> <debugger version="1"> <debugger kind="GDB" isBundled="true" /> <env /> </debugger> - <gdbserver exe="$USER_HOME$/st/stm32cubeide_1.16.1/plugins/com.st.stm32cube.ide.mcu.externaltools.stlink-gdb-server.linux64_2.1.400.202404281720/tools/bin/ST-LINK_gdbserver" programmer="$USER_HOME$/STMicroelectronics/STM32Cube/STM32CubeProgrammer/bin" /> + <gdbserver exe="/opt/st/stm32cubeclt_1.20.0/STLink-gdb-server/bin/ST-LINK_gdbserver" programmer="/opt/st/stm32cubeclt_1.20.0/STM32CubeProgrammer/bin" /> <st-link /> <device interface="SWD" /> <connection port="61234" warmup-ms="500" /> diff --git a/.idea/debugServers/mcxa153.xml b/.idea/debugServers/mcxa153.xml new file mode 100644 index 000000000..0e493cbd5 --- /dev/null +++ b/.idea/debugServers/mcxa153.xml @@ -0,0 +1,13 @@ +<component name="DebugServers"> + <jlink-debug-target name="mcxa153" uniqueID="6a023429-69e6-4f8c-a592-4995cdf255db"> + <debugger version="1"> + <debugger kind="GDB" isBundled="true" /> + <env /> + </debugger> + <gdbserver exe="/usr/bin/JLinkGDBServerCLExe" /> + <console port="19021" /> + <target device="MCXA153" reset-before="false" /> + <connection extended-remote="false" port="4444" warmup-ms="500" /> + <swo /> + </jlink-debug-target> +</component>
\ No newline at end of file diff --git a/.idea/debugServers/ra6m1.xml b/.idea/debugServers/ra6m1.xml new file mode 100644 index 000000000..17c902ec4 --- /dev/null +++ b/.idea/debugServers/ra6m1.xml @@ -0,0 +1,13 @@ +<component name="DebugServers"> + <jlink-debug-target name="ra6m1" uniqueID="c8cdc79a-939b-4342-92b1-d24da72d12fe"> + <debugger version="1"> + <debugger kind="GDB" isBundled="true" /> + <env /> + </debugger> + <gdbserver exe="/usr/bin/JLinkGDBServerCLExe" /> + <console port="19021" /> + <target device="R7FA6M1AD" reset-before="false" frequency="16000" /> + <connection extended-remote="false" port="4444" warmup-ms="500" /> + <swo /> + </jlink-debug-target> +</component>
\ No newline at end of file diff --git a/.idea/debugServers/ra6m5.xml b/.idea/debugServers/ra6m5.xml new file mode 100644 index 000000000..d8dfbdeeb --- /dev/null +++ b/.idea/debugServers/ra6m5.xml @@ -0,0 +1,13 @@ +<component name="DebugServers"> + <jlink-debug-target name="ra6m5" uniqueID="19100d9f-7329-47da-b566-f9faf297f47c"> + <debugger version="1"> + <debugger kind="GDB" isBundled="true" /> + <env /> + </debugger> + <gdbserver exe="/usr/bin/JLinkGDBServerCLExe" /> + <console port="19021" /> + <target device="R7FA6M5BH" reset-before="false" frequency="16000" /> + <connection extended-remote="false" port="4444" warmup-ms="500" /> + <swo /> + </jlink-debug-target> +</component>
\ No newline at end of file diff --git a/.idea/debugServers/rt1011.xml b/.idea/debugServers/rt1011.xml new file mode 100644 index 000000000..b4be501bd --- /dev/null +++ b/.idea/debugServers/rt1011.xml @@ -0,0 +1,13 @@ +<component name="DebugServers"> + <jlink-debug-target name="rt1011" uniqueID="e10c53c4-acf5-4a6f-a05d-32b7b042d70a"> + <debugger version="1"> + <debugger kind="GDB" isBundled="true" /> + <env /> + </debugger> + <gdbserver exe="/usr/bin/JLinkGDBServerCLExe" /> + <console port="19021" /> + <target device="MIMXRT1011xxx5A" reset-before="false" /> + <connection extended-remote="false" port="4444" warmup-ms="500" /> + <swo /> + </jlink-debug-target> +</component>
\ No newline at end of file diff --git a/.idea/debugServers/rt1170.xml b/.idea/debugServers/rt1170.xml new file mode 100644 index 000000000..9a564ed57 --- /dev/null +++ b/.idea/debugServers/rt1170.xml @@ -0,0 +1,13 @@ +<component name="DebugServers"> + <jlink-debug-target name="rt1170" uniqueID="cfc772e4-782e-49a3-99fb-b6f726e14f9d"> + <debugger version="1"> + <debugger kind="GDB" isBundled="true" /> + <env /> + </debugger> + <gdbserver exe="/usr/bin/JLinkGDBServerCLExe" /> + <console port="19021" /> + <target device="MIMXRT1176xxxA_M7" reset-before="false" frequency="16000" /> + <connection extended-remote="false" port="4444" warmup-ms="500" /> + <swo /> + </jlink-debug-target> +</component>
\ No newline at end of file diff --git a/.idea/debugServers/stm32f072.xml b/.idea/debugServers/stm32f072.xml new file mode 100644 index 000000000..c56f5a8fb --- /dev/null +++ b/.idea/debugServers/stm32f072.xml @@ -0,0 +1,13 @@ +<component name="DebugServers"> + <jlink-debug-target name="stm32f072" uniqueID="f5c65701-0f8d-4923-a7ea-3ee2547147ae"> + <debugger version="1"> + <debugger kind="GDB" isBundled="true" /> + <env /> + </debugger> + <gdbserver exe="/usr/bin/JLinkGDBServerCLExe" /> + <console port="19021" /> + <target device="STM32F072RB" reset-before="false" frequency="12000" /> + <connection extended-remote="false" port="4444" warmup-ms="500" /> + <swo /> + </jlink-debug-target> +</component>
\ No newline at end of file diff --git a/.idea/debugServers/stm32f303.xml b/.idea/debugServers/stm32f303.xml new file mode 100644 index 000000000..84aafc1e3 --- /dev/null +++ b/.idea/debugServers/stm32f303.xml @@ -0,0 +1,13 @@ +<component name="DebugServers"> + <jlink-debug-target name="stm32f303" uniqueID="1cdd63e5-1736-42be-bff3-4c48e1f169fa"> + <debugger version="1"> + <debugger kind="GDB" isBundled="true" /> + <env /> + </debugger> + <gdbserver exe="/usr/bin/JLinkGDBServerCLExe" /> + <console port="19021" /> + <target device="STM32F303VC" reset-before="false" frequency="12000" /> + <connection extended-remote="false" port="4444" warmup-ms="500" /> + <swo /> + </jlink-debug-target> +</component>
\ No newline at end of file diff --git a/.idea/debugServers/stm32l053.xml b/.idea/debugServers/stm32l053.xml new file mode 100644 index 000000000..5365189cc --- /dev/null +++ b/.idea/debugServers/stm32l053.xml @@ -0,0 +1,13 @@ +<component name="DebugServers"> + <jlink-debug-target name="stm32l053" uniqueID="51d156d7-86a6-4006-814a-ed14981d7b49"> + <debugger version="1"> + <debugger kind="GDB" isBundled="true" /> + <env /> + </debugger> + <gdbserver exe="/usr/bin/JLinkGDBServerCLExe" /> + <console port="19021" /> + <target device="STM32L053R8" reset-before="false" frequency="12000" /> + <connection extended-remote="false" port="4444" warmup-ms="500" /> + <swo /> + </jlink-debug-target> +</component>
\ No newline at end of file @@ -91,6 +91,22 @@ make BOARD=raspberry_pi_pico all - Make: `make BOARD=raspberry_pi_pico all uf2` - **List all targets** (CMake/Ninja): `ninja -t targets` +## J-Link GDB Server + RTT Logging + +- Build with RTT logging enabled (example): + `cd examples/device/cdc_msc && make BOARD=stm32h743eval LOG=2 LOGGER=rtt all` +- Flash with J-Link: + `cd examples/device/cdc_msc && make BOARD=stm32h743eval LOG=2 LOGGER=rtt flash-jlink` +- Launch GDB server (keep this running in terminal 1): + `JLinkGDBServer -device stm32h743xi -if SWD -speed 4000 -port 2331 -swoport 2332 -telnetport 2333 -RTTTelnetPort 19021 -nogui` +- Read RTT output (terminal 2): + `JLinkRTTClient` +- Capture RTT to file (optional): + `JLinkRTTClient | tee rtt.log` +- For non-interactive capture: + `timeout 20s JLinkRTTClient > rtt.log` +- Use the board-specific `JLINK_DEVICE` from `hw/bsp/*/boards/*/board.mk` if you are not using `stm32h743eval`. + ## Unit Testing - Install Ceedling: `sudo gem install ceedling` @@ -101,9 +117,15 @@ make BOARD=raspberry_pi_pico all ## Hardware-in-the-Loop (HIL) Testing +- `-B examples` means `examples` is the parent folder that contains multi-board build outputs such as `examples/cmake-build-BOARD_NAME/...` +- Select config file before running HIL tests: + - if GitHub Actions self-hosted runner service is running, use `tinyusb.json` + - otherwise use `local.json` + - example: + `HIL_CONFIG=$( (systemctl list-units --type=service --state=running 2>/dev/null; systemctl --user list-units --type=service --state=running 2>/dev/null) | grep -q 'actions\.runner' && echo tinyusb.json || echo local.json )` - Run tests on actual hardware, one of following ways: - - test a specific board `python test/hil/hil_test.py -b BOARD_NAME -B examples local.json` - - test all boards in config `python test/hil/hil_test.py -B examples local.json` + - test a specific board `python test/hil/hil_test.py -b BOARD_NAME -B examples $HIL_CONFIG` + - test all boards in config `python test/hil/hil_test.py -B examples $HIL_CONFIG` - In case of error, enabled verbose mode with `-v` flag for detailed logs. Also try to observe script output, and try to modify hil_test.py (temporarily) to add more debug prints to pinpoint the issue. - Requires pre-built (all) examples for target boards (see Build Examples section 2) diff --git a/README.rst b/README.rst index 2ad0b3439..a3863c375 100644 --- a/README.rst +++ b/README.rst @@ -1,7 +1,7 @@ TinyUSB ======= -|Build Status| |CircleCI Status| |Documentation Status| |Static Analysis| |Fuzzing Status| |License| +|Build Status| |CircleCI Status| |Documentation Status| |Static Analysis| |Fuzzing Status| |Membrowse| |License| Sponsors -------- @@ -101,10 +101,11 @@ If you have a special requirement, ``usbd_app_driver_get_cb()`` can be used to w 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, PL2303 +- Human Interface Device (HID): Keyboard, Mouse, Generic +- Mass Storage Class (MSC) +- Musical Instrument Digital Interface (MIDI) - 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. @@ -141,7 +142,8 @@ Supported CPUs +--------------+-----------------------------+--------+------+-----------+------------------------+--------------------+ | Artery AT32 | F403a_407, F413 | ✔ | | | fsdev | 512 USB RAM | | +-----------------------------+--------+------+-----------+------------------------+--------------------+ -| | F415, F435_437, F423, F425 | ✔ | ✔ | | dwc2 | | +| | F415, F435_437, F423, | ✔ | ✔ | | dwc2 | | +| | F425, F45x | | | | | | | +-----------------------------+--------+------+-----------+------------------------+--------------------+ | | F402_F405 | ✔ | ✔ | ✔ | dwc2 | F405 is HS | +--------------+-----------------------------+--------+------+-----------+------------------------+--------------------+ @@ -292,6 +294,8 @@ The following tools are provided freely to support the development of the TinyUS :target: https://github.com/hathach/tinyusb/actions/workflows/static_analysis.yml .. |Fuzzing Status| image:: https://oss-fuzz-build-logs.storage.googleapis.com/badges/tinyusb.svg :target: https://oss-fuzz-build-logs.storage.googleapis.com/index.html#tinyusb +.. |Membrowse| image:: https://membrowse.com/badge.svg + :target: https://membrowse.com/public/hathach/tinyusb .. |License| image:: https://img.shields.io/badge/license-MIT-brightgreen.svg :target: https://opensource.org/licenses/MIT diff --git a/docs/getting_started.rst b/docs/getting_started.rst index 0c3fcec80..8442305d4 100644 --- a/docs/getting_started.rst +++ b/docs/getting_started.rst @@ -34,7 +34,10 @@ Get the Code $ python tools/get_deps.py -b stm32h743eval # or python tools/get_deps.py stm32h7 .. note:: - For rp2040 `pico-sdk <https://github.com/raspberrypi/pico-sdk>`_ or `esp-idf <https://github.com/espressif/esp-idf>`_ for Espressif targets are required; install them per vendor instructions. + Some MCU families require additional SDKs, please follow their instructions to install and set it up + + * **rp2040**: Requires `pico-sdk <https://github.com/raspberrypi/pico-sdk>`_ + * **Espressif (esp32)**: Requires `esp-idf <https://github.com/espressif/esp-idf>`_. Only a few examples support the ESP-IDF build system. Look for ones with `src/CMakeLists.txt` that contain `idf_component_register()`, such as `cdc_msc_freertos`. Simple Device Example --------------------- diff --git a/docs/reference/boards.rst b/docs/reference/boards.rst index 12da5c90b..f6dd3cd91 100644 --- a/docs/reference/boards.rst +++ b/docs/reference/boards.rst @@ -44,6 +44,9 @@ at_start_f423 AT-START-F423 at32f423 https:/ at_start_f425 AT-START-F425 at32f425 https://www.arterychip.com/en/product/AT32F425.jsp at_start_f435 AT-START-F435 at32f435_437 https://www.arterychip.com/en/product/AT32F435.jsp at_start_f437 AT-START-F437 at32f435_437 https://www.arterychip.com/en/product/AT32F437.jsp +at_start_f455 AT-START-F455 at32f45x https://www.arterychip.com/en/product/AT32F455.jsp +at_start_f456 AT-START-F456 at32f45x https://www.arterychip.com/en/product/AT32F456.jsp +at_start_f457 AT-START-F457 at32f45x https://www.arterychip.com/en/product/AT32F457.jsp ========================= ============================= ============= ==================================================== ====== Bridgetek @@ -289,6 +292,7 @@ stm32h723nucleo STM32 H723 Nucleo stm32h7 https://www.s 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 +stm32h747disco STM32 H747 Discovery stm32h7 https://www.st.com/en/evaluation-tools/stm32h747i-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 @@ -330,6 +334,7 @@ Board Name Family URL 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 +ek_tm4c1294xl TM4C1294 LaunchPad tm4c https://www.ti.com/tool/EK-TM4C1294XL ================= ===================== ======== ========================================= ====== Tomu diff --git a/docs/reference/dependencies.rst b/docs/reference/dependencies.rst index de1603383..ce5f265d5 100644 --- a/docs/reference/dependencies.rst +++ b/docs/reference/dependencies.rst @@ -16,6 +16,7 @@ hw/mcu/artery/at32f415 https://github.com/ArteryTek/AT32F415_ hw/mcu/artery/at32f423 https://github.com/ArteryTek/AT32F423_Firmware_Library.git 2afa7f12852e57a9e8aab3a892c641e1a8635a18 at32f423 hw/mcu/artery/at32f425 https://github.com/ArteryTek/AT32F425_Firmware_Library.git 620233e1357d5c1b7e2bde6b9dd5196822b91817 at32f425 hw/mcu/artery/at32f435_437 https://github.com/ArteryTek/AT32F435_437_Firmware_Library.git 25439cc6650a8ae0345934e8707a5f38c7ae41f8 at32f435_437 +hw/mcu/artery/at32f45x https://github.com/ArteryTek/AT32F45x_Firmware_Library.git 3d4a1b38be8ebac292e2350ca53bc4bfa4430233 at32f45x 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 diff --git a/examples/device/cdc_dual_ports/src/tusb_config.h b/examples/device/cdc_dual_ports/src/tusb_config.h index 0da4032a7..710c01ee2 100644 --- a/examples/device/cdc_dual_ports/src/tusb_config.h +++ b/examples/device/cdc_dual_ports/src/tusb_config.h @@ -104,6 +104,8 @@ #define CFG_TUD_CDC_TX_BUFSIZE (TUD_OPT_HIGH_SPEED ? 512 : 64) // CDC Endpoint transfer buffer size, more is faster +// Leave it as default size (512 for HS, 64 for FS) unless your host application +// is able to send ZLP (Zero Length Packet) to terminate transfer ! #define CFG_TUD_CDC_EP_BUFSIZE (TUD_OPT_HIGH_SPEED ? 512 : 64) #ifdef __cplusplus diff --git a/examples/device/cdc_msc/src/tusb_config.h b/examples/device/cdc_msc/src/tusb_config.h index fdb2ddf18..3f2f05f20 100644 --- a/examples/device/cdc_msc/src/tusb_config.h +++ b/examples/device/cdc_msc/src/tusb_config.h @@ -104,6 +104,8 @@ #define CFG_TUD_CDC_TX_BUFSIZE (TUD_OPT_HIGH_SPEED ? 512 : 64) // CDC Endpoint transfer buffer size, more is faster +// Leave it as default size (512 for HS, 64 for FS) unless your host application +// is able to send ZLP (Zero Length Packet) to terminate transfer ! #define CFG_TUD_CDC_EP_BUFSIZE (TUD_OPT_HIGH_SPEED ? 512 : 64) // MSC Buffer size of Device Mass storage diff --git a/examples/device/cdc_msc_freertos/src/tusb_config.h b/examples/device/cdc_msc_freertos/src/tusb_config.h index 6b1937a8d..8277b1604 100644 --- a/examples/device/cdc_msc_freertos/src/tusb_config.h +++ b/examples/device/cdc_msc_freertos/src/tusb_config.h @@ -111,6 +111,8 @@ #define CFG_TUD_CDC_TX_BUFSIZE (TUD_OPT_HIGH_SPEED ? 512 : 64) // CDC Endpoint transfer buffer size, more is faster +// Leave it as default size (512 for HS, 64 for FS) unless your host application +// is able to send ZLP (Zero Length Packet) to terminate transfer ! #define CFG_TUD_CDC_EP_BUFSIZE (TUD_OPT_HIGH_SPEED ? 512 : 64) // MSC Buffer size of Device Mass storage diff --git a/examples/device/cdc_uac2/src/tusb_config.h b/examples/device/cdc_uac2/src/tusb_config.h index b7ece8b7c..5eb2e8f74 100644 --- a/examples/device/cdc_uac2/src/tusb_config.h +++ b/examples/device/cdc_uac2/src/tusb_config.h @@ -160,6 +160,8 @@ extern "C" { #define CFG_TUD_CDC_TX_BUFSIZE (TUD_OPT_HIGH_SPEED ? 512 : 64) // CDC Endpoint transfer buffer size, more is faster +// Leave it as default size (512 for HS, 64 for FS) unless your host application +// is able to send ZLP (Zero Length Packet) to terminate transfer ! #define CFG_TUD_CDC_EP_BUFSIZE (TUD_OPT_HIGH_SPEED ? 512 : 64) #ifdef __cplusplus diff --git a/examples/device/dfu/skip.txt b/examples/device/dfu/skip.txt index 9dde06c30..79d3da9d2 100644 --- a/examples/device/dfu/skip.txt +++ b/examples/device/dfu/skip.txt @@ -1,3 +1,3 @@ -mcu:TM4C123 +mcu:TM4C mcu:BCM2835 family:espressif diff --git a/examples/device/mtp/src/mtp_fs_example.c b/examples/device/mtp/src/mtp_fs_example.c index 7fd7db61b..60fc9f79e 100644 --- a/examples/device/mtp/src/mtp_fs_example.c +++ b/examples/device/mtp/src/mtp_fs_example.c @@ -557,7 +557,7 @@ static int32_t fs_send_object_info(tud_mtp_cb_data_t* cb_data) { return MTP_RESP_INVALID_STORAGE_ID; } - if (obj_info->parent_object != 0) { // not root + if (obj_info->parent_object != 0 && obj_info->parent_object != 0xFFFFFFFFu) { // not root fs_file_t* parent = fs_get_file(obj_info->parent_object); if (parent == NULL || 0u == parent->association_type) { return MTP_RESP_INVALID_PARENT_OBJECT; 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 00d059b66..fffb54d58 100644 --- a/examples/dual/host_info_to_device_cdc/src/main.c +++ b/examples/dual/host_info_to_device_cdc/src/main.c @@ -246,10 +246,9 @@ static void print_device_info(uint8_t daddr, const tusb_desc_device_t* desc_devi 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; + serial[0] = (uint16_t)((TUSB_DESC_STRING << 8) | (2 * 1 + 2)); + serial[1] = '0'; + serial[2] = 0; } print_utf16(serial, TU_ARRAY_SIZE(serial)); cdc_printf("\r\n"); diff --git a/examples/host/device_info/src/main.c b/examples/host/device_info/src/main.c index 5b914a2ee..ab617e989 100644 --- a/examples/host/device_info/src/main.c +++ b/examples/host/device_info/src/main.c @@ -130,11 +130,10 @@ void tuh_mount_cb(uint8_t daddr) { } if (XFER_RESULT_SUCCESS != xfer_result) { uint16_t* serial = (uint16_t*)(uintptr_t) desc.serial; - serial[0] = (uint16_t) ((TUSB_DESC_STRING << 8) | (2 * 3 + 2)); - serial[1] = 'n'; - serial[2] = '/'; - serial[3] = 'a'; - serial[4] = 0; + + serial[0] = (uint16_t)((TUSB_DESC_STRING << 8) | (2 * 1 + 2)); + serial[1] = '0'; // simply 0 + serial[2] = 0; } print_utf16((uint16_t*)(uintptr_t) desc.serial, sizeof(desc.serial)/2); printf("\r\n"); diff --git a/hw/bsp/BoardPresets.json b/hw/bsp/BoardPresets.json index 440ef8733..fabbeed93 100644 --- a/hw/bsp/BoardPresets.json +++ b/hw/bsp/BoardPresets.json @@ -175,6 +175,10 @@ "inherits": "default" }, { + "name": "ek_tm4c1294xl", + "inherits": "default" + }, + { "name": "f1c100s", "inherits": "default" }, @@ -719,6 +723,10 @@ "inherits": "default" }, { + "name": "stm32h747disco", + "inherits": "default" + }, + { "name": "stm32h750_weact", "inherits": "default" }, @@ -1109,6 +1117,11 @@ "configurePreset": "ek_tm4c123gxl" }, { + "name": "ek_tm4c1294xl", + "description": "Build preset for the ek_tm4c1294xl board", + "configurePreset": "ek_tm4c1294xl" + }, + { "name": "espressif_addax_1", "description": "Build preset for the espressif_addax_1 board", "configurePreset": "espressif_addax_1" @@ -1834,6 +1847,11 @@ "configurePreset": "stm32h745disco" }, { + "name": "stm32h747disco", + "description": "Build preset for the stm32h747disco board", + "configurePreset": "stm32h747disco" + }, + { "name": "stm32h750_weact", "description": "Build preset for the stm32h750_weact board", "configurePreset": "stm32h750_weact" @@ -2543,6 +2561,19 @@ ] }, { + "name": "ek_tm4c1294xl", + "steps": [ + { + "type": "configure", + "name": "ek_tm4c1294xl" + }, + { + "type": "build", + "name": "ek_tm4c1294xl" + } + ] + }, + { "name": "espressif_addax_1", "steps": [ { @@ -4428,6 +4459,19 @@ ] }, { + "name": "stm32h747disco", + "steps": [ + { + "type": "configure", + "name": "stm32h747disco" + }, + { + "type": "build", + "name": "stm32h747disco" + } + ] + }, + { "name": "stm32h750_weact", "steps": [ { diff --git a/hw/bsp/at32f45x/FreeRTOSConfig/FreeRTOSConfig.h b/hw/bsp/at32f45x/FreeRTOSConfig/FreeRTOSConfig.h new file mode 100644 index 000000000..c5b89452e --- /dev/null +++ b/hw/bsp/at32f45x/FreeRTOSConfig/FreeRTOSConfig.h @@ -0,0 +1,176 @@ +/* + * 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 "at32f45x.h" +#endif + +/* Cortex-M4 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 system_core_clock +#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 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 + +#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<<configPRIO_BITS) - 1) + +/* The highest interrupt priority that can be used by any interrupt service +routine that makes calls to interrupt safe FreeRTOS API functions. DO NOT CALL +INTERRUPT SAFE FREERTOS API FUNCTIONS FROM ANY INTERRUPT THAT HAS A HIGHER +PRIORITY THAN THIS! (higher priorities are lower numeric values. */ +#define configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY 2 + +/* Interrupt priorities used by the kernel port layer itself. These are generic +to all Cortex-M ports, and do not rely on any particular library functions. */ +#define configKERNEL_INTERRUPT_PRIORITY ( configLIBRARY_LOWEST_INTERRUPT_PRIORITY << (8 - configPRIO_BITS) ) + +/* !!!! configMAX_SYSCALL_INTERRUPT_PRIORITY must not be set to zero !!!! +See http://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html. */ +#define configMAX_SYSCALL_INTERRUPT_PRIORITY ( configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY << (8 - configPRIO_BITS) ) + +#endif + +#endif /* __FREERTOS_CONFIG__H */ diff --git a/hw/bsp/at32f45x/at32f45x_clock.c b/hw/bsp/at32f45x/at32f45x_clock.c new file mode 100644 index 000000000..a66a8b1aa --- /dev/null +++ b/hw/bsp/at32f45x/at32f45x_clock.c @@ -0,0 +1,114 @@ +/** + ************************************************************************** + * @file at32f45x_clock.c + * @brief system clock config program + ************************************************************************** + * + * Copyright (c) 2025, Artery Technology, All rights reserved. + * + * The software Board Support Package (BSP) that is made available to + * download from Artery official website is the copyrighted work of Artery. + * Artery authorizes customers to use, copy, and distribute the BSP + * software and its related documentation for the purpose of design and + * development in conjunction with Artery microcontrollers. Use of the + * software is governed by this copyright notice and the following disclaimer. + * + * THIS SOFTWARE IS PROVIDED ON "AS IS" BASIS WITHOUT WARRANTIES, + * GUARANTEES OR REPRESENTATIONS OF ANY KIND. ARTERY EXPRESSLY DISCLAIMS, + * TO THE FULLEST EXTENT PERMITTED BY LAW, ALL EXPRESS, IMPLIED OR + * STATUTORY OR OTHER WARRANTIES, GUARANTEES OR REPRESENTATIONS, + * INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. + * + ************************************************************************** + */ + +/* includes ------------------------------------------------------------------*/ +#include "at32f45x_clock.h" + +/** + * @brief system clock config program + * @note the system clock is configured as follow: + * - system clock = (hext * pll_ns)/(pll_ms * pll_fp) + * - system clock source = pll (hext) + * - hext = 8000000 + * - sclk = 192000000 + * - ahbdiv = 1 + * - ahbclk = 192000000 + * - apb2div = 1 + * - apb2clk = 192000000 + * - apb1div = 1 + * - apb1clk = 192000000 + * - pll_ns = 96 + * - pll_ms = 1 + * - pll_fp = 4 + * @param none + * @retval none + */ +void system_clock_config(void) +{ + /* reset crm */ + crm_reset(); + + /* set the flash clock divider */ + flash_psr_set(FLASH_WAIT_CYCLE_5); + + /* enable pwc periph clock */ + crm_periph_clock_enable(CRM_PWC_PERIPH_CLOCK, TRUE); + + /* config ldo voltage */ + pwc_ldo_output_voltage_set(PWC_LDO_OUTPUT_1V3); + + crm_clock_source_enable(CRM_CLOCK_SOURCE_HEXT, TRUE); + + /* wait till hext is ready */ + while(crm_hext_stable_wait() == ERROR) + { + } + + /* config pll clock resource */ + crm_pll_config(CRM_PLL_SOURCE_HEXT, 96, 1, CRM_PLL_FP_4); + + /* config pllu divider */ + crm_pllu_div_set(CRM_PLL_FU_16); + + /* pllu enable */ + crm_pllu_output_set(TRUE); + + /* enable pll */ + crm_clock_source_enable(CRM_CLOCK_SOURCE_PLL, TRUE); + + /* wait till pll is ready */ + while(crm_flag_get(CRM_PLL_STABLE_FLAG) != SET) + { + } + + /* config ahbclk */ + crm_ahb_div_set(CRM_AHB_DIV_1); + + /* config apb3clk, the maximum frequency of APB3 clock is 90 MHz */ + crm_apb3_div_set(CRM_APB3_DIV_4); + + /* config apb2clk, the maximum frequency of APB2 clock is 192 MHz */ + crm_apb2_div_set(CRM_APB2_DIV_1); + + /* config apb1clk, the maximum frequency of APB1 clock is 192 MHz */ + crm_apb1_div_set(CRM_APB1_DIV_1); + + /* enable auto step mode */ + crm_auto_step_mode_enable(TRUE); + + /* select pll as system clock source */ + crm_sysclk_switch(CRM_SCLK_PLL); + + /* wait till pll is used as system clock source */ + while(crm_sysclk_switch_status_get() != CRM_SCLK_PLL) + { + } + + /* disable auto step mode */ + crm_auto_step_mode_enable(FALSE); + + /* update system_core_clock global variable */ + system_core_clock_update(); +} diff --git a/hw/bsp/at32f45x/at32f45x_clock.h b/hw/bsp/at32f45x/at32f45x_clock.h new file mode 100644 index 000000000..a372a605b --- /dev/null +++ b/hw/bsp/at32f45x/at32f45x_clock.h @@ -0,0 +1,44 @@ +/** + ************************************************************************** + * @file at32f45x_clock.h + * @brief header file of clock program + ************************************************************************** + * + * Copyright (c) 2025, Artery Technology, All rights reserved. + * + * The software Board Support Package (BSP) that is made available to + * download from Artery official website is the copyrighted work of Artery. + * Artery authorizes customers to use, copy, and distribute the BSP + * software and its related documentation for the purpose of design and + * development in conjunction with Artery microcontrollers. Use of the + * software is governed by this copyright notice and the following disclaimer. + * + * THIS SOFTWARE IS PROVIDED ON "AS IS" BASIS WITHOUT WARRANTIES, + * GUARANTEES OR REPRESENTATIONS OF ANY KIND. ARTERY EXPRESSLY DISCLAIMS, + * TO THE FULLEST EXTENT PERMITTED BY LAW, ALL EXPRESS, IMPLIED OR + * STATUTORY OR OTHER WARRANTIES, GUARANTEES OR REPRESENTATIONS, + * INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. + * + ************************************************************************** + */ + +/* define to prevent recursive inclusion -------------------------------------*/ +#ifndef __AT32F45x_CLOCK_H +#define __AT32F45x_CLOCK_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* includes ------------------------------------------------------------------*/ +#include "at32f45x.h" + +/* exported functions ------------------------------------------------------- */ +void system_clock_config(void); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/hw/bsp/at32f45x/at32f45x_conf.h b/hw/bsp/at32f45x/at32f45x_conf.h new file mode 100644 index 000000000..90182437f --- /dev/null +++ b/hw/bsp/at32f45x/at32f45x_conf.h @@ -0,0 +1,174 @@ +/** + ************************************************************************** + * @file at32f45x_conf.h + * @brief at32f45x config header file + ************************************************************************** + * + * Copyright (c) 2025, Artery Technology, All rights reserved. + * + * The software Board Support Package (BSP) that is made available to + * download from Artery official website is the copyrighted work of Artery. + * Artery authorizes customers to use, copy, and distribute the BSP + * software and its related documentation for the purpose of design and + * development in conjunction with Artery microcontrollers. Use of the + * software is governed by this copyright notice and the following disclaimer. + * + * THIS SOFTWARE IS PROVIDED ON "AS IS" BASIS WITHOUT WARRANTIES, + * GUARANTEES OR REPRESENTATIONS OF ANY KIND. ARTERY EXPRESSLY DISCLAIMS, + * TO THE FULLEST EXTENT PERMITTED BY LAW, ALL EXPRESS, IMPLIED OR + * STATUTORY OR OTHER WARRANTIES, GUARANTEES OR REPRESENTATIONS, + * INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. + * + ************************************************************************** + */ + +/* define to prevent recursive inclusion -------------------------------------*/ +#ifndef __AT32F45x_CONF_H +#define __AT32F45x_CONF_H + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief in the following line adjust the value of high speed external crystal (hext) + * used in your application + * + * tip: to avoid modifying this file each time you need to use different hext, you + * can define the hext value in your toolchain compiler preprocessor. + * + */ +#if !defined HEXT_VALUE +#define HEXT_VALUE ((uint32_t)8000000) /*!< value of the high speed external crystal in hz */ +#endif + +/** + * @brief in the following line adjust the high speed external crystal (hext) startup + * timeout value + */ +#define HEXT_STARTUP_TIMEOUT ((uint16_t)0x3000) /*!< time out for hext start up */ +#define HICK_VALUE ((uint32_t)8000000) /*!< value of the high speed internal clock in hz */ +#define LEXT_VALUE ((uint32_t)32768) /*!< value of the low speed external clock in hz */ + +/* module define -------------------------------------------------------------*/ +#define ACC_MODULE_ENABLED +#define ADC_MODULE_ENABLED +#define AES_MODULE_ENABLED +#define CAN_MODULE_ENABLED +#define CRC_MODULE_ENABLED +#define CRM_MODULE_ENABLED +#define DAC_MODULE_ENABLED +#define DEBUG_MODULE_ENABLED +#define DMA_MODULE_ENABLED +#define EMAC_MODULE_ENABLED +#define ERTC_MODULE_ENABLED +#define EXINT_MODULE_ENABLED +#define FLASH_MODULE_ENABLED +#define GPIO_MODULE_ENABLED +#define I2C_MODULE_ENABLED +#define MISC_MODULE_ENABLED +#define PWC_MODULE_ENABLED +#define QSPI_MODULE_ENABLED +#define SCFG_MODULE_ENABLED +#define SDIO_MODULE_ENABLED +#define SPI_MODULE_ENABLED +#define TMR_MODULE_ENABLED +#define TRNG_MODULE_ENABLED +#define USART_MODULE_ENABLED +#define USB_MODULE_ENABLED +#define WWDT_MODULE_ENABLED +#define WDT_MODULE_ENABLED +#define XMC_MODULE_ENABLED + +/* includes ------------------------------------------------------------------*/ +#ifdef ACC_MODULE_ENABLED +#include "at32f45x_acc.h" +#endif +#ifdef ADC_MODULE_ENABLED +#include "at32f45x_adc.h" +#endif +#ifdef AES_MODULE_ENABLED +#include "at32f45x_aes.h" +#endif +#ifdef CAN_MODULE_ENABLED +#include "at32f45x_can.h" +#endif +#ifdef CRC_MODULE_ENABLED +#include "at32f45x_crc.h" +#endif +#ifdef CRM_MODULE_ENABLED +#include "at32f45x_crm.h" +#endif +#ifdef DAC_MODULE_ENABLED +#include "at32f45x_dac.h" +#endif +#ifdef DEBUG_MODULE_ENABLED +#include "at32f45x_debug.h" +#endif +#ifdef DMA_MODULE_ENABLED +#include "at32f45x_dma.h" +#endif +#ifdef EMAC_MODULE_ENABLED +#include "at32f45x_emac.h" +#endif +#ifdef ERTC_MODULE_ENABLED +#include "at32f45x_ertc.h" +#endif +#ifdef EXINT_MODULE_ENABLED +#include "at32f45x_exint.h" +#endif +#ifdef FLASH_MODULE_ENABLED +#include "at32f45x_flash.h" +#endif +#ifdef GPIO_MODULE_ENABLED +#include "at32f45x_gpio.h" +#endif +#ifdef I2C_MODULE_ENABLED +#include "at32f45x_i2c.h" +#endif +#ifdef MISC_MODULE_ENABLED +#include "at32f45x_misc.h" +#endif +#ifdef PWC_MODULE_ENABLED +#include "at32f45x_pwc.h" +#endif +#ifdef QSPI_MODULE_ENABLED +#include "at32f45x_qspi.h" +#endif +#ifdef SCFG_MODULE_ENABLED +#include "at32f45x_scfg.h" +#endif +#ifdef SDIO_MODULE_ENABLED +#include "at32f45x_sdio.h" +#endif +#ifdef SPI_MODULE_ENABLED +#include "at32f45x_spi.h" +#endif +#ifdef TMR_MODULE_ENABLED +#include "at32f45x_tmr.h" +#endif +#ifdef TRNG_MODULE_ENABLED +#include "at32f45x_trng.h" +#endif +#ifdef USART_MODULE_ENABLED +#include "at32f45x_usart.h" +#endif +#ifdef USB_MODULE_ENABLED +#include "at32f45x_usb.h" +#endif +#ifdef WDT_MODULE_ENABLED +#include "at32f45x_wdt.h" +#endif +#ifdef WWDT_MODULE_ENABLED +#include "at32f45x_wwdt.h" +#endif +#ifdef XMC_MODULE_ENABLED +#include "at32f45x_xmc.h" +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/hw/bsp/at32f45x/at32f45x_int.c b/hw/bsp/at32f45x/at32f45x_int.c new file mode 100644 index 000000000..b3ba6ad9c --- /dev/null +++ b/hw/bsp/at32f45x/at32f45x_int.c @@ -0,0 +1,100 @@ +/** + ************************************************************************** + * @file at32f45x_int.c + * @brief main interrupt service routines. + ************************************************************************** + * + * Copyright (c) 2025, Artery Technology, All rights reserved. + * + * The software Board Support Package (BSP) that is made available to + * download from Artery official website is the copyrighted work of Artery. + * Artery authorizes customers to use, copy, and distribute the BSP + * software and its related documentation for the purpose of design and + * development in conjunction with Artery microcontrollers. Use of the + * software is governed by this copyright notice and the following disclaimer. + * + * THIS SOFTWARE IS PROVIDED ON "AS IS" BASIS WITHOUT WARRANTIES, + * GUARANTEES OR REPRESENTATIONS OF ANY KIND. ARTERY EXPRESSLY DISCLAIMS, + * TO THE FULLEST EXTENT PERMITTED BY LAW, ALL EXPRESS, IMPLIED OR + * STATUTORY OR OTHER WARRANTIES, GUARANTEES OR REPRESENTATIONS, + * INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. + * + ************************************************************************** + */ + +/* includes ------------------------------------------------------------------*/ +#include "at32f45x_int.h" + +/** @addtogroup AT32F45X_BSP + * @{ + */ + +/** @addtogroup AT32F45X_USB_Device_Keyboard + * @{ + */ + +/** + * @brief this function handles nmi exception. + * @param none + * @retval none + */ +void NMI_Handler(void) +{ +} + +/** + * @brief this function handles memory manage exception. + * @param none + * @retval none + */ +void MemManage_Handler(void) +{ + /* go to infinite loop when memory manage exception occurs */ + while(1) + { + } +} + +/** + * @brief this function handles bus fault exception. + * @param none + * @retval none + */ +void BusFault_Handler(void) +{ + /* go to infinite loop when bus fault exception occurs */ + while(1) + { + } +} + +/** + * @brief this function handles usage fault exception. + * @param none + * @retval none + */ +void UsageFault_Handler(void) +{ + /* go to infinite loop when usage fault exception occurs */ + while(1) + { + } +} + +/** + * @brief this function handles debug monitor exception. + * @param none + * @retval none + */ +void DebugMon_Handler(void) +{ +} + +/** + * @} + */ + +/** + * @} + */ diff --git a/hw/bsp/at32f45x/at32f45x_int.h b/hw/bsp/at32f45x/at32f45x_int.h new file mode 100644 index 000000000..3a2667e9d --- /dev/null +++ b/hw/bsp/at32f45x/at32f45x_int.h @@ -0,0 +1,59 @@ +/** + ************************************************************************** + * @file at32f45x_int.h + * @brief header file of main interrupt service routines. + ************************************************************************** + * + * Copyright (c) 2025, Artery Technology, All rights reserved. + * + * The software Board Support Package (BSP) that is made available to + * download from Artery official website is the copyrighted work of Artery. + * Artery authorizes customers to use, copy, and distribute the BSP + * software and its related documentation for the purpose of design and + * development in conjunction with Artery microcontrollers. Use of the + * software is governed by this copyright notice and the following disclaimer. + * + * THIS SOFTWARE IS PROVIDED ON "AS IS" BASIS WITHOUT WARRANTIES, + * GUARANTEES OR REPRESENTATIONS OF ANY KIND. ARTERY EXPRESSLY DISCLAIMS, + * TO THE FULLEST EXTENT PERMITTED BY LAW, ALL EXPRESS, IMPLIED OR + * STATUTORY OR OTHER WARRANTIES, GUARANTEES OR REPRESENTATIONS, + * INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. + * + ************************************************************************** + */ + +/* define to prevent recursive inclusion -------------------------------------*/ +#ifndef __AT32F45x_INT_H +#define __AT32F45x_INT_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* includes ------------------------------------------------------------------*/ +#include "at32f45x.h" + +/* exported types ------------------------------------------------------------*/ +/* exported constants --------------------------------------------------------*/ +/* exported macro ------------------------------------------------------------*/ +/* exported functions ------------------------------------------------------- */ + +void NMI_Handler(void); +void HardFault_Handler(void); +void MemManage_Handler(void); +void BusFault_Handler(void); +void UsageFault_Handler(void); +void SVC_Handler(void); +void DebugMon_Handler(void); +void PendSV_Handler(void); +void SysTick_Handler(void); + +void OTGFS1_IRQHandler(void); +void OTGFS1_WKUP_IRQHandler(void); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/hw/bsp/at32f45x/boards/at_start_f455/board.cmake b/hw/bsp/at32f45x/boards/at_start_f455/board.cmake new file mode 100644 index 000000000..f06f9599e --- /dev/null +++ b/hw/bsp/at32f45x/boards/at_start_f455/board.cmake @@ -0,0 +1,8 @@ +set(MCU_VARIANT AT32F455ZET7) +set(MCU_LINKER_NAME AT32F455xE) + +set(JLINK_DEVICE ${MCU_VARIANT}) + +function(update_board TARGET) + target_compile_definitions(${TARGET} PUBLIC ${MCU_VARIANT}) +endfunction() diff --git a/hw/bsp/at32f45x/boards/at_start_f455/board.h b/hw/bsp/at32f45x/boards/at_start_f455/board.h new file mode 100644 index 000000000..64e27c016 --- /dev/null +++ b/hw/bsp/at32f45x/boards/at_start_f455/board.h @@ -0,0 +1,96 @@ +/* + * 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: AT-START-F455 + url: https://www.arterychip.com/en/product/AT32F455.jsp +*/ + +#ifndef BOARD_H_ +#define BOARD_H_ + +#ifdef __cplusplus + extern "C" { +#endif + +#define USB_VBUS_IGNORE + +// LED +#define LED_PORT GPIOD +#define LED_PIN GPIO_PINS_13 +#define LED_STATE_ON 0 // Active Low +#define LED_GPIO_CLK_EN() crm_periph_clock_enable(CRM_GPIOD_PERIPH_CLOCK, TRUE) + +// Button +#define BUTTON_PORT GPIOA +#define BUTTON_PIN GPIO_PINS_0 +#define BUTTON_STATE_ACTIVE 1 +#define BUTTON_GPIO_CLK_EN() crm_periph_clock_enable(CRM_GPIOA_PERIPH_CLOCK, TRUE) + +// UART +#define PRINT_UART USART1 +#define PRINT_UART_CRM_CLK CRM_USART1_PERIPH_CLOCK +#define PRINT_UART_TX_PIN GPIO_PINS_9 +#define PRINT_UART_TX_GPIO GPIOA +#define PRINT_UART_TX_GPIO_CRM_CLK CRM_GPIOA_PERIPH_CLOCK +#define PRINT_UART_TX_PIN_SOURCE GPIO_PINS_SOURCE9 +#define PRINT_UART_TX_PIN_MUX_NUM GPIO_MUX_7 + +//USB +#define USB_ID 0 +#define OTG_CLOCK CRM_OTGFS1_PERIPH_CLOCK +#define OTG_IRQ OTGFS1_IRQn +#define OTG_IRQ_HANDLER OTGFS1_IRQHandler +#define OTG_WKUP_IRQ OTGFS1_WKUP_IRQn +#define OTG_WKUP_HANDLER OTGFS1_WKUP_IRQHandler +#define OTG_WKUP_EXINT_LINE EXINT_LINE_18 +#define OTG_PIN_GPIO GPIOA +#define OTG_PIN_GPIO_CLOCK CRM_GPIOA_PERIPH_CLOCK +#define OTG_PIN_DP GPIO_PINS_12 +#define OTG_PIN_DP_SOURCE GPIO_PINS_SOURCE12 +#define OTG_PIN_DM GPIO_PINS_11 +#define OTG_PIN_DM_SOURCE GPIO_PINS_SOURCE11 +#define OTG_PIN_VBUS GPIO_PINS_9 +#define OTG_PIN_VBUS_SOURCE GPIO_PINS_SOURCE9 +#define OTG_PIN_ID GPIO_PINS_10 +#define OTG_PIN_ID_SOURCE GPIO_PINS_SOURCE10 +#define OTG_PIN_SOF_GPIO GPIOA +#define OTG_PIN_SOF_GPIO_CLOCK CRM_GPIOA_PERIPH_CLOCK +#define OTG_PIN_SOF GPIO_PINS_8 +#define OTG_PIN_SOF_SOURCE GPIO_PINS_SOURCE8 +#define OTG_PIN_MUX GPIO_MUX_10 + +//Vbus +static inline void board_vbus_sense_init(void) +{ + *(int*)(0x50000038) |= (1<<21); +} + +#ifdef __cplusplus + } +#endif + +#endif /* BOARD_H_ */ diff --git a/hw/bsp/at32f45x/boards/at_start_f455/board.mk b/hw/bsp/at32f45x/boards/at_start_f455/board.mk new file mode 100644 index 000000000..7c24ad288 --- /dev/null +++ b/hw/bsp/at32f45x/boards/at_start_f455/board.mk @@ -0,0 +1,7 @@ +MCU_VARIANT = AT32F455ZET7 +MCU_LINKER_NAME = AT32F455xE + +JLINK_DEVICE = ${MCU_VARIANT} + +CFLAGS += \ + -D${MCU_VARIANT} diff --git a/hw/bsp/at32f45x/boards/at_start_f456/board.cmake b/hw/bsp/at32f45x/boards/at_start_f456/board.cmake new file mode 100644 index 000000000..a5048d3b1 --- /dev/null +++ b/hw/bsp/at32f45x/boards/at_start_f456/board.cmake @@ -0,0 +1,8 @@ +set(MCU_VARIANT AT32F456ZET7) +set(MCU_LINKER_NAME AT32F456xE) + +set(JLINK_DEVICE ${MCU_VARIANT}) + +function(update_board TARGET) + target_compile_definitions(${TARGET} PUBLIC ${MCU_VARIANT}) +endfunction() diff --git a/hw/bsp/at32f45x/boards/at_start_f456/board.h b/hw/bsp/at32f45x/boards/at_start_f456/board.h new file mode 100644 index 000000000..d3d734a9b --- /dev/null +++ b/hw/bsp/at32f45x/boards/at_start_f456/board.h @@ -0,0 +1,96 @@ +/* + * 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: AT-START-F456 + url: https://www.arterychip.com/en/product/AT32F456.jsp +*/ + +#ifndef BOARD_H_ +#define BOARD_H_ + +#ifdef __cplusplus + extern "C" { +#endif + +#define USB_VBUS_IGNORE + +// LED +#define LED_PORT GPIOD +#define LED_PIN GPIO_PINS_13 +#define LED_STATE_ON 0 // Active Low +#define LED_GPIO_CLK_EN() crm_periph_clock_enable(CRM_GPIOD_PERIPH_CLOCK, TRUE) + +// Button +#define BUTTON_PORT GPIOA +#define BUTTON_PIN GPIO_PINS_0 +#define BUTTON_STATE_ACTIVE 1 +#define BUTTON_GPIO_CLK_EN() crm_periph_clock_enable(CRM_GPIOA_PERIPH_CLOCK, TRUE) + +// UART +#define PRINT_UART USART1 +#define PRINT_UART_CRM_CLK CRM_USART1_PERIPH_CLOCK +#define PRINT_UART_TX_PIN GPIO_PINS_9 +#define PRINT_UART_TX_GPIO GPIOA +#define PRINT_UART_TX_GPIO_CRM_CLK CRM_GPIOA_PERIPH_CLOCK +#define PRINT_UART_TX_PIN_SOURCE GPIO_PINS_SOURCE9 +#define PRINT_UART_TX_PIN_MUX_NUM GPIO_MUX_7 + +//USB +#define USB_ID 0 +#define OTG_CLOCK CRM_OTGFS1_PERIPH_CLOCK +#define OTG_IRQ OTGFS1_IRQn +#define OTG_IRQ_HANDLER OTGFS1_IRQHandler +#define OTG_WKUP_IRQ OTGFS1_WKUP_IRQn +#define OTG_WKUP_HANDLER OTGFS1_WKUP_IRQHandler +#define OTG_WKUP_EXINT_LINE EXINT_LINE_18 +#define OTG_PIN_GPIO GPIOA +#define OTG_PIN_GPIO_CLOCK CRM_GPIOA_PERIPH_CLOCK +#define OTG_PIN_DP GPIO_PINS_12 +#define OTG_PIN_DP_SOURCE GPIO_PINS_SOURCE12 +#define OTG_PIN_DM GPIO_PINS_11 +#define OTG_PIN_DM_SOURCE GPIO_PINS_SOURCE11 +#define OTG_PIN_VBUS GPIO_PINS_9 +#define OTG_PIN_VBUS_SOURCE GPIO_PINS_SOURCE9 +#define OTG_PIN_ID GPIO_PINS_10 +#define OTG_PIN_ID_SOURCE GPIO_PINS_SOURCE10 +#define OTG_PIN_SOF_GPIO GPIOA +#define OTG_PIN_SOF_GPIO_CLOCK CRM_GPIOA_PERIPH_CLOCK +#define OTG_PIN_SOF GPIO_PINS_8 +#define OTG_PIN_SOF_SOURCE GPIO_PINS_SOURCE8 +#define OTG_PIN_MUX GPIO_MUX_10 + +//Vbus +static inline void board_vbus_sense_init(void) +{ + *(int*)(0x50000038) |= (1<<21); +} + +#ifdef __cplusplus + } +#endif + +#endif /* BOARD_H_ */ diff --git a/hw/bsp/at32f45x/boards/at_start_f456/board.mk b/hw/bsp/at32f45x/boards/at_start_f456/board.mk new file mode 100644 index 000000000..596d99d61 --- /dev/null +++ b/hw/bsp/at32f45x/boards/at_start_f456/board.mk @@ -0,0 +1,7 @@ +MCU_VARIANT = AT32F456ZET7 +MCU_LINKER_NAME = AT32F456xE + +JLINK_DEVICE = ${MCU_VARIANT} + +CFLAGS += \ + -D${MCU_VARIANT} diff --git a/hw/bsp/at32f45x/boards/at_start_f457/board.cmake b/hw/bsp/at32f45x/boards/at_start_f457/board.cmake new file mode 100644 index 000000000..c8cd886be --- /dev/null +++ b/hw/bsp/at32f45x/boards/at_start_f457/board.cmake @@ -0,0 +1,8 @@ +set(MCU_VARIANT AT32F457ZET7) +set(MCU_LINKER_NAME AT32F457xE) + +set(JLINK_DEVICE ${MCU_VARIANT}) + +function(update_board TARGET) + target_compile_definitions(${TARGET} PUBLIC ${MCU_VARIANT}) +endfunction() diff --git a/hw/bsp/at32f45x/boards/at_start_f457/board.h b/hw/bsp/at32f45x/boards/at_start_f457/board.h new file mode 100644 index 000000000..2216b1ed3 --- /dev/null +++ b/hw/bsp/at32f45x/boards/at_start_f457/board.h @@ -0,0 +1,96 @@ +/* + * 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: AT-START-F457 + url: https://www.arterychip.com/en/product/AT32F457.jsp +*/ + +#ifndef BOARD_H_ +#define BOARD_H_ + +#ifdef __cplusplus + extern "C" { +#endif + +#define USB_VBUS_IGNORE + +// LED +#define LED_PORT GPIOD +#define LED_PIN GPIO_PINS_13 +#define LED_STATE_ON 0 // Active Low +#define LED_GPIO_CLK_EN() crm_periph_clock_enable(CRM_GPIOD_PERIPH_CLOCK, TRUE) + +// Button +#define BUTTON_PORT GPIOA +#define BUTTON_PIN GPIO_PINS_0 +#define BUTTON_STATE_ACTIVE 1 +#define BUTTON_GPIO_CLK_EN() crm_periph_clock_enable(CRM_GPIOA_PERIPH_CLOCK, TRUE) + +// UART +#define PRINT_UART USART1 +#define PRINT_UART_CRM_CLK CRM_USART1_PERIPH_CLOCK +#define PRINT_UART_TX_PIN GPIO_PINS_9 +#define PRINT_UART_TX_GPIO GPIOA +#define PRINT_UART_TX_GPIO_CRM_CLK CRM_GPIOA_PERIPH_CLOCK +#define PRINT_UART_TX_PIN_SOURCE GPIO_PINS_SOURCE9 +#define PRINT_UART_TX_PIN_MUX_NUM GPIO_MUX_7 + +//USB +#define USB_ID 0 +#define OTG_CLOCK CRM_OTGFS1_PERIPH_CLOCK +#define OTG_IRQ OTGFS1_IRQn +#define OTG_IRQ_HANDLER OTGFS1_IRQHandler +#define OTG_WKUP_IRQ OTGFS1_WKUP_IRQn +#define OTG_WKUP_HANDLER OTGFS1_WKUP_IRQHandler +#define OTG_WKUP_EXINT_LINE EXINT_LINE_18 +#define OTG_PIN_GPIO GPIOA +#define OTG_PIN_GPIO_CLOCK CRM_GPIOA_PERIPH_CLOCK +#define OTG_PIN_DP GPIO_PINS_12 +#define OTG_PIN_DP_SOURCE GPIO_PINS_SOURCE12 +#define OTG_PIN_DM GPIO_PINS_11 +#define OTG_PIN_DM_SOURCE GPIO_PINS_SOURCE11 +#define OTG_PIN_VBUS GPIO_PINS_9 +#define OTG_PIN_VBUS_SOURCE GPIO_PINS_SOURCE9 +#define OTG_PIN_ID GPIO_PINS_10 +#define OTG_PIN_ID_SOURCE GPIO_PINS_SOURCE10 +#define OTG_PIN_SOF_GPIO GPIOA +#define OTG_PIN_SOF_GPIO_CLOCK CRM_GPIOA_PERIPH_CLOCK +#define OTG_PIN_SOF GPIO_PINS_8 +#define OTG_PIN_SOF_SOURCE GPIO_PINS_SOURCE8 +#define OTG_PIN_MUX GPIO_MUX_10 + +//Vbus +static inline void board_vbus_sense_init(void) +{ + *(int*)(0x50000038) |= (1<<21); +} + +#ifdef __cplusplus + } +#endif + +#endif /* BOARD_H_ */ diff --git a/hw/bsp/at32f45x/boards/at_start_f457/board.mk b/hw/bsp/at32f45x/boards/at_start_f457/board.mk new file mode 100644 index 000000000..4cb4adad5 --- /dev/null +++ b/hw/bsp/at32f45x/boards/at_start_f457/board.mk @@ -0,0 +1,7 @@ +MCU_VARIANT = AT32F457ZET7 +MCU_LINKER_NAME = AT32F457xE + +JLINK_DEVICE = ${MCU_VARIANT} + +CFLAGS += \ + -D${MCU_VARIANT} diff --git a/hw/bsp/at32f45x/family.c b/hw/bsp/at32f45x/family.c new file mode 100644 index 000000000..0593e5115 --- /dev/null +++ b/hw/bsp/at32f45x/family.c @@ -0,0 +1,258 @@ +/* + * 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. + */ + +/* metadata: + manufacturer: Artery +*/ + +#include "at32f45x_clock.h" +#include "at32f45x_int.h" +#include "board.h" +#include "bsp/board_api.h" + +void usb_clock48m_select(usb_clk48_s clk_s); +void led_and_button_init(void); +void uart_print_init(uint32_t baudrate); +//--------------------------------------------------------------------+ +// Forward USB interrupt events to TinyUSB IRQ Handler +//--------------------------------------------------------------------+ +void OTGFS1_IRQHandler(void) { + tusb_int_handler(0, true); +} +void OTGFS1_WKUP_IRQHandler(void) { + tusb_int_handler(0, true); +} + +void board_init(void) { + /* config nvic priority group */ + nvic_priority_group_config(NVIC_PRIORITY_GROUP_4); + + /* config system clock */ + system_clock_config(); + + /* enable usb clock */ + crm_periph_clock_enable(OTG_CLOCK, TRUE); + + /* select usb 48m clcok source */ + usb_clock48m_select(USB_CLK_HEXT); + + /* vbus ignore */ + board_vbus_sense_init(); + + /* configure systick */ + systick_clock_source_config(SYSTICK_CLOCK_SOURCE_AHBCLK_NODIV); + SysTick_Config(system_core_clock / 1000); +#if CFG_TUSB_OS == OPT_OS_FREERTOS + // If freeRTOS is used, IRQ priority is limit by max syscall ( smaller is higher ) + NVIC_SetPriority(OTG_IRQ, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY); +#endif + +/* otgfs use vbus pin */ +#ifndef USB_VBUS_IGNORE + gpio_init_type gpio_init_struct; + crm_periph_clock_enable(OTG_PIN_GPIO_CLOCK, TRUE); + gpio_default_para_init(&gpio_init_struct); + gpio_init_struct.gpio_drive_strength = GPIO_DRIVE_STRENGTH_STRONGER; + gpio_init_struct.gpio_out_type = GPIO_OUTPUT_PUSH_PULL; + gpio_init_struct.gpio_mode = GPIO_MODE_MUX; + gpio_init_struct.gpio_pins = OTG_PIN_VBUS; + gpio_init_struct.gpio_pull = GPIO_PULL_DOWN; + gpio_pin_mux_config(OTG_PIN_GPIO, OTG_PIN_VBUS_SOURCE, OTG_PIN_MUX); + gpio_init(OTG_PIN_GPIO, &gpio_init_struct); +#endif + + /* config led and key */ + led_and_button_init(); + + /* config usart printf */ + uart_print_init(115200); + printf("usart printf config success!\r\n"); +} + +//--------------------------------------------------------------------+ +// Board porting API +//--------------------------------------------------------------------+ +/** + * @brief usb 48M clock select + * @param clk_s:USB_CLK_HICK, USB_CLK_HEXT + * @retval none + */ +void usb_clock48m_select(usb_clk48_s clk_s) +{ + if(clk_s == USB_CLK_HICK) + { + crm_usb_clock_source_select(CRM_USB_CLOCK_SOURCE_HICK); + + /* enable the acc calibration ready interrupt */ + crm_periph_clock_enable(CRM_ACC_PERIPH_CLOCK, TRUE); + + /* update the c1\c2\c3 value */ + acc_write_c1(7980); + acc_write_c2(8000); + acc_write_c3(8020); + + /* open acc calibration */ + acc_calibration_mode_enable(ACC_CAL_HICKTRIM, TRUE); + } + else + { + crm_usb_clock_source_select(CRM_USB_CLOCK_SOURCE_PLLU); + } +} + +void uart_print_init(uint32_t baudrate) { + gpio_init_type gpio_init_struct; + /* enable the uart and gpio clock */ + crm_periph_clock_enable(PRINT_UART_CRM_CLK, TRUE); + crm_periph_clock_enable(PRINT_UART_TX_GPIO_CRM_CLK, TRUE); + gpio_default_para_init(&gpio_init_struct); + /* configure the uart tx pin */ + gpio_init_struct.gpio_drive_strength = GPIO_DRIVE_STRENGTH_STRONGER; + gpio_init_struct.gpio_out_type = GPIO_OUTPUT_PUSH_PULL; + gpio_init_struct.gpio_mode = GPIO_MODE_MUX; + gpio_init_struct.gpio_pins = PRINT_UART_TX_PIN; + gpio_init_struct.gpio_pull = GPIO_PULL_NONE; + gpio_init(PRINT_UART_TX_GPIO, &gpio_init_struct); + gpio_pin_mux_config(PRINT_UART_TX_GPIO, PRINT_UART_TX_PIN_SOURCE, PRINT_UART_TX_PIN_MUX_NUM); + /* configure uart param */ + usart_init(PRINT_UART, baudrate, USART_DATA_8BITS, USART_STOP_1_BIT); + usart_transmitter_enable(PRINT_UART, TRUE); + usart_enable(PRINT_UART, TRUE); +} + +void led_and_button_init(void) { + /* LED */ + gpio_init_type gpio_led_init_struct; + /* enable the led clock */ + LED_GPIO_CLK_EN(); + /* set default parameter */ + gpio_default_para_init(&gpio_led_init_struct); + /* configure the led gpio */ + gpio_led_init_struct.gpio_drive_strength = GPIO_DRIVE_STRENGTH_STRONGER; + gpio_led_init_struct.gpio_out_type = GPIO_OUTPUT_PUSH_PULL; + gpio_led_init_struct.gpio_mode = GPIO_MODE_OUTPUT; + gpio_led_init_struct.gpio_pins = LED_PIN; + gpio_led_init_struct.gpio_pull = GPIO_PULL_NONE; + gpio_init(LED_PORT, &gpio_led_init_struct); + /* Button */ + gpio_init_type gpio_button_init_struct; + /* enable the button clock */ + BUTTON_GPIO_CLK_EN(); + /* set default parameter */ + gpio_default_para_init(&gpio_button_init_struct); + /* configure the button gpio */ + gpio_button_init_struct.gpio_drive_strength = GPIO_DRIVE_STRENGTH_STRONGER; + gpio_button_init_struct.gpio_out_type = GPIO_OUTPUT_PUSH_PULL; + gpio_button_init_struct.gpio_mode = GPIO_MODE_INPUT; + gpio_button_init_struct.gpio_pins = BUTTON_PIN; + gpio_button_init_struct.gpio_pull = GPIO_PULL_DOWN; + gpio_init(BUTTON_PORT, &gpio_button_init_struct); +} + +void board_led_write(bool state) { + gpio_bits_write(LED_PORT, LED_PIN, state ^ (!LED_STATE_ON)); +} + +uint32_t board_button_read(void) { + return gpio_input_data_bit_read(BUTTON_PORT, BUTTON_PIN); +} + +size_t board_get_unique_id(uint8_t id[], size_t max_len) { + (void) max_len; + volatile uint32_t *at32_uuid = ((volatile uint32_t *) 0x1FFFF7E8); + uint32_t *id32 = (uint32_t *) (uintptr_t) id; + uint8_t const len = 12; + + id32[0] = at32_uuid[0]; + id32[1] = at32_uuid[1]; + id32[2] = at32_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) { +#if CFG_TUSB_OS == OPT_OS_NONE + int txsize = len; + uint16_t timeout = 0xffff; + while (txsize--) { + while (usart_flag_get(PRINT_UART, USART_TDBE_FLAG) == RESET) { + timeout--; + if (timeout == 0) { + return 0; + } + } + PRINT_UART->dt = (*((uint8_t const *) buf) & 0x01FF); + buf++; + } + return len; +#else + (void) buf; + (void) len; + return 0; +#endif +} + +#if CFG_TUSB_OS == OPT_OS_NONE +volatile uint32_t system_ticks = 0; +void SysTick_Handler(void) { + system_ticks++; +} + +uint32_t board_millis(void) { + return system_ticks; +} + +void SVC_Handler(void) { +} + +void PendSV_Handler(void) { +} +#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); +void _init(void) { +} + +#ifdef USE_FULL_ASSERT +void assert_failed(const char *file, uint32_t line) { + /* USER CODE BEGIN 6 */ + /* User can add his own implementation to report the file name and line number, + e.g.: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ + /* USER CODE END 6 */ +} +#endif /* USE_FULL_ASSERT */ diff --git a/hw/bsp/at32f45x/family.cmake b/hw/bsp/at32f45x/family.cmake new file mode 100644 index 000000000..fe13347af --- /dev/null +++ b/hw/bsp/at32f45x/family.cmake @@ -0,0 +1,97 @@ +include_guard() + +set(AT32_FAMILY at32f45x) +set(AT32_SDK_LIB ${TOP}/hw/mcu/artery/${AT32_FAMILY}/libraries) + +string(TOUPPER ${AT32_FAMILY} AT32_FAMILY_UPPER) + +# 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) + +set(FAMILY_MCUS ${AT32_FAMILY_UPPER} CACHE INTERNAL "") + +#------------------------------------ +# Startup & Linker script +#------------------------------------ +set(STARTUP_FILE_GNU ${AT32_SDK_LIB}/cmsis/cm4/device_support/startup/gcc/startup_${AT32_FAMILY}.s) +set(STARTUP_FILE_Clang ${STARTUP_FILE_GNU}) +set(STARTUP_FILE_IAR ${AT32_SDK_LIB}/cmsis/cm4/device_support/startup/iar/startup_${AT32_FAMILY}.s) +if (NOT DEFINED LD_FILE_GNU) +set(LD_FILE_GNU ${AT32_SDK_LIB}/cmsis/cm4/device_support/startup/gcc/linker/${MCU_LINKER_NAME}_FLASH.ld) +endif () +set(LD_FILE_Clang ${LD_FILE_GNU}) +set(LD_FILE_IAR ${AT32_SDK_LIB}/cmsis/cm4/device_support/startup/iar/linker/${MCU_LINKER_NAME}.icf) + +#------------------------------------ +# BOARD_TARGET +#------------------------------------ +function(family_add_board BOARD_TARGET) + add_library(${BOARD_TARGET} STATIC + ${AT32_SDK_LIB}/cmsis/cm4/device_support/system_${AT32_FAMILY}.c + ${AT32_SDK_LIB}/drivers/src/${AT32_FAMILY}_gpio.c + ${AT32_SDK_LIB}/drivers/src/${AT32_FAMILY}_misc.c + ${AT32_SDK_LIB}/drivers/src/${AT32_FAMILY}_usart.c + ${AT32_SDK_LIB}/drivers/src/${AT32_FAMILY}_acc.c + ${AT32_SDK_LIB}/drivers/src/${AT32_FAMILY}_crm.c + ) + target_include_directories(${BOARD_TARGET} PUBLIC + ${CMAKE_CURRENT_FUNCTION_LIST_DIR} + ${AT32_SDK_LIB}/cmsis/cm4/core_support + ${AT32_SDK_LIB}/cmsis/cm4/device_support + ${AT32_SDK_LIB}/drivers/inc + ) + + update_board(${BOARD_TARGET}) +endfunction() + +#------------------------------------ +# Functions +#------------------------------------ +function(family_configure_example TARGET RTOS) + family_configure_common(${TARGET} ${RTOS}) + family_add_tinyusb(${TARGET} OPT_MCU_${AT32_FAMILY_UPPER}) + + target_sources(${TARGET} PUBLIC + ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/family.c + ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/../board.c + ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/${AT32_FAMILY}_clock.c + ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/${AT32_FAMILY}_int.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 + ${STARTUP_FILE_${CMAKE_C_COMPILER_ID}} + ) + target_include_directories(${TARGET} PUBLIC + ${CMAKE_CURRENT_FUNCTION_LIST_DIR} + ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/../../ + ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/boards/${BOARD} + ) + + if (CMAKE_C_COMPILER_ID STREQUAL "GNU") + target_link_options(${TARGET} PUBLIC + "LINKER:--script=${LD_FILE_GNU}" + -nostartfiles + --specs=nosys.specs --specs=nano.specs + ) + elseif (CMAKE_C_COMPILER_ID STREQUAL "Clang") + target_link_options(${TARGET} PUBLIC + "LINKER:--script=${LD_FILE_Clang}" + ) + elseif (CMAKE_C_COMPILER_ID STREQUAL "IAR") + target_link_options(${TARGET} PUBLIC + "LINKER:--config=${LD_FILE_IAR}" + ) + endif () + + set_source_files_properties(${STARTUP_FILE_${CMAKE_C_COMPILER_ID}} PROPERTIES + SKIP_LINTING ON + COMPILE_OPTIONS -w) + + # Flashing + family_add_bin_hex(${TARGET}) + family_flash_jlink(${TARGET}) +endfunction() diff --git a/hw/bsp/at32f45x/family.mk b/hw/bsp/at32f45x/family.mk new file mode 100644 index 000000000..e42f27557 --- /dev/null +++ b/hw/bsp/at32f45x/family.mk @@ -0,0 +1,40 @@ +AT32_FAMILY = at32f45x +AT32_SDK_LIB = hw/mcu/artery/${AT32_FAMILY}/libraries + +include $(TOP)/$(BOARD_PATH)/board.mk + +CPU_CORE ?= cortex-m4 + +CFLAGS_GCC += \ + -flto + +CFLAGS += \ + -DCFG_TUSB_MCU=OPT_MCU_AT32F45X \ + +LDFLAGS_GCC += \ + -flto --specs=nosys.specs -nostdlib -nostartfiles + +SRC_C += \ + src/portable/synopsys/dwc2/dcd_dwc2.c \ + src/portable/synopsys/dwc2/hcd_dwc2.c \ + src/portable/synopsys/dwc2/dwc2_common.c \ + $(AT32_SDK_LIB)/drivers/src/${AT32_FAMILY}_gpio.c \ + $(AT32_SDK_LIB)/drivers/src/${AT32_FAMILY}_misc.c \ + $(AT32_SDK_LIB)/drivers/src/${AT32_FAMILY}_usart.c \ + $(AT32_SDK_LIB)/drivers/src/${AT32_FAMILY}_crm.c \ + $(AT32_SDK_LIB)/drivers/src/${AT32_FAMILY}_acc.c \ + $(AT32_SDK_LIB)/cmsis/cm4/device_support/system_${AT32_FAMILY}.c + +INC += \ + $(TOP)/$(BOARD_PATH) \ + $(TOP)/$(AT32_SDK_LIB)/drivers/inc \ + $(TOP)/$(AT32_SDK_LIB)/cmsis/cm4/core_support \ + $(TOP)/$(AT32_SDK_LIB)/cmsis/cm4/device_support + +SRC_S_GCC += ${AT32_SDK_LIB}/cmsis/cm4/device_support/startup/gcc/startup_${AT32_FAMILY}.s +SRC_S_IAR += ${AT32_SDK_LIB}/cmsis/cm4/device_support/startup/iar/startup_${AT32_FAMILY}.s + +LD_FILE_GCC ?= ${AT32_SDK_LIB}/cmsis/cm4/device_support/startup/gcc/linker/${MCU_LINKER_NAME}_FLASH.ld +LD_FILE_IAR ?= ${AT32_SDK_LIB}/cmsis/cm4/device_support/startup/iar/linker/${MCU_LINKER_NAME}.icf + +flash: flash-atlink diff --git a/hw/bsp/family_support.cmake b/hw/bsp/family_support.cmake index baa8422fe..699afda92 100644 --- a/hw/bsp/family_support.cmake +++ b/hw/bsp/family_support.cmake @@ -238,6 +238,7 @@ function(family_add_bloaty TARGET) COMMAND ${BLOATY_EXE} ${OPTION_LIST} $<TARGET_FILE:${TARGET}> VERBATIM) + set_property(TARGET ${TARGET}-bloaty PROPERTY FOLDER ${TARGET}) # post build # add_custom_command(TARGET ${TARGET} POST_BUILD # COMMAND ${BLOATY_EXE} --csv ${OPTION_LIST} $<TARGET_FILE:${TARGET}> > ${CMAKE_CURRENT_BINARY_DIR}/${TARGET}_bloaty.csv @@ -258,12 +259,103 @@ function(family_add_linkermap TARGET) VERBATIM ) + set_property(TARGET ${TARGET}-linkermap PROPERTY FOLDER ${TARGET}) + # post build add_custom_command(TARGET ${TARGET} POST_BUILD COMMAND python ${LINKERMAP_PY} ${OPTION_LIST} $<TARGET_FILE:${TARGET}>.map VERBATIM) endfunction() +# Add membrowse target (installed with pip install membrowse) +function(family_add_membrowse TARGET) + find_program(MEMBROWSE_EXE membrowse) + if (MEMBROWSE_EXE STREQUAL MEMBROWSE_EXE-NOTFOUND) + # force anyway, bash login shell will find it from pip install path + set(MEMBROWSE_EXE membrowse) + endif () + + set(OPTION "") + if (DEFINED MEMBROWSE_OPTION) + string(APPEND OPTION " ${MEMBROWSE_OPTION}") + endif () + + # For Ninja generator, extract all linker scripts from Ninja commands (with INCLUDE) and pass them to membrowse. + if (CMAKE_GENERATOR MATCHES "Ninja") + set(TARGET_ELF_PATH "$<TARGET_FILE_DIR:${TARGET}>/$<TARGET_FILE_NAME:${TARGET}>") + set(MEMBROWSE_LD_SCRIPTS_CMD + "ld_scripts=\"$(${CMAKE_MAKE_PROGRAM} -C ${CMAKE_BINARY_DIR} -t commands ${TARGET} | grep -oP '(?:-Wl,--script=|-T\\s*)\\K[A-Za-z0-9_./-]+\\.ld' | xargs)\"; \ +all_ld_scripts=\"\"; \ +pending_ld_scripts=\"$ld_scripts\"; \ +while [ -n \"$pending_ld_scripts\" ]; do \ + next_pending=\"\"; \ + for script in $pending_ld_scripts; do \ + case \" $all_ld_scripts \" in *\" $script \"*) continue ;; esac; \ + all_ld_scripts=\"$all_ld_scripts $script\"; \ + script_dir=$(dirname \"$script\"); \ + include_scripts=$(grep -hoP '^\\s*INCLUDE\\s+[<\"]?\\K[^\">[:space:]]+\\.ld' \"$script\" 2>/dev/null | xargs); \ + for include_script in $include_scripts; do \ + resolved_script=\"\"; \ + if [ -f \"$include_script\" ]; then \ + resolved_script=\"$include_script\"; \ + elif [ -f \"$script_dir/$include_script\" ]; then \ + resolved_script=\"$script_dir/$include_script\"; \ + fi; \ + if [ -n \"$resolved_script\" ]; then \ + case \" $all_ld_scripts $next_pending \" in *\" $resolved_script \"*) ;; *) next_pending=\"$next_pending $resolved_script\" ;; esac; \ + fi; \ + done; \ + done; \ + pending_ld_scripts=\"$(echo \"$next_pending\" | xargs)\"; \ +done; \ +ld_scripts=\"$(echo \"$all_ld_scripts\" | xargs)\"") + set(MEMBROWSE_LD_DEFS_CMD + "ld_symbols=\"$(${CMAKE_MAKE_PROGRAM} -C ${CMAKE_BINARY_DIR} -t commands ${TARGET} | grep -oP '(?<=--defsym[=,])[^[:space:]]+' | xargs)\"; \ +ld_defs=\"\"; \ +for symbol in $ld_symbols; do \ + ld_defs=\"$ld_defs --def $symbol\"; \ +done; \ +ld_defs=\"$(echo \"$ld_defs\" | xargs)\"") + set(MEMBROWSE_PREPARE_CMD + "if [ -f \"${TARGET_ELF_PATH}\" ]; then \ + ${MEMBROWSE_LD_SCRIPTS_CMD}; \ + ${MEMBROWSE_LD_DEFS_CMD}; \ + if [ \"$MEMBROWSE_UPLOAD\" = \"1\" ]; then \ + MEMBROWSE_CMD=\"${MEMBROWSE_EXE} report ${OPTION} \\\"${TARGET_ELF_PATH}\\\" \\\"$ld_scripts\\\" $ld_defs --upload --github --target-name ${BOARD}/${TARGET} --api-key $ENV{MEMBROWSE_API_KEY}\"; \ + else \ + MEMBROWSE_CMD=\"${MEMBROWSE_EXE} report ${OPTION} \\\"${TARGET_ELF_PATH}\\\" \\\"$ld_scripts\\\" $ld_defs\"; \ + fi; \ +else \ + if [ \"$MEMBROWSE_UPLOAD\" = \"1\" ]; then \ + MEMBROWSE_CMD=\"${MEMBROWSE_EXE} report ${OPTION} --identical --upload --github --target-name ${BOARD}/${TARGET} --api-key $ENV{MEMBROWSE_API_KEY}\"; \ + else \ + MEMBROWSE_CMD=\"${MEMBROWSE_EXE} report ${OPTION} --identical\"; \ + fi; \ +fi; \ +echo \"$MEMBROWSE_CMD\"") + + add_custom_target(${TARGET}-membrowse + DEPENDS ${TARGET} + COMMAND ${CMAKE_COMMAND} -E env MEMBROWSE_UPLOAD=0 bash -lc "${MEMBROWSE_PREPARE_CMD}; eval \"$MEMBROWSE_CMD\"" + VERBATIM + ) + set_property(TARGET ${TARGET}-membrowse PROPERTY FOLDER ${TARGET}) + + add_custom_target(${TARGET}-membrowse-upload + COMMAND ${CMAKE_COMMAND} -E env MEMBROWSE_UPLOAD=1 bash -lc "${MEMBROWSE_PREPARE_CMD}; eval \"$MEMBROWSE_CMD\"" + VERBATIM + ) + + if (NOT TARGET examples-membrowse-upload) + add_custom_target(examples-membrowse-upload) + endif () + add_dependencies(examples-membrowse-upload ${TARGET}-membrowse-upload) + + set_property(TARGET ${TARGET}-membrowse-upload PROPERTY FOLDER ${TARGET}) + endif () +endfunction() + + #------------------------------------------------------------- # Common Target Configure # Most families use these settings except rp2040 and espressif @@ -377,6 +469,7 @@ function(family_configure_common TARGET RTOS) # Analyze size with bloaty and linkermap family_add_bloaty(${TARGET}) family_add_linkermap(${TARGET}) + family_add_membrowse(${TARGET}) endif () # run size after build @@ -508,6 +601,8 @@ exit" COMMAND ${JLINKEXE} -device ${JLINK_DEVICE} ${OPTION_LIST} -if ${JLINK_IF} -JTAGConf -1,-1 -speed auto -CommandFile $<TARGET_FILE_DIR:${BINARY_TARGET}>/${BINARY_TARGET}.jlink VERBATIM ) + + set_property(TARGET ${NAME_TARGET}-jlink PROPERTY FOLDER ${TARGET}) endfunction() @@ -521,6 +616,8 @@ function(family_flash_stlink TARGET) DEPENDS ${TARGET} COMMAND ${STM32_PROGRAMMER_CLI} --connect port=swd --write $<TARGET_FILE:${TARGET}> --go ) + + set_property(TARGET ${TARGET}-stlink PROPERTY FOLDER ${TARGET}) endfunction() @@ -534,6 +631,8 @@ function(family_flash_stflash TARGET) DEPENDS ${TARGET} COMMAND ${ST_FLASH} write $<TARGET_FILE_DIR:${TARGET}>/${TARGET}.bin 0x8000000 ) + + set_property(TARGET ${TARGET}-stflash PROPERTY FOLDER ${TARGET}) endfunction() @@ -560,6 +659,8 @@ function(family_flash_openocd TARGET) COMMAND ${OPENOCD} -c "tcl_port disabled; gdb_port disabled" ${OPTION_LIST} -c "init; halt; program $<TARGET_FILE:${TARGET}>" -c reset ${OPTION_LIST2} -c exit VERBATIM ) + + set_property(TARGET ${TARGET}-openocd PROPERTY FOLDER ${TARGET}) endfunction() @@ -621,6 +722,8 @@ function(family_flash_wlink_rs TARGET) DEPENDS ${TARGET} COMMAND ${WLINK_RS} flash $<TARGET_FILE:${TARGET}> ) + + set_property(TARGET ${TARGET}-wlink-rs PROPERTY FOLDER ${TARGET}) endfunction() @@ -634,6 +737,8 @@ function(family_flash_pyocd TARGET) DEPENDS ${TARGET} COMMAND ${PYOCD} flash -t ${PYOCD_TARGET} $<TARGET_FILE:${TARGET}> ) + + set_property(TARGET ${TARGET}-pyocd PROPERTY FOLDER ${TARGET}) endfunction() @@ -643,6 +748,7 @@ function(family_flash_uf2 TARGET FAMILY_ID) DEPENDS ${TARGET} COMMAND python ${UF2CONV_PY} -f ${FAMILY_ID} --deploy $<TARGET_FILE_DIR:${TARGET}>/${TARGET}.uf2 ) + set_property(TARGET ${TARGET}-uf2 PROPERTY FOLDER ${TARGET}) endfunction() @@ -657,6 +763,8 @@ function(family_flash_teensy TARGET) COMMAND ${CMAKE_OBJCOPY} -Oihex $<TARGET_FILE:${TARGET}> $<TARGET_FILE_DIR:${TARGET}>/${TARGET}.hex COMMAND ${TEENSY_CLI} --mcu=${TEENSY_MCU} -w -s $<TARGET_FILE_DIR:${TARGET}>/${TARGET}.hex ) + + set_property(TARGET ${TARGET}-teensy PROPERTY FOLDER ${TARGET}) endfunction() @@ -675,6 +783,8 @@ function(family_flash_nxplink TARGET) DEPENDS ${TARGET} COMMAND ${LINKSERVER_PATH} flash ${NXPLINK_DEVICE} load $<TARGET_FILE:${TARGET}> ) + + set_property(TARGET ${TARGET}-nxplink PROPERTY FOLDER ${TARGET}) endfunction() @@ -688,6 +798,8 @@ function(family_flash_dfu_util TARGET OPTION) COMMAND ${DFU_UTIL} -R -d ${DFU_UTIL_VID_PID} -a 0 -D $<TARGET_FILE_DIR:${TARGET}>/${TARGET}.bin VERBATIM ) + + set_property(TARGET ${TARGET}-dfu-util PROPERTY FOLDER ${TARGET}) endfunction() function(family_flash_msp430flasher TARGET) @@ -703,6 +815,8 @@ function(family_flash_msp430flasher TARGET) COMMAND ${CMAKE_COMMAND} -E env LD_LIBRARY_PATH=${MSP430FLASHER_PARENT_DIR} ${MSP430FLASHER} -w $<TARGET_FILE_DIR:${TARGET}>/${TARGET}.hex -z [VCC] ) + + set_property(TARGET ${TARGET}-msp430flasher PROPERTY FOLDER ${TARGET}) endfunction() function(family_flash_uniflash TARGET) @@ -717,6 +831,8 @@ function(family_flash_uniflash TARGET) COMMAND ${DSLITE} ${UNIFLASH_OPTION} -f $<TARGET_FILE_DIR:${TARGET}>/${TARGET}.hex VERBATIM ) + + set_property(TARGET ${TARGET}-uniflash PROPERTY FOLDER ${TARGET}) endfunction() #---------------------------------- diff --git a/hw/bsp/rp2040/family.cmake b/hw/bsp/rp2040/family.cmake index 1602e35eb..82d0034a1 100644 --- a/hw/bsp/rp2040/family.cmake +++ b/hw/bsp/rp2040/family.cmake @@ -157,10 +157,12 @@ target_link_libraries(tinyusb_bsp INTERFACE # tinyusb_additions will hold our extra settings for examples add_library(tinyusb_additions INTERFACE) +if (PICO_PLATFORM STREQUAL rp2040) target_compile_definitions(tinyusb_additions INTERFACE PICO_RP2040_USB_DEVICE_ENUMERATION_FIX=1 PICO_RP2040_USB_DEVICE_UFRAME_FIX=1 -) + ) +endif () if(LOGGER STREQUAL "RTT" OR LOGGER STREQUAL "rtt") target_compile_definitions(tinyusb_additions INTERFACE @@ -248,8 +250,10 @@ function(family_configure_target TARGET RTOS) family_flash_openocd(${TARGET}) family_flash_jlink(${TARGET}) - # Generate linkermap target and post build. LINKERMAP_OPTION can be set with -D to change default options + # Generate linkermap target and post build. LINKERMAP_OPTION can be set with -D to change default options + family_add_bloaty(${TARGET}) family_add_linkermap(${TARGET}) + family_add_membrowse(${TARGET}) endfunction() diff --git a/hw/bsp/stm32f2/family.c b/hw/bsp/stm32f2/family.c index 9c78cf7dd..d6a0cb827 100644 --- a/hw/bsp/stm32f2/family.c +++ b/hw/bsp/stm32f2/family.c @@ -31,7 +31,6 @@ #include "stm32f2xx_hal.h" #include "bsp/board_api.h" #include "board.h" - //--------------------------------------------------------------------+ // Forward USB interrupt events to TinyUSB IRQ Handler //--------------------------------------------------------------------+ @@ -105,9 +104,12 @@ void board_init(void) { /* Enable USB FS Clocks */ __HAL_RCC_USB_OTG_FS_CLK_ENABLE(); +#if CFG_TUD_ENABLED // Enable VBUS sense (B device) via pin PA9 - USB_OTG_FS->GCCFG &= ~USB_OTG_GCCFG_NOVBUSSENS; - USB_OTG_FS->GCCFG |= USB_OTG_GCCFG_VBUSBSEN; + tud_configure_dwc2_t cfg = CFG_TUD_CONFIGURE_DWC2_DEFAULT; + cfg.vbus_sensing = true; + tud_configure(0, TUD_CFGID_DWC2, &cfg); +#endif } //--------------------------------------------------------------------+ diff --git a/hw/bsp/stm32f4/boards/feather_stm32f405/board.h b/hw/bsp/stm32f4/boards/feather_stm32f405/board.h index 11e976a42..2db42b98a 100644 --- a/hw/bsp/stm32f4/boards/feather_stm32f405/board.h +++ b/hw/bsp/stm32f4/boards/feather_stm32f405/board.h @@ -43,6 +43,8 @@ #define PINID_UART_TX 2 #define PINID_UART_RX 3 +#define VBUS_SENSE_EN 1 + static board_pindef_t board_pindef[] = { { // LED .port = GPIOC, @@ -106,14 +108,6 @@ static inline void board_clock_init(void) __HAL_RCC_USART3_CLK_ENABLE(); } -static inline void board_vbus_sense_init(uint8_t rhport) { - if (rhport == 0) { - // Enable VBUS sense (B device) via pin PA9 - USB_OTG_FS->GCCFG &= ~USB_OTG_GCCFG_NOVBUSSENS; - USB_OTG_FS->GCCFG |= USB_OTG_GCCFG_VBUSBSEN; - } -} - static inline void board_vbus_set(uint8_t rhport, bool state) { (void) rhport; (void) state; } diff --git a/hw/bsp/stm32f4/boards/pyboardv11/board.h b/hw/bsp/stm32f4/boards/pyboardv11/board.h index 9583a924b..319d2336a 100644 --- a/hw/bsp/stm32f4/boards/pyboardv11/board.h +++ b/hw/bsp/stm32f4/boards/pyboardv11/board.h @@ -43,6 +43,8 @@ #define PINID_UART_TX 2 #define PINID_UART_RX 3 +#define VBUS_SENSE_EN 1 + static board_pindef_t board_pindef[] = { { // LED .port = GPIOB, @@ -106,14 +108,6 @@ static inline void board_clock_init(void) __HAL_RCC_USART2_CLK_ENABLE(); } -static inline void board_vbus_sense_init(uint8_t rhport) { - if (rhport == 0) { - // Enable VBUS sense (B device) via pin PA9 - USB_OTG_FS->GCCFG &= ~USB_OTG_GCCFG_NOVBUSSENS; - USB_OTG_FS->GCCFG |= USB_OTG_GCCFG_VBUSBSEN; - } -} - static inline void board_vbus_set(uint8_t rhport, bool state) { (void) rhport; (void) state; } diff --git a/hw/bsp/stm32f4/boards/stm32f401blackpill/board.h b/hw/bsp/stm32f4/boards/stm32f401blackpill/board.h index 8a3fe8409..b69ebbeaf 100644 --- a/hw/bsp/stm32f4/boards/stm32f401blackpill/board.h +++ b/hw/bsp/stm32f4/boards/stm32f401blackpill/board.h @@ -44,6 +44,8 @@ #define PINID_UART_TX 2 #define PINID_UART_RX 3 +#define VBUS_SENSE_EN 0 + static board_pindef_t board_pindef[] = { { // LED .port = GPIOC, @@ -107,15 +109,6 @@ static inline void board_clock_init(void) __HAL_RCC_USART2_CLK_ENABLE(); } -static inline void board_vbus_sense_init(uint8_t rhport) { - // Blackpill doesn't use VBUS sense (B device) explicitly disable it - if (rhport == 0) { - USB_OTG_FS->GCCFG |= USB_OTG_GCCFG_NOVBUSSENS; - USB_OTG_FS->GCCFG &= ~USB_OTG_GCCFG_VBUSBSEN; - USB_OTG_FS->GCCFG &= ~USB_OTG_GCCFG_VBUSASEN; - } -} - static inline void board_vbus_set(uint8_t rhport, bool state) { (void) rhport; (void) state; } diff --git a/hw/bsp/stm32f4/boards/stm32f407blackvet/board.h b/hw/bsp/stm32f4/boards/stm32f407blackvet/board.h index effbf2be8..ebefeb988 100644 --- a/hw/bsp/stm32f4/boards/stm32f407blackvet/board.h +++ b/hw/bsp/stm32f4/boards/stm32f407blackvet/board.h @@ -44,6 +44,8 @@ #define PINID_UART_TX 2 #define PINID_UART_RX 3 +#define VBUS_SENSE_EN 0 + static board_pindef_t board_pindef[] = { { // LED .port = GPIOA, @@ -106,15 +108,6 @@ static inline void board_clock_init(void) __HAL_RCC_USART2_CLK_ENABLE(); } -static inline void board_vbus_sense_init(uint8_t rhport) { - if (rhport == 0) { - // Black F407VET6 doesn't use VBUS sense (B device) explicitly disable it - USB_OTG_FS->GCCFG |= USB_OTG_GCCFG_NOVBUSSENS; - USB_OTG_FS->GCCFG &= ~USB_OTG_GCCFG_VBUSBSEN; - USB_OTG_FS->GCCFG &= ~USB_OTG_GCCFG_VBUSASEN; - } -} - static inline void board_vbus_set(uint8_t rhport, bool state) { (void) rhport; (void) state; } diff --git a/hw/bsp/stm32f4/boards/stm32f407disco/board.h b/hw/bsp/stm32f4/boards/stm32f407disco/board.h index 19a029768..bcfa6059a 100644 --- a/hw/bsp/stm32f4/boards/stm32f407disco/board.h +++ b/hw/bsp/stm32f4/boards/stm32f407disco/board.h @@ -46,6 +46,8 @@ #define PINID_UART_RX 3 #define PINID_VBUS0_EN 4 +#define VBUS_SENSE_EN 1 + static board_pindef_t board_pindef[] = { { // LED .port = GPIOD, @@ -114,14 +116,6 @@ static inline void board_clock_init(void) __HAL_RCC_USART2_CLK_ENABLE(); } -static inline void board_vbus_sense_init(uint8_t rhport) { - if (rhport == 0) { - // Enable VBUS sense (B device) via pin PA9 - USB_OTG_FS->GCCFG &= ~USB_OTG_GCCFG_NOVBUSSENS; - USB_OTG_FS->GCCFG |= USB_OTG_GCCFG_VBUSBSEN; - } -} - static inline void board_vbus_set(uint8_t rhport, bool state) { if (rhport == 0) { board_pindef_t* pindef = &board_pindef[PINID_VBUS0_EN]; diff --git a/hw/bsp/stm32f4/boards/stm32f411blackpill/board.h b/hw/bsp/stm32f4/boards/stm32f411blackpill/board.h index 61e5de70d..0faf6fe11 100644 --- a/hw/bsp/stm32f4/boards/stm32f411blackpill/board.h +++ b/hw/bsp/stm32f4/boards/stm32f411blackpill/board.h @@ -43,6 +43,8 @@ #define PINID_UART_TX 2 #define PINID_UART_RX 3 +#define VBUS_SENSE_EN 0 + static board_pindef_t board_pindef[] = { { // LED .port = GPIOC, @@ -106,15 +108,6 @@ static inline void board_clock_init(void) __HAL_RCC_USART2_CLK_ENABLE(); } -static inline void board_vbus_sense_init(uint8_t rhport) { - // Blackpill doesn't use VBUS sense (B device) explicitly disable it - if (rhport == 0) { - USB_OTG_FS->GCCFG |= USB_OTG_GCCFG_NOVBUSSENS; - USB_OTG_FS->GCCFG &= ~USB_OTG_GCCFG_VBUSBSEN; - USB_OTG_FS->GCCFG &= ~USB_OTG_GCCFG_VBUSASEN; - } -} - static inline void board_vbus_set(uint8_t rhport, bool state) { (void) rhport; (void) state; } diff --git a/hw/bsp/stm32f4/boards/stm32f411disco/board.h b/hw/bsp/stm32f4/boards/stm32f411disco/board.h index d7b02e79d..1a289dfb5 100644 --- a/hw/bsp/stm32f4/boards/stm32f411disco/board.h +++ b/hw/bsp/stm32f4/boards/stm32f411disco/board.h @@ -44,6 +44,8 @@ #define PINID_UART_RX 3 #define PINID_VBUS0_EN 4 +#define VBUS_SENSE_EN 1 + static board_pindef_t board_pindef[] = { { // LED .port = GPIOD, @@ -111,14 +113,6 @@ static inline void board_clock_init(void) { __HAL_RCC_USART2_CLK_ENABLE(); } -static inline void board_vbus_sense_init(uint8_t rhport) { - // Enable VBUS sense (B device) via pin PA9 - if (rhport == 0) { - USB_OTG_FS->GCCFG &= ~USB_OTG_GCCFG_NOVBUSSENS; - USB_OTG_FS->GCCFG |= USB_OTG_GCCFG_VBUSBSEN; - } -} - static inline void board_vbus_set(uint8_t rhport, bool state) { if (rhport == 0) { board_pindef_t* pindef = &board_pindef[PINID_VBUS0_EN]; diff --git a/hw/bsp/stm32f4/boards/stm32f412disco/board.h b/hw/bsp/stm32f4/boards/stm32f412disco/board.h index d5146ae3c..0689dfe87 100644 --- a/hw/bsp/stm32f4/boards/stm32f412disco/board.h +++ b/hw/bsp/stm32f4/boards/stm32f412disco/board.h @@ -45,6 +45,8 @@ #define PINID_UART_RX 3 #define PINID_VBUS0_EN 4 +#define VBUS_SENSE_EN 1 + static board_pindef_t board_pindef[] = { { // LED .port = GPIOE, @@ -127,13 +129,6 @@ static inline void board_clock_init(void) { __HAL_RCC_USART2_CLK_ENABLE(); } -static inline void board_vbus_sense_init(uint8_t rhport) { - if (rhport == 0) { - // Enable VBUS sense (B device) via pin PA9 - USB_OTG_FS->GCCFG |= USB_OTG_GCCFG_VBDEN; - } -} - static inline void board_vbus_set(uint8_t rhport, bool state) { if (rhport == 0) { board_pindef_t* pindef = &board_pindef[PINID_VBUS0_EN]; diff --git a/hw/bsp/stm32f4/boards/stm32f412nucleo/board.h b/hw/bsp/stm32f4/boards/stm32f412nucleo/board.h index f7026ce61..be58f8ae7 100644 --- a/hw/bsp/stm32f4/boards/stm32f412nucleo/board.h +++ b/hw/bsp/stm32f4/boards/stm32f412nucleo/board.h @@ -45,6 +45,8 @@ #define PINID_UART_RX 3 #define PINID_VBUS0_EN 4 +#define VBUS_SENSE_EN 1 + static board_pindef_t board_pindef[] = { { // LED .port = GPIOB, @@ -128,13 +130,6 @@ static inline void board_clock_init(void) __HAL_RCC_USART3_CLK_ENABLE(); } -static inline void board_vbus_sense_init(uint8_t rhport) { - if (rhport == 0) { - // Enable VBUS sense (B device) via pin PA9 - USB_OTG_FS->GCCFG |= USB_OTG_GCCFG_VBDEN; - } -} - static inline void board_vbus_set(uint8_t rhport, bool state) { if (rhport == 0) { board_pindef_t* pindef = &board_pindef[PINID_VBUS0_EN]; diff --git a/hw/bsp/stm32f4/boards/stm32f439nucleo/board.h b/hw/bsp/stm32f4/boards/stm32f439nucleo/board.h index 9a348f33f..b1633b395 100644 --- a/hw/bsp/stm32f4/boards/stm32f439nucleo/board.h +++ b/hw/bsp/stm32f4/boards/stm32f439nucleo/board.h @@ -46,6 +46,8 @@ #define PINID_UART_RX 3 #define PINID_VBUS0_EN 4 +#define VBUS_SENSE_EN 1 + static board_pindef_t board_pindef[] = { { // LED .port = GPIOB, @@ -117,14 +119,6 @@ static inline void board_clock_init(void) __HAL_RCC_USART3_CLK_ENABLE(); } -static inline void board_vbus_sense_init(uint8_t rhport) { - if (rhport == 0) { - // Enable VBUS sense (B device) via pin PA9 - USB_OTG_FS->GCCFG |= USB_OTG_GCCFG_NOVBUSSENS; - USB_OTG_FS->GCCFG |= USB_OTG_GCCFG_VBUSBSEN; - } -} - static inline void board_vbus_set(uint8_t rhport, bool state) { if (rhport == 0) { board_pindef_t* pindef = &board_pindef[PINID_VBUS0_EN]; diff --git a/hw/bsp/stm32f4/family.c b/hw/bsp/stm32f4/family.c index 025f6a08c..f0e9620f2 100644 --- a/hw/bsp/stm32f4/family.c +++ b/hw/bsp/stm32f4/family.c @@ -180,11 +180,14 @@ void board_init(void) { #endif #if CFG_TUD_ENABLED - board_vbus_sense_init(BOARD_TUD_RHPORT); + tud_configure_dwc2_t cfg = CFG_TUD_CONFIGURE_DWC2_DEFAULT; + cfg.vbus_sensing = VBUS_SENSE_EN; + tud_configure(BOARD_TUD_RHPORT, TUD_CFGID_DWC2, &cfg); + board_vbus_set(BOARD_TUD_RHPORT, false); #endif #if CFG_TUH_ENABLED - board_vbus_set(BOARD_TUD_RHPORT, true); + board_vbus_set(BOARD_TUH_RHPORT, true); #endif } diff --git a/hw/bsp/stm32f7/boards/stm32f723disco/board.h b/hw/bsp/stm32f7/boards/stm32f723disco/board.h index 35102c1f2..ca9641c68 100644 --- a/hw/bsp/stm32f7/boards/stm32f723disco/board.h +++ b/hw/bsp/stm32f7/boards/stm32f723disco/board.h @@ -41,7 +41,7 @@ // VBUS Sense detection #define OTG_FS_VBUS_SENSE 1 -#define OTG_HS_VBUS_SENSE 0 +#define OTG_HS_VBUS_SENSE 1 #define PINID_LED 0 #define PINID_BUTTON 1 diff --git a/hw/bsp/stm32f7/boards/stm32f746disco/board.h b/hw/bsp/stm32f7/boards/stm32f746disco/board.h index 2964ebada..f57ffb317 100644 --- a/hw/bsp/stm32f7/boards/stm32f746disco/board.h +++ b/hw/bsp/stm32f7/boards/stm32f746disco/board.h @@ -40,8 +40,8 @@ #define UART_CLK_EN __HAL_RCC_USART1_CLK_ENABLE // VBUS Sense detection -#define OTG_FS_VBUS_SENSE 0 -#define OTG_HS_VBUS_SENSE 0 +#define OTG_FS_VBUS_SENSE 1 +#define OTG_HS_VBUS_SENSE 1 #define PINID_LED 0 #define PINID_BUTTON 1 diff --git a/hw/bsp/stm32f7/family.c b/hw/bsp/stm32f7/family.c index ac22c606f..d8f0da201 100644 --- a/hw/bsp/stm32f7/family.c +++ b/hw/bsp/stm32f7/family.c @@ -154,18 +154,14 @@ void board_init(void) { GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_NOPULL; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); - - // Enable VBUS sense (B device) via pin PA9 - USB_OTG_FS->GCCFG |= USB_OTG_GCCFG_VBDEN; -#else - // Disable VBUS sense (B device) via pin PA9 - 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 +#if CFG_TUD_ENABLED && BOARD_TUD_RHPORT == 0 + tud_configure_dwc2_t cfg = CFG_TUD_CONFIGURE_DWC2_DEFAULT; + cfg.vbus_sensing = OTG_FS_VBUS_SENSE; + tud_configure(0, TUD_CFGID_DWC2, &cfg); +#endif + //------------- rhport1: OTG_HS -------------// #ifdef USB_HS_PHYC // MCU with built-in HS PHY such as F723, F733, F730 @@ -178,9 +174,6 @@ void board_init(void) { GPIO_InitStruct.Alternate = GPIO_AF12_OTG_HS_FS; HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); - // Enable HS VBUS sense (B device) via pin PB13 - USB_OTG_HS->GCCFG |= USB_OTG_GCCFG_VBDEN; - /* Configure OTG-HS ID pin */ GPIO_InitStruct.Pin = GPIO_PIN_13; GPIO_InitStruct.Mode = GPIO_MODE_AF_OD; @@ -243,17 +236,16 @@ void board_init(void) { __HAL_RCC_USB_OTG_HS_ULPI_CLK_ENABLE(); __HAL_RCC_USB_OTG_HS_CLK_ENABLE(); -#if OTG_HS_VBUS_SENSE - #error OTG HS VBUS Sense enabled is not implemented -#else - // No VBUS sense - USB_OTG_HS->GCCFG &= ~USB_OTG_GCCFG_VBDEN; - - // B-peripheral session valid override enable - USB_OTG_HS->GOTGCTL |= USB_OTG_GOTGCTL_BVALOEN; - USB_OTG_HS->GOTGCTL |= USB_OTG_GOTGCTL_BVALOVAL; +#if CFG_TUD_ENABLED && BOARD_TUD_RHPORT == 1 + tud_configure_dwc2_t cfg = CFG_TUD_CONFIGURE_DWC2_DEFAULT; + cfg.vbus_sensing = OTG_HS_VBUS_SENSE; + tud_configure(1, TUD_CFGID_DWC2, &cfg); #endif + // Turn off device vbus +#if CFG_TUD_ENABLED + board_vbus_set(BOARD_TUD_RHPORT, false); +#endif // Turn on host vbus #if CFG_TUH_ENABLED board_vbus_set(BOARD_TUH_RHPORT, true); diff --git a/hw/bsp/stm32h7/boards/stm32h743eval/board.h b/hw/bsp/stm32h7/boards/stm32h743eval/board.h index 96bfc24e1..44ca58dc5 100644 --- a/hw/bsp/stm32h7/boards/stm32h743eval/board.h +++ b/hw/bsp/stm32h7/boards/stm32h743eval/board.h @@ -44,7 +44,7 @@ // VBUS Sense detection #define OTG_FS_VBUS_SENSE 1 -#define OTG_HS_VBUS_SENSE 0 +#define OTG_HS_VBUS_SENSE 1 // USB HS External PHY Pin: CLK, STP, DIR, NXT, D0-D7 #define ULPI_PINS \ diff --git a/hw/bsp/stm32h7/boards/stm32h747disco/board.cmake b/hw/bsp/stm32h7/boards/stm32h747disco/board.cmake new file mode 100644 index 000000000..8bce542a5 --- /dev/null +++ b/hw/bsp/stm32h7/boards/stm32h747disco/board.cmake @@ -0,0 +1,23 @@ +set(MCU_VARIANT stm32h747xx) +set(JLINK_DEVICE stm32h747xi_m7) + +set(LD_FILE_GNU ${CMAKE_CURRENT_LIST_DIR}/../../linker/${MCU_VARIANT}_flash_CM7.ld) +set(LD_FILE_IAR ${ST_CMSIS}/Source/Templates/iar/linker/${MCU_VARIANT}_flash_CM7.icf) + +set(RHPORT_SPEED OPT_MODE_FULL_SPEED OPT_MODE_HIGH_SPEED) + +# 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 1) +endif() + +function(update_board TARGET) + target_compile_definitions(${TARGET} PUBLIC + STM32H747xx + HSE_VALUE=25000000 + CORE_CM7 + ) +endfunction() diff --git a/hw/bsp/stm32h7/boards/stm32h747disco/board.h b/hw/bsp/stm32h7/boards/stm32h747disco/board.h new file mode 100644 index 000000000..458aa48b6 --- /dev/null +++ b/hw/bsp/stm32h7/boards/stm32h747disco/board.h @@ -0,0 +1,169 @@ +/* + * 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 H745 Discovery + url: https://www.st.com/en/evaluation-tools/stm32h745i-disco.html +*/ + +#ifndef BOARD_H_ +#define BOARD_H_ + +#ifdef __cplusplus + extern "C" { +#endif + +// UART +#define UART_DEV USART3 +#define UART_CLK_EN __HAL_RCC_USART3_CLK_ENABLE + +// VBUS Sense detection +#define OTG_FS_VBUS_SENSE 1 +#define OTG_HS_VBUS_SENSE 1 + +// USB HS External PHY Pin: CLK, STP, DIR, NXT, D0-D7 +#define ULPI_PINS \ + {GPIOA, GPIO_PIN_3 }, {GPIOA, GPIO_PIN_5 }, {GPIOB, GPIO_PIN_0 }, {GPIOB, GPIO_PIN_1 }, \ + {GPIOB, GPIO_PIN_5 }, {GPIOB, GPIO_PIN_10}, {GPIOB, GPIO_PIN_11}, {GPIOB, GPIO_PIN_12}, \ + {GPIOB, GPIO_PIN_13}, {GPIOC, GPIO_PIN_0 }, {GPIOH, GPIO_PIN_4 }, {GPIOI, GPIO_PIN_11} + +#define PINID_LED 0 +#define PINID_BUTTON 1 +#define PINID_UART_TX 2 +#define PINID_UART_RX 3 + +static board_pindef_t board_pindef[] = { + { // LED + .port = GPIOI, + .pin_init = { .Pin = GPIO_PIN_12, .Mode = GPIO_MODE_OUTPUT_PP, .Pull = GPIO_PULLDOWN, .Speed = GPIO_SPEED_HIGH, .Alternate = 0 }, + .active_state = 0 + }, + { // Button + .port = GPIOC, + .pin_init = { .Pin = GPIO_PIN_13, .Mode = GPIO_MODE_INPUT, .Pull = GPIO_PULLUP, .Speed = GPIO_SPEED_HIGH, .Alternate = 0 }, + .active_state = 1 + }, + { // UART TX + .port = GPIOA, + .pin_init = { .Pin = GPIO_PIN_9, .Mode = GPIO_MODE_AF_PP, .Pull = GPIO_PULLUP, .Speed = GPIO_SPEED_HIGH, .Alternate = GPIO_AF7_USART3 }, + .active_state = 0 + }, + { // UART RX + .port = GPIOA, + .pin_init = { .Pin = GPIO_PIN_10, .Mode = GPIO_MODE_AF_PP, .Pull = GPIO_PULLUP, .Speed = GPIO_SPEED_HIGH, .Alternate = GPIO_AF7_USART3 }, + .active_state = 0 + } +}; + +//--------------------------------------------------------------------+ +// RCC Clock +//--------------------------------------------------------------------+ +static inline void SystemClock_Config(void) +{ + RCC_ClkInitTypeDef RCC_ClkInitStruct = { 0 }; + RCC_OscInitTypeDef RCC_OscInitStruct = { 0 }; + RCC_PeriphCLKInitTypeDef PeriphClkInitStruct = { 0 }; + + /*!< Supply configuration update enable */ + /* For STM32H750XB, use "HAL_PWREx_ConfigSupply(PWR_LDO_SUPPLY);" */ + HAL_PWREx_ConfigSupply(PWR_DIRECT_SMPS_SUPPLY); + + /* The voltage scaling allows optimizing the power consumption when the + device is clocked below the maximum system frequency, to update the + voltage scaling value regarding system frequency refer to product + datasheet. */ + __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1); + + while ((PWR->D3CR & (PWR_D3CR_VOSRDY)) != PWR_D3CR_VOSRDY) {} + + /* Enable HSE Oscillator and activate PLL with HSE as source */ + RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE; + RCC_OscInitStruct.HSEState = RCC_HSE_BYPASS; + RCC_OscInitStruct.HSIState = RCC_HSI_OFF; + RCC_OscInitStruct.CSIState = RCC_CSI_OFF; + RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; + RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; + + /* PLL1 for System Clock */ + RCC_OscInitStruct.PLL.PLLM = 5; + RCC_OscInitStruct.PLL.PLLN = 160; + RCC_OscInitStruct.PLL.PLLFRACN = 0; + RCC_OscInitStruct.PLL.PLLP = 2; + RCC_OscInitStruct.PLL.PLLR = 2; + RCC_OscInitStruct.PLL.PLLQ = 4; + + RCC_OscInitStruct.PLL.PLLVCOSEL = RCC_PLL1VCOMEDIUM; + RCC_OscInitStruct.PLL.PLLRGE = RCC_PLL1VCIRANGE_2; + HAL_RCC_OscConfig(&RCC_OscInitStruct); + + /* PLL3 for USB Clock */ + PeriphClkInitStruct.PLL3.PLL3M = 25; + PeriphClkInitStruct.PLL3.PLL3N = 336; + PeriphClkInitStruct.PLL3.PLL3FRACN = 0; + PeriphClkInitStruct.PLL3.PLL3P = 2; + PeriphClkInitStruct.PLL3.PLL3R = 2; + PeriphClkInitStruct.PLL3.PLL3Q = 7; + + PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_USB; + PeriphClkInitStruct.UsbClockSelection = RCC_USBCLKSOURCE_PLL3; + HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct); + + /* Select PLL as system clock source and configure bus clocks dividers */ + RCC_ClkInitStruct.ClockType = (RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_D1PCLK1 | RCC_CLOCKTYPE_PCLK1 | \ + RCC_CLOCKTYPE_PCLK2 | RCC_CLOCKTYPE_D3PCLK1); + + RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; + RCC_ClkInitStruct.SYSCLKDivider = RCC_SYSCLK_DIV1; + RCC_ClkInitStruct.AHBCLKDivider = RCC_HCLK_DIV2; + RCC_ClkInitStruct.APB1CLKDivider = RCC_APB1_DIV2; + RCC_ClkInitStruct.APB2CLKDivider = RCC_APB2_DIV2; + RCC_ClkInitStruct.APB3CLKDivider = RCC_APB3_DIV1; + HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4); + + /*activate CSI clock mondatory for I/O Compensation Cell*/ + __HAL_RCC_CSI_ENABLE() ; + + /* Enable SYSCFG clock mondatory for I/O Compensation Cell */ + __HAL_RCC_SYSCFG_CLK_ENABLE() ; + + /* Enables the I/O Compensation Cell */ + HAL_EnableCompensationCell(); +} + +static inline void board_init2(void) { + // For this board does nothing +} + +void board_vbus_set(uint8_t rhport, bool state) { + (void) rhport; + (void) state; +} + +#ifdef __cplusplus + } +#endif + +#endif diff --git a/hw/bsp/stm32h7/boards/stm32h747disco/board.mk b/hw/bsp/stm32h7/boards/stm32h747disco/board.mk new file mode 100644 index 000000000..4b17246e2 --- /dev/null +++ b/hw/bsp/stm32h7/boards/stm32h747disco/board.mk @@ -0,0 +1,15 @@ +# STM32H747I-DISCO uses OTG_FS +# FIXME: Reset enumerates, un/replug USB plug does not enumerate +MCU_VARIANT = stm32h747xx +CFLAGS += -DSTM32H747xx -DCORE_CM7 -DHSE_VALUE=25000000 + +# Default is FulSpeed port +PORT ?= 0 + +LD_FILE_GCC = $(FAMILY_PATH)/linker/${MCU_VARIANT}_flash_CM7.ld +LD_FILE_IAR = $(ST_CMSIS)/Source/Templates/iar/linker/stm32h747xx_flash_CM7.icf + +# For flash-jlink target +JLINK_DEVICE = stm32h747xi_m7 +# flash target using on-board stlink +flash: flash-stlink diff --git a/hw/bsp/stm32h7/family.c b/hw/bsp/stm32h7/family.c index 054d7855f..a320a7e72 100644 --- a/hw/bsp/stm32h7/family.c +++ b/hw/bsp/stm32h7/family.c @@ -180,18 +180,14 @@ void board_init(void) { GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_NOPULL; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); - - // Enable VBUS sense (B device) via pin PA9 - USB_OTG_FS->GCCFG |= USB_OTG_GCCFG_VBDEN; -#else - // Disable VBUS sense (B device) via pin PA9 - 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 +#if CFG_TUD_ENABLED && BOARD_TUD_RHPORT == 0 + tud_configure_dwc2_t cfg = CFG_TUD_CONFIGURE_DWC2_DEFAULT; + cfg.vbus_sensing = OTG_FS_VBUS_SENSE; + tud_configure(0, TUD_CFGID_DWC2, &cfg); +#endif + //------------- USB HS -------------// #if (CFG_TUD_ENABLED && BOARD_TUD_RHPORT == 1) || (CFG_TUH_ENABLED && BOARD_TUH_RHPORT == 1) // Despite being call USB2_OTG @@ -216,28 +212,24 @@ void board_init(void) { __HAL_RCC_USB1_OTG_HS_ULPI_CLK_ENABLE(); __HAL_RCC_USB1_OTG_HS_CLK_ENABLE(); -#if OTG_HS_VBUS_SENSE - #error OTG HS VBUS Sense enabled is not implemented -#else - // No VBUS sense - USB_OTG_HS->GCCFG &= ~USB_OTG_GCCFG_VBDEN; - - // B-peripheral session valid override enable - USB_OTG_HS->GOTGCTL |= USB_OTG_GOTGCTL_BVALOEN; - USB_OTG_HS->GOTGCTL |= USB_OTG_GOTGCTL_BVALOVAL; -#endif - - // Force device mode - USB_OTG_HS->GUSBCFG &= ~USB_OTG_GUSBCFG_FHMOD; - USB_OTG_HS->GUSBCFG |= USB_OTG_GUSBCFG_FDMOD; + #if CFG_TUD_ENABLED && BOARD_TUD_RHPORT == 1 + tud_configure_dwc2_t cfg = CFG_TUD_CONFIGURE_DWC2_DEFAULT; + cfg.vbus_sensing = OTG_HS_VBUS_SENSE; + tud_configure(1, TUD_CFGID_DWC2, &cfg); + #endif #endif HAL_PWREx_EnableUSBVoltageDetector(); board_init2(); // optional init + // Turn off device vbus +#if CFG_TUD_ENABLED + board_vbus_set(BOARD_TUD_RHPORT, false); +#endif + // Turn on host vbus #if CFG_TUH_ENABLED - board_vbus_set(BOARD_TUH_RHPORT, 1); + board_vbus_set(BOARD_TUH_RHPORT, true); #endif } diff --git a/hw/bsp/stm32h7/linker/stm32h747xx_flash_CM7.ld b/hw/bsp/stm32h7/linker/stm32h747xx_flash_CM7.ld new file mode 100644 index 000000000..5b7fe4528 --- /dev/null +++ b/hw/bsp/stm32h7/linker/stm32h747xx_flash_CM7.ld @@ -0,0 +1,184 @@ +/* +****************************************************************************** +** + +** File : LinkerScript.ld +** +** +** Abstract : Linker script for STM32H7 series +** 1024Kbytes FLASH and 192Kbytes 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) 2019 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) + +/* Highest address of the user mode stack */ +_estack = 0x20020000; /* end of RAM */ +/* Generate a link error if heap and stack don't fit into RAM */ +_Min_Heap_Size = 0x200; /* required amount of heap */ +_Min_Stack_Size = 0x400; /* required amount of stack */ + +/* Specify the memory areas */ +MEMORY +{ +FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 1024K +RAM (xrw) : ORIGIN = 0x20000000, LENGTH = 128K +ITCMRAM (xrw) : ORIGIN = 0x00000000, LENGTH = 64K +} + +/* Define output sections */ +SECTIONS +{ + /* The startup code goes first into FLASH */ + .isr_vector : + { + . = ALIGN(4); + KEEP(*(.isr_vector)) /* Startup code */ + . = ALIGN(4); + } >FLASH + + /* The program code and other data goes into FLASH */ + .text : + { + . = ALIGN(4); + *(.text) /* .text sections (code) */ + *(.text*) /* .text* sections (code) */ + *(.glue_7) /* glue arm to thumb code */ + *(.glue_7t) /* glue thumb to arm code */ + *(.eh_frame) + + KEEP (*(.init)) + KEEP (*(.fini)) + + . = ALIGN(4); + _etext = .; /* define a global symbols at end of code */ + } >FLASH + + /* Constant data goes into FLASH */ + .rodata : + { + . = ALIGN(4); + *(.rodata) /* .rodata sections (constants, strings, etc.) */ + *(.rodata*) /* .rodata* sections (constants, strings, etc.) */ + . = ALIGN(4); + } >FLASH + + .ARM.extab : + { + . = 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 goes into RAM, load LMA copy after code */ + .data : + { + . = ALIGN(4); + _sdata = .; /* create a global symbol at data start */ + *(.data) /* .data sections */ + *(.data*) /* .data* sections */ + + . = ALIGN(4); + _edata = .; /* define a global symbol at data end */ + } >RAM AT> FLASH + + + /* Uninitialized data section */ + . = ALIGN(4); + .bss : + { + /* This is used by the startup in order to initialize the .bss 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 left */ + ._user_heap_stack : + { + . = ALIGN(8); + PROVIDE ( end = . ); + PROVIDE ( _end = . ); + . = . + _Min_Heap_Size; + . = . + _Min_Stack_Size; + . = ALIGN(8); + } >RAM + + + + /* Remove information from the standard libraries */ + /DISCARD/ : + { + libc.a ( * ) + libm.a ( * ) + libgcc.a ( * ) + } + + .ARM.attributes 0 : { *(.ARM.attributes) } +} diff --git a/hw/bsp/stm32h7rs/boards/stm32h7s3nucleo/board.cmake b/hw/bsp/stm32h7rs/boards/stm32h7s3nucleo/board.cmake index 7b3456585..189c175dd 100644 --- a/hw/bsp/stm32h7rs/boards/stm32h7s3nucleo/board.cmake +++ b/hw/bsp/stm32h7rs/boards/stm32h7s3nucleo/board.cmake @@ -2,6 +2,8 @@ set(MCU_VARIANT stm32h7s3xx) set(JLINK_DEVICE stm32h7s3l8) set(LD_FILE_Clang ${LD_FILE_GNU}) +set(RHPORT_DEVICE 1) +set(RHPORT_HOST 1) function(update_board TARGET) target_compile_definitions(${TARGET} PUBLIC diff --git a/hw/bsp/stm32h7rs/boards/stm32h7s3nucleo/board.h b/hw/bsp/stm32h7rs/boards/stm32h7s3nucleo/board.h index 58adf2664..4b8564709 100644 --- a/hw/bsp/stm32h7rs/boards/stm32h7s3nucleo/board.h +++ b/hw/bsp/stm32h7rs/boards/stm32h7s3nucleo/board.h @@ -44,7 +44,7 @@ #define UART_CLK_EN __HAL_RCC_USART3_CLK_ENABLE // VBUS Sense detection -#define OTG_FS_VBUS_SENSE 1 +#define OTG_FS_VBUS_SENSE 0 #define OTG_HS_VBUS_SENSE 0 #define PINID_LED 0 diff --git a/hw/bsp/stm32h7rs/family.c b/hw/bsp/stm32h7rs/family.c index 784c92465..2cc39b7ac 100644 --- a/hw/bsp/stm32h7rs/family.c +++ b/hw/bsp/stm32h7rs/family.c @@ -356,17 +356,14 @@ void board_init(void) { GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Alternate = GPIO_AF10_OTG_FS; HAL_GPIO_Init(GPIOM, &GPIO_InitStruct); +#endif // vbus sense - // 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; +#if CFG_TUD_ENABLED && BOARD_TUD_RHPORT == 0 + tud_configure_dwc2_t cfg = CFG_TUD_CONFIGURE_DWC2_DEFAULT; + cfg.vbus_sensing = OTG_FS_VBUS_SENSE; + tud_configure(0, TUD_CFGID_DWC2, &cfg); +#endif - // 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 -------------// @@ -382,33 +379,31 @@ void board_init(void) { #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; + GPIO_InitTypeDef GPIO_InitStruct2; + GPIO_InitStruct2.Pin = GPIO_PIN_8; + GPIO_InitStruct2.Mode = GPIO_MODE_INPUT; + GPIO_InitStruct2.Pull = GPIO_NOPULL; + GPIO_InitStruct2.Alternate = GPIO_AF10_OTG_HS; + HAL_GPIO_Init(GPIOM, &GPIO_InitStruct2); +#endif #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; + tud_configure_dwc2_t cfg = CFG_TUD_CONFIGURE_DWC2_DEFAULT; + cfg.vbus_sensing = OTG_HS_VBUS_SENSE; + tud_configure(1, TUD_CFGID_DWC2, &cfg); #endif #endif -#endif board_init2(); + // Turn off device vbus +#if CFG_TUD_ENABLED + board_vbus_set(BOARD_TUD_RHPORT, false); +#endif + // Turn on host vbus #if CFG_TUH_ENABLED - board_vbus_set(BOARD_TUH_RHPORT, 1); + board_vbus_set(BOARD_TUH_RHPORT, true); #endif } diff --git a/hw/bsp/stm32h7rs/family.cmake b/hw/bsp/stm32h7rs/family.cmake index 1fd1cb057..3b9dbf5cf 100644 --- a/hw/bsp/stm32h7rs/family.cmake +++ b/hw/bsp/stm32h7rs/family.cmake @@ -24,7 +24,7 @@ if (NOT DEFINED RHPORT_DEVICE) set(RHPORT_DEVICE 1) endif () if (NOT DEFINED RHPORT_HOST) - set(RHPORT_HOST 1) + set(RHPORT_HOST 0) endif () if (NOT DEFINED RHPORT_SPEED) diff --git a/hw/bsp/stm32l4/boards/stm32l476disco/board.h b/hw/bsp/stm32l4/boards/stm32l476disco/board.h index 8c766d8ea..cf84d3e66 100644 --- a/hw/bsp/stm32l4/boards/stm32l476disco/board.h +++ b/hw/bsp/stm32l4/boards/stm32l476disco/board.h @@ -51,6 +51,8 @@ #define UART_TX_PIN GPIO_PIN_5 #define UART_RX_PIN GPIO_PIN_6 +#define VBUS_SENSE_EN 0 + //--------------------------------------------------------------------+ // RCC Clock //--------------------------------------------------------------------+ @@ -128,15 +130,6 @@ static inline void board_clock_init(void) HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4); } -static inline void board_vbus_sense_init(void) -{ - // L476Disco use general GPIO PC11 for VBUS sensing instead of dedicated PA9 as others - // Disable VBUS Sense and force device mode - USB_OTG_FS->GCCFG &= ~USB_OTG_GCCFG_VBDEN; - - USB_OTG_FS->GOTGCTL |= USB_OTG_GOTGCTL_BVALOEN | USB_OTG_GOTGCTL_BVALOVAL; -} - #ifdef __cplusplus } #endif diff --git a/hw/bsp/stm32l4/boards/stm32l496nucleo/board.h b/hw/bsp/stm32l4/boards/stm32l496nucleo/board.h index 607210cec..3b031e00f 100644 --- a/hw/bsp/stm32l4/boards/stm32l496nucleo/board.h +++ b/hw/bsp/stm32l4/boards/stm32l496nucleo/board.h @@ -52,6 +52,8 @@ #define UART_TX_PIN GPIO_PIN_7 #define UART_RX_PIN GPIO_PIN_8 +#define VBUS_SENSE_EN 1 + //--------------------------------------------------------------------+ // RCC Clock //--------------------------------------------------------------------+ @@ -145,12 +147,6 @@ static inline void board_clock_init(void) HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct); } -static inline void board_vbus_sense_init(void) -{ - // Enable VBUS sense (B device) via pin PA9 - USB_OTG_FS->GCCFG |= USB_OTG_GCCFG_VBDEN; -} - #ifdef __cplusplus } #endif diff --git a/hw/bsp/stm32l4/boards/stm32l4p5nucleo/board.h b/hw/bsp/stm32l4/boards/stm32l4p5nucleo/board.h index f522e7522..94978638e 100644 --- a/hw/bsp/stm32l4/boards/stm32l4p5nucleo/board.h +++ b/hw/bsp/stm32l4/boards/stm32l4p5nucleo/board.h @@ -51,6 +51,8 @@ #define UART_TX_PIN GPIO_PIN_7 #define UART_RX_PIN GPIO_PIN_8 +#define VBUS_SENSE_EN 1 + //--------------------------------------------------------------------+ // RCC Clock //--------------------------------------------------------------------+ @@ -129,12 +131,6 @@ static inline void board_clock_init(void) HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5); } -static inline void board_vbus_sense_init(void) -{ - // Enable VBUS sense (B device) via pin PA9 - USB_OTG_FS->GCCFG |= USB_OTG_GCCFG_VBDEN; -} - #ifdef __cplusplus } #endif diff --git a/hw/bsp/stm32l4/boards/stm32l4r5nucleo/board.h b/hw/bsp/stm32l4/boards/stm32l4r5nucleo/board.h index c181f5d4a..f603ae855 100644 --- a/hw/bsp/stm32l4/boards/stm32l4r5nucleo/board.h +++ b/hw/bsp/stm32l4/boards/stm32l4r5nucleo/board.h @@ -51,6 +51,8 @@ #define UART_TX_PIN GPIO_PIN_7 #define UART_RX_PIN GPIO_PIN_8 +#define VBUS_SENSE_EN 1 + //--------------------------------------------------------------------+ // RCC Clock //--------------------------------------------------------------------+ @@ -129,12 +131,6 @@ static inline void board_clock_init(void) HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5); } -static inline void board_vbus_sense_init(void) -{ - // Enable VBUS sense (B device) via pin PA9 - USB_OTG_FS->GCCFG |= USB_OTG_GCCFG_VBDEN; -} - #ifdef __cplusplus } #endif diff --git a/hw/bsp/stm32l4/family.c b/hw/bsp/stm32l4/family.c index e69ae8e3b..65f6b9ab3 100644 --- a/hw/bsp/stm32l4/family.c +++ b/hw/bsp/stm32l4/family.c @@ -170,10 +170,16 @@ void board_init(void) { HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); #endif - /* Enable USB FS Clocks */ #if defined(USB_OTG_FS) + /* Enable USB FS Clocks */ __HAL_RCC_USB_OTG_FS_CLK_ENABLE(); - board_vbus_sense_init(); + + #if CFG_TUD_ENABLED + /* Set Vbus sense */ + tud_configure_dwc2_t cfg = CFG_TUD_CONFIGURE_DWC2_DEFAULT; + cfg.vbus_sensing = VBUS_SENSE_EN; + tud_configure(0, TUD_CFGID_DWC2, &cfg); + #endif #else __HAL_RCC_USB_CLK_ENABLE(); #endif diff --git a/hw/bsp/stm32n6/boards/stm32n6570dk/board.cmake b/hw/bsp/stm32n6/boards/stm32n6570dk/board.cmake index e88efefb9..00efc974c 100644 --- a/hw/bsp/stm32n6/boards/stm32n6570dk/board.cmake +++ b/hw/bsp/stm32n6/boards/stm32n6570dk/board.cmake @@ -1,5 +1,5 @@ set(MCU_VARIANT stm32n657xx) -set(JLINK_DEVICE stm32n6xx) +set(JLINK_DEVICE stm32n657x0) set(LD_FILE_GNU ${CMAKE_CURRENT_LIST_DIR}/STM32N657XX_AXISRAM2_fsbl.ld) diff --git a/hw/bsp/stm32n6/boards/stm32n6570dk/board.h b/hw/bsp/stm32n6/boards/stm32n6570dk/board.h index bbcad6340..8c2ec66dc 100644 --- a/hw/bsp/stm32n6/boards/stm32n6570dk/board.h +++ b/hw/bsp/stm32n6/boards/stm32n6570dk/board.h @@ -44,17 +44,16 @@ extern "C" { #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 OTG_FS_VBUS_SENSE 0 +#define OTG_HS_VBUS_SENSE 0 #define PINID_LED 0 #define PINID_BUTTON 1 #define PINID_UART_TX 2 #define PINID_UART_RX 3 #define PINID_TCPP0203_EN 4 +#define PINID_PWR_USB2 8 static board_pindef_t board_pindef[] = { {// LED @@ -77,21 +76,22 @@ static board_pindef_t board_pindef[] = { .port = GPIOA, .pin_init = {.Pin = GPIO_PIN_4, .Mode = GPIO_MODE_OUTPUT_PP, .Pull = GPIO_PULLDOWN, .Speed = GPIO_SPEED_FREQ_HIGH, .Alternate = 0}, .active_state = 0}, - { - // I2C SCL for TCPP0203 - .port = GPIOD, - .pin_init = {.Pin = GPIO_PIN_14, .Mode = GPIO_MODE_AF_OD, .Pull = GPIO_NOPULL, .Speed = GPIO_SPEED_FREQ_LOW, .Alternate = GPIO_AF4_I2C2}, + { // I2C SCL for TCPP0203 + .port = GPIOD, + .pin_init = {.Pin = GPIO_PIN_14, .Mode = GPIO_MODE_AF_OD, .Pull = GPIO_NOPULL, .Speed = GPIO_SPEED_FREQ_LOW, .Alternate = GPIO_AF4_I2C2}, }, - { - // I2C SDA for TCPP0203 - .port = GPIOD, - .pin_init = {.Pin = GPIO_PIN_4, .Mode = GPIO_MODE_AF_OD, .Pull = GPIO_NOPULL, .Speed = GPIO_SPEED_FREQ_LOW, .Alternate = GPIO_AF4_I2C2}, + {// I2C SDA for TCPP0203 + .port = GPIOD, + .pin_init = {.Pin = GPIO_PIN_4, .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_10, .Mode = GPIO_MODE_IT_FALLING, .Pull = GPIO_PULLUP, .Speed = GPIO_SPEED_FREQ_HIGH, .Alternate = 0}, + {// INT for TCPP0203 + .port = GPIOD, + .pin_init = {.Pin = GPIO_PIN_10, .Mode = GPIO_MODE_IT_FALLING, .Pull = GPIO_PULLUP, .Speed = GPIO_SPEED_FREQ_HIGH, .Alternate = 0}, }, + {// PWR for USB2 + .port = GPIOB, + .pin_init = {.Pin = GPIO_PIN_9, .Mode = GPIO_MODE_OUTPUT_PP, .Pull = GPIO_NOPULL, .Speed = GPIO_SPEED_FREQ_HIGH, .Alternate = 0}, + } }; //--------------------------------------------------------------------+ @@ -262,9 +262,12 @@ static inline void board_init2(void) { } 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, ); + if (rhport == 0) { + uint8_t switch_state = state ? TCPP0203_GD_PROVIDER_SWITCH_CLOSED : TCPP0203_GD_PROVIDER_SWITCH_OPEN; + TU_ASSERT(TCPP0203_SetGateDriverProvider(&tcpp0203_obj, switch_state) == TCPP0203_OK, ); + } else if (rhport == 1) { + board_pindef_t *pindef = &board_pindef[PINID_PWR_USB2]; + HAL_GPIO_WritePin(pindef->port, pindef->pin_init.Pin, state ? GPIO_PIN_SET : GPIO_PIN_RESET); } } diff --git a/hw/bsp/stm32n6/boards/stm32n657nucleo/board.cmake b/hw/bsp/stm32n6/boards/stm32n657nucleo/board.cmake index e88efefb9..e682cabcb 100644 --- a/hw/bsp/stm32n6/boards/stm32n657nucleo/board.cmake +++ b/hw/bsp/stm32n6/boards/stm32n657nucleo/board.cmake @@ -1,8 +1,15 @@ set(MCU_VARIANT stm32n657xx) -set(JLINK_DEVICE stm32n6xx) +set(JLINK_DEVICE stm32n657x0) set(LD_FILE_GNU ${CMAKE_CURRENT_LIST_DIR}/STM32N657XX_AXISRAM2_fsbl.ld) +if (NOT DEFINED RHPORT_DEVICE) + set(RHPORT_DEVICE 0) +endif () +if (NOT DEFINED RHPORT_HOST) + set(RHPORT_HOST 0) +endif () + function(update_board TARGET) target_compile_definitions(${TARGET} PUBLIC STM32N657xx diff --git a/hw/bsp/stm32n6/boards/stm32n657nucleo/board.h b/hw/bsp/stm32n6/boards/stm32n657nucleo/board.h index 33c68f7cf..5bdbaff3c 100644 --- a/hw/bsp/stm32n6/boards/stm32n657nucleo/board.h +++ b/hw/bsp/stm32n6/boards/stm32n657nucleo/board.h @@ -44,11 +44,9 @@ extern "C" { #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 OTG_FS_VBUS_SENSE 0 +#define OTG_HS_VBUS_SENSE 0 #define PINID_LED 0 #define PINID_BUTTON 1 @@ -77,20 +75,17 @@ static board_pindef_t board_pindef[] = { .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 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}, + {// 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}, + {// 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}, }, }; @@ -262,9 +257,9 @@ static inline void board_init2(void) { } 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, ); + if (rhport == 0) { + uint8_t switch_state = state ? TCPP0203_GD_PROVIDER_SWITCH_CLOSED : TCPP0203_GD_PROVIDER_SWITCH_OPEN; + TU_ASSERT(TCPP0203_SetGateDriverProvider(&tcpp0203_obj, switch_state) == TCPP0203_OK, ); } } diff --git a/hw/bsp/stm32n6/boards/stm32n657nucleo/board.mk b/hw/bsp/stm32n6/boards/stm32n657nucleo/board.mk index 05717699c..efbb82611 100644 --- a/hw/bsp/stm32n6/boards/stm32n657nucleo/board.mk +++ b/hw/bsp/stm32n6/boards/stm32n657nucleo/board.mk @@ -1,9 +1,12 @@ MCU_VARIANT = stm32n657xx CFLAGS += -DSTM32N657xx -JLINK_DEVICE = stm32n6xx +JLINK_DEVICE = stm32n657x0 LD_FILE_GCC = $(BOARD_PATH)/STM32N657XX_AXISRAM2_fsbl.ld +RHPORT_DEVICE ?= 0 +RHPORT_HOST ?= 0 + # flash target using on-board stlink flash: flash-stlink diff --git a/hw/bsp/stm32n6/family.c b/hw/bsp/stm32n6/family.c index 567bb7294..c839e6b3e 100644 --- a/hw/bsp/stm32n6/family.c +++ b/hw/bsp/stm32n6/family.c @@ -48,7 +48,8 @@ TU_ATTR_UNUSED static void Error_Handler(void) { } void HardFault_Handler(void); - +static void MPU_Config(void); +static void SystemIsolation_Config(void); typedef struct { GPIO_TypeDef* port; GPIO_InitTypeDef pin_init; @@ -87,20 +88,25 @@ static UART_HandleTypeDef UartHandle = { // 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); + tusb_int_handler(1, 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); + tusb_int_handler(0, true); } void board_init(void) { - /* Enable BusFault and SecureFault handlers (HardFault is default) */ SCB->SHCSR |= (SCB_SHCSR_BUSFAULTENA_Msk | SCB_SHCSR_SECUREFAULTENA_Msk); + MPU_Config(); + SystemIsolation_Config(); + + SCB_EnableICache(); + SCB_EnableDCache(); + HAL_PWREx_EnableVddA(); HAL_PWREx_EnableVddIO2(); HAL_PWREx_EnableVddIO3(); @@ -126,8 +132,6 @@ void board_init(void) { __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); } @@ -155,7 +159,7 @@ void board_init(void) { HAL_UART_Init(&UartHandle); #endif - +#if (CFG_TUD_ENABLED && BOARD_TUD_RHPORT == 0) || (CFG_TUH_ENABLED && BOARD_TUH_RHPORT == 0) __HAL_RCC_USB1_OTG_HS_CLK_ENABLE(); __HAL_RCC_PWR_CLK_ENABLE(); HAL_PWREx_EnableVddUSBVMEN(); @@ -196,11 +200,109 @@ void board_init(void) { /* Peripheral PHY clock enable */ __HAL_RCC_USB1_OTG_HS_PHY_CLK_ENABLE(); - board_init2(); +#if CFG_TUH_ENABLED && BOARD_TUH_RHPORT == 0 + board_vbus_set(BOARD_TUH_RHPORT, 1); +#endif +#endif + +#if (CFG_TUD_ENABLED && BOARD_TUD_RHPORT == 1) || (CFG_TUH_ENABLED && BOARD_TUH_RHPORT == 1) + __HAL_RCC_USB2_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_USB2_OTG_HS_FORCE_RESET(); + __HAL_RCC_USB2_OTG_HS_PHY_FORCE_RESET(); + + LL_RCC_HSE_SelectHSEDiv2AsDiv2Clock(); + LL_AHB5_GRP1_ReleaseReset(0x00800000); + + /* Peripheral clock enable */ + __HAL_RCC_USB2_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 + } + + USB2_HS_PHYC->USBPHYC_CR &= ~(0x7 << 0x4); + + USB2_HS_PHYC->USBPHYC_CR |= (0x1 << 16) | + (0x2 << 4) | + (0x1 << 2) | + 0x1U; + + __HAL_RCC_USB2_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_USB2_OTG_HS_RELEASE_RESET(); + + /* Peripheral PHY clock enable */ + __HAL_RCC_USB2_OTG_HS_PHY_CLK_ENABLE(); -#if CFG_TUH_ENABLED +#if CFG_TUH_ENABLED && BOARD_TUH_RHPORT == 1 board_vbus_set(BOARD_TUH_RHPORT, 1); #endif +#endif + + board_init2(); +} + +static void MPU_Config(void) +{ + MPU_Region_InitTypeDef default_config = {0}; + MPU_Attributes_InitTypeDef attr_config = {0}; + uint32_t primask_bit = __get_PRIMASK(); + __disable_irq(); + + /* disable the MPU */ + HAL_MPU_Disable(); + + /* create an attribute configuration for the MPU */ + attr_config.Attributes = INNER_OUTER(MPU_NOT_CACHEABLE); + attr_config.Number = MPU_ATTRIBUTES_NUMBER0; + + HAL_MPU_ConfigMemoryAttributes(&attr_config); + + /* Create a non cacheable region */ + /*Normal memory type, code execution allowed */ + default_config.Enable = MPU_REGION_ENABLE; + default_config.Number = MPU_REGION_NUMBER0; + default_config.BaseAddress = __NON_CACHEABLE_SECTION_BEGIN; + default_config.LimitAddress = __NON_CACHEABLE_SECTION_END; + default_config.DisableExec = MPU_INSTRUCTION_ACCESS_ENABLE; + default_config.AccessPermission = MPU_REGION_ALL_RW; + default_config.IsShareable = MPU_ACCESS_NOT_SHAREABLE; + default_config.AttributesIndex = MPU_ATTRIBUTES_NUMBER0; + HAL_MPU_ConfigRegion(&default_config); + + /* enable the MPU */ + HAL_MPU_Enable(MPU_PRIVILEGED_DEFAULT); + + /* Exit critical section to lock the system and avoid any issue around MPU mechanisme */ + __set_PRIMASK(primask_bit); +} + +static void SystemIsolation_Config(void) { + /* set all required IPs as secure privileged */ + __HAL_RCC_RIFSC_CLK_ENABLE(); + RIMC_MasterConfig_t RIMC_master = {0}; + RIMC_master.MasterCID = RIF_CID_1; + RIMC_master.SecPriv = RIF_ATTRIBUTE_SEC | RIF_ATTRIBUTE_PRIV; + + /*RIMC configuration*/ + HAL_RIF_RIMC_ConfigMasterAttributes(RIF_MASTER_INDEX_OTG1, &RIMC_master); + HAL_RIF_RIMC_ConfigMasterAttributes(RIF_MASTER_INDEX_OTG2, &RIMC_master); + + /*RISUP configuration*/ + HAL_RIF_RISC_SetSlaveSecureAttributes(RIF_RISC_PERIPH_INDEX_OTG1HS , RIF_ATTRIBUTE_SEC | RIF_ATTRIBUTE_PRIV); + HAL_RIF_RISC_SetSlaveSecureAttributes(RIF_RISC_PERIPH_INDEX_OTG2HS , RIF_ATTRIBUTE_SEC | RIF_ATTRIBUTE_PRIV); } //--------------------------------------------------------------------+ diff --git a/hw/bsp/stm32n6/family.cmake b/hw/bsp/stm32n6/family.cmake index 6c7aaea61..972138018 100644 --- a/hw/bsp/stm32n6/family.cmake +++ b/hw/bsp/stm32n6/family.cmake @@ -21,7 +21,7 @@ set(FAMILY_MCUS STM32N6 CACHE INTERNAL "") # Port & Speed Selection # ---------------------- if (NOT DEFINED RHPORT_DEVICE) - set(RHPORT_DEVICE 1) + set(RHPORT_DEVICE 0) endif () if (NOT DEFINED RHPORT_HOST) set(RHPORT_HOST 1) @@ -68,6 +68,7 @@ function(family_add_board BOARD_TARGET) ${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 + ${ST_HAL_DRIVER}/Src/${ST_PREFIX}_hal_rif.c ) target_include_directories(${BOARD_TARGET} PUBLIC ${CMAKE_CURRENT_FUNCTION_LIST_DIR} @@ -80,8 +81,8 @@ function(family_add_board BOARD_TARGET) 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 + SEGGER_RTT_SECTION=".noncacheable" + BUFFER_SIZE_UP=0x4000 ) update_board(${BOARD_TARGET}) diff --git a/hw/bsp/stm32n6/family.mk b/hw/bsp/stm32n6/family.mk index 45554e251..9fef533b1 100644 --- a/hw/bsp/stm32n6/family.mk +++ b/hw/bsp/stm32n6/family.mk @@ -12,7 +12,7 @@ CPU_CORE ?= cortex-m55 # ---------------------- # Port & Speed Selection # ---------------------- -RHPORT_DEVICE ?= 1 +RHPORT_DEVICE ?= 0 RHPORT_HOST ?= 1 ifndef RHPORT_DEVICE_SPEED @@ -32,8 +32,8 @@ CFLAGS += \ -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 \ + -DSEGGER_RTT_SECTION="\".noncacheable\"" \ + -DBUFFER_SIZE_UP=0x4000 \ # GCC Flags CFLAGS_GCC += \ diff --git a/hw/bsp/stm32n6/setup_iar.mac b/hw/bsp/stm32n6/setup_iar.mac new file mode 100644 index 000000000..b6f2bc97a --- /dev/null +++ b/hw/bsp/stm32n6/setup_iar.mac @@ -0,0 +1,12 @@ +/* Called once after the target reset. */ +execUserReset() +{ + /* Re-load image as AIXRAM2 is erased after CPU reset */ + __loadImage("$EXE_DIR$\\$TARGET_BNAME$.hex", 0, 0); + + __restoreSoftwareBreakpoints(); + + #PC = __readMemory32(0x34180404, "Memory"); + + #SP = 0x341FFD00; +} diff --git a/hw/bsp/stm32n6/stm32n6.jdebug b/hw/bsp/stm32n6/stm32n6.jdebug new file mode 100644 index 000000000..81490db5d --- /dev/null +++ b/hw/bsp/stm32n6/stm32n6.jdebug @@ -0,0 +1,362 @@ +/********************************************************************* +* (c) SEGGER Microcontroller GmbH * +* The Embedded Experts * +* www.segger.com * +********************************************************************** + +File : +Created : 31. Jan 2026 16:34 +Ozone Version : V3.40e +*/ + +/********************************************************************* +* +* OnProjectLoad +* +* Function description +* Project load routine. Required. +* +********************************************************************** +*/ +void OnProjectLoad (void) { + // + // Dialog-generated settings + // + Project.SetDevice ("STM32N657X0"); + Project.SetHostIF ("USB", ""); + Project.SetTargetIF ("SWD"); + Project.SetTIFSpeed ("4 MHz"); + Project.AddSvdFile ("$(InstallDir)/Config/CPU/Cortex-M55F.svd"); + // + // User settings + // + File.Open ("$(ProjectDir)/../../../examples/device/cdc_msc/build/stm32n6570dk/RelWithDebInfo/cdc_msc.elf"); +} + +/********************************************************************* +* +* OnStartupComplete +* +* Function description +* Called when program execution has reached/passed +* the startup completion point. Optional. +* +********************************************************************** +*/ +//void OnStartupComplete (void) { +//} + +/********************************************************************* +* +* TargetReset +* +* Function description +* Replaces the default target device reset routine. Optional. +* +* Notes +* This example demonstrates the usage when +* debugging an application in RAM on a Cortex-M target device. +* +********************************************************************** +*/ +//void TargetReset (void) { +// +// unsigned int SP; +// unsigned int PC; +// unsigned int VectorTableAddr; +// +// VectorTableAddr = Elf.GetBaseAddr(); +// // +// // Set up initial stack pointer +// // +// if (VectorTableAddr != 0xFFFFFFFF) { +// SP = Target.ReadU32(VectorTableAddr); +// Target.SetReg("SP", SP); +// } +// // +// // Set up entry point PC +// // +// PC = Elf.GetEntryPointPC(); +// +// if (PC != 0xFFFFFFFF) { +// Target.SetReg("PC", PC); +// } else if (VectorTableAddr != 0xFFFFFFFF) { +// PC = Target.ReadU32(VectorTableAddr + 4); +// Target.SetReg("PC", PC); +// } else { +// Util.Error("Project file error: failed to set entry point PC", 1); +// } +//} + +/********************************************************************* +* +* BeforeTargetReset +* +* Function description +* Event handler routine. Optional. +* +********************************************************************** +*/ +//void BeforeTargetReset (void) { +//} + +/********************************************************************* +* +* AfterTargetReset +* +* Function description +* Event handler routine. Optional. +* The default implementation initializes SP and PC to reset values. +** +********************************************************************** +*/ +void AfterTargetReset (void) { + _SetupTarget(); +} + +/********************************************************************* +* +* DebugStart +* +* Function description +* Replaces the default debug session startup routine. Optional. +* +********************************************************************** +*/ +//void DebugStart (void) { +//} + +/********************************************************************* +* +* TargetConnect +* +* Function description +* Replaces the default target IF connection routine. Optional. +* +********************************************************************** +*/ +//void TargetConnect (void) { +//} + +/********************************************************************* +* +* BeforeTargetConnect +* +* Function description +* Event handler routine. Optional. +* +********************************************************************** +*/ +//void BeforeTargetConnect (void) { +//} + +/********************************************************************* +* +* 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) { +//} + +/********************************************************************* +* +* OnDebugStartBreakSymbolReached +* +* Function description +* Called when program execution has reached/passed +* the symbol to be breaked at during debug start. Optional. +* +********************************************************************** +*/ +//void OnDebugStartBreakSymReached (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; + + Debug.Download(); + Debug.Halt(); + + 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/stm32n6/stm32n6xx_hal_conf.h b/hw/bsp/stm32n6/stm32n6xx_hal_conf.h index 00cb31159..49ca767fe 100644 --- a/hw/bsp/stm32n6/stm32n6xx_hal_conf.h +++ b/hw/bsp/stm32n6/stm32n6xx_hal_conf.h @@ -67,7 +67,7 @@ /*#define HAL_PKA_MODULE_ENABLED */ /*#define HAL_PSSI_MODULE_ENABLED */ /*#define HAL_RAMCFG_MODULE_ENABLED */ -/*#define HAL_RIF_MODULE_ENABLED */ +#define HAL_RIF_MODULE_ENABLED /*#define HAL_RNG_MODULE_ENABLED */ /*#define HAL_RTC_MODULE_ENABLED */ /*#define HAL_SAI_MODULE_ENABLED */ diff --git a/hw/bsp/stm32u5/boards/b_u585i_iot2a/board.h b/hw/bsp/stm32u5/boards/b_u585i_iot2a/board.h index cf3f63ea5..c99743738 100644 --- a/hw/bsp/stm32u5/boards/b_u585i_iot2a/board.h +++ b/hw/bsp/stm32u5/boards/b_u585i_iot2a/board.h @@ -55,6 +55,8 @@ extern "C" #define UART_TX_PIN GPIO_PIN_9 #define UART_RX_PIN GPIO_PIN_10 +#define VBUS_SENSE_EN 0 + //--------------------------------------------------------------------+ // RCC Clock //--------------------------------------------------------------------+ @@ -110,6 +112,9 @@ static void SystemClock_Config(void) { static void SystemPower_Config(void) { } +static inline void board_vbus_sense_init(void) { +} + #ifdef __cplusplus } #endif diff --git a/hw/bsp/stm32u5/boards/stm32u545nucleo/board.h b/hw/bsp/stm32u5/boards/stm32u545nucleo/board.h index 0c3439b2c..eb2b63721 100644 --- a/hw/bsp/stm32u5/boards/stm32u545nucleo/board.h +++ b/hw/bsp/stm32u5/boards/stm32u545nucleo/board.h @@ -110,6 +110,9 @@ static void SystemClock_Config(void) { static void SystemPower_Config(void) { } +static inline void board_vbus_sense_init(void) { +} + #ifdef __cplusplus } #endif diff --git a/hw/bsp/stm32u5/boards/stm32u575eval/board.h b/hw/bsp/stm32u5/boards/stm32u575eval/board.h index b11f6a747..cce3e38b3 100644 --- a/hw/bsp/stm32u5/boards/stm32u575eval/board.h +++ b/hw/bsp/stm32u5/boards/stm32u575eval/board.h @@ -56,6 +56,8 @@ extern "C" #define UART_TX_PIN GPIO_PIN_9 #define UART_RX_PIN GPIO_PIN_10 +#define VBUS_SENSE_EN 0 + //--------------------------------------------------------------------+ // RCC Clock //--------------------------------------------------------------------+ @@ -111,6 +113,9 @@ static void SystemClock_Config(void) { static void SystemPower_Config(void) { } +static inline void board_vbus_sense_init(void) { +} + #ifdef __cplusplus } #endif diff --git a/hw/bsp/stm32u5/boards/stm32u575nucleo/board.h b/hw/bsp/stm32u5/boards/stm32u575nucleo/board.h index be037b68a..b6b60f021 100644 --- a/hw/bsp/stm32u5/boards/stm32u575nucleo/board.h +++ b/hw/bsp/stm32u5/boards/stm32u575nucleo/board.h @@ -37,6 +37,8 @@ extern "C" { #endif +#include "stm32u5xx_ll_tim.h" + // LED GREEN #define LED_PORT GPIOC #define LED_PIN GPIO_PIN_7 @@ -55,6 +57,8 @@ extern "C" #define UART_TX_PIN GPIO_PIN_7 #define UART_RX_PIN GPIO_PIN_8 +#define VBUS_SENSE_EN 0 + //--------------------------------------------------------------------+ // RCC Clock //--------------------------------------------------------------------+ @@ -110,6 +114,104 @@ static void SystemClock_Config(void) { static void SystemPower_Config(void) { } +static inline void board_vbus_sense_init(void) { + /* ADC config */ + GPIO_InitTypeDef GPIO_InitStruct = {0}; + RCC_PeriphCLKInitTypeDef PeriphClkInit = {0}; + PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_ADCDAC; + PeriphClkInit.AdcDacClockSelection = RCC_ADCDACCLKSOURCE_HSE; + if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK) + { + Error_Handler(); + } + __HAL_RCC_ADC12_CLK_ENABLE(); + __HAL_RCC_GPIOC_CLK_ENABLE(); + GPIO_InitStruct.Pin = GPIO_PIN_2; + GPIO_InitStruct.Mode = GPIO_MODE_ANALOG; + GPIO_InitStruct.Pull = GPIO_NOPULL; + HAL_GPIO_Init(GPIOC, &GPIO_InitStruct); + + ADC_HandleTypeDef hadc1; + hadc1.Instance = ADC1; + hadc1.Init.ClockPrescaler = ADC_CLOCK_ASYNC_DIV1; + hadc1.Init.Resolution = ADC_RESOLUTION_14B; + hadc1.Init.GainCompensation = 0; + hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT; + hadc1.Init.ScanConvMode = ADC_SCAN_DISABLE; + hadc1.Init.EOCSelection = ADC_EOC_SINGLE_CONV; + hadc1.Init.LowPowerAutoWait = DISABLE; + hadc1.Init.ContinuousConvMode = DISABLE; + hadc1.Init.NbrOfConversion = 1; + hadc1.Init.DiscontinuousConvMode = DISABLE; + hadc1.Init.ExternalTrigConv = ADC_EXTERNALTRIG_T1_TRGO; + hadc1.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_RISING; + hadc1.Init.DMAContinuousRequests = DISABLE; + hadc1.Init.TriggerFrequencyMode = ADC_TRIGGER_FREQ_HIGH; + hadc1.Init.Overrun = ADC_OVR_DATA_OVERWRITTEN; + hadc1.Init.LeftBitShift = ADC_LEFTBITSHIFT_NONE; + hadc1.Init.ConversionDataManagement = ADC_CONVERSIONDATA_DR; + hadc1.Init.OversamplingMode = DISABLE; + if (HAL_ADC_Init(&hadc1) != HAL_OK) { + Error_Handler(); + } + + ADC_ChannelConfTypeDef sConfig = {0}; + sConfig.Channel = ADC_CHANNEL_3; + sConfig.Rank = ADC_REGULAR_RANK_1; + sConfig.SamplingTime = ADC_SAMPLETIME_68CYCLES; + sConfig.SingleDiff = ADC_SINGLE_ENDED; + sConfig.OffsetNumber = ADC_OFFSET_NONE; + sConfig.Offset = 0; + if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK) { + Error_Handler(); + } + HAL_NVIC_EnableIRQ(ADC1_IRQn); + + /* TIM1 init for TRGO */ + __HAL_RCC_TIM1_CLK_ENABLE(); + TIM_HandleTypeDef htim1; + TIM_ClockConfigTypeDef sClockSourceConfig = {0}; + htim1.Instance = TIM1; + htim1.Init.Prescaler = 159; + htim1.Init.CounterMode = TIM_COUNTERMODE_UP; + htim1.Init.Period = 999; + htim1.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1; + htim1.Init.RepetitionCounter = 0; + htim1.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE; + if (HAL_TIM_Base_Init(&htim1) != HAL_OK) { + Error_Handler(); + } + sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL; + if (HAL_TIM_ConfigClockSource(&htim1, &sClockSourceConfig) != HAL_OK) { + Error_Handler(); + } + LL_TIM_SetTriggerOutput(htim1.Instance, LL_TIM_TRGO_UPDATE); + + HAL_ADCEx_Calibration_Start(&hadc1, ADC_CALIB_OFFSET, ADC_SINGLE_ENDED); + HAL_ADC_Start_IT(&hadc1); + HAL_TIM_Base_Start(&htim1); +} + +void ADC1_IRQHandler(void) { + if(LL_ADC_IsActiveFlag_EOC(ADC1) != 0) { + /* Clear flag ADC group regular end of unitary conversion */ + LL_ADC_ClearFlag_EOC(ADC1); + /* ADC code = 4.5V * R2 / (R1 + R2) * (2^14) / 3.3V + * with R1 = 330kOhm and R2 = 50kOhm + */ + const uint32_t threshold = 4500 * 50 / (50 + 330) * 16384 / 3300; + if((ADC1->DR > threshold) && (USB_OTG_FS->GOTGCTL & USB_OTG_GOTGCTL_BVALOEN)) { + USB_OTG_FS->GOTGCTL |= USB_OTG_GOTGCTL_BVALOVAL; + } else { + USB_OTG_FS->GOTGCTL &= ~USB_OTG_GOTGCTL_BVALOVAL; + } + } + if(LL_ADC_IsActiveFlag_OVR(ADC1) != 0) { + /* Clear flag ADC group regular overrun */ + LL_ADC_ClearFlag_OVR(ADC1); + } +} + #ifdef __cplusplus } #endif diff --git a/hw/bsp/stm32u5/boards/stm32u5a5nucleo/board.h b/hw/bsp/stm32u5/boards/stm32u5a5nucleo/board.h index 0785fb36b..15106aee6 100644 --- a/hw/bsp/stm32u5/boards/stm32u5a5nucleo/board.h +++ b/hw/bsp/stm32u5/boards/stm32u5a5nucleo/board.h @@ -37,6 +37,8 @@ extern "C" { #endif +#include "stm32u5xx_ll_tim.h" + // LED GREEN #define LED_PORT GPIOC #define LED_PIN GPIO_PIN_7 @@ -55,11 +57,13 @@ extern "C" #define UART_TX_PIN GPIO_PIN_9 #define UART_RX_PIN GPIO_PIN_10 +#define VBUS_SENSE_EN 0 + //--------------------------------------------------------------------+ // RCC Clock //--------------------------------------------------------------------+ -static void SystemClock_Config(void) { +static inline void SystemClock_Config(void) { RCC_OscInitTypeDef RCC_OscInitStruct = { 0 }; RCC_ClkInitTypeDef RCC_ClkInitStruct = { 0 }; @@ -128,7 +132,7 @@ static void SystemClock_Config(void) { } } -static void SystemPower_Config(void) { +static inline void SystemPower_Config(void) { HAL_PWREx_EnableVddIO2(); /* @@ -141,7 +145,105 @@ static void SystemPower_Config(void) { /* USER CODE END PWR */ } +static inline void board_vbus_sense_init(void) { + /* ADC config */ + GPIO_InitTypeDef GPIO_InitStruct = {0}; + RCC_PeriphCLKInitTypeDef PeriphClkInit = {0}; + PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_ADCDAC; + PeriphClkInit.AdcDacClockSelection = RCC_ADCDACCLKSOURCE_HSE; + if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK) + { + Error_Handler(); + } + __HAL_RCC_ADC12_CLK_ENABLE(); + __HAL_RCC_GPIOC_CLK_ENABLE(); + GPIO_InitStruct.Pin = GPIO_PIN_2; + GPIO_InitStruct.Mode = GPIO_MODE_ANALOG; + GPIO_InitStruct.Pull = GPIO_NOPULL; + HAL_GPIO_Init(GPIOC, &GPIO_InitStruct); + + ADC_HandleTypeDef hadc1; + hadc1.Instance = ADC1; + hadc1.Init.ClockPrescaler = ADC_CLOCK_ASYNC_DIV1; + hadc1.Init.Resolution = ADC_RESOLUTION_14B; + hadc1.Init.GainCompensation = 0; + hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT; + hadc1.Init.ScanConvMode = ADC_SCAN_DISABLE; + hadc1.Init.EOCSelection = ADC_EOC_SINGLE_CONV; + hadc1.Init.LowPowerAutoWait = DISABLE; + hadc1.Init.ContinuousConvMode = DISABLE; + hadc1.Init.NbrOfConversion = 1; + hadc1.Init.DiscontinuousConvMode = DISABLE; + hadc1.Init.ExternalTrigConv = ADC_EXTERNALTRIG_T1_TRGO; + hadc1.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_RISING; + hadc1.Init.DMAContinuousRequests = DISABLE; + hadc1.Init.TriggerFrequencyMode = ADC_TRIGGER_FREQ_HIGH; + hadc1.Init.Overrun = ADC_OVR_DATA_OVERWRITTEN; + hadc1.Init.LeftBitShift = ADC_LEFTBITSHIFT_NONE; + hadc1.Init.ConversionDataManagement = ADC_CONVERSIONDATA_DR; + hadc1.Init.OversamplingMode = DISABLE; + if (HAL_ADC_Init(&hadc1) != HAL_OK) { + Error_Handler(); + } + + ADC_ChannelConfTypeDef sConfig = {0}; + sConfig.Channel = ADC_CHANNEL_3; + sConfig.Rank = ADC_REGULAR_RANK_1; + sConfig.SamplingTime = ADC_SAMPLETIME_68CYCLES; + sConfig.SingleDiff = ADC_SINGLE_ENDED; + sConfig.OffsetNumber = ADC_OFFSET_NONE; + sConfig.Offset = 0; + if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK) { + Error_Handler(); + } + HAL_NVIC_EnableIRQ(ADC1_2_IRQn); + + /* TIM1 init for TRGO */ + __HAL_RCC_TIM1_CLK_ENABLE(); + TIM_HandleTypeDef htim1; + TIM_ClockConfigTypeDef sClockSourceConfig = {0}; + htim1.Instance = TIM1; + htim1.Init.Prescaler = 159; + htim1.Init.CounterMode = TIM_COUNTERMODE_UP; + htim1.Init.Period = 999; + htim1.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1; + htim1.Init.RepetitionCounter = 0; + htim1.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE; + if (HAL_TIM_Base_Init(&htim1) != HAL_OK) { + Error_Handler(); + } + sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL; + if (HAL_TIM_ConfigClockSource(&htim1, &sClockSourceConfig) != HAL_OK) { + Error_Handler(); + } + LL_TIM_SetTriggerOutput(htim1.Instance, LL_TIM_TRGO_UPDATE); + + HAL_ADCEx_Calibration_Start(&hadc1, ADC_CALIB_OFFSET, ADC_SINGLE_ENDED); + HAL_ADC_Start_IT(&hadc1); + HAL_TIM_Base_Start(&htim1); +} +void ADC1_2_IRQHandler(void) { + if(LL_ADC_IsActiveFlag_EOC(ADC1) != 0) { + /* Clear flag ADC group regular end of unitary conversion */ + LL_ADC_ClearFlag_EOC(ADC1); + /* ADC code = 4.5V * R2 / (R1 + R2) * (2^14) / 3.3V + * with R1 = 330kOhm and R2 = 50kOhm + */ + const uint32_t threshold = 4500 * 50 / (50 + 330) * 16384 / 3300; + if((ADC1->DR > threshold) && (USB_OTG_HS->GOTGCTL & USB_OTG_GOTGCTL_BVALOEN)) { + USB_OTG_HS->GOTGCTL |= USB_OTG_GOTGCTL_BVALOVAL; + USB_OTG_HS->GCCFG |= USB_OTG_GCCFG_VBVALOVAL; + } else { + USB_OTG_HS->GOTGCTL &= ~USB_OTG_GOTGCTL_BVALOVAL; + USB_OTG_HS->GCCFG &= ~USB_OTG_GCCFG_VBVALOVAL; + } + } + if(LL_ADC_IsActiveFlag_OVR(ADC1) != 0) { + /* Clear flag ADC group regular overrun */ + LL_ADC_ClearFlag_OVR(ADC1); + } +} #ifdef __cplusplus } #endif diff --git a/hw/bsp/stm32u5/family.c b/hw/bsp/stm32u5/family.c index 26d72d6a0..dfcf5c537 100644 --- a/hw/bsp/stm32u5/family.c +++ b/hw/bsp/stm32u5/family.c @@ -179,18 +179,14 @@ void board_init(void) { GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_NOPULL; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); - - // Enable VBUS sense (B device) via pin PA9 - USB_OTG_FS->GCCFG |= USB_OTG_GCCFG_VBDEN; - #else - // Disable VBUS sense (B device) via pin PA9 - 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 +#if CFG_TUD_ENABLED + tud_configure_dwc2_t cfg = CFG_TUD_CONFIGURE_DWC2_DEFAULT; + cfg.vbus_sensing = VBUS_SENSE_EN; + tud_configure(0, TUD_CFGID_DWC2, &cfg); +#endif + /* Enable USB power on Pwrctrl CR2 register */ HAL_PWREx_EnableVddUSB(); @@ -218,13 +214,15 @@ void board_init(void) { /*Configuring the SYSCFG registers OTG_HS PHY*/ HAL_SYSCFG_EnableOTGPHY(SYSCFG_OTG_HS_PHY_ENABLE); - // Disable VBUS sense (B device) - USB_OTG_HS->GCCFG &= ~USB_OTG_GCCFG_VBDEN; - - // B-peripheral session valid override enable - USB_OTG_HS->GCCFG |= USB_OTG_GCCFG_VBVALEXTOEN; - USB_OTG_HS->GCCFG |= USB_OTG_GCCFG_VBVALOVAL; +#if CFG_TUD_ENABLED + tud_configure_dwc2_t cfg = CFG_TUD_CONFIGURE_DWC2_DEFAULT; + cfg.vbus_sensing = VBUS_SENSE_EN; + tud_configure(0, TUD_CFGID_DWC2, &cfg); +#endif #endif // USB_OTG_FS + + /* Non-standard VBus sense settings */ + board_vbus_sense_init(); } //--------------------------------------------------------------------+ diff --git a/hw/bsp/stm32u5/family.cmake b/hw/bsp/stm32u5/family.cmake index 58dc63ae3..3d23c554d 100644 --- a/hw/bsp/stm32u5/family.cmake +++ b/hw/bsp/stm32u5/family.cmake @@ -45,6 +45,9 @@ function(family_add_board BOARD_TARGET) ${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 + ${ST_HAL_DRIVER}/Src/${ST_PREFIX}_hal_adc.c + ${ST_HAL_DRIVER}/Src/${ST_PREFIX}_hal_adc_ex.c + ${ST_HAL_DRIVER}/Src/${ST_PREFIX}_hal_tim.c ) target_include_directories(${BOARD_TARGET} PUBLIC ${CMAKE_CURRENT_FUNCTION_LIST_DIR} @@ -96,7 +99,7 @@ function(family_configure_example TARGET RTOS) endif () if (CMAKE_C_COMPILER_ID STREQUAL "GNU" OR CMAKE_C_COMPILER_ID STREQUAL "Clang") - set_source_files_properties(${CMAKE_CURRENT_FUNCTION_LIST_DIR}/family.c PROPERTIES COMPILE_FLAGS "-Wno-missing-prototypes") + set_source_files_properties(${CMAKE_CURRENT_FUNCTION_LIST_DIR}/family.c PROPERTIES COMPILE_FLAGS "-Wno-missing-prototypes -Wno-self-assign") endif () set_source_files_properties(${STARTUP_FILE_${CMAKE_C_COMPILER_ID}} PROPERTIES SKIP_LINTING ON diff --git a/hw/bsp/stm32u5/family.mk b/hw/bsp/stm32u5/family.mk index 47aed10a9..3dab8c610 100644 --- a/hw/bsp/stm32u5/family.mk +++ b/hw/bsp/stm32u5/family.mk @@ -16,6 +16,7 @@ CFLAGS_GCC += \ -Wno-error=undef \ -Wno-error=unused-parameter \ -Wno-error=type-limits \ + -Wno-self-assign \ ifeq ($(TOOLCHAIN),gcc) CFLAGS_GCC += -Wno-error=maybe-uninitialized @@ -35,11 +36,15 @@ SRC_C += \ $(ST_HAL_DRIVER)/Src/stm32$(ST_FAMILY)xx_hal_pwr_ex.c \ $(ST_HAL_DRIVER)/Src/stm32$(ST_FAMILY)xx_hal_rcc.c \ $(ST_HAL_DRIVER)/Src/stm32$(ST_FAMILY)xx_hal_rcc_ex.c \ - $(ST_HAL_DRIVER)/Src/stm32$(ST_FAMILY)xx_hal_uart.c + $(ST_HAL_DRIVER)/Src/stm32$(ST_FAMILY)xx_hal_uart.c \ + $(ST_HAL_DRIVER)/Src/stm32$(ST_FAMILY)xx_hal_adc.c \ + $(ST_HAL_DRIVER)/Src/stm32$(ST_FAMILY)xx_hal_adc_ex.c \ + $(ST_HAL_DRIVER)/Src/stm32$(ST_FAMILY)xx_hal_tim.c ifneq ($(filter stm32u545xx stm32u535xx,$(MCU_VARIANT)),) SRC_C += \ src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c \ + src/portable/st/stm32_fsdev/hcd_stm32_fsdev.c \ src/portable/st/stm32_fsdev/fsdev_common.c else SRC_C += \ diff --git a/hw/bsp/stm32u5/stm32u5xx_hal_conf.h b/hw/bsp/stm32u5/stm32u5xx_hal_conf.h index 87c3683de..5d95862f6 100644 --- a/hw/bsp/stm32u5/stm32u5xx_hal_conf.h +++ b/hw/bsp/stm32u5/stm32u5xx_hal_conf.h @@ -36,7 +36,7 @@ #define HAL_MODULE_ENABLED -/*#define HAL_ADC_MODULE_ENABLED */ +#define HAL_ADC_MODULE_ENABLED /*#define HAL_MDF_MODULE_ENABLED */ /*#define HAL_COMP_MODULE_ENABLED */ /*#define HAL_CORDIC_MODULE_ENABLED */ @@ -76,7 +76,7 @@ /*#define HAL_SMBUS_MODULE_ENABLED */ /*#define HAL_SPI_MODULE_ENABLED */ /*#define HAL_SRAM_MODULE_ENABLED */ -/*#define HAL_TIM_MODULE_ENABLED */ +#define HAL_TIM_MODULE_ENABLED /*#define HAL_TSC_MODULE_ENABLED */ /*#define HAL_RAMCFG_MODULE_ENABLED */ #define HAL_UART_MODULE_ENABLED diff --git a/hw/bsp/stm32wba/family.c b/hw/bsp/stm32wba/family.c index 8dc6547ae..d05415755 100644 --- a/hw/bsp/stm32wba/family.c +++ b/hw/bsp/stm32wba/family.c @@ -172,14 +172,7 @@ void board_init(void) { // Configuring the SYSCFG registers OTG_HS PHY SYSCFG->OTGHSPHYCR |= SYSCFG_OTGHSPHYCR_EN; - - // Disable VBUS sense (B device) - USB_OTG_HS->GCCFG &= ~USB_OTG_GCCFG_VBDEN; - - // B-peripheral session valid override enable - USB_OTG_HS->GCCFG |= USB_OTG_GCCFG_VBVALEXTOEN; - USB_OTG_HS->GCCFG |= USB_OTG_GCCFG_VBVALOVAL; - #endif // USB_OTG_FS + #endif // USB_OTG_HS } void board_led_write(bool state) { HAL_GPIO_WritePin(LED_PORT, LED_PIN, state ? LED_STATE_ON : (1 - LED_STATE_ON)); } diff --git a/hw/bsp/tm4c/FreeRTOSConfig/FreeRTOSConfig.h b/hw/bsp/tm4c/FreeRTOSConfig/FreeRTOSConfig.h index 454b085e9..b4423e269 100644 --- a/hw/bsp/tm4c/FreeRTOSConfig/FreeRTOSConfig.h +++ b/hw/bsp/tm4c/FreeRTOSConfig/FreeRTOSConfig.h @@ -44,7 +44,13 @@ // skip if included from IAR assembler #ifndef __IASMARM__ - #include "TM4C123.h" + #ifdef TM4C123GH6PM + #include "TM4C123.h" + #elif TM4C1294NCPDT + #include "TM4C129.h" + #else + #error "Unknown TM4C device" + #endif #endif /* Cortex M23/M33 port configuration. */ diff --git a/hw/bsp/tm4c/boards/ek_tm4c123gxl/board.h b/hw/bsp/tm4c/boards/ek_tm4c123gxl/board.h index c0ceb4cd8..fc0ab4c60 100644 --- a/hw/bsp/tm4c/boards/ek_tm4c123gxl/board.h +++ b/hw/bsp/tm4c/boards/ek_tm4c123gxl/board.h @@ -36,20 +36,26 @@ extern "C" { #endif +#include "TM4C123.h" + #define BOARD_UART UART0 #define BOARD_UART_PORT GPIOA +#define BTN_PORT_CLK 5 #define BOARD_BTN_PORT GPIOF #define BOARD_BTN 4 #define BOARD_BTN_Msk (1u<<4) #define BUTTON_STATE_ACTIVE 0 +#define LED_PORT_CLK 5 #define LED_PORT GPIOF #define LED_PIN_RED 1 #define LED_PIN_BLUE 2 #define LED_PIN_GREEN 3 #define LED_STATE_ON 1 +#define BOARD_LED_PIN LED_PIN_BLUE + #ifdef __cplusplus } #endif diff --git a/hw/bsp/tm4c/boards/ek_tm4c123gxl/tm4c123.ld b/hw/bsp/tm4c/boards/ek_tm4c123gxl/tm4c123.ld index 11e9608cc..3f06d8f03 100644 --- a/hw/bsp/tm4c/boards/ek_tm4c123gxl/tm4c123.ld +++ b/hw/bsp/tm4c/boards/ek_tm4c123gxl/tm4c123.ld @@ -17,7 +17,7 @@ SECTIONS .text : { . = ALIGN(4) ; - *(.vectors) + KEEP(*(.vectors)) *(.text) *(.text.*) *(.init) diff --git a/hw/bsp/tm4c/boards/ek_tm4c1294xl/TM4C1294NC.icf b/hw/bsp/tm4c/boards/ek_tm4c1294xl/TM4C1294NC.icf new file mode 100644 index 000000000..2dba41866 --- /dev/null +++ b/hw/bsp/tm4c/boards/ek_tm4c1294xl/TM4C1294NC.icf @@ -0,0 +1,28 @@ +/*###ICF### Section handled by ICF editor, don't touch! ****/ +/*-Editor annotation file-*/ +/* IcfEditorFile="$TOOLKIT_DIR$\config\ide\IcfEditor\cortex_v1_0.xml" */ +/*-Specials-*/ +define symbol __ICFEDIT_intvec_start__ = 0x00000000; +/*-Memory Regions-*/ +define symbol __ICFEDIT_region_ROM_start__ = 0x00000000; +define symbol __ICFEDIT_region_ROM_end__ = 0x000FFFFF; +define symbol __ICFEDIT_region_RAM_start__ = 0x20000000; +define symbol __ICFEDIT_region_RAM_end__ = 0x2003FFFF; +/*-Sizes-*/ +define symbol __ICFEDIT_size_cstack__ = 0x8000; +define symbol __ICFEDIT_size_heap__ = 0x10000; +/**** End of ICF editor section. ###ICF###*/ + +define memory mem with size = 4G; +define region ROM_region = mem:[from __ICFEDIT_region_ROM_start__ to __ICFEDIT_region_ROM_end__]; +define region RAM_region = mem:[from __ICFEDIT_region_RAM_start__ to __ICFEDIT_region_RAM_end__]; + +define block CSTACK with alignment = 8, size = __ICFEDIT_size_cstack__ { }; +define block HEAP with alignment = 8, size = __ICFEDIT_size_heap__ { }; + +initialize by copy { readwrite }; + +place at address mem:__ICFEDIT_intvec_start__ { readonly section .intvec }; +place in ROM_region { readonly }; +place in RAM_region { readwrite, + block CSTACK, block HEAP }; diff --git a/hw/bsp/tm4c/boards/ek_tm4c1294xl/board.cmake b/hw/bsp/tm4c/boards/ek_tm4c1294xl/board.cmake new file mode 100644 index 000000000..3e03b3f72 --- /dev/null +++ b/hw/bsp/tm4c/boards/ek_tm4c1294xl/board.cmake @@ -0,0 +1,13 @@ +set(MCU_SUB_VARIANT 129) + +set(JLINK_DEVICE TM4C1294NCPDT) +set(LD_FILE_GNU ${CMAKE_CURRENT_LIST_DIR}/tm4c1294nc.ld) +set(LD_FILE_IAR ${CMAKE_CURRENT_LIST_DIR}/TM4C1294NC.icf) + +set(OPENOCD_OPTION "-f board/ti_ek-tm4c1294xl.cfg") + +function(update_board TARGET) + target_compile_definitions(${TARGET} PUBLIC + TM4C1294NCPDT + ) +endfunction() diff --git a/hw/bsp/tm4c/boards/ek_tm4c1294xl/board.h b/hw/bsp/tm4c/boards/ek_tm4c1294xl/board.h new file mode 100644 index 000000000..4530e9430 --- /dev/null +++ b/hw/bsp/tm4c/boards/ek_tm4c1294xl/board.h @@ -0,0 +1,75 @@ +/* + * 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: TM4C1294 LaunchPad + url: https://www.ti.com/tool/EK-TM4C1294XL +*/ + +#ifndef _BOARD_H_ +#define _BOARD_H_ + +#ifdef __cplusplus + extern "C" { +#endif + +#include "TM4C129.h" + +#define BOARD_UART UART0 +#define BOARD_UART_PORT GPIOA + +#define BTN_PORT_CLK 8 +#define BOARD_BTN_PORT GPIOJ +#define BOARD_BTN 0 +#define BOARD_BTN_Msk (1u<<0) +#define BUTTON_STATE_ACTIVE 0 + +#define LED_PORT_CLK 12 +#define LED_PORT GPION +#define LED_PIN_1 1 +#define LED_PIN_2 0 +#define LED_STATE_ON 1 + +#define BOARD_LED_PIN LED_PIN_2 + +#define GPIOA GPIOA_AHB +#define GPIOB GPIOB_AHB +#define GPIOC GPIOC_AHB +#define GPIOD GPIOD_AHB +#define GPIOE GPIOE_AHB +#define GPIOF GPIOF_AHB +#define GPIOG GPIOG_AHB +#define GPIOH GPIOH_AHB +#define GPIOI GPIOI_AHB +#define GPIOJ GPIOJ_AHB + +#define GPIOA_Type GPIOA_AHB_Type + +#ifdef __cplusplus + } +#endif + +#endif diff --git a/hw/bsp/tm4c/boards/ek_tm4c1294xl/board.mk b/hw/bsp/tm4c/boards/ek_tm4c1294xl/board.mk new file mode 100644 index 000000000..b01977674 --- /dev/null +++ b/hw/bsp/tm4c/boards/ek_tm4c1294xl/board.mk @@ -0,0 +1,16 @@ +MCU_SUB_VARIANT = 129 + +CFLAGS += -DTM4C1294NCPDT + +LD_FILE_GCC = $(BOARD_PATH)/tm4c1294nc.ld +LD_FILE_IAR = $(BOARD_PATH)/TM4C1294NC.icf + +# For flash-jlink target +JLINK_DEVICE = TM4C1294NCPDT + +# flash using openocd +OPENOCD_OPTION = -f board/ti_ek-tm4c1294xl.cfg + +UNIFLASH_OPTION = -c ${TOP}/${BOARD_PATH}/${BOARD}.ccxml -r 1 + +flash: flash-openocd diff --git a/hw/bsp/tm4c/boards/ek_tm4c1294xl/tm4c1294nc.ld b/hw/bsp/tm4c/boards/ek_tm4c1294xl/tm4c1294nc.ld new file mode 100644 index 000000000..fa4ea4dc5 --- /dev/null +++ b/hw/bsp/tm4c/boards/ek_tm4c1294xl/tm4c1294nc.ld @@ -0,0 +1,66 @@ +ENTRY(Reset_Handler) + +_estack = 0x20008000; /* end of RAM */ +/* Generate a link error if heap and stack don't fit into RAM */ +_Min_Heap_Size = 0; /* required amount of heap */ +_Min_Stack_Size = 0x1000; /* required amount of stack */ + + +MEMORY +{ + FLASH (rx) : ORIGIN = 0x00000000, LENGTH = 0x00100000 + SRAM (rwx) : ORIGIN = 0x20000000, LENGTH = 0x00040000 +} + +SECTIONS +{ + .text : + { + . = ALIGN(4) ; + _text = . ; + KEEP(*(.isr_vector)) + *(.text) + *(.text.*) + *(.init) + *(.fini) + *(.rodata) + *(.rodata.*) + *(.ARM.exidx*) + _etext = . ; + . = ALIGN(4) ; + } >FLASH + + .data : AT(ADDR(.text) + SIZEOF(.text)) + { + _data = .; + . = ALIGN(4); + _ldata = LOADADDR (.data); + *(.data) + *(.data.*) + _edata = .; + . = ALIGN(4); + + } >SRAM + + .bss : + { + . = ALIGN(4) ; + _bss = .; + *(.bss) + *(.bss.*) + *(.COMMON) + _ebss = .; + . = ALIGN(4); + }>SRAM + + /* User_heap_stack section, used to check that there is enough RAM left */ + ._user_heap_stack : + { + . = ALIGN(8); + PROVIDE ( end = . ); + PROVIDE ( _end = . ); + . = . + _Min_Heap_Size; + . = . + _Min_Stack_Size; + . = ALIGN(8); + } >SRAM +} diff --git a/hw/bsp/tm4c/family.c b/hw/bsp/tm4c/family.c index ee1fa2a3c..ae7f22f00 100644 --- a/hw/bsp/tm4c/family.c +++ b/hw/bsp/tm4c/family.c @@ -2,7 +2,6 @@ manufacturer: Texas Instruments */ -#include "TM4C123.h" #include "bsp/board_api.h" #include "board.h" @@ -27,6 +26,9 @@ static void board_uart_init(void) { SYSCTL->RCGCUART |= (1 << 0); // Enable the clock to UART0 SYSCTL->RCGCGPIO |= (1 << 0); // Enable the clock to GPIOA + while (!(SYSCTL->PRGPIO & (1 << 0))) {} // Wait for the GPIOA clock to stabilize + while (!(SYSCTL->PRUART & (1 << 0))) {} // Wait for the UART0 clock to stabilize + GPIOA->AFSEL |= (1 << 1) | (1 << 0); // Enable the alternate function on pin PA0 & PA1 GPIOA->PCTL |= (1 << 0) | (1 << 4); // Configure the GPIOPCTL register to select UART0 in PA0 and PA1 GPIOA->DEN |= (1 << 0) | (1 << 1); // Enable the digital functionality in PA0 and PA1 @@ -44,12 +46,26 @@ static void board_uart_init(void) { UART0->CTL = (1 << 0) | (1 << 8) | (1 << 9); // UART0 Enable, Transmit Enable, Receive Enable } -static void initialize_board_led(GPIOA_Type* port, uint8_t PinMsk, uint8_t dirmsk) { - /* Enable PortF Clock */ - SYSCTL->RCGCGPIO |= (1 << 5); +static void board_button_init(GPIOA_Type* port, uint8_t PinMsk) { + /* Enable Port Clock */ + SYSCTL->RCGCGPIO |= (1 << BTN_PORT_CLK); + + /* Let the clock stabilize */ + while (!((SYSCTL->PRGPIO) & (1 << BTN_PORT_CLK))) {} + + /* Port Digital Enable */ + port->DEN |= PinMsk; + + /* Set direction */ + port->DIR &= ~PinMsk; +} + +static void board_led_init(GPIOA_Type* port, uint8_t PinMsk, uint8_t dirmsk) { + /* Enable Port Clock */ + SYSCTL->RCGCGPIO |= (1 << LED_PORT_CLK); /* Let the clock stabilize */ - while (!((SYSCTL->PRGPIO) & (1 << 5))) {} + while (!((SYSCTL->PRGPIO) & (1 << LED_PORT_CLK))) {} /* Port Digital Enable */ port->DEN |= PinMsk; @@ -71,7 +87,9 @@ static uint32_t ReadGPIOPin(GPIOA_Type* port, uint8_t pinMsk) { } void board_init(void) { +#ifdef TM4C123_H SystemCoreClockUpdate(); +#endif #if CFG_TUSB_OS == OPT_OS_NONE // 1ms tick timer @@ -83,6 +101,7 @@ void board_init(void) { NVIC_SetPriority(USB0_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY ); #endif +#ifdef TM4C123_H /* Reset USB */ SYSCTL->SRCR2 |= (1u << 16); @@ -99,7 +118,7 @@ void board_init(void) { /* USB IO Initialization */ SYSCTL->RCGCGPIO |= (1u << 3); - /* Let the clock stabilize */ + /* Let the clock stabilize */ while (!(SYSCTL->PRGPIO & (1u << 3))) {} /* USB IOs to Analog Mode */ @@ -107,16 +126,43 @@ void board_init(void) { GPIOD->DEN &= ~((1u << 4) | (1u << 5)); GPIOD->AMSEL |= ((1u << 4) | (1u << 5)); - uint8_t leds = (1 << LED_PIN_RED) | (1 << LED_PIN_BLUE) | (1 << LED_PIN_GREEN); - uint8_t dirmsk = (1 << LED_PIN_RED) | (1 << LED_PIN_BLUE) | (1 << LED_PIN_GREEN); +#else // TM4C129 + /* Reset USB */ + SYSCTL->SRUSB = 1; - /* Configure GPIO for board LED */ - initialize_board_led(LED_PORT, leds, dirmsk); + for (volatile uint8_t i = 0; i < 20; i++) {} + + SYSCTL->SRUSB = 0; - /* Configure GPIO for board switch */ - GPIOF->DIR &= ~(1 << BOARD_BTN); - GPIOF->PUR |= (1 << BOARD_BTN); - GPIOF->DEN |= (1 << BOARD_BTN); + /* Open the USB clock gate */ + SYSCTL->RCGCUSB = 1; + + /* Let the clock stabilize */ + while(!(SYSCTL->PRUSB & 1)) {} + + /* USB IO Initialization */ + SYSCTL->RCGCGPIO |= (1u << 10); + + /* Let the clock stabilize */ + while (!(SYSCTL->PRGPIO & (1u << 10))) {} + + /* USB IOs to Analog Mode */ + GPIOL->AFSEL &= ~((1u << 6) | (1u << 7)); + GPIOL->DEN &= ~((1u << 6) | (1u << 7)); + GPIOL->AMSEL |= ((1u << 6) | (1u << 7)); + + /* USB Clock Configuration */ + USB0->CC = 0x207; +#endif + + uint8_t leds = 1 << BOARD_LED_PIN; + uint8_t dirmsk = 1 << BOARD_LED_PIN; + + /* Configure GPIO for board button */ + board_button_init(BOARD_BTN_PORT, BOARD_BTN_Msk); + + /* Configure GPIO for board LED */ + board_led_init(LED_PORT, leds, dirmsk); /* Initialize board UART */ board_uart_init(); @@ -125,7 +171,7 @@ void board_init(void) { } void board_led_write(bool state) { - WriteGPIOPin(LED_PORT, (1 << LED_PIN_BLUE), state); + WriteGPIOPin(LED_PORT, (1 << BOARD_LED_PIN), state); } uint32_t board_button_read(void) { diff --git a/hw/bsp/tm4c/family.cmake b/hw/bsp/tm4c/family.cmake index 12f0448a3..41b8a597a 100644 --- a/hw/bsp/tm4c/family.cmake +++ b/hw/bsp/tm4c/family.cmake @@ -5,14 +5,14 @@ include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake) set(MCU_VARIANT tm4c${MCU_SUB_VARIANT}) set(MCU_VARIANT_UPPER TM4C${MCU_SUB_VARIANT}) -set(SDK_DIR ${TOP}/hw/mcu/ti/${MCU_VARIANT}xx) +set(SDK_DIR ${TOP}/hw/mcu/ti/tm4c) set(CMSIS_DIR ${TOP}/lib/CMSIS_5) # 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) -set(FAMILY_MCUS TM4C123 CACHE INTERNAL "") +set(FAMILY_MCUS TM4C CACHE INTERNAL "") #------------------------------------ # Startup & Linker script @@ -20,7 +20,7 @@ set(FAMILY_MCUS TM4C123 CACHE INTERNAL "") set(LD_FILE_Clang ${LD_FILE_GNU}) set(STARTUP_FILE_GNU ${SDK_DIR}/Source/GCC/${MCU_VARIANT}_startup.c) set(STARTUP_FILE_Clang ${STARTUP_FILE_GNU}) - +set(STARTUP_FILE_IAR ${SDK_DIR}/Source/IAR/${MCU_VARIANT}_startup.c) #------------------------------------ # Board Target #------------------------------------ @@ -29,7 +29,7 @@ function(family_add_board BOARD_TARGET) ${SDK_DIR}/Source/system_${MCU_VARIANT_UPPER}.c ) target_include_directories(${BOARD_TARGET} PUBLIC - ${SDK_DIR}/Include/${MCU_VARIANT_UPPER} + ${SDK_DIR}/Include ${CMSIS_DIR}/CMSIS/Core/Include ) @@ -41,7 +41,7 @@ endfunction() #------------------------------------ function(family_configure_example TARGET RTOS) family_configure_common(${TARGET} ${RTOS}) - family_add_tinyusb(${TARGET} OPT_MCU_TM4C123) + family_add_tinyusb(${TARGET} OPT_MCU_TM4C${MCU_SUB_VARIANT}) target_sources(${TARGET} PUBLIC ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/family.c @@ -71,13 +71,14 @@ function(family_configure_example TARGET RTOS) if (CMAKE_C_COMPILER_ID STREQUAL "GNU" OR CMAKE_C_COMPILER_ID STREQUAL "Clang") set_source_files_properties(${CMAKE_CURRENT_FUNCTION_LIST_DIR}/family.c PROPERTIES COMPILE_FLAGS "-Wno-missing-prototypes") + set_source_files_properties(${STARTUP_FILE_${CMAKE_C_COMPILER_ID}} PROPERTIES + SKIP_LINTING ON + COMPILE_OPTIONS -w) endif () - set_source_files_properties(${STARTUP_FILE_${CMAKE_C_COMPILER_ID}} PROPERTIES - SKIP_LINTING ON - COMPILE_OPTIONS -w) # Flashing family_add_bin_hex(${TARGET}) + family_flash_jlink(${TARGET}) family_flash_openocd(${TARGET}) family_flash_uniflash(${TARGET}) endfunction() diff --git a/hw/bsp/tm4c/family.mk b/hw/bsp/tm4c/family.mk index 76ae785b2..bc966d98e 100644 --- a/hw/bsp/tm4c/family.mk +++ b/hw/bsp/tm4c/family.mk @@ -4,11 +4,11 @@ CPU_CORE ?= cortex-m4 MCU_VARIANT = tm4c${MCU_SUB_VARIANT} MCU_VARIANT_UPPER = TM4C${MCU_SUB_VARIANT} -SDK_DIR = hw/mcu/ti/${MCU_VARIANT}xx +SDK_DIR = hw/mcu/ti/tm4c CFLAGS += \ -flto \ - -DCFG_TUSB_MCU=OPT_MCU_TM4C123 \ + -DCFG_TUSB_MCU=OPT_MCU_TM4C${MCU_SUB_VARIANT} \ -uvectors \ # mcu driver cause following warnings @@ -18,7 +18,7 @@ LDFLAGS_GCC += --specs=nosys.specs --specs=nano.specs INC += \ $(TOP)/lib/CMSIS_5/CMSIS/Core/Include \ - $(TOP)/$(SDK_DIR)/Include/${MCU_VARIANT_UPPER} \ + $(TOP)/$(SDK_DIR)/Include \ $(TOP)/$(BOARD_PATH) SRC_C += \ diff --git a/src/class/cdc/cdc_host.c b/src/class/cdc/cdc_host.c index f19c4a327..8f6dd7200 100644 --- a/src/class/cdc/cdc_host.c +++ b/src/class/cdc/cdc_host.c @@ -127,7 +127,7 @@ static bool acm_set_control_line_state(cdch_interface_t *p_cdc, tuh_xfer_cb_ static uint16_t const ftdi_vid_pid_list[][2] = {CFG_TUH_CDC_FTDI_VID_PID_LIST}; static uint16_t 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 bool ftdi_process_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_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); @@ -216,82 +216,84 @@ typedef struct { #define DRIVER_NAME_DECLARE(_str) #endif +// clang-format off // 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_set_config, - .request_complete = acm_internal_control_complete, - .set_control_line_state = acm_set_control_line_state, - .set_baudrate = acm_set_line_coding, - .set_data_format = acm_set_line_coding, - .set_line_coding = acm_set_line_coding, - DRIVER_NAME_DECLARE("ACM") + .vid_pid_list = NULL, + .vid_pid_count = 0, + .open = acm_open, + .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_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 { - .vid_pid_list = ftdi_vid_pid_list, - .vid_pid_count = TU_ARRAY_SIZE(ftdi_vid_pid_list), - .open = ftdi_open, - .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 = NULL, // 2 stage set line coding - DRIVER_NAME_DECLARE("FTDI") + .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_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 = NULL, // 2 stage set line coding + DRIVER_NAME_DECLARE("FTDI") }, #endif #if CFG_TUH_CDC_CP210X { - .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_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 = NULL, // 2 stage set line coding - DRIVER_NAME_DECLARE("CP210x") + .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_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 = NULL, // 2 stage set line coding + DRIVER_NAME_DECLARE("CP210x") }, #endif #if CFG_TUH_CDC_CH34X { - .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_set_config, - .request_complete = ch34x_internal_control_complete, + .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_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 = NULL, // 2 stage set line coding - DRIVER_NAME_DECLARE("CH34x") + .set_control_line_state = ch34x_set_modem_ctrl, + .set_baudrate = ch34x_set_baudrate, + .set_data_format = ch34x_set_data_format, + .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") + .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 }; +// clang-format on TU_VERIFY_STATIC(TU_ARRAY_SIZE(serial_drivers) == SERIAL_DRIVER_COUNT, "Serial driver count mismatch"); @@ -761,7 +763,8 @@ uint16_t cdch_open(uint8_t rhport, uint8_t daddr, const tusb_desc_interface_t *i 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) { const uint16_t drv_len = driver->open(daddr, itf_desc, max_len); - TU_LOG_DRV("[:%u:%u] CDCh %s open %s\r\n", daddr, itf_desc->bInterfaceNumber, driver->name, drv_len > 0 ? "OK" : "FAILED"); + TU_LOG_DRV("[:%u:%u] CDCh %s open %s\r\n", daddr, itf_desc->bInterfaceNumber, driver->name, + drv_len > 0 ? "OK" : "FAILED"); return drv_len; } } @@ -773,35 +776,16 @@ uint16_t cdch_open(uint8_t rhport, uint8_t daddr, const tusb_desc_interface_t *i return 0; } -bool cdch_set_config(uint8_t daddr, uint8_t itf_num) { - tusb_control_request_t request; - request.wIndex = tu_htole16((uint16_t) itf_num); - uint8_t const idx = tuh_cdc_itf_get_index(daddr, itf_num); - 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); - - 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; + p_cdc->mounted = true; tuh_cdc_mount_cb(idx); // Prepare for incoming data tu_edpt_stream_read_xfer(&p_cdc->stream.rx); } else { // clear the interface entry - p_cdc->daddr = 0; + p_cdc->daddr = 0; p_cdc->bInterfaceNumber = 0; } @@ -810,6 +794,33 @@ static void set_config_complete(cdch_interface_t *p_cdc, bool success) { usbh_driver_set_config_complete(p_cdc->daddr, p_cdc->bInterfaceNumber + itf_offset); } +bool cdch_set_config(uint8_t daddr, uint8_t itf_num) { + const uint8_t idx = tuh_cdc_itf_get_index(daddr, itf_num); + 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() + tusb_control_request_t request; + request.wIndex = tu_htole16((uint16_t)itf_num); + + tuh_xfer_t xfer; + xfer.daddr = daddr; + xfer.ep_addr = 0; + xfer.result = XFER_RESULT_SUCCESS; + xfer.setup = &request; + xfer.complete_cb = NULL; + xfer.buffer = NULL; + xfer.user_data = 0; // initial state 0 + + 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); + } + + return true; +} + 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,); @@ -1215,22 +1226,14 @@ static uint16_t ftdi_open(uint8_t daddr, const tusb_desc_interface_t *itf_desc, return drv_len; } -static bool ftdi_proccess_set_config(cdch_interface_t *p_cdc, tuh_xfer_t *xfer) { +static bool ftdi_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) { // 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_ASSERT(ftdi_determine_type(p_cdc)); TU_ATTR_FALLTHROUGH; case CONFIG_FTDI_WRITE_LATENCY: diff --git a/src/class/msc/msc_device.c b/src/class/msc/msc_device.c index 15bfafc35..3766e3a25 100644 --- a/src/class/msc/msc_device.c +++ b/src/class/msc/msc_device.c @@ -646,7 +646,11 @@ bool mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t break; } - TU_ASSERT(prepare_cbw(p_msc)); + if (!usbd_edpt_stalled(rhport, p_msc->ep_out)) { + TU_ASSERT(prepare_cbw(p_msc)); + } else { + p_msc->stage = MSC_STAGE_CMD; + } } else { // Any xfer ended here is considered unknown error, ignore it TU_LOG1(" Warning expect SCSI Status but received unknown data\r\n"); diff --git a/src/class/mtp/mtp_device.c b/src/class/mtp/mtp_device.c index 4942a105a..59096e476 100644 --- a/src/class/mtp/mtp_device.c +++ b/src/class/mtp/mtp_device.c @@ -92,8 +92,9 @@ typedef struct { uint8_t itf_num; uint8_t ep_in; uint8_t ep_out; - uint8_t ep_event; + uint8_t ep_event; + uint8_t ep_sz_fs; // Bulk Only Transfer (BOT) Protocol uint8_t phase; @@ -194,42 +195,47 @@ static bool prepare_new_command(mtpd_interface_t* p_mtp) { return usbd_edpt_xfer(p_mtp->rhport, p_mtp->ep_out, _mtpd_epbuf.buf, CFG_TUD_MTP_EP_BUFSIZE, false); } -static bool mtpd_data_xfer(mtp_container_info_t* p_container, uint8_t ep_addr) { - mtpd_interface_t* p_mtp = &_mtpd_itf; +bool tud_mtp_data_send(mtp_container_info_t *p_container) { + mtpd_interface_t *p_mtp = &_mtpd_itf; if (p_mtp->phase == MTP_PHASE_COMMAND) { // 1st data block: header + payload p_mtp->phase = MTP_PHASE_DATA; p_mtp->xferred_len = 0; + p_mtp->total_len = p_container->header->len; - if (tu_edpt_dir(ep_addr) == TUSB_DIR_IN) { - p_mtp->total_len = p_container->header->len; - p_container->header->type = MTP_CONTAINER_TYPE_DATA_BLOCK; - p_container->header->transaction_id = p_mtp->command.header.transaction_id; - p_mtp->io_header = *p_container->header; // save header for subsequent data - } else { - // OUT transfer: total length is at least max packet size - p_mtp->total_len = tu_max32(p_container->header->len, CFG_TUD_MTP_EP_BUFSIZE); - } - } else { - // subsequent data block: payload only - TU_ASSERT(p_mtp->phase == MTP_PHASE_DATA); + p_container->header->type = MTP_CONTAINER_TYPE_DATA_BLOCK; + p_container->header->transaction_id = p_mtp->command.header.transaction_id; + p_mtp->io_header = *p_container->header; // save header for subsequent data } - const uint16_t xact_len = (uint16_t) tu_min32(p_mtp->total_len - p_mtp->xferred_len, CFG_TUD_MTP_EP_BUFSIZE); + const uint16_t xact_len = (uint16_t)tu_min32(p_mtp->total_len - p_mtp->xferred_len, CFG_TUD_MTP_EP_BUFSIZE); + + TU_LOG_DRV(" MTP Data IN: xferred_len/total_len=%lu/%lu, xact_len=%u\r\n", p_mtp->xferred_len, p_mtp->total_len, + xact_len); if (xact_len) { - // already transferred all bytes in header's length. Application make an unnecessary extra call - TU_VERIFY(usbd_edpt_claim(p_mtp->rhport, ep_addr)); - TU_ASSERT(usbd_edpt_xfer(p_mtp->rhport, ep_addr, _mtpd_epbuf.buf, xact_len, false)); + TU_VERIFY(usbd_edpt_claim(p_mtp->rhport, p_mtp->ep_in)); + TU_ASSERT(usbd_edpt_xfer(p_mtp->rhport, p_mtp->ep_in, _mtpd_epbuf.buf, xact_len, false)); } return true; } -bool tud_mtp_data_send(mtp_container_info_t* p_container) { - return mtpd_data_xfer(p_container, _mtpd_itf.ep_in); -} +bool tud_mtp_data_receive(mtp_container_info_t *p_container) { + mtpd_interface_t *p_mtp = &_mtpd_itf; + if (p_mtp->phase == MTP_PHASE_COMMAND) { + // 1st data block: header + payload + p_mtp->phase = MTP_PHASE_DATA; + p_mtp->xferred_len = 0; + p_mtp->total_len = p_container->header->len; + } -bool tud_mtp_data_receive(mtp_container_info_t* p_container) { - return mtpd_data_xfer(p_container, _mtpd_itf.ep_out); + // up to buffer size since 1st packet (with header) may also contain payload + const uint16_t xact_len = CFG_TUD_MTP_EP_BUFSIZE; + + TU_LOG_DRV(" MTP Data OUT: xferred_len/total_len=%lu/%lu, xact_len=%u\r\n", p_mtp->xferred_len, p_mtp->total_len, + xact_len); + TU_VERIFY(usbd_edpt_claim(p_mtp->rhport, p_mtp->ep_out)); + TU_ASSERT(usbd_edpt_xfer(p_mtp->rhport, p_mtp->ep_out, _mtpd_epbuf.buf, xact_len, false)); + return true; } bool tud_mtp_response_send(mtp_container_info_t* p_container) { @@ -287,15 +293,20 @@ uint16_t mtpd_open(uint8_t rhport, tusb_desc_interface_t const* itf_desc, uint16 p_mtp->itf_num = itf_desc->bInterfaceNumber; // Open interrupt IN endpoint - const tusb_desc_endpoint_t* ep_desc = (const tusb_desc_endpoint_t*) tu_desc_next(itf_desc); - TU_ASSERT(ep_desc->bDescriptorType == TUSB_DESC_ENDPOINT && ep_desc->bmAttributes.xfer == TUSB_XFER_INTERRUPT, 0); - TU_ASSERT(usbd_edpt_open(rhport, ep_desc), 0); - p_mtp->ep_event = ep_desc->bEndpointAddress; + const tusb_desc_endpoint_t* ep_desc_int = (const tusb_desc_endpoint_t*) tu_desc_next(itf_desc); + TU_ASSERT(ep_desc_int->bDescriptorType == TUSB_DESC_ENDPOINT && ep_desc_int->bmAttributes.xfer == TUSB_XFER_INTERRUPT, 0); + TU_ASSERT(usbd_edpt_open(rhport, ep_desc_int), 0); + p_mtp->ep_event = ep_desc_int->bEndpointAddress; // Open endpoint pair - TU_ASSERT(usbd_open_edpt_pair(rhport, tu_desc_next(ep_desc), 2, TUSB_XFER_BULK, &p_mtp->ep_out, &p_mtp->ep_in), 0); + const tusb_desc_endpoint_t* ep_desc_bulk = (const tusb_desc_endpoint_t*) tu_desc_next(ep_desc_int); + TU_ASSERT(usbd_open_edpt_pair(rhport, (const uint8_t*)ep_desc_bulk, 2, TUSB_XFER_BULK, &p_mtp->ep_out, &p_mtp->ep_in), 0); TU_ASSERT(prepare_new_command(p_mtp), 0); + if (tud_speed_get() == TUSB_SPEED_FULL) { + p_mtp->ep_sz_fs = (uint8_t)tu_edpt_packet_size(ep_desc_bulk); + } + return mtpd_itf_size; } @@ -377,8 +388,8 @@ bool mtpd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t mtp_generic_container_t* p_container = (mtp_generic_container_t*) _mtpd_epbuf.buf; #if CFG_TUSB_DEBUG >= CFG_TUD_MTP_LOG_LEVEL - tu_lookup_find(&_mtp_op_table, p_mtp->command.header.code); - TU_LOG_DRV(" MTP %s: %s phase\r\n", (const char *) tu_lookup_find(&_mtp_op_table, p_mtp->command.header.code), + const uint16_t code = (p_mtp->phase == MTP_PHASE_COMMAND) ? p_container->header.code : p_mtp->command.header.code; + TU_LOG_DRV(" MTP %s: %s phase\r\n", (const char *) tu_lookup_find(&_mtp_op_table, code), _mtp_phase_str[p_mtp->phase]); #endif @@ -417,19 +428,35 @@ bool mtpd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t } case MTP_PHASE_DATA: { - const uint16_t bulk_mps = (tud_speed_get() == TUSB_SPEED_HIGH) ? 512 : 64; p_mtp->xferred_len += xferred_bytes; cb_data.total_xferred_bytes = p_mtp->xferred_len; - bool is_complete = false; - // complete if ZLP or short packet or total length reached - if (xferred_bytes == 0 || // ZLP - (xferred_bytes & (bulk_mps - 1)) || // short packet - p_mtp->xferred_len >= p_mtp->total_len) { // total length reached - is_complete = true; + const bool is_data_in = (ep_addr == p_mtp->ep_in); + // For IN endpoint, threshold is bulk max packet size + // For OUT endpoint, threshold is endpoint buffer size, since we always queue fixed size + uint16_t threshold; + if (is_data_in) { + threshold = (p_mtp->ep_sz_fs > 0) ? p_mtp->ep_sz_fs : 512; // full speed bulk if set + } else { + threshold = CFG_TUD_MTP_EP_BUFSIZE; + } + + // Check completion: ZLP, short packet, or total length reached + const bool is_complete = + (xferred_bytes == 0 || xferred_bytes < threshold || p_mtp->xferred_len >= p_mtp->total_len); + + TU_LOG_DRV(" MTP Data %s CB: xferred_bytes=%lu, xferred_len/total_len=%lu/%lu, is_complete=%d\r\n", + is_data_in ? "IN" : "OUT", xferred_bytes, p_mtp->xferred_len, p_mtp->total_len, is_complete ? 1 : 0); + + // Send/queue ZLP if packet is full-sized but transfer is complete + if (is_complete && xferred_bytes > 0 && !(xferred_bytes & (threshold - 1))) { + TU_LOG_DRV(" queue ZLP\r\n"); + TU_VERIFY(usbd_edpt_claim(p_mtp->rhport, ep_addr)); + TU_ASSERT(usbd_edpt_xfer(p_mtp->rhport, ep_addr, NULL, 0, false)); + return true; } - if (ep_addr == p_mtp->ep_in) { + if (is_data_in) { // Data In if (is_complete) { cb_data.io_container.header->len = sizeof(mtp_container_header_t); diff --git a/src/class/mtp/mtp_device.h b/src/class/mtp/mtp_device.h index a33f1dc08..6cce7efbb 100644 --- a/src/class/mtp/mtp_device.h +++ b/src/class/mtp/mtp_device.h @@ -18,7 +18,7 @@ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN0 + * 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. diff --git a/src/class/vendor/vendor_device.c b/src/class/vendor/vendor_device.c index b8e6fec6f..b917c8dc7 100644 --- a/src/class/vendor/vendor_device.c +++ b/src/class/vendor/vendor_device.c @@ -40,36 +40,33 @@ typedef struct { uint8_t rhport; uint8_t itf_num; + #if CFG_TUD_VENDOR_TXRX_BUFFERED /*------------- From this point, data is not cleared by bus reset -------------*/ - struct { - tu_edpt_stream_t tx; - tu_edpt_stream_t rx; - - #if CFG_TUD_VENDOR_TX_BUFSIZE > 0 - uint8_t tx_ff_buf[CFG_TUD_VENDOR_TX_BUFSIZE]; - #endif - - #if CFG_TUD_VENDOR_RX_BUFSIZE > 0 - uint8_t rx_ff_buf[CFG_TUD_VENDOR_RX_BUFSIZE]; + tu_edpt_stream_t tx_stream; + tu_edpt_stream_t rx_stream; + uint8_t tx_ff_buf[CFG_TUD_VENDOR_TX_BUFSIZE]; + uint8_t rx_ff_buf[CFG_TUD_VENDOR_RX_BUFSIZE]; + #else + uint8_t ep_in; + uint8_t ep_out; + uint16_t ep_in_mps; + uint16_t ep_out_mps; #endif - } stream; } vendord_interface_t; -#define ITF_MEM_RESET_SIZE (offsetof(vendord_interface_t, itf_num) + sizeof(((vendord_interface_t *)0)->itf_num)) + #if CFG_TUD_VENDOR_TXRX_BUFFERED + #define ITF_MEM_RESET_SIZE (offsetof(vendord_interface_t, itf_num) + TU_FIELD_SIZE(vendord_interface_t, itf_num)) + #else + #define ITF_MEM_RESET_SIZE sizeof(vendord_interface_t) + #endif static vendord_interface_t _vendord_itf[CFG_TUD_VENDOR]; -#if CFG_TUD_EDPT_DEDICATED_HWFIFO == 0 || CFG_TUD_VENDOR_RX_BUFSIZE == 0 + // Skip local EP buffer if dedicated hw FIFO is supported or no fifo mode + #if CFG_TUD_EDPT_DEDICATED_HWFIFO == 0 || !CFG_TUD_VENDOR_TXRX_BUFFERED typedef struct { - // Skip local EP buffer if dedicated hw FIFO is supported - #if CFG_TUD_EDPT_DEDICATED_HWFIFO == 0 || CFG_TUD_VENDOR_RX_BUFSIZE == 0 TUD_EPBUF_DEF(epout, CFG_TUD_VENDOR_EPSIZE); - #endif - - // Skip local EP buffer if dedicated hw FIFO is supported - #if CFG_TUD_EDPT_DEDICATED_HWFIFO == 0 TUD_EPBUF_DEF(epin, CFG_TUD_VENDOR_EPSIZE); - #endif } vendord_epbuf_t; CFG_TUD_MEM_SECTION static vendord_epbuf_t _vendord_epbuf[CFG_TUD_VENDOR]; @@ -78,7 +75,6 @@ CFG_TUD_MEM_SECTION static vendord_epbuf_t _vendord_epbuf[CFG_TUD_VENDOR]; //--------------------------------------------------------------------+ // Weak stubs: invoked if no strong implementation is available //--------------------------------------------------------------------+ - TU_ATTR_WEAK void tud_vendor_rx_cb(uint8_t idx, const uint8_t *buffer, uint32_t bufsize) { (void)idx; (void)buffer; @@ -93,40 +89,44 @@ TU_ATTR_WEAK void tud_vendor_tx_cb(uint8_t idx, uint32_t sent_bytes) { //-------------------------------------------------------------------- // Application API //-------------------------------------------------------------------- - bool tud_vendor_n_mounted(uint8_t idx) { TU_VERIFY(idx < CFG_TUD_VENDOR); vendord_interface_t *p_itf = &_vendord_itf[idx]; - return p_itf->stream.rx.ep_addr || p_itf->stream.tx.ep_addr; + + #if CFG_TUD_VENDOR_TXRX_BUFFERED + return (p_itf->rx_stream.ep_addr != 0) || (p_itf->tx_stream.ep_addr != 0); + #else + return (p_itf->ep_out != 0) || (p_itf->ep_in != 0); + #endif } //--------------------------------------------------------------------+ // Read API //--------------------------------------------------------------------+ -#if CFG_TUD_VENDOR_RX_BUFSIZE > 0 + #if CFG_TUD_VENDOR_TXRX_BUFFERED uint32_t tud_vendor_n_available(uint8_t idx) { TU_VERIFY(idx < CFG_TUD_VENDOR, 0); vendord_interface_t *p_itf = &_vendord_itf[idx]; - return tu_edpt_stream_read_available(&p_itf->stream.rx); + return tu_edpt_stream_read_available(&p_itf->rx_stream); } bool tud_vendor_n_peek(uint8_t idx, uint8_t *u8) { TU_VERIFY(idx < CFG_TUD_VENDOR); vendord_interface_t *p_itf = &_vendord_itf[idx]; - return tu_edpt_stream_peek(&p_itf->stream.rx, u8); + return tu_edpt_stream_peek(&p_itf->rx_stream, u8); } uint32_t tud_vendor_n_read(uint8_t idx, void *buffer, uint32_t bufsize) { TU_VERIFY(idx < CFG_TUD_VENDOR, 0); vendord_interface_t *p_itf = &_vendord_itf[idx]; - return tu_edpt_stream_read(&p_itf->stream.rx, buffer, bufsize); + return tu_edpt_stream_read(&p_itf->rx_stream, buffer, bufsize); } void tud_vendor_n_read_flush(uint8_t idx) { TU_VERIFY(idx < CFG_TUD_VENDOR, ); vendord_interface_t *p_itf = &_vendord_itf[idx]; - tu_edpt_stream_clear(&p_itf->stream.rx); - tu_edpt_stream_read_xfer(&p_itf->stream.rx); + tu_edpt_stream_clear(&p_itf->rx_stream); + tu_edpt_stream_read_xfer(&p_itf->rx_stream); } #endif @@ -134,9 +134,17 @@ void tud_vendor_n_read_flush(uint8_t idx) { bool tud_vendor_n_read_xfer(uint8_t idx) { TU_VERIFY(idx < CFG_TUD_VENDOR); vendord_interface_t *p_itf = &_vendord_itf[idx]; - return tu_edpt_stream_read_xfer(&p_itf->stream.rx); + + #if CFG_TUD_VENDOR_TXRX_BUFFERED + return tu_edpt_stream_read_xfer(&p_itf->rx_stream); + + #else + // Non-FIFO mode + TU_VERIFY(usbd_edpt_claim(p_itf->rhport, p_itf->ep_out)); + return usbd_edpt_xfer(p_itf->rhport, p_itf->ep_out, _vendord_epbuf[idx].epout, CFG_TUD_VENDOR_EPSIZE, false); + #endif } -#endif + #endif //--------------------------------------------------------------------+ @@ -145,26 +153,45 @@ bool tud_vendor_n_read_xfer(uint8_t idx) { uint32_t tud_vendor_n_write(uint8_t idx, const void *buffer, uint32_t bufsize) { TU_VERIFY(idx < CFG_TUD_VENDOR, 0); vendord_interface_t *p_itf = &_vendord_itf[idx]; - return tu_edpt_stream_write(&p_itf->stream.tx, buffer, (uint16_t)bufsize); + + #if CFG_TUD_VENDOR_TXRX_BUFFERED + return tu_edpt_stream_write(&p_itf->tx_stream, buffer, (uint16_t)bufsize); + + #else + // non-fifo mode: direct transfer + TU_VERIFY(usbd_edpt_claim(p_itf->rhport, p_itf->ep_in), 0); + const uint32_t xact_len = tu_min32(bufsize, CFG_TUD_VENDOR_EPSIZE); + memcpy(_vendord_epbuf[idx].epin, buffer, xact_len); + TU_ASSERT(usbd_edpt_xfer(p_itf->rhport, p_itf->ep_in, _vendord_epbuf[idx].epin, (uint16_t)xact_len, false), 0); + return xact_len; + #endif } -#if CFG_TUD_VENDOR_TX_BUFSIZE > 0 -uint32_t tud_vendor_n_write_flush(uint8_t idx) { +uint32_t tud_vendor_n_write_available(uint8_t idx) { TU_VERIFY(idx < CFG_TUD_VENDOR, 0); vendord_interface_t *p_itf = &_vendord_itf[idx]; - return tu_edpt_stream_write_xfer(&p_itf->stream.tx); + + #if CFG_TUD_VENDOR_TXRX_BUFFERED + return tu_edpt_stream_write_available(&p_itf->tx_stream); + + #else + // Non-FIFO mode + TU_VERIFY(p_itf->ep_in > 0, 0); // must be opened + return usbd_edpt_busy(p_itf->rhport, p_itf->ep_in) ? 0 : CFG_TUD_VENDOR_EPSIZE; + #endif } -uint32_t tud_vendor_n_write_available(uint8_t idx) { + #if CFG_TUD_VENDOR_TXRX_BUFFERED +uint32_t tud_vendor_n_write_flush(uint8_t idx) { TU_VERIFY(idx < CFG_TUD_VENDOR, 0); vendord_interface_t *p_itf = &_vendord_itf[idx]; - return tu_edpt_stream_write_available(&p_itf->stream.tx); + return tu_edpt_stream_write_xfer(&p_itf->tx_stream); } bool tud_vendor_n_write_clear(uint8_t idx) { TU_VERIFY(idx < CFG_TUD_VENDOR, 0); vendord_interface_t *p_itf = &_vendord_itf[idx]; - tu_edpt_stream_clear(&p_itf->stream.tx); + tu_edpt_stream_clear(&p_itf->tx_stream); return true; } #endif @@ -175,48 +202,37 @@ bool tud_vendor_n_write_clear(uint8_t idx) { void vendord_init(void) { tu_memclr(_vendord_itf, sizeof(_vendord_itf)); - for(uint8_t i=0; i<CFG_TUD_VENDOR; i++) { - vendord_interface_t* p_itf = &_vendord_itf[i]; + #if CFG_TUD_VENDOR_TXRX_BUFFERED + for (uint8_t i = 0; i < CFG_TUD_VENDOR; i++) { + vendord_interface_t *p_itf = &_vendord_itf[i]; - #if CFG_TUD_EDPT_DEDICATED_HWFIFO - #if CFG_TUD_VENDOR_RX_BUFSIZE == 0 // non-fifo rx still need ep buffer - uint8_t *epout_buf = _vendord_epbuf[i].epout; - #else + #if CFG_TUD_EDPT_DEDICATED_HWFIFO uint8_t *epout_buf = NULL; - #endif - - uint8_t *epin_buf = NULL; - #else + uint8_t *epin_buf = NULL; + #else uint8_t *epout_buf = _vendord_epbuf[i].epout; uint8_t *epin_buf = _vendord_epbuf[i].epin; - #endif - - #if CFG_TUD_VENDOR_RX_BUFSIZE > 0 - uint8_t *rx_ff_buf = p_itf->stream.rx_ff_buf; - #else - uint8_t *rx_ff_buf = NULL; - #endif + #endif - tu_edpt_stream_init(&p_itf->stream.rx, false, false, false, rx_ff_buf, CFG_TUD_VENDOR_RX_BUFSIZE, epout_buf, + uint8_t *rx_ff_buf = p_itf->rx_ff_buf; + tu_edpt_stream_init(&p_itf->rx_stream, false, false, false, rx_ff_buf, CFG_TUD_VENDOR_RX_BUFSIZE, epout_buf, CFG_TUD_VENDOR_EPSIZE); - #if CFG_TUD_VENDOR_TX_BUFSIZE > 0 - uint8_t *tx_ff_buf = p_itf->stream.tx_ff_buf; - #else - uint8_t *tx_ff_buf = NULL; - #endif - - tu_edpt_stream_init(&p_itf->stream.tx, false, true, false, tx_ff_buf, CFG_TUD_VENDOR_TX_BUFSIZE, epin_buf, + uint8_t *tx_ff_buf = p_itf->tx_ff_buf; + tu_edpt_stream_init(&p_itf->tx_stream, false, true, false, tx_ff_buf, CFG_TUD_VENDOR_TX_BUFSIZE, epin_buf, CFG_TUD_VENDOR_EPSIZE); } + #endif } bool vendord_deinit(void) { - for(uint8_t i=0; i<CFG_TUD_VENDOR; i++) { - vendord_interface_t* p_itf = &_vendord_itf[i]; - tu_edpt_stream_deinit(&p_itf->stream.rx); - tu_edpt_stream_deinit(&p_itf->stream.tx); + #if CFG_TUD_VENDOR_TXRX_BUFFERED + for (uint8_t i = 0; i < CFG_TUD_VENDOR; i++) { + vendord_interface_t *p_itf = &_vendord_itf[i]; + tu_edpt_stream_deinit(&p_itf->rx_stream); + tu_edpt_stream_deinit(&p_itf->tx_stream); } + #endif return true; } @@ -227,11 +243,12 @@ void vendord_reset(uint8_t rhport) { vendord_interface_t* p_itf = &_vendord_itf[i]; tu_memclr(p_itf, ITF_MEM_RESET_SIZE); - tu_edpt_stream_clear(&p_itf->stream.rx); - tu_edpt_stream_close(&p_itf->stream.rx); - - tu_edpt_stream_clear(&p_itf->stream.tx); - tu_edpt_stream_close(&p_itf->stream.tx); + #if CFG_TUD_VENDOR_TXRX_BUFFERED + tu_edpt_stream_clear(&p_itf->rx_stream); + tu_edpt_stream_close(&p_itf->rx_stream); + tu_edpt_stream_clear(&p_itf->tx_stream); + tu_edpt_stream_close(&p_itf->tx_stream); + #endif } } @@ -241,13 +258,25 @@ static uint8_t find_vendor_itf(uint8_t ep_addr) { const vendord_interface_t *p_vendor = &_vendord_itf[idx]; if (ep_addr == 0) { // find unused: require both ep == 0 - if (p_vendor->stream.rx.ep_addr == 0 && p_vendor->stream.tx.ep_addr == 0) { + #if CFG_TUD_VENDOR_TXRX_BUFFERED + if (p_vendor->rx_stream.ep_addr == 0 && p_vendor->tx_stream.ep_addr == 0) { return idx; } - } else if (ep_addr == p_vendor->stream.rx.ep_addr || ep_addr == p_vendor->stream.tx.ep_addr) { - return idx; + #else + if (p_vendor->ep_out == 0 && p_vendor->ep_in == 0) { + return idx; + } + #endif } else { - // nothing to do + #if CFG_TUD_VENDOR_TXRX_BUFFERED + if (ep_addr == p_vendor->rx_stream.ep_addr || ep_addr == p_vendor->tx_stream.ep_addr) { + return idx; + } + #else + if (ep_addr == p_vendor->ep_out || ep_addr == p_vendor->ep_in) { + return idx; + } + #endif } } return 0xff; @@ -273,28 +302,39 @@ uint16_t vendord_open(uint8_t rhport, const tusb_desc_interface_t *desc_itf, uin const tusb_desc_endpoint_t* desc_ep = (const tusb_desc_endpoint_t*) p_desc; TU_ASSERT(usbd_edpt_open(rhport, desc_ep)); - // open endpoint stream, skip if already opened (multiple IN/OUT endpoints) + #if CFG_TUD_VENDOR_TXRX_BUFFERED + // open endpoint stream if (tu_edpt_dir(desc_ep->bEndpointAddress) == TUSB_DIR_IN) { - tu_edpt_stream_t *stream_tx = &p_vendor->stream.tx; - if (stream_tx->ep_addr == 0) { - tu_edpt_stream_open(stream_tx, rhport, desc_ep); - tu_edpt_stream_write_xfer(stream_tx); // flush pending data - } + tu_edpt_stream_t *tx_stream = &p_vendor->tx_stream; + tu_edpt_stream_open(tx_stream, rhport, desc_ep); + tu_edpt_stream_write_xfer(tx_stream); // flush pending data } else { - tu_edpt_stream_t *stream_rx = &p_vendor->stream.rx; - if (stream_rx->ep_addr == 0) { - tu_edpt_stream_open(stream_rx, rhport, desc_ep); - #if CFG_TUD_VENDOR_RX_MANUAL_XFER == 0 - TU_ASSERT(tu_edpt_stream_read_xfer(stream_rx) > 0, 0); // prepare for incoming data - #endif - } + tu_edpt_stream_t *rx_stream = &p_vendor->rx_stream; + tu_edpt_stream_open(rx_stream, rhport, desc_ep); + #if CFG_TUD_VENDOR_RX_MANUAL_XFER == 0 + TU_ASSERT(tu_edpt_stream_read_xfer(rx_stream) > 0, 0); // prepare for incoming data + #endif + } + #else + // Non-FIFO mode: store endpoint info + if (tu_edpt_dir(desc_ep->bEndpointAddress) == TUSB_DIR_IN) { + p_vendor->ep_in = desc_ep->bEndpointAddress; + p_vendor->ep_in_mps = tu_edpt_packet_size(desc_ep); + } else { + p_vendor->ep_out = desc_ep->bEndpointAddress; + p_vendor->ep_out_mps = tu_edpt_packet_size(desc_ep); + #if CFG_TUD_VENDOR_RX_MANUAL_XFER == 0 + // Prepare for incoming data + TU_ASSERT(usbd_edpt_xfer(rhport, p_vendor->ep_out, _vendord_epbuf[idx].epout, CFG_TUD_VENDOR_EPSIZE, false), 0); + #endif } + #endif } p_desc = tu_desc_next(p_desc); } - return (uint16_t) ((uintptr_t) p_desc - (uintptr_t) desc_itf); + return (uint16_t)((uintptr_t)p_desc - (uintptr_t)desc_itf); } bool vendord_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes) { @@ -304,34 +344,36 @@ bool vendord_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint TU_VERIFY(idx < CFG_TUD_VENDOR); vendord_interface_t *p_vendor = &_vendord_itf[idx]; - if (ep_addr == p_vendor->stream.rx.ep_addr) { - #if CFG_TUD_VENDOR_RX_BUFSIZE - // Received new data: put into stream's fifo - tu_edpt_stream_read_xfer_complete(&p_vendor->stream.rx, xferred_bytes); - #endif - - // invoke callback - #if CFG_TUD_VENDOR_RX_BUFSIZE == 0 - tud_vendor_rx_cb(idx, p_vendor->stream.rx.ep_buf, xferred_bytes); - #else +#if CFG_TUD_VENDOR_TXRX_BUFFERED + if (ep_addr == p_vendor->rx_stream.ep_addr) { + // Put received data to FIFO + tu_edpt_stream_read_xfer_complete(&p_vendor->rx_stream, xferred_bytes); tud_vendor_rx_cb(idx, NULL, 0); - #endif - - #if CFG_TUD_VENDOR_RX_MANUAL_XFER == 0 - tu_edpt_stream_read_xfer(&p_vendor->stream.rx); // prepare next data - #endif - } else if (ep_addr == p_vendor->stream.tx.ep_addr) { + #if CFG_TUD_VENDOR_RX_MANUAL_XFER == 0 + tu_edpt_stream_read_xfer(&p_vendor->rx_stream); // prepare next data + #endif + } else if (ep_addr == p_vendor->tx_stream.ep_addr) { // Send complete tud_vendor_tx_cb(idx, (uint16_t)xferred_bytes); - #if CFG_TUD_VENDOR_TX_BUFSIZE > 0 // try to send more if possible - if (0 == tu_edpt_stream_write_xfer(&p_vendor->stream.tx)) { + if (0 == tu_edpt_stream_write_xfer(&p_vendor->tx_stream)) { // 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(&p_vendor->stream.tx, xferred_bytes); + tu_edpt_stream_write_zlp_if_needed(&p_vendor->tx_stream, xferred_bytes); } - #endif } + #else + if (ep_addr == p_vendor->ep_out) { + // Non-FIFO mode: invoke callback with buffer + tud_vendor_rx_cb(idx, _vendord_epbuf[idx].epout, xferred_bytes); + #if CFG_TUD_VENDOR_RX_MANUAL_XFER == 0 + usbd_edpt_xfer(rhport, p_vendor->ep_out, _vendord_epbuf[idx].epout, CFG_TUD_VENDOR_EPSIZE, false); + #endif + } else if (ep_addr == p_vendor->ep_in) { + // Send complete + tud_vendor_tx_cb(idx, (uint16_t)xferred_bytes); + } + #endif return true; } diff --git a/src/class/vendor/vendor_device.h b/src/class/vendor/vendor_device.h index c3de4c49d..101765bb1 100644 --- a/src/class/vendor/vendor_device.h +++ b/src/class/vendor/vendor_device.h @@ -50,8 +50,14 @@ extern "C" { #define CFG_TUD_VENDOR_TX_BUFSIZE 64 #endif +// Vendor is buffered (FIFO mode) if both TX and RX buffers are configured +// If either is 0, vendor operates in non-buffered (direct transfer) mode +#ifndef CFG_TUD_VENDOR_TXRX_BUFFERED + #define CFG_TUD_VENDOR_TXRX_BUFFERED ((CFG_TUD_VENDOR_RX_BUFSIZE > 0) && (CFG_TUD_VENDOR_TX_BUFSIZE > 0)) +#endif + // Application will manually schedule RX transfer. This can be useful when using with non-fifo (buffered) mode -// i.e. CFG_TUD_VENDOR_RX_BUFSIZE = 0 +// i.e. CFG_TUD_VENDOR_TXRX_BUFFERED = 0 #ifndef CFG_TUD_VENDOR_RX_MANUAL_XFER #define CFG_TUD_VENDOR_RX_MANUAL_XFER 0 #endif @@ -63,7 +69,8 @@ extern "C" { // Return whether the vendor interface is mounted bool tud_vendor_n_mounted(uint8_t idx); -#if CFG_TUD_VENDOR_RX_BUFSIZE > 0 +//------------- RX -------------// +#if CFG_TUD_VENDOR_TXRX_BUFFERED // Return number of available bytes for reading uint32_t tud_vendor_n_available(uint8_t idx); @@ -82,16 +89,17 @@ void tud_vendor_n_read_flush(uint8_t idx); bool tud_vendor_n_read_xfer(uint8_t idx); #endif +//------------- TX -------------// // Write to TX FIFO. This can be buffered and not sent immediately unless buffered bytes >= USB endpoint size uint32_t tud_vendor_n_write(uint8_t idx, const void *buffer, uint32_t bufsize); -#if CFG_TUD_VENDOR_TX_BUFSIZE > 0 +// Return number of bytes available for writing in TX FIFO (or endpoint if non-buffered) +uint32_t tud_vendor_n_write_available(uint8_t idx); + +#if CFG_TUD_VENDOR_TXRX_BUFFERED // Force sending buffered data, return number of bytes sent uint32_t tud_vendor_n_write_flush(uint8_t idx); -// Return number of bytes available for writing in TX FIFO -uint32_t tud_vendor_n_write_available(uint8_t idx); - // Clear the transmit FIFO bool tud_vendor_n_write_clear(uint8_t idx); #endif @@ -111,7 +119,7 @@ TU_ATTR_ALWAYS_INLINE static inline bool tud_vendor_mounted(void) { return tud_vendor_n_mounted(0); } -#if CFG_TUD_VENDOR_RX_BUFSIZE > 0 +#if CFG_TUD_VENDOR_TXRX_BUFFERED TU_ATTR_ALWAYS_INLINE static inline uint32_t tud_vendor_available(void) { return tud_vendor_n_available(0); } @@ -127,6 +135,14 @@ TU_ATTR_ALWAYS_INLINE static inline uint32_t tud_vendor_read(void *buffer, uint3 TU_ATTR_ALWAYS_INLINE static inline void tud_vendor_read_flush(void) { tud_vendor_n_read_flush(0); } + +TU_ATTR_ALWAYS_INLINE static inline uint32_t tud_vendor_write_flush(void) { + return tud_vendor_n_write_flush(0); +} + +TU_ATTR_ALWAYS_INLINE static inline bool tud_vendor_write_clear(void) { + return tud_vendor_n_write_clear(0); +} #endif #if CFG_TUD_VENDOR_RX_MANUAL_XFER @@ -143,20 +159,10 @@ TU_ATTR_ALWAYS_INLINE static inline uint32_t tud_vendor_write_str(const char *st return tud_vendor_n_write_str(0, str); } -#if CFG_TUD_VENDOR_TX_BUFSIZE > 0 -TU_ATTR_ALWAYS_INLINE static inline uint32_t tud_vendor_write_flush(void) { - return tud_vendor_n_write_flush(0); -} - TU_ATTR_ALWAYS_INLINE static inline uint32_t tud_vendor_write_available(void) { return tud_vendor_n_write_available(0); } -TU_ATTR_ALWAYS_INLINE static inline bool tud_vendor_write_clear(void) { - return tud_vendor_n_write_clear(0); -} -#endif - // backward compatible #define tud_vendor_flush() tud_vendor_write_flush() @@ -165,8 +171,8 @@ TU_ATTR_ALWAYS_INLINE static inline bool tud_vendor_write_clear(void) { //--------------------------------------------------------------------+ // Invoked when received new data. -// - CFG_TUD_VENDOR_RX_BUFSIZE > 0; buffer and bufsize must not be used (both NULL,0) since data is in RX FIFO -// - CFG_TUD_VENDOR_RX_BUFSIZE = 0: Buffer and bufsize are valid +// - CFG_TUD_VENDOR_TXRX_BUFFERED = 1: buffer and bufsize must not be used (both NULL,0) since data is in RX FIFO +// - CFG_TUD_VENDOR_TXRX_BUFFERED = 0: Buffer and bufsize are valid void tud_vendor_rx_cb(uint8_t idx, const uint8_t *buffer, uint32_t bufsize); // Invoked when tx transfer is finished diff --git a/src/class/video/video_device.h b/src/class/video/video_device.h index f14555e4f..2750bb2fb 100644 --- a/src/class/video/video_device.h +++ b/src/class/video/video_device.h @@ -99,8 +99,7 @@ int tud_video_commit_cb(uint_fast8_t ctl_idx, uint_fast8_t stm_idx, * @param[in] stm_idx Destination streaming interface index * @param[out] payload_buf Payload storage buffer (target buffer for requested data) * @param[in] payload_size Size of payload_buf (requested data size) - * @param[in] offset Current byte offset relative to given bufsize from tud_video_n_frame_xfer (framesize) - * @return video_error_code_t */ + * @param[in] offset Current byte offset relative to given bufsize from tud_video_n_frame_xfer (framesize) */ void tud_video_prepare_payload_cb(uint_fast8_t ctl_idx, uint_fast8_t stm_idx, tud_video_payload_request_t* request); //--------------------------------------------------------------------+ diff --git a/src/common/tusb_fifo.c b/src/common/tusb_fifo.c index a92435912..9f188f296 100644 --- a/src/common/tusb_fifo.c +++ b/src/common/tusb_fifo.c @@ -33,7 +33,7 @@ // Suppress IAR warning // Warning[Pa082]: undefined behavior: the order of volatile accesses is undefined in this statement #if defined(__ICCARM__) -#pragma diag_suppress = Pa082 + #pragma diag_suppress = Pa082 #endif #if OSAL_MUTEX_REQUIRED @@ -110,8 +110,9 @@ void tu_fifo_set_overwritable(tu_fifo_t *f, bool overwritable) { } //--------------------------------------------------------------------+ -// Pull & Push -// copy data to/from fifo without updating read/write pointers +// Hardware FIFO API +// Support different data access width and address increment scheme +// Can support multiple i.e both 16 and 32-bit data access if needed //--------------------------------------------------------------------+ #if CFG_TUSB_FIFO_HWFIFO_API #if CFG_TUSB_FIFO_HWFIFO_ADDR_STRIDE @@ -122,18 +123,31 @@ void tu_fifo_set_overwritable(tu_fifo_t *f, bool overwritable) { #define HWFIFO_ADDR_NEXT(_hwfifo, _const) HWFIFO_ADDR_NEXT_N(_hwfifo, _const, CFG_TUSB_FIFO_HWFIFO_ADDR_STRIDE) +//------------- Write -------------// #ifndef CFG_TUSB_FIFO_HWFIFO_CUSTOM_WRITE -static inline void stride_write(volatile void *hwfifo, const void *src, uint8_t data_stride) { +TU_ATTR_ALWAYS_INLINE static inline void stride_write(volatile void *hwfifo, const void *src, uint8_t data_stride) { + (void)data_stride; // possible unused #if CFG_TUSB_FIFO_HWFIFO_DATA_STRIDE & 4 - if (data_stride == 4) { + #if CFG_TUSB_FIFO_HWFIFO_DATA_STRIDE != 4 + if (data_stride == 4) + #endif + { *((volatile uint32_t *)hwfifo) = tu_unaligned_read32(src); } - #endif - #if CFG_TUSB_FIFO_HWFIFO_DATA_STRIDE & 2 - if (data_stride == 2) { + #endif + + #if CFG_TUSB_FIFO_HWFIFO_DATA_STRIDE & 2 + #if CFG_TUSB_FIFO_HWFIFO_DATA_STRIDE != 2 + if (data_stride == 2) + #endif + { *((volatile uint16_t *)hwfifo) = tu_unaligned_read16(src); } - #endif + #endif + + #if CFG_TUSB_FIFO_HWFIFO_DATA_STRIDE == 1 + *((volatile uint8_t *)hwfifo) = *(const uint8_t *)src; + #endif } // Copy from fifo to fixed address buffer (usually a tx register) with TU_FIFO_FIXED_ADDR_RW32 mode @@ -147,7 +161,8 @@ void tu_hwfifo_write(volatile void *hwfifo, const uint8_t *src, uint16_t len, co HWFIFO_ADDR_NEXT(hwfifo, ); } - #ifdef CFG_TUSB_FIFO_HWFIFO_DATA_ODD_16BIT_ACCESS + #if CFG_TUSB_FIFO_HWFIFO_DATA_STRIDE > 1 + #ifdef CFG_TUSB_FIFO_HWFIFO_DATA_ODD_16BIT_ACCESS // 16-bit access is allowed for odd bytes if (len >= 2) { *((volatile uint16_t *)hwfifo) = tu_unaligned_read16(src); @@ -155,16 +170,16 @@ void tu_hwfifo_write(volatile void *hwfifo, const uint8_t *src, uint16_t len, co len -= 2; HWFIFO_ADDR_NEXT_N(hwfifo, , 2); } - #endif + #endif - #ifdef CFG_TUSB_FIFO_HWFIFO_DATA_ODD_8BIT_ACCESS + #ifdef CFG_TUSB_FIFO_HWFIFO_DATA_ODD_8BIT_ACCESS // 8-bit access is allowed for odd bytes while (len > 0) { *((volatile uint8_t *)hwfifo) = *src++; len--; HWFIFO_ADDR_NEXT_N(hwfifo, , 1); } - #else + #else // Write odd bytes i.e 1 byte for 16 bit or 1-3 bytes for 32 bit if (len > 0) { @@ -173,13 +188,16 @@ void tu_hwfifo_write(volatile void *hwfifo, const uint8_t *src, uint16_t len, co stride_write(hwfifo, &tmp, data_stride); HWFIFO_ADDR_NEXT(hwfifo, ); } + #endif #endif } #endif +//------------- Read -------------// #ifndef CFG_TUSB_FIFO_HWFIFO_CUSTOM_READ -static inline void stride_read(const volatile void *hwfifo, void *dest, uint8_t data_stride) { +TU_ATTR_ALWAYS_INLINE static inline void stride_read(const volatile void *hwfifo, void *dest, uint8_t data_stride) { (void)data_stride; // possible unused + #if CFG_TUSB_FIFO_HWFIFO_DATA_STRIDE & 4 #if CFG_TUSB_FIFO_HWFIFO_DATA_STRIDE != 4 if (data_stride == 4) @@ -197,6 +215,10 @@ static inline void stride_read(const volatile void *hwfifo, void *dest, uint8_t tu_unaligned_write16(dest, *((const volatile uint16_t *)hwfifo)); } #endif + + #if CFG_TUSB_FIFO_HWFIFO_DATA_STRIDE == 1 + *(uint8_t *)dest = *((const volatile uint8_t *)hwfifo); + #endif } void tu_hwfifo_read(const volatile void *hwfifo, uint8_t *dest, uint16_t len, const tu_hwfifo_access_t *access_mode) { @@ -209,7 +231,8 @@ void tu_hwfifo_read(const volatile void *hwfifo, uint8_t *dest, uint16_t len, co HWFIFO_ADDR_NEXT(hwfifo, const); } - #ifdef CFG_TUSB_FIFO_HWFIFO_DATA_ODD_16BIT_ACCESS + #if CFG_TUSB_FIFO_HWFIFO_DATA_STRIDE > 1 + #ifdef CFG_TUSB_FIFO_HWFIFO_DATA_ODD_16BIT_ACCESS // 16-bit access is allowed for odd bytes if (len >= 2) { tu_unaligned_write16(dest, *((const volatile uint16_t *)hwfifo)); @@ -235,6 +258,7 @@ void tu_hwfifo_read(const volatile void *hwfifo, uint8_t *dest, uint16_t len, co HWFIFO_ADDR_NEXT(hwfifo, const); } #endif + #endif } #endif @@ -251,7 +275,11 @@ static void hwff_push_n(const tu_fifo_t *f, const void *app_buf, uint16_t n, uin tu_hwfifo_read(hwfifo, ff_buf, n, access_mode); } else { // Wrap around case - + #if CFG_TUSB_FIFO_HWFIFO_DATA_STRIDE == 1 + tu_hwfifo_read(hwfifo, ff_buf, lin_bytes, access_mode); // linear part + HWFIFO_ADDR_NEXT_N(hwfifo, const, lin_bytes); + tu_hwfifo_read(hwfifo, f->buffer, wrap_bytes, access_mode); // wrapped part + #else // Write full words to linear part of buffer const uint8_t data_stride = access_mode->data_stride; const uint32_t odd_mask = data_stride - 1; @@ -286,6 +314,7 @@ static void hwff_push_n(const tu_fifo_t *f, const void *app_buf, uint16_t n, uin if (wrap_bytes > 0) { tu_hwfifo_read(hwfifo, ff_buf, wrap_bytes, access_mode); } + #endif } } @@ -303,11 +332,15 @@ static void hwff_pull_n(const tu_fifo_t *f, void *app_buf, uint16_t n, uint16_t tu_hwfifo_write(hwfifo, ff_buf, n, access_mode); } else { // Wrap around case - + #if CFG_TUSB_FIFO_HWFIFO_DATA_STRIDE == 1 + tu_hwfifo_write(hwfifo, ff_buf, lin_bytes, access_mode); // linear part + HWFIFO_ADDR_NEXT_N(hwfifo, , lin_bytes); + tu_hwfifo_write(hwfifo, f->buffer, wrap_bytes, access_mode); // wrapped part + #else // Read full words from linear part const uint8_t data_stride = access_mode->data_stride; const uint32_t odd_mask = data_stride - 1; - uint16_t lin_even = lin_bytes & ~odd_mask; + uint16_t lin_even = lin_bytes & ~odd_mask; tu_hwfifo_write(hwfifo, ff_buf, lin_even, access_mode); HWFIFO_ADDR_NEXT_N(hwfifo, , lin_even); ff_buf += lin_even; @@ -338,10 +371,15 @@ static void hwff_pull_n(const tu_fifo_t *f, void *app_buf, uint16_t n, uint16_t if (wrap_bytes > 0) { tu_hwfifo_write(hwfifo, ff_buf, wrap_bytes, access_mode); } + #endif } } #endif +//--------------------------------------------------------------------+ +// Pull & Push +// copy data to/from fifo without updating read/write pointers +//--------------------------------------------------------------------+ // send n items to fifo WITHOUT updating write pointer static void ff_push_n(const tu_fifo_t *f, const void *app_buf, uint16_t n, uint16_t wr_ptr) { uint16_t lin_bytes = f->depth - wr_ptr; @@ -787,6 +825,6 @@ void tu_fifo_get_write_info(tu_fifo_t *f, tu_fifo_buffer_info_t *info) { } else { info->linear.len = f->depth - wr_ptr; info->wrapped.len = remain - info->linear.len; // Remaining length - n already was limited to remain or FIFO depth - info->wrapped.ptr = f->buffer; // Always start of buffer + info->wrapped.ptr = f->buffer; // Always start of buffer } } diff --git a/src/common/tusb_mcu.h b/src/common/tusb_mcu.h index 1a4e517b7..5b9497b9a 100644 --- a/src/common/tusb_mcu.h +++ b/src/common/tusb_mcu.h @@ -635,17 +635,7 @@ #define TUP_USBIP_DWC2_AT32 #define TUP_DCD_ENDPOINT_MAX 4 -#elif TU_CHECK_MCU(OPT_MCU_AT32F435_437) - #define TUP_USBIP_DWC2 - #define TUP_USBIP_DWC2_AT32 - #define TUP_DCD_ENDPOINT_MAX 8 - -#elif TU_CHECK_MCU(OPT_MCU_AT32F423) - #define TUP_USBIP_DWC2 - #define TUP_USBIP_DWC2_AT32 - #define TUP_DCD_ENDPOINT_MAX 8 - -#elif TU_CHECK_MCU(OPT_MCU_AT32F402_405) +#elif TU_CHECK_MCU(OPT_MCU_AT32F402_405, OPT_MCU_AT32F423, OPT_MCU_AT32F425, OPT_MCU_AT32F435_437, OPT_MCU_AT32F45X) #define TUP_USBIP_DWC2 #define TUP_USBIP_DWC2_AT32 #define TUP_DCD_ENDPOINT_MAX 8 @@ -657,11 +647,6 @@ #define TUP_RHPORT_HIGHSPEED 1 // Port0: FS, Port1: HS #endif -#elif TU_CHECK_MCU(OPT_MCU_AT32F425) - #define TUP_USBIP_DWC2 - #define TUP_USBIP_DWC2_AT32 - #define TUP_DCD_ENDPOINT_MAX 8 - //--------------------------------------------------------------------+ // HPMicro //--------------------------------------------------------------------+ diff --git a/src/common/tusb_private.h b/src/common/tusb_private.h index 10e12c2af..43ce7a1df 100644 --- a/src/common/tusb_private.h +++ b/src/common/tusb_private.h @@ -37,14 +37,6 @@ // Configuration //--------------------------------------------------------------------+ -#if CFG_TUD_ENABLED && CFG_TUD_VENDOR && (CFG_TUD_VENDOR_TX_BUFSIZE == 0 || CFG_TUD_VENDOR_RX_BUFSIZE == 0) - #define CFG_TUSB_EDPT_STREAM_NO_FIFO_ENABLED 1 -#endif - -#ifndef CFG_TUSB_EDPT_STREAM_NO_FIFO_ENABLED - #define CFG_TUSB_EDPT_STREAM_NO_FIFO_ENABLED 0 -#endif - #define TUP_USBIP_CONTROLLER_NUM 2 extern tusb_role_t _tusb_rhport_role[TUP_USBIP_CONTROLLER_NUM]; diff --git a/src/common/tusb_types.h b/src/common/tusb_types.h index d473e53e6..7d26ac74e 100644 --- a/src/common/tusb_types.h +++ b/src/common/tusb_types.h @@ -554,7 +554,7 @@ TU_ATTR_ALWAYS_INLINE static inline uint8_t tu_edpt_number(uint8_t addr) { } TU_ATTR_ALWAYS_INLINE static inline uint8_t tu_edpt_addr(uint8_t num, uint8_t dir) { - return (uint8_t) (num | (dir == TUSB_DIR_IN ? TUSB_DIR_IN_MASK : 0u)); + return (uint8_t) (num | (dir == (uint8_t)TUSB_DIR_IN ? (uint8_t)TUSB_DIR_IN_MASK : 0u)); } TU_ATTR_ALWAYS_INLINE static inline uint16_t tu_edpt_packet_size(tusb_desc_endpoint_t const* desc_ep) { diff --git a/src/common/tusb_verify.h b/src/common/tusb_verify.h index c9e06361c..bd00b9d11 100644 --- a/src/common/tusb_verify.h +++ b/src/common/tusb_verify.h @@ -73,8 +73,13 @@ #define TU_MESS_FAILED() do {} while (0) #endif +// Custom defined application function +#ifdef CFG_TUSB_DEBUG_BREAKPOINT + extern void CFG_TUSB_DEBUG_BREAKPOINT(void); + #define TU_BREAKPOINT() CFG_TUSB_DEBUG_BREAKPOINT() + // Halt CPU (breakpoint) when hitting error, only apply for Cortex M3, M4, M7, M33. M55 -#if defined(__ARM_ARCH_7M__) || defined (__ARM_ARCH_7EM__) || defined(__ARM_ARCH_8M_MAIN__) || defined(__ARM_ARCH_8_1M_MAIN__) || \ +#elif defined(__ARM_ARCH_7M__) || defined (__ARM_ARCH_7EM__) || defined(__ARM_ARCH_8M_MAIN__) || defined(__ARM_ARCH_8_1M_MAIN__) || \ defined(__ARM7M__) || defined (__ARM7EM__) || defined(__ARM8M_MAINLINE__) || defined(__ARM8EM_MAINLINE__) #define TU_BREAKPOINT() do { \ volatile uint32_t* ARM_CM_DHCSR = ((volatile uint32_t*) 0xE000EDF0UL); /* Cortex M CoreDebug->DHCSR */ \ diff --git a/src/device/usbd.c b/src/device/usbd.c index 9cfc2cc59..127a7bd62 100644 --- a/src/device/usbd.c +++ b/src/device/usbd.c @@ -666,8 +666,14 @@ void tud_task_ext(uint32_t timeout_ms, bool in_isr) { return; } - // Loop until there is no more events in the queue - while (1) { + // Loop until there are no more events in the queue or CFG_TUD_TASK_EVENTS_PER_RUN is reached + for (unsigned epr = 0;; epr++) { +#if CFG_TUD_TASK_EVENTS_PER_RUN > 0 + if (epr >= CFG_TUD_TASK_EVENTS_PER_RUN) { + TU_LOG_USBD("USBD event limit (" TU_XSTRING(CFG_TUD_TASK_EVENTS_PER_RUN) ") reached\r\n"); + break; + } +#endif dcd_event_t event; if (!osal_queue_receive(_usbd_q, &event, timeout_ms)) { return; diff --git a/src/device/usbd.h b/src/device/usbd.h index bd5a3c395..825fdba90 100644 --- a/src/device/usbd.h +++ b/src/device/usbd.h @@ -41,8 +41,13 @@ enum { typedef struct { uint16_t bm_double_buffered; // bitmap of IN endpoints to be double buffered, only effective for bulk endpoints + bool vbus_sensing; // Vbus pin is used for device connection detection, mandatory for tud_umount_cb() } tud_configure_dwc2_t; + #ifndef CFG_TUD_CONFIGURE_DWC2_DEFAULT + #define CFG_TUD_CONFIGURE_DWC2_DEFAULT {.bm_double_buffered = 0, .vbus_sensing = CFG_TUD_VBUS_DETECT_HW} + #endif + typedef union { tud_configure_dwc2_t dwc2; } tud_configure_param_t; @@ -819,7 +824,7 @@ bool tud_vendor_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb_control_requ /* Interface */ \ 9, TUSB_DESC_INTERFACE, _itfnum, 0, 0, TUD_DFU_APP_CLASS, TUD_DFU_APP_SUBCLASS, DFU_PROTOCOL_RT, _stridx, \ /* Function */ \ - 9, DFU_DESC_FUNCTIONAL, _attr, U16_TO_U8S_LE(_timeout), U16_TO_U8S_LE(_xfer_size), U16_TO_U8S_LE(0x0101) + 9, DFU_DESC_FUNCTIONAL, _attr, U16_TO_U8S_LE(_timeout), U16_TO_U8S_LE(_xfer_size), U16_TO_U8S_LE(0x0110) //--------------------------------------------------------------------+ // DFU Descriptor Templates @@ -833,7 +838,7 @@ bool tud_vendor_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb_control_requ #define TUD_DFU_DESCRIPTOR(_itfnum, _alt_count, _stridx, _attr, _timeout, _xfer_size) \ TU_XSTRCAT(TUD_DFU_ALT_,_alt_count)(_itfnum, 0, _stridx), \ /* Function */ \ - 9, DFU_DESC_FUNCTIONAL, _attr, U16_TO_U8S_LE(_timeout), U16_TO_U8S_LE(_xfer_size), U16_TO_U8S_LE(0x0101) + 9, DFU_DESC_FUNCTIONAL, _attr, U16_TO_U8S_LE(_timeout), U16_TO_U8S_LE(_xfer_size), U16_TO_U8S_LE(0x0110) #define TUD_DFU_ALT(_itfnum, _alt, _stridx) \ /* Interface */ \ diff --git a/src/host/usbh.c b/src/host/usbh.c index da6afdddb..3400eaf74 100644 --- a/src/host/usbh.c +++ b/src/host/usbh.c @@ -599,8 +599,14 @@ void tuh_task_ext(uint32_t timeout_ms, bool in_isr) { return; } - // Loop until there is no more events in the queue - while (1) { + // Loop until there are no more events in the queue or CFG_TUH_TASK_EVENTS_PER_RUN is reached + for (unsigned epr = 0;; epr++) { +#if CFG_TUH_TASK_EVENTS_PER_RUN > 0 + if (epr >= CFG_TUH_TASK_EVENTS_PER_RUN) { + TU_LOG_USBH("USBH event limit (" TU_XSTRING(CFG_TUH_TASK_EVENTS_PER_RUN) ") reached\r\n"); + break; + } +#endif hcd_event_t event; if (!osal_queue_receive(_usbh_q, &event, timeout_ms)) { return; } @@ -1835,6 +1841,12 @@ static uint8_t enum_get_new_address(bool is_hub) { } } +#if CFG_TUH_HUB + if ( is_hub ) { + TU_LOG1("All addresses are occupied, try to increase CFG_TUH_HUB value.\r\n"); + } +#endif // CFG_TUH_HUB + return 0; // invalid address } diff --git a/src/host/usbh.h b/src/host/usbh.h index d86efbcb2..143d36f8c 100644 --- a/src/host/usbh.h +++ b/src/host/usbh.h @@ -96,6 +96,7 @@ enum { TUH_CFGID_RPI_PIO_USB_CONFIGURATION = 100, // cfg_param: pio_usb_configuration_t TUH_CFGID_MAX3421 = 200, TUH_CFGID_FSDEV = 300, + TUH_CFGID_DWC2 = 400 }; typedef struct { @@ -108,10 +109,15 @@ typedef struct { uint8_t max_nak; // max NAK per endpoint per frame to save CPU usage (0=unlimited) } tuh_configure_fsdev_t; +typedef struct { + bool use_hs_phy; // Always use high-speed ULPI/UTMI phy even when working at full-speed +} tuh_configure_dwc2_t; + typedef union { // For TUH_CFGID_RPI_PIO_USB_CONFIGURATION use pio_usb_configuration_t tuh_configure_max3421_t max3421; tuh_configure_fsdev_t fsdev; + tuh_configure_dwc2_t dwc2; } tuh_configure_param_t; //--------------------------------------------------------------------+ diff --git a/src/portable/mentor/musb/dcd_musb.c b/src/portable/mentor/musb/dcd_musb.c index 3827be318..d329285e9 100644 --- a/src/portable/mentor/musb/dcd_musb.c +++ b/src/portable/mentor/musb/dcd_musb.c @@ -32,12 +32,6 @@ #define MUSB_DEBUG 2 #define MUSB_REGS(rhport) ((musb_regs_t*) MUSB_BASES[rhport]) -#if __GNUC__ > 8 && defined(__ARM_FEATURE_UNALIGNED) -/* GCC warns that an address may be unaligned, even though - * the target CPU has the capability for unaligned memory access. */ -_Pragma("GCC diagnostic ignored \"-Waddress-of-packed-member\""); -#endif - #include "musb_type.h" #include "device/dcd.h" @@ -73,7 +67,10 @@ typedef struct TU_ATTR_PACKED typedef struct { - tusb_control_request_t setup_packet; + union { + tusb_control_request_t setup_packet; + uint32_t setup_buffer[2]; + }; uint16_t remaining_ctrl; /* The number of bytes remaining in data stage of control transfer. */ int8_t status_out; pipe_state_t pipe0; @@ -174,10 +171,8 @@ static void process_setup_packet(uint8_t rhport) { musb_regs_t* musb_regs = MUSB_REGS(rhport); // Read setup packet - uint32_t *p = (void*)&_dcd.setup_packet; - volatile uint32_t *fifo_ptr = &musb_regs->fifo[0]; - p[0] = *fifo_ptr; - p[1] = *fifo_ptr; + _dcd.setup_buffer[0] = musb_regs->fifo[0]; + _dcd.setup_buffer[1] = musb_regs->fifo[0]; _dcd.pipe0.buf = NULL; _dcd.pipe0.length = 0; @@ -194,14 +189,13 @@ static void process_setup_packet(uint8_t rhport) { } } -static bool handle_xfer_in(uint8_t rhport, uint_fast8_t ep_addr) -{ +static bool handle_xfer_in(uint8_t rhport, uint_fast8_t ep_addr) { unsigned epnum = tu_edpt_number(ep_addr); unsigned epnum_minus1 = epnum - 1; pipe_state_t *pipe = &_dcd.pipe[tu_edpt_dir(ep_addr)][epnum_minus1]; const unsigned rem = pipe->remaining; - if (!rem) { + if (rem == 0 && pipe->length > 0) { pipe->buf = NULL; return true; } @@ -218,7 +212,7 @@ static bool handle_xfer_in(uint8_t rhport, uint_fast8_t ep_addr) tu_hwfifo_write_from_fifo(fifo_ptr, (tu_fifo_t *)buf, len, NULL); } else { tu_hwfifo_write(fifo_ptr, buf, len, NULL); - pipe->buf = buf + len; + pipe->buf = (uint8_t*)buf + len; } pipe->remaining = rem - len; } @@ -249,7 +243,7 @@ static bool handle_xfer_out(uint8_t rhport, uint_fast8_t ep_addr) tu_hwfifo_read_to_fifo(fifo_ptr, (tu_fifo_t *)buf, len, NULL); } else { tu_hwfifo_read(fifo_ptr, buf, len, NULL); - pipe->buf = buf + len; + pipe->buf = (uint8_t*)buf + len; } pipe->remaining = rem - len; } diff --git a/src/portable/mentor/musb/musb_ti.h b/src/portable/mentor/musb/musb_ti.h index d17e836ee..68e89d77d 100644 --- a/src/portable/mentor/musb/musb_ti.h +++ b/src/portable/mentor/musb/musb_ti.h @@ -35,7 +35,10 @@ #include "TM4C123.h" #define FIFO0_WORD FIFO0 #define FIFO1_WORD FIFO1 -//#elif CFG_TUSB_MCU == OPT_MCU_TM4C129 +#elif CFG_TUSB_MCU == OPT_MCU_TM4C129 + #include "TM4C129.h" + #define FIFO0_WORD FIFOA + #define FIFO1_WORD FIFOB #elif CFG_TUSB_MCU == OPT_MCU_MSP432E4 #include "msp.h" #else diff --git a/src/portable/mentor/musb/musb_type.h b/src/portable/mentor/musb/musb_type.h index 4e448c0ed..b2f6492fa 100644 --- a/src/portable/mentor/musb/musb_type.h +++ b/src/portable/mentor/musb/musb_type.h @@ -147,7 +147,7 @@ typedef struct TU_ATTR_PACKED { TU_VERIFY_STATIC(sizeof(musb_ep_csr_t) == 16, "size is not correct"); -typedef struct TU_ATTR_PACKED { +typedef struct { //------------- Common -------------// __IO uint8_t faddr; // 0x00: FADDR union { diff --git a/src/portable/raspberrypi/rp2040/dcd_rp2040.c b/src/portable/raspberrypi/rp2040/dcd_rp2040.c index 15852f29f..240e6c727 100644 --- a/src/portable/raspberrypi/rp2040/dcd_rp2040.c +++ b/src/portable/raspberrypi/rp2040/dcd_rp2040.c @@ -39,122 +39,103 @@ #include "device/dcd.h" // Current implementation force vbus detection as always present, causing device think it is always plugged into host. -// Therefore it cannot detect disconnect event, mistaken it as suspend. +// Therefore, it cannot detect disconnect event, mistaken it as suspend. // Note: won't work if change to 0 (for now) -#define FORCE_VBUS_DETECT 1 + #define FORCE_VBUS_DETECT 1 + + #define USB_INTS_ERROR_BITS \ + (USB_INTS_ERROR_DATA_SEQ_BITS | USB_INTS_ERROR_BIT_STUFF_BITS | USB_INTS_ERROR_CRC_BITS | \ + USB_INTS_ERROR_RX_OVERFLOW_BITS | USB_INTS_ERROR_RX_TIMEOUT_BITS) /*------------------------------------------------------------------*/ /* Low level controller *------------------------------------------------------------------*/ -// Init these in dcd_init -static uint8_t* next_buffer_ptr; +// HW buffer pointer from USB buffer space (max 3840 bytes) +static uint8_t *hw_buffer_ptr; // USB_MAX_ENDPOINTS Endpoints, direction TUSB_DIR_OUT for out and TUSB_DIR_IN for in. static struct hw_endpoint hw_endpoints[USB_MAX_ENDPOINTS][2]; -// SOF may be used by remote wakeup as RESUME, this indicate whether SOF is actually used by usbd +// SOF may be used by remote wakeup as RESUME, this indicates whether SOF is actually used by usbd static bool _sof_enable = false; -TU_ATTR_ALWAYS_INLINE static inline struct hw_endpoint* hw_endpoint_get_by_num(uint8_t num, tusb_dir_t dir) { - return &hw_endpoints[num][dir]; -} - -TU_ATTR_ALWAYS_INLINE static inline struct hw_endpoint* hw_endpoint_get_by_addr(uint8_t ep_addr) { - uint8_t num = tu_edpt_number(ep_addr); - tusb_dir_t dir = tu_edpt_dir(ep_addr); - return hw_endpoint_get_by_num(num, dir); -} - -// Allocate from the USB buffer space (max 3840 bytes) -static void hw_endpoint_alloc(struct hw_endpoint* ep, size_t size) { - // round up size to multiple of 64 - size = tu_round_up(ep->wMaxPacketSize, 64); - - // double buffered Bulk endpoint - if (ep->transfer_type == TUSB_XFER_BULK) { - size *= 2u; - } - - // assign buffer - ep->hw_data_buf = next_buffer_ptr; - next_buffer_ptr += size; - - hard_assert(next_buffer_ptr < usb_dpram->epx_data + sizeof(usb_dpram->epx_data)); - pico_info(" Allocated %d bytes (0x%p)\r\n", size, ep->hw_data_buf); +TU_ATTR_ALWAYS_INLINE static inline hw_endpoint_t *hw_endpoint_get(uint8_t epnum, tusb_dir_t dir) { + return &hw_endpoints[epnum][dir]; } -// Enable endpoint -TU_ATTR_ALWAYS_INLINE static inline void hw_endpoint_enable(struct hw_endpoint* ep) { - uint32_t const reg = EP_CTRL_ENABLE_BITS | ((uint) ep->transfer_type << EP_CTRL_BUFFER_TYPE_LSB) | hw_data_offset(ep->hw_data_buf); - *ep->endpoint_control = reg; +TU_ATTR_ALWAYS_INLINE static inline hw_endpoint_t *hw_endpoint_get_by_addr(uint8_t ep_addr) { + const uint8_t num = tu_edpt_number(ep_addr); + const tusb_dir_t dir = tu_edpt_dir(ep_addr); + return hw_endpoint_get(num, dir); } // main processing for dcd_edpt_iso_activate -static void hw_endpoint_init(uint8_t ep_addr, uint16_t wMaxPacketSize, uint8_t transfer_type) { - struct hw_endpoint* ep = hw_endpoint_get_by_addr(ep_addr); - - const uint8_t num = tu_edpt_number(ep_addr); - const tusb_dir_t dir = tu_edpt_dir(ep_addr); - - ep->ep_addr = ep_addr; - - // For device, IN is a tx transfer and OUT is an rx transfer - ep->rx = (dir == TUSB_DIR_OUT); - - ep->next_pid = 0u; +static void hw_endpoint_init(hw_endpoint_t *ep, uint8_t ep_addr, uint16_t wMaxPacketSize, uint8_t transfer_type) { + ep->ep_addr = ep_addr; + ep->next_pid = 0u; ep->wMaxPacketSize = wMaxPacketSize; - ep->transfer_type = transfer_type; - - // Every endpoint has a buffer control register in dpram - if (dir == TUSB_DIR_IN) { - ep->buffer_control = &usb_dpram->ep_buf_ctrl[num].in; - } else { - ep->buffer_control = &usb_dpram->ep_buf_ctrl[num].out; - } // Clear existing buffer control state - *ep->buffer_control = 0; - - if (num == 0) { - // EP0 has no endpoint control register because the buffer offsets are fixed - ep->endpoint_control = NULL; + io_rw_32 *buf_ctrl_reg = hwbuf_ctrl_reg_device(ep); + *buf_ctrl_reg = 0; + // allocated hw buffer + const uint8_t epnum = tu_edpt_number(ep_addr); + if (epnum == 0) { // Buffer offset is fixed (also double buffered) ep->hw_data_buf = (uint8_t*) &usb_dpram->ep0_buf_a[0]; } else { - // Set the endpoint control register (starts at EP1, hence num-1) - if (dir == TUSB_DIR_IN) { - ep->endpoint_control = &usb_dpram->ep_ctrl[num - 1].in; - } else { - ep->endpoint_control = &usb_dpram->ep_ctrl[num - 1].out; + // round up size to multiple of 64 + uint16_t size = (uint16_t)tu_round_up(wMaxPacketSize, 64); + + // double buffered Bulk endpoint + if (transfer_type == TUSB_XFER_BULK) { + size *= 2u; + + #if TUD_OPT_RP2040_USB_DEVICE_UFRAME_FIX + if (tu_edpt_dir(ep_addr) == TUSB_DIR_IN) { + ep->e15_bulk_in = true; + } + #endif } + + // assign buffer + ep->hw_data_buf = hw_buffer_ptr; + hw_buffer_ptr += size; + + hard_assert(hw_buffer_ptr < usb_dpram->epx_data + sizeof(usb_dpram->epx_data)); + pico_info(" Allocated %d bytes (0x%p)\r\n", size, ep->hw_data_buf); } } -// Init, allocate buffer and enable endpoint -static void hw_endpoint_open(uint8_t ep_addr, uint16_t wMaxPacketSize, uint8_t transfer_type) { - struct hw_endpoint* ep = hw_endpoint_get_by_addr(ep_addr); - hw_endpoint_init(ep_addr, wMaxPacketSize, transfer_type); - const uint8_t num = tu_edpt_number(ep_addr); - if (num != 0) { - // EP0 is already enabled - hw_endpoint_alloc(ep, ep->wMaxPacketSize); - hw_endpoint_enable(ep); +static void hw_endpoint_enable(hw_endpoint_t *ep, uint8_t transfer_type) { + io_rw_32 *ctrl_reg = hwep_ctrl_reg_device(ep); + // Set endpoint control register to enable (EP0 has no endpoint control register) + if (ctrl_reg != NULL) { + const uint32_t ctrl_value = + EP_CTRL_ENABLE_BITS | ((uint32_t)transfer_type << EP_CTRL_BUFFER_TYPE_LSB) | hw_data_offset(ep->hw_data_buf); + *ctrl_reg = ctrl_value; } } -static void hw_endpoint_xfer(uint8_t ep_addr, uint8_t* buffer, uint16_t total_bytes) { - struct hw_endpoint* ep = hw_endpoint_get_by_addr(ep_addr); - hw_endpoint_xfer_start(ep, buffer, total_bytes); +// Init and enable endpoint +static void hw_endpoint_open(uint8_t ep_addr, uint16_t wMaxPacketSize, uint8_t transfer_type) { + const uint8_t epnum = tu_edpt_number(ep_addr); + const tusb_dir_t dir = tu_edpt_dir(ep_addr); + hw_endpoint_t *ep = hw_endpoint_get(epnum, dir); + + hw_endpoint_init(ep, ep_addr, wMaxPacketSize, transfer_type); + hw_endpoint_enable(ep, transfer_type); } static void hw_endpoint_abort_xfer(struct hw_endpoint* ep) { // Abort any pending transfer + const uint8_t dir = (uint8_t)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)); + // 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) {} @@ -165,7 +146,8 @@ static void hw_endpoint_abort_xfer(struct hw_endpoint* ep) { buf_ctrl |= USB_BUF_CTRL_DATA1_PID; } - _hw_endpoint_buffer_control_set_value32(ep, buf_ctrl); + io_rw_32 *buf_ctrl_reg = hwbuf_ctrl_reg_device(ep); + hwbuf_ctrl_set(buf_ctrl_reg, buf_ctrl); hw_endpoint_reset_transfer(ep); if (rp2040_chip_version() >= 2) { @@ -174,7 +156,7 @@ static void hw_endpoint_abort_xfer(struct hw_endpoint* ep) { } } -static void __tusb_irq_path_func(hw_handle_buff_status)(void) { +static void __tusb_irq_path_func(handle_hw_buff_status)(void) { uint32_t remaining_buffers = usb_hw->buf_status; pico_trace("buf_status = 0x%08lx\r\n", remaining_buffers); uint bit = 1u; @@ -184,12 +166,13 @@ static void __tusb_irq_path_func(hw_handle_buff_status)(void) { usb_hw_clear->buf_status = bit; // IN transfer for even i, OUT transfer for odd i - struct hw_endpoint* ep = hw_endpoint_get_by_num(i >> 1u, (i & 1u) ? TUSB_DIR_OUT : TUSB_DIR_IN); + const uint8_t epnum = i >> 1u; + const tusb_dir_t dir = (i & 1u) ? TUSB_DIR_OUT : TUSB_DIR_IN; + hw_endpoint_t *ep = hw_endpoint_get(epnum, dir); - // Continue xfer - bool done = hw_endpoint_xfer_continue(ep); + const bool done = hw_endpoint_xfer_continue(ep); if (done) { - // Notify + // Notify usbd const uint16_t xferred_len = ep->xferred_len; hw_endpoint_reset_transfer(ep); dcd_event_xfer_complete(0, ep->ep_addr, xferred_len, XFER_RESULT_SUCCESS, true); @@ -204,7 +187,7 @@ TU_ATTR_ALWAYS_INLINE static inline void reset_ep0(void) { // If we have finished this transfer on EP0 set pid back to 1 for next // 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); + struct hw_endpoint *ep = hw_endpoint_get(0, dir); ep->next_pid = 1u; if (ep->active) { hw_endpoint_abort_xfer(ep); // Abort any pending transfer per USB specs @@ -223,11 +206,11 @@ static void __tusb_irq_path_func(reset_non_control_endpoints)(void) { tu_memclr(hw_endpoints[1], sizeof(hw_endpoints) - 2 * sizeof(hw_endpoint_t)); // reclaim buffer space - next_buffer_ptr = &usb_dpram->epx_data[0]; + hw_buffer_ptr = &usb_dpram->epx_data[0]; } static void __tusb_irq_path_func(dcd_rp2040_irq)(void) { - uint32_t const status = usb_hw->ints; + const uint32_t status = usb_hw->ints; uint32_t handled = 0; if (status & USB_INTF_DEV_SOF_BITS) { @@ -240,27 +223,26 @@ static void __tusb_irq_path_func(dcd_rp2040_irq)(void) { e15_last_sof = time_us_32(); for (uint8_t i = 0; i < USB_MAX_ENDPOINTS; i++) { - struct hw_endpoint* ep = hw_endpoint_get_by_num(i, TUSB_DIR_IN); + struct hw_endpoint *ep = hw_endpoint_get(i, TUSB_DIR_IN); // Active Bulk IN endpoint requires SOF - if ((ep->transfer_type == TUSB_XFER_BULK) && ep->active) { + if (ep->e15_bulk_in && ep->active) { keep_sof_alive = true; hw_endpoint_lock_update(ep, 1); - - // Deferred enable? if (ep->pending) { ep->pending = 0; hw_endpoint_start_next_buffer(ep); } - hw_endpoint_lock_update(ep, -1); } } #endif // disable SOF interrupt if it is used for RESUME in remote wakeup - if (!keep_sof_alive && !_sof_enable) usb_hw_clear->inte = USB_INTS_DEV_SOF_BITS; + if (!keep_sof_alive && !_sof_enable) { + usb_hw_clear->inte = USB_INTS_DEV_SOF_BITS; + } dcd_event_sof(0, usb_hw->sof_rd & USB_SOF_RD_BITS, true); } @@ -269,7 +251,7 @@ static void __tusb_irq_path_func(dcd_rp2040_irq)(void) { // before closing the EP, the events will be delivered in same order. if (status & USB_INTS_BUFF_STATUS_BITS) { handled |= USB_INTS_BUFF_STATUS_BITS; - hw_handle_buff_status(); + handle_hw_buff_status(); } if (status & USB_INTS_SETUP_REQ_BITS) { @@ -287,15 +269,12 @@ static void __tusb_irq_path_func(dcd_rp2040_irq)(void) { #if FORCE_VBUS_DETECT == 0 // Since we force VBUS detect On, device will always think it is connected and // couldn't distinguish between disconnect and suspend - if (status & USB_INTS_DEV_CONN_DIS_BITS) - { + if (status & USB_INTS_DEV_CONN_DIS_BITS) { handled |= USB_INTS_DEV_CONN_DIS_BITS; - if ( usb_hw->sie_status & USB_SIE_STATUS_CONNECTED_BITS ) - { + if (usb_hw->sie_status & USB_SIE_STATUS_CONNECTED_BITS) { // Connected: nothing to do - }else - { + } else { // Disconnected dcd_event_bus_signal(0, DCD_EVENT_UNPLUGGED, true); } @@ -315,10 +294,12 @@ static void __tusb_irq_path_func(dcd_rp2040_irq)(void) { dcd_event_bus_reset(0, TUSB_SPEED_FULL, true); usb_hw_clear->sie_status = USB_SIE_STATUS_BUS_RESET_BITS; -#if TUD_OPT_RP2040_USB_DEVICE_ENUMERATION_FIX + #if TUD_OPT_RP2040_USB_DEVICE_ENUMERATION_FIX // Only run enumeration workaround if pull up is enabled - if (usb_hw->sie_ctrl & USB_SIE_CTRL_PULLUP_EN_BITS) rp2040_usb_device_enumeration_fix(); -#endif + if (usb_hw->sie_ctrl & USB_SIE_CTRL_PULLUP_EN_BITS) { + rp2040_usb_device_enumeration_fix(); + } + #endif } /* Note from pico datasheet 4.1.2.6.4 (v1.2) @@ -346,13 +327,6 @@ static void __tusb_irq_path_func(dcd_rp2040_irq)(void) { } } -#define USB_INTS_ERROR_BITS ( \ - USB_INTS_ERROR_DATA_SEQ_BITS | \ - USB_INTS_ERROR_BIT_STUFF_BITS | \ - USB_INTS_ERROR_CRC_BITS | \ - USB_INTS_ERROR_RX_OVERFLOW_BITS | \ - USB_INTS_ERROR_RX_TIMEOUT_BITS) - /*------------------------------------------------------------------*/ /* Controller API *------------------------------------------------------------------*/ @@ -369,9 +343,9 @@ bool dcd_init(uint8_t rhport, const tusb_rhport_init_t* rh_init) { TU_LOG(2, "Chip Version B%u\r\n", rp2040_chip_version()); // Reset hardware to default state - rp2040_usb_init(); + rp2usb_init(); -#if FORCE_VBUS_DETECT + #if FORCE_VBUS_DETECT // Force VBUS detect so the device thinks it is plugged into a host usb_hw->pwr = USB_USB_PWR_VBUS_DETECT_BITS | USB_USB_PWR_VBUS_DETECT_OVERRIDE_EN_BITS; #endif @@ -425,12 +399,11 @@ void dcd_int_disable(__unused uint8_t rhport) { irq_set_enabled(USBCTRL_IRQ, false); } -void dcd_set_address(__unused uint8_t rhport, __unused uint8_t dev_addr) { - assert(rhport == 0); - +void dcd_set_address(uint8_t rhport, uint8_t dev_addr) { + (void)dev_addr; // Can't set device address in hardware until status xfer has complete // Send 0len complete response on EP0 IN - hw_endpoint_xfer(0x80, NULL, 0); + dcd_edpt_xfer(rhport, 0x80, NULL, 0, false); } void dcd_remote_wakeup(__unused uint8_t rhport) { @@ -475,7 +448,6 @@ void dcd_sof_enable(uint8_t rhport, bool en) { /*------------------------------------------------------------------*/ /* DCD Endpoint port *------------------------------------------------------------------*/ - void dcd_edpt0_status_complete(uint8_t rhport, tusb_control_request_t const* request) { (void) rhport; @@ -489,7 +461,6 @@ void dcd_edpt0_status_complete(uint8_t rhport, tusb_control_request_t const* req bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const* desc_edpt) { (void) rhport; const uint8_t xfer_type = desc_edpt->bmAttributes.xfer; - TU_VERIFY(xfer_type != TUSB_XFER_ISOCHRONOUS); hw_endpoint_open(desc_edpt->bEndpointAddress, tu_edpt_packet_size(desc_edpt), xfer_type); return true; } @@ -497,56 +468,65 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const* desc_edpt) { // New API: Allocate packet buffer used by ISO endpoints // Some MCU need manual packet buffer allocation, we allocate the largest size to avoid clustering bool dcd_edpt_iso_alloc(uint8_t rhport, uint8_t ep_addr, uint16_t largest_packet_size) { - (void) rhport; - struct hw_endpoint* ep = hw_endpoint_get_by_addr(ep_addr); - hw_endpoint_init(ep_addr, largest_packet_size, TUSB_XFER_ISOCHRONOUS); - hw_endpoint_alloc(ep, largest_packet_size); + (void)rhport; + struct hw_endpoint *ep = hw_endpoint_get_by_addr(ep_addr); + hw_endpoint_init(ep, ep_addr, largest_packet_size, TUSB_XFER_ISOCHRONOUS); return true; } // 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; - struct hw_endpoint* ep = hw_endpoint_get_by_addr(ep_desc->bEndpointAddress); +bool dcd_edpt_iso_activate(uint8_t rhport, const tusb_desc_endpoint_t *ep_desc) { + (void)rhport; + const uint8_t epnum = tu_edpt_number(ep_desc->bEndpointAddress); + const tusb_dir_t dir = tu_edpt_dir(ep_desc->bEndpointAddress); + struct hw_endpoint *ep = hw_endpoint_get(epnum, dir); 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); + + hw_endpoint_enable(ep, TUSB_XFER_ISOCHRONOUS); return true; } void dcd_edpt_close_all(uint8_t rhport) { (void) rhport; - // may need to use EP Abort reset_non_control_endpoints(); } -bool dcd_edpt_xfer(__unused uint8_t rhport, uint8_t ep_addr, uint8_t* buffer, uint16_t total_bytes, bool is_isr) { - (void) is_isr; - assert(rhport == 0); - hw_endpoint_xfer(ep_addr, buffer, total_bytes); +bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t *buffer, uint16_t total_bytes, bool is_isr) { + (void)rhport; + (void)is_isr; + hw_endpoint_t *ep = hw_endpoint_get_by_addr(ep_addr); + hw_endpoint_xfer_start(ep, buffer, NULL, total_bytes); + return true; +} + +bool dcd_edpt_xfer_fifo(uint8_t rhport, uint8_t ep_addr, tu_fifo_t *ff, uint16_t total_bytes, bool is_isr) { + (void)rhport; + (void)is_isr; + hw_endpoint_t *ep = hw_endpoint_get_by_addr(ep_addr); + hw_endpoint_xfer_start(ep, NULL, ff, total_bytes); return true; } void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr) { - (void) rhport; + (void)rhport; + const uint8_t epnum = tu_edpt_number(ep_addr); + const tusb_dir_t dir = tu_edpt_dir(ep_addr); + hw_endpoint_t *ep = hw_endpoint_get(epnum, dir); - if (tu_edpt_number(ep_addr) == 0) { + if (epnum == 0) { // A stall on EP0 has to be armed so it can be cleared on the next setup packet - usb_hw_set->ep_stall_arm = (tu_edpt_dir(ep_addr) == TUSB_DIR_IN) ? USB_EP_STALL_ARM_EP0_IN_BITS - : USB_EP_STALL_ARM_EP0_OUT_BITS; + usb_hw_set->ep_stall_arm = (dir == TUSB_DIR_IN) ? USB_EP_STALL_ARM_EP0_IN_BITS : USB_EP_STALL_ARM_EP0_OUT_BITS; } - struct hw_endpoint* ep = hw_endpoint_get_by_addr(ep_addr); - - // stall and clear current pending buffer - // may need to use EP_ABORT - _hw_endpoint_buffer_control_set_value32(ep, USB_BUF_CTRL_STALL); + // stall and clear current pending buffer, may need to use EP_ABORT + io_rw_32 *buf_ctrl_reg = hwbuf_ctrl_reg_device(ep); + hwbuf_ctrl_set(buf_ctrl_reg, USB_BUF_CTRL_STALL); } void dcd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr) { @@ -557,7 +537,8 @@ void dcd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr) { // clear stall also reset toggle to DATA0, ready for next transfer ep->next_pid = 0; - _hw_endpoint_buffer_control_clear_mask32(ep, USB_BUF_CTRL_STALL); + io_rw_32 *buf_ctrl_reg = hwbuf_ctrl_reg_device(ep); + hwbuf_ctrl_clear_mask(buf_ctrl_reg, USB_BUF_CTRL_STALL); } } diff --git a/src/portable/raspberrypi/rp2040/hcd_rp2040.c b/src/portable/raspberrypi/rp2040/hcd_rp2040.c index cd8c905d5..06c0ce340 100644 --- a/src/portable/raspberrypi/rp2040/hcd_rp2040.c +++ b/src/portable/raspberrypi/rp2040/hcd_rp2040.c @@ -62,34 +62,33 @@ enum { USB_SIE_CTRL_PULLDOWN_EN_BITS | USB_SIE_CTRL_EP0_INT_1BUF_BITS }; -static struct hw_endpoint *get_dev_ep(uint8_t dev_addr, uint8_t ep_addr) -{ +static struct hw_endpoint *get_dev_ep(uint8_t dev_addr, uint8_t ep_addr) { uint8_t num = tu_edpt_number(ep_addr); - if ( num == 0 ) return &epx; + if (num == 0) { + return &epx; + } - for ( uint32_t i = 1; i < TU_ARRAY_SIZE(ep_pool); i++ ) - { + for (uint32_t i = 1; i < TU_ARRAY_SIZE(ep_pool); i++) { struct hw_endpoint *ep = &ep_pool[i]; - if ( ep->configured && (ep->dev_addr == dev_addr) && (ep->ep_addr == ep_addr) ) return ep; + if (ep->configured && (ep->dev_addr == dev_addr) && (ep->ep_addr == ep_addr)) { + return ep; + } } return NULL; } -TU_ATTR_ALWAYS_INLINE static inline uint8_t dev_speed(void) -{ +TU_ATTR_ALWAYS_INLINE static inline uint8_t dev_speed(void) { return (usb_hw->sie_status & USB_SIE_STATUS_SPEED_BITS) >> USB_SIE_STATUS_SPEED_LSB; } -TU_ATTR_ALWAYS_INLINE static inline bool need_pre(uint8_t dev_addr) -{ +TU_ATTR_ALWAYS_INLINE static inline bool need_pre(uint8_t dev_addr) { // If this device is different to the speed of the root device // (i.e. is a low speed device on a full speed hub) then need pre return hcd_port_speed_get(0) != tuh_speed_get(dev_addr); } -static void __tusb_irq_path_func(hw_xfer_complete)(struct hw_endpoint *ep, xfer_result_t xfer_result) -{ +static void __tusb_irq_path_func(hw_xfer_complete)(struct hw_endpoint *ep, xfer_result_t xfer_result) { // Mark transfer as done before we tell the tinyusb stack uint8_t dev_addr = ep->dev_addr; uint8_t ep_addr = ep->ep_addr; @@ -98,47 +97,28 @@ static void __tusb_irq_path_func(hw_xfer_complete)(struct hw_endpoint *ep, xfer_ hcd_event_xfer_complete(dev_addr, ep_addr, xferred_len, xfer_result, true); } -static void __tusb_irq_path_func(_handle_buff_status_bit)(uint bit, struct hw_endpoint *ep) -{ +static void __tusb_irq_path_func(handle_hwbuf_status_bit)(uint bit, struct hw_endpoint *ep) { usb_hw_clear->buf_status = bit; - // EP may have been stalled? - assert(ep->active); - bool done = hw_endpoint_xfer_continue(ep); - if ( done ) - { + const bool done = hw_endpoint_xfer_continue(ep); + if (done) { hw_xfer_complete(ep, XFER_RESULT_SUCCESS); } } -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\n", remaining_buffers); +static void __tusb_irq_path_func(handle_hwbuf_status)(void) { + uint32_t buf_status = usb_hw->buf_status; + pico_trace("buf_status 0x%08lx\n", buf_status); // Check EPX first - uint bit = 0b1; - if ( remaining_buffers & bit ) - { - remaining_buffers &= ~bit; + uint32_t bit = 1u; + if (buf_status & bit) { + buf_status &= ~bit; struct hw_endpoint * ep = &epx; - - uint32_t ep_ctrl = *ep->endpoint_control; - if ( ep_ctrl & EP_CTRL_DOUBLE_BUFFERED_BITS ) - { - TU_LOG(3, "Double Buffered: "); - } - else - { - TU_LOG(3, "Single Buffered: "); - } - TU_LOG_HEX(3, ep_ctrl); - - _handle_buff_status_bit(bit, ep); + handle_hwbuf_status_bit(bit, ep); } // Check "interrupt" (asynchronous) endpoints for both IN and OUT - for ( uint i = 1; i <= USB_HOST_INTERRUPT_ENDPOINTS && remaining_buffers; i++ ) - { + for (uint i = 1; i <= USB_HOST_INTERRUPT_ENDPOINTS && buf_status; i++) { // EPX is bit 0 & 1 // IEP1 IN is bit 2 // IEP1 OUT is bit 3 @@ -147,20 +127,17 @@ static void __tusb_irq_path_func(hw_handle_buff_status)(void) // IEP3 IN is bit 6 // IEP3 OUT is bit 7 // etc - for ( uint j = 0; j < 2; j++ ) - { + for (uint j = 0; j < 2; j++) { bit = 1 << (i * 2 + j); - if ( remaining_buffers & bit ) - { - remaining_buffers &= ~bit; - _handle_buff_status_bit(bit, &ep_pool[i]); + if (buf_status & bit) { + buf_status &= ~bit; + handle_hwbuf_status_bit(bit, &ep_pool[i]); } } } - if ( remaining_buffers ) - { - panic("Unhandled buffer %d\n", remaining_buffers); + if (buf_status) { + panic("Unhandled buffer %d\n", buf_status); } } @@ -220,7 +197,7 @@ static void __tusb_irq_path_func(hcd_rp2040_irq)(void) { handled |= USB_INTS_BUFF_STATUS_BITS; TU_LOG(2, "Buffer complete\r\n"); - hw_handle_buff_status(); + handle_hwbuf_status(); } if ( status & USB_INTS_TRANS_COMPLETE_BITS ) @@ -240,9 +217,8 @@ static void __tusb_irq_path_func(hcd_rp2040_irq)(void) if ( status & USB_INTS_ERROR_DATA_SEQ_BITS ) { usb_hw_clear->sie_status = USB_SIE_STATUS_DATA_SEQ_ERROR_BITS; - TU_LOG(3, " Seq Error: [0] = 0x%04u [1] = 0x%04x\r\n", - tu_u32_low16(*epx.buffer_control), - tu_u32_high16(*epx.buffer_control)); + TU_LOG(3, " Seq Error: [0] = 0x%04u [1] = 0x%04x\r\n", tu_u32_low16(*hwbuf_ctrl_reg_host(&epx)), + tu_u32_high16(*hwbuf_ctrl_reg_host(&epx))); panic("Data Seq Error \n"); } @@ -266,7 +242,7 @@ static struct hw_endpoint *_next_free_interrupt_ep(void) ep = &ep_pool[i]; if ( !ep->configured ) { - // Will be configured by _hw_endpoint_init / _hw_endpoint_allocate + // Will be configured by hw_endpoint_init / hw_endpoint_allocate ep->interrupt_num = (uint8_t) (i - 1); return ep; } @@ -274,41 +250,31 @@ static struct hw_endpoint *_next_free_interrupt_ep(void) return ep; } -static struct hw_endpoint *_hw_endpoint_allocate(uint8_t transfer_type) -{ - struct hw_endpoint * ep = NULL; +static hw_endpoint_t *hw_endpoint_allocate(uint8_t transfer_type) { + hw_endpoint_t *ep = NULL; - if ( transfer_type != TUSB_XFER_CONTROL ) - { + if (transfer_type == TUSB_XFER_CONTROL) { + ep = &epx; + ep->hw_data_buf = &usbh_dpram->epx_data[0]; + } else { // Note: even though datasheet name these "Interrupt" endpoints. These are actually // "Asynchronous" endpoints and can be used for other type such as: Bulk (ISO need confirmation) ep = _next_free_interrupt_ep(); pico_info("Allocate %s ep %d\n", tu_edpt_type_str(transfer_type), ep->interrupt_num); assert(ep); - ep->buffer_control = &usbh_dpram->int_ep_buffer_ctrl[ep->interrupt_num].ctrl; - ep->endpoint_control = &usbh_dpram->int_ep_ctrl[ep->interrupt_num].ctrl; // 0 for epx (double buffered): TODO increase to 1024 for ISO // 2x64 for intep0 // 3x64 for intep1 // etc ep->hw_data_buf = &usbh_dpram->epx_data[64 * (ep->interrupt_num + 2)]; } - else - { - ep = &epx; - ep->buffer_control = &usbh_dpram->epx_buf_ctrl; - ep->endpoint_control = &usbh_dpram->epx_ctrl; - ep->hw_data_buf = &usbh_dpram->epx_data[0]; - } return ep; } -static void _hw_endpoint_init(struct hw_endpoint *ep, uint8_t dev_addr, uint8_t ep_addr, uint16_t wMaxPacketSize, uint8_t transfer_type, uint8_t bmInterval) -{ +static void hw_endpoint_init(struct hw_endpoint *ep, uint8_t dev_addr, uint8_t ep_addr, uint16_t wMaxPacketSize, + uint8_t transfer_type, uint8_t bmInterval) { // Already has data buffer, endpoint control, and buffer control allocated at this point - assert(ep->endpoint_control); - assert(ep->buffer_control); assert(ep->hw_data_buf); uint8_t const num = tu_edpt_number(ep_addr); @@ -317,49 +283,41 @@ static void _hw_endpoint_init(struct hw_endpoint *ep, uint8_t dev_addr, uint8_t ep->ep_addr = ep_addr; ep->dev_addr = dev_addr; - // For host, IN to host == RX, anything else rx == false - ep->rx = (dir == TUSB_DIR_IN); - // Response to a setup packet on EP0 starts with pid of 1 ep->next_pid = (num == 0 ? 1u : 0u); ep->wMaxPacketSize = wMaxPacketSize; - ep->transfer_type = transfer_type; - pico_trace("hw_endpoint_init dev %d ep %02X xfer %d\n", ep->dev_addr, ep->ep_addr, ep->transfer_type); + pico_trace("hw_endpoint_init dev %d ep %02X xfer %d\n", ep->dev_addr, ep->ep_addr, transfer_type); pico_trace("dev %d ep %02X setup buffer @ 0x%p\n", ep->dev_addr, ep->ep_addr, ep->hw_data_buf); uint dpram_offset = hw_data_offset(ep->hw_data_buf); // Bits 0-5 should be 0 assert(!(dpram_offset & 0b111111)); // Fill in endpoint control register with buffer offset - uint32_t ep_reg = EP_CTRL_ENABLE_BITS - | EP_CTRL_INTERRUPT_PER_BUFFER - | (ep->transfer_type << EP_CTRL_BUFFER_TYPE_LSB) - | dpram_offset; - if ( bmInterval ) - { - ep_reg |= (uint32_t) ((bmInterval - 1) << EP_CTRL_HOST_INTERRUPT_INTERVAL_LSB); + uint32_t ctrl_value = EP_CTRL_ENABLE_BITS | EP_CTRL_INTERRUPT_PER_BUFFER | + ((uint32_t)transfer_type << EP_CTRL_BUFFER_TYPE_LSB) | dpram_offset; + if (bmInterval) { + ctrl_value |= (uint32_t)((bmInterval - 1) << EP_CTRL_HOST_INTERRUPT_INTERVAL_LSB); } - *ep->endpoint_control = ep_reg; - pico_trace("endpoint control (0x%p) <- 0x%lx\n", ep->endpoint_control, ep_reg); + + io_rw_32 *ctrl_reg = hwep_ctrl_reg_host(ep); + *ctrl_reg = ctrl_value; + pico_trace("endpoint control (0x%p) <- 0x%lx\n", ctrl_reg, ctrl_value); ep->configured = true; - if ( ep != &epx ) - { + if (ep != &epx) { // Endpoint has its own addr_endp and interrupt bits to be setup! // This is an interrupt/async endpoint. so need to set up ADDR_ENDP register with: // - device address // - endpoint number / direction // - preamble - uint32_t reg = (uint32_t) (dev_addr | (num << USB_ADDR_ENDP1_ENDPOINT_LSB)); + uint32_t reg = (uint32_t)(dev_addr | (num << USB_ADDR_ENDP1_ENDPOINT_LSB)); - if ( dir == TUSB_DIR_OUT ) - { + if (dir == TUSB_DIR_OUT) { reg |= USB_ADDR_ENDP1_INTEP_DIR_BITS; } - if ( need_pre(dev_addr) ) - { + if (need_pre(dev_addr)) { reg |= USB_ADDR_ENDP1_INTEP_PREAMBLE_BITS; } usb_hw->int_ep_addr_ctrl[ep->interrupt_num] = reg; @@ -367,8 +325,7 @@ static void _hw_endpoint_init(struct hw_endpoint *ep, uint8_t dev_addr, uint8_t // Finally, enable interrupt that endpoint usb_hw_set->int_ep_ctrl = 1 << (ep->interrupt_num + 1); - // If it's an interrupt endpoint we need to set up the buffer control - // register + // If it's an interrupt endpoint we need to set up the buffer control register } } @@ -382,7 +339,7 @@ bool hcd_init(uint8_t rhport, const tusb_rhport_init_t* rh_init) { assert(rhport == 0); // Reset any previous state - rp2040_usb_init(); + rp2usb_init(); // Force VBUS detect to always present, for now we assume vbus is always provided (without using VBUS En) usb_hw->pwr = USB_USB_PWR_VBUS_DETECT_BITS | USB_USB_PWR_VBUS_DETECT_OVERRIDE_EN_BITS; @@ -466,8 +423,8 @@ void hcd_device_close(uint8_t rhport, uint8_t dev_addr) { // 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; + *hwep_ctrl_reg_host(&epx) = 0; + *hwbuf_ctrl_reg_host(&epx) = 0; hw_endpoint_reset_transfer(&epx); } @@ -482,54 +439,41 @@ void hcd_device_close(uint8_t rhport, uint8_t dev_addr) { // unconfigure the endpoint ep->configured = false; - *ep->endpoint_control = 0; - *ep->buffer_control = 0; + *hwep_ctrl_reg_host(ep) = 0; + *hwbuf_ctrl_reg_host(ep) = 0; hw_endpoint_reset_transfer(ep); } } } } -uint32_t hcd_frame_number(uint8_t rhport) -{ - (void) rhport; +uint32_t hcd_frame_number(uint8_t rhport) { + (void)rhport; return usb_hw->sof_rd; } -void hcd_int_enable(uint8_t rhport) -{ - (void) rhport; - assert(rhport == 0); +void hcd_int_enable(uint8_t rhport) { + (void)rhport; irq_set_enabled(USBCTRL_IRQ, true); } -void hcd_int_disable(uint8_t rhport) -{ - (void) rhport; +void hcd_int_disable(uint8_t rhport) { + (void)rhport; // todo we should check this is disabling from the correct core; note currently this is never called - assert(rhport == 0); irq_set_enabled(USBCTRL_IRQ, false); } //--------------------------------------------------------------------+ // 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, const tusb_desc_endpoint_t *ep_desc) { + (void)rhport; pico_trace("hcd_edpt_open dev_addr %d, ep_addr %d\n", dev_addr, ep_desc->bEndpointAddress); - - // Allocated differently based on if it's an interrupt endpoint or not - struct hw_endpoint *ep = _hw_endpoint_allocate(ep_desc->bmAttributes.xfer); + hw_endpoint_t *ep = hw_endpoint_allocate(ep_desc->bmAttributes.xfer); TU_ASSERT(ep); - _hw_endpoint_init(ep, - dev_addr, - ep_desc->bEndpointAddress, - tu_edpt_packet_size(ep_desc), - ep_desc->bmAttributes.xfer, - ep_desc->bInterval); + hw_endpoint_init(ep, dev_addr, ep_desc->bEndpointAddress, tu_edpt_packet_size(ep_desc), ep_desc->bmAttributes.xfer, + ep_desc->bInterval); return true; } @@ -539,13 +483,12 @@ bool hcd_edpt_close(uint8_t rhport, uint8_t daddr, uint8_t 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 hcd_edpt_xfer(uint8_t rhport, uint8_t dev_addr, uint8_t ep_addr, uint8_t *buffer, uint16_t buflen) { (void) rhport; pico_trace("hcd_edpt_xfer dev_addr %d, ep_addr 0x%x, len %d\n", dev_addr, ep_addr, buflen); - uint8_t const ep_num = tu_edpt_number(ep_addr); + const uint8_t ep_num = tu_edpt_number(ep_addr); tusb_dir_t const ep_dir = tu_edpt_dir(ep_addr); // Get appropriate ep. Either EPX or interrupt endpoint @@ -557,20 +500,18 @@ bool hcd_edpt_xfer(uint8_t rhport, uint8_t dev_addr, uint8_t ep_addr, uint8_t * assert(!ep->active); // Control endpoint can change direction 0x00 <-> 0x80 - if ( ep_addr != ep->ep_addr ) - { + if (ep_addr != ep->ep_addr) { assert(ep_num == 0); // Direction has flipped on endpoint control so re init it but with same properties - _hw_endpoint_init(ep, dev_addr, ep_addr, ep->wMaxPacketSize, ep->transfer_type, 0); + hw_endpoint_init(ep, dev_addr, ep_addr, ep->wMaxPacketSize, TUSB_XFER_CONTROL, 0); } // If a normal transfer (non-interrupt) then initiate using // sie ctrl registers. Otherwise, interrupt ep registers should // already be configured - if ( ep == &epx ) - { - hw_endpoint_xfer_start(ep, buffer, buflen); + if (ep == &epx) { + hw_endpoint_xfer_start(ep, buffer, NULL, buflen); // That has set up buffer control, endpoint control etc // for host we have to initiate the transfer @@ -585,9 +526,8 @@ bool hcd_edpt_xfer(uint8_t rhport, uint8_t dev_addr, uint8_t ep_addr, uint8_t * usb_hw->sie_ctrl = flags & ~USB_SIE_CTRL_START_TRANS_BITS; busy_wait_at_least_cycles(12); usb_hw->sie_ctrl = flags; - }else - { - hw_endpoint_xfer_start(ep, buffer, buflen); + } else { + hw_endpoint_xfer_start(ep, buffer, NULL, buflen); } return true; @@ -611,14 +551,14 @@ bool hcd_setup_send(uint8_t rhport, uint8_t dev_addr, uint8_t const setup_packet } // Configure EP0 struct with setup info for the trans complete - struct hw_endpoint * ep = _hw_endpoint_allocate( (uint8_t) TUSB_XFER_CONTROL); + hw_endpoint_t *ep = hw_endpoint_allocate((uint8_t)TUSB_XFER_CONTROL); TU_ASSERT(ep); // EPX should be inactive assert(!ep->active); // EP0 out - _hw_endpoint_init(ep, dev_addr, 0x00, ep->wMaxPacketSize, 0, 0); + hw_endpoint_init(ep, dev_addr, 0x00, ep->wMaxPacketSize, 0, 0); assert(ep->configured); ep->remaining_len = 8; diff --git a/src/portable/raspberrypi/rp2040/rp2040_usb.c b/src/portable/raspberrypi/rp2040/rp2040_usb.c index 9d0bd762d..3b65f57a4 100644 --- a/src/portable/raspberrypi/rp2040/rp2040_usb.c +++ b/src/portable/raspberrypi/rp2040/rp2040_usb.c @@ -35,34 +35,35 @@ //--------------------------------------------------------------------+ // MACRO CONSTANT TYPEDEF PROTOTYPE //--------------------------------------------------------------------+ -static void _hw_endpoint_xfer_sync(struct hw_endpoint* ep); +static void sync_xfer(hw_endpoint_t *ep); -#if TUD_OPT_RP2040_USB_DEVICE_UFRAME_FIX - static bool e15_is_bulkin_ep(struct hw_endpoint* ep); - static bool e15_is_critical_frame_period(struct hw_endpoint* ep); -#else - #define e15_is_bulkin_ep(x) (false) - #define e15_is_critical_frame_period(x) (false) -#endif - -// if usb hardware is in host mode -TU_ATTR_ALWAYS_INLINE static inline bool is_host_mode(void) { - return (usb_hw->main_ctrl & USB_MAIN_CTRL_HOST_NDEVICE_BITS) ? true : false; -} + #if TUD_OPT_RP2040_USB_DEVICE_UFRAME_FIX +static bool e15_is_critical_frame_period(struct hw_endpoint *ep); + #else + #define e15_is_critical_frame_period(x) (false) + #endif //--------------------------------------------------------------------+ // Implementation //--------------------------------------------------------------------+ // Provide own byte by byte memcpy as not all copies are aligned -static void unaligned_memcpy(void *dst, const void *src, size_t n) { - uint8_t *dst_byte = (uint8_t*)dst; - const uint8_t *src_byte = (const uint8_t*)src; +static void unaligned_memcpy(uint8_t *dst, const uint8_t *src, size_t n) { while (n--) { - *dst_byte++ = *src_byte++; + *dst++ = *src++; } } -void rp2040_usb_init(void) { +void tu_hwfifo_write(volatile void *hwfifo, const uint8_t *src, uint16_t len, const tu_hwfifo_access_t *access_mode) { + (void)access_mode; + unaligned_memcpy((uint8_t *)(uintptr_t)hwfifo, src, len); +} + +void tu_hwfifo_read(const volatile void *hwfifo, uint8_t *dest, uint16_t len, const tu_hwfifo_access_t *access_mode) { + (void)access_mode; + unaligned_memcpy(dest, (const uint8_t *)(uintptr_t)hwfifo, len); +} + +void rp2usb_init(void) { // Reset usb controller reset_block(RESETS_RESET_USBCTRL_BITS); unreset_block_wait(RESETS_RESET_USBCTRL_BITS); @@ -93,35 +94,38 @@ void __tusb_irq_path_func(hw_endpoint_reset_transfer)(struct hw_endpoint* ep) { ep->user_buf = 0; } -void __tusb_irq_path_func(_hw_endpoint_buffer_control_update32)(struct hw_endpoint* ep, uint32_t and_mask, - uint32_t or_mask) { - uint32_t value = 0; +void __tusb_irq_path_func(hwbuf_ctrl_update)(io_rw_32 *buf_ctrl_reg, uint32_t and_mask, uint32_t or_mask) { + const bool is_host = rp2usb_is_host_mode(); + uint32_t value = 0; + uint32_t buf_ctrl = *buf_ctrl_reg; if (and_mask) { - value = *ep->buffer_control & and_mask; + value = buf_ctrl & and_mask; } if (or_mask) { value |= or_mask; if (or_mask & USB_BUF_CTRL_AVAIL) { - if (*ep->buffer_control & USB_BUF_CTRL_AVAIL) { - panic("ep %02X was already available", ep->ep_addr); + if (buf_ctrl & USB_BUF_CTRL_AVAIL) { + panic("buf_ctrl @ 0x%lX already available", (uintptr_t)buf_ctrl_reg); } - *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 + *buf_ctrl_reg = value & ~USB_BUF_CTRL_AVAIL; + + // Section 4.1.2.7.1 (rp2040) / 12.7.3.7.1 (rp2350) Concurrent access: after write to buffer control, we need to + // wait at least 1/48 mhz (usb clock), 12 cycles should be good for 48*12Mhz = 576Mhz. // Don't need delay in host mode as host is in charge - if (!is_host_mode()) { + if (!is_host) { busy_wait_at_least_cycles(12); } } } - *ep->buffer_control = value; + *buf_ctrl_reg = value; } -// prepare buffer, return buffer control -static uint32_t __tusb_irq_path_func(prepare_ep_buffer)(struct hw_endpoint* ep, uint8_t buf_id) { - uint16_t const buflen = tu_min16(ep->remaining_len, ep->wMaxPacketSize); +// prepare buffer, move data if tx, return buffer control +static uint32_t __tusb_irq_path_func(prepare_ep_buffer)(struct hw_endpoint *ep, uint8_t buf_id, bool is_rx) { + const uint16_t buflen = tu_min16(ep->remaining_len, ep->wMaxPacketSize); ep->remaining_len = (uint16_t) (ep->remaining_len - buflen); uint32_t buf_ctrl = buflen | USB_BUF_CTRL_AVAIL; @@ -130,10 +134,18 @@ static uint32_t __tusb_irq_path_func(prepare_ep_buffer)(struct hw_endpoint* ep, buf_ctrl |= ep->next_pid ? USB_BUF_CTRL_DATA1_PID : USB_BUF_CTRL_DATA0_PID; ep->next_pid ^= 1u; - if (!ep->rx) { - // Copy data from user buffer to hw buffer - unaligned_memcpy(ep->hw_data_buf + buf_id * 64, ep->user_buf, buflen); - ep->user_buf += buflen; + if (!is_rx) { + if (buflen) { + // Copy data from user buffer/fifo to hw buffer + uint8_t *hw_buf = ep->hw_data_buf + buf_id * 64; + if (ep->is_xfer_fifo) { + // not in sram, may mess up timing with E15 workaround + tu_hwfifo_write_from_fifo(hw_buf, ep->user_fifo, buflen, NULL); + } else { + unaligned_memcpy(hw_buf, ep->user_buf, buflen); + ep->user_buf += buflen; + } + } // Mark as full buf_ctrl |= USB_BUF_CTRL_FULL; @@ -146,52 +158,75 @@ static uint32_t __tusb_irq_path_func(prepare_ep_buffer)(struct hw_endpoint* ep, buf_ctrl |= USB_BUF_CTRL_LAST; } - if (buf_id) buf_ctrl = buf_ctrl << 16; + if (buf_id) { + buf_ctrl = buf_ctrl << 16; + } return buf_ctrl; } // Prepare buffer control register value void __tusb_irq_path_func(hw_endpoint_start_next_buffer)(struct hw_endpoint* ep) { - uint32_t ep_ctrl = *ep->endpoint_control; + const tusb_dir_t dir = tu_edpt_dir(ep->ep_addr); + bool is_rx; + bool is_host = false; + io_rw_32 *ep_ctrl_reg; + io_rw_32 *buf_ctrl_reg; + + #if CFG_TUH_ENABLED + is_host = rp2usb_is_host_mode(); + if (is_host) { + buf_ctrl_reg = hwbuf_ctrl_reg_host(ep); + ep_ctrl_reg = hwep_ctrl_reg_host(ep); + is_rx = (dir == TUSB_DIR_IN); + } else + #endif + { + buf_ctrl_reg = hwbuf_ctrl_reg_device(ep); + ep_ctrl_reg = hwep_ctrl_reg_device(ep); + is_rx = (dir == TUSB_DIR_OUT); + } // always compute and start with buffer 0 - uint32_t buf_ctrl = prepare_ep_buffer(ep, 0) | USB_BUF_CTRL_SEL; + uint32_t buf_ctrl = prepare_ep_buffer(ep, 0, is_rx) | USB_BUF_CTRL_SEL; - // For now: skip double buffered for OUT endpoint in Device mode, since - // host could send < 64 bytes and cause short packet on buffer0 - // NOTE: this could happen to Host mode IN endpoint - // Also, Host mode "interrupt" endpoint hardware is only single buffered, - // NOTE2: Currently Host bulk is implemented using "interrupt" endpoint - bool const is_host = is_host_mode(); - bool const force_single = (!is_host && !tu_edpt_dir(ep->ep_addr)) || - (is_host && tu_edpt_number(ep->ep_addr) != 0); + // EP0 has no endpoint control register, also usbd only schedule 1 packet at a time (single buffer) + if (ep_ctrl_reg != NULL) { + uint32_t ep_ctrl = *ep_ctrl_reg; - if (ep->remaining_len && !force_single) { - // Use buffer 1 (double buffered) if there is still data - // TODO: Isochronous for buffer1 bit-field is different than CBI (control bulk, interrupt) + // For now: skip double buffered for RX e.g OUT endpoint in Device mode, since host could send < 64 bytes and cause + // short packet on buffer0 + // NOTE: this could happen to Host mode IN endpoint Also, Host mode "interrupt" endpoint hardware is only single + // buffered, + // NOTE2: Currently Host bulk is implemented using "interrupt" endpoint + const bool force_single = (!is_host && is_rx) || (is_host && tu_edpt_number(ep->ep_addr) != 0); - buf_ctrl |= prepare_ep_buffer(ep, 1); + if (ep->remaining_len && !force_single) { + // Use buffer 1 (double buffered) if there is still data + // TODO: Isochronous for buffer1 bit-field is different than CBI (control bulk, interrupt) - // Set endpoint control double buffered bit if needed - ep_ctrl &= ~EP_CTRL_INTERRUPT_PER_BUFFER; - ep_ctrl |= EP_CTRL_DOUBLE_BUFFERED_BITS | EP_CTRL_INTERRUPT_PER_DOUBLE_BUFFER; - } else { - // Single buffered since 1 is enough - ep_ctrl &= ~(EP_CTRL_DOUBLE_BUFFERED_BITS | EP_CTRL_INTERRUPT_PER_DOUBLE_BUFFER); - ep_ctrl |= EP_CTRL_INTERRUPT_PER_BUFFER; - } + buf_ctrl |= prepare_ep_buffer(ep, 1, is_rx); - *ep->endpoint_control = ep_ctrl; + // Set endpoint control double buffered bit if needed + ep_ctrl &= ~EP_CTRL_INTERRUPT_PER_BUFFER; + ep_ctrl |= EP_CTRL_DOUBLE_BUFFERED_BITS | EP_CTRL_INTERRUPT_PER_DOUBLE_BUFFER; + } else { + // Single buffered since 1 is enough + ep_ctrl &= ~(EP_CTRL_DOUBLE_BUFFERED_BITS | EP_CTRL_INTERRUPT_PER_DOUBLE_BUFFER); + ep_ctrl |= EP_CTRL_INTERRUPT_PER_BUFFER; + } + + *ep_ctrl_reg = ep_ctrl; + } TU_LOG(3, " Prepare BufCtrl: [0] = 0x%04x [1] = 0x%04x\r\n", tu_u32_low16(buf_ctrl), tu_u32_high16(buf_ctrl)); // Finally, write to buffer_control which will trigger the transfer // the next time the controller polls this dpram address - _hw_endpoint_buffer_control_set_value32(ep, buf_ctrl); + hwbuf_ctrl_set(buf_ctrl_reg, buf_ctrl); } -void hw_endpoint_xfer_start(struct hw_endpoint* ep, uint8_t* buffer, uint16_t total_len) { +void hw_endpoint_xfer_start(struct hw_endpoint *ep, uint8_t *buffer, tu_fifo_t *ff, uint16_t total_len) { hw_endpoint_lock_update(ep, 1); if (ep->active) { @@ -204,15 +239,25 @@ void hw_endpoint_xfer_start(struct hw_endpoint* ep, uint8_t* buffer, uint16_t to ep->remaining_len = total_len; ep->xferred_len = 0; ep->active = true; - ep->user_buf = buffer; - if (e15_is_bulkin_ep(ep)) { + if (ff != NULL) { + ep->user_fifo = ff; + ep->is_xfer_fifo = true; + } else { + ep->user_buf = buffer; + ep->is_xfer_fifo = false; + } + + #if TUD_OPT_RP2040_USB_DEVICE_UFRAME_FIX + if (ep->e15_bulk_in) { usb_hw_set->inte = USB_INTS_DEV_SOF_BITS; } if (e15_is_critical_frame_period(ep)) { - ep->pending = 1; - } else { + ep->pending = 1; // skip transfer if we are in critical frame period + } else + #endif + { hw_endpoint_start_next_buffer(ep); } @@ -220,31 +265,37 @@ void hw_endpoint_xfer_start(struct hw_endpoint* ep, uint8_t* buffer, uint16_t to } // sync endpoint buffer and return transferred bytes -static uint16_t __tusb_irq_path_func(sync_ep_buffer)(struct hw_endpoint* ep, uint8_t buf_id) { - uint32_t buf_ctrl = _hw_endpoint_buffer_control_get_value32(ep); - if (buf_id) buf_ctrl = buf_ctrl >> 16; +static uint16_t __tusb_irq_path_func(sync_ep_buffer)(hw_endpoint_t *ep, io_rw_32 *buf_ctrl_reg, uint8_t buf_id, + bool is_rx) { + uint32_t buf_ctrl = *buf_ctrl_reg; + if (buf_id) { + buf_ctrl = buf_ctrl >> 16; + } - uint16_t xferred_bytes = buf_ctrl & USB_BUF_CTRL_LEN_MASK; + const uint16_t xferred_bytes = buf_ctrl & USB_BUF_CTRL_LEN_MASK; - if (!ep->rx) { + if (!is_rx) { // We are continuing a transfer here. If we are TX, we have successfully // sent some data can increase the length we have sent assert(!(buf_ctrl & USB_BUF_CTRL_FULL)); - - ep->xferred_len = (uint16_t) (ep->xferred_len + xferred_bytes); } else { // If we have received some data, so can increase the length // we have received AFTER we have copied it to the user buffer at the appropriate offset assert(buf_ctrl & USB_BUF_CTRL_FULL); - unaligned_memcpy(ep->user_buf, ep->hw_data_buf + buf_id * 64, xferred_bytes); - ep->xferred_len = (uint16_t) (ep->xferred_len + xferred_bytes); - ep->user_buf += xferred_bytes; + uint8_t *hw_buf = ep->hw_data_buf + buf_id * 64; + if (ep->is_xfer_fifo) { + // not in sram, may mess up timing with E15 workaround + tu_hwfifo_read_to_fifo(hw_buf, ep->user_fifo, xferred_bytes, NULL); + } else { + unaligned_memcpy(ep->user_buf, hw_buf, xferred_bytes); + ep->user_buf += xferred_bytes; + } } + ep->xferred_len += xferred_bytes; // Short packet if (xferred_bytes < ep->wMaxPacketSize) { - pico_trace(" Short packet on buffer %d with %u bytes\r\n", buf_id, xferred_bytes); // Reduce total length as this is last packet ep->remaining_len = 0; } @@ -252,21 +303,38 @@ static uint16_t __tusb_irq_path_func(sync_ep_buffer)(struct hw_endpoint* ep, uin return xferred_bytes; } -static void __tusb_irq_path_func(_hw_endpoint_xfer_sync)(struct hw_endpoint* ep) { - // Update hw endpoint struct with info from hardware - // after a buff status interrupt +// Update hw endpoint struct with info from hardware after a buff status interrupt +static void __tusb_irq_path_func(sync_xfer)(hw_endpoint_t *ep) { + // const uint8_t ep_num = tu_edpt_number(ep->ep_addr); + const tusb_dir_t dir = tu_edpt_dir(ep->ep_addr); - uint32_t __unused buf_ctrl = _hw_endpoint_buffer_control_get_value32(ep); - TU_LOG(3, " Sync BufCtrl: [0] = 0x%04x [1] = 0x%04x\r\n", tu_u32_low16(buf_ctrl), tu_u32_high16(buf_ctrl)); + io_rw_32 *buf_ctrl_reg; + io_rw_32 *ep_ctrl_reg; + bool is_rx; - // always sync buffer 0 - uint16_t buf0_bytes = sync_ep_buffer(ep, 0); + #if CFG_TUH_ENABLED + const bool is_host = rp2usb_is_host_mode(); + if (is_host) { + buf_ctrl_reg = hwbuf_ctrl_reg_host(ep); + ep_ctrl_reg = hwep_ctrl_reg_host(ep); + is_rx = (dir == TUSB_DIR_IN); + } else + #endif + { + buf_ctrl_reg = hwbuf_ctrl_reg_device(ep); + ep_ctrl_reg = hwep_ctrl_reg_device(ep); + is_rx = (dir == TUSB_DIR_OUT); + } + + TU_LOG(3, " Sync BufCtrl: [0] = 0x%04x [1] = 0x%04x\r\n", tu_u32_low16(*buf_ctrl_reg), + tu_u32_high16(*buf_ctrl_reg)); + uint16_t buf0_bytes = sync_ep_buffer(ep, buf_ctrl_reg, 0, is_rx); // always sync buffer 0 // sync buffer 1 if double buffered - if ((*ep->endpoint_control) & EP_CTRL_DOUBLE_BUFFERED_BITS) { + if (ep_ctrl_reg != NULL && (*ep_ctrl_reg) & EP_CTRL_DOUBLE_BUFFERED_BITS) { if (buf0_bytes == ep->wMaxPacketSize) { // sync buffer 1 if not short packet - sync_ep_buffer(ep, 1); + sync_ep_buffer(ep, buf_ctrl_reg, 1, is_rx); } else { // short packet on buffer 0 // TODO couldn't figure out how to handle this case which happen with net_lwip_webserver example @@ -287,7 +355,8 @@ static void __tusb_irq_path_func(_hw_endpoint_xfer_sync)(struct hw_endpoint* ep) ep_ctrl &= ~(EP_CTRL_DOUBLE_BUFFERED_BITS | EP_CTRL_INTERRUPT_PER_DOUBLE_BUFFER); ep_ctrl |= EP_CTRL_INTERRUPT_PER_BUFFER; - _hw_endpoint_buffer_control_set_value32(ep, 0); + io_rw_32 *buf_ctrl_reg = is_host ? hwbuf_ctrl_reg_host(ep) : hwbuf_ctrl_reg_device(ep); + hwbuf_ctrl_set(buf_ctrl_reg, 0); usb_hw->abort &= ~TU_BIT(ep_id); @@ -307,8 +376,7 @@ bool __tusb_irq_path_func(hw_endpoint_xfer_continue)(struct hw_endpoint* ep) { panic("Can't continue xfer on inactive ep %02X", ep->ep_addr); } - // Update EP struct from hardware state - _hw_endpoint_xfer_sync(ep); + sync_xfer(ep); // Update EP struct from hardware state // Now we have synced our state with the hardware. Is there more data to transfer? // If we are done then notify tinyusb @@ -318,9 +386,12 @@ bool __tusb_irq_path_func(hw_endpoint_xfer_continue)(struct hw_endpoint* ep) { hw_endpoint_lock_update(ep, -1); return true; } else { + #if TUD_OPT_RP2040_USB_DEVICE_UFRAME_FIX if (e15_is_critical_frame_period(ep)) { ep->pending = 1; - } else { + } else + #endif + { hw_endpoint_start_next_buffer(ep); } } @@ -335,6 +406,7 @@ bool __tusb_irq_path_func(hw_endpoint_xfer_continue)(struct hw_endpoint* ep) { //--------------------------------------------------------------------+ #if TUD_OPT_RP2040_USB_DEVICE_UFRAME_FIX +// E15 is fixed with RP2350 /* Don't mark IN buffers as available during the last 200us of a full-speed frame. This avoids a situation seen with the USB2.0 hub on a Raspberry @@ -354,16 +426,12 @@ bool __tusb_irq_path_func(hw_endpoint_xfer_continue)(struct hw_endpoint* ep) { volatile uint32_t e15_last_sof = 0; -// check if Errata 15 is needed for this endpoint i.e device bulk-in -static bool __tusb_irq_path_func(e15_is_bulkin_ep)(struct hw_endpoint* ep) { - return (!is_host_mode() && tu_edpt_dir(ep->ep_addr) == TUSB_DIR_IN && - ep->transfer_type == TUSB_XFER_BULK); -} - // check if we need to apply Errata 15 workaround : i.e // Endpoint is BULK IN and is currently in critical frame period i.e 20% of last usb frame static bool __tusb_irq_path_func(e15_is_critical_frame_period)(struct hw_endpoint* ep) { - TU_VERIFY(e15_is_bulkin_ep(ep)); + if (!ep->e15_bulk_in) { + return false; + } /* Avoid the last 200us (uframe 6.5-7) of a frame, up to the EOF2 point. * The device state machine cannot recover from receiving an incorrect PID diff --git a/src/portable/raspberrypi/rp2040/rp2040_usb.h b/src/portable/raspberrypi/rp2040/rp2040_usb.h index d4d29a816..c03dc34b2 100644 --- a/src/portable/raspberrypi/rp2040/rp2040_usb.h +++ b/src/portable/raspberrypi/rp2040/rp2040_usb.h @@ -1,29 +1,44 @@ #ifndef RP2040_COMMON_H_ #define RP2040_COMMON_H_ -#if defined(RP2040_USB_HOST_MODE) && defined(RP2040_USB_DEVICE_MODE) -#error TinyUSB device and host mode not supported at the same time -#endif - -#include "common/tusb_common.h" - #include "pico.h" #include "hardware/structs/usb.h" #include "hardware/irq.h" #include "hardware/resets.h" #include "hardware/timer.h" -#if defined(PICO_RP2040_USB_DEVICE_ENUMERATION_FIX) && !defined(TUD_OPT_RP2040_USB_DEVICE_ENUMERATION_FIX) -#define TUD_OPT_RP2040_USB_DEVICE_ENUMERATION_FIX PICO_RP2040_USB_DEVICE_ENUMERATION_FIX +#include "common/tusb_common.h" +#include "osal/osal.h" +#include "common/tusb_fifo.h" + +#if defined(RP2040_USB_HOST_MODE) && defined(RP2040_USB_DEVICE_MODE) + #error TinyUSB device and host mode not supported at the same time +#endif + +// E5 and E15 only apply to RP2040 +#if defined(PICO_RP2040) && PICO_RP2040 == 1 + // RP2040 E5: USB device fails to exit RESET state on busy USB bus. + #if defined(PICO_RP2040_USB_DEVICE_ENUMERATION_FIX) && !defined(TUD_OPT_RP2040_USB_DEVICE_ENUMERATION_FIX) + #define TUD_OPT_RP2040_USB_DEVICE_ENUMERATION_FIX PICO_RP2040_USB_DEVICE_ENUMERATION_FIX + #endif + + // RP2040 E15: USB Device controller will hang if certain bus errors occur during an IN transfer. + #if defined(PICO_RP2040_USB_DEVICE_UFRAME_FIX) && !defined(TUD_OPT_RP2040_USB_DEVICE_UFRAME_FIX) + #define TUD_OPT_RP2040_USB_DEVICE_UFRAME_FIX PICO_RP2040_USB_DEVICE_UFRAME_FIX + #endif +#endif + +#ifndef TUD_OPT_RP2040_USB_DEVICE_ENUMERATION_FIX + #define TUD_OPT_RP2040_USB_DEVICE_ENUMERATION_FIX 0 #endif -#if defined(PICO_RP2040_USB_DEVICE_UFRAME_FIX) && !defined(TUD_OPT_RP2040_USB_DEVICE_UFRAME_FIX) -#define TUD_OPT_RP2040_USB_DEVICE_UFRAME_FIX PICO_RP2040_USB_DEVICE_UFRAME_FIX +#ifndef TUD_OPT_RP2040_USB_DEVICE_UFRAME_FIX + #define TUD_OPT_RP2040_USB_DEVICE_UFRAME_FIX 0 #endif #if TUD_OPT_RP2040_USB_DEVICE_UFRAME_FIX -#undef PICO_RP2040_USB_FAST_IRQ -#define PICO_RP2040_USB_FAST_IRQ 1 + #undef PICO_RP2040_USB_FAST_IRQ + #define PICO_RP2040_USB_FAST_IRQ 1 #endif #ifndef PICO_RP2040_USB_FAST_IRQ @@ -36,6 +51,9 @@ #define __tusb_irq_path_func(x) x #endif +//--------------------------------------------------------------------+ +// +//--------------------------------------------------------------------+ #define usb_hw_set ((usb_hw_t *) hw_set_alias_untyped(usb_hw)) #define usb_hw_clear ((usb_hw_t *) hw_clear_alias_untyped(usb_hw)) @@ -43,63 +61,48 @@ #define pico_trace(...) TU_LOG(3, __VA_ARGS__) // Hardware information per endpoint -typedef struct hw_endpoint -{ - // Is this a valid struct - bool configured; - - // Transfer direction (i.e. IN is rx for host but tx for device) - // allows us to common up transfer functions - bool rx; - - uint8_t ep_addr; - uint8_t next_pid; - - // Endpoint control register - io_rw_32 *endpoint_control; - - // Buffer control register - io_rw_32 *buffer_control; - - // Buffer pointer in usb dpram - uint8_t *hw_data_buf; - - // User buffer in main memory - uint8_t *user_buf; - - // Current transfer information - uint16_t remaining_len; - uint16_t xferred_len; +typedef struct hw_endpoint { + uint8_t ep_addr; + uint8_t next_pid; + bool active; // transferring data + bool is_xfer_fifo; // transfer using fifo - // Data needed from EP descriptor - uint16_t wMaxPacketSize; - - // Endpoint is in use - bool active; - - // Interrupt, bulk, etc - uint8_t transfer_type; - - // Transfer scheduled but not active - uint8_t pending; +#if TUD_OPT_RP2040_USB_DEVICE_UFRAME_FIX + bool e15_bulk_in; // Errata15 device bulk in + uint8_t pending; // Transfer scheduled but not active +#endif #if CFG_TUH_ENABLED - // Only needed for host - uint8_t dev_addr; - - // If interrupt endpoint - uint8_t interrupt_num; + bool configured; // Is this a valid struct + uint8_t dev_addr; + uint8_t interrupt_num; // for host interrupt endpoints #endif + uint16_t wMaxPacketSize; + uint8_t *hw_data_buf; // Buffer pointer in usb dpram + + // transfer info + union { + uint8_t *user_buf; // User buffer in main memory + tu_fifo_t *user_fifo; + }; + uint16_t remaining_len; + uint16_t xferred_len; + } hw_endpoint_t; #if TUD_OPT_RP2040_USB_DEVICE_UFRAME_FIX extern volatile uint32_t e15_last_sof; #endif -void rp2040_usb_init(void); +void rp2usb_init(void); + +// if usb hardware is in host mode +TU_ATTR_ALWAYS_INLINE static inline bool rp2usb_is_host_mode(void) { + return (usb_hw->main_ctrl & USB_MAIN_CTRL_HOST_NDEVICE_BITS) ? true : false; +} -void hw_endpoint_xfer_start(struct hw_endpoint *ep, uint8_t *buffer, uint16_t total_len); +void hw_endpoint_xfer_start(struct hw_endpoint *ep, uint8_t *buffer, tu_fifo_t *ff, uint16_t total_len); bool hw_endpoint_xfer_continue(struct hw_endpoint *ep); void hw_endpoint_reset_transfer(struct hw_endpoint *ep); void hw_endpoint_start_next_buffer(struct hw_endpoint *ep); @@ -110,34 +113,60 @@ TU_ATTR_ALWAYS_INLINE static inline void hw_endpoint_lock_update(__unused struct // sense to have worker and IRQ on same core, however I think using critsec is about equivalent. } -void _hw_endpoint_buffer_control_update32(struct hw_endpoint *ep, uint32_t and_mask, uint32_t or_mask); +// #if CFG_TUD_ENABLED +TU_ATTR_ALWAYS_INLINE static inline io_rw_32 *hwep_ctrl_reg_device(struct hw_endpoint *ep) { + uint8_t const epnum = tu_edpt_number(ep->ep_addr); + const uint8_t dir = (uint8_t)tu_edpt_dir(ep->ep_addr); + if (epnum == 0) { + // EP0 has no endpoint control register because the buffer offsets are fixed and always enabled + return NULL; + } + return (dir == TUSB_DIR_IN) ? &usb_dpram->ep_ctrl[epnum - 1].in : &usb_dpram->ep_ctrl[epnum - 1].out; +} -TU_ATTR_ALWAYS_INLINE static inline uint32_t _hw_endpoint_buffer_control_get_value32 (struct hw_endpoint *ep) -{ - return *ep->buffer_control; +TU_ATTR_ALWAYS_INLINE static inline io_rw_32 *hwbuf_ctrl_reg_device(struct hw_endpoint *ep) { + const uint8_t epnum = tu_edpt_number(ep->ep_addr); + const uint8_t dir = (uint8_t)tu_edpt_dir(ep->ep_addr); + return (dir == TUSB_DIR_IN) ? &usb_dpram->ep_buf_ctrl[epnum].in : &usb_dpram->ep_buf_ctrl[epnum].out; } +// #endif -TU_ATTR_ALWAYS_INLINE static inline void _hw_endpoint_buffer_control_set_value32 (struct hw_endpoint *ep, uint32_t value) -{ - _hw_endpoint_buffer_control_update32(ep, 0, value); +#if CFG_TUH_ENABLED +TU_ATTR_ALWAYS_INLINE static inline io_rw_32 *hwep_ctrl_reg_host(struct hw_endpoint *ep) { + if (tu_edpt_number(ep->ep_addr) == 0) { + return &usbh_dpram->epx_ctrl; + } + return &usbh_dpram->int_ep_ctrl[ep->interrupt_num].ctrl; } -TU_ATTR_ALWAYS_INLINE static inline void _hw_endpoint_buffer_control_set_mask32 (struct hw_endpoint *ep, uint32_t value) -{ - _hw_endpoint_buffer_control_update32(ep, ~value, value); +TU_ATTR_ALWAYS_INLINE static inline io_rw_32 *hwbuf_ctrl_reg_host(struct hw_endpoint *ep) { + if (tu_edpt_number(ep->ep_addr) == 0) { + return &usbh_dpram->epx_buf_ctrl; + } + return &usbh_dpram->int_ep_buffer_ctrl[ep->interrupt_num].ctrl; } +#endif -TU_ATTR_ALWAYS_INLINE static inline void _hw_endpoint_buffer_control_clear_mask32 (struct hw_endpoint *ep, uint32_t value) -{ - _hw_endpoint_buffer_control_update32(ep, ~value, 0); +//--------------------------------------------------------------------+ +// +//--------------------------------------------------------------------+ +void hwbuf_ctrl_update(io_rw_32 *buf_ctrl_reg, uint32_t and_mask, uint32_t or_mask); + +TU_ATTR_ALWAYS_INLINE static inline void hwbuf_ctrl_set(io_rw_32 *buf_ctrl_reg, uint32_t value) { + hwbuf_ctrl_update(buf_ctrl_reg, 0, value); } -static inline uintptr_t hw_data_offset (uint8_t *buf) -{ - // Remove usb base from buffer pointer - return (uintptr_t) buf ^ (uintptr_t) usb_dpram; +TU_ATTR_ALWAYS_INLINE static inline void hwbuf_ctrl_set_mask(io_rw_32 *buf_ctrl_reg, uint32_t value) { + hwbuf_ctrl_update(buf_ctrl_reg, ~value, value); } -extern const char *ep_dir_string[]; +TU_ATTR_ALWAYS_INLINE static inline void hwbuf_ctrl_clear_mask(io_rw_32 *buf_ctrl_reg, uint32_t value) { + hwbuf_ctrl_update(buf_ctrl_reg, ~value, 0); +} + +static inline uintptr_t hw_data_offset(uint8_t *buf) { + // Remove usb base from buffer pointer + return (uintptr_t)buf ^ (uintptr_t)usb_dpram; +} #endif diff --git a/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c b/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c index 22a9e4af8..a6abc6244 100644 --- a/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c +++ b/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c @@ -833,7 +833,7 @@ void dcd_int_disable(uint8_t rhport) { fsdev_int_disable(rhport); } - #if defined(USB_BCDR_DPPU) || defined(SYSCFG_PMC_USB_PU) + #if defined(USB_BCDR_DPPU) || defined(SYSCFG_PMC_USB_PU) || defined(EXTEN_USBD_PU_EN) void dcd_connect(uint8_t rhport) { fsdev_connect(rhport); } diff --git a/src/portable/st/stm32_fsdev/fsdev_common.h b/src/portable/st/stm32_fsdev/fsdev_common.h index c53e345b0..b749a92ff 100644 --- a/src/portable/st/stm32_fsdev/fsdev_common.h +++ b/src/portable/st/stm32_fsdev/fsdev_common.h @@ -63,23 +63,21 @@ TU_VERIFY_STATIC(FSDEV_BTABLE_BASE % 8 == 0, "BTABLE base must be aligned to 8 b // CFG_TUSB_FSDEV_PMA_SIZE is PMA buffer size in bytes. // - 512-byte devices, access with a stride of two words (use every other 16-bit address) -// - 1024-byte devices, access with a stride of one word (use every 16-bit address) +// - 1024-byte devices, access with a stride of one word (use every 16-bit address) or 32-bit address // - 2048-byte devices, access with 32-bit address - -// For purposes of accessing the packet -#if CFG_TUSB_FSDEV_PMA_SIZE == 512 - // 1x16 bit / word access scheme - #define FSDEV_PMA_STRIDE 2 - #define pma_access_scheme TU_ATTR_ALIGNED(4) -#elif CFG_TUSB_FSDEV_PMA_SIZE == 1024 - // 2x16 bit / word access scheme - #define FSDEV_PMA_STRIDE 1 - #define pma_access_scheme -#elif CFG_TUSB_FSDEV_PMA_SIZE == 2048 +#if CFG_TUSB_FSDEV_PMA_SIZE == 2048 || TU_CHECK_MCU(OPT_MCU_STM32U0) // 32 bit access scheme #define FSDEV_BUS_32BIT #define FSDEV_PMA_STRIDE 1 #define pma_access_scheme +#elif CFG_TUSB_FSDEV_PMA_SIZE == 1024 + // 2x16 bit / word access scheme + #define FSDEV_PMA_STRIDE 1 + #define pma_access_scheme +#elif CFG_TUSB_FSDEV_PMA_SIZE == 512 + // 1x16 bit / word access scheme + #define FSDEV_PMA_STRIDE 2 + #define pma_access_scheme TU_ATTR_ALIGNED(4) #endif // The fsdev_bus_t type can be used for both register and PMA access necessities diff --git a/src/portable/synopsys/dwc2/dcd_dwc2.c b/src/portable/synopsys/dwc2/dcd_dwc2.c index 57dcb6fba..cb93b99a6 100644 --- a/src/portable/synopsys/dwc2/dcd_dwc2.c +++ b/src/portable/synopsys/dwc2/dcd_dwc2.c @@ -77,9 +77,7 @@ CFG_TUD_MEM_SECTION static struct { TUD_EPBUF_DEF(setup_packet, 8); } _dcd_usbbuf; -static tud_configure_dwc2_t _tud_cfg = { - .bm_double_buffered = 0 -}; +static tud_configure_dwc2_t _tud_cfg = CFG_TUD_CONFIGURE_DWC2_DEFAULT; TU_ATTR_ALWAYS_INLINE static inline uint8_t dwc2_ep_count(const dwc2_regs_t* dwc2) { #if TU_CHECK_MCU(OPT_MCU_GD32VF103) @@ -444,14 +442,14 @@ bool dcd_init(uint8_t rhport, const tusb_rhport_init_t* rh_init) { tu_memclr(&_dcd_data, sizeof(_dcd_data)); // Core Initialization - const bool is_highspeed = dwc2_core_is_highspeed(dwc2, TUSB_ROLE_DEVICE); + const bool is_hs_phy = dwc2_core_is_highspeed_phy(dwc2, TUD_OPT_HIGH_SPEED); const bool is_dma = dma_device_enabled(dwc2); - TU_ASSERT(dwc2_core_init(rhport, is_highspeed, is_dma)); + TU_ASSERT(dwc2_core_init(rhport, is_hs_phy, is_dma)); //------------- 7.1 Device Initialization -------------// // Set device max speed uint32_t dcfg = dwc2->dcfg & ~DCFG_DSPD_Msk; - if (is_highspeed) { + if (is_hs_phy) { // dcfg Highspeed's mask is 0 // XCVRDLY: transceiver delay between xcvr_sel and txvalid during device chirp is required @@ -472,13 +470,16 @@ bool dcd_init(uint8_t rhport, const tusb_rhport_init_t* rh_init) { // Force device mode dwc2->gusbcfg = (dwc2->gusbcfg & ~GUSBCFG_FHMOD) | GUSBCFG_FDMOD; - // Clear A override, force B Valid - dwc2->gotgctl = (dwc2->gotgctl & ~GOTGCTL_AVALOEN) | GOTGCTL_BVALOEN | GOTGCTL_BVALOVAL; + // OTG Ctrl + uint32_t gotgctl = dwc2->gotgctl & ~GOTGCTL_AVALOEN; // Clear A-override + if (!_tud_cfg.vbus_sensing) { + gotgctl |= GOTGCTL_BVALOEN | GOTGCTL_BVALOVAL; // force B Valid if not sensing VBus + } + dwc2->gotgctl = gotgctl; -#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 + #ifdef TUP_USBIP_DWC2_STM32 + dwc2_stm32_gccfg_cfg(dwc2, _tud_cfg.vbus_sensing, false); + #endif // Enable required interrupts dwc2->gintmsk |= GINTMSK_OTGINT | GINTMSK_USBRST | GINTMSK_ENUMDNEM | GINTMSK_WUIM; @@ -792,7 +793,7 @@ static void handle_bus_reset(uint8_t rhport) { dwc2->epout[0].doeptsiz |= (3 << DOEPTSIZ_STUPCNT_Pos); } - dwc2->gintmsk |= GINTMSK_OEPINT | GINTMSK_IEPINT | GINTMSK_IISOIXFRM; + dwc2->gintmsk |= GINTMSK_OTGINT | GINTMSK_OEPINT | GINTMSK_IEPINT | GINTMSK_IISOIXFRM; } static void handle_enum_done(uint8_t rhport) { @@ -1192,6 +1193,7 @@ void dcd_int_handler(uint8_t rhport) { const uint32_t otg_int = dwc2->gotgint; if (otg_int & GOTGINT_SEDET) { + dwc2->gintmsk &= ~GINTMSK_OTGINT; dcd_event_bus_signal(rhport, DCD_EVENT_UNPLUGGED, true); } diff --git a/src/portable/synopsys/dwc2/dwc2_at32.h b/src/portable/synopsys/dwc2/dwc2_at32.h index 513495eb1..10824ae92 100644 --- a/src/portable/synopsys/dwc2/dwc2_at32.h +++ b/src/portable/synopsys/dwc2/dwc2_at32.h @@ -61,6 +61,11 @@ #define OTG1_FIFO_SIZE 1280 #define OTG1_IRQn OTGFS1_IRQn #define DWC2_OTG1_REG_BASE 0x50000000UL +#elif CFG_TUSB_MCU == OPT_MCU_AT32F45X + #include <at32f45x.h> + #define OTG1_FIFO_SIZE 1280 + #define OTG1_IRQn OTGFS1_IRQn + #define DWC2_OTG1_REG_BASE 0x50000000UL #endif #ifdef __cplusplus diff --git a/src/portable/synopsys/dwc2/dwc2_common.c b/src/portable/synopsys/dwc2/dwc2_common.c index ce38ed6ec..a6afc3154 100644 --- a/src/portable/synopsys/dwc2/dwc2_common.c +++ b/src/portable/synopsys/dwc2/dwc2_common.c @@ -60,6 +60,7 @@ static void reset_core(dwc2_regs_t* dwc2) { while (!(dwc2->grstctl & GRSTCTL_AHBIDL)) {} // wait for AHB master IDLE } +// Dedicated FS PHY is internal with a clock 48Mhz. static void phy_fs_init(dwc2_regs_t* dwc2) { TU_LOG(DWC2_COMMON_DEBUG, "Fullspeed PHY init\r\n"); @@ -86,6 +87,13 @@ static void phy_fs_init(dwc2_regs_t* dwc2) { dwc2_phy_update(dwc2, GHWCFG2_HSPHY_NOT_SUPPORTED); } +/* dwc2 has 2 highspeed PHYs options + * - UTMI+ is internal highspeed PHY, can be clocked at 30/60 Mhz for fullspeed or 60 Mhz for highspeed. Can be either + * 8 or 16-bit interface. + * - ULPI is external highspeed PHY, clocked at 60Mhz with 8-bit interface. + * + * In addition, UTMI+/ULPI can be shared to run at fullspeed mode with 48Mhz + */ static void phy_hs_init(dwc2_regs_t* dwc2) { uint32_t gusbcfg = dwc2->gusbcfg; const dwc2_ghwcfg2_t ghwcfg2 = {.value = dwc2->ghwcfg2}; @@ -179,32 +187,20 @@ 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; - } -#endif -#if CFG_TUH_ENABLED - if (role == TUSB_ROLE_HOST && !TUH_OPT_HIGH_SPEED) { - return false; - } -#endif +bool dwc2_core_is_highspeed_phy(dwc2_regs_t* dwc2, bool prefer_hs_phy) { + const dwc2_ghwcfg2_t ghwcfg2 = {.value = dwc2->ghwcfg2}; + const bool has_hs_phy = (ghwcfg2.hs_phy_type != GHWCFG2_HSPHY_NOT_SUPPORTED); - const dwc2_ghwcfg2_t ghwcfg2 = {.value = dwc2->ghwcfg2}; - return ghwcfg2.hs_phy_type != GHWCFG2_HSPHY_NOT_SUPPORTED; + if (prefer_hs_phy) { + return has_hs_phy; + } else { + const bool has_fs_phy = (ghwcfg2.fs_phy_type != GHWCFG2_FSPHY_NOT_SUPPORTED); + // false if has fs phy, otherwise true since hs phy is the only available phy + return !has_fs_phy && has_hs_phy; + } } -/* dwc2 has several PHYs option - * - UTMI+ is internal highspeed PHY, clock can be 30 Mhz (8-bit) or 60 Mhz (16-bit) - * - ULPI is external highspeed PHY, clock is 60Mhz with only 8-bit interface - * - Dedicated FS PHY is internal with clock 48Mhz. - * - * In addition, UTMI+/ULPI can be shared to run at fullspeed mode with 48Mhz - * -*/ -bool dwc2_core_init(uint8_t rhport, bool is_highspeed, bool is_dma) { +bool dwc2_core_init(uint8_t rhport, bool is_hs_phy, bool is_dma) { dwc2_regs_t* dwc2 = DWC2_REG(rhport); // Check Synopsys ID register, failed if controller clock/power is not enabled @@ -213,7 +209,7 @@ bool dwc2_core_init(uint8_t rhport, bool is_highspeed, bool is_dma) { // disable global interrupt dwc2->gahbcfg &= ~GAHBCFG_GINT; - if (is_highspeed) { + if (is_hs_phy) { phy_hs_init(dwc2); } else { phy_fs_init(dwc2); diff --git a/src/portable/synopsys/dwc2/dwc2_common.h b/src/portable/synopsys/dwc2/dwc2_common.h index af532dc5e..c74ad2233 100644 --- a/src/portable/synopsys/dwc2/dwc2_common.h +++ b/src/portable/synopsys/dwc2/dwc2_common.h @@ -84,8 +84,9 @@ TU_ATTR_ALWAYS_INLINE static inline dwc2_regs_t* DWC2_REG(uint8_t rhport) { return (dwc2_regs_t*)_dwc2_controller[rhport].reg_base; } -bool dwc2_core_is_highspeed(dwc2_regs_t* dwc2, tusb_role_t role); -bool dwc2_core_init(uint8_t rhport, bool is_highspeed, bool is_dma); +// check if highspeed phy should be used +bool dwc2_core_is_highspeed_phy(dwc2_regs_t* dwc2, bool prefer_hs_phy); +bool dwc2_core_init(uint8_t rhport, bool is_hs_phy, bool is_dma); void dwc2_core_deinit(uint8_t rhport); void dwc2_core_handle_common_irq(uint8_t rhport, bool in_isr); diff --git a/src/portable/synopsys/dwc2/dwc2_info.md b/src/portable/synopsys/dwc2/dwc2_info.md index f655e4dba..f83007b8c 100644 --- a/src/portable/synopsys/dwc2/dwc2_info.md +++ b/src/portable/synopsys/dwc2/dwc2_info.md @@ -1,58 +1,58 @@ -| | AT32 F405 FS | AT32 F405 HS | AT32 F415 | BCM2711 (Pi4) | EFM32GG | ESP32-S2/S3 | ESP32-P4 | nRF54 | 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 | 0x00002000 | 0x00000000 | 0x00001000 | 0x2708A000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00001200 | 0x00001100 | 0x00002000 | 0x00003000 | 0x00003100 | 0x00002100 | 0x00002300 | 0x00002000 | 0x00005000 | 0x00AEC000 | 0x00001000 | -| GSNPSID | 0x4F54400A | 0x4F54400A | 0x4F54400A | 0x4F54280A | 0x4F54330A | 0x4F54400A | 0x4F54400A | 0x4F54430A | 0x4F54281A | 0x4F54281A | 0x4F54320A | 0x4F54330A | 0x4F54330A | 0x4F54320A | 0x4F54330A | 0x4F54310A | 0x4F54411A | 0x4F54292A | 0x00000000 | -| - specs version | 4.00a | 4.00a | 4.00a | 2.80a | 3.30a | 4.00a | 4.00a | 4.30a | 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 | 0xAA555000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00000000 | -| GHWCFG2 | 0x228FDD00 | 0x229FDDD0 | 0x228DCD00 | 0x228DDD50 | 0x228F5910 | 0x224DD930 | 0x215FFFD0 | 0x228BFC72 | 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 | noHNP noSRP | HNP SRP | HNP SRP | HNP SRP | HNP SRP | HNP SRP | HNP SRP | HNP SRP | HNP SRP | noHNP noSRP | HNP SRP | HNP SRP | -| - arch | Slave only | DMA internal | Slave only | DMA internal | 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 | hub | hub | hub | n/a | hub | n/a | n/a | hub | n/a | n/a | hub | hub | hub | n/a | hub | n/a | hub | -| - hs_phy_type | n/a | UTMI+/ULPI | n/a | UTMI+ | n/a | n/a | UTMI+/ULPI | UTMI+ | n/a | ULPI | n/a | n/a | UTMI+/ULPI | ULPI | ULPI | n/a | UTMI+ | n/a | n/a | -| - fs_phy_type | Dedicated | Dedicated | Dedicated | Dedicated | Dedicated | Dedicated | Shared ULPI | n/a | Dedicated | Dedicated | Dedicated | Dedicated | Dedicated | Dedicated | Dedicated | Dedicated | n/a | Dedicated | n/a | -| - num_dev_ep | 7 | 7 | 3 | 7 | 6 | 6 | 15 | 15 | 3 | 5 | 5 | 5 | 8 | 8 | 8 | 5 | 8 | 6 | 0 | -| - num_host_ch | 15 | 15 | 7 | 7 | 13 | 7 | 15 | 15 | 7 | 11 | 11 | 11 | 15 | 15 | 15 | 11 | 15 | 13 | 0 | -| - period_channel_support | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 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 | 1 | 1 | 1 | 1 | 0 | -| - mul_proc_intrpt | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 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 | 0 | 0 | 0 | 0 | -| - nptx_q_depth | 8 | 8 | 8 | 8 | 8 | 4 | 4 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 2 | -| - ptx_q_depth | 8 | 8 | 8 | 8 | 8 | 8 | 4 | 8 | 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 | 8 | 8 | 8 | 8 | 0 | -| - otg_enable_ic_usb | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | -| GHWCFG3 | 0x020004E8 | 0x03F006E8 | 0x020004E8 | 0x0FF000E8 | 0x01F204E8 | 0x00C804B5 | 0x03805EB5 | 0x0BEAC0E8 | 0x020001E8 | 0x03F403E8 | 0x0200D1E8 | 0x0200D1E8 | 0x03EED2E8 | 0x03EED2E8 | 0x03B8D2E8 | 0x0200D1E8 | 0x03B882E8 | 0x027A01E5 | 0x00000000 | -| - xfer_size_width | 8 | 8 | 8 | 8 | 8 | 5 | 5 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 5 | 0 | -| - packet_size_width | 6 | 6 | 6 | 6 | 6 | 3 | 3 | 6 | 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 | 1 | 1 | 1 | 1 | 0 | -| - i2c_enable | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | -| - vendor_ctrl_itf | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 1 | 1 | 1 | 0 | 1 | 0 | 0 | -| - optional_feature_removed | 1 | 1 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | -| - synch_reset | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | -| - otg_adp_support | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 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 | 0 | 0 | 0 | 0 | -| - battery_charger_support | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | -| - lpm_mode | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | -| - dfifo_depth | 512 | 1008 | 512 | 4080 | 498 | 200 | 896 | 3050 | 512 | 1012 | 512 | 512 | 1006 | 1006 | 952 | 512 | 952 | 634 | 0 | -| GHWCFG4 | 0x1FF0A020 | 0x1FF0A020 | 0x0000000F | 0x1FF00020 | 0x1BF08030 | 0xD3F0A030 | 0xDFF1A030 | 0x1E10AA60 | 0x0FF08030 | 0x17F00030 | 0x17F08030 | 0x17F08030 | 0x23F00030 | 0x23F00030 | 0xE3F00030 | 0x17F08030 | 0xE2103E30 | 0xDBF08030 | 0x00000000 | -| - num_dev_period_in_ep | 0 | 0 | 15 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | -| - partial_powerdown | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | -| - ahb_freq_min | 1 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | -| - hibernation | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 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 | 0 | 0 | 0 | 0 | -| - reserved8 | 0 | 0 | 0 | 0 | 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 | 1 | 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 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | -| - ipg_isoc_support | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 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 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | -| - enhanced_lpm_support | 1 | 1 | 0 | 0 | 0 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | -| - phy_data_width | 8/16 bit | 8/16 bit | 8 bit | 8 bit | 8/16 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 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | -| - iddg_filter | 1 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | -| - vbus_valid_filter | 1 | 1 | 0 | 1 | 1 | 1 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 1 | 0 | -| - a_valid_filter | 1 | 1 | 0 | 1 | 1 | 1 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 1 | 0 | -| - b_valid_filter | 1 | 1 | 0 | 1 | 1 | 1 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 1 | 0 | -| - session_end_filter | 1 | 1 | 0 | 1 | 1 | 1 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 1 | 0 | -| - dedicated_fifos | 1 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | -| - num_dev_in_eps | 7 | 7 | 0 | 7 | 6 | 4 | 7 | 7 | 3 | 5 | 5 | 5 | 8 | 8 | 8 | 5 | 8 | 6 | 0 | -| - dma_desc_enable | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 0 | -| - dma_desc_dynamic | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 0 | +| | AT32 F405 FS | AT32 F405 HS | AT32 F415 | BCM2711 (Pi4) | EFM32GG | ESP32-S2/S3 | ESP32-P4 | nRF54 | ST F407/429 HS | ST F207/F407/411/429 FS | ST L476 FS | ST F412/76x FS | ST F76x HS | ST H743/H750 | ST F723/L4P5 FS | ST F723 HS | ST H7RS FS | ST U5A5/H7RS/N6 HS | XMC4500 | GD32VF103 | +|:---------------------------|:---------------|:---------------|:------------|:----------------|:-------------|:--------------|:-------------|:-------------|:-----------------|:--------------------------|:-------------|:-----------------|:-------------|:---------------|:------------------|:-------------|:-------------|:---------------------|:-------------|:------------| +| GUID | 0x00002000 | 0x00000000 | 0x00001000 | 0x2708A000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00001100 | 0x00001200 | 0x00002000 | 0x00002000 | 0x00002100 | 0x00002300 | 0x00003000 | 0x00003100 | 0x00004000 | 0x00005000 | 0x00AEC000 | 0x00001000 | +| GSNPSID | 0x4F54400A | 0x4F54400A | 0x4F54400A | 0x4F54280A | 0x4F54330A | 0x4F54400A | 0x4F54400A | 0x4F54430A | 0x4F54281A | 0x4F54281A | 0x4F54310A | 0x4F54320A | 0x4F54320A | 0x4F54330A | 0x4F54330A | 0x4F54330A | 0x4F54411A | 0x4F54411A | 0x4F54292A | 0x00000000 | +| - specs version | 4.00a | 4.00a | 4.00a | 2.80a | 3.30a | 4.00a | 4.00a | 4.30a | 2.81a | 2.81a | 3.10a | 3.20a | 3.20a | 3.30a | 3.30a | 3.30a | 4.11a | 4.11a | 2.92a | 0.00W | +| GHWCFG1 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00000000 | 0xAA555000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00000000 | 0x00000000 | +| GHWCFG2 | 0x228FDD00 | 0x229FDDD0 | 0x228DCD00 | 0x228DDD50 | 0x228F5910 | 0x224DD930 | 0x215FFFD0 | 0x228BFC72 | 0x229ED590 | 0x229DCD20 | 0x229ED520 | 0x229ED520 | 0x229FE190 | 0x229FE190 | 0x229ED520 | 0x229FE1D0 | 0x229ED522 | 0x228FE052 | 0x228F5930 | 0x00000000 | +| - op_mode | HNP SRP | HNP SRP | HNP SRP | HNP SRP | HNP SRP | HNP SRP | HNP SRP | noHNP noSRP | HNP SRP | HNP SRP | HNP SRP | HNP SRP | HNP SRP | HNP SRP | HNP SRP | HNP SRP | noHNP noSRP | noHNP noSRP | HNP SRP | HNP SRP | +| - arch | Slave only | DMA internal | Slave only | DMA internal | DMA internal | DMA internal | DMA internal | DMA internal | DMA internal | Slave only | Slave only | Slave only | DMA internal | DMA internal | Slave only | DMA internal | Slave only | DMA internal | DMA internal | Slave only | +| - single_point | hub | hub | hub | hub | hub | n/a | hub | n/a | hub | n/a | n/a | n/a | hub | hub | n/a | hub | n/a | hub | n/a | hub | +| - hs_phy_type | n/a | UTMI+/ULPI | n/a | UTMI+ | n/a | n/a | UTMI+/ULPI | UTMI+ | ULPI | n/a | n/a | n/a | ULPI | ULPI | n/a | UTMI+/ULPI | n/a | UTMI+ | n/a | n/a | +| - fs_phy_type | Dedicated | Dedicated | Dedicated | Dedicated | Dedicated | Dedicated | Shared ULPI | n/a | Dedicated | Dedicated | Dedicated | Dedicated | Dedicated | Dedicated | Dedicated | Dedicated | Dedicated | n/a | Dedicated | n/a | +| - num_dev_ep | 7 | 7 | 3 | 7 | 6 | 6 | 15 | 15 | 5 | 3 | 5 | 5 | 8 | 8 | 5 | 8 | 5 | 8 | 6 | 0 | +| - num_host_ch | 15 | 15 | 7 | 7 | 13 | 7 | 15 | 15 | 11 | 7 | 11 | 11 | 15 | 15 | 11 | 15 | 11 | 15 | 13 | 0 | +| - period_channel_support | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 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 | 1 | 1 | 1 | 1 | 1 | 0 | +| - mul_proc_intrpt | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 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 | 0 | 0 | 0 | 0 | 0 | +| - nptx_q_depth | 8 | 8 | 8 | 8 | 8 | 4 | 4 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 2 | +| - ptx_q_depth | 8 | 8 | 8 | 8 | 8 | 8 | 4 | 8 | 8 | 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 | 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 | 0 | 0 | 0 | 0 | 0 | +| GHWCFG3 | 0x020004E8 | 0x03F006E8 | 0x020004E8 | 0x0FF000E8 | 0x01F204E8 | 0x00C804B5 | 0x03805EB5 | 0x0BEAC0E8 | 0x03F403E8 | 0x020001E8 | 0x0200D1E8 | 0x0200D1E8 | 0x03EED2E8 | 0x03B8D2E8 | 0x0200D1E8 | 0x03EED2E8 | 0x020081E8 | 0x03B882E8 | 0x027A01E5 | 0x00000000 | +| - xfer_size_width | 8 | 8 | 8 | 8 | 8 | 5 | 5 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 5 | 0 | +| - packet_size_width | 6 | 6 | 6 | 6 | 6 | 3 | 3 | 6 | 6 | 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 | 1 | 1 | 1 | 1 | 1 | 0 | +| - i2c_enable | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | +| - vendor_ctrl_itf | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | +| - optional_feature_removed | 1 | 1 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| - synch_reset | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| - otg_adp_support | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | +| - otg_enable_hsic | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| - battery_charger_support | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | +| - lpm_mode | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | +| - dfifo_depth | 512 | 1008 | 512 | 4080 | 498 | 200 | 896 | 3050 | 1012 | 512 | 512 | 512 | 1006 | 952 | 512 | 1006 | 512 | 952 | 634 | 0 | +| GHWCFG4 | 0x1FF0A020 | 0x1FF0A020 | 0x0000000F | 0x1FF00020 | 0x1BF08030 | 0xD3F0A030 | 0xDFF1A030 | 0x1E10AA60 | 0x17F00030 | 0x0FF08030 | 0x17F08030 | 0x17F08030 | 0x23F00030 | 0xE3F00030 | 0x17F08030 | 0x23F00030 | 0x1610B230 | 0xE2103E30 | 0xDBF08030 | 0x00000000 | +| - num_dev_period_in_ep | 0 | 0 | 15 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| - partial_powerdown | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | +| - ahb_freq_min | 1 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | +| - hibernation | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 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 | 0 | 0 | 0 | 0 | 0 | +| - reserved8 | 0 | 0 | 0 | 0 | 0 | 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 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | +| - service_interval_flow | 0 | 0 | 0 | 0 | 0 | 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 | 1 | 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 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | +| - enhanced_lpm_support | 1 | 1 | 0 | 0 | 0 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | +| - phy_data_width | 8/16 bit | 8/16 bit | 8 bit | 8 bit | 8/16 bit | 8/16 bit | 8/16 bit | 8/16 bit | 8 bit | 8/16 bit | 8/16 bit | 8/16 bit | 8 bit | 8 bit | 8/16 bit | 8 bit | 8/16 bit | 8 bit | 8/16 bit | 8 bit | +| - ctrl_ep_num | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| - iddg_filter | 1 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | +| - vbus_valid_filter | 1 | 1 | 0 | 1 | 1 | 1 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 1 | 0 | +| - a_valid_filter | 1 | 1 | 0 | 1 | 1 | 1 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 1 | 0 | +| - b_valid_filter | 1 | 1 | 0 | 1 | 1 | 1 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 1 | 0 | +| - session_end_filter | 1 | 1 | 0 | 1 | 1 | 1 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 1 | 0 | +| - dedicated_fifos | 1 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | +| - num_dev_in_eps | 7 | 7 | 0 | 7 | 6 | 4 | 7 | 7 | 5 | 3 | 5 | 5 | 8 | 8 | 5 | 8 | 5 | 8 | 6 | 0 | +| - dma_desc_enable | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 1 | 0 | +| - dma_desc_dynamic | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 1 | 0 | diff --git a/src/portable/synopsys/dwc2/dwc2_info.py b/src/portable/synopsys/dwc2/dwc2_info.py index 8fbbc00a0..e6601f482 100755 --- a/src/portable/synopsys/dwc2/dwc2_info.py +++ b/src/portable/synopsys/dwc2/dwc2_info.py @@ -16,14 +16,16 @@ dwc2_reg_value = { 'ESP32-S2/S3': [0, 0x4F54400A, 0, 0x224DD930, 0x0C804B5, 0xD3F0A030], 'ESP32-P4': [0, 0x4F54400A, 0, 0x215FFFD0, 0x03805EB5, 0xDFF1A030], 'nRF54': [0, 0x4F54430A, 0xAA555000, 0x228BFC72, 0x0BEAC0E8, 0x1E10AA60], - 'ST F207/F407/411/429 FS': [0x1200, 0x4F54281A, 0, 0x229DCD20, 0x020001E8, 0x0FF08030], + # ST sort by GUID 'ST F407/429 HS': [0x1100, 0x4F54281A, 0, 0x229ED590, 0x03F403E8, 0x17F00030], + 'ST F207/F407/411/429 FS': [0x1200, 0x4F54281A, 0, 0x229DCD20, 0x020001E8, 0x0FF08030], + 'ST L476 FS': [0x2000, 0x4F54310A, 0, 0x229ED520, 0x0200D1E8, 0x17F08030], 'ST F412/76x FS': [0x2000, 0x4F54320A, 0, 0x229ED520, 0x0200D1E8, 0x17F08030], - 'ST F723/L4P5 FS': [0x3000, 0x4F54330A, 0, 0x229ED520, 0x0200D1E8, 0x17F08030], - 'ST F723 HS': [0x3100, 0x4F54330A, 0, 0x229FE1D0, 0x03EED2E8, 0x23F00030], '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 F723/L4P5 FS': [0x3000, 0x4F54330A, 0, 0x229ED520, 0x0200D1E8, 0x17F08030], + 'ST F723 HS': [0x3100, 0x4F54330A, 0, 0x229FE1D0, 0x03EED2E8, 0x23F00030], + 'ST H7RS FS': [0x4000, 0x4F54411A, 0, 0x229ED522, 0x20081E8, 0x1610B230], '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 516eb021b..753917a20 100644 --- a/src/portable/synopsys/dwc2/dwc2_stm32.h +++ b/src/portable/synopsys/dwc2/dwc2_stm32.h @@ -85,8 +85,11 @@ extern "C" { #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 + #define USB_OTG_FS_PERIPH_BASE USB1_OTG_HS_BASE + #define OTG_FS_IRQn USB1_OTG_HS_IRQn + + #define USB_OTG_HS_PERIPH_BASE USB2_OTG_HS_BASE + #define OTG_HS_IRQn USB2_OTG_HS_IRQn #elif CFG_TUSB_MCU == OPT_MCU_STM32F7 #include "stm32f7xx.h" @@ -300,6 +303,66 @@ static inline void dwc2_phy_update(dwc2_regs_t* dwc2, uint8_t hs_phy_type) { } } +//------------- GCCFG configuration -------------// +static inline void dwc2_stm32_gccfg_cfg(dwc2_regs_t* dwc2, bool vbus_sensing, bool is_host) { + if (is_host) { + vbus_sensing = false; + } + + uint32_t gccfg = dwc2->stm32_gccfg; + if (dwc2->guid < 0x2000) { + // use VBUSASEN/VBUSBSEN/NOVBUSSENS bits + if (is_host) { + gccfg &= ~(STM32_GCCFG_NOVBUSSENS | STM32_GCCFG_VBUSBSEN | STM32_GCCFG_VBUSASEN); + } else { + if (vbus_sensing) { + gccfg &= ~STM32_GCCFG_NOVBUSSENS; + gccfg |= STM32_GCCFG_VBUSBSEN; + } else { + gccfg |= STM32_GCCFG_NOVBUSSENS; + gccfg &= ~(STM32_GCCFG_VBUSBSEN | STM32_GCCFG_VBUSASEN); + } + } + } else if (dwc2->guid < 0x5000) { + // the later version uses VBDEN with battery charging detection + if (vbus_sensing) { + gccfg |= STM32_GCCFG_VBDEN; + } else { + gccfg &= ~STM32_GCCFG_VBDEN; + } + } else { + // from 0x5000 ST seems to use femtoPHY for UTMI+ HS PHY. Which use VBVALEXTOEN and VBVALOVAL for software override + // external VBUS sensing + // Note: N6 does not support hardware VBUS sensing, so the software override is always active. Therefore, VBDEN and + // VBVALEXTOEN are not available +#if CFG_TUSB_MCU == OPT_MCU_STM32N6 + if (is_host) { + gccfg |= STM32_GCCFG_PULLDOWNEN; + gccfg &= ~(STM32_GCCFG_VBVALOVAL); + } else { + gccfg &= ~STM32_GCCFG_PULLDOWNEN; + gccfg |= STM32_GCCFG_VBVALOVAL; + } +#else + if (is_host) { + gccfg |= STM32_GCCFG_PULLDOWNEN; + gccfg &= ~(STM32_GCCFG_VBDEN | STM32_GCCFG_VBVALEXTOEN | STM32_GCCFG_VBVALOVAL); + } else { + gccfg &= ~STM32_GCCFG_PULLDOWNEN; + if (vbus_sensing) { + gccfg |= STM32_GCCFG_VBDEN; + gccfg &= ~(STM32_GCCFG_VBVALEXTOEN | STM32_GCCFG_VBVALOVAL); + } else { + gccfg &= ~STM32_GCCFG_VBDEN; + gccfg |= STM32_GCCFG_VBVALEXTOEN | STM32_GCCFG_VBVALOVAL; + } + } +#endif + } + + dwc2->stm32_gccfg = gccfg; +} + //------------- DCache -------------// #if CFG_TUD_MEM_DCACHE_ENABLE || CFG_TUH_MEM_DCACHE_ENABLE @@ -321,8 +384,13 @@ static mem_region_t uncached_regions[] = { // DTCM (although USB DMA can't transfer to/from DTCM) {.start = 0x20000000, .end = 0x2002FFFF}, #elif CFG_TUSB_MCU == OPT_MCU_STM32F7 - // DTCM + // DTCM {.start = 0x20000000, .end = 0x2000FFFF}, +#elif CFG_TUSB_MCU == OPT_MCU_STM32N6 + // DTCM NS + {.start = 0x20000000, .end = 0x2003FFFF}, + // DTCM S + {.start = 0x30000000, .end = 0x3003FFFF}, #else #error "Cache maintenance is not supported yet" #endif diff --git a/src/portable/synopsys/dwc2/dwc2_type.h b/src/portable/synopsys/dwc2/dwc2_type.h index 7693ce02a..596bd0b34 100644 --- a/src/portable/synopsys/dwc2/dwc2_type.h +++ b/src/portable/synopsys/dwc2/dwc2_type.h @@ -1650,24 +1650,38 @@ TU_VERIFY_STATIC(offsetof(dwc2_regs_t, fifo ) == 0x1000, "incorrect size"); #define STM32_GCCFG_PHYHSEN_Msk (0x1UL << STM32_GCCFG_PHYHSEN_Pos) // 0x00800000 #define STM32_GCCFG_PHYHSEN STM32_GCCFG_PHYHSEN_Msk // HS PHY enable -// TODO stm32u5a5 SDEN is 22nd bit, conflict with 20th bit above -//#define STM32_GCCFG_SDEN_Pos (22U) -//#define STM32_GCCFG_SDEN_Msk (0x1U << STM32_GCCFG_SDEN_Pos) // 0x00400000 -//#define STM32_GCCFG_SDEN STM32_GCCFG_SDEN_Msk // Secondary detection (PD) mode enable +// GUID < 0x2000: VBUSASEN, VBUSBSEN, NOVBUSSENS bits +#define STM32_GCCFG_VBUSASEN_Pos (18U) +#define STM32_GCCFG_VBUSASEN_Msk (0x1UL << STM32_GCCFG_VBUSASEN_Pos) // 0x00040000 +#define STM32_GCCFG_VBUSASEN STM32_GCCFG_VBUSASEN_Msk // Enable A-device (host) VBUS sensing -// TODO stm32u5a5 VBVALOVA is 23rd bit, conflict with PHYHSEN bit above -#define STM32_GCCFG_VBVALOVAL_Pos (23U) -#define STM32_GCCFG_VBVALOVAL_Msk (0x1U << STM32_GCCFG_VBVALOVAL_Pos) // 0x00800000 -#define STM32_GCCFG_VBVALOVAL STM32_GCCFG_VBVALOVAL_Msk // Value of VBUSVLDEXT0 femtoPHY input +#define STM32_GCCFG_VBUSBSEN_Pos (19U) +#define STM32_GCCFG_VBUSBSEN_Msk (0x1UL << STM32_GCCFG_VBUSBSEN_Pos) // 0x00080000 +#define STM32_GCCFG_VBUSBSEN STM32_GCCFG_VBUSBSEN_Msk // Enable B-device (peripheral) VBUS sensing -#define STM32_GCCFG_VBVALEXTOEN_Pos (24U) -#define STM32_GCCFG_VBVALEXTOEN_Msk (0x1U << STM32_GCCFG_VBVALEXTOEN_Pos) // 0x01000000 -#define STM32_GCCFG_VBVALEXTOEN STM32_GCCFG_VBVALEXTOEN_Msk // Enables of VBUSVLDEXT0 femtoPHY input override +#define STM32_GCCFG_NOVBUSSENS_Pos (21U) +#define STM32_GCCFG_NOVBUSSENS_Msk (0x1UL << STM32_GCCFG_NOVBUSSENS_Pos) // 0x00200000 +#define STM32_GCCFG_NOVBUSSENS STM32_GCCFG_NOVBUSSENS_Msk // VBUS sensing disable option +// GUID < 0x2000: end -#define STM32_GCCFG_PULLDOWNEN_Pos (25U) -#define STM32_GCCFG_PULLDOWNEN_Msk (0x1U << STM32_GCCFG_PULLDOWNEN_Pos) // 0x02000000 -#define STM32_GCCFG_PULLDOWNEN STM32_GCCFG_PULLDOWNEN_Msk // Enables of femtoPHY pulldown resistors, used when ID PAD is disabled +// TODO: stm32u5a5 SDEN is 22nd bit, conflict with 20th bit above +// #define STM32_GCCFG_SDEN_Pos (22U) +// #define STM32_GCCFG_SDEN_Msk (0x1U << STM32_GCCFG_SDEN_Pos) // 0x00400000 +// #define STM32_GCCFG_SDEN STM32_GCCFG_SDEN_Msk // Secondary detection (PD) mode enable +// GUID >= 0x5000 use femtoPHY: VBVALOVA, VBVALEXTOEN, PULLDOWNEN +#define STM32_GCCFG_VBVALOVAL_Pos (23U) +#define STM32_GCCFG_VBVALOVAL_Msk (0x1U << STM32_GCCFG_VBVALOVAL_Pos) // 0x00800000 +#define STM32_GCCFG_VBVALOVAL STM32_GCCFG_VBVALOVAL_Msk // Value of VBUSVLDEXT0 femtoPHY input + +#define STM32_GCCFG_VBVALEXTOEN_Pos (24U) +#define STM32_GCCFG_VBVALEXTOEN_Msk (0x1U << STM32_GCCFG_VBVALEXTOEN_Pos) // 0x01000000 +#define STM32_GCCFG_VBVALEXTOEN STM32_GCCFG_VBVALEXTOEN_Msk // Enables of VBUSVLDEXT0 femtoPHY input override + +#define STM32_GCCFG_PULLDOWNEN_Pos (25U) +#define STM32_GCCFG_PULLDOWNEN_Msk (0x1U << STM32_GCCFG_PULLDOWNEN_Pos) // 0x02000000 +#define STM32_GCCFG_PULLDOWNEN STM32_GCCFG_PULLDOWNEN_Msk // Enables of femtoPHY pulldown resistors, used when ID PAD is disabled +// GUID >= 0x5000: end /******************** Bit definition for DEACHINTMSK register ********************/ #define DEACHINTMSK_IEP1INTM_Pos (1U) diff --git a/src/portable/synopsys/dwc2/hcd_dwc2.c b/src/portable/synopsys/dwc2/hcd_dwc2.c index fb075582f..1bdab6a45 100644 --- a/src/portable/synopsys/dwc2/hcd_dwc2.c +++ b/src/portable/synopsys/dwc2/hcd_dwc2.c @@ -111,7 +111,8 @@ typedef struct { hcd_endpoint_t edpt[CFG_TUH_DWC2_ENDPOINT_MAX]; } hcd_data_t; -hcd_data_t _hcd_data; +static hcd_data_t _hcd_data; +static tuh_configure_dwc2_t _tuh_cfg = {.use_hs_phy = TUH_OPT_HIGH_SPEED}; //-------------------------------------------------------------------- // @@ -350,7 +351,7 @@ TU_ATTR_ALWAYS_INLINE static inline uint8_t cal_next_pid(uint8_t pid, uint8_t pa * TX periodic (PTX) * - At least largest-EPsize*MulCount/4 (MulCount up to 3 for high-bandwidth ISO/interrupt) */ -static void dfifo_host_init(uint8_t rhport) { +static void dfifo_host_init(uint8_t rhport, bool is_hs_phy) { const dwc2_controller_t* dwc2_controller = &_dwc2_controller[rhport]; dwc2_regs_t* dwc2 = DWC2_REG(rhport); const dwc2_ghwcfg2_t ghwcfg2 = {.value = dwc2->ghwcfg2}; @@ -363,10 +364,9 @@ static void dfifo_host_init(uint8_t rhport) { } // fixed allocation for now, improve later: - // - ptx_largest is limited to 256 for FS since most FS core only has 1024 bytes total - bool is_highspeed = dwc2_core_is_highspeed(dwc2, TUSB_ROLE_HOST); - uint32_t nptx_largest = is_highspeed ? TUSB_EPSIZE_BULK_HS/4 : TUSB_EPSIZE_BULK_FS/4; - uint32_t ptx_largest = is_highspeed ? TUSB_EPSIZE_ISO_HS_MAX/4 : 256/4; + // - ptx_largest is limited to 256 for FS since most FS core only has 1024 bytes total + uint32_t nptx_largest = is_hs_phy ? TUSB_EPSIZE_BULK_HS / 4 : TUSB_EPSIZE_BULK_FS / 4; + uint32_t ptx_largest = is_hs_phy ? TUSB_EPSIZE_ISO_HS_MAX / 4 : 256 / 4; uint16_t nptxfsiz = 2 * nptx_largest; uint16_t rxfsiz = 2 * (ptx_largest + 2) + ghwcfg2.num_host_ch; @@ -392,29 +392,23 @@ static void dfifo_host_init(uint8_t rhport) { // 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; - + TU_VERIFY(cfg_id == TUH_CFGID_DWC2 && cfg_param != NULL); + tuh_configure_param_t const* cfg = (tuh_configure_param_t const*) cfg_param; + _tuh_cfg = cfg->dwc2; return true; } // Initialize controller to host mode bool hcd_init(uint8_t rhport, const tusb_rhport_init_t* rh_init) { - (void) rh_init; dwc2_regs_t* dwc2 = DWC2_REG(rhport); - tu_memclr(&_hcd_data, sizeof(_hcd_data)); // Core Initialization - const bool is_highspeed = dwc2_core_is_highspeed(dwc2, TUSB_ROLE_HOST); + const bool is_hs_phy = dwc2_core_is_highspeed_phy(dwc2, _tuh_cfg.use_hs_phy); const bool is_dma = dma_host_enabled(dwc2); - TU_ASSERT(dwc2_core_init(rhport, is_highspeed, is_dma)); + TU_ASSERT(dwc2_core_init(rhport, is_hs_phy, is_dma)); //------------- 3.1 Host Initialization -------------// - - // work at max supported speed - dwc2->hcfg &= ~HCFG_FSLS_ONLY; - // Enable HFIR reload if (dwc2->gsnpsid >= DWC2_CORE_REV_2_92a) { dwc2->hfir |= HFIR_RELOAD_CTRL; @@ -422,14 +416,25 @@ 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 + #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 + #endif + while ((dwc2->gintsts & GINTSTS_CMOD) != GINTSTS_CMODE_HOST) {} - // configure fixed-allocated fifo scheme - dfifo_host_init(rhport); + #ifdef TUP_USBIP_DWC2_STM32 + dwc2_stm32_gccfg_cfg(dwc2, false, true); + #endif + + if (is_hs_phy && (rh_init->speed == TUSB_SPEED_HIGH || rh_init->speed == TUSB_SPEED_AUTO)) { + dwc2->hcfg &= ~HCFG_FSLS_ONLY; // max speed + } else { + dwc2->hcfg |= HCFG_FSLS_ONLY; // disable high speed mode + } + + // configure a fixed-allocated fifo scheme + dfifo_host_init(rhport, is_hs_phy); dwc2->hprt = HPRT_W1_MASK; // clear all write-1-clear bits dwc2->hprt = HPRT_POWER; // turn on VBUS diff --git a/src/tusb.c b/src/tusb.c index 803803ca2..a857e5adf 100644 --- a/src/tusb.c +++ b/src/tusb.c @@ -315,11 +315,9 @@ bool tu_edpt_stream_init(tu_edpt_stream_t *s, bool is_host, bool is_tx, bool ove uint16_t ff_bufsize, uint8_t *ep_buf, uint16_t ep_bufsize) { (void) is_tx; - #if CFG_TUSB_EDPT_STREAM_NO_FIFO_ENABLED == 0 // FIFO is required if (ff_buf == NULL || ff_bufsize == 0) { return false; } - #endif s->is_host = is_host; tu_fifo_config(&s->ff, ff_buf, ff_bufsize, overwritable); @@ -400,7 +398,7 @@ uint32_t tu_edpt_stream_write_xfer(tu_edpt_stream_t *s) { // Pull data from FIFO -> EP buf uint16_t count; if (s->ep_buf == NULL) { - count = ff_count; + count = tu_fifo_count(&s->ff); // re-get count since fifo can be changed } else { count = tu_fifo_read_n(&s->ff, s->ep_buf, s->ep_bufsize); } @@ -417,90 +415,45 @@ uint32_t tu_edpt_stream_write_xfer(tu_edpt_stream_t *s) { } uint32_t tu_edpt_stream_write(tu_edpt_stream_t *s, const void *buffer, uint32_t bufsize) { - #if CFG_TUSB_EDPT_STREAM_NO_FIFO_ENABLED - if (0 == tu_fifo_depth(&s->ff)) { - // non-fifo mode: TX need ep buffer - TU_VERIFY(s->ep_buf != NULL, 0); - TU_VERIFY(stream_claim(s), 0); - uint32_t xact_len = tu_min32(bufsize, s->ep_bufsize); - memcpy(s->ep_buf, buffer, xact_len); - TU_ASSERT(stream_xfer(s, (uint16_t) xact_len), 0); - return xact_len; - } else - #endif - { - TU_VERIFY(bufsize > 0); - const uint16_t ret = tu_fifo_write_n(&s->ff, buffer, (uint16_t) bufsize); + TU_VERIFY(bufsize > 0); + const uint16_t ret = tu_fifo_write_n(&s->ff, buffer, (uint16_t) bufsize); - // flush if fifo has more than packet size or - // in rare case: fifo depth is configured too small (which never reach packet size) - if ((tu_fifo_count(&s->ff) >= s->mps) || (tu_fifo_depth(&s->ff) < s->mps)) { - tu_edpt_stream_write_xfer(s); - } - return ret; + // flush if fifo has more than packet size or + // in rare case: fifo depth is configured too small (which never reach packet size) + if ((tu_fifo_count(&s->ff) >= s->mps) || (tu_fifo_depth(&s->ff) < s->mps)) { + tu_edpt_stream_write_xfer(s); } + return ret; } uint32_t tu_edpt_stream_write_available(tu_edpt_stream_t *s) { - #if CFG_TUSB_EDPT_STREAM_NO_FIFO_ENABLED - if (0 == tu_fifo_depth(&s->ff)) { - // non-fifo mode - TU_VERIFY(s->ep_addr > 0); // must be opened - bool is_busy = true; - if (s->is_host) { - #if CFG_TUH_ENABLED - is_busy = usbh_edpt_busy(s->hwid, s->ep_addr); - #endif - } else { - #if CFG_TUD_ENABLED - is_busy = usbd_edpt_busy(s->hwid, s->ep_addr); - #endif - } - return is_busy ? 0 : s->ep_bufsize; - } else - #endif - { - return (uint32_t)tu_fifo_remaining(&s->ff); - } + return (uint32_t)tu_fifo_remaining(&s->ff); } //--------------------------------------------------------------------+ // Stream Read //--------------------------------------------------------------------+ uint32_t tu_edpt_stream_read_xfer(tu_edpt_stream_t *s) { - #if CFG_TUSB_EDPT_STREAM_NO_FIFO_ENABLED - if (0 == tu_fifo_depth(&s->ff)) { - // non-fifo mode: RX need ep buffer - TU_VERIFY(s->ep_buf != NULL, 0); - TU_VERIFY(stream_claim(s), 0); - TU_ASSERT(stream_xfer(s, s->ep_bufsize), 0); - return s->ep_bufsize; - } else - #endif - { - uint16_t available = tu_fifo_remaining(&s->ff); + uint16_t available = tu_fifo_remaining(&s->ff); - // Prepare for incoming data but only allow what we can store in the ring buffer. - // TODO Actually we can still carry out the transfer, keeping count of received bytes - // and slowly move it to the FIFO when read(). - // This pre-check reduces endpoint claiming - TU_VERIFY(available >= s->mps); - TU_VERIFY(stream_claim(s), 0); - available = tu_fifo_remaining(&s->ff); // re-get available since fifo can be changed + // Prepare for incoming data but only allow what we can store in the ring buffer. + // TODO Actually we can still carry out the transfer, keeping count of received bytes + // and slowly move it to the FIFO when read(). + // This pre-check reduces endpoint claiming + TU_VERIFY(available >= s->mps); + TU_VERIFY(stream_claim(s), 0); + available = tu_fifo_remaining(&s->ff); // re-get available since fifo can be changed - if (available >= s->mps) { - // multiple of packet size limit by ep bufsize - uint16_t count = (uint16_t) (available & ~(s->mps - 1)); - if (s->ep_buf != NULL) { - count = tu_min16(count, s->ep_bufsize); - } - TU_ASSERT(stream_xfer(s, count), 0); - return count; - } else { - // Release endpoint since we don't make any transfer - stream_release(s); - return 0; - } + if (available >= s->mps) { + // multiple of packet size limit by ep bufsize + uint16_t count = (uint16_t) (available & ~(s->mps - 1)); + count = tu_min16(count, s->ep_bufsize); + TU_ASSERT(stream_xfer(s, count), 0); + return count; + } else { + // Release endpoint since we don't make any transfer + stream_release(s); + return 0; } } diff --git a/src/tusb_option.h b/src/tusb_option.h index 08a0ba2ef..d87c2dc8b 100644 --- a/src/tusb_option.h +++ b/src/tusb_option.h @@ -216,6 +216,7 @@ #define OPT_MCU_AT32F402_405 2504 ///< ArteryTek AT32F402_405 #define OPT_MCU_AT32F425 2505 ///< ArteryTek AT32F425 #define OPT_MCU_AT32F413 2506 ///< ArteryTek AT32F413 +#define OPT_MCU_AT32F45X 2507 ///< ArteryTek AT32F45x // HPMicro #define OPT_MCU_HPM 2600 ///< HPMicro @@ -271,6 +272,25 @@ // USBIP //--------------------------------------------------------------------+ +//------------- ChipIdea -------------// +// 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 + +// CI_HS support FIFO transfer if endpoint buffer is 4k aligned and size is multiple of 4k, also DCACHE is disabled +#ifndef CFG_TUD_CI_HS_EPBUF_4K_ALIGNED + #define CFG_TUD_CI_HS_EPBUF_4K_ALIGNED 0 +#endif + +#if CFG_TUD_CI_HS_EPBUF_4K_ALIGNED && !CFG_TUD_MEM_DCACHE_ENABLE + #define CFG_TUD_EDPT_DEDICATED_HWFIFO 1 +#endif + //------------- DWC2 -------------// // DMA mode for device #ifndef CFG_TUD_DWC2_DMA_ENABLE @@ -316,57 +336,28 @@ #define CFG_TUSB_FIFO_HWFIFO_ADDR_STRIDE 0 // fixed hwfifo address #endif -//------------- ChipIdea -------------// -// 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 - -// CI_HS support FIFO transfer if endpoint buffer is 4k aligned and size is multiple of 4k, also DCACHE is disabled -#ifndef CFG_TUD_CI_HS_EPBUF_4K_ALIGNED - #define CFG_TUD_CI_HS_EPBUF_4K_ALIGNED 0 -#endif - -#if CFG_TUD_CI_HS_EPBUF_4K_ALIGNED && !CFG_TUD_MEM_DCACHE_ENABLE - #define CFG_TUD_EDPT_DEDICATED_HWFIFO 1 -#endif - -//------------- pio-usb -------------// -// Enable PIO-USB software host controller -#ifndef CFG_TUH_RPI_PIO_USB - #define CFG_TUH_RPI_PIO_USB 0 -#endif - -#ifndef CFG_TUD_RPI_PIO_USB - #define CFG_TUD_RPI_PIO_USB 0 -#endif - -//------------ MAX3421 -------------// -// Enable MAX3421 USB host controller -#ifndef CFG_TUH_MAX3421 - #define CFG_TUH_MAX3421 0 -#endif - //------------ FSDEV --------------// #if defined(TUP_USBIP_FSDEV) #define CFG_TUD_EDPT_DEDICATED_HWFIFO 1 - #if CFG_TUSB_FSDEV_PMA_SIZE == 512 - #define CFG_TUSB_FIFO_HWFIFO_DATA_STRIDE 2 // 16-bit data + #if CFG_TUSB_FSDEV_PMA_SIZE == 2048 || TU_CHECK_MCU(OPT_MCU_STM32U0) + #define CFG_TUSB_FIFO_HWFIFO_DATA_STRIDE 4 // 32-bit data #define CFG_TUSB_FIFO_HWFIFO_ADDR_STRIDE 4 // 32-bit address increase #elif CFG_TUSB_FSDEV_PMA_SIZE == 1024 #define CFG_TUSB_FIFO_HWFIFO_DATA_STRIDE 2 // 16-bit data #define CFG_TUSB_FIFO_HWFIFO_ADDR_STRIDE 2 // 16-bit address increase - #elif CFG_TUSB_FSDEV_PMA_SIZE == 2048 - #define CFG_TUSB_FIFO_HWFIFO_DATA_STRIDE 4 // 32-bit data + #elif CFG_TUSB_FSDEV_PMA_SIZE == 512 + #define CFG_TUSB_FIFO_HWFIFO_DATA_STRIDE 2 // 16-bit data #define CFG_TUSB_FIFO_HWFIFO_ADDR_STRIDE 4 // 32-bit address increase #endif #endif +//------------ MAX3421 -------------// +// Enable MAX3421 USB host controller +#ifndef CFG_TUH_MAX3421 + #define CFG_TUH_MAX3421 0 +#endif + //------------ MUSB --------------// #if defined(TUP_USBIP_MUSB) #define CFG_TUD_EDPT_DEDICATED_HWFIFO 1 @@ -374,13 +365,30 @@ #define CFG_TUSB_FIFO_HWFIFO_DATA_ODD_16BIT_ACCESS // allow odd 16bit access #define CFG_TUSB_FIFO_HWFIFO_DATA_ODD_8BIT_ACCESS // allow odd 8bit access #define CFG_TUSB_FIFO_HWFIFO_ADDR_STRIDE 0 // fixed hwfifo +#endif + +//------------- Raspberry Pi -------------// +// Enable PIO-USB software host controller +#ifndef CFG_TUH_RPI_PIO_USB + #define CFG_TUH_RPI_PIO_USB 0 +#endif +#ifndef CFG_TUD_RPI_PIO_USB + #define CFG_TUD_RPI_PIO_USB 0 +#endif + +#if (CFG_TUSB_MCU == OPT_MCU_RP2040) && !CFG_TUD_RPI_PIO_USB + #define CFG_TUD_EDPT_DEDICATED_HWFIFO 1 + #define CFG_TUSB_FIFO_HWFIFO_DATA_STRIDE 1 + #define CFG_TUSB_FIFO_HWFIFO_ADDR_STRIDE 1 + #define CFG_TUSB_FIFO_HWFIFO_CUSTOM_WRITE + #define CFG_TUSB_FIFO_HWFIFO_CUSTOM_READ #endif //------------ RUSB2 --------------// #if defined(TUP_USBIP_RUSB2) #define CFG_TUD_EDPT_DEDICATED_HWFIFO 1 - #define CFG_TUSB_FIFO_HWFIFO_DATA_STRIDE (2 | (TUD_OPT_HIGH_SPEED ? 4 : 0)) // 16 bit and 32 bit data if highspeed + #define CFG_TUSB_FIFO_HWFIFO_DATA_STRIDE (2 | (TUD_OPT_HIGH_SPEED ? 4 : 0)) // 16 bit and 32 bit if highspeed #define CFG_TUSB_FIFO_HWFIFO_ADDR_STRIDE 0 #define CFG_TUSB_FIFO_HWFIFO_CUSTOM_WRITE // custom write since rusb2 can change access width 32 -> 16 and can write // odd byte with byte access @@ -552,6 +560,11 @@ #define CFG_TUD_INTERFACE_MAX 16 #endif +// max events processed in one tud_task_ext() call, 0 for unlimited +#ifndef CFG_TUD_TASK_EVENTS_PER_RUN + #define CFG_TUD_TASK_EVENTS_PER_RUN 16 +#endif + // default to max hardware endpoint, but can be smaller to save RAM #ifndef CFG_TUD_ENDPPOINT_MAX #define CFG_TUD_ENDPPOINT_MAX TUP_DCD_ENDPOINT_MAX @@ -566,9 +579,18 @@ #define CFG_TUD_TEST_MODE 0 #endif +#ifndef CFG_TUD_VBUS_DETECT_HW_DEFAULT + #define CFG_TUD_VBUS_DETECT_HW_DEFAULT 0 +#endif + +// Enable VBUS Detect hardware, usually via functional GPIO +#ifndef CFG_TUD_VBUS_DETECT_HW + #define CFG_TUD_VBUS_DETECT_HW CFG_TUD_VBUS_DETECT_HW_DEFAULT +#endif + //------------- Device Class Driver -------------// #ifndef CFG_TUD_BTH - #define CFG_TUD_BTH 0 + #define CFG_TUD_BTH 0 #endif #if CFG_TUD_BTH && !defined(CFG_TUD_BTH_ISO_ALT_COUNT) @@ -671,6 +693,11 @@ #define CFG_TUH_MEM_DCACHE_LINE_SIZE CFG_TUSB_MEM_DCACHE_LINE_SIZE #endif +// max events processed in one tuh_task_ext() call, 0 for unlimited +#ifndef CFG_TUH_TASK_EVENTS_PER_RUN + #define CFG_TUH_TASK_EVENTS_PER_RUN 16 +#endif + //------------- CLASS -------------// #ifndef CFG_TUH_HUB @@ -742,7 +769,7 @@ #define CFG_TUH_CDC_PL2303 0 #endif -#ifndef CFG_TUH_CDC_PL2303_VID_PID_QUIRKS_LIST +#ifndef CFG_TUH_CDC_PL2303_VID_PID_LIST // List of product IDs that can use the PL2303 CDC driver #define CFG_TUH_CDC_PL2303_VID_PID_LIST \ { 0x067b, 0x2303 }, /* initial 2303 */ \ diff --git a/test/hil/hil_test.py b/test/hil/hil_test.py index b2e883119..b84740867 100755 --- a/test/hil/hil_test.py +++ b/test/hil/hil_test.py @@ -151,7 +151,7 @@ def read_disk_file(uid, lun, fname): def open_mtp_dev(uid): mtp = MTP() # MTP seems to take a while to enumerate - timeout = 2*ENUM_TIMEOUT + timeout = 2 * ENUM_TIMEOUT while timeout > 0: # run_cmd(f"gio mount -u mtp://TinyUsb_TinyUsb_Device_{uid}/") for raw in mtp.detect_devices(): @@ -410,22 +410,22 @@ def test_device_cdc_dual_ports(board): sizes = [32, 64, 128, 256, 512, random.randint(2000, 5000)] def write_and_check(writer, payload): - size = len(payload) + payload_len = len(payload) for s in ser: s.reset_input_buffer() rd0 = b'' rd1 = b'' offset = 0 # Write in chunks of random 1-64 bytes (device has 64-byte buffer) - while offset < size: - chunk_size = min(random.randint(1, 64), size - offset) + while offset < payload_len: + chunk_size = min(random.randint(1, 64), payload_len - offset) ser[writer].write(payload[offset:offset + chunk_size]) ser[writer].flush() rd0 += ser[0].read(chunk_size) rd1 += ser[1].read(chunk_size) offset += chunk_size - assert rd0 == payload.lower(), f'Port0 wrong data ({size}): expected {payload.lower()[:16]}... was {rd0[:16]}' - assert rd1 == payload.upper(), f'Port1 wrong data ({size}): expected {payload.upper()[:16]}... was {rd1[:16]}' + assert rd0 == payload.lower(), f'Port0 wrong data ({payload_len}): expected {payload.lower()}... was {rd0}' + assert rd1 == payload.upper(), f'Port1 wrong data ({payload_len}): expected {payload.upper()}... was {rd1}' for size in sizes: payload0 = rand_ascii(size) diff --git a/test/hil/tinyusb.json b/test/hil/tinyusb.json index 047d0879c..7cb561b2d 100644 --- a/test/hil/tinyusb.json +++ b/test/hil/tinyusb.json @@ -107,7 +107,6 @@ "host": false, "dual": false }, - "comment": "MSC is slow to enumerated #2602", "flasher": { "name": "jlink", "uid": "000831174392", diff --git a/tools/build.py b/tools/build.py index 87064b7a0..3c5c3c077 100755 --- a/tools/build.py +++ b/tools/build.py @@ -24,7 +24,6 @@ build_separator = '-' * 95 build_status = [STATUS_OK, STATUS_FAILED, STATUS_SKIPPED] verbose = False -clean_build = False parallel_jobs = os.cpu_count() # CI board control lists (used when running under CI) @@ -40,7 +39,9 @@ ci_skip_boards = { } ci_preferred_boards = { - 'stm32h7': ['stm32h743eval'], + 'samd2x_l2x': ['metro_m0_express'], + 'samd5x_e5x': ['metro_m4_express'], + 'stm32h7': ['stm32h743eval'] } @@ -96,15 +97,15 @@ def get_examples(family): return all_examples -def print_build_result(board, example, status, duration): +def print_build_result(board, build_target, status, duration): if isinstance(duration, (int, float)): duration = "{:.2f}s".format(duration) - print(build_format.format(board, example, build_status[status], duration)) + print(build_format.format(board, build_target, build_status[status], duration)) # ----------------------------- # CMake # ----------------------------- -def cmake_board(board, build_args, build_flags_on): +def cmake_board(board, build_args, build_flags_on, build_targets): ret = [0, 0, 0] start_time = time.monotonic() @@ -133,39 +134,36 @@ def cmake_board(board, build_args, build_flags_on): f'-DBOARD={board}', '-DCMAKE_BUILD_TYPE=MinSizeRel', '-DLINKERMAP_OPTION=-q -f tinyusb/src', *build_args, *build_flags]) if rcmd.returncode == 0: - if clean_build: - run_cmd(["cmake", "--build", build_dir, '--target', 'clean']) cmd = ["cmake", "--build", build_dir, '--parallel', str(parallel_jobs)] - rcmd = run_cmd(cmd) - if rcmd.returncode == 0: - ret[0] += 1 - run_cmd(["cmake", "--build", build_dir, '--target', 'tinyusb_metrics']) - # print(rcmd.stdout.decode("utf-8")) - else: - ret[1] += 1 + for target in build_targets: + rcmd = run_cmd(cmd + ['--target', target]) + if rcmd.returncode != 0: + break + ret[0 if rcmd.returncode == 0 else 1] += 1 - example = 'all' - print_build_result(board, example, 0 if ret[1] == 0 else 1, time.monotonic() - start_time) + print_build_result(board, ','.join(build_targets), 0 if ret[1] == 0 else 1, time.monotonic() - start_time) return ret # ----------------------------- # Make # ----------------------------- -def make_one_example(example, board, make_option): +def make_one_example(example, board, make_option, build_targets): # Check if board is skipped if build_utils.skip_example(example, board): print_build_result(board, example, 2, '-') r = 2 else: start_time = time.monotonic() - make_args = ["make", "-C", f"examples/{example}", f"BOARD={board}", '-j', str(parallel_jobs)] + make_cmd = ["make", "-C", f"examples/{example}", f"BOARD={board}", '-j', str(parallel_jobs)] if make_option: - make_args += shlex.split(make_option) - if clean_build: - run_cmd(make_args + ["clean"]) - build_result = run_cmd(make_args + ['all']) - r = 0 if build_result.returncode == 0 else 1 + make_cmd += shlex.split(make_option) + r = 0 + for target in build_targets: + build_result = run_cmd(make_cmd + [target]) + if build_result.returncode != 0: + r = 1 + break print_build_result(board, example, r, time.monotonic() - start_time) ret = [0, 0, 0] @@ -173,7 +171,7 @@ def make_one_example(example, board, make_option): return ret -def make_board(board, build_args): +def make_board(board, build_args, build_targets): print(build_separator) family = find_family(board); all_examples = get_examples(family) @@ -184,7 +182,7 @@ def make_board(board, build_args): final_status = 2 else: with Pool(processes=os.cpu_count()) as pool: - pool_args = list((map(lambda e, b=board, o=f"{build_args}": [e, b, o], all_examples))) + pool_args = list((map(lambda e, b=board, o=f"{build_args}", t=build_targets: [e, b, o, t], 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)))) @@ -196,16 +194,16 @@ def make_board(board, build_args): # ----------------------------- # Build Family # ----------------------------- -def build_boards_list(boards, build_defines, build_system, build_flags_on): +def build_boards_list(boards, build_defines, build_system, build_flags_on, build_targets): ret = [0, 0, 0] for b in boards: r = [0, 0, 0] if build_system == 'cmake': build_args = [f'-D{d}' for d in build_defines] - r = cmake_board(b, build_args, build_flags_on) + r = cmake_board(b, build_args, build_flags_on, build_targets) elif build_system == 'make': build_args = ' '.join(f'{d}' for d in build_defines) - r = make_board(b, build_args) + r = make_board(b, build_args, build_targets) ret[0] += r[0] ret[1] += r[1] ret[2] += r[2] @@ -255,13 +253,11 @@ def get_family_boards(family, one_random, one_first): # ----------------------------- def main(): global verbose - global clean_build global parallel_jobs parser = argparse.ArgumentParser() parser.add_argument('families', nargs='*', default=[], help='Families to build') parser.add_argument('-b', '--board', action='append', default=[], help='Boards to build') - parser.add_argument('-c', '--clean', action='store_true', default=False, help='Clean before build') parser.add_argument('-t', '--toolchain', default='gcc', help='Toolchain to use, default is gcc') parser.add_argument('-s', '--build-system', default='cmake', help='Build system to use, default is cmake') parser.add_argument('-D', '--define-symbol', action='append', default=[], help='Define to pass to build system') @@ -271,6 +267,8 @@ def main(): parser.add_argument('--one-first', action='store_true', default=False, help='Build only the first board (alphabetical) of each specified family') parser.add_argument('-j', '--jobs', type=int, default=os.cpu_count(), help='Number of jobs to run in parallel') + parser.add_argument('-T', '--target', action='append', default=[], + help='Build target to use, may be specified multiple times (default: all)') parser.add_argument('-v', '--verbose', action='store_true', help='Verbose output') args = parser.parse_args() @@ -282,8 +280,8 @@ def main(): build_flags_on = args.build_flags_on one_random = args.one_random one_first = args.one_first + build_targets = args.target if args.target else ['all'] verbose = args.verbose - clean_build = args.clean parallel_jobs = args.jobs build_defines.append(f'TOOLCHAIN={toolchain}') @@ -293,7 +291,7 @@ def main(): return 1 print(build_separator) - print(build_format.format('Board', 'Example', '\033[39mResult\033[0m', 'Time')) + print(build_format.format('Board', 'Target', '\033[39mResult\033[0m', 'Time')) total_time = time.monotonic() # get all families @@ -312,7 +310,7 @@ def main(): all_boards.extend(get_family_boards(f, one_random, one_first)) # build all boards - result = build_boards_list(all_boards, build_defines, build_system, build_flags_on) + result = build_boards_list(all_boards, build_defines, build_system, build_flags_on, build_targets) total_time = time.monotonic() - total_time print(build_separator) diff --git a/tools/codespell/ignore-words.txt b/tools/codespell/ignore-words.txt index 957cbd86b..5b6e2e98b 100644 --- a/tools/codespell/ignore-words.txt +++ b/tools/codespell/ignore-words.txt @@ -1,14 +1,15 @@ -synopsys -sie -tre -thre -hsi -fro -dout -mot -te attch +busses +dout endianess +fro +hsi +inout +mot pris -busses ser +sie +synopsys +te +thre +tre diff --git a/tools/get_deps.py b/tools/get_deps.py index deacbb23b..1d596469b 100755 --- a/tools/get_deps.py +++ b/tools/get_deps.py @@ -45,7 +45,7 @@ deps_optional = { 'xmc4000'], 'hw/mcu/microchip': ['https://github.com/hathach/microchip_driver.git', '9e8b37e307d8404033bb881623a113931e1edf27', - 'sam3x samd11 samd21 samd51 samd5x_e5x same5x same7x saml2x samg'], + 'sam3x samd11 samd21 samd51 samd5x_e5x same5x same7x samd2x_l2x samg'], 'hw/mcu/mindmotion/mm32sdk': ['https://github.com/hathach/mm32sdk.git', 'b93e856211060ae825216c6a1d6aa347ec758843', 'mm32'], @@ -209,7 +209,7 @@ deps_optional = { '9442fbb71f855ff2e64fbf662b7726beba511a24', 'stm32wba'], 'hw/mcu/ti': ['https://github.com/hathach/ti_driver.git', - '143ed6cc20a7615d042b03b21e070197d473e6e5', + '083944907e7d08fcb1f614b47598ce45935b8da1', 'msp430 msp432e4 tm4c'], 'hw/mcu/wch/ch32v103': ['https://github.com/openwch/ch32v103.git', '7578cae0b21f86dd053a1f781b2fc6ab99d0ec17', @@ -244,16 +244,19 @@ deps_optional = { 'hw/mcu/artery/at32f413': ['https://github.com/ArteryTek/AT32F413_Firmware_Library.git', 'f6fe62dfec9fd40c5b63d92fc5ef2c2b5e77a450', 'at32f413'], + 'hw/mcu/artery/at32f45x': ['https://github.com/ArteryTek/AT32F45x_Firmware_Library.git', + '3d4a1b38be8ebac292e2350ca53bc4bfa4430233', + 'at32f45x'], 'hw/mcu/hpmicro/hpm_sdk': ['https://github.com/hpmicro/hpm_sdk', '8d2af741ecc4aaa82d7ee395dc1ce25d7070c3ff', 'hpmicro'], 'lib/CMSIS_5': ['https://github.com/ARM-software/CMSIS_5.git', '2b7495b8535bdcb306dac29b9ded4cfb679d7e5c', - 'imxrt kinetis_k32l2 kinetis_kl lpc51 lpc54 lpc55 mcx rw61x mm32 msp432e4 nrf saml2x ' + 'imxrt kinetis_k kinetis_k32l2 kinetis_kl lpc51 lpc54 lpc55 mcx rw61x mm32 msp432e4 nrf samd2x_l2x ' 'lpc11 lpc13 lpc15 lpc17 lpc18 lpc40 lpc43 ' 'stm32c0 stm32f0 stm32f1 stm32f2 stm32f3 stm32f4 stm32f7 stm32g0 stm32g4 stm32h5 ' 'stm32h7 stm32h7rs stm32l0 stm32l1 stm32l4 stm32l5 stm32u0 stm32u5 stm32wb stm32wba ' - 'sam3x samd11 samd21 samd51 samd5x_e5x same5x same7x saml2x samg ' + 'sam3x samd11 samd21 samd51 samd5x_e5x same5x same7x samd2x_l2x samg ' 'tm4c '], 'lib/CMSIS_6': ['https://github.com/ARM-software/CMSIS_6.git', '6f0a58d01aa9bd2feba212097f9afe7acd991d52', @@ -327,18 +330,16 @@ def main(): parser.add_argument('-b', '--board', action='append', default=[], help='Boards to fetch') parser.add_argument('-D', '--define', action='append', default=[], help='Have no effect') parser.add_argument('-f1', '--build-flags-on', action='append', default=[], help='Have no effect') - parser.add_argument('--print', action='store_true', help='Print commit hash only') args = parser.parse_args() families = args.families boards = args.board - print_only = args.print status = 0 - deps = list(deps_mandatory.keys()) + deps = [] if 'all' in families: - deps += deps_optional.keys() + deps.extend(deps_optional.keys()) else: families = list(families) if boards is not None: @@ -346,24 +347,16 @@ def main(): f = find_family(b) if f is not None: families.append(f) - for f in families: for d in deps_optional: if d not in deps and f in deps_optional[d][2].split(): deps.append(d) + if len(deps) == 0: + print('WARN: no additional dependencies found for given boards or families') - if print_only: - pvalue = {} - # print only without arguments, always add CMSIS_5 - if len(families) == 0 and len(boards) == 0: - deps.append('lib/CMSIS_5') - for d in deps: - commit = deps_all[d][1] - pvalue[d] = commit - print(pvalue) - else: - with Pool() as pool: - status = sum(pool.map(get_a_dep, deps)) + deps.extend(deps_mandatory.keys()) + with Pool() as pool: + status = sum(pool.map(get_a_dep, deps)) return status |
